-
Notifications
You must be signed in to change notification settings - Fork 4
/
main.js
2173 lines (1885 loc) · 56.2 KB
/
main.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// comfyui API
class ComfyApi extends EventTarget {
#registered = new Set()
constructor () {
super()
this.api_host = location.host
this.api_base = location.pathname.split('/').slice(0, -1).join('/')
this.protocol = location.protocol
}
apiURL (route) {
return this.api_base + route
}
fetchApi (route, options) {
if (!options) {
options = {}
}
if (!options.headers) {
options.headers = {}
}
options.headers['Comfy-User'] = this.user
return fetch(this.apiURL(route), options)
}
addEventListener (type, callback, options) {
super.addEventListener(type, callback, options)
this.#registered.add(type)
}
/**
* Poll status for colab and other things that don't support websockets.
*/
#pollQueue () {
this._pollQueueInterval = setInterval(async () => {
try {
const resp = await this.fetchApi('/prompt')
const status = await resp.json()
this.dispatchEvent(new CustomEvent('status', { detail: status }))
} catch (error) {
this.dispatchEvent(new CustomEvent('status', { detail: null }))
}
}, 1000)
}
/**
* Creates and connects a WebSocket for realtime updates
* @param {boolean} isReconnect If the socket is connection is a reconnect attempt
*/
#createSocket (isReconnect) {
if (this.socket) {
return
}
let opened = false
let existingSession = window.name || ''
if (existingSession) {
existingSession = '?clientId=' + existingSession
}
this.socket = new WebSocket(
`ws${this.protocol === 'https:' ? 's' : ''}://${this.api_host}${
this.api_base
}/ws${existingSession}`
)
console.log(
`ws${this.protocol === 'https:' ? 's' : ''}://${this.api_host}${
this.api_base
}/ws${existingSession}`
)
this.socket.binaryType = 'arraybuffer'
this.socket.addEventListener('open', () => {
opened = true
if (isReconnect) {
this.dispatchEvent(new CustomEvent('reconnected'))
}
})
this.socket.addEventListener('error', () => {
this.socket = null
this.dispatchEvent(new CustomEvent('status', { detail: null }))
// try {
// if (this.socket) {
// this.socket.close()
// }
// if (!isReconnect && !opened) {
// // this.#pollQueue()
// }
// } catch (error) {
// console.log('error',error)
// this.socket=null;
// this.dispatchEvent(new CustomEvent('status', { detail: null }));
// }
})
this.socket.addEventListener('close', () => {
console.log('close', this.socket)
if (this.socket) {
setTimeout(() => {
this.socket = null
this.#createSocket(true)
}, 300)
}
if (opened) {
this.dispatchEvent(new CustomEvent('status', { detail: null }))
this.dispatchEvent(new CustomEvent('reconnecting'))
}
})
this.socket.addEventListener('message', event => {
try {
if (event.data instanceof ArrayBuffer) {
const view = new DataView(event.data)
const eventType = view.getUint32(0)
const buffer = event.data.slice(4)
switch (eventType) {
case 1:
const view2 = new DataView(event.data)
const imageType = view2.getUint32(0)
let imageMime
switch (imageType) {
case 1:
default:
imageMime = 'image/jpeg'
break
case 2:
imageMime = 'image/png'
}
const imageBlob = new Blob([buffer.slice(4)], { type: imageMime })
this.dispatchEvent(
new CustomEvent('b_preview', { detail: imageBlob })
)
break
default:
throw new Error(
`Unknown binary websocket message of type ${eventType}`
)
}
} else {
const msg = JSON.parse(event.data)
switch (msg.type) {
case 'status':
if (msg.data.sid) {
this.clientId = msg.data.sid
window.name = this.clientId
}
this.dispatchEvent(
new CustomEvent('status', { detail: msg.data.status })
)
break
case 'progress':
this.dispatchEvent(
new CustomEvent('progress', { detail: msg.data })
)
break
case 'executing':
this.dispatchEvent(
new CustomEvent('executing', { detail: msg.data.node })
)
break
case 'executed':
this.dispatchEvent(
new CustomEvent('executed', { detail: msg.data })
)
break
case 'execution_start':
this.dispatchEvent(
new CustomEvent('execution_start', { detail: msg.data })
)
break
case 'execution_error':
this.dispatchEvent(
new CustomEvent('execution_error', { detail: msg.data })
)
break
case 'execution_cached':
this.dispatchEvent(
new CustomEvent('execution_cached', { detail: msg.data })
)
break
default:
if (this.#registered.has(msg.type)) {
this.dispatchEvent(
new CustomEvent(msg.type, { detail: msg.data })
)
} else {
throw new Error(`Unknown message type ${msg.type}`)
}
}
}
} catch (error) {
console.warn('Unhandled message:', event.data, error)
}
})
}
/**
* Initialises sockets and realtime updates
*/
init () {
// console.log('#init',this.protocol,this.api_host)
this.#createSocket()
}
/**
* Gets a list of extension urls
* @returns An array of script urls to import
*/
async getExtensions () {
const resp = await this.fetchApi('/extensions', { cache: 'no-store' })
return await resp.json()
}
/**
* Gets a list of embedding names
* @returns An array of script urls to import
*/
async getEmbeddings () {
const resp = await this.fetchApi('/embeddings', { cache: 'no-store' })
return await resp.json()
}
/**
* Loads node object definitions for the graph
* @returns The node definitions
*/
async getNodeDefs () {
const resp = await this.fetchApi('/object_info', { cache: 'no-store' })
return await resp.json()
}
/**
*
* @param {number} number The index at which to queue the prompt, passing -1 will insert the prompt at the front of the queue
* @param {object} prompt The prompt data to queue
*/
async queuePrompt (number, { output, workflow }) {
const body = {
client_id: this.clientId,
prompt: output,
extra_data: { extra_pnginfo: { workflow } }
}
if (number === -1) {
body.front = true
} else if (number != 0) {
body.number = number
}
const res = await this.fetchApi('/prompt', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(body)
})
if (res.status !== 200) {
throw {
response: await res.json()
}
}
return await res.json()
}
/**
* Loads a list of items (queue or history)
* @param {string} type The type of items to load, queue or history
* @returns The items of the specified type grouped by their status
*/
async getItems (type) {
if (type === 'queue') {
return this.getQueue()
}
return this.getHistory()
}
/**
* Gets the current state of the queue
* @returns The currently running and queued items
*/
async getQueue () {
try {
const res = await this.fetchApi('/queue')
const data = await res.json()
return {
// Running action uses a different endpoint for cancelling
Running: data.queue_running.map(prompt => ({
prompt,
remove: { name: 'Cancel', cb: () => api.interrupt() }
})),
Pending: data.queue_pending.map(prompt => ({ prompt }))
}
} catch (error) {
console.error(error)
return { Running: [], Pending: [] }
}
}
/**
* Gets the prompt execution history
* @returns Prompt history including node outputs
*/
async getHistory (max_items = 200) {
try {
const res = await this.fetchApi(`/history?max_items=${max_items}`)
return { History: Object.values(await res.json()) }
} catch (error) {
console.error(error)
return { History: [] }
}
}
/**
* Gets system & device stats
* @returns System stats such as python version, OS, per device info
*/
async getSystemStats () {
const res = await this.fetchApi('/system_stats')
return await res.json()
}
/**
* Sends a POST request to the API
* @param {*} type The endpoint to post to
* @param {*} body Optional POST data
*/
async #postItem (type, body) {
try {
await this.fetchApi('/' + type, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: body ? JSON.stringify(body) : undefined
})
} catch (error) {
console.error(error)
}
}
/**
* Deletes an item from the specified list
* @param {string} type The type of item to delete, queue or history
* @param {number} id The id of the item to delete
*/
async deleteItem (type, id) {
await this.#postItem(type, { delete: [id] })
}
/**
* Clears the specified list
* @param {string} type The type of list to clear, queue or history
*/
async clearItems (type) {
await this.#postItem(type, { clear: true })
}
/**
* Interrupts the execution of the running prompt
*/
async interrupt () {
await this.#postItem('interrupt', null)
}
/**
* Gets user configuration data and where data should be stored
* @returns { Promise<{ storage: "server" | "browser", users?: Promise<string, unknown>, migrated?: boolean }> }
*/
async getUserConfig () {
return (await this.fetchApi('/users')).json()
}
/**
* Creates a new user
* @param { string } username
* @returns The fetch response
*/
createUser (username) {
return this.fetchApi('/users', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ username })
})
}
/**
* Gets all setting values for the current user
* @returns { Promise<string, unknown> } A dictionary of id -> value
*/
async getSettings () {
return (await this.fetchApi('/settings')).json()
}
/**
* Gets a setting for the current user
* @param { string } id The id of the setting to fetch
* @returns { Promise<unknown> } The setting value
*/
async getSetting (id) {
return (await this.fetchApi(`/settings/${encodeURIComponent(id)}`)).json()
}
/**
* Stores a dictionary of settings for the current user
* @param { Record<string, unknown> } settings Dictionary of setting id -> value to save
* @returns { Promise<void> }
*/
async storeSettings (settings) {
return this.fetchApi(`/settings`, {
method: 'POST',
body: JSON.stringify(settings)
})
}
/**
* Stores a setting for the current user
* @param { string } id The id of the setting to update
* @param { unknown } value The value of the setting
* @returns { Promise<void> }
*/
async storeSetting (id, value) {
return this.fetchApi(`/settings/${encodeURIComponent(id)}`, {
method: 'POST',
body: JSON.stringify(value)
})
}
/**
* Gets a user data file for the current user
* @param { string } file The name of the userdata file to load
* @param { RequestInit } [options]
* @returns { Promise<unknown> } The fetch response object
*/
async getUserData (file, options) {
return this.fetchApi(`/userdata/${encodeURIComponent(file)}`, options)
}
/**
* Stores a user data file for the current user
* @param { string } file The name of the userdata file to save
* @param { unknown } data The data to save to the file
* @param { RequestInit & { stringify?: boolean, throwOnError?: boolean } } [options]
* @returns { Promise<void> }
*/
async storeUserData (
file,
data,
options = { stringify: true, throwOnError: true }
) {
const resp = await this.fetchApi(`/userdata/${encodeURIComponent(file)}`, {
method: 'POST',
body: options?.stringify ? JSON.stringify(data) : data,
...options
})
if (resp.status !== 200) {
throw new Error(
`Error storing user data file '${file}': ${resp.status} ${
(await resp).statusText
}`
)
}
}
}
const { entrypoints } = require('uxp')
const { localFileSystem: fs, fileTypes, formats } = require('uxp').storage
const { app: photoshop, constants } = require('photoshop')
// const imaging = require('photoshop').imaging //此api不存在
const { executeAsModal } = require('photoshop').core
const batchPlay = require('photoshop').action.batchPlay
const Jimp = require('./lib/jimp.min.js')
const base64Df =
'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAwAAAAMCAYAAABWdVznAAAAAXNSR0IArs4c6QAAALZJREFUKFOFkLERwjAQBPdbgBkInECGaMLUQDsE0AkRVRAYWqAByxldPPOWHwnw4OBGye1p50UDSoA+W2ABLPN7i+C5dyC6R/uiAUXRQCs0bXoNIu4QPQzAxDKxHoALOrZcqtiyR/T6CXw7+3IGHhkYcy6BOR2izwT8LptG8rbMiCRAUb+CQ6WzQVb0SNOi5Z2/nX35DRyb/ENazhpWKoGwrpD6nICp5c2qogc4of+c7QcrhgF4Aa/aoAFHiL+RAAAAAElFTkSuQmCC'
// 当前的workflow
window.app = null
let hostUrl = 'http://127.0.0.1:8188'
function createSetup (parentElement) {
let heading = document.createElement('sp-heading')
heading.innerHTML = `<span class="status"></span>`
parentElement.appendChild(heading)
const [div, textInput] = createTextInput('Host Url', hostUrl, true)
parentElement.appendChild(div)
textInput.addEventListener('change', e => {
hostUrl = textInput.value
const appDom = document.getElementById('apps')
appDom.innerText = ''
const mainDom = document.getElementById('main')
mainDom.innerText = ''
if (window.api?._pollQueueInterval)
clearInterval(window.api._pollQueueInterval)
window.api = null
btn.style.background = 'normal'
})
let footer = document.createElement('footer')
parentElement.appendChild(footer)
let btn = document.createElement('sp-button')
btn.innerText = 'Load ComfyUI App'
btn.addEventListener('click', async () => {
btn.style.background = 'darkblue'
// console.log(await navigator.clipboard.read());
showAppsNames()
// setTimeout(()=>btn.style.background='normal',1500)
})
footer.appendChild(btn)
}
function handleFlyout (id) {
if (id === 'about') {
document.querySelector('dialog').showModal()
}
}
entrypoints.setup({
panels: {
mixlab_app: {
show (node) {
// console.log(node)
}
},
setup: {
show (node) {
createSetup(node)
// console.log(node)
}
}
// menuItems: [
// {id: "about", label: "about"},
// // {id: "mixlab_app", label: "Mixlab App"},
// ],
// invokeMenu(id) {
// handleFlyout(id);
// }
}
})
async function arrayBufferToFile (arrayBuffer, image_name = 'output_image.png') {
// const img = _base64ToArrayBuffer(b64Image)
const img = arrayBuffer
const img_name = image_name
const folder = await fs.getTemporaryFolder()
const file = await folder.createFile(img_name, { overwrite: true })
await file.write(img, { format: formats.binary })
const token = await fs.createSessionToken(file) // batchPlay requires a token on _path
let place_event_result
let imported_layer
await executeAsModal(async () => {
const result = await batchPlay(
[
{
_obj: 'placeEvent',
// ID: 6,
null: {
_path: token,
_kind: 'local'
},
freeTransformCenterState: {
_enum: 'quadCenterState',
_value: 'QCSAverage'
},
offset: {
_obj: 'offset',
horizontal: {
_unit: 'pixelsUnit',
_value: 0
},
vertical: {
_unit: 'pixelsUnit',
_value: 0
}
},
_isCommand: true,
_options: {
dialogOptions: 'dontDisplay'
}
}
],
{
synchronousExecution: true,
modalBehavior: 'execute'
}
)
console.log('placeEmbedd batchPlay result: ', result)
place_event_result = result[0]
imported_layer = await photoshop.activeDocument.activeLayers[0]
})
return imported_layer
// return place_event_result
}
// 创建下拉选择
function createSelect (options, defaultValue) {
var selectElement = document.createElement('select')
selectElement.className = 'select'
// 循环遍历选项数组
for (var i = 0; i < options.length; i++) {
var option = document.createElement('option')
option.value = options[i].value
option.innerText = options[i].text
selectElement.appendChild(option)
// if(options[i].selected)
}
// 设置默认值
selectElement.value = defaultValue
// console.log(defaultValue, options)
return selectElement
}
// 创建下拉选择 - 带说明
function createSelectWithOptions (title, options, defaultValue) {
const div = document.createElement('div')
div.className = 'card'
// Create a label for the upload control
const nameLabel = document.createElement('label')
nameLabel.textContent = title
div.appendChild(nameLabel)
var selectElement = createSelect(options, defaultValue)
div.appendChild(selectElement)
return [div, selectElement]
}
// 创建图片输入 - 带说明
function createImageInput (title, defaultValue) {
const div = document.createElement('div')
div.className = 'card'
// Create a label for the upload control
const nameLabel = document.createElement('label')
nameLabel.textContent = title
div.appendChild(nameLabel)
// 从选区
// let selectionTag = document.createElement('em')
// selectionTag.innerText = '#From Selection'
// selectionTag.className = 'tag'
// nameLabel.appendChild(selectionTag)
// Create an input field for the image name
const imgInput = document.createElement('img')
console.log(defaultValue)
imgInput.src = defaultValue || base64Df
imgInput.className = 'input_image'
// imgInput.src = `${hostUrl}/view?filename=${encodeURIComponent(
// defaultValue
// )}&type=input&rand=${Math.random()}`
div.appendChild(imgInput)
return [div, imgInput]
}
// 创建文本输入 - 带说明
function createTextInput (title, defaultValue, isSingle = false) {
// Create a container for the upload control
const div = document.createElement('div')
div.className = 'card'
// Create a label for the upload control
const nameLabel = document.createElement('label')
nameLabel.textContent = title
div.appendChild(nameLabel)
// Create an input field for the image name
const textInput = document.createElement('textarea')
textInput.value = defaultValue
if (isSingle) {
textInput.style.height = '44px'
}
div.appendChild(textInput)
// fixbug ,按backspace的时候,会删除图层
textInput.addEventListener('focus', async e => {
lockedCurrentLayerForTextInput()
})
textInput.addEventListener('blur', async e => {
unLockedCurrentLayerForTextInput()
})
// 粘贴文本
let pasteFromClipboard = document.createElement('div')
nameLabel.appendChild(pasteFromClipboard)
pasteFromClipboard.innerText = '+'
pasteFromClipboard.addEventListener('click', async e => {
let obj = await navigator.clipboard.read()
if (obj['text/plain']) textInput.value = obj['text/plain']
})
return [div, textInput]
}
// 数字输入
function createNumberSelectInput (title, defaultValue, opts) {
const { step, min, max, unit } = opts
// const [div, numInput] = createSelectWithOptions(
// title,
// Array.from(new Array((max - min) / step), (a, i) => {
// return {
// text: (i + 1) * step,
// value: (i + 1) * step
// }
// }),
// defaultValue
// )
const div = document.createElement('div')
div.className = 'card'
// Create a label for the upload control
const nameLabel = document.createElement('label')
nameLabel.textContent = title
div.appendChild(nameLabel)
let inpDiv = document.createElement('div')
div.appendChild(inpDiv)
// Create an input field for the image name
const numInput = document.createElement('input')
numInput.type = 'range'
numInput.className = 'input_num'
numInput.value = defaultValue
numInput.min = min || 0
numInput.max = max || 255
numInput.step = String(step || 1)
inpDiv.appendChild(numInput)
const value = document.createElement('label')
value.innerText = defaultValue + (unit ? unit : '')
inpDiv.appendChild(value)
numInput.addEventListener('input', e => {
value.innerText = numInput.value + (unit ? unit : '')
})
// 增加一个100%的按钮,获取画布最大尺寸
let maxInput = document.createElement('label')
maxInput.className = 'tag'
maxInput.innerText = 'Max'
inpDiv.appendChild(maxInput)
maxInput.addEventListener('click', e => {
// console.log(outNumInput)
const maxSize = Math.max(
photoshop.activeDocument.height,
photoshop.activeDocument.width
)
numInput.max = maxSize
numInput.value = maxSize
value.innerText = maxSize + (unit ? unit : '')
})
return [div, numInput]
}
// 种子的处理
function randomSeed (seed, data) {
for (const id in data) {
if (
data[id].inputs.seed != undefined &&
!Array.isArray(data[id].inputs.seed) && //如果是数组,则由其他节点控制
['increment', 'decrement', 'randomize'].includes(seed[id])
) {
data[id].inputs.seed = Math.round(Math.random() * 1849378600828930)
// console.log('new Seed', data[id])
}
if (
data[id].inputs.noise_seed != undefined &&
!Array.isArray(data[id].inputs.noise_seed) && //如果是数组,则由其他节点控制
['increment', 'decrement', 'randomize'].includes(seed[id])
) {
data[id].inputs.noise_seed = Math.round(Math.random() * 1849378600828930)
}
console.log('new Seed', data[id])
}
return data
}
async function getMyApps (
hostUrl,
category = '',
filename = null,
admin = false
) {
let url = hostUrl
const res = await fetch(`${url}/mixlab/workflow`, {
method: 'POST',
body: JSON.stringify({
task: 'my_app',
filename,
category,
admin
})
})
let result = await res.json()
let data = []
try {
for (const res of result.data) {
let { output, app } = res.data
if (app.filename)
data.push({
...app,
data: output,
date: res.date
})
}
} catch (error) {}
return data
}
function parseUrlFromImageName (name) {
let [subfolder,filename]=name.split('/')
console.log(name,subfolder,filename)
// filename=filename.split(' ')[0]
let url=`${hostUrl}/view?filename=${encodeURIComponent(
filename
)}&type=input&subfolder=${subfolder}&rand=${Math.random()}`
return url
}
// TODO ps插件不支持File类型,需要调整
async function uploadImage (arrayBuffer, fileType = '.png', filename) {
const body = new FormData()
const fileName = (filename || new Date().getTime()) + fileType
// 直接传
body.append('image', arrayBuffer, fileName)
const url = hostUrl
const resp = await fetch(`${url}/upload/image`, {
method: 'POST',
body
})
// console.log(resp)
let data = await resp.json()
let { name, subfolder } = data
let src = `${url}/view?filename=${encodeURIComponent(
name
)}&type=input&subfolder=${subfolder}&rand=${Math.random()}`
return { url: src, name }
}
async function uploadMask (arrayBuffer, imgurl) {
const body = new FormData()
const filename = 'clipspace-mask-' + performance.now() + '.png'
let original_url = new URL(imgurl)
const original_ref = { filename: original_url.searchParams.get('filename') }
let original_subfolder = original_url.searchParams.get('subfolder')
if (original_subfolder) original_ref.subfolder = original_subfolder
let original_type = original_url.searchParams.get('type')
if (original_type) original_ref.type = original_type
body.append('image', arrayBuffer, filename)
body.append('original_ref', JSON.stringify(original_ref))
body.append('type', 'input')
body.append('subfolder', 'clipspace')
const url = hostUrl
const resp = await fetch(`${url}/upload/mask`, {
method: 'POST',
body
})
// console.log(resp)
let data = await resp.json()
let { name, subfolder, type } = data
let src = `${url}/view?filename=${encodeURIComponent(
name
)}&type=${type}&subfolder=${subfolder}&rand=${Math.random()}`
return { url: src, name: 'clipspace/' + name }
}
function runMyApp (url, data) {
fetch(`${url}/prompt`, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: data
})
.then(response => {
// Handle response here
console.log(response)
})
.catch(error => {
// Handle error here
})
}
// 取消选择
async function unselectActiveLayers () {
const layers = await photoshop.activeDocument.activeLayers
for (layer of layers) {
layer.selected = false
}
}
async function unselectActiveLayersExe () {
await executeAsModal(async () => {
await unselectActiveLayers()
})
}
async function selectLayers (layers) {
await unselectActiveLayers()
for (layer of layers) {
try {
if (layer) {
const is_visible = layer.visible // don't change the visibility when selecting the layer
layer.selected = true
layer.visible = is_visible
}
} catch (e) {
console.warn(e)
}
}
}
async function selectLayersExe (layers) {
await executeAsModal(async () => {
await selectLayers(layers)
})
}
async function lockedCurrentLayerForTextInput () {
window._layersLocked = []
for (layer of photoshop.activeDocument.activeLayers) {
try {
if (layer) {
window._layersLocked.push({
_id: layer._id,
locked: layer.locked
})
layer.locked = true
}
} catch (e) {
console.warn(e)
}
}
}
function unLockedCurrentLayerForTextInput () {
// window._layersLocked = []
for (layer of photoshop.activeDocument.layers) {
try {
if (
window._layersLocked &&
window._layersLocked.filter(l => l._id === layer._id)[0]
) {
let l = window._layersLocked.filter(l => l._id === layer._id)[0]
layer.locked = l.locked
}
} catch (e) {
console.warn(e)
}