Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // ==UserScript==
- // @name Stash-TCode-USB
- // @namespace Steel
- // @version 0.5.6-USB-Beta
- // @description Integrate TCode Devices with Stash via USB Web Serial
- // @author Steel (Spunkle-Modded)
- // @include http*://*:9999*
- // @grant GM_xmlhttpRequest
- // @grant GM_setValue
- // @grant GM_getValue
- // @grant GM_info
- // @grant unsafeWindow
- // @license GPLv3
- // ==/UserScript==
- var video="";
- var lastPage = null;
- var pendingKey = null;
- var settings = loadSettings();
- // --- SERIAL VARIABLES ---
- var port = null;
- var writer = null;
- var keepReading = false;
- var serialConnected = false;
- var reader = null;
- var readableStreamClosed = null;
- var writableStreamClosed = null;
- var textEncoder = new TextEncoder();
- var serialBuffer = ""; // Buffer for accumulating fragmented serial responses
- var bufferTimeout = null;
- // ------------------------
- var scriptList = null;
- var AXIS = new Object();
- var adjustMin = false; // 0 = Max 1= Min
- var scrollWheelEnabled = false; // Only enabled when minKey or initialKey is held
- var pending = false;
- var msPending = false;
- var mouseEnabled = true;
- var videoPlayerLoaded = false;
- const BOTH = 0;
- const LOWER = 1;
- const UPPER = 2;
- const isChrome = !!unsafeWindow.chrome;
- function isNewerVersion (oldVer, newVer) {
- const oldParts = oldVer.split('.')
- const newParts = newVer.split('.')
- for (var i = 0; i < newParts.length; i++) {
- const a = ~~newParts[i]; const b = ~~oldParts[i];
- if (a > b) return true; if (a < b) return false;
- }
- return false;
- }
- function handleUpgrade(thisVersion){
- if(settings.currentVersion === undefined || isNewerVersion(settings.currentVersion, thisVersion)){
- return true;
- }
- return false;
- }
- function getLimit(axis, which=BOTH){
- var limits = [0, 9999];
- if(AXIS && AXIS[axis] && AXIS[axis].limits){ limits = AXIS[axis].limits; }
- switch(which){
- case BOTH: return limits;
- case LOWER: return limits[0];
- case UPPER: return limits[1];
- }
- }
- function debug(text, value=""){
- if(settings.debug){
- if(value == ""){ console.log(text); } else { unsafeWindow[value] = text; }
- }
- }
- function settingsMenuApplySaved(){
- for(const setting in settings){
- if(setting == "axes"){
- for (const axis in settings.axes){
- var axisCheck = document.querySelector('#enable' + axis);
- if(axisCheck && settings.axes[axis].enabled){
- axisCheck.checked = true;
- var parentContainer = axisCheck.parentNode.parentNode.querySelector('.dual-slider-container');
- if(parentContainer){ parentContainer.classList.remove('disabled'); }
- }
- var randomCheck = document.querySelector('#random' + axis);
- if(randomCheck){
- if(settings.axes[axis].random == ""){ continue; }
- randomCheck.checked = true;
- var trackedAxis = document.querySelector('#track' + axis);
- if(trackedAxis){ trackedAxis.value = settings.axes[axis].random; }
- }
- var invertCheck = document.querySelector('#invert' + axis);
- if(invertCheck && settings.axes[axis].invert){ invertCheck.checked = true; }
- }
- continue;
- }
- var input = document.querySelector('#' + setting);
- if(input){
- if(input.type == "checkbox"){
- if(JSON.parse(settings[setting])){ input.checked = true; }
- }else if(input.type == "text" || input.type == "range"){
- input.value = settings[setting];
- }
- }
- }
- }
- function saveSettings(saveToDevice=true){
- for(const setting in settings){
- if(setting == "axes"){
- for (const axis in settings.axes){
- var axisCheck = document.querySelector('#enable' + axis);
- if(axisCheck){ settings.axes[axis].enabled = axisCheck.checked; }
- var randomCheck = document.querySelector('#random' + axis);
- if(randomCheck){
- if(!randomCheck.checked){ settings.axes[axis].random = ""; continue; }
- var trackedAxis = document.querySelector('#track' + axis);
- if(trackedAxis){ settings.axes[axis].random = trackedAxis.value; }
- }
- var invertCheck = document.querySelector('#invert' + axis);
- if(invertCheck){ settings.axes[axis].invert = invertCheck.checked; }
- }
- continue;
- }
- var input = document.querySelector('#' + setting);
- if(input){
- if(input.type == "checkbox"){
- if(input.checked){ settings[setting] = true; }else{ settings[setting] = false; }
- }else if(input.type == "text" || input.type == "range"){
- settings[setting] = input.value;
- }
- }
- }
- if(saveToDevice){
- for(const axis of listAxes()){
- var min = document.querySelector('#min' + axis);
- var max = document.querySelector('#max' + axis);
- if(min && max){ setLimits(min.value, max.value, axis); }
- }
- }
- GM_setValue("settings", settings);
- }
- function loadSettings(){
- var thisVersion = GM_info.script.version;
- var defaultSettings = {"debug": false, "device": "", "initialKey": "Shift", "minKey": "Meta", "settingsKey": "F2", "syncKey": "z", "sync": 0,
- "showNotifications": true,
- "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} },
- "currentVersion": thisVersion};
- settings = GM_getValue("settings", defaultSettings);
- handleUpgrade(thisVersion);
- for(const setting in defaultSettings){
- if(settings[setting] === undefined){ settings[setting] = defaultSettings[setting]; }
- }
- return settings;
- }
- // --- TOAST NOTIFICATION SYSTEM ---
- var toastContainer = null;
- var toastQueue = [];
- var toastActive = false;
- function initToastContainer() {
- if (toastContainer) return;
- toastContainer = document.createElement('div');
- toastContainer.id = 'tcode-toast-container';
- toastContainer.style.cssText = `
- position: fixed; bottom: 20px; left: 50%; transform: translateX(-50%);
- z-index: 999999; display: flex; flex-direction: column-reverse; gap: 8px;
- pointer-events: none; max-width: 90%; width: 400px;
- `;
- document.body.appendChild(toastContainer);
- // Add toast styles
- var toastStyles = document.createElement('style');
- toastStyles.id = 'tcode-toast-styles';
- toastStyles.textContent = `
- .tcode-toast {
- background: linear-gradient(135deg, rgba(26, 26, 46, 0.95) 0%, rgba(22, 33, 62, 0.95) 100%);
- border: 1px solid rgba(255, 255, 255, 0.1);
- border-radius: 12px;
- padding: 14px 20px;
- color: #fff;
- font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
- font-size: 14px;
- box-shadow: 0 10px 40px rgba(0, 0, 0, 0.4);
- backdrop-filter: blur(10px);
- -webkit-backdrop-filter: blur(10px);
- display: flex;
- align-items: center;
- gap: 12px;
- animation: toastSlideIn 0.3s ease-out;
- pointer-events: auto;
- }
- .tcode-toast.toast-success { border-left: 4px solid #4ade80; }
- .tcode-toast.toast-info { border-left: 4px solid #60a5fa; }
- .tcode-toast.toast-warning { border-left: 4px solid #fbbf24; }
- .tcode-toast.toast-error { border-left: 4px solid #f87171; }
- .tcode-toast .toast-icon {
- font-size: 1.4em;
- flex-shrink: 0;
- }
- .tcode-toast .toast-content {
- flex: 1;
- }
- .tcode-toast .toast-title {
- font-weight: 600;
- margin-bottom: 2px;
- }
- .tcode-toast .toast-message {
- opacity: 0.8;
- font-size: 0.9em;
- }
- .tcode-toast.toast-exit {
- animation: toastSlideOut 0.3s ease-in forwards;
- }
- @keyframes toastSlideIn {
- from { opacity: 0; transform: translateY(20px); }
- to { opacity: 1; transform: translateY(0); }
- }
- @keyframes toastSlideOut {
- from { opacity: 1; transform: translateY(0); }
- to { opacity: 0; transform: translateY(-20px); }
- }
- `;
- document.head.appendChild(toastStyles);
- }
- function showToast(title, message, type = 'info', duration = 4000) {
- if (!settings.showNotifications) return;
- initToastContainer();
- var icons = {
- success: '✅',
- info: 'ℹ️',
- warning: '⚠️',
- error: '❌'
- };
- var toast = document.createElement('div');
- toast.className = 'tcode-toast toast-' + type;
- toast.innerHTML = `
- <span class="toast-icon">${icons[type] || icons.info}</span>
- <div class="toast-content">
- <div class="toast-title">${title}</div>
- ${message ? '<div class="toast-message">' + message + '</div>' : ''}
- </div>
- `;
- toastContainer.appendChild(toast);
- // Auto-remove after duration
- setTimeout(() => {
- toast.classList.add('toast-exit');
- setTimeout(() => {
- if (toast.parentNode) toast.remove();
- }, 300);
- }, duration);
- }
- // ---------------------------------
- function setKey(key){
- settings[pendingKey] = key;
- var label = document.getElementById(pendingKey).label;
- document.getElementById(pendingKey).innerHTML = label + " " + settings[pendingKey];
- pendingKey = null;
- saveSettings();
- }
- function settingsAddButton(parent, id, label, key=""){
- var button = document.createElement("button");
- button.setAttribute("id", id);
- button.innerHTML = label;
- button.label = label;
- if(key != ""){ button.innerHTML += " " + key; }
- parent.appendChild(button);
- }
- function settingsAddCheckBox(parent, id, label){
- var box = document.createElement("input");
- box.setAttribute("id", id);
- box.setAttribute("type", "checkbox");
- var boxLabel = document.createElement("label");
- boxLabel.setAttribute("for", id);
- boxLabel.innerHTML = " " + label;
- parent.appendChild(box);
- parent.appendChild(boxLabel);
- }
- function settingsAddInput(parent, id, label){
- var input = document.createElement("input");
- input.setAttribute("id", id);
- input.style.marginLeft = "3px";
- var inputLabel = document.createElement("label");
- inputLabel.setAttribute("for", id);
- inputLabel.innerHTML = " " + label;
- parent.appendChild(inputLabel);
- parent.appendChild(input);
- }
- function settingsAddDualSlider(parent, minId, maxId, label, minVal, maxVal, minLimit, maxLimit) {
- minVal = parseFloat(minVal); maxVal = parseFloat(maxVal); minLimit = parseFloat(minLimit); maxLimit = parseFloat(maxLimit);
- if (isNaN(minVal)) minVal = 0; if (isNaN(maxVal)) maxVal = 100; if (isNaN(minLimit)) minLimit = 0; if (isNaN(maxLimit)) maxLimit = 100;
- var wrapper = document.createElement("div"); wrapper.className = "dual-slider-container";
- var labelElem = document.createElement("label"); labelElem.innerHTML = label; wrapper.appendChild(labelElem);
- // Slider wrapper for positioning
- var sliderArea = document.createElement("div");
- sliderArea.className = "slider-area";
- sliderArea.style.cssText = "position: relative; height: 24px; width: 100%;";
- var track = document.createElement("div"); track.className = "slider-track"; sliderArea.appendChild(track);
- var fill = document.createElement("div"); fill.className = "slider-fill"; fill.id = minId + "Fill"; sliderArea.appendChild(fill);
- var minSlider = document.createElement("input");
- minSlider.type = "range"; minSlider.id = minId;
- minSlider.min = minLimit; minSlider.max = maxLimit; minSlider.value = minVal; minSlider.step = "1";
- minSlider.style.cssText = "position: absolute; left: 0; top: 50%; transform: translateY(-50%); width: 100%;";
- sliderArea.appendChild(minSlider);
- var maxSlider = document.createElement("input");
- maxSlider.type = "range"; maxSlider.id = maxId;
- maxSlider.min = minLimit; maxSlider.max = maxLimit; maxSlider.value = maxVal; maxSlider.step = "1";
- maxSlider.style.cssText = "position: absolute; left: 0; top: 50%; transform: translateY(-50%); width: 100%;";
- sliderArea.appendChild(maxSlider);
- wrapper.appendChild(sliderArea);
- var valuesDiv = document.createElement("div"); valuesDiv.className = "dual-slider-values";
- var minSpan = document.createElement("span"); minSpan.id = minId + "Value"; minSpan.innerHTML = minVal; valuesDiv.appendChild(minSpan);
- var maxSpan = document.createElement("span"); maxSpan.id = maxId + "Value"; maxSpan.innerHTML = maxVal; valuesDiv.appendChild(maxSpan);
- wrapper.appendChild(valuesDiv);
- parent.appendChild(wrapper);
- }
- function settingsAddSingleSlider(parent, id, label, value, minLimit, maxLimit, suffix="ms") {
- value = parseFloat(value); minLimit = parseFloat(minLimit); maxLimit = parseFloat(maxLimit);
- if (isNaN(value)) value = minLimit;
- var wrapper = document.createElement("div"); wrapper.className = "single-slider-container";
- var labelElem = document.createElement("label"); labelElem.innerHTML = label; wrapper.appendChild(labelElem);
- var sliderWrapper = document.createElement("div"); sliderWrapper.className = "slider-wrapper"; wrapper.appendChild(sliderWrapper);
- var track = document.createElement("div"); track.className = "slider-track"; sliderWrapper.appendChild(track);
- var fill = document.createElement("div"); fill.className = "slider-fill"; fill.id = id + "Fill"; sliderWrapper.appendChild(fill);
- var slider = document.createElement("input"); slider.type = "range"; slider.id = id; slider.min = minLimit; slider.max = maxLimit; slider.value = value; slider.step = "1";
- if(isChrome){ slider.style = "margin-top: -4px; transform: translateY(-50%)"; }
- sliderWrapper.appendChild(slider);
- var valueSpan = document.createElement("span"); valueSpan.id = id + "Value"; valueSpan.className = "single-slider-value"; valueSpan.innerHTML = String(value + suffix).padStart(6, ' ');
- wrapper.appendChild(valueSpan);
- parent.appendChild(wrapper);
- slider.addEventListener('input', () => {
- const currentVal = parseFloat(slider.value);
- const range = maxLimit - minLimit;
- const percent = ((currentVal - minLimit) / range) * 100;
- fill.style.width = `${percent}%`;
- valueSpan.textContent = String(currentVal + suffix).padStart(6, ' ');
- });
- const initialRange = maxLimit - minLimit;
- const initialPercent = ((value - minLimit) / initialRange) * 100;
- fill.style.width = `${initialPercent}%`;
- }
- function settingsAddGroupedControls(parent, checkboxId, axis, minId, maxId, sliderLabel, minVal, maxVal, minLimit, maxLimit, allSliderIds) {
- const groupContainer = document.createElement('div'); groupContainer.classList.add('control-group'); parent.appendChild(groupContainer);
- const checkboxWrapper = document.createElement('div'); checkboxWrapper.classList.add('checkbox-wrapper');
- const checkbox = document.createElement('input'); checkbox.type = 'checkbox'; checkbox.id = checkboxId; checkbox.checked = false;
- checkboxWrapper.appendChild(checkbox);
- const label = document.createElement('label'); label.setAttribute('for', checkboxId); label.textContent = axis;
- checkboxWrapper.appendChild(label); groupContainer.appendChild(checkboxWrapper);
- const randomWrapper = document.createElement('div'); randomWrapper.classList.add('random-wrapper');
- const randomCheckbox = document.createElement('input'); randomCheckbox.type = 'checkbox'; randomCheckbox.id = `random${axis}`;
- randomWrapper.appendChild(randomCheckbox);
- const randomLabel = document.createElement('label'); randomLabel.setAttribute('for', `random${axis}`); randomLabel.textContent = 'Random';
- randomWrapper.appendChild(randomLabel);
- const trackDropdown = document.createElement('select'); trackDropdown.id = `track${axis}`;
- allSliderIds.forEach(id => {
- if (id !== minId) {
- const option = document.createElement('option'); option.value = id; option.textContent = id; trackDropdown.appendChild(option);
- }
- });
- randomWrapper.appendChild(trackDropdown); groupContainer.appendChild(randomWrapper);
- const invertWrapper = document.createElement('div'); invertWrapper.classList.add('invert-wrapper');
- const invertCheckbox = document.createElement('input'); invertCheckbox.type = 'checkbox'; invertCheckbox.id = `invert${axis}`;
- invertWrapper.appendChild(invertCheckbox);
- const invertLabel = document.createElement('label'); invertLabel.setAttribute('for', `invert${axis}`); invertLabel.textContent = 'Invert';
- invertWrapper.appendChild(invertLabel);
- groupContainer.appendChild(invertWrapper);
- settingsAddDualSlider(groupContainer, minId, maxId, sliderLabel, minVal, maxVal, minLimit, maxLimit);
- const dualSliderContainer = groupContainer.querySelector('.dual-slider-container');
- checkbox.addEventListener('change', (event) => {
- settings.axes[axis].enabled = event.target.checked;
- if (event.target.checked) {
- dualSliderContainer.classList.remove('disabled');
- randomWrapper.style.opacity = '1';
- invertWrapper.style.opacity = '1';
- } else {
- dualSliderContainer.classList.add('disabled');
- randomWrapper.style.opacity = '0.5';
- invertWrapper.style.opacity = '0.5';
- }
- });
- randomCheckbox.addEventListener('change', (event) => { settings.axes[axis].random = event.target.value; });
- invertCheckbox.addEventListener('change', (event) => { settings.axes[axis].invert = event.target.checked; });
- toolTip(randomCheckbox, "Generates random motion, based on selected axis");
- if (!checkbox.checked) {
- dualSliderContainer.classList.add('disabled');
- randomWrapper.style.opacity = '0.5';
- invertWrapper.style.opacity = '0.5';
- }
- }
- function menuListeners(keys){
- for(var key of keys){
- document.getElementById(key).addEventListener("click", function(){ this.innerHTML = "Press a key..."; pendingKey = this.id; }, false);
- }
- }
- function dualSliderListeners(minId, maxId) {
- const minSlider = document.getElementById(minId); const maxSlider = document.getElementById(maxId);
- const fill = document.getElementById(minId + "Fill"); const minValueDisplay = document.getElementById(minId + "Value"); const maxValueDisplay = document.getElementById(maxId + "Value");
- if (!minSlider || !maxSlider || !minValueDisplay || !maxValueDisplay || !fill) return;
- function updateDualSlider() {
- let currentMinVal = parseFloat(minSlider.value); let currentMaxVal = parseFloat(maxSlider.value);
- if (currentMinVal > currentMaxVal) { minSlider.value = currentMaxVal; }
- if (currentMaxVal < currentMinVal) { maxSlider.value = currentMinVal; }
- currentMinVal = parseFloat(minSlider.value); currentMaxVal = parseFloat(maxSlider.value);
- const range = parseFloat(maxSlider.max) - parseFloat(minSlider.min);
- const minPercent = ((currentMinVal - parseFloat(minSlider.min)) / range) * 100;
- const maxPercent = ((currentMaxVal - parseFloat(minSlider.min)) / range) * 100;
- fill.style.left = `${minPercent}%`; fill.style.width = `${Math.abs(maxPercent - minPercent)}%`;
- minValueDisplay.textContent = currentMinVal; maxValueDisplay.textContent = currentMaxVal;
- setLimits(currentMinVal, currentMaxVal, minSlider.id.replace('min', ''), false);
- }
- minSlider.addEventListener('input', updateDualSlider); maxSlider.addEventListener('input', updateDualSlider);
- updateDualSlider();
- }
- let activeTab = 'device';
- function settingsAddTabContent(parentDiv, type, id, label, key = "") {
- switch (type) {
- case 'button': settingsAddButton(parentDiv, id, label, key); break;
- case 'checkbox': settingsAddCheckBox(parentDiv, id, label); break;
- case 'input': settingsAddInput(parentDiv, id, label); break;
- }
- }
- function showTab(tabId) {
- const tabContents = document.querySelectorAll('.tab-content'); tabContents.forEach(content => { content.style.display = 'none'; });
- const tabButtons = document.querySelectorAll('.tab-button'); tabButtons.forEach(button => { button.classList.remove('active-tab'); });
- const selectedTabContent = document.getElementById(tabId + 'Content'); if (selectedTabContent) { selectedTabContent.style.display = 'block'; }
- const selectedTabButton = document.getElementById(tabId + 'Tab'); if (selectedTabButton) { selectedTabButton.classList.add('active-tab'); }
- activeTab = tabId;
- }
- function toolTip(element, txt){
- var tooltip = document.querySelector('#dynamic-tooltip');
- if(!tooltip){
- tooltip = document.createElement('div'); tooltip.id = 'dynamic-tooltip';
- tooltip.style.position = 'absolute'; tooltip.style.backgroundColor = 'black'; tooltip.style.color = 'white';
- tooltip.style.padding = '5px'; tooltip.style.zIndex = '200000'; tooltip.style.visibility = 'hidden';
- document.body.appendChild(tooltip);
- }
- var tooltipTimeout = null;
- element.addEventListener('mouseover', () => { tooltipTimeout = setTimeout(function(){ tooltip.textContent = txt; tooltip.style.visibility = 'visible'; }, 750); });
- element.addEventListener('mousemove', (e) => { tooltip.style.left = e.pageX + 10 + 'px'; tooltip.style.top = e.pageY + 10 + 'px'; });
- element.addEventListener('mouseout', () => { clearTimeout(tooltipTimeout); tooltip.style.visibility = 'hidden'; });
- }
- function toggleMenu() {
- if (document.getElementById("settings-overlay") != null) {
- document.getElementById("settings-close-btn").click();
- return -1;
- }
- // Modern dark theme stylesheet
- const styleSheet = document.createElement("style");
- styleSheet.id = "stash-tcode-styles";
- styleSheet.type = "text/css";
- styleSheet.innerText = `
- /* Overlay backdrop with blur */
- #settings-overlay {
- position: fixed; top: 0; left: 0; right: 0; bottom: 0;
- background: rgba(0, 0, 0, 0.6); backdrop-filter: blur(8px); -webkit-backdrop-filter: blur(8px);
- z-index: 999998; display: flex; align-items: center; justify-content: center;
- }
- /* Main settings panel */
- #settings {
- position: relative; width: 90%; max-width: 700px; max-height: 85vh;
- background: linear-gradient(145deg, #1a1a2e 0%, #16213e 100%);
- 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);
- overflow: hidden; font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
- }
- /* Header */
- #settings .settings-header {
- background: linear-gradient(90deg, #0f3460 0%, #533483 100%);
- padding: 20px 24px; display: flex; align-items: center; justify-content: space-between;
- }
- #settings .settings-title {
- font-size: 1.5em; font-weight: 700; color: #fff; letter-spacing: 0.5px;
- text-shadow: 0 2px 4px rgba(0,0,0,0.3);
- }
- #settings-close-btn {
- width: 36px; height: 36px; border-radius: 50%; border: none;
- background: rgba(255,255,255,0.1); color: #fff; font-size: 1.4em;
- cursor: pointer; transition: all 0.2s ease; display: flex; align-items: center; justify-content: center;
- }
- #settings-close-btn:hover { background: rgba(255,255,255,0.2); transform: scale(1.1); }
- /* Tab navigation */
- #tabContainer {
- display: flex; background: rgba(0,0,0,0.3); padding: 0 16px; gap: 4px;
- }
- .tab-button {
- padding: 14px 20px; border: none; background: transparent; color: rgba(255,255,255,0.6);
- font-size: 0.95em; font-weight: 500; cursor: pointer; transition: all 0.2s ease;
- border-bottom: 3px solid transparent; text-transform: uppercase; letter-spacing: 0.5px;
- }
- .tab-button:hover { color: rgba(255,255,255,0.9); background: rgba(255,255,255,0.05); }
- .tab-button.active-tab {
- color: #e94560 !important; border-bottom-color: #e94560 !important;
- background: rgba(233, 69, 96, 0.1) !important;
- }
- /* Tab content area */
- #tabContentContainer {
- padding: 24px; max-height: calc(85vh - 140px); overflow-y: auto; color: #e0e0e0;
- }
- #tabContentContainer::-webkit-scrollbar { width: 8px; }
- #tabContentContainer::-webkit-scrollbar-track { background: rgba(255,255,255,0.05); border-radius: 4px; }
- #tabContentContainer::-webkit-scrollbar-thumb { background: rgba(255,255,255,0.2); border-radius: 4px; }
- #tabContentContainer::-webkit-scrollbar-thumb:hover { background: rgba(255,255,255,0.3); }
- .tab-content { display: none; animation: fadeIn 0.3s ease; }
- @keyframes fadeIn { from { opacity: 0; transform: translateY(10px); } to { opacity: 1; transform: translateY(0); } }
- /* Control groups */
- .control-group {
- display: flex; align-items: center; gap: 16px; padding: 16px 20px; margin-bottom: 12px;
- background: rgba(255,255,255,0.05); border: 1px solid rgba(255,255,255,0.1);
- border-radius: 12px; transition: all 0.2s ease;
- }
- .control-group:hover { background: rgba(255,255,255,0.08); border-color: rgba(255,255,255,0.15); }
- .checkbox-wrapper { display: flex; align-items: center; gap: 8px; min-width: 50px; }
- .checkbox-wrapper label { color: #fff; font-weight: 600; font-size: 1.1em; }
- .random-wrapper { display: flex; align-items: center; gap: 8px; }
- .random-wrapper label { color: rgba(255,255,255,0.7); font-size: 0.9em; }
- .invert-wrapper { display: flex; align-items: center; gap: 8px; }
- .invert-wrapper label { color: rgba(255,255,255,0.7); font-size: 0.9em; }
- /* Custom checkboxes */
- .control-group input[type="checkbox"], #tabContentContainer input[type="checkbox"] {
- width: 20px; height: 20px; accent-color: #e94560; cursor: pointer;
- }
- /* Dropdowns */
- .control-group select, #tabContentContainer select {
- background: rgba(255,255,255,0.1); border: 1px solid rgba(255,255,255,0.2);
- color: #fff; padding: 6px 10px; border-radius: 6px; cursor: pointer;
- }
- .control-group select option, #tabContentContainer select option {
- background: #1a1a2e; color: #fff;
- }
- .control-group select:focus, #tabContentContainer select:focus { outline: none; border-color: #e94560; }
- /* Dual slider container */
- .dual-slider-container {
- flex: 1; min-width: 200px; margin: 0; padding: 5px 0;
- }
- .dual-slider-container.disabled { pointer-events: none; opacity: 0.4; }
- .dual-slider-container > label { display: block; margin-bottom: 8px; color: rgba(255,255,255,0.7); font-size: 0.9em; }
- .dual-slider-container .slider-area {
- position: relative; height: 24px; width: 100%;
- }
- .dual-slider-container .slider-track {
- position: absolute; left: 0; right: 0; top: 50%; transform: translateY(-50%);
- height: 6px; border-radius: 3px; background: rgba(255,255,255,0.15); z-index: 0;
- }
- .dual-slider-container .slider-fill {
- position: absolute; top: 50%; transform: translateY(-50%);
- height: 6px; border-radius: 3px; background: linear-gradient(90deg, #e94560, #533483);
- z-index: 1; left: 0; width: 100%;
- }
- .dual-slider-container input[type="range"] {
- -webkit-appearance: none; appearance: none; width: 100%; outline: none;
- background: transparent; pointer-events: none; z-index: 3; margin: 0; height: 24px;
- }
- .dual-slider-container input[type="range"]::-webkit-slider-runnable-track {
- height: 6px; background: transparent;
- }
- .dual-slider-container input[type="range"]::-webkit-slider-thumb {
- -webkit-appearance: none; appearance: none; height: 18px; width: 18px;
- background: #fff; cursor: pointer; pointer-events: auto; border-radius: 50%;
- box-shadow: 0 2px 6px rgba(0,0,0,0.3), 0 0 0 2px rgba(233, 69, 96, 0.3);
- transition: transform 0.15s ease, box-shadow 0.15s ease;
- margin-top: -6px;
- }
- .dual-slider-container input[type="range"]::-webkit-slider-thumb:hover {
- transform: scale(1.15);
- box-shadow: 0 2px 8px rgba(0,0,0,0.4), 0 0 0 3px rgba(233, 69, 96, 0.4);
- }
- .dual-slider-container input[type="range"]:hover { z-index: 10; }
- .dual-slider-container input[type="range"]:active { z-index: 11; }
- .dual-slider-values {
- display: flex; justify-content: space-between; margin-top: 8px;
- font-size: 0.85em; color: rgba(255,255,255,0.7); font-weight: 500;
- }
- .dual-slider-values span {
- min-width: 40px; text-align: center;
- }
- /* Single slider */
- .single-slider-container {
- display: flex; align-items: center; gap: 16px; width: 100%;
- padding: 16px 20px; background: rgba(255,255,255,0.05);
- border: 1px solid rgba(255,255,255,0.1); border-radius: 12px; margin-bottom: 12px;
- }
- .single-slider-container label { color: #fff; font-weight: 500; min-width: 60px; }
- .single-slider-container .slider-wrapper {
- position: relative; flex-grow: 1; display: flex; align-items: center; height: 24px;
- }
- .single-slider-container .slider-track, .single-slider-container .slider-fill {
- position: absolute; height: 6px; border-radius: 3px; left: 0; top: 50%; transform: translateY(-50%); width: 100%;
- }
- .single-slider-container .slider-track { background: rgba(255,255,255,0.15); }
- .single-slider-container .slider-fill { background: linear-gradient(90deg, #e94560, #533483); }
- .single-slider-container input[type="range"] {
- -webkit-appearance: none; appearance: none; background: transparent; cursor: pointer;
- width: 100%; position: absolute; left: 0; top: 50%; transform: translateY(-50%); z-index: 2;
- }
- .single-slider-container input[type="range"]::-webkit-slider-thumb {
- -webkit-appearance: none; height: 20px; width: 20px; background: #fff;
- border-radius: 50%; box-shadow: 0 2px 6px rgba(0,0,0,0.3); cursor: pointer;
- }
- .single-slider-container input[type="range"]::-webkit-slider-runnable-track { background: transparent; }
- .single-slider-value {
- flex-shrink: 0; min-width: 60px; text-align: right; color: rgba(255,255,255,0.8);
- font-family: 'SF Mono', Monaco, monospace; font-size: 0.9em;
- }
- /* Buttons */
- #tabContentContainer button {
- padding: 12px 24px; border: none; border-radius: 8px; font-size: 0.95em;
- font-weight: 600; cursor: pointer; transition: all 0.2s ease; margin: 8px 8px 8px 0;
- }
- #btnConnectUSB {
- background: linear-gradient(135deg, #e94560 0%, #533483 100%) !important;
- color: #fff !important; box-shadow: 0 4px 15px rgba(233, 69, 96, 0.3);
- }
- #btnConnectUSB:hover:not(:disabled) { transform: translateY(-2px); box-shadow: 0 6px 20px rgba(233, 69, 96, 0.4); }
- #btnConnectUSB:disabled { opacity: 0.6; cursor: not-allowed; }
- #initialKey, #minKey, #settingsKey {
- background: rgba(255,255,255,0.1) !important; color: #fff !important;
- border: 1px solid rgba(255,255,255,0.2) !important;
- }
- #initialKey:hover, #minKey:hover, #settingsKey:hover {
- background: rgba(255,255,255,0.15) !important; border-color: #e94560 !important;
- }
- /* Labels in tab content */
- #tabContentContainer > label { color: rgba(255,255,255,0.8); display: flex; align-items: center; gap: 8px; margin: 12px 0; }
- `;
- document.head.appendChild(styleSheet);
- // Create overlay backdrop
- var overlay = document.createElement("div");
- overlay.setAttribute("id", "settings-overlay");
- // Main settings panel
- var div = document.createElement("div");
- div.setAttribute("id", "settings");
- // Header
- var header = document.createElement("div");
- header.className = "settings-header";
- var title = document.createElement("span");
- title.className = "settings-title";
- title.innerHTML = "⚙️ TCode Settings";
- var closeBtn = document.createElement("button");
- closeBtn.id = "settings-close-btn";
- closeBtn.innerHTML = "✕";
- header.appendChild(title);
- header.appendChild(closeBtn);
- div.appendChild(header);
- // Tab container
- var tabContainer = document.createElement("div");
- tabContainer.id = "tabContainer";
- div.appendChild(tabContainer);
- // Tab content container
- var tabContentContainer = document.createElement("div");
- tabContentContainer.id = "tabContentContainer";
- div.appendChild(tabContentContainer);
- // Create tabs
- const tabs = ['device', 'keys', 'axes', 'advanced'];
- const tabContents = {};
- const tabIcons = { device: '🔌', keys: '⌨️', axes: '🎚️', advanced: '🔧' };
- tabs.forEach(t => {
- const btn = document.createElement('button');
- btn.id = t + 'Tab';
- btn.className = 'tab-button';
- btn.innerHTML = tabIcons[t] + ' ' + t.charAt(0).toUpperCase() + t.slice(1);
- btn.addEventListener('click', () => showTab(t));
- tabContainer.appendChild(btn);
- const content = document.createElement('div');
- content.id = t + 'Content';
- content.className = 'tab-content';
- content.style.display = 'none';
- tabContentContainer.appendChild(content);
- tabContents[t] = content;
- });
- // Device tab content
- const deviceContentDiv = tabContents['device'];
- const usbBtn = document.createElement('button');
- usbBtn.id = "btnConnectUSB";
- usbBtn.innerText = serialConnected ? "✓ USB Connected" : "🔗 Connect Serial (USB)";
- usbBtn.onclick = function() { connectSerial(); };
- if (serialConnected) usbBtn.disabled = true;
- deviceContentDiv.appendChild(usbBtn);
- deviceContentDiv.appendChild(document.createElement("br"));
- deviceContentDiv.appendChild(document.createElement("br"));
- settingsAddSingleSlider(deviceContentDiv, "sync", "Sync:", settings.sync, -250, 250);
- // Keys tab content
- const keysContentDiv = tabContents['keys'];
- settingsAddTabContent(keysContentDiv, "button", "initialKey", "Set Initial Ranges: ", settings.initialKey);
- keysContentDiv.appendChild(document.createElement("br"));
- settingsAddTabContent(keysContentDiv, "button", "minKey", "Set Minimum: ", settings.minKey);
- // Axes tab content
- const axesContentDiv = tabContents['axes'];
- ["L0","L1","L2","R0","R1","R2"].forEach(ax => {
- settingsAddGroupedControls(axesContentDiv, "enable"+ax, ax, "min"+ax, "max"+ax, "Range:", getLimit(ax,LOWER), getLimit(ax,UPPER), 0, 9999, listAxes(ax));
- });
- // Advanced tab content
- const advancedContentDiv = tabContents['advanced'];
- settingsAddTabContent(advancedContentDiv, "button", "settingsKey", "Settings Hotkey: ", settings.settingsKey);
- advancedContentDiv.appendChild(document.createElement("br"));
- settingsAddTabContent(advancedContentDiv, "checkbox", "showNotifications", "Show Script Load Notifications");
- advancedContentDiv.appendChild(document.createElement("br"));
- settingsAddTabContent(advancedContentDiv, "checkbox", "debug", "Enable Debug Mode");
- // Append panel to overlay, then overlay to body
- overlay.appendChild(div);
- document.body.appendChild(overlay);
- showTab(activeTab);
- settingsMenuApplySaved();
- // Close button handler
- closeBtn.addEventListener("click", function(){
- saveSettings();
- var overlayEl = document.getElementById("settings-overlay");
- if (overlayEl) overlayEl.remove();
- var styleEl = document.getElementById("stash-tcode-styles");
- if (styleEl) styleEl.remove();
- }, false);
- // Click on backdrop to close
- overlay.addEventListener("click", function(e){
- if (e.target === overlay) closeBtn.click();
- }, false);
- document.getElementById("settings").addEventListener("change", function(){ saveSettings(false); }, false);
- menuListeners(["initialKey", "settingsKey", "minKey"]);
- ["L0","L1","L2","R0","R1","R2"].forEach(ax => dualSliderListeners("min"+ax, "max"+ax));
- }
- // --- WEB SERIAL IMPLEMENTATION ---
- async function connectSerial() {
- if (!navigator.serial) {
- 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.");
- return;
- }
- try {
- port = await navigator.serial.requestPort();
- await port.open({ baudRate: 115200 }); // Standard TCode Baud Rate
- const textEncoder = new TextEncoderStream();
- writableStreamClosed = textEncoder.readable.pipeTo(port.writable);
- writer = textEncoder.writable.getWriter();
- serialConnected = true;
- keepReading = true;
- var usbBtn = document.getElementById("btnConnectUSB");
- if (usbBtn) {
- usbBtn.innerText = "USB Connected";
- usbBtn.disabled = true;
- }
- debug("USB Serial Connected");
- createOverlay("USB Connected");
- showToast("USB Connected", "Serial connection established at 115200 baud", "success");
- readSerialLoop();
- } catch (e) {
- console.error("Serial Connection Failed:", e);
- showToast("Connection Failed", e.message, "error");
- alert("Could not connect to Serial device. \n" + e.message);
- }
- }
- async function readSerialLoop() {
- while (port.readable && keepReading) {
- const textDecoder = new TextDecoderStream();
- readableStreamClosed = port.readable.pipeTo(textDecoder.writable);
- reader = textDecoder.readable.getReader();
- try {
- while (true) {
- const { value, done } = await reader.read();
- if (done) { break; }
- if (value) { processWSReply({ data: value }); }
- }
- } catch (error) { console.error(error); } finally { reader.releaseLock(); }
- }
- }
- function sendTCode(data) {
- if (serialConnected && writer) { writer.write(data); }
- }
- // ---------------------------------
- /* Stash Integration */
- function fetchSceneInfo(id){
- GM_xmlhttpRequest({
- method: "POST",
- url: location.protocol + '//' + location.host + '/graphql',
- 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}"}',
- cookie: document.cookie,
- anonymous: true,
- headers: { "Content-Type": "application/json" },
- onload: function(response){
- var json = JSON.parse(response.response);
- if(json.data && json.data.findScene && json.data.findScene.files.length > 0){
- video = json.data.findScene.files[0].path;
- debug("Video: " + video);
- fetchAllFunscripts();
- }
- }
- });
- }
- function initAxis(name){
- if(AXIS[name]){ return -1; }
- AXIS[name] = new Object();
- AXIS[name].index = 0; AXIS[name].start = 0; AXIS[name].end = 0; AXIS[name].scriptLoaded = false;
- AXIS[name].acts = null; AXIS[name].limits = null; AXIS[name].altLimits = null;
- }
- function fetchAllFunscripts(){
- // First, try to fetch the main funscript which may contain multiple axes
- fetchMainFunscript();
- }
- // Parse a multi-axis funscript file (version 1.1+ with "axes" array)
- function parseMultiAxisFunscript(json) {
- var foundAxes = [];
- // Check if this is a multi-axis funscript (has "axes" array)
- if (json.axes && Array.isArray(json.axes) && json.axes.length > 0) {
- debug("Multi-axis funscript detected with " + json.axes.length + " axes");
- // Process each axis in the axes array
- for (var i = 0; i < json.axes.length; i++) {
- var axisData = json.axes[i];
- var axisId = axisData.id; // e.g., "R1", "R2", "L0", etc.
- if (axisId && axisData.actions && Array.isArray(axisData.actions) && axisData.actions.length > 0) {
- if (!AXIS[axisId]) { initAxis(axisId); }
- AXIS[axisId].acts = axisData.actions;
- AXIS[axisId].start = AXIS[axisId].acts[0].at;
- AXIS[axisId].end = AXIS[axisId].acts[AXIS[axisId].acts.length - 1].at;
- AXIS[axisId].scriptLoaded = true;
- foundAxes.push(axisId);
- debug("Loaded axis " + axisId + " from multi-axis file with " + axisData.actions.length + " actions");
- }
- }
- // Also check for root-level actions (usually L0/stroke)
- if (json.actions && Array.isArray(json.actions) && json.actions.length > 0) {
- if (!AXIS["L0"]) { initAxis("L0"); }
- AXIS["L0"].acts = json.actions;
- AXIS["L0"].start = AXIS["L0"].acts[0].at;
- AXIS["L0"].end = AXIS["L0"].acts[AXIS["L0"].acts.length - 1].at;
- AXIS["L0"].scriptLoaded = true;
- foundAxes.push("L0");
- debug("Loaded L0 from root actions with " + json.actions.length + " actions");
- }
- return foundAxes;
- }
- // Not a multi-axis file
- return null;
- }
- // Fetch the main funscript file first, then check if it's multi-axis
- function fetchMainFunscript() {
- var chosenScript = document.querySelector('#stash-interactive-tools-select-funscripts');
- var url = "";
- if (chosenScript) {
- url = chosenScript.value;
- } else {
- url = location.protocol + '//' + location.host + '/scene/' + getSceneId() + '/funscript';
- }
- GM_xmlhttpRequest({
- method: "GET",
- url: url,
- cookie: document.cookie,
- anonymous: true,
- onload: function(response) {
- if (response.status == 200) {
- try {
- var json = JSON.parse(response.response);
- // Try to parse as multi-axis first
- var multiAxisResult = parseMultiAxisFunscript(json);
- if (multiAxisResult && multiAxisResult.length > 0) {
- // Multi-axis file was successfully parsed
- debug("Successfully loaded multi-axis funscript with axes: " + multiAxisResult.join(", "));
- showToast("Multi-Axis Script Loaded", "Parsed " + multiAxisResult.length + " axes: " + multiAxisResult.join(", "), "success");
- // For any axes not found in the multi-axis file, try fetching separate files or use random
- for (var axis in AXIS) {
- if (!AXIS[axis].scriptLoaded) {
- if (settings.axes[axis].random != "") {
- generateRandomMotion(axis, settings.axes[axis].random);
- AXIS[axis].scriptLoaded = true;
- } else {
- // Try fetching individual axis file
- fetchFunscript(axis, true);
- }
- }
- }
- } else {
- // Single-axis file (legacy format) - load as L0
- if (json.actions && Array.isArray(json.actions) && json.actions.length > 0) {
- if (!AXIS["L0"]) { initAxis("L0"); }
- AXIS["L0"].acts = json.actions;
- AXIS["L0"].start = AXIS["L0"].acts[0].at;
- AXIS["L0"].end = AXIS["L0"].acts[AXIS["L0"].acts.length - 1].at;
- AXIS["L0"].scriptLoaded = true;
- debug("Loaded single-axis funscript as L0 with " + json.actions.length + " actions");
- showToast("Script Loaded", "L0 axis with " + json.actions.length + " actions", "success");
- }
- // Fetch other axes from separate files
- for (var axis in AXIS) {
- if (!AXIS[axis].scriptLoaded) {
- if (settings.axes[axis].random != "") {
- if (!AXIS[settings.axes[axis].random].scriptLoaded) {
- fetchFunscript(axis);
- } else {
- generateRandomMotion(axis, settings.axes[axis].random);
- AXIS[axis].scriptLoaded = true;
- }
- } else if (axis !== "L0") {
- fetchFunscript(axis);
- }
- }
- }
- }
- } catch (error) {
- debug("JSON parse error in main funscript: " + error);
- showToast("Parse Error", "Failed to parse funscript, trying individual files", "warning");
- // Fallback to fetching individual files
- fetchIndividualAxisFiles();
- }
- } else {
- debug("Main funscript not found, trying individual files");
- showToast("No Main Script", "Searching for individual axis files...", "info");
- fetchIndividualAxisFiles();
- }
- // Clean up dropdown options
- if (chosenScript) { cleanUpOptions(chosenScript); }
- }
- });
- }
- // Fallback: fetch individual axis files
- function fetchIndividualAxisFiles() {
- for (var axis in AXIS) {
- if (settings.axes[axis].random != "") {
- if (!AXIS[settings.axes[axis].random].scriptLoaded) {
- fetchFunscript(axis);
- }
- }
- if (!AXIS[axis].scriptLoaded) {
- fetchFunscript(axis);
- }
- }
- var chosenScript = document.querySelector('#stash-interactive-tools-select-funscripts');
- if (chosenScript) { cleanUpOptions(chosenScript); }
- }
- function generateRandomMotion(axis, relatedAxis=""){
- if(AXIS[axis].acts != null){ return -1; }
- var interval = -1;
- var modifier = Math.random() * (1500 - 250) + 250;
- if(Math.random() < 0.5){ modifier * -1; }
- if(AXIS[relatedAxis]){
- if(AXIS[relatedAxis].acts == null && generateRandomMotion.caller != ""){
- setTimeout(function(){ generateRandomMotion(axis, relatedAxis) }, 500);
- return -1;
- }
- AXIS[axis].acts = new Array();
- for(var i=AXIS[relatedAxis].index;i<AXIS[relatedAxis].acts.length;i++){
- AXIS[axis].acts[i] = new Object();
- interval = Math.round(AXIS[relatedAxis].acts[i].at + modifier);
- if(interval < 0){ interval = 0; }
- AXIS[axis].acts[i].at = interval;
- AXIS[axis].acts[i].pos = AXIS[relatedAxis].acts[i].pos;
- }
- AXIS[axis].start = AXIS[axis].acts[0].at;
- AXIS[axis].end = AXIS[axis].acts[AXIS[axis].acts.length-1].at;
- }
- }
- function fetchFunscript(axis, force=false){
- if(scriptList == null){
- GM_xmlhttpRequest({
- method: "POST",
- url: location.protocol + '//' + location.host + '/graphql',
- 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}"}',
- cookie: document.cookie,
- anonymous: true,
- headers: { "Content-Type": "application/json" },
- onload: function(response){
- var json = JSON.parse(response.response);
- if(json.data && json.data.runPluginOperation){
- scriptList = json.data.runPluginOperation.scripts;
- fetchFunscript(axis);
- }
- }
- });
- }else{
- var chosenScript = document.querySelector('#stash-interactive-tools-select-funscripts');
- if(!chosenScript && !force){ setTimeout(function(){fetchFunscript(axis, true)}, 500); return -1; }
- var url = "";
- if(chosenScript){ url = chosenScript.value.split('.funscript')[0]; }
- else{ url = location.protocol + '//' + location.host + '/scene/' + getSceneId() + '/funscript'; }
- switch(axis){
- 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;
- }
- if(chosenScript){ url = url + ".funscript"; }
- GM_xmlhttpRequest({
- method: "GET", url: url, cookie: document.cookie, anonymous: true,
- onload: function(response){
- if(response.status == 200){
- if(!AXIS[axis]){ AXIS[axis] = new Object(); }
- try { AXIS[axis].acts = JSON.parse(response.response).actions; }
- catch (error) { debug("JSON error"); }
- if(AXIS[axis].acts == null){ fetchFunscript(axis, force); return -1; }
- AXIS[axis].start = AXIS[axis].acts[0].at;
- AXIS[axis].end = AXIS[axis].acts[AXIS[axis].acts.length-1].at;
- showToast("Axis Loaded", axis + " with " + AXIS[axis].acts.length + " actions", "success", 3000);
- }else{
- if(settings.axes[axis].random != ""){
- generateRandomMotion(axis, settings.axes[axis].random);
- showToast("Random Generated", axis + " (based on " + settings.axes[axis].random + ")", "info", 3000);
- }
- else{ AXIS[axis].acts = null; }
- }
- AXIS[axis].scriptLoaded = true;
- }
- });
- }
- }
- function listAxes(exclude=""){
- var keys = Object.keys(AXIS);
- let removeAxis = keys.indexOf(exclude);
- if (removeAxis !== -1) { keys.splice(removeAxis, 1); }
- return keys;
- }
- function centerAxis(axis){
- if(!serialConnected){ return -1; }
- if(!settings.axes[axis].enabled){ return -1; }
- if(!AXIS[axis].limits || AXIS[axis].limits == null){ setTimeout(function(){ centerAxis(axis)}, 500); return -1; }
- var center = Math.floor(parseInt(AXIS[axis].limits[0]) + ((AXIS[axis].limits[1] - AXIS[axis].limits[0])/2));
- sendTCode(axis + 5 + "I" + center + '\n');
- }
- function formatMoveCommand(axis, pos, int){
- if(parseInt(pos) > parseInt(AXIS[axis].limits[1]/100)){ pos = Math.floor(AXIS[axis].limits[1]/100); }
- else if(parseInt(pos) < parseInt(AXIS[axis].limits[0]/100)){ pos = Math.floor(AXIS[axis].limits[0]/100); }
- if(pos < 10){ pos = "0" + pos; }
- var cmd = axis + pos + "I" + int;
- debug(`[TCode] Queued: ${cmd} (axis: ${axis}, enabled: ${settings.axes[axis]?.enabled}, hasLimits: ${AXIS[axis].limits != null})`);
- return cmd;
- }
- function currentAction(ms){
- if(msPending){ return -1; }
- msPending = true;
- ms += parseInt(settings.sync);
- var cmdBuffer = "";
- for(var x in AXIS){
- if(settings.axes[x].enabled && AXIS[x].acts != null && AXIS[x].limits != null && AXIS[x].acts[AXIS[x].index] != null){
- if(AXIS[x].index == 0 || AXIS[x].acts[AXIS[x].index-1].at < ms){
- for(var i=AXIS[x].index;i<AXIS[x].acts.length;i++){
- if(AXIS[x].acts[i].at > ms){
- var pos = AXIS[x].acts[i].pos;
- if (settings.axes[x].invert) { pos = 100 - pos; }
- var act = Math.floor((((pos/100)*(AXIS[x].limits[1] - AXIS[x].limits[0]))+parseInt(AXIS[x].limits[0]))/100);
- var cmd = formatMoveCommand(x, act, (AXIS[x].acts[i].at - ms));
- if(cmd) cmdBuffer += cmd;
- AXIS[x].index = ++i;
- break;
- }
- }
- }
- }
- }
- if(cmdBuffer.length > 0 && serialConnected){
- sendTCode(cmdBuffer + '\n');
- }
- msPending = false;
- }
- function resetIndex(axis=""){
- for(var i in AXIS){ if(settings.axes[i].enabled){ AXIS[i].index = 0; } }
- }
- function updateTime(player){
- if(!player.paused){ currentAction(Math.floor(player.currentTime*1000)); }
- }
- function waitForVideoPlayer(){
- var player = document.querySelector('video');
- if(!player){ setTimeout(waitForVideoPlayer, 500); }
- else{
- if(!videoPlayerLoaded){
- player.addEventListener("seeking", resetIndex, false);
- init();
- videoPlayerLoaded = true;
- }
- updateTime(player);
- setTimeout(waitForVideoPlayer, 10);
- }
- }
- function setInitials(axis="L0"){
- if(AXIS[axis] && AXIS[axis].limits != null){ AXIS[axis].altLimits = AXIS[axis].limits.slice(0); }
- }
- function processLimits(data){
- var values;
- var axesFound = [];
- console.log(`[TCode] Device returned limits:`, data);
- for(var i=0;i<data.length-1;i++){
- values = data[i].split(' ');
- if(AXIS[values[0]]){
- AXIS[values[0]].limits = new Array(values[1], values[2]);
- AXIS[values[0]].altLimits = new Array(values[1], values[2]);
- console.log(`[TCode] Set ${values[0]} limits: ${values[1]} - ${values[2]}`);
- // Auto-enable axes that the device supports (L and R axes only, not V or A)
- if(/^[LR]\d+$/.test(values[0]) && settings.axes[values[0]]){
- if(!settings.axes[values[0]].enabled){
- settings.axes[values[0]].enabled = true;
- axesFound.push(values[0]);
- console.log(`[TCode] Auto-enabled ${values[0]} (device supports this axis)`);
- }
- }
- }
- }
- if(axesFound.length > 0){
- showToast("Axes Auto-Enabled", "Enabled " + axesFound.join(", ") + " based on device capabilities", "info");
- saveSettings(false); // Save without sending to device
- }
- }
- function processWSReply(event){
- try {
- // Accumulate data in buffer
- serialBuffer += event.data;
- // Clear existing timeout
- if(bufferTimeout) clearTimeout(bufferTimeout);
- // Wait for data to finish arriving (100ms timeout)
- bufferTimeout = setTimeout(() => {
- var cleanData = serialBuffer.replaceAll('\n', '|').replaceAll('\r', '');
- serialBuffer = ""; // Clear buffer
- // Handle JSON format (wrapped in {command: "..."})
- if(cleanData.startsWith('{')) {
- var json = JSON.parse(cleanData);
- debug("[TCode] Parsed JSON: " + JSON.stringify(json));
- processLimits(json.command.split("|"));
- }
- // Handle plain text format - check if ANY line matches axis limits pattern
- else if(/[LRVA]\d+\s+\d+\s+\d+/.test(cleanData)) {
- debug("[TCode] Plain text limits detected");
- // Filter and process only lines that match the pattern (including those after pipes)
- var lines = cleanData.split("|");
- var validLines = lines.filter(line => {
- var trimmed = line.trim();
- return /^[LRVA]\d+\s+\d+\s+\d+/.test(trimmed);
- });
- if(validLines.length > 0){
- debug("[TCode] Found " + validLines.length + " valid limit lines");
- processLimits(validLines);
- }
- }
- }, 100); // 100ms debounce
- } catch(e) {
- debug("[TCode] Error processing device response: " + e);
- }
- }
- function setPendingFalse(){ pending = false; }
- function loadCurrentLimits(){
- if(pending){ return -1; }
- pending = true;
- if(serialConnected){
- console.log("[TCode] Requesting device limits with D2 command...");
- sendTCode("D2" + '\n');
- }
- setPendingFalse();
- }
- function onClick(event) {
- if(!mouseEnabled){ return -1; }
- if(event.which == 2){
- var axis = "L0";
- if(AXIS[axis] && AXIS[axis].altLimits != null){ setLimits(AXIS[axis].altLimits[0], AXIS[axis].altLimits[1], axis); }
- }
- }
- function onScroll(event) {
- if(!mouseEnabled){ return -1; }
- if(!scrollWheelEnabled){ return -1; } // Only allow scroll when minKey or initialKey is held
- var axis = "L0";
- if(AXIS[axis].limits == null){ loadCurrentLimits(); return -1; }
- if (event.deltaY >= 0) {
- if(adjustMin){ AXIS[axis].limits[0] = +AXIS[axis].limits[0] - 250; } else{ AXIS[axis].limits[1] = +AXIS[axis].limits[1] - 250; }
- }else if (event.deltaY < 0){
- if(adjustMin){ AXIS[axis].limits[0] = +AXIS[axis].limits[0] + 250; } else{ AXIS[axis].limits[1] = +AXIS[axis].limits[1] + 250; }
- }
- if ( AXIS[axis].limits[0] > AXIS[axis].limits[1] ){
- if(adjustMin){ AXIS[axis].limits[1] = AXIS[axis].limits[0]; } else{ AXIS[axis].limits[0] = AXIS[axis].limits[1]; }
- }
- if( AXIS[axis].limits[1] < 0){ AXIS[axis].limits[1] = 0; } else if( AXIS[axis].limits[1] > 9999){ AXIS[axis].limits[1] = 9999; }
- if( AXIS[axis].limits[0] < 0){ AXIS[axis].limits[0] = 0; } else if( AXIS[axis].limits[0] > 9999){ AXIS[axis].limits[0] = 9999; }
- setLimits(AXIS[axis].limits[0], AXIS[axis].limits[1], axis);
- }
- function keyDown(event){
- if(pendingKey == null){
- switch(event.key){
- case settings.minKey:
- adjustMin = true;
- scrollWheelEnabled = true;
- break;
- case settings.initialKey:
- setInitials();
- scrollWheelEnabled = true;
- break;
- case settings.settingsKey:
- toggleMenu();
- break;
- }
- }else{ setKey(event.key); }
- }
- function keyUp(event){
- if(event.key === settings.minKey || event.key === settings.initialKey){
- adjustMin = false;
- scrollWheelEnabled = false;
- }
- }
- function hideOverlay(){ try{ document.querySelector('#overlay').hidden = "true"; }catch{ return ""; } }
- function createOverlay(text){
- var video = document.querySelector("#VideoJsPlayer_html5_api");
- if(video){
- video = video.parentNode;
- var overlayElement = document.createElement('div');
- overlayElement.setAttribute('id', 'overlay');
- 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;";
- overlayElement.innerHTML = "<h2></h2>";
- video.appendChild(overlayElement);
- show(text);
- }else{ setTimeout(show, 500, text); }
- }
- function show(text){
- var overlay = document.querySelector('#overlay');
- if(!overlay){ createOverlay(text); }
- else{ overlay.childNodes[0].innerText = text; overlay.removeAttribute("hidden"); setTimeout(hideOverlay, 1000); }
- }
- function limits2socket(axis=""){
- function sendAxis2socket(axis){
- if(AXIS[axis] && AXIS[axis].limits){
- sendTCode("$" + axis + "-" + AXIS[axis].limits[0].toString().padStart(4, '0') + "-" + AXIS[axis].limits[1].toString().padStart(4, '0') + '\n');
- }
- }
- if(axis == ""){ for(var thisAxis in AXIS){ sendAxis2socket(thisAxis); } } else{ sendAxis2socket(axis); }
- }
- function setLimits(min, max, axis="L0", save=true){
- show(axis + ": " + min + " - " + max);
- if(!AXIS[axis]){ return -1; }
- if(AXIS[axis].limits == null){ AXIS[axis].limits = new Array(); }
- AXIS[axis].limits[0] = min; AXIS[axis].limits[1] = max;
- if(pending){ return -1; }
- if(serialConnected && save){
- pending = true; limits2socket(axis); setPendingFalse();
- }
- }
- function init(){
- document.addEventListener('wheel', onScroll, false);
- document.addEventListener('auxclick', onClick, false);
- document.addEventListener('keydown', keyDown, true);
- document.addEventListener('keyup', keyUp, true);
- ["L0","L1","L2","R0","R1","R2"].forEach(ax => initAxis(ax));
- loadCurrentLimits();
- }
- function getSceneId(){ return parseInt(location.href.split('/scenes/')[1]); }
- function main(){
- if(serialConnected){
- loadCurrentLimits();
- // Wait a moment for device limits, then set fallbacks for any missing
- setTimeout(() => {
- ["L0","L1","L2"].forEach(ax => {
- if(AXIS[ax] && (!AXIS[ax].limits || AXIS[ax].limits == null)){
- console.log(`[TCode] No limits received for ${ax}, using fallback: 0 - 9999`);
- AXIS[ax].limits = [0, 9999];
- AXIS[ax].altLimits = [0, 9999];
- }
- });
- }, 1000);
- ["L0","L1","L2","R0","R1","R2"].forEach(ax => centerAxis(ax));
- fetchSceneInfo(getSceneId());
- waitForVideoPlayer();
- }else{ setTimeout(main, 500); }
- }
- function cleanUpOptions(list){
- var options = list.childNodes;
- for(var i=0;i<options.length;i++){
- if(!options[i]){ return -1; }
- var type = options[i].value.replace(/\.funscript/, '').split('.');
- switch(type[type.length-1]){
- case "sway": case "surge": case "twist": case "pitch": case "roll":
- options[i].parentNode.removeChild(options[i]); break;
- }
- }
- }
- function waitForPageChange(){
- var chosenScript = document.querySelector('#stash-interactive-tools-select-funscripts');
- if(chosenScript){ chosenScript.addEventListener('change', fetchAllFunscripts); cleanUpOptions(chosenScript); }
- if(location.href == lastPage){ setTimeout(waitForPageChange, 500); return -1; }
- lastPage = location.href;
- scriptList = null;
- // Reset ALL axis data when changing videos
- for(var axis in AXIS){
- AXIS[axis].index = 0;
- AXIS[axis].start = 0;
- AXIS[axis].end = 0;
- AXIS[axis].scriptLoaded = false;
- AXIS[axis].acts = null;
- // Keep limits and altLimits - these come from the device
- }
- if(location.href.indexOf('/scenes/') != -1){
- init(); mouseEnabled = true; main();
- }else{ mouseEnabled = false; videoPlayerLoaded = false; }
- setTimeout(waitForPageChange, 500);
- }
- waitForPageChange();
Advertisement
Add Comment
Please, Sign In to add comment