Files
ai-game-2/tools/ora_editor/templates/editor.html
Bryce fb812e57bc Restructure ORA editor into modular blueprints with browse dialog
- Split app.py into route blueprints (files, layers, images, polygon, mask, krita)
- Create services layer (polygon_storage, comfyui, file_browser)
- Extract config constants to config.py
- Split templates into Jinja partials (base, components, modals)
- Add browse dialog for visual file navigation
- Add /api/browse endpoint for directory listing
2026-03-27 21:29:27 -07:00

782 lines
27 KiB
HTML

{% extends "base.html" %}
{% block body %}
<div x-data="oraEditor()" x-init="init()" class="min-h-screen p-4">
<!-- Header -->
<header class="mb-4 flex items-center gap-4">
<div class="flex-1 flex items-center gap-2">
<input
type="text"
x-model="filePath"
placeholder="Path (e.g., scenes/kq4_010/pic.png)"
class="flex-1 bg-gray-700 border border-gray-600 rounded px-3 py-2 text-white focus:border-blue-500 outline-none"
@keydown.enter="openFile()"
>
<button
@click="openBrowseModal()"
class="bg-gray-600 hover:bg-gray-500 px-3 py-2 rounded transition"
title="Browse files"
>
📁 Browse
</button>
<button
@click="openFile()"
:disabled="!filePath || isLoading"
class="bg-blue-600 hover:bg-blue-700 disabled:bg-gray-600 px-4 py-2 rounded transition flex items-center justify-center gap-2"
>
<span x-show="isLoading" class="animate-spin rounded-full h-4 w-4 border-t-2 border-b-2 border-white"></span>
<span x-text="isLoading ? 'Opening...' : 'Open'"></span>
</button>
</div>
<!-- Krita button -->
<button
@click="openInKrita()"
:disabled="!oraPath || isExtracting"
class="bg-purple-600 hover:bg-purple-700 disabled:bg-gray-600 px-4 py-2 rounded flex items-center gap-2"
title="Open in Krita (Review mode: full ORA; Add mode: base with polygon)"
>
Open in Krita
</button>
<button
@click="saveCurrent()"
:disabled="!oraPath || isLoading"
class="bg-green-600 hover:bg-green-700 disabled:bg-gray-600 px-4 py-2 rounded transition"
>Save</button>
<!-- Save notification -->
<div
x-show="saveNotification"
x-transition
class="fixed top-4 right-4 bg-green-600 text-white px-4 py-2 rounded shadow-lg z-50"
x-text="saveNotification"
></div>
<!-- Scale slider -->
<div x-show="oraPath" class="flex items-center gap-2 bg-gray-800 rounded px-3 py-2 border border-gray-700">
<span class="text-sm text-gray-300">Scale:</span>
<input
type="range"
x-model.number="scale"
min="10"
max="100"
step="5"
class="w-32 accent-blue-500"
>
<span class="text-sm text-gray-300 w-12" x-text="scale + '%'"></span>
</div>
<button @click="showSettings = true" class="bg-gray-700 hover:bg-gray-600 px-4 py-2 rounded transition">⚙️</button>
</header>
<!-- Main content (after file loaded) -->
<template x-if="oraPath">
<div class="flex gap-4">
<!-- SIDEBAR -->
<aside class="w-72 flex-shrink-0 space-y-4">
{% include "components/sidebar.html" %}
</aside>
<!-- MAIN CANVAS AREA -->
{% include "components/canvas.html" %}
</div>
</template>
<!-- No file loaded message -->
<div x-show="!oraPath && !isLoading && !error" class="text-gray-400 text-center mt-20">
<p class="text-xl">Open a PNG or ORA file to start editing</p>
</div>
<!-- Modals -->
{% include "modals/browse.html" %}
{% include "modals/settings.html" %}
{% include "modals/mask_preview.html" %}
{% include "modals/krita.html" %}
</div>
{% endblock %}
{% block scripts %}
<!-- Alpine.js data object -->
<script>
function oraEditor() {
return {
// File state
filePath: '',
oraPath: '',
layers: [],
// Image dimensions
imageWidth: 800,
imageHeight: 600,
// Display scale
scale: 25,
// Mode: 'review' or 'add'
mode: 'review',
// Selected layer for editing
selectedLayer: null,
// Add masked element mode
entityName: '',
// Polygon state
isDrawing: false,
polygonPoints: [],
polygonColor: '#FF0000',
polygonWidth: 2,
polygonPreviewUrl: null,
// Mask extraction
maskSubject: '',
usePolygonHint: true,
isExtracting: false,
maskViewMode: 'with-bg',
showMaskModal: false,
tempMaskPath: null,
tempMaskUrl: null,
lastError: '',
// Settings
showSettings: false,
comfyUrl: localStorage.getItem('ora_comfy_url') || '127.0.0.1:8188',
saveNotification: null,
// Krita modal
showKritaModal: false,
kritaTempPath: null,
kritaPathCopied: false,
// Browse modal
showBrowseModal: false,
browsePath: '',
browseDirectories: [],
browseFiles: [],
browseSelectedPath: null,
// Loading/error
isLoading: false,
error: '',
init() {
console.log('ORA Editor initialized');
this.setupKeyHandlers();
},
setupKeyHandlers() {
document.addEventListener('keydown', (e) => {
if (e.key === 'Escape' && this.isDrawing) this.clearPolygon();
if (e.key === 'Enter' && this.isDrawing && this.polygonPoints.length >= 3) this.finishDrawing();
});
},
// === File Browser ===
async openBrowseModal() {
this.browsePath = '';
this.browseSelectedPath = null;
await this.loadBrowseDirectory('');
this.showBrowseModal = true;
},
closeBrowseModal() {
this.showBrowseModal = false;
},
async loadBrowseDirectory(path) {
try {
const response = await fetch('/api/browse?path=' + encodeURIComponent(path));
const data = await response.json();
if (data.success) {
this.browsePath = data.current_path;
this.browseDirectories = data.directories;
this.browseFiles = data.files;
} else {
console.error('Browse error:', data.error);
}
} catch (e) {
console.error('Browse error:', e);
}
},
navigateBrowseDirectory(path) {
this.browseSelectedPath = null;
this.loadBrowseDirectory(path);
},
navigateBrowseParent() {
const parent = this.browsePath.split('/').slice(0, -1).join('/');
this.browseSelectedPath = null;
this.loadBrowseDirectory(parent);
},
selectBrowseFile(file) {
this.browseSelectedPath = file.path;
},
openBrowseFile(file) {
this.filePath = file.path;
this.showBrowseModal = false;
this.openFile();
},
openSelectedFile() {
if (this.browseSelectedPath) {
this.filePath = this.browseSelectedPath;
this.showBrowseModal = false;
this.openFile();
}
},
// === File Operations ===
async openFile() {
if (!this.filePath || this.isLoading) return;
console.log('[ORA EDITOR] Opening file:', this.filePath);
this.isLoading = true;
this.error = '';
try {
const response = await fetch('/api/open', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ path: this.filePath })
});
const data = await response.json();
console.log('[ORA EDITOR] File opened:', data);
if (!data.success) throw new Error(data.error || 'Failed to open file');
this.oraPath = data.ora_path;
this.layers = data.layers.map(layer => ({
...layer,
visible: true
}));
this.imageWidth = data.width;
this.imageHeight = data.height;
this.mode = 'review';
this.clearPolygon();
} catch (e) {
console.error('[ORA EDITOR] Error opening file:', e);
this.error = e.message;
} finally {
this.isLoading = false;
}
},
async saveCurrent() {
if (!this.oraPath) return;
let savePath = this.oraPath;
const response = await fetch('/api/save', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ ora_path: savePath })
});
const data = await response.json();
if (data.success) {
this.saveNotification = 'Saved to ' + savePath;
setTimeout(() => { this.saveNotification = null; }, 3000);
} else {
alert('Error saving: ' + data.error);
}
},
// === Mode Management ===
enterAddMode() {
console.log('[ORA EDITOR] Entering add masked element mode');
this.mode = 'add';
this.entityName = '';
this.maskSubject = '';
this.clearPolygon();
this.scale = 100;
},
exitAddMode() {
console.log('[ORA EDITOR] Exiting add masked element mode');
this.mode = 'review';
this.isDrawing = false;
this.polygonPoints = [];
this.polygonPreviewUrl = null;
const canvas = document.getElementById('polygonCanvas');
if (canvas) {
canvas.style.display = 'none';
}
},
async cancelAddMode() {
if (this.isDrawing) {
this.clearPolygon();
} else {
this.exitAddMode();
}
},
// === Layer Operations ===
async toggleVisibility(layerName, visible) {
const idx = this.layers.findIndex(l => l.name === layerName);
if (idx >= 0) {
this.layers[idx].visible = visible;
}
await fetch('/api/layer/visibility', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
ora_path: this.oraPath,
layer_name: layerName,
visible: visible
})
});
},
async renameLayer() {
const oldName = this.selectedLayer;
const newName = prompt('New layer name:', this.selectedLayer);
if (!newName || newName === oldName) return;
const layer = this.layers.find(l => l.name === oldName);
if (layer) layer.name = newName;
this.selectedLayer = newName;
await fetch('/api/layer/rename', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
ora_path: this.oraPath,
old_name: oldName,
new_name: newName
})
});
},
async deleteLayer() {
const layerToDelete = this.selectedLayer;
if (!confirm(`Delete layer "${layerToDelete}"?`)) return;
const idx = this.layers.findIndex(l => l.name === layerToDelete);
if (idx > -1) this.layers.splice(idx, 1);
this.selectedLayer = null;
await fetch('/api/layer/delete', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
ora_path: this.oraPath,
layer_name: layerToDelete
})
});
},
async reorderLayer(direction) {
if (!this.selectedLayer) return;
const idx = this.layers.findIndex(l => l.name === this.selectedLayer);
if (idx < 0) return;
const newIdx = direction === 'up' ? idx - 1 : idx + 1;
if (newIdx < 0 || newIdx >= this.layers.length) return;
const layerName = this.selectedLayer;
[this.layers[idx], this.layers[newIdx]] = [this.layers[newIdx], this.layers[idx]];
await fetch('/api/layer/reorder', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
ora_path: this.oraPath,
layer_name: layerName,
direction: direction
})
});
},
// === Polygon Drawing ===
startDrawing() {
console.log('[ORA EDITOR] Starting polygon drawing mode');
this.isDrawing = true;
this.polygonPoints = [];
canvasDoubleClickPending = false;
this.polygonPreviewUrl = null;
setTimeout(() => {
this.setupCanvas();
const canvas = document.getElementById('polygonCanvas');
if (canvas) {
canvas.style.display = 'block';
}
}, 50);
},
setupCanvas() {
const canvas = document.getElementById('polygonCanvas');
if (!canvas) return;
canvas.width = this.imageWidth;
canvas.height = this.imageHeight;
},
addPolygonPoint(x, y) {
if (!this.isDrawing) return;
x = Math.max(-0.1, Math.min(1.1, x));
y = Math.max(-0.1, Math.min(1.1, y));
this.polygonPoints.push({ x, y });
this.drawPolygonOnCanvas();
},
startDragPoint(e, idx) {
e.preventDefault();
e.stopPropagation();
const container = document.getElementById('imageContainer');
if (!container) return;
const moveHandler = (moveEvent) => {
const rect = container.getBoundingClientRect();
let x, y;
if (moveEvent.touches) {
x = (moveEvent.touches[0].clientX - rect.left) / rect.width;
y = (moveEvent.touches[0].clientY - rect.top) / rect.height;
} else {
x = (moveEvent.clientX - rect.left) / rect.width;
y = (moveEvent.clientY - rect.top) / rect.height;
}
x = Math.max(-0.1, Math.min(1.1, x));
y = Math.max(-0.1, Math.min(1.1, y));
this.polygonPoints[idx] = { x, y };
this.drawPolygonOnCanvas();
};
const upHandler = () => {
document.removeEventListener('mousemove', moveHandler);
document.removeEventListener('mouseup', upHandler);
document.removeEventListener('touchmove', moveHandler);
document.removeEventListener('touchend', upHandler);
if (this.polygonPoints.length >= 3) {
this.updatePolygonPreview();
}
};
document.addEventListener('mousemove', moveHandler);
document.addEventListener('mouseup', upHandler);
document.addEventListener('touchmove', moveHandler);
document.addEventListener('touchend', upHandler);
},
drawPolygonOnCanvas() {
const canvas = document.getElementById('polygonCanvas');
if (!canvas || this.polygonPoints.length < 2) return;
const ctx = canvas.getContext('2d');
if (!ctx) return;
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.beginPath();
ctx.strokeStyle = this.polygonColor;
ctx.lineWidth = this.polygonWidth;
ctx.lineCap = 'round';
ctx.lineJoin = 'round';
const startPoint = this.polygonPoints[0];
ctx.moveTo(startPoint.x * canvas.width, startPoint.y * canvas.height);
for (let i = 1; i < this.polygonPoints.length; i++) {
const point = this.polygonPoints[i];
ctx.lineTo(point.x * canvas.width, point.y * canvas.height);
}
if (this.polygonPoints.length >= 3) {
ctx.closePath();
}
ctx.stroke();
ctx.fillStyle = '#FFFFFF';
for (const point of this.polygonPoints) {
const px = point.x * canvas.width;
const py = point.y * canvas.height;
ctx.beginPath();
ctx.arc(px, py, 6, 0, Math.PI * 2);
ctx.fill();
ctx.beginPath();
ctx.strokeStyle = this.polygonColor;
ctx.lineWidth = 2;
ctx.arc(px, py, 6, 0, Math.PI * 2);
ctx.stroke();
}
},
async updatePolygonPreview() {
console.log('[UPDATE] Updating preview with', this.polygonPoints.length, 'points');
if (!this.oraPath || this.polygonPoints.length < 3) return;
const response = await fetch('/api/polygon', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
ora_path: this.oraPath,
points: [...this.polygonPoints],
color: this.polygonColor,
width: this.polygonWidth
})
});
if (response.ok) {
const data = await response.json();
this.polygonPreviewUrl = data.overlay_url + '&ts=' + Date.now();
}
},
async finishDrawing() {
console.log('[FINISH] finishDrawing called');
if (this.polygonPoints.length >= 3) {
await this.updatePolygonPreview();
this.isDrawing = false;
const canvas = document.getElementById('polygonCanvas');
if (canvas) {
canvas.style.display = 'none';
}
} else {
this.clearPolygon();
}
},
clearPolygon() {
this.isDrawing = false;
this.polygonPoints = [];
this.polygonPreviewUrl = null;
const canvas = document.getElementById('polygonCanvas');
if (canvas) {
canvas.style.display = 'none';
const ctx = canvas.getContext('2d');
if (ctx) {
ctx.clearRect(0, 0, canvas.width, canvas.height);
}
}
if (this.oraPath) {
fetch('/api/polygon/clear', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ ora_path: this.oraPath })
});
}
},
// === Mask Extraction ===
async extractMask() {
if (!this.maskSubject.trim()) return;
console.log('[ORA EDITOR] Extracting mask for:', this.maskSubject);
this.isExtracting = true;
this.lastError = '';
try {
const response = await fetch('/api/mask/extract', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
subject: this.maskSubject,
use_polygon: this.usePolygonHint && this.polygonPoints.length >= 3,
ora_path: this.oraPath,
comfy_url: this.comfyUrl
})
});
const data = await response.json();
console.log('[ORA EDITOR] Mask extraction response:', data);
if (!data.success) throw new Error(data.error || 'Failed');
this.tempMaskPath = data.mask_path;
this.tempMaskUrl = data.mask_url || '/api/file/mask?path=' + encodeURIComponent(data.mask_path);
this.showMaskModal = true;
} catch (e) {
console.error('[ORA EDITOR] Error extracting mask:', e);
this.lastError = e.message;
} finally {
this.isExtracting = false;
}
},
rerollMask() {
this.extractMask();
},
async useMask() {
if (!this.tempMaskPath) return;
let finalEntityName = this.entityName || 'element';
const existingLayers = this.layers.filter(l => l.name.startsWith(finalEntityName + '_'));
let counter = 0;
while (existingLayers.some(l => l.name === `${finalEntityName}_${counter}`)) {
counter++;
}
finalEntityName = `${finalEntityName}_${counter}`;
console.log('[ORA EDITOR] Adding layer:', finalEntityName);
await fetch('/api/layer/add', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
ora_path: this.oraPath,
entity_name: finalEntityName,
mask_path: this.tempMaskPath
})
});
const response = await fetch('/api/layers?ora_path=' + encodeURIComponent(this.oraPath));
const data = await response.json();
if (data.success) {
this.layers = data.layers.map(layer => ({
...layer,
visible: true
}));
}
this.closeMaskModal();
this.exitAddMode();
},
closeMaskModal() {
this.showMaskModal = false;
this.tempMaskPath = null;
this.tempMaskUrl = null;
},
// === Krita Integration ===
async openInKrita() {
if (!this.oraPath) return;
let requestBody;
if (this.mode === 'review') {
requestBody = {
ora_path: this.oraPath,
open_full_ora: true
};
} else {
requestBody = {
ora_path: this.oraPath,
open_base_with_polygon: true,
points: this.polygonPoints,
color: this.polygonColor,
width: this.polygonWidth
};
}
const response = await fetch('/api/krita/open', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(requestBody)
});
const data = await response.json();
if (data.success) {
this.kritaTempPath = data.temp_path;
this.showKritaModal = true;
} else {
alert('Error: ' + data.error);
}
},
copyKritaPath() {
if (this.kritaTempPath) {
navigator.clipboard.writeText(this.kritaTempPath);
this.kritaPathCopied = true;
setTimeout(() => { this.kritaPathCopied = false; }, 2000);
}
},
closeKritaModal() {
this.showKritaModal = false;
this.kritaTempPath = null;
this.kritaPathCopied = false;
},
// === Settings ===
saveSettings() {
localStorage.setItem('ora_comfy_url', this.comfyUrl);
this.showSettings = false;
}
};
}
</script>
<!-- Custom JS for canvas click handling -->
<script>
let canvasDoubleClickPending = false;
document.addEventListener('alpine:init', () => {
const observer = new MutationObserver(() => {
const canvas = document.getElementById('polygonCanvas');
if (canvas && !canvas.hasAttribute('data-handlers-setup')) {
canvas.setAttribute('data-handlers-setup', 'true');
canvas.addEventListener('click', (e) => {
if (canvasDoubleClickPending) return;
const container = document.getElementById('imageContainer');
if (!container) return;
const rect = container.getBoundingClientRect();
let x = (e.clientX - rect.left) / rect.width;
let y = (e.clientY - rect.top) / rect.height;
x = Math.max(-0.1, Math.min(1.1, x));
y = Math.max(-0.1, Math.min(1.1, y));
const alpineEl = container.closest('[x-data]');
if (!alpineEl) return;
const store = Alpine.$data(alpineEl);
if (store && store.isDrawing) {
store.addPolygonPoint(x, y);
}
});
canvas.addEventListener('dblclick', (e) => {
e.preventDefault();
canvasDoubleClickPending = true;
const container = document.getElementById('imageContainer');
if (!container) return;
const alpineEl = container.closest('[x-data]');
if (!alpineEl) return;
const store = Alpine.$data(alpineEl);
if (store && store.isDrawing && store.polygonPoints.length >= 3) {
store.finishDrawing();
}
});
setTimeout(() => { canvasDoubleClickPending = false; }, 200);
}
});
observer.observe(document.body, { childList: true, subtree: true });
});
</script>
{% endblock %}