feat: instances v2 (#6431)

* feat: base of instances v2

* feat: use old profiles with compat layer

* prototype: instances v2

* fix: install_from using profile

* fix: skins migration fix

* fix: frontend still using profile path

* fix: add update proj multiselect guard

* fix: cargo fmt

* fix: content missing fields

* feat: break up app-lib/api/instance.rs

* fix: check_content_updates mismatch

* fix: updater modal cleanup w/new structure

* feat: better update all handling

* fix: remove preview_update_all

* fix: feedback on bulk update + lint

* fix: rem transitions

* fix: change to jsonb

* feat: app db backup after update

* fix: lint

* fix: sqlx prepare + use sqlx macros

* fix: lint

* fix: bugs

* feat: defuck the installing process up

* fix: bug of hell

* fix: shear

* fix: fmt

* fix: install progress spacing + change mc/content/overrides to bytes

* fix: lint

* fix: prepr

* fix: navtabs anim not working in app

* fix: worlds.vue improvements + browse page fixes

* feat: optimise queries + adapter fns

* fix: lint

* fix: lint

* feat: shared modrinth-content-management crate (#6469)

* feat: disable warnings setting

* feat: add instances shortcuts (#6329)

* Add modrinth://launch deep link to start a profile

Support external profile launching via modrinth://launch/{profile_path} for integrations such as Stream Deck.

* Change route to /launch/profile/{id} for future extensibility

* fix: ensure profile path is url decoded

* fix: URL-decode profile path from deep link

* fix: use urlencoding crate for URL decoding

* feat: implement app instance shortcuts

* feat: change windows shortcut creation to use windows api instead

* feat: implement creating a shortcut launching world/server

* format

* fmt

* fix multiline inline tables

* pnpm prepr

* feat: move create shortcut to last item

* refactor: split up shortcuts.rs for individual platforms

* refactor: turn profile launch url into url type

* use string literal and add safety comment

* pt2

* refactor: rename anything that's profile into instance

* update mac shortcut

---------

Co-authored-by: DJCheesusReal <134006619+DJCheesusReal@users.noreply.github.com>

---------

Co-authored-by: Truman Gao <106889354+tdgao@users.noreply.github.com>
Co-authored-by: DJCheesusReal <134006619+DJCheesusReal@users.noreply.github.com>
This commit is contained in:
Calum H.
2026-06-25 21:19:29 +00:00
committed by GitHub
co-authored by DJCheesusReal Truman Gao
parent ef4044534f
commit 734720e11e
353 changed files with 24745 additions and 9771 deletions
Generated
+15 -1
View File
@@ -5372,6 +5372,7 @@ dependencies = [
"labrinth",
"lettre",
"meilisearch-sdk",
"modrinth-content-management",
"modrinth-util",
"muralpay",
"murmur2",
@@ -5947,6 +5948,17 @@ dependencies = [
"windows-sys 0.59.0",
]
[[package]]
name = "modrinth-content-management"
version = "0.0.0"
dependencies = [
"async-trait",
"chrono",
"serde",
"thiserror 2.0.17",
"tokio",
]
[[package]]
name = "modrinth-log"
version = "0.0.0"
@@ -10730,9 +10742,9 @@ name = "theseus"
version = "1.0.0-local"
dependencies = [
"ariadne",
"async-compression",
"async-minecraft-ping",
"async-recursion",
"async-trait",
"async-tungstenite",
"async-walkdir",
"async_zip",
@@ -10762,6 +10774,7 @@ dependencies = [
"hickory-resolver 0.25.2",
"indicatif",
"itertools 0.14.0",
"modrinth-content-management",
"notify",
"notify-debouncer-mini",
"p256",
@@ -10794,6 +10807,7 @@ dependencies = [
"tracing-error",
"tracing-subscriber",
"url",
"urlencoding",
"uuid 1.23.3",
"whoami",
"windows",
+2 -1
View File
@@ -9,6 +9,7 @@ members = [
"packages/ariadne",
"packages/daedalus",
"packages/labrinth-derive",
"packages/modrinth-content-management",
"packages/modrinth-log",
"packages/modrinth-maxmind",
"packages/modrinth-util",
@@ -32,7 +33,6 @@ actix-ws = "0.3.0"
arc-swap = "1.7.1"
argon2 = { version = "0.5.3", features = ["std"] }
ariadne = { path = "packages/ariadne" }
async-compression = { version = "0.4.32", default-features = false }
async-minecraft-ping = { path = "packages/async-minecraft-ping" }
async-recursion = "1.1.1"
async-stripe = { version = "0.41.0", default-features = false, features = [
@@ -119,6 +119,7 @@ lettre = { version = "0.11.19", default-features = false, features = [
] }
maxminddb = "0.26.0"
meilisearch-sdk = { version = "0.30.0", default-features = false }
modrinth-content-management = { path = "packages/modrinth-content-management" }
modrinth-log = { path = "packages/modrinth-log" }
modrinth-util = { path = "packages/modrinth-util" }
muralpay = { path = "packages/muralpay" }
+23 -5
View File
@@ -94,9 +94,9 @@ import { debugAnalytics, initAnalytics, trackEvent } from '@/helpers/analytics'
import { check_reachable } from '@/helpers/auth.js'
import { get_user, get_version } from '@/helpers/cache.js'
import { command_listener, notification_listener, warning_listener } from '@/helpers/events.js'
import { install_create_modpack_instance, install_get_modpack_preview } from '@/helpers/install'
import { list, run } from '@/helpers/instance'
import { cancelLogin, get as getCreds, login, logout } from '@/helpers/mr_auth.ts'
import { create_profile_and_install_from_file } from '@/helpers/pack'
import { list } from '@/helpers/profile.js'
import { mergeUrlQuery, parseModrinthLink } from '@/helpers/project-links.ts'
import { get as getSettings, set as setSettings } from '@/helpers/settings.ts'
import { get_opening_command, initialize_state } from '@/helpers/state'
@@ -110,6 +110,7 @@ import {
isNetworkMetered,
setRestartAfterPendingUpdate,
} from '@/helpers/utils.js'
import { start_join_server, start_join_singleplayer_world } from '@/helpers/worlds.ts'
import i18n from '@/i18n.config'
import {
appUpdateState,
@@ -852,13 +853,30 @@ async function handleCommand(e) {
if (e.event === 'RunMRPack') {
// RunMRPack should directly install a local mrpack given a path
if (e.path.endsWith('.mrpack')) {
await create_profile_and_install_from_file(e.path, (createProfile, fileName) =>
unknownPackWarningModal.value?.show(createProfile, fileName),
).catch(handleError)
const location = { type: 'fromFile', path: e.path }
const preview = await install_get_modpack_preview(location).catch(handleError)
if (preview?.unknownFile) {
const splitPath = e.path.split(/[\\/]/)
const fileName = splitPath ? splitPath[splitPath.length - 1] : e.path
unknownPackWarningModal.value?.show(
() => install_create_modpack_instance(location).then(() => undefined),
fileName,
)
} else {
await install_create_modpack_instance(location).catch(handleError)
}
trackEvent('InstanceCreate', {
source: 'CreationModalFileDrop',
})
}
} else if (e.event === 'LaunchInstance') {
if (e.server) {
await start_join_server(e.id, e.server).catch(handleError)
} else if (e.singleplayer_world) {
await start_join_singleplayer_world(e.id, e.singleplayer_world).catch(handleError)
} else {
await run(e.id).catch(handleError)
}
} else if (e.event === 'InstallServer') {
await router.push(`/project/${e.id}`)
await playServerProject(e.id).catch(handleError)
@@ -24,7 +24,8 @@ import { computed, ref } from 'vue'
import ContextMenu from '@/components/ui/ContextMenu.vue'
import Instance from '@/components/ui/Instance.vue'
import ConfirmDeleteInstanceModal from '@/components/ui/modal/ConfirmDeleteInstanceModal.vue'
import { duplicate, remove } from '@/helpers/profile.js'
import { install_duplicate_instance } from '@/helpers/install'
import { remove } from '@/helpers/instance'
const { handleError } = injectNotificationManager()
@@ -48,21 +49,21 @@ const instanceComponents = ref(null)
const currentDeleteInstance = ref(null)
const confirmModal = ref(null)
async function deleteProfile() {
async function deleteInstance() {
if (currentDeleteInstance.value) {
instanceComponents.value = instanceComponents.value.filter(
(x) => x.instance.path !== currentDeleteInstance.value,
(x) => x.instance.id !== currentDeleteInstance.value,
)
await remove(currentDeleteInstance.value).catch(handleError)
}
}
async function duplicateProfile(p) {
await duplicate(p).catch(handleError)
async function duplicateInstance(p) {
await install_duplicate_instance(p).catch(handleError)
}
const handleRightClick = (event, profilePathId) => {
const item = instanceComponents.value.find((x) => x.instance.path === profilePathId)
const handleRightClick = (event, instanceId) => {
const item = instanceComponents.value.find((x) => x.instance.id === instanceId)
const baseOptions = [
{ name: 'add_content' },
{ type: 'divider' },
@@ -114,16 +115,16 @@ const handleOptionsClick = async (args) => {
break
case 'duplicate':
if (args.item.instance.install_stage == 'installed')
await duplicateProfile(args.item.instance.path)
await duplicateInstance(args.item.instance.id)
break
case 'open':
await args.item.openFolder()
break
case 'copy':
await navigator.clipboard.writeText(args.item.instance.path)
await navigator.clipboard.writeText(args.item.instance.id)
break
case 'delete':
currentDeleteInstance.value = args.item.instance.path
currentDeleteInstance.value = args.item.instance.id
confirmModal.value.show()
break
}
@@ -321,13 +322,13 @@ const filteredResults = computed(() => {
<Instance
v-for="instance in instanceSection.value"
ref="instanceComponents"
:key="instance.path + instance.install_stage"
:key="instance.id + instance.install_stage"
:instance="instance"
@contextmenu.prevent.stop="(event) => handleRightClick(event, instance.path)"
@contextmenu.prevent.stop="(event) => handleRightClick(event, instance.id)"
/>
</section>
</Accordion>
<ConfirmDeleteInstanceModal ref="confirmModal" @delete="deleteProfile" />
<ConfirmDeleteInstanceModal ref="confirmModal" @delete="deleteInstance" />
<ContextMenu ref="instanceOptions" @option-clicked="handleOptionsClick">
<template #play> <PlayIcon /> Play </template>
<template #stop> <StopCircleIcon /> Stop </template>
+18 -19
View File
@@ -21,9 +21,10 @@ import Instance from '@/components/ui/Instance.vue'
import LegacyProjectCard from '@/components/ui/LegacyProjectCard.vue'
import ConfirmDeleteInstanceModal from '@/components/ui/modal/ConfirmDeleteInstanceModal.vue'
import { trackEvent } from '@/helpers/analytics'
import { get_by_profile_path } from '@/helpers/process.js'
import { duplicate, kill, remove, run } from '@/helpers/profile.js'
import { showProfileInFolder } from '@/helpers/utils.js'
import { install_duplicate_instance } from '@/helpers/install'
import { kill, remove, run } from '@/helpers/instance'
import { get_by_instance_id } from '@/helpers/process.js'
import { showInstanceInFolder } from '@/helpers/utils.js'
import { injectContentInstall } from '@/providers/content-install'
import { handleSevereError } from '@/store/error.js'
@@ -60,14 +61,14 @@ const deleteConfirmModal = ref(null)
const currentDeleteInstance = ref(null)
async function deleteProfile() {
async function deleteInstance() {
if (currentDeleteInstance.value) {
await remove(currentDeleteInstance.value).catch(handleError)
}
}
async function duplicateProfile(p) {
await duplicate(p).catch(handleError)
async function duplicateInstance(p) {
await install_duplicate_instance(p).catch(handleError)
}
const handleInstanceRightClick = async (event, passedInstance) => {
@@ -85,7 +86,7 @@ const handleInstanceRightClick = async (event, passedInstance) => {
},
]
const runningProcesses = await get_by_profile_path(passedInstance.path).catch(handleError)
const runningProcesses = await get_by_instance_id(passedInstance.id).catch(handleError)
const options =
runningProcesses.length > 0
@@ -126,16 +127,14 @@ const handleProjectClick = (event, passedInstance) => {
const handleOptionsClick = async (args) => {
switch (args.option) {
case 'play':
await run(args.item.path).catch((err) =>
handleSevereError(err, { profilePath: args.item.path }),
)
await run(args.item.id).catch((err) => handleSevereError(err, { instanceId: args.item.id }))
trackEvent('InstanceStart', {
loader: args.item.loader,
game_version: args.item.game_version,
})
break
case 'stop':
await kill(args.item.path).catch(handleError)
await kill(args.item.id).catch(handleError)
trackEvent('InstanceStop', {
loader: args.item.loader,
game_version: args.item.game_version,
@@ -144,26 +143,26 @@ const handleOptionsClick = async (args) => {
case 'add_content':
await router.push({
path: `/browse/${args.item.loader === 'vanilla' ? 'datapack' : 'mod'}`,
query: { i: args.item.path },
query: { i: args.item.id },
})
break
case 'edit':
await router.push({
path: `/instance/${encodeURIComponent(args.item.path)}`,
path: `/instance/${encodeURIComponent(args.item.id)}`,
})
break
case 'duplicate':
if (args.item.install_stage == 'installed') await duplicateProfile(args.item.path)
if (args.item.install_stage == 'installed') await duplicateInstance(args.item.id)
break
case 'delete':
currentDeleteInstance.value = args.item.path
currentDeleteInstance.value = args.item.id
deleteConfirmModal.value.show()
break
case 'open_folder':
await showProfileInFolder(args.item.path)
await showInstanceInFolder(args.item.id)
break
case 'copy_path':
await navigator.clipboard.writeText(args.item.path)
await navigator.clipboard.writeText(args.item.id)
break
case 'install': {
await installVersion(
@@ -239,7 +238,7 @@ onUnmounted(() => {
</script>
<template>
<ConfirmDeleteInstanceModal ref="deleteConfirmModal" @delete="deleteProfile" />
<ConfirmDeleteInstanceModal ref="deleteConfirmModal" @delete="deleteInstance" />
<div ref="rowContainer" class="flex flex-col gap-4">
<div v-for="row in actualInstances" ref="rows" :key="row.label" class="row">
<HeadingLink class="mt-1" :to="row.route">
@@ -256,7 +255,7 @@ onUnmounted(() => {
0,
row.compact ? maxInstancesPerCompactRow : maxInstancesPerRow,
)"
:key="row.label + instance.path"
:key="row.label + instance.id"
:instance="instance"
:compact="row.compact"
:first="instanceIndex === 0"
@@ -4,7 +4,7 @@ import { ButtonStyled, injectNotificationManager, OverflowMenu } from '@modrinth
import { open } from '@tauri-apps/plugin-dialog'
import { useRouter } from 'vue-router'
import { add_project_from_path } from '@/helpers/profile.js'
import { add_project_from_path } from '@/helpers/instance'
const { handleError } = injectNotificationManager()
@@ -22,14 +22,14 @@ const handleAddContentFromFile = async () => {
if (!newProject) return
for (const project of newProject) {
await add_project_from_path(props.instance.path, project.path ?? project).catch(handleError)
await add_project_from_path(props.instance.id, project.path ?? project).catch(handleError)
}
}
const handleSearchContent = async () => {
await router.push({
path: `/browse/${props.instance.loader === 'vanilla' ? 'resourcepack' : 'mod'}`,
query: { i: props.instance.path },
query: { i: props.instance.id },
})
}
</script>
@@ -47,28 +47,28 @@
<div class="text-contrast flex items-center gap-2">
<router-link
v-tooltip="formatMessage(messages.viewInstance)"
:to="`/instance/${encodeURIComponent(selectedProcess.profile.path)}`"
:to="`/instance/${encodeURIComponent(selectedProcess.instance.id)}`"
class="hover:underline"
>
{{ selectedProcess.profile.name }}
{{ selectedProcess.instance.name }}
</router-link>
<Dropdown
v-if="currentProcesses.length > 1"
placement="bottom"
:triggers="['click']"
:hide-triggers="['click']"
@show="showProfiles = true"
@hide="showProfiles = false"
@show="showInstances = true"
@hide="showInstances = false"
>
<ButtonStyled type="transparent" circular size="small">
<button
v-tooltip="
showProfiles
showInstances
? formatMessage(messages.hideMoreRunningInstances)
: formatMessage(messages.showMoreRunningInstances)
"
>
<DropdownIcon :class="{ 'rotate-180': !!showProfiles }" />
<DropdownIcon :class="{ 'rotate-180': !!showInstances }" />
</button>
</ButtonStyled>
<template #popper>
@@ -93,7 +93,7 @@
>
<OnlineIndicatorIcon />
<span class="mr-auto text-contrast flex items-center gap-2">
{{ process.profile.name }}
{{ process.instance.name }}
<StarIcon v-if="process.uuid === selectedProcess.uuid" class="text-orange" />
</span>
</button>
@@ -107,7 +107,7 @@
<button
v-tooltip="formatMessage(messages.viewLogs)"
class="active:scale-95 flex"
@click.stop="goToTerminal(process.profile.path)"
@click.stop="goToTerminal(process.instance.id)"
>
<TerminalSquareIcon class="text-secondary size-5" />
</button>
@@ -164,10 +164,11 @@ import { Dropdown } from 'floating-vue'
import { computed, nextTick, onBeforeUnmount, onMounted, ref, watch } from 'vue'
import { useRouter } from 'vue-router'
import { useInstallJobNotifications } from '@/composables/browse/install-job-notifications'
import { trackEvent } from '@/helpers/analytics'
import { loading_listener, process_listener } from '@/helpers/events'
import { get_many as getInstances } from '@/helpers/instance'
import { get_all as getRunningProcesses, kill as killProcess } from '@/helpers/process'
import { get_many as getInstances } from '@/helpers/profile.js'
import type { LoadingBar } from '@/helpers/state'
import { progress_bars_list } from '@/helpers/state'
import type { GameInstance } from '@/helpers/types'
@@ -183,12 +184,12 @@ const { formatMessage } = useVIntl()
const router = useRouter()
const showProfiles = ref(false)
const showInstances = ref(false)
interface RunningProcess {
uuid: string
profile_path: string
profile: GameInstance
instance_id: string
instance: GameInstance
}
const messages = defineMessages({
@@ -337,22 +338,22 @@ const refresh = async () => {
const processes = ((await getRunningProcesses().catch((error) => {
handleError(error)
return []
})) ?? []) as Array<{ uuid: string; profile_path: string }>
const paths = processes.map((process) => process.profile_path)
const profiles: GameInstance[] = await getInstances(paths).catch((error) => {
})) ?? []) as Array<{ uuid: string; instance_id: string }>
const instanceIds = processes.map((process) => process.instance_id)
const instances: GameInstance[] = await getInstances(instanceIds).catch((error) => {
handleError(error)
return []
})
currentProcesses.value = processes
.map((process) => {
const profile = profiles.find((item) => process.profile_path === item.path)
if (!profile) {
const instance = instances.find((item) => process.instance_id === item.id)
if (!instance) {
return null
}
return {
...process,
profile,
instance,
}
})
.filter((process): process is RunningProcess => process !== null)
@@ -385,8 +386,8 @@ const stop = async (process: RunningProcess) => {
await killProcess(process.uuid).catch(handleError)
trackEvent('InstanceStop', {
loader: process.profile.loader,
game_version: process.profile.game_version,
loader: process.instance.loader,
game_version: process.instance.game_version,
source: 'AppBar',
})
} catch (e) {
@@ -395,12 +396,12 @@ const stop = async (process: RunningProcess) => {
await refresh()
}
function goToTerminal(path?: string) {
const selectedPath = path ?? selectedProcess.value?.profile.path
if (!selectedPath) {
function goToTerminal(instanceId?: string) {
const selectedInstanceId = instanceId ?? selectedProcess.value?.instance.id
if (!selectedInstanceId) {
return
}
router.push(`/instance/${encodeURIComponent(selectedPath)}/logs`)
router.push(`/instance/${encodeURIComponent(selectedInstanceId)}/logs`)
}
const currentLoadingBars = ref<LoadingBar[]>([])
@@ -420,8 +421,7 @@ function getLoadingProgress(loadingBar: LoadingBar): number {
}
function getLoadingText(loadingBar: LoadingBar): string {
const percent = Math.floor(getLoadingProgress(loadingBar) * 100)
return loadingBar.message ? `${percent}% ${loadingBar.message}` : `${percent}%`
return loadingBar.message ?? ''
}
function getDisplayIconUrl(icon: string | null | undefined): string | null {
@@ -453,25 +453,33 @@ function removeNotification(): void {
}
function buildDownloadItems(): PopupNotificationProgressItem[] {
return currentLoadingBars.value.map((bar) => ({
return [
...installJobNotifications.progressItems.value,
...currentLoadingBars.value.map((bar) => ({
id: getLoadingBarKey(bar),
title: bar.title ?? '',
text: getLoadingText(bar),
iconUrl: currentLoadingBarIconUrls.value[getLoadingBarKey(bar)] ?? null,
progress: getLoadingProgress(bar),
waiting: !bar.total || bar.total <= 0,
}))
progressType: 'percentage',
progressCurrent: bar.current,
progressTotal: bar.total,
})),
]
}
const hasVisibleActiveDownloadToasts = computed(() => !!getNotification())
const hasActiveLoadingBars = computed(() => currentLoadingBars.value.length > 0)
const hasActiveLoadingBars = computed(
() => currentLoadingBars.value.length > 0 || installJobNotifications.active.value,
)
function updateNotification(resummon = false): void {
if (resummon) {
dismissed.value = false
}
if (currentLoadingBars.value.length === 0) {
if (currentLoadingBars.value.length === 0 && !installJobNotifications.active.value) {
removeNotification()
dismissed.value = false
return
@@ -490,17 +498,23 @@ function updateNotification(resummon = false): void {
const progressItems = buildDownloadItems()
if (notif) {
notif.title = formatMessage(messages.downloads)
notif.title = installJobNotifications.active.value
? installJobNotifications.title.value
: formatMessage(messages.downloads)
notif.text = undefined
notif.progressItems = progressItems
notif.buttons = installJobNotifications.buttons.value
notif.progress = undefined
notif.waiting = undefined
} else {
notif = popupNotificationManager.addPopupNotification({
title: formatMessage(messages.downloads),
title: installJobNotifications.active.value
? installJobNotifications.title.value
: formatMessage(messages.downloads),
type: 'download',
autoCloseMs: null,
progressItems,
buttons: installJobNotifications.buttons.value,
})
notificationId.value = notif.id
}
@@ -513,8 +527,8 @@ function formatLoadingBars(loadingBar: LoadingBar): LoadingBar {
version: formatted.bar_type.version,
})
}
if (formatted.bar_type?.profile_path) {
formatted.title = formatted.bar_type.profile_path
if (formatted.bar_type?.instance_id) {
formatted.title = formatted.bar_type.instance_name ?? formatted.bar_type.instance_id
}
if (formatted.bar_type?.pack_name) {
formatted.title = formatted.bar_type.pack_name
@@ -530,31 +544,41 @@ async function refreshLoadingBars() {
currentLoadingBars.value = Object.values(bars)
.map(formatLoadingBars)
.filter((bar) => bar?.bar_type?.type !== 'launcher_update')
.filter(
(bar) =>
bar?.bar_type?.type !== 'launcher_update' &&
![
'java_download',
'pack_file_download',
'pack_download',
'minecraft_download',
'copy_instance',
].includes(bar?.bar_type?.type ?? ''),
)
const profilePaths = Array.from(
const instanceIds = Array.from(
new Set(
currentLoadingBars.value
.map((bar) => bar.bar_type?.profile_path)
.filter((path): path is string => !!path),
.map((bar) => bar.bar_type?.instance_id)
.filter((instanceId): instanceId is string => !!instanceId),
),
)
const profiles = profilePaths.length
? await getInstances(profilePaths).catch((error) => {
const instances = instanceIds.length
? await getInstances(instanceIds).catch((error) => {
handleError(error)
return []
})
: []
const profileIconUrls = new Map(
profiles.map((profile) => [profile.path, getDisplayIconUrl(profile.icon_path)]),
const instanceIconUrls = new Map(
instances.map((instance) => [instance.id, getDisplayIconUrl(instance.icon_path)]),
)
currentLoadingBarIconUrls.value = Object.fromEntries(
currentLoadingBars.value.map((bar) => {
const barIconUrl = getDisplayIconUrl(bar.bar_type?.icon)
const profileIconUrl = bar.bar_type?.profile_path
? profileIconUrls.get(bar.bar_type.profile_path)
const instanceIconUrl = bar.bar_type?.instance_id
? instanceIconUrls.get(bar.bar_type.instance_id)
: null
return [getLoadingBarKey(bar), barIconUrl ?? profileIconUrl ?? null]
return [getLoadingBarKey(bar), barIconUrl ?? instanceIconUrl ?? null]
}),
)
@@ -567,6 +591,12 @@ async function refreshLoadingBars() {
updateNotification()
}
const installJobNotifications = await useInstallJobNotifications({
router,
handleError,
onChange: updateNotification,
})
await refreshLoadingBars()
const unlistenLoading = await loading_listener(async () => {
@@ -588,6 +618,7 @@ onBeforeUnmount(() => {
window.removeEventListener('online', handleOnline)
unlistenProcess()
unlistenLoading()
installJobNotifications.dispose()
if (readyPillAnimationFrame !== null) {
cancelAnimationFrame(readyPillAnimationFrame)
}
@@ -12,7 +12,7 @@
<div v-for="(option, index) in options" :key="index" @click.stop="optionClicked(option.name)">
<hr v-if="option.type === 'divider'" class="divider" />
<div
v-else-if="!(isLinkedData(item) && option.name === `add_content`)"
v-else-if="!(isInstanceLink(item) && option.name === `add_content`)"
class="item clickable"
:class="[option.color ?? 'base']"
>
@@ -64,10 +64,10 @@ defineExpose({
},
})
const isLinkedData = (item) => {
if (item.instance != undefined && item.instance.linked_data) {
const isInstanceLink = (item) => {
if (item.instance != undefined && item.instance.link) {
return true
} else if (item != undefined && item.linked_data) {
} else if (item != undefined && item.link) {
return true
}
return false
@@ -16,7 +16,7 @@ import { ChatIcon } from '@/assets/icons'
import ModalWrapper from '@/components/ui/modal/ModalWrapper.vue'
import { trackEvent } from '@/helpers/analytics'
import { login as login_flow, set_default_user } from '@/helpers/auth.js'
import { install } from '@/helpers/profile.js'
import { install_existing_instance } from '@/helpers/install'
import { cancel_directory_change } from '@/helpers/settings.ts'
import { handleSevereError } from '@/store/error.js'
@@ -72,7 +72,7 @@ defineExpose({
title.value = 'No loader selected'
errorType.value = 'no_loader_version'
supportLink.value = 'https://support.modrinth.com'
metadata.value.profilePath = context.profilePath
metadata.value.instanceId = context.instanceId
} else if (source === 'state_init') {
title.value = 'Error initializing Modrinth App'
errorType.value = 'state_init'
@@ -125,7 +125,7 @@ const loadingRepair = ref(false)
async function repairInstance() {
loadingRepair.value = true
try {
await install(metadata.value.profilePath, false)
await install_existing_instance(metadata.value.instanceId, false)
errorModal.value.hide()
} catch (err) {
handleSevereError(err)
@@ -15,7 +15,7 @@ import { ref } from 'vue'
import { PackageIcon, VersionIcon } from '@/assets/icons'
import ModalWrapper from '@/components/ui/modal/ModalWrapper.vue'
import { export_profile_mrpack, get_pack_export_candidates } from '@/helpers/profile.js'
import { export_instance_mrpack, get_pack_export_candidates } from '@/helpers/instance'
const { handleError } = injectNotificationManager()
const { formatMessage } = useVIntl()
@@ -75,7 +75,7 @@ const initFiles = async () => {
const newFolders = new Map()
const sep = '/'
files.value = []
await get_pack_export_candidates(props.instance.path).then((filePaths) =>
await get_pack_export_candidates(props.instance.id).then((filePaths) =>
filePaths
.map((folder) => ({
path: folder,
@@ -136,8 +136,8 @@ const exportPack = async () => {
})
if (outputPath) {
export_profile_mrpack(
props.instance.path,
export_instance_mrpack(
props.instance.id,
outputPath,
filesToExport,
versionInput.value,
@@ -15,9 +15,10 @@ import { useRouter } from 'vue-router'
import { trackEvent } from '@/helpers/analytics'
import { process_listener } from '@/helpers/events'
import { get_by_profile_path } from '@/helpers/process'
import { finish_install, kill, run } from '@/helpers/profile'
import { showProfileInFolder } from '@/helpers/utils.js'
import { install_existing_instance, install_pack_to_existing_instance } from '@/helpers/install'
import { kill, run } from '@/helpers/instance'
import { get_by_instance_id } from '@/helpers/process'
import { showInstanceInFolder } from '@/helpers/utils.js'
import { handleSevereError } from '@/store/error.js'
const { handleError } = injectNotificationManager()
@@ -54,11 +55,11 @@ const installed = computed(() => props.instance.install_stage === 'installed')
const router = useRouter()
const seeInstance = async () => {
await router.push(`/instance/${encodeURIComponent(props.instance.path)}`)
await router.push(`/instance/${encodeURIComponent(props.instance.id)}`)
}
const checkProcess = async () => {
const runningProcesses = await get_by_profile_path(props.instance.path).catch(handleError)
const runningProcesses = await get_by_instance_id(props.instance.id).catch(handleError)
playing.value = runningProcesses.length > 0
}
@@ -66,8 +67,8 @@ const checkProcess = async () => {
const play = async (e, context) => {
e?.stopPropagation()
loading.value = true
await run(props.instance.path)
.catch((err) => handleSevereError(err, { profilePath: props.instance.path }))
await run(props.instance.id)
.catch((err) => handleSevereError(err, { instanceId: props.instance.id }))
.finally(() => {
trackEvent('InstanceStart', {
loader: props.instance.loader,
@@ -82,7 +83,7 @@ const stop = async (e, context) => {
e?.stopPropagation()
playing.value = false
await kill(props.instance.path).catch(handleError)
await kill(props.instance.id).catch(handleError)
trackEvent('InstanceStop', {
loader: props.instance.loader,
@@ -94,17 +95,30 @@ const stop = async (e, context) => {
const repair = async (e) => {
e?.stopPropagation()
await finish_install(props.instance).catch(handleError)
if (
props.instance.install_stage !== 'pack_installed' &&
(props.instance.link?.type === 'modrinth_modpack' ||
props.instance.link?.type === 'server_project_modpack')
) {
await install_pack_to_existing_instance(props.instance.id, {
type: 'fromVersionId',
project_id: props.instance.link.project_id ?? props.instance.link.server_project_id ?? '',
version_id: props.instance.link.version_id ?? props.instance.link.content_version_id ?? '',
title: props.instance.name,
}).catch(handleError)
} else {
await install_existing_instance(props.instance.id, false).catch(handleError)
}
}
const openFolder = async () => {
await showProfileInFolder(props.instance.path)
await showInstanceInFolder(props.instance.id)
}
const addContent = async () => {
await router.push({
path: `/browse/${props.instance.loader === 'vanilla' ? 'datapack' : 'mod'}`,
query: { i: props.instance.path },
query: { i: props.instance.id },
})
}
@@ -120,7 +134,7 @@ defineExpose({
const currentEvent = ref(null)
const unlisten = await process_listener((e) => {
if (e.profile_path_id === props.instance.path) {
if (e.instance_id === props.instance.id) {
currentEvent.value = e.event
if (e.event === 'finished') {
playing.value = false
@@ -142,7 +156,7 @@ onUnmounted(() => unlisten())
<Avatar
size="48px"
:src="instance.icon_path ? convertFileSrc(instance.icon_path) : null"
:tint-by="instance.path"
:tint-by="instance.id"
alt="Mod card"
/>
<div class="h-full flex items-center font-bold text-contrast leading-normal">
@@ -191,7 +205,7 @@ onUnmounted(() => unlisten())
<Avatar
size="48px"
:src="instance.icon_path ? convertFileSrc(instance.icon_path) : null"
:tint-by="instance.path"
:tint-by="instance.id"
alt="Mod card"
:class="`transition-all ${modLoading || installing ? `brightness-[0.25] scale-[0.85]` : `group-hover:brightness-75`}`"
/>
@@ -22,7 +22,7 @@ const props = withDefaults(
)
const instanceLink = computed(() => {
const base = `/instance/${encodeURIComponent(props.instance.path)}`
const base = `/instance/${encodeURIComponent(props.instance.id)}`
return props.backTab ? `${base}/${props.backTab}` : base
})
</script>
@@ -5,7 +5,7 @@ import { computed, ref } from 'vue'
import { SwapIcon } from '@/assets/icons/index.js'
import ModalWrapper from '@/components/ui/modal/ModalWrapper.vue'
import { update_managed_modrinth_version } from '@/helpers/profile'
import { update_managed_modrinth_version } from '@/helpers/instance'
import { releaseColor } from '@/helpers/utils'
const props = defineProps({
@@ -32,14 +32,14 @@ const filteredVersions = computed(() => {
})
const modpackVersionModal = ref(null)
const installedVersion = computed(() => props.instance?.linked_data?.version_id)
const installedVersion = computed(() => props.instance?.link?.version_id)
const installing = computed(() => props.instance.install_stage !== 'installed')
const inProgress = ref(false)
const switchVersion = async (versionId) => {
modpackVersionModal.value.hide()
inProgress.value = true
await update_managed_modrinth_version(props.instance.path, versionId)
await update_managed_modrinth_version(props.instance.id, versionId)
inProgress.value = false
emit('finish-install')
}
@@ -59,7 +59,7 @@ const onHide = () => {
:on-hide="onHide"
>
<div class="modal-body">
<div v-if="instance.linked_data" class="mod-card">
<div v-if="instance.link" class="mod-card">
<div class="table">
<div class="table-row with-columns table-head">
<div class="table-cell table-text download-cell" />
@@ -6,16 +6,16 @@ import dayjs from 'dayjs'
import { onUnmounted, ref } from 'vue'
import NavButton from '@/components/ui/NavButton.vue'
import { profile_listener } from '@/helpers/events.js'
import { list } from '@/helpers/profile'
import { instance_listener } from '@/helpers/events.js'
import { list } from '@/helpers/instance'
const { handleError } = injectNotificationManager()
const recentInstances = ref([])
const getInstances = async () => {
const profiles = await list().catch(handleError)
const instances = await list().catch(handleError)
recentInstances.value = profiles
recentInstances.value = instances
.sort((a, b) => {
const dateACreated = dayjs(a.created)
const dateAPlayed = a.last_played ? dayjs(a.last_played) : dayjs(0)
@@ -37,24 +37,24 @@ const getInstances = async () => {
await getInstances()
const unlistenProfile = await profile_listener(async (event) => {
const unlistenInstance = await instance_listener(async (event) => {
if (event.event !== 'synced') {
await getInstances()
}
})
onUnmounted(() => {
unlistenProfile()
unlistenInstance()
})
</script>
<template>
<div v-for="instance in recentInstances" :key="instance.id" v-tooltip.right="instance.name">
<NavButton :to="`/instance/${encodeURIComponent(instance.path)}`" class="relative">
<NavButton :to="`/instance/${encodeURIComponent(instance.id)}`" class="relative">
<Avatar
:src="instance.icon_path ? convertFileSrc(instance.icon_path) : null"
size="28px"
:tint-by="instance.path"
:tint-by="instance.id"
:class="`transition-all ${instance.install_stage !== 'installed' ? `brightness-[0.25] scale-[0.85]` : `group-hover:brightness-75`}`"
/>
<div
@@ -65,10 +65,7 @@ onUnmounted(() => {
</div>
</NavButton>
</div>
<div
v-if="instances && recentInstances.length > 0"
class="h-px w-6 mx-auto my-2 bg-divider"
></div>
<div v-if="recentInstances.length > 0" class="h-px w-6 mx-auto my-2 bg-divider"></div>
</template>
<style scoped lang="scss"></style>
@@ -7,26 +7,28 @@ import {
injectNotificationManager,
StyledInput,
} from '@modrinth/ui'
import { useQueryClient } from '@tanstack/vue-query'
import { convertFileSrc } from '@tauri-apps/api/core'
import { computed, ref } from 'vue'
import ModalWrapper from '@/components/ui/modal/ModalWrapper.vue'
import { trackEvent } from '@/helpers/analytics'
import { list } from '@/helpers/profile'
import { add_server_to_profile, get_profile_worlds } from '@/helpers/worlds.ts'
import { list } from '@/helpers/instance'
import { add_server_to_instance, get_instance_worlds } from '@/helpers/worlds.ts'
const { handleError } = injectNotificationManager()
const queryClient = useQueryClient()
const modal = ref()
const searchFilter = ref('')
const profiles = ref([])
const instances = ref([])
const serverName = ref('')
const serverAddress = ref('')
const shownProfiles = computed(() =>
profiles.value.filter((profile) => {
return profile.name.toLowerCase().includes(searchFilter.value.toLowerCase())
const shownInstances = computed(() =>
instances.value.filter((instance) => {
return instance.name.toLowerCase().includes(searchFilter.value.toLowerCase())
}),
)
@@ -36,15 +38,15 @@ defineExpose({
serverAddress.value = address
searchFilter.value = ''
const profilesVal = await list().catch(handleError)
const instanceValues = await list().catch(handleError)
await Promise.allSettled(
profilesVal.map(async (profile) => {
profile.adding = false
profile.added = false
instanceValues.map(async (instance) => {
instance.adding = false
instance.added = false
try {
const worlds = await get_profile_worlds(profile.path)
profile.added = worlds.some(
const worlds = await get_instance_worlds(instance.id)
instance.added = worlds.some(
(w) => w.type === 'server' && w.address === serverAddress.value,
)
} catch {
@@ -53,28 +55,29 @@ defineExpose({
}),
)
profiles.value = profilesVal
instances.value = instanceValues
modal.value.show()
trackEvent('AddServerToInstanceStart', { source: 'AddServerToInstanceModal' })
},
})
async function addServer(profile) {
profile.adding = true
async function addServer(instance) {
instance.adding = true
try {
await add_server_to_profile(profile.path, serverName.value, serverAddress.value, 'prompt')
profile.added = true
await add_server_to_instance(instance.id, serverName.value, serverAddress.value, 'prompt')
instance.added = true
await queryClient.invalidateQueries({ queryKey: ['worlds', instance.id] })
trackEvent('AddServerToInstance', {
server_name: serverName.value,
instance_name: profile.name,
instance_name: instance.name,
source: 'AddServerToInstanceModal',
})
} catch (err) {
handleError(err)
}
profile.adding = false
instance.adding = false
}
</script>
@@ -91,26 +94,26 @@ async function addServer(profile) {
/>
<div class="max-h-[21rem] overflow-y-auto">
<div
v-for="profile in shownProfiles"
:key="profile.path"
v-for="instance in shownInstances"
:key="instance.id"
class="flex w-full items-center justify-between gap-2 bg-bg-raised text-icon shadow-none"
>
<router-link
class="btn btn-transparent p-2 text-left"
:to="`/instance/${encodeURIComponent(profile.path)}`"
:to="`/instance/${encodeURIComponent(instance.id)}`"
@click="modal.hide()"
>
<Avatar
:src="profile.icon_path ? convertFileSrc(profile.icon_path) : null"
:src="instance.icon_path ? convertFileSrc(instance.icon_path) : null"
class="mr-2 [--size:2rem]"
/>
{{ profile.name }}
{{ instance.name }}
</router-link>
<ButtonStyled>
<button :disabled="profile.added || profile.adding" @click="addServer(profile)">
<PlusIcon v-if="!profile.added && !profile.adding" />
<CheckIcon v-else-if="profile.added" />
{{ profile.adding ? 'Adding...' : profile.added ? 'Added' : 'Add' }}
<button :disabled="instance.added || instance.adding" @click="addServer(instance)">
<PlusIcon v-if="!instance.added && !instance.adding" />
<CheckIcon v-else-if="instance.added" />
{{ instance.adding ? 'Adding...' : instance.added ? 'Added' : 'Add' }}
</button>
</ButtonStyled>
</div>
@@ -19,7 +19,8 @@ import { useRouter } from 'vue-router'
import ConfirmDeleteInstanceModal from '@/components/ui/modal/ConfirmDeleteInstanceModal.vue'
import { trackEvent } from '@/helpers/analytics'
import { duplicate, edit, edit_icon, list, remove } from '@/helpers/profile'
import { install_duplicate_instance } from '@/helpers/install'
import { edit, edit_icon, list, remove } from '@/helpers/instance'
import { injectInstanceSettings } from '@/providers/instance-settings'
import type { GameInstance } from '../../../helpers/types'
@@ -32,14 +33,14 @@ const queryClient = useQueryClient()
const deleteConfirmModal = ref()
const { instance } = injectInstanceSettings()
type ReleaseChannel = GameInstance['preferred_update_channel']
type ReleaseChannel = GameInstance['update_channel']
const releaseChannelOptions: ReleaseChannel[] = ['release', 'beta', 'alpha']
const title = ref(instance.value.name)
const icon: Ref<string | undefined> = ref(instance.value.icon_path)
const groups = ref([...instance.value.groups])
const savingReleaseChannel = ref(false)
const selectedReleaseChannel = ref<ReleaseChannel>(instance.value.preferred_update_channel)
const selectedReleaseChannel = ref<ReleaseChannel>(instance.value.update_channel)
const releaseChannelDisabledItems = computed<ReleaseChannel[]>(() =>
savingReleaseChannel.value ? [...releaseChannelOptions] : [],
)
@@ -48,8 +49,8 @@ const newCategoryInput = ref('')
const installing = computed(() => instance.value.install_stage !== 'installed')
async function duplicateProfile() {
await duplicate(instance.value.path).catch(handleError)
async function duplicateInstance() {
await install_duplicate_instance(instance.value.id).catch(handleError)
trackEvent('InstanceDuplicate', {
loader: instance.value.loader,
game_version: instance.value.game_version,
@@ -84,22 +85,22 @@ function formatReleaseChannelDescription(channel: ReleaseChannel) {
}
watch(
() => [instance.value.path, instance.value.preferred_update_channel] as const,
() => [instance.value.id, instance.value.update_channel] as const,
() => {
if (!savingReleaseChannel.value) {
selectedReleaseChannel.value = instance.value.preferred_update_channel
selectedReleaseChannel.value = instance.value.update_channel
}
},
)
watch(selectedReleaseChannel, async (channel, previousChannel) => {
const previousReleaseChannel = previousChannel ?? instance.value.preferred_update_channel
if (channel === instance.value.preferred_update_channel) return
const previousReleaseChannel = previousChannel ?? instance.value.update_channel
if (channel === instance.value.update_channel) return
savingReleaseChannel.value = true
const profilePath = instance.value.path
await edit(profilePath, { preferred_update_channel: channel })
.then(() => queryClient.invalidateQueries({ queryKey: ['linkedModpackInfo', profilePath] }))
const instanceId = instance.value.id
await edit(instanceId, { update_channel: channel })
.then(() => queryClient.invalidateQueries({ queryKey: ['linkedModpackInfo', instanceId] }))
.catch((error) => {
selectedReleaseChannel.value = previousReleaseChannel
handleError(error)
@@ -109,7 +110,7 @@ watch(selectedReleaseChannel, async (channel, previousChannel) => {
async function resetIcon() {
icon.value = undefined
await edit_icon(instance.value.path, null).catch(handleError)
await edit_icon(instance.value.id, null).catch(handleError)
trackEvent('InstanceRemoveIcon')
}
@@ -127,12 +128,12 @@ async function setIcon() {
if (!value) return
icon.value = value
await edit_icon(instance.value.path, icon.value).catch(handleError)
await edit_icon(instance.value.id, icon.value).catch(handleError)
trackEvent('InstanceSetIcon')
}
const editProfileObject = computed(() => ({
const editInstanceObject = computed(() => ({
name: title.value.trim().substring(0, 32) ?? 'Instance',
groups: groups.value.map((x) => x.trim().substring(0, 32)).filter((x) => x.length > 0),
}))
@@ -158,15 +159,15 @@ watch(
[title, groups, groups],
async () => {
if (removing.value) return
await edit(instance.value.path, editProfileObject.value).catch(handleError)
await edit(instance.value.id, editInstanceObject.value).catch(handleError)
},
{ deep: true },
)
const removing = ref(false)
async function removeProfile() {
async function removeInstance() {
removing.value = true
const path = instance.value.path
const path = instance.value.id
trackEvent('InstanceRemove', {
loader: instance.value.loader,
@@ -284,7 +285,7 @@ const messages = defineMessages({
</script>
<template>
<ConfirmDeleteInstanceModal ref="deleteConfirmModal" @delete="removeProfile" />
<ConfirmDeleteInstanceModal ref="deleteConfirmModal" @delete="removeInstance" />
<div class="block">
<div class="float-end ml-10 relative group w-fit">
<div class="flex flex-col gap-1">
@@ -310,7 +311,7 @@ const messages = defineMessages({
:src="icon ? convertFileSrc(icon) : icon"
size="108px"
class="transition-[filter] group-hover:brightness-75"
:tint-by="instance.path"
:tint-by="instance.id"
no-shadow
/>
<div
@@ -350,7 +351,7 @@ const messages = defineMessages({
aria-labelledby="duplicate-instance-label"
:disabled="installing"
class="w-max !shadow-none"
@click="duplicateProfile"
@click="duplicateInstance"
>
<CopyIcon /> {{ formatMessage(messages.duplicateButton) }}
</button>
@@ -8,7 +8,7 @@ import {
} from '@modrinth/ui'
import { computed, ref, watch } from 'vue'
import { edit } from '@/helpers/profile'
import { edit } from '@/helpers/instance'
import { get } from '@/helpers/settings.ts'
import { injectInstanceSettings } from '@/providers/instance-settings'
@@ -28,21 +28,21 @@ const overrideHooks = ref(
)
const hooks = ref(instance.value.hooks ?? globalSettings.hooks)
const editProfileObject = computed(() => {
const editProfile: {
const editInstanceObject = computed(() => {
const editInstancePatch: {
hooks?: Hooks
} = {}
// When hooks are not overridden per-instance, we want to clear them
editProfile.hooks = overrideHooks.value ? hooks.value : {}
editInstancePatch.hooks = overrideHooks.value ? hooks.value : {}
return editProfile
return editInstancePatch
})
watch(
[overrideHooks, hooks],
async () => {
await edit(instance.value.path, editProfileObject.value)
await edit(instance.value.id, editInstanceObject.value)
},
{ deep: true },
)
@@ -4,6 +4,7 @@ import {
commonMessages,
defineMessages,
formatLoaderLabel,
injectFilePicker,
injectNotificationManager,
InstallationSettingsLayout,
provideAppBackup,
@@ -17,30 +18,41 @@ import { computed, ref } from 'vue'
import { trackEvent } from '@/helpers/analytics'
import { get_project_versions, get_version } from '@/helpers/cache'
import { get_loader_versions } from '@/helpers/metadata'
import {
duplicate,
install_duplicate_instance,
install_existing_instance,
install_pack_to_existing_instance,
installJobInstanceId,
wait_for_install_job,
} from '@/helpers/install'
import {
edit,
get_linked_modpack_info,
install,
list,
update_managed_modrinth_version,
update_repair_modrinth,
} from '@/helpers/profile'
} from '@/helpers/instance'
import { get_loader_versions } from '@/helpers/metadata'
import { get_game_versions, get_loaders } from '@/helpers/tags'
import { injectInstanceSettings } from '@/providers/instance-settings'
import { useTheming } from '@/store/state'
import type { Manifest } from '../../../helpers/types'
const { handleError } = injectNotificationManager()
const filePicker = injectFilePicker()
const { formatMessage } = useVIntl()
const queryClient = useQueryClient()
const debug = useDebugLogger('AppInstallationSettings')
const themeStore = useTheming()
const { instance, offline, isMinecraftServer, onUnlinked, closeModal } = injectInstanceSettings()
const skipNonEssentialWarnings = computed(() =>
themeStore.getFeatureFlag('skip_non_essential_warnings'),
)
debug('metadata load: start', {
instancePath: instance.value.path,
instanceId: instance.value.id,
loader: instance.value.loader,
gameVersion: instance.value.game_version,
installStage: instance.value.install_stage,
@@ -91,15 +103,22 @@ const metadataLoading = computed(() =>
)
debug('metadata queries configured', {
instancePath: instance.value.path,
instanceId: instance.value.id,
loader: instance.value.loader,
gameVersion: instance.value.game_version,
})
const isModrinthLinkedModpack = computed(
() =>
instance.value.link?.type === 'modrinth_modpack' ||
instance.value.link?.type === 'server_project_modpack',
)
const isImportedModpack = computed(() => instance.value.link?.type === 'imported_modpack')
const modpackInfoQuery = useQuery({
queryKey: computed(() => ['linkedModpackInfo', instance.value.path]),
queryFn: () => get_linked_modpack_info(instance.value.path, 'must_revalidate'),
enabled: computed(() => !!instance.value.linked_data?.project_id && !offline),
queryKey: computed(() => ['linkedModpackInfo', instance.value.id]),
queryFn: () => get_linked_modpack_info(instance.value.id, 'must_revalidate'),
enabled: computed(() => isModrinthLinkedModpack.value && !offline),
})
const modpackInfo = modpackInfoQuery.data
@@ -129,22 +148,39 @@ function getManifest(loader: string) {
return manifest
}
async function installLocalModpackFromPicker() {
const picked = await filePicker.pickModpackFile({ readFile: false })
if (!picked?.path) return false
const job = await install_pack_to_existing_instance(instance.value.id, {
type: 'fromFile',
path: picked.path,
}).catch(handleError)
if (!job) return false
const completed = await wait_for_install_job(job.job_id).catch(handleError)
return !!completed
}
provideAppBackup({
async createBackup() {
debug('createBackup: start', {
instancePath: instance.value.path,
instanceId: instance.value.id,
instanceName: instance.value.name,
})
const allProfiles = await list()
const allInstances = await list()
const prefix = `${instance.value.name} - Backup #`
const existingNums = allProfiles
const existingNums = allInstances
.filter((p) => p.name.startsWith(prefix))
.map((p) => parseInt(p.name.slice(prefix.length), 10))
.filter((n) => !isNaN(n))
const nextNum = existingNums.length > 0 ? Math.max(...existingNums) + 1 : 1
const newPath = await duplicate(instance.value.path)
await edit(newPath, { name: `${prefix}${nextNum}` })
debug('createBackup: done', { newPath, backupName: `${prefix}${nextNum}` })
const job = await install_duplicate_instance(instance.value.id)
const newInstanceId = installJobInstanceId(job)
if (newInstanceId) {
await edit(newInstanceId, { name: `${prefix}${nextNum}` })
}
debug('createBackup: done', { newInstanceId, backupName: `${prefix}${nextNum}` })
},
})
@@ -172,7 +208,7 @@ provideInstallationSettings({
}
return rows
}),
isLinked: computed(() => !!instance.value.linked_data?.locked),
isLinked: computed(() => isModrinthLinkedModpack.value || isImportedModpack.value),
isBusy: computed(
() =>
instance.value.install_stage !== 'installed' ||
@@ -180,7 +216,16 @@ provideInstallationSettings({
reinstalling.value ||
!!offline,
),
skipNonEssentialWarnings,
modpack: computed(() => {
if (isImportedModpack.value && instance.value.link?.type === 'imported_modpack') {
return {
iconUrl: instance.value.icon_path,
title: instance.value.link.name ?? instance.value.name,
versionNumber: instance.value.link.version_number ?? undefined,
filename: instance.value.link.filename ?? undefined,
}
}
if (!modpackInfo.value) return null
return {
iconUrl: modpackInfo.value.project.icon_url,
@@ -261,25 +306,25 @@ provideInstallationSettings({
async save(platform, gameVersion, loaderVersionId) {
debug('save: called', {
instancePath: instance.value.path,
instanceId: instance.value.id,
platform,
gameVersion,
loaderVersionId,
})
const editProfile: Record<string, string | undefined> = {
const editInstancePatch: Record<string, string | undefined> = {
loader: platform,
game_version: gameVersion,
}
if (platform !== 'vanilla' && loaderVersionId) {
editProfile.loader_version = loaderVersionId
editInstancePatch.loader_version = loaderVersionId
}
await edit(instance.value.path, editProfile).catch(handleError)
debug('save: edit complete', { editProfile })
await edit(instance.value.id, editInstancePatch).catch(handleError)
debug('save: edit complete', { editInstancePatch })
},
afterSave: async () => {
debug('afterSave: installing', { instancePath: instance.value.path })
await install(instance.value.path, false).catch(handleError)
debug('afterSave: installing', { instanceId: instance.value.id })
await install_existing_instance(instance.value.id, false).catch(handleError)
trackEvent('InstanceRepair', {
loader: instance.value.loader,
game_version: instance.value.game_version,
@@ -288,9 +333,9 @@ provideInstallationSettings({
},
async repair() {
debug('repair: called', { instancePath: instance.value.path })
debug('repair: called', { instanceId: instance.value.id })
repairing.value = true
await install(instance.value.path, true).catch(handleError)
await install_existing_instance(instance.value.id, true).catch(handleError)
repairing.value = false
trackEvent('InstanceRepair', {
loader: instance.value.loader,
@@ -300,24 +345,52 @@ provideInstallationSettings({
},
async reinstallModpack() {
debug('reinstallModpack: called', { instancePath: instance.value.path })
debug('reinstallModpack: called', { instanceId: instance.value.id })
reinstalling.value = true
await update_repair_modrinth(instance.value.path).catch(handleError)
let shouldTrack = false
try {
if (isImportedModpack.value) {
shouldTrack = await installLocalModpackFromPicker()
} else {
await update_repair_modrinth(instance.value.id).catch(handleError)
shouldTrack = true
}
} finally {
reinstalling.value = false
}
if (shouldTrack) {
trackEvent('InstanceRepair', {
loader: instance.value.loader,
game_version: instance.value.game_version,
})
}
debug('reinstallModpack: done')
},
async swapModpack() {
debug('swapModpack: called', { instanceId: instance.value.id })
reinstalling.value = true
try {
const installed = await installLocalModpackFromPicker()
if (installed) {
trackEvent('InstanceRepair', {
loader: instance.value.loader,
game_version: instance.value.game_version,
})
}
} finally {
reinstalling.value = false
}
debug('swapModpack: done')
},
async unlinkModpack() {
debug('unlinkModpack: called', { instancePath: instance.value.path })
await edit(instance.value.path, {
linked_data: null as unknown as undefined,
debug('unlinkModpack: called', { instanceId: instance.value.id })
await edit(instance.value.id, {
link: null as unknown as undefined,
})
await queryClient.invalidateQueries({
queryKey: ['linkedModpackInfo', instance.value.path],
queryKey: ['linkedModpackInfo', instance.value.id],
})
onUnlinked()
debug('unlinkModpack: done')
@@ -326,11 +399,9 @@ provideInstallationSettings({
getCachedModpackVersions: () => null,
async fetchModpackVersions() {
debug('fetchModpackVersions: called', {
projectId: instance.value.linked_data?.project_id,
projectId: instance.value.link?.project_id,
})
const versions = await get_project_versions(instance.value.linked_data!.project_id!).catch(
handleError,
)
const versions = await get_project_versions(instance.value.link!.project_id!).catch(handleError)
debug('fetchModpackVersions: done', { count: versions?.length ?? 0 })
return (versions ?? []) as Labrinth.Versions.v2.Version[]
},
@@ -345,19 +416,18 @@ provideInstallationSettings({
async onModpackVersionConfirm(version) {
debug('onModpackVersionConfirm: called', {
versionId: version.id,
instancePath: instance.value.path,
instanceId: instance.value.id,
})
await update_managed_modrinth_version(instance.value.path, version.id)
await update_managed_modrinth_version(instance.value.id, version.id)
await queryClient.invalidateQueries({
queryKey: ['linkedModpackInfo', instance.value.path],
queryKey: ['linkedModpackInfo', instance.value.id],
})
debug('onModpackVersionConfirm: done')
},
updaterModalProps: computed(() => ({
isApp: true,
currentVersionId:
modpackInfo.value?.update_version_id ?? instance.value.linked_data?.version_id ?? '',
currentVersionId: modpackInfo.value?.update_version_id ?? instance.value.link?.version_id ?? '',
projectIconUrl: modpackInfo.value?.project?.icon_url,
projectName: modpackInfo.value?.project?.title ?? 'Modpack',
currentGameVersion: instance.value.game_version,
@@ -366,7 +436,10 @@ provideInstallationSettings({
isServer: false,
isApp: true,
showModpackVersionActions: !isMinecraftServer.value,
showModpackVersionActions: computed(
() => isModrinthLinkedModpack.value && !isMinecraftServer.value,
),
isLocalFile: isImportedModpack,
repairing,
reinstalling,
})
@@ -23,7 +23,7 @@ import { computed, readonly, ref, watch } from 'vue'
import JavaDetectionModal from '@/components/ui/JavaDetectionModal.vue'
import useJavaTest from '@/composables/useJavaTest'
import useMemorySlider from '@/composables/useMemorySlider'
import { edit, get_optimal_jre_key } from '@/helpers/profile'
import { edit, get_optimal_jre_key } from '@/helpers/instance'
import { get } from '@/helpers/settings.ts'
import { injectInstanceSettings } from '@/providers/instance-settings'
@@ -36,7 +36,7 @@ const { instance } = injectInstanceSettings()
const globalSettings = (await get().catch(handleError)) as unknown as AppSettings
const optimalJava = readonly(await get_optimal_jre_key(instance.value.path).catch(handleError))
const optimalJava = readonly(await get_optimal_jre_key(instance.value.id).catch(handleError))
const overrideJavaInstall = ref(!!instance.value.java_path)
const javaPath = ref(instance.value.java_path ?? optimalJava?.path ?? '')
@@ -104,7 +104,7 @@ const { maxMemory, snapPoints } = (await useMemorySlider().catch(handleError)) a
snapPoints: number[]
}
const editProfileObject = computed(() => {
const editInstanceObject = computed(() => {
return {
java_path:
overrideJavaInstall.value && javaPath.value
@@ -136,7 +136,7 @@ watch(
memory,
],
async () => {
await edit(instance.value.path, editProfileObject.value)
await edit(instance.value.id, editInstanceObject.value)
},
{ deep: true },
)
@@ -9,7 +9,7 @@ import {
} from '@modrinth/ui'
import { computed, type Ref, ref, watch } from 'vue'
import { edit } from '@/helpers/profile'
import { edit } from '@/helpers/instance'
import { get } from '@/helpers/settings.ts'
import { injectInstanceSettings } from '@/providers/instance-settings'
@@ -32,7 +32,7 @@ const fullscreenSetting: Ref<boolean> = ref(
instance.value.force_fullscreen ?? globalSettings.force_fullscreen,
)
const editProfileObject = computed(() => {
const editInstanceObject = computed(() => {
if (!overrideWindowSettings.value) {
return {
force_fullscreen: null,
@@ -48,7 +48,7 @@ const editProfileObject = computed(() => {
watch(
[overrideWindowSettings, resolution, fullscreenSetting],
async () => {
await edit(instance.value.path, editProfileObject.value)
await edit(instance.value.id, editInstanceObject.value)
},
{ deep: true },
)
@@ -14,7 +14,7 @@ defineProps<{
<Avatar
:src="instance.icon_path ? convertFileSrc(instance.icon_path) : undefined"
size="24px"
:tint-by="instance.path"
:tint-by="instance.id"
/>
{{ instance.name }} <ChevronRightIcon />
</span>
@@ -17,7 +17,7 @@ import {
useVIntl,
} from '@modrinth/ui'
import type { PlatformTag } from '@modrinth/utils'
import { useQuery } from '@tanstack/vue-query'
import { useQuery, useQueryClient } from '@tanstack/vue-query'
import { convertFileSrc } from '@tauri-apps/api/core'
import { computed, nextTick, ref, watch } from 'vue'
@@ -27,14 +27,15 @@ import InstallationSettings from '@/components/ui/instance_settings/Installation
import JavaSettings from '@/components/ui/instance_settings/JavaSettings.vue'
import WindowSettings from '@/components/ui/instance_settings/WindowSettings.vue'
import { get_project_v3 } from '@/helpers/cache'
import { get_linked_modpack_info } from '@/helpers/instance'
import { get_loader_versions } from '@/helpers/metadata'
import { get_linked_modpack_info } from '@/helpers/profile'
import { get_game_versions, get_loaders } from '@/helpers/tags'
import { provideInstanceSettings } from '@/providers/instance-settings'
import type { GameInstance } from '../../../helpers/types'
const { formatMessage } = useVIntl()
const queryClient = useQueryClient()
const props = defineProps<{
instance: GameInstance
@@ -66,8 +67,8 @@ watch(
() => props.instance,
(instance) => {
isMinecraftServer.value = false
if (instance.linked_data?.project_id) {
get_project_v3(instance.linked_data.project_id, 'must_revalidate')
if (instance.link?.project_id) {
get_project_v3(instance.link.project_id, 'must_revalidate')
.then((project: Labrinth.Projects.v3.Project | undefined) => {
if (project?.minecraft_server != null) {
isMinecraftServer.value = true
@@ -156,12 +157,18 @@ useQuery({
queryFn: getSupportedModpackLoaders,
})
useQuery({
queryKey: computed(() => ['linkedModpackInfo', props.instance.path]),
queryFn: () => get_linked_modpack_info(props.instance.path, 'stale_while_revalidate'),
enabled: computed(() => !!props.instance.linked_data?.project_id && !props.offline),
queryKey: computed(() => ['linkedModpackInfo', props.instance.id]),
queryFn: () => get_linked_modpack_info(props.instance.id, 'stale_while_revalidate'),
enabled: computed(() => !!props.instance.link?.project_id && !props.offline),
})
function show(tabIndex?: number) {
if (props.instance.link?.project_id) {
queryClient.prefetchQuery({
queryKey: ['linkedModpackInfo', props.instance.id],
queryFn: () => get_linked_modpack_info(props.instance.id, 'stale_while_revalidate'),
})
}
tabbedModal.value?.show()
if (tabIndex !== undefined) {
nextTick(() => tabbedModal.value?.setTab(tabIndex))
@@ -182,7 +189,7 @@ defineExpose({ show, hide })
<Avatar
:src="instance.icon_path ? convertFileSrc(instance.icon_path) : undefined"
size="24px"
:tint-by="props.instance.path"
:tint-by="props.instance.id"
/>
{{ instance.name }} <ChevronRightIcon />
<span class="font-extrabold text-contrast">{{
@@ -68,17 +68,17 @@ const messages = defineMessages({
})
const emit = defineEmits<{
(e: 'go-to-instance', instancePath: string): void
(e: 'go-to-instance', instanceId: string): void
(e: 'create-anyway'): void
}>()
const modal = ref<InstanceType<typeof NewModal>>()
const instanceName = ref('')
const instancePath = ref('')
const instanceId = ref('')
function show(name: string, path: string) {
function show(name: string, id: string) {
instanceName.value = name
instancePath.value = path
instanceId.value = id
modal.value?.show()
}
@@ -88,7 +88,7 @@ function handleCancel() {
function handleGoToInstance() {
modal.value?.hide()
emit('go-to-instance', instancePath.value)
emit('go-to-instance', instanceId.value)
}
function handleCreateAnyway() {
@@ -31,7 +31,8 @@ import dayjs from 'dayjs'
import { computed, ref, watch } from 'vue'
import { get_project_many, get_version, get_version_many } from '@/helpers/cache.js'
import { update_managed_modrinth_version } from '@/helpers/profile'
import { wait_for_install_job } from '@/helpers/install'
import { update_managed_modrinth_version } from '@/helpers/instance'
import type { GameInstance } from '@/helpers/types'
import { injectServerInstall } from '@/providers/server-install'
@@ -202,15 +203,15 @@ async function computeDependencyDiffs(
}
async function checkUpdateAvailable(inst: GameInstance): Promise<DependencyDiff[] | null> {
if (!inst.linked_data) return null
if (!modpackVersionId.value || !inst.linked_data.version_id) return null
if (!inst.link) return null
if (!modpackVersionId.value || !inst.link.version_id) return null
try {
// For server projects, linked_data.project_id is the server project but
// linked_data.version_id references a content modpack version from a different project.
// Detect this by comparing the version's project_id with linked_data.project_id.
// For server projects, link.project_id is the server project but
// link.version_id references a content modpack version from a different project.
// Detect this by comparing the version's project_id with link.project_id.
modpackVersion.value = await get_version(modpackVersionId.value, 'bypass')
const instanceModpackVersion = await get_version(inst.linked_data.version_id, 'bypass')
const instanceModpackVersion = await get_version(inst.link.version_id, 'bypass')
// Compute dependency diffs between current and latest version
if (instanceModpackVersion && modpackVersion.value) {
@@ -238,11 +239,12 @@ watch(
async function handleUpdate() {
hide()
const serverProjectId = instance.value?.linked_data?.project_id
const serverProjectId = instance.value?.link?.project_id
if (serverProjectId) startInstallingServer(serverProjectId)
try {
if (modpackVersionId.value && instance.value) {
await update_managed_modrinth_version(instance.value.path, modpackVersionId.value)
const job = await update_managed_modrinth_version(instance.value.id, modpackVersionId.value)
await wait_for_install_job(job.job_id)
await onUpdateComplete.value()
}
} catch (error) {
@@ -253,10 +255,8 @@ async function handleUpdate() {
}
function handleReport() {
if (instance.value?.linked_data?.project_id) {
openUrl(
`https://modrinth.com/report?item=project&itemID=${instance.value.linked_data.project_id}`,
)
if (instance.value?.link?.project_id) {
openUrl(`https://modrinth.com/report?item=project&itemID=${instance.value.link.project_id}`)
}
}
@@ -297,11 +297,8 @@ const messages = defineMessages({
})
const hasUpdate = computed(() => {
if (!instance.value?.linked_data) return false
return (
modpackVersionId.value != null &&
modpackVersionId.value !== instance.value.linked_data.version_id
)
if (!instance.value?.link) return false
return modpackVersionId.value != null && modpackVersionId.value !== instance.value.link.version_id
})
defineExpose({ show, hide, hasUpdate })
@@ -11,6 +11,7 @@ const themeStore = useTheming()
const { formatMessage } = useVIntl()
const worldsInHomeFlag: FeatureFlag = 'worlds_in_home'
const skipNonEssentialWarningsFlag: FeatureFlag = 'skip_non_essential_warnings'
const skipUnknownPackWarningFlag: FeatureFlag = 'skip_unknown_pack_warning'
const showPlayTimeFlag: FeatureFlag = 'show_instance_play_time'
@@ -101,6 +102,15 @@ const messages = defineMessages({
defaultMessage:
"If you attempt to install a Modrinth Pack file (.mrpack) that isn't hosted on Modrinth, we'll make sure you understand the risks before installing it.",
},
skipNonEssentialWarningsTitle: {
id: 'app.appearance-settings.skip-non-essential-warnings.title',
defaultMessage: 'Skip non-essential warnings',
},
skipNonEssentialWarningsDescription: {
id: 'app.appearance-settings.skip-non-essential-warnings.description',
defaultMessage:
'Automatically skips low-risk confirmations like duplicate modpack installs, normal content deletion, bulk updates, unlinking modpacks, and repair prompts. Dangerous warnings will still be shown.',
},
showPlayTimeTitle: {
id: 'app.appearance-settings.show-play-time.title',
defaultMessage: 'Show play time',
@@ -285,6 +295,25 @@ watch(
/>
</div>
<div class="mt-6 flex items-center justify-between gap-4">
<div>
<h2 class="m-0 text-lg font-semibold text-contrast">
{{ formatMessage(messages.skipNonEssentialWarningsTitle) }}
</h2>
<p class="m-0 mt-1">{{ formatMessage(messages.skipNonEssentialWarningsDescription) }}</p>
</div>
<Toggle
:model-value="themeStore.getFeatureFlag(skipNonEssentialWarningsFlag)"
@update:model-value="
() => {
const newValue = !themeStore.getFeatureFlag(skipNonEssentialWarningsFlag)
themeStore.featureFlags[skipNonEssentialWarningsFlag] = newValue
settings.feature_flags[skipNonEssentialWarningsFlag] = newValue
}
"
/>
</div>
<div class="mt-6 flex items-center justify-between">
<div>
<h2 class="m-0 text-lg font-semibold text-contrast">
@@ -1,5 +1,5 @@
<script setup>
import { BoxIcon, FolderSearchIcon, TrashIcon } from '@modrinth/assets'
import { BoxIcon, FolderOpenIcon, FolderSearchIcon, TrashIcon } from '@modrinth/assets'
import { ButtonStyled, injectNotificationManager, Slider, StyledInput } from '@modrinth/ui'
import { open } from '@tauri-apps/plugin-dialog'
import { ref, watch } from 'vue'
@@ -7,9 +7,13 @@ import { ref, watch } from 'vue'
import ConfirmModalWrapper from '@/components/ui/modal/ConfirmModalWrapper.vue'
import { purge_cache_types } from '@/helpers/cache.js'
import { get, set } from '@/helpers/settings.ts'
import { showAppDbBackupsFolder } from '@/helpers/utils.js'
import { useTheming } from '@/store/state'
const { handleError } = injectNotificationManager()
const themeStore = useTheming()
const settings = ref(await get())
const purgeCacheConfirmModal = ref(null)
watch(
settings,
@@ -48,6 +52,19 @@ async function purgeCache() {
]).catch(handleError)
}
function handlePurgeCacheClick() {
if (themeStore.getFeatureFlag('skip_non_essential_warnings')) {
void purgeCache()
return
}
purgeCacheConfirmModal.value?.show()
}
async function openDbBackupsFolder() {
await showAppDbBackupsFolder().catch(handleError)
}
async function findLauncherDir() {
const newDir = await open({
multiple: false,
@@ -97,7 +114,7 @@ async function findLauncherDir() {
@proceed="purgeCache"
/>
<h2 class="m-0 text-lg font-semibold text-contrast">App cache</h2>
<button id="purge-cache" class="btn min-w-max" @click="$refs.purgeCacheConfirmModal.show()">
<button id="purge-cache" class="btn min-w-max" @click="handlePurgeCacheClick">
<TrashIcon />
Purge cache
</button>
@@ -136,5 +153,16 @@ async function findLauncherDir() {
value if you are frequently getting I/O errors. (app restart required to take effect)
</p>
</div>
<div class="flex flex-col gap-2.5">
<h2 class="mt-0 m-0 text-lg font-semibold text-contrast">App database backups</h2>
<button id="open-db-backups-folder" class="btn min-w-max" @click="openDbBackupsFolder">
<FolderOpenIcon />
Open backups folder
</button>
<p class="m-0 leading-tight text-secondary">
Backups of important app data are stored here in case you need to recover them later.
</p>
</div>
</div>
</template>
@@ -27,10 +27,10 @@ import { useRouter } from 'vue-router'
import { trackEvent } from '@/helpers/analytics'
import { get_project } from '@/helpers/cache'
import { process_listener } from '@/helpers/events'
import { get_by_profile_path } from '@/helpers/process'
import { kill, run } from '@/helpers/profile'
import { kill, run } from '@/helpers/instance'
import { get_by_instance_id } from '@/helpers/process'
import type { GameInstance } from '@/helpers/types'
import { showProfileInFolder } from '@/helpers/utils'
import { showInstanceInFolder } from '@/helpers/utils'
import { handleSevereError } from '@/store/error'
const { handleError } = injectNotificationManager()
@@ -52,13 +52,13 @@ const props = defineProps<{
last_played: Dayjs
}>()
const loadingModpack = ref(!!props.instance.linked_data)
const loadingModpack = ref(!!props.instance.link)
const modpack = ref()
if (props.instance.linked_data) {
if (props.instance.link) {
nextTick().then(async () => {
modpack.value = await get_project(props.instance.linked_data?.project_id, 'must_revalidate')
modpack.value = await get_project(props.instance.link?.project_id, 'must_revalidate')
loadingModpack.value = false
})
}
@@ -81,8 +81,8 @@ const playing = ref(false)
const play = async (event: MouseEvent) => {
event?.stopPropagation()
loading.value = true
await run(props.instance.path)
.catch((err) => handleSevereError(err, { profilePath: props.instance.path }))
await run(props.instance.id)
.catch((err) => handleSevereError(err, { instanceId: props.instance.id }))
.finally(() => {
trackEvent('InstanceStart', {
loader: props.instance.loader,
@@ -97,7 +97,7 @@ const play = async (event: MouseEvent) => {
const stop = async (event: MouseEvent) => {
event?.stopPropagation()
loading.value = true
await kill(props.instance.path).catch(handleError)
await kill(props.instance.id).catch(handleError)
trackEvent('InstanceStop', {
loader: props.instance.loader,
game_version: props.instance.game_version,
@@ -112,7 +112,7 @@ const unlistenProcesses = await process_listener(async () => {
})
const checkProcess = async () => {
const runningProcesses = await get_by_profile_path(props.instance.path).catch(handleError)
const runningProcesses = await get_by_instance_id(props.instance.id).catch(handleError)
playing.value = runningProcesses.length > 0
}
@@ -130,7 +130,7 @@ onUnmounted(() => {
<template #clickable>
<router-link
class="no-click-animation"
:to="`/instance/${encodeURIComponent(instance.path)}`"
:to="`/instance/${encodeURIComponent(instance.id)}`"
/>
</template>
<div
@@ -138,7 +138,7 @@ onUnmounted(() => {
>
<Avatar
:src="instanceIcon ? convertFileSrc(instanceIcon) : undefined"
:tint-by="instance.path"
:tint-by="instance.id"
size="48px"
/>
<div class="flex flex-col col-span-2 justify-between h-full">
@@ -206,12 +206,12 @@ onUnmounted(() => {
:options="[
{
id: 'open-instance',
shown: !!instance.path,
action: () => router.push(encodeURI(`/instance/${instance.path}`)),
shown: !!instance.id,
action: () => router.push(encodeURI(`/instance/${instance.id}`)),
},
{
id: 'open-folder',
action: () => showProfileInFolder(instance.path),
action: () => showInstanceInFolder(instance.id),
},
]"
>
@@ -10,13 +10,13 @@ import { computed, onMounted, onUnmounted, ref, watch } from 'vue'
import InstanceItem from '@/components/ui/world/InstanceItem.vue'
import WorldItem from '@/components/ui/world/WorldItem.vue'
import { trackEvent } from '@/helpers/analytics'
import { process_listener, profile_listener } from '@/helpers/events'
import { instance_listener, process_listener } from '@/helpers/events'
import { kill, run } from '@/helpers/instance'
import { get_all } from '@/helpers/process'
import { kill, run } from '@/helpers/profile'
import { get_game_versions } from '@/helpers/tags'
import type { GameInstance } from '@/helpers/types'
import {
get_profile_protocol_version,
get_instance_protocol_version,
get_recent_worlds,
getWorldIdentifier,
hasServerQuickPlaySupport,
@@ -27,7 +27,7 @@ import {
type ServerWorld,
start_join_server,
start_join_singleplayer_world,
type WorldWithProfile,
type WorldWithInstance,
} from '@/helpers/worlds.ts'
import { handleSevereError } from '@/store/error'
import { useTheming } from '@/store/theme.ts'
@@ -66,7 +66,7 @@ type InstanceJumpBackInItem = BaseJumpBackInItem & {
type WorldJumpBackInItem = BaseJumpBackInItem & {
type: 'world'
world: WorldWithProfile
world: WorldWithInstance
}
type JumpBackInItem = InstanceJumpBackInItem | WorldJumpBackInItem
@@ -100,7 +100,7 @@ async function populateJumpBackIn() {
const worlds = await get_recent_worlds(MAX_JUMP_BACK_IN, ['normal', 'favorite'])
worlds.forEach((world) => {
const instance = props.recentInstances.find((instance) => instance.path === world.profile)
const instance = props.recentInstances.find((instance) => instance.id === world.instance_id)
if (!instance || !world.last_played) {
return
@@ -115,23 +115,23 @@ async function populateJumpBackIn() {
})
const servers: {
instancePath: string
instanceId: string
address: string
}[] = worldItems
.filter((item) => item.world.type === 'server' && item.instance)
.map((item) => ({
instancePath: item.instance.path,
instanceId: item.instance.id,
address: (item.world as ServerWorld).address,
}))
// fetch protocol versions for all unique MC versions with server worlds
const uniqueServerInstances = new Set<string>(servers.map((x) => x.instancePath))
const uniqueServerInstances = new Set<string>(servers.map((x) => x.instanceId))
await Promise.all(
[...uniqueServerInstances].map((path) =>
get_profile_protocol_version(path)
.then((protoVer) => (protocolVersions.value[path] = protoVer))
[...uniqueServerInstances].map((instanceId) =>
get_instance_protocol_version(instanceId)
.then((protoVer) => (protocolVersions.value[instanceId] = protoVer))
.catch(() => {
console.error(`Failed to get profile protocol for: ${path} `)
console.error(`Failed to get instance protocol for: ${instanceId} `)
}),
),
)
@@ -145,14 +145,14 @@ async function populateJumpBackIn() {
}
})
servers.forEach(({ instancePath, address }) =>
refreshServerData(serverData.value[address], protocolVersions.value[instancePath], address),
servers.forEach(({ instanceId, address }) =>
refreshServerData(serverData.value[address], protocolVersions.value[instanceId], address),
)
}
const instanceItems: InstanceJumpBackInItem[] = []
for (const instance of props.recentInstances) {
const worldItem = worldItems.find((item) => item.instance.path === instance.path)
const worldItem = worldItems.find((item) => item.instance.id === instance.id)
if ((worldItem && worldItem.last_played.isAfter(TWO_WEEKS_AGO)) || !instance.last_played) {
continue
}
@@ -171,14 +171,14 @@ async function populateJumpBackIn() {
.slice(0, MAX_JUMP_BACK_IN)
}
function refreshServer(address: string, instancePath: string) {
refreshServerData(serverData.value[address], protocolVersions.value[instancePath], address)
function refreshServer(address: string, instanceId: string) {
refreshServerData(serverData.value[address], protocolVersions.value[instanceId], address)
}
async function joinWorld(world: WorldWithProfile, instance?: GameInstance) {
async function joinWorld(world: WorldWithInstance, instance?: GameInstance) {
console.log(`Joining world ${getWorldIdentifier(world)}`)
if (world.type === 'server') {
await start_join_server(world.profile, world.address).catch(handleError)
await start_join_server(world.instance_id, world.address).catch(handleError)
if (instance) {
trackEvent('InstanceStart', {
loader: instance.loader,
@@ -187,13 +187,13 @@ async function joinWorld(world: WorldWithProfile, instance?: GameInstance) {
})
}
} else if (world.type === 'singleplayer') {
await start_join_singleplayer_world(world.profile, world.path).catch(handleError)
await start_join_singleplayer_world(world.instance_id, world.path).catch(handleError)
}
}
async function playInstance(instance: GameInstance) {
await run(instance.path)
.catch((err) => handleSevereError(err, { profilePath: instance.path }))
await run(instance.id)
.catch((err) => handleSevereError(err, { instanceId: instance.id }))
.finally(() => {
trackEvent('InstanceStart', {
loader: instance.loader,
@@ -210,14 +210,14 @@ async function stopInstance(path: string) {
})
}
const currentProfile = ref<string>()
const currentInstance = ref<string>()
const currentWorld = ref<string>()
const unlistenProcesses = await process_listener(async () => {
await checkProcesses()
})
const unlistenProfiles = await profile_listener(async () => {
const unlistenInstances = await instance_listener(async () => {
await populateJumpBackIn().catch(() => {
console.error('Failed to populate jump back in')
})
@@ -227,18 +227,18 @@ const runningInstances = ref<string[]>([])
type ProcessMetadata = {
uuid: string
profile_path: string
instance_id: string
start_time: string
}
const checkProcesses = async () => {
const runningProcesses: ProcessMetadata[] = await get_all().catch(handleError)
const runningPaths = runningProcesses.map((x) => x.profile_path)
const runningPaths = runningProcesses.map((x) => x.instance_id)
const stoppedInstances = runningInstances.value.filter((x) => !runningPaths.includes(x))
if (currentProfile.value && stoppedInstances.includes(currentProfile.value)) {
currentProfile.value = undefined
if (currentInstance.value && stoppedInstances.includes(currentInstance.value)) {
currentInstance.value = undefined
currentWorld.value = undefined
}
@@ -252,7 +252,7 @@ onMounted(() => {
onUnmounted(() => {
unlistenProcesses()
unlistenProfiles()
unlistenInstances()
})
</script>
@@ -278,14 +278,14 @@ onUnmounted(() => {
<div class="grid-when-huge flex flex-col w-full gap-2">
<template
v-for="item in jumpBackInItems"
:key="`${item.instance.path}-${item.type === 'world' ? getWorldIdentifier(item.world) : 'instance'}`"
:key="`${item.instance.id}-${item.type === 'world' ? getWorldIdentifier(item.world) : 'instance'}`"
>
<WorldItem
v-if="item.type === 'world'"
:world="item.world"
:playing-instance="runningInstances.includes(item.instance.path)"
:playing-instance="runningInstances.includes(item.instance.id)"
:playing-world="
currentProfile === item.instance.path && currentWorld === getWorldIdentifier(item.world)
currentInstance === item.instance.id && currentWorld === getWorldIdentifier(item.world)
"
:refreshing="
item.world.type === 'server'
@@ -306,34 +306,34 @@ onUnmounted(() => {
:rendered-motd="
item.world.type === 'server' ? serverData[item.world.address].renderedMotd : undefined
"
:current-protocol="protocolVersions[item.instance.path]"
:current-protocol="protocolVersions[item.instance.id]"
:game-mode="
item.world.type === 'singleplayer' ? GAME_MODES[item.world.game_mode] : undefined
"
:instance-path="item.instance.path"
:instance-id="item.instance.id"
:instance-name="item.instance.name"
:instance-icon="item.instance.icon_path"
@refresh="
() =>
item.world.type === 'server'
? refreshServer(item.world.address, item.instance.path)
? refreshServer(item.world.address, item.instance.id)
: {}
"
@update="() => populateJumpBackIn()"
@play="
() => {
currentProfile = item.instance.path
currentInstance = item.instance.id
currentWorld = getWorldIdentifier(item.world)
joinWorld(item.world, item.instance)
}
"
@play-instance="
() => {
currentProfile = item.instance.path
currentInstance = item.instance.id
playInstance(item.instance)
}
"
@stop="() => stopInstance(item.instance.path)"
@stop="() => stopInstance(item.instance.id)"
/>
<InstanceItem v-else :instance="item.instance" :last_played="item.last_played" />
</template>
@@ -2,6 +2,7 @@
import {
ClipboardCopyIcon,
EditIcon,
ExternalIcon,
EyeIcon,
FolderOpenIcon,
IssuesIcon,
@@ -23,6 +24,7 @@ import {
ButtonStyled,
commonMessages,
defineMessages,
injectNotificationManager,
OverflowMenu,
SmartClickable,
TagItem,
@@ -39,7 +41,7 @@ import type { Component } from 'vue'
import { computed } from 'vue'
import { useRouter } from 'vue-router'
import { copyToClipboard } from '@/helpers/utils'
import { copyToClipboard, createInstanceShortcut } from '@/helpers/utils'
import type {
ProtocolVersion,
ServerStatus,
@@ -60,6 +62,7 @@ const formatDateTime = useFormatDateTime({
})
const router = useRouter()
const { addNotification } = injectNotificationManager()
const emit = defineEmits<{
(e: 'play' | 'play-instance' | 'update' | 'stop' | 'refresh' | 'edit' | 'delete'): void
@@ -91,9 +94,10 @@ const props = withDefaults(
managed?: boolean
// Instance
instancePath?: string
instanceId?: string
instanceName?: string
instanceIcon?: string
shortcutInstanceId?: string
}>(),
{
playingInstance: false,
@@ -110,9 +114,10 @@ const props = withDefaults(
gameMode: undefined,
managed: false,
instancePath: undefined,
instanceId: undefined,
instanceName: undefined,
instanceIcon: undefined,
shortcutInstanceId: undefined,
},
)
@@ -131,6 +136,33 @@ const serverIncompatible = computed(
const locked = computed(() => props.world.type === 'singleplayer' && props.world.locked)
const managed = computed(() => props.managed)
const shortcutInstanceId = computed(() => props.shortcutInstanceId ?? props.instanceId)
async function createShortcut() {
if (!shortcutInstanceId.value) return
try {
const shortcutPath = await createInstanceShortcut(
props.world.name,
shortcutInstanceId.value,
props.world.type === 'server'
? { server: (props.world as ServerWorld).address }
: { singleplayerWorld: (props.world as SingleplayerWorld).path },
)
if (!shortcutPath) return
addNotification({
type: 'success',
title: 'Shortcut created',
})
} catch (error) {
addNotification({
type: 'error',
title: 'Failed to create shortcut',
text: error instanceof Error ? error.message : '',
})
}
}
const messages = defineMessages({
hardcore: {
@@ -185,6 +217,10 @@ const messages = defineMessages({
id: 'instance.worlds.dont_show_on_home',
defaultMessage: `Don't show on Home`,
},
createShortcut: {
id: 'instance.worlds.create_shortcut',
defaultMessage: 'Create shortcut',
},
linkedServer: {
id: 'instance.worlds.linked_server',
defaultMessage: 'Managed by server project',
@@ -209,10 +245,10 @@ const messages = defineMessages({
</script>
<template>
<SmartClickable>
<template v-if="instancePath" #clickable>
<template v-if="instanceId" #clickable>
<router-link
class="no-click-animation"
:to="`/instance/${encodeURIComponent(instancePath)}/worlds?highlight=${encodeURIComponent(getWorldIdentifier(world))}`"
:to="`/instance/${encodeURIComponent(instanceId)}/worlds?highlight=${encodeURIComponent(getWorldIdentifier(world))}`"
/>
</template>
<div
@@ -324,16 +360,16 @@ const messages = defineMessages({
</template>
<template v-else> {{ formatMessage(messages.notPlayedYet) }} </template>
</div>
<template v-if="instancePath">
<template v-if="instanceId">
<router-link
class="flex items-center gap-1 truncate hover:underline text-secondary smart-clickable:allow-pointer-events"
:to="`/instance/${instancePath}`"
:to="`/instance/${instanceId}`"
>
<Avatar
:src="instanceIcon ? convertFileSrc(instanceIcon) : undefined"
size="16px"
:tint-by="instancePath"
:tint-by="instanceId"
class="shrink-0"
/>
<span class="truncate">{{ instanceName }}</span>
@@ -420,14 +456,14 @@ const messages = defineMessages({
:options="[
{
id: 'play-instance',
shown: !!instancePath,
shown: !!instanceId,
disabled: playingInstance,
action: () => emit('play-instance'),
},
{
id: 'open-instance',
shown: !!instancePath,
action: () => router.push(encodeURI(`/instance/${instancePath}`)),
shown: !!instanceId,
action: () => router.push(`/instance/${encodeURIComponent(instanceId)}`),
},
{
id: 'refresh',
@@ -442,7 +478,7 @@ const messages = defineMessages({
{
id: 'edit',
action: () => emit('edit'),
shown: !instancePath,
shown: !instanceId,
disabled: locked || managed,
tooltip: locked
? formatMessage(messages.worldInUse)
@@ -457,14 +493,14 @@ const messages = defineMessages({
},
{
divider: true,
shown: !!instancePath,
shown: !!instanceId,
},
{
id: 'dont-show-on-home',
shown: !!instancePath,
shown: !!instanceId,
action: () => {
set_world_display_status(
instancePath,
instanceId,
world.type,
getWorldIdentifier(world),
'hidden',
@@ -473,16 +509,21 @@ const messages = defineMessages({
})
},
},
{
id: 'create-shortcut',
shown: !!shortcutInstanceId,
action: () => createShortcut(),
},
{
divider: true,
shown: !instancePath,
shown: !instanceId,
},
{
id: 'delete',
color: 'red',
hoverFilled: true,
action: () => emit('delete'),
shown: !instancePath,
shown: !instanceId,
disabled: locked || managed,
tooltip: locked
? formatMessage(messages.worldInUse)
@@ -517,6 +558,10 @@ const messages = defineMessages({
<UpdatedIcon aria-hidden="true" />
{{ formatMessage(commonMessages.refreshButton) }}
</template>
<template #create-shortcut>
<ExternalIcon aria-hidden="true" />
{{ formatMessage(messages.createShortcut) }}
</template>
<template #dont-show-on-home>
<XIcon aria-hidden="true" />
{{ formatMessage(messages.dontShowOnHome) }}
@@ -12,7 +12,11 @@ import { ref } from 'vue'
import ServerModalBody from '@/components/ui/world/modal/ServerModalBody.vue'
import type { GameInstance } from '@/helpers/types'
import { add_server_to_profile, type ServerPackStatus, type ServerWorld } from '@/helpers/worlds.ts'
import {
add_server_to_instance,
type ServerPackStatus,
type ServerWorld,
} from '@/helpers/worlds.ts'
const { handleError } = injectNotificationManager()
const { formatMessage } = useVIntl()
@@ -35,8 +39,8 @@ async function addServer(play: boolean) {
const serverName = name.value ? name.value : address.value
const resourcePackStatus = resourcePack.value
const index =
(await add_server_to_profile(
props.instance.path,
(await add_server_to_instance(
props.instance.id,
serverName,
address.value,
resourcePackStatus,
@@ -0,0 +1,124 @@
<script setup lang="ts">
import { TrashIcon, XIcon } from '@modrinth/assets'
import {
Admonition,
ButtonStyled,
commonMessages,
defineMessages,
NewModal,
useVIntl,
} from '@modrinth/ui'
import { computed, ref } from 'vue'
import type { World } from '@/helpers/worlds.ts'
const { formatMessage } = useVIntl()
const props = defineProps<{
world: World | null
}>()
const emit = defineEmits<{
confirm: [world: World]
}>()
const messages = defineMessages({
removeServerTitle: {
id: 'app.instance.worlds.remove-server-modal.title',
defaultMessage: 'Remove server',
},
deleteWorldTitle: {
id: 'app.instance.worlds.delete-world-modal.title',
defaultMessage: 'Delete world',
},
removeServerWarningHeader: {
id: 'app.instance.worlds.remove-server-modal.warning-header',
defaultMessage: 'Removing {name}',
},
deleteWorldWarningHeader: {
id: 'app.instance.worlds.delete-world-modal.warning-header',
defaultMessage: 'Deleting {name}',
},
removeServerWarningBody: {
id: 'app.instance.worlds.remove-server-modal.warning-body',
defaultMessage:
'This server will be removed from your server list and from the in-game server list. You can add it again later if you know the address.',
},
deleteWorldWarningBody: {
id: 'app.instance.worlds.delete-world-modal.warning-body',
defaultMessage:
'This world will be permanently deleted from this instance. This action cannot be undone.',
},
removeServerButton: {
id: 'app.instance.worlds.remove-server-modal.remove-button',
defaultMessage: 'Remove server',
},
deleteWorldButton: {
id: 'app.instance.worlds.delete-world-modal.delete-button',
defaultMessage: 'Delete world',
},
})
const modal = ref<InstanceType<typeof NewModal>>()
const isServer = computed(() => props.world?.type === 'server')
const isSingleplayer = computed(() => props.world?.type === 'singleplayer')
const titleMessage = computed(() =>
isServer.value ? messages.removeServerTitle : messages.deleteWorldTitle,
)
const actionMessage = computed(() =>
isServer.value ? messages.removeServerButton : messages.deleteWorldButton,
)
const warningHeaderMessage = computed(() =>
isServer.value ? messages.removeServerWarningHeader : messages.deleteWorldWarningHeader,
)
const warningBodyMessage = computed(() =>
isServer.value ? messages.removeServerWarningBody : messages.deleteWorldWarningBody,
)
function show() {
modal.value?.show()
}
function hide() {
modal.value?.hide()
}
function confirm() {
if (!props.world) return
emit('confirm', props.world)
hide()
}
defineExpose({ show, hide })
</script>
<template>
<NewModal ref="modal" :header="formatMessage(titleMessage)" fade="danger" max-width="500px">
<div class="flex flex-col gap-4">
<Admonition
type="critical"
:header="formatMessage(warningHeaderMessage, { name: world?.name })"
>
{{ formatMessage(warningBodyMessage) }}
</Admonition>
</div>
<template #actions>
<div class="flex gap-2 justify-end">
<ButtonStyled type="outlined">
<button @click="hide">
<XIcon />
{{ formatMessage(commonMessages.cancelButton) }}
</button>
</ButtonStyled>
<ButtonStyled color="red">
<button :disabled="!isServer && !isSingleplayer" @click="confirm">
<TrashIcon />
{{ formatMessage(actionMessage) }}
</button>
</ButtonStyled>
</div>
</template>
</NewModal>
</template>
@@ -15,7 +15,7 @@ import ServerModalBody from '@/components/ui/world/modal/ServerModalBody.vue'
import type { GameInstance } from '@/helpers/types'
import {
type DisplayStatus,
edit_server_in_profile,
edit_server_in_instance,
type ServerPackStatus,
type ServerWorld,
set_world_display_status,
@@ -46,8 +46,8 @@ const newDisplayStatus = computed(() => (hideFromHome.value ? 'hidden' : 'normal
async function saveServer() {
const serverName = name.value ? name.value : address.value
const resourcePackStatus = resourcePack.value
await edit_server_in_profile(
props.instance.path,
await edit_server_in_instance(
props.instance.id,
index.value,
serverName,
address.value,
@@ -56,7 +56,7 @@ async function saveServer() {
if (newDisplayStatus.value !== displayStatus.value) {
await set_world_display_status(
props.instance.path,
props.instance.id,
'server',
address.value,
newDisplayStatus.value,
@@ -40,14 +40,14 @@ const hideFromHome = ref(false)
const newDisplayStatus = computed(() => (hideFromHome.value ? 'hidden' : 'normal'))
async function saveWorld() {
await rename_world(props.instance.path, path.value, name.value).catch(handleError)
await rename_world(props.instance.id, path.value, name.value).catch(handleError)
if (removeIcon.value) {
await reset_world_icon(props.instance.path, path.value).catch(handleError)
await reset_world_icon(props.instance.id, path.value).catch(handleError)
}
if (newDisplayStatus.value !== displayStatus.value) {
await set_world_display_status(
props.instance.path,
props.instance.id,
'singleplayer',
path.value,
newDisplayStatus.value,
@@ -0,0 +1,387 @@
import { UpdatedIcon } from '@modrinth/assets'
import {
defineMessages,
type PopupNotificationButton,
type PopupNotificationProgressItem,
type PopupNotificationProgressType,
useVIntl,
} from '@modrinth/ui'
import { convertFileSrc } from '@tauri-apps/api/core'
import { computed, ref } from 'vue'
import type { Router } from 'vue-router'
import { install_job_listener } from '@/helpers/events'
import {
install_job_dismiss,
install_job_list,
install_job_retry,
installJobInstanceId,
type InstallJobSnapshot,
type InstallJobStatus,
type InstallProgress,
} from '@/helpers/install'
import { get_many as getInstances } from '@/helpers/instance'
const messages = defineMessages({
installs: {
id: 'app.action-bar.installs',
defaultMessage: 'Installs',
},
retry: {
id: 'app.action-bar.install.retry',
defaultMessage: 'Retry',
},
dismiss: {
id: 'app.action-bar.install.dismiss',
defaultMessage: 'Dismiss',
},
openInstance: {
id: 'app.action-bar.install.open-instance',
defaultMessage: 'Open instance',
},
installFailed: {
id: 'app.action-bar.install.failed',
defaultMessage: 'Install failed',
},
installFailedAppClosed: {
id: 'app.action-bar.install.failed-app-closed',
defaultMessage: 'Installation failed due to app closing.',
},
installFailedNetwork: {
id: 'app.action-bar.install.failed-network',
defaultMessage: 'Installation failed due to a network error.',
},
installFailedUnknown: {
id: 'app.action-bar.install.failed-unknown',
defaultMessage: 'Installation failed due to an unknown error.',
},
unknownInstance: {
id: 'app.action-bar.install.unknown-instance',
defaultMessage: 'Unknown instance',
},
})
const phaseMessages = defineMessages({
preparing_instance: {
id: 'app.install.phase.preparing_instance',
defaultMessage: 'Preparing instance',
},
resolving_pack: {
id: 'app.install.phase.resolving_pack',
defaultMessage: 'Resolving content',
},
downloading_pack_file: {
id: 'app.install.phase.downloading_pack_file',
defaultMessage: 'Downloading pack file',
},
reading_pack_manifest: {
id: 'app.install.phase.reading_pack_manifest',
defaultMessage: 'Reading pack manifest',
},
downloading_content: {
id: 'app.install.phase.downloading_content',
defaultMessage: 'Downloading content',
},
extracting_overrides: {
id: 'app.install.phase.extracting_overrides',
defaultMessage: 'Extracting overrides',
},
resolving_minecraft: {
id: 'app.install.phase.resolving_minecraft',
defaultMessage: 'Resolving Minecraft',
},
resolving_loader: {
id: 'app.install.phase.resolving_loader',
defaultMessage: 'Resolving loader',
},
preparing_java: {
id: 'app.install.phase.preparing_java',
defaultMessage: 'Preparing Java',
},
downloading_minecraft: {
id: 'app.install.phase.downloading_minecraft',
defaultMessage: 'Downloading Minecraft',
},
running_loader_processors: {
id: 'app.install.phase.running_loader_processors',
defaultMessage: 'Running loader processors',
},
finalizing: {
id: 'app.install.phase.finalizing',
defaultMessage: 'Finalizing',
},
rolling_back: {
id: 'app.install.phase.rolling_back',
defaultMessage: 'Rolling back',
},
})
const javaStepMessages = defineMessages({
resolving: {
id: 'app.install.phase.preparing_java.resolving',
defaultMessage: 'Preparing Java {version}',
},
fetching_metadata: {
id: 'app.install.phase.preparing_java.fetching-metadata',
defaultMessage: 'Fetching Java {version}',
},
downloading: {
id: 'app.install.phase.preparing_java.downloading',
defaultMessage: 'Downloading Java {version}',
},
extracting: {
id: 'app.install.phase.preparing_java.extracting',
defaultMessage: 'Extracting Java {version}',
},
validating: {
id: 'app.install.phase.preparing_java.validating',
defaultMessage: 'Validating Java {version}',
},
})
const visibleJobStatuses = new Set<InstallJobStatus>(['queued', 'running', 'failed', 'interrupted'])
function getDisplayIconUrl(icon: string | null | undefined): string | null {
if (!icon) return null
if (/^(https?:|data:|blob:|asset:|tauri:)/.test(icon)) return icon
return convertFileSrc(icon)
}
export async function useInstallJobNotifications(opts: {
router: Router
handleError: (err: unknown) => void
onChange: () => void
}) {
const { formatMessage } = useVIntl()
const jobs = ref<InstallJobSnapshot[]>([])
const iconUrls = ref<Record<string, string | null>>({})
const instanceNames = ref<Record<string, string>>({})
const jobOrder = new Map<string, number>()
let refreshRequest = 0
let metadataRequest = 0
let nextJobOrder = 0
function getTitle(job: InstallJobSnapshot): string {
if (job.display?.title) return job.display.title
if (job.details.type === 'instance') return job.details.name
if (job.details.type === 'modpack' && job.details.title) return job.details.title
const instanceId = installJobInstanceId(job)
return (
(instanceId ? instanceNames.value[instanceId] : null) ??
formatMessage(messages.unknownInstance)
)
}
function getText(job: InstallJobSnapshot): string {
if (job.status === 'failed' || job.status === 'interrupted') {
if (job.error?.code === 'interrupted') {
return formatMessage(messages.installFailedAppClosed)
}
if (job.error?.code === 'network_error') {
return formatMessage(messages.installFailedNetwork)
}
return formatMessage(messages.installFailedUnknown)
}
if (job.phase === 'preparing_java' && job.details.type === 'java') {
return formatMessage(javaStepMessages[job.details.step], {
version: job.details.major_version,
})
}
return formatMessage(phaseMessages[job.phase])
}
function getProgressType(job: InstallJobSnapshot): PopupNotificationProgressType | undefined {
if (!getEffectiveProgress(job)) return undefined
if (
job.phase === 'preparing_java' &&
job.details.type === 'java' &&
job.details.step === 'downloading'
) {
return 'bytes'
}
if (job.phase === 'downloading_content') {
return job.progress?.secondary ? 'bytes' : 'count'
}
if (
job.phase === 'downloading_pack_file' ||
job.phase === 'extracting_overrides' ||
job.phase === 'downloading_minecraft'
) {
return 'bytes'
}
if (job.phase === 'running_loader_processors') {
return 'count'
}
return 'percentage'
}
function getEffectiveProgress(job: InstallJobSnapshot): InstallProgress | null | undefined {
if (job.phase === 'downloading_content' && job.progress?.secondary) {
return job.progress.secondary
}
return job.progress
}
function getProgress(job: InstallJobSnapshot): number {
if (job.status === 'succeeded') return 1
if (job.status === 'failed' || job.status === 'interrupted') return 0
const progress = getEffectiveProgress(job)
if (!progress || progress.total <= 0) return 0
return Math.max(0, Math.min(1, progress.current / progress.total))
}
function isTerminalJob(job: InstallJobSnapshot): boolean {
return job.status === 'failed' || job.status === 'interrupted'
}
function getTerminalButtons(job: InstallJobSnapshot): PopupNotificationButton[] | undefined {
if (!isTerminalJob(job)) return undefined
return [
{
label: formatMessage(messages.retry),
icon: UpdatedIcon,
color: 'brand',
keepOpen: true,
action: async () => {
await install_job_retry(job.job_id).catch(opts.handleError)
await refresh()
},
},
]
}
function setJobs(nextJobs: InstallJobSnapshot[]) {
for (const job of nextJobs) {
if (!jobOrder.has(job.job_id)) {
jobOrder.set(job.job_id, nextJobOrder++)
}
}
jobs.value = nextJobs
.filter((job) => visibleJobStatuses.has(job.status))
.sort(
(a, b) =>
a.created.localeCompare(b.created) ||
(jobOrder.get(a.job_id) ?? 0) - (jobOrder.get(b.job_id) ?? 0),
)
}
const progressItems = computed<PopupNotificationProgressItem[]>(() =>
jobs.value.map((job) => {
const progress = getEffectiveProgress(job)
return {
id: job.job_id,
title: getTitle(job),
text: getText(job),
iconUrl: iconUrls.value[job.job_id] ?? null,
progress: getProgress(job),
waiting: !job.progress && ['queued', 'running'].includes(job.status),
showProgress: !isTerminalJob(job),
wrapText: isTerminalJob(job),
progressType: isTerminalJob(job) ? undefined : getProgressType(job),
progressCurrent: isTerminalJob(job) ? undefined : progress?.current,
progressTotal: isTerminalJob(job) ? undefined : progress?.total,
buttons: getTerminalButtons(job),
onDismiss: isTerminalJob(job)
? async () => {
await install_job_dismiss(job.job_id).catch(opts.handleError)
await refresh()
}
: undefined,
}
}),
)
const buttons = computed<PopupNotificationButton[] | undefined>(() => undefined)
async function refreshMetadata(notify = true) {
const request = ++metadataRequest
const sourceJobs = jobs.value
const instanceIds = Array.from(
new Set(
sourceJobs
.map((job) => installJobInstanceId(job))
.filter((instanceId): instanceId is string => !!instanceId),
),
)
const instances = instanceIds.length
? await getInstances(instanceIds).catch((error) => {
opts.handleError(error)
return []
})
: []
if (request !== metadataRequest) {
return
}
const instanceIconUrls = new Map(
instances.map((instance) => [instance.id, getDisplayIconUrl(instance.icon_path)]),
)
instanceNames.value = Object.fromEntries(
instances.map((instance) => [instance.id, instance.name]),
)
iconUrls.value = Object.fromEntries(
sourceJobs.map((job) => [
job.job_id,
getDisplayIconUrl(job.display?.icon) ??
instanceIconUrls.get(installJobInstanceId(job) ?? '') ??
null,
]),
)
if (notify) {
opts.onChange()
}
}
async function refresh(notify = true) {
const request = ++refreshRequest
const nextJobs = await install_job_list(false).catch((error) => {
opts.handleError(error)
return []
})
if (request !== refreshRequest) {
return
}
setJobs(nextJobs)
await refreshMetadata(false)
if (request !== refreshRequest) {
return
}
if (notify) {
opts.onChange()
}
}
function applyJobUpdate(job: InstallJobSnapshot) {
refreshRequest += 1
const existingJob = jobs.value.find((item) => item.job_id === job.job_id)
if (existingJob && existingJob.modified.localeCompare(job.modified) > 0) {
return
}
setJobs([...jobs.value.filter((item) => item.job_id !== job.job_id), job])
opts.onChange()
void refreshMetadata()
}
await refresh(false)
const unlisten = await install_job_listener((job: InstallJobSnapshot) => applyJobUpdate(job))
return {
active: computed(() => jobs.value.length > 0),
title: computed(() => formatMessage(messages.installs)),
progressItems,
buttons,
refresh,
dispose: () => unlisten(),
}
}
@@ -2,17 +2,17 @@ import type { Labrinth } from '@modrinth/api-client'
import { CheckIcon, PlayIcon, PlusIcon, StopCircleIcon } from '@modrinth/assets'
import type { CardAction } from '@modrinth/ui'
import { commonMessages, defineMessages, useDebugLogger, useVIntl } from '@modrinth/ui'
import { useQueryClient } from '@tanstack/vue-query'
import { openUrl } from '@tauri-apps/plugin-opener'
import type { ComputedRef, Ref } from 'vue'
import { onUnmounted, ref, shallowRef } from 'vue'
import type { Router } from 'vue-router'
import { process_listener } from '@/helpers/events'
import { get_by_profile_path } from '@/helpers/process'
import { kill, list as listInstances } from '@/helpers/profile.js'
import { kill, list as listInstances } from '@/helpers/instance'
import { get_by_instance_id } from '@/helpers/process'
import type { GameInstance } from '@/helpers/types'
import { add_server_to_profile, getServerLatency } from '@/helpers/worlds'
import { getServerAddress } from '@/store/install.js'
import { add_server_to_instance, getServerAddress, getServerLatency } from '@/helpers/worlds'
interface BrowseServerInstance {
name: string
@@ -65,6 +65,7 @@ const messages = defineMessages({
export function useAppServerBrowse(options: UseAppServerBrowseOptions) {
const { formatMessage } = useVIntl()
const queryClient = useQueryClient()
const debugLog = useDebugLogger('BrowseServer')
const serverPings = shallowRef<Record<string, number | undefined>>({})
const serverPingCache = new Map<string, number | undefined>()
@@ -83,13 +84,11 @@ export function useAppServerBrowse(options: UseAppServerBrowseOptions) {
})
const newRunning: Record<string, string> = {}
for (const hit of hits) {
const inst = packs.find(
(pack: GameInstance) => pack.linked_data?.project_id === hit.project_id,
)
const inst = packs.find((pack: GameInstance) => pack.link?.project_id === hit.project_id)
if (inst) {
const processes = await get_by_profile_path(inst.path).catch(() => [])
const processes = await get_by_instance_id(inst.id).catch(() => [])
if (Array.isArray(processes) && processes.length > 0) {
newRunning[hit.project_id] = inst.path
newRunning[hit.project_id] = inst.id
}
}
}
@@ -99,9 +98,9 @@ export function useAppServerBrowse(options: UseAppServerBrowseOptions) {
async function handleStopServerProject(projectId: string) {
debugLog('handleStopServerProject', projectId)
const instancePath = runningServerProjects.value[projectId]
if (!instancePath) return
await kill(instancePath).catch(() => {})
const instanceId = runningServerProjects.value[projectId]
if (!instanceId) return
await kill(instanceId).catch(() => {})
const { [projectId]: _, ...rest } = runningServerProjects.value
runningServerProjects.value = rest
}
@@ -118,9 +117,10 @@ export function useAppServerBrowse(options: UseAppServerBrowseOptions) {
if (!address) return
if (options.instance.value) {
const instanceId = options.instance.value.id
try {
await add_server_to_profile(
options.instance.value.path,
await add_server_to_instance(
instanceId,
project.name,
address,
'prompt',
@@ -128,6 +128,7 @@ export function useAppServerBrowse(options: UseAppServerBrowseOptions) {
project.minecraft_java_server?.content?.kind,
)
options.newlyInstalled.value.push(project.project_id)
await queryClient.invalidateQueries({ queryKey: ['worlds', instanceId] })
} catch (error) {
options.handleError(error)
}
@@ -289,11 +290,11 @@ export function useAppServerBrowse(options: UseAppServerBrowseOptions) {
}
}
process_listener((event: { event: string; profile_path_id: string }) => {
process_listener((event: { event: string; instance_id: string }) => {
debugLog('process event', event)
if (event.event === 'finished') {
const projectId = Object.entries(runningServerProjects.value).find(
([, path]) => path === event.profile_path_id,
([, path]) => path === event.instance_id,
)?.[0]
if (projectId) {
const { [projectId]: _, ...rest } = runningServerProjects.value
@@ -22,8 +22,8 @@ interface InstanceConsoleEntry {
const instances = new Map<string, InstanceConsoleEntry>()
function getOrCreate(profilePathId: string): InstanceConsoleEntry {
let entry = instances.get(profilePathId)
function getOrCreate(instanceId: string): InstanceConsoleEntry {
let entry = instances.get(instanceId)
if (entry) return entry
entry = {
@@ -32,25 +32,25 @@ function getOrCreate(profilePathId: string): InstanceConsoleEntry {
historicalCache: new Map(),
logList: null,
}
instances.set(profilePathId, entry)
instances.set(instanceId, entry)
return entry
}
async function hydrate(profilePathId: string): Promise<void> {
const entry = getOrCreate(profilePathId)
async function hydrate(instanceId: string): Promise<void> {
const entry = getOrCreate(instanceId)
if (entry.liveConsole.output.value.length > 0) return
const buffer = await get_live_log_buffer(profilePathId)
const buffer = await get_live_log_buffer(instanceId)
if (buffer) {
entry.liveConsole.addLegacyLog(buffer)
}
}
async function getHistoricalLogs(profilePathId: string, instancePath: string): Promise<LogEntry[]> {
const entry = getOrCreate(profilePathId)
async function getHistoricalLogs(instanceId: string): Promise<LogEntry[]> {
const entry = getOrCreate(instanceId)
if (entry.logList) return entry.logList
const logs: LogEntry[] = await get_logs(instancePath, true)
const logs: LogEntry[] = await get_logs(instanceId, true)
entry.logList = logs
for (const log of logs) {
@@ -62,38 +62,38 @@ async function getHistoricalLogs(profilePathId: string, instancePath: string): P
return logs
}
function getHistoricalContent(profilePathId: string, filename: string): string | undefined {
return instances.get(profilePathId)?.historicalCache.get(filename)
function getHistoricalContent(instanceId: string, filename: string): string | undefined {
return instances.get(instanceId)?.historicalCache.get(filename)
}
function invalidate(profilePathId: string): void {
const entry = instances.get(profilePathId)
function invalidate(instanceId: string): void {
const entry = instances.get(instanceId)
if (!entry) return
entry.historicalCache.clear()
entry.logList = null
}
async function clearLive(profilePathId: string): Promise<void> {
const entry = getOrCreate(profilePathId)
async function clearLive(instanceId: string): Promise<void> {
const entry = getOrCreate(instanceId)
entry.liveConsole.clear()
await clear_log_buffer(profilePathId).catch(() => {})
await clear_log_buffer(instanceId).catch(() => {})
}
async function destroy(profilePathId: string): Promise<void> {
instances.delete(profilePathId)
await clear_log_buffer(profilePathId).catch(() => {})
async function destroy(instanceId: string): Promise<void> {
instances.delete(instanceId)
await clear_log_buffer(instanceId).catch(() => {})
}
export function useInstanceConsole(profilePathId: string) {
const entry = getOrCreate(profilePathId)
export function useInstanceConsole(instanceId: string) {
const entry = getOrCreate(instanceId)
return {
liveConsole: entry.liveConsole,
historicalConsole: entry.historicalConsole,
hydrate: () => hydrate(profilePathId),
getHistoricalLogs: (instancePath: string) => getHistoricalLogs(profilePathId, instancePath),
getHistoricalContent: (filename: string) => getHistoricalContent(profilePathId, filename),
invalidate: () => invalidate(profilePathId),
clearLive: () => clearLive(profilePathId),
destroy: () => destroy(profilePathId),
hydrate: () => hydrate(instanceId),
getHistoricalLogs: () => getHistoricalLogs(instanceId),
getHistoricalContent: (filename: string) => getHistoricalContent(instanceId, filename),
invalidate: () => invalidate(instanceId),
clearLive: () => clearLive(instanceId),
destroy: () => destroy(instanceId),
}
}
+1 -1
View File
@@ -1,6 +1,6 @@
/**
* All theseus API calls return serialized values (both return values and errors);
* So, for example, addDefaultInstance creates a blank Profile object, where the Rust struct is serialized,
* So, for example, addDefaultInstance creates a blank instance object, where the Rust struct is serialized,
* and deserialized into a usable JS object.
*/
import { invoke } from '@tauri-apps/api/core'
+25 -11
View File
@@ -31,8 +31,8 @@ import { listen } from '@tauri-apps/api/event'
pack_name: name of the pack
pack_id, optional, the id of the modpack
pack_version, optional, the version of the modpack
profile_name: name of the profile
profile_uuid: unique identification of the profile
instance_name: name of the instance
instance_id: unique identification of the instance
}
loader_uuid: unique identification of the loading bar
@@ -57,18 +57,32 @@ export async function process_listener(callback) {
return await listen('process', (event) => callback(event.payload))
}
/// Payload for the 'profile' event
/// Payload for the 'instance' event
/*
ProfilePayload {
uuid: unique identification of the process in the state (currently identified by path, but that will change)
name: name of the profile
profile_path: relative path toprofile_listener profile (used for path identification)
path: path to profile (used for opening the profile in the OS file explorer)
InstancePayload {
instance_id: unique identification of the instance
event: event type ("Created", "Added", "Edited", "Removed")
}
*/
export async function profile_listener(callback) {
return await listen('profile', (event) => callback(event.payload))
export async function instance_listener(callback) {
return await listen('instance', (event) => callback(event.payload))
}
/// Payload for the 'instance_bulk_update_progress' event
/*
InstanceBulkUpdateProgress {
instanceId: string
stage: "resolving_versions" | "downloading" | "finishing"
current: number
total: number
}
*/
export async function instance_bulk_update_progress_listener(callback) {
return await listen('instance_bulk_update_progress', (event) => callback(event.payload))
}
export async function install_job_listener(callback) {
return await listen('install_job', (event) => callback(event.payload))
}
/// Payload for the 'command' event
@@ -105,7 +119,7 @@ export async function notification_listener(callback) {
/// Payload for the 'log' event
/*
LogPayload {
profile_path_id: string,
instance_id: string,
type: "log4j" | "legacy",
// log4j fields (when type === "log4j"):
timestamp_millis?: number,
+1 -1
View File
@@ -8,7 +8,7 @@ import type { ModrinthCredentials } from '@/helpers/mr_auth'
export type UserStatus = {
user_id: string
profile_name: string | null
instance_name: string | null
last_update: string
}
+3 -14
View File
@@ -1,11 +1,11 @@
/**
* All theseus API calls return serialized values (both return values and errors);
* So, for example, addDefaultInstance creates a blank Profile object, where the Rust struct is serialized,
* So, for example, addDefaultInstance creates a blank instance object, where the Rust struct is serialized,
* and deserialized into a usable JS object.
*/
import { invoke } from '@tauri-apps/api/core'
import { create } from './profile'
import { install_import_instance } from './install'
/*
API for importing instances from other launchers
@@ -32,19 +32,8 @@ export async function get_importable_instances(launcherType, basePath) {
}
/// Import an instance from a launcher type and base path
/// eg: import_instance("profile-name-to-go-to", "MultiMC", "C:/MultiMC", "Instance 1")
export async function import_instance(launcherType, basePath, instanceFolder) {
// create a basic, empty instance (most properties will be filled in by the import process)
// We do NOT watch the fs for changes to avoid duplicate events during installation
// fs watching will be enabled once the instance is imported
const profilePath = await create(instanceFolder, '1.19.4', 'vanilla', 'latest', null, true)
return await invoke('plugin:import|import_instance', {
profilePath,
launcherType,
basePath,
instanceFolder,
})
return await install_import_instance(launcherType, basePath, instanceFolder)
}
/// Checks if this instance is valid for importing, given a certain launcher type
+266
View File
@@ -0,0 +1,266 @@
import { invoke } from '@tauri-apps/api/core'
import { install_job_listener } from './events'
import type { InstanceLink, InstanceLoader } from './types'
export interface PackLocationVersionId {
type: 'fromVersionId'
project_id: string
version_id: string
title: string
icon_url?: string | null
}
export interface PackLocationFile {
type: 'fromFile'
path: string
}
export type CreatePackLocation = PackLocationVersionId | PackLocationFile
export interface InstallModpackPreview {
name: string
gameVersion: string
modloader: InstanceLoader
loaderVersion: string | null
icon?: string | null
iconUrl?: string | null
link?: InstanceLink | null
unknownFile: boolean
}
export interface InstallCreateInstanceRequest {
name: string
gameVersion: string
loader: InstanceLoader
loaderVersion: string | null
iconPath: string | null
link?: InstanceLink | null
}
export interface InstallPostInstallEdit {
name?: string | null
iconPath?: string | null
link?: InstanceLink | null
}
export type InstallJobStatus =
| 'queued'
| 'running'
| 'succeeded'
| 'failed'
| 'interrupted'
| 'canceled'
export type InstallPhaseId =
| 'preparing_instance'
| 'resolving_pack'
| 'downloading_pack_file'
| 'reading_pack_manifest'
| 'downloading_content'
| 'extracting_overrides'
| 'resolving_minecraft'
| 'resolving_loader'
| 'preparing_java'
| 'downloading_minecraft'
| 'running_loader_processors'
| 'finalizing'
| 'rolling_back'
export interface InstallProgress {
current: number
total: number
secondary?: InstallProgressSecondary | null
}
export interface InstallProgressSecondary {
current: number
total: number
}
export type InstallJavaStep =
| 'resolving'
| 'fetching_metadata'
| 'downloading'
| 'extracting'
| 'validating'
export interface InstallJobSnapshot {
job_id: string
instance_id?: string | null
kind:
| 'create_instance'
| 'create_modpack_instance'
| 'import_instance'
| 'duplicate_instance'
| 'install_existing_instance'
| 'install_pack_to_existing_instance'
status: InstallJobStatus
target:
| { type: 'new_instance'; instance_id?: string | null }
| { type: 'existing_instance'; instance_id: string }
phase: InstallPhaseId
progress?: InstallProgress | null
details:
| { type: 'empty' }
| { type: 'instance'; name: string }
| { type: 'minecraft'; game_version: string; loader: InstanceLoader }
| { type: 'java'; major_version: number; step: InstallJavaStep }
| {
type: 'modpack'
project_id?: string | null
version_id?: string | null
title?: string | null
}
| { type: 'import'; launcher_type: string; instance_folder: string }
display?: { title: string; icon?: string | null } | null
error?: { code: string; message: string } | null
created: string
modified: string
finished?: string | null
}
export async function install_get_modpack_preview(location: CreatePackLocation) {
return await invoke<InstallModpackPreview>('plugin:install|install_get_modpack_preview', {
location,
})
}
export async function install_create_instance(request: InstallCreateInstanceRequest) {
return await invoke<InstallJobSnapshot>('plugin:install|install_create_instance', { request })
}
export async function install_create_modpack_instance(
location: CreatePackLocation,
postInstallEdit?: InstallPostInstallEdit | null,
) {
return await invoke<InstallJobSnapshot>('plugin:install|install_create_modpack_instance', {
location,
postInstallEdit,
})
}
export async function install_import_instance(
launcherType: string,
basePath: string,
instanceFolder: string,
) {
return await invoke<InstallJobSnapshot>('plugin:install|install_import_instance', {
launcherType,
basePath,
instanceFolder,
})
}
export async function install_duplicate_instance(sourceInstanceId: string) {
return await invoke<InstallJobSnapshot>('plugin:install|install_duplicate_instance', {
sourceInstanceId,
})
}
export async function install_existing_instance(instanceId: string, force: boolean) {
return await invoke<InstallJobSnapshot>('plugin:install|install_existing_instance', {
instanceId,
force,
})
}
export async function install_pack_to_existing_instance(
instanceId: string,
location: CreatePackLocation,
postInstallEdit?: InstallPostInstallEdit | null,
) {
return await invoke<InstallJobSnapshot>('plugin:install|install_pack_to_existing_instance', {
instanceId,
location,
postInstallEdit,
})
}
export async function install_job_list(includeFinished: boolean) {
return await invoke<InstallJobSnapshot[]>('plugin:install|install_job_list', { includeFinished })
}
export async function install_job_get(jobId: string) {
return await invoke<InstallJobSnapshot>('plugin:install|install_job_get', { jobId })
}
export async function install_job_retry(jobId: string) {
return await invoke<InstallJobSnapshot>('plugin:install|install_job_retry', { jobId })
}
export async function install_job_cancel(jobId: string) {
return await invoke<InstallJobSnapshot>('plugin:install|install_job_cancel', { jobId })
}
export async function install_job_dismiss(jobId: string) {
return await invoke<void>('plugin:install|install_job_dismiss', { jobId })
}
export function installJobInstanceId(job: InstallJobSnapshot): string | null {
return job.instance_id ?? job.target.instance_id ?? null
}
export function isInstallJobFinished(status: InstallJobStatus) {
return (
status === 'succeeded' ||
status === 'failed' ||
status === 'interrupted' ||
status === 'canceled'
)
}
function settleInstallJob(job: InstallJobSnapshot) {
if (job.status === 'succeeded') return job
throw new Error(job.error?.message ?? `Install job ${job.job_id} ${job.status}`)
}
export async function wait_for_install_job(jobId: string) {
const current = await install_job_get(jobId)
if (isInstallJobFinished(current.status)) return settleInstallJob(current)
return await new Promise<InstallJobSnapshot>((resolve, reject) => {
let finished = false
let unlisten: (() => void) | null = null
const cleanup = () => {
if (unlisten) {
unlisten()
unlisten = null
}
}
const resolveJob = (job: InstallJobSnapshot) => {
if (finished || job.job_id !== jobId || !isInstallJobFinished(job.status)) return
finished = true
cleanup()
try {
resolve(settleInstallJob(job))
} catch (err) {
reject(err)
}
}
const rejectWait = (err: unknown) => {
if (finished) return
finished = true
cleanup()
reject(err)
}
install_job_listener(resolveJob)
.then((listener) => {
if (finished) {
listener()
return
}
unlisten = listener
install_job_get(jobId).then(resolveJob).catch(rejectWait)
})
.catch(rejectWait)
})
}
@@ -10,7 +10,7 @@ import {
get_content_items,
get_linked_modpack_info,
type LinkedModpackInfo,
} from '@/helpers/profile'
} from '@/helpers/instance'
import { get_categories } from '@/helpers/tags.js'
import type { CacheBehaviour } from '@/helpers/types'
+333
View File
@@ -0,0 +1,333 @@
/**
* All theseus API calls return serialized values (both return values and errors);
* So, for example, addDefaultInstance creates a blank instance object, where the Rust struct is serialized,
* and deserialized into a usable JS object.
*/
import type { Labrinth } from '@modrinth/api-client'
import type { ContentItem, ContentOwner } from '@modrinth/ui'
import { invoke } from '@tauri-apps/api/core'
import type { InstallJobSnapshot } from './install'
import type {
CacheBehaviour,
ContentFile,
ContentFileProjectType,
GameInstance,
InstanceLoader,
} from './types'
export async function remove(instanceId: string): Promise<void> {
return await invoke('plugin:instance|instance_remove', { instanceId })
}
export async function get(instanceId: string): Promise<GameInstance | null> {
return await invoke('plugin:instance|instance_get', { instanceId })
}
export async function get_many(instanceIds: string[]): Promise<GameInstance[]> {
return await invoke('plugin:instance|instance_get_many', { instanceIds })
}
export async function get_projects(
instanceId: string,
cacheBehaviour?: CacheBehaviour,
): Promise<Record<string, ContentFile>> {
return await invoke('plugin:instance|instance_get_projects', { instanceId, cacheBehaviour })
}
export async function get_installed_project_ids(instanceId: string): Promise<string[]> {
return await invoke('plugin:instance|instance_get_installed_project_ids', { instanceId })
}
export type InstanceInstallTarget = {
game_version: string
loader: string
}
export type InstanceInstallCandidate = {
id: string
name: string
icon_path?: string | null
game_version: string
loader: InstanceLoader
installed: boolean
compatible: boolean
}
export async function get_install_candidates(
projectId: string,
projectType: string,
targets: InstanceInstallTarget[],
): Promise<InstanceInstallCandidate[]> {
return await invoke('plugin:instance|instance_get_install_candidates', {
projectId,
projectType,
targets,
})
}
// Get content items with rich metadata for an instance
// Returns content items filtered to exclude modpack files (if linked),
// sorted alphabetically by project name
export async function get_content_items(
instanceId: string,
cacheBehaviour?: CacheBehaviour,
): Promise<ContentItem[]> {
return await invoke('plugin:instance|instance_get_content_items', { instanceId, cacheBehaviour })
}
// Linked modpack info returned from backend
export interface LinkedModpackInfo {
project: Labrinth.Projects.v2.Project
version: Labrinth.Versions.v2.Version
owner: ContentOwner | null
has_update: boolean
update_version_id: string | null
update_version: Labrinth.Versions.v2.Version | null
}
// Get linked modpack info for an instance
// Returns project, version, and owner information for the linked modpack,
// or null if the instance is not linked to a modpack
export async function get_linked_modpack_info(
instanceId: string,
cacheBehaviour?: CacheBehaviour,
): Promise<LinkedModpackInfo | null> {
return await invoke('plugin:instance|instance_get_linked_modpack_info', {
instanceId,
cacheBehaviour,
})
}
// Get content items that are part of the linked modpack
// Returns the modpack's dependencies as ContentItem list
// Returns empty array if the instance is not linked to a modpack
export async function get_linked_modpack_content(
instanceId: string,
cacheBehaviour?: CacheBehaviour,
): Promise<ContentItem[]> {
return await invoke('plugin:instance|instance_get_linked_modpack_content', {
instanceId,
cacheBehaviour,
})
}
// Convert a list of dependencies into ContentItems with rich metadata
export async function get_dependencies_as_content_items(
dependencies: Labrinth.Versions.v3.Dependency[],
cacheBehaviour?: CacheBehaviour,
): Promise<ContentItem[]> {
return await invoke('plugin:instance|instance_get_dependencies_as_content_items', {
dependencies,
cacheBehaviour,
})
}
export async function get_full_path(instanceId: string): Promise<string> {
return await invoke('plugin:instance|instance_get_full_path', { instanceId })
}
export async function get_mod_full_path(instanceId: string, projectPath: string): Promise<string> {
return await invoke('plugin:instance|instance_get_mod_full_path', { instanceId, projectPath })
}
export interface JavaVersion {
parsed_version: number
version: string
architecture: string
path: string
}
export async function get_optimal_jre_key(instanceId: string): Promise<JavaVersion | null> {
return await invoke('plugin:instance|instance_get_optimal_jre_key', { instanceId })
}
export async function list(): Promise<GameInstance[]> {
return await invoke('plugin:instance|instance_list')
}
export async function check_installed(instanceId: string, projectId: string): Promise<boolean> {
return await invoke('plugin:instance|instance_check_installed', { instanceId, projectId })
}
export async function update_all(instanceId: string): Promise<Record<string, string>> {
return await invoke('plugin:instance|instance_update_all', { instanceId })
}
// Updates a specified project
export async function update_project(instanceId: string, projectPath: string): Promise<string> {
return await invoke('plugin:instance|instance_update_project', { instanceId, projectPath })
}
// Add a project to an instance from a version
// Returns a path to the new project file
export type DownloadReason = 'standalone' | 'dependency' | 'modpack' | 'update'
export interface ResolutionPreferences {
game_versions?: string[]
loaders?: string[]
}
export interface ResolveContentRequest {
project_id: string
version_id?: string | null
content_type: Labrinth.Content.v3.ContentType
selected?: ResolutionPreferences
}
export interface ResolvedContent {
project_id: string
version_id: string
dependent_on_version_id?: string | null
}
export interface ResolveContentPlan {
primary: ResolvedContent
dependencies: ResolvedContent[]
skipped: Array<{
project_id: string
version_id?: string | null
dependent_on_version_id?: string | null
reason: string
}>
}
export async function add_project_from_version(
instanceId: string,
versionId: string,
reason: DownloadReason,
dependentOnVersionId?: string,
): Promise<string> {
return await invoke('plugin:instance|instance_add_project_from_version', {
instanceId,
versionId,
reason,
dependentOnVersionId,
})
}
export async function install_project_with_dependencies(
instanceId: string,
request: ResolveContentRequest,
): Promise<ResolveContentPlan> {
return await invoke('plugin:instance|instance_install_project_with_dependencies', {
instanceId,
request,
})
}
export async function switch_project_version_with_dependencies(
instanceId: string,
projectPath: string,
versionId: string,
): Promise<string> {
return await invoke('plugin:instance|instance_switch_project_version_with_dependencies', {
instanceId,
projectPath,
versionId,
})
}
// Add a project to an instance from a path + project_type
// Returns a path to the new project file
export async function add_project_from_path(
instanceId: string,
projectPath: string,
projectType?: ContentFileProjectType,
): Promise<string> {
return await invoke('plugin:instance|instance_add_project_from_path', {
instanceId,
projectPath,
projectType,
})
}
// Toggle disabling a project
export async function toggle_disable_project(
instanceId: string,
projectPath: string,
desiredEnabled?: boolean,
): Promise<string> {
return await invoke('plugin:instance|instance_toggle_disable_project', {
instanceId,
projectPath,
desiredEnabled,
})
}
// Remove a project
export async function remove_project(instanceId: string, projectPath: string): Promise<void> {
return await invoke('plugin:instance|instance_remove_project', { instanceId, projectPath })
}
// Update a managed Modrinth instance to a specific version
export async function update_managed_modrinth_version(
instanceId: string,
versionId: string,
): Promise<InstallJobSnapshot> {
return await invoke('plugin:instance|instance_update_managed_modrinth_version', {
instanceId,
versionId,
})
}
// Repair a managed Modrinth instance
export async function update_repair_modrinth(instanceId: string): Promise<InstallJobSnapshot> {
return await invoke('plugin:instance|instance_repair_managed_modrinth', { instanceId })
}
// Export an instance to .mrpack
// included_overrides is an array of paths to override folders to include (ie: 'mods', 'resource_packs')
// Version id is optional (ie: 1.1.5)
export async function export_instance_mrpack(
instanceId: string,
exportLocation: string,
includedOverrides: string[],
versionId?: string,
description?: string,
name?: string,
): Promise<void> {
return await invoke('plugin:instance|instance_export_mrpack', {
instanceId,
exportLocation,
includedOverrides,
versionId,
description,
name,
})
}
// Given a folder path, populate an array of all the subfolders
// Intended to be used for finding potential override folders
// profile
// -- mods
// -- resourcepacks
// -- file1
// => [mods, resourcepacks]
// allows selection for 'included_overrides' in export_instance_mrpack
export async function get_pack_export_candidates(instanceId: string): Promise<string[]> {
return await invoke('plugin:instance|instance_get_pack_export_candidates', { instanceId })
}
// Run Minecraft using an instance
// Returns PID of child
export async function run(
instanceId: string,
serverAddress: string | null = null,
): Promise<unknown> {
return await invoke('plugin:instance|instance_run', { instanceId, serverAddress })
}
export async function kill(instanceId: string): Promise<void> {
return await invoke('plugin:instance|instance_kill', { instanceId })
}
// Edits an instance
export async function edit(instanceId: string, editInstance: Partial<GameInstance>): Promise<void> {
return await invoke('plugin:instance|instance_edit', { instanceId, editInstance })
}
// Edits an instance's icon
export async function edit_icon(instanceId: string, iconPath: string | null): Promise<void> {
return await invoke('plugin:instance|instance_edit_icon', { instanceId, iconPath })
}
+1 -1
View File
@@ -1,6 +1,6 @@
/**
* All theseus API calls return serialized values (both return values and errors);
* So, for example, addDefaultInstance creates a blank Profile object, where the Rust struct is serialized,
* So, for example, addDefaultInstance creates a blank instance object, where the Rust struct is serialized,
* and deserialized into a usable JS object.
*/
import { invoke } from '@tauri-apps/api/core'
+25 -25
View File
@@ -1,6 +1,6 @@
/**
* All theseus API calls return serialized values (both return values and errors);
* So, for example, addDefaultInstance creates a blank Profile object, where the Rust struct is serialized,
* So, for example, addDefaultInstance creates a blank instance object, where the Rust struct is serialized,
* and deserialized into a usable JS object.
*/
import { invoke } from '@tauri-apps/api/core'
@@ -14,41 +14,41 @@ pub struct Logs {
}
*/
/// Get all logs that exist for a given profile
/// Get all logs that exist for a given instance
/// This is returned as an array of Log objects, sorted by filename (the folder name, when the log was created)
export async function get_logs(profilePath, clearContents) {
return await invoke('plugin:logs|logs_get_logs', { profilePath, clearContents })
export async function get_logs(instanceId, clearContents) {
return await invoke('plugin:logs|logs_get_logs', { instanceId, clearContents })
}
/// Get a profile's log by filename
export async function get_logs_by_filename(profilePath, logType, filename) {
return await invoke('plugin:logs|logs_get_logs_by_filename', { profilePath, logType, filename })
/// Get an instance's log by filename
export async function get_logs_by_filename(instanceId, logType, filename) {
return await invoke('plugin:logs|logs_get_logs_by_filename', { instanceId, logType, filename })
}
/// Get a profile's log text only by filename
export async function get_output_by_filename(profilePath, logType, filename) {
/// Get an instance's log text only by filename
export async function get_output_by_filename(instanceId, logType, filename) {
return await invoke('plugin:logs|logs_get_output_by_filename', {
profilePath,
instanceId,
logType,
filename,
})
}
/// Delete a profile's log by filename
export async function delete_logs_by_filename(profilePath, logType, filename) {
/// Delete an instance's log by filename
export async function delete_logs_by_filename(instanceId, logType, filename) {
return await invoke('plugin:logs|logs_delete_logs_by_filename', {
profilePath,
instanceId,
logType,
filename,
})
}
/// Delete all logs for a given profile
export async function delete_logs(profilePath) {
return await invoke('plugin:logs|logs_delete_logs', { profilePath })
/// Delete all logs for a given instance
export async function delete_logs(instanceId) {
return await invoke('plugin:logs|logs_delete_logs', { instanceId })
}
/// Get the latest log for a given profile and cursor (startpoint to read withi nthe file)
/// Get the latest log for a given instance and cursor (startpoint to read within the file)
/// Returns:
/*
{
@@ -59,16 +59,16 @@ export async function delete_logs(profilePath) {
*/
// From latest.log directly
export async function get_latest_log_cursor(profilePath, cursor) {
return await invoke('plugin:logs|logs_get_latest_log_cursor', { profilePath, cursor })
export async function get_latest_log_cursor(instanceId, cursor) {
return await invoke('plugin:logs|logs_get_latest_log_cursor', { instanceId, cursor })
}
/// Get all buffered live log lines for a profile from the Rust ring buffer
export async function get_live_log_buffer(profilePath) {
return await invoke('plugin:logs|logs_get_live_log_buffer', { profilePath })
/// Get all buffered live log lines for an instance from the Rust ring buffer
export async function get_live_log_buffer(instanceId) {
return await invoke('plugin:logs|logs_get_live_log_buffer', { instanceId })
}
/// Clear the live log buffer for a profile on the Rust side
export async function clear_log_buffer(profilePath) {
return await invoke('plugin:logs|logs_clear_live_log_buffer', { profilePath })
/// Clear the live log buffer for an instance on the Rust side
export async function clear_log_buffer(instanceId) {
return await invoke('plugin:logs|logs_clear_live_log_buffer', { instanceId })
}
+1 -1
View File
@@ -1,6 +1,6 @@
/**
* All theseus API calls return serialized values (both return values and errors);
* So, for example, addDefaultInstance creates a blank Profile object, where the Rust struct is serialized,
* So, for example, addDefaultInstance creates a blank instance object, where the Rust struct is serialized,
* and deserialized into a usable JS object.
*/
import { invoke } from '@tauri-apps/api/core'
-105
View File
@@ -1,105 +0,0 @@
import { invoke } from '@tauri-apps/api/core'
import { create } from './profile'
import type { InstanceLoader } from './types'
interface PackProfileCreator {
name: string
gameVersion: string
modloader: InstanceLoader
loaderVersion: string | null
unknownFile: boolean
}
interface PackLocationVersionId {
type: 'fromVersionId'
project_id: string
version_id: string
title: string
icon_url?: string
}
interface PackLocationFile {
type: 'fromFile'
path: string
}
export async function create_profile_and_install(
projectId: string,
versionId: string,
packTitle: string,
iconUrl?: string,
createInstanceCallback: (profile: string) => void = () => {},
): Promise<void> {
const location: PackLocationVersionId = {
type: 'fromVersionId',
project_id: projectId,
version_id: versionId,
title: packTitle,
icon_url: iconUrl,
}
const profile_creator = await invoke<PackProfileCreator>(
'plugin:pack|pack_get_profile_from_pack',
{ location },
)
const profile = await create(
profile_creator.name,
profile_creator.gameVersion,
profile_creator.modloader,
profile_creator.loaderVersion,
null,
true,
)
createInstanceCallback(profile)
return await invoke('plugin:pack|pack_install', { location, profile })
}
export async function install_to_existing_profile(
projectId: string,
versionId: string,
title: string,
profilePath: string,
): Promise<void> {
const location: PackLocationVersionId = {
type: 'fromVersionId',
project_id: projectId,
version_id: versionId,
title,
}
return await invoke('plugin:pack|pack_install', { location, profile: profilePath })
}
export async function create_profile_and_install_from_file(
path: string,
showUnknownPackWarningModal?: (createProfile: () => Promise<void>, fileName: string) => void,
): Promise<void> {
const location: PackLocationFile = {
type: 'fromFile',
path,
}
const profile_creator = await invoke<PackProfileCreator>(
'plugin:pack|pack_get_profile_from_pack',
{ location },
)
const createProfile = async () => {
const profile = await create(
profile_creator.name,
profile_creator.gameVersion,
profile_creator.modloader,
profile_creator.loaderVersion,
null,
true,
)
await invoke('plugin:pack|pack_install', { location, profile })
}
if (profile_creator.unknownFile && showUnknownPackWarningModal) {
const splitPath = path.split(/[\\/]/)
const fileName = splitPath ? splitPath[splitPath.length - 1] : path
showUnknownPackWarningModal(createProfile, fileName)
} else {
await createProfile()
}
}
+5 -5
View File
@@ -1,17 +1,17 @@
/**
* All theseus API calls return serialized values (both return values and errors);
* So, for example, addDefaultInstance creates a blank Profile object, where the Rust struct is serialized,
* So, for example, addDefaultInstance creates a blank instance object, where the Rust struct is serialized,
* and deserialized into a usable JS object.
*/
import { invoke } from '@tauri-apps/api/core'
/// Gets all running process IDs with a given profile path
/// Gets all running process IDs with a given instance ID
/// Returns [u32]
export async function get_by_profile_path(path) {
return await invoke('plugin:process|process_get_by_profile_path', { path })
export async function get_by_instance_id(instanceId) {
return await invoke('plugin:process|process_get_by_instance_id', { instanceId })
}
/// Gets all running process IDs with a given profile path
/// Gets all running process IDs
/// Returns [u32]
export async function get_all() {
return await invoke('plugin:process|process_get_all')
-317
View File
@@ -1,317 +0,0 @@
/**
* All theseus API calls return serialized values (both return values and errors);
* So, for example, addDefaultInstance creates a blank Profile object, where the Rust struct is serialized,
* and deserialized into a usable JS object.
*/
import type { Labrinth } from '@modrinth/api-client'
import type { ContentItem, ContentOwner } from '@modrinth/ui'
import { invoke } from '@tauri-apps/api/core'
import { install_to_existing_profile } from '@/helpers/pack'
import type {
CacheBehaviour,
ContentFile,
ContentFileProjectType,
GameInstance,
InstanceLoader,
} from './types'
// Add instance
/*
name: String, // the name of the profile, and relative path to create
game_version: String, // the game version of the profile
modloader: ModLoader, // the modloader to use
- ModLoader is an enum, with the following variants: Vanilla, Forge, Fabric, Quilt
loader_version: String, // the modloader version to use, set to "latest", "stable", or the ID of your chosen loader
icon: Path, // the icon for the profile
- icon is a path to an image file, which will be copied into the profile directory
*/
export async function create(
name: string,
gameVersion: string,
modloader: InstanceLoader,
loaderVersion: string | null,
icon: string | null,
skipInstall: boolean,
linkedData?: { project_id: string; version_id: string; locked: boolean } | null,
): Promise<string> {
// Trim string name to avoid "Unable to find directory"
name = name.trim()
return await invoke('plugin:profile-create|profile_create', {
name,
gameVersion,
modloader,
loaderVersion,
icon,
skipInstall,
linkedData,
})
}
// duplicate a profile
export async function duplicate(path: string): Promise<string> {
return await invoke('plugin:profile-create|profile_duplicate', { path })
}
// Remove a profile
export async function remove(path: string): Promise<void> {
return await invoke('plugin:profile|profile_remove', { path })
}
// Get a profile by path
// Returns a Profile
export async function get(path: string): Promise<GameInstance | null> {
return await invoke('plugin:profile|profile_get', { path })
}
export async function get_many(paths: string[]): Promise<GameInstance[]> {
return await invoke('plugin:profile|profile_get_many', { paths })
}
// Get a profile's projects
// Returns a map of a path to profile file
export async function get_projects(
path: string,
cacheBehaviour?: CacheBehaviour,
): Promise<Record<string, ContentFile>> {
return await invoke('plugin:profile|profile_get_projects', { path, cacheBehaviour })
}
// Get just the installed project IDs for a profile (lightweight, skips update checks)
export async function get_installed_project_ids(path: string): Promise<string[]> {
return await invoke('plugin:profile|profile_get_installed_project_ids', { path })
}
// Get content items with rich metadata for a profile
// Returns content items filtered to exclude modpack files (if linked),
// sorted alphabetically by project name
export async function get_content_items(
path: string,
cacheBehaviour?: CacheBehaviour,
): Promise<ContentItem[]> {
return await invoke('plugin:profile|profile_get_content_items', { path, cacheBehaviour })
}
// Linked modpack info returned from backend
export interface LinkedModpackInfo {
project: Labrinth.Projects.v2.Project
version: Labrinth.Versions.v2.Version
owner: ContentOwner | null
has_update: boolean
update_version_id: string | null
update_version: Labrinth.Versions.v2.Version | null
}
// Get linked modpack info for a profile
// Returns project, version, and owner information for the linked modpack,
// or null if the profile is not linked to a modpack
export async function get_linked_modpack_info(
path: string,
cacheBehaviour?: CacheBehaviour,
): Promise<LinkedModpackInfo | null> {
return await invoke('plugin:profile|profile_get_linked_modpack_info', { path, cacheBehaviour })
}
// Get content items that are part of the linked modpack
// Returns the modpack's dependencies as ContentItem list
// Returns empty array if the profile is not linked to a modpack
export async function get_linked_modpack_content(
path: string,
cacheBehaviour?: CacheBehaviour,
): Promise<ContentItem[]> {
return await invoke('plugin:profile|profile_get_linked_modpack_content', { path, cacheBehaviour })
}
// Convert a list of dependencies into ContentItems with rich metadata
export async function get_dependencies_as_content_items(
dependencies: Labrinth.Versions.v3.Dependency[],
cacheBehaviour?: CacheBehaviour,
): Promise<ContentItem[]> {
return await invoke('plugin:profile|profile_get_dependencies_as_content_items', {
dependencies,
cacheBehaviour,
})
}
// Get a profile's full fs path
// Returns a path
export async function get_full_path(path: string): Promise<string> {
return await invoke('plugin:profile|profile_get_full_path', { path })
}
// Get's a mod's full fs path
// Returns a path
export async function get_mod_full_path(path: string, projectPath: string): Promise<string> {
return await invoke('plugin:profile|profile_get_mod_full_path', { path, projectPath })
}
export interface JavaVersion {
parsed_version: number
version: string
architecture: string
path: string
}
// Get optimal java version from profile
// Returns a java version
export async function get_optimal_jre_key(path: string): Promise<JavaVersion | null> {
return await invoke('plugin:profile|profile_get_optimal_jre_key', { path })
}
// Get a copy of the profile set
// Returns hashmap of path -> Profile
export async function list(): Promise<GameInstance[]> {
return await invoke('plugin:profile|profile_list')
}
export async function check_installed(path: string, projectId: string): Promise<boolean> {
return await invoke('plugin:profile|profile_check_installed', { path, projectId })
}
export async function check_installed_batch(projectId: string): Promise<Record<string, boolean>> {
return await invoke('plugin:profile|profile_check_installed_batch', { projectId })
}
// Installs/Repairs a profile
export async function install(path: string, force: boolean): Promise<void> {
return await invoke('plugin:profile|profile_install', { path, force })
}
// Updates all of a profile's projects
export async function update_all(path: string): Promise<Record<string, string>> {
return await invoke('plugin:profile|profile_update_all', { path })
}
// Updates a specified project
export async function update_project(path: string, projectPath: string): Promise<string> {
return await invoke('plugin:profile|profile_update_project', { path, projectPath })
}
// Add a project to a profile from a version
// Returns a path to the new project file
export type DownloadReason = 'standalone' | 'dependency' | 'modpack' | 'update'
export async function add_project_from_version(
path: string,
versionId: string,
reason: DownloadReason,
dependentOnVersionId?: string,
): Promise<string> {
return await invoke('plugin:profile|profile_add_project_from_version', {
path,
versionId,
reason,
dependentOnVersionId,
})
}
// Add a project to a profile from a path + project_type
// Returns a path to the new project file
export async function add_project_from_path(
path: string,
projectPath: string,
projectType?: ContentFileProjectType,
): Promise<string> {
return await invoke('plugin:profile|profile_add_project_from_path', {
path,
projectPath,
projectType,
})
}
// Toggle disabling a project
export async function toggle_disable_project(path: string, projectPath: string): Promise<string> {
return await invoke('plugin:profile|profile_toggle_disable_project', { path, projectPath })
}
// Remove a project
export async function remove_project(path: string, projectPath: string): Promise<void> {
return await invoke('plugin:profile|profile_remove_project', { path, projectPath })
}
// Update a managed Modrinth profile to a specific version
export async function update_managed_modrinth_version(
path: string,
versionId: string,
): Promise<void> {
return await invoke('plugin:profile|profile_update_managed_modrinth_version', {
path,
versionId,
})
}
// Repair a managed Modrinth profile
export async function update_repair_modrinth(path: string): Promise<void> {
return await invoke('plugin:profile|profile_repair_managed_modrinth', { path })
}
// Export a profile to .mrpack
// included_overrides is an array of paths to override folders to include (ie: 'mods', 'resource_packs')
// Version id is optional (ie: 1.1.5)
export async function export_profile_mrpack(
path: string,
exportLocation: string,
includedOverrides: string[],
versionId?: string,
description?: string,
name?: string,
): Promise<void> {
return await invoke('plugin:profile|profile_export_mrpack', {
path,
exportLocation,
includedOverrides,
versionId,
description,
name,
})
}
// Given a folder path, populate an array of all the subfolders
// Intended to be used for finding potential override folders
// profile
// -- mods
// -- resourcepacks
// -- file1
// => [mods, resourcepacks]
// allows selection for 'included_overrides' in export_profile_mrpack
export async function get_pack_export_candidates(profilePath: string): Promise<string[]> {
return await invoke('plugin:profile|profile_get_pack_export_candidates', { profilePath })
}
// Run Minecraft using a pathed profile
// Returns PID of child
export async function run(path: string, serverAddress: string | null = null): Promise<unknown> {
return await invoke('plugin:profile|profile_run', { path, serverAddress })
}
export async function kill(path: string): Promise<void> {
return await invoke('plugin:profile|profile_kill', { path })
}
// Edits a profile
export async function edit(path: string, editProfile: Partial<GameInstance>): Promise<void> {
return await invoke('plugin:profile|profile_edit', { path, editProfile })
}
// Edits a profile's icon
export async function edit_icon(path: string, iconPath: string | null): Promise<void> {
return await invoke('plugin:profile|profile_edit_icon', { path, iconPath })
}
export async function finish_install(instance: GameInstance): Promise<void> {
if (instance.install_stage !== 'pack_installed') {
const linkedData = instance.linked_data
if (linkedData) {
await install_to_existing_profile(
linkedData.project_id,
linkedData.version_id,
instance.name,
instance.path,
)
}
} else {
await install(instance.path, false)
}
}
+1 -1
View File
@@ -1,6 +1,6 @@
/**
* All theseus API calls return serialized values (both return values and errors);
* So, for example, addDefaultInstance creates a blank Profile object, where the Rust struct is serialized,
* So, for example, addDefaultInstance creates a blank instance object, where the Rust struct is serialized,
* and deserialized into a usable JS object.
*/
import { invoke } from '@tauri-apps/api/core'
+3 -2
View File
@@ -1,6 +1,6 @@
/**
* All theseus API calls return serialized values (both return values and errors);
* So, for example, addDefaultInstance creates a blank Profile object, where the Rust struct is serialized,
* So, for example, addDefaultInstance creates a blank instance object, where the Rust struct is serialized,
* and deserialized into a usable JS object.
*/
import { invoke } from '@tauri-apps/api/core'
@@ -8,7 +8,8 @@ import { invoke } from '@tauri-apps/api/core'
export interface LoadingBarType {
type?: string
version?: string
profile_path?: string
instance_id?: string
instance_name?: string
pack_name?: string
icon?: string | null
}
+1 -1
View File
@@ -1,6 +1,6 @@
/**
* All theseus API calls return serialized values (both return values and errors);
* So, for example, addDefaultInstance creates a blank Profile object, where the Rust struct is serialized,
* So, for example, addDefaultInstance creates a blank instance object, where the Rust struct is serialized,
* and deserialized into a usable JS object.
*/
import { invoke } from '@tauri-apps/api/core'
+50 -5
View File
@@ -1,20 +1,23 @@
import type { ModrinthId } from '@modrinth/utils'
export type GameInstance = {
id: string
path: string
install_stage: InstallStage
launcher_feature_version: string
name: string
icon_path?: string
game_version: string
protocol_version?: number
loader: InstanceLoader
loader_version?: string
groups: string[]
linked_data?: LinkedData
preferred_update_channel: ReleaseChannel
link?: InstanceLink | null
update_channel: ReleaseChannel
created: Date
modified: Date
@@ -40,12 +43,54 @@ type InstallStage =
| 'pack_installing'
| 'not_installed'
type LinkedData = {
type InstanceLinkIdentity = {
project_id?: ModrinthId | null
version_id?: ModrinthId | null
server_project_id?: ModrinthId | null
content_project_id?: ModrinthId | null
content_version_id?: ModrinthId | null
}
export type InstanceLink = InstanceLinkIdentity &
(
| {
type: 'modrinth_modpack'
project_id: ModrinthId
version_id: ModrinthId
locked: boolean
}
| {
type: 'server_project'
project_id: ModrinthId
}
| {
type: 'server_project_modpack'
server_project_id: ModrinthId
content_project_id?: ModrinthId | null
content_version_id: ModrinthId
project_id?: ModrinthId
version_id?: ModrinthId
}
| {
type: 'imported_modpack'
project_id?: ModrinthId | null
version_id?: ModrinthId | null
name?: string | null
version_number?: string | null
filename?: string | null
}
| {
type: 'modrinth_hosting'
server_id: string
instance_ids: string[]
active_instance_id?: string | null
}
| {
type: 'shared_instance'
shared_instance_id: string
}
)
export type Instance = GameInstance
type ReleaseChannel = 'release' | 'beta' | 'alpha'
+27 -6
View File
@@ -1,6 +1,7 @@
import { invoke } from '@tauri-apps/api/core'
import { save } from '@tauri-apps/plugin-dialog'
import { get_full_path, get_mod_full_path } from '@/helpers/profile'
import { get_full_path, get_mod_full_path } from '@/helpers/instance'
export async function isDev() {
return await invoke('is_dev')
@@ -47,14 +48,34 @@ export async function showLauncherLogsFolder() {
return await invoke('plugin:utils|show_launcher_logs_folder', {})
}
// Opens a profile's folder in the OS file explorer
export async function showProfileInFolder(path) {
const fullPath = await get_full_path(path)
export async function createInstanceShortcut(instanceName, instanceId, options = {}) {
const outputPath = await save({
defaultPath: `Modrinth - ${instanceName}`,
})
if (!outputPath) return null
return await invoke('plugin:shortcuts|create_instance_shortcut', {
instanceName,
instanceId,
outputPath,
server: options.server,
singleplayerWorld: options.singleplayerWorld,
})
}
export async function showAppDbBackupsFolder() {
return await invoke('plugin:utils|show_app_db_backups_folder', {})
}
// Opens an instance's folder in the OS file explorer
export async function showInstanceInFolder(instanceId) {
const fullPath = await get_full_path(instanceId)
return await openPath(fullPath)
}
export async function highlightModInProfile(profilePath, projectPath) {
const fullPath = await get_mod_full_path(profilePath, projectPath)
export async function highlightModInInstance(instanceId, projectPath) {
const fullPath = await get_mod_full_path(instanceId, projectPath)
return await highlightInFolder(fullPath)
}
+64 -34
View File
@@ -3,7 +3,7 @@ import { autoToHTML } from '@sfirew/minecraft-motd-parser'
import { invoke } from '@tauri-apps/api/core'
import dayjs from 'dayjs'
import { get_full_path } from '@/helpers/profile'
import { get_full_path } from '@/helpers/instance'
import { openPath } from '@/helpers/utils'
type BaseWorld = {
@@ -36,8 +36,8 @@ export type ServerWorld = BaseWorld & {
export type World = SingleplayerWorld | ServerWorld
export type WorldWithProfile = {
profile: string
export type WorldWithInstance = {
instance_id: string
} & World
export type SingleplayerGameMode = 'survival' | 'creative' | 'adventure' | 'spectator'
@@ -88,12 +88,12 @@ export type ProtocolVersion = {
export async function get_recent_worlds(
limit: number,
displayStatuses?: DisplayStatus[],
): Promise<WorldWithProfile[]> {
): Promise<WorldWithInstance[]> {
return await invoke('plugin:worlds|get_recent_worlds', { limit, displayStatuses })
}
export async function get_profile_worlds(path: string): Promise<World[]> {
return await invoke('plugin:worlds|get_profile_worlds', { path })
export async function get_instance_worlds(instanceId: string): Promise<World[]> {
return await invoke('plugin:worlds|get_instance_worlds', { instanceId })
}
export async function get_singleplayer_world(
@@ -137,16 +137,16 @@ export async function delete_world(instance: string, world: string): Promise<voi
return await invoke('plugin:worlds|delete_world', { instance, world })
}
export async function add_server_to_profile(
path: string,
export async function add_server_to_instance(
instanceId: string,
name: string,
address: string,
packStatus: ServerPackStatus,
projectId?: string,
contentKind?: string,
): Promise<number> {
return await invoke('plugin:worlds|add_server_to_profile', {
path,
return await invoke('plugin:worlds|add_server_to_instance', {
instanceId,
name,
address,
packStatus,
@@ -155,15 +155,15 @@ export async function add_server_to_profile(
})
}
export async function edit_server_in_profile(
path: string,
export async function edit_server_in_instance(
instanceId: string,
index: number,
name: string,
address: string,
packStatus: ServerPackStatus,
): Promise<void> {
return await invoke('plugin:worlds|edit_server_in_profile', {
path,
return await invoke('plugin:worlds|edit_server_in_instance', {
instanceId,
index,
name,
address,
@@ -171,12 +171,17 @@ export async function edit_server_in_profile(
})
}
export async function remove_server_from_profile(path: string, index: number): Promise<void> {
return await invoke('plugin:worlds|remove_server_from_profile', { path, index })
export async function remove_server_from_instance(
instanceId: string,
index: number,
): Promise<void> {
return await invoke('plugin:worlds|remove_server_from_instance', { instanceId, index })
}
export async function get_profile_protocol_version(path: string): Promise<ProtocolVersion | null> {
return await invoke('plugin:worlds|get_profile_protocol_version', { path })
export async function get_instance_protocol_version(
instanceId: string,
): Promise<ProtocolVersion | null> {
return await invoke('plugin:worlds|get_instance_protocol_version', { instanceId })
}
export async function get_server_status(
@@ -186,16 +191,19 @@ export async function get_server_status(
return await invoke('plugin:worlds|get_server_status', { address, protocolVersion })
}
export async function start_join_singleplayer_world(path: string, world: string): Promise<unknown> {
return await invoke('plugin:worlds|start_join_singleplayer_world', { path, world })
export async function start_join_singleplayer_world(
instanceId: string,
world: string,
): Promise<unknown> {
return await invoke('plugin:worlds|start_join_singleplayer_world', { instanceId, world })
}
export async function start_join_server(path: string, address: string): Promise<unknown> {
return await invoke('plugin:worlds|start_join_server', { path, address })
export async function start_join_server(instanceId: string, address: string): Promise<unknown> {
return await invoke('plugin:worlds|start_join_server', { instanceId, address })
}
export async function showWorldInFolder(instancePath: string, worldPath: string) {
const fullPath = await get_full_path(instancePath)
export async function showWorldInFolder(instanceId: string, worldPath: string) {
const fullPath = await get_full_path(instanceId)
return await openPath(fullPath + '/saves/' + worldPath)
}
@@ -348,6 +356,28 @@ export function resolveManagedServerWorld(
)
}
export function getServerAddress(javaServer?: { address?: string | null } | null) {
if (!javaServer) return null
return javaServer.address ?? null
}
export async function ensureManagedServerWorldExists(
instanceId: string,
serverName: string,
serverAddress: string | null,
) {
if (!instanceId || !serverAddress) return
try {
const worlds = await get_instance_worlds(instanceId)
const managedWorld = resolveManagedServerWorld(worlds, serverName, serverAddress)
if (!managedWorld) {
await add_server_to_instance(instanceId, serverName, serverAddress, 'prompt')
}
} catch (err) {
console.error('Failed to ensure managed server world exists:', err)
}
}
export async function getServerLatency(
address: string,
protocolVersion: ProtocolVersion | null = null,
@@ -420,9 +450,9 @@ export function refreshServers(
)
}
export async function refreshWorld(worlds: World[], instancePath: string, worldPath: string) {
export async function refreshWorld(worlds: World[], instanceId: string, worldPath: string) {
const index = worlds.findIndex((w) => w.type === 'singleplayer' && w.path === worldPath)
const newWorld = await get_singleplayer_world(instancePath, worldPath)
const newWorld = await get_singleplayer_world(instanceId, worldPath)
if (index !== -1) {
worlds[index] = newWorld
} else {
@@ -432,13 +462,13 @@ export async function refreshWorld(worlds: World[], instancePath: string, worldP
sortWorlds(worlds)
}
export async function handleDefaultProfileUpdateEvent(
export async function handleDefaultInstanceUpdateEvent(
worlds: World[],
instancePath: string,
e: ProfileEvent,
instanceId: string,
e: InstanceEvent,
) {
if (e.event === 'world_updated') {
await refreshWorld(worlds, instancePath, e.world)
await refreshWorld(worlds, instanceId, e.world)
}
if (e.event === 'server_joined') {
@@ -456,9 +486,9 @@ export async function handleDefaultProfileUpdateEvent(
}
}
export async function refreshWorlds(instancePath: string): Promise<World[]> {
const worlds = await get_profile_worlds(instancePath).catch((err) => {
console.error(`Error refreshing worlds for instance: ${instancePath}`, err)
export async function refreshWorlds(instanceId: string): Promise<World[]> {
const worlds = await get_instance_worlds(instanceId).catch((err) => {
console.error(`Error refreshing worlds for instance: ${instanceId}`, err)
})
if (worlds) {
sortWorlds(worlds)
@@ -489,7 +519,7 @@ export function hasWorldQuickPlaySupport(gameVersions: GameVersion[], currentVer
return versionIndex !== -1 && targetIndex !== -1 && versionIndex <= targetIndex
}
export type ProfileEvent = { profile_path_id: string } & (
export type InstanceEvent = { instance_id: string } & (
| {
event: 'servers_updated'
}
@@ -107,12 +107,6 @@
"app.browse.server.installing": {
"message": "جاري التثبيت"
},
"app.creation-modal.installing-modpack.description": {
"message": "{fileName}"
},
"app.creation-modal.installing-modpack.title": {
"message": "تنزيل الحزم"
},
"app.export-modal.description-placeholder": {
"message": "أدخل وصف التعديل..."
},
@@ -185,12 +179,6 @@
"app.instance.worlds.browse-servers": {
"message": "تصفح الخوادم"
},
"app.instance.worlds.delete-world-description": {
"message": "سيتم حذف '{name}' **نهائيا**, و لن هناك أي طريقة لاسترداده."
},
"app.instance.worlds.delete-world-title": {
"message": "هل أنت متيقِّن من رغبتك بحذف هذا العالم نهائيا؟"
},
"app.instance.worlds.filter-modded": {
"message": "معدّل"
},
@@ -209,21 +197,9 @@
"app.instance.worlds.no-worlds-heading": {
"message": "لم تتم إضافة أي من الخوادم أو العوالم"
},
"app.instance.worlds.remove-server-description": {
"message": "ستتم إزالة '{name}' من قائمتك, إضافة لما داخل اللعبة, و لن يكون هناك أي طريقة لاسترداده."
},
"app.instance.worlds.remove-server-description-with-address": {
"message": "ستتم إزالة '{name}' ({address}) من قائمتك, إضافة لما داخل اللعبة, و لن يكون هناك أي طريقة لاسترداده."
},
"app.instance.worlds.remove-server-title": {
"message": "هل أنت متيقِّن من رغبتك في إزالة {name}؟"
},
"app.instance.worlds.search-worlds-placeholder": {
"message": "ابحث بين ال{count} عوالم..."
},
"app.instance.worlds.this-server": {
"message": "هذا الخادم"
},
"app.modal.install-to-play.content-required": {
"message": "المحتوى مطلوب"
},
@@ -161,12 +161,6 @@
"app.content-install.no-compatible-versions": {
"message": "Žádná dostupná verze se neshoduje s verzí {compatibilityLabel}. Vyber verzi, abys ji i přesto nainstaloval/a. Závislosti nebudou automaticky nainstalovány."
},
"app.creation-modal.installing-modpack.description": {
"message": "{fileName}"
},
"app.creation-modal.installing-modpack.title": {
"message": "Probíhá instalace modpacku..."
},
"app.export-modal.description-placeholder": {
"message": "Zadej popis modpacku..."
},
@@ -242,12 +236,6 @@
"app.instance.worlds.browse-servers": {
"message": "Procházet servery"
},
"app.instance.worlds.delete-world-description": {
"message": "'{name}' bude **navždy smazán** a nebude možné jej obnovit."
},
"app.instance.worlds.delete-world-title": {
"message": "Jsi si jistý, že chceš trvale smazat tento svět?"
},
"app.instance.worlds.filter-modded": {
"message": "Módovaný"
},
@@ -266,21 +254,9 @@
"app.instance.worlds.no-worlds-heading": {
"message": "Žádné servery nebo světy nebyly přidány"
},
"app.instance.worlds.remove-server-description": {
"message": "'{name}' bude odstraněn z tvého seznamu i ze hry a nebude možné jej obnovit."
},
"app.instance.worlds.remove-server-description-with-address": {
"message": "'{name}' ({address}) bude odstraněn z tvého seznamu i ze hry a nebude možné jej obnovit."
},
"app.instance.worlds.remove-server-title": {
"message": "Opravdu chceš odstranit {name}?"
},
"app.instance.worlds.search-worlds-placeholder": {
"message": "Hledat v {count} světech..."
},
"app.instance.worlds.this-server": {
"message": "tento server"
},
"app.modal.install-to-play.content-required": {
"message": "Požadovaný obsah"
},
@@ -155,12 +155,6 @@
"app.content-install.no-compatible-versions": {
"message": "Ingen tilgængelige versioner passer til {compatibilityLabel}. Vælg en version for at installere. Afhængigheder bliver ikke installeret automatisk."
},
"app.creation-modal.installing-modpack.description": {
"message": "{fileName}"
},
"app.creation-modal.installing-modpack.title": {
"message": "Installere modpack..."
},
"app.export-modal.description-placeholder": {
"message": "Indtast modpack beskrivelse..."
},
@@ -236,9 +230,6 @@
"app.instance.worlds.browse-servers": {
"message": "Søg servere"
},
"app.instance.worlds.delete-world-title": {
"message": "Er du sikker på din vil slette denne verden permanent?"
},
"app.instance.worlds.filter-modded": {
"message": "Moddet"
},
@@ -257,15 +248,9 @@
"app.instance.worlds.no-worlds-heading": {
"message": "Ingen servere eller verdener tilføjet"
},
"app.instance.worlds.remove-server-title": {
"message": "Er du sikker på din vil fjerne {name}?"
},
"app.instance.worlds.search-worlds-placeholder": {
"message": "Søg {count} verdener..."
},
"app.instance.worlds.this-server": {
"message": "denne server"
},
"app.modal.install-to-play.content-required": {
"message": "Indhold krævet"
},
@@ -161,12 +161,6 @@
"app.content-install.no-compatible-versions": {
"message": "Keine verfügbaren Versionen stimmen mit {compatibilityLabel} überein. Wähle eine Version aus, um sie trotzdem zu installieren. Abhängigkeiten werden nicht automatisch installiert."
},
"app.creation-modal.installing-modpack.description": {
"message": "{fileName}"
},
"app.creation-modal.installing-modpack.title": {
"message": "Modpack wird installiert..."
},
"app.export-modal.description-placeholder": {
"message": "Modpaketbeschreibung eingeben..."
},
@@ -242,9 +236,6 @@
"app.instance.worlds.browse-servers": {
"message": "Server durchsuchen"
},
"app.instance.worlds.delete-world-title": {
"message": "Möchtest du diese Welt wirklich endgültig löschen?"
},
"app.instance.worlds.filter-modded": {
"message": "Modifiziert"
},
@@ -263,15 +254,9 @@
"app.instance.worlds.no-worlds-heading": {
"message": "Keine Server oder Welten hinzugefügt"
},
"app.instance.worlds.remove-server-title": {
"message": "Möchtest du {name} wirklich entfernen?"
},
"app.instance.worlds.search-worlds-placeholder": {
"message": "Durchsuche {count} Welten..."
},
"app.instance.worlds.this-server": {
"message": "dieser Server"
},
"app.modal.install-to-play.content-required": {
"message": "Inhalte benötigt"
},
@@ -161,12 +161,6 @@
"app.content-install.no-compatible-versions": {
"message": "Keine verfügbaren Versionen stimmen mit {compatibilityLabel} überein. Wähle eine Version aus, um sie trotzdem zu installieren. Abhängigkeiten werden nicht automatisch installiert."
},
"app.creation-modal.installing-modpack.description": {
"message": "{fileName}"
},
"app.creation-modal.installing-modpack.title": {
"message": "Modpack wird installiert..."
},
"app.export-modal.description-placeholder": {
"message": "Beschreibung des Modpacks eingeben..."
},
@@ -242,9 +236,6 @@
"app.instance.worlds.browse-servers": {
"message": "Server durchsuchen"
},
"app.instance.worlds.delete-world-title": {
"message": "Möchtest du diese Welt wirklich endgültig löschen?"
},
"app.instance.worlds.filter-modded": {
"message": "Modifiziert"
},
@@ -263,15 +254,9 @@
"app.instance.worlds.no-worlds-heading": {
"message": "Keine Server oder Welten hinzugefügt"
},
"app.instance.worlds.remove-server-title": {
"message": "Möchtest du {name} wirklich entfernen?"
},
"app.instance.worlds.search-worlds-placeholder": {
"message": "Durchsuche {count} Welten..."
},
"app.instance.worlds.this-server": {
"message": "dieser Server"
},
"app.modal.install-to-play.content-required": {
"message": "Inhalte benötigt"
},
+118 -19
View File
@@ -11,6 +11,33 @@
"app.action-bar.hide-more-running-instances": {
"message": "Hide more running instances"
},
"app.action-bar.install.dismiss": {
"message": "Dismiss"
},
"app.action-bar.install.failed": {
"message": "Install failed"
},
"app.action-bar.install.failed-app-closed": {
"message": "Installation failed due to app closing."
},
"app.action-bar.install.failed-network": {
"message": "Installation failed due to a network error."
},
"app.action-bar.install.failed-unknown": {
"message": "Installation failed due to an unknown error."
},
"app.action-bar.install.open-instance": {
"message": "Open instance"
},
"app.action-bar.install.retry": {
"message": "Retry"
},
"app.action-bar.install.unknown-instance": {
"message": "Unknown instance"
},
"app.action-bar.installs": {
"message": "Installs"
},
"app.action-bar.make-primary-instance": {
"message": "Make primary instance"
},
@@ -101,6 +128,12 @@
"app.appearance-settings.show-play-time.title": {
"message": "Show play time"
},
"app.appearance-settings.skip-non-essential-warnings.description": {
"message": "Automatically skips low-risk confirmations like duplicate modpack installs, normal content deletion, bulk updates, unlinking modpacks, and repair prompts. Dangerous warnings will still be shown."
},
"app.appearance-settings.skip-non-essential-warnings.title": {
"message": "Skip non-essential warnings"
},
"app.appearance-settings.toggle-sidebar.description": {
"message": "Enables the ability to toggle the sidebar."
},
@@ -161,12 +194,6 @@
"app.content-install.no-compatible-versions": {
"message": "No available versions match {compatibilityLabel}. Select a version to install anyway. Dependencies will not be installed automatically."
},
"app.creation-modal.installing-modpack.description": {
"message": "{fileName}"
},
"app.creation-modal.installing-modpack.title": {
"message": "Installing modpack..."
},
"app.export-modal.description-placeholder": {
"message": "Enter modpack description..."
},
@@ -194,6 +221,60 @@
"app.export-modal.version-number-placeholder": {
"message": "1.0.0"
},
"app.install.phase.downloading_content": {
"message": "Downloading content"
},
"app.install.phase.downloading_minecraft": {
"message": "Downloading Minecraft"
},
"app.install.phase.downloading_pack_file": {
"message": "Downloading pack file"
},
"app.install.phase.extracting_overrides": {
"message": "Extracting overrides"
},
"app.install.phase.finalizing": {
"message": "Finalizing"
},
"app.install.phase.preparing_instance": {
"message": "Preparing instance"
},
"app.install.phase.preparing_java": {
"message": "Preparing Java"
},
"app.install.phase.preparing_java.downloading": {
"message": "Downloading Java {version}"
},
"app.install.phase.preparing_java.extracting": {
"message": "Extracting Java {version}"
},
"app.install.phase.preparing_java.fetching-metadata": {
"message": "Fetching Java {version}"
},
"app.install.phase.preparing_java.resolving": {
"message": "Preparing Java {version}"
},
"app.install.phase.preparing_java.validating": {
"message": "Validating Java {version}"
},
"app.install.phase.reading_pack_manifest": {
"message": "Reading pack manifest"
},
"app.install.phase.resolving_loader": {
"message": "Resolving loader"
},
"app.install.phase.resolving_minecraft": {
"message": "Resolving Minecraft"
},
"app.install.phase.resolving_pack": {
"message": "Resolving content"
},
"app.install.phase.rolling_back": {
"message": "Rolling back"
},
"app.install.phase.running_loader_processors": {
"message": "Running loader processors"
},
"app.instance.confirm-delete.admonition-body": {
"message": "All data for your instance will be permanently deleted, including your worlds, configs, and all installed content."
},
@@ -218,6 +299,15 @@
"app.instance.modpack-already-installed.instance": {
"message": "Instance"
},
"app.instance.mods.bulk-update.downloading-projects": {
"message": "Downloading {current, number}/{total, number} projects..."
},
"app.instance.mods.bulk-update.finishing": {
"message": "Finishing update..."
},
"app.instance.mods.bulk-update.resolving-versions": {
"message": "Resolving versions..."
},
"app.instance.mods.content-type-project": {
"message": "project"
},
@@ -242,11 +332,17 @@
"app.instance.worlds.browse-servers": {
"message": "Browse servers"
},
"app.instance.worlds.delete-world-description": {
"message": "'{name}' will be **permanently deleted**, and there will be no way to recover it."
"app.instance.worlds.delete-world-modal.delete-button": {
"message": "Delete world"
},
"app.instance.worlds.delete-world-title": {
"message": "Are you sure you want to permanently delete this world?"
"app.instance.worlds.delete-world-modal.title": {
"message": "Delete world"
},
"app.instance.worlds.delete-world-modal.warning-body": {
"message": "This world will be permanently deleted from this instance. This action cannot be undone."
},
"app.instance.worlds.delete-world-modal.warning-header": {
"message": "Deleting {name}"
},
"app.instance.worlds.filter-modded": {
"message": "Modded"
@@ -266,21 +362,21 @@
"app.instance.worlds.no-worlds-heading": {
"message": "No servers or worlds added"
},
"app.instance.worlds.remove-server-description": {
"message": "'{name}' will be removed from your list, including in-game, and there will be no way to recover it."
"app.instance.worlds.remove-server-modal.remove-button": {
"message": "Remove server"
},
"app.instance.worlds.remove-server-description-with-address": {
"message": "'{name}' ({address}) will be removed from your list, including in-game, and there will be no way to recover it."
"app.instance.worlds.remove-server-modal.title": {
"message": "Remove server"
},
"app.instance.worlds.remove-server-title": {
"message": "Are you sure you want to remove {name}?"
"app.instance.worlds.remove-server-modal.warning-body": {
"message": "This server will be removed from your server list and from the in-game server list. You can add it again later if you know the address."
},
"app.instance.worlds.remove-server-modal.warning-header": {
"message": "Removing {name}"
},
"app.instance.worlds.search-worlds-placeholder": {
"message": "Search {count} worlds..."
},
"app.instance.worlds.this-server": {
"message": "this server"
},
"app.modal.install-to-play.content-required": {
"message": "Content required"
},
@@ -863,6 +959,9 @@
"instance.worlds.copy_address": {
"message": "Copy address"
},
"instance.worlds.create_shortcut": {
"message": "Create shortcut"
},
"instance.worlds.dont_show_on_home": {
"message": "Don't show on Home"
},
@@ -161,12 +161,6 @@
"app.content-install.no-compatible-versions": {
"message": "No hay versiones disponibles que coincidan con {compatibilityLabel}. Selecciona una versión para instalarla de todas formas. Las dependencias no se instalarán automáticamente."
},
"app.creation-modal.installing-modpack.description": {
"message": "{fileName}"
},
"app.creation-modal.installing-modpack.title": {
"message": "Instalando modpack..."
},
"app.export-modal.description-placeholder": {
"message": "Introduce la descripción del modpack..."
},
@@ -242,9 +236,6 @@
"app.instance.worlds.browse-servers": {
"message": "Explorar servidores"
},
"app.instance.worlds.delete-world-title": {
"message": "¿Estás seguro de que quieres eliminar este mundo de forma permanente?"
},
"app.instance.worlds.filter-modded": {
"message": "Con mods"
},
@@ -263,15 +254,9 @@
"app.instance.worlds.no-worlds-heading": {
"message": "No hay servidores ni mundos añadidos"
},
"app.instance.worlds.remove-server-title": {
"message": "¿Estás seguro de que quieres eliminar {name}?"
},
"app.instance.worlds.search-worlds-placeholder": {
"message": "Buscar en {count} mundos..."
},
"app.instance.worlds.this-server": {
"message": "este servidor"
},
"app.modal.install-to-play.content-required": {
"message": "Contenido requerido"
},
@@ -161,12 +161,6 @@
"app.content-install.no-compatible-versions": {
"message": "No hay versiones disponibles que coincidan con {compatibilityLabel}. Selecciona una versión para instalarla de todas formas. Las dependencias no se instalarán automáticamente."
},
"app.creation-modal.installing-modpack.description": {
"message": "{fileName}"
},
"app.creation-modal.installing-modpack.title": {
"message": "Instalando modpack..."
},
"app.export-modal.description-placeholder": {
"message": "Escribe la descripción del modpack..."
},
@@ -242,12 +236,6 @@
"app.instance.worlds.browse-servers": {
"message": "Explorar servidores"
},
"app.instance.worlds.delete-world-description": {
"message": "'{name}' será **permanentemente eliminado**, y habrá forma de recuperarlo."
},
"app.instance.worlds.delete-world-title": {
"message": "¿Estás seguro de qué quieres eliminar permanentemente este mundo?"
},
"app.instance.worlds.filter-modded": {
"message": "Modeado"
},
@@ -266,21 +254,9 @@
"app.instance.worlds.no-worlds-heading": {
"message": "No hay servidores o mundos añadidos"
},
"app.instance.worlds.remove-server-description": {
"message": "'{name}' será eliminado de tu lista, incluyendo dentro del juego, y no habrá forma de recuperarlo."
},
"app.instance.worlds.remove-server-description-with-address": {
"message": "'{name}' ({address}) será eliminado de tu lista, incluyendo dentro del juego, y no habrá forma de recuperarlo."
},
"app.instance.worlds.remove-server-title": {
"message": "¿Estás seguro de qué quieres eliminar {name}?"
},
"app.instance.worlds.search-worlds-placeholder": {
"message": "Buscar {count} mundos..."
},
"app.instance.worlds.this-server": {
"message": "este servidor"
},
"app.modal.install-to-play.content-required": {
"message": "Contenido obligatorio"
},
@@ -146,12 +146,6 @@
"app.content-install.no-compatible-versions": {
"message": "Yhtään versiota ei ole saatavilla yhteensopivuudella {compatibilityLabel}. Valitse asennettava versio siitä huolimatta. Riippuvuuksia ei asenneta automaattisesti."
},
"app.creation-modal.installing-modpack.description": {
"message": "{fileName}"
},
"app.creation-modal.installing-modpack.title": {
"message": "Asennetaan modipakettia..."
},
"app.export-modal.description-placeholder": {
"message": "Lisää modipaketin kuvaus..."
},
@@ -227,12 +221,6 @@
"app.instance.worlds.browse-servers": {
"message": "Selaa palvelimia"
},
"app.instance.worlds.delete-world-description": {
"message": "'{name}' tullaan **poistamaan pysyvästi**, eikä tule olemaan mitään tapaa palauttaa sitä."
},
"app.instance.worlds.delete-world-title": {
"message": "Oletko varma että haluat pysyvästi poistaa tämän maailman?"
},
"app.instance.worlds.filter-modded": {
"message": "Modattu"
},
@@ -251,21 +239,9 @@
"app.instance.worlds.no-worlds-heading": {
"message": "Ei palvelimia tai maailmoja lisättynä"
},
"app.instance.worlds.remove-server-description": {
"message": "'{name}' tullaan poistamaan sinun listaltasi, mukaan lukien pelin sisällä, eikä tule olemaan mitään tapaa palauttaa sitä."
},
"app.instance.worlds.remove-server-description-with-address": {
"message": "'{name}' ({address}) tullaan poistamaan sinun listaltasi, mukaan lukien pelin sisällä, eikä tule olemaan mitään tapaa palauttaa sitä."
},
"app.instance.worlds.remove-server-title": {
"message": "Oletko varma että haluat poistaa {name}?"
},
"app.instance.worlds.search-worlds-placeholder": {
"message": "Hae {count} maailmasta..."
},
"app.instance.worlds.this-server": {
"message": "tämän palvelimen"
},
"app.modal.install-to-play.content-required": {
"message": "Sisältö vaaditaan"
},
@@ -155,12 +155,6 @@
"app.browse.server.installing": {
"message": "Ini-install"
},
"app.creation-modal.installing-modpack.description": {
"message": "{fileName}"
},
"app.creation-modal.installing-modpack.title": {
"message": "Ini-install ang modpack..."
},
"app.export-modal.description-placeholder": {
"message": "Ilagay ang paglalarawan ng modpack..."
},
@@ -236,12 +230,6 @@
"app.instance.worlds.browse-servers": {
"message": "Mag-browse ng servers"
},
"app.instance.worlds.delete-world-description": {
"message": "'{name}' ay **permanenteng mabubura**, at walang paraan upang maibalik muli."
},
"app.instance.worlds.delete-world-title": {
"message": "Sigurado ka bang gusto mong permanenteng burahin ang world na ito?"
},
"app.instance.worlds.filter-modded": {
"message": "Modded"
},
@@ -260,21 +248,9 @@
"app.instance.worlds.no-worlds-heading": {
"message": "Walang servers o worlds ang nalalagay"
},
"app.instance.worlds.remove-server-description": {
"message": "'{name}' ay matatangal sa iyong listahan, pati sa loob ng laro, at walang paraan upang maibalik ito."
},
"app.instance.worlds.remove-server-description-with-address": {
"message": "'{name}' ({address}) ay matatangal sa iyong listahan, pati sa loob ng laro, at walang paraan upang maibalik ito."
},
"app.instance.worlds.remove-server-title": {
"message": "Sigurado ka bang gusto mong tanggalin ang {name}?"
},
"app.instance.worlds.search-worlds-placeholder": {
"message": "Hanapin sa {count} mundo..."
},
"app.instance.worlds.this-server": {
"message": "server na ito"
},
"app.modal.install-to-play.content-required": {
"message": "Nangangailangan ng kontento"
},
@@ -161,12 +161,6 @@
"app.content-install.no-compatible-versions": {
"message": "Aucune version disponible ne correspond à {compatibilityLabel}. Sélectionnez une version pour l'installer malgré tout. Les dépendances ne seront pas installées automatiquement."
},
"app.creation-modal.installing-modpack.description": {
"message": "{fileName}"
},
"app.creation-modal.installing-modpack.title": {
"message": "Installation du modpack..."
},
"app.export-modal.description-placeholder": {
"message": "Saisir la description du modpack..."
},
@@ -242,9 +236,6 @@
"app.instance.worlds.browse-servers": {
"message": "Parcourir des serveurs"
},
"app.instance.worlds.delete-world-title": {
"message": "Êtes-vous sûr·e de vouloir supprimer ce monde pour toujours ?"
},
"app.instance.worlds.filter-modded": {
"message": "Moddé"
},
@@ -263,15 +254,9 @@
"app.instance.worlds.no-worlds-heading": {
"message": "Aucun serveur ou monde ajoutés"
},
"app.instance.worlds.remove-server-title": {
"message": "Êtes-vous sûr·e de vouloir retirer {name} ?"
},
"app.instance.worlds.search-worlds-placeholder": {
"message": "Rechercher {count} mondes..."
},
"app.instance.worlds.this-server": {
"message": "ce serveur"
},
"app.modal.install-to-play.content-required": {
"message": "Contenu requis"
},
@@ -119,12 +119,6 @@
"app.instance.worlds.browse-servers": {
"message": "עיון בשרתים"
},
"app.instance.worlds.delete-world-description": {
"message": "'{name}' יימחק לצמיתות, ולא תהיה דרך לשחזר אותו."
},
"app.instance.worlds.delete-world-title": {
"message": "האם אתה בטוח שברצונך למחוק לצמיתות את העולם הזה?"
},
"app.instance.worlds.filter-modded": {
"message": "עם מודים"
},
@@ -143,21 +137,9 @@
"app.instance.worlds.no-worlds-heading": {
"message": "אין שרתים אן עולמות שנוספו"
},
"app.instance.worlds.remove-server-description": {
"message": "'{name}' יוסר מהרשימה שלך, כולל מתוך המשחק, ולא תהיה דרך לשחזר אותו."
},
"app.instance.worlds.remove-server-description-with-address": {
"message": "'{name}' ({address}) יוסר מהרשימה שלך, כולל מתוך המשחק, ולא תהיה דרך לשחזר אותו."
},
"app.instance.worlds.remove-server-title": {
"message": "אתה בטוח שאתה רוצה להסיר {name}?"
},
"app.instance.worlds.search-worlds-placeholder": {
"message": "חיפוש ב-{count} עולמות..."
},
"app.instance.worlds.this-server": {
"message": "השרת הזה"
},
"app.modal.install-to-play.content-required": {
"message": "תוכן נדרש"
},
@@ -161,12 +161,6 @@
"app.content-install.no-compatible-versions": {
"message": "Nincs a(z) {compatibilityLabel} verziónak megfelelő elérhető verzió. Válassz ki egy verziót, ha mégis telepíteni szeretnéd. A függőségek nem települnek automatikusan."
},
"app.creation-modal.installing-modpack.description": {
"message": "{fileName}"
},
"app.creation-modal.installing-modpack.title": {
"message": "Modcsomag telepítése..."
},
"app.export-modal.description-placeholder": {
"message": "Írd be a modcsomag leírását..."
},
@@ -242,12 +236,6 @@
"app.instance.worlds.browse-servers": {
"message": "Szerverek böngészése"
},
"app.instance.worlds.delete-world-description": {
"message": "'{name}' **véglegesen törlődik**, és azt semmilyen módon nem lehet majd helyreállítani."
},
"app.instance.worlds.delete-world-title": {
"message": "Biztosan véglegesen törölni szeretnéd ezt a világot?"
},
"app.instance.worlds.filter-modded": {
"message": "Modolt"
},
@@ -266,21 +254,9 @@
"app.instance.worlds.no-worlds-heading": {
"message": "Nincs szerver vagy világ"
},
"app.instance.worlds.remove-server-description": {
"message": "'{name}' eltávolításra kerül a listádról, beleértve a játékon belülieket is. Ezt a lépést nem tudod visszavonni."
},
"app.instance.worlds.remove-server-description-with-address": {
"message": "'{name}' ({address}) eltávolításra kerül a listádról, beleértve a játékon belülieket is. Ezt a lépést nem tudod visszavonni."
},
"app.instance.worlds.remove-server-title": {
"message": "Biztosan el akarod távolítani ezt: {name}?"
},
"app.instance.worlds.search-worlds-placeholder": {
"message": "Keresés {count} világ között..."
},
"app.instance.worlds.this-server": {
"message": "ez a szerver"
},
"app.modal.install-to-play.content-required": {
"message": "Szükséges tartalom"
},
@@ -161,12 +161,6 @@
"app.content-install.no-compatible-versions": {
"message": "Tidak ada versi tersedia yang cocok untuk {compatibilityLabel}. Anda tetap dapat memilih versi yang akan dipasang. Dependensi tidak akan dipasang secara otomatis."
},
"app.creation-modal.installing-modpack.description": {
"message": "{fileName}"
},
"app.creation-modal.installing-modpack.title": {
"message": "Memasang paket mod..."
},
"app.export-modal.description-placeholder": {
"message": "Masukkan deskripsi paket mod..."
},
@@ -242,12 +236,6 @@
"app.instance.worlds.browse-servers": {
"message": "Telusuri server"
},
"app.instance.worlds.delete-world-description": {
"message": "'{name}' akan **dihapus secara permanen**, dan Anda tidak akan dapat memulihkannya."
},
"app.instance.worlds.delete-world-title": {
"message": "Apakah Anda yakin ingin menghapus dunia ini secara permanen?"
},
"app.instance.worlds.filter-modded": {
"message": "Dimodifikasi"
},
@@ -266,21 +254,9 @@
"app.instance.worlds.no-worlds-heading": {
"message": "Tidak ada server atau dunia yang ditambahkan"
},
"app.instance.worlds.remove-server-description": {
"message": "'{name}' akan dihapus dari daftar Anda, termasuk di dalam permainan, dan Anda tidak akan dapat memulihkannya."
},
"app.instance.worlds.remove-server-description-with-address": {
"message": "'{name}' ({address}) akan dihapus dari daftar Anda, termasuk di dalam permainan, dan Anda tidak akan dapat memulihkannya."
},
"app.instance.worlds.remove-server-title": {
"message": "Apakah Anda yakin ingin menghapus {name}?"
},
"app.instance.worlds.search-worlds-placeholder": {
"message": "Cari {count} dunia..."
},
"app.instance.worlds.this-server": {
"message": "server ini"
},
"app.modal.install-to-play.content-required": {
"message": "Konten diperlukan"
},
@@ -161,12 +161,6 @@
"app.content-install.no-compatible-versions": {
"message": "Nessuna versione disponibile soddisfa {compatibilityLabel}. Puoi selezionare una versione da installare comunque. Le dipendenze non verranno scaricate automaticamente."
},
"app.creation-modal.installing-modpack.description": {
"message": "{fileName}"
},
"app.creation-modal.installing-modpack.title": {
"message": "Installando il pacchetto..."
},
"app.export-modal.description-placeholder": {
"message": "Inserisci descrizione del pacchetto..."
},
@@ -239,9 +233,6 @@
"app.instance.worlds.browse-servers": {
"message": "Esplora i server"
},
"app.instance.worlds.delete-world-title": {
"message": "Vuoi davvero eliminare questo mondo per sempre?"
},
"app.instance.worlds.filter-modded": {
"message": "Moddato"
},
@@ -260,15 +251,9 @@
"app.instance.worlds.no-worlds-heading": {
"message": "Nessun server o mondo aggiunto"
},
"app.instance.worlds.remove-server-title": {
"message": "Vuoi davvero rimuovere {name}?"
},
"app.instance.worlds.search-worlds-placeholder": {
"message": "Cerca tra {count} mondi..."
},
"app.instance.worlds.this-server": {
"message": "questo server"
},
"app.modal.install-to-play.content-required": {
"message": "Contenuto richiesto"
},
@@ -140,12 +140,6 @@
"app.browse.server.installing": {
"message": "インストール中"
},
"app.creation-modal.installing-modpack.description": {
"message": "{fileName}"
},
"app.creation-modal.installing-modpack.title": {
"message": "Modパックをインストール中..."
},
"app.export-modal.description-placeholder": {
"message": "Modパックの説明を入力…"
},
@@ -215,12 +209,6 @@
"app.instance.worlds.browse-servers": {
"message": "サーバーを探す"
},
"app.instance.worlds.delete-world-description": {
"message": "'{name}' は **完全に削除**され、元に戻すことはできません。"
},
"app.instance.worlds.delete-world-title": {
"message": "本当にこのワールドを完全に削除しますか?"
},
"app.instance.worlds.filter-modded": {
"message": "Mod導入済み"
},
@@ -239,21 +227,9 @@
"app.instance.worlds.no-worlds-heading": {
"message": "サーバー、ワールドは追加されていません"
},
"app.instance.worlds.remove-server-description": {
"message": "'{name}' はゲーム内を含むサーバーリストから削除され、元に戻すことはできません。"
},
"app.instance.worlds.remove-server-description-with-address": {
"message": "'{name}' ({address}) はゲーム内を含むサーバーリストから削除され、元に戻すことはできません。"
},
"app.instance.worlds.remove-server-title": {
"message": "本当に {name} を削除しますか?"
},
"app.instance.worlds.search-worlds-placeholder": {
"message": "{count} 個のワールドを検索…"
},
"app.instance.worlds.this-server": {
"message": "このサーバー"
},
"app.modal.install-to-play.content-required": {
"message": "必須コンテンツ"
},
@@ -155,12 +155,6 @@
"app.content-install.no-compatible-versions": {
"message": "{compatibilityLabel} 버전과 일치하는 버전이 없습니다. 설치할 버전을 선택하세요. 종속성은 자동으로 설치되지 않습니다."
},
"app.creation-modal.installing-modpack.description": {
"message": "{fileName}"
},
"app.creation-modal.installing-modpack.title": {
"message": "모드팩 설치중..."
},
"app.export-modal.description-placeholder": {
"message": "모드팩 설명 입력..."
},
@@ -236,12 +230,6 @@
"app.instance.worlds.browse-servers": {
"message": "서버 탐색하기"
},
"app.instance.worlds.delete-world-description": {
"message": "'{name}'이(가) **영구적으로 삭제**되며, 복구할 수 없습니다."
},
"app.instance.worlds.delete-world-title": {
"message": "정말로 이 세계를 영구적으로 삭제하시겠습니까?"
},
"app.instance.worlds.filter-modded": {
"message": "수정됨"
},
@@ -260,21 +248,9 @@
"app.instance.worlds.no-worlds-heading": {
"message": "추가된 서버 또는 세계 없음"
},
"app.instance.worlds.remove-server-description": {
"message": "'{name}'이(가) 게임 내를 포함한 모든 목록에서 삭제되며, 복구할 수 없습니다."
},
"app.instance.worlds.remove-server-description-with-address": {
"message": "'{name}' ({address})이(가) 게임 내를 포함한 모든 목록에서 삭제되며, 복구할 수 없습니다."
},
"app.instance.worlds.remove-server-title": {
"message": "정말로 {name}을(를) 제거하시겠습니까?"
},
"app.instance.worlds.search-worlds-placeholder": {
"message": "{count}개의 세계 검색..."
},
"app.instance.worlds.this-server": {
"message": "이 서버"
},
"app.modal.install-to-play.content-required": {
"message": "콘텐츠 설치 필요"
},
@@ -146,12 +146,6 @@
"app.content-install.no-compatible-versions": {
"message": "Tiada versi tersedia yang sepadan dengan {compatibilityLabel}. Pilih versi untuk dipasang juga. Kebergantungan tidak akan dipasang secara automatik."
},
"app.creation-modal.installing-modpack.description": {
"message": "{fileName}"
},
"app.creation-modal.installing-modpack.title": {
"message": "Sedang memasang pek mod..."
},
"app.export-modal.description-placeholder": {
"message": "Masukkan keterangan pek mod..."
},
@@ -227,12 +221,6 @@
"app.instance.worlds.browse-servers": {
"message": "Layari pelayan"
},
"app.instance.worlds.delete-world-description": {
"message": "'{name}' akan **dipadamkan secara kekal**, dan tiada cara untuk memulihkannya."
},
"app.instance.worlds.delete-world-title": {
"message": "Adakah anda pasti mahu memadamkan dunia ini secara kekal?"
},
"app.instance.worlds.filter-modded": {
"message": "Diubah Suai"
},
@@ -251,21 +239,9 @@
"app.instance.worlds.no-worlds-heading": {
"message": "Tiada pelayan atau dunia ditambah"
},
"app.instance.worlds.remove-server-description": {
"message": "'{name}' akan dialih keluar daripada senarai anda, termasuk dalam permainan, dan tiada cara untuk memulihkannya."
},
"app.instance.worlds.remove-server-description-with-address": {
"message": "'{name}' ({address}) akan dialih keluar daripada senarai anda, termasuk dalam permainan, dan tiada cara untuk memulihkannya."
},
"app.instance.worlds.remove-server-title": {
"message": "Adakah anda pasti mahu mengalih keluar {name}?"
},
"app.instance.worlds.search-worlds-placeholder": {
"message": "Cari {count} dunia..."
},
"app.instance.worlds.this-server": {
"message": "pelayan ini"
},
"app.modal.install-to-play.content-required": {
"message": "Kandungan yang diperlukan"
},
@@ -161,12 +161,6 @@
"app.content-install.no-compatible-versions": {
"message": "Er zijn geen beschikbare versies die overeenkomen met {compatibilityLabel}. Selecteer toch een versie om te installeren. Afhankelijkheden worden niet automatisch geïnstalleerd."
},
"app.creation-modal.installing-modpack.description": {
"message": "{fileName}"
},
"app.creation-modal.installing-modpack.title": {
"message": "Modpack aan het installeren..."
},
"app.export-modal.description-placeholder": {
"message": "Voeg modpack beschrijving in..."
},
@@ -242,9 +236,6 @@
"app.instance.worlds.browse-servers": {
"message": "Zoek servers"
},
"app.instance.worlds.delete-world-title": {
"message": "Weet je zeker dat je deze wereld definitief wilt verwijderen?"
},
"app.instance.worlds.filter-modded": {
"message": "Gemod"
},
@@ -263,21 +254,9 @@
"app.instance.worlds.no-worlds-heading": {
"message": "Noch servers noch werelden toegevoegd"
},
"app.instance.worlds.remove-server-description": {
"message": "'{name}' wordt uit je lijst verwijderd, ook in de game, en kan op geen enkele manier worden hersteld."
},
"app.instance.worlds.remove-server-description-with-address": {
"message": "'{name}' ({address}) wordt uit je lijst verwijderd, ook in de game, en kan op geen enkele manier worden hersteld."
},
"app.instance.worlds.remove-server-title": {
"message": "Ben je zeker dat je {name} wil verwijderen?"
},
"app.instance.worlds.search-worlds-placeholder": {
"message": "Zoek werelden"
},
"app.instance.worlds.this-server": {
"message": "deze server"
},
"app.modal.install-to-play.content-required": {
"message": "Content vereist"
},
@@ -161,12 +161,6 @@
"app.content-install.no-compatible-versions": {
"message": "Nie znaleziono żadnych wersji pasujących do {compatibilityLabel}. Wybierz wersję, by zainstalować ją mimo tego. Zależności nie zostaną zainstalowane automatycznie."
},
"app.creation-modal.installing-modpack.description": {
"message": "{fileName}"
},
"app.creation-modal.installing-modpack.title": {
"message": "Instalowanie paczki modów..."
},
"app.export-modal.description-placeholder": {
"message": "Wprowadź opis paczki modów..."
},
@@ -239,12 +233,6 @@
"app.instance.worlds.browse-servers": {
"message": "Szukaj serwerów"
},
"app.instance.worlds.delete-world-description": {
"message": "'{name}' zostanie **permanentnie usunięty** i nie ma możliwości go odzyskać."
},
"app.instance.worlds.delete-world-title": {
"message": "Czy na pewno chcesz trwale usunąć ten świat?"
},
"app.instance.worlds.filter-modded": {
"message": "Zmodowany"
},
@@ -263,21 +251,9 @@
"app.instance.worlds.no-worlds-heading": {
"message": "Nie dodano żadnych światów ani serwerów"
},
"app.instance.worlds.remove-server-description": {
"message": "'{name}' zostanie usunięty z twojej listy, również z gry, i nie będzie możliwości go odzyskać."
},
"app.instance.worlds.remove-server-description-with-address": {
"message": "'{name}' ({address}) zostanie usunięty z twojej listy, również z gry, i nie będzie możliwości go odzyskać."
},
"app.instance.worlds.remove-server-title": {
"message": "Czy jesteś pewny, że chcesz usunąć {name}?"
},
"app.instance.worlds.search-worlds-placeholder": {
"message": "Szukaj wśród {count} światów..."
},
"app.instance.worlds.this-server": {
"message": "ten serwer"
},
"app.modal.install-to-play.content-required": {
"message": "Wymagana zawartość"
},
@@ -161,12 +161,6 @@
"app.content-install.no-compatible-versions": {
"message": "Nenhuma versão disponível corresponde a {compatibilityLabel}. Selecione uma versão para instalar mesmo assim. As dependências não serão instaladas automaticamente."
},
"app.creation-modal.installing-modpack.description": {
"message": "{fileName}"
},
"app.creation-modal.installing-modpack.title": {
"message": "Instalando pacote de mods..."
},
"app.export-modal.description-placeholder": {
"message": "Insira uma descrição para o pacote de mods..."
},
@@ -242,12 +236,6 @@
"app.instance.worlds.browse-servers": {
"message": "Explorar servidores"
},
"app.instance.worlds.delete-world-description": {
"message": "'{name}' será **excluído permanentemente**, e não poderá ser recuperado."
},
"app.instance.worlds.delete-world-title": {
"message": "Deseja mesmo excluir este mundo permanentemente?"
},
"app.instance.worlds.filter-modded": {
"message": "Modificado"
},
@@ -266,21 +254,9 @@
"app.instance.worlds.no-worlds-heading": {
"message": "Nenhum servidor ou mundo adicionado"
},
"app.instance.worlds.remove-server-description": {
"message": "'{name}' será removido da lista, inclusive no jogo, e não poderá ser recuperado."
},
"app.instance.worlds.remove-server-description-with-address": {
"message": "'{name}' ({address}) será removido da lista, inclusive no jogo, e não poderá ser recuperado."
},
"app.instance.worlds.remove-server-title": {
"message": "Deseja mesmo remover {name}?"
},
"app.instance.worlds.search-worlds-placeholder": {
"message": "Buscar {count} mundos..."
},
"app.instance.worlds.this-server": {
"message": "este servidor"
},
"app.modal.install-to-play.content-required": {
"message": "Conteúdo necessário"
},
@@ -170,9 +170,6 @@
"app.instance.worlds.browse-servers": {
"message": "Procurar servidores"
},
"app.instance.worlds.delete-world-title": {
"message": "Tens a certeza que queres apagar permanentemente este mundo?"
},
"app.instance.worlds.filter-modded": {
"message": "Com Mods"
},
@@ -191,15 +188,9 @@
"app.instance.worlds.no-worlds-heading": {
"message": "Sem servidores ou mundos adicionados"
},
"app.instance.worlds.remove-server-title": {
"message": "Tens a certeza que queres remover {name}?"
},
"app.instance.worlds.search-worlds-placeholder": {
"message": "Pesquisar {count} mundos..."
},
"app.instance.worlds.this-server": {
"message": "este servidor"
},
"app.modal.install-to-play.content-required": {
"message": "Conteúdo necessário"
},
@@ -161,12 +161,6 @@
"app.content-install.no-compatible-versions": {
"message": "Не найдено доступных версий, совместимых с {compatibilityLabel}. Выберите версию для установки вручную. Зависимости не будут установлены автоматически."
},
"app.creation-modal.installing-modpack.description": {
"message": "{fileName}"
},
"app.creation-modal.installing-modpack.title": {
"message": "Установка сборки..."
},
"app.export-modal.description-placeholder": {
"message": "Введите описание сборки..."
},
@@ -239,9 +233,6 @@
"app.instance.worlds.browse-servers": {
"message": "Найти серверы"
},
"app.instance.worlds.delete-world-title": {
"message": "Вы действительно хотите удалить этот мир?"
},
"app.instance.worlds.filter-modded": {
"message": "Модовые"
},
@@ -260,12 +251,6 @@
"app.instance.worlds.no-worlds-heading": {
"message": "Нет серверов и миров"
},
"app.instance.worlds.remove-server-title": {
"message": "Вы действительно хотите удалить {name}?"
},
"app.instance.worlds.this-server": {
"message": "этот сервер"
},
"app.modal.install-to-play.content-required": {
"message": "Требуется дополнительный контент"
},
@@ -92,12 +92,6 @@
"app.instance.worlds.browse-servers": {
"message": "Pretraži servere"
},
"app.instance.worlds.delete-world-description": {
"message": "'{name}' će biti **trajno izbrisan**, i neće biti načina da se vrati."
},
"app.instance.worlds.delete-world-title": {
"message": "Da li ste sigurni da hoćete da trajno izbrišete ovaj svet?"
},
"app.instance.worlds.filter-modded": {
"message": "Modifikovano"
},
@@ -116,21 +110,9 @@
"app.instance.worlds.no-worlds-heading": {
"message": "Nema dodatih servera niti svetova"
},
"app.instance.worlds.remove-server-description": {
"message": "'{name}' će biti izbrisan sa vaše liste, uključujući i unutar igre, i neće biti načina da se oporavi."
},
"app.instance.worlds.remove-server-description-with-address": {
"message": "'{name}' ({address}) će biti izbrisan sa vaše liste, uključujući i unutar igre, i neće biti načina da se oporavi."
},
"app.instance.worlds.remove-server-title": {
"message": "Da li ste sigurni da hoćete da izbrišete {name}?"
},
"app.instance.worlds.search-worlds-placeholder": {
"message": "Pretraži {count} svetova..."
},
"app.instance.worlds.this-server": {
"message": "ovaj server"
},
"app.settings.tabs.appearance": {
"message": "Izgled"
},
@@ -152,12 +152,6 @@
"app.content-install.no-compatible-versions": {
"message": "Ingen tillgänglig version matchar {compatibilityLabel}. Välj en version att installera ändå. Beroenden kommer inte installeras automatiskt."
},
"app.creation-modal.installing-modpack.description": {
"message": "{fileName}"
},
"app.creation-modal.installing-modpack.title": {
"message": "Installerar modpaket..."
},
"app.export-modal.description-placeholder": {
"message": "Ange modpaketets beskrivning..."
},
@@ -233,12 +227,6 @@
"app.instance.worlds.browse-servers": {
"message": "Utforska servrar"
},
"app.instance.worlds.delete-world-description": {
"message": "'{name}' kommer ** tas bort permanent**, och det kommer inte finnas något sätt att återskapa den."
},
"app.instance.worlds.delete-world-title": {
"message": "Är du säker på att du vill permanent radera denna värld?"
},
"app.instance.worlds.filter-modded": {
"message": "Moddad"
},
@@ -257,21 +245,9 @@
"app.instance.worlds.no-worlds-heading": {
"message": "Inga servrar eller världar tillagda"
},
"app.instance.worlds.remove-server-description": {
"message": "'{name}' kommer bli borttagen från din lista, inklusive i spelet, och det kommer inte finnas något sätt att återskapa den."
},
"app.instance.worlds.remove-server-description-with-address": {
"message": "'{name}' ({address}) kommer bli borttagen från din lista, inklusive i spelet, och det kommer inte finnas något sätt att återskapa den."
},
"app.instance.worlds.remove-server-title": {
"message": "Är du säker på att du vill radera {name}?"
},
"app.instance.worlds.search-worlds-placeholder": {
"message": "Sök {count} världar..."
},
"app.instance.worlds.this-server": {
"message": "denna server"
},
"app.modal.install-to-play.content-required": {
"message": "Innehåll krävs"
},
@@ -161,12 +161,6 @@
"app.content-install.no-compatible-versions": {
"message": "ไม่มีเวอร์ชันที่เข้ากันได้ {compatibilityLabel} โปรดเลือกเวอร์ชันที่จะติดตั้ง ไฟล์ที่จำเป็นจะไม่ถูกติดตั้งโดยอัตโนมัติ"
},
"app.creation-modal.installing-modpack.description": {
"message": "{fileName}"
},
"app.creation-modal.installing-modpack.title": {
"message": "กำลังติดตั้งแพ็กม็อด..."
},
"app.export-modal.description-placeholder": {
"message": "กรอกคำอธิบายมอดแพ็ก.."
},
@@ -242,12 +236,6 @@
"app.instance.worlds.browse-servers": {
"message": "ค้นหาเซิร์ฟเวอร์"
},
"app.instance.worlds.delete-world-description": {
"message": "'{name}' จะ**ถูกลบออกอย่างถาวร** และจะไม่มีทางสามารถกู้คืนได้"
},
"app.instance.worlds.delete-world-title": {
"message": "คุณแน่ใจหรือไม่ว่าต้องการลบโลกนี้อย่างถาวร?"
},
"app.instance.worlds.filter-modded": {
"message": "ม็อด"
},
@@ -266,21 +254,9 @@
"app.instance.worlds.no-worlds-heading": {
"message": "ไม่มีเซิร์ฟเวอร์หรือโลกที่เพิ่มไว้"
},
"app.instance.worlds.remove-server-description": {
"message": "'{name}' จะถูกลบออกจากรายการของคุณ ซึ่งจะรวมถึงในเกม และการลบดังกล่าวจะไม่มีทางกู้คืนได้อีก"
},
"app.instance.worlds.remove-server-description-with-address": {
"message": "'{name}' ({address}) จะถูกลบออกจากรายการของคุณ ซึ่งจะรวมถึงในเกม และการลบดังกล่าวจะไม่มีทางกู้คืนได้อีก"
},
"app.instance.worlds.remove-server-title": {
"message": "คุณแน่ใจหรือไม่ว่าต้องการลบ {name}?"
},
"app.instance.worlds.search-worlds-placeholder": {
"message": "ค้าหาโลกทั้งหมด {count} โลก"
},
"app.instance.worlds.this-server": {
"message": "เซิร์ฟเวอร์นี้"
},
"app.modal.install-to-play.content-required": {
"message": "เนื้อหาที่จำเป็น"
},
@@ -161,12 +161,6 @@
"app.content-install.no-compatible-versions": {
"message": "Kullanılabilir sürümler {compatibilityLabel} ile eşleşmiyor. Yine de kurulacak bir sürüm seçin. Bağımlılıklar otomatik olarak yüklenmeyecektir."
},
"app.creation-modal.installing-modpack.description": {
"message": "{fileName}"
},
"app.creation-modal.installing-modpack.title": {
"message": "Mod paketi indiriliyor..."
},
"app.export-modal.description-placeholder": {
"message": "Mod paketi açıklaması girin..."
},
@@ -242,12 +236,6 @@
"app.instance.worlds.browse-servers": {
"message": "Sunucuları Keşfet"
},
"app.instance.worlds.delete-world-description": {
"message": "'{name}' **kalıcı olarak silinecek** ve geri getirilmesi mümkün olmayacaktır."
},
"app.instance.worlds.delete-world-title": {
"message": "Bu dünyayı kalıcı olarak silmek istediğinizden emin misiniz?"
},
"app.instance.worlds.filter-modded": {
"message": "Modlu"
},
@@ -266,21 +254,9 @@
"app.instance.worlds.no-worlds-heading": {
"message": "Eklenmiş sunucu veya dünya yok"
},
"app.instance.worlds.remove-server-description": {
"message": "'{name}' oyun içi dahil olmak üzere listenizden kaldırılacak ve geri getirilmesi mümkün olmayacaktır."
},
"app.instance.worlds.remove-server-description-with-address": {
"message": "'{name}' ({address}) oyun içi dahil olmak üzere listenizden kaldırılacak ve geri getirilmesi mümkün olmayacaktır."
},
"app.instance.worlds.remove-server-title": {
"message": "{name}'i kaldırmak istediğinizden emin misiniz?"
},
"app.instance.worlds.search-worlds-placeholder": {
"message": "{count} dünya ara..."
},
"app.instance.worlds.this-server": {
"message": "bu sunucu"
},
"app.modal.install-to-play.content-required": {
"message": "İçerik gerekli"
},
@@ -161,12 +161,6 @@
"app.content-install.no-compatible-versions": {
"message": "Жодна доступна версія не сумісна з {compatibilityLabel}. Виберіть версію, щоб усе одно її встановити. Залежності не встановлюватимуться автоматично."
},
"app.creation-modal.installing-modpack.description": {
"message": "{fileName}"
},
"app.creation-modal.installing-modpack.title": {
"message": "Установлення збірки…"
},
"app.export-modal.description-placeholder": {
"message": "Уведіть опис збірки…"
},
@@ -242,9 +236,6 @@
"app.instance.worlds.browse-servers": {
"message": "Переглянути сервери"
},
"app.instance.worlds.delete-world-title": {
"message": "Ви впевнені, що хочете назавжди видалити цей світ?"
},
"app.instance.worlds.filter-modded": {
"message": "Модифіковано"
},
@@ -263,15 +254,9 @@
"app.instance.worlds.no-worlds-heading": {
"message": "Сервера або світи не додано"
},
"app.instance.worlds.remove-server-title": {
"message": "Ви впевнені, що хочете видалити «{name}»?"
},
"app.instance.worlds.search-worlds-placeholder": {
"message": "Пошук {count} світів…"
},
"app.instance.worlds.this-server": {
"message": "цей сервер"
},
"app.modal.install-to-play.content-required": {
"message": "Потрібний уміст"
},
@@ -161,12 +161,6 @@
"app.content-install.no-compatible-versions": {
"message": "Không có phiên bản nào phù hợp với {compatibilityLabel}. Nếu vẫn chọn một phiên bản để cài đặt, các gói phụ thuộc sẽ không được tải tự động."
},
"app.creation-modal.installing-modpack.description": {
"message": "{fileName}"
},
"app.creation-modal.installing-modpack.title": {
"message": "Đang cài đặt modpack..."
},
"app.export-modal.description-placeholder": {
"message": "Thêm miêu tả cho gói modpack..."
},
@@ -242,12 +236,6 @@
"app.instance.worlds.browse-servers": {
"message": "Tìm kiếm máy chủ"
},
"app.instance.worlds.delete-world-description": {
"message": "'{name}' sẽ bị **xóa vĩnh viễn** và không có cách nào khôi phục lại."
},
"app.instance.worlds.delete-world-title": {
"message": "Bạn có chắc cắn rằng bạn muốn xoá vĩnh viễn thế giới này không?"
},
"app.instance.worlds.filter-modded": {
"message": "Modded"
},
@@ -266,21 +254,9 @@
"app.instance.worlds.no-worlds-heading": {
"message": "Không có máy chủ hay thế giới nào đã được thêm"
},
"app.instance.worlds.remove-server-description": {
"message": "'{name}' sẽ bị xóa khỏi danh sách của bạn, kể cả trong game, và bạn sẽ không có cách nào để khôi phục lại."
},
"app.instance.worlds.remove-server-description-with-address": {
"message": "'{name}' ({address}) sẽ bị xóa khỏi danh sách của bạn, kể cả trong game, và bạn sẽ không có cách nào để khôi phục lại."
},
"app.instance.worlds.remove-server-title": {
"message": "Bạn có chắc chắn rằng bạn muốn xoá {name}?"
},
"app.instance.worlds.search-worlds-placeholder": {
"message": "Tìm kiếm {count} world..."
},
"app.instance.worlds.this-server": {
"message": "Máy chủ này"
},
"app.modal.install-to-play.content-required": {
"message": "Nội dung bắt buộc"
},
@@ -161,12 +161,6 @@
"app.content-install.no-compatible-versions": {
"message": "没有与 {compatibilityLabel} 匹配的可用版本。如果仍要安装,请选择一个版本。依赖项将不会自动安装。"
},
"app.creation-modal.installing-modpack.description": {
"message": "{fileName}"
},
"app.creation-modal.installing-modpack.title": {
"message": "正在安装整合包……"
},
"app.export-modal.description-placeholder": {
"message": "输入整合包描述……"
},
@@ -242,9 +236,6 @@
"app.instance.worlds.browse-servers": {
"message": "浏览服务器"
},
"app.instance.worlds.delete-world-title": {
"message": "你确定要永久删除这个世界吗?"
},
"app.instance.worlds.filter-modded": {
"message": "模组适配"
},
@@ -263,15 +254,9 @@
"app.instance.worlds.no-worlds-heading": {
"message": "未添加服务器或世界"
},
"app.instance.worlds.remove-server-title": {
"message": "你确定要删除 {name} 吗?"
},
"app.instance.worlds.search-worlds-placeholder": {
"message": "搜索 {count} 个世界……"
},
"app.instance.worlds.this-server": {
"message": "此服务器"
},
"app.modal.install-to-play.content-required": {
"message": "需求内容"
},
@@ -161,12 +161,6 @@
"app.content-install.no-compatible-versions": {
"message": "沒有符合 {compatibilityLabel} 的可用版本。請選擇一個版本強制安裝。不會自動安裝相依模組。"
},
"app.creation-modal.installing-modpack.description": {
"message": "{fileName}"
},
"app.creation-modal.installing-modpack.title": {
"message": "正在安裝模組包..."
},
"app.export-modal.description-placeholder": {
"message": "輸入模組包描述..."
},
@@ -242,9 +236,6 @@
"app.instance.worlds.browse-servers": {
"message": "瀏覽伺服器"
},
"app.instance.worlds.delete-world-title": {
"message": "確定要永久刪除這個世界嗎?"
},
"app.instance.worlds.filter-modded": {
"message": "模組"
},
@@ -263,15 +254,9 @@
"app.instance.worlds.no-worlds-heading": {
"message": "未新增任何伺服器或世界"
},
"app.instance.worlds.remove-server-title": {
"message": "確定要移除「{name}」嗎?"
},
"app.instance.worlds.search-worlds-placeholder": {
"message": "搜尋 {count} 個世界..."
},
"app.instance.worlds.this-server": {
"message": "這個伺服器"
},
"app.modal.install-to-play.content-required": {
"message": "所需內容"
},
+44 -32
View File
@@ -41,14 +41,14 @@ import {
get_search_results_v3,
get_version_many,
} from '@/helpers/cache.js'
import { profile_listener } from '@/helpers/events.js'
import { get_loader_versions as getLoaderManifest } from '@/helpers/metadata'
import { instance_listener } from '@/helpers/events.js'
import {
get as getInstance,
get_installed_project_ids as getInstalledProjectIds,
} from '@/helpers/profile.js'
} from '@/helpers/instance'
import { get_loader_versions as getLoaderManifest } from '@/helpers/metadata'
import { get_categories, get_game_versions, get_loaders } from '@/helpers/tags'
import { get_profile_worlds } from '@/helpers/worlds'
import { get_instance_worlds } from '@/helpers/worlds'
import { injectContentInstall } from '@/providers/content-install'
import { injectServerInstall } from '@/providers/server-install'
import {
@@ -56,6 +56,7 @@ import {
provideServerInstallContent,
} from '@/providers/setup/server-install-content'
import { useBreadcrumbs } from '@/store/breadcrumbs'
import { useTheming } from '@/store/state'
const { handleError } = injectNotificationManager()
const { formatMessage } = useVIntl()
@@ -67,6 +68,7 @@ const debugLog = useDebugLogger('Browse')
const router = useRouter()
const route = useRoute()
const themeStore = useTheming()
const serverSetupModalRef = ref<InstanceType<typeof CreationFlowModal> | null>(null)
const serverInstallContent = createServerInstallContent({ serverSetupModalRef })
provideServerInstallContent(serverInstallContent)
@@ -131,10 +133,10 @@ type Instance = {
install_stage: string
icon_path?: string
name: string
linked_data?: {
link?: {
type: string
project_id: string
version_id: string
locked: boolean
}
}
@@ -186,7 +188,7 @@ async function refreshInstalledProjectIds() {
if (!route.query.i) return
if (route.query.from === 'worlds') {
const worlds = await get_profile_worlds(route.query.i as string).catch(handleError)
const worlds = await get_instance_worlds(route.query.i as string).catch(handleError)
if (!worlds) return
const serverProjectIds = worlds
@@ -224,10 +226,10 @@ async function initInstanceContext() {
await refreshInstalledProjectIds()
if (instance.value?.linked_data?.project_id) {
debugLog('checking linked project for server status', instance.value.linked_data.project_id)
if (instance.value?.link?.project_id) {
debugLog('checking linked project for server status', instance.value.link.project_id)
const projectV3 = await get_project_v3(
instance.value.linked_data.project_id,
instance.value.link.project_id,
'must_revalidate',
).catch(handleError)
if (projectV3?.minecraft_server != null) {
@@ -448,7 +450,7 @@ const browseTitle = computed(() =>
)
breadcrumbs.setName('BrowseTitle', browseTitle.value)
if (instance.value) {
const instanceLink = `/instance/${encodeURIComponent(instance.value.path)}`
const instanceLink = `/instance/${encodeURIComponent(instance.value.id)}`
breadcrumbs.setContext({
name: instance.value.name,
link: isFromWorlds.value ? `${instanceLink}/worlds` : instanceLink,
@@ -467,6 +469,21 @@ onBeforeRouteLeave(() => {
const projectType = ref<ProjectType>(route.params.projectType as ProjectType)
function resetInstanceContext() {
if (!instance.value) return
debugLog('instance context removed, resetting')
instance.value = null
installedProjectIds.value = null
instanceHideInstalled.value = false
newlyInstalled.value = []
hiddenInstanceProjectIds.value = new Set()
hiddenInstanceProjectIdsInitialized.value = false
isServerInstance.value = false
breadcrumbs.setName('BrowseTitle', formatMessage(messages.discoverContent))
breadcrumbs.setContext(null)
}
watch(
() => route.params.projectType as ProjectType,
async (newType) => {
@@ -479,16 +496,14 @@ watch(
debugLog('projectType route param changed', { from: projectType.value, to: newType })
projectType.value = newType
},
)
if (!route.query.i && instance.value) {
debugLog('instance context removed, resetting')
instance.value = null
installedProjectIds.value = null
instanceHideInstalled.value = false
newlyInstalled.value = []
isServerInstance.value = false
breadcrumbs.setName('BrowseTitle', formatMessage(messages.discoverContent))
breadcrumbs.setContext(null)
watch(
() => route.query.i,
(instanceId) => {
if (!instanceId && route.path.startsWith('/browse')) {
resetInstanceContext()
}
},
)
@@ -564,6 +579,7 @@ const installContext = computed(() => {
queuedCount: queuedServerInstallCount.value,
selectedProjects: selectedServerInstallProjects.value,
isInstallingSelected: isInstallingQueuedServerInstalls.value,
skipNonEssentialWarnings: themeStore.getFeatureFlag('skip_non_essential_warnings'),
installProgress: queuedInstallProgress.value,
clearQueued: clearQueuedServerInstalls,
clearSelected: clearQueuedServerInstalls,
@@ -578,7 +594,7 @@ const installContext = computed(() => {
loader: instance.value.loader,
gameVersion: instance.value.game_version,
iconSrc: instance.value.icon_path ? convertFileSrc(instance.value.icon_path) : null,
backUrl: `/instance/${encodeURIComponent(instance.value.path)}${isFromWorlds.value ? '/worlds' : ''}`,
backUrl: `/instance/${encodeURIComponent(instance.value.id)}${isFromWorlds.value ? '/worlds' : ''}`,
backLabel: formatMessage(messages.backToInstance),
heading: formatMessage(
isFromWorlds.value ? messages.addServersToInstance : commonMessages.installingContentLabel,
@@ -809,7 +825,7 @@ function getCardActions(
await installVersion(
projectResult.project_id,
selectedInstall.versionId,
instance.value ? instance.value.path : null,
instance.value ? instance.value.id : null,
'SearchCard',
(versionId, installedProjectIds) => {
setProjectInstalling(projectResult.project_id, false)
@@ -982,20 +998,16 @@ if (instance.value?.game_version) {
}
}
await searchState.refreshSearch()
void searchState.refreshSearch()
type UnlistenFn = () => void
let isUnmounted = false
let unlistenProfiles: UnlistenFn | null = null
let unlistenInstances: UnlistenFn | null = null
onMounted(() => {
profile_listener(async (event: { event: string; profile_path_id: string }) => {
if (
instance.value &&
event.profile_path_id === instance.value.path &&
event.event === 'synced'
) {
instance_listener(async (event: { event: string; instance_id: string }) => {
if (instance.value && event.instance_id === instance.value.id && event.event === 'synced') {
await refreshInstalledProjectIds()
await searchState.refreshSearch()
}
@@ -1006,14 +1018,14 @@ onMounted(() => {
return
}
unlistenProfiles = unlisten
unlistenInstances = unlisten
})
.catch(handleError)
})
onUnmounted(() => {
isUnmounted = true
unlistenProfiles?.()
unlistenInstances?.()
})
function getProjectBrowseQuery() {
+7 -7
View File
@@ -8,8 +8,8 @@ import { useRoute } from 'vue-router'
import RowDisplay from '@/components/RowDisplay.vue'
import RecentWorldsList from '@/components/ui/world/RecentWorldsList.vue'
import { get_search_results } from '@/helpers/cache.js'
import { profile_listener } from '@/helpers/events'
import { list } from '@/helpers/profile.js'
import { instance_listener } from '@/helpers/events'
import { list } from '@/helpers/instance'
import type { GameInstance } from '@/helpers/types'
import { useBreadcrumbs } from '@/store/breadcrumbs'
@@ -49,8 +49,8 @@ async function fetchInstances() {
const filters = []
for (const instance of instances.value) {
if (instance.linked_data && instance.linked_data.project_id) {
filters.push(`NOT"project_id"="${instance.linked_data.project_id}"`)
if (instance.link && instance.link.project_id) {
filters.push(`NOT"project_id"="${instance.link.project_id}"`)
}
}
installedModpacksFilter.value = filters.join(' AND ')
@@ -85,8 +85,8 @@ async function refreshFeaturedProjects() {
await fetchInstances()
await refreshFeaturedProjects()
const unlistenProfile = await profile_listener(
async (e: { event: string; profile_path_id: string }) => {
const unlistenInstance = await instance_listener(
async (e: { event: string; instance_id: string }) => {
await fetchInstances()
if (e.event === 'added' || e.event === 'created' || e.event === 'removed') {
@@ -96,7 +96,7 @@ const unlistenProfile = await profile_listener(
)
onUnmounted(() => {
unlistenProfile()
unlistenInstance()
})
</script>
+17 -17
View File
@@ -24,8 +24,8 @@ import {
} from '@tauri-apps/plugin-fs'
import { onUnmounted, ref, watch } from 'vue'
import { profile_listener } from '@/helpers/events'
import { get_full_path } from '@/helpers/profile'
import { instance_listener } from '@/helpers/events'
import { get_full_path } from '@/helpers/instance'
import type { GameInstance } from '@/helpers/types'
import { highlightInFolder } from '@/helpers/utils'
@@ -62,9 +62,9 @@ const error = ref<Error | null>(null)
const currentPath = ref('')
const editingFile = ref<EditingFile | null>(null)
debug('setup: start, instance.path =', props.instance.path)
debug('setup: start, instance.id =', props.instance.id)
instanceRoot.value = await get_full_path(props.instance.path)
instanceRoot.value = await get_full_path(props.instance.id)
debug('setup: instanceRoot =', instanceRoot.value)
await refresh()
debug('setup: refresh complete, items =', items.value.length, 'error =', error.value)
@@ -221,7 +221,7 @@ async function handleWriteFile(path: string, content: string) {
async function handleDownloadFile(path: string, _fileName: string) {
await invoke('plugin:files|file_save_as', {
instancePath: props.instance.path,
instanceId: props.instance.id,
filePath: path,
})
}
@@ -275,7 +275,7 @@ async function handleUploadFiles(files: File[]) {
async function handleExtractFile(path: string, override: boolean, dry: boolean) {
try {
return await invoke('plugin:files|file_extract_zip', {
instancePath: props.instance.path,
instanceId: props.instance.id,
filePath: path,
overrideConflicts: override,
dryRun: dry,
@@ -289,28 +289,28 @@ async function handleExtractFile(path: string, override: boolean, dry: boolean)
}
}
debug('setup: registering profile_listener')
const unlistenProfiles = await profile_listener(
async (event: { event: string; profile_path_id: string }) => {
debug('profile_listener: event =', event.event, 'path =', event.profile_path_id)
if (event.profile_path_id === props.instance.path && event.event === 'synced') {
debug('profile_listener: synced event matched, calling refresh')
debug('setup: registering instance_listener')
const unlistenInstances = await instance_listener(
async (event: { event: string; instance_id: string }) => {
debug('instance_listener: event =', event.event, 'path =', event.instance_id)
if (event.instance_id === props.instance.id && event.event === 'synced') {
debug('instance_listener: synced event matched, calling refresh')
await refresh()
}
},
)
debug('setup: profile_listener registered')
debug('setup: instance_listener registered')
onUnmounted(() => {
unlistenProfiles()
unlistenInstances()
})
watch(
() => props.instance.path,
() => props.instance.id,
async () => {
debug('watch instance.path: changed to', props.instance.path)
debug('watch instance.id: changed to', props.instance.id)
firstPaintPending.value = true
instanceRoot.value = await get_full_path(props.instance.path)
instanceRoot.value = await get_full_path(props.instance.id)
currentPath.value = ''
await refresh()
},
+90 -48
View File
@@ -6,7 +6,7 @@
>
<ExportModal ref="exportModal" :instance="instance" />
<InstanceSettingsModal
:key="instance.path"
:key="instance.id"
ref="settingsModal"
:instance="instance"
:offline="offline"
@@ -19,7 +19,7 @@
:src="icon ? icon : undefined"
:alt="instance.name"
size="64px"
:tint-by="instance.path"
:tint-by="instance.id"
/>
</template>
<template #title>
@@ -78,7 +78,7 @@
<Avatar
:src="linkedProjectV3.icon_url"
:alt="linkedProjectV3.name"
:tint-by="instance.path"
:tint-by="instance.id"
size="24px"
/>
<router-link
@@ -190,13 +190,17 @@
{
id: 'open-folder',
action: () => {
if (instance) showProfileInFolder(instance.path)
if (instance) showInstanceInFolder(instance.id)
},
},
{
id: 'export-mrpack',
action: () => exportModal?.show(),
},
{
id: 'create-shortcut',
action: () => createShortcut(),
},
]"
>
<MoreVerticalIcon />
@@ -204,6 +208,7 @@
<template #host-a-server> <ServerIcon /> Create a server </template>
<template #open-folder> <FolderOpenIcon /> Open folder </template>
<template #export-mrpack> <PackageIcon /> Export modpack </template>
<template #create-shortcut> <ExternalIcon /> Create shortcut </template>
</OverflowMenu>
</ButtonStyled>
</div>
@@ -214,14 +219,10 @@
<NavTabs :links="tabs" />
</div>
<div :class="['p-6 pt-4', { 'min-h-0 flex-1 overflow-y-auto': isFixedRender }]">
<RouterView
v-if="route.path.startsWith('/instance')"
v-slot="{ Component }"
:key="instance.path"
>
<RouterView v-slot="{ Component }" :key="instance.id" :route="displayedInstanceRoute">
<template v-if="Component">
<Suspense
:key="instance.path"
:key="instance.id"
@pending="subpagePending = true"
@resolve="subpagePending = false"
>
@@ -309,7 +310,7 @@ import { convertFileSrc } from '@tauri-apps/api/core'
import dayjs from 'dayjs'
import duration from 'dayjs/plugin/duration'
import relativeTime from 'dayjs/plugin/relativeTime'
import { computed, onUnmounted, ref, watch } from 'vue'
import { computed, onUnmounted, ref, shallowRef, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import ContextMenu from '@/components/ui/ContextMenu.vue'
@@ -319,12 +320,13 @@ import UpdateToPlayModal from '@/components/ui/modal/UpdateToPlayModal.vue'
import { useInstanceConsole } from '@/composables/useInstanceConsole'
import { trackEvent } from '@/helpers/analytics'
import { get_project_v3 } from '@/helpers/cache.js'
import { process_listener, profile_listener } from '@/helpers/events'
import { instance_listener, process_listener } from '@/helpers/events'
import { install_existing_instance, install_pack_to_existing_instance } from '@/helpers/install'
import { get, get_full_path, kill, run } from '@/helpers/instance'
import { type InstanceContentData, loadInstanceContentData } from '@/helpers/instance-content'
import { get_by_profile_path } from '@/helpers/process'
import { finish_install, get, get_full_path, kill, run } from '@/helpers/profile'
import { get_by_instance_id } from '@/helpers/process'
import type { GameInstance } from '@/helpers/types'
import { showProfileInFolder } from '@/helpers/utils.js'
import { createInstanceShortcut, showInstanceInFolder } from '@/helpers/utils.js'
import { get_server_status, refreshWorlds } from '@/helpers/worlds'
import { injectServerInstall } from '@/providers/server-install'
import { handleSevereError } from '@/store/error.js'
@@ -333,12 +335,13 @@ import { useBreadcrumbs, useTheming } from '@/store/state'
dayjs.extend(duration)
dayjs.extend(relativeTime)
const { handleError } = injectNotificationManager()
const { addNotification, handleError } = injectNotificationManager()
const { playServerProject } = injectServerInstall()
const queryClient = useQueryClient()
const route = useRoute()
const router = useRouter()
const displayedInstanceRoute = shallowRef(router.currentRoute.value)
const breadcrumbs = useBreadcrumbs()
const themeStore = useTheming()
const showInstancePlayTime = computed(() => themeStore.getFeatureFlag('show_instance_play_time'))
@@ -377,7 +380,17 @@ const playersOnline = ref<number | undefined>(undefined)
const ping = ref<number | undefined>(undefined)
const loadingServerPing = ref(false)
function isContentSubpageRoute(routeName = route.name) {
watch(
() => router.currentRoute.value,
(nextRoute) => {
if (nextRoute.path.startsWith('/instance')) {
displayedInstanceRoute.value = nextRoute
}
},
{ immediate: true },
)
function isContentSubpageRoute(routeName = displayedInstanceRoute.value.name) {
return typeof routeName === 'string' && contentSubpageRouteNames.has(routeName)
}
@@ -395,15 +408,12 @@ async function fetchInstance() {
const contentPreloadPromise =
nextInstance && isContentSubpageRoute()
? loadInstanceContentData(nextInstance.path, undefined, handleError)
? loadInstanceContentData(nextInstance.id, undefined, handleError)
: Promise.resolve(null)
if (!offline.value && nextInstance?.linked_data && nextInstance.linked_data.project_id) {
if (!offline.value && nextInstance?.link && nextInstance.link.project_id) {
try {
nextLinkedProjectV3 = await get_project_v3(
nextInstance.linked_data.project_id,
'must_revalidate',
)
nextLinkedProjectV3 = await get_project_v3(nextInstance.link.project_id, 'must_revalidate')
if (nextLinkedProjectV3?.minecraft_server != null) {
nextIsServerInstance = true
@@ -424,8 +434,8 @@ async function fetchInstance() {
if (nextInstance) {
queryClient.prefetchQuery({
queryKey: ['worlds', nextInstance.path],
queryFn: () => refreshWorlds(nextInstance.path),
queryKey: ['worlds', nextInstance.id],
queryFn: () => refreshWorlds(nextInstance.id),
staleTime: 30_000,
})
}
@@ -454,7 +464,7 @@ function fetchDeferredData() {
async function updatePlayState() {
if (!route.params.id) return
const runningProcesses = await get_by_profile_path(route.params.id as string).catch(handleError)
const runningProcesses = await get_by_instance_id(route.params.id as string).catch(handleError)
playing.value = Array.isArray(runningProcesses) && runningProcesses.length > 0
}
@@ -469,7 +479,9 @@ watch(
},
)
const basePath = computed(() => `/instance/${encodeURIComponent(route.params.id as string)}`)
const basePath = computed(
() => `/instance/${encodeURIComponent(displayedInstanceRoute.value.params.id as string)}`,
)
/**
* Per-route layout mode.
@@ -480,7 +492,7 @@ const basePath = computed(() => `/instance/${encodeURIComponent(route.params.id
* Used by tabs whose content (e.g. the log console) needs a bounded height to resolve `h-full`.
*/
const renderMode = computed<'scroll' | 'fixed'>(() =>
route.meta.renderMode === 'fixed' ? 'fixed' : 'scroll',
displayedInstanceRoute.value.meta.renderMode === 'fixed' ? 'fixed' : 'scroll',
)
const isFixedRender = computed(() => renderMode.value === 'fixed')
const contentSubpageProps = computed(() =>
@@ -519,8 +531,8 @@ if (instance.value) {
)
breadcrumbs.setContext({
name: instance.value.name,
link: route.path,
query: route.query,
link: displayedInstanceRoute.value.path,
query: displayedInstanceRoute.value.query,
})
}
@@ -538,7 +550,7 @@ const startInstance = async (context: string) => {
await run(route.params.id as string)
playing.value = true
} catch (err) {
handleSevereError(err, { profilePath: route.params.id as string })
handleSevereError(err, { instanceId: route.params.id as string })
}
loading.value = false
@@ -564,10 +576,10 @@ const stopInstance = async (context: string) => {
}
const handlePlayServer = async () => {
if (!instance.value?.linked_data?.project_id) return
if (!instance.value?.link?.project_id) return
loading.value = true
try {
await playServerProject(instance.value.linked_data.project_id)
await playServerProject(instance.value.link.project_id)
} finally {
await updatePlayState()
loading.value = false
@@ -575,7 +587,39 @@ const handlePlayServer = async () => {
}
const repairInstance = async () => {
await finish_install(instance.value).catch(handleError)
if (
instance.value.install_stage !== 'pack_installed' &&
(instance.value.link?.type === 'modrinth_modpack' ||
instance.value.link?.type === 'server_project_modpack')
) {
await install_pack_to_existing_instance(instance.value.id, {
type: 'fromVersionId',
project_id: instance.value.link.project_id ?? instance.value.link.server_project_id ?? '',
version_id: instance.value.link.version_id ?? instance.value.link.content_version_id ?? '',
title: instance.value.name,
}).catch(handleError)
} else {
await install_existing_instance(instance.value.id, false).catch(handleError)
}
}
const createShortcut = async () => {
if (!instance.value) return
try {
const shortcutPath = await createInstanceShortcut(instance.value.name, instance.value.id)
if (!shortcutPath) return
addNotification({
type: 'success',
title: 'Shortcut created',
})
} catch (error: unknown) {
addNotification({
type: 'error',
title: `Error creating shortcut`,
text: `${error}`,
})
}
}
const handleRightClick = (event: MouseEvent) => {
@@ -628,7 +672,7 @@ const handleOptionsClick = async (args: { option: string; item: unknown }) => {
})
break
case 'open_folder':
if (instance.value) await showProfileInFolder(instance.value.path)
if (instance.value) await showInstanceInFolder(instance.value.id)
break
case 'copy_path': {
if (instance.value) {
@@ -640,9 +684,9 @@ const handleOptionsClick = async (args: { option: string; item: unknown }) => {
}
}
const unlistenProfiles = await profile_listener(
async (event: { profile_path_id: string; event: string }) => {
if (event.profile_path_id !== route.params.id) return
const unlistenInstances = await instance_listener(
async (event: { instance_id: string; event: string }) => {
if (event.instance_id !== route.params.id) return
if (event.event === 'removed' || route.path === '/') {
if (route.path !== '/') {
await router.push({ path: '/' })
@@ -656,20 +700,18 @@ const unlistenProfiles = await profile_listener(
}
return handleError(err)
})
if (!instance.value?.linked_data?.project_id) {
if (!instance.value?.link?.project_id) {
linkedProjectV3.value = undefined
isServerInstance.value = false
}
},
)
const unlistenProcesses = await process_listener(
(e: { event: string; profile_path_id: string }) => {
if (e.event === 'finished' && e.profile_path_id === route.params.id) {
const unlistenProcesses = await process_listener((e: { event: string; instance_id: string }) => {
if (e.event === 'finished' && e.instance_id === route.params.id) {
playing.value = false
}
},
)
})
const icon = computed(() =>
instance.value?.icon_path ? convertFileSrc(instance.value.icon_path) : null,
@@ -701,10 +743,10 @@ const timePlayedHumanized = computed(() => {
onUnmounted(() => {
unlistenProcesses()
unlistenProfiles()
const profilePath = route.params.id
if (profilePath) {
const { destroy } = useInstanceConsole(profilePath)
unlistenInstances()
const instanceId = displayedInstanceRoute.value.params.id
if (instanceId) {
const { destroy } = useInstanceConsole(instanceId)
destroy()
}
})
+11 -13
View File
@@ -55,7 +55,7 @@ const props = defineProps({
},
})
const profilePathId = computed(() => route.params.id)
const instanceId = computed(() => route.params.id)
const {
liveConsole,
historicalConsole,
@@ -64,7 +64,7 @@ const {
getHistoricalContent,
invalidate,
clearLive,
} = useInstanceConsole(profilePathId.value)
} = useInstanceConsole(instanceId.value)
await hydrate()
@@ -89,7 +89,7 @@ function buildLogList(rawLogs) {
const logs = ref(buildLogList([]))
void getHistoricalLogs(props.instance.path)
void getHistoricalLogs()
.then((allLogs) => {
logs.value = buildLogList(allLogs)
})
@@ -146,9 +146,9 @@ const deleteDisabled = computed(() => {
async function deleteSelectedLog() {
const log = selectedLog.value
if (!log || log.live) return
await delete_logs_by_filename(props.instance.path, log.log_type, log.filename)
await delete_logs_by_filename(props.instance.id, log.log_type, log.filename)
invalidate()
const freshLogs = await getHistoricalLogs(props.instance.path)
const freshLogs = await getHistoricalLogs()
logs.value = buildLogList(freshLogs)
selectedLogIndex.value = 0
}
@@ -186,11 +186,9 @@ watch(selectedLogIndex, async (newIndex) => {
return
}
const output = await get_output_by_filename(
props.instance.path,
log.log_type,
log.filename,
).catch(handleError)
const output = await get_output_by_filename(props.instance.id, log.log_type, log.filename).catch(
handleError,
)
if (output) {
historicalConsole.clear()
historicalConsole.addLegacyLog(output)
@@ -204,7 +202,7 @@ if (!props.playing) {
}
const unlistenLog = await log_listener((payload) => {
if (payload.profile_path_id !== profilePathId.value) return
if (payload.instance_id !== instanceId.value) return
if (payload.type === 'log4j') {
liveConsole.addLog4jEvent(payload)
@@ -214,7 +212,7 @@ const unlistenLog = await log_listener((payload) => {
})
const unlistenProcesses = await process_listener(async (e) => {
if (e.profile_path_id !== profilePathId.value) return
if (e.instance_id !== instanceId.value) return
if (e.event === 'launched') {
liveConsole.clear()
invalidate()
@@ -222,7 +220,7 @@ const unlistenProcesses = await process_listener(async (e) => {
}
if (e.event === 'finished') {
invalidate()
const freshLogs = await getHistoricalLogs(props.instance.path)
const freshLogs = await getHistoricalLogs()
logs.value = buildLogList(freshLogs)
void analyseForCrash()
}
+315 -141
View File
@@ -10,21 +10,21 @@
/>
<ModpackContentModal
ref="modpackContentModal"
:modpack-name="linkedModpackProject?.title"
:modpack-icon-url="linkedModpackProject?.icon_url ?? undefined"
:modpack-name="displayedModpackProject?.title"
:modpack-icon-url="displayedModpackProject?.icon_url ?? undefined"
:enable-toggle="!props.isServerInstance"
:busy="isBulkOperating"
:get-overflow-options="getOverflowOptions"
:switch-version="handleSwitchVersion"
@update:enabled="handleModpackContentToggle"
@bulk:enable="handleModpackContentBulkToggle"
@bulk:disable="handleModpackContentBulkToggle"
@bulk:enable="(items) => handleModpackContentBulkToggle(items, true)"
@bulk:disable="(items) => handleModpackContentBulkToggle(items, false)"
/>
<ConfirmModpackUpdateModal
ref="modpackUpdateConfirmModal"
:downgrade="isModpackUpdateDowngrade"
:backup-tip="
[linkedModpackProject?.title, pendingModpackUpdateVersion?.version_number]
[displayedModpackProject?.title, pendingModpackUpdateVersion?.version_number]
.filter(Boolean)
.join(' ')
"
@@ -40,17 +40,17 @@
:current-loader="instance.loader"
:current-version-id="
updatingModpack
? (instance.linked_data?.version_id ?? '')
? (instance.link?.version_id ?? '')
: (updatingProject?.version?.id ?? '')
"
:is-app="true"
:project-type="updatingModpack ? 'modpack' : updatingProject?.project_type"
:project-icon-url="
updatingModpack ? linkedModpackProject?.icon_url : updatingProject?.project?.icon_url
updatingModpack ? displayedModpackProject?.icon_url : updatingProject?.project?.icon_url
"
:project-name="
updatingModpack
? (linkedModpackProject?.title ?? formatMessage(commonMessages.modpackLabel))
? (displayedModpackProject?.title ?? formatMessage(commonMessages.modpackLabel))
: (updatingProject?.project?.title ?? updatingProject?.file_name)
"
:loading="loadingVersions"
@@ -69,6 +69,7 @@
import type { Labrinth } from '@modrinth/api-client'
import { ClipboardCopyIcon, FolderOpenIcon } from '@modrinth/assets'
import {
type BulkOperationStatus,
commonMessages,
ConfirmModpackUpdateModal,
ContentCardLayout as ContentPageLayout,
@@ -91,6 +92,7 @@ import {
versionChangesGameVersion,
} from '@modrinth/ui'
import { useQuery, useQueryClient } from '@tanstack/vue-query'
import { convertFileSrc } from '@tauri-apps/api/core'
import { getCurrentWebview } from '@tauri-apps/api/webview'
import { open } from '@tauri-apps/plugin-dialog'
import { openUrl } from '@tauri-apps/plugin-opener'
@@ -101,25 +103,28 @@ import ExportModal from '@/components/ui/ExportModal.vue'
import ShareModalWrapper from '@/components/ui/modal/ShareModalWrapper.vue'
import { trackEvent } from '@/helpers/analytics'
import { get_project_versions, get_version, get_version_many } from '@/helpers/cache.js'
import { profile_listener } from '@/helpers/events.js'
import { type InstanceContentData, loadInstanceContentData } from '@/helpers/instance-content'
import {
instance_bulk_update_progress_listener,
instance_listener,
type InstanceBulkUpdateProgress,
} from '@/helpers/events.js'
import { install_duplicate_instance, installJobInstanceId } from '@/helpers/install'
import {
add_project_from_path,
add_project_from_version,
duplicate,
edit,
get,
get_linked_modpack_content,
list,
remove_project,
switch_project_version_with_dependencies,
toggle_disable_project,
update_all,
update_managed_modrinth_version,
update_project,
} from '@/helpers/profile'
} from '@/helpers/instance'
import { type InstanceContentData, loadInstanceContentData } from '@/helpers/instance-content'
import type { CacheBehaviour, GameInstance } from '@/helpers/types'
import { highlightModInProfile } from '@/helpers/utils.js'
import { highlightModInInstance } from '@/helpers/utils.js'
import { injectContentInstall } from '@/providers/content-install'
import { installVersionDependencies } from '@/store/install'
import { useTheming } from '@/store/state'
const messages = defineMessages({
shareTitle: {
@@ -146,16 +151,33 @@ const messages = defineMessages({
id: 'app.instance.mods.content-type-project',
defaultMessage: 'project',
},
bulkUpdateResolvingVersions: {
id: 'app.instance.mods.bulk-update.resolving-versions',
defaultMessage: 'Resolving versions...',
},
bulkUpdateDownloadingProjects: {
id: 'app.instance.mods.bulk-update.downloading-projects',
defaultMessage: 'Downloading {current, number}/{total, number} projects...',
},
bulkUpdateFinishing: {
id: 'app.instance.mods.bulk-update.finishing',
defaultMessage: 'Finishing update...',
},
})
let savedModalState: ModpackContentModalState | null = null
const { formatMessage } = useVIntl()
const { handleError, addNotification } = injectNotificationManager()
const { installingItems } = injectContentInstall()
const { installingItems, installRevisionByInstance, installFailureRevisionByInstance } =
injectContentInstall()
const router = useRouter()
const queryClient = useQueryClient()
const debug = useDebugLogger('Mods:ContentUpdate')
const themeStore = useTheming()
const skipNonEssentialWarnings = computed(() =>
themeStore.getFeatureFlag('skip_non_essential_warnings'),
)
const props = defineProps<{
instance: GameInstance
@@ -164,13 +186,18 @@ const props = defineProps<{
preloadedContent?: InstanceContentData | null
}>()
const loading = ref(true)
function hasPreloadedContent(contentData: InstanceContentData | null | undefined) {
return contentData?.path === props.instance.id
}
const loading = ref(!hasPreloadedContent(props.preloadedContent))
const projects = ref<ContentItem[]>([])
const installingBuffer = ref<ContentItem[]>([])
const handledInstallRevision = ref(0)
watch(
() => installingItems.value.get(props.instance.path),
() => installingItems.value.get(props.instance.id),
(items) => {
if (items && items.length > 0) {
installingBuffer.value = [...items]
@@ -188,25 +215,69 @@ watch(projects, (newProjects) => {
})
const mergedProjects = computed<ContentItem[]>(() => {
const active = installingItems.value.get(props.instance.path)
const active = installingItems.value.get(props.instance.id)
const pending = active ?? installingBuffer.value
if (pending.length === 0) return projects.value
const realProjectIds = new Set(projects.value.map((p) => p.project?.id).filter(Boolean))
const pendingProjectIds = new Set(pending.map((p) => p.project?.id).filter(Boolean))
const displayProjects = projects.value.map((project) =>
project.project?.id && pendingProjectIds.has(project.project.id)
? { ...project, installing: true }
: project,
)
const realProjectIds = new Set(displayProjects.map((p) => p.project?.id).filter(Boolean))
const placeholders = pending.filter((item) => !realProjectIds.has(item.project?.id))
return placeholders.length > 0 ? [...projects.value, ...placeholders] : projects.value
return placeholders.length > 0 ? [...displayProjects, ...placeholders] : displayProjects
})
watch(
() => installFailureRevisionByInstance.value.get(props.instance.id) ?? 0,
(revision, previousRevision) => {
if (revision === previousRevision) return
installingBuffer.value = []
},
)
const linkedModpackProject = ref<ContentModpackCardProject | null>(null)
const linkedModpackVersion = ref<ContentModpackCardVersion | null>(null)
const linkedModpackOwner = ref<ContentOwner | null>(null)
const linkedModpackCategories = ref<ContentModpackCardCategory[]>([])
const linkedModpackHasUpdate = ref(false)
const linkedModpackUpdateVersionId = ref<string | null>(null)
const localImportedModpackUnlinked = ref(false)
const localImportedModpackProject = computed<ContentModpackCardProject | null>(() => {
const link = props.instance.link
if (localImportedModpackUnlinked.value || link?.type !== 'imported_modpack') return null
return {
id: link.filename ?? props.instance.id,
slug: link.filename ?? props.instance.id,
title: link.name ?? props.instance.name,
icon_url: props.instance.icon_path ? convertFileSrc(props.instance.icon_path) : undefined,
description: '',
filename: link.filename ?? undefined,
}
})
const displayedModpackProject = computed(
() => linkedModpackProject.value ?? localImportedModpackProject.value,
)
watch(
() => props.instance.link,
() => {
localImportedModpackUnlinked.value = false
},
)
const isModpackUpdating = ref(false)
const isBulkOperating = ref(false)
const isInstanceBusy = computed(() => props.instance?.install_stage !== 'installed')
const isPackLocked = computed(() => props.instance?.linked_data?.locked ?? false)
const isPackLocked = computed(
() =>
props.instance?.link?.type === 'modrinth_modpack' ||
props.instance?.link?.type === 'server_project_modpack',
)
const shareModal = ref<InstanceType<typeof ShareModalWrapper> | null>()
const exportModal = ref(null)
@@ -214,11 +285,16 @@ const contentUpdaterModal = ref<InstanceType<typeof ContentUpdaterModal> | null>
const modpackContentModal = ref<InstanceType<typeof ModpackContentModal> | null>()
const modpackUpdateConfirmModal = ref<InstanceType<typeof ConfirmModpackUpdateModal> | null>()
const modpackContentQueryKey = computed(() => ['linkedModpackContent', props.instance.path])
const modpackContentQueryKey = computed(() => ['linkedModpackContent', props.instance.id])
const modpackContentQuery = useQuery({
queryKey: modpackContentQueryKey,
queryFn: () => get_linked_modpack_content(props.instance.path),
enabled: computed(() => !!props.instance?.path && !!props.instance?.linked_data),
queryFn: () => get_linked_modpack_content(props.instance.id),
enabled: computed(
() =>
!!props.instance?.id &&
!!props.instance?.link &&
props.instance.install_stage === 'installed',
),
})
// TODO: Extract content operation and updater modal state into composables; this page currently owns file mutations, dependency installs, busy flags, and version selection flow.
@@ -239,6 +315,38 @@ function fileNameFromPath(path: string) {
return path.split('/').pop() ?? path
}
function matchesContentItem(
item: ContentItem,
target: ContentItem,
originalFileName: string,
originalFilePath?: string,
) {
if (item.file_name === originalFileName || item.file_path === originalFilePath) return true
const projectId = target.project?.id
if (!projectId || item.project?.id !== projectId) return false
const versionId = target.version?.id
return !versionId || item.version?.id === versionId
}
function updateLinkedModpackContentCache(
target: ContentItem,
originalFileName: string,
originalFilePath: string | undefined,
updates: Partial<ContentItem>,
) {
queryClient.setQueryData<ContentItem[]>(modpackContentQueryKey.value, (items) => {
if (!items) return items
return items.map((item) =>
matchesContentItem(item, target, originalFileName, originalFilePath)
? { ...item, ...updates }
: item,
)
})
}
function getContentItemId(item: ContentItem | null | undefined) {
return item?.file_path ?? item?.file_name ?? item?.id ?? ''
}
@@ -254,6 +362,10 @@ function hasContentOperation(item: ContentItem) {
return keys.some((key) => activeContentOperationKeys.value.has(key))
}
function canUpdateProject(item: ContentItem) {
return !!item.file_path && !!item.has_update && !!item.update_version_id
}
function setContentItemBusy(item: ContentItem, busy: boolean, originalFileName = item.file_name) {
item.installing = busy
modpackContentModal.value?.updateItem(originalFileName, {
@@ -362,7 +474,7 @@ async function handleBrowseContent() {
if (!props.instance) return
await router.push({
path: `/browse/${props.instance.loader === 'vanilla' ? 'resourcepack' : 'mod'}`,
query: { i: props.instance.path },
query: { i: props.instance.id },
})
}
@@ -376,7 +488,7 @@ async function handleUploadFiles() {
const path = (file as { path?: string }).path ?? file
const fileName = typeof path === 'string' ? (path.split('/').pop() ?? path) : String(path)
try {
await add_project_from_path(props.instance.path, path)
await add_project_from_path(props.instance.id, path)
addedFiles.push(fileName)
} catch (e) {
handleError(e as Error)
@@ -402,21 +514,28 @@ async function handleUploadFiles() {
}
}
async function toggleDisableMod(mod: ContentItem) {
async function toggleDisableMod(mod: ContentItem, desiredEnabled?: boolean) {
if (!mod.file_path) return
const operation = beginContentOperation(mod)
if (!operation) return
const originalFilePath = mod.file_path
try {
const newPath = await toggle_disable_project(props.instance.path, mod.file_path)
const newPath = await toggle_disable_project(props.instance.id, mod.file_path, desiredEnabled)
const newFileName = fileNameFromPath(newPath)
const enabled = !newPath.endsWith('.disabled')
mod.file_path = newPath
mod.file_name = newFileName
mod.enabled = !mod.enabled
mod.enabled = enabled
modpackContentModal.value?.updateItem(operation.originalFileName, {
file_path: newPath,
file_name: newFileName,
enabled: mod.enabled,
enabled,
})
updateLinkedModpackContentCache(mod, operation.originalFileName, originalFilePath, {
file_path: newPath,
file_name: newFileName,
enabled,
})
trackEvent('InstanceProjectDisable', {
@@ -425,7 +544,7 @@ async function toggleDisableMod(mod: ContentItem) {
id: mod.project?.id,
name: mod.project?.title ?? mod.file_name,
project_type: mod.project_type,
disabled: !mod.enabled,
disabled: !enabled,
})
} catch (err) {
handleError(err as Error)
@@ -443,7 +562,7 @@ async function removeMod(mod: ContentItem) {
try {
const removedPath = mod.file_path
await remove_project(props.instance.path, removedPath)
await remove_project(props.instance.id, removedPath)
projects.value = projects.value.filter((x) => removedPath !== x.file_path)
trackEvent('InstanceProjectRemove', {
@@ -517,26 +636,68 @@ async function getDeleteDependencyWarning(items: ContentItem[]) {
return dependents.length > 0 ? { items, dependents } : null
}
function formatBulkUpdateProgress(progress: InstanceBulkUpdateProgress): BulkOperationStatus {
if (progress.stage === 'resolving_versions') {
return {
message: formatMessage(messages.bulkUpdateResolvingVersions),
waiting: true,
}
}
if (progress.stage === 'finishing') {
return {
message: formatMessage(messages.bulkUpdateFinishing),
progress: progress.current,
total: progress.total,
}
}
return {
message: formatMessage(messages.bulkUpdateDownloadingProjects, {
current: progress.current,
total: progress.total,
}),
progress: progress.current,
total: progress.total,
}
}
async function bulkUpdateAllProjects(onProgress?: (status: BulkOperationStatus) => void) {
let unlisten: (() => void) | null = null
try {
if (onProgress) {
onProgress({
message: formatMessage(messages.bulkUpdateResolvingVersions),
waiting: true,
})
unlisten = await instance_bulk_update_progress_listener((progress) => {
if (progress.instanceId !== props.instance.id) return
onProgress(formatBulkUpdateProgress(progress))
})
}
await update_all(props.instance.id)
await refreshContentState('must_revalidate')
} catch (err) {
handleError(err as Error)
throw err
} finally {
unlisten?.()
}
}
async function updateProject(mod: ContentItem) {
if (!mod.file_path) return
if (!canUpdateProject(mod)) return
const operation = beginContentOperation(mod)
if (!operation) return
try {
const updateVersionId = mod.update_version_id
await update_project(props.instance.path, mod.file_path)
if (updateVersionId) {
const versionData = await get_version(updateVersionId, 'must_revalidate').catch(handleError)
if (versionData) {
const profile = await get(props.instance.path).catch(handleError)
if (profile) {
await installVersionDependencies(profile, versionData, 'update').catch(handleError)
}
}
}
const updateVersionId = mod.update_version_id!
await switch_project_version_with_dependencies(
props.instance.id,
mod.file_path,
updateVersionId,
)
trackEvent('InstanceProjectUpdate', {
loader: props.instance.loader,
@@ -560,27 +721,9 @@ async function switchProjectVersion(mod: ContentItem, version: Labrinth.Versions
if (!operation) return
const oldPath = mod.file_path
const wasDisabled = mod.enabled === false || oldPath.endsWith('.disabled')
let newPath: string | null = null
let shouldRemoveNewOnError = false
try {
newPath = await add_project_from_version(props.instance.path, version.id, 'update')
shouldRemoveNewOnError = newPath !== oldPath
if (wasDisabled) {
newPath = await toggle_disable_project(props.instance.path, newPath)
}
const profile = await get(props.instance.path).catch(handleError)
if (profile) {
await installVersionDependencies(profile, version, 'update').catch(handleError)
}
shouldRemoveNewOnError = false
if (newPath !== oldPath) {
await remove_project(props.instance.path, oldPath)
}
await switch_project_version_with_dependencies(props.instance.id, oldPath, version.id)
trackEvent('InstanceProjectUpdate', {
loader: props.instance.loader,
@@ -590,9 +733,6 @@ async function switchProjectVersion(mod: ContentItem, version: Labrinth.Versions
project_type: mod.project_type,
})
} catch (err) {
if (shouldRemoveNewOnError && newPath && newPath !== oldPath) {
await remove_project(props.instance.path, newPath).catch(() => {})
}
handleError(err as Error)
} finally {
await refreshContentState('must_revalidate')
@@ -602,7 +742,7 @@ async function switchProjectVersion(mod: ContentItem, version: Labrinth.Versions
async function handleUpdate(id: string) {
const item = projects.value.find((p) => getContentItemId(p) === id)
if (!item?.has_update || !item.project?.id || !item.version?.id) return
if (!item || !canUpdateProject(item) || !item.project?.id || !item.version?.id) return
const requestId = beginUpdateRequest()
const itemId = getContentItemId(item)
@@ -642,11 +782,11 @@ async function handleUpdate(id: string) {
updateVersionId: item.update_version_id,
},
instance: {
path: props.instance.path,
path: props.instance.id,
name: props.instance.name,
gameVersion: props.instance.game_version,
loader: props.instance.loader,
linkedData: props.instance.linked_data,
link: props.instance.link,
},
modalStateBeforeFetch: {
updatingModpack: updatingModpack.value,
@@ -738,18 +878,18 @@ async function handleSwitchVersion(item: ContentItem) {
updatingProjectVersions.value = versions
}
async function handleModpackContentToggle(item: ContentItem) {
await toggleDisableDebounced(item)
async function handleModpackContentToggle(item: ContentItem, enabled: boolean) {
await toggleDisableDebounced(item, enabled)
}
async function handleModpackContentBulkToggle(items: ContentItem[]) {
await Promise.all(items.map((item) => toggleDisableMod(item)))
async function handleModpackContentBulkToggle(items: ContentItem[], enabled: boolean) {
await Promise.all(items.map((item) => toggleDisableMod(item, enabled)))
}
async function handleModpackContent() {
if (!props.instance?.path) return
if (!props.instance?.id) return
if (modpackContentQuery.data.value !== undefined) {
if (modpackContentQuery.data.value?.length) {
modpackContentModal.value?.show(modpackContentQuery.data.value)
return
}
@@ -767,12 +907,12 @@ async function handleModpackContent() {
}
async function refreshModpackContentItems(cacheBehaviour?: CacheBehaviour) {
if (!props.instance?.path) return
if (!props.instance?.id) return
const contentItems = await queryClient
.fetchQuery({
queryKey: modpackContentQueryKey.value,
queryFn: () => get_linked_modpack_content(props.instance.path, cacheBehaviour),
queryFn: () => get_linked_modpack_content(props.instance.id, cacheBehaviour),
})
.catch(handleError)
@@ -786,8 +926,17 @@ async function refreshContentState(cacheBehaviour?: CacheBehaviour) {
await refreshModpackContentItems(cacheBehaviour)
}
watch(
() => installRevisionByInstance.value.get(props.instance.id) ?? 0,
async (revision) => {
if (revision <= handledInstallRevision.value) return
handledInstallRevision.value = revision
await refreshContentState('must_revalidate')
},
)
async function handleModpackUpdate() {
if (!props.instance?.linked_data?.project_id) return
if (!props.instance?.link?.project_id) return
const requestId = beginUpdateRequest()
@@ -800,7 +949,7 @@ async function handleModpackUpdate() {
await nextTick()
const initialVersionId =
linkedModpackUpdateVersionId.value ?? props.instance?.linked_data?.version_id ?? undefined
linkedModpackUpdateVersionId.value ?? props.instance?.link?.version_id ?? undefined
debug('handleModpackUpdate: opening modpack updater modal', {
type: 'modpack',
initialVersionId,
@@ -809,11 +958,11 @@ async function handleModpackUpdate() {
linkedModpackVersion: linkedModpackVersion.value,
linkedModpackHasUpdate: linkedModpackHasUpdate.value,
instance: {
path: props.instance.path,
path: props.instance.id,
name: props.instance.name,
gameVersion: props.instance.game_version,
loader: props.instance.loader,
linkedData: props.instance.linked_data,
link: props.instance.link,
},
modalStateBeforeFetch: {
updatingModpack: updatingModpack.value,
@@ -829,10 +978,7 @@ async function handleModpackUpdate() {
})
contentUpdaterModal.value?.show(initialVersionId)
const versions = await getUpdaterProjectVersions(
props.instance.linked_data.project_id,
initialVersionId,
)
const versions = await getUpdaterProjectVersions(props.instance.link.project_id, initialVersionId)
if (!isActiveUpdateRequest(requestId) || !updatingModpack.value) return
@@ -857,7 +1003,7 @@ async function handleModpackUpdate() {
: null,
versionCount: versions.length,
linkedModpackUpdateVersionId: linkedModpackUpdateVersionId.value,
currentLinkedVersionId: props.instance.linked_data.version_id,
currentLinkedVersionId: props.instance.link.version_id,
})
updatingProjectVersions.value = versions
@@ -909,7 +1055,7 @@ function resetUpdateState() {
async function handleModpackUpdateRequest(selectedVersion: Labrinth.Versions.v2.Version) {
pendingModpackUpdateVersion.value = selectedVersion
const currentVersionId = props.instance?.linked_data?.version_id
const currentVersionId = props.instance?.link?.version_id
const currentVersion = updatingProjectVersions.value.find((v) => v.id === currentVersionId)
isModpackUpdateDowngrade.value = currentVersion
? new Date(selectedVersion.date_published) < new Date(currentVersion.date_published)
@@ -918,7 +1064,7 @@ async function handleModpackUpdateRequest(selectedVersion: Labrinth.Versions.v2.
isModpackUpdateDowngrade.value ||
versionChangesGameVersion(selectedVersion, props.instance.game_version)
if (!shouldShowWarning) {
if (skipNonEssentialWarnings.value || !shouldShowWarning) {
await handleModpackUpdateConfirm()
return
}
@@ -927,7 +1073,7 @@ async function handleModpackUpdateRequest(selectedVersion: Labrinth.Versions.v2.
}
async function handleModpackUpdateConfirm() {
if (!pendingModpackUpdateVersion.value || !props.instance?.path) return
if (!pendingModpackUpdateVersion.value || !props.instance?.id) return
const version = pendingModpackUpdateVersion.value
pendingModpackUpdateVersion.value = null
@@ -935,7 +1081,7 @@ async function handleModpackUpdateConfirm() {
contentUpdaterModal.value?.hide()
isModpackUpdating.value = true
try {
await update_managed_modrinth_version(props.instance.path, version.id)
await update_managed_modrinth_version(props.instance.id, version.id)
await initProjects()
} finally {
isModpackUpdating.value = false
@@ -973,15 +1119,16 @@ async function handleModalUpdate(
}
}
async function unpairProfile() {
await edit(props.instance.path, {
linked_data: null as unknown as undefined,
async function unpairInstance() {
await edit(props.instance.id, {
link: null as unknown as undefined,
})
linkedModpackProject.value = null
linkedModpackVersion.value = null
linkedModpackOwner.value = null
linkedModpackHasUpdate.value = false
linkedModpackUpdateVersionId.value = null
localImportedModpackUnlinked.value = true
await initProjects()
}
@@ -1025,7 +1172,7 @@ function getOverflowOptions(item: ContentItem): OverflowMenuOption[] {
options.push({
id: formatMessage(commonMessages.showFileButton),
icon: FolderOpenIcon,
action: () => highlightModInProfile(props.instance.path, item.file_path),
action: () => highlightModInInstance(props.instance.id, item.file_path),
})
if (item.project?.slug) {
@@ -1046,23 +1193,24 @@ function getOverflowOptions(item: ContentItem): OverflowMenuOption[] {
async function initProjects(cacheBehaviour?: CacheBehaviour) {
if (!props.instance) return
const contentData = await loadInstanceContentData(
props.instance.path,
cacheBehaviour,
handleError,
)
const contentData = await loadInstanceContentData(props.instance.id, cacheBehaviour, handleError)
applyContentData(contentData)
}
function applyContentData(contentData: InstanceContentData) {
if (contentData.path !== props.instance.path) return false
if (contentData.path !== props.instance.id) {
return false
}
if (!contentData.contentItems) {
loading.value = false
return true
}
projects.value = contentData.contentItems
projects.value = contentData.contentItems.map((item) => ({
...item,
has_update: canUpdateProject(item),
}))
if (contentData.modpack) {
linkedModpackProject.value = contentData.modpack.project
@@ -1086,15 +1234,18 @@ function applyContentData(contentData: InstanceContentData) {
provideAppBackup({
async createBackup() {
const allProfiles = await list()
const allInstances = await list()
const prefix = `${props.instance.name} - Backup #`
const existingNums = allProfiles
const existingNums = allInstances
.filter((p) => p.name.startsWith(prefix))
.map((p) => parseInt(p.name.slice(prefix.length), 10))
.filter((n) => !isNaN(n))
const nextNum = existingNums.length > 0 ? Math.max(...existingNums) + 1 : 1
const newPath = await duplicate(props.instance.path)
await edit(newPath, { name: `${prefix}${nextNum}` })
const job = await install_duplicate_instance(props.instance.id)
const newInstanceId = installJobInstanceId(job)
if (newInstanceId) {
await edit(newInstanceId, { name: `${prefix}${nextNum}` })
}
},
})
@@ -1109,20 +1260,20 @@ provideContentManager({
items: mergedProjects,
loading,
error: ref(null),
modpack: computed(() =>
linkedModpackProject.value
? {
modpack: computed(() => {
if (linkedModpackProject.value) {
return {
project: linkedModpackProject.value,
projectLink: {
path: `/project/${linkedModpackProject.value.slug ?? linkedModpackProject.value.id}`,
query: { i: props.instance.path },
query: { i: props.instance.id },
},
version: linkedModpackVersion.value ?? undefined,
versionLink:
linkedModpackProject.value && linkedModpackVersion.value
? {
path: `/project/${linkedModpackProject.value.slug ?? linkedModpackProject.value.id}/version/${linkedModpackVersion.value.id}`,
query: { i: props.instance.path },
query: { i: props.instance.id },
}
: undefined,
owner: linkedModpackOwner.value
@@ -1141,21 +1292,36 @@ provideContentManager({
? formatMessage(commonMessages.updatingLabel)
: formatMessage(commonMessages.installingLabel),
}
: null,
),
}
if (localImportedModpackProject.value) {
return {
project: localImportedModpackProject.value,
categories: [],
hasUpdate: false,
disabled: isModpackUpdating.value,
disabledText: isModpackUpdating.value
? formatMessage(commonMessages.updatingLabel)
: formatMessage(commonMessages.installingLabel),
}
}
return null
}),
isPackLocked,
isBusy: isInstanceBusy,
isBulkOperating,
skipNonEssentialWarnings,
contentTypeLabel: ref(formatMessage(messages.contentTypeProject)),
toggleEnabled: toggleDisableDebounced,
bulkEnableItems: (items: ContentItem[]) =>
Promise.all(items.filter((item) => !item.enabled).map((item) => toggleDisableMod(item))).then(
() => {},
),
Promise.all(
items.filter((item) => !item.enabled).map((item) => toggleDisableMod(item, true)),
).then(() => {}),
bulkDisableItems: (items: ContentItem[]) =>
Promise.all(items.filter((item) => item.enabled).map((item) => toggleDisableMod(item))).then(
() => {},
),
Promise.all(
items.filter((item) => item.enabled).map((item) => toggleDisableMod(item, false)),
).then(() => {}),
deleteItem: removeMod,
bulkDeleteItems: (items: ContentItem[]) =>
Promise.all(items.map((item) => removeMod(item))).then(() => {}),
@@ -1165,10 +1331,11 @@ provideContentManager({
uploadFiles: handleUploadFiles,
hasUpdateSupport: true,
updateItem: handleUpdate,
bulkUpdateAll: bulkUpdateAllProjects,
bulkUpdateItem: updateProject,
updateModpack: props.isServerInstance ? undefined : handleModpackUpdate,
viewModpackContent: handleModpackContent,
unlinkModpack: unpairProfile,
unlinkModpack: unpairInstance,
openSettings: props.openSettings,
switchVersion: handleSwitchVersion,
getOverflowOptions,
@@ -1184,9 +1351,7 @@ provideContentManager({
title: item.file_name.replace('.disabled', ''),
icon_url: null,
},
projectLink: item.project?.id
? { path: `/project/${item.project.id}`, query: { i: props.instance.path } }
: undefined,
projectLink: item.project?.id ? { path: `/project/${item.project.id}` } : undefined,
version: item.version ?? {
id: item.file_name,
version_number: formatMessage(commonMessages.unknownLabel),
@@ -1196,7 +1361,6 @@ provideContentManager({
item.project?.id && item.version?.id
? {
path: `/project/${item.project.id}/version/${item.version.id}`,
query: { i: props.instance.path },
}
: undefined,
owner: item.owner
@@ -1208,7 +1372,7 @@ provideContentManager({
enabled: item.enabled,
installing: item.installing,
}),
filterPersistKey: props.instance.path,
filterPersistKey: props.instance.id,
})
type UnlistenFn = () => void
@@ -1216,7 +1380,17 @@ type UnlistenFn = () => void
const initialContentReady = loadInitialContent()
void initialContentReady.then(restoreModpackContentModalState).catch(handleError)
function getInstallRevision() {
return installRevisionByInstance.value.get(props.instance.id) ?? 0
}
function loadInitialContent() {
const installRevision = getInstallRevision()
if (installRevision > handledInstallRevision.value) {
handledInstallRevision.value = installRevision
return initProjects('must_revalidate')
}
if (props.preloadedContent && applyContentData(props.preloadedContent)) {
return Promise.resolve()
}
@@ -1241,7 +1415,7 @@ const removeBeforeEach = router.beforeEach(() => {
let isUnmounted = false
let unlistenDragDrop: UnlistenFn | null = null
let unlistenProfiles: UnlistenFn | null = null
let unlistenInstances: UnlistenFn | null = null
onMounted(() => {
void getCurrentWebview()
@@ -1250,7 +1424,7 @@ onMounted(() => {
for (const file of event.payload.paths) {
if (file.endsWith('.mrpack')) continue
await add_project_from_path(props.instance.path, file).catch(handleError)
await add_project_from_path(props.instance.id, file).catch(handleError)
}
await initProjects()
})
@@ -1264,10 +1438,10 @@ onMounted(() => {
})
.catch(handleError)
void profile_listener(async (event: { event: string; profile_path_id: string }) => {
void instance_listener(async (event: { event: string; instance_id: string }) => {
if (
props.instance &&
event.profile_path_id === props.instance.path &&
event.instance_id === props.instance.id &&
event.event === 'synced' &&
props.instance.install_stage !== 'pack_installing' &&
!isBulkOperating.value
@@ -1281,7 +1455,7 @@ onMounted(() => {
return
}
unlistenProfiles = unlisten
unlistenInstances = unlisten
})
.catch(handleError)
})
@@ -1290,7 +1464,7 @@ watch(
() => props.instance?.install_stage,
async (newStage, oldStage) => {
if (oldStage !== 'installed' && newStage === 'installed') {
await initProjects('must_revalidate')
await refreshContentState('must_revalidate')
} else if (oldStage === 'not_installed' && newStage === 'pack_installing') {
await initProjects()
}
@@ -1298,16 +1472,16 @@ watch(
)
watch(
() => props.instance?.linked_data,
async (newLinkedData, oldLinkedData) => {
if (oldLinkedData && !newLinkedData) {
() => props.instance?.link,
async (newInstanceLink, oldInstanceLink) => {
if (oldInstanceLink && !newInstanceLink) {
await initProjects('must_revalidate')
}
},
)
watch(
() => props.instance?.preferred_update_channel,
() => props.instance?.update_channel,
async (newValue, oldValue) => {
if (newValue !== oldValue) {
await initProjects('must_revalidate')
@@ -1319,6 +1493,6 @@ onUnmounted(() => {
isUnmounted = true
removeBeforeEach()
unlistenDragDrop?.()
unlistenProfiles?.()
unlistenInstances?.()
})
</script>
+50 -112
View File
@@ -13,29 +13,10 @@
/>
<EditServerModal ref="editServerModal" :instance="instance" @submit="editServer" />
<EditWorldModal ref="editWorldModal" :instance="instance" @submit="editWorld" />
<ConfirmModalWrapper
ref="removeServerModal"
:title="
formatMessage(messages.removeServerTitle, {
name: serverToRemove?.name ?? formatMessage(messages.thisServer),
})
"
:description="
serverToRemove?.address === serverToRemove?.name
? formatMessage(messages.removeServerDescription, { name: serverToRemove?.name })
: formatMessage(messages.removeServerDescriptionWithAddress, {
name: serverToRemove?.name,
address: serverToRemove?.address,
})
"
:markdown="false"
@proceed="proceedRemoveServer"
/>
<ConfirmModalWrapper
ref="deleteWorldModal"
:title="formatMessage(messages.deleteWorldTitle)"
:description="formatMessage(messages.deleteWorldDescription, { name: worldToDelete?.name })"
@proceed="proceedDeleteWorld"
<ConfirmRemoveWorldModal
ref="removeWorldModal"
:world="worldToRemove"
@confirm="proceedRemoveWorld"
/>
<ReadyTransition :pending="worldsReadyPending">
<div v-if="dedupedWorlds.length > 0" class="flex flex-col gap-4">
@@ -64,7 +45,7 @@
<button
class="!h-10 flex items-center gap-2"
@click="
router.push({ path: '/browse/server', query: { i: instance.path, from: 'worlds' } })
router.push({ path: '/browse/server', query: { i: instance.id, from: 'worlds' } })
"
>
<CompassIcon class="size-5" />
@@ -117,6 +98,7 @@
world.type === 'server' ? serverData[world.address]?.renderedMotd : undefined
"
:game-mode="world.type === 'singleplayer' ? GAME_MODES[world.game_mode] : undefined"
:shortcut-instance-id="instance.id"
@play="() => joinWorld(world)"
@stop="() => emit('stop')"
@refresh="() => refreshServer((world as ServerWorld).address)"
@@ -129,7 +111,7 @@
: editServerModal?.show(world)
"
@delete="() => !isManagedServerWorld(world) && promptToRemoveWorld(world)"
@open-folder="(world: SingleplayerWorld) => showWorldInFolder(instance.path, world.path)"
@open-folder="(world: SingleplayerWorld) => showWorldInFolder(instance.id, world.path)"
/>
</div>
</div>
@@ -150,7 +132,7 @@
<button
class="!h-10 flex items-center gap-2"
@click="
router.push({ path: '/browse/server', query: { i: instance.path, from: 'worlds' } })
router.push({ path: '/browse/server', query: { i: instance.id, from: 'worlds' } })
"
>
<CompassIcon class="size-5" />
@@ -182,32 +164,33 @@ import { computed, onBeforeUnmount, ref, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import type ContextMenu from '@/components/ui/ContextMenu.vue'
import ConfirmModalWrapper from '@/components/ui/modal/ConfirmModalWrapper.vue'
import AddServerModal from '@/components/ui/world/modal/AddServerModal.vue'
import ConfirmRemoveWorldModal from '@/components/ui/world/modal/ConfirmRemoveWorldModal.vue'
import EditServerModal from '@/components/ui/world/modal/EditServerModal.vue'
import EditWorldModal from '@/components/ui/world/modal/EditSingleplayerWorldModal.vue'
import WorldItem from '@/components/ui/world/WorldItem.vue'
import { trackEvent } from '@/helpers/analytics'
import { get_project, get_project_v3 } from '@/helpers/cache.js'
import { profile_listener } from '@/helpers/events'
import { instance_listener } from '@/helpers/events'
import { get_game_versions } from '@/helpers/tags'
import type { GameInstance } from '@/helpers/types'
import { ensureManagedServerWorldExists, getServerAddress } from '@/helpers/worlds'
import {
delete_world,
get_profile_protocol_version,
get_instance_protocol_version,
getServerDomainKey,
getWorldIdentifier,
handleDefaultProfileUpdateEvent,
handleDefaultInstanceUpdateEvent,
hasServerQuickPlaySupport,
hasWorldQuickPlaySupport,
type InstanceEvent,
normalizeServerAddress,
type ProfileEvent,
type ProtocolVersion,
refreshServerData,
refreshServers,
refreshWorld,
refreshWorlds,
remove_server_from_profile,
remove_server_from_instance,
resolveManagedServerWorld,
type ServerData,
type ServerWorld,
@@ -220,32 +203,8 @@ import {
} from '@/helpers/worlds.ts'
import { injectServerInstall } from '@/providers/server-install'
import { handleSevereError } from '@/store/error.js'
import { ensureManagedServerWorldExists, getServerAddress } from '@/store/install'
const messages = defineMessages({
removeServerTitle: {
id: 'app.instance.worlds.remove-server-title',
defaultMessage: 'Are you sure you want to remove {name}?',
},
removeServerDescription: {
id: 'app.instance.worlds.remove-server-description',
defaultMessage:
"'{name}' will be removed from your list, including in-game, and there will be no way to recover it.",
},
removeServerDescriptionWithAddress: {
id: 'app.instance.worlds.remove-server-description-with-address',
defaultMessage:
"'{name}' ({address}) will be removed from your list, including in-game, and there will be no way to recover it.",
},
deleteWorldTitle: {
id: 'app.instance.worlds.delete-world-title',
defaultMessage: 'Are you sure you want to permanently delete this world?',
},
deleteWorldDescription: {
id: 'app.instance.worlds.delete-world-description',
defaultMessage:
"'{name}' will be **permanently deleted**, and there will be no way to recover it.",
},
searchWorldsPlaceholder: {
id: 'app.instance.worlds.search-worlds-placeholder',
defaultMessage: 'Search {count} worlds...',
@@ -266,10 +225,6 @@ const messages = defineMessages({
id: 'app.instance.worlds.no-worlds-description',
defaultMessage: 'Add a server or browse to get started',
},
thisServer: {
id: 'app.instance.worlds.this-server',
defaultMessage: 'this server',
},
vanillaFilter: {
id: 'app.instance.worlds.filter-vanilla',
defaultMessage: 'Vanilla',
@@ -297,11 +252,9 @@ const router = useRouter()
const addServerModal = ref<InstanceType<typeof AddServerModal>>()
const editServerModal = ref<InstanceType<typeof EditServerModal>>()
const editWorldModal = ref<InstanceType<typeof EditWorldModal>>()
const removeServerModal = ref<InstanceType<typeof ConfirmModalWrapper>>()
const deleteWorldModal = ref<InstanceType<typeof ConfirmModalWrapper>>()
const removeWorldModal = ref<InstanceType<typeof ConfirmRemoveWorldModal>>()
const serverToRemove = ref<ServerWorld>()
const worldToDelete = ref<SingleplayerWorld>()
const worldToRemove = ref<World | null>(null)
const emit = defineEmits<{
(event: 'play', world: World): void
@@ -357,8 +310,8 @@ const startingInstance = ref(false)
const worldPlaying = ref<World>()
const worldsQuery = useQuery({
queryKey: computed(() => ['worlds', instance.value.path]),
queryFn: () => refreshWorlds(instance.value.path),
queryKey: computed(() => ['worlds', instance.value.id]),
queryFn: () => refreshWorlds(instance.value.id),
staleTime: 30_000,
})
@@ -406,12 +359,12 @@ function isManagedServerWorld(world: World): world is ServerWorld {
async function refreshManagedServerMetadata() {
await ensureManagedServerWorldExists(
instance.value.path,
instance.value.id,
managedServerName.value,
managedServerAddress.value,
)
const projectId = instance.value.linked_data?.project_id
const projectId = instance.value.link?.project_id
if (!projectId) {
managedServerName.value = null
managedServerAddress.value = null
@@ -441,7 +394,7 @@ async function refreshManagedServerMetadata() {
managedServerAddress.value = serverAddress
} catch (err) {
console.error(
`Failed to resolve managed server metadata for profile: ${instance.value.path}`,
`Failed to resolve managed server metadata for instance: ${instance.value.id}`,
err,
)
managedServerName.value = null
@@ -450,22 +403,22 @@ async function refreshManagedServerMetadata() {
}
watch(
() => instance.value.linked_data?.project_id,
() => instance.value.link?.project_id,
async () => {
await refreshManagedServerMetadata()
},
{ immediate: true },
)
let unlistenProfile: (() => void) | null = null
let unlistenInstance: (() => void) | null = null
let worldsTabAlive = true
async function initWorldsTab() {
const [_unlistenProfile, resolvedProtocolVersion, resolvedGameVersions] = await Promise.all([
profile_listener(async (e: ProfileEvent) => {
if (e.profile_path_id !== instance.value.path) return
const [_unlistenInstance, resolvedProtocolVersion, resolvedGameVersions] = await Promise.all([
instance_listener(async (e: InstanceEvent) => {
if (e.instance_id !== instance.value.id) return
console.info(`Handling profile event '${e.event}' for profile: ${e.profile_path_id}`)
console.info(`Handling instance event '${e.event}' for instance: ${e.instance_id}`)
if (e.event === 'servers_updated') {
if (isLinux && linuxRefreshCount.value >= MAX_LINUX_REFRESHES) return
@@ -474,18 +427,18 @@ async function initWorldsTab() {
await refreshAllWorlds()
}
await handleDefaultProfileUpdateEvent(worlds.value, instance.value.path, e)
await handleDefaultInstanceUpdateEvent(worlds.value, instance.value.id, e)
}),
get_profile_protocol_version(instance.value.path).catch(() => null),
get_instance_protocol_version(instance.value.id).catch(() => null),
get_game_versions().catch(() => [] as GameVersion[]),
])
if (!worldsTabAlive) {
_unlistenProfile()
_unlistenInstance()
return
}
unlistenProfile = _unlistenProfile
unlistenInstance = _unlistenInstance
protocolVersion.value = resolvedProtocolVersion
gameVersions.value = resolvedGameVersions
}
@@ -508,7 +461,7 @@ async function refreshAllWorlds() {
}
refreshingAll.value = true
await queryClient.invalidateQueries({ queryKey: ['worlds', instance.value.path] })
await queryClient.invalidateQueries({ queryKey: ['worlds', instance.value.id] })
refreshingAll.value = false
}
@@ -534,7 +487,7 @@ async function editServer(server: ServerWorld) {
}
async function removeServer(server: ServerWorld) {
await remove_server_from_profile(instance.value.path, server.index).catch(handleError)
await remove_server_from_instance(instance.value.id, server.index).catch(handleError)
worlds.value = worlds.value.filter((w) => w.type !== 'server' || w.index !== server.index)
let serverIdx = 0
for (const w of worlds.value) {
@@ -559,12 +512,12 @@ async function editWorld(path: string, name: string, removeIcon: boolean) {
}
async function deleteWorld(world: SingleplayerWorld) {
await delete_world(instance.value.path, world.path).catch(handleError)
await delete_world(instance.value.id, world.path).catch(handleError)
worlds.value = worlds.value.filter((w) => w.type !== 'singleplayer' || w.path !== world.path)
}
function handleJoinError(err: Error) {
handleSevereError(err, { profilePath: instance.value.path })
handleSevereError(err, { instanceId: instance.value.id })
startingInstance.value = false
worldPlaying.value = undefined
}
@@ -574,7 +527,7 @@ async function joinWorld(world: World) {
startingInstance.value = true
worldPlaying.value = world
if (world.type === 'server') {
const managedProjectId = instance.value.linked_data?.project_id
const managedProjectId = instance.value.link?.project_id
if (managedProjectId && isManagedServerWorld(world)) {
await playServerProject(managedProjectId).catch(handleJoinError)
trackEvent('InstanceStart', {
@@ -585,14 +538,14 @@ async function joinWorld(world: World) {
startingInstance.value = false
return
}
await start_join_server(instance.value.path, world.address).catch(handleJoinError)
await start_join_server(instance.value.id, world.address).catch(handleJoinError)
trackEvent('InstanceStart', {
loader: instance.value.loader,
game_version: instance.value.game_version,
source: 'WorldsPage',
})
} else if (world.type === 'singleplayer') {
await start_join_singleplayer_world(instance.value.path, world.path).catch(handleJoinError)
await start_join_singleplayer_world(instance.value.id, world.path).catch(handleJoinError)
}
play(world)
startingInstance.value = false
@@ -607,7 +560,7 @@ watch(
setTimeout(async () => {
for (const world of worlds.value) {
if (world.type === 'singleplayer' && world.locked) {
await refreshWorld(worlds.value, instance.value.path, world.path)
await refreshWorld(worlds.value, instance.value.id, world.path)
}
}
}, 1000)
@@ -744,37 +697,22 @@ const filteredWorlds = computed(() =>
const highlightedWorld = ref(route.query.highlight)
function promptToRemoveWorld(world: World): boolean {
worldToRemove.value = world
removeWorldModal.value?.show()
return !!removeWorldModal.value
}
async function proceedRemoveWorld(world: World) {
if (world.type === 'server') {
serverToRemove.value = world
removeServerModal.value?.show()
return !!removeServerModal.value
await removeServer(world)
} else {
worldToDelete.value = world
deleteWorldModal.value?.show()
return !!deleteWorldModal.value
await deleteWorld(world)
}
}
async function proceedRemoveServer() {
if (!serverToRemove.value) {
handleError(new Error(`Error removing server, no server marked for removal.`))
return
}
await removeServer(serverToRemove.value)
serverToRemove.value = undefined
}
async function proceedDeleteWorld() {
if (!worldToDelete.value) {
handleError(new Error(`Error deleting world, no world marked for removal.`))
return
}
await deleteWorld(worldToDelete.value)
worldToDelete.value = undefined
worldToRemove.value = null
}
onBeforeUnmount(() => {
worldsTabAlive = false
unlistenProfile?.()
unlistenInstance?.()
})
</script>
@@ -12,6 +12,6 @@ defineProps({
<GridDisplay
v-if="instances && instances.length > 0"
label="Instances"
:instances="instances.filter((i) => !i.linked_data)"
:instances="instances.filter((i) => !i.link)"
/>
</template>
@@ -12,6 +12,6 @@ defineProps({
<GridDisplay
v-if="instances && instances.length > 0"
label="Instances"
:instances="instances.filter((i) => i.linked_data)"
:instances="instances.filter((i) => i.link)"
/>
</template>
@@ -5,8 +5,8 @@ import { inject, onUnmounted, ref, shallowRef } from 'vue'
import { useRoute } from 'vue-router'
import { NewInstanceImage } from '@/assets/icons'
import { profile_listener } from '@/helpers/events.js'
import { list } from '@/helpers/profile.js'
import { instance_listener } from '@/helpers/events.js'
import { list } from '@/helpers/instance'
import { useBreadcrumbs } from '@/store/breadcrumbs.js'
const { handleError } = injectNotificationManager()
@@ -26,11 +26,11 @@ window.addEventListener('online', () => {
offline.value = false
})
const unlistenProfile = await profile_listener(async () => {
const unlistenInstance = await instance_listener(async () => {
instances.value = await list().catch(handleError)
})
onUnmounted(() => {
unlistenProfile()
unlistenInstance()
})
</script>
@@ -13,11 +13,11 @@ const props = defineProps({
const serverProjectIds = ref(new Set())
const linkedInstances = computed(() => props.instances.filter((i) => i.linked_data))
const linkedInstances = computed(() => props.instances.filter((i) => i.link))
watchEffect(async () => {
const projectIds = [
...new Set(linkedInstances.value.map((i) => i.linked_data?.project_id).filter(Boolean)),
...new Set(linkedInstances.value.map((i) => i.link?.project_id).filter(Boolean)),
]
if (projectIds.length === 0) {
serverProjectIds.value = new Set()
@@ -35,7 +35,7 @@ watchEffect(async () => {
})
const filteredInstances = computed(() =>
linkedInstances.value.filter((i) => !serverProjectIds.value.has(i.linked_data?.project_id)),
linkedInstances.value.filter((i) => !serverProjectIds.value.has(i.link?.project_id)),
)
</script>
<template>
@@ -13,11 +13,11 @@ const props = defineProps({
const serverProjectIds = ref(new Set())
const linkedInstances = computed(() => props.instances.filter((i) => i.linked_data))
const linkedInstances = computed(() => props.instances.filter((i) => i.link))
watchEffect(async () => {
const projectIds = [
...new Set(linkedInstances.value.map((i) => i.linked_data?.project_id).filter(Boolean)),
...new Set(linkedInstances.value.map((i) => i.link?.project_id).filter(Boolean)),
]
if (projectIds.length === 0) {
serverProjectIds.value = new Set()
@@ -35,7 +35,7 @@ watchEffect(async () => {
})
const filteredInstances = computed(() =>
linkedInstances.value.filter((i) => serverProjectIds.value.has(i.linked_data?.project_id)),
linkedInstances.value.filter((i) => serverProjectIds.value.has(i.link?.project_id)),
)
</script>
<template>
+9 -10
View File
@@ -304,21 +304,20 @@ import {
get_version_many,
} from '@/helpers/cache.js'
import { process_listener } from '@/helpers/events'
import { get_loader_versions as getLoaderManifest } from '@/helpers/metadata'
import { get_by_profile_path } from '@/helpers/process'
import {
get as getInstance,
get_projects as getInstanceProjects,
kill,
list as listInstances,
} from '@/helpers/profile'
} from '@/helpers/instance'
import { get_loader_versions as getLoaderManifest } from '@/helpers/metadata'
import { get_by_instance_id } from '@/helpers/process'
import { get_categories, get_game_versions, get_loaders } from '@/helpers/tags'
import { getServerLatency } from '@/helpers/worlds'
import { getServerAddress, getServerLatency } from '@/helpers/worlds'
import { injectContentInstall } from '@/providers/content-install'
import { injectServerInstall } from '@/providers/server-install'
import { createServerInstallContent } from '@/providers/setup/server-install-content'
import { useBreadcrumbs } from '@/store/breadcrumbs'
import { getServerAddress } from '@/store/install.js'
import { useTheming } from '@/store/state.js'
dayjs.extend(relativeTime)
@@ -529,10 +528,10 @@ async function handleClickPlay() {
async function updateServerPlayState() {
if (!isServerProject.value || !data.value) return
const packs = await listInstances()
const inst = packs.find((p) => p.linked_data?.project_id === data.value.id)
const inst = packs.find((p) => p.link?.project_id === data.value.id)
if (inst) {
serverInstancePath.value = inst.path
const processes = await get_by_profile_path(inst.path).catch(() => [])
serverInstancePath.value = inst.id
const processes = await get_by_instance_id(inst.id).catch(() => [])
serverPlaying.value = Array.isArray(processes) && processes.length > 0
} else {
serverInstancePath.value = null
@@ -662,7 +661,7 @@ process_listener((e) => {
if (
e.event === 'finished' &&
serverInstancePath.value &&
e.profile_path_id === serverInstancePath.value
e.instance_id === serverInstancePath.value
) {
serverPlaying.value = false
}
@@ -737,7 +736,7 @@ async function install(version) {
await installVersion(
data.value.id,
version,
instance.value ? instance.value.path : null,
instance.value ? instance.value.id : null,
'ProjectPage',
(version, installedProjectIds) => {
installing.value = false
+334 -151
View File
@@ -11,38 +11,56 @@ import { trackEvent } from '@/helpers/analytics'
import {
get_organization,
get_project,
get_project_v3_many,
get_project_many,
get_team,
get_version_many,
} from '@/helpers/cache.js'
import { create_profile_and_install as packInstall } from '@/helpers/pack'
import { instance_listener } from '@/helpers/events.js'
import {
install_create_instance,
install_create_modpack_instance,
installJobInstanceId,
} from '@/helpers/install'
import {
add_project_from_version,
check_installed_batch,
create,
get,
get_install_candidates,
get_projects,
install_project_with_dependencies,
list,
remove_project,
} from '@/helpers/profile.js'
type ResolveContentPlan,
} from '@/helpers/instance'
import { get_game_versions } from '@/helpers/tags'
import type { GameInstance, InstanceLoader } from '@/helpers/types'
import {
findPreferredVersion,
installVersionDependencies,
isVersionCompatible,
} from '@/store/install.js'
import { useTheming } from '@/store/state'
interface ModalRef {
show: (initialVersionId?: string) => void
hide: () => void
}
interface ModpackAlreadyInstalledModalRef {
show: (instanceName: string, instancePath: string) => void
show: (instanceName: string, instanceId: string) => void
}
export type ContentInstallCallback = (versionId?: string, installedProjectIds?: string[]) => void
type InstallingProjectDisplay = {
id?: string
slug?: string | null
title?: string
name?: string
icon_url?: string | null
project_type?: string
type?: string
organization?: string | null
team?: string
}
type ContentInstallInstanceEvent = {
event: string
instance_id: string
project_ids?: string[]
message?: string
}
const LOADER_ORDER = ['vanilla', 'fabric', 'quilt', 'neoforge', 'forge']
const SUPPORTED_LOADERS: Set<string> = new Set(['vanilla', 'forge', 'fabric', 'quilt', 'neoforge'])
@@ -53,6 +71,48 @@ const noCompatibleVersionsMessage = defineMessage({
'No available versions match {compatibilityLabel}. Select a version to install anyway. Dependencies will not be installed automatically.',
})
const RESOLVABLE_PROJECT_TYPES = new Set<Labrinth.Content.v3.ContentType>([
'mod',
'plugin',
'datapack',
'resourcepack',
'shader',
'modpack',
])
function resolveContentType(projectType?: Labrinth.Projects.v2.ProjectType) {
return projectType && RESOLVABLE_PROJECT_TYPES.has(projectType) ? projectType : 'mod'
}
function isVersionCompatible(
version: Labrinth.Versions.v2.Version,
project: Labrinth.Projects.v2.Project,
instance: GameInstance,
) {
return (
version.game_versions.includes(instance.game_version) &&
(project.project_type === 'mod'
? version.loaders.includes(instance.loader) || version.loaders.includes('datapack')
: true)
)
}
function findPreferredVersion(
versions: Labrinth.Versions.v2.Version[],
project: Labrinth.Projects.v2.Project,
instance: GameInstance,
) {
const projectType = project.project_type ?? 'mod'
return (
versions.find(
(v) =>
v.game_versions.includes(instance.game_version) &&
(projectType === 'mod' ? v.loaders.includes(instance.loader) : true),
) ?? versions.find((v) => isVersionCompatible(v, project, instance))
)
}
function sortLoaders(loaders: string[]): string[] {
return loaders.slice().sort((a, b) => {
const aIdx = LOADER_ORDER.indexOf(a)
@@ -64,6 +124,11 @@ function sortLoaders(loaders: string[]): string[] {
})
}
type InstallTargetInstance = Pick<
GameInstance,
'id' | 'name' | 'icon_path' | 'game_version' | 'loader'
>
export interface ContentInstallContext {
instances: Ref<ContentInstallInstance[]>
compatibleLoaders: Ref<string[]>
@@ -87,7 +152,7 @@ export interface ContentInstallContext {
setContentInstallModal: (ref: ModalRef) => void
setModpackAlreadyInstalledModal: (ref: ModpackAlreadyInstalledModalRef) => void
handleModpackDuplicateCreateAnyway: () => Promise<void>
handleModpackDuplicateGoToInstance: (instancePath: string) => void
handleModpackDuplicateGoToInstance: (instanceId: string) => void
setIncompatibilityWarningModal: (ref: ModalRef) => void
incompatibilityWarningVersions: Ref<Labrinth.Versions.v2.Version[]>
incompatibilityWarningCurrentGameVersion: Ref<string>
@@ -102,13 +167,15 @@ export interface ContentInstallContext {
install: (
projectId: string,
versionId?: string | null,
instancePath?: string | null,
instanceId?: string | null,
source?: string,
callback?: ContentInstallCallback,
createInstanceCallback?: (profile: string) => void,
createInstanceCallback?: (instanceId: string) => void,
hints?: { preferredLoader?: string; preferredGameVersion?: string; showProjectInfo?: boolean },
) => Promise<void>
installingItems: Ref<Map<string, ContentItem[]>>
installRevisionByInstance: Ref<Map<string, number>>
installFailureRevisionByInstance: Ref<Map<string, number>>
}
export const [injectContentInstall, provideContentInstall] = createContext<ContentInstallContext>(
@@ -121,6 +188,7 @@ export function createContentInstall(opts: {
handleError: (err: unknown) => void
}): ContentInstallContext {
const { formatMessage } = useVIntl()
const themeStore = useTheming()
const instances = ref<ContentInstallInstance[]>([])
const compatibleLoaders = ref<string[]>([])
const gameVersions = ref<string[]>([])
@@ -132,6 +200,8 @@ export function createContentInstall(opts: {
const projectInfo = ref<ContentInstallProjectInfo | null>(null)
const installingItems = ref<Map<string, ContentItem[]>>(new Map())
const installRevisionByInstance = ref<Map<string, number>>(new Map())
const installFailureRevisionByInstance = ref<Map<string, number>>(new Map())
const incompatibilityWarningVersions = ref<Labrinth.Versions.v2.Version[]>([])
const incompatibilityWarningCurrentGameVersion = ref('')
const incompatibilityWarningCurrentLoader = ref('')
@@ -142,7 +212,7 @@ export function createContentInstall(opts: {
const incompatibilityWarningInstalling = ref(false)
function addInstallingItem(
instancePath: string,
instanceId: string,
project: {
id: string
slug?: string | null
@@ -178,15 +248,15 @@ export function createContentInstall(opts: {
installing: true,
}
const next = new Map(installingItems.value)
const items = next.get(instancePath) ?? []
const items = next.get(instanceId) ?? []
if (items.some((i) => i.file_name === placeholder.file_name)) return
next.set(instancePath, [...items, placeholder])
next.set(instanceId, [...items, placeholder])
installingItems.value = next
if (project.organization) {
get_organization(project.organization)
.then((org: { id: string; slug: string; name: string; icon_url?: string }) => {
updateInstallingItem(instancePath, placeholder.file_name, {
updateInstallingItem(instanceId, placeholder.file_name, {
owner: {
id: org.id,
name: org.name,
@@ -207,7 +277,7 @@ export function createContentInstall(opts: {
) => {
const owner = members.find((m) => m.is_owner)
if (owner) {
updateInstallingItem(instancePath, placeholder.file_name, {
updateInstallingItem(instanceId, placeholder.file_name, {
owner: {
id: owner.user.id,
name: owner.user.username,
@@ -223,44 +293,122 @@ export function createContentInstall(opts: {
}
function updateInstallingItem(
instancePath: string,
instanceId: string,
fileName: string,
updates: Partial<ContentItem>,
) {
const next = new Map(installingItems.value)
const items = next.get(instancePath)
const items = next.get(instanceId)
if (!items) return
const index = items.findIndex((i) => i.file_name === fileName)
if (index === -1) return
const updated = [...items]
updated[index] = { ...updated[index], ...updates }
next.set(instancePath, updated)
next.set(instanceId, updated)
installingItems.value = next
}
function removeInstallingItems(instancePath: string, projectIds: string[]) {
function removeInstallingItems(instanceId: string, projectIds: string[]) {
const next = new Map(installingItems.value)
const items = next.get(instancePath)
const items = next.get(instanceId)
if (items) {
const idsToRemove = new Set(projectIds.map((id) => `__installing_${id}`))
const filtered = items.filter((i) => !idsToRemove.has(i.file_name))
if (filtered.length > 0) {
next.set(instancePath, filtered)
next.set(instanceId, filtered)
} else {
next.delete(instancePath)
next.delete(instanceId)
}
installingItems.value = next
}
}
function resolvedProjectIds(plan: ResolveContentPlan) {
return [
plan.primary.project_id,
...plan.dependencies.map((dependency) => dependency.project_id),
]
}
async function addInstallingItemsForPlan(
instanceId: string,
plan: ResolveContentPlan,
primaryProject: Labrinth.Projects.v2.Project,
primaryVersion: Labrinth.Versions.v2.Version,
) {
const entries = [plan.primary, ...plan.dependencies]
const projectIds = [...new Set(entries.map((entry) => entry.project_id))]
const versionIds = [...new Set(entries.map((entry) => entry.version_id))]
const projectMap = new Map<string, InstallingProjectDisplay>([
[primaryProject.id, primaryProject],
])
const versionMap = new Map<string, Labrinth.Versions.v2.Version>([
[primaryVersion.id, primaryVersion],
])
const [projects, versions] = await Promise.all([
get_project_many(projectIds, 'bypass').catch(() => []),
get_version_many(versionIds, 'bypass').catch(() => []),
])
for (const project of projects as InstallingProjectDisplay[]) {
if (project?.id) projectMap.set(project.id, project)
}
for (const version of versions as Labrinth.Versions.v2.Version[]) {
if (version?.id) versionMap.set(version.id, version)
}
for (const entry of entries) {
const project = projectMap.get(entry.project_id)
const version = versionMap.get(entry.version_id)
addInstallingItem(
instanceId,
{
id: entry.project_id,
slug: project?.slug ?? entry.project_id,
title: project?.title ?? project?.name ?? entry.project_id,
icon_url: project?.icon_url ?? null,
project_type: project?.project_type ?? project?.type ?? primaryProject.project_type,
organization: project?.organization ?? null,
team: project?.team,
},
version,
)
}
}
function markInstanceContentChanged(instanceId: string) {
const next = new Map(installRevisionByInstance.value)
next.set(instanceId, (next.get(instanceId) ?? 0) + 1)
installRevisionByInstance.value = next
}
function markInstanceContentInstallFailed(instanceId: string) {
const next = new Map(installFailureRevisionByInstance.value)
next.set(instanceId, (next.get(instanceId) ?? 0) + 1)
installFailureRevisionByInstance.value = next
}
void instance_listener((event: ContentInstallInstanceEvent) => {
if (event.event === 'content_install_finished') {
markInstanceContentChanged(event.instance_id)
removeInstallingItems(event.instance_id, event.project_ids ?? [])
} else if (event.event === 'content_install_failed') {
removeInstallingItems(event.instance_id, event.project_ids ?? [])
markInstanceContentInstallFailed(event.instance_id)
markInstanceContentChanged(event.instance_id)
opts.handleError(event.message ?? 'Failed to install content')
}
}).catch(opts.handleError)
let modalRef: ModalRef | null = null
let modpackAlreadyInstalledModalRef: ModpackAlreadyInstalledModalRef | null = null
let incompatibilityWarningModalRef: ModalRef | null = null
let currentProject: Labrinth.Projects.v2.Project | null = null
let currentVersions: Labrinth.Versions.v2.Version[] = []
let currentCallback: ContentInstallCallback = () => {}
let profileMap: Record<string, GameInstance> = {}
let incompatibilityWarningInstance: GameInstance | null = null
let instanceMap: Record<string, InstallTargetInstance> = {}
let incompatibilityWarningInstance: InstallTargetInstance | null = null
let incompatibilityWarningProject: Labrinth.Projects.v2.Project | null = null
let incompatibilityWarningCallback: ContentInstallCallback = () => {}
let incompatibilityWarningInstalled = false
@@ -270,7 +418,7 @@ export function createContentInstall(opts: {
version: string
source: string
callback: ContentInstallCallback
createInstanceCallback: (profile: string) => void
createInstanceCallback: (instanceId: string) => void
} | null = null
async function showModInstallModal(
@@ -284,6 +432,7 @@ export function createContentInstall(opts: {
currentCallback = onInstall
instances.value = []
loading.value = true
defaultTab.value = 'existing'
if (hints?.showProjectInfo) {
@@ -350,9 +499,22 @@ export function createContentInstall(opts: {
else if (VANILLA_COMPATIBLE_LOADERS.has(l)) mappedLoaders.add('vanilla')
}
compatibleLoaders.value = sortLoaders([...mappedLoaders])
gameVersions.value = [...gameVersionSet]
releaseGameVersions.value = new Set(gameVersionSet)
try {
const allGameVersions = await get_game_versions()
preferredLoader.value =
hints?.preferredLoader && loaderSet.has(hints.preferredLoader) ? hints.preferredLoader : null
preferredGameVersion.value =
hints?.preferredGameVersion && gameVersionSet.has(hints.preferredGameVersion)
? hints.preferredGameVersion
: null
await nextTick()
modalRef?.show()
trackEvent('ProjectInstallStart', { source: 'ProjectInstallModal' })
get_game_versions()
.then((allGameVersions) => {
const releases = new Set<string>()
const ordered: string[] = []
for (const gv of allGameVersions) {
@@ -365,54 +527,29 @@ export function createContentInstall(opts: {
}
gameVersions.value = ordered
releaseGameVersions.value = releases
} catch {
gameVersions.value = [...gameVersionSet]
releaseGameVersions.value = new Set(gameVersionSet)
}
preferredLoader.value =
hints?.preferredLoader && loaderSet.has(hints.preferredLoader) ? hints.preferredLoader : null
preferredGameVersion.value =
hints?.preferredGameVersion && gameVersionSet.has(hints.preferredGameVersion)
? hints.preferredGameVersion
: null
})
.catch(() => {})
try {
let profiles = await list()
const linkedProjectIds = profiles
.filter((p) => p.linked_data?.project_id)
.map((p) => p.linked_data!.project_id)
if (linkedProjectIds.length > 0) {
const linkedProjects = await get_project_v3_many(linkedProjectIds, 'must_revalidate').catch(
() => [],
const candidates = await get_install_candidates(
project.id,
project.project_type,
getInstallTargets(versions),
)
const serverProjectIds = new Set(
linkedProjects
.filter((p: { id: string; minecraft_server?: unknown }) => p?.minecraft_server != null)
.map((p: { id: string }) => p.id),
)
profiles = profiles.filter(
(p) => !p.linked_data?.project_id || !serverProjectIds.has(p.linked_data.project_id),
)
}
const newProfileMap: Record<string, GameInstance> = {}
const installedMap = await check_installed_batch(project.id)
const newInstances: ContentInstallInstance[] = profiles.map((profile) => {
newProfileMap[profile.path] = profile
const newInstanceMap: Record<string, InstallTargetInstance> = {}
const newInstances: ContentInstallInstance[] = candidates.map((instance) => {
newInstanceMap[instance.id] = instance
return {
id: profile.path,
name: profile.name,
iconUrl: profile.icon_path ? convertFileSrc(profile.icon_path) : null,
installed: installedMap[profile.path] ?? false,
compatible: versions.some((v) => isVersionCompatible(v, project, profile)),
id: instance.id,
name: instance.name,
iconUrl: instance.icon_path ? convertFileSrc(instance.icon_path) : null,
installed: instance.installed,
compatible: instance.compatible,
installing: false,
}
})
profileMap = newProfileMap
instanceMap = newInstanceMap
instances.value = newInstances
if (!newInstances.some((i) => i.compatible && !i.installed)) {
@@ -420,22 +557,38 @@ export function createContentInstall(opts: {
}
} catch (err) {
opts.handleError(err)
} finally {
loading.value = false
}
}
await nextTick()
modalRef?.show()
trackEvent('ProjectInstallStart', { source: 'ProjectInstallModal' })
function getInstallTargets(versions: Labrinth.Versions.v2.Version[]) {
const targets: { game_version: string; loader: string }[] = []
const seen = new Set<string>()
for (const version of versions) {
for (const gameVersion of version.game_versions) {
for (const loader of version.loaders) {
const key = `${gameVersion}\0${loader}`
if (seen.has(key)) continue
seen.add(key)
targets.push({ game_version: gameVersion, loader })
}
}
}
return targets
}
async function handleInstallToInstance(instance: ContentInstallInstance) {
const profile = profileMap[instance.id]
const selectedInstance = instanceMap[instance.id]
const storeInstance = instances.value.find((i) => i.id === instance.id)
if (!currentProject || !profile) {
if (!currentProject || !selectedInstance) {
opts.handleError('No project or instance found')
return
}
const version = findPreferredVersion(currentVersions, currentProject, profile)
const version = findPreferredVersion(currentVersions, currentProject, selectedInstance)
if (!version) {
if (currentVersions.length > 0 && incompatibilityWarningModalRef) {
const onIncompatibleInstall = (versionId?: string) => {
@@ -445,7 +598,7 @@ export function createContentInstall(opts: {
currentCallback(versionId, versionId && currentProject ? [currentProject.id] : undefined)
}
await showIncompatibilityWarning(
profile,
selectedInstance,
currentProject,
currentVersions,
currentVersions[0],
@@ -459,30 +612,32 @@ export function createContentInstall(opts: {
if (storeInstance) storeInstance.installing = true
const installedProjectIds: string[] = []
if (currentProject) {
const installedProjectIds: string[] = [currentProject.id]
let plannedProjectIds: string[] = [currentProject.id]
addInstallingItem(instance.id, currentProject, version)
installedProjectIds.push(currentProject.id)
}
try {
await add_project_from_version(instance.id, version.id, 'standalone')
await installVersionDependencies(
profile,
version,
'dependency',
(depProject: Labrinth.Projects.v2.Project, depVersion?: Labrinth.Versions.v2.Version) => {
addInstallingItem(instance.id, depProject, depVersion)
installedProjectIds.push(depProject.id)
},
const request = {
project_id: currentProject.id,
version_id: version.id,
content_type: resolveContentType(currentProject.project_type),
}
const plan = await install_project_with_dependencies(instance.id, request)
plannedProjectIds = resolvedProjectIds(plan)
await addInstallingItemsForPlan(instance.id, plan, currentProject, version)
installedProjectIds.splice(
0,
installedProjectIds.length,
plan.primary.project_id,
...plan.dependencies.map((dependency) => dependency.project_id),
)
if (storeInstance) {
storeInstance.installed = true
storeInstance.installing = false
}
trackEvent('ProjectInstall', {
loader: profile.loader,
game_version: profile.game_version,
loader: selectedInstance.loader,
game_version: selectedInstance.game_version,
id: currentProject!.id,
version_id: version.id,
project_type: currentProject!.project_type,
@@ -492,14 +647,14 @@ export function createContentInstall(opts: {
currentCallback(version.id, installedProjectIds)
} catch (err) {
if (storeInstance) storeInstance.installing = false
removeInstallingItems(instance.id, plannedProjectIds)
markInstanceContentInstallFailed(instance.id)
opts.handleError(err)
} finally {
removeInstallingItems(instance.id, installedProjectIds)
}
}
async function showIncompatibilityWarning(
instance: GameInstance,
instance: InstallTargetInstance,
project: Labrinth.Projects.v2.Project,
versions: Labrinth.Versions.v2.Version[],
version: Labrinth.Versions.v2.Version,
@@ -534,18 +689,23 @@ export function createContentInstall(opts: {
if (!incompatibilityWarningInstance || !incompatibilityWarningProject) return
incompatibilityWarningInstalling.value = true
addInstallingItem(incompatibilityWarningInstance.id, incompatibilityWarningProject, version)
try {
await add_project_from_version(incompatibilityWarningInstance.path, version.id, 'standalone')
await add_project_from_version(incompatibilityWarningInstance.id, version.id, 'standalone')
} catch (err) {
opts.handleError(err)
incompatibilityWarningInstalling.value = false
removeInstallingItems(incompatibilityWarningInstance.id, [incompatibilityWarningProject.id])
markInstanceContentInstallFailed(incompatibilityWarningInstance.id)
return
}
incompatibilityWarningInstalling.value = false
incompatibilityWarningInstalled = true
incompatibilityWarningCallback(version.id, [incompatibilityWarningProject.id])
markInstanceContentChanged(incompatibilityWarningInstance.id)
incompatibilityWarningModalRef?.hide()
removeInstallingItems(incompatibilityWarningInstance.id, [incompatibilityWarningProject.id])
trackEvent('ProjectInstall', {
loader: incompatibilityWarningInstance.loader,
@@ -581,23 +741,28 @@ export function createContentInstall(opts: {
loaderCandidates.some((l) => v.loaders.includes(l)),
) ?? currentVersions[0]
let createdInstanceId: string | null = null
try {
const id = await create(
data.name,
data.gameVersion,
data.loader as InstanceLoader,
'latest',
data.iconPath,
false,
)
const job = await install_create_instance({
name: data.name,
gameVersion: data.gameVersion,
loader: data.loader as InstanceLoader,
loaderVersion: 'latest',
iconPath: data.iconPath,
})
const id = installJobInstanceId(job)
if (!id) return
createdInstanceId = id
addInstallingItem(id, currentProject!, version)
await add_project_from_version(id, version.id, 'standalone')
const plan = await install_project_with_dependencies(id, {
project_id: currentProject!.id,
version_id: version.id,
content_type: resolveContentType(currentProject!.project_type),
})
await addInstallingItemsForPlan(id, plan, currentProject!, version)
await opts.router.push(`/instance/${encodeURIComponent(id)}`)
const instance = await get(id)
await installVersionDependencies(instance, version, 'dependency')
trackEvent('InstanceCreate', {
source: 'ProjectInstallModal',
})
@@ -611,9 +776,13 @@ export function createContentInstall(opts: {
source: 'ProjectInstallModal',
})
currentCallback(version.id)
currentCallback(version.id, resolvedProjectIds(plan))
modalRef?.hide()
} catch (err) {
if (createdInstanceId && currentProject) {
removeInstallingItems(createdInstanceId, [currentProject.id])
markInstanceContentInstallFailed(createdInstanceId)
}
opts.handleError(err)
}
}
@@ -630,10 +799,10 @@ export function createContentInstall(opts: {
async function install(
projectId: string,
versionId?: string | null,
instancePath?: string | null,
instanceId?: string | null,
source: string = 'unknown',
callback: ContentInstallCallback = () => {},
createInstanceCallback: (profile: string) => void = () => {},
createInstanceCallback: (instanceId: string) => void = () => {},
hints?: { preferredLoader?: string; preferredGameVersion?: string; showProjectInfo?: boolean },
) {
const project: Labrinth.Projects.v2.Project = await get_project(projectId, 'must_revalidate')
@@ -641,21 +810,25 @@ export function createContentInstall(opts: {
if (project.project_type === 'modpack') {
const version = versionId ?? project.versions[project.versions.length - 1]
const packs = await list()
const existingPack = packs.find((pack) => pack.linked_data?.project_id === project.id)
const existingPack = packs.find((pack) => pack.link?.project_id === project.id)
if (existingPack) {
if (existingPack && !themeStore.getFeatureFlag('skip_non_essential_warnings')) {
pendingModpackInstall = { project, version, source, callback, createInstanceCallback }
modpackAlreadyInstalledModalRef?.show(existingPack.name, existingPack.path)
modpackAlreadyInstalledModalRef?.show(existingPack.name, existingPack.id)
return
}
await packInstall(
project.id,
version,
project.title,
project.icon_url,
createInstanceCallback,
)
const job = await install_create_modpack_instance({
type: 'fromVersionId',
project_id: project.id,
version_id: version,
title: project.title,
icon_url: project.icon_url,
})
const instanceId = installJobInstanceId(job)
if (instanceId) {
createInstanceCallback(instanceId)
}
trackEvent('PackInstall', {
id: project.id,
version_id: version,
@@ -663,10 +836,10 @@ export function createContentInstall(opts: {
source,
})
callback(version)
} else if (instancePath) {
} else if (instanceId) {
const [instanceOrNull, instanceProjects, versions] = await Promise.all([
get(instancePath),
get_projects(instancePath),
get(instanceId),
get_projects(instanceId),
get_version_many(project.versions, 'must_revalidate') as Promise<
Labrinth.Versions.v2.Version[]
>,
@@ -686,25 +859,27 @@ export function createContentInstall(opts: {
if (isVersionCompatible(version, project, instance)) {
for (const [path, file] of Object.entries(instanceProjects)) {
if (file.metadata?.project_id === project.id) {
await remove_project(instance.path, path)
await remove_project(instance.id, path)
}
}
const installedProjectIds: string[] = [project.id]
addInstallingItem(instancePath, project, version)
let plannedProjectIds: string[] = [project.id]
addInstallingItem(instanceId, project, version)
try {
await add_project_from_version(instance.path, version.id, 'standalone')
await installVersionDependencies(
instance,
version,
'dependency',
(
depProject: Labrinth.Projects.v2.Project,
depVersion?: Labrinth.Versions.v2.Version,
) => {
addInstallingItem(instancePath, depProject, depVersion)
installedProjectIds.push(depProject.id)
},
const request = {
project_id: project.id,
version_id: version.id,
content_type: resolveContentType(project.project_type),
}
const plan = await install_project_with_dependencies(instance.id, request)
plannedProjectIds = resolvedProjectIds(plan)
await addInstallingItemsForPlan(instanceId, plan, project, version)
installedProjectIds.splice(
0,
installedProjectIds.length,
plan.primary.project_id,
...plan.dependencies.map((dependency) => dependency.project_id),
)
trackEvent('ProjectInstall', {
@@ -717,8 +892,10 @@ export function createContentInstall(opts: {
source,
})
callback(version.id, installedProjectIds)
} finally {
removeInstallingItems(instancePath, installedProjectIds)
} catch (err) {
removeInstallingItems(instanceId, plannedProjectIds)
markInstanceContentInstallFailed(instanceId)
throw err
}
} else {
await showIncompatibilityWarning(instance, project, projectVersions, version, callback)
@@ -756,13 +933,17 @@ export function createContentInstall(opts: {
if (!pendingModpackInstall) return
const { project, version, source, callback, createInstanceCallback } = pendingModpackInstall
pendingModpackInstall = null
await packInstall(
project.id,
version,
project.title,
project.icon_url,
createInstanceCallback,
)
const job = await install_create_modpack_instance({
type: 'fromVersionId',
project_id: project.id,
version_id: version,
title: project.title,
icon_url: project.icon_url,
})
const instanceId = installJobInstanceId(job)
if (instanceId) {
createInstanceCallback(instanceId)
}
trackEvent('PackInstall', {
id: project.id,
version_id: version,
@@ -771,9 +952,9 @@ export function createContentInstall(opts: {
})
callback(version)
},
handleModpackDuplicateGoToInstance(instancePath: string) {
handleModpackDuplicateGoToInstance(instanceId: string) {
pendingModpackInstall = null
opts.router.push(`/instance/${encodeURIComponent(instancePath)}`)
opts.router.push(`/instance/${encodeURIComponent(instanceId)}`)
},
setIncompatibilityWarningModal(ref: ModalRef) {
incompatibilityWarningModalRef = ref
@@ -790,5 +971,7 @@ export function createContentInstall(opts: {
handleIncompatibilityWarningCancel,
install,
installingItems,
installRevisionByInstance,
installFailureRevisionByInstance,
}
}

Some files were not shown because too many files have changed in this diff Show More