File: juce_Windowing_linux.cpp

package info (click to toggle)
juce 8.0.6%2Bds-2
  • links: PTS, VCS
  • area: main
  • in suites: trixie
  • size: 78,204 kB
  • sloc: cpp: 521,891; ansic: 159,819; java: 2,996; javascript: 847; xml: 273; python: 224; sh: 162; makefile: 84
file content (876 lines) | stat: -rw-r--r-- 32,420 bytes parent folder | download | duplicates (2)
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
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
/*
  ==============================================================================

   This file is part of the JUCE framework.
   Copyright (c) Raw Material Software Limited

   JUCE is an open source framework subject to commercial or open source
   licensing.

   By downloading, installing, or using the JUCE framework, or combining the
   JUCE framework with any other source code, object code, content or any other
   copyrightable work, you agree to the terms of the JUCE End User Licence
   Agreement, and all incorporated terms including the JUCE Privacy Policy and
   the JUCE Website Terms of Service, as applicable, which will bind you. If you
   do not agree to the terms of these agreements, we will not license the JUCE
   framework to you, and you must discontinue the installation or download
   process and cease use of the JUCE framework.

   JUCE End User Licence Agreement: https://juce.com/legal/juce-8-licence/
   JUCE Privacy Policy: https://juce.com/juce-privacy-policy
   JUCE Website Terms of Service: https://juce.com/juce-website-terms-of-service/

   Or:

   You may also use this code under the terms of the AGPLv3:
   https://www.gnu.org/licenses/agpl-3.0.en.html

   THE JUCE FRAMEWORK IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL
   WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING WARRANTY OF
   MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, ARE DISCLAIMED.

  ==============================================================================
*/

