# Copyright 2015 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.

import("//base/android/jni_generator/jni_exception_list.gni")
import("//build/buildflag_header.gni")
import("//build/config/features.gni")
import("//build/config/sanitizers/sanitizers.gni")
import("//build/config/ui.gni")
import("//chromecast/build/tests/cast_test.gni")
import("//chromecast/chromecast.gni")
import("//media/media_options.gni")
import("//tools/grit/repack.gni")
import("//ui/ozone/ozone.gni")
import("//v8/gni/v8.gni")

if (is_android) {
  import("//build/config/android/rules.gni")
}

declare_args() {
  cast_test_extra_flags = ""
}

config("playready_config") {
  if (use_playready) {
    defines = [ "PLAYREADY_CDM_AVAILABLE" ]
  }
}

# Depends on all non-test targets that should be built by the Chromecast
# internal build infrastructure.
group("all") {
  deps = []
  if (is_android && chromecast_branding == "public") {
    deps += [ ":cast_shell_apk" ]
  }
  if (!is_android) {
    deps += [ ":cast_shell" ]
  }
  if (is_linux) {
    deps += [ "//chromecast/tracing" ]
  }
  if (chromecast_branding != "public") {
    deps += [ "//chromecast/internal:all" ]
  }

  # No other targets should depend on this target, since it's just a convenience
  # target for the Chromecast internal build infrastructure.
  visibility = []
  testonly = true
}

# This is a config which is applied on all cast_* targets (which should be all
# code under chromecast/).
config("cast_config") {
}

