summaryrefslogtreecommitdiffstats
path: root/cui/source/dialogs/screenshotannotationdlg.cxx
blob: fca03c02d42d9e3472d80340a3514f840be4715e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
 * This file is part of the LibreOffice project.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 *
 * This file incorporates work covered by the following license notice:
 *
 *   Licensed to the Apache Software Foundation (ASF) under one or more
 *   contributor license agreements. See the NOTICE file distributed
 *   with this work for additional information regarding copyright
 *   ownership. The ASF licenses this file to you under the Apache
 *   License, Version 2.0 (the "License"); you may not use this file
 *   except in compliance with the License. You may obtain a copy of
 *   the License at http://www.apache.org/licenses/LICENSE-2.0 .
 */

#include <screenshotannotationdlg.hxx>

#include <strings.hrc>
#include <dialmgr.hxx>

#include <basegfx/range/b2irange.hxx>
#include <com/sun/star/ui/dialogs/TemplateDescription.hpp>
#include <com/sun/star/ui/dialogs/ExecutableDialogResults.hpp>
#include <com/sun/star/ui/dialogs/XFilePicker3.hpp>

#include <comphelper/random.hxx>
#include <basegfx/polygon/b2dpolygontools.hxx>
#include <sfx2/filedlghelper.hxx>
#include <tools/stream.hxx>
#include <tools/urlobj.hxx>
#include <vcl/bitmapex.hxx>
#include <vcl/customweld.hxx>
#include <vcl/event.hxx>
#include <vcl/filter/PngImageWriter.hxx>
#include <vcl/svapp.hxx>
#include <vcl/salgtype.hxx>
#include <vcl/virdev.hxx>
#include <vcl/weld.hxx>
#include <svtools/optionsdrawinglayer.hxx>
#include <basegfx/matrix/b2dhommatrix.hxx>
#include <set>
#include <string_view>

using namespace com::sun::star;

namespace
{
    OUString lcl_genRandom( std::u16string_view rId )
    {
        //FIXME: plus timestamp
        unsigned int nRand = comphelper::rng::uniform_uint_distribution(0, 0xFFFF);
        return OUString( rId + OUString::number( nRand ) );
    }


    OUString lcl_AltDescr()
    {
        OUString aTempl("<alt id=\"%1\">"
                        " " //FIXME real dialog title or something
                        "</alt>");
        aTempl = aTempl.replaceFirst( "%1", lcl_genRandom(u"alt_id") );

        return aTempl;
    }

    OUString lcl_Image( std::u16string_view rScreenshotId, const Size& rSize )
    {
        OUString aTempl("<image id=\"%1\" src=\"media/screenshots/%2.png\""
                           " width=\"%3cm\"  height=\"%4cm\">"
                           "%5"
                        "</image>");
        aTempl = aTempl.replaceFirst( "%1", lcl_genRandom(u"img_id") );
        aTempl = aTempl.replaceFirst( "%2", rScreenshotId );
        aTempl = aTempl.replaceFirst( "%3", OUString::number( rSize.Width() ) );
        aTempl = aTempl.replaceFirst( "%4", OUString::number( rSize.Height() ) );
        aTempl = aTempl.replaceFirst( "%5", lcl_AltDescr() );

        return aTempl;
    }

    OUString lcl_ParagraphWithImage( std::u16string_view rScreenshotId, const Size& rSize )
    {
        OUString aTempl( "<paragraph id=\"%1\" role=\"paragraph\">%2"
                         "</paragraph>"  SAL_NEWLINE_STRING );
        aTempl = aTempl.replaceFirst( "%1", lcl_genRandom(u"par_id") );
        aTempl = aTempl.replaceFirst( "%2", lcl_Image(rScreenshotId, rSize) );

        return aTempl;
    }

    OUString lcl_Bookmark( std::u16string_view rWidgetId )
    {
        OUString aTempl = "<!-- Bookmark for widget %1 -->" SAL_NEWLINE_STRING
                          "<bookmark branch=\"hid/%2\" id=\"%3\" localize=\"false\"/>" SAL_NEWLINE_STRING;
        aTempl = aTempl.replaceFirst( "%1", rWidgetId );
        aTempl = aTempl.replaceFirst( "%2", rWidgetId );
        aTempl = aTempl.replaceFirst( "%3", lcl_genRandom(u"bm_id") );

        return aTempl;
    }
}