namespace juce
{

//==============================================================================
class LinuxComponentPeer final : public ComponentPeer,
                                 private XWindowSystemUtilities::XSettings::Listener
{
public:
    LinuxComponentPeer (Component& comp, int windowStyleFlags, ::Window parentToAddTo)
        : ComponentPeer (comp, windowStyleFlags),
          isAlwaysOnTop (comp.isAlwaysOnTop())
    {
        // it's dangerous to create a window on a thread other than the message thread.
        JUCE_ASSERT_MESSAGE_MANAGER_IS_LOCKED

        const auto* instance = XWindowSystem::getInstance();

        if (! instance->isX11Available())
            return;

        if (isAlwaysOnTop)
            ++WindowUtilsInternal::numAlwaysOnTopPeers;

        repainter = std::make_unique<LinuxRepaintManager> (*this);

        windowH = instance->createWindow (parentToAddTo, this);
        parentWindow = parentToAddTo;

        setTitle (component.getName());

        if (auto* xSettings = instance->getXSettings())
            xSettings->addListener (this);

        getNativeRealtimeModifiers = []() -> ModifierKeys { return XWindowSystem::getInstance()->getNativeRealtimeModifiers(); };

        updateVBlankTimer();
    }

    ~LinuxComponentPeer() override
    {
        // it's dangerous to delete a window on a thread other than the message thread.
        JUCE_ASSERT_MESSAGE_MANAGER_IS_LOCKED

        auto* instance = XWindowSystem::getInstance();

        repainter = nullptr;
        instance->destroyWindow (windowH);

        if (auto* xSettings = instance->getXSettings())
            xSettings->removeListener (this);

        if (isAlwaysOnTop)
            --WindowUtilsInternal::numAlwaysOnTopPeers;
    }

    ::Window getWindowHandle() const noexcept
    {
        return windowH;
    }

    //==============================================================================
    void* getNativeHandle() const override
    {
        return reinterpret_cast<void*> (getWindowHandle());
    }

    //==============================================================================
    void forceSetBounds (const Rectangle<int>& correctedNewBounds, bool isNowFullScreen)
    {
        bounds = correctedNewBounds;

        updateScaleFactorFromNewBounds (bounds, false);

        auto physicalBounds = parentWindow == 0 ? Desktop::getInstance().getDisplays().logicalToPhysical (bounds)
                                                : bounds * currentScaleFactor;

        WeakReference<Component> deletionChecker (&component);

        // If we are in a ConfigureNotify handler then forceSetBounds is being called as a
        // consequence of X11 telling us what the window size is. There's no need to report this
        // size back again to X11. By this we are avoiding a pitfall, when we get many subsequent
        // ConfigureNotify events, many of which has stale size information. By not calling
        // XWindowSystem::setBounds we are not actualising these old, incorrect sizes.
        if (! inConfigureNotifyHandler)
            XWindowSystem::getInstance()->setBounds (windowH, physicalBounds, isNowFullScreen);

        fullScreen = isNowFullScreen;

        if (deletionChecker != nullptr)
        {
            updateBorderSize();
            handleMovedOrResized();
        }
    }

    void setBounds (const Rectangle<int>& newBounds, bool isNowFullScreen) override
    {
        const auto correctedNewBounds = newBounds.withSize (jmax (1, newBounds.getWidth()),
                                                            jmax (1, newBounds.getHeight()));

        if (bounds != correctedNewBounds || fullScreen != isNowFullScreen)
            forceSetBounds (correctedNewBounds, isNowFullScreen);
    }

    Point<int> getScreenPosition (bool physical) const
    {
        auto physicalParentPosition = XWindowSystem::getInstance()->getPhysicalParentScreenPosition();
        auto parentPosition = parentWindow == 0 ? Desktop::getInstance().getDisplays().physicalToLogical (physicalParentPosition)
                                                : physicalParentPosition / currentScaleFactor;

        auto screenBounds = parentWindow == 0 ? bounds
                                              : bounds.translated (parentPosition.x, parentPosition.y);

        if (physical)
            return parentWindow == 0 ? Desktop::getInstance().getDisplays().logicalToPhysical (screenBounds.getTopLeft())
                                     : screenBounds.getTopLeft() * currentScaleFactor;

        return screenBounds.getTopLeft();
    }

    Rectangle<int> getBounds() const override
    {
        return bounds;
    }

    OptionalBorderSize getFrameSizeIfPresent() const override
    {
        return windowBorder;
    }

    BorderSize<int> getFrameSize() const override
    {
        const auto optionalBorderSize = getFrameSizeIfPresent();
        return optionalBorderSize ? (*optionalBorderSize) : BorderSize<int>();
    }

    Point<float> localToGlobal (Point<float> relativePosition) override
    {
        return localToGlobal (*this, relativePosition);
    }

    Point<float> globalToLocal (Point<float> screenPosition) override
    {
        return globalToLocal (*this, screenPosition);
    }

    using ComponentPeer::localToGlobal;
    using ComponentPeer::globalToLocal;

    //==============================================================================
    StringArray getAvailableRenderingEngines() override
    {
        return { "Software Renderer" };
    }

    void setVisible (bool shouldBeVisible) override
    {
        XWindowSystem::getInstance()->setVisible (windowH, shouldBeVisible);
    }

    void setTitle (const String& title) override
    {
        XWindowSystem::getInstance()->setTitle (windowH, title);
    }

    void setMinimised (bool shouldBeMinimised) override
    {
        if (shouldBeMinimised)
            XWindowSystem::getInstance()->setMinimised (windowH, shouldBeMinimised);
        else
            setVisible (true);
    }

    bool isMinimised() const override
    {
        return XWindowSystem::getInstance()->isMinimised (windowH);
    }

    bool isShowing() const override
    {
        return ! XWindowSystem::getInstance()->isMinimised (windowH);
    }

    void setFullScreen (bool shouldBeFullScreen) override
    {
        auto r = lastNonFullscreenBounds; // (get a copy of this before de-minimising)

        setMinimised (false);

        if (fullScreen != shouldBeFullScreen)
        {
            const auto usingNativeTitleBar = ((styleFlags & windowHasTitleBar) != 0);

            if (usingNativeTitleBar)
                XWindowSystem::getInstance()->setMaximised (windowH, shouldBeFullScreen);

            if (shouldBeFullScreen)
                r = usingNativeTitleBar ? XWindowSystem::getInstance()->getWindowBounds (windowH, parentWindow)
                                        : Desktop::getInstance().getDisplays().getDisplayForRect (bounds)->userArea;

            if (! r.isEmpty())
                setBounds (detail::ScalingHelpers::scaledScreenPosToUnscaled (component, r), shouldBeFullScreen);

            component.repaint();
        }
    }

    bool isFullScreen() const override
    {
        return fullScreen;
    }

    bool contains (Point<int> localPos, bool trueIfInAChildWindow) const override
    {
        if (! bounds.withZeroOrigin().contains (localPos))
            return false;

        for (int i = Desktop::getInstance().getNumComponents(); --i >= 0;)
        {
            auto* c = Desktop::getInstance().getComponent (i);

            if (c == &component)
                break;

            if (! c->isVisible())
                continue;

            auto* otherPeer = c->getPeer();
            jassert (otherPeer == nullptr || dynamic_cast<LinuxComponentPeer*> (c->getPeer()) != nullptr);

            if (auto* peer = static_cast<LinuxComponentPeer*> (otherPeer))
                if (peer->contains (globalToLocal (*peer, localToGlobal (*this, localPos.toFloat())).roundToInt(), true))
                    return false;
        }

        if (trueIfInAChildWindow)
            return true;

        return XWindowSystem::getInstance()->contains (windowH, localPos * currentScaleFactor);
    }

    void toFront (bool makeActive) override
    {
        if (makeActive)
        {
            setVisible (true);
            grabFocus();
        }

        XWindowSystem::getInstance()->toFront (windowH, makeActive);
        handleBroughtToFront();
    }

    void toBehind (ComponentPeer* other) override
    {
        if (auto* otherPeer = dynamic_cast<LinuxComponentPeer*> (other))
        {
            if (otherPeer->styleFlags & windowIsTemporary)
                return;

            setMinimised (false);
            XWindowSystem::getInstance()->toBehind (windowH, otherPeer->windowH);
        }
        else
        {
            jassertfalse; // wrong type of window?
        }
    }

    bool isFocused() const override
    {
        return XWindowSystem::getInstance()->isFocused (windowH);
    }

    void grabFocus() override
    {
        if (XWindowSystem::getInstance()->grabFocus (windowH))
            isActiveApplication = true;
    }

    //==============================================================================
    void repaint (const Rectangle<int>& area) override
    {
        if (repainter != nullptr)
            repainter->repaint (area.getIntersection (bounds.withZeroOrigin()));
    }

    void performAnyPendingRepaintsNow() override
    {
        if (repainter != nullptr)
            repainter->performAnyPendingRepaintsNow();
    }

    void setIcon (const Image& newIcon) override
    {
        XWindowSystem::getInstance()->setIcon (windowH, newIcon);
    }

    double getPlatformScaleFactor() const noexcept override
    {
        return currentScaleFactor;
    }

    void setAlpha (float) override                                  {}
    bool setAlwaysOnTop (bool) override                             { return false; }
    void textInputRequired (Point<int>, TextInputTarget&) override  {}

    //==============================================================================
    void addOpenGLRepaintListener (Component* dummy)
    {
        if (dummy != nullptr)
            glRepaintListeners.addIfNotAlreadyThere (dummy);
    }

    void removeOpenGLRepaintListener (Component* dummy)
    {
        if (dummy != nullptr)
            glRepaintListeners.removeAllInstancesOf (dummy);
    }

    void repaintOpenGLContexts()
    {
        for (auto* c : glRepaintListeners)
            c->handleCommandMessage (0);
    }

    //==============================================================================
    ::Window getParentWindow()                         { return parentWindow; }
    void setParentWindow (::Window newParent)          { parentWindow = newParent; }

    //==============================================================================
    bool isConstrainedNativeWindow() const
    {
        return constrainer != nullptr
            && (styleFlags & (windowHasTitleBar | windowIsResizable)) == (windowHasTitleBar | windowIsResizable)
            && ! isKioskMode();
    }

    void updateWindowBounds()
    {
        if (windowH == 0)
        {
            jassertfalse;
            return;
        }

        if (isConstrainedNativeWindow())
            XWindowSystem::getInstance()->updateConstraints (windowH);

        auto physicalBounds = XWindowSystem::getInstance()->getWindowBounds (windowH, parentWindow);

        updateScaleFactorFromNewBounds (physicalBounds, true);

        bounds = parentWindow == 0 ? Desktop::getInstance().getDisplays().physicalToLogical (physicalBounds)
                                   : physicalBounds / currentScaleFactor;

        updateVBlankTimer();
    }

    void updateBorderSize()
    {
        if ((styleFlags & windowHasTitleBar) == 0)
        {
            windowBorder = ComponentPeer::OptionalBorderSize { BorderSize<int>() };
        }
        else if (! windowBorder
                 || ((*windowBorder).getTopAndBottom() == 0 && (*windowBorder).getLeftAndRight() == 0))
        {
            windowBorder = [&]()
            {
                if (auto unscaledBorderSize = XWindowSystem::getInstance()->getBorderSize (windowH))
                    return OptionalBorderSize { (*unscaledBorderSize).multipliedBy (1.0 / currentScaleFactor) };

                return OptionalBorderSize {};
            }();
        }
    }

    bool setWindowAssociation (::Window windowIn)
    {
        clearWindowAssociation();
        association = { this, windowIn };
        return association.isValid();
    }

    void clearWindowAssociation() { association = {}; }

    void startHostManagedResize (Point<int>, ResizableBorderComponent::Zone zone) override
    {
        XWindowSystem::getInstance()->startHostManagedResize (windowH, zone);
    }

    //==============================================================================
    static bool isActiveApplication;
    bool focused = false;
    bool inConfigureNotifyHandler = false;

private:
    //==============================================================================
    class LinuxRepaintManager
    {
    public:
        LinuxRepaintManager (LinuxComponentPeer& p)
            : peer (p),
              isSemiTransparentWindow ((peer.getStyleFlags() & ComponentPeer::windowIsSemiTransparent) != 0)
        {
        }

        void dispatchDeferredRepaints()
        {
            XWindowSystem::getInstance()->processPendingPaintsForWindow (peer.windowH);

            if (XWindowSystem::getInstance()->getNumPaintsPendingForWindow (peer.windowH) > 0)
                return;

            if (! regionsNeedingRepaint.isEmpty())
                performAnyPendingRepaintsNow();
            else if (Time::getApproximateMillisecondCounter() > lastTimeImageUsed + 3000)
                image = Image();
        }

        void repaint (Rectangle<int> area)
        {
            regionsNeedingRepaint.add (area * peer.currentScaleFactor);
        }

        void performAnyPendingRepaintsNow()
        {
            if (XWindowSystem::getInstance()->getNumPaintsPendingForWindow (peer.windowH) > 0)
                return;

            auto originalRepaintRegion = regionsNeedingRepaint;
            regionsNeedingRepaint.clear();
            auto totalArea = originalRepaintRegion.getBounds();

            if (! totalArea.isEmpty())
            {
                const auto wasImageNull = image.isNull();

                if (wasImageNull || image.getWidth() < totalArea.getWidth()
                     || image.getHeight() < totalArea.getHeight())
                {
                    image = XWindowSystem::getInstance()->createImage (isSemiTransparentWindow,
                                                                       totalArea.getWidth(), totalArea.getHeight(),
                                                                       useARGBImagesForRendering);
                    if (wasImageNull)
                    {
                        // After calling createImage() XWindowSystem::getWindowBounds() will return
                        // changed coordinates that look like the result of some position
                        // defaulting mechanism. If we handle a configureNotifyEvent after
                        // createImage() and before we would issue new, valid coordinates, we will
                        // apply these default, unwanted coordinates to our window. To avoid that
                        // we immediately send another positioning message to guarantee that the
                        // next configureNotifyEvent will read valid values.
                        //
                        // This issue only occurs right after peer creation, when the image is
                        // null. Updating when only the width or height is changed would lead to
                        // incorrect behaviour.
                        peer.forceSetBounds (detail::ScalingHelpers::scaledScreenPosToUnscaled (peer.component, peer.component.getBoundsInParent()),
                                             peer.isFullScreen());
                    }
                }

                RectangleList<int> adjustedList (originalRepaintRegion);
                adjustedList.offsetAll (-totalArea.getX(), -totalArea.getY());

                if (XWindowSystem::getInstance()->canUseARGBImages())
                    for (auto& i : originalRepaintRegion)
                        image.clear (i - totalArea.getPosition());

                {
                    auto context = peer.getComponent().getLookAndFeel()
                                     .createGraphicsContext (image, -totalArea.getPosition(), adjustedList);

                    context->addTransform (AffineTransform::scale ((float) peer.currentScaleFactor));
                    peer.handlePaint (*context);
                }

                for (auto& i : originalRepaintRegion)
                   XWindowSystem::getInstance()->blitToWindow (peer.windowH, image, i, totalArea);
            }

            lastTimeImageUsed = Time::getApproximateMillisecondCounter();
        }

    private:
        LinuxComponentPeer& peer;
        const bool isSemiTransparentWindow;
        Image image;
        uint32 lastTimeImageUsed = 0;
        RectangleList<int> regionsNeedingRepaint;

        bool useARGBImagesForRendering = XWindowSystem::getInstance()->canUseARGBImages();

        JUCE_DECLARE_NON_COPYABLE (LinuxRepaintManager)
    };

    //==============================================================================
    template <typename This>
    static Point<float> localToGlobal (This& t, Point<float> relativePosition)
    {
        return relativePosition + t.getScreenPosition (false).toFloat();
    }

    template <typename This>
    static Point<float> globalToLocal (This& t, Point<float> screenPosition)
    {
        return screenPosition - t.getScreenPosition (false).toFloat();
    }

    //==============================================================================
    void settingChanged (const XWindowSystemUtilities::XSetting& settingThatHasChanged) override
    {
        static StringArray possibleSettings { XWindowSystem::getWindowScalingFactorSettingName(),
                                              "Gdk/UnscaledDPI",
                                              "Xft/DPI" };

        if (possibleSettings.contains (settingThatHasChanged.name))
            forceDisplayUpdate();
    }

    void updateScaleFactorFromNewBounds (const Rectangle<int>& newBounds, bool isPhysical)
    {
        Point<int> translation = (parentWindow != 0 ? getScreenPosition (isPhysical) : Point<int>());
        const auto& desktop = Desktop::getInstance();

        if (auto* display = desktop.getDisplays().getDisplayForRect (newBounds.translated (translation.x, translation.y),
                                                                     isPhysical))
        {
            auto newScaleFactor = display->scale / desktop.getGlobalScaleFactor();

            if (! approximatelyEqual (newScaleFactor, currentScaleFactor))
            {
                currentScaleFactor = newScaleFactor;
                scaleFactorListeners.call ([&] (ScaleFactorListener& l) { l.nativeScaleFactorChanged (currentScaleFactor); });
            }
        }
    }

    void onVBlank()
    {
        const auto timestampSec = Time::getMillisecondCounterHiRes() / 1000.0;
        callVBlankListeners (timestampSec);

        if (repainter != nullptr)
            repainter->dispatchDeferredRepaints();
    }

    void updateVBlankTimer()
    {
        if (auto* display = Desktop::getInstance().getDisplays().getDisplayForRect (bounds))
        {
            // Some systems fail to set an explicit refresh rate, or ask for a refresh rate of 0
            // (observed on Raspbian Bullseye over VNC). In these situations, use a fallback value.
            const auto newIntFrequencyHz = roundToInt (display->verticalFrequencyHz.value_or (0.0));
            const auto frequencyToUse = newIntFrequencyHz != 0 ? newIntFrequencyHz : 100;

            if (vBlankManager.getTimerInterval() != frequencyToUse)
                vBlankManager.startTimerHz (frequencyToUse);
        }
    }

    //==============================================================================
    std::unique_ptr<LinuxRepaintManager> repainter;
    TimedCallback vBlankManager { [this]() { onVBlank(); } };

    ::Window windowH = {}, parentWindow = {};
    Rectangle<int> bounds;
    ComponentPeer::OptionalBorderSize windowBorder;
    bool fullScreen = false, isAlwaysOnTop = false;
    double currentScaleFactor = 1.0;
    Array<Component*> glRepaintListeners;
    ScopedWindowAssociation association;

    //==============================================================================
    JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (LinuxComponentPeer)
};

bool LinuxComponentPeer::isActiveApplication = false;

//==============================================================================
ComponentPeer* Component::createNewPeer (int styleFlags, void* nativeWindowToAttachTo)
{
    return new LinuxComponentPeer (*this, styleFlags, (::Window) nativeWindowToAttachTo);
}

//==============================================================================
JUCE_API bool JUCE_CALLTYPE Process::isForegroundProcess()    { return LinuxComponentPeer::isActiveApplication; }

JUCE_API void JUCE_CALLTYPE Process::makeForegroundProcess()  {}
JUCE_API void JUCE_CALLTYPE Process::hide()                   {}

//==============================================================================
void Desktop::setKioskComponent (Component* comp, bool enableOrDisable, bool)
{
    if (enableOrDisable)
        comp->setBounds (getDisplays().getDisplayForRect (comp->getScreenBounds())->totalArea);
}

void Displays::findDisplays (float masterScale)
{
    if (XWindowSystem::getInstance()->getDisplay() != nullptr)
    {
        displays = XWindowSystem::getInstance()->findDisplays (masterScale);

        if (! displays.isEmpty())
            updateToLogical();
    }
}

bool Desktop::canUseSemiTransparentWindows() noexcept
{
    return XWindowSystem::getInstance()->canUseSemiTransparentWindows();
}

class Desktop::NativeDarkModeChangeDetectorImpl  : private XWindowSystemUtilities::XSettings::Listener
{
public:
    NativeDarkModeChangeDetectorImpl()
    {
        const auto* windowSystem = XWindowSystem::getInstance();

        if (auto* xSettings = windowSystem->getXSettings())
            xSettings->addListener (this);

        darkModeEnabled = windowSystem->isDarkModeActive();
    }

