base.js 42 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186
  1. // Player status bar functionality - Updated to fix logMessage errors
  2. // Update LED nav label based on provider
  3. async function updateLedNavLabel() {
  4. try {
  5. const response = await fetch('/get_led_config');
  6. if (response.ok) {
  7. const data = await response.json();
  8. const navLabel = document.getElementById('led-nav-label');
  9. if (navLabel) {
  10. if (data.provider === 'wled') {
  11. navLabel.textContent = 'WLED';
  12. } else if (data.provider === 'dw_leds') {
  13. navLabel.textContent = 'DW LEDs';
  14. } else {
  15. navLabel.textContent = 'LED';
  16. }
  17. }
  18. }
  19. } catch (error) {
  20. console.error('Error updating LED nav label:', error);
  21. }
  22. }
  23. // Call on page load
  24. document.addEventListener('DOMContentLoaded', updateLedNavLabel);
  25. // Pattern files cache for improved performance with localStorage persistence
  26. const PATTERN_CACHE_KEY = 'dune_weaver_pattern_files_cache';
  27. const PATTERN_CACHE_EXPIRY = 30 * 60 * 1000; // 30 minutes cache (longer since it persists)
  28. // Function to get cached pattern files or fetch fresh data
  29. async function getCachedPatternFiles(forceRefresh = false) {
  30. const now = Date.now();
  31. // Try to load from localStorage first
  32. if (!forceRefresh) {
  33. try {
  34. const cachedData = localStorage.getItem(PATTERN_CACHE_KEY);
  35. if (cachedData) {
  36. const { files, timestamp } = JSON.parse(cachedData);
  37. if (files && timestamp && (now - timestamp) < PATTERN_CACHE_EXPIRY) {
  38. console.log('Using cached pattern files from localStorage');
  39. return files;
  40. }
  41. }
  42. } catch (error) {
  43. console.warn('Error reading pattern files cache from localStorage:', error);
  44. }
  45. }
  46. try {
  47. console.log('Fetching fresh pattern files from server');
  48. const response = await fetch('/list_theta_rho_files');
  49. if (!response.ok) {
  50. throw new Error(`Failed to fetch pattern files: ${response.status}`);
  51. }
  52. const files = await response.json();
  53. // Store in localStorage
  54. try {
  55. const cacheData = { files, timestamp: now };
  56. localStorage.setItem(PATTERN_CACHE_KEY, JSON.stringify(cacheData));
  57. } catch (error) {
  58. console.warn('Error storing pattern files cache in localStorage:', error);
  59. }
  60. return files;
  61. } catch (error) {
  62. console.error('Error fetching pattern files:', error);
  63. // Try to return any cached data as fallback, even if expired
  64. try {
  65. const cachedData = localStorage.getItem(PATTERN_CACHE_KEY);
  66. if (cachedData) {
  67. const { files } = JSON.parse(cachedData);
  68. if (files) {
  69. console.log('Using expired cached pattern files as fallback');
  70. return files;
  71. }
  72. }
  73. } catch (fallbackError) {
  74. console.warn('Error reading fallback cache:', fallbackError);
  75. }
  76. return [];
  77. }
  78. }
  79. // Function to invalidate pattern files cache
  80. function invalidatePatternFilesCache() {
  81. try {
  82. localStorage.removeItem(PATTERN_CACHE_KEY);
  83. console.log('Pattern files cache invalidated');
  84. } catch (error) {
  85. console.warn('Error invalidating pattern files cache:', error);
  86. }
  87. }
  88. // Helper function to normalize file paths for cross-platform compatibility
  89. function normalizeFilePath(filePath) {
  90. if (!filePath) return '';
  91. // First normalize path separators
  92. let normalized = filePath.replace(/\\/g, '/');
  93. // Remove only the patterns directory prefix, not patterns within the path
  94. if (normalized.startsWith('./patterns/')) {
  95. normalized = normalized.substring(11);
  96. } else if (normalized.startsWith('patterns/')) {
  97. normalized = normalized.substring(9);
  98. }
  99. return normalized;
  100. }
  101. let ws = null;
  102. let reconnectAttempts = 0;
  103. const maxReconnectAttempts = 5;
  104. const reconnectDelay = 3000; // 3 seconds
  105. let isEditingSpeed = false; // Track if user is editing speed
  106. let playerPreviewData = null; // Store the current pattern's preview data for modal
  107. let playerPreviewCtx = null; // Store the canvas context for modal preview
  108. let playerAnimationId = null; // Store animation frame ID for modal
  109. let lastProgress = 0; // Last known progress from backend
  110. let targetProgress = 0; // Target progress to animate towards
  111. let animationStartTime = 0; // Start time of current animation
  112. let animationDuration = 1000; // Duration of interpolation in ms
  113. let smoothAnimationStartTime = 0; // Start time for smooth coordinate animation
  114. let smoothAnimationActive = false; // Whether smooth animation is running
  115. let modalAnimationId = null; // Store animation frame ID for modal
  116. let modalLastProgress = 0; // Last known progress for modal
  117. let modalTargetProgress = 0; // Target progress for modal
  118. let modalAnimationStartTime = 0; // Start time for modal animation
  119. let userDismissedModal = false; // Track if user has manually dismissed the modal
  120. // Function to set modal visibility
  121. function setModalVisibility(show, userAction = false) {
  122. const modal = document.getElementById('playerPreviewModal');
  123. if (!modal) return;
  124. if (show) {
  125. modal.classList.remove('hidden');
  126. } else {
  127. modal.classList.add('hidden');
  128. }
  129. if (userAction) {
  130. userDismissedModal = !show;
  131. }
  132. }
  133. let currentPreviewFile = null; // Track the current file for preview data
  134. function connectWebSocket() {
  135. if (ws) {
  136. ws.close();
  137. }
  138. ws = new WebSocket(`ws://${window.location.host}/ws/status`);
  139. ws.onopen = function() {
  140. console.log("WebSocket connection established");
  141. reconnectAttempts = 0;
  142. };
  143. ws.onclose = function() {
  144. console.log("WebSocket connection closed");
  145. if (reconnectAttempts < maxReconnectAttempts) {
  146. reconnectAttempts++;
  147. setTimeout(connectWebSocket, reconnectDelay);
  148. }
  149. };
  150. ws.onerror = function(error) {
  151. console.error("WebSocket error:", error);
  152. };
  153. ws.onmessage = function(event) {
  154. try {
  155. const data = JSON.parse(event.data);
  156. if (data.type === 'status_update') {
  157. // Update modal status with the full data
  158. syncModalControls(data.data);
  159. // Update speed input field on table control page if it exists
  160. if (data.data && data.data.speed) {
  161. const currentSpeedDisplay = document.getElementById('currentSpeedDisplay');
  162. if (currentSpeedDisplay) {
  163. currentSpeedDisplay.textContent = `${data.data.speed} mm/s`;
  164. }
  165. }
  166. // Update connection status dot using 'connection_status' or fallback to 'connected'
  167. if (data.data.hasOwnProperty('connection_status')) {
  168. updateConnectionStatus(data.data.connection_status);
  169. }
  170. // Check if current file has changed and reload preview data if needed
  171. if (data.data.current_file) {
  172. const newFile = normalizeFilePath(data.data.current_file);
  173. if (newFile !== currentPreviewFile) {
  174. currentPreviewFile = newFile;
  175. // Only preload if we're on the browse page (index.html)
  176. // Other pages (playlists, table_control, LED, settings) will load on-demand
  177. const modal = document.getElementById('playerPreviewModal');
  178. const browsePage = document.getElementById('browseSortFieldSelect');
  179. if (modal && browsePage) {
  180. // We're on the browse page with the modal - preload coordinates
  181. loadPlayerPreviewData(data.data.current_file);
  182. }
  183. }
  184. } else {
  185. currentPreviewFile = null;
  186. playerPreviewData = null;
  187. }
  188. // Update progress for modal animation with smooth interpolation
  189. if (playerPreviewData && data.data.progress && data.data.progress.percentage !== null) {
  190. const newProgress = data.data.progress.percentage / 100;
  191. targetProgress = newProgress;
  192. // Update modal if open with smooth animation
  193. const modal = document.getElementById('playerPreviewModal');
  194. if (modal && !modal.classList.contains('hidden')) {
  195. updateModalPreviewSmooth(newProgress);
  196. }
  197. }
  198. // Reset userDismissedModal flag if no pattern is playing
  199. if (!data.data.current_file || !data.data.is_running) {
  200. userDismissedModal = false;
  201. }
  202. }
  203. } catch (error) {
  204. console.error("Error processing WebSocket message:", error);
  205. }
  206. };
  207. }
  208. function updateConnectionStatus(isConnected) {
  209. const statusDot = document.getElementById("connectionStatusDot");
  210. if (statusDot) {
  211. // Update dot color
  212. statusDot.className = `inline-block size-2 rounded-full ml-2 align-middle ${
  213. isConnected ? "bg-green-500" : "bg-red-500"
  214. }`;
  215. }
  216. }
  217. // Setup player preview with expand button
  218. function setupPlayerPreview() {
  219. const previewContainer = document.getElementById('player-pattern-preview');
  220. if (!previewContainer) return;
  221. // Get current background image URL
  222. const currentBgImage = previewContainer.style.backgroundImage;
  223. // Clear container
  224. previewContainer.innerHTML = '';
  225. previewContainer.style.backgroundImage = '';
  226. // Create preview image container
  227. const imageContainer = document.createElement('div');
  228. imageContainer.className = 'relative aspect-square rounded-full overflow-hidden w-full h-full';
  229. // Create image element
  230. const img = document.createElement('img');
  231. img.className = 'w-full h-full object-cover';
  232. // img.alt = 'Pattern Preview';
  233. // Extract URL from background-image CSS
  234. img.src = currentBgImage.replace(/^url\(['"](.+)['"]\)$/, '$1');
  235. // Add expand button overlay
  236. const expandOverlay = document.createElement('div');
  237. expandOverlay.className = 'absolute inset-0 flex items-center justify-center opacity-0 hover:opacity-100 transition-opacity duration-200 cursor-pointer z-20 bg-black bg-opacity-20 hover:bg-opacity-30';
  238. expandOverlay.innerHTML = '<div class="bg-white rounded-full p-3 shadow-lg flex items-center justify-center w-12 h-12"><span class="material-icons text-xl text-gray-800">fullscreen</span></div>';
  239. // Add click handler for expand button
  240. expandOverlay.addEventListener('click', (e) => {
  241. e.stopPropagation();
  242. openPlayerPreviewModal();
  243. });
  244. // Add image and overlay to image container
  245. imageContainer.appendChild(img);
  246. imageContainer.appendChild(expandOverlay);
  247. // Add image container to preview container
  248. previewContainer.appendChild(imageContainer);
  249. }
  250. // Open player preview modal
  251. async function openPlayerPreviewModal() {
  252. try {
  253. const modal = document.getElementById('playerPreviewModal');
  254. const title = document.getElementById('playerPreviewTitle');
  255. const canvas = document.getElementById('playerPreviewCanvas');
  256. const ctx = canvas.getContext('2d');
  257. const toggleBtn = document.getElementById('toggle-preview-modal-btn');
  258. // Show modal immediately for instant feedback
  259. modal.classList.remove('hidden');
  260. // Setup canvas (so it's ready to display loading state)
  261. setupPlayerPreviewCanvas(ctx);
  262. // Load preview data on-demand if not already loaded
  263. if (!playerPreviewData && currentPreviewFile) {
  264. // Show loading state
  265. title.textContent = 'Loading pattern...';
  266. drawLoadingState(ctx);
  267. // Load data in background
  268. await loadPlayerPreviewData(`./patterns/${currentPreviewFile}`);
  269. // Update title when loaded
  270. title.textContent = 'Live Pattern Preview';
  271. } else {
  272. // Data already loaded
  273. title.textContent = 'Live Pattern Preview';
  274. }
  275. // Draw the pattern (either immediately if cached, or after loading)
  276. drawPlayerPreview(ctx, targetProgress);
  277. } catch (error) {
  278. console.error(`Error opening player preview modal: ${error.message}`);
  279. showStatusMessage('Failed to load pattern for animation', 'error');
  280. }
  281. }
  282. // Setup player preview canvas for modal
  283. function setupPlayerPreviewCanvas(ctx) {
  284. const canvas = ctx.canvas;
  285. const container = canvas.parentElement; // This is the div with max-w and max-h constraints
  286. const modal = document.getElementById('playerPreviewModal');
  287. if (!container || !modal) return;
  288. // Calculate available viewport space directly
  289. const viewportWidth = window.innerWidth;
  290. const viewportHeight = window.innerHeight;
  291. // Calculate maximum canvas size based on viewport and fixed estimates
  292. // Modal uses max-w-5xl (1024px) but we want to be responsive to actual viewport
  293. const modalMaxWidth = Math.min(1024, viewportWidth * 0.9); // Account for modal padding
  294. const modalMaxHeight = viewportHeight * 0.95; // max-h-[95vh]
  295. // Reserve space for modal header (~80px) and controls (~200px) and padding
  296. const reservedSpace = 320; // Header + controls + padding
  297. const availableModalHeight = modalMaxHeight - reservedSpace;
  298. // Calculate canvas constraints (stay within original 800px max, but be responsive)
  299. const maxCanvasSize = Math.min(800, modalMaxWidth - 64, availableModalHeight); // 64px for canvas area padding
  300. // Ensure minimum size
  301. const finalSize = Math.max(200, maxCanvasSize);
  302. // Update container to exact size (override CSS constraints)
  303. container.style.width = `${finalSize}px`;
  304. container.style.height = `${finalSize}px`;
  305. container.style.maxWidth = `${finalSize}px`;
  306. container.style.maxHeight = `${finalSize}px`;
  307. container.style.minWidth = `${finalSize}px`;
  308. container.style.minHeight = `${finalSize}px`;
  309. // Set the internal canvas size for high-DPI rendering
  310. const pixelRatio = (window.devicePixelRatio || 1) * 2;
  311. canvas.width = finalSize * pixelRatio;
  312. canvas.height = finalSize * pixelRatio;
  313. // Set the display size (canvas fills its container)
  314. canvas.style.width = '100%';
  315. canvas.style.height = '100%';
  316. console.log('Canvas resized:', {
  317. viewport: `${viewportWidth}x${viewportHeight}`,
  318. modalMaxWidth,
  319. availableModalHeight,
  320. finalSize: finalSize
  321. });
  322. }
  323. // Get interpolated coordinate at specific progress
  324. function getInterpolatedCoordinate(progress) {
  325. if (!playerPreviewData || playerPreviewData.length === 0) return null;
  326. const totalPoints = playerPreviewData.length;
  327. const exactIndex = progress * (totalPoints - 1);
  328. const index = Math.floor(exactIndex);
  329. const fraction = exactIndex - index;
  330. // Ensure we don't go out of bounds
  331. if (index >= totalPoints - 1) {
  332. return playerPreviewData[totalPoints - 1];
  333. }
  334. if (index < 0) {
  335. return playerPreviewData[0];
  336. }
  337. // Get the two coordinates to interpolate between
  338. const [theta1, rho1] = playerPreviewData[index];
  339. const [theta2, rho2] = playerPreviewData[index + 1];
  340. // Interpolate theta (handle angle wrapping)
  341. let deltaTheta = theta2 - theta1;
  342. if (deltaTheta > Math.PI) deltaTheta -= 2 * Math.PI;
  343. if (deltaTheta < -Math.PI) deltaTheta += 2 * Math.PI;
  344. const interpolatedTheta = theta1 + deltaTheta * fraction;
  345. const interpolatedRho = rho1 + (rho2 - rho1) * fraction;
  346. return [interpolatedTheta, interpolatedRho];
  347. }
  348. // Draw loading state on canvas
  349. function drawLoadingState(ctx) {
  350. if (!ctx) return;
  351. const canvas = ctx.canvas;
  352. const pixelRatio = (window.devicePixelRatio || 1) * 2;
  353. const containerSize = canvas.width / pixelRatio;
  354. const center = containerSize / 2;
  355. ctx.save();
  356. // Clear canvas
  357. ctx.clearRect(0, 0, canvas.width, canvas.height);
  358. // Create circular clipping path
  359. ctx.beginPath();
  360. ctx.arc(canvas.width/2, canvas.height/2, canvas.width/2, 0, Math.PI * 2);
  361. ctx.clip();
  362. // Setup coordinate system
  363. ctx.scale(pixelRatio, pixelRatio);
  364. // Draw loading text only
  365. ctx.fillStyle = '#9ca3af';
  366. ctx.font = '16px sans-serif';
  367. ctx.textAlign = 'center';
  368. ctx.textBaseline = 'middle';
  369. ctx.fillText('Loading pattern...', center, center);
  370. ctx.restore();
  371. }
  372. // Draw player preview for modal
  373. function drawPlayerPreview(ctx, progress) {
  374. if (!ctx || !playerPreviewData || playerPreviewData.length === 0) return;
  375. const canvas = ctx.canvas;
  376. const pixelRatio = (window.devicePixelRatio || 1) * 2;
  377. const containerSize = canvas.width / pixelRatio;
  378. const center = containerSize / 2;
  379. const scale = (containerSize / 2) - 30;
  380. ctx.save();
  381. // Clear canvas for fresh drawing
  382. ctx.clearRect(0, 0, canvas.width, canvas.height);
  383. // Create circular clipping path
  384. ctx.beginPath();
  385. ctx.arc(canvas.width/2, canvas.height/2, canvas.width/2, 0, Math.PI * 2);
  386. ctx.clip();
  387. // Setup coordinate system for drawing
  388. ctx.scale(pixelRatio, pixelRatio);
  389. // Calculate how many points to draw
  390. const totalPoints = playerPreviewData.length;
  391. const pointsToDraw = Math.floor(totalPoints * progress);
  392. if (pointsToDraw < 2) {
  393. ctx.restore();
  394. return;
  395. }
  396. // Draw the pattern
  397. ctx.beginPath();
  398. ctx.strokeStyle = '#808080';
  399. ctx.lineWidth = 1;
  400. ctx.lineCap = 'round';
  401. ctx.lineJoin = 'round';
  402. // Enable high quality rendering
  403. ctx.imageSmoothingEnabled = true;
  404. ctx.imageSmoothingQuality = 'high';
  405. // Draw pattern lines up to the last complete segment
  406. for (let i = 0; i < pointsToDraw - 1; i++) {
  407. const [theta1, rho1] = playerPreviewData[i];
  408. const [theta2, rho2] = playerPreviewData[i + 1];
  409. const x1 = center + rho1 * scale * Math.cos(theta1);
  410. const y1 = center + rho1 * scale * Math.sin(theta1);
  411. const x2 = center + rho2 * scale * Math.cos(theta2);
  412. const y2 = center + rho2 * scale * Math.sin(theta2);
  413. if (i === 0) {
  414. ctx.moveTo(x1, y1);
  415. }
  416. ctx.lineTo(x2, y2);
  417. }
  418. // Draw the final partial segment to the interpolated position
  419. if (pointsToDraw > 0) {
  420. const interpolatedCoord = getInterpolatedCoordinate(progress);
  421. if (interpolatedCoord && pointsToDraw > 1) {
  422. // Get the last complete coordinate
  423. const [lastTheta, lastRho] = playerPreviewData[pointsToDraw - 1];
  424. const lastX = center + lastRho * scale * Math.cos(lastTheta);
  425. const lastY = center + lastRho * scale * Math.sin(lastTheta);
  426. // Draw line to interpolated position
  427. const [interpTheta, interpRho] = interpolatedCoord;
  428. const interpX = center + interpRho * scale * Math.cos(interpTheta);
  429. const interpY = center + interpRho * scale * Math.sin(interpTheta);
  430. ctx.lineTo(interpX, interpY);
  431. }
  432. }
  433. ctx.stroke();
  434. // Draw current position dot with interpolated position
  435. if (pointsToDraw > 0) {
  436. const interpolatedCoord = getInterpolatedCoordinate(progress);
  437. if (interpolatedCoord) {
  438. const [theta, rho] = interpolatedCoord;
  439. const x = center + rho * scale * Math.cos(theta);
  440. const y = center + rho * scale * Math.sin(theta);
  441. // Draw white border
  442. ctx.beginPath();
  443. ctx.fillStyle = '#ffffff';
  444. ctx.arc(x, y, 7.5, 0, Math.PI * 2);
  445. ctx.fill();
  446. // Draw red dot
  447. ctx.beginPath();
  448. ctx.fillStyle = '#ff0000';
  449. ctx.arc(x, y, 6, 0, Math.PI * 2);
  450. ctx.fill();
  451. }
  452. }
  453. ctx.restore();
  454. }
  455. // Load pattern coordinates for player preview
  456. async function loadPlayerPreviewData(pattern) {
  457. try {
  458. const response = await fetch('/get_theta_rho_coordinates', {
  459. method: 'POST',
  460. headers: { 'Content-Type': 'application/json' },
  461. body: JSON.stringify({ file_name: pattern })
  462. });
  463. if (!response.ok) {
  464. throw new Error(`HTTP error! status: ${response.status}`);
  465. }
  466. const data = await response.json();
  467. if (data.error) {
  468. throw new Error(data.error);
  469. }
  470. playerPreviewData = data.coordinates;
  471. // Store the filename for comparison
  472. playerPreviewData.fileName = normalizeFilePath(pattern);
  473. } catch (error) {
  474. console.error(`Error loading player preview data: ${error.message}`);
  475. playerPreviewData = null;
  476. }
  477. }
  478. // Ultra-smooth animation function for modal
  479. function animateModalPreview() {
  480. const modal = document.getElementById('playerPreviewModal');
  481. if (!modal || modal.classList.contains('hidden')) return;
  482. const canvas = document.getElementById('playerPreviewCanvas');
  483. const ctx = canvas.getContext('2d');
  484. if (!ctx || !playerPreviewData) return;
  485. const currentTime = Date.now();
  486. const elapsed = currentTime - modalAnimationStartTime;
  487. const totalDuration = animationDuration;
  488. // Calculate smooth progress with easing
  489. const rawProgress = Math.min(elapsed / totalDuration, 1);
  490. const easeProgress = rawProgress < 0.5
  491. ? 2 * rawProgress * rawProgress
  492. : 1 - Math.pow(-2 * rawProgress + 2, 2) / 2;
  493. // Interpolate between last and target progress
  494. const currentProgress = modalLastProgress + (modalTargetProgress - modalLastProgress) * easeProgress;
  495. // Draw the pattern up to current progress
  496. drawPlayerPreview(ctx, currentProgress);
  497. // Continue animation if not at target
  498. if (rawProgress < 1) {
  499. modalAnimationId = requestAnimationFrame(animateModalPreview);
  500. }
  501. }
  502. // Update modal preview with smooth animation
  503. function updateModalPreviewSmooth(newProgress) {
  504. if (newProgress === modalTargetProgress) return; // No change needed
  505. // Stop any existing animation
  506. if (modalAnimationId) {
  507. cancelAnimationFrame(modalAnimationId);
  508. }
  509. // Update animation parameters
  510. modalLastProgress = modalTargetProgress;
  511. modalTargetProgress = newProgress;
  512. modalAnimationStartTime = Date.now();
  513. // Start smooth animation
  514. animateModalPreview();
  515. }
  516. // Setup player preview modal events
  517. function setupPlayerPreviewModalEvents() {
  518. const modal = document.getElementById('playerPreviewModal');
  519. const closeBtn = document.getElementById('closePlayerPreview');
  520. const toggleBtn = document.getElementById('toggle-preview-modal-btn');
  521. if (!modal || !closeBtn || !toggleBtn) return;
  522. // Remove any existing event listeners to prevent conflicts
  523. const newToggleBtn = toggleBtn.cloneNode(true);
  524. toggleBtn.parentNode.replaceChild(newToggleBtn, toggleBtn);
  525. // Toggle button click handler
  526. newToggleBtn.addEventListener('click', () => {
  527. const isHidden = modal.classList.contains('hidden');
  528. if (isHidden) {
  529. openPlayerPreviewModal();
  530. } else {
  531. modal.classList.add('hidden');
  532. }
  533. });
  534. // Close modal when clicking close button
  535. closeBtn.addEventListener('click', () => {
  536. setModalVisibility(false, true);
  537. });
  538. // Close modal when clicking outside
  539. modal.addEventListener('click', (e) => {
  540. if (e.target === modal) {
  541. setModalVisibility(false, true);
  542. }
  543. });
  544. // Close modal with Escape key
  545. document.addEventListener('keydown', (e) => {
  546. if (e.key === 'Escape' && !modal.classList.contains('hidden')) {
  547. setModalVisibility(false, true);
  548. }
  549. });
  550. // Setup modal control buttons
  551. setupModalControls();
  552. }
  553. // Handle pause/resume toggle
  554. async function togglePauseResume() {
  555. const pauseButton = document.getElementById('modal-pause-button');
  556. if (!pauseButton) return;
  557. try {
  558. const pauseIcon = pauseButton.querySelector('.material-icons');
  559. const isCurrentlyPaused = pauseIcon.textContent === 'play_arrow';
  560. // Show immediate feedback
  561. showStatusMessage(isCurrentlyPaused ? 'Resuming...' : 'Pausing...', 'info');
  562. const endpoint = isCurrentlyPaused ? '/resume_execution' : '/pause_execution';
  563. const response = await fetch(endpoint, { method: 'POST' });
  564. if (!response.ok) throw new Error(`Failed to ${isCurrentlyPaused ? 'resume' : 'pause'}`);
  565. // Show success message
  566. showStatusMessage(isCurrentlyPaused ? 'Pattern resumed' : 'Pattern paused', 'success');
  567. } catch (error) {
  568. console.error('Error toggling pause:', error);
  569. showStatusMessage('Failed to pause/resume pattern', 'error');
  570. }
  571. }
  572. // Setup modal controls
  573. function setupModalControls() {
  574. const pauseButton = document.getElementById('modal-pause-button');
  575. const skipButton = document.getElementById('modal-skip-button');
  576. const stopButton = document.getElementById('modal-stop-button');
  577. const speedDisplay = document.getElementById('modal-speed-display');
  578. const speedInput = document.getElementById('modal-speed-input');
  579. if (!pauseButton || !skipButton || !stopButton || !speedDisplay || !speedInput) return;
  580. // Pause button click handler
  581. pauseButton.addEventListener('click', togglePauseResume);
  582. // Skip button click handler
  583. skipButton.addEventListener('click', async () => {
  584. try {
  585. // Show immediate feedback
  586. showStatusMessage('Skipping to next pattern...', 'info');
  587. const response = await fetch('/skip_pattern', { method: 'POST' });
  588. if (!response.ok) throw new Error('Failed to skip pattern');
  589. // Show success message
  590. showStatusMessage('Skipped to next pattern', 'success');
  591. } catch (error) {
  592. console.error('Error skipping pattern:', error);
  593. showStatusMessage('Failed to skip pattern', 'error');
  594. }
  595. });
  596. // Stop button click handler
  597. stopButton.addEventListener('click', async () => {
  598. try {
  599. // Show immediate feedback
  600. showStatusMessage('Stopping...', 'info');
  601. const response = await fetch('/stop_execution', { method: 'POST' });
  602. if (!response.ok) throw new Error('Failed to stop pattern');
  603. else {
  604. // Show success message
  605. showStatusMessage('Pattern stopped', 'success');
  606. // Hide modal when stopping
  607. const modal = document.getElementById('playerPreviewModal');
  608. if (modal) modal.classList.add('hidden');
  609. }
  610. } catch (error) {
  611. console.error('Error stopping pattern:', error);
  612. showStatusMessage('Failed to stop pattern', 'error');
  613. }
  614. });
  615. // Speed display click to edit
  616. speedDisplay.addEventListener('click', () => {
  617. isEditingSpeed = true;
  618. speedDisplay.classList.add('hidden');
  619. speedInput.value = speedDisplay.textContent;
  620. speedInput.classList.remove('hidden');
  621. speedInput.focus();
  622. speedInput.select();
  623. });
  624. // Speed input handlers
  625. speedInput.addEventListener('keydown', (e) => {
  626. if (e.key === 'Enter') {
  627. e.preventDefault();
  628. exitModalSpeedEditMode(true);
  629. } else if (e.key === 'Escape') {
  630. e.preventDefault();
  631. exitModalSpeedEditMode(false);
  632. }
  633. });
  634. speedInput.addEventListener('blur', () => {
  635. exitModalSpeedEditMode(true);
  636. });
  637. }
  638. // Exit modal speed edit mode
  639. async function exitModalSpeedEditMode(save = false) {
  640. const speedDisplay = document.getElementById('modal-speed-display');
  641. const speedInput = document.getElementById('modal-speed-input');
  642. if (!speedDisplay || !speedInput) return;
  643. isEditingSpeed = false;
  644. speedInput.classList.add('hidden');
  645. speedDisplay.classList.remove('hidden');
  646. if (save) {
  647. const speed = parseInt(speedInput.value);
  648. if (!isNaN(speed) && speed >= 1 && speed <= 5000) {
  649. try {
  650. const response = await fetch('/set_speed', {
  651. method: 'POST',
  652. headers: { 'Content-Type': 'application/json' },
  653. body: JSON.stringify({ speed: speed })
  654. });
  655. const data = await response.json();
  656. if (data.success) {
  657. speedDisplay.textContent = speed;
  658. showStatusMessage(`Speed set to ${speed} mm/s`, 'success');
  659. } else {
  660. throw new Error(data.detail || 'Failed to set speed');
  661. }
  662. } catch (error) {
  663. console.error('Error setting speed:', error);
  664. showStatusMessage('Failed to set speed', 'error');
  665. }
  666. } else {
  667. showStatusMessage('Please enter a valid speed (1-5000)', 'error');
  668. }
  669. }
  670. }
  671. // Helper function to clean up pattern names
  672. function getCleanPatternName(filePath) {
  673. if (!filePath) return '';
  674. const fileName = normalizeFilePath(filePath);
  675. return fileName.split('/').pop().replace('.thr', '');
  676. }
  677. // Sync modal controls with player status
  678. function syncModalControls(status) {
  679. // Pattern name - clean up to show only filename
  680. const modalPatternName = document.getElementById('modal-pattern-name');
  681. if (modalPatternName && status.current_file) {
  682. modalPatternName.textContent = getCleanPatternName(status.current_file);
  683. }
  684. // Pattern preview image
  685. const modalPatternPreviewImg = document.getElementById('modal-pattern-preview-img');
  686. if (modalPatternPreviewImg && status.current_file) {
  687. const encodedFilename = normalizeFilePath(status.current_file).replace(/[\\/]/g, '--');
  688. const previewUrl = `/preview/${encodedFilename}`;
  689. modalPatternPreviewImg.src = previewUrl;
  690. }
  691. // ETA or Pause Countdown
  692. const modalEta = document.getElementById('modal-eta');
  693. if (modalEta) {
  694. // Check if we're in a pause between patterns
  695. if (status.pause_time_remaining && status.pause_time_remaining > 0) {
  696. const minutes = Math.floor(status.pause_time_remaining / 60);
  697. const seconds = Math.floor(status.pause_time_remaining % 60);
  698. modalEta.textContent = `Next in: ${minutes}:${seconds.toString().padStart(2, '0')}`;
  699. } else if (status.progress && status.progress.remaining_time !== null) {
  700. const minutes = Math.floor(status.progress.remaining_time / 60);
  701. const seconds = Math.floor(status.progress.remaining_time % 60);
  702. modalEta.textContent = `ETA: ${minutes}:${seconds.toString().padStart(2, '0')}`;
  703. } else {
  704. modalEta.textContent = 'ETA: calculating...';
  705. }
  706. }
  707. // Progress bar
  708. const modalProgressBar = document.getElementById('modal-progress-bar');
  709. if (modalProgressBar) {
  710. if (status.progress && status.progress.percentage !== null) {
  711. modalProgressBar.style.width = `${status.progress.percentage}%`;
  712. } else {
  713. modalProgressBar.style.width = '0%';
  714. }
  715. }
  716. // Next pattern - clean up to show only filename
  717. const modalNextPattern = document.getElementById('modal-next-pattern');
  718. if (modalNextPattern) {
  719. if (status.playlist && status.playlist.next_file) {
  720. modalNextPattern.textContent = getCleanPatternName(status.playlist.next_file);
  721. } else {
  722. modalNextPattern.textContent = 'None';
  723. }
  724. }
  725. // Pause button
  726. const modalPauseBtn = document.getElementById('modal-pause-button');
  727. if (modalPauseBtn) {
  728. const pauseIcon = modalPauseBtn.querySelector('.material-icons');
  729. if (status.is_paused) {
  730. pauseIcon.textContent = 'play_arrow';
  731. } else {
  732. pauseIcon.textContent = 'pause';
  733. }
  734. }
  735. // Skip button visibility
  736. const modalSkipBtn = document.getElementById('modal-skip-button');
  737. if (modalSkipBtn) {
  738. if (status.playlist && status.playlist.next_file) {
  739. modalSkipBtn.classList.remove('invisible');
  740. } else {
  741. modalSkipBtn.classList.add('invisible');
  742. }
  743. }
  744. // Speed display
  745. const modalSpeedDisplay = document.getElementById('modal-speed-display');
  746. if (modalSpeedDisplay && status.speed && !isEditingSpeed) {
  747. modalSpeedDisplay.textContent = status.speed;
  748. }
  749. }
  750. // Toggle modal visibility
  751. function togglePreviewModal() {
  752. const modal = document.getElementById('playerPreviewModal');
  753. const toggleBtn = document.getElementById('toggle-preview-modal-btn');
  754. if (!modal || !toggleBtn) return;
  755. const isHidden = modal.classList.contains('hidden');
  756. if (isHidden) {
  757. openPlayerPreviewModal();
  758. } else {
  759. setModalVisibility(false, true);
  760. toggleBtn.classList.remove('active-tab');
  761. toggleBtn.classList.add('inactive-tab');
  762. }
  763. }
  764. // Button event handlers
  765. document.addEventListener('DOMContentLoaded', async () => {
  766. try {
  767. // Initialize WebSocket connection
  768. initializeWebSocket();
  769. // Setup player preview modal events
  770. setupPlayerPreviewModalEvents();
  771. console.log('Player initialized successfully');
  772. } catch (error) {
  773. console.error(`Error during initialization: ${error.message}`);
  774. }
  775. });
  776. // Initialize WebSocket connection
  777. function initializeWebSocket() {
  778. connectWebSocket();
  779. }
  780. // Clean up WebSocket when page unloads to prevent memory leaks
  781. window.addEventListener('beforeunload', () => {
  782. if (ws) {
  783. // Disable reconnection before closing
  784. ws.onclose = null;
  785. ws.close();
  786. ws = null;
  787. }
  788. });
  789. // Add resize handler for responsive canvas with debouncing
  790. let resizeTimeout;
  791. window.addEventListener('resize', () => {
  792. const canvas = document.getElementById('playerPreviewCanvas');
  793. const modal = document.getElementById('playerPreviewModal');
  794. if (canvas && modal && !modal.classList.contains('hidden')) {
  795. // Clear previous timeout
  796. clearTimeout(resizeTimeout);
  797. // Debounce resize calls to avoid excessive updates
  798. resizeTimeout = setTimeout(() => {
  799. const ctx = canvas.getContext('2d');
  800. setupPlayerPreviewCanvas(ctx);
  801. drawPlayerPreview(ctx, targetProgress);
  802. }, 16); // ~60fps update rate
  803. }
  804. });
  805. // Handle file changes and reload preview data
  806. function handleFileChange(newFile) {
  807. if (newFile !== currentPreviewFile) {
  808. currentPreviewFile = newFile;
  809. if (newFile) {
  810. loadPlayerPreviewData(`./patterns/${newFile}`);
  811. } else {
  812. playerPreviewData = null;
  813. }
  814. }
  815. }
  816. // Cache All Previews Prompt functionality
  817. let cacheAllInProgress = false;
  818. function shouldShowCacheAllPrompt() {
  819. // Check if we've already shown the prompt
  820. const promptShown = localStorage.getItem('cacheAllPromptShown');
  821. console.log('shouldShowCacheAllPrompt - promptShown:', promptShown);
  822. return !promptShown;
  823. }
  824. function showCacheAllPrompt(forceShow = false) {
  825. console.log('showCacheAllPrompt called, forceShow:', forceShow);
  826. if (!forceShow && !shouldShowCacheAllPrompt()) {
  827. console.log('Cache all prompt already shown, skipping');
  828. return;
  829. }
  830. const modal = document.getElementById('cacheAllPromptModal');
  831. if (modal) {
  832. console.log('Showing cache all prompt modal');
  833. modal.classList.remove('hidden');
  834. // Store whether this was forced (manually triggered)
  835. modal.dataset.manuallyTriggered = forceShow.toString();
  836. } else {
  837. console.log('Cache all prompt modal not found');
  838. }
  839. }
  840. function hideCacheAllPrompt() {
  841. const modal = document.getElementById('cacheAllPromptModal');
  842. if (modal) {
  843. modal.classList.add('hidden');
  844. }
  845. }
  846. function markCacheAllPromptAsShown() {
  847. localStorage.setItem('cacheAllPromptShown', 'true');
  848. }
  849. function initializeCacheAllPrompt() {
  850. const modal = document.getElementById('cacheAllPromptModal');
  851. const skipBtn = document.getElementById('skipCacheAllBtn');
  852. const startBtn = document.getElementById('startCacheAllBtn');
  853. const closeBtn = document.getElementById('closeCacheAllBtn');
  854. if (!modal || !skipBtn || !startBtn || !closeBtn) {
  855. return;
  856. }
  857. // Skip button handler
  858. skipBtn.addEventListener('click', () => {
  859. const wasManuallyTriggered = modal.dataset.manuallyTriggered === 'true';
  860. hideCacheAllPrompt();
  861. // Only mark as shown if it was automatically shown (not manually triggered)
  862. if (!wasManuallyTriggered) {
  863. markCacheAllPromptAsShown();
  864. }
  865. });
  866. // Close button handler (after completion)
  867. closeBtn.addEventListener('click', () => {
  868. const wasManuallyTriggered = modal.dataset.manuallyTriggered === 'true';
  869. hideCacheAllPrompt();
  870. // Always mark as shown after successful completion
  871. if (!wasManuallyTriggered) {
  872. markCacheAllPromptAsShown();
  873. }
  874. });
  875. // Start caching button handler
  876. startBtn.addEventListener('click', async () => {
  877. if (cacheAllInProgress) {
  878. return;
  879. }
  880. cacheAllInProgress = true;
  881. // Hide buttons and show progress
  882. document.getElementById('cacheAllButtons').classList.add('hidden');
  883. document.getElementById('cacheAllProgress').classList.remove('hidden');
  884. try {
  885. await startCacheAllProcess();
  886. // Show completion message
  887. document.getElementById('cacheAllProgress').classList.add('hidden');
  888. document.getElementById('cacheAllComplete').classList.remove('hidden');
  889. } catch (error) {
  890. console.error('Error caching all previews:', error);
  891. // Show error and reset
  892. document.getElementById('cacheAllProgressText').textContent = 'Error occurred during caching';
  893. setTimeout(() => {
  894. hideCacheAllPrompt();
  895. markCacheAllPromptAsShown();
  896. }, 3000);
  897. } finally {
  898. cacheAllInProgress = false;
  899. }
  900. });
  901. }
  902. async function startCacheAllProcess() {
  903. try {
  904. // Get list of patterns using cached function
  905. const patterns = await getCachedPatternFiles();
  906. if (!patterns || patterns.length === 0) {
  907. throw new Error('No patterns found');
  908. }
  909. const progressBar = document.getElementById('cacheAllProgressBar');
  910. const progressText = document.getElementById('cacheAllProgressText');
  911. const progressPercentage = document.getElementById('cacheAllProgressPercentage');
  912. let completed = 0;
  913. const batchSize = 5; // Process in small batches to avoid overwhelming the server
  914. for (let i = 0; i < patterns.length; i += batchSize) {
  915. const batch = patterns.slice(i, i + batchSize);
  916. // Update progress text
  917. progressText.textContent = `Caching previews... (${Math.min(i + batchSize, patterns.length)}/${patterns.length})`;
  918. // Process batch
  919. const batchPromises = batch.map(async (pattern) => {
  920. try {
  921. const previewResponse = await fetch('/preview_thr', {
  922. method: 'POST',
  923. headers: {
  924. 'Content-Type': 'application/json',
  925. },
  926. body: JSON.stringify({ file_name: pattern })
  927. });
  928. if (previewResponse.ok) {
  929. const data = await previewResponse.json();
  930. if (data.preview_url) {
  931. // Pre-load the image to cache it
  932. return new Promise((resolve) => {
  933. const img = new Image();
  934. img.onload = () => resolve();
  935. img.onerror = () => resolve(); // Continue even if image fails
  936. img.src = data.preview_url;
  937. });
  938. }
  939. }
  940. return Promise.resolve();
  941. } catch (error) {
  942. console.warn(`Failed to cache preview for ${pattern}:`, error);
  943. return Promise.resolve(); // Continue with other patterns
  944. }
  945. });
  946. await Promise.all(batchPromises);
  947. completed += batch.length;
  948. // Update progress bar
  949. const progress = Math.round((completed / patterns.length) * 100);
  950. progressBar.style.width = `${progress}%`;
  951. progressPercentage.textContent = `${progress}%`;
  952. // Small delay between batches to prevent overwhelming the server
  953. if (i + batchSize < patterns.length) {
  954. await new Promise(resolve => setTimeout(resolve, 100));
  955. }
  956. }
  957. progressText.textContent = `Completed! Cached ${patterns.length} previews.`;
  958. } catch (error) {
  959. throw error;
  960. }
  961. }
  962. // Function to be called after initial cache generation completes
  963. function onInitialCacheComplete() {
  964. console.log('onInitialCacheComplete called');
  965. // Show the cache all prompt after a short delay
  966. setTimeout(() => {
  967. console.log('Triggering cache all prompt after delay');
  968. showCacheAllPrompt();
  969. }, 1000);
  970. }
  971. // Initialize on DOM load
  972. document.addEventListener('DOMContentLoaded', () => {
  973. initializeCacheAllPrompt();
  974. });
  975. // Make functions available globally for debugging
  976. window.onInitialCacheComplete = onInitialCacheComplete;
  977. window.showCacheAllPrompt = showCacheAllPrompt;
  978. window.testCacheAllPrompt = function() {
  979. console.log('Manual test trigger');
  980. // Clear localStorage for testing
  981. localStorage.removeItem('cacheAllPromptShown');
  982. showCacheAllPrompt();
  983. };