diff --git a/index.html b/index.html index aeae281..8cb3dc8 100644 --- a/index.html +++ b/index.html @@ -29,6 +29,7 @@ + diff --git a/js/minipaint.js b/js/minipaint.js index 9495ae8..725eeb2 100644 --- a/js/minipaint.js +++ b/js/minipaint.js @@ -1,4 +1,14 @@ //seCKsBzKNhggbcp2XPphkYDv +Hooks.once('init', () => { + game.settings.register('minipaint', 'stabilityAiApiKey', { + name: "Stability AI API Key", + hint: "Enter your Stability AI API key here. You can get your API key from https://platform.stability.ai/. Note that you have 50 free uses per month.", + scope: 'client', + config: true, + type: String, + default: "", + }); +}); let minipaintDoc; Hooks.once('init', () => { @@ -595,3 +605,307 @@ async function removeBackgroundAndAddLayer() { }, "image/png"); } + +async function applySketchEffect() { + const apiKey = game.settings.get('minipaint', 'stabilityAiApiKey'); + if (!apiKey) { + ui.notifications.error("API key for Stability AI is not set. Please configure it in the module settings."); + return; + } + + let prompt = await new Promise((resolve) => { + new Dialog({ + title: "Enter Prompt for Sketch Effect", + content: `
`, + buttons: { + ok: { + label: "Apply", + callback: (html) => resolve(html.find('#sketch-prompt').val()) + }, + cancel: { + label: "Cancel", + callback: () => resolve(null) + } + }, + default: "ok", + }).render(true); + }); + + if (!prompt) { + ui.notifications.warn("Sketch effect cancelled."); + return; + } + + try { + const iframe = document.getElementById('myFrame'); + const minipaintCanvas = iframe.contentWindow.document.querySelector('#canvas_minipaint'); + + if (!minipaintCanvas) { + throw new Error("Could not find the miniPaint canvas."); + } + + const blob = await new Promise(resolve => minipaintCanvas.toBlob(resolve, "image/png")); + if (!blob) { + throw new Error("Failed to create a Blob from the canvas."); + } + + const formData = new FormData(); + formData.append("image", blob); + formData.append("prompt", prompt); + formData.append("control_strength", "0.7"); + formData.append("output_format", "png"); + + const response = await fetch("https://api.stability.ai/v2beta/stable-image/control/sketch", { + method: "POST", + headers: { + "Authorization": `Bearer ${apiKey}`, + "Accept": "application/json" + }, + body: formData, + }); + + if (!response.ok) { + throw new Error(`${response.status}: ${response.statusText}`); + } + + const responseData = await response.json(); + console.log("API Response Data:", responseData); + + // Check if the image is returned in the response + if (responseData.image) { + const base64String = responseData.image; + + // Convert the base64 string to an Image object + const processedImage = new Image(); + processedImage.src = `data:image/png;base64,${base64String}`; + + processedImage.onload = () => { + const Layers = iframe.contentWindow.Layers; + const new_layer = { + name: "Sketch Effect Layer", + type: 'image', + data: processedImage, + width: processedImage.naturalWidth || processedImage.width, + height: processedImage.naturalHeight || processedImage.height, + width_original: processedImage.naturalWidth || processedImage.width, + height_original: processedImage.naturalHeight || processedImage.height, + }; + Layers.insert(new_layer); + + ui.notifications.info("Sketch effect applied and new layer added successfully."); + }; + } else { + throw new Error("No image returned by the API."); + } + + } catch (error) { + console.error("Error applying sketch effect:", error); + ui.notifications.error("Failed to apply the sketch effect. Check console for details."); + } +} +async function removeBackgroundUsingStabilityAI() { + const iframe = document.getElementById('myFrame'); + const minipaintCanvas = iframe.contentWindow.document.querySelector('#canvas_minipaint'); + + if (!minipaintCanvas) { + ui.notifications.error("Could not find the miniPaint canvas."); + return; + } + + // Convert the canvas content to a Blob + minipaintCanvas.toBlob(async (blob) => { + if (!blob) { + ui.notifications.error("Failed to create a Blob from the canvas."); + return; + } + + try { + const apiKey = game.settings.get('minipaint', 'stabilityAiApiKey'); + + if (!apiKey) { + ui.notifications.error("API key for Stability AI is not set. Please configure it in the module settings."); + return; + } + + // Prepare the form data + const formData = new FormData(); + formData.append("image", blob); + formData.append("output_format", "png"); // You can change this to "webp" if needed + + // Send the request to the Stability AI API + const response = await fetch("https://api.stability.ai/v2beta/stable-image/edit/remove-background", { + method: "POST", + headers: { + "Authorization": `Bearer ${apiKey}`, + "Accept": "application/json", + }, + body: formData, + }); + + if (!response.ok) { + throw new Error(`${response.status}: ${response.statusText}`); + } + + const responseData = await response.json(); + + if (!responseData.image) { + throw new Error("No image returned by the API."); + } + + // Convert the base64 string to an Image object + const processedImage = new Image(); + processedImage.src = `data:image/png;base64,${responseData.image}`; + + // Add the processed image as a new layer + processedImage.onload = () => { + const Layers = iframe.contentWindow.Layers; + const new_layer = { + name: "Removed Background Layer", + type: 'image', + data: processedImage, + width: processedImage.naturalWidth || processedImage.width, + height: processedImage.naturalHeight || processedImage.height, + width_original: processedImage.naturalWidth || processedImage.width, + height_original: processedImage.naturalHeight || processedImage.height, + }; + Layers.insert(new_layer); + + ui.notifications.info("Background removed and new layer added successfully."); + }; + + } catch (error) { + console.error("Error applying background removal effect:", error); + ui.notifications.error("Failed to remove the background. Check console for details."); + } + }, "image/png"); +} + +async function searchAndReplace() { + const iframe = document.getElementById('myFrame'); + const minipaintCanvas = iframe.contentWindow.document.querySelector('#canvas_minipaint'); + + if (!minipaintCanvas) { + ui.notifications.error("Could not find the miniPaint canvas."); + return; + } + + const { prompt, searchPrompt } = await new Promise((resolve) => { + let formContent = ` +
+ + + + +
+ `; + + new Dialog({ + title: "Search and Replace", + content: formContent, + buttons: { + yes: { + label: "OK", + callback: (html) => resolve({ + prompt: html.find('#promptInput').val(), + searchPrompt: html.find('#searchPromptInput').val(), + }), + }, + no: { + label: "Cancel", + callback: () => resolve({ prompt: null, searchPrompt: null }), + }, + }, + default: "yes", + }).render(true); + }); + + if (!prompt || !searchPrompt) { + ui.notifications.error("Prompt or search prompt cannot be empty."); + return; + } + + // Convert the canvas content to a Blob + minipaintCanvas.toBlob(async (blob) => { + if (!blob) { + ui.notifications.error("Failed to create a Blob from the canvas."); + return; + } + + try { + const apiKey = game.settings.get('minipaint', 'stabilityAiApiKey'); + + if (!apiKey) { + ui.notifications.error("API key for Stability AI is not set. Please configure it in the module settings."); + return; + } + + const formData = new FormData(); + formData.append("image", blob); + formData.append("prompt", prompt); + formData.append("search_prompt", searchPrompt); + formData.append("output_format", "png"); // You can change this to "webp" if needed + + // Send the request to the Stability AI API + const response = await fetch("https://api.stability.ai/v2beta/stable-image/edit/search-and-replace", { + method: "POST", + headers: { + "Authorization": `Bearer ${apiKey}`, + "Accept": "application/json", + }, + body: formData, + }); + + if (!response.ok) { + throw new Error(`${response.status}: ${response.statusText}`); + } + + const responseData = await response.json(); + + if (!responseData.image) { + throw new Error("No image returned by the API."); + } + + // Convert the base64 string to an Image object + const processedImage = new Image(); + processedImage.src = `data:image/png;base64,${responseData.image}`; + + // Add the processed image as a new layer + processedImage.onload = () => { + const Layers = iframe.contentWindow.Layers; + const new_layer = { + name: "Search and Replace Layer", + type: 'image', + data: processedImage, + width: processedImage.naturalWidth || processedImage.width, + height: processedImage.naturalHeight || processedImage.height, + width_original: processedImage.naturalWidth || processedImage.width, + height_original: processedImage.naturalHeight || processedImage.height, + }; + Layers.insert(new_layer); + + ui.notifications.info("Search and Replace applied and new layer added successfully."); + }; + + } catch (error) { + console.error("Error applying search and replace effect:", error); + ui.notifications.error("Failed to apply the search and replace effect. Check console for details."); + } + }, "image/png"); +} +function open_tokenframe() { + // Access the miniPaint iframe and its FileOpen function + var miniPaint = document.getElementById('myFrame').contentWindow; + var miniPaint_FileOpen = miniPaint.FileOpen; + + // Fetch the JSON file + window.fetch("modules/minipaint/images/tokenframe.json").then(function(response) { + return response.json(); + }).then(function(json) { + // Load the JSON data into miniPaint + miniPaint_FileOpen.load_json(json, false); + console.log("JSON file loaded successfully."); + }).catch(function(ex) { + alert('Sorry, image could not be loaded.'); + console.error("Error loading JSON file:", ex); + }); +} \ No newline at end of file diff --git a/module.json b/module.json index ff117f3..52f3bbb 100644 --- a/module.json +++ b/module.json @@ -2,7 +2,7 @@ "name": "minipaint", "title": "miniPaint", "description": "Adds a button in the Tile Controls to open miniPaint for editing Tiles, Paint with a drawing tablet and more. ", - "version": "1.2.3", + "version": "1.3", "author": "DMKal", "minimumCoreVersion": "11", "compatibleCoreVersion": "11", @@ -29,5 +29,5 @@ "url": "https://github.com/tirzah2/minipaint", "readme": "https://github.com/tirzah2/minipaint/README.md", "manifest": "https://github.com/tirzah2/minipaint/releases/latest/download/module.json", - "download": "https://github.com/tirzah2/minipaint/releases/download/1.2.3/module.zip" + "download": "https://github.com/tirzah2/minipaint/releases/download/1.3/module.zip" } diff --git a/styles/style2.css b/styles/style2.css index e14a275..4ddc3e6 100644 --- a/styles/style2.css +++ b/styles/style2.css @@ -46,3 +46,31 @@ width: unset !important; height: 100%; border: 0; } + +.sidebar_left { + width: 75px !important; + min-width: 75px !important; + align-content: flex-end !important; +} +#myFrame .sidebar_left { + width: 75px !important; + min-width: 75px !important; + align-content: flex-end !important; +} + +.minpaint .sidebar_left { + width: 75px !important; + min-width: 75px !important; + align-content: flex-end !important; +} + +.tools_container .sidebar_left { + width: 75px !important; + min-width: 75px !important; + align-content: flex-end !important; +} +#tools_container .sidebar_left { + width: 75px !important; + min-width: 75px !important; + align-content: flex-end !important; +} \ No newline at end of file diff --git a/templates/minipaint.html b/templates/minipaint.html index 30a9239..97484bf 100644 --- a/templates/minipaint.html +++ b/templates/minipaint.html @@ -40,7 +40,103 @@ if (iframe && iframe.contentWindow) { const iframeDocument = iframe.contentWindow.document; - // Find the menu bar element + // test + + const fileMenu = iframeDocument.querySelector('#main_menu_0_0'); + const imageMenu = iframeDocument.querySelector('#main_menu_0_3'); // Adjust ID if necessary + +if (imageMenu) { + // Wait until the Image dropdown is clicked to expand the items + imageMenu.addEventListener('click', () => { + const infoMenuItem = iframeDocument.querySelector('#main_menu_1_0'); // Adjust the ID if necessary to target "Information ..." + + if (infoMenuItem) { + // Create the Pop! menu item + const popMenuItem = iframeDocument.createElement('a'); + popMenuItem.id = "main_menu_pop"; + popMenuItem.role = "menuitem"; + popMenuItem.tabindex = "-1"; + popMenuItem.ariaHaspopup = "false"; + popMenuItem.href = "javascript:void(0)"; + popMenuItem.target = "_self"; + popMenuItem.dataset.level = "70"; + popMenuItem.dataset.index = "pop"; + popMenuItem.innerHTML = ` + Show Players + `; + popMenuItem.onclick = () => window.parent.showCanvasInImagePopout(); + + // Insert the Pop! menu item above the "Information ..." item + infoMenuItem.parentNode.insertBefore(popMenuItem, infoMenuItem); + } + }); +} + + + +if (fileMenu) { + // Wait until the File dropdown is clicked to expand the items + fileMenu.addEventListener('click', () => { + const saveAsMenuItem = iframeDocument.querySelector('#main_menu_1_6'); + const newMenuItem = iframeDocument.querySelector('#main_menu_1_0'); + + if (saveAsMenuItem && newMenuItem) { + // Create New Token menu item + const newTokenMenuItem = iframeDocument.createElement('a'); + newTokenMenuItem.id = "main_menu_new_token"; + newTokenMenuItem.role = "menuitem"; + newTokenMenuItem.tabindex = "-1"; + newTokenMenuItem.ariaHaspopup = "false"; + newTokenMenuItem.href = "javascript:void(0)"; + newTokenMenuItem.target = "_self"; + newTokenMenuItem.dataset.level = "70"; + newTokenMenuItem.dataset.index = "5"; + newTokenMenuItem.innerHTML = ` + New Token + `; + newTokenMenuItem.onclick = () => window.parent.open_tokenframe(); + + // Create Save Token menu item + const saveTokenMenuItem = iframeDocument.createElement('a'); + saveTokenMenuItem.id = "main_menu_save_proto"; + saveTokenMenuItem.role = "menuitem"; + saveTokenMenuItem.tabindex = "-1"; + saveTokenMenuItem.ariaHaspopup = "false"; + saveTokenMenuItem.href = "javascript:void(0)"; + saveTokenMenuItem.target = "_self"; + saveTokenMenuItem.dataset.level = "1"; + saveTokenMenuItem.dataset.index = "10"; + saveTokenMenuItem.innerHTML = ` + Save Token + `; + saveTokenMenuItem.onclick = () => window.parent.replaceActorTexture('prototypeToken'); + + // Create Save Portrait menu item + const savePortraitMenuItem = iframeDocument.createElement('a'); + savePortraitMenuItem.id = "main_menu_save_actor_image"; + savePortraitMenuItem.role = "menuitem"; + savePortraitMenuItem.tabindex = "-1"; + savePortraitMenuItem.ariaHaspopup = "false"; + savePortraitMenuItem.href = "javascript:void(0)"; + savePortraitMenuItem.target = "_self"; + savePortraitMenuItem.dataset.level = "1"; + savePortraitMenuItem.dataset.index = "10"; + savePortraitMenuItem.innerHTML = ` + Save Portrait + `; + savePortraitMenuItem.onclick = () => window.parent.replaceActorTexture('img'); + + // Insert the New Token menu item above the "New" item + newMenuItem.parentNode.insertBefore(newTokenMenuItem, newMenuItem); + + // Insert the new menu items above the "Save As" item + saveAsMenuItem.parentNode.insertBefore(savePortraitMenuItem, saveAsMenuItem); + saveAsMenuItem.parentNode.insertBefore(saveTokenMenuItem, savePortraitMenuItem); + } + }); +} + + const menuBar = iframeDocument.querySelector('.menu_bar'); if (menuBar) { @@ -57,7 +153,6 @@ Token `; - // Browse Foundry Menu Item const loadBrowseMenuItem = iframeDocument.createElement('li'); loadBrowseMenuItem.innerHTML = ` @@ -65,7 +160,6 @@ Foundry `; - // Create the Replace Tile and Replace Token menu items const replaceTileMenuItem = iframeDocument.createElement('li'); replaceTileMenuItem.innerHTML = ` @@ -79,31 +173,6 @@ Token `; - - // Add Save Proto Button - const saveProtoMenuItem = iframeDocument.createElement('li'); - saveProtoMenuItem.innerHTML = ` - - `; - const saveAIMGMenuItem = iframeDocument.createElement('li'); - saveAIMGMenuItem.innerHTML = ` - - `; - const sendTochat = iframeDocument.createElement('li'); - sendTochat.innerHTML = ` - - `; - - // Insert the new menu items at the beginning of the menu bar - menuBar.insertBefore(sendTochat, menuBar.firstChild); - menuBar.insertBefore(saveAIMGMenuItem, menuBar.firstChild); - menuBar.insertBefore(saveProtoMenuItem, menuBar.firstChild); menuBar.insertBefore(replaceTokenMenuItem, menuBar.firstChild); menuBar.insertBefore(replaceTileMenuItem, menuBar.firstChild); menuBar.insertBefore(loadBrowseMenuItem, menuBar.firstChild); @@ -115,54 +184,129 @@ // Attach an event listener to the iframe to run the function once it's loaded document.getElementById('myFrame').addEventListener('load', injectMenuItems); + +function createStyledButton(iframeDocument, text, clickHandler) { + const buttonDiv = iframeDocument.createElement('div'); + buttonDiv.style.width = '65px'; + buttonDiv.style.height = '25px'; + buttonDiv.style.backgroundColor = 'transparent'; + buttonDiv.style.position = 'relative'; + buttonDiv.style.display = 'flex'; + buttonDiv.style.justifyContent = 'center'; + buttonDiv.style.alignItems = 'center'; + buttonDiv.style.marginTop = '5px'; + buttonDiv.style.marginLeft = '5px'; + buttonDiv.style.cursor = 'pointer'; + buttonDiv.style.border = '1px solid #ccc'; + + const buttonText = iframeDocument.createElement('span'); + buttonText.textContent = text; + buttonText.style.color = '#FFFFFF'; + buttonText.style.fontSize = '12px'; + buttonText.style.fontWeight = 'bold'; + buttonText.style.cursor = 'pointer'; + buttonText.style.pointerEvents = 'none'; + + buttonDiv.appendChild(buttonText); + buttonDiv.onclick = clickHandler; + + return buttonDiv; +} +// Function to create a new button with shared styles +function createStyledButton(iframeDocument, text, action) { + const buttonDiv = iframeDocument.createElement('div'); + buttonDiv.style.width = '65px'; + buttonDiv.style.height = '25px'; + buttonDiv.style.backgroundColor = '#464d4f'; + buttonDiv.style.position = 'relative'; + buttonDiv.style.display = 'flex'; + buttonDiv.style.justifyContent = 'center'; + buttonDiv.style.alignItems = 'center'; + buttonDiv.style.marginTop = '5px'; + buttonDiv.style.marginLeft = '5px'; + buttonDiv.style.cursor = 'pointer'; + buttonDiv.style.border = '1px solid #ccc'; // Optional border for visibility + + const buttonText = iframeDocument.createElement('span'); + buttonText.textContent = text; + buttonText.style.color = '#FFFFFF'; + buttonText.style.fontSize = '12px'; + buttonText.style.fontWeight = 'bold'; + buttonText.style.cursor = 'pointer'; + buttonText.style.pointerEvents = 'none'; // Prevent text from blocking clicks + + buttonDiv.appendChild(buttonText); + buttonDiv.onclick = action; + + return buttonDiv; +} + +// Function to replace the element in the iframe function replaceElementInIframe() { const iframe = document.getElementById('myFrame'); - - // Check if iframe and its content are accessible + if (iframe && iframe.contentWindow) { const iframeDocument = iframe.contentWindow.document; - // Use querySelector to find the specific element by its ID or class const animationElement = iframeDocument.querySelector('#animation'); if (animationElement) { - // Create a new div element to replace the original span - const newDiv = iframeDocument.createElement('div'); - newDiv.style.width = '65px'; - newDiv.style.height = '25px'; - newDiv.style.backgroundColor = 'transparent'; - newDiv.style.position = 'relative'; - newDiv.style.display = 'flex'; - newDiv.style.justifyContent = 'center'; - newDiv.style.alignItems = 'center'; - newDiv.style.marginTop = '5px'; - newDiv.style.marginLeft = '5px'; - newDiv.style.cursor = 'pointer'; - newDiv.style.border = '1px solid #ccc'; // Optional border for visibility - - // Add a letter "BG" in the middle of the div - const letterBG = iframeDocument.createElement('span'); - letterBG.textContent = 'BG'; - letterBG.style.color = '#FFFFFF'; - letterBG.style.fontSize = '12px'; - letterBG.style.fontWeight = 'bold'; - letterBG.style.cursor = 'pointer'; - letterBG.style.pointerEvents = 'none'; // Prevent text from blocking clicks - - // Append the letter BG to the new div - newDiv.appendChild(letterBG); - - // Set the onclick event to run the function removeBackgroundAndAddLayer - newDiv.onclick = () => { + // Create label divs + const bgLabel = iframeDocument.createElement('div'); + bgLabel.style.width = '65px'; + bgLabel.style.height = '11px'; + bgLabel.style.backgroundColor = 'transparent'; + bgLabel.style.position = 'relative'; + bgLabel.style.display = 'flex'; + bgLabel.style.justifyContent = 'center'; + bgLabel.style.alignItems = 'center'; + bgLabel.style.marginTop = '5px'; + bgLabel.style.marginLeft = '5px'; + bgLabel.textContent = 'BgRemove'; + + const sketchLabel = iframeDocument.createElement('div'); + sketchLabel.style.width = '65px'; + sketchLabel.style.height = '11px'; + sketchLabel.style.backgroundColor = 'transparent'; + sketchLabel.style.position = 'relative'; + sketchLabel.style.display = 'flex'; + sketchLabel.style.justifyContent = 'center'; + sketchLabel.style.alignItems = 'center'; + sketchLabel.style.marginTop = '5px'; + sketchLabel.style.marginLeft = '5px'; + sketchLabel.textContent = 'StabilityAI'; + + // Create the "BG" button using the reusable function + const bgButton = createStyledButton(iframeDocument, 'BG', () => { window.parent.removeBackgroundAndAddLayer(); - }; + }); + + // Create the "Sketch" button using the reusable function + const sketchButton = createStyledButton(iframeDocument, 'Sketch', () => { + window.parent.applySketchEffect(); + }); - // Replace the old element with the new div - animationElement.parentNode.replaceChild(newDiv, animationElement); + // Create and insert the "BG Remove" button using Stability AI + const bgRemoveButton = createStyledButton(iframeDocument, 'BG', () => { + window.parent.removeBackgroundUsingStabilityAI(); + }); + const srButton = createStyledButton(iframeDocument, 'S&R', () => { + window.parent.searchAndReplace(); + }); + + // Insert the labels and buttons into the DOM in the correct order + animationElement.parentNode.replaceChild(bgLabel, animationElement); + bgLabel.parentNode.insertBefore(bgButton, bgLabel.nextSibling); + bgButton.parentNode.insertBefore(sketchLabel, bgButton.nextSibling); + sketchLabel.parentNode.insertBefore(sketchButton, sketchLabel.nextSibling); + sketchButton.parentNode.insertBefore(bgRemoveButton, sketchButton.nextSibling); + sketchButton.parentNode.insertBefore(srButton, sketchButton.nextSibling); } } } // Attach an event listener to the iframe to run the function once it's loaded document.getElementById('myFrame').addEventListener('load', replaceElementInIframe); + + diff --git a/templates/minipaint.html2 b/templates/minipaint.html2 new file mode 100644 index 0000000..30a9239 --- /dev/null +++ b/templates/minipaint.html2 @@ -0,0 +1,168 @@ +
+ + +
+ + + diff --git a/templates/minipaint.html3 b/templates/minipaint.html3 new file mode 100644 index 0000000..bdfc865 --- /dev/null +++ b/templates/minipaint.html3 @@ -0,0 +1,205 @@ +
+ + +
+ + +