    ~NativeDarkModeChangeDetectorImpl() override
    {
        if (auto* windowSystem = XWindowSystem::getInstanceWithoutCreating())
            if (auto* xSettings = windowSystem->getXSettings())
                xSettings->removeListener (this);
    }

    bool isDarkModeEnabled() const noexcept  { return darkModeEnabled; }

private:
    void settingChanged (const XWindowSystemUtilities::XSetting& settingThatHasChanged) override
    {
        if (settingThatHasChanged.name == XWindowSystem::getThemeNameSettingName())
        {
            const auto wasDarkModeEnabled = std::exchange (darkModeEnabled, XWindowSystem::getInstance()->isDarkModeActive());

            if (darkModeEnabled != wasDarkModeEnabled)
                Desktop::getInstance().darkModeChanged();
        }
    }

    bool darkModeEnabled = false;

    JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (NativeDarkModeChangeDetectorImpl)
};

std::unique_ptr<Desktop::NativeDarkModeChangeDetectorImpl> Desktop::createNativeDarkModeChangeDetectorImpl()
{
    return std::make_unique<NativeDarkModeChangeDetectorImpl>();
}

bool Desktop::isDarkModeActive() const
{
    return nativeDarkModeChangeDetectorImpl->isDarkModeEnabled();
}

static bool screenSaverAllowed = true;

void Desktop::setScreenSaverEnabled (bool isEnabled)
{
    if (screenSaverAllowed != isEnabled)
    {
        screenSaverAllowed = isEnabled;
        XWindowSystem::getInstance()->setScreenSaverEnabled (screenSaverAllowed);
    }
}

bool Desktop::isScreenSaverEnabled()
{
    return screenSaverAllowed;
}

double Desktop::getDefaultMasterScale()                             { return 1.0; }

Desktop::DisplayOrientation Desktop::getCurrentOrientation() const  { return upright; }
void Desktop::allowedOrientationsChanged()                          {}

//==============================================================================
bool detail::MouseInputSourceList::addSource()
{
    if (sources.isEmpty())
    {
        addSource (0, MouseInputSource::InputSourceType::mouse);
        return true;
    }

    return false;
}

bool detail::MouseInputSourceList::canUseTouch() const
{
    return false;
}

Point<float> MouseInputSource::getCurrentRawMousePosition()
{
    return Desktop::getInstance().getDisplays().physicalToLogical (XWindowSystem::getInstance()->getCurrentMousePosition());
}

void MouseInputSource::setRawMousePosition (Point<float> newPosition)
{
    XWindowSystem::getInstance()->setMousePosition (Desktop::getInstance().getDisplays().logicalToPhysical (newPosition));
}

//==============================================================================
class MouseCursor::PlatformSpecificHandle
{
public:
    explicit PlatformSpecificHandle (const MouseCursor::StandardCursorType type)
        : cursorHandle (makeHandle (type)) {}

