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