Skip to content

A games launcher for GOG, Amazon and Epic Games for Linux, Windows and macOS.

35.0 KB
Raw Blame
import {
  faDownload,
  faHardDrive,
  faSpinner
} from '@fortawesome/free-solid-svg-icons'
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'

import classNames from 'classnames'
import {
  GameInfo,
  GameStatus,
  InstallInfo,
  InstallPlatform,
  Runner,
  WineInstallation
} from 'common/types'
import {
  SelectiveDownload,
  DLCInfo as LegendaryDLCInfo
} from 'common/types/legendary'
import { BuildItem, DLCInfo as GOGDLCInfo } from 'common/types/gog'
import { ZoomInstallInfo } from 'common/types/zoom'
import {
  canInstallZoomSelection,
  carryZoomSelection,
  hasSelectedGameFile,
  selectedZoomFileGroups,
  shouldShowZoomCollections,
  ZoomFileGroups,
  zoomFilesBytes
} from 'common/zoomFiles'
import {
  PathSelectionBox,
  SettingsCard,
  TabPanel,
  Tabs,
  ToggleSwitch
} from 'frontend/components/UI'
import type { TabItem } from 'frontend/components/UI/Tabs'
import Anticheat from 'frontend/components/UI/Anticheat'
import { getFortniteLinuxConfirmOptions } from 'frontend/components/UI/Anticheat/FortniteLinux'
import {
  ModalHeader,
  ModalFooter,
  ModalContent
} from 'frontend/components/UI/Modal'
import Button from 'frontend/components/UI/Button'
import {
  getProgress,
  size,
  getInstallInfo,
  writeConfig,
  getPreferredInstallLanguage
} from 'frontend/helpers'
import { install } from 'frontend/helpers/library'
import { isUsingGamepad } from 'frontend/helpers/gamepad'
import {
  GAMEPAD_TABLIST_EVENT,
  rememberGamepadTabListForFocus
} from 'frontend/helpers/settingsFocus'
import ContextProvider from 'frontend/state/ContextProvider'
import { InstallProgress } from 'frontend/types'
import React, {
  useCallback,
  useContext,
  useEffect,
  useMemo,
  useRef,
  useState
} from 'react'
import { useTranslation } from 'react-i18next'
import { AvailablePlatforms } from '../index'
import { configStore } from 'frontend/helpers/electronStores'
import DLCDownloadListing from './DLCDownloadListing'
import BuildSelector from './BuildSelector'
import GameLanguageSelector from './GameLanguageSelector'
import SteamLibrarySelector from './SteamLibrarySelector'
import { SteamInstallLibrary } from 'common/types/steam'
import { hasAnticheatInfo } from 'frontend/hooks/hasAnticheatInfo'
import { anticheatConfirmationFor } from 'frontend/helpers/anticheat'
import BranchSelector from './BranchSelector'
import ZoomCollections, { type ZoomCollectionsStatus } from './ZoomCollections'
import AnticheatDisabledMessage from './AnticheatDisabledMessage'
import { getVisibleInstallTabs, InstallTab } from './installTabs'
import { openInstallGameModal } from 'frontend/state/InstallGameModal'

interface Props {
  backdropClick: () => void
  appName: string
  runner: Runner
  platformToInstall: InstallPlatform
  setPlatformToInstall: (platform: InstallPlatform) => void
  availablePlatforms: AvailablePlatforms
  winePrefix: string
  crossoverBottle: string
  wineVersion: WineInstallation | undefined
  wineSelectionValid: boolean
  platformSelection: React.ReactNode
  wineSelector?: React.ReactNode
  gameInfo: GameInfo
}

type DiskSpaceInfo = {
  notEnoughDiskSpace: boolean
  message: string
  validPath: boolean
  validFlatpakPath: boolean
  spaceLeftAfter: string
}

const storage: Storage = window.localStorage

function getUniqueKey(sdl: SelectiveDownload) {
  if (sdl.tags) {
    return sdl.tags.join(',')
  }
  return ''
}

const userHome = configStore.get('userHome', '')

function getDefaultInstallPath() {
  const { defaultInstallPath = `${userHome}/Games/Heroic` } = {
    ...configStore.get_nodefault('settings')
  }
  return defaultInstallPath
}

export default function DownloadDialog({
  backdropClick,
  appName,
  runner,
  platformToInstall,
  setPlatformToInstall,
  availablePlatforms,
  winePrefix,
  wineVersion,
  wineSelectionValid,
  platformSelection,
  wineSelector,
  gameInfo,
  crossoverBottle
}: Props) {
  const previousProgress = JSON.parse(
    storage.getItem(appName) || '{}'
  ) as InstallProgress
  const { libraryStatus, platform, showDialogModal } =
    useContext(ContextProvider)

  const isWin = platform === 'win32'
  const isSteam = runner === 'steam'

  const [gameInstallInfo, setGameInstallInfo] = useState<InstallInfo | null>(
    null
  )
  const [installLanguages, setInstallLanguages] = useState(Array<string>())
  const [installLanguage, setInstallLanguage] = useState('')
  const [languageLocales, setLanguageLocales] = useState<
    Record<string, string> | undefined
  >()

  const [diskSize, setDiskSize] = useState(0)

  const [gameBuilds, setBuilds] = useState<BuildItem[]>([])
  const [selectedBuild, setSelectedBuild] = useState<string | undefined>()

  const [savedBranchPassword, setSavedBranchPassword] = useState<string>('')
  const [branches, setBranches] = useState<Array<string | null>>([])
  const [branch, setBranch] = useState<string | undefined>()

  const [installPath, setInstallPath] = useState(
    previousProgress.folder || getDefaultInstallPath()
  )
  const gameStatus: GameStatus = libraryStatus.filter(
    (game: GameStatus) => game.appName === appName
  )[0]

  const [steamLibraries, setSteamLibraries] = useState<
    SteamInstallLibrary[] | null
  >(null)

  const [dlcsToInstall, setDlcsToInstall] = useState<string[]>([])
  const [sdls, setSdls] = useState<SelectiveDownload[]>([])
  const [selectedSdls, setSelectedSdls] = useState<{ [key: string]: boolean }>(
    {}
  )
  const [gettingInstallInfo, setGettingInstallInfo] = useState(false)

  const isZoom = runner === 'zoom'
  const [zoomFiles, setZoomFiles] = useState<ZoomFileGroups>({
    game: [],
    extras: []
  })
  const [selectedZoomFiles, setSelectedZoomFiles] = useState<string[]>([])
  const [zoomFilesError, setZoomFilesError] = useState<string | null>(null)
  const [zoomFilesLoaded, setZoomFilesLoaded] = useState(false)
  const [zoomRetryKey, setZoomRetryKey] = useState(0)

  function focusPlatformPicker() {
    const picker = document.getElementById('platformPick')
    if (!picker) return

    picker.scrollIntoView({ block: 'center', behavior: 'smooth' })
    picker.focus({ preventScroll: true })
  }

  const handleZoomFileToggle = useCallback((fileId: string) => {
    setSelectedZoomFiles((current) =>
      current.includes(fileId)
        ? current.filter((id) => id !== fileId)
        : [...current, fileId]
    )
  }, [])

  const [activeTab, setActiveTab] = useState<InstallTab>('installation')
  const panelAreaRef = useRef<HTMLDivElement>(null)

  const installFolder = gameStatus?.folder || installPath

  const [spaceLeft, setSpaceLeft] = useState<DiskSpaceInfo>({
    message: '',
    notEnoughDiskSpace: false,
    validPath: true,
    validFlatpakPath: true,
    spaceLeftAfter: ''
  })

  const anticheatInfo = hasAnticheatInfo(gameInfo)

  const { i18n, t } = useTranslation('gamepage')
  const { t: tr } = useTranslation()

  const haveSDL = sdls.length > 0

  const sdlList = useMemo(() => {
    const list = []
    if (haveSDL) {
      for (const sdl of sdls) {
        if (sdl.required || selectedSdls[getUniqueKey(sdl)]) {
          if (Array.isArray(sdl.tags)) {
            list.push(...sdl.tags)
          }
        }
      }
    }
    return list
  }, [selectedSdls, sdls])

  useEffect(() => {
    async function get() {
      const branchPassword = await window.api.getPrivateBranchPassword(
        gameInfo.app_name
      )
      setSavedBranchPassword(branchPassword)
    }
    get()
  }, [])

  const handleSdl = useCallback(
    (sdl: SelectiveDownload, value: boolean) => {
      setSelectedSdls({
        ...selectedSdls,
        [getUniqueKey(sdl)]: value
      })
    },
    [selectedSdls]
  )

  async function confirmInstallBrokenAnticheat(path?: string) {
    const { allowInstallationBrokenAnticheat } =
      await window.api.requestAppSettings()
    const title = t(
      'install.anticheat-warning.title',
      'Anticheat Broken/Denied'
    )
    if (allowInstallationBrokenAnticheat) {
      showDialogModal({
        title,
        message: t(
          'install.anticheat-warning.multiplayer_message',
          'The anticheat support is broken or denied. The game may open but the multiplayer features will not work. Do you want to install it anyway?'
        ),
        buttons: [
          {
            text: t(
              'install.anticheat-warning.install_anyway',
              'Yes (I understand the multiplayer features will not work)'
            ),
            onClick: async () => handleInstall(path, true)
          },
          {
            text: t('install.anticheat-warning.cancel', 'No'),
            onClick: () => null
          }
        ]
      })
    } else {
      showDialogModal({
        title,
        message: <AnticheatDisabledMessage />,
        buttons: [
          {
            text: t('install.anticheat-warning.ok', 'Ok'),
            onClick: () => null
          }
        ]
      })
    }
  }

  async function handleInstall(path?: string, ignoreAnticheat = false) {
    if (!wineSelectionValid) return

    if (
      isZoom &&
      !canInstallZoomSelection(
        zoomFiles,
        selectedZoomFiles,
        zoomFilesError,
        zoomFilesLoaded
      )
    ) {
      return
    }

    const confirmation = ignoreAnticheat
      ? null
      : anticheatConfirmationFor(anticheatInfo, platform, {
          appName: gameInfo.app_name,
          runner: gameInfo.runner
        })

    if (confirmation === 'fortnite') {
      showDialogModal(getFortniteLinuxConfirmOptions(tr, handleInstall, path))
      return
    }

    if (confirmation === 'generic') {
      void confirmInstallBrokenAnticheat(path)
      return
    }

    backdropClick()

    // Write Default game config with prefix on linux
    if (!isWin) {
      const gameSettings = await window.api.requestGameSettings(appName)

      if (wineVersion) {
        writeConfig({
          appName,
          config: {
            ...gameSettings,
            winePrefix,
            wineVersion,
            wineCrossoverBottle: crossoverBottle
          }
        })
      }
    }

    return install({
      gameInfo,
      installPath: path || installFolder,
      isInstalling: false,
      previousProgress,
      progress: previousProgress,
      t,
      sdlList,
      installDlcs: dlcsToInstall,
      installLanguage,
      platformToInstall,
      build: selectedBuild,
      branch,
      zoomFileIds: selectedZoomFiles,
      showDialogModal: () => backdropClick()
    })
  }

  function handleSwitchToImport() {
    backdropClick()
    openInstallGameModal({
      appName,
      runner,
      gameInfo,
      action: 'import'
    })
  }

  useEffect(() => {
    const getInstInfo = async () => {
      try {
        const fetchedPlatform = platformToInstall
        const fetchedBuild = selectedBuild
        setGettingInstallInfo(true)
        if (isZoom) {
          setZoomFilesError(null)
          setZoomFilesLoaded(false)
        }
        const gameInstallInfo = await getInstallInfo(
          appName,
          runner,
          platformToInstall,
          selectedBuild,
          branch
        )

        const noContent =
          gameInstallInfo?.manifest &&
          gameInstallInfo?.manifest.disk_size === 0 &&
          gameInstallInfo.manifest.download_size === 0

        // Steam: the current platform was auto-selected, but this game has no
        // depots for it (dry-run reports 0 sizes). Fall back to Windows (run via
        // Proton) instead of declaring the game uninstallable.
        if (
          noContent &&
          isSteam &&
          platformToInstall !== 'Windows' &&
          availablePlatforms.some((p) => p.value === 'Windows')
        ) {
          setPlatformToInstall('Windows')
          return
        }

        if (isZoom && !gameInstallInfo) {
          setZoomFilesError(
            tr('zoom.collections.loadError', 'Could not load the files.')
          )
          setZoomFilesLoaded(true)
          setGettingInstallInfo(false)
          return
        }

        if (noContent && !isZoom) {
          showDialogModal({
            showDialog: true,
            title: t(
              'label.game.not-installable-game',
              'Game is NOT Installable'
            ),
            message: t(
              'status.gog-goodie',
              "This game doesn't appear to be installable. Check downloadable content on https://gog.com/account"
            ),
            buttons: [
              {
                text: tr('box.ok')
              }
            ],
            type: 'MESSAGE'
          })
          backdropClick()
          return
        }

        if (isZoom) {
          const zoomInfo = gameInstallInfo as ZoomInstallInfo | null
          const files = zoomInfo?.files ?? { game: [], extras: [] }
          setZoomFilesError(null)
          setZoomFilesLoaded(true)
          setZoomFiles(files)
          setSelectedZoomFiles((previous) =>
            carryZoomSelection(files, previous, zoomInfo?.installedFileIds)
          )
        }

        setGameInstallInfo(gameInstallInfo)
        setGettingInstallInfo(false)

        // Prevent condition when user changes the platform before we reach this point
        if (
          platformToInstall !== fetchedPlatform ||
          fetchedBuild !== selectedBuild
        ) {
          return
        }
        const dlcs: string[] = []
        if (
          gameInstallInfo &&
          'game' in gameInstallInfo &&
          gameInstallInfo.game.owned_dlc
        ) {
          gameInstallInfo.game.owned_dlc.forEach((dlc) =>
            dlcs.push(dlc.app_name)
          )
        }
        setDlcsToInstall(dlcs)
        if (gameInstallInfo && gameInstallInfo.manifest) {
          setDiskSize(gameInstallInfo.manifest?.disk_size ?? 0)
        }

        if (gameInstallInfo) {
          if (
            gameInstallInfo.manifest &&
            'builds' in gameInstallInfo.manifest
          ) {
            const builds = (gameInstallInfo.manifest.builds || [])
              .filter(
                // We either take branch when both are falsy (null | undefined)
                // or when they are equal
                (build) => (!branch && !build.branch) || build.branch === branch
              )
              .sort(
                (a, b) =>
                  new Date(b.date_published).getTime() -
                  new Date(a.date_published).getTime()
              )
            setBuilds(builds)
          }

          const manifest = gameInstallInfo.manifest
          if (
            manifest &&
            'languages' in manifest &&
            manifest.languages?.length
          ) {
            const languages = [...manifest.languages].sort()
            setInstallLanguages(languages)
            // Steam: Aurelia's default goes first
            const preferred =
              'default_language' in manifest
                ? manifest.default_language
                : undefined
            if (!languages.includes(installLanguage)) {
              setInstallLanguage(
                preferred ??
                  getPreferredInstallLanguage(languages, i18n.languages)
              )
            }
            setLanguageLocales(
              'language_locales' in manifest
                ? manifest.language_locales
                : undefined
            )
          } else if (isSteam) {
            // Older Aurelia lists no languages
            setInstallLanguages([])
            setInstallLanguage('')
          }

          if (
            gameInstallInfo.manifest &&
            'game' in gameInstallInfo &&
            'branches' in gameInstallInfo.game
          ) {
            setBranches(gameInstallInfo.game.branches || [])
          }
        }
      } catch (error) {
        if (isZoom) {
          console.error(error)
          setGettingInstallInfo(false)
          setZoomFilesLoaded(true)
          setZoomFilesError(
            tr('zoom.collections.loadError', 'Could not load the files.')
          )
          return
        }
        showDialogModal({
          type: 'ERROR',
          title: tr('box.error.generic.title', 'Error!'),
          message: `${tr('box.error.generic.message', 'Something Went Wrong!')}
          ${error}`
        })
        backdropClick()
        return
      }
    }
    void getInstInfo()
  }, [
    appName,
    i18n.languages,
    isZoom,
    platformToInstall,
    selectedBuild,
    branch,
    savedBranchPassword,
    zoomRetryKey
  ])

  useEffect(() => {
    if (!isSteam) return
    let cancelled = false
    void window.api
      .getSteamInstallLibraries()
      .then((libraries) => {
        if (cancelled) return
        setSteamLibraries(libraries)
        if (!libraries.length) return
        const configuredPath =
          gameInstallInfo &&
          'game' in gameInstallInfo &&
          'path' in gameInstallInfo.game
            ? gameInstallInfo.game.path
            : ''
        const preselected =
          libraries.find((lib) => configuredPath.startsWith(lib.path))?.path ??
          libraries[0].path
        setInstallPath(preselected)
      })
      .catch((error) => {
        if (cancelled) return
        window.api.logError(`Could not load Steam libraries: ${error}`)
        setSteamLibraries([])
      })
    return () => {
      cancelled = true
    }
  }, [isSteam, gameInstallInfo])

  useEffect(() => {
    const getGameSdl = async () => {
      if (runner === 'legendary') {
        const { sdl_config } = await window.api.getGameOverride()
        if (sdl_config && sdl_config[appName]) {
          const sdl = await window.api.getGameSdl(appName)
          if (sdl.length > 0) {
            setSdls(sdl)
          }
        }
      }
    }
    getGameSdl()
  }, [appName, runner])

  useEffect(() => {
    const getSpace = async () => {
      const { message, free, validPath, validFlatpakPath } =
        await window.api.checkDiskSpace(installPath)
      if (diskSize) {
        let notEnoughDiskSpace = free < diskSize
        let spaceLeftAfter = size(free - Number(diskSize))
        if (previousProgress.folder === installPath) {
          const progress = 100 - getProgress(previousProgress)
          notEnoughDiskSpace = free < (progress / 100) * diskSize

          spaceLeftAfter = size(free - (progress / 100) * diskSize)
        }

        setSpaceLeft({
          message,
          notEnoughDiskSpace,
          validPath,
          validFlatpakPath,
          spaceLeftAfter
        })
      }
    }
    getSpace()
  }, [installPath, diskSize])

  const DLCList: Array<GOGDLCInfo | LegendaryDLCInfo> =
    (gameInstallInfo &&
      'game' in gameInstallInfo &&
      gameInstallInfo?.game?.owned_dlc) ||
    []

  const downloadSize = useMemo(() => {
    if (isZoom) {
      if (zoomFilesError) return '—'
      if (!zoomFilesLoaded) return ''
      if (!zoomFiles.game.length && !zoomFiles.extras.length) return size(0)
      const selected = selectedZoomFileGroups(zoomFiles, selectedZoomFiles)
      return size(zoomFilesBytes([...selected.game, ...selected.extras]))
    }
    if (
      gameInstallInfo &&
      gameInstallInfo.manifest &&
      'perLangSize' in gameInstallInfo.manifest &&
      gameInstallInfo.manifest.perLangSize
    ) {
      const languageSize =
        gameInstallInfo?.manifest?.perLangSize[installLanguage]
          ?.download_size ?? 0
      const universalSize =
        gameInstallInfo?.manifest?.perLangSize['*']?.download_size ?? 0

      const dlcSize = DLCList.reduce((acc, dlc) => {
        if (dlcsToInstall.includes(dlc.app_name) && 'perLangSize' in dlc) {
          const languageSize =
            dlc.perLangSize[installLanguage]?.download_size ?? 0
          const universalSize = dlc.perLangSize['*']?.download_size ?? 0
          acc += languageSize + universalSize
        }
        return acc
      }, 0)

      return size(languageSize + universalSize + dlcSize)
    }

    if (
      gameInstallInfo?.manifest &&
      'tag_download_size' in gameInstallInfo.manifest
    ) {
      let total = 0
      for (const tag of sdlList) {
        total +=
          gameInstallInfo.manifest.tag_download_size.find(
            (tds) => tds.tag === tag
          )?.size ?? 0
      }
      return size(total)
    }

    if (gameInstallInfo?.manifest?.download_size) {
      if (previousProgress.folder === installPath) {
        const progress = 100 - getProgress(previousProgress)
        return size(
          (progress / 100) * Number(gameInstallInfo.manifest.disk_size)
        )
      }

      return size(Number(gameInstallInfo?.manifest?.download_size))
    }
    return ''
  }, [
    installPath,
    gameInstallInfo,
    installLanguage,
    dlcsToInstall,
    isZoom,
    zoomFiles,
    selectedZoomFiles,
    zoomFilesLoaded,
    zoomFilesError,
    sdlList
  ])

  const installSize = useMemo(() => {
    if (isZoom) {
      if (zoomFilesError) return '—'
      if (!zoomFilesLoaded) return ''
      if (!zoomFiles.game.length && !zoomFiles.extras.length) return size(0)
      const selected = selectedZoomFileGroups(zoomFiles, selectedZoomFiles)
      return size(zoomFilesBytes([...selected.game, ...selected.extras]))
    }
    if (
      gameInstallInfo &&
      gameInstallInfo.manifest &&
      'perLangSize' in gameInstallInfo.manifest &&
      gameInstallInfo.manifest.perLangSize
    ) {
      const languageSize =
        gameInstallInfo?.manifest?.perLangSize[installLanguage]?.disk_size ?? 0
      const universalSize =
        gameInstallInfo?.manifest?.perLangSize['*']?.disk_size ?? 0
      const dlcSize = DLCList.reduce((acc, dlc) => {
        if (dlcsToInstall.includes(dlc.app_name) && 'perLangSize' in dlc) {
          const languageSize = dlc.perLangSize[installLanguage]?.disk_size ?? 0
          const universalSize = dlc.perLangSize['*']?.disk_size ?? 0
          acc += languageSize + universalSize
        }
        return acc
      }, 0)
      setDiskSize(languageSize + universalSize + dlcSize)
      return size(languageSize + universalSize + dlcSize)
    }

    if (gameInstallInfo?.manifest) {
      if ('tag_disk_size' in gameInstallInfo.manifest) {
        let total = 0
        for (const tag of sdlList) {
          total +=
            gameInstallInfo.manifest.tag_disk_size.find(
              (tds) => tds.tag === tag
            )?.size ?? 0
        }
        return size(total)
      }

      return size(gameInstallInfo.manifest.disk_size)
    }

    return ''
  }, [
    gameInstallInfo,
    installLanguage,
    platformToInstall,
    dlcsToInstall,
    isZoom,
    zoomFiles,
    selectedZoomFiles,
    zoomFilesLoaded,
    zoomFilesError,
    sdlList
  ])

  const {
    validPath,
    validFlatpakPath,
    notEnoughDiskSpace,
    message,
    spaceLeftAfter
  } = spaceLeft
  const title = gameInfo?.title

  function getInstallLabel() {
    if (installPath) {
      if (notEnoughDiskSpace) {
        return t('button.force-innstall', 'Force Install')
      } else {
        return previousProgress.folder === installPath
          ? t('button.continue', 'Continue Download')
          : t('button.install')
      }
    }
    return t('button.no-path-selected', 'No path selected')
  }

  const zoomSelectionReady = canInstallZoomSelection(
    zoomFiles,
    selectedZoomFiles,
    zoomFilesError,
    zoomFilesLoaded
  )
  const zoomCollectionsLoading = isZoom && !zoomFilesLoaded
  const zoomCollectionsEmpty =
    isZoom &&
    zoomFilesLoaded &&
    !zoomFilesError &&
    !zoomFiles.game.length &&
    !zoomFiles.extras.length
  const zoomCollectionsStatus: ZoomCollectionsStatus = zoomFilesError
    ? 'error'
    : zoomCollectionsLoading
      ? 'loading'
      : zoomCollectionsEmpty
        ? 'empty'
        : 'ready'
  const zoomSelectionHint =
    isZoom &&
    zoomCollectionsStatus === 'ready' &&
    !hasSelectedGameFile(zoomFiles, selectedZoomFiles)
      ? tr(
          'zoom.collections.selectOne',
          'Select at least one game file to continue.'
        )
      : ''
  const steamLibrariesReady = !isSteam || !!steamLibraries?.length
  const showInstallSpinner =
    gettingInstallInfo ||
    (!isZoom && !diskSize) ||
    (isZoom && !zoomFilesLoaded) ||
    (isSteam && steamLibraries === null)
  const readyToInstall = isZoom
    ? !!installPath &&
      !gettingInstallInfo &&
      validFlatpakPath &&
      zoomSelectionReady &&
      wineSelectionValid &&
      steamLibrariesReady
    : installPath &&
      !!diskSize &&
      !gettingInstallInfo &&
      validFlatpakPath &&
      wineSelectionValid &&
      steamLibrariesReady

  const hasDlcs = DLCList.length > 0
  const hasWine = Boolean(wineSelector)

  const installTabs = getVisibleInstallTabs({
    hasComponents: haveSDL,
    hasDlcs,
    hasWine
  })

  useEffect(() => {
    if (!installTabs.includes(activeTab)) {
      setActiveTab('installation')
    }
  }, [activeTab, installTabs])

  // Hand the install tabs to the controller when the dialog opens with one in
  // use. Focus may sit on the close button, so seed the tablist instead of
  // moving focus: the first L2/R2 works and the hint shows right away.
  useEffect(() => {
    if (installTabs.length <= 1 || !isUsingGamepad()) return

    const frame = requestAnimationFrame(() => {
      const tablist = document.querySelector<HTMLElement>(
        '.InstallModal__tabs[role="tablist"]'
      )
      if (!tablist) return

      rememberGamepadTabListForFocus(tablist)
      window.dispatchEvent(new Event(GAMEPAD_TABLIST_EVENT))
    })

    return () => cancelAnimationFrame(frame)
  }, [installTabs.length])

  const changeTab = (value: InstallTab) => {
    setActiveTab(value)
    panelAreaRef.current?.scrollTo({ top: 0 })
  }

  const tabLabels: Record<InstallTab, string> = {
    installation: t('install.tabs.installation', 'Installation'),
    components: t('install.tabs.components', 'Components'),
    dlcs: t('install.tabs.dlcs', 'DLCs'),
    wine: t('install.tabs.wine', 'Wine')
  }

  const tabItems: Array<TabItem<InstallTab>> = installTabs.map((value) => ({
    value,
    label: tabLabels[value]
  }))

  const sizeChips = (
    <>
      <div className="InstallModal__size">
        <FontAwesomeIcon
          className={classNames('InstallModal__sizeIcon', {
            'fa-spin-pulse': !downloadSize
          })}
          icon={downloadSize ? faDownload : faSpinner}
        />
        {downloadSize ? (
          <>
            <div className="InstallModal__sizeLabel">
              {t('game.downloadSize', 'Download Size')}:
            </div>
            <div className="InstallModal__sizeValue">{downloadSize}</div>
          </>
        ) : (
          `${t('game.getting-download-size', 'Geting download size')}...`
        )}
      </div>
      {!isZoom && (
        <div className="InstallModal__size">
          <FontAwesomeIcon
            className={classNames('InstallModal__sizeIcon', {
              'fa-spin-pulse': !downloadSize
            })}
            icon={downloadSize ? faHardDrive : faSpinner}
          />
          {downloadSize ? (
            <>
              <div className="InstallModal__sizeLabel">
                {t('game.installSize', 'Install Size')}:
              </div>
              <div className="InstallModal__sizeValue">{installSize}</div>
            </>
          ) : (
            `${t('game.getting-install-size', 'Geting install size')}...`
          )}
        </div>
      )}
      {previousProgress.folder === installPath && (
        <div className="InstallModal__size">
          <FontAwesomeIcon
            className="InstallModal__sizeIcon"
            icon={faSpinner}
          />
          <div className="InstallModal__sizeLabel">
            {t('status.totalDownloaded', 'Total Downloaded')}:
          </div>
          <div className="InstallModal__sizeValue">
            {getProgress(previousProgress)}%
          </div>
        </div>
      )}
    </>
  )

  const installationContent = (
    <>
      {platformSelection}
      {installLanguages && installLanguages?.length > 1 && (
        <GameLanguageSelector
          installPlatform={platformToInstall}
          installLanguage={installLanguage}
          setInstallLanguage={setInstallLanguage}
          installLanguages={installLanguages}
          languageLocales={languageLocales}
        />
      )}

      {isSteam ? (
        steamLibraries && (
          <SteamLibrarySelector
            libraries={steamLibraries}
            selectedPath={installPath}
            onChange={setInstallPath}
          />
        )
      ) : (
        <PathSelectionBox
          type="directory"
          onPathChange={setInstallPath}
          path={installPath}
          placeholder={getDefaultInstallPath()}
          pathDialogTitle={t('install.path')}
          pathDialogDefaultPath={getDefaultInstallPath()}
          htmlId="setinstallpath"
          label={t('install.path', 'Select Install Path')}
          noDeleteButton
          afterInput={
            downloadSize ? (
              <span className="smallInputInfo">
                {validPath && validFlatpakPath && (
                  <>
                    <span>
                      {`${t('install.disk-space-left', 'Space Available')}: `}
                    </span>
                    <span>
                      <strong>{`${message}`}</strong>
                    </span>
                    {!notEnoughDiskSpace && (
                      <>
                        <span>
                          {` - ${t(
                            'install.space-after-install',
                            'After Install'
                          )}: `}
                        </span>
                        <span>
                          <strong>{`${spaceLeftAfter}`}</strong>
                        </span>
                      </>
                    )}
                  </>
                )}
                {!validPath && (
                  <span className="warning">
                    {`${t(
                      'install.path-not-writtable',
                      'Warning: path might not be writable.'
                    )}`}
                  </span>
                )}
                {validPath && !validFlatpakPath && (
                  <span className="error">
                    {`${t(
                      'install.flatpak-path-not-writtable',
                      'Error: Sandbox access not granted to this path, data loss will occur.'
                    )}`}
                  </span>
                )}
                {validPath && notEnoughDiskSpace && (
                  <span className="warning">
                    {` (${t(
                      'install.not-enough-disk-space',
                      'Not enough disk space'
                    )})`}
                  </span>
                )}
              </span>
            ) : null
          }
        />
      )}

      {platformToInstall !== 'linux' && branches.length > 1 && (
        <div>
          <BranchSelector
            appName={gameInfo.app_name}
            branches={branches}
            branch={branch}
            setBranch={setBranch}
            savedBranchPassword={savedBranchPassword}
            onPasswordChange={(newPasswd) => setSavedBranchPassword(newPasswd)}
          />
        </div>
      )}

      {platformToInstall !== 'linux' && !!gameBuilds.length && (
        <div>
          <BuildSelector
            gameBuilds={gameBuilds}
            selectedBuild={selectedBuild}
            setSelectedBuild={setSelectedBuild}
          />
        </div>
      )}

      {isZoom &&
        (zoomCollectionsLoading ||
          !!zoomFilesError ||
          shouldShowZoomCollections(zoomFiles)) && (
          <ZoomCollections
            files={zoomFiles}
            selectedIds={selectedZoomFiles}
            status={zoomCollectionsStatus}
            error={zoomFilesError}
            onToggle={handleZoomFileToggle}
            onRetry={() => setZoomRetryKey((key) => key + 1)}
            canChangePlatform={availablePlatforms.length > 1}
            onChangePlatform={focusPlatformPicker}
            onClose={backdropClick}
          />
        )}
    </>
  )

  const componentsContent = (
    <SettingsCard title={t('sdl.title', 'Select components to Install')}>
      {sdls.map((sdl: SelectiveDownload, idx: number) => (
        <ToggleSwitch
          key={sdl.name}
          htmlId={`sdls-${idx}`}
          title={
            sdl.required
              ? `${sdl.name} (${t('install.components.required', 'Required')})`
              : sdl.name
          }
          description={sdl.description}
          value={!!sdl.required || !!selectedSdls[getUniqueKey(sdl)]}
          disabled={sdl.required}
          handleChange={(e) => handleSdl(sdl, e.target.checked)}
        />
      ))}
    </SettingsCard>
  )

  return (
    <>
      <ModalHeader
        meta={<div className="InstallModal__sizes">{sizeChips}</div>}
      >
        {title ? title : '...'}
        {availablePlatforms.map((p) => (
          <FontAwesomeIcon
            className="InstallModal__platformIcon"
            icon={p.icon}
            key={p.value}
          />
        ))}
      </ModalHeader>
      <Anticheat
        anticheatInfo={anticheatInfo}
        compact
        appName={gameInfo.app_name}
        runner={gameInfo.runner}
      />
      <ModalContent className="InstallModal__content">
        {installTabs.length > 1 && (
          <Tabs
            items={tabItems}
            value={activeTab}
            onChange={changeTab}
            aria-label={t('install.tabs.ariaLabel', 'Install sections')}
            idPrefix="install-tab"
            className="InstallModal__tabs"
            gamepadNavigation
          />
        )}
        <div className="InstallModal__panelArea" ref={panelAreaRef}>
          {installTabs.length > 1 ? (
            <TabPanel
              value={activeTab}
              idPrefix="install-tab"
              index="installation"
            >
              {installationContent}
            </TabPanel>
          ) : (
            installationContent
          )}
          {haveSDL && (
            <TabPanel
              value={activeTab}
              idPrefix="install-tab"
              index="components"
            >
              {componentsContent}
            </TabPanel>
          )}
          {hasDlcs && (
            <TabPanel value={activeTab} idPrefix="install-tab" index="dlcs">
              <DLCDownloadListing
                DLCList={DLCList}
                dlcsToInstall={dlcsToInstall}
                setDlcsToInstall={setDlcsToInstall}
              />
            </TabPanel>
          )}
          {hasWine && (
            <TabPanel
              value={activeTab}
              idPrefix="install-tab"
              index="wine"
              keepMounted
            >
              {wineSelector}
            </TabPanel>
          )}
        </div>
      </ModalContent>
      {zoomSelectionHint && (
        <p
          className="InstallModal__zoomHint"
          id="zoom-select-hint"
          aria-live="polite"
        >
          {zoomSelectionHint}
        </p>
      )}
      <ModalFooter>
        <Button
          onClick={async () => handleInstall()}
          disabled={!readyToInstall}
          aria-describedby={zoomSelectionHint ? 'zoom-select-hint' : undefined}
          icon={
            showInstallSpinner ? (
              <FontAwesomeIcon className="fa-spin-pulse" icon={faSpinner} />
            ) : null
          }
        >
          {getInstallLabel()}
        </Button>
        {!isSteam && (
          <Button variant="secondary" onClick={handleSwitchToImport}>
            {t('button.import', 'Import Game')}
          </Button>
        )}
      </ModalFooter>
    </>
  )
}