    explicit PlatformSpecificHandle (const detail::CustomMouseCursorInfo& info)
        : cursorHandle (makeHandle (info)) {}

    ~PlatformSpecificHandle()
    {
        if (cursorHandle != Cursor{})
            XWindowSystem::getInstance()->deleteMouseCursor (cursorHandle);
    }

    static void showInWindow (PlatformSpecificHandle* handle, ComponentPeer* peer)
    {
        const auto cursor = handle != nullptr ? handle->cursorHandle : Cursor{};

        if (peer != nullptr)
            XWindowSystem::getInstance()->showCursor ((::Window) peer->getNativeHandle(), cursor);
    }

private:
    static Cursor makeHandle (const detail::CustomMouseCursorInfo& info)
    {
        const auto image = info.image.getImage();
        return XWindowSystem::getInstance()->createCustomMouseCursorInfo (image.rescaled ((int) (image.getWidth()  / info.image.getScale()),
                                                                                          (int) (image.getHeight() / info.image.getScale())), info.hotspot);
    }

    static Cursor makeHandle (MouseCursor::StandardCursorType type)
    {
        return XWindowSystem::getInstance()->createStandardMouseCursor (type);
    }

    Cursor cursorHandle;

    //==============================================================================
    JUCE_DECLARE_NON_COPYABLE (PlatformSpecificHandle)
    JUCE_DECLARE_NON_MOVEABLE (PlatformSpecificHandle)
};

//==============================================================================
static LinuxComponentPeer* getPeerForDragEvent (Component* sourceComp)
{
    if (sourceComp == nullptr)
        if (auto* draggingSource = Desktop::getInstance().getDraggingMouseSource (0))
            sourceComp = draggingSource->getComponentUnderMouse();

    if (sourceComp != nullptr)
        if (auto* lp = dynamic_cast<LinuxComponentPeer*> (sourceComp->getPeer()))
            return lp;

    jassertfalse;  // This method must be called in response to a component's mouseDown or mouseDrag event!
    return nullptr;
}

bool DragAndDropContainer::performExternalDragDropOfFiles (const StringArray& files, bool canMoveFiles,
                                                           Component* sourceComp, std::function<void()> callback)
{
    if (files.isEmpty())
        return false;

    if (auto* peer = getPeerForDragEvent (sourceComp))
        return XWindowSystem::getInstance()->externalDragFileInit (peer, files, canMoveFiles, std::move (callback));

    // This method must be called in response to a component's mouseDown or mouseDrag event!
    jassertfalse;
    return false;
}

bool DragAndDropContainer::performExternalDragDropOfText (const String& text, Component* sourceComp,
                                                          std::function<void()> callback)
{
    if (text.isEmpty())
        return false;

    if (auto* peer = getPeerForDragEvent (sourceComp))
        return XWindowSystem::getInstance()->externalDragTextInit (peer, text, std::move (callback));

    // This method must be called in response to a component's mouseDown or mouseDrag event!
    jassertfalse;
    return false;
}

//==============================================================================
void SystemClipboard::copyTextToClipboard (const String& clipText)
{
    XWindowSystem::getInstance()->copyTextToClipboard (clipText);
}

String SystemClipboard::getTextFromClipboard()
{
    return XWindowSystem::getInstance()->getTextFromClipboard();
}

//==============================================================================
bool KeyPress::isKeyCurrentlyDown (int keyCode)
{
    return XWindowSystem::getInstance()->isKeyCurrentlyDown (keyCode);
}

void LookAndFeel::playAlertSound()
{
    std::cout << "\a" << std::flush;
}

//==============================================================================
Image detail::WindowingHelpers::createIconForFile (const File&)
{
    return {};
}

void juce_LinuxAddRepaintListener (ComponentPeer* peer, Component* dummy);
void juce_LinuxAddRepaintListener (ComponentPeer* peer, Component* dummy)
{
    if (auto* linuxPeer = dynamic_cast<LinuxComponentPeer*> (peer))
        linuxPeer->addOpenGLRepaintListener (dummy);
}

void juce_LinuxRemoveRepaintListener (ComponentPeer* peer, Component* dummy);
void juce_LinuxRemoveRepaintListener (ComponentPeer* peer, Component* dummy)
{
    if (auto* linuxPeer = dynamic_cast<LinuxComponentPeer*> (peer))
        linuxPeer->removeOpenGLRepaintListener (dummy);
}

} // namespace juce