namespace
{
    class Picture : public weld::CustomWidgetController
    {
    private:
        ScreenshotAnnotationDlg_Impl *m_pDialog;
        bool m_bMouseOver;
    private:
        virtual void Paint(vcl::RenderContext& rRenderContext, const tools::Rectangle&) override;
        virtual bool MouseMove(const MouseEvent& rMouseEvent) override;
        virtual bool MouseButtonUp(const MouseEvent& rMouseEvent) override;
    public:
        Picture(ScreenshotAnnotationDlg_Impl* pDialog)
            : m_pDialog(pDialog)
            , m_bMouseOver(false)
        {
        }

        bool IsMouseOver() const
        {
            return m_bMouseOver;
        }
    };
}

class ScreenshotAnnotationDlg_Impl
{
public:
    ScreenshotAnnotationDlg_Impl(
        weld::Window* pParent,
        weld::Builder& rParent,
        weld::Dialog& rParentDialog);
    ~ScreenshotAnnotationDlg_Impl();

private:
    // Handler for click on save
    DECL_LINK(saveButtonHandler, weld::Button&, void);

    // helper methods
    weld::ScreenShotEntry* CheckHit(const basegfx::B2IPoint& rPosition);
    void PaintScreenShotEntry(
        const weld::ScreenShotEntry& rEntry,
        const Color& rColor,
        double fLineWidth,
        double fTransparency);
    void RepaintToBuffer(
        bool bUseDimmed = false,
        bool bPaintHilight = false);
    void RepaintPictureElement();
    Point GetOffsetInPicture() const;

    // local variables
    weld::Window*               mpParentWindow;
    weld::Dialog&               mrParentDialog;
    BitmapEx                    maParentDialogBitmap;
    BitmapEx                    maDimmedDialogBitmap;
    Size                        maParentDialogSize;

    // VirtualDevice for buffered interaction paints
    VclPtr<VirtualDevice>       mxVirtualBufferDevice;

    // all detected children
    weld::ScreenShotCollection  maAllChildren;

    // highlighted/selected children
    weld::ScreenShotEntry*           mpHilighted;
    std::set< weld::ScreenShotEntry* >
                                maSelected;

    // list of detected controls
    Picture maPicture;
    std::unique_ptr<weld::CustomWeld> mxPicture;
    std::unique_ptr<weld::TextView> mxText;
    std::unique_ptr<weld::Button> mxSave;

    // save as text
    OUString                    maSaveAsText;
    OUString                    maMainMarkupText;

    // folder URL
    static OUString             maLastFolderURL;
public:
    void Paint(vcl::RenderContext& rRenderContext);
    bool MouseMove(const MouseEvent& rMouseEvent);
    bool MouseButtonUp();
};

OUString ScreenshotAnnotationDlg_Impl::maLastFolderURL = OUString();

ScreenshotAnnotationDlg_Impl::ScreenshotAnnotationDlg_Impl(
    weld::Window* pParent,
    weld::Builder& rParentBuilder,
    weld::Dialog& rParentDialog)
