Quellcodebibliothek Statistik Leitseite products/Sources/formale Sprachen/C/LibreOffice/sfx2/source/view/   (Office von Apache Version 25.8.3.2©)  Datei vom 5.10.2025 mit Größe 144 kB image not shown  

Quelle  viewsh.cxx   Sprache: C

 
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4; fill-column: 100 -*- */
/*
 * This file is part of the LibreOffice project.
 *
 * 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/.
 *
 * This file incorporates work covered by the following license notice:
 *
 *   Licensed to the Apache Software Foundation (ASF) under one or more
 *   contributor license agreements. See the NOTICE file distributed
 *   with this work for additional information regarding copyright
 *   ownership. The ASF licenses this file to you under the Apache
 *   License, Version 2.0 (the "License"); you may not use this file
 *   except in compliance with the License. You may obtain a copy of
 *   the License at http://www.apache.org/licenses/LICENSE-2.0 .
 */


#include <config_features.h>

#include <boost/property_tree/json_parser.hpp>

#include <sal/log.hxx>
#include <svl/stritem.hxx>
#include <svl/eitem.hxx>
#include <svl/whiter.hxx>
#include <utility>
#include <vcl/svapp.hxx>
#include <vcl/toolbox.hxx>
#include <vcl/weld.hxx>
#include <svl/intitem.hxx>
#include <svtools/colorcfg.hxx>
#include <svtools/langhelp.hxx>
#include <com/sun/star/awt/XPopupMenu.hpp>
#include <com/sun/star/frame/XLayoutManager.hpp>
#include <com/sun/star/frame/ModuleManager.hpp>
#include <com/sun/star/io/IOException.hpp>
#include <com/sun/star/beans/XPropertySet.hpp>
#include <com/sun/star/embed/EmbedStates.hpp>
#include <com/sun/star/embed/EmbedMisc.hpp>
#include <com/sun/star/embed/XEmbeddedObject.hpp>
#include <com/sun/star/container/XContainerQuery.hpp>
#include <com/sun/star/frame/XStorable.hpp>
#include <com/sun/star/frame/XModel.hpp>
#include <com/sun/star/datatransfer/clipboard/XClipboard.hpp>
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#include <com/sun/star/datatransfer/clipboard/XClipboardListener.hpp>
#include <com/sun/star/datatransfer/clipboard/XClipboardNotifier.hpp>
#include <com/sun/star/drawing/XShapes.hpp>
#include <com/sun/star/view/XRenderable.hpp>
#include <com/sun/star/uno/Reference.hxx>
#include <com/sun/star/lang/IndexOutOfBoundsException.hpp>
#include <com/sun/star/accessibility/XAccessibleContext.hpp>
#include <com/sun/star/accessibility/XAccessibleEventBroadcaster.hpp>
#include <com/sun/star/accessibility/XAccessibleSelection.hpp>
#include <com/sun/star/accessibility/AccessibleEventId.hpp>
#include <com/sun/star/accessibility/AccessibleStateType.hpp>
#include <com/sun/star/accessibility/AccessibleRole.hpp>
#include <com/sun/star/accessibility/XAccessibleText.hpp>
#include <com/sun/star/accessibility/XAccessibleTable.hpp>
#include <cppuhelper/implbase.hxx>
#include <com/sun/star/ui/XAcceleratorConfiguration.hpp>

#include <cppuhelper/weakref.hxx>

#include <com/sun/star/accessibility/XAccessibleTextAttributes.hpp>
#include <com/sun/star/accessibility/AccessibleTextType.hpp>
#include <com/sun/star/awt/FontSlant.hpp>

#include <comphelper/diagnose_ex.hxx>
#include <editeng/unoprnms.hxx>
#include <tools/urlobj.hxx>
#include <unotools/tempfile.hxx>
#include <svtools/soerr.hxx>
#include <tools/svborder.hxx>

#include <framework/actiontriggerhelper.hxx>
#include <comphelper/lok.hxx>
#include <comphelper/processfactory.hxx>
#include <comphelper/propertyvalue.hxx>
#include <comphelper/sequenceashashmap.hxx>
#include <toolkit/helper/vclunohelper.hxx>
#include <vcl/settings.hxx>
#include <vcl/commandinfoprovider.hxx>
#include <LibreOfficeKit/LibreOfficeKitEnums.h>

#include <officecfg/Setup.hxx>
#include <sfx2/app.hxx>
#include <sfx2/flatpak.hxx>
#include <sfx2/viewsh.hxx>
#include "viewimp.hxx"
#include <sfx2/sfxresid.hxx>
#include <sfx2/request.hxx>
#include <sfx2/printer.hxx>
#include <sfx2/docfile.hxx>
#include <sfx2/dispatch.hxx>
#include <sfx2/strings.hrc>
#include <sfx2/sfxbasecontroller.hxx>
#include <sfx2/mailmodelapi.hxx>
#include <bluthsndapi.hxx>
#include <sfx2/viewfrm.hxx>
#include <sfx2/event.hxx>
#include <sfx2/ipclient.hxx>
#include <sfx2/sfxsids.hrc>
#include <sfx2/objface.hxx>
#include <sfx2/lokhelper.hxx>
#include <sfx2/lokcallback.hxx>
#include <openuriexternally.hxx>
#include <iostream>
#include <vector>
#include <list>
#include <libxml/xmlwriter.h>
#include <toolkit/awt/vclxmenu.hxx>
#include <unordered_map>
#include <unordered_set>

#define ShellClass_SfxViewShell
#include <sfxslots.hxx>

using namespace ::com::sun::star;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::frame;
using namespace ::com::sun::star::beans;
using namespace ::cppu;

class SfxClipboardChangeListener : public ::cppu::WeakImplHelper<
    datatransfer::clipboard::XClipboardListener >
{
public:
    SfxClipboardChangeListener( SfxViewShell* pView, uno::Reference< datatransfer::clipboard::XClipboardNotifier > xClpbrdNtfr );

    // XEventListener
    virtual void SAL_CALL disposing( const lang::EventObject& rEventObject ) override;

    // XClipboardListener
    virtual void SAL_CALL changedContents( const datatransfer::clipboard::ClipboardEvent&&nbsp;rEventObject ) override;

    void DisconnectViewShell() { m_pViewShell = nullptr; }
    void ChangedContents();

    enum AsyncExecuteCmd
    {
        ASYNCEXECUTE_CMD_DISPOSING,
        ASYNCEXECUTE_CMD_CHANGEDCONTENTS
    };

    struct AsyncExecuteInfo
    {
        AsyncExecuteInfo( AsyncExecuteCmd eCmd, SfxClipboardChangeListener* pListener ) :
            m_eCmd( eCmd ), m_xListener( pListener ) {}

        AsyncExecuteCmd m_eCmd;
        rtl::Reference<SfxClipboardChangeListener> m_xListener;
    };

private:
    SfxViewShell* m_pViewShell;
    uno::Reference< datatransfer::clipboard::XClipboardNotifier > m_xClpbrdNtfr;
    uno::Reference< lang::XComponent > m_xCtrl;

    DECL_STATIC_LINK( SfxClipboardChangeListener, AsyncExecuteHdl_Impl, void*, void );
};

SfxClipboardChangeListener::SfxClipboardChangeListener( SfxViewShell* pView, uno::Reference< datatransfer::clipboard::XClipboardNotifier > xClpbrdNtfr )
  : m_pViewShell( nullptr ), m_xClpbrdNtfr(std::move( xClpbrdNtfr )), m_xCtrl(pView->GetController())
{
    if ( m_xCtrl.is() )
    {
        m_xCtrl->addEventListener( uno::Reference < lang::XEventListener > ( static_cast < lang::XEventListener* >( this ) ) );
        m_pViewShell = pView;
    }
    if ( m_xClpbrdNtfr.is() )
    {
        m_xClpbrdNtfr->addClipboardListener( uno::Reference< datatransfer::clipboard::XClipboardListener >(
            static_cast< datatransfer::clipboard::XClipboardListener* >( this )));
    }
}

