예제 #1
0
 void Generate(nsTArray<RefPtr<Image> > &aImages)
 {
   aImages.AppendElement(CreateI420Image());
   aImages.AppendElement(CreateNV12Image());
   aImages.AppendElement(CreateNV21Image());
 }
예제 #2
0
nsresult
GfxInfo::GetFeatureStatusImpl(int32_t aFeature, 
                              int32_t *aStatus, 
                              nsAString & aSuggestedDriverVersion,
                              const nsTArray<GfxDriverInfo>& aDriverInfo, 
                              OperatingSystem* aOS /* = nullptr */)
{
  NS_ENSURE_ARG_POINTER(aStatus);
  aSuggestedDriverVersion.SetIsVoid(true);
  *aStatus = nsIGfxInfo::FEATURE_STATUS_UNKNOWN;
  OperatingSystem os = mOS;
  if (aOS)
    *aOS = os;

  EnsureInitializedFromGfxInfoData();

  if (!mError.IsEmpty()) {
    *aStatus = nsIGfxInfo::FEATURE_BLOCKED_DEVICE;
    return NS_OK;
  }

  // Don't evaluate special cases when evaluating the downloaded blocklist.
  if (aDriverInfo.IsEmpty()) {
    if (aFeature == FEATURE_WEBGL_OPENGL) {
      if (mRenderer.Find("Adreno 200") != -1 ||
          mRenderer.Find("Adreno 205") != -1)
      {
        *aStatus = nsIGfxInfo::FEATURE_BLOCKED_DEVICE;
        return NS_OK;
      }

      if (mHardware.Equals(NS_LITERAL_STRING("ville"))) {
        *aStatus = nsIGfxInfo::FEATURE_BLOCKED_DEVICE;
        return NS_OK;
      }
    }

    if (aFeature == FEATURE_STAGEFRIGHT) {
      NS_LossyConvertUTF16toASCII cManufacturer(mManufacturer);
      NS_LossyConvertUTF16toASCII cModel(mModel);
      NS_LossyConvertUTF16toASCII cHardware(mHardware);

      if (cHardware.Equals("antares") ||
          cHardware.Equals("endeavoru") ||
          cHardware.Equals("harmony") ||
          cHardware.Equals("picasso") ||
          cHardware.Equals("picasso_e") ||
          cHardware.Equals("ventana") ||
          cHardware.Equals("rk30board"))
      {
        *aStatus = nsIGfxInfo::FEATURE_BLOCKED_DEVICE;
        return NS_OK;
      }

      if (CompareVersions(mOSVersion.get(), "2.2.0") >= 0 &&
          CompareVersions(mOSVersion.get(), "2.3.0") < 0)
      {
        // Froyo LG devices are whitelisted.
        // All other Froyo
        bool isWhitelisted =
          cManufacturer.Equals("lge", nsCaseInsensitiveCStringComparator());

        if (!isWhitelisted) {
          *aStatus = nsIGfxInfo::FEATURE_BLOCKED_DEVICE;
          return NS_OK;
        }
      }
      else if (CompareVersions(mOSVersion.get(), "2.3.0") >= 0 &&
          CompareVersions(mOSVersion.get(), "2.4.0") < 0)
      {
        // Gingerbread HTC devices are whitelisted.
        // Gingerbread Samsung devices are whitelisted except for:
        //   Samsung devices identified in Bug 847837
        //   Samsung SGH-T989 (Bug 818363)
        // All other Gingerbread devices are blacklisted.
        bool isWhitelisted =
          cManufacturer.Equals("htc", nsCaseInsensitiveCStringComparator()) ||
          cManufacturer.Equals("samsung", nsCaseInsensitiveCStringComparator());

        if (cModel.Equals("GT-I8160", nsCaseInsensitiveCStringComparator()) ||
            cModel.Equals("GT-I8160L", nsCaseInsensitiveCStringComparator()) ||
            cModel.Equals("GT-I8530", nsCaseInsensitiveCStringComparator()) ||
            cModel.Equals("GT-I9070", nsCaseInsensitiveCStringComparator()) ||
            cModel.Equals("GT-I9070P", nsCaseInsensitiveCStringComparator()) ||
            cModel.Equals("GT-I8160P", nsCaseInsensitiveCStringComparator()) ||
            cModel.Equals("GT-S7500", nsCaseInsensitiveCStringComparator()) ||
            cModel.Equals("GT-S7500T", nsCaseInsensitiveCStringComparator()) ||
            cModel.Equals("GT-S7500L", nsCaseInsensitiveCStringComparator()) ||
            cModel.Equals("GT-S6500T", nsCaseInsensitiveCStringComparator()) ||
            cModel.Equals("SGH-T989", nsCaseInsensitiveCStringComparator()) ||
            cHardware.Equals("smdkc110", nsCaseInsensitiveCStringComparator()) ||
            cHardware.Equals("smdkc210", nsCaseInsensitiveCStringComparator()) ||
            cHardware.Equals("herring", nsCaseInsensitiveCStringComparator()) ||
            cHardware.Equals("shw-m110s", nsCaseInsensitiveCStringComparator()) ||
            cHardware.Equals("shw-m180s", nsCaseInsensitiveCStringComparator()) ||
            cHardware.Equals("n1", nsCaseInsensitiveCStringComparator()) ||
            cHardware.Equals("latona", nsCaseInsensitiveCStringComparator()) ||
            cHardware.Equals("aalto", nsCaseInsensitiveCStringComparator()) ||
            cHardware.Equals("atlas", nsCaseInsensitiveCStringComparator()) ||
            cHardware.Equals("qcom", nsCaseInsensitiveCStringComparator()))
        {
          isWhitelisted = false;
        }

        if (!isWhitelisted) {
          *aStatus = nsIGfxInfo::FEATURE_BLOCKED_DEVICE;
          return NS_OK;
        }
      }
      else if (CompareVersions(mOSVersion.get(), "3.0.0") >= 0 &&
          CompareVersions(mOSVersion.get(), "4.0.0") < 0)
      {
        // Honeycomb Samsung devices are whitelisted.
        // All other Honeycomb devices are blacklisted.
	bool isWhitelisted =
          cManufacturer.Equals("samsung", nsCaseInsensitiveCStringComparator());

        if (!isWhitelisted) {
          *aStatus = nsIGfxInfo::FEATURE_BLOCKED_DEVICE;
          return NS_OK;
        }
      }
      else if (CompareVersions(mOSVersion.get(), "4.0.0") < 0)
      {
        *aStatus = nsIGfxInfo::FEATURE_BLOCKED_OS_VERSION;
        return NS_OK;
      }
      else if (CompareVersions(mOSVersion.get(), "4.1.0") < 0)
      {
        // Whitelist:
        //   All Samsung ICS devices, except for:
        //     Samsung SGH-I717 (Bug 845729)
        //     Samsung SGH-I727 (Bug 845729)
        //     Samsung SGH-I757 (Bug 845729)
        //     Samsung SGH-T989 (Bug 845729)
        //   All Galaxy nexus ICS devices
        //   Sony Xperia Ion (LT28) ICS devices
        bool isWhitelisted =
          cModel.Equals("LT28h", nsCaseInsensitiveCStringComparator()) ||
          cManufacturer.Equals("samsung", nsCaseInsensitiveCStringComparator()) ||
          cModel.Equals("galaxy nexus", nsCaseInsensitiveCStringComparator()); // some Galaxy Nexus have manufacturer=amazon

        if (cModel.Find("SGH-I717", true) != -1 ||
            cModel.Find("SGH-I727", true) != -1 ||
            cModel.Find("SGH-I757", true) != -1 ||
            cModel.Find("SGH-T989", true) != -1)
        {
          isWhitelisted = false;
        }

        if (!isWhitelisted) {
          *aStatus = nsIGfxInfo::FEATURE_BLOCKED_DEVICE;
          return NS_OK;
        }
      }
      else if (CompareVersions(mOSVersion.get(), "4.2.0") < 0)
      {
        // Whitelist:
        //   All JB phones except for those in blocklist below
        // Blocklist:
        //   Samsung devices from bug 812881 and 853522.
        //   All Sony devices (Bug 845734)

        bool isBlocklisted =
          cModel.Find("SCH-I535", true) ||
          cModel.Find("SGH-I747", true) ||
          cModel.Find("SGH-T999", true) ||
          cModel.Find("SPH-L710", true) ||
          cModel.Find("GT-I8190", true) ||
          cModel.Find("GT-P3100", true) ||
          cModel.Find("GT-P3110", true) ||
          cModel.Find("GT-P3113", true) ||
          cModel.Find("GT-P5100", true) ||
          cModel.Find("GT-P5110", true) ||
          cModel.Find("GT-P5113", true) ||
          cManufacturer.Equals("Sony", nsCaseInsensitiveCStringComparator());

        if (isBlocklisted) {
          *aStatus = nsIGfxInfo::FEATURE_BLOCKED_DEVICE;
          return NS_OK;
        }
      }
    }
  }

  return GfxInfoBase::GetFeatureStatusImpl(aFeature, aStatus, aSuggestedDriverVersion, aDriverInfo, &os);
}
예제 #3
0
already_AddRefed<Layer> CreateLayerTree(
    const char* aLayerTreeDescription,
    nsIntRegion* aVisibleRegions,
    const Matrix4x4* aTransforms,
    nsRefPtr<LayerManager>& manager,
    nsTArray<nsRefPtr<Layer> >& aLayersOut) {

  aLayersOut.Clear();

  if (!manager) {
    manager = new TestLayerManager();
  }

  nsRefPtr<Layer> rootLayer = nullptr;
  nsRefPtr<ContainerLayer> parentContainerLayer = nullptr;
  nsRefPtr<Layer> lastLayer = nullptr;
  int layerNumber = 0;
  for (size_t i = 0; i < strlen(aLayerTreeDescription); i++) {
    if (aLayerTreeDescription[i] == '(') {
      if (!lastLayer) {
        printf("Syntax error, likely '(' character isn't preceded by a container.\n");
        MOZ_CRASH();
      }
      parentContainerLayer = lastLayer->AsContainerLayer();
      if (!parentContainerLayer) {
        printf("Layer before '(' must be a container.\n");
        MOZ_CRASH();
      }
    } else if (aLayerTreeDescription[i] == ')') {
      parentContainerLayer = parentContainerLayer->GetParent();
      lastLayer = nullptr;
    } else {
      nsRefPtr<Layer> layer = CreateLayer(aLayerTreeDescription[i], manager.get());
      if (aVisibleRegions) {
        layer->SetVisibleRegion(aVisibleRegions[layerNumber]);
        layer->SetEventRegions(EventRegions(aVisibleRegions[layerNumber]));
      }
      if (aTransforms) {
        layer->SetBaseTransform(aTransforms[layerNumber]);
      }
      aLayersOut.AppendElement(layer);
      layerNumber++;
      if (rootLayer && !parentContainerLayer) {
        MOZ_CRASH();
      }
      if (!rootLayer) {
        rootLayer = layer;
      }
      if (parentContainerLayer) {
        parentContainerLayer->InsertAfter(layer, parentContainerLayer->GetLastChild());
        layer->SetParent(parentContainerLayer);
      }
      lastLayer = layer;
    }
  }
  if (rootLayer) {
    rootLayer->ComputeEffectiveTransforms(Matrix4x4());
    manager->SetRoot(rootLayer);
    if (rootLayer->AsLayerComposite()) {
      // Only perform this for LayerManagerComposite
      CompositorParent::SetShadowProperties(rootLayer);
    }
  }
  return rootLayer.forget();
}
nsresult
HTMLFormControlsCollection::GetSortedControls(
  nsTArray<nsGenericHTMLFormElement*>& aControls) const
{
#ifdef DEBUG
  HTMLFormElement::AssertDocumentOrder(mElements, mForm);
  HTMLFormElement::AssertDocumentOrder(mNotInElements, mForm);
#endif

  aControls.Clear();

  // Merge the elements list and the not in elements list. Both lists are
  // already sorted.
  uint32_t elementsLen = mElements.Length();
  uint32_t notInElementsLen = mNotInElements.Length();
  aControls.SetCapacity(elementsLen + notInElementsLen);

  uint32_t elementsIdx = 0;
  uint32_t notInElementsIdx = 0;

  while (elementsIdx < elementsLen || notInElementsIdx < notInElementsLen) {
    // Check whether we're done with mElements
    if (elementsIdx == elementsLen) {
      NS_ASSERTION(notInElementsIdx < notInElementsLen,
                   "Should have remaining not-in-elements");
      // Append the remaining mNotInElements elements
      if (!aControls.AppendElements(mNotInElements.Elements() +
                                      notInElementsIdx,
                                    notInElementsLen -
                                      notInElementsIdx)) {
        return NS_ERROR_OUT_OF_MEMORY;
      }
      break;
    }
    // Check whether we're done with mNotInElements
    if (notInElementsIdx == notInElementsLen) {
      NS_ASSERTION(elementsIdx < elementsLen,
                   "Should have remaining in-elements");
      // Append the remaining mElements elements
      if (!aControls.AppendElements(mElements.Elements() +
                                      elementsIdx,
                                    elementsLen -
                                      elementsIdx)) {
        return NS_ERROR_OUT_OF_MEMORY;
      }
      break;
    }
    // Both lists have elements left.
    NS_ASSERTION(mElements[elementsIdx] &&
                 mNotInElements[notInElementsIdx],
                 "Should have remaining elements");
    // Determine which of the two elements should be ordered
    // first and add it to the end of the list.
    nsGenericHTMLFormElement* elementToAdd;
    if (HTMLFormElement::CompareFormControlPosition(
          mElements[elementsIdx], mNotInElements[notInElementsIdx], mForm) < 0) {
      elementToAdd = mElements[elementsIdx];
      ++elementsIdx;
    } else {
      elementToAdd = mNotInElements[notInElementsIdx];
      ++notInElementsIdx;
    }
    // Add the first element to the list.
    if (!aControls.AppendElement(elementToAdd)) {
      return NS_ERROR_OUT_OF_MEMORY;
    }
  }

  NS_ASSERTION(aControls.Length() == elementsLen + notInElementsLen,
               "Not all form controls were added to the sorted list");
#ifdef DEBUG
  HTMLFormElement::AssertDocumentOrder(aControls, mForm);
#endif

  return NS_OK;
}
예제 #5
0
void
nsCSSExpandedDataBlock::Compress(nsCSSCompressedDataBlock **aNormalBlock,
                                 nsCSSCompressedDataBlock **aImportantBlock,
                                 const nsTArray<uint32_t>& aOrder)
{
  nsAutoPtr<nsCSSCompressedDataBlock> result_normal, result_important;
  uint32_t i_normal = 0, i_important = 0;

  uint32_t numPropsNormal, numPropsImportant;
  ComputeNumProps(&numPropsNormal, &numPropsImportant);

  result_normal =
    new(numPropsNormal) nsCSSCompressedDataBlock(numPropsNormal);

  if (numPropsImportant != 0) {
    result_important =
      new(numPropsImportant) nsCSSCompressedDataBlock(numPropsImportant);
  } else {
    result_important = nullptr;
  }

  /*
   * Save needless copying and allocation by copying the memory
   * corresponding to the stored data in the expanded block, and then
   * clearing the data in the expanded block.
   */
  for (size_t i = 0; i < aOrder.Length(); i++) {
    nsCSSProperty iProp = static_cast<nsCSSProperty>(aOrder[i]);
    if (iProp >= eCSSProperty_COUNT) {
      // a custom property
      continue;
    }
    MOZ_ASSERT(mPropertiesSet.HasProperty(iProp),
               "aOrder identifies a property not in the expanded "
               "data block");
    MOZ_ASSERT(!nsCSSProps::IsShorthand(iProp), "out of range");
    bool important = mPropertiesImportant.HasProperty(iProp);
    nsCSSCompressedDataBlock *result =
      important ? result_important : result_normal;
    uint32_t* ip = important ? &i_important : &i_normal;
    nsCSSValue* val = PropertyAt(iProp);
    MOZ_ASSERT(val->GetUnit() != eCSSUnit_Null,
               "Null value while compressing");
    result->SetPropertyAtIndex(*ip, iProp);
    result->RawCopyValueToIndex(*ip, val);
    new (val) nsCSSValue();
    (*ip)++;
    result->mStyleBits |=
      nsCachedStyleData::GetBitForSID(nsCSSProps::kSIDTable[iProp]);
  }

  MOZ_ASSERT(numPropsNormal == i_normal, "bad numProps");

  if (result_important) {
    MOZ_ASSERT(numPropsImportant == i_important, "bad numProps");
  }

#ifdef DEBUG
  {
    // assert that we didn't have any other properties on this expanded data
    // block that we didn't find in aOrder
    uint32_t numPropsInSet = 0;
    for (size_t iHigh = 0; iHigh < nsCSSPropertySet::kChunkCount; iHigh++) {
      if (!mPropertiesSet.HasPropertyInChunk(iHigh)) {
        continue;
      }
      for (size_t iLow = 0; iLow < nsCSSPropertySet::kBitsInChunk; iLow++) {
        if (mPropertiesSet.HasPropertyAt(iHigh, iLow)) {
          numPropsInSet++;
        }
      }
    }
    MOZ_ASSERT(numPropsNormal + numPropsImportant == numPropsInSet,
               "aOrder missing properties from the expanded data block");
  }
#endif

  ClearSets();
  AssertInitialState();
  *aNormalBlock = result_normal.forget();
  *aImportantBlock = result_important.forget();
}
예제 #6
0
nsresult
nsNumberControlFrame::CreateAnonymousContent(nsTArray<ContentInfo>& aElements)
{
  nsresult rv;

  // We create an anonymous tree for our input element that is structured as
  // follows:
  //
  // input
  //   div      - outer wrapper with "display:flex" by default
  //     input  - text input field
  //     div    - spin box wrapping up/down arrow buttons
  //       div  - spin up (up arrow button)
  //       div  - spin down (down arrow button)
  //
  // If you change this, be careful to change the destruction order in
  // nsNumberControlFrame::DestroyFrom.


  // Create the anonymous outer wrapper:
  rv = MakeAnonymousElement(getter_AddRefs(mOuterWrapper),
                            aElements,
                            nsGkAtoms::div,
                            nsCSSPseudoElements::ePseudo_mozNumberWrapper,
                            mStyleContext);
  NS_ENSURE_SUCCESS(rv, rv);

  ContentInfo& outerWrapperCI = aElements.LastElement();

  // Create the ::-moz-number-text pseudo-element:
  rv = MakeAnonymousElement(getter_AddRefs(mTextField),
                            outerWrapperCI.mChildren,
                            nsGkAtoms::input,
                            nsCSSPseudoElements::ePseudo_mozNumberText,
                            outerWrapperCI.mStyleContext);
  NS_ENSURE_SUCCESS(rv, rv);

  mTextField->SetAttr(kNameSpaceID_None, nsGkAtoms::type,
                      NS_LITERAL_STRING("text"), PR_FALSE);

  HTMLInputElement* content = HTMLInputElement::FromContent(mContent);
  HTMLInputElement* textField = HTMLInputElement::FromContent(mTextField);

  // Initialize the text field value:
  nsAutoString value;
  content->GetValue(value);
  SetValueOfAnonTextControl(value);

  // If we're readonly, make sure our anonymous text control is too:
  nsAutoString readonly;
  if (mContent->GetAttr(kNameSpaceID_None, nsGkAtoms::readonly, readonly)) {
    mTextField->SetAttr(kNameSpaceID_None, nsGkAtoms::readonly, readonly, false);
  }

  // Propogate our tabindex:
  int32_t tabIndex;
  content->GetTabIndex(&tabIndex);
  textField->SetTabIndex(tabIndex);

  // Initialize the text field's placeholder, if ours is set:
  nsAutoString placeholder;
  if (mContent->GetAttr(kNameSpaceID_None, nsGkAtoms::placeholder, placeholder)) {
    mTextField->SetAttr(kNameSpaceID_None, nsGkAtoms::placeholder, placeholder, false);
  }

  if (mContent->AsElement()->State().HasState(NS_EVENT_STATE_FOCUS)) {
    // We don't want to focus the frame but the text field.
    nsIFocusManager* fm = nsFocusManager::GetFocusManager();
    nsCOMPtr<nsIDOMElement> element = do_QueryInterface(mTextField);
    NS_ASSERTION(element, "Really, this should be a nsIDOMElement!");
    fm->SetFocus(element, 0);
  }

  if (StyleDisplay()->mAppearance == NS_THEME_TEXTFIELD) {
    // The author has elected to hide the spinner by setting this
    // -moz-appearance. We will reframe if it changes.
    return rv;
  }

  // Create the ::-moz-number-spin-box pseudo-element:
  rv = MakeAnonymousElement(getter_AddRefs(mSpinBox),
                            outerWrapperCI.mChildren,
                            nsGkAtoms::div,
                            nsCSSPseudoElements::ePseudo_mozNumberSpinBox,
                            outerWrapperCI.mStyleContext);
  NS_ENSURE_SUCCESS(rv, rv);

  ContentInfo& spinBoxCI = outerWrapperCI.mChildren.LastElement();

  // Create the ::-moz-number-spin-up pseudo-element:
  rv = MakeAnonymousElement(getter_AddRefs(mSpinUp),
                            spinBoxCI.mChildren,
                            nsGkAtoms::div,
                            nsCSSPseudoElements::ePseudo_mozNumberSpinUp,
                            spinBoxCI.mStyleContext);
  NS_ENSURE_SUCCESS(rv, rv);

  // Create the ::-moz-number-spin-down pseudo-element:
  rv = MakeAnonymousElement(getter_AddRefs(mSpinDown),
                            spinBoxCI.mChildren,
                            nsGkAtoms::div,
                            nsCSSPseudoElements::ePseudo_mozNumberSpinDown,
                            spinBoxCI.mStyleContext);

  SyncDisabledState();

  return rv;
}
예제 #7
0
nsresult
nsTextControlFrame::CreateAnonymousContent(nsTArray<ContentInfo>& aElements)
{
  NS_ASSERTION(mContent, "We should have a content!");

  mState |= NS_FRAME_INDEPENDENT_SELECTION;

  nsCOMPtr<nsITextControlElement> txtCtrl = do_QueryInterface(GetContent());
  NS_ASSERTION(txtCtrl, "Content not a text control element");

  // Bind the frame to its text control
  nsresult rv = txtCtrl->BindToFrame(this);
  NS_ENSURE_SUCCESS(rv, rv);

  nsIContent* rootNode = txtCtrl->GetRootEditorNode();
  NS_ENSURE_TRUE(rootNode, NS_ERROR_OUT_OF_MEMORY);

  if (!aElements.AppendElement(rootNode))
    return NS_ERROR_OUT_OF_MEMORY;

  // Do we need a placeholder node?
  nsAutoString placeholderTxt;
  mContent->GetAttr(kNameSpaceID_None, nsGkAtoms::placeholder,
                    placeholderTxt);
  nsContentUtils::RemoveNewlines(placeholderTxt);
  mUsePlaceholder = !placeholderTxt.IsEmpty();

  // Create the placeholder anonymous content if needed.
  if (mUsePlaceholder) {
    nsIContent* placeholderNode = txtCtrl->CreatePlaceholderNode();
    NS_ENSURE_TRUE(placeholderNode, NS_ERROR_OUT_OF_MEMORY);

    // Associate ::-moz-placeholder pseudo-element with the placeholder node.
    nsCSSPseudoElements::Type pseudoType =
      nsCSSPseudoElements::ePseudo_mozPlaceholder;

    nsRefPtr<nsStyleContext> placeholderStyleContext =
      PresContext()->StyleSet()->ResolvePseudoElementStyle(
          mContent->AsElement(), pseudoType, GetStyleContext());

    if (!aElements.AppendElement(ContentInfo(placeholderNode,
                                 placeholderStyleContext))) {
      return NS_ERROR_OUT_OF_MEMORY;
    }
  }

  rv = UpdateValueDisplay(false);
  NS_ENSURE_SUCCESS(rv, rv);

  // textareas are eagerly initialized
  bool initEagerly = !IsSingleLineTextControl();
  if (!initEagerly) {
    // Also, input elements which have a cached selection should get eager
    // editor initialization.
    nsCOMPtr<nsITextControlElement> txtCtrl = do_QueryInterface(GetContent());
    NS_ASSERTION(txtCtrl, "Content not a text control element");
    initEagerly = txtCtrl->HasCachedSelection();
  }
  if (!initEagerly) {
    nsCOMPtr<nsIDOMHTMLElement> element = do_QueryInterface(txtCtrl);
    if (element) {
      // so are input text controls with spellcheck=true
      element->GetSpellcheck(&initEagerly);
    }
  }

  if (initEagerly) {
    NS_ASSERTION(!nsContentUtils::IsSafeToRunScript(),
                 "Someone forgot a script blocker?");
    EditorInitializer* initializer = (EditorInitializer*) Properties().Get(TextControlInitializer());
    if (initializer) {
      initializer->Revoke();
    }
    initializer = new EditorInitializer(this);
    Properties().Set(TextControlInitializer(),initializer);
    if (!nsContentUtils::AddScriptRunner(initializer)) {
      initializer->Revoke(); // paranoia
      Properties().Delete(TextControlInitializer());
      delete initializer;
      return NS_ERROR_OUT_OF_MEMORY;
    }
  }

  return NS_OK;
}
예제 #8
0
nsresult
nsFontCache::GetMetricsFor(const nsFont& aFont,
                           nsIAtom* aLanguage, bool aExplicitLanguage,
                           gfxFont::Orientation aOrientation,
                           gfxUserFontSet* aUserFontSet,
                           gfxTextPerfMetrics* aTextPerf,
                           nsFontMetrics*& aMetrics)
{
    if (!aLanguage)
        aLanguage = mLocaleLanguage;

    // First check our cache
    // start from the end, which is where we put the most-recent-used element

    nsFontMetrics* fm;
    int32_t n = mFontMetrics.Length() - 1;
    for (int32_t i = n; i >= 0; --i) {
        fm = mFontMetrics[i];
        if (fm->Font().Equals(aFont) && fm->GetUserFontSet() == aUserFontSet &&
            fm->Language() == aLanguage && fm->Orientation() == aOrientation) {
            if (i != n) {
                // promote it to the end of the cache
                mFontMetrics.RemoveElementAt(i);
                mFontMetrics.AppendElement(fm);
            }
            fm->GetThebesFontGroup()->UpdateUserFonts();
            NS_ADDREF(aMetrics = fm);
            return NS_OK;
        }
    }

    // It's not in the cache. Get font metrics and then cache them.

    fm = new nsFontMetrics();
    NS_ADDREF(fm);
    nsresult rv = fm->Init(aFont, aLanguage, aExplicitLanguage, aOrientation,
                           mContext, aUserFontSet, aTextPerf);
    if (NS_SUCCEEDED(rv)) {
        // the mFontMetrics list has the "head" at the end, because append
        // is cheaper than insert
        mFontMetrics.AppendElement(fm);
        aMetrics = fm;
        NS_ADDREF(aMetrics);
        return NS_OK;
    }
    fm->Destroy();
    NS_RELEASE(fm);

    // One reason why Init() fails is because the system is running out of
    // resources. e.g., on Win95/98 only a very limited number of GDI
    // objects are available. Compact the cache and try again.

    Compact();
    fm = new nsFontMetrics();
    NS_ADDREF(fm);
    rv = fm->Init(aFont, aLanguage, aExplicitLanguage, aOrientation, mContext,
                  aUserFontSet, aTextPerf);
    if (NS_SUCCEEDED(rv)) {
        mFontMetrics.AppendElement(fm);
        aMetrics = fm;
        return NS_OK;
    }
    fm->Destroy();
    NS_RELEASE(fm);

    // could not setup a new one, send an old one (XXX search a "best
    // match"?)

    n = mFontMetrics.Length() - 1; // could have changed in Compact()
    if (n >= 0) {
        aMetrics = mFontMetrics[n];
        NS_ADDREF(aMetrics);
        return NS_OK;
    }

    NS_POSTCONDITION(NS_SUCCEEDED(rv),
                     "font metrics should not be null - bug 136248");
    return rv;
}
예제 #9
0
void
nsFontCache::FontMetricsDeleted(const nsFontMetrics* aFontMetrics)
{
    mFontMetrics.RemoveElement(aFontMetrics);
}
예제 #10
0
nsresult
nsCanvasFrame::CreateAnonymousContent(nsTArray<ContentInfo>& aElements)
{
  if (!mContent) {
    return NS_OK;
  }

  nsCOMPtr<nsIDocument> doc = mContent->OwnerDoc();
  nsresult rv = NS_OK;
  ErrorResult er;
  // We won't create touch caret element if preference is not enabled.
  if (PresShell::TouchCaretPrefEnabled()) {
    nsRefPtr<dom::NodeInfo> nodeInfo;

    // Create and append touch caret frame.
    nodeInfo = doc->NodeInfoManager()->GetNodeInfo(nsGkAtoms::div, nullptr,
                                                   kNameSpaceID_XHTML,
                                                   nsIDOMNode::ELEMENT_NODE);
    NS_ENSURE_TRUE(nodeInfo, NS_ERROR_OUT_OF_MEMORY);

    rv = NS_NewHTMLElement(getter_AddRefs(mTouchCaretElement), nodeInfo.forget(),
                           mozilla::dom::NOT_FROM_PARSER);
    NS_ENSURE_SUCCESS(rv, rv);
    aElements.AppendElement(mTouchCaretElement);

    // Add a _moz_anonclass attribute as touch caret selector.
    mTouchCaretElement->SetAttribute(NS_LITERAL_STRING("_moz_anonclass"),
                                     NS_LITERAL_STRING("mozTouchCaret"), er);
    NS_ENSURE_SUCCESS(er.ErrorCode(), er.ErrorCode());

    // Set touch caret to visibility: hidden by default.
    nsAutoString classValue;
    classValue.AppendLiteral("moz-touchcaret hidden");
    rv = mTouchCaretElement->SetAttr(kNameSpaceID_None, nsGkAtoms::_class,
                                     classValue, true);
    NS_ENSURE_SUCCESS(rv, rv);
  }

  if (PresShell::SelectionCaretPrefEnabled()) {
    // Selection caret
    mSelectionCaretsStartElement = doc->CreateHTMLElement(nsGkAtoms::div);
    aElements.AppendElement(mSelectionCaretsStartElement);

    mSelectionCaretsEndElement = doc->CreateHTMLElement(nsGkAtoms::div);
    aElements.AppendElement(mSelectionCaretsEndElement);

    mSelectionCaretsStartElement->SetAttribute(NS_LITERAL_STRING("_moz_anonclass"),
                                               NS_LITERAL_STRING("mozTouchCaret"), er);
    rv = mSelectionCaretsStartElement->SetAttr(kNameSpaceID_None, nsGkAtoms::_class,
                                               NS_LITERAL_STRING("moz-selectioncaret-left hidden"),
                                               true);
    NS_ENSURE_SUCCESS(rv, rv);

    mSelectionCaretsEndElement->SetAttribute(NS_LITERAL_STRING("_moz_anonclass"),
                                             NS_LITERAL_STRING("mozTouchCaret"), er);
    rv = mSelectionCaretsEndElement->SetAttr(kNameSpaceID_None, nsGkAtoms::_class,
                                             NS_LITERAL_STRING("moz-selectioncaret-right hidden"),
                                             true);
    NS_ENSURE_SUCCESS(rv, rv);
  }

  return NS_OK;
}
예제 #11
0
void SortLayersBy3DZOrder(nsTArray<Layer*>& aLayers)
{
  uint32_t nodeCount = aLayers.Length();
  if (nodeCount > MAX_SORTABLE_LAYERS) {
    return;
  }
  DirectedGraph<Layer*> graph;

#ifdef DEBUG
  if (gDumpLayerSortList) {
    for (uint32_t i = 0; i < nodeCount; i++) {
      if (aLayers.ElementAt(i)->GetDebugColorIndex() == 0) {
        aLayers.ElementAt(i)->SetDebugColorIndex(gColorIndex++);
        if (gColorIndex > 7) {
          gColorIndex = 1;
        }
      }
    }
    fprintf(stderr, " --- Layers before sorting: --- \n");
    DumpLayerList(aLayers);
  }
#endif

  // Iterate layers and determine edges.
  for (uint32_t i = 0; i < nodeCount; i++) {
    for (uint32_t j = i + 1; j < nodeCount; j++) {
      Layer* a = aLayers.ElementAt(i);
      Layer* b = aLayers.ElementAt(j);
      LayerSortOrder order = CompareDepth(a, b);
      if (order == ABeforeB) {
        graph.AddEdge(a, b);
      } else if (order == BBeforeA) {
        graph.AddEdge(b, a);
      }
    }
  }

#ifdef DEBUG
  if (gDumpLayerSortList) {
    fprintf(stderr, " --- Edge List: --- \n");
    DumpEdgeList(graph);
  }
#endif

  // Build a new array using the graph.
  nsTArray<Layer*> noIncoming;
  nsTArray<Layer*> sortedList;

  // Make a list of all layers with no incoming edges.
  noIncoming.AppendElements(aLayers);
  const nsTArray<DirectedGraph<Layer*>::Edge>& edges = graph.GetEdgeList();
  for (uint32_t i = 0; i < edges.Length(); i++) {
    noIncoming.RemoveElement(edges.ElementAt(i).mTo);
  }

  // Move each item without incoming edges into the sorted list,
  // and remove edges from it.
  do {
    if (!noIncoming.IsEmpty()) {
      uint32_t last = noIncoming.Length() - 1;

      Layer* layer = noIncoming.ElementAt(last);
      MOZ_ASSERT(layer); // don't let null layer pointers sneak into sortedList

      noIncoming.RemoveElementAt(last);
      sortedList.AppendElement(layer);

      nsTArray<DirectedGraph<Layer*>::Edge> outgoing;
      graph.GetEdgesFrom(layer, outgoing);
      for (uint32_t i = 0; i < outgoing.Length(); i++) {
        DirectedGraph<Layer*>::Edge edge = outgoing.ElementAt(i);
        graph.RemoveEdge(edge);
        if (!graph.NumEdgesTo(edge.mTo)) {
          // If this node also has no edges now, add it to the list
          noIncoming.AppendElement(edge.mTo);
        }
      }
    }

    // If there are no nodes without incoming edges, but there
    // are still edges, then we have a cycle.
    if (noIncoming.IsEmpty() && graph.GetEdgeCount()) {
      // Find the node with the least incoming edges.
      uint32_t minEdges = UINT_MAX;
      Layer* minNode = nullptr;
      for (uint32_t i = 0; i < aLayers.Length(); i++) {
        uint32_t edgeCount = graph.NumEdgesTo(aLayers.ElementAt(i));
        if (edgeCount && edgeCount < minEdges) {
          minEdges = edgeCount;
          minNode = aLayers.ElementAt(i);
          if (minEdges == 1) {
            break;
          }
        }
      }

      if (minNode) {
        // Remove all of them!
        graph.RemoveEdgesTo(minNode);
        noIncoming.AppendElement(minNode);
      }
    }
  } while (!noIncoming.IsEmpty());
  NS_ASSERTION(!graph.GetEdgeCount(), "Cycles detected!");
#ifdef DEBUG
  if (gDumpLayerSortList) {
    fprintf(stderr, " --- Layers after sorting: --- \n");
    DumpLayerList(sortedList);
  }
#endif

  aLayers.Clear();
  aLayers.AppendElements(sortedList);
}
void
nsSVGTextContainerFrame::GetEffectiveRotate(nsTArray<float> &aRotate)
{
  aRotate.AppendElements(mRotate);
}
예제 #13
0
nsresult nsFontCache::FontMetricsDeleted(const nsIFontMetrics* aFontMetrics)
{
    mFontMetrics.RemoveElement(aFontMetrics);
    return NS_OK;
}
예제 #14
0
nsresult
nsFontCache::GetMetricsFor(const nsFont& aFont, nsIAtom* aLanguage,
  gfxUserFontSet* aUserFontSet, nsIFontMetrics*& aMetrics)
{
    // First check our cache
    // start from the end, which is where we put the most-recent-used element

    nsIFontMetrics* fm;
    PRInt32 n = mFontMetrics.Length() - 1;
    for (PRInt32 i = n; i >= 0; --i) {
        fm = mFontMetrics[i];
        nsIThebesFontMetrics* tfm = static_cast<nsIThebesFontMetrics*>(fm);
        if (fm->Font().Equals(aFont) && tfm->GetUserFontSet() == aUserFontSet) {
            nsCOMPtr<nsIAtom> language;
            fm->GetLanguage(getter_AddRefs(language));
            if (aLanguage == language.get()) {
                if (i != n) {
                    // promote it to the end of the cache
                    mFontMetrics.RemoveElementAt(i);
                    mFontMetrics.AppendElement(fm);
                }
                tfm->GetThebesFontGroup()->UpdateFontList();
                NS_ADDREF(aMetrics = fm);
                return NS_OK;
            }
        }
    }

    // It's not in the cache. Get font metrics and then cache them.

    aMetrics = nsnull;
    nsresult rv = CreateFontMetricsInstance(&fm);
    if (NS_FAILED(rv)) return rv;
    rv = fm->Init(aFont, aLanguage, mContext, aUserFontSet);
    if (NS_SUCCEEDED(rv)) {
        // the mFontMetrics list has the "head" at the end, because append
        // is cheaper than insert
        mFontMetrics.AppendElement(fm);
        aMetrics = fm;
        NS_ADDREF(aMetrics);
        return NS_OK;
    }
    fm->Destroy();
    NS_RELEASE(fm);

    // One reason why Init() fails is because the system is running out of
    // resources. e.g., on Win95/98 only a very limited number of GDI
    // objects are available. Compact the cache and try again.

    Compact();
    rv = CreateFontMetricsInstance(&fm);
    if (NS_FAILED(rv)) return rv;
    rv = fm->Init(aFont, aLanguage, mContext, aUserFontSet);
    if (NS_SUCCEEDED(rv)) {
        mFontMetrics.AppendElement(fm);
        aMetrics = fm;
        NS_ADDREF(aMetrics);
        return NS_OK;
    }
    fm->Destroy();
    NS_RELEASE(fm);

    // could not setup a new one, send an old one (XXX search a "best
    // match"?)

    n = mFontMetrics.Length() - 1; // could have changed in Compact()
    if (n >= 0) {
        aMetrics = mFontMetrics[n];
        NS_ADDREF(aMetrics);
        return NS_OK;
    }

    NS_POSTCONDITION(NS_SUCCEEDED(rv), "font metrics should not be null - bug 136248");
    return rv;
}
예제 #15
0
NS_IMETHODIMP
nsPrintSettings::GetPageRanges(nsTArray<int32_t> &aPages)
{
  aPages.Clear();
  return NS_OK;
}
void nsAutoSyncState::OnNewHeaderFetchCompleted(const nsTArray<nsMsgKey> &aMsgKeyList)
{
  SetLastUpdateTime(PR_Now());
  if (!aMsgKeyList.IsEmpty())
    PlaceIntoDownloadQ(aMsgKeyList);
}
예제 #17
0
void
DOMIntersectionObserver::TakeRecords(nsTArray<RefPtr<DOMIntersectionObserverEntry>>& aRetVal)
{
  aRetVal.SwapElements(mQueuedEntries);
  mQueuedEntries.Clear();
}
nsresult nsAutoSyncState::PlaceIntoDownloadQ(const nsTArray<nsMsgKey> &aMsgKeyList)
{
  nsresult rv;
  if (!aMsgKeyList.IsEmpty())
  {
    nsCOMPtr <nsIMsgFolder> folder = do_QueryReferent(mOwnerFolder, &rv);
    NS_ENSURE_SUCCESS(rv, rv);
        
    nsCOMPtr<nsIMsgDatabase> database;
    rv = folder->GetMsgDatabase(getter_AddRefs(database));
    if (!database)
      return NS_ERROR_FAILURE;
    
    nsCOMPtr<nsIAutoSyncManager> autoSyncMgr = do_GetService(NS_AUTOSYNCMANAGER_CONTRACTID, &rv);
    NS_ENSURE_SUCCESS(rv,rv);
    
    nsCOMPtr<nsIAutoSyncMsgStrategy> msgStrategy;
    autoSyncMgr->GetMsgStrategy(getter_AddRefs(msgStrategy));
    
    // increase the array size
    mDownloadQ.SetCapacity(mDownloadQ.Length() + aMsgKeyList.Length());
    
    // remove excluded messages
    int32_t elemCount = aMsgKeyList.Length();
    for (int32_t idx = 0; idx < elemCount; idx++)
    {
      nsCOMPtr<nsIMsgDBHdr> hdr;
      bool containsKey;
      database->ContainsKey(aMsgKeyList[idx], &containsKey);
      if (!containsKey)
        continue;
      rv = database->GetMsgHdrForKey(aMsgKeyList[idx], getter_AddRefs(hdr));
      if(!hdr)
        continue; // can't get message header, continue with the next one
      
      bool doesFit = true;
      rv = autoSyncMgr->DoesMsgFitDownloadCriteria(hdr, &doesFit);
      if (NS_SUCCEEDED(rv) && !mDownloadSet.Contains(aMsgKeyList[idx]) && doesFit)
      {
        bool excluded = false;
        if (msgStrategy)
        {
          rv = msgStrategy->IsExcluded(folder, hdr, &excluded);
          
          if (NS_SUCCEEDED(rv) && !excluded)
          {
            mIsDownloadQChanged = true;
            mDownloadSet.PutEntry(aMsgKeyList[idx]);
            mDownloadQ.AppendElement(aMsgKeyList[idx]);
          }
        }
      }
    }//endfor

    if (mIsDownloadQChanged)
    {
      LogOwnerFolderName("Download Q is created for ");
      LogQWithSize(mDownloadQ, 0);
      rv = autoSyncMgr->OnDownloadQChanged(this);
    }
    
  }
  return rv;
}
예제 #19
0
nsresult
GfxInfo::GetFeatureStatusImpl(int32_t aFeature,
                              int32_t *aStatus, 
                              nsAString & aSuggestedDriverVersion, 
                              const nsTArray<GfxDriverInfo>& aDriverInfo,
                              OperatingSystem* aOS /* = nullptr */)
{
  NS_ENSURE_ARG_POINTER(aStatus);
  aSuggestedDriverVersion.SetIsVoid(true);
  OperatingSystem os = WindowsVersionToOperatingSystem(mWindowsVersion);
  *aStatus = nsIGfxInfo::FEATURE_STATUS_UNKNOWN;
  if (aOS)
    *aOS = os;

  // Don't evaluate special cases if we're checking the downloaded blocklist.
  if (!aDriverInfo.Length()) {
    nsAutoString adapterVendorID;
    nsAutoString adapterDeviceID;
    nsAutoString adapterDriverVersionString;
    if (NS_FAILED(GetAdapterVendorID(adapterVendorID)) ||
        NS_FAILED(GetAdapterDeviceID(adapterDeviceID)) ||
        NS_FAILED(GetAdapterDriverVersion(adapterDriverVersionString)))
    {
      return NS_ERROR_FAILURE;
    }

    if (!adapterVendorID.Equals(GfxDriverInfo::GetDeviceVendor(VendorIntel), nsCaseInsensitiveStringComparator()) &&
        !adapterVendorID.Equals(GfxDriverInfo::GetDeviceVendor(VendorNVIDIA), nsCaseInsensitiveStringComparator()) &&
        !adapterVendorID.Equals(GfxDriverInfo::GetDeviceVendor(VendorAMD), nsCaseInsensitiveStringComparator()) &&
        !adapterVendorID.Equals(GfxDriverInfo::GetDeviceVendor(VendorATI), nsCaseInsensitiveStringComparator()) &&
        // FIXME - these special hex values are currently used in xpcshell tests introduced by
        // bug 625160 patch 8/8. Maybe these tests need to be adjusted now that we're only whitelisting
        // intel/ati/nvidia.
        !adapterVendorID.LowerCaseEqualsLiteral("0xabcd") &&
        !adapterVendorID.LowerCaseEqualsLiteral("0xdcba") &&
        !adapterVendorID.LowerCaseEqualsLiteral("0xabab") &&
        !adapterVendorID.LowerCaseEqualsLiteral("0xdcdc"))
    {
      *aStatus = FEATURE_BLOCKED_DEVICE;
      return NS_OK;
    }

    uint64_t driverVersion;
    if (!ParseDriverVersion(adapterDriverVersionString, &driverVersion)) {
      return NS_ERROR_FAILURE;
    }

    // special-case the WinXP test slaves: they have out-of-date drivers, but we still want to
    // whitelist them, actually we do know that this combination of device and driver version
    // works well.
    if (mWindowsVersion == gfxWindowsPlatform::kWindowsXP &&
        adapterVendorID.Equals(GfxDriverInfo::GetDeviceVendor(VendorNVIDIA), nsCaseInsensitiveStringComparator()) &&
        adapterDeviceID.LowerCaseEqualsLiteral("0x0861") && // GeForce 9400
        driverVersion == V(6,14,11,7756))
    {
      *aStatus = FEATURE_NO_INFO;
      return NS_OK;
    }

    // ANGLE currently uses D3D10 <-> D3D9 interop, which crashes on Optimus
    // machines.
    if (aFeature == FEATURE_WEBGL_ANGLE &&
        gfxWindowsPlatform::IsOptimus())
    {
      *aStatus = FEATURE_BLOCKED_DEVICE;
      return NS_OK;
    }

    // Windows Server 2003 should be just like Windows XP for present purpose, but still has a different version number.
    // OTOH Windows Server 2008 R1 and R2 already have the same version numbers as Vista and Seven respectively
    if (os == DRIVER_OS_WINDOWS_SERVER_2003)
      os = DRIVER_OS_WINDOWS_XP;

    if (mHasDriverVersionMismatch) {
      if (aFeature == nsIGfxInfo::FEATURE_DIRECT3D_10_LAYERS ||
          aFeature == nsIGfxInfo::FEATURE_DIRECT3D_10_1_LAYERS ||
          aFeature == nsIGfxInfo::FEATURE_DIRECT2D)
      {
        *aStatus = nsIGfxInfo::FEATURE_BLOCKED_DRIVER_VERSION;
        return NS_OK;
      }
    }
  }

  return GfxInfoBase::GetFeatureStatusImpl(aFeature, aStatus, aSuggestedDriverVersion, aDriverInfo, &os);
}
예제 #20
0
nsresult WebCL_getVariantsFromJSArray (JSContext *cx, nsIVariant* aVariant,
                                       nsTArray<nsIVariant*> & aResultOut)
{
  D_METHOD_START;
  nsresult rv;

  NS_ENSURE_ARG_POINTER (aVariant);
  PRUint16 variantType = 0;
  rv = aVariant->GetDataType (&variantType);
  switch (variantType)
  {
    // Accept VTYPE_ARRAY, VTYPE_EMPTY_ARRAY
    case nsIDataType::VTYPE_ARRAY:
    case nsIDataType::VTYPE_EMPTY_ARRAY:
      // Array detected
      break;
    case nsIDataType::VTYPE_INTERFACE:
    case nsIDataType::VTYPE_INTERFACE_IS:
      // Might be a proxy object holding the array
      break;

    default:
      D_LOG (LOG_LEVEL_ERROR, "Argument aVariant is not an array (type: %u).", variantType);
      return NS_ERROR_INVALID_ARG;
  }

  if (!cx)
  {
    nsCOMPtr<nsIThreadJSContextStack> stack = do_GetService ("@mozilla.org/js/xpc/ContextStack;1", &rv);
    NS_ENSURE_SUCCESS (rv, rv);
    cx = stack->GetSafeJSContext ();
    NS_ENSURE_TRUE (cx, NS_ERROR_FAILURE);
  }
  nsCOMPtr<nsIXPConnect> xpc = do_GetService (nsIXPConnect::GetCID (), &rv);
  NS_ENSURE_SUCCESS (rv, rv);

  js::Value jsVal;
  rv = xpc->VariantToJS(cx, JS_GetGlobalObject(cx), aVariant, &jsVal);
  NS_ENSURE_SUCCESS (rv, rv);

  if ( !jsVal.isObject ())
  {
    D_LOG (LOG_LEVEL_ERROR, "Argument aVariant is not a JSObject.");
    return NS_ERROR_INVALID_ARG;
  }

  JSObject* jsArrObj = jsVal.toObjectOrNull ();
  if (jsArrObj && js::IsObjectProxy (jsArrObj))
  {
    jsArrObj = js::UnwrapObject (jsArrObj);
  }

  if (!jsArrObj || !JS_IsArrayObject (cx, jsArrObj))
  {
    D_LOG (LOG_LEVEL_ERROR, "Argument aVariant is not a JS Array Object.");
    return NS_ERROR_INVALID_ARG;
  }

  nsTArray <nsIVariant*> res;

  JS_BeginRequest (cx);

  JSBool ok = JS_TRUE;
  uint32_t jsArrLen = 0;
  ok = JS_GetArrayLength(cx, jsArrObj, &jsArrLen);
  if (!ok)
  {
    JS_EndRequest(cx);
    D_LOG (LOG_LEVEL_ERROR, "Failed to get array length.");
    return NS_ERROR_FAILURE;
  }

  res.SetCapacity (jsArrLen);

  for (uint32_t i = 0; i < jsArrLen; ++i)
  {
    jsval elem;
    JSBool ok = JS_GetElement (cx, jsArrObj, i, &elem);
    if (ok)
    {
      nsCOMPtr<nsIVariant> variant;
      rv = xpc->JSValToVariant (cx, &elem, getter_AddRefs(variant));
      if (NS_SUCCEEDED (rv))
      {
        res.AppendElement (variant);
        NS_ADDREF (variant);
      }
      else
      {
        D_LOG (LOG_LEVEL_WARNING,
              "Failed to convert element at position %d to nsIVariant. (rv %d)",
              i+1, rv);
      }
    }
    else
    {
        D_LOG (LOG_LEVEL_WARNING,
               "Failed to get element at position %d to nsIVariant. (rv %d)",
               i+1, rv);
    }
  }

  JS_EndRequest(cx);

  aResultOut.SwapElements (res);

  return NS_OK;
}
void nsXBLPrototypeResources::AppendStyleSheetsTo(
    nsTArray<StyleSheet*>& aResult) const {
  aResult.AppendElements(mStyleSheetList);
}
예제 #22
0
nsresult WebCL_convertVectorToJSArrayInVariant_string(JSContext *cx,
                                                      nsTArray<nsCString> const& aVector,
                                                      int aType, nsIVariant** aResultOut,
                                                      WebCL_LibCLWrapper*)
{
  D_METHOD_START;
  NS_ENSURE_ARG_POINTER (aResultOut);
  nsresult rv;

  switch (aType)
  {
    case types::STRING_V:
      // Accept string vector types
      break;
    default:
    {
      D_LOG (LOG_LEVEL_ERROR, "Unsupported type %d, expected types::STRING_V", aType);
      return NS_ERROR_FAILURE;
    }
  }

  if (!cx)
  {
    nsCOMPtr<nsIThreadJSContextStack> stack = do_GetService ("@mozilla.org/js/xpc/ContextStack;1", &rv);
    NS_ENSURE_SUCCESS (rv, rv);
    cx = stack->GetSafeJSContext ();
    NS_ENSURE_TRUE (cx, NS_ERROR_FAILURE);
  }

  nsCOMPtr<nsIXPConnect> xpc = do_GetService (nsIXPConnect::GetCID (), &rv);
  NS_ENSURE_SUCCESS (rv, rv);

  JS_BeginRequest (cx);
  JSBool ignored = JS_EnterLocalRootScope (cx);
  (void)ignored; // ignored is there to avoid gcc warnings..

  JSObject* jsArr = JS_NewArrayObject (cx, aVector.Length (), NULL);
  if (!jsArr)
  {
    JS_LeaveLocalRootScope (cx);
    JS_EndRequest(cx);
    return NS_ERROR_OUT_OF_MEMORY;
  }

  size_t cnt = 0;
  for (nsTArray<nsCString>::index_type i = 0; i < aVector.Length(); ++i)
  {
    jsval val = STRING_TO_JSVAL (JS_NewStringCopyZ (cx, aVector[i].get ()));
    JS_SetElement (cx, jsArr, cnt++, &val);
  }

  JS_LeaveLocalRootScope (cx);
  JS_EndRequest(cx);

  // Wrap the JSArray in an nsIVariant
  nsCOMPtr<nsIVariant> value;
  js::Value jsValue;
  jsValue.setObjectOrNull (jsArr);
  rv = xpc->JSValToVariant(cx, &jsValue, getter_AddRefs(value));
  NS_ENSURE_SUCCESS (rv, rv);

  NS_ADDREF (*aResultOut = value);

  return NS_OK;
}
예제 #23
0
void VideoFrameContainer::SetCurrentFramesLocked(const gfx::IntSize& aIntrinsicSize,
                                                 const nsTArray<ImageContainer::NonOwningImage>& aImages)
{
  mMutex.AssertCurrentThreadOwns();

  if (aIntrinsicSize != mIntrinsicSize) {
    mIntrinsicSize = aIntrinsicSize;
    mIntrinsicSizeChanged = true;
  }

  gfx::IntSize oldFrameSize = mImageContainer->GetCurrentSize();

  // When using the OMX decoder, destruction of the current image can indirectly
  //  block on main thread I/O. If we let this happen while holding onto
  //  |mImageContainer|'s lock, then when the main thread then tries to
  //  composite it can then block on |mImageContainer|'s lock, causing a
  //  deadlock. We use this hack to defer the destruction of the current image
  //  until it is safe.
  nsTArray<ImageContainer::OwningImage> oldImages;
  mImageContainer->GetCurrentImages(&oldImages);

  ImageContainer::FrameID lastFrameIDForOldPrincipalHandle =
    mFrameIDForPendingPrincipalHandle - 1;
  if (mPendingPrincipalHandle != PRINCIPAL_HANDLE_NONE &&
       ((!oldImages.IsEmpty() &&
          oldImages.LastElement().mFrameID >= lastFrameIDForOldPrincipalHandle) ||
        (!aImages.IsEmpty() &&
          aImages[0].mFrameID > lastFrameIDForOldPrincipalHandle))) {
    // We are releasing the last FrameID prior to `lastFrameIDForOldPrincipalHandle`
    // OR
    // there are no FrameIDs prior to `lastFrameIDForOldPrincipalHandle` in the new
    // set of images.
    // This means that the old principal handle has been flushed out and we can
    // notify our video element about this change.
    RefPtr<VideoFrameContainer> self = this;
    PrincipalHandle principalHandle = mPendingPrincipalHandle;
    mLastPrincipalHandle = mPendingPrincipalHandle;
    mPendingPrincipalHandle = PRINCIPAL_HANDLE_NONE;
    mFrameIDForPendingPrincipalHandle = 0;
    mMainThread->Dispatch(
      NS_NewRunnableFunction(
        "PrincipalHandleChangedForVideoFrameContainer",
        [self, principalHandle]() {
          if (self->mElement) {
            self->mElement->PrincipalHandleChangedForVideoFrameContainer(self, principalHandle);
          }
        }
      )
    );
  }

  if (aImages.IsEmpty()) {
    mImageContainer->ClearAllImages();
  } else {
    mImageContainer->SetCurrentImages(aImages);
  }
  gfx::IntSize newFrameSize = mImageContainer->GetCurrentSize();
  if (oldFrameSize != newFrameSize) {
    mImageSizeChanged = true;
  }
}
예제 #24
0
nsresult WebCL_convertVectorToJSArrayInVariant(JSContext *cx, nsTArray<cl_image_format> const& aVector,
                                               nsIVariant** aResultOut, WebCL_LibCLWrapper*)
{
  D_METHOD_START;
  NS_ENSURE_ARG_POINTER (aResultOut);
  nsresult rv;

  if (!cx)
  {
    nsCOMPtr<nsIThreadJSContextStack> stack = do_GetService ("@mozilla.org/js/xpc/ContextStack;1", &rv);
    NS_ENSURE_SUCCESS (rv, rv);
    cx = stack->GetSafeJSContext ();
    NS_ENSURE_TRUE (cx, NS_ERROR_FAILURE);
  }

  nsCOMPtr<nsIXPConnect> xpc = do_GetService (nsIXPConnect::GetCID (), &rv);
  NS_ENSURE_SUCCESS (rv, rv);

  JS_BeginRequest (cx);
  JSBool ignored = JS_EnterLocalRootScope (cx);
  (void)ignored; // ignored is there to avoid gcc warnings..

  JSObject* jsArr = JS_NewArrayObject (cx, aVector.Length (), NULL);
  if (!jsArr)
  {
    JS_LeaveLocalRootScope (cx);
    JS_EndRequest(cx);
    return NS_ERROR_OUT_OF_MEMORY;
  }

  size_t cnt = 0;
  for (nsTArray<cl_image_format>::index_type i = 0; i < aVector.Length(); ++i)
  {
    JSObject* jsObj = JS_NewObject (cx, NULL, NULL, NULL);
    if (jsObj)
    {
      js::Value propChannelOrder;
      propChannelOrder.setInt32 (aVector[i].image_channel_order);
      js::Value propChannelDataType;
      propChannelDataType.setInt32 (aVector[i].image_channel_data_type);
      JS_SetProperty(cx, jsObj, "channelOrder", &propChannelOrder);
      JS_SetProperty(cx, jsObj, "channelDataType", &propChannelDataType);
      JS_SetProperty(cx, jsObj, "image_channel_order", &propChannelOrder);
      JS_SetProperty(cx, jsObj, "image_channel_data_type", &propChannelDataType);

      js::Value objVal;
      objVal.setObjectOrNull (jsObj);
      JS_SetElement (cx, jsArr, cnt++, &objVal);
    }
  }

  JS_LeaveLocalRootScope (cx);
  JS_EndRequest(cx);
  if (NS_FAILED (rv))
    return rv;

  // Wrap the JSArray in an nsIVariant
  nsCOMPtr<nsIVariant> value;
  js::Value jsValue;
  jsValue.setObjectOrNull (jsArr);
  rv = xpc->JSValToVariant(cx, &jsValue, getter_AddRefs(value));
  NS_ENSURE_SUCCESS (rv, rv);

  NS_ADDREF (*aResultOut = value);

  return NS_OK;
}
예제 #25
0
void
InternalHeaders::GetEntries(nsTArray<InternalHeaders::Entry>& aEntries) const
{
    MOZ_ASSERT(aEntries.IsEmpty());
    aEntries.AppendElements(mList);
}
예제 #26
0
NS_IMETHODIMP
PresentationService::StartSession(
               const nsTArray<nsString>& aUrls,
               const nsAString& aSessionId,
               const nsAString& aOrigin,
               const nsAString& aDeviceId,
               uint64_t aWindowId,
               nsIDOMEventTarget* aEventTarget,
               nsIPrincipal* aPrincipal,
               nsIPresentationServiceCallback* aCallback,
               nsIPresentationTransportBuilderConstructor* aBuilderConstructor)
{
  PRES_DEBUG("%s:id[%s]\n", __func__, NS_ConvertUTF16toUTF8(aSessionId).get());

  MOZ_ASSERT(NS_IsMainThread());
  MOZ_ASSERT(aCallback);
  MOZ_ASSERT(!aSessionId.IsEmpty());
  MOZ_ASSERT(!aUrls.IsEmpty());

  nsCOMPtr<nsIPresentationDeviceRequest> request =
    new PresentationDeviceRequest(aUrls,
                                  aSessionId,
                                  aOrigin,
                                  aWindowId,
                                  aEventTarget,
                                  aPrincipal,
                                  aCallback,
                                  aBuilderConstructor);

  if (aDeviceId.IsVoid()) {
    // Pop up a prompt and ask user to select a device.
    nsCOMPtr<nsIPresentationDevicePrompt> prompt =
      do_GetService(PRESENTATION_DEVICE_PROMPT_CONTRACTID);
    if (NS_WARN_IF(!prompt)) {
      return aCallback->NotifyError(NS_ERROR_DOM_INVALID_ACCESS_ERR);
    }

    nsresult rv = prompt->PromptDeviceSelection(request);
    if (NS_WARN_IF(NS_FAILED(rv))) {
      return aCallback->NotifyError(NS_ERROR_DOM_OPERATION_ERR);
    }

    return NS_OK;
  }

  // Find the designated device from available device list.
  nsCOMPtr<nsIPresentationDeviceManager> deviceManager =
    do_GetService(PRESENTATION_DEVICE_MANAGER_CONTRACTID);
  if (NS_WARN_IF(!deviceManager)) {
    return aCallback->NotifyError(NS_ERROR_DOM_OPERATION_ERR);
  }

  nsCOMPtr<nsIArray> presentationUrls;
  if (NS_WARN_IF(NS_FAILED(
    ConvertURLArrayHelper(aUrls, getter_AddRefs(presentationUrls))))) {
    return aCallback->NotifyError(NS_ERROR_DOM_OPERATION_ERR);
  }

  nsCOMPtr<nsIArray> devices;
  nsresult rv = deviceManager->GetAvailableDevices(presentationUrls, getter_AddRefs(devices));
  if (NS_WARN_IF(NS_FAILED(rv))) {
    return aCallback->NotifyError(NS_ERROR_DOM_OPERATION_ERR);
  }

  nsCOMPtr<nsISimpleEnumerator> enumerator;
  rv = devices->Enumerate(getter_AddRefs(enumerator));
  if (NS_WARN_IF(NS_FAILED(rv))) {
    return aCallback->NotifyError(NS_ERROR_DOM_OPERATION_ERR);
  }

  NS_ConvertUTF16toUTF8 utf8DeviceId(aDeviceId);
  bool hasMore;
  while (NS_SUCCEEDED(enumerator->HasMoreElements(&hasMore)) && hasMore) {
    nsCOMPtr<nsISupports> isupports;
    rv = enumerator->GetNext(getter_AddRefs(isupports));

    nsCOMPtr<nsIPresentationDevice> device(do_QueryInterface(isupports));
    MOZ_ASSERT(device);

    nsAutoCString id;
    if (NS_SUCCEEDED(device->GetId(id)) && id.Equals(utf8DeviceId)) {
      request->Select(device);
      return NS_OK;
    }
  }

  // Reject if designated device is not available.
  return aCallback->NotifyError(NS_ERROR_DOM_NOT_FOUND_ERR);
}
예제 #27
0
void WebMBufferedParser::Append(const unsigned char* aBuffer, uint32_t aLength,
                                nsTArray<WebMTimeDataOffset>& aMapping,
                                ReentrantMonitor& aReentrantMonitor)
{
  static const uint32_t SEGMENT_ID = 0x18538067;
  static const uint32_t SEGINFO_ID = 0x1549a966;
  static const uint32_t CLUSTER_ID = 0x1f43b675;
  static const uint32_t TIMECODESCALE_ID = 0x2ad7b1;
  static const unsigned char TIMECODE_ID = 0xe7;
  static const unsigned char BLOCK_ID = 0xa1;
  static const unsigned char SIMPLEBLOCK_ID = 0xa3;
  static const uint32_t BLOCK_TIMECODE_LENGTH = 2;

  const unsigned char* p = aBuffer;

  // Parse each byte in aBuffer one-by-one, producing timecodes and updating
  // aMapping as we go.  Parser pauses at end of stream (which may be at any
  // point within the parse) and resumes parsing the next time Append is
  // called with new data.
  while (p < aBuffer + aLength) {
    switch (mState) {
    case READ_ELEMENT_ID:
      mVIntRaw = true;
      mState = READ_VINT;
      mNextState = READ_ELEMENT_SIZE;
      break;
    case READ_ELEMENT_SIZE:
      mVIntRaw = false;
      mElement.mID = mVInt;
      mState = READ_VINT;
      mNextState = PARSE_ELEMENT;
      break;
    case PARSE_ELEMENT:
      mElement.mSize = mVInt;
      switch (mElement.mID.mValue) {
      case SEGMENT_ID:
        mState = READ_ELEMENT_ID;
        break;
      case SEGINFO_ID:
        mGotTimecodeScale = true;
        mState = READ_ELEMENT_ID;
        break;
      case TIMECODE_ID:
        mVInt = VInt();
        mVIntLeft = mElement.mSize.mValue;
        mState = READ_VINT_REST;
        mNextState = READ_CLUSTER_TIMECODE;
        break;
      case TIMECODESCALE_ID:
        mVInt = VInt();
        mVIntLeft = mElement.mSize.mValue;
        mState = READ_VINT_REST;
        mNextState = READ_TIMECODESCALE;
        break;
      case CLUSTER_ID:
        mClusterOffset = mCurrentOffset + (p - aBuffer) -
                        (mElement.mID.mLength + mElement.mSize.mLength);
        mState = READ_ELEMENT_ID;
        break;
      case SIMPLEBLOCK_ID:
        /* FALLTHROUGH */
      case BLOCK_ID:
        mBlockSize = mElement.mSize.mValue;
        mBlockTimecode = 0;
        mBlockTimecodeLength = BLOCK_TIMECODE_LENGTH;
        mBlockOffset = mCurrentOffset + (p - aBuffer) -
                       (mElement.mID.mLength + mElement.mSize.mLength);
        mState = READ_VINT;
        mNextState = READ_BLOCK_TIMECODE;
        break;
      default:
        mSkipBytes = mElement.mSize.mValue;
        mState = SKIP_DATA;
        mNextState = READ_ELEMENT_ID;
        break;
      }
      break;
    case READ_VINT: {
      unsigned char c = *p++;
      uint32_t mask;
      mVInt.mLength = VIntLength(c, &mask);
      mVIntLeft = mVInt.mLength - 1;
      mVInt.mValue = mVIntRaw ? c : c & ~mask;
      mState = READ_VINT_REST;
      break;
    }
    case READ_VINT_REST:
      if (mVIntLeft) {
        mVInt.mValue <<= 8;
        mVInt.mValue |= *p++;
        mVIntLeft -= 1;
      } else {
        mState = mNextState;
      }
      break;
    case READ_TIMECODESCALE:
      MOZ_ASSERT(mGotTimecodeScale);
      mTimecodeScale = mVInt.mValue;
      mState = READ_ELEMENT_ID;
      break;
    case READ_CLUSTER_TIMECODE:
      mClusterTimecode = mVInt.mValue;
      mState = READ_ELEMENT_ID;
      break;
    case READ_BLOCK_TIMECODE:
      if (mBlockTimecodeLength) {
        mBlockTimecode <<= 8;
        mBlockTimecode |= *p++;
        mBlockTimecodeLength -= 1;
      } else {
        // It's possible we've parsed this data before, so avoid inserting
        // duplicate WebMTimeDataOffset entries.
        {
          ReentrantMonitorAutoEnter mon(aReentrantMonitor);
          int64_t endOffset = mBlockOffset + mBlockSize +
                              mElement.mID.mLength + mElement.mSize.mLength;
          uint32_t idx = aMapping.IndexOfFirstElementGt(endOffset);
          if (idx == 0 || aMapping[idx - 1] != endOffset) {
            // Don't insert invalid negative timecodes.
            if (mBlockTimecode >= 0 || mClusterTimecode >= uint16_t(abs(mBlockTimecode))) {
              MOZ_ASSERT(mGotTimecodeScale);
              uint64_t absTimecode = mClusterTimecode + mBlockTimecode;
              absTimecode *= mTimecodeScale;
              WebMTimeDataOffset entry(endOffset, absTimecode, mClusterOffset);
              aMapping.InsertElementAt(idx, entry);
            }
          }
        }

        // Skip rest of block header and the block's payload.
        mBlockSize -= mVInt.mLength;
        mBlockSize -= BLOCK_TIMECODE_LENGTH;
        mSkipBytes = uint32_t(mBlockSize);
        mState = SKIP_DATA;
        mNextState = READ_ELEMENT_ID;
      }
      break;
    case SKIP_DATA:
      if (mSkipBytes) {
        uint32_t left = aLength - (p - aBuffer);
        left = std::min(left, mSkipBytes);
        p += left;
        mSkipBytes -= left;
      } else {
        mState = mNextState;
      }
      break;
    }
  }

  NS_ASSERTION(p == aBuffer + aLength, "Must have parsed to end of data.");
  mCurrentOffset += aLength;
}
예제 #28
0
nsresult
AppleATDecoder::GetInputAudioDescription(AudioStreamBasicDescription& aDesc,
                                         const nsTArray<uint8_t>& aExtraData)
{
  MOZ_ASSERT(mTaskQueue->IsCurrentThreadIn());

  // Request the properties from CoreAudio using the codec magic cookie
  AudioFormatInfo formatInfo;
  PodZero(&formatInfo.mASBD);
  formatInfo.mASBD.mFormatID = mFormatID;
  if (mFormatID == kAudioFormatMPEG4AAC) {
    formatInfo.mASBD.mFormatFlags = mConfig.mExtendedProfile;
  }
  formatInfo.mMagicCookieSize = aExtraData.Length();
  formatInfo.mMagicCookie = aExtraData.Elements();

  UInt32 formatListSize;
  // Attempt to retrieve the default format using
  // kAudioFormatProperty_FormatInfo method.
  // This method only retrieves the FramesPerPacket information required
  // by the decoder, which depends on the codec type and profile.
  aDesc.mFormatID = mFormatID;
  aDesc.mChannelsPerFrame = mConfig.mChannels;
  aDesc.mSampleRate = mConfig.mRate;
  UInt32 inputFormatSize = sizeof(aDesc);
  OSStatus rv = AudioFormatGetProperty(kAudioFormatProperty_FormatInfo,
                                       0,
                                       NULL,
                                       &inputFormatSize,
                                       &aDesc);
  if (NS_WARN_IF(rv)) {
    return NS_ERROR_FAILURE;
  }

  // If any of the methods below fail, we will return the default format as
  // created using kAudioFormatProperty_FormatInfo above.
  rv = AudioFormatGetPropertyInfo(kAudioFormatProperty_FormatList,
                                  sizeof(formatInfo),
                                  &formatInfo,
                                  &formatListSize);
  if (rv || (formatListSize % sizeof(AudioFormatListItem))) {
    return NS_OK;
  }
  size_t listCount = formatListSize / sizeof(AudioFormatListItem);
  auto formatList = MakeUnique<AudioFormatListItem[]>(listCount);

  rv = AudioFormatGetProperty(kAudioFormatProperty_FormatList,
                              sizeof(formatInfo),
                              &formatInfo,
                              &formatListSize,
                              formatList.get());
  if (rv) {
    return NS_OK;
  }
  LOG("found %u available audio stream(s)",
      formatListSize / sizeof(AudioFormatListItem));
  // Get the index number of the first playable format.
  // This index number will be for the highest quality layer the platform
  // is capable of playing.
  UInt32 itemIndex;
  UInt32 indexSize = sizeof(itemIndex);
  rv = AudioFormatGetProperty(kAudioFormatProperty_FirstPlayableFormatFromList,
                              formatListSize,
                              formatList.get(),
                              &indexSize,
                              &itemIndex);
  if (rv) {
    return NS_OK;
  }

  aDesc = formatList[itemIndex].mASBD;

  return NS_OK;
}
예제 #29
0
static void ValidateTreePointers(nsTArray<nsRefPtr<Layer> >& aLayers) {
  for (uint32_t i = 0; i < aLayers.Length(); i++) {
    ValidateTreePointers(aLayers[i]);
  }
}
/*
 * RemoteDevicePropertiesChangeCallback will be called, as the
 * following conditions:
 * 1. When BT is turning on, bluedroid automatically execute this callback
 * 2. When get_remote_device_properties()
 */
