Skip to content

Commit

Permalink
fix: deno crash + stuff
Browse files Browse the repository at this point in the history
  • Loading branch information
louis030195 committed Sep 6, 2024
1 parent 4ff7d7d commit 87b24d3
Show file tree
Hide file tree
Showing 15 changed files with 317 additions and 60 deletions.
74 changes: 74 additions & 0 deletions examples/apps/screenpipe-app-tauri/components/pipe-config-form.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
import React, { useState, useEffect } from "react";
import { Input } from "./ui/input";
import { Button } from "./ui/button";
import { Label } from "./ui/label";
import { Checkbox } from "./ui/checkbox";
import { Pipe } from "@/lib/hooks/use-pipes";
import { invoke } from "@tauri-apps/api/core";

type PipeConfigFormProps = {
pipe: Pipe;
onConfigSave: (config: Record<string, any>) => void;
};

export const PipeConfigForm: React.FC<PipeConfigFormProps> = ({
pipe,
onConfigSave,
}) => {
const [config, setConfig] = useState<Record<string, any>>(pipe.config || {});

useEffect(() => {
const loadConfig = async () => {
try {
const loadedConfig = await invoke("load_pipe_config", {
pipeName: pipe.name,
});
setConfig(loadedConfig as Record<string, any>);
} catch (error) {
console.error("Error loading pipe config:", error);
}
};

loadConfig();
}, [pipe.name]);

const handleInputChange = (name: string, value: any) => {
setConfig((prev) => ({ ...prev, [name]: value }));
};

const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
try {
await invoke("save_pipe_config", { pipeName: pipe.name, config });
onConfigSave(config);
} catch (error) {
console.error("Error saving pipe config:", error);
}
};

return (
<form onSubmit={handleSubmit} className="space-y-4">
<h3 className="text-lg font-semibold">Pipe Configuration</h3>
{Object.entries(config).map(([key, value]) => (
<div key={key} className="space-y-2">
<Label htmlFor={key}>{key}</Label>
{typeof value === "boolean" ? (
<Checkbox
id={key}
checked={value}
onCheckedChange={(checked) => handleInputChange(key, checked)}
/>
) : (
<Input
id={key}
type={typeof value === "number" ? "number" : "text"}
value={value}
onChange={(e) => handleInputChange(key, e.target.value)}
/>
)}
</div>
))}
<Button type="submit">Save Configuration</Button>
</form>
);
};
25 changes: 24 additions & 1 deletion examples/apps/screenpipe-app-tauri/components/pipe-store.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ import { Input } from "./ui/input";
import { Plus } from "lucide-react";
import { FeatureRequestLink } from "./feature-request-link";
import PipeLogger from "./pipe-logger";
import { PipeConfigForm } from "./pipe-config-form";
const formatDate = (dateString: string) => {
const date = new Date(dateString);
return date.toLocaleDateString("en-US", {
Expand Down Expand Up @@ -70,6 +71,21 @@ const PipeDialog: React.FC = () => {
}
};

const handleConfigSave = async (config: Record<string, any>) => {
if (selectedPipe) {
const updatedPipe = { ...selectedPipe, config };
const updatedInstalledPipes = settings.installedPipes.map((p) =>
p.name === selectedPipe.name ? updatedPipe : p
);
await updateSettings({ installedPipes: updatedInstalledPipes });
setSelectedPipe(updatedPipe);
toast({
title: "Configuration saved",
description: "The pipe configuration has been updated.",
});
}
};

const formatUpdatedTime = (date: string) => {
const now = new Date();
const updated = new Date(date);
Expand Down Expand Up @@ -236,6 +252,12 @@ const PipeDialog: React.FC = () => {
</div>
<Separator className="my-4" />

{isInstalled && (
<PipeConfigForm pipe={selectedPipe} onConfigSave={handleConfigSave} />
)}

<Separator className="my-4" />

<div className="mt-4">
<h3 className="text-xl font-semibold mb-2">About this pipe</h3>
<MemoizedReactMarkdown
Expand Down Expand Up @@ -289,7 +311,8 @@ const PipeDialog: React.FC = () => {
{selectedPipe.fullDescription.replace(/Â/g, "")}
</MemoizedReactMarkdown>
</div>
<PipeLogger pipeId={selectedPipe.name} />
{/* https://github.com/denoland/deno_core/issues/898 */}
{/* <PipeLogger pipeId={selectedPipe.name} /> */}
</>
);
};
Expand Down
30 changes: 30 additions & 0 deletions examples/apps/screenpipe-app-tauri/components/ui/checkbox.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
"use client"

import * as React from "react"
import * as CheckboxPrimitive from "@radix-ui/react-checkbox"
import { Check } from "lucide-react"

import { cn } from "@/lib/utils"

const Checkbox = React.forwardRef<
React.ElementRef<typeof CheckboxPrimitive.Root>,
React.ComponentPropsWithoutRef<typeof CheckboxPrimitive.Root>
>(({ className, ...props }, ref) => (
<CheckboxPrimitive.Root
ref={ref}
className={cn(
"peer h-4 w-4 shrink-0 rounded-sm border border-primary ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:bg-primary data-[state=checked]:text-primary-foreground",
className
)}
{...props}
>
<CheckboxPrimitive.Indicator
className={cn("flex items-center justify-center text-current")}
>
<Check className="h-4 w-4" />
</CheckboxPrimitive.Indicator>
</CheckboxPrimitive.Root>
))
Checkbox.displayName = CheckboxPrimitive.Root.displayName

export { Checkbox }
30 changes: 30 additions & 0 deletions examples/apps/screenpipe-app-tauri/lib/hooks/use-pipes.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ export type Pipe = {
description: string;
fullDescription: string;
mainFile?: string;
config?: Record<string, any>;
};

const CACHE_DURATION = 60 * 60 * 1000; // 1 hour in milliseconds
Expand Down Expand Up @@ -116,6 +117,25 @@ const fetchFileContent = async (
}
};

const fetchPipeConfig = async (
repoFullName: string,
branch: string,
subDir: string
): Promise<Record<string, any> | undefined> => {
try {
const configPath = subDir ? `${subDir}/pipe.json` : "pipe.json";
const configContent = await fetchFileContent(
repoFullName,
branch,
configPath
);
return JSON.parse(configContent);
} catch (error) {
console.error("Error fetching pipe config:", error);
return undefined;
}
};

export const usePipes = (initialRepoUrls: string[]) => {
const [pipes, setPipes] = useState<Pipe[]>([]);
const [loading, setLoading] = useState(true);
Expand All @@ -137,6 +157,8 @@ export const usePipes = (initialRepoUrls: string[]) => {
`https://api.github.com/repos/${repoFullName}`
);

let pipeConfig: Record<string, any> | undefined;

if (isSubdir) {
console.log(
`Fetching subdirectory contents for ${repoFullName}/${subDir}`
Expand Down Expand Up @@ -172,6 +194,9 @@ export const usePipes = (initialRepoUrls: string[]) => {

console.log(`Fetching latest release for ${repoFullName}`);

console.log(`Fetching pipe config for ${repoFullName}/${subDir}`);
pipeConfig = await fetchPipeConfig(repoFullName, branch, subDir);

return {
name: subDir.split("/").pop() || repoData.name,
downloads: repoData.stargazers_count,
Expand All @@ -185,6 +210,7 @@ export const usePipes = (initialRepoUrls: string[]) => {
? convertHtmlToMarkdown(readmeContent)
: "",
mainFile: mainFileUrl,
config: pipeConfig,
};
} else {
console.log(`Fetching README for ${repoFullName}`);
Expand All @@ -193,6 +219,9 @@ export const usePipes = (initialRepoUrls: string[]) => {
console.log(`Fetching latest release for ${repoFullName}`);
const version = await fetchLatestRelease(repoFullName);

console.log(`Fetching pipe config for ${repoFullName}`);
pipeConfig = await fetchPipeConfig(repoFullName, branch, "");

return {
name: repoData.name,
downloads: repoData.stargazers_count,
Expand All @@ -203,6 +232,7 @@ export const usePipes = (initialRepoUrls: string[]) => {
lastUpdate: repoData.updated_at,
description: repoData.description,
fullDescription,
config: pipeConfig,
};
}
} catch (error) {
Expand Down
30 changes: 30 additions & 0 deletions examples/apps/screenpipe-app-tauri/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions examples/apps/screenpipe-app-tauri/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
"@mlc-ai/web-llm": "^0.2.51",
"@radix-ui/react-accordion": "^1.2.0",
"@radix-ui/react-avatar": "^1.1.0",
"@radix-ui/react-checkbox": "^1.1.1",
"@radix-ui/react-dialog": "^1.1.1",
"@radix-ui/react-dropdown-menu": "^2.1.1",
"@radix-ui/react-icons": "^1.3.0",
Expand Down
1 change: 1 addition & 0 deletions examples/apps/screenpipe-app-tauri/src-tauri/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,7 @@ tauri-plugin-dialog = "2.0.0-alpha.2"
tauri-plugin-os = "2.0.0-alpha.2"
tauri-plugin-process = "2.0.0-alpha.2"

dirs = "5.0.1"

# M series MacOS
[target.'cfg(target_os = "macos")'.dependencies]
Expand Down

Large diffs are not rendered by default.

33 changes: 30 additions & 3 deletions examples/apps/screenpipe-app-tauri/src-tauri/src/commands.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@

// #[tauri::command]
// pub fn has_screen_capture_access() -> bool {
// scap::has_permission()
// }

use serde_json::Value;

#[tauri::command]
pub fn open_screen_capture_preferences() {
#[cfg(target_os = "macos")]
Expand All @@ -13,7 +14,7 @@ pub fn open_screen_capture_preferences() {
.expect("failed to open system preferences");
}

#[allow(unused_imports)]
#[allow(dead_code)]
#[tauri::command]
pub fn open_mic_preferences() {
#[cfg(target_os = "macos")]
Expand All @@ -23,7 +24,7 @@ pub fn open_mic_preferences() {
.expect("failed to open system preferences");
}

#[allow(unused_imports)]
#[allow(dead_code)]
#[tauri::command]
pub fn reset_screen_permissions() {
#[cfg(target_os = "macos")]
Expand All @@ -35,6 +36,7 @@ pub fn reset_screen_permissions() {
.expect("failed to reset screen permissions");
}

#[allow(dead_code)]
#[tauri::command]
pub fn reset_microphone_permissions() {
#[cfg(target_os = "macos")]
Expand All @@ -45,3 +47,28 @@ pub fn reset_microphone_permissions() {
.spawn()
.expect("failed to reset microphone permissions");
}

#[tauri::command]
pub async fn load_pipe_config(pipe_name: String) -> Result<Value, String> {
let default_path = dirs::home_dir().unwrap().join(".screenpipe").join("pipes");

let config_path = default_path.join(pipe_name);
let config_content = tokio::fs::read_to_string(config_path)
.await
.map_err(|e| format!("Failed to read pipe config: {}", e))?;
let config: Value = serde_json::from_str(&config_content)
.map_err(|e| format!("Failed to parse pipe config: {}", e))?;
Ok(config)
}

#[tauri::command]
pub async fn save_pipe_config(pipe_name: String, config: Value) -> Result<(), String> {
let default_path = dirs::home_dir().unwrap().join(".screenpipe").join("pipes");
let config_path = default_path.join(pipe_name);
let config_content = serde_json::to_string_pretty(&config)
.map_err(|e| format!("Failed to serialize pipe config: {}", e))?;
tokio::fs::write(config_path, config_content)
.await
.map_err(|e| format!("Failed to write pipe config: {}", e))?;
Ok(())
}
4 changes: 4 additions & 0 deletions examples/apps/screenpipe-app-tauri/src-tauri/src/main.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
// Prevents additional console window on Windows in release, DO NOT REMOVE!!
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]

use commands::load_pipe_config;
use commands::save_pipe_config;
use sidecar::SidecarManager;
use tauri::Config;
use tokio::sync::mpsc;
Expand Down Expand Up @@ -76,6 +78,8 @@ async fn main() {
kill_all_sreenpipes,
reset_screen_permissions,
open_screen_capture_preferences,
load_pipe_config,
save_pipe_config
])
.setup(|app| {
// Logging setup
Expand Down
Loading

0 comments on commit 87b24d3

Please sign in to comment.