1347 lines
47 KiB
JavaScript
1347 lines
47 KiB
JavaScript
// ===== GLOBAL STATE =====
|
||
let currentImage = null;
|
||
let currentRectangles = [];
|
||
let currentCoordinateString = '';
|
||
let currentFileName = '';
|
||
let canvas = null;
|
||
let ctx = null;
|
||
|
||
let batchFiles = [];
|
||
let batchResults = [];
|
||
let isProcessingBatch = false;
|
||
let currentBatchDetailIndex = -1; // New State for tracking detail view
|
||
let detailCanvas = null;
|
||
let detailCtx = null;
|
||
let detailImage = null;
|
||
|
||
// Drawing Mode State
|
||
let isDrawingMode = false;
|
||
let isDrawing = false;
|
||
let startX = 0;
|
||
let startY = 0;
|
||
let drawingRect = null;
|
||
|
||
// Batch Drawing State
|
||
let isBatchDrawingMode = false;
|
||
let isBatchDrawing = false;
|
||
let batchStartX = 0;
|
||
let batchStartY = 0;
|
||
|
||
// ===== INITIALIZATION =====
|
||
document.addEventListener('DOMContentLoaded', function () {
|
||
// Initialize canvas
|
||
canvas = document.getElementById('imageCanvas');
|
||
ctx = canvas.getContext('2d');
|
||
|
||
// Initialize Detail Canvas
|
||
detailCanvas = document.getElementById('detailCanvas');
|
||
detailCtx = detailCanvas.getContext('2d');
|
||
|
||
// Setup event listeners
|
||
setupEventListeners();
|
||
|
||
// Load format settings from localStorage
|
||
FormatManager.load();
|
||
|
||
// Load initial results
|
||
loadResults();
|
||
|
||
// Check server health
|
||
checkServerHealth();
|
||
|
||
// Canvas Mouse Events for Drawing
|
||
canvas.addEventListener('mousedown', handleMouseDown);
|
||
canvas.addEventListener('mousemove', handleMouseMove);
|
||
canvas.addEventListener('mouseup', handleMouseUp);
|
||
|
||
// Detail Canvas Mouse Events
|
||
detailCanvas.addEventListener('mousedown', handleBatchMouseDown);
|
||
detailCanvas.addEventListener('mousemove', handleBatchMouseMove);
|
||
detailCanvas.addEventListener('mouseup', handleBatchMouseUp);
|
||
});
|
||
|
||
// ===== EVENT LISTENERS SETUP =====
|
||
function setupEventListeners() {
|
||
// File input
|
||
const fileInput = document.getElementById('fileInput');
|
||
if (fileInput) {
|
||
fileInput.addEventListener('change', handleFileSelect);
|
||
}
|
||
|
||
// Folder input
|
||
const folderInput = document.getElementById('folderInput');
|
||
if (folderInput) {
|
||
folderInput.addEventListener('change', handleFolderSelect);
|
||
}
|
||
|
||
// Drag and drop
|
||
const uploadArea = document.getElementById('uploadArea');
|
||
if (uploadArea) {
|
||
uploadArea.addEventListener('dragover', handleDragOver);
|
||
uploadArea.addEventListener('dragleave', handleDragLeave);
|
||
uploadArea.addEventListener('drop', handleDrop);
|
||
}
|
||
}
|
||
|
||
// ===== DRAG AND DROP HANDLERS =====
|
||
function handleDragOver(e) {
|
||
e.preventDefault();
|
||
e.stopPropagation();
|
||
e.currentTarget.classList.add('drag-over');
|
||
}
|
||
|
||
function handleDragLeave(e) {
|
||
e.preventDefault();
|
||
e.stopPropagation();
|
||
e.currentTarget.classList.remove('drag-over');
|
||
}
|
||
|
||
function handleDrop(e) {
|
||
e.preventDefault();
|
||
e.stopPropagation();
|
||
e.currentTarget.classList.remove('drag-over');
|
||
|
||
const files = e.dataTransfer.files;
|
||
if (files.length > 0) {
|
||
const file = files[0];
|
||
if (file.type.startsWith('image/')) {
|
||
loadImageFile(file);
|
||
} else {
|
||
showMessage('Please drop an image file', 'error');
|
||
}
|
||
}
|
||
}
|
||
|
||
// ===== FILE HANDLING =====
|
||
function handleFileSelect(e) {
|
||
const file = e.target.files[0];
|
||
if (file) {
|
||
loadImageFile(file);
|
||
}
|
||
}
|
||
|
||
function handleFolderSelect(e) {
|
||
const files = Array.from(e.target.files);
|
||
batchFiles = files.filter(file => file.type.startsWith('image/'));
|
||
|
||
if (batchFiles.length > 0) {
|
||
const folderName = batchFiles[0].webkitRelativePath.split('/')[0];
|
||
document.getElementById('batchStatus').innerHTML = `
|
||
<i class="fas fa-folder" style="color: #667eea;"></i>
|
||
<strong>Selected Folder:</strong> ${folderName}<br>
|
||
<strong>Images Found:</strong> ${batchFiles.length} files
|
||
`;
|
||
document.getElementById('progressContainer').style.display = 'block';
|
||
document.getElementById('batchResults').style.display = 'block';
|
||
document.getElementById('batchResultsList').innerHTML = '';
|
||
|
||
showMessage(`Found ${batchFiles.length} images in folder`, 'info');
|
||
} else {
|
||
showMessage('No image files found in selected folder', 'error');
|
||
}
|
||
}
|
||
|
||
function loadImageFile(file) {
|
||
const reader = new FileReader();
|
||
reader.onload = function (e) {
|
||
const img = new Image();
|
||
img.onload = function () {
|
||
displayImage(img);
|
||
currentFileName = file.name;
|
||
};
|
||
img.onerror = function () {
|
||
showMessage('Failed to load image', 'error');
|
||
};
|
||
img.src = e.target.result;
|
||
};
|
||
reader.readAsDataURL(file);
|
||
}
|
||
|
||
function displayImage(img) {
|
||
currentImage = img;
|
||
canvas.width = img.width;
|
||
canvas.height = img.height;
|
||
ctx.clearRect(0, 0, canvas.width, canvas.height);
|
||
ctx.drawImage(img, 0, 0);
|
||
|
||
document.getElementById('emptyState').style.display = 'none';
|
||
canvas.style.display = 'block';
|
||
|
||
currentRectangles = [];
|
||
updateCoordinatesList();
|
||
showMessage('Image loaded successfully', 'info');
|
||
}
|
||
|
||
// ===== IMAGE ANALYSIS =====
|
||
function analyzeImage() {
|
||
if (!currentImage) {
|
||
showMessage('Please select an image first', 'error');
|
||
return;
|
||
}
|
||
|
||
showLoading(true);
|
||
const analyzeBtn = document.getElementById('analyzeBtn');
|
||
analyzeBtn.disabled = true;
|
||
|
||
canvas.toBlob(function (blob) {
|
||
if (!blob) {
|
||
showMessage('Failed to process image', 'error');
|
||
showLoading(false);
|
||
analyzeBtn.disabled = false;
|
||
return;
|
||
}
|
||
|
||
const formData = new FormData();
|
||
formData.append('file', blob, currentFileName || 'image.png');
|
||
|
||
fetch('/upload', {
|
||
method: 'POST',
|
||
body: formData
|
||
})
|
||
.then(response => {
|
||
if (!response.ok) {
|
||
throw new Error(`HTTP error! status: ${response.status}`);
|
||
}
|
||
return response.json();
|
||
})
|
||
.then(data => {
|
||
if (data.success) {
|
||
currentRectangles = data.rectangles || [];
|
||
currentCoordinateString = data.coordinate_string || '';
|
||
|
||
if (data.image_url && currentRectangles.length > 0) {
|
||
const processedImg = new Image();
|
||
processedImg.onload = function () {
|
||
canvas.width = processedImg.width;
|
||
canvas.height = processedImg.height;
|
||
ctx.clearRect(0, 0, canvas.width, canvas.height);
|
||
ctx.drawImage(processedImg, 0, 0);
|
||
|
||
updateCoordinatesList();
|
||
document.getElementById('saveBtn').disabled = false;
|
||
showMessage(`Found ${currentRectangles.length} frame(s)`, 'success');
|
||
};
|
||
processedImg.onerror = function () {
|
||
showMessage('Failed to load processed image', 'error');
|
||
};
|
||
processedImg.src = data.image_url + '?t=' + new Date().getTime();
|
||
} else {
|
||
showMessage('No PNG frames detected', 'error');
|
||
updateCoordinatesList();
|
||
}
|
||
} else {
|
||
showMessage(data.error || 'Analysis failed', 'error');
|
||
}
|
||
})
|
||
.catch(error => {
|
||
console.error('Error:', error);
|
||
showMessage('Error: ' + error.message, 'error');
|
||
})
|
||
.finally(() => {
|
||
showLoading(false);
|
||
analyzeBtn.disabled = false;
|
||
});
|
||
}, 'image/png');
|
||
}
|
||
|
||
// ===== COORDINATES DISPLAY =====
|
||
function updateCoordinatesList() {
|
||
const listElement = document.getElementById('coordinatesList');
|
||
|
||
if (!currentRectangles || currentRectangles.length === 0) {
|
||
listElement.innerHTML = `
|
||
<div class="empty-state">
|
||
<i class="fas fa-times-circle"></i>
|
||
<p>No frames detected</p>
|
||
<p>The image may not contain transparent areas</p>
|
||
</div>
|
||
`;
|
||
return;
|
||
}
|
||
|
||
let html = '';
|
||
currentRectangles.forEach(rect => {
|
||
// Generate coordinate string using FormatManager for consistency
|
||
const coordStr = FormatManager.generateString([rect]);
|
||
|
||
html += `
|
||
<div class="coord-item">
|
||
<div>
|
||
<span class="color-dot" style="background-color: ${rect.color.hex};"></span>
|
||
<strong>${rect.color.name} ${rect.shape_type}</strong>
|
||
<span style="float: right; color: #6c757d;">${rect.width}×${rect.height}px</span>
|
||
</div>
|
||
<div class="coord-string">${coordStr}</div>
|
||
</div>
|
||
`;
|
||
});
|
||
|
||
listElement.innerHTML = html;
|
||
}
|
||
|
||
// ===== SAVE OPERATIONS =====
|
||
function saveCoordinates() {
|
||
// Generate latest string based on current format settings
|
||
const formattedString = FormatManager.generateString(currentRectangles);
|
||
|
||
console.log('💾 Saving coordinates:', formattedString);
|
||
|
||
if (!formattedString) {
|
||
showMessage('No coordinates to save', 'error');
|
||
return;
|
||
}
|
||
|
||
showLoading(true);
|
||
|
||
fetch('/save_coordinates', {
|
||
method: 'POST',
|
||
headers: {
|
||
'Content-Type': 'application/json',
|
||
},
|
||
body: JSON.stringify({
|
||
image_name: currentFileName,
|
||
coordinate_string: formattedString
|
||
})
|
||
})
|
||
.then(response => response.json())
|
||
.then(data => {
|
||
if (data.success) {
|
||
showMessage('Coordinates saved successfully!', 'success');
|
||
loadResults();
|
||
} else {
|
||
showMessage(data.error || 'Failed to save', 'error');
|
||
}
|
||
})
|
||
.catch(error => {
|
||
console.error('Error:', error);
|
||
showMessage('Error: ' + error.message, 'error');
|
||
})
|
||
.finally(() => {
|
||
showLoading(false);
|
||
});
|
||
}
|
||
|
||
// ===== BATCH PROCESSING =====
|
||
function startBatchProcessing() {
|
||
if (batchFiles.length === 0) {
|
||
showMessage('Please select a folder first', 'error');
|
||
return;
|
||
}
|
||
|
||
if (isProcessingBatch) {
|
||
showMessage('Batch processing already in progress', 'error');
|
||
return;
|
||
}
|
||
|
||
isProcessingBatch = true;
|
||
batchResults = [];
|
||
document.getElementById('batchStartBtn').disabled = true;
|
||
document.getElementById('saveAllBtn').disabled = true;
|
||
document.getElementById('batchResultsList').innerHTML = '';
|
||
|
||
const totalFiles = batchFiles.length;
|
||
let processedFiles = 0;
|
||
let successfulFiles = 0;
|
||
|
||
updateProgress(totalFiles, 0, 0);
|
||
|
||
function processNextFile(index) {
|
||
if (index >= totalFiles) {
|
||
isProcessingBatch = false;
|
||
document.getElementById('batchStartBtn').disabled = false;
|
||
if (batchResults.length > 0) {
|
||
document.getElementById('saveAllBtn').disabled = false;
|
||
}
|
||
|
||
showMessage(`Batch complete: ${successfulFiles}/${totalFiles} successful`, 'success');
|
||
return;
|
||
}
|
||
|
||
const file = batchFiles[index];
|
||
const formData = new FormData();
|
||
formData.append('file', file);
|
||
|
||
fetch('/upload', {
|
||
method: 'POST',
|
||
body: formData
|
||
})
|
||
.then(response => response.json())
|
||
.then(data => {
|
||
processedFiles++;
|
||
|
||
const resultItem = document.createElement('div');
|
||
resultItem.className = 'batch-item';
|
||
|
||
if (data.success && data.rectangles) {
|
||
successfulFiles++;
|
||
|
||
// Show device info once at the start of batch
|
||
if (processedFiles === 1) {
|
||
const deviceMsg = data.device === 'cuda' ? 'GPU (CUDA)' : 'CPU';
|
||
showMessage(`Batch started using ${deviceMsg}`, 'success');
|
||
}
|
||
|
||
// Generate formatted coordinate string using FormatManager
|
||
const formattedCoords = FormatManager.generateString(data.rectangles);
|
||
|
||
// Extract folder path from webkitRelativePath
|
||
const relativePath = file.webkitRelativePath || file.name;
|
||
const pathParts = relativePath.split('/');
|
||
// Remove root folder name and filename to get subfolder path
|
||
const folderPath = pathParts.length > 2 ? pathParts.slice(1, -1).join('/') : '';
|
||
const fullPath = folderPath ? `${folderPath}/${file.name}` : file.name;
|
||
|
||
batchResults.push({
|
||
filename: file.name,
|
||
folderPath: folderPath, // NEW: relative folder path
|
||
fullPath: fullPath, // NEW: full path with filename
|
||
coordinates: formattedCoords, // Use formatted string
|
||
rectangles: data.rectangles, // Store raw data for re-formatting
|
||
image_url: data.image_url, // Store image URL
|
||
original_url: data.original_url // Store original URL for clean re-drawing
|
||
});
|
||
|
||
|
||
resultItem.classList.add('success');
|
||
|
||
// Create folder badge if folderPath exists
|
||
const folderBadge = folderPath ?
|
||
`<div class="folder-badge"><i class="fas fa-folder"></i> ${folderPath}</div>` : '';
|
||
|
||
resultItem.innerHTML = `
|
||
<div class="batch-image-container">
|
||
<img src="${data.image_url}" class="batch-image" alt="${file.name}">
|
||
<button class="batch-info-btn" onclick="openBatchDetail(${batchResults.length - 1})" title="View Details">
|
||
<i class="fas fa-info"></i>
|
||
</button>
|
||
</div>
|
||
${folderBadge}
|
||
<div class="batch-item-header">
|
||
<i class="fas fa-check-circle" style="color: var(--success-color);"></i>
|
||
${file.name}
|
||
</div>
|
||
<div class="batch-item-details" id="batch-details-${batchResults.length - 1}">
|
||
${data.frame_count || 0} frame(s)<br>
|
||
${formattedCoords}
|
||
</div>
|
||
`;
|
||
} else {
|
||
resultItem.classList.add('error');
|
||
resultItem.innerHTML = `
|
||
<div class="batch-image-container" style="background: #fff5f5; display: flex; flex-direction: column;">
|
||
<i class="fas fa-exclamation-circle" style="font-size: 32px; color: var(--danger-color); margin-bottom: 10px;"></i>
|
||
<span style="font-size: 12px; color: var(--danger-color);">Analysis Failed</span>
|
||
</div>
|
||
<div class="batch-item-header">
|
||
<i class="fas fa-times-circle" style="color: var(--danger-color);"></i>
|
||
${file.name}
|
||
</div>
|
||
<div class="batch-item-details" style="color: var(--danger-color);">
|
||
${data.error || 'No frames detected'}
|
||
</div>
|
||
`;
|
||
}
|
||
|
||
document.getElementById('batchResultsList').appendChild(resultItem);
|
||
|
||
// Auto-scroll container to the end (newest item)
|
||
const listContainer = document.getElementById('batchResultsList');
|
||
listContainer.scrollTo({
|
||
left: listContainer.scrollWidth,
|
||
behavior: 'smooth'
|
||
});
|
||
|
||
updateProgress(totalFiles, processedFiles, successfulFiles);
|
||
|
||
setTimeout(() => processNextFile(index + 1), 100);
|
||
})
|
||
.catch(error => {
|
||
console.error('Error processing file:', error);
|
||
processedFiles++;
|
||
|
||
const resultItem = document.createElement('div');
|
||
resultItem.className = 'batch-item error';
|
||
resultItem.innerHTML = `
|
||
<div class="batch-image-container" style="background: #fff5f5; display: flex; flex-direction: column;">
|
||
<i class="fas fa-exclamation-triangle" style="font-size: 32px; color: var(--danger-color); margin-bottom: 10px;"></i>
|
||
<span style="font-size: 12px; color: var(--danger-color);">Error</span>
|
||
</div>
|
||
<div class="batch-item-header">
|
||
<i class="fas fa-times-circle" style="color: var(--danger-color);"></i>
|
||
${file.name}
|
||
</div>
|
||
<div class="batch-item-details" style="color: var(--danger-color);">
|
||
${error.message}
|
||
</div>
|
||
`;
|
||
document.getElementById('batchResultsList').appendChild(resultItem);
|
||
|
||
updateProgress(totalFiles, processedFiles, successfulFiles);
|
||
setTimeout(() => processNextFile(index + 1), 100);
|
||
});
|
||
}
|
||
|
||
processNextFile(0);
|
||
}
|
||
|
||
function updateProgress(total, processed, successful) {
|
||
const percent = Math.round((processed / total) * 100);
|
||
|
||
document.getElementById('progressFill').style.width = percent + '%';
|
||
document.getElementById('progressPercent').textContent = percent + '%';
|
||
document.getElementById('progressText').textContent = `Processing: ${processed}/${total}`;
|
||
document.getElementById('batchStats').innerHTML = `
|
||
<i class="fas fa-file-image"></i> Files: ${total} |
|
||
<i class="fas fa-check-circle" style="color: #4facfe;"></i> Successful: ${successful} |
|
||
<i class="fas fa-times-circle" style="color: #f5576c;"></i> Failed: ${processed - successful}
|
||
`;
|
||
}
|
||
|
||
function saveAllCoordinates() {
|
||
if (batchResults.length === 0) {
|
||
showMessage('No batch results to save', 'error');
|
||
return;
|
||
}
|
||
|
||
showLoading(true);
|
||
|
||
// Re-format all batch results with current settings
|
||
// Use fullPath to preserve folder structure in output
|
||
const formattedResults = batchResults.map(item => ({
|
||
filename: item.fullPath || item.filename, // Use full path (e.g., folder/file.png)
|
||
coordinates: FormatManager.generateString(item.rectangles) // Use stored rects
|
||
}));
|
||
|
||
console.log('💾 Saving batch coordinates with folder paths:', formattedResults);
|
||
|
||
fetch('/save_all_coordinates', {
|
||
method: 'POST',
|
||
headers: {
|
||
'Content-Type': 'application/json',
|
||
},
|
||
body: JSON.stringify({
|
||
results: formattedResults
|
||
})
|
||
})
|
||
.then(response => response.json())
|
||
.then(data => {
|
||
if (data.success) {
|
||
showMessage(`Saved ${batchResults.length} images to coordinates file`, 'success');
|
||
loadResults();
|
||
} else {
|
||
showMessage(data.error || 'Failed to save', 'error');
|
||
}
|
||
})
|
||
.catch(error => {
|
||
console.error('Error:', error);
|
||
showMessage('Error: ' + error.message, 'error');
|
||
})
|
||
.finally(() => {
|
||
showLoading(false);
|
||
});
|
||
}
|
||
|
||
function clearBatch() {
|
||
if (!confirm('Clear batch results?')) return;
|
||
|
||
batchFiles = [];
|
||
batchResults = [];
|
||
document.getElementById('batchStatus').innerHTML = 'No folder selected';
|
||
document.getElementById('batchResults').style.display = 'none';
|
||
document.getElementById('batchResultsList').innerHTML = '';
|
||
document.getElementById('progressContainer').style.display = 'none';
|
||
document.getElementById('saveAllBtn').disabled = true;
|
||
document.getElementById('folderInput').value = '';
|
||
showMessage('Batch results cleared', 'info');
|
||
}
|
||
|
||
// ===== RESULTS MANAGEMENT =====
|
||
function loadResults() {
|
||
fetch('/get_coordinates')
|
||
.then(response => response.json())
|
||
.then(data => {
|
||
const resultsContent = document.getElementById('resultsContent');
|
||
|
||
if (data.content && data.content.trim()) {
|
||
resultsContent.textContent = data.content;
|
||
|
||
// Update recent entries
|
||
const lines = data.content.split('\n').filter(line => line.includes('|'));
|
||
const recent = lines.slice(-10).reverse();
|
||
let recentHtml = '';
|
||
|
||
recent.forEach(line => {
|
||
const parts = line.split('|').map(p => p.trim());
|
||
if (parts.length >= 3) {
|
||
recentHtml += `
|
||
<div style="background: white; padding: 15px; border-radius: 12px; margin-bottom: 12px; border-left: 4px solid #667eea; box-shadow: 0 2px 8px rgba(0,0,0,0.08);">
|
||
<div style="font-weight: bold; color: #667eea; margin-bottom: 5px;">${parts[1]}</div>
|
||
<div style="font-size: 11px; color: #6c757d; font-family: Monaco, monospace;">${parts[2].substring(0, 100)}${parts[2].length > 100 ? '...' : ''}</div>
|
||
</div>
|
||
`;
|
||
}
|
||
});
|
||
|
||
document.getElementById('recentEntries').innerHTML = recentHtml || '<p style="color: #adb5bd;">No recent entries</p>';
|
||
} else {
|
||
resultsContent.textContent = 'No coordinates saved yet';
|
||
document.getElementById('recentEntries').innerHTML = '<p style="color: #adb5bd;">No recent entries</p>';
|
||
}
|
||
})
|
||
.catch(error => {
|
||
console.error('Error loading results:', error);
|
||
document.getElementById('resultsContent').textContent = 'Error loading results';
|
||
});
|
||
}
|
||
|
||
function clearResults() {
|
||
if (!confirm('Clear all saved coordinates? This cannot be undone.')) return;
|
||
|
||
fetch('/clear_coordinates', {
|
||
method: 'POST'
|
||
})
|
||
.then(response => response.json())
|
||
.then(data => {
|
||
if (data.success) {
|
||
showMessage('All coordinates cleared', 'success');
|
||
loadResults();
|
||
} else {
|
||
showMessage(data.error || 'Failed to clear', 'error');
|
||
}
|
||
})
|
||
.catch(error => {
|
||
console.error('Error:', error);
|
||
showMessage('Error: ' + error.message, 'error');
|
||
});
|
||
}
|
||
|
||
function downloadResults() {
|
||
const content = document.getElementById('resultsContent').textContent;
|
||
if (!content || content === 'No coordinates saved yet') {
|
||
showMessage('No results to download', 'error');
|
||
return;
|
||
}
|
||
|
||
const blob = new Blob([content], { type: 'text/plain' });
|
||
const url = URL.createObjectURL(blob);
|
||
const a = document.createElement('a');
|
||
a.href = url;
|
||
a.download = `coordinates_${new Date().toISOString().slice(0, 10)}.txt`;
|
||
document.body.appendChild(a);
|
||
a.click();
|
||
document.body.removeChild(a);
|
||
URL.revokeObjectURL(url);
|
||
|
||
showMessage('Results downloaded', 'success');
|
||
}
|
||
|
||
// ===== TAB NAVIGATION =====
|
||
function switchTab(tabName) {
|
||
document.querySelectorAll('.tab-content').forEach(tab => {
|
||
tab.classList.remove('active');
|
||
});
|
||
|
||
document.querySelectorAll('.tab').forEach(tab => {
|
||
tab.classList.remove('active');
|
||
});
|
||
|
||
document.getElementById(tabName + '-tab').classList.add('active');
|
||
event.currentTarget.classList.add('active');
|
||
|
||
if (tabName === 'results') {
|
||
loadResults();
|
||
}
|
||
}
|
||
|
||
// ===== UTILITY FUNCTIONS =====
|
||
function clearImage() {
|
||
if (!confirm('Clear current image?')) return;
|
||
|
||
currentImage = null;
|
||
currentRectangles = [];
|
||
currentCoordinateString = '';
|
||
currentFileName = '';
|
||
|
||
ctx.clearRect(0, 0, canvas.width, canvas.height);
|
||
canvas.style.display = 'none';
|
||
document.getElementById('emptyState').style.display = 'block';
|
||
updateCoordinatesList();
|
||
document.getElementById('saveBtn').disabled = true;
|
||
document.getElementById('fileInput').value = '';
|
||
showMessage('Image cleared', 'info');
|
||
}
|
||
|
||
// ===== MANUAL DRAWING FUNCTIONS =====
|
||
function toggleDrawMode() {
|
||
if (!currentImage) {
|
||
showMessage('Please load an image first', 'error');
|
||
return;
|
||
}
|
||
|
||
isDrawingMode = !isDrawingMode;
|
||
const btn = document.getElementById('drawModeBtn');
|
||
|
||
if (isDrawingMode) {
|
||
btn.classList.add('active');
|
||
btn.innerHTML = '<i class="fas fa-stop"></i> <span>Stop Drawing</span>';
|
||
canvas.style.cursor = 'crosshair';
|
||
showMessage('Drawing Mode Enabled: Click and drag to add frames', 'info');
|
||
|
||
// Disable other interactions if needed
|
||
} else {
|
||
btn.classList.remove('active');
|
||
btn.innerHTML = '<i class="fas fa-pencil-alt"></i> <span>Draw Manual</span>';
|
||
canvas.style.cursor = 'default';
|
||
showMessage('Drawing Mode Disabled', 'info');
|
||
}
|
||
}
|
||
|
||
function handleMouseDown(e) {
|
||
if (!isDrawingMode || !currentImage) return;
|
||
|
||
const rect = canvas.getBoundingClientRect();
|
||
const scaleX = canvas.width / rect.width;
|
||
const scaleY = canvas.height / rect.height;
|
||
|
||
startX = (e.clientX - rect.left) * scaleX;
|
||
startY = (e.clientY - rect.top) * scaleY;
|
||
|
||
isDrawing = true;
|
||
}
|
||
|
||
function handleMouseMove(e) {
|
||
if (!isDrawingMode || !isDrawing) return;
|
||
|
||
// Redraw image + existing rectangles
|
||
redrawCanvas();
|
||
|
||
const rect = canvas.getBoundingClientRect();
|
||
const scaleX = canvas.width / rect.width;
|
||
const scaleY = canvas.height / rect.height;
|
||
|
||
const currentX = (e.clientX - rect.left) * scaleX;
|
||
const currentY = (e.clientY - rect.top) * scaleY;
|
||
|
||
const width = currentX - startX;
|
||
const height = currentY - startY;
|
||
|
||
// Draw current selection rectangle
|
||
ctx.strokeStyle = '#00FF00';
|
||
ctx.lineWidth = 2;
|
||
ctx.strokeRect(startX, startY, width, height);
|
||
}
|
||
|
||
function handleMouseUp(e) {
|
||
if (!isDrawingMode || !isDrawing) return;
|
||
|
||
isDrawing = false;
|
||
|
||
const rect = canvas.getBoundingClientRect();
|
||
const scaleX = canvas.width / rect.width;
|
||
const scaleY = canvas.height / rect.height;
|
||
|
||
const currentX = (e.clientX - rect.left) * scaleX;
|
||
const currentY = (e.clientY - rect.top) * scaleY;
|
||
|
||
// Normalize coordinates (handle negative width/height)
|
||
let x = Math.min(startX, currentX);
|
||
let y = Math.min(startY, currentY);
|
||
let w = Math.abs(startX - currentX);
|
||
let h = Math.abs(startY - currentY);
|
||
|
||
// Ignore very small clicks
|
||
if (w < 5 && h < 5) return;
|
||
|
||
// Create new rectangle object
|
||
const newRect = {
|
||
id: currentRectangles.length + 1,
|
||
x: Math.round(x),
|
||
y: Math.round(y),
|
||
width: Math.round(w),
|
||
height: Math.round(h),
|
||
area: Math.round(w * h),
|
||
shape_type: "Manual",
|
||
color: { name: 'Green', hex: '#00FF00', bgr: (0, 255, 0) }, // Distinct color
|
||
corners: {
|
||
top_left: { x: Math.round(x), y: Math.round(y) },
|
||
top_right: { x: Math.round(x + w), y: Math.round(y) },
|
||
bottom_right: { x: Math.round(x + w), y: Math.round(y + h) },
|
||
bottom_left: { x: Math.round(x), y: Math.round(y + h) }
|
||
}
|
||
};
|
||
|
||
currentRectangles.push(newRect);
|
||
|
||
// Update UI and List
|
||
redrawCanvas();
|
||
updateCoordinatesList();
|
||
document.getElementById('saveBtn').disabled = false;
|
||
showMessage('Frame added manually', 'success');
|
||
}
|
||
|
||
function redrawCanvas() {
|
||
if (!currentImage) return;
|
||
|
||
ctx.clearRect(0, 0, canvas.width, canvas.height);
|
||
ctx.drawImage(currentImage, 0, 0);
|
||
|
||
// Draw existing rectangles
|
||
currentRectangles.forEach(r => {
|
||
ctx.strokeStyle = r.color.hex || '#FF0000';
|
||
ctx.lineWidth = 3;
|
||
ctx.strokeRect(r.x, r.y, r.width, r.height);
|
||
|
||
// Label
|
||
ctx.font = "bold 16px Arial";
|
||
ctx.fillStyle = r.color.hex || '#FF0000';
|
||
ctx.fillText(r.id.toString(), r.x, r.y - 5);
|
||
});
|
||
}
|
||
|
||
function showLoading(show) {
|
||
document.getElementById('loading').style.display = show ? 'flex' : 'none';
|
||
}
|
||
|
||
function showMessage(text, type = 'info') {
|
||
const message = document.getElementById('message');
|
||
message.textContent = text;
|
||
message.className = `message ${type}`;
|
||
|
||
setTimeout(() => {
|
||
message.classList.add('show');
|
||
}, 10);
|
||
|
||
setTimeout(() => {
|
||
message.classList.remove('show');
|
||
}, 5000);
|
||
}
|
||
|
||
// ===== BATCH SCROLLING =====
|
||
function scrollBatch(direction) {
|
||
const list = document.getElementById('batchResultsList');
|
||
const scrollAmount = 340; // Approx card width (320) + gap (20)
|
||
|
||
if (direction === 'left') {
|
||
list.scrollBy({ left: -scrollAmount, behavior: 'smooth' });
|
||
} else {
|
||
list.scrollBy({ left: scrollAmount, behavior: 'smooth' });
|
||
}
|
||
}
|
||
|
||
// ===== FORMAT SETTINGS MANAGEMENT =====
|
||
const FormatManager = {
|
||
settings: {
|
||
// Points as ordered array
|
||
points: [
|
||
{ id: 'tl', label: 'Top-Left (x1,y1)', enabled: true },
|
||
{ id: 'tr', label: 'Top-Right (x2,y2)', enabled: true },
|
||
{ id: 'br', label: 'Bottom-Right (x3,y3)', enabled: true },
|
||
{ id: 'bl', label: 'Bottom-Left (x4,y4)', enabled: true }
|
||
],
|
||
separators: {
|
||
coord: ',', // x,y
|
||
point: ':', // p1:p2
|
||
frame: ';' // f1;f2
|
||
}
|
||
},
|
||
|
||
dragSrcEl: null,
|
||
|
||
// Load settings
|
||
load: function () {
|
||
const saved = localStorage.getItem('formatSettings_v2'); // Use v2 key for new structure
|
||
console.log('🔧 FormatManager.load() - localStorage value:', saved);
|
||
if (saved) {
|
||
try {
|
||
const parsed = JSON.parse(saved);
|
||
// Validate structure to avoid breaking on old format
|
||
if (Array.isArray(parsed.points)) {
|
||
this.settings = parsed;
|
||
console.log('✅ Loaded custom settings:', this.settings);
|
||
}
|
||
} catch (e) { console.error('Error loading settings', e); }
|
||
} else {
|
||
console.log('ℹ️ No saved settings found, using defaults:', this.settings);
|
||
}
|
||
this.renderPointsUI();
|
||
this.applyToUI();
|
||
},
|
||
|
||
// Save settings
|
||
save: function () {
|
||
// Collect enabled states from UI
|
||
this.settings.points.forEach(p => {
|
||
const checkbox = document.getElementById(`check_${p.id}`);
|
||
if (checkbox) p.enabled = checkbox.checked;
|
||
});
|
||
|
||
this.settings.separators = {
|
||
coord: document.getElementById('sepCoord').value || ',',
|
||
point: document.getElementById('sepPoint').value || ':',
|
||
frame: document.getElementById('sepFrame').value || ';'
|
||
};
|
||
|
||
localStorage.setItem('formatSettings_v2', JSON.stringify(this.settings));
|
||
this.updatePreview();
|
||
},
|
||
|
||
// Render the Sortable List
|
||
renderPointsUI: function () {
|
||
const list = document.getElementById('sortablePoints');
|
||
if (!list) return;
|
||
|
||
list.innerHTML = '';
|
||
this.settings.points.forEach((point, index) => {
|
||
const li = document.createElement('li');
|
||
li.className = 'sortable-item';
|
||
li.draggable = true;
|
||
li.dataset.index = index;
|
||
li.innerHTML = `
|
||
<i class="fas fa-grip-lines drag-handle"></i>
|
||
<input type="checkbox" id="check_${point.id}" ${point.enabled ? 'checked' : ''}>
|
||
<span class="item-label">${point.label}</span>
|
||
`;
|
||
|
||
// Event Listeners for DnD
|
||
li.addEventListener('dragstart', this.handleDragStart.bind(this));
|
||
li.addEventListener('dragenter', this.handleDragEnter.bind(this));
|
||
li.addEventListener('dragover', this.handleDragOver.bind(this));
|
||
li.addEventListener('dragleave', this.handleDragLeave.bind(this));
|
||
li.addEventListener('drop', this.handleDrop.bind(this));
|
||
li.addEventListener('dragend', this.handleDragEnd.bind(this));
|
||
|
||
// Checkbox listener
|
||
const checkbox = li.querySelector('input[type="checkbox"]');
|
||
checkbox.addEventListener('change', () => {
|
||
point.enabled = checkbox.checked;
|
||
this.updatePreview();
|
||
});
|
||
|
||
list.appendChild(li);
|
||
});
|
||
},
|
||
|
||
// Apply separator values to UI
|
||
applyToUI: function () {
|
||
document.getElementById('sepCoord').value = this.settings.separators.coord;
|
||
document.getElementById('sepPoint').value = this.settings.separators.point;
|
||
document.getElementById('sepFrame').value = this.settings.separators.frame;
|
||
this.updatePreview();
|
||
},
|
||
|
||
// Drag handlers
|
||
handleDragStart: function (e) {
|
||
this.dragSrcEl = e.currentTarget;
|
||
e.dataTransfer.effectAllowed = 'move';
|
||
e.dataTransfer.setData('text/html', e.currentTarget.innerHTML);
|
||
|
||
// Timeout to allow the ghost image to be captured before adding the class
|
||
setTimeout(() => {
|
||
e.currentTarget.classList.add('dragging');
|
||
}, 0);
|
||
},
|
||
|
||
handleDragOver: function (e) {
|
||
if (e.preventDefault) e.preventDefault();
|
||
e.dataTransfer.dropEffect = 'move';
|
||
|
||
const target = e.currentTarget;
|
||
|
||
if (this.dragSrcEl && target && this.dragSrcEl !== target && target.classList.contains('sortable-item')) {
|
||
// Get current array indices
|
||
const srcIndex = parseInt(this.dragSrcEl.dataset.index);
|
||
const targetIndex = parseInt(target.dataset.index);
|
||
|
||
// Swap in data array
|
||
const movedItem = this.settings.points.splice(srcIndex, 1)[0];
|
||
this.settings.points.splice(targetIndex, 0, movedItem);
|
||
|
||
// Swap nodes in DOM for visual feedback
|
||
const list = document.getElementById('sortablePoints');
|
||
// Re-render completely to ensure indices are correct and state is clean
|
||
// Or just move the node? Moving node is smoother visually usually, but re-render ensures consistency
|
||
// Let's try moving the node to keep the 'dragging' class on the source active without flicker
|
||
|
||
// Get all items again to find positions
|
||
const items = [...list.querySelectorAll('.sortable-item')];
|
||
const srcNode = items[srcIndex];
|
||
const targetNode = items[targetIndex];
|
||
|
||
// Visual swap
|
||
if (srcIndex < targetIndex) {
|
||
targetNode.after(srcNode);
|
||
} else {
|
||
targetNode.before(srcNode);
|
||
}
|
||
|
||
// Update indices on all elements to match new order
|
||
list.querySelectorAll('.sortable-item').forEach((item, idx) => {
|
||
item.dataset.index = idx;
|
||
});
|
||
|
||
// Update preview continuously
|
||
this.updatePreview();
|
||
}
|
||
|
||
return false;
|
||
},
|
||
|
||
handleDragEnter: function (e) {
|
||
// e.currentTarget.classList.add('over'); // Not needed for fluid swap
|
||
},
|
||
|
||
handleDragLeave: function (e) {
|
||
// e.currentTarget.classList.remove('over');
|
||
},
|
||
|
||
handleDrop: function (e) {
|
||
if (e.stopPropagation) e.stopPropagation();
|
||
return false;
|
||
},
|
||
|
||
handleDragEnd: function (e) {
|
||
this.dragSrcEl.classList.remove('dragging');
|
||
this.dragSrcEl = null;
|
||
|
||
// Final save or just cleanup? The settings.points are already updated during dragOver.
|
||
// We do not save to localStorage until "Apply" is clicked, but the this.settings state is updated.
|
||
// We should re-render cleanly just to be safe?
|
||
// this.renderPointsUI(); // Might cause flicker, skip if DOM is good.
|
||
},
|
||
|
||
|
||
|
||
// Generate String
|
||
generateString: function (rectangles) {
|
||
if (!rectangles || rectangles.length === 0) return '';
|
||
|
||
console.log('📐 generateString() called with', rectangles.length, 'rectangles');
|
||
console.log('📐 Current settings:', JSON.stringify(this.settings));
|
||
|
||
const frameStrings = rectangles.map(rect => {
|
||
const points = [];
|
||
const corners = rect.corners;
|
||
|
||
// Iterate through ORDERED points
|
||
this.settings.points.forEach(p => {
|
||
if (p.enabled) {
|
||
const sepC = this.settings.separators.coord;
|
||
// Map ID (tl, tr, etc.) to backend key (top_left, etc.)
|
||
let cornerKey = '';
|
||
if (p.id === 'tl') cornerKey = 'top_left';
|
||
else if (p.id === 'tr') cornerKey = 'top_right';
|
||
else if (p.id === 'br') cornerKey = 'bottom_right';
|
||
else if (p.id === 'bl') cornerKey = 'bottom_left';
|
||
|
||
if (corners[cornerKey]) {
|
||
points.push(`${corners[cornerKey].x}${sepC}${corners[cornerKey].y}`);
|
||
}
|
||
}
|
||
});
|
||
return points.join(this.settings.separators.point);
|
||
});
|
||
const result = frameStrings.join(this.settings.separators.frame);
|
||
console.log('📐 Generated string:', result);
|
||
return result;
|
||
},
|
||
|
||
updatePreview: function () {
|
||
const mockRects = [{
|
||
corners: {
|
||
top_left: { x: 'x1', y: 'y1' },
|
||
top_right: { x: 'x2', y: 'y2' },
|
||
bottom_right: { x: 'x3', y: 'y3' },
|
||
bottom_left: { x: 'x4', y: 'y4' }
|
||
}
|
||
}];
|
||
|
||
// Use current in-memory settings which are kept up-to-date by events
|
||
// except separators inputs which might change without saving
|
||
const tempSettings = JSON.parse(JSON.stringify(this.settings));
|
||
tempSettings.separators = {
|
||
coord: document.getElementById('sepCoord').value || ',',
|
||
point: document.getElementById('sepPoint').value || ':',
|
||
frame: document.getElementById('sepFrame').value || ';'
|
||
};
|
||
|
||
// Need to temporarily override this.settings to use generateString helper effectively
|
||
// OR pass settings to generateString. Let's make generateString use `this.settings` but we swap it?
|
||
// Safer to just rewrite logic briefly here or abstract it.
|
||
// Actually, let's just use the main logic but with temp separators.
|
||
const originalSeps = this.settings.separators;
|
||
this.settings.separators = tempSettings.separators;
|
||
const result = this.generateString(mockRects);
|
||
this.settings.separators = originalSeps; // Restore
|
||
|
||
document.getElementById('formatPreview').textContent = result || 'Select at least one point';
|
||
}
|
||
};
|
||
|
||
// Global modal functions
|
||
function toggleFormatModal(show) {
|
||
const modal = document.getElementById('formatModal');
|
||
if (show) {
|
||
modal.classList.add('show');
|
||
FormatManager.load(); // Refresh/Init
|
||
} else {
|
||
modal.classList.remove('show');
|
||
}
|
||
}
|
||
|
||
function saveFormatSettings() {
|
||
FormatManager.save();
|
||
toggleFormatModal(false);
|
||
showMessage('Format settings saved', 'success');
|
||
}
|
||
|
||
// Add listeners for real-time preview
|
||
document.addEventListener('DOMContentLoaded', function () {
|
||
// Inputs (separators)
|
||
['sepCoord', 'sepPoint', 'sepFrame'].forEach(id => {
|
||
const el = document.getElementById(id);
|
||
if (el) {
|
||
el.addEventListener('input', () => FormatManager.updatePreview());
|
||
}
|
||
});
|
||
});
|
||
|
||
function checkServerHealth() {
|
||
fetch('/health')
|
||
.then(response => response.json())
|
||
.then(data => {
|
||
if (data.status === 'healthy') {
|
||
console.log('Server is healthy');
|
||
}
|
||
})
|
||
.catch(error => {
|
||
console.error('Server health check failed:', error);
|
||
showMessage('Warning: Server connection issues', 'error');
|
||
});
|
||
}
|
||
|
||
// ===== BATCH DETAIL VIEW FUNCTIONS =====
|
||
|
||
function openBatchDetail(index) {
|
||
if (index < 0 || index >= batchResults.length) return;
|
||
|
||
currentBatchDetailIndex = index;
|
||
const result = batchResults[index];
|
||
|
||
// Load image for canvas
|
||
detailImage = new Image();
|
||
detailImage.onload = function() {
|
||
renderDetailView();
|
||
document.getElementById('batchDetailModal').classList.add('show');
|
||
};
|
||
// Use original URL if available (to avoid ghost boxes), otherwise fallback to processed
|
||
detailImage.src = result.original_url || result.image_url;
|
||
}
|
||
|
||
function closeBatchDetail() {
|
||
document.getElementById('batchDetailModal').classList.remove('show');
|
||
|
||
// Reset drawing mode if active
|
||
if (isBatchDrawingMode) {
|
||
toggleBatchDrawMode();
|
||
}
|
||
|
||
currentBatchDetailIndex = -1;
|
||
detailImage = null;
|
||
}
|
||
|
||
function renderDetailView() {
|
||
if (currentBatchDetailIndex === -1 || !detailImage) return;
|
||
|
||
const result = batchResults[currentBatchDetailIndex];
|
||
const rectangles = result.rectangles;
|
||
|
||
// 1. Render Canvas
|
||
detailCanvas.width = detailImage.width;
|
||
detailCanvas.height = detailImage.height;
|
||
detailCtx.clearRect(0, 0, detailCanvas.width, detailCanvas.height);
|
||
detailCtx.drawImage(detailImage, 0, 0);
|
||
|
||
// Draw rectangles
|
||
rectangles.forEach((rect, i) => {
|
||
// Draw Box
|
||
detailCtx.lineWidth = 3;
|
||
detailCtx.strokeStyle = rect.color.hex || '#FF0000'; // detailed view hex
|
||
|
||
detailCtx.strokeRect(rect.x, rect.y, rect.width, rect.height);
|
||
|
||
// Draw Label
|
||
detailCtx.font = "bold 16px Arial";
|
||
detailCtx.fillStyle = rect.color.hex || '#FF0000';
|
||
detailCtx.fillText(`${i + 1}`, rect.x, rect.y - 5);
|
||
});
|
||
|
||
// 2. Render List
|
||
const listContainer = document.getElementById('detailList');
|
||
listContainer.innerHTML = '';
|
||
|
||
if (rectangles.length === 0) {
|
||
listContainer.innerHTML = '<p class="text-muted text-center" style="margin-top: 20px;">No frames detected (or all removed)</p>';
|
||
return;
|
||
}
|
||
|
||
rectangles.forEach((rect, i) => {
|
||
const item = document.createElement('div');
|
||
item.className = 'detail-item';
|
||
|
||
const color = rect.color.hex || '#FF0000';
|
||
|
||
item.innerHTML = `
|
||
<div style="width: 20px; height: 20px; background: ${color}; border-radius: 4px; margin-right: 10px; display: flex; align-items: center; justify-content: center; color: white; font-weight: bold; font-size: 12px;">
|
||
${i + 1}
|
||
</div>
|
||
<div>
|
||
<div style="font-weight: 600; font-size: 14px;">Frame #${i + 1}</div>
|
||
<div style="font-size: 12px; color: #6c757d;">
|
||
${rect.width}x${rect.height} • (${rect.x}, ${rect.y})
|
||
</div>
|
||
</div>
|
||
<button class="detail-remove-btn" onclick="removeFrameFromBatch(${currentBatchDetailIndex}, ${i})" title="Remove Frame">
|
||
<i class="fas fa-times"></i>
|
||
</button>
|
||
`;
|
||
listContainer.appendChild(item);
|
||
});
|
||
}
|
||
|
||
function removeFrameFromBatch(batchIndex, frameIndex) {
|
||
if (batchIndex !== currentBatchDetailIndex) return;
|
||
if (!confirm('Remove this frame? It will not be saved.')) return;
|
||
|
||
const result = batchResults[batchIndex];
|
||
|
||
// Remove from array
|
||
result.rectangles.splice(frameIndex, 1);
|
||
|
||
// Regenerate coordinate string using FormatManager
|
||
result.coordinates = FormatManager.generateString(result.rectangles);
|
||
|
||
// Update Batch Item UI in the background list
|
||
const batchDetailsEl = document.getElementById(`batch-details-${batchIndex}`);
|
||
if (batchDetailsEl) {
|
||
batchDetailsEl.innerHTML = `
|
||
${result.rectangles.length} frame(s)<br>
|
||
${result.coordinates}
|
||
`;
|
||
}
|
||
|
||
// Re-render Detail View
|
||
renderDetailView();
|
||
|
||
showMessage('Frame removed', 'success');
|
||
}
|
||
|
||
// ===== BATCH DRAWING FUNCTIONS =====
|
||
function toggleBatchDrawMode() {
|
||
isBatchDrawingMode = !isBatchDrawingMode;
|
||
const btn = document.getElementById('batchDrawBtn');
|
||
|
||
if (isBatchDrawingMode) {
|
||
btn.classList.add('active');
|
||
btn.innerHTML = '<i class="fas fa-stop"></i> Stop Drawing';
|
||
detailCanvas.style.cursor = 'crosshair';
|
||
} else {
|
||
btn.classList.remove('active');
|
||
btn.innerHTML = '<i class="fas fa-pencil-alt"></i> Draw Manual';
|
||
detailCanvas.style.cursor = 'default';
|
||
renderDetailView(); // Clean redraw
|
||
}
|
||
}
|
||
|
||
function handleBatchMouseDown(e) {
|
||
if (!isBatchDrawingMode || !detailImage) return;
|
||
|
||
const rect = detailCanvas.getBoundingClientRect();
|
||
const scaleX = detailCanvas.width / rect.width;
|
||
const scaleY = detailCanvas.height / rect.height;
|
||
|
||
batchStartX = (e.clientX - rect.left) * scaleX;
|
||
batchStartY = (e.clientY - rect.top) * scaleY;
|
||
|
||
isBatchDrawing = true;
|
||
}
|
||
|
||
function handleBatchMouseMove(e) {
|
||
if (!isBatchDrawingMode || !isBatchDrawing) return;
|
||
|
||
// Redraw base view (image + rects)
|
||
renderDetailView();
|
||
|
||
const rect = detailCanvas.getBoundingClientRect();
|
||
const scaleX = detailCanvas.width / rect.width;
|
||
const scaleY = detailCanvas.height / rect.height;
|
||
|
||
const currentX = (e.clientX - rect.left) * scaleX;
|
||
const currentY = (e.clientY - rect.top) * scaleY;
|
||
|
||
const width = currentX - batchStartX;
|
||
const height = currentY - batchStartY;
|
||
|
||
// Draw current selection
|
||
detailCtx.strokeStyle = '#00FF00';
|
||
detailCtx.lineWidth = 2;
|
||
detailCtx.strokeRect(batchStartX, batchStartY, width, height);
|
||
}
|
||
|
||
function handleBatchMouseUp(e) {
|
||
if (!isBatchDrawingMode || !isBatchDrawing) return;
|
||
|
||
isBatchDrawing = false;
|
||
|
||
const rect = detailCanvas.getBoundingClientRect();
|
||
const scaleX = detailCanvas.width / rect.width;
|
||
const scaleY = detailCanvas.height / rect.height;
|
||
|
||
const currentX = (e.clientX - rect.left) * scaleX;
|
||
const currentY = (e.clientY - rect.top) * scaleY;
|
||
|
||
// Normalize properties
|
||
let x = Math.min(batchStartX, currentX);
|
||
let y = Math.min(batchStartY, currentY);
|
||
let w = Math.abs(batchStartX - currentX);
|
||
let h = Math.abs(batchStartY - currentY);
|
||
|
||
if (w < 5 && h < 5) return;
|
||
|
||
// Add to batch results
|
||
const result = batchResults[currentBatchDetailIndex];
|
||
if (result) {
|
||
const newRect = {
|
||
id: result.rectangles.length + 1,
|
||
x: Math.round(x),
|
||
y: Math.round(y),
|
||
width: Math.round(w),
|
||
height: Math.round(h),
|
||
area: Math.round(w * h),
|
||
shape_type: "Manual",
|
||
color: { name: 'Green', hex: '#00FF00', bgr: (0, 255, 0) },
|
||
corners: {
|
||
top_left: { x: Math.round(x), y: Math.round(y) },
|
||
top_right: { x: Math.round(x + w), y: Math.round(y) },
|
||
bottom_right: { x: Math.round(x + w), y: Math.round(y + h) },
|
||
bottom_left: { x: Math.round(x), y: Math.round(y + h) }
|
||
}
|
||
};
|
||
|
||
result.rectangles.push(newRect);
|
||
|
||
// Update Coordinate String
|
||
result.coordinates = FormatManager.generateString(result.rectangles);
|
||
|
||
// Update Background List UI
|
||
const batchDetailsEl = document.getElementById(`batch-details-${currentBatchDetailIndex}`);
|
||
if (batchDetailsEl) {
|
||
batchDetailsEl.innerHTML = `
|
||
${result.rectangles.length} frame(s)<br>
|
||
${result.coordinates}
|
||
`;
|
||
}
|
||
|
||
renderDetailView();
|
||
showMessage('Frame added manually', 'success');
|
||
}
|
||
} |