-
Notifications
You must be signed in to change notification settings - Fork 508
/
index.js
1823 lines (1616 loc) · 61.3 KB
/
index.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
// import {helloHelper} from 'helper.js'
// helloHelper2 = require('./helper.js')
// for organizational proposes
// let g_sdapi_path = 'sdapi'
const g_image_not_found_url =
'https://images.unsplash.com/source-404?fit=crop&fm=jpg&h=800&q=60&w=1200'
const _log = console.log
const _warn = console.warn
const _error = console.error
let g_timer_value = 300 // temporary global variable for testing the timer pause function
let g_version =
'v' +
JSON.parse(require('fs').readFileSync('plugin:manifest.json', 'utf-8'))
.version
let g_sd_url = 'http://127.0.0.1:7860'
let g_online_data_url =
'https://raw.githubusercontent.com/AbdullahAlfaraj/Auto-Photoshop-StableDiffusion-Plugin/master/utility/online_data.json'
const Jimp = require('./jimp/browser/lib/jimp.min')
const Enum = require('./enum')
const helper = require('./helper')
const sdapi = require('./sdapi_py_re')
// const exportHelper = require('./export_png')
const psapi = require('./psapi')
const app = window.require('photoshop').app
const constants = require('photoshop').constants
const { batchPlay } = require('photoshop').action
const { executeAsModal } = require('photoshop').core
const dialog_box = require('./dialog_box')
// const {entrypoints} = require('uxp')
const { sd_tab_store } = require('./typescripts/dist/bundle')
const html_manip = require('./utility/html_manip')
// const export_png = require('./export_png')
const selection = require('./selection')
const layer_util = require('./utility/layer')
const sd_options = require('./utility/sdapi/options')
// const sd_config = require('./utility/sdapi/config')
const session = require('./utility/session')
const { getSettings } = require('./utility/session')
const script_horde = require('./utility/sd_scripts/horde')
const prompt_shortcut = require('./utility/sdapi/prompt_shortcut')
const formats = require('uxp').storage.formats
const storage = require('uxp').storage
const shell = require('uxp').shell
const fs = storage.localFileSystem
const horde_native = require('./utility/sdapi/horde_native')
const dummy = require('./utility/dummy')
const general = require('./utility/general')
const thumbnail = require('./thumbnail')
const note = require('./utility/notification')
const settings_tab = require('./utility/tab/settings')
//load tabs
const image_search_tab = require('./utility/tab/image_search_tab')
// const share_tab = require('./utility/tab/share_tab')
const api = require('./utility/api')
const {
scripts,
main,
after_detailer_script,
control_net,
logger,
toJS,
viewer,
viewer_util,
preview,
// session_ts,
session_store,
progress,
sd_tab_ts,
// sd_tab_store,
sam,
settings_tab_ts,
one_button_prompt,
enum_ts,
multiPrompts,
ui_ts,
preset,
preset_util,
// dialog_box,
sd_tab_util,
node_fs,
io_ts,
extra_page,
selection_ts,
stores,
lexica,
api_ts,
comfyui,
comfyui_util,
comfyui_main_ui,
comfyapi,
} = require('./typescripts/dist/bundle')
const io = require('./utility/io')
function setLogMethod(should_log_to_file = true) {
let timer_id
if (should_log_to_file) {
console.log = (data, ...optional_param) => {
try {
_log(data, ...optional_param)
// const error = new Error({ data, ...optional_param });
const formattedOutput = logger.formateLog(
data,
...optional_param
)
io.IOLog.saveLogToFile({ log: formattedOutput }, 'log.txt')
} catch (e) {
_warn('error while logging: ')
_warn(e)
}
}
console.warn = (data, ...optional_param) => {
try {
_warn(data, ...optional_param)
const error = new Error()
const stackTrace = error.stack
const formattedOutput = logger.formateLog(
data,
...optional_param
)
io.IOLog.saveLogToFile(
{ warning: formattedOutput, stackTrace },
'log.txt'
)
} catch (e) {
_warn('error while logging: ')
_warn(e)
}
}
console.error = (data, ...optional_param) => {
try {
_error(data, ...optional_param)
const error = new Error()
const stackTrace = error.stack
const formattedOutput = logger.formateLog(
data,
...optional_param
)
io.IOLog.saveLogToFile(
{ error: formattedOutput, stackTrace },
'log.txt'
)
} catch (e) {
_error('error while logging: ')
_error(e)
}
}
} else {
console.log = _log
console.warn = _warn
console.error = _error
}
}
setLogMethod(settings_tab_ts.store.data.should_log_to_file)
// const {
// script_args,
// script_name,
// } = require('./ultimate_sd_upscaler/dist/ultimate_sd_upscaler')
let g_horde_generator = new horde_native.hordeGenerator()
let g_automatic_status = Enum.AutomaticStatusEnum['Offline']
let g_current_batch_index = 0
let g_is_laso_inapint_mode = true
//REFACTOR: move to session.js
async function hasSessionSelectionChanged() {
try {
const isSelectionActive = await psapi.checkIfSelectionAreaIsActive()
if (isSelectionActive) {
const current_selection = isSelectionActive // Note: don't use checkIfSelectionAreaIsActive to return the selection object, change this.
if (
await hasSelectionChanged(
current_selection,
g_generation_session.selectionInfo
)
) {
return true
} else {
//selection has not changed
return false
}
}
} catch (e) {
console.warn(e)
return false
}
}
async function calcWidthHeightFromSelection(selectionInfo) {
//set the width and height, hrWidth, and hrHeight using selection info and selection mode
const selection_mode = sd_tab_store.data.selection_mode
if (selection_mode === 'ratio') {
//change (width and height) and (hrWidth, hrHeight) to match the ratio of selection
const base_size = sd_tab_util.helper_store.data.base_size
const [width, height, hr_width, hr_height] =
await selection.selectionToFinalWidthHeight(
selectionInfo,
base_size,
base_size
)
// console.log('width,height: ', width, height)
html_manip.autoFillInWidth(width)
html_manip.autoFillInHeight(height)
html_manip.autoFillInHRWidth(hr_width)
html_manip.autoFillInHRHeight(hr_height)
} else if (selection_mode === 'precise') {
const [width, height, hr_width, hr_height] = [
selectionInfo.width,
selectionInfo.height,
0,
0,
]
html_manip.autoFillInWidth(width)
html_manip.autoFillInHeight(height)
}
}
//REFACTOR: rename to newSelectionEventHandler and move to session.js
const eventHandler = async (event, descriptor) => {
try {
console.log(event, descriptor)
const new_selection_info = await psapi.getSelectionInfoExe()
session_store.updateProperty(
'current_selection_info',
new_selection_info
)
// const isSelectionActive = await psapi.checkIfSelectionAreaIsActive()
if (new_selection_info) {
await calcWidthHeightFromSelection(new_selection_info)
}
} catch (e) {
console.warn(e)
}
}
//REFACTOR: move to generation_settings.js
function getCurrentGenerationModeByValue(value) {
for (let key in generationMode) {
if (
generationMode.hasOwnProperty(key) &&
generationMode[key] === value
) {
return key
}
}
return undefined
}
require('photoshop').action.addNotificationListener(
['set', 'move', 'addTo', 'subtractFrom'],
eventHandler
)
//REFACTOR: move to document.js
async function getUniqueDocumentId() {
console.warn(
'getUniqueDocumentId is deprecated, instead use the methods in IOFolder'
)
try {
let uniqueDocumentId = await psapi.readUniqueDocumentIdExe()
console.log(
'getUniqueDocumentId(): uniqueDocumentId: ',
uniqueDocumentId
)
// Regular expression to check if string is a valid UUID
const regexExp =
/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/gi
// String with valid UUID separated by dash
// const str = 'a24a6ea4-ce75-4665-a070-57453082c256'
const isValidId = regexExp.test(uniqueDocumentId) // true
console.log('isValidId: ', isValidId)
if (isValidId == false) {
let uuid = self.crypto.randomUUID()
console.log(uuid) // for example "36b8f84d-df4e-4d49-b662-bcde71a8764f"
await psapi.saveUniqueDocumentIdExe(uuid)
uniqueDocumentId = uuid
}
return uniqueDocumentId
} catch (e) {
console.warn('warning Document Id may not be valid', e)
}
}
// attach event listeners for tabs
//REFACTOR: move to html_manip.js (?) - if there is no business logic here and it's only for UI.
Array.from(document.querySelectorAll('.sp-tab')).forEach((theTab) => {
theTab.onclick = () => {
try {
// localStorage.setItem("currentTab", theTab.getAttribute("id"));
Array.from(document.querySelectorAll('.sp-tab')).forEach((aTab) => {
if (aTab.getAttribute('id') === theTab.getAttribute('id')) {
aTab.classList.add('selected')
} else {
aTab.classList.remove('selected')
}
})
Array.from(document.querySelectorAll('.sp-tab-page')).forEach(
(tabPage) => {
if (
tabPage
.getAttribute('id')
.startsWith(theTab.getAttribute('id'))
) {
tabPage.classList.add('visible')
} else {
tabPage.classList.remove('visible')
}
}
)
} catch (e) {
console.warn(e)
}
}
})
// entrypoints.setup({
// panels:{
// vanilla: ()=>{
// console.log("you are in the vanilla panel")
// },
// experimental_1: ()=>{
// console.log("you are in the experimental_1 panel")
// }
// }
// }
// )
// just a number that shouldn't unique enough that we will use when save files.
// each session will get a number from 1 to 1000000
//REFACTOR: move to session.js
const random_session_id = Math.floor(Math.random() * 1000000 + 1)
//REFACTOR: move to helpers.js (or other utility file)
function getSelectedText() {
// JavaScript
// // Obtain the object reference for the <textarea>
// const txtarea = document.getElementById("taPrompt");
const promptTextarea = document.querySelector('#taPrompt')
console.log('promptTextarea: ', promptTextarea.value)
// // Obtain the index of the first selected character
var start = promptTextarea.selectionStart
console.log('start: ', start)
// // Obtain the index of the last selected character
// var finish = txtarea.selectionEnd;
// console.log("finish: ",finish)
// // Obtain the selected text
// var sel = txtarea.value.substring(start, finish);
// console.log("selected textarea: ", sel)
// Do something with the selected content
}
//REFACTOR: move to helpers.js
// setInterval(getSelectedText,2000)
function getCommentedString() {
// const text = document.getElementById("taPrompt").value
// let text = `Visit /*W3Schools
// cute, girl, painterly
// *\\ any text
// and prompt`;
// let text = `cute cat /*by greg
// and artgerm
// */ and famous artist`
let text = `Visit /*W3Schools
cute, girl, painterly
*/ any text
and prompt
cute cat /*by greg
and artgerm
*/ and famous artist`
console.log('getCommentedString: text: ', text)
// let pattern = /(\/)(\*)(\s|\S)*\*\\/g;
let pattern = /(\/)(\*)(\s|\S)*?(\*\/)/g
let result = text.match(pattern)
console.log('getCommentedString: ', result)
}
//REFACTOR: move to the notfication.js
async function displayNotification(automatic_status) {
if (automatic_status === Enum.AutomaticStatusEnum['RunningWithApi']) {
//do nothing
} else if (
g_automatic_status === Enum.AutomaticStatusEnum['RunningNoApi']
) {
await note.Notification.webuiAPIMissing()
} else if (g_automatic_status === Enum.AutomaticStatusEnum['Offline']) {
await note.Notification.webuiIsOffline()
}
}
//REFACTOR: move to sdapi.js
async function checkAutoStatus() {
try {
const options = await g_sd_options_obj.getOptions()
if (options) {
//means both automatic1111 and proxy server are online
html_manip.setAutomaticStatus('connected', 'disconnected')
g_automatic_status = Enum.AutomaticStatusEnum['RunningWithApi']
const extension_url = py_re.getExtensionUrl()
const full_url = `${extension_url}/heartbeat`
const heartbeat = (await api.requestGet(full_url))?.heartbeat
if (heartbeat) {
html_manip.setProxyServerStatus('connected', 'disconnected')
session_store.data.auto_photoshop_sd_extension_status = true
} else {
html_manip.setProxyServerStatus('disconnected', 'connected')
g_automatic_status =
Enum.AutomaticStatusEnum['AutoPhotoshopSDExtensionMissing']
session_store.data.auto_photoshop_sd_extension_status = false
}
// html_manip.setProxyServerStatus('connected','disconnected')
} else {
html_manip.setAutomaticStatus('disconnected', 'connected')
if (await sdapi.isWebuiRunning()) {
//running with no api
g_automatic_status = Enum.AutomaticStatusEnum['RunningNoApi']
// await note.Notification.webuiAPIMissing()
} else {
//not running and of course no api
g_automatic_status = Enum.AutomaticStatusEnum['Offline']
// await note.Notification.webuiIsOffline()
}
return g_automatic_status
}
} catch (e) {
console.warn(e)
}
return g_automatic_status
}
//REFACTOR: move to helper.js
function promptShortcutExample() {
let prompt_shortcut_example = {
game_like:
'Unreal Engine, Octane Render, arcane card game ui, hearthstone art style, epic fantasy style art',
large_building_1: 'castle, huge building, large building',
painterly_style_1:
'A full portrait of a beautiful post apocalyptic offworld arctic explorer, intricate, elegant, highly detailed, digital painting, artstation, concept art, smooth, sharp focus, illustration',
ugly: '((((ugly)))), (((duplicate))), ((morbid)), ((mutilated)), out of frame, extra fingers, mutated hands, ((poorly drawn hands)), ((poorly drawn face)), (((mutation))), (((deformed))), ((ugly)), blurry, ((bad anatomy)), (((bad proportions))), ((extra limbs)), cloned face, (((disfigured))), out of frame, ugly, extra limbs, (bad anatomy), gross proportions, (malformed limbs), ((missing arms)), ((missing legs)), (((extra arms))), (((extra legs))), mutated hands, (fused fingers), (too many fingers), (((long neck)))',
}
var JSONInPrettyFormat = JSON.stringify(
prompt_shortcut_example,
undefined,
7
)
document.getElementById('taPromptShortcut').value = JSONInPrettyFormat
return prompt_shortcut_example
}
//**********Start: global variables
let prompt_dir_name = ''
let gImage_paths = []
let g_image_path_to_layer = {}
let g_init_images_dir = './server/python_server/init_images'
//REFACTOR: move to generationSettings.js
gCurrentImagePath = ''
// let g_init_mask_layer;
//REFACTOR: move to generationSettings.js
// let g_mask_related_layers = {}
// let g_init_image_related_layers = {}
//REFACTOR: move to generationSettings.js, Note: numberOfImages deprecated global variable
// let numberOfImages = document.querySelector('#tiNumberOfImages').value
//REFACTOR: move to generationSettings.js
//REFACTOR: move to generationSettings.js
let g_sd_sampler = 'Euler a'
//REFACTOR: move to generationSettings.js
let g_denoising_strength = 0.7
let g_models = []
// let g_models_horde = []
let g_model_title = ''
// let gWidth = 512
// let gHeight = 512
//REFACTOR: move to generationSettings.js
let hWidth = 512
//REFACTOR: move to generationSettings.js
let hHeight = 512
//REFACTOR: move to generationSettings.js
let h_denoising_strength = 0.7
// let g_inpainting_fill = 0
// let g_last_outpaint_layers = []
// let g_last_inpaint_layers = []
// let g_last_snap_and_fill_layers = []
//REFACTOR: move to generationSettings.js
let g_metadatas = []
//REFACTOR: move to generationSettings.js
let g_can_request_progress = true
let g_saved_active_layers = []
let g_saved_active_selection = {}
let g_is_active_layers_stored = false
let g_number_generation_per_session = 0
let g_isViewerMenuDisabled = false // disable the viewer menu and viewerImage when we're importing images into the current document
let g_b_mask_layer_exist = false // true if inpaint mask layer exist, false otherwise.
let g_inpaint_mask_layer
let g_inpaint_mask_layer_history_id //store the history state id when creating a new inpaint mask layer
// let g_selection = {}
//REFACTOR: move to session.js
let g_selection = {}
let g_b_use_smart_object = true // true to keep layer as smart objects, false to rasterize them
let g_sd_options_obj = new sd_options.SdOptions()
let g_controlnet_max_models
let g_generation_session = new session.GenerationSession(0) //session manager
g_generation_session.deactivate() //session starte as inactive
let g_ui_settings_object = ui_ts.getUISettingsObject()
let g_batch_count_interrupt_status = false
const requestState = {
Generate: 'generate',
Interrupt: 'interrupt',
}
let g_request_status = '' //
//REFACTOR: move to Enum.js
const generationMode = {
Txt2Img: 'txt2img',
Img2Img: 'img2img',
Inpaint: 'inpaint',
Outpaint: 'outpaint',
Upscale: 'upscale',
}
const backendTypeEnum = {
Auto1111: 'auto1111',
HordeNative: 'horde_native',
Auto1111HordeExtension: 'auto1111_horde_extension',
}
g_generation_session.mode = generationMode['Txt2Img']
//********** End: global variables */
document
.getElementById('sp-extras-tab')
.addEventListener('click', async (evt) => {
try {
sd_tab_store.updateProperty('mode', 'upscale')
await postModeSelection() // do things after selection
} catch (e) {
console.warn(e)
}
})
//REFACTOR: move to events.js
document
.getElementById('sp-stable-diffusion-ui-tab')
.addEventListener('click', async (evt) => {
try {
sd_tab_store.updateProperty('mode', sd_tab_store.data.rb_mode)
await postModeSelection() // do things after selection
} catch (e) {
console.warn(e)
}
})
//REFACTOR: move to psapi.js
async function createTempInpaintMaskLayer() {
if (!g_b_mask_layer_exist) {
//make new layer "Mask -- Paint White to Mask -- temporary"
const name = 'Mask -- Paint White to Mask -- temporary'
await psapi.unselectActiveLayersExe() // so that the mask layer get create at the top of the layer stocks
const top_layer_doc = await app.activeDocument.layers[0]
g_inpaint_mask_layer = await layer_util.createNewLayerExe(name, 60)
await executeAsModal(async () => {
await g_inpaint_mask_layer.moveAbove(top_layer_doc)
})
// g_inpaint_mask_layer.opacity = 50
g_b_mask_layer_exist = true
const index = app.activeDocument.historyStates.length - 1
g_inpaint_mask_layer_history_id =
app.activeDocument.historyStates[index].id
console.log(
'g_inpaint_mask_layer_history_id: ',
g_inpaint_mask_layer_history_id
)
}
}
//REFACTOR: move to psapi.js
async function deleteTempInpaintMaskLayer() {
console.log(
'g_inpaint_mask_layer_history_id: ',
g_inpaint_mask_layer_history_id
)
const historyBrushTools = app.activeDocument.historyStates
.slice(-10)
.filter(
(h) =>
h.id > g_inpaint_mask_layer_history_id &&
h.name === 'Brush Tool'
)
console.log(historyBrushTools)
if (historyBrushTools.length === 0 && g_b_mask_layer_exist) {
await layer_util.deleteLayers([g_inpaint_mask_layer])
g_b_mask_layer_exist = false
}
}
//REFACTOR: move to ui.js
async function postModeSelection() {
try {
if (sd_tab_store.data.rb_mode === generationMode['Inpaint']) {
//check if the we already have created a mask layer
await createTempInpaintMaskLayer()
} else {
// if we switch from inpaint mode, delete the mask layer
// Find all history states after the creation of the inpaint mask and their name brush tool
await deleteTempInpaintMaskLayer()
}
} catch (e) {
console.warn(e)
}
}
//REFACTOR: move to events.js
document.addEventListener('mouseenter', async (event) => {
try {
//only check if the generation mode has not changed( e.g a session.mode === img2img and the current selection is "img2img" ).
// changing the mode will trigger it's own procedure, so doing it here again is redundant
if (
g_generation_session.isActive() &&
g_generation_session.mode === sd_tab_store.data.rb_mode
) {
//if the generation session is active and the selected mode is still the same as the generation mode
console.log('hover on window')
const new_selection = await psapi.getSelectionInfoExe() //get the current active selection if there is any
if (
new_selection &&
(await hasSelectionChanged(
new_selection,
g_generation_session.selectionInfo
))
) {
// if there is an active selection and if the selection has changed
await calcWidthHeightFromSelection(new_selection)
} else {
// sessionStartHtml(true)//generate more, green color
//if you didn't move the selection.
}
}
} catch (e) {
console.warn(e)
}
})
// function showLayerNames () {
// const app = window.require('photoshop').app
// const allLayers = app.activeDocument.layers
// const allLayerNames = allLayers.map(
// layer => `${layer.name} (${layer.opacity} %)`
// )
// const sortedNames = allLayerNames.sort((a, b) => (a < b ? -1 : a > b ? 1 : 0))
// document.getElementById('layers').innerHTML = `
// <ul>${sortedNames.map(name => `<li>${name}</li>`).join('')}</ul>`
// }
//REFACTOR: move to psapi.js
function selectTool() {
var doc = app.activeDocument
var activeTool = app.currentTool
// if (activeTool !== toolName) {
// toolName = activeTool;
// doc.activeTool = toolName;
// }
// const util = require('util')
// console.log(util.inspect(myObject, {showHidden: false, depth: null, colors: true}))
console.dir(app, { depth: null })
console.log('hello this is Abdullah')
document.getElementById('layers').innerHTML = `<span>
selectTool was called, ${activeTool}
</span>`
//rectanglemarquee
// await require('photoshop').core.executeAsModal(newNormalLayer);
}
// User picks an image file
// open a explorer for user to select a image file
//REFACTOR: move to psapi.js
async function fillImage() {
const storage = require('uxp').storage
const fs = storage.localFileSystem
let imageFile = await fs.getFileForOpening({
types: storage.fileTypes.images,
})
// Create ImageFill for this image
const ImageFill = require('scenegraph').ImageFill
let fill = new ImageFill(imageFile)
// Set fill of first selected item
selection.items[0].fill = fill
}
// fillImage()
//REFACTOR: move to psapi.js
function pastImage2Layer() {
const { batchPlay } = require('photoshop').action
const { executeAsModal } = require('photoshop').core
executeAsModal(
() => {
// batchPlay([command], {})
const result = batchPlay(
[
{
_obj: 'paste',
antiAlias: {
_enum: 'antiAliasType',
_value: 'antiAliasNone',
},
as: {
_class: 'pixel',
},
_options: {
dialogOptions: 'dontDisplay',
},
},
],
{
synchronousExecution: true,
modalBehavior: 'execute',
}
)
},
{
commandName: 'Create Label',
}
)
}
//REFACTOR: move to ui.js
function sliderToResolution(sliderValue) {
return sliderValue * 64
}
//REFACTOR: move to psapi.js
//store active layers only if they are not stored.
async function storeActiveLayers() {
setTimeout(async () => {
const layers = await app.activeDocument.activeLayers
console.log('storeActiveLayers: ', layers.length)
if (layers.length > 0) {
g_saved_active_layers = layers
await psapi.unselectActiveLayersExe()
}
}, 200)
// if (g_is_active_layers_stored == false) {
// g_saved_active_layers = await app.activeDocument.activeLayers
// g_is_active_layers_stored = true
// await psapi.unselectActiveLayersExe()
// } else {
// }
}
//REFACTOR: move to psapi.js
async function restoreActiveLayers() {
const layers = await app.activeDocument.activeLayers
console.log('restoreActiveLayers: ', layers.length)
if (layers.length == 0) {
await psapi.selectLayersExe(g_saved_active_layers)
g_saved_active_layers = []
}
// if (g_is_active_layers_stored == true) {
// // g_saved_active_layers = await app.activeDocument.activeLayers
// await psapi.selectLayersExe(g_saved_active_layers)
// g_is_active_layers_stored = false
// g_saved_active_layers = []
// }
}
//store active selection only if they are not stored.
//REFACTOR: move to psapi.js
async function storeActiveSelection() {
try {
setTimeout(async () => {
const layers = await app.activeDocument.activeLayers
const current_selection = await psapi.checkIfSelectionAreaIsActive()
console.log('storeActiveSelection: ', current_selection)
if (current_selection) {
g_saved_active_selection = current_selection
await psapi.unSelectMarqueeExe()
}
}, 200)
} catch (e) {
console.warn(e)
}
}
//REFACTOR: move to psapi.js
async function restoreActiveSelection() {
try {
const current_selection = await psapi.checkIfSelectionAreaIsActive()
console.log('restoreActiveSelection: ', current_selection)
if (
!current_selection &&
psapi.isSelectionValid(g_saved_active_selection)
) {
await psapi.reSelectMarqueeExe(g_saved_active_selection)
g_saved_active_selection = {}
}
} catch (e) {
console.warn(e)
}
}
//REFACTOR: unused, remove?
function updateMetadata(new_metadata) {
const metadatas = []
try {
for (metadata of new_metadata) {
metadata_json = JSON.parse(metadata)
console.log('metadata_json:', metadata_json)
metadatas.push(metadata_json)
}
} catch (e) {
console.warn(e)
}
return metadatas
}
//REFACTOR: move to selection.js
async function hasSelectionChanged(new_selection, old_selection) {
if (
new_selection.left === old_selection.left &&
new_selection.bottom === old_selection.bottom &&
new_selection.right === old_selection.right &&
new_selection.top === old_selection.top
) {
return false
} else {
return true
}
}
//REFACTOR: move to ui.js
function updateProgressBarsHtml(new_value) {
document.querySelectorAll('.pProgressBars').forEach((el) => {
// id = el.getAttribute("id")
// console.log("progressbar id:", id)
el.setAttribute('value', new_value)
})
document.querySelectorAll('.lProgressLabel').forEach((el) => {
console.log('updateProgressBarsHtml: ', new_value)
if (new_value > 0) el.innerHTML = 'In progress...'
else el.innerHTML = 'No work in progress'
})
// document.querySelector('#pProgressBar').value
}
//REFACTOR: move to psapi.js
function _base64ToArrayBuffer(base64) {
var binary_string = window.atob(base64)
var len = binary_string.length
var bytes = new Uint8Array(len)
for (var i = 0; i < len; i++) {
bytes[i] = binary_string.charCodeAt(i)
}
return bytes.buffer
}
//REFACTOR: move to psapi.js
function _arrayBufferToBase64(buffer) {
var binary = ''
var bytes = new Uint8Array(buffer)
var len = bytes.byteLength
for (var i = 0; i < len; i++) {
binary += String.fromCharCode(bytes[i])
}
return window.btoa(binary)
}
//REFACTOR: move to io.js
async function getDocFolder(doc_uuid) {
try {
// const uuid = await getUniqueDocumentId()
const data_folder = await storage.localFileSystem.getDataFolder()
let doc_folder
try {
doc_folder = await data_folder.getEntry(doc_uuid)
} catch (e) {
console.warn(e)
//create document folder
doc_folder = await data_folder.createFolder(doc_uuid)
}
return doc_folder
} catch (e) {
console.warn(e)
}
}
//REFACTOR: move to document.js
async function getCurrentDocFolder() {
//move to a global utililty lib
const uuid = await getUniqueDocumentId()
let doc_folder = await getDocFolder(uuid)
return doc_folder
}
//REFACTOR: move to document.js
async function getInitImagesDir() {
const uuid = await getUniqueDocumentId()
let doc_folder = await getDocFolder(uuid)
let init_folder
try {
init_folder = await doc_folder.getEntry('init_images')
} catch (e) {
console.warn(e)
//create document folder
init_folder = await doc_folder.createFolder('init_images')
}
return init_folder
}
//REFACTOR: move to document.js
async function base64ToFile(b64Image, image_name = 'output_image.png') {
// const b64Image =
// 'iVBORw0KGgoAAAANSUhEUgAAAQAAAAEACAIAAADTED8xAAADMElEQVR4nOzVwQnAIBQFQYXff81RUkQCOyDj1YOPnbXWPmeTRef+/3O/OyBjzh3CD95BfqICMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMK0CMO0TAAD//2Anhf4QtqobAAAAAElFTkSuQmCC'
try {
const img = _base64ToArrayBuffer(b64Image)
const img_name = image_name
const folder = await storage.localFileSystem.getTemporaryFolder()
const file = await folder.createFile(img_name, { overwrite: true })
await file.write(img, { format: storage.formats.binary })
const token = await storage.localFileSystem.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: {