LibreOffice Module sw (master) 1
translatehelper.cxx
Go to the documentation of this file.
1/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
2/*
3 * This file is part of the LibreOffice project.
4 *
5 * This Source Code Form is subject to the terms of the Mozilla Public
6 * License, v. 2.0. If a copy of the MPL was not distributed with this
7 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
8 *
9 * This file incorporates work covered by the following license notice:
10 *
11 * Licensed to the Apache Software Foundation (ASF) under one or more
12 * contributor license agreements. See the NOTICE file distributed
13 * with this work for additional information regarding copyright
14 * ownership. The ASF licenses this file to you under the Apache
15 * License, Version 2.0 (the "License"); you may not use this file
16 * except in compliance with the License. You may obtain a copy of
17 * the License at http://www.apache.org/licenses/LICENSE-2.0 .
18 */
19#include <config_wasm_strip.h>
20#include <wrtsh.hxx>
21#include <pam.hxx>
22#include <node.hxx>
23#include <ndtxt.hxx>
24#include <translatehelper.hxx>
25#include <sal/log.hxx>
26#include <rtl/string.h>
27#include <shellio.hxx>
28#include <vcl/scheduler.hxx>
29#include <vcl/svapp.hxx>
30#include <boost/property_tree/ptree.hpp>
31#include <boost/property_tree/json_parser.hpp>
33#include <vcl/transfer.hxx>
34#include <swdtflvr.hxx>
36#include <com/sun/star/task/XStatusIndicator.hpp>
37#include <sfx2/viewfrm.hxx>
38#include <com/sun/star/task/XStatusIndicatorFactory.hpp>
39#include <strings.hrc>
40
41namespace SwTranslateHelper
42{
43OString ExportPaMToHTML(SwPaM* pCursor)
44{
45 SolarMutexGuard gMutex;
46 OString aResult;
47 WriterRef xWrt;
48 GetHTMLWriter(u"NoLineLimit,SkipHeaderFooter,NoPrettyPrint", OUString(), xWrt);
49 if (pCursor != nullptr)
50 {
51 SvMemoryStream aMemoryStream;
52 SwWriter aWriter(aMemoryStream, *pCursor);
53 ErrCode nError = aWriter.Write(xWrt);
54 if (nError.IsError())
55 {
56 SAL_WARN("sw.ui", "ExportPaMToHTML: failed to export selection to HTML");
57 return {};
58 }
59 aResult
60 = OString(static_cast<const char*>(aMemoryStream.GetData()), aMemoryStream.GetSize());
61 aResult = aResult.replaceAll("<p", "<span");
62 aResult = aResult.replaceAll("</p>", "</span>");
63
64 // HTML has for that <br> and <p> also does new line
65 aResult = aResult.replaceAll("<ul>", "");
66 aResult = aResult.replaceAll("</ul>", "");
67 aResult = aResult.replaceAll("<ol>", "");
68 aResult = aResult.replaceAll("</ol>", "");
69 aResult = aResult.replaceAll("\n", "").trim();
70 return aResult;
71 }
72 return {};
73}
74
75void PasteHTMLToPaM(SwWrtShell& rWrtSh, SwPaM* pCursor, const OString& rData)
76{
77 SolarMutexGuard gMutex;
80 if (pHtmlTransferable.is())
81 {
82 TransferableDataHelper aDataHelper(pHtmlTransferable);
83 if (aDataHelper.GetXTransferable().is()
84 && SwTransferable::IsPasteSpecial(rWrtSh, aDataHelper))
85 {
86 rWrtSh.SetSelection(*pCursor);
87 SwTransferable::Paste(rWrtSh, aDataHelper);
88 rWrtSh.KillSelection(nullptr, false);
89 }
90 }
91}
92
93#if !ENABLE_WASM_STRIP_EXTRA
94void TranslateDocument(SwWrtShell& rWrtSh, const TranslateAPIConfig& rConfig)
95{
96 bool bCancel = false;
97 TranslateDocumentCancellable(rWrtSh, rConfig, bCancel);
98}
99
101 bool& rCancelTranslation)
102{
103 auto m_pCurrentPam = rWrtSh.GetCursor();
104 bool bHasSelection = rWrtSh.HasSelection();
105
106 if (bHasSelection)
107 {
108 // iteration will start top to bottom
109 if (m_pCurrentPam->GetPoint()->nNode > m_pCurrentPam->GetMark()->nNode)
110 m_pCurrentPam->Exchange();
111 }
112
113 auto const& pNodes = rWrtSh.GetNodes();
114 SwPosition aPoint = *m_pCurrentPam->GetPoint();
115 SwPosition aMark = *m_pCurrentPam->GetMark();
116 auto startNode = bHasSelection ? aPoint.nNode.GetIndex() : SwNodeOffset(0);
117 auto endNode = bHasSelection ? aMark.nNode.GetIndex() : pNodes.Count() - 1;
118
119 sal_Int32 nCount(0);
120 sal_Int32 nProgress(0);
121
122 for (SwNodeOffset n(startNode); n <= endNode; ++n)
123 {
124 if (pNodes[n] && pNodes[n]->IsTextNode())
125 {
126 if (pNodes[n]->GetTextNode()->GetText().isEmpty())
127 continue;
128 nCount++;
129 }
130 }
131
133 uno::Reference<frame::XFrame> xFrame(pFrame ? pFrame->GetFrame().GetFrameInterface() : nullptr);
134 uno::Reference<task::XStatusIndicatorFactory> xProgressFactory(xFrame, uno::UNO_QUERY);
135 uno::Reference<task::XStatusIndicator> xStatusIndicator;
136
137 if (xProgressFactory.is())
138 {
139 xStatusIndicator = xProgressFactory->createStatusIndicator();
140 }
141
142 if (xStatusIndicator.is())
143 xStatusIndicator->start(SwResId(STR_STATSTR_SWTRANSLATE), nCount);
144
145 for (SwNodeOffset n(startNode); n <= endNode; ++n)
146 {
147 if (rCancelTranslation)
148 break;
149
150 if (n >= rWrtSh.GetNodes().Count())
151 break;
152
153 if (!pNodes[n])
154 break;
155
156 SwNode* pNode = pNodes[n];
157 if (pNode->IsTextNode())
158 {
159 if (pNode->GetTextNode()->GetText().isEmpty())
160 continue;
161
162 auto cursor
163 = Writer::NewUnoCursor(*rWrtSh.GetDoc(), pNode->GetIndex(), pNode->GetIndex());
164
165 // set edges (start, end) for nodes inside the selection.
166 if (bHasSelection)
167 {
168 if (startNode == endNode)
169 {
170 cursor->SetMark();
171 cursor->GetPoint()->nContent = aPoint.nContent;
172 cursor->GetMark()->nContent = aMark.nContent;
173 }
174 else if (n == startNode)
175 {
176 cursor->SetMark();
177 cursor->GetPoint()->nContent = std::min(aPoint.nContent, aMark.nContent);
178 }
179 else if (n == endNode)
180 {
181 cursor->SetMark();
182 cursor->GetMark()->nContent = aMark.nContent;
183 cursor->GetPoint()->nContent = 0;
184 }
185 }
186
187 const auto aOut = SwTranslateHelper::ExportPaMToHTML(cursor.get());
188 const auto aTranslatedOut = linguistic::Translate(
189 rConfig.m_xTargetLanguage, rConfig.m_xAPIUrl, rConfig.m_xAuthKey, aOut);
190 SwTranslateHelper::PasteHTMLToPaM(rWrtSh, cursor.get(), aTranslatedOut);
191
192 if (xStatusIndicator.is())
193 xStatusIndicator->setValue((100 * ++nProgress) / nCount);
194
195 Idle aIdle("ProgressBar::SetValue aIdle");
196 aIdle.SetPriority(TaskPriority::POST_PAINT);
197 aIdle.Start();
198
199 rWrtSh.LockView(true);
200 while (aIdle.IsActive() && !Application::IsQuit())
201 {
203 }
204 rWrtSh.LockView(false);
205 }
206 }
207
208 if (xStatusIndicator.is())
209 xStatusIndicator->end();
210}
211#endif // !ENABLE_WASM_STRIP_EXTRA
212}
static void Yield()
static bool IsQuit()
bool IsError() const
virtual void Start(bool bStartTimer=true) override
const css::uno::Reference< css::frame::XFrame > & GetFrameInterface() const
static SAL_WARN_UNUSED_RESULT SfxViewFrame * Current()
SfxFrame & GetFrame() const
const void * GetData()
sal_uInt64 GetSize()
void SetMark(const sw::mark::IMark *pMark)
Definition: index.cxx:222
const sw::mark::IMark * GetMark() const
void SetSelection(const SwPaM &rCursor)
Definition: crsrsh.cxx:3868
SwCursor * GetCursor(bool bMakeTableCursor=true) const
Return pointer to the current shell cursor.
Definition: crsrsh.cxx:194
SwNodeOffset GetIndex() const
Definition: ndindex.hxx:111
Base class of the Writer document model elements.
Definition: node.hxx:98
SwTextNode * GetTextNode()
Inline methods from Node.hxx.
Definition: ndtxt.hxx:901
SwNodeOffset GetIndex() const
Definition: node.hxx:312
bool IsTextNode() const
Definition: node.hxx:190
SwNodeOffset Count() const
Definition: ndarr.hxx:142
PaM is Point and Mark: a selection of the document model.
Definition: pam.hxx:188
const OUString & GetText() const
Definition: ndtxt.hxx:244
static bool Paste(SwWrtShell &, TransferableDataHelper &, RndStdIds nAnchorType=RndStdIds::FLY_AT_PARA, bool bIgnoreComments=false, PasteTableType ePasteTable=PasteTableType::PASTE_DEFAULT)
Definition: swdtflvr.cxx:1455
static bool IsPasteSpecial(const SwWrtShell &rWrtShell, const TransferableDataHelper &)
Definition: swdtflvr.cxx:3383
const SwNodes & GetNodes() const
Definition: viewsh.cxx:2181
SwDoc * GetDoc() const
Definition: viewsh.hxx:308
void LockView(bool b)
Definition: viewsh.hxx:491
ErrCode Write(WriterRef const &rxWriter, const OUString *=nullptr)
Definition: shellio.cxx:745
Used by the UI to modify the document model.
Definition: wrtsh.hxx:97
tools::Long KillSelection(const Point *pPt, bool bProp)
Definition: wrtsh.hxx:126
bool HasSelection() const
Definition: wrtsh.hxx:147
bool IsActive() const
void SetPriority(TaskPriority ePriority)
css::uno::Reference< css::datatransfer::XTransferable > GetXTransferable() const
static std::shared_ptr< SwUnoCursor > NewUnoCursor(SwDoc &rDoc, SwNodeOffset const nStartIdx, SwNodeOffset const nEndIdx)
Definition: writer.cxx:170
int nCount
float u
sal_Int64 n
#define SAL_WARN(area, stream)
SW_DLLPUBLIC OString ExportPaMToHTML(SwPaM *pCursor)
SW_DLLPUBLIC void TranslateDocumentCancellable(SwWrtShell &rWrtSh, const TranslateAPIConfig &rConfig, bool &rCancelTranslation)
SW_DLLPUBLIC void PasteHTMLToPaM(SwWrtShell &rWrtSh, SwPaM *pCursor, const OString &rData)
SW_DLLPUBLIC void TranslateDocument(SwWrtShell &rWrtSh, const TranslateAPIConfig &rConfig)
OString Translate(const OString &rTargetLang, const OString &rAPIUrl, const OString &rAuthKey, const OString &rData)
o3tl::strong_int< sal_Int32, struct Tag_SwNodeOffset > SwNodeOffset
Definition: nodeoffset.hxx:16
SwNodeOffset min(const SwNodeOffset &a, const SwNodeOffset &b)
Definition: nodeoffset.hxx:35
Marks a position in the document model.
Definition: pam.hxx:38
SwNodeIndex nNode
Definition: pam.hxx:39
SwContentIndex nContent
Definition: pam.hxx:40
Reference< XFrame > xFrame
OUString SwResId(TranslateId aId)
Definition: swmodule.cxx:168
void GetHTMLWriter(std::u16string_view rFilterOptions, const OUString &rBaseURL, WriterRef &xRet)
Definition: wrthtml.cxx:1675