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

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

   JUCE is an open source library subject to commercial or open-source
   licensing.

   By using JUCE, you agree to the terms of both the JUCE 7 End-User License
   Agreement and JUCE Privacy Policy.

   End User License Agreement: www.juce.com/juce-7-licence
   Privacy Policy: www.juce.com/juce-privacy-policy

   Or: You may also use this code under the terms of the GPL v3 (see
   www.gnu.org/licenses).

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

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

namespace juce
{
// This byte-code is generated from native/java/com/rmsl/juce/ComponentPeerView.java with min sdk version 16
// See juce_core/native/java/README.txt on how to generate this byte-code.
static const uint8 javaComponentPeerView[] =
{ 31,139,8,8,136,16,72,99,0,3,74,97,118,97,68,101,120,66,121,116,101,67,111,100,101,46,100,101,120,0,165,155,11,124,220,85,149,199,207,253,255,255,51,147,76,38,201,100,242,108,155,180,147,52,208,36,52,201,36,233,35,33,45,180,77,90,154,52,109,98,51,13,52,
  97,23,38,201,36,153,118,242,159,233,204,36,77,4,165,101,89,169,110,113,1,43,139,80,21,177,160,235,11,84,240,193,178,187,40,42,174,136,128,143,69,87,101,169,139,90,21,92,20,20,151,5,187,191,115,239,157,201,164,15,89,119,147,207,119,206,185,231,62,254,
  247,113,238,185,247,159,199,120,120,206,29,104,91,75,23,61,245,207,167,202,99,239,248,192,190,187,191,252,216,84,255,10,199,175,90,191,95,180,235,111,191,112,251,209,245,68,113,34,154,27,90,227,35,253,245,240,58,162,181,66,217,59,65,183,131,104,27,100,
  192,73,180,156,203,230,18,93,15,57,229,38,114,112,186,128,40,85,71,84,81,72,244,53,20,248,58,120,28,124,27,124,15,252,24,156,4,191,1,111,128,194,21,68,171,64,19,104,1,107,193,70,176,9,116,131,237,96,7,232,7,54,184,17,188,11,188,27,220,10,110,3,119,130,
  187,192,61,224,31,193,203,160,192,79,84,15,186,193,56,184,1,220,7,254,5,252,4,188,10,242,171,137,58,192,229,32,14,142,130,207,131,111,130,159,129,229,53,68,151,130,4,184,23,60,11,10,86,162,143,32,4,110,6,79,131,37,181,68,65,112,16,188,31,124,9,156,4,
  214,5,68,43,193,70,48,0,82,224,14,112,31,248,54,248,25,112,92,136,250,96,59,24,7,215,128,163,224,3,224,4,248,12,120,16,60,10,158,6,223,3,63,2,207,129,83,224,215,224,119,224,53,64,171,208,30,200,5,5,160,24,84,128,229,160,6,52,128,70,208,10,218,193,70,
  208,13,122,193,46,48,8,70,192,40,152,0,251,192,219,193,123,192,7,193,199,193,231,193,163,224,73,240,67,240,115,240,50,56,13,60,88,247,101,160,5,116,128,109,96,0,236,7,179,96,30,28,5,199,192,113,112,2,124,18,60,0,190,4,190,5,158,5,191,7,142,122,140,1,
  148,130,86,208,14,54,131,110,176,3,76,131,57,112,29,184,9,220,1,62,6,30,3,63,5,47,1,209,128,241,131,85,160,5,108,4,59,192,16,216,15,230,192,77,224,78,112,47,248,60,248,42,248,22,120,6,60,15,126,15,156,23,97,92,160,1,92,12,174,0,127,9,198,193,36,56,12,
  110,5,39,192,231,192,87,193,119,193,73,240,42,200,89,141,53,6,117,96,45,232,5,65,48,13,14,130,183,129,67,224,40,184,5,220,13,62,13,190,12,158,0,63,4,63,5,47,130,255,2,102,35,214,20,212,131,86,176,3,12,131,16,136,131,89,240,118,240,14,240,78,240,183,224,
  118,112,55,184,31,124,1,252,19,248,10,120,6,188,0,254,8,138,154,176,15,193,102,16,4,211,96,6,220,0,142,129,187,193,39,193,195,224,171,224,73,240,44,120,1,188,2,222,0,174,102,172,27,88,10,234,65,0,244,131,81,16,6,54,184,21,220,9,238,1,143,130,111,128,
  39,193,191,131,23,129,51,64,84,6,106,193,37,96,15,72,128,235,192,187,193,29,224,99,224,11,224,49,240,12,248,25,160,22,212,5,30,80,2,42,65,13,88,5,26,193,122,112,49,216,12,122,193,0,8,129,40,120,59,184,9,188,15,28,7,31,4,31,6,31,1,31,7,247,129,207,130,
  60,60,6,33,142,138,64,37,168,34,21,7,17,114,8,33,133,16,54,8,97,130,16,22,8,33,128,176,197,73,111,77,130,91,19,220,146,224,82,4,183,32,44,37,97,218,9,211,70,205,28,83,213,16,168,21,180,129,53,96,45,64,8,38,132,102,106,7,29,224,98,29,139,55,128,141,224,
  18,112,41,216,4,54,131,45,160,139,99,53,216,74,42,94,95,6,182,131,30,208,11,118,128,62,176,11,188,5,140,3,27,196,72,197,250,3,164,198,154,254,242,104,233,173,82,227,23,233,180,214,217,206,115,98,104,187,79,235,21,176,151,66,58,181,189,2,228,240,92,105,
  123,129,182,151,234,182,210,122,73,150,94,174,245,50,176,68,63,107,137,214,235,116,59,75,179,218,231,53,9,84,41,157,215,162,93,151,169,207,106,103,181,110,167,92,235,155,170,84,27,172,111,135,190,76,175,203,128,110,135,245,43,116,59,1,221,14,151,225,
  181,186,90,247,135,215,107,170,74,205,231,90,93,38,168,117,126,214,30,173,199,161,15,105,157,159,123,185,214,175,133,126,133,214,143,66,223,171,245,219,161,15,107,253,4,244,17,173,127,2,250,149,90,255,2,244,191,208,250,35,208,175,210,250,215,179,236,
  79,101,233,223,135,30,210,250,115,89,246,23,178,244,87,178,244,215,179,218,180,150,47,216,61,89,122,9,244,171,181,94,153,101,127,189,114,65,231,181,248,75,173,111,207,106,179,54,171,60,207,243,168,214,87,195,62,166,245,53,89,101,186,179,244,190,229,202,
  127,215,233,57,15,107,61,8,251,132,214,175,204,210,167,160,79,106,61,5,125,74,235,215,66,143,104,253,8,244,253,90,63,6,125,159,214,143,103,217,217,247,162,90,63,1,251,180,214,31,200,42,255,200,114,222,59,130,254,154,148,172,22,28,55,234,232,58,82,242,
  235,82,10,122,92,203,39,180,252,150,150,79,106,249,148,46,255,67,226,88,83,67,203,133,146,171,4,199,157,117,244,111,196,178,154,86,8,142,65,42,191,90,231,87,35,167,65,240,94,168,160,183,17,75,131,254,69,202,106,250,129,148,43,232,121,41,215,209,107,82,
  230,209,27,196,49,44,32,247,45,75,151,148,235,200,173,211,249,82,10,218,173,211,131,188,86,216,97,253,196,247,192,11,201,33,120,207,59,233,46,98,89,70,247,67,230,98,135,89,82,174,39,55,242,221,136,132,156,206,211,246,60,60,37,79,240,60,169,180,23,37,
  63,34,101,35,25,130,227,139,65,31,32,150,229,244,33,82,233,191,215,242,211,196,49,71,229,179,252,160,148,22,157,208,233,143,75,105,210,39,72,197,166,79,106,249,41,41,5,125,78,203,207,179,31,163,252,61,82,94,68,15,18,239,249,85,178,63,165,136,182,175,
  72,185,129,126,39,101,37,253,129,56,134,4,232,176,150,57,130,227,69,7,253,43,113,76,200,167,159,74,137,241,8,142,47,106,92,203,16,237,89,46,71,196,126,76,202,213,84,32,88,110,161,10,185,174,109,50,127,5,102,226,22,41,151,208,109,58,253,119,82,118,210,
  105,185,222,45,178,156,31,237,254,150,120,157,85,189,106,216,19,90,38,165,244,82,74,202,165,180,68,40,185,84,250,67,157,44,95,131,21,155,145,178,149,102,165,236,166,131,82,150,208,156,150,243,82,118,209,91,165,92,74,55,104,249,78,41,47,166,119,75,89,
  69,239,145,114,37,189,79,202,98,58,46,101,1,189,95,74,39,125,88,251,223,61,58,255,94,41,219,233,163,82,186,233,62,237,127,159,209,229,62,43,101,14,61,32,165,90,15,120,55,125,81,63,239,33,45,255,65,203,135,181,95,255,163,148,126,250,39,237,223,255,172,
  243,31,209,245,191,164,229,151,181,124,84,202,26,250,138,148,151,208,87,165,236,160,239,105,249,140,148,23,208,41,41,107,233,23,90,254,82,203,95,233,252,23,116,250,69,45,127,45,101,33,253,167,148,245,244,146,148,205,244,27,41,55,211,203,82,42,191,170,
  209,126,197,233,223,235,253,248,170,148,202,207,184,252,127,73,121,41,9,185,126,107,201,163,101,190,148,77,228,149,114,25,249,164,92,67,197,58,93,162,203,149,106,89,166,243,203,133,154,151,58,193,251,88,249,103,61,60,248,99,82,110,165,239,202,125,109,
  208,183,165,244,209,133,130,207,66,85,174,9,59,239,110,226,243,208,164,119,73,105,208,179,196,103,98,41,125,135,248,14,179,84,251,177,58,219,211,103,52,94,25,233,1,156,9,87,235,67,210,175,237,124,198,242,89,193,249,223,132,188,78,231,87,235,250,77,89,
  245,127,132,252,91,117,62,159,241,69,164,206,102,171,74,229,191,128,252,135,116,254,74,157,159,174,159,163,229,189,8,208,187,215,170,123,202,27,56,188,173,181,234,46,83,160,109,43,33,27,128,169,243,215,64,191,68,151,185,76,218,77,169,127,174,69,181,57,
  34,220,20,247,242,211,70,140,60,248,124,14,90,225,119,226,47,181,168,187,159,79,4,71,221,116,192,187,14,246,60,163,12,83,211,98,24,86,135,97,145,203,91,68,193,209,60,58,224,175,198,206,245,16,151,11,142,169,178,38,229,89,7,6,218,105,203,140,219,232,48,
  94,60,109,123,121,188,46,111,221,207,45,253,252,103,90,212,253,170,6,51,30,247,30,150,163,229,103,115,191,79,182,168,51,242,124,207,54,169,72,248,124,109,171,150,156,253,204,64,7,109,113,120,176,55,95,194,51,121,223,187,133,237,175,71,44,247,136,186,
  159,157,93,250,98,89,186,238,23,28,199,45,217,159,87,91,212,221,56,24,87,229,56,167,204,144,119,92,163,3,101,124,216,23,193,3,238,236,124,67,220,32,222,235,186,247,160,179,19,35,115,83,221,75,38,250,203,99,180,90,213,186,142,248,242,49,198,107,97,243,
  209,149,94,143,188,63,230,32,197,99,205,111,85,247,164,98,103,9,213,24,30,148,227,89,8,38,243,41,216,86,64,182,247,50,148,242,136,14,177,97,193,230,223,1,239,88,40,209,141,18,110,115,55,46,238,187,47,16,244,233,224,45,100,90,107,175,94,74,123,146,152,
  7,179,140,124,230,149,208,210,229,131,169,124,244,187,21,35,241,88,220,127,75,206,195,122,234,114,112,249,14,211,69,235,175,118,144,175,152,235,240,179,150,192,147,109,111,5,143,236,140,103,212,125,139,215,146,125,174,29,99,40,148,227,44,208,227,228,
  40,22,247,55,98,7,140,120,65,113,161,190,127,11,57,47,219,81,158,247,88,220,203,111,12,5,25,251,64,198,190,70,218,13,125,99,191,162,85,249,115,208,91,40,247,4,123,16,63,247,234,86,117,199,15,250,11,209,71,126,83,192,56,171,189,232,245,114,60,185,32,83,
  110,242,188,229,86,200,114,5,240,120,30,137,141,114,28,51,124,46,95,89,220,191,20,231,116,141,149,135,222,56,209,171,145,99,101,72,85,83,28,47,135,199,114,71,142,21,35,181,2,169,58,153,42,65,187,93,88,107,143,181,212,113,45,218,197,10,66,95,97,85,160,
  94,17,85,90,14,216,230,113,174,187,173,118,107,156,86,184,57,141,119,66,26,62,238,131,150,194,73,117,229,157,165,208,166,113,151,179,253,182,252,140,225,60,170,65,155,113,47,143,189,216,42,161,149,155,215,35,150,241,109,219,246,91,232,121,144,251,228,
  192,254,245,59,136,91,116,225,169,62,211,246,190,77,247,164,80,248,46,92,57,209,129,241,140,230,84,209,206,28,167,203,87,94,153,147,39,53,59,48,71,65,167,199,108,55,75,200,103,248,106,87,118,95,76,62,199,1,239,53,152,7,143,115,167,211,114,248,74,125,
  82,218,129,67,244,30,235,128,244,100,143,101,251,221,116,140,61,195,203,190,206,99,84,99,57,70,117,119,228,91,117,47,130,95,129,95,128,239,128,167,225,40,153,247,34,245,117,232,82,250,179,210,103,126,169,124,190,131,151,97,111,242,30,247,242,58,155,23,
  221,37,26,62,32,90,142,11,163,249,132,104,188,91,144,142,52,68,63,214,254,51,232,247,201,152,108,201,40,72,244,124,218,223,2,131,84,109,22,96,255,59,100,236,123,177,85,253,92,48,190,39,74,213,93,110,233,219,233,58,175,165,243,2,91,81,199,35,253,49,157,
  103,182,165,243,54,103,242,92,242,70,137,153,211,121,179,206,43,100,148,224,54,29,58,6,44,107,83,251,103,112,147,47,43,214,152,152,101,182,196,3,253,184,137,213,189,182,48,158,149,186,45,126,39,28,198,152,10,116,31,248,171,190,77,157,3,62,236,149,28,
  216,184,92,91,155,42,59,56,112,86,251,176,196,47,31,32,71,72,175,47,241,250,14,80,221,203,233,189,119,73,91,122,239,149,232,119,101,101,239,214,246,61,222,82,217,119,67,239,225,222,54,146,247,109,219,219,35,199,41,99,38,250,226,163,186,63,154,186,143,
  3,109,250,204,146,245,212,219,247,112,150,205,169,207,129,209,55,153,151,157,122,94,210,229,163,111,82,126,87,102,30,85,63,102,207,209,143,67,231,176,29,201,178,89,250,89,55,183,169,51,222,39,248,134,48,18,48,72,73,147,246,182,32,126,190,180,55,224,162,
  189,1,167,182,230,98,15,192,11,188,123,3,22,242,115,228,237,38,30,168,37,191,40,210,227,229,117,250,96,155,58,243,207,221,255,224,150,50,138,239,190,156,172,183,212,253,129,253,202,148,190,251,247,231,173,211,182,245,244,105,57,238,77,155,200,10,113,
  29,55,158,195,103,254,231,218,212,253,35,120,168,8,235,228,39,206,105,71,79,7,15,35,26,121,249,13,198,141,40,82,194,210,178,177,190,144,14,27,167,125,46,229,57,93,135,102,115,250,180,127,241,154,186,241,44,246,239,71,219,212,187,163,207,59,152,64,79,
  248,172,22,56,171,133,58,49,87,231,240,207,55,56,199,246,22,232,246,242,89,58,93,7,196,13,179,206,183,96,126,235,94,140,5,150,209,141,185,56,65,79,217,222,13,24,97,29,191,224,25,106,156,252,243,140,37,90,22,107,60,250,204,62,217,166,126,246,228,163,193,
  235,241,108,167,124,182,179,67,152,120,114,71,110,46,158,153,135,72,225,22,190,154,214,106,23,197,54,85,210,237,15,225,41,191,181,113,22,231,225,116,109,23,124,67,81,186,237,127,59,251,173,131,91,226,62,230,113,31,15,139,99,170,143,62,111,221,51,106,
  238,121,189,78,183,169,251,219,226,185,87,35,102,27,143,213,73,110,35,190,123,55,86,13,117,127,71,58,26,224,220,95,179,224,83,185,58,238,84,173,81,107,25,187,162,138,130,179,217,173,182,227,153,202,135,103,225,195,92,167,80,175,101,19,234,84,162,161,
  193,167,81,218,228,145,11,83,206,186,40,20,182,151,207,93,119,46,175,93,1,229,185,190,119,203,105,186,72,252,94,122,109,221,111,6,191,237,131,180,253,197,184,239,240,58,151,112,89,7,175,119,1,143,249,233,217,156,32,143,184,168,238,71,111,94,114,72,149,
  124,236,205,75,238,65,73,219,203,49,203,157,231,43,90,191,172,129,124,213,43,43,219,17,119,182,209,19,228,91,186,246,161,106,226,86,184,141,79,113,27,254,50,150,194,231,232,118,120,28,215,239,249,90,169,237,47,87,150,178,110,167,199,121,253,196,215,202,
  210,237,126,223,237,22,117,207,161,31,127,133,55,7,188,108,62,120,203,73,183,200,233,112,87,208,255,118,4,245,52,113,58,187,63,255,151,158,112,75,117,63,252,243,123,16,212,61,184,224,255,221,131,160,236,1,150,89,184,164,175,177,111,113,28,106,214,146,
  227,23,191,155,38,165,239,25,242,238,115,207,26,245,174,129,62,226,254,224,34,143,177,212,196,45,187,100,101,55,238,15,142,81,39,238,15,242,46,48,71,173,22,223,71,93,232,119,62,246,63,120,221,231,91,89,131,219,131,201,183,135,28,220,9,118,90,134,201,
  183,134,3,70,221,175,243,141,186,23,192,47,193,41,246,247,34,244,109,153,220,187,136,122,70,115,89,99,133,121,81,93,195,106,254,85,71,38,222,62,157,181,55,76,109,253,193,26,117,151,110,55,92,196,51,146,64,137,2,242,109,170,251,111,30,159,138,201,255,
  177,70,197,1,190,139,241,173,121,169,241,180,188,139,85,227,105,43,48,239,237,136,30,182,247,58,236,80,183,216,40,138,49,219,118,96,21,5,48,226,94,89,222,14,92,72,94,43,216,82,140,27,114,64,182,159,206,241,25,118,224,2,242,26,42,175,133,231,247,183,11,
  247,217,63,172,73,223,91,175,149,189,230,223,35,242,87,250,231,205,60,182,90,216,86,107,123,250,171,253,140,244,246,51,210,92,191,76,175,87,49,158,80,168,109,105,106,180,204,33,117,230,151,232,254,84,106,123,181,150,134,166,70,207,101,19,93,44,237,1,
  109,15,224,148,86,82,200,113,8,253,237,160,133,243,222,208,253,72,159,243,86,70,23,186,125,67,231,187,228,207,224,149,109,157,44,107,102,234,231,103,234,178,116,234,60,39,173,147,249,108,115,105,153,171,165,71,215,45,144,189,163,204,28,20,103,198,188,
  78,143,173,70,218,249,12,114,72,153,30,133,42,191,94,203,118,93,79,232,187,23,203,124,221,15,214,139,50,249,69,89,99,204,207,140,125,73,166,63,170,109,159,126,94,77,166,36,233,159,79,169,210,130,212,190,18,117,228,104,105,10,52,97,20,27,200,185,33,98,
  71,82,151,144,113,73,39,21,108,30,24,232,235,233,218,28,236,233,223,117,85,79,55,185,183,236,233,233,235,190,42,184,119,96,43,121,183,204,68,162,227,93,49,123,34,50,217,180,47,52,27,162,178,174,216,116,60,102,135,237,212,64,56,156,24,138,132,15,42,187,
  163,123,235,150,61,151,145,216,70,198,182,30,114,110,235,219,60,212,191,155,68,15,25,61,245,0,119,177,94,50,122,251,168,170,119,102,44,188,121,108,44,156,76,70,70,35,209,72,106,126,87,108,60,60,144,136,205,70,198,195,9,42,223,17,158,31,141,133,18,227,
  221,145,228,116,36,153,236,139,36,83,97,27,25,162,143,140,62,180,214,135,102,250,250,200,236,67,2,31,189,252,209,71,101,125,33,123,60,17,139,140,55,135,226,241,230,205,99,169,200,44,90,238,164,53,139,237,241,120,52,50,22,74,69,98,118,109,186,76,95,100,
  34,60,54,63,22,13,119,133,162,209,209,208,216,254,100,39,45,57,95,173,236,172,177,152,141,158,165,154,187,88,206,165,178,179,38,19,161,248,84,100,44,217,220,21,178,103,67,104,112,249,57,178,98,209,88,98,91,36,154,10,39,206,159,191,51,148,74,68,230,58,
  169,254,79,230,47,106,170,226,236,162,3,161,136,141,254,149,159,157,179,59,60,134,140,226,76,70,44,217,188,101,198,30,143,134,59,169,36,219,216,179,37,98,143,115,235,13,25,235,44,86,190,185,107,42,150,8,199,100,115,225,68,237,182,68,104,58,51,141,157,
  84,249,39,202,102,247,70,230,98,217,183,206,134,185,155,75,23,103,236,140,241,196,235,188,250,197,121,236,125,181,253,246,182,216,216,76,178,107,42,100,79,134,211,238,146,61,168,76,209,236,201,201,24,47,75,196,102,226,157,180,238,236,156,96,34,28,238,
  31,77,134,19,179,24,91,191,125,89,52,54,26,138,246,133,230,99,51,169,133,199,172,248,211,245,58,169,101,113,129,80,182,231,55,47,218,7,59,67,118,104,146,171,180,254,175,171,240,214,233,177,39,98,103,245,255,77,234,164,183,91,39,53,45,174,23,177,227,51,
  169,233,112,106,42,54,222,188,37,148,68,227,72,195,195,109,56,138,244,255,11,206,95,126,235,120,36,21,75,168,238,52,156,191,216,89,77,54,190,73,217,157,82,207,204,206,165,125,99,177,233,230,196,116,50,218,188,15,161,164,249,172,120,84,251,39,35,76,39,
  109,123,211,6,206,19,131,106,23,175,108,199,255,181,157,78,170,126,179,170,157,84,43,139,192,217,18,144,241,144,61,223,60,59,26,13,217,251,155,179,34,114,39,213,244,141,135,162,179,145,253,205,33,219,142,165,100,140,106,222,106,143,69,99,201,136,61,217,
  21,13,37,101,240,57,187,76,15,166,63,161,243,171,207,145,191,51,60,61,170,11,132,81,164,234,28,69,6,35,147,118,40,53,147,8,243,182,226,35,160,25,221,155,196,54,15,37,6,195,7,102,194,246,24,114,138,178,115,212,227,106,178,76,61,209,104,120,50,20,85,139,
  181,117,110,44,28,87,46,81,123,142,50,137,201,153,105,204,80,86,169,226,236,82,8,194,147,106,106,23,140,187,98,131,51,99,83,202,127,178,234,249,178,138,244,143,238,147,49,176,42,203,54,24,30,155,73,192,109,206,83,101,16,49,215,158,100,191,93,176,37,194,
  19,81,180,131,110,204,198,212,81,17,12,37,38,195,217,189,93,122,142,226,170,107,157,84,170,242,102,82,145,104,243,230,68,34,52,207,174,210,73,133,89,102,182,144,247,12,67,39,89,242,152,246,100,123,38,137,33,242,12,109,221,61,200,231,121,87,127,247,214,
  133,212,174,205,59,183,146,49,212,67,142,161,30,124,65,237,37,231,80,111,207,182,109,189,100,65,114,70,47,103,152,67,189,210,194,39,237,80,239,48,10,178,194,167,237,144,52,245,13,35,183,111,24,103,241,208,48,90,24,150,173,137,97,50,161,145,133,143,62,
  86,251,200,49,220,203,186,5,129,243,123,152,173,56,183,157,195,125,210,236,96,9,251,8,46,13,35,61,228,27,57,219,91,138,71,206,177,88,110,21,222,106,3,129,64,70,111,201,210,91,179,244,182,44,125,77,150,190,54,75,95,151,165,175,207,210,219,161,231,41,125,
  91,52,52,153,164,252,69,113,149,74,66,231,136,223,228,12,201,192,198,53,89,246,133,70,195,81,202,9,233,251,6,45,9,141,143,159,251,52,161,220,144,118,242,36,137,81,42,226,99,116,203,76,42,21,179,7,18,120,76,120,156,156,163,49,36,167,33,229,41,77,206,49,
  121,193,32,215,152,60,253,198,201,129,139,76,40,65,121,99,28,241,98,56,246,55,167,56,145,185,42,80,129,76,4,19,33,59,57,17,75,76,83,25,162,75,83,86,148,105,82,81,134,242,249,122,131,123,67,82,182,130,7,168,91,14,30,16,155,65,122,217,88,34,28,74,157,29,
  101,57,250,147,53,30,153,152,32,215,120,76,94,8,72,132,201,17,230,243,155,252,19,184,70,156,179,78,114,203,124,144,155,207,229,18,242,60,39,199,132,20,158,137,133,211,125,156,242,100,138,35,100,207,56,21,76,112,251,193,200,116,120,87,200,142,37,105,25,
  54,220,162,214,183,101,21,174,60,51,115,209,181,51,87,230,202,101,43,204,168,59,67,201,253,120,102,41,27,22,238,128,250,190,71,249,48,115,176,195,194,134,19,73,202,225,36,251,44,185,89,211,133,60,28,3,120,236,220,75,249,148,237,225,200,228,84,138,138,
  161,202,211,45,187,143,121,210,152,76,133,16,59,101,137,62,29,76,250,237,65,76,120,216,150,237,33,104,132,6,17,132,85,123,42,132,200,94,203,165,66,212,150,43,228,89,48,160,101,23,82,187,67,7,175,72,43,123,229,179,118,199,98,41,126,52,121,145,24,156,135,
  23,78,15,34,132,68,240,244,2,88,246,216,17,246,35,30,164,236,205,153,151,27,57,5,67,145,204,118,224,58,151,99,253,98,7,131,177,253,232,108,101,38,45,11,69,195,56,7,227,209,208,188,114,11,11,185,87,200,207,189,36,166,168,2,43,12,151,94,180,68,219,99,252,
  148,66,157,19,143,15,132,102,120,23,120,51,134,221,225,36,246,75,198,178,37,179,97,40,95,89,186,181,15,234,36,14,228,238,216,65,108,205,76,114,79,156,74,50,9,121,88,111,143,140,143,163,243,250,169,59,99,120,164,172,179,200,144,8,77,166,219,148,6,52,163,
  219,148,151,109,42,214,137,112,130,119,153,246,172,156,169,80,82,249,118,249,20,188,110,48,54,161,93,32,17,155,86,243,132,34,168,45,119,130,53,21,67,192,23,17,114,195,115,250,229,25,146,36,51,50,61,77,133,252,234,22,9,69,187,66,241,228,78,172,15,229,
  107,195,96,56,186,213,30,207,228,35,9,55,73,96,83,201,43,85,112,62,30,38,143,84,175,82,215,43,202,193,195,134,66,209,25,4,146,8,14,174,253,97,60,44,153,113,192,156,72,178,63,30,194,73,78,75,34,201,96,12,39,233,214,185,56,130,135,244,200,173,118,8,11,
  58,142,182,147,122,113,201,181,63,60,223,197,253,41,223,127,158,119,184,252,116,198,224,20,207,168,35,42,67,99,62,92,34,156,224,238,237,194,29,136,172,104,120,34,69,206,104,216,158,76,77,145,83,119,85,216,100,217,188,146,46,59,124,112,23,43,57,118,58,
  222,120,236,236,173,236,140,141,114,224,34,43,22,29,159,146,159,7,169,40,102,167,223,247,186,100,224,26,167,226,5,83,119,56,153,74,196,230,217,143,22,140,218,215,178,106,166,157,109,217,130,105,48,52,27,78,207,151,218,146,89,229,229,228,47,110,98,48,
  21,139,199,97,42,71,24,145,253,56,227,50,140,206,219,240,173,131,148,31,203,126,171,161,130,216,162,3,131,60,49,91,238,13,25,90,40,55,102,167,29,59,95,170,59,103,162,169,72,156,151,68,38,225,156,57,124,14,201,170,40,49,24,121,107,56,29,80,209,146,90,
  90,217,146,51,166,22,220,165,228,85,168,55,131,35,36,133,248,230,136,75,199,118,199,67,9,148,148,81,35,63,190,200,189,29,113,121,84,84,197,99,241,153,232,121,15,135,162,56,252,122,209,155,34,137,4,185,18,234,37,156,106,18,225,73,118,151,196,249,223,207,
  185,48,78,185,36,92,64,43,87,81,101,34,60,141,9,81,147,212,111,159,113,174,58,18,50,230,154,201,112,138,10,146,28,157,51,47,204,228,65,90,78,53,251,51,149,103,167,122,212,212,200,61,198,213,178,222,70,100,181,190,180,223,82,5,82,231,124,15,165,210,100,
  58,178,238,137,100,133,202,101,231,52,243,107,64,8,7,118,82,197,90,233,230,249,201,69,49,214,157,78,70,85,159,46,143,68,163,187,98,41,233,52,158,36,182,85,58,140,161,34,82,153,24,131,194,236,142,170,95,184,190,34,27,190,184,144,172,72,170,222,244,44,
  60,75,143,212,146,7,153,149,154,138,36,201,201,159,181,1,45,91,96,229,99,205,68,75,80,121,34,114,102,82,19,237,242,192,16,179,228,152,149,177,197,37,69,255,4,89,252,126,71,133,252,153,237,130,185,108,8,198,246,96,65,189,179,103,29,49,179,145,68,106,38,
  20,213,39,164,123,118,97,42,196,65,18,115,100,204,5,64,11,104,5,109,96,13,137,121,122,208,50,232,99,134,171,96,184,145,30,182,196,39,12,87,149,145,247,180,49,87,181,207,164,231,197,210,159,236,160,39,44,227,253,6,236,5,244,29,75,188,79,184,170,30,55,
  222,90,245,91,147,238,20,141,141,183,58,136,126,98,153,159,48,174,251,43,225,42,120,116,5,189,108,8,66,91,27,232,53,131,92,171,71,76,227,6,35,255,157,166,56,45,74,155,230,94,53,233,61,194,216,183,65,20,21,69,54,24,201,42,7,109,16,121,78,52,96,168,30,
  24,235,246,26,59,14,54,210,191,27,226,126,126,220,153,242,20,154,44,120,128,94,84,98,163,121,179,120,93,124,67,184,86,27,207,81,167,241,71,113,208,120,74,28,156,51,190,115,205,115,71,132,225,112,111,110,220,208,180,97,195,37,35,38,29,21,238,107,77,113,
  147,104,223,112,111,181,105,62,39,218,68,121,105,96,185,105,252,88,24,162,168,194,97,204,25,253,232,139,67,56,76,167,219,184,232,132,195,237,36,167,112,26,78,179,161,193,152,93,237,48,26,140,228,106,106,87,125,104,55,238,55,62,45,21,139,149,207,24,159,
  93,108,205,40,142,116,246,3,156,188,147,251,252,174,74,154,135,216,65,175,152,198,125,198,131,108,191,73,136,227,152,184,163,75,71,232,55,22,242,232,118,158,62,250,165,201,159,119,88,198,97,113,35,178,233,152,37,14,179,252,163,41,37,26,186,71,89,254,
  166,146,222,157,41,117,151,46,117,68,203,15,153,226,13,44,215,142,29,141,195,59,134,155,232,122,33,142,168,202,143,152,198,61,198,99,92,125,89,35,189,42,196,109,80,143,136,178,66,63,157,48,140,31,112,178,234,70,163,180,202,152,174,50,10,59,155,118,132,
  141,153,222,43,141,249,94,250,134,97,254,64,220,34,243,141,162,119,24,137,170,219,70,246,29,49,29,168,212,28,190,148,30,209,117,11,110,244,87,222,70,95,52,29,239,20,207,138,187,141,119,25,239,224,206,220,111,90,159,50,190,40,78,137,159,35,181,241,198,
  97,250,168,122,238,141,198,215,169,202,120,232,186,170,29,102,238,117,70,159,233,250,144,97,26,143,210,94,99,211,106,81,92,24,80,120,251,204,188,147,194,216,184,193,244,28,54,58,54,10,97,186,31,23,70,163,168,204,191,212,225,118,120,90,28,121,251,156,
  238,38,81,92,102,92,211,185,193,233,217,40,170,74,217,190,216,104,108,19,85,5,244,164,41,62,137,153,247,155,226,184,209,38,124,101,134,103,53,198,185,194,164,247,138,192,114,7,73,165,105,165,131,78,6,26,232,113,83,252,7,247,253,63,77,113,3,100,164,146,
  142,24,226,195,168,253,21,147,158,16,43,154,246,237,152,187,122,201,141,228,228,197,50,106,197,61,70,69,141,113,129,113,141,229,59,41,202,139,141,85,48,84,186,202,69,121,79,121,97,249,206,114,179,188,181,220,161,74,85,203,82,6,74,13,100,202,151,24,23,
  114,121,81,225,87,138,81,177,162,162,218,89,126,211,122,167,88,177,222,37,44,81,110,144,33,44,247,205,126,225,171,59,124,200,122,106,121,189,120,105,185,16,79,173,16,226,5,112,202,143,108,225,49,196,205,254,198,67,135,172,7,170,155,196,247,171,201,116,
  82,1,215,16,190,102,212,57,190,82,28,241,127,147,63,158,231,143,215,87,10,227,88,173,48,30,174,37,231,146,202,34,31,182,131,79,125,175,69,225,231,107,81,228,225,58,124,124,151,63,94,224,143,35,245,248,56,193,31,143,212,59,174,55,72,0,11,184,180,254,231,
  80,2,220,96,131,248,81,189,16,71,27,132,248,40,120,184,193,20,127,104,40,23,55,95,132,52,248,38,120,14,188,2,78,172,22,226,187,224,20,120,29,220,220,40,196,243,224,246,38,148,3,119,53,99,55,5,132,56,214,34,172,167,192,243,45,200,107,117,136,231,214,97,
  138,214,27,226,80,187,33,78,180,59,73,80,249,18,145,249,62,200,19,211,81,148,245,123,156,180,76,255,95,26,255,14,33,253,191,105,252,187,133,244,255,167,169,191,177,85,255,163,198,191,87,72,255,159,154,147,22,254,87,205,244,42,157,127,207,36,252,234,255,
  47,6,160,59,253,170,62,255,157,162,240,42,59,255,109,162,225,87,207,229,255,109,51,117,121,254,251,63,203,175,126,119,196,127,39,232,240,171,254,241,223,22,242,31,55,114,251,242,111,29,189,202,206,255,83,247,63,73,81,207,80,140,55,0,0,0,0 };

//==============================================================================
#if JUCE_PUSH_NOTIFICATIONS && JUCE_MODULE_AVAILABLE_juce_gui_extra
 bool juce_handleNotificationIntent (void*);
 void juce_firebaseDeviceNotificationsTokenRefreshed (void*);
 void juce_firebaseRemoteNotificationReceived (void*);
 void juce_firebaseRemoteMessagesDeleted();
 void juce_firebaseRemoteMessageSent(void*);
 void juce_firebaseRemoteMessageSendError (void*, void*);
#endif

#if JUCE_IN_APP_PURCHASES && JUCE_MODULE_AVAILABLE_juce_product_unlocking
 void juce_handleOnResume();
#else
 static void juce_handleOnResume() {}
#endif

//==============================================================================
#define JNI_CLASS_MEMBERS(METHOD, STATICMETHOD, FIELD, STATICFIELD, CALLBACK) \
 METHOD (create, "<init>", "(II)V")

DECLARE_JNI_CLASS (AndroidLayoutParams, "android/view/ViewGroup$LayoutParams")
#undef JNI_CLASS_MEMBERS

#define JNI_CLASS_MEMBERS(METHOD, STATICMETHOD, FIELD, STATICFIELD, CALLBACK) \
 METHOD (addView,          "addView",             "(Landroid/view/View;Landroid/view/ViewGroup$LayoutParams;)V") \
 METHOD (removeView,       "removeView",          "(Landroid/view/View;)V") \
 METHOD (updateViewLayout, "updateViewLayout",    "(Landroid/view/View;Landroid/view/ViewGroup$LayoutParams;)V")

DECLARE_JNI_CLASS (AndroidViewManager, "android/view/ViewManager")
#undef JNI_CLASS_MEMBERS

#define JNI_CLASS_MEMBERS(METHOD, STATICMETHOD, FIELD, STATICFIELD, CALLBACK) \
 METHOD (create,           "<init>",             "(IIIIIII)V") \
 FIELD  (gravity,          "gravity",            "I") \
 FIELD  (windowAnimations, "windowAnimations",   "I")

DECLARE_JNI_CLASS (AndroidWindowManagerLayoutParams, "android/view/WindowManager$LayoutParams")
#undef JNI_CLASS_MEMBERS

#define JNI_CLASS_MEMBERS(METHOD, STATICMETHOD, FIELD, STATICFIELD, CALLBACK) \
 FIELD  (layoutInDisplayCutoutMode, "layoutInDisplayCutoutMode", "I")

DECLARE_JNI_CLASS_WITH_MIN_SDK (AndroidWindowManagerLayoutParams28, "android/view/WindowManager$LayoutParams", 28)
#undef JNI_CLASS_MEMBERS

#define JNI_CLASS_MEMBERS(METHOD, STATICMETHOD, FIELD, STATICFIELD, CALLBACK) \
 METHOD (getDisplayCutout, "getDisplayCutout", "()Landroid/view/DisplayCutout;") \
 METHOD (consumeDisplayCutout, "consumeDisplayCutout", "()Landroid/view/WindowInsets;")

