std::wstring FormatFilterForExtensions()

in libcef/browser/native/file_dialog_runner_win.cc [66:156]


std::wstring FormatFilterForExtensions(
    const std::vector<std::wstring>& file_ext,
    const std::vector<std::wstring>& ext_desc,
    bool include_all_files) {
  const std::wstring all_ext = L"*.*";
  const std::wstring all_desc =
      base::UTF16ToWide(l10n_util::GetStringUTF16(IDS_APP_SAVEAS_ALL_FILES)) +
      L" (" + all_ext + L")";

  DCHECK(file_ext.size() >= ext_desc.size());

  if (file_ext.empty())
    include_all_files = true;

  std::wstring result;

  // Create all supported .ext filter if more than one filter.
  if (file_ext.size() > 1) {
    std::set<base::WStringPiece> unique_exts;
    for (const auto& exts : file_ext) {
      for (const auto& ext : base::SplitStringPiece(
               exts, L";", base::TRIM_WHITESPACE, base::SPLIT_WANT_NONEMPTY)) {
        unique_exts.insert(ext);
      }
    }

    if (unique_exts.size() > 1) {
      std::wstring ext;
      auto it = unique_exts.cbegin();
      ext = std::wstring(*it);
      for (++it; it != unique_exts.cend(); ++it) {
        ext += L";" + std::wstring(*it);
      }
      std::wstring desc =
          base::UTF16ToWide(l10n_util::GetStringUTF16(IDS_CUSTOM_FILES)) +
          L" (" + ext + L")";

      result.append(desc.c_str(), desc.size() + 1);  // Append NULL too.
      result.append(ext.c_str(), ext.size() + 1);
    }
  }

  for (size_t i = 0; i < file_ext.size(); ++i) {
    std::wstring ext = file_ext[i];
    std::wstring desc;
    if (i < ext_desc.size())
      desc = ext_desc[i];

    if (ext.empty()) {
      // Force something reasonable to appear in the dialog box if there is no
      // extension provided.
      include_all_files = true;
      continue;
    }

    if (desc.empty()) {
      DCHECK(ext.find(L'.') != std::wstring::npos);
      std::wstring first_extension = ext.substr(ext.find(L'.'));
      size_t first_separator_index = first_extension.find(L';');
      if (first_separator_index != std::wstring::npos)
        first_extension = first_extension.substr(0, first_separator_index);

      // Find the extension name without the preceeding '.' character.
      std::wstring ext_name = first_extension;
      size_t ext_index = ext_name.find_first_not_of(L'.');
      if (ext_index != std::wstring::npos)
        ext_name = ext_name.substr(ext_index);

      if (!GetRegistryDescriptionFromExtension(first_extension, &desc)) {
        // The extension doesn't exist in the registry.
        include_all_files = true;
      }
    }

    if (!desc.empty())
      desc += L" (" + ext + L")";
    else
      desc = ext;

    result.append(desc.c_str(), desc.size() + 1);  // Append NULL too.
    result.append(ext.c_str(), ext.size() + 1);
  }

  if (include_all_files) {
    result.append(all_desc.c_str(), all_desc.size() + 1);
    result.append(all_ext.c_str(), all_ext.size() + 1);
  }

  result.append(1, '\0');  // Double NULL required.
  return result;
}