/* SPDX-FileCopyrightText: 2008 Blender Authors
 *
 * SPDX-License-Identifier: GPL-2.0-or-later */

/** \file
 * \ingroup spfile
 */

#include <algorithm>
#include <cerrno>
#include <cstring>
#include <string>

#include <fmt/format.h>

#include "BLI_rect.h"
#include "DNA_space_enums.h"
#include "ED_asset_menu_utils.hh"
#include "MEM_guardedalloc.h"

#include "AS_asset_library.hh"
#include "AS_asset_representation.hh"
#include "AS_remote_library.hh"

#include "BLI_fileops.h"
#include "BLI_fileops_types.h"
#include "BLI_listbase.h"
#include "BLI_math_color.h"
#include "BLI_math_vector.h"
#include "BLI_path_utils.hh"
#include "BLI_string.h"
#include "BLI_string_utf8.h"
#include "BLI_utildefines.h"

#ifdef WIN32
#  include "BLI_winstuff.h"
#endif

#include "BIF_glutil.hh"

#include "BKE_blendfile.hh"
#include "BKE_context.hh"
#include "BKE_global.hh"
#include "BKE_icons.hh"
#include "BKE_preferences.h"
#include "BKE_report.hh"

#include "BLO_readfile.hh"

#include "BLT_date_string.hh"
#include "BLT_lang.hh"
#include "BLT_translation.hh"

#include "BLF_api.hh"

#include "IMB_imbuf.hh"
#include "IMB_imbuf_types.hh"
#include "IMB_metadata.hh"
#include "IMB_thumbs.hh"

#include "DNA_userdef_types.h"
#include "DNA_windowmanager_types.h"

#include "RNA_access.hh"
#include "RNA_prototypes.hh"

#include "ED_asset.hh"
#include "ED_fileselect.hh"
#include "ED_screen.hh"

#include "UI_interface.hh"
#include "UI_interface_c.hh"
#include "UI_interface_icons.hh"
#include "UI_interface_layout.hh"
#include "UI_resources.hh"
#include "UI_view2d.hh"

#include "WM_api.hh"
#include "WM_types.hh"

#include "GPU_immediate.hh"
#include "GPU_immediate_util.hh"
#include "GPU_state.hh"

#include "file_banner.hh"
#include "filelist.hh"

#include "file_intern.hh" /* own include */

namespace blender {

using RemoteLibraryLoadingStatus = asset_system::RemoteLibraryLoadingStatus;

void ED_file_path_button(bScreen *screen,
                         SpaceFile *sfile,
                         FileSelectParams *params,
                         ui::Block *block)
{
  ui::Button *but;

  BLI_assert_msg(params != nullptr,
                 "File select parameters not set. The caller is expected to check this.");
  BLI_assert(params == sfile->params || params == &sfile->asset_params->base_params);

  PointerRNA space_ptr = RNA_pointer_create_discrete(&screen->id, RNA_SpaceFileBrowser, sfile);
  PointerRNA params_rna_ptr = RNA_pointer_create_with_parent(
      space_ptr, RNA_FileSelectParams, params);

  /* callbacks for operator check functions */
  block_func_set(block, file_draw_check_cb, nullptr, nullptr);

  but = uiDefButR(block,
                  ui::ButtonType::Text,
                  "",
                  0,
                  0,
                  UI_UNIT_X * 10,
                  UI_UNIT_Y,
                  &params_rna_ptr,
                  "directory",
                  0,
                  0.0f,
                  float(FILE_MAX),
                  TIP_("File path"));
  button_retval_set(but, -1);

  BLI_assert(!button_flag_is_set(but, ui::BUT_UNDO));
  BLI_assert(!but_is_utf8(but));

  button_func_complete_set(but, autocomplete_directory, nullptr);
  button_funcN_set(but, file_directory_enter_handle, nullptr, but);

  /* TODO: directory editing is non-functional while a library is loaded
   * until this is properly supported just disable it. */
  if (sfile && sfile->files && filelist_lib(sfile->files)) {
    button_flag_enable(but, ui::BUT_DISABLED);
  }

  /* clear func */
  block_func_set(block, nullptr, nullptr, nullptr);
}

struct FileTooltipData {
  const SpaceFile *sfile;
  const FileDirEntry *file;
};

static FileTooltipData *file_tooltip_data_create(const SpaceFile *sfile, const FileDirEntry *file)
{
  FileTooltipData *data = MEM_new_uninitialized<FileTooltipData>(__func__);
  data->sfile = sfile;
  data->file = file;
  return data;
}

static void file_draw_tooltip_custom_func(bContext & /*C*/,
                                          ui::TooltipData &tip,
                                          ui::Button * /*but*/,
                                          void *argN)
{
  FileTooltipData *file_data = static_cast<FileTooltipData *>(argN);
  const SpaceFile *sfile = file_data->sfile;
  const FileList *files = sfile->files;
  const FileSelectParams *params = ED_fileselect_get_active_params(sfile);
  const FileDirEntry *file = file_data->file;

  BLI_assert_msg(!file->asset, "Asset tooltip should never be overridden here.");

  /* Check the FileDirEntry first to see if the preview is already loaded. */
  ImBuf *thumb = filelist_file_get_preview_image(file);

  /* Only free if it is loaded later. */
  bool free_imbuf = (thumb == nullptr);

  tooltip_text_field_add(tip, file->name, {}, ui::TIP_STYLE_HEADER, ui::TIP_LC_MAIN);
  tooltip_text_field_add(tip, {}, {}, ui::TIP_STYLE_SPACER, ui::TIP_LC_NORMAL);

  if (!(file->typeflag & FILE_TYPE_BLENDERLIB)) {

    char full_path[FILE_MAX_LIBEXTRA];
    filelist_file_get_full_path(files, file, full_path);

    if (params->recursion_level > 0) {
      char root[FILE_MAX];
      BLI_path_split_dir_part(full_path, root, FILE_MAX);
      tooltip_text_field_add(tip, root, {}, ui::TIP_STYLE_NORMAL, ui::TIP_LC_NORMAL);
    }

    if (file->redirection_path) {
      tooltip_text_field_add(
          tip,
          fmt::format(fmt::runtime(TIP_("Link target: {}")), file->redirection_path),
          {},
          ui::TIP_STYLE_NORMAL,
          ui::TIP_LC_NORMAL);
    }
    if (file->attributes & FILE_ATTR_OFFLINE) {
      tooltip_text_field_add(
          tip, TIP_("This file is offline"), {}, ui::TIP_STYLE_NORMAL, ui::TIP_LC_ALERT);
    }
    if (file->attributes & FILE_ATTR_READONLY) {
      tooltip_text_field_add(
          tip, TIP_("This file is read-only"), {}, ui::TIP_STYLE_NORMAL, ui::TIP_LC_ALERT);
    }
    if (file->attributes & (FILE_ATTR_SYSTEM | FILE_ATTR_RESTRICTED)) {
      tooltip_text_field_add(tip,
                             TIP_("This is a restricted system file"),
                             {},
                             ui::TIP_STYLE_NORMAL,
                             ui::TIP_LC_ALERT);
    }

    if (file->typeflag & (FILE_TYPE_BLENDER | FILE_TYPE_BLENDER_BACKUP)) {
      char version_str[128] = {0};
      if (!thumb) {
        /* Load the thumbnail from cache if existing, but don't create if not. */
        thumb = IMB_thumb_read(full_path, THB_LARGE);
      }
      if (thumb) {
        /* Look for version in existing thumbnail if available. */
        IMB_metadata_get_field(
            thumb->metadata, "Thumb::Blender::Version", version_str, sizeof(version_str));
      }

      if (!version_str[0] && !(file->attributes & FILE_ATTR_OFFLINE)) {
        /* Load Blender version directly from the file. */
        short version = BLO_version_from_file(full_path);
        if (version != 0) {
          SNPRINTF_UTF8(version_str, "%d.%01d", version / 100, version % 100);
        }
      }

      if (version_str[0]) {
        tooltip_text_field_add(tip,
                               fmt::format("Blender {}", version_str),
                               {},
                               ui::TIP_STYLE_NORMAL,
                               ui::TIP_LC_NORMAL);
        tooltip_text_field_add(tip, {}, {}, ui::TIP_STYLE_SPACER, ui::TIP_LC_NORMAL);
      }
    }
    else if (file->typeflag & FILE_TYPE_IMAGE) {
      if (!thumb) {
        /* Load the thumbnail from cache if existing, create if not. */
        thumb = IMB_thumb_manage(full_path, THB_LARGE, THB_SOURCE_IMAGE);
      }
      if (thumb) {
        char value1[128];
        char value2[128];
        if (IMB_metadata_get_field(
                thumb->metadata, "Thumb::Image::Width", value1, sizeof(value1)) &&
            IMB_metadata_get_field(
                thumb->metadata, "Thumb::Image::Height", value2, sizeof(value2)))
        {
          tooltip_text_field_add(tip,
                                 fmt::format("{} \u00D7 {}", value1, value2),
                                 {},
                                 ui::TIP_STYLE_NORMAL,
                                 ui::TIP_LC_NORMAL);
          tooltip_text_field_add(tip, {}, {}, ui::TIP_STYLE_SPACER, ui::TIP_LC_NORMAL);
        }
      }
    }
    else if (file->typeflag & FILE_TYPE_MOVIE) {
      if (!thumb) {
        /* This could possibly take a while. */
        thumb = IMB_thumb_manage(full_path, THB_LARGE, THB_SOURCE_MOVIE);
      }
      if (thumb) {
        char value1[128];
        char value2[128];
        char value3[128];
        if (IMB_metadata_get_field(
                thumb->metadata, "Thumb::Video::Width", value1, sizeof(value1)) &&
            IMB_metadata_get_field(
                thumb->metadata, "Thumb::Video::Height", value2, sizeof(value2)))
        {
          tooltip_text_field_add(tip,
                                 fmt::format("{} \u00D7 {}", value1, value2),
                                 {},
                                 ui::TIP_STYLE_NORMAL,
                                 ui::TIP_LC_NORMAL);
        }
        if (IMB_metadata_get_field(
                thumb->metadata, "Thumb::Video::Frames", value1, sizeof(value1)) &&
            IMB_metadata_get_field(thumb->metadata, "Thumb::Video::FPS", value2, sizeof(value2)) &&
            IMB_metadata_get_field(
                thumb->metadata, "Thumb::Video::Duration", value3, sizeof(value3)))
        {
          tooltip_text_field_add(
              tip,
              fmt::format(fmt::runtime(TIP_("{} Frames @ {} FPS")), value1, value2),
              {},
              ui::TIP_STYLE_NORMAL,
              ui::TIP_LC_NORMAL);
          tooltip_text_field_add(tip,
                                 fmt::format(fmt::runtime(TIP_("{} seconds")), value3),
                                 {},
                                 ui::TIP_STYLE_NORMAL,
                                 ui::TIP_LC_NORMAL);
          tooltip_text_field_add(tip, {}, {}, ui::TIP_STYLE_SPACER, ui::TIP_LC_NORMAL);
        }
      }
    }
    else if (file->typeflag & FILE_TYPE_FTFONT) {
      float color[4];
      bTheme *btheme = ui::theme::theme_get();
      rgba_uchar_to_float(color, btheme->tui.wcol_tooltip.text);
      thumb = IMB_font_preview(file->redirection_path ? file->redirection_path : full_path,
                               512 * UI_SCALE_FAC,
                               color,
                               TIP_("The five boxing wizards jump quickly! 0123456789"));
      free_imbuf = true;
    }

    const time_t file_time = (time_t)file->time;
    const std::tm mod_time = date_string::localtime_safe(file_time);
    const time_t ts_now = time(nullptr);
    const std::tm now = date_string::localtime_safe(ts_now);
    const char *lang = BLT_lang_get();
    std::string modified_s = blender::date_string::datetime(mod_time,
                                                            lang,
                                                            date_string::DateFormat(U.date_format),
                                                            date_string::TimeFormat(U.time_format),
                                                            &now,
                                                            TIP_("Today"),
                                                            TIP_("Yesterday"));
    tooltip_text_field_add(tip,
                           fmt::format(fmt::runtime(TIP_("Modified: {}")), modified_s),
                           {},
                           ui::TIP_STYLE_NORMAL,
                           ui::TIP_LC_NORMAL);

    if (!(file->typeflag & FILE_TYPE_DIR) && file->size > 0) {
      char size[16];
      BLI_filelist_entry_size_to_string(nullptr, file->size, false, size);
      if (file->size < 10000) {
        char size_full[BLI_STR_FORMAT_UINT64_GROUPED_SIZE];
        BLI_str_format_uint64_grouped(size_full, file->size);
        tooltip_text_field_add(
            tip,
            fmt::format(fmt::runtime(TIP_("Size: {} ({} bytes)")), size, size_full),
            {},
            ui::TIP_STYLE_NORMAL,
            ui::TIP_LC_NORMAL);
      }
      else {
        tooltip_text_field_add(tip,
                               fmt::format(fmt::runtime(TIP_("Size: {}")), size),
                               {},
                               ui::TIP_STYLE_NORMAL,
                               ui::TIP_LC_NORMAL);
      }
    }
  }

  if (thumb && file->typeflag & FILE_TYPE_FTFONT) {
    const float scale = (512.0f * UI_SCALE_FAC) / float(std::max(thumb->x, thumb->y));
    ui::TooltipImage image_data;
    image_data.ibuf = thumb;
    image_data.width = short(float(thumb->x) * scale);
    image_data.height = short(float(thumb->y) * scale);
    image_data.background = ui::TooltipImageBackground::None;
    image_data.premultiplied = false;
    image_data.text_color = true;
    image_data.border = false;
    tooltip_text_field_add(tip, {}, {}, ui::TIP_STYLE_SPACER, ui::TIP_LC_NORMAL);
    tooltip_image_field_add(tip, image_data);
  }
  else if (thumb && params->display != FILE_IMGDISPLAY) {
    tooltip_text_field_add(tip, {}, {}, ui::TIP_STYLE_SPACER, ui::TIP_LC_NORMAL);
    tooltip_text_field_add(tip, {}, {}, ui::TIP_STYLE_SPACER, ui::TIP_LC_NORMAL);

    ui::TooltipImage image_data;
    float scale = (96.0f * UI_SCALE_FAC) / float(std::max(thumb->x, thumb->y));
    image_data.ibuf = thumb;
    image_data.width = short(float(thumb->x) * scale);
    image_data.height = short(float(thumb->y) * scale);
    image_data.border = true;
    image_data.background = ui::TooltipImageBackground::Checkerboard_Themed;
    image_data.premultiplied = true;
    tooltip_image_field_add(tip, image_data);
  }

  if (thumb && free_imbuf) {
    IMB_freeImBuf(thumb);
  }
}

static void file_draw_asset_tooltip_custom_func(bContext & /*C*/,
                                                ui::TooltipData &tip,
                                                ui::Button * /*but*/,
                                                void *argN)
{
  const auto *asset = static_cast<asset_system::AssetRepresentation *>(argN);
  ed::asset::asset_tooltip(*asset, tip);
}

static void draw_tile_background(const rcti *draw_rect, int colorid, int shade)
{
  float color[4];
  rctf draw_rect_fl;
  BLI_rctf_rcti_copy(&draw_rect_fl, draw_rect);

  ui::theme::get_color_shade_4fv(colorid, shade, color);
  draw_roundbox_corner_set(ui::CNR_ALL);
  ui::draw_roundbox_aa(&draw_rect_fl, true, 5.0f, color);
}

static void file_but_enable_drag(ui::Button *but,
                                 const SpaceFile *sfile,
                                 const FileDirEntry *file,
                                 const char *path,
                                 const ImBuf *preview_image,
                                 int icon,
                                 float scale)
{
  ID *id;

  if ((id = filelist_file_get_id(file))) {
    button_drag_set_id(but, id);
    if (preview_image) {
      button_drag_attach_image(but, preview_image, scale);
    }
  }
  else if (sfile->browse_mode == FILE_BROWSE_MODE_ASSETS &&
           (file->typeflag & FILE_TYPE_ASSET) != 0)
  {
    const int import_method = ED_fileselect_asset_import_method_get(sfile, file);
    BLI_assert(import_method > -1);
    if (import_method > -1) {
      AssetImportSettings import_settings{};
      import_settings.method = eAssetImportMethod(import_method);
      import_settings.use_instance_collections =
          (sfile->asset_params->import_flags &
           (ELEM(import_method, ASSET_IMPORT_LINK, ASSET_IMPORT_PACK) ?
                FILE_ASSET_IMPORT_INSTANCE_COLLECTIONS_ON_LINK :
                FILE_ASSET_IMPORT_INSTANCE_COLLECTIONS_ON_APPEND)) != 0;

      button_drag_set_asset(but, file->asset, import_settings, icon, file->preview_icon_id);
    }
  }
  else if (preview_image) {
    button_drag_set_image(but, path, icon, preview_image, scale);
  }
  else {
    /* path is no more static, cannot give it directly to but... */
    button_drag_set_path(but, path);
  }
}

static void file_but_tooltip_func_set(const SpaceFile *sfile,
                                      const FileDirEntry *file,
                                      ui::Button *but)
{
  if (file->asset) {
    button_func_tooltip_custom_set(but, file_draw_asset_tooltip_custom_func, file->asset, nullptr);
  }
  else {
    button_func_tooltip_custom_set(but,
                                   file_draw_tooltip_custom_func,
                                   file_tooltip_data_create(sfile, file),
                                   MEM_delete_void);
  }
}

static ui::Button *file_add_icon_but(const SpaceFile *sfile,
                                     ui::Block *block,
                                     const char * /*path*/,
                                     const FileDirEntry *file,
                                     const rcti *tile_draw_rect,
                                     int icon,
                                     int width,
                                     int height,
                                     int padx,
                                     bool dimmed)
{
  ui::Button *but;

  const int x = tile_draw_rect->xmin + padx;
  const int y = tile_draw_rect->ymin +
                round_fl_to_int((BLI_rcti_size_y(tile_draw_rect) - height) / 2.0f);

  if (icon < BIFICONID_LAST_STATIC) {
    /* Small built-in icon. Draw centered in given width. */
    but = uiDefIconBut(block,
                       ui::ButtonType::Label,
                       icon,
                       x,
                       y,
                       width,
                       height,
                       nullptr,
                       0.0f,
                       0.0f,
                       std::nullopt);
    /* Center the icon. */
    button_drawflag_disable(but, ui::BUT_ICON_LEFT);
  }
  else {
    /* Larger preview icon. Fills available width/height. */
    but = uiDefIconPreviewBut(block,
                              ui::ButtonType::Label,
                              icon,
                              x,
                              y,
                              width,
                              height,
                              nullptr,
                              0.0f,
                              0.0f,
                              std::nullopt);
  }
  button_label_alpha_factor_set(but, dimmed ? 0.3f : 1.0f);
  file_but_tooltip_func_set(sfile, file, but);

  return but;
}

static ui::Button *file_add_overlay_icon_but(ui::Block *block, int pos_x, int pos_y, int icon)
{
  ui::Button *but = uiDefIconBut(block,
                                 ui::ButtonType::Label,
                                 icon,
                                 pos_x,
                                 pos_y,
                                 ICON_DEFAULT_WIDTH_SCALE,
                                 ICON_DEFAULT_HEIGHT_SCALE,
                                 nullptr,
                                 0.0f,
                                 0.0f,
                                 std::nullopt);
  /* Otherwise a left hand padding will be added. */
  button_drawflag_disable(but, ui::BUT_ICON_LEFT);
  button_label_alpha_factor_set(but, 0.6f);
  const uchar light[4] = {255, 255, 255, 255};
  button_color_set(but, light);

  return but;
}

static void file_draw_string(int sx,
                             int sy,
                             const char *string,
                             float width,
                             int height,
                             ui::FontStyleAlign align,
                             const uchar col[4])
{
  uiFontStyle fs;
  rcti rect;
  char filename[FILE_MAXFILE];

  if (string[0] == '\0' || width < 1) {
    return;
  }

  const uiStyle *style = ui::style_get();
  fs = style->widget;

  STRNCPY(filename, string);
  ui::text_clip_middle_ex(&fs, filename, width, UI_ICON_SIZE, sizeof(filename), '\0');

  /* no text clipping needed, fontstyle_draw does it but is a bit too strict
   * (for buttons it works) */
  rect.xmin = sx;
  rect.xmax = sx + round_fl_to_int(width);
  rect.ymin = sy - height;
  rect.ymax = sy;

  ui::FontStyleDrawParams font_style_params{};
  font_style_params.align = align;

  fontstyle_draw(&fs, &rect, filename, sizeof(filename), col, &font_style_params);
}

/**
 * Draw the string over at max \a line_count lines, clipping in the middle so it fits.
 */
static void file_draw_string_mulitline_clipped(const rcti *rect,
                                               const char *string,
                                               ui::FontStyleAlign align,
                                               const uchar col[4])
{
  if (string[0] == '\0' || BLI_rcti_size_x(rect) < 1) {
    return;
  }

  const uiStyle *style = ui::style_get();
  uiFontStyle fs = style->widget;

  fontstyle_draw_multiline_clipped(&fs, rect, string, col, align);
}

static rcti file_measure_string_multiline(const StringRef string, const int wrap_width)
{
  if (string[0] == '\0' || wrap_width < 1) {
    return {.xmin = 0, .xmax = 0, .ymin = 0, .ymax = 0};
  }

  const uiStyle *style = ui::style_get();
  const int font_id = style->widget.uifont_id;

  rcti textbox;
  BLF_wordwrap(font_id,
               wrap_width,
               BLFWrapMode::Typographical | BLFWrapMode::Path | BLFWrapMode::HardLimit);
  BLF_enable(font_id, BLF_WORD_WRAP);
  BLF_boundbox(font_id, string.data(), string.size(), &textbox);
  BLF_disable(font_id, BLF_WORD_WRAP);

  return textbox;
}

/**
 * \param r_sx, r_sy: The lower right corner of the last line drawn, plus the height of the last
 *                    line. This is the cursor position on completion to allow drawing more text
 *                    behind that.
 */
static void file_draw_string_multiline(int sx,
                                       int sy,
                                       const StringRef string,
                                       int wrap_width,
                                       int line_height,
                                       const uchar text_col[4],
                                       int *r_sx,
                                       int *r_sy)
{
  rcti rect;

  if (string[0] == '\0' || wrap_width < 1) {
    return;
  }

  const uiStyle *style = ui::style_get();
  const rcti textbox = file_measure_string_multiline(string, wrap_width);

  /* no text clipping needed, fontstyle_draw does it but is a bit too strict
   * (for buttons it works) */
  rect.xmin = sx;
  rect.xmax = sx + wrap_width;
  /* Need to increase the clipping rect by one more line, since the #fontstyle_draw_ex() will
   * actually start drawing at (ymax - line-height). */
  rect.ymin = sy - BLI_rcti_size_y(&textbox) - line_height;
  rect.ymax = sy;

  ui::FontStyleDrawParams font_style_params{};
  font_style_params.align = ui::UI_STYLE_TEXT_LEFT;
  font_style_params.word_wrap = true;

  ResultBLF result;
  fontstyle_draw_ex(&style->widget,
                    &rect,
                    string.data(),
                    string.size(),
                    text_col,
                    &font_style_params,
                    nullptr,
                    nullptr,
                    &result);
  if (r_sx) {
    *r_sx = result.width;
  }
  if (r_sy) {
    *r_sy = rect.ymin + line_height;
  }
}

static std::tuple<int, int, float> preview_image_scaled_dimensions_get(const int image_width,
                                                                       const int image_height,
                                                                       const FileLayout &layout)
{
  const float ui_imbx = image_width * UI_SCALE_FAC;
  const float ui_imby = image_height * UI_SCALE_FAC;

  float scale;
  float scaledx, scaledy;
  if (((ui_imbx > layout.prv_w) || (ui_imby > layout.prv_h)) ||
      ((ui_imbx < layout.prv_w) || (ui_imby < layout.prv_h)))
  {
    if (image_width > image_height) {
      scaledx = float(layout.prv_w);
      scaledy = (float(image_height) / float(image_width)) * layout.prv_w;
      scale = scaledx / image_width;
    }
    else {
      scaledy = float(layout.prv_h);
      scaledx = (float(image_width) / float(image_height)) * layout.prv_h;
      scale = scaledy / image_height;
    }
  }
  else {
    scaledx = ui_imbx;
    scaledy = ui_imby;
    scale = UI_SCALE_FAC;
  }

  return std::make_tuple(int(scaledx), int(scaledy), scale);
}

static void file_add_preview_drag_but(const SpaceFile *sfile,
                                      ui::Block *block,
                                      FileLayout *layout,
                                      const FileDirEntry *file,
                                      const char *path,
                                      const rcti *tile_draw_rect,
                                      const int file_type_icon)
{
  /* Invisible button for dragging. */
  rcti drag_rect = *tile_draw_rect;
  /* A bit smaller than the full tile, to increase the gap between items that users can drag from
   * for box select. */
  BLI_rcti_pad(&drag_rect, -layout->tile_border_x, -layout->tile_border_y);

  ui::Button *but = uiDefBut(block,
                             ui::ButtonType::Label,
                             "",
                             drag_rect.xmin,
                             drag_rect.ymin,
                             BLI_rcti_size_x(&drag_rect),
                             BLI_rcti_size_y(&drag_rect),
                             nullptr,
                             0.0,
                             0.0,
                             std::nullopt);

  const ImBuf *preview_image = filelist_file_get_preview_image(file);
  const ImBuf *drag_image = (preview_image || file->asset) ?
                                preview_image :
                                /* Larger directory or document icon. */
                                filelist_geticon_special_file_image_ex(file);
  const float scale = drag_image ? (PREVIEW_DRAG_DRAW_SIZE * UI_SCALE_FAC) /
                                       std::max(drag_image->x, drag_image->y) :
                                   1.0f;
  file_but_enable_drag(but, sfile, file, path, drag_image, file_type_icon, scale);
  file_but_tooltip_func_set(sfile, file, but);
}

static void file_add_asset_download_but(ui::Block *block,
                                        const FileLayout *layout,
                                        const FileDirEntry *file,
                                        const rcti *tile_draw_rect)
{
  const int preview_center_x = BLI_rcti_cent_x(tile_draw_rect);
  const int preview_center_y = tile_draw_rect->ymax - layout->tile_border_y - layout->prv_h * 0.5f;
  const int icon_width = ICON_DEFAULT_WIDTH_SCALE * 2.0f;
  const int icon_height = ICON_DEFAULT_HEIGHT_SCALE * 2.0f;
  const int icon_x = preview_center_x - icon_width * 0.5f;
  const int icon_y = preview_center_y - icon_height * 0.5f;

  ui::Button *but = uiDefIconButO(block,
                                  ui::ButtonType::But,
                                  "ASSET_OT_asset_download",
                                  wm::OpCallContext::ExecDefault,
                                  ICON_DOWNLOAD,
                                  icon_x,
                                  icon_y,
                                  icon_width,
                                  icon_height,
                                  std::nullopt);
  PointerRNA *opptr = ui::button_operator_ptr_ensure(but);
  ed::asset::operator_asset_reference_props_set(*file->asset, *opptr);
  ui::button_icon_scale_set(but, 1.5f);
  ui::button_pushbutton_draw_as_overlay_set(but, true);
}

static void file_draw_preview(const FileDirEntry *file,
                              const rcti *tile_draw_rect,
                              const IconBufferRef &preview,
                              FileLayout *layout,
                              const bool dimmed)
{
  const auto [scaled_width, scaled_height, scale] = preview_image_scaled_dimensions_get(
      preview.width, preview.height, *layout);

  /* Additional offset to keep the scaled image centered. Difference between maximum
   * width/height and the actual width/height, divided by two for centering. */
  const float ofs_x = (float(layout->prv_w) - float(scaled_width)) / 2.0f;
  const float ofs_y = (float(layout->prv_h) - float(scaled_height)) / 2.0f;
  const int xmin = tile_draw_rect->xmin + layout->prv_border_x + int(ofs_x + 0.5f);
  const int ymin = tile_draw_rect->ymax - layout->prv_border_y - layout->prv_h + int(ofs_y + 0.5f);

  GPU_blend(GPU_BLEND_ALPHA);

  float document_img_col[4] = {1.0f, 1.0f, 1.0f, 1.0f};
  if (file->typeflag & FILE_TYPE_FTFONT) {
    ui::theme::get_color_4fv(TH_TEXT, document_img_col);
  }
  if (dimmed) {
    document_img_col[3] *= 0.3f;
  }

  if (ELEM(file->typeflag, FILE_TYPE_IMAGE, FILE_TYPE_OBJECT_IO)) {
    /* Draw checker pattern behind image previews in case they have transparency. */
    imm_draw_box_checker_2d(
        float(xmin), float(ymin), float(xmin + scaled_width), float(ymin + scaled_height));
  }

  if (file->typeflag & FILE_TYPE_BLENDERLIB) {
    /* Datablock preview images use premultiplied alpha. */
    GPU_blend(GPU_BLEND_ALPHA_PREMULT);
  }

  const gpu::TextureFormat format = gpu::TextureFormat::UNORM_8_8_8_8;
  BLI_assert_msg(preview.channels == 4, "preview images are expected to be 4 channels");

  PixelBitmapDrawer drawer(GPU_SHADER_3D_IMAGE_COLOR);
  drawer.draw(float(xmin),
              float(ymin),
              preview.width,
              preview.height,
              format,
              true,
              preview.buffer.data(),
              scale,
              scale,
              document_img_col);

  const bool show_outline = (file->typeflag & (FILE_TYPE_IMAGE | FILE_TYPE_OBJECT_IO |
                                               FILE_TYPE_MOVIE | FILE_TYPE_BLENDER));
  /* Contrasting outline around some preview types. */
  if (show_outline) {
    GPU_blend(GPU_BLEND_ALPHA);

    GPUVertFormat *format = immVertexFormat();
    uint pos = GPU_vertformat_attr_add(format, "pos", gpu::VertAttrType::SFLOAT_32_32);
    immBindBuiltinProgram(GPU_SHADER_3D_UNIFORM_COLOR);
    float border_color[4] = {1.0f, 1.0f, 1.0f, 0.15f};
    float bgcolor[4];
    ui::theme::get_color_4fv(TH_BACK, bgcolor);
    if (srgb_to_grayscale(bgcolor) > 0.5f) {
      border_color[0] = 0.0f;
      border_color[1] = 0.0f;
      border_color[2] = 0.0f;
    }
    immUniformColor4fv(border_color);
    imm_draw_box_wire_2d(pos,
                         float(xmin),
                         float(ymin),
                         float(xmin + scaled_width + 1),
                         float(ymin + scaled_height + 1));
    immUnbindProgram();
  }

  GPU_blend(GPU_BLEND_NONE);
}

static void file_draw_special_image(const FileDirEntry *file,
                                    const rcti *tile_draw_rect,
                                    const int file_type_icon,
                                    const float icon_aspect,
                                    const FileLayout *layout,
                                    const bool dimmed)
{
  float document_img_col[4] = {1.0f, 1.0f, 1.0f, 1.0f};
  if (file->typeflag & FILE_TYPE_DIR) {
    ui::theme::get_color_4fv(TH_ICON_FOLDER, document_img_col);
  }
  else {
    ui::theme::get_color_4fv(TH_TEXT, document_img_col);
  }

  if (dimmed) {
    document_img_col[3] *= 0.3f;
  }

  GPU_blend(GPU_BLEND_ALPHA);

  const int cent_x = tile_draw_rect->xmin + layout->prv_border_x + (layout->prv_w / 2.0f) + 0.5f;
  const int cent_y = tile_draw_rect->ymax - layout->prv_border_y - (layout->prv_h / 2.0f) + 0.5f;
  const float aspect = icon_aspect / UI_SCALE_FAC;

  {
    /* Draw large folder or document icon. */
    const int icon_large = (file->typeflag & FILE_TYPE_DIR) ? ICON_FILE_FOLDER_LARGE :
                                                              ICON_FILE_LARGE;

    uchar icon_col[4];
    rgba_float_to_uchar(icon_col, document_img_col);

    const float scale = 4.0f;
    const float ofs_y = (file->typeflag & FILE_TYPE_DIR ? -0.02f : 0.0f) * layout->prv_h;

    ui::icon_draw_ex(cent_x - (ICON_DEFAULT_WIDTH * scale / aspect / 2.0f),
                     cent_y - (ICON_DEFAULT_HEIGHT * scale / aspect / 2.0f) + ofs_y,
                     icon_large,
                     icon_aspect / UI_SCALE_FAC / scale,
                     document_img_col[3],
                     0.0f,
                     icon_col,
                     false,
                     UI_NO_ICON_OVERLAY_TEXT);
  }

  if (file_type_icon) {
    /* Small icon in the middle of large image, scaled to fit container and UI scale */
    float icon_opacity = 0.4f;
    uchar icon_color[4] = {0, 0, 0, 255};
    if (srgb_to_grayscale(document_img_col) < 0.5f) {
      icon_color[0] = 255;
      icon_color[1] = 255;
      icon_color[2] = 255;
    }

    const float scale = file->typeflag & FILE_TYPE_DIR ? 1.5f : 2.0f;
    const float ofs_y = (file->typeflag & FILE_TYPE_DIR ? -0.035f : -0.135f) * layout->prv_h;

    ui::icon_draw_ex(cent_x - (ICON_DEFAULT_WIDTH * scale / aspect / 2.0f),
                     cent_y - (ICON_DEFAULT_HEIGHT * scale / aspect / 2.0f) + ofs_y,
                     file_type_icon,
                     icon_aspect / UI_SCALE_FAC / scale,
                     icon_opacity,
                     0.0f,
                     icon_color,
                     false,
                     UI_NO_ICON_OVERLAY_TEXT);
  }

  GPU_blend(GPU_BLEND_NONE);
}

static void file_draw_loading_icon(const rcti *tile_draw_rect,
                                   const float preview_icon_aspect,
                                   const FileLayout *layout)
{
  uchar icon_color[4] = {0, 0, 0, 255};
  /* Contrast with background since we are not showing the large document image. */
  ui::theme::get_color_4ubv(TH_TEXT, icon_color);

  const int cent_x = tile_draw_rect->xmin + layout->prv_border_x + (layout->prv_w / 2.0f) + 0.5f;
  const int cent_y = tile_draw_rect->ymax - layout->prv_border_y - (layout->prv_h / 2.0f) + 0.5f;
  const float aspect = preview_icon_aspect / UI_SCALE_FAC;

  ui::icon_draw_ex(cent_x - (ICON_DEFAULT_WIDTH / aspect / 2.0f),
                   cent_y - (ICON_DEFAULT_HEIGHT / aspect / 2.0f),
                   ICON_PREVIEW_LOADING,
                   aspect,
                   1.0f,
                   0.0f,
                   icon_color,
                   false,
                   UI_NO_ICON_OVERLAY_TEXT);
}

static void file_draw_indicator_icons(const FileList *files,
                                      const FileDirEntry *file,
                                      const FileLayout *layout,
                                      const rcti *tile_draw_rect,
                                      const float preview_icon_aspect,
                                      const int file_type_icon,
                                      const bool has_special_file_image,
                                      const eDirEntry_SelectFlag /*selflag*/)
{
  const bool is_offline = (file->attributes & FILE_ATTR_OFFLINE);
  const bool is_link = (file->attributes & FILE_ATTR_ANY_LINK);
  const bool is_loading = filelist_file_is_preview_pending(files, file);

  /* Don't draw these icons if the preview image is small. They are just indicators and shouldn't
   * cover the preview. */
  if (preview_icon_aspect < 2.0f) {
    const float icon_x = float(tile_draw_rect->xmin) + (3.0f * UI_SCALE_FAC);
    const float icon_y = float(tile_draw_rect->ymax) - layout->prv_border_y - layout->prv_h;
    const uchar light[4] = {255, 255, 255, 255};
    if (is_offline) {
      /* Icon at bottom to indicate the file is offline. */
      ui::icon_draw_ex(icon_x,
                       icon_y,
                       ICON_INTERNET,
                       1.0f / UI_SCALE_FAC,
                       0.6f,
                       0.0f,
                       light,
                       true,
                       UI_NO_ICON_OVERLAY_TEXT);
    }
    else if (is_link) {
      /* Icon at bottom to indicate it is a shortcut, link, or alias. */
      ui::icon_draw_ex(icon_x,
                       icon_y,
                       ICON_FILE_ALIAS,
                       1.0f / UI_SCALE_FAC,
                       0.6f,
                       0.0f,
                       nullptr,
                       false,
                       UI_NO_ICON_OVERLAY_TEXT);
    }
    else if (file_type_icon) {
      /* Smaller, fainter type icon at bottom-left.
       *
       * Always draw while loading, the preview shows a loading icon and doesn't indicate the type
       * yet then. After loading, the special file image may already draw the type icon in
       * #file_draw_preview(), don't draw it again here. Also don't draw it for font files, they
       * render a font preview already, the type indicator would be redundant.
       */
      if (is_loading || !(has_special_file_image || (file->typeflag & FILE_TYPE_FTFONT))) {
        ui::icon_draw_ex(icon_x,
                         icon_y,
                         file_type_icon,
                         1.0f / UI_SCALE_FAC,
                         0.6f,
                         0.0f,
                         light,
                         true,
                         UI_NO_ICON_OVERLAY_TEXT);
      }
    }
  }

  {
    const float icon_x = float(tile_draw_rect->xmax) - (16.0f * UI_SCALE_FAC);
    const float icon_y = float(tile_draw_rect->ymax) - (20.0f * UI_SCALE_FAC);
    const uchar light[4] = {255, 255, 255, 255};

    const bool is_current_main_data = filelist_file_get_id(file) != nullptr;
    if (is_current_main_data) {
      /* Smaller, fainter icon at the top-right indicating that the file represents data from the
       * current file (from current #Main in fact). */
      ui::icon_draw_ex(icon_x,
                       icon_y,
                       ICON_CURRENT_FILE,
                       1.0f / UI_SCALE_FAC,
                       0.6f,
                       0.0f,
                       light,
                       true,
                       UI_NO_ICON_OVERLAY_TEXT);
    }
    else if ((file->typeflag & FILE_TYPE_ASSET_ONLINE) != 0) {
      ui::icon_draw_ex(icon_x,
                       icon_y,
                       ICON_INTERNET,
                       1.0f / UI_SCALE_FAC,
                       0.6f,
                       0.0f,
                       light,
                       true,
                       UI_NO_ICON_OVERLAY_TEXT);
    }
    else if (file->asset &&
             file->asset->remote_file_status() == asset_system::RemoteAssetFileStatus::NO_MATCH)
    {
      /* This on-disk asset no longer matches the asset listing it was downloaded from. */
      ui::icon_draw_ex(icon_x,
                       icon_y,
                       ICON_ERROR,
                       1.0f / UI_SCALE_FAC,
                       0.6f,
                       0.0f,
                       light,
                       true,
                       UI_NO_ICON_OVERLAY_TEXT);
    }
  }
}

static void renamebutton_cb(bContext &C, StringRefNull oldname)
{
  char newname[FILE_MAX + 12];
  char orgname[FILE_MAX + 12];
  char filename[FILE_MAX + 12];
  wmWindowManager *wm = CTX_wm_manager(&C);
  wmWindow *win = CTX_wm_window(&C);
  SpaceFile *sfile = reinterpret_cast<SpaceFile *>(CTX_wm_space_data(&C));
  ARegion *region = CTX_wm_region(&C);
  FileSelectParams *params = ED_fileselect_get_active_params(sfile);

  BLI_path_join(orgname, sizeof(orgname), params->dir, oldname.c_str());
  STRNCPY(filename, params->renamefile);
  BLI_path_make_safe_filename(filename);
  BLI_path_join(newname, sizeof(newname), params->dir, filename);

  if (!STREQ(orgname, newname)) {
    errno = 0;
    if ((BLI_rename(orgname, newname) != 0) || !BLI_exists(newname)) {
      WM_global_reportf(
          RPT_ERROR, "Could not rename: %s", errno ? strerror(errno) : "unknown error");
      WM_report_banner_show(wm, win);
      /* Renaming failed, reset the name for further renaming handling. */
      STRNCPY(params->renamefile, oldname.c_str());
    }
    else {
      /* If rename is successful, set renamefile to newly renamed entry.
       * This is used later to select and scroll to the file.
       */
      STRNCPY(params->renamefile, filename);
    }

    /* Ensure we select and scroll to the renamed file.
     * This is done even if the rename fails as we want to make sure that the file we tried to
     * rename is still selected and in view. (it can move if something added files/folders to the
     * directory while we were renaming).
     */
    file_params_invoke_rename_postscroll(wm, win, sfile);
    /* to make sure we show what is on disk */
    ED_fileselect_clear(wm, sfile);
    ED_region_tag_redraw(region);
  }
}

static void draw_background(FileLayout *layout, View2D *v2d)
{
  const int item_height = layout->tile_h + (2 * layout->tile_border_y);
  int i;
  int sy;

  uint pos = GPU_vertformat_attr_add(immVertexFormat(), "pos", gpu::VertAttrType::SFLOAT_32_32);
  immBindBuiltinProgram(GPU_SHADER_3D_UNIFORM_COLOR);
  float col_alternating[4];
  ui::theme::get_color_4fv(TH_ROW_ALTERNATE, col_alternating);
  immUniformThemeColorBlend(TH_BACK, TH_ROW_ALTERNATE, col_alternating[3]);

  /* alternating flat shade background */
  for (i = 2; (i <= layout->rows + 1); i += 2) {
    sy = int(v2d->cur.ymax) - layout->offset_top - i * item_height - layout->list_padding_top;

    /* Offset pattern slightly to add scroll effect. */
    sy += round_fl_to_int(item_height * (v2d->tot.ymax - v2d->cur.ymax) / item_height);

    immRectf(pos,
             v2d->cur.xmin,
             float(sy),
             v2d->cur.xmax,
             float(sy + layout->tile_h + 2 * layout->tile_border_y));
  }

  immUnbindProgram();
}

static void draw_dividers(FileLayout *layout, View2D *v2d)
{
  /* vertical column dividers */

  const int step = (layout->tile_w + 2 * layout->tile_border_x);

  uint vertex_len = 0;
  int sx = int(v2d->tot.xmin);
  while (sx < v2d->cur.xmax) {
    sx += step;
    vertex_len += 4; /* vertex_count = 2 points per line * 2 lines per divider */
  }

  if (vertex_len > 0) {
    float v1[2], v2[2];
    float col_hi[3], col_lo[3];

    ui::theme::get_color_shade_3fv(TH_BACK, 30, col_hi);
    ui::theme::get_color_shade_3fv(TH_BACK, -30, col_lo);

    v1[1] = v2d->cur.ymax - layout->tile_border_y;
    v2[1] = v2d->cur.ymin;

    GPUVertFormat *format = immVertexFormat();
    uint pos = GPU_vertformat_attr_add(format, "pos", gpu::VertAttrType::SFLOAT_32_32);
    uint color = GPU_vertformat_attr_add(format, "color", gpu::VertAttrType::SFLOAT_32_32_32);

    immBindBuiltinProgram(GPU_SHADER_3D_FLAT_COLOR);
    immBegin(GPU_PRIM_LINES, vertex_len);

    sx = int(v2d->tot.xmin);
    while (sx < v2d->cur.xmax) {
      sx += step;

      v1[0] = v2[0] = sx;
      immAttrSkip(color);
      immVertex2fv(pos, v1);
      immAttr3fv(color, col_lo);
      immVertex2fv(pos, v2);

      v1[0] = v2[0] = sx + 1;
      immAttrSkip(color);
      immVertex2fv(pos, v1);
      immAttr3fv(color, col_hi);
      immVertex2fv(pos, v2);
    }

    immEnd();
    immUnbindProgram();
  }
}

static void draw_fixed_header_background(const View2D *v2d, const float height)
{
  uint pos = GPU_vertformat_attr_add(immVertexFormat(), "pos", gpu::VertAttrType::SFLOAT_32_32);

  immBindBuiltinProgram(GPU_SHADER_3D_UNIFORM_COLOR);
  immUniformThemeColorShade(TH_BACK, 11);

  immRectf(pos, v2d->cur.xmin, v2d->cur.ymax - height, v2d->cur.xmax, v2d->cur.ymax);

  immUnbindProgram();
}

static void draw_columnheader_columns(const FileSelectParams *params,
                                      FileLayout *layout,
                                      const View2D *v2d,
                                      const uchar text_col[4])
{
  const float divider_pad = 0.2 * layout->attribute_column_header_h;
  int sx = v2d->cur.xmin, sy = v2d->cur.ymax;

  for (int column_type = 0; column_type < ATTRIBUTE_COLUMN_MAX; column_type++) {
    if (!file_attribute_column_type_enabled(params, FileAttributeColumnType(column_type), layout))
    {
      continue;
    }
    const FileAttributeColumn *column = &layout->attribute_columns[column_type];

    /* Active sort type triangle */
    if (params->sort == column->sort_type) {
      float tri_color[4];

      rgba_uchar_to_float(tri_color, text_col);
      ui::draw_icon_tri(sx + column->width - (0.3f * U.widget_unit) -
                            ATTRIBUTE_COLUMN_PADDING / 2.0f,
                        sy + (0.1f * U.widget_unit) - (layout->attribute_column_header_h / 2),
                        (params->flag & FILE_SORT_INVERT) ? 't' : 'v',
                        tri_color);
    }

    file_draw_string(sx + ATTRIBUTE_COLUMN_PADDING,
                     sy - layout->tile_border_y,
                     IFACE_(column->name),
                     column->width - 2 * ATTRIBUTE_COLUMN_PADDING,
                     layout->attribute_column_header_h - layout->tile_border_y,
                     ui::UI_STYLE_TEXT_LEFT,
                     text_col);

    /* Separator line */
    if (column_type != COLUMN_NAME) {
      uint pos = GPU_vertformat_attr_add(
          immVertexFormat(), "pos", gpu::VertAttrType::SFLOAT_32_32);

      immBindBuiltinProgram(GPU_SHADER_3D_UNIFORM_COLOR);
      immUniformThemeColorShade(TH_BACK, -10);
      immBegin(GPU_PRIM_LINES, 2);
      immVertex2f(pos, sx - 1, sy - divider_pad);
      immVertex2f(pos, sx - 1, sy - layout->attribute_column_header_h + divider_pad);
      immEnd();
      immUnbindProgram();
    }

    sx += column->width;
  }

  /* Vertical separator lines line */
  {
    uint pos = GPU_vertformat_attr_add(immVertexFormat(), "pos", gpu::VertAttrType::SFLOAT_32_32);
    immBindBuiltinProgram(GPU_SHADER_3D_UNIFORM_COLOR);
    immUniformThemeColorShade(TH_BACK, -10);
    immBegin(GPU_PRIM_LINES, 4);
    immVertex2f(pos, v2d->cur.xmin, sy);
    immVertex2f(pos, v2d->cur.xmax, sy);
    immVertex2f(pos, v2d->cur.xmin, sy - layout->attribute_column_header_h);
    immVertex2f(pos, v2d->cur.xmax, sy - layout->attribute_column_header_h);
    immEnd();
    immUnbindProgram();
  }
}

/**
 * Updates the stat string stored in file->entry if necessary.
 */
static const char *filelist_get_details_column_string(
    FileAttributeColumnType column,
    /* Generated string will be cached in the file, so non-const. */
    FileDirEntry *file,
    const bool compact,
    const bool update_stat_strings)
{
  switch (column) {
    case COLUMN_DATETIME:
      if (!(file->typeflag & FILE_TYPE_BLENDERLIB) && !FILENAME_IS_CURRPAR(file->relpath)) {
        if (file->draw_data.datetime_str[0] == '\0' || update_stat_strings) {
          const time_t file_time = (time_t)file->time;
          const std::tm mod_time = date_string::localtime_safe(file_time);
          const time_t ts_now = time(nullptr);
          const std::tm now = date_string::localtime_safe(ts_now);
          const char *lang = BLT_lang_get();
          std::string modified_s =
              compact ? date_string::date(mod_time, lang, date_string::DateFormat(U.date_format)) :
                        date_string::datetime(mod_time,
                                              lang,
                                              date_string::DateFormat(U.date_format),
                                              date_string::TimeFormat(U.time_format),
                                              &now,
                                              TIP_("Today"),
                                              TIP_("Yesterday"));
          STRNCPY_UTF8(file->draw_data.datetime_str, modified_s.c_str());
        }
        return file->draw_data.datetime_str;
      }
      break;
    case COLUMN_SIZE:
      if ((file->typeflag & (FILE_TYPE_BLENDER | FILE_TYPE_BLENDER_BACKUP)) ||
          !(file->typeflag & (FILE_TYPE_DIR | FILE_TYPE_BLENDERLIB)))
      {
        if (file->draw_data.size_str[0] == '\0' || update_stat_strings) {
          BLI_filelist_entry_size_to_string(
              nullptr, file->size, compact, file->draw_data.size_str);
        }

        return file->draw_data.size_str;
      }
      break;
    default:
      break;
  }

  return nullptr;
}

static void draw_details_columns(const FileSelectParams *params,
                                 const FileLayout *layout,
                                 FileDirEntry *file,
                                 const rcti *tile_draw_rect,
                                 const uchar text_col[4])
{
  const bool compact = FILE_LAYOUT_COMPACT(layout);
  const bool update_stat_strings = layout->width != layout->curr_size;
  int sx = tile_draw_rect->xmin - layout->tile_border_x;

  for (int column_type = 0; column_type < ATTRIBUTE_COLUMN_MAX; column_type++) {
    const FileAttributeColumn *column = &layout->attribute_columns[column_type];

    /* Name column is not a detail column (should already be drawn), always skip here. */
    if (column_type == COLUMN_NAME) {
      sx += column->width;
      continue;
    }
    if (!file_attribute_column_type_enabled(params, FileAttributeColumnType(column_type), layout))
    {
      continue;
    }

    const char *str = filelist_get_details_column_string(
        FileAttributeColumnType(column_type), file, compact, update_stat_strings);

    if (str) {
      file_draw_string(sx + ATTRIBUTE_COLUMN_PADDING,
                       tile_draw_rect->ymax,
                       IFACE_(str),
                       column->width - 2 * ATTRIBUTE_COLUMN_PADDING,
                       layout->tile_h,
                       ui::FontStyleAlign(column->text_align),
                       text_col);
    }

    sx += column->width;
  }
}

static rcti tile_draw_rect_get(const View2D *v2d, const FileLayout *layout, const int file_idx)
{
  int tile_pos_x, tile_pos_y;
  ED_fileselect_layout_tilepos(layout, file_idx, &tile_pos_x, &tile_pos_y);
  tile_pos_x += int(v2d->tot.xmin);
  tile_pos_y = int(v2d->tot.ymax - tile_pos_y);

  rcti rect;
  rect.xmin = tile_pos_x;
  rect.xmax = rect.xmin + layout->tile_w;
  rect.ymax = tile_pos_y;
  rect.ymin = rect.ymax - layout->tile_h;

  return rect;
}

/**
 * Get the boundaries to display the name label in (this isn't the rectangle of the text itself).
 */
static rcti text_draw_rect_get(const View2D *v2d,
                               const eFileDisplayType display_type,
                               const FileLayout *layout,
                               const int file_idx,
                               const int icon_ofs_x)
{
  rcti tile_rect = tile_draw_rect_get(v2d, layout, file_idx);

  rcti rect = tile_rect;
  if (display_type == FILE_IMGDISPLAY) {
    rect.ymin += round_fl_to_int(layout->prv_border_y * 0.5f);
    rect.ymax = rect.ymin + layout->text_line_height * layout->text_lines_count;
  }
  else {
    rect.xmin += icon_ofs_x + 1;
    rect.xmax = tile_rect.xmin + round_fl_to_int(layout->attribute_columns[COLUMN_NAME].width) -
                layout->tile_border_x;
  }

  return rect;
}

void file_draw_list(const bContext *C, ARegion *region)
{
  wmWindowManager *wm = CTX_wm_manager(C);
  wmWindow *win = CTX_wm_window(C);
  SpaceFile *sfile = CTX_wm_space_file(C);
  FileSelectParams *params = ED_fileselect_get_active_params(sfile);
  FileLayout *layout = ED_fileselect_get_layout(sfile, region);
  View2D *v2d = &region->v2d;
  FileList *files = sfile->files;
  FileDirEntry *file;
  ui::Block *block = block_begin(C, region, __func__, ui::EmbossType::Emboss);
  int numfiles;
  int numfiles_layout;
  int offset;
  int i;
  ui::FontStyleAlign align;
  bool do_drag;
  uchar text_col[4];
  const bool draw_columnheader = (params->display == FILE_VERTICALDISPLAY);
  const float thumb_icon_aspect = std::min(64.0f / float(params->thumbnail_size), 4.0f);

  numfiles = filelist_files_ensure(files);

  if (params->display != FILE_IMGDISPLAY) {
    draw_background(layout, v2d);
    draw_dividers(layout, v2d);
  }

  offset = ED_fileselect_layout_offset(
      layout, int(region->v2d.cur.xmin), int(-region->v2d.cur.ymax) + layout->offset_top);
  offset = std::max(offset, 0);

  numfiles_layout = ED_fileselect_layout_numfiles(layout, region);

  /* adjust, so the next row is already drawn when scrolling */
  if (layout->flag & FILE_LAYOUT_HOR) {
    numfiles_layout += layout->rows;
  }
  else {
    numfiles_layout += layout->flow_columns;
  }

  filelist_file_cache_slidingwindow_set(files, numfiles_layout);

  align = (FILE_IMGDISPLAY == params->display) ? ui::UI_STYLE_TEXT_CENTER : ui::UI_STYLE_TEXT_LEFT;

  if (numfiles > 0) {
    const bool success = filelist_file_cache_block(
        files, min_ii(offset + (numfiles_layout / 2), numfiles - 1));
    BLI_assert(success);
    UNUSED_VARS_NDEBUG(success);

    filelist_cache_previews_update(files);

    /* Handle preview timer here,
     * since it's filelist_file_cache_block() and filelist_cache_previews_update()
     * which controls previews task.
     * Note that online assets don't use this system.
     */
    {
      const bool previews_running = filelist_cache_previews_running(files) &&
                                    !filelist_cache_previews_done(files);
      //          printf("%s: preview task: %d\n", __func__, previews_running);
      if (previews_running && !sfile->previews_timer) {
        sfile->previews_timer = WM_event_timer_add_notifier(
            wm, win, NC_SPACE | ND_SPACE_FILE_PREVIEW, 0.01);
      }
      if (!previews_running && sfile->previews_timer) {
        /* Preview is not running, no need to keep generating update events! */
        //              printf("%s: Inactive preview task, sleeping!\n", __func__);
        WM_event_timer_remove_notifier(wm, win, sfile->previews_timer);
        sfile->previews_timer = nullptr;
      }
    }
  }

  BLF_batch_draw_begin();

  ui::theme::get_color_4ubv(TH_TEXT, text_col);

  const bool filelist_loading = !filelist_is_ready(files);

  for (i = offset; (i < numfiles) && (i < offset + numfiles_layout); i++) {
    const int padx = 0.1f * UI_UNIT_X;
    int icon_ofs = 0;

    const rcti tile_draw_rect = tile_draw_rect_get(v2d, layout, i);

    file = filelist_file(files, i);
    eDirEntry_SelectFlag file_selflag = filelist_entry_select_get(sfile->files, file, CHECK_ALL);
    if (params->highlight_file == i) {
      file_selflag |= FILE_SEL_HIGHLIGHTED;
    }

    char path[FILE_MAX_LIBEXTRA];
    filelist_file_get_full_path(files, file, path);

    if (!(file_selflag & FILE_SEL_EDITING)) {
      if (file_selflag & (FILE_SEL_HIGHLIGHTED | FILE_SEL_SELECTED)) {
        int colorid = (file_selflag & FILE_SEL_SELECTED) ? TH_HILITE : TH_BACK;
        int shade = (file_selflag & FILE_SEL_HIGHLIGHTED) ? 35 : 0;
        BLI_assert(i == 0 || !FILENAME_IS_CURRPAR(file->relpath));

        draw_tile_background(&tile_draw_rect, colorid, shade);
      }
    }
    draw_roundbox_corner_set(ui::CNR_NONE);

    /* don't drag parent or refresh items */
    do_drag = !FILENAME_IS_CURRPAR(file->relpath);
    const bool is_hidden = (file->attributes & FILE_ATTR_HIDDEN);

    if (FILE_IMGDISPLAY == params->display) {
      if ((file->typeflag & FILE_TYPE_ASSET_ONLINE) && !filelist_loading) {
        filelist_online_asset_preview_request(C, file);
        /* Trigger the preview loader to wait until the download is done and load the preview from
         * disk. Has to be done explicitly here because the preview isn't attached to a button. */
        if (!file->asset->is_local_id()) {
          if (PreviewImage *preview = file->asset->get_preview()) {
            ui::icon_render_id_ex(C, nullptr, nullptr, ICON_SIZE_PREVIEW, true, preview);
          }
        }
      }

      const int file_type_icon = filelist_geticon_file_type(files, i, false);
      std::optional<IconBufferRef> preview_buf = file->preview_icon_id ?
                                                     BKE_icon_get_buffer(file->preview_icon_id,
                                                                         ICON_SIZE_PREVIEW) :
                                                     std::nullopt;

      bool has_special_file_image = false;

      const bool is_loading = filelist_file_is_preview_pending(files, file);
      if (is_loading) {
        file_draw_loading_icon(&tile_draw_rect, thumb_icon_aspect, layout);
      }
      else if (preview_buf) {
        file_draw_preview(file, &tile_draw_rect, *preview_buf, layout, is_hidden);
      }
      else {
        /* Larger folder or document icon, with file/folder type icon in the middle (if any). */
        file_draw_special_image(
            file, &tile_draw_rect, file_type_icon, thumb_icon_aspect, layout, is_hidden);
        has_special_file_image = true;
      }

      file_draw_indicator_icons(files,
                                file,
                                layout,
                                &tile_draw_rect,
                                thumb_icon_aspect,
                                file_type_icon,
                                has_special_file_image,
                                file_selflag);

      if (do_drag) {
        file_add_preview_drag_but(
            sfile, block, layout, file, path, &tile_draw_rect, file_type_icon);
      }

      const bool is_highlighted = file_selflag & (FILE_SEL_HIGHLIGHTED | FILE_SEL_HIGHLIGHTED);
      if (is_highlighted && file->asset && file->asset->needs_download()) {
        file_add_asset_download_but(block, layout, file, &tile_draw_rect);
      }
    }
    else {
      const BIFIconID icon = [&]() {
        if (file->asset) {
          file->asset->ensure_previewable(*C);

          if (filelist_loading) {
            return BIFIconID(ICON_PREVIEW_LOADING);
          }
          return ed::asset::asset_preview_or_icon(*file->asset);
        }
        return filelist_geticon_file_type(files, i, true);
      }();

      icon_ofs += layout->prv_w + 2 * padx;

      /* Add dummy draggable button covering the icon and the label. */
      if (do_drag) {
        const uiStyle *style = ui::style_get();
        const int str_width = ui::fontstyle_string_width(&style->widget, file->name);
        const int drag_width = std::min(
            str_width + icon_ofs,
            int(layout->attribute_columns[COLUMN_NAME].width - ATTRIBUTE_COLUMN_PADDING));
        if (drag_width > 0) {
          /* Uses full row height (tile height plus 2 * tile border padding) so there's no space
           * between rows. */
          ui::Button *drag_but = uiDefBut(block,
                                          ui::ButtonType::Label,
                                          "",
                                          tile_draw_rect.xmin,
                                          tile_draw_rect.ymin - layout->tile_border_y,
                                          drag_width,
                                          layout->tile_h + layout->tile_border_y * 2,
                                          nullptr,
                                          0,
                                          0,
                                          std::nullopt);
          button_dragflag_enable(drag_but, ui::BUT_DRAG_FULL_BUT);
          file_but_enable_drag(drag_but, sfile, file, path, nullptr, icon, UI_SCALE_FAC);
          file_but_tooltip_func_set(sfile, file, drag_but);
        }
      }

      /* Add this after the fake draggable button, so the icon button tooltip is displayed. */
      ui::Button *icon_but = file_add_icon_but(sfile,
                                               block,
                                               path,
                                               file,
                                               &tile_draw_rect,
                                               icon,
                                               layout->prv_w,
                                               layout->prv_h,
                                               padx,
                                               is_hidden);
      if (do_drag) {
        /* For some reason the dragging is unreliable for the icon button if we don't explicitly
         * enable dragging, even though the dummy drag button above covers the same area. */
        file_but_enable_drag(icon_but, sfile, file, path, nullptr, icon, UI_SCALE_FAC);
      }

      if (layout->prv_w >= round_fl_to_int(ICON_DEFAULT_WIDTH_SCALE * 2) &&
          (filelist_loading || icon >= BIFICONID_LAST_STATIC))
      {
        const BIFIconID type_icon = filelist_geticon_file_type(files, i, true);
        file_add_overlay_icon_but(block,
                                  tile_draw_rect.xmin + padx - 2,
                                  tile_draw_rect.ymin - 2 * UI_SCALE_FAC,
                                  type_icon);
      }
    }

    const rcti text_rect = text_draw_rect_get(
        v2d, eFileDisplayType(params->display), layout, i, icon_ofs);

    if (file_selflag & FILE_SEL_EDITING) {
      const int but_height =
          (params->display == FILE_IMGDISPLAY) ?
              layout->text_line_height * 1.4f :
              /* Just a little smaller than the tile height, clamped to #UI_UNIT_Y as maximum. */
              std::min(short(BLI_rcti_size_y(&text_rect) - 1.0f * UI_SCALE_FAC), UI_UNIT_Y);
      ui::Button *but = uiDefBut(block,
                                 ui::ButtonType::Text,
                                 "",
                                 text_rect.xmin,
                                 /* First line only, when name is displayed in multiple lines. */
                                 text_rect.ymax - but_height,
                                 BLI_rcti_size_x(&text_rect),
                                 but_height,
                                 params->renamefile,
                                 1.0f,
                                 float(sizeof(params->renamefile)),
                                 "");
      button_retval_set(but, 1);
      text_button_func_rename_set(but, renamebutton_cb);
      button_flag_enable(but, ui::BUT_NO_UTF8); /* Allow non UTF8 names. */
      button_flag_disable(but, ui::BUT_UNDO);
      if (false == button_active_only(C, region, block, but)) {
        /* Note that this is the only place where we can also handle a cancelled renaming. */

        file_params_rename_end(wm, win, sfile, file);

        /* After the rename button is removed, we need to make sure the view is redrawn once more,
         * in case selection changed. Usually UI code would trigger that redraw, but the rename
         * operator may have been called from a different region.
         * Tagging regions for redrawing while drawing is rightfully prevented. However, this
         * active button removing basically introduces handling logic to drawing code. So a
         * notifier should be an acceptable workaround. */
        WM_event_add_notifier_ex(wm, win, NC_SPACE | ND_SPACE_FILE_PARAMS, nullptr);

        file_selflag = filelist_entry_select_get(sfile->files, file, CHECK_ALL);
      }
    }

    /* file_selflag might have been modified by branch above. */
    if ((file_selflag & FILE_SEL_EDITING) == 0) {
      if (layout->text_lines_count == 1) {
        file_draw_string(text_rect.xmin,
                         text_rect.ymax,
                         file->name,
                         BLI_rcti_size_x(&text_rect),
                         BLI_rcti_size_y(&text_rect),
                         align,
                         text_col);
      }
      else {
        file_draw_string_mulitline_clipped(&text_rect, file->name, align, text_col);
      }
    }

    if (params->display != FILE_IMGDISPLAY) {
      draw_details_columns(params, layout, file, &tile_draw_rect, text_col);
    }
  }

  if (numfiles < 1) {
    const rcti tile_draw_rect = tile_draw_rect_get(v2d, layout, 0);
    const uiStyle *style = ui::style_get();

    const bool is_filtered = params->filter_search[0] != '\0';

    uchar text_col_mod[4];
    copy_v4_v4_uchar(text_col_mod, text_col);
    if (!is_filtered) {
      text_col_mod[3] /= 2;
    }

    const char *message = [&]() {
      if (!filelist_is_ready(files)) {
        return IFACE_("Loading...");
      }
      if (is_filtered) {
        return IFACE_("No results match the search filter");
      }
      FileAssetSelectParams *asset_params = ED_fileselect_get_asset_params(sfile);
      if (asset_params && (asset_params->asset_access == AssetAccess::OnlyOnline)) {
        return IFACE_("No items. Note: The \"Only Online\" filter option is enabled.");
      }
      if (asset_params && (asset_params->asset_access == AssetAccess::OnlyOffline)) {
        return IFACE_("No items. Note: The \"Only Offline\" filter option is enabled.");
      }
      return IFACE_("No items");
    }();

    ui::fontstyle_draw_simple(&style->widget,
                              tile_draw_rect.xmin + UI_UNIT_X,
                              tile_draw_rect.ymax - UI_UNIT_Y,
                              message,
                              text_col_mod);
  }

  BLF_batch_draw_end();

  block_end(C, block);
  block_draw(C, block);

  /* Draw last, on top of file list. */
  if (draw_columnheader) {
    draw_fixed_header_background(v2d, layout->attribute_column_header_h);
    draw_columnheader_columns(params, layout, v2d, text_col);
  }

  if (numfiles != -1) {
    /* Only save current size if there is something to show. */
    layout->curr_size = layout->width;
  }
}

void file_draw_banner(const bContext *C, const SpaceFile *sfile, ARegion *region)
{
  /* Passed into lambda as block idname. */
  static const char *funcname = __func__;

  file_banners_for_first_visible(*sfile, [&](const BannerType &banner) {
    draw_fixed_header_background(&region->v2d, sfile->layout->offset_top);

    ui::Block *block = block_begin(C, region, funcname, ui::EmbossType::Emboss);
    ui::Layout &layout = ui::block_layout(
        block,
        ui::LayoutDirection::Vertical,
        ui::LayoutType::Panel,
        sfile->layout->tile_border_x,
        -sfile->layout->tile_border_y + region->v2d.cur.ymax,
        std::max(0, region->winx - 2 * sfile->layout->tile_border_x),
        0,
        0,
        ui::style_get_dpi());

    banner.layout(*sfile, layout.row(false));

    block_layout_resolve(block);
    block_end(C, block);
    block_draw(C, block);
  });
}

static void file_draw_invalid_asset_library_hint(const bContext *C,
                                                 const SpaceFile *sfile,
                                                 ARegion *region,
                                                 FileAssetSelectParams *asset_params)
{
  char library_ui_path[FILE_MAX_LIBEXTRA];
  file_path_to_ui_path(asset_params->base_params.dir, library_ui_path, sizeof(library_ui_path));

  uchar text_col[4];
  ui::theme::get_color_4ubv(TH_TEXT, text_col);

  const View2D *v2d = &region->v2d;
  const int pad = sfile->layout->tile_border_x;
  const int width = BLI_rctf_size_x(&v2d->tot) - (2 * pad);
  const int line_height = sfile->layout->text_line_height;
  int sx = v2d->tot.xmin + pad;
  /* For some reason no padding needed. */
  int sy = v2d->tot.ymax;

  {
    const char *message = RPT_("Path to asset library does not exist:");
    file_draw_string_multiline(sx, sy, message, width, line_height, text_col, nullptr, &sy);

    sy -= line_height;
    file_draw_string(
        sx, sy, library_ui_path, width, line_height, ui::UI_STYLE_TEXT_LEFT, text_col);
  }

  /* Separate a bit further. */
  sy -= line_height * 2.2f;

  {
    ui::icon_draw(sx, sy - UI_UNIT_Y, ICON_INFO);

    const char *suggestion = RPT_(
        "Asset Libraries are local directories that can contain .blend files with assets inside.\n"
        "Manage Asset Libraries from the Asset Libraries section in the Preferences");
    file_draw_string_multiline(
        sx + UI_UNIT_X, sy, suggestion, width - UI_UNIT_X, line_height, text_col, nullptr, &sy);

    ui::Block *block = block_begin(C, region, __func__, ui::EmbossType::Emboss);
    wmOperatorType *ot = WM_operatortype_find("SCREEN_OT_userpref_show", false);
    ui::Button *but = uiDefIconTextButO_ptr(block,
                                            ui::ButtonType::But,
                                            ot,
                                            wm::OpCallContext::InvokeDefault,
                                            ICON_PREFERENCES,
                                            WM_operatortype_name(ot, nullptr),
                                            sx + UI_UNIT_X,
                                            sy - line_height - UI_UNIT_Y * 1.2f,
                                            UI_UNIT_X * 8,
                                            UI_UNIT_Y,
                                            std::nullopt);
    PointerRNA *but_opptr = button_operator_ptr_ensure(but);
    RNA_enum_set(but_opptr, "section", USER_SECTION_ASSETS);

    block_end(C, block);
    block_draw(C, block);
  }
}

static void file_draw_asset_library_internet_access_required_hint(const bContext *C,
                                                                  const SpaceFile *sfile,
                                                                  ARegion *region)
{
  using namespace blender;

  uchar text_col[4];
  ui::theme::get_color_4ubv(TH_TEXT, text_col);

  const View2D *v2d = &region->v2d;
  const int pad_x = sfile->layout->tile_border_x * 2;
  const int pad_y = sfile->layout->tile_border_y * 2;
  const int available_width = BLI_rctf_size_x(&v2d->tot) - (2 * pad_x);
  const int line_height = sfile->layout->text_line_height;
  const char *message = RPT_(
      "Allow Online Access in order to browse and download online assets, or turn off the "
      "\"Remote Assets\" filter to show only the downloaded assets.\n\nYou can adjust this "
      "later from the \"System\" preferences.");

  const int box_width = std::min(available_width, UI_UNIT_X * 28);
  /* The width we have available inside the box. */
  const int wrap_width = box_width - 2 * pad_x;
  const rcti message_textbox = file_measure_string_multiline(message, wrap_width);
  /* The text box doesn't seem to encompass all text, apparently half a line too little. */
  const int message_height = BLI_rcti_size_y(&message_textbox) + 0.5f * line_height;

  const int heading_height = UI_UNIT_Y;
  const int box_height = heading_height + message_height +
                         /* Extra spacing after header and after main message. */
                         2 * pad_y +
                         /* Button height. */
                         UI_UNIT_Y +
                         /* Top and bottom padding. */
                         2 * pad_y;

  int sx = round_fl_to_int(BLI_rctf_cent_x(&v2d->tot) - box_width / 2.0f);
  int sy = round_fl_to_int(BLI_rctf_cent_y(&v2d->tot) + box_height / 2.0f);

  ui::Block *block = ui::block_begin(C, region, __func__, ui::EmbossType::Emboss);

  uiDefBut(block,
           ui::ButtonType::Roundbox,
           "",
           sx,
           sy - box_height,
           box_width,
           box_height,
           nullptr,
           0.0,
           0.0,
           "");

  /* Top left padding within the box. */
  sx += pad_x;
  sy -= pad_y;

  {
    uiDefIconTextBut(block,
                     ui::ButtonType::Label,
                     ICON_INTERNET_OFFLINE,
                     "Internet Access Required",
                     sx,
                     sy - heading_height,
                     wrap_width,
                     heading_height,
                     nullptr,
                     {});

    const int button_width = (wrap_width - pad_x) * 0.5f;
    ui::Button *but = uiDefIconTextButO(block,
                                        ui::ButtonType::But,
                                        "WM_OT_context_set_boolean",
                                        wm::OpCallContext::InvokeDefault,
                                        ICON_X,
                                        "Continue Offline",
                                        sx,
                                        sy + pad_y - box_height + pad_y,
                                        button_width,
                                        UI_UNIT_Y,
                                        {});
    PointerRNA *but_opptr = ui::button_operator_ptr_ensure(but);
    RNA_string_set(but_opptr, "data_path", "preferences.extensions.use_online_access_handled");
    RNA_boolean_set(but_opptr, "value", true);

    uiDefIconTextButO(block,
                      ui::ButtonType::But,
                      "extensions.userpref_allow_online",
                      wm::OpCallContext::InvokeDefault,
                      ICON_CHECKMARK,
                      "Allow Online Access",
                      sx + button_width + pad_x,
                      sy + pad_y - box_height + pad_y,
                      button_width,
                      UI_UNIT_Y,
                      {});
  }

  ui::block_end(C, block);
  ui::block_draw(C, block);

  /* Draw multi-line text on top of widget drawing. */
  file_draw_string_multiline(sx,
                             sy - heading_height - pad_y,
                             message,
                             wrap_width,
                             line_height,
                             text_col,
                             nullptr,
                             nullptr);
}

static void file_draw_asset_library_remote_loading_failed_hint(const bContext *C,
                                                               const SpaceFile *sfile,
                                                               ARegion *region,
                                                               const bUserAssetLibrary *library)
{
  using namespace blender;

  uchar text_col[4];
  ui::theme::get_color_4ubv(TH_TEXT, text_col);

  const View2D *v2d = &region->v2d;
  const int pad_x = sfile->layout->tile_border_x * 2;
  const int pad_y = sfile->layout->tile_border_y * 2;
  const int available_width = BLI_rctf_size_x(&v2d->tot) - (2 * pad_x);
  const int line_height = sfile->layout->text_line_height;
  StringRefNull message =
      RemoteLibraryLoadingStatus::failure_message(library->remote_url).value_or("Unknown reason");

  const int message_width = ui::fontstyle_string_width(&ui::style_get()->widget, message.c_str());
  const int box_width = std::min({available_width, UI_UNIT_X * 28, message_width + (2 * pad_x)});
  /* The width we have available inside the box. */
  const int wrap_width = box_width - 2 * pad_x;
  const rcti message_textbox = file_measure_string_multiline(message, wrap_width);
  /* The text box doesn't seem to encompass all text, apparently half a line too little. */
  const int message_height = BLI_rcti_size_y(&message_textbox) + 0.5f * line_height;

  const int heading_height = UI_UNIT_Y;
  const int box_height = heading_height + message_height +
                         /* Extra spacing after header. */
                         pad_y +
                         /* Top and bottom padding. */
                         2 * pad_y;

  int sx = round_fl_to_int(BLI_rctf_cent_x(&v2d->tot) - box_width / 2.0f);
  int sy = round_fl_to_int(BLI_rctf_cent_y(&v2d->tot) + box_height / 2.0f);

  ui::Block *block = ui::block_begin(C, region, __func__, ui::EmbossType::Emboss);

  uiDefBut(block,
           ui::ButtonType::Roundbox,
           "",
           sx,
           sy - box_height,
           box_width,
           box_height,
           nullptr,
           0.0,
           0.0,
           "");

  /* Top left padding within the box. */
  sx += pad_x;
  sy -= pad_y;

  {
    uiDefIconTextBut(block,
                     ui::ButtonType::Label,
                     ICON_CANCEL,
                     "Asset Library Download Failed",
                     sx,
                     sy - heading_height,
                     wrap_width,
                     heading_height,
                     nullptr,
                     {});
  }

  ui::block_end(C, block);
  ui::block_draw(C, block);

  /* Draw multi-line text on top of widget drawing. */
  file_draw_string_multiline(sx,
                             sy - heading_height - pad_y,
                             message,
                             wrap_width,
                             line_height,
                             text_col,
                             nullptr,
                             nullptr);
}

static void file_draw_invalid_library_hint(const bContext * /*C*/,
                                           const SpaceFile *sfile,
                                           ARegion *region,
                                           const char *blendfile_path,
                                           ReportList *reports)
{
  uchar text_col[4];
  ui::theme::get_color_4ubv(TH_TEXT, text_col);

  const View2D *v2d = &region->v2d;
  const int pad = sfile->layout->tile_border_x;
  const int width = BLI_rctf_size_x(&v2d->tot) - (2 * pad);
  const int line_height = sfile->layout->text_line_height;
  int sx = v2d->tot.xmin + pad;
  /* For some reason no padding needed. */
  int sy = v2d->tot.ymax;

  {
    const char *message = RPT_("Unreadable Blender library file:");
    file_draw_string_multiline(sx, sy, message, width, line_height, text_col, nullptr, &sy);

    sy -= line_height;
    file_draw_string(sx, sy, blendfile_path, width, line_height, ui::UI_STYLE_TEXT_LEFT, text_col);
  }

  /* Separate a bit further. */
  sy -= line_height * 2.2f;

  for (Report &report : reports->list) {
    const short report_type = report.type;
    if (report_type <= RPT_INFO) {
      continue;
    }

    int icon = ICON_INFO;
    if (report_type > RPT_WARNING) {
      icon = ICON_ERROR;
    }
    ui::icon_draw(sx, sy - UI_UNIT_Y, icon);

    file_draw_string_multiline(sx + UI_UNIT_X,
                               sy,
                               RPT_(report.message),
                               width - UI_UNIT_X,
                               line_height,
                               text_col,
                               nullptr,
                               &sy);
    sy -= line_height;
  }
}

static const bUserAssetLibrary *assetlib_as_remote_library(
    const AssetLibraryReference &asset_library_ref)
{
  if (asset_library_ref.type != ASSET_LIBRARY_CUSTOM) {
    return nullptr;
  }

  const bUserAssetLibrary *library = BKE_preferences_asset_library_find_index(
      &U, asset_library_ref.custom_library_index);
  if (!library) {
    return nullptr;
  }

  const bool is_remote_lib = library->flag & ASSET_LIBRARY_USE_REMOTE_URL;
  if (!is_remote_lib) {
    return nullptr;
  }

  return library;
}

bool file_draw_hint_if_invalid(const bContext *C, const SpaceFile *sfile, ARegion *region)
{
  char blendfile_path[FILE_MAX_LIBEXTRA];
  const bool is_asset_browser = ED_fileselect_is_asset_browser(sfile);
  const bool is_library_browser = !is_asset_browser &&
                                  filelist_islibrary(sfile->files, blendfile_path, nullptr);
  /* Call this before drawing a hint, otherwise drawing will not be visible. */
  const auto setup_view = [region]() {
    ui::view2d_totRect_set(&region->v2d, region->winx, region->winy);
    ui::view2d_view_ortho(&region->v2d);
  };

  if (is_asset_browser) {
    FileAssetSelectParams *asset_params = ED_fileselect_get_asset_params(sfile);

    const bUserAssetLibrary *remote_library = assetlib_as_remote_library(
        asset_params->asset_library_ref);
    const bool is_remote_library = remote_library != nullptr;

    if (is_remote_library) {
      /* With remote libraries, there may be already-downloaded assets available that should be
       * displayed. Don't show the "internet access required" hint until done loading, and only if
       * there are no already-downloaded assets to display. */
      if (!filelist_is_ready(sfile->files) || !filelist_files_num_entries(sfile->files)) {
        return false;
      }

      const bool is_online_allowed = G.f & G_FLAG_INTERNET_ALLOW;
      const bool was_choice_made = U.extension_flag & USER_EXTENSION_FLAG_ONLINE_ACCESS_HANDLED;
      if (!is_online_allowed && !was_choice_made) {
        setup_view();
        file_draw_asset_library_internet_access_required_hint(C, sfile, region);
        return true;
      }
      if (RemoteLibraryLoadingStatus::status(remote_library->remote_url) ==
          RemoteLibraryLoadingStatus::Failure)
      {
        setup_view();
        file_draw_asset_library_remote_loading_failed_hint(C, sfile, region, remote_library);
        return true;
      }
    }

    const bool is_on_disk_library = !ELEM(asset_params->asset_library_ref.type,
                                          ASSET_LIBRARY_LOCAL,
                                          ASSET_LIBRARY_ALL) &&
                                    !is_remote_library;

    /* Check if the asset library exists. */
    if (is_on_disk_library && !filelist_is_dir(sfile->files, asset_params->base_params.dir)) {
      setup_view();
      file_draw_invalid_asset_library_hint(C, sfile, region, asset_params);
      return true;
    }
  }

  /* Check if the blendfile library is valid (has entries). */
  if (is_library_browser) {
    if (!filelist_is_ready(sfile->files)) {
      return false;
    }

    const int numfiles = filelist_files_num_entries(sfile->files);
    if (numfiles > 0) {
      return false;
    }

    /* This could all be part of the file-list loading:
     *   - When loading fails this could be saved in the file-list, e.g. when
     *     `BLO_blendhandle_from_file()` returns null in `filelist_readjob_list_lib()`, a
     *     `FL_HAS_INVALID_LIBRARY` file-list flag could be set.
     *   - Reports from it could also be stored in `FileList` rather than being ignored
     *     (`RPT_STORE` must be set!).
     *   - Then we could just check for `is_library_browser` and the `FL_HAS_INVALID_LIBRARY` flag
     *     here, and draw the hint with the reports in the file-list. (We would not draw a hint for
     *     recursive loading, even if the file-list has the "has invalid library" flag set, which
     *     seems like the wanted behavior.)
     *   - The call to BKE_blendfile_is_readable() would not be needed then.
     */
    if (!sfile->runtime->is_blendfile_status_set) {
      BKE_reports_clear(&sfile->runtime->is_blendfile_readable_reports);
      sfile->runtime->is_blendfile_readable = BKE_blendfile_is_readable(
          blendfile_path, &sfile->runtime->is_blendfile_readable_reports);
      sfile->runtime->is_blendfile_status_set = true;
    }
    if (!sfile->runtime->is_blendfile_readable) {
      setup_view();
      file_draw_invalid_library_hint(
          C, sfile, region, blendfile_path, &sfile->runtime->is_blendfile_readable_reports);
      return true;
    }
  }

  return false;
}

}  // namespace blender