:   mpParentWindow(pParent),
    mrParentDialog(rParentDialog),
    mxVirtualBufferDevice(nullptr),
    mpHilighted(nullptr),
    maPicture(this),
    maSaveAsText(CuiResId(RID_CUISTR_SAVE_SCREENSHOT_AS))
{
    VclPtr<VirtualDevice> xParentDialogSurface(rParentDialog.screenshot());
    maParentDialogSize = xParentDialogSurface->GetOutputSizePixel();
    maParentDialogBitmap = xParentDialogSurface->GetBitmapEx(Point(), maParentDialogSize);
    maDimmedDialogBitmap = maParentDialogBitmap;

    // image ain't empty
    assert(!maParentDialogBitmap.IsEmpty());
    assert(0 != maParentDialogBitmap.GetSizePixel().Width());
    assert(0 != maParentDialogBitmap.GetSizePixel().Height());

    // get needed widgets
    mxPicture.reset(new weld::CustomWeld(rParentBuilder, "picture", maPicture));
    assert(mxPicture);
    mxText = rParentBuilder.weld_text_view("text");
    assert(mxText);
    mxSave = rParentBuilder.weld_button("save");
    assert(mxSave);

    // set screenshot image at DrawingArea, resize, set event listener
    if (mxPicture)
    {
        maAllChildren = mrParentDialog.collect_screenshot_data();

        // to make clear that maParentDialogBitmap is a background image, adjust
        // luminance a bit for maDimmedDialogBitmap - other methods may be applied
        maDimmedDialogBitmap.Adjust(-15, 0, 0, 0, 0);

        // init paint buffering VirtualDevice
        mxVirtualBufferDevice = VclPtr<VirtualDevice>::Create(*Application::GetDefaultDevice(), DeviceFormat::WITHOUT_ALPHA);
        mxVirtualBufferDevice->SetOutputSizePixel(maParentDialogSize);
        mxVirtualBufferDevice->SetFillColor(COL_TRANSPARENT);

        // initially set image for picture control
        mxVirtualBufferDevice->DrawBitmapEx(Point(0, 0), maDimmedDialogBitmap);

        // set size for picture control, this will re-layout so that
        // the picture control shows the whole dialog
        maPicture.SetOutputSizePixel(maParentDialogSize);
        mxPicture->set_size_request(maParentDialogSize.Width(), maParentDialogSize.Height());

        mxPicture->queue_draw();
    }

    // set some test text at VclMultiLineEdit and make read-only - only
    // copying content to clipboard is allowed
    if (mxText)
    {
        mxText->set_size_request(400, mxText->get_height_rows(10));
        OUString aHelpId = mrParentDialog.get_help_id();
        Size aSizeCm = Application::GetDefaultDevice()->PixelToLogic(maParentDialogSize, MapMode(MapUnit::MapCM));
        maMainMarkupText = lcl_ParagraphWithImage( aHelpId, aSizeCm );
        mxText->set_text( maMainMarkupText );
        mxText->set_editable(false);
    }

    // set click handler for save button
    if (mxSave)
    {
        mxSave->connect_clicked(LINK(this, ScreenshotAnnotationDlg_Impl, saveButtonHandler));
    }
}

ScreenshotAnnotationDlg_Impl::~ScreenshotAnnotationDlg_Impl()
{
    mxVirtualBufferDevice.disposeAndClear();
}

IMPL_LINK_NOARG(ScreenshotAnnotationDlg_Impl, saveButtonHandler, weld::Button&, void)
{
    // 'save screenshot...' pressed, offer to save maParentDialogBitmap
    // as PNG image, use *.id file name as screenshot file name offering
    // get a suggestion for the filename from buildable name
    OUString aDerivedFileName = mrParentDialog.get_buildable_name();

    auto xFileDlg = std::make_unique<sfx2::FileDialogHelper>(ui::dialogs::TemplateDescription::FILESAVE_AUTOEXTENSION,
                                                             FileDialogFlags::NONE, mpParentWindow);
    xFileDlg->SetContext(sfx2::FileDialogHelper::ScreenshotAnnotation);

    const uno::Reference< ui::dialogs::XFilePicker3 > xFilePicker = xFileDlg->GetFilePicker();

    xFilePicker->setTitle(maSaveAsText);

    if (!maLastFolderURL.isEmpty())
    {
        xFilePicker->setDisplayDirectory(maLastFolderURL);
    }

    xFilePicker->appendFilter("*.png", "*.png");
    xFilePicker->setCurrentFilter("*.png");
    xFilePicker->setDefaultName(aDerivedFileName);
    xFilePicker->setMultiSelectionMode(false);

    if (xFilePicker->execute() != ui::dialogs::ExecutableDialogResults::OK)
        return;

    maLastFolderURL = xFilePicker->getDisplayDirectory();
    const uno::Sequence< OUString > files(xFilePicker->getSelectedFiles());

    if (!files.hasElements())
        return;

    OUString aConfirmedName = files[0];

    if (aConfirmedName.isEmpty())
        return;

    INetURLObject aConfirmedURL(aConfirmedName);
    OUString aCurrentExtension(aConfirmedURL.getExtension());

    if (!aCurrentExtension.isEmpty() && aCurrentExtension != "png")
    {
        aConfirmedURL.removeExtension();
        aCurrentExtension.clear();
    }

    if (aCurrentExtension.isEmpty())
    {
        aConfirmedURL.setExtension(u"png");
    }

    // open stream
    SvFileStream aNew(aConfirmedURL.PathToFileName(), StreamMode::WRITE | StreamMode::TRUNC);

    if (!aNew.IsOpen())
        return;

    // prepare bitmap to save - do use the original screenshot here,
    // not the dimmed one
    RepaintToBuffer();

    // extract Bitmap
    const BitmapEx aTargetBitmap(
        mxVirtualBufferDevice->GetBitmapEx(
        Point(0, 0),
        mxVirtualBufferDevice->GetOutputSizePixel()));

    // write as PNG
    vcl::PngImageWriter aPNGWriter(aNew);
    aPNGWriter.write(aTargetBitmap);
}

