summaryrefslogtreecommitdiff
path: root/writerfilter/source/dmapper/SdtHelper.cxx
blob: 8a2356051a21c384267c690089dd15fd5517ed70 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
 * 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/.
 */

#include "SdtHelper.hxx"
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#include <com/sun/star/drawing/XControlShape.hpp>
#include <com/sun/star/text/VertOrientation.hpp>
#include <editeng/unoprnms.hxx>
#include <sal/log.hxx>
#include <vcl/svapp.hxx>
#include <vcl/outdev.hxx>
#include <comphelper/string.hxx>
#include <comphelper/sequence.hxx>
#include <xmloff/odffields.hxx>
#include <com/sun/star/text/XTextField.hpp>
#include "DomainMapper_Impl.hxx"
#include "StyleSheetTable.hxx"
#include <officecfg/Office/Writer.hxx>
#include <com/sun/star/util/XRefreshable.hpp>
#include <com/sun/star/text/XTextFieldsSupplier.hpp>
#include <com/sun/star/document/XOOXMLDocumentPropertiesImporter.hpp>
#include <com/sun/star/embed/ElementModes.hpp>
#include <ooxml/OOXMLDocument.hxx>
#include <com/sun/star/xml/xpath/XPathAPI.hpp>
#include <com/sun/star/xml/dom/DocumentBuilder.hpp>
#include <com/sun/star/xml/dom/XNode.hpp>