# A list of all public test() binaries. This is an organizational target that
# cannot be depended upon or built directly. Build cast_test_lists instead.
cast_test_group("cast_tests") {
  filters = []
  tests = [
    "//base:base_unittests",
    "//cc:cc_unittests",
    "//chromecast/base:cast_base_unittests",
    "//chromecast/base/component:cast_component_unittests",
    "//chromecast/crypto:cast_crypto_unittests",
    "//chromecast/device/bluetooth:cast_bluetooth_unittests",
    "//chromecast/media:cast_media_unittests",
    "//chromecast/net:cast_net_unittests",
    "//chromecast/system/reboot:cast_reboot_unittests",
    "//content/test:content_unittests",
    "//crypto:crypto_unittests",
    "//media:media_unittests",
    "//media/midi:midi_unittests",
    "//net:net_unittests",
    "//sql:sql_unittests",
    "//storage:storage_unittests",
    "//third_party/cacheinvalidation:cacheinvalidation_unittests",
    "//ui/base:ui_base_unittests",
  ]

  if (!is_cast_audio_only) {
    tests += [ "//gpu:gpu_unittests" ]

    if (use_aura) {
      tests += [ "//chromecast/graphics:cast_graphics_unittests" ]
    }
  }

  if (is_linux) {
    tests += [
      "//chromecast/crash:cast_crash_unittests",
      "//sandbox/linux:sandbox_linux_unittests",
    ]
  }

  if (is_linux || is_fuchsia) {
    tests += [
      "//chromecast/media/cma/backend:cast_audio_backend_unittests",
      "//chromecast/media/cma/backend:cast_av_sync_backend_unittests",
    ]
  }

  if (!is_android) {
    tests += [
      ":cast_shell_browsertests",
      ":cast_shell_unittests",
      "//ipc:ipc_tests",
      "//url:url_unittests",
    ]

    if (!is_fuchsia) {
      tests += [ "//jingle:jingle_unittests" ]
    }

    cast_media_unittests_filter = {
      test_name = "cast_media_unittests"

      # --test-launcher-jobs=1 => so internal code can bind to port
      args = [ "--test-launcher-jobs=1" ]
    }
    filters += [ cast_media_unittests_filter ]

    cast_shell_browsertests_filter = {
      test_name = "cast_shell_browsertests"

      # --enable-local-file-accesses => to load sample media files
      # --test-launcher-jobs=1 => so internal code can bind to port
      args = [
        "--no-sandbox",
        "--enable-local-file-accesses",
        "--test-launcher-jobs=1",
      ]
      if (!is_cast_desktop_build) {
        args += [ "--use-gpu-in-tests" ]

        # TODO(derekjchow): Make these tests pass on Chromecast devices.
        #    Once all of the CastMediaBlockerTest.* have been un-DISABLEd and
        #    are running successfully, revisit these tests and see if they pass
        #    on devices. (crbug/665118, internal b/32023194)
        gtest_excludes = [
          "CastMediaBlockerBrowserTest.Video_BlockUnblock",
          "CastMediaBlockerBrowserTest.Audio_BlockUnblock",
        ]

        # TODO(mbjorge): The ReusedRenderer test is failing on v1 and cast audio
        # devices. Temporarily disable them as part of an effort_to re-green
        # the unittests. Current failures (2017-03-15) are being disabled to get
        # back to a green state. Re-enable once the tests have been fixed.
        # Limitations in the build mean this unfortunately is getting disabled
        # across all devices, even though it is only failing on some.
        # b/36238710, b/36239051, hotlist/461351
        gtest_excludes += [ "RendererPrelauncherTest.ReusedRenderer" ]
      }

      if (!is_cast_desktop_build && !is_cast_audio_only && !enable_assistant) {
        # TODO(mbjorge): The VideoPlaybackMp4 test is failing on v1 devices.
        # Temporarily disable it as part of an effort to re-green the unittests.
        # Re-enable once the tests have been fixed. Limitations in the filter
        # system mean this is getting temporarily disabled on all video devices,
        # though it is only failing on v1.
        # b/36723698, hotlist/461351
        gtest_excludes += [ "CastNavigationBrowserTest.VideoPlaybackMp4" ]
      }

      # TODO(mbjorge): Temporarily disable AudioPlaybackWavPcm because it is
      # failing on device. As part of an effort to re-green the unittests,
      # current (2017-03-15) failures are being disabled to get back to a
      # green state. Re-enable once the tests have been fixed.
      # b/36239152, hotlist/461351
      if (enable_assistant && !is_cast_desktop_build) {
        gtest_excludes += [ "CastNavigationBrowserTest.AudioPlaybackWavPcm" ]
      }
    }
    filters += [ cast_shell_browsertests_filter ]

    ipc_tests_filter = {
      test_name = "ipc_tests"

      # --test-launcher-jobs=1 => so internal code can bind to port
      args = [ "--test-launcher-jobs=1" ]
    }
    filters += [ ipc_tests_filter ]

    url_unittests_filter = {
      test_name = "url_unittests"

      if (target_os == "linux" && !is_cast_desktop_build) {
        # DoAppendUTF8Invalid fails because of dcheck_always_on flag in Eng builds
        gtest_excludes = [ "URLCanonTest.DoAppendUTF8Invalid" ]
      }
    }
    filters += [ url_unittests_filter ]
  }

  base_unittests_filter = {
    test_name = "base_unittests"
    gtest_excludes = []
    if (target_os == "linux") {
      if (is_cast_desktop_build) {
        # Disable PartitionAllocDeathTest.Repeated*ReturnNullDirect (b/67975693)
        gtest_excludes += [
          "PartitionAllocDeathTest.RepeatedAllocReturnNullDirect",
          "PartitionAllocDeathTest.RepeatedReallocReturnNullDirect",
        ]
      } else {
        # Disable ProcessMetricsTest.GetNumberOfThreads (b/15610509)
        # Disable ProcessUtilTest.* (need to define OS_ANDROID)
        # Disable StackContainer.BufferAlignment (don't support 16-byte alignment)
        # Disable SystemMetrics2Test.GetSystemMemoryInfo (buffers>0 can't be guaranteed)
        # Disable PostTasksViaTaskRunner/* to green up devices (b/62246873)
        # Disable WorkerDetaches to green up devices (b/62246873)
        gtest_excludes += [
          "ProcessMetricsTest.GetNumberOfThreads",
          "ProcessUtilTest.*",
          "StackContainer.BufferAlignment",
          "SystemMetrics2Test.GetSystemMemoryInfo",
          "OneTraitsExecutionModePair/TaskSchedulerImplTest.PostTasksViaTaskRunner/*",
          "TaskSchedulerWorkerTest.WorkerDetaches",
        ]
      }

      if (is_cast_audio_only) {
        # Also disable TimeFormattingTest on audio-only builds, since we don't
        # include the necessary info in icudtl.dat.
        gtest_excludes += [ "TimeFormattingTest.*" ]
      }
    }
  }
  filters += [ base_unittests_filter ]

  cc_unittests_filter = {
    test_name = "cc_unittests"
    if (!is_cast_desktop_build) {
      #Disable ToColorSpace/ColorTransformPixelTest*  (b/64346790)
      #Disable ImageBackgroundFilter* (b/64346875)
      #Disable LayerTreeHostTilesTestPartialInvalidation* (b/65844132)
      gtest_excludes = [
        "ToColorSpace/ColorTransformPixelTest.*",
        "ImageBackgroundFilter.*",
        "LayerTreeHostTilesTestPartialInvalidation.*",
      ]
    }
  }
  filters += [ cc_unittests_filter ]

  content_unittests_filter = {
    test_name = "content_unittests"

    # IsSupportedVideoConfig_VP9TransferFunctions fails on all cast builds since
    # the cast IsSupporedVideoConfigs ignore the transfer function parameter.
    # (b/36984215).
    gtest_excludes = [ "*.IsSupportedVideoConfig_VP9TransferFunctions" ]
    if (target_os == "linux" && !is_cast_desktop_build) {
      # DesktopCaptureDeviceTest.*: No capture device on Eureka
      # Disable PepperGamepadHostTest.WaitForReply (pepper not supported on Eureka)
      # Disable RenderWidgetHostTest.Background because we disable the
      # blacklist to enable WebGL (b/16142554)
      gtest_excludes += [
        "DOMStorageDatabaseTest.TestCanOpenAndReadWebCoreDatabase",
        "DesktopCaptureDeviceTest.Capture",
        "GamepadProviderTest.PollingAccess",
        "PepperGamepadHostTest.WaitForReply",
        "RenderWidgetHostTest.Background",
      ]
    }
    if (is_cast_audio_only) {
      # No way to display URL's on audio only cast devices.
      gtest_excludes += [ "NavigationEntryTest.NavigationEntryURLs" ]
    }
    if (enable_assistant && !is_cast_desktop_build) {
      # Temporarily disable InvalidUUID and DefaultConstructor on assistant
      # device builds. Cause of failure is unclear, but it's highly likely it's
      # related to them being DEATH tests. These were passing until the
      # is_official_build flag was enabled. These tests are considered
      # non-critical in this context. (b/62469368)
      gtest_excludes += [
        "BluetoothBlocklistTest.InvalidUUID",
        "WebBluetoothDeviceIdTest.DefaultConstructor",
      ]
    }
  }
  filters += [ content_unittests_filter ]

  media_unittests_filter = {
    test_name = "media_unittests"
    if (target_os == "linux" && !is_cast_desktop_build) {
      # Disable VP9 related tests (b/18593324)
      #   PipelineIntegrationTest.BasicPlayback_MediaSource_VP9_WebM
      #   PipelineIntegrationTest.BasicPlayback_VideoOnly_VP9_WebM
      #   PipelineIntegrationTest.BasicPlayback_VP9*
      #   PipelineIntegrationTest.P444_VP9_WebM
      # Disable VP8A tests (b/18593324)
      #   PipelineIntegrationTest.BasicPlayback_VP8A*
      # Disable OpusAudioDecoderTest/AudioDecoderTest.ProduceAudioSamples/0 (unit
      # test fails when Opus decoder uses fixed-point)
      # Due to b/16456550, disable the following four test cases:
      #   AudioOutputControllerTest.PlayDivertSwitchDeviceRevertClose
      #   AudioOutputControllerTest.PlaySwitchDeviceClose
      #   AudioStreamHandlerTest.Play
      #   SoundsManagerTest.Play
      # Disable AudioStreamHandlerTest.ConsecutivePlayRequests (b/16539293)
      gtest_excludes = [
        "AudioOutputControllerTest.PlayDivertSwitchDeviceRevertClose",
        "AudioOutputControllerTest.PlaySwitchDeviceClose",
        "AudioStreamHandlerTest.Play",
        "AudioStreamHandlerTest.ConsecutivePlayRequests",
        "PipelineIntegrationTest.BasicPlayback_MediaSource_VP9_WebM",
        "PipelineIntegrationTest.BasicPlayback_VideoOnly_VP9_WebM",
        "PipelineIntegrationTest.BasicPlayback_VP9*",
        "PipelineIntegrationTest.P444_VP9_WebM",
        "PipelineIntegrationTest.BasicPlayback_VP8A*",
        "OpusAudioDecoderTest/AudioDecoderTest.ProduceAudioSamples/0",
        "SoundsManagerTest.Play",
      ]
    } else if (target_os == "android" || is_cast_desktop_build) {
      # Disable PipelineIntegrationTest.BasicPlayback_MediaSource_VP9_WebM (not supported)
      gtest_excludes =
          [ "PipelineIntegrationTest.BasicPlayback_MediaSource_VP9_WebM" ]
    }
  }
  filters += [ media_unittests_filter ]

  net_unittests_filter = {
    test_name = "net_unittests"
    if (using_sanitizer) {
      # TODO(mbjorge): net_unittests do not complete when run with sanitizers,
      # (in particular, TSAN and UBSAN), resulting in build machines getting stuck
      # for many hours. Disable them for now, since these are getting run on
      # Chromium bots anyway. (internal b/31279943)
      gtest_excludes = [ "*" ]
    } else if (target_os == "linux" && !is_cast_desktop_build) {
      # Run net_unittests first to avoid random failures due to slow python startup
      # URLRequestTestHTTP.GetTest_ManyCookies takes roughly 55s to run. Increase
      # timeout to 90s from 45s to allow it to pass (b/19821476)
      # PacFileFetcherImplTest.HttpMimeType is flaking (b/19848784)
      # Running a batch of net_unittests has high overhead. Run tests in batches of 50 to reduce number of batches (b/23156294).
      gtest_excludes = [ "PacFileFetcherImplTest.HttpMimeType" ]
      args = [
        "--test-launcher-timeout=90000",
        "--test-launcher-batch-limit=50",
      ]
    } else if (is_cast_desktop_build || target_os == "android") {
      # URLRequestTestHTTP.GetTest_ManyCookies takes roughly 55s to run. Increase
      # timeout to 90s from 45s to allow it to pass (b/19821476) (b/29415636).
      # CTLogVerifierTest.VerifiesValidConsistencyProofsFromReferenceGenerator
      # times out occasionally, paricularly on the CQ bots; disable to reduce
      # CQ flakiness (crbug/598406) (b/29415636).
      # Running a batch of net_unittests has high overhead, so
      # run tests in batches of 25 to reduce number of batches (b/23156294).
      gtest_excludes = [ "CTLogVerifierTest.VerifiesValidConsistencyProofsFromReferenceGenerator" ]
      args = [
        "--test-launcher-timeout=90000",
        "--test-launcher-batch-limit=25",
      ]
    }
  }
  filters += [ net_unittests_filter ]
}

# Creates the build and run lists for all test targets.
cast_test_group_list("cast_test_lists") {
  build_list_path = "$root_out_dir/tests/build_test_list.txt"
  runtime_deps_path = "$root_out_dir/tests/runtime_deps.json"
  run_list_path = "$root_out_dir/tests/run_test_list.txt"

  additional_options = [
    "--ozone-platform=headless --test-launcher-bot-mode $cast_test_extra_flags",
  ]

  test_groups = [ ":cast_tests" ]

  if (chromecast_branding != "public") {
    test_groups += [ "//chromecast/internal:internal_cast_tests" ]
  }
}

if (is_android) {
  cast_test_group("cast_junit_tests") {
    test_type = "junit"
    tests = [
      "//base:base_junit_tests",
      "//chromecast/base:cast_base_junit_tests",
      "//chromecast/browser/android:cast_shell_junit_tests",
      "//content/public/android:content_junit_tests",
      "//net/android:net_junit_tests",
      "//testing/android/junit:junit_unit_tests",
      "//ui/android:ui_junit_tests",
    ]
  }

  cast_test_group_list("cast_junit_test_lists") {
    test_type = "junit"
    build_list_path = "$root_out_dir/junit/build_junit_test_list.txt"
    runtime_deps_path = "$root_out_dir/junit/runtime_deps.json"
    run_list_path = "$root_out_dir/junit/run_junit_test_list.txt"
    test_groups = [ ":cast_junit_tests" ]
    if (chromecast_branding != "public") {
      test_groups += [ "//chromecast/internal:internal_cast_junit_tests" ]
    }
  }
}

test("cast_shell_unittests") {
  deps = [
    ":cast_shell_lib",
    "//chromecast/app:test_support",
    "//chromecast/app:unittests",
    "//chromecast/browser:unittests",
    "//ui/gl:test_support",
  ]
}

test("cast_shell_browsertests") {
  deps = [
    ":cast_shell_lib",
    "//chromecast/app:test_support",
    "//chromecast/browser:browsertests",
  ]

  data_deps = [
    ":chromecast_locales_pak",
  ]
}

group("cast_shell_lib") {
  data_deps = [
    ":cast_shell_pak",
  ]

  deps = [
    "//chromecast/app",
    "//chromecast/browser",
    "//chromecast/common",
    "//chromecast/renderer",
  ]

  if (chromecast_branding != "public") {
    deps += [ "//chromecast/internal/shell" ]
  }
}

cast_executable("cast_shell") {
  sources = [
    "app/cast_main.cc",
  ]

  deps = [
    ":cast_shell_lib",
    ":chromecast_locales_pak",
    "//chromecast/app",
    "//content/public/app:both",
  ]
}

if (is_fuchsia) {
  fuchsia_package("cast_shell_pkg") {
    binary = ":cast_shell"
    package_name_override = "cast_shell"

    if (chromecast_branding != "public") {
      deps = [
        "//chromecast/internal:fuchsia_internal_data_deps",
      ]
    }
  }

  fuchsia_package_runner("cast_shell_fuchsia") {
    package = ":cast_shell_pkg"
    package_name_override = "cast_shell"
  }
}

repack("cast_shell_pak") {
  sources = [
    "$root_gen_dir/chromecast/app/shell_resources.pak",
    "$root_gen_dir/chromecast/browser/cast_browser_resources.pak",
    "$root_gen_dir/content/app/resources/content_resources_100_percent.pak",
    "$root_gen_dir/content/app/strings/content_strings_en-US.pak",
    "$root_gen_dir/content/content_resources.pak",
    "$root_gen_dir/mojo/public/js/mojo_bindings_resources.pak",
    "$root_gen_dir/net/net_resources.pak",
    "$root_gen_dir/third_party/blink/public/resources/blink_resources.pak",
    "$root_gen_dir/third_party/blink/public/resources/blink_scaled_resources_100_percent.pak",
    "$root_gen_dir/ui/resources/ui_resources_100_percent.pak",
    "$root_gen_dir/ui/resources/webui_resources.pak",
    "$root_gen_dir/ui/strings/app_locale_settings_en-US.pak",
    "$root_gen_dir/ui/strings/ui_strings_en-US.pak",
  ]

  output = "$root_out_dir/assets/cast_shell.pak"

  deps = [
    "//chromecast/app:resources",
    "//chromecast/browser:resources",
    "//content:resources",
    "//content/app/resources",
    "//content/app/strings",
    "//mojo/public/js:resources",
    "//net:net_resources",
    "//third_party/blink/public:resources",
    "//third_party/blink/public:scaled_resources_100_percent",
    "//ui/resources",
    "//ui/strings",
  ]

  if (enable_chromecast_extensions) {
    sources += [
      "$root_gen_dir/chromecast/renderer/extensions_renderer_resources.pak",
      "$root_gen_dir/extensions/extensions_renderer_resources.pak",
      "$root_gen_dir/extensions/extensions_resources.pak",
      "$root_gen_dir/extensions/shell/app_shell_resources.pak",
    ]
    deps += [
      "//chromecast/renderer:extensions_resources",
      "//extensions:extensions_resources",
      "//extensions/shell:resources",
    ]
  }

  if (chromecast_branding != "public") {
    sources += [ "$root_gen_dir/chromecast/internal/cast_shell_internal.pak" ]

    deps += [ "//chromecast/internal:cast_shell_internal_pak" ]
  }
}

