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