 DECLARE_JNI_CLASS_WITH_MIN_SDK (AndroidWindowInsets28, "android/view/WindowInsets", 28)
#undef JNI_CLASS_MEMBERS

#define JNI_CLASS_MEMBERS(METHOD, STATICMETHOD, FIELD, STATICFIELD, CALLBACK) \
 METHOD (getInsets, "getInsets", "(I)Landroid/graphics/Insets;") \
 STATICFIELD (CONSUMED, "CONSUMED", "Landroid/view/WindowInsets;")

 DECLARE_JNI_CLASS_WITH_MIN_SDK (AndroidWindowInsets30, "android/view/WindowInsets", 30)
#undef JNI_CLASS_MEMBERS

#define JNI_CLASS_MEMBERS(METHOD, STATICMETHOD, FIELD, STATICFIELD, CALLBACK) \
 METHOD (getSafeInsetBottom, "getSafeInsetBottom", "()I") \
 METHOD (getSafeInsetLeft,   "getSafeInsetLeft",   "()I") \
 METHOD (getSafeInsetRight,  "getSafeInsetRight",  "()I") \
 METHOD (getSafeInsetTop,    "getSafeInsetTop",    "()I")

 DECLARE_JNI_CLASS_WITH_MIN_SDK (AndroidDisplayCutout, "android/view/DisplayCutout", 28)
#undef JNI_CLASS_MEMBERS

#define JNI_CLASS_MEMBERS(METHOD, STATICMETHOD, FIELD, STATICFIELD, CALLBACK) \
 FIELD (bottom, "bottom", "I") \
 FIELD (left, "left", "I") \
 FIELD (right, "right", "I") \
 FIELD (top, "top", "I")