# Intermediate targets that repack grit resources by locale. For each locale
# in |cast_locales| (see //chromecast/chromecast.gni), all resources
# are packed into a single .pak file in an output directory. These targets
# should not be depended on directly; depend on ":chromecast_locales_pak"
# instead.
foreach(locale, cast_locales) {
  repack("_cast_repack_${locale}") {
    visibility = [ ":chromecast_locales_pak" ]
    output = "$root_out_dir/chromecast_locales/${locale}.pak"
    sources = [
      "$root_gen_dir/chromecast/app/chromecast_settings_${locale}.pak",
    ]
    deps = [
      "//chromecast/app:chromecast_settings",
    ]

    if (chromecast_branding != "public") {
      sources += [
        "$root_gen_dir/chromecast/internal/webui/app_strings_${locale}.pak",
      ]
      deps += [ "//chromecast/internal/webui:chromecast_app_strings" ]

      if (enable_chromecast_webui) {
        sources += [ "$root_gen_dir/chromecast/internal/webui/webui_localized_${locale}.pak" ]
        deps += [ "//chromecast/internal/webui:chromecast_webui_localized" ]
      }
    }
  }
}

# A meta-target which repacks resources by locale.
group("chromecast_locales_pak") {
  deps = []
  foreach(locale, cast_locales) {
    deps += [ ":_cast_repack_${locale}" ]
  }
}

buildflag_header("chromecast_buildflags") {
  header = "chromecast_buildflags.h"
  flags = [
    "ENABLE_ASSISTANT=$enable_assistant",
    "ENABLE_VOLUME_TABLES_ACCESS=$enable_volume_tables_access",
    "IS_ANDROID_THINGS=$is_android_things",
    "IS_CAST_AUDIO_ONLY=$is_cast_audio_only",
    "IS_CAST_DESKTOP_BUILD=$is_cast_desktop_build",
    "IS_CAST_USING_CMA_BACKEND=$is_cast_using_cma_backend",
    "SUPPORTS_MULTIZONE=$supports_multizone",
    "ENABLE_HEADLESS_MUSIC_MODE=$enable_headless_music_mode",
    "ENABLE_CHROMECAST_EXTENSIONS=$enable_chromecast_extensions",
    "ENABLE_CAST_FRAGMENT=$enable_cast_fragment",
    "IS_ANDROID_THINGS_NON_PUBLIC=$is_android_things_non_public",
  ]
}

if (is_android) {
  generate_jni_registration("cast_shell_jni_registration") {
    target = ":cast_shell_apk"
    output = "$root_gen_dir/chromecast/android/${target_name}.h"
    exception_files = jni_exception_files
  }

  android_assets("cast_shell_apk_assets") {
    assert(v8_use_external_startup_data)

    sources = [
      "$root_out_dir/assets/cast_shell.pak",
    ]

    deps = [
      ":cast_shell_apk_locale_assets",
      ":cast_shell_pak",
      "//third_party/icu:icu_assets",
      "//v8:v8_external_startup_data_assets",
    ]
    disable_compression = true
  }

  android_assets("cast_shell_apk_locale_assets") {
    renaming_sources = []
    renaming_destinations = []

    foreach(locale, cast_locales) {
      renaming_sources += [ "$root_out_dir/chromecast_locales/${locale}.pak" ]
      renaming_destinations += [ "stored-locales/${locale}.pak" ]
    }

    deps = [
      ":chromecast_locales_pak",
    ]

    treat_as_locale_paks = true
    disable_compression = true
  }

  android_apk("cast_shell_apk") {
    apk_name = "CastShell"
    android_manifest = "$root_gen_dir/cast_shell_manifest/AndroidManifest.xml"
    android_manifest_dep = "//chromecast/browser/android:cast_shell_manifest"

    shared_libraries = [ "//chromecast/android:libcast_shell_android" ]

    deps = [
      ":cast_shell_apk_assets",
      "//base:base_java",
      "//chromecast/android:libcast_shell_android",
      "//chromecast/browser/android:cast_shell_java",
    ]

    command_line_flags_file = "castshell-command-line"
  }
}
