Guest User

Stash-TCode-5.6-Beta

a guest
Jan 2nd, 2026
219
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
JavaScript 62.44 KB | Source Code | 0 0
  1. // ==UserScript==
  2. // @name         Stash-TCode-USB
  3. // @namespace    Steel
  4. // @version      0.5.6-USB-Beta
  5. // @description  Integrate TCode Devices with Stash via USB Web Serial
  6. // @author       Steel (Spunkle-Modded)
  7. // @include      http*://*:9999*
  8. // @grant        GM_xmlhttpRequest
  9. // @grant        GM_setValue
  10. // @grant        GM_getValue
  11. // @grant        GM_info
  12. // @grant        unsafeWindow
  13. // @license      GPLv3
  14. // ==/UserScript==
  15.  
  16. var video="";
  17. var lastPage = null;
  18.  
  19. var pendingKey = null;
  20.  
  21. var settings = loadSettings();
  22.  
  23. // --- SERIAL VARIABLES ---
  24. var port = null;
  25. var writer = null;
  26. var keepReading = false;
  27. var serialConnected = false;
  28. var reader = null;
  29. var readableStreamClosed = null;
  30. var writableStreamClosed = null;
  31. var textEncoder = new TextEncoder();
  32. var serialBuffer = ""; // Buffer for accumulating fragmented serial responses
  33. var bufferTimeout = null;
  34. // ------------------------
  35.  
  36. var scriptList = null;
  37. var AXIS = new Object();
  38. var adjustMin = false; // 0 = Max 1= Min
  39. var scrollWheelEnabled = false; // Only enabled when minKey or initialKey is held
  40. var pending = false;
  41. var msPending = false;
  42. var mouseEnabled = true;
  43. var videoPlayerLoaded = false;
  44. const BOTH = 0;
  45. const LOWER = 1;
  46. const UPPER = 2;
  47. const isChrome = !!unsafeWindow.chrome;
  48.  
  49. function isNewerVersion (oldVer, newVer) {
  50.     const oldParts = oldVer.split('.')
  51.     const newParts = newVer.split('.')
  52.     for (var i = 0; i < newParts.length; i++) {
  53.         const a = ~~newParts[i]; const b = ~~oldParts[i];
  54.         if (a > b) return true; if (a < b) return false;
  55.     }
  56.     return false;
  57. }
  58.  
  59. function handleUpgrade(thisVersion){
  60.     if(settings.currentVersion === undefined || isNewerVersion(settings.currentVersion, thisVersion)){
  61.         return true;
  62.     }
  63.     return false;
  64. }
  65.  
  66. function getLimit(axis, which=BOTH){
  67.     var limits = [0, 9999];
  68.     if(AXIS && AXIS[axis] && AXIS[axis].limits){ limits = AXIS[axis].limits; }
  69.     switch(which){
  70.         case BOTH: return limits;
  71.         case LOWER: return limits[0];
  72.         case UPPER: return limits[1];
  73.     }
  74. }
  75.  
  76. function debug(text, value=""){
  77.     if(settings.debug){
  78.         if(value == ""){ console.log(text); } else { unsafeWindow[value] = text; }
  79.     }
  80. }
  81.  
  82. function settingsMenuApplySaved(){
  83.     for(const setting in settings){
  84.         if(setting == "axes"){
  85.             for (const axis in settings.axes){
  86.                 var axisCheck = document.querySelector('#enable' + axis);
  87.                 if(axisCheck && settings.axes[axis].enabled){
  88.                     axisCheck.checked = true;
  89.                     var parentContainer = axisCheck.parentNode.parentNode.querySelector('.dual-slider-container');
  90.                     if(parentContainer){ parentContainer.classList.remove('disabled'); }
  91.                 }
  92.                 var randomCheck = document.querySelector('#random' + axis);
  93.                 if(randomCheck){
  94.                     if(settings.axes[axis].random == ""){ continue; }
  95.                     randomCheck.checked = true;
  96.                     var trackedAxis = document.querySelector('#track' + axis);
  97.                     if(trackedAxis){ trackedAxis.value = settings.axes[axis].random; }
  98.                 }
  99.                 var invertCheck = document.querySelector('#invert' + axis);
  100.                 if(invertCheck && settings.axes[axis].invert){ invertCheck.checked = true; }
  101.             }
  102.             continue;
  103.         }
  104.         var input = document.querySelector('#' + setting);
  105.         if(input){
  106.             if(input.type == "checkbox"){
  107.                 if(JSON.parse(settings[setting])){ input.checked = true; }
  108.             }else if(input.type == "text" || input.type == "range"){
  109.                 input.value = settings[setting];
  110.             }
  111.         }
  112.     }
  113. }
  114.  
  115. function saveSettings(saveToDevice=true){
  116.     for(const setting in settings){
  117.         if(setting == "axes"){
  118.             for (const axis in settings.axes){
  119.                 var axisCheck = document.querySelector('#enable' + axis);
  120.                 if(axisCheck){ settings.axes[axis].enabled = axisCheck.checked; }
  121.                 var randomCheck = document.querySelector('#random' + axis);
  122.                 if(randomCheck){
  123.                     if(!randomCheck.checked){ settings.axes[axis].random = ""; continue; }
  124.                     var trackedAxis = document.querySelector('#track' + axis);
  125.                     if(trackedAxis){ settings.axes[axis].random = trackedAxis.value; }
  126.                 }
  127.                 var invertCheck = document.querySelector('#invert' + axis);
  128.                 if(invertCheck){ settings.axes[axis].invert = invertCheck.checked; }
  129.             }
  130.             continue;
  131.         }
  132.         var input = document.querySelector('#' + setting);
  133.         if(input){
  134.             if(input.type == "checkbox"){
  135.                 if(input.checked){ settings[setting] = true; }else{ settings[setting] = false; }
  136.             }else if(input.type == "text" || input.type == "range"){
  137.                 settings[setting] = input.value;
  138.             }
  139.         }
  140.     }
  141.     if(saveToDevice){
  142.         for(const axis of listAxes()){
  143.             var min = document.querySelector('#min' + axis);
  144.             var max = document.querySelector('#max' + axis);
  145.             if(min && max){ setLimits(min.value, max.value, axis); }
  146.         }
  147.     }
  148.     GM_setValue("settings", settings);
  149. }
  150.  
  151. function loadSettings(){
  152.     var thisVersion = GM_info.script.version;
  153.     var defaultSettings = {"debug": false, "device": "", "initialKey": "Shift", "minKey": "Meta", "settingsKey": "F2", "syncKey": "z", "sync": 0,
  154.                            "showNotifications": true,
  155.                            "axes": { L0: {enabled: true, random: "", invert: false}, L1: {enabled: false, random: "", invert: false}, L2: {enabled: false, random: "", invert: false}, R0: {enabled: false, random: "", invert: false}, R1: {enabled: false, random: "", invert: false}, R2: {enabled: false, random: "", invert: false} },
  156.                            "currentVersion": thisVersion};
  157.     settings = GM_getValue("settings", defaultSettings);
  158.     handleUpgrade(thisVersion);
  159.     for(const setting in defaultSettings){
  160.         if(settings[setting] === undefined){ settings[setting] = defaultSettings[setting]; }
  161.     }
  162.     return settings;
  163. }
  164.  
  165. // --- TOAST NOTIFICATION SYSTEM ---
  166. var toastContainer = null;
  167. var toastQueue = [];
  168. var toastActive = false;
  169.  
  170. function initToastContainer() {
  171.     if (toastContainer) return;
  172.     toastContainer = document.createElement('div');
  173.     toastContainer.id = 'tcode-toast-container';
  174.     toastContainer.style.cssText = `
  175.         position: fixed; bottom: 20px; left: 50%; transform: translateX(-50%);
  176.         z-index: 999999; display: flex; flex-direction: column-reverse; gap: 8px;
  177.         pointer-events: none; max-width: 90%; width: 400px;
  178.     `;
  179.     document.body.appendChild(toastContainer);
  180.    
  181.     // Add toast styles
  182.     var toastStyles = document.createElement('style');
  183.     toastStyles.id = 'tcode-toast-styles';
  184.     toastStyles.textContent = `
  185.         .tcode-toast {
  186.             background: linear-gradient(135deg, rgba(26, 26, 46, 0.95) 0%, rgba(22, 33, 62, 0.95) 100%);
  187.             border: 1px solid rgba(255, 255, 255, 0.1);
  188.             border-radius: 12px;
  189.             padding: 14px 20px;
  190.             color: #fff;
  191.             font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
  192.             font-size: 14px;
  193.             box-shadow: 0 10px 40px rgba(0, 0, 0, 0.4);
  194.             backdrop-filter: blur(10px);
  195.             -webkit-backdrop-filter: blur(10px);
  196.             display: flex;
  197.             align-items: center;
  198.             gap: 12px;
  199.             animation: toastSlideIn 0.3s ease-out;
  200.             pointer-events: auto;
  201.         }
  202.         .tcode-toast.toast-success { border-left: 4px solid #4ade80; }
  203.         .tcode-toast.toast-info { border-left: 4px solid #60a5fa; }
  204.         .tcode-toast.toast-warning { border-left: 4px solid #fbbf24; }
  205.         .tcode-toast.toast-error { border-left: 4px solid #f87171; }
  206.         .tcode-toast .toast-icon {
  207.             font-size: 1.4em;
  208.             flex-shrink: 0;
  209.         }
  210.         .tcode-toast .toast-content {
  211.             flex: 1;
  212.         }
  213.         .tcode-toast .toast-title {
  214.             font-weight: 600;
  215.             margin-bottom: 2px;
  216.         }
  217.         .tcode-toast .toast-message {
  218.             opacity: 0.8;
  219.             font-size: 0.9em;
  220.         }
  221.         .tcode-toast.toast-exit {
  222.             animation: toastSlideOut 0.3s ease-in forwards;
  223.         }
  224.         @keyframes toastSlideIn {
  225.             from { opacity: 0; transform: translateY(20px); }
  226.             to { opacity: 1; transform: translateY(0); }
  227.         }
  228.         @keyframes toastSlideOut {
  229.             from { opacity: 1; transform: translateY(0); }
  230.             to { opacity: 0; transform: translateY(-20px); }
  231.         }
  232.     `;
  233.     document.head.appendChild(toastStyles);
  234. }
  235.  
  236. function showToast(title, message, type = 'info', duration = 4000) {
  237.     if (!settings.showNotifications) return;
  238.    
  239.     initToastContainer();
  240.    
  241.     var icons = {
  242.         success: '✅',
  243.         info: 'ℹ️',
  244.         warning: '⚠️',
  245.         error: '❌'
  246.     };
  247.    
  248.     var toast = document.createElement('div');
  249.     toast.className = 'tcode-toast toast-' + type;
  250.     toast.innerHTML = `
  251.         <span class="toast-icon">${icons[type] || icons.info}</span>
  252.         <div class="toast-content">
  253.             <div class="toast-title">${title}</div>
  254.             ${message ? '<div class="toast-message">' + message + '</div>' : ''}
  255.         </div>
  256.     `;
  257.    
  258.     toastContainer.appendChild(toast);
  259.    
  260.     // Auto-remove after duration
  261.     setTimeout(() => {
  262.         toast.classList.add('toast-exit');
  263.         setTimeout(() => {
  264.             if (toast.parentNode) toast.remove();
  265.         }, 300);
  266.     }, duration);
  267. }
  268. // ---------------------------------
  269.  
  270. function setKey(key){
  271.     settings[pendingKey] = key;
  272.     var label = document.getElementById(pendingKey).label;
  273.     document.getElementById(pendingKey).innerHTML = label + " " + settings[pendingKey];
  274.     pendingKey = null;
  275.     saveSettings();
  276. }
  277.  
  278. function settingsAddButton(parent, id, label, key=""){
  279.     var button = document.createElement("button");
  280.     button.setAttribute("id", id);
  281.     button.innerHTML = label;
  282.     button.label = label;
  283.     if(key != ""){ button.innerHTML += " " + key; }
  284.     parent.appendChild(button);
  285. }
  286.  
  287. function settingsAddCheckBox(parent, id, label){
  288.     var box = document.createElement("input");
  289.     box.setAttribute("id", id);
  290.     box.setAttribute("type", "checkbox");
  291.     var boxLabel = document.createElement("label");
  292.     boxLabel.setAttribute("for", id);
  293.     boxLabel.innerHTML = " " + label;
  294.     parent.appendChild(box);
  295.     parent.appendChild(boxLabel);
  296. }
  297.  
  298. function settingsAddInput(parent, id, label){
  299.     var input = document.createElement("input");
  300.     input.setAttribute("id", id);
  301.     input.style.marginLeft = "3px";
  302.     var inputLabel = document.createElement("label");
  303.     inputLabel.setAttribute("for", id);
  304.     inputLabel.innerHTML = " " + label;
  305.     parent.appendChild(inputLabel);
  306.     parent.appendChild(input);
  307. }
  308.  
  309. function settingsAddDualSlider(parent, minId, maxId, label, minVal, maxVal, minLimit, maxLimit) {
  310.     minVal = parseFloat(minVal); maxVal = parseFloat(maxVal); minLimit = parseFloat(minLimit); maxLimit = parseFloat(maxLimit);
  311.     if (isNaN(minVal)) minVal = 0; if (isNaN(maxVal)) maxVal = 100; if (isNaN(minLimit)) minLimit = 0; if (isNaN(maxLimit)) maxLimit = 100;
  312.  
  313.     var wrapper = document.createElement("div"); wrapper.className = "dual-slider-container";
  314.     var labelElem = document.createElement("label"); labelElem.innerHTML = label; wrapper.appendChild(labelElem);
  315.    
  316.     // Slider wrapper for positioning
  317.     var sliderArea = document.createElement("div");
  318.     sliderArea.className = "slider-area";
  319.     sliderArea.style.cssText = "position: relative; height: 24px; width: 100%;";
  320.    
  321.     var track = document.createElement("div"); track.className = "slider-track"; sliderArea.appendChild(track);
  322.     var fill = document.createElement("div"); fill.className = "slider-fill"; fill.id = minId + "Fill"; sliderArea.appendChild(fill);
  323.  
  324.     var minSlider = document.createElement("input");
  325.     minSlider.type = "range"; minSlider.id = minId;
  326.     minSlider.min = minLimit; minSlider.max = maxLimit; minSlider.value = minVal; minSlider.step = "1";
  327.     minSlider.style.cssText = "position: absolute; left: 0; top: 50%; transform: translateY(-50%); width: 100%;";
  328.     sliderArea.appendChild(minSlider);
  329.  
  330.     var maxSlider = document.createElement("input");
  331.     maxSlider.type = "range"; maxSlider.id = maxId;
  332.     maxSlider.min = minLimit; maxSlider.max = maxLimit; maxSlider.value = maxVal; maxSlider.step = "1";
  333.     maxSlider.style.cssText = "position: absolute; left: 0; top: 50%; transform: translateY(-50%); width: 100%;";
  334.     sliderArea.appendChild(maxSlider);
  335.    
  336.     wrapper.appendChild(sliderArea);
  337.  
  338.     var valuesDiv = document.createElement("div"); valuesDiv.className = "dual-slider-values";
  339.     var minSpan = document.createElement("span"); minSpan.id = minId + "Value"; minSpan.innerHTML = minVal; valuesDiv.appendChild(minSpan);
  340.     var maxSpan = document.createElement("span"); maxSpan.id = maxId + "Value"; maxSpan.innerHTML = maxVal; valuesDiv.appendChild(maxSpan);
  341.     wrapper.appendChild(valuesDiv);
  342.     parent.appendChild(wrapper);
  343. }
  344.  
  345. function settingsAddSingleSlider(parent, id, label, value, minLimit, maxLimit, suffix="ms") {
  346.     value = parseFloat(value); minLimit = parseFloat(minLimit); maxLimit = parseFloat(maxLimit);
  347.     if (isNaN(value)) value = minLimit;
  348.  
  349.     var wrapper = document.createElement("div"); wrapper.className = "single-slider-container";
  350.     var labelElem = document.createElement("label"); labelElem.innerHTML = label; wrapper.appendChild(labelElem);
  351.     var sliderWrapper = document.createElement("div"); sliderWrapper.className = "slider-wrapper"; wrapper.appendChild(sliderWrapper);
  352.     var track = document.createElement("div"); track.className = "slider-track"; sliderWrapper.appendChild(track);
  353.     var fill = document.createElement("div"); fill.className = "slider-fill"; fill.id = id + "Fill"; sliderWrapper.appendChild(fill);
  354.  
  355.     var slider = document.createElement("input"); slider.type = "range"; slider.id = id; slider.min = minLimit; slider.max = maxLimit; slider.value = value; slider.step = "1";
  356.     if(isChrome){ slider.style = "margin-top: -4px; transform: translateY(-50%)"; }
  357.     sliderWrapper.appendChild(slider);
  358.  
  359.     var valueSpan = document.createElement("span"); valueSpan.id = id + "Value"; valueSpan.className = "single-slider-value"; valueSpan.innerHTML = String(value + suffix).padStart(6, ' ');
  360.     wrapper.appendChild(valueSpan);
  361.     parent.appendChild(wrapper);
  362.  
  363.     slider.addEventListener('input', () => {
  364.         const currentVal = parseFloat(slider.value);
  365.         const range = maxLimit - minLimit;
  366.         const percent = ((currentVal - minLimit) / range) * 100;
  367.         fill.style.width = `${percent}%`;
  368.         valueSpan.textContent = String(currentVal + suffix).padStart(6, ' ');
  369.     });
  370.     const initialRange = maxLimit - minLimit;
  371.     const initialPercent = ((value - minLimit) / initialRange) * 100;
  372.     fill.style.width = `${initialPercent}%`;
  373. }
  374.  
  375. function settingsAddGroupedControls(parent, checkboxId, axis, minId, maxId, sliderLabel, minVal, maxVal, minLimit, maxLimit, allSliderIds) {
  376.     const groupContainer = document.createElement('div'); groupContainer.classList.add('control-group'); parent.appendChild(groupContainer);
  377.     const checkboxWrapper = document.createElement('div'); checkboxWrapper.classList.add('checkbox-wrapper');
  378.     const checkbox = document.createElement('input'); checkbox.type = 'checkbox'; checkbox.id = checkboxId; checkbox.checked = false;
  379.     checkboxWrapper.appendChild(checkbox);
  380.     const label = document.createElement('label'); label.setAttribute('for', checkboxId); label.textContent = axis;
  381.     checkboxWrapper.appendChild(label); groupContainer.appendChild(checkboxWrapper);
  382.  
  383.     const randomWrapper = document.createElement('div'); randomWrapper.classList.add('random-wrapper');
  384.     const randomCheckbox = document.createElement('input'); randomCheckbox.type = 'checkbox'; randomCheckbox.id = `random${axis}`;
  385.     randomWrapper.appendChild(randomCheckbox);
  386.     const randomLabel = document.createElement('label'); randomLabel.setAttribute('for', `random${axis}`); randomLabel.textContent = 'Random';
  387.     randomWrapper.appendChild(randomLabel);
  388.  
  389.     const trackDropdown = document.createElement('select'); trackDropdown.id = `track${axis}`;
  390.     allSliderIds.forEach(id => {
  391.         if (id !== minId) {
  392.             const option = document.createElement('option'); option.value = id; option.textContent = id; trackDropdown.appendChild(option);
  393.         }
  394.     });
  395.     randomWrapper.appendChild(trackDropdown); groupContainer.appendChild(randomWrapper);
  396.  
  397.     const invertWrapper = document.createElement('div'); invertWrapper.classList.add('invert-wrapper');
  398.     const invertCheckbox = document.createElement('input'); invertCheckbox.type = 'checkbox'; invertCheckbox.id = `invert${axis}`;
  399.     invertWrapper.appendChild(invertCheckbox);
  400.     const invertLabel = document.createElement('label'); invertLabel.setAttribute('for', `invert${axis}`); invertLabel.textContent = 'Invert';
  401.     invertWrapper.appendChild(invertLabel);
  402.     groupContainer.appendChild(invertWrapper);
  403.  
  404.     settingsAddDualSlider(groupContainer, minId, maxId, sliderLabel, minVal, maxVal, minLimit, maxLimit);
  405.     const dualSliderContainer = groupContainer.querySelector('.dual-slider-container');
  406.  
  407.     checkbox.addEventListener('change', (event) => {
  408.         settings.axes[axis].enabled = event.target.checked;
  409.         if (event.target.checked) {
  410.             dualSliderContainer.classList.remove('disabled');
  411.             randomWrapper.style.opacity = '1';
  412.             invertWrapper.style.opacity = '1';
  413.         } else {
  414.             dualSliderContainer.classList.add('disabled');
  415.             randomWrapper.style.opacity = '0.5';
  416.             invertWrapper.style.opacity = '0.5';
  417.         }
  418.     });
  419.     randomCheckbox.addEventListener('change', (event) => { settings.axes[axis].random = event.target.value; });
  420.     invertCheckbox.addEventListener('change', (event) => { settings.axes[axis].invert = event.target.checked; });
  421.     toolTip(randomCheckbox, "Generates random motion, based on selected axis");
  422.     if (!checkbox.checked) {
  423.         dualSliderContainer.classList.add('disabled');
  424.         randomWrapper.style.opacity = '0.5';
  425.         invertWrapper.style.opacity = '0.5';
  426.     }
  427. }
  428.  
  429. function menuListeners(keys){
  430.     for(var key of keys){
  431.         document.getElementById(key).addEventListener("click", function(){ this.innerHTML = "Press a key..."; pendingKey = this.id; }, false);
  432.     }
  433. }
  434.  
  435. function dualSliderListeners(minId, maxId) {
  436.     const minSlider = document.getElementById(minId); const maxSlider = document.getElementById(maxId);
  437.     const fill = document.getElementById(minId + "Fill"); const minValueDisplay = document.getElementById(minId + "Value"); const maxValueDisplay = document.getElementById(maxId + "Value");
  438.     if (!minSlider || !maxSlider || !minValueDisplay || !maxValueDisplay || !fill) return;
  439.  
  440.     function updateDualSlider() {
  441.         let currentMinVal = parseFloat(minSlider.value); let currentMaxVal = parseFloat(maxSlider.value);
  442.         if (currentMinVal > currentMaxVal) { minSlider.value = currentMaxVal; }
  443.         if (currentMaxVal < currentMinVal) { maxSlider.value = currentMinVal; }
  444.         currentMinVal = parseFloat(minSlider.value); currentMaxVal = parseFloat(maxSlider.value);
  445.         const range = parseFloat(maxSlider.max) - parseFloat(minSlider.min);
  446.         const minPercent = ((currentMinVal - parseFloat(minSlider.min)) / range) * 100;
  447.         const maxPercent = ((currentMaxVal - parseFloat(minSlider.min)) / range) * 100;
  448.         fill.style.left = `${minPercent}%`; fill.style.width = `${Math.abs(maxPercent - minPercent)}%`;
  449.         minValueDisplay.textContent = currentMinVal; maxValueDisplay.textContent = currentMaxVal;
  450.         setLimits(currentMinVal, currentMaxVal, minSlider.id.replace('min', ''), false);
  451.     }
  452.     minSlider.addEventListener('input', updateDualSlider); maxSlider.addEventListener('input', updateDualSlider);
  453.     updateDualSlider();
  454. }
  455.  
  456. let activeTab = 'device';
  457. function settingsAddTabContent(parentDiv, type, id, label, key = "") {
  458.     switch (type) {
  459.         case 'button': settingsAddButton(parentDiv, id, label, key); break;
  460.         case 'checkbox': settingsAddCheckBox(parentDiv, id, label); break;
  461.         case 'input': settingsAddInput(parentDiv, id, label); break;
  462.     }
  463. }
  464.  
  465. function showTab(tabId) {
  466.     const tabContents = document.querySelectorAll('.tab-content'); tabContents.forEach(content => { content.style.display = 'none'; });
  467.     const tabButtons = document.querySelectorAll('.tab-button'); tabButtons.forEach(button => { button.classList.remove('active-tab'); });
  468.     const selectedTabContent = document.getElementById(tabId + 'Content'); if (selectedTabContent) { selectedTabContent.style.display = 'block'; }
  469.     const selectedTabButton = document.getElementById(tabId + 'Tab'); if (selectedTabButton) { selectedTabButton.classList.add('active-tab'); }
  470.     activeTab = tabId;
  471. }
  472.  
  473. function toolTip(element, txt){
  474.     var tooltip = document.querySelector('#dynamic-tooltip');
  475.     if(!tooltip){
  476.         tooltip = document.createElement('div'); tooltip.id = 'dynamic-tooltip';
  477.         tooltip.style.position = 'absolute'; tooltip.style.backgroundColor = 'black'; tooltip.style.color = 'white';
  478.         tooltip.style.padding = '5px'; tooltip.style.zIndex = '200000'; tooltip.style.visibility = 'hidden';
  479.         document.body.appendChild(tooltip);
  480.     }
  481.     var tooltipTimeout = null;
  482.     element.addEventListener('mouseover', () => { tooltipTimeout = setTimeout(function(){ tooltip.textContent = txt; tooltip.style.visibility = 'visible'; }, 750); });
  483.     element.addEventListener('mousemove', (e) => { tooltip.style.left = e.pageX + 10 + 'px'; tooltip.style.top = e.pageY + 10 + 'px'; });
  484.     element.addEventListener('mouseout', () => { clearTimeout(tooltipTimeout); tooltip.style.visibility = 'hidden'; });
  485. }
  486.  
  487. function toggleMenu() {
  488.     if (document.getElementById("settings-overlay") != null) {
  489.         document.getElementById("settings-close-btn").click();
  490.         return -1;
  491.     }
  492.  
  493.     // Modern dark theme stylesheet
  494.     const styleSheet = document.createElement("style");
  495.     styleSheet.id = "stash-tcode-styles";
  496.     styleSheet.type = "text/css";
  497.     styleSheet.innerText = `
  498. /* Overlay backdrop with blur */
  499. #settings-overlay {
  500.     position: fixed; top: 0; left: 0; right: 0; bottom: 0;
  501.     background: rgba(0, 0, 0, 0.6); backdrop-filter: blur(8px); -webkit-backdrop-filter: blur(8px);
  502.     z-index: 999998; display: flex; align-items: center; justify-content: center;
  503. }
  504.  
  505. /* Main settings panel */
  506. #settings {
  507.     position: relative; width: 90%; max-width: 700px; max-height: 85vh;
  508.     background: linear-gradient(145deg, #1a1a2e 0%, #16213e 100%);
  509.     border-radius: 16px; box-shadow: 0 25px 50px -12px rgba(0, 0, 0, 0.5), 0 0 0 1px rgba(255, 255, 255, 0.1);
  510.     overflow: hidden; font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
  511. }
  512.  
  513. /* Header */
  514. #settings .settings-header {
  515.     background: linear-gradient(90deg, #0f3460 0%, #533483 100%);
  516.     padding: 20px 24px; display: flex; align-items: center; justify-content: space-between;
  517. }
  518. #settings .settings-title {
  519.     font-size: 1.5em; font-weight: 700; color: #fff; letter-spacing: 0.5px;
  520.     text-shadow: 0 2px 4px rgba(0,0,0,0.3);
  521. }
  522. #settings-close-btn {
  523.     width: 36px; height: 36px; border-radius: 50%; border: none;
  524.     background: rgba(255,255,255,0.1); color: #fff; font-size: 1.4em;
  525.     cursor: pointer; transition: all 0.2s ease; display: flex; align-items: center; justify-content: center;
  526. }
  527. #settings-close-btn:hover { background: rgba(255,255,255,0.2); transform: scale(1.1); }
  528.  
  529. /* Tab navigation */
  530. #tabContainer {
  531.     display: flex; background: rgba(0,0,0,0.3); padding: 0 16px; gap: 4px;
  532. }
  533. .tab-button {
  534.     padding: 14px 20px; border: none; background: transparent; color: rgba(255,255,255,0.6);
  535.     font-size: 0.95em; font-weight: 500; cursor: pointer; transition: all 0.2s ease;
  536.     border-bottom: 3px solid transparent; text-transform: uppercase; letter-spacing: 0.5px;
  537. }
  538. .tab-button:hover { color: rgba(255,255,255,0.9); background: rgba(255,255,255,0.05); }
  539. .tab-button.active-tab {
  540.     color: #e94560 !important; border-bottom-color: #e94560 !important;
  541.     background: rgba(233, 69, 96, 0.1) !important;
  542. }
  543.  
  544. /* Tab content area */
  545. #tabContentContainer {
  546.     padding: 24px; max-height: calc(85vh - 140px); overflow-y: auto; color: #e0e0e0;
  547. }
  548. #tabContentContainer::-webkit-scrollbar { width: 8px; }
  549. #tabContentContainer::-webkit-scrollbar-track { background: rgba(255,255,255,0.05); border-radius: 4px; }
  550. #tabContentContainer::-webkit-scrollbar-thumb { background: rgba(255,255,255,0.2); border-radius: 4px; }
  551. #tabContentContainer::-webkit-scrollbar-thumb:hover { background: rgba(255,255,255,0.3); }
  552. .tab-content { display: none; animation: fadeIn 0.3s ease; }
  553. @keyframes fadeIn { from { opacity: 0; transform: translateY(10px); } to { opacity: 1; transform: translateY(0); } }
  554.  
  555. /* Control groups */
  556. .control-group {
  557.     display: flex; align-items: center; gap: 16px; padding: 16px 20px; margin-bottom: 12px;
  558.     background: rgba(255,255,255,0.05); border: 1px solid rgba(255,255,255,0.1);
  559.     border-radius: 12px; transition: all 0.2s ease;
  560. }
  561. .control-group:hover { background: rgba(255,255,255,0.08); border-color: rgba(255,255,255,0.15); }
  562. .checkbox-wrapper { display: flex; align-items: center; gap: 8px; min-width: 50px; }
  563. .checkbox-wrapper label { color: #fff; font-weight: 600; font-size: 1.1em; }
  564. .random-wrapper { display: flex; align-items: center; gap: 8px; }
  565. .random-wrapper label { color: rgba(255,255,255,0.7); font-size: 0.9em; }
  566. .invert-wrapper { display: flex; align-items: center; gap: 8px; }
  567. .invert-wrapper label { color: rgba(255,255,255,0.7); font-size: 0.9em; }
  568.  
  569. /* Custom checkboxes */
  570. .control-group input[type="checkbox"], #tabContentContainer input[type="checkbox"] {
  571.     width: 20px; height: 20px; accent-color: #e94560; cursor: pointer;
  572. }
  573.  
  574. /* Dropdowns */
  575. .control-group select, #tabContentContainer select {
  576.     background: rgba(255,255,255,0.1); border: 1px solid rgba(255,255,255,0.2);
  577.     color: #fff; padding: 6px 10px; border-radius: 6px; cursor: pointer;
  578. }
  579. .control-group select option, #tabContentContainer select option {
  580.     background: #1a1a2e; color: #fff;
  581. }
  582. .control-group select:focus, #tabContentContainer select:focus { outline: none; border-color: #e94560; }
  583.  
  584. /* Dual slider container */
  585. .dual-slider-container {
  586.     flex: 1; min-width: 200px; margin: 0; padding: 5px 0;
  587. }
  588. .dual-slider-container.disabled { pointer-events: none; opacity: 0.4; }
  589. .dual-slider-container > label { display: block; margin-bottom: 8px; color: rgba(255,255,255,0.7); font-size: 0.9em; }
  590. .dual-slider-container .slider-area {
  591.     position: relative; height: 24px; width: 100%;
  592. }
  593. .dual-slider-container .slider-track {
  594.     position: absolute; left: 0; right: 0; top: 50%; transform: translateY(-50%);
  595.     height: 6px; border-radius: 3px; background: rgba(255,255,255,0.15); z-index: 0;
  596. }
  597. .dual-slider-container .slider-fill {
  598.     position: absolute; top: 50%; transform: translateY(-50%);
  599.     height: 6px; border-radius: 3px; background: linear-gradient(90deg, #e94560, #533483);
  600.     z-index: 1; left: 0; width: 100%;
  601. }
  602. .dual-slider-container input[type="range"] {
  603.     -webkit-appearance: none; appearance: none; width: 100%; outline: none;
  604.     background: transparent; pointer-events: none; z-index: 3; margin: 0; height: 24px;
  605. }
  606. .dual-slider-container input[type="range"]::-webkit-slider-runnable-track {
  607.     height: 6px; background: transparent;
  608. }
  609. .dual-slider-container input[type="range"]::-webkit-slider-thumb {
  610.     -webkit-appearance: none; appearance: none; height: 18px; width: 18px;
  611.     background: #fff; cursor: pointer; pointer-events: auto; border-radius: 50%;
  612.     box-shadow: 0 2px 6px rgba(0,0,0,0.3), 0 0 0 2px rgba(233, 69, 96, 0.3);
  613.     transition: transform 0.15s ease, box-shadow 0.15s ease;
  614.     margin-top: -6px;
  615. }
  616. .dual-slider-container input[type="range"]::-webkit-slider-thumb:hover {
  617.     transform: scale(1.15);
  618.     box-shadow: 0 2px 8px rgba(0,0,0,0.4), 0 0 0 3px rgba(233, 69, 96, 0.4);
  619. }
  620. .dual-slider-container input[type="range"]:hover { z-index: 10; }
  621. .dual-slider-container input[type="range"]:active { z-index: 11; }
  622. .dual-slider-values {
  623.     display: flex; justify-content: space-between; margin-top: 8px;
  624.     font-size: 0.85em; color: rgba(255,255,255,0.7); font-weight: 500;
  625. }
  626. .dual-slider-values span {
  627.     min-width: 40px; text-align: center;
  628. }
  629.  
  630. /* Single slider */
  631. .single-slider-container {
  632.     display: flex; align-items: center; gap: 16px; width: 100%;
  633.     padding: 16px 20px; background: rgba(255,255,255,0.05);
  634.     border: 1px solid rgba(255,255,255,0.1); border-radius: 12px; margin-bottom: 12px;
  635. }
  636. .single-slider-container label { color: #fff; font-weight: 500; min-width: 60px; }
  637. .single-slider-container .slider-wrapper {
  638.     position: relative; flex-grow: 1; display: flex; align-items: center; height: 24px;
  639. }
  640. .single-slider-container .slider-track, .single-slider-container .slider-fill {
  641.     position: absolute; height: 6px; border-radius: 3px; left: 0; top: 50%; transform: translateY(-50%); width: 100%;
  642. }
  643. .single-slider-container .slider-track { background: rgba(255,255,255,0.15); }
  644. .single-slider-container .slider-fill { background: linear-gradient(90deg, #e94560, #533483); }
  645. .single-slider-container input[type="range"] {
  646.     -webkit-appearance: none; appearance: none; background: transparent; cursor: pointer;
  647.     width: 100%; position: absolute; left: 0; top: 50%; transform: translateY(-50%); z-index: 2;
  648. }
  649. .single-slider-container input[type="range"]::-webkit-slider-thumb {
  650.     -webkit-appearance: none; height: 20px; width: 20px; background: #fff;
  651.     border-radius: 50%; box-shadow: 0 2px 6px rgba(0,0,0,0.3); cursor: pointer;
  652. }
  653. .single-slider-container input[type="range"]::-webkit-slider-runnable-track { background: transparent; }
  654. .single-slider-value {
  655.     flex-shrink: 0; min-width: 60px; text-align: right; color: rgba(255,255,255,0.8);
  656.     font-family: 'SF Mono', Monaco, monospace; font-size: 0.9em;
  657. }
  658.  
  659. /* Buttons */
  660. #tabContentContainer button {
  661.     padding: 12px 24px; border: none; border-radius: 8px; font-size: 0.95em;
  662.     font-weight: 600; cursor: pointer; transition: all 0.2s ease; margin: 8px 8px 8px 0;
  663. }
  664. #btnConnectUSB {
  665.     background: linear-gradient(135deg, #e94560 0%, #533483 100%) !important;
  666.     color: #fff !important; box-shadow: 0 4px 15px rgba(233, 69, 96, 0.3);
  667. }
  668. #btnConnectUSB:hover:not(:disabled) { transform: translateY(-2px); box-shadow: 0 6px 20px rgba(233, 69, 96, 0.4); }
  669. #btnConnectUSB:disabled { opacity: 0.6; cursor: not-allowed; }
  670. #initialKey, #minKey, #settingsKey {
  671.     background: rgba(255,255,255,0.1) !important; color: #fff !important;
  672.     border: 1px solid rgba(255,255,255,0.2) !important;
  673. }
  674. #initialKey:hover, #minKey:hover, #settingsKey:hover {
  675.     background: rgba(255,255,255,0.15) !important; border-color: #e94560 !important;
  676. }
  677.  
  678. /* Labels in tab content */
  679. #tabContentContainer > label { color: rgba(255,255,255,0.8); display: flex; align-items: center; gap: 8px; margin: 12px 0; }
  680. `;
  681.     document.head.appendChild(styleSheet);
  682.  
  683.     // Create overlay backdrop
  684.     var overlay = document.createElement("div");
  685.     overlay.setAttribute("id", "settings-overlay");
  686.  
  687.     // Main settings panel
  688.     var div = document.createElement("div");
  689.     div.setAttribute("id", "settings");
  690.  
  691.     // Header
  692.     var header = document.createElement("div");
  693.     header.className = "settings-header";
  694.     var title = document.createElement("span");
  695.     title.className = "settings-title";
  696.     title.innerHTML = "⚙️ TCode Settings";
  697.     var closeBtn = document.createElement("button");
  698.     closeBtn.id = "settings-close-btn";
  699.     closeBtn.innerHTML = "✕";
  700.     header.appendChild(title);
  701.     header.appendChild(closeBtn);
  702.     div.appendChild(header);
  703.  
  704.     // Tab container
  705.     var tabContainer = document.createElement("div");
  706.     tabContainer.id = "tabContainer";
  707.     div.appendChild(tabContainer);
  708.  
  709.     // Tab content container
  710.     var tabContentContainer = document.createElement("div");
  711.     tabContentContainer.id = "tabContentContainer";
  712.     div.appendChild(tabContentContainer);
  713.  
  714.     // Create tabs
  715.     const tabs = ['device', 'keys', 'axes', 'advanced'];
  716.     const tabContents = {};
  717.     const tabIcons = { device: '🔌', keys: '⌨️', axes: '🎚️', advanced: '🔧' };
  718.     tabs.forEach(t => {
  719.         const btn = document.createElement('button');
  720.         btn.id = t + 'Tab';
  721.         btn.className = 'tab-button';
  722.         btn.innerHTML = tabIcons[t] + ' ' + t.charAt(0).toUpperCase() + t.slice(1);
  723.         btn.addEventListener('click', () => showTab(t));
  724.         tabContainer.appendChild(btn);
  725.         const content = document.createElement('div');
  726.         content.id = t + 'Content';
  727.         content.className = 'tab-content';
  728.         content.style.display = 'none';
  729.         tabContentContainer.appendChild(content);
  730.         tabContents[t] = content;
  731.     });
  732.  
  733.     // Device tab content
  734.     const deviceContentDiv = tabContents['device'];
  735.     const usbBtn = document.createElement('button');
  736.     usbBtn.id = "btnConnectUSB";
  737.     usbBtn.innerText = serialConnected ? "✓ USB Connected" : "🔗 Connect Serial (USB)";
  738.     usbBtn.onclick = function() { connectSerial(); };
  739.     if (serialConnected) usbBtn.disabled = true;
  740.     deviceContentDiv.appendChild(usbBtn);
  741.     deviceContentDiv.appendChild(document.createElement("br"));
  742.     deviceContentDiv.appendChild(document.createElement("br"));
  743.     settingsAddSingleSlider(deviceContentDiv, "sync", "Sync:", settings.sync, -250, 250);
  744.  
  745.     // Keys tab content
  746.     const keysContentDiv = tabContents['keys'];
  747.     settingsAddTabContent(keysContentDiv, "button", "initialKey", "Set Initial Ranges: ", settings.initialKey);
  748.     keysContentDiv.appendChild(document.createElement("br"));
  749.     settingsAddTabContent(keysContentDiv, "button", "minKey", "Set Minimum: ", settings.minKey);
  750.  
  751.     // Axes tab content
  752.     const axesContentDiv = tabContents['axes'];
  753.     ["L0","L1","L2","R0","R1","R2"].forEach(ax => {
  754.         settingsAddGroupedControls(axesContentDiv, "enable"+ax, ax, "min"+ax, "max"+ax, "Range:", getLimit(ax,LOWER), getLimit(ax,UPPER), 0, 9999, listAxes(ax));
  755.     });
  756.  
  757.     // Advanced tab content
  758.     const advancedContentDiv = tabContents['advanced'];
  759.     settingsAddTabContent(advancedContentDiv, "button", "settingsKey", "Settings Hotkey: ", settings.settingsKey);
  760.     advancedContentDiv.appendChild(document.createElement("br"));
  761.     settingsAddTabContent(advancedContentDiv, "checkbox", "showNotifications", "Show Script Load Notifications");
  762.     advancedContentDiv.appendChild(document.createElement("br"));
  763.     settingsAddTabContent(advancedContentDiv, "checkbox", "debug", "Enable Debug Mode");
  764.  
  765.     // Append panel to overlay, then overlay to body
  766.     overlay.appendChild(div);
  767.     document.body.appendChild(overlay);
  768.  
  769.     showTab(activeTab);
  770.     settingsMenuApplySaved();
  771.  
  772.     // Close button handler
  773.     closeBtn.addEventListener("click", function(){
  774.         saveSettings();
  775.         var overlayEl = document.getElementById("settings-overlay");
  776.         if (overlayEl) overlayEl.remove();
  777.         var styleEl = document.getElementById("stash-tcode-styles");
  778.         if (styleEl) styleEl.remove();
  779.     }, false);
  780.  
  781.     // Click on backdrop to close
  782.     overlay.addEventListener("click", function(e){
  783.         if (e.target === overlay) closeBtn.click();
  784.     }, false);
  785.  
  786.     document.getElementById("settings").addEventListener("change", function(){ saveSettings(false); }, false);
  787.     menuListeners(["initialKey", "settingsKey", "minKey"]);
  788.     ["L0","L1","L2","R0","R1","R2"].forEach(ax => dualSliderListeners("min"+ax, "max"+ax));
  789. }
  790.  
  791. // --- WEB SERIAL IMPLEMENTATION ---
  792.  
  793. async function connectSerial() {
  794.     if (!navigator.serial) {
  795.         alert("Web Serial API is NOT available.\n\nSince you are using a custom domain (umbra.lan), you must enable 'Insecure origins treated as secure' in chrome://flags or use HTTPS.");
  796.         return;
  797.     }
  798.  
  799.     try {
  800.         port = await navigator.serial.requestPort();
  801.         await port.open({ baudRate: 115200 }); // Standard TCode Baud Rate
  802.         const textEncoder = new TextEncoderStream();
  803.         writableStreamClosed = textEncoder.readable.pipeTo(port.writable);
  804.         writer = textEncoder.writable.getWriter();
  805.         serialConnected = true;
  806.         keepReading = true;
  807.         var usbBtn = document.getElementById("btnConnectUSB");
  808.         if (usbBtn) {
  809.             usbBtn.innerText = "USB Connected";
  810.             usbBtn.disabled = true;
  811.         }
  812.         debug("USB Serial Connected");
  813.         createOverlay("USB Connected");
  814.         showToast("USB Connected", "Serial connection established at 115200 baud", "success");
  815.         readSerialLoop();
  816.     } catch (e) {
  817.         console.error("Serial Connection Failed:", e);
  818.         showToast("Connection Failed", e.message, "error");
  819.         alert("Could not connect to Serial device. \n" + e.message);
  820.     }
  821. }
  822.  
  823. async function readSerialLoop() {
  824.     while (port.readable && keepReading) {
  825.         const textDecoder = new TextDecoderStream();
  826.         readableStreamClosed = port.readable.pipeTo(textDecoder.writable);
  827.         reader = textDecoder.readable.getReader();
  828.         try {
  829.             while (true) {
  830.                 const { value, done } = await reader.read();
  831.                 if (done) { break; }
  832.                 if (value) { processWSReply({ data: value }); }
  833.             }
  834.         } catch (error) { console.error(error); } finally { reader.releaseLock(); }
  835.     }
  836. }
  837.  
  838. function sendTCode(data) {
  839.     if (serialConnected && writer) { writer.write(data); }
  840. }
  841.  
  842. // ---------------------------------
  843.  
  844. /* Stash Integration */
  845. function fetchSceneInfo(id){
  846.     GM_xmlhttpRequest({
  847.         method: "POST",
  848.         url: location.protocol + '//' + location.host + '/graphql',
  849.         data: '{"operationName":"FindScene","variables":{"id":"' + id + '"},"query":"query FindScene($id: ID!, $checksum: String) {\\n  findScene(id: $id, checksum: $checksum) {\\n    ...SceneData\\n  }\\n}\\n\\nfragment SceneData on Scene {\\n  files {\\n    ...VideoFileData\\n  }\\n  paths {\\n    funscript\\n}\\n}\\n\\nfragment VideoFileData on VideoFile {\\n  path\\n}"}',
  850.         cookie: document.cookie,
  851.         anonymous: true,
  852.         headers: { "Content-Type": "application/json" },
  853.         onload: function(response){
  854.             var json = JSON.parse(response.response);
  855.             if(json.data && json.data.findScene && json.data.findScene.files.length > 0){
  856.                 video = json.data.findScene.files[0].path;
  857.                 debug("Video: " + video);
  858.                 fetchAllFunscripts();
  859.             }
  860.         }
  861.     });
  862. }
  863.  
  864. function initAxis(name){
  865.     if(AXIS[name]){ return -1; }
  866.     AXIS[name] = new Object();
  867.     AXIS[name].index = 0; AXIS[name].start = 0; AXIS[name].end = 0; AXIS[name].scriptLoaded = false;
  868.     AXIS[name].acts = null; AXIS[name].limits = null; AXIS[name].altLimits = null;
  869. }
  870.  
  871. function fetchAllFunscripts(){
  872.     // First, try to fetch the main funscript which may contain multiple axes
  873.     fetchMainFunscript();
  874. }
  875.  
  876. // Parse a multi-axis funscript file (version 1.1+ with "axes" array)
  877. function parseMultiAxisFunscript(json) {
  878.     var foundAxes = [];
  879.    
  880.     // Check if this is a multi-axis funscript (has "axes" array)
  881.     if (json.axes && Array.isArray(json.axes) && json.axes.length > 0) {
  882.         debug("Multi-axis funscript detected with " + json.axes.length + " axes");
  883.        
  884.         // Process each axis in the axes array
  885.         for (var i = 0; i < json.axes.length; i++) {
  886.             var axisData = json.axes[i];
  887.             var axisId = axisData.id; // e.g., "R1", "R2", "L0", etc.
  888.            
  889.             if (axisId && axisData.actions && Array.isArray(axisData.actions) && axisData.actions.length > 0) {
  890.                 if (!AXIS[axisId]) { initAxis(axisId); }
  891.                 AXIS[axisId].acts = axisData.actions;
  892.                 AXIS[axisId].start = AXIS[axisId].acts[0].at;
  893.                 AXIS[axisId].end = AXIS[axisId].acts[AXIS[axisId].acts.length - 1].at;
  894.                 AXIS[axisId].scriptLoaded = true;
  895.                 foundAxes.push(axisId);
  896.                 debug("Loaded axis " + axisId + " from multi-axis file with " + axisData.actions.length + " actions");
  897.             }
  898.         }
  899.        
  900.         // Also check for root-level actions (usually L0/stroke)
  901.         if (json.actions && Array.isArray(json.actions) && json.actions.length > 0) {
  902.             if (!AXIS["L0"]) { initAxis("L0"); }
  903.             AXIS["L0"].acts = json.actions;
  904.             AXIS["L0"].start = AXIS["L0"].acts[0].at;
  905.             AXIS["L0"].end = AXIS["L0"].acts[AXIS["L0"].acts.length - 1].at;
  906.             AXIS["L0"].scriptLoaded = true;
  907.             foundAxes.push("L0");
  908.             debug("Loaded L0 from root actions with " + json.actions.length + " actions");
  909.         }
  910.        
  911.         return foundAxes;
  912.     }
  913.    
  914.     // Not a multi-axis file
  915.     return null;
  916. }
  917.  
  918. // Fetch the main funscript file first, then check if it's multi-axis
  919. function fetchMainFunscript() {
  920.     var chosenScript = document.querySelector('#stash-interactive-tools-select-funscripts');
  921.     var url = "";
  922.    
  923.     if (chosenScript) {
  924.         url = chosenScript.value;
  925.     } else {
  926.         url = location.protocol + '//' + location.host + '/scene/' + getSceneId() + '/funscript';
  927.     }
  928.    
  929.     GM_xmlhttpRequest({
  930.         method: "GET",
  931.         url: url,
  932.         cookie: document.cookie,
  933.         anonymous: true,
  934.         onload: function(response) {
  935.             if (response.status == 200) {
  936.                 try {
  937.                     var json = JSON.parse(response.response);
  938.                    
  939.                     // Try to parse as multi-axis first
  940.                     var multiAxisResult = parseMultiAxisFunscript(json);
  941.                    
  942.                     if (multiAxisResult && multiAxisResult.length > 0) {
  943.                         // Multi-axis file was successfully parsed
  944.                         debug("Successfully loaded multi-axis funscript with axes: " + multiAxisResult.join(", "));
  945.                         showToast("Multi-Axis Script Loaded", "Parsed " + multiAxisResult.length + " axes: " + multiAxisResult.join(", "), "success");
  946.                        
  947.                         // For any axes not found in the multi-axis file, try fetching separate files or use random
  948.                         for (var axis in AXIS) {
  949.                             if (!AXIS[axis].scriptLoaded) {
  950.                                 if (settings.axes[axis].random != "") {
  951.                                     generateRandomMotion(axis, settings.axes[axis].random);
  952.                                     AXIS[axis].scriptLoaded = true;
  953.                                 } else {
  954.                                     // Try fetching individual axis file
  955.                                     fetchFunscript(axis, true);
  956.                                 }
  957.                             }
  958.                         }
  959.                     } else {
  960.                         // Single-axis file (legacy format) - load as L0
  961.                         if (json.actions && Array.isArray(json.actions) && json.actions.length > 0) {
  962.                             if (!AXIS["L0"]) { initAxis("L0"); }
  963.                             AXIS["L0"].acts = json.actions;
  964.                             AXIS["L0"].start = AXIS["L0"].acts[0].at;
  965.                             AXIS["L0"].end = AXIS["L0"].acts[AXIS["L0"].acts.length - 1].at;
  966.                             AXIS["L0"].scriptLoaded = true;
  967.                             debug("Loaded single-axis funscript as L0 with " + json.actions.length + " actions");
  968.                             showToast("Script Loaded", "L0 axis with " + json.actions.length + " actions", "success");
  969.                         }
  970.                        
  971.                         // Fetch other axes from separate files
  972.                         for (var axis in AXIS) {
  973.                             if (!AXIS[axis].scriptLoaded) {
  974.                                 if (settings.axes[axis].random != "") {
  975.                                     if (!AXIS[settings.axes[axis].random].scriptLoaded) {
  976.                                         fetchFunscript(axis);
  977.                                     } else {
  978.                                         generateRandomMotion(axis, settings.axes[axis].random);
  979.                                         AXIS[axis].scriptLoaded = true;
  980.                                     }
  981.                                 } else if (axis !== "L0") {
  982.                                     fetchFunscript(axis);
  983.                                 }
  984.                             }
  985.                         }
  986.                     }
  987.                 } catch (error) {
  988.                     debug("JSON parse error in main funscript: " + error);
  989.                     showToast("Parse Error", "Failed to parse funscript, trying individual files", "warning");
  990.                     // Fallback to fetching individual files
  991.                     fetchIndividualAxisFiles();
  992.                 }
  993.             } else {
  994.                 debug("Main funscript not found, trying individual files");
  995.                 showToast("No Main Script", "Searching for individual axis files...", "info");
  996.                 fetchIndividualAxisFiles();
  997.             }
  998.            
  999.             // Clean up dropdown options
  1000.             if (chosenScript) { cleanUpOptions(chosenScript); }
  1001.         }
  1002.     });
  1003. }
  1004.  
  1005. // Fallback: fetch individual axis files
  1006. function fetchIndividualAxisFiles() {
  1007.     for (var axis in AXIS) {
  1008.         if (settings.axes[axis].random != "") {
  1009.             if (!AXIS[settings.axes[axis].random].scriptLoaded) {
  1010.                 fetchFunscript(axis);
  1011.             }
  1012.         }
  1013.         if (!AXIS[axis].scriptLoaded) {
  1014.             fetchFunscript(axis);
  1015.         }
  1016.     }
  1017.     var chosenScript = document.querySelector('#stash-interactive-tools-select-funscripts');
  1018.     if (chosenScript) { cleanUpOptions(chosenScript); }
  1019. }
  1020.  
  1021. function generateRandomMotion(axis, relatedAxis=""){
  1022.     if(AXIS[axis].acts != null){ return -1; }
  1023.     var interval = -1;
  1024.     var modifier = Math.random() * (1500 - 250) + 250;
  1025.     if(Math.random() < 0.5){ modifier * -1; }
  1026.     if(AXIS[relatedAxis]){
  1027.         if(AXIS[relatedAxis].acts == null && generateRandomMotion.caller != ""){
  1028.             setTimeout(function(){ generateRandomMotion(axis, relatedAxis) }, 500);
  1029.             return -1;
  1030.         }
  1031.         AXIS[axis].acts = new Array();
  1032.         for(var i=AXIS[relatedAxis].index;i<AXIS[relatedAxis].acts.length;i++){
  1033.             AXIS[axis].acts[i] = new Object();
  1034.             interval = Math.round(AXIS[relatedAxis].acts[i].at + modifier);
  1035.             if(interval < 0){ interval = 0; }
  1036.             AXIS[axis].acts[i].at = interval;
  1037.             AXIS[axis].acts[i].pos = AXIS[relatedAxis].acts[i].pos;
  1038.         }
  1039.         AXIS[axis].start = AXIS[axis].acts[0].at;
  1040.         AXIS[axis].end = AXIS[axis].acts[AXIS[axis].acts.length-1].at;
  1041.     }
  1042. }
  1043.  
  1044. function fetchFunscript(axis, force=false){
  1045.     if(scriptList == null){
  1046.         GM_xmlhttpRequest({
  1047.             method: "POST",
  1048.             url: location.protocol + '//' + location.host + '/graphql',
  1049.             data: '{"operationName":"RunPluginOperation","variables":{"plugin_id":"StashInteractiveTools","args":{"mode":"init","scene_id":"' + getSceneId() + '","origin":"' + location.origin + '"}},"query":"mutation RunPluginOperation($plugin_id: ID!, $args: Map) {\\n  runPluginOperation(plugin_id: $plugin_id, args: $args)\\n}"}',
  1050.             cookie: document.cookie,
  1051.             anonymous: true,
  1052.             headers: { "Content-Type": "application/json" },
  1053.             onload: function(response){
  1054.                 var json = JSON.parse(response.response);
  1055.                 if(json.data && json.data.runPluginOperation){
  1056.                     scriptList = json.data.runPluginOperation.scripts;
  1057.                     fetchFunscript(axis);
  1058.                 }
  1059.             }
  1060.         });
  1061.     }else{
  1062.         var chosenScript = document.querySelector('#stash-interactive-tools-select-funscripts');
  1063.         if(!chosenScript && !force){ setTimeout(function(){fetchFunscript(axis, true)}, 500); return -1; }
  1064.         var url = "";
  1065.         if(chosenScript){ url = chosenScript.value.split('.funscript')[0]; }
  1066.         else{ url = location.protocol + '//' + location.host + '/scene/' + getSceneId() + '/funscript'; }
  1067.  
  1068.         switch(axis){
  1069.             case "L1": url += ".sway"; break; case "L2": url += ".surge"; break; case "R0": url += ".twist"; break; case "R1": url += ".pitch"; break; case "R2": url += ".roll"; break;
  1070.         }
  1071.         if(chosenScript){ url = url + ".funscript"; }
  1072.         GM_xmlhttpRequest({
  1073.             method: "GET", url: url, cookie: document.cookie, anonymous: true,
  1074.             onload: function(response){
  1075.                 if(response.status == 200){
  1076.                     if(!AXIS[axis]){ AXIS[axis] = new Object(); }
  1077.                     try { AXIS[axis].acts = JSON.parse(response.response).actions; }
  1078.                     catch (error) { debug("JSON error"); }
  1079.                     if(AXIS[axis].acts == null){ fetchFunscript(axis, force); return -1; }
  1080.                     AXIS[axis].start = AXIS[axis].acts[0].at;
  1081.                     AXIS[axis].end = AXIS[axis].acts[AXIS[axis].acts.length-1].at;
  1082.                     showToast("Axis Loaded", axis + " with " + AXIS[axis].acts.length + " actions", "success", 3000);
  1083.                 }else{
  1084.                     if(settings.axes[axis].random != ""){
  1085.                         generateRandomMotion(axis, settings.axes[axis].random);
  1086.                         showToast("Random Generated", axis + " (based on " + settings.axes[axis].random + ")", "info", 3000);
  1087.                     }
  1088.                     else{ AXIS[axis].acts = null; }
  1089.                 }
  1090.                 AXIS[axis].scriptLoaded = true;
  1091.             }
  1092.         });
  1093.     }
  1094. }
  1095.  
  1096. function listAxes(exclude=""){
  1097.     var keys = Object.keys(AXIS);
  1098.     let removeAxis = keys.indexOf(exclude);
  1099.     if (removeAxis !== -1) { keys.splice(removeAxis, 1); }
  1100.     return keys;
  1101. }
  1102.  
  1103. function centerAxis(axis){
  1104.     if(!serialConnected){ return -1; }
  1105.     if(!settings.axes[axis].enabled){ return -1; }
  1106.     if(!AXIS[axis].limits || AXIS[axis].limits == null){ setTimeout(function(){ centerAxis(axis)}, 500); return -1; }
  1107.     var center = Math.floor(parseInt(AXIS[axis].limits[0]) + ((AXIS[axis].limits[1] - AXIS[axis].limits[0])/2));
  1108.     sendTCode(axis + 5 + "I" + center + '\n');
  1109. }
  1110.  
  1111. function formatMoveCommand(axis, pos, int){
  1112.     if(parseInt(pos) > parseInt(AXIS[axis].limits[1]/100)){ pos = Math.floor(AXIS[axis].limits[1]/100); }
  1113.     else if(parseInt(pos) < parseInt(AXIS[axis].limits[0]/100)){ pos = Math.floor(AXIS[axis].limits[0]/100); }
  1114.     if(pos < 10){ pos = "0" + pos; }
  1115.     var cmd = axis + pos + "I" + int;
  1116.     debug(`[TCode] Queued: ${cmd} (axis: ${axis}, enabled: ${settings.axes[axis]?.enabled}, hasLimits: ${AXIS[axis].limits != null})`);
  1117.     return cmd;
  1118. }
  1119.  
  1120. function currentAction(ms){
  1121.     if(msPending){ return -1; }
  1122.     msPending = true;
  1123.     ms += parseInt(settings.sync);
  1124.    
  1125.     var cmdBuffer = "";
  1126.    
  1127.     for(var x in AXIS){
  1128.         if(settings.axes[x].enabled && AXIS[x].acts != null && AXIS[x].limits != null && AXIS[x].acts[AXIS[x].index] != null){
  1129.             if(AXIS[x].index == 0 || AXIS[x].acts[AXIS[x].index-1].at < ms){
  1130.                 for(var i=AXIS[x].index;i<AXIS[x].acts.length;i++){
  1131.                     if(AXIS[x].acts[i].at > ms){
  1132.                         var pos = AXIS[x].acts[i].pos;
  1133.                         if (settings.axes[x].invert) { pos = 100 - pos; }
  1134.                         var act = Math.floor((((pos/100)*(AXIS[x].limits[1] - AXIS[x].limits[0]))+parseInt(AXIS[x].limits[0]))/100);
  1135.                         var cmd = formatMoveCommand(x, act, (AXIS[x].acts[i].at - ms));
  1136.                         if(cmd) cmdBuffer += cmd;
  1137.                         AXIS[x].index = ++i;
  1138.                         break;
  1139.                     }
  1140.                 }
  1141.             }
  1142.         }
  1143.     }
  1144.    
  1145.     if(cmdBuffer.length > 0 && serialConnected){
  1146.         sendTCode(cmdBuffer + '\n');
  1147.     }
  1148.    
  1149.     msPending = false;
  1150. }
  1151.  
  1152. function resetIndex(axis=""){
  1153.     for(var i in AXIS){ if(settings.axes[i].enabled){ AXIS[i].index = 0; } }
  1154. }
  1155.  
  1156. function updateTime(player){
  1157.     if(!player.paused){ currentAction(Math.floor(player.currentTime*1000)); }
  1158. }
  1159.  
  1160. function waitForVideoPlayer(){
  1161.     var player = document.querySelector('video');
  1162.     if(!player){ setTimeout(waitForVideoPlayer, 500); }
  1163.     else{
  1164.         if(!videoPlayerLoaded){
  1165.             player.addEventListener("seeking", resetIndex, false);
  1166.             init();
  1167.             videoPlayerLoaded = true;
  1168.         }
  1169.         updateTime(player);
  1170.         setTimeout(waitForVideoPlayer, 10);
  1171.     }
  1172. }
  1173.  
  1174. function setInitials(axis="L0"){
  1175.     if(AXIS[axis] && AXIS[axis].limits != null){ AXIS[axis].altLimits = AXIS[axis].limits.slice(0); }
  1176. }
  1177.  
  1178. function processLimits(data){
  1179.     var values;
  1180.     var axesFound = [];
  1181.     console.log(`[TCode] Device returned limits:`, data);
  1182.     for(var i=0;i<data.length-1;i++){
  1183.         values = data[i].split(' ');
  1184.         if(AXIS[values[0]]){
  1185.             AXIS[values[0]].limits = new Array(values[1], values[2]);
  1186.             AXIS[values[0]].altLimits = new Array(values[1], values[2]);
  1187.             console.log(`[TCode] Set ${values[0]} limits: ${values[1]} - ${values[2]}`);
  1188.            
  1189.             // Auto-enable axes that the device supports (L and R axes only, not V or A)
  1190.             if(/^[LR]\d+$/.test(values[0]) && settings.axes[values[0]]){
  1191.                 if(!settings.axes[values[0]].enabled){
  1192.                     settings.axes[values[0]].enabled = true;
  1193.                     axesFound.push(values[0]);
  1194.                     console.log(`[TCode] Auto-enabled ${values[0]} (device supports this axis)`);
  1195.                 }
  1196.             }
  1197.         }
  1198.     }
  1199.     if(axesFound.length > 0){
  1200.         showToast("Axes Auto-Enabled", "Enabled " + axesFound.join(", ") + " based on device capabilities", "info");
  1201.         saveSettings(false); // Save without sending to device
  1202.     }
  1203. }
  1204.  
  1205. function processWSReply(event){
  1206.     try {
  1207.         // Accumulate data in buffer
  1208.         serialBuffer += event.data;
  1209.        
  1210.         // Clear existing timeout
  1211.         if(bufferTimeout) clearTimeout(bufferTimeout);
  1212.        
  1213.         // Wait for data to finish arriving (100ms timeout)
  1214.         bufferTimeout = setTimeout(() => {
  1215.             var cleanData = serialBuffer.replaceAll('\n', '|').replaceAll('\r', '');
  1216.             serialBuffer = ""; // Clear buffer
  1217.            
  1218.             // Handle JSON format (wrapped in {command: "..."})
  1219.             if(cleanData.startsWith('{')) {
  1220.                  var json = JSON.parse(cleanData);
  1221.                  debug("[TCode] Parsed JSON: " + JSON.stringify(json));
  1222.                  processLimits(json.command.split("|"));
  1223.             }
  1224.             // Handle plain text format - check if ANY line matches axis limits pattern
  1225.             else if(/[LRVA]\d+\s+\d+\s+\d+/.test(cleanData)) {
  1226.                 debug("[TCode] Plain text limits detected");
  1227.                 // Filter and process only lines that match the pattern (including those after pipes)
  1228.                 var lines = cleanData.split("|");
  1229.                 var validLines = lines.filter(line => {
  1230.                     var trimmed = line.trim();
  1231.                     return /^[LRVA]\d+\s+\d+\s+\d+/.test(trimmed);
  1232.                 });
  1233.                 if(validLines.length > 0){
  1234.                     debug("[TCode] Found " + validLines.length + " valid limit lines");
  1235.                     processLimits(validLines);
  1236.                 }
  1237.             }
  1238.         }, 100); // 100ms debounce
  1239.     } catch(e) {
  1240.         debug("[TCode] Error processing device response: " + e);
  1241.     }
  1242. }
  1243.  
  1244. function setPendingFalse(){ pending = false; }
  1245.  
  1246. function loadCurrentLimits(){
  1247.     if(pending){ return -1; }
  1248.     pending = true;
  1249.     if(serialConnected){
  1250.         console.log("[TCode] Requesting device limits with D2 command...");
  1251.         sendTCode("D2" + '\n');
  1252.     }
  1253.     setPendingFalse();
  1254. }
  1255.  
  1256. function onClick(event) {
  1257.     if(!mouseEnabled){ return -1; }
  1258.     if(event.which == 2){
  1259.         var axis = "L0";
  1260.         if(AXIS[axis] && AXIS[axis].altLimits != null){ setLimits(AXIS[axis].altLimits[0], AXIS[axis].altLimits[1], axis); }
  1261.     }
  1262. }
  1263.  
  1264. function onScroll(event) {
  1265.     if(!mouseEnabled){ return -1; }
  1266.     if(!scrollWheelEnabled){ return -1; } // Only allow scroll when minKey or initialKey is held
  1267.     var axis = "L0";
  1268.     if(AXIS[axis].limits == null){ loadCurrentLimits(); return -1; }
  1269.     if (event.deltaY >= 0) {
  1270.         if(adjustMin){ AXIS[axis].limits[0] = +AXIS[axis].limits[0] - 250; } else{ AXIS[axis].limits[1] = +AXIS[axis].limits[1] - 250; }
  1271.     }else if (event.deltaY < 0){
  1272.         if(adjustMin){ AXIS[axis].limits[0] = +AXIS[axis].limits[0] + 250; } else{ AXIS[axis].limits[1] = +AXIS[axis].limits[1] + 250; }
  1273.     }
  1274.     if ( AXIS[axis].limits[0] > AXIS[axis].limits[1] ){
  1275.         if(adjustMin){ AXIS[axis].limits[1] = AXIS[axis].limits[0]; } else{ AXIS[axis].limits[0] = AXIS[axis].limits[1]; }
  1276.     }
  1277.     if( AXIS[axis].limits[1] < 0){ AXIS[axis].limits[1] = 0; } else if( AXIS[axis].limits[1] > 9999){ AXIS[axis].limits[1] = 9999; }
  1278.     if( AXIS[axis].limits[0] < 0){ AXIS[axis].limits[0] = 0; } else if( AXIS[axis].limits[0] > 9999){ AXIS[axis].limits[0] = 9999; }
  1279.     setLimits(AXIS[axis].limits[0], AXIS[axis].limits[1], axis);
  1280. }
  1281.  
  1282. function keyDown(event){
  1283.     if(pendingKey == null){
  1284.         switch(event.key){
  1285.             case settings.minKey:
  1286.                 adjustMin = true;
  1287.                 scrollWheelEnabled = true;
  1288.                 break;
  1289.             case settings.initialKey:
  1290.                 setInitials();
  1291.                 scrollWheelEnabled = true;
  1292.                 break;
  1293.             case settings.settingsKey:
  1294.                 toggleMenu();
  1295.                 break;
  1296.         }
  1297.     }else{ setKey(event.key); }
  1298. }
  1299.  
  1300. function keyUp(event){
  1301.     if(event.key === settings.minKey || event.key === settings.initialKey){
  1302.         adjustMin = false;
  1303.         scrollWheelEnabled = false;
  1304.     }
  1305. }
  1306.  
  1307. function hideOverlay(){ try{ document.querySelector('#overlay').hidden = "true"; }catch{ return ""; } }
  1308.  
  1309. function createOverlay(text){
  1310.     var video = document.querySelector("#VideoJsPlayer_html5_api");
  1311.     if(video){
  1312.         video = video.parentNode;
  1313.         var overlayElement = document.createElement('div');
  1314.         overlayElement.setAttribute('id', 'overlay');
  1315.         overlayElement.style = "position: absolute;z-index: 999999999999999;left: 50%;transform: translateX(-50%); font-size: 2.5em; color: white; -webkit-text-stroke-width: .75px; -webkit-text-stroke-color: black;";
  1316.         overlayElement.innerHTML = "<h2></h2>";
  1317.         video.appendChild(overlayElement);
  1318.         show(text);
  1319.     }else{ setTimeout(show, 500, text); }
  1320. }
  1321.  
  1322. function show(text){
  1323.     var overlay = document.querySelector('#overlay');
  1324.     if(!overlay){ createOverlay(text); }
  1325.     else{ overlay.childNodes[0].innerText = text; overlay.removeAttribute("hidden"); setTimeout(hideOverlay, 1000); }
  1326. }
  1327.  
  1328. function limits2socket(axis=""){
  1329.     function sendAxis2socket(axis){
  1330.         if(AXIS[axis] && AXIS[axis].limits){
  1331.             sendTCode("$" + axis + "-" + AXIS[axis].limits[0].toString().padStart(4, '0') + "-" + AXIS[axis].limits[1].toString().padStart(4, '0') + '\n');
  1332.         }
  1333.     }
  1334.     if(axis == ""){ for(var thisAxis in AXIS){ sendAxis2socket(thisAxis); } } else{ sendAxis2socket(axis); }
  1335. }
  1336.  
  1337. function setLimits(min, max, axis="L0", save=true){
  1338.     show(axis + ": " + min + " - " + max);
  1339.     if(!AXIS[axis]){ return -1; }
  1340.     if(AXIS[axis].limits == null){ AXIS[axis].limits = new Array(); }
  1341.     AXIS[axis].limits[0] = min; AXIS[axis].limits[1] = max;
  1342.     if(pending){ return -1; }
  1343.     if(serialConnected && save){
  1344.         pending = true; limits2socket(axis); setPendingFalse();
  1345.     }
  1346. }
  1347.  
  1348. function init(){
  1349.     document.addEventListener('wheel', onScroll, false);
  1350.     document.addEventListener('auxclick', onClick, false);
  1351.     document.addEventListener('keydown', keyDown, true);
  1352.     document.addEventListener('keyup', keyUp, true);
  1353.     ["L0","L1","L2","R0","R1","R2"].forEach(ax => initAxis(ax));
  1354.     loadCurrentLimits();
  1355. }
  1356.  
  1357. function getSceneId(){ return parseInt(location.href.split('/scenes/')[1]); }
  1358.  
  1359. function main(){
  1360.     if(serialConnected){
  1361.         loadCurrentLimits();
  1362.        
  1363.         // Wait a moment for device limits, then set fallbacks for any missing
  1364.         setTimeout(() => {
  1365.             ["L0","L1","L2"].forEach(ax => {
  1366.                 if(AXIS[ax] && (!AXIS[ax].limits || AXIS[ax].limits == null)){
  1367.                     console.log(`[TCode] No limits received for ${ax}, using fallback: 0 - 9999`);
  1368.                     AXIS[ax].limits = [0, 9999];
  1369.                     AXIS[ax].altLimits = [0, 9999];
  1370.                 }
  1371.             });
  1372.         }, 1000);
  1373.        
  1374.         ["L0","L1","L2","R0","R1","R2"].forEach(ax => centerAxis(ax));
  1375.         fetchSceneInfo(getSceneId());
  1376.         waitForVideoPlayer();
  1377.     }else{ setTimeout(main, 500); }
  1378. }
  1379.  
  1380. function cleanUpOptions(list){
  1381.     var options = list.childNodes;
  1382.     for(var i=0;i<options.length;i++){
  1383.         if(!options[i]){ return -1; }
  1384.         var type = options[i].value.replace(/\.funscript/, '').split('.');
  1385.         switch(type[type.length-1]){
  1386.             case "sway": case "surge": case "twist": case "pitch": case "roll":
  1387.                 options[i].parentNode.removeChild(options[i]); break;
  1388.         }
  1389.     }
  1390. }
  1391.  
  1392. function waitForPageChange(){
  1393.     var chosenScript = document.querySelector('#stash-interactive-tools-select-funscripts');
  1394.     if(chosenScript){ chosenScript.addEventListener('change', fetchAllFunscripts); cleanUpOptions(chosenScript); }
  1395.     if(location.href == lastPage){ setTimeout(waitForPageChange, 500); return -1; }
  1396.     lastPage = location.href;
  1397.     scriptList = null;
  1398.    
  1399.     // Reset ALL axis data when changing videos
  1400.     for(var axis in AXIS){
  1401.         AXIS[axis].index = 0;
  1402.         AXIS[axis].start = 0;
  1403.         AXIS[axis].end = 0;
  1404.         AXIS[axis].scriptLoaded = false;
  1405.         AXIS[axis].acts = null;
  1406.         // Keep limits and altLimits - these come from the device
  1407.     }
  1408.    
  1409.     if(location.href.indexOf('/scenes/') != -1){
  1410.         init(); mouseEnabled = true; main();
  1411.     }else{ mouseEnabled = false; videoPlayerLoaded = false; }
  1412.     setTimeout(waitForPageChange, 500);
  1413. }
  1414.  
  1415. waitForPageChange();
Advertisement
Add Comment
Please, Sign In to add comment