 DECLARE_JNI_CLASS_WITH_MIN_SDK (AndroidGraphicsInsets, "android/graphics/Insets", 29)
#undef JNI_CLASS_MEMBERS

#define JNI_CLASS_MEMBERS(METHOD, STATICMETHOD, FIELD, STATICFIELD, CALLBACK) \
 STATICMETHOD (ime, "ime", "()I") \
 STATICMETHOD (displayCutout, "displayCutout", "()I")

 DECLARE_JNI_CLASS_WITH_MIN_SDK (AndroidWindowInsetsType, "android/view/WindowInsets$Type", 30)
#undef JNI_CLASS_MEMBERS

//==============================================================================
namespace
{
    enum
    {
        SYSTEM_UI_FLAG_VISIBLE = 0,
        SYSTEM_UI_FLAG_LOW_PROFILE = 1,
        SYSTEM_UI_FLAG_HIDE_NAVIGATION = 2,
        SYSTEM_UI_FLAG_FULLSCREEN = 4,
        SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION = 512,
        SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN = 1024,
        SYSTEM_UI_FLAG_IMMERSIVE = 2048,
        SYSTEM_UI_FLAG_IMMERSIVE_STICKY = 4096
    };

    constexpr int fullScreenFlags = SYSTEM_UI_FLAG_HIDE_NAVIGATION | SYSTEM_UI_FLAG_FULLSCREEN | SYSTEM_UI_FLAG_IMMERSIVE_STICKY;
    constexpr int FLAG_NOT_FOCUSABLE = 0x8;
}

//==============================================================================
static bool supportsDisplayCutout()
{
    return getAndroidSDKVersion() >= 28;
}

static BorderSize<int> androidDisplayCutoutToBorderSize (LocalRef<jobject> displayCutout, double displayScale)
{
    if (displayCutout == nullptr)
        return {};

    auto* env = getEnv();

    const auto getInset = [&] (jmethodID methodID)
    {
        return roundToInt (env->CallIntMethod (displayCutout, methodID) / displayScale);
    };

    return { getInset (AndroidDisplayCutout.getSafeInsetTop),
             getInset (AndroidDisplayCutout.getSafeInsetLeft),
             getInset (AndroidDisplayCutout.getSafeInsetBottom),
             getInset (AndroidDisplayCutout.getSafeInsetRight) };
}

static BorderSize<int> androidInsetsToBorderSize (LocalRef<jobject> insets, double displayScale)
{
    if (insets == nullptr)
        return {};

    auto* env = getEnv();

    const auto getInset = [&] (jfieldID fieldID)
    {
        return roundToInt (env->GetIntField (insets, fieldID) / displayScale);
    };

    return { getInset (AndroidGraphicsInsets.top),
             getInset (AndroidGraphicsInsets.left),
             getInset (AndroidGraphicsInsets.bottom),
             getInset (AndroidGraphicsInsets.right) };
}

class JuceInsets
{
    template <typename Display>
    static auto tieDisplay (Display& d) { return std::tie (d.safeAreaInsets, d.keyboardInsets); }

public:
    BorderSize<int> displayCutout, keyboard;

    static auto tie (      Displays::Display& d) { return tieDisplay (d); }
    static auto tie (const Displays::Display& d) { return tieDisplay (d); }

