-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathEverpic.ahk
1775 lines (1382 loc) · 51 KB
/
Everpic.ahk
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
AUTOEXEC_Everpic: ; Workaround for Autohotkey's ugly auto-exec feature. Must be first line.
/* APIs:
Evp_LaunchUI(http_server_baseurl:="")
Everpic_InitHotkeys(http_server_baseurl:="") ; optional
Evp_FixInternalHttpServer()
; -- If HTTP server chokes(not respond to client), need to call this to recover. (testing)
[Scenario 1] If user feels OK with the default hotkey of App+C, then, none of the above API is needed.
When user press App+C, Evp_LaunchUI() is triggered and the Everpic UI pops up converting the clipboard image.
[Scenario 2a] If user feels OK with the default hotkey of App+C and want to have HTTP server activated
(so that the image-carrying CF_HTML can be pasted into Evclip), user should call
Everpic_InitHotkeys("*")
once in customize.ahk .
[Scenario 2b] If user wants to work with customized HTTP server, then in customize.ahk, he calls once:
Everpic_InitHotkeys("http://localhost:2017")
[Scenario 3] If user wants to have another hotkey(^#c for example) to activate Everpic UI, then
he should call one of below once in customize.ahk :
fxhk_DefineHotkey("^#c", false, "Evp_LaunchUI")
fxhk_DefineHotkey("^#c", false, "Evp_LaunchUI", "*")
fxhk_DefineHotkey("^#c", false, "Evp_LaunchUI", "http://localhost:2017")
*/
;;;;;;;; Everpic global vars ;;;;;;;;;;
; global g_evpTempDir := A_Temp "\Everpic" ; [2025-01-13] Now use Everpic.dirTempImg .
global gc_evpBatchConvertExecpath := A_ScriptDir "\exe\everpic-batch-prepare.bat"
global g_evpBaseImageFilepath_100pct
; If user choose a new scale, we use g_evpBaseImageFilepath_100pct to re-generate
; new scaled images, instead of re-generate from clipboard.
; Note: The so-called "BaseImage", is always in Everpic.dirTempImg.
;global g_evpBaseImageFilepath_scaled ; no use
global g_evpImageWidth
global g_evpImageHeight
global g_evpImglistTxtPath
global g_evpBatchProgressFilepath
global g_evpImageSig := ""
; need it as "signature" in Evernote image footnote. by Evp_GenImageSigByTimestamp().
; Example: "everpic-20221205_150413"
global g_evpTempPreserveMinutes := 60*24 ; default to one day
global g_evpHwndToPaste
global gc_evpImgpaneDefWidth := 400 ; image-pane default width
global gc_evpImgpaneDefHeight := 300
global g_evpImgpaneWidth := gc_evpImgpaneDefWidth ; To be filled in Evp_ShowGui()
global g_evpImgpaneHeight := gc_evpImgpaneDefHeight ; To be filled in Evp_ShowGui()
global gc_evpCol1Width := 160 ; EVP GUI Column 1 width in pixels
global gc_evpGapX := 10 ; const, gap between listbox and pic-control
global gc_evpGapY := 10 ; const, gap between listbox and pic-control
global gc_evp_GUIDefWidth := gc_evpGapX*2 + gc_evpCol1Width + gc_evpImgpaneDefWidth ; GUI default width
global gar_evpScalePcts := [ 100, 75, 50, 40, 30, 20 ]
global gc_evpMarginX := 10 ; const
global gc_evpMarginY := 10 ; const
global g_evpWindowBorder := 14 ; assume, may not be accurate yes
global g_evpBottomLineHeight := 16 ; for Button OK/Dismiss/Use_This
global g_HwndEVPGui
global gc_evp_CF_BITMAP := 2
; First column controls:
;
global gu_evpBtnCvtFromClipbrd := "" ; The top-left corner "Convert from Clipboard" button
global gu_evpCkbAutoConvert := 0
global gu_evpTxtScale := "" ; the small "Scale:" text label
global gu_evpCbxScalePct := 0 ; The image-scale percent combobox
global gu_evpBtnCvtFromBaseImg := "" ; The Refresh button that converts from existing Base-image
global g_evpCurrentScalePct := 100
global gu_evpLbxImages := 0 ; Image-candidates list listbox
global gu_evpEdrLoadStat := "" ; Small text label, result statistics, e.g, "640*480, 0.2s"
;
; Second column controls:
;
global gu_evpTxtClipbState := "" ; Text label showing clipboard state.
global gu_evpIcnWarnNoTranspixel := "" ; Icon warning "no transparent pixel in png"
global gu_evpCkbKeepPngTrans := ""
global gu_evpEdrBaseImgFilepath := "" ; Currently previewing image filepath (readonly editbox)
global gu_evpPicPreview ; gui-assoc, Picture control
global g_evpCurPngHasTranspx := false ; Current png has transparent pixel? Detected by Evp_TimerProcCheckPngfileTranspixel()
;
global gu_evpBtnOK := "" ; Left-bottom "Use This" button
global gu_evpCkbAutoPaste := ""
global gu_evpCkbKeepWindow := ""
global gu_evpEdrFootline := "" ; current select image filepath
global gu_evpBtnCopyFile := "" ; the button at right edge of gu_evpEdrFootline
global gc_evpIconBtnWidth := 25
global g_evpIsGuiVisible := false
global g_evpConvertStartCount := 0 ; increase one each time Launch convert.
global g_evpConvertSuccCount := 0
global gc_evpConvertBtnText := "&Convert from Clipboard"
global g_evpTimerStage := "Monitoring"
; "Monitoring" : Periodically check(monitor) the clipboard for image or CF_BITMAP or image-filepath.
; "ConvertStarting" : External everpic-batch-prepare.bat launched, waiting for <basename>.progress.done.txt .
; "ConvertStarted" : <basename>.progress.done.txt detected, checking its content for progress.
global g_evpTickConvertStart := 0
global g_evpIsCancelling := false
global gc_evpFileSuffix_progressdone := ".progress.done.txt"
global gc_evpFileSuffix_imagelist := ".imagelist.txt"
global gc_evpStartingTimeoutSec := 3
global g_evpBgCvtProcessId := 0
global g_evp_arImageStore := [] ; g_evp_arImageStore[1] refers to the first previewed image.
; members: .hint .filelen_desc .path
global g_evpImageZoom := 1
global gut_progressbar := ""
global g_isKeepPngTransparent
global gc_KeepPngTransparent := true ; as synonym for true
global g_evpIsFullUIExpaned := -1 ; -1 means unset
global g_evp_hClipmon ; Clipboard monitor handle
global g_evp_ClipmonSeqNow := 0 ; Clipboard change sequence-number
global g_evp_ClipmonSeqAct := 0 ; The sequence-number on which we have done image-conversion.
global g_evpDbgCfg := {"showdbginfo":false, "showdbgcleanup":false, "showbgcmd":false, "slowbgcmd":0}
global g_evpSuppressUicTooltipBfrThis := A_Now ; will store A_Now format string
Everpic_InitHotkeys()
#Include %A_LineFile%\..\libs\Gdip_All.ahk
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
return ; End of auto-execute section.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
class Everpic
{
static dirTempImg := A_Temp "\Everpic"
static dirSaveImg := A_AppData "\Everpic-save"
; -- User can override the above two dirs in customize.ahk .
static listen_port_base := 2024
static baseurl := "(not-set)" ; http://localhost:2024
static httpserver := "" ; points to internal HttpServer() object
}
Everpic_InitHotkeys(http_server_baseurl:="")
{
; App+c to callup Everpic UI, we make it global hotkey.
; This converts in-clipboard image to your preferred format(png/jpg) and put CF_HTML content into clipboard,
; so Ctrl+v pasting it into Evernote saves quite much space (Evernote defaultly gives you very big PNG-32).
;
; Note: Before Evp_LaunchUI() is actually called, user can call Everpic_InitHotkeys() a second time
; with another http_server_baseurl value to overide the to-be-used BaseURL.
; After Evp_LaunchUI() is called the first time, the BaseURL is solidified and can not be changed any more.
;
; Example:
; Everpic_InitHotkeys("http://localhost:2017")
hotkey_purpose := "Purpose-Evp_LaunchUI"
ret_purpose := fxhk_DefineComboHotkeyCondComment("AppsKey", "c"
, hotkey_purpose ; must be explicit, so that a second call can override it.
, "" ; user_comment
, "" ; fn_cond
, "Evp_LaunchUI", http_server_baseurl)
dev_assert(hotkey_purpose==ret_purpose)
}
evp_HttpServing(ByRef request, ByRef response, ByRef server) {
parts := StrSplit(request.path, "/")
filenam := parts[parts.length()]
dir_everpic_save := Everpic.dirSaveImg
imgpath := Format("{}\{}", dir_everpic_save, filenam)
; Amdbg0("Want: " imgpath)
retlen := server.ServeFile(response, imgpath)
if(retlen>0)
response.status := 200
}
evp_LaunchHttpServer(listen_port)
{
paths := {}
paths["/Everpic-save"] := Func("evp_HttpServing")
serv := new HttpServer()
serv.LoadMimes("libs\mime.types")
serv.SetPaths(paths)
; Try 10 listen_port until success.
listen_port_end_ := listen_port + 10
Loop
{
; Amdbg0("Trying... " listen_port)
err := serv.Serve(listen_port)
if(!err)
break
listen_port++
Sleep, 10
}
if(listen_port==listen_port_end_) {
dev_MsgBoxError(Format("In evernote.ahk: Error starting HTTP server, tried port range {} ~ {}, Last WinError={}"
, listen_port, listen_port_end_, ErrorLevel))
return false
}
Everpic.baseurl := Format("http://localhost:{}", listen_port)
Everpic.httpserver := serv
return true
}
evp_StopHttpServer()
{
Everpic.httpserver.StopServe()
}
Evp_FixInternalHttpServer()
{
if(not Everpic.httpserver)
{
dev_MsgBoxInfo("You are not using Everpic's internal HTTP server, nothing to fix.")
return
}
evp_StopHttpServer()
is_ok := evp_LaunchHttpServer(Everpic.listen_port_base)
if(is_ok)
dev_MsgBoxInfo("Everpic internal HTTP server restart success.")
else
dev_MsgBoxWarning("Everpic internal HTTP server restart failed. You may try again.")
}
Evp_WinTitle()
{
return "Everpic v2024.04"
}
evpdbg(msg)
{
if(g_evpDbgCfg.showdbginfo)
Dbgwin_Output(msg)
}
Evp_LaunchUI(http_server_baseurl:="")
{
static s_inited := false
if(!s_inited)
{
if(http_server_baseurl=="")
{
; No HTTP server involved. User will not be able to paste CF_HTML into Evclip,
; only to copy generated image filepath, or, "List of files" for pasting into Explorer.
}
if(http_server_baseurl=="*")
{
; Use AHKHttp as (internal) HTTP server
evp_LaunchHttpServer(Everpic.listen_port_base)
}
else if(http_server_baseurl!="")
{
; User may set-up his own HTTP server for this purpose. For example:
; "http://localhost:2017"
Everpic.baseurl := http_server_baseurl
}
s_inited := true ; Even if HTTP server start-up fail.
}
if(!dev_CreateDirIfNotExist(Everpic.dirTempImg))
{
dev_MsgBoxError("Error. Cannot create folder: " Everpic.dirTempImg)
return
}
; Remember current active window, it becomes paste target later
g_evpHwndToPaste := dev_GetActiveHwnd()
was_gui_visible := g_evpIsGuiVisible
Evp_ShowGui()
Gui_Show("EVP", "", Evp_WinTitle()) ; This ensures EVP is brought to front(not passing "NoActive" option)
; If the EVP GUI has been on screen, and user calls up Evp_LaunchUI(), and there is currently
; no bitmap in the clipboard, our UI will keep *silent* (=not popping a msgbox saying clipboard is empty).
; This decision matches such a usage scenario:
; * User ticks [Keep window], wanting to keep EVP GUI on the screen (perhaps on his secondary monitor);
; * Then user picks "png (8 colors)" to paste into Evernote, leaving EVP GUI on screen;
; (Now, clipboard has CF_HTML, not a bitmap or bitmap-filepath.)
; * After some Evernote editing, user calls up Evp_LaunchUI( AppsKey&c ), this time, he probably wants
; to pick another image vairant to use, "jpg (60%)" for example.
; -- At this point, we'd better not telling the user "No bitmap in clipboard", instead we'd better
; keep the EVP UI silent so the user can pick "jpg (60%") from last time.
if(was_gui_visible)
{
hasbm := Evp_IsBitmapInClipboard(bitmap_filepath)
if(!hasbm and !bitmap_filepath)
return ; keep EVP UI silent
}
Evp_LaunchConvert_fromClipboard()
}
Evp_ShowGui()
{
if(g_evpIsGuiVisible)
return
if(!g_HwndEVPGui) {
Evp_CreateGui()
} else {
; MsgBox, % "Skip Evp_CreateGui()"
}
Evp_AutosizeNowUI() ; Gui, EVP:Show inside
g_evpIsGuiVisible := true
dev_OnMessageRegister(0x200, "Evp_WM_MOUSEMOVE")
dev_OnMessageRegister(0x111, "Evp_WM_COMMAND")
dev_OnMessageRegister(0x205, "Evp_WM_RBUTTONUP")
g_evp_hClipmon := Clipmon_CreateMonitor(Func("Evp_ClipmonCallback"), "Evp_ShowGui")
g_evp_ClipmonSeqNow := 0
g_evp_ClipmonSeqAct := 0
Evp_TimerOn()
}
Evp_CleanupUI() ; [2024-04-12] Better named (traditional) Evp_HideGui(), so it pairs with Evp_ShowGui()
{
Evp_TimerOff()
Clipmon_DeleteMonitor(g_evp_hClipmon)
dev_OnMessageUnRegister(0x200, "Evp_WM_MOUSEMOVE")
dev_OnMessageUnRegister(0x111, "Evp_WM_COMMAND")
dev_OnMessageUnRegister(0x205, "Evp_WM_RBUTTONUP")
Gui, EVP:Hide ; I will not do EVP:Destroy. If really want, just Reload the AHK script.
g_evpIsGuiVisible := false
}
EVPGuiEscape(hwndGui)
{
; dev_TooltipAutoClear("EVPGuiEscape() called")
Evp_CleanupUI()
}
EVPGuiClose(hwndGui)
{
; dev_TooltipAutoClear("EVPGuiClose() called")
Evp_CleanupUI()
}
Evp_CreateGui()
{
; Evp: short for "Everpic"
; This UI will generate a series of image previews with different quality,
; then user can pick the "best" one to use(paste it into Evernote).
Gui, EVP:New ; Destroy old window if any
Gui_AssociateHwndVarname("EVP", "g_HwndEVPGui") ; Gui hwnd generated in g_HwndEVPGui
Gui_SetXYMargin("EVP", gc_evpMarginX, gc_evpMarginY)
Gui_Switch_Font("EVP", 9, "Black", "Tahoma") ; Gui, EVP:Font, s9 cBlack, Tahoma
fullwidth := Evp_CalCtrlFullWidth()
; ==== Create Column1 controls. ====
;
col1w := gc_evpCol1Width
Gui_Add_Button( "EVP", "gu_evpBtnCvtFromClipbrd", col1w, "Section xm ym g" . "Evp_evtCvtFromClipboard" , gc_evpConvertBtnText)
Gui_Add_Checkbox("EVP", "gu_evpCkbAutoConvert", col1w, "xm+16 y+5 Hidden", "&Auto Convert")
Gui_Add_Editbox( "EVP", "gu_evpEdrBaseImgFilepath", fullwidth, "xm y+34 Readonly -E0x200", "Base-image file path (to fill)")
;
lwScale := 42 ; label-width
lwRefresh := 30
Gui_Add_TxtLabel("EVP", "gu_evpTxtScale", lwScale, "xm+2 y+4", "&Scale:")
Gui_Add_Combobox("EVP", "gu_evpCbxScalePct", col1w-lwScale-lwRefresh-gc_evpGapX
, Format("x+{} yp-2 AltSubmit g{}", 0, "Evp_evtCbxScalepctChanged"))
Gui_Add_Button( "EVP", "gu_evpBtnCvtFromBaseImg", lwRefresh
, Format("x+{} yp-1 g{}", gc_evpGapX, "Evp_evtCvtFromBaseImg"), "→") ; "↻" (the Refresh Unicode char) is rendered ugly, so use right-arrow instead
;
Gui_Add_Listbox( "EVP", "gu_evpLbxImages", col1w, Format("xs r12 AltSubmit g{}", "Evp_RefreshImgpane"))
Gui_Add_Editbox( "EVP", "gu_evpEdrLoadStat", col1w, "Readonly -E0x200", "")
; FootLine (The output filepath/[Copy] as in Explorer button)
Gui_Add_Editbox( "EVP", "gu_evpEdrFootline", fullwidth-gc_evpIconBtnWidth, "xm Readonly", "...")
Gui_Add_Button( "EVP", "gu_evpBtnCopyFile", gc_evpIconBtnWidth, "x+2 g" . "Evp_CopyConvertedImageFileToClipboard", "")
GuiButton_SetIconFromDll("EVP", "gu_evpBtnCopyFile", "shell32.dll", 243, 16, true) ; #243 is the [Copy] icon, 16 is icon size
; OK button
Gui_Add_Button( "EVP", "gu_evpBtnOK", col1w, "default xm " gui_g("Evp_BtnOK"), "&Use This (or press Enter)")
;
; Two checkboxes beside BtnOK
Gui_Add_Checkbox("EVP", "gu_evpCkbAutoPaste", -1, "x+5 yp+5 Checked", "Auto &paste") ; Auto paste
Gui_Add_Checkbox("EVP", "gu_evpCkbKeepWindow",-1, "x+5 yp", "Keep &window") ; Keep window
; ==== Create Column2 controls. ====
;
col2w := gc_evpImgpaneDefWidth
Gui_Add_TxtLabel("EVP", "gu_evpTxtClipbState", col2w, Format("xs+{} ys+5 section +0x8000", col1w+gc_evpGapX), "Clipboard state")
;
Gui_Add_Picture( "EVP", "gu_evpIcnWarnNoTranspixel", 16, "h16 hidden +0x100") ; 0x100: SS_NOTIFY, for hovering tooltip
Gui_Picture_SetIconFromDll("EVP", "gu_evpIcnWarnNoTranspixel", "user32.dll", 2) ; 2: yellow exclamation triangle
Gui_Add_Checkbox("EVP", "gu_evpCkbKeepPngTrans", -1, "x+4 yp+1 c666666 Hidden g" . "Evp_ToggleKeepPngTransparent"
, "&Keep transparent pixels when converting png file.")
;
Gui_Add_Picture( "EVP", "gu_evpPicPreview", col2w, "h" g_evpImgpaneHeight)
; The above GUI control layout will later be updated by Evp_SyncGuiByBaseImage()
; Fill gu_evpCbxScalePct combobox
for index,value in gar_evpScalePcts
{
if(index==1)
jstr := value . "%|" ; extra "|" means default selection
else
jstr := jstr "|" value "%"
}
GuiControl_SetText("EVP", "gu_evpCbxScalePct", jstr)
; Set default states of the controls:
;
evpdbg("UIC Disable: gu_evpBtnCvtFromClipbrd")
GuiControl_Enable("EVP","gu_evpBtnCvtFromClipbrd", false) ; Not enabled until image in clipboard
GuiControl_Enable("EVP","gu_evpBtnOK", false) ; Not enabled until image previews all generated
;
Evp_ShowAllControls(false)
Gui_Show("EVP", "xCenter yCenter", Evp_WinTitle()) ; only center it when first created
g_evpConvertStartCount := 0
g_evpConvertSuccCount := 0
}
Evp_ShowAllControls(is_show:=true)
{
if(is_show==g_evpIsFullUIExpaned)
return
g_evpIsFullUIExpaned := is_show
ctls := [ "gu_evpCkbAutoConvert"
, "gu_evpTxtScale", "gu_evpCbxScalePct", "gu_evpBtnCvtFromBaseImg"
, "gu_evpLbxImages", "gu_evpEdrLoadStat"
, "gu_evpBtnOK", "gu_evpCkbAutoPaste", "gu_evpCkbKeepWindow"
, "gu_evpEdrBaseImgFilepath"
; , "gu_evpCkbKeepPngTrans"
, "gu_evpPicPreview", "gu_evpEdrFootline", "gu_evpBtnCopyFile" ]
for index,value in ctls
{
GuiControl_Show("EVP", value, is_show)
}
Evp_AutosizeNowUI()
}
Evp_AutosizeNowUI()
{
is_auto := GuiControl_GetValue("EVP", "gu_evpCkbAutoConvert")
showopt := "AutoSize" . (is_auto ? " NoActivate" : "")
Gui_Show("EVP", showopt, Evp_WinTitle())
}
Evp_CalCtrlFullWidth()
{
; Calculate from g_evpImgpaneWidth
;
return gc_evpCol1Width + gc_evpGapX + g_evpImgpaneWidth
}
Evp_CalGuiFullWidth()
{
return 2 * gc_evpMarginX + Evp_CalCtrlFullWidth()
}
Evp_GenImageSigByTimestamp()
{
; Example: everpic-20221205_150413
FormatTime, dt, , % "yyyyMMdd_HHmmss"
return "everpic-" dt
}
Evp_BaseImageFilepathPrefix(imgsig)
{
return Format("{}\{}", Everpic.dirTempImg, imgsig)
}
Evp_ScaleDownImage(scale_pct, srcimgpath, dstimgpath, isKeepPngTransparent)
{
; 2022.12.09 https://www.autohotkey.com/board/topic/52033-convertresize-image-with-gdip-solved/
If !pToken := Gdip_Startup()
return false
is_succ := false
sBitmap := Gdip_CreateBitmapFromFile(srcimgpath)
if(sBitmap<=0)
goto Evp_ScaleDownImage_END
sWidth := Gdip_GetImageWidth(sBitmap)
sHeight := Gdip_GetImageHeight(sBitmap)
dWidth := sWidth * scale_pct // 100
dHeight := sHeight * scale_pct // 100
dBitmap := Gdip_CreateBitmap(dWidth, dHeight)
G := Gdip_GraphicsFromImage(dBitmap)
if(!isKeepPngTransparent)
{
; If not isKeepPngTransparent, we set white background for it.
;pBrush2 := Gdip_BrushCreateSolid(0x80FF2000)
pBrushClear := Gdip_BrushCreateSolid(0xFFffffff)
; -- Fill ARGB(255,255,255,255), alpha-value=255 is required.
; Otherwise, the default ARGB is (0,0,0,0), which will result in black bg onto jpg.
Gdip_FillRectangle(G, pBrushClear, 0, 0, dWidth, dHeight)
;Gdip_FillRectangle(G, pBrush2, 0, 0, dWidth, dHeight)
Gdip_DeleteBrush(pBrushClear)
;Gdip_DeleteBrush(pBrush2)
}
Gdip_DrawImage(G, sBitmap, 0, 0, dWidth, dHeight, 0, 0, sWidth, sHeight)
err := Gdip_SaveBitmapToFile(dBitmap, dstimgpath)
if(err)
goto Evp_ScaleDownImage_END
is_succ := true
Evp_ScaleDownImage_END:
Gdip_DisposeImage(sBitmap)
Gdip_DisposeImage(dBitmap)
Gdip_DeleteGraphics(G)
Gdip_Shutdown(pToken)
return is_succ
}
Evp_evtCvtFromClipboard(CtrlHwnd, GuiEvent, EventInfo, ErrLevel:="")
{
evpdbg(Format("In Evp_evtCvtFromClipboard().")) ; debug
Evp_LaunchConvert_fromClipboard()
}
Evp_evtCvtFromBaseImg(CtrlHwnd, GuiEvent, EventInfo, ErrLevel:="")
{
dev_assert(g_evpBaseImageFilepath_100pct)
Evp_LaunchConvert_fromBaseImage(g_evpBaseImageFilepath_100pct)
}
Evp_GetUIScalePct()
{
GuiControl_ChangeOpt("EVP", "gu_evpCbxScalePct", "-AltSubmit")
text := GuiControl_GetText("EVP", "gu_evpCbxScalePct")
GuiControl_ChangeOpt("EVP", "gu_evpCbxScalePct", "+AltSubmit")
scale_pct := dev_str2num(text)
return scale_pct
}
Evp_ToggleKeepPngTransparent()
{
is_checked := GuiControl_GetValue("EVP", "gu_evpCkbKeepPngTrans")
g_isKeepPngTransparent := is_checked ? true : false
}
Evp_CheckAndWarnConvertBusy()
{
if(g_evpTimerStage!="Monitoring")
{
is_yes := dev_MsgBoxYesNo("Previous converting is in progress. Really cancel?")
if(g_evpTimerStage=="Monitoring")
{
; During above dialog displaying period, the conversion have been completed.
return true ; true means "was busy"
}
if(is_yes)
{
g_evpIsCancelling := true
GuiControl_Enable("EVP", "gu_evpBtnCvtFromClipbrd", false)
; -- so to avoid "repetitive" user-cancel.
is_succ := dev_KillProcessByPid(g_evpBgCvtProcessId, winerr)
if(!is_succ)
{
dev_MsgBoxWarning(Format("dev_KillProcessByPid(pid={}) fails with winerr={}", g_evpBgCvtProcessId, winerr))
}
}
return true ; true means "was busy"
}
else
return false
}
Evp_LaunchConvert_fromClipboard()
{
; evpdbg("In Evp_LaunchConvert_fromClipboard().")
Gui_ChangeOpt( "EVP", "+OwnDialogs")
if(Evp_CheckAndWarnConvertBusy())
return ""
; make it show blank
GuiControl_Show("EVP", "gu_evpIcnWarnNoTranspixel", false)
; -- Memo: Using
; GuiControl_SetText("EVP", "gu_evpIcnWarnNoTranspixel" , "")
; is problematic, bcz it will make the control-window become 0-width,
; so when we next do Gui_Picture_SetIconFromDll(), its width *changes* to
; icon's actual width(no longer 16).
g_evpCurPngHasTranspx := false
Evp_LaunchBatchConvert()
}
Evp_LaunchConvert_fromBaseImage(fpBaseImage)
{
Gui_ChangeOpt( "EVP", "+OwnDialogs")
if(Evp_CheckAndWarnConvertBusy())
return ""
Evp_LaunchBatchConvert(fpBaseImage)
}
Evp_LaunchConvertResetUI()
{
g_evpConvertStartCount++
; Clear listbox
hwndListbox := GuiControl_GetHwnd("EVP", "gu_evpLbxImages")
dev_assert(hwndListbox)
dev_Listbox_Clear(hwndListbox)
GuiControl_Enable("EVP", "gu_evpLbxImages", true)
}
Evp_LaunchBatchConvert(fpFromImage:="", scale_pct:=0)
{
; Return BaseImage filepath, empty string if launching fail.
if(scale_pct==0) {
scale_pct := Evp_GetUIScalePct()
}
if(scale_pct<=1 || scale_pct>100) {
dev_MsgBoxError("Bad Scale percent value(should be 2 ~ 100): " scale_pct)
return ""
}
if(Evp_CheckAndWarnConvertBusy())
return ""
evpdbg(Format("In Evp_LaunchBatchConvert(). `r`n"
. " fpFromImage = {}`r`n"
. " scale_pct = {}"
, fpFromImage, scale_pct))
g_evp_ClipmonSeqAct := g_evp_ClipmonSeqNow ; even if fpimg100pct fails
imgsig := Evp_GenImageSigByTimestamp()
fpimg100pct := Evp_GenerateBaseImage(fpFromImage, scale_pct, imgsig, g_isKeepPngTransparent
, imgw, imgh, fpimgScaled) ; these three are output-vars
; -- filepath of the base-image, example:
; C:\Users\win7evn\AppData\Local\Temp\Everpic\everpic-20221204_150000.png
if(!fpimg100pct)
return "" ; Error should have been pop-up-ed in Evp_GenerateBaseImage()
Evp_LaunchConvertResetUI()
dev_assert(FileExist(fpimgScaled))
; Note: fpimgScaled has wide meaning including 100% or less-than-100% scaling.
; We will pass this fpimgScaled image to .bat .
fpImageStem := dev_SplitExtname(fpimgScaled)
fpImageList := fpImageStem . gc_evpFileSuffix_imagelist
stageline_png32b := Format("PNG (32-bit)*{}`r`n", fpimgScaled)
FileDelete, % fpImageList
FileAppend, % stageline_png32b, % fpImageList
fpbat := gc_evpBatchConvertExecpath
fpbatlog := fpbat ".log"
stdout_to_log := Format("1>""{}"" 2>&1", fpbatlog)
batchcmd := Format("cmd /c @""{}"" ""{}"" {}"
, fpbat
, fpimgScaled
, g_evpDbgCfg.showbgcmd ? "" : stdout_to_log)
; We use `Run`, not `RunWait`, to avoid blocking ourselves.
; `Run` reports success as long as CreateProcess() succeeds. That means,
; only when the target exe/bat(cmd.exe in this case) does not exists will we get ErrorLevel.
; In turn, for `cmd /c foo.bat`, even if foo.bat does not exist, `Run` still report success.
;
; So, we'd better explictly check for .bat existence here.
;
if(!FileExist(fpbat))
{
dev_MsgBoxError(Format("Everpic missing required file: ""{}""", fpbat))
return false
}
;
opt_hidewindow := g_evpDbgCfg.showbgcmd ? "" : "Hide"
dev_SetEnvVar("EverpicSimulateSlowCmd", g_evpDbgCfg.slowbgcmd>0 ? g_evpDbgCfg.slowbgcmd : "") ; .bat code will check this env-var
;
Run, % batchcmd, , UseErrorLevel %opt_hidewindow%, g_evpBgCvtProcessId
if(ErrorLevel)
{ ; Not likely to get this.
dev_MsgBoxError(Format("{} launch error.`n`nSee log file for reason:`n`n{}", fpbat, fpbatlog))
return false
}
evpdbg("Everpic has launched bg-process with pid=" g_evpBgCvtProcessId)
g_evpImageSig := imgsig
g_evpBaseImageFilepath_100pct := fpimg100pct
; g_evpBaseImageFilepath_scaled := fpimgScaled
g_evpCurrentScalePct := scale_pct
g_evpImageWidth := imgw
g_evpImageHeight := imgh
g_evpImglistTxtPath := fpImageList
g_evpBatchProgressFilepath := fpImageStem . gc_evpFileSuffix_progressdone
if(FileExist(g_evpBatchProgressFilepath))
FileDelete, % g_evpBatchProgressFilepath
g_evpTimerStage := "ConvertStarting"
g_evpTickConvertStart := A_TickCount
evpdbg("UIC Enable: gu_evpBtnCvtFromClipbrd")
GuiControl_Enable ("EVP", "gu_evpBtnCvtFromClipbrd", true)
GuiControl_SetText("EVP", "gu_evpBtnCvtFromClipbrd", "Cancel converting")
GuiControl_SetText("EVP", "gu_evpTxtClipbState", "Convert starting...")
Evp_SyncGuiByBaseImage(fpimgScaled, imgw*scale_pct//100, imgh*scale_pct//100)
Evp_ShowAllControls(true)
if(g_evpConvertStartCount==1)
{ ; Center the UI only at the first run.
Gui_Show("EVP", "xCenter yCenter", Evp_WinTitle())
}
return true
}
Evp_GenerateBaseImage(fpFromImage, scale_pct, imgsig, is_keeppngtrans
, byref imgw, byref imgh, byref ofpScaled)
{
; If fpFromImage is empty, generate the base .png image from clipboard.
; Else, fpFromImage is the existing image file to use.
; Return that 100pct .png filepath, empty string if fail.
;
; Return in `ofpScaled` the scaled 32-bit png filepath. 'o' implied output var.
;
; Memo: Whether scale_pct is 100, we always generate 100pct image, so that when
; user changes scale,we can use that 100pct image instead of re-generate from clipboard.
;
; This function does NOT change global vars.
ofpprefix := Evp_BaseImageFilepathPrefix(imgsig)
ptp_suffix := "-ptp"
fp_100pctimg := ofpprefix . (is_keeppngtrans ? ptp_suffix : "") ".png"
fp_scaledimg := dev_AppendToStemname(fp_100pctimg, "-s" scale_pct) ;fp_scaledimg := Format("{}-z{}.png", ofpprefix, scale_pct)
ofpScaled := scale_pct==100 ? fp_100pctimg : fp_scaledimg
if(FileExist(fp_100pctimg) && FileExist(ofpScaled))
{
dev_TooltipAutoClear("BaseImage already exists: " ofpScaled)
return fp_100pctimg
}
is_100pct_succ := false ; assume fail
if(!FileExist(fp_100pctimg))
{
If !pToken := Gdip_Startup()
{
dev_MsgBoxError("Gdip_Startup() failed. GDI+ problem!")
return ""
}
Evp_IsBitmapInClipboard(bitmap_filepath)
if(!fpFromImage && bitmap_filepath)
fpFromImage := bitmap_filepath
if(fpFromImage)
{
if(!FileExist(fpFromImage)) {
dev_MsgBoxError("Image file does not exist:`n`n" fpFromImage)
goto EVP_CLEANUP_20221204
}
; fpFromImage can be any format(bmp, jpg, gif, png etc)
; We need to first save it as 32-bit png, via Gdip libray.
bitmap := Gdip_CreateBitmapFromFile(fpFromImage)
if(bitmap<=0) {
dev_MsgBoxError(Format("Gdip_CreateBitmapFromFile(""{}"") fail, errcode={}.", fp_100pctimg, bitmap))
goto EVP_CLEANUP_20221204
}
Gdip_GetImageDimensions(bitmap, imgw, imgh)
dev_assert(StrIsEndsWith(fp_100pctimg, ".png", true))
if(is_keeppngtrans)
{
err := Gdip_SaveBitmapToFile(bitmap, fp_100pctimg) ; this does not destroy png transparent pixels.
if(err) {
dev_MsgBoxError(Format("Gdip_SaveBitmapToFile(""{}"") fail, errcode={}.", fp_100pctimg, err))
goto EVP_CLEANUP_20221204
}
}
else
{
; Inside Evp_ScaleDownImage, we call Gdip_DrawImage(), which will remove all png transparent pixels.
; so fp_100pctimg will be non-transparent.
succ := Evp_ScaleDownImage(100, fpFromImage, fp_100pctimg, !gc_KeepPngTransparent)
if(!succ) {
goto EVP_CLEANUP_20221204 ; error reported in Evp_ScaleDownImage()
}
}
is_100pct_succ := true
}
else ; will get CF_BITMAP from Clipboard
{
bitmap := Gdip_CreateBitmapFromClipboard()
if(bitmap<=0)
{
if(g_evpConvertStartCount>0)
{
dev_MsgBoxWarning("No bitmap in clipboard yet. Nothing to convert by Everpic.")
}
goto EVP_CLEANUP_20221204
}
Gdip_GetImageDimensions(bitmap, imgw, imgh)
err := Gdip_SaveBitmapToFile(bitmap, fp_100pctimg)
if(err) {
dev_MsgBoxError(Format("Gdip_SaveBitmapToFile(""{}"") fail, errcode={}.", fp_100pctimg, err))
goto EVP_CLEANUP_20221204
}
is_100pct_succ := true
}
EVP_CLEANUP_20221204:
Gdip_DisposeImage(bitmap)
Gdip_Shutdown(pToken)
} ; if(!FileExist(fp_100pctimg))
is_succ := false ; Re-assume faile
;;; Do scale_pct if required to
;
if(is_100pct_succ)
{
if(scale_pct!=100 && !FileExist(fp_scaledimg))
{
succ := Evp_ScaleDownImage(scale_pct, fp_100pctimg, fp_scaledimg, is_keeppngtrans)
if(!succ)
return "" ; Error should have been reported inside Evp_ScaleDownImage()
}
is_succ := true
}
;;; Launch timer to check for png-transparent.
; This checking is very slow, and we do NOT want to block here, so use a timer.
;
if(is_succ && StrIsEndsWith(fpFromImage, ".png", true) && is_keeppngtrans)
{
fn := Func("Evp_TimerProcCheckPngfileTranspixel").Bind(fpFromImage, g_evpConvertStartCount)
SetTimer, % fn, -99 ; one-time timer, start after(99 ms)
}
return is_succ ? fp_100pctimg : ""
}
Evp_WM_MOUSEMOVE(wParam, lParam, msg, hwnd)
{
if(A_Now >= g_evpSuppressUicTooltipBfrThis)
{
evp_ShowUicTooltips(wParam, lParam, msg, hwnd)
}
}
evp_ShowUicTooltips(wParam, lParam, msg, hwnd)
{
static s_prev_tooltiping_uic := 0
is_from_tooltiping_uic := true ; assume message is from a GuiControl
if(A_GuiControl=="gu_evpCkbAutoPaste")
{
dev_TooltipAutoClear("If ticked, ""Use this"" button will paste the selected image into where you have come from(e.g. Evernote window).`r`n"
. "If not ticked, you have to strike Ctrl+V to paste into your target application.")
}
else if(A_GuiControl=="gu_evpCkbKeepWindow")
{
dev_TooltipAutoClear("If ticked, after clicking ""Use this"" button, this Everpic window will remain visible instead of close itself.")
}
else if(A_GuiControl=="gu_evpCkbAutoConvert")
{
dev_TooltipAutoClear("Auto convert when new content in clipboard is detected.")
}
else if(A_GuiControl=="gu_evpBtnCvtFromBaseImg")
{
dev_TooltipAutoClear("Convert from current Base-image using new Scale value.")
}
else if(A_GuiControl=="gu_evpCkbKeepPngTrans")
{
dev_TooltipAutoClear("If ticked, an input png file's transparent pixels remains transparent in output pngs.`n"
. "If not ticked, input transparent pixels becomes white pixels in output pngs.`n`n"
. "This takes effect next time you Convert from Clipboard.")
}
else if(A_GuiControl=="gu_evpIcnWarnNoTranspixel")
{
dev_TooltipAutoClear("This input png file does NOT seem to have transparent pixels.")
}
else if(A_GuiControl=="gu_evpBtnCopyFile")
{
dev_TooltipAutoClear("Copy this file to Clipboard, so that you can paste the file to another folder.")
}
else
is_from_tooltiping_uic := false
if(A_Gui=="EVP")
{