LibreOffice Module cui (master) 1
QrCodeGenDialog.cxx
Go to the documentation of this file.
1/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4; fill-column: 100 -*- */
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
10#include <QrCodeGenDialog.hxx>
11
14#include <tools/stream.hxx>
15#include <dialmgr.hxx>
16#include <strings.hrc>
18#include <utility>
19#include <vcl/svapp.hxx>
20
21#if ENABLE_ZXING
22#include <rtl/strbuf.hxx>
23
24#ifdef __GNUC__
25#pragma GCC diagnostic push
26#pragma GCC diagnostic ignored "-Wshadow"
27#endif
28
29#include <BarcodeFormat.h>
30#include <BitArray.h>
31#include <BitMatrix.h>
32#include <MultiFormatWriter.h>
33#include <TextUtfEncoding.h>
34
35#ifdef __GNUC__
36#pragma GCC diagnostic pop
37#endif
38
39#endif // ENABLE_ZXING
40
41#include <com/sun/star/beans/XPropertySet.hpp>
42#include <com/sun/star/drawing/XDrawPageSupplier.hpp>
43#include <com/sun/star/drawing/XShape.hpp>
44#include <com/sun/star/graphic/GraphicProvider.hpp>
45#include <com/sun/star/graphic/XGraphic.hpp>
46#include <com/sun/star/drawing/BarCode.hpp>
47#include <com/sun/star/drawing/BarCodeErrorCorrection.hpp>
48#include <com/sun/star/graphic/XGraphicProvider.hpp>
49#include <com/sun/star/io/XInputStream.hpp>
50#include <com/sun/star/lang/XMultiServiceFactory.hpp>
51#include <com/sun/star/lang/XServiceInfo.hpp>
52#include <com/sun/star/sheet/XSpreadsheet.hpp>
53#include <com/sun/star/sheet/XSpreadsheetView.hpp>
54#include <com/sun/star/text/TextContentAnchorType.hpp>
55#include <com/sun/star/text/XTextContent.hpp>
56#include <com/sun/star/text/XTextViewCursor.hpp>
57#include <com/sun/star/text/XTextViewCursorSupplier.hpp>
58#include <com/sun/star/drawing/XDrawView.hpp>
59#include <com/sun/star/drawing/XDrawPage.hpp>
60
61using namespace css;
62using namespace css::uno;
63using namespace css::beans;
64using namespace css::container;
65using namespace css::frame;
66using namespace css::io;
67using namespace css::lang;
68using namespace css::sheet;
69using namespace css::text;
70using namespace css::drawing;
71using namespace css::graphic;
72
73namespace
74{
75#if ENABLE_ZXING
76// Implementation adapted from the answer: https://stackoverflow.com/questions/10789059/create-qr-code-in-vector-image/60638350#60638350
77OString ConvertToSVGFormat(const ZXing::BitMatrix& bitmatrix)
78{
79 OStringBuffer sb;
80 const int width = bitmatrix.width();
81 const int height = bitmatrix.height();
82 ZXing::BitArray row(width);
83 sb.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
84 "<svg xmlns=\"http://www.w3.org/2000/svg\" version=\"1.1\" viewBox=\"0 0 "
85 + OString::number(width) + " " + OString::number(height)
86 + "\" stroke=\"none\">\n"
87 "<path d=\"");
88 for (int i = 0; i < height; ++i)
89 {
90 bitmatrix.getRow(i, row);
91 for (int j = 0; j < width; ++j)
92 {
93 if (row.get(j))
94 {
95 sb.append("M" + OString::number(j) + "," + OString::number(i) + "h1v1h-1z");
96 }
97 }
98 }
99 sb.append("\"/>\n</svg>");
100 return sb.toString();
101}
102
103std::string GetBarCodeType(int type)
104{
105 switch (type)
106 {
107 case 1:
108 return "Code128";
109 default:
110 return "QRCode";
111 }
112}
113
114OString GenerateQRCode(std::u16string_view aQRText, tools::Long aQRECC, int aQRBorder, int aQRType)
115{
116 // Associated ZXing error correction levels (0-8) to our constants arbitrarily.
117 int bqrEcc = 1;
118
119 switch (aQRECC)
120 {
121 case css::drawing::BarCodeErrorCorrection::LOW:
122 {
123 bqrEcc = 1;
124 break;
125 }
126 case css::drawing::BarCodeErrorCorrection::MEDIUM:
127 {
128 bqrEcc = 3;
129 break;
130 }
131 case css::drawing::BarCodeErrorCorrection::QUARTILE:
132 {
133 bqrEcc = 5;
134 break;
135 }
136 case css::drawing::BarCodeErrorCorrection::HIGH:
137 {
138 bqrEcc = 7;
139 break;
140 }
141 }
142
143 OString o = OUStringToOString(aQRText, RTL_TEXTENCODING_UTF8);
144 std::string QRText(o.getStr(), o.getLength());
145 ZXing::BarcodeFormat format = ZXing::BarcodeFormatFromString(GetBarCodeType(aQRType));
146 auto writer = ZXing::MultiFormatWriter(format).setMargin(aQRBorder).setEccLevel(bqrEcc);
147 writer.setEncoding(ZXing::CharacterSet::UTF8);
148 ZXing::BitMatrix bitmatrix = writer.encode(ZXing::TextUtfEncoding::FromUtf8(QRText), 0, 0);
149 return ConvertToSVGFormat(bitmatrix);
150}
151#endif
152
153} // anonymous namespace
154
155QrCodeGenDialog::QrCodeGenDialog(weld::Widget* pParent, Reference<XModel> xModel,
156 bool bEditExisting)
157 : GenericDialogController(pParent, "cui/ui/qrcodegen.ui", "QrCodeGenDialog")
158 , m_xModel(std::move(xModel))
159 , m_xEdittext(m_xBuilder->weld_entry("edit_text"))
160 , m_xECC{ m_xBuilder->weld_radio_button("button_low"),
161 m_xBuilder->weld_radio_button("button_medium"),
162 m_xBuilder->weld_radio_button("button_quartile"),
163 m_xBuilder->weld_radio_button("button_high") }
164 , m_xSpinBorder(m_xBuilder->weld_spin_button("edit_margin"))
165 , m_xComboType(m_xBuilder->weld_combo_box("choose_type"))
166#if ENABLE_ZXING
167 , mpParent(pParent)
168#endif
169{
170 if (!bEditExisting)
171 {
172 // TODO: This only works in Writer doc. Should also work in shapes
173 Reference<XIndexAccess> xSelections(m_xModel->getCurrentSelection(), UNO_QUERY);
174 if (xSelections.is())
175 {
176 Reference<XTextRange> xSelection(xSelections->getByIndex(0), UNO_QUERY);
177 if (xSelection.is())
178 m_xEdittext->set_text(xSelection->getString());
179 }
180 return;
181 }
182
183 Reference<container::XIndexAccess> xIndexAccess(m_xModel->getCurrentSelection(),
184 UNO_QUERY_THROW);
185 Reference<XPropertySet> xProps(xIndexAccess->getByIndex(0), UNO_QUERY_THROW);
186
187 // Read properties from selected QR Code
188 css::drawing::BarCode aBarCode;
189 xProps->getPropertyValue("BarCodeProperties") >>= aBarCode;
190
191 m_xEdittext->set_text(aBarCode.Payload);
192
193 //Get Error Correction Constant from selected QR Code
194 GetErrorCorrection(aBarCode.ErrorCorrection);
195
196 m_xSpinBorder->set_value(aBarCode.Border);
197
198 m_xComboType->set_active(aBarCode.Type);
199
200 // Mark this as existing shape
202}
203
205{
206#if ENABLE_ZXING
207 short nRet;
208 while (true)
209 {
210 nRet = GenericDialogController::run();
211 if (nRet == RET_OK)
212 {
213 try
214 {
215 Apply();
216 break;
217 }
218 catch (const std::exception&)
219 {
220 std::unique_ptr<weld::MessageDialog> xBox(Application::CreateMessageDialog(
221 mpParent, VclMessageType::Warning, VclButtonsType::Ok,
222 CuiResId(RID_CUISTR_QRCODEDATALONG)));
223 xBox->run();
224 }
225 }
226 else
227 break;
228 }
229 return nRet;
230#else
231 return RET_CANCEL;
232#endif
233}
234
236{
237#if ENABLE_ZXING
238 css::drawing::BarCode aBarCode;
239 aBarCode.Payload = m_xEdittext->get_text();
240 aBarCode.Type = m_xComboType->get_active();
241
242 bool bLowECCActive(m_xECC[0]->get_active());
243 bool bMediumECCActive(m_xECC[1]->get_active());
244 bool bQuartileECCActive(m_xECC[2]->get_active());
245
246 if (bLowECCActive)
247 {
248 aBarCode.ErrorCorrection = css::drawing::BarCodeErrorCorrection::LOW;
249 }
250 else if (bMediumECCActive)
251 {
252 aBarCode.ErrorCorrection = css::drawing::BarCodeErrorCorrection::MEDIUM;
253 }
254 else if (bQuartileECCActive)
255 {
256 aBarCode.ErrorCorrection = css::drawing::BarCodeErrorCorrection::QUARTILE;
257 }
258 else
259 {
260 aBarCode.ErrorCorrection = css::drawing::BarCodeErrorCorrection::HIGH;
261 }
262
263 aBarCode.Border = m_xSpinBorder->get_value();
264
265 // Read svg and replace placeholder texts
266 OString aSvgImage = GenerateQRCode(aBarCode.Payload, aBarCode.ErrorCorrection, aBarCode.Border,
267 aBarCode.Type);
268
269 // Insert/Update graphic
270 SvMemoryStream aSvgStream(4096, 4096);
271 aSvgStream.WriteOString(aSvgImage);
272 Reference<XInputStream> xInputStream(new utl::OSeekableInputStreamWrapper(aSvgStream));
273 Reference<XComponentContext> xContext(comphelper::getProcessComponentContext());
274 Reference<XGraphicProvider> xProvider = css::graphic::GraphicProvider::create(xContext);
275
276 Sequence<PropertyValue> aMediaProperties{ comphelper::makePropertyValue("InputStream",
277 xInputStream) };
278 Reference<XGraphic> xGraphic(xProvider->queryGraphic(aMediaProperties));
279
280 bool bIsExistingQRCode = m_xExistingShapeProperties.is();
281 Reference<XPropertySet> xShapeProps;
282 if (bIsExistingQRCode)
283 xShapeProps = m_xExistingShapeProperties;
284 else
285 xShapeProps.set(Reference<lang::XMultiServiceFactory>(m_xModel, UNO_QUERY_THROW)
286 ->createInstance("com.sun.star.drawing.GraphicObjectShape"),
287 UNO_QUERY);
288
289 xShapeProps->setPropertyValue("Graphic", Any(xGraphic));
290
291 // Set QRCode properties
292 xShapeProps->setPropertyValue("BarCodeProperties", Any(aBarCode));
293
294 if (bIsExistingQRCode)
295 return;
296
297 // Default size
298 Reference<XShape> xShape(xShapeProps, UNO_QUERY);
299 awt::Size aShapeSize;
300 aShapeSize.Height = 4000;
301 aShapeSize.Width = 4000;
302 xShape->setSize(aShapeSize);
303
304 // Default anchoring
305 xShapeProps->setPropertyValue("AnchorType", Any(TextContentAnchorType_AT_PARAGRAPH));
306
307 const Reference<XServiceInfo> xServiceInfo(m_xModel, UNO_QUERY_THROW);
308
309 // Writer
310 if (xServiceInfo->supportsService("com.sun.star.text.TextDocument"))
311 {
312 Reference<XTextContent> xTextContent(xShape, UNO_QUERY_THROW);
313 Reference<XTextViewCursorSupplier> xViewCursorSupplier(m_xModel->getCurrentController(),
314 UNO_QUERY_THROW);
315 Reference<XTextViewCursor> xCursor = xViewCursorSupplier->getViewCursor();
316 // use cursor's XText - it might be in table cell, frame, ...
317 Reference<XText> const xText(xCursor->getText());
318 assert(xText.is());
319 xText->insertTextContent(xCursor, xTextContent, true);
320 return;
321 }
322
323 // Calc
324 else if (xServiceInfo->supportsService("com.sun.star.sheet.SpreadsheetDocument"))
325 {
326 Reference<XPropertySet> xSheetCell(m_xModel->getCurrentSelection(), UNO_QUERY_THROW);
327 awt::Point aCellPosition;
328 xSheetCell->getPropertyValue("Position") >>= aCellPosition;
329 xShape->setPosition(aCellPosition);
330
331 Reference<XSpreadsheetView> xView(m_xModel->getCurrentController(), UNO_QUERY_THROW);
332 Reference<XSpreadsheet> xSheet(xView->getActiveSheet(), UNO_SET_THROW);
333 Reference<XDrawPageSupplier> xDrawPageSupplier(xSheet, UNO_QUERY_THROW);
334 Reference<XDrawPage> xDrawPage(xDrawPageSupplier->getDrawPage(), UNO_SET_THROW);
335 Reference<XShapes> xShapes(xDrawPage, UNO_QUERY_THROW);
336
337 xShapes->add(xShape);
338 return;
339 }
340
341 //Impress and Draw
342 else if (xServiceInfo->supportsService("com.sun.star.presentation.PresentationDocument")
343 || xServiceInfo->supportsService("com.sun.star.drawing.DrawingDocument"))
344 {
345 Reference<XDrawView> xView(m_xModel->getCurrentController(), UNO_QUERY_THROW);
346 Reference<XDrawPage> xPage(xView->getCurrentPage(), UNO_SET_THROW);
347 Reference<XShapes> xShapes(xPage, UNO_QUERY_THROW);
348
349 xShapes->add(xShape);
350 return;
351 }
352
353 else
354 {
355 //Not implemented for math,base and other apps.
356 throw uno::RuntimeException("Not implemented");
357 }
358#endif
359}
360
362{
363 switch (ErrorCorrection)
364 {
365 case css::drawing::BarCodeErrorCorrection::LOW:
366 {
367 m_xECC[0]->set_active(true);
368 break;
369 }
370 case css::drawing::BarCodeErrorCorrection::MEDIUM:
371 {
372 m_xECC[1]->set_active(true);
373 break;
374 }
375 case css::drawing::BarCodeErrorCorrection::QUARTILE:
376 {
377 m_xECC[2]->set_active(true);
378 break;
379 }
380 case css::drawing::BarCodeErrorCorrection::HIGH:
381 {
382 m_xECC[3]->set_active(true);
383 break;
384 }
385 }
386}
387
388/* vim:set shiftwidth=4 softtabstop=4 expandtab cinoptions=b1,g0,N-s cinkeys+=0=break: */
HRESULT createInstance(REFIID iid, Ifc **ppIfc)
static weld::MessageDialog * CreateMessageDialog(weld::Widget *pParent, VclMessageType eMessageType, VclButtonsType eButtonType, const OUString &rPrimaryMessage, bool bMobile=false)
virtual short run() override
QrCodeGenDialog(weld::Widget *pParent, css::uno::Reference< css::frame::XModel > xModel, bool bEditExisting)
std::unique_ptr< weld::Entry > m_xEdittext
std::unique_ptr< weld::SpinButton > m_xSpinBorder
css::uno::Reference< css::beans::XPropertySet > m_xExistingShapeProperties
std::unique_ptr< weld::RadioButton > m_xECC[4]
css::uno::Reference< css::frame::XModel > m_xModel
std::unique_ptr< weld::ComboBox > m_xComboType
void GetErrorCorrection(tools::Long)
SvStream & WriteOString(std::string_view rStr)
OUString CuiResId(TranslateId aKey)
Definition: cuiresmgr.cxx:23
Reference< frame::XModel > m_xModel
RegionData_Impl * mpParent
if(aStr !=aBuf) UpdateName_Impl(m_xFollowLb.get()
Reference< XComponentContext > getProcessComponentContext()
css::beans::PropertyValue makePropertyValue(const OUString &rName, T &&rValue)
int i
OString OUStringToOString(std::u16string_view str, ConnectionSettings const *settings)
long Long
Reference< XModel > xModel
RET_OK
RET_CANCEL