    auto tie() const { return std::tie (displayCutout, keyboard); }
};

static JuceInsets getInsetsFromAndroidWindowInsets (LocalRef<jobject> windowInsets, double scale)
{
    auto* env = getEnv();

    if (windowInsets == nullptr)
        return {};

    const auto displayCutout = [&]() -> BorderSize<int>
    {
        if (AndroidWindowInsets28.getDisplayCutout == nullptr)
            return {};

        const LocalRef<jobject> insets { env->CallObjectMethod (windowInsets, AndroidWindowInsets28.getDisplayCutout) };
        return androidDisplayCutoutToBorderSize (insets, scale);
    }();

    const auto keyboard = [&]() -> BorderSize<int>
    {
        if (AndroidWindowInsetsType.ime == nullptr || AndroidWindowInsets30.getInsets == nullptr)
            return {};

        const auto mask = env->CallStaticIntMethod (AndroidWindowInsetsType, AndroidWindowInsetsType.ime);
        const LocalRef<jobject> insets { env->CallObjectMethod (windowInsets, AndroidWindowInsets30.getInsets, mask) };
        return androidInsetsToBorderSize (insets, scale);
    }();

    return { displayCutout, keyboard };
}

/* The usage of the KeyPress class relies on its keyCode member having the standard ASCII values
   represent ASCII keycodes. However in the native Android keycodes the values for special keys
   e.g. RETURN, F1-F12 overlap with the ASCII range. Hence we need to translate them.
*/
static constexpr int translateAndroidKeyCode (int keyCode) noexcept
{
    switch (keyCode)
    {
        case 7:   return '0';
        case 8:   return '1';
        case 9:   return '2';
        case 10:  return '3';
        case 11:  return '4';
        case 12:  return '5';
        case 13:  return '6';
        case 14:  return '7';
        case 15:  return '8';
        case 16:  return '9';
        case 17:  return '*';
        case 18:  return '#';
        case 19:  return KeyPress::upKey;             // KEYCODE_DPAD_UP
        case 20:  return KeyPress::downKey;           // KEYCODE_DPAD_DOWN
        case 21:  return KeyPress::leftKey;           // KEYCODE_DPAD_LEFT
        case 22:  return KeyPress::rightKey;          // KEYCODE_DPAD_RIGHT
        case 29:  return 'A';
        case 30:  return 'B';
        case 31:  return 'C';
        case 32:  return 'D';
        case 33:  return 'E';
        case 34:  return 'F';
        case 35:  return 'G';
        case 36:  return 'H';
        case 37:  return 'I';
        case 38:  return 'J';
        case 39:  return 'K';
        case 40:  return 'L';
        case 41:  return 'M';
        case 42:  return 'N';
        case 43:  return 'O';
        case 44:  return 'P';
        case 45:  return 'Q';
        case 46:  return 'R';
        case 47:  return 'S';
        case 48:  return 'T';
        case 49:  return 'U';
        case 50:  return 'V';
        case 51:  return 'W';
        case 52:  return 'X';
        case 53:  return 'Y';
        case 54:  return 'Z';
        case 55:  return ',';
        case 56:  return '.';
        case 61:  return KeyPress::tabKey;            // KEYCODE_TAB
        case 62:  return KeyPress::spaceKey;          // KEYCODE_SPACE
        case 66:  return KeyPress::returnKey;         // KEYCODE_ENTER
        case 67:  return KeyPress::backspaceKey;      // KEYCODE_DEL
        case 68:  return '`';
        case 69:  return '-';
        case 70:  return '=';
        case 71:  return '[';
        case 72:  return ']';
        case 73:  return '\\';
        case 74:  return ';';
        case 75:  return '\'';
        case 76:  return '/';
        case 77:  return '@';
        case 81:  return '+';
        case 85:  return KeyPress::playKey;           // KEYCODE_MEDIA_PLAY_PAUSE
        case 86:  return KeyPress::stopKey;           // KEYCODE_MEDIA_STOP
        case 87:  return KeyPress::fastForwardKey;    // KEYCODE_MEDIA_NEXT
        case 88:  return KeyPress::rewindKey;         // KEYCODE_MEDIA_PREVIOUS
        case 92:  return KeyPress::pageUpKey;         // KEYCODE_PAGE_UP
        case 93:  return KeyPress::pageDownKey;       // KEYCODE_PAGE_DOWN
        case 111: return KeyPress::escapeKey;         // KEYCODE_ESCAPE
        case 112: return KeyPress::deleteKey;         // KEYCODE_FORWARD_DEL
        case 122: return KeyPress::homeKey;           // KEYCODE_MOVE_HOME
        case 123: return KeyPress::endKey;            // KEYCODE_MOVE_END
        case 124: return KeyPress::insertKey;         // KEYCODE_INSERT
        case 131: return KeyPress::F1Key;             // KEYCODE_F1
        case 132: return KeyPress::F2Key;             // KEYCODE_F2
        case 133: return KeyPress::F3Key;             // KEYCODE_F3
        case 134: return KeyPress::F4Key;             // KEYCODE_F4
        case 135: return KeyPress::F5Key;             // KEYCODE_F5
        case 136: return KeyPress::F6Key;             // KEYCODE_F6
        case 137: return KeyPress::F7Key;             // KEYCODE_F7
        case 138: return KeyPress::F8Key;             // KEYCODE_F8
        case 139: return KeyPress::F9Key;             // KEYCODE_F9
        case 140: return KeyPress::F10Key;            // KEYCODE_F10
        case 141: return KeyPress::F11Key;            // KEYCODE_F11
        case 142: return KeyPress::F12Key;            // KEYCODE_F12
        case 144: return '0';
        case 145: return '1';
        case 146: return '2';
        case 147: return '3';
        case 148: return '4';
        case 149: return '5';
        case 150: return '6';
        case 151: return '7';
        case 152: return '8';
        case 153: return '9';
        case 154: return '/';
        case 155: return '*';
        case 156: return '-';
        case 157: return '+';
        case 158: return '.';
        case 159: return ',';
        case 161: return '=';
        case 162: return '(';
        case 163: return ')';

        default:  return 0;
    }
}

static constexpr int translateAndroidKeyboardFlags (int javaFlags) noexcept
{
    constexpr int metaShiftOn = 0x1;
    constexpr int metaAltOn   = 0x02;
    constexpr int metaCtrlOn  = 0x1000;

    int flags = 0;

    if ((javaFlags & metaShiftOn) != 0) flags |= ModifierKeys::shiftModifier;
    if ((javaFlags & metaAltOn) != 0)   flags |= ModifierKeys::altModifier;
    if ((javaFlags & metaCtrlOn) != 0)  flags |= ModifierKeys::ctrlModifier;

    return flags;
}

//==============================================================================
class AndroidComponentPeer  : public ComponentPeer,
                              private Timer
{
public:
    AndroidComponentPeer (Component& comp, int windowStyleFlags, void* nativeViewHandle)
        : ComponentPeer (comp, windowStyleFlags)
    {
        auto* env = getEnv();

        // NB: must not put this in the initialiser list, as it invokes a callback,
        // which will fail if the peer is only half-constructed.
        view = GlobalRef (LocalRef<jobject> (env->NewObject (ComponentPeerView, ComponentPeerView.create,
                                                             getAppContext().get(), (jboolean) component.isOpaque(),
                                                             (jlong) this)));

        if (nativeViewHandle != nullptr)
        {
            viewGroupIsWindow = false;

            // we don't know if the user is holding on to a local ref to this, so
            // explicitly create a new one
            auto nativeView = LocalRef<jobject> (env->NewLocalRef (static_cast<jobject> (nativeViewHandle)));

            if (env->IsInstanceOf (nativeView.get(), AndroidActivity))
            {
                viewGroup = GlobalRef (nativeView);
                env->CallVoidMethod (viewGroup.get(), AndroidActivity.setContentView, view.get());
            }
            else if (env->IsInstanceOf (nativeView.get(), AndroidViewGroup))
            {
                viewGroup = GlobalRef (nativeView);
                LocalRef<jobject> layoutParams (env->NewObject (AndroidLayoutParams, AndroidLayoutParams.create, -2, -2));

                env->CallVoidMethod (view.get(), AndroidView.setLayoutParams, layoutParams.get());
                env->CallVoidMethod ((jobject) viewGroup.get(), AndroidViewGroup.addView, view.get());
            }
            else
            {
                // the native handle you passed as a second argument to Component::addToDesktop must
                // either be an Activity or a ViewGroup
                jassertfalse;
            }
        }
        else
        {
            viewGroupIsWindow = true;

            LocalRef<jobject> viewLayoutParams (env->NewObject (AndroidLayoutParams, AndroidLayoutParams.create, -2, -2));
            env->CallVoidMethod (view.get(), AndroidView.setLayoutParams, viewLayoutParams.get());

            auto physicalBounds = (comp.getBoundsInParent().toFloat() * scale).toNearestInt();

            view.callVoidMethod (AndroidView.layout,
                                 physicalBounds.getX(), physicalBounds.getY(), physicalBounds.getRight(), physicalBounds.getBottom());

            LocalRef<jobject> windowLayoutParams (env->NewObject (AndroidWindowManagerLayoutParams, AndroidWindowManagerLayoutParams.create,
                                                                  physicalBounds.getWidth(), physicalBounds.getHeight(),
                                                                  physicalBounds.getX(), physicalBounds.getY(),
                                                                  TYPE_APPLICATION, FLAG_NOT_TOUCH_MODAL | FLAG_LAYOUT_IN_SCREEN | FLAG_LAYOUT_NO_LIMITS | FLAG_NOT_FOCUSABLE,
                                                                  component.isOpaque() ? PIXEL_FORMAT_OPAQUE : PIXEL_FORMAT_TRANSPARENT));

            env->SetIntField (windowLayoutParams.get(), AndroidWindowManagerLayoutParams.gravity, GRAVITY_LEFT | GRAVITY_TOP);
            env->SetIntField (windowLayoutParams.get(), AndroidWindowManagerLayoutParams.windowAnimations, 0x01030000 /* android.R.style.Animation */);

            if (supportsDisplayCutout())
            {
                if (const auto fieldID = AndroidWindowManagerLayoutParams28.layoutInDisplayCutoutMode)
                    env->SetIntField (windowLayoutParams, fieldID, LAYOUT_IN_DISPLAY_CUTOUT_MODE_ALWAYS);
            }

            if (Desktop::getInstance().getKioskModeComponent() != nullptr)
                setNavBarsHidden (true);

            LocalRef<jobject> activity (getCurrentActivity());

            if (activity == nullptr)
                activity = getMainActivity();

            viewGroup = GlobalRef (LocalRef<jobject> (env->CallObjectMethod (activity.get(), AndroidContext.getSystemService, javaString ("window").get())));
            env->CallVoidMethod (viewGroup.get(), AndroidViewManager.addView, view.get(), windowLayoutParams.get());
        }

        if (supportsDisplayCutout())
        {
            if (const auto methodID = AndroidView23.setOnApplyWindowInsetsListener)
            {
                env->CallVoidMethod (view,
                                     methodID,
                                     CreateJavaInterface (new ViewWindowInsetsListener,
                                                          "android/view/View$OnApplyWindowInsetsListener").get());
            }
        }

        if (isFocused())
            handleFocusGain();
    }

    ~AndroidComponentPeer() override
    {
        stopTimer();

        auto* env = getEnv();

        env->CallVoidMethod (view, ComponentPeerView.clear);
        frontWindow = nullptr;

        GlobalRef localView (view);
        GlobalRef localViewGroup (viewGroup);

        callOnMessageThread ([env, localView, localViewGroup]
        {
            if (env->IsInstanceOf (localViewGroup.get(), AndroidActivity))
                env->CallVoidMethod (localViewGroup.get(), AndroidActivity.setContentView, nullptr);
            else
                env->CallVoidMethod (localViewGroup.get(), AndroidViewManager.removeView, localView.get());
        });
    }

    void* getNativeHandle() const override
    {
        return (void*) view.get();
    }

    void setVisible (bool shouldBeVisible) override
    {
        GlobalRef localView (view);

        callOnMessageThread ([localView, shouldBeVisible]
        {
            localView.callVoidMethod (ComponentPeerView.setVisible, shouldBeVisible);
        });
    }

    void setTitle (const String& title) override
    {
        view.callVoidMethod (ComponentPeerView.setViewName, javaString (title).get());
    }

    void setBounds (const Rectangle<int>& userRect, bool isNowFullScreen) override
    {
        auto bounds = (userRect.toFloat() * scale).toNearestInt();

        if (MessageManager::getInstance()->isThisTheMessageThread())
        {
            fullScreen = isNowFullScreen;

            view.callVoidMethod (AndroidView.layout,
                                 bounds.getX(), bounds.getY(), bounds.getRight(), bounds.getBottom());

            if (viewGroup != nullptr && viewGroupIsWindow)
            {
                auto* env = getEnv();

                LocalRef<jobject> windowLayoutParams (env->NewObject (AndroidWindowManagerLayoutParams, AndroidWindowManagerLayoutParams.create,
                                                                      bounds.getWidth(), bounds.getHeight(), bounds.getX(), bounds.getY(),
                                                                      TYPE_APPLICATION, FLAG_NOT_TOUCH_MODAL | FLAG_LAYOUT_IN_SCREEN | FLAG_LAYOUT_NO_LIMITS,
                                                                      component.isOpaque() ? PIXEL_FORMAT_OPAQUE : PIXEL_FORMAT_TRANSPARENT));

                env->SetIntField (windowLayoutParams.get(), AndroidWindowManagerLayoutParams.gravity, GRAVITY_LEFT | GRAVITY_TOP);
                env->CallVoidMethod (viewGroup.get(), AndroidViewManager.updateViewLayout, view.get(), windowLayoutParams.get());
            }
        }
        else
        {
            GlobalRef localView (view);

            MessageManager::callAsync ([localView, bounds]
            {
                localView.callVoidMethod (AndroidView.layout,
                                          bounds.getX(), bounds.getY(), bounds.getRight(), bounds.getBottom());
            });
        }
    }

    Rectangle<int> getBounds() const override
    {
        Rectangle<int> bounds (view.callIntMethod (AndroidView.getLeft),
                               view.callIntMethod (AndroidView.getTop),
                               view.callIntMethod (AndroidView.getWidth),
                               view.callIntMethod (AndroidView.getHeight));

        return (bounds.toFloat() / scale).toNearestInt();
    }

    void handleScreenSizeChange() override
    {
        ComponentPeer::handleScreenSizeChange();

        if (isFullScreen())
            setFullScreen (true);
    }

    Point<int> getScreenPosition() const
    {
        auto* env = getEnv();

        LocalRef<jintArray> position (env->NewIntArray (2));
        env->CallVoidMethod (view.get(), AndroidView.getLocationOnScreen, position.get());

        jint* const screenPosition = env->GetIntArrayElements (position.get(), nullptr);
        Point<int> pos (screenPosition[0], screenPosition[1]);
        env->ReleaseIntArrayElements (position.get(), screenPosition, 0);

        return pos;
    }

    Point<float> localToGlobal (Point<float> relativePosition) override
    {
        return relativePosition + (getScreenPosition().toFloat() / scale);
    }

    using ComponentPeer::localToGlobal;

    Point<float> globalToLocal (Point<float> screenPosition) override
    {
        return screenPosition - (getScreenPosition().toFloat() / scale);
    }

    using ComponentPeer::globalToLocal;

    void setMinimised (bool /*shouldBeMinimised*/) override
    {
        // n/a
    }

    bool isMinimised() const override
    {
        return false;
    }

    void setFullScreen (bool shouldBeFullScreen) override
    {
        if (shouldNavBarsBeHidden (shouldBeFullScreen))
        {
            if (isTimerRunning())
                return;

            startTimer (500);
        }
        else
        {
            setNavBarsHidden (false);
        }

        auto newBounds = [&]
        {
            if (navBarsHidden || shouldBeFullScreen)
                if (auto* display = Desktop::getInstance().getDisplays().getPrimaryDisplay())
                    return navBarsHidden ? display->totalArea
                                         : display->userArea;

            return lastNonFullscreenBounds.isEmpty() ? getBounds() : lastNonFullscreenBounds;
        }();

        if (! newBounds.isEmpty())
            setBounds (newBounds, shouldBeFullScreen);

        component.repaint();
    }

    bool isFullScreen() const override
    {
        return fullScreen;
    }

    void setIcon (const Image& /*newIcon*/) override
    {
        // n/a
    }

    bool contains (Point<int> localPos, bool trueIfInAChildWindow) const override
    {
        return isPositiveAndBelow (localPos.x, component.getWidth())
            && isPositiveAndBelow (localPos.y, component.getHeight())
            && ((! trueIfInAChildWindow) || view.callBooleanMethod (ComponentPeerView.containsPoint,
                                                                    (float) localPos.x * scale,
                                                                    (float) localPos.y * scale));
    }

    OptionalBorderSize getFrameSizeIfPresent() const override
    {
        // TODO
        return {};
    }

    BorderSize<int> getFrameSize() const override
    {
        // TODO
        return {};
    }

    bool setAlwaysOnTop (bool /*alwaysOnTop*/) override
    {
        // TODO
        return false;
    }

    void toFront (bool makeActive) override
    {
        // Avoid calling bringToFront excessively: it's very slow
        if (frontWindow != this)
        {
            view.callVoidMethod (AndroidView.bringToFront);
            frontWindow = this;
        }

        if (makeActive)
            grabFocus();

        handleBroughtToFront();
    }

    void toBehind (ComponentPeer*) override
    {
        // TODO
    }

    //==============================================================================
    void handleMouseDownCallback (int index, Point<float> sysPos, int64 time)
    {
        lastMousePos = sysPos / scale;
        auto pos = globalToLocal (lastMousePos);

        // this forces a mouse-enter/up event, in case for some reason we didn't get a mouse-up before.
        handleMouseEvent (MouseInputSource::InputSourceType::touch,
                          pos,
                          ModifierKeys::currentModifiers.withoutMouseButtons(),
                          MouseInputSource::defaultPressure,
                          MouseInputSource::defaultOrientation,
                          time,
                          {},
                          index);

        if (isValidPeer (this))
            handleMouseDragCallback (index, sysPos, time);
    }

    void handleMouseDragCallback (int index, Point<float> sysPos, int64 time)
    {
        lastMousePos = sysPos / scale;
        auto pos = globalToLocal (lastMousePos);

        jassert (index < 64);
        touchesDown = (touchesDown | (1 << (index & 63)));

        ModifierKeys::currentModifiers = ModifierKeys::currentModifiers.withoutMouseButtons().withFlags (ModifierKeys::leftButtonModifier);

        handleMouseEvent (MouseInputSource::InputSourceType::touch,
                          pos,
                          ModifierKeys::currentModifiers.withoutMouseButtons().withFlags (ModifierKeys::leftButtonModifier),
                          MouseInputSource::defaultPressure,
                          MouseInputSource::defaultOrientation,
                          time,
                          {},
                          index);
    }

    void handleMouseUpCallback (int index, Point<float> sysPos, int64 time)
    {
        lastMousePos = sysPos / scale;
        auto pos = globalToLocal (lastMousePos);

        jassert (index < 64);
        touchesDown = (touchesDown & ~(1 << (index & 63)));

        if (touchesDown == 0)
            ModifierKeys::currentModifiers = ModifierKeys::currentModifiers.withoutMouseButtons();

        handleMouseEvent (MouseInputSource::InputSourceType::touch,
                          pos,
                          ModifierKeys::currentModifiers.withoutMouseButtons(),
                          MouseInputSource::defaultPressure,
                          MouseInputSource::defaultOrientation,
                          time,
                          {},
                          index);
    }

    void handleAccessibilityHoverCallback (int command, Point<float> sysPos, int64)
    {
        enum
        {
            TYPE_VIEW_HOVER_ENTER = 0x00000080,
            TYPE_VIEW_HOVER_EXIT  = 0x00000100,

            ACTION_HOVER_ENTER    = 0x00000009,
            ACTION_HOVER_MOVE     = 0x00000007,
            ACTION_HOVER_EXIT     = 0x0000000a
        };

        if (auto* topHandler = component.getAccessibilityHandler())
        {
            if (auto* virtualHandler = topHandler->getChildAt ((sysPos / scale).roundToInt()))
            {
                switch (command)
                {
                    case ACTION_HOVER_ENTER:
                    case ACTION_HOVER_MOVE:
                        AccessibilityNativeHandle::sendAccessibilityEventImpl (*virtualHandler, TYPE_VIEW_HOVER_ENTER, 0);
                        break;

                    case ACTION_HOVER_EXIT:
                        AccessibilityNativeHandle::sendAccessibilityEventImpl (*virtualHandler, TYPE_VIEW_HOVER_EXIT, 0);
                        break;
                }
            }
        }
    }

    void handleKeyDownCallback (int k, int kc, int kbFlags)
    {
        ModifierKeys::currentModifiers = ModifierKeys::currentModifiers.withOnlyMouseButtons()
                                                                       .withFlags (translateAndroidKeyboardFlags (kbFlags));
        handleKeyPress (translateAndroidKeyCode (k), static_cast<juce_wchar> (kc));
    }

    void handleKeyUpCallback (int /*k*/, int /*kc*/)
    {
    }

    void handleBackButtonCallback()
    {
        bool handled = false;

        if (auto* app = JUCEApplicationBase::getInstance())
            handled = app->backButtonPressed();

        if (isKioskModeComponent())
            setNavBarsHidden (navBarsHidden);

        if (! handled)
        {
            auto* env = getEnv();
            LocalRef<jobject> activity (getCurrentActivity());

            if (activity != nullptr)
            {
                if (const auto finishMethod = AndroidActivity.finish)
                    env->CallVoidMethod (activity.get(), finishMethod);
            }
        }
    }

    void handleKeyboardHiddenCallback()
    {
        Component::unfocusAllComponents();
    }

    void handleAppPausedCallback() {}

    void handleAppResumedCallback()
    {
        if (isKioskModeComponent())
            setNavBarsHidden (navBarsHidden);
    }

    //==============================================================================
    AccessibilityNativeHandle* getNativeHandleForViewId (jint virtualViewId) const
    {
        if (auto* handler = (virtualViewId == HOST_VIEW_ID
                                 ? component.getAccessibilityHandler()
                                 : AccessibilityNativeHandle::getAccessibilityHandlerForVirtualViewId (virtualViewId)))
        {
            return handler->getNativeImplementation();
        }

        return nullptr;
    }

    jboolean populateAccessibilityNodeInfoCallback (jint virtualViewId, jobject info) const
    {
        if (auto* handle = getNativeHandleForViewId (virtualViewId))
        {
            handle->populateNodeInfo (info);
            return true;
        }

        return false;
    }

    jboolean handlePerformActionCallback (jint virtualViewId, jint action, jobject arguments) const
    {
        if (auto* handle = getNativeHandleForViewId (virtualViewId))
            return handle->performAction (action, arguments);

        return false;
    }

    static jobject getFocusViewIdForHandler (const AccessibilityHandler* handler)
    {
        if (handler != nullptr)
            return getEnv()->NewObject (JavaInteger,
                                        JavaInteger.constructor,
                                        handler->getNativeImplementation()->getVirtualViewId());

        return nullptr;
    }

    jobject getInputFocusViewIdCallback()
    {
        if (auto* comp = dynamic_cast<Component*> (findCurrentTextInputTarget()))
            return getFocusViewIdForHandler (comp->getAccessibilityHandler());

        return nullptr;
    }

    jobject getAccessibilityFocusViewIdCallback() const
    {
        if (auto* handler = component.getAccessibilityHandler())
        {
            if (auto* modal = Component::getCurrentlyModalComponent())
            {
                if (! component.isParentOf (modal)
                     && component.isCurrentlyBlockedByAnotherModalComponent())
                {
                    if (auto* modalHandler = modal->getAccessibilityHandler())
                    {
                        if (auto* focusChild = modalHandler->getChildFocus())
                            return getFocusViewIdForHandler (focusChild);

                        return getFocusViewIdForHandler (modalHandler);
                    }
                }
            }

            if (auto* focusChild = handler->getChildFocus())
                return getFocusViewIdForHandler (focusChild);
        }

        return nullptr;
    }

    //==============================================================================
    bool isFocused() const override
    {
        if (view != nullptr)
            return view.callBooleanMethod (AndroidView.hasFocus);

        return false;
    }

    void grabFocus() override
    {
        if (view != nullptr)
            view.callBooleanMethod (AndroidView.requestFocus);
    }

    void handleFocusChangeCallback (bool hasFocus)
    {
        if (isFullScreen())
            setFullScreen (true);

        if (hasFocus)
            handleFocusGain();
        else
            handleFocusLoss();
    }

    static const char* getVirtualKeyboardType (TextInputTarget::VirtualKeyboardType type) noexcept
    {
        switch (type)
        {
            case TextInputTarget::textKeyboard:          return "text";
            case TextInputTarget::numericKeyboard:       return "number";
            case TextInputTarget::decimalKeyboard:       return "numberDecimal";
            case TextInputTarget::urlKeyboard:           return "textUri";
            case TextInputTarget::emailAddressKeyboard:  return "textEmailAddress";
            case TextInputTarget::phoneNumberKeyboard:   return "phone";
            default:                                     jassertfalse; break;
        }

        return "text";
    }

    void textInputRequired (Point<int>, TextInputTarget& target) override
    {
        view.callVoidMethod (ComponentPeerView.showKeyboard,
                             javaString (getVirtualKeyboardType (target.getKeyboardType())).get());
    }

    void dismissPendingTextInput() override
    {
        closeInputMethodContext();

        view.callVoidMethod (ComponentPeerView.showKeyboard, javaString ("").get());

        if (! isTimerRunning())
            startTimer (500);
    }

    //==============================================================================
    void handleDoFrameCallback ([[maybe_unused]] int64 frameTimeNanos)
    {
        vBlankListeners.call ([] (auto& l) { l.onVBlank(); });
    }

    void handlePaintCallback (jobject canvas, jobject paint)
    {
        auto* env = getEnv();

        jobject rect = env->CallObjectMethod (canvas, AndroidCanvas.getClipBounds);
        auto left   = env->GetIntField (rect, AndroidRect.left);
        auto top    = env->GetIntField (rect, AndroidRect.top);
        auto right  = env->GetIntField (rect, AndroidRect.right);
        auto bottom = env->GetIntField (rect, AndroidRect.bottom);
        env->DeleteLocalRef (rect);

        auto clip = Rectangle<int>::leftTopRightBottom (left, top, right, bottom);

        if (clip.isEmpty())
            return;

        auto sizeNeeded = clip.getWidth() * clip.getHeight();

        if (sizeAllocated < sizeNeeded)
        {
            buffer.clear();
            sizeAllocated = sizeNeeded;
            buffer = GlobalRef (LocalRef<jobject> ((jobject) env->NewIntArray (sizeNeeded)));
        }

        if (jint* dest = env->GetIntArrayElements ((jintArray) buffer.get(), nullptr))
        {
            {
                Image temp (new PreallocatedImage (clip.getWidth(), clip.getHeight(),
                                                   dest, ! component.isOpaque()));

                {
                    LowLevelGraphicsSoftwareRenderer g (temp);
                    g.setOrigin (-clip.getPosition());
                    g.addTransform (AffineTransform::scale (scale));
                    handlePaint (g);
                }
            }

            env->ReleaseIntArrayElements ((jintArray) buffer.get(), dest, 0);

            env->CallVoidMethod (canvas, AndroidCanvas.drawBitmap, (jintArray) buffer.get(), 0, clip.getWidth(),
                                 (jfloat) clip.getX(), (jfloat) clip.getY(),
                                 clip.getWidth(), clip.getHeight(), true, paint);
        }
    }

    void repaint (const Rectangle<int>& userArea) override
    {
        auto area = (userArea.toFloat() * scale).toNearestInt();

        GlobalRef localView (view);

        callOnMessageThread ([area, localView]
        {
            localView.callVoidMethod (AndroidView.invalidate,
                                      area.getX(), area.getY(), area.getRight(), area.getBottom());
        });
    }

    void performAnyPendingRepaintsNow() override
    {
        // TODO
    }

    void setAlpha (float /*newAlpha*/) override
    {
        // TODO
    }

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

    //==============================================================================
    static Point<float> lastMousePos;
    static int64 touchesDown;

    //==============================================================================
    struct StartupActivityCallbackListener  : public ActivityLifecycleCallbacks
    {
        void onActivityStarted (jobject /*activity*/) override
        {
            auto* env = getEnv();
            LocalRef<jobject> appContext (getAppContext());

            if (appContext.get() != nullptr)
            {
                env->CallVoidMethod (appContext.get(),
                                     AndroidApplication.unregisterActivityLifecycleCallbacks,
                                     activityCallbackListener.get());
                clear();
                activityCallbackListener.clear();

                forceDisplayUpdate();
            }
        }
    };

private:
    //==============================================================================
    #define JNI_CLASS_MEMBERS(METHOD, STATICMETHOD, FIELD, STATICFIELD, CALLBACK) \
     METHOD   (create,                           "<init>",                        "(Landroid/content/Context;ZJ)V") \
     METHOD   (clear,                            "clear",                         "()V") \
     METHOD   (setViewName,                      "setViewName",                   "(Ljava/lang/String;)V") \
     METHOD   (setVisible,                       "setVisible",                    "(Z)V") \
     METHOD   (isVisible,                        "isVisible",                     "()Z") \
     METHOD   (containsPoint,                    "containsPoint",                 "(II)Z") \
     METHOD   (showKeyboard,                     "showKeyboard",                  "(Ljava/lang/String;)V") \
     METHOD   (setSystemUiVisibilityCompat,      "setSystemUiVisibilityCompat",   "(I)V")                           \
     CALLBACK (handleDoFrameJni,                 "handleDoFrame",                 "(JJ)V") \
     CALLBACK (handlePaintJni,                   "handlePaint",                   "(JLandroid/graphics/Canvas;Landroid/graphics/Paint;)V") \
     CALLBACK (handleMouseDownJni,               "handleMouseDown",               "(JIFFJ)V") \
     CALLBACK (handleMouseDragJni,               "handleMouseDrag",               "(JIFFJ)V") \
     CALLBACK (handleMouseUpJni,                 "handleMouseUp",                 "(JIFFJ)V") \
     CALLBACK (handleAccessibleHoverJni,         "handleAccessibilityHover",      "(JIFFJ)V") \
     CALLBACK (handleKeyDownJni,                 "handleKeyDown",                 "(JIII)V") \
     CALLBACK (handleKeyUpJni,                   "handleKeyUp",                   "(JII)V") \
     CALLBACK (handleBackButtonJni,              "handleBackButton",              "(J)V") \
     CALLBACK (handleKeyboardHiddenJni,          "handleKeyboardHidden",          "(J)V") \
     CALLBACK (viewSizeChangedJni,               "viewSizeChanged",               "(J)V") \
     CALLBACK (focusChangedJni,                  "focusChanged",                  "(JZ)V") \
     CALLBACK (handleAppPausedJni,               "handleAppPaused",               "(J)V") \
     CALLBACK (handleAppResumedJni,              "handleAppResumed",              "(J)V") \
     CALLBACK (populateAccessibilityNodeInfoJni, "populateAccessibilityNodeInfo", "(JILandroid/view/accessibility/AccessibilityNodeInfo;)Z") \
     CALLBACK (handlePerformActionJni,           "handlePerformAction",           "(JIILandroid/os/Bundle;)Z") \
     CALLBACK (getInputFocusViewIdJni,           "getInputFocusViewId",           "(J)Ljava/lang/Integer;") \
     CALLBACK (getAccessibilityFocusViewIdJni,   "getAccessibilityFocusViewId",   "(J)Ljava/lang/Integer;") \

    DECLARE_JNI_CLASS_WITH_BYTECODE (ComponentPeerView, "com/rmsl/juce/ComponentPeerView", 16, javaComponentPeerView, sizeof (javaComponentPeerView))
    #undef JNI_CLASS_MEMBERS

    static void JNICALL handleDoFrameJni        (JNIEnv*, jobject /*view*/, jlong host, jlong frameTimeNanos)                    { if (auto* myself = reinterpret_cast<AndroidComponentPeer*> (host)) myself->handleDoFrameCallback (frameTimeNanos); }
    static void JNICALL handlePaintJni          (JNIEnv*, jobject /*view*/, jlong host, jobject canvas, jobject paint)           { if (auto* myself = reinterpret_cast<AndroidComponentPeer*> (host)) myself->handlePaintCallback (canvas, paint); }
    static void JNICALL handleMouseDownJni      (JNIEnv*, jobject /*view*/, jlong host, jint i, jfloat x, jfloat y, jlong time)  { if (auto* myself = reinterpret_cast<AndroidComponentPeer*> (host)) myself->handleMouseDownCallback (i, Point<float> ((float) x, (float) y), (int64) time); }
    static void JNICALL handleMouseDragJni      (JNIEnv*, jobject /*view*/, jlong host, jint i, jfloat x, jfloat y, jlong time)  { if (auto* myself = reinterpret_cast<AndroidComponentPeer*> (host)) myself->handleMouseDragCallback (i, Point<float> ((float) x, (float) y), (int64) time); }
    static void JNICALL handleMouseUpJni        (JNIEnv*, jobject /*view*/, jlong host, jint i, jfloat x, jfloat y, jlong time)  { if (auto* myself = reinterpret_cast<AndroidComponentPeer*> (host)) myself->handleMouseUpCallback   (i, Point<float> ((float) x, (float) y), (int64) time); }
    static void JNICALL handleAccessibleHoverJni(JNIEnv*, jobject /*view*/, jlong host, jint c, jfloat x, jfloat y, jlong time)  { if (auto* myself = reinterpret_cast<AndroidComponentPeer*> (host)) myself->handleAccessibilityHoverCallback ((int) c, Point<float> ((float) x, (float) y), (int64) time); }
    static void JNICALL viewSizeChangedJni      (JNIEnv*, jobject /*view*/, jlong host)                                          { if (auto* myself = reinterpret_cast<AndroidComponentPeer*> (host)) myself->handleMovedOrResized(); }
    static void JNICALL focusChangedJni         (JNIEnv*, jobject /*view*/, jlong host, jboolean hasFocus)                       { if (auto* myself = reinterpret_cast<AndroidComponentPeer*> (host)) myself->handleFocusChangeCallback (hasFocus); }
    static void JNICALL handleKeyDownJni        (JNIEnv*, jobject /*view*/, jlong host, jint k, jint kc, jint kbFlags)           { if (auto* myself = reinterpret_cast<AndroidComponentPeer*> (host)) myself->handleKeyDownCallback ((int) k, (int) kc, (int) kbFlags); }
    static void JNICALL handleKeyUpJni          (JNIEnv*, jobject /*view*/, jlong host, jint k, jint kc)                         { if (auto* myself = reinterpret_cast<AndroidComponentPeer*> (host)) myself->handleKeyUpCallback ((int) k, (int) kc); }
    static void JNICALL handleBackButtonJni     (JNIEnv*, jobject /*view*/, jlong host)                                          { if (auto* myself = reinterpret_cast<AndroidComponentPeer*> (host)) myself->handleBackButtonCallback(); }
    static void JNICALL handleKeyboardHiddenJni (JNIEnv*, jobject /*view*/, jlong host)                                          { if (auto* myself = reinterpret_cast<AndroidComponentPeer*> (host)) myself->handleKeyboardHiddenCallback(); }
    static void JNICALL handleAppPausedJni      (JNIEnv*, jobject /*view*/, jlong host)                                          { if (auto* myself = reinterpret_cast<AndroidComponentPeer*> (host)) myself->handleAppPausedCallback(); }
    static void JNICALL handleAppResumedJni     (JNIEnv*, jobject /*view*/, jlong host)                                          { if (auto* myself = reinterpret_cast<AndroidComponentPeer*> (host)) myself->handleAppResumedCallback(); }

    static jboolean JNICALL populateAccessibilityNodeInfoJni (JNIEnv*, jobject /*view*/, jlong host, jint virtualViewId, jobject info)
    {
        if (auto* myself = reinterpret_cast<AndroidComponentPeer*> (host))
            return myself->populateAccessibilityNodeInfoCallback (virtualViewId, info);

        return false;
    }

    static jboolean JNICALL handlePerformActionJni (JNIEnv*, jobject /*view*/, jlong host, jint virtualViewId, jint action, jobject arguments)
    {
        if (auto* myself = reinterpret_cast<AndroidComponentPeer*> (host))
            return myself->handlePerformActionCallback (virtualViewId, action, arguments);

        return false;
    }

    static jobject JNICALL getInputFocusViewIdJni (JNIEnv*, jobject /*view*/, jlong host)
    {
        if (auto* myself = reinterpret_cast<AndroidComponentPeer*> (host))
            return myself->getInputFocusViewIdCallback();

        return nullptr;
    }

    static jobject JNICALL getAccessibilityFocusViewIdJni (JNIEnv*, jobject /*view*/, jlong host)
    {
        if (auto* myself = reinterpret_cast<AndroidComponentPeer*> (host))
            return myself->getAccessibilityFocusViewIdCallback();

        return nullptr;
    }

    //==============================================================================
    class ViewWindowInsetsListener  : public juce::AndroidInterfaceImplementer
    {
    public:
        jobject onApplyWindowInsets (LocalRef<jobject>, LocalRef<jobject> insets)
        {
            auto* env = getEnv();

            const auto& mainDisplay = *Desktop::getInstance().getDisplays().getPrimaryDisplay();
            const auto newInsets = getInsetsFromAndroidWindowInsets (insets, mainDisplay.scale);

            if (newInsets.tie() != JuceInsets::tie (mainDisplay))
                forceDisplayUpdate();

            if (const auto fieldId = AndroidWindowInsets30.CONSUMED)
                return env->GetStaticObjectField (AndroidWindowInsets30, fieldId);

            return env->CallObjectMethod (insets, AndroidWindowInsets28.consumeDisplayCutout);
        }

    private:
        jobject invoke (jobject proxy, jobject method, jobjectArray args) override
        {
            auto* env = getEnv();
            auto methodName = juce::juceString ((jstring) env->CallObjectMethod (method, JavaMethod.getName));

            if (methodName == "onApplyWindowInsets")
            {
                jassert (env->GetArrayLength (args) == 2);

                LocalRef<jobject> windowView (env->GetObjectArrayElement (args, 0));
                LocalRef<jobject> insets     (env->GetObjectArrayElement (args, 1));

                return onApplyWindowInsets (std::move (windowView), std::move (insets));
            }

            // invoke base class
            return AndroidInterfaceImplementer::invoke (proxy, method, args);
        }
    };

    //==============================================================================
    struct PreallocatedImage  : public ImagePixelData
    {
        PreallocatedImage (int width_, int height_, jint* data_, bool hasAlpha_)
            : ImagePixelData (Image::ARGB, width_, height_), data (data_), hasAlpha (hasAlpha_)
        {
            if (hasAlpha_)
                zeromem (data_, static_cast<size_t> (width * height) * sizeof (jint));
        }

        ~PreallocatedImage() override
        {
            if (hasAlpha)
            {
                auto pix = (PixelARGB*) data;

                for (int i = width * height; --i >= 0;)
                {
                    pix->unpremultiply();
                    ++pix;
                }
            }
        }

        std::unique_ptr<ImageType> createType() const override
        {
            return std::make_unique<SoftwareImageType>();
        }

        std::unique_ptr<LowLevelGraphicsContext> createLowLevelContext() override
        {
            return std::make_unique<LowLevelGraphicsSoftwareRenderer> (Image (this));
        }

        void initialiseBitmapData (Image::BitmapData& bm, int x, int y, Image::BitmapData::ReadWriteMode /*mode*/) override
        {
            bm.lineStride = width * static_cast<int> (sizeof (jint));
            bm.pixelStride = static_cast<int> (sizeof (jint));
            bm.pixelFormat = Image::ARGB;
            const auto offset = (size_t) x + (size_t) y * (size_t) width;
            bm.data = (uint8*) (data + offset);
            bm.size = sizeof (jint) * (((size_t) height * (size_t) width) - offset);
        }

        ImagePixelData::Ptr clone() override
        {
            auto s = new PreallocatedImage (width, height, nullptr, hasAlpha);
            s->allocatedData.malloc (sizeof (jint) * static_cast<size_t> (width * height));
            s->data = s->allocatedData;
            memcpy (s->data, data, sizeof (jint) * static_cast<size_t> (width * height));
            return s;
        }

    private:
        jint* data;
        HeapBlock<jint> allocatedData;
        bool hasAlpha;

        JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (PreallocatedImage)
    };

    //==============================================================================
    void timerCallback() override
    {
        setNavBarsHidden (shouldNavBarsBeHidden (fullScreen));
        setFullScreen (fullScreen);
        stopTimer();
    }

    bool isKioskModeComponent() const
    {
        if (auto* kiosk = Desktop::getInstance().getKioskModeComponent())
            return kiosk->getPeer() == this;

        return false;
    }

    bool shouldNavBarsBeHidden (bool shouldBeFullScreen) const
    {
        return (shouldBeFullScreen && isKioskModeComponent());
    }

    void setNavBarsHidden (bool hidden)
    {
        if (navBarsHidden != hidden)
        {
            navBarsHidden = hidden;

            view.callVoidMethod (ComponentPeerView.setSystemUiVisibilityCompat,
                                 (navBarsHidden ? (jint) (fullScreenFlags) : (jint) (SYSTEM_UI_FLAG_VISIBLE)));
        }
    }

    template <typename Callback>
    static void callOnMessageThread (Callback&& callback)
    {
        if (MessageManager::getInstance()->isThisTheMessageThread())
            callback();
        else
            MessageManager::callAsync (std::forward<Callback> (callback));
    }

    //==============================================================================
    friend class Displays;
    static AndroidComponentPeer* frontWindow;
    static GlobalRef activityCallbackListener;

    static constexpr int GRAVITY_LEFT = 0x3, GRAVITY_TOP = 0x30;
    static constexpr int TYPE_APPLICATION = 0x2;
    static constexpr int FLAG_NOT_TOUCH_MODAL = 0x20, FLAG_LAYOUT_IN_SCREEN = 0x100, FLAG_LAYOUT_NO_LIMITS = 0x200;
    static constexpr int PIXEL_FORMAT_OPAQUE = -1, PIXEL_FORMAT_TRANSPARENT = -2;
    static constexpr int LAYOUT_IN_DISPLAY_CUTOUT_MODE_ALWAYS = 0x3;

    GlobalRef view, viewGroup, buffer;
    bool viewGroupIsWindow = false, fullScreen = false, navBarsHidden = false;
    int sizeAllocated = 0;
    float scale = (float) Desktop::getInstance().getDisplays().getPrimaryDisplay()->scale;

    //==============================================================================
    JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AndroidComponentPeer)
};

