<!DOCTYPE html>
<html>
<head>
  <title>Test whether windowless plugins receive correct visible/invisible notifications.</title>
  <script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
  <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css" />

  <style>
    .hidden { visibility: hidden; }
  </style>

<body onload="startTest()">
  <p id="display"></p>

  <script type="application/javascript" src="plugin-utils.js"></script>
  <script type="application/javascript">
  SimpleTest.waitForExplicitFinish();
  SimpleTest.requestFlakyTimeout("untriaged");
  setTestPluginEnabledState(SpecialPowers.Ci.nsIPluginTag.STATE_ENABLED);

  var didPaint = function() {};

  function startTest() {
    if (p.getPaintCount() < 1) {
      setTimeout(startTest, 0);
      return;
    }

    didPaint = function() {
      ok(false, "Plugin should not paint until it is visible!");
    };

    ok(!p.isVisible(), "Plugin should not be visible.");
    paintCountIs(p, 0, "Plugin should not have painted.");

    didPaint = part2;

    p.style.visibility = 'visible';
  }

  function part2() {
    ok(p.isVisible(), "Plugin should now be visible.");
    paintCountIs(p, 1, "Plugin should have painted once.");

    didPaint = part3;

    p.setColor('FF0000FF'); // this causes an invalidate/repaint
  }

  const kTimeout = 5000; // 5 seconds
  var part4GiveUp;
  var part4Interval;

  function part3() {
    ok(p.isVisible(), "Plugin should still be visible.");
    paintCountIs(p, 2, "Plugin should have painted twice.");

    didPaint = function() {
      ok(false, "Plugin should not paint when it is invisible.");
    };

    p.style.visibility = 'hidden';

    part4GiveUp = Date.now() + kTimeout;
    part4Interval = setInterval(part4, 100);
  }

  function part4() {
    if (p.isVisible()) {
      if (Date.now() < part4GiveUp)
        return;

      ok(false, "Plugin never became invisible in part4.");
      SimpleTest.finish();
      return;
    }

    clearInterval(part4Interval);

    ok(true, "Plugin became invisible again.");
    p.setColor('FF00FF00');
    setTimeout(SimpleTest.finish, 500);
    // wait to make sure we don't actually paint
  }

  function inPaint() {
    // We're actually in the middle of painting the plugin so don't do anything
    // complex here, for the sake of cases where async plugin painting isn't
    // enabled yet
    setTimeout(didPaint, 0);
    // Don't run that didPaint callback again
    didPaint = function() {};
  }
  </script>

  <embed id="theplugin" class="hidden" type="application/x-test" drawmode="solid" color="FFFF0000" paintscript="inPaint()"></embed>
  
  <script type="application/javascript">
  var p = document.getElementById('theplugin');
  </script>