static void
RemoteDevicePropertiesChangeCallback(bt_status_t aStatus,
                                     bt_bdaddr_t *aBdAddress,
                                     int aNumProperties,
                                     bt_property_t *aProperties)
{
  MOZ_ASSERT(!NS_IsMainThread());

  if (sRequestedDeviceCountArray.IsEmpty()) {
    MOZ_ASSERT(sGetDeviceRunnableArray.IsEmpty());
    return;
  }

  sRequestedDeviceCountArray[0]--;

  InfallibleTArray<BluetoothNamedValue> props;

  nsString remoteDeviceBdAddress;
  BdAddressTypeToString(aBdAddress, remoteDeviceBdAddress);
  props.AppendElement(
    BluetoothNamedValue(NS_LITERAL_STRING("Address"), remoteDeviceBdAddress));

  for (int i = 0; i < aNumProperties; ++i) {
    bt_property_t p = aProperties[i];

    if (p.type == BT_PROPERTY_BDNAME) {
      BluetoothValue propertyValue = NS_ConvertUTF8toUTF16((char*)p.val);
      props.AppendElement(
        BluetoothNamedValue(NS_LITERAL_STRING("Name"), propertyValue));
    } else if (p.type == BT_PROPERTY_CLASS_OF_DEVICE) {
      uint32_t cod = *(uint32_t*)p.val;
      props.AppendElement(
        BluetoothNamedValue(NS_LITERAL_STRING("Class"), BluetoothValue(cod)));

      nsString icon;
      ClassToIcon(cod, icon);
      props.AppendElement(
        BluetoothNamedValue(NS_LITERAL_STRING("Icon"), BluetoothValue(icon)));
    } else {
      BT_LOGD("Other non-handled device properties. Type: %d", p.type);
    }
  }

  // Use address as the index
  sRemoteDevicesPack.AppendElement(
    BluetoothNamedValue(remoteDeviceBdAddress, props));

  if (sRequestedDeviceCountArray[0] == 0) {
    MOZ_ASSERT(!sGetDeviceRunnableArray.IsEmpty());

    if (sGetDeviceRunnableArray.IsEmpty()) {
      BT_LOGR("No runnable to return");
      return;
    }

    DispatchBluetoothReply(sGetDeviceRunnableArray[0],
                           sRemoteDevicesPack, EmptyString());

    // After firing it, clean up cache
    sRemoteDevicesPack.Clear();

    sRequestedDeviceCountArray.RemoveElementAt(0);
    sGetDeviceRunnableArray.RemoveElementAt(0);
  }
}