Point<float> AndroidComponentPeer::lastMousePos;
int64 AndroidComponentPeer::touchesDown = 0;
AndroidComponentPeer* AndroidComponentPeer::frontWindow = nullptr;
GlobalRef AndroidComponentPeer::activityCallbackListener;
AndroidComponentPeer::ComponentPeerView_Class AndroidComponentPeer::ComponentPeerView;

//==============================================================================
ComponentPeer* Component::createNewPeer (int styleFlags, void* nativeWindow)
{
    return new AndroidComponentPeer (*this, styleFlags, nativeWindow);
}

//==============================================================================
bool Desktop::canUseSemiTransparentWindows() noexcept
{
    return true;
}

class Desktop::NativeDarkModeChangeDetectorImpl  : public ActivityLifecycleCallbacks
{
public:
    NativeDarkModeChangeDetectorImpl()
    {
        LocalRef<jobject> appContext (getAppContext());

        if (appContext != nullptr)
        {
            auto* env = getEnv();

            myself = GlobalRef (CreateJavaInterface (this, "android/app/Application$ActivityLifecycleCallbacks"));
            env->CallVoidMethod (appContext.get(), AndroidApplication.registerActivityLifecycleCallbacks, myself.get());
        }
    }

    ~NativeDarkModeChangeDetectorImpl() override
    {
        LocalRef<jobject> appContext (getAppContext());

        if (appContext != nullptr && myself != nullptr)
        {
            auto* env = getEnv();

            env->CallVoidMethod (appContext.get(),
                                 AndroidApplication.unregisterActivityLifecycleCallbacks,
                                 myself.get());
            clear();
            myself.clear();
        }
    }

    bool isDarkModeEnabled() const noexcept  { return darkModeEnabled; }

    void onActivityStarted (jobject /*activity*/) override
    {
        const auto isEnabled = getDarkModeSetting();

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

private:
    static bool getDarkModeSetting()
    {
        auto* env = getEnv();

        const LocalRef<jobject> resources (env->CallObjectMethod (getAppContext().get(), AndroidContext.getResources));
        const LocalRef<jobject> configuration (env->CallObjectMethod (resources, AndroidResources.getConfiguration));

        const auto uiMode = env->GetIntField (configuration, AndroidConfiguration.uiMode);

        return ((uiMode & UI_MODE_NIGHT_MASK) == UI_MODE_NIGHT_YES);
    }

    static constexpr int UI_MODE_NIGHT_MASK      = 0x00000030,
                         UI_MODE_NIGHT_NO        = 0x00000010,
                         UI_MODE_NIGHT_UNDEFINED = 0x00000000,
                         UI_MODE_NIGHT_YES       = 0x00000020;

    GlobalRef myself;
    bool darkModeEnabled = getDarkModeSetting();

    //==============================================================================
    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();
}

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

Desktop::DisplayOrientation Desktop::getCurrentOrientation() const
{
    enum
    {
        ROTATION_0   = 0,
        ROTATION_90  = 1,
        ROTATION_180 = 2,
        ROTATION_270 = 3
    };

    JNIEnv* env = getEnv();
    LocalRef<jstring> windowServiceString (javaString ("window"));


    LocalRef<jobject> windowManager = LocalRef<jobject> (env->CallObjectMethod (getAppContext().get(), AndroidContext.getSystemService, windowServiceString.get()));

    if (windowManager.get() != nullptr)
    {
        LocalRef<jobject> display = LocalRef<jobject> (env->CallObjectMethod (windowManager, AndroidWindowManager.getDefaultDisplay));

        if (display.get() != nullptr)
        {
            int rotation = env->CallIntMethod (display, AndroidDisplay.getRotation);

            switch (rotation)
            {
                case ROTATION_0:   return upright;
                case ROTATION_90:  return rotatedAntiClockwise;
                case ROTATION_180: return upsideDown;
                case ROTATION_270: return rotatedClockwise;
            }
        }
    }

    jassertfalse;
    return upright;
}

bool MouseInputSource::SourceList::addSource()
{
    addSource (sources.size(), MouseInputSource::InputSourceType::touch);
    return true;
}

bool MouseInputSource::SourceList::canUseTouch()
{
    return true;
}

Point<float> MouseInputSource::getCurrentRawMousePosition()
{
    return AndroidComponentPeer::lastMousePos;
}

void MouseInputSource::setRawMousePosition (Point<float>)
{
    // not needed
}

//==============================================================================
bool KeyPress::isKeyCurrentlyDown (int /*keyCode*/)
{
    // TODO
    return false;
}

JUCE_API void JUCE_CALLTYPE Process::hide()
{
    auto* env = getEnv();
    LocalRef<jobject> currentActivity (getCurrentActivity().get());

    if (env->CallBooleanMethod (currentActivity.get(), AndroidActivity.moveTaskToBack, true) == 0)
    {
        GlobalRef intent (LocalRef<jobject> (env->NewObject (AndroidIntent, AndroidIntent.constructor)));
        env->CallObjectMethod (intent, AndroidIntent.setAction,   javaString ("android.intent.action.MAIN")  .get());
        env->CallObjectMethod (intent, AndroidIntent.addCategory, javaString ("android.intent.category.HOME").get());

        env->CallVoidMethod (currentActivity.get(), AndroidContext.startActivity, intent.get());
    }
}

//==============================================================================
// TODO
JUCE_API bool JUCE_CALLTYPE Process::isForegroundProcess() { return true; }
JUCE_API void JUCE_CALLTYPE Process::makeForegroundProcess() {}

//==============================================================================
#define JNI_CLASS_MEMBERS(METHOD, STATICMETHOD, FIELD, STATICFIELD, CALLBACK) \
 METHOD (show,                   "show",                 "()V") \
 METHOD (getWindow,              "getWindow",            "()Landroid/view/Window;")

DECLARE_JNI_CLASS (AndroidDialog, "android/app/Dialog")
#undef JNI_CLASS_MEMBERS

#define JNI_CLASS_MEMBERS(METHOD, STATICMETHOD, FIELD, STATICFIELD, CALLBACK) \
 METHOD (construct,                   "<init>",                 "(Landroid/content/Context;)V") \
 METHOD (create,                      "create",                 "()Landroid/app/AlertDialog;") \
 METHOD (setTitle,                    "setTitle",               "(Ljava/lang/CharSequence;)Landroid/app/AlertDialog$Builder;") \
 METHOD (setMessage,                  "setMessage",             "(Ljava/lang/CharSequence;)Landroid/app/AlertDialog$Builder;") \
 METHOD (setCancelable,               "setCancelable",          "(Z)Landroid/app/AlertDialog$Builder;") \
 METHOD (setOnCancelListener,         "setOnCancelListener",    "(Landroid/content/DialogInterface$OnCancelListener;)Landroid/app/AlertDialog$Builder;") \
 METHOD (setPositiveButton,           "setPositiveButton",      "(Ljava/lang/CharSequence;Landroid/content/DialogInterface$OnClickListener;)Landroid/app/AlertDialog$Builder;") \
 METHOD (setNegativeButton,           "setNegativeButton",      "(Ljava/lang/CharSequence;Landroid/content/DialogInterface$OnClickListener;)Landroid/app/AlertDialog$Builder;") \
 METHOD (setNeutralButton,            "setNeutralButton",       "(Ljava/lang/CharSequence;Landroid/content/DialogInterface$OnClickListener;)Landroid/app/AlertDialog$Builder;")

DECLARE_JNI_CLASS (AndroidAlertDialogBuilder, "android/app/AlertDialog$Builder")
#undef JNI_CLASS_MEMBERS

#define JNI_CLASS_MEMBERS(METHOD, STATICMETHOD, FIELD, STATICFIELD, CALLBACK) \
 METHOD (dismiss,    "dismiss",  "()V")

DECLARE_JNI_CLASS (AndroidDialogInterface, "android/content/DialogInterface")
#undef JNI_CLASS_MEMBERS

#define JNI_CLASS_MEMBERS(METHOD, STATICMETHOD, FIELD, STATICFIELD, CALLBACK) \

DECLARE_JNI_CLASS (AndroidDialogOnClickListener, "android/content/DialogInterface$OnClickListener")
#undef JNI_CLASS_MEMBERS

//==============================================================================
class DialogListener  : public juce::AndroidInterfaceImplementer
{
public:
    DialogListener (std::shared_ptr<ModalComponentManager::Callback> callbackToUse, int resultToUse)
        : callback (std::move (callbackToUse)), result (resultToUse)
    {}

    void onResult (jobject dialog)
    {
        auto* env = getEnv();
        env->CallVoidMethod (dialog, AndroidDialogInterface.dismiss);

        if (callback != nullptr)
            callback->modalStateFinished (result);

        callback = nullptr;
    }

private:
    jobject invoke (jobject proxy, jobject method, jobjectArray args) override
    {
        auto* env = getEnv();
        auto methodName = juce::juceString ((jstring) env->CallObjectMethod (method, JavaMethod.getName));

        if (methodName == "onCancel" || methodName == "onClick")
        {
            onResult (env->GetObjectArrayElement (args, 0));
            return nullptr;
        }

        // invoke base class
        return AndroidInterfaceImplementer::invoke (proxy, method, args);
    }

    std::shared_ptr<ModalComponentManager::Callback> callback;
    int result;
};

//==============================================================================
static void createAndroidDialog (const MessageBoxOptions& opts,
                                 ModalComponentManager::Callback* callbackIn,
                                 AlertWindowMappings::MapFn mapFn)
{
    auto* env = getEnv();

    LocalRef<jobject> builder (env->NewObject (AndroidAlertDialogBuilder, AndroidAlertDialogBuilder.construct, getMainActivity().get()));

    builder = LocalRef<jobject> (env->CallObjectMethod (builder.get(), AndroidAlertDialogBuilder.setTitle,   javaString (opts.getTitle()).get()));
    builder = LocalRef<jobject> (env->CallObjectMethod (builder.get(), AndroidAlertDialogBuilder.setMessage, javaString (opts.getMessage()).get()));
    builder = LocalRef<jobject> (env->CallObjectMethod (builder.get(), AndroidAlertDialogBuilder.setCancelable, true));

    std::shared_ptr<ModalComponentManager::Callback> sharedCallback (AlertWindowMappings::getWrappedCallback (callbackIn, mapFn));

    builder = LocalRef<jobject> (env->CallObjectMethod (builder.get(), AndroidAlertDialogBuilder.setOnCancelListener,
                                                        CreateJavaInterface (new DialogListener (sharedCallback, 0),
                                                                             "android/content/DialogInterface$OnCancelListener").get()));

    builder = LocalRef<jobject> (env->CallObjectMethod (builder.get(), AndroidAlertDialogBuilder.setPositiveButton,
                                                        javaString (opts.getButtonText (0)).get(),
                                                        CreateJavaInterface (new DialogListener (sharedCallback, 0),
                                                                             "android/content/DialogInterface$OnClickListener").get()));

    if (opts.getButtonText (1).isNotEmpty())
        builder = LocalRef<jobject> (env->CallObjectMethod (builder.get(), AndroidAlertDialogBuilder.setNegativeButton,
                                                            javaString (opts.getButtonText (1)).get(),
                                                            CreateJavaInterface (new DialogListener (sharedCallback, 1),
                                                                                 "android/content/DialogInterface$OnClickListener").get()));

    if (opts.getButtonText (2).isNotEmpty())
        builder = LocalRef<jobject> (env->CallObjectMethod (builder.get(), AndroidAlertDialogBuilder.setNeutralButton,
                                                            javaString (opts.getButtonText (2)).get(),
                                                            CreateJavaInterface (new DialogListener (sharedCallback, 2),
                                                                                 "android/content/DialogInterface$OnClickListener").get()));

    LocalRef<jobject> dialog (env->CallObjectMethod (builder.get(), AndroidAlertDialogBuilder.create));

    LocalRef<jobject> window (env->CallObjectMethod (dialog.get(), AndroidDialog.getWindow));

    if (Desktop::getInstance().getKioskModeComponent() != nullptr)
    {
        env->CallVoidMethod (window.get(), AndroidWindow.setFlags, FLAG_NOT_FOCUSABLE, FLAG_NOT_FOCUSABLE);
        LocalRef<jobject> decorView (env->CallObjectMethod (window.get(), AndroidWindow.getDecorView));
        env->CallVoidMethod (decorView.get(), AndroidView.setSystemUiVisibility, fullScreenFlags);
    }

    env->CallVoidMethod (dialog.get(), AndroidDialog.show);

    if (Desktop::getInstance().getKioskModeComponent() != nullptr)
        env->CallVoidMethod (window.get(), AndroidWindow.clearFlags, FLAG_NOT_FOCUSABLE);
}

void JUCE_CALLTYPE NativeMessageBox::showMessageBoxAsync (MessageBoxIconType /*iconType*/,
                                                          const String& title, const String& message,
                                                          Component* /*associatedComponent*/,
                                                          ModalComponentManager::Callback* callback)
{
    createAndroidDialog (MessageBoxOptions()
                           .withTitle (title)
                           .withMessage (message)
                           .withButton (TRANS("OK")),
                         callback, AlertWindowMappings::messageBox);
}

bool JUCE_CALLTYPE NativeMessageBox::showOkCancelBox (MessageBoxIconType /*iconType*/,
                                                      const String& title, const String& message,
                                                      Component* /*associatedComponent*/,
                                                      ModalComponentManager::Callback* callback)
{
    createAndroidDialog (MessageBoxOptions()
                           .withTitle (title)
                           .withMessage (message)
                           .withButton (TRANS("OK"))
                           .withButton (TRANS("Cancel")),
                         callback, AlertWindowMappings::okCancel);

    return false;
}

int JUCE_CALLTYPE NativeMessageBox::showYesNoCancelBox (MessageBoxIconType /*iconType*/,
                                                        const String& title, const String& message,
                                                        Component* /*associatedComponent*/,
                                                        ModalComponentManager::Callback* callback)
{
    createAndroidDialog (MessageBoxOptions()
                           .withTitle (title)
                           .withMessage (message)
                           .withButton (TRANS("Yes"))
                           .withButton (TRANS("No"))
                           .withButton (TRANS("Cancel")),
                         callback, AlertWindowMappings::yesNoCancel);

    return 0;
}

int JUCE_CALLTYPE NativeMessageBox::showYesNoBox (MessageBoxIconType /*iconType*/,
                                                  const String& title, const String& message,
                                                  Component* /*associatedComponent*/,
                                                  ModalComponentManager::Callback* callback)
{
    createAndroidDialog (MessageBoxOptions()
                           .withTitle (title)
                           .withMessage (message)
                           .withButton (TRANS("Yes"))
                           .withButton (TRANS("No")),
                         callback, AlertWindowMappings::okCancel);

    return 0;
}

void JUCE_CALLTYPE NativeMessageBox::showAsync (const MessageBoxOptions& options,
                                                ModalComponentManager::Callback* callback)
{
    createAndroidDialog (options, callback, AlertWindowMappings::noMapping);
}

void JUCE_CALLTYPE NativeMessageBox::showAsync (const MessageBoxOptions& options,
                                                std::function<void (int)> callback)
{
    showAsync (options, ModalCallbackFunction::create (callback));
}

//==============================================================================
static bool androidScreenSaverEnabled = true;

void Desktop::setScreenSaverEnabled (bool shouldEnable)
{
    constexpr auto FLAG_KEEP_SCREEN_ON = 0x80;

    if (shouldEnable != androidScreenSaverEnabled)
    {
        LocalRef<jobject> activity (getMainActivity());

        if (activity != nullptr)
        {
            auto* env = getEnv();

            LocalRef<jobject> mainWindow (env->CallObjectMethod (activity.get(), AndroidActivity.getWindow));
            env->CallVoidMethod (mainWindow.get(), AndroidWindow.setFlags, shouldEnable ? 0 : FLAG_KEEP_SCREEN_ON, FLAG_KEEP_SCREEN_ON);
        }

        androidScreenSaverEnabled = shouldEnable;
    }
}

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

//==============================================================================
void Desktop::setKioskComponent (Component* kioskComp, bool enableOrDisable, bool allowMenusAndBars)
{
    ignoreUnused (allowMenusAndBars);

    if (AndroidComponentPeer* peer = dynamic_cast<AndroidComponentPeer*> (kioskComp->getPeer()))
        peer->setFullScreen (enableOrDisable);
    else
        jassertfalse; // (this should have been checked by the caller)
}

//==============================================================================
static jint getAndroidOrientationFlag (int orientations) noexcept
{
    enum
    {
        SCREEN_ORIENTATION_LANDSCAPE          = 0,
        SCREEN_ORIENTATION_PORTRAIT           = 1,
        SCREEN_ORIENTATION_USER               = 2,
        SCREEN_ORIENTATION_REVERSE_LANDSCAPE  = 8,
        SCREEN_ORIENTATION_REVERSE_PORTRAIT   = 9,
        SCREEN_ORIENTATION_USER_LANDSCAPE     = 11,
        SCREEN_ORIENTATION_USER_PORTRAIT      = 12,
    };

    switch (orientations)
    {
        case Desktop::upright:                                          return (jint) SCREEN_ORIENTATION_PORTRAIT;
        case Desktop::upsideDown:                                       return (jint) SCREEN_ORIENTATION_REVERSE_PORTRAIT;
        case Desktop::upright + Desktop::upsideDown:                    return (jint) SCREEN_ORIENTATION_USER_PORTRAIT;
        case Desktop::rotatedAntiClockwise:                             return (jint) SCREEN_ORIENTATION_LANDSCAPE;
        case Desktop::rotatedClockwise:                                 return (jint) SCREEN_ORIENTATION_REVERSE_LANDSCAPE;
        case Desktop::rotatedClockwise + Desktop::rotatedAntiClockwise: return (jint) SCREEN_ORIENTATION_USER_LANDSCAPE;
        default:                                                        return (jint) SCREEN_ORIENTATION_USER;
    }
}

void Desktop::allowedOrientationsChanged()
{
    LocalRef<jobject> activity (getMainActivity());

    if (activity != nullptr)
        getEnv()->CallVoidMethod (activity.get(), AndroidActivity.setRequestedOrientation, getAndroidOrientationFlag (allowedOrientations));
}

//==============================================================================
bool juce_areThereAnyAlwaysOnTopWindows()
{
    return false;
}

//==============================================================================
#define JNI_CLASS_MEMBERS(METHOD, STATICMETHOD, FIELD, STATICFIELD, CALLBACK) \
 METHOD (create,          "<init>",         "()V") \
 FIELD  (density,         "density",        "F") \
 FIELD  (widthPixels,     "widthPixels",    "I") \
 FIELD  (heightPixels,    "heightPixels",   "I")

DECLARE_JNI_CLASS (AndroidDisplayMetrics, "android/util/DisplayMetrics")
#undef JNI_CLASS_MEMBERS

//==============================================================================
class LayoutChangeListener  : public juce::AndroidInterfaceImplementer
{
public:
    virtual void onLayoutChange (LocalRef<jobject> view, int left, int top, int right, int bottom,
                                 int oldLeft, int oldTop, int oldRight, int oldBottom) = 0;

private:
    jobject invoke (jobject proxy, jobject method, jobjectArray args) override
    {
        auto* env = getEnv();
        auto methodName = juce::juceString ((jstring) env->CallObjectMethod (method, JavaMethod.getName));

        if (methodName == "onLayoutChange")
        {
            jassert (env->GetArrayLength (args) == 9);

            LocalRef<jobject> view (env->GetObjectArrayElement (args, 0));
            int dims[8];

            for (int i = 1; i < 9; ++i)
            {
                LocalRef<jobject> integer (env->GetObjectArrayElement (args, i));
                dims[i - 1] = env->CallIntMethod (integer.get(), JavaInteger.intValue);
            }

            onLayoutChange (std::move (view), dims[0], dims[1], dims[2], dims[3],
                            dims[4], dims[5], dims[6], dims[7]);

            return nullptr;
        }

        // invoke base class
        return AndroidInterfaceImplementer::invoke (proxy, method, args);
    }