void SfxClipboardChangeListener::ChangedContents()
{
    const SolarMutexGuard aGuard;
    if (!m_pViewShell)
        return;

    SfxBindings& rBind = m_pViewShell->GetViewFrame().GetBindings();
    rBind.Invalidate(SID_PASTE);
    rBind.Invalidate(SID_PASTE_SPECIAL);
    rBind.Invalidate(SID_CLIPBOARD_FORMAT_ITEMS);

    if (comphelper::LibreOfficeKit::isActive())
    {
        // In the future we might send the payload as well.
        SfxLokHelper::notifyAllViews(LOK_CALLBACK_CLIPBOARD_CHANGED, ""_ostr);
    }
}

IMPL_STATIC_LINK( SfxClipboardChangeListener, AsyncExecuteHdl_Impl, void*, p, void )
{
    AsyncExecuteInfo* pAsyncExecuteInfo = static_cast<AsyncExecuteInfo*>(p);
    if ( pAsyncExecuteInfo )
    {
        if ( pAsyncExecuteInfo->m_xListener.is() )
        {
            if ( pAsyncExecuteInfo->m_eCmd == ASYNCEXECUTE_CMD_DISPOSING )
                pAsyncExecuteInfo->m_xListener->DisconnectViewShell();
            else if ( pAsyncExecuteInfo->m_eCmd == ASYNCEXECUTE_CMD_CHANGEDCONTENTS )
                pAsyncExecuteInfo->m_xListener->ChangedContents();
        }
    }
    delete pAsyncExecuteInfo;
}

void SAL_CALL SfxClipboardChangeListener::disposing( const lang::EventObject& /*rEventObject*/ )
{
    // Either clipboard or ViewShell is going to be destroyed -> no interest in listening anymore
    uno::Reference< lang::XComponent > xCtrl( m_xCtrl );
    uno::Reference< datatransfer::clipboard::XClipboardNotifier > xNotify( m_xClpbrdNtfr );

    uno::Reference< datatransfer::clipboard::XClipboardListener > xThis( static_cast< datatransfer::clipboard::XClipboardListener* >( this ));
    if ( xCtrl.is() )
        xCtrl->removeEventListener( uno::Reference < lang::XEventListener > ( static_cast < lang::XEventListener* >( this )));
    if ( xNotify.is() )
        xNotify->removeClipboardListener( xThis );

    // Make asynchronous call to avoid locking SolarMutex which is the
    // root for many deadlocks, especially in conjunction with the "Windows"
    // based single thread apartment clipboard code!
    AsyncExecuteInfo* pInfo = new AsyncExecuteInfo( ASYNCEXECUTE_CMD_DISPOSING, this );
    if (!Application::PostUserEvent( LINK( nullptr, SfxClipboardChangeListener, AsyncExecuteHdl_Impl ), pInfo ))
        delete pInfo;
}

void SAL_CALL SfxClipboardChangeListener::changedContents( const datatransfer::clipboard::ClipboardEvent& )
{
    // Make asynchronous call to avoid locking SolarMutex which is the
    // root for many deadlocks, especially in conjunction with the "Windows"
    // based single thread apartment clipboard code!
    AsyncExecuteInfo* pInfo = new AsyncExecuteInfo( ASYNCEXECUTE_CMD_CHANGEDCONTENTS, this );
    if (!Application::PostUserEvent( LINK( nullptr, SfxClipboardChangeListener, AsyncExecuteHdl_Impl ), pInfo ))
        delete pInfo;
}

namespace
{
struct TableSizeType
{
    sal_Int32 nRowCount;
    sal_Int32 nColCount;
};
}

typedef std::list<uno::Reference<accessibility::XAccessibleTable>> XAccessibleTableList;

namespace
{
constexpr
bool isText(sal_Int16 nRole)
{
    return nRole == accessibility::AccessibleRole::DOCUMENT_TEXT;
}

constexpr
bool isSpreadsheet(sal_Int16 nRole)
{
    return nRole == accessibility::AccessibleRole::DOCUMENT_SPREADSHEET;
}

constexpr
bool isPresentation(sal_Int16 nRole)
{
    return nRole == accessibility::AccessibleRole::DOCUMENT_PRESENTATION;
}

constexpr
bool isDocument(sal_Int16 nRole)
{
    return isText(nRole) || isSpreadsheet(nRole) || isPresentation(nRole);
}

bool hasState(const accessibility::AccessibleEventObject& aEvent, ::sal_Int64 nState)
{
    bool res = false;
    uno::Reference< accessibility::XAccessibleContext > xContext(aEvent.Source, uno::UNO_QUERY);
    if (xContext.is())
    {
        ::sal_Int64 nStateSet = xContext->getAccessibleStateSet();
        res = (nStateSet & nState) != 0;
    }
    return res;
}

bool isFocused(const accessibility::AccessibleEventObject& aEvent)
{
    return hasState(aEvent, accessibility::AccessibleStateType::FOCUSED);
}

uno::Reference<accessibility::XAccessibleContext>
getParentContext(const uno::Reference<accessibility::XAccessibleContext>& xContext)
{
    uno::Reference<accessibility::XAccessibleContext> xParentContext;
    uno::Reference<accessibility::XAccessible> xParent = xContext->getAccessibleParent();
    if (xParent.is())
        xParentContext = uno::Reference<accessibility::XAccessibleContext>(xParent, uno::UNO_QUERY);
    return xParentContext;
}

OUString selectionEventTypeToString(sal_Int16 nEventId)
{
    using namespace accessibility;
    switch(nEventId)
    {
        case AccessibleEventId::SELECTION_CHANGED:
            return u"create"_ustr;
        case AccessibleEventId::SELECTION_CHANGED_ADD:
            return u"add"_ustr;
        case AccessibleEventId::SELECTION_CHANGED_REMOVE:
            return u"remove"_ustr;
        default:
            return u""_ustr;
    }
}

bool selectionHasToBeNotified(const uno::Reference<accessibility::XAccessibleContext>& xContext)
{
    sal_Int16 nRole = xContext->getAccessibleRole();
    return
        nRole == accessibility::AccessibleRole::GRAPHIC ||
        nRole == accessibility::AccessibleRole::EMBEDDED_OBJECT ||
        nRole == accessibility::AccessibleRole::SHAPE;
}

bool hasToBeActiveForEditing(sal_Int16 nRole)
{
    return
        nRole == accessibility::AccessibleRole::SHAPE;
}

sal_Int16 getParentRole(const uno::Reference<accessibility::XAccessibleContext>& xContext)
{
    sal_Int16 nRole = 0;
    if (xContext.is())
    {
        uno::Reference<accessibility::XAccessibleContext> xParentContext = getParentContext(xContext);
        if (xParentContext.is())
            nRole = xParentContext->getAccessibleRole();
    }
    return nRole;
}

sal_Int64 getAccessibleSiblingCount(const Reference<accessibility::XAccessibleContext>& xContext)
{
    if (!xContext.is())
        return -1;

    sal_Int64 nChildCount = 0;
    Reference<accessibility::XAccessible> xParent = xContext->getAccessibleParent();
    if (xParent.is())
    {
        Reference<accessibility::XAccessibleContext> xParentContext = xParent->getAccessibleContext();
        if (xParentContext.is())
        {
            nChildCount = xParentContext->getAccessibleChildCount();
        }
    }
    return nChildCount - 1;
}

// Put in rAncestorList all ancestors of xTable up to xAncestorTable or
// up to the first not-a-table ancestor if xAncestorTable is not an ancestor.
// xTable is included in the list, xAncestorTable is not included.
// The list is ordered from the ancient ancestor to xTable.
// Return true if xAncestorTable is an ancestor of xTable.
bool getAncestorList(XAccessibleTableList& rAncestorList,
                     const uno::Reference<accessibility::XAccessibleTable>& xTable,
                     const uno::Reference<accessibility::XAccessibleTable>& xAncestorTable = uno::Reference<accessibility::XAccessibleTable>())
{
    uno::Reference<accessibility::XAccessibleTable> xCurrentTable = xTable;
    while (xCurrentTable.is() && xCurrentTable != xAncestorTable)
    {
        rAncestorList.push_front(xCurrentTable);

        uno::Reference<accessibility::XAccessibleContext> xContext(xCurrentTable, uno::UNO_QUERY);
        xCurrentTable.clear();
        if (xContext.is())
        {
            uno::Reference<accessibility::XAccessible> xParent = xContext->getAccessibleParent();
            uno::Reference<accessibility::XAccessibleContext> xParentContext(xParent, uno::UNO_QUERY);
            if (xParentContext.is()
                    && xParentContext->getAccessibleRole() == accessibility::AccessibleRole::TABLE_CELL)
            {
                uno::Reference<accessibility::XAccessible> xCellParent = xParentContext->getAccessibleParent();
                if (xCellParent.is())
                {
                    xCurrentTable = uno::Reference<accessibility::XAccessibleTable>(xCellParent, uno::UNO_QUERY);
                }
            }
        }
    }

    return xCurrentTable.is() && xCurrentTable == xAncestorTable;
}

void lookForParentTable(const uno::Reference<accessibility::XAccessibleContext>& xContext,
                        uno::Reference<accessibility::XAccessibleTable>& xTable,
                        sal_Int64& nChildIndex)
{
    using namespace accessibility;
    uno::Reference<XAccessibleContext> xParentContext = getParentContext(xContext);
    if (xParentContext.is() && xParentContext->getAccessibleRole() == AccessibleRole::TABLE_CELL)
    {
        uno::Reference<XAccessible> xCellParent = xParentContext->getAccessibleParent();
        if (xCellParent.is())
        {
            xTable = uno::Reference<XAccessibleTable>(xCellParent, uno::UNO_QUERY);
            if (xTable.is())
            {
                nChildIndex = xParentContext->getAccessibleIndexInParent();
            }
        }
    }
}

OUString truncateText(std::u16string_view sText, sal_Int32 nNewLength)
{
    // truncate test to given length
    std::u16string_view sNewText = sText.substr(0, nNewLength);
    // try to truncate at a word
    size_t nLastPos = sNewText.rfind(u" ");
    if (nLastPos != 0 && nLastPos != std::u16string_view::npos)
        sNewText = sNewText.substr(0, nLastPos);
    return OUString(sNewText);
}

std::string stateSetToString(::sal_Int64 stateSet)
{
    static const std::string states[35] = {
            "ACTIVE""ARMED""BUSY""CHECKED""DEFUNC",
            "EDITABLE""ENABLED""EXPANDABLE""EXPANDED""FOCUSABLE",
            "FOCUSED""HORIZONTAL""ICONIFIED""INDETERMINATE""MANAGES_DESCENDANTS",
            "MODAL""MULTI_LINE""MULTI_SELECTABLE""OPAQUE""PRESSED",
            "RESIZABLE""SELECTABLE""SELECTED""SENSITIVE""SHOWING",
            "SINGLE_LINE""STALE""TRANSIENT""VERTICAL""VISIBLE",
            "MOVEABLE""DEFAULT""OFFSCREEN""COLLAPSE""CHECKABLE"
    };

    if (stateSet == 0)
        return "INVALID";
    ::sal_Int64 state = 1;
    std::string s;
    for (int i = 0; i < 35; ++i)
    {
        if (stateSet & state)
        {
            s += states[i];
            s += "|";
        }
        state <<= 1;
    }
    return s;
}

void aboutView(std::string msg,  const void* pInstance, const SfxViewShell* pViewShell)
{
    if (!pViewShell)
        return;

    SAL_INFO("lok.a11y"">>> " << msg << ": instance: " << pInstance
            << ", VIED ID: " <<  pViewShell->GetViewShellId().get() << " <<<");
}

void aboutEvent(std::string msg, const accessibility::AccessibleEventObject& aEvent)
{
    try
    {
        uno::Reference< accessibility::XAccessible > xSource(aEvent.Source, uno::UNO_QUERY);
        if (xSource.is())
        {
            uno::Reference< accessibility::XAccessibleContext > xContext =
                    xSource->getAccessibleContext();

            if (xContext.is())
            {
                SAL_INFO("lok.a11y", msg << ": event id: " << aEvent.EventId
                        << "\n xSource: " << xSource.get()
                        << "\n role: " << xContext->getAccessibleRole()
                        << "\n name: " << xContext->getAccessibleName()
                        << "\n index in parent: " << xContext->getAccessibleIndexInParent()
                        << "\n state set: " << stateSetToString(xContext->getAccessibleStateSet())
                        << "\n parent: " << xContext->getAccessibleParent().get()
                        << "\n child count: " << xContext->getAccessibleChildCount());
            }
            else
            {
                SAL_INFO("lok.a11y", msg << ": event id: " << aEvent.EventId
                                         << ", no accessible context!");
            }
        }
        else
        {
            SAL_INFO("lok.a11y", msg << ": event id: " << aEvent.EventId
                                     << ", no accessible source!");
        }
        uno::Reference< accessibility::XAccessible > xOldValue;
        aEvent.OldValue >>= xOldValue;
        if (xOldValue.is())
        {
            uno::Reference< accessibility::XAccessibleContext > xContext =
                    xOldValue->getAccessibleContext();

            if (xContext.is())
            {
                SAL_INFO("lok.a11y", msg << ": "
                           "\n xOldValue: " << xOldValue.get()
                        << "\n role: " << xContext->getAccessibleRole()
                        << "\n name: " << xContext->getAccessibleName()
                        << "\n index in parent: " << xContext->getAccessibleIndexInParent()
                        << "\n state set: " << stateSetToString(xContext->getAccessibleStateSet())
                        << "\n parent: " << xContext->getAccessibleParent().get()
                        << "\n child count: " << xContext->getAccessibleChildCount());
            }
        }
        uno::Reference< accessibility::XAccessible > xNewValue;
        aEvent.NewValue >>= xNewValue;
        if (xNewValue.is())
        {
            uno::Reference< accessibility::XAccessibleContext > xContext =
                    xNewValue->getAccessibleContext();

            if (xContext.is())
            {
                SAL_INFO("lok.a11y", msg << ": "
                           "\n xNewValue: " << xNewValue.get()
                        << "\n role: " << xContext->getAccessibleRole()
                        << "\n name: " << xContext->getAccessibleName()
                        << "\n index in parent: " << xContext->getAccessibleIndexInParent()
                        << "\n state set: " << stateSetToString(xContext->getAccessibleStateSet())
                        << "\n parent: " << xContext->getAccessibleParent().get()
                        << "\n child count: " << xContext->getAccessibleChildCount());
            }
        }
    }
    catchconst lang::IndexOutOfBoundsException& /*e*/ )
    {
        LOK_WARN("lok.a11y""Focused object has invalid index in parent");
    }
}

sal_Int32 getListPrefixSize(const uno::Reference<css::accessibility::XAccessibleText>& xAccText)
{
    if (!xAccText.is())
        return 0;

    OUString sText = xAccText->getText();
    sal_Int32 nLength = sText.getLength();
    if (nLength <= 0)
        return 0;

    css::uno::Sequence< css::beans::PropertyValue > aRunAttributeList;
    css::uno::Sequence< OUString > aRequestedAttributes = {UNO_NAME_NUMBERING_LEVEL, UNO_NAME_NUMBERING};
    aRunAttributeList = xAccText->getCharacterAttributes(0, aRequestedAttributes);

    sal_Int16 nLevel = -1;
    bool bIsCounted = false;
    for (const auto& attribute: aRunAttributeList)
    {
        if (attribute.Name.isEmpty())
            continue;
        if (attribute.Name == UNO_NAME_NUMBERING_LEVEL)
           attribute.Value >>= nLevel;
        else if (attribute.Name == UNO_NAME_NUMBERING)
           attribute.Value >>= bIsCounted;
    }
    if (nLevel < 0 || !bIsCounted)
        return 0;

    css::accessibility::TextSegment aTextSegment =
        xAccText->getTextAtIndex(0, css::accessibility::AccessibleTextType::ATTRIBUTE_RUN);

    SAL_INFO("lok.a11y""getListPrefixSize: prefix: " << aTextSegment.SegmentText << ", level: " << nLevel);

    return aTextSegment.SegmentEnd;
}

void aboutTextFormatting(std::string msg, const uno::Reference<css::accessibility::XAccessibleText>& xAccText)
{
    if (!xAccText.is())
        return;

    OUString sText = xAccText->getText();
    sal_Int32 nLength = sText.getLength();
    if (nLength <= 0)
        return;

    css::uno::Reference<css::accessibility::XAccessibleTextAttributes>
        xAccTextAttr(xAccText, uno::UNO_QUERY);
    css::uno::Sequence< OUString > aRequestedAttributes;

    sal_Int32 nPos = 0;
    while (nPos < nLength)
    {
        css::accessibility::TextSegment aTextSegment =
                xAccText->getTextAtIndex(nPos, css::accessibility::AccessibleTextType::ATTRIBUTE_RUN);
        SAL_INFO("lok.a11y", msg << ": "
                "text segment: '" << aTextSegment.SegmentText
                << "', start: " << aTextSegment.SegmentStart
                << ", end: " << aTextSegment.SegmentEnd);

        css::uno::Sequence< css::beans::PropertyValue > aRunAttributeList;
        if (xAccTextAttr.is())
        {
            aRunAttributeList = xAccTextAttr->getRunAttributes(nPos, aRequestedAttributes);
        }
        else
        {
            aRunAttributeList = xAccText->getCharacterAttributes(nPos, aRequestedAttributes);
        }

        sal_Int32 nSize = aRunAttributeList.getLength();
        SAL_INFO("lok.a11y",
                 msg << ": attribute list size: " << nSize);
        if (nSize)
        {
            OUString sValue;
            OUString sAttributes = u"{ "_ustr;
            for (const auto& attribute: aRunAttributeList)
            {
                if (attribute.Name.isEmpty())
                    continue;

                if (attribute.Name == "CharHeight" || attribute.Name == "CharWeight")
                {
                    float fValue = 0;
                    attribute.Value >>= fValue;
                    sValue = OUString::number(fValue);
                }
                else if (attribute.Name == "CharPosture")
                {
                    awt::FontSlant nValue = awt::FontSlant_NONE;
                    attribute.Value >>= nValue;
                    sValue = OUString::number(static_cast<unsigned int>(nValue));
                }
                else if (attribute.Name == "CharUnderline")
                {
                    sal_Int16 nValue = 0;
                    attribute.Value >>= nValue;
                    sValue = OUString::number(nValue);
                }
                else if (attribute.Name == "CharFontName")
                {
                    attribute.Value >>= sValue;
                }
                else if (attribute.Name == "Rsid")
                {
                    sal_uInt32 nValue = 0;
                    attribute.Value >>= nValue;
                    sValue = OUString::number(nValue);
                }
                else if (attribute.Name == UNO_NAME_NUMBERING_LEVEL)
                {
                    sal_Int16 nValue(-1);
                    attribute.Value >>= nValue;
                    sValue = OUString::number(nValue);
                }
                else if (attribute.Name == UNO_NAME_NUMBERING)
                {
                    bool bValue(false);
                    attribute.Value >>= bValue;
                    sValue = OUString::boolean(bValue);
                }
                else if (attribute.Name == UNO_NAME_NUMBERING_RULES)
                {
                    attribute.Value >>= sValue;
                }

                if (!sValue.isEmpty())
                {
                    if (sAttributes != "{ ")
                        sAttributes += ", ";
                    sAttributes += attribute.Name + ": " + sValue;
                    sValue = "";
                }
            }
            sAttributes += " }";
            SAL_INFO("lok.a11y",
                     msg << ": " << sAttributes);
        }
        nPos = aTextSegment.SegmentEnd + 1;
    }
}

void aboutParagraph(const std::string& msg, const OUString& rsParagraphContent, sal_Int32 nCaretPosition,
                    sal_Int32 nSelectionStart, sal_Int32 nSelectionEnd, sal_Int32 nListPrefixLength,
                    bool force = false)
{
    SAL_INFO("lok.a11y", msg << ": "
            "\n text content: \"" << rsParagraphContent << "\""
            "\n caret pos: " << nCaretPosition
            << "\n selection: start: " << nSelectionStart << ", end: " << nSelectionEnd
            << "\n list prefix length: " << nListPrefixLength
            << "\n force: " << force
            );
}

void aboutParagraph(const std::string& msg, const uno::Reference<css::accessibility::XAccessibleText>& xAccText,
                    bool force = false)
{
    if (!xAccText.is())
        return;

    OUString sText = xAccText->getText();
    sal_Int32 nCaretPosition = xAccText->getCaretPosition();
    sal_Int32 nSelectionStart = xAccText->getSelectionStart();
    sal_Int32 nSelectionEnd = xAccText->getSelectionEnd();
    sal_Int32 nListPrefixLength = getListPrefixSize(xAccText);
    aboutParagraph(msg, sText, nCaretPosition, nSelectionStart, nSelectionEnd, nListPrefixLength, force);
}

void aboutFocusedCellChanged(sal_Int32 nOutCount, const std::vector<TableSizeType>& ;aInList,
                             sal_Int32 nRow, sal_Int32 nCol, sal_Int32 nRowSpan, sal_Int32 nColSpan)
{
    std::stringstream inListStream;
    inListStream << "[ ";
    for (const auto& rTableSize: aInList)
    {
        inListStream << "{ rowCount: " << rTableSize.nRowCount << " colCount: " << rTableSize.nColCount << " } ";
    }
    inListStream << "]";

    SAL_INFO("lok.a11y""LOKDocumentFocusListener::notifyFocusedCellChanged: "
            "\n outCount: " << nOutCount
            << "\n inList: " << inListStream.str()
            << "\n row: " << nRow
            << "\n column: " << nCol
            << "\n rowSpan: " << nRowSpan
            << "\n colSpan: " << nColSpan
            );
}
// anonymous namespace

class LOKDocumentFocusListener :
    public ::cppu::WeakImplHelper< accessibility::XAccessibleEventListener >
{
    static constexpr sal_Int64 MAX_ATTACHABLE_CHILDREN = 100;

    const SfxViewShell* m_pViewShell;
    sal_Int16 m_nDocumentType;
    std::unordered_set<uno::Reference<uno::XInterface>> m_aRefList;
    OUString m_sFocusedParagraph;
    sal_Int32 m_nCaretPosition;
    sal_Int32 m_nSelectionStart;
    sal_Int32 m_nSelectionEnd;
    sal_Int32 m_nListPrefixLength;
    uno::Reference<accessibility::XAccessibleTable> m_xLastTable;
    OUString m_sSelectedText;
    bool m_bIsEditingCell;
    // used for text content of a shape
    bool m_bIsEditingInSelection;
    OUString m_sSelectedCellAddress;
    uno::Reference<accessibility::XAccessible> m_xSelectedObject;

public:
    explicit LOKDocumentFocusListener(const SfxViewShell* pViewShell);

    /// @throws lang::IndexOutOfBoundsException
    /// @throws uno::RuntimeException
    void attachRecursive(
        const uno::Reference< accessibility::XAccessible >& xAccessible
    );

    /// @throws lang::IndexOutOfBoundsException
    /// @throws uno::RuntimeException
    void attachRecursive(
        const uno::Reference< accessibility::XAccessible >& xAccessible,
        const uno::Reference< accessibility::XAccessibleContext >& xContext
    );

    /// @throws lang::IndexOutOfBoundsException
    /// @throws uno::RuntimeException
    void attachRecursive(
        const uno::Reference< accessibility::XAccessible >& xAccessible,
        const uno::Reference< accessibility::XAccessibleContext >& xContext,
        const sal_Int64 nStateSet
    );

    /// @throws lang::IndexOutOfBoundsException
    /// @throws uno::RuntimeException
    void detachRecursive(
        const uno::Reference< accessibility::XAccessible >& xAccessible,
        bool bForce = false
    );

    /// @throws lang::IndexOutOfBoundsException
    /// @throws uno::RuntimeException
    void detachRecursive(
        const uno::Reference< accessibility::XAccessibleContext >& xContext,
        bool bForce = false
    );

    /// @throws lang::IndexOutOfBoundsException
    /// @throws uno::RuntimeException
    void detachRecursive(
        const uno::Reference< accessibility::XAccessibleContext >& xContext,
        const sal_Int64 nStateSet,
        bool bForce = false
    );

    /// @throws lang::IndexOutOfBoundsException
    /// @throws uno::RuntimeException
    static uno::Reference< accessibility::XAccessible > getAccessible(const lang::EventObject& aEvent );

    // XEventListener
    virtual void SAL_CALL disposing( const lang::EventObject& Source ) override;

    // XAccessibleEventListener
    virtual void SAL_CALL notifyEvent( const accessibility::AccessibleEventObject& aEvent ) override;

    void notifyEditingInSelectionState(bool bParagraph = true);
    void notifyFocusedParagraphChanged(bool force = false);
    void notifyCaretChanged();
    void notifyTextSelectionChanged();
    void notifyFocusedCellChanged(sal_Int32 nOutCount, const std::vector<TableSizeType>&&nbsp;aInList, sal_Int32 nRow, sal_Int32 nCol, sal_Int32 nRowSpan, sal_Int32 nColSpan);
    void notifySelectionChanged(const uno::Reference<accessibility::XAccessible>& xAccObj, const OUString& sAction);

    OUString getFocusedParagraph() const;
    int getCaretPosition() const;

private:
    void paragraphPropertiesToTree(boost::property_tree::ptree& aPayloadTree, bool force = falseconst;
    void paragraphPropertiesToJson(std::string& aPayload, bool force = falseconst;
    bool updateParagraphInfo(const uno::Reference<css::accessibility::XAccessibleText>&&nbsp;xAccText,
                             bool force, const std::string& msg = "");
    void updateAndNotifyParagraph(const uno::Reference<css::accessibility::XAccessibleText>& xAccText,
                                  bool force, const std::string& msg = "");
    void resetParagraphInfo();
    void onFocusedParagraphInWriterTable(const uno::Reference<accessibility::XAccessibleTable>& xTable,
                                         sal_Int64 nChildIndex,
                                         const uno::Reference<accessibility::XAccessibleText>& xAccText);
    uno::Reference< accessibility::XAccessible >
    getSelectedObject(const accessibility::AccessibleEventObject& aEvent) const;
    void onShapeSelectionChanged(const Reference<accessibility::XAccessible>& xSelectedObject,
                                 const OUString& sAction);
};

LOKDocumentFocusListener::LOKDocumentFocusListener(const SfxViewShell* pViewShell)
    : m_pViewShell(pViewShell)
    , m_nDocumentType(0)
    , m_nCaretPosition(0)
    , m_nSelectionStart(0)
    , m_nSelectionEnd(0)
    , m_nListPrefixLength(0)
    , m_bIsEditingCell(false)
    , m_bIsEditingInSelection(false)
{
}

void LOKDocumentFocusListener::paragraphPropertiesToTree(boost::property_tree::ptree& aPayloadTree, bool force) const
{
    bool bLeftToRight = m_nCaretPosition == m_nSelectionEnd;
    aPayloadTree.put("content", m_sFocusedParagraph.toUtf8().getStr());
    aPayloadTree.put("position", m_nCaretPosition);
    aPayloadTree.put("start", bLeftToRight ? m_nSelectionStart : m_nSelectionEnd);
    aPayloadTree.put("end", bLeftToRight ? m_nSelectionEnd : m_nSelectionStart);
    if (m_nListPrefixLength > 0)
        aPayloadTree.put("listPrefixLength", m_nListPrefixLength);
    if (force)
        aPayloadTree.put("force", 1);
}

void LOKDocumentFocusListener::paragraphPropertiesToJson(std::string& aPayloadbool force) const
{
    boost::property_tree::ptree aPayloadTree;
    paragraphPropertiesToTree(aPayloadTree, force);
    std::stringstream aStream;
    boost::property_tree::write_json(aStream, aPayloadTree);
    aPayload = aStream.str();
}

OUString LOKDocumentFocusListener::getFocusedParagraph() const
{
    aboutView("LOKDocumentFocusListener::getFocusedParagraph"this, m_pViewShell);
    aboutParagraph("LOKDocumentFocusListener::getFocusedParagraph",
                   m_sFocusedParagraph, m_nCaretPosition,
                   m_nSelectionStart, m_nSelectionEnd, m_nListPrefixLength);

    std::string aPayload;
    paragraphPropertiesToJson(aPayload);
    OUString sRet = OUString::fromUtf8(aPayload);
    return sRet;
}

int LOKDocumentFocusListener::getCaretPosition() const
{
    aboutView("LOKDocumentFocusListener::getCaretPosition"this, m_pViewShell);
    SAL_INFO("lok.a11y""LOKDocumentFocusListener::getCaretPosition: " << m_nCaretPosition);
    return m_nCaretPosition;
}

// notifyEditingInSelectionState
// Used for notifying when editing becomes active/disabled for a shape
// bParagraph: should we append currently focused paragraph ?
// The problem is that the initially focused paragraph could not be the one user has clicked on,
// when there are more than a single paragraph.
// So in some case sending the focused paragraph could be misleading.
void LOKDocumentFocusListener::notifyEditingInSelectionState(bool bParagraph)
{
    aboutView("LOKDocumentFocusListener::notifyEditingInSelectionState"this, m_pViewShell);

    boost::property_tree::ptree aPayloadTree;
    bool bIsCell = !m_sSelectedCellAddress.isEmpty();
    aPayloadTree.put("cell", bIsCell ? 1 : 0);
    if (bIsCell)
    {
        aPayloadTree.put("enabled", m_bIsEditingCell ? 1 : 0);
        if (m_bIsEditingCell)
        {
            aPayloadTree.put("selection", m_sSelectedCellAddress);
            if (bParagraph)
                aPayloadTree.put("paragraph", m_sFocusedParagraph);
        }
    }
    else
    {
        aPayloadTree.put("enabled", m_bIsEditingInSelection ? 1 : 0);
        if (m_bIsEditingInSelection && m_xSelectedObject.is())
        {
            uno::Reference<accessibility::XAccessibleContext> xContext = m_xSelectedObject->getAccessibleContext();
            if (xContext.is())
            {
                OUString sSelectionDescr = xContext->getAccessibleName();
                sSelectionDescr = sSelectionDescr.trim();
                aPayloadTree.put("selection", sSelectionDescr);
                if (bParagraph)
                    aPayloadTree.put("paragraph", m_sFocusedParagraph);
            }
        }
    }

    std::stringstream aStream;
    boost::property_tree::write_json(aStream, aPayloadTree);
    std::string aPayload = aStream.str();
    if (m_pViewShell)
    {
        SAL_INFO("lok.a11y""LOKDocumentFocusListener::notifyEditingInSelectionState: payload: \n" << aPayload);
        m_pViewShell->libreOfficeKitViewCallback(LOK_CALLBACK_A11Y_EDITING_IN_SELECTION_STATE, aPayload.c_str());
    }
}

/// notifyFocusedParagraphChanged
//
//  Notify content, caret position and text selection start/end for the focused paragraph
//  in current view.
//  For focused we don't mean to be necessarily the currently focused accessibility node.
//  It's enough that the caret is present in the paragraph (position != -1).
//  In fact each view has its own accessibility node per each text paragraph.
//  Anyway there can be only one focused accessibility node at time.
//  So when text changes are performed in one view, both accessibility nodes emit
//  a text changed event, anyway only the accessibility node belonging to the view
//  where the text change has occurred is the focused one.
//
//  force: when true update the clipboard content even if client is composing.
//
//  Usually when editing on the client involves composing the clipboard area updating
//  is skipped until the composition is over.
//  On the contrary the composition would be aborted, making dictation not possible.
//  Anyway when the text change has been performed by another view we are in due
//  to update the clipboard content even if the user is in the middle of a composition.
void LOKDocumentFocusListener::notifyFocusedParagraphChanged(bool force)
{
    aboutView("LOKDocumentFocusListener::notifyFocusedParagraphChanged"this, m_pViewShell);
    std::string aPayload;
    paragraphPropertiesToJson(aPayload, force);
    if (m_pViewShell)
    {
        aboutParagraph("LOKDocumentFocusListener::notifyFocusedParagraphChanged",
                       m_sFocusedParagraph, m_nCaretPosition,
                       m_nSelectionStart, m_nSelectionEnd, m_nListPrefixLength, force);

        m_pViewShell->libreOfficeKitViewCallback(LOK_CALLBACK_A11Y_FOCUS_CHANGED, aPayload.c_str());
    }
}

void LOKDocumentFocusListener::notifyCaretChanged()
{
    aboutView("LOKDocumentFocusListener::notifyCaretChanged"this, m_pViewShell);
    boost::property_tree::ptree aPayloadTree;
    aPayloadTree.put("position", m_nCaretPosition);
    std::stringstream aStream;
    boost::property_tree::write_json(aStream, aPayloadTree);
    std::string aPayload = aStream.str();
    if (m_pViewShell)
    {
        SAL_INFO("lok.a11y""LOKDocumentFocusListener::notifyCaretChanged: " << m_nCaretPosition);
        m_pViewShell->libreOfficeKitViewCallback(LOK_CALLBACK_A11Y_CARET_CHANGED, aPayload.c_str());
    }
}

void LOKDocumentFocusListener::notifyTextSelectionChanged()
{
    aboutView("LOKDocumentFocusListener::notifyTextSelectionChanged"this, m_pViewShell);
    bool bLeftToRight = m_nCaretPosition == m_nSelectionEnd;
    boost::property_tree::ptree aPayloadTree;
    aPayloadTree.put("start", bLeftToRight ? m_nSelectionStart : m_nSelectionEnd);
    aPayloadTree.put("end", bLeftToRight ? m_nSelectionEnd : m_nSelectionStart);
    std::stringstream aStream;
    boost::property_tree::write_json(aStream, aPayloadTree);
    std::string aPayload = aStream.str();
    if (m_pViewShell)
    {
        SAL_INFO("lok.a11y",  "LOKDocumentFocusListener::notifyTextSelectionChanged: "
                "start: " << m_nSelectionStart << ", end: " << m_nSelectionEnd);
        m_pViewShell->libreOfficeKitViewCallback(LOK_CALLBACK_A11Y_TEXT_SELECTION_CHANGED, aPayload.c_str());
    }
}

void LOKDocumentFocusListener::notifyFocusedCellChanged(
        sal_Int32 nOutCount, const std::vector<TableSizeType>& aInList,
        sal_Int32 nRow, sal_Int32 nCol, sal_Int32 nRowSpan, sal_Int32 nColSpan)
{
    aboutView("LOKDocumentFocusListener::notifyTablePositionChanged"this, m_pViewShell);
    boost::property_tree::ptree aPayloadTree;
    if (nOutCount > 0)
    {
        aPayloadTree.put("outCount", nOutCount);
    }
    if (!aInList.empty())
    {
        boost::property_tree::ptree aInListNode;
        for (const auto& rTableSize: aInList)
        {
            boost::property_tree::ptree aTableSizeNode;
            aTableSizeNode.put("rowCount", rTableSize.nRowCount);
            aTableSizeNode.put("colCount", rTableSize.nColCount);

            aInListNode.push_back(std::make_pair(std::string(), aTableSizeNode));
        }
        aPayloadTree.add_child("inList", aInListNode);
    }

    aPayloadTree.put("row", nRow);
    aPayloadTree.put("col", nCol);

    if (nRowSpan > 1)
    {
        aPayloadTree.put("rowSpan", nRowSpan);
    }
    if (nColSpan > 1)
    {
        aPayloadTree.put("colSpan", nColSpan);
    }

    boost::property_tree::ptree aContentNode;
    paragraphPropertiesToTree(aContentNode);
    aPayloadTree.add_child("paragraph", aContentNode);

    std::stringstream aStream;
    boost::property_tree::write_json(aStream, aPayloadTree);
    std::string aPayload = aStream.str();
    if (m_pViewShell)
    {
        aboutFocusedCellChanged(nOutCount, aInList, nRow, nCol, nRowSpan, nColSpan);
        aboutParagraph("LOKDocumentFocusListener::notifyFocusedCellChanged: paragraph: ",
                       m_sFocusedParagraph, m_nCaretPosition, m_nSelectionStart, m_nSelectionEnd,
                       m_nListPrefixLength, false);

        m_pViewShell->libreOfficeKitViewCallback(LOK_CALLBACK_A11Y_FOCUSED_CELL_CHANGED, aPayload.c_str());
    }
}

void LOKDocumentFocusListener::notifySelectionChanged(const uno::Reference<accessibility::XAccessible>& xAccObj,
                                                      const OUString& sAction)
{
    using namespace accessibility;
    if (!xAccObj.is())
        return;

    aboutView("LOKDocumentFocusListener::notifySelectionChanged"this, m_pViewShell);
    uno::Reference<XAccessibleContext> xContext = xAccObj->getAccessibleContext();
    if (xContext.is())
    {
        OUString sName = xContext->getAccessibleName();
        sName = sName.trim();
        if (sName == "GraphicObjectShape")
            sName = "Graphic";

        // check for text content and send it with some limitations:
        // no more than 10 paragraphs, no more than 1000 chars
        bool bIsCell = xContext->getAccessibleRole() == AccessibleRole::TABLE_CELL;
        OUString sTextContent;
        if (sAction == "create" || sAction == "add")
        {
            const sal_Int64 nMaxJoinedParagraphs = 10;
            const sal_Int32 nMaxTextContentLength = 1000;
            if (bIsCell)
            {
                uno::Reference<XAccessibleText> xAccText(xAccObj, uno::UNO_QUERY);
                if (xAccText.is())
                {
                    sTextContent = xAccText->getText();
                    sal_Int32 nTextLength = sTextContent.getLength();
                    if (nTextLength > nMaxTextContentLength)
                    {
                        sTextContent = truncateText(sTextContent, nMaxTextContentLength);
                    }
                }
            }
            else
            {
                sal_Int32 nTotalTextLength = 0;
                sal_Int64 nChildCount = xContext->getAccessibleChildCount();
                if (nChildCount > nMaxJoinedParagraphs)
                    nChildCount = nMaxJoinedParagraphs;
                for (sal_Int64 i = 0; i < nChildCount; ++i)
                {
                    uno::Reference<XAccessible> xChild = xContext->getAccessibleChild(i);
                    uno::Reference<XAccessibleText> xAccText(xChild, uno::UNO_QUERY);
                    if (!xAccText.is())
                        continue;
                    OUString sText = xAccText->getText();
                    sal_Int32 nTextLength = sText.getLength();
                    if (nTextLength < 1)
                        continue;
                    if (nTotalTextLength + nTextLength < nMaxTextContentLength)
                    {
                        nTotalTextLength += nTextLength;
                        sTextContent += sText + " \n";
                    }
                    else
                    {
                        // truncate paragraph
                        sal_Int32 nNewLength = nMaxTextContentLength - nTotalTextLength;
                        sTextContent += truncateText(sText, nNewLength);
                        break;
                    }
                }
            }
        }

        boost::property_tree::ptree aPayloadTree;
        aPayloadTree.put("cell", bIsCell ? 1 : 0);
        aPayloadTree.put("action", sAction);
        aPayloadTree.put("name", sName);
        if (!sTextContent.isEmpty())
            aPayloadTree.put("text", sTextContent);
        std::stringstream aStream;
        boost::property_tree::write_json(aStream, aPayloadTree);
        std::string aPayload = aStream.str();
        if (m_pViewShell)
        {
            SAL_INFO("lok.a11y",  "LOKDocumentFocusListener::notifySelectionChanged: "
                                     "action: " << sAction << ", name: " << sName);
            m_pViewShell->libreOfficeKitViewCallback(LOK_CALLBACK_A11Y_SELECTION_CHANGED, aPayload.c_str());
        }
    }
}

void LOKDocumentFocusListener::disposing( const lang::EventObject& aEvent )
{
    // Unref the object here, but do not remove as listener since the object
    // might no longer be in a state that safely allows this.
    if( aEvent.Source.is() )
        m_aRefList.erase(aEvent.Source);

}

bool LOKDocumentFocusListener::updateParagraphInfo(const uno::Reference<css::accessibility::XAccessibleText>& xAccText,
                                                   bool force, const std::string& msg)
{
    if (!xAccText.is())
        return false;

    bool bNotify = false;
    // If caret is present inside the paragraph (pos != -1), it means that paragraph has focus in the current view.
    sal_Int32 nCaretPosition = xAccText->getCaretPosition();
    if (nCaretPosition >= 0)
    {
        OUString sText = xAccText->getText();
        m_nCaretPosition = nCaretPosition;
        m_nSelectionStart = xAccText->getSelectionStart();
        m_nSelectionEnd = xAccText->getSelectionEnd();
        m_nListPrefixLength = getListPrefixSize(xAccText);

        // Inside a text shape when there is no selection, selection-start and selection-end are
        // set to current caret position instead of -1. Moreover, inside a text shape pressing
        // delete or backspace with an empty selection really deletes text and not only the empty
        // selection as it occurs in a text paragraph in Writer.
        // So whenever selection-start == selection-end, and we are inside a shape we need
        // to set these parameters to -1 in order to have the client to handle delete and
        // backspace properly.
        if (m_nSelectionStart == m_nSelectionEnd && m_nSelectionStart != -1)
        {
            uno::Reference<accessibility::XAccessibleContext> xContext(xAccText, uno::UNO_QUERY);
            sal_Int16 nParentRole = getParentRole(xContext);
            if (nParentRole == accessibility::AccessibleRole::SHAPE ||
                nParentRole == accessibility::AccessibleRole::TEXT_FRAME) // spreadsheet cell editing
                m_nSelectionStart = m_nSelectionEnd = -1;
        }

        // In case only caret position or text selection are different we can rely on specific events.
        if (m_sFocusedParagraph != sText)
        {
            m_sFocusedParagraph = sText;
            bNotify = true;
        }
    }
    else
    {
        SAL_WARN("lok.a11y",
                 "LOKDocumentFocusListener::updateParagraphInfo: skipped since no caret is present");
    }

    std::string header = "LOKDocumentFocusListener::updateParagraphInfo";
    if (msg.size())
        header += ": " + msg;
    aboutParagraph(header, xAccText, force);
    return bNotify;

}

void LOKDocumentFocusListener::updateAndNotifyParagraph(
        const uno::Reference<css::accessibility::XAccessibleText>& xAccText,
        bool force, const std::string& msg)
{
    if (updateParagraphInfo(xAccText, force, msg))
        notifyFocusedParagraphChanged(force);
}

void LOKDocumentFocusListener::resetParagraphInfo()
{
    m_sFocusedParagraph = "";
    m_nCaretPosition = 0;
    m_nSelectionStart = -1;
    m_nSelectionEnd = -1;
    m_nListPrefixLength = 0;
}

// For a presentation document when an accessible event of type SELECTION_CHANGED_XXX occurs
// the selected (or unselected) object is put in NewValue, instead for a text document
// the selected object is put in Source.
// The following function helps to retrieve the selected object independently on where it has been put.
uno::Reference< accessibility::XAccessible >
LOKDocumentFocusListener::getSelectedObject(const accessibility::AccessibleEventObject& aEvent) const
{
    uno::Reference< accessibility::XAccessible > xSelectedObject;
    if (isText(m_nDocumentType))
    {
        xSelectedObject.set(aEvent.Source, uno::UNO_QUERY);
    }
    else
    {
        aEvent.NewValue >>= xSelectedObject;
    }
    return xSelectedObject;
}

void LOKDocumentFocusListener::onShapeSelectionChanged(
    const uno::Reference<accessibility::XAccessible>& xSelectedObject,
    const OUString& sAction)
{
    // when a shape is selected or unselected we could need to notify that text content editing
    // is no more active, that allows on the client side to prevent default input.
    resetParagraphInfo();
    if (m_bIsEditingInSelection)
    {
        m_bIsEditingInSelection = false;
        notifyEditingInSelectionState();
    }
    notifySelectionChanged(xSelectedObject, sAction);
}

void LOKDocumentFocusListener::onFocusedParagraphInWriterTable(
    const uno::Reference<accessibility::XAccessibleTable>& xTable,
    sal_Int64 nChildIndex,
    const uno::Reference<accessibility::XAccessibleText>& xAccText
)
{
    std::vector<TableSizeType> aInList;
    sal_Int32 nOutCount = 0;

    if (m_xLastTable.is())
    {
        if (xTable != m_xLastTable)
        {
            // do we get in one or more nested tables ?
            // check if xTable is a descendant of m_xLastTable
            XAccessibleTableList newTableAncestorList;
            bool isLastAncestorOfNew = getAncestorList(newTableAncestorList, xTable, m_xLastTable);
            bool isNewAncestorOfLast = false;
            if (!isLastAncestorOfNew)
            {
                // do we get out of one or more nested tables ?
                // check if m_xLastTable is a descendant of xTable
                XAccessibleTableList lastTableAncestorList;
                isNewAncestorOfLast = getAncestorList(lastTableAncestorList, m_xLastTable, xTable);
                // we have to notify "out of table" for all  m_xLastTable ancestors up to xTable
                // or the first not-a-table ancestor
                nOutCount = lastTableAncestorList.size();
            }
            if (isLastAncestorOfNew || !isNewAncestorOfLast)
            {
                // we have to notify row/col count for all xTable ancestors starting from the ancestor
                // which is a child of m_xLastTable (isLastAncestorOfNew) or the first not-a-table ancestor
                for (const auto& ancestor: newTableAncestorList)
                {
                    TableSizeType aTableSize{ancestor->getAccessibleRowCount(),
                                              ancestor->getAccessibleColumnCount()};
                    aInList.push_back(aTableSize);
                }
            }
        }
    }
    else
    {
        // cursor was not inside any table and gets inside one or more tables
        // we have to notify row/col count for all xTable ancestors starting from first not-a-table ancestor
        XAccessibleTableList newTableAncestorList;
        getAncestorList(newTableAncestorList, xTable);
        for (const auto& ancestor: newTableAncestorList)
        {
            TableSizeType aTableSize{ancestor->getAccessibleRowCount(),
                                      ancestor->getAccessibleColumnCount()};
            aInList.push_back(aTableSize);
        }
    }

    // we have to notify current row/col of xTable and related row/col span
    sal_Int32 nRow = xTable->getAccessibleRow(nChildIndex);
    sal_Int32 nCol = xTable->getAccessibleColumn(nChildIndex);
    sal_Int32 nRowSpan = xTable->getAccessibleRowExtentAt(nRow, nCol);
    sal_Int32 nColSpan = xTable->getAccessibleColumnExtentAt(nRow, nCol);

    m_xLastTable = xTable;
    updateParagraphInfo(xAccText, false"STATE_CHANGED: FOCUSED");
    notifyFocusedCellChanged(nOutCount, aInList, nRow, nCol, nRowSpan, nColSpan);
}

void LOKDocumentFocusListener::notifyEvent(const accessibility::AccessibleEventObject& aEvent)
{
    using namespace accessibility;
    aboutView("LOKDocumentFocusListener::notifyEvent"this, m_pViewShell);

    try
    {
        aboutEvent("LOKDocumentFocusListener::notifyEvent", aEvent);

        switch (aEvent.EventId)
        {
            case AccessibleEventId::STATE_CHANGED:
            {
                // logging
                sal_Int64 nState = accessibility::AccessibleStateType::INVALID;
                aEvent.NewValue >>= nState;
                sal_Int64 nOldState = accessibility::AccessibleStateType::INVALID;
                aEvent.OldValue >>= nOldState;
                SAL_INFO("lok.a11y""LOKDocumentFocusListener::notifyEvent: STATE_CHANGED: "
                                        " New State: " << stateSetToString(nState)
                                     << ", Old State: " << stateSetToString(nOldState));

                // check validity
                uno::Reference< XAccessible > xAccessibleObject = getAccessible(aEvent);
                if (!xAccessibleObject.is())
                    return;
                uno::Reference<XAccessibleContext> xContext(aEvent.Source, uno::UNO_QUERY);
                if (!xContext)
                    return;

                sal_Int16 nRole = xContext->getAccessibleRole();

                if (nRole == AccessibleRole::PARAGRAPH)
                {
                    uno::Reference<XAccessibleText> xAccText(xAccessibleObject, uno::UNO_QUERY);
                    if (!xAccText.is())
                        return;

                    switch (nState)
                    {
                        case AccessibleStateType::ACTIVE:
                        {
                            if (!m_bIsEditingInSelection && hasToBeActiveForEditing(getParentRole(xContext)))
                            {
                                m_bIsEditingInSelection = true;
                            }
                            break;
                        }
                        case AccessibleStateType::FOCUSED:
                        {
                            if (m_bIsEditingInSelection && m_xSelectedObject.is())
                            {
                                updateParagraphInfo(xAccText, true"STATE_CHANGED: FOCUSED");
                                notifyEditingInSelectionState(getAccessibleSiblingCount(xContext) == 0);
                                notifyFocusedParagraphChanged(true);
                                // we clear selected object so when editing is over but shape is
                                // still selected, the selection event is notified the same to the client
                                m_xSelectedObject.clear();
                                return;
                            }
                            if (isText(m_nDocumentType))
                            {
                                // check if we are inside a table: in case notify table and current cell info
                                bool isInsideTable = false;
                                uno::Reference<XAccessibleTable> xTable;
                                sal_Int64 nChildIndex = 0;
                                lookForParentTable(xContext, xTable, nChildIndex);
                                if (xTable.is())
                                {
                                    onFocusedParagraphInWriterTable(xTable, nChildIndex, xAccText);
                                    isInsideTable = true;
                                }
                                // paragraph is not inside any table
                                if (!isInsideTable)
                                {
                                    if (m_xLastTable.is())
                                    {
                                        // we get out one or more tables
                                        // we have to notify "out of table" for all m_xLastTable ancestors
                                        // up to the first not-a-table ancestor
                                        XAccessibleTableList lastTableAncestorList;
                                        getAncestorList(lastTableAncestorList, m_xLastTable);
                                        sal_Int32 nOutCount = lastTableAncestorList.size();
                                        // no more inside a table
                                        m_xLastTable.clear();
                                        // notify
                                        std::vector<TableSizeType> aInList;
                                        updateParagraphInfo(xAccText, false"STATE_CHANGED: FOCUSED");
                                        notifyFocusedCellChanged(nOutCount, aInList, -1, -1, 1, 1);
                                    }
                                    else
                                    {
                                        updateAndNotifyParagraph(xAccText, false"STATE_CHANGED: FOCUSED");
                                    }
                                }
                            }
                            else if (isSpreadsheet(m_nDocumentType))
                            {
                                if (m_bIsEditingCell)
                                {
                                    if (!hasState(aEvent, AccessibleStateType::ACTIVE))
                                    {
                                        SAL_WARN("lok.a11y",
                                                 "LOKDocumentFocusListener::notifyEvent: FOCUSED: "
                                                 "cell not ACTIVE for editing yet");
                                        return;
                                    }
                                    else if (m_xSelectedObject.is())
                                    {
                                        updateParagraphInfo(xAccText, true"STATE_CHANGED: ACTIVE");
                                        notifyEditingInSelectionState(getAccessibleSiblingCount(xContext) == 0);
                                        notifyFocusedParagraphChanged(true);
                                        m_xSelectedObject.clear();
                                        return;
                                    }

                                    updateAndNotifyParagraph(xAccText, false"STATE_CHANGED: FOCUSED");
                                }
                            }
                            else if (isPresentation(m_nDocumentType))
                            {
                                updateAndNotifyParagraph(xAccText, false"STATE_CHANGED: FOCUSED");
                            }
                            aboutTextFormatting("LOKDocumentFocusListener::notifyEvent: STATE_CHANGED: FOCUSED", xAccText);

                            break;
                        }
                        default:
                            break;
                    }
                }
                break;
            }
            case AccessibleEventId::CARET_CHANGED:
            {
                sal_Int32 nNewPos = -1;
                aEvent.NewValue >>= nNewPos;
                sal_Int32 nOldPos = -1;
                aEvent.OldValue >>= nOldPos;

                if (nNewPos >= 0)
                {
                    SAL_INFO("lok.a11y""LOKDocumentFocusListener::notifyEvent: CARET_CHANGED: "
                                         "new pos: " << nNewPos << ", nOldPos: " << nOldPos);

                    uno::Reference<XAccessibleText> xAccText(getAccessible(aEvent), uno::UNO_QUERY);
                    if (xAccText.is())
                    {
                        m_nCaretPosition = nNewPos;
                        // Let's say we are in the following case: 'Hello wor|ld',
                        // where '|' is the cursor position for the current view.
                        // Suppose that in another view it's typed <enter> soon before 'world'.
                        // Now the new paragraph content and caret position is: 'wor|ld'.
                        // Anyway no new paragraph focused event is emitted for current view.
                        // Only a new caret position event is emitted.
                        // So we could need to notify a new focused paragraph changed message.
                        if (!isFocused(aEvent))
                        {
                            if (updateParagraphInfo(xAccText, false"CARET_CHANGED"))
                                notifyFocusedParagraphChanged(true);
                        }
                        else
                        {
                            notifyCaretChanged();
                        }
                        aboutParagraph("LOKDocumentFocusListener::notifyEvent: CARET_CHANGED", xAccText);
                    }
                }
                break;
            }
            case AccessibleEventId::TEXT_CHANGED:
            {
                TextSegment aDeletedText;
                TextSegment aInsertedText;

                if (aEvent.OldValue >>= aDeletedText)
                {
                    SAL_INFO("lok.a11y""LOKDocumentFocusListener::notifyEvent: TEXT_CHANGED: "
                                             "deleted text: >" << aDeletedText.SegmentText << "<");
                }
                if (aEvent.NewValue >>= aInsertedText)
                {
                    SAL_INFO("lok.a11y""LOKDocumentFocusListener::notifyEvent: TEXT_CHANGED: "
                                             "inserted text: >" << aInsertedText.SegmentText << "<");
                }
                uno::Reference<XAccessibleText> xAccText(getAccessible(aEvent), uno::UNO_QUERY);

                // When the change has been performed in another view we need to force
                // paragraph content updating on the client, even if current editing involves composing.
                // We make a guess that if the paragraph accessibility node is not focused,
                // it means that the text change has been performed in another view.
                updateAndNotifyParagraph(xAccText, !isFocused(aEvent), "TEXT_CHANGED");

                break;
            }
            case AccessibleEventId::TEXT_SELECTION_CHANGED:
            {
                if (!isFocused(aEvent))
                {
                    SAL_WARN("lok.a11y",
                             "LOKDocumentFocusListener::notifyEvent: TEXT_SELECTION_CHANGED: "
                             "skip non focused paragraph");
                    return;
                }

                uno::Reference<XAccessibleText> xAccText(getAccessible(aEvent), uno::UNO_QUERY);
                if (xAccText.is())
                {
                    // We send a message to client also when start/end are -1, in this way the client knows
                    // if a text selection object exists or not. That's needed because of the odd behavior
                    // occurring when <backspace>/<delete> are hit and a text selection is empty,
                    // but it still exists.
                    // Such keys delete the empty selection instead of the previous/next char.
                    updateParagraphInfo(xAccText, false"TEXT_SELECTION_CHANGED");

                    m_sSelectedText = xAccText->getSelectedText();
                    SAL_INFO("lok.a11y",
                             "LOKDocumentFocusListener::notifyEvent: TEXT_SELECTION_CHANGED: selected text: >"
                              << m_sSelectedText << "<");

                    // Calc: when editing a formula send the update content
                    if (m_bIsEditingCell)
                    {
                        OUString sText = xAccText->getText();
                        if (!m_sSelectedCellAddress.isEmpty() &&
                            !m_sSelectedText.isEmpty() && sText.startsWith("="))
                        {
                            notifyFocusedParagraphChanged();
                        }
                    }
                    notifyTextSelectionChanged();
                }
                break;
            }
            case AccessibleEventId::SELECTION_CHANGED:
            case AccessibleEventId::SELECTION_CHANGED_REMOVE:
            {
                uno::Reference< XAccessible > xSelectedObject = getSelectedObject(aEvent);
                if (!xSelectedObject.is())
                    return;
                uno::Reference< XAccessibleContext > xContext = xSelectedObject->getAccessibleContext();
                if (!xContext.is())
                    return;

                if (aEvent.EventId == AccessibleEventId::SELECTION_CHANGED_REMOVE)
                    m_xSelectedObject.clear();
                else if (m_xSelectedObject.is() && m_xSelectedObject == xSelectedObject)
--> --------------------

--> maximum size reached

--> --------------------

Messung V0.5
C=92 H=96 G=93

¤ Dauer der Verarbeitung: 0.20 Sekunden  ¤

*© Formatika GbR, Deutschland






Wurzel

Suchen

Beweissystem der NASA

Beweissystem Isabelle

NIST Cobol Testsuite

Cephes Mathematical Library

Wiener Entwicklungsmethode

Haftungshinweis

Die Informationen auf dieser Webseite wurden nach bestem Wissen sorgfältig zusammengestellt. Es wird jedoch weder Vollständigkeit, noch Richtigkeit, noch Qualität der bereit gestellten Informationen zugesichert.

Bemerkung:

Die farbliche Syntaxdarstellung und die Messung sind noch experimentell.