Compare commits

..

18 Commits

Author SHA1 Message Date
2mal3 18d150c767 bump to v0.1.3 2026-01-30 15:28:50 +01:00
2mal3 71f152ef2a refactor(display): use chrome devtools protocol (#38) 2026-01-30 15:26:57 +01:00
2mal3 cbbf50e5a4 bump to v0.1.2 2026-01-29 20:31:46 +01:00
2mal3 934dd42866 fix(control): typo in credits 2026-01-24 11:26:51 +01:00
2mal3 d2add33a7c fix(control): couldn't upload same file multiple times 2026-01-24 11:15:23 +01:00
2mal3 b4f9215fd4 fix(control): could not upload odp files 2026-01-23 23:13:19 +01:00
2mal3 666f04e3c6 style: supported_file_types.json 2026-01-23 23:06:47 +01:00
2mal3 eea15c558f fix(nixos): xfce pop when connecting new display 2026-01-21 18:30:11 +01:00
E44 9a4e2d4919 fix(control): enable startup_button if needed 2026-01-20 17:56:15 +01:00
E44 1138842269 refactor(control): improve code structure through new function 2026-01-19 23:35:38 +01:00
E44 c7bf6fa6f7 chore(control): clear loggin messages 2026-01-19 23:31:45 +01:00
E44 befa83131b fix(control): download button wasn't enabled 2026-01-19 23:14:30 +01:00
E44 c865dbeeae fix(control): get_missing_colliding_display_ids 2026-01-19 23:11:19 +01:00
E44 a5ee1b28d9 fix(control): open_inode_action and icon is now correct 2026-01-19 23:10:53 +01:00
E44 9e325566c5 refactor(control): remove unnecessary logging 2026-01-19 22:48:20 +01:00
E44 168576db81 refactor(control): create new constantly updated list of selected_online_display_ids 2026-01-19 22:47:36 +01:00
E44 3a30aca1dc chore(control): Keyboard queue (#31)
Co-authored-by: 2mal3 <56305732+2mal3@users.noreply.github.com>
2026-01-19 22:28:24 +01:00
2mal3 f2a648b429 chore(display): cleaner file download handling (#30) 2026-01-19 21:48:09 +01:00
36 changed files with 806 additions and 719 deletions
@@ -1,5 +1,5 @@
<script lang="ts"> <script lang="ts">
import { ArrowRight, Ban, FileIcon, Folder, Play } from 'lucide-svelte'; import { ArrowRight, Ban, FileIcon, Folder, Play, Triangle, TriangleAlert } from 'lucide-svelte';
import { import {
current_height, current_height,
get_selectable_color_classes, get_selectable_color_classes,
@@ -31,11 +31,15 @@
import RefreshPlay from '../svgs/RefreshPlay.svelte'; import RefreshPlay from '../svgs/RefreshPlay.svelte';
import { get_file_size_display_string, get_file_type } from '$lib/ts/utils'; import { get_file_size_display_string, get_file_type } from '$lib/ts/utils';
import { open_file } from '$lib/ts/api_handler'; import { open_file } from '$lib/ts/api_handler';
import { get_display_by_id, run_on_all_selected_displays } from '$lib/ts/stores/displays'; import {
get_display_by_id,
run_on_all_selected_displays,
selected_online_display_ids
} from '$lib/ts/stores/displays';
import { get_thumbnail_url } from '$lib/ts/stores/thumbnails'; import { get_thumbnail_url } from '$lib/ts/stores/thumbnails';
import { liveQuery, type Observable } from 'dexie'; import { liveQuery, type Observable } from 'dexie';
import { db } from '$lib/ts/database'; import { db } from '$lib/ts/database';
import { file_transfer_tasks } from '$lib/ts/file_transfer_handler'; import { add_sync_recursively, file_transfer_tasks } from '$lib/ts/file_transfer_handler';
let { file, not_interactable = false }: { file: Inode; not_interactable?: boolean } = $props(); let { file, not_interactable = false }: { file: Inode; not_interactable?: boolean } = $props();
@@ -45,10 +49,15 @@
| Observable<{ missing: string[]; colliding: string[] }> | Observable<{ missing: string[]; colliding: string[] }>
| undefined = $state(); | undefined = $state();
$effect(() => { $effect(() => {
const s = $selected_file_ids; const f = file;
missing_colliding_displays_ids = liveQuery(() => get_missing_colliding_display_ids(file, s)); const s = $selected_online_display_ids;
missing_colliding_displays_ids = liveQuery(() => get_missing_colliding_display_ids(f, s));
}); });
let colliding_warning: boolean = $derived(
!!$missing_colliding_displays_ids && $missing_colliding_displays_ids.colliding.length !== 0
);
let file_size: Observable<number> | undefined = $state(); let file_size: Observable<number> | undefined = $state();
$effect(() => { $effect(() => {
const f = file; const f = file;
@@ -159,6 +168,11 @@
async function open() { async function open() {
if (file_is_folder) { if (file_is_folder) {
await change_file_path($current_file_path + file.name + '/'); await change_file_path($current_file_path + file.name + '/');
} else if (
!!$missing_colliding_displays_ids &&
$missing_colliding_displays_ids.missing.length !== 0
) {
await add_sync_recursively(get_file_primary_key(file), $selected_online_display_ids, true);
} else { } else {
const path_to_file = $current_file_path + file.name; const path_to_file = $current_file_path + file.name;
await run_on_all_selected_displays((d) => open_file(d.ip, path_to_file)); await run_on_all_selected_displays((d) => open_file(d.ip, path_to_file));
@@ -215,7 +229,7 @@
if (is_folder(file)) { if (is_folder(file)) {
const folder_elements = await get_folder_elements( const folder_elements = await get_folder_elements(
file.path + file.name + '/', file.path + file.name + '/',
$selected_display_ids $selected_online_display_ids
); );
let out: number = 0; let out: number = 0;
for (const el of folder_elements) { for (const el of folder_elements) {
@@ -237,33 +251,43 @@
{#if !not_interactable} {#if !not_interactable}
<div class="h-{$current_height.file} aspect-square max-w-15 flex"> <div class="h-{$current_height.file} aspect-square max-w-15 flex">
<Button <Button
disabled={!file_is_folder && get_file_type(file) === null} disabled={(!file_is_folder && get_file_type(file) === null) || colliding_warning}
title={!file_is_folder && get_file_type(file) === null ? 'Dateityp nicht unterstützt' : ''} title={!file_is_folder && get_file_type(file) === null
? 'Dateityp nicht unterstützt'
: colliding_warning
? 'Dateien kollidieren auf verschiedenen Bildschirmen'
: ''}
className="flex rounded-l-lg rounded-r-none {file_is_folder className="flex rounded-l-lg rounded-r-none {file_is_folder
? 'text-stone-450' ? 'text-stone-450'
: 'text-stone-800'} w-full" : 'text-stone-800'} w-full"
div_class="w-full" div_class="w-full"
bg={get_selectable_color_classes( bg={colliding_warning
!file_is_folder && get_file_type(file) !== null, ? 'bg-red-400'
{ : get_selectable_color_classes(
bg: true !file_is_folder && get_file_type(file) !== null,
}, {
-50 bg: true
)} },
hover_bg={get_selectable_color_classes( -50
!file_is_folder, )}
{ hover_bg={colliding_warning
bg: true ? 'bg-red-500'
}, : get_selectable_color_classes(
50 !file_is_folder,
)} {
active_bg={get_selectable_color_classes( bg: true
!file_is_folder, },
{ 50
bg: true )}
}, active_bg={colliding_warning
100 ? 'bg-red-500'
)} : get_selectable_color_classes(
!file_is_folder,
{
bg: true
},
100
)}
click_function={(e) => { click_function={(e) => {
open(); open();
e.stopPropagation(); e.stopPropagation();
@@ -271,12 +295,14 @@
> >
{#if file_is_folder} {#if file_is_folder}
<ArrowRight class="size-full" strokeWidth="3" /> <ArrowRight class="size-full" strokeWidth="3" />
{:else if $missing_colliding_displays_ids && $missing_colliding_displays_ids.missing.length !== 0} {:else if get_file_type(file) === null}
<RefreshPlay className="size-full" />
{:else if get_file_type(file) !== null}
<Play class="size-full" strokeWidth="3" />
{:else}
<Ban class="size-full" strokeWidth="3" /> <Ban class="size-full" strokeWidth="3" />
{:else if colliding_warning}
<TriangleAlert class="size-full" strokeWidth="3" />
{:else if !!$missing_colliding_displays_ids && $missing_colliding_displays_ids.missing.length !== 0}
<RefreshPlay className="size-full" />
{:else}
<Play class="size-full" strokeWidth="3" />
{/if} {/if}
</Button> </Button>
</div> </div>
@@ -325,33 +351,6 @@
is_selected(file_primary_key, $selected_file_ids) is_selected(file_primary_key, $selected_file_ids)
)} duration-200 transition-colors" )} duration-200 transition-colors"
> >
<!-- {#if get_display_ids_where_file_is_missing($current_file_path, file, $selected_display_ids, $all_files)[1].length !== 0}
<Button
className="h-8 aspect-square transition-colors duration-200 !p-1.5 text-stone-100"
bg="bg-red-500"
click_function={(e) => {
e.stopPropagation();
}}
>
<TriangleAlert class="size-full" />
</Button>
{:else if get_display_ids_where_file_is_missing($current_file_path, file, $selected_display_ids, $all_files)[0].length !== 0}
<Button
className="h-8 aspect-square transition-colors duration-200 !p-1.5"
bg="bg-transparent"
hover_bg={get_selectable_color_classes(false, {
bg: true
})}
active_bg={get_selectable_color_classes(false, {
bg: true
})}
click_function={(e) => {
e.stopPropagation();
}}
>
<RefreshCcwDot class="size-full" />
</Button>
{/if} -->
<div <div
class="w-14 content-center text-center select-none text-xs whitespace-nowrap" class="w-14 content-center text-center select-none text-xs whitespace-nowrap"
title={get_created_info($date_mapping, true)} title={get_created_info($date_mapping, true)}
+9 -9
View File
@@ -51,9 +51,15 @@ export async function show_html(ip: string, html: string): Promise<void> {
await request_display(ip, '/showHTML', options); await request_display(ip, '/showHTML', options);
} }
export async function show_website(ip: string, url: string): Promise<void> { export async function open_website(ip: string, url: string): Promise<void> {
const command = `screen -dmS custom_website chromium-browser --user-data-dir=$(mktemp -d) --start-fullscreen --app="${url}"`; const options = {
await run_shell_command(ip, command); method: 'PATCH',
headers: { 'content-type': 'application/json' },
body: JSON.stringify({
url: url
})
};
await request_display(ip, '/openWebsite', options);
} }
export async function get_file_data( export async function get_file_data(
@@ -232,9 +238,6 @@ async function request(
): Promise<RequestResponse> { ): Promise<RequestResponse> {
try { try {
const cache_buster = `${url.includes('?') ? '&' : '?'}=${Date.now()}`; const cache_buster = `${url.includes('?') ? '&' : '?'}=${Date.now()}`;
if (dev) {
console.debug('Sending request: ', url + cache_buster, 'with', options.body ?? 'none');
}
const response = await fetch(url + cache_buster, options); const response = await fetch(url + cache_buster, options);
if (response.ok || supress_error_handling_http_codes.includes(response.status)) { if (response.ok || supress_error_handling_http_codes.includes(response.status)) {
const contentType = response.headers.get('content-type') || ''; const contentType = response.headers.get('content-type') || '';
@@ -245,9 +248,6 @@ async function request(
} else { } else {
const json: Record<string, unknown> = await response.json(); const json: Record<string, unknown> = await response.json();
request_response = { ok: response.ok, http_code: response.status, json: json }; request_response = { ok: response.ok, http_code: response.status, json: json };
if (dev) {
console.debug(request_response);
}
} }
return request_response; return request_response;
} }
@@ -1,6 +1,6 @@
import { get, writable, type Writable } from 'svelte/store'; import { get, writable, type Writable } from 'svelte/store';
import { db } from './database'; import { db } from './database';
import { get_display_by_id } from './stores/displays'; import { get_display_by_id, run_on_all_selected_displays } from './stores/displays';
import { import {
create_path_on_all_selected_displays, create_path_on_all_selected_displays,
get_folder_elements, get_folder_elements,
@@ -20,6 +20,7 @@ import {
type ShortDisplay type ShortDisplay
} from './types'; } from './types';
import { get_sanitized_file_url, get_uuid, make_valid_name } from './utils'; import { get_sanitized_file_url, get_uuid, make_valid_name } from './utils';
import { open_file } from './api_handler';
const START_LOADING_DATA = { const START_LOADING_DATA = {
percentage: 0, percentage: 0,
@@ -102,7 +103,8 @@ export async function add_upload(
export async function add_sync_recursively( export async function add_sync_recursively(
selected_file_id: string, selected_file_id: string,
selected_display_ids: string[] selected_display_ids: string[],
open_file_afterwards: boolean = false
) { ) {
const file_data = await find_file_data_on_active_selected_display( const file_data = await find_file_data_on_active_selected_display(
selected_file_id, selected_file_id,
@@ -134,7 +136,8 @@ export async function add_sync_recursively(
destination_display_data: file_data.short_displays_without_file.map((display) => ({ destination_display_data: file_data.short_displays_without_file.map((display) => ({
display, display,
loading_data: START_LOADING_DATA loading_data: START_LOADING_DATA
})) })),
open_file_afterwards_on_display_ids: open_file_afterwards ? selected_display_ids : []
}, },
display: file_data.short_display_with_file, display: file_data.short_display_with_file,
path: file_data.file.path, path: file_data.file.path,
@@ -285,6 +288,12 @@ export async function sync(file_primary_key: string, task: FileTransferTask) {
} }
await dir.removeEntry(temp_name); await dir.removeEntry(temp_name);
// open file, if required
if (task.data.open_file_afterwards_on_display_ids.length !== 0) {
const path_to_file = task.path + task.file_name;
await run_on_all_selected_displays((d) => open_file(d.ip, path_to_file), true, task.data.open_file_afterwards_on_display_ids);
}
} catch (e) { } catch (e) {
show_general_error(file_primary_key, task, String(e)); show_general_error(file_primary_key, task, String(e));
} }
@@ -295,8 +304,7 @@ export async function download_file(selected_file_id: string, selected_display_i
selected_file_id, selected_file_id,
selected_display_ids selected_display_ids
); );
if (!file_data || is_folder(file_data.file)) if (!file_data || is_folder(file_data.file)) return console.warn('Download cancelled: is folder');
return console.warn('Download cancelled: is folder');
try { try {
const url = `http://${file_data.short_display_with_file.ip}:1323/api${get_sanitized_file_url(file_data.file.path + file_data.file.name)}`; const url = `http://${file_data.short_display_with_file.ip}:1323/api${get_sanitized_file_url(file_data.file.path + file_data.file.name)}`;
@@ -455,7 +463,11 @@ function update_current_loading_data(
}); });
} }
function get_updated_task(current_loading_data: FileLoadingData, destination_display_id: string | null, task: FileTransferTask): FileTransferTask { function get_updated_task(
current_loading_data: FileLoadingData,
destination_display_id: string | null,
task: FileTransferTask
): FileTransferTask {
if (destination_display_id && task.data.type === 'sync') { if (destination_display_id && task.data.type === 'sync') {
const updatedDestinations = task.data.destination_display_data.map((dd) => const updatedDestinations = task.data.destination_display_data.map((dd) =>
dd.display.id === destination_display_id ? { ...dd, loading_data: current_loading_data } : dd dd.display.id === destination_display_id ? { ...dd, loading_data: current_loading_data } : dd
+9 -13
View File
@@ -22,8 +22,12 @@ export const online_displays_sub = liveQuery(() =>
db.displays.where('status').equals('app_online').toArray() db.displays.where('status').equals('app_online').toArray()
).subscribe((value) => { ).subscribe((value) => {
online_displays.set(value); online_displays.set(value);
const current_online_display_ids = value.map((d) => d.id);
selected_online_display_ids.set(get(selected_display_ids).filter((id) => current_online_display_ids.includes(id)));
}); });
export const selected_online_display_ids: Writable<string[]> = writable<string[]>([]);
export const local_displays: Writable<DisplayIdGroup[]> = writable<DisplayIdGroup[]>([]); export const local_displays: Writable<DisplayIdGroup[]> = writable<DisplayIdGroup[]>([]);
export async function is_display_name_taken(name: string): Promise<boolean> { export async function is_display_name_taken(name: string): Promise<boolean> {
@@ -193,17 +197,18 @@ export function screenshot_loop(display_id: string) {
export async function run_on_all_selected_displays( export async function run_on_all_selected_displays(
run_function: (display: Display) => void | Promise<void>, run_function: (display: Display) => void | Promise<void>,
update_screenshot_afterwards: boolean = true, update_screenshot_afterwards: boolean = true,
ignore_offline: boolean = true display_ids: string[] | null = null
) { ) {
if (!display_ids) display_ids = get(selected_online_display_ids);
const maybe_displays: (Display | null)[] = await Promise.all( const maybe_displays: (Display | null)[] = await Promise.all(
// fails when only a single promis fails // fails when only a single promis fails
get(selected_display_ids).map(async (id) => await get_display_by_id(id)) display_ids.map(async (id) => await get_display_by_id(id))
); );
const displays: Display[] = maybe_displays.filter((d): d is Display => d !== null); const displays: Display[] = maybe_displays.filter((d): d is Display => d !== null);
Promise.all( await Promise.all(
displays.map(async (display) => { displays.map(async (display) => {
if (!display || (ignore_offline && display.status === 'host_offline')) return; if (!display) return;
await run_function(display); await run_function(display);
if (update_screenshot_afterwards) { if (update_screenshot_afterwards) {
screenshot_loop(display.id); screenshot_loop(display.id);
@@ -269,15 +274,6 @@ export function set_new_display_order(display_id_group_id: string, new_data: Dis
}); });
} }
export function no_active_display_selected(
selected_display_ids: string[],
online_displays: Display[]
) {
const online_and_selected_displays = online_displays.filter((d) =>
selected_display_ids.includes(d.id)
);
return online_and_selected_displays.length === 0;
}
if (dev) { if (dev) {
setTimeout(add_testing_displays, 0); setTimeout(add_testing_displays, 0);
+27 -19
View File
@@ -7,7 +7,7 @@ import {
type Inode, type Inode,
type TreeElement type TreeElement
} from '../types'; } from '../types';
import { get_display_by_id } from './displays'; import { get_display_by_id, selected_online_display_ids } from './displays';
import { is_selected, select, selected_display_ids, selected_file_ids } from './select'; import { is_selected, select, selected_display_ids, selected_file_ids } from './select';
import { create_path, get_file_data, get_file_tree_data } from '../api_handler'; import { create_path, get_file_data, get_file_tree_data } from '../api_handler';
import { deactivate_old_thumbnail_urls, generate_thumbnail } from './thumbnails'; import { deactivate_old_thumbnail_urls, generate_thumbnail } from './thumbnails';
@@ -29,12 +29,16 @@ export async function change_file_path(new_path: string) {
const displays = await db.displays.toArray(); const displays = await db.displays.toArray();
for (const display of displays) { for (const display of displays) {
const changed_paths = await get_changed_directory_paths(display, new_path); await update_changed_directories(display, new_path);
if (!changed_paths) continue; }
console.debug('Update file system from', display.name, ':', changed_paths); }
for (const path of changed_paths) {
await update_folder_elements_recursively(display, path); async function update_changed_directories(display: Display, path: string = '/') {
} const changed_paths = await get_changed_directory_paths(display, path);
if (!changed_paths) return;
console.debug('Update file system from', display.name, ':', changed_paths);
for (const path of changed_paths) {
await update_folder_elements_recursively(display, path);
} }
} }
@@ -94,7 +98,10 @@ export async function update_current_folder_on_selected_displays() {
}); });
const current_path = get(current_file_path); const current_path = get(current_file_path);
for (const display of await db.displays.where('id').anyOf(get(selected_display_ids)).toArray()) { for (const display of await db.displays
.where('id')
.anyOf(get(selected_online_display_ids))
.toArray()) {
await update_folder_elements_recursively(display, current_path); await update_folder_elements_recursively(display, current_path);
} }
} }
@@ -107,13 +114,19 @@ export async function get_missing_colliding_display_ids(
const colliding: string[] = []; const colliding: string[] = [];
const colliding_files = await db.files const colliding_files = await db.files
.where('[path+name]') .where('name')
.equals([file.path, file.name]) .equals(file.name)
.filter((e) => e.size !== file.size || e.type !== file.type) .filter((e) => e.path === file.path && e.size !== file.size)
.toArray(); .toArray();
for (const colliding_file of colliding_files) { for (const colliding_file of colliding_files) {
colliding.push( colliding.push(
...(await get_display_ids_where_file_is_missing(colliding_file, selected_display_ids)) ...(
await db.files_on_display
.where('file_primary_key')
.equals(get_file_primary_key(colliding_file))
.filter((fod) => selected_display_ids.includes(fod.display_id))
.toArray()
).map((fod) => fod.display_id)
); );
} }
@@ -371,7 +384,7 @@ export async function get_file_by_id(
export async function run_for_selected_files_on_selected_displays( export async function run_for_selected_files_on_selected_displays(
action: (ip: string, file_names: string[]) => Promise<void> action: (ip: string, file_names: string[]) => Promise<void>
): Promise<void> { ): Promise<void> {
for (const display_id of get(selected_display_ids)) { for (const display_id of get(selected_online_display_ids)) {
const file_key_strings_on_display: string[] = ( const file_key_strings_on_display: string[] = (
await db.files_on_display.where('display_id').equals(display_id).toArray() await db.files_on_display.where('display_id').equals(display_id).toArray()
).map((e) => e.file_primary_key); ).map((e) => e.file_primary_key);
@@ -409,12 +422,7 @@ export async function create_path_on_all_selected_displays(
} }
setTimeout(async () => { setTimeout(async () => {
for (const display of displays_without_path) { for (const display of displays_without_path) {
const changed_paths = await get_changed_directory_paths(display, '/'); await update_changed_directories(display);
if (!changed_paths) continue;
console.debug('Update file system from', display.name, ':', changed_paths);
for (const path of changed_paths) {
await update_folder_elements_recursively(display, path);
}
} }
}, 0); }, 0);
} }
+7 -1
View File
@@ -1,4 +1,5 @@
import { writable, type Writable } from 'svelte/store'; import { get, writable, type Writable } from 'svelte/store';
import { online_displays, selected_online_display_ids } from './displays';
export const selected_file_ids: Writable<string[]> = writable<string[]>([]); // JSON.stringify([string, string, number, string]) export const selected_file_ids: Writable<string[]> = writable<string[]>([]); // JSON.stringify([string, string, number, string])
export const selected_display_ids: Writable<string[]> = writable<string[]>([]); export const selected_display_ids: Writable<string[]> = writable<string[]>([]);
@@ -19,6 +20,11 @@ export function select(
} }
return all_ids; return all_ids;
}); });
if (selected_ids === selected_display_ids) {
const current_online_display_ids = get(online_displays).map((d) => d.id);
selected_online_display_ids.set(get(selected_display_ids).filter((id) => current_online_display_ids.includes(id)));
}
} }
export function is_selected(id: string, selected_ids: string[]): boolean { export function is_selected(id: string, selected_ids: string[]): boolean {
+1
View File
@@ -48,6 +48,7 @@ export type FileTransferTaskData =
display: ShortDisplay; display: ShortDisplay;
loading_data: FileLoadingData; loading_data: FileLoadingData;
}[]; }[];
open_file_afterwards_on_display_ids: string[];
}; };
export type FileLoadingData = { export type FileLoadingData = {
+9
View File
@@ -113,3 +113,12 @@ export function get_sanitized_file_url(file_path: string, is_preview = false) {
return `/file/${is_preview ? 'preview/' : ''}${[...pathSegments].join('/')}`; return `/file/${is_preview ? 'preview/' : ''}${[...pathSegments].join('/')}`;
} }
let keyboard_queue = Promise.resolve();
export function add_to_keyboard_queue(task: () => Promise<void>) {
keyboard_queue = keyboard_queue.then(task).catch((err) => {
console.error('Error in input queue:', err);
});
}
+8 -8
View File
@@ -46,7 +46,7 @@
open: false, open: false,
snippet: null, snippet: null,
title: '', title: '',
title_class: '!text-xl', title_class: '!text-xl'
}); });
let remove_display_name = $state(''); let remove_display_name = $state('');
@@ -120,7 +120,7 @@
title: 'Neuen Bildschirm Hinzufügen', title: 'Neuen Bildschirm Hinzufügen',
title_icon: Monitor, title_icon: Monitor,
title_class: '!text-xl', title_class: '!text-xl',
window_class: 'w-3xl', window_class: 'w-3xl'
}; };
}; };
@@ -131,7 +131,7 @@
title: 'Einstellungen', title: 'Einstellungen',
title_icon: Settings, title_icon: Settings,
title_class: '!text-xl', title_class: '!text-xl',
window_class: 'w-3xl', window_class: 'w-3xl'
}; };
}; };
@@ -143,7 +143,7 @@
snippet_arg: display_id, snippet_arg: display_id,
title: 'Bildschirm wirklich löschen?', title: 'Bildschirm wirklich löschen?',
title_class: 'text-red-400 !text-xl', title_class: 'text-red-400 !text-xl',
title_icon: Trash2, title_icon: Trash2
}; };
}; };
@@ -161,7 +161,7 @@
snippet_arg: display_id, snippet_arg: display_id,
title: 'Bildschirm bearbeiten', title: 'Bildschirm bearbeiten',
title_icon: Monitor, title_icon: Monitor,
title_class: '!text-xl', title_class: '!text-xl'
}; };
}; };
@@ -173,7 +173,7 @@
snippet: about_popup, snippet: about_popup,
title: 'Über PLG MuDiCS', title: 'Über PLG MuDiCS',
title_icon: Info, title_icon: Info,
title_class: '!text-xl', title_class: '!text-xl'
}; };
}; };
</script> </script>
@@ -182,8 +182,8 @@
<div class="px-2"> <div class="px-2">
<h3 class="text-lg font-bold mt-4">Entwickler</h3> <h3 class="text-lg font-bold mt-4">Entwickler</h3>
<p> <p>
<a target="_blank" class="link" href="https://github.com/programmer-44">E44</a> <a target="_blank" class="link" href="https://github.com/programmer-44">E44</a>,
<a target="_blank" class="link" href="https://codeberg.org/2mal3">2mal3</a>, <a target="_blank" class="link" href="https://codeberg.org/2mal3">2mal3</a>
</p> </p>
<h3 class="text-lg font-bold mt-4">Lizenz</h3> <h3 class="text-lg font-bold mt-4">Lizenz</h3>
+33 -33
View File
@@ -21,19 +21,20 @@
show_blackscreen, show_blackscreen,
shutdown, shutdown,
startup, startup,
show_website show_html,
open_website
} from '$lib/ts/api_handler'; } from '$lib/ts/api_handler';
import { import {
get_display_by_id, get_display_by_id,
no_active_display_selected, run_on_all_selected_displays,
online_displays, selected_online_display_ids
run_on_all_selected_displays
} from '$lib/ts/stores/displays'; } from '$lib/ts/stores/displays';
import { selected_display_ids } from '$lib/ts/stores/select'; import { selected_display_ids } from '$lib/ts/stores/select';
import TipTapInput from './TipTapInput.svelte'; import TipTapInput from './TipTapInput.svelte';
import { db } from '$lib/ts/database'; import { db } from '$lib/ts/database';
import { liveQuery, type Observable } from 'dexie'; import { liveQuery, type Observable } from 'dexie';
import TextInput from '$lib/components/TextInput.svelte'; import TextInput from '$lib/components/TextInput.svelte';
import { add_to_keyboard_queue } from '$lib/ts/utils';
let all_display_states: Observable<'on' | 'off' | 'mixed'> | undefined = $state(); let all_display_states: Observable<'on' | 'off' | 'mixed'> | undefined = $state();
$effect(() => { $effect(() => {
@@ -44,7 +45,7 @@
let popup_content: PopupContent = $state({ let popup_content: PopupContent = $state({
open: false, open: false,
snippet: null, snippet: null,
title: '' title: '',
}); });
let current_text = $state(''); let current_text = $state('');
@@ -79,7 +80,7 @@
snippet: website_popup, snippet: website_popup,
title: 'Webseite Anzeigen', title: 'Webseite Anzeigen',
window_class: 'w-xl', window_class: 'w-xl',
title_icon: Globe title_icon: Globe,
}; };
}; };
@@ -102,7 +103,7 @@
open: true, open: true,
snippet: ask_shutdown_popup, snippet: ask_shutdown_popup,
title: 'Bildschirm Herunterfahren', title: 'Bildschirm Herunterfahren',
title_icon: PowerOff title_icon: PowerOff,
}; };
} }
@@ -110,10 +111,7 @@
popup_content.open = false; popup_content.open = false;
await run_on_all_selected_displays((d) => { await run_on_all_selected_displays((d) => {
shutdown(d.ip); // no await here because we want to be fast shutdown(d.ip); // no await here because we want to be fast
db.displays.update(d.id, { db.displays.update(d.id, { status: 'app_offline', preview: { currently_updating: false, url: null} });
status: 'app_offline',
preview: { currently_updating: false, url: null }
});
}, false); }, false);
} }
@@ -125,7 +123,7 @@
db.displays.update(d.id, { status: 'app_offline' }); db.displays.update(d.id, { status: 'app_offline' });
}, },
false, false,
false $selected_display_ids
); );
} }
@@ -146,7 +144,9 @@
async function send_website() { async function send_website() {
popup_content.open = false; popup_content.open = false;
await run_on_all_selected_displays((d) => show_website(d.ip, website_url)); await run_on_all_selected_displays((d) =>
open_website(d.ip, website_url)
);
} }
</script> </script>
@@ -186,11 +186,11 @@
{/snippet} {/snippet}
{#snippet send_keys_popup()} {#snippet send_keys_popup()}
<KeyInput {popup_close_function} /> <KeyInput {popup_close_function}/>
{/snippet} {/snippet}
{#snippet text_popup()} {#snippet text_popup()}
<TipTapInput bind:text={current_text} /> <TipTapInput bind:text={current_text}/>
{/snippet} {/snippet}
<div class="grid grid-rows-[2.5rem_auto] bg-stone-800 rounded-2xl min-w-0"> <div class="grid grid-rows-[2.5rem_auto] bg-stone-800 rounded-2xl min-w-0">
@@ -203,15 +203,15 @@
<div class="flex flex-row gap-2 w-75 justify-normal"> <div class="flex flex-row gap-2 w-75 justify-normal">
<button <button
title="Vorherige Folie (Pfeil nach Links) [gedrückt halten möglich]" title="Vorherige Folie (Pfeil nach Links) [gedrückt halten möglich]"
class="px-9 bg-stone-700 {$selected_display_ids.length === 0 class="px-9 bg-stone-700 {$selected_online_display_ids.length === 0
? 'text-stone-500 cursor-not-allowed' ? 'text-stone-500 cursor-not-allowed'
: 'hover:bg-stone-600 active:bg-stone-500 cursor-pointer'} py-2 rounded-xl flex justify-center items-center transition-colors duration-200" : 'hover:bg-stone-600 active:bg-stone-500 cursor-pointer'} py-2 rounded-xl flex justify-center items-center transition-colors duration-200"
disabled={$selected_display_ids.length === 0} disabled={$selected_online_display_ids.length === 0}
onmousedown={async () => { onmousedown={() => {
await send_single_key_press('ArrowLeft', 'press'); add_to_keyboard_queue(async () => await send_single_key_press('ArrowLeft', 'press'));
}} }}
onmouseup={async () => { onmouseup={() => {
await send_single_key_press('ArrowLeft', 'release'); add_to_keyboard_queue(async () => await send_single_key_press('ArrowLeft', 'release'));
}} }}
> >
<ArrowBigLeft /> <ArrowBigLeft />
@@ -219,15 +219,15 @@
<button <button
title="Vorherige Folie (Pfeil nach Links) [gedrückt halten möglich]" title="Vorherige Folie (Pfeil nach Links) [gedrückt halten möglich]"
class="px-9 bg-stone-700 {$selected_display_ids.length === 0 class="px-9 bg-stone-700 {$selected_online_display_ids.length === 0
? 'text-stone-500 cursor-not-allowed' ? 'text-stone-500 cursor-not-allowed'
: 'hover:bg-stone-600 active:bg-stone-500 cursor-pointer'} py-2 rounded-xl flex justify-center items-center transition-colors duration-200" : 'hover:bg-stone-600 active:bg-stone-500 cursor-pointer'} py-2 rounded-xl flex justify-center items-center transition-colors duration-200"
disabled={$selected_display_ids.length === 0} disabled={$selected_online_display_ids.length === 0}
onmousedown={async () => { onmousedown={() => {
await send_single_key_press('ArrowRight', 'press'); add_to_keyboard_queue(async () => await send_single_key_press('ArrowRight', 'press'));
}} }}
onmouseup={async () => { onmouseup={() => {
await send_single_key_press('ArrowRight', 'release'); add_to_keyboard_queue(async () => await send_single_key_press('ArrowRight', 'release'));
}} }}
> >
<ArrowBigRight /> <ArrowBigRight />
@@ -237,19 +237,19 @@
<Button <Button
className="px-3 flex gap-3 w-75 justify-normal" className="px-3 flex gap-3 w-75 justify-normal"
click_function={show_text_popup} click_function={show_text_popup}
disabled={no_active_display_selected($selected_display_ids, $online_displays)} disabled={$selected_online_display_ids.length === 0}
><TextAlignStart /> Text Anzeigen</Button ><TextAlignStart /> Text Anzeigen</Button
> >
<Button <Button
className="px-3 flex gap-3 w-75 justify-normal" className="px-3 flex gap-3 w-75 justify-normal"
disabled={no_active_display_selected($selected_display_ids, $online_displays)} disabled={$selected_online_display_ids.length === 0}
click_function={show_website_popup}><Globe /> Webseite Anzeigen</Button click_function={show_website_popup}><Globe /> Webseite Anzeigen</Button
> >
<Button <Button
className="px-3 flex gap-3 w-75 justify-normal" className="px-3 flex gap-3 w-75 justify-normal"
disabled={no_active_display_selected($selected_display_ids, $online_displays)} disabled={$selected_online_display_ids.length === 0}
click_function={async () => { click_function={async () => {
await run_on_all_selected_displays((d) => show_blackscreen(d.ip)); await run_on_all_selected_displays((d) => show_blackscreen(d.ip));
}}><Presentation />Blackout</Button }}><Presentation />Blackout</Button
@@ -264,7 +264,7 @@
<Button <Button
className="px-3 flex gap-3 w-75 justify-normal" className="px-3 flex gap-3 w-75 justify-normal"
disabled={no_active_display_selected($selected_display_ids, $online_displays)} disabled={$selected_online_display_ids.length === 0}
click_function={show_send_keys_popup}><Keyboard /> Tastatur-Eingaben Senden</Button click_function={show_send_keys_popup}><Keyboard /> Tastatur-Eingaben Senden</Button
> >
</div> </div>
@@ -273,7 +273,7 @@
<Button <Button
className="px-3 flex gap-3 w-full xl:w-75 justify-normal" className="px-3 flex gap-3 w-full xl:w-75 justify-normal"
disabled={$all_display_states === 'on' || disabled={$all_display_states === 'on' ||
no_active_display_selected($selected_display_ids, $online_displays)} $selected_display_ids.length === 0}
click_function={startup_action} click_function={startup_action}
> >
<Power /> Bildschirm Hochfahren <Power /> Bildschirm Hochfahren
@@ -282,7 +282,7 @@
<Button <Button
className="px-3 flex gap-3 w-full xl:w-75 justify-normal" className="px-3 flex gap-3 w-full xl:w-75 justify-normal"
disabled={$all_display_states === 'off' || disabled={$all_display_states === 'off' ||
no_active_display_selected($selected_display_ids, $online_displays)} $selected_online_display_ids.length === 0}
click_function={ask_shutdown} click_function={ask_shutdown}
> >
<PowerOff /> Bildschirm Herunterfahren</Button <PowerOff /> Bildschirm Herunterfahren</Button
+24 -20
View File
@@ -23,7 +23,6 @@
update_current_folder_on_selected_displays, update_current_folder_on_selected_displays,
get_displays_where_path_not_exists, get_displays_where_path_not_exists,
create_path_on_all_selected_displays create_path_on_all_selected_displays
} from '$lib/ts/stores/files'; } from '$lib/ts/stores/files';
import { slide } from 'svelte/transition'; import { slide } from 'svelte/transition';
import InodeElement from '../lib/components/InodeElement.svelte'; import InodeElement from '../lib/components/InodeElement.svelte';
@@ -39,7 +38,7 @@
import HighlightedText from '$lib/components/HighlightedText.svelte'; import HighlightedText from '$lib/components/HighlightedText.svelte';
import { liveQuery, type Observable } from 'dexie'; import { liveQuery, type Observable } from 'dexie';
import { download_file, add_upload, add_sync_recursively } from '$lib/ts/file_transfer_handler'; import { download_file, add_upload, add_sync_recursively } from '$lib/ts/file_transfer_handler';
import { no_active_display_selected, online_displays } from '$lib/ts/stores/displays'; import { selected_online_display_ids } from '$lib/ts/stores/displays';
let current_name: string = $state(''); let current_name: string = $state('');
let current_valid: boolean = $state(false); let current_valid: boolean = $state(false);
@@ -53,7 +52,7 @@
let current_folder_elements: Observable<Inode[]> | undefined = $state(); let current_folder_elements: Observable<Inode[]> | undefined = $state();
$effect(() => { $effect(() => {
const path = $current_file_path, const path = $current_file_path,
display_ids = $selected_display_ids; display_ids = $selected_online_display_ids;
current_folder_elements = liveQuery(() => get_folder_elements(path, display_ids)); current_folder_elements = liveQuery(() => get_folder_elements(path, display_ids));
}); });
let one_file_selected: Observable<boolean> | undefined = $state(); let one_file_selected: Observable<boolean> | undefined = $state();
@@ -62,14 +61,14 @@
one_file_selected = liveQuery(async () => { one_file_selected = liveQuery(async () => {
const inode = await get_file_by_id(s[0]); const inode = await get_file_by_id(s[0]);
if (!inode) return false; if (!inode) return false;
return s.length === 1 && is_folder(inode); return s.length === 1 && !is_folder(inode);
}); });
}); });
let popup_content: PopupContent = $state({ let popup_content: PopupContent = $state({
open: false, open: false,
snippet: null, snippet: null,
title: '', title: ''
}); });
let file_input: HTMLInputElement; let file_input: HTMLInputElement;
@@ -91,7 +90,7 @@
async function create_new_folder() { async function create_new_folder() {
popup_close_function(); popup_close_function();
const path_with_folder_name = ($current_file_path += current_name.trim() + '/'); const path_with_folder_name = ($current_file_path += current_name.trim() + '/');
await create_path_on_all_selected_displays(path_with_folder_name, $selected_display_ids); await create_path_on_all_selected_displays(path_with_folder_name, $selected_online_display_ids);
await update_current_folder_on_selected_displays(); await update_current_folder_on_selected_displays();
} }
@@ -119,7 +118,7 @@
snippet: edit_file_name_popup, snippet: edit_file_name_popup,
title: `${file_is_folder ? 'Ordner' : 'Datei'} umbenennen`, title: `${file_is_folder ? 'Ordner' : 'Datei'} umbenennen`,
title_icon: FolderPlus, title_icon: FolderPlus,
snippet_arg: extension, snippet_arg: extension
}; };
}; };
@@ -127,13 +126,13 @@
current_name = ''; current_name = '';
current_valid = false; current_valid = false;
display_names_where_path_does_not_exist = ( display_names_where_path_does_not_exist = (
await get_displays_where_path_not_exists($current_file_path, $selected_display_ids) await get_displays_where_path_not_exists($current_file_path, $selected_online_display_ids)
).map((display) => display.name); ).map((display) => display.name);
popup_content = { popup_content = {
open: true, open: true,
snippet: new_folder_popup, snippet: new_folder_popup,
title: 'Neuen Ordner erstellen', title: 'Neuen Ordner erstellen',
title_icon: FolderPlus, title_icon: FolderPlus
}; };
}; };
@@ -142,7 +141,7 @@
open: true, open: true,
snippet: delete_request_popup, snippet: delete_request_popup,
title: `${$selected_file_ids.length} ${$selected_file_ids.length === 1 ? 'Objekt' : 'Objekte'} wirklich löschen?`, title: `${$selected_file_ids.length} ${$selected_file_ids.length === 1 ? 'Objekt' : 'Objekte'} wirklich löschen?`,
title_icon: Trash2, title_icon: Trash2
}; };
}; };
@@ -152,7 +151,9 @@
current_folder_elements: Inode[] current_folder_elements: Inode[]
) { ) {
if (current_selected_file_ids.length === 0 && current_folder_elements.length > 0) { if (current_selected_file_ids.length === 0 && current_folder_elements.length > 0) {
current_selected_file_ids = current_folder_elements.map((inode) => get_file_primary_key(inode)); current_selected_file_ids = current_folder_elements.map((inode) =>
get_file_primary_key(inode)
);
} }
if (current_selected_file_ids.length === 0) return; if (current_selected_file_ids.length === 0) return;
// Mit For-Schleife über ausgewählte Elemente gehen // Mit For-Schleife über ausgewählte Elemente gehen
@@ -276,8 +277,11 @@
bind:this={file_input} bind:this={file_input}
multiple multiple
accept={get_accepted_file_type_string()} accept={get_accepted_file_type_string()}
onchange={(e) => onchange={async (e) => {
add_upload((e.target as HTMLInputElement).files!, $selected_display_ids, $current_file_path)} const target = e.target as HTMLInputElement;
await add_upload(target.files!, $selected_online_display_ids, $current_file_path);
target.value = '';
}}
/> />
<div class="bg-stone-800 h-full rounded-2xl grid grid-rows-[2.5rem_1fr] min-h-0"> <div class="bg-stone-800 h-full rounded-2xl grid grid-rows-[2.5rem_1fr] min-h-0">
@@ -319,7 +323,7 @@
title="Neuen Ordner erstellen (Neuen Ordner mit ausgewählten Objekten erstellen)" title="Neuen Ordner erstellen (Neuen Ordner mit ausgewählten Objekten erstellen)"
className="px-3 flex" className="px-3 flex"
click_function={show_new_folder_popup} click_function={show_new_folder_popup}
disabled={no_active_display_selected($selected_display_ids, $online_displays)}><FolderPlus /></Button disabled={$selected_online_display_ids.length === 0}><FolderPlus /></Button
> >
<div class="border border-stone-700 my-1"></div> <div class="border border-stone-700 my-1"></div>
<Button <Button
@@ -328,13 +332,13 @@
click_function={() => { click_function={() => {
if (file_input) file_input.click(); if (file_input) file_input.click();
}} }}
disabled={no_active_display_selected($selected_display_ids, $online_displays)}><Upload /></Button disabled={$selected_online_display_ids.length === 0}><Upload /></Button
> >
<Button <Button
title="Ausgewählte Datei herunterladen" title="Ausgewählte Datei herunterladen"
className="px-3 flex" className="px-3 flex"
click_function={async () => click_function={async () =>
await download_file($selected_file_ids[0], $selected_display_ids)} await download_file($selected_file_ids[0], $selected_online_display_ids)}
disabled={!$one_file_selected}><Download /></Button disabled={!$one_file_selected}><Download /></Button
> >
<div class="border border-stone-700 my-1"></div> <div class="border border-stone-700 my-1"></div>
@@ -344,10 +348,10 @@
click_function={async () => click_function={async () =>
await sync_selected_files( await sync_selected_files(
$selected_file_ids, $selected_file_ids,
$selected_display_ids, $selected_online_display_ids,
$current_folder_elements ?? [] $current_folder_elements ?? []
)} )}
disabled={no_active_display_selected($selected_display_ids, $online_displays)} disabled={$selected_online_display_ids.length === 0}
><RefreshCcw /> ><RefreshCcw />
<span class="hidden 2xl:flex">Synchronisieren</span> <span class="hidden 2xl:flex">Synchronisieren</span>
</Button> </Button>
@@ -361,7 +365,7 @@
<Button <Button
title="Ausgewählte Datei(en) einfügen" title="Ausgewählte Datei(en) einfügen"
className="px-3 flex" className="px-3 flex"
disabled={no_active_display_selected($selected_display_ids, $online_displays)} disabled={$selected_online_display_ids.length === 0}
> >
<ClipboardPaste /> <ClipboardPaste />
</Button> </Button>
@@ -385,7 +389,7 @@
</div> </div>
<div class="min-h-0 h-full overflow-y-auto overflow-x-hidden bg-stone-750 rounded-xl"> <div class="min-h-0 h-full overflow-y-auto overflow-x-hidden bg-stone-750 rounded-xl">
<div class="flex flex-col gap-2 p-2 min-h-0 max-w-full"> <div class="flex flex-col gap-2 p-2 min-h-0 max-w-full">
{#if no_active_display_selected($selected_display_ids, $online_displays)} {#if $selected_online_display_ids.length === 0}
<span class="text-stone-450 px-10 py-6 leading-relaxed text-center"> <span class="text-stone-450 px-10 py-6 leading-relaxed text-center">
Es sind keine Bildschirme ausgewählt. Es sind keine Bildschirme ausgewählt.
</span> </span>
+9 -4
View File
@@ -7,6 +7,7 @@
import { ArrowDownToLine, ArrowUpFromLine, Grid2x2, Grid2X2, Option } from 'lucide-svelte'; import { ArrowDownToLine, ArrowUpFromLine, Grid2x2, Grid2X2, Option } from 'lucide-svelte';
import Button from '$lib/components/Button.svelte'; import Button from '$lib/components/Button.svelte';
import { onDestroy } from 'svelte'; import { onDestroy } from 'svelte';
import { add_to_keyboard_queue } from '$lib/ts/utils';
let { let {
popup_close_function popup_close_function
@@ -58,17 +59,21 @@
const action: 'press' | 'release' = key_down ? 'press' : 'release'; const action: 'press' | 'release' = key_down ? 'press' : 'release';
add_to_last_keys(action.toUpperCase() + ' ' + key); add_to_last_keys(action.toUpperCase() + ' ' + key);
await run_on_all_selected_displays((d) => send_keyboard_input(d.ip, [{ key, action }]), true); add_to_keyboard_queue(async () => {
await run_on_all_selected_displays((d) => send_keyboard_input(d.ip, [{ key, action }]), true);
});
} }
async function release_all_pressed_keys() { function release_all_pressed_keys() {
const inputs: { key: string; action: 'press' | 'release' }[] = []; const inputs: { key: string; action: 'press' | 'release' }[] = [];
for (let i = current_keys.length - 1; i >= 0; i--) { for (let i = current_keys.length - 1; i >= 0; i--) {
inputs.push({ key: current_keys[i], action: 'release' }); inputs.push({ key: current_keys[i], action: 'release' });
current_keys.splice(i, 1); current_keys.splice(i, 1);
} }
await run_on_all_selected_displays((d) => send_keyboard_input(d.ip, inputs), true); add_to_keyboard_queue(async () => {
await run_on_all_selected_displays((d) => send_keyboard_input(d.ip, inputs), true);
});
} }
onDestroy(() => { onDestroy(() => {
@@ -91,7 +96,7 @@
}} }}
onblur={async () => { onblur={async () => {
active = false; active = false;
await release_all_pressed_keys(); release_all_pressed_keys();
}} }}
onkeydown={(e) => on_keyboard_input(e, true)} onkeydown={(e) => on_keyboard_input(e, true)}
onkeyup={(e) => on_keyboard_input(e, false)} onkeyup={(e) => on_keyboard_input(e, false)}
+1 -1
View File
@@ -64,7 +64,7 @@ func main() {
os.Exit(1) os.Exit(1)
} }
}() }()
err = shared.OpenBrowserWindow("http://localhost:"+port, false, "control") err = openBrowserWindow("http://localhost:" + port)
if err != nil { if err != nil {
slog.Error("Failed to open browser window", "error", err) slog.Error("Failed to open browser window", "error", err)
os.Exit(1) os.Exit(1)
@@ -1,4 +1,4 @@
package shared package main
import ( import (
"errors" "errors"
@@ -6,35 +6,30 @@ import (
"os" "os"
"os/exec" "os/exec"
"path/filepath" "path/filepath"
"plg-mudics/shared"
) )
func OpenBrowserWindow(url string, fullscreen bool, profile string) error { func openBrowserWindow(url string) error {
bins := []string{"chromium", "chromium-browser"} bins := []string{"chromium", "chromium-browser"}
home, err := os.UserHomeDir() home, err := os.UserHomeDir()
if err != nil { if err != nil {
return fmt.Errorf("unable to determine user home directory: %w", err) return fmt.Errorf("unable to determine user home directory: %w", err)
} }
browserProfileDirPath := filepath.Join(home, ".local", "share", "plg-mudics", fmt.Sprintf("browser-%s", profile)) browserProfileDirPath := filepath.Join(home, ".local", "share", "plg-mudics", "browser-control")
if err := os.MkdirAll(browserProfileDirPath, os.ModePerm); err != nil { if err := os.MkdirAll(browserProfileDirPath, os.ModePerm); err != nil {
return fmt.Errorf("failed to create local config directory: %w", err) return fmt.Errorf("failed to create local config directory: %w", err)
} }
args := []string{ args := []string{
fmt.Sprintf("--app=%s", url), fmt.Sprintf("--app=%s", url),
"--autoplay-policy=no-user-gesture-required",
fmt.Sprintf("--user-data-dir=%s", browserProfileDirPath), fmt.Sprintf("--user-data-dir=%s", browserProfileDirPath),
"--allow-running-insecure-content",
"--disable-features=XFrameOptions",
}
if fullscreen {
args = append(args, "--start-fullscreen")
} }
errs := []string{} errs := []string{}
for _, bin := range bins { for _, bin := range bins {
cmd := exec.Command(bin, args...) cmd := exec.Command(bin, args...)
commandOutput := RunShellCommand(cmd) commandOutput := shared.RunShellCommand(cmd)
if commandOutput.ExitCode == 0 { if commandOutput.ExitCode == 0 {
return nil return nil
} }
+6
View File
@@ -62,6 +62,12 @@ Even when the command itself fails.
The screenshot as binary in the response body. The screenshot as binary in the response body.
## PATCH `/openWebsite`
### Request Body
- `url`: string
## POST `/file/<path>` - Upload File ## POST `/file/<path>` - Upload File
### Responses ### Responses
+72
View File
@@ -0,0 +1,72 @@
package browser
import (
"context"
"fmt"
"os"
"path/filepath"
"github.com/chromedp/chromedp"
)
var Browser BrowserType = BrowserType{}
type BrowserType struct {
Ctx context.Context
Cancel context.CancelFunc
}
func (b *BrowserType) Init() error {
home, err := os.UserHomeDir()
if err != nil {
return fmt.Errorf("unable to determine user home directory: %w", err)
}
browserProfileDirPath := filepath.Join(home, ".local", "share", "plg-mudics", "browser-display")
if err := os.MkdirAll(browserProfileDirPath, os.ModePerm); err != nil {
return fmt.Errorf("failed to create local config directory: %w", err)
}
opts := []chromedp.ExecAllocatorOption{
chromedp.Flag("headless", false),
chromedp.Flag("app", "http://example.com"), // app mode prevents a few unwanted features of chrome, the start url is directly overwritten
chromedp.Flag("start-fullscreen", true),
chromedp.Flag("hide-scrollbars", true),
chromedp.Flag("allow-file-access-from-files", true),
chromedp.Flag("user-data-dir", browserProfileDirPath),
chromedp.Flag("autoplay-policy", "no-user-gesture-required"),
}
initCtx, _ := chromedp.NewExecAllocator(context.Background(), opts...)
b.Ctx, b.Cancel = chromedp.NewContext(initCtx)
return nil
}
func (b *BrowserType) OpenPage(url string) {
chromedp.Run(b.Ctx, chromedp.Navigate(url))
}
// Yes, we need that trick with creating a temp file and not directly sending html since
// chrome only allows us to access local files via other local files
func (b *BrowserType) OpenHTML(html string) error {
var err error
tempFile, err := os.CreateTemp("", "mudics-*.html")
if err != nil {
return fmt.Errorf("could not create tempfile: %w", err)
}
defer tempFile.Close()
_, err = tempFile.WriteString(html)
if err != nil {
return fmt.Errorf("could not write to tempfile: %w", err)
}
chromedp.Run(b.Ctx, chromedp.Navigate("file://"+tempFile.Name()))
return nil
}
func (b *BrowserType) OpenPDF(path string) {
b.OpenPage("file://" + path + "#toolbar=0&view=Fit")
}
+10 -3
View File
@@ -1,9 +1,10 @@
module plg-mudics/display module plg-mudics/display
go 1.24.4 go 1.25
require ( require (
github.com/a-h/templ v0.3.960 github.com/a-h/templ v0.3.977
github.com/chromedp/chromedp v0.14.2
github.com/gabriel-vasile/mimetype v1.4.11 github.com/gabriel-vasile/mimetype v1.4.11
github.com/labstack/echo/v4 v4.15.0 github.com/labstack/echo/v4 v4.15.0
github.com/micmonay/keybd_event v1.1.2 github.com/micmonay/keybd_event v1.1.2
@@ -14,9 +15,15 @@ require (
github.com/a-h/parse v0.0.0-20250122154542-74294addb73e // indirect github.com/a-h/parse v0.0.0-20250122154542-74294addb73e // indirect
github.com/andybalholm/brotli v1.1.0 // indirect github.com/andybalholm/brotli v1.1.0 // indirect
github.com/cenkalti/backoff/v4 v4.3.0 // indirect github.com/cenkalti/backoff/v4 v4.3.0 // indirect
github.com/chromedp/cdproto v0.0.0-20250803210736-d308e07a266d // indirect
github.com/chromedp/sysutil v1.1.0 // indirect
github.com/cli/browser v1.3.0 // indirect github.com/cli/browser v1.3.0 // indirect
github.com/fatih/color v1.16.0 // indirect github.com/fatih/color v1.16.0 // indirect
github.com/fsnotify/fsnotify v1.7.0 // indirect github.com/fsnotify/fsnotify v1.7.0 // indirect
github.com/go-json-experiment/json v0.0.0-20251027170946-4849db3c2f7e // indirect
github.com/gobwas/httphead v0.1.0 // indirect
github.com/gobwas/pool v0.2.1 // indirect
github.com/gobwas/ws v1.4.0 // indirect
github.com/labstack/gommon v0.4.2 // indirect github.com/labstack/gommon v0.4.2 // indirect
github.com/mattn/go-colorable v0.1.14 // indirect github.com/mattn/go-colorable v0.1.14 // indirect
github.com/mattn/go-isatty v0.0.20 // indirect github.com/mattn/go-isatty v0.0.20 // indirect
@@ -27,7 +34,7 @@ require (
golang.org/x/mod v0.30.0 // indirect golang.org/x/mod v0.30.0 // indirect
golang.org/x/net v0.48.0 // indirect golang.org/x/net v0.48.0 // indirect
golang.org/x/sync v0.19.0 // indirect golang.org/x/sync v0.19.0 // indirect
golang.org/x/sys v0.39.0 // indirect golang.org/x/sys v0.40.0 // indirect
golang.org/x/text v0.32.0 // indirect golang.org/x/text v0.32.0 // indirect
golang.org/x/time v0.14.0 // indirect golang.org/x/time v0.14.0 // indirect
golang.org/x/tools v0.39.0 // indirect golang.org/x/tools v0.39.0 // indirect
+18
View File
@@ -2,10 +2,18 @@ github.com/a-h/parse v0.0.0-20250122154542-74294addb73e h1:HjVbSQHy+dnlS6C3XajZ6
github.com/a-h/parse v0.0.0-20250122154542-74294addb73e/go.mod h1:3mnrkvGpurZ4ZrTDbYU84xhwXW2TjTKShSwjRi2ihfQ= github.com/a-h/parse v0.0.0-20250122154542-74294addb73e/go.mod h1:3mnrkvGpurZ4ZrTDbYU84xhwXW2TjTKShSwjRi2ihfQ=
github.com/a-h/templ v0.3.960 h1:trshEpGa8clF5cdI39iY4ZrZG8Z/QixyzEyUnA7feTM= github.com/a-h/templ v0.3.960 h1:trshEpGa8clF5cdI39iY4ZrZG8Z/QixyzEyUnA7feTM=
github.com/a-h/templ v0.3.960/go.mod h1:oCZcnKRf5jjsGpf2yELzQfodLphd2mwecwG4Crk5HBo= github.com/a-h/templ v0.3.960/go.mod h1:oCZcnKRf5jjsGpf2yELzQfodLphd2mwecwG4Crk5HBo=
github.com/a-h/templ v0.3.977 h1:kiKAPXTZE2Iaf8JbtM21r54A8bCNsncrfnokZZSrSDg=
github.com/a-h/templ v0.3.977/go.mod h1:oCZcnKRf5jjsGpf2yELzQfodLphd2mwecwG4Crk5HBo=
github.com/andybalholm/brotli v1.1.0 h1:eLKJA0d02Lf0mVpIDgYnqXcUn0GqVmEFny3VuID1U3M= github.com/andybalholm/brotli v1.1.0 h1:eLKJA0d02Lf0mVpIDgYnqXcUn0GqVmEFny3VuID1U3M=
github.com/andybalholm/brotli v1.1.0/go.mod h1:sms7XGricyQI9K10gOSf56VKKWS4oLer58Q+mhRPtnY= github.com/andybalholm/brotli v1.1.0/go.mod h1:sms7XGricyQI9K10gOSf56VKKWS4oLer58Q+mhRPtnY=
github.com/cenkalti/backoff/v4 v4.3.0 h1:MyRJ/UdXutAwSAT+s3wNd7MfTIcy71VQueUuFK343L8= github.com/cenkalti/backoff/v4 v4.3.0 h1:MyRJ/UdXutAwSAT+s3wNd7MfTIcy71VQueUuFK343L8=
github.com/cenkalti/backoff/v4 v4.3.0/go.mod h1:Y3VNntkOUPxTVeUxJ/G5vcM//AlwfmyYozVcomhLiZE= github.com/cenkalti/backoff/v4 v4.3.0/go.mod h1:Y3VNntkOUPxTVeUxJ/G5vcM//AlwfmyYozVcomhLiZE=
github.com/chromedp/cdproto v0.0.0-20250803210736-d308e07a266d h1:ZtA1sedVbEW7EW80Iz2GR3Ye6PwbJAJXjv7D74xG6HU=
github.com/chromedp/cdproto v0.0.0-20250803210736-d308e07a266d/go.mod h1:NItd7aLkcfOA/dcMXvl8p1u+lQqioRMq/SqDp71Pb/k=
github.com/chromedp/chromedp v0.14.2 h1:r3b/WtwM50RsBZHMUm9fsNhhzRStTHrKdr2zmwbZSzM=
github.com/chromedp/chromedp v0.14.2/go.mod h1:rHzAv60xDE7VNy/MYtTUrYreSc0ujt2O1/C3bzctYBo=
github.com/chromedp/sysutil v1.1.0 h1:PUFNv5EcprjqXZD9nJb9b/c9ibAbxiYo4exNWZyipwM=
github.com/chromedp/sysutil v1.1.0/go.mod h1:WiThHUdltqCNKGc4gaU50XgYjwjYIhKWoHGPTUfWTJ8=
github.com/cli/browser v1.3.0 h1:LejqCrpWr+1pRqmEPDGnTZOjsMe7sehifLynZJuqJpo= github.com/cli/browser v1.3.0 h1:LejqCrpWr+1pRqmEPDGnTZOjsMe7sehifLynZJuqJpo=
github.com/cli/browser v1.3.0/go.mod h1:HH8s+fOAxjhQoBUAsKuPCbqUuxZDhQ2/aD+SzsEfBTk= github.com/cli/browser v1.3.0/go.mod h1:HH8s+fOAxjhQoBUAsKuPCbqUuxZDhQ2/aD+SzsEfBTk=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
@@ -16,6 +24,14 @@ github.com/fsnotify/fsnotify v1.7.0 h1:8JEhPFa5W2WU7YfeZzPNqzMP6Lwt7L2715Ggo0nos
github.com/fsnotify/fsnotify v1.7.0/go.mod h1:40Bi/Hjc2AVfZrqy+aj+yEI+/bRxZnMJyTJwOpGvigM= github.com/fsnotify/fsnotify v1.7.0/go.mod h1:40Bi/Hjc2AVfZrqy+aj+yEI+/bRxZnMJyTJwOpGvigM=
github.com/gabriel-vasile/mimetype v1.4.11 h1:AQvxbp830wPhHTqc1u7nzoLT+ZFxGY7emj5DR5DYFik= github.com/gabriel-vasile/mimetype v1.4.11 h1:AQvxbp830wPhHTqc1u7nzoLT+ZFxGY7emj5DR5DYFik=
github.com/gabriel-vasile/mimetype v1.4.11/go.mod h1:d+9Oxyo1wTzWdyVUPMmXFvp4F9tea18J8ufA774AB3s= github.com/gabriel-vasile/mimetype v1.4.11/go.mod h1:d+9Oxyo1wTzWdyVUPMmXFvp4F9tea18J8ufA774AB3s=
github.com/go-json-experiment/json v0.0.0-20251027170946-4849db3c2f7e h1:Lf/gRkoycfOBPa42vU2bbgPurFong6zXeFtPoxholzU=
github.com/go-json-experiment/json v0.0.0-20251027170946-4849db3c2f7e/go.mod h1:uNVvRXArCGbZ508SxYYTC5v1JWoz2voff5pm25jU1Ok=
github.com/gobwas/httphead v0.1.0 h1:exrUm0f4YX0L7EBwZHuCF4GDp8aJfVeBrlLQrs6NqWU=
github.com/gobwas/httphead v0.1.0/go.mod h1:O/RXo79gxV8G+RqlR/otEwx4Q36zl9rqC5u12GKvMCM=
github.com/gobwas/pool v0.2.1 h1:xfeeEhW7pwmX8nuLVlqbzVc7udMDrwetjEv+TZIz1og=
github.com/gobwas/pool v0.2.1/go.mod h1:q8bcK0KcYlCgd9e7WYLm9LpyS+YeLd8JVDW6WezmKEw=
github.com/gobwas/ws v1.4.0 h1:CTaoG1tojrh4ucGPcoJFiAQUAsEWekEWvLy7GsVNqGs=
github.com/gobwas/ws v1.4.0/go.mod h1:G3gNqMNtPppf5XUz7O4shetPpcZ1VJ7zt18dlUeakrc=
github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI= github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI=
github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
github.com/labstack/echo/v4 v4.13.4 h1:oTZZW+T3s9gAu5L8vmzihV7/lkXGZuITzTQkTEhcXEA= github.com/labstack/echo/v4 v4.13.4 h1:oTZZW+T3s9gAu5L8vmzihV7/lkXGZuITzTQkTEhcXEA=
@@ -64,6 +80,8 @@ golang.org/x/sys v0.34.0 h1:H5Y5sJ2L2JRdyv7ROF1he/lPdvFsd0mJHFw2ThKHxLA=
golang.org/x/sys v0.34.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k= golang.org/x/sys v0.34.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k=
golang.org/x/sys v0.39.0 h1:CvCKL8MeisomCi6qNZ+wbb0DN9E5AATixKsvNtMoMFk= golang.org/x/sys v0.39.0 h1:CvCKL8MeisomCi6qNZ+wbb0DN9E5AATixKsvNtMoMFk=
golang.org/x/sys v0.39.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks= golang.org/x/sys v0.39.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=
golang.org/x/sys v0.40.0 h1:DBZZqJ2Rkml6QMQsZywtnjnnGvHza6BTfYFWY9kjEWQ=
golang.org/x/sys v0.40.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=
golang.org/x/text v0.27.0 h1:4fGWRpyh641NLlecmyl4LOe6yDdfaYNrGb2zdfo4JV4= golang.org/x/text v0.27.0 h1:4fGWRpyh641NLlecmyl4LOe6yDdfaYNrGb2zdfo4JV4=
golang.org/x/text v0.27.0/go.mod h1:1D28KMCvyooCX9hBiosv5Tz/+YLxj0j7XhWjpSUF7CU= golang.org/x/text v0.27.0/go.mod h1:1D28KMCvyooCX9hBiosv5Tz/+YLxj0j7XhWjpSUF7CU=
golang.org/x/text v0.32.0 h1:ZD01bjUt1FQ9WJ0ClOL5vxgxOI/sVCNgX1YtKwcY0mU= golang.org/x/text v0.32.0 h1:ZD01bjUt1FQ9WJ0ClOL5vxgxOI/sVCNgX1YtKwcY0mU=
+7 -7
View File
@@ -4,9 +4,9 @@ import (
"log/slog" "log/slog"
"os" "os"
"plg-mudics/display/browser"
"plg-mudics/display/pkg" "plg-mudics/display/pkg"
"plg-mudics/display/web" "plg-mudics/display/web"
"plg-mudics/shared"
) )
//go:generate go tool templ generate //go:generate go tool templ generate
@@ -25,10 +25,10 @@ func main() {
// the order is important, the open browser command exitsts as soon as the winodw is closed // the order is important, the open browser command exitsts as soon as the winodw is closed
// and since its the last action in the main go func all other goroutines (e.g. the webserver) are killed // and since its the last action in the main go func all other goroutines (e.g. the webserver) are killed
go web.StartWebServer(shared.Version, port) go web.StartWebServer(port)
err = shared.OpenBrowserWindow("http://localhost:"+port, true, "display")
if err != nil { browser.Browser.Init()
slog.Error("Failed to open browser window", "error", err) pkg.OpenStartScreen()
os.Exit(1) defer browser.Browser.Cancel()
} <-browser.Browser.Ctx.Done()
} }
-75
View File
@@ -1,75 +0,0 @@
package pkg
import (
"fmt"
"log/slog"
"os"
"os/exec"
"path/filepath"
"plg-mudics/shared"
"syscall"
"github.com/gabriel-vasile/mimetype"
)
var FileHandler fileHandler = fileHandler{}
type fileHandler struct {
runningProgram *exec.Cmd
}
func (fh *fileHandler) OpenFile(path string) error {
var err error
mType, err := mimetype.DetectFile(path)
if err != nil {
return fmt.Errorf("failed to detect mime type: %w", err)
}
tempDirPath, err := os.MkdirTemp("", "plg-mudics-program-profile-")
if err != nil {
return fmt.Errorf("failed to create temporary profile directory: %w", err)
}
err = fh.CloseRunningProgram()
if err != nil {
return err
}
switch mType.String() {
case "application/vnd.openxmlformats-officedocument.presentationml.presentation", "application/vnd.oasis.opendocument.presentation":
// yes, we need this weird workaround to delete lock files since libreoffice
// doesn't expose an option to ignore them or prevent their creation
// the --view argument for some reason doesn't work with --show
parent := filepath.Dir(path)
cmd := exec.Command("find", parent, "-name", ".~lock*", "-type", "f", "-delete")
result := shared.RunShellCommand(cmd)
if result.ExitCode != 0 {
slog.Warn("could not remove lock files", "path", parent, "stderr", result.Stderr, "exitCode", result.ExitCode)
}
fh.runningProgram = exec.Command("soffice", "--show", path, "--nologo", "--norestore", fmt.Sprintf("-env:UserInstallation=file://%s", tempDirPath))
case "application/pdf":
fh.runningProgram = exec.Command("xreader", path, "--presentation")
default:
return fmt.Errorf("unsupported file type: %s", mType.String())
}
fh.runningProgram.SysProcAttr = &syscall.SysProcAttr{Setpgid: true}
result := shared.RunShellCommandNonBlocking(fh.runningProgram)
if result.ExitCode != 0 {
return fmt.Errorf("could not open pdf: %s (%d)", result.Stderr, result.ExitCode)
}
return nil
}
func (fh *fileHandler) CloseRunningProgram() error {
if fh.runningProgram == nil {
return nil
}
err := syscall.Kill(-fh.runningProgram.Process.Pid, syscall.SIGTERM)
fh.runningProgram = nil
return err
}
+21 -32
View File
@@ -1,49 +1,21 @@
package pkg package pkg
import ( import (
"bytes"
"context"
"errors" "errors"
"fmt" "fmt"
"net" "log/slog"
"os" "os"
"os/exec" "os/exec"
"path/filepath" "path/filepath"
"strings" "strings"
"time" "time"
"plg-mudics/display/browser"
"plg-mudics/shared" "plg-mudics/shared"
) )
func GetDeviceIp() (string, error) {
addrs, err := net.InterfaceAddrs()
if err != nil {
return "", fmt.Errorf("failed to get network interfaces: %w", err)
}
for _, addr := range addrs {
ipNet, ok := addr.(*net.IPNet)
if ok && !ipNet.IP.IsLoopback() && ipNet.IP.To4() != nil {
return ipNet.IP.String(), nil
}
}
return "", fmt.Errorf("no suitable IP address found")
}
func GetDeviceMac() (string, error) {
interfaces, err := net.Interfaces()
if err != nil {
return "", fmt.Errorf("failed to get network interfaces: %w", err)
}
for _, interf := range interfaces {
mac := interf.HardwareAddr.String()
if mac != "" {
return mac, nil
}
}
return "", fmt.Errorf("no suitable MAC address found")
}
func TakeScreenshot() (string, error) { func TakeScreenshot() (string, error) {
tempFilePath := filepath.Join(os.TempDir(), fmt.Sprintf("screenshot_%d.png", time.Now().Unix())) tempFilePath := filepath.Join(os.TempDir(), fmt.Sprintf("screenshot_%d.png", time.Now().Unix()))
@@ -106,3 +78,20 @@ func ResolveStorageFilePath(pathParam string) (string, bool, error) {
return fullPath, true, nil return fullPath, true, nil
} }
func ShowHTML(html string) error {
ResetView()
var templateBuffer bytes.Buffer
htmlTemplate(html).Render(context.Background(), &templateBuffer)
err := browser.Browser.OpenHTML(templateBuffer.String())
return err
}
func ResetView() {
err := fileHandler.closeRunningProgram()
if err != nil {
slog.Error("Failed to close running program", "error", err)
}
}
+148
View File
@@ -0,0 +1,148 @@
package pkg
templ basicTemplate() {
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<title>PLG MuDiCS Display</title>
<style>
:root {
--background-color: black;
--foreground-color: oklch(92.3% 0.003 48.717);
--font-size: 5rem;
}
body {
display: flex;
justify-content: center;
/* centers horizontally */
align-items: center;
/* centers vertically */
width: 100vw;
/* Viewport width */
height: 100vh;
/* Viewport height */
margin: 0;
padding: 0;
overflow: hidden;
background-color: var(--background-color);
color: var(--foreground-color);
font-family: ui-sans-serif, system-ui, sans-serif, 'Apple Color Emoji', 'Segoe UI Emoji', 'Segoe UI Symbol', 'Noto Color Emoji';
cursor: none;
}
video,
img {
width: 100vw;
/* Viewport width */
height: 100vh;
/* Viewport height */
object-fit: contain;
}
p,
li {
font-size: var(--font-size);
line-height: 1.2;
text-wrap: balance;
max-width: 90vw;
word-break: break-word;
margin: 0 0 calc(var(--font-size) * 0.4) 0;
}
ul,
ol {
padding-left: calc(var(--font-size)*1.5);
}
</style>
</head>
<bod>
{ children... }
</bod>
</html>
}
templ videoTemplate(path string) {
@basicTemplate() {
<video autoplay>
<source src={ "file://" + path } type="video/mp4"/>
</video>
}
}
templ htmlTemplate(html string) {
@basicTemplate() {
@templ.Raw(html)
}
}
templ imageTemplate(path string) {
@basicTemplate() {
<img src={ "file://" + path }/>
}
}
templ deviceInfoTemplate(ip string, mac string, showQR bool) {
@basicTemplate() {
<div style="width: 100vw; height: 100vh; display: flex; flex-direction: row; justify-content: space-between;">
<div
style="display: flex; flex-direction: column; gap: 1rem; justify-content: end; padding: 2rem; font-size: 4rem;"
>
{ ip }
<span style="text-transform: uppercase;">{ mac }</span>
</div>
if showQR {
<div style="display: flex; justify-content: end; align-items: end; padding: 2rem;">
<div style="padding: 1rem; background-color: var(--foreground-color); border-radius: 1rem;">
<img
style="height: 30vh; width: auto; image-rendering: pixelated; image-rendering: crisp-edges;"
src={ "/qr?data=http://" + ip + ":8080" }
alt="QR-Code"
/>
</div>
</div>
}
</div>
<style>
:root {
--splash-bg: transparent !important;
--splash-fade-out-state: paused !important;
--background-color: oklch(21.6% 0.006 56.043);
}
</style>
}
}
templ startScreenTemplate(splashScreenHtml string, ip string, mac string, qrPath string) {
@basicTemplate() {
<div style="width: 100vw; height: 100vh; display: flex; flex-direction: row; justify-content: space-between;">
<div
style="display: flex; flex-direction: column; gap: 1rem; justify-content: end; padding: 2rem; font-size: 4rem;"
>
{ ip }
<span style="text-transform: uppercase;">{ mac }</span>
</div>
if qrPath != "" {
<div style="display: flex; justify-content: end; align-items: end; padding: 2rem;">
<div style="padding: 1rem; background-color: var(--foreground-color); border-radius: 1rem;">
<img
style="height: 30vh; width: auto; image-rendering: pixelated; image-rendering: crisp-edges;"
src={ "file://" + qrPath }
alt="QR-Code"
/>
</div>
</div>
}
</div>
@templ.Raw(splashScreenHtml)
<style>
:root {
--splash-bg: transparent !important;
--splash-fade-out-state: paused !important;
--background-color: oklch(21.6% 0.006 56.043);
}
</style>
}
}
+108
View File
@@ -0,0 +1,108 @@
package pkg
import (
"bytes"
"context"
"fmt"
"log/slog"
"os"
"os/exec"
"path/filepath"
"plg-mudics/shared"
"syscall"
"github.com/gabriel-vasile/mimetype"
"plg-mudics/display/browser"
)
var fileHandler fileHandlerType = fileHandlerType{}
type fileHandlerType struct {
runningProgram *exec.Cmd
}
func OpenFile(path string) error {
ResetView()
mType, err := mimetype.DetectFile(path)
if err != nil {
slog.Error("Failed to detect mime type", "file", path, "error", err)
}
switch mType.String() {
case "video/mp4":
var templateBuffer bytes.Buffer
videoTemplate(path).Render(context.Background(), &templateBuffer)
browser.Browser.OpenHTML(templateBuffer.String())
case "image/jpeg", "image/png", "image/gif":
var templateBuffer bytes.Buffer
imageTemplate(path).Render(context.Background(), &templateBuffer)
browser.Browser.OpenHTML(templateBuffer.String())
case "application/pdf":
browser.Browser.OpenPDF(path)
case "application/vnd.openxmlformats-officedocument.presentationml.presentation", "application/vnd.oasis.opendocument.presentation":
err = fileHandler.openFileWithApp(path)
default:
return fmt.Errorf("unsupported file type: %s", mType.String())
}
return nil
}
func (fh *fileHandlerType) openFileWithApp(path string) error {
var err error
mType, err := mimetype.DetectFile(path)
if err != nil {
return fmt.Errorf("failed to detect mime type: %w", err)
}
switch mType.String() {
case "application/vnd.openxmlformats-officedocument.presentationml.presentation", "application/vnd.oasis.opendocument.presentation":
err = fh.openLibreoffice(path)
if err != nil {
return err
}
default:
return fmt.Errorf("unsupported file type: %s", mType.String())
}
fh.runningProgram.SysProcAttr = &syscall.SysProcAttr{Setpgid: true}
result := shared.RunShellCommandNonBlocking(fh.runningProgram)
if result.ExitCode != 0 {
return fmt.Errorf("could not open pdf: %s (%d)", result.Stderr, result.ExitCode)
}
return nil
}
func (fh *fileHandlerType) openLibreoffice(path string) error {
// yes, we need this weird workaround to delete lock files since libreoffice
// doesn't expose an option to ignore them or prevent their creation
// the --view argument for some reason doesn't work with --show
parent := filepath.Dir(path)
cmd := exec.Command("find", parent, "-name", ".~lock*", "-type", "f", "-delete")
result := shared.RunShellCommand(cmd)
if result.ExitCode != 0 {
slog.Warn("could not remove lock files", "path", parent, "stderr", result.Stderr, "exitCode", result.ExitCode)
}
tempDirPath, err := os.MkdirTemp("", "plg-mudics-program-profile-")
if err != nil {
return fmt.Errorf("failed to create temporary profile directory: %w", err)
}
fh.runningProgram = exec.Command("soffice", "--show", path, "--nologo", "--norestore", fmt.Sprintf("-env:UserInstallation=file://%s", tempDirPath))
return nil
}
func (fh *fileHandlerType) closeRunningProgram() error {
if fh.runningProgram == nil {
return nil
}
err := syscall.Kill(-fh.runningProgram.Process.Pid, syscall.SIGTERM)
fh.runningProgram = nil
return err
}
+117
View File
@@ -0,0 +1,117 @@
package pkg
import (
"bytes"
"context"
"fmt"
"image/color"
"log/slog"
"net"
"os"
"plg-mudics/shared"
"strings"
"plg-mudics/display/browser"
"github.com/skip2/go-qrcode"
)
func OpenStartScreen() {
var err error
raw := shared.RawSplashScreenTemplate
html := strings.ReplaceAll(raw, "%%APP-VERSION%%", shared.Version)
ip, err := getDeviceIp()
if err != nil {
slog.Error("Failed to get device IP", "error", err)
}
mac, err := getDeviceMac()
if err != nil {
slog.Error("Failed to get device MAC address", "error", err)
}
port := 8080
showQrCode := !isPortFree(port)
qrCodePath := ""
if showQrCode {
qrCodePath, err = generateQRCode(fmt.Sprintf("http://%s:%d", ip, port))
if err != nil {
slog.Error("could not generate qr code", "error", err)
}
}
var templateBuffer bytes.Buffer
startScreenTemplate(html, ip, mac, qrCodePath).Render(context.Background(), &templateBuffer)
browser.Browser.OpenHTML(templateBuffer.String())
}
func getDeviceIp() (string, error) {
addrs, err := net.InterfaceAddrs()
if err != nil {
return "", fmt.Errorf("failed to get network interfaces: %w", err)
}
for _, addr := range addrs {
ipNet, ok := addr.(*net.IPNet)
if ok && !ipNet.IP.IsLoopback() && ipNet.IP.To4() != nil {
return ipNet.IP.String(), nil
}
}
return "", fmt.Errorf("no suitable IP address found")
}
func isPortFree(port int) bool {
addr := fmt.Sprintf("127.0.0.1:%d", port)
l, err := net.Listen("tcp", addr)
if err != nil {
return false
}
_ = l.Close()
return true
}
func getDeviceMac() (string, error) {
interfaces, err := net.Interfaces()
if err != nil {
return "", fmt.Errorf("failed to get network interfaces: %w", err)
}
for _, interf := range interfaces {
mac := interf.HardwareAddr.String()
if mac != "" {
return mac, nil
}
}
return "", fmt.Errorf("no suitable MAC address found")
}
func generateQRCode(data string) (string, error) {
qr, err := qrcode.New(data, qrcode.Medium)
if err != nil {
return "", fmt.Errorf("could not generate qr code: %w", err)
}
qr.DisableBorder = true
qr.ForegroundColor = color.RGBA{R: 0x1c, G: 0x19, B: 0x17, A: 0xff}
qr.BackgroundColor = color.RGBA{R: 0xe7, G: 0xe5, B: 0xe4, A: 0xff}
png, err := qr.PNG(-1)
if err != nil {
return "", fmt.Errorf("could not render qr code: %w", err)
}
file, err := os.CreateTemp("", "mudics-qr-code-*.png")
if err != nil {
return "", fmt.Errorf("could not save qr code: %w", err)
}
defer file.Close()
_, err = file.Write(png)
if err != nil {
return "", fmt.Errorf("could not write qr code to file: %w", err)
}
return file.Name(), nil
}
+22
View File
@@ -0,0 +1,22 @@
meta {
name: openWebsite
type: http
seq: 10
}
patch {
url: 127.0.0.1:1323/api/openWebsite
body: json
auth: inherit
}
body:json {
{
"url": "https://example.com"
}
}
settings {
encodeUrl: true
timeout: 0
}
-12
View File
@@ -1,12 +0,0 @@
package web
import (
"embed"
"io/fs"
)
//go:embed all:static
var staticDir embed.FS
// BuildDirFS contains the embedded dist directory files (without the "build" prefix)
var StaticDirFS, _ = fs.Sub(staticDir, "static")
+19 -168
View File
@@ -1,53 +1,27 @@
package web package web
import ( import (
"bytes"
"context"
"errors" "errors"
"fmt" "fmt"
"image/color"
"io" "io"
"log/slog" "log/slog"
"net"
"net/http" "net/http"
"net/url" "net/url"
"os" "os"
"os/exec" "os/exec"
"path/filepath" "path/filepath"
shared "plg-mudics/shared" shared "plg-mudics/shared"
"strings"
"github.com/gabriel-vasile/mimetype"
"github.com/labstack/echo/v4" "github.com/labstack/echo/v4"
"github.com/labstack/echo/v4/middleware" "github.com/labstack/echo/v4/middleware"
"github.com/skip2/go-qrcode"
"plg-mudics/display/browser"
"plg-mudics/display/pkg" "plg-mudics/display/pkg"
) )
var version string func StartWebServer(port string) {
var sseConnection chan string
func StartWebServer(v string, port string) {
version = v
e := echo.New() e := echo.New()
e.GET("/", indexRoute)
e.GET("/sse", sseRoute)
e.GET("/splash", func(ctx echo.Context) error {
html := shared.SplashScreenTemplate
html = strings.ReplaceAll(html, "%%APP-VERSION%%", version)
return ctx.HTML(http.StatusOK, html)
})
e.GET("/qr", qrRoute)
staticGroup := e.Group("/static")
staticGroup.Use(middleware.StaticWithConfig(middleware.StaticConfig{
Filesystem: http.FS(StaticDirFS),
HTML5: true,
}))
apiGroup := e.Group("/api") apiGroup := e.Group("/api")
apiGroup.Use(middleware.CORS()) apiGroup.Use(middleware.CORS())
apiGroup.GET("/ping", pingRoute) apiGroup.GET("/ping", pingRoute)
@@ -55,6 +29,7 @@ func StartWebServer(v string, port string) {
apiGroup.PATCH("/keyboardInput", keyboardInputRoute) apiGroup.PATCH("/keyboardInput", keyboardInputRoute)
apiGroup.PATCH("/showHTML", showHTMLRoute) apiGroup.PATCH("/showHTML", showHTMLRoute)
apiGroup.PATCH("/takeScreenshot", takeScreenshotRoute) apiGroup.PATCH("/takeScreenshot", takeScreenshotRoute)
apiGroup.PATCH("/openWebsite", openWebsiteRoute)
fileGroup := apiGroup.Group("/file") fileGroup := apiGroup.Group("/file")
fileGroup.Use(extractFilePathMiddleware) fileGroup.Use(extractFilePathMiddleware)
@@ -69,85 +44,6 @@ func StartWebServer(v string, port string) {
} }
} }
func indexRoute(ctx echo.Context) error {
return indexTemplate().Render(ctx.Request().Context(), ctx.Response().Writer)
}
func sseRoute(ctx echo.Context) error {
slog.Info("SSE client connected")
w := ctx.Response()
w.Header().Set("Content-Type", "text/event-stream")
w.Header().Set("Cache-Control", "no-cache")
w.Header().Set("Connection", "keep-alive")
w.WriteHeader(http.StatusOK)
flusher, _ := w.Writer.(http.Flusher)
sseConnection = make(chan string)
// init display
ip, err := pkg.GetDeviceIp()
if err != nil {
slog.Error("Failed to get device IP address", "error", err)
}
mac, err := pkg.GetDeviceMac()
if err != nil {
slog.Error("Failed to get device MAC address", "error", err)
}
showQR := !isPortFree(8080)
var status bytes.Buffer
deviceInfoTemplate(ip, mac, showQR).Render(context.Background(), &status)
connectedEvent := Event{
Data: status.Bytes(),
}
connectedEvent.MarshalTo(w)
flusher.Flush()
for {
select {
case <-ctx.Request().Context().Done():
slog.Info("SSE client disconnected")
sseConnection = nil
return nil
case event := <-sseConnection:
rawEvent := Event{
Event: []byte(""),
Data: []byte(event),
}
if err := rawEvent.MarshalTo(w); err != nil {
slog.Warn("Error writing to client", "error", err)
return err
}
flusher.Flush()
}
}
}
func qrRoute(c echo.Context) error {
data := c.QueryParam("data")
if data == "" {
return c.String(http.StatusBadRequest, "missing data")
}
qr, err := qrcode.New(data, qrcode.Medium)
if err != nil {
return c.String(http.StatusInternalServerError, "could not generate qr")
}
qr.DisableBorder = true
qr.ForegroundColor = color.RGBA{R: 0x1c, G: 0x19, B: 0x17, A: 0xff}
qr.BackgroundColor = color.RGBA{R: 0xe7, G: 0xe5, B: 0xe4, A: 0xff}
png, err := qr.PNG(-1)
if err != nil {
return c.String(http.StatusInternalServerError, "could not encode png")
}
return c.Blob(http.StatusOK, "image/png", png)
}
func extractFilePathMiddleware(next echo.HandlerFunc) echo.HandlerFunc { func extractFilePathMiddleware(next echo.HandlerFunc) echo.HandlerFunc {
return func(ctx echo.Context) error { return func(ctx echo.Context) error {
raw := ctx.Param("path") raw := ctx.Param("path")
@@ -295,14 +191,7 @@ func downloadFileRoute(ctx echo.Context) error {
slog.Info("Serving file for download", "path", fullPath) slog.Info("Serving file for download", "path", fullPath)
file, err := os.Open(fullPath) return ctx.File(fullPath)
if err != nil {
slog.Error("Failed to open file", "file", fullPath, "error", err)
return ctx.JSON(http.StatusInternalServerError, shared.ErrorResponse{Description: "Failed to open file"})
}
defer file.Close()
return ctx.Stream(http.StatusOK, "application/octet-stream", file)
} }
func openFileRoute(ctx echo.Context) error { func openFileRoute(ctx echo.Context) error {
@@ -315,38 +204,7 @@ func openFileRoute(ctx echo.Context) error {
return ctx.JSON(http.StatusNotFound, shared.ErrorResponse{Description: "File not found"}) return ctx.JSON(http.StatusNotFound, shared.ErrorResponse{Description: "File not found"})
} }
if sseConnection == nil { err = pkg.OpenFile(fullPath)
return ctx.JSON(http.StatusInternalServerError, shared.ErrorResponse{Description: "Cant connect to display browser client"})
}
err = resetView()
if err != nil {
slog.Error("Failed to reset view", "error", err)
}
mType, err := mimetype.DetectFile(fullPath)
if err != nil {
slog.Error("Failed to detect mime type", "file", pathParam, "error", err)
return ctx.JSON(http.StatusInternalServerError, shared.ErrorResponse{Description: "Failed to detect file type"})
}
switch mType.String() {
case "video/mp4":
var templateBuffer bytes.Buffer
videoTemplate(pathParam).Render(context.Background(), &templateBuffer)
sseConnection <- templateBuffer.String()
case "image/jpeg", "image/png", "image/gif":
var templateBuffer bytes.Buffer
imageTemplate(pathParam).Render(context.Background(), &templateBuffer)
sseConnection <- templateBuffer.String()
case "application/pdf", "application/vnd.openxmlformats-officedocument.presentationml.presentation", "application/vnd.oasis.opendocument.presentation":
err = pkg.FileHandler.OpenFile(fullPath)
default:
slog.Info("Unsupported file type", "type", mType)
return ctx.JSON(http.StatusUnsupportedMediaType, shared.ErrorResponse{Description: "Unsupported file type: " + mType.String()})
}
if err != nil { if err != nil {
slog.Error("Failed to open file", "file", pathParam, "error", err) slog.Error("Failed to open file", "file", pathParam, "error", err)
return ctx.JSON(http.StatusInternalServerError, shared.ErrorResponse{Description: "Failed to open file"}) return ctx.JSON(http.StatusInternalServerError, shared.ErrorResponse{Description: "Failed to open file"})
@@ -365,13 +223,12 @@ func showHTMLRoute(ctx echo.Context) error {
return ctx.JSON(http.StatusBadRequest, shared.ErrorResponse{Description: shared.BadRequestDescription}) return ctx.JSON(http.StatusBadRequest, shared.ErrorResponse{Description: shared.BadRequestDescription})
} }
err := resetView() err := pkg.ShowHTML(request.HTML)
if err != nil { if err != nil {
slog.Error("Failed to reset view", "error", err) slog.Error("Failed to open html", "error", err)
return ctx.JSON(http.StatusInternalServerError, shared.ErrorResponse{Description: "Failed to open html"})
} }
sseConnection <- request.HTML
slog.Info("HTML content sent to client") slog.Info("HTML content sent to client")
return ctx.JSON(http.StatusOK, struct{}{}) return ctx.JSON(http.StatusOK, struct{}{})
} }
@@ -379,7 +236,7 @@ func showHTMLRoute(ctx echo.Context) error {
func pingRoute(ctx echo.Context) error { func pingRoute(ctx echo.Context) error {
return ctx.JSON(http.StatusOK, struct { return ctx.JSON(http.StatusOK, struct {
Version string `json:"version"` Version string `json:"version"`
}{Version: version}) }{Version: shared.Version})
} }
func takeScreenshotRoute(ctx echo.Context) error { func takeScreenshotRoute(ctx echo.Context) error {
@@ -422,24 +279,18 @@ func previewRoute(ctx echo.Context) error {
return ctx.File(outputFilePath) return ctx.File(outputFilePath)
} }
// Reset previous file views so they dont collide with the new one func openWebsiteRoute(ctx echo.Context) error {
func resetView() error { var request struct {
err := pkg.FileHandler.CloseRunningProgram() URL string `json:"url"`
if err != nil { }
return fmt.Errorf("failed to close running program: %w", err) if err := ctx.Bind(&request); err != nil {
slog.Error("Failed to parse website input", "error", err)
return ctx.JSON(http.StatusBadRequest, shared.ErrorResponse{Description: shared.BadRequestDescription})
} }
sseConnection <- "" slog.Info("Opening url")
return nil browser.Browser.OpenPage(request.URL)
}
func isPortFree(port int) bool { return ctx.JSON(http.StatusOK, struct{}{})
addr := fmt.Sprintf("127.0.0.1:%d", port)
l, err := net.Listen("tcp", addr)
if err != nil {
return false
}
_ = l.Close()
return true
} }
-123
View File
@@ -1,123 +0,0 @@
package web
templ indexTemplate() {
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<title>PLG MuDiCS Display</title>
<script src="/static/htmx.min.js"></script>
<script src="/static/htmx-ext-sse.min.js"></script>
<style>
:root {
--background-color: black;
--foreground-color: oklch(92.3% 0.003 48.717);
--font-size: 5rem;
}
body {
display: flex;
justify-content: center;
/* centers horizontally */
align-items: center;
/* centers vertically */
width: 100vw;
/* Viewport width */
height: 100vh;
/* Viewport height */
margin: 0;
padding: 0;
overflow: hidden;
background-color: var(--background-color);
color: var(--foreground-color);
font-family: ui-sans-serif, system-ui, sans-serif, 'Apple Color Emoji', 'Segoe UI Emoji', 'Segoe UI Symbol', 'Noto Color Emoji';
cursor: none;
}
video,
img,
iframe {
width: 100vw;
/* Viewport width */
height: 100vh;
/* Viewport height */
object-fit: contain;
}
p,
li {
font-size: var(--font-size);
line-height: 1.2;
text-wrap: balance;
max-width: 90vw;
word-break: break-word;
margin: 0 0 calc(var(--font-size) * 0.4) 0;
}
ul,
ol {
padding-left: calc(var(--font-size)*1.5);
}
</style>
<script>
document.addEventListener('keydown', function (event) {
if (event.code === 'Space') {
event.preventDefault();
var video = document.querySelector('video');
if (video) {
if (video.paused) {
video.play();
} else {
video.pause();
}
}
}
});
</script>
</head>
<bod>
<div hx-get="/splash" hx-trigger="load"></div>
<main hx-ext="sse" sse-connect="/sse" sse-swap="message"></main>
</bod>
</html>
}
templ videoTemplate(path string) {
<video autoplay>
<source src={ "/api/file/" + path } type="video/mp4"/>
</video>
}
templ imageTemplate(path string) {
<img src={ "/api/file/" + path }/>
}
templ deviceInfoTemplate(ip string, mac string, showQR bool) {
<div style="width: 100vw; height: 100vh; display: flex; flex-direction: row; justify-content: space-between;">
<div
style="display: flex; flex-direction: column; gap: 1rem; justify-content: end; padding: 2rem; font-size: 4rem;"
>
{ ip }
<span style="text-transform: uppercase;">{ mac }</span>
</div>
if showQR {
<div style="display: flex; justify-content: end; align-items: end; padding: 2rem;">
<div style="padding: 1rem; background-color: var(--foreground-color); border-radius: 1rem;">
<img
style="height: 30vh; width: auto; image-rendering: pixelated; image-rendering: crisp-edges;"
src={ "/qr?data=http://" + ip + ":8080" }
alt="QR-Code"
/>
</div>
</div>
}
</div>
<style>
:root {
--splash-bg: transparent !important;
--splash-fade-out-state: paused !important;
--background-color: oklch(21.6% 0.006 56.043);
}
</style>
}
-75
View File
@@ -1,75 +0,0 @@
package web
import (
"bytes"
"fmt"
"io"
)
// Event represents Server-Sent Event.
// SSE explanation: https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events#event_stream_format
type Event struct {
// ID is used to set the EventSource object's last event ID value.
ID []byte
// Data field is for the message. When the EventSource receives multiple consecutive lines
// that begin with data:, it concatenates them, inserting a newline character between each one.
// Trailing newlines are removed.
Data []byte
// Event is a string identifying the type of event described. If this is specified, an event
// will be dispatched on the browser to the listener for the specified event name; the website
// source code should use addEventListener() to listen for named events. The onmessage handler
// is called if no event name is specified for a message.
Event []byte
// Retry is the reconnection time. If the connection to the server is lost, the browser will
// wait for the specified time before attempting to reconnect. This must be an integer, specifying
// the reconnection time in milliseconds. If a non-integer value is specified, the field is ignored.
Retry []byte
// Comment line can be used to prevent connections from timing out; a server can send a comment
// periodically to keep the connection alive.
Comment []byte
}
// MarshalTo marshals Event to given Writer
func (ev *Event) MarshalTo(w io.Writer) error {
// Marshalling part is taken from: https://github.com/r3labs/sse/blob/c6d5381ee3ca63828b321c16baa008fd6c0b4564/http.go#L16
if len(ev.Data) == 0 && len(ev.Comment) == 0 {
return nil
}
if len(ev.Data) > 0 {
if _, err := fmt.Fprintf(w, "id: %s\n", ev.ID); err != nil {
return err
}
sd := bytes.Split(ev.Data, []byte("\n"))
for i := range sd {
if _, err := fmt.Fprintf(w, "data: %s\n", sd[i]); err != nil {
return err
}
}
if len(ev.Event) > 0 {
if _, err := fmt.Fprintf(w, "event: %s\n", ev.Event); err != nil {
return err
}
}
if len(ev.Retry) > 0 {
if _, err := fmt.Fprintf(w, "retry: %s\n", ev.Retry); err != nil {
return err
}
}
}
if len(ev.Comment) > 0 {
if _, err := fmt.Fprintf(w, ": %s\n", ev.Comment); err != nil {
return err
}
}
if _, err := fmt.Fprint(w, "\n"); err != nil {
return err
}
return nil
}
-1
View File
@@ -1 +0,0 @@
(function(){var g;htmx.defineExtension("sse",{init:function(e){g=e;if(htmx.createEventSource==undefined){htmx.createEventSource=t}},getSelectors:function(){return["[sse-connect]","[data-sse-connect]","[sse-swap]","[data-sse-swap]"]},onEvent:function(e,t){var r=t.target||t.detail.elt;switch(e){case"htmx:beforeCleanupElement":var n=g.getInternalData(r);var s=n.sseEventSource;if(s){g.triggerEvent(r,"htmx:sseClose",{source:s,type:"nodeReplaced"});n.sseEventSource.close()}return;case"htmx:afterProcessNode":i(r)}}});function t(e){return new EventSource(e,{withCredentials:true})}function a(n){if(g.getAttributeValue(n,"sse-swap")){var s=g.getClosestMatch(n,v);if(s==null){return null}var e=g.getInternalData(s);var a=e.sseEventSource;var t=g.getAttributeValue(n,"sse-swap");var r=t.split(",");for(var i=0;i<r.length;i++){const u=r[i].trim();const c=function(e){if(l(s)){return}if(!g.bodyContains(n)){a.removeEventListener(u,c);return}if(!g.triggerEvent(n,"htmx:sseBeforeMessage",e)){return}f(n,e.data);g.triggerEvent(n,"htmx:sseMessage",e)};g.getInternalData(n).sseEventListener=c;a.addEventListener(u,c)}}if(g.getAttributeValue(n,"hx-trigger")){var s=g.getClosestMatch(n,v);if(s==null){return null}var e=g.getInternalData(s);var a=e.sseEventSource;var o=g.getTriggerSpecs(n);o.forEach(function(t){if(t.trigger.slice(0,4)!=="sse:"){return}var r=function(e){if(l(s)){return}if(!g.bodyContains(n)){a.removeEventListener(t.trigger.slice(4),r)}htmx.trigger(n,t.trigger,e);htmx.trigger(n,"htmx:sseMessage",e)};g.getInternalData(n).sseEventListener=r;a.addEventListener(t.trigger.slice(4),r)})}}function i(e,t){if(e==null){return null}if(g.getAttributeValue(e,"sse-connect")){var r=g.getAttributeValue(e,"sse-connect");if(r==null){return}n(e,r,t)}a(e)}function n(r,e,n){var s=htmx.createEventSource(e);s.onerror=function(e){g.triggerErrorEvent(r,"htmx:sseError",{error:e,source:s});if(l(r)){return}if(s.readyState===EventSource.CLOSED){n=n||0;n=Math.max(Math.min(n*2,128),1);var t=n*500;window.setTimeout(function(){i(r,n)},t)}};s.onopen=function(e){g.triggerEvent(r,"htmx:sseOpen",{source:s});if(n&&n>0){const t=r.querySelectorAll("[sse-swap], [data-sse-swap], [hx-trigger], [data-hx-trigger]");for(let e=0;e<t.length;e++){a(t[e])}n=0}};g.getInternalData(r).sseEventSource=s;var t=g.getAttributeValue(r,"sse-close");if(t){s.addEventListener(t,function(){g.triggerEvent(r,"htmx:sseClose",{source:s,type:"message"});s.close()})}}function l(e){if(!g.bodyContains(e)){var t=g.getInternalData(e).sseEventSource;if(t!=undefined){g.triggerEvent(e,"htmx:sseClose",{source:t,type:"nodeMissing"});t.close();return true}}return false}function f(t,r){g.withExtensions(t,function(e){r=e.transformResponse(r,null,t)});var e=g.getSwapSpecification(t);var n=g.getTarget(t);g.swap(n,r,e,{contextElement:t})}function v(e){return g.getInternalData(e).sseEventSource!=null}})();
File diff suppressed because one or more lines are too long
+2
View File
@@ -1,4 +1,6 @@
github.com/a-h/htmlformat v0.0.0-20250209131833-673be874c677/go.mod h1:FMIm5afKmEfarNbIXOaPHFY8X7fo+fRQB6I9MPG2nB0= github.com/a-h/htmlformat v0.0.0-20250209131833-673be874c677/go.mod h1:FMIm5afKmEfarNbIXOaPHFY8X7fo+fRQB6I9MPG2nB0=
github.com/ledongthuc/pdf v0.0.0-20220302134840-0c2507a12d80/go.mod h1:imJHygn/1yfhB7XSJJKlFZKl/J+dCPAknuiaGOshXAs=
github.com/orisano/pixelmatch v0.0.0-20220722002657-fb0b55479cde/go.mod h1:nZgzbfBr3hhjoZnS66nKrHmduYNpc34ny7RK4z5/HM0=
github.com/rs/cors v1.11.0/go.mod h1:XyqrcTp5zjWr1wsJ8PIRZssZ8b/WMcMf71DJnit4EMU= github.com/rs/cors v1.11.0/go.mod h1:XyqrcTp5zjWr1wsJ8PIRZssZ8b/WMcMf71DJnit4EMU=
github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=
github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY= github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY=
+1 -2
View File
@@ -92,10 +92,8 @@
nushell nushell
unzip unzip
iputils iputils
xreader
tree tree
jq jq
screen
# Libraries # Libraries
imagemagick imagemagick
@@ -107,6 +105,7 @@
xfconf.settings = { xfconf.settings = {
xfce4-power-manager."xfce4-power-manager/dpms-enabled" = false; xfce4-power-manager."xfce4-power-manager/dpms-enabled" = false;
xfce4-screensaver."saver/enabled" = false; xfce4-screensaver."saver/enabled" = false;
displays.Notify = 0; # disable popup when connecting new display
}; };
home.stateVersion = "25.05"; home.stateVersion = "25.05";
+1 -1
View File
@@ -6,7 +6,7 @@ import (
) )
//go:embed splash_screen.html //go:embed splash_screen.html
var SplashScreenTemplate string var RawSplashScreenTemplate string
//go:embed version.txt //go:embed version.txt
var versionNotTrimmed string var versionNotTrimmed string
+32 -32
View File
@@ -1,34 +1,34 @@
{ {
".mp4": { ".mp4": {
"display_name": "MP4", "display_name": "MP4",
"mime_type": "video/mp4" "mime_type": "video/mp4"
}, },
".jpg": { ".jpg": {
"display_name": "JPG", "display_name": "JPG",
"mime_type": "image/jpg" "mime_type": "image/jpg"
}, },
".jpeg": { ".jpeg": {
"display_name": "JPG", "display_name": "JPG",
"mime_type": "image/jpeg" "mime_type": "image/jpeg"
}, },
".png": { ".png": {
"display_name": "PNG", "display_name": "PNG",
"mime_type": "image/png" "mime_type": "image/png"
}, },
".gif": { ".gif": {
"display_name": "GIF", "display_name": "GIF",
"mime_type": "image/gif" "mime_type": "image/gif"
}, },
".pptx": { ".pptx": {
"display_name": "PPTX", "display_name": "PPTX",
"mime_type": "application/vnd.openxmlformats-officedocument.presentationml.presentation" "mime_type": "application/vnd.openxmlformats-officedocument.presentationml.presentation"
}, },
".odp": { ".odp": {
"display_name": "ODP", "display_name": "ODP",
"mime_type": "application/vnd.oasis.opendocument.presentation" "mime_type": ".odp"
}, },
".pdf": { ".pdf": {
"display_name": "PDF", "display_name": "PDF",
"mime_type": "application/pdf" "mime_type": "application/pdf"
} }
} }
+1 -1
View File
@@ -1 +1 @@
v0.0.19 v0.1.3