weld::ScreenShotEntry* ScreenshotAnnotationDlg_Impl::CheckHit(const basegfx::B2IPoint& rPosition)
{
    weld::ScreenShotEntry* pRetval = nullptr;

    for (auto&& rCandidate : maAllChildren)
    {
        if (rCandidate.getB2IRange().isInside(rPosition))
        {
            if (pRetval)
            {
                if (pRetval->getB2IRange().isInside(rCandidate.getB2IRange().getMinimum())
                    && pRetval->getB2IRange().isInside(rCandidate.getB2IRange().getMaximum()))
                {
                    pRetval = &rCandidate;
                }
            }
            else
            {
                pRetval = &rCandidate;
            }
        }
    }

    return pRetval;
}

void ScreenshotAnnotationDlg_Impl::PaintScreenShotEntry(
    const weld::ScreenShotEntry& rEntry,
    const Color& rColor,
    double fLineWidth,
    double fTransparency)
{
    if (!(mxPicture && mxVirtualBufferDevice))
        return;

    basegfx::B2DRange aB2DRange(rEntry.getB2IRange());

    // grow in pixels to be a little bit 'outside'. This also
    // ensures that getWidth()/getHeight() ain't 0.0 (see division below)
    static const double fGrowTopLeft(1.5);
    static const double fGrowBottomRight(0.5);
    aB2DRange.expand(aB2DRange.getMinimum() - basegfx::B2DPoint(fGrowTopLeft, fGrowTopLeft));
    aB2DRange.expand(aB2DRange.getMaximum() + basegfx::B2DPoint(fGrowBottomRight, fGrowBottomRight));

    // edge rounding in pixel. Need to convert, value for
    // createPolygonFromRect is relative [0.0 .. 1.0]
    static const double fEdgeRoundPixel(8.0);
    const basegfx::B2DPolygon aPolygon(
        basegfx::utils::createPolygonFromRect(
        aB2DRange,
        fEdgeRoundPixel / aB2DRange.getWidth(),
        fEdgeRoundPixel / aB2DRange.getHeight()));

    mxVirtualBufferDevice->SetLineColor(rColor);

    // try to use transparency
    if (!mxVirtualBufferDevice->DrawPolyLineDirect(
        basegfx::B2DHomMatrix(),
        aPolygon,
        fLineWidth,
        fTransparency,
        nullptr, // MM01
        basegfx::B2DLineJoin::Round))
    {
        // no transparency, draw without
        mxVirtualBufferDevice->DrawPolyLine(
            aPolygon,
            fLineWidth);
    }
}

Point ScreenshotAnnotationDlg_Impl::GetOffsetInPicture() const
{
    const Size aPixelSizeTarget(maPicture.GetOutputSizePixel());

    return Point(
        aPixelSizeTarget.Width() > maParentDialogSize.Width() ? (aPixelSizeTarget.Width() - maParentDialogSize.Width()) >> 1 : 0,
        aPixelSizeTarget.Height() > maParentDialogSize.Height() ? (aPixelSizeTarget.Height() - maParentDialogSize.Height()) >> 1 : 0);
}