namespace writerfilter
{
namespace dmapper

{
using namespace ::com::sun::star;
using namespace ::css::xml::xpath;
using namespace ::comphelper;

/// w:sdt's w:dropDownList doesn't have width, so guess the size based on the longest string.
static awt::Size lcl_getOptimalWidth(const StyleSheetTablePtr& pStyleSheet,
                                     OUString const& rDefault, std::vector<OUString>& rItems)
{
    OUString aLongest = rDefault;
    sal_Int32 nHeight = 0;
    for (const OUString& rItem : rItems)
        if (rItem.getLength() > aLongest.getLength())
            aLongest = rItem;

    MapMode aMap(MapUnit::Map100thMM);
    OutputDevice* pOut = Application::GetDefaultDevice();
    pOut->Push(PushFlags::FONT | PushFlags::MAPMODE);

    PropertyMapPtr pDefaultCharProps = pStyleSheet->GetDefaultCharProps();
    vcl::Font aFont(pOut->GetFont());
    boost::optional<PropertyMap::Property> aFontName
        = pDefaultCharProps->getProperty(PROP_CHAR_FONT_NAME);
    if (aFontName)
        aFont.SetFamilyName(aFontName->second.get<OUString>());
    boost::optional<PropertyMap::Property> aHeight
        = pDefaultCharProps->getProperty(PROP_CHAR_HEIGHT);
    if (aHeight)
    {
        nHeight = aHeight->second.get<double>() * 35; // points -> mm100
        aFont.SetFontSize(Size(0, nHeight));
    }
    pOut->SetFont(aFont);
    pOut->SetMapMode(aMap);
    sal_Int32 nWidth = pOut->GetTextWidth(aLongest);

    pOut->Pop();

    // Border: see PDFWriterImpl::drawFieldBorder(), border size is font height / 4,
    // so additional width / height needed is height / 2.
    sal_Int32 nBorder = nHeight / 2;

    // Width: space for the text + the square having the dropdown arrow.
    return { nWidth + nBorder + nHeight, nHeight + nBorder };
}

SdtHelper::SdtHelper(DomainMapper_Impl& rDM_Impl,
                     css::uno::Reference<css::uno::XComponentContext> const& xContext)
    : m_rDM_Impl(rDM_Impl)
    , m_xComponentContext(xContext)
    , m_aControlType(SdtControlType::unknown)
    , m_bHasElements(false)
    , m_bOutsideAParagraph(false)
    , m_bPropertiesXMLsLoaded(false)
{
}

SdtHelper::~SdtHelper() = default;

void SdtHelper::loadPropertiesXMLs()
{
    // Initialize properties xml storage (m_xPropertiesXMLs)
    uno::Reference<uno::XInterface> xTemp
        = m_xComponentContext->getServiceManager()->createInstanceWithContext(
            "com.sun.star.document.OOXMLDocumentPropertiesImporter", m_xComponentContext);
    uno::Reference<document::XOOXMLDocumentPropertiesImporter> xImporter(xTemp, uno::UNO_QUERY);
    if (!xImporter.is())
        return;

    uno::Reference<xml::dom::XDocumentBuilder> xDomBuilder(
        xml::dom::DocumentBuilder::create(m_xComponentContext));
    if (!xDomBuilder.is())
        return;

    std::vector<uno::Reference<xml::dom::XDocument>> aPropDocs;

    // Load core properties
    try
    {
        auto xCorePropsStream = xImporter->getCorePropertiesStream(m_rDM_Impl.m_xDocumentStorage);
        aPropDocs.push_back(xDomBuilder->parse(xCorePropsStream));
    }
    catch (const uno::Exception&)
    {
        SAL_WARN("writerfilter",
                 "SdtHelper::loadPropertiesXMLs: failed loading core properties XML");
    }

    // Load extended properties
    try
    {
        auto xExtPropsStream
            = xImporter->getExtendedPropertiesStream(m_rDM_Impl.m_xDocumentStorage);
        aPropDocs.push_back(xDomBuilder->parse(xExtPropsStream));
    }
    catch (const uno::Exception&)
    {
        SAL_WARN("writerfilter",
                 "SdtHelper::loadPropertiesXMLs: failed loading extended properties XML");
    }

    // TODO: some other property items?

    // Add custom XMLs
    uno::Sequence<uno::Reference<xml::dom::XDocument>> aCustomXmls
        = m_rDM_Impl.getDocumentReference()->getCustomXmlDomList();
    for (const auto& xDoc : aCustomXmls)
    {
        aPropDocs.push_back(xDoc);
    }

    m_xPropertiesXMLs = comphelper::containerToSequence(aPropDocs);
    m_bPropertiesXMLsLoaded = true;
}

static void lcl_registerNamespaces(const OUString& sNamespaceString,
                                   const uno::Reference<XXPathAPI>& xXPathAPI)
{
    // Split namespaces and register it in XPathAPI
    auto aNamespaces = string::split(sNamespaceString, ' ');
    for (const auto& sNamespace : aNamespaces)
    {
        // Here we have just one namespace in format "xmlns:ns0='http://someurl'"
        auto aNamespace = string::split(sNamespace, '=');
        if (aNamespace.size() < 2)
        {
            SAL_WARN("writerfilter",
                     "SdtHelper::getValueFromDataBinding: invalid namespace: " << sNamespace);
            continue;
        }

        auto aNamespaceId = string::split(aNamespace[0], ':');
        if (aNamespaceId.size() < 2)
        {
            SAL_WARN("writerfilter",
                     "SdtHelper::getValueFromDataBinding: invalid namespace: " << aNamespace[0]);
            continue;
        }

        OUString sNamespaceURL = aNamespace[1];
        sNamespaceURL = string::strip(sNamespaceURL, ' ');
        sNamespaceURL = string::strip(sNamespaceURL, '\'');

        xXPathAPI->registerNS(aNamespaceId[1], sNamespaceURL);
    }
}

std::optional<OUString> SdtHelper::getValueFromDataBinding()
{
    // No xpath - nothing to do
    if (m_sDataBindingXPath.isEmpty())
        return {};

    // Load properties XMLs
    if (!m_bPropertiesXMLsLoaded)
        loadPropertiesXMLs();

    uno::Reference<XXPathAPI> xXpathAPI = XPathAPI::create(m_xComponentContext);

    lcl_registerNamespaces(m_sDataBindingPrefixMapping, xXpathAPI);

    // Iterate all properties xml documents and try to fetch data
    for (const auto& xDocument : m_xPropertiesXMLs)
    {
        uno::Reference<XXPathObject> xResult = xXpathAPI->eval(xDocument, m_sDataBindingXPath);

        if (xResult.is() && xResult->getNodeList() && xResult->getNodeList()->getLength())
        {
            return xResult->getString();
        }
    }

    // No data
    return {};
}

void SdtHelper::createDropDownControl()
{
    assert(getControlType() == SdtControlType::dropDown);

    const bool bDropDown
        = officecfg::Office::Writer::Filter::Import::DOCX::ImportComboBoxAsDropDown::get();
    const OUString aDefaultText = m_aSdtTexts.makeStringAndClear();

    if (bDropDown)
    {
        // create field
        uno::Reference<css::text::XTextField> xControlModel(
            m_rDM_Impl.GetTextFactory()->createInstance("com.sun.star.text.TextField.DropDown"),
            uno::UNO_QUERY);

        const auto it = std::find_if(
            m_aDropDownItems.begin(), m_aDropDownItems.end(),
            [aDefaultText](const OUString& item) -> bool { return !item.compareTo(aDefaultText); });

        if (m_aDropDownItems.end() == it)
        {
            m_aDropDownItems.push_back(aDefaultText);
        }

        // set properties
        uno::Reference<beans::XPropertySet> xPropertySet(xControlModel, uno::UNO_QUERY);
        xPropertySet->setPropertyValue("SelectedItem", uno::makeAny(aDefaultText));
        xPropertySet->setPropertyValue(
            "Items", uno::makeAny(comphelper::containerToSequence(m_aDropDownItems)));

        // add it into document
        m_rDM_Impl.appendTextContent(xControlModel, uno::Sequence<beans::PropertyValue>());

        m_bHasElements = true;
    }
    else
    {
        // create control
        uno::Reference<awt::XControlModel> xControlModel(
            m_rDM_Impl.GetTextFactory()->createInstance("com.sun.star.form.component.ComboBox"),
            uno::UNO_QUERY);

        // set properties
        uno::Reference<beans::XPropertySet> xPropertySet(xControlModel, uno::UNO_QUERY);
        xPropertySet->setPropertyValue("DefaultText", uno::makeAny(aDefaultText));
        xPropertySet->setPropertyValue("Dropdown", uno::makeAny(true));
        xPropertySet->setPropertyValue(
            "StringItemList", uno::makeAny(comphelper::containerToSequence(m_aDropDownItems)));

        // add it into document
        createControlShape(
            lcl_getOptimalWidth(m_rDM_Impl.GetStyleSheetTable(), aDefaultText, m_aDropDownItems),
            xControlModel, uno::Sequence<beans::PropertyValue>());
    }

    // clean up
    m_aDropDownItems.clear();
    setControlType(SdtControlType::unknown);
}

void SdtHelper::createPlainTextControl()
{
    assert(getControlType() == SdtControlType::plainText);

    OUString aDefaultText = m_aSdtTexts.makeStringAndClear();

    // create field
    uno::Reference<css::text::XTextField> xControlModel(
        m_rDM_Impl.GetTextFactory()->createInstance("com.sun.star.text.TextField.Input"),
        uno::UNO_QUERY);

    // set properties
    uno::Reference<beans::XPropertySet> xPropertySet(xControlModel, uno::UNO_QUERY);

    std::optional<OUString> oData = getValueFromDataBinding();
    if (oData.has_value())
        aDefaultText = *oData;

    xPropertySet->setPropertyValue("Content", uno::makeAny(aDefaultText));

    // add it into document
    m_rDM_Impl.appendTextContent(xControlModel, uno::Sequence<beans::PropertyValue>());

    // Store all unused sdt parameters from grabbag
    xPropertySet->setPropertyValue(UNO_NAME_MISC_OBJ_INTEROPGRABBAG,
                                   uno::makeAny(getInteropGrabBagAndClear()));

    // clean up
    m_aDropDownItems.clear();
    setControlType(SdtControlType::unknown);
}

void SdtHelper::createDateContentControl()
{
    if (!m_xDateFieldStartRange.is())
        return;

    uno::Reference<text::XTextCursor> xCrsr;
    if (m_rDM_Impl.HasTopText())
    {
        uno::Reference<text::XTextAppend> xTextAppend = m_rDM_Impl.GetTopTextAppend();
        if (xTextAppend.is())
        {
            xCrsr = xTextAppend->createTextCursorByRange(xTextAppend);
        }
    }
    if (xCrsr.is())
    {
        try
        {
            xCrsr->gotoRange(m_xDateFieldStartRange, false);
            bool bIsInTable
                = (m_rDM_Impl.hasTableManager() && m_rDM_Impl.getTableManager().isInTable())
                  || (m_rDM_Impl.m_nTableDepth > 0);
            if (bIsInTable)
                xCrsr->goRight(1, false);
            xCrsr->gotoEnd(true);
        }
        catch (uno::Exception&)
        {
            OSL_ENSURE(false, "Cannot get the right text range for date field");
            return;
        }

        uno::Reference<uno::XInterface> xFieldInterface
            = m_rDM_Impl.GetTextFactory()->createInstance("com.sun.star.text.Fieldmark");
        uno::Reference<text::XFormField> xFormField(xFieldInterface, uno::UNO_QUERY);
        uno::Reference<text::XTextContent> xToInsert(xFormField, uno::UNO_QUERY);
        if (xFormField.is() && xToInsert.is())
        {
            xToInsert->attach(uno::Reference<text::XTextRange>(xCrsr, uno::UNO_QUERY_THROW));
            xFormField->setFieldType(ODF_FORMDATE);
            uno::Reference<container::XNameContainer> xNameCont = xFormField->getParameters();
            if (xNameCont.is())
            {
                OUString sDateFormat = m_sDateFormat.makeStringAndClear();
                // Replace quotation mark used for marking static strings in date format
                sDateFormat = sDateFormat.replaceAll("'", "\"");
                xNameCont->insertByName(ODF_FORMDATE_DATEFORMAT, uno::makeAny(sDateFormat));
                xNameCont->insertByName(ODF_FORMDATE_DATEFORMAT_LANGUAGE,
                                        uno::makeAny(m_sLocale.makeStringAndClear()));
            }
            OUString sFullDate = m_sDate.makeStringAndClear();

            std::optional<OUString> oData = getValueFromDataBinding();
            if (oData.has_value())
                sFullDate = *oData;

            if (!sFullDate.isEmpty())
            {
                sal_Int32 nTimeSep = sFullDate.indexOf("T");
                if (nTimeSep != -1)
                    sFullDate = sFullDate.copy(0, nTimeSep);
                xNameCont->insertByName(ODF_FORMDATE_CURRENTDATE, uno::makeAny(sFullDate));
            }

            // Store all unused sdt parameters from grabbag
            xNameCont->insertByName(UNO_NAME_MISC_OBJ_INTEROPGRABBAG,
                                    uno::makeAny(getInteropGrabBagAndClear()));
        }
    }

    setControlType(SdtControlType::unknown);
}

void SdtHelper::createControlShape(awt::Size aSize,
                                   uno::Reference<awt::XControlModel> const& xControlModel,
                                   const uno::Sequence<beans::PropertyValue>& rGrabBag)
{
    uno::Reference<drawing::XControlShape> xControlShape(
        m_rDM_Impl.GetTextFactory()->createInstance("com.sun.star.drawing.ControlShape"),
        uno::UNO_QUERY);
    xControlShape->setSize(aSize);
    xControlShape->setControl(xControlModel);

    uno::Reference<beans::XPropertySet> xPropertySet(xControlShape, uno::UNO_QUERY);
    xPropertySet->setPropertyValue("VertOrient", uno::makeAny(text::VertOrientation::CENTER));

    if (rGrabBag.hasElements())
        xPropertySet->setPropertyValue(UNO_NAME_MISC_OBJ_INTEROPGRABBAG, uno::makeAny(rGrabBag));

    uno::Reference<text::XTextContent> xTextContent(xControlShape, uno::UNO_QUERY);
    m_rDM_Impl.appendTextContent(xTextContent, uno::Sequence<beans::PropertyValue>());
    m_bHasElements = true;
}

void SdtHelper::appendToInteropGrabBag(const beans::PropertyValue& rValue)
{
    m_aGrabBag.push_back(rValue);
}

uno::Sequence<beans::PropertyValue> SdtHelper::getInteropGrabBagAndClear()
{
    uno::Sequence<beans::PropertyValue> aRet = comphelper::containerToSequence(m_aGrabBag);
    m_aGrabBag.clear();
    return aRet;
}

bool SdtHelper::isInteropGrabBagEmpty() const { return m_aGrabBag.empty(); }

sal_Int32 SdtHelper::getInteropGrabBagSize() const { return m_aGrabBag.size(); }

bool SdtHelper::containedInInteropGrabBag(const OUString& rValueName)
{
    for (const beans::PropertyValue& i : m_aGrabBag)
        if (i.Name == rValueName)
            return true;

    return false;
}

} // namespace dmapper
} // namespace writerfilter

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */