# Copyright 2013 The PDFium Authors
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.

import("//build/config/features.gni")
import("//build/config/freetype/freetype.gni")
import("//build/config/ui.gni")
import("//testing/test.gni")
import("//third_party/skia/gn/codec.gni")
import("//third_party/skia/gn/shared_sources.gni")
import("//third_party/skia/modules/skcms/skcms.gni")
import("../pdfium.gni")
import("features.gni")

if (current_cpu == "arm") {
  import("//build/config/arm.gni")
}
if (current_cpu == "mipsel" || current_cpu == "mips64el") {
  import("//build/config/mips.gni")
}

if (pdf_enable_fontations || pdf_enable_rust_png) {
  import("//build/rust/rust_static_library.gni")
}

skia_use_ganesh_backend = !is_ios
skia_support_pdf = false

if (pdf_enable_fontations) {
  source_set("path_bridge") {
    sources = skia_fontations_path_bridge_sources
  }

  rust_static_library("bridge_rust_side") {
    allow_unsafe = true
    crate_root = skia_fontations_bridge_root
    sources = skia_ports_fontations_bridge_rust_side_sources
    cxx_bindings = [ skia_fontations_bridge_root ]
    deps = [
      ":path_bridge",
      "//third_party/rust/font_types/v0_12:lib",
      "//third_party/rust/read_fonts/v0_41:lib",
      "//third_party/rust/skrifa/v0_44:lib",
    ]
    configs -= [ "//build/config/compiler:chromium_code" ]
    configs += [
      ":skia_config",
      "//build/config/compiler:no_chromium_code",
    ]
  }
}

if (pdf_enable_rust_bmp || pdf_enable_rust_png) {
  # TODO(https://crbug.com/448663461): Deduplicate `rust_png_ffi` and
  # `rust_png_ffi_cpp` target definitions (the exact same target definitions
  # are present in Chromium's //skia/BUILD.gn` and here in PDFium's
  # `//skia/BUILD.gn`).

  rust_static_library("rust_common_ffi") {
    visibility = [ ":*" ]
    crate_name = "skia_rust_common"
    allow_unsafe = true  # For FFI
    crate_root = skia_rust_common_ffi_crate_root
    sources = skia_rust_common_ffi_rs_srcs
    cxx_bindings = skia_rust_common_ffi_cxx_bridge_srcs
    public_deps = [ ":rust_common_ffi_cpp" ]
    configs -= [ "//build/config/compiler:chromium_code" ]
    configs += [
      ":skia_config",
      "//build/config/compiler:no_chromium_code",
    ]
  }

  source_set("rust_common_ffi_cpp") {
    visibility = [ ":*" ]
    sources = skia_rust_common_ffi_cpp_srcs
    public = skia_rust_common_ffi_cpp_hdrs
    public_deps = [ "//build/rust:cxx_cppdeps" ]
    configs -= [ "//build/config/compiler:chromium_code" ]
    configs += [
      ":skia_config",
      "//build/config/compiler:no_chromium_code",
    ]

    # This uses Skia files, but can't depend on :skia w/o introducing a cycle
    check_includes = false
  }

  if (pdf_enable_rust_bmp) {
    rust_static_library("rust_bmp_ffi") {
      visibility = [ ":*" ]
      allow_unsafe = true  # For FFI
      crate_root = skia_codec_rust_bmp_ffi_crate_root
      sources = skia_codec_rust_bmp_ffi_rs_srcs
      cxx_bindings = skia_codec_rust_bmp_ffi_cxx_bridge_srcs
      public_deps = [ ":rust_bmp_ffi_cpp" ]
      deps = [
        ":rust_common_ffi",
        "//third_party/rust/image/v0_25:lib",
      ]
      edition = "2021"
      configs -= [ "//build/config/compiler:chromium_code" ]
      configs += [
        ":skia_config",
        "//build/config/compiler:no_chromium_code",
      ]
    }

    source_set("rust_bmp_ffi_cpp") {
      visibility = [ ":*" ]
      configs -= [ "//build/config/compiler:chromium_code" ]
      configs += [
        ":skia_config",
        "//build/config/compiler:no_chromium_code",
      ]
    }
  }

  if (pdf_enable_rust_png) {
    rust_static_library("rust_png_ffi") {
      visibility = [ ":*" ]
      allow_unsafe = true  # For FFI
      crate_root = skia_codec_rust_png_ffi_crate_root
      sources = skia_codec_rust_png_ffi_rs_srcs
      cxx_bindings = skia_codec_rust_png_ffi_cxx_bridge_srcs
      public_deps = [ ":rust_png_ffi_cpp" ]
      deps = [
        ":rust_common_ffi",
        "//third_party/rust/png/v0_18:lib",
      ]
      edition = "2021"
      configs -= [ "//build/config/compiler:chromium_code" ]
      configs += [
        ":skia_config",
        "//build/config/compiler:no_chromium_code",
      ]
    }

    source_set("rust_png_ffi_cpp") {
      visibility = [ ":*" ]
      public = skia_codec_rust_png_ffi_cpp_hdrs
      configs -= [ "//build/config/compiler:chromium_code" ]
      configs += [
        ":skia_config",
        "//build/config/compiler:no_chromium_code",
      ]
    }
  }
}

