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, bool bReplacePTag)
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 if (bReplacePTag)
62 {
63 aResult = aResult.replaceAll("<p", "<span");
64 aResult = aResult.replaceAll("</p>", "</span>");
65 }
66
67 // HTML has for that <br> and <p> also does new line
68 aResult = aResult.replaceAll("<ul>", "");
69 aResult = aResult.replaceAll("</ul>", "");
70 aResult = aResult.replaceAll("<ol>", "");
71 aResult = aResult.replaceAll("</ol>", "");
72 aResult = aResult.replaceAll("\n", "").trim();
73 return aResult;
74 }
75 return {};
76}
77
78void PasteHTMLToPaM(SwWrtShell& rWrtSh, SwPaM* pCursor, const OString& rData, bool bSetSelection)
79{
80 SolarMutexGuard gMutex;
83 if (pHtmlTransferable.is())
84 {
85 TransferableDataHelper aDataHelper(pHtmlTransferable);
86 if (aDataHelper.GetXTransferable().is()
87 && SwTransferable::IsPasteSpecial(rWrtSh, aDataHelper))
88 {
89 if (bSetSelection)
90 {
91 rWrtSh.SetSelection(*pCursor);
92 }
93 SwTransferable::Paste(rWrtSh, aDataHelper);
94 rWrtSh.KillSelection(nullptr, false);
95 }
96 }
97}
98
99#if !ENABLE_WASM_STRIP_EXTRA
101{
102 bool bCancel = false;
103 TranslateDocumentCancellable(rWrtSh, rConfig, bCancel);
104}
105
107 bool& rCancelTranslation)
108{
109 auto m_pCurrentPam = rWrtSh.GetCursor();
110 bool bHasSelection = rWrtSh.HasSelection();
111
112 if (bHasSelection)
113 {
114 // iteration will start top to bottom
115 if (m_pCurrentPam->GetPoint()->nNode > m_pCurrentPam->GetMark()->nNode)
116 m_pCurrentPam->Exchange();
117 }
118
119 auto const& pNodes = rWrtSh.GetNodes();
120 SwPosition aPoint = *m_pCurrentPam->GetPoint();
121 SwPosition aMark = *m_pCurrentPam->GetMark();
122 auto startNode = bHasSelection ? aPoint.nNode.GetIndex() : SwNodeOffset(0);
123 auto endNode = bHasSelection ? aMark.nNode.GetIndex() : pNodes.Count() - 1;
124
125 sal_Int32 nCount(0);
126 sal_Int32 nProgress(0);
127
128 for (SwNodeOffset n(startNode); n <= endNode; ++n)
129 {
130 if (pNodes[n] && pNodes[n]->IsTextNode())
131 {
132 if (pNodes[n]->GetTextNode()->GetText().isEmpty())
133 continue;
134 nCount++;
135 }
136 }
137
139 uno::Reference<frame::XFrame> xFrame(pFrame ? pFrame->GetFrame().GetFrameInterface() : nullptr);
140 uno::Reference<task::XStatusIndicatorFactory> xProgressFactory(xFrame, uno::UNO_QUERY);
141 uno::Reference<task::XStatusIndicator> xStatusIndicator;
142
143 if (xProgressFactory.is())
144 {
145 xStatusIndicator = xProgressFactory->createStatusIndicator();
146 }
147
148 if (xStatusIndicator.is())
149 xStatusIndicator->start(SwResId(STR_STATSTR_SWTRANSLATE), nCount);
150
151 for (SwNodeOffset n(startNode); n <= endNode; ++n)
152 {
153 if (rCancelTranslation)
154 break;
155
156 if (n >= rWrtSh.GetNodes().Count())
157 break;
158
159 if (!pNodes[n])
160 break;
161
162 SwNode* pNode = pNodes[n];
163 if (pNode->IsTextNode())
164 {
165 if (pNode->GetTextNode()->GetText().isEmpty())
166 continue;
167
168 auto cursor
169 = Writer::NewUnoCursor(*rWrtSh.GetDoc(), pNode->GetIndex(), pNode->GetIndex());
170
171 // set edges (start, end) for nodes inside the selection.
172 if (bHasSelection)
173 {
174 if (startNode == endNode)
175 {
176 cursor->SetMark();
177 cursor->GetPoint()->nContent = aPoint.nContent;
178 cursor->GetMark()->nContent = aMark.nContent;
179 }
180 else if (n == startNode)
181 {
182 cursor->SetMark();
183 cursor->GetPoint()->nContent = std::min(aPoint.nContent, aMark.nContent);
184 }
185 else if (n == endNode)
186 {
187 cursor->SetMark();
188 cursor->GetMark()->nContent = aMark.nContent;
189 cursor->GetPoint()->nContent = 0;
190 }
191 }
192
193 const auto aOut = SwTranslateHelper::ExportPaMToHTML(cursor.get(), true);
194 const auto aTranslatedOut = linguistic::Translate(
195 rConfig.m_xTargetLanguage, rConfig.m_xAPIUrl, rConfig.m_xAuthKey, aOut);
196 SwTranslateHelper::PasteHTMLToPaM(rWrtSh, cursor.get(), aTranslatedOut, true);
197
198 if (xStatusIndicator.is())
199 xStatusIndicator->setValue((100 * ++nProgress) / nCount);
200
201 Idle aIdle("ProgressBar::SetValue aIdle");
202 aIdle.SetPriority(TaskPriority::POST_PAINT);
203 aIdle.Start();
204
205 rWrtSh.LockView(true);
206 while (aIdle.IsActive() && !Application::IsQuit())
207 {
209 }
210 rWrtSh.LockView(false);
211 }
212 }
213
214 if (xStatusIndicator.is())
215 xStatusIndicator->end();
216}
217#endif // !ENABLE_WASM_STRIP_EXTRA
218}
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:3561
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:903
SwNodeOffset GetIndex() const
Definition: node.hxx:312
bool IsTextNode() const
Definition: node.hxx:687
SwNodeOffset Count() const
Definition: ndarr.hxx:142
PaM is Point and Mark: a selection of the document model.
Definition: pam.hxx:187
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:3378
const SwNodes & GetNodes() const
Definition: viewsh.cxx:2177
SwDoc * GetDoc() const
Definition: viewsh.hxx:290
void LockView(bool b)
Definition: viewsh.hxx:473
ErrCode Write(WriterRef const &rxWriter, const OUString *=nullptr)
Definition: shellio.cxx:739
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:191
int nCount
float u
sal_Int64 n
#define SAL_WARN(area, stream)
SW_DLLPUBLIC void TranslateDocumentCancellable(SwWrtShell &rWrtSh, const TranslateAPIConfig &rConfig, bool &rCancelTranslation)
SW_DLLPUBLIC OString ExportPaMToHTML(SwPaM *pCursor, bool bReplacePTag)
SW_DLLPUBLIC void PasteHTMLToPaM(SwWrtShell &rWrtSh, SwPaM *pCursor, const OString &rData, bool bSetSelection)
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:37
SwNodeIndex nNode
Definition: pam.hxx:38
SwContentIndex nContent
Definition: pam.hxx:39
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:1672