diff options
author | Daniel Baumann <daniel.baumann@progress-linux.org> | 2024-04-28 14:29:10 +0000 |
---|---|---|
committer | Daniel Baumann <daniel.baumann@progress-linux.org> | 2024-04-28 14:29:10 +0000 |
commit | 2aa4a82499d4becd2284cdb482213d541b8804dd (patch) | |
tree | b80bf8bf13c3766139fbacc530efd0dd9d54394c /accessible/generic | |
parent | Initial commit. (diff) | |
download | firefox-upstream.tar.xz firefox-upstream.zip |
Adding upstream version 86.0.1.upstream/86.0.1upstream
Signed-off-by: Daniel Baumann <daniel.baumann@progress-linux.org>
Diffstat (limited to '')
31 files changed, 14815 insertions, 0 deletions
diff --git a/accessible/generic/ARIAGridAccessible-inl.h b/accessible/generic/ARIAGridAccessible-inl.h new file mode 100644 index 0000000000..5ed73c2c5c --- /dev/null +++ b/accessible/generic/ARIAGridAccessible-inl.h @@ -0,0 +1,35 @@ +/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* vim: set ts=2 et sw=2 tw=80: */ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +#ifndef mozilla_a11y_ARIAGridAccessible_inl_h__ +#define mozilla_a11y_ARIAGridAccessible_inl_h__ + +#include "ARIAGridAccessible.h" + +#include "AccIterator.h" +#include "nsAccUtils.h" + +namespace mozilla { +namespace a11y { + +inline int32_t ARIAGridCellAccessible::RowIndexFor(Accessible* aRow) const { + Accessible* table = nsAccUtils::TableFor(aRow); + if (table) { + int32_t rowIdx = 0; + Accessible* row = nullptr; + AccIterator rowIter(table, filters::GetRow); + while ((row = rowIter.Next()) && row != aRow) rowIdx++; + + if (row) return rowIdx; + } + + return -1; +} + +} // namespace a11y +} // namespace mozilla + +#endif diff --git a/accessible/generic/ARIAGridAccessible.cpp b/accessible/generic/ARIAGridAccessible.cpp new file mode 100644 index 0000000000..ceab82a19b --- /dev/null +++ b/accessible/generic/ARIAGridAccessible.cpp @@ -0,0 +1,627 @@ +/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +#include "ARIAGridAccessible-inl.h" + +#include "Accessible-inl.h" +#include "AccIterator.h" +#include "nsAccUtils.h" +#include "Role.h" +#include "States.h" + +#include "mozilla/dom/Element.h" +#include "nsIPersistentProperties2.h" +#include "nsComponentManagerUtils.h" + +using namespace mozilla; +using namespace mozilla::a11y; + +//////////////////////////////////////////////////////////////////////////////// +// ARIAGridAccessible +//////////////////////////////////////////////////////////////////////////////// + +//////////////////////////////////////////////////////////////////////////////// +// Constructor + +ARIAGridAccessible::ARIAGridAccessible(nsIContent* aContent, + DocAccessible* aDoc) + : HyperTextAccessibleWrap(aContent, aDoc) { + mGenericTypes |= eTable; +} + +role ARIAGridAccessible::NativeRole() const { + a11y::role r = GetAccService()->MarkupRole(mContent); + return r != roles::NOTHING ? r : roles::TABLE; +} + +already_AddRefed<nsIPersistentProperties> +ARIAGridAccessible::NativeAttributes() { + nsCOMPtr<nsIPersistentProperties> attributes = + AccessibleWrap::NativeAttributes(); + + if (IsProbablyLayoutTable()) { + nsAutoString unused; + attributes->SetStringProperty("layout-guess"_ns, u"true"_ns, unused); + } + + return attributes.forget(); +} + +//////////////////////////////////////////////////////////////////////////////// +// Table + +uint32_t ARIAGridAccessible::ColCount() const { + AccIterator rowIter(this, filters::GetRow); + Accessible* row = rowIter.Next(); + if (!row) return 0; + + AccIterator cellIter(row, filters::GetCell); + Accessible* cell = nullptr; + + uint32_t colCount = 0; + while ((cell = cellIter.Next())) { + MOZ_ASSERT(cell->IsTableCell(), "No table or grid cell!"); + colCount += cell->AsTableCell()->ColExtent(); + } + + return colCount; +} + +uint32_t ARIAGridAccessible::RowCount() { + uint32_t rowCount = 0; + AccIterator rowIter(this, filters::GetRow); + while (rowIter.Next()) rowCount++; + + return rowCount; +} + +Accessible* ARIAGridAccessible::CellAt(uint32_t aRowIndex, + uint32_t aColumnIndex) { + Accessible* row = RowAt(aRowIndex); + if (!row) return nullptr; + + return CellInRowAt(row, aColumnIndex); +} + +bool ARIAGridAccessible::IsColSelected(uint32_t aColIdx) { + if (IsARIARole(nsGkAtoms::table)) return false; + + AccIterator rowIter(this, filters::GetRow); + Accessible* row = rowIter.Next(); + if (!row) return false; + + do { + if (!nsAccUtils::IsARIASelected(row)) { + Accessible* cell = CellInRowAt(row, aColIdx); + if (!cell || !nsAccUtils::IsARIASelected(cell)) return false; + } + } while ((row = rowIter.Next())); + + return true; +} + +bool ARIAGridAccessible::IsRowSelected(uint32_t aRowIdx) { + if (IsARIARole(nsGkAtoms::table)) return false; + + Accessible* row = RowAt(aRowIdx); + if (!row) return false; + + if (!nsAccUtils::IsARIASelected(row)) { + AccIterator cellIter(row, filters::GetCell); + Accessible* cell = nullptr; + while ((cell = cellIter.Next())) { + if (!nsAccUtils::IsARIASelected(cell)) return false; + } + } + + return true; +} + +bool ARIAGridAccessible::IsCellSelected(uint32_t aRowIdx, uint32_t aColIdx) { + if (IsARIARole(nsGkAtoms::table)) return false; + + Accessible* row = RowAt(aRowIdx); + if (!row) return false; + + if (!nsAccUtils::IsARIASelected(row)) { + Accessible* cell = CellInRowAt(row, aColIdx); + if (!cell || !nsAccUtils::IsARIASelected(cell)) return false; + } + + return true; +} + +uint32_t ARIAGridAccessible::SelectedCellCount() { + if (IsARIARole(nsGkAtoms::table)) return 0; + + uint32_t count = 0, colCount = ColCount(); + + AccIterator rowIter(this, filters::GetRow); + Accessible* row = nullptr; + + while ((row = rowIter.Next())) { + if (nsAccUtils::IsARIASelected(row)) { + count += colCount; + continue; + } + + AccIterator cellIter(row, filters::GetCell); + Accessible* cell = nullptr; + + while ((cell = cellIter.Next())) { + if (nsAccUtils::IsARIASelected(cell)) count++; + } + } + + return count; +} + +uint32_t ARIAGridAccessible::SelectedColCount() { + if (IsARIARole(nsGkAtoms::table)) return 0; + + uint32_t colCount = ColCount(); + if (!colCount) return 0; + + AccIterator rowIter(this, filters::GetRow); + Accessible* row = rowIter.Next(); + if (!row) return 0; + + nsTArray<bool> isColSelArray(colCount); + isColSelArray.AppendElements(colCount); + memset(isColSelArray.Elements(), true, colCount * sizeof(bool)); + + uint32_t selColCount = colCount; + do { + if (nsAccUtils::IsARIASelected(row)) continue; + + AccIterator cellIter(row, filters::GetCell); + Accessible* cell = nullptr; + for (uint32_t colIdx = 0; (cell = cellIter.Next()) && colIdx < colCount; + colIdx++) + if (isColSelArray[colIdx] && !nsAccUtils::IsARIASelected(cell)) { + isColSelArray[colIdx] = false; + selColCount--; + } + } while ((row = rowIter.Next())); + + return selColCount; +} + +uint32_t ARIAGridAccessible::SelectedRowCount() { + if (IsARIARole(nsGkAtoms::table)) return 0; + + uint32_t count = 0; + + AccIterator rowIter(this, filters::GetRow); + Accessible* row = nullptr; + + while ((row = rowIter.Next())) { + if (nsAccUtils::IsARIASelected(row)) { + count++; + continue; + } + + AccIterator cellIter(row, filters::GetCell); + Accessible* cell = cellIter.Next(); + if (!cell) continue; + + bool isRowSelected = true; + do { + if (!nsAccUtils::IsARIASelected(cell)) { + isRowSelected = false; + break; + } + } while ((cell = cellIter.Next())); + + if (isRowSelected) count++; + } + + return count; +} + +void ARIAGridAccessible::SelectedCells(nsTArray<Accessible*>* aCells) { + if (IsARIARole(nsGkAtoms::table)) return; + + AccIterator rowIter(this, filters::GetRow); + + Accessible* row = nullptr; + while ((row = rowIter.Next())) { + AccIterator cellIter(row, filters::GetCell); + Accessible* cell = nullptr; + + if (nsAccUtils::IsARIASelected(row)) { + while ((cell = cellIter.Next())) aCells->AppendElement(cell); + + continue; + } + + while ((cell = cellIter.Next())) { + if (nsAccUtils::IsARIASelected(cell)) aCells->AppendElement(cell); + } + } +} + +void ARIAGridAccessible::SelectedCellIndices(nsTArray<uint32_t>* aCells) { + if (IsARIARole(nsGkAtoms::table)) return; + + uint32_t colCount = ColCount(); + + AccIterator rowIter(this, filters::GetRow); + Accessible* row = nullptr; + for (uint32_t rowIdx = 0; (row = rowIter.Next()); rowIdx++) { + if (nsAccUtils::IsARIASelected(row)) { + for (uint32_t colIdx = 0; colIdx < colCount; colIdx++) + aCells->AppendElement(rowIdx * colCount + colIdx); + + continue; + } + + AccIterator cellIter(row, filters::GetCell); + Accessible* cell = nullptr; + for (uint32_t colIdx = 0; (cell = cellIter.Next()); colIdx++) { + if (nsAccUtils::IsARIASelected(cell)) + aCells->AppendElement(rowIdx * colCount + colIdx); + } + } +} + +void ARIAGridAccessible::SelectedColIndices(nsTArray<uint32_t>* aCols) { + if (IsARIARole(nsGkAtoms::table)) return; + + uint32_t colCount = ColCount(); + if (!colCount) return; + + AccIterator rowIter(this, filters::GetRow); + Accessible* row = rowIter.Next(); + if (!row) return; + + nsTArray<bool> isColSelArray(colCount); + isColSelArray.AppendElements(colCount); + memset(isColSelArray.Elements(), true, colCount * sizeof(bool)); + + do { + if (nsAccUtils::IsARIASelected(row)) continue; + + AccIterator cellIter(row, filters::GetCell); + Accessible* cell = nullptr; + for (uint32_t colIdx = 0; (cell = cellIter.Next()) && colIdx < colCount; + colIdx++) + if (isColSelArray[colIdx] && !nsAccUtils::IsARIASelected(cell)) { + isColSelArray[colIdx] = false; + } + } while ((row = rowIter.Next())); + + for (uint32_t colIdx = 0; colIdx < colCount; colIdx++) + if (isColSelArray[colIdx]) aCols->AppendElement(colIdx); +} + +void ARIAGridAccessible::SelectedRowIndices(nsTArray<uint32_t>* aRows) { + if (IsARIARole(nsGkAtoms::table)) return; + + AccIterator rowIter(this, filters::GetRow); + Accessible* row = nullptr; + for (uint32_t rowIdx = 0; (row = rowIter.Next()); rowIdx++) { + if (nsAccUtils::IsARIASelected(row)) { + aRows->AppendElement(rowIdx); + continue; + } + + AccIterator cellIter(row, filters::GetCell); + Accessible* cell = cellIter.Next(); + if (!cell) continue; + + bool isRowSelected = true; + do { + if (!nsAccUtils::IsARIASelected(cell)) { + isRowSelected = false; + break; + } + } while ((cell = cellIter.Next())); + + if (isRowSelected) aRows->AppendElement(rowIdx); + } +} + +void ARIAGridAccessible::SelectRow(uint32_t aRowIdx) { + if (IsARIARole(nsGkAtoms::table)) return; + + AccIterator rowIter(this, filters::GetRow); + + Accessible* row = nullptr; + for (uint32_t rowIdx = 0; (row = rowIter.Next()); rowIdx++) { + DebugOnly<nsresult> rv = SetARIASelected(row, rowIdx == aRowIdx); + NS_ASSERTION(NS_SUCCEEDED(rv), "SetARIASelected() Shouldn't fail!"); + } +} + +void ARIAGridAccessible::SelectCol(uint32_t aColIdx) { + if (IsARIARole(nsGkAtoms::table)) return; + + AccIterator rowIter(this, filters::GetRow); + + Accessible* row = nullptr; + while ((row = rowIter.Next())) { + // Unselect all cells in the row. + DebugOnly<nsresult> rv = SetARIASelected(row, false); + NS_ASSERTION(NS_SUCCEEDED(rv), "SetARIASelected() Shouldn't fail!"); + + // Select cell at the column index. + Accessible* cell = CellInRowAt(row, aColIdx); + if (cell) SetARIASelected(cell, true); + } +} + +void ARIAGridAccessible::UnselectRow(uint32_t aRowIdx) { + if (IsARIARole(nsGkAtoms::table)) return; + + Accessible* row = RowAt(aRowIdx); + if (row) SetARIASelected(row, false); +} + +void ARIAGridAccessible::UnselectCol(uint32_t aColIdx) { + if (IsARIARole(nsGkAtoms::table)) return; + + AccIterator rowIter(this, filters::GetRow); + + Accessible* row = nullptr; + while ((row = rowIter.Next())) { + Accessible* cell = CellInRowAt(row, aColIdx); + if (cell) SetARIASelected(cell, false); + } +} + +//////////////////////////////////////////////////////////////////////////////// +// Protected + +nsresult ARIAGridAccessible::SetARIASelected(Accessible* aAccessible, + bool aIsSelected, bool aNotify) { + if (IsARIARole(nsGkAtoms::table)) return NS_OK; + + nsIContent* content = aAccessible->GetContent(); + NS_ENSURE_STATE(content); + + nsresult rv = NS_OK; + if (content->IsElement()) { + if (aIsSelected) + rv = content->AsElement()->SetAttr( + kNameSpaceID_None, nsGkAtoms::aria_selected, u"true"_ns, aNotify); + else + rv = content->AsElement()->SetAttr( + kNameSpaceID_None, nsGkAtoms::aria_selected, u"false"_ns, aNotify); + } + + NS_ENSURE_SUCCESS(rv, rv); + + // No "smart" select/unselect for internal call. + if (!aNotify) return NS_OK; + + // If row or cell accessible was selected then we're able to not bother about + // selection of its cells or its row because our algorithm is row oriented, + // i.e. we check selection on row firstly and then on cells. + if (aIsSelected) return NS_OK; + + roles::Role role = aAccessible->Role(); + + // If the given accessible is row that was unselected then remove + // aria-selected from cell accessible. + if (role == roles::ROW) { + AccIterator cellIter(aAccessible, filters::GetCell); + Accessible* cell = nullptr; + + while ((cell = cellIter.Next())) { + rv = SetARIASelected(cell, false, false); + NS_ENSURE_SUCCESS(rv, rv); + } + return NS_OK; + } + + // If the given accessible is cell that was unselected and its row is selected + // then remove aria-selected from row and put aria-selected on + // siblings cells. + if (role == roles::GRID_CELL || role == roles::ROWHEADER || + role == roles::COLUMNHEADER) { + Accessible* row = aAccessible->Parent(); + + if (row && row->Role() == roles::ROW && nsAccUtils::IsARIASelected(row)) { + rv = SetARIASelected(row, false, false); + NS_ENSURE_SUCCESS(rv, rv); + + AccIterator cellIter(row, filters::GetCell); + Accessible* cell = nullptr; + while ((cell = cellIter.Next())) { + if (cell != aAccessible) { + rv = SetARIASelected(cell, true, false); + NS_ENSURE_SUCCESS(rv, rv); + } + } + } + } + + return NS_OK; +} + +//////////////////////////////////////////////////////////////////////////////// +// ARIARowAccessible +//////////////////////////////////////////////////////////////////////////////// + +ARIARowAccessible::ARIARowAccessible(nsIContent* aContent, DocAccessible* aDoc) + : HyperTextAccessibleWrap(aContent, aDoc) { + mGenericTypes |= eTableRow; +} + +role ARIARowAccessible::NativeRole() const { + a11y::role r = GetAccService()->MarkupRole(mContent); + return r != roles::NOTHING ? r : roles::ROW; +} + +GroupPos ARIARowAccessible::GroupPosition() { + int32_t count = 0, index = 0; + Accessible* table = nsAccUtils::TableFor(this); + if (table) { + if (nsCoreUtils::GetUIntAttr(table->GetContent(), nsGkAtoms::aria_rowcount, + &count) && + nsCoreUtils::GetUIntAttr(mContent, nsGkAtoms::aria_rowindex, &index)) { + return GroupPos(0, index, count); + } + + // Deal with the special case here that tables and grids can have rows + // which are wrapped in generic text container elements. Exclude tree grids + // because these are dealt with elsewhere. + if (table->Role() == roles::TABLE) { + Accessible* row = nullptr; + AccIterator rowIter(table, filters::GetRow); + while ((row = rowIter.Next())) { + index++; + if (row == this) { + break; + } + } + + if (row) { + count = table->AsTable()->RowCount(); + return GroupPos(0, index, count); + } + } + } + + return AccessibleWrap::GroupPosition(); +} + +// Accessible protected +ENameValueFlag ARIARowAccessible::NativeName(nsString& aName) const { + // We want to calculate the name from content only if an ARIA role is + // present. ARIARowAccessible might also be used by tables with + // display:block; styling, in which case we do not want the name from + // content. + if (HasStrongARIARole()) { + return AccessibleWrap::NativeName(aName); + } + + return eNameOK; +} + +//////////////////////////////////////////////////////////////////////////////// +// ARIAGridCellAccessible +//////////////////////////////////////////////////////////////////////////////// + +//////////////////////////////////////////////////////////////////////////////// +// Constructor + +ARIAGridCellAccessible::ARIAGridCellAccessible(nsIContent* aContent, + DocAccessible* aDoc) + : HyperTextAccessibleWrap(aContent, aDoc) { + mGenericTypes |= eTableCell; +} + +role ARIAGridCellAccessible::NativeRole() const { + a11y::role r = GetAccService()->MarkupRole(mContent); + return r != roles::NOTHING ? r : roles::CELL; +} + +//////////////////////////////////////////////////////////////////////////////// +// TableCell + +TableAccessible* ARIAGridCellAccessible::Table() const { + Accessible* table = nsAccUtils::TableFor(Row()); + return table ? table->AsTable() : nullptr; +} + +uint32_t ARIAGridCellAccessible::ColIdx() const { + Accessible* row = Row(); + if (!row) return 0; + + int32_t indexInRow = IndexInParent(); + uint32_t colIdx = 0; + for (int32_t idx = 0; idx < indexInRow; idx++) { + Accessible* cell = row->GetChildAt(idx); + if (cell->IsTableCell()) { + colIdx += cell->AsTableCell()->ColExtent(); + } + } + + return colIdx; +} + +uint32_t ARIAGridCellAccessible::RowIdx() const { return RowIndexFor(Row()); } + +bool ARIAGridCellAccessible::Selected() { + Accessible* row = Row(); + if (!row) return false; + + return nsAccUtils::IsARIASelected(row) || nsAccUtils::IsARIASelected(this); +} + +//////////////////////////////////////////////////////////////////////////////// +// Accessible + +void ARIAGridCellAccessible::ApplyARIAState(uint64_t* aState) const { + HyperTextAccessibleWrap::ApplyARIAState(aState); + + // Return if the gridcell has aria-selected="true". + if (*aState & states::SELECTED) return; + + // Check aria-selected="true" on the row. + Accessible* row = Parent(); + if (!row || row->Role() != roles::ROW) return; + + nsIContent* rowContent = row->GetContent(); + if (nsAccUtils::HasDefinedARIAToken(rowContent, nsGkAtoms::aria_selected) && + !rowContent->AsElement()->AttrValueIs(kNameSpaceID_None, + nsGkAtoms::aria_selected, + nsGkAtoms::_false, eCaseMatters)) + *aState |= states::SELECTABLE | states::SELECTED; +} + +already_AddRefed<nsIPersistentProperties> +ARIAGridCellAccessible::NativeAttributes() { + nsCOMPtr<nsIPersistentProperties> attributes = + HyperTextAccessibleWrap::NativeAttributes(); + + // Expose "table-cell-index" attribute. + Accessible* thisRow = Row(); + if (!thisRow) return attributes.forget(); + + int32_t rowIdx = RowIndexFor(thisRow); + if (rowIdx == -1) { // error + return attributes.forget(); + } + + int32_t colIdx = 0, colCount = 0; + uint32_t childCount = thisRow->ChildCount(); + for (uint32_t childIdx = 0; childIdx < childCount; childIdx++) { + Accessible* child = thisRow->GetChildAt(childIdx); + if (child == this) colIdx = colCount; + + roles::Role role = child->Role(); + if (role == roles::CELL || role == roles::GRID_CELL || + role == roles::ROWHEADER || role == roles::COLUMNHEADER) + colCount++; + } + + nsAutoString stringIdx; + stringIdx.AppendInt(rowIdx * colCount + colIdx); + nsAccUtils::SetAccAttr(attributes, nsGkAtoms::tableCellIndex, stringIdx); + +#ifdef DEBUG + nsAutoString unused; + attributes->SetStringProperty("cppclass"_ns, u"ARIAGridCellAccessible"_ns, + unused); +#endif + + return attributes.forget(); +} + +GroupPos ARIAGridCellAccessible::GroupPosition() { + int32_t count = 0, index = 0; + TableAccessible* table = Table(); + if (table && + nsCoreUtils::GetUIntAttr(table->AsAccessible()->GetContent(), + nsGkAtoms::aria_colcount, &count) && + nsCoreUtils::GetUIntAttr(mContent, nsGkAtoms::aria_colindex, &index)) { + return GroupPos(0, index, count); + } + + return GroupPos(); +} diff --git a/accessible/generic/ARIAGridAccessible.h b/accessible/generic/ARIAGridAccessible.h new file mode 100644 index 0000000000..054efcc916 --- /dev/null +++ b/accessible/generic/ARIAGridAccessible.h @@ -0,0 +1,134 @@ +/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +#ifndef MOZILLA_A11Y_ARIAGridAccessible_h_ +#define MOZILLA_A11Y_ARIAGridAccessible_h_ + +#include "HyperTextAccessibleWrap.h" +#include "TableAccessible.h" +#include "TableCellAccessible.h" + +namespace mozilla { +namespace a11y { + +/** + * Accessible for ARIA grid and treegrid. + */ +class ARIAGridAccessible : public HyperTextAccessibleWrap, + public TableAccessible { + public: + ARIAGridAccessible(nsIContent* aContent, DocAccessible* aDoc); + + NS_INLINE_DECL_REFCOUNTING_INHERITED(ARIAGridAccessible, + HyperTextAccessibleWrap) + + // Accessible + virtual a11y::role NativeRole() const override; + virtual already_AddRefed<nsIPersistentProperties> NativeAttributes() override; + virtual TableAccessible* AsTable() override { return this; } + + // TableAccessible + virtual uint32_t ColCount() const override; + virtual uint32_t RowCount() override; + virtual Accessible* CellAt(uint32_t aRowIndex, + uint32_t aColumnIndex) override; + virtual bool IsColSelected(uint32_t aColIdx) override; + virtual bool IsRowSelected(uint32_t aRowIdx) override; + virtual bool IsCellSelected(uint32_t aRowIdx, uint32_t aColIdx) override; + virtual uint32_t SelectedCellCount() override; + virtual uint32_t SelectedColCount() override; + virtual uint32_t SelectedRowCount() override; + virtual void SelectedCells(nsTArray<Accessible*>* aCells) override; + virtual void SelectedCellIndices(nsTArray<uint32_t>* aCells) override; + virtual void SelectedColIndices(nsTArray<uint32_t>* aCols) override; + virtual void SelectedRowIndices(nsTArray<uint32_t>* aRows) override; + virtual void SelectCol(uint32_t aColIdx) override; + virtual void SelectRow(uint32_t aRowIdx) override; + virtual void UnselectCol(uint32_t aColIdx) override; + virtual void UnselectRow(uint32_t aRowIdx) override; + virtual Accessible* AsAccessible() override { return this; } + + protected: + virtual ~ARIAGridAccessible() {} + + /** + * Set aria-selected attribute value on DOM node of the given accessible. + * + * @param aAccessible [in] accessible + * @param aIsSelected [in] new value of aria-selected attribute + * @param aNotify [in, optional] specifies if DOM should be notified + * about attribute change (used internally). + */ + nsresult SetARIASelected(Accessible* aAccessible, bool aIsSelected, + bool aNotify = true); +}; + +/** + * Accessible for ARIA row. + */ +class ARIARowAccessible : public HyperTextAccessibleWrap { + public: + ARIARowAccessible(nsIContent* aContent, DocAccessible* aDoc); + + NS_INLINE_DECL_REFCOUNTING_INHERITED(ARIARowAccessible, + HyperTextAccessibleWrap) + + // Accessible + virtual a11y::role NativeRole() const override; + virtual mozilla::a11y::GroupPos GroupPosition() override; + + protected: + virtual ~ARIARowAccessible() {} + + // Accessible + virtual ENameValueFlag NativeName(nsString& aName) const override; +}; + +/** + * Accessible for ARIA gridcell and rowheader/columnheader. + */ +class ARIAGridCellAccessible : public HyperTextAccessibleWrap, + public TableCellAccessible { + public: + ARIAGridCellAccessible(nsIContent* aContent, DocAccessible* aDoc); + + NS_INLINE_DECL_REFCOUNTING_INHERITED(ARIAGridCellAccessible, + HyperTextAccessibleWrap) + + // Accessible + virtual a11y::role NativeRole() const override; + virtual TableCellAccessible* AsTableCell() override { return this; } + virtual void ApplyARIAState(uint64_t* aState) const override; + virtual already_AddRefed<nsIPersistentProperties> NativeAttributes() override; + virtual mozilla::a11y::GroupPos GroupPosition() override; + + protected: + virtual ~ARIAGridCellAccessible() {} + + /** + * Return a containing row. + */ + Accessible* Row() const { + Accessible* row = Parent(); + return row && row->IsTableRow() ? row : nullptr; + } + + /** + * Return index of the given row. + * Returns -1 upon error. + */ + int32_t RowIndexFor(Accessible* aRow) const; + + // TableCellAccessible + virtual TableAccessible* Table() const override; + virtual uint32_t ColIdx() const override; + virtual uint32_t RowIdx() const override; + virtual bool Selected() override; +}; + +} // namespace a11y +} // namespace mozilla + +#endif diff --git a/accessible/generic/Accessible-inl.h b/accessible/generic/Accessible-inl.h new file mode 100644 index 0000000000..d0f98061ce --- /dev/null +++ b/accessible/generic/Accessible-inl.h @@ -0,0 +1,134 @@ +/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* vim: set ts=2 et sw=2 tw=80: */ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this file, + * You can obtain one at http://mozilla.org/MPL/2.0/. */ + +#ifndef mozilla_a11y_Accessible_inl_h_ +#define mozilla_a11y_Accessible_inl_h_ + +#include "DocAccessible.h" +#include "ARIAMap.h" +#include "nsCoreUtils.h" +#include "mozilla/dom/Element.h" +#include "mozilla/PresShell.h" + +#ifdef A11Y_LOG +# include "Logging.h" +#endif + +namespace mozilla { +namespace a11y { + +inline mozilla::a11y::role Accessible::Role() const { + const nsRoleMapEntry* roleMapEntry = ARIARoleMap(); + if (!roleMapEntry || roleMapEntry->roleRule != kUseMapRole) + return ARIATransformRole(NativeRole()); + + return ARIATransformRole(roleMapEntry->role); +} + +inline bool Accessible::HasARIARole() const { + return mRoleMapEntryIndex != aria::NO_ROLE_MAP_ENTRY_INDEX; +} + +inline bool Accessible::IsARIARole(nsAtom* aARIARole) const { + const nsRoleMapEntry* roleMapEntry = ARIARoleMap(); + return roleMapEntry && roleMapEntry->Is(aARIARole); +} + +inline bool Accessible::HasStrongARIARole() const { + const nsRoleMapEntry* roleMapEntry = ARIARoleMap(); + return roleMapEntry && roleMapEntry->roleRule == kUseMapRole; +} + +inline const nsRoleMapEntry* Accessible::ARIARoleMap() const { + return aria::GetRoleMapFromIndex(mRoleMapEntryIndex); +} + +inline mozilla::a11y::role Accessible::ARIARole() { + const nsRoleMapEntry* roleMapEntry = ARIARoleMap(); + if (!roleMapEntry || roleMapEntry->roleRule != kUseMapRole) + return mozilla::a11y::roles::NOTHING; + + return ARIATransformRole(roleMapEntry->role); +} + +inline void Accessible::SetRoleMapEntry(const nsRoleMapEntry* aRoleMapEntry) { + mRoleMapEntryIndex = aria::GetIndexFromRoleMap(aRoleMapEntry); +} + +inline bool Accessible::IsSearchbox() const { + const nsRoleMapEntry* roleMapEntry = ARIARoleMap(); + return (roleMapEntry && roleMapEntry->Is(nsGkAtoms::searchbox)) || + (mContent->IsHTMLElement(nsGkAtoms::input) && + mContent->AsElement()->AttrValueIs(kNameSpaceID_None, nsGkAtoms::type, + nsGkAtoms::search, eCaseMatters)); +} + +inline bool Accessible::HasGenericType(AccGenericType aType) const { + const nsRoleMapEntry* roleMapEntry = ARIARoleMap(); + return (mGenericTypes & aType) || + (roleMapEntry && roleMapEntry->IsOfType(aType)); +} + +inline bool Accessible::NativeHasNumericValue() const { + return mStateFlags & eHasNumericValue; +} + +inline bool Accessible::ARIAHasNumericValue() const { + const nsRoleMapEntry* roleMapEntry = ARIARoleMap(); + if (!roleMapEntry || roleMapEntry->valueRule == eNoValue) return false; + + if (roleMapEntry->valueRule == eHasValueMinMaxIfFocusable) + return InteractiveState() & states::FOCUSABLE; + + return true; +} + +inline bool Accessible::HasNumericValue() const { + return NativeHasNumericValue() || ARIAHasNumericValue(); +} + +inline bool Accessible::IsDefunct() const { + MOZ_ASSERT(mStateFlags & eIsDefunct || IsApplication() || IsDoc() || + mStateFlags & eSharedNode || mContent, + "No content"); + return mStateFlags & eIsDefunct; +} + +inline void Accessible::ScrollTo(uint32_t aHow) const { + if (mContent) { + RefPtr<PresShell> presShell = mDoc->PresShellPtr(); + nsCOMPtr<nsIContent> content = mContent; + nsCoreUtils::ScrollTo(presShell, content, aHow); + } +} + +inline bool Accessible::InsertAfter(Accessible* aNewChild, + Accessible* aRefChild) { + MOZ_ASSERT(aNewChild, "No new child to insert"); + + if (aRefChild && aRefChild->Parent() != this) { +#ifdef A11Y_LOG + logging::TreeInfo("broken accessible tree", 0, "parent", this, + "prev sibling parent", aRefChild->Parent(), "child", + aNewChild, nullptr); + if (logging::IsEnabled(logging::eVerbose)) { + logging::Tree("TREE", "Document tree", mDoc); + logging::DOMTree("TREE", "DOM document tree", mDoc); + } +#endif + MOZ_ASSERT_UNREACHABLE("Broken accessible tree"); + mDoc->UnbindFromDocument(aNewChild); + return false; + } + + return InsertChildAt(aRefChild ? aRefChild->IndexInParent() + 1 : 0, + aNewChild); +} + +} // namespace a11y +} // namespace mozilla + +#endif diff --git a/accessible/generic/Accessible.cpp b/accessible/generic/Accessible.cpp new file mode 100644 index 0000000000..a6631766d0 --- /dev/null +++ b/accessible/generic/Accessible.cpp @@ -0,0 +1,2813 @@ +/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +#include "Accessible-inl.h" + +#include "EmbeddedObjCollector.h" +#include "AccGroupInfo.h" +#include "AccIterator.h" +#include "nsAccUtils.h" +#include "nsAccessibilityService.h" +#include "ApplicationAccessible.h" +#include "nsAccessiblePivot.h" +#include "nsGenericHTMLElement.h" +#include "NotificationController.h" +#include "nsEventShell.h" +#include "nsTextEquivUtils.h" +#include "DocAccessibleChild.h" +#include "EventTree.h" +#include "GeckoProfiler.h" +#include "Pivot.h" +#include "Relation.h" +#include "Role.h" +#include "RootAccessible.h" +#include "States.h" +#include "StyleInfo.h" +#include "TextRange.h" +#include "TableAccessible.h" +#include "TableCellAccessible.h" +#include "TreeWalker.h" + +#include "nsIDOMXULButtonElement.h" +#include "nsIDOMXULSelectCntrlEl.h" +#include "nsIDOMXULSelectCntrlItemEl.h" +#include "nsINodeList.h" +#include "nsPIDOMWindow.h" + +#include "mozilla/dom/Document.h" +#include "mozilla/dom/HTMLFormElement.h" +#include "nsIContent.h" +#include "nsIForm.h" +#include "nsIFormControl.h" + +#include "nsDeckFrame.h" +#include "nsLayoutUtils.h" +#include "nsIStringBundle.h" +#include "nsPresContext.h" +#include "nsIFrame.h" +#include "nsView.h" +#include "nsIDocShellTreeItem.h" +#include "nsIScrollableFrame.h" +#include "nsFocusManager.h" + +#include "nsString.h" +#include "nsUnicharUtils.h" +#include "nsReadableUtils.h" +#include "prdtoa.h" +#include "nsAtom.h" +#include "nsIURI.h" +#include "nsArrayUtils.h" +#include "nsWhitespaceTokenizer.h" +#include "nsAttrName.h" +#include "nsPersistentProperties.h" + +#include "mozilla/Assertions.h" +#include "mozilla/BasicEvents.h" +#include "mozilla/ErrorResult.h" +#include "mozilla/EventStates.h" +#include "mozilla/FloatingPoint.h" +#include "mozilla/MouseEvents.h" +#include "mozilla/PresShell.h" +#include "mozilla/Unused.h" +#include "mozilla/Preferences.h" +#include "mozilla/StaticPrefs_ui.h" +#include "mozilla/dom/CanvasRenderingContext2D.h" +#include "mozilla/dom/Element.h" +#include "mozilla/dom/HTMLCanvasElement.h" +#include "mozilla/dom/HTMLBodyElement.h" +#include "mozilla/dom/KeyboardEventBinding.h" +#include "mozilla/dom/TreeWalker.h" +#include "mozilla/dom/UserActivation.h" + +using namespace mozilla; +using namespace mozilla::a11y; + +//////////////////////////////////////////////////////////////////////////////// +// Accessible: nsISupports and cycle collection + +NS_IMPL_CYCLE_COLLECTION_CLASS(Accessible) +NS_IMPL_CYCLE_COLLECTION_UNLINK_BEGIN(Accessible) + tmp->Shutdown(); +NS_IMPL_CYCLE_COLLECTION_UNLINK_END +NS_IMPL_CYCLE_COLLECTION_TRAVERSE_BEGIN(Accessible) + NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mContent, mDoc) +NS_IMPL_CYCLE_COLLECTION_TRAVERSE_END + +NS_INTERFACE_MAP_BEGIN_CYCLE_COLLECTION(Accessible) + NS_INTERFACE_MAP_ENTRY_CONCRETE(Accessible) + NS_INTERFACE_MAP_ENTRY_AMBIGUOUS(nsISupports, Accessible) +NS_INTERFACE_MAP_END + +NS_IMPL_CYCLE_COLLECTING_ADDREF(Accessible) +NS_IMPL_CYCLE_COLLECTING_RELEASE_WITH_DESTROY(Accessible, LastRelease()) + +Accessible::Accessible(nsIContent* aContent, DocAccessible* aDoc) + : mContent(aContent), + mDoc(aDoc), + mParent(nullptr), + mIndexInParent(-1), + mRoleMapEntryIndex(aria::NO_ROLE_MAP_ENTRY_INDEX), + mStateFlags(0), + mContextFlags(0), + mType(0), + mGenericTypes(0), + mReorderEventTarget(false), + mShowEventTarget(false), + mHideEventTarget(false) { + mBits.groupInfo = nullptr; + mInt.mIndexOfEmbeddedChild = -1; +} + +Accessible::~Accessible() { + NS_ASSERTION(!mDoc, "LastRelease was never called!?!"); +} + +ENameValueFlag Accessible::Name(nsString& aName) const { + aName.Truncate(); + + if (!HasOwnContent()) return eNameOK; + + ARIAName(aName); + if (!aName.IsEmpty()) return eNameOK; + + ENameValueFlag nameFlag = NativeName(aName); + if (!aName.IsEmpty()) return nameFlag; + + // In the end get the name from tooltip. + if (mContent->IsHTMLElement()) { + if (mContent->AsElement()->GetAttr(kNameSpaceID_None, nsGkAtoms::title, + aName)) { + aName.CompressWhitespace(); + return eNameFromTooltip; + } + } else if (mContent->IsXULElement()) { + if (mContent->AsElement()->GetAttr(kNameSpaceID_None, + nsGkAtoms::tooltiptext, aName)) { + aName.CompressWhitespace(); + return eNameFromTooltip; + } + } else if (mContent->IsSVGElement()) { + // If user agents need to choose among multiple 'desc' or 'title' + // elements for processing, the user agent shall choose the first one. + for (nsIContent* childElm = mContent->GetFirstChild(); childElm; + childElm = childElm->GetNextSibling()) { + if (childElm->IsSVGElement(nsGkAtoms::desc)) { + nsTextEquivUtils::AppendTextEquivFromContent(this, childElm, &aName); + return eNameFromTooltip; + } + } + } + + if (nameFlag != eNoNameOnPurpose) aName.SetIsVoid(true); + + return nameFlag; +} + +void Accessible::Description(nsString& aDescription) { + // There are 4 conditions that make an accessible have no accDescription: + // 1. it's a text node; or + // 2. It has no ARIA describedby or description property + // 3. it doesn't have an accName; or + // 4. its title attribute already equals to its accName nsAutoString name; + + if (!HasOwnContent() || mContent->IsText()) return; + + ARIADescription(aDescription); + + if (aDescription.IsEmpty()) { + NativeDescription(aDescription); + + if (aDescription.IsEmpty()) { + // Keep the Name() method logic. + if (mContent->IsHTMLElement()) { + mContent->AsElement()->GetAttr(kNameSpaceID_None, nsGkAtoms::title, + aDescription); + } else if (mContent->IsXULElement()) { + mContent->AsElement()->GetAttr(kNameSpaceID_None, + nsGkAtoms::tooltiptext, aDescription); + } else if (mContent->IsSVGElement()) { + for (nsIContent* childElm = mContent->GetFirstChild(); childElm; + childElm = childElm->GetNextSibling()) { + if (childElm->IsSVGElement(nsGkAtoms::desc)) { + nsTextEquivUtils::AppendTextEquivFromContent(this, childElm, + &aDescription); + break; + } + } + } + } + } + + if (!aDescription.IsEmpty()) { + aDescription.CompressWhitespace(); + nsAutoString name; + Name(name); + // Don't expose a description if it is the same as the name. + if (aDescription.Equals(name)) aDescription.Truncate(); + } +} + +KeyBinding Accessible::AccessKey() const { + if (!HasOwnContent()) return KeyBinding(); + + uint32_t key = nsCoreUtils::GetAccessKeyFor(mContent); + if (!key && mContent->IsElement()) { + Accessible* label = nullptr; + + // Copy access key from label node. + if (mContent->IsHTMLElement()) { + // Unless it is labeled via an ancestor <label>, in which case that would + // be redundant. + HTMLLabelIterator iter(Document(), this, + HTMLLabelIterator::eSkipAncestorLabel); + label = iter.Next(); + } + if (!label) { + XULLabelIterator iter(Document(), mContent); + label = iter.Next(); + } + + if (label) key = nsCoreUtils::GetAccessKeyFor(label->GetContent()); + } + + if (!key) return KeyBinding(); + + // Get modifier mask. Use ui.key.generalAccessKey (unless it is -1). + switch (StaticPrefs::ui_key_generalAccessKey()) { + case -1: + break; + case dom::KeyboardEvent_Binding::DOM_VK_SHIFT: + return KeyBinding(key, KeyBinding::kShift); + case dom::KeyboardEvent_Binding::DOM_VK_CONTROL: + return KeyBinding(key, KeyBinding::kControl); + case dom::KeyboardEvent_Binding::DOM_VK_ALT: + return KeyBinding(key, KeyBinding::kAlt); + case dom::KeyboardEvent_Binding::DOM_VK_META: + return KeyBinding(key, KeyBinding::kMeta); + default: + return KeyBinding(); + } + + // Determine the access modifier used in this context. + dom::Document* document = mContent->GetUncomposedDoc(); + if (!document) return KeyBinding(); + + nsCOMPtr<nsIDocShellTreeItem> treeItem(document->GetDocShell()); + if (!treeItem) return KeyBinding(); + + nsresult rv = NS_ERROR_FAILURE; + int32_t modifierMask = 0; + switch (treeItem->ItemType()) { + case nsIDocShellTreeItem::typeChrome: + modifierMask = StaticPrefs::ui_key_chromeAccess(); + rv = NS_OK; + break; + case nsIDocShellTreeItem::typeContent: + modifierMask = StaticPrefs::ui_key_contentAccess(); + rv = NS_OK; + break; + } + + return NS_SUCCEEDED(rv) ? KeyBinding(key, modifierMask) : KeyBinding(); +} + +KeyBinding Accessible::KeyboardShortcut() const { return KeyBinding(); } + +void Accessible::TranslateString(const nsString& aKey, nsAString& aStringOut) { + nsCOMPtr<nsIStringBundleService> stringBundleService = + services::GetStringBundleService(); + if (!stringBundleService) return; + + nsCOMPtr<nsIStringBundle> stringBundle; + stringBundleService->CreateBundle( + "chrome://global-platform/locale/accessible.properties", + getter_AddRefs(stringBundle)); + if (!stringBundle) return; + + nsAutoString xsValue; + nsresult rv = stringBundle->GetStringFromName( + NS_ConvertUTF16toUTF8(aKey).get(), xsValue); + if (NS_SUCCEEDED(rv)) aStringOut.Assign(xsValue); +} + +uint64_t Accessible::VisibilityState() const { + nsIFrame* frame = GetFrame(); + if (!frame) { + // Element having display:contents is considered visible semantically, + // despite it doesn't have a visually visible box. + if (nsCoreUtils::IsDisplayContents(mContent)) { + return states::OFFSCREEN; + } + return states::INVISIBLE; + } + + if (!frame->StyleVisibility()->IsVisible()) return states::INVISIBLE; + + // It's invisible if the presshell is hidden by a visibility:hidden element in + // an ancestor document. + if (frame->PresShell()->IsUnderHiddenEmbedderElement()) { + return states::INVISIBLE; + } + + // Offscreen state if the document's visibility state is not visible. + if (Document()->IsHidden()) return states::OFFSCREEN; + + // Walk the parent frame chain to see if the frame is in background tab or + // scrolled out. + nsIFrame* curFrame = frame; + do { + nsView* view = curFrame->GetView(); + if (view && view->GetVisibility() == nsViewVisibility_kHide) + return states::INVISIBLE; + + if (nsLayoutUtils::IsPopup(curFrame)) return 0; + + // Offscreen state for background tab content and invisible for not selected + // deck panel. + nsIFrame* parentFrame = curFrame->GetParent(); + nsDeckFrame* deckFrame = do_QueryFrame(parentFrame); + if (deckFrame && deckFrame->GetSelectedBox() != curFrame) { +#if defined(ANDROID) + // In Fennec instead of a <tabpanels> container there is a <deck> + // with direct <browser> children. + if (curFrame->GetContent()->IsXULElement(nsGkAtoms::browser)) + return states::OFFSCREEN; +#else + if (deckFrame->GetContent()->IsXULElement(nsGkAtoms::tabpanels)) + return states::OFFSCREEN; +#endif + + MOZ_ASSERT_UNREACHABLE( + "Children of not selected deck panel are not accessible."); + return states::INVISIBLE; + } + + // If contained by scrollable frame then check that at least 12 pixels + // around the object is visible, otherwise the object is offscreen. + nsIScrollableFrame* scrollableFrame = do_QueryFrame(parentFrame); + const nscoord kMinPixels = nsPresContext::CSSPixelsToAppUnits(12); + if (scrollableFrame) { + nsRect scrollPortRect = scrollableFrame->GetScrollPortRect(); + nsRect frameRect = nsLayoutUtils::TransformFrameRectToAncestor( + frame, frame->GetRectRelativeToSelf(), parentFrame); + if (!scrollPortRect.Contains(frameRect)) { + scrollPortRect.Deflate(kMinPixels, kMinPixels); + if (!scrollPortRect.Intersects(frameRect)) return states::OFFSCREEN; + } + } + + if (!parentFrame) { + parentFrame = nsLayoutUtils::GetCrossDocParentFrame(curFrame); + // Even if we couldn't find the parent frame, it might mean we are in an + // out-of-process iframe, try to see if |frame| is scrolled out in an + // scrollable frame in a cross-process ancestor document. + if (!parentFrame && + nsLayoutUtils::FrameIsMostlyScrolledOutOfViewInCrossProcess( + frame, kMinPixels)) { + return states::OFFSCREEN; + } + } + + curFrame = parentFrame; + } while (curFrame); + + // Zero area rects can occur in the first frame of a multi-frame text flow, + // in which case the rendered text is not empty and the frame should not be + // marked invisible. + // XXX Can we just remove this check? Why do we need to mark empty + // text invisible? + if (frame->IsTextFrame() && !(frame->GetStateBits() & NS_FRAME_OUT_OF_FLOW) && + frame->GetRect().IsEmpty()) { + nsIFrame::RenderedText text = frame->GetRenderedText( + 0, UINT32_MAX, nsIFrame::TextOffsetType::OffsetsInContentText, + nsIFrame::TrailingWhitespace::DontTrim); + if (text.mString.IsEmpty()) { + return states::INVISIBLE; + } + } + + return 0; +} + +uint64_t Accessible::NativeState() const { + uint64_t state = 0; + + if (!IsInDocument()) state |= states::STALE; + + if (HasOwnContent() && mContent->IsElement()) { + EventStates elementState = mContent->AsElement()->State(); + + if (elementState.HasState(NS_EVENT_STATE_INVALID)) state |= states::INVALID; + + if (elementState.HasState(NS_EVENT_STATE_REQUIRED)) + state |= states::REQUIRED; + + state |= NativeInteractiveState(); + if (FocusMgr()->IsFocused(this)) state |= states::FOCUSED; + } + + // Gather states::INVISIBLE and states::OFFSCREEN flags for this object. + state |= VisibilityState(); + + nsIFrame* frame = GetFrame(); + if (frame) { + if (frame->GetStateBits() & NS_FRAME_OUT_OF_FLOW) state |= states::FLOATING; + + // XXX we should look at layout for non XUL box frames, but need to decide + // how that interacts with ARIA. + if (HasOwnContent() && mContent->IsXULElement() && frame->IsXULBoxFrame()) { + const nsStyleXUL* xulStyle = frame->StyleXUL(); + if (xulStyle && frame->IsXULBoxFrame()) { + // In XUL all boxes are either vertical or horizontal + if (xulStyle->mBoxOrient == StyleBoxOrient::Vertical) + state |= states::VERTICAL; + else + state |= states::HORIZONTAL; + } + } + } + + // Check if a XUL element has the popup attribute (an attached popup menu). + if (HasOwnContent() && mContent->IsXULElement() && + mContent->AsElement()->HasAttr(kNameSpaceID_None, nsGkAtoms::popup)) + state |= states::HASPOPUP; + + // Bypass the link states specialization for non links. + const nsRoleMapEntry* roleMapEntry = ARIARoleMap(); + if (!roleMapEntry || roleMapEntry->roleRule == kUseNativeRole || + roleMapEntry->role == roles::LINK) + state |= NativeLinkState(); + + return state; +} + +uint64_t Accessible::NativeInteractiveState() const { + if (!mContent->IsElement()) return 0; + + if (NativelyUnavailable()) return states::UNAVAILABLE; + + nsIFrame* frame = GetFrame(); + if (frame && frame->IsFocusable()) return states::FOCUSABLE; + + return 0; +} + +uint64_t Accessible::NativeLinkState() const { return 0; } + +bool Accessible::NativelyUnavailable() const { + if (mContent->IsHTMLElement()) return mContent->AsElement()->IsDisabled(); + + return mContent->IsElement() && mContent->AsElement()->AttrValueIs( + kNameSpaceID_None, nsGkAtoms::disabled, + nsGkAtoms::_true, eCaseMatters); +} + +Accessible* Accessible::FocusedChild() { + Accessible* focus = FocusMgr()->FocusedAccessible(); + if (focus && (focus == this || focus->Parent() == this)) return focus; + + return nullptr; +} + +Accessible* Accessible::ChildAtPoint(int32_t aX, int32_t aY, + EWhichChildAtPoint aWhichChild) { + // If we can't find the point in a child, we will return the fallback answer: + // we return |this| if the point is within it, otherwise nullptr. + Accessible* fallbackAnswer = nullptr; + nsIntRect rect = Bounds(); + if (rect.Contains(aX, aY)) fallbackAnswer = this; + + if (nsAccUtils::MustPrune(this)) // Do not dig any further + return fallbackAnswer; + + // Search an accessible at the given point starting from accessible document + // because containing block (see CSS2) for out of flow element (for example, + // absolutely positioned element) may be different from its DOM parent and + // therefore accessible for containing block may be different from accessible + // for DOM parent but GetFrameForPoint() should be called for containing block + // to get an out of flow element. + DocAccessible* accDocument = Document(); + NS_ENSURE_TRUE(accDocument, nullptr); + + nsIFrame* rootFrame = accDocument->GetFrame(); + NS_ENSURE_TRUE(rootFrame, nullptr); + + nsIFrame* startFrame = rootFrame; + + // Check whether the point is at popup content. + nsIWidget* rootWidget = rootFrame->GetView()->GetNearestWidget(nullptr); + NS_ENSURE_TRUE(rootWidget, nullptr); + + LayoutDeviceIntRect rootRect = rootWidget->GetScreenBounds(); + + WidgetMouseEvent dummyEvent(true, eMouseMove, rootWidget, + WidgetMouseEvent::eSynthesized); + dummyEvent.mRefPoint = + LayoutDeviceIntPoint(aX - rootRect.X(), aY - rootRect.Y()); + + nsIFrame* popupFrame = nsLayoutUtils::GetPopupFrameForEventCoordinates( + accDocument->PresContext()->GetRootPresContext(), &dummyEvent); + if (popupFrame) { + // If 'this' accessible is not inside the popup then ignore the popup when + // searching an accessible at point. + DocAccessible* popupDoc = + GetAccService()->GetDocAccessible(popupFrame->GetContent()->OwnerDoc()); + Accessible* popupAcc = + popupDoc->GetAccessibleOrContainer(popupFrame->GetContent()); + Accessible* popupChild = this; + while (popupChild && !popupChild->IsDoc() && popupChild != popupAcc) + popupChild = popupChild->Parent(); + + if (popupChild == popupAcc) startFrame = popupFrame; + } + + nsPresContext* presContext = startFrame->PresContext(); + nsRect screenRect = startFrame->GetScreenRectInAppUnits(); + nsPoint offset(presContext->DevPixelsToAppUnits(aX) - screenRect.X(), + presContext->DevPixelsToAppUnits(aY) - screenRect.Y()); + + nsIFrame* foundFrame = nsLayoutUtils::GetFrameForPoint( + RelativeTo{startFrame, ViewportType::Visual}, offset); + + nsIContent* content = nullptr; + if (!foundFrame || !(content = foundFrame->GetContent())) + return fallbackAnswer; + + // Get accessible for the node with the point or the first accessible in + // the DOM parent chain. + DocAccessible* contentDocAcc = + GetAccService()->GetDocAccessible(content->OwnerDoc()); + + // contentDocAcc in some circumstances can be nullptr. See bug 729861 + NS_ASSERTION(contentDocAcc, "could not get the document accessible"); + if (!contentDocAcc) return fallbackAnswer; + + Accessible* accessible = contentDocAcc->GetAccessibleOrContainer(content); + if (!accessible) return fallbackAnswer; + + // Hurray! We have an accessible for the frame that layout gave us. + // Since DOM node of obtained accessible may be out of flow then we should + // ensure obtained accessible is a child of this accessible. + Accessible* child = accessible; + while (child != this) { + Accessible* parent = child->Parent(); + if (!parent) { + // Reached the top of the hierarchy. These bounds were inside an + // accessible that is not a descendant of this one. + return fallbackAnswer; + } + + // If we landed on a legitimate child of |this|, and we want the direct + // child, return it here. + if (parent == this && aWhichChild == eDirectChild) return child; + + child = parent; + } + + // Manually walk through accessible children and see if the are within this + // point. Skip offscreen or invisible accessibles. This takes care of cases + // where layout won't walk into things for us, such as image map areas and + // sub documents (XXX: subdocuments should be handled by methods of + // OuterDocAccessibles). + uint32_t childCount = accessible->ChildCount(); + for (uint32_t childIdx = 0; childIdx < childCount; childIdx++) { + Accessible* child = accessible->GetChildAt(childIdx); + + nsIntRect childRect = child->Bounds(); + if (childRect.Contains(aX, aY) && + (child->State() & states::INVISIBLE) == 0) { + if (aWhichChild == eDeepestChild) + return child->ChildAtPoint(aX, aY, eDeepestChild); + + return child; + } + } + + return accessible; +} + +nsRect Accessible::RelativeBounds(nsIFrame** aBoundingFrame) const { + nsIFrame* frame = GetFrame(); + if (frame && mContent) { + if (mContent->GetProperty(nsGkAtoms::hitregion) && mContent->IsElement()) { + // This is for canvas fallback content + // Find a canvas frame the found hit region is relative to. + nsIFrame* canvasFrame = frame->GetParent(); + if (canvasFrame) { + canvasFrame = nsLayoutUtils::GetClosestFrameOfType( + canvasFrame, LayoutFrameType::HTMLCanvas); + } + + // make the canvas the bounding frame + if (canvasFrame) { + *aBoundingFrame = canvasFrame; + if (auto* canvas = + dom::HTMLCanvasElement::FromNode(canvasFrame->GetContent())) { + if (auto* context = canvas->GetCurrentContext()) { + nsRect bounds; + if (context->GetHitRegionRect(mContent->AsElement(), bounds)) { + return bounds; + } + } + } + } + } + + *aBoundingFrame = nsLayoutUtils::GetContainingBlockForClientRect(frame); + return nsLayoutUtils::GetAllInFlowRectsUnion( + frame, *aBoundingFrame, nsLayoutUtils::RECTS_ACCOUNT_FOR_TRANSFORMS); + } + + return nsRect(); +} + +nsRect Accessible::BoundsInAppUnits() const { + nsIFrame* boundingFrame = nullptr; + nsRect unionRectTwips = RelativeBounds(&boundingFrame); + if (!boundingFrame) { + return nsRect(); + } + + PresShell* presShell = mDoc->PresContext()->PresShell(); + + // We need to inverse translate with the offset of the edge of the visual + // viewport from top edge of the layout viewport. + nsPoint viewportOffset = presShell->GetVisualViewportOffset() - + presShell->GetLayoutViewportOffset(); + unionRectTwips.MoveBy(-viewportOffset); + + // We need to take into account a non-1 resolution set on the presshell. + // This happens with async pinch zooming. Here we scale the bounds before + // adding the screen-relative offset. + unionRectTwips.ScaleRoundOut(presShell->GetResolution()); + // We have the union of the rectangle, now we need to put it in absolute + // screen coords. + nsRect orgRectPixels = boundingFrame->GetScreenRectInAppUnits(); + unionRectTwips.MoveBy(orgRectPixels.X(), orgRectPixels.Y()); + + return unionRectTwips; +} + +nsIntRect Accessible::Bounds() const { + return BoundsInAppUnits().ToNearestPixels( + mDoc->PresContext()->AppUnitsPerDevPixel()); +} + +nsIntRect Accessible::BoundsInCSSPixels() const { + return BoundsInAppUnits().ToNearestPixels(AppUnitsPerCSSPixel()); +} + +void Accessible::SetSelected(bool aSelect) { + if (!HasOwnContent()) return; + + Accessible* select = nsAccUtils::GetSelectableContainer(this, State()); + if (select) { + if (select->State() & states::MULTISELECTABLE) { + if (mContent->IsElement() && ARIARoleMap()) { + if (aSelect) { + mContent->AsElement()->SetAttr( + kNameSpaceID_None, nsGkAtoms::aria_selected, u"true"_ns, true); + } else { + mContent->AsElement()->UnsetAttr(kNameSpaceID_None, + nsGkAtoms::aria_selected, true); + } + } + return; + } + + if (aSelect) TakeFocus(); + } +} + +void Accessible::TakeSelection() { + Accessible* select = nsAccUtils::GetSelectableContainer(this, State()); + if (select) { + if (select->State() & states::MULTISELECTABLE) select->UnselectAll(); + SetSelected(true); + } +} + +void Accessible::TakeFocus() const { + nsIFrame* frame = GetFrame(); + if (!frame) return; + + nsIContent* focusContent = mContent; + + // If the accessible focus is managed by container widget then focus the + // widget and set the accessible as its current item. + if (!frame->IsFocusable()) { + Accessible* widget = ContainerWidget(); + if (widget && widget->AreItemsOperable()) { + nsIContent* widgetElm = widget->GetContent(); + nsIFrame* widgetFrame = widgetElm->GetPrimaryFrame(); + if (widgetFrame && widgetFrame->IsFocusable()) { + focusContent = widgetElm; + widget->SetCurrentItem(this); + } + } + } + + if (RefPtr<nsFocusManager> fm = nsFocusManager::GetFocusManager()) { + dom::AutoHandlingUserInputStatePusher inputStatePusher(true); + // XXXbz: Can we actually have a non-element content here? + RefPtr<dom::Element> element = dom::Element::FromNodeOrNull(focusContent); + fm->SetFocus(element, 0); + } +} + +void Accessible::NameFromAssociatedXULLabel(DocAccessible* aDocument, + nsIContent* aElm, nsString& aName) { + Accessible* label = nullptr; + XULLabelIterator iter(aDocument, aElm); + while ((label = iter.Next())) { + // Check if label's value attribute is used + label->Elm()->GetAttr(kNameSpaceID_None, nsGkAtoms::value, aName); + if (aName.IsEmpty()) { + // If no value attribute, a non-empty label must contain + // children that define its text -- possibly using HTML + nsTextEquivUtils::AppendTextEquivFromContent(label, label->Elm(), &aName); + } + } + aName.CompressWhitespace(); +} + +void Accessible::XULElmName(DocAccessible* aDocument, nsIContent* aElm, + nsString& aName) { + /** + * 3 main cases for XUL Controls to be labeled + * 1 - control contains label="foo" + * 2 - non-child label contains control="controlID" + * - label has either value="foo" or children + * 3 - name from subtree; e.g. a child label element + * Cases 1 and 2 are handled here. + * Case 3 is handled by GetNameFromSubtree called in NativeName. + * Once a label is found, the search is discontinued, so a control + * that has a label attribute as well as having a label external to + * the control that uses the control="controlID" syntax will use + * the label attribute for its Name. + */ + + // CASE #1 (via label attribute) -- great majority of the cases + // Only do this if this is not a select control element, which uses label + // attribute to indicate, which option is selected. + nsCOMPtr<nsIDOMXULSelectControlElement> select = + aElm->AsElement()->AsXULSelectControl(); + if (!select) { + aElm->AsElement()->GetAttr(kNameSpaceID_None, nsGkAtoms::label, aName); + } + + // CASE #2 -- label as <label control="id" ... ></label> + if (aName.IsEmpty()) { + NameFromAssociatedXULLabel(aDocument, aElm, aName); + } + + aName.CompressWhitespace(); +} + +nsresult Accessible::HandleAccEvent(AccEvent* aEvent) { + NS_ENSURE_ARG_POINTER(aEvent); + +#ifdef MOZ_GECKO_PROFILER + if (profiler_thread_is_being_profiled()) { + nsAutoCString strEventType; + GetAccService()->GetStringEventType(aEvent->GetEventType(), strEventType); + nsAutoCString strMarker; + strMarker.AppendLiteral("A11y Event - "); + strMarker.Append(strEventType); + PROFILER_MARKER_UNTYPED(strMarker, OTHER); + } +#endif + + if (IPCAccessibilityActive() && Document()) { + DocAccessibleChild* ipcDoc = mDoc->IPCDoc(); + // If ipcDoc is null, we can't fire the event to the client. We shouldn't + // have fired the event in the first place, since this makes events + // inconsistent for local and remote documents. To avoid this, don't call + // nsEventShell::FireEvent on a DocAccessible for which + // HasLoadState(eTreeConstructed) is false. + MOZ_ASSERT(ipcDoc); + if (ipcDoc) { + uint64_t id = aEvent->GetAccessible()->IsDoc() + ? 0 + : reinterpret_cast<uintptr_t>( + aEvent->GetAccessible()->UniqueID()); + + switch (aEvent->GetEventType()) { + case nsIAccessibleEvent::EVENT_SHOW: + ipcDoc->ShowEvent(downcast_accEvent(aEvent)); + break; + + case nsIAccessibleEvent::EVENT_HIDE: + ipcDoc->SendHideEvent(id, aEvent->IsFromUserInput()); + break; + + case nsIAccessibleEvent::EVENT_REORDER: + // reorder events on the application acc aren't necessary to tell the + // parent about new top level documents. + if (!aEvent->GetAccessible()->IsApplication()) + ipcDoc->SendEvent(id, aEvent->GetEventType()); + break; + case nsIAccessibleEvent::EVENT_STATE_CHANGE: { + AccStateChangeEvent* event = downcast_accEvent(aEvent); + ipcDoc->SendStateChangeEvent(id, event->GetState(), + event->IsStateEnabled()); + break; + } + case nsIAccessibleEvent::EVENT_TEXT_CARET_MOVED: { + AccCaretMoveEvent* event = downcast_accEvent(aEvent); + ipcDoc->SendCaretMoveEvent(id, event->GetCaretOffset(), + event->IsSelectionCollapsed()); + break; + } + case nsIAccessibleEvent::EVENT_TEXT_INSERTED: + case nsIAccessibleEvent::EVENT_TEXT_REMOVED: { + AccTextChangeEvent* event = downcast_accEvent(aEvent); + const nsString& text = event->ModifiedText(); +#if defined(XP_WIN) + // On Windows, events for live region updates containing embedded + // objects require us to dispatch synchronous events. + bool sync = text.Contains(L'\xfffc') && + nsAccUtils::IsARIALive(aEvent->GetAccessible()); +#endif + ipcDoc->SendTextChangeEvent(id, text, event->GetStartOffset(), + event->GetLength(), + event->IsTextInserted(), + event->IsFromUserInput() +#if defined(XP_WIN) + // This parameter only exists on Windows. + , + sync +#endif + ); + break; + } + case nsIAccessibleEvent::EVENT_SELECTION: + case nsIAccessibleEvent::EVENT_SELECTION_ADD: + case nsIAccessibleEvent::EVENT_SELECTION_REMOVE: { + AccSelChangeEvent* selEvent = downcast_accEvent(aEvent); + uint64_t widgetID = + selEvent->Widget()->IsDoc() + ? 0 + : reinterpret_cast<uintptr_t>(selEvent->Widget()->UniqueID()); + ipcDoc->SendSelectionEvent(id, widgetID, aEvent->GetEventType()); + break; + } + case nsIAccessibleEvent::EVENT_VIRTUALCURSOR_CHANGED: { + AccVCChangeEvent* vcEvent = downcast_accEvent(aEvent); + Accessible* position = vcEvent->NewAccessible(); + Accessible* oldPosition = vcEvent->OldAccessible(); + ipcDoc->SendVirtualCursorChangeEvent( + id, + oldPosition ? reinterpret_cast<uintptr_t>(oldPosition->UniqueID()) + : 0, + vcEvent->OldStartOffset(), vcEvent->OldEndOffset(), + position ? reinterpret_cast<uintptr_t>(position->UniqueID()) : 0, + vcEvent->NewStartOffset(), vcEvent->NewEndOffset(), + vcEvent->Reason(), vcEvent->BoundaryType(), + vcEvent->IsFromUserInput()); + break; + } +#if defined(XP_WIN) + case nsIAccessibleEvent::EVENT_FOCUS: { + ipcDoc->SendFocusEvent(id); + break; + } +#endif + case nsIAccessibleEvent::EVENT_SCROLLING_END: + case nsIAccessibleEvent::EVENT_SCROLLING: { + AccScrollingEvent* scrollingEvent = downcast_accEvent(aEvent); + ipcDoc->SendScrollingEvent( + id, aEvent->GetEventType(), scrollingEvent->ScrollX(), + scrollingEvent->ScrollY(), scrollingEvent->MaxScrollX(), + scrollingEvent->MaxScrollY()); + break; + } +#if !defined(XP_WIN) + case nsIAccessibleEvent::EVENT_ANNOUNCEMENT: { + AccAnnouncementEvent* announcementEvent = downcast_accEvent(aEvent); + ipcDoc->SendAnnouncementEvent(id, announcementEvent->Announcement(), + announcementEvent->Priority()); + break; + } + case nsIAccessibleEvent::EVENT_TEXT_SELECTION_CHANGED: { + AccTextSelChangeEvent* textSelChangeEvent = downcast_accEvent(aEvent); + AutoTArray<TextRange, 1> ranges; + textSelChangeEvent->SelectionRanges(&ranges); + nsTArray<TextRangeData> textRangeData(ranges.Length()); + for (size_t i = 0; i < ranges.Length(); i++) { + const TextRange& range = ranges.ElementAt(i); + Accessible* start = range.StartContainer(); + Accessible* end = range.EndContainer(); + textRangeData.AppendElement(TextRangeData( + start->IsDoc() && start->AsDoc()->IPCDoc() + ? 0 + : reinterpret_cast<uint64_t>(start->UniqueID()), + end->IsDoc() && end->AsDoc()->IPCDoc() + ? 0 + : reinterpret_cast<uint64_t>(end->UniqueID()), + range.StartOffset(), range.EndOffset())); + } + ipcDoc->SendTextSelectionChangeEvent(id, textRangeData); + break; + } +#endif + default: + ipcDoc->SendEvent(id, aEvent->GetEventType()); + } + } + } + + if (nsCoreUtils::AccEventObserversExist()) { + nsCoreUtils::DispatchAccEvent(MakeXPCEvent(aEvent)); + } + + return NS_OK; +} + +already_AddRefed<nsIPersistentProperties> Accessible::Attributes() { + nsCOMPtr<nsIPersistentProperties> attributes = NativeAttributes(); + if (!HasOwnContent() || !mContent->IsElement()) return attributes.forget(); + + // 'xml-roles' attribute coming from ARIA. + nsAutoString xmlRoles; + if (mContent->AsElement()->GetAttr(kNameSpaceID_None, nsGkAtoms::role, + xmlRoles)) { + nsAccUtils::SetAccAttr(attributes, nsGkAtoms::xmlroles, xmlRoles); + } else if (nsAtom* landmark = LandmarkRole()) { + // 'xml-roles' attribute for landmark. + nsAccUtils::SetAccAttr(attributes, nsGkAtoms::xmlroles, landmark); + } + + // Expose object attributes from ARIA attributes. + nsAutoString unused; + aria::AttrIterator attribIter(mContent); + nsAutoString name, value; + while (attribIter.Next(name, value)) + attributes->SetStringProperty(NS_ConvertUTF16toUTF8(name), value, unused); + + // If there is no aria-live attribute then expose default value of 'live' + // object attribute used for ARIA role of this accessible. + const nsRoleMapEntry* roleMapEntry = ARIARoleMap(); + if (roleMapEntry) { + if (roleMapEntry->Is(nsGkAtoms::searchbox)) { + nsAccUtils::SetAccAttr(attributes, nsGkAtoms::textInputType, + u"search"_ns); + } + + nsAutoString live; + nsAccUtils::GetAccAttr(attributes, nsGkAtoms::live, live); + if (live.IsEmpty()) { + if (nsAccUtils::GetLiveAttrValue(roleMapEntry->liveAttRule, live)) + nsAccUtils::SetAccAttr(attributes, nsGkAtoms::live, live); + } + } + + return attributes.forget(); +} + +already_AddRefed<nsIPersistentProperties> Accessible::NativeAttributes() { + RefPtr<nsPersistentProperties> attributes = new nsPersistentProperties(); + + nsAutoString unused; + + // We support values, so expose the string value as well, via the valuetext + // object attribute. We test for the value interface because we don't want + // to expose traditional Value() information such as URL's on links and + // documents, or text in an input. + if (HasNumericValue()) { + nsAutoString valuetext; + Value(valuetext); + attributes->SetStringProperty("valuetext"_ns, valuetext, unused); + } + + // Expose checkable object attribute if the accessible has checkable state + if (State() & states::CHECKABLE) { + nsAccUtils::SetAccAttr(attributes, nsGkAtoms::checkable, u"true"_ns); + } + + // Expose 'explicit-name' attribute. + nsAutoString name; + if (Name(name) != eNameFromSubtree && !name.IsVoid()) { + attributes->SetStringProperty("explicit-name"_ns, u"true"_ns, unused); + } + + // Group attributes (level/setsize/posinset) + GroupPos groupPos = GroupPosition(); + nsAccUtils::SetAccGroupAttrs(attributes, groupPos.level, groupPos.setSize, + groupPos.posInSet); + + bool hierarchical = false; + uint32_t itemCount = AccGroupInfo::TotalItemCount(this, &hierarchical); + if (itemCount) { + nsAutoString itemCountStr; + itemCountStr.AppendInt(itemCount); + attributes->SetStringProperty("child-item-count"_ns, itemCountStr, unused); + } + + if (hierarchical) { + attributes->SetStringProperty("hierarchical"_ns, u"true"_ns, unused); + } + + // If the accessible doesn't have own content (such as list item bullet or + // xul tree item) then don't calculate content based attributes. + if (!HasOwnContent()) return attributes.forget(); + + nsEventShell::GetEventAttributes(GetNode(), attributes); + + // Get container-foo computed live region properties based on the closest + // container with the live region attribute. Inner nodes override outer nodes + // within the same document. The inner nodes can be used to override live + // region behavior on more general outer nodes. + nsAccUtils::SetLiveContainerAttributes(attributes, mContent); + + if (!mContent->IsElement()) return attributes.forget(); + + nsAutoString id; + if (nsCoreUtils::GetID(mContent, id)) + attributes->SetStringProperty("id"_ns, id, unused); + + // Expose class because it may have useful microformat information. + nsAutoString _class; + if (mContent->AsElement()->GetAttr(kNameSpaceID_None, nsGkAtoms::_class, + _class)) + nsAccUtils::SetAccAttr(attributes, nsGkAtoms::_class, _class); + + // Expose tag. + nsAutoString tagName; + mContent->NodeInfo()->GetName(tagName); + nsAccUtils::SetAccAttr(attributes, nsGkAtoms::tag, tagName); + + // Expose draggable object attribute. + if (auto htmlElement = nsGenericHTMLElement::FromNode(mContent)) { + if (htmlElement->Draggable()) { + nsAccUtils::SetAccAttr(attributes, nsGkAtoms::draggable, u"true"_ns); + } + } + + // Don't calculate CSS-based object attributes when no frame (i.e. + // the accessible is unattached from the tree). + if (!mContent->GetPrimaryFrame()) return attributes.forget(); + + // CSS style based object attributes. + nsAutoString value; + StyleInfo styleInfo(mContent->AsElement()); + + // Expose 'display' attribute. + styleInfo.Display(value); + nsAccUtils::SetAccAttr(attributes, nsGkAtoms::display, value); + + // Expose 'text-align' attribute. + styleInfo.TextAlign(value); + nsAccUtils::SetAccAttr(attributes, nsGkAtoms::textAlign, value); + + // Expose 'text-indent' attribute. + styleInfo.TextIndent(value); + nsAccUtils::SetAccAttr(attributes, nsGkAtoms::textIndent, value); + + // Expose 'margin-left' attribute. + styleInfo.MarginLeft(value); + nsAccUtils::SetAccAttr(attributes, nsGkAtoms::marginLeft, value); + + // Expose 'margin-right' attribute. + styleInfo.MarginRight(value); + nsAccUtils::SetAccAttr(attributes, nsGkAtoms::marginRight, value); + + // Expose 'margin-top' attribute. + styleInfo.MarginTop(value); + nsAccUtils::SetAccAttr(attributes, nsGkAtoms::marginTop, value); + + // Expose 'margin-bottom' attribute. + styleInfo.MarginBottom(value); + nsAccUtils::SetAccAttr(attributes, nsGkAtoms::marginBottom, value); + + // Expose data-at-shortcutkeys attribute for web applications and virtual + // cursors. Currently mostly used by JAWS. + nsAutoString atShortcutKeys; + if (mContent->AsElement()->GetAttr( + kNameSpaceID_None, nsGkAtoms::dataAtShortcutkeys, atShortcutKeys)) { + nsAccUtils::SetAccAttr(attributes, nsGkAtoms::dataAtShortcutkeys, + atShortcutKeys); + } + + return attributes.forget(); +} + +GroupPos Accessible::GroupPosition() { + GroupPos groupPos; + if (!HasOwnContent()) return groupPos; + + // Get group position from ARIA attributes. + nsCoreUtils::GetUIntAttr(mContent, nsGkAtoms::aria_level, &groupPos.level); + nsCoreUtils::GetUIntAttr(mContent, nsGkAtoms::aria_setsize, + &groupPos.setSize); + nsCoreUtils::GetUIntAttr(mContent, nsGkAtoms::aria_posinset, + &groupPos.posInSet); + + // If ARIA is missed and the accessible is visible then calculate group + // position from hierarchy. + if (State() & states::INVISIBLE) return groupPos; + + // Calculate group level if ARIA is missed. + if (groupPos.level == 0) { + int32_t level = GetLevelInternal(); + if (level != 0) { + groupPos.level = level; + } else { + const nsRoleMapEntry* role = this->ARIARoleMap(); + if (role && role->Is(nsGkAtoms::heading)) { + groupPos.level = 2; + } + } + } + + // Calculate position in group and group size if ARIA is missed. + if (groupPos.posInSet == 0 || groupPos.setSize == 0) { + int32_t posInSet = 0, setSize = 0; + GetPositionAndSizeInternal(&posInSet, &setSize); + if (posInSet != 0 && setSize != 0) { + if (groupPos.posInSet == 0) groupPos.posInSet = posInSet; + + if (groupPos.setSize == 0) groupPos.setSize = setSize; + } + } + + return groupPos; +} + +uint64_t Accessible::State() { + if (IsDefunct()) return states::DEFUNCT; + + uint64_t state = NativeState(); + // Apply ARIA states to be sure accessible states will be overridden. + ApplyARIAState(&state); + + // If this is an ARIA item of the selectable widget and if it's focused and + // not marked unselected explicitly (i.e. aria-selected="false") then expose + // it as selected to make ARIA widget authors life easier. + const nsRoleMapEntry* roleMapEntry = ARIARoleMap(); + if (roleMapEntry && !(state & states::SELECTED) && + (!mContent->IsElement() || + !mContent->AsElement()->AttrValueIs(kNameSpaceID_None, + nsGkAtoms::aria_selected, + nsGkAtoms::_false, eCaseMatters))) { + // Special case for tabs: focused tab or focus inside related tab panel + // implies selected state. + if (roleMapEntry->role == roles::PAGETAB) { + if (state & states::FOCUSED) { + state |= states::SELECTED; + } else { + // If focus is in a child of the tab panel surely the tab is selected! + Relation rel = RelationByType(RelationType::LABEL_FOR); + Accessible* relTarget = nullptr; + while ((relTarget = rel.Next())) { + if (relTarget->Role() == roles::PROPERTYPAGE && + FocusMgr()->IsFocusWithin(relTarget)) + state |= states::SELECTED; + } + } + } else if (state & states::FOCUSED) { + Accessible* container = nsAccUtils::GetSelectableContainer(this, state); + if (container && + !nsAccUtils::HasDefinedARIAToken(container->GetContent(), + nsGkAtoms::aria_multiselectable)) { + state |= states::SELECTED; + } + } + } + + const uint32_t kExpandCollapseStates = states::COLLAPSED | states::EXPANDED; + if ((state & kExpandCollapseStates) == kExpandCollapseStates) { + // Cannot be both expanded and collapsed -- this happens in ARIA expanded + // combobox because of limitation of ARIAMap. + // XXX: Perhaps we will be able to make this less hacky if we support + // extended states in ARIAMap, e.g. derive COLLAPSED from + // EXPANDABLE && !EXPANDED. + state &= ~states::COLLAPSED; + } + + if (!(state & states::UNAVAILABLE)) { + state |= states::ENABLED | states::SENSITIVE; + + // If the object is a current item of container widget then mark it as + // ACTIVE. This allows screen reader virtual buffer modes to know which + // descendant is the current one that would get focus if the user navigates + // to the container widget. + Accessible* widget = ContainerWidget(); + if (widget && widget->CurrentItem() == this) state |= states::ACTIVE; + } + + if ((state & states::COLLAPSED) || (state & states::EXPANDED)) + state |= states::EXPANDABLE; + + // For some reasons DOM node may have not a frame. We tract such accessibles + // as invisible. + nsIFrame* frame = GetFrame(); + if (!frame) return state; + + if (frame->StyleEffects()->mOpacity == 1.0f && !(state & states::INVISIBLE)) { + state |= states::OPAQUE1; + } + + return state; +} + +void Accessible::ApplyARIAState(uint64_t* aState) const { + if (!mContent->IsElement()) return; + + dom::Element* element = mContent->AsElement(); + + // Test for universal states first + *aState |= aria::UniversalStatesFor(element); + + const nsRoleMapEntry* roleMapEntry = ARIARoleMap(); + if (roleMapEntry) { + // We only force the readonly bit off if we have a real mapping for the aria + // role. This preserves the ability for screen readers to use readonly + // (primarily on the document) as the hint for creating a virtual buffer. + if (roleMapEntry->role != roles::NOTHING) *aState &= ~states::READONLY; + + if (mContent->HasID()) { + // If has a role & ID and aria-activedescendant on the container, assume + // focusable. + const Accessible* ancestor = this; + while ((ancestor = ancestor->Parent()) && !ancestor->IsDoc()) { + dom::Element* el = ancestor->Elm(); + if (el && + el->HasAttr(kNameSpaceID_None, nsGkAtoms::aria_activedescendant)) { + *aState |= states::FOCUSABLE; + break; + } + } + } + } + + if (*aState & states::FOCUSABLE) { + // Propogate aria-disabled from ancestors down to any focusable descendant. + const Accessible* ancestor = this; + while ((ancestor = ancestor->Parent()) && !ancestor->IsDoc()) { + dom::Element* el = ancestor->Elm(); + if (el && el->AttrValueIs(kNameSpaceID_None, nsGkAtoms::aria_disabled, + nsGkAtoms::_true, eCaseMatters)) { + *aState |= states::UNAVAILABLE; + break; + } + } + } else { + // Sometimes, we use aria-activedescendant targeting something which isn't + // actually a descendant. This is technically a spec violation, but it's a + // useful hack which makes certain things much easier. For example, we use + // this for "fake focus" for multi select browser tabs and Quantumbar + // autocomplete suggestions. + // In these cases, the aria-activedescendant code above won't make the + // active item focusable. It doesn't make sense for something to have + // focus when it isn't focusable, so fix that here. + if (FocusMgr()->IsActiveItem(this)) { + *aState |= states::FOCUSABLE; + } + } + + // special case: A native button element whose role got transformed by ARIA to + // a toggle button Also applies to togglable button menus, like in the Dev + // Tools Web Console. + if (IsButton() || IsMenuButton()) + aria::MapToState(aria::eARIAPressed, element, aState); + + if (!roleMapEntry) return; + + *aState |= roleMapEntry->state; + + if (aria::MapToState(roleMapEntry->attributeMap1, element, aState) && + aria::MapToState(roleMapEntry->attributeMap2, element, aState) && + aria::MapToState(roleMapEntry->attributeMap3, element, aState)) + aria::MapToState(roleMapEntry->attributeMap4, element, aState); + + // ARIA gridcell inherits readonly state from the grid until it's overridden. + if ((roleMapEntry->Is(nsGkAtoms::gridcell) || + roleMapEntry->Is(nsGkAtoms::columnheader) || + roleMapEntry->Is(nsGkAtoms::rowheader)) && + !nsAccUtils::HasDefinedARIAToken(mContent, nsGkAtoms::aria_readonly)) { + const TableCellAccessible* cell = AsTableCell(); + if (cell) { + TableAccessible* table = cell->Table(); + if (table) { + Accessible* grid = table->AsAccessible(); + uint64_t gridState = 0; + grid->ApplyARIAState(&gridState); + *aState |= gridState & states::READONLY; + } + } + } +} + +void Accessible::Value(nsString& aValue) const { + if (HasNumericValue()) { + // aria-valuenow is a number, and aria-valuetext is the optional text + // equivalent. For the string value, we will try the optional text + // equivalent first. + if (!mContent->IsElement()) { + return; + } + + if (!mContent->AsElement()->GetAttr(kNameSpaceID_None, + nsGkAtoms::aria_valuetext, aValue)) { + if (!NativeHasNumericValue()) { + double checkValue = CurValue(); + if (!IsNaN(checkValue)) { + aValue.AppendFloat(checkValue); + } + } + } + return; + } + + const nsRoleMapEntry* roleMapEntry = ARIARoleMap(); + if (!roleMapEntry) { + return; + } + + // Value of textbox is a textified subtree. + if (roleMapEntry->Is(nsGkAtoms::textbox)) { + nsTextEquivUtils::GetTextEquivFromSubtree(this, aValue); + return; + } + + // Value of combobox is a text of current or selected item. + if (roleMapEntry->Is(nsGkAtoms::combobox)) { + Accessible* option = CurrentItem(); + if (!option) { + uint32_t childCount = ChildCount(); + for (uint32_t idx = 0; idx < childCount; idx++) { + Accessible* child = mChildren.ElementAt(idx); + if (child->IsListControl()) { + option = child->GetSelectedItem(0); + break; + } + } + } + + if (option) nsTextEquivUtils::GetTextEquivFromSubtree(option, aValue); + } +} + +double Accessible::MaxValue() const { + double checkValue = AttrNumericValue(nsGkAtoms::aria_valuemax); + return IsNaN(checkValue) && !NativeHasNumericValue() ? 100 : checkValue; +} + +double Accessible::MinValue() const { + double checkValue = AttrNumericValue(nsGkAtoms::aria_valuemin); + return IsNaN(checkValue) && !NativeHasNumericValue() ? 0 : checkValue; +} + +double Accessible::Step() const { + return UnspecifiedNaN<double>(); // no mimimum increment (step) in ARIA. +} + +double Accessible::CurValue() const { + double checkValue = AttrNumericValue(nsGkAtoms::aria_valuenow); + if (IsNaN(checkValue) && !NativeHasNumericValue()) { + double minValue = MinValue(); + return minValue + ((MaxValue() - minValue) / 2); + } + + return checkValue; +} + +bool Accessible::SetCurValue(double aValue) { + const nsRoleMapEntry* roleMapEntry = ARIARoleMap(); + if (!roleMapEntry || roleMapEntry->valueRule == eNoValue) return false; + + const uint32_t kValueCannotChange = states::READONLY | states::UNAVAILABLE; + if (State() & kValueCannotChange) return false; + + double checkValue = MinValue(); + if (!IsNaN(checkValue) && aValue < checkValue) return false; + + checkValue = MaxValue(); + if (!IsNaN(checkValue) && aValue > checkValue) return false; + + nsAutoString strValue; + strValue.AppendFloat(aValue); + + if (!mContent->IsElement()) return true; + + return NS_SUCCEEDED(mContent->AsElement()->SetAttr( + kNameSpaceID_None, nsGkAtoms::aria_valuenow, strValue, true)); +} + +role Accessible::ARIATransformRole(role aRole) const { + // Beginning with ARIA 1.1, user agents are expected to use the native host + // language role of the element when the region role is used without a name. + // https://rawgit.com/w3c/aria/master/core-aam/core-aam.html#role-map-region + // + // XXX: While the name computation algorithm can be non-trivial in the general + // case, it should not be especially bad here: If the author hasn't used the + // region role, this calculation won't occur. And the region role's name + // calculation rule excludes name from content. That said, this use case is + // another example of why we should consider caching the accessible name. See: + // https://bugzilla.mozilla.org/show_bug.cgi?id=1378235. + if (aRole == roles::REGION) { + nsAutoString name; + Name(name); + return name.IsEmpty() ? NativeRole() : aRole; + } + + // XXX: these unfortunate exceptions don't fit into the ARIA table. This is + // where the accessible role depends on both the role and ARIA state. + if (aRole == roles::PUSHBUTTON) { + if (nsAccUtils::HasDefinedARIAToken(mContent, nsGkAtoms::aria_pressed)) { + // For simplicity, any existing pressed attribute except "" or "undefined" + // indicates a toggle. + return roles::TOGGLE_BUTTON; + } + + if (mContent->IsElement() && + mContent->AsElement()->AttrValueIs(kNameSpaceID_None, + nsGkAtoms::aria_haspopup, + nsGkAtoms::_true, eCaseMatters)) { + // For button with aria-haspopup="true". + return roles::BUTTONMENU; + } + + } else if (aRole == roles::LISTBOX) { + // A listbox inside of a combobox needs a special role because of ATK + // mapping to menu. + if (mParent && mParent->IsCombobox()) { + return roles::COMBOBOX_LIST; + } else { + // Listbox is owned by a combobox + Relation rel = RelationByType(RelationType::NODE_CHILD_OF); + Accessible* targetAcc = nullptr; + while ((targetAcc = rel.Next())) + if (targetAcc->IsCombobox()) return roles::COMBOBOX_LIST; + } + + } else if (aRole == roles::OPTION) { + if (mParent && mParent->Role() == roles::COMBOBOX_LIST) + return roles::COMBOBOX_OPTION; + + } else if (aRole == roles::MENUITEM) { + // Menuitem has a submenu. + if (mContent->IsElement() && + mContent->AsElement()->AttrValueIs(kNameSpaceID_None, + nsGkAtoms::aria_haspopup, + nsGkAtoms::_true, eCaseMatters)) { + return roles::PARENT_MENUITEM; + } + + } else if (aRole == roles::CELL) { + // A cell inside an ancestor table element that has a grid role needs a + // gridcell role + // (https://www.w3.org/TR/html-aam-1.0/#html-element-role-mappings). + const TableCellAccessible* cell = AsTableCell(); + if (cell) { + TableAccessible* table = cell->Table(); + if (table && table->AsAccessible()->IsARIARole(nsGkAtoms::grid)) { + return roles::GRID_CELL; + } + } + } + + return aRole; +} + +nsAtom* Accessible::LandmarkRole() const { + const nsRoleMapEntry* roleMapEntry = ARIARoleMap(); + return roleMapEntry && roleMapEntry->IsOfType(eLandmark) + ? roleMapEntry->roleAtom + : nullptr; +} + +role Accessible::NativeRole() const { return roles::NOTHING; } + +uint8_t Accessible::ActionCount() const { + return GetActionRule() == eNoAction ? 0 : 1; +} + +void Accessible::ActionNameAt(uint8_t aIndex, nsAString& aName) { + aName.Truncate(); + + if (aIndex != 0) return; + + uint32_t actionRule = GetActionRule(); + + switch (actionRule) { + case eActivateAction: + aName.AssignLiteral("activate"); + return; + + case eClickAction: + aName.AssignLiteral("click"); + return; + + case ePressAction: + aName.AssignLiteral("press"); + return; + + case eCheckUncheckAction: { + uint64_t state = State(); + if (state & states::CHECKED) + aName.AssignLiteral("uncheck"); + else if (state & states::MIXED) + aName.AssignLiteral("cycle"); + else + aName.AssignLiteral("check"); + return; + } + + case eJumpAction: + aName.AssignLiteral("jump"); + return; + + case eOpenCloseAction: + if (State() & states::COLLAPSED) + aName.AssignLiteral("open"); + else + aName.AssignLiteral("close"); + return; + + case eSelectAction: + aName.AssignLiteral("select"); + return; + + case eSwitchAction: + aName.AssignLiteral("switch"); + return; + + case eSortAction: + aName.AssignLiteral("sort"); + return; + + case eExpandAction: + if (State() & states::COLLAPSED) + aName.AssignLiteral("expand"); + else + aName.AssignLiteral("collapse"); + return; + } +} + +bool Accessible::DoAction(uint8_t aIndex) const { + if (aIndex != 0) return false; + + if (GetActionRule() != eNoAction) { + DoCommand(); + return true; + } + + return false; +} + +nsIContent* Accessible::GetAtomicRegion() const { + nsIContent* loopContent = mContent; + nsAutoString atomic; + while (loopContent && + (!loopContent->IsElement() || + !loopContent->AsElement()->GetAttr(kNameSpaceID_None, + nsGkAtoms::aria_atomic, atomic))) + loopContent = loopContent->GetParent(); + + return atomic.EqualsLiteral("true") ? loopContent : nullptr; +} + +Relation Accessible::RelationByType(RelationType aType) const { + if (!HasOwnContent()) return Relation(); + + const nsRoleMapEntry* roleMapEntry = ARIARoleMap(); + + // Relationships are defined on the same content node that the role would be + // defined on. + switch (aType) { + case RelationType::LABELLED_BY: { + Relation rel( + new IDRefsIterator(mDoc, mContent, nsGkAtoms::aria_labelledby)); + if (mContent->IsHTMLElement()) { + rel.AppendIter(new HTMLLabelIterator(Document(), this)); + } + rel.AppendIter(new XULLabelIterator(Document(), mContent)); + + return rel; + } + + case RelationType::LABEL_FOR: { + Relation rel(new RelatedAccIterator(Document(), mContent, + nsGkAtoms::aria_labelledby)); + if (mContent->IsXULElement(nsGkAtoms::label)) + rel.AppendIter(new IDRefsIterator(mDoc, mContent, nsGkAtoms::control)); + + return rel; + } + + case RelationType::DESCRIBED_BY: { + Relation rel( + new IDRefsIterator(mDoc, mContent, nsGkAtoms::aria_describedby)); + if (mContent->IsXULElement()) + rel.AppendIter(new XULDescriptionIterator(Document(), mContent)); + + return rel; + } + + case RelationType::DESCRIPTION_FOR: { + Relation rel(new RelatedAccIterator(Document(), mContent, + nsGkAtoms::aria_describedby)); + + // This affectively adds an optional control attribute to xul:description, + // which only affects accessibility, by allowing the description to be + // tied to a control. + if (mContent->IsXULElement(nsGkAtoms::description)) + rel.AppendIter(new IDRefsIterator(mDoc, mContent, nsGkAtoms::control)); + + return rel; + } + + case RelationType::NODE_CHILD_OF: { + Relation rel; + // This is an ARIA tree or treegrid that doesn't use owns, so we need to + // get the parent the hard way. + if (roleMapEntry && (roleMapEntry->role == roles::OUTLINEITEM || + roleMapEntry->role == roles::LISTITEM || + roleMapEntry->role == roles::ROW)) { + rel.AppendTarget(GetGroupInfo()->ConceptualParent()); + } + + // If this is an OOP iframe document, we can't support NODE_CHILD_OF + // here, since the iframe resides in a different process. This is fine + // because the client will then request the parent instead, which will be + // correctly handled by platform/AccessibleOrProxy code. + if (XRE_IsContentProcess() && IsRoot()) { + dom::Document* doc = + const_cast<Accessible*>(this)->AsDoc()->DocumentNode(); + dom::BrowsingContext* bc = doc->GetBrowsingContext(); + MOZ_ASSERT(bc); + if (!bc->Top()->IsInProcess()) { + return rel; + } + } + + // If accessible is in its own Window, or is the root of a document, + // then we should provide NODE_CHILD_OF relation so that MSAA clients + // can easily get to true parent instead of getting to oleacc's + // ROLE_WINDOW accessible which will prevent us from going up further + // (because it is system generated and has no idea about the hierarchy + // above it). + nsIFrame* frame = GetFrame(); + if (frame) { + nsView* view = frame->GetView(); + if (view) { + nsIScrollableFrame* scrollFrame = do_QueryFrame(frame); + if (scrollFrame || view->GetWidget() || !frame->GetParent()) + rel.AppendTarget(Parent()); + } + } + + return rel; + } + + case RelationType::NODE_PARENT_OF: { + // ARIA tree or treegrid can do the hierarchy by @aria-level, ARIA trees + // also can be organized by groups. + if (roleMapEntry && (roleMapEntry->role == roles::OUTLINEITEM || + roleMapEntry->role == roles::LISTITEM || + roleMapEntry->role == roles::ROW || + roleMapEntry->role == roles::OUTLINE || + roleMapEntry->role == roles::LIST || + roleMapEntry->role == roles::TREE_TABLE)) { + return Relation(new ItemIterator(this)); + } + + return Relation(); + } + + case RelationType::CONTROLLED_BY: + return Relation(new RelatedAccIterator(Document(), mContent, + nsGkAtoms::aria_controls)); + + case RelationType::CONTROLLER_FOR: { + Relation rel( + new IDRefsIterator(mDoc, mContent, nsGkAtoms::aria_controls)); + rel.AppendIter(new HTMLOutputIterator(Document(), mContent)); + return rel; + } + + case RelationType::FLOWS_TO: + return Relation( + new IDRefsIterator(mDoc, mContent, nsGkAtoms::aria_flowto)); + + case RelationType::FLOWS_FROM: + return Relation( + new RelatedAccIterator(Document(), mContent, nsGkAtoms::aria_flowto)); + + case RelationType::MEMBER_OF: { + if (Role() == roles::RADIOBUTTON) { + /* If we see a radio button role here, we're dealing with an aria + * radio button (because input=radio buttons are + * HTMLRadioButtonAccessibles) */ + Relation rel = Relation(); + Accessible* currParent = Parent(); + while (currParent && currParent->Role() != roles::RADIO_GROUP) { + currParent = currParent->Parent(); + } + + if (currParent && currParent->Role() == roles::RADIO_GROUP) { + /* If we found a radiogroup parent, search for all + * roles::RADIOBUTTON children and add them to our relation. + * This search will include the radio button this method + * was called from, which is expected. */ + Pivot p = Pivot(currParent); + PivotRoleRule rule(roles::RADIOBUTTON); + AccessibleOrProxy wrappedParent = AccessibleOrProxy(currParent); + AccessibleOrProxy match = p.Next(wrappedParent, rule); + while (!match.IsNull()) { + MOZ_ASSERT( + !match.IsProxy(), + "We shouldn't find any proxy's while building our relation!"); + rel.AppendTarget(match.AsAccessible()); + match = p.Next(match, rule); + } + } + + /* By webkit's standard, aria radio buttons do not get grouped + * if they lack a group parent, so we return an empty + * relation here if the above check fails. */ + + return rel; + } + + return Relation(mDoc, GetAtomicRegion()); + } + + case RelationType::SUBWINDOW_OF: + case RelationType::EMBEDS: + case RelationType::EMBEDDED_BY: + case RelationType::POPUP_FOR: + case RelationType::PARENT_WINDOW_OF: + return Relation(); + + case RelationType::DEFAULT_BUTTON: { + if (mContent->IsHTMLElement()) { + // HTML form controls implements nsIFormControl interface. + nsCOMPtr<nsIFormControl> control(do_QueryInterface(mContent)); + if (control) { + if (dom::HTMLFormElement* form = control->GetFormElement()) { + nsCOMPtr<nsIContent> formContent = + do_QueryInterface(form->GetDefaultSubmitElement()); + return Relation(mDoc, formContent); + } + } + } else { + // In XUL, use first <button default="true" .../> in the document + dom::Document* doc = mContent->OwnerDoc(); + nsIContent* buttonEl = nullptr; + if (doc->AllowXULXBL()) { + nsCOMPtr<nsIHTMLCollection> possibleDefaultButtons = + doc->GetElementsByAttribute(u"default"_ns, u"true"_ns); + if (possibleDefaultButtons) { + uint32_t length = possibleDefaultButtons->Length(); + // Check for button in list of default="true" elements + for (uint32_t count = 0; count < length && !buttonEl; count++) { + nsIContent* item = possibleDefaultButtons->Item(count); + RefPtr<nsIDOMXULButtonElement> button = + item->IsElement() ? item->AsElement()->AsXULButton() + : nullptr; + if (button) { + buttonEl = item; + } + } + } + return Relation(mDoc, buttonEl); + } + } + return Relation(); + } + + case RelationType::CONTAINING_DOCUMENT: + return Relation(mDoc); + + case RelationType::CONTAINING_TAB_PANE: { + nsCOMPtr<nsIDocShell> docShell = nsCoreUtils::GetDocShellFor(GetNode()); + if (docShell) { + // Walk up the parent chain without crossing the boundary at which item + // types change, preventing us from walking up out of tab content. + nsCOMPtr<nsIDocShellTreeItem> root; + docShell->GetInProcessSameTypeRootTreeItem(getter_AddRefs(root)); + if (root) { + // If the item type is typeContent, we assume we are in browser tab + // content. Note, this includes content such as about:addons, + // for consistency. + if (root->ItemType() == nsIDocShellTreeItem::typeContent) { + return Relation(nsAccUtils::GetDocAccessibleFor(root)); + } + } + } + return Relation(); + } + + case RelationType::CONTAINING_APPLICATION: + return Relation(ApplicationAcc()); + + case RelationType::DETAILS: + return Relation( + new IDRefsIterator(mDoc, mContent, nsGkAtoms::aria_details)); + + case RelationType::DETAILS_FOR: + return Relation( + new RelatedAccIterator(mDoc, mContent, nsGkAtoms::aria_details)); + + case RelationType::ERRORMSG: + return Relation( + new IDRefsIterator(mDoc, mContent, nsGkAtoms::aria_errormessage)); + + case RelationType::ERRORMSG_FOR: + return Relation( + new RelatedAccIterator(mDoc, mContent, nsGkAtoms::aria_errormessage)); + + default: + return Relation(); + } +} + +void Accessible::GetNativeInterface(void** aNativeAccessible) {} + +void Accessible::DoCommand(nsIContent* aContent, uint32_t aActionIndex) const { + class Runnable final : public mozilla::Runnable { + public: + Runnable(const Accessible* aAcc, nsIContent* aContent, uint32_t aIdx) + : mozilla::Runnable("Runnable"), + mAcc(aAcc), + mContent(aContent), + mIdx(aIdx) {} + + // XXX Cannot mark as MOZ_CAN_RUN_SCRIPT because the base class change + // requires too big changes across a lot of modules. + MOZ_CAN_RUN_SCRIPT_BOUNDARY NS_IMETHOD Run() override { + if (mAcc) { + MOZ_KnownLive(mAcc)->DispatchClickEvent(MOZ_KnownLive(mContent), mIdx); + } + return NS_OK; + } + + void Revoke() { + mAcc = nullptr; + mContent = nullptr; + } + + private: + RefPtr<const Accessible> mAcc; + nsCOMPtr<nsIContent> mContent; + uint32_t mIdx; + }; + + nsIContent* content = aContent ? aContent : mContent.get(); + nsCOMPtr<nsIRunnable> runnable = new Runnable(this, content, aActionIndex); + NS_DispatchToMainThread(runnable); +} + +void Accessible::DispatchClickEvent(nsIContent* aContent, + uint32_t aActionIndex) const { + if (IsDefunct()) return; + + RefPtr<PresShell> presShell = mDoc->PresShellPtr(); + + // Scroll into view. + presShell->ScrollContentIntoView(aContent, ScrollAxis(), ScrollAxis(), + ScrollFlags::ScrollOverflowHidden); + + AutoWeakFrame frame = aContent->GetPrimaryFrame(); + if (!frame) return; + + // Compute x and y coordinates. + nsPoint point; + nsCOMPtr<nsIWidget> widget = frame->GetNearestWidget(point); + if (!widget) return; + + nsSize size = frame->GetSize(); + + RefPtr<nsPresContext> presContext = presShell->GetPresContext(); + int32_t x = presContext->AppUnitsToDevPixels(point.x + size.width / 2); + int32_t y = presContext->AppUnitsToDevPixels(point.y + size.height / 2); + + // Simulate a touch interaction by dispatching touch events with mouse events. + nsCoreUtils::DispatchTouchEvent(eTouchStart, x, y, aContent, frame, presShell, + widget); + nsCoreUtils::DispatchMouseEvent(eMouseDown, x, y, aContent, frame, presShell, + widget); + nsCoreUtils::DispatchTouchEvent(eTouchEnd, x, y, aContent, frame, presShell, + widget); + nsCoreUtils::DispatchMouseEvent(eMouseUp, x, y, aContent, frame, presShell, + widget); +} + +void Accessible::ScrollToPoint(uint32_t aCoordinateType, int32_t aX, + int32_t aY) { + nsIFrame* frame = GetFrame(); + if (!frame) return; + + nsIntPoint coords = + nsAccUtils::ConvertToScreenCoords(aX, aY, aCoordinateType, this); + + nsIFrame* parentFrame = frame; + while ((parentFrame = parentFrame->GetParent())) + nsCoreUtils::ScrollFrameToPoint(parentFrame, frame, coords); +} + +void Accessible::AppendTextTo(nsAString& aText, uint32_t aStartOffset, + uint32_t aLength) { + // Return text representation of non-text accessible within hypertext + // accessible. Text accessible overrides this method to return enclosed text. + if (aStartOffset != 0 || aLength == 0) return; + + nsIFrame* frame = GetFrame(); + if (!frame) { + if (nsCoreUtils::IsDisplayContents(mContent)) { + aText += kEmbeddedObjectChar; + } + return; + } + + MOZ_ASSERT(mParent, + "Called on accessible unbound from tree. Result can be wrong."); + + if (frame->IsBrFrame()) { + aText += kForcedNewLineChar; + } else if (mParent && nsAccUtils::MustPrune(mParent)) { + // Expose the embedded object accessible as imaginary embedded object + // character if its parent hypertext accessible doesn't expose children to + // AT. + aText += kImaginaryEmbeddedObjectChar; + } else { + aText += kEmbeddedObjectChar; + } +} + +void Accessible::Shutdown() { + // Mark the accessible as defunct, invalidate the child count and pointers to + // other accessibles, also make sure none of its children point to this + // parent + mStateFlags |= eIsDefunct; + + int32_t childCount = mChildren.Length(); + for (int32_t childIdx = 0; childIdx < childCount; childIdx++) { + mChildren.ElementAt(childIdx)->UnbindFromParent(); + } + mChildren.Clear(); + + mEmbeddedObjCollector = nullptr; + + if (mParent) mParent->RemoveChild(this); + + mContent = nullptr; + mDoc = nullptr; + if (SelectionMgr() && SelectionMgr()->AccessibleWithCaret(nullptr) == this) + SelectionMgr()->ResetCaretOffset(); +} + +// Accessible protected +void Accessible::ARIAName(nsString& aName) const { + // aria-labelledby now takes precedence over aria-label + nsresult rv = nsTextEquivUtils::GetTextEquivFromIDRefs( + this, nsGkAtoms::aria_labelledby, aName); + if (NS_SUCCEEDED(rv)) { + aName.CompressWhitespace(); + } + + if (aName.IsEmpty() && mContent->IsElement() && + mContent->AsElement()->GetAttr(kNameSpaceID_None, nsGkAtoms::aria_label, + aName)) { + aName.CompressWhitespace(); + } +} + +// Accessible protected +void Accessible::ARIADescription(nsString& aDescription) const { + // aria-describedby takes precedence over aria-description + nsresult rv = nsTextEquivUtils::GetTextEquivFromIDRefs( + this, nsGkAtoms::aria_describedby, aDescription); + if (NS_SUCCEEDED(rv)) { + aDescription.CompressWhitespace(); + } + + if (aDescription.IsEmpty() && mContent->IsElement() && + mContent->AsElement()->GetAttr( + kNameSpaceID_None, nsGkAtoms::aria_description, aDescription)) { + aDescription.CompressWhitespace(); + } +} + +// Accessible protected +ENameValueFlag Accessible::NativeName(nsString& aName) const { + if (mContent->IsHTMLElement()) { + Accessible* label = nullptr; + HTMLLabelIterator iter(Document(), this); + while ((label = iter.Next())) { + nsTextEquivUtils::AppendTextEquivFromContent(this, label->GetContent(), + &aName); + aName.CompressWhitespace(); + } + + if (!aName.IsEmpty()) return eNameOK; + + NameFromAssociatedXULLabel(mDoc, mContent, aName); + if (!aName.IsEmpty()) { + return eNameOK; + } + + nsTextEquivUtils::GetNameFromSubtree(this, aName); + return aName.IsEmpty() ? eNameOK : eNameFromSubtree; + } + + if (mContent->IsXULElement()) { + XULElmName(mDoc, mContent, aName); + if (!aName.IsEmpty()) return eNameOK; + + nsTextEquivUtils::GetNameFromSubtree(this, aName); + return aName.IsEmpty() ? eNameOK : eNameFromSubtree; + } + + if (mContent->IsSVGElement()) { + // If user agents need to choose among multiple 'desc' or 'title' + // elements for processing, the user agent shall choose the first one. + for (nsIContent* childElm = mContent->GetFirstChild(); childElm; + childElm = childElm->GetNextSibling()) { + if (childElm->IsSVGElement(nsGkAtoms::title)) { + nsTextEquivUtils::AppendTextEquivFromContent(this, childElm, &aName); + return eNameOK; + } + } + } + + return eNameOK; +} + +// Accessible protected +void Accessible::NativeDescription(nsString& aDescription) { + bool isXUL = mContent->IsXULElement(); + if (isXUL) { + // Try XUL <description control="[id]">description text</description> + XULDescriptionIterator iter(Document(), mContent); + Accessible* descr = nullptr; + while ((descr = iter.Next())) { + nsTextEquivUtils::AppendTextEquivFromContent(this, descr->GetContent(), + &aDescription); + } + } +} + +// Accessible protected +void Accessible::BindToParent(Accessible* aParent, uint32_t aIndexInParent) { + MOZ_ASSERT(aParent, "This method isn't used to set null parent"); + MOZ_ASSERT(!mParent, "The child was expected to be moved"); + +#ifdef A11Y_LOG + if (mParent) { + logging::TreeInfo("BindToParent: stealing accessible", 0, "old parent", + mParent, "new parent", aParent, "child", this, nullptr); + } +#endif + + mParent = aParent; + mIndexInParent = aIndexInParent; + + // Note: this is currently only used for richlistitems and their children. + if (mParent->HasNameDependentParent() || mParent->IsXULListItem()) + mContextFlags |= eHasNameDependentParent; + else + mContextFlags &= ~eHasNameDependentParent; + + mContextFlags |= + static_cast<uint32_t>((mParent->IsAlert() || mParent->IsInsideAlert())) & + eInsideAlert; + + // if a new column header is being added, invalidate the table's header cache. + TableCellAccessible* cell = AsTableCell(); + if (cell && Role() == roles::COLUMNHEADER) { + TableAccessible* table = cell->Table(); + if (table) { + table->GetHeaderCache().Clear(); + } + } +} + +// Accessible protected +void Accessible::UnbindFromParent() { + mParent = nullptr; + mIndexInParent = -1; + mInt.mIndexOfEmbeddedChild = -1; + if (IsProxy()) MOZ_CRASH("this should never be called on proxy wrappers"); + + delete mBits.groupInfo; + mBits.groupInfo = nullptr; + mContextFlags &= ~eHasNameDependentParent & ~eInsideAlert; +} + +//////////////////////////////////////////////////////////////////////////////// +// Accessible public methods + +RootAccessible* Accessible::RootAccessible() const { + nsCOMPtr<nsIDocShell> docShell = nsCoreUtils::GetDocShellFor(GetNode()); + NS_ASSERTION(docShell, "No docshell for mContent"); + if (!docShell) { + return nullptr; + } + + nsCOMPtr<nsIDocShellTreeItem> root; + docShell->GetInProcessRootTreeItem(getter_AddRefs(root)); + NS_ASSERTION(root, "No root content tree item"); + if (!root) { + return nullptr; + } + + DocAccessible* docAcc = nsAccUtils::GetDocAccessibleFor(root); + return docAcc ? docAcc->AsRoot() : nullptr; +} + +nsIFrame* Accessible::GetFrame() const { + return mContent ? mContent->GetPrimaryFrame() : nullptr; +} + +nsINode* Accessible::GetNode() const { return mContent; } + +dom::Element* Accessible::Elm() const { + return dom::Element::FromNodeOrNull(mContent); +} + +void Accessible::Language(nsAString& aLanguage) { + aLanguage.Truncate(); + + if (!mDoc) return; + + nsCoreUtils::GetLanguageFor(mContent, nullptr, aLanguage); + if (aLanguage.IsEmpty()) { // Nothing found, so use document's language + mDoc->DocumentNode()->GetHeaderData(nsGkAtoms::headerContentLanguage, + aLanguage); + } +} + +bool Accessible::InsertChildAt(uint32_t aIndex, Accessible* aChild) { + if (!aChild) return false; + + if (aIndex == mChildren.Length()) { + // XXX(Bug 1631371) Check if this should use a fallible operation as it + // pretended earlier. + mChildren.AppendElement(aChild); + } else { + // XXX(Bug 1631371) Check if this should use a fallible operation as it + // pretended earlier. + mChildren.InsertElementAt(aIndex, aChild); + + MOZ_ASSERT(mStateFlags & eKidsMutating, "Illicit children change"); + + for (uint32_t idx = aIndex + 1; idx < mChildren.Length(); idx++) { + mChildren[idx]->mIndexInParent = idx; + } + } + + if (aChild->IsText()) { + mStateFlags |= eHasTextKids; + } + + aChild->BindToParent(this, aIndex); + return true; +} + +bool Accessible::RemoveChild(Accessible* aChild) { + MOZ_DIAGNOSTIC_ASSERT(aChild, "No child was given"); + MOZ_DIAGNOSTIC_ASSERT(aChild->mParent, "No parent"); + MOZ_DIAGNOSTIC_ASSERT(aChild->mParent == this, "Wrong parent"); + MOZ_DIAGNOSTIC_ASSERT(aChild->mIndexInParent != -1, + "Unbound child was given"); + MOZ_DIAGNOSTIC_ASSERT((mStateFlags & eKidsMutating) || aChild->IsDefunct() || + aChild->IsDoc() || IsApplication(), + "Illicit children change"); + + int32_t index = static_cast<uint32_t>(aChild->mIndexInParent); + if (mChildren.SafeElementAt(index) != aChild) { + MOZ_ASSERT_UNREACHABLE("A wrong child index"); + index = mChildren.IndexOf(aChild); + if (index == -1) { + MOZ_ASSERT_UNREACHABLE("No child was found"); + return false; + } + } + + aChild->UnbindFromParent(); + mChildren.RemoveElementAt(index); + + for (uint32_t idx = index; idx < mChildren.Length(); idx++) { + mChildren[idx]->mIndexInParent = idx; + } + + return true; +} + +void Accessible::RelocateChild(uint32_t aNewIndex, Accessible* aChild) { + MOZ_DIAGNOSTIC_ASSERT(aChild, "No child was given"); + MOZ_DIAGNOSTIC_ASSERT(aChild->mParent == this, + "A child from different subtree was given"); + MOZ_DIAGNOSTIC_ASSERT(aChild->mIndexInParent != -1, + "Unbound child was given"); + MOZ_DIAGNOSTIC_ASSERT( + aChild->mParent->GetChildAt(aChild->mIndexInParent) == aChild, + "Wrong index in parent"); + MOZ_DIAGNOSTIC_ASSERT( + static_cast<uint32_t>(aChild->mIndexInParent) != aNewIndex, + "No move, same index"); + MOZ_DIAGNOSTIC_ASSERT(aNewIndex <= mChildren.Length(), + "Wrong new index was given"); + + RefPtr<AccHideEvent> hideEvent = new AccHideEvent(aChild, false); + if (mDoc->Controller()->QueueMutationEvent(hideEvent)) { + aChild->SetHideEventTarget(true); + } + + mEmbeddedObjCollector = nullptr; + mChildren.RemoveElementAt(aChild->mIndexInParent); + + uint32_t startIdx = aNewIndex, endIdx = aChild->mIndexInParent; + + // If the child is moved after its current position. + if (static_cast<uint32_t>(aChild->mIndexInParent) < aNewIndex) { + startIdx = aChild->mIndexInParent; + if (aNewIndex == mChildren.Length() + 1) { + // The child is moved to the end. + mChildren.AppendElement(aChild); + endIdx = mChildren.Length() - 1; + } else { + mChildren.InsertElementAt(aNewIndex - 1, aChild); + endIdx = aNewIndex; + } + } else { + // The child is moved prior its current position. + mChildren.InsertElementAt(aNewIndex, aChild); + } + + for (uint32_t idx = startIdx; idx <= endIdx; idx++) { + mChildren[idx]->mIndexInParent = idx; + mChildren[idx]->mInt.mIndexOfEmbeddedChild = -1; + } + + for (uint32_t idx = 0; idx < mChildren.Length(); idx++) { + mChildren[idx]->mStateFlags |= eGroupInfoDirty; + } + + RefPtr<AccShowEvent> showEvent = new AccShowEvent(aChild); + DebugOnly<bool> added = mDoc->Controller()->QueueMutationEvent(showEvent); + MOZ_ASSERT(added); + aChild->SetShowEventTarget(true); +} + +Accessible* Accessible::GetChildAt(uint32_t aIndex) const { + Accessible* child = mChildren.SafeElementAt(aIndex, nullptr); + if (!child) return nullptr; + +#ifdef DEBUG + Accessible* realParent = child->mParent; + NS_ASSERTION(!realParent || realParent == this, + "Two accessibles have the same first child accessible!"); +#endif + + return child; +} + +uint32_t Accessible::ChildCount() const { return mChildren.Length(); } + +int32_t Accessible::IndexInParent() const { return mIndexInParent; } + +uint32_t Accessible::EmbeddedChildCount() { + if (mStateFlags & eHasTextKids) { + if (!mEmbeddedObjCollector) + mEmbeddedObjCollector.reset(new EmbeddedObjCollector(this)); + return mEmbeddedObjCollector->Count(); + } + + return ChildCount(); +} + +Accessible* Accessible::GetEmbeddedChildAt(uint32_t aIndex) { + if (mStateFlags & eHasTextKids) { + if (!mEmbeddedObjCollector) + mEmbeddedObjCollector.reset(new EmbeddedObjCollector(this)); + return mEmbeddedObjCollector.get() + ? mEmbeddedObjCollector->GetAccessibleAt(aIndex) + : nullptr; + } + + return GetChildAt(aIndex); +} + +int32_t Accessible::GetIndexOfEmbeddedChild(Accessible* aChild) { + if (mStateFlags & eHasTextKids) { + if (!mEmbeddedObjCollector) + mEmbeddedObjCollector.reset(new EmbeddedObjCollector(this)); + return mEmbeddedObjCollector.get() + ? mEmbeddedObjCollector->GetIndexAt(aChild) + : -1; + } + + return GetIndexOf(aChild); +} + +//////////////////////////////////////////////////////////////////////////////// +// HyperLinkAccessible methods + +bool Accessible::IsLink() const { + // Every embedded accessible within hypertext accessible implements + // hyperlink interface. + return mParent && mParent->IsHyperText() && !IsText(); +} + +uint32_t Accessible::StartOffset() { + MOZ_ASSERT(IsLink(), "StartOffset is called not on hyper link!"); + + HyperTextAccessible* hyperText = mParent ? mParent->AsHyperText() : nullptr; + return hyperText ? hyperText->GetChildOffset(this) : 0; +} + +uint32_t Accessible::EndOffset() { + MOZ_ASSERT(IsLink(), "EndOffset is called on not hyper link!"); + + HyperTextAccessible* hyperText = mParent ? mParent->AsHyperText() : nullptr; + return hyperText ? (hyperText->GetChildOffset(this) + 1) : 0; +} + +uint32_t Accessible::AnchorCount() { + MOZ_ASSERT(IsLink(), "AnchorCount is called on not hyper link!"); + return 1; +} + +Accessible* Accessible::AnchorAt(uint32_t aAnchorIndex) { + MOZ_ASSERT(IsLink(), "GetAnchor is called on not hyper link!"); + return aAnchorIndex == 0 ? this : nullptr; +} + +already_AddRefed<nsIURI> Accessible::AnchorURIAt(uint32_t aAnchorIndex) const { + MOZ_ASSERT(IsLink(), "AnchorURIAt is called on not hyper link!"); + return nullptr; +} + +void Accessible::ToTextPoint(HyperTextAccessible** aContainer, int32_t* aOffset, + bool aIsBefore) const { + if (IsHyperText()) { + *aContainer = const_cast<Accessible*>(this)->AsHyperText(); + *aOffset = aIsBefore ? 0 : (*aContainer)->CharacterCount(); + return; + } + + const Accessible* child = nullptr; + const Accessible* parent = this; + do { + child = parent; + parent = parent->Parent(); + } while (parent && !parent->IsHyperText()); + + if (parent) { + *aContainer = const_cast<Accessible*>(parent)->AsHyperText(); + *aOffset = (*aContainer) + ->GetChildOffset(child->IndexInParent() + + static_cast<int32_t>(!aIsBefore)); + } +} + +//////////////////////////////////////////////////////////////////////////////// +// SelectAccessible + +void Accessible::SelectedItems(nsTArray<Accessible*>* aItems) { + AccIterator iter(this, filters::GetSelected); + Accessible* selected = nullptr; + while ((selected = iter.Next())) aItems->AppendElement(selected); +} + +uint32_t Accessible::SelectedItemCount() { + uint32_t count = 0; + AccIterator iter(this, filters::GetSelected); + Accessible* selected = nullptr; + while ((selected = iter.Next())) ++count; + + return count; +} + +Accessible* Accessible::GetSelectedItem(uint32_t aIndex) { + AccIterator iter(this, filters::GetSelected); + Accessible* selected = nullptr; + + uint32_t index = 0; + while ((selected = iter.Next()) && index < aIndex) index++; + + return selected; +} + +bool Accessible::IsItemSelected(uint32_t aIndex) { + uint32_t index = 0; + AccIterator iter(this, filters::GetSelectable); + Accessible* selected = nullptr; + while ((selected = iter.Next()) && index < aIndex) index++; + + return selected && selected->State() & states::SELECTED; +} + +bool Accessible::AddItemToSelection(uint32_t aIndex) { + uint32_t index = 0; + AccIterator iter(this, filters::GetSelectable); + Accessible* selected = nullptr; + while ((selected = iter.Next()) && index < aIndex) index++; + + if (selected) selected->SetSelected(true); + + return static_cast<bool>(selected); +} + +bool Accessible::RemoveItemFromSelection(uint32_t aIndex) { + uint32_t index = 0; + AccIterator iter(this, filters::GetSelectable); + Accessible* selected = nullptr; + while ((selected = iter.Next()) && index < aIndex) index++; + + if (selected) selected->SetSelected(false); + + return static_cast<bool>(selected); +} + +bool Accessible::SelectAll() { + bool success = false; + Accessible* selectable = nullptr; + + AccIterator iter(this, filters::GetSelectable); + while ((selectable = iter.Next())) { + success = true; + selectable->SetSelected(true); + } + return success; +} + +bool Accessible::UnselectAll() { + bool success = false; + Accessible* selected = nullptr; + + AccIterator iter(this, filters::GetSelected); + while ((selected = iter.Next())) { + success = true; + selected->SetSelected(false); + } + return success; +} + +//////////////////////////////////////////////////////////////////////////////// +// Widgets + +bool Accessible::IsWidget() const { return false; } + +bool Accessible::IsActiveWidget() const { + if (FocusMgr()->HasDOMFocus(mContent)) return true; + + // If text entry of combobox widget has a focus then the combobox widget is + // active. + const nsRoleMapEntry* roleMapEntry = ARIARoleMap(); + if (roleMapEntry && roleMapEntry->Is(nsGkAtoms::combobox)) { + uint32_t childCount = ChildCount(); + for (uint32_t idx = 0; idx < childCount; idx++) { + Accessible* child = mChildren.ElementAt(idx); + if (child->Role() == roles::ENTRY) + return FocusMgr()->HasDOMFocus(child->GetContent()); + } + } + + return false; +} + +bool Accessible::AreItemsOperable() const { + return HasOwnContent() && mContent->IsElement() && + mContent->AsElement()->HasAttr(kNameSpaceID_None, + nsGkAtoms::aria_activedescendant); +} + +Accessible* Accessible::CurrentItem() const { + // Check for aria-activedescendant, which changes which element has focus. + // For activedescendant, the ARIA spec does not require that the user agent + // checks whether pointed node is actually a DOM descendant of the element + // with the aria-activedescendant attribute. + nsAutoString id; + if (HasOwnContent() && mContent->IsElement() && + mContent->AsElement()->GetAttr(kNameSpaceID_None, + nsGkAtoms::aria_activedescendant, id)) { + dom::Element* activeDescendantElm = IDRefsIterator::GetElem(mContent, id); + if (activeDescendantElm) { + if (mContent->IsInclusiveDescendantOf(activeDescendantElm)) { + // Don't want a cyclical descendant relationship. That would be bad. + return nullptr; + } + + DocAccessible* document = Document(); + if (document) return document->GetAccessible(activeDescendantElm); + } + } + return nullptr; +} + +void Accessible::SetCurrentItem(const Accessible* aItem) { + nsAtom* id = aItem->GetContent()->GetID(); + if (id) { + nsAutoString idStr; + id->ToString(idStr); + mContent->AsElement()->SetAttr( + kNameSpaceID_None, nsGkAtoms::aria_activedescendant, idStr, true); + } +} + +Accessible* Accessible::ContainerWidget() const { + if (HasARIARole() && mContent->HasID()) { + for (Accessible* parent = Parent(); parent; parent = parent->Parent()) { + nsIContent* parentContent = parent->GetContent(); + if (parentContent && parentContent->IsElement() && + parentContent->AsElement()->HasAttr( + kNameSpaceID_None, nsGkAtoms::aria_activedescendant)) { + return parent; + } + + // Don't cross DOM document boundaries. + if (parent->IsDoc()) break; + } + } + return nullptr; +} + +void Accessible::Announce(const nsAString& aAnnouncement, uint16_t aPriority) { + RefPtr<AccAnnouncementEvent> event = + new AccAnnouncementEvent(this, aAnnouncement, aPriority); + nsEventShell::FireEvent(event); +} + +//////////////////////////////////////////////////////////////////////////////// +// Accessible protected methods + +void Accessible::LastRelease() { + // First cleanup if needed... + if (mDoc) { + Shutdown(); + NS_ASSERTION(!mDoc, + "A Shutdown() impl forgot to call its parent's Shutdown?"); + } + // ... then die. + delete this; +} + +Accessible* Accessible::GetSiblingAtOffset(int32_t aOffset, + nsresult* aError) const { + if (!mParent || mIndexInParent == -1) { + if (aError) *aError = NS_ERROR_UNEXPECTED; + + return nullptr; + } + + if (aError && + mIndexInParent + aOffset >= static_cast<int32_t>(mParent->ChildCount())) { + *aError = NS_OK; // fail peacefully + return nullptr; + } + + Accessible* child = mParent->GetChildAt(mIndexInParent + aOffset); + if (aError && !child) *aError = NS_ERROR_UNEXPECTED; + + return child; +} + +double Accessible::AttrNumericValue(nsAtom* aAttr) const { + const nsRoleMapEntry* roleMapEntry = ARIARoleMap(); + if (!roleMapEntry || roleMapEntry->valueRule == eNoValue) + return UnspecifiedNaN<double>(); + + nsAutoString attrValue; + if (!mContent->IsElement() || + !mContent->AsElement()->GetAttr(kNameSpaceID_None, aAttr, attrValue)) + return UnspecifiedNaN<double>(); + + nsresult error = NS_OK; + double value = attrValue.ToDouble(&error); + return NS_FAILED(error) ? UnspecifiedNaN<double>() : value; +} + +uint32_t Accessible::GetActionRule() const { + if (!HasOwnContent() || (InteractiveState() & states::UNAVAILABLE)) + return eNoAction; + + // Return "click" action on elements that have an attached popup menu. + if (mContent->IsXULElement()) + if (mContent->AsElement()->HasAttr(kNameSpaceID_None, nsGkAtoms::popup)) + return eClickAction; + + // Has registered 'click' event handler. + bool isOnclick = nsCoreUtils::HasClickListener(mContent); + + if (isOnclick) return eClickAction; + + // Get an action based on ARIA role. + const nsRoleMapEntry* roleMapEntry = ARIARoleMap(); + if (roleMapEntry && roleMapEntry->actionRule != eNoAction) + return roleMapEntry->actionRule; + + // Get an action based on ARIA attribute. + if (nsAccUtils::HasDefinedARIAToken(mContent, nsGkAtoms::aria_expanded)) + return eExpandAction; + + return eNoAction; +} + +AccGroupInfo* Accessible::GetGroupInfo() const { + if (IsProxy()) MOZ_CRASH("This should never be called on proxy wrappers"); + + if (mBits.groupInfo) { + if (HasDirtyGroupInfo()) { + mBits.groupInfo->Update(); + mStateFlags &= ~eGroupInfoDirty; + } + + return mBits.groupInfo; + } + + mBits.groupInfo = AccGroupInfo::CreateGroupInfo(this); + mStateFlags &= ~eGroupInfoDirty; + return mBits.groupInfo; +} + +void Accessible::MaybeFireFocusableStateChange(bool aPreviouslyFocusable) { + bool isFocusable = (State() & states::FOCUSABLE); + if (isFocusable != aPreviouslyFocusable) { + RefPtr<AccEvent> focusableChangeEvent = + new AccStateChangeEvent(this, states::FOCUSABLE, isFocusable); + mDoc->FireDelayedEvent(focusableChangeEvent); + } +} + +void Accessible::GetPositionAndSizeInternal(int32_t* aPosInSet, + int32_t* aSetSize) { + AccGroupInfo* groupInfo = GetGroupInfo(); + if (groupInfo) { + *aPosInSet = groupInfo->PosInSet(); + *aSetSize = groupInfo->SetSize(); + } +} + +int32_t Accessible::GetLevelInternal() { + int32_t level = nsAccUtils::GetDefaultLevel(this); + + if (!IsBoundToParent()) return level; + + roles::Role role = Role(); + if (role == roles::OUTLINEITEM) { + // Always expose 'level' attribute for 'outlineitem' accessible. The number + // of nested 'grouping' accessibles containing 'outlineitem' accessible is + // its level. + level = 1; + + Accessible* parent = this; + while ((parent = parent->Parent())) { + roles::Role parentRole = parent->Role(); + + if (parentRole == roles::OUTLINE) break; + if (parentRole == roles::GROUPING) ++level; + } + + } else if (role == roles::LISTITEM) { + // Expose 'level' attribute on nested lists. We support two hierarchies: + // a) list -> listitem -> list -> listitem (nested list is a last child + // of listitem of the parent list); + // b) list -> listitem -> group -> listitem (nested listitems are contained + // by group that is a last child of the parent listitem). + + // Calculate 'level' attribute based on number of parent listitems. + level = 0; + Accessible* parent = this; + while ((parent = parent->Parent())) { + roles::Role parentRole = parent->Role(); + + if (parentRole == roles::LISTITEM) + ++level; + else if (parentRole != roles::LIST && parentRole != roles::GROUPING) + break; + } + + if (level == 0) { + // If this listitem is on top of nested lists then expose 'level' + // attribute. + parent = Parent(); + uint32_t siblingCount = parent->ChildCount(); + for (uint32_t siblingIdx = 0; siblingIdx < siblingCount; siblingIdx++) { + Accessible* sibling = parent->GetChildAt(siblingIdx); + + Accessible* siblingChild = sibling->LastChild(); + if (siblingChild) { + roles::Role lastChildRole = siblingChild->Role(); + if (lastChildRole == roles::LIST || lastChildRole == roles::GROUPING) + return 1; + } + } + } else { + ++level; // level is 1-index based + } + } else if (role == roles::COMMENT) { + // For comments, count the ancestor elements with the same role to get the + // level. + level = 1; + + Accessible* parent = this; + while ((parent = parent->Parent())) { + roles::Role parentRole = parent->Role(); + if (parentRole == roles::COMMENT) { + ++level; + } + } + } + + return level; +} + +void Accessible::StaticAsserts() const { + static_assert(eLastStateFlag <= (1 << kStateFlagsBits) - 1, + "Accessible::mStateFlags was oversized by eLastStateFlag!"); + static_assert(eLastAccType <= (1 << kTypeBits) - 1, + "Accessible::mType was oversized by eLastAccType!"); + static_assert(eLastContextFlag <= (1 << kContextFlagsBits) - 1, + "Accessible::mContextFlags was oversized by eLastContextFlag!"); + static_assert( + eLastAccGenericType <= (1 << kGenericTypesBits) - 1, + "Accessible::mGenericType was oversized by eLastAccGenericType!"); +} + +//////////////////////////////////////////////////////////////////////////////// +// KeyBinding class + +// static +uint32_t KeyBinding::AccelModifier() { + switch (WidgetInputEvent::AccelModifier()) { + case MODIFIER_ALT: + return kAlt; + case MODIFIER_CONTROL: + return kControl; + case MODIFIER_META: + return kMeta; + case MODIFIER_OS: + return kOS; + default: + MOZ_CRASH("Handle the new result of WidgetInputEvent::AccelModifier()"); + return 0; + } +} + +void KeyBinding::ToPlatformFormat(nsAString& aValue) const { + nsCOMPtr<nsIStringBundle> keyStringBundle; + nsCOMPtr<nsIStringBundleService> stringBundleService = + mozilla::services::GetStringBundleService(); + if (stringBundleService) + stringBundleService->CreateBundle( + "chrome://global-platform/locale/platformKeys.properties", + getter_AddRefs(keyStringBundle)); + + if (!keyStringBundle) return; + + nsAutoString separator; + keyStringBundle->GetStringFromName("MODIFIER_SEPARATOR", separator); + + nsAutoString modifierName; + if (mModifierMask & kControl) { + keyStringBundle->GetStringFromName("VK_CONTROL", modifierName); + + aValue.Append(modifierName); + aValue.Append(separator); + } + + if (mModifierMask & kAlt) { + keyStringBundle->GetStringFromName("VK_ALT", modifierName); + + aValue.Append(modifierName); + aValue.Append(separator); + } + + if (mModifierMask & kShift) { + keyStringBundle->GetStringFromName("VK_SHIFT", modifierName); + + aValue.Append(modifierName); + aValue.Append(separator); + } + + if (mModifierMask & kMeta) { + keyStringBundle->GetStringFromName("VK_META", modifierName); + + aValue.Append(modifierName); + aValue.Append(separator); + } + + aValue.Append(mKey); +} + +void KeyBinding::ToAtkFormat(nsAString& aValue) const { + nsAutoString modifierName; + if (mModifierMask & kControl) aValue.AppendLiteral("<Control>"); + + if (mModifierMask & kAlt) aValue.AppendLiteral("<Alt>"); + + if (mModifierMask & kShift) aValue.AppendLiteral("<Shift>"); + + if (mModifierMask & kMeta) aValue.AppendLiteral("<Meta>"); + + aValue.Append(mKey); +} diff --git a/accessible/generic/Accessible.h b/accessible/generic/Accessible.h new file mode 100644 index 0000000000..a867cd42c2 --- /dev/null +++ b/accessible/generic/Accessible.h @@ -0,0 +1,1270 @@ +/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +#ifndef _Accessible_H_ +#define _Accessible_H_ + +#include "mozilla/a11y/AccTypes.h" +#include "mozilla/a11y/RelationType.h" +#include "mozilla/a11y/Role.h" +#include "mozilla/a11y/States.h" + +#include "mozilla/UniquePtr.h" + +#include "nsIContent.h" +#include "nsTArray.h" +#include "nsRefPtrHashtable.h" +#include "nsRect.h" + +struct nsRoleMapEntry; + +class nsIFrame; +class nsIPersistentProperties; + +namespace mozilla::dom { +class Element; +} + +namespace mozilla { +namespace a11y { + +class Accessible; +class AccEvent; +class AccGroupInfo; +class ApplicationAccessible; +class DocAccessible; +class EmbeddedObjCollector; +class EventTree; +class HTMLImageMapAccessible; +class HTMLLIAccessible; +class HTMLLinkAccessible; +class HyperTextAccessible; +class ImageAccessible; +class KeyBinding; +class OuterDocAccessible; +class ProxyAccessible; +class Relation; +class RootAccessible; +class TableAccessible; +class TableCellAccessible; +class TextLeafAccessible; +class XULLabelAccessible; +class XULTreeAccessible; + +#ifdef A11Y_LOG +namespace logging { +typedef const char* (*GetTreePrefix)(void* aData, Accessible*); +void Tree(const char* aTitle, const char* aMsgText, Accessible* aRoot, + GetTreePrefix aPrefixFunc, void* GetTreePrefixData); +}; // namespace logging +#endif + +/** + * Name type flags. + */ +enum ENameValueFlag { + /** + * Name either + * a) present (not empty): !name.IsEmpty() + * b) no name (was missed): name.IsVoid() + */ + eNameOK, + + /** + * Name was left empty by the author on purpose: + * name.IsEmpty() && !name.IsVoid(). + */ + eNoNameOnPurpose, + + /** + * Name was computed from the subtree. + */ + eNameFromSubtree, + + /** + * Tooltip was used as a name. + */ + eNameFromTooltip +}; + +/** + * Group position (level, position in set and set size). + */ +struct GroupPos { + GroupPos() : level(0), posInSet(0), setSize(0) {} + GroupPos(int32_t aLevel, int32_t aPosInSet, int32_t aSetSize) + : level(aLevel), posInSet(aPosInSet), setSize(aSetSize) {} + + int32_t level; + int32_t posInSet; + int32_t setSize; +}; + +/** + * An index type. Assert if out of range value was attempted to be used. + */ +class index_t { + public: + MOZ_IMPLICIT index_t(int32_t aVal) : mVal(aVal) {} + + operator uint32_t() const { + MOZ_ASSERT(mVal >= 0, "Attempt to use wrong index!"); + return mVal; + } + + bool IsValid() const { return mVal >= 0; } + + private: + int32_t mVal; +}; + +typedef nsRefPtrHashtable<nsPtrHashKey<const void>, Accessible> + AccessibleHashtable; + +#define NS_ACCESSIBLE_IMPL_IID \ + { /* 133c8bf4-4913-4355-bd50-426bd1d6e1ad */ \ + 0x133c8bf4, 0x4913, 0x4355, { \ + 0xbd, 0x50, 0x42, 0x6b, 0xd1, 0xd6, 0xe1, 0xad \ + } \ + } + +class Accessible : public nsISupports { + public: + Accessible(nsIContent* aContent, DocAccessible* aDoc); + + NS_DECL_CYCLE_COLLECTING_ISUPPORTS + NS_DECL_CYCLE_COLLECTION_CLASS(Accessible) + + NS_DECLARE_STATIC_IID_ACCESSOR(NS_ACCESSIBLE_IMPL_IID) + + ////////////////////////////////////////////////////////////////////////////// + // Public methods + + /** + * Return the document accessible for this accessible. + */ + DocAccessible* Document() const { return mDoc; } + + /** + * Return the root document accessible for this accessible. + */ + a11y::RootAccessible* RootAccessible() const; + + /** + * Return frame for this accessible. + */ + virtual nsIFrame* GetFrame() const; + + /** + * Return DOM node associated with the accessible. + */ + virtual nsINode* GetNode() const; + + nsIContent* GetContent() const { return mContent; } + dom::Element* Elm() const; + + /** + * Return node type information of DOM node associated with the accessible. + */ + bool IsContent() const { return GetNode() && GetNode()->IsContent(); } + + /** + * Return the unique identifier of the accessible. + */ + void* UniqueID() { return static_cast<void*>(this); } + + /** + * Return language associated with the accessible. + */ + void Language(nsAString& aLocale); + + /** + * Get the description of this accessible. + */ + virtual void Description(nsString& aDescription); + + /** + * Get the value of this accessible. + */ + virtual void Value(nsString& aValue) const; + + /** + * Get help string for the accessible. + */ + void Help(nsString& aHelp) const { aHelp.Truncate(); } + + /** + * Get the name of this accessible. + * + * Note: aName.IsVoid() when name was left empty by the author on purpose. + * aName.IsEmpty() when the author missed name, AT can try to repair a name. + */ + virtual ENameValueFlag Name(nsString& aName) const; + + /** + * Maps ARIA state attributes to state of accessible. Note the given state + * argument should hold states for accessible before you pass it into this + * method. + * + * @param [in/out] where to fill the states into. + */ + virtual void ApplyARIAState(uint64_t* aState) const; + + /** + * Return enumerated accessible role (see constants in Role.h). + */ + mozilla::a11y::role Role() const; + + /** + * Return true if ARIA role is specified on the element. + */ + bool HasARIARole() const; + bool IsARIARole(nsAtom* aARIARole) const; + bool HasStrongARIARole() const; + + /** + * Retrun ARIA role map if any. + */ + const nsRoleMapEntry* ARIARoleMap() const; + + /** + * Return accessible role specified by ARIA (see constants in + * roles). + */ + mozilla::a11y::role ARIARole(); + + /** + * Return a landmark role if applied. + */ + virtual nsAtom* LandmarkRole() const; + + /** + * Returns enumerated accessible role from native markup (see constants in + * Role.h). Doesn't take into account ARIA roles. + */ + virtual mozilla::a11y::role NativeRole() const; + + /** + * Return all states of accessible (including ARIA states). + */ + virtual uint64_t State(); + + /** + * Return interactive states present on the accessible + * (@see NativeInteractiveState). + */ + uint64_t InteractiveState() const { + uint64_t state = NativeInteractiveState(); + ApplyARIAState(&state); + return state; + } + + /** + * Return link states present on the accessible. + */ + uint64_t LinkState() const { + uint64_t state = NativeLinkState(); + ApplyARIAState(&state); + return state; + } + + /** + * Return the states of accessible, not taking into account ARIA states. + * Use State() to get complete set of states. + */ + virtual uint64_t NativeState() const; + + /** + * Return native interactice state (unavailable, focusable or selectable). + */ + virtual uint64_t NativeInteractiveState() const; + + /** + * Return native link states present on the accessible. + */ + virtual uint64_t NativeLinkState() const; + + /** + * Return bit set of invisible and offscreen states. + */ + uint64_t VisibilityState() const; + + /** + * Return true if native unavailable state present. + */ + virtual bool NativelyUnavailable() const; + + /** + * Return object attributes for the accessible. + */ + virtual already_AddRefed<nsIPersistentProperties> Attributes(); + + /** + * Return group position (level, position in set and set size). + */ + virtual mozilla::a11y::GroupPos GroupPosition(); + + /** + * Used by ChildAtPoint() method to get direct or deepest child at point. + */ + enum EWhichChildAtPoint { eDirectChild, eDeepestChild }; + + /** + * Return direct or deepest child at the given point. + * + * @param aX [in] x coordinate relative screen + * @param aY [in] y coordinate relative screen + * @param aWhichChild [in] flag points if deepest or direct child + * should be returned + */ + virtual Accessible* ChildAtPoint(int32_t aX, int32_t aY, + EWhichChildAtPoint aWhichChild); + + /** + * Return the focused child if any. + */ + virtual Accessible* FocusedChild(); + + /** + * Return calculated group level based on accessible hierarchy. + */ + virtual int32_t GetLevelInternal(); + + /** + * Calculate position in group and group size ('posinset' and 'setsize') based + * on accessible hierarchy. + * + * @param aPosInSet [out] accessible position in the group + * @param aSetSize [out] the group size + */ + virtual void GetPositionAndSizeInternal(int32_t* aPosInSet, + int32_t* aSetSize); + + /** + * Get the relation of the given type. + */ + virtual Relation RelationByType(RelationType aType) const; + + ////////////////////////////////////////////////////////////////////////////// + // Initializing methods + + /** + * Shutdown this accessible object. + */ + virtual void Shutdown(); + + /** + * Set the ARIA role map entry for a new accessible. + */ + void SetRoleMapEntry(const nsRoleMapEntry* aRoleMapEntry); + + /** + * Append/insert/remove a child. Return true if operation was successful. + */ + bool AppendChild(Accessible* aChild) { + return InsertChildAt(mChildren.Length(), aChild); + } + virtual bool InsertChildAt(uint32_t aIndex, Accessible* aChild); + + /** + * Inserts a child after given sibling. If the child cannot be inserted, + * then the child is unbound from the document, and false is returned. Make + * sure to null out any references on the child object as it may be destroyed. + */ + bool InsertAfter(Accessible* aNewChild, Accessible* aRefChild); + + virtual bool RemoveChild(Accessible* aChild); + + /** + * Reallocates the child within its parent. + */ + virtual void RelocateChild(uint32_t aNewIndex, Accessible* aChild); + + ////////////////////////////////////////////////////////////////////////////// + // Accessible tree traverse methods + + /** + * Return parent accessible. + */ + Accessible* Parent() const { return mParent; } + + /** + * Return child accessible at the given index. + */ + virtual Accessible* GetChildAt(uint32_t aIndex) const; + + /** + * Return child accessible count. + */ + virtual uint32_t ChildCount() const; + + /** + * Return index of the given child accessible. + */ + int32_t GetIndexOf(const Accessible* aChild) const { + return (aChild->mParent != this) ? -1 : aChild->IndexInParent(); + } + + /** + * Return index in parent accessible. + */ + virtual int32_t IndexInParent() const; + + /** + * Return true if accessible has children; + */ + bool HasChildren() const { return !!GetChildAt(0); } + + /** + * Return first/last/next/previous sibling of the accessible. + */ + inline Accessible* NextSibling() const { return GetSiblingAtOffset(1); } + inline Accessible* PrevSibling() const { return GetSiblingAtOffset(-1); } + inline Accessible* FirstChild() const { return GetChildAt(0); } + inline Accessible* LastChild() const { + uint32_t childCount = ChildCount(); + return childCount != 0 ? GetChildAt(childCount - 1) : nullptr; + } + + /** + * Return embedded accessible children count. + */ + uint32_t EmbeddedChildCount(); + + /** + * Return embedded accessible child at the given index. + */ + Accessible* GetEmbeddedChildAt(uint32_t aIndex); + + /** + * Return index of the given embedded accessible child. + */ + int32_t GetIndexOfEmbeddedChild(Accessible* aChild); + + /** + * Return number of content children/content child at index. The content + * child is created from markup in contrast to it's never constructed by its + * parent accessible (like treeitem accessibles for XUL trees). + */ + uint32_t ContentChildCount() const { return mChildren.Length(); } + Accessible* ContentChildAt(uint32_t aIndex) const { + return mChildren.ElementAt(aIndex); + } + + /** + * Return true if the accessible is attached to tree. + */ + bool IsBoundToParent() const { return !!mParent; } + + ////////////////////////////////////////////////////////////////////////////// + // Miscellaneous methods + + /** + * Handle accessible event, i.e. process it, notifies observers and fires + * platform specific event. + */ + virtual nsresult HandleAccEvent(AccEvent* aAccEvent); + + /** + * Return true if the accessible is an acceptable child. + */ + virtual bool IsAcceptableChild(nsIContent* aEl) const { + return aEl && + !aEl->IsAnyOfHTMLElements(nsGkAtoms::option, nsGkAtoms::optgroup); + } + + /** + * Returns text of accessible if accessible has text role otherwise empty + * string. + * + * @param aText [in] returned text of the accessible + * @param aStartOffset [in, optional] start offset inside of the accessible, + * if missed entire text is appended + * @param aLength [in, optional] required length of text, if missed + * then text form start offset till the end is appended + */ + virtual void AppendTextTo(nsAString& aText, uint32_t aStartOffset = 0, + uint32_t aLength = UINT32_MAX); + + /** + * Return boundaries in screen coordinates in app units. + */ + virtual nsRect BoundsInAppUnits() const; + + /** + * Return boundaries in screen coordinates. + */ + virtual nsIntRect Bounds() const; + + /** + * Return boundaries in screen coordinates in CSS pixels. + */ + virtual nsIntRect BoundsInCSSPixels() const; + + /** + * Return boundaries rect relative the bounding frame. + */ + virtual nsRect RelativeBounds(nsIFrame** aRelativeFrame) const; + + /** + * Selects the accessible within its container if applicable. + */ + virtual void SetSelected(bool aSelect); + + /** + * Select the accessible within its container. + */ + void TakeSelection(); + + /** + * Focus the accessible. + */ + MOZ_CAN_RUN_SCRIPT_BOUNDARY virtual void TakeFocus() const; + + /** + * Scroll the accessible into view. + */ + MOZ_CAN_RUN_SCRIPT + virtual void ScrollTo(uint32_t aHow) const; + + /** + * Scroll the accessible to the given point. + */ + void ScrollToPoint(uint32_t aCoordinateType, int32_t aX, int32_t aY); + + /** + * Get a pointer to accessibility interface for this node, which is specific + * to the OS/accessibility toolkit we're running on. + */ + virtual void GetNativeInterface(void** aNativeAccessible); + + ////////////////////////////////////////////////////////////////////////////// + // Downcasting and types + + inline bool IsAbbreviation() const { + return mContent->IsAnyOfHTMLElements(nsGkAtoms::abbr, nsGkAtoms::acronym); + } + + bool IsAlert() const { return HasGenericType(eAlert); } + + bool IsApplication() const { return mType == eApplicationType; } + ApplicationAccessible* AsApplication(); + + bool IsAutoComplete() const { return HasGenericType(eAutoComplete); } + + bool IsAutoCompletePopup() const { + return HasGenericType(eAutoCompletePopup); + } + + bool IsButton() const { return HasGenericType(eButton); } + + bool IsCombobox() const { return HasGenericType(eCombobox); } + + bool IsDoc() const { return HasGenericType(eDocument); } + DocAccessible* AsDoc(); + + bool IsGenericHyperText() const { return mType == eHyperTextType; } + bool IsHyperText() const { return HasGenericType(eHyperText); } + HyperTextAccessible* AsHyperText(); + + bool IsHTMLBr() const { return mType == eHTMLBRType; } + bool IsHTMLCaption() const { return mType == eHTMLCaptionType; } + bool IsHTMLCombobox() const { return mType == eHTMLComboboxType; } + bool IsHTMLFileInput() const { return mType == eHTMLFileInputType; } + + bool IsHTMLListItem() const { return mType == eHTMLLiType; } + HTMLLIAccessible* AsHTMLListItem(); + + bool IsHTMLLink() const { return mType == eHTMLLinkType; } + HTMLLinkAccessible* AsHTMLLink(); + + bool IsHTMLOptGroup() const { return mType == eHTMLOptGroupType; } + + bool IsHTMLTable() const { return mType == eHTMLTableType; } + bool IsHTMLTableRow() const { return mType == eHTMLTableRowType; } + + bool IsImage() const { return mType == eImageType; } + ImageAccessible* AsImage(); + + bool IsImageMap() const { return mType == eImageMapType; } + HTMLImageMapAccessible* AsImageMap(); + + bool IsList() const { return HasGenericType(eList); } + + bool IsListControl() const { return HasGenericType(eListControl); } + + bool IsMenuButton() const { return HasGenericType(eMenuButton); } + + bool IsMenuPopup() const { return mType == eMenuPopupType; } + + bool IsProxy() const { return mType == eProxyType; } + ProxyAccessible* Proxy() const { + MOZ_ASSERT(IsProxy()); + return mBits.proxy; + } + uint32_t ProxyInterfaces() const { + MOZ_ASSERT(IsProxy()); + return mInt.mProxyInterfaces; + } + void SetProxyInterfaces(uint32_t aInterfaces) { + MOZ_ASSERT(IsProxy()); + mInt.mProxyInterfaces = aInterfaces; + } + + bool IsOuterDoc() const { return mType == eOuterDocType; } + OuterDocAccessible* AsOuterDoc(); + + bool IsProgress() const { return mType == eProgressType; } + + bool IsRoot() const { return mType == eRootType; } + a11y::RootAccessible* AsRoot(); + + bool IsSearchbox() const; + + bool IsSelect() const { return HasGenericType(eSelect); } + + bool IsTable() const { return HasGenericType(eTable); } + virtual TableAccessible* AsTable() { return nullptr; } + + /** + * Note: The eTable* types defined in the ARIA map are used in + * nsAccessibilityService::CreateAccessible to determine which ARIAGrid* + * classes to use for accessible object creation. However, an invalid table + * structure might cause these classes not to be used after all. + * + * To make sure we're really dealing with a table cell, only check the + * generic type defined by the class, not the type defined in the ARIA map. + */ + bool IsTableCell() const { return mGenericTypes & eTableCell; } + virtual TableCellAccessible* AsTableCell() { return nullptr; } + const TableCellAccessible* AsTableCell() const { + return const_cast<Accessible*>(this)->AsTableCell(); + } + + bool IsTableRow() const { return HasGenericType(eTableRow); } + + bool IsTextField() const { + return mType == eHTMLTextFieldType || mType == eHTMLTextPasswordFieldType; + } + + bool IsPassword() const { return mType == eHTMLTextPasswordFieldType; } + + bool IsText() const { return mGenericTypes & eText; } + + bool IsTextLeaf() const { return mType == eTextLeafType; } + TextLeafAccessible* AsTextLeaf(); + + bool IsXULLabel() const { return mType == eXULLabelType; } + XULLabelAccessible* AsXULLabel(); + + bool IsXULListItem() const { return mType == eXULListItemType; } + + bool IsXULTabpanels() const { return mType == eXULTabpanelsType; } + + bool IsXULTooltip() const { return mType == eXULTooltipType; } + + bool IsXULTree() const { return mType == eXULTreeType; } + XULTreeAccessible* AsXULTree(); + + /** + * Return true if the accessible belongs to the given accessible type. + */ + bool HasGenericType(AccGenericType aType) const; + + ////////////////////////////////////////////////////////////////////////////// + // ActionAccessible + + /** + * Return the number of actions that can be performed on this accessible. + */ + virtual uint8_t ActionCount() const; + + /** + * Return action name at given index. + */ + virtual void ActionNameAt(uint8_t aIndex, nsAString& aName); + + /** + * Default to localized action name. + */ + void ActionDescriptionAt(uint8_t aIndex, nsAString& aDescription) { + nsAutoString name; + ActionNameAt(aIndex, name); + TranslateString(name, aDescription); + } + + /** + * Invoke the accessible action. + */ + virtual bool DoAction(uint8_t aIndex) const; + + /** + * Return access key, such as Alt+D. + */ + virtual KeyBinding AccessKey() const; + + /** + * Return global keyboard shortcut for default action, such as Ctrl+O for + * Open file menuitem. + */ + virtual KeyBinding KeyboardShortcut() const; + + ////////////////////////////////////////////////////////////////////////////// + // HyperLinkAccessible (any embedded object in text can implement HyperLink, + // which helps determine where it is located within containing text). + + /** + * Return true if the accessible is hyper link accessible. + */ + virtual bool IsLink() const; + + /** + * Return the start offset of the link within the parent accessible. + */ + virtual uint32_t StartOffset(); + + /** + * Return the end offset of the link within the parent accessible. + */ + virtual uint32_t EndOffset(); + + /** + * Return true if the link is valid (e. g. points to a valid URL). + */ + inline bool IsLinkValid() { + MOZ_ASSERT(IsLink(), "IsLinkValid is called on not hyper link!"); + + // XXX In order to implement this we would need to follow every link + // Perhaps we can get information about invalid links from the cache + // In the mean time authors can use role="link" aria-invalid="true" + // to force it for links they internally know to be invalid + return (0 == (State() & mozilla::a11y::states::INVALID)); + } + + /** + * Return the number of anchors within the link. + */ + virtual uint32_t AnchorCount(); + + /** + * Returns an anchor accessible at the given index. + */ + virtual Accessible* AnchorAt(uint32_t aAnchorIndex); + + /** + * Returns an anchor URI at the given index. + */ + virtual already_AddRefed<nsIURI> AnchorURIAt(uint32_t aAnchorIndex) const; + + /** + * Returns a text point for the accessible element. + */ + void ToTextPoint(HyperTextAccessible** aContainer, int32_t* aOffset, + bool aIsBefore = true) const; + + ////////////////////////////////////////////////////////////////////////////// + // SelectAccessible + + /** + * Return an array of selected items. + */ + virtual void SelectedItems(nsTArray<Accessible*>* aItems); + + /** + * Return the number of selected items. + */ + virtual uint32_t SelectedItemCount(); + + /** + * Return selected item at the given index. + */ + virtual Accessible* GetSelectedItem(uint32_t aIndex); + + /** + * Determine if item at the given index is selected. + */ + virtual bool IsItemSelected(uint32_t aIndex); + + /** + * Add item at the given index the selection. Return true if success. + */ + virtual bool AddItemToSelection(uint32_t aIndex); + + /** + * Remove item at the given index from the selection. Return if success. + */ + virtual bool RemoveItemFromSelection(uint32_t aIndex); + + /** + * Select all items. Return true if success. + */ + virtual bool SelectAll(); + + /** + * Unselect all items. Return true if success. + */ + virtual bool UnselectAll(); + + ////////////////////////////////////////////////////////////////////////////// + // Value (numeric value interface) + + virtual double MaxValue() const; + virtual double MinValue() const; + virtual double CurValue() const; + virtual double Step() const; + virtual bool SetCurValue(double aValue); + + ////////////////////////////////////////////////////////////////////////////// + // Widgets + + /** + * Return true if accessible is a widget, i.e. control or accessible that + * manages its items. Note, being a widget the accessible may be a part of + * composite widget. + */ + virtual bool IsWidget() const; + + /** + * Return true if the widget is active, i.e. has a focus within it. + */ + virtual bool IsActiveWidget() const; + + /** + * Return true if the widget has items and items are operable by user and + * can be activated. + */ + virtual bool AreItemsOperable() const; + + /** + * Return the current item of the widget, i.e. an item that has or will have + * keyboard focus when widget gets active. + */ + virtual Accessible* CurrentItem() const; + + /** + * Set the current item of the widget. + */ + virtual void SetCurrentItem(const Accessible* aItem); + + /** + * Return container widget this accessible belongs to. + */ + virtual Accessible* ContainerWidget() const; + + /** + * Return the localized string for the given key. + */ + static void TranslateString(const nsString& aKey, nsAString& aStringOut); + + /** + * Return true if the accessible is defunct. + */ + bool IsDefunct() const; + + /** + * Return false if the accessible is no longer in the document. + */ + bool IsInDocument() const { return !(mStateFlags & eIsNotInDocument); } + + /** + * Return true if the accessible should be contained by document node map. + */ + bool IsNodeMapEntry() const { + return HasOwnContent() && !(mStateFlags & eNotNodeMapEntry); + } + + /** + * Return true if the accessible's group info needs to be updated. + */ + inline bool HasDirtyGroupInfo() const { + return mStateFlags & eGroupInfoDirty; + } + + /** + * Return true if the accessible has associated DOM content. + */ + bool HasOwnContent() const { + return mContent && !(mStateFlags & eSharedNode); + } + + /** + * Return true if native markup has a numeric value. + */ + bool NativeHasNumericValue() const; + + /** + * Return true if ARIA specifies support for a numeric value. + */ + bool ARIAHasNumericValue() const; + + /** + * Return true if the accessible has a numeric value. + */ + bool HasNumericValue() const; + + /** + * Return true if the accessible state change is processed by handling proper + * DOM UI event, if otherwise then false. For example, CheckboxAccessible + * created for HTML:input@type="checkbox" will process + * nsIDocumentObserver::ContentStateChanged instead of 'CheckboxStateChange' + * event. + */ + bool NeedsDOMUIEvent() const { return !(mStateFlags & eIgnoreDOMUIEvent); } + + /** + * Get/set repositioned bit indicating that the accessible was moved in + * the accessible tree, i.e. the accessible tree structure differs from DOM. + */ + bool IsRelocated() const { return mStateFlags & eRelocated; } + void SetRelocated(bool aRelocated) { + if (aRelocated) + mStateFlags |= eRelocated; + else + mStateFlags &= ~eRelocated; + } + + /** + * Return true if the accessible allows accessible children from subtree of + * a DOM element of this accessible. + */ + bool KidsFromDOM() const { return !(mStateFlags & eNoKidsFromDOM); } + + /** + * Return true if this accessible has a parent whose name depends on this + * accessible. + */ + bool HasNameDependentParent() const { + return mContextFlags & eHasNameDependentParent; + } + + /** + * Return true if the element is inside an alert. + */ + bool IsInsideAlert() const { return mContextFlags & eInsideAlert; } + + /** + * Return true if there is a pending reorder event for this accessible. + */ + bool ReorderEventTarget() const { return mReorderEventTarget; } + + /** + * Return true if there is a pending show event for this accessible. + */ + bool ShowEventTarget() const { return mShowEventTarget; } + + /** + * Return true if there is a pending hide event for this accessible. + */ + bool HideEventTarget() const { return mHideEventTarget; } + + /** + * Set if there is a pending reorder event for this accessible. + */ + void SetReorderEventTarget(bool aTarget) { mReorderEventTarget = aTarget; } + + /** + * Set if this accessible is a show event target. + */ + void SetShowEventTarget(bool aTarget) { mShowEventTarget = aTarget; } + + /** + * Set if this accessible is a hide event target. + */ + void SetHideEventTarget(bool aTarget) { mHideEventTarget = aTarget; } + + void Announce(const nsAString& aAnnouncement, uint16_t aPriority); + + /** + * Fire a focusable state change event if the previous state + * was different. + */ + void MaybeFireFocusableStateChange(bool aPreviouslyFocusable); + + protected: + virtual ~Accessible(); + + /** + * Return the accessible name provided by native markup. It doesn't take + * into account ARIA markup used to specify the name. + */ + virtual mozilla::a11y::ENameValueFlag NativeName(nsString& aName) const; + + /** + * Return the accessible description provided by native markup. It doesn't + * take into account ARIA markup used to specify the description. + */ + virtual void NativeDescription(nsString& aDescription); + + /** + * Return object attributes provided by native markup. It doesn't take into + * account ARIA. + */ + virtual already_AddRefed<nsIPersistentProperties> NativeAttributes(); + + ////////////////////////////////////////////////////////////////////////////// + // Initializing, cache and tree traverse methods + + /** + * Destroy the object. + */ + void LastRelease(); + + /** + * Set accessible parent and index in parent. + */ + void BindToParent(Accessible* aParent, uint32_t aIndexInParent); + void UnbindFromParent(); + + /** + * Return sibling accessible at the given offset. + */ + virtual Accessible* GetSiblingAtOffset(int32_t aOffset, + nsresult* aError = nullptr) const; + + /** + * Flags used to describe the state of this accessible. + */ + enum StateFlags { + eIsDefunct = 1 << 0, // accessible is defunct + eIsNotInDocument = 1 << 1, // accessible is not in document + eSharedNode = 1 << 2, // accessible shares DOM node from another accessible + eNotNodeMapEntry = 1 << 3, // accessible shouldn't be in document node map + eHasNumericValue = 1 << 4, // accessible has a numeric value + eGroupInfoDirty = 1 << 5, // accessible needs to update group info + eKidsMutating = 1 << 6, // subtree is being mutated + eIgnoreDOMUIEvent = 1 << 7, // don't process DOM UI events for a11y events + eRelocated = 1 << 8, // accessible was moved in tree + eNoKidsFromDOM = 1 << 9, // accessible doesn't allow children from DOM + eHasTextKids = 1 << 10, // accessible have a text leaf in children + + eLastStateFlag = eHasTextKids + }; + + /** + * Flags used for contextual information about the accessible. + */ + enum ContextFlags { + eHasNameDependentParent = + 1 << 0, // Parent's name depends on this accessible. + eInsideAlert = 1 << 1, + + eLastContextFlag = eInsideAlert + }; + + protected: + ////////////////////////////////////////////////////////////////////////////// + // Miscellaneous helpers + + /** + * Return ARIA role (helper method). + */ + mozilla::a11y::role ARIATransformRole(mozilla::a11y::role aRole) const; + + ////////////////////////////////////////////////////////////////////////////// + // Name helpers + + /** + * Returns the accessible name specified by ARIA. + */ + void ARIAName(nsString& aName) const; + + /** + * Returns the accessible description specified by ARIA. + */ + void ARIADescription(nsString& aDescription) const; + + /** + * Returns the accessible name specified for this control using XUL + * <label control="id" ...>. + */ + static void NameFromAssociatedXULLabel(DocAccessible* aDocument, + nsIContent* aElm, nsString& aName); + + /** + * Return the name for XUL element. + */ + static void XULElmName(DocAccessible* aDocument, nsIContent* aElm, + nsString& aName); + + // helper method to verify frames + static nsresult GetFullKeyName(const nsAString& aModifierName, + const nsAString& aKeyName, + nsAString& aStringOut); + + ////////////////////////////////////////////////////////////////////////////// + // Action helpers + + /** + * Prepares click action that will be invoked in timeout. + * + * @note DoCommand() prepares an action in timeout because when action + * command opens a modal dialog/window, it won't return until the + * dialog/window is closed. If executing action command directly in + * nsIAccessible::DoAction() method, it will block AT tools (e.g. GOK) that + * invoke action of mozilla accessibles direclty (see bug 277888 for + * details). + * + * @param aContent [in, optional] element to click + * @param aActionIndex [in, optional] index of accessible action + */ + void DoCommand(nsIContent* aContent = nullptr, + uint32_t aActionIndex = 0) const; + + /** + * Dispatch click event. + */ + MOZ_CAN_RUN_SCRIPT + virtual void DispatchClickEvent(nsIContent* aContent, + uint32_t aActionIndex) const; + + ////////////////////////////////////////////////////////////////////////////// + // Helpers + + /** + * Get the container node for an atomic region, defined by aria-atomic="true" + * @return the container node + */ + nsIContent* GetAtomicRegion() const; + + /** + * Return numeric value of the given ARIA attribute, NaN if not applicable. + * + * @param aARIAProperty [in] the ARIA property we're using + * @return a numeric value + */ + double AttrNumericValue(nsAtom* aARIAAttr) const; + + /** + * Return the action rule based on ARIA enum constants EActionRule + * (see ARIAMap.h). Used by ActionCount() and ActionNameAt(). + */ + uint32_t GetActionRule() const; + + /** + * Return group info. + */ + AccGroupInfo* GetGroupInfo() const; + + // Data Members + nsCOMPtr<nsIContent> mContent; + RefPtr<DocAccessible> mDoc; + + Accessible* mParent; + nsTArray<Accessible*> mChildren; + int32_t mIndexInParent; + + static const uint8_t kStateFlagsBits = 11; + static const uint8_t kContextFlagsBits = 2; + static const uint8_t kTypeBits = 6; + static const uint8_t kGenericTypesBits = 16; + + /** + * Non-NO_ROLE_MAP_ENTRY_INDEX indicates author-supplied role; + * possibly state & value as well + */ + uint8_t mRoleMapEntryIndex; + + /** + * Keep in sync with StateFlags, ContextFlags, and AccTypes. + */ + mutable uint32_t mStateFlags : kStateFlagsBits; + uint32_t mContextFlags : kContextFlagsBits; + uint32_t mType : kTypeBits; + uint32_t mGenericTypes : kGenericTypesBits; + uint32_t mReorderEventTarget : 1; + uint32_t mShowEventTarget : 1; + uint32_t mHideEventTarget : 1; + + void StaticAsserts() const; + +#ifdef A11Y_LOG + friend void logging::Tree(const char* aTitle, const char* aMsgText, + Accessible* aRoot, + logging::GetTreePrefix aPrefixFunc, + void* aGetTreePrefixData); +#endif + friend class DocAccessible; + friend class xpcAccessible; + friend class TreeMutation; + + UniquePtr<mozilla::a11y::EmbeddedObjCollector> mEmbeddedObjCollector; + union { + int32_t mIndexOfEmbeddedChild; + uint32_t mProxyInterfaces; + } mInt; + + friend class EmbeddedObjCollector; + + union { + AccGroupInfo* groupInfo; + ProxyAccessible* proxy; + } mutable mBits; + friend class AccGroupInfo; + + private: + Accessible() = delete; + Accessible(const Accessible&) = delete; + Accessible& operator=(const Accessible&) = delete; +}; + +NS_DEFINE_STATIC_IID_ACCESSOR(Accessible, NS_ACCESSIBLE_IMPL_IID) + +/** + * Represent key binding associated with accessible (such as access key and + * global keyboard shortcuts). + */ +class KeyBinding { + public: + /** + * Modifier mask values. + */ + static const uint32_t kShift = 1; + static const uint32_t kControl = 2; + static const uint32_t kAlt = 4; + static const uint32_t kMeta = 8; + static const uint32_t kOS = 16; + + static uint32_t AccelModifier(); + + KeyBinding() : mKey(0), mModifierMask(0) {} + KeyBinding(uint32_t aKey, uint32_t aModifierMask) + : mKey(aKey), mModifierMask(aModifierMask) {} + + inline bool IsEmpty() const { return !mKey; } + inline uint32_t Key() const { return mKey; } + inline uint32_t ModifierMask() const { return mModifierMask; } + + enum Format { ePlatformFormat, eAtkFormat }; + + /** + * Return formatted string for this key binding depending on the given format. + */ + inline void ToString(nsAString& aValue, + Format aFormat = ePlatformFormat) const { + aValue.Truncate(); + AppendToString(aValue, aFormat); + } + inline void AppendToString(nsAString& aValue, + Format aFormat = ePlatformFormat) const { + if (mKey) { + if (aFormat == ePlatformFormat) + ToPlatformFormat(aValue); + else + ToAtkFormat(aValue); + } + } + + private: + void ToPlatformFormat(nsAString& aValue) const; + void ToAtkFormat(nsAString& aValue) const; + + uint32_t mKey; + uint32_t mModifierMask; +}; + +} // namespace a11y +} // namespace mozilla + +#endif diff --git a/accessible/generic/ApplicationAccessible.cpp b/accessible/generic/ApplicationAccessible.cpp new file mode 100644 index 0000000000..7a3fe07869 --- /dev/null +++ b/accessible/generic/ApplicationAccessible.cpp @@ -0,0 +1,139 @@ +/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* vim:expandtab:shiftwidth=2:tabstop=2: + */ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +#include "ApplicationAccessible.h" + +#include "nsAccessibilityService.h" +#include "nsAccUtils.h" +#include "Relation.h" +#include "Role.h" +#include "States.h" + +#include "nsServiceManagerUtils.h" +#include "mozilla/dom/Document.h" +#include "mozilla/Services.h" +#include "nsGlobalWindow.h" +#include "nsIStringBundle.h" + +using namespace mozilla::a11y; + +ApplicationAccessible::ApplicationAccessible() + : AccessibleWrap(nullptr, nullptr) { + mType = eApplicationType; + mAppInfo = do_GetService("@mozilla.org/xre/app-info;1"); + MOZ_ASSERT(mAppInfo, "no application info"); +} + +//////////////////////////////////////////////////////////////////////////////// +// nsIAccessible + +ENameValueFlag ApplicationAccessible::Name(nsString& aName) const { + aName.Truncate(); + + nsCOMPtr<nsIStringBundleService> bundleService = + mozilla::services::GetStringBundleService(); + + NS_ASSERTION(bundleService, "String bundle service must be present!"); + if (!bundleService) return eNameOK; + + nsCOMPtr<nsIStringBundle> bundle; + nsresult rv = bundleService->CreateBundle( + "chrome://branding/locale/brand.properties", getter_AddRefs(bundle)); + if (NS_FAILED(rv)) return eNameOK; + + nsAutoString appName; + rv = bundle->GetStringFromName("brandShortName", appName); + if (NS_FAILED(rv) || appName.IsEmpty()) { + NS_WARNING("brandShortName not found, using default app name"); + appName.AssignLiteral("Gecko based application"); + } + + aName.Assign(appName); + return eNameOK; +} + +void ApplicationAccessible::Description(nsString& aDescription) { + aDescription.Truncate(); +} + +void ApplicationAccessible::Value(nsString& aValue) const { aValue.Truncate(); } + +uint64_t ApplicationAccessible::State() { + return IsDefunct() ? states::DEFUNCT : 0; +} + +already_AddRefed<nsIPersistentProperties> +ApplicationAccessible::NativeAttributes() { + return nullptr; +} + +GroupPos ApplicationAccessible::GroupPosition() { return GroupPos(); } + +Accessible* ApplicationAccessible::ChildAtPoint( + int32_t aX, int32_t aY, EWhichChildAtPoint aWhichChild) { + return nullptr; +} + +Accessible* ApplicationAccessible::FocusedChild() { + Accessible* focus = FocusMgr()->FocusedAccessible(); + if (focus && focus->Parent() == this) return focus; + + return nullptr; +} + +Relation ApplicationAccessible::RelationByType( + RelationType aRelationType) const { + return Relation(); +} + +nsIntRect ApplicationAccessible::Bounds() const { return nsIntRect(); } + +nsRect ApplicationAccessible::BoundsInAppUnits() const { return nsRect(); } + +//////////////////////////////////////////////////////////////////////////////// +// Accessible public methods + +void ApplicationAccessible::Shutdown() { mAppInfo = nullptr; } + +void ApplicationAccessible::ApplyARIAState(uint64_t* aState) const {} + +role ApplicationAccessible::NativeRole() const { return roles::APP_ROOT; } + +uint64_t ApplicationAccessible::NativeState() const { return 0; } + +KeyBinding ApplicationAccessible::AccessKey() const { return KeyBinding(); } + +void ApplicationAccessible::Init() { + // Basically children are kept updated by Append/RemoveChild method calls. + // However if there are open windows before accessibility was started + // then we need to make sure root accessibles for open windows are created so + // that all root accessibles are stored in application accessible children + // array. + + nsGlobalWindowOuter::OuterWindowByIdTable* windowsById = + nsGlobalWindowOuter::GetWindowsTable(); + + if (!windowsById) { + return; + } + + for (auto iter = windowsById->Iter(); !iter.Done(); iter.Next()) { + nsGlobalWindowOuter* window = iter.Data(); + if (window->GetDocShell() && window->IsRootOuterWindow()) { + if (RefPtr<dom::Document> docNode = window->GetExtantDoc()) { + GetAccService()->GetDocAccessible(docNode); // ensure creation + } + } + } +} + +Accessible* ApplicationAccessible::GetSiblingAtOffset(int32_t aOffset, + nsresult* aError) const { + if (aError) *aError = NS_OK; // fail peacefully + + return nullptr; +} diff --git a/accessible/generic/ApplicationAccessible.h b/accessible/generic/ApplicationAccessible.h new file mode 100644 index 0000000000..e85edaab2a --- /dev/null +++ b/accessible/generic/ApplicationAccessible.h @@ -0,0 +1,109 @@ +/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* vim:expandtab:shiftwidth=2:tabstop=2: + */ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +#ifndef mozilla_a11y_ApplicationAccessible_h__ +#define mozilla_a11y_ApplicationAccessible_h__ + +#include "AccessibleWrap.h" + +#include "nsIXULAppInfo.h" + +namespace mozilla { +namespace a11y { + +/** + * ApplicationAccessible is for the whole application of Mozilla. + * Only one instance of ApplicationAccessible exists for one Mozilla instance. + * And this one should be created when Mozilla Startup (if accessibility + * feature has been enabled) and destroyed when Mozilla Shutdown. + * + * All the accessibility objects for toplevel windows are direct children of + * the ApplicationAccessible instance. + */ + +class ApplicationAccessible : public AccessibleWrap { + public: + ApplicationAccessible(); + + NS_INLINE_DECL_REFCOUNTING_INHERITED(ApplicationAccessible, AccessibleWrap) + + // Accessible + virtual void Shutdown() override; + virtual nsIntRect Bounds() const override; + virtual nsRect BoundsInAppUnits() const override; + virtual already_AddRefed<nsIPersistentProperties> NativeAttributes() override; + virtual GroupPos GroupPosition() override; + virtual ENameValueFlag Name(nsString& aName) const override; + virtual void ApplyARIAState(uint64_t* aState) const override; + virtual void Description(nsString& aDescription) override; + virtual void Value(nsString& aValue) const override; + virtual mozilla::a11y::role NativeRole() const override; + virtual uint64_t State() override; + virtual uint64_t NativeState() const override; + virtual Relation RelationByType(RelationType aType) const override; + + virtual Accessible* ChildAtPoint(int32_t aX, int32_t aY, + EWhichChildAtPoint aWhichChild) override; + virtual Accessible* FocusedChild() override; + + // ActionAccessible + virtual KeyBinding AccessKey() const override; + + // ApplicationAccessible + void Init(); + + void AppName(nsAString& aName) const { + MOZ_ASSERT(mAppInfo, "no application info"); + + if (mAppInfo) { + nsAutoCString cname; + mAppInfo->GetName(cname); + AppendUTF8toUTF16(cname, aName); + } + } + + void AppVersion(nsAString& aVersion) const { + MOZ_ASSERT(mAppInfo, "no application info"); + + if (mAppInfo) { + nsAutoCString cversion; + mAppInfo->GetVersion(cversion); + AppendUTF8toUTF16(cversion, aVersion); + } + } + + void PlatformName(nsAString& aName) const { aName.AssignLiteral("Gecko"); } + + void PlatformVersion(nsAString& aVersion) const { + MOZ_ASSERT(mAppInfo, "no application info"); + + if (mAppInfo) { + nsAutoCString cversion; + mAppInfo->GetPlatformVersion(cversion); + AppendUTF8toUTF16(cversion, aVersion); + } + } + + protected: + virtual ~ApplicationAccessible() {} + + // Accessible + virtual Accessible* GetSiblingAtOffset( + int32_t aOffset, nsresult* aError = nullptr) const override; + + private: + nsCOMPtr<nsIXULAppInfo> mAppInfo; +}; + +inline ApplicationAccessible* Accessible::AsApplication() { + return IsApplication() ? static_cast<ApplicationAccessible*>(this) : nullptr; +} + +} // namespace a11y +} // namespace mozilla + +#endif diff --git a/accessible/generic/BaseAccessibles.cpp b/accessible/generic/BaseAccessibles.cpp new file mode 100644 index 0000000000..8f1f6286a4 --- /dev/null +++ b/accessible/generic/BaseAccessibles.cpp @@ -0,0 +1,211 @@ +/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +#include "BaseAccessibles.h" + +#include "Accessible-inl.h" +#include "HyperTextAccessibleWrap.h" +#include "nsAccessibilityService.h" +#include "nsAccUtils.h" +#include "nsCoreUtils.h" +#include "Role.h" +#include "States.h" +#include "nsIURI.h" + +using namespace mozilla::a11y; + +//////////////////////////////////////////////////////////////////////////////// +// LeafAccessible +//////////////////////////////////////////////////////////////////////////////// + +LeafAccessible::LeafAccessible(nsIContent* aContent, DocAccessible* aDoc) + : AccessibleWrap(aContent, aDoc) { + mStateFlags |= eNoKidsFromDOM; +} + +//////////////////////////////////////////////////////////////////////////////// +// LeafAccessible: Accessible public + +Accessible* LeafAccessible::ChildAtPoint(int32_t aX, int32_t aY, + EWhichChildAtPoint aWhichChild) { + // Don't walk into leaf accessibles. + return this; +} + +bool LeafAccessible::InsertChildAt(uint32_t aIndex, Accessible* aChild) { + MOZ_ASSERT_UNREACHABLE("InsertChildAt called on leaf accessible!"); + return false; +} + +bool LeafAccessible::RemoveChild(Accessible* aChild) { + MOZ_ASSERT_UNREACHABLE("RemoveChild called on leaf accessible!"); + return false; +} + +bool LeafAccessible::IsAcceptableChild(nsIContent* aEl) const { + // No children for leaf accessible. + return false; +} + +//////////////////////////////////////////////////////////////////////////////// +// LinkableAccessible +//////////////////////////////////////////////////////////////////////////////// + +//////////////////////////////////////////////////////////////////////////////// +// LinkableAccessible. nsIAccessible + +void LinkableAccessible::TakeFocus() const { + if (const Accessible* actionAcc = ActionWalk()) { + actionAcc->TakeFocus(); + } else { + AccessibleWrap::TakeFocus(); + } +} + +uint64_t LinkableAccessible::NativeLinkState() const { + bool isLink; + const Accessible* actionAcc = ActionWalk(&isLink); + if (isLink) { + return states::LINKED | (actionAcc->LinkState() & states::TRAVERSED); + } + + return 0; +} + +void LinkableAccessible::Value(nsString& aValue) const { + aValue.Truncate(); + + Accessible::Value(aValue); + if (!aValue.IsEmpty()) { + return; + } + + bool isLink; + const Accessible* actionAcc = ActionWalk(&isLink); + if (isLink) { + actionAcc->Value(aValue); + } +} + +uint8_t LinkableAccessible::ActionCount() const { + bool isLink, isOnclick, isLabelWithControl; + ActionWalk(&isLink, &isOnclick, &isLabelWithControl); + return (isLink || isOnclick || isLabelWithControl) ? 1 : 0; +} + +const Accessible* LinkableAccessible::ActionWalk( + bool* aIsLink, bool* aIsOnclick, bool* aIsLabelWithControl) const { + if (aIsOnclick) { + *aIsOnclick = false; + } + if (aIsLink) { + *aIsLink = false; + } + if (aIsLabelWithControl) { + *aIsLabelWithControl = false; + } + + if (nsCoreUtils::HasClickListener(mContent)) { + if (aIsOnclick) { + *aIsOnclick = true; + } + return nullptr; + } + + // XXX: The logic looks broken since the click listener may be registered + // on non accessible node in parent chain but this node is skipped when tree + // is traversed. + const Accessible* walkUpAcc = this; + while ((walkUpAcc = walkUpAcc->Parent()) && !walkUpAcc->IsDoc()) { + if (walkUpAcc->LinkState() & states::LINKED) { + if (aIsLink) { + *aIsLink = true; + } + return walkUpAcc; + } + + if (nsCoreUtils::HasClickListener(walkUpAcc->GetContent())) { + if (aIsOnclick) { + *aIsOnclick = true; + } + return walkUpAcc; + } + + if (nsCoreUtils::IsLabelWithControl(walkUpAcc->GetContent())) { + if (aIsLabelWithControl) { + *aIsLabelWithControl = true; + } + return walkUpAcc; + } + } + return nullptr; +} + +void LinkableAccessible::ActionNameAt(uint8_t aIndex, nsAString& aName) { + aName.Truncate(); + + // Action 0 (default action): Jump to link + if (aIndex == eAction_Jump) { + bool isOnclick, isLink, isLabelWithControl; + ActionWalk(&isLink, &isOnclick, &isLabelWithControl); + if (isLink) { + aName.AssignLiteral("jump"); + } else if (isOnclick || isLabelWithControl) { + aName.AssignLiteral("click"); + } + } +} + +bool LinkableAccessible::DoAction(uint8_t aIndex) const { + if (aIndex != eAction_Jump) { + return false; + } + + if (const Accessible* actionAcc = ActionWalk()) { + return actionAcc->DoAction(aIndex); + } + + return AccessibleWrap::DoAction(aIndex); +} + +KeyBinding LinkableAccessible::AccessKey() const { + if (const Accessible* actionAcc = + const_cast<LinkableAccessible*>(this)->ActionWalk()) { + return actionAcc->AccessKey(); + } + + return Accessible::AccessKey(); +} + +//////////////////////////////////////////////////////////////////////////////// +// LinkableAccessible: HyperLinkAccessible + +already_AddRefed<nsIURI> LinkableAccessible::AnchorURIAt( + uint32_t aAnchorIndex) const { + bool isLink; + const Accessible* actionAcc = ActionWalk(&isLink); + if (isLink) { + NS_ASSERTION(actionAcc->IsLink(), "HyperLink isn't implemented."); + + if (actionAcc->IsLink()) { + return actionAcc->AnchorURIAt(aAnchorIndex); + } + } + + return nullptr; +} + +//////////////////////////////////////////////////////////////////////////////// +// DummyAccessible +//////////////////////////////////////////////////////////////////////////////// + +uint64_t DummyAccessible::NativeState() const { return 0; } +uint64_t DummyAccessible::NativeInteractiveState() const { return 0; } + +uint64_t DummyAccessible::NativeLinkState() const { return 0; } + +bool DummyAccessible::NativelyUnavailable() const { return false; } + +void DummyAccessible::ApplyARIAState(uint64_t* aState) const {} diff --git a/accessible/generic/BaseAccessibles.h b/accessible/generic/BaseAccessibles.h new file mode 100644 index 0000000000..774c668452 --- /dev/null +++ b/accessible/generic/BaseAccessibles.h @@ -0,0 +1,129 @@ +/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +#ifndef mozilla_a11y_BaseAccessibles_h__ +#define mozilla_a11y_BaseAccessibles_h__ + +#include "AccessibleWrap.h" +#include "HyperTextAccessibleWrap.h" + +class nsIContent; + +/** + * This file contains a number of classes that are used as base + * classes for the different accessibility implementations of + * the HTML and XUL widget sets. --jgaunt + */ + +namespace mozilla { +namespace a11y { + +/** + * Leaf version of DOM Accessible -- has no children + */ +class LeafAccessible : public AccessibleWrap { + public: + LeafAccessible(nsIContent* aContent, DocAccessible* aDoc); + + // nsISupports + NS_INLINE_DECL_REFCOUNTING_INHERITED(LeafAccessible, AccessibleWrap) + + // Accessible + virtual Accessible* ChildAtPoint(int32_t aX, int32_t aY, + EWhichChildAtPoint aWhichChild) override; + bool InsertChildAt(uint32_t aIndex, Accessible* aChild) final; + bool RemoveChild(Accessible* aChild) final; + + virtual bool IsAcceptableChild(nsIContent* aEl) const override; + + protected: + virtual ~LeafAccessible() {} +}; + +/** + * Used for text or image accessible nodes contained by link accessibles or + * accessibles for nodes with registered click event handler. It knows how to + * report the state of the host link (traveled or not) and can activate (click) + * the host accessible programmatically. + */ +class LinkableAccessible : public AccessibleWrap { + public: + enum { eAction_Jump = 0 }; + + LinkableAccessible(nsIContent* aContent, DocAccessible* aDoc) + : AccessibleWrap(aContent, aDoc) {} + + NS_INLINE_DECL_REFCOUNTING_INHERITED(LinkableAccessible, AccessibleWrap) + + // Accessible + virtual void Value(nsString& aValue) const override; + virtual uint64_t NativeLinkState() const override; + virtual void TakeFocus() const override; + + // ActionAccessible + virtual uint8_t ActionCount() const override; + virtual void ActionNameAt(uint8_t aIndex, nsAString& aName) override; + virtual bool DoAction(uint8_t index) const override; + virtual KeyBinding AccessKey() const override; + + // ActionAccessible helpers + const Accessible* ActionWalk(bool* aIsLink = nullptr, + bool* aIsOnclick = nullptr, + bool* aIsLabelWithControl = nullptr) const; + // HyperLinkAccessible + virtual already_AddRefed<nsIURI> AnchorURIAt( + uint32_t aAnchorIndex) const override; + + protected: + virtual ~LinkableAccessible() {} +}; + +/** + * A simple accessible that gets its enumerated role. + */ +template <a11y::role R> +class EnumRoleAccessible : public AccessibleWrap { + public: + EnumRoleAccessible(nsIContent* aContent, DocAccessible* aDoc) + : AccessibleWrap(aContent, aDoc) {} + + NS_IMETHOD QueryInterface(REFNSIID aIID, void** aPtr) override { + return Accessible::QueryInterface(aIID, aPtr); + } + + // Accessible + virtual a11y::role NativeRole() const override { return R; } + + protected: + virtual ~EnumRoleAccessible() {} +}; + +/** + * A wrapper accessible around native accessible to connect it with + * crossplatform accessible tree. + */ +class DummyAccessible : public AccessibleWrap { + public: + explicit DummyAccessible(DocAccessible* aDocument = nullptr) + : AccessibleWrap(nullptr, aDocument) { + // IsDefunct() asserts if mContent is null, which is always true for + // DummyAccessible. We can prevent this by setting eSharedNode. + mStateFlags |= eSharedNode; + } + + uint64_t NativeState() const final; + uint64_t NativeInteractiveState() const final; + uint64_t NativeLinkState() const final; + bool NativelyUnavailable() const final; + void ApplyARIAState(uint64_t* aState) const final; + + protected: + virtual ~DummyAccessible() {} +}; + +} // namespace a11y +} // namespace mozilla + +#endif diff --git a/accessible/generic/DocAccessible-inl.h b/accessible/generic/DocAccessible-inl.h new file mode 100644 index 0000000000..e7ab8491c3 --- /dev/null +++ b/accessible/generic/DocAccessible-inl.h @@ -0,0 +1,196 @@ +/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* vim: set ts=2 et sw=2 tw=80: */ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this file, + * You can obtain one at http://mozilla.org/MPL/2.0/. */ + +#ifndef mozilla_a11y_DocAccessible_inl_h_ +#define mozilla_a11y_DocAccessible_inl_h_ + +#include "DocAccessible.h" +#include "nsAccessibilityService.h" +#include "nsAccessiblePivot.h" +#include "NotificationController.h" +#include "States.h" +#include "nsIScrollableFrame.h" +#include "mozilla/dom/DocumentInlines.h" + +#ifdef A11Y_LOG +# include "Logging.h" +#endif + +namespace mozilla { +namespace a11y { + +inline Accessible* DocAccessible::AccessibleOrTrueContainer( + nsINode* aNode, bool aNoContainerIfPruned) const { + // HTML comboboxes have no-content list accessible as an intermediate + // containing all options. + Accessible* container = GetAccessibleOrContainer(aNode, aNoContainerIfPruned); + if (container && container->IsHTMLCombobox()) { + return container->FirstChild(); + } + return container; +} + +inline nsIAccessiblePivot* DocAccessible::VirtualCursor() { + if (!mVirtualCursor) { + mVirtualCursor = new nsAccessiblePivot(this); + mVirtualCursor->AddObserver(this); + } + return mVirtualCursor; +} + +inline bool DocAccessible::IsContentLoaded() const { + // eDOMLoaded flag check is used for error pages as workaround to make this + // method return correct result since error pages do not receive 'pageshow' + // event and as consequence Document::IsShowing() returns false. + return mDocumentNode && mDocumentNode->IsVisible() && + (mDocumentNode->IsShowing() || HasLoadState(eDOMLoaded)); +} + +inline bool DocAccessible::IsHidden() const { return mDocumentNode->Hidden(); } + +inline void DocAccessible::FireDelayedEvent(AccEvent* aEvent) { +#ifdef A11Y_LOG + if (logging::IsEnabled(logging::eDocLoad)) logging::DocLoadEventFired(aEvent); +#endif + + mNotificationController->QueueEvent(aEvent); +} + +inline void DocAccessible::FireDelayedEvent(uint32_t aEventType, + Accessible* aTarget) { + RefPtr<AccEvent> event = new AccEvent(aEventType, aTarget); + FireDelayedEvent(event); +} + +inline void DocAccessible::BindChildDocument(DocAccessible* aDocument) { + mNotificationController->ScheduleChildDocBinding(aDocument); +} + +template <class Class, class... Args> +inline void DocAccessible::HandleNotification( + Class* aInstance, typename TNotification<Class, Args...>::Callback aMethod, + Args*... aArgs) { + if (mNotificationController) { + mNotificationController->HandleNotification<Class, Args...>( + aInstance, aMethod, aArgs...); + } +} + +inline void DocAccessible::UpdateText(nsIContent* aTextNode) { + NS_ASSERTION(mNotificationController, "The document was shut down!"); + + // Ignore the notification if initial tree construction hasn't been done yet. + if (mNotificationController && HasLoadState(eTreeConstructed)) + mNotificationController->ScheduleTextUpdate(aTextNode); +} + +inline void DocAccessible::NotifyOfLoad(uint32_t aLoadEventType) { + mLoadState |= eDOMLoaded; + mLoadEventType = aLoadEventType; + + // If the document is loaded completely then network activity was presumingly + // caused by file loading. Fire busy state change event. + if (HasLoadState(eCompletelyLoaded) && IsLoadEventTarget()) { + RefPtr<AccEvent> stateEvent = + new AccStateChangeEvent(this, states::BUSY, false); + FireDelayedEvent(stateEvent); + } +} + +inline void DocAccessible::MaybeNotifyOfValueChange(Accessible* aAccessible) { + if (aAccessible->IsCombobox() || aAccessible->Role() == roles::ENTRY || + aAccessible->Role() == roles::SPINBUTTON) { + FireDelayedEvent(nsIAccessibleEvent::EVENT_TEXT_VALUE_CHANGE, aAccessible); + } +} + +inline Accessible* DocAccessible::GetAccessibleEvenIfNotInMapOrContainer( + nsINode* aNode) const { + Accessible* acc = GetAccessibleEvenIfNotInMap(aNode); + return acc ? acc : GetContainerAccessible(aNode); +} + +inline void DocAccessible::CreateSubtree(Accessible* aChild) { + // If a focused node has been shown then it could mean its frame was recreated + // while the node stays focused and we need to fire focus event on + // the accessible we just created. If the queue contains a focus event for + // this node already then it will be suppressed by this one. + Accessible* focusedAcc = nullptr; + CacheChildrenInSubtree(aChild, &focusedAcc); + +#ifdef A11Y_LOG + if (logging::IsEnabled(logging::eVerbose)) { + logging::Tree("TREE", "Created subtree", aChild); + } +#endif + + // Fire events for ARIA elements. + if (aChild->HasARIARole()) { + roles::Role role = aChild->ARIARole(); + if (role == roles::MENUPOPUP) { + FireDelayedEvent(nsIAccessibleEvent::EVENT_MENUPOPUP_START, aChild); + } else if (role == roles::ALERT) { + FireDelayedEvent(nsIAccessibleEvent::EVENT_ALERT, aChild); + } + } + + // XXX: do we really want to send focus to focused DOM node not taking into + // account active item? + if (focusedAcc) { + FocusMgr()->DispatchFocusEvent(this, focusedAcc); + SelectionMgr()->SetControlSelectionListener( + focusedAcc->GetNode()->AsElement()); + } +} + +inline DocAccessible::AttrRelProviders* DocAccessible::GetRelProviders( + dom::Element* aElement, const nsAString& aID) const { + DependentIDsHashtable* hash = mDependentIDsHashes.Get( + aElement->GetUncomposedDocOrConnectedShadowRoot()); + if (hash) { + return hash->Get(aID); + } + return nullptr; +} + +inline DocAccessible::AttrRelProviders* DocAccessible::GetOrCreateRelProviders( + dom::Element* aElement, const nsAString& aID) { + dom::DocumentOrShadowRoot* docOrShadowRoot = + aElement->GetUncomposedDocOrConnectedShadowRoot(); + DependentIDsHashtable* hash = mDependentIDsHashes.Get(docOrShadowRoot); + if (!hash) { + hash = new DependentIDsHashtable(); + mDependentIDsHashes.Put(docOrShadowRoot, hash); + } + + AttrRelProviders* providers = hash->Get(aID); + if (!providers) { + providers = new AttrRelProviders(); + hash->Put(aID, providers); + } + return providers; +} + +inline void DocAccessible::RemoveRelProvidersIfEmpty(dom::Element* aElement, + const nsAString& aID) { + dom::DocumentOrShadowRoot* docOrShadowRoot = + aElement->GetUncomposedDocOrConnectedShadowRoot(); + DependentIDsHashtable* hash = mDependentIDsHashes.Get(docOrShadowRoot); + if (hash) { + AttrRelProviders* providers = hash->Get(aID); + if (providers && providers->Length() == 0) { + hash->Remove(aID); + if (mDependentIDsHashes.IsEmpty()) { + mDependentIDsHashes.Remove(docOrShadowRoot); + } + } + } +} + +} // namespace a11y +} // namespace mozilla + +#endif diff --git a/accessible/generic/DocAccessible.cpp b/accessible/generic/DocAccessible.cpp new file mode 100644 index 0000000000..e8ed40092d --- /dev/null +++ b/accessible/generic/DocAccessible.cpp @@ -0,0 +1,2701 @@ +/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* vim: set ts=8 sts=2 et sw=2 tw=80: */ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +#include "Accessible-inl.h" +#include "AccIterator.h" +#include "DocAccessible-inl.h" +#include "DocAccessibleChild.h" +#include "HTMLImageMapAccessible.h" +#include "nsAccCache.h" +#include "nsAccessiblePivot.h" +#include "nsAccUtils.h" +#include "nsDeckFrame.h" +#include "nsEventShell.h" +#include "nsLayoutUtils.h" +#include "nsTextEquivUtils.h" +#include "Role.h" +#include "RootAccessible.h" +#include "TreeWalker.h" +#include "xpcAccessibleDocument.h" + +#include "nsCommandManager.h" +#include "nsContentUtils.h" +#include "nsIDocShell.h" +#include "mozilla/dom/Document.h" +#include "nsPIDOMWindow.h" +#include "nsIEditingSession.h" +#include "nsIFrame.h" +#include "nsIInterfaceRequestorUtils.h" +#include "nsImageFrame.h" +#include "nsIPersistentProperties2.h" +#include "nsViewManager.h" +#include "nsIScrollableFrame.h" +#include "nsUnicharUtils.h" +#include "nsIURI.h" +#include "nsIWebNavigation.h" +#include "nsFocusManager.h" +#include "mozilla/ArrayUtils.h" +#include "mozilla/Assertions.h" +#include "mozilla/EventStates.h" +#include "mozilla/HTMLEditor.h" +#include "mozilla/PresShell.h" +#include "mozilla/TextEditor.h" +#include "mozilla/dom/AncestorIterator.h" +#include "mozilla/dom/BrowserChild.h" +#include "mozilla/dom/DocumentType.h" +#include "mozilla/dom/Element.h" +#include "mozilla/dom/MutationEventBinding.h" +#include "mozilla/dom/UserActivation.h" +#include "HTMLElementAccessibles.h" + +using namespace mozilla; +using namespace mozilla::a11y; + +//////////////////////////////////////////////////////////////////////////////// +// Static member initialization + +static nsStaticAtom* const kRelationAttrs[] = {nsGkAtoms::aria_labelledby, + nsGkAtoms::aria_describedby, + nsGkAtoms::aria_details, + nsGkAtoms::aria_owns, + nsGkAtoms::aria_controls, + nsGkAtoms::aria_flowto, + nsGkAtoms::aria_errormessage, + nsGkAtoms::_for, + nsGkAtoms::control}; + +static const uint32_t kRelationAttrsLen = ArrayLength(kRelationAttrs); + +//////////////////////////////////////////////////////////////////////////////// +// Constructor/desctructor + +DocAccessible::DocAccessible(dom::Document* aDocument, + PresShell* aPresShell) + : // XXX don't pass a document to the Accessible constructor so that we + // don't set mDoc until our vtable is fully setup. If we set mDoc before + // setting up the vtable we will call Accessible::AddRef() but not the + // overrides of it for subclasses. It is important to call those + // overrides to avoid confusing leak checking machinary. + HyperTextAccessibleWrap(nullptr, nullptr), + // XXX aaronl should we use an algorithm for the initial cache size? + mAccessibleCache(kDefaultCacheLength), + mNodeToAccessibleMap(kDefaultCacheLength), + mDocumentNode(aDocument), + mLoadState(eTreeConstructionPending), + mDocFlags(0), + mLoadEventType(0), + mARIAAttrOldValue{nullptr}, + mVirtualCursor(nullptr), + mPresShell(aPresShell), + mIPCDoc(nullptr) { + mGenericTypes |= eDocument; + mStateFlags |= eNotNodeMapEntry; + mDoc = this; + + MOZ_ASSERT(mPresShell, "should have been given a pres shell"); + mPresShell->SetDocAccessible(this); +} + +DocAccessible::~DocAccessible() { + NS_ASSERTION(!mPresShell, "LastRelease was never called!?!"); +} + +//////////////////////////////////////////////////////////////////////////////// +// nsISupports + +NS_IMPL_CYCLE_COLLECTION_CLASS(DocAccessible) + +NS_IMPL_CYCLE_COLLECTION_TRAVERSE_BEGIN_INHERITED(DocAccessible, Accessible) + NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mNotificationController) + NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mVirtualCursor) + NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mChildDocuments) + for (auto hashesIter = tmp->mDependentIDsHashes.Iter(); !hashesIter.Done(); + hashesIter.Next()) { + auto dependentIDsHash = hashesIter.UserData(); + for (auto providersIter = dependentIDsHash->Iter(); !providersIter.Done(); + providersIter.Next()) { + AttrRelProviders* providers = providersIter.UserData(); + for (int32_t provIdx = providers->Length() - 1; provIdx >= 0; provIdx--) { + NS_CYCLE_COLLECTION_NOTE_EDGE_NAME( + cb, "content of dependent ids hash entry of document accessible"); + + const auto& provider = (*providers)[provIdx]; + cb.NoteXPCOMChild(provider->mContent); + } + } + } + NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mAccessibleCache) + NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mAnchorJumpElm) + NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mInvalidationList) + for (auto it = tmp->mARIAOwnsHash.ConstIter(); !it.Done(); it.Next()) { + nsTArray<RefPtr<Accessible>>* ar = it.UserData(); + for (uint32_t i = 0; i < ar->Length(); i++) { + NS_CYCLE_COLLECTION_NOTE_EDGE_NAME(cb, "mARIAOwnsHash entry item"); + cb.NoteXPCOMChild(ar->ElementAt(i)); + } + } +NS_IMPL_CYCLE_COLLECTION_TRAVERSE_END + +NS_IMPL_CYCLE_COLLECTION_UNLINK_BEGIN_INHERITED(DocAccessible, Accessible) + NS_IMPL_CYCLE_COLLECTION_UNLINK(mNotificationController) + NS_IMPL_CYCLE_COLLECTION_UNLINK(mVirtualCursor) + NS_IMPL_CYCLE_COLLECTION_UNLINK(mChildDocuments) + tmp->mDependentIDsHashes.Clear(); + tmp->mNodeToAccessibleMap.Clear(); + NS_IMPL_CYCLE_COLLECTION_UNLINK(mAccessibleCache) + NS_IMPL_CYCLE_COLLECTION_UNLINK(mAnchorJumpElm) + NS_IMPL_CYCLE_COLLECTION_UNLINK(mInvalidationList) + NS_IMPL_CYCLE_COLLECTION_UNLINK_WEAK_REFERENCE + tmp->mARIAOwnsHash.Clear(); +NS_IMPL_CYCLE_COLLECTION_UNLINK_END + +NS_INTERFACE_MAP_BEGIN_CYCLE_COLLECTION(DocAccessible) + NS_INTERFACE_MAP_ENTRY(nsIDocumentObserver) + NS_INTERFACE_MAP_ENTRY(nsIMutationObserver) + NS_INTERFACE_MAP_ENTRY(nsISupportsWeakReference) + NS_INTERFACE_MAP_ENTRY(nsIObserver) + NS_INTERFACE_MAP_ENTRY(nsIAccessiblePivotObserver) +NS_INTERFACE_MAP_END_INHERITING(HyperTextAccessible) + +NS_IMPL_ADDREF_INHERITED(DocAccessible, HyperTextAccessible) +NS_IMPL_RELEASE_INHERITED(DocAccessible, HyperTextAccessible) + +//////////////////////////////////////////////////////////////////////////////// +// nsIAccessible + +ENameValueFlag DocAccessible::Name(nsString& aName) const { + aName.Truncate(); + + if (mParent) { + mParent->Name(aName); // Allow owning iframe to override the name + } + if (aName.IsEmpty()) { + // Allow name via aria-labelledby or title attribute + Accessible::Name(aName); + } + if (aName.IsEmpty()) { + Title(aName); // Try title element + } + if (aName.IsEmpty()) { // Last resort: use URL + URL(aName); + } + + return eNameOK; +} + +// Accessible public method +role DocAccessible::NativeRole() const { + nsCOMPtr<nsIDocShell> docShell = nsCoreUtils::GetDocShellFor(mDocumentNode); + if (docShell) { + nsCOMPtr<nsIDocShellTreeItem> sameTypeRoot; + docShell->GetInProcessSameTypeRootTreeItem(getter_AddRefs(sameTypeRoot)); + int32_t itemType = docShell->ItemType(); + if (sameTypeRoot == docShell) { + // Root of content or chrome tree + if (itemType == nsIDocShellTreeItem::typeChrome) + return roles::CHROME_WINDOW; + + if (itemType == nsIDocShellTreeItem::typeContent) { + return roles::DOCUMENT; + } + } else if (itemType == nsIDocShellTreeItem::typeContent) { + return roles::DOCUMENT; + } + } + + return roles::PANE; // Fall back; +} + +void DocAccessible::Description(nsString& aDescription) { + if (mParent) mParent->Description(aDescription); + + if (HasOwnContent() && aDescription.IsEmpty()) { + nsTextEquivUtils::GetTextEquivFromIDRefs(this, nsGkAtoms::aria_describedby, + aDescription); + } +} + +// Accessible public method +uint64_t DocAccessible::NativeState() const { + // Document is always focusable. + uint64_t state = + states::FOCUSABLE; // keep in sync with NativeInteractiveState() impl + if (FocusMgr()->IsFocused(this)) state |= states::FOCUSED; + + // Expose stale state until the document is ready (DOM is loaded and tree is + // constructed). + if (!HasLoadState(eReady)) state |= states::STALE; + + // Expose state busy until the document and all its subdocuments is completely + // loaded. + if (!HasLoadState(eCompletelyLoaded)) state |= states::BUSY; + + nsIFrame* frame = GetFrame(); + if (!frame || !frame->IsVisibleConsideringAncestors( + nsIFrame::VISIBILITY_CROSS_CHROME_CONTENT_BOUNDARY)) { + state |= states::INVISIBLE | states::OFFSCREEN; + } + + RefPtr<TextEditor> textEditor = GetEditor(); + state |= textEditor ? states::EDITABLE : states::READONLY; + + return state; +} + +uint64_t DocAccessible::NativeInteractiveState() const { + // Document is always focusable. + return states::FOCUSABLE; +} + +bool DocAccessible::NativelyUnavailable() const { return false; } + +// Accessible public method +void DocAccessible::ApplyARIAState(uint64_t* aState) const { + // Grab states from content element. + if (mContent) Accessible::ApplyARIAState(aState); + + // Allow iframe/frame etc. to have final state override via ARIA. + if (mParent) mParent->ApplyARIAState(aState); +} + +already_AddRefed<nsIPersistentProperties> DocAccessible::Attributes() { + nsCOMPtr<nsIPersistentProperties> attributes = + HyperTextAccessibleWrap::Attributes(); + + // No attributes if document is not attached to the tree or if it's a root + // document. + if (!mParent || IsRoot()) return attributes.forget(); + + // Override ARIA object attributes from outerdoc. + aria::AttrIterator attribIter(mParent->GetContent()); + nsAutoString name, value, unused; + while (attribIter.Next(name, value)) + attributes->SetStringProperty(NS_ConvertUTF16toUTF8(name), value, unused); + + return attributes.forget(); +} + +Accessible* DocAccessible::FocusedChild() { + // Return an accessible for the current global focus, which does not have to + // be contained within the current document. + return FocusMgr()->FocusedAccessible(); +} + +void DocAccessible::TakeFocus() const { + // Focus the document. + nsFocusManager* fm = nsFocusManager::GetFocusManager(); + RefPtr<dom::Element> newFocus; + dom::AutoHandlingUserInputStatePusher inputStatePusher(true); + fm->MoveFocus(mDocumentNode->GetWindow(), nullptr, + nsFocusManager::MOVEFOCUS_ROOT, 0, getter_AddRefs(newFocus)); +} + +// HyperTextAccessible method +already_AddRefed<TextEditor> DocAccessible::GetEditor() const { + // Check if document is editable (designMode="on" case). Otherwise check if + // the html:body (for HTML document case) or document element is editable. + if (!mDocumentNode->HasFlag(NODE_IS_EDITABLE) && + (!mContent || !mContent->HasFlag(NODE_IS_EDITABLE))) + return nullptr; + + nsCOMPtr<nsIDocShell> docShell = mDocumentNode->GetDocShell(); + if (!docShell) { + return nullptr; + } + + nsCOMPtr<nsIEditingSession> editingSession; + docShell->GetEditingSession(getter_AddRefs(editingSession)); + if (!editingSession) return nullptr; // No editing session interface + + RefPtr<HTMLEditor> htmlEditor = + editingSession->GetHTMLEditorForWindow(mDocumentNode->GetWindow()); + if (!htmlEditor) { + return nullptr; + } + + bool isEditable = false; + htmlEditor->GetIsDocumentEditable(&isEditable); + if (isEditable) { + return htmlEditor.forget(); + } + + return nullptr; +} + +// DocAccessible public method + +void DocAccessible::URL(nsAString& aURL) const { + nsCOMPtr<nsISupports> container = mDocumentNode->GetContainer(); + nsCOMPtr<nsIWebNavigation> webNav(do_GetInterface(container)); + nsAutoCString theURL; + if (webNav) { + nsCOMPtr<nsIURI> pURI; + webNav->GetCurrentURI(getter_AddRefs(pURI)); + if (pURI) pURI->GetSpec(theURL); + } + CopyUTF8toUTF16(theURL, aURL); +} + +void DocAccessible::Title(nsString& aTitle) const { + mDocumentNode->GetTitle(aTitle); +} + +void DocAccessible::MimeType(nsAString& aType) const { + mDocumentNode->GetContentType(aType); +} + +void DocAccessible::DocType(nsAString& aType) const { + dom::DocumentType* docType = mDocumentNode->GetDoctype(); + if (docType) docType->GetPublicId(aType); +} + +//////////////////////////////////////////////////////////////////////////////// +// Accessible + +void DocAccessible::Init() { +#ifdef A11Y_LOG + if (logging::IsEnabled(logging::eDocCreate)) + logging::DocCreate("document initialize", mDocumentNode, this); +#endif + + // Initialize notification controller. + mNotificationController = new NotificationController(this, mPresShell); + + // Mark the document accessible as loaded if its DOM document was loaded at + // this point (this can happen because a11y is started late or DOM document + // having no container was loaded. + if (mDocumentNode->GetReadyStateEnum() == dom::Document::READYSTATE_COMPLETE) + mLoadState |= eDOMLoaded; + + AddEventListeners(); +} + +void DocAccessible::Shutdown() { + if (!mPresShell) { // already shutdown + return; + } + +#ifdef A11Y_LOG + if (logging::IsEnabled(logging::eDocDestroy)) + logging::DocDestroy("document shutdown", mDocumentNode, this); +#endif + + // Mark the document as shutdown before AT is notified about the document + // removal from its container (valid for root documents on ATK and due to + // some reason for MSAA, refer to bug 757392 for details). + mStateFlags |= eIsDefunct; + + if (mNotificationController) { + mNotificationController->Shutdown(); + mNotificationController = nullptr; + } + + RemoveEventListeners(); + + if (mParent) { + DocAccessible* parentDocument = mParent->Document(); + if (parentDocument) parentDocument->RemoveChildDocument(this); + + mParent->RemoveChild(this); + MOZ_ASSERT(!mParent, "Parent has to be null!"); + } + + // Walk the array backwards because child documents remove themselves from the + // array as they are shutdown. + int32_t childDocCount = mChildDocuments.Length(); + for (int32_t idx = childDocCount - 1; idx >= 0; idx--) + mChildDocuments[idx]->Shutdown(); + + mChildDocuments.Clear(); + + // XXX thinking about ordering? + if (mIPCDoc) { + MOZ_ASSERT(IPCAccessibilityActive()); + mIPCDoc->Shutdown(); + MOZ_ASSERT(!mIPCDoc); + } + + if (mVirtualCursor) { + mVirtualCursor->RemoveObserver(this); + mVirtualCursor = nullptr; + } + + mPresShell->SetDocAccessible(nullptr); + mPresShell = nullptr; // Avoid reentrancy + + mDependentIDsHashes.Clear(); + mNodeToAccessibleMap.Clear(); + + mAnchorJumpElm = nullptr; + mInvalidationList.Clear(); + + for (auto iter = mAccessibleCache.Iter(); !iter.Done(); iter.Next()) { + Accessible* accessible = iter.Data(); + MOZ_ASSERT(accessible); + if (accessible && !accessible->IsDefunct()) { + // Unlink parent to avoid its cleaning overhead in shutdown. + accessible->mParent = nullptr; + accessible->Shutdown(); + } + iter.Remove(); + } + + HyperTextAccessibleWrap::Shutdown(); + + GetAccService()->NotifyOfDocumentShutdown(this, mDocumentNode); + mDocumentNode = nullptr; +} + +nsIFrame* DocAccessible::GetFrame() const { + nsIFrame* root = nullptr; + if (mPresShell) { + root = mPresShell->GetRootFrame(); + } + + return root; +} + +nsINode* DocAccessible::GetNode() const { return mDocumentNode; } + +// DocAccessible protected member +nsRect DocAccessible::RelativeBounds(nsIFrame** aRelativeFrame) const { + *aRelativeFrame = GetFrame(); + + dom::Document* document = mDocumentNode; + dom::Document* parentDoc = nullptr; + + nsRect bounds; + while (document) { + PresShell* presShell = document->GetPresShell(); + if (!presShell) { + return nsRect(); + } + + nsRect scrollPort; + nsIScrollableFrame* sf = presShell->GetRootScrollFrameAsScrollable(); + if (sf) { + scrollPort = sf->GetScrollPortRect(); + } else { + nsIFrame* rootFrame = presShell->GetRootFrame(); + if (!rootFrame) return nsRect(); + + scrollPort = rootFrame->GetRect(); + } + + if (parentDoc) { // After first time thru loop + // XXXroc bogus code! scrollPort is relative to the viewport of + // this document, but we're intersecting rectangles derived from + // multiple documents and assuming they're all in the same coordinate + // system. See bug 514117. + bounds.IntersectRect(scrollPort, bounds); + } else { // First time through loop + bounds = scrollPort; + } + + document = parentDoc = document->GetInProcessParentDocument(); + } + + return bounds; +} + +// DocAccessible protected member +nsresult DocAccessible::AddEventListeners() { + nsCOMPtr<nsIDocShell> docShell(mDocumentNode->GetDocShell()); + + // We want to add a command observer only if the document is content and has + // an editor. + if (docShell->ItemType() == nsIDocShellTreeItem::typeContent) { + RefPtr<nsCommandManager> commandManager = docShell->GetCommandManager(); + if (commandManager) + commandManager->AddCommandObserver(this, "obs_documentCreated"); + } + + SelectionMgr()->AddDocSelectionListener(mPresShell); + + // Add document observer. + mDocumentNode->AddObserver(this); + return NS_OK; +} + +// DocAccessible protected member +nsresult DocAccessible::RemoveEventListeners() { + // Remove listeners associated with content documents + NS_ASSERTION(mDocumentNode, "No document during removal of listeners."); + + if (mDocumentNode) { + mDocumentNode->RemoveObserver(this); + + nsCOMPtr<nsIDocShell> docShell(mDocumentNode->GetDocShell()); + NS_ASSERTION(docShell, "doc should support nsIDocShellTreeItem."); + + if (docShell) { + if (docShell->ItemType() == nsIDocShellTreeItem::typeContent) { + RefPtr<nsCommandManager> commandManager = docShell->GetCommandManager(); + if (commandManager) { + commandManager->RemoveCommandObserver(this, "obs_documentCreated"); + } + } + } + } + + if (mScrollWatchTimer) { + mScrollWatchTimer->Cancel(); + mScrollWatchTimer = nullptr; + NS_RELEASE_THIS(); // Kung fu death grip + } + + SelectionMgr()->RemoveDocSelectionListener(mPresShell); + return NS_OK; +} + +void DocAccessible::ScrollTimerCallback(nsITimer* aTimer, void* aClosure) { + DocAccessible* docAcc = reinterpret_cast<DocAccessible*>(aClosure); + + if (docAcc) { + // Dispatch a scroll-end for all entries in table. They have not + // been scrolled in at least `kScrollEventInterval`. + for (auto iter = docAcc->mLastScrollingDispatch.Iter(); !iter.Done(); + iter.Next()) { + docAcc->DispatchScrollingEvent(iter.Key(), + nsIAccessibleEvent::EVENT_SCROLLING_END); + iter.Remove(); + } + + if (docAcc->mScrollWatchTimer) { + docAcc->mScrollWatchTimer = nullptr; + NS_RELEASE(docAcc); // Release kung fu death grip + } + } +} + +void DocAccessible::HandleScroll(nsINode* aTarget) { + const uint32_t kScrollEventInterval = 100; + TimeStamp now = TimeStamp::Now(); + TimeStamp lastDispatch; + // If we haven't dispatched a scrolling event for a target in at least + // kScrollEventInterval milliseconds, dispatch one now. + if (!mLastScrollingDispatch.Get(aTarget, &lastDispatch) || + (now - lastDispatch).ToMilliseconds() >= kScrollEventInterval) { + // We can't fire events on a document whose tree isn't constructed yet. + if (HasLoadState(eTreeConstructed)) { + DispatchScrollingEvent(aTarget, nsIAccessibleEvent::EVENT_SCROLLING); + } + mLastScrollingDispatch.Put(aTarget, now); + } + + // If timer callback is still pending, push it 100ms into the future. + // When scrolling ends and we don't fire this callback anymore, the + // timer callback will fire and dispatch an EVENT_SCROLLING_END. + if (mScrollWatchTimer) { + mScrollWatchTimer->SetDelay(kScrollEventInterval); + } else { + NS_NewTimerWithFuncCallback(getter_AddRefs(mScrollWatchTimer), + ScrollTimerCallback, this, kScrollEventInterval, + nsITimer::TYPE_ONE_SHOT, + "a11y::DocAccessible::ScrollPositionDidChange"); + if (mScrollWatchTimer) { + NS_ADDREF_THIS(); // Kung fu death grip + } + } +} + +//////////////////////////////////////////////////////////////////////////////// +// nsIObserver + +NS_IMETHODIMP +DocAccessible::Observe(nsISupports* aSubject, const char* aTopic, + const char16_t* aData) { + if (!nsCRT::strcmp(aTopic, "obs_documentCreated")) { + // State editable will now be set, readonly is now clear + // Normally we only fire delayed events created from the node, not an + // accessible object. See the AccStateChangeEvent constructor for details + // about this exceptional case. + RefPtr<AccEvent> event = + new AccStateChangeEvent(this, states::EDITABLE, true); + FireDelayedEvent(event); + } + + return NS_OK; +} + +//////////////////////////////////////////////////////////////////////////////// +// nsIAccessiblePivotObserver + +NS_IMETHODIMP +DocAccessible::OnPivotChanged(nsIAccessiblePivot* aPivot, + nsIAccessible* aOldAccessible, int32_t aOldStart, + int32_t aOldEnd, nsIAccessible* aNewAccessible, + int32_t aNewStart, int32_t aNewEnd, + PivotMoveReason aReason, + TextBoundaryType aBoundaryType, + bool aIsFromUserInput) { + RefPtr<AccEvent> event = new AccVCChangeEvent( + this, (aOldAccessible ? aOldAccessible->ToInternalAccessible() : nullptr), + aOldStart, aOldEnd, + (aNewAccessible ? aNewAccessible->ToInternalAccessible() : nullptr), + aNewStart, aNewEnd, aReason, aBoundaryType, + aIsFromUserInput ? eFromUserInput : eNoUserInput); + nsEventShell::FireEvent(event); + + return NS_OK; +} + +//////////////////////////////////////////////////////////////////////////////// +// nsIDocumentObserver + +NS_IMPL_NSIDOCUMENTOBSERVER_CORE_STUB(DocAccessible) +NS_IMPL_NSIDOCUMENTOBSERVER_LOAD_STUB(DocAccessible) + +void DocAccessible::AttributeWillChange(dom::Element* aElement, + int32_t aNameSpaceID, + nsAtom* aAttribute, int32_t aModType) { + Accessible* accessible = GetAccessible(aElement); + if (!accessible) { + if (aElement != mContent) return; + + accessible = this; + } + + // Update dependent IDs cache. Take care of elements that are accessible + // because dependent IDs cache doesn't contain IDs from non accessible + // elements. + if (aModType != dom::MutationEvent_Binding::ADDITION) + RemoveDependentIDsFor(accessible, aAttribute); + + if (aAttribute == nsGkAtoms::id) { + RelocateARIAOwnedIfNeeded(aElement); + } + + // Store the ARIA attribute old value so that it can be used after + // attribute change. Note, we assume there's no nested ARIA attribute + // changes. If this happens then we should end up with keeping a stack of + // old values. + + // XXX TODO: bugs 472142, 472143. + // Here we will want to cache whatever attribute values we are interested + // in, such as the existence of aria-pressed for button (so we know if we + // need to newly expose it as a toggle button) etc. + if (aAttribute == nsGkAtoms::aria_checked || + aAttribute == nsGkAtoms::aria_pressed) { + mARIAAttrOldValue = (aModType != dom::MutationEvent_Binding::ADDITION) + ? nsAccUtils::GetARIAToken(aElement, aAttribute) + : nullptr; + return; + } + + if (aAttribute == nsGkAtoms::aria_disabled || aAttribute == nsGkAtoms::href || + aAttribute == nsGkAtoms::disabled || aAttribute == nsGkAtoms::tabindex || + aAttribute == nsGkAtoms::contenteditable) { + mPrevStateBits = accessible->State(); + } +} + +void DocAccessible::NativeAnonymousChildListChange(nsIContent* aContent, + bool aIsRemove) { + if (aIsRemove) { +#ifdef A11Y_LOG + if (logging::IsEnabled(logging::eTree)) { + logging::MsgBegin("TREE", "Anonymous content removed; doc: %p", this); + logging::Node("node", aContent); + logging::MsgEnd(); + } +#endif + + ContentRemoved(aContent); + } +} + +void DocAccessible::AttributeChanged(dom::Element* aElement, + int32_t aNameSpaceID, nsAtom* aAttribute, + int32_t aModType, + const nsAttrValue* aOldValue) { + NS_ASSERTION(!IsDefunct(), + "Attribute changed called on defunct document accessible!"); + + // Proceed even if the element is not accessible because element may become + // accessible if it gets certain attribute. + if (UpdateAccessibleOnAttrChange(aElement, aAttribute)) return; + + // Update the accessible tree on aria-hidden change. Make sure to not create + // a tree under aria-hidden='true'. + if (aAttribute == nsGkAtoms::aria_hidden) { + if (aria::HasDefinedARIAHidden(aElement)) { + ContentRemoved(aElement); + } else { + ContentInserted(aElement, aElement->GetNextSibling()); + } + return; + } + + // Ignore attribute change if the element doesn't have an accessible (at all + // or still) iff the element is not a root content of this document accessible + // (which is treated as attribute change on this document accessible). + // Note: we don't bail if all the content hasn't finished loading because + // these attributes are changing for a loaded part of the content. + Accessible* accessible = GetAccessible(aElement); + if (!accessible) { + if (mContent != aElement) return; + + accessible = this; + } + + MOZ_ASSERT(accessible->IsBoundToParent() || accessible->IsDoc(), + "DOM attribute change on an accessible detached from the tree"); + + // Fire accessible events iff there's an accessible, otherwise we consider + // the accessible state wasn't changed, i.e. its state is initial state. + AttributeChangedImpl(accessible, aNameSpaceID, aAttribute, aModType); + + // Update dependent IDs cache. Take care of accessible elements because no + // accessible element means either the element is not accessible at all or + // its accessible will be created later. It doesn't make sense to keep + // dependent IDs for non accessible elements. For the second case we'll update + // dependent IDs cache when its accessible is created. + if (aModType == dom::MutationEvent_Binding::MODIFICATION || + aModType == dom::MutationEvent_Binding::ADDITION) { + AddDependentIDsFor(accessible, aAttribute); + } +} + +// DocAccessible protected member +void DocAccessible::AttributeChangedImpl(Accessible* aAccessible, + int32_t aNameSpaceID, + nsAtom* aAttribute, int32_t aModType) { + // Fire accessible event after short timer, because we need to wait for + // DOM attribute & resulting layout to actually change. Otherwise, + // assistive technology will retrieve the wrong state/value/selection info. + + // XXX todo + // We still need to handle special HTML cases here + // For example, if an <img>'s usemap attribute is modified + // Otherwise it may just be a state change, for example an object changing + // its visibility + // + // XXX todo: report aria state changes for "undefined" literal value changes + // filed as bug 472142 + // + // XXX todo: invalidate accessible when aria state changes affect exposed + // role filed as bug 472143 + + // Universal boolean properties that don't require a role. Fire the state + // change when disabled or aria-disabled attribute is set. + // Note. Checking the XUL or HTML namespace would not seem to gain us + // anything, because disabled attribute really is going to mean the same + // thing in any namespace. + // Note. We use the attribute instead of the disabled state bit because + // ARIA's aria-disabled does not affect the disabled state bit. + if (aAttribute == nsGkAtoms::disabled || + aAttribute == nsGkAtoms::aria_disabled) { + // disabled can affect focusable state + aAccessible->MaybeFireFocusableStateChange( + (mPrevStateBits & states::FOCUSABLE) != 0); + + // Do nothing if state wasn't changed (like @aria-disabled was removed but + // @disabled is still presented). + uint64_t unavailableState = (aAccessible->State() & states::UNAVAILABLE); + if ((mPrevStateBits & states::UNAVAILABLE) == unavailableState) { + return; + } + + RefPtr<AccEvent> enabledChangeEvent = new AccStateChangeEvent( + aAccessible, states::ENABLED, !unavailableState); + FireDelayedEvent(enabledChangeEvent); + + RefPtr<AccEvent> sensitiveChangeEvent = new AccStateChangeEvent( + aAccessible, states::SENSITIVE, !unavailableState); + FireDelayedEvent(sensitiveChangeEvent); + + return; + } + + if (aAttribute == nsGkAtoms::tabindex) { + // Fire a focusable state change event if the previous state was different. + // It may be the same if tabindex is on a redundantly focusable element. + aAccessible->MaybeFireFocusableStateChange( + (mPrevStateBits & states::FOCUSABLE)); + return; + } + + // When a details object has its open attribute changed + // we should fire a state-change event on the accessible of + // its main summary + if (aAttribute == nsGkAtoms::open) { + // FromDetails checks if the given accessible belongs to + // a details frame and also locates the accessible of its + // main summary. + if (HTMLSummaryAccessible* summaryAccessible = + HTMLSummaryAccessible::FromDetails(aAccessible)) { + RefPtr<AccEvent> expandedChangeEvent = + new AccStateChangeEvent(summaryAccessible, states::EXPANDED); + FireDelayedEvent(expandedChangeEvent); + return; + } + } + + // Check for namespaced ARIA attribute + if (aNameSpaceID == kNameSpaceID_None) { + // Check for hyphenated aria-foo property? + if (StringBeginsWith(nsDependentAtomString(aAttribute), u"aria-"_ns)) { + ARIAAttributeChanged(aAccessible, aAttribute); + } + } + + // Fire name change and description change events. XXX: it's not complete and + // dupes the code logic of accessible name and description calculation, we do + // that for performance reasons. + if (aAttribute == nsGkAtoms::aria_label) { + FireDelayedEvent(nsIAccessibleEvent::EVENT_NAME_CHANGE, aAccessible); + return; + } + + if (aAttribute == nsGkAtoms::aria_describedby) { + FireDelayedEvent(nsIAccessibleEvent::EVENT_DESCRIPTION_CHANGE, aAccessible); + return; + } + + dom::Element* elm = aAccessible->GetContent()->AsElement(); + if (aAttribute == nsGkAtoms::aria_labelledby && + !elm->HasAttr(kNameSpaceID_None, nsGkAtoms::aria_label)) { + FireDelayedEvent(nsIAccessibleEvent::EVENT_NAME_CHANGE, aAccessible); + return; + } + + if (aAttribute == nsGkAtoms::alt && + !elm->HasAttr(kNameSpaceID_None, nsGkAtoms::aria_label) && + !elm->HasAttr(kNameSpaceID_None, nsGkAtoms::aria_labelledby)) { + FireDelayedEvent(nsIAccessibleEvent::EVENT_NAME_CHANGE, aAccessible); + return; + } + + if (aAttribute == nsGkAtoms::title) { + if (!elm->HasAttr(kNameSpaceID_None, nsGkAtoms::aria_label) && + !elm->HasAttr(kNameSpaceID_None, nsGkAtoms::aria_labelledby) && + !elm->HasAttr(kNameSpaceID_None, nsGkAtoms::alt)) { + FireDelayedEvent(nsIAccessibleEvent::EVENT_NAME_CHANGE, aAccessible); + return; + } + + if (!elm->HasAttr(kNameSpaceID_None, nsGkAtoms::aria_describedby)) + FireDelayedEvent(nsIAccessibleEvent::EVENT_DESCRIPTION_CHANGE, + aAccessible); + + return; + } + + if (aAttribute == nsGkAtoms::aria_busy) { + bool isOn = elm->AttrValueIs(aNameSpaceID, aAttribute, nsGkAtoms::_true, + eCaseMatters); + RefPtr<AccEvent> event = + new AccStateChangeEvent(aAccessible, states::BUSY, isOn); + FireDelayedEvent(event); + return; + } + + if (aAttribute == nsGkAtoms::id) { + RelocateARIAOwnedIfNeeded(elm); + ARIAActiveDescendantIDMaybeMoved(elm); + } + + // ARIA or XUL selection + if ((aAccessible->GetContent()->IsXULElement() && + aAttribute == nsGkAtoms::selected) || + aAttribute == nsGkAtoms::aria_selected) { + Accessible* widget = + nsAccUtils::GetSelectableContainer(aAccessible, aAccessible->State()); + if (widget) { + AccSelChangeEvent::SelChangeType selChangeType = + elm->AttrValueIs(aNameSpaceID, aAttribute, nsGkAtoms::_true, + eCaseMatters) + ? AccSelChangeEvent::eSelectionAdd + : AccSelChangeEvent::eSelectionRemove; + + RefPtr<AccEvent> event = + new AccSelChangeEvent(widget, aAccessible, selChangeType); + FireDelayedEvent(event); + } + + return; + } + + if (aAttribute == nsGkAtoms::contenteditable) { + RefPtr<AccEvent> editableChangeEvent = + new AccStateChangeEvent(aAccessible, states::EDITABLE); + FireDelayedEvent(editableChangeEvent); + // Fire a focusable state change event if the previous state was different. + // It may be the same if contenteditable is set on a node that doesn't + // support it. Like an <input>. + aAccessible->MaybeFireFocusableStateChange( + (mPrevStateBits & states::FOCUSABLE)); + return; + } + + if (aAttribute == nsGkAtoms::value) { + if (aAccessible->IsProgress()) + FireDelayedEvent(nsIAccessibleEvent::EVENT_VALUE_CHANGE, aAccessible); + return; + } + + if (aModType == dom::MutationEvent_Binding::REMOVAL || + aModType == dom::MutationEvent_Binding::ADDITION) { + if (aAttribute == nsGkAtoms::href) { + if (aAccessible->IsHTMLLink() && + !nsCoreUtils::HasClickListener(aAccessible->GetContent())) { + RefPtr<AccEvent> linkedChangeEvent = + new AccStateChangeEvent(aAccessible, states::LINKED); + FireDelayedEvent(linkedChangeEvent); + // Fire a focusable state change event if the previous state was + // different. It may be the same if there is tabindex on this link. + aAccessible->MaybeFireFocusableStateChange( + (mPrevStateBits & states::FOCUSABLE)); + } + } + } +} + +// DocAccessible protected member +void DocAccessible::ARIAAttributeChanged(Accessible* aAccessible, + nsAtom* aAttribute) { + // Note: For universal/global ARIA states and properties we don't care if + // there is an ARIA role present or not. + + if (aAttribute == nsGkAtoms::aria_required) { + RefPtr<AccEvent> event = + new AccStateChangeEvent(aAccessible, states::REQUIRED); + FireDelayedEvent(event); + return; + } + + if (aAttribute == nsGkAtoms::aria_invalid) { + RefPtr<AccEvent> event = + new AccStateChangeEvent(aAccessible, states::INVALID); + FireDelayedEvent(event); + return; + } + + // The activedescendant universal property redirects accessible focus events + // to the element with the id that activedescendant points to. Make sure + // the tree up to date before processing. In other words, when a node has just + // been inserted, the tree won't be up to date yet, so we must always schedule + // an async notification so that a newly inserted node will be present in + // the tree. + if (aAttribute == nsGkAtoms::aria_activedescendant) { + mNotificationController->ScheduleNotification<DocAccessible, Accessible>( + this, &DocAccessible::ARIAActiveDescendantChanged, aAccessible); + return; + } + + // We treat aria-expanded as a global ARIA state for historical reasons + if (aAttribute == nsGkAtoms::aria_expanded) { + RefPtr<AccEvent> event = + new AccStateChangeEvent(aAccessible, states::EXPANDED); + FireDelayedEvent(event); + return; + } + + // For aria attributes like drag and drop changes we fire a generic attribute + // change event; at least until native API comes up with a more meaningful + // event. + uint8_t attrFlags = aria::AttrCharacteristicsFor(aAttribute); + if (!(attrFlags & ATTR_BYPASSOBJ)) { + RefPtr<AccEvent> event = + new AccObjectAttrChangedEvent(aAccessible, aAttribute); + FireDelayedEvent(event); + } + + dom::Element* elm = aAccessible->GetContent()->AsElement(); + + if (aAttribute == nsGkAtoms::aria_checked || + (aAccessible->IsButton() && aAttribute == nsGkAtoms::aria_pressed)) { + const uint64_t kState = (aAttribute == nsGkAtoms::aria_checked) + ? states::CHECKED + : states::PRESSED; + RefPtr<AccEvent> event = new AccStateChangeEvent(aAccessible, kState); + FireDelayedEvent(event); + + bool wasMixed = (mARIAAttrOldValue == nsGkAtoms::mixed); + bool isMixed = elm->AttrValueIs(kNameSpaceID_None, aAttribute, + nsGkAtoms::mixed, eCaseMatters); + if (isMixed != wasMixed) { + RefPtr<AccEvent> event = + new AccStateChangeEvent(aAccessible, states::MIXED, isMixed); + FireDelayedEvent(event); + } + return; + } + + if (aAttribute == nsGkAtoms::aria_readonly) { + RefPtr<AccEvent> event = + new AccStateChangeEvent(aAccessible, states::READONLY); + FireDelayedEvent(event); + return; + } + + // Fire text value change event whenever aria-valuetext is changed. + if (aAttribute == nsGkAtoms::aria_valuetext) { + FireDelayedEvent(nsIAccessibleEvent::EVENT_TEXT_VALUE_CHANGE, aAccessible); + return; + } + + // Fire numeric value change event when aria-valuenow is changed and + // aria-valuetext is empty + if (aAttribute == nsGkAtoms::aria_valuenow && + (!elm->HasAttr(kNameSpaceID_None, nsGkAtoms::aria_valuetext) || + elm->AttrValueIs(kNameSpaceID_None, nsGkAtoms::aria_valuetext, + nsGkAtoms::_empty, eCaseMatters))) { + FireDelayedEvent(nsIAccessibleEvent::EVENT_VALUE_CHANGE, aAccessible); + return; + } + + if (aAttribute == nsGkAtoms::aria_current) { + RefPtr<AccEvent> event = + new AccStateChangeEvent(aAccessible, states::CURRENT); + FireDelayedEvent(event); + return; + } + + if (aAttribute == nsGkAtoms::aria_haspopup) { + RefPtr<AccEvent> event = + new AccStateChangeEvent(aAccessible, states::HASPOPUP); + FireDelayedEvent(event); + return; + } + + if (aAttribute == nsGkAtoms::aria_owns) { + mNotificationController->ScheduleRelocation(aAccessible); + } +} + +void DocAccessible::ARIAActiveDescendantChanged(Accessible* aAccessible) { + nsIContent* elm = aAccessible->GetContent(); + if (elm && elm->IsElement() && aAccessible->IsActiveWidget()) { + nsAutoString id; + if (elm->AsElement()->GetAttr(kNameSpaceID_None, + nsGkAtoms::aria_activedescendant, id)) { + dom::Element* activeDescendantElm = IDRefsIterator::GetElem(elm, id); + if (activeDescendantElm) { + Accessible* activeDescendant = GetAccessible(activeDescendantElm); + if (activeDescendant) { + FocusMgr()->ActiveItemChanged(activeDescendant, false); +#ifdef A11Y_LOG + if (logging::IsEnabled(logging::eFocus)) + logging::ActiveItemChangeCausedBy("ARIA activedescedant changed", + activeDescendant); +#endif + return; + } + } + } + + // aria-activedescendant was cleared or changed to a non-existent node. + // Move focus back to the element itself. + FocusMgr()->ActiveItemChanged(aAccessible, false); +#ifdef A11Y_LOG + if (logging::IsEnabled(logging::eFocus)) { + logging::ActiveItemChangeCausedBy("ARIA activedescedant cleared", + aAccessible); + } +#endif + } +} + +void DocAccessible::ContentAppended(nsIContent* aFirstNewContent) {} + +void DocAccessible::ContentStateChanged(dom::Document* aDocument, + nsIContent* aContent, + EventStates aStateMask) { + Accessible* accessible = GetAccessible(aContent); + if (!accessible) return; + + if (aStateMask.HasState(NS_EVENT_STATE_CHECKED)) { + Accessible* widget = accessible->ContainerWidget(); + if (widget && widget->IsSelect()) { + AccSelChangeEvent::SelChangeType selChangeType = + aContent->AsElement()->State().HasState(NS_EVENT_STATE_CHECKED) + ? AccSelChangeEvent::eSelectionAdd + : AccSelChangeEvent::eSelectionRemove; + RefPtr<AccEvent> event = + new AccSelChangeEvent(widget, accessible, selChangeType); + FireDelayedEvent(event); + return; + } + + RefPtr<AccEvent> event = new AccStateChangeEvent( + accessible, states::CHECKED, + aContent->AsElement()->State().HasState(NS_EVENT_STATE_CHECKED)); + FireDelayedEvent(event); + } + + if (aStateMask.HasState(NS_EVENT_STATE_INVALID)) { + RefPtr<AccEvent> event = + new AccStateChangeEvent(accessible, states::INVALID, true); + FireDelayedEvent(event); + } + + if (aStateMask.HasState(NS_EVENT_STATE_REQUIRED)) { + RefPtr<AccEvent> event = + new AccStateChangeEvent(accessible, states::REQUIRED); + FireDelayedEvent(event); + } + + if (aStateMask.HasState(NS_EVENT_STATE_VISITED)) { + RefPtr<AccEvent> event = + new AccStateChangeEvent(accessible, states::TRAVERSED, true); + FireDelayedEvent(event); + } +} + +void DocAccessible::CharacterDataWillChange(nsIContent* aContent, + const CharacterDataChangeInfo&) {} + +void DocAccessible::CharacterDataChanged(nsIContent* aContent, + const CharacterDataChangeInfo&) {} + +void DocAccessible::ContentInserted(nsIContent* aChild) {} + +void DocAccessible::ContentRemoved(nsIContent* aChildNode, + nsIContent* aPreviousSiblingNode) { +#ifdef A11Y_LOG + if (logging::IsEnabled(logging::eTree)) { + logging::MsgBegin("TREE", "DOM content removed; doc: %p", this); + logging::Node("container node", aChildNode->GetParent()); + logging::Node("content node", aChildNode); + logging::MsgEnd(); + } +#endif + // This one and content removal notification from layout may result in + // double processing of same subtrees. If it pops up in profiling, then + // consider reusing a document node cache to reject these notifications early. + ContentRemoved(aChildNode); +} + +void DocAccessible::ParentChainChanged(nsIContent* aContent) {} + +//////////////////////////////////////////////////////////////////////////////// +// Accessible + +#ifdef A11Y_LOG +nsresult DocAccessible::HandleAccEvent(AccEvent* aEvent) { + if (logging::IsEnabled(logging::eDocLoad)) + logging::DocLoadEventHandled(aEvent); + + return HyperTextAccessible::HandleAccEvent(aEvent); +} +#endif + +//////////////////////////////////////////////////////////////////////////////// +// Public members + +nsPresContext* DocAccessible::PresContext() const { + return mPresShell->GetPresContext(); +} + +void* DocAccessible::GetNativeWindow() const { + if (!mPresShell) { + return nullptr; + } + + nsViewManager* vm = mPresShell->GetViewManager(); + if (!vm) return nullptr; + + nsCOMPtr<nsIWidget> widget; + vm->GetRootWidget(getter_AddRefs(widget)); + if (widget) return widget->GetNativeData(NS_NATIVE_WINDOW); + + return nullptr; +} + +Accessible* DocAccessible::GetAccessibleByUniqueIDInSubtree(void* aUniqueID) { + Accessible* child = GetAccessibleByUniqueID(aUniqueID); + if (child) return child; + + uint32_t childDocCount = mChildDocuments.Length(); + for (uint32_t childDocIdx = 0; childDocIdx < childDocCount; childDocIdx++) { + DocAccessible* childDocument = mChildDocuments.ElementAt(childDocIdx); + child = childDocument->GetAccessibleByUniqueIDInSubtree(aUniqueID); + if (child) return child; + } + + return nullptr; +} + +Accessible* DocAccessible::GetAccessibleOrContainer( + nsINode* aNode, bool aNoContainerIfPruned) const { + if (!aNode || !aNode->GetComposedDoc()) { + return nullptr; + } + + nsINode* start = aNode; + if (auto* shadowRoot = dom::ShadowRoot::FromNode(aNode)) { + // This can happen, for example, when called within + // SelectionManager::ProcessSelectionChanged due to focusing a direct + // child of a shadow root. + // GetFlattenedTreeParent works on children of a shadow root, but not the + // shadow root itself. + start = shadowRoot->GetHost(); + if (!start) { + return nullptr; + } + } + + for (nsINode* currNode : dom::InclusiveFlatTreeAncestors(*start)) { + // No container if is inside of aria-hidden subtree. + if (aNoContainerIfPruned && currNode->IsElement() && + aria::HasDefinedARIAHidden(currNode->AsElement())) { + return nullptr; + } + + // Check if node is in an unselected deck panel + if (aNoContainerIfPruned && currNode->IsXULElement()) { + if (nsIFrame* frame = currNode->AsContent()->GetPrimaryFrame()) { + nsDeckFrame* deckFrame = do_QueryFrame(frame->GetParent()); + if (deckFrame && deckFrame->GetSelectedBox() != frame) { + // If deck is not a <tabpanels>, return null + nsIContent* parentFrameContent = deckFrame->GetContent(); + if (!parentFrameContent || + !parentFrameContent->IsXULElement(nsGkAtoms::tabpanels)) { + return nullptr; + } + } + } + } + + // Check if node is in zero-sized map + if (aNoContainerIfPruned && currNode->IsHTMLElement(nsGkAtoms::map)) { + if (nsIFrame* frame = currNode->AsContent()->GetPrimaryFrame()) { + if (nsLayoutUtils::GetAllInFlowRectsUnion(frame, frame->GetParent()) + .IsEmpty()) { + return nullptr; + } + } + } + + if (Accessible* accessible = GetAccessible(currNode)) { + return accessible; + } + } + + return nullptr; +} + +Accessible* DocAccessible::GetAccessibleOrDescendant(nsINode* aNode) const { + Accessible* acc = GetAccessible(aNode); + if (acc) return acc; + + if (aNode == mContent || aNode == mDocumentNode->GetRootElement()) { + // If the node is the doc's body or root element, return the doc accessible. + return const_cast<DocAccessible*>(this); + } + + acc = GetContainerAccessible(aNode); + if (acc) { + // We access the `mChildren` array directly so that we don't access + // lazily created children in places like `XULTreeAccessible` and + // `XULTreeGridAccessible`. + uint32_t childCnt = acc->mChildren.Length(); + for (uint32_t idx = 0; idx < childCnt; idx++) { + Accessible* child = acc->mChildren.ElementAt(idx); + for (nsIContent* elm = child->GetContent(); + elm && elm != acc->GetContent(); + elm = elm->GetFlattenedTreeParent()) { + if (elm == aNode) return child; + } + } + } + + return nullptr; +} + +void DocAccessible::BindToDocument(Accessible* aAccessible, + const nsRoleMapEntry* aRoleMapEntry) { + // Put into DOM node cache. + if (aAccessible->IsNodeMapEntry()) + mNodeToAccessibleMap.Put(aAccessible->GetNode(), aAccessible); + + // Put into unique ID cache. + mAccessibleCache.Put(aAccessible->UniqueID(), RefPtr{aAccessible}); + + aAccessible->SetRoleMapEntry(aRoleMapEntry); + + if (aAccessible->HasOwnContent()) { + AddDependentIDsFor(aAccessible); + + nsIContent* content = aAccessible->GetContent(); + if (content->IsElement() && content->AsElement()->HasAttr( + kNameSpaceID_None, nsGkAtoms::aria_owns)) { + mNotificationController->ScheduleRelocation(aAccessible); + } + } +} + +void DocAccessible::UnbindFromDocument(Accessible* aAccessible) { + NS_ASSERTION(mAccessibleCache.GetWeak(aAccessible->UniqueID()), + "Unbinding the unbound accessible!"); + + // Fire focus event on accessible having DOM focus if last focus was removed + // from the tree. + if (FocusMgr()->WasLastFocused(aAccessible)) { + FocusMgr()->ActiveItemChanged(nullptr); +#ifdef A11Y_LOG + if (logging::IsEnabled(logging::eFocus)) + logging::ActiveItemChangeCausedBy("tree shutdown", aAccessible); +#endif + } + + // Remove an accessible from node-to-accessible map if it exists there. + if (aAccessible->IsNodeMapEntry() && + mNodeToAccessibleMap.Get(aAccessible->GetNode()) == aAccessible) + mNodeToAccessibleMap.Remove(aAccessible->GetNode()); + + aAccessible->mStateFlags |= eIsNotInDocument; + + // Update XPCOM part. + xpcAccessibleDocument* xpcDoc = GetAccService()->GetCachedXPCDocument(this); + if (xpcDoc) xpcDoc->NotifyOfShutdown(aAccessible); + + void* uniqueID = aAccessible->UniqueID(); + + NS_ASSERTION(!aAccessible->IsDefunct(), "Shutdown the shutdown accessible!"); + aAccessible->Shutdown(); + + mAccessibleCache.Remove(uniqueID); +} + +void DocAccessible::ContentInserted(nsIContent* aStartChildNode, + nsIContent* aEndChildNode) { + // Ignore content insertions until we constructed accessible tree. Otherwise + // schedule tree update on content insertion after layout. + if (!mNotificationController || !HasLoadState(eTreeConstructed)) { + return; + } + + // The frame constructor guarantees that only ranges with the same parent + // arrive here in presence of dynamic changes to the page, see + // nsCSSFrameConstructor::IssueSingleInsertNotifications' callers. + nsINode* parent = aStartChildNode->GetFlattenedTreeParentNode(); + if (!parent) { + return; + } + + Accessible* container = AccessibleOrTrueContainer(parent); + if (!container) { + return; + } + + AutoTArray<nsCOMPtr<nsIContent>, 10> list; + for (nsIContent* node = aStartChildNode; node != aEndChildNode; + node = node->GetNextSibling()) { + MOZ_ASSERT(parent == node->GetFlattenedTreeParentNode()); + if (PruneOrInsertSubtree(node)) { + list.AppendElement(node); + } + } + + mNotificationController->ScheduleContentInsertion(container, list); +} + +bool DocAccessible::PruneOrInsertSubtree(nsIContent* aRoot) { + bool insert = false; + + // In the case that we are, or are in, a shadow host, we need to assure + // some accessibles are removed if they are not rendered anymore. + nsIContent* shadowHost = + aRoot->GetShadowRoot() ? aRoot : aRoot->GetContainingShadowHost(); + if (shadowHost) { + dom::ExplicitChildIterator iter(shadowHost); + + // Check all explicit children in the host, if they are not slotted + // then remove their accessibles and subtrees. + while (nsIContent* childNode = iter.GetNextChild()) { + if (!childNode->GetPrimaryFrame() && + !nsCoreUtils::IsDisplayContents(childNode)) { + ContentRemoved(childNode); + } + } + + // If this is a slot, check to see if its fallback content is rendered, + // if not - remove it. + if (aRoot->IsHTMLElement(nsGkAtoms::slot)) { + for (nsIContent* childNode = aRoot->GetFirstChild(); childNode; + childNode = childNode->GetNextSibling()) { + if (!childNode->GetPrimaryFrame() && + !nsCoreUtils::IsDisplayContents(childNode)) { + ContentRemoved(childNode); + } + } + } + } + + // If we already have an accessible, check if we need to remove it, recreate + // it, or keep it in place. + Accessible* acc = GetAccessible(aRoot); + if (acc) { + MOZ_ASSERT(aRoot == acc->GetContent(), "Accessible has differing content!"); +#ifdef A11Y_LOG + if (logging::IsEnabled(logging::eTree)) { + logging::MsgBegin( + "TREE", "inserted content already has accessible; doc: %p", this); + logging::Node("content node", aRoot); + logging::AccessibleInfo("accessible node", acc); + logging::MsgEnd(); + } +#endif + + nsIFrame* frame = acc->GetFrame(); + + // Accessible has no frame and it's not display:contents. Remove it. + // As well as removing the a11y subtree, we must also remove Accessibles + // for DOM descendants, since some of these might be relocated Accessibles + // and their DOM nodes are now hidden as well. + if (!frame && !nsCoreUtils::IsDisplayContents(aRoot)) { + ContentRemoved(aRoot); + return false; + } + + // If it's a XULLabel it was probably reframed because a `value` attribute + // was added. The accessible creates its text leaf upon construction, so we + // need to recreate. Remove it, and schedule for reconstruction. + if (acc->IsXULLabel()) { + ContentRemoved(acc); + return true; + } + + // It is a broken image that is being reframed because it either got + // or lost an `alt` tag that would rerender this node as text. + if (frame && (acc->IsImage() != (frame->AccessibleType() == eImageType))) { + ContentRemoved(aRoot); + return true; + } + + // If the frame is an OuterDoc frame but this isn't an OuterDocAccessible, + // we need to recreate the Accessible. This can happen for embed or object + // elements if their embedded content changes to be web content. + if (frame && !acc->IsOuterDoc() && + frame->AccessibleType() == eOuterDocType) { + ContentRemoved(aRoot); + return true; + } + + // If the content is focused, and is being re-framed, reset the selection + // listener for the node because the previous selection listener is on the + // old frame. + if (aRoot->IsElement() && FocusMgr()->HasDOMFocus(aRoot)) { + SelectionMgr()->SetControlSelectionListener(aRoot->AsElement()); + } + + // The accessible can be reparented or reordered in its parent. + // We schedule it for reinsertion. For example, a slotted element + // can change its slot attribute to a different slot. + insert = true; + } else { + // If there is no current accessible, and the node has a frame, or is + // display:contents, schedule it for insertion. + if (aRoot->GetPrimaryFrame() || nsCoreUtils::IsDisplayContents(aRoot)) { + // This may be a new subtree, the insertion process will recurse through + // its descendants. + if (!GetAccessibleOrDescendant(aRoot)) { + return true; + } + + // Content is not an accessible, but has accessible descendants. + // We schedule this container for insertion strictly for the case where it + // itself now needs an accessible. We will still need to recurse into the + // descendant content to prune accessibles, and in all likelyness to + // insert accessibles since accessible insertions will likeley get missed + // in an existing subtree. + insert = true; + } + } + + if (Accessible* container = AccessibleOrTrueContainer(aRoot)) { + AutoTArray<nsCOMPtr<nsIContent>, 10> list; + dom::AllChildrenIterator iter = + dom::AllChildrenIterator(aRoot, nsIContent::eAllChildren, true); + while (nsIContent* childNode = iter.GetNextChild()) { + if (PruneOrInsertSubtree(childNode)) { + list.AppendElement(childNode); + } + } + + if (!list.IsEmpty()) { + mNotificationController->ScheduleContentInsertion(container, list); + } + } + + return insert; +} + +void DocAccessible::RecreateAccessible(nsIContent* aContent) { +#ifdef A11Y_LOG + if (logging::IsEnabled(logging::eTree)) { + logging::MsgBegin("TREE", "accessible recreated"); + logging::Node("content", aContent); + logging::MsgEnd(); + } +#endif + + // XXX: we shouldn't recreate whole accessible subtree, instead we should + // subclass hide and show events to handle them separately and implement their + // coalescence with normal hide and show events. Note, in this case they + // should be coalesced with normal show/hide events. + ContentRemoved(aContent); + ContentInserted(aContent, aContent->GetNextSibling()); +} + +void DocAccessible::ProcessInvalidationList() { + // Invalidate children of container accessible for each element in + // invalidation list. Allow invalidation list insertions while container + // children are recached. + for (uint32_t idx = 0; idx < mInvalidationList.Length(); idx++) { + nsIContent* content = mInvalidationList[idx]; + if (!HasAccessible(content) && content->HasID()) { + Accessible* container = GetContainerAccessible(content); + if (container) { + // Check if the node is a target of aria-owns, and if so, don't process + // it here and let DoARIAOwnsRelocation process it. + AttrRelProviders* list = GetRelProviders( + content->AsElement(), nsDependentAtomString(content->GetID())); + bool shouldProcess = !!list; + if (shouldProcess) { + for (uint32_t idx = 0; idx < list->Length(); idx++) { + if (list->ElementAt(idx)->mRelAttr == nsGkAtoms::aria_owns) { + shouldProcess = false; + break; + } + } + + if (shouldProcess) { + ProcessContentInserted(container, content); + } + } + } + } + } + + mInvalidationList.Clear(); +} + +Accessible* DocAccessible::GetAccessibleEvenIfNotInMap(nsINode* aNode) const { + if (!aNode->IsContent() || + !aNode->AsContent()->IsHTMLElement(nsGkAtoms::area)) + return GetAccessible(aNode); + + // XXX Bug 135040, incorrect when multiple images use the same map. + nsIFrame* frame = aNode->AsContent()->GetPrimaryFrame(); + nsImageFrame* imageFrame = do_QueryFrame(frame); + if (imageFrame) { + Accessible* parent = GetAccessible(imageFrame->GetContent()); + if (parent) { + Accessible* area = parent->AsImageMap()->GetChildAccessibleFor(aNode); + if (area) return area; + + return nullptr; + } + } + + return GetAccessible(aNode); +} + +//////////////////////////////////////////////////////////////////////////////// +// Protected members + +void DocAccessible::NotifyOfLoading(bool aIsReloading) { + // Mark the document accessible as loading, if it stays alive then we'll mark + // it as loaded when we receive proper notification. + mLoadState &= ~eDOMLoaded; + + if (!IsLoadEventTarget()) return; + + if (aIsReloading && !mLoadEventType && + // We can't fire events on a document whose tree isn't constructed yet. + HasLoadState(eTreeConstructed)) { + // Fire reload and state busy events on existing document accessible while + // event from user input flag can be calculated properly and accessible + // is alive. When new document gets loaded then this one is destroyed. + RefPtr<AccEvent> reloadEvent = + new AccEvent(nsIAccessibleEvent::EVENT_DOCUMENT_RELOAD, this); + nsEventShell::FireEvent(reloadEvent); + } + + // Fire state busy change event. Use delayed event since we don't care + // actually if event isn't delivered when the document goes away like a shot. + RefPtr<AccEvent> stateEvent = + new AccStateChangeEvent(this, states::BUSY, true); + FireDelayedEvent(stateEvent); +} + +void DocAccessible::DoInitialUpdate() { + if (nsCoreUtils::IsTopLevelContentDocInProcess(mDocumentNode)) { + mDocFlags |= eTopLevelContentDocInProcess; + if (IPCAccessibilityActive()) { + nsIDocShell* docShell = mDocumentNode->GetDocShell(); + if (RefPtr<dom::BrowserChild> browserChild = + dom::BrowserChild::GetFrom(docShell)) { + // In content processes, top level content documents are always + // RootAccessibles. + MOZ_ASSERT(IsRoot()); + DocAccessibleChild* ipcDoc = IPCDoc(); + if (ipcDoc) { + browserChild->SetTopLevelDocAccessibleChild(ipcDoc); + } else { + ipcDoc = new DocAccessibleChild(this, browserChild); + SetIPCDoc(ipcDoc); + // Subsequent initialization might depend on being able to get the + // top level DocAccessibleChild, so set that as early as possible. + browserChild->SetTopLevelDocAccessibleChild(ipcDoc); + +#if defined(XP_WIN) + IAccessibleHolder holder( + CreateHolderFromAccessible(WrapNotNull(this))); + MOZ_ASSERT(!holder.IsNull()); + int32_t childID = AccessibleWrap::GetChildIDFor(this); +#else + int32_t holder = 0, childID = 0; +#endif + browserChild->SendPDocAccessibleConstructor(ipcDoc, nullptr, 0, + childID, holder); +#if !defined(XP_WIN) + ipcDoc->SendPDocAccessiblePlatformExtConstructor(); +#endif + } +#if !defined(XP_WIN) + // It's safe for us to mark top level documents as constructed in the + // parent process without receiving an explicit message, since we can + // never get queries for this document or descendants before parent + // process construction is complete. + ipcDoc->SetConstructedInParentProcess(); +#endif + } + } + } + + mLoadState |= eTreeConstructed; + + // Set up a root element and ARIA role mapping. + UpdateRootElIfNeeded(); + + // Build initial tree. + CacheChildrenInSubtree(this); +#ifdef A11Y_LOG + if (logging::IsEnabled(logging::eVerbose)) { + logging::Tree("TREE", "Initial subtree", this); + } +#endif + + // Fire reorder event after the document tree is constructed. Note, since + // this reorder event is processed by parent document then events targeted to + // this document may be fired prior to this reorder event. If this is + // a problem then consider to keep event processing per tab document. + if (!IsRoot()) { + RefPtr<AccReorderEvent> reorderEvent = new AccReorderEvent(Parent()); + ParentDocument()->FireDelayedEvent(reorderEvent); + } + + if (IPCAccessibilityActive()) { + DocAccessibleChild* ipcDoc = IPCDoc(); + MOZ_ASSERT(ipcDoc); + if (ipcDoc) { + for (auto idx = 0U; idx < mChildren.Length(); idx++) { + ipcDoc->InsertIntoIpcTree(this, mChildren.ElementAt(idx), idx); + } + } + } +} + +void DocAccessible::ProcessLoad() { + mLoadState |= eCompletelyLoaded; + +#ifdef A11Y_LOG + if (logging::IsEnabled(logging::eDocLoad)) + logging::DocCompleteLoad(this, IsLoadEventTarget()); +#endif + + // Do not fire document complete/stop events for root chrome document + // accessibles and for frame/iframe documents because + // a) screen readers start working on focus event in the case of root chrome + // documents + // b) document load event on sub documents causes screen readers to act is if + // entire page is reloaded. + if (!IsLoadEventTarget()) return; + + // Fire complete/load stopped if the load event type is given. + if (mLoadEventType) { + RefPtr<AccEvent> loadEvent = new AccEvent(mLoadEventType, this); + FireDelayedEvent(loadEvent); + + mLoadEventType = 0; + } + + // Fire busy state change event. + RefPtr<AccEvent> stateEvent = + new AccStateChangeEvent(this, states::BUSY, false); + FireDelayedEvent(stateEvent); +} + +void DocAccessible::AddDependentIDsFor(Accessible* aRelProvider, + nsAtom* aRelAttr) { + dom::Element* relProviderEl = aRelProvider->Elm(); + if (!relProviderEl) return; + + for (uint32_t idx = 0; idx < kRelationAttrsLen; idx++) { + nsStaticAtom* relAttr = kRelationAttrs[idx]; + if (aRelAttr && aRelAttr != relAttr) continue; + + if (relAttr == nsGkAtoms::_for) { + if (!relProviderEl->IsAnyOfHTMLElements(nsGkAtoms::label, + nsGkAtoms::output)) + continue; + + } else if (relAttr == nsGkAtoms::control) { + if (!relProviderEl->IsAnyOfXULElements(nsGkAtoms::label, + nsGkAtoms::description)) + continue; + } + + IDRefsIterator iter(this, relProviderEl, relAttr); + while (true) { + const nsDependentSubstring id = iter.NextID(); + if (id.IsEmpty()) break; + + nsIContent* dependentContent = iter.GetElem(id); + if (!dependentContent || + (relAttr == nsGkAtoms::aria_owns && + !aRelProvider->IsAcceptableChild(dependentContent))) + continue; + + AttrRelProviders* providers = + GetOrCreateRelProviders(dependentContent->AsElement(), id); + if (providers) { + AttrRelProvider* provider = new AttrRelProvider(relAttr, relProviderEl); + if (provider) { + providers->AppendElement(provider); + + // We've got here during the children caching. If the referenced + // content is not accessible then store it to pend its container + // children invalidation (this happens immediately after the caching + // is finished). + if (dependentContent) { + if (!HasAccessible(dependentContent)) { + mInvalidationList.AppendElement(dependentContent); + } + } + } + } + } + + // If the relation attribute is given then we don't have anything else to + // check. + if (aRelAttr) break; + } + + // Make sure to schedule the tree update if needed. + mNotificationController->ScheduleProcessing(); +} + +void DocAccessible::RemoveDependentIDsFor(Accessible* aRelProvider, + nsAtom* aRelAttr) { + dom::Element* relProviderElm = aRelProvider->Elm(); + if (!relProviderElm) return; + + for (uint32_t idx = 0; idx < kRelationAttrsLen; idx++) { + nsStaticAtom* relAttr = kRelationAttrs[idx]; + if (aRelAttr && aRelAttr != kRelationAttrs[idx]) continue; + + IDRefsIterator iter(this, relProviderElm, relAttr); + while (true) { + const nsDependentSubstring id = iter.NextID(); + if (id.IsEmpty()) break; + + AttrRelProviders* providers = GetRelProviders(relProviderElm, id); + if (providers) { + providers->RemoveElementsBy( + [relAttr, relProviderElm](const auto& provider) { + return provider->mRelAttr == relAttr && + provider->mContent == relProviderElm; + }); + + RemoveRelProvidersIfEmpty(relProviderElm, id); + } + } + + // If the relation attribute is given then we don't have anything else to + // check. + if (aRelAttr) break; + } +} + +bool DocAccessible::UpdateAccessibleOnAttrChange(dom::Element* aElement, + nsAtom* aAttribute) { + if (aAttribute == nsGkAtoms::role) { + // It is common for js libraries to set the role on the body element after + // the document has loaded. In this case we just update the role map entry. + if (mContent == aElement) { + SetRoleMapEntryForDoc(aElement); + if (mIPCDoc) { + mIPCDoc->SendRoleChangedEvent(Role()); + } + + return true; + } + + // Recreate the accessible when role is changed because we might require a + // different accessible class for the new role or the accessible may expose + // a different sets of interfaces (COM restriction). + RecreateAccessible(aElement); + + return true; + } + + if (aAttribute == nsGkAtoms::aria_multiselectable && + aElement->HasAttr(kNameSpaceID_None, nsGkAtoms::role)) { + // This affects whether the accessible supports SelectAccessible. + // COM says we cannot change what interfaces are supported on-the-fly, + // so invalidate this object. A new one will be created on demand. + RecreateAccessible(aElement); + + return true; + } + + if (aAttribute == nsGkAtoms::type) { + // If the input[type] changes, we should recreate the accessible. + RecreateAccessible(aElement); + return true; + } + + return false; +} + +void DocAccessible::UpdateRootElIfNeeded() { + dom::Element* rootEl = mDocumentNode->GetBodyElement(); + if (!rootEl) { + rootEl = mDocumentNode->GetRootElement(); + } + if (rootEl != mContent) { + mContent = rootEl; + SetRoleMapEntryForDoc(rootEl); + if (mIPCDoc) { + mIPCDoc->SendRoleChangedEvent(Role()); + } + } +} + +/** + * Content insertion helper. + */ +class InsertIterator final { + public: + InsertIterator(Accessible* aContext, + const nsTArray<nsCOMPtr<nsIContent>>* aNodes) + : mChild(nullptr), + mChildBefore(nullptr), + mWalker(aContext), + mNodes(aNodes), + mNodesIdx(0) { + MOZ_ASSERT(aContext, "No context"); + MOZ_ASSERT(aNodes, "No nodes to search for accessible elements"); + MOZ_COUNT_CTOR(InsertIterator); + } + MOZ_COUNTED_DTOR(InsertIterator) + + Accessible* Context() const { return mWalker.Context(); } + Accessible* Child() const { return mChild; } + Accessible* ChildBefore() const { return mChildBefore; } + DocAccessible* Document() const { return mWalker.Document(); } + + /** + * Iterates to a next accessible within the inserted content. + */ + bool Next(); + + void Rejected() { + mChild = nullptr; + mChildBefore = nullptr; + } + + private: + Accessible* mChild; + Accessible* mChildBefore; + TreeWalker mWalker; + + const nsTArray<nsCOMPtr<nsIContent>>* mNodes; + nsTHashtable<nsPtrHashKey<const nsIContent>> mProcessedNodes; + uint32_t mNodesIdx; +}; + +bool InsertIterator::Next() { + if (mNodesIdx > 0) { + // If we already processed the first node in the mNodes list, + // check if we can just use the walker to get its next sibling. + Accessible* nextChild = mWalker.Next(); + if (nextChild) { + mChildBefore = mChild; + mChild = nextChild; + return true; + } + } + + while (mNodesIdx < mNodes->Length()) { + nsIContent* node = mNodes->ElementAt(mNodesIdx++); + // Check to see if we already processed this node with this iterator. + // this can happen if we get two redundant insertions in the case of a + // text and frame insertion. + if (!mProcessedNodes.EnsureInserted(node)) { + continue; + } + + Accessible* container = Document()->AccessibleOrTrueContainer( + node->GetFlattenedTreeParentNode(), true); + // Ignore nodes that are not contained by the container anymore. + // The container might be changed, for example, because of the subsequent + // overlapping content insertion (i.e. other content was inserted between + // this inserted content and its container or the content was reinserted + // into different container of unrelated part of tree). To avoid a double + // processing of the content insertion ignore this insertion notification. + // Note, the inserted content might be not in tree at all at this point + // what means there's no container. Ignore the insertion too. + if (container != Context()) { + continue; + } + + // HTML comboboxes have no-content list accessible as an intermediate + // containing all options. + if (container->IsHTMLCombobox()) { + container = container->FirstChild(); + } + + if (!container->IsAcceptableChild(node)) { + continue; + } + +#ifdef A11Y_LOG + logging::TreeInfo("traversing an inserted node", logging::eVerbose, + "container", container, "node", node); +#endif + + nsIContent* prevNode = mChild ? mChild->GetContent() : nullptr; + if (prevNode && prevNode->GetNextSibling() == node) { + // If inserted nodes are siblings then just move the walker next. + Accessible* nextChild = mWalker.Scope(node); + if (nextChild) { + mChildBefore = mChild; + mChild = nextChild; + return true; + } + } else { + // Otherwise use a new walker to find this node in the container's + // subtree, and retrieve its preceding sibling. + TreeWalker finder(container); + if (finder.Seek(node)) { + mChild = mWalker.Scope(node); + if (mChild) { + MOZ_ASSERT(!mChild->IsRelocated(), "child cannot be aria owned"); + mChildBefore = finder.Prev(); + return true; + } + } + } + } + + return false; +} + +void DocAccessible::ProcessContentInserted( + Accessible* aContainer, const nsTArray<nsCOMPtr<nsIContent>>* aNodes) { + // Process insertions if the container accessible is still in tree. + if (!aContainer->IsInDocument()) { + return; + } + + // If new root content has been inserted then update it. + if (aContainer == this) { + UpdateRootElIfNeeded(); + } + + InsertIterator iter(aContainer, aNodes); + if (!iter.Next()) { + return; + } + +#ifdef A11Y_LOG + logging::TreeInfo("children before insertion", logging::eVerbose, aContainer); +#endif + + TreeMutation mt(aContainer); + do { + Accessible* parent = iter.Child()->Parent(); + if (parent) { + Accessible* previousSibling = iter.ChildBefore(); + if (parent != aContainer || + iter.Child()->PrevSibling() != previousSibling) { + if (previousSibling && previousSibling->Parent() != aContainer) { + // previousSibling hasn't been moved into aContainer yet. + // previousSibling should be later in the insertion list, so the tree + // will get adjusted when we process it later. + MOZ_DIAGNOSTIC_ASSERT(parent == aContainer, + "Child moving to new parent, but previous " + "sibling in wrong parent"); + continue; + } +#ifdef A11Y_LOG + logging::TreeInfo("relocating accessible", 0, "old parent", parent, + "new parent", aContainer, "child", iter.Child(), + nullptr); +#endif + MoveChild(iter.Child(), aContainer, + previousSibling ? previousSibling->IndexInParent() + 1 : 0); + } + continue; + } + + if (aContainer->InsertAfter(iter.Child(), iter.ChildBefore())) { +#ifdef A11Y_LOG + logging::TreeInfo("accessible was inserted", 0, "container", aContainer, + "child", iter.Child(), nullptr); +#endif + + CreateSubtree(iter.Child()); + mt.AfterInsertion(iter.Child()); + continue; + } + + MOZ_ASSERT_UNREACHABLE("accessible was rejected"); + iter.Rejected(); + } while (iter.Next()); + + mt.Done(); + +#ifdef A11Y_LOG + logging::TreeInfo("children after insertion", logging::eVerbose, aContainer); +#endif + + FireEventsOnInsertion(aContainer); +} + +void DocAccessible::ProcessContentInserted(Accessible* aContainer, + nsIContent* aNode) { + if (!aContainer->IsInDocument()) { + return; + } + +#ifdef A11Y_LOG + logging::TreeInfo("children before insertion", logging::eVerbose, aContainer); +#endif + +#ifdef A11Y_LOG + logging::TreeInfo("traversing an inserted node", logging::eVerbose, + "container", aContainer, "node", aNode); +#endif + + TreeWalker walker(aContainer); + if (aContainer->IsAcceptableChild(aNode) && walker.Seek(aNode)) { + Accessible* child = GetAccessible(aNode); + if (!child) { + child = GetAccService()->CreateAccessible(aNode, aContainer); + } + + if (child) { + TreeMutation mt(aContainer); + if (!aContainer->InsertAfter(child, walker.Prev())) { + return; + } + CreateSubtree(child); + mt.AfterInsertion(child); + mt.Done(); + + FireEventsOnInsertion(aContainer); + } + } + +#ifdef A11Y_LOG + logging::TreeInfo("children after insertion", logging::eVerbose, aContainer); +#endif +} + +void DocAccessible::FireEventsOnInsertion(Accessible* aContainer) { + // Check to see if change occurred inside an alert, and fire an EVENT_ALERT + // if it did. + if (aContainer->IsAlert() || aContainer->IsInsideAlert()) { + Accessible* ancestor = aContainer; + do { + if (ancestor->IsAlert()) { + FireDelayedEvent(nsIAccessibleEvent::EVENT_ALERT, ancestor); + break; + } + } while ((ancestor = ancestor->Parent())); + } +} + +void DocAccessible::ContentRemoved(Accessible* aChild) { + Accessible* parent = aChild->Parent(); + MOZ_DIAGNOSTIC_ASSERT(parent, "Unattached accessible from tree"); + +#ifdef A11Y_LOG + logging::TreeInfo("process content removal", 0, "container", parent, "child", + aChild, nullptr); +#endif + + // XXX: event coalescence may kill us + RefPtr<Accessible> kungFuDeathGripChild(aChild); + + TreeMutation mt(parent); + mt.BeforeRemoval(aChild); + + if (aChild->IsDefunct()) { + MOZ_ASSERT_UNREACHABLE("Event coalescence killed the accessible"); + mt.Done(); + return; + } + + MOZ_DIAGNOSTIC_ASSERT(aChild->Parent(), "Alive but unparented #1"); + + if (aChild->IsRelocated()) { + nsTArray<RefPtr<Accessible>>* owned = mARIAOwnsHash.Get(parent); + MOZ_ASSERT(owned, "IsRelocated flag is out of sync with mARIAOwnsHash"); + owned->RemoveElement(aChild); + if (owned->Length() == 0) { + mARIAOwnsHash.Remove(parent); + } + } + MOZ_DIAGNOSTIC_ASSERT(aChild->Parent(), "Unparented #2"); + parent->RemoveChild(aChild); + UncacheChildrenInSubtree(aChild); + + mt.Done(); +} + +void DocAccessible::ContentRemoved(nsIContent* aContentNode) { + // If child node is not accessible then look for its accessible children. + Accessible* acc = GetAccessible(aContentNode); + if (acc) { + ContentRemoved(acc); + } + + dom::AllChildrenIterator iter = + dom::AllChildrenIterator(aContentNode, nsIContent::eAllChildren, true); + while (nsIContent* childNode = iter.GetNextChild()) { + ContentRemoved(childNode); + } + + // If this node has a shadow root, remove its explicit children too. + // The host node may be removed after the shadow root was attached, and + // before we asynchronously prune the light DOM and construct the shadow DOM. + // If this is a case where the node does not have its own accessible, we will + // not recurse into its current children, so we need to use an + // ExplicitChildIterator in order to get its accessible children in the light + // DOM, since they are not accessible anymore via AllChildrenIterator. + if (aContentNode->GetShadowRoot()) { + dom::ExplicitChildIterator iter = dom::ExplicitChildIterator(aContentNode); + while (nsIContent* childNode = iter.GetNextChild()) { + ContentRemoved(childNode); + } + } +} + +bool DocAccessible::RelocateARIAOwnedIfNeeded(nsIContent* aElement) { + if (!aElement->HasID()) return false; + + AttrRelProviders* list = GetRelProviders( + aElement->AsElement(), nsDependentAtomString(aElement->GetID())); + if (list) { + for (uint32_t idx = 0; idx < list->Length(); idx++) { + if (list->ElementAt(idx)->mRelAttr == nsGkAtoms::aria_owns) { + Accessible* owner = GetAccessible(list->ElementAt(idx)->mContent); + if (owner) { + mNotificationController->ScheduleRelocation(owner); + return true; + } + } + } + } + + return false; +} + +void DocAccessible::DoARIAOwnsRelocation(Accessible* aOwner) { + MOZ_ASSERT(aOwner, "aOwner must be a valid pointer"); + MOZ_ASSERT(aOwner->Elm(), "aOwner->Elm() must be a valid pointer"); + +#ifdef A11Y_LOG + logging::TreeInfo("aria owns relocation", logging::eVerbose, aOwner); +#endif + + nsTArray<RefPtr<Accessible>>* owned = mARIAOwnsHash.LookupOrAdd(aOwner); + + IDRefsIterator iter(this, aOwner->Elm(), nsGkAtoms::aria_owns); + uint32_t idx = 0; + while (nsIContent* childEl = iter.NextElem()) { + Accessible* child = GetAccessible(childEl); + auto insertIdx = aOwner->ChildCount() - owned->Length() + idx; + + // Make an attempt to create an accessible if it wasn't created yet. + if (!child) { + // An owned child cannot be an ancestor of the owner. + if (aOwner->Elm()->IsInclusiveDescendantOf(childEl)) { + continue; + } + + if (aOwner->IsAcceptableChild(childEl)) { + child = GetAccService()->CreateAccessible(childEl, aOwner); + if (child) { + TreeMutation imut(aOwner); + aOwner->InsertChildAt(insertIdx, child); + imut.AfterInsertion(child); + imut.Done(); + + child->SetRelocated(true); + owned->InsertElementAt(idx, child); + idx++; + + // Create subtree before adjusting the insertion index, since subtree + // creation may alter children in the container. + CreateSubtree(child); + FireEventsOnInsertion(aOwner); + } + } + continue; + } + +#ifdef A11Y_LOG + logging::TreeInfo("aria owns traversal", logging::eVerbose, "candidate", + child, nullptr); +#endif + + if (owned->IndexOf(child) < idx) { + continue; // ignore second entry of same ID + } + + // Same child on same position, no change. + if (child->Parent() == aOwner) { + int32_t indexInParent = child->IndexInParent(); + + // The child is being placed in its current index, + // eg. aria-owns='id1 id2 id3' is changed to aria-owns='id3 id2 id1'. + if (indexInParent == static_cast<int32_t>(insertIdx)) { + MOZ_ASSERT(child->IsRelocated(), + "A child, having an index in parent from aria ownded " + "indices range, has to be aria owned"); + MOZ_ASSERT(owned->ElementAt(idx) == child, + "Unexpected child in ARIA owned array"); + idx++; + continue; + } + + // The child is being inserted directly after its current index, + // resulting in a no-move case. This will happen when a parent aria-owns + // its last ordinal child: + // <ul aria-owns='id2'><li id='id1'></li><li id='id2'></li></ul> + if (indexInParent == static_cast<int32_t>(insertIdx) - 1) { + MOZ_ASSERT(!child->IsRelocated(), + "Child should be in its ordinal position"); + child->SetRelocated(true); + owned->InsertElementAt(idx, child); + idx++; + continue; + } + } + + MOZ_ASSERT(owned->SafeElementAt(idx) != child, "Already in place!"); + + // A new child is found, check for loops. + if (child->Parent() != aOwner) { + // Child is aria-owned by another container, skip. + if (child->IsRelocated()) { + continue; + } + + Accessible* parent = aOwner; + while (parent && parent != child && !parent->IsDoc()) { + parent = parent->Parent(); + } + // A referred child cannot be a parent of the owner. + if (parent == child) { + continue; + } + } + + if (MoveChild(child, aOwner, insertIdx)) { + child->SetRelocated(true); + MOZ_ASSERT(owned == mARIAOwnsHash.Get(aOwner)); + owned = mARIAOwnsHash.LookupOrAdd(aOwner); + owned->InsertElementAt(idx, child); + idx++; + } + } + + // Put back children that are not seized anymore. + PutChildrenBack(owned, idx); + if (owned->Length() == 0) { + mARIAOwnsHash.Remove(aOwner); + } +} + +void DocAccessible::PutChildrenBack(nsTArray<RefPtr<Accessible>>* aChildren, + uint32_t aStartIdx) { + MOZ_ASSERT(aStartIdx <= aChildren->Length(), "Wrong removal index"); + + for (auto idx = aStartIdx; idx < aChildren->Length(); idx++) { + Accessible* child = aChildren->ElementAt(idx); + if (!child->IsInDocument()) { + continue; + } + + // Remove the child from the owner + Accessible* owner = child->Parent(); + if (!owner) { + NS_ERROR("Cannot put the child back. No parent, a broken tree."); + continue; + } + +#ifdef A11Y_LOG + logging::TreeInfo("aria owns put child back", 0, "old parent", owner, + "child", child, nullptr); +#endif + + // Unset relocated flag to find an insertion point for the child. + child->SetRelocated(false); + + nsIContent* content = child->GetContent(); + int32_t idxInParent = -1; + Accessible* origContainer = + AccessibleOrTrueContainer(content->GetFlattenedTreeParentNode()); + if (origContainer) { + TreeWalker walker(origContainer); + if (walker.Seek(content)) { + Accessible* prevChild = walker.Prev(); + if (prevChild) { + idxInParent = prevChild->IndexInParent() + 1; + MOZ_DIAGNOSTIC_ASSERT(origContainer == prevChild->Parent(), + "Broken tree"); + origContainer = prevChild->Parent(); + } else { + idxInParent = 0; + } + } + } + + // The child may have already be in its ordinal place for 2 reasons: + // 1. It was the last ordinal child, and the first aria-owned child. + // given: <ul id="list" aria-owns="b"><li id="a"></li><li + // id="b"></li></ul> after load: $("list").setAttribute("aria-owns", ""); + // 2. The preceding adopted children were just reclaimed, eg: + // given: <ul id="list"><li id="b"></li></ul> + // after load: $("list").setAttribute("aria-owns", "a b"); + // later: $("list").setAttribute("aria-owns", ""); + if (origContainer != owner || child->IndexInParent() != idxInParent) { + DebugOnly<bool> moved = MoveChild(child, origContainer, idxInParent); + MOZ_ASSERT(moved, "Failed to put child back."); + } else { + MOZ_ASSERT(!child->PrevSibling() || !child->PrevSibling()->IsRelocated(), + "No relocated child should appear before this one"); + MOZ_ASSERT(!child->NextSibling() || child->NextSibling()->IsRelocated(), + "No ordinal child should appear after this one"); + } + } + + aChildren->RemoveLastElements(aChildren->Length() - aStartIdx); +} + +bool DocAccessible::MoveChild(Accessible* aChild, Accessible* aNewParent, + int32_t aIdxInParent) { + MOZ_ASSERT(aChild, "No child"); + MOZ_ASSERT(aChild->Parent(), "No parent"); + // We can't guarantee MoveChild works correctly for accessibilities storing + // children outside mChildren. + MOZ_ASSERT( + aIdxInParent <= static_cast<int32_t>(aNewParent->mChildren.Length()), + "Wrong insertion point for a moving child"); + + Accessible* curParent = aChild->Parent(); + + if (!aNewParent->IsAcceptableChild(aChild->GetContent())) { + return false; + } + +#ifdef A11Y_LOG + logging::TreeInfo("move child", 0, "old parent", curParent, "new parent", + aNewParent, "child", aChild, nullptr); +#endif + + // Forget aria-owns info in case of ARIA owned element. The caller is expected + // to update it if needed. + if (aChild->IsRelocated()) { + aChild->SetRelocated(false); + nsTArray<RefPtr<Accessible>>* owned = mARIAOwnsHash.Get(curParent); + MOZ_ASSERT(owned, "IsRelocated flag is out of sync with mARIAOwnsHash"); + owned->RemoveElement(aChild); + if (owned->Length() == 0) { + mARIAOwnsHash.Remove(curParent); + } + } + + NotificationController::MoveGuard mguard(mNotificationController); + + if (curParent == aNewParent) { + MOZ_ASSERT(aChild->IndexInParent() != aIdxInParent, "No move case"); + curParent->RelocateChild(aIdxInParent, aChild); + +#ifdef A11Y_LOG + logging::TreeInfo("move child: parent tree after", logging::eVerbose, + curParent); +#endif + return true; + } + + // If the child cannot be re-inserted into the tree, then make sure to remove + // it from its present parent and then shutdown it. + bool hasInsertionPoint = + (aIdxInParent >= 0) && + (aIdxInParent <= static_cast<int32_t>(aNewParent->mChildren.Length())); + + TreeMutation rmut(curParent); + rmut.BeforeRemoval(aChild, hasInsertionPoint && TreeMutation::kNoShutdown); + curParent->RemoveChild(aChild); + rmut.Done(); + + // No insertion point for the child. + if (!hasInsertionPoint) { + return true; + } + + TreeMutation imut(aNewParent); + aNewParent->InsertChildAt(aIdxInParent, aChild); + imut.AfterInsertion(aChild); + imut.Done(); + +#ifdef A11Y_LOG + logging::TreeInfo("move child: old parent tree after", logging::eVerbose, + curParent); + logging::TreeInfo("move child: new parent tree after", logging::eVerbose, + aNewParent); +#endif + + return true; +} + +void DocAccessible::CacheChildrenInSubtree(Accessible* aRoot, + Accessible** aFocusedAcc) { + // If the accessible is focused then report a focus event after all related + // mutation events. + if (aFocusedAcc && !*aFocusedAcc && + FocusMgr()->HasDOMFocus(aRoot->GetContent())) + *aFocusedAcc = aRoot; + + Accessible* root = aRoot->IsHTMLCombobox() ? aRoot->FirstChild() : aRoot; + if (root->KidsFromDOM()) { + TreeMutation mt(root, TreeMutation::kNoEvents); + TreeWalker walker(root); + while (Accessible* child = walker.Next()) { + if (child->IsBoundToParent()) { + MoveChild(child, root, root->mChildren.Length()); + continue; + } + + root->AppendChild(child); + mt.AfterInsertion(child); + + CacheChildrenInSubtree(child, aFocusedAcc); + } + mt.Done(); + } + + // Fire events for ARIA elements. + if (!aRoot->HasARIARole()) { + return; + } + + // XXX: we should delay document load complete event if the ARIA document + // has aria-busy. + roles::Role role = aRoot->ARIARole(); + if (!aRoot->IsDoc() && + (role == roles::DIALOG || role == roles::NON_NATIVE_DOCUMENT)) { + FireDelayedEvent(nsIAccessibleEvent::EVENT_DOCUMENT_LOAD_COMPLETE, aRoot); + } +} + +void DocAccessible::UncacheChildrenInSubtree(Accessible* aRoot) { + aRoot->mStateFlags |= eIsNotInDocument; + RemoveDependentIDsFor(aRoot); + + nsTArray<RefPtr<Accessible>>* owned = mARIAOwnsHash.Get(aRoot); + uint32_t count = aRoot->ContentChildCount(); + for (uint32_t idx = 0; idx < count; idx++) { + Accessible* child = aRoot->ContentChildAt(idx); + + if (child->IsRelocated()) { + MOZ_ASSERT(owned, "IsRelocated flag is out of sync with mARIAOwnsHash"); + owned->RemoveElement(child); + if (owned->Length() == 0) { + mARIAOwnsHash.Remove(aRoot); + owned = nullptr; + } + } + + // Removing this accessible from the document doesn't mean anything about + // accessibles for subdocuments, so skip removing those from the tree. + if (!child->IsDoc()) { + UncacheChildrenInSubtree(child); + } + } + + if (aRoot->IsNodeMapEntry() && + mNodeToAccessibleMap.Get(aRoot->GetNode()) == aRoot) + mNodeToAccessibleMap.Remove(aRoot->GetNode()); +} + +void DocAccessible::ShutdownChildrenInSubtree(Accessible* aAccessible) { + // Traverse through children and shutdown them before this accessible. When + // child gets shutdown then it removes itself from children array of its + // parent. Use jdx index to process the cases if child is not attached to the + // parent and as result doesn't remove itself from its children. + uint32_t count = aAccessible->ContentChildCount(); + for (uint32_t idx = 0, jdx = 0; idx < count; idx++) { + Accessible* child = aAccessible->ContentChildAt(jdx); + if (!child->IsBoundToParent()) { + NS_ERROR("Parent refers to a child, child doesn't refer to parent!"); + jdx++; + } + + // Don't cross document boundaries. The outerdoc shutdown takes care about + // its subdocument. + if (!child->IsDoc()) ShutdownChildrenInSubtree(child); + } + + UnbindFromDocument(aAccessible); +} + +bool DocAccessible::IsLoadEventTarget() const { + nsCOMPtr<nsIDocShellTreeItem> treeItem = mDocumentNode->GetDocShell(); + NS_ASSERTION(treeItem, "No document shell for document!"); + + nsCOMPtr<nsIDocShellTreeItem> parentTreeItem; + treeItem->GetInProcessParent(getter_AddRefs(parentTreeItem)); + + // Not a root document. + if (parentTreeItem) { + // Return true if it's either: + // a) tab document; + nsCOMPtr<nsIDocShellTreeItem> rootTreeItem; + treeItem->GetInProcessRootTreeItem(getter_AddRefs(rootTreeItem)); + if (parentTreeItem == rootTreeItem) return true; + + // b) frame/iframe document and its parent document is not in loading state + // Note: we can get notifications while document is loading (and thus + // while there's no parent document yet). + DocAccessible* parentDoc = ParentDocument(); + return parentDoc && parentDoc->HasLoadState(eCompletelyLoaded); + } + + // It's content (not chrome) root document. + return (treeItem->ItemType() == nsIDocShellTreeItem::typeContent); +} + +void DocAccessible::SetIPCDoc(DocAccessibleChild* aIPCDoc) { + MOZ_ASSERT(!mIPCDoc || !aIPCDoc, "Clobbering an attached IPCDoc!"); + mIPCDoc = aIPCDoc; +} + +void DocAccessible::DispatchScrollingEvent(nsINode* aTarget, + uint32_t aEventType) { + Accessible* acc = GetAccessible(aTarget); + if (!acc) { + return; + } + + nsIFrame* frame = acc->GetFrame(); + if (!frame) { + // Although the accessible had a frame at scroll time, it may now be gone + // because of display: contents. + return; + } + + LayoutDevicePoint scrollPoint; + LayoutDeviceRect scrollRange; + nsIScrollableFrame* sf = acc == this + ? mPresShell->GetRootScrollFrameAsScrollable() + : frame->GetScrollTargetFrame(); + + // If there is no scrollable frame, it's likely a scroll in a popup, like + // <select>. Just send an event with no scroll info. The scroll info + // is currently only used on Android, and popups are rendered natively + // there. + if (sf) { + int32_t appUnitsPerDevPixel = + mPresShell->GetPresContext()->AppUnitsPerDevPixel(); + scrollPoint = LayoutDevicePoint::FromAppUnits(sf->GetScrollPosition(), + appUnitsPerDevPixel) * + mPresShell->GetResolution(); + + scrollRange = LayoutDeviceRect::FromAppUnits(sf->GetScrollRange(), + appUnitsPerDevPixel); + scrollRange.ScaleRoundOut(mPresShell->GetResolution()); + } + + RefPtr<AccEvent> event = + new AccScrollingEvent(aEventType, acc, scrollPoint.x, scrollPoint.y, + scrollRange.width, scrollRange.height); + nsEventShell::FireEvent(event); +} + +void DocAccessible::ARIAActiveDescendantIDMaybeMoved(dom::Element* aElm) { + nsINode* focusNode = FocusMgr()->FocusedDOMNode(); + // The focused element must be within this document. + if (!focusNode || focusNode->OwnerDoc() != mDocumentNode) { + return; + } + + dom::Element* focusElm = nullptr; + if (focusNode == mDocumentNode) { + // The document is focused, so look for aria-activedescendant on the + // body/root. + focusElm = Elm(); + if (!focusElm) { + return; + } + } else { + MOZ_ASSERT(focusNode->IsElement()); + focusElm = focusNode->AsElement(); + } + + // Check if the focus has aria-activedescendant and whether + // it refers to the id just set on aElm. + nsAutoString id; + aElm->GetAttr(kNameSpaceID_None, nsGkAtoms::id, id); + if (!focusElm->AttrValueIs(kNameSpaceID_None, + nsGkAtoms::aria_activedescendant, id, + eCaseMatters)) { + return; + } + + // The aria-activedescendant target has probably changed. + Accessible* acc = GetAccessibleEvenIfNotInMapOrContainer(focusNode); + if (!acc) { + return; + } + + // The active descendant might have just been inserted and may not be in the + // tree yet. Therefore, schedule this async to ensure the tree is up to date. + mNotificationController->ScheduleNotification<DocAccessible, Accessible>( + this, &DocAccessible::ARIAActiveDescendantChanged, acc); +} + +void DocAccessible::SetRoleMapEntryForDoc(dom::Element* aElement) { + const nsRoleMapEntry* entry = aria::GetRoleMap(aElement); + if (!entry || entry->role == roles::APPLICATION || + entry->role == roles::DIALOG || + // Role alert isn't valid on the body element according to the ARIA spec, + // but it's useful for our UI; e.g. the WebRTC sharing indicator. + (entry->role == roles::ALERT && + !nsCoreUtils::IsContentDocument(mDocumentNode))) { + SetRoleMapEntry(entry); + return; + } + // No other ARIA roles are valid on body elements. + SetRoleMapEntry(nullptr); +} + +Accessible* DocAccessible::GetAccessible(nsINode* aNode) const { + return aNode == mDocumentNode ? const_cast<DocAccessible*>(this) + : mNodeToAccessibleMap.Get(aNode); +} diff --git a/accessible/generic/DocAccessible.h b/accessible/generic/DocAccessible.h new file mode 100644 index 0000000000..dc1cca0d15 --- /dev/null +++ b/accessible/generic/DocAccessible.h @@ -0,0 +1,729 @@ +/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +#ifndef mozilla_a11y_DocAccessible_h__ +#define mozilla_a11y_DocAccessible_h__ + +#include "nsIAccessiblePivot.h" + +#include "HyperTextAccessibleWrap.h" +#include "AccEvent.h" + +#include "nsClassHashtable.h" +#include "nsDataHashtable.h" +#include "mozilla/UniquePtr.h" +#include "nsIDocumentObserver.h" +#include "nsIObserver.h" +#include "nsITimer.h" +#include "nsWeakReference.h" + +class nsAccessiblePivot; + +const uint32_t kDefaultCacheLength = 128; + +namespace mozilla { + +class PresShell; +class TextEditor; + +namespace dom { +class Document; +} + +namespace a11y { + +class DocManager; +class NotificationController; +class DocAccessibleChild; +class RelatedAccIterator; +template <class Class, class... Args> +class TNotification; + +class DocAccessible : public HyperTextAccessibleWrap, + public nsIDocumentObserver, + public nsIObserver, + public nsSupportsWeakReference, + public nsIAccessiblePivotObserver { + NS_DECL_ISUPPORTS_INHERITED + NS_DECL_CYCLE_COLLECTION_CLASS_INHERITED(DocAccessible, Accessible) + + NS_DECL_NSIOBSERVER + NS_DECL_NSIACCESSIBLEPIVOTOBSERVER + + protected: + typedef mozilla::dom::Document Document; + + public: + DocAccessible(Document* aDocument, PresShell* aPresShell); + + // nsIDocumentObserver + NS_DECL_NSIDOCUMENTOBSERVER + + // Accessible + virtual void Init(); + virtual void Shutdown() override; + virtual nsIFrame* GetFrame() const override; + virtual nsINode* GetNode() const override; + Document* DocumentNode() const { return mDocumentNode; } + + virtual mozilla::a11y::ENameValueFlag Name(nsString& aName) const override; + virtual void Description(nsString& aDescription) override; + virtual Accessible* FocusedChild() override; + virtual mozilla::a11y::role NativeRole() const override; + virtual uint64_t NativeState() const override; + virtual uint64_t NativeInteractiveState() const override; + virtual bool NativelyUnavailable() const override; + virtual void ApplyARIAState(uint64_t* aState) const override; + virtual already_AddRefed<nsIPersistentProperties> Attributes() override; + + virtual void TakeFocus() const override; + +#ifdef A11Y_LOG + virtual nsresult HandleAccEvent(AccEvent* aEvent) override; +#endif + + virtual nsRect RelativeBounds(nsIFrame** aRelativeFrame) const override; + + // HyperTextAccessible + virtual already_AddRefed<TextEditor> GetEditor() const override; + + // DocAccessible + + /** + * Return document URL. + */ + void URL(nsAString& aURL) const; + + /** + * Return DOM document title. + */ + void Title(nsString& aTitle) const; + + /** + * Return DOM document mime type. + */ + void MimeType(nsAString& aType) const; + /** + * Return DOM document type. + */ + void DocType(nsAString& aType) const; + + /** + * Return virtual cursor associated with the document. + */ + nsIAccessiblePivot* VirtualCursor(); + + /** + * Returns true if the instance has shutdown. + */ + bool HasShutdown() const { return !mPresShell; } + + /** + * Return presentation shell for this document accessible. + */ + PresShell* PresShellPtr() const { + MOZ_DIAGNOSTIC_ASSERT(!HasShutdown()); + return mPresShell; + } + + /** + * Return the presentation shell's context. + */ + nsPresContext* PresContext() const; + + /** + * Return true if associated DOM document was loaded and isn't unloading. + */ + bool IsContentLoaded() const; + + bool IsHidden() const; + + /** + * Document load states. + */ + enum LoadState { + // initial tree construction is pending + eTreeConstructionPending = 0, + // initial tree construction done + eTreeConstructed = 1, + // DOM document is loaded. + eDOMLoaded = 1 << 1, + // document is ready + eReady = eTreeConstructed | eDOMLoaded, + // document and all its subdocuments are ready + eCompletelyLoaded = eReady | 1 << 2 + }; + + /** + * Return true if the document has given document state. + */ + bool HasLoadState(LoadState aState) const { + return (mLoadState & static_cast<uint32_t>(aState)) == + static_cast<uint32_t>(aState); + } + + /** + * Return a native window handler or pointer depending on platform. + */ + virtual void* GetNativeWindow() const; + + /** + * Return the parent document. + */ + DocAccessible* ParentDocument() const { + return mParent ? mParent->Document() : nullptr; + } + + /** + * Return the child document count. + */ + uint32_t ChildDocumentCount() const { return mChildDocuments.Length(); } + + /** + * Return the child document at the given index. + */ + DocAccessible* GetChildDocumentAt(uint32_t aIndex) const { + return mChildDocuments.SafeElementAt(aIndex, nullptr); + } + + /** + * Fire accessible event asynchronously. + */ + void FireDelayedEvent(AccEvent* aEvent); + void FireDelayedEvent(uint32_t aEventType, Accessible* aTarget); + void FireEventsOnInsertion(Accessible* aContainer); + + /** + * Fire value change event on the given accessible if applicable. + */ + void MaybeNotifyOfValueChange(Accessible* aAccessible); + + /** + * Get/set the anchor jump. + */ + Accessible* AnchorJump() { return GetAccessibleOrContainer(mAnchorJumpElm); } + + void SetAnchorJump(nsIContent* aTargetNode) { mAnchorJumpElm = aTargetNode; } + + /** + * Bind the child document to the tree. + */ + void BindChildDocument(DocAccessible* aDocument); + + /** + * Process the generic notification. + * + * @note The caller must guarantee that the given instance still exists when + * notification is processed. + * @see NotificationController::HandleNotification + */ + template <class Class, class... Args> + void HandleNotification( + Class* aInstance, + typename TNotification<Class, Args...>::Callback aMethod, Args*... aArgs); + + /** + * Return the cached accessible by the given DOM node if it's in subtree of + * this document accessible or the document accessible itself, otherwise null. + * + * @return the accessible object + */ + Accessible* GetAccessible(nsINode* aNode) const; + + /** + * Return an accessible for the given node even if the node is not in + * document's node map cache (like HTML area element). + * + * XXX: it should be really merged with GetAccessible(). + */ + Accessible* GetAccessibleEvenIfNotInMap(nsINode* aNode) const; + Accessible* GetAccessibleEvenIfNotInMapOrContainer(nsINode* aNode) const; + + /** + * Return whether the given DOM node has an accessible or not. + */ + bool HasAccessible(nsINode* aNode) const { return GetAccessible(aNode); } + + /** + * Return the cached accessible by the given unique ID within this document. + * + * @note the unique ID matches with the uniqueID() of Accessible + * + * @param aUniqueID [in] the unique ID used to cache the node. + */ + Accessible* GetAccessibleByUniqueID(void* aUniqueID) { + return UniqueID() == aUniqueID ? this : mAccessibleCache.GetWeak(aUniqueID); + } + + /** + * Return the cached accessible by the given unique ID looking through + * this and nested documents. + */ + Accessible* GetAccessibleByUniqueIDInSubtree(void* aUniqueID); + + /** + * Return an accessible for the given DOM node or container accessible if + * the node is not accessible. If aNoContainerIfPruned is true it will return + * null if the node is in a pruned subtree (eg. aria-hidden or unselected deck + * panel) + */ + Accessible* GetAccessibleOrContainer(nsINode* aNode, + bool aNoContainerIfPruned = false) const; + + /** + * Return a container accessible for the given DOM node. + */ + Accessible* GetContainerAccessible(nsINode* aNode) const { + return aNode ? GetAccessibleOrContainer(aNode->GetParentNode()) : nullptr; + } + + /** + * Return an accessible for the given node if any, or an immediate accessible + * container for it. + */ + Accessible* AccessibleOrTrueContainer( + nsINode* aNode, bool aNoContainerIfPruned = false) const; + + /** + * Return an accessible for the given node or its first accessible descendant. + */ + Accessible* GetAccessibleOrDescendant(nsINode* aNode) const; + + /** + * Returns aria-owns seized child at the given index. + */ + Accessible* ARIAOwnedAt(Accessible* aParent, uint32_t aIndex) const { + nsTArray<RefPtr<Accessible>>* children = mARIAOwnsHash.Get(aParent); + if (children) { + return children->SafeElementAt(aIndex); + } + return nullptr; + } + uint32_t ARIAOwnedCount(Accessible* aParent) const { + nsTArray<RefPtr<Accessible>>* children = mARIAOwnsHash.Get(aParent); + return children ? children->Length() : 0; + } + + /** + * Return true if the given ID is referred by relation attribute. + */ + bool IsDependentID(dom::Element* aElement, const nsAString& aID) const { + return GetRelProviders(aElement, aID); + } + + /** + * Initialize the newly created accessible and put it into document caches. + * + * @param aAccessible [in] created accessible + * @param aRoleMapEntry [in] the role map entry role the ARIA role or + * nullptr if none + */ + void BindToDocument(Accessible* aAccessible, + const nsRoleMapEntry* aRoleMapEntry); + + /** + * Remove from document and shutdown the given accessible. + */ + void UnbindFromDocument(Accessible* aAccessible); + + /** + * Notify the document accessible that content was inserted. + */ + void ContentInserted(nsIContent* aStartChildNode, nsIContent* aEndChildNode); + + /** + * Update the tree on content removal. + */ + void ContentRemoved(Accessible* aAccessible); + void ContentRemoved(nsIContent* aContentNode); + + /** + * Updates accessible tree when rendered text is changed. + */ + void UpdateText(nsIContent* aTextNode); + + /** + * Recreate an accessible, results in hide/show events pair. + */ + void RecreateAccessible(nsIContent* aContent); + + /** + * Schedule ARIA owned element relocation if needed. Return true if relocation + * was scheduled. + */ + bool RelocateARIAOwnedIfNeeded(nsIContent* aEl); + + /** + * Return a notification controller associated with the document. + */ + NotificationController* Controller() const { return mNotificationController; } + + /** + * If this document is in a content process return the object responsible for + * communicating with the main process for it. + */ + DocAccessibleChild* IPCDoc() const { return mIPCDoc; } + + /** + * Notify the document that a DOM node has been scrolled. document will + * dispatch throttled accessibility events for scrolling, and a scroll-end + * event. + */ + void HandleScroll(nsINode* aTarget); + + protected: + virtual ~DocAccessible(); + + void LastRelease(); + + // DocAccessible + virtual nsresult AddEventListeners(); + virtual nsresult RemoveEventListeners(); + + /** + * Marks this document as loaded or loading. + */ + void NotifyOfLoad(uint32_t aLoadEventType); + void NotifyOfLoading(bool aIsReloading); + + friend class DocManager; + + /** + * Perform initial update (create accessible tree). + * Can be overridden by wrappers to prepare initialization work. + */ + virtual void DoInitialUpdate(); + + /** + * Updates root element and picks up ARIA role on it if any. + */ + void UpdateRootElIfNeeded(); + + /** + * Process document load notification, fire document load and state busy + * events if applicable. + */ + void ProcessLoad(); + + /** + * Append the given document accessible to this document's child document + * accessibles. + */ + bool AppendChildDocument(DocAccessible* aChildDocument) { + // XXX(Bug 1631371) Check if this should use a fallible operation as it + // pretended earlier, or change the return type to void. + mChildDocuments.AppendElement(aChildDocument); + return true; + } + + /** + * Remove the given document accessible from this document's child document + * accessibles. + */ + void RemoveChildDocument(DocAccessible* aChildDocument) { + mChildDocuments.RemoveElement(aChildDocument); + } + + /** + * Add dependent IDs pointed by accessible element by relation attribute to + * cache. If the relation attribute is missed then all relation attributes + * are checked. + * + * @param aRelProvider [in] accessible that element has relation attribute + * @param aRelAttr [in, optional] relation attribute + */ + void AddDependentIDsFor(Accessible* aRelProvider, nsAtom* aRelAttr = nullptr); + + /** + * Remove dependent IDs pointed by accessible element by relation attribute + * from cache. If the relation attribute is absent then all relation + * attributes are checked. + * + * @param aRelProvider [in] accessible that element has relation attribute + * @param aRelAttr [in, optional] relation attribute + */ + void RemoveDependentIDsFor(Accessible* aRelProvider, + nsAtom* aRelAttr = nullptr); + + /** + * Update or recreate an accessible depending on a changed attribute. + * + * @param aElement [in] the element the attribute was changed on + * @param aAttribute [in] the changed attribute + * @return true if an action was taken on the attribute change + */ + bool UpdateAccessibleOnAttrChange(mozilla::dom::Element* aElement, + nsAtom* aAttribute); + + /** + * Fire accessible events when attribute is changed. + * + * @param aAccessible [in] accessible the DOM attribute is changed for + * @param aNameSpaceID [in] namespace of changed attribute + * @param aAttribute [in] changed attribute + * @param aModType [in] modification type (changed/added/removed) + */ + void AttributeChangedImpl(Accessible* aAccessible, int32_t aNameSpaceID, + nsAtom* aAttribute, int32_t aModType); + + /** + * Fire accessible events when ARIA attribute is changed. + * + * @param aAccessible [in] accesislbe the DOM attribute is changed for + * @param aAttribute [in] changed attribute + */ + void ARIAAttributeChanged(Accessible* aAccessible, nsAtom* aAttribute); + + /** + * Process ARIA active-descendant attribute change. + */ + void ARIAActiveDescendantChanged(Accessible* aAccessible); + + /** + * Update the accessible tree for inserted content. + */ + void ProcessContentInserted( + Accessible* aContainer, + const nsTArray<nsCOMPtr<nsIContent>>* aInsertedContent); + void ProcessContentInserted(Accessible* aContainer, + nsIContent* aInsertedContent); + + /** + * Used to notify the document to make it process the invalidation list. + * + * While children are cached we may encounter the case there's no accessible + * for referred content by related accessible. Store these related nodes to + * invalidate their containers later. + */ + void ProcessInvalidationList(); + + /** + * Steals or puts back accessible subtrees. + */ + void DoARIAOwnsRelocation(Accessible* aOwner); + + /** + * Moves children back under their original parents. + */ + void PutChildrenBack(nsTArray<RefPtr<Accessible>>* aChildren, + uint32_t aStartIdx); + + bool MoveChild(Accessible* aChild, Accessible* aNewParent, + int32_t aIdxInParent); + + /** + * Create accessible tree. + * + * @param aRoot [in] a root of subtree to create + * @param aFocusedAcc [in, optional] a focused accessible under created + * subtree if any + */ + void CacheChildrenInSubtree(Accessible* aRoot, + Accessible** aFocusedAcc = nullptr); + void CreateSubtree(Accessible* aRoot); + + /** + * Remove accessibles in subtree from node to accessible map. + */ + void UncacheChildrenInSubtree(Accessible* aRoot); + + /** + * Shutdown any cached accessible in the subtree. + * + * @param aAccessible [in] the root of the subrtee to invalidate accessible + * child/parent refs in + */ + void ShutdownChildrenInSubtree(Accessible* aAccessible); + + /** + * Return true if the document is a target of document loading events + * (for example, state busy change or document reload events). + * + * Rules: The root chrome document accessible is never an event target + * (for example, Firefox UI window). If the sub document is loaded within its + * parent document then the parent document is a target only (aka events + * coalescence). + */ + bool IsLoadEventTarget() const; + + /* + * Set the object responsible for communicating with the main process on + * behalf of this document. + */ + void SetIPCDoc(DocAccessibleChild* aIPCDoc); + + friend class DocAccessibleChildBase; + + /** + * Used to fire scrolling end event after page scroll. + * + * @param aTimer [in] the timer object + * @param aClosure [in] the document accessible where scrolling happens + */ + static void ScrollTimerCallback(nsITimer* aTimer, void* aClosure); + + void DispatchScrollingEvent(nsINode* aTarget, uint32_t aEventType); + + /** + * Check if an id attribute change affects aria-activedescendant and handle + * the aria-activedescendant change if appropriate. + * If the currently focused element has aria-activedescendant and an + * element's id changes to match this, the id was probably moved from the + * previous active descendant, thus making this element the new active + * descendant. In that case, accessible focus must be changed accordingly. + */ + void ARIAActiveDescendantIDMaybeMoved(dom::Element* aElm); + + /** + * Traverse content subtree and for each node do one of 3 things: + * 1. Check if content node has an accessible that should be removed and + * remove it. + * 2. Check if content node has an accessible that needs to be recreated. + * Remove it and schedule it for reinsertion. + * 3. Check if content node has no accessible but needs one. Schedule one for + * insertion. + * + * Returns true if the root node should be reinserted. + */ + bool PruneOrInsertSubtree(nsIContent* aRoot); + + protected: + /** + * State and property flags, kept by mDocFlags. + */ + enum { + // Whether the document is a top level content document in this process. + eTopLevelContentDocInProcess = 1 << 0 + }; + + /** + * Cache of accessibles within this document accessible. + */ + AccessibleHashtable mAccessibleCache; + nsDataHashtable<nsPtrHashKey<const nsINode>, Accessible*> + mNodeToAccessibleMap; + + Document* mDocumentNode; + nsCOMPtr<nsITimer> mScrollWatchTimer; + nsDataHashtable<nsPtrHashKey<nsINode>, TimeStamp> mLastScrollingDispatch; + + /** + * Bit mask of document load states (@see LoadState). + */ + uint32_t mLoadState : 3; + + /** + * Bit mask of other states and props. + */ + uint32_t mDocFlags : 28; + + /** + * Type of document load event fired after the document is loaded completely. + */ + uint32_t mLoadEventType; + + /** + * Reference to anchor jump element. + */ + nsCOMPtr<nsIContent> mAnchorJumpElm; + + /** + * A generic state (see items below) before the attribute value was changed. + * @see AttributeWillChange and AttributeChanged notifications. + */ + union { + // ARIA attribute value + const nsAtom* mARIAAttrOldValue; + + // Previous state bits before attribute change + uint64_t mPrevStateBits; + }; + + nsTArray<RefPtr<DocAccessible>> mChildDocuments; + + /** + * The virtual cursor of the document. + */ + RefPtr<nsAccessiblePivot> mVirtualCursor; + + /** + * A storage class for pairing content with one of its relation attributes. + */ + class AttrRelProvider { + public: + AttrRelProvider(nsAtom* aRelAttr, nsIContent* aContent) + : mRelAttr(aRelAttr), mContent(aContent) {} + + nsAtom* mRelAttr; + nsCOMPtr<nsIContent> mContent; + + private: + AttrRelProvider(); + AttrRelProvider(const AttrRelProvider&); + AttrRelProvider& operator=(const AttrRelProvider&); + }; + + typedef nsTArray<mozilla::UniquePtr<AttrRelProvider>> AttrRelProviders; + typedef nsClassHashtable<nsStringHashKey, AttrRelProviders> + DependentIDsHashtable; + + /** + * Returns/creates/removes attribute relation providers associated with + * a DOM document if the element is in uncomposed document or associated + * with shadow DOM the element is in. + */ + AttrRelProviders* GetRelProviders(dom::Element* aElement, + const nsAString& aID) const; + AttrRelProviders* GetOrCreateRelProviders(dom::Element* aElement, + const nsAString& aID); + void RemoveRelProvidersIfEmpty(dom::Element* aElement, const nsAString& aID); + + /** + * The cache of IDs pointed by relation attributes. + */ + nsClassHashtable<nsPtrHashKey<dom::DocumentOrShadowRoot>, + DependentIDsHashtable> + mDependentIDsHashes; + + friend class RelatedAccIterator; + + /** + * Used for our caching algorithm. We store the list of nodes that should be + * invalidated. + * + * @see ProcessInvalidationList + */ + nsTArray<RefPtr<nsIContent>> mInvalidationList; + + /** + * Holds a list of aria-owns relocations. + */ + nsClassHashtable<nsPtrHashKey<Accessible>, nsTArray<RefPtr<Accessible>>> + mARIAOwnsHash; + + /** + * Used to process notification from core and accessible events. + */ + RefPtr<NotificationController> mNotificationController; + friend class EventTree; + friend class NotificationController; + + private: + void SetRoleMapEntryForDoc(dom::Element* aElement); + + PresShell* mPresShell; + + // Exclusively owned by IPDL so don't manually delete it! + DocAccessibleChild* mIPCDoc; +}; + +inline DocAccessible* Accessible::AsDoc() { + return IsDoc() ? static_cast<DocAccessible*>(this) : nullptr; +} + +} // namespace a11y +} // namespace mozilla + +#endif diff --git a/accessible/generic/FormControlAccessible.cpp b/accessible/generic/FormControlAccessible.cpp new file mode 100644 index 0000000000..0bf6ccb02a --- /dev/null +++ b/accessible/generic/FormControlAccessible.cpp @@ -0,0 +1,99 @@ +/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +// NOTE: alphabetically ordered + +#include "FormControlAccessible.h" + +#include "mozilla/dom/HTMLInputElement.h" +#include "mozilla/FloatingPoint.h" +#include "Role.h" + +using namespace mozilla::a11y; + +//////////////////////////////////////////////////////////////////////////////// +// CheckboxAccessible +//////////////////////////////////////////////////////////////////////////////// + +role CheckboxAccessible::NativeRole() const { return roles::CHECKBUTTON; } + +uint8_t CheckboxAccessible::ActionCount() const { return 1; } + +void CheckboxAccessible::ActionNameAt(uint8_t aIndex, nsAString& aName) { + if (aIndex == eAction_Click) { + uint64_t state = NativeState(); + if (state & states::CHECKED) { + aName.AssignLiteral("uncheck"); + } else if (state & states::MIXED) { + aName.AssignLiteral("cycle"); + } else { + aName.AssignLiteral("check"); + } + } +} + +bool CheckboxAccessible::DoAction(uint8_t aIndex) const { + if (aIndex != eAction_Click) { + return false; + } + DoCommand(); + return true; +} + +uint64_t CheckboxAccessible::NativeState() const { + uint64_t state = LeafAccessible::NativeState(); + + state |= states::CHECKABLE; + dom::HTMLInputElement* input = dom::HTMLInputElement::FromNode(mContent); + if (input) { // HTML:input@type="checkbox" + if (input->Indeterminate()) { + return state | states::MIXED; + } + + if (input->Checked()) { + return state | states::CHECKED; + } + + } else if (mContent->AsElement()->AttrValueIs( + kNameSpaceID_None, nsGkAtoms::checked, nsGkAtoms::_true, + eCaseMatters)) { // XUL checkbox + return state | states::CHECKED; + } + + return state; +} + +//////////////////////////////////////////////////////////////////////////////// +// CheckboxAccessible: Widgets + +bool CheckboxAccessible::IsWidget() const { return true; } + +//////////////////////////////////////////////////////////////////////////////// +// RadioButtonAccessible +//////////////////////////////////////////////////////////////////////////////// + +RadioButtonAccessible::RadioButtonAccessible(nsIContent* aContent, + DocAccessible* aDoc) + : LeafAccessible(aContent, aDoc) {} + +uint8_t RadioButtonAccessible::ActionCount() const { return 1; } + +void RadioButtonAccessible::ActionNameAt(uint8_t aIndex, nsAString& aName) { + if (aIndex == eAction_Click) aName.AssignLiteral("select"); +} + +bool RadioButtonAccessible::DoAction(uint8_t aIndex) const { + if (aIndex != eAction_Click) return false; + + DoCommand(); + return true; +} + +role RadioButtonAccessible::NativeRole() const { return roles::RADIOBUTTON; } + +//////////////////////////////////////////////////////////////////////////////// +// RadioButtonAccessible: Widgets + +bool RadioButtonAccessible::IsWidget() const { return true; } diff --git a/accessible/generic/FormControlAccessible.h b/accessible/generic/FormControlAccessible.h new file mode 100644 index 0000000000..eb7466de81 --- /dev/null +++ b/accessible/generic/FormControlAccessible.h @@ -0,0 +1,67 @@ +/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +#ifndef MOZILLA_A11Y_FormControlAccessible_H_ +#define MOZILLA_A11Y_FormControlAccessible_H_ + +#include "BaseAccessibles.h" + +namespace mozilla { +namespace a11y { + +/** + * Checkbox accessible. + */ +class CheckboxAccessible : public LeafAccessible { + public: + enum { eAction_Click = 0 }; + + CheckboxAccessible(nsIContent* aContent, DocAccessible* aDoc) + : LeafAccessible(aContent, aDoc) { + // Ignore "CheckboxStateChange" DOM event in lieu of document observer + // state change notification. + if (aContent->IsHTMLElement()) { + mStateFlags |= eIgnoreDOMUIEvent; + } + } + + // Accessible + virtual mozilla::a11y::role NativeRole() const override; + virtual uint64_t NativeState() const override; + + // ActionAccessible + virtual uint8_t ActionCount() const override; + virtual void ActionNameAt(uint8_t aIndex, nsAString& aName) override; + virtual bool DoAction(uint8_t aIndex) const override; + + // Widgets + virtual bool IsWidget() const override; +}; + +/** + * Generic class used for radio buttons. + */ +class RadioButtonAccessible : public LeafAccessible { + public: + RadioButtonAccessible(nsIContent* aContent, DocAccessible* aDoc); + + // Accessible + virtual mozilla::a11y::role NativeRole() const override; + + // ActionAccessible + virtual uint8_t ActionCount() const override; + virtual void ActionNameAt(uint8_t aIndex, nsAString& aName) override; + virtual bool DoAction(uint8_t aIndex) const override; + + enum { eAction_Click = 0 }; + + // Widgets + virtual bool IsWidget() const override; +}; + +} // namespace a11y +} // namespace mozilla + +#endif diff --git a/accessible/generic/HyperTextAccessible-inl.h b/accessible/generic/HyperTextAccessible-inl.h new file mode 100644 index 0000000000..bf4edea477 --- /dev/null +++ b/accessible/generic/HyperTextAccessible-inl.h @@ -0,0 +1,151 @@ +/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +#ifndef mozilla_a11y_HyperTextAccessible_inl_h__ +#define mozilla_a11y_HyperTextAccessible_inl_h__ + +#include "HyperTextAccessible.h" + +#include "nsAccUtils.h" + +#include "nsIClipboard.h" +#include "nsFrameSelection.h" + +#include "mozilla/TextEditor.h" + +namespace mozilla { +namespace a11y { + +inline bool HyperTextAccessible::IsValidOffset(int32_t aOffset) { + index_t offset = ConvertMagicOffset(aOffset); + return offset.IsValid() && offset <= CharacterCount(); +} + +inline bool HyperTextAccessible::IsValidRange(int32_t aStartOffset, + int32_t aEndOffset) { + index_t startOffset = ConvertMagicOffset(aStartOffset); + index_t endOffset = ConvertMagicOffset(aEndOffset); + return startOffset.IsValid() && endOffset.IsValid() && + startOffset <= endOffset && endOffset <= CharacterCount(); +} + +inline void HyperTextAccessible::SetCaretOffset(int32_t aOffset) { + SetSelectionRange(aOffset, aOffset); + // XXX: Force cache refresh until a good solution for AT emulation of user + // input is implemented (AccessFu caret movement). + SelectionMgr()->UpdateCaretOffset(this, aOffset); +} + +inline bool HyperTextAccessible::AddToSelection(int32_t aStartOffset, + int32_t aEndOffset) { + dom::Selection* domSel = DOMSelection(); + return domSel && + SetSelectionBoundsAt(domSel->RangeCount(), aStartOffset, aEndOffset); +} + +inline void HyperTextAccessible::ReplaceText(const nsAString& aText) { + if (aText.Length() == 0) { + DeleteText(0, CharacterCount()); + return; + } + + SetSelectionRange(0, CharacterCount()); + + RefPtr<TextEditor> textEditor = GetEditor(); + if (!textEditor) { + return; + } + + DebugOnly<nsresult> rv = textEditor->InsertTextAsAction(aText); + NS_WARNING_ASSERTION(NS_SUCCEEDED(rv), "Failed to insert the new text"); +} + +inline void HyperTextAccessible::InsertText(const nsAString& aText, + int32_t aPosition) { + RefPtr<TextEditor> textEditor = GetEditor(); + if (textEditor) { + SetSelectionRange(aPosition, aPosition); + DebugOnly<nsresult> rv = textEditor->InsertTextAsAction(aText); + NS_WARNING_ASSERTION(NS_SUCCEEDED(rv), "Failed to insert the text"); + } +} + +inline void HyperTextAccessible::CopyText(int32_t aStartPos, int32_t aEndPos) { + RefPtr<TextEditor> textEditor = GetEditor(); + if (textEditor) { + SetSelectionRange(aStartPos, aEndPos); + textEditor->Copy(); + } +} + +inline void HyperTextAccessible::CutText(int32_t aStartPos, int32_t aEndPos) { + RefPtr<TextEditor> textEditor = GetEditor(); + if (textEditor) { + SetSelectionRange(aStartPos, aEndPos); + textEditor->Cut(); + } +} + +inline void HyperTextAccessible::DeleteText(int32_t aStartPos, + int32_t aEndPos) { + RefPtr<TextEditor> textEditor = GetEditor(); + if (!textEditor) { + return; + } + SetSelectionRange(aStartPos, aEndPos); + DebugOnly<nsresult> rv = + textEditor->DeleteSelectionAsAction(nsIEditor::eNone, nsIEditor::eStrip); + NS_WARNING_ASSERTION(NS_SUCCEEDED(rv), "Failed to delete text"); +} + +inline void HyperTextAccessible::PasteText(int32_t aPosition) { + RefPtr<TextEditor> textEditor = GetEditor(); + if (textEditor) { + SetSelectionRange(aPosition, aPosition); + textEditor->PasteAsAction(nsIClipboard::kGlobalClipboard, true); + } +} + +inline index_t HyperTextAccessible::ConvertMagicOffset(int32_t aOffset) const { + if (aOffset == nsIAccessibleText::TEXT_OFFSET_END_OF_TEXT) + return CharacterCount(); + + if (aOffset == nsIAccessibleText::TEXT_OFFSET_CARET) return CaretOffset(); + + return aOffset; +} + +inline uint32_t HyperTextAccessible::AdjustCaretOffset(uint32_t aOffset) const { + // It is the same character offset when the caret is visually at the very + // end of a line or the start of a new line (soft line break). Getting text + // at the line should provide the line with the visual caret, otherwise + // screen readers will announce the wrong line as the user presses up or + // down arrow and land at the end of a line. + if (aOffset > 0 && IsCaretAtEndOfLine()) return aOffset - 1; + + return aOffset; +} + +inline bool HyperTextAccessible::IsCaretAtEndOfLine() const { + RefPtr<nsFrameSelection> frameSelection = FrameSelection(); + return frameSelection && frameSelection->GetHint() == CARET_ASSOCIATE_BEFORE; +} + +inline already_AddRefed<nsFrameSelection> HyperTextAccessible::FrameSelection() + const { + nsIFrame* frame = GetFrame(); + return frame ? frame->GetFrameSelection() : nullptr; +} + +inline dom::Selection* HyperTextAccessible::DOMSelection() const { + RefPtr<nsFrameSelection> frameSelection = FrameSelection(); + return frameSelection ? frameSelection->GetSelection(SelectionType::eNormal) + : nullptr; +} + +} // namespace a11y +} // namespace mozilla + +#endif diff --git a/accessible/generic/HyperTextAccessible.cpp b/accessible/generic/HyperTextAccessible.cpp new file mode 100644 index 0000000000..14ebbd117e --- /dev/null +++ b/accessible/generic/HyperTextAccessible.cpp @@ -0,0 +1,2423 @@ +/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* vim: set ts=2 sw=2 et tw=78: */ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +#include "HyperTextAccessible-inl.h" + +#include "Accessible-inl.h" +#include "nsAccessibilityService.h" +#include "nsAccessiblePivot.h" +#include "nsIAccessibleTypes.h" +#include "DocAccessible.h" +#include "HTMLListAccessible.h" +#include "Pivot.h" +#include "Relation.h" +#include "Role.h" +#include "States.h" +#include "TextAttrs.h" +#include "TextRange.h" +#include "TreeWalker.h" + +#include "nsCaret.h" +#include "nsContentUtils.h" +#include "nsDebug.h" +#include "nsFocusManager.h" +#include "nsIEditingSession.h" +#include "nsContainerFrame.h" +#include "nsFrameSelection.h" +#include "nsILineIterator.h" +#include "nsIInterfaceRequestorUtils.h" +#include "nsPersistentProperties.h" +#include "nsIScrollableFrame.h" +#include "nsIMathMLFrame.h" +#include "nsRange.h" +#include "nsTextFragment.h" +#include "mozilla/Assertions.h" +#include "mozilla/BinarySearch.h" +#include "mozilla/EventStates.h" +#include "mozilla/HTMLEditor.h" +#include "mozilla/MathAlgorithms.h" +#include "mozilla/PresShell.h" +#include "mozilla/StaticPrefs_layout.h" +#include "mozilla/TextEditor.h" +#include "mozilla/dom/Element.h" +#include "mozilla/dom/HTMLBRElement.h" +#include "mozilla/dom/HTMLHeadingElement.h" +#include "mozilla/dom/Selection.h" +#include "gfxSkipChars.h" +#include <algorithm> + +using namespace mozilla; +using namespace mozilla::a11y; + +/** + * This class is used in HyperTextAccessible to search for paragraph + * boundaries. + */ +class ParagraphBoundaryRule : public PivotRule { + public: + explicit ParagraphBoundaryRule(Accessible* aAnchor, + uint32_t aAnchorTextoffset, + nsDirection aDirection, + bool aSkipAnchorSubtree = false) + : mAnchor(aAnchor), + mAnchorTextOffset(aAnchorTextoffset), + mDirection(aDirection), + mSkipAnchorSubtree(aSkipAnchorSubtree), + mLastMatchTextOffset(0) {} + + virtual uint16_t Match(const AccessibleOrProxy& aAccOrProxy) override { + MOZ_ASSERT(aAccOrProxy.IsAccessible()); + Accessible* acc = aAccOrProxy.AsAccessible(); + if (acc->IsOuterDoc()) { + // The child document might be remote and we can't (and don't want to) + // handle remote documents. Also, iframes are inline anyway and thus + // can't be paragraph boundaries. Therefore, skip this unconditionally. + return nsIAccessibleTraversalRule::FILTER_IGNORE_SUBTREE; + } + + uint16_t result = nsIAccessibleTraversalRule::FILTER_IGNORE; + if (mSkipAnchorSubtree && acc == mAnchor) { + result |= nsIAccessibleTraversalRule::FILTER_IGNORE_SUBTREE; + } + + // First, deal with the case that we encountered a line break, for example, + // a br in a paragraph. + if (acc->Role() == roles::WHITESPACE) { + result |= nsIAccessibleTraversalRule::FILTER_MATCH; + return result; + } + + // Now, deal with the case that we encounter a new block level accessible. + // This also means a new paragraph boundary start. + nsIFrame* frame = acc->GetFrame(); + if (frame && frame->IsBlockFrame()) { + result |= nsIAccessibleTraversalRule::FILTER_MATCH; + return result; + } + + // A text leaf can contain a line break if it's pre-formatted text. + if (acc->IsTextLeaf()) { + nsAutoString name; + acc->Name(name); + int32_t offset; + if (mDirection == eDirPrevious) { + if (acc == mAnchor && mAnchorTextOffset == 0) { + // We're already at the start of this node, so there can be no line + // break before. + return result; + } + // If we began on a line break, we don't want to match it, so search + // from 1 before our anchor offset. + offset = + name.RFindChar('\n', acc == mAnchor ? mAnchorTextOffset - 1 : -1); + } else { + offset = name.FindChar('\n', acc == mAnchor ? mAnchorTextOffset : 0); + } + if (offset != -1) { + // Line ebreak! + mLastMatchTextOffset = offset; + result |= nsIAccessibleTraversalRule::FILTER_MATCH; + } + } + + return result; + } + + // This is only valid if the last match was a text leaf. It returns the + // offset of the line break character in that text leaf. + uint32_t GetLastMatchTextOffset() { return mLastMatchTextOffset; } + + private: + Accessible* mAnchor; + uint32_t mAnchorTextOffset; + nsDirection mDirection; + bool mSkipAnchorSubtree; + uint32_t mLastMatchTextOffset; +}; + +/** + * This class is used in HyperTextAccessible::FindParagraphStartOffset to + * search forward exactly one step from a match found by the above. + * It should only be initialized with a boundary, and it will skip that + * boundary's sub tree if it is a block element boundary. + */ +class SkipParagraphBoundaryRule : public PivotRule { + public: + explicit SkipParagraphBoundaryRule(AccessibleOrProxy& aBoundary) + : mBoundary(aBoundary) {} + + virtual uint16_t Match(const AccessibleOrProxy& aAccOrProxy) override { + MOZ_ASSERT(aAccOrProxy.IsAccessible()); + // If matching the boundary, skip its sub tree. + if (aAccOrProxy == mBoundary) { + return nsIAccessibleTraversalRule::FILTER_IGNORE_SUBTREE; + } + return nsIAccessibleTraversalRule::FILTER_MATCH; + } + + private: + AccessibleOrProxy& mBoundary; +}; + +//////////////////////////////////////////////////////////////////////////////// +// HyperTextAccessible +//////////////////////////////////////////////////////////////////////////////// + +HyperTextAccessible::HyperTextAccessible(nsIContent* aNode, DocAccessible* aDoc) + : AccessibleWrap(aNode, aDoc) { + mType = eHyperTextType; + mGenericTypes |= eHyperText; +} + +role HyperTextAccessible::NativeRole() const { + a11y::role r = GetAccService()->MarkupRole(mContent); + if (r != roles::NOTHING) return r; + + nsIFrame* frame = GetFrame(); + if (frame && frame->IsInlineFrame()) return roles::TEXT; + + return roles::TEXT_CONTAINER; +} + +uint64_t HyperTextAccessible::NativeState() const { + uint64_t states = AccessibleWrap::NativeState(); + + if (mContent->AsElement()->State().HasState(NS_EVENT_STATE_READWRITE)) { + states |= states::EDITABLE; + + } else if (mContent->IsHTMLElement(nsGkAtoms::article)) { + // We want <article> to behave like a document in terms of readonly state. + states |= states::READONLY; + } + + nsIFrame* frame = GetFrame(); + if ((states & states::EDITABLE) || (frame && frame->IsSelectable(nullptr))) { + // If the accessible is editable the layout selectable state only disables + // mouse selection, but keyboard (shift+arrow) selection is still possible. + states |= states::SELECTABLE_TEXT; + } + + return states; +} + +nsIntRect HyperTextAccessible::GetBoundsInFrame(nsIFrame* aFrame, + uint32_t aStartRenderedOffset, + uint32_t aEndRenderedOffset) { + nsPresContext* presContext = mDoc->PresContext(); + if (!aFrame->IsTextFrame()) { + return aFrame->GetScreenRectInAppUnits().ToNearestPixels( + presContext->AppUnitsPerDevPixel()); + } + + // Substring must be entirely within the same text node. + int32_t startContentOffset, endContentOffset; + nsresult rv = RenderedToContentOffset(aFrame, aStartRenderedOffset, + &startContentOffset); + NS_ENSURE_SUCCESS(rv, nsIntRect()); + rv = RenderedToContentOffset(aFrame, aEndRenderedOffset, &endContentOffset); + NS_ENSURE_SUCCESS(rv, nsIntRect()); + + nsIFrame* frame; + int32_t startContentOffsetInFrame; + // Get the right frame continuation -- not really a child, but a sibling of + // the primary frame passed in + rv = aFrame->GetChildFrameContainingOffset( + startContentOffset, false, &startContentOffsetInFrame, &frame); + NS_ENSURE_SUCCESS(rv, nsIntRect()); + + nsRect screenRect; + while (frame && startContentOffset < endContentOffset) { + // Start with this frame's screen rect, which we will shrink based on + // the substring we care about within it. We will then add that frame to + // the total screenRect we are returning. + nsRect frameScreenRect = frame->GetScreenRectInAppUnits(); + + // Get the length of the substring in this frame that we want the bounds for + int32_t startFrameTextOffset, endFrameTextOffset; + frame->GetOffsets(startFrameTextOffset, endFrameTextOffset); + int32_t frameTotalTextLength = endFrameTextOffset - startFrameTextOffset; + int32_t seekLength = endContentOffset - startContentOffset; + int32_t frameSubStringLength = + std::min(frameTotalTextLength - startContentOffsetInFrame, seekLength); + + // Add the point where the string starts to the frameScreenRect + nsPoint frameTextStartPoint; + rv = frame->GetPointFromOffset(startContentOffset, &frameTextStartPoint); + NS_ENSURE_SUCCESS(rv, nsIntRect()); + + // Use the point for the end offset to calculate the width + nsPoint frameTextEndPoint; + rv = frame->GetPointFromOffset(startContentOffset + frameSubStringLength, + &frameTextEndPoint); + NS_ENSURE_SUCCESS(rv, nsIntRect()); + + frameScreenRect.SetRectX( + frameScreenRect.X() + + std::min(frameTextStartPoint.x, frameTextEndPoint.x), + mozilla::Abs(frameTextStartPoint.x - frameTextEndPoint.x)); + + screenRect.UnionRect(frameScreenRect, screenRect); + + // Get ready to loop back for next frame continuation + startContentOffset += frameSubStringLength; + startContentOffsetInFrame = 0; + frame = frame->GetNextContinuation(); + } + + return screenRect.ToNearestPixels(presContext->AppUnitsPerDevPixel()); +} + +void HyperTextAccessible::TextSubstring(int32_t aStartOffset, + int32_t aEndOffset, nsAString& aText) { + aText.Truncate(); + + index_t startOffset = ConvertMagicOffset(aStartOffset); + index_t endOffset = ConvertMagicOffset(aEndOffset); + if (!startOffset.IsValid() || !endOffset.IsValid() || + startOffset > endOffset || endOffset > CharacterCount()) { + NS_ERROR("Wrong in offset"); + return; + } + + int32_t startChildIdx = GetChildIndexAtOffset(startOffset); + if (startChildIdx == -1) return; + + int32_t endChildIdx = GetChildIndexAtOffset(endOffset); + if (endChildIdx == -1) return; + + if (startChildIdx == endChildIdx) { + int32_t childOffset = GetChildOffset(startChildIdx); + if (childOffset == -1) return; + + Accessible* child = GetChildAt(startChildIdx); + child->AppendTextTo(aText, startOffset - childOffset, + endOffset - startOffset); + return; + } + + int32_t startChildOffset = GetChildOffset(startChildIdx); + if (startChildOffset == -1) return; + + Accessible* startChild = GetChildAt(startChildIdx); + startChild->AppendTextTo(aText, startOffset - startChildOffset); + + for (int32_t childIdx = startChildIdx + 1; childIdx < endChildIdx; + childIdx++) { + Accessible* child = GetChildAt(childIdx); + child->AppendTextTo(aText); + } + + int32_t endChildOffset = GetChildOffset(endChildIdx); + if (endChildOffset == -1) return; + + Accessible* endChild = GetChildAt(endChildIdx); + endChild->AppendTextTo(aText, 0, endOffset - endChildOffset); +} + +uint32_t HyperTextAccessible::DOMPointToOffset(nsINode* aNode, + int32_t aNodeOffset, + bool aIsEndOffset) const { + if (!aNode) return 0; + + uint32_t offset = 0; + nsINode* findNode = nullptr; + + if (aNodeOffset == -1) { + findNode = aNode; + + } else if (aNode->IsText()) { + // For text nodes, aNodeOffset comes in as a character offset + // Text offset will be added at the end, if we find the offset in this + // hypertext We want the "skipped" offset into the text (rendered text + // without the extra whitespace) + nsIFrame* frame = aNode->AsContent()->GetPrimaryFrame(); + NS_ENSURE_TRUE(frame, 0); + + nsresult rv = ContentToRenderedOffset(frame, aNodeOffset, &offset); + NS_ENSURE_SUCCESS(rv, 0); + + findNode = aNode; + + } else { + // findNode could be null if aNodeOffset == # of child nodes, which means + // one of two things: + // 1) there are no children, and the passed-in node is not mContent -- use + // parentContent for the node to find + // 2) there are no children and the passed-in node is mContent, which means + // we're an empty nsIAccessibleText + // 3) there are children and we're at the end of the children + + findNode = aNode->GetChildAt_Deprecated(aNodeOffset); + if (!findNode) { + if (aNodeOffset == 0) { + if (aNode == GetNode()) { + // Case #1: this accessible has no children and thus has empty text, + // we can only be at hypertext offset 0. + return 0; + } + + // Case #2: there are no children, we're at this node. + findNode = aNode; + } else if (aNodeOffset == static_cast<int32_t>(aNode->GetChildCount())) { + // Case #3: we're after the last child, get next node to this one. + for (nsINode* tmpNode = aNode; + !findNode && tmpNode && tmpNode != mContent; + tmpNode = tmpNode->GetParent()) { + findNode = tmpNode->GetNextSibling(); + } + } + } + } + + // Get accessible for this findNode, or if that node isn't accessible, use the + // accessible for the next DOM node which has one (based on forward depth + // first search) + Accessible* descendant = nullptr; + if (findNode) { + dom::HTMLBRElement* brElement = dom::HTMLBRElement::FromNode(findNode); + if (brElement && brElement->IsPaddingForEmptyEditor()) { + // This <br> is the hacky "padding <br> element" used when there is no + // text in the editor. + return 0; + } + + descendant = mDoc->GetAccessible(findNode); + if (!descendant && findNode->IsContent()) { + Accessible* container = mDoc->GetContainerAccessible(findNode); + if (container) { + TreeWalker walker(container, findNode->AsContent(), + TreeWalker::eWalkContextTree); + descendant = walker.Next(); + if (!descendant) descendant = container; + } + } + } + + return TransformOffset(descendant, offset, aIsEndOffset); +} + +uint32_t HyperTextAccessible::TransformOffset(Accessible* aDescendant, + uint32_t aOffset, + bool aIsEndOffset) const { + // From the descendant, go up and get the immediate child of this hypertext. + uint32_t offset = aOffset; + Accessible* descendant = aDescendant; + while (descendant) { + Accessible* parent = descendant->Parent(); + if (parent == this) return GetChildOffset(descendant) + offset; + + // This offset no longer applies because the passed-in text object is not + // a child of the hypertext. This happens when there are nested hypertexts, + // e.g. <div>abc<h1>def</h1>ghi</div>. Thus we need to adjust the offset + // to make it relative the hypertext. + // If the end offset is not supposed to be inclusive and the original point + // is not at 0 offset then the returned offset should be after an embedded + // character the original point belongs to. + if (aIsEndOffset) { + // Similar to our special casing in FindOffset, we add handling for + // bulleted lists here because PeekOffset returns the inner text node + // for a list when it should return the list bullet. + // We manually set the offset so the error doesn't propagate up. + if (offset == 0 && parent && parent->IsHTMLListItem() && + descendant->PrevSibling() && descendant->PrevSibling()->GetFrame() && + descendant->PrevSibling()->GetFrame()->IsBulletFrame()) { + offset = 0; + } else { + offset = (offset > 0 || descendant->IndexInParent() > 0) ? 1 : 0; + } + } else { + offset = 0; + } + + descendant = parent; + } + + // If the given a11y point cannot be mapped into offset relative this + // hypertext offset then return length as fallback value. + return CharacterCount(); +} + +DOMPoint HyperTextAccessible::OffsetToDOMPoint(int32_t aOffset) const { + // 0 offset is valid even if no children. In this case the associated editor + // is empty so return a DOM point for editor root element. + if (aOffset == 0) { + RefPtr<TextEditor> textEditor = GetEditor(); + if (textEditor) { + if (textEditor->IsEmpty()) { + return DOMPoint(textEditor->GetRoot(), 0); + } + } + } + + int32_t childIdx = GetChildIndexAtOffset(aOffset); + if (childIdx == -1) return DOMPoint(); + + Accessible* child = GetChildAt(childIdx); + int32_t innerOffset = aOffset - GetChildOffset(childIdx); + + // A text leaf case. + if (child->IsTextLeaf()) { + // The point is inside the text node. This is always true for any text leaf + // except a last child one. See assertion below. + if (aOffset < GetChildOffset(childIdx + 1)) { + nsIContent* content = child->GetContent(); + int32_t idx = 0; + if (NS_FAILED(RenderedToContentOffset(content->GetPrimaryFrame(), + innerOffset, &idx))) + return DOMPoint(); + + return DOMPoint(content, idx); + } + + // Set the DOM point right after the text node. + MOZ_ASSERT(static_cast<uint32_t>(aOffset) == CharacterCount()); + innerOffset = 1; + } + + // Case of embedded object. The point is either before or after the element. + NS_ASSERTION(innerOffset == 0 || innerOffset == 1, "A wrong inner offset!"); + nsINode* node = child->GetNode(); + nsINode* parentNode = node->GetParentNode(); + return parentNode ? DOMPoint(parentNode, + parentNode->ComputeIndexOf(node) + innerOffset) + : DOMPoint(); +} + +uint32_t HyperTextAccessible::FindOffset(uint32_t aOffset, + nsDirection aDirection, + nsSelectionAmount aAmount, + EWordMovementType aWordMovementType) { + NS_ASSERTION(aDirection == eDirPrevious || aAmount != eSelectBeginLine, + "eSelectBeginLine should only be used with eDirPrevious"); + + // Find a leaf accessible frame to start with. PeekOffset wants this. + HyperTextAccessible* text = this; + Accessible* child = nullptr; + int32_t innerOffset = aOffset; + + do { + int32_t childIdx = text->GetChildIndexAtOffset(innerOffset); + + // We can have an empty text leaf as our only child. Since empty text + // leaves are not accessible we then have no children, but 0 is a valid + // innerOffset. + if (childIdx == -1) { + NS_ASSERTION(innerOffset == 0 && !text->ChildCount(), "No childIdx?"); + return DOMPointToOffset(text->GetNode(), 0, aDirection == eDirNext); + } + + child = text->GetChildAt(childIdx); + + // HTML list items may need special processing because PeekOffset doesn't + // work with list bullets. + if (text->IsHTMLListItem()) { + HTMLLIAccessible* li = text->AsHTMLListItem(); + if (child == li->Bullet()) { + // XXX: the logic is broken for multichar bullets in moving by + // char/cluster/word cases. + if (text != this) { + return aDirection == eDirPrevious ? TransformOffset(text, 0, false) + : TransformOffset(text, 1, true); + } + if (aDirection == eDirPrevious) return 0; + + uint32_t nextOffset = GetChildOffset(1); + if (nextOffset == 0) return 0; + + switch (aAmount) { + case eSelectLine: + case eSelectEndLine: + // Ask a text leaf next (if not empty) to the bullet for an offset + // since list item may be multiline. + return nextOffset < CharacterCount() + ? FindOffset(nextOffset, aDirection, aAmount, + aWordMovementType) + : nextOffset; + + default: + return nextOffset; + } + } + } + + innerOffset -= text->GetChildOffset(childIdx); + + text = child->AsHyperText(); + } while (text); + + nsIFrame* childFrame = child->GetFrame(); + if (!childFrame) { + NS_ERROR("No child frame"); + return 0; + } + + int32_t innerContentOffset = innerOffset; + if (child->IsTextLeaf()) { + NS_ASSERTION(childFrame->IsTextFrame(), "Wrong frame!"); + RenderedToContentOffset(childFrame, innerOffset, &innerContentOffset); + } + + nsIFrame* frameAtOffset = childFrame; + int32_t unusedOffsetInFrame = 0; + childFrame->GetChildFrameContainingOffset( + innerContentOffset, true, &unusedOffsetInFrame, &frameAtOffset); + + const bool kIsJumpLinesOk = true; // okay to jump lines + const bool kIsScrollViewAStop = false; // do not stop at scroll views + const bool kIsKeyboardSelect = true; // is keyboard selection + const bool kIsVisualBidi = false; // use visual order for bidi text + nsPeekOffsetStruct pos( + aAmount, aDirection, innerContentOffset, nsPoint(0, 0), kIsJumpLinesOk, + kIsScrollViewAStop, kIsKeyboardSelect, kIsVisualBidi, false, + nsPeekOffsetStruct::ForceEditableRegion::No, aWordMovementType, false); + nsresult rv = frameAtOffset->PeekOffset(&pos); + + // PeekOffset fails on last/first lines of the text in certain cases. + bool fallBackToSelectEndLine = false; + if (NS_FAILED(rv) && aAmount == eSelectLine) { + fallBackToSelectEndLine = aDirection == eDirNext; + pos.mAmount = fallBackToSelectEndLine ? eSelectEndLine : eSelectBeginLine; + frameAtOffset->PeekOffset(&pos); + } + if (!pos.mResultContent) { + NS_ERROR("No result content!"); + return 0; + } + + // Turn the resulting DOM point into an offset. + uint32_t hyperTextOffset = DOMPointToOffset( + pos.mResultContent, pos.mContentOffset, aDirection == eDirNext); + + if (fallBackToSelectEndLine && IsLineEndCharAt(hyperTextOffset)) { + // We used eSelectEndLine, but the caller requested eSelectLine. + // If there's a '\n' at the end of the line, eSelectEndLine will stop on + // it rather than after it. This is not what we want, since the caller + // wants the next line, not the same line. + ++hyperTextOffset; + } + + if (aDirection == eDirPrevious) { + // If we reached the end during search, this means we didn't find the DOM + // point and we're actually at the start of the paragraph + if (hyperTextOffset == CharacterCount()) return 0; + + // PeekOffset stops right before bullet so return 0 to workaround it. + if (IsHTMLListItem() && aAmount == eSelectBeginLine && + hyperTextOffset > 0) { + Accessible* prevOffsetChild = GetChildAtOffset(hyperTextOffset - 1); + if (prevOffsetChild == AsHTMLListItem()->Bullet()) return 0; + } + } + + return hyperTextOffset; +} + +uint32_t HyperTextAccessible::FindWordBoundary( + uint32_t aOffset, nsDirection aDirection, + EWordMovementType aWordMovementType) { + uint32_t orig = + FindOffset(aOffset, aDirection, eSelectWord, aWordMovementType); + if (aWordMovementType != eStartWord) { + return orig; + } + if (aDirection == eDirPrevious) { + // When layout.word_select.stop_at_punctuation is true (the default), + // for a word beginning with punctuation, layout treats the punctuation + // as the start of the word when moving next. However, when moving + // previous, layout stops *after* the punctuation. We want to be + // consistent regardless of movement direction and always treat punctuation + // as the start of a word. + if (!StaticPrefs::layout_word_select_stop_at_punctuation()) { + return orig; + } + // Case 1: Example: "a @" + // If aOffset is 2 or 3, orig will be 0, but it should be 2. That is, + // previous word moved back too far. + Accessible* child = GetChildAtOffset(orig); + if (child && child->IsHyperText()) { + // For a multi-word embedded object, previous word correctly goes back + // to the start of the word (the embedded object). Next word (below) + // incorrectly stops after the embedded object in this case, so return + // the already correct result. + // Example: "a x y b", where "x y" is an embedded link + // If aOffset is 4, orig will be 2, which is correct. + // If we get the next word (below), we'll end up returning 3 instead. + return orig; + } + uint32_t next = FindOffset(orig, eDirNext, eSelectWord, eStartWord); + if (next < aOffset) { + // Next word stopped on punctuation. + return next; + } + // case 2: example: "a @@b" + // If aOffset is 2, 3 or 4, orig will be 4, but it should be 2. That is, + // previous word didn't go back far enough. + if (orig == 0) { + return orig; + } + // Walk backwards by offset, getting the next word. + // In the loop, o is unsigned, so o >= 0 will always be true and won't + // prevent us from decrementing at 0. Instead, we check that o doesn't + // wrap around. + for (uint32_t o = orig - 1; o < orig; --o) { + next = FindOffset(o, eDirNext, eSelectWord, eStartWord); + if (next == orig) { + // Next word and previous word were consistent. This + // punctuation problem isn't applicable here. + break; + } + if (next < orig) { + // Next word stopped on punctuation. + return next; + } + } + } else { + // When layout.word_select.stop_at_punctuation is true (the default), + // when positioned on punctuation in the middle of a word, next word skips + // the rest of the word. However, when positioned before the punctuation, + // next word moves just after the punctuation. We want to be consistent + // regardless of starting position and always stop just after the + // punctuation. + // Next word can move too far when positioned on white space too. + // Example: "a b@c" + // If aOffset is 3, orig will be 5, but it should be 4. That is, next word + // moved too far. + if (aOffset == 0) { + return orig; + } + uint32_t prev = FindOffset(orig, eDirPrevious, eSelectWord, eStartWord); + if (prev <= aOffset) { + // orig definitely isn't too far forward. + return orig; + } + // Walk backwards by offset, getting the next word. + // In the loop, o is unsigned, so o >= 0 will always be true and won't + // prevent us from decrementing at 0. Instead, we check that o doesn't + // wrap around. + for (uint32_t o = aOffset - 1; o < aOffset; --o) { + uint32_t next = FindOffset(o, eDirNext, eSelectWord, eStartWord); + if (next > aOffset && next < orig) { + return next; + } + if (next <= aOffset) { + break; + } + } + } + return orig; +} + +uint32_t HyperTextAccessible::FindLineBoundary( + uint32_t aOffset, EWhichLineBoundary aWhichLineBoundary) { + // Note: empty last line doesn't have own frame (a previous line contains '\n' + // character instead) thus when it makes a difference we need to process this + // case separately (otherwise operations are performed on previous line). + switch (aWhichLineBoundary) { + case ePrevLineBegin: { + // Fetch a previous line and move to its start (as arrow up and home keys + // were pressed). + if (IsEmptyLastLineOffset(aOffset)) + return FindOffset(aOffset, eDirPrevious, eSelectBeginLine); + + uint32_t tmpOffset = FindOffset(aOffset, eDirPrevious, eSelectLine); + return FindOffset(tmpOffset, eDirPrevious, eSelectBeginLine); + } + + case ePrevLineEnd: { + if (IsEmptyLastLineOffset(aOffset)) return aOffset - 1; + + // If offset is at first line then return 0 (first line start). + uint32_t tmpOffset = FindOffset(aOffset, eDirPrevious, eSelectBeginLine); + if (tmpOffset == 0) return 0; + + // Otherwise move to end of previous line (as arrow up and end keys were + // pressed). + tmpOffset = FindOffset(aOffset, eDirPrevious, eSelectLine); + return FindOffset(tmpOffset, eDirNext, eSelectEndLine); + } + + case eThisLineBegin: { + if (IsEmptyLastLineOffset(aOffset)) return aOffset; + + // Move to begin of the current line (as home key was pressed). + uint32_t thisLineBeginOffset = + FindOffset(aOffset, eDirPrevious, eSelectBeginLine); + if (IsCharAt(thisLineBeginOffset, kEmbeddedObjectChar)) { + // We landed on an embedded character, don't mess with possible embedded + // line breaks, and assume the offset is correct. + return thisLineBeginOffset; + } + + // Sometimes, there is the possibility layout returned an + // offset smaller than it should. Sanity-check by moving to the end of the + // previous line and see if that has a greater offset. + uint32_t tmpOffset = FindOffset(aOffset, eDirPrevious, eSelectLine); + tmpOffset = FindOffset(tmpOffset, eDirNext, eSelectEndLine); + if (tmpOffset > thisLineBeginOffset && tmpOffset < aOffset) { + // We found a previous line offset. Return the next character after it + // as our start offset if it points to a line end char. + return IsLineEndCharAt(tmpOffset) ? tmpOffset + 1 : tmpOffset; + } + return thisLineBeginOffset; + } + + case eThisLineEnd: + if (IsEmptyLastLineOffset(aOffset)) return aOffset; + + // Move to end of the current line (as end key was pressed). + return FindOffset(aOffset, eDirNext, eSelectEndLine); + + case eNextLineBegin: { + if (IsEmptyLastLineOffset(aOffset)) return aOffset; + + // Move to begin of the next line if any (arrow down and home keys), + // otherwise end of the current line (arrow down only). + uint32_t tmpOffset = FindOffset(aOffset, eDirNext, eSelectLine); + uint32_t characterCount = CharacterCount(); + if (tmpOffset == characterCount) { + return tmpOffset; + } + + // Now, simulate the Home key on the next line to get its real offset. + uint32_t nextLineBeginOffset = + FindOffset(tmpOffset, eDirPrevious, eSelectBeginLine); + // Sometimes, there are line breaks inside embedded characters. If this + // is the case, the cursor is after the line break, but the offset will + // be that of the embedded character, which points to before the line + // break. We definitely want the line break included. + if (IsCharAt(nextLineBeginOffset, kEmbeddedObjectChar)) { + // We can determine if there is a line break by pressing End from + // the queried offset. If there is a line break, the offset will be 1 + // greater, since this line ends with the embed. If there is not, the + // value will be different even if a line break follows right after the + // embed. + uint32_t thisLineEndOffset = + FindOffset(aOffset, eDirNext, eSelectEndLine); + if (thisLineEndOffset == nextLineBeginOffset + 1) { + // If we're querying the offset of the embedded character, we want + // the end offset of the parent line instead. Press End + // once more from the current position, which is after the embed. + if (nextLineBeginOffset == aOffset) { + uint32_t thisLineEndOffset2 = + FindOffset(thisLineEndOffset, eDirNext, eSelectEndLine); + // The above returns an offset exclusive the final line break, so we + // need to add 1 to it to return an inclusive end offset. Make sure + // we don't overshoot if we've started from another embedded + // character that has a line break, or landed on another embedded + // character, or if the result is the very end. + return (thisLineEndOffset2 == characterCount || + (IsCharAt(thisLineEndOffset, kEmbeddedObjectChar) && + thisLineEndOffset2 == thisLineEndOffset + 1) || + IsCharAt(thisLineEndOffset2, kEmbeddedObjectChar)) + ? thisLineEndOffset2 + : thisLineEndOffset2 + 1; + } + + return thisLineEndOffset; + } + return nextLineBeginOffset; + } + + // If the resulting offset is not greater than the offset we started from, + // layout could not find the offset for us. This can happen with certain + // inline-block elements. + if (nextLineBeginOffset <= aOffset) { + // Walk forward from the offset we started from up to tmpOffset, + // stopping after a line end character. + nextLineBeginOffset = aOffset; + while (nextLineBeginOffset < tmpOffset) { + if (IsLineEndCharAt(nextLineBeginOffset)) { + return nextLineBeginOffset + 1; + } + nextLineBeginOffset++; + } + } + + return nextLineBeginOffset; + } + + case eNextLineEnd: { + if (IsEmptyLastLineOffset(aOffset)) return aOffset; + + // Move to next line end (as down arrow and end key were pressed). + uint32_t tmpOffset = FindOffset(aOffset, eDirNext, eSelectLine); + if (tmpOffset == CharacterCount()) return tmpOffset; + + return FindOffset(tmpOffset, eDirNext, eSelectEndLine); + } + } + + return 0; +} + +int32_t HyperTextAccessible::FindParagraphStartOffset(uint32_t aOffset) { + // Because layout often gives us offsets that are incompatible with + // accessibility API requirements, for example when a paragraph contains + // presentational line breaks as found in Google Docs, use the accessibility + // tree to find the start offset instead. + Accessible* child = GetChildAtOffset(aOffset); + if (!child) { + return -1; // Invalid offset + } + + // Use the pivot class to search for the start offset. + Pivot p = Pivot(this); + ParagraphBoundaryRule boundaryRule = ParagraphBoundaryRule( + child, child->IsTextLeaf() ? aOffset - GetChildOffset(child) : 0, + eDirPrevious); + AccessibleOrProxy wrappedChild = AccessibleOrProxy(child); + AccessibleOrProxy match = p.Prev(wrappedChild, boundaryRule, true); + if (match.IsNull() || match.AsAccessible() == this) { + // Found nothing, or pivot found the root of the search, startOffset is 0. + // This will include all relevant text nodes. + return 0; + } + + if (match == wrappedChild) { + // We started out on a boundary. + if (match.Role() == roles::WHITESPACE) { + // We are on a line break boundary, so force pivot to find the previous + // boundary. What we want is any text before this, if any. + match = p.Prev(match, boundaryRule); + if (match.IsNull() || match.AsAccessible() == this) { + // Same as before, we landed on the root, so offset is definitely 0. + return 0; + } + } else if (!match.AsAccessible()->IsTextLeaf()) { + // The match is a block element, which is always a starting point, so + // just return its offset. + return TransformOffset(match.AsAccessible(), 0, false); + } + } + + if (match.AsAccessible()->IsTextLeaf()) { + // ParagraphBoundaryRule only returns a text leaf if it contains a line + // break. We want to stop after that. + return TransformOffset(match.AsAccessible(), + boundaryRule.GetLastMatchTextOffset() + 1, false); + } + + // This is a previous boundary, we don't want to include it itself. + // So, walk forward one accessible, excluding the descendants of this + // boundary if it is a block element. The below call to Next should always be + // initialized with a boundary. + SkipParagraphBoundaryRule goForwardOneRule = SkipParagraphBoundaryRule(match); + match = p.Next(match, goForwardOneRule); + // We already know that the search skipped over at least one accessible, + // so match can't be null. Get its transformed offset. + MOZ_ASSERT(!match.IsNull()); + return TransformOffset(match.AsAccessible(), 0, false); +} + +int32_t HyperTextAccessible::FindParagraphEndOffset(uint32_t aOffset) { + // Because layout often gives us offsets that are incompatible with + // accessibility API requirements, for example when a paragraph contains + // presentational line breaks as found in Google Docs, use the accessibility + // tree to find the end offset instead. + Accessible* child = GetChildAtOffset(aOffset); + if (!child) { + return -1; // invalid offset + } + + // Use the pivot class to search for the end offset. + Pivot p = Pivot(this); + AccessibleOrProxy wrappedChild = AccessibleOrProxy(child); + ParagraphBoundaryRule boundaryRule = ParagraphBoundaryRule( + child, child->IsTextLeaf() ? aOffset - GetChildOffset(child) : 0, + eDirNext, + // In order to encompass all paragraphs inside embedded objects, not just + // the first, we want to skip the anchor's subtree. + /* aSkipAnchorSubtree */ true); + // Search forward for the end offset, including wrappedChild. We don't want + // to go beyond this point if this offset indicates a paragraph boundary. + AccessibleOrProxy match = p.Next(wrappedChild, boundaryRule, true); + if (!match.IsNull()) { + // Found something of relevance, adjust end offset. + Accessible* matchAcc = match.AsAccessible(); + uint32_t matchOffset; + if (matchAcc->IsTextLeaf()) { + // ParagraphBoundaryRule only returns a text leaf if it contains a line + // break. + matchOffset = boundaryRule.GetLastMatchTextOffset() + 1; + } else if (matchAcc->Role() != roles::WHITESPACE && matchAcc != child) { + // We found a block boundary that wasn't our origin. We want to stop + // right on it, not after it, since we don't want to include the content + // of the block. + matchOffset = 0; + } else { + matchOffset = nsAccUtils::TextLength(matchAcc); + } + return TransformOffset(matchAcc, matchOffset, true); + } + + // Didn't find anything, end offset is character count. + return CharacterCount(); +} + +void HyperTextAccessible::TextBeforeOffset(int32_t aOffset, + AccessibleTextBoundary aBoundaryType, + int32_t* aStartOffset, + int32_t* aEndOffset, + nsAString& aText) { + *aStartOffset = *aEndOffset = 0; + aText.Truncate(); + + if (aBoundaryType == nsIAccessibleText::BOUNDARY_PARAGRAPH) { + // Not supported, bail out with empty text. + return; + } + + index_t convertedOffset = ConvertMagicOffset(aOffset); + if (!convertedOffset.IsValid() || convertedOffset > CharacterCount()) { + NS_ERROR("Wrong in offset!"); + return; + } + + uint32_t adjustedOffset = convertedOffset; + if (aOffset == nsIAccessibleText::TEXT_OFFSET_CARET) + adjustedOffset = AdjustCaretOffset(adjustedOffset); + + switch (aBoundaryType) { + case nsIAccessibleText::BOUNDARY_CHAR: + if (convertedOffset != 0) + CharAt(convertedOffset - 1, aText, aStartOffset, aEndOffset); + break; + + case nsIAccessibleText::BOUNDARY_WORD_START: { + // If the offset is a word start (except text length offset) then move + // backward to find a start offset (end offset is the given offset). + // Otherwise move backward twice to find both start and end offsets. + if (adjustedOffset == CharacterCount()) { + *aEndOffset = + FindWordBoundary(adjustedOffset, eDirPrevious, eStartWord); + *aStartOffset = FindWordBoundary(*aEndOffset, eDirPrevious, eStartWord); + } else { + *aStartOffset = + FindWordBoundary(adjustedOffset, eDirPrevious, eStartWord); + *aEndOffset = FindWordBoundary(*aStartOffset, eDirNext, eStartWord); + if (*aEndOffset != static_cast<int32_t>(adjustedOffset)) { + *aEndOffset = *aStartOffset; + *aStartOffset = + FindWordBoundary(*aEndOffset, eDirPrevious, eStartWord); + } + } + TextSubstring(*aStartOffset, *aEndOffset, aText); + break; + } + + case nsIAccessibleText::BOUNDARY_WORD_END: { + // Move word backward twice to find start and end offsets. + *aEndOffset = FindWordBoundary(convertedOffset, eDirPrevious, eEndWord); + *aStartOffset = FindWordBoundary(*aEndOffset, eDirPrevious, eEndWord); + TextSubstring(*aStartOffset, *aEndOffset, aText); + break; + } + + case nsIAccessibleText::BOUNDARY_LINE_START: + *aStartOffset = FindLineBoundary(adjustedOffset, ePrevLineBegin); + *aEndOffset = FindLineBoundary(adjustedOffset, eThisLineBegin); + TextSubstring(*aStartOffset, *aEndOffset, aText); + break; + + case nsIAccessibleText::BOUNDARY_LINE_END: { + *aEndOffset = FindLineBoundary(adjustedOffset, ePrevLineEnd); + int32_t tmpOffset = *aEndOffset; + // Adjust offset if line is wrapped. + if (*aEndOffset != 0 && !IsLineEndCharAt(*aEndOffset)) tmpOffset--; + + *aStartOffset = FindLineBoundary(tmpOffset, ePrevLineEnd); + TextSubstring(*aStartOffset, *aEndOffset, aText); + break; + } + } +} + +void HyperTextAccessible::TextAtOffset(int32_t aOffset, + AccessibleTextBoundary aBoundaryType, + int32_t* aStartOffset, + int32_t* aEndOffset, nsAString& aText) { + *aStartOffset = *aEndOffset = 0; + aText.Truncate(); + + uint32_t adjustedOffset = ConvertMagicOffset(aOffset); + if (adjustedOffset == std::numeric_limits<uint32_t>::max()) { + NS_ERROR("Wrong given offset!"); + return; + } + + switch (aBoundaryType) { + case nsIAccessibleText::BOUNDARY_CHAR: + // Return no char if caret is at the end of wrapped line (case of no line + // end character). Returning a next line char is confusing for AT. + if (aOffset == nsIAccessibleText::TEXT_OFFSET_CARET && + IsCaretAtEndOfLine()) + *aStartOffset = *aEndOffset = adjustedOffset; + else + CharAt(adjustedOffset, aText, aStartOffset, aEndOffset); + break; + + case nsIAccessibleText::BOUNDARY_WORD_START: + if (aOffset == nsIAccessibleText::TEXT_OFFSET_CARET) + adjustedOffset = AdjustCaretOffset(adjustedOffset); + + *aEndOffset = FindWordBoundary(adjustedOffset, eDirNext, eStartWord); + *aStartOffset = FindWordBoundary(*aEndOffset, eDirPrevious, eStartWord); + TextSubstring(*aStartOffset, *aEndOffset, aText); + break; + + case nsIAccessibleText::BOUNDARY_WORD_END: + // Ignore the spec and follow what WebKitGtk does because Orca expects it, + // i.e. return a next word at word end offset of the current word + // (WebKitGtk behavior) instead the current word (AKT spec). + *aEndOffset = FindWordBoundary(adjustedOffset, eDirNext, eEndWord); + *aStartOffset = FindWordBoundary(*aEndOffset, eDirPrevious, eEndWord); + TextSubstring(*aStartOffset, *aEndOffset, aText); + break; + + case nsIAccessibleText::BOUNDARY_LINE_START: + if (aOffset == nsIAccessibleText::TEXT_OFFSET_CARET) + adjustedOffset = AdjustCaretOffset(adjustedOffset); + + *aStartOffset = FindLineBoundary(adjustedOffset, eThisLineBegin); + *aEndOffset = FindLineBoundary(adjustedOffset, eNextLineBegin); + TextSubstring(*aStartOffset, *aEndOffset, aText); + break; + + case nsIAccessibleText::BOUNDARY_LINE_END: + if (aOffset == nsIAccessibleText::TEXT_OFFSET_CARET) + adjustedOffset = AdjustCaretOffset(adjustedOffset); + + // In contrast to word end boundary we follow the spec here. + *aStartOffset = FindLineBoundary(adjustedOffset, ePrevLineEnd); + *aEndOffset = FindLineBoundary(adjustedOffset, eThisLineEnd); + TextSubstring(*aStartOffset, *aEndOffset, aText); + break; + + case nsIAccessibleText::BOUNDARY_PARAGRAPH: { + if (aOffset == nsIAccessibleText::TEXT_OFFSET_CARET) { + adjustedOffset = AdjustCaretOffset(adjustedOffset); + } + + if (IsEmptyLastLineOffset(adjustedOffset)) { + // We are on the last line of a paragraph where there is no text. + // For example, in a textarea where a new line has just been inserted. + // In this case, return offsets for an empty line without text content. + *aStartOffset = *aEndOffset = adjustedOffset; + break; + } + + *aStartOffset = FindParagraphStartOffset(adjustedOffset); + *aEndOffset = FindParagraphEndOffset(adjustedOffset); + TextSubstring(*aStartOffset, *aEndOffset, aText); + break; + } + } +} + +void HyperTextAccessible::TextAfterOffset(int32_t aOffset, + AccessibleTextBoundary aBoundaryType, + int32_t* aStartOffset, + int32_t* aEndOffset, + nsAString& aText) { + *aStartOffset = *aEndOffset = 0; + aText.Truncate(); + + if (aBoundaryType == nsIAccessibleText::BOUNDARY_PARAGRAPH) { + // Not supported, bail out with empty text. + return; + } + + index_t convertedOffset = ConvertMagicOffset(aOffset); + if (!convertedOffset.IsValid() || convertedOffset > CharacterCount()) { + NS_ERROR("Wrong in offset!"); + return; + } + + uint32_t adjustedOffset = convertedOffset; + if (aOffset == nsIAccessibleText::TEXT_OFFSET_CARET) + adjustedOffset = AdjustCaretOffset(adjustedOffset); + + switch (aBoundaryType) { + case nsIAccessibleText::BOUNDARY_CHAR: + // If caret is at the end of wrapped line (case of no line end character) + // then char after the offset is a first char at next line. + if (adjustedOffset >= CharacterCount()) + *aStartOffset = *aEndOffset = CharacterCount(); + else + CharAt(adjustedOffset + 1, aText, aStartOffset, aEndOffset); + break; + + case nsIAccessibleText::BOUNDARY_WORD_START: + // Move word forward twice to find start and end offsets. + *aStartOffset = FindWordBoundary(adjustedOffset, eDirNext, eStartWord); + *aEndOffset = FindWordBoundary(*aStartOffset, eDirNext, eStartWord); + TextSubstring(*aStartOffset, *aEndOffset, aText); + break; + + case nsIAccessibleText::BOUNDARY_WORD_END: + // If the offset is a word end (except 0 offset) then move forward to find + // end offset (start offset is the given offset). Otherwise move forward + // twice to find both start and end offsets. + if (convertedOffset == 0) { + *aStartOffset = FindWordBoundary(convertedOffset, eDirNext, eEndWord); + *aEndOffset = FindWordBoundary(*aStartOffset, eDirNext, eEndWord); + } else { + *aEndOffset = FindWordBoundary(convertedOffset, eDirNext, eEndWord); + *aStartOffset = FindWordBoundary(*aEndOffset, eDirPrevious, eEndWord); + if (*aStartOffset != static_cast<int32_t>(convertedOffset)) { + *aStartOffset = *aEndOffset; + *aEndOffset = FindWordBoundary(*aStartOffset, eDirNext, eEndWord); + } + } + TextSubstring(*aStartOffset, *aEndOffset, aText); + break; + + case nsIAccessibleText::BOUNDARY_LINE_START: + *aStartOffset = FindLineBoundary(adjustedOffset, eNextLineBegin); + *aEndOffset = FindLineBoundary(*aStartOffset, eNextLineBegin); + TextSubstring(*aStartOffset, *aEndOffset, aText); + break; + + case nsIAccessibleText::BOUNDARY_LINE_END: + *aStartOffset = FindLineBoundary(adjustedOffset, eThisLineEnd); + *aEndOffset = FindLineBoundary(adjustedOffset, eNextLineEnd); + TextSubstring(*aStartOffset, *aEndOffset, aText); + break; + } +} + +already_AddRefed<nsIPersistentProperties> HyperTextAccessible::TextAttributes( + bool aIncludeDefAttrs, int32_t aOffset, int32_t* aStartOffset, + int32_t* aEndOffset) { + // 1. Get each attribute and its ranges one after another. + // 2. As we get each new attribute, we pass the current start and end offsets + // as in/out parameters. In other words, as attributes are collected, + // the attribute range itself can only stay the same or get smaller. + + *aStartOffset = *aEndOffset = 0; + index_t offset = ConvertMagicOffset(aOffset); + if (!offset.IsValid() || offset > CharacterCount()) { + NS_ERROR("Wrong in offset!"); + return nullptr; + } + + RefPtr<nsPersistentProperties> attributes = new nsPersistentProperties(); + + Accessible* accAtOffset = GetChildAtOffset(offset); + if (!accAtOffset) { + // Offset 0 is correct offset when accessible has empty text. Include + // default attributes if they were requested, otherwise return empty set. + if (offset == 0) { + if (aIncludeDefAttrs) { + TextAttrsMgr textAttrsMgr(this); + textAttrsMgr.GetAttributes(attributes); + } + return attributes.forget(); + } + return nullptr; + } + + int32_t accAtOffsetIdx = accAtOffset->IndexInParent(); + uint32_t startOffset = GetChildOffset(accAtOffsetIdx); + uint32_t endOffset = GetChildOffset(accAtOffsetIdx + 1); + int32_t offsetInAcc = offset - startOffset; + + TextAttrsMgr textAttrsMgr(this, aIncludeDefAttrs, accAtOffset, + accAtOffsetIdx); + textAttrsMgr.GetAttributes(attributes, &startOffset, &endOffset); + + // Compute spelling attributes on text accessible only. + nsIFrame* offsetFrame = accAtOffset->GetFrame(); + if (offsetFrame && offsetFrame->IsTextFrame()) { + int32_t nodeOffset = 0; + RenderedToContentOffset(offsetFrame, offsetInAcc, &nodeOffset); + + // Set 'misspelled' text attribute. + GetSpellTextAttr(accAtOffset->GetNode(), nodeOffset, &startOffset, + &endOffset, attributes); + } + + *aStartOffset = startOffset; + *aEndOffset = endOffset; + return attributes.forget(); +} + +already_AddRefed<nsIPersistentProperties> +HyperTextAccessible::DefaultTextAttributes() { + RefPtr<nsPersistentProperties> attributes = new nsPersistentProperties(); + + TextAttrsMgr textAttrsMgr(this); + textAttrsMgr.GetAttributes(attributes); + return attributes.forget(); +} + +int32_t HyperTextAccessible::GetLevelInternal() { + if (auto* heading = dom::HTMLHeadingElement::FromNode(mContent)) { + return heading->AccessibilityLevel(); + } + return AccessibleWrap::GetLevelInternal(); +} + +void HyperTextAccessible::SetMathMLXMLRoles( + nsIPersistentProperties* aAttributes) { + // Add MathML xmlroles based on the position inside the parent. + Accessible* parent = Parent(); + if (parent) { + switch (parent->Role()) { + case roles::MATHML_CELL: + case roles::MATHML_ENCLOSED: + case roles::MATHML_ERROR: + case roles::MATHML_MATH: + case roles::MATHML_ROW: + case roles::MATHML_SQUARE_ROOT: + case roles::MATHML_STYLE: + if (Role() == roles::MATHML_OPERATOR) { + // This is an operator inside an <mrow> (or an inferred <mrow>). + // See http://www.w3.org/TR/MathML3/chapter3.html#presm.inferredmrow + // XXX We should probably do something similar for MATHML_FENCED, but + // operators do not appear in the accessible tree. See bug 1175747. + nsIMathMLFrame* mathMLFrame = do_QueryFrame(GetFrame()); + if (mathMLFrame) { + nsEmbellishData embellishData; + mathMLFrame->GetEmbellishData(embellishData); + if (NS_MATHML_EMBELLISH_IS_FENCE(embellishData.flags)) { + if (!PrevSibling()) { + nsAccUtils::SetAccAttr(aAttributes, nsGkAtoms::xmlroles, + nsGkAtoms::open_fence); + } else if (!NextSibling()) { + nsAccUtils::SetAccAttr(aAttributes, nsGkAtoms::xmlroles, + nsGkAtoms::close_fence); + } + } + if (NS_MATHML_EMBELLISH_IS_SEPARATOR(embellishData.flags)) { + nsAccUtils::SetAccAttr(aAttributes, nsGkAtoms::xmlroles, + nsGkAtoms::separator_); + } + } + } + break; + case roles::MATHML_FRACTION: + nsAccUtils::SetAccAttr(aAttributes, nsGkAtoms::xmlroles, + IndexInParent() == 0 ? nsGkAtoms::numerator + : nsGkAtoms::denominator); + break; + case roles::MATHML_ROOT: + nsAccUtils::SetAccAttr( + aAttributes, nsGkAtoms::xmlroles, + IndexInParent() == 0 ? nsGkAtoms::base : nsGkAtoms::root_index); + break; + case roles::MATHML_SUB: + nsAccUtils::SetAccAttr( + aAttributes, nsGkAtoms::xmlroles, + IndexInParent() == 0 ? nsGkAtoms::base : nsGkAtoms::subscript); + break; + case roles::MATHML_SUP: + nsAccUtils::SetAccAttr( + aAttributes, nsGkAtoms::xmlroles, + IndexInParent() == 0 ? nsGkAtoms::base : nsGkAtoms::superscript); + break; + case roles::MATHML_SUB_SUP: { + int32_t index = IndexInParent(); + nsAccUtils::SetAccAttr( + aAttributes, nsGkAtoms::xmlroles, + index == 0 + ? nsGkAtoms::base + : (index == 1 ? nsGkAtoms::subscript : nsGkAtoms::superscript)); + } break; + case roles::MATHML_UNDER: + nsAccUtils::SetAccAttr( + aAttributes, nsGkAtoms::xmlroles, + IndexInParent() == 0 ? nsGkAtoms::base : nsGkAtoms::underscript); + break; + case roles::MATHML_OVER: + nsAccUtils::SetAccAttr( + aAttributes, nsGkAtoms::xmlroles, + IndexInParent() == 0 ? nsGkAtoms::base : nsGkAtoms::overscript); + break; + case roles::MATHML_UNDER_OVER: { + int32_t index = IndexInParent(); + nsAccUtils::SetAccAttr(aAttributes, nsGkAtoms::xmlroles, + index == 0 + ? nsGkAtoms::base + : (index == 1 ? nsGkAtoms::underscript + : nsGkAtoms::overscript)); + } break; + case roles::MATHML_MULTISCRIPTS: { + // Get the <multiscripts> base. + nsIContent* child; + bool baseFound = false; + for (child = parent->GetContent()->GetFirstChild(); child; + child = child->GetNextSibling()) { + if (child->IsMathMLElement()) { + baseFound = true; + break; + } + } + if (baseFound) { + nsIContent* content = GetContent(); + if (child == content) { + // We are the base. + nsAccUtils::SetAccAttr(aAttributes, nsGkAtoms::xmlroles, + nsGkAtoms::base); + } else { + // Browse the list of scripts to find us and determine our type. + bool postscript = true; + bool subscript = true; + for (child = child->GetNextSibling(); child; + child = child->GetNextSibling()) { + if (!child->IsMathMLElement()) continue; + if (child->IsMathMLElement(nsGkAtoms::mprescripts_)) { + postscript = false; + subscript = true; + continue; + } + if (child == content) { + if (postscript) { + nsAccUtils::SetAccAttr(aAttributes, nsGkAtoms::xmlroles, + subscript ? nsGkAtoms::subscript + : nsGkAtoms::superscript); + } else { + nsAccUtils::SetAccAttr(aAttributes, nsGkAtoms::xmlroles, + subscript ? nsGkAtoms::presubscript + : nsGkAtoms::presuperscript); + } + break; + } + subscript = !subscript; + } + } + } + } break; + default: + break; + } + } +} + +already_AddRefed<nsIPersistentProperties> +HyperTextAccessible::NativeAttributes() { + nsCOMPtr<nsIPersistentProperties> attributes = + AccessibleWrap::NativeAttributes(); + + // 'formatting' attribute is deprecated, 'display' attribute should be + // instead. + nsIFrame* frame = GetFrame(); + if (frame && frame->IsBlockFrame()) { + nsAutoString unused; + attributes->SetStringProperty("formatting"_ns, u"block"_ns, unused); + } + + if (FocusMgr()->IsFocused(this)) { + int32_t lineNumber = CaretLineNumber(); + if (lineNumber >= 1) { + nsAutoString strLineNumber; + strLineNumber.AppendInt(lineNumber); + nsAccUtils::SetAccAttr(attributes, nsGkAtoms::lineNumber, strLineNumber); + } + } + + if (HasOwnContent()) { + GetAccService()->MarkupAttributes(mContent, attributes); + if (mContent->IsMathMLElement()) SetMathMLXMLRoles(attributes); + } + + return attributes.forget(); +} + +nsAtom* HyperTextAccessible::LandmarkRole() const { + if (!HasOwnContent()) return nullptr; + + // For the html landmark elements we expose them like we do ARIA landmarks to + // make AT navigation schemes "just work". + if (mContent->IsHTMLElement(nsGkAtoms::nav)) { + return nsGkAtoms::navigation; + } + + if (mContent->IsHTMLElement(nsGkAtoms::aside)) { + return nsGkAtoms::complementary; + } + + if (mContent->IsHTMLElement(nsGkAtoms::main)) { + return nsGkAtoms::main; + } + + return AccessibleWrap::LandmarkRole(); +} + +int32_t HyperTextAccessible::OffsetAtPoint(int32_t aX, int32_t aY, + uint32_t aCoordType) { + nsIFrame* hyperFrame = GetFrame(); + if (!hyperFrame) return -1; + + nsIntPoint coords = + nsAccUtils::ConvertToScreenCoords(aX, aY, aCoordType, this); + + nsPresContext* presContext = mDoc->PresContext(); + nsPoint coordsInAppUnits = + ToAppUnits(coords, presContext->AppUnitsPerDevPixel()); + + nsRect frameScreenRect = hyperFrame->GetScreenRectInAppUnits(); + if (!frameScreenRect.Contains(coordsInAppUnits.x, coordsInAppUnits.y)) + return -1; // Not found + + nsPoint pointInHyperText(coordsInAppUnits.x - frameScreenRect.X(), + coordsInAppUnits.y - frameScreenRect.Y()); + + // Go through the frames to check if each one has the point. + // When one does, add up the character offsets until we have a match + + // We have an point in an accessible child of this, now we need to add up the + // offsets before it to what we already have + int32_t offset = 0; + uint32_t childCount = ChildCount(); + for (uint32_t childIdx = 0; childIdx < childCount; childIdx++) { + Accessible* childAcc = mChildren[childIdx]; + + nsIFrame* primaryFrame = childAcc->GetFrame(); + NS_ENSURE_TRUE(primaryFrame, -1); + + nsIFrame* frame = primaryFrame; + while (frame) { + nsIContent* content = frame->GetContent(); + NS_ENSURE_TRUE(content, -1); + nsPoint pointInFrame = pointInHyperText - frame->GetOffsetTo(hyperFrame); + nsSize frameSize = frame->GetSize(); + if (pointInFrame.x < frameSize.width && + pointInFrame.y < frameSize.height) { + // Finished + if (frame->IsTextFrame()) { + nsIFrame::ContentOffsets contentOffsets = + frame->GetContentOffsetsFromPointExternal( + pointInFrame, nsIFrame::IGNORE_SELECTION_STYLE); + if (contentOffsets.IsNull() || contentOffsets.content != content) { + return -1; // Not found + } + uint32_t addToOffset; + nsresult rv = ContentToRenderedOffset( + primaryFrame, contentOffsets.offset, &addToOffset); + NS_ENSURE_SUCCESS(rv, -1); + offset += addToOffset; + } + return offset; + } + frame = frame->GetNextContinuation(); + } + + offset += nsAccUtils::TextLength(childAcc); + } + + return -1; // Not found +} + +nsIntRect HyperTextAccessible::TextBounds(int32_t aStartOffset, + int32_t aEndOffset, + uint32_t aCoordType) { + index_t startOffset = ConvertMagicOffset(aStartOffset); + index_t endOffset = ConvertMagicOffset(aEndOffset); + if (!startOffset.IsValid() || !endOffset.IsValid() || + startOffset > endOffset || endOffset > CharacterCount()) { + NS_ERROR("Wrong in offset"); + return nsIntRect(); + } + + if (CharacterCount() == 0) { + nsPresContext* presContext = mDoc->PresContext(); + // Empty content, use our own bound to at least get x,y coordinates + nsIFrame* frame = GetFrame(); + if (!frame) { + return nsIntRect(); + } + return frame->GetScreenRectInAppUnits().ToNearestPixels( + presContext->AppUnitsPerDevPixel()); + } + + int32_t childIdx = GetChildIndexAtOffset(startOffset); + if (childIdx == -1) return nsIntRect(); + + nsIntRect bounds; + int32_t prevOffset = GetChildOffset(childIdx); + int32_t offset1 = startOffset - prevOffset; + + while (childIdx < static_cast<int32_t>(ChildCount())) { + nsIFrame* frame = GetChildAt(childIdx++)->GetFrame(); + if (!frame) { + MOZ_ASSERT_UNREACHABLE("No frame for a child!"); + continue; + } + + int32_t nextOffset = GetChildOffset(childIdx); + if (nextOffset >= static_cast<int32_t>(endOffset)) { + bounds.UnionRect( + bounds, GetBoundsInFrame(frame, offset1, endOffset - prevOffset)); + break; + } + + bounds.UnionRect(bounds, + GetBoundsInFrame(frame, offset1, nextOffset - prevOffset)); + + prevOffset = nextOffset; + offset1 = 0; + } + + // This document may have a resolution set, we will need to multiply + // the document-relative coordinates by that value and re-apply the doc's + // screen coordinates. + nsPresContext* presContext = mDoc->PresContext(); + nsIFrame* rootFrame = presContext->PresShell()->GetRootFrame(); + nsIntRect orgRectPixels = + rootFrame->GetScreenRectInAppUnits().ToNearestPixels( + presContext->AppUnitsPerDevPixel()); + bounds.MoveBy(-orgRectPixels.X(), -orgRectPixels.Y()); + bounds.ScaleRoundOut(presContext->PresShell()->GetResolution()); + bounds.MoveBy(orgRectPixels.X(), orgRectPixels.Y()); + + auto boundsX = bounds.X(); + auto boundsY = bounds.Y(); + nsAccUtils::ConvertScreenCoordsTo(&boundsX, &boundsY, aCoordType, this); + bounds.MoveTo(boundsX, boundsY); + return bounds; +} + +already_AddRefed<TextEditor> HyperTextAccessible::GetEditor() const { + if (!mContent->HasFlag(NODE_IS_EDITABLE)) { + // If we're inside an editable container, then return that container's + // editor + Accessible* ancestor = Parent(); + while (ancestor) { + HyperTextAccessible* hyperText = ancestor->AsHyperText(); + if (hyperText) { + // Recursion will stop at container doc because it has its own impl + // of GetEditor() + return hyperText->GetEditor(); + } + + ancestor = ancestor->Parent(); + } + + return nullptr; + } + + nsCOMPtr<nsIDocShell> docShell = nsCoreUtils::GetDocShellFor(mContent); + nsCOMPtr<nsIEditingSession> editingSession; + docShell->GetEditingSession(getter_AddRefs(editingSession)); + if (!editingSession) return nullptr; // No editing session interface + + dom::Document* docNode = mDoc->DocumentNode(); + RefPtr<HTMLEditor> htmlEditor = + editingSession->GetHTMLEditorForWindow(docNode->GetWindow()); + return htmlEditor.forget(); +} + +/** + * =================== Caret & Selection ====================== + */ + +nsresult HyperTextAccessible::SetSelectionRange(int32_t aStartPos, + int32_t aEndPos) { + // Before setting the selection range, we need to ensure that the editor + // is initialized. (See bug 804927.) + // Otherwise, it's possible that lazy editor initialization will override + // the selection we set here and leave the caret at the end of the text. + // By calling GetEditor here, we ensure that editor initialization is + // completed before we set the selection. + RefPtr<TextEditor> textEditor = GetEditor(); + + bool isFocusable = InteractiveState() & states::FOCUSABLE; + + // If accessible is focusable then focus it before setting the selection to + // neglect control's selection changes on focus if any (for example, inputs + // that do select all on focus). + // some input controls + if (isFocusable) TakeFocus(); + + RefPtr<dom::Selection> domSel = DOMSelection(); + NS_ENSURE_STATE(domSel); + + // Set up the selection. + for (int32_t idx = domSel->RangeCount() - 1; idx > 0; idx--) { + RefPtr<nsRange> range{domSel->GetRangeAt(idx)}; + domSel->RemoveRangeAndUnselectFramesAndNotifyListeners(*range, + IgnoreErrors()); + } + SetSelectionBoundsAt(0, aStartPos, aEndPos); + + // Make sure it is visible + domSel->ScrollIntoView(nsISelectionController::SELECTION_FOCUS_REGION, + ScrollAxis(), ScrollAxis(), + dom::Selection::SCROLL_FOR_CARET_MOVE | + dom::Selection::SCROLL_OVERFLOW_HIDDEN); + + // When selection is done, move the focus to the selection if accessible is + // not focusable. That happens when selection is set within hypertext + // accessible. + if (isFocusable) return NS_OK; + + nsFocusManager* DOMFocusManager = nsFocusManager::GetFocusManager(); + if (DOMFocusManager) { + NS_ENSURE_TRUE(mDoc, NS_ERROR_FAILURE); + dom::Document* docNode = mDoc->DocumentNode(); + NS_ENSURE_TRUE(docNode, NS_ERROR_FAILURE); + nsCOMPtr<nsPIDOMWindowOuter> window = docNode->GetWindow(); + RefPtr<dom::Element> result; + DOMFocusManager->MoveFocus( + window, nullptr, nsIFocusManager::MOVEFOCUS_CARET, + nsIFocusManager::FLAG_BYMOVEFOCUS, getter_AddRefs(result)); + } + + return NS_OK; +} + +int32_t HyperTextAccessible::CaretOffset() const { + // Not focused focusable accessible except document accessible doesn't have + // a caret. + if (!IsDoc() && !FocusMgr()->IsFocused(this) && + (InteractiveState() & states::FOCUSABLE)) { + return -1; + } + + // Check cached value. + int32_t caretOffset = -1; + HyperTextAccessible* text = SelectionMgr()->AccessibleWithCaret(&caretOffset); + + // Use cached value if it corresponds to this accessible. + if (caretOffset != -1) { + if (text == this) return caretOffset; + + nsINode* textNode = text->GetNode(); + // Ignore offset if cached accessible isn't a text leaf. + if (nsCoreUtils::IsAncestorOf(GetNode(), textNode)) + return TransformOffset(text, textNode->IsText() ? caretOffset : 0, false); + } + + // No caret if the focused node is not inside this DOM node and this DOM node + // is not inside of focused node. + FocusManager::FocusDisposition focusDisp = + FocusMgr()->IsInOrContainsFocus(this); + if (focusDisp == FocusManager::eNone) return -1; + + // Turn the focus node and offset of the selection into caret hypretext + // offset. + dom::Selection* domSel = DOMSelection(); + NS_ENSURE_TRUE(domSel, -1); + + nsINode* focusNode = domSel->GetFocusNode(); + uint32_t focusOffset = domSel->FocusOffset(); + + // No caret if this DOM node is inside of focused node but the selection's + // focus point is not inside of this DOM node. + if (focusDisp == FocusManager::eContainedByFocus) { + nsINode* resultNode = + nsCoreUtils::GetDOMNodeFromDOMPoint(focusNode, focusOffset); + + nsINode* thisNode = GetNode(); + if (resultNode != thisNode && + !nsCoreUtils::IsAncestorOf(thisNode, resultNode)) + return -1; + } + + return DOMPointToOffset(focusNode, focusOffset); +} + +int32_t HyperTextAccessible::CaretLineNumber() { + // Provide the line number for the caret, relative to the + // currently focused node. Use a 1-based index + RefPtr<nsFrameSelection> frameSelection = FrameSelection(); + if (!frameSelection) return -1; + + dom::Selection* domSel = frameSelection->GetSelection(SelectionType::eNormal); + if (!domSel) return -1; + + nsINode* caretNode = domSel->GetFocusNode(); + if (!caretNode || !caretNode->IsContent()) return -1; + + nsIContent* caretContent = caretNode->AsContent(); + if (!nsCoreUtils::IsAncestorOf(GetNode(), caretContent)) return -1; + + int32_t returnOffsetUnused; + uint32_t caretOffset = domSel->FocusOffset(); + CaretAssociationHint hint = frameSelection->GetHint(); + nsIFrame* caretFrame = frameSelection->GetFrameForNodeOffset( + caretContent, caretOffset, hint, &returnOffsetUnused); + NS_ENSURE_TRUE(caretFrame, -1); + + int32_t lineNumber = 1; + nsAutoLineIterator lineIterForCaret; + nsIContent* hyperTextContent = IsContent() ? mContent.get() : nullptr; + while (caretFrame) { + if (hyperTextContent == caretFrame->GetContent()) { + return lineNumber; // Must be in a single line hyper text, there is no + // line iterator + } + nsContainerFrame* parentFrame = caretFrame->GetParent(); + if (!parentFrame) break; + + // Add lines for the sibling frames before the caret + nsIFrame* sibling = parentFrame->PrincipalChildList().FirstChild(); + while (sibling && sibling != caretFrame) { + nsAutoLineIterator lineIterForSibling = sibling->GetLineIterator(); + if (lineIterForSibling) { + // For the frames before that grab all the lines + int32_t addLines = lineIterForSibling->GetNumLines(); + lineNumber += addLines; + } + sibling = sibling->GetNextSibling(); + } + + // Get the line number relative to the container with lines + if (!lineIterForCaret) { // Add the caret line just once + lineIterForCaret = parentFrame->GetLineIterator(); + if (lineIterForCaret) { + // Ancestor of caret + int32_t addLines = lineIterForCaret->FindLineContaining(caretFrame); + lineNumber += addLines; + } + } + + caretFrame = parentFrame; + } + + MOZ_ASSERT_UNREACHABLE( + "DOM ancestry had this hypertext but frame ancestry didn't"); + return lineNumber; +} + +LayoutDeviceIntRect HyperTextAccessible::GetCaretRect(nsIWidget** aWidget) { + *aWidget = nullptr; + + RefPtr<nsCaret> caret = mDoc->PresShellPtr()->GetCaret(); + NS_ENSURE_TRUE(caret, LayoutDeviceIntRect()); + + bool isVisible = caret->IsVisible(); + if (!isVisible) return LayoutDeviceIntRect(); + + nsRect rect; + nsIFrame* frame = caret->GetGeometry(&rect); + if (!frame || rect.IsEmpty()) return LayoutDeviceIntRect(); + + nsPoint offset; + // Offset from widget origin to the frame origin, which includes chrome + // on the widget. + *aWidget = frame->GetNearestWidget(offset); + NS_ENSURE_TRUE(*aWidget, LayoutDeviceIntRect()); + rect.MoveBy(offset); + + LayoutDeviceIntRect caretRect = LayoutDeviceIntRect::FromUnknownRect( + rect.ToOutsidePixels(frame->PresContext()->AppUnitsPerDevPixel())); + // clang-format off + // ((content screen origin) - (content offset in the widget)) = widget origin on the screen + // clang-format on + caretRect.MoveBy((*aWidget)->WidgetToScreenOffset() - + (*aWidget)->GetClientOffset()); + + // Correct for character size, so that caret always matches the size of + // the character. This is important for font size transitions, and is + // necessary because the Gecko caret uses the previous character's size as + // the user moves forward in the text by character. + nsIntRect charRect = CharBounds( + CaretOffset(), nsIAccessibleCoordinateType::COORDTYPE_SCREEN_RELATIVE); + if (!charRect.IsEmpty()) { + caretRect.SetTopEdge(charRect.Y()); + } + return caretRect; +} + +void HyperTextAccessible::GetSelectionDOMRanges(SelectionType aSelectionType, + nsTArray<nsRange*>* aRanges) { + // Ignore selection if it is not visible. + RefPtr<nsFrameSelection> frameSelection = FrameSelection(); + if (!frameSelection || frameSelection->GetDisplaySelection() <= + nsISelectionController::SELECTION_HIDDEN) + return; + + dom::Selection* domSel = frameSelection->GetSelection(aSelectionType); + if (!domSel) return; + + nsINode* startNode = GetNode(); + + RefPtr<TextEditor> textEditor = GetEditor(); + if (textEditor) { + startNode = textEditor->GetRoot(); + } + + if (!startNode) return; + + uint32_t childCount = startNode->GetChildCount(); + nsresult rv = domSel->GetRangesForIntervalArray(startNode, 0, startNode, + childCount, true, aRanges); + NS_ENSURE_SUCCESS_VOID(rv); + + // Remove collapsed ranges + aRanges->RemoveElementsBy( + [](const auto& range) { return range->Collapsed(); }); +} + +int32_t HyperTextAccessible::SelectionCount() { + nsTArray<nsRange*> ranges; + GetSelectionDOMRanges(SelectionType::eNormal, &ranges); + return ranges.Length(); +} + +bool HyperTextAccessible::SelectionBoundsAt(int32_t aSelectionNum, + int32_t* aStartOffset, + int32_t* aEndOffset) { + *aStartOffset = *aEndOffset = 0; + + nsTArray<nsRange*> ranges; + GetSelectionDOMRanges(SelectionType::eNormal, &ranges); + + uint32_t rangeCount = ranges.Length(); + if (aSelectionNum < 0 || aSelectionNum >= static_cast<int32_t>(rangeCount)) + return false; + + nsRange* range = ranges[aSelectionNum]; + + // Get start and end points. + nsINode* startNode = range->GetStartContainer(); + nsINode* endNode = range->GetEndContainer(); + int32_t startOffset = range->StartOffset(), endOffset = range->EndOffset(); + + // Make sure start is before end, by swapping DOM points. This occurs when + // the user selects backwards in the text. + const Maybe<int32_t> order = + nsContentUtils::ComparePoints(endNode, endOffset, startNode, startOffset); + + if (!order) { + MOZ_ASSERT_UNREACHABLE(); + return false; + } + + if (*order < 0) { + nsINode* tempNode = startNode; + startNode = endNode; + endNode = tempNode; + int32_t tempOffset = startOffset; + startOffset = endOffset; + endOffset = tempOffset; + } + + if (!startNode->IsInclusiveDescendantOf(mContent)) + *aStartOffset = 0; + else + *aStartOffset = DOMPointToOffset(startNode, startOffset); + + if (!endNode->IsInclusiveDescendantOf(mContent)) + *aEndOffset = CharacterCount(); + else + *aEndOffset = DOMPointToOffset(endNode, endOffset, true); + return true; +} + +bool HyperTextAccessible::SetSelectionBoundsAt(int32_t aSelectionNum, + int32_t aStartOffset, + int32_t aEndOffset) { + index_t startOffset = ConvertMagicOffset(aStartOffset); + index_t endOffset = ConvertMagicOffset(aEndOffset); + if (!startOffset.IsValid() || !endOffset.IsValid() || + std::max(startOffset, endOffset) > CharacterCount()) { + NS_ERROR("Wrong in offset"); + return false; + } + + TextRange range(this, this, startOffset, this, endOffset); + return range.SetSelectionAt(aSelectionNum); +} + +bool HyperTextAccessible::RemoveFromSelection(int32_t aSelectionNum) { + RefPtr<dom::Selection> domSel = DOMSelection(); + if (!domSel) return false; + + if (aSelectionNum < 0 || + aSelectionNum >= static_cast<int32_t>(domSel->RangeCount())) + return false; + + const RefPtr<nsRange> range{domSel->GetRangeAt(aSelectionNum)}; + domSel->RemoveRangeAndUnselectFramesAndNotifyListeners(*range, + IgnoreErrors()); + return true; +} + +void HyperTextAccessible::ScrollSubstringTo(int32_t aStartOffset, + int32_t aEndOffset, + uint32_t aScrollType) { + TextRange range(this, this, aStartOffset, this, aEndOffset); + range.ScrollIntoView(aScrollType); +} + +void HyperTextAccessible::ScrollSubstringToPoint(int32_t aStartOffset, + int32_t aEndOffset, + uint32_t aCoordinateType, + int32_t aX, int32_t aY) { + nsIFrame* frame = GetFrame(); + if (!frame) return; + + nsIntPoint coords = + nsAccUtils::ConvertToScreenCoords(aX, aY, aCoordinateType, this); + + RefPtr<nsRange> domRange = nsRange::Create(mContent); + TextRange range(this, this, aStartOffset, this, aEndOffset); + if (!range.AssignDOMRange(domRange)) { + return; + } + + nsPresContext* presContext = frame->PresContext(); + nsPoint coordsInAppUnits = + ToAppUnits(coords, presContext->AppUnitsPerDevPixel()); + + bool initialScrolled = false; + nsIFrame* parentFrame = frame; + while ((parentFrame = parentFrame->GetParent())) { + nsIScrollableFrame* scrollableFrame = do_QueryFrame(parentFrame); + if (scrollableFrame) { + if (!initialScrolled) { + // Scroll substring to the given point. Turn the point into percents + // relative scrollable area to use nsCoreUtils::ScrollSubstringTo. + nsRect frameRect = parentFrame->GetScreenRectInAppUnits(); + nscoord offsetPointX = coordsInAppUnits.x - frameRect.X(); + nscoord offsetPointY = coordsInAppUnits.y - frameRect.Y(); + + nsSize size(parentFrame->GetSize()); + + // avoid divide by zero + size.width = size.width ? size.width : 1; + size.height = size.height ? size.height : 1; + + int16_t hPercent = offsetPointX * 100 / size.width; + int16_t vPercent = offsetPointY * 100 / size.height; + + nsresult rv = nsCoreUtils::ScrollSubstringTo( + frame, domRange, ScrollAxis(vPercent, WhenToScroll::Always), + ScrollAxis(hPercent, WhenToScroll::Always)); + if (NS_FAILED(rv)) return; + + initialScrolled = true; + } else { + // Substring was scrolled to the given point already inside its closest + // scrollable area. If there are nested scrollable areas then make + // sure we scroll lower areas to the given point inside currently + // traversed scrollable area. + nsCoreUtils::ScrollFrameToPoint(parentFrame, frame, coords); + } + } + frame = parentFrame; + } +} + +void HyperTextAccessible::EnclosingRange(a11y::TextRange& aRange) const { + if (IsTextField()) { + aRange.Set(mDoc, const_cast<HyperTextAccessible*>(this), 0, + const_cast<HyperTextAccessible*>(this), CharacterCount()); + } else { + aRange.Set(mDoc, mDoc, 0, mDoc, mDoc->CharacterCount()); + } +} + +void HyperTextAccessible::SelectionRanges( + nsTArray<a11y::TextRange>* aRanges) const { + dom::Selection* sel = DOMSelection(); + if (!sel) { + return; + } + + TextRange::TextRangesFromSelection(sel, aRanges); +} + +void HyperTextAccessible::VisibleRanges( + nsTArray<a11y::TextRange>* aRanges) const {} + +void HyperTextAccessible::RangeByChild(Accessible* aChild, + a11y::TextRange& aRange) const { + HyperTextAccessible* ht = aChild->AsHyperText(); + if (ht) { + aRange.Set(mDoc, ht, 0, ht, ht->CharacterCount()); + return; + } + + Accessible* child = aChild; + Accessible* parent = nullptr; + while ((parent = child->Parent()) && !(ht = parent->AsHyperText())) + child = parent; + + // If no text then return collapsed text range, otherwise return a range + // containing the text enclosed by the given child. + if (ht) { + int32_t childIdx = child->IndexInParent(); + int32_t startOffset = ht->GetChildOffset(childIdx); + int32_t endOffset = + child->IsTextLeaf() ? ht->GetChildOffset(childIdx + 1) : startOffset; + aRange.Set(mDoc, ht, startOffset, ht, endOffset); + } +} + +void HyperTextAccessible::RangeAtPoint(int32_t aX, int32_t aY, + a11y::TextRange& aRange) const { + Accessible* child = mDoc->ChildAtPoint(aX, aY, eDeepestChild); + if (!child) return; + + Accessible* parent = nullptr; + while ((parent = child->Parent()) && !parent->IsHyperText()) child = parent; + + // Return collapsed text range for the point. + if (parent) { + HyperTextAccessible* ht = parent->AsHyperText(); + int32_t offset = ht->GetChildOffset(child); + aRange.Set(mDoc, ht, offset, ht, offset); + } +} + +//////////////////////////////////////////////////////////////////////////////// +// Accessible public + +// Accessible protected +ENameValueFlag HyperTextAccessible::NativeName(nsString& aName) const { + // Check @alt attribute for invalid img elements. + bool hasImgAlt = false; + if (mContent->IsHTMLElement(nsGkAtoms::img)) { + hasImgAlt = mContent->AsElement()->GetAttr(kNameSpaceID_None, + nsGkAtoms::alt, aName); + if (!aName.IsEmpty()) return eNameOK; + } + + ENameValueFlag nameFlag = AccessibleWrap::NativeName(aName); + if (!aName.IsEmpty()) return nameFlag; + + // Get name from title attribute for HTML abbr and acronym elements making it + // a valid name from markup. Otherwise their name isn't picked up by recursive + // name computation algorithm. See NS_OK_NAME_FROM_TOOLTIP. + if (IsAbbreviation() && mContent->AsElement()->GetAttr( + kNameSpaceID_None, nsGkAtoms::title, aName)) + aName.CompressWhitespace(); + + return hasImgAlt ? eNoNameOnPurpose : eNameOK; +} + +void HyperTextAccessible::Shutdown() { + mOffsets.Clear(); + AccessibleWrap::Shutdown(); +} + +bool HyperTextAccessible::RemoveChild(Accessible* aAccessible) { + const int32_t childIndex = aAccessible->IndexInParent(); + if (childIndex < static_cast<int64_t>(mOffsets.Length())) { + mOffsets.RemoveLastElements(mOffsets.Length() - + aAccessible->IndexInParent()); + } + + return AccessibleWrap::RemoveChild(aAccessible); +} + +bool HyperTextAccessible::InsertChildAt(uint32_t aIndex, Accessible* aChild) { + if (aIndex < mOffsets.Length()) { + mOffsets.RemoveLastElements(mOffsets.Length() - aIndex); + } + + return AccessibleWrap::InsertChildAt(aIndex, aChild); +} + +Relation HyperTextAccessible::RelationByType(RelationType aType) const { + Relation rel = Accessible::RelationByType(aType); + + switch (aType) { + case RelationType::NODE_CHILD_OF: + if (HasOwnContent() && mContent->IsMathMLElement()) { + Accessible* parent = Parent(); + if (parent) { + nsIContent* parentContent = parent->GetContent(); + if (parentContent && + parentContent->IsMathMLElement(nsGkAtoms::mroot_)) { + // Add a relation pointing to the parent <mroot>. + rel.AppendTarget(parent); + } + } + } + break; + case RelationType::NODE_PARENT_OF: + if (HasOwnContent() && mContent->IsMathMLElement(nsGkAtoms::mroot_)) { + Accessible* base = GetChildAt(0); + Accessible* index = GetChildAt(1); + if (base && index) { + // Append the <mroot> children in the order index, base. + rel.AppendTarget(index); + rel.AppendTarget(base); + } + } + break; + default: + break; + } + + return rel; +} + +//////////////////////////////////////////////////////////////////////////////// +// HyperTextAccessible public static + +nsresult HyperTextAccessible::ContentToRenderedOffset( + nsIFrame* aFrame, int32_t aContentOffset, uint32_t* aRenderedOffset) const { + if (!aFrame) { + // Current frame not rendered -- this can happen if text is set on + // something with display: none + *aRenderedOffset = 0; + return NS_OK; + } + + if (IsTextField()) { + *aRenderedOffset = aContentOffset; + return NS_OK; + } + + NS_ASSERTION(aFrame->IsTextFrame(), "Need text frame for offset conversion"); + NS_ASSERTION(aFrame->GetPrevContinuation() == nullptr, + "Call on primary frame only"); + + nsIFrame::RenderedText text = + aFrame->GetRenderedText(aContentOffset, aContentOffset + 1, + nsIFrame::TextOffsetType::OffsetsInContentText, + nsIFrame::TrailingWhitespace::DontTrim); + *aRenderedOffset = text.mOffsetWithinNodeRenderedText; + + return NS_OK; +} + +nsresult HyperTextAccessible::RenderedToContentOffset( + nsIFrame* aFrame, uint32_t aRenderedOffset, int32_t* aContentOffset) const { + if (IsTextField()) { + *aContentOffset = aRenderedOffset; + return NS_OK; + } + + *aContentOffset = 0; + NS_ENSURE_TRUE(aFrame, NS_ERROR_FAILURE); + + NS_ASSERTION(aFrame->IsTextFrame(), "Need text frame for offset conversion"); + NS_ASSERTION(aFrame->GetPrevContinuation() == nullptr, + "Call on primary frame only"); + + nsIFrame::RenderedText text = + aFrame->GetRenderedText(aRenderedOffset, aRenderedOffset + 1, + nsIFrame::TextOffsetType::OffsetsInRenderedText, + nsIFrame::TrailingWhitespace::DontTrim); + *aContentOffset = text.mOffsetWithinNodeText; + + return NS_OK; +} + +//////////////////////////////////////////////////////////////////////////////// +// HyperTextAccessible public + +int32_t HyperTextAccessible::GetChildOffset(uint32_t aChildIndex, + bool aInvalidateAfter) const { + if (aChildIndex == 0) { + if (aInvalidateAfter) mOffsets.Clear(); + + return aChildIndex; + } + + int32_t count = mOffsets.Length() - aChildIndex; + if (count > 0) { + if (aInvalidateAfter) mOffsets.RemoveElementsAt(aChildIndex, count); + + return mOffsets[aChildIndex - 1]; + } + + uint32_t lastOffset = + mOffsets.IsEmpty() ? 0 : mOffsets[mOffsets.Length() - 1]; + + while (mOffsets.Length() < aChildIndex) { + Accessible* child = mChildren[mOffsets.Length()]; + lastOffset += nsAccUtils::TextLength(child); + mOffsets.AppendElement(lastOffset); + } + + return mOffsets[aChildIndex - 1]; +} + +int32_t HyperTextAccessible::GetChildIndexAtOffset(uint32_t aOffset) const { + uint32_t lastOffset = 0; + const uint32_t offsetCount = mOffsets.Length(); + + if (offsetCount > 0) { + lastOffset = mOffsets[offsetCount - 1]; + if (aOffset < lastOffset) { + size_t index; + if (BinarySearch(mOffsets, 0, offsetCount, aOffset, &index)) { + return (index < (offsetCount - 1)) ? index + 1 : index; + } + + return (index == offsetCount) ? -1 : index; + } + } + + uint32_t childCount = ChildCount(); + while (mOffsets.Length() < childCount) { + Accessible* child = GetChildAt(mOffsets.Length()); + lastOffset += nsAccUtils::TextLength(child); + mOffsets.AppendElement(lastOffset); + if (aOffset < lastOffset) return mOffsets.Length() - 1; + } + + if (aOffset == lastOffset) return mOffsets.Length() - 1; + + return -1; +} + +//////////////////////////////////////////////////////////////////////////////// +// HyperTextAccessible protected + +nsresult HyperTextAccessible::GetDOMPointByFrameOffset(nsIFrame* aFrame, + int32_t aOffset, + Accessible* aAccessible, + DOMPoint* aPoint) { + NS_ENSURE_ARG(aAccessible); + + if (!aFrame) { + // If the given frame is null then set offset after the DOM node of the + // given accessible. + NS_ASSERTION(!aAccessible->IsDoc(), + "Shouldn't be called on document accessible!"); + + nsIContent* content = aAccessible->GetContent(); + NS_ASSERTION(content, "Shouldn't operate on defunct accessible!"); + + nsIContent* parent = content->GetParent(); + + aPoint->idx = parent->ComputeIndexOf(content) + 1; + aPoint->node = parent; + + } else if (aFrame->IsTextFrame()) { + nsIContent* content = aFrame->GetContent(); + NS_ENSURE_STATE(content); + + nsIFrame* primaryFrame = content->GetPrimaryFrame(); + nsresult rv = + RenderedToContentOffset(primaryFrame, aOffset, &(aPoint->idx)); + NS_ENSURE_SUCCESS(rv, rv); + + aPoint->node = content; + + } else { + nsIContent* content = aFrame->GetContent(); + NS_ENSURE_STATE(content); + + nsIContent* parent = content->GetParent(); + NS_ENSURE_STATE(parent); + + aPoint->idx = parent->ComputeIndexOf(content); + aPoint->node = parent; + } + + return NS_OK; +} + +// HyperTextAccessible +void HyperTextAccessible::GetSpellTextAttr( + nsINode* aNode, int32_t aNodeOffset, uint32_t* aStartOffset, + uint32_t* aEndOffset, nsIPersistentProperties* aAttributes) { + RefPtr<nsFrameSelection> fs = FrameSelection(); + if (!fs) return; + + dom::Selection* domSel = fs->GetSelection(SelectionType::eSpellCheck); + if (!domSel) return; + + int32_t rangeCount = domSel->RangeCount(); + if (rangeCount <= 0) return; + + uint32_t startOffset = 0, endOffset = 0; + for (int32_t idx = 0; idx < rangeCount; idx++) { + const nsRange* range = domSel->GetRangeAt(idx); + if (range->Collapsed()) continue; + + // See if the point comes after the range in which case we must continue in + // case there is another range after this one. + nsINode* endNode = range->GetEndContainer(); + int32_t endNodeOffset = range->EndOffset(); + Maybe<int32_t> order = nsContentUtils::ComparePoints( + aNode, aNodeOffset, endNode, endNodeOffset); + if (NS_WARN_IF(!order)) { + continue; + } + + if (*order >= 0) { + continue; + } + + // At this point our point is either in this range or before it but after + // the previous range. So we check to see if the range starts before the + // point in which case the point is in the missspelled range, otherwise it + // must be before the range and after the previous one if any. + nsINode* startNode = range->GetStartContainer(); + int32_t startNodeOffset = range->StartOffset(); + order = nsContentUtils::ComparePoints(startNode, startNodeOffset, aNode, + aNodeOffset); + if (!order) { + // As (`aNode`, `aNodeOffset`) is comparable to the end of the range, it + // should also be comparable to the range's start. Returning here + // prevents crashes in release builds. + MOZ_ASSERT_UNREACHABLE(); + return; + } + + if (*order <= 0) { + startOffset = DOMPointToOffset(startNode, startNodeOffset); + + endOffset = DOMPointToOffset(endNode, endNodeOffset); + + if (startOffset > *aStartOffset) *aStartOffset = startOffset; + + if (endOffset < *aEndOffset) *aEndOffset = endOffset; + + if (aAttributes) { + nsAccUtils::SetAccAttr(aAttributes, nsGkAtoms::invalid, u"spelling"_ns); + } + + return; + } + + // This range came after the point. + endOffset = DOMPointToOffset(startNode, startNodeOffset); + + if (idx > 0) { + const nsRange* prevRange = domSel->GetRangeAt(idx - 1); + startOffset = DOMPointToOffset(prevRange->GetEndContainer(), + prevRange->EndOffset()); + } + + // The previous range might not be within this accessible. In that case, + // DOMPointToOffset returns length as a fallback. We don't want to use + // that offset if so, hence the startOffset < *aEndOffset check. + if (startOffset > *aStartOffset && startOffset < *aEndOffset) + *aStartOffset = startOffset; + + if (endOffset < *aEndOffset) *aEndOffset = endOffset; + + return; + } + + // We never found a range that ended after the point, therefore we know that + // the point is not in a range, that we do not need to compute an end offset, + // and that we should use the end offset of the last range to compute the + // start offset of the text attribute range. + const nsRange* prevRange = domSel->GetRangeAt(rangeCount - 1); + startOffset = + DOMPointToOffset(prevRange->GetEndContainer(), prevRange->EndOffset()); + + // The previous range might not be within this accessible. In that case, + // DOMPointToOffset returns length as a fallback. We don't want to use + // that offset if so, hence the startOffset < *aEndOffset check. + if (startOffset > *aStartOffset && startOffset < *aEndOffset) + *aStartOffset = startOffset; +} + +bool HyperTextAccessible::IsTextRole() { + const nsRoleMapEntry* roleMapEntry = ARIARoleMap(); + if (roleMapEntry && (roleMapEntry->role == roles::GRAPHIC || + roleMapEntry->role == roles::IMAGE_MAP || + roleMapEntry->role == roles::SLIDER || + roleMapEntry->role == roles::PROGRESSBAR || + roleMapEntry->role == roles::SEPARATOR)) + return false; + + return true; +} diff --git a/accessible/generic/HyperTextAccessible.h b/accessible/generic/HyperTextAccessible.h new file mode 100644 index 0000000000..112587a242 --- /dev/null +++ b/accessible/generic/HyperTextAccessible.h @@ -0,0 +1,561 @@ +/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +#ifndef mozilla_a11y_HyperTextAccessible_h__ +#define mozilla_a11y_HyperTextAccessible_h__ + +#include "AccessibleWrap.h" +#include "nsIAccessibleText.h" +#include "nsIAccessibleTypes.h" +#include "nsIFrame.h" // only for nsSelectionAmount +#include "nsISelectionController.h" +#include "nsDirection.h" +#include "WordMovementType.h" + +class nsFrameSelection; +class nsIFrame; +class nsRange; +class nsIWidget; + +namespace mozilla { +class TextEditor; +namespace dom { +class Selection; +} + +namespace a11y { + +class TextRange; + +struct DOMPoint { + DOMPoint() : node(nullptr), idx(0) {} + DOMPoint(nsINode* aNode, int32_t aIdx) : node(aNode), idx(aIdx) {} + + nsINode* node; + int32_t idx; +}; + +// This character marks where in the text returned via Text interface, +// that embedded object characters exist +const char16_t kEmbeddedObjectChar = 0xfffc; +const char16_t kImaginaryEmbeddedObjectChar = ' '; +const char16_t kForcedNewLineChar = '\n'; + +/** + * Special Accessible that knows how contain both text and embedded objects + */ +class HyperTextAccessible : public AccessibleWrap { + public: + HyperTextAccessible(nsIContent* aContent, DocAccessible* aDoc); + + NS_INLINE_DECL_REFCOUNTING_INHERITED(HyperTextAccessible, AccessibleWrap) + + // Accessible + virtual nsAtom* LandmarkRole() const override; + virtual int32_t GetLevelInternal() override; + virtual already_AddRefed<nsIPersistentProperties> NativeAttributes() override; + virtual mozilla::a11y::role NativeRole() const override; + virtual uint64_t NativeState() const override; + + virtual void Shutdown() override; + virtual bool RemoveChild(Accessible* aAccessible) override; + virtual bool InsertChildAt(uint32_t aIndex, Accessible* aChild) override; + virtual Relation RelationByType(RelationType aType) const override; + + // HyperTextAccessible (static helper method) + + // Convert content offset to rendered text offset + nsresult ContentToRenderedOffset(nsIFrame* aFrame, int32_t aContentOffset, + uint32_t* aRenderedOffset) const; + + // Convert rendered text offset to content offset + nsresult RenderedToContentOffset(nsIFrame* aFrame, uint32_t aRenderedOffset, + int32_t* aContentOffset) const; + + ////////////////////////////////////////////////////////////////////////////// + // HyperLinkAccessible + + /** + * Return link count within this hypertext accessible. + */ + uint32_t LinkCount() { return EmbeddedChildCount(); } + + /** + * Return link accessible at the given index. + */ + Accessible* LinkAt(uint32_t aIndex) { return GetEmbeddedChildAt(aIndex); } + + /** + * Return index for the given link accessible. + */ + int32_t LinkIndexOf(Accessible* aLink) { + return GetIndexOfEmbeddedChild(aLink); + } + + /** + * Return link accessible at the given text offset. + */ + int32_t LinkIndexAtOffset(uint32_t aOffset) { + Accessible* child = GetChildAtOffset(aOffset); + return child ? LinkIndexOf(child) : -1; + } + + ////////////////////////////////////////////////////////////////////////////// + // HyperTextAccessible: DOM point to text offset conversions. + + /** + * Turn a DOM point (node and offset) into a character offset of this + * hypertext. Will look for closest match when the DOM node does not have + * an accessible object associated with it. Will return an offset for the end + * of the string if the node is not found. + * + * @param aNode [in] the node to look for + * @param aNodeOffset [in] the offset to look for + * if -1 just look directly for the node + * if >=0 and aNode is text, this represents a char + * offset if >=0 and aNode is not text, this represents a child node offset + * @param aIsEndOffset [in] if true, then then this offset is not inclusive. + * The character indicated by the offset returned is at [offset - 1]. This + * means if the passed-in offset is really in a descendant, then the offset + * returned will come just after the relevant embedded object characer. If + * false, then the offset is inclusive. The character indicated by the offset + * returned is at [offset]. If the passed-in offset in inside a descendant, + * then the returned offset will be on the relevant embedded object char. + */ + uint32_t DOMPointToOffset(nsINode* aNode, int32_t aNodeOffset, + bool aIsEndOffset = false) const; + + /** + * Transform the given a11y point into the offset relative this hypertext. + */ + uint32_t TransformOffset(Accessible* aDescendant, uint32_t aOffset, + bool aIsEndOffset) const; + + /** + * Convert the given offset into DOM point. + * + * If offset is at text leaf then DOM point is (text node, offsetInTextNode), + * if before embedded object then (parent node, indexInParent), if after then + * (parent node, indexInParent + 1). + */ + DOMPoint OffsetToDOMPoint(int32_t aOffset) const; + + /** + * Return true if the used ARIA role (if any) allows the hypertext accessible + * to expose text interfaces. + */ + bool IsTextRole(); + + ////////////////////////////////////////////////////////////////////////////// + // TextAccessible + + /** + * Return character count within the hypertext accessible. + */ + uint32_t CharacterCount() const { return GetChildOffset(ChildCount()); } + + /** + * Get a character at the given offset (don't support magic offsets). + */ + bool CharAt(int32_t aOffset, nsAString& aChar, + int32_t* aStartOffset = nullptr, int32_t* aEndOffset = nullptr) { + NS_ASSERTION(!aStartOffset == !aEndOffset, + "Offsets should be both defined or both undefined!"); + + int32_t childIdx = GetChildIndexAtOffset(aOffset); + if (childIdx == -1) return false; + + Accessible* child = GetChildAt(childIdx); + child->AppendTextTo(aChar, aOffset - GetChildOffset(childIdx), 1); + + if (aStartOffset && aEndOffset) { + *aStartOffset = aOffset; + *aEndOffset = aOffset + aChar.Length(); + } + return true; + } + + char16_t CharAt(int32_t aOffset) { + nsAutoString charAtOffset; + CharAt(aOffset, charAtOffset); + return charAtOffset.CharAt(0); + } + + /** + * Return true if char at the given offset equals to given char. + */ + bool IsCharAt(int32_t aOffset, char16_t aChar) { + return CharAt(aOffset) == aChar; + } + + /** + * Return true if terminal char is at the given offset. + */ + bool IsLineEndCharAt(int32_t aOffset) { return IsCharAt(aOffset, '\n'); } + + /** + * Return text between given offsets. + */ + void TextSubstring(int32_t aStartOffset, int32_t aEndOffset, + nsAString& aText); + + /** + * Return text before/at/after the given offset corresponding to + * the boundary type. + */ + void TextBeforeOffset(int32_t aOffset, AccessibleTextBoundary aBoundaryType, + int32_t* aStartOffset, int32_t* aEndOffset, + nsAString& aText); + void TextAtOffset(int32_t aOffset, AccessibleTextBoundary aBoundaryType, + int32_t* aStartOffset, int32_t* aEndOffset, + nsAString& aText); + void TextAfterOffset(int32_t aOffset, AccessibleTextBoundary aBoundaryType, + int32_t* aStartOffset, int32_t* aEndOffset, + nsAString& aText); + + /** + * Return text attributes for the given text range. + */ + already_AddRefed<nsIPersistentProperties> TextAttributes( + bool aIncludeDefAttrs, int32_t aOffset, int32_t* aStartOffset, + int32_t* aEndOffset); + + /** + * Return text attributes applied to the accessible. + */ + already_AddRefed<nsIPersistentProperties> DefaultTextAttributes(); + + /** + * Return text offset of the given child accessible within hypertext + * accessible. + * + * @param aChild [in] accessible child to get text offset for + * @param aInvalidateAfter [in, optional] indicates whether invalidate + * cached offsets for next siblings of the child + */ + int32_t GetChildOffset(const Accessible* aChild, + bool aInvalidateAfter = false) const { + int32_t index = GetIndexOf(aChild); + return index == -1 ? -1 : GetChildOffset(index, aInvalidateAfter); + } + + /** + * Return text offset for the child accessible index. + */ + int32_t GetChildOffset(uint32_t aChildIndex, + bool aInvalidateAfter = false) const; + + /** + * Return child accessible at the given text offset. + * + * @param aOffset [in] the given text offset + */ + int32_t GetChildIndexAtOffset(uint32_t aOffset) const; + + /** + * Return child accessible at the given text offset. + * + * @param aOffset [in] the given text offset + */ + Accessible* GetChildAtOffset(uint32_t aOffset) const { + return GetChildAt(GetChildIndexAtOffset(aOffset)); + } + + /** + * Return true if the given offset/range is valid. + */ + bool IsValidOffset(int32_t aOffset); + bool IsValidRange(int32_t aStartOffset, int32_t aEndOffset); + + /** + * Return an offset at the given point. + */ + int32_t OffsetAtPoint(int32_t aX, int32_t aY, uint32_t aCoordType); + + /** + * Return a rect of the given text range relative given coordinate system. + */ + nsIntRect TextBounds( + int32_t aStartOffset, int32_t aEndOffset, + uint32_t aCoordType = + nsIAccessibleCoordinateType::COORDTYPE_SCREEN_RELATIVE); + + /** + * Return a rect for character at given offset relative given coordinate + * system. + */ + nsIntRect CharBounds(int32_t aOffset, uint32_t aCoordType) { + int32_t endOffset = aOffset == static_cast<int32_t>(CharacterCount()) + ? aOffset + : aOffset + 1; + return TextBounds(aOffset, endOffset, aCoordType); + } + + /** + * Get/set caret offset, if no caret then -1. + */ + int32_t CaretOffset() const; + void SetCaretOffset(int32_t aOffset); + + /** + * Provide the line number for the caret. + * @return 1-based index for the line number with the caret + */ + int32_t CaretLineNumber(); + + /** + * Return the caret rect and the widget containing the caret within this + * text accessible. + * + * @param [out] the widget containing the caret + * @return the caret rect + */ + mozilla::LayoutDeviceIntRect GetCaretRect(nsIWidget** aWidget); + + /** + * Return selected regions count within the accessible. + */ + int32_t SelectionCount(); + + /** + * Return the start and end offset of the specified selection. + */ + bool SelectionBoundsAt(int32_t aSelectionNum, int32_t* aStartOffset, + int32_t* aEndOffset); + + /* + * Changes the start and end offset of the specified selection. + * @return true if succeeded + */ + // TODO: annotate this with `MOZ_CAN_RUN_SCRIPT` instead. + MOZ_CAN_RUN_SCRIPT_BOUNDARY bool SetSelectionBoundsAt(int32_t aSelectionNum, + int32_t aStartOffset, + int32_t aEndOffset); + + /** + * Adds a selection bounded by the specified offsets. + * @return true if succeeded + */ + bool AddToSelection(int32_t aStartOffset, int32_t aEndOffset); + + /* + * Removes the specified selection. + * @return true if succeeded + */ + // TODO: annotate this with `MOZ_CAN_RUN_SCRIPT` instead. + MOZ_CAN_RUN_SCRIPT_BOUNDARY bool RemoveFromSelection(int32_t aSelectionNum); + + /** + * Scroll the given text range into view. + */ + void ScrollSubstringTo(int32_t aStartOffset, int32_t aEndOffset, + uint32_t aScrollType); + + /** + * Scroll the given text range to the given point. + */ + void ScrollSubstringToPoint(int32_t aStartOffset, int32_t aEndOffset, + uint32_t aCoordinateType, int32_t aX, int32_t aY); + + /** + * Return a range that encloses the text control or the document this + * accessible belongs to. + */ + void EnclosingRange(TextRange& aRange) const; + + /** + * Return an array of disjoint ranges for selected text within the text + * control or the document this accessible belongs to. + */ + void SelectionRanges(nsTArray<TextRange>* aRanges) const; + + /** + * Return an array of disjoint ranges of visible text within the text control + * or the document this accessible belongs to. + */ + void VisibleRanges(nsTArray<TextRange>* aRanges) const; + + /** + * Return a range containing the given accessible. + */ + void RangeByChild(Accessible* aChild, TextRange& aRange) const; + + /** + * Return a range containing an accessible at the given point. + */ + void RangeAtPoint(int32_t aX, int32_t aY, TextRange& aRange) const; + + ////////////////////////////////////////////////////////////////////////////// + // EditableTextAccessible + + MOZ_CAN_RUN_SCRIPT_BOUNDARY void ReplaceText(const nsAString& aText); + MOZ_CAN_RUN_SCRIPT_BOUNDARY void InsertText(const nsAString& aText, + int32_t aPosition); + void CopyText(int32_t aStartPos, int32_t aEndPos); + MOZ_CAN_RUN_SCRIPT_BOUNDARY void CutText(int32_t aStartPos, int32_t aEndPos); + MOZ_CAN_RUN_SCRIPT_BOUNDARY void DeleteText(int32_t aStartPos, + int32_t aEndPos); + MOZ_CAN_RUN_SCRIPT + void PasteText(int32_t aPosition); + + /** + * Return the editor associated with the accessible. + * The result may be either TextEditor or HTMLEditor. + */ + virtual already_AddRefed<TextEditor> GetEditor() const; + + /** + * Return DOM selection object for the accessible. + */ + dom::Selection* DOMSelection() const; + + protected: + virtual ~HyperTextAccessible() {} + + // Accessible + virtual ENameValueFlag NativeName(nsString& aName) const override; + + // HyperTextAccessible + + /** + * Transform magic offset into text offset. + */ + index_t ConvertMagicOffset(int32_t aOffset) const; + + /** + * Adjust an offset the caret stays at to get a text by line boundary. + */ + uint32_t AdjustCaretOffset(uint32_t aOffset) const; + + /** + * Return true if caret is at end of line. + */ + bool IsCaretAtEndOfLine() const; + + /** + * Return true if the given offset points to terminal empty line if any. + */ + bool IsEmptyLastLineOffset(int32_t aOffset) { + return aOffset == static_cast<int32_t>(CharacterCount()) && + IsLineEndCharAt(aOffset - 1); + } + + /** + * Return an offset of the found word boundary. + */ + uint32_t FindWordBoundary(uint32_t aOffset, nsDirection aDirection, + EWordMovementType aWordMovementType); + + /** + * Used to get begin/end of previous/this/next line. Note: end of line + * is an offset right before '\n' character if any, the offset is right after + * '\n' character is begin of line. In case of wrap word breaks these offsets + * are equal. + */ + enum EWhichLineBoundary { + ePrevLineBegin, + ePrevLineEnd, + eThisLineBegin, + eThisLineEnd, + eNextLineBegin, + eNextLineEnd + }; + + /** + * Return an offset for requested line boundary. See constants above. + */ + uint32_t FindLineBoundary(uint32_t aOffset, + EWhichLineBoundary aWhichLineBoundary); + + /** + * Find the start offset for a paragraph , taking into account + * inner block elements and line breaks. + */ + int32_t FindParagraphStartOffset(uint32_t aOffset); + + /** + * Find the end offset for a paragraph , taking into account + * inner block elements and line breaks. + */ + int32_t FindParagraphEndOffset(uint32_t aOffset); + + /** + * Return an offset corresponding to the given direction and selection amount + * relative the given offset. A helper used to find word or line boundaries. + */ + uint32_t FindOffset(uint32_t aOffset, nsDirection aDirection, + nsSelectionAmount aAmount, + EWordMovementType aWordMovementType = eDefaultBehavior); + + /** + * Return the boundaries of the substring in case of textual frame or + * frame boundaries in case of non textual frame, offsets are ignored. + */ + nsIntRect GetBoundsInFrame(nsIFrame* aFrame, uint32_t aStartRenderedOffset, + uint32_t aEndRenderedOffset); + + // Selection helpers + + /** + * Return frame selection object for the accessible. + */ + already_AddRefed<nsFrameSelection> FrameSelection() const; + + /** + * Return selection ranges within the accessible subtree. + */ + void GetSelectionDOMRanges(SelectionType aSelectionType, + nsTArray<nsRange*>* aRanges); + + // TODO: annotate this with `MOZ_CAN_RUN_SCRIPT` instead. + MOZ_CAN_RUN_SCRIPT_BOUNDARY nsresult SetSelectionRange(int32_t aStartPos, + int32_t aEndPos); + + // Helpers + nsresult GetDOMPointByFrameOffset(nsIFrame* aFrame, int32_t aOffset, + Accessible* aAccessible, + mozilla::a11y::DOMPoint* aPoint); + + /** + * Set 'misspelled' text attribute and return range offsets where the + * attibute is stretched. If the text is not misspelled at the given offset + * then we expose only range offsets where text is not misspelled. The method + * is used by TextAttributes() method. + * + * @param aIncludeDefAttrs [in] points whether text attributes having default + * values of attributes should be included + * @param aSourceNode [in] the node we start to traverse from + * @param aStartOffset [in, out] the start offset + * @param aEndOffset [in, out] the end offset + * @param aAttributes [out, optional] result attributes + */ + void GetSpellTextAttr(nsINode* aNode, int32_t aNodeOffset, + uint32_t* aStartOffset, uint32_t* aEndOffset, + nsIPersistentProperties* aAttributes); + + /** + * Set xml-roles attributes for MathML elements. + * @param aAttributes + */ + void SetMathMLXMLRoles(nsIPersistentProperties* aAttributes); + + private: + /** + * End text offsets array. + */ + mutable nsTArray<uint32_t> mOffsets; +}; + +//////////////////////////////////////////////////////////////////////////////// +// Accessible downcasting method + +inline HyperTextAccessible* Accessible::AsHyperText() { + return IsHyperText() ? static_cast<HyperTextAccessible*>(this) : nullptr; +} + +} // namespace a11y +} // namespace mozilla + +#endif diff --git a/accessible/generic/ImageAccessible.cpp b/accessible/generic/ImageAccessible.cpp new file mode 100644 index 0000000000..3611f52f6f --- /dev/null +++ b/accessible/generic/ImageAccessible.cpp @@ -0,0 +1,201 @@ +/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +#include "ImageAccessible.h" + +#include "nsAccUtils.h" +#include "Role.h" +#include "AccIterator.h" +#include "States.h" + +#include "imgIContainer.h" +#include "imgIRequest.h" +#include "nsGenericHTMLElement.h" +#include "mozilla/dom/BrowsingContext.h" +#include "mozilla/dom/Document.h" +#include "nsContentUtils.h" +#include "nsIImageLoadingContent.h" +#include "nsIPersistentProperties2.h" +#include "nsPIDOMWindow.h" +#include "nsIURI.h" + +using namespace mozilla::a11y; + +//////////////////////////////////////////////////////////////////////////////// +// ImageAccessible +//////////////////////////////////////////////////////////////////////////////// + +ImageAccessible::ImageAccessible(nsIContent* aContent, DocAccessible* aDoc) + : LinkableAccessible(aContent, aDoc) { + mType = eImageType; +} + +ImageAccessible::~ImageAccessible() {} + +//////////////////////////////////////////////////////////////////////////////// +// Accessible public + +uint64_t ImageAccessible::NativeState() const { + // The state is a bitfield, get our inherited state, then logically OR it with + // states::ANIMATED if this is an animated image. + + uint64_t state = LinkableAccessible::NativeState(); + + nsCOMPtr<nsIImageLoadingContent> content(do_QueryInterface(mContent)); + nsCOMPtr<imgIRequest> imageRequest; + + if (content) + content->GetRequest(nsIImageLoadingContent::CURRENT_REQUEST, + getter_AddRefs(imageRequest)); + + if (imageRequest) { + nsCOMPtr<imgIContainer> imgContainer; + imageRequest->GetImage(getter_AddRefs(imgContainer)); + if (imgContainer) { + bool animated = false; + imgContainer->GetAnimated(&animated); + if (animated) { + state |= states::ANIMATED; + } + } + + nsIFrame* frame = GetFrame(); + MOZ_ASSERT(!frame || frame->AccessibleType() == eImageType || + frame->AccessibleType() == a11y::eHTMLImageMapType); + if (frame && !(frame->GetStateBits() & IMAGE_SIZECONSTRAINED)) { + uint32_t status = imgIRequest::STATUS_NONE; + imageRequest->GetImageStatus(&status); + if (!(status & imgIRequest::STATUS_SIZE_AVAILABLE)) { + // The size of this image hasn't been constrained and we haven't loaded + // enough of the image to know its size yet. This means it currently + // has 0 width and height. + state |= states::INVISIBLE; + } + } + } + + return state; +} + +ENameValueFlag ImageAccessible::NativeName(nsString& aName) const { + bool hasAltAttrib = + mContent->AsElement()->GetAttr(kNameSpaceID_None, nsGkAtoms::alt, aName); + if (!aName.IsEmpty()) return eNameOK; + + ENameValueFlag nameFlag = Accessible::NativeName(aName); + if (!aName.IsEmpty()) return nameFlag; + + // No accessible name but empty 'alt' attribute is present. If further name + // computation algorithm doesn't provide non empty name then it means + // an empty 'alt' attribute was used to indicate a decorative image (see + // Accessible::Name() method for details). + return hasAltAttrib ? eNoNameOnPurpose : eNameOK; +} + +role ImageAccessible::NativeRole() const { return roles::GRAPHIC; } + +//////////////////////////////////////////////////////////////////////////////// +// Accessible + +uint8_t ImageAccessible::ActionCount() const { + uint8_t actionCount = LinkableAccessible::ActionCount(); + return HasLongDesc() ? actionCount + 1 : actionCount; +} + +void ImageAccessible::ActionNameAt(uint8_t aIndex, nsAString& aName) { + aName.Truncate(); + if (IsLongDescIndex(aIndex) && HasLongDesc()) + aName.AssignLiteral("showlongdesc"); + else + LinkableAccessible::ActionNameAt(aIndex, aName); +} + +bool ImageAccessible::DoAction(uint8_t aIndex) const { + // Get the long description uri and open in a new window. + if (!IsLongDescIndex(aIndex)) return LinkableAccessible::DoAction(aIndex); + + nsCOMPtr<nsIURI> uri = GetLongDescURI(); + if (!uri) return false; + + nsAutoCString utf8spec; + uri->GetSpec(utf8spec); + NS_ConvertUTF8toUTF16 spec(utf8spec); + + dom::Document* document = mContent->OwnerDoc(); + nsCOMPtr<nsPIDOMWindowOuter> piWindow = document->GetWindow(); + if (!piWindow) return false; + + RefPtr<mozilla::dom::BrowsingContext> tmp; + return NS_SUCCEEDED(piWindow->Open(spec, u""_ns, u""_ns, + /* aLoadInfo = */ nullptr, + /* aForceNoOpener = */ false, + getter_AddRefs(tmp))); +} + +//////////////////////////////////////////////////////////////////////////////// +// ImageAccessible + +nsIntPoint ImageAccessible::Position(uint32_t aCoordType) { + nsIntPoint point = Bounds().TopLeft(); + nsAccUtils::ConvertScreenCoordsTo(&point.x, &point.y, aCoordType, this); + return point; +} + +nsIntSize ImageAccessible::Size() { return Bounds().Size(); } + +// Accessible +already_AddRefed<nsIPersistentProperties> ImageAccessible::NativeAttributes() { + nsCOMPtr<nsIPersistentProperties> attributes = + LinkableAccessible::NativeAttributes(); + + nsAutoString src; + mContent->AsElement()->GetAttr(kNameSpaceID_None, nsGkAtoms::src, src); + if (!src.IsEmpty()) nsAccUtils::SetAccAttr(attributes, nsGkAtoms::src, src); + + return attributes.forget(); +} + +//////////////////////////////////////////////////////////////////////////////// +// Private methods + +already_AddRefed<nsIURI> ImageAccessible::GetLongDescURI() const { + if (mContent->AsElement()->HasAttr(kNameSpaceID_None, nsGkAtoms::longdesc)) { + // To check if longdesc contains an invalid url. + nsAutoString longdesc; + mContent->AsElement()->GetAttr(kNameSpaceID_None, nsGkAtoms::longdesc, + longdesc); + if (longdesc.FindChar(' ') != -1 || longdesc.FindChar('\t') != -1 || + longdesc.FindChar('\r') != -1 || longdesc.FindChar('\n') != -1) { + return nullptr; + } + nsCOMPtr<nsIURI> uri; + nsContentUtils::NewURIWithDocumentCharset(getter_AddRefs(uri), longdesc, + mContent->OwnerDoc(), + mContent->GetBaseURI()); + return uri.forget(); + } + + DocAccessible* document = Document(); + if (document) { + IDRefsIterator iter(document, mContent, nsGkAtoms::aria_describedby); + while (nsIContent* target = iter.NextElem()) { + if ((target->IsHTMLElement(nsGkAtoms::a) || + target->IsHTMLElement(nsGkAtoms::area)) && + target->AsElement()->HasAttr(kNameSpaceID_None, nsGkAtoms::href)) { + nsGenericHTMLElement* element = nsGenericHTMLElement::FromNode(target); + + nsCOMPtr<nsIURI> uri; + element->GetURIAttr(nsGkAtoms::href, nullptr, getter_AddRefs(uri)); + return uri.forget(); + } + } + } + + return nullptr; +} + +bool ImageAccessible::IsLongDescIndex(uint8_t aIndex) const { + return aIndex == LinkableAccessible::ActionCount(); +} diff --git a/accessible/generic/ImageAccessible.h b/accessible/generic/ImageAccessible.h new file mode 100644 index 0000000000..05ef2a0f00 --- /dev/null +++ b/accessible/generic/ImageAccessible.h @@ -0,0 +1,81 @@ +/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +#ifndef mozilla_a11y_ImageAccessible_h__ +#define mozilla_a11y_ImageAccessible_h__ + +#include "BaseAccessibles.h" + +namespace mozilla { +namespace a11y { + +/* Accessible for supporting images + * supports: + * - gets name, role + * - support basic state + */ +class ImageAccessible : public LinkableAccessible { + public: + ImageAccessible(nsIContent* aContent, DocAccessible* aDoc); + + // Accessible + virtual a11y::role NativeRole() const override; + virtual uint64_t NativeState() const override; + virtual already_AddRefed<nsIPersistentProperties> NativeAttributes() override; + + // ActionAccessible + virtual uint8_t ActionCount() const override; + virtual void ActionNameAt(uint8_t aIndex, nsAString& aName) override; + virtual bool DoAction(uint8_t aIndex) const override; + + // ImageAccessible + nsIntPoint Position(uint32_t aCoordType); + nsIntSize Size(); + + protected: + virtual ~ImageAccessible(); + + // Accessible + virtual ENameValueFlag NativeName(nsString& aName) const override; + + private: + /** + * Return whether the element has a longdesc URI. + */ + bool HasLongDesc() const { + nsCOMPtr<nsIURI> uri = GetLongDescURI(); + return uri; + } + + /** + * Return an URI for showlongdesc action if any. + */ + already_AddRefed<nsIURI> GetLongDescURI() const; + + /** + * Used by ActionNameAt and DoAction to ensure the index for opening the + * longdesc URL is valid. + * It is always assumed that the highest possible index opens the longdesc. + * This doesn't check that there is actually a longdesc, just that the index + * would be correct if there was one. + * + * @param aIndex The 0-based index to be tested. + * + * @returns true if index is valid for longdesc action. + */ + inline bool IsLongDescIndex(uint8_t aIndex) const; +}; + +//////////////////////////////////////////////////////////////////////////////// +// Accessible downcasting method + +inline ImageAccessible* Accessible::AsImage() { + return IsImage() ? static_cast<ImageAccessible*>(this) : nullptr; +} + +} // namespace a11y +} // namespace mozilla + +#endif diff --git a/accessible/generic/OuterDocAccessible.cpp b/accessible/generic/OuterDocAccessible.cpp new file mode 100644 index 0000000000..02d4e08a1e --- /dev/null +++ b/accessible/generic/OuterDocAccessible.cpp @@ -0,0 +1,244 @@ +/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +#include "OuterDocAccessible.h" + +#include "Accessible-inl.h" +#include "nsAccUtils.h" +#include "DocAccessible-inl.h" +#include "mozilla/a11y/DocAccessibleChild.h" +#include "mozilla/a11y/DocAccessibleParent.h" +#if defined(XP_WIN) +# include "mozilla/a11y/ProxyWrappers.h" +#endif +#include "mozilla/dom/BrowserBridgeChild.h" +#include "mozilla/dom/BrowserParent.h" +#include "Role.h" +#include "States.h" + +#ifdef A11Y_LOG +# include "Logging.h" +#endif + +using namespace mozilla; +using namespace mozilla::a11y; + +//////////////////////////////////////////////////////////////////////////////// +// OuterDocAccessible +//////////////////////////////////////////////////////////////////////////////// + +OuterDocAccessible::OuterDocAccessible(nsIContent* aContent, + DocAccessible* aDoc) + : AccessibleWrap(aContent, aDoc) { + mType = eOuterDocType; + +#ifdef XP_WIN + if (DocAccessibleParent* remoteDoc = RemoteChildDoc()) { + remoteDoc->SendParentCOMProxy(this); + } +#endif + + if (IPCAccessibilityActive()) { + auto bridge = dom::BrowserBridgeChild::GetFrom(aContent); + if (bridge) { + // This is an iframe which will be rendered in another process. + SendEmbedderAccessible(bridge); + } + } + + // Request document accessible for the content document to make sure it's + // created. It will appended to outerdoc accessible children asynchronously. + dom::Document* outerDoc = mContent->GetUncomposedDoc(); + if (outerDoc) { + dom::Document* innerDoc = outerDoc->GetSubDocumentFor(mContent); + if (innerDoc) GetAccService()->GetDocAccessible(innerDoc); + } +} + +OuterDocAccessible::~OuterDocAccessible() {} + +void OuterDocAccessible::SendEmbedderAccessible( + dom::BrowserBridgeChild* aBridge) { + MOZ_ASSERT(mDoc); + DocAccessibleChild* ipcDoc = mDoc->IPCDoc(); + if (ipcDoc) { + uint64_t id = reinterpret_cast<uintptr_t>(UniqueID()); +#if defined(XP_WIN) + ipcDoc->SetEmbedderOnBridge(aBridge, id); +#else + aBridge->SendSetEmbedderAccessible(ipcDoc, id); +#endif + } +} + +//////////////////////////////////////////////////////////////////////////////// +// Accessible public (DON'T add methods here) + +role OuterDocAccessible::NativeRole() const { return roles::INTERNAL_FRAME; } + +Accessible* OuterDocAccessible::ChildAtPoint(int32_t aX, int32_t aY, + EWhichChildAtPoint aWhichChild) { + nsIntRect docRect = Bounds(); + if (!docRect.Contains(aX, aY)) return nullptr; + + // Always return the inner doc as direct child accessible unless bounds + // outside of it. + Accessible* child = GetChildAt(0); + NS_ENSURE_TRUE(child, nullptr); + + if (aWhichChild == eDeepestChild) { +#if defined(XP_WIN) + // On Windows, OuterDocAccessible::GetChildAt can return a proxy wrapper + // for a remote document. These aren't real Accessibles and + // shouldn't be returned except to the Windows a11y code (which doesn't use + // eDeepestChild). Calling ChildAtPoint on these will crash! + return nullptr; +#else + return child->ChildAtPoint(aX, aY, eDeepestChild); +#endif // defined(XP_WIN) + } + return child; +} + +//////////////////////////////////////////////////////////////////////////////// +// Accessible public + +void OuterDocAccessible::Shutdown() { +#ifdef A11Y_LOG + if (logging::IsEnabled(logging::eDocDestroy)) logging::OuterDocDestroy(this); +#endif + + Accessible* child = mChildren.SafeElementAt(0, nullptr); + if (child) { +#ifdef A11Y_LOG + if (logging::IsEnabled(logging::eDocDestroy)) { + logging::DocDestroy("outerdoc's child document rebind is scheduled", + child->AsDoc()->DocumentNode()); + } +#endif + RemoveChild(child); + + // XXX: sometimes outerdoc accessible is shutdown because of layout style + // change however the presshell of underlying document isn't destroyed and + // the document doesn't get pagehide events. Schedule a document rebind + // to its parent document. Otherwise a document accessible may be lost if + // its outerdoc has being recreated (see bug 862863 for details). + if (!mDoc->IsDefunct()) { + MOZ_ASSERT(!child->IsDefunct(), + "Attempt to reattach shutdown document accessible"); + if (!child->IsDefunct()) { + mDoc->BindChildDocument(child->AsDoc()); + } + } + } + + AccessibleWrap::Shutdown(); +} + +bool OuterDocAccessible::InsertChildAt(uint32_t aIdx, Accessible* aAccessible) { + MOZ_RELEASE_ASSERT(aAccessible->IsDoc(), + "OuterDocAccessible can have a document child only!"); + + // We keep showing the old document for a bit after creating the new one, + // and while building the new DOM and frame tree. That's done on purpose + // to avoid weird flashes of default background color. + // The old viewer will be destroyed after the new one is created. + // For a11y, it should be safe to shut down the old document now. + if (mChildren.Length()) mChildren[0]->Shutdown(); + + if (!AccessibleWrap::InsertChildAt(0, aAccessible)) return false; + +#ifdef A11Y_LOG + if (logging::IsEnabled(logging::eDocCreate)) { + logging::DocCreate("append document to outerdoc", + aAccessible->AsDoc()->DocumentNode()); + logging::Address("outerdoc", this); + } +#endif + + return true; +} + +bool OuterDocAccessible::RemoveChild(Accessible* aAccessible) { + Accessible* child = mChildren.SafeElementAt(0, nullptr); + MOZ_ASSERT(child == aAccessible, "Wrong child to remove!"); + if (child != aAccessible) { + return false; + } + +#ifdef A11Y_LOG + if (logging::IsEnabled(logging::eDocDestroy)) { + logging::DocDestroy("remove document from outerdoc", + child->AsDoc()->DocumentNode(), child->AsDoc()); + logging::Address("outerdoc", this); + } +#endif + + bool wasRemoved = AccessibleWrap::RemoveChild(child); + + NS_ASSERTION(!mChildren.Length(), + "This child document of outerdoc accessible wasn't removed!"); + + return wasRemoved; +} + +bool OuterDocAccessible::IsAcceptableChild(nsIContent* aEl) const { + // outer document accessible doesn't not participate in ordinal tree + // mutations. + return false; +} + +#if defined(XP_WIN) + +Accessible* OuterDocAccessible::RemoteChildDocAccessible() const { + ProxyAccessible* docProxy = RemoteChildDoc(); + if (docProxy) { + // We're in the parent process, but we're embedding a remote document. + return WrapperFor(docProxy); + } + + if (IPCAccessibilityActive()) { + auto bridge = dom::BrowserBridgeChild::GetFrom(mContent); + if (bridge) { + // We're an iframe in a content process and we're embedding a remote + // document (in another content process). The COM proxy for the embedded + // document accessible was sent to us from the parent via PBrowserBridge. + return bridge->GetEmbeddedDocAccessible(); + } + } + + return nullptr; +} + +// On Windows e10s, since we don't cache in the chrome process, these next two +// functions must be implemented so that we properly cross the chrome-to-content +// boundary when traversing. + +uint32_t OuterDocAccessible::ChildCount() const { + uint32_t result = mChildren.Length(); + if (!result && RemoteChildDocAccessible()) { + result = 1; + } + return result; +} + +Accessible* OuterDocAccessible::GetChildAt(uint32_t aIndex) const { + Accessible* result = AccessibleWrap::GetChildAt(aIndex); + if (result || aIndex) { + return result; + } + // If we are asking for child 0 and GetChildAt doesn't return anything, try + // to get the remote child doc and return that instead. + return RemoteChildDocAccessible(); +} + +#endif // defined(XP_WIN) + +DocAccessibleParent* OuterDocAccessible::RemoteChildDoc() const { + dom::BrowserParent* tab = dom::BrowserParent::GetFrom(GetContent()); + if (!tab) return nullptr; + + return tab->GetTopLevelDocAccessible(); +} diff --git a/accessible/generic/OuterDocAccessible.h b/accessible/generic/OuterDocAccessible.h new file mode 100644 index 0000000000..ec49d03247 --- /dev/null +++ b/accessible/generic/OuterDocAccessible.h @@ -0,0 +1,76 @@ +/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +#ifndef MOZILLA_A11Y_OUTERDOCACCESSIBLE_H_ +#define MOZILLA_A11Y_OUTERDOCACCESSIBLE_H_ + +#include "AccessibleWrap.h" + +namespace mozilla { + +namespace dom { +class BrowserBridgeChild; +} + +namespace a11y { +class DocAccessibleParent; + +/** + * Used for <browser>, <frame>, <iframe>, <page> or editor> elements. + * + * In these variable names, "outer" relates to the OuterDocAccessible as + * opposed to the DocAccessibleWrap which is "inner". The outer node is + * a something like tags listed above, whereas the inner node corresponds to + * the inner document root. + */ + +class OuterDocAccessible final : public AccessibleWrap { + public: + OuterDocAccessible(nsIContent* aContent, DocAccessible* aDoc); + + NS_INLINE_DECL_REFCOUNTING_INHERITED(OuterDocAccessible, AccessibleWrap) + + DocAccessibleParent* RemoteChildDoc() const; +#if defined(XP_WIN) + Accessible* RemoteChildDocAccessible() const; +#endif + + /** + * For iframes in a content process which will be rendered in another content + * process, tell the parent process about this OuterDocAccessible + * so it can link the trees together when the embedded document is added. + * Note that an OuterDocAccessible can be created before the + * BrowserBridgeChild or vice versa. Therefore, this must be conditionally + * called when either of these is created. + */ + void SendEmbedderAccessible(dom::BrowserBridgeChild* aBridge); + + // Accessible + virtual void Shutdown() override; + virtual mozilla::a11y::role NativeRole() const override; + virtual Accessible* ChildAtPoint(int32_t aX, int32_t aY, + EWhichChildAtPoint aWhichChild) override; + + virtual bool InsertChildAt(uint32_t aIdx, Accessible* aChild) override; + virtual bool RemoveChild(Accessible* aAccessible) override; + virtual bool IsAcceptableChild(nsIContent* aEl) const override; + +#if defined(XP_WIN) + virtual uint32_t ChildCount() const override; + virtual Accessible* GetChildAt(uint32_t aIndex) const override; +#endif // defined(XP_WIN) + + protected: + virtual ~OuterDocAccessible() override; +}; + +inline OuterDocAccessible* Accessible::AsOuterDoc() { + return IsOuterDoc() ? static_cast<OuterDocAccessible*>(this) : nullptr; +} + +} // namespace a11y +} // namespace mozilla + +#endif diff --git a/accessible/generic/RootAccessible.cpp b/accessible/generic/RootAccessible.cpp new file mode 100644 index 0000000000..adcd02f480 --- /dev/null +++ b/accessible/generic/RootAccessible.cpp @@ -0,0 +1,711 @@ +/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +#include "RootAccessible.h" + +#include "mozilla/ArrayUtils.h" +#include "mozilla/PresShell.h" // for nsAccUtils::GetDocAccessibleFor() + +#define CreateEvent CreateEventA + +#include "Accessible-inl.h" +#include "DocAccessible-inl.h" +#include "mozilla/a11y/DocAccessibleParent.h" +#include "nsAccessibilityService.h" +#include "nsAccUtils.h" +#include "nsCoreUtils.h" +#include "nsEventShell.h" +#include "Relation.h" +#include "Role.h" +#include "States.h" +#ifdef MOZ_XUL +# include "XULTreeAccessible.h" +#endif + +#include "mozilla/dom/BindingUtils.h" +#include "mozilla/dom/CustomEvent.h" +#include "mozilla/dom/Element.h" +#include "mozilla/dom/ScriptSettings.h" +#include "mozilla/dom/BrowserHost.h" + +#include "nsIDocShellTreeOwner.h" +#include "mozilla/dom/Event.h" +#include "mozilla/dom/EventTarget.h" +#include "nsIDOMXULMultSelectCntrlEl.h" +#include "mozilla/dom/Document.h" +#include "nsIInterfaceRequestorUtils.h" +#include "nsIPropertyBag2.h" +#include "nsPIDOMWindow.h" +#include "nsIWebBrowserChrome.h" +#include "nsReadableUtils.h" +#include "nsFocusManager.h" +#include "nsGlobalWindow.h" + +#ifdef MOZ_XUL +# include "nsIAppWindow.h" +#endif + +using namespace mozilla; +using namespace mozilla::a11y; +using namespace mozilla::dom; + +//////////////////////////////////////////////////////////////////////////////// +// nsISupports + +NS_IMPL_ISUPPORTS_INHERITED(RootAccessible, DocAccessible, nsIDOMEventListener) + +//////////////////////////////////////////////////////////////////////////////// +// Constructor/destructor + +RootAccessible::RootAccessible(Document* aDocument, PresShell* aPresShell) + : DocAccessibleWrap(aDocument, aPresShell) { + mType = eRootType; +} + +RootAccessible::~RootAccessible() {} + +//////////////////////////////////////////////////////////////////////////////// +// Accessible + +ENameValueFlag RootAccessible::Name(nsString& aName) const { + aName.Truncate(); + + if (ARIARoleMap()) { + Accessible::Name(aName); + if (!aName.IsEmpty()) return eNameOK; + } + + mDocumentNode->GetTitle(aName); + return eNameOK; +} + +// RootAccessible protected member +#ifdef MOZ_XUL +uint32_t RootAccessible::GetChromeFlags() const { + // Return the flag set for the top level window as defined + // by nsIWebBrowserChrome::CHROME_WINDOW_[FLAGNAME] + // Not simple: nsIAppWindow is not just a QI from nsIDOMWindow + nsCOMPtr<nsIDocShell> docShell = nsCoreUtils::GetDocShellFor(mDocumentNode); + NS_ENSURE_TRUE(docShell, 0); + nsCOMPtr<nsIDocShellTreeOwner> treeOwner; + docShell->GetTreeOwner(getter_AddRefs(treeOwner)); + NS_ENSURE_TRUE(treeOwner, 0); + nsCOMPtr<nsIAppWindow> appWin(do_GetInterface(treeOwner)); + if (!appWin) { + return 0; + } + uint32_t chromeFlags; + appWin->GetChromeFlags(&chromeFlags); + return chromeFlags; +} +#endif + +uint64_t RootAccessible::NativeState() const { + uint64_t state = DocAccessibleWrap::NativeState(); + if (state & states::DEFUNCT) return state; + +#ifdef MOZ_XUL + uint32_t chromeFlags = GetChromeFlags(); + if (chromeFlags & nsIWebBrowserChrome::CHROME_WINDOW_RESIZE) + state |= states::SIZEABLE; + // If it has a titlebar it's movable + // XXX unless it's minimized or maximized, but not sure + // how to detect that + if (chromeFlags & nsIWebBrowserChrome::CHROME_TITLEBAR) + state |= states::MOVEABLE; + if (chromeFlags & nsIWebBrowserChrome::CHROME_MODAL) state |= states::MODAL; +#endif + + nsFocusManager* fm = nsFocusManager::GetFocusManager(); + if (fm && fm->GetActiveWindow() == mDocumentNode->GetWindow()) + state |= states::ACTIVE; + + return state; +} + +const char* const kEventTypes[] = { +#ifdef DEBUG_DRAGDROPSTART + // Capture mouse over events and fire fake DRAGDROPSTART event to simplify + // debugging a11y objects with event viewers. + "mouseover", +#endif + // Fired when list or tree selection changes. + "select", + // Fired when value changes immediately, wether or not focused changed. + "ValueChange", "AlertActive", "TreeRowCountChanged", "TreeInvalidated", + // add ourself as a OpenStateChange listener (custom event fired in + // tree.xml) + "OpenStateChange", + // add ourself as a CheckboxStateChange listener (custom event fired in + // HTMLInputElement.cpp) + "CheckboxStateChange", + // add ourself as a RadioStateChange Listener (custom event fired in in + // HTMLInputElement.cpp & radio.js) + "RadioStateChange", "popupshown", "popuphiding", "DOMMenuInactive", + "DOMMenuItemActive", "DOMMenuItemInactive", "DOMMenuBarActive", + "DOMMenuBarInactive", "scroll"}; + +nsresult RootAccessible::AddEventListeners() { + // EventTarget interface allows to register event listeners to + // receive untrusted events (synthetic events generated by untrusted code). + // For example, XBL bindings implementations for elements that are hosted in + // non chrome document fire untrusted events. + // We must use the window's parent target in order to receive events from + // iframes and shadow DOM; e.g. ValueChange events from a <select> in an + // iframe or shadow DOM. The root document itself doesn't receive these. + nsPIDOMWindowOuter* window = mDocumentNode->GetWindow(); + nsCOMPtr<EventTarget> nstarget = window ? window->GetParentTarget() : nullptr; + + if (nstarget) { + for (const char *const *e = kEventTypes, *const *e_end = + ArrayEnd(kEventTypes); + e < e_end; ++e) { + nsresult rv = nstarget->AddEventListener(NS_ConvertASCIItoUTF16(*e), this, + true, true); + NS_ENSURE_SUCCESS(rv, rv); + } + } + + return DocAccessible::AddEventListeners(); +} + +nsresult RootAccessible::RemoveEventListeners() { + nsPIDOMWindowOuter* window = mDocumentNode->GetWindow(); + nsCOMPtr<EventTarget> target = window ? window->GetParentTarget() : nullptr; + if (target) { + for (const char *const *e = kEventTypes, *const *e_end = + ArrayEnd(kEventTypes); + e < e_end; ++e) { + target->RemoveEventListener(NS_ConvertASCIItoUTF16(*e), this, true); + } + } + + // Do this before removing clearing caret accessible, so that it can use + // shutdown the caret accessible's selection listener + DocAccessible::RemoveEventListeners(); + return NS_OK; +} + +//////////////////////////////////////////////////////////////////////////////// +// public + +void RootAccessible::DocumentActivated(DocAccessible* aDocument) {} + +//////////////////////////////////////////////////////////////////////////////// +// nsIDOMEventListener + +NS_IMETHODIMP +RootAccessible::HandleEvent(Event* aDOMEvent) { + MOZ_ASSERT(aDOMEvent); + if (IsDefunct()) { + // Even though we've been shut down, RemoveEventListeners might not have + // removed the event handlers on the window's parent target if GetWindow + // returned null, so we might still get events here in this case. We should + // just ignore these events. + return NS_OK; + } + + nsCOMPtr<nsINode> origTargetNode = + do_QueryInterface(aDOMEvent->GetOriginalTarget()); + if (!origTargetNode) return NS_OK; + +#ifdef A11Y_LOG + if (logging::IsEnabled(logging::eDOMEvents)) { + nsAutoString eventType; + aDOMEvent->GetType(eventType); + logging::DOMEvent("handled", origTargetNode, eventType); + } +#endif + + DocAccessible* document = + GetAccService()->GetDocAccessible(origTargetNode->OwnerDoc()); + + if (document) { + nsAutoString eventType; + aDOMEvent->GetType(eventType); + if (eventType.EqualsLiteral("scroll")) { + // We don't put this in the notification queue for 2 reasons: + // 1. We will flood the queue with repetitive events. + // 2. Since this doesn't necessarily touch layout, we are not + // guaranteed to have a WillRefresh tick any time soon. + document->HandleScroll(origTargetNode); + } else { + // Root accessible exists longer than any of its descendant documents so + // that we are guaranteed notification is processed before root accessible + // is destroyed. + // For shadow DOM, GetOriginalTarget on the Event returns null if we + // process the event async, so we must pass the target node as well. + document->HandleNotification<RootAccessible, Event, nsINode>( + this, &RootAccessible::ProcessDOMEvent, aDOMEvent, origTargetNode); + } + } + + return NS_OK; +} + +// RootAccessible protected +void RootAccessible::ProcessDOMEvent(Event* aDOMEvent, nsINode* aTarget) { + MOZ_ASSERT(aDOMEvent); + MOZ_ASSERT(aTarget); + + nsAutoString eventType; + aDOMEvent->GetType(eventType); + +#ifdef A11Y_LOG + if (logging::IsEnabled(logging::eDOMEvents)) + logging::DOMEvent("processed", aTarget, eventType); +#endif + + if (eventType.EqualsLiteral("popuphiding")) { + HandlePopupHidingEvent(aTarget); + return; + } + + DocAccessible* targetDocument = + GetAccService()->GetDocAccessible(aTarget->OwnerDoc()); + if (!targetDocument) { + // Document has ceased to exist. + return; + } + + if (eventType.EqualsLiteral("popupshown") && + aTarget->IsXULElement(nsGkAtoms::tooltip)) { + targetDocument->ContentInserted(aTarget->AsContent(), + aTarget->GetNextSibling()); + return; + } + + Accessible* accessible = targetDocument->GetAccessibleOrContainer(aTarget); + if (!accessible) return; + +#ifdef MOZ_XUL + XULTreeAccessible* treeAcc = accessible->AsXULTree(); + if (treeAcc) { + if (eventType.EqualsLiteral("TreeRowCountChanged")) { + HandleTreeRowCountChangedEvent(aDOMEvent, treeAcc); + return; + } + + if (eventType.EqualsLiteral("TreeInvalidated")) { + HandleTreeInvalidatedEvent(aDOMEvent, treeAcc); + return; + } + } +#endif + + if (eventType.EqualsLiteral("RadioStateChange")) { + uint64_t state = accessible->State(); + bool isEnabled = (state & (states::CHECKED | states::SELECTED)) != 0; + + if (accessible->NeedsDOMUIEvent()) { + RefPtr<AccEvent> accEvent = + new AccStateChangeEvent(accessible, states::CHECKED, isEnabled); + nsEventShell::FireEvent(accEvent); + } + + if (isEnabled) { + FocusMgr()->ActiveItemChanged(accessible); +#ifdef A11Y_LOG + if (logging::IsEnabled(logging::eFocus)) + logging::ActiveItemChangeCausedBy("RadioStateChange", accessible); +#endif + } + + return; + } + + if (eventType.EqualsLiteral("CheckboxStateChange")) { + if (accessible->NeedsDOMUIEvent()) { + uint64_t state = accessible->State(); + bool isEnabled = !!(state & states::CHECKED); + + RefPtr<AccEvent> accEvent = + new AccStateChangeEvent(accessible, states::CHECKED, isEnabled); + nsEventShell::FireEvent(accEvent); + } + return; + } + + Accessible* treeItemAcc = nullptr; +#ifdef MOZ_XUL + // If it's a tree element, need the currently selected item. + if (treeAcc) { + treeItemAcc = accessible->CurrentItem(); + if (treeItemAcc) accessible = treeItemAcc; + } + + if (treeItemAcc && eventType.EqualsLiteral("OpenStateChange")) { + uint64_t state = accessible->State(); + bool isEnabled = (state & states::EXPANDED) != 0; + + RefPtr<AccEvent> accEvent = + new AccStateChangeEvent(accessible, states::EXPANDED, isEnabled); + nsEventShell::FireEvent(accEvent); + return; + } + + nsINode* targetNode = accessible->GetNode(); + if (treeItemAcc && eventType.EqualsLiteral("select")) { + // XXX: We shouldn't be based on DOM select event which doesn't provide us + // any context info. We should integrate into nsTreeSelection instead. + // If multiselect tree, we should fire selectionadd or selection removed + if (FocusMgr()->HasDOMFocus(targetNode)) { + nsCOMPtr<nsIDOMXULMultiSelectControlElement> multiSel = + targetNode->AsElement()->AsXULMultiSelectControl(); + if (!multiSel) { + // This shouldn't be possible. All XUL trees should have + // nsIDOMXULMultiSelectControlElement, and the tree is focused, so it + // shouldn't be dying. Nevertheless, this sometimes happens in the wild + // (bug 1597043). + MOZ_ASSERT_UNREACHABLE( + "XUL tree doesn't have nsIDOMXULMultiSelectControlElement"); + return; + } + nsAutoString selType; + multiSel->GetSelType(selType); + if (selType.IsEmpty() || !selType.EqualsLiteral("single")) { + // XXX: We need to fire EVENT_SELECTION_ADD and EVENT_SELECTION_REMOVE + // for each tree item. Perhaps each tree item will need to cache its + // selection state and fire an event after a DOM "select" event when + // that state changes. XULTreeAccessible::UpdateTreeSelection(); + nsEventShell::FireEvent(nsIAccessibleEvent::EVENT_SELECTION_WITHIN, + accessible); + return; + } + + RefPtr<AccSelChangeEvent> selChangeEvent = new AccSelChangeEvent( + treeAcc, treeItemAcc, AccSelChangeEvent::eSelectionAdd); + nsEventShell::FireEvent(selChangeEvent); + return; + } + } else +#endif + if (eventType.EqualsLiteral("AlertActive")) { + nsEventShell::FireEvent(nsIAccessibleEvent::EVENT_ALERT, accessible); + } else if (eventType.EqualsLiteral("popupshown")) { + HandlePopupShownEvent(accessible); + } else if (eventType.EqualsLiteral("DOMMenuInactive")) { + if (accessible->Role() == roles::MENUPOPUP) { + nsEventShell::FireEvent(nsIAccessibleEvent::EVENT_MENUPOPUP_END, + accessible); + } + } else if (eventType.EqualsLiteral("DOMMenuItemActive")) { + FocusMgr()->ActiveItemChanged(accessible); +#ifdef A11Y_LOG + if (logging::IsEnabled(logging::eFocus)) + logging::ActiveItemChangeCausedBy("DOMMenuItemActive", accessible); +#endif + } else if (eventType.EqualsLiteral("DOMMenuItemInactive")) { + // Process DOMMenuItemInactive event for autocomplete only because this is + // unique widget that may acquire focus from autocomplete popup while popup + // stays open and has no active item. In case of XUL tree autocomplete + // popup this event is fired for tree accessible. + Accessible* widget = + accessible->IsWidget() ? accessible : accessible->ContainerWidget(); + if (widget && widget->IsAutoCompletePopup()) { + FocusMgr()->ActiveItemChanged(nullptr); +#ifdef A11Y_LOG + if (logging::IsEnabled(logging::eFocus)) + logging::ActiveItemChangeCausedBy("DOMMenuItemInactive", accessible); +#endif + } + } else if (eventType.EqualsLiteral( + "DOMMenuBarActive")) { // Always from user input + nsEventShell::FireEvent(nsIAccessibleEvent::EVENT_MENU_START, accessible, + eFromUserInput); + + // Notify of active item change when menubar gets active and if it has + // current item. This is a case of mouseover (set current menuitem) and + // mouse click (activate the menubar). If menubar doesn't have current item + // (can be a case of menubar activation from keyboard) then ignore this + // notification because later we'll receive DOMMenuItemActive event after + // current menuitem is set. + Accessible* activeItem = accessible->CurrentItem(); + if (activeItem) { + FocusMgr()->ActiveItemChanged(activeItem); +#ifdef A11Y_LOG + if (logging::IsEnabled(logging::eFocus)) + logging::ActiveItemChangeCausedBy("DOMMenuBarActive", accessible); +#endif + } + } else if (eventType.EqualsLiteral( + "DOMMenuBarInactive")) { // Always from user input + nsEventShell::FireEvent(nsIAccessibleEvent::EVENT_MENU_END, accessible, + eFromUserInput); + + FocusMgr()->ActiveItemChanged(nullptr); +#ifdef A11Y_LOG + if (logging::IsEnabled(logging::eFocus)) + logging::ActiveItemChangeCausedBy("DOMMenuBarInactive", accessible); +#endif + } else if (accessible->NeedsDOMUIEvent() && + eventType.EqualsLiteral("ValueChange")) { + uint32_t event = accessible->HasNumericValue() + ? nsIAccessibleEvent::EVENT_VALUE_CHANGE + : nsIAccessibleEvent::EVENT_TEXT_VALUE_CHANGE; + targetDocument->FireDelayedEvent(event, accessible); + } +#ifdef DEBUG_DRAGDROPSTART + else if (eventType.EqualsLiteral("mouseover")) { + nsEventShell::FireEvent(nsIAccessibleEvent::EVENT_DRAGDROP_START, + accessible); + } +#endif +} + +//////////////////////////////////////////////////////////////////////////////// +// Accessible + +void RootAccessible::Shutdown() { + // Called manually or by Accessible::LastRelease() + if (HasShutdown()) { + return; + } + DocAccessibleWrap::Shutdown(); +} + +Relation RootAccessible::RelationByType(RelationType aType) const { + if (!mDocumentNode || aType != RelationType::EMBEDS) { + return DocAccessibleWrap::RelationByType(aType); + } + + if (nsIDocShell* docShell = mDocumentNode->GetDocShell()) { + nsCOMPtr<nsIDocShellTreeOwner> owner; + docShell->GetTreeOwner(getter_AddRefs(owner)); + if (owner) { + nsCOMPtr<nsIDocShellTreeItem> contentShell; + owner->GetPrimaryContentShell(getter_AddRefs(contentShell)); + if (contentShell) { + return Relation(nsAccUtils::GetDocAccessibleFor(contentShell)); + } + } + } + + return Relation(); +} + +//////////////////////////////////////////////////////////////////////////////// +// Protected members + +void RootAccessible::HandlePopupShownEvent(Accessible* aAccessible) { + roles::Role role = aAccessible->Role(); + + if (role == roles::MENUPOPUP) { + // Don't fire menupopup events for combobox and autocomplete lists. + nsEventShell::FireEvent(nsIAccessibleEvent::EVENT_MENUPOPUP_START, + aAccessible); + return; + } + + if (role == roles::COMBOBOX_LIST) { + // Fire expanded state change event for comboboxes and autocompeletes. + Accessible* combobox = aAccessible->Parent(); + if (!combobox) return; + + if (combobox->IsCombobox() || combobox->IsAutoComplete()) { + RefPtr<AccEvent> event = + new AccStateChangeEvent(combobox, states::EXPANDED, true); + if (event) nsEventShell::FireEvent(event); + } + + // If aria-activedescendant is present, redirect focus. + // This is needed for parent process <select> dropdowns, which use a + // menulist containing div elements instead of XUL menuitems. XUL menuitems + // fire DOMMenuItemActive events from layout instead. + MOZ_ASSERT(aAccessible->Elm()); + if (aAccessible->Elm()->HasAttr(kNameSpaceID_None, + nsGkAtoms::aria_activedescendant)) { + Accessible* activeDescendant = aAccessible->CurrentItem(); + if (activeDescendant) { + FocusMgr()->ActiveItemChanged(activeDescendant, false); +#ifdef A11Y_LOG + if (logging::IsEnabled(logging::eFocus)) { + logging::ActiveItemChangeCausedBy("ARIA activedescendant on popup", + activeDescendant); + } +#endif + } + } + } +} + +void RootAccessible::HandlePopupHidingEvent(nsINode* aPopupNode) { + DocAccessible* document = nsAccUtils::GetDocAccessibleFor(aPopupNode); + if (!document) return; + + if (aPopupNode->IsXULElement(nsGkAtoms::tooltip)) { + document->ContentRemoved(aPopupNode->AsContent()); + return; + } + + // Get popup accessible. There are cases when popup element isn't accessible + // but an underlying widget is and behaves like popup, an example is + // autocomplete popups. + Accessible* popup = document->GetAccessible(aPopupNode); + if (!popup) { + Accessible* popupContainer = document->GetContainerAccessible(aPopupNode); + if (!popupContainer) return; + + uint32_t childCount = popupContainer->ChildCount(); + for (uint32_t idx = 0; idx < childCount; idx++) { + Accessible* child = popupContainer->GetChildAt(idx); + if (child->IsAutoCompletePopup()) { + popup = child; + break; + } + } + + // No popup no events. Focus is managed by DOM. This is a case for + // menupopups of menus on Linux since there are no accessible for popups. + if (!popup) return; + } + + // In case of autocompletes and comboboxes fire state change event for + // expanded state. Note, HTML form autocomplete isn't a subject of state + // change event because they aren't autocompletes strictly speaking. + // When popup closes (except nested popups and menus) then fire focus event to + // where it was. The focus event is expected even if popup didn't take a + // focus. + + static const uint32_t kNotifyOfFocus = 1; + static const uint32_t kNotifyOfState = 2; + uint32_t notifyOf = 0; + + // HTML select is target of popuphidding event. Otherwise get container + // widget. No container widget means this is either tooltip or menupopup. + // No events in the former case. + Accessible* widget = nullptr; + if (popup->IsCombobox()) { + widget = popup; + } else { + widget = popup->ContainerWidget(); + if (!widget) { + if (!popup->IsMenuPopup()) return; + + widget = popup; + } + } + + if (popup->IsAutoCompletePopup()) { + // No focus event for autocomplete because it's managed by + // DOMMenuItemInactive events. + if (widget->IsAutoComplete()) notifyOf = kNotifyOfState; + + } else if (widget->IsCombobox()) { + // Fire focus for active combobox, otherwise the focus is managed by DOM + // focus notifications. Always fire state change event. + if (widget->IsActiveWidget()) notifyOf = kNotifyOfFocus; + notifyOf |= kNotifyOfState; + + } else if (widget->IsMenuButton()) { + // Can be a part of autocomplete. + Accessible* compositeWidget = widget->ContainerWidget(); + if (compositeWidget && compositeWidget->IsAutoComplete()) { + widget = compositeWidget; + notifyOf = kNotifyOfState; + } + + // Autocomplete (like searchbar) can be inactive when popup hiddens + notifyOf |= kNotifyOfFocus; + + } else if (widget == popup) { + // Top level context menus and alerts. + // Ignore submenus and menubar. When submenu is closed then sumbenu + // container menuitem takes a focus via DOMMenuItemActive notification. + // For menubars processing we listen DOMMenubarActive/Inactive + // notifications. + notifyOf = kNotifyOfFocus; + } + + // Restore focus to where it was. + if (notifyOf & kNotifyOfFocus) { + FocusMgr()->ActiveItemChanged(nullptr); +#ifdef A11Y_LOG + if (logging::IsEnabled(logging::eFocus)) + logging::ActiveItemChangeCausedBy("popuphiding", popup); +#endif + } + + // Fire expanded state change event. + if (notifyOf & kNotifyOfState) { + RefPtr<AccEvent> event = + new AccStateChangeEvent(widget, states::EXPANDED, false); + document->FireDelayedEvent(event); + } +} + +#ifdef MOZ_XUL +static void GetPropertyBagFromEvent(Event* aEvent, + nsIPropertyBag2** aPropertyBag) { + *aPropertyBag = nullptr; + + CustomEvent* customEvent = aEvent->AsCustomEvent(); + if (!customEvent) return; + + AutoJSAPI jsapi; + if (!jsapi.Init(customEvent->GetParentObject())) return; + + JSContext* cx = jsapi.cx(); + JS::Rooted<JS::Value> detail(cx); + customEvent->GetDetail(cx, &detail); + if (!detail.isObject()) return; + + JS::Rooted<JSObject*> detailObj(cx, &detail.toObject()); + + nsresult rv; + nsCOMPtr<nsIPropertyBag2> propBag; + rv = UnwrapArg<nsIPropertyBag2>(cx, detailObj, getter_AddRefs(propBag)); + if (NS_FAILED(rv)) return; + + propBag.forget(aPropertyBag); +} + +void RootAccessible::HandleTreeRowCountChangedEvent( + Event* aEvent, XULTreeAccessible* aAccessible) { + nsCOMPtr<nsIPropertyBag2> propBag; + GetPropertyBagFromEvent(aEvent, getter_AddRefs(propBag)); + if (!propBag) return; + + nsresult rv; + int32_t index, count; + rv = propBag->GetPropertyAsInt32(u"index"_ns, &index); + if (NS_FAILED(rv)) return; + + rv = propBag->GetPropertyAsInt32(u"count"_ns, &count); + if (NS_FAILED(rv)) return; + + aAccessible->InvalidateCache(index, count); +} + +void RootAccessible::HandleTreeInvalidatedEvent( + Event* aEvent, XULTreeAccessible* aAccessible) { + nsCOMPtr<nsIPropertyBag2> propBag; + GetPropertyBagFromEvent(aEvent, getter_AddRefs(propBag)); + if (!propBag) return; + + int32_t startRow = 0, endRow = -1, startCol = 0, endCol = -1; + propBag->GetPropertyAsInt32(u"startrow"_ns, &startRow); + propBag->GetPropertyAsInt32(u"endrow"_ns, &endRow); + propBag->GetPropertyAsInt32(u"startcolumn"_ns, &startCol); + propBag->GetPropertyAsInt32(u"endcolumn"_ns, &endCol); + + aAccessible->TreeViewInvalidated(startRow, endRow, startCol, endCol); +} +#endif + +ProxyAccessible* RootAccessible::GetPrimaryRemoteTopLevelContentDoc() const { + nsCOMPtr<nsIDocShellTreeOwner> owner; + mDocumentNode->GetDocShell()->GetTreeOwner(getter_AddRefs(owner)); + NS_ENSURE_TRUE(owner, nullptr); + + nsCOMPtr<nsIRemoteTab> remoteTab; + owner->GetPrimaryRemoteTab(getter_AddRefs(remoteTab)); + if (!remoteTab) { + return nullptr; + } + + auto tab = static_cast<dom::BrowserHost*>(remoteTab.get()); + return tab->GetTopLevelDocAccessible(); +} diff --git a/accessible/generic/RootAccessible.h b/accessible/generic/RootAccessible.h new file mode 100644 index 0000000000..f169692b16 --- /dev/null +++ b/accessible/generic/RootAccessible.h @@ -0,0 +1,88 @@ +/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +#ifndef mozilla_a11y_RootAccessible_h__ +#define mozilla_a11y_RootAccessible_h__ + +#include "HyperTextAccessible.h" +#include "DocAccessibleWrap.h" + +#include "nsIDOMEventListener.h" + +namespace mozilla { + +class PresShell; + +namespace a11y { + +class RootAccessible : public DocAccessibleWrap, public nsIDOMEventListener { + NS_DECL_ISUPPORTS_INHERITED + + public: + RootAccessible(dom::Document* aDocument, PresShell* aPresShell); + + // nsIDOMEventListener + NS_DECL_NSIDOMEVENTLISTENER + + // Accessible + virtual void Shutdown() override; + virtual mozilla::a11y::ENameValueFlag Name(nsString& aName) const override; + virtual Relation RelationByType(RelationType aType) const override; + virtual uint64_t NativeState() const override; + + // RootAccessible + + /** + * Notify that the sub document presshell was activated. + */ + virtual void DocumentActivated(DocAccessible* aDocument); + + /** + * Return the primary remote top level document if any. + */ + ProxyAccessible* GetPrimaryRemoteTopLevelContentDoc() const; + + protected: + virtual ~RootAccessible(); + + /** + * Add/remove DOM event listeners. + */ + virtual nsresult AddEventListeners() override; + virtual nsresult RemoveEventListeners() override; + + /** + * Process the DOM event. + */ + void ProcessDOMEvent(dom::Event* aDOMEvent, nsINode* aTarget); + + /** + * Process "popupshown" event. Used by HandleEvent(). + */ + void HandlePopupShownEvent(Accessible* aAccessible); + + /* + * Process "popuphiding" event. Used by HandleEvent(). + */ + void HandlePopupHidingEvent(nsINode* aNode); + +#ifdef MOZ_XUL + void HandleTreeRowCountChangedEvent(dom::Event* aEvent, + XULTreeAccessible* aAccessible); + void HandleTreeInvalidatedEvent(dom::Event* aEvent, + XULTreeAccessible* aAccessible); + + uint32_t GetChromeFlags() const; +#endif +}; + +inline RootAccessible* Accessible::AsRoot() { + return IsRoot() ? static_cast<mozilla::a11y::RootAccessible*>(this) : nullptr; +} + +} // namespace a11y +} // namespace mozilla + +#endif diff --git a/accessible/generic/TableAccessible.cpp b/accessible/generic/TableAccessible.cpp new file mode 100644 index 0000000000..f32b6d7a60 --- /dev/null +++ b/accessible/generic/TableAccessible.cpp @@ -0,0 +1,315 @@ +/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* vim: set ts=2 et sw=2 tw=80: */ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this file, + * You can obtain one at http://mozilla.org/MPL/2.0/. */ + +#include "TableAccessible.h" + +#include "Accessible-inl.h" +#include "AccIterator.h" + +#include "nsTableCellFrame.h" +#include "nsTableWrapperFrame.h" +#include "TableCellAccessible.h" + +using namespace mozilla; +using namespace mozilla::a11y; + +bool TableAccessible::IsProbablyLayoutTable() { + // Implement a heuristic to determine if table is most likely used for layout. + + // XXX do we want to look for rowspan or colspan, especialy that span all but + // a couple cells at the beginning or end of a row/col, and especially when + // they occur at the edge of a table? + + // XXX For now debugging descriptions are always on via SHOW_LAYOUT_HEURISTIC + // This will allow release trunk builds to be used by testers to refine + // the algorithm. Integrate it into Logging. + // Change to |#define SHOW_LAYOUT_HEURISTIC DEBUG| before final release +#ifdef SHOW_LAYOUT_HEURISTIC +# define RETURN_LAYOUT_ANSWER(isLayout, heuristic) \ + { \ + mLayoutHeuristic = isLayout \ + ? nsLiteralString(u"layout table: " heuristic) \ + : nsLiteralString(u"data table: " heuristic); \ + return isLayout; \ + } +#else +# define RETURN_LAYOUT_ANSWER(isLayout, heuristic) \ + { return isLayout; } +#endif + + Accessible* thisacc = AsAccessible(); + + MOZ_ASSERT(!thisacc->IsDefunct(), "Table accessible should not be defunct"); + + // Need to see all elements while document is being edited. + if (thisacc->Document()->State() & states::EDITABLE) { + RETURN_LAYOUT_ANSWER(false, "In editable document"); + } + + // Check to see if an ARIA role overrides the role from native markup, + // but for which we still expose table semantics (treegrid, for example). + if (thisacc->HasARIARole()) { + RETURN_LAYOUT_ANSWER(false, "Has role attribute"); + } + + dom::Element* el = thisacc->Elm(); + if (el->IsMathMLElement(nsGkAtoms::mtable_)) { + RETURN_LAYOUT_ANSWER(false, "MathML matrix"); + } + + MOZ_ASSERT(el->IsHTMLElement(nsGkAtoms::table), + "Table should not be built by CSS display:table style"); + + // Check if datatable attribute has "0" value. + if (el->AttrValueIs(kNameSpaceID_None, nsGkAtoms::datatable, u"0"_ns, + eCaseMatters)) { + RETURN_LAYOUT_ANSWER(true, "Has datatable = 0 attribute, it's for layout"); + } + + // Check for legitimate data table attributes. + if (el->Element::HasNonEmptyAttr(nsGkAtoms::summary)) { + RETURN_LAYOUT_ANSWER(false, "Has summary -- legitimate table structures"); + } + + // Check for legitimate data table elements. + Accessible* caption = thisacc->FirstChild(); + if (caption && caption->IsHTMLCaption() && caption->HasChildren()) { + RETURN_LAYOUT_ANSWER(false, + "Not empty caption -- legitimate table structures"); + } + + for (nsIContent* childElm = el->GetFirstChild(); childElm; + childElm = childElm->GetNextSibling()) { + if (!childElm->IsHTMLElement()) continue; + + if (childElm->IsAnyOfHTMLElements(nsGkAtoms::col, nsGkAtoms::colgroup, + nsGkAtoms::tfoot, nsGkAtoms::thead)) { + RETURN_LAYOUT_ANSWER( + false, + "Has col, colgroup, tfoot or thead -- legitimate table structures"); + } + + if (childElm->IsHTMLElement(nsGkAtoms::tbody)) { + for (nsIContent* rowElm = childElm->GetFirstChild(); rowElm; + rowElm = rowElm->GetNextSibling()) { + if (rowElm->IsHTMLElement(nsGkAtoms::tr)) { + if (Accessible* row = thisacc->Document()->GetAccessible(rowElm)) { + if (const nsRoleMapEntry* roleMapEntry = row->ARIARoleMap()) { + if (roleMapEntry->role != roles::ROW) { + RETURN_LAYOUT_ANSWER(true, "Repurposed tr with different role"); + } + } + } + + for (nsIContent* cellElm = rowElm->GetFirstChild(); cellElm; + cellElm = cellElm->GetNextSibling()) { + if (cellElm->IsHTMLElement()) { + if (cellElm->NodeInfo()->Equals(nsGkAtoms::th)) { + RETURN_LAYOUT_ANSWER(false, + "Has th -- legitimate table structures"); + } + + if (cellElm->AsElement()->HasAttr(kNameSpaceID_None, + nsGkAtoms::headers) || + cellElm->AsElement()->HasAttr(kNameSpaceID_None, + nsGkAtoms::scope) || + cellElm->AsElement()->HasAttr(kNameSpaceID_None, + nsGkAtoms::abbr)) { + RETURN_LAYOUT_ANSWER(false, + "Has headers, scope, or abbr attribute -- " + "legitimate table structures"); + } + + if (Accessible* cell = + thisacc->Document()->GetAccessible(cellElm)) { + if (const nsRoleMapEntry* roleMapEntry = cell->ARIARoleMap()) { + if (roleMapEntry->role != roles::CELL && + roleMapEntry->role != roles::COLUMNHEADER && + roleMapEntry->role != roles::ROWHEADER && + roleMapEntry->role != roles::GRID_CELL) { + RETURN_LAYOUT_ANSWER(true, + "Repurposed cell with different role"); + } + } + if (cell->ChildCount() == 1 && + cell->FirstChild()->IsAbbreviation()) { + RETURN_LAYOUT_ANSWER( + false, "has abbr -- legitimate table structures"); + } + } + } + } + } + } + } + } + + // Check for nested tables. + nsCOMPtr<nsIHTMLCollection> nestedTables = + el->GetElementsByTagName(u"table"_ns); + if (nestedTables->Length() > 0) { + RETURN_LAYOUT_ANSWER(true, "Has a nested table within it"); + } + + // If only 1 column or only 1 row, it's for layout. + auto colCount = ColCount(); + if (colCount <= 1) { + RETURN_LAYOUT_ANSWER(true, "Has only 1 column"); + } + auto rowCount = RowCount(); + if (rowCount <= 1) { + RETURN_LAYOUT_ANSWER(true, "Has only 1 row"); + } + + // Check for many columns. + if (colCount >= 5) { + RETURN_LAYOUT_ANSWER(false, ">=5 columns"); + } + + // Now we know there are 2-4 columns and 2 or more rows. Check to see if + // there are visible borders on the cells. + // XXX currently, we just check the first cell -- do we really need to do + // more? + nsTableWrapperFrame* tableFrame = do_QueryFrame(el->GetPrimaryFrame()); + if (!tableFrame) { + RETURN_LAYOUT_ANSWER(false, "table with no frame!"); + } + + nsIFrame* cellFrame = tableFrame->GetCellFrameAt(0, 0); + if (!cellFrame) { + RETURN_LAYOUT_ANSWER(false, "table's first cell has no frame!"); + } + + nsMargin border; + cellFrame->GetXULBorder(border); + if (border.top && border.bottom && border.left && border.right) { + RETURN_LAYOUT_ANSWER(false, "Has nonzero border-width on table cell"); + } + + // Rules for non-bordered tables with 2-4 columns and 2+ rows from here on + // forward. + + // Check for styled background color across rows (alternating background + // color is a common feature for data tables). + auto childCount = thisacc->ChildCount(); + nscolor rowColor = 0; + nscolor prevRowColor; + for (auto childIdx = 0U; childIdx < childCount; childIdx++) { + Accessible* child = thisacc->GetChildAt(childIdx); + if (child->IsHTMLTableRow()) { + prevRowColor = rowColor; + nsIFrame* rowFrame = child->GetFrame(); + MOZ_ASSERT(rowFrame, "Table hierarchy got screwed up"); + if (!rowFrame) { + RETURN_LAYOUT_ANSWER(false, "Unexpected table hierarchy"); + } + + rowColor = rowFrame->StyleBackground()->BackgroundColor(rowFrame); + + if (childIdx > 0 && prevRowColor != rowColor) { + RETURN_LAYOUT_ANSWER(false, + "2 styles of row background color, non-bordered"); + } + } + } + + // Check for many rows. + const uint32_t kMaxLayoutRows = 20; + if (rowCount > kMaxLayoutRows) { // A ton of rows, this is probably for data + RETURN_LAYOUT_ANSWER(false, ">= kMaxLayoutRows (20) and non-bordered"); + } + + // Check for very wide table. + nsIFrame* documentFrame = thisacc->Document()->GetFrame(); + nsSize documentSize = documentFrame->GetSize(); + if (documentSize.width > 0) { + nsSize tableSize = thisacc->GetFrame()->GetSize(); + int32_t percentageOfDocWidth = (100 * tableSize.width) / documentSize.width; + if (percentageOfDocWidth > 95) { + // 3-4 columns, no borders, not a lot of rows, and 95% of the doc's width + // Probably for layout + RETURN_LAYOUT_ANSWER( + true, "<= 4 columns, table width is 95% of document width"); + } + } + + // Two column rules. + if (rowCount * colCount <= 10) { + RETURN_LAYOUT_ANSWER(true, "2-4 columns, 10 cells or less, non-bordered"); + } + + static const nsLiteralString tags[] = {u"embed"_ns, u"object"_ns, + u"iframe"_ns}; + for (auto& tag : tags) { + nsCOMPtr<nsIHTMLCollection> descendants = el->GetElementsByTagName(tag); + if (descendants->Length() > 0) { + RETURN_LAYOUT_ANSWER(true, + "Has no borders, and has iframe, object or embed, " + "typical of advertisements"); + } + } + + RETURN_LAYOUT_ANSWER(false, + "No layout factor strong enough, so will guess data"); +} + +Accessible* TableAccessible::RowAt(int32_t aRow) { + int32_t rowIdx = aRow; + + AccIterator rowIter(this->AsAccessible(), filters::GetRow); + + Accessible* row = rowIter.Next(); + while (rowIdx != 0 && (row = rowIter.Next())) { + rowIdx--; + } + + return row; +} + +Accessible* TableAccessible::CellInRowAt(Accessible* aRow, int32_t aColumn) { + int32_t colIdx = aColumn; + + AccIterator cellIter(aRow, filters::GetCell); + Accessible* cell = nullptr; + + while (colIdx >= 0 && (cell = cellIter.Next())) { + MOZ_ASSERT(cell->IsTableCell(), "No table or grid cell!"); + colIdx -= cell->AsTableCell()->ColExtent(); + } + + return cell; +} + +int32_t TableAccessible::ColIndexAt(uint32_t aCellIdx) { + uint32_t colCount = ColCount(); + if (colCount < 1 || aCellIdx >= colCount * RowCount()) { + return -1; // Error: column count is 0 or index out of bounds. + } + + return aCellIdx % colCount; +} + +int32_t TableAccessible::RowIndexAt(uint32_t aCellIdx) { + uint32_t colCount = ColCount(); + if (colCount < 1 || aCellIdx >= colCount * RowCount()) { + return -1; // Error: column count is 0 or index out of bounds. + } + + return aCellIdx / colCount; +} + +void TableAccessible::RowAndColIndicesAt(uint32_t aCellIdx, int32_t* aRowIdx, + int32_t* aColIdx) { + uint32_t colCount = ColCount(); + if (colCount < 1 || aCellIdx >= colCount * RowCount()) { + *aRowIdx = -1; + *aColIdx = -1; + return; // Error: column count is 0 or index out of bounds. + } + + *aRowIdx = aCellIdx / colCount; + *aColIdx = aCellIdx % colCount; +} diff --git a/accessible/generic/TableAccessible.h b/accessible/generic/TableAccessible.h new file mode 100644 index 0000000000..9b0ccdb8af --- /dev/null +++ b/accessible/generic/TableAccessible.h @@ -0,0 +1,220 @@ +/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* vim: set ts=2 et sw=2 tw=80: */ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this file, + * You can obtain one at http://mozilla.org/MPL/2.0/. */ + +#ifndef TABLE_ACCESSIBLE_H +#define TABLE_ACCESSIBLE_H + +#include "TableCellAccessible.h" +#include "nsPointerHashKeys.h" +#include "nsRefPtrHashtable.h" +#include "nsString.h" +#include "nsTArray.h" + +namespace mozilla { +namespace a11y { + +class Accessible; + +/** + * Accessible table interface. + */ +class TableAccessible { + public: + /** + * Return the caption accessible if any for this table. + */ + virtual Accessible* Caption() const { return nullptr; } + + /** + * Get the summary for this table. + */ + virtual void Summary(nsString& aSummary) { aSummary.Truncate(); } + + /** + * Return the number of columns in the table. + */ + virtual uint32_t ColCount() const { return 0; } + + /** + * Return the number of rows in the table. + */ + virtual uint32_t RowCount() { return 0; } + + /** + * Return the accessible for the cell at the given row and column indices. + */ + virtual Accessible* CellAt(uint32_t aRowIdx, uint32_t aColIdx) { + return nullptr; + } + + /** + * Return the index of the cell at the given row and column. + */ + virtual int32_t CellIndexAt(uint32_t aRowIdx, uint32_t aColIdx) { + return ColCount() * aRowIdx + aColIdx; + } + + /** + * Return the column index of the cell with the given index. + * This returns -1 if the column count is 0 or an invalid index is being + * passed in. + */ + virtual int32_t ColIndexAt(uint32_t aCellIdx); + + /** + * Return the row index of the cell with the given index. + * This returns -1 if the column count is 0 or an invalid index is being + * passed in. + */ + virtual int32_t RowIndexAt(uint32_t aCellIdx); + + /** + * Get the row and column indices for the cell at the given index. + * This returns -1 for both output parameters if the column count is 0 or an + * invalid index is being passed in. + */ + virtual void RowAndColIndicesAt(uint32_t aCellIdx, int32_t* aRowIdx, + int32_t* aColIdx); + + /** + * Return the number of columns occupied by the cell at the given row and + * column indices. + */ + virtual uint32_t ColExtentAt(uint32_t aRowIdx, uint32_t aColIdx) { return 1; } + + /** + * Return the number of rows occupied by the cell at the given row and column + * indices. + */ + virtual uint32_t RowExtentAt(uint32_t aRowIdx, uint32_t aColIdx) { return 1; } + + /** + * Get the description of the given column. + */ + virtual void ColDescription(uint32_t aColIdx, nsString& aDescription) { + aDescription.Truncate(); + } + + /** + * Get the description for the given row. + */ + virtual void RowDescription(uint32_t aRowIdx, nsString& aDescription) { + aDescription.Truncate(); + } + + /** + * Return true if the given column is selected. + */ + virtual bool IsColSelected(uint32_t aColIdx) { return false; } + + /** + * Return true if the given row is selected. + */ + virtual bool IsRowSelected(uint32_t aRowIdx) { return false; } + + /** + * Return true if the given cell is selected. + */ + virtual bool IsCellSelected(uint32_t aRowIdx, uint32_t aColIdx) { + return false; + } + + /** + * Return the number of selected cells. + */ + virtual uint32_t SelectedCellCount() { return 0; } + + /** + * Return the number of selected columns. + */ + virtual uint32_t SelectedColCount() { return 0; } + + /** + * Return the number of selected rows. + */ + virtual uint32_t SelectedRowCount() { return 0; } + + /** + * Get the set of selected cells. + */ + virtual void SelectedCells(nsTArray<Accessible*>* aCells) = 0; + + /** + * Get the set of selected cell indices. + */ + virtual void SelectedCellIndices(nsTArray<uint32_t>* aCells) = 0; + + /** + * Get the set of selected column indices. + */ + virtual void SelectedColIndices(nsTArray<uint32_t>* aCols) = 0; + + /** + * Get the set of selected row indices. + */ + virtual void SelectedRowIndices(nsTArray<uint32_t>* aRows) = 0; + + /** + * Select the given column unselecting any other selected columns. + */ + virtual void SelectCol(uint32_t aColIdx) {} + + /** + * Select the given row unselecting all other previously selected rows. + */ + virtual void SelectRow(uint32_t aRowIdx) {} + + /** + * Unselect the given column leaving other selected columns selected. + */ + virtual void UnselectCol(uint32_t aColIdx) {} + + /** + * Unselect the given row leaving other selected rows selected. + */ + virtual void UnselectRow(uint32_t aRowIdx) {} + + /** + * Return true if the table is probably for layout. + */ + virtual bool IsProbablyLayoutTable(); + + /** + * Convert the table to an Accessible*. + */ + virtual Accessible* AsAccessible() = 0; + + typedef nsRefPtrHashtable<nsPtrHashKey<const TableCellAccessible>, Accessible> + HeaderCache; + + /** + * Get the header cache, which maps a TableCellAccessible to its previous + * header. + * Although this data is only used in TableCellAccessible, it is stored on + * TableAccessible so the cache can be easily invalidated when the table + * is mutated. + */ + HeaderCache& GetHeaderCache() { return mHeaderCache; } + + protected: + /** + * Return row accessible at the given row index. + */ + Accessible* RowAt(int32_t aRow); + + /** + * Return cell accessible at the given column index in the row. + */ + Accessible* CellInRowAt(Accessible* aRow, int32_t aColumn); + + private: + HeaderCache mHeaderCache; +}; + +} // namespace a11y +} // namespace mozilla + +#endif diff --git a/accessible/generic/TableCellAccessible.cpp b/accessible/generic/TableCellAccessible.cpp new file mode 100644 index 0000000000..8c7210417e --- /dev/null +++ b/accessible/generic/TableCellAccessible.cpp @@ -0,0 +1,113 @@ +/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* vim: set ts=2 et sw=2 tw=80: */ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this file, + * You can obtain one at http://mozilla.org/MPL/2.0/. */ + +#include "TableCellAccessible.h" + +#include "Accessible-inl.h" +#include "TableAccessible.h" + +using namespace mozilla; +using namespace mozilla::a11y; + +void TableCellAccessible::RowHeaderCells(nsTArray<Accessible*>* aCells) { + uint32_t rowIdx = RowIdx(), colIdx = ColIdx(); + TableAccessible* table = Table(); + if (!table) return; + + // Move to the left to find row header cells + for (uint32_t curColIdx = colIdx - 1; curColIdx < colIdx; curColIdx--) { + Accessible* cell = table->CellAt(rowIdx, curColIdx); + if (!cell) continue; + + // CellAt should always return a TableCellAccessible (XXX Bug 587529) + TableCellAccessible* tableCell = cell->AsTableCell(); + NS_ASSERTION(tableCell, "cell should be a table cell!"); + if (!tableCell) continue; + + // Avoid addding cells multiple times, if this cell spans more columns + // we'll get it later. + if (tableCell->ColIdx() == curColIdx && cell->Role() == roles::ROWHEADER) + aCells->AppendElement(cell); + } +} + +Accessible* TableCellAccessible::PrevColHeader() { + TableAccessible* table = Table(); + if (!table) { + return nullptr; + } + + TableAccessible::HeaderCache& cache = table->GetHeaderCache(); + bool inCache = false; + Accessible* cachedHeader = cache.GetWeak(this, &inCache); + if (inCache) { + // Cached but null means we know there is no previous column header. + // if defunct, the cell was removed, so behave as if there is no cached + // value. + if (!cachedHeader || !cachedHeader->IsDefunct()) { + return cachedHeader; + } + } + + uint32_t rowIdx = RowIdx(), colIdx = ColIdx(); + for (uint32_t curRowIdx = rowIdx - 1; curRowIdx < rowIdx; curRowIdx--) { + Accessible* cell = table->CellAt(curRowIdx, colIdx); + if (!cell) { + continue; + } + // CellAt should always return a TableCellAccessible (XXX Bug 587529) + TableCellAccessible* tableCell = cell->AsTableCell(); + MOZ_ASSERT(tableCell, "cell should be a table cell!"); + if (!tableCell) { + continue; + } + + // Check whether the previous table cell has a cached value. + cachedHeader = cache.GetWeak(tableCell, &inCache); + if ( + // We check the cache first because even though we might not use it, + // it's faster than the other conditions. + inCache && + // Only use the cached value if: + // 1. cell is a table cell which is not a column header. In that case, + // cell is the previous header and cachedHeader is the one before that. + // We will return cell later. + cell->Role() != roles::COLUMNHEADER && + // 2. cell starts in this column. If it starts in a previous column and + // extends into this one, its header will be for the starting column, + // which is wrong for this cell. + // ColExtent is faster than ColIdx, so check that first. + (tableCell->ColExtent() == 1 || tableCell->ColIdx() == colIdx)) { + if (!cachedHeader || !cachedHeader->IsDefunct()) { + // Cache it for this cell. + cache.Put(this, RefPtr<Accessible>(cachedHeader)); + return cachedHeader; + } + } + + // Avoid addding cells multiple times, if this cell spans more rows + // we'll get it later. + if (cell->Role() != roles::COLUMNHEADER || + tableCell->RowIdx() != curRowIdx) { + continue; + } + + // Cache the header we found. + cache.Put(this, RefPtr<Accessible>(cell)); + return cell; + } + + // There's no header, so cache that fact. + cache.Put(this, RefPtr<Accessible>(nullptr)); + return nullptr; +} + +void TableCellAccessible::ColHeaderCells(nsTArray<Accessible*>* aCells) { + for (Accessible* cell = PrevColHeader(); cell; + cell = cell->AsTableCell()->PrevColHeader()) { + aCells->AppendElement(cell); + } +} diff --git a/accessible/generic/TableCellAccessible.h b/accessible/generic/TableCellAccessible.h new file mode 100644 index 0000000000..29ebb1f973 --- /dev/null +++ b/accessible/generic/TableCellAccessible.h @@ -0,0 +1,71 @@ +/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* vim: set ts=2 et sw=2 tw=80: */ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this file, + * You can obtain one at http://mozilla.org/MPL/2.0/. */ + +#ifndef mozilla_a11y_TableCellAccessible_h__ +#define mozilla_a11y_TableCellAccessible_h__ + +#include "nsTArray.h" +#include <stdint.h> + +namespace mozilla { +namespace a11y { + +class Accessible; +class TableAccessible; + +/** + * Abstract interface implemented by table cell accessibles. + */ +class TableCellAccessible { + public: + /** + * Return the table this cell is in. + */ + virtual TableAccessible* Table() const = 0; + + /** + * Return the column of the table this cell is in. + */ + virtual uint32_t ColIdx() const = 0; + + /** + * Return the row of the table this cell is in. + */ + virtual uint32_t RowIdx() const = 0; + + /** + * Return the column extent of this cell. + */ + virtual uint32_t ColExtent() const { return 1; } + + /** + * Return the row extent of this cell. + */ + virtual uint32_t RowExtent() const { return 1; } + + /** + * Return the column header cells for this cell. + */ + virtual void ColHeaderCells(nsTArray<Accessible*>* aCells); + + /** + * Return the row header cells for this cell. + */ + virtual void RowHeaderCells(nsTArray<Accessible*>* aCells); + + /** + * Returns true if this cell is selected. + */ + virtual bool Selected() = 0; + + private: + Accessible* PrevColHeader(); +}; + +} // namespace a11y +} // namespace mozilla + +#endif // mozilla_a11y_TableCellAccessible_h__ diff --git a/accessible/generic/TextLeafAccessible.cpp b/accessible/generic/TextLeafAccessible.cpp new file mode 100644 index 0000000000..1f7c2ff13a --- /dev/null +++ b/accessible/generic/TextLeafAccessible.cpp @@ -0,0 +1,44 @@ +/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +#include "TextLeafAccessible.h" + +#include "nsAccUtils.h" +#include "DocAccessible.h" +#include "Role.h" + +using namespace mozilla::a11y; + +//////////////////////////////////////////////////////////////////////////////// +// TextLeafAccessible +//////////////////////////////////////////////////////////////////////////////// + +TextLeafAccessible::TextLeafAccessible(nsIContent* aContent, + DocAccessible* aDoc) + : LinkableAccessible(aContent, aDoc) { + mType = eTextLeafType; + mGenericTypes |= eText; + mStateFlags |= eNoKidsFromDOM; +} + +TextLeafAccessible::~TextLeafAccessible() {} + +role TextLeafAccessible::NativeRole() const { + nsIFrame* frame = GetFrame(); + if (frame && frame->IsGeneratedContentFrame()) return roles::STATICTEXT; + + return roles::TEXT_LEAF; +} + +void TextLeafAccessible::AppendTextTo(nsAString& aText, uint32_t aStartOffset, + uint32_t aLength) { + aText.Append(Substring(mText, aStartOffset, aLength)); +} + +ENameValueFlag TextLeafAccessible::Name(nsString& aName) const { + // Text node, ARIA can't be used. + aName = mText; + return eNameOK; +} diff --git a/accessible/generic/TextLeafAccessible.h b/accessible/generic/TextLeafAccessible.h new file mode 100644 index 0000000000..e491e9cb6f --- /dev/null +++ b/accessible/generic/TextLeafAccessible.h @@ -0,0 +1,46 @@ +/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +#ifndef mozilla_a11y_TextLeafAccessible_h__ +#define mozilla_a11y_TextLeafAccessible_h__ + +#include "BaseAccessibles.h" + +namespace mozilla { +namespace a11y { + +/** + * Generic class used for text nodes. + */ +class TextLeafAccessible : public LinkableAccessible { + public: + TextLeafAccessible(nsIContent* aContent, DocAccessible* aDoc); + virtual ~TextLeafAccessible(); + + // Accessible + virtual mozilla::a11y::role NativeRole() const override; + virtual void AppendTextTo(nsAString& aText, uint32_t aStartOffset = 0, + uint32_t aLength = UINT32_MAX) override; + virtual ENameValueFlag Name(nsString& aName) const override; + + // TextLeafAccessible + void SetText(const nsAString& aText) { mText = aText; } + const nsString& Text() const { return mText; } + + protected: + nsString mText; +}; + +//////////////////////////////////////////////////////////////////////////////// +// Accessible downcast method + +inline TextLeafAccessible* Accessible::AsTextLeaf() { + return IsTextLeaf() ? static_cast<TextLeafAccessible*>(this) : nullptr; +} + +} // namespace a11y +} // namespace mozilla + +#endif diff --git a/accessible/generic/moz.build b/accessible/generic/moz.build new file mode 100644 index 0000000000..8612b7d6f6 --- /dev/null +++ b/accessible/generic/moz.build @@ -0,0 +1,77 @@ +# -*- Mode: python; indent-tabs-mode: nil; tab-width: 40 -*- +# vim: set filetype=python: +# This Source Code Form is subject to the terms of the Mozilla Public +# License, v. 2.0. If a copy of the MPL was not distributed with this +# file, You can obtain one at http://mozilla.org/MPL/2.0/. + +EXPORTS.mozilla.a11y += [ + "Accessible.h", + "DocAccessible.h", + "HyperTextAccessible.h", + "OuterDocAccessible.h", +] + +UNIFIED_SOURCES += [ + "Accessible.cpp", + "ApplicationAccessible.cpp", + "ARIAGridAccessible.cpp", + "BaseAccessibles.cpp", + "DocAccessible.cpp", + "FormControlAccessible.cpp", + "HyperTextAccessible.cpp", + "ImageAccessible.cpp", + "OuterDocAccessible.cpp", + "RootAccessible.cpp", + "TableAccessible.cpp", + "TableCellAccessible.cpp", + "TextLeafAccessible.cpp", +] + +LOCAL_INCLUDES += [ + "/accessible/base", + "/accessible/html", + "/accessible/xpcom", + "/accessible/xul", + "/dom/base", + "/dom/xul", + "/layout/generic", + "/layout/xul", +] + +if CONFIG["OS_ARCH"] == "WINNT": + LOCAL_INCLUDES += [ + "/accessible/ipc/win", + ] +else: + LOCAL_INCLUDES += [ + "/accessible/ipc/other", + ] + +if CONFIG["MOZ_WIDGET_TOOLKIT"] == "gtk": + LOCAL_INCLUDES += [ + "/accessible/atk", + ] +elif CONFIG["MOZ_WIDGET_TOOLKIT"] == "windows": + LOCAL_INCLUDES += [ + "/accessible/windows/ia2", + "/accessible/windows/msaa", + ] +elif CONFIG["MOZ_WIDGET_TOOLKIT"] == "cocoa": + LOCAL_INCLUDES += [ + "/accessible/mac", + ] +elif CONFIG["MOZ_WIDGET_TOOLKIT"] == "android": + LOCAL_INCLUDES += [ + "/accessible/android", + ] +else: + LOCAL_INCLUDES += [ + "/accessible/other", + ] + +FINAL_LIBRARY = "xul" + +include("/ipc/chromium/chromium-config.mozbuild") + +if CONFIG["CC_TYPE"] in ("clang", "gcc"): + CXXFLAGS += ["-Wno-error=shadow"] |