void ScreenshotAnnotationDlg_Impl::RepaintToBuffer(
    bool bUseDimmed,
    bool bPaintHilight)
{
    if (!mxVirtualBufferDevice)
        return;

    // reset with original screenshot bitmap
    mxVirtualBufferDevice->DrawBitmapEx(
        Point(0, 0),
        bUseDimmed ? maDimmedDialogBitmap : maParentDialogBitmap);

    // get various options
    const Color aHilightColor(SvtOptionsDrawinglayer::getHilightColor());
    const double fTransparence(SvtOptionsDrawinglayer::GetTransparentSelectionPercent() * 0.01);
    const bool bIsAntiAliasing(SvtOptionsDrawinglayer::IsAntiAliasing());
    const AntialiasingFlags nOldAA(mxVirtualBufferDevice->GetAntialiasing());

    if (bIsAntiAliasing)
    {
        mxVirtualBufferDevice->SetAntialiasing(AntialiasingFlags::Enable);
    }

    // paint selected entries
    for (auto&& rCandidate : maSelected)
    {
        static const double fLineWidthEntries(5.0);
        PaintScreenShotEntry(*rCandidate, COL_LIGHTRED, fLineWidthEntries, fTransparence * 0.2);
    }

    // paint highlighted entry
    if (mpHilighted && bPaintHilight)
    {
        static const double fLineWidthHilight(7.0);
        PaintScreenShotEntry(*mpHilighted, aHilightColor, fLineWidthHilight, fTransparence);
    }

    if (bIsAntiAliasing)
    {
        mxVirtualBufferDevice->SetAntialiasing(nOldAA);
    }
}

void ScreenshotAnnotationDlg_Impl::RepaintPictureElement()
{
    if (mxPicture && mxVirtualBufferDevice)
    {
        // reset image in buffer, use dimmed version and allow highlight
        RepaintToBuffer(true, true);
        mxPicture->queue_draw();
    }
}

void ScreenshotAnnotationDlg_Impl::Paint(vcl::RenderContext& rRenderContext)
{
    Point aPos(GetOffsetInPicture());
    Size aSize(mxVirtualBufferDevice->GetOutputSizePixel());
    rRenderContext.DrawOutDev(aPos, aSize, Point(), aSize, *mxVirtualBufferDevice);
}

void Picture::Paint(vcl::RenderContext& rRenderContext, const tools::Rectangle&)
{
    m_pDialog->Paint(rRenderContext);
}

bool ScreenshotAnnotationDlg_Impl::MouseMove(const MouseEvent& rMouseEvent)
{
    bool bRepaint(false);

    if (maPicture.IsMouseOver())
    {
        const weld::ScreenShotEntry* pOldHit = mpHilighted;
        const Point aOffset(GetOffsetInPicture());
        const basegfx::B2IPoint aMousePos(
            rMouseEvent.GetPosPixel().X() - aOffset.X(),
            rMouseEvent.GetPosPixel().Y() - aOffset.Y());
        const weld::ScreenShotEntry* pHit = CheckHit(aMousePos);

        if (pHit && pOldHit != pHit)
        {
            mpHilighted = const_cast<weld::ScreenShotEntry*>(pHit);
            bRepaint = true;
        }
    }
    else if (mpHilighted)
    {
        mpHilighted = nullptr;
        bRepaint = true;
    }

    if (bRepaint)
    {
        RepaintPictureElement();
    }

    return true;
}

bool Picture::MouseMove(const MouseEvent& rMouseEvent)
{
    if (rMouseEvent.IsEnterWindow())
        m_bMouseOver = true;
    if (rMouseEvent.IsLeaveWindow())
        m_bMouseOver = false;
    return m_pDialog->MouseMove(rMouseEvent);
}

bool ScreenshotAnnotationDlg_Impl::MouseButtonUp()
{
    // event in picture frame
    bool bRepaint(false);

    if (maPicture.IsMouseOver() && mpHilighted)
    {
        if (maSelected.erase(mpHilighted) == 0)
        {
            maSelected.insert(mpHilighted);
        }

        OUStringBuffer aBookmarks(maMainMarkupText);
        for (auto&& rCandidate : maSelected)
            aBookmarks.append(lcl_Bookmark(rCandidate->GetHelpId()));

        mxText->set_text( aBookmarks.makeStringAndClear() );
        bRepaint = true;
    }

    if (bRepaint)
    {
        RepaintPictureElement();
    }

    return true;
}

bool Picture::MouseButtonUp(const MouseEvent&)
{
    return m_pDialog->MouseButtonUp();
}

ScreenshotAnnotationDlg::ScreenshotAnnotationDlg(weld::Dialog& rParentDialog)
    : GenericDialogController(&rParentDialog, "cui/ui/screenshotannotationdialog.ui", "ScreenshotAnnotationDialog")
{
    m_pImpl.reset(new ScreenshotAnnotationDlg_Impl(m_xDialog.get(), *m_xBuilder, rParentDialog));
}

ScreenshotAnnotationDlg::~ScreenshotAnnotationDlg()
{
}

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */