Run openscad from /home (w/ symlinks to libs) and force user files to relative

This commit is contained in:
ochafik 2023-03-26 22:33:14 +01:00
commit bcebd5ae00
10 changed files with 68 additions and 122 deletions

View file

@ -6,14 +6,12 @@ import openscadEditorOptions from '../language/openscad-editor-options';
import * as monaco from 'monaco-editor/esm/vs/editor/editor.api';
import { Button } from 'primereact/button';
import { MenuItem } from 'primereact/menuitem';
import { TreeSelect } from 'primereact/treeselect';
import TreeNode from 'primereact/treenode';
import { Menu } from 'primereact/menu';
import { getParentDir, librariesFolder } from '../fs/filesystem';
import { buildUrlForStateParams } from '../state/fragment-state';
import { blankProjectState } from '../state/initial-state';
import { ModelContext, FSContext } from './contexts';
import FilePicker, { isFileWritable } from './FilePicker';
import FilePicker, { } from './FilePicker';
import { isFileWritable } from '../state/model';
// import "primereact/resources/themes/lara-light-indigo/theme.css";
// import "primereact/resources/primereact.min.css";
@ -22,46 +20,6 @@ import FilePicker, { isFileWritable } from './FilePicker';
let monacoInstance: Monaco
loader.init().then(mi => monacoInstance = mi);
// const isFileWritable = (path: string) => getParentDir(path) === '/home'
// function listFilesAsNodes(fs: FS, path: string): TreeNode[] {
// const files: [string, string][] = []
// const dirs: [string, string][] = []
// for (const name of fs.readdirSync(path)) {
// if (name.startsWith('.')) {
// continue;
// }
// const childPath = `${path}/${name}`;
// const stat = fs.lstatSync(childPath);
// const isDirectory = stat.isDirectory();
// if (!isDirectory && !name.endsWith('.scad')) {
// continue;
// }
// (isDirectory ? dirs : files).push([name, childPath]);
// }
// [files, dirs].forEach(arr => arr.sort(([a], [b]) => a.localeCompare(b)));
// const nodes: TreeNode[] = []
// for (const [arr, isDirectory] of [[files, false], [dirs, true]] as [[string, string][], boolean][]) {
// for (const [name, path] of arr) {
// const children = isDirectory ? listFilesAsNodes(fs, path) : undefined;
// if (isDirectory && children!.length == 0) {
// continue;
// }
// nodes.push({
// // icon: path == '/home' ? 'pi-home' : ...
// icon: isDirectory ? 'pi pi-folder' : isFileWritable(path) ? 'pi pi-file' : 'pi pi-lock',
// label: name,
// data: path,
// key: path,
// children,
// selectable: !isDirectory // && (name == 'LICENSE' || name.endsWith('.scad') || name.endsWith('.scad')
// });
// }
// }
// return nodes;
// }
export default function EditorPanel({className, style}: {className?: string, style?: CSSProperties}) {
const model = useContext(ModelContext);
@ -71,9 +29,7 @@ export default function EditorPanel({className, style}: {className?: string, sty
const state = model.state;
// const fs = useContext(FSContext);
const [editor, setEditor] = useState(null as monaco.editor.IStandaloneCodeEditor | null)
// const [modelFile, setModelFile] = useState(state.params.sourcePath);
if (editor) {
const checkerRun = state.lastCheckerRun;

View file

@ -3,12 +3,8 @@
import { CSSProperties, useContext } from 'react';
import { TreeSelect } from 'primereact/treeselect';
import TreeNode from 'primereact/treenode';
import { getParentDir, librariesFolder } from '../fs/filesystem';
import { ModelContext, FSContext } from './contexts';
export const isFileWritable = (path: string) => getParentDir(path) === '/home'
// export const isFileWritable = (path: string) => !path.startsWith(librariesFolder + '/');
import { isFileWritable } from '../state/model';
function listFilesAsNodes(fs: FS, path: string, accept?: (path: string) => boolean): TreeNode[] {
const files: [string, string][] = []
@ -58,23 +54,7 @@ export default function FilePicker({className, style}: {className?: string, styl
const fs = useContext(FSContext);
const fsItems = fs && [
{
icon: 'pi pi-home',
label: 'User files',
key: '/home',
children: listFilesAsNodes(fs, '/home'),//
// children: listFilesAsNodes(fs, '/', f => f != librariesFolder && !f.startsWith(`${librariesFolder}/`)),
selectable: false
},
{
icon: 'pi pi-database',
label: 'Builtin libraries',
key: librariesFolder,
children: listFilesAsNodes(fs, librariesFolder),
selectable: false
},
] || [];
const fsItems = fs && listFilesAsNodes(fs, '/home')
return (
<TreeSelect

View file

@ -94,24 +94,32 @@ export default function Footer({style}: {style?: CSSProperties}) {
title="Render the model (F6 / Ctrl+Enter). Models can test $preview to enable more detail in renders only."
label="Render" />
{/* {state.error != null &&
<i className="pi pi-exclamation-circle" style={{color: 'red'}} title={state.error}></i>} */}
{(state.lastCheckerRun || state.output) &&
<Button type="button"
// label={state.view.logs ? "Hide logs" : "Show logs"}
label="Logs"
icon="pi pi-align-left"
text={!state.view.logs}
onClick={() => model.logsVisible = !state.view.logs}
// onLabel="Logs" offLabel="Logs"
// onIcon="pi pi-align-left"
// offIcon="pi pi-align-left"
className={maxMarkerSeverity && `p-button-${severityByMarkerSeverity.get(maxMarkerSeverity) ?? 'success'}`}
>
{getBadge(monaco.MarkerSeverity.Error)}
{getBadge(monaco.MarkerSeverity.Warning)}
{getBadge(monaco.MarkerSeverity.Info)}
</Button>}
<Button type="button"
// label={state.view.logs ? "Hide logs" : "Show logs"}
label="Logs"
icon="pi pi-align-left"
text={!state.view.logs}
onClick={() => model.logsVisible = !state.view.logs}
// onLabel="Logs" offLabel="Logs"
// onIcon="pi pi-align-left"
// offIcon="pi pi-align-left"
className={maxMarkerSeverity && `p-button-${severityByMarkerSeverity.get(maxMarkerSeverity) ?? 'success'}`}
>
{getBadge(monaco.MarkerSeverity.Error)}
{getBadge(monaco.MarkerSeverity.Warning)}
{getBadge(monaco.MarkerSeverity.Info)}
</Button>
{state.output && (
<Button icon='pi pi-download'
title={`Download ${state.output.isPreview ? "preview.stl" : "render.stl"} (${state.output.formattedStlFileSize})`}
severity="secondary"
text
// label={state.output.isPreview ? "preview.stl" : "render.stl"}
iconPos='right'
onClick={() => downloadOutput(state)} />
)}
{/* {state.output &&
<span style={{color: 'blue'}}>
@ -130,24 +138,6 @@ export default function Footer({style}: {style?: CSSProperties}) {
<ConfirmDialog />
<Toast ref={toast} />
{state.output && (
<Button icon='pi pi-download'
title={`Download ${state.output.isPreview ? "preview.stl" : "render.stl"} (${state.output.formattedStlFileSize})`}
severity="secondary"
text
// label={state.output.isPreview ? "preview.stl" : "render.stl"}
iconPos='right'
onClick={() => downloadOutput(state)} />
// <a href={state.output.stlFileURL}
// target="_blank"
// download={state.output.isPreview ? "preview.stl" : "render.stl"}
// title="STL Download">
// {state.output.isPreview ? "preview.stl" : "render.stl"} ({state.output.formattedStlFileSize})
// </a>
)}
<SettingsMenu />
<HelpMenu />
</div>

View file

@ -5,6 +5,7 @@ import { SingleLayoutComponentId } from '../state/app-state'
import { TabMenu } from 'primereact/tabmenu';
import { ToggleButton } from 'primereact/togglebutton';
import { ModelContext, FSContext } from './contexts';
import SettingsMenu from './SettingsMenu';
export default function PanelSwitcher() {
const model = useContext(ModelContext);
@ -49,15 +50,18 @@ export default function PanelSwitcher() {
/>
)}
</div>
: <TabMenu
: <>
<TabMenu
activeIndex={singleTargets.map(t => t.id).indexOf(state.view.layout.focus)}
style={{
flex: 1,
// justifyContent: 'center'
}}
model={singleTargets.map(({icon, label, id}) =>
({icon, label, disabled: id === 'customizer', command: () => model.changeSingleVisibility(id)}))} />
({icon, label, disabled: id === 'customizer', command: () => model.changeSingleVisibility(id)}))} />
</>
}
<SettingsMenu />
</div>
</div>
);

View file

@ -2,8 +2,6 @@
import { zipArchives } from "./zip-archives";
export const librariesFolder = '/libraries'
declare var BrowserFS: BrowserFSInterface
export type FSMounts = {
@ -13,6 +11,7 @@ export type FSMounts = {
export type Symlinks = {[alias: string]: string};
export const getParentDir = (path: string) => path.split('/').slice(0, -1).join('/');
export const getFileName = (path: string) => path.split('/').splice(-1)[0];
export function readDirAsArray(fs: FS, path: string): Promise<string[] | undefined> {
return new Promise((res, rej) => fs.readdir(path, (err, files) => err ? rej(err) : res(files)));
@ -74,12 +73,12 @@ function configureAndInstallFS(windowOrSelf: Window, options: any) {
});
}
export async function createEditorFS(workingDir='/home'): Promise<FS> {
export async function createEditorFS(prefix: string): Promise<FS> {
const archiveNames = Object.keys(zipArchives);
const librariesMounts = await getBrowserFSLibrariesMounts(archiveNames);
const allMounts: FSMounts = {};
for (const n in librariesMounts) {
allMounts[`${workingDir}/${n}`] = librariesMounts[n];
allMounts[`${prefix}${n}`] = librariesMounts[n];
}
await configureAndInstallFS(typeof window === 'object' && window || self, {

View file

@ -26,8 +26,8 @@ export const checkSyntax =
const result = await job;
// console.log(result);
res(processMergedOutputs(result.mergedOutputs, {shiftSourceLines: {
[sourcePath]: 1,
[sourcePath.split('/').slice(-1)[0]]: 1
sourcePath,
skipLines: 1,
}}));
} catch (e) {
console.error(e);
@ -52,7 +52,7 @@ export const render =
turnIntoDelayableExecution(renderDelay, (params: RenderArgs) => {
const args = [
params.sourcePath,
"-o", "/home/out.stl",
"-o", "out.stl",
"--export-format=binstl",
...(params.features ?? []).map(f => `--enable=${f}`),
...(params.extraArgs ?? [])
@ -68,7 +68,7 @@ export const render =
// wasmMemory,
inputs: [[params.sourcePath, source]],
args,
outputPaths: ['/home/out.stl']
outputPaths: ['out.stl']
});
return AbortablePromise<RenderOutput>((resolve, reject) => {
@ -79,8 +79,8 @@ export const render =
const {logText, markers} = processMergedOutputs(result.mergedOutputs, {
shiftSourceLines: {
[params.sourcePath]: prefixLines.length,
[params.sourcePath.split('/').slice(-1)[0]]: prefixLines.length
sourcePath: params.sourcePath,
skipLines: prefixLines.length
}
});

View file

@ -2,7 +2,7 @@
import OpenSCAD from "../wasm/openscad.js";
import { createEditorFS, getBrowserFSLibrariesMounts, librariesFolder, symlinkLibraries } from "../fs/filesystem";
import { createEditorFS, getBrowserFSLibrariesMounts, symlinkLibraries } from "../fs/filesystem";
import { OpenSCADInvocation, OpenSCADInvocationResults } from "./openscad-runner";
import { zipArchives } from "../fs/zip-archives";
declare var BrowserFS: BrowserFSInterface
@ -17,7 +17,7 @@ export type MergedOutputs = {stdout?: string, stderr?: string, error?: string}[]
addEventListener('message', async (e) => {
const { inputs, args, outputPaths, wasmMemory, workingDir } = e.data as OpenSCADInvocation;
const { inputs, args, outputPaths, wasmMemory } = e.data as OpenSCADInvocation;
const mergedOutputs: MergedOutputs = [];
try {

View file

@ -1,4 +1,5 @@
import * as monaco from 'monaco-editor/esm/vs/editor/editor.api';
import { getFileName } from '../fs/filesystem';
import { MergedOutputs } from "./openscad-worker";
const ignoredLogs = new Set([
@ -6,7 +7,10 @@ const ignoredLogs = new Set([
]);
type MergedOutputsOptions = {
shiftSourceLines: {[path: string]: number}
shiftSourceLines?: {
sourcePath: string,
skipLines: number,
}
}
export const processMergedOutputs = (outputs: MergedOutputs, opts: MergedOutputsOptions) => ({
logText: joinMergedOutputs(outputs, opts),
@ -41,9 +45,14 @@ export function parseMergedOutputs(mergedOutputs: MergedOutputs, opts: MergedOut
severity: monaco.MarkerSeverity.Error
})
}
const shiftSourceName = opts.shiftSourceLines && getFileName(opts.shiftSourceLines.sourcePath);
const getLine = (path: string, lineStr: string) => {
const shift = opts.shiftSourceLines[path] ?? 0;
return Number(lineStr) - shift;
const line = Number(lineStr);
if (shiftSourceName && getFileName(path) == shiftSourceName) {
return line - opts.shiftSourceLines!.skipLines;
} else {
return line;
}
}
for (const {stderr, stdout, error} of mergedOutputs){
if (stderr) {

View file

@ -3,7 +3,7 @@
import defaultScad from './default-scad';
import { State } from './app-state';
export const defaultSourcePath = '/home/playground.scad';
export const defaultSourcePath = 'playground.scad';
export const blankProjectState: State = {
params: {

View file

@ -5,6 +5,11 @@ import { MultiLayoutComponentId, SingleLayoutComponentId, State } from "./app-st
import { bubbleUpDeepMutations } from "./deep-mutate";
import { writeStateInFragment } from "./fragment-state";
import { formatBytes, formatMillis } from '../utils'
import { getParentDir } from "../fs/filesystem";
// export const isFileWritable = (path: string) => !path.startsWith('/');
export const isFileWritable = (path: string) => getParentDir(path) === '/home';
// export const isFileWritable = (path: string) => !path.startsWith(librariesFolder + '/');
export class Model {
constructor(private fs: FS, public state: State, private setStateCallback?: (state: State) => void) {
@ -105,7 +110,10 @@ export class Model {
private processSource() {
const params = this.state.params;
// this.fs.writeFile(params.sourcePath, params.source);
if (isFileWritable(params.sourcePath)) {
const absolutePath = `/home/${params.sourcePath}`;
this.fs.writeFile(absolutePath, params.source);
}
this.checkSyntax();
this.render({isPreview: true, now: false});
}