Initial commit: file-browser-picker Paseo plugin
This commit is contained in:
commit
069e1d2082
15 files changed
+5599
No files matched your search
@@ -0,0 +1,4 @@
|
||||
node_modules/
|
||||
dist/
|
||||
*.tsbuildinfo
|
||||
.DS_Store
|
||||
+26
@@ -0,0 +1,26 @@
|
||||
Open a project in Paseo using your operating system's native file browser instead of Paseo's built-in folder dialog, with an automatic host folder browser fallback on headless servers.
|
||||
|
||||
Selecting **Open from file browser** from the sidebar or running **Open project from file browser** in the Command Center opens a native folder selection window on desktop Paseo hosts. Once you choose a directory, Paseo registers it as a project and opens a workspace there. On headless hosts without an active desktop session (such as remote Linux servers or Kubernetes pods), the screen automatically opens a host folder browser so you can navigate directories and open projects directly.
|
||||
|
||||
## Requirements
|
||||
|
||||
- Paseo `>=0.16.1`
|
||||
- For native OS dialogs on Linux or FreeBSD, one of the following on an active desktop session:
|
||||
- `python3` with PyGObject (`gi`) and a running `xdg-desktop-portal`
|
||||
- `kdialog`, `zenity`, or `yad`
|
||||
- On macOS, uses `osascript` (Finder folder dialog, built in).
|
||||
- On Windows, uses PowerShell `FolderBrowserDialog` (built in).
|
||||
- On headless hosts, no external tools are required; the plugin falls back to browsing directories through the daemon host.
|
||||
|
||||
## Settings
|
||||
|
||||
Host-scoped settings are available under **Settings -> Plugins -> File browser picker**:
|
||||
|
||||
- **Picker program**: Choose `auto` (detects a native picker on the host) or force a specific backend (`portal`, `kdialog`, `zenity`, `yad`, `osascript`, `powershell`, or `custom`).
|
||||
- **Start folder**: Initial directory shown when the file browser opens (defaults to the host user's home directory).
|
||||
- **Dialog title**: Title shown in the native folder picker window.
|
||||
- **Custom command**: Shell command used when **Picker program** is set to `custom`. `{dir}` is replaced with the start folder, and the command must print the chosen directory path to stdout.
|
||||
|
||||
## Permissions and limits
|
||||
|
||||
Folder discovery and native pickers run on the machine hosting the selected Paseo daemon, so they browse that host's filesystem.
|
||||
@@ -0,0 +1,390 @@
|
||||
import type { PluginScreenProps } from "@getpaseo/plugin/client";
|
||||
import { useRpc } from "@getpaseo/plugin/client";
|
||||
import { Icon, ScrollView, TextInput } from "@getpaseo/plugin/client/ui";
|
||||
import { useMutation, useQuery } from "@tanstack/react-query";
|
||||
import { useEffect, useMemo, useRef, useState } from "react";
|
||||
import { Pressable, Text, View } from "react-native";
|
||||
import { detectRpc, listDirRpc, openFolderRpc, pickAndOpenRpc } from "../shared/picker";
|
||||
|
||||
export function PickerScreen({ theme, layout, host, params, navigation }: PluginScreenProps) {
|
||||
const pickAndOpen = useRpc(pickAndOpenRpc);
|
||||
const openFolder = useRpc(openFolderRpc);
|
||||
const detect = useRpc(detectRpc);
|
||||
const listDir = useRpc(listDirRpc);
|
||||
|
||||
const [browserOpen, setBrowserOpen] = useState(false);
|
||||
const [currentPath, setCurrentPath] = useState<string | undefined>(undefined);
|
||||
const [showHidden, setShowHidden] = useState(false);
|
||||
const [filter, setFilter] = useState("");
|
||||
const lastTrigger = useRef<string | null>(null);
|
||||
|
||||
const detection = useQuery({
|
||||
queryKey: ["picker-detect", host.id],
|
||||
queryFn: () => detect({}),
|
||||
});
|
||||
|
||||
const pick = useMutation({
|
||||
mutationFn: () => pickAndOpen({}),
|
||||
});
|
||||
|
||||
const openDirect = useMutation({
|
||||
mutationFn: (path: string) => openFolder({ path }),
|
||||
});
|
||||
|
||||
const hasGuiPicker = Boolean(detection.data?.effectivePicker);
|
||||
const showBrowser = browserOpen || (detection.isSuccess && !hasGuiPicker);
|
||||
|
||||
const directory = useQuery({
|
||||
queryKey: ["picker-list-dir", host.id, currentPath ?? "__default__", showHidden],
|
||||
queryFn: () => listDir({ path: currentPath, showHidden }),
|
||||
enabled: showBrowser,
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
setBrowserOpen(false);
|
||||
setCurrentPath(undefined);
|
||||
setFilter("");
|
||||
lastTrigger.current = null;
|
||||
}, [host.id]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!detection.isSuccess || !hasGuiPicker) return;
|
||||
if (params.autostart !== "1") return;
|
||||
const triggerKey = `${host.id}:${params.trigger ?? "__mount__"}`;
|
||||
if (lastTrigger.current === triggerKey) return;
|
||||
lastTrigger.current = triggerKey;
|
||||
if (!pick.isPending) {
|
||||
pick.mutate();
|
||||
}
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [detection.isSuccess, hasGuiPicker, host.id, params.autostart, params.trigger]);
|
||||
|
||||
const openResult = openDirect.data ?? pick.data;
|
||||
const openingPending = pick.isPending || openDirect.isPending;
|
||||
const openError = openDirect.error ?? pick.error;
|
||||
|
||||
useEffect(() => {
|
||||
if (openResult?.status === "opened") {
|
||||
navigation?.openWorkspace({ workspaceId: openResult.workspaceId });
|
||||
}
|
||||
}, [openResult, navigation]);
|
||||
|
||||
const filteredEntries = useMemo(() => {
|
||||
if (directory.data?.status !== "ok") return [];
|
||||
const needle = filter.trim().toLowerCase();
|
||||
if (!needle) return directory.data.entries;
|
||||
return directory.data.entries.filter((entry) => entry.name.toLowerCase().includes(needle));
|
||||
}, [directory.data, filter]);
|
||||
|
||||
const styles = useMemo(
|
||||
() => ({
|
||||
screen: { flex: 1, backgroundColor: theme.colors.surface0 },
|
||||
body: { padding: layout.compact ? 16 : 24, gap: 12 },
|
||||
row: { flexDirection: "row" as const, flexWrap: "wrap" as const, alignItems: "center" as const, gap: 8 },
|
||||
between: {
|
||||
flexDirection: "row" as const,
|
||||
alignItems: "center" as const,
|
||||
justifyContent: "space-between" as const,
|
||||
gap: 8,
|
||||
},
|
||||
heading: { color: theme.colors.foreground, fontSize: 18, fontWeight: "600" as const },
|
||||
text: { color: theme.colors.foreground, fontSize: 14 },
|
||||
mono: { color: theme.colors.foregroundMuted, fontSize: 12 },
|
||||
muted: { color: theme.colors.foregroundMuted, fontSize: 13 },
|
||||
error: { color: theme.colors.statusDanger, fontSize: 14 },
|
||||
success: { color: theme.colors.statusSuccess, fontSize: 14 },
|
||||
button: {
|
||||
paddingVertical: 10,
|
||||
paddingHorizontal: 14,
|
||||
borderRadius: 8,
|
||||
backgroundColor: theme.colors.accent,
|
||||
alignSelf: "flex-start" as const,
|
||||
opacity: openingPending ? 0.6 : 1,
|
||||
},
|
||||
buttonText: { color: theme.colors.accentForeground, fontSize: 14, fontWeight: "600" as const },
|
||||
secondaryButton: {
|
||||
paddingVertical: 8,
|
||||
paddingHorizontal: 12,
|
||||
borderRadius: 8,
|
||||
borderWidth: 1,
|
||||
borderColor: theme.colors.border,
|
||||
backgroundColor: theme.colors.surface1,
|
||||
alignSelf: "flex-start" as const,
|
||||
},
|
||||
secondaryButtonText: { color: theme.colors.foreground, fontSize: 13 },
|
||||
card: {
|
||||
borderWidth: 1,
|
||||
borderColor: theme.colors.border,
|
||||
borderRadius: 8,
|
||||
padding: 12,
|
||||
gap: 8,
|
||||
backgroundColor: theme.colors.surface1,
|
||||
},
|
||||
input: {
|
||||
borderWidth: 1,
|
||||
borderColor: theme.colors.border,
|
||||
borderRadius: 8,
|
||||
paddingHorizontal: 10,
|
||||
paddingVertical: 8,
|
||||
color: theme.colors.foreground,
|
||||
backgroundColor: theme.colors.surface0,
|
||||
fontSize: 14,
|
||||
},
|
||||
folderRow: {
|
||||
flexDirection: "row" as const,
|
||||
alignItems: "center" as const,
|
||||
justifyContent: "space-between" as const,
|
||||
gap: 8,
|
||||
paddingVertical: 8,
|
||||
paddingHorizontal: 10,
|
||||
borderRadius: 6,
|
||||
borderWidth: 1,
|
||||
borderColor: theme.colors.border,
|
||||
backgroundColor: theme.colors.surface0,
|
||||
},
|
||||
folderMain: {
|
||||
flex: 1,
|
||||
flexDirection: "row" as const,
|
||||
alignItems: "center" as const,
|
||||
gap: 8,
|
||||
},
|
||||
gitBadge: {
|
||||
color: theme.colors.foregroundMuted,
|
||||
fontSize: 11,
|
||||
paddingHorizontal: 6,
|
||||
paddingVertical: 2,
|
||||
borderRadius: 4,
|
||||
borderWidth: 1,
|
||||
borderColor: theme.colors.border,
|
||||
},
|
||||
}),
|
||||
[theme, layout.compact, openingPending],
|
||||
);
|
||||
|
||||
function navigateTo(nextPath: string) {
|
||||
setFilter("");
|
||||
setCurrentPath(nextPath);
|
||||
}
|
||||
|
||||
return (
|
||||
<ScrollView style={styles.screen} contentContainerStyle={styles.body}>
|
||||
<Text style={styles.heading}>Open a project from {host.label}</Text>
|
||||
|
||||
{detection.isLoading ? (
|
||||
<Text style={styles.muted}>Checking available file browsers on {host.label}…</Text>
|
||||
) : null}
|
||||
|
||||
{hasGuiPicker ? (
|
||||
<>
|
||||
<Text style={styles.text}>
|
||||
Pick a folder in the file browser on {host.label}. Paseo adds it as a project and opens a
|
||||
workspace there, without showing the built-in project dialog.
|
||||
</Text>
|
||||
<View style={styles.row}>
|
||||
<Pressable
|
||||
accessibilityRole="button"
|
||||
accessibilityLabel="Choose a folder in the file browser"
|
||||
style={styles.button}
|
||||
disabled={openingPending}
|
||||
onPress={() => pick.mutate()}
|
||||
>
|
||||
<Text style={styles.buttonText}>
|
||||
{pick.isPending ? "File browser is open…" : "Choose folder in file browser"}
|
||||
</Text>
|
||||
</Pressable>
|
||||
<Pressable
|
||||
accessibilityRole="button"
|
||||
accessibilityLabel="Toggle host folder browser"
|
||||
style={styles.secondaryButton}
|
||||
onPress={() => setBrowserOpen((value) => !value)}
|
||||
>
|
||||
<Text style={styles.secondaryButtonText}>
|
||||
{browserOpen ? "Hide folder browser" : "Browse host folders here"}
|
||||
</Text>
|
||||
</Pressable>
|
||||
</View>
|
||||
</>
|
||||
) : detection.isSuccess ? (
|
||||
<Text style={styles.muted}>
|
||||
{host.label} is headless (no desktop file dialog is available). Browse folders on{" "}
|
||||
{host.label} below and open one as a Paseo project.
|
||||
</Text>
|
||||
) : null}
|
||||
|
||||
{pick.isPending ? (
|
||||
<Text style={styles.muted}>Choose a folder in the file browser window on {host.label}.</Text>
|
||||
) : null}
|
||||
|
||||
{openResult?.status === "cancelled" ? (
|
||||
<Text style={styles.muted}>Cancelled. Nothing was opened.</Text>
|
||||
) : null}
|
||||
|
||||
{openResult?.status === "error" ? <Text style={styles.error}>{openResult.message}</Text> : null}
|
||||
{openError ? (
|
||||
<Text style={styles.error}>
|
||||
{openError instanceof Error ? openError.message : "Failed to open the selected folder."}
|
||||
</Text>
|
||||
) : null}
|
||||
|
||||
{openResult?.status === "opened" ? (
|
||||
<View style={styles.card}>
|
||||
<Text style={styles.success}>Opened {openResult.name}</Text>
|
||||
<Text style={styles.muted}>{openResult.path}</Text>
|
||||
{navigation ? (
|
||||
<Pressable
|
||||
accessibilityRole="button"
|
||||
accessibilityLabel="Go to the new workspace"
|
||||
style={styles.secondaryButton}
|
||||
onPress={() => navigation.openWorkspace({ workspaceId: openResult.workspaceId })}
|
||||
>
|
||||
<Text style={styles.secondaryButtonText}>Go to workspace</Text>
|
||||
</Pressable>
|
||||
) : (
|
||||
<Text style={styles.muted}>Find the new workspace in the sidebar.</Text>
|
||||
)}
|
||||
</View>
|
||||
) : null}
|
||||
|
||||
{showBrowser ? (
|
||||
<View style={styles.card}>
|
||||
<View style={styles.between}>
|
||||
<Text style={styles.text} numberOfLines={1}>
|
||||
{directory.data?.status === "ok"
|
||||
? directory.data.path
|
||||
: currentPath ?? detection.data?.defaultStartDir ?? "~"}
|
||||
</Text>
|
||||
{directory.data?.status === "ok" ? (
|
||||
<Pressable
|
||||
accessibilityRole="button"
|
||||
accessibilityLabel="Open current folder"
|
||||
style={styles.button}
|
||||
disabled={openingPending}
|
||||
onPress={() => {
|
||||
if (directory.data?.status === "ok") {
|
||||
openDirect.mutate(directory.data.path);
|
||||
}
|
||||
}}
|
||||
>
|
||||
<Text style={styles.buttonText}>
|
||||
{openDirect.isPending ? "Opening…" : "Open this folder"}
|
||||
</Text>
|
||||
</Pressable>
|
||||
) : null}
|
||||
</View>
|
||||
|
||||
<View style={styles.row}>
|
||||
<Pressable
|
||||
accessibilityRole="button"
|
||||
accessibilityLabel="Go to parent folder"
|
||||
style={styles.secondaryButton}
|
||||
disabled={directory.data?.status !== "ok" || !directory.data.parent}
|
||||
onPress={() => {
|
||||
if (directory.data?.status === "ok" && directory.data.parent) {
|
||||
navigateTo(directory.data.parent);
|
||||
}
|
||||
}}
|
||||
>
|
||||
<Text style={styles.secondaryButtonText}>Up</Text>
|
||||
</Pressable>
|
||||
<Pressable
|
||||
accessibilityRole="button"
|
||||
accessibilityLabel="Go to home folder"
|
||||
style={styles.secondaryButton}
|
||||
disabled={directory.data?.status !== "ok"}
|
||||
onPress={() => {
|
||||
if (directory.data?.status === "ok") {
|
||||
navigateTo(directory.data.home);
|
||||
}
|
||||
}}
|
||||
>
|
||||
<Text style={styles.secondaryButtonText}>Home</Text>
|
||||
</Pressable>
|
||||
<Pressable
|
||||
accessibilityRole="button"
|
||||
accessibilityLabel="Toggle hidden folders"
|
||||
style={styles.secondaryButton}
|
||||
onPress={() => setShowHidden((value) => !value)}
|
||||
>
|
||||
<Text style={styles.secondaryButtonText}>
|
||||
{showHidden ? "Hide dotfiles" : "Show dotfiles"}
|
||||
</Text>
|
||||
</Pressable>
|
||||
<Pressable
|
||||
accessibilityRole="button"
|
||||
accessibilityLabel="Refresh folder list"
|
||||
style={styles.secondaryButton}
|
||||
onPress={() => void directory.refetch()}
|
||||
>
|
||||
<Text style={styles.secondaryButtonText}>Refresh</Text>
|
||||
</Pressable>
|
||||
</View>
|
||||
|
||||
<TextInput
|
||||
value={filter}
|
||||
onChangeText={setFilter}
|
||||
placeholder="Filter folders in this directory…"
|
||||
placeholderTextColor={theme.colors.foregroundMuted}
|
||||
style={styles.input}
|
||||
/>
|
||||
|
||||
{directory.isLoading ? <Text style={styles.muted}>Reading folders…</Text> : null}
|
||||
{directory.data?.status === "error" ? (
|
||||
<Text style={styles.error}>{directory.data.message}</Text>
|
||||
) : null}
|
||||
|
||||
{directory.data?.status === "ok" && filteredEntries.length === 0 ? (
|
||||
<Text style={styles.muted}>No subfolders match here.</Text>
|
||||
) : null}
|
||||
|
||||
{filteredEntries.map((entry) => (
|
||||
<View key={entry.path} style={styles.folderRow}>
|
||||
<Pressable
|
||||
accessibilityRole="button"
|
||||
accessibilityLabel={`Browse ${entry.name}`}
|
||||
style={styles.folderMain}
|
||||
onPress={() => navigateTo(entry.path)}
|
||||
>
|
||||
<Icon
|
||||
name={entry.isGitRepo ? "FolderGit2" : "Folder"}
|
||||
size={16}
|
||||
color={entry.isGitRepo ? theme.colors.accent : theme.colors.foregroundMuted}
|
||||
/>
|
||||
<Text style={styles.text} numberOfLines={1}>
|
||||
{entry.name}
|
||||
</Text>
|
||||
{entry.isGitRepo ? <Text style={styles.gitBadge}>git</Text> : null}
|
||||
</Pressable>
|
||||
<Pressable
|
||||
accessibilityRole="button"
|
||||
accessibilityLabel={`Open ${entry.name}`}
|
||||
style={styles.secondaryButton}
|
||||
disabled={openingPending}
|
||||
onPress={() => openDirect.mutate(entry.path)}
|
||||
>
|
||||
<Text style={styles.secondaryButtonText}>Open</Text>
|
||||
</Pressable>
|
||||
</View>
|
||||
))}
|
||||
</View>
|
||||
) : null}
|
||||
|
||||
{detection.data ? (
|
||||
<View style={styles.card}>
|
||||
<Text style={styles.mono}>
|
||||
Host: {detection.data.platform}
|
||||
{detection.data.desktop ? ` · ${detection.data.desktop}` : ""}
|
||||
{detection.data.effectivePicker
|
||||
? ` · picker: ${detection.data.effectivePicker}`
|
||||
: " · headless host browser"}
|
||||
</Text>
|
||||
{detection.data.pickers.map((picker) => (
|
||||
<Text key={picker.id} style={styles.mono}>
|
||||
{picker.available ? "•" : "○"} {picker.label}: {picker.detail}
|
||||
</Text>
|
||||
))}
|
||||
<Text style={styles.mono}>Change the picker or the start folder in plugin settings.</Text>
|
||||
</View>
|
||||
) : null}
|
||||
</ScrollView>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,180 @@
|
||||
import type { PluginSurfaceProps } from "@getpaseo/plugin/client";
|
||||
import { useSettings } from "@getpaseo/plugin/client";
|
||||
import {
|
||||
ScrollView,
|
||||
SettingsAction,
|
||||
SettingsCard,
|
||||
SettingsInput,
|
||||
SettingsRow,
|
||||
SettingsSection,
|
||||
SettingsSelect,
|
||||
} from "@getpaseo/plugin/client/ui";
|
||||
import { useEffect, useMemo, useState } from "react";
|
||||
import { Text, View } from "react-native";
|
||||
import { defaultPickerSettings, pickerSettings, type PickerSettings } from "../shared/settings";
|
||||
|
||||
const PICKER_OPTIONS: readonly { label: string; value: PickerSettings["picker"] }[] = [
|
||||
{ label: "Automatic (host default)", value: "auto" },
|
||||
{ label: "Desktop portal (Linux XDG)", value: "portal" },
|
||||
{ label: "KDE dialog (kdialog)", value: "kdialog" },
|
||||
{ label: "GTK dialog (zenity)", value: "zenity" },
|
||||
{ label: "GTK dialog (yad)", value: "yad" },
|
||||
{ label: "macOS Finder (osascript)", value: "osascript" },
|
||||
{ label: "Windows FolderBrowserDialog", value: "powershell" },
|
||||
{ label: "Custom command", value: "custom" },
|
||||
];
|
||||
|
||||
export function PickerSettingsScreen({ theme, layout, host }: PluginSurfaceProps) {
|
||||
const settings = useSettings(pickerSettings);
|
||||
const [draft, setDraft] = useState<PickerSettings>(defaultPickerSettings);
|
||||
const [statusMessage, setStatusMessage] = useState<string | null>(null);
|
||||
|
||||
const readyRevision = settings.status === "ready" ? settings.revision : null;
|
||||
const readyValues = settings.status === "ready" ? settings.values : null;
|
||||
|
||||
useEffect(() => {
|
||||
if (readyValues) {
|
||||
setDraft(readyValues);
|
||||
}
|
||||
}, [readyRevision, readyValues]);
|
||||
|
||||
const styles = useMemo(
|
||||
() => ({
|
||||
screen: { flex: 1, backgroundColor: theme.colors.surface0 },
|
||||
body: { padding: layout.compact ? 16 : 24, gap: 16 },
|
||||
text: { color: theme.colors.foreground, fontSize: 14 },
|
||||
muted: { color: theme.colors.foregroundMuted, fontSize: 13 },
|
||||
error: { color: theme.colors.statusDanger, fontSize: 13 },
|
||||
success: { color: theme.colors.statusSuccess, fontSize: 13 },
|
||||
}),
|
||||
[theme, layout.compact],
|
||||
);
|
||||
|
||||
if (settings.status === "loading") {
|
||||
return (
|
||||
<View style={[styles.screen, styles.body]}>
|
||||
<Text style={styles.muted}>Loading picker settings for {host.label}…</Text>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
if (settings.status === "error") {
|
||||
return (
|
||||
<View style={[styles.screen, styles.body]}>
|
||||
<Text style={styles.error}>Could not load settings: {settings.error}</Text>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
const isInvalid = settings.status === "invalid";
|
||||
const revision = settings.revision;
|
||||
const isDirty =
|
||||
settings.status === "ready" &&
|
||||
(draft.picker !== settings.values.picker ||
|
||||
draft.startDir !== settings.values.startDir ||
|
||||
draft.prompt !== settings.values.prompt ||
|
||||
draft.customCommand !== settings.values.customCommand);
|
||||
|
||||
async function saveDraft(next: PickerSettings) {
|
||||
setStatusMessage(null);
|
||||
const ok = await settings.save(next, revision);
|
||||
if (ok) {
|
||||
setStatusMessage("Saved.");
|
||||
}
|
||||
}
|
||||
|
||||
async function handleReset() {
|
||||
setStatusMessage(null);
|
||||
const ok = await settings.reset();
|
||||
if (ok) {
|
||||
setDraft(defaultPickerSettings);
|
||||
setStatusMessage("Reset to defaults.");
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<ScrollView style={styles.screen} contentContainerStyle={styles.body}>
|
||||
<SettingsSection
|
||||
title="File browser picker"
|
||||
info={<Text style={styles.muted}>Host settings for {host.label}.</Text>}
|
||||
>
|
||||
{isInvalid ? (
|
||||
<SettingsCard>
|
||||
<SettingsRow label="Invalid saved settings" error={settings.error} />
|
||||
</SettingsCard>
|
||||
) : null}
|
||||
|
||||
<SettingsCard key={revision}>
|
||||
<SettingsSelect
|
||||
label="Picker program"
|
||||
hint="Automatic uses your desktop's native folder dialog."
|
||||
value={draft.picker}
|
||||
disabled={settings.saving}
|
||||
options={PICKER_OPTIONS}
|
||||
onValueChange={(picker) => {
|
||||
const next = { ...draft, picker };
|
||||
setDraft(next);
|
||||
void saveDraft(next);
|
||||
}}
|
||||
/>
|
||||
|
||||
<SettingsInput
|
||||
label="Start folder"
|
||||
hint="Folder the file browser opens in. Leave blank for the host home folder."
|
||||
initialValue={draft.startDir}
|
||||
placeholder="~"
|
||||
disabled={settings.saving}
|
||||
onChangeText={(startDir) => {
|
||||
setStatusMessage(null);
|
||||
setDraft((prev) => ({ ...prev, startDir }));
|
||||
}}
|
||||
/>
|
||||
|
||||
<SettingsInput
|
||||
label="Dialog title"
|
||||
hint="Title shown in the OS folder picker window."
|
||||
initialValue={draft.prompt}
|
||||
placeholder={defaultPickerSettings.prompt}
|
||||
disabled={settings.saving}
|
||||
onChangeText={(prompt) => {
|
||||
setStatusMessage(null);
|
||||
setDraft((prev) => ({ ...prev, prompt }));
|
||||
}}
|
||||
/>
|
||||
|
||||
<SettingsInput
|
||||
label="Custom command"
|
||||
hint="Used when Picker program is Custom command. Print the selected folder path to stdout; {dir} expands to the start folder."
|
||||
initialValue={draft.customCommand}
|
||||
placeholder='kdialog --getexistingdirectory "{dir}"'
|
||||
disabled={settings.saving}
|
||||
onChangeText={(customCommand) => {
|
||||
setStatusMessage(null);
|
||||
setDraft((prev) => ({ ...prev, customCommand }));
|
||||
}}
|
||||
/>
|
||||
</SettingsCard>
|
||||
|
||||
<SettingsCard>
|
||||
<SettingsAction
|
||||
label="Save text changes"
|
||||
hint={isDirty ? "You have unsaved changes." : "Applies start folder, dialog title, and custom command."}
|
||||
actionLabel={settings.saving ? "Saving…" : "Save"}
|
||||
disabled={settings.saving || (!isDirty && !isInvalid)}
|
||||
onPress={() => void saveDraft(draft)}
|
||||
/>
|
||||
<SettingsAction
|
||||
label="Reset settings"
|
||||
hint="Restore default picker settings on this host."
|
||||
actionLabel="Reset"
|
||||
disabled={settings.saving}
|
||||
onPress={() => void handleReset()}
|
||||
/>
|
||||
</SettingsCard>
|
||||
|
||||
{settings.saveError ? <Text style={styles.error}>{settings.saveError}</Text> : null}
|
||||
{statusMessage ? <Text style={styles.success}>{statusMessage}</Text> : null}
|
||||
</SettingsSection>
|
||||
</ScrollView>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="m6 14 1.5-2.9A2 2 0 0 1 9.24 10H20a2 2 0 0 1 1.94 2.5l-1.54 6a2 2 0 0 1-1.95 1.5H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h3.9a2 2 0 0 1 1.69.9l.81 1.2a2 2 0 0 0 1.67.9H18a2 2 0 0 1 2 2v2"/></svg>
|
||||
|
After Width: | Height: | Size: 354 B |
@@ -0,0 +1,56 @@
|
||||
import type { PluginClientContext, PluginSidebarItemProps } from "@getpaseo/plugin/client";
|
||||
import { SidebarRow } from "@getpaseo/plugin/client/ui";
|
||||
import { PickerScreen } from "./client/picker-screen";
|
||||
import { PickerSettingsScreen } from "./client/settings-screen";
|
||||
|
||||
function PickerSidebarItem({ currentScreen, openScreen }: PluginSidebarItemProps) {
|
||||
return (
|
||||
<SidebarRow
|
||||
icon="FolderOpen"
|
||||
active={currentScreen?.screenId === "picker"}
|
||||
onPress={() =>
|
||||
openScreen({
|
||||
screenId: "picker",
|
||||
params: { autostart: "1", trigger: String(Date.now()) },
|
||||
})
|
||||
}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
export default function contribute(client: PluginClientContext) {
|
||||
client.addScreen({
|
||||
id: "picker",
|
||||
title: "Open from file browser",
|
||||
Component: PickerScreen,
|
||||
});
|
||||
|
||||
client.addSidebarHeaderItem({
|
||||
id: "open-project",
|
||||
title: "Open from file browser",
|
||||
Component: PickerSidebarItem,
|
||||
});
|
||||
|
||||
client.addCommandCenterItem({
|
||||
id: "open-project-file-browser",
|
||||
title: "Open project from file browser",
|
||||
icon: "FolderOpen",
|
||||
keywords: ["folder", "directory", "browse", "project", "open"],
|
||||
context: "global",
|
||||
onSelect({ openScreen }) {
|
||||
openScreen({
|
||||
screenId: "picker",
|
||||
params: { autostart: "1", trigger: String(Date.now()) },
|
||||
});
|
||||
},
|
||||
});
|
||||
|
||||
client.addSettingsScreen({
|
||||
id: "picker",
|
||||
title: "File browser picker",
|
||||
icon: "FolderOpen",
|
||||
Component: PickerSettingsScreen,
|
||||
});
|
||||
|
||||
return () => {};
|
||||
}
|
||||
+107
@@ -0,0 +1,107 @@
|
||||
/// <reference types="node" />
|
||||
import type { PluginHandlerContext, PluginServerContext } from "@getpaseo/plugin/server";
|
||||
import { stat } from "node:fs/promises";
|
||||
import { basename } from "node:path";
|
||||
import {
|
||||
detectPickers,
|
||||
listDirectory,
|
||||
pickFolder,
|
||||
resolvePicker,
|
||||
resolveStartDir,
|
||||
} from "./server/pick-folder";
|
||||
import {
|
||||
detectRpc,
|
||||
listDirRpc,
|
||||
openFolderRpc,
|
||||
pickAndOpenRpc,
|
||||
pickRpc,
|
||||
} from "./shared/picker";
|
||||
import { defaultPickerSettings, pickerSettings } from "./shared/settings";
|
||||
|
||||
async function openWorkspaceFolder(
|
||||
paseo: PluginHandlerContext["paseo"],
|
||||
folderPath: string,
|
||||
picker: string,
|
||||
) {
|
||||
const info = await stat(folderPath).catch(() => null);
|
||||
if (!info?.isDirectory()) {
|
||||
return { status: "error" as const, message: `Not a folder on this host: ${folderPath}` };
|
||||
}
|
||||
|
||||
try {
|
||||
const workspace = await paseo.workspaces.open({ cwd: folderPath });
|
||||
return {
|
||||
status: "opened" as const,
|
||||
path: folderPath,
|
||||
name: workspace.name ?? basename(folderPath),
|
||||
workspaceId: workspace.id,
|
||||
projectId: workspace.projectId,
|
||||
picker,
|
||||
};
|
||||
} catch (error) {
|
||||
return {
|
||||
status: "error" as const,
|
||||
message: `Paseo could not open ${folderPath}: ${error instanceof Error ? error.message : String(error)}`,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
export default function contribute(server: PluginServerContext) {
|
||||
const settings = server.registerSettings(pickerSettings);
|
||||
let pickInFlight = false;
|
||||
|
||||
async function readSettings() {
|
||||
const state = await settings.read();
|
||||
return state.status === "ready" ? state.values : defaultPickerSettings;
|
||||
}
|
||||
|
||||
async function pick(initialDir?: string) {
|
||||
if (pickInFlight) {
|
||||
return { status: "error" as const, message: "A folder picker is already open on this host." };
|
||||
}
|
||||
pickInFlight = true;
|
||||
try {
|
||||
return await pickFolder(await readSettings(), initialDir);
|
||||
} finally {
|
||||
pickInFlight = false;
|
||||
}
|
||||
}
|
||||
|
||||
server.handle(detectRpc, async () => {
|
||||
const current = await readSettings();
|
||||
const detected = detectPickers();
|
||||
const resolved = resolvePicker(current, detected);
|
||||
return {
|
||||
...detected,
|
||||
effectivePicker: typeof resolved === "string" ? resolved : null,
|
||||
defaultStartDir: resolveStartDir(current.startDir),
|
||||
};
|
||||
});
|
||||
|
||||
server.handle(pickRpc, async ({ initialDir }) => {
|
||||
const result = await pick(initialDir);
|
||||
if (result.status !== "picked") return result;
|
||||
const info = await stat(result.path).catch(() => null);
|
||||
if (!info?.isDirectory()) {
|
||||
return { status: "error" as const, message: `Not a folder on this host: ${result.path}` };
|
||||
}
|
||||
return result;
|
||||
});
|
||||
|
||||
server.handle(pickAndOpenRpc, async ({ initialDir }, { paseo }) => {
|
||||
const result = await pick(initialDir);
|
||||
if (result.status === "cancelled" || result.status === "error") return result;
|
||||
return openWorkspaceFolder(paseo, result.path, result.picker);
|
||||
});
|
||||
|
||||
server.handle(listDirRpc, async ({ path, showHidden }) => {
|
||||
const current = await readSettings();
|
||||
return listDirectory(path ?? resolveStartDir(current.startDir), showHidden ?? false);
|
||||
});
|
||||
|
||||
server.handle(openFolderRpc, async ({ path }, { paseo }) => {
|
||||
return openWorkspaceFolder(paseo, path, "browser");
|
||||
});
|
||||
|
||||
return () => {};
|
||||
}
|
||||
Generated
+4148
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,30 @@
|
||||
{
|
||||
"name": "file-browser-picker",
|
||||
"private": true,
|
||||
"version": "0.0.0",
|
||||
"files": [
|
||||
"paseo-plugin.json",
|
||||
"OVERVIEW.md",
|
||||
"OVERVIEW.*.md",
|
||||
"index.client.ts",
|
||||
"index.client.tsx",
|
||||
"index.server.ts",
|
||||
"index.server.tsx",
|
||||
"client/",
|
||||
"server/",
|
||||
"shared/"
|
||||
],
|
||||
"scripts": {
|
||||
"typecheck": "tsc --noEmit"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@getpaseo/plugin": "0.16.2",
|
||||
"@tanstack/react-query": "^5.90.11",
|
||||
"@types/node": "^20.19.43",
|
||||
"@types/react": "~19.2.0",
|
||||
"react": "19.1.0",
|
||||
"react-native": "0.81.5",
|
||||
"typescript": "^5.9.3",
|
||||
"zod": "^4.4.3"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
{
|
||||
"id": "file-browser-picker",
|
||||
"name": "Open from file browser",
|
||||
"media": [],
|
||||
"requirements": {
|
||||
"paseo": ">=0.16.1"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,398 @@
|
||||
/// <reference types="node" />
|
||||
import { execFile, execFileSync } from "node:child_process";
|
||||
import { accessSync, constants, existsSync } from "node:fs";
|
||||
import { access, readdir, stat } from "node:fs/promises";
|
||||
import { homedir } from "node:os";
|
||||
import { delimiter, dirname, join, resolve } from "node:path";
|
||||
import { promisify } from "node:util";
|
||||
import type { PickerSettings } from "../shared/settings";
|
||||
import { PORTAL_PICK_SCRIPT } from "./portal-script";
|
||||
|
||||
const exec = promisify(execFile);
|
||||
|
||||
// Five minutes is enough for a person to browse to a folder. The picker is
|
||||
// a window on the host, so nothing shorter is safe.
|
||||
const PICK_TIMEOUT_MS = 5 * 60 * 1000;
|
||||
|
||||
export type PickResult =
|
||||
| { status: "picked"; path: string; picker: string }
|
||||
| { status: "cancelled"; picker: string }
|
||||
| { status: "error"; message: string };
|
||||
|
||||
export interface PickerInfo {
|
||||
id: string;
|
||||
label: string;
|
||||
available: boolean;
|
||||
detail: string;
|
||||
}
|
||||
|
||||
export interface DetectResult {
|
||||
platform: string;
|
||||
desktop: string | null;
|
||||
pickers: PickerInfo[];
|
||||
recommended: string | null;
|
||||
}
|
||||
|
||||
function onPath(command: string): string | null {
|
||||
if (command.includes("/")) {
|
||||
try {
|
||||
accessSync(command, constants.X_OK);
|
||||
return command;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
for (const dir of (process.env.PATH ?? "").split(delimiter)) {
|
||||
if (!dir) continue;
|
||||
const candidate = join(dir, command);
|
||||
try {
|
||||
accessSync(candidate, constants.X_OK);
|
||||
return candidate;
|
||||
} catch {
|
||||
// Keep searching the PATH.
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
// The plugin process inherits the daemon's environment, which normally
|
||||
// carries the desktop session. When the session bus address is missing,
|
||||
// fall back to the standard runtime socket so portal and KDE dialogs
|
||||
// still reach the running desktop.
|
||||
function buildEnv(): NodeJS.ProcessEnv {
|
||||
const env: NodeJS.ProcessEnv = { ...process.env };
|
||||
if (!env.DBUS_SESSION_BUS_ADDRESS) {
|
||||
const runtimeDir = env.XDG_RUNTIME_DIR ?? `/run/user/${process.getuid?.() ?? ""}`;
|
||||
const bus = join(runtimeDir, "bus");
|
||||
if (existsSync(bus)) env.DBUS_SESSION_BUS_ADDRESS = `unix:path=${bus}`;
|
||||
}
|
||||
return env;
|
||||
}
|
||||
|
||||
export function detectPickers(): DetectResult {
|
||||
const env = buildEnv();
|
||||
const platform = process.platform;
|
||||
const desktop = env.XDG_CURRENT_DESKTOP ?? null;
|
||||
const pickers: PickerInfo[] = [];
|
||||
|
||||
if (platform === "linux" || platform === "freebsd") {
|
||||
const hasDisplay = Boolean(env.DISPLAY || env.WAYLAND_DISPLAY);
|
||||
for (const [id, label] of [
|
||||
["kdialog", "KDE file dialog (kdialog)"],
|
||||
["zenity", "GTK file dialog (zenity)"],
|
||||
["yad", "GTK file dialog (yad)"],
|
||||
] as const) {
|
||||
const found = onPath(id);
|
||||
const available = found !== null && hasDisplay;
|
||||
pickers.push({
|
||||
id,
|
||||
label,
|
||||
available,
|
||||
detail: !found
|
||||
? `Install ${id} on the host to use it.`
|
||||
: !hasDisplay
|
||||
? `${found} is installed, but no desktop display session is active.`
|
||||
: found,
|
||||
});
|
||||
}
|
||||
const python = onPath("python3");
|
||||
const portalReady =
|
||||
python !== null && Boolean(env.DBUS_SESSION_BUS_ADDRESS) && hasPortalSession(python, env);
|
||||
pickers.push({
|
||||
id: "portal",
|
||||
label: "Desktop portal file browser",
|
||||
available: portalReady,
|
||||
detail: portalReady
|
||||
? "Uses the XDG portal through python3 and PyGObject."
|
||||
: "Needs python3 with PyGObject and an active XDG desktop portal session.",
|
||||
});
|
||||
} else if (platform === "darwin") {
|
||||
pickers.push({
|
||||
id: "osascript",
|
||||
label: "macOS Finder folder dialog",
|
||||
available: onPath("osascript") !== null,
|
||||
detail: "Built into macOS.",
|
||||
});
|
||||
} else if (platform === "win32") {
|
||||
pickers.push({
|
||||
id: "powershell",
|
||||
label: "Windows folder dialog",
|
||||
available: onPath("powershell.exe") !== null || onPath("powershell") !== null,
|
||||
detail: "Uses Windows PowerShell and FolderBrowserDialog.",
|
||||
});
|
||||
}
|
||||
pickers.push({
|
||||
id: "custom",
|
||||
label: "Custom command",
|
||||
available: true,
|
||||
detail: "Any command that prints the chosen folder to stdout.",
|
||||
});
|
||||
|
||||
const recommended = pickers.find((picker) => picker.available && picker.id !== "custom");
|
||||
return { platform, desktop, pickers, recommended: recommended?.id ?? null };
|
||||
}
|
||||
|
||||
export function resolvePicker(settings: PickerSettings, detected: DetectResult): string | { error: string } {
|
||||
if (settings.picker === "custom") {
|
||||
if (!settings.customCommand.trim()) {
|
||||
return { error: "The picker is set to a custom command, but no command is saved in settings." };
|
||||
}
|
||||
return "custom";
|
||||
}
|
||||
if (settings.picker !== "auto") {
|
||||
const info = detected.pickers.find((picker) => picker.id === settings.picker);
|
||||
if (!info?.available) {
|
||||
return {
|
||||
error: `The ${settings.picker} picker is not available on this host. ${info?.detail ?? ""}`.trim(),
|
||||
};
|
||||
}
|
||||
return settings.picker;
|
||||
}
|
||||
if (!detected.recommended) {
|
||||
return {
|
||||
error:
|
||||
"No file browser picker was found on this host. Install kdialog (KDE) or zenity (GNOME), or python3 with PyGObject for the desktop portal, then try again.",
|
||||
};
|
||||
}
|
||||
return detected.recommended;
|
||||
}
|
||||
|
||||
let cachedPortalSession: boolean | null = null;
|
||||
|
||||
function hasPortalSession(pythonPath: string, env: NodeJS.ProcessEnv): boolean {
|
||||
if (cachedPortalSession !== null) return cachedPortalSession;
|
||||
try {
|
||||
execFileSync(
|
||||
pythonPath,
|
||||
[
|
||||
"-c",
|
||||
"from gi.repository import Gio, GLib; bus = Gio.bus_get_sync(Gio.BusType.SESSION, None); res = bus.call_sync('org.freedesktop.DBus', '/org/freedesktop/DBus', 'org.freedesktop.DBus', 'NameHasOwner', GLib.Variant('(s)', ('org.freedesktop.portal.Desktop',)), GLib.VariantType('(b)'), Gio.DBusCallFlags.NONE, 1000, None); exit(0 if res.unpack()[0] else 1)",
|
||||
],
|
||||
{
|
||||
env,
|
||||
timeout: 2000,
|
||||
stdio: "ignore",
|
||||
},
|
||||
);
|
||||
cachedPortalSession = true;
|
||||
} catch {
|
||||
cachedPortalSession = false;
|
||||
}
|
||||
return cachedPortalSession;
|
||||
}
|
||||
|
||||
interface RunResult {
|
||||
stdout: string;
|
||||
stderr: string;
|
||||
code: number | null;
|
||||
}
|
||||
|
||||
async function run(command: string, args: string[], shell = false): Promise<RunResult> {
|
||||
try {
|
||||
const { stdout, stderr } = await exec(command, args, {
|
||||
env: buildEnv(),
|
||||
timeout: PICK_TIMEOUT_MS,
|
||||
maxBuffer: 1024 * 1024,
|
||||
shell,
|
||||
});
|
||||
return { stdout, stderr, code: 0 };
|
||||
} catch (error) {
|
||||
const failure = error as { code?: number | string; stdout?: string; stderr?: string; message?: string; killed?: boolean };
|
||||
if (failure.killed) {
|
||||
throw new Error("The file browser was open for five minutes without a selection and was closed.");
|
||||
}
|
||||
if (failure.code === "ENOENT") {
|
||||
throw new Error(`Could not run ${command} on this host.`);
|
||||
}
|
||||
return {
|
||||
stdout: failure.stdout ?? "",
|
||||
stderr: failure.stderr ?? "",
|
||||
code: typeof failure.code === "number" ? failure.code : null,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
function firstLine(stdout: string): string {
|
||||
return stdout.split("\n").map((line) => line.trim()).find((line) => line.length > 0) ?? "";
|
||||
}
|
||||
|
||||
export function resolveStartDir(raw?: string): string {
|
||||
const home = homedir();
|
||||
const trimmed = raw?.trim();
|
||||
if (!trimmed) return home;
|
||||
const expanded = trimmed === "~" ? home : trimmed.startsWith("~/") ? join(home, trimmed.slice(2)) : trimmed;
|
||||
return existsSync(expanded) ? resolve(expanded) : home;
|
||||
}
|
||||
|
||||
export type ListDirResult =
|
||||
| {
|
||||
status: "ok";
|
||||
path: string;
|
||||
parent: string | null;
|
||||
home: string;
|
||||
entries: Array<{ name: string; path: string; isGitRepo: boolean }>;
|
||||
}
|
||||
| { status: "error"; message: string };
|
||||
|
||||
export async function listDirectory(rawPath?: string, showHidden = false): Promise<ListDirResult> {
|
||||
const home = homedir();
|
||||
const target = rawPath?.trim()
|
||||
? rawPath.trim() === "~"
|
||||
? home
|
||||
: rawPath.trim().startsWith("~/")
|
||||
? join(home, rawPath.trim().slice(2))
|
||||
: resolve(rawPath.trim())
|
||||
: home;
|
||||
|
||||
try {
|
||||
const info = await stat(target);
|
||||
if (!info.isDirectory()) {
|
||||
return { status: "error", message: `Not a folder on this host: ${target}` };
|
||||
}
|
||||
|
||||
const dirents = await readdir(target, { withFileTypes: true });
|
||||
const dirCandidates: Array<{ name: string; fullPath: string }> = [];
|
||||
|
||||
for (const dirent of dirents) {
|
||||
if (!showHidden && dirent.name.startsWith(".")) continue;
|
||||
const fullPath = join(target, dirent.name);
|
||||
if (dirent.isDirectory()) {
|
||||
dirCandidates.push({ name: dirent.name, fullPath });
|
||||
} else if (dirent.isSymbolicLink()) {
|
||||
const linked = await stat(fullPath).catch(() => null);
|
||||
if (linked?.isDirectory()) {
|
||||
dirCandidates.push({ name: dirent.name, fullPath });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
dirCandidates.sort((a, b) => a.name.localeCompare(b.name, undefined, { sensitivity: "base" }));
|
||||
|
||||
const entries = await Promise.all(
|
||||
dirCandidates.map(async ({ name, fullPath }) => {
|
||||
const isGitRepo = await access(join(fullPath, ".git"))
|
||||
.then(() => true)
|
||||
.catch(() => false);
|
||||
return { name, path: fullPath, isGitRepo };
|
||||
}),
|
||||
);
|
||||
|
||||
const parentDir = dirname(target);
|
||||
return {
|
||||
status: "ok",
|
||||
path: target,
|
||||
parent: parentDir === target ? null : parentDir,
|
||||
home,
|
||||
entries,
|
||||
};
|
||||
} catch (error) {
|
||||
return {
|
||||
status: "error",
|
||||
message: error instanceof Error ? error.message : String(error),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
export async function pickFolder(
|
||||
settings: PickerSettings,
|
||||
initialDir?: string,
|
||||
): Promise<PickResult> {
|
||||
const detected = detectPickers();
|
||||
const picker = resolvePicker(settings, detected);
|
||||
if (typeof picker !== "string") return { status: "error", message: picker.error };
|
||||
|
||||
const prompt = settings.prompt.trim() || "Select project folder";
|
||||
const startDir = resolveStartDir(initialDir?.trim() || settings.startDir);
|
||||
|
||||
try {
|
||||
switch (picker) {
|
||||
case "kdialog": {
|
||||
const result = await run("kdialog", ["--title", prompt, "--getexistingdirectory", startDir]);
|
||||
const path = firstLine(result.stdout);
|
||||
if (path) return { status: "picked", path, picker };
|
||||
return result.code === 1
|
||||
? { status: "cancelled", picker }
|
||||
: { status: "error", message: "kdialog closed without returning a folder." };
|
||||
}
|
||||
case "zenity": {
|
||||
const result = await run("zenity", [
|
||||
"--file-selection",
|
||||
"--directory",
|
||||
"--title",
|
||||
prompt,
|
||||
"--filename",
|
||||
`${startDir}/`,
|
||||
]);
|
||||
const path = firstLine(result.stdout);
|
||||
if (path) return { status: "picked", path, picker };
|
||||
return result.code === 1
|
||||
? { status: "cancelled", picker }
|
||||
: { status: "error", message: "zenity closed without returning a folder." };
|
||||
}
|
||||
case "yad": {
|
||||
const result = await run("yad", [
|
||||
"--file",
|
||||
"--directory",
|
||||
"--title",
|
||||
prompt,
|
||||
"--filename",
|
||||
`${startDir}/`,
|
||||
]);
|
||||
const path = firstLine(result.stdout).replace(/\|$/, "");
|
||||
if (path) return { status: "picked", path, picker };
|
||||
return result.code === 1 || result.code === 252
|
||||
? { status: "cancelled", picker }
|
||||
: { status: "error", message: "yad closed without returning a folder." };
|
||||
}
|
||||
case "portal": {
|
||||
const result = await run("python3", ["-c", PORTAL_PICK_SCRIPT, prompt, startDir]);
|
||||
const path = firstLine(result.stdout);
|
||||
if (path) return { status: "picked", path, picker };
|
||||
if (result.code === 3) return { status: "cancelled", picker };
|
||||
const detail = result.stderr.trim();
|
||||
return {
|
||||
status: "error",
|
||||
message:
|
||||
detail ||
|
||||
"The desktop portal file browser failed. It needs python3 with PyGObject and a running xdg-desktop-portal on the host. Install kdialog or zenity as an alternative.",
|
||||
};
|
||||
}
|
||||
case "osascript": {
|
||||
const escapedPrompt = prompt.replace(/\\/g, "\\\\").replace(/"/g, '\\"');
|
||||
const escapedDir = startDir.replace(/\\/g, "\\\\").replace(/"/g, '\\"');
|
||||
const script = `POSIX path of (choose folder with prompt "${escapedPrompt}" default location POSIX file "${escapedDir}")`;
|
||||
const result = await run("osascript", ["-e", script]);
|
||||
const path = firstLine(result.stdout);
|
||||
if (path) return { status: "picked", path: path.replace(/\/$/, "") || "/", picker };
|
||||
return { status: "cancelled", picker };
|
||||
}
|
||||
case "powershell": {
|
||||
const escapedDir = startDir.replace(/'/g, "''");
|
||||
const script = [
|
||||
"Add-Type -AssemblyName System.Windows.Forms;",
|
||||
"$dialog = New-Object System.Windows.Forms.FolderBrowserDialog;",
|
||||
`$dialog.Description = '${prompt.replace(/'/g, "''")}';`,
|
||||
`$dialog.SelectedPath = '${escapedDir}';`,
|
||||
"if ($dialog.ShowDialog() -eq [System.Windows.Forms.DialogResult]::OK) { [Console]::Out.Write($dialog.SelectedPath) }",
|
||||
].join(" ");
|
||||
const result = await run("powershell.exe", ["-NoProfile", "-STA", "-Command", script]);
|
||||
const path = firstLine(result.stdout);
|
||||
if (path) return { status: "picked", path, picker };
|
||||
return { status: "cancelled", picker };
|
||||
}
|
||||
case "custom": {
|
||||
const command = settings.customCommand.replaceAll("{dir}", startDir);
|
||||
const result = await run(command, [], true);
|
||||
const path = firstLine(result.stdout);
|
||||
if (path) return { status: "picked", path, picker };
|
||||
return result.code === 1
|
||||
? { status: "cancelled", picker }
|
||||
: { status: "error", message: "The custom picker command printed no folder." };
|
||||
}
|
||||
default:
|
||||
return { status: "error", message: `Unknown picker: ${picker}` };
|
||||
}
|
||||
} catch (error) {
|
||||
return { status: "error", message: error instanceof Error ? error.message : String(error) };
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,102 @@
|
||||
/**
|
||||
* Embedded Python script for XDG desktop portal folder selection.
|
||||
*
|
||||
* Inline string so it works even when Paseo bundles index.server.ts into an
|
||||
* in-memory CommonJS module where import.meta.url is unavailable.
|
||||
*/
|
||||
export const PORTAL_PICK_SCRIPT = String.raw`
|
||||
import os
|
||||
import sys
|
||||
from urllib.parse import unquote, urlparse
|
||||
|
||||
from gi.repository import Gio, GLib
|
||||
|
||||
|
||||
def fail(message):
|
||||
print(message, file=sys.stderr)
|
||||
sys.exit(2)
|
||||
|
||||
|
||||
def main():
|
||||
title = sys.argv[1] if len(sys.argv) > 1 else "Select project folder"
|
||||
start_dir = sys.argv[2] if len(sys.argv) > 2 else ""
|
||||
|
||||
try:
|
||||
bus = Gio.bus_get_sync(Gio.BusType.SESSION, None)
|
||||
except GLib.Error as error:
|
||||
fail(f"Could not connect to the session bus: {error.message}")
|
||||
|
||||
loop = GLib.MainLoop()
|
||||
token = f"paseo_file_browser_picker_{os.getpid()}"
|
||||
outcome = {"code": 2, "path": None, "error": None}
|
||||
|
||||
def on_response(_conn, _sender, _path, _iface, _signal, params, _data):
|
||||
code, results = params.unpack()
|
||||
try:
|
||||
if code == 0:
|
||||
uris = results.get("uris") or []
|
||||
if not uris:
|
||||
outcome["error"] = "The file browser returned no folder."
|
||||
else:
|
||||
outcome["path"] = unquote(urlparse(uris[0]).path)
|
||||
outcome["code"] = 0
|
||||
elif code == 1:
|
||||
outcome["code"] = 3
|
||||
else:
|
||||
outcome["error"] = "The file browser closed without a selection."
|
||||
finally:
|
||||
loop.quit()
|
||||
|
||||
sender = bus.get_unique_name().lstrip(":").replace(".", "_")
|
||||
request_path = f"/org/freedesktop/portal/desktop/request/{sender}/{token}"
|
||||
bus.signal_subscribe(
|
||||
"org.freedesktop.portal.Desktop",
|
||||
"org.freedesktop.portal.Request",
|
||||
"Response",
|
||||
request_path,
|
||||
None,
|
||||
Gio.DBusSignalFlags.NONE,
|
||||
on_response,
|
||||
None,
|
||||
)
|
||||
|
||||
options = {
|
||||
"handle_token": GLib.Variant("s", token),
|
||||
"accept_label": GLib.Variant("s", "Open"),
|
||||
"multiple": GLib.Variant("b", False),
|
||||
"directory": GLib.Variant("b", True),
|
||||
}
|
||||
if start_dir:
|
||||
options["current_folder"] = GLib.Variant(
|
||||
"ay", start_dir.encode("utf-8") + b"\x00"
|
||||
)
|
||||
|
||||
try:
|
||||
bus.call_sync(
|
||||
"org.freedesktop.portal.Desktop",
|
||||
"/org/freedesktop/portal/desktop",
|
||||
"org.freedesktop.portal.FileChooser",
|
||||
"OpenFile",
|
||||
GLib.Variant("(ssa{sv})", ("", title, options)),
|
||||
GLib.VariantType("(o)"),
|
||||
Gio.DBusCallFlags.NONE,
|
||||
-1,
|
||||
None,
|
||||
)
|
||||
except GLib.Error as error:
|
||||
fail(f"Could not open the file browser: {error.message}")
|
||||
|
||||
loop.run()
|
||||
|
||||
if outcome["code"] == 0 and outcome["path"]:
|
||||
print(outcome["path"])
|
||||
sys.stdout.flush()
|
||||
sys.exit(0)
|
||||
if outcome["code"] == 3:
|
||||
sys.exit(3)
|
||||
fail(outcome["error"] or "The file browser closed without a selection.")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
`;
|
||||
@@ -0,0 +1,90 @@
|
||||
import { defineRpc } from "@getpaseo/plugin";
|
||||
import { z } from "zod";
|
||||
|
||||
const pickInput = z.object({
|
||||
// Folder the file browser starts in. Falls back to the start folder in
|
||||
// plugin settings, then the home folder on the host.
|
||||
initialDir: z.string().optional(),
|
||||
});
|
||||
|
||||
export const openOutput = z.discriminatedUnion("status", [
|
||||
z.object({
|
||||
status: z.literal("opened"),
|
||||
path: z.string(),
|
||||
name: z.string(),
|
||||
workspaceId: z.string(),
|
||||
projectId: z.string().nullable(),
|
||||
picker: z.string(),
|
||||
}),
|
||||
z.object({ status: z.literal("cancelled"), picker: z.string() }),
|
||||
z.object({ status: z.literal("error"), message: z.string() }),
|
||||
]);
|
||||
|
||||
export const pickAndOpenRpc = defineRpc({
|
||||
name: "picker.pick_and_open",
|
||||
input: pickInput,
|
||||
output: openOutput,
|
||||
});
|
||||
|
||||
export const openFolderRpc = defineRpc({
|
||||
name: "picker.open_folder",
|
||||
input: z.object({ path: z.string() }),
|
||||
output: openOutput,
|
||||
});
|
||||
|
||||
export const pickRpc = defineRpc({
|
||||
name: "picker.pick",
|
||||
input: pickInput,
|
||||
output: z.discriminatedUnion("status", [
|
||||
z.object({ status: z.literal("picked"), path: z.string(), picker: z.string() }),
|
||||
z.object({ status: z.literal("cancelled"), picker: z.string() }),
|
||||
z.object({ status: z.literal("error"), message: z.string() }),
|
||||
]),
|
||||
});
|
||||
|
||||
export const detectRpc = defineRpc({
|
||||
name: "picker.detect",
|
||||
input: z.object({}),
|
||||
output: z.object({
|
||||
platform: z.string(),
|
||||
desktop: z.string().nullable(),
|
||||
pickers: z.array(
|
||||
z.object({
|
||||
id: z.string(),
|
||||
label: z.string(),
|
||||
available: z.boolean(),
|
||||
detail: z.string(),
|
||||
}),
|
||||
),
|
||||
recommended: z.string().nullable(),
|
||||
effectivePicker: z.string().nullable(),
|
||||
defaultStartDir: z.string(),
|
||||
}),
|
||||
});
|
||||
|
||||
export const listDirRpc = defineRpc({
|
||||
name: "picker.list_dir",
|
||||
input: z.object({
|
||||
path: z.string().optional(),
|
||||
showHidden: z.boolean().optional(),
|
||||
}),
|
||||
output: z.discriminatedUnion("status", [
|
||||
z.object({
|
||||
status: z.literal("ok"),
|
||||
path: z.string(),
|
||||
parent: z.string().nullable(),
|
||||
home: z.string(),
|
||||
entries: z.array(
|
||||
z.object({
|
||||
name: z.string(),
|
||||
path: z.string(),
|
||||
isGitRepo: z.boolean(),
|
||||
}),
|
||||
),
|
||||
}),
|
||||
z.object({
|
||||
status: z.literal("error"),
|
||||
message: z.string(),
|
||||
}),
|
||||
]),
|
||||
});
|
||||
@@ -0,0 +1,36 @@
|
||||
import { defineSettings } from "@getpaseo/plugin";
|
||||
import { z } from "zod";
|
||||
|
||||
export const pickerSchema = z.object({
|
||||
// Which program draws the folder picker on the host. "auto" tries the
|
||||
// desktop's own picker first, then the XDG portal dialog.
|
||||
picker: z
|
||||
.enum(["auto", "kdialog", "zenity", "yad", "portal", "osascript", "powershell", "custom"])
|
||||
.default("auto"),
|
||||
// Used only when picker is "custom". The command runs in a shell on the
|
||||
// host and must print the chosen folder to stdout. {dir} is replaced with
|
||||
// the start folder.
|
||||
customCommand: z.string().default(""),
|
||||
// Folder the picker starts in. Empty means the home folder on the host.
|
||||
startDir: z.string().default(""),
|
||||
// Title shown by the file browser dialog.
|
||||
prompt: z.string().default("Select project folder"),
|
||||
});
|
||||
|
||||
export type PickerSettings = z.output<typeof pickerSchema>;
|
||||
|
||||
// Host scope: the picker runs on the machine running the daemon, so the
|
||||
// choice belongs to that host, not to each connected client.
|
||||
export const pickerSettings = defineSettings({
|
||||
id: "picker",
|
||||
scope: "host",
|
||||
version: 1,
|
||||
schema: pickerSchema,
|
||||
});
|
||||
|
||||
export const defaultPickerSettings: PickerSettings = {
|
||||
picker: "auto",
|
||||
customCommand: "",
|
||||
startDir: "",
|
||||
prompt: "Select project folder",
|
||||
};
|
||||
@@ -0,0 +1,23 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"target": "ES2020",
|
||||
"module": "ESNext",
|
||||
"moduleResolution": "Bundler",
|
||||
"lib": [
|
||||
"ES2023"
|
||||
],
|
||||
"types": [
|
||||
"react"
|
||||
],
|
||||
"jsx": "react-jsx",
|
||||
"strict": true,
|
||||
"skipLibCheck": true,
|
||||
"noEmit": true,
|
||||
"esModuleInterop": true,
|
||||
"allowSyntheticDefaultImports": true
|
||||
},
|
||||
"include": [
|
||||
"**/*.ts",
|
||||
"**/*.tsx"
|
||||
]
|
||||
}
|
||||
Reference in new issue
Block a user