-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathorganizer_display.go
More file actions
1583 lines (1377 loc) · 46.3 KB
/
organizer_display.go
File metadata and controls
1583 lines (1377 loc) · 46.3 KB
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
package main
import (
"bytes"
"encoding/base64"
"errors"
"fmt"
"image"
"image/png"
net_url "net/url"
"os"
"regexp"
"strconv"
"strings"
"sync"
"github.com/charmbracelet/glamour"
"github.com/charmbracelet/glamour/ansi"
"github.com/slzatz/vimango/auth"
)
const (
// PREVIEW_RIGHT_PADDING is the number of columns to reserve as padding
// on the right side of the markdown preview pane (for text and images)
PREVIEW_RIGHT_PADDING = 5
NOTICE_RIGHT_PADDING = 12
)
var (
timeKeywordsRegex = regexp.MustCompile(`seconds|minutes|hours|days`)
emptyImageMarker = strings.Repeat(" ", IMAGE_MARKER_WIDTH)
filledImageMarker = padImageMarker(IMAGE_MARKER_SYMBOL)
// In-memory map of imageID -> dimensions for current render
// Cleared at start of each renderMarkdown() call
currentRenderImageDims = make(map[uint32]struct{ cols, rows int })
currentRenderImageMux sync.RWMutex
// Track which image IDs have been transmitted in this process (kitty session)
kittySessionImageMux sync.RWMutex
kittySessionImages = make(map[uint32]kittySessionEntry) // imageID -> metadata
seededKittyCache bool
trustKittyCache bool
kittyPurgeBeforeRender bool
kittyClearedOnStart bool
kittyIDMap = make(map[string]uint32) // url -> small kitty ID
kittyIDReverse = make(map[uint32]string)
kittyIDNext uint32 = 1
kittyImagesSent uint64
kittyBytesSent uint64
)
type kittySessionEntry struct {
fingerprint string
confirmed bool // true if this process sent the image data
}
func kittyQFlag() string {
if os.Getenv("VIMANGO_KITTY_VERBOSE") != "" {
return "1"
}
return "2"
}
func currentKittyWindowID() string {
return os.Getenv("KITTY_WINDOW_ID")
}
const (
// Transparent placeholder image ID (constant, reused for all images)
KITTY_PLACEHOLDER_IMAGE_ID = 1
KITTY_PLACEHOLDER_PLACEMENT_ID = 1
)
// Reserved for future side-by-side image support (relative placements):
// type pendingRelativePlacement struct {
// imageID uint32
// placementID uint32
// cols int
// rows int
// }
// preparedImage holds the heavy work (load/decode/encode) for a markdown image.
type preparedImage struct {
url string
data []byte
imgW int
imgH int
isGoogleDrive bool
cachedImageID uint32
cachedFingerprint string
err error
source string // "reuse-kitty" | "disk-cache" | "fresh-load"
}
var (
// Track if transparent placeholder has been transmitted
transparentPlaceholderTransmitted = false
// Reserved for future side-by-side image support (relative placements):
// nextRelativePlacementID uint32 = 2 // Start at 2 (1 is reserved for transparent placeholder)
// pendingRelativePlacements []pendingRelativePlacement
// pendingPlacementsMux sync.Mutex
// Ordered list of image IDs for this render (to give deterministic lookups)
currentRenderImageOrder []uint32
currentRenderOrderIdx int
// Map from imageID to URL for metadata lookup during marker replacement
currentRenderImageURLs = make(map[uint32]string)
// Regex to extract markdown images
markdownImageRegex = regexp.MustCompile(`!\[([^\]]*)\]\(([^)]+)\)`)
// Diacritic table for encoding row/column positions in kitty placeholders
kittyDiacritics = []rune{
'\u0305', '\u030D', '\u030E', '\u0310', '\u0312', '\u033D', '\u033E', '\u033F',
'\u0346', '\u034A', '\u034B', '\u034C', '\u0350', '\u0351', '\u0352', '\u0357',
'\u035B', '\u0363', '\u0364', '\u0365', '\u0366', '\u0367', '\u0368', '\u0369',
'\u036A', '\u036B', '\u036C', '\u036D', '\u036E', '\u036F', '\u0483', '\u0484',
}
)
func (o *Organizer) sortColumnStart() int {
return o.Screen.divider - TIME_COL_WIDTH + 2
}
func (o *Organizer) markerColumnStart() int {
sortX := o.sortColumnStart()
markerX := sortX - IMAGE_MARKER_WIDTH - IMAGE_MARKER_AGE_GAP
if markerX <= LEFT_MARGIN+1 {
return LEFT_MARGIN + 2
}
return markerX
}
func (o *Organizer) titleColumnWidth() int {
markerX := o.markerColumnStart()
width := markerX - LEFT_MARGIN - 1
if width < 0 {
return 0
}
return width
}
// should probably be named drawOrgRows
func (o *Organizer) refreshScreen() {
var ab strings.Builder
leftClearWidth := o.Screen.divider - LEFT_MARGIN - 1
if leftClearWidth < 0 {
leftClearWidth = 0
}
leftBlank := strings.Repeat(" ", leftClearWidth)
ab.WriteString("\x1b[?25l") //hides the cursor
//Erases the left side of the screen
for j := TOP_MARGIN; j < o.Screen.textLines+1; j++ {
fmt.Fprintf(&ab, "\x1b[%d;%dH", j+TOP_MARGIN, LEFT_MARGIN) //+1 changed 11282025
ab.WriteString(leftBlank)
}
// }
// put cursor at upper left after erasing
ab.WriteString(fmt.Sprintf("\x1b[%d;%dH", TOP_MARGIN+1, LEFT_MARGIN+1))
fmt.Print(ab.String())
if o.taskview == BY_FIND {
o.drawSearchRows()
//o.drawActive() //////////////////////////
} else {
o.drawRows()
}
}
func (o *Organizer) drawActiveRow(ab *strings.Builder) {
// When drawing the current row there are only two things
// we need to deal with: 1) horizontal scrolling and 2) visual mode highlighting
titlecols := o.titleColumnWidth()
y := o.fr - o.rowoff
row := &o.rows[o.fr]
if o.coloff > 0 {
fmt.Fprintf(ab, "\x1b[%d;%dH\x1b[1K\x1b[%dG", y+TOP_MARGIN+1, titlecols+LEFT_MARGIN+1, LEFT_MARGIN+1)
length := len(row.title) - o.coloff
if length > titlecols {
length = titlecols
}
if length < 0 {
length = 0
}
beg := o.coloff
if len(row.title[beg:]) > length {
ab.WriteString(row.title[beg : beg+length])
} else {
ab.WriteString(row.title[beg:])
}
}
if o.mode == VISUAL {
var j, k int
if o.highlight[1] > o.highlight[0] {
j, k = 0, 1
} else {
k, j = 0, 1
}
fmt.Fprintf(ab, "\x1b[%d;%dH\x1b[1K\x1b[%dG", y+TOP_MARGIN+1, titlecols+LEFT_MARGIN+1, LEFT_MARGIN+1)
ab.WriteString(row.title[o.coloff : o.highlight[j]-o.coloff])
ab.WriteString(LIGHT_GRAY_BG)
ab.WriteString(row.title[o.highlight[j] : o.highlight[k]-o.coloff])
ab.WriteString(RESET)
ab.WriteString(row.title[o.highlight[k]:])
}
}
func (o *Organizer) appendStandardRow(ab *strings.Builder, fr, y, titlecols int) {
row := &o.rows[fr]
// position cursor -note that you don't use lf/cr to position lines
fmt.Fprintf(ab, "\x1b[%d;%dH", y+TOP_MARGIN+1, LEFT_MARGIN+1)
if row.star {
ab.WriteString(BOLD)
}
if timeKeywordsRegex.MatchString(row.sort) {
ab.WriteString(CYAN)
} else {
ab.WriteString(WHITE)
}
if row.archived && row.deleted {
ab.WriteString(GREEN)
} else if row.archived {
ab.WriteString(YELLOW)
} else if row.deleted {
ab.WriteString(RED)
}
if row.dirty {
ab.WriteString(BLACK + WHITE_BG)
}
if _, ok := o.marked_entries[row.id]; ok {
ab.WriteString(BLACK + YELLOW_BG)
}
if len(row.title) > titlecols {
ab.WriteString(row.title[:titlecols])
} else {
ab.WriteString(row.title)
ab.WriteString(strings.Repeat(" ", titlecols-len(row.title)))
}
ab.WriteString(RESET)
o.writeImageMarker(ab, y, row.hasImage)
ab.WriteString(WHITE)
sortX := o.Screen.divider - TIME_COL_WIDTH + 2
width := o.Screen.divider - sortX
if width > 0 {
fmt.Fprintf(ab, "\x1b[%d;%dH", y+TOP_MARGIN+1, sortX)
ab.WriteString(strings.Repeat(" ", width))
fmt.Fprintf(ab, "\x1b[%d;%dH", y+TOP_MARGIN+1, sortX)
if len(row.sort) > width {
ab.WriteString(row.sort[:width])
} else {
ab.WriteString(row.sort)
}
}
ab.WriteString(RESET)
}
func (o *Organizer) appendSearchRow(ab *strings.Builder, fr, y, titlecols int) {
row := &o.rows[fr]
fmt.Fprintf(ab, "\x1b[%d;%dH", y+TOP_MARGIN+1, LEFT_MARGIN+1)
if row.star {
ab.WriteString(BOLD)
}
if timeKeywordsRegex.MatchString(row.sort) {
ab.WriteString(CYAN)
} else {
ab.WriteString(WHITE)
}
if row.archived && row.deleted {
ab.WriteString(GREEN)
} else if row.archived {
ab.WriteString(YELLOW)
} else if row.deleted {
ab.WriteString(RED)
}
if row.dirty {
ab.WriteString(BLACK + WHITE_BG)
}
if _, ok := o.marked_entries[row.id]; ok {
ab.WriteString(BLACK + YELLOW_BG)
}
if len(row.title) <= titlecols {
ab.WriteString(row.ftsTitle)
} else {
pos := strings.Index(row.ftsTitle, "\x1b[49m")
if pos > 0 && pos < titlecols+11 && len(row.ftsTitle) >= titlecols+15 {
ab.WriteString(row.ftsTitle[:titlecols+15])
} else {
ab.WriteString(row.title[:titlecols])
}
}
length := len(row.title)
if length > titlecols {
length = titlecols
}
if spaces := titlecols - length; spaces > 0 {
ab.WriteString(strings.Repeat(" ", spaces))
}
ab.WriteString(RESET)
o.writeImageMarker(ab, y, row.hasImage)
sortX := o.Screen.divider - TIME_COL_WIDTH + 2
width := o.Screen.divider - sortX
if width > 0 {
fmt.Fprintf(ab, "\x1b[%d;%dH", y+TOP_MARGIN+1, sortX)
ab.WriteString(strings.Repeat(" ", width))
fmt.Fprintf(ab, "\x1b[%d;%dH", y+TOP_MARGIN+1, sortX)
if len(row.sort) > width {
ab.WriteString(row.sort[:width])
} else {
ab.WriteString(row.sort)
}
}
ab.WriteString(RESET)
}
func (o *Organizer) writeImageMarker(ab *strings.Builder, y int, hasImage bool) {
markerX := o.markerColumnStart()
if markerX <= LEFT_MARGIN {
return
}
fmt.Fprintf(ab, "\x1b[%d;%dH", y+TOP_MARGIN+1, markerX)
ab.WriteString(WHITE)
if hasImage {
ab.WriteString(filledImageMarker)
} else {
ab.WriteString(emptyImageMarker)
}
ab.WriteString(RESET)
for i := 0; i < IMAGE_MARKER_AGE_GAP; i++ {
fmt.Fprintf(ab, "\x1b[%d;%dH \x1b[37;1mx\x1b[0m", y+TOP_MARGIN+1, markerX+IMAGE_MARKER_WIDTH+i)
}
}
func padImageMarker(symbol string) string {
if IMAGE_MARKER_WIDTH <= 0 {
return ""
}
runes := []rune(symbol)
runeLen := len(runes)
if runeLen == 0 {
return emptyImageMarker
}
if runeLen >= IMAGE_MARKER_WIDTH {
return string(runes[:IMAGE_MARKER_WIDTH])
}
return symbol + strings.Repeat(" ", IMAGE_MARKER_WIDTH-runeLen)
}
func (o *Organizer) drawRows() {
if len(o.rows) == 0 {
return
}
var ab strings.Builder
titlecols := o.titleColumnWidth()
for y := 0; y < o.Screen.textLines; y++ {
fr := y + o.rowoff
if fr > len(o.rows)-1 {
break
}
o.appendStandardRow(&ab, fr, y, titlecols)
}
// instances that require a full redraw do not require separate drawing of active row
//o.drawActiveRow(&ab)
ab.WriteString(RESET)
fmt.Print(ab.String())
}
// for drawing containers when making a selection
func (o *Organizer) drawAltRows() {
if len(o.altRows) == 0 {
return
}
var ab strings.Builder
fmt.Fprintf(&ab, "\x1b[%d;%dH", TOP_MARGIN+1, o.Screen.divider+2)
lf_ret := fmt.Sprintf("\r\n\x1b[%dC", o.Screen.divider+1)
for y := 0; y < o.Screen.textLines; y++ {
fr := y + o.altRowoff
if fr > len(o.altRows)-1 {
break
}
length := len(o.altRows[fr].title)
if length > o.Screen.totaleditorcols {
length = o.Screen.totaleditorcols
}
if o.altRows[fr].star {
ab.WriteString("\x1b[1m") //bold
ab.WriteString("\x1b[1;36m")
}
if fr == o.altFr {
ab.WriteString("\x1b[48;5;236m") // 236 is a grey
}
ab.WriteString(o.altRows[fr].title[:length])
ab.WriteString("\x1b[0m") // return background to normal
ab.WriteString(lf_ret)
}
fmt.Print(ab.String())
}
func (o *Organizer) drawRenderedNote() {
if debugLog, err := os.OpenFile("kitty_debug.log", os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666); err == nil {
fmt.Fprintf(debugLog, "drawRenderedNote: ENTER (note has %d lines)\n", len(o.note))
debugLog.Close()
}
if len(o.note) == 0 {
return
}
start := o.altRowoff
var end int
// check if there are more lines than can fit on the screen
if len(o.note)-start > o.Screen.textLines-1 {
end = o.Screen.textLines + start
} else {
//end = len(o.note) - 1
end = len(o.note)
}
if debugLog, err := os.OpenFile("kitty_debug.log", os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666); err == nil {
fmt.Fprintf(debugLog, "drawRenderedNote: printing lines %d to %d\n", start, end)
debugLog.Close()
}
fmt.Fprintf(os.Stdout, "\x1b[%d;%dH", TOP_MARGIN+1, o.Screen.divider+1)
lf_ret := fmt.Sprintf("\r\n\x1b[%dC", o.Screen.divider+0)
fmt.Print(strings.Join(o.note[start:end], lf_ret))
fmt.Print(RESET) //sometimes there is an unclosed escape sequence
// Note: With Unicode placeholders (U+10EEEE), we don't need separate placements
// The placeholders are embedded directly in the text and reference the transmitted images
// Calling createImagePlacementsAtPositions() would delete the images!
if debugLog, err := os.OpenFile("kitty_debug.log", os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666); err == nil {
fmt.Fprintf(debugLog, "drawRenderedNote: COMPLETE\n")
debugLog.Close()
}
}
// deleteAllKittyPlacements deletes all kitty image placements
func deleteAllKittyPlacements() {
if !app.kitty {
return
}
oscOpen, oscClose := "\x1b_G", "\x1b\\"
if IsTmuxScreen() {
oscOpen = "\x1bPtmux;\x1b\x1b_G"
oscClose = "\x1b\x1b\\\\\x1b\\"
}
// Delete all placements: a=d (delete), d=A (all placements)
cmd := oscOpen + "a=d,d=A,q=1" + oscClose
fmt.Fprint(os.Stdout, cmd)
os.Stdout.Sync()
if debugLog, err := os.OpenFile("kitty_debug.log", os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666); err == nil {
fmt.Fprintf(debugLog, "DELETED: all kitty placements\n")
debugLog.Close()
}
}
// createKittyPlacement creates a placement at the current cursor position
func createKittyPlacement(imageID uint32, cols, rows int) error {
if !app.kitty {
return errors.New("kitty terminal not detected")
}
oscOpen, oscClose := "\x1b_G", "\x1b\\"
if IsTmuxScreen() {
oscOpen = "\x1bPtmux;\x1b\x1b_G"
oscClose = "\x1b\x1b\\\\\x1b\\"
}
// Create placement at current cursor position: a=p (place), i=imageID, c=cols, r=rows
args := []string{
"a=p",
"q=1", // show errors
fmt.Sprintf("i=%d", imageID),
}
if cols > 0 {
args = append(args, fmt.Sprintf("c=%d", cols))
}
if rows > 0 {
args = append(args, fmt.Sprintf("r=%d", rows))
}
cmd := oscOpen + strings.Join(args, ",") + oscClose
_, err := fmt.Fprint(os.Stdout, cmd)
return err
}
// createImagePlacementsAtPositions creates kitty image placements at the correct screen positions
func (o *Organizer) createImagePlacementsAtPositions(startLine, endLine int) {
if !app.kitty {
return
}
// First, delete all existing placements
deleteAllKittyPlacements()
// Parse each visible line for image markers
imageMarkerRegex := regexp.MustCompile(`\[KITTY_IMAGE:id=(\d+),cols=(\d+),rows=(\d+)\]`)
for lineIdx := startLine; lineIdx < endLine && lineIdx < len(o.note); lineIdx++ {
line := o.note[lineIdx]
matches := imageMarkerRegex.FindAllStringSubmatch(line, -1)
for _, match := range matches {
if len(match) != 4 {
continue
}
imageID, _ := strconv.ParseUint(match[1], 10, 32)
cols, _ := strconv.Atoi(match[2])
rows, _ := strconv.Atoi(match[3])
// Calculate screen position
screenRow := TOP_MARGIN + 1 + (lineIdx - startLine)
screenCol := o.Screen.divider + 1
// Move cursor to position
fmt.Fprintf(os.Stdout, "\x1b[%d;%dH", screenRow, screenCol)
// Create placement at current cursor position
if err := createKittyPlacement(uint32(imageID), cols, rows); err != nil {
if debugLog, err := os.OpenFile("kitty_debug.log", os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666); err == nil {
fmt.Fprintf(debugLog, "ERROR creating placement: %v\n", err)
debugLog.Close()
}
} else {
if debugLog, err := os.OpenFile("kitty_debug.log", os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666); err == nil {
fmt.Fprintf(debugLog, "PLACEMENT: created i=%d at row=%d,col=%d (%dx%d cells)\n",
imageID, screenRow, screenCol, cols, rows)
debugLog.Close()
}
}
}
}
// Flush output
os.Stdout.Sync()
}
// Reserved for future side-by-side image support (relative placements):
// createPendingRelativePlacements creates all pending relative placements after Unicode placeholders are drawn
// func createPendingRelativePlacements() {
// pendingPlacementsMux.Lock()
// defer pendingPlacementsMux.Unlock()
//
// if len(pendingRelativePlacements) == 0 {
// return
// }
//
// for _, p := range pendingRelativePlacements {
// if err := kittyCreateRelativePlacement(os.Stdout, p.imageID, p.placementID,
// KITTY_PLACEHOLDER_IMAGE_ID, KITTY_PLACEHOLDER_PLACEMENT_ID,
// p.cols, p.rows, 0, 0); err != nil {
// if debugLog, err := os.OpenFile("kitty_debug.log", os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666); err == nil {
// fmt.Fprintf(debugLog, "ERROR creating relative placement: %v\n", err)
// debugLog.Close()
// }
// } else {
// if debugLog, err := os.OpenFile("kitty_debug.log", os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666); err == nil {
// fmt.Fprintf(debugLog, "CREATED RELATIVE PLACEMENT: i=%d, p=%d, P=%d, Q=%d, c=%d, r=%d\n",
// p.imageID, p.placementID, KITTY_PLACEHOLDER_IMAGE_ID, KITTY_PLACEHOLDER_PLACEMENT_ID, p.cols, p.rows)
// debugLog.Close()
// }
// }
// }
//
// // Clear pending list
// pendingRelativePlacements = nil
//
// // Ensure all commands are sent to kitty immediately
// os.Stdout.Sync()
//
// if debugLog, err := os.OpenFile("kitty_debug.log", os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666); err == nil {
// fmt.Fprintf(debugLog, "FLUSHED: all relative placement commands sent to kitty\n")
// debugLog.Close()
// }
// }
func (o *Organizer) drawStatusBar() {
var ab strings.Builder
//position cursor and erase - and yes you do have to reposition cursor after erase
fmt.Fprintf(&ab, "\x1b[%d;%dH\x1b[1K\x1b[%d;1H", o.Screen.textLines+TOP_MARGIN+1, o.Screen.divider, o.Screen.textLines+TOP_MARGIN+1)
ab.WriteString("\x1b[7m") //switches to reversed colors
var str string
var id int
var title string
var keywords string
if len(o.rows) > 0 {
switch o.view {
case TASK:
id = o.getId()
switch o.taskview {
case BY_FIND:
str = "search - " + o.Session.fts_search_terms
case BY_FOLDER:
//str = fmt.Sprintf("%s[f] (%s[c])", o.filter, o.Database.taskContext(id))
//folder could have been changed so show task's folder
str = fmt.Sprintf("%s[f] (%s[c])", o.Database.taskFolder(id), o.Database.taskContext(id))
case BY_CONTEXT:
//str = fmt.Sprintf("%s[c] (%s[f])", o.filter, o.Database.taskFolder(id))
//context could have been changed so show task's context
str = fmt.Sprintf("%s[c] (%s[f])", o.Database.taskContext(id), o.Database.taskFolder(id))
case BY_RECENT:
str = fmt.Sprintf("Recent: %s[c] %s[f]",
o.Database.taskContext(id), o.Database.taskFolder(id))
case BY_KEYWORD:
str = o.filter + "[k]"
}
case CONTEXT:
str = "Contexts"
case FOLDER:
str = "Folders"
case KEYWORD:
str = "Keywords"
//case SYNC_LOG_VIEW:
// str = "Sync Log"
default:
str = "Other"
}
row := &o.rows[o.fr]
if len(row.title) > 16 {
title = row.title[:12] + "..."
} else {
title = row.title
}
id = row.id
if o.view == TASK {
keywords = o.Database.getTaskKeywords(row.id)
}
} else {
title = " No Results "
id = -1
}
// [49m - revert background to normal
// 7m - reverses video
// because video is reversted [42 sets text to green and 49 undoes it
// also [0;35;7m -> because of 7m it reverses background and foreground
// [0;7m is revert text to normal and reverse video
status := fmt.Sprintf("\x1b[1m%s\x1b[0;7m %s \x1b[0;35;7m%s\x1b[0;7m %d %d/%d \x1b[1;42m%%s\x1b[0;7m sort: %s ",
str, title, keywords, id, o.fr+1, len(o.rows), o.sort)
// klugy way of finding length of string without the escape characters
plain := fmt.Sprintf("%s %s %s %d %d/%d sort: %s ",
str, title, keywords, id, o.fr+1, len(o.rows), o.sort)
length := len(plain)
if length+len(fmt.Sprintf("%s", o.mode)) <= o.Screen.divider {
/*
s := fmt.Sprintf("%%-%ds", o.divider-length) // produces "%-25s"
t := fmt.Sprintf(s, o.mode)
fmt.Fprintf(&ab, status, t)
*/
fmt.Fprintf(&ab, status, fmt.Sprintf(fmt.Sprintf("%%-%ds", o.Screen.divider-length), o.mode))
} else {
status = fmt.Sprintf("\x1b[1m%s\x1b[0;7m %s \x1b[0;35;7m%s\x1b[0;7m %d %d/%d\x1b[49m",
str, title, keywords, id, o.fr+1, len(o.rows))
plain = fmt.Sprintf("%s %s %s %d %d/%d",
str, title, keywords, id, o.fr+1, len(o.rows))
length := len(plain)
if length < o.Screen.divider {
fmt.Fprintf(&ab, "%s%-*s", status, o.Screen.divider-length, " ")
} else {
status = fmt.Sprintf("\x1b[1m%s\x1b[0;7m %s %s %d %d/%d",
str, title, keywords, id, o.fr+1, len(o.rows))
ab.WriteString(status[:o.Screen.divider+10])
}
}
ab.WriteString("\x1b[0m") //switches back to normal formatting
fmt.Print(ab.String())
}
func (o *Organizer) drawSearchRows() {
if len(o.rows) == 0 {
return
}
var ab strings.Builder
titlecols := o.titleColumnWidth()
for y := 0; y < o.Screen.textLines; y++ {
fr := y + o.rowoff
if fr > len(o.rows)-1 {
break
}
o.appendSearchRow(&ab, fr, y, titlecols)
}
fmt.Print(ab.String())
}
// should be removed after more testing
func (o *Organizer) drawRowAt(fr int) {
if fr < 0 || fr >= len(o.rows) {
return
}
if fr < o.rowoff || fr >= o.rowoff+o.Screen.textLines {
return
}
titlecols := o.titleColumnWidth()
y := fr - o.rowoff
var ab strings.Builder
if o.taskview == BY_FIND {
o.appendSearchRow(&ab, fr, y, titlecols)
} else {
o.appendStandardRow(&ab, fr, y, titlecols)
}
fmt.Print(ab.String())
}
func (o *Organizer) drawActive() {
// When doing a partial redraw, we first draw the standard row, then
// address horizontal scrolling and visual mode highlighting
titlecols := o.titleColumnWidth()
y := o.fr - o.rowoff
var ab strings.Builder
o.appendStandardRow(&ab, o.fr, y, titlecols)
o.drawActiveRow(&ab)
fmt.Print(ab.String())
}
func (o *Organizer) erasePreviousRowMarker(prevRow int) {
y := prevRow - o.rowoff
fmt.Fprintf(os.Stdout, "\x1b[%d;%dH ", y+TOP_MARGIN+1, 0)
}
// deleteAllKittyImages sends delete command for all cached kitty images
func deleteAllKittyImages() {
if !app.kitty || !app.kittyPlace {
return
}
oscOpen, oscClose := "\x1b_G", "\x1b\\"
if IsTmuxScreen() {
oscOpen = "\x1bPtmux;\x1b\x1b_G"
oscClose = "\x1b\x1b\\\\\x1b\\"
}
// Delete all images: a=d (delete), d=A (all images)
deleteCmd := oscOpen + "a=d,d=A" + oscClose
os.Stdout.WriteString(deleteCmd)
}
// render and display the markdown note
func (o *Organizer) displayNote() {
if len(o.rows) == 0 {
o.Screen.eraseRightScreen()
return
}
id := o.rows[o.fr].id
var note string
if o.taskview != BY_FIND {
note = o.Database.readNoteIntoString(id)
} else {
note = o.Database.highlightTerms2(id)
}
o.Screen.eraseRightScreen()
if o.Database.taskFolder(id) == "code" {
c := o.Database.taskContext(id)
if lang, ok := Languages[c]; ok {
o.renderCode(note, lang)
o.drawRenderedNote()
} else {
app.RenderManager.StartRender(id, note, o.Screen.totaleditorcols)
}
} else {
// Always use RenderManager for markdown- it handles all cases internally
// (kitty/no-kitty, images/no-images, cached/uncached)
app.RenderManager.StartRender(id, note, o.Screen.totaleditorcols)
}
}
func (o *Organizer) renderCode(s string, lang string) {
var buf bytes.Buffer
_ = Highlight(&buf, s, lang, "terminal16m", o.Session.style[o.Session.styleIndex])
note := buf.String()
if o.taskview == BY_FIND {
// could use strings.Count to make sure they are balanced
note = strings.ReplaceAll(note, "qx", "\x1b[48;5;31m") //^^
note = strings.ReplaceAll(note, "qy", "\x1b[0m") // %%
}
note = WordWrap(note, o.Screen.totaleditorcols, 0)
o.note = strings.Split(note, "\n")
}
func (o *Organizer) drawRenderedNote_() {
if len(o.note) == 0 {
return
}
start := o.altRowoff
var end int
// check if there are more lines than can fit on the screen
if len(o.note)-start > o.Screen.textLines-1 {
end = o.Screen.textLines + start
} else {
//end = len(o.note) - 1
end = len(o.note)
}
fmt.Fprintf(os.Stdout, "\x1b[%d;%dH", TOP_MARGIN+1, o.Screen.divider+1)
lf_ret := fmt.Sprintf("\r\n\x1b[%dC", o.Screen.divider+0)
fmt.Print(strings.Join(o.note[start:end], lf_ret))
fmt.Print(RESET) //sometimes there is an unclosed escape sequence
}
// extractImageURLs extracts all image URLs from markdown
func extractImageURLs(markdown string) []string {
matches := markdownImageRegex.FindAllStringSubmatch(markdown, -1)
urls := make([]string, 0, len(matches))
for _, match := range matches {
if len(match) > 2 {
urls = append(urls, match[2]) // match[2] is the URL
}
}
return urls
}
// prepareKittyImage loads and encodes an image (possibly from cache) without transmitting it.
// It is safe to run concurrently.
func prepareKittyImage(url string) *preparedImage {
initImageCache()
res := &preparedImage{
url: url,
isGoogleDrive: strings.HasPrefix(url, "gdrive:") || strings.Contains(url, "drive.google.com"),
source: "fresh-load",
}
var imgObj image.Image
// Try cache metadata first (kitty reuse)
if globalImageCache != nil {
if entry, ok := globalImageCache.GetKittyMeta(url); ok {
res.cachedImageID = entry.ImageID
res.cachedFingerprint = entry.Fingerprint
res.imgW = entry.Width
res.imgH = entry.Height
}
}
// Load cached base64 if available (Drive only)
if res.isGoogleDrive && globalImageCache != nil {
if cachedBase64, width, height, found := globalImageCache.GetCachedImageData(url); found {
decoded, err := base64.StdEncoding.DecodeString(cachedBase64)
if err == nil {
res.data = decoded
res.imgW = width
res.imgH = height
if res.cachedFingerprint == "" {
res.cachedFingerprint = hashString(cachedBase64)
}
res.source = "disk-cache"
return res
}
}
}
// Load fresh
img, err := loadImageForGlamour(url)
if err != nil {
res.err = err
return res
}
imgObj = img
res.imgW = imgObj.Bounds().Dx()
res.imgH = imgObj.Bounds().Dy()
// Encode to PNG
var buf bytes.Buffer
if err := png.Encode(&buf, imgObj); err != nil {
res.err = err
return res
}
res.data = buf.Bytes()
// Cache Drive images
if res.isGoogleDrive && globalImageCache != nil {
base64Data := base64.StdEncoding.EncodeToString(res.data)
res.cachedFingerprint = hashString(base64Data)
_ = globalImageCache.StoreCachedImageData(url, base64Data, res.imgW, res.imgH)
// Also fetch and cache Google Drive metadata (filename, folder)
if fileID, err := ExtractFileID(url); err == nil && app.Session.googleDrive != nil {
if fileName, folderName, err := auth.GetGDriveFileInfo(app.Session.googleDrive, fileID); err == nil {
_ = globalImageCache.UpdateGDriveMeta(url, fileName, folderName)
}
}
}
if res.cachedFingerprint == "" {
res.cachedFingerprint = hashBytes(res.data)
}
return res
}
// transmitPreparedKittyImage transmits (or reuses) a prepared image and returns imageID, cols, rows.
// Must be called in render order to keep Glamour's lookup ordering intact.
func transmitPreparedKittyImage(prep *preparedImage, maxCols int) (uint32, int, int) {
if prep == nil || prep.err != nil || prep.imgW == 0 || prep.imgH == 0 {
return 0, 0, 0
}
targetCols := maxCols - 2
if targetCols <= 0 || targetCols > app.imageScale {
targetCols = app.imageScale
}
rows := int(float64(prep.imgH) / float64(prep.imgW) * float64(targetCols) * 0.42)
if rows < 1 {
rows = 1
}
isTmux := IsTmuxScreen()
// Reuse if fingerprint matches cache
if prep.cachedImageID != 0 && prep.cachedFingerprint != "" {
kittySessionImageMux.RLock()
entry, ok := kittySessionImages[prep.cachedImageID]
kittySessionImageMux.RUnlock()
if ok && (entry.fingerprint == prep.cachedFingerprint || entry.fingerprint == "") && (entry.confirmed || trustKittyCache) {
if debugLog, err := os.OpenFile("kitty_debug.log", os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666); err == nil {
fmt.Fprintf(debugLog, "transmitKittyImage[reuse-kitty]: %s -> ID=%d, cols=%d, rows=%d\n",
prep.url, prep.cachedImageID, targetCols, rows)
debugLog.Close()
}
_ = kittyUpdateVirtualPlacement(prep.cachedImageID, targetCols, rows, isTmux)
if prep.isGoogleDrive && globalImageCache != nil {
_ = globalImageCache.UpdateKittyMeta(prep.url, prep.cachedImageID, targetCols, rows, prep.cachedFingerprint)
}
return prep.cachedImageID, targetCols, rows
}
}
// Need to transmit
imageID := nextSmallKittyID(prep.url)
if debugLog, err := os.OpenFile("kitty_debug.log", os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666); err == nil {
fmt.Fprintf(debugLog, "transmitKittyImage[%s]: %s -> ID=%d, cols=%d, rows=%d (scale=%d)\n",
prep.source, prep.url, imageID, targetCols, rows, app.imageScale)
debugLog.Close()
}
if err := kittyTransmitActualImage(prep.data, imageID, targetCols, rows, isTmux); err != nil {
return 0, 0, 0
}
kittySessionImageMux.Lock()
kittySessionImages[imageID] = kittySessionEntry{
fingerprint: prep.cachedFingerprint,
confirmed: true,
}
kittySessionImageMux.Unlock()
if prep.isGoogleDrive && globalImageCache != nil {
_ = globalImageCache.UpdateKittyMeta(prep.url, imageID, targetCols, rows, prep.cachedFingerprint)
}
return imageID, targetCols, rows
}
// replaceImagesWithPlaceholders replaces glamour's image output with kitty placeholders