# External-facing config for dependent code.
config("skia_config") {
  include_dirs = [ "//third_party/skia" ]

  defines = [
    "SK_USER_CONFIG_HEADER=\"../../skia/config/SkPdfiumUserConfig.h\"",
    "SK_DISABLE_LEGACY_INIT_DECODERS",
    "SK_DISABLE_LEGACY_PNG_WRITEBUFFER",
    "SK_DISABLE_LEGACY_XPS_FACTORIES",
    "SK_ENABLE_LEGACY_SHADERCONTEXT",
  ]

  if (is_win) {
    defines += [ "SK_FREETYPE_MINIMUM_RUNTIME_VERSION=(((FREETYPE_MAJOR) * 0x01000000) | ((FREETYPE_MINOR) * 0x00010000) | ((FREETYPE_PATCH) * 0x00000100))" ]
  }

  if (is_component_build) {
    defines += [
      "SKIA_DLL",
      "GR_GL_IGNORE_ES3_MSAA=0",
    ]
  }

  if (skia_use_ganesh_backend) {
    defines += [ "SK_GANESH" ]
  }

  if (skia_use_gl) {
    defines += [ "SK_GL" ]
  }

  if (is_android) {
    defines += [
      "SK_BUILD_FOR_ANDROID",
      "USE_CHROMIUM_SKIA",
    ]
  }

  if (is_mac) {
    defines += [ "SK_BUILD_FOR_MAC" ]
  }

  if (is_win) {
    defines += [ "GR_GL_FUNCTION_TYPE=__stdcall" ]
  }

  if (pdf_enable_fontations || pdf_enable_rust_png) {
    include_dirs += [ "$root_gen_dir/third_party/skia" ]
  }

  if (pdf_enable_rust_bmp) {
    defines += [ "SK_CODEC_DECODES_BMP_WITH_RUST" ]
  }

  if (pdf_enable_rust_jpeg) {
    defines += [
      "SK_CODEC_DECODES_JPEG",
      "SK_CODEC_DECODES_JPEG_WITH_RUST",
    ]
  }

  if (pdf_enable_rust_png) {
    defines += [
      "SK_CODEC_DECODES_PNG",
      "SK_CODEC_DECODES_PNG_WITH_RUST",
      "SK_CODEC_ENCODES_PNG",
      "SK_CODEC_ENCODES_PNG_WITH_RUST",
    ]
  }
}

# Internal-facing config for Skia library code.
config("skia_library_config") {
  # Turn on SK_API to export Skia's public API
  defines = [
    "IS_SKIA_IMPL=1",
    "SKIA_IMPLEMENTATION=1",
  ]

  if (use_blink && !use_system_freetype) {
    defines += [ "SK_FREETYPE_MINIMUM_RUNTIME_VERSION=(((FREETYPE_MAJOR) * 0x01000000) | ((FREETYPE_MINOR) * 0x00010000) | ((FREETYPE_PATCH) * 0x00000100))" ]
  }
  if (use_blink) {
    defines += [ "SK_TYPEFACE_FACTORY_FREETYPE" ]
  }
  if (is_win) {
    defines += [ "SK_TYPEFACE_FACTORY_DIRECTWRITE" ]
  }
  if (is_apple) {
    defines += [ "SK_TYPEFACE_FACTORY_CORETEXT" ]
  }

  if (current_cpu == "arm") {
    defines += [ "SK_ARM_HAS_NEON" ]
  }

  # Settings for text blitting, chosen to approximate the system browser.
  if (is_linux || is_chromeos) {
    defines += [
      "SK_GAMMA_EXPONENT=1.2",
      "SK_GAMMA_CONTRAST=0.2",
    ]
  } else if (is_android) {
    defines += [
      "SK_GAMMA_APPLY_TO_A8",
      "SK_GAMMA_EXPONENT=1.4",
      "SK_GAMMA_CONTRAST=0.0",
    ]
  } else if (is_win) {
    defines += [
      "SK_GAMMA_SRGB",
      "SK_GAMMA_CONTRAST=0.5",
    ]
  } else if (is_mac) {
    defines += [
      "SK_GAMMA_SRGB",
      "SK_GAMMA_CONTRAST=0.0",
    ]
  }

  if (is_android) {
    defines += [
      # Android devices are typically more memory constrained, so default to a
      # smaller glyph cache (it may be overriden at runtime when the renderer
      # starts up, depending on the actual device memory).
      "SK_DEFAULT_FONT_CACHE_LIMIT=1048576",  # 1024 * 1024
    ]
  } else {
    defines += [ "SK_DEFAULT_FONT_CACHE_LIMIT=20971520" ]  # 20 * 1024 * 1024
  }

  if (is_win) {
    defines += [
      # On windows, GDI handles are a scarse system-wide resource so we have to
      # keep the glyph cache, which holds up to 4 GDI handles per entry, to a
      # fairly small size. http://crbug.com/314387
      "SK_DEFAULT_FONT_CACHE_COUNT_LIMIT=256",
    ]
  }
}

component("skia") {
  deps = []

  sources = [
    # PDFium sources.
    "config/SkPdfiumUserConfig.h",
    "ext/google_logging.cc",
  ]

  # The skia sources values are relative to the skia_dir, so we need to rebase.
  sources += skia_core_public
  sources += skia_pathops_sources
  sources += skia_sksl_pipeline_sources
  sources += skia_sksl_codegen_sources
  sources += skia_sksl_core_sources
  sources += skia_sksl_core_module_sources
  sources += skia_utils_private
  sources += skia_xps_sources

  if (pdf_enable_rust_bmp) {
    sources += skia_codec_rust_bmp
    sources += skia_codec_rust_bmp_public
    deps += [
      ":rust_bmp_ffi",
      ":rust_common_ffi",
    ]
  } else {
    sources += skia_codec_decode_bmp
  }

  sources += skia_ports_sources
  sources += [
    "//third_party/skia/src/sfnt/SkOTTable_name.cpp",
    "//third_party/skia/src/sfnt/SkOTUtils.cpp",

    #pdfium
    "//third_party/skia/src/ports/SkDiscardableMemory_none.cpp",
    "//third_party/skia/src/ports/SkMemory_malloc.cpp",
  ]

  # This and skia_opts are really the same conceptual target so share headers.
  allow_circular_includes_from = [ ":skia_opts" ]

  # GPU
  if (skia_use_ganesh_backend) {
    sources += skia_gpu_public
    sources += skia_ganesh_private
    sources += skia_null_gpu_sources
    sources += skia_shared_gpu_sources
    if (skia_use_gl) {
      sources += skia_gpu_gl_public
      sources += skia_gpu_gl_private
    }
  }

  # Remove unused util files include in utils.gni
  sources -= [
    "//third_party/skia/src/utils/SkCamera.cpp",
    "//third_party/skia/src/utils/SkParsePath.cpp",
  ]

  if (is_win) {
    libs = [ "fontsub.lib" ]
  }

  # Select Skia ports.

  # FreeType is needed everywhere (except on iOS), on Linux and Android as main
  # font backend, on Windows and Mac as fallback backend for Variations.
  if (!is_ios) {
    sources += skia_ports_freetype_sources
  }

  if (is_win) {
    # See SK_TYPEFACE_FACTORY_DIRECTWRITE
    sources += skia_ports_windows_fonts_sources
    sources += skia_ports_windows_sources
  } else {
    sources += [ "//third_party/skia/src/ports/SkOSFile_posix.cpp" ]
  }

  frameworks = []
  if (is_apple) {
    # See SK_TYPEFACE_FACTORY_CORETEXT
    sources += skia_ports_fontmgr_coretext_sources
    frameworks += [
      "CoreFoundation.framework",
      "CoreGraphics.framework",
      "CoreText.framework",
    ]
  }

  if (is_linux || is_chromeos) {
    sources += skia_ports_fci_sources
    sources += skia_ports_fontmgr_custom_sources
    sources += skia_ports_fontmgr_empty_sources
    sources += skia_ports_typeface_proxy_sources
  }

  if (is_android) {
    # Unlike Chromium, standalone PDFium on Linux and Chrome OS does not
    # require these files, since PDFium does not perform Android emulation.
    # Note that this requires expat.
    sources += skia_ports_fontmgr_android_sources
  }

  if (is_win) {
    sources += [ "//third_party/skia/src/ports/SkLog_win.cpp" ]
  } else if (is_android) {
    sources += [ "//third_party/skia/src/ports/SkLog_android.cpp" ]
  } else {
    sources += [ "//third_party/skia/src/ports/SkLog_stdio.cpp" ]
  }

  if (is_win || (is_apple && use_blink)) {
    # Add the FreeType custom font manager as a fallback backend for variable
    # fonts.
    sources += skia_ports_fontmgr_custom_sources
    sources += skia_ports_fontmgr_empty_sources
  }

  if (pdf_enable_fontations) {
    sources += skia_ports_typeface_fontations_sources
    sources += skia_ports_fontmgr_fontations_sources

    # Fontations Rust/C++ bridge interfaces.
    deps += [
      ":bridge_rust_side",
      ":path_bridge",
    ]
  }

  if (is_clang) {
    # Skia won't compile with some of the more strict clang warnings.
    # e.g. it does:
    #  SkASSERT(!"sk_out_of_memory");
    configs -= [ "//build/config/clang:extra_warnings" ]
  }

  configs -= [ "//build/config/compiler:chromium_code" ]
  configs += [
    ":skia_config",
    ":skia_library_config",
    "//build/config/compiler:no_chromium_code",
  ]
  public_configs = [ ":skia_config" ]

  deps += [
    ":skcms",
    ":skia_opts",
    "../third_party:zlib",
    "//:freetype_common",
  ]
  public_deps = [ ":skia_core_and_effects" ]

  if (is_linux || is_chromeos) {
    deps += [
      "//third_party:fontconfig",
      "//third_party/icu:icuuc",
    ]
  }

  if (is_android) {
    deps += [
      "//third_party/cpu_features:ndk_compat",
      "//third_party/expat",
    ]
  }

  if (is_android && !is_debug) {
    configs -= [ "//build/config/compiler:default_optimization" ]
    configs += [ "//build/config/compiler:optimize_max" ]
  }

  if (is_ios) {
    frameworks += [ "ImageIO.framework" ]
  }

  if (skia_support_pdf) {
    sources += skia_pdf_sources
  } else {
    sources += [ "//third_party/skia/src/pdf/SkDocument_PDF_None.cpp" ]
  }

  sources += skia_codec_png_base
  sources += skia_codec_public
  sources += skia_codec_shared
  sources += skia_encode_png_base
  sources += skia_encode_public
  sources += skia_encode_srcs
  sources += [
    "//third_party/skia/src/codec/SkJpegCodec.cpp",
    "//third_party/skia/src/codec/SkJpegDecoderMgr.cpp",
    "//third_party/skia/src/codec/SkJpegMetadataDecoderImpl.cpp",
    "//third_party/skia/src/codec/SkJpegMultiPicture.cpp",
    "//third_party/skia/src/codec/SkJpegSegmentScan.cpp",
    "//third_party/skia/src/codec/SkJpegSourceMgr.cpp",
    "//third_party/skia/src/codec/SkJpegUtility.cpp",
  ]

  if (pdf_enable_rust_png) {
    sources += skia_codec_rust_png
    sources += skia_codec_rust_png_public
    sources += skia_encode_rust_png_public
    sources += skia_encode_rust_png_srcs
    deps += [
      ":rust_common_ffi",
      ":rust_png_ffi",
    ]
  } else {
    sources += skia_codec_libpng_srcs
    sources += skia_encode_libpng_srcs
    sources += skia_encode_png_public
    deps += [ "../third_party:png" ]
  }
  deps += [ "../third_party:jpeg" ]
}

# Template for things that are logically part of :skia, but need to be split out
# so custom compile flags can be applied.
#
# These are all opted out of check_includes, due to (logically) being part of
# skia.
template("skia_source_set") {
  source_set(target_name) {
    forward_variables_from(invoker, "*")

    check_includes = false

    if (!is_debug) {
      configs -= [ "//build/config/compiler:default_optimization" ]
      configs += [ "//build/config/compiler:optimize_max" ]
    }

    configs -= [ "//build/config/compiler:chromium_code" ]
    configs += [
      ":skia_config",
      ":skia_library_config",
      "//build/config/compiler:no_chromium_code",
    ]
    public_configs = [ ":skia_config" ]
  }
}

skia_source_set("skia_core_and_effects") {
  defines = []
  sources = skia_core_sources
  sources += skia_effects_sources
  sources += skia_colorfilters_sources
  sources += skia_effects_imagefilter_sources

  visibility = [ ":skia" ]
}

# Bits that involve special vector-y hardware.
if (current_cpu == "x86" || current_cpu == "x64") {
  skia_source_set("skia_opts_hsw") {
    sources = skia_opts.hsw_sources
    if (!is_win) {
      cflags = [
        "-mavx2",
        "-mbmi",
        "-mbmi2",
        "-mf16c",
        "-mfma",
      ]
    }
    if (is_win) {
      cflags = [ "/arch:AVX2" ]
    }
    visibility = [ ":skia_opts" ]
  }
}

skia_source_set("skia_opts") {
  cflags = []
  defines = []

  if (current_cpu == "x86" || current_cpu == "x64") {
    deps = [ ":skia_opts_hsw" ]
  } else if (current_cpu == "arm") {
    # The assembly uses the frame pointer register (r7 in Thumb/r11 in
    # ARM), the compiler doesn't like that.
    cflags += [ "-fomit-frame-pointer" ]
  } else if (current_cpu == "arm64") {
    # Conditional and empty body needed to avoid assert below
  } else if (current_cpu == "mipsel" || current_cpu == "mips64el") {
    cflags += [ "-fomit-frame-pointer" ]
  } else {
    assert(false, "Unsupported target CPU " + current_cpu)
  }

  if (is_android && !is_debug) {
    configs -= [ "//build/config/compiler:default_optimization" ]
    configs += [ "//build/config/compiler:optimize_max" ]
  }

  visibility = [ ":skia" ]
}

if (current_cpu == "x64") {
  skia_source_set("skcms_TransformHsw") {
    sources = skcms_TransformHsw
    if (!is_win) {
      cflags = [
        "-w",
        "-march=haswell",
        "-std=c11",
      ]
    } else {
      cflags = [ "/arch:AVX2" ]
    }
    visibility = [ ":skcms" ]
  }
  skia_source_set("skcms_TransformSkx") {
    sources = skcms_TransformSkx
    if (!is_win) {
      cflags = [
        "-w",
        "-march=skylake-avx512",
        "-std=c11",
      ]
    } else {
      cflags = [ "/arch:AVX512" ]
    }
    visibility = [ ":skcms" ]
  }
} else {
  skia_source_set("skcms_TransformHsw") {
    sources = []
    visibility = [ ":skcms" ]
  }
  skia_source_set("skcms_TransformSkx") {
    sources = []
    visibility = [ ":skcms" ]
  }
}

source_set("skcms_TransformBaseline_and_public") {
  if (!is_win || is_clang) {
    cflags = [
      "-w",
      "-std=c11",
    ]
  } else {
    cflags = []
  }

  # LLVM automatically sets the equivalent of GCC's -mfp16-format=ieee on ARM
  # builds by default, while GCC itself does not. We need it to enable support
  # for half-precision floating point data types used by SKCMS on ARM.
  if ((is_linux || is_chromeos) && !is_clang && current_cpu == "arm") {
    cflags += [ "-mfp16-format=ieee" ]
  }

  sources = rebase_path(skcms_TransformBaseline + skcms_public,
                        ".",
                        "//third_party/skia/modules/skcms")
}

source_set("skcms") {
  deps = [
    ":skcms_TransformBaseline_and_public",
    ":skcms_TransformHsw",
    ":skcms_TransformSkx",
  ]
  public =
      rebase_path(skcms_public_headers, ".", "//third_party/skia/modules/skcms")
  include_dirs = [ "//third_party/skia/modules/skcms" ]
}