    std::unique_ptr<ModalComponentManager::Callback> callback;
};

//==============================================================================
struct MainActivityWindowLayoutListener   : public LayoutChangeListener
{
    MainActivityWindowLayoutListener (std::function<void()>&& updateDisplaysCb)
        : forceDisplayUpdate (std::move (updateDisplaysCb))
    {
    }

    void onLayoutChange (LocalRef<jobject> /*view*/, int left, int top, int right, int bottom,
                         int oldLeft, int oldTop, int oldRight, int oldBottom) override
    {
        auto newBounds = Rectangle<int>::leftTopRightBottom (left, top, right, bottom);
        auto oldBounds = Rectangle<int>::leftTopRightBottom (oldLeft, oldTop, oldRight, oldBottom);

        if (newBounds != oldBounds)
        {
            const auto& mainDisplay = *Desktop::getInstance().getDisplays().getPrimaryDisplay();
            auto userArea = (newBounds.toFloat() / mainDisplay.scale).toNearestInt();

            if (userArea != mainDisplay.userArea)
                forceDisplayUpdate();
        }
    }

    std::function<void()> forceDisplayUpdate;
};

//==============================================================================
void Displays::findDisplays (float masterScale)
{
    auto* env = getEnv();

    LocalRef<jobject> usableSize (env->NewObject (AndroidPoint, AndroidPoint.create, 0, 0));
    LocalRef<jstring> windowServiceString (javaString ("window"));
    LocalRef<jobject> displayMetrics (env->NewObject (AndroidDisplayMetrics, AndroidDisplayMetrics.create));
    LocalRef<jobject> windowManager (env->CallObjectMethod (getAppContext().get(), AndroidContext.getSystemService, windowServiceString.get()));
    LocalRef<jobject> display (env->CallObjectMethod (windowManager, AndroidWindowManager.getDefaultDisplay));

    if (const auto getRealMetricsMethod = AndroidDisplay17.getRealMetrics)
        env->CallVoidMethod (display, getRealMetricsMethod, displayMetrics.get());
    else
        env->CallVoidMethod (display, AndroidDisplay.getMetrics, displayMetrics.get());

    env->CallVoidMethod (display, AndroidDisplay.getSize, usableSize.get());

    Display d;

    d.isMain = true;
    d.scale = env->GetFloatField (displayMetrics.get(), AndroidDisplayMetrics.density);
    d.dpi = (d.scale * 160.f);
    d.scale *= masterScale;

    d.totalArea = Rectangle<int> (env->GetIntField (displayMetrics.get(), AndroidDisplayMetrics.widthPixels),
                                  env->GetIntField (displayMetrics.get(), AndroidDisplayMetrics.heightPixels)) / d.scale;

    d.userArea = Rectangle<int> (env->GetIntField (usableSize.get(), AndroidPoint.x),
                                 env->GetIntField (usableSize.get(), AndroidPoint.y)) / d.scale;

    // unfortunately usableSize still contains the nav bar
    // the best workaround is to try to get the size of the top-level view of
    // the main activity
    LocalRef<jobject> activity (getMainActivity());

    if (activity != nullptr)
    {
        LocalRef<jobject> mainWindow (env->CallObjectMethod (activity.get(), AndroidActivity.getWindow));
        LocalRef<jobject> decorView (env->CallObjectMethod (mainWindow.get(), AndroidWindow.getDecorView));
        LocalRef<jobject> contentView (env->CallObjectMethod (decorView.get(), AndroidView.findViewById, 0x01020002 /* android.R.id.content */));

        if (contentView != nullptr)
        {
            Rectangle<int> activityArea (env->CallIntMethod (contentView.get(), AndroidView.getLeft),
                                         env->CallIntMethod (contentView.get(), AndroidView.getTop),
                                         env->CallIntMethod (contentView.get(), AndroidView.getWidth),
                                         env->CallIntMethod (contentView.get(), AndroidView.getHeight));

            if (! activityArea.isEmpty())
                d.userArea = activityArea / d.scale;

            if (const auto getRootWindowInsetsMethodId = AndroidView23.getRootWindowInsets)
            {
                LocalRef<jobject> insets (env->CallObjectMethod (contentView.get(), getRootWindowInsetsMethodId));
                JuceInsets::tie (d) = getInsetsFromAndroidWindowInsets (insets, d.scale).tie();
            }

            static bool hasAddedMainActivityListener = false;

            if (! hasAddedMainActivityListener)
            {
                hasAddedMainActivityListener = true;

                env->CallVoidMethod (contentView.get(), AndroidView.addOnLayoutChangeListener,
                                     CreateJavaInterface (new MainActivityWindowLayoutListener ([this] { refresh(); }),
                                                          "android/view/View$OnLayoutChangeListener").get());
            }
        }
    }
    else
    {
        // the main activity may have not started yet so add an activity listener
        if (AndroidComponentPeer::activityCallbackListener == nullptr)
        {
            LocalRef<jobject> appContext (getAppContext());

            if (appContext.get() != nullptr)
            {
                AndroidComponentPeer::activityCallbackListener = GlobalRef (CreateJavaInterface (
                        new AndroidComponentPeer::StartupActivityCallbackListener,
                        "android/app/Application$ActivityLifecycleCallbacks"));

                env->CallVoidMethod (appContext.get(),
                                     AndroidApplication.registerActivityLifecycleCallbacks,
                                     AndroidComponentPeer::activityCallbackListener.get());
            }
        }
    }

    displays.add (d);
}

//==============================================================================
Image juce_createIconForFile (const File& /*file*/)
{
    return Image();
}

//==============================================================================
class MouseCursor::PlatformSpecificHandle
{
public:
    PlatformSpecificHandle (const MouseCursor::StandardCursorType)      {}
    PlatformSpecificHandle (const CustomMouseCursorInfo&)               {}

    static void showInWindow (PlatformSpecificHandle*, ComponentPeer*)  {}
};

//==============================================================================
bool DragAndDropContainer::performExternalDragDropOfFiles (const StringArray& /*files*/, bool /*canMove*/,
                                                           Component* /*srcComp*/, std::function<void()> /*callback*/)
{
    jassertfalse;    // no such thing on Android!
    return false;
}

bool DragAndDropContainer::performExternalDragDropOfText (const String& /*text*/, Component* /*srcComp*/,
                                                          std::function<void()> /*callback*/)
{
    jassertfalse;    // no such thing on Android!
    return false;
}

//==============================================================================
void LookAndFeel::playAlertSound()
{
}

//==============================================================================
#define JNI_CLASS_MEMBERS(METHOD, STATICMETHOD, FIELD, STATICFIELD, CALLBACK) \
 METHOD (getText,      "getText",            "()Ljava/lang/CharSequence;") \
 METHOD (setText,      "setText",            "(Ljava/lang/CharSequence;)V")

DECLARE_JNI_CLASS (AndroidClipboardManager, "android/content/ClipboardManager")
#undef JNI_CLASS_MEMBERS

//==============================================================================
void SystemClipboard::copyTextToClipboard (const String& text)
{
    auto* env = getEnv();

    LocalRef<jobject> clipboardManager (env->CallObjectMethod (getAppContext().get(), AndroidContext.getSystemService, javaString ("clipboard").get()));
    env->CallVoidMethod (clipboardManager.get(), AndroidClipboardManager.setText, javaString(text).get());
}

String SystemClipboard::getTextFromClipboard()
{
    auto* env = getEnv();

    LocalRef<jobject> clipboardManager (env->CallObjectMethod (getAppContext().get(), AndroidContext.getSystemService, javaString ("clipboard").get()));
    LocalRef<jobject> charSequence (env->CallObjectMethod (clipboardManager.get(), AndroidClipboardManager.getText));

    if (charSequence == nullptr)
        return {};

    return juceString(LocalRef<jstring> ((jstring) env->CallObjectMethod(charSequence.get(), JavaCharSequence.toString)));
}

//==============================================================================
constexpr int extendedKeyModifier           = 0x10000;

const int KeyPress::spaceKey                = ' ';
const int KeyPress::returnKey               = extendedKeyModifier + 2;
const int KeyPress::escapeKey               = extendedKeyModifier + 3;
const int KeyPress::backspaceKey            = extendedKeyModifier + 4;
const int KeyPress::leftKey                 = extendedKeyModifier + 5;
const int KeyPress::rightKey                = extendedKeyModifier + 6;
const int KeyPress::upKey                   = extendedKeyModifier + 7;
const int KeyPress::downKey                 = extendedKeyModifier + 8;
const int KeyPress::pageUpKey               = extendedKeyModifier + 9;
const int KeyPress::pageDownKey             = extendedKeyModifier + 10;
const int KeyPress::endKey                  = extendedKeyModifier + 11;
const int KeyPress::homeKey                 = extendedKeyModifier + 12;
const int KeyPress::deleteKey               = extendedKeyModifier + 13;
const int KeyPress::insertKey               = extendedKeyModifier + 14;
const int KeyPress::tabKey                  = extendedKeyModifier + 15;
const int KeyPress::F1Key                   = extendedKeyModifier + 16;
const int KeyPress::F2Key                   = extendedKeyModifier + 17;
const int KeyPress::F3Key                   = extendedKeyModifier + 18;
const int KeyPress::F4Key                   = extendedKeyModifier + 19;
const int KeyPress::F5Key                   = extendedKeyModifier + 20;
const int KeyPress::F6Key                   = extendedKeyModifier + 21;
const int KeyPress::F7Key                   = extendedKeyModifier + 22;
const int KeyPress::F8Key                   = extendedKeyModifier + 23;
const int KeyPress::F9Key                   = extendedKeyModifier + 24;
const int KeyPress::F10Key                  = extendedKeyModifier + 25;
const int KeyPress::F11Key                  = extendedKeyModifier + 26;
const int KeyPress::F12Key                  = extendedKeyModifier + 27;
const int KeyPress::F13Key                  = extendedKeyModifier + 28;
const int KeyPress::F14Key                  = extendedKeyModifier + 29;
const int KeyPress::F15Key                  = extendedKeyModifier + 30;
const int KeyPress::F16Key                  = extendedKeyModifier + 31;
const int KeyPress::F17Key                  = extendedKeyModifier + 32;
const int KeyPress::F18Key                  = extendedKeyModifier + 33;
const int KeyPress::F19Key                  = extendedKeyModifier + 34;
const int KeyPress::F20Key                  = extendedKeyModifier + 35;
const int KeyPress::F21Key                  = extendedKeyModifier + 36;
const int KeyPress::F22Key                  = extendedKeyModifier + 37;
const int KeyPress::F23Key                  = extendedKeyModifier + 38;
const int KeyPress::F24Key                  = extendedKeyModifier + 39;
const int KeyPress::F25Key                  = extendedKeyModifier + 40;
const int KeyPress::F26Key                  = extendedKeyModifier + 41;
const int KeyPress::F27Key                  = extendedKeyModifier + 42;
const int KeyPress::F28Key                  = extendedKeyModifier + 43;
const int KeyPress::F29Key                  = extendedKeyModifier + 44;
const int KeyPress::F30Key                  = extendedKeyModifier + 45;
const int KeyPress::F31Key                  = extendedKeyModifier + 46;
const int KeyPress::F32Key                  = extendedKeyModifier + 47;
const int KeyPress::F33Key                  = extendedKeyModifier + 48;
const int KeyPress::F34Key                  = extendedKeyModifier + 49;
const int KeyPress::F35Key                  = extendedKeyModifier + 50;
const int KeyPress::numberPad0              = extendedKeyModifier + 51;
const int KeyPress::numberPad1              = extendedKeyModifier + 52;
const int KeyPress::numberPad2              = extendedKeyModifier + 53;
const int KeyPress::numberPad3              = extendedKeyModifier + 54;
const int KeyPress::numberPad4              = extendedKeyModifier + 55;
const int KeyPress::numberPad5              = extendedKeyModifier + 56;
const int KeyPress::numberPad6              = extendedKeyModifier + 57;
const int KeyPress::numberPad7              = extendedKeyModifier + 58;
const int KeyPress::numberPad8              = extendedKeyModifier + 59;
const int KeyPress::numberPad9              = extendedKeyModifier + 60;
const int KeyPress::numberPadAdd            = extendedKeyModifier + 61;
const int KeyPress::numberPadSubtract       = extendedKeyModifier + 62;
const int KeyPress::numberPadMultiply       = extendedKeyModifier + 63;
const int KeyPress::numberPadDivide         = extendedKeyModifier + 64;
const int KeyPress::numberPadSeparator      = extendedKeyModifier + 65;
const int KeyPress::numberPadDecimalPoint   = extendedKeyModifier + 66;
const int KeyPress::numberPadEquals         = extendedKeyModifier + 67;
const int KeyPress::numberPadDelete         = extendedKeyModifier + 68;
const int KeyPress::playKey                 = extendedKeyModifier + 69;
const int KeyPress::stopKey                 = extendedKeyModifier + 70;
const int KeyPress::fastForwardKey          = extendedKeyModifier + 71;
const int KeyPress::rewindKey               = extendedKeyModifier + 72;

//==============================================================================
#ifdef JUCE_PUSH_NOTIFICATIONS_ACTIVITY
 struct JuceActivityNewIntentListener
 {
     #define JNI_CLASS_MEMBERS(METHOD, STATICMETHOD, FIELD, STATICFIELD, CALLBACK) \
      CALLBACK (appNewIntent, "appNewIntent", "(Landroid/content/Intent;)V") \
      CALLBACK (appOnResume,  "appOnResume",  "()V")

      DECLARE_JNI_CLASS (JavaActivity, JUCE_PUSH_NOTIFICATIONS_ACTIVITY)
     #undef JNI_CLASS_MEMBERS

     static void JNICALL appNewIntent (JNIEnv*, jobject /*activity*/, jobject intentData)
     {
         juce_handleNotificationIntent (static_cast<void*> (intentData));
     }

     static void JNICALL appOnResume (JNIEnv*, jobject)
     {
         juce_handleOnResume();
     }
 };

 JuceActivityNewIntentListener::JavaActivity_Class JuceActivityNewIntentListener::JavaActivity;
#endif

} // namespace juce
