├── requirements.txt
├── __init__.py
├── pyproject.toml
├── .github
└── workflows
│ └── publish.yml
├── js
├── removebg.js
├── magic_wand_manager.js
├── brush_manager.js
├── mask_manager.js
├── mask_painter_manager.js
└── toolbar.js
├── README.md
├── WF-Example
├── final-layers-utilityV10.json
└── Nunchaku-qwen-edit-flux+layers-system.json
├── layer_system_final.py
└── LICENSE
/requirements.txt:
--------------------------------------------------------------------------------
1 | rembg
--------------------------------------------------------------------------------
/__init__.py:
--------------------------------------------------------------------------------
1 | from .layer_system_final import NODE_CLASS_MAPPINGS, NODE_DISPLAY_NAME_MAPPINGS
2 | WEB_DIRECTORY = "./js"
3 | __all__ = ["NODE_CLASS_MAPPINGS", "NODE_DISPLAY_NAME_MAPPINGS", "WEB_DIRECTORY"]
--------------------------------------------------------------------------------
/pyproject.toml:
--------------------------------------------------------------------------------
1 | [project]
2 | name = "ComfyUI-Layers-Utility"
3 | description = "This custom node for ComfyUI provides a powerful and flexible dynamic layering system, similar to what you would find in image editing software like Photoshop."
4 | version = "3.3.1"
5 | license = { file = "LICENSE.txt" }
6 |
7 | [project.urls]
8 | Repository = "https://github.com/tritant/ComfyUI_Layers_Utility"
9 |
10 | [tool.comfy]
11 | PublisherId = "tritant"
12 | DisplayName = "Layers System"
13 | Icon = ""
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 |
32 |
--------------------------------------------------------------------------------
/.github/workflows/publish.yml:
--------------------------------------------------------------------------------
1 | name: Publish to Comfy registry
2 | on:
3 | workflow_dispatch:
4 | push:
5 | branches:
6 | - main
7 | paths:
8 | - "pyproject.toml"
9 |
10 | permissions:
11 | issues: write
12 |
13 | jobs:
14 | publish-node:
15 | name: Publish Custom Node to registry
16 | runs-on: ubuntu-latest
17 | if: ${{ github.repository_owner == 'tritant' }}
18 | steps:
19 | - name: Check out code
20 | uses: actions/checkout@v4
21 | - name: Publish Custom Node
22 | uses: Comfy-Org/publish-node-action@v1
23 | with:
24 | personal_access_token: ${{ secrets.REGISTRY_ACCESS_TOKEN }}
25 |
--------------------------------------------------------------------------------
/js/removebg.js:
--------------------------------------------------------------------------------
1 | export class RemoveBgManager {
2 | constructor(node, maskManager) {
3 | this.node = node;
4 | this.maskManager = maskManager;
5 | this.button = null;
6 | }
7 |
8 | async performRemoveBg() {
9 | const activeLayer = this.node.getActiveLayer();
10 | if (!activeLayer) return;
11 | const layerIndex = activeLayer.index;
12 | const layerName = activeLayer.name;
13 | const previewInfo = this.node.preview_data?.[layerName];
14 | const layerProps = this.node.layer_properties?.[layerName];
15 | const sourceFilename = layerProps?.source_filename;
16 |
17 | if (!sourceFilename) {
18 | alert("Erreur : Unable to find source file name.");
19 | return;
20 | }
21 |
22 | if (this.button) {
23 | this.button.textContent = "processing...";
24 | this.button.disabled = true;
25 | }
26 |
27 | try {
28 | const response = await fetch("/layersystem/remove_bg", {
29 | method: "POST",
30 | headers: { "Content-Type": "application/json" },
31 | body: JSON.stringify({ filename: sourceFilename, layer_index_str: String(layerIndex)}),
32 | });
33 |
34 | if (!response.ok) throw new Error(`Server error : ${await response.text()}`);
35 |
36 | const newMasks = await response.json();
37 | const previewMaskDetails = newMasks.preview_mask_details;
38 | const renderMaskDetails = newMasks.render_mask_details;
39 | const layerProps = this.node.layer_properties[layerName];
40 | layerProps.internal_mask_filename = renderMaskDetails.name;
41 | layerProps.internal_mask_details = renderMaskDetails;
42 | layerProps.internal_preview_mask_details = previewMaskDetails;
43 | layerProps.mask_last_update = Date.now();
44 | this.node.updatePropertiesJSON();
45 |
46 | const previewMaskUrl = new URL("/view", window.location.origin);
47 | previewMaskUrl.searchParams.set("filename", previewMaskDetails.name);
48 | previewMaskUrl.searchParams.set("type", previewMaskDetails.type);
49 | previewMaskUrl.searchParams.set("subfolder", previewMaskDetails.subfolder);
50 |
51 | previewMaskUrl.searchParams.set("t", layerProps.mask_last_update);
52 |
53 | const newMaskImage = new Image();
54 | newMaskImage.crossOrigin = "anonymous";
55 | newMaskImage.src = previewMaskUrl.href;
56 | await new Promise((r, rj) => { newMaskImage.onload = r; newMaskImage.onerror = rj; });
57 |
58 | const maskName = `mask_${activeLayer.index}`;
59 | if (this.node.loaded_preview_images) {
60 | this.node.loaded_preview_images[maskName] = newMaskImage;
61 | }
62 |
63 | this.maskManager.show();
64 | this.node.redrawPreviewCanvas();
65 |
66 | } catch (error) {
67 | console.error("[LayerSystem] Error while removing BG:", error);
68 | } finally {
69 | if (this.button) {
70 | this.button.textContent = "Remove BG";
71 | this.button.disabled = false;
72 | }
73 | }
74 | }
75 | }
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # 겹 Layer System (Dynamic) for ComfyUI
2 |
3 | This custom node for ComfyUI provides a powerful and flexible dynamic layering system, similar to what you would find in image editing software like Photoshop. It allows you to stack multiple images and masks, control blending modes, opacity, and transformations for each layer individually. Real-time preview(beta), position your layers with the mouse.
4 |
5 | This system is built to be intuitive, enabling complex composites directly within your workflow.
6 |
7 | -----
8 |
9 |
10 | https://github.com/user-attachments/assets/643df32d-82e7-451a-99bf-55741b8c6506
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 | https://github.com/user-attachments/assets/38f8afcc-1ac6-4967-b6aa-cd40360a7d56
21 |
22 |
23 |
24 | https://github.com/user-attachments/assets/a0c129e8-a624-49b8-9c36-fed70e3b91a0
25 |
26 |
27 |
28 | https://github.com/user-attachments/assets/d99582e5-0f7d-45b7-9c21-a1f1cfa2835d
29 |
30 |
31 |
32 |
33 | https://github.com/user-attachments/assets/26ae1586-7582-4a72-909d-0e59cdad9fa9
34 |
35 |
36 |
37 | https://github.com/user-attachments/assets/ba1f3f98-6541-40f4-8269-3cfe23dec4a4
38 |
39 |
40 |
41 | https://github.com/user-attachments/assets/db8d28b5-e52e-4ae2-a3de-6ff8ce54fe67
42 |
43 |
44 |
45 |
46 |
47 |
48 |
49 | ## 🎛️ Node Parameters
50 |
51 | The entire system is managed through a single node: **Layer System (Dynamic)**. When you connect an image to a `layer_` input, a new set of controls (widgets) for that layer appears directly in the node's properties panel. A new empty `layer_` and `mask_` input pair is then added automatically.
52 |
53 | ## Per-Layer Controls
54 |
55 | | Parameter | Type | Description |
56 | | :--- | :--- | :--- |
57 | | **Enabled** | Toggle | A master switch to enable or disable the layer entirely. |
58 | | **Up / Down** | Buttons | Moves the layer up or down in the stacking order. |
59 | | **blend_mode** | Combo | Sets the blending mode (`normal`, `multiply`, `screen`, `overlay`, etc.). |
60 | | **opacity** | Number | Controls the opacity of the layer from 0.0 (transparent) to 1.0 (opaque). |
61 | | **Color Adjustments** | Toggle | A collapsible section to show or hide all color-related controls. |
62 | | **Brightness** | Number | Adjusts the overall brightness of the layer (-1.0 to 1.0). |
63 | | **Contrast** | Number | Adjusts the overall contrast of the layer (-1.0 to 1.0). |
64 | | **Saturation** | Number | Controls the color intensity of the layer (0.0 is grayscale, 1.0 is original). |
65 | | **R / G / B** | Number | Adjusts the intensity of the Red, Green, and Blue channels individually. |
66 | | **Invert Mask** | Toggle | Inverts the connected mask (visible only if a mask is connected). |
67 | | **resize_mode** | Combo | Determines how the layer is placed: `stretch`, `fit`, `cover`, or `crop`. |
68 | | **scale** | Number | Scales the layer (visible only in `crop` mode). |
69 | | **offset_x / offset_y** | Number | Controls the X and Y position of the layer (visible only in `crop` mode). |
70 | -----
71 |
72 |
73 | This system allows for building complex, multi-element scenes in a dynamic and non-destructive way.
74 |
--------------------------------------------------------------------------------
/WF-Example/final-layers-utilityV10.json:
--------------------------------------------------------------------------------
1 | {"id":"232abb08-1c43-49f7-b490-63fd2c509d83","revision":0,"last_node_id":269,"last_link_id":388532,"nodes":[{"id":41,"type":"VAEDecode","pos":[490,1150],"size":[185.81666564941406,46],"flags":{"collapsed":true},"order":9,"mode":4,"inputs":[{"localized_name":"samples","name":"samples","type":"LATENT","link":325950},{"localized_name":"vae","name":"vae","type":"VAE","link":325795}],"outputs":[{"localized_name":"IMAGE","name":"IMAGE","type":"IMAGE","links":[325951]}],"title":"[[edit:run]] VAE Decode","properties":{"cnr_id":"comfy-core","ver":"0.3.43","Node name for S&R":"VAEDecode","ue_properties":{"version":"7.1","widget_ue_connectable":{},"input_ue_unconnectable":{}}},"widgets_values":[]},{"id":36,"type":"VAEEncode","pos":[490,1110],"size":[185.0458221435547,46],"flags":{"collapsed":true},"order":6,"mode":4,"inputs":[{"localized_name":"pixels","name":"pixels","type":"IMAGE","link":388532},{"localized_name":"vae","name":"vae","type":"VAE","link":325792}],"outputs":[{"localized_name":"LATENT","name":"LATENT","type":"LATENT","links":[325948]}],"title":"[[edit:run]] VAE Encode","properties":{"cnr_id":"comfy-core","ver":"0.3.43","Node name for S&R":"VAEEncode","ue_properties":{"version":"7.1","widget_ue_connectable":{},"input_ue_unconnectable":{}}},"widgets_values":[]},{"id":37,"type":"NunchakuFluxDiTLoader","pos":[410,360],"size":[330,210],"flags":{},"order":0,"mode":4,"inputs":[{"localized_name":"model_path","name":"model_path","type":"COMBO","widget":{"name":"model_path"},"link":null},{"localized_name":"cache_threshold","name":"cache_threshold","type":"FLOAT","widget":{"name":"cache_threshold"},"link":null},{"localized_name":"attention","name":"attention","type":"COMBO","widget":{"name":"attention"},"link":null},{"localized_name":"cpu_offload","name":"cpu_offload","type":"COMBO","widget":{"name":"cpu_offload"},"link":null},{"localized_name":"device_id","name":"device_id","type":"INT","widget":{"name":"device_id"},"link":null},{"localized_name":"data_type","name":"data_type","type":"COMBO","widget":{"name":"data_type"},"link":null},{"localized_name":"i2f_mode","name":"i2f_mode","shape":7,"type":"COMBO","widget":{"name":"i2f_mode"},"link":null}],"outputs":[{"localized_name":"MODEL","name":"MODEL","type":"MODEL","links":[325914]}],"title":"[[edit:run]] Nunchaku FLUX DiT Loader","properties":{"cnr_id":"ComfyUI-nunchaku","ver":"aee38dd7ee8f88bf5db0a7ce813da67a4f969c88","Node name for S&R":"NunchakuFluxDiTLoader","ue_properties":{"version":"7.1","widget_ue_connectable":{},"input_ue_unconnectable":{}}},"widgets_values":["svdq-int4_r32-flux.1-dev.safetensors",0,"nunchaku-fp16","auto",0,"bfloat16","enabled"]},{"id":39,"type":"VAELoader","pos":[410,780],"size":[330,70],"flags":{},"order":1,"mode":4,"inputs":[{"localized_name":"vae_name","name":"vae_name","type":"COMBO","widget":{"name":"vae_name"},"link":null}],"outputs":[{"localized_name":"VAE","name":"VAE","type":"VAE","links":[325792,325795,325947]}],"title":"[[edit:run]] Load VAE","properties":{"cnr_id":"comfy-core","ver":"0.3.43","Node name for S&R":"VAELoader","ue_properties":{"version":"7.1","widget_ue_connectable":{},"input_ue_unconnectable":{}}},"widgets_values":["ae.sft"]},{"id":38,"type":"NunchakuTextEncoderLoaderV2","pos":[410,610],"size":[330,130],"flags":{},"order":2,"mode":4,"inputs":[{"localized_name":"model_type","name":"model_type","type":"COMBO","widget":{"name":"model_type"},"link":null},{"localized_name":"text_encoder1","name":"text_encoder1","type":"COMBO","widget":{"name":"text_encoder1"},"link":null},{"localized_name":"text_encoder2","name":"text_encoder2","type":"COMBO","widget":{"name":"text_encoder2"},"link":null},{"localized_name":"t5_min_length","name":"t5_min_length","type":"INT","widget":{"name":"t5_min_length"},"link":null}],"outputs":[{"localized_name":"CLIP","name":"CLIP","type":"CLIP","links":[325798]}],"title":"[[edit:run]] Nunchaku Text Encoder Loader V2","properties":{"cnr_id":"ComfyUI-nunchaku","ver":"aee38dd7ee8f88bf5db0a7ce813da67a4f969c88","Node name for S&R":"NunchakuTextEncoderLoaderV2","ue_properties":{"version":"7.1","widget_ue_connectable":{},"input_ue_unconnectable":{}}},"widgets_values":["flux.1","clip_l.safetensors","t5xxl_fp8_e4m3fn.safetensors",512]},{"id":60,"type":"ResampleBandingFix","pos":[410,890],"size":[330,180],"flags":{},"order":8,"mode":4,"inputs":[{"localized_name":"latent","name":"latent","type":"LATENT","link":325949},{"localized_name":"model","name":"model","type":"MODEL","link":325914},{"localized_name":"positive","name":"positive","type":"CONDITIONING","link":325900},{"localized_name":"negative","name":"negative","type":"CONDITIONING","link":325901},{"localized_name":"denoise","name":"denoise","type":"FLOAT","widget":{"name":"denoise"},"link":null},{"localized_name":"sampler","name":"sampler","type":"COMBO","widget":{"name":"sampler"},"link":null},{"localized_name":"scheduler","name":"scheduler","type":"COMBO","widget":{"name":"scheduler"},"link":null}],"outputs":[{"localized_name":"LATENT","name":"LATENT","type":"LATENT","links":[325950]}],"title":"[[edit:run]] 🧽 Resample Banding Fix","properties":{"cnr_id":"remove-banding-artifacts","ver":"1.0.1","Node name for S&R":"ResampleBandingFix","ue_properties":{"version":"7.1","widget_ue_connectable":{},"input_ue_unconnectable":{}}},"widgets_values":[0.22,"euler","beta"]},{"id":71,"type":"LatentPixelScale","pos":[410,1190],"size":[330,150],"flags":{},"order":7,"mode":4,"inputs":[{"localized_name":"samples","name":"samples","type":"LATENT","link":325948},{"localized_name":"vae","name":"vae","type":"VAE","link":325947},{"localized_name":"upscale_model_opt","name":"upscale_model_opt","shape":7,"type":"UPSCALE_MODEL","link":null},{"localized_name":"scale_method","name":"scale_method","type":"COMBO","widget":{"name":"scale_method"},"link":null},{"localized_name":"scale_factor","name":"scale_factor","type":"FLOAT","widget":{"name":"scale_factor"},"link":null},{"localized_name":"use_tiled_vae","name":"use_tiled_vae","type":"BOOLEAN","widget":{"name":"use_tiled_vae"},"link":null}],"outputs":[{"localized_name":"LATENT","name":"LATENT","type":"LATENT","links":[325949]},{"localized_name":"IMAGE","name":"IMAGE","type":"IMAGE","links":null}],"title":"[[edit:run]] Latent Scale (on Pixel Space)","properties":{"cnr_id":"comfyui-impact-pack","ver":"705698faf242851881abd7d1e1774baa3cf47136","Node name for S&R":"LatentPixelScale","ue_properties":{"version":"7.1","widget_ue_connectable":{},"input_ue_unconnectable":{}}},"widgets_values":["lanczos",1.5,true]},{"id":74,"type":"UpscaleImageWithModel","pos":[2520,750],"size":[290.5666809082031,106],"flags":{},"order":11,"mode":4,"inputs":[{"localized_name":"image","name":"image","type":"IMAGE","link":325953},{"localized_name":"model_name","name":"model_name","type":"COMBO","widget":{"name":"model_name"},"link":null},{"localized_name":"upscale_by","name":"upscale_by","type":"FLOAT","widget":{"name":"upscale_by"},"link":null},{"localized_name":"tile_size","name":"tile_size","type":"INT","widget":{"name":"tile_size"},"link":null}],"outputs":[{"localized_name":"IMAGE","name":"IMAGE","type":"IMAGE","links":[388531]}],"title":"[[edit:run]]🖌️ Upscale Image with Model","properties":{"cnr_id":"ComfyUI-NeuralMedia","ver":"067d950b97f07298feca3dfd36409db8370791b4","Node name for S&R":"UpscaleImageWithModel","ue_properties":{"version":"7.1","widget_ue_connectable":{},"input_ue_unconnectable":{}}},"widgets_values":["4x_NMKD-Siax_200k.pth",2.0000000000000004,512]},{"id":72,"type":"PhotoFilmGrain","pos":[2520,360],"size":[290,350],"flags":{},"order":10,"mode":4,"inputs":[{"localized_name":"images","name":"images","type":"IMAGE","link":325951},{"localized_name":"grain_type","name":"grain_type","type":"COMBO","widget":{"name":"grain_type"},"link":null},{"localized_name":"grain_intensity","name":"grain_intensity","type":"FLOAT","widget":{"name":"grain_intensity"},"link":null},{"localized_name":"grain_size","name":"grain_size","type":"FLOAT","widget":{"name":"grain_size"},"link":null},{"localized_name":"saturation_mix","name":"saturation_mix","type":"FLOAT","widget":{"name":"saturation_mix"},"link":null},{"localized_name":"adaptive_grain","name":"adaptive_grain","type":"FLOAT","widget":{"name":"adaptive_grain"},"link":null},{"localized_name":"halation_strength","name":"halation_strength","type":"FLOAT","widget":{"name":"halation_strength"},"link":null},{"localized_name":"vignette_strength","name":"vignette_strength","type":"FLOAT","widget":{"name":"vignette_strength"},"link":null},{"localized_name":"chromatic_aberration","name":"chromatic_aberration","type":"FLOAT","widget":{"name":"chromatic_aberration"},"link":null},{"localized_name":"lens_distortion","name":"lens_distortion","type":"FLOAT","widget":{"name":"lens_distortion"},"link":null}],"outputs":[{"localized_name":"IMAGE","name":"IMAGE","type":"IMAGE","links":[325953]}],"title":"[[edit:run]] 📸 Photo Film Grain","properties":{"cnr_id":"comfyui-advanced-photo-grain","ver":"1.0.1","Node name for S&R":"PhotoFilmGrain","ue_properties":{"version":"7.1","widget_ue_connectable":{},"input_ue_unconnectable":{}}},"widgets_values":["poisson",0.012000000000000004,1,0.22,0,0,0,0,0]},{"id":42,"type":"CLIPTextEncode","pos":[2520,900],"size":[290,250],"flags":{"collapsed":false},"order":5,"mode":4,"inputs":[{"localized_name":"clip","name":"clip","type":"CLIP","link":325798},{"localized_name":"text","name":"text","type":"STRING","widget":{"name":"text"},"link":null}],"outputs":[{"localized_name":"CONDITIONING","name":"CONDITIONING","type":"CONDITIONING","links":[325900,325901]}],"title":"[[edit:run]] CLIP Text Encode (Prompt)","properties":{"cnr_id":"comfy-core","ver":"0.3.43","Node name for S&R":"CLIPTextEncode","ue_properties":{"version":"7.1","widget_ue_connectable":{},"input_ue_unconnectable":{}}},"widgets_values":[""]},{"id":3,"type":"PreviewImage","pos":[1560,360],"size":[950,1270],"flags":{},"order":12,"mode":4,"inputs":[{"localized_name":"images","name":"images","type":"IMAGE","link":388531}],"outputs":[],"title":"[[edit:run]] Preview Image","properties":{"cnr_id":"comfy-core","ver":"0.3.43","Node name for S&R":"PreviewImage","ue_properties":{"version":"7.1","widget_ue_connectable":{},"input_ue_unconnectable":{}}},"widgets_values":[]},{"id":269,"type":"LayerSystem","pos":[750,360],"size":[800,126],"flags":{},"order":4,"mode":0,"inputs":[{"localized_name":"_properties_json","name":"_properties_json","shape":7,"type":"STRING","widget":{"name":"_properties_json"},"link":null},{"localized_name":"_preview_anchor","name":"_preview_anchor","shape":7,"type":"STRING","widget":{"name":"_preview_anchor"},"link":null},{"localized_name":"header_anchor_1","name":"header_anchor_1","shape":7,"type":"STRING","widget":{"name":"header_anchor_1"},"link":null},{"localized_name":"header_anchor_2","name":"header_anchor_2","shape":7,"type":"STRING","widget":{"name":"header_anchor_2"},"link":null},{"localized_name":"header_anchor_3","name":"header_anchor_3","shape":7,"type":"STRING","widget":{"name":"header_anchor_3"},"link":null},{"localized_name":"header_anchor_4","name":"header_anchor_4","shape":7,"type":"STRING","widget":{"name":"header_anchor_4"},"link":null},{"localized_name":"header_anchor_5","name":"header_anchor_5","shape":7,"type":"STRING","widget":{"name":"header_anchor_5"},"link":null},{"localized_name":"header_anchor_6","name":"header_anchor_6","shape":7,"type":"STRING","widget":{"name":"header_anchor_6"},"link":null},{"localized_name":"header_anchor_7","name":"header_anchor_7","shape":7,"type":"STRING","widget":{"name":"header_anchor_7"},"link":null},{"localized_name":"header_anchor_8","name":"header_anchor_8","shape":7,"type":"STRING","widget":{"name":"header_anchor_8"},"link":null},{"localized_name":"header_anchor_9","name":"header_anchor_9","shape":7,"type":"STRING","widget":{"name":"header_anchor_9"},"link":null},{"localized_name":"header_anchor_10","name":"header_anchor_10","shape":7,"type":"STRING","widget":{"name":"header_anchor_10"},"link":null},{"localized_name":"header_anchor_11","name":"header_anchor_11","shape":7,"type":"STRING","widget":{"name":"header_anchor_11"},"link":null}],"outputs":[{"localized_name":"IMAGE","name":"IMAGE","type":"IMAGE","links":[388532]}],"properties":{"cnr_id":"comfyui-layers-utility","ver":"3.1.1","Node name for S&R":"LayerSystem"},"widgets_values":["","{\"base\":null,\"layers\":{},\"texts\":[],\"preview_width\":300,\"preview_height\":150,\"toolbar_width\":40}","","","","","","","","","","","",null,null]},{"id":268,"type":"OrchestratorNodeToogle","pos":[2520,1190],"size":[290,96],"flags":{},"order":3,"mode":0,"inputs":[],"outputs":[],"properties":{"cnr_id":"comfyui_custom_switch","ver":"1.5.0","Node name for S&R":"OrchestratorNodeToogle","ue_properties":{"widget_ue_connectable":{},"version":"7.1","input_ue_unconnectable":{}}},"widgets_values":["edit",null,false]}],"links":[[325792,39,0,36,1,"VAE"],[325795,39,0,41,1,"VAE"],[325798,38,0,42,0,"CLIP"],[325900,42,0,60,2,"CONDITIONING"],[325901,42,0,60,3,"CONDITIONING"],[325914,37,0,60,1,"MODEL"],[325947,39,0,71,1,"VAE"],[325948,36,0,71,0,"LATENT"],[325949,71,0,60,0,"LATENT"],[325950,60,0,41,0,"LATENT"],[325951,41,0,72,0,"IMAGE"],[325953,72,0,74,0,"IMAGE"],[388531,74,0,3,0,"IMAGE"],[388532,269,0,36,0,"IMAGE"]],"groups":[],"config":{},"extra":{"ue_links":[],"ds":{"scale":0.7290000000000046,"offset":[-169.80060664654445,-273.7513605624225]},"links_added_by_ue":[]},"version":0.4}
--------------------------------------------------------------------------------
/js/magic_wand_manager.js:
--------------------------------------------------------------------------------
1 | export class MagicWandManager {
2 | constructor(node) {
3 | this.node = node;
4 | this.contextualToolbar = null;
5 | this.activeMaskPreview = null;
6 | this.settings = {
7 | tolerance: 32,
8 | contiguous: true,
9 | fusionMode: 'add'
10 | };
11 | this.createContextualToolbar();
12 | }
13 |
14 | async handleCanvasClick(e) {
15 | this.hideSelectionPreview();
16 | const activeLayer = this.node.getActiveLayer();
17 | if (!activeLayer) return;
18 |
19 | const layerName = activeLayer.name;
20 | const props = this.node.layer_properties[layerName];
21 | const layerImage = this.node.loaded_preview_images[layerName];
22 | const baseImage = this.node.basePreviewImage;
23 | const preview = this.node.previewCanvas;
24 | const toolbar = this.node.toolbar;
25 |
26 | if (!props || !layerImage || !baseImage || !preview || !toolbar) return;
27 |
28 | const previewCanvasScale = this.node.previewCanvasScale || 1.0;
29 | const imageAreaCenterX = toolbar.width + (preview.width - toolbar.width) / 2;
30 | const imageAreaCenterY = preview.height / 2;
31 |
32 | const transformedWidth = layerImage.naturalWidth * props.scale * previewCanvasScale;
33 | const transformedHeight = layerImage.naturalHeight * props.scale * previewCanvasScale;
34 | const centerX = imageAreaCenterX + (props.offset_x * previewCanvasScale);
35 | const centerY = imageAreaCenterY + (props.offset_y * previewCanvasScale);
36 |
37 | const clickX = e.offsetX;
38 | const clickY = e.offsetY;
39 | const dx = clickX - centerX;
40 | const dy = clickY - centerY;
41 |
42 | const angleRad = - (props.rotation || 0) * Math.PI / 180;
43 | const cosA = Math.cos(angleRad);
44 | const sinA = Math.sin(angleRad);
45 | const unrotatedDx = dx * cosA - dy * sinA;
46 | const unrotatedDy = dx * sinA + dy * cosA;
47 |
48 | if (Math.abs(unrotatedDx) > transformedWidth / 2 || Math.abs(unrotatedDy) > transformedHeight / 2) {
49 | return;
50 | }
51 |
52 | const localX = unrotatedDx + transformedWidth / 2;
53 | const localY = unrotatedDy + transformedHeight / 2;
54 |
55 | console.log("--- DIAGNOSTIC BAGUETTE MAGIQUE ---");
56 | console.log(`clickX (e.offsetX): ${clickX}`);
57 | console.log(`preview.width: ${preview.width}`);
58 | console.log(`toolbar.width: ${toolbar.width}`);
59 | console.log(`baseImage.naturalWidth: ${this.node.basePreviewImage.naturalWidth}`);
60 | console.log(`Variable this.node.previewCanvasScale: ${this.node.previewCanvasScale}`);
61 | console.log(`props.scale: ${props.scale}`);
62 | console.log(`props.offset_x: ${props.offset_x}`);
63 | console.log("---------------------------------");
64 |
65 | const finalX = Math.round(localX * (layerImage.naturalWidth / transformedWidth));
66 | const finalY = Math.round(localY * (layerImage.naturalHeight / transformedHeight));
67 |
68 | const applyButton = this.contextualToolbar.querySelector("button");
69 | applyButton.innerText = "Processing...";
70 | applyButton.disabled = true;
71 |
72 | const dataToSend = {
73 | filename: props.source_filename,
74 | details: props.source_details,
75 | x: finalX,
76 | y: finalY,
77 | tolerance: this.settings.tolerance,
78 | contiguous: this.settings.contiguous,
79 | };
80 |
81 | try {
82 | const response = await fetch("/layersystem/magic_wand", {
83 | method: "POST",
84 | headers: { "Content-Type": "application/json" },
85 | body: JSON.stringify(dataToSend),
86 | });
87 | const result = await response.json();
88 |
89 | if (result.success && result.mask_details) {
90 | const maskUrl = new URL("/view", window.location.origin);
91 | maskUrl.searchParams.set("filename", result.mask_details.name);
92 | maskUrl.searchParams.set("type", result.mask_details.type);
93 | maskUrl.searchParams.set("t", Date.now());
94 |
95 | const maskImage = new Image();
96 | maskImage.src = maskUrl.href;
97 | maskImage.onload = () => {
98 | this.activeMaskPreview = maskImage;
99 | this.showSelectionPreview(maskImage, props, layerImage);
100 | };
101 | }
102 | } catch (error) {
103 | console.error("Erreur lors de l'appel à la baguette magique:", error);
104 | } finally {
105 | applyButton.innerText = "Apply mask";
106 | applyButton.disabled = false;
107 | }
108 | }
109 |
110 | showSelectionPreview(maskImage, props, layerImage) {
111 | const overlay = this.node.overlayCanvas;
112 | const preview = this.node.previewCanvas;
113 | if (!overlay || !maskImage || !props || !layerImage) return;
114 |
115 | const ctx = overlay.getContext('2d');
116 | overlay.width = preview.width;
117 | overlay.height = preview.height;
118 | ctx.clearRect(0, 0, overlay.width, overlay.height);
119 |
120 | const tempCanvas = document.createElement('canvas');
121 | const tempCtx = tempCanvas.getContext('2d', { willReadFrequently: true });
122 | tempCanvas.width = maskImage.naturalWidth;
123 | tempCanvas.height = maskImage.naturalHeight;
124 | tempCtx.drawImage(maskImage, 0, 0);
125 | const maskData = tempCtx.getImageData(0, 0, tempCanvas.width, tempCanvas.height);
126 | const highlightData = tempCtx.createImageData(tempCanvas.width, tempCanvas.height);
127 |
128 | for (let i = 0; i < maskData.data.length; i += 4) {
129 | if (maskData.data[i] > 128) {
130 | highlightData.data[i] = 255;
131 | highlightData.data[i + 1] = 0;
132 | highlightData.data[i + 2] = 0;
133 | highlightData.data[i + 3] = 102;
134 | }
135 | }
136 | tempCtx.putImageData(highlightData, 0, 0);
137 |
138 | const previewCanvasScale = this.node.previewCanvasScale || 1.0;
139 | const imageAreaCenterX = this.node.toolbar.width + (preview.width - this.node.toolbar.width) / 2;
140 | const imageAreaCenterY = preview.height / 2;
141 |
142 | const transformedWidth = layerImage.naturalWidth * props.scale * previewCanvasScale;
143 | const transformedHeight = layerImage.naturalHeight * props.scale * previewCanvasScale;
144 | const centerX = imageAreaCenterX + (props.offset_x * previewCanvasScale);
145 | const centerY = imageAreaCenterY + (props.offset_y * previewCanvasScale);
146 | const angleRad = (props.rotation || 0) * Math.PI / 180;
147 |
148 | ctx.save();
149 | ctx.translate(centerX, centerY);
150 | ctx.rotate(angleRad);
151 |
152 | ctx.drawImage(tempCanvas, -transformedWidth / 2, -transformedHeight / 2, transformedWidth, transformedHeight);
153 |
154 | ctx.restore();
155 | }
156 |
157 | hideSelectionPreview() {
158 | const overlay = this.node.overlayCanvas;
159 | if (overlay) {
160 | const ctx = overlay.getContext('2d');
161 | ctx.clearRect(0, 0, overlay.width, overlay.height);
162 | }
163 | }
164 |
165 | async _uploadFile(file, isTemp = true) {
166 | const formData = new FormData();
167 | const type = isTemp ? "temp" : "input";
168 | formData.append("image", file);
169 | formData.append("overwrite", "true");
170 | formData.append("type", type);
171 | const response = await fetch("/upload/image", { method: "POST", body: formData });
172 | if (response.status !== 200) throw new Error(`Upload failed: ${response.status}`);
173 | return await response.json();
174 | }
175 |
176 | createContextualToolbar() {
177 | if (this.contextualToolbar) this.contextualToolbar.remove();
178 | this.contextualToolbar = document.createElement("div");
179 | Object.assign(this.contextualToolbar.style, {
180 | position: 'fixed',
181 | display: 'none',
182 | top: '20px',
183 | left: '20px',
184 | zIndex: '10001',
185 | backgroundColor: 'rgba(40, 40, 40, 0.9)',
186 | border: '1px solid #555',
187 | borderRadius: '8px',
188 | padding: '10px',
189 | alignItems: 'center',
190 | gap: '6px',
191 | fontFamily: 'sans-serif',
192 | fontSize: '14px',
193 | color: 'white',
194 | });
195 |
196 | const toleranceLabel = document.createElement("label");
197 | toleranceLabel.innerText = "Tolerance :";
198 | const toleranceInput = document.createElement("input");
199 | toleranceInput.type = "range";
200 | toleranceInput.min = "0";
201 | toleranceInput.max = "255";
202 | toleranceInput.value = this.settings.tolerance;
203 | toleranceInput.style.width = '80px';
204 | toleranceInput.oninput = (e) => {
205 | this.settings.tolerance = parseInt(e.target.value, 10);
206 | toleranceValue.innerText = this.settings.tolerance;
207 | };
208 | const toleranceValue = document.createElement("span");
209 | toleranceValue.innerText = this.settings.tolerance;
210 | toleranceValue.style.minWidth = "25px";
211 |
212 | const contiguousLabel = document.createElement("label");
213 | contiguousLabel.innerText = "Contigu :";
214 | const contiguousInput = document.createElement("input");
215 | contiguousInput.type = "checkbox";
216 | contiguousInput.checked = this.settings.contiguous;
217 | contiguousInput.onchange = (e) => {
218 | this.settings.contiguous = e.target.checked;
219 | };
220 |
221 | const modeLabel = document.createElement("label");
222 | modeLabel.innerText = "Mode :";
223 | Object.assign(modeLabel.style, { marginLeft: '10px' });
224 |
225 | const modeSelect = document.createElement("select");
226 | modeSelect.innerHTML = `
227 |
228 |
229 |
230 | `;
231 | modeSelect.value = this.settings.fusionMode;
232 | modeSelect.style.backgroundColor = "#333";
233 | modeSelect.style.color = "white";
234 | modeSelect.onchange = (e) => {
235 | this.settings.fusionMode = e.target.value;
236 | };
237 |
238 | const applyButton = document.createElement("button");
239 | applyButton.innerText = "Apply mask";
240 | applyButton.onclick = async () => {
241 | if (!this.activeMaskPreview) {
242 | alert("Aucune sélection à appliquer.");
243 | return;
244 | }
245 | const activeLayer = this.node.getActiveLayer();
246 | if (!activeLayer) return;
247 |
248 | applyButton.innerText = "Processing...";
249 | applyButton.disabled = true;
250 |
251 | try {
252 | const tempCanvas = document.createElement('canvas');
253 | tempCanvas.width = this.activeMaskPreview.naturalWidth;
254 | tempCanvas.height = this.activeMaskPreview.naturalHeight;
255 | tempCanvas.getContext('2d').drawImage(this.activeMaskPreview, 0, 0);
256 | const blob = await new Promise(resolve => tempCanvas.toBlob(resolve, 'image/png'));
257 | const tempFile = new File([blob], `temp_selection_mask.png`, { type: "image/png" });
258 | const newMaskDetails = await this._uploadFile(tempFile, false);
259 |
260 | const props = this.node.layer_properties[activeLayer.name];
261 | const existingMaskFilename = props.internal_mask_filename || null;
262 |
263 | const response = await fetch("/layersystem/apply_mask", {
264 | method: "POST", headers: { "Content-Type": "application/json" },
265 | body: JSON.stringify({
266 | new_mask_details: newMaskDetails,
267 | existing_mask_filename: existingMaskFilename,
268 | fusion_mode: this.settings.fusionMode,
269 | layer_index: activeLayer.index
270 | }),
271 | });
272 | const result = await response.json();
273 |
274 | if (result.success && result.render_mask_details && result.preview_mask_details && result.editor_mask_details) {
275 |
276 | props.internal_mask_filename = result.render_mask_details.name;
277 | props.internal_mask_details = result.render_mask_details;
278 | props.internal_preview_mask_details = result.preview_mask_details;
279 | props.internal_editor_mask_details = result.editor_mask_details;
280 | props.mask_last_update = Date.now();
281 | this.node.updatePropertiesJSON();
282 |
283 | const finalMaskUrl = new URL('/view', window.location.origin);
284 | finalMaskUrl.searchParams.set("filename", result.preview_mask_details.name);
285 | finalMaskUrl.searchParams.set("type", "input");
286 | finalMaskUrl.searchParams.set("t", Date.now());
287 |
288 | const finalMaskImage = new Image();
289 | finalMaskImage.src = finalMaskUrl.href;
290 | await new Promise(r => finalMaskImage.onload = r);
291 |
292 | this.node.loaded_preview_images[activeLayer.name.replace("layer_", "mask_")] = finalMaskImage;
293 |
294 | this.hide();
295 | this.node.toolbar.activeTool = 'mask';
296 | this.node.toolbar.maskManager.show();
297 | this.node.redrawPreviewCanvas();
298 | }
299 | } catch (error) {
300 | console.error("Erreur lors de l'application du masque:", error);
301 | } finally {
302 | applyButton.innerText = "Apply mask";
303 | applyButton.disabled = false;
304 | }
305 | };
306 |
307 | this.contextualToolbar.append(
308 | toleranceLabel, toleranceInput, toleranceValue,
309 | contiguousLabel, contiguousInput,
310 | modeLabel, modeSelect,
311 | applyButton
312 | );
313 | document.body.appendChild(this.contextualToolbar);
314 | }
315 |
316 | show() {
317 | if (!this.contextualToolbar) return;
318 | this.contextualToolbar.style.display = 'flex';
319 | this.positionToolbar();
320 | }
321 |
322 | hide() {
323 | if (!this.contextualToolbar) return;
324 | this.contextualToolbar.style.display = 'none';
325 | this.hideSelectionPreview();
326 | }
327 |
328 | positionToolbar() {
329 | if (!this.node.previewCanvas) return;
330 | const canvasRect = this.node.previewCanvas.getBoundingClientRect();
331 | const toolbarRect = this.contextualToolbar.getBoundingClientRect();
332 | const left = canvasRect.left + (canvasRect.width / 2) - (toolbarRect.width / 2);
333 | const top = canvasRect.top - toolbarRect.height - 2;
334 | this.contextualToolbar.style.left = `${left}px`;
335 | this.contextualToolbar.style.top = `${top}px`;
336 | }
337 | }
--------------------------------------------------------------------------------
/js/brush_manager.js:
--------------------------------------------------------------------------------
1 | export class BrushManager {
2 | constructor(node) {
3 | this.node = node;
4 | this.isDrawing = false;
5 | this.lastPoint = { x: 0, y: 0 };
6 | this.settings = { size: 10, color: '#FFFFFF', mode: 'brush' };
7 |
8 | this.finalDrawingCanvas = document.createElement('canvas');
9 | this.finalDrawingCtx = this.finalDrawingCanvas.getContext('2d');
10 |
11 | this.liveDrawingOverlay = null;
12 | this.liveDrawingCtx = null;
13 |
14 | this.boundHandleMouseEvent = this.handleMouseEvent.bind(this);
15 | this.createSettingsToolbar();
16 | }
17 |
18 | createSettingsToolbar() {
19 |
20 | const styleId = 'ls-brush-toolbar-style';
21 | if (!document.getElementById(styleId)) {
22 | const style = document.createElement('style');
23 | style.id = styleId;
24 |
25 | style.innerHTML = `
26 | .ls-brush-toolbar button.ls-tool-button {
27 | border: 1px solid white;
28 | border-radius: 4px;
29 | background-color: transparent;
30 | transition: background-color 0.2s;
31 | }
32 | .ls-brush-toolbar button.ls-tool-button:not(.active):hover {
33 | background-color: rgba(255, 255, 255, 0.1);
34 | }
35 | .ls-brush-toolbar button.active {
36 | background-color: rgba(100, 180, 255, 0.4);
37 | }
38 | `;
39 | document.head.appendChild(style);
40 | }
41 |
42 | this.toolbar = document.createElement("div");
43 | this.toolbar.className = 'ls-brush-toolbar';
44 | Object.assign(this.toolbar.style, {
45 | position: 'fixed', display: 'none', zIndex: '10002',
46 | backgroundColor: 'rgba(40, 40, 40, 0.9)', border: '1px solid #555',
47 | borderRadius: '8px', padding: '8px', alignItems: 'center',
48 | gap: '6px', color: 'white'
49 | });
50 | this.toolbar.innerHTML = `
51 |
52 |
53 | ${this.settings.size}
54 |
55 |
56 |
57 |
58 |
59 |
60 |
61 | `;
62 | document.body.appendChild(this.toolbar);
63 |
64 | this.toolbar.addEventListener('input', (e) => {
65 | if (e.target.dataset.setting === 'size') {
66 | this.settings.size = parseInt(e.target.value, 10);
67 | this.toolbar.querySelector('span[data-value="size"]').textContent = this.settings.size;
68 | }
69 | if (e.target.dataset.setting === 'color') {
70 | this.settings.color = e.target.value;
71 | }
72 | });
73 | this.toolbar.addEventListener('click', (e) => {
74 | const target = e.target.closest('button');
75 | if (!target) return;
76 |
77 | if (target.dataset.mode) this._updateToolState({ mode: target.dataset.mode });
78 | if (target.dataset.tool === 'eyedropper') this._updateToolState({ tool: 'eyedropper' });
79 | if (target.dataset.action === 'apply') this.finalizeDrawing();
80 | if (target.dataset.action === 'cancel') this.hide();
81 | });
82 | }
83 |
84 | _updateToolState({ mode = null, tool = null }) {
85 | this.isEyedropperActive = (tool === 'eyedropper');
86 | if (mode) {
87 | this.settings.mode = mode;
88 | }
89 |
90 | if (this.isEyedropperActive) {
91 | this.node.previewCanvas.style.cursor = 'copy';
92 | } else {
93 | this.node.previewCanvas.style.cursor = 'crosshair';
94 | }
95 |
96 | this.toolbar.querySelectorAll('.ls-tool-button').forEach(b => b.classList.remove('active'));
97 |
98 | if (this.isEyedropperActive) {
99 | this.toolbar.querySelector('[data-tool="eyedropper"]').classList.add('active');
100 | } else {
101 | this.toolbar.querySelector(`[data-mode="${this.settings.mode}"]`).classList.add('active');
102 | }
103 | }
104 |
105 | activateEyedropper() {
106 | this.isEyedropperActive = true;
107 | }
108 |
109 | pickColor(e) {
110 | const ctx = this.node.previewCanvas.getContext('2d', { willReadFrequently: true });
111 | const pixelData = ctx.getImageData(e.offsetX, e.offsetY, 1, 1).data;
112 | const hexColor = `#${("00" + pixelData[0].toString(16)).slice(-2)}${("00" + pixelData[1].toString(16)).slice(-2)}${("00" + pixelData[2].toString(16)).slice(-2)}`;
113 |
114 | this.settings.color = hexColor;
115 | this.toolbar.querySelector('input[data-setting="color"]').value = hexColor;
116 |
117 | this.isEyedropperActive = false;
118 | this.settings.mode = 'brush';
119 | this._updateToolState({ mode: 'brush' });
120 | }
121 |
122 | show() {
123 | if (this.liveDrawingOverlay) {
124 | this.liveDrawingOverlay.remove();
125 | this.liveDrawingOverlay = null;
126 | this.liveDrawingCtx = null;
127 | }
128 | this.activeLayer = this.node.getActiveLayer();
129 | if (!this.activeLayer) {
130 | alert("Please select a layer to draw on.");
131 | if (this.node.toolbar.activeTool === 'brush') this.node.toolbar.activeTool = null;
132 | this.node.refreshUI();
133 | return;
134 | }
135 |
136 | const layerImage = this.node.loaded_preview_images[this.activeLayer.name];
137 | if (!layerImage || !layerImage.naturalWidth) return;
138 |
139 | this.finalDrawingCanvas.width = layerImage.naturalWidth;
140 | this.finalDrawingCanvas.height = layerImage.naturalHeight;
141 | this.finalDrawingCtx.clearRect(0, 0, this.finalDrawingCanvas.width, this.finalDrawingCanvas.height);
142 |
143 | const preview = this.node.previewCanvas;
144 | const container = preview.parentElement;
145 | if (!container) return;
146 |
147 | this.liveDrawingOverlay = document.createElement('canvas');
148 |
149 | Object.assign(this.liveDrawingOverlay.style, {
150 | position: 'absolute', top: '0', left: '0',
151 | zIndex: '10001', pointerEvents: 'auto',
152 | width: '100%', height: '100%'
153 | });
154 |
155 | this.liveDrawingOverlay.width = preview.width;
156 | this.liveDrawingOverlay.height = preview.height;
157 | this.liveDrawingCtx = this.liveDrawingOverlay.getContext('2d');
158 |
159 | container.appendChild(this.liveDrawingOverlay);
160 |
161 | this.liveDrawingOverlay.addEventListener('mousedown', this.boundHandleMouseEvent);
162 | this.liveDrawingOverlay.addEventListener('mousemove', this.boundHandleMouseEvent);
163 | this.liveDrawingOverlay.addEventListener('mouseup', this.boundHandleMouseEvent);
164 | this.liveDrawingOverlay.addEventListener('mouseleave', this.boundHandleMouseEvent);
165 |
166 | this.toolbar.style.display = 'flex';
167 | this._updateToolState({ mode: 'brush' });
168 | this.positionToolbar();
169 | }
170 |
171 | hide() {
172 | this.toolbar.style.display = 'none';
173 |
174 | if (this.liveDrawingOverlay) {
175 | this.liveDrawingOverlay.style.cursor = 'default';
176 | this.liveDrawingOverlay.removeEventListener('mousedown', this.boundHandleMouseEvent);
177 | this.liveDrawingOverlay.removeEventListener('mousemove', this.boundHandleMouseEvent);
178 | this.liveDrawingOverlay.removeEventListener('mouseup', this.boundHandleMouseEvent);
179 | this.liveDrawingOverlay.removeEventListener('mouseleave', this.boundHandleMouseEvent);
180 | this.liveDrawingOverlay.remove();
181 | this.liveDrawingOverlay = null;
182 | this.liveDrawingCtx = null;
183 | }
184 | if (this.node.toolbar.activeTool === 'brush') {
185 | this.node.toolbar.activeTool = null;
186 | this.node.refreshUI();
187 | }
188 | }
189 |
190 | handleMouseEvent(e) {
191 | this.liveDrawingOverlay.style.cursor = 'crosshair';
192 | const mainCanvasRect = this.node.previewCanvas.getBoundingClientRect();
193 | const zoom = app.canvas.ds.scale || 1;
194 | const clickX_on_main_canvas = (e.clientX - mainCanvasRect.left) / zoom;
195 | const clickY_on_main_canvas = (e.clientY - mainCanvasRect.top) / zoom;
196 |
197 | if (e.type === 'mousedown' && this.node.toolbar.isClickOnToolbar(clickX_on_main_canvas, clickY_on_main_canvas)) {
198 | this.node.toolbar.handleClick(e, clickX_on_main_canvas, clickY_on_main_canvas);
199 | return;
200 | }
201 |
202 | const activeLayer = this.node.getActiveLayer();
203 | if (!activeLayer) return;
204 |
205 | if (this.isEyedropperActive) {
206 | this.liveDrawingOverlay.style.cursor = 'copy';
207 | if (e.type === 'mousedown') {
208 | this.pickColor(e);
209 | }
210 | return;
211 | }
212 |
213 |
214 | const props = this.node.layer_properties[activeLayer.name];
215 | const layerImage = this.node.loaded_preview_images[activeLayer.name];
216 | const preview = this.node.previewCanvas;
217 | const toolbar = this.node.toolbar;
218 | const baseImage = this.node.basePreviewImage;
219 | if (!props || !layerImage || !preview || !toolbar || !baseImage) return;
220 |
221 | const previewCanvasScale = (preview.width - toolbar.width) / baseImage.naturalWidth;
222 | const imageAreaCenterX = toolbar.width + (preview.width - toolbar.width) / 2;
223 | const imageAreaCenterY = preview.height / 2;
224 | const transformedWidth = layerImage.naturalWidth * props.scale * previewCanvasScale;
225 | const transformedHeight = layerImage.naturalHeight * props.scale * previewCanvasScale;
226 | const centerX = imageAreaCenterX + (props.offset_x * previewCanvasScale);
227 | const centerY = imageAreaCenterY + (props.offset_y * previewCanvasScale);
228 | const clickX = e.offsetX;
229 | const clickY = e.offsetY;
230 | const dx = clickX - centerX;
231 | const dy = clickY - centerY;
232 | const angleRad = - (props.rotation || 0) * Math.PI / 180;
233 | const unrotatedDx = dx * Math.cos(angleRad) - dy * Math.sin(angleRad);
234 | const unrotatedDy = dx * Math.sin(angleRad) + dy * Math.cos(angleRad);
235 | const localX = unrotatedDx + transformedWidth / 2;
236 | const localY = unrotatedDy + transformedHeight / 2;
237 | const originalX = localX / (transformedWidth / layerImage.naturalWidth);
238 | const originalY = localY / (transformedHeight / layerImage.naturalHeight);
239 | const coords = { x: originalX, y: originalY };
240 |
241 | switch (e.type) {
242 | case 'mousedown':
243 | this.isDrawing = true;
244 | this.lastPoint = coords;
245 | break;
246 | case 'mousemove':
247 | if (this.isDrawing) {
248 | this.draw(coords);
249 | this.lastPoint = coords;
250 | }
251 | break;
252 | case 'mouseup':
253 | case 'mouseleave':
254 | this.isDrawing = false;
255 | break;
256 | }
257 | }
258 |
259 | draw(coords) {
260 | this.finalDrawingCtx.beginPath();
261 | this.finalDrawingCtx.moveTo(this.lastPoint.x, this.lastPoint.y);
262 | this.finalDrawingCtx.lineTo(coords.x, coords.y);
263 | this.finalDrawingCtx.lineCap = 'round';
264 | this.finalDrawingCtx.lineJoin = 'round';
265 | this.finalDrawingCtx.lineWidth = this.settings.size;
266 | if (this.settings.mode === 'eraser') {
267 | this.finalDrawingCtx.globalCompositeOperation = 'destination-out';
268 | } else {
269 | this.finalDrawingCtx.globalCompositeOperation = 'source-over';
270 | this.finalDrawingCtx.strokeStyle = this.settings.color;
271 | }
272 | this.finalDrawingCtx.stroke();
273 | this.updatePreviewOverlay();
274 | }
275 |
276 | updatePreviewOverlay() {
277 | if (!this.liveDrawingCtx) return;
278 | this.liveDrawingCtx.clearRect(0, 0, this.liveDrawingOverlay.width, this.liveDrawingOverlay.height);
279 |
280 | const props = this.node.layer_properties[this.activeLayer.name];
281 | const layerImage = this.node.loaded_preview_images[this.activeLayer.name];
282 | const preview = this.node.previewCanvas;
283 | const toolbar = this.node.toolbar;
284 | const baseImage = this.node.basePreviewImage;
285 | if (!props || !layerImage || !preview || !toolbar || !baseImage) return;
286 |
287 | const previewCanvasScale = (preview.width - toolbar.width) / baseImage.naturalWidth;
288 | const imageAreaCenterX = toolbar.width + (preview.width - toolbar.width) / 2;
289 | const imageAreaCenterY = preview.height / 2;
290 | const transformedWidth = layerImage.naturalWidth * props.scale * previewCanvasScale;
291 | const transformedHeight = layerImage.naturalHeight * props.scale * previewCanvasScale;
292 | const centerX = imageAreaCenterX + (props.offset_x * previewCanvasScale);
293 | const centerY = imageAreaCenterY + (props.offset_y * previewCanvasScale);
294 | const angleRad = (props.rotation || 0) * Math.PI / 180;
295 |
296 | this.liveDrawingCtx.save();
297 | this.liveDrawingCtx.translate(centerX, centerY);
298 | this.liveDrawingCtx.rotate(angleRad);
299 | this.liveDrawingCtx.drawImage(this.finalDrawingCanvas, -transformedWidth / 2, -transformedHeight / 2, transformedWidth, transformedHeight);
300 | this.liveDrawingCtx.restore();
301 | }
302 |
303 | async finalizeDrawing() {
304 | const applyButton = this.toolbar.querySelector('[data-action="apply"]');
305 | applyButton.textContent = "Applying...";
306 | applyButton.disabled = true;
307 | try {
308 | const props = this.node.layer_properties[this.activeLayer.name];
309 | const originalImage = this.node.loaded_preview_images[this.activeLayer.name];
310 | const finalCanvas = document.createElement('canvas');
311 | finalCanvas.width = originalImage.naturalWidth;
312 | finalCanvas.height = originalImage.naturalHeight;
313 | const finalCtx = finalCanvas.getContext('2d');
314 | finalCtx.drawImage(originalImage, 0, 0);
315 |
316 | finalCtx.drawImage(this.finalDrawingCanvas, 0, 0);
317 |
318 | const blob = await new Promise(resolve => finalCanvas.toBlob(resolve, 'image/png'));
319 | const file = new File([blob], props.source_filename, { type: 'image/png' });
320 | const formData = new FormData();
321 | formData.append('image', file);
322 | formData.append('overwrite', 'true');
323 | formData.append('type', 'input');
324 | await fetch('/upload/image', { method: 'POST', body: formData });
325 |
326 | const newPreviewImage = new Image();
327 | newPreviewImage.src = finalCanvas.toDataURL();
328 | await new Promise(resolve => newPreviewImage.onload = resolve);
329 | this.node.loaded_preview_images[this.activeLayer.name] = newPreviewImage;
330 | this.node.redrawPreviewCanvas();
331 |
332 | } catch(e) {
333 | console.error("Failed to apply drawing:", e);
334 | } finally {
335 | applyButton.textContent = "Apply";
336 | applyButton.disabled = false;
337 | this.hide();
338 | }
339 | }
340 |
341 | positionToolbar() {
342 | if (!this.node.previewCanvas) return;
343 | const canvasRect = this.node.previewCanvas.getBoundingClientRect();
344 | this.toolbar.style.left = `${canvasRect.left}px`;
345 | this.toolbar.style.top = `${canvasRect.top - this.toolbar.offsetHeight - 5}px`;
346 | }
347 | }
--------------------------------------------------------------------------------
/js/mask_manager.js:
--------------------------------------------------------------------------------
1 | import { app, ComfyApp } from "../../scripts/app.js";
2 |
3 | function standardizeMaskFromEditor(editorImage) {
4 | const canvas = document.createElement('canvas');
5 | const ctx = canvas.getContext('2d', { willReadFrequently: true });
6 | canvas.width = editorImage.naturalWidth;
7 | canvas.height = editorImage.naturalHeight;
8 | ctx.drawImage(editorImage, 0, 0);
9 | const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
10 | const data = imageData.data;
11 | for (let i = 0; i < data.length; i += 4) {
12 | const alpha = data[i + 3];
13 | const value = (alpha > 128) ? 0 : 255;
14 | data[i] = value;
15 | data[i + 1] = value;
16 | data[i + 2] = value;
17 | data[i + 3] = 255;
18 | }
19 | ctx.putImageData(imageData, 0, 0);
20 | return canvas;
21 | }
22 |
23 | export class MaskManager {
24 | constructor(node) {
25 | this.node = node;
26 | this.contextualToolbar = null;
27 | this.activeLayer = null;
28 | this.returned_image = null;
29 | this.createContextualToolbar();
30 | }
31 |
32 | async _uploadFile(file, isFinalMask = false) {
33 | const formData = new FormData();
34 | const type = isFinalMask ? "input" : "temp";
35 | formData.append("image", file);
36 | formData.append("overwrite", "true");
37 | formData.append("type", type);
38 | const response = await fetch("/upload/image", { method: "POST", body: formData });
39 | if (response.status !== 200) throw new Error(`Upload failed: ${response.status}`);
40 | return await response.json();
41 | }
42 |
43 | async getSourceImageForActiveLayer() {
44 | if (!this.activeLayer) {
45 | throw new Error("Aucun calque actif n'est sélectionné.");
46 | }
47 |
48 | const layerProps = this.node.layer_properties[this.activeLayer.name];
49 | if (!layerProps || !layerProps.source_filename) {
50 | throw new Error("Impossible de trouver le fichier source pour le calque actif.");
51 | }
52 | const filename = layerProps.source_filename;
53 | const details = layerProps.source_details;
54 |
55 | const imageUrl = new URL("/view", window.location.origin);
56 | imageUrl.searchParams.set("filename", filename);
57 | imageUrl.searchParams.set("type", details.type || "input");
58 | imageUrl.searchParams.set("subfolder", details.subfolder || "");
59 | imageUrl.searchParams.set("t", Date.now());
60 |
61 | try {
62 | const img = new Image();
63 | img.src = imageUrl.href;
64 | img.crossOrigin = "anonymous";
65 | await new Promise((resolve, reject) => {
66 | img.onload = resolve;
67 | img.onerror = reject;
68 | });
69 | return img;
70 | } catch (error) {
71 | console.error(`[Layer System] Échec du chargement de l'image source : ${imageUrl.href}`, error);
72 | throw new Error(`Impossible de charger l'image source : ${filename}`);
73 | }
74 | }
75 |
76 | hasActiveMask() {
77 | if (!this.activeLayer) {
78 | return false;
79 | }
80 | const layerProps = this.node.layer_properties[this.activeLayer.name];
81 | return layerProps && layerProps.internal_mask_filename;
82 | }
83 |
84 | async handleCreateMask() {
85 | this.activeLayer = this.node.getActiveLayer();
86 | if (!this.activeLayer) return alert("Erreur : No active layer.");
87 | try {
88 | const sourceImage = await this.getSourceImageForActiveLayer();
89 | if (!sourceImage) throw new Error("Source image not found.");
90 |
91 | const tempNode = LiteGraph.createNode("LoadImage");
92 | ComfyApp.copyToClipspace({ imgs: [sourceImage] });
93 | ComfyApp.clipspace_return_node = tempNode;
94 |
95 | const original_onClipspaceEditorClosed = ComfyApp.onClipspaceEditorClosed;
96 | ComfyApp.onClipspaceEditorClosed = () => {
97 | if (tempNode.imgs && tempNode.imgs[0]) this.returned_image = tempNode.imgs[0];
98 | ComfyApp.onClipspaceEditorClosed = original_onClipspaceEditorClosed;
99 | setTimeout(() => this.handleMaskEditorClose(this.activeLayer), 100);
100 | };
101 | this.hide();
102 | ComfyApp.open_maskeditor();
103 | } catch (error) {
104 | console.error("[Layer System] Error creating mask :", error);
105 | }
106 | }
107 |
108 | async handleEditMask() {
109 | this.activeLayer = this.node.getActiveLayer();
110 | if (!this.activeLayer) return alert("Erreur : No active layer.");
111 |
112 | const layerProps = this.node.layer_properties[this.activeLayer.name];
113 | if (!layerProps || !layerProps.internal_mask_details) {
114 | return alert("This layer does not have an editable internal mask.");
115 | }
116 |
117 | try {
118 | const sourceImage = await this.getSourceImageForActiveLayer();
119 |
120 | if (!sourceImage || !sourceImage.complete || sourceImage.naturalWidth === 0) {
121 | console.warn("[Layer System] The source image was not ready. Waiting for loading...");
122 | if (sourceImage && sourceImage.src) {
123 | await new Promise((resolve, reject) => {
124 | if (sourceImage.complete) { resolve(); }
125 | else { sourceImage.onload = resolve; sourceImage.onerror = reject; }
126 | });
127 | } else {
128 | throw new Error("Source image found but invalid.");
129 | }
130 | }
131 |
132 | const maskDetails = layerProps.internal_mask_details;
133 | const maskUrl = new URL("/view", window.location.origin);
134 | maskUrl.searchParams.set("filename", maskDetails.name);
135 | maskUrl.searchParams.set("type", maskDetails.type);
136 | maskUrl.searchParams.set("subfolder", maskDetails.subfolder);
137 |
138 | const lastUpdate = layerProps.mask_last_update || Date.now();
139 | maskUrl.searchParams.set("t", lastUpdate);
140 |
141 | const rawMaskImage = new Image();
142 | rawMaskImage.crossOrigin = "anonymous";
143 | rawMaskImage.src = maskUrl.href;
144 | const maskLoadingPromise = new Promise((r, rj) => { rawMaskImage.onload = r; rawMaskImage.onerror = rj; });
145 |
146 | const tempNode = LiteGraph.createNode("LoadImage");
147 | ComfyApp.copyToClipspace({ imgs: [sourceImage] });
148 | ComfyApp.clipspace_return_node = tempNode;
149 |
150 | const original_onClipspaceEditorClosed = ComfyApp.onClipspaceEditorClosed;
151 | ComfyApp.onClipspaceEditorClosed = () => {
152 | if (tempNode.imgs && tempNode.imgs[0]) { this.returned_image = tempNode.imgs[0]; }
153 | ComfyApp.onClipspaceEditorClosed = original_onClipspaceEditorClosed;
154 | setTimeout(() => this.handleMaskEditorClose(this.activeLayer), 100);
155 | };
156 |
157 | this.hide();
158 | ComfyApp.open_maskeditor();
159 |
160 | await maskLoadingPromise;
161 |
162 | let attempts = 0;
163 | const maxAttempts = 50;
164 | const checkEditor = () => {
165 | attempts++;
166 | const editorCanvas = document.getElementById('maskCanvas');
167 |
168 | if (editorCanvas && editorCanvas.width > 0 && editorCanvas.style.display !== 'none') {
169 | setTimeout(() => {
170 | let whiteOnBlackMask;
171 | if (maskDetails.name.includes("_rbg_") || maskDetails.name.includes("_render_")) {
172 | const invertedCanvas = document.createElement('canvas');
173 | const ctx = invertedCanvas.getContext('2d');
174 | invertedCanvas.width = rawMaskImage.naturalWidth;
175 | invertedCanvas.height = rawMaskImage.naturalHeight;
176 | ctx.filter = 'invert(1)';
177 | ctx.drawImage(rawMaskImage, 0, 0);
178 | whiteOnBlackMask = invertedCanvas;
179 | } else {
180 | whiteOnBlackMask = standardizeMaskFromEditor(rawMaskImage);
181 | }
182 |
183 | const finalMaskForEditor = document.createElement('canvas');
184 | const finalCtx = finalMaskForEditor.getContext('2d', { willReadFrequently: true });
185 | finalMaskForEditor.width = whiteOnBlackMask.width;
186 | finalMaskForEditor.height = whiteOnBlackMask.height;
187 | finalCtx.drawImage(whiteOnBlackMask, 0, 0);
188 |
189 | const imageData = finalCtx.getImageData(0, 0, finalMaskForEditor.width, finalMaskForEditor.height);
190 | const data = imageData.data;
191 | for (let i = 0; i < data.length; i += 4) {
192 | const luminance = data[i];
193 | if (luminance > 128) {
194 | data[i] = 0; data[i + 1] = 0; data[i + 2] = 0; data[i + 3] = 255;
195 | } else {
196 | data[i + 3] = 0;
197 | }
198 | }
199 | finalCtx.putImageData(imageData, 0, 0);
200 |
201 | const editorCtx = editorCanvas.getContext('2d');
202 | if (editorCtx) {
203 | editorCtx.clearRect(0, 0, editorCanvas.width, editorCanvas.height);
204 | editorCtx.drawImage(finalMaskForEditor, 0, 0, editorCanvas.width, editorCanvas.height);
205 | }
206 | }, 450);
207 |
208 | } else if (attempts < maxAttempts) {
209 | setTimeout(checkEditor, 300);
210 | } else {
211 | console.error("[Layer System] Timeout: The mask editor did not initialize.");
212 | }
213 | };
214 | setTimeout(checkEditor, 300);
215 |
216 | } catch (error) {
217 | console.error("[Layer System] Error re-editing mask :", error);
218 | }
219 | }
220 | async handleMaskEditorClose(activeLayer) {
221 | if (!activeLayer) activeLayer = this.node.getActiveLayer();
222 | if (!activeLayer) return;
223 | const returned_image = this.returned_image;
224 | if (!returned_image) return;
225 | this.returned_image = null;
226 |
227 | try {
228 | if (!returned_image.complete || returned_image.naturalWidth === 0) {
229 | await new Promise((r, rj) => { returned_image.onload = r; returned_image.onerror = rj; });
230 | }
231 |
232 | const rawCanvas = document.createElement('canvas');
233 | rawCanvas.width = returned_image.naturalWidth;
234 | rawCanvas.height = returned_image.naturalHeight;
235 | rawCanvas.getContext('2d').drawImage(returned_image, 0, 0);
236 | const blobToUpload = await new Promise(resolve => rawCanvas.toBlob(resolve, 'image/png'));
237 | const file = new File([blobToUpload], `internal_mask_${activeLayer.index}.png`, { type: "image/png" });
238 | const finalMaskResponse = await this._uploadFile(file, true);
239 |
240 | const layerProps = this.node.layer_properties[activeLayer.name];
241 | layerProps.internal_mask_filename = finalMaskResponse.name;
242 | layerProps.internal_mask_details = finalMaskResponse;
243 | layerProps.mask_last_update = Date.now();
244 | this.node.updatePropertiesJSON();
245 |
246 | const standardizedCanvas = standardizeMaskFromEditor(returned_image);
247 | this.updatePreview(standardizedCanvas.toDataURL());
248 |
249 | const maskName = `mask_${activeLayer.index}`;
250 | if (this.node.loaded_preview_images) {
251 | const previewMaskImage = new Image();
252 | previewMaskImage.src = standardizedCanvas.toDataURL();
253 | await new Promise((r, rj) => { previewMaskImage.onload = r; previewMaskImage.onerror = rj; });
254 | this.node.loaded_preview_images[maskName] = previewMaskImage;
255 | }
256 | } catch (e) {
257 | console.error("[Layer System] Critical error while processing mask.", e);
258 | }
259 |
260 | this.show();
261 | this.node.redrawPreviewCanvas();
262 | this.node.setDirtyCanvas(true, true);
263 | }
264 |
265 | handleDeleteMask() {
266 | this.activeLayer = this.node.getActiveLayer();
267 | if (!this.activeLayer) return;
268 | const layerProps = this.node.layer_properties[this.activeLayer.name];
269 | if (layerProps && layerProps.internal_mask_filename) {
270 | delete layerProps.internal_mask_filename;
271 | delete layerProps.internal_mask_details;
272 | }
273 | const maskName = `mask_${this.activeLayer.index}`;
274 | if (this.node.loaded_preview_images && this.node.loaded_preview_images[maskName]) {
275 | delete this.node.loaded_preview_images[maskName];
276 | }
277 | this.node.redrawPreviewCanvas();
278 | this.updatePreview(null);
279 | this.updateToolbarState();
280 | this.node.graph.setDirtyCanvas(true, true);
281 | this.node.updatePropertiesJSON();
282 | }
283 |
284 | createContextualToolbar() {
285 | if (this.contextualToolbar) this.contextualToolbar.remove();
286 | const toolbar = document.createElement("div");
287 | toolbar.id = 'mask-contextual-toolbar';
288 | Object.assign(toolbar.style, {
289 | position: 'fixed', display: 'none', zIndex: '10001',
290 | backgroundColor: 'rgba(30, 30, 30, 0.8)', border: '1px solid #555',
291 | borderRadius: '8px', padding: '5px', display: 'flex',
292 | alignItems: 'center', gap: '10px',
293 | });
294 |
295 | const buttonContainer = document.createElement("div");
296 | buttonContainer.style.display = 'flex';
297 | buttonContainer.style.gap = '5px';
298 |
299 | const creationContainer = document.createElement("div");
300 | creationContainer.className = 'creation-tools';
301 | creationContainer.style.display = 'flex';
302 |
303 | const editionContainer = document.createElement("div");
304 | editionContainer.className = 'edition-tools';
305 | editionContainer.style.display = 'flex';
306 |
307 | const drawMaskButton = document.createElement("button");
308 | drawMaskButton.innerText = "Draw Mask";
309 | drawMaskButton.onclick = () => this.handleCreateMask();
310 |
311 | const reeditMaskButton = document.createElement("button");
312 | reeditMaskButton.innerText = "Edit mask";
313 | reeditMaskButton.onclick = () => this.handleEditMask();
314 |
315 | const deleteMaskButton = document.createElement("button");
316 | deleteMaskButton.innerText = "Delete mask";
317 | deleteMaskButton.onclick = () => this.handleDeleteMask();
318 |
319 | const removeBgButton = document.createElement("button");
320 | removeBgButton.innerText = "Remove BG";
321 | removeBgButton.onclick = () => {
322 | if (this.node.toolbar.removeBgManager) {
323 | this.node.toolbar.removeBgManager.button = removeBgButton;
324 | this.node.toolbar.removeBgManager.performRemoveBg();
325 | }
326 | };
327 |
328 | creationContainer.append(drawMaskButton);
329 | editionContainer.append(reeditMaskButton, deleteMaskButton);
330 | buttonContainer.append(creationContainer, editionContainer);
331 | buttonContainer.append(removeBgButton);
332 |
333 | [drawMaskButton, reeditMaskButton, deleteMaskButton, removeBgButton].forEach(btn => {
334 | Object.assign(btn.style, {
335 | backgroundColor: '#444', color: 'white', border: '1px solid #666',
336 | padding: '8px 12px', margin: '2px', cursor: 'pointer', borderRadius: '4px'
337 | });
338 | btn.onmouseover = () => btn.style.backgroundColor = '#555';
339 | btn.onmouseout = () => btn.style.backgroundColor = '#444';
340 | });
341 |
342 | const previewContainer = document.createElement("div");
343 | Object.assign(previewContainer.style, {
344 | width: '64px', height: '64px', border: '1px solid #555',
345 | backgroundColor: '#222', flexShrink: '0', padding: '2px'
346 | });
347 | const previewImage = document.createElement("img");
348 | previewImage.id = "ls-mask-preview-image";
349 | Object.assign(previewImage.style, {
350 | width: '100%', height: '100%', objectFit: 'contain', display: 'none'
351 | });
352 | previewContainer.append(previewImage);
353 | toolbar.append(buttonContainer, previewContainer);
354 | document.body.appendChild(toolbar);
355 | this.contextualToolbar = toolbar;
356 | }
357 |
358 | updatePreview(imageUrl) {
359 | const previewEl = document.getElementById("ls-mask-preview-image");
360 | if (previewEl) {
361 | previewEl.src = imageUrl || "";
362 | previewEl.style.display = imageUrl ? "block" : "none";
363 | }
364 | }
365 |
366 | show() {
367 | this.activeLayer = this.node.getActiveLayer();
368 | if (!this.activeLayer) { this.hide(); return; }
369 | this.updateToolbarState();
370 | const layerProps = this.node.layer_properties[this.activeLayer.name];
371 | if (layerProps && layerProps.internal_mask_details) {
372 | const details = layerProps.internal_mask_details;
373 | const url = new URL("/view", window.location.origin);
374 | url.searchParams.append("filename", details.name);
375 | url.searchParams.append("type", details.type);
376 | url.searchParams.append("subfolder", details.subfolder);
377 |
378 | const lastUpdate = layerProps.mask_last_update || Date.now();
379 | url.searchParams.append("t", lastUpdate);
380 |
381 | this.updatePreview(url.href);
382 | } else {
383 | this.updatePreview(null);
384 | }
385 | this.contextualToolbar.style.display = 'flex';
386 | requestAnimationFrame(() => this.positionToolbar());
387 | }
388 |
389 | hide() {
390 | if (this.contextualToolbar) {
391 | this.contextualToolbar.style.display = 'none';
392 | }
393 | }
394 |
395 | updateToolbarState() {
396 | const hasMask = this.hasActiveMask();
397 | this.contextualToolbar.querySelector('.creation-tools').style.display = hasMask ? 'none' : 'flex';
398 | this.contextualToolbar.querySelector('.edition-tools').style.display = hasMask ? 'flex' : 'none';
399 | }
400 |
401 | positionToolbar() {
402 | if (!this.node.previewCanvas) return;
403 | const canvasRect = this.node.previewCanvas.getBoundingClientRect();
404 | const toolbarRect = this.contextualToolbar.getBoundingClientRect();
405 | const left = canvasRect.left + (canvasRect.width / 2) - (toolbarRect.width / 2);
406 | const top = canvasRect.bottom - (toolbarRect.height || 50) - 20;
407 | this.contextualToolbar.style.left = `${left}px`;
408 | this.contextualToolbar.style.top = `${top}px`;
409 | }
410 | }
--------------------------------------------------------------------------------
/js/mask_painter_manager.js:
--------------------------------------------------------------------------------
1 | export class MaskPainterManager {
2 | constructor(node) {
3 | this.node = node;
4 | this.isDrawing = false;
5 | this.lastPoint = { x: 0, y: 0 };
6 | this.settings = {
7 | size: 30,
8 | hardness: 80,
9 | opacity: 100,
10 | mode: 'brush'
11 | };
12 |
13 | this.maskCanvas = document.createElement('canvas');
14 | this.maskCtx = this.maskCanvas.getContext('2d', { willReadFrequently: true });
15 |
16 | this.liveOverlay = null;
17 | this.liveCtx = null;
18 |
19 | this.boundHandleMouseEvent = this.handleMouseEvent.bind(this);
20 | this.createSettingsToolbar();
21 | }
22 |
23 | createSettingsToolbar() {
24 | if (this.toolbar) this.toolbar.remove();
25 |
26 | const styleId = 'ls-mask-painter-style';
27 | if (!document.getElementById(styleId)) {
28 | const style = document.createElement('style');
29 | style.id = styleId;
30 | style.innerHTML = `
31 | .ls-mask-painter-toolbar .ls-tool-button { border: 1px solid white; background-color: transparent; color: white; border-radius: 4px; cursor: pointer; transition: background-color 0.2s; font-size: 18px; width: 32px; height: 32px; padding: 2px; }
32 | .ls-mask-painter-toolbar .ls-tool-button:not(.active):hover { background-color: rgba(255, 255, 255, 0.15); }
33 | .ls-mask-painter-toolbar .ls-tool-button.active { background-color: rgba(100, 180, 255, 0.4); border-color: #64b4ff; }
34 | `;
35 | document.head.appendChild(style);
36 | }
37 |
38 | this.toolbar = document.createElement("div");
39 | this.toolbar.className = 'ls-mask-painter-toolbar';
40 | Object.assign(this.toolbar.style, {
41 | position: 'fixed', display: 'none', zIndex: '10002',
42 | backgroundColor: 'rgba(40, 40, 40, 0.9)', border: '1px solid #555',
43 | borderRadius: '8px', padding: '8px', alignItems: 'center',
44 | gap: '6px', color: 'white', fontFamily: 'sans-serif'
45 | });
46 |
47 | this.toolbar.innerHTML = `
48 |
49 |
50 | ${this.settings.size}
51 |
52 |
53 | ${this.settings.hardness}%
54 |
55 |
56 | ${this.settings.opacity}%
57 |
58 |
59 |
60 |
61 | `;
62 | document.body.appendChild(this.toolbar);
63 |
64 | this.toolbar.querySelector('[data-mode="brush"]').classList.add('active');
65 |
66 | this.toolbar.addEventListener('input', (e) => {
67 | const setting = e.target.dataset.setting;
68 | if (setting) {
69 | this.settings[setting] = parseInt(e.target.value, 10);
70 | const suffix = (setting === 'hardness' || setting === 'opacity') ? '%' : '';
71 | this.toolbar.querySelector(`span[data-value="${setting}"]`).textContent = e.target.value + suffix;
72 | }
73 | });
74 |
75 | this.toolbar.addEventListener('click', (e) => {
76 | const target = e.target.closest('button');
77 | if (!target) return;
78 | if (target.dataset.mode) {
79 | this.settings.mode = target.dataset.mode;
80 | this.toolbar.querySelectorAll('.ls-tool-button').forEach(btn => btn.classList.remove('active'));
81 | target.classList.add('active');
82 | }
83 | if (target.dataset.action === 'apply') this.finalizeDrawing();
84 | if (target.dataset.action === 'cancel') this.hide();
85 | });
86 | }
87 |
88 | async show() {
89 | this.node.toolbar.activeTool = 'mask_painter';
90 | this.activeLayer = this.node.getActiveLayer();
91 | if (!this.activeLayer) {
92 | alert("Please select a layer to paint a mask on.");
93 | return;
94 | }
95 |
96 | const layerImage = this.node.loaded_preview_images[this.activeLayer.name];
97 | if (!layerImage || !layerImage.naturalWidth) return;
98 |
99 | const props = this.node.layer_properties[this.activeLayer.name];
100 | props.enabled = false;
101 | this.node.refreshUI();
102 |
103 | const preview = this.node.previewCanvas;
104 | this.maskCanvas.width = layerImage.naturalWidth;
105 | this.maskCanvas.height = layerImage.naturalHeight;
106 |
107 | this.liveOverlay = document.createElement('canvas');
108 | Object.assign(this.liveOverlay.style, {
109 | position: 'absolute', top: '0', left: '0',
110 | zIndex: '10001', pointerEvents: 'auto', cursor: 'none'
111 | });
112 | this.liveOverlay.width = preview.width;
113 | this.liveOverlay.height = preview.height;
114 | this.liveCtx = this.liveOverlay.getContext('2d');
115 | preview.parentElement.appendChild(this.liveOverlay);
116 |
117 | this.liveOverlay.addEventListener('mousedown', this.boundHandleMouseEvent);
118 | this.liveOverlay.addEventListener('mousemove', this.boundHandleMouseEvent);
119 | this.liveOverlay.addEventListener('mouseup', this.boundHandleMouseEvent);
120 | this.liveOverlay.addEventListener('mouseleave', this.boundHandleMouseEvent);
121 |
122 | this.maskCtx.clearRect(0, 0, this.maskCanvas.width, this.maskCanvas.height);
123 |
124 | if (props.internal_mask_details) {
125 | const details = props.internal_mask_details;
126 | const url = new URL("/view", window.location.origin);
127 | url.searchParams.set("filename", details.name);
128 | url.searchParams.set("type", details.type);
129 | url.searchParams.set("t", Date.now());
130 | const existingMask = new Image();
131 | existingMask.crossOrigin = "anonymous";
132 | existingMask.src = url.href;
133 | await new Promise(resolve => { existingMask.onload = resolve; existingMask.onerror = resolve; });
134 |
135 | const tempCtx = document.createElement('canvas').getContext('2d', { willReadFrequently: true });
136 | tempCtx.canvas.width = this.maskCanvas.width;
137 | tempCtx.canvas.height = this.maskCanvas.height;
138 | tempCtx.drawImage(existingMask, 0, 0, tempCtx.canvas.width, tempCtx.canvas.height);
139 | const imageData = tempCtx.getImageData(0, 0, tempCtx.canvas.width, tempCtx.canvas.height);
140 | const data = imageData.data;
141 |
142 | let hasAlpha = false;
143 | for (let i = 3; i < data.length; i += 4) {
144 | if (data[i] < 255) {
145 | hasAlpha = true;
146 | break;
147 | }
148 | }
149 |
150 | if (hasAlpha) {
151 | for (let i = 0; i < data.length; i += 4) {
152 | data[i + 3] = 255 - data[i + 3];
153 | data[i] = 255; data[i + 1] = 255; data[i + 2] = 255;
154 | }
155 | } else {
156 | for (let i = 0; i < data.length; i += 4) {
157 | data[i + 3] = 255 - data[i];
158 | data[i] = data[i+1] = data[i+2] = 255;
159 | }
160 | }
161 | this.maskCtx.putImageData(imageData, 0, 0);
162 |
163 | } else {
164 | this.maskCtx.fillStyle = 'white';
165 | this.maskCtx.fillRect(0, 0, this.maskCanvas.width, this.maskCanvas.height);
166 | }
167 |
168 | this.updateLivePreview();
169 | this.toolbar.style.display = 'flex';
170 | this.positionToolbar();
171 | }
172 |
173 | drawStamp(point) {
174 | const ctx = this.maskCtx;
175 | const radius = this.settings.size / 2;
176 |
177 | const gradient = ctx.createRadialGradient(point.x, point.y, 0, point.x, point.y, radius);
178 | const hardnessStop = Math.max(0, Math.min(1, this.settings.hardness / 100));
179 |
180 | ctx.save();
181 | ctx.globalAlpha = this.settings.opacity / 100;
182 |
183 | if (this.settings.mode === 'brush') {
184 | gradient.addColorStop(0, 'white');
185 | gradient.addColorStop(hardnessStop, 'white');
186 | gradient.addColorStop(1, 'rgba(255, 255, 255, 0)');
187 | ctx.globalCompositeOperation = 'lighter';
188 | ctx.fillStyle = gradient;
189 | } else {
190 | gradient.addColorStop(0, 'black');
191 | gradient.addColorStop(hardnessStop, 'black');
192 | gradient.addColorStop(1, 'rgba(0, 0, 0, 0)');
193 | ctx.globalCompositeOperation = 'destination-out';
194 | ctx.fillStyle = gradient;
195 | }
196 |
197 | ctx.beginPath();
198 | ctx.arc(point.x, point.y, radius, 0, 2 * Math.PI);
199 | ctx.fill();
200 |
201 | ctx.restore();
202 | }
203 | hide() {
204 | if (this.activeLayer) {
205 | const props = this.node.layer_properties[this.activeLayer.name];
206 | if (props) {
207 | props.enabled = true;
208 | this.node.updatePropertiesJSON();
209 | }
210 | }
211 | this.toolbar.style.display = 'none';
212 | if (this.liveOverlay) {
213 | this.liveOverlay.remove();
214 | this.liveOverlay = null;
215 | this.liveCtx = null;
216 | }
217 | if (this.node.toolbar.activeTool === 'mask_painter') {
218 | this.node.toolbar.activeTool = null;
219 |
220 | }
221 | this.node.refreshUI();
222 | }
223 |
224 | async switchLayer() {
225 | this.hide();
226 | await new Promise(resolve => setTimeout(resolve, 0));
227 | this.show();
228 | }
229 |
230 | async finalizeDrawing() {
231 | const applyButton = this.toolbar.querySelector('[data-action="apply"]');
232 | applyButton.textContent = "Applying...";
233 | applyButton.disabled = true;
234 |
235 | try {
236 | const blob = await new Promise(resolve => this.maskCanvas.toBlob(resolve, 'image/png'));
237 | const file = new File([blob], `temp_alpha_mask_${this.activeLayer.index}.png`, { type: "image/png" });
238 | const formData = new FormData();
239 | formData.append("image", file);
240 | formData.append("overwrite", "true");
241 | formData.append("type", "input");
242 |
243 | let response = await fetch("/upload/image", { method: "POST", body: formData });
244 | const tempAlphaMaskDetails = await response.json();
245 |
246 | response = await fetch("/layersystem/finalize_painter_mask", {
247 | method: "POST",
248 | headers: { "Content-Type": "application/json" },
249 | body: JSON.stringify({
250 | alpha_mask_details: tempAlphaMaskDetails,
251 | layer_index: this.activeLayer.index
252 | }),
253 | });
254 |
255 | if (!response.ok) {
256 | throw new Error(`Server error: ${await response.text()}`);
257 | }
258 | const finalMasks = await response.json();
259 |
260 | const props = this.node.layer_properties[this.activeLayer.name];
261 | props.internal_mask_filename = finalMasks.render_mask_details.name;
262 | props.internal_mask_details = finalMasks.render_mask_details;
263 | props.internal_preview_mask_details = finalMasks.preview_mask_details;
264 | props.mask_last_update = Date.now();
265 | this.node.updatePropertiesJSON();
266 |
267 | const newMaskImage = new Image();
268 | const previewUrl = new URL("/view", window.location.origin);
269 | previewUrl.searchParams.set("filename", finalMasks.preview_mask_details.name);
270 | previewUrl.searchParams.set("type", "input");
271 | previewUrl.searchParams.set("t", props.mask_last_update);
272 | newMaskImage.src = previewUrl.href;
273 |
274 | await new Promise(resolve => newMaskImage.onload = resolve);
275 | this.node.loaded_preview_images[this.activeLayer.name.replace('layer_', 'mask_')] = newMaskImage;
276 |
277 | } catch (e) {
278 | console.error("Failed to apply mask drawing:", e);
279 | } finally {
280 | applyButton.textContent = "Apply Mask";
281 | applyButton.disabled = false;
282 | this.hide();
283 | }
284 | }
285 |
286 | getOriginalCoords(e) {
287 | const props = this.node.layer_properties[this.activeLayer.name];
288 | const layerImage = this.node.loaded_preview_images[this.activeLayer.name];
289 | const preview = this.node.previewCanvas;
290 | const toolbar = this.node.toolbar;
291 | const baseImage = this.node.basePreviewImage;
292 | const previewCanvasScale = (preview.width - toolbar.width) / baseImage.naturalWidth;
293 | const imageAreaCenterX = toolbar.width + (preview.width - toolbar.width) / 2;
294 | const imageAreaCenterY = preview.height / 2;
295 | const transformedWidth = layerImage.naturalWidth * props.scale * previewCanvasScale;
296 | const transformedHeight = layerImage.naturalHeight * props.scale * previewCanvasScale;
297 | const centerX = imageAreaCenterX + (props.offset_x * previewCanvasScale);
298 | const centerY = imageAreaCenterY + (props.offset_y * previewCanvasScale);
299 | const dx = e.offsetX - centerX;
300 | const dy = e.offsetY - centerY;
301 | const angleRad = -(props.rotation || 0) * Math.PI / 180;
302 | const unrotatedDx = dx * Math.cos(angleRad) - dy * Math.sin(angleRad);
303 | const unrotatedDy = dx * Math.sin(angleRad) + dy * Math.cos(angleRad);
304 | const localX = unrotatedDx + transformedWidth / 2;
305 | const localY = unrotatedDy + transformedHeight / 2;
306 | return {
307 | x: localX / (transformedWidth / layerImage.naturalWidth),
308 | y: localY / (transformedHeight / layerImage.naturalHeight)
309 | };
310 | }
311 |
312 | handleMouseEvent(e) {
313 | if (!this.activeLayer) return;
314 |
315 | const mainCanvasRect = this.node.previewCanvas.getBoundingClientRect();
316 | const zoom = app.canvas.ds.scale || 1;
317 | const mouseX = (e.clientX - mainCanvasRect.left) / zoom;
318 | const mouseY = (e.clientY - mainCanvasRect.top) / zoom;
319 | const isOverToolbar = this.node.toolbar.isClickOnToolbar(mouseX, mouseY);
320 |
321 | if (isOverToolbar) {
322 | this.liveOverlay.style.cursor = 'default';
323 | this.updateLivePreview(null);
324 | if (e.type === 'mousedown') {
325 | this.node.toolbar.handleClick(e, mouseX, mouseY);
326 | }
327 | return;
328 | }
329 |
330 | this.liveOverlay.style.cursor = 'none';
331 |
332 | if (e.type === 'mousedown') {
333 | this.isDrawing = true;
334 | const coords = this.getOriginalCoords(e);
335 | this.lastPoint = coords;
336 | this.drawStamp(coords);
337 | }
338 | else if (e.type === 'mousemove') {
339 | if (this.isDrawing) {
340 | const coords = this.getOriginalCoords(e);
341 | const dist = Math.hypot(coords.x - this.lastPoint.x, coords.y - this.lastPoint.y);
342 | const spacing = this.settings.size / 2;
343 |
344 | if (dist >= spacing) {
345 | this.drawStroke(this.lastPoint, coords);
346 | this.lastPoint = coords;
347 | }
348 | }
349 | }
350 | else if (e.type === 'mouseup' || e.type === 'mouseleave') {
351 | this.isDrawing = false;
352 | }
353 |
354 | this.updateLivePreview(e);
355 | }
356 |
357 | drawStroke(from, to) {
358 | const dist = Math.hypot(to.x - from.x, to.y - from.y);
359 | const angle = Math.atan2(to.y - from.y, to.x - from.x);
360 | const step = this.settings.size / 4;
361 | for (let i = 0; i < dist; i += step) {
362 | const x = from.x + (Math.cos(angle) * i);
363 | const y = from.y + (Math.sin(angle) * i);
364 | this.drawStamp({ x, y });
365 | }
366 | this.drawStamp(to);
367 | }
368 |
369 | updateLivePreview(mouseEvent = null) {
370 | if (!this.liveCtx) return;
371 | this.liveCtx.clearRect(0, 0, this.liveOverlay.width, this.liveOverlay.height);
372 |
373 | const tempLayerCanvas = document.createElement('canvas');
374 | tempLayerCanvas.width = this.maskCanvas.width;
375 | tempLayerCanvas.height = this.maskCanvas.height;
376 | const tempLayerCtx = tempLayerCanvas.getContext('2d');
377 |
378 | const layerImage = this.node.loaded_preview_images[this.activeLayer.name];
379 | tempLayerCtx.drawImage(layerImage, 0, 0);
380 | tempLayerCtx.globalCompositeOperation = 'destination-in';
381 | tempLayerCtx.drawImage(this.maskCanvas, 0, 0);
382 |
383 | const props = this.node.layer_properties[this.activeLayer.name];
384 | const preview = this.node.previewCanvas;
385 | const toolbar = this.node.toolbar;
386 | const baseImage = this.node.basePreviewImage;
387 | const previewCanvasScale = (preview.width - toolbar.width) / baseImage.naturalWidth;
388 | const imageAreaCenterX = toolbar.width + (preview.width - toolbar.width) / 2;
389 | const imageAreaCenterY = preview.height / 2;
390 | const transformedWidth = layerImage.naturalWidth * props.scale * previewCanvasScale;
391 | const transformedHeight = layerImage.naturalHeight * props.scale * previewCanvasScale;
392 | const centerX = imageAreaCenterX + (props.offset_x * previewCanvasScale);
393 | const centerY = imageAreaCenterY + (props.offset_y * previewCanvasScale);
394 | const angleRad = (props.rotation || 0) * Math.PI / 180;
395 |
396 | this.liveCtx.save();
397 | this.liveCtx.translate(centerX, centerY);
398 | this.liveCtx.rotate(angleRad);
399 | this.liveCtx.drawImage(tempLayerCanvas, -transformedWidth / 2, -transformedHeight / 2, transformedWidth, transformedHeight);
400 | this.liveCtx.restore();
401 |
402 | if (mouseEvent) {
403 | const previewSize = (this.settings.size / this.maskCanvas.width) * transformedWidth;
404 | this.liveCtx.beginPath();
405 | this.liveCtx.arc(mouseEvent.offsetX, mouseEvent.offsetY, previewSize / 2, 0, 2 * Math.PI);
406 | this.liveCtx.strokeStyle = 'white';
407 | this.liveCtx.lineWidth = 1;
408 | this.liveCtx.setLineDash([2, 2]);
409 | this.liveCtx.stroke();
410 | this.liveCtx.setLineDash([]);
411 | }
412 | }
413 |
414 | positionToolbar() {
415 | if (!this.node.previewCanvas) return;
416 | const canvasRect = this.node.previewCanvas.getBoundingClientRect();
417 | this.toolbar.style.left = `${canvasRect.left}px`;
418 | this.toolbar.style.top = `${canvasRect.top - this.toolbar.offsetHeight - 5}px`;
419 | }
420 | }
--------------------------------------------------------------------------------
/WF-Example/Nunchaku-qwen-edit-flux+layers-system.json:
--------------------------------------------------------------------------------
1 | {"id":"5a4e0d14-2914-4928-aeb6-248672d97568","revision":0,"last_node_id":292,"last_link_id":388592,"nodes":[{"id":287,"type":"AutomaticImageSwitcher","pos":[450,1400],"size":[253.27499389648438,66],"flags":{},"order":22,"mode":0,"inputs":[{"localized_name":"image_1","name":"image_1","shape":7,"type":"IMAGE","link":388576},{"localized_name":"image_2","name":"image_2","shape":7,"type":"IMAGE","link":388577},{"localized_name":"image_3","name":"image_3","shape":7,"type":"IMAGE","link":null}],"outputs":[{"localized_name":"IMAGE","name":"IMAGE","type":"IMAGE","links":[388592]}],"properties":{"cnr_id":"comfyui_custom_switch","ver":"1.5.0","Node name for S&R":"AutomaticImageSwitcher","ue_properties":{"widget_ue_connectable":{},"version":"7.1","input_ue_unconnectable":{}}},"widgets_values":[]},{"id":37,"type":"NunchakuFluxDiTLoader","pos":[410,360],"size":[330,210],"flags":{},"order":0,"mode":4,"inputs":[{"localized_name":"model_path","name":"model_path","type":"COMBO","widget":{"name":"model_path"},"link":null},{"localized_name":"cache_threshold","name":"cache_threshold","type":"FLOAT","widget":{"name":"cache_threshold"},"link":null},{"localized_name":"attention","name":"attention","type":"COMBO","widget":{"name":"attention"},"link":null},{"localized_name":"cpu_offload","name":"cpu_offload","type":"COMBO","widget":{"name":"cpu_offload"},"link":null},{"localized_name":"device_id","name":"device_id","type":"INT","widget":{"name":"device_id"},"link":null},{"localized_name":"data_type","name":"data_type","type":"COMBO","widget":{"name":"data_type"},"link":null},{"localized_name":"i2f_mode","name":"i2f_mode","shape":7,"type":"COMBO","widget":{"name":"i2f_mode"},"link":null}],"outputs":[{"localized_name":"MODEL","name":"MODEL","type":"MODEL","links":[325914]}],"title":"[[edit:flux]] Nunchaku FLUX DiT Loader","properties":{"cnr_id":"ComfyUI-nunchaku","ver":"aee38dd7ee8f88bf5db0a7ce813da67a4f969c88","Node name for S&R":"NunchakuFluxDiTLoader","ue_properties":{"version":"7.1","widget_ue_connectable":{},"input_ue_unconnectable":{}}},"widgets_values":["svdq-int4_r32-flux.1-dev.safetensors",0,"nunchaku-fp16","auto",0,"bfloat16","enabled"]},{"id":38,"type":"NunchakuTextEncoderLoaderV2","pos":[410,610],"size":[330,130],"flags":{},"order":1,"mode":4,"inputs":[{"localized_name":"model_type","name":"model_type","type":"COMBO","widget":{"name":"model_type"},"link":null},{"localized_name":"text_encoder1","name":"text_encoder1","type":"COMBO","widget":{"name":"text_encoder1"},"link":null},{"localized_name":"text_encoder2","name":"text_encoder2","type":"COMBO","widget":{"name":"text_encoder2"},"link":null},{"localized_name":"t5_min_length","name":"t5_min_length","type":"INT","widget":{"name":"t5_min_length"},"link":null}],"outputs":[{"localized_name":"CLIP","name":"CLIP","type":"CLIP","links":[325798]}],"title":"[[edit:flux]] Nunchaku Text Encoder Loader V2","properties":{"cnr_id":"ComfyUI-nunchaku","ver":"aee38dd7ee8f88bf5db0a7ce813da67a4f969c88","Node name for S&R":"NunchakuTextEncoderLoaderV2","ue_properties":{"version":"7.1","widget_ue_connectable":{},"input_ue_unconnectable":{}}},"widgets_values":["flux.1","clip_l.safetensors","t5xxl_fp8_e4m3fn.safetensors",512]},{"id":39,"type":"VAELoader","pos":[410,780],"size":[330,70],"flags":{},"order":2,"mode":4,"inputs":[{"localized_name":"vae_name","name":"vae_name","type":"COMBO","widget":{"name":"vae_name"},"link":null}],"outputs":[{"localized_name":"VAE","name":"VAE","type":"VAE","links":[325792,325795,325947]}],"title":"[[edit:flux]] Load VAE","properties":{"cnr_id":"comfy-core","ver":"0.3.43","Node name for S&R":"VAELoader","ue_properties":{"version":"7.1","widget_ue_connectable":{},"input_ue_unconnectable":{}}},"widgets_values":["ae.sft"]},{"id":60,"type":"ResampleBandingFix","pos":[410,890],"size":[330,180],"flags":{},"order":17,"mode":4,"inputs":[{"localized_name":"latent","name":"latent","type":"LATENT","link":325949},{"localized_name":"model","name":"model","type":"MODEL","link":325914},{"localized_name":"positive","name":"positive","type":"CONDITIONING","link":325900},{"localized_name":"negative","name":"negative","type":"CONDITIONING","link":325901},{"localized_name":"denoise","name":"denoise","type":"FLOAT","widget":{"name":"denoise"},"link":null},{"localized_name":"sampler","name":"sampler","type":"COMBO","widget":{"name":"sampler"},"link":null},{"localized_name":"scheduler","name":"scheduler","type":"COMBO","widget":{"name":"scheduler"},"link":null}],"outputs":[{"localized_name":"LATENT","name":"LATENT","type":"LATENT","links":[325950]}],"title":"[[edit:flux]] 🧽 Resample Banding Fix","properties":{"cnr_id":"remove-banding-artifacts","ver":"1.0.1","Node name for S&R":"ResampleBandingFix","ue_properties":{"version":"7.1","widget_ue_connectable":{},"input_ue_unconnectable":{}}},"widgets_values":[0.22,"euler","beta"]},{"id":71,"type":"LatentPixelScale","pos":[410,1190],"size":[330,150],"flags":{},"order":15,"mode":4,"inputs":[{"localized_name":"samples","name":"samples","type":"LATENT","link":325948},{"localized_name":"vae","name":"vae","type":"VAE","link":325947},{"localized_name":"upscale_model_opt","name":"upscale_model_opt","shape":7,"type":"UPSCALE_MODEL","link":null},{"localized_name":"scale_method","name":"scale_method","type":"COMBO","widget":{"name":"scale_method"},"link":null},{"localized_name":"scale_factor","name":"scale_factor","type":"FLOAT","widget":{"name":"scale_factor"},"link":null},{"localized_name":"use_tiled_vae","name":"use_tiled_vae","type":"BOOLEAN","widget":{"name":"use_tiled_vae"},"link":null}],"outputs":[{"localized_name":"LATENT","name":"LATENT","type":"LATENT","links":[325949]},{"localized_name":"IMAGE","name":"IMAGE","type":"IMAGE","links":null}],"title":"[[edit:flux]] Latent Scale (on Pixel Space)","properties":{"cnr_id":"comfyui-impact-pack","ver":"705698faf242851881abd7d1e1774baa3cf47136","Node name for S&R":"LatentPixelScale","ue_properties":{"version":"7.1","widget_ue_connectable":{},"input_ue_unconnectable":{}}},"widgets_values":["lanczos",1.5,true]},{"id":72,"type":"PhotoFilmGrain","pos":[2520,360],"size":[290,350],"flags":{},"order":20,"mode":4,"inputs":[{"localized_name":"images","name":"images","type":"IMAGE","link":325951},{"localized_name":"grain_type","name":"grain_type","type":"COMBO","widget":{"name":"grain_type"},"link":null},{"localized_name":"grain_intensity","name":"grain_intensity","type":"FLOAT","widget":{"name":"grain_intensity"},"link":null},{"localized_name":"grain_size","name":"grain_size","type":"FLOAT","widget":{"name":"grain_size"},"link":null},{"localized_name":"saturation_mix","name":"saturation_mix","type":"FLOAT","widget":{"name":"saturation_mix"},"link":null},{"localized_name":"adaptive_grain","name":"adaptive_grain","type":"FLOAT","widget":{"name":"adaptive_grain"},"link":null},{"localized_name":"halation_strength","name":"halation_strength","type":"FLOAT","widget":{"name":"halation_strength"},"link":null},{"localized_name":"vignette_strength","name":"vignette_strength","type":"FLOAT","widget":{"name":"vignette_strength"},"link":null},{"localized_name":"chromatic_aberration","name":"chromatic_aberration","type":"FLOAT","widget":{"name":"chromatic_aberration"},"link":null},{"localized_name":"lens_distortion","name":"lens_distortion","type":"FLOAT","widget":{"name":"lens_distortion"},"link":null}],"outputs":[{"localized_name":"IMAGE","name":"IMAGE","type":"IMAGE","links":[325953]}],"title":"[[edit:flux]] 📸 Photo Film Grain","properties":{"cnr_id":"comfyui-advanced-photo-grain","ver":"1.0.1","Node name for S&R":"PhotoFilmGrain","ue_properties":{"version":"7.1","widget_ue_connectable":{},"input_ue_unconnectable":{}}},"widgets_values":["poisson",0.012000000000000004,1,0.22,0,0,0,0,0]},{"id":74,"type":"UpscaleImageWithModel","pos":[2520,750],"size":[292.1499938964844,106],"flags":{},"order":21,"mode":4,"inputs":[{"localized_name":"image","name":"image","type":"IMAGE","link":325953},{"localized_name":"model_name","name":"model_name","type":"COMBO","widget":{"name":"model_name"},"link":null},{"localized_name":"upscale_by","name":"upscale_by","type":"FLOAT","widget":{"name":"upscale_by"},"link":null},{"localized_name":"tile_size","name":"tile_size","type":"INT","widget":{"name":"tile_size"},"link":null}],"outputs":[{"localized_name":"IMAGE","name":"IMAGE","type":"IMAGE","links":[388577]}],"title":"[[edit:flux]]🖌️ Upscale Image with Model","properties":{"cnr_id":"ComfyUI-NeuralMedia","ver":"067d950b97f07298feca3dfd36409db8370791b4","Node name for S&R":"UpscaleImageWithModel","ue_properties":{"version":"7.1","widget_ue_connectable":{},"input_ue_unconnectable":{}}},"widgets_values":["4x_NMKD-Siax_200k.pth",2.0000000000000004,512]},{"id":42,"type":"CLIPTextEncode","pos":[2520,900],"size":[290,250],"flags":{"collapsed":false},"order":8,"mode":4,"inputs":[{"localized_name":"clip","name":"clip","type":"CLIP","link":325798},{"localized_name":"text","name":"text","type":"STRING","widget":{"name":"text"},"link":null}],"outputs":[{"localized_name":"CONDITIONING","name":"CONDITIONING","type":"CONDITIONING","links":[325900,325901]}],"title":"[[edit:flux]] CLIP Text Encode (Prompt)","properties":{"cnr_id":"comfy-core","ver":"0.3.43","Node name for S&R":"CLIPTextEncode","ue_properties":{"version":"7.1","widget_ue_connectable":{},"input_ue_unconnectable":{}}},"widgets_values":[""]},{"id":36,"type":"VAEEncode","pos":[490,1110],"size":[186.62916564941406,46],"flags":{"collapsed":true},"order":10,"mode":4,"inputs":[{"localized_name":"pixels","name":"pixels","type":"IMAGE","link":388588},{"localized_name":"vae","name":"vae","type":"VAE","link":325792}],"outputs":[{"localized_name":"LATENT","name":"LATENT","type":"LATENT","links":[325948]}],"title":"[[edit:flux]] VAE Encode","properties":{"cnr_id":"comfy-core","ver":"0.3.43","Node name for S&R":"VAEEncode","ue_properties":{"version":"7.1","widget_ue_connectable":{},"input_ue_unconnectable":{}}},"widgets_values":[]},{"id":41,"type":"VAEDecode","pos":[490,1150],"size":[187.39999389648438,46],"flags":{"collapsed":true},"order":19,"mode":4,"inputs":[{"localized_name":"samples","name":"samples","type":"LATENT","link":325950},{"localized_name":"vae","name":"vae","type":"VAE","link":325795}],"outputs":[{"localized_name":"IMAGE","name":"IMAGE","type":"IMAGE","links":[325951]}],"title":"[[edit:flux]] VAE Decode","properties":{"cnr_id":"comfy-core","ver":"0.3.43","Node name for S&R":"VAEDecode","ue_properties":{"version":"7.1","widget_ue_connectable":{},"input_ue_unconnectable":{}}},"widgets_values":[]},{"id":270,"type":"NunchakuQwenImageDiTLoader","pos":[80,360],"size":[321.0041809082031,130],"flags":{},"order":3,"mode":0,"inputs":[{"localized_name":"model_name","name":"model_name","type":"COMBO","widget":{"name":"model_name"},"link":null},{"localized_name":"cpu_offload","name":"cpu_offload","type":"COMBO","widget":{"name":"cpu_offload"},"link":null},{"localized_name":"num_blocks_on_gpu","name":"num_blocks_on_gpu","shape":7,"type":"INT","widget":{"name":"num_blocks_on_gpu"},"link":null},{"localized_name":"use_pin_memory","name":"use_pin_memory","shape":7,"type":"COMBO","widget":{"name":"use_pin_memory"},"link":null}],"outputs":[{"localized_name":"MODEL","name":"MODEL","type":"MODEL","links":[388539]}],"title":"[[edit:qwen]]","properties":{"cnr_id":"comfyui-nunchaku","ver":"1.0.1","Node name for S&R":"NunchakuQwenImageDiTLoader","ue_properties":{"widget_ue_connectable":{"model_name":true,"cpu_offload":true,"num_blocks_on_gpu":true,"use_pin_memory":true},"version":"7.1","input_ue_unconnectable":{}}},"widgets_values":["svdq-int4_r32-qwen-image-edit-2509-lightningv2.0-4steps.safetensors","auto",1,"disable"]},{"id":273,"type":"CLIPLoader","pos":[80,760],"size":[320,110],"flags":{},"order":4,"mode":0,"inputs":[{"localized_name":"clip_name","name":"clip_name","type":"COMBO","widget":{"name":"clip_name"},"link":null},{"localized_name":"type","name":"type","type":"COMBO","widget":{"name":"type"},"link":null},{"localized_name":"device","name":"device","shape":7,"type":"COMBO","widget":{"name":"device"},"link":null}],"outputs":[{"localized_name":"CLIP","name":"CLIP","type":"CLIP","links":[388533,388579]}],"title":"[[edit:qwen]]","properties":{"cnr_id":"comfy-core","ver":"0.3.60","Node name for S&R":"CLIPLoader","ue_properties":{"widget_ue_connectable":{"clip_name":true,"type":true,"device":true},"version":"7.1","input_ue_unconnectable":{}}},"widgets_values":["qwen_2.5_vl_7b_fp8_scaled.safetensors","qwen_image","default"]},{"id":274,"type":"VAELoader","pos":[80,910],"size":[320,58],"flags":{},"order":5,"mode":0,"inputs":[{"localized_name":"vae_name","name":"vae_name","type":"COMBO","widget":{"name":"vae_name"},"link":null}],"outputs":[{"localized_name":"VAE","name":"VAE","type":"VAE","links":[388535,388547,388548,388580]}],"title":"[[edit:qwen]]","properties":{"cnr_id":"comfy-core","ver":"0.3.60","Node name for S&R":"VAELoader","ue_properties":{"widget_ue_connectable":{"vae_name":true},"version":"7.1","input_ue_unconnectable":{}}},"widgets_values":["qwen_image_vae.safetensors"]},{"id":275,"type":"ModelSamplingAuraFlow","pos":[80,1010],"size":[320,60],"flags":{},"order":9,"mode":0,"inputs":[{"localized_name":"model","name":"model","type":"MODEL","link":388539},{"localized_name":"shift","name":"shift","type":"FLOAT","widget":{"name":"shift"},"link":null}],"outputs":[{"localized_name":"MODEL","name":"MODEL","type":"MODEL","links":[388540]}],"title":"[[edit:qwen]]","properties":{"cnr_id":"comfy-core","ver":"0.3.60","Node name for S&R":"ModelSamplingAuraFlow","ue_properties":{"widget_ue_connectable":{"shift":true},"version":"7.1","input_ue_unconnectable":{}}},"widgets_values":[3]},{"id":276,"type":"CFGNorm","pos":[80,1110],"size":[320,70],"flags":{},"order":14,"mode":0,"inputs":[{"localized_name":"model","name":"model","type":"MODEL","link":388540},{"localized_name":"strength","name":"strength","type":"FLOAT","widget":{"name":"strength"},"link":null}],"outputs":[{"localized_name":"patched_model","name":"patched_model","type":"MODEL","links":[388541]}],"title":"[[edit:qwen]]","properties":{"cnr_id":"comfy-core","ver":"0.3.60","Node name for S&R":"CFGNorm","ue_properties":{"widget_ue_connectable":{"strength":true},"version":"7.1","input_ue_unconnectable":{}}},"widgets_values":[1]},{"id":277,"type":"KSampler","pos":[80,1220],"size":[320,262],"flags":{},"order":16,"mode":0,"inputs":[{"localized_name":"model","name":"model","type":"MODEL","link":388541},{"localized_name":"positive","name":"positive","type":"CONDITIONING","link":388582},{"localized_name":"negative","name":"negative","type":"CONDITIONING","link":388543},{"localized_name":"latent_image","name":"latent_image","type":"LATENT","link":388550},{"localized_name":"seed","name":"seed","type":"INT","widget":{"name":"seed"},"link":null},{"localized_name":"steps","name":"steps","type":"INT","widget":{"name":"steps"},"link":null},{"localized_name":"cfg","name":"cfg","type":"FLOAT","widget":{"name":"cfg"},"link":null},{"localized_name":"sampler_name","name":"sampler_name","type":"COMBO","widget":{"name":"sampler_name"},"link":null},{"localized_name":"scheduler","name":"scheduler","type":"COMBO","widget":{"name":"scheduler"},"link":null},{"localized_name":"denoise","name":"denoise","type":"FLOAT","widget":{"name":"denoise"},"link":null}],"outputs":[{"localized_name":"LATENT","name":"LATENT","type":"LATENT","links":[388545]}],"title":"[[edit:qwen]]","properties":{"cnr_id":"comfy-core","ver":"0.3.60","Node name for S&R":"KSampler","ue_properties":{"widget_ue_connectable":{"seed":true,"steps":true,"cfg":true,"sampler_name":true,"scheduler":true,"denoise":true},"version":"7.1","input_ue_unconnectable":{}}},"widgets_values":[213932845013054,"randomize",4,1,"euler","beta",1]},{"id":279,"type":"VAEDecode","pos":[250,1520],"size":[140,46],"flags":{"collapsed":true},"order":18,"mode":0,"inputs":[{"localized_name":"samples","name":"samples","type":"LATENT","link":388545},{"localized_name":"vae","name":"vae","type":"VAE","link":388547}],"outputs":[{"localized_name":"IMAGE","name":"IMAGE","type":"IMAGE","links":[388576]}],"title":"[[edit:qwen]]","properties":{"cnr_id":"comfy-core","ver":"0.3.60","Node name for S&R":"VAEDecode","ue_properties":{"widget_ue_connectable":{},"version":"7.1","input_ue_unconnectable":{}}},"widgets_values":[]},{"id":280,"type":"VAEEncode","pos":[100,1520],"size":[140,46],"flags":{"collapsed":true},"order":12,"mode":0,"inputs":[{"localized_name":"pixels","name":"pixels","type":"IMAGE","link":388590},{"localized_name":"vae","name":"vae","type":"VAE","link":388548}],"outputs":[{"localized_name":"LATENT","name":"LATENT","type":"LATENT","links":[388550]}],"title":"[[edit:qwen]]","properties":{"cnr_id":"comfy-core","ver":"0.3.60","Node name for S&R":"VAEEncode","ue_properties":{"widget_ue_connectable":{},"version":"7.1","input_ue_unconnectable":{}}},"widgets_values":[]},{"id":272,"type":"TextEncodeQwenImageEdit","pos":[160,1560],"size":[320,140],"flags":{"collapsed":true},"order":11,"mode":0,"inputs":[{"localized_name":"clip","name":"clip","type":"CLIP","link":388533},{"localized_name":"vae","name":"vae","shape":7,"type":"VAE","link":388535},{"localized_name":"image","name":"image","shape":7,"type":"IMAGE","link":388589},{"localized_name":"prompt","name":"prompt","type":"STRING","widget":{"name":"prompt"},"link":null}],"outputs":[{"localized_name":"CONDITIONING","name":"CONDITIONING","type":"CONDITIONING","links":[388543]}],"title":"[[edit:qwen]]","properties":{"cnr_id":"comfy-core","ver":"0.3.60","Node name for S&R":"TextEncodeQwenImageEdit","ue_properties":{"widget_ue_connectable":{"prompt":true},"version":"7.1","input_ue_unconnectable":{}}},"widgets_values":["bad quality"]},{"id":288,"type":"TextEncodeQwenImageEditPlus","pos":[80,530],"size":[320,190],"flags":{},"order":13,"mode":0,"inputs":[{"localized_name":"clip","name":"clip","type":"CLIP","link":388579},{"localized_name":"vae","name":"vae","shape":7,"type":"VAE","link":388580},{"localized_name":"image1","name":"image1","shape":7,"type":"IMAGE","link":388591},{"localized_name":"image2","name":"image2","shape":7,"type":"IMAGE","link":null},{"localized_name":"image3","name":"image3","shape":7,"type":"IMAGE","link":null},{"localized_name":"prompt","name":"prompt","type":"STRING","widget":{"name":"prompt"},"link":null}],"outputs":[{"localized_name":"CONDITIONING","name":"CONDITIONING","type":"CONDITIONING","links":[388582]}],"title":"[[edit:qwen]]","properties":{"cnr_id":"comfy-core","ver":"0.3.60","Node name for S&R":"TextEncodeQwenImageEditPlus","ue_properties":{"widget_ue_connectable":{"prompt":true},"version":"7.1","input_ue_unconnectable":{}}},"widgets_values":["woman fly"]},{"id":291,"type":"LayerSystem","pos":[750,360],"size":[800,126],"flags":{},"order":7,"mode":0,"inputs":[{"localized_name":"_properties_json","name":"_properties_json","shape":7,"type":"STRING","widget":{"name":"_properties_json"},"link":null},{"localized_name":"_preview_anchor","name":"_preview_anchor","shape":7,"type":"STRING","widget":{"name":"_preview_anchor"},"link":null},{"localized_name":"header_anchor_1","name":"header_anchor_1","shape":7,"type":"STRING","widget":{"name":"header_anchor_1"},"link":null},{"localized_name":"header_anchor_2","name":"header_anchor_2","shape":7,"type":"STRING","widget":{"name":"header_anchor_2"},"link":null},{"localized_name":"header_anchor_3","name":"header_anchor_3","shape":7,"type":"STRING","widget":{"name":"header_anchor_3"},"link":null},{"localized_name":"header_anchor_4","name":"header_anchor_4","shape":7,"type":"STRING","widget":{"name":"header_anchor_4"},"link":null},{"localized_name":"header_anchor_5","name":"header_anchor_5","shape":7,"type":"STRING","widget":{"name":"header_anchor_5"},"link":null},{"localized_name":"header_anchor_6","name":"header_anchor_6","shape":7,"type":"STRING","widget":{"name":"header_anchor_6"},"link":null},{"localized_name":"header_anchor_7","name":"header_anchor_7","shape":7,"type":"STRING","widget":{"name":"header_anchor_7"},"link":null},{"localized_name":"header_anchor_8","name":"header_anchor_8","shape":7,"type":"STRING","widget":{"name":"header_anchor_8"},"link":null},{"localized_name":"header_anchor_9","name":"header_anchor_9","shape":7,"type":"STRING","widget":{"name":"header_anchor_9"},"link":null},{"localized_name":"header_anchor_10","name":"header_anchor_10","shape":7,"type":"STRING","widget":{"name":"header_anchor_10"},"link":null},{"localized_name":"header_anchor_11","name":"header_anchor_11","shape":7,"type":"STRING","widget":{"name":"header_anchor_11"},"link":null}],"outputs":[{"localized_name":"IMAGE","name":"IMAGE","type":"IMAGE","links":[388588,388589,388590,388591]}],"properties":{"cnr_id":"comfyui-layers-utility","ver":"3.1.1","Node name for S&R":"LayerSystem","ue_properties":{"widget_ue_connectable":{"_properties_json":true,"_preview_anchor":true,"header_anchor_1":true,"header_anchor_2":true,"header_anchor_3":true,"header_anchor_4":true,"header_anchor_5":true,"header_anchor_6":true,"header_anchor_7":true,"header_anchor_8":true,"header_anchor_9":true,"header_anchor_10":true,"header_anchor_11":true},"version":"7.1","input_ue_unconnectable":{}}},"widgets_values":["","{\"base\":null,\"layers\":{},\"texts\":[],\"preview_width\":300,\"preview_height\":150,\"toolbar_width\":40}","","","","","","","","","","","",null,null]},{"id":292,"type":"PreviewImage","pos":[1560,360],"size":[950,1270],"flags":{},"order":23,"mode":0,"inputs":[{"localized_name":"images","name":"images","type":"IMAGE","link":388592}],"outputs":[],"title":"view","properties":{"cnr_id":"comfy-core","ver":"0.3.60","Node name for S&R":"PreviewImage","ue_properties":{"widget_ue_connectable":{},"version":"7.1","input_ue_unconnectable":{}}},"widgets_values":[]},{"id":268,"type":"OrchestratorNodeToogle","pos":[2520,1190],"size":[290,120],"flags":{},"order":6,"mode":0,"inputs":[],"outputs":[],"properties":{"cnr_id":"comfyui_custom_switch","ver":"1.5.0","Node name for S&R":"OrchestratorNodeToogle","ue_properties":{"widget_ue_connectable":{},"version":"7.1","input_ue_unconnectable":{}}},"widgets_values":["edit",null,false,true]}],"links":[[325792,39,0,36,1,"VAE"],[325795,39,0,41,1,"VAE"],[325798,38,0,42,0,"CLIP"],[325900,42,0,60,2,"CONDITIONING"],[325901,42,0,60,3,"CONDITIONING"],[325914,37,0,60,1,"MODEL"],[325947,39,0,71,1,"VAE"],[325948,36,0,71,0,"LATENT"],[325949,71,0,60,0,"LATENT"],[325950,60,0,41,0,"LATENT"],[325951,41,0,72,0,"IMAGE"],[325953,72,0,74,0,"IMAGE"],[388533,273,0,272,0,"CLIP"],[388535,274,0,272,1,"VAE"],[388539,270,0,275,0,"MODEL"],[388540,275,0,276,0,"MODEL"],[388541,276,0,277,0,"MODEL"],[388543,272,0,277,2,"CONDITIONING"],[388545,277,0,279,0,"LATENT"],[388547,274,0,279,1,"VAE"],[388548,274,0,280,1,"VAE"],[388550,280,0,277,3,"LATENT"],[388576,279,0,287,0,"IMAGE"],[388577,74,0,287,1,"IMAGE"],[388579,273,0,288,0,"CLIP"],[388580,274,0,288,1,"VAE"],[388582,288,0,277,1,"CONDITIONING"],[388588,291,0,36,0,"IMAGE"],[388589,291,0,272,2,"IMAGE"],[388590,291,0,280,0,"IMAGE"],[388591,291,0,288,2,"IMAGE"],[388592,287,0,292,0,"IMAGE"]],"groups":[],"config":{},"extra":{"ue_links":[],"ds":{"scale":0.6627272727272777,"offset":[101.6363801155102,-281.4870060551175]},"links_added_by_ue":[]},"version":0.4}
--------------------------------------------------------------------------------
/js/toolbar.js:
--------------------------------------------------------------------------------
1 | import { MaskManager } from './mask_manager.js';
2 | import { BrushManager } from './brush_manager.js';
3 | import { RemoveBgManager } from './removebg.js';
4 | import { MagicWandManager } from './magic_wand_manager.js';
5 | import { MaskPainterManager } from './mask_painter_manager.js';
6 |
7 | const textIconPath = new Path2D("M5 4v2h5v12h4V6h5V4H5z");
8 | const maskIconPath = new Path2D("M2 2 H22 V22 H2 Z M12 12 m-6 0 a6 6 0 1 0 12 0 a6 6 0 1 0 -12 0");
9 | const FONT_LIST = [
10 | // Sans-serif
11 | "Arial",
12 | "Verdana",
13 | "Tahoma",
14 | "Trebuchet MS",
15 | "Impact",
16 | "Lucida Sans Unicode",
17 | // Serif
18 | "Georgia",
19 | "Times New Roman",
20 | "Garamond",
21 | // Monospace
22 | "Courier New",
23 | "Lucida Console"
24 | ];
25 | function ensureToolbarStyles() {
26 | const styleId = 'contextual-toolbar-styles';
27 | if (document.getElementById(styleId)) return;
28 | const style = document.createElement('style');
29 | style.id = styleId;
30 | style.innerHTML = `
31 | #contextual-text-toolbar {
32 | /* MODIFIÉ : Fond blanc avec 85% d'opacité */
33 | background-color: rgba(255, 255, 255, 0.5) !important;
34 | backdrop-filter: blur(8px);
35 | -webkit-backdrop-filter: blur(8px);
36 | /* MODIFIÉ : Bordure grise subtile */
37 | border: 1px solid rgba(0, 0, 0, 0.1);
38 | border-radius: 8px;
39 | box-shadow: 0 4px H12px rgba(0,0,0,0.2);
40 | padding: 2px;
41 | display: flex;
42 | gap: 4px;
43 | }
44 | #contextual-text-toolbar button {
45 | background-color: transparent;
46 | border: none;
47 | /* MODIFIÉ : Icônes sombres pour la lisibilité sur fond blanc */
48 | color: #333;
49 | font-size: 18px;
50 | cursor: pointer;
51 | padding: 4px;
52 | border-radius: 4px;
53 | transition: background-color 0.2s;
54 | }
55 | #contextual-text-toolbar button:hover {
56 | /* MODIFIÉ : Effet de survol gris très clair */
57 | background-color: rgba(0, 0, 0, 0.05);
58 | }
59 | `;
60 | document.head.appendChild(style);
61 | }
62 | export class Toolbar {
63 | constructor(node) {
64 | this.node = node;
65 | this.width = 40;
66 | this.activeTool = null;
67 | this.textElements = [];
68 | this.activeTextarea = null;
69 | this.lastClickTime = 0;
70 | this.lastClickTarget = null;
71 | this.clickTimeout = null;
72 | this.tools = [
73 | { name: 'text', icon: textIconPath, y: 9 },
74 | { name: 'mask', icon: '🎭', y: 45 },
75 | { name: 'magic_wand', icon: '☯️', y: 81 },
76 | { name: 'brush', icon: '🖌️', y: 117 }
77 | ];
78 |
79 | this.toolBounds = {};
80 | this.selectedTextObject = null;
81 | this.textEditTool = 'move';
82 | this.contextualToolbar = null;
83 | this.isTextDragging = false;
84 | this.dragStart = { x: 0, y: 0 };
85 | this.initialTextPos = { x: 0, y: 0 };
86 | this.dragOffset = { x: 0, y: 0 };
87 | this.boundDragMove = this.handleDragMove.bind(this);
88 | this.boundDragEnd = this.handleDragEnd.bind(this);
89 | this.isResizing = false;
90 | this.resizeSensitivity = 0.5;
91 | this.colorPicker = null;
92 |
93 | this.maskManager = new MaskManager(this.node);
94 | this.removeBgManager = new RemoveBgManager(this.node, this.maskManager);
95 | this.magicWandManager = new MagicWandManager(this.node);
96 | this.brushManager = new BrushManager(this.node);
97 | this.maskPainterManager = new MaskPainterManager(this.node);
98 |
99 | this.setupColorPicker();
100 | this.createContextualToolbar();
101 | this.selectionSubMenu = null;
102 | this.createSelectionSubMenu();
103 | }
104 | createContextualToolbar() {
105 | ensureToolbarStyles();
106 | if (this.contextualToolbar) this.contextualToolbar.remove();
107 | const toolbar = document.createElement("div");
108 | toolbar.id = 'contextual-text-toolbar';
109 | this.contextualToolbar = toolbar;
110 | Object.assign(toolbar.style, {
111 | position: 'fixed', display: 'none', zIndex: '10001',
112 | });
113 |
114 | const fontSelect = document.createElement("select");
115 | fontSelect.className = 'font-select';
116 | Object.assign(fontSelect.style, {
117 | backgroundColor: 'transparent',
118 | border: '1px solid rgba(0, 0, 0, 0.1)',
119 | borderRadius: '4px',
120 | color: '#333',
121 | padding: '3px',
122 | margin: '0 2px'
123 | });
124 | FONT_LIST.forEach(fontName => {
125 | const option = document.createElement("option");
126 | option.value = fontName;
127 | option.textContent = fontName;
128 | option.style.fontFamily = fontName;
129 | fontSelect.appendChild(option);
130 | });
131 | fontSelect.addEventListener('change', () => {
132 | if (this.selectedTextObject) {
133 | this.selectedTextObject.fontFamily = fontSelect.value;
134 | this.node.redrawPreviewCanvas();
135 | this.node.updatePropertiesJSON();
136 | }
137 | });
138 | toolbar.appendChild(fontSelect);
139 |
140 | const icons = {
141 | 'move': '↔️', 'edit': '✏️', 'resize': '🔍', 'color': '🎨', 'delete': '🗑️', 'close': '❌'
142 | };
143 | for (const action in icons) {
144 | const button = document.createElement("button");
145 | button.innerHTML = icons[action];
146 |
147 | button.addEventListener('click', () => {
148 | if (!this.selectedTextObject) return;
149 | this.isTextDragging = false;
150 | this.isResizing = false;
151 | this.node.previewCanvas.style.setProperty('cursor', 'default', 'important');
152 | Array.from(event.currentTarget.parentElement.children).forEach(btn => {
153 | btn.style.backgroundColor = 'transparent';
154 | });
155 | switch(action) {
156 | case 'resize':
157 | this.isResizing = true;
158 | this.node.previewCanvas.style.setProperty('cursor', 'ns-resize', 'important');
159 | event.currentTarget.style.backgroundColor = 'rgba(0, 0, 0, 0.1)';
160 | break;
161 | case 'move':
162 | this.isTextDragging = true;
163 | this.node.previewCanvas.style.setProperty('cursor', 'move', 'important');
164 | event.currentTarget.style.backgroundColor = 'rgba(0, 0, 0, 0.1)';
165 | break;
166 | case 'edit':
167 | this.node.editTextElement(this.selectedTextObject);
168 | event.currentTarget.style.backgroundColor = 'rgba(0, 0, 0, 0.1)';
169 | break;
170 | case 'delete':
171 | const index = this.textElements.findIndex(el => el.id === this.selectedTextObject.id);
172 | if (index > -1) {
173 | this.textElements.splice(index, 1);
174 | this.hideContextualToolbar();
175 | this.node.updatePropertiesJSON();
176 | }
177 | break;
178 | case 'close':
179 | this.hideContextualToolbar();
180 | break;
181 | case 'color':
182 | event.currentTarget.style.backgroundColor = 'rgba(0, 0, 0, 0.1)';
183 | if (this.selectedTextObject && this.colorPicker) {
184 | this.colorPicker.value = this.selectedTextObject.color || '#FFFFFF';
185 | this.colorPicker.click();
186 | }
187 | break;
188 | }
189 | });
190 | toolbar.appendChild(button);
191 | }
192 | document.body.appendChild(toolbar);
193 | }
194 | getTexts() {
195 | return this.textElements;
196 | }
197 | draw(ctx) {
198 | const canvas = this.node.previewCanvas;
199 | if (!canvas) return;
200 | const x = 0;
201 | ctx.save();
202 | ctx.fillStyle = '#282828';
203 | ctx.fillRect(x, 0, this.width, canvas.height);
204 | ctx.strokeStyle = '#111111';
205 | ctx.lineWidth = 1;
206 | ctx.strokeRect(x, 0, this.width, canvas.height);
207 | ctx.restore();
208 | this.tools.forEach(tool => {
209 | const iconSize = 24;
210 | const iconX_start = (this.width - iconSize) / 2;
211 | const iconY_start = tool.y;
212 |
213 | this.toolBounds[tool.name] = {
214 | x: iconX_start,
215 | y: iconY_start,
216 | size: iconSize
217 | };
218 |
219 | const isActive = this.activeTool === tool.name ||
220 | (tool.name === 'magic_wand' && this.selectionSubMenu?.style.display === 'flex');
221 |
222 | if (isActive) {
223 | ctx.fillStyle = "rgba(255, 221, 255, 0.6)";
224 | const padding = 2;
225 | ctx.fillRect(iconX_start - padding, iconY_start - padding, iconSize + (padding * 2), iconSize + (padding * 2));
226 | }
227 |
228 | ctx.save();
229 | if (tool.icon instanceof Path2D) {
230 | ctx.translate(iconX_start, iconY_start);
231 | ctx.scale(iconSize / 24, iconSize / 24);
232 | ctx.strokeStyle = (this.activeTool === tool.name) ? "#FFD700" : "#FFFFFF";
233 | ctx.lineWidth = 2;
234 | ctx.stroke(tool.icon);
235 | } else {
236 | ctx.font = `${iconSize}px sans-serif`;
237 | ctx.textAlign = 'center';
238 | ctx.textBaseline = 'middle';
239 | ctx.fillText(tool.icon, iconX_start + iconSize / 2, iconY_start + iconSize / 2);
240 | }
241 |
242 | ctx.restore();
243 | });
244 | }
245 | getConversionRatio() {
246 | if (!this.node.basePreviewImage || !this.node.previewCanvas || (this.node.previewCanvas.width - this.width) <= 0) {
247 | return 1.0;
248 | }
249 | const baseImageWidth = this.node.basePreviewImage.naturalWidth;
250 | const previewImageAreaWidth = this.node.previewCanvas.width - this.width;
251 | return baseImageWidth / previewImageAreaWidth;
252 | }
253 | drawTextElements(ctx) {
254 | if (!this.node.previewCanvas || !this.node.basePreviewImage) return;
255 | const ratio = this.getConversionRatio();
256 | if (ratio === 1.0 && this.textElements.length > 0) return;
257 | const inverseRatio = 1 / ratio;
258 | const previewImageAreaWidth = this.node.previewCanvas.width - this.width;
259 | const previewCenterX = previewImageAreaWidth / 2;
260 | const previewCenterY = this.node.previewCanvas.height / 2;
261 | ctx.save();
262 | this.textElements.forEach(textEl => {
263 | const preview_offset_x = textEl.offset_x * inverseRatio;
264 | const preview_offset_y = textEl.offset_y * inverseRatio;
265 | const preview_size = textEl.size * inverseRatio;
266 | const preview_x = this.width + previewCenterX + preview_offset_x;
267 | const preview_y = previewCenterY + preview_offset_y;
268 | ctx.fillStyle = textEl.color;
269 | ctx.font = `${preview_size}px ${textEl.fontFamily || 'Arial'}`;
270 | ctx.textBaseline = 'top';
271 | ctx.fillText(textEl.text, preview_x, preview_y);
272 | });
273 | ctx.restore();
274 | }
275 |
276 | handleClick(e, mouseX, mouseY) {
277 | const clickedTool = this.tools.find(tool => {
278 | const bounds = this.toolBounds[tool.name];
279 | if (!bounds) return false;
280 | return mouseX >= bounds.x && mouseX < (bounds.x + bounds.size) &&
281 | mouseY >= bounds.y && mouseY < (bounds.y + bounds.size);
282 | });
283 |
284 | if (clickedTool) {
285 | const toolName = clickedTool.name;
286 | const isDeactivating = this.activeTool === toolName ||
287 | (toolName === 'magic_wand' && this.selectionSubMenu?.style.display === 'flex');
288 |
289 | this.activeTool = null;
290 | this.maskManager.hide();
291 | this.magicWandManager.hide();
292 | this.brushManager.hide();
293 | this.maskPainterManager.hide();
294 | if (this.selectionSubMenu) {
295 | this.selectionSubMenu.style.display = 'none';
296 | }
297 |
298 | if (!isDeactivating) {
299 | if (toolName !== 'magic_wand') {
300 | this.activeTool = toolName;
301 | }
302 |
303 | switch (toolName) {
304 | case 'mask':
305 | this.maskManager.show();
306 | break;
307 | case 'magic_wand':
308 | if (this.selectionSubMenu) {
309 | this.selectionSubMenu.style.display = 'flex';
310 | this.positionSelectionSubMenu();
311 | }
312 | break;
313 | case 'brush':
314 | this.brushManager.show();
315 | break;
316 | case 'text':
317 | break;
318 | }
319 | }
320 | if (clickedTool || this.activeTool) {
321 | this.node.movingLayer = null;
322 |
323 | }
324 | this.node.refreshUI();
325 | }
326 | }
327 |
328 | handleCanvasClick(e) {
329 | if (this.activeTool !== 'text') {
330 | return;
331 | }
332 |
333 | if (this.selectedTextObject) {
334 | const clickedText = this.node.findTextElementAtPos(e.offsetX, e.offsetY);
335 | if (clickedText && clickedText.id === this.selectedTextObject.id) {
336 | this.handleDragStart(e);
337 | } else {
338 | this.hideContextualToolbar();
339 | }
340 | return;
341 | }
342 |
343 | const now = Date.now();
344 | const clickedTextForSelection = this.node.findTextElementAtPos(e.offsetX, e.offsetY);
345 |
346 | if (clickedTextForSelection && (now - this.lastClickTime < 300) && this.lastClickTarget === clickedTextForSelection.id) {
347 | if (this.clickTimeout) { clearTimeout(this.clickTimeout); this.clickTimeout = null; }
348 | this.showContextualToolbar(clickedTextForSelection, e);
349 | this.lastClickTime = 0;
350 | return;
351 | }
352 | this.lastClickTime = now;
353 | this.lastClickTarget = clickedTextForSelection ? clickedTextForSelection.id : null;
354 | if (!clickedTextForSelection) {
355 | this.clickTimeout = setTimeout(() => {
356 | if (this.activeTextarea) this.activeTextarea.remove();
357 |
358 | const textInput = document.createElement("div");
359 | this.activeTextarea = textInput;
360 | textInput.contentEditable = true;
361 | Object.assign(textInput.style, {
362 | position: 'fixed', left: `${e.clientX}px`, top: `${e.clientY}px`,
363 | border: '2px solid #FFD700', background: 'rgba(20,20,20,0.9)',
364 | color: 'white', zIndex: '9999', fontFamily: 'Arial',
365 | fontSize: '16px', padding: '5px', minWidth: '100px',
366 | resize: 'both', overflow: 'auto', whiteSpace: 'pre-wrap'
367 | });
368 | document.body.appendChild(textInput);
369 | textInput.focus();
370 | document.execCommand('selectAll', false, null);
371 | const onFinish = () => {
372 | if (textInput.innerText.trim() !== "") {
373 | const ratio = this.getConversionRatio();
374 | const previewImageAreaWidth = this.node.previewCanvas.width - this.width;
375 | const previewCenterX = previewImageAreaWidth / 2;
376 | const previewCenterY = this.node.previewCanvas.height / 2;
377 | const click_x_in_preview_area = e.offsetX - this.width;
378 | const click_y_in_preview_area = e.offsetY;
379 | const newTextElement = {
380 | id: `text_${Date.now()}`,
381 | text: textInput.innerText,
382 | offset_x: (click_x_in_preview_area - previewCenterX) * ratio,
383 | offset_y: (click_y_in_preview_area - previewCenterY) * ratio,
384 | size: 24 * ratio,
385 | color: '#FFFFFF',
386 | fontFamily: 'Arial',
387 | };
388 | this.textElements.push(newTextElement);
389 | this.node.updatePropertiesJSON();
390 | this.node.redrawPreviewCanvas();
391 | }
392 | if (textInput.parentElement) textInput.parentElement.removeChild(textInput);
393 | this.activeTextarea = null;
394 | };
395 |
396 | textInput.addEventListener('blur', onFinish);
397 | textInput.addEventListener('keydown', (evt) => {
398 | evt.stopPropagation();
399 | if (evt.key === 'Enter' && !evt.shiftKey) {
400 | evt.preventDefault();
401 | onFinish();
402 | }
403 | });
404 | }, 250);
405 | }
406 | }
407 | showContextualToolbar(textElement, event) {
408 | this.selectedTextObject = textElement;
409 | this.contextualToolbar.style.display = 'flex';
410 | this.node.redrawPreviewCanvas();
411 | this.setDefaultMode();
412 |
413 | const fontSelect = this.contextualToolbar.querySelector('.font-select');
414 | if (fontSelect && this.selectedTextObject.fontFamily) {
415 | fontSelect.value = this.selectedTextObject.fontFamily;
416 | }
417 |
418 | this.updateContextualToolbarPosition();
419 | }
420 | handleDragStart(e) {
421 | if (!this.selectedTextObject) return;
422 |
423 | this.initialTextData = {
424 | offset_x: this.selectedTextObject.offset_x,
425 | offset_y: this.selectedTextObject.offset_y,
426 | size: this.selectedTextObject.size
427 | };
428 |
429 | this.dragStart = { x: e.clientX, y: e.clientY };
430 |
431 | if (this.isResizing) {
432 | window.addEventListener('mousemove', this.boundDragMove, true);
433 | window.addEventListener('mouseup', this.boundDragEnd, true);
434 | return;
435 | }
436 |
437 | this.isTextDragging = true;
438 | window.addEventListener('mousemove', this.boundDragMove, true);
439 | window.addEventListener('mouseup', this.boundDragEnd, true);
440 | }
441 | updateContextualToolbarPosition() {
442 | if (!this.selectedTextObject || !this.node.previewCanvas || !this.node.getTextPreviewMetrics) return;
443 | const metrics = this.node.getTextPreviewMetrics(this.selectedTextObject);
444 | if (!metrics) return;
445 | const canvasRect = this.node.previewCanvas.getBoundingClientRect();
446 |
447 | let zoom = 1.0;
448 | const unscaledWidth = this.node.previewCanvas.width;
449 | if (unscaledWidth > 0 && canvasRect.width > 0) {
450 | zoom = canvasRect.width / unscaledWidth;
451 | }
452 | const anchorX = canvasRect.left + (metrics.x + metrics.width / 2) * zoom;
453 | const anchorY = canvasRect.top + metrics.y * zoom;
454 | const toolbarEl = this.contextualToolbar;
455 | if (!toolbarEl) return;
456 |
457 | toolbarEl.style.left = `${anchorX}px`;
458 | toolbarEl.style.top = `${anchorY}px`;
459 |
460 | const margin = 60;
461 | toolbarEl.style.transform = `translate(-50%, -100%) translateY(-${margin}px)`;
462 | }
463 | handleDragMove(e) {
464 | if (!this.selectedTextObject) return;
465 |
466 | const dx = e.clientX - this.dragStart.x;
467 | const dy = e.clientY - this.dragStart.y;
468 | const ratio = this.getConversionRatio();
469 | if (this.isResizing) {
470 | const delta_size_final = -(dy * this.resizeSensitivity) * ratio;
471 | const newSize = this.initialTextData.size + delta_size_final;
472 | this.selectedTextObject.size = Math.max(5 * ratio, newSize);
473 | }
474 | else if (this.isTextDragging) {
475 | e.preventDefault();
476 | e.stopPropagation();
477 | const delta_x_final = dx * ratio;
478 | const delta_y_final = dy * ratio;
479 | this.selectedTextObject.offset_x = this.initialTextData.offset_x + delta_x_final;
480 | this.selectedTextObject.offset_y = this.initialTextData.offset_y + delta_y_final;
481 | }
482 |
483 | this.node.redrawPreviewCanvas();
484 | }
485 | handleDragEnd(e) {
486 | window.removeEventListener('mousemove', this.boundDragMove, true);
487 | window.removeEventListener('mouseup', this.boundDragEnd, true);
488 |
489 | this.node.updatePropertiesJSON();
490 | this.node.redrawPreviewCanvas();
491 | if (this.isResizing) {
492 | }
493 | else if (this.isTextDragging) {
494 | this.isTextDragging = false;
495 | this.updateContextualToolbarPosition();
496 | }
497 | }
498 |
499 | createSelectionSubMenu() {
500 | this.selectionSubMenu = document.createElement("div");
501 | Object.assign(this.selectionSubMenu.style, {
502 | position: 'fixed',
503 | display: 'none',
504 | zIndex: '10002',
505 | backgroundColor: 'rgba(30, 30, 30, 0.9)',
506 | border: '1px solid #555',
507 | borderRadius: '8px',
508 | padding: '4px',
509 | flexDirection: 'column',
510 | gap: '4px',
511 | });
512 |
513 | const createEmojiButton = (emoji, title) => {
514 | const button = document.createElement("button");
515 | button.innerText = emoji;
516 | button.title = title;
517 | Object.assign(button.style, {
518 | backgroundColor: '#444',
519 | color: 'white',
520 | border: '1px solid #666',
521 | padding: '0',
522 | borderRadius: '5px',
523 | cursor: 'pointer',
524 | width: '26px',
525 | height: '26px',
526 | fontSize: '16px',
527 | textAlign: 'center',
528 | lineHeight: '26px',
529 | });
530 | button.onmouseover = () => button.style.backgroundColor = '#5E5E5E';
531 | button.onmouseout = () => button.style.backgroundColor = '#444';
532 | return button;
533 | };
534 |
535 | const wandButton = createEmojiButton("🪄", "Baguette Magique");
536 | wandButton.onclick = () => {
537 | this.activeTool = 'magic_wand';
538 | this.magicWandManager.show();
539 | this.selectionSubMenu.style.display = 'none';
540 | };
541 |
542 | const paintMaskButton = createEmojiButton("🖌️", "Paint Mask"); // NOUVEAU
543 | paintMaskButton.onclick = () => {
544 | //this.activeTool = 'mask_painter';
545 | if (this.maskPainterManager) {
546 | this.maskPainterManager.show();
547 | }
548 | this.selectionSubMenu.style.display = 'none';
549 | };
550 |
551 | this.selectionSubMenu.append(wandButton, paintMaskButton);
552 | document.body.appendChild(this.selectionSubMenu);
553 | }
554 |
555 | positionSelectionSubMenu() {
556 | if (!this.selectionSubMenu || this.selectionSubMenu.style.display === 'none') {
557 | return;
558 | }
559 |
560 | const bounds = this.toolBounds['magic_wand'];
561 | if (!bounds || !this.node.previewCanvas) return;
562 |
563 | const canvasRect = this.node.previewCanvas.getBoundingClientRect();
564 |
565 | this.selectionSubMenu.style.left = `${canvasRect.left + bounds.x + bounds.size}px`;
566 | this.selectionSubMenu.style.top = `${canvasRect.top + bounds.y - 40}px`;
567 | }
568 |
569 | hideContextualToolbar() {
570 | this.selectedTextObject = null;
571 | this.contextualToolbar.style.display = 'none';
572 | this.isResizing = false;
573 | this.isTextDragging = false;
574 |
575 | if (this.node.previewCanvas) {
576 | this.node.previewCanvas.style.setProperty('cursor', 'default', 'important');
577 | }
578 | this.node.redrawPreviewCanvas();
579 | }
580 | setupColorPicker() {
581 | const picker = document.createElement('input');
582 | picker.type = 'color';
583 | Object.assign(picker.style, {
584 | position: 'fixed',
585 | opacity: 0,
586 | pointerEvents: 'none',
587 | left: '-100px',
588 | top: '-100px'
589 | });
590 | picker.addEventListener('input', () => {
591 | if (this.selectedTextObject) {
592 | this.selectedTextObject.color = picker.value;
593 | this.node.redrawPreviewCanvas();
594 | }
595 | });
596 | picker.addEventListener('change', () => {
597 | if (this.selectedTextObject) {
598 | this.setDefaultMode();
599 | this.node.updatePropertiesJSON();
600 | }
601 | });
602 | document.body.appendChild(picker);
603 | this.colorPicker = picker;
604 | }
605 | setDefaultMode() {
606 | this.isTextDragging = true;
607 | this.isResizing = false;
608 | this.node.previewCanvas.style.setProperty('cursor', 'move', 'important');
609 | if (!this.contextualToolbar) return;
610 | Array.from(this.contextualToolbar.children).forEach(button => {
611 | button.style.backgroundColor = 'transparent';
612 | if (button.innerHTML === '↔️') {
613 | button.style.backgroundColor = 'rgba(0, 0, 0, 0.1)';
614 | }
615 | });
616 | }
617 | isClickOnToolbar(mouseX, mouseY) {
618 | const canvas = this.node.previewCanvas;
619 | return canvas && mouseX < this.width;
620 | }
621 | }
--------------------------------------------------------------------------------
/layer_system_final.py:
--------------------------------------------------------------------------------
1 | import server
2 | from aiohttp import web
3 | import time
4 | import torch
5 | import torch.nn.functional as F
6 | import json
7 | import numpy as np
8 | import folder_paths
9 | from PIL import Image, ImageOps, ImageDraw, ImageFont
10 | import os
11 | import http.server
12 | import socketserver
13 | import threading
14 | import math
15 | import glob
16 | from rembg import remove, new_session
17 |
18 | base_path = os.path.dirname(folder_paths.get_input_directory())
19 | rembg_dir = os.path.join(base_path, "models", "rembg")
20 | model_path = os.path.join(rembg_dir, "RMBG-1.4.pth")
21 |
22 | if not os.path.exists(model_path):
23 | print(f"[Layer System] ATTENTION: Model rmbg-1.4 not found at location : {model_path}")
24 | print(f"[Layer System] The clipping will use the default template 'u2net'. For better quality, download rmbg-1.4.pth.")
25 | session = new_session("u2net")
26 | else:
27 | print(f"[Layer System] INFO: Loading the high-performance model rmbg-1.4...")
28 | session = new_session(model_path=model_path)
29 |
30 | preview_server_thread = None
31 | PREVIEW_SERVER_PORT = 8189
32 |
33 | def start_preview_server():
34 | global preview_server_thread
35 | if preview_server_thread is None or not preview_server_thread.is_alive():
36 | class SecureHandler(http.server.SimpleHTTPRequestHandler):
37 | def __init__(self, *args, **kwargs):
38 | super().__init__(*args, directory=folder_paths.get_temp_directory(), **kwargs)
39 | def end_headers(self):
40 | self.send_header('Access-Control-Allow-Origin', '*')
41 | super().end_headers()
42 | def do_GET(self):
43 | if self.path == '/' or self.path.endswith('/'):
44 | self.send_error(403, "Directory listing is not allowed")
45 | return
46 | super().do_GET()
47 | def log_message(self, format, *args):
48 | return
49 | address = ("127.0.0.1", PREVIEW_SERVER_PORT)
50 | socketserver.TCPServer.allow_reuse_address = True
51 | httpd = socketserver.TCPServer(address, SecureHandler)
52 | thread = threading.Thread(target=httpd.serve_forever)
53 | thread.daemon = True
54 | thread.start()
55 | preview_server_thread = thread
56 | print(f"\n[Layer System] INFO: Starting the local preview server on http://127.0.0.1:{PREVIEW_SERVER_PORT}")
57 |
58 | def tensor_to_pil(tensor):
59 | return Image.fromarray(np.clip(255. * tensor.cpu().numpy().squeeze(), 0, 255).astype(np.uint8))
60 |
61 | def pil_to_tensor(image):
62 | return torch.from_numpy(np.array(image).astype(np.float32) / 255.0).unsqueeze(0)
63 |
64 | def prepare_layer(top_image, base_image, resize_mode, scale, offset_x, offset_y):
65 | B, base_H, base_W, C = base_image.shape
66 | _, top_H, top_W, top_C = top_image.shape
67 | if scale != 1.0:
68 | new_H, new_W = int(top_H * scale), int(top_W * scale)
69 | if new_H > 0 and new_W > 0:
70 | top_image = F.interpolate(top_image.permute(0, 3, 1, 2), size=(new_H, new_W), mode='bilinear', align_corners=False).permute(0, 2, 3, 1)
71 | top_H, top_W = new_H, new_W
72 |
73 | canvas = torch.zeros(B, base_H, base_W, top_C, device=base_image.device)
74 | if resize_mode == 'stretch':
75 | return F.interpolate(top_image.permute(0, 3, 1, 2), size=(base_H, base_W), mode='bilinear', align_corners=False).permute(0, 2, 3, 1)
76 | elif resize_mode == 'fit':
77 | if top_W == 0 or top_H == 0: return canvas
78 | ratio = min(base_W / top_W, base_H / top_H)
79 | fit_H, fit_W = int(top_H * ratio), int(top_W * ratio)
80 | resized_top = F.interpolate(top_image.permute(0, 3, 1, 2), size=(fit_H, fit_W), mode='bilinear', align_corners=False).permute(0, 2, 3, 1)
81 | y_start, x_start = (base_H - fit_H) // 2, (base_W - fit_W) // 2
82 | canvas[:, y_start:y_start+fit_H, x_start:x_start+fit_W, :] = resized_top
83 | return canvas
84 | elif resize_mode == 'cover':
85 | if top_W == 0 or top_H == 0: return canvas
86 | ratio = max(base_W / top_W, base_H / top_H)
87 | cover_H, cover_W = int(top_H * ratio), int(top_W * ratio)
88 | resized_top = F.interpolate(top_image.permute(0, 3, 1, 2), size=(cover_H, cover_W), mode='bilinear', align_corners=False)
89 | y_start, x_start = (cover_H - base_H) // 2, (cover_W - base_W) // 2
90 | src_y_end = min(y_start + base_H, cover_H)
91 | src_x_end = min(x_start + base_W, cover_W)
92 | canvas_permuted = resized_top[:, :, y_start:src_y_end, x_start:src_x_end]
93 | return canvas_permuted.permute(0, 2, 3, 1)
94 | elif resize_mode == 'crop':
95 | x_start_abs = (base_W // 2) + offset_x
96 | y_start_abs = (base_H // 2) + offset_y
97 |
98 | x_start_centered = x_start_abs - (top_W // 2)
99 | y_start_centered = y_start_abs - (top_H // 2)
100 |
101 | src_x_start = max(0, -x_start_centered)
102 | src_y_start = max(0, -y_start_centered)
103 | dst_x_start = max(0, x_start_centered)
104 | dst_y_start = max(0, y_start_centered)
105 |
106 | copy_W = min(base_W - dst_x_start, top_W - src_x_start)
107 | copy_H = min(base_H - dst_y_start, top_H - src_y_start)
108 |
109 | if copy_W > 0 and copy_H > 0:
110 | src_slice = top_image[:, src_y_start:src_y_start+copy_H, src_x_start:src_x_start+copy_W, :]
111 | canvas[:, dst_y_start:dst_y_start+copy_H, dst_x_start:dst_x_start+copy_W, :] = src_slice
112 | return canvas
113 | return canvas
114 |
115 |
116 | class LayerSystem:
117 | OUTPUT_NODE = True
118 |
119 | @classmethod
120 | def INPUT_TYPES(cls):
121 | header_anchors = {}
122 | for i in range(1, 12):
123 | header_anchors[f"header_anchor_{i}"] = ("STRING", {"multiline": True, "default": ""})
124 |
125 | optional_inputs = {
126 | "_properties_json": ("STRING", {"multiline": True, "default": "{}"}),
127 | "_preview_anchor": ("STRING", {"multiline": True, "default": "PREVIEW_ANCHOR"}),
128 | }
129 | optional_inputs.update(header_anchors)
130 |
131 | return {
132 | "required": {},
133 | "optional": optional_inputs
134 | }
135 |
136 | RETURN_TYPES = ("IMAGE",)
137 | FUNCTION = "composite_layers"
138 | CATEGORY = "Layer System"
139 |
140 | @classmethod
141 | def IS_CHANGED(cls, **kwargs):
142 | return float("NaN")
143 |
144 | def _blend(self, base, top, mode):
145 | if mode == 'normal': return top
146 | if mode == 'multiply': return base * top
147 | if mode == 'screen': return 1.0 - (1.0 - base) * (1.0 - top)
148 | if mode == 'overlay': return torch.where(base < 0.5, 2.0 * base * top, 1.0 - 2.0 * (1.0 - base) * (1.0 - top))
149 | if mode == 'soft_light': return torch.where(top < 0.5, 2.0 * base * top + base.pow(2.0) * (1.0 - 2.0 * top), torch.sqrt(base) * (2.0 * top - 1.0) + 2.0 * base * (1.0 - top))
150 | if mode == 'hard_light': return torch.where(top < 0.5, 2.0 * top * base, 1.0 - 2.0 * (1.0 - top) * (1.0 - base))
151 | if mode == 'difference': return torch.abs(base - top)
152 | if mode == 'color_dodge':
153 | denominator = 1.0 - top
154 | return torch.where(denominator < 1e-6, torch.ones_like(base), torch.clamp(base / (denominator + 1e-6), 0, 1))
155 | if mode == 'color_burn':
156 | return torch.where(top < 1e-6, torch.zeros_like(base), 1.0 - torch.clamp((1.0 - base) / (top + 1e-6), 0, 1))
157 | return top
158 |
159 | def composite_layers(self, _properties_json="{}", **kwargs):
160 | # print(f"[Layer System DEBUG] JSON reçu par Python: {_properties_json}")
161 | start_preview_server()
162 |
163 | try:
164 | full_properties = json.loads(_properties_json)
165 | except json.JSONDecodeError:
166 | full_properties = {}
167 |
168 | base_props = full_properties.get("base", {})
169 | base_filename = base_props.get("filename")
170 |
171 | if not base_filename:
172 | print("[Layer System] AVERTISSEMENT: Aucune image de base chargée. Retour d'une image vide.")
173 | return {"result": (torch.zeros(1, 512, 512, 3, dtype=torch.float32),)}
174 |
175 | base_image_path = folder_paths.get_annotated_filepath(base_filename)
176 | i = Image.open(base_image_path)
177 | i = ImageOps.exif_transpose(i)
178 | base_image = pil_to_tensor(i)
179 |
180 | final_image = base_image.clone()
181 |
182 | previews_data = {}
183 | temp_dir = folder_paths.get_temp_directory()
184 | B, base_H, base_W, C = base_image.shape
185 |
186 | base_pil = tensor_to_pil(base_image)
187 | base_preview_filename = "layersys_base.png"
188 | base_pil.save(os.path.join(temp_dir, base_preview_filename))
189 | previews_data["base_image"] = {
190 | "url": f"http://127.0.0.1:{PREVIEW_SERVER_PORT}/{base_preview_filename}",
191 | "filename": base_filename
192 | }
193 |
194 | if final_image.shape[-1] == 4:
195 | final_image = final_image[..., :3]
196 |
197 | layers_properties = full_properties.get("layers", {})
198 | sorted_layer_names = sorted(layers_properties.keys(), key=lambda x: int(x.split('_')[1]))
199 |
200 | for layer_name in sorted_layer_names:
201 | props = layers_properties.get(layer_name, {})
202 |
203 | layer_filename = props.get("source_filename")
204 | if not layer_filename:
205 | continue
206 |
207 | layer_image_path = folder_paths.get_annotated_filepath(layer_filename)
208 | i_layer = Image.open(layer_image_path)
209 | i_layer = ImageOps.exif_transpose(i_layer)
210 | layer_image_full = pil_to_tensor(i_layer)
211 |
212 | layer_pil = tensor_to_pil(layer_image_full)
213 | layer_preview_filename_temp = f"layersys_{layer_name}.png"
214 | layer_pil.save(os.path.join(temp_dir, layer_preview_filename_temp))
215 | previews_data[layer_name] = {
216 | "url": f"http://127.0.0.1:{PREVIEW_SERVER_PORT}/{layer_preview_filename_temp}",
217 | "filename": layer_filename
218 | }
219 |
220 | mask = None
221 | internal_mask_filename = props.get("internal_mask_filename")
222 | if internal_mask_filename:
223 | image_path = folder_paths.get_annotated_filepath(internal_mask_filename)
224 | if os.path.exists(image_path):
225 | try:
226 | i = Image.open(image_path)
227 | i = ImageOps.exif_transpose(i)
228 | mask = pil_to_tensor(i)
229 | if mask.shape[-1] > 1:
230 | if mask.shape[-1] == 4:
231 | mask = mask[..., 3:4]
232 | else:
233 | mask = mask[..., 0:1]
234 | mask = 1.0 - mask
235 | except Exception as e:
236 | print(f"[Layer System] ERROR: Unable to load internal mask '{internal_mask_filename}': {e}")
237 | else:
238 | print(f"[Layer System] WARNING: Internal mask file not found: {image_path}")
239 | if mask is not None:
240 | mask_name = layer_name.replace("layer_", "mask_")
241 | mask_preview_filename_temp = f"layersys_{mask_name}.png"
242 | mask_pil_for_preview = tensor_to_pil(mask)
243 | mask_pil_for_preview.convert("RGB").save(os.path.join(temp_dir, mask_preview_filename_temp))
244 |
245 | previews_data[mask_name] = {
246 | "url": f"http://127.0.0.1:{PREVIEW_SERVER_PORT}/{mask_preview_filename_temp}",
247 | "filename": internal_mask_filename
248 | }
249 | if not props.get("enabled", True): continue
250 |
251 | resize_mode = props.get("resize_mode", "fit")
252 | scale = props.get("scale", 1.0)
253 | offset_x = props.get("offset_x", 0)
254 | offset_y = props.get("offset_y", 0)
255 | rotation = props.get("rotation", 0.0)
256 |
257 | prepared_layer = None
258 | layer_alpha = None
259 |
260 | if resize_mode == 'crop' and rotation != 0.0:
261 | pil_layer = tensor_to_pil(layer_image_full)
262 | if pil_layer.mode != 'RGBA':
263 | pil_layer = pil_layer.convert('RGBA')
264 |
265 | new_w = int(pil_layer.width * scale)
266 | new_h = int(pil_layer.height * scale)
267 | if new_w > 0 and new_h > 0:
268 | pil_layer = pil_layer.resize((new_w, new_h), Image.Resampling.BICUBIC)
269 |
270 | pil_layer = pil_layer.rotate(-rotation, resample=Image.Resampling.BICUBIC, expand=True)
271 |
272 | final_canvas_pil = Image.new('RGBA', (base_W, base_H), (0, 0, 0, 0))
273 | paste_x = (base_W // 2) + offset_x - (pil_layer.width // 2)
274 | paste_y = (base_H // 2) + offset_y - (pil_layer.height // 2)
275 |
276 | final_canvas_pil.paste(pil_layer, (paste_x, paste_y), pil_layer)
277 |
278 | prepared_tensor = pil_to_tensor(final_canvas_pil)
279 | prepared_layer = prepared_tensor[..., :3]
280 | layer_alpha = prepared_tensor[..., 3:4]
281 | else:
282 | if layer_image_full.shape[-1] == 4:
283 | layer_alpha = layer_image_full[..., 3:4]
284 | layer_image = layer_image_full[..., :3]
285 | else:
286 | layer_image = layer_image_full
287 |
288 | prepared_layer = prepare_layer(layer_image, final_image, resize_mode, scale, offset_x, offset_y)
289 | if layer_alpha is not None:
290 | prepared_alpha = prepare_layer(layer_alpha, final_image, resize_mode, scale, offset_x, offset_y)
291 | layer_alpha = prepared_alpha
292 |
293 | brightness = props.get("brightness", 0.0)
294 | if brightness != 0.0: prepared_layer = torch.clamp(prepared_layer + brightness, 0.0, 1.0)
295 | contrast = props.get("contrast", 0.0)
296 | if contrast != 0.0:
297 | contrast_factor = 1.0 + contrast
298 | prepared_layer = torch.clamp((prepared_layer - 0.5) * contrast_factor + 0.5, 0.0, 1.0)
299 | color_r, color_g, color_b = props.get("color_r", 1.0), props.get("color_g", 1.0), props.get("color_b", 1.0)
300 | if color_r != 1.0 or color_g != 1.0 or color_b != 1.0:
301 | prepared_layer[..., 0] = torch.clamp(prepared_layer[..., 0] * color_r, 0.0, 1.0)
302 | prepared_layer[..., 1] = torch.clamp(prepared_layer[..., 1] * color_g, 0.0, 1.0)
303 | prepared_layer[..., 2] = torch.clamp(prepared_layer[..., 2] * color_b, 0.0, 1.0)
304 | saturation = props.get("saturation", 1.0)
305 | if saturation != 1.0:
306 | grayscale = prepared_layer[..., 0] * 0.299 + prepared_layer[..., 1] * 0.587 + prepared_layer[..., 2] * 0.114
307 | grayscale = grayscale.unsqueeze(-1)
308 | prepared_layer = torch.clamp(grayscale * (1.0 - saturation) + prepared_layer * saturation, 0.0, 1.0)
309 |
310 | mode = props.get("blend_mode", "normal").replace('-', '_')
311 | opacity = props.get("opacity", 1.0)
312 | blended_image = self._blend(final_image, prepared_layer, mode)
313 |
314 | content_alpha_mask = layer_alpha
315 | if content_alpha_mask is None and resize_mode != 'stretch':
316 | content_alpha_mask = (prepared_layer.sum(dim=-1, keepdim=True) > 0.001).float()
317 |
318 | if content_alpha_mask is not None:
319 | blended_image = final_image * (1.0 - content_alpha_mask) + blended_image * content_alpha_mask
320 |
321 | final_mask = None
322 | if mask is not None:
323 | if mask.dim() == 3: mask = mask.unsqueeze(-1)
324 | if resize_mode == 'crop' and rotation != 0.0:
325 | pil_mask = tensor_to_pil(mask)
326 | if pil_mask.mode != 'L': pil_mask = pil_mask.convert('L')
327 |
328 | mask_w = int(pil_mask.width * scale)
329 | mask_h = int(pil_mask.height * scale)
330 | if mask_w > 0 and mask_h > 0:
331 | pil_mask = pil_mask.resize((mask_w, mask_h), Image.Resampling.BICUBIC)
332 |
333 | if rotation != 0.0:
334 | pil_mask = pil_mask.rotate(-rotation, resample=Image.Resampling.BICUBIC, expand=True)
335 |
336 | mask_canvas_pil = Image.new('L', (base_W, base_H), 0)
337 | mask_paste_x = (base_W // 2) + offset_x - (pil_mask.width // 2)
338 | mask_paste_y = (base_H // 2) + offset_y - (pil_mask.height // 2)
339 | mask_canvas_pil.paste(pil_mask, (mask_paste_x, mask_paste_y))
340 | final_mask = pil_to_tensor(mask_canvas_pil)
341 | else:
342 | final_mask = prepare_layer(mask, final_image, resize_mode, scale, offset_x, offset_y)
343 |
344 | if final_mask is not None:
345 | if final_mask.dim() == 3:
346 | final_mask = final_mask.unsqueeze(-1)
347 | if props.get("invert_mask", False):
348 | final_mask = 1.0 - final_mask
349 |
350 | if final_mask.shape[1:3] != final_image.shape[1:3]:
351 | final_mask = F.interpolate(final_mask.permute(0, 3, 1, 2), size=(base_H, base_W), mode='bilinear', align_corners=False).permute(0, 2, 3, 1)
352 |
353 | final_mask_with_opacity = final_mask * opacity
354 | final_image = final_image * (1.0 - final_mask_with_opacity) + blended_image * final_mask_with_opacity
355 | else:
356 | final_image = (1.0 - opacity) * final_image + blended_image * opacity
357 |
358 | text_elements = full_properties.get("texts", [])
359 | if text_elements:
360 | pil_image = tensor_to_pil(final_image).convert('RGBA')
361 |
362 | image_width = pil_image.width
363 | image_height = pil_image.height
364 | center_x = image_width // 2
365 | center_y = image_height // 2
366 |
367 | text_canvas = Image.new('RGBA', (image_width, image_height), (0, 0, 0, 0))
368 | draw = ImageDraw.Draw(text_canvas)
369 |
370 | import sys
371 | FONT_MAP = {
372 | "Arial": "arial.ttf", "Verdana": "verdana.ttf", "Tahoma": "tahoma.ttf",
373 | "Trebuchet MS": "trebuc.ttf", "Impact": "impact.ttf", "Lucida Sans Unicode": "l_10646.ttf",
374 | "Georgia": "georgia.ttf", "Times New Roman": "times.ttf", "Garamond": "gara.ttf",
375 | "Courier New": "cour.ttf", "Lucida Console": "lucon.ttf"
376 | }
377 | font_dirs = []
378 | if sys.platform == "win32":
379 | font_dirs.append("C:/Windows/Fonts")
380 | elif sys.platform == "darwin":
381 | font_dirs.extend(["/System/Library/Fonts/Supplemental", "/Library/Fonts"])
382 | else:
383 | font_dirs.extend(["/usr/share/fonts/truetype/msttcorefonts", "/usr/share/fonts/truetype/dejavu"])
384 |
385 | def find_font_path(font_name):
386 | font_file = FONT_MAP.get(font_name)
387 | if not font_file: return None
388 | for d in font_dirs:
389 | path = os.path.join(d, font_file)
390 | if os.path.exists(path): return path
391 | return None
392 |
393 | for text_el in text_elements:
394 | text_content = text_el.get("text", "")
395 | if not text_content:
396 | continue
397 |
398 | offset_x = text_el.get("offset_x", 0.0)
399 | offset_y = text_el.get("offset_y", 0.0)
400 | final_size = int(text_el.get("size", 24))
401 |
402 | if final_size <= 0:
403 | continue
404 |
405 | final_x = int(center_x + offset_x)
406 | final_y = int(center_y + offset_y)
407 |
408 | color = text_el.get("color", "#FFFFFF")
409 | font_family = text_el.get("fontFamily", "Arial")
410 |
411 | font_path = find_font_path(font_family)
412 | font = None
413 | try:
414 | if font_path:
415 | font = ImageFont.truetype(font_path, final_size)
416 | else:
417 | print(f"[Layer System] ATTENTION : font '{font_family}' not found. Utilisation de la police par défaut.")
418 | font = ImageFont.load_default()
419 | except Exception as e:
420 | print(f"[Layer System] ERROR: Unable to load font {font_family}: {e}")
421 | font = ImageFont.load_default()
422 |
423 | draw.text((final_x, final_y), text_content, font=font, fill=color, anchor="lt")
424 |
425 | pil_image.alpha_composite(text_canvas)
426 |
427 | final_image = pil_to_tensor(pil_image)
428 | try:
429 | active_files = set()
430 |
431 | if base_props.get("source_filename"):
432 | active_files.add(base_props["source_filename"])
433 | elif base_props.get("filename"):
434 | active_files.add(base_props["filename"])
435 |
436 | for layer_name, props in layers_properties.items():
437 | if props.get("source_filename"):
438 | active_files.add(props["source_filename"])
439 | if props.get("internal_mask_filename"):
440 | active_files.add(props["internal_mask_filename"])
441 | if props.get("internal_preview_mask_details"):
442 | active_files.add(props["internal_preview_mask_details"]["name"])
443 |
444 | input_dir = folder_paths.get_input_directory()
445 | disk_files = glob.glob(os.path.join(input_dir, "layersystem_*.png"))
446 |
447 | for file_path in disk_files:
448 | filename = os.path.basename(file_path)
449 | if filename not in active_files:
450 | #print(f"[Layer System] Cleanup: Deleting the orphaned file {filename}")
451 | os.remove(file_path)
452 |
453 | except Exception as e:
454 | print(f"[Layer System] ERREUR pendant le nettoyage automatique : {e}")
455 |
456 | return {
457 | "result": (final_image,),
458 | "ui": {
459 | "layer_previews": [previews_data]
460 | }
461 | }
462 |
463 | @server.PromptServer.instance.routes.post("/layersystem/remove_bg")
464 | async def remove_background_route(request):
465 | try:
466 | post_data = await request.json()
467 | filename = post_data.get("filename")
468 | layer_index_str = post_data.get("layer_index_str")
469 | if not filename:
470 | return web.Response(status=400, text="Nom de fichier manquant")
471 |
472 | mask_details = process_remove_bg(filename, layer_index_str)
473 |
474 | return web.json_response(mask_details)
475 | except Exception as e:
476 | print(f"[Layer System] ERREUR API remove_bg: {e}")
477 | return web.Response(status=500, text=str(e))
478 |
479 | def process_remove_bg(filename, layer_index_str):
480 | image_path = folder_paths.get_annotated_filepath(filename)
481 | if not os.path.exists(image_path):
482 | raise FileNotFoundError(f"Image source non trouvée dans le dossier input: {filename}")
483 |
484 | input_image = Image.open(image_path)
485 |
486 | image_with_alpha = remove(
487 | input_image,
488 | session=session,
489 | alpha_matting=True,
490 | alpha_matting_foreground_threshold=240,
491 | alpha_matting_background_threshold=10,
492 | alpha_matting_erode_size=14
493 | )
494 |
495 | if image_with_alpha.mode != 'RGBA':
496 | raise ValueError("rembg n'a pas renvoyé une image RGBA attendue.")
497 |
498 | alpha_mask = image_with_alpha.split()[-1]
499 |
500 | preview_mask_image = Image.new("RGB", alpha_mask.size, "black")
501 | preview_mask_image.paste((255, 255, 255), mask=alpha_mask)
502 |
503 | render_mask_image = ImageOps.invert(preview_mask_image.convert("L")).convert("RGB")
504 |
505 | preview_mask_filename = f"internal_mask_preview_{layer_index_str}.png"
506 | preview_mask_path = os.path.join(folder_paths.get_input_directory(), preview_mask_filename)
507 | preview_mask_image.save(preview_mask_path)
508 |
509 | render_mask_filename = f"internal_mask_render_{layer_index_str}.png"
510 | render_mask_path = os.path.join(folder_paths.get_input_directory(), render_mask_filename)
511 | render_mask_image.save(render_mask_path)
512 |
513 | return {
514 | "preview_mask_details": { "name": preview_mask_filename, "subfolder": "", "type": "input" },
515 | "render_mask_details": { "name": render_mask_filename, "subfolder": "", "type": "input" }
516 | }
517 |
518 | @server.PromptServer.instance.routes.post("/layersystem/delete_file")
519 | async def delete_file_route(request):
520 | try:
521 | post_data = await request.json()
522 | filename = post_data.get("filename")
523 | subfolder = post_data.get("subfolder", "")
524 |
525 | if not filename:
526 | return web.Response(status=400, text="Nom de fichier manquant")
527 |
528 | input_dir = folder_paths.get_input_directory()
529 | file_path = os.path.join(input_dir, subfolder, filename)
530 |
531 | if os.path.commonpath([input_dir]) != os.path.commonpath([input_dir, file_path]):
532 | return web.Response(status=403, text="Accès interdit")
533 |
534 | if os.path.exists(file_path):
535 | os.remove(file_path)
536 | print(f"[Layer System] deleted file : {file_path}")
537 | return web.json_response({"success": True, "message": f"file {filename} supprimé."})
538 | else:
539 | return web.json_response({"success": False, "message": "file not found."}, status=404)
540 |
541 | except Exception as e:
542 | print(f"[Layer System] ERREUR API delete_file: {e}")
543 | return web.Response(status=500, text=str(e))
544 |
545 | @server.PromptServer.instance.routes.post("/layersystem/magic_wand")
546 | async def magic_wand_route(request):
547 | try:
548 | data = await request.json()
549 | filename = data.get("filename")
550 | start_x, start_y = data.get("x"), data.get("y")
551 | tolerance = data.get("tolerance", 32)
552 | contiguous = data.get("contiguous", True)
553 |
554 | image_path = folder_paths.get_annotated_filepath(filename)
555 | img_pil = Image.open(image_path).convert("RGB")
556 |
557 | pixels = np.array(img_pil)
558 | h, w, _ = pixels.shape
559 |
560 | start_color = pixels[start_y, start_x].astype(np.float32)
561 | pixels_float = pixels.astype(np.float32)
562 |
563 | if contiguous:
564 | mask = np.zeros((h, w), dtype=np.uint8)
565 | q = [(start_y, start_x)]
566 | visited = set([(start_y, start_x)])
567 | while len(q) > 0:
568 | y, x = q.pop(0)
569 | color_diff = np.sqrt(np.sum((pixels_float[y, x] - start_color) ** 2))
570 | if color_diff <= tolerance:
571 | mask[y, x] = 255
572 | for dx, dy in [(0, 1), (0, -1), (1, 0), (-1, 0)]:
573 | nx, ny = x + dx, y + dy
574 | if 0 <= nx < w and 0 <= ny < h and (ny, nx) not in visited:
575 | q.append((ny, nx))
576 | visited.add((ny, nx))
577 | else:
578 | color_diffs = np.sqrt(np.sum((pixels_float - start_color) ** 2, axis=2))
579 | mask = (color_diffs <= tolerance).astype(np.uint8) * 255
580 |
581 | mask_pil = Image.fromarray(mask, mode="L")
582 | mask_timestamp = int(time.time() * 1000)
583 | mask_filename = f"layersystem_mask_{mask_timestamp}.png"
584 |
585 | output_dir = folder_paths.get_input_directory()
586 | mask_pil.save(os.path.join(output_dir, mask_filename), "PNG")
587 |
588 | return web.json_response({
589 | "success": True,
590 | "mask_details": { "name": mask_filename, "subfolder": "", "type": "input" }
591 | })
592 |
593 |
594 |
595 | except Exception as e:
596 | import traceback
597 | print(f"[Layer System] ERREUR API magic_wand: {e}")
598 | traceback.print_exc()
599 | return web.Response(status=500, text=str(e))
600 |
601 | @server.PromptServer.instance.routes.post("/layersystem/apply_mask")
602 | async def apply_mask_route(request):
603 | try:
604 | data = await request.json()
605 | new_mask_details = data.get("new_mask_details")
606 | existing_mask_filename = data.get("existing_mask_filename")
607 | fusion_mode = data.get("fusion_mode", "add")
608 | layer_index = data.get("layer_index")
609 |
610 | if not new_mask_details or layer_index is None:
611 | return web.Response(status=400, text="Données manquantes")
612 |
613 | new_mask_path = folder_paths.get_annotated_filepath(new_mask_details.get("name"))
614 | new_mask_pil = Image.open(new_mask_path).convert("L")
615 |
616 | if existing_mask_filename:
617 | fusion_source_filename = existing_mask_filename
618 | if "_render_" in existing_mask_filename:
619 | fusion_source_filename = existing_mask_filename.replace("_render_", "_preview_")
620 |
621 | existing_mask_path = folder_paths.get_annotated_filepath(fusion_source_filename)
622 |
623 | if os.path.exists(existing_mask_path):
624 | existing_mask_pil_raw = Image.open(existing_mask_path)
625 | if 'A' in existing_mask_pil_raw.getbands():
626 | alpha_channel = existing_mask_pil_raw.getchannel('A')
627 | existing_mask_pille = Image.fromarray((np.array(alpha_channel) > 128).astype(np.uint8) * 255)
628 | existing_mask_pil = ImageOps.invert(existing_mask_pille.convert("L"))
629 | else:
630 | existing_mask_pil = existing_mask_pil_raw.convert("L")
631 | else:
632 | existing_mask_pil = Image.new("L", new_mask_pil.size, "black")
633 | else:
634 | existing_mask_pil = Image.new("L", new_mask_pil.size, "white")
635 |
636 | if existing_mask_pil.size != new_mask_pil.size:
637 | new_mask_pil = new_mask_pil.resize(existing_mask_pil.size, Image.LANCZOS)
638 |
639 | existing_arr = np.array(existing_mask_pil)
640 | new_arr = np.array(new_mask_pil)
641 |
642 | if fusion_mode == "add": combined_arr = np.maximum(existing_arr, new_arr)
643 | elif fusion_mode == "subtract": combined_arr = np.maximum(existing_arr - new_arr, 0)
644 | elif fusion_mode == "intersect": combined_arr = np.minimum(existing_arr, new_arr)
645 | else: combined_arr = np.maximum(existing_arr, new_arr)
646 |
647 | final_preview_pil = Image.fromarray(combined_arr, mode="L")
648 |
649 | output_dir = folder_paths.get_input_directory()
650 | editor_filename = f"internal_mask_{layer_index}.png"
651 | preview_filename = f"internal_mask_preview_{layer_index}.png"
652 | render_filename = f"internal_mask_render_{layer_index}.png"
653 |
654 | final_render_pil = ImageOps.invert(final_preview_pil.convert("L")).convert("RGB")
655 |
656 | final_preview_pil.save(os.path.join(output_dir, editor_filename), "PNG")
657 | final_preview_pil.save(os.path.join(output_dir, preview_filename), "PNG")
658 | final_render_pil.save(os.path.join(output_dir, render_filename), "PNG")
659 |
660 | return web.json_response({
661 | "success": True,
662 | "editor_mask_details": { "name": editor_filename, "subfolder": "", "type": "input" },
663 | "preview_mask_details": { "name": preview_filename, "subfolder": "", "type": "input" },
664 | "render_mask_details": { "name": render_filename, "subfolder": "", "type": "input" }
665 | })
666 |
667 | except Exception as e:
668 | import traceback
669 | print(f"[Layer System] ERREUR API apply_mask: {e}")
670 | traceback.print_exc()
671 | return web.Response(status=500, text=str(e))
672 |
673 | @server.PromptServer.instance.routes.post("/layersystem/refresh_previews")
674 | async def refresh_previews_route(request):
675 | try:
676 | post_data = await request.json()
677 | properties_json = post_data.get("properties_json")
678 |
679 | layer_system_instance = LayerSystem()
680 |
681 | ui_data = layer_system_instance.composite_layers(_properties_json=properties_json)
682 |
683 | return web.json_response(ui_data.get("ui", {}))
684 |
685 | except Exception as e:
686 | print(f"[Layer System] ERREUR API refresh_previews: {e}")
687 | return web.Response(status=500, text=str(e))
688 |
689 | @server.PromptServer.instance.routes.post("/layersystem/finalize_painter_mask")
690 | async def finalize_painter_mask_route(request):
691 | try:
692 | data = await request.json()
693 | temp_alpha_mask_details = data.get("alpha_mask_details")
694 | layer_index = data.get("layer_index")
695 |
696 | if not temp_alpha_mask_details or layer_index is None:
697 | return web.Response(status=400, text="Données manquantes")
698 |
699 | alpha_mask_path = folder_paths.get_annotated_filepath(temp_alpha_mask_details["name"])
700 | alpha_mask_pil = Image.open(alpha_mask_path)
701 | alpha_channel = alpha_mask_pil.getchannel('A')
702 |
703 | preview_mask_pil = Image.new("RGB", alpha_channel.size, "black")
704 | preview_mask_pil.paste((255, 255, 255), mask=alpha_channel)
705 |
706 | render_mask_pil = ImageOps.invert(preview_mask_pil.convert("L")).convert("RGB")
707 |
708 | output_dir = folder_paths.get_input_directory()
709 |
710 | preview_filename = f"internal_mask_preview_{layer_index}.png"
711 | render_filename = f"internal_mask_render_{layer_index}.png"
712 |
713 | preview_mask_pil.save(os.path.join(output_dir, preview_filename), "PNG")
714 | render_mask_pil.save(os.path.join(output_dir, render_filename), "PNG")
715 |
716 | if os.path.exists(alpha_mask_path):
717 | os.remove(alpha_mask_path)
718 |
719 | return web.json_response({
720 | "success": True,
721 | "preview_mask_details": { "name": preview_filename, "subfolder": "", "type": "input" },
722 | "render_mask_details": { "name": render_filename, "subfolder": "", "type": "input" }
723 | })
724 |
725 | except Exception as e:
726 | import traceback
727 | print(f"[Layer System] ERREUR API finalize_painter_mask: {e}")
728 | traceback.print_exc()
729 | return web.Response(status=500, text=str(e))
730 |
731 |
732 | NODE_CLASS_MAPPINGS = { "LayerSystem": LayerSystem }
733 |
734 | NODE_DISPLAY_NAME_MAPPINGS = { "LayerSystem": "Layers System" }
735 |
736 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU General Public License is a free, copyleft license for
11 | software and other kinds of works.
12 |
13 | The licenses for most software and other practical works are designed
14 | to take away your freedom to share and change the works. By contrast,
15 | the GNU General Public License is intended to guarantee your freedom to
16 | share and change all versions of a program--to make sure it remains free
17 | software for all its users. We, the Free Software Foundation, use the
18 | GNU General Public License for most of our software; it applies also to
19 | any other work released this way by its authors. You can apply it to
20 | your programs, too.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | To protect your rights, we need to prevent others from denying you
30 | these rights or asking you to surrender the rights. Therefore, you have
31 | certain responsibilities if you distribute copies of the software, or if
32 | you modify it: responsibilities to respect the freedom of others.
33 |
34 | For example, if you distribute copies of such a program, whether
35 | gratis or for a fee, you must pass on to the recipients the same
36 | freedoms that you received. You must make sure that they, too, receive
37 | or can get the source code. And you must show them these terms so they
38 | know their rights.
39 |
40 | Developers that use the GNU GPL protect your rights with two steps:
41 | (1) assert copyright on the software, and (2) offer you this License
42 | giving you legal permission to copy, distribute and/or modify it.
43 |
44 | For the developers' and authors' protection, the GPL clearly explains
45 | that there is no warranty for this free software. For both users' and
46 | authors' sake, the GPL requires that modified versions be marked as
47 | changed, so that their problems will not be attributed erroneously to
48 | authors of previous versions.
49 |
50 | Some devices are designed to deny users access to install or run
51 | modified versions of the software inside them, although the manufacturer
52 | can do so. This is fundamentally incompatible with the aim of
53 | protecting users' freedom to change the software. The systematic
54 | pattern of such abuse occurs in the area of products for individuals to
55 | use, which is precisely where it is most unacceptable. Therefore, we
56 | have designed this version of the GPL to prohibit the practice for those
57 | products. If such problems arise substantially in other domains, we
58 | stand ready to extend this provision to those domains in future versions
59 | of the GPL, as needed to protect the freedom of users.
60 |
61 | Finally, every program is threatened constantly by software patents.
62 | States should not allow patents to restrict development and use of
63 | software on general-purpose computers, but in those that do, we wish to
64 | avoid the special danger that patents applied to a free program could
65 | make it effectively proprietary. To prevent this, the GPL assures that
66 | patents cannot be used to render the program non-free.
67 |
68 | The precise terms and conditions for copying, distribution and
69 | modification follow.
70 |
71 | TERMS AND CONDITIONS
72 |
73 | 0. Definitions.
74 |
75 | "This License" refers to version 3 of the GNU General Public License.
76 |
77 | "Copyright" also means copyright-like laws that apply to other kinds of
78 | works, such as semiconductor masks.
79 |
80 | "The Program" refers to any copyrightable work licensed under this
81 | License. Each licensee is addressed as "you". "Licensees" and
82 | "recipients" may be individuals or organizations.
83 |
84 | To "modify" a work means to copy from or adapt all or part of the work
85 | in a fashion requiring copyright permission, other than the making of an
86 | exact copy. The resulting work is called a "modified version" of the
87 | earlier work or a work "based on" the earlier work.
88 |
89 | A "covered work" means either the unmodified Program or a work based
90 | on the Program.
91 |
92 | To "propagate" a work means to do anything with it that, without
93 | permission, would make you directly or secondarily liable for
94 | infringement under applicable copyright law, except executing it on a
95 | computer or modifying a private copy. Propagation includes copying,
96 | distribution (with or without modification), making available to the
97 | public, and in some countries other activities as well.
98 |
99 | To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies. Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 |
103 | An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License. If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 |
112 | 1. Source Code.
113 |
114 | The "source code" for a work means the preferred form of the work
115 | for making modifications to it. "Object code" means any non-source
116 | form of a work.
117 |
118 | A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 |
123 | The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form. A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 |
134 | The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities. However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work. For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 |
147 | The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 |
151 | The Corresponding Source for a work in source code form is that
152 | same work.
153 |
154 | 2. Basic Permissions.
155 |
156 | All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met. This License explicitly affirms your unlimited
159 | permission to run the unmodified Program. The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work. This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 |
164 | You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force. You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright. Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 |
175 | Conveying under any other circumstances is permitted solely under
176 | the conditions stated below. Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 |
179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 |
181 | No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 |
187 | When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 |
195 | 4. Conveying Verbatim Copies.
196 |
197 | You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 |
205 | You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 |
208 | 5. Conveying Modified Source Versions.
209 |
210 | You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 |
214 | a) The work must carry prominent notices stating that you modified
215 | it, and giving a relevant date.
216 |
217 | b) The work must carry prominent notices stating that it is
218 | released under this License and any conditions added under section
219 | 7. This requirement modifies the requirement in section 4 to
220 | "keep intact all notices".
221 |
222 | c) You must license the entire work, as a whole, under this
223 | License to anyone who comes into possession of a copy. This
224 | License will therefore apply, along with any applicable section 7
225 | additional terms, to the whole of the work, and all its parts,
226 | regardless of how they are packaged. This License gives no
227 | permission to license the work in any other way, but it does not
228 | invalidate such permission if you have separately received it.
229 |
230 | d) If the work has interactive user interfaces, each must display
231 | Appropriate Legal Notices; however, if the Program has interactive
232 | interfaces that do not display Appropriate Legal Notices, your
233 | work need not make them do so.
234 |
235 | A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit. Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 |
245 | 6. Conveying Non-Source Forms.
246 |
247 | You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 |
252 | a) Convey the object code in, or embodied in, a physical product
253 | (including a physical distribution medium), accompanied by the
254 | Corresponding Source fixed on a durable physical medium
255 | customarily used for software interchange.
256 |
257 | b) Convey the object code in, or embodied in, a physical product
258 | (including a physical distribution medium), accompanied by a
259 | written offer, valid for at least three years and valid for as
260 | long as you offer spare parts or customer support for that product
261 | model, to give anyone who possesses the object code either (1) a
262 | copy of the Corresponding Source for all the software in the
263 | product that is covered by this License, on a durable physical
264 | medium customarily used for software interchange, for a price no
265 | more than your reasonable cost of physically performing this
266 | conveying of source, or (2) access to copy the
267 | Corresponding Source from a network server at no charge.
268 |
269 | c) Convey individual copies of the object code with a copy of the
270 | written offer to provide the Corresponding Source. This
271 | alternative is allowed only occasionally and noncommercially, and
272 | only if you received the object code with such an offer, in accord
273 | with subsection 6b.
274 |
275 | d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 |
288 | e) Convey the object code using peer-to-peer transmission, provided
289 | you inform other peers where the object code and Corresponding
290 | Source of the work are being offered to the general public at no
291 | charge under subsection 6d.
292 |
293 | A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 |
297 | A "User Product" is either (1) a "consumer product", which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling. In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage. For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product. A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 |
310 | "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source. The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed. Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 |
337 | Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 |
343 | 7. Additional Terms.
344 |
345 | "Additional permissions" are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law. If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 |
354 | When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it. (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.) You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 |
361 | Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 |
365 | a) Disclaiming warranty or limiting liability differently from the
366 | terms of sections 15 and 16 of this License; or
367 |
368 | b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 |
372 | c) Prohibiting misrepresentation of the origin of that material, or
373 | requiring that modified versions of such material be marked in
374 | reasonable ways as different from the original version; or
375 |
376 | d) Limiting the use for publicity purposes of names of licensors or
377 | authors of the material; or
378 |
379 | e) Declining to grant rights under trademark law for use of some
380 | trade names, trademarks, or service marks; or
381 |
382 | f) Requiring indemnification of licensors and authors of that
383 | material by anyone who conveys the material (or modified versions of
384 | it) with contractual assumptions of liability to the recipient, for
385 | any liability that these contractual assumptions directly impose on
386 | those licensors and authors.
387 |
388 | All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10. If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term. If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 |
398 | If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 |
403 | Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 |
407 | 8. Termination.
408 |
409 | You may not propagate or modify a covered work except as expressly
410 | provided under this License. Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 |
415 | However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 |
422 | Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 |
429 | Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License. If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 |
435 | 9. Acceptance Not Required for Having Copies.
436 |
437 | You are not required to accept this License in order to receive or
438 | run a copy of the Program. Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance. However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work. These actions infringe copyright if you do
443 | not accept this License. Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 |
446 | 10. Automatic Licensing of Downstream Recipients.
447 |
448 | Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License. You are not responsible
451 | for enforcing compliance by third parties with this License.
452 |
453 | An "entity transaction" is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations. If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 |
463 | You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License. For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 |
471 | 11. Patents.
472 |
473 | A "contributor" is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based. The
475 | work thus licensed is called the contributor's "contributor version".
476 |
477 | A contributor's "essential patent claims" are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version. For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 |
487 | Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 |
492 | In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement). To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 |
499 | If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients. "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 |
513 | If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 |
521 | A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License. You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 |
536 | Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 |
540 | 12. No Surrender of Others' Freedom.
541 |
542 | If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License. If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all. For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 |
552 | 13. Use with the GNU Affero General Public License.
553 |
554 | Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work. The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 |
563 | 14. Revised Versions of this License.
564 |
565 | The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time. Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 |
570 | Each version is given a distinguishing version number. If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation. If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 |
579 | If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 |
584 | Later license versions may give you additional or different
585 | permissions. However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 |
589 | 15. Disclaimer of Warranty.
590 |
591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 |
600 | 16. Limitation of Liability.
601 |
602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 |
612 | 17. Interpretation of Sections 15 and 16.
613 |
614 | If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 |
621 | END OF TERMS AND CONDITIONS
622 |
623 | How to Apply These Terms to Your New Programs
624 |
625 | If you develop a new program, and you want it to be of the greatest
626 | possible use to the public, the best way to achieve this is to make it
627 | free software which everyone can redistribute and change under these terms.
628 |
629 | To do so, attach the following notices to the program. It is safest
630 | to attach them to the start of each source file to most effectively
631 | state the exclusion of warranty; and each file should have at least
632 | the "copyright" line and a pointer to where the full notice is found.
633 |
634 |
635 | Copyright (C)
636 |
637 | This program is free software: you can redistribute it and/or modify
638 | it under the terms of the GNU General Public License as published by
639 | the Free Software Foundation, either version 3 of the License, or
640 | (at your option) any later version.
641 |
642 | This program is distributed in the hope that it will be useful,
643 | but WITHOUT ANY WARRANTY; without even the implied warranty of
644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645 | GNU General Public License for more details.
646 |
647 | You should have received a copy of the GNU General Public License
648 | along with this program. If not, see .
649 |
650 | Also add information on how to contact you by electronic and paper mail.
651 |
652 | If the program does terminal interaction, make it output a short
653 | notice like this when it starts in an interactive mode:
654 |
655 | Copyright (C)
656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 | This is free software, and you are welcome to redistribute it
658 | under certain conditions; type `show c' for details.
659 |
660 | The hypothetical commands `show w' and `show c' should show the appropriate
661 | parts of the General Public License. Of course, your program's commands
662 | might be different; for a GUI interface, you would use an "about box".
663 |
664 | You should also get your employer (if you work as a programmer) or school,
665 | if any, to sign a "copyright disclaimer" for the program, if necessary.
666 | For more information on this, and how to apply and follow the GNU GPL, see
667 | .
668 |
669 | The GNU General Public License does not permit incorporating your program
670 | into proprietary programs. If your program is a subroutine library, you
671 | may consider it more useful to permit linking proprietary applications with
672 | the library. If this is what you want to do, use the GNU Lesser General
673 | Public License instead of this License. But first, please read
674 | .
675 |
--------------------------------------------------------------------------------