-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathorganizer_render.go
More file actions
470 lines (398 loc) · 11.4 KB
/
organizer_render.go
File metadata and controls
470 lines (398 loc) · 11.4 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
package main
import (
"fmt"
"strings"
"sync"
"time"
"github.com/charmbracelet/glamour"
"github.com/charmbracelet/glamour/ansi"
)
// RenderRequest represents an async rendering request for a note
type RenderRequest struct {
RequestID string // Unique: "note_<id>_<timestamp>"
NoteID int // Database ID of note
Markdown string // Note content
MaxCols int // Maximum columns for rendering
CancelCh chan struct{}
CreatedAt time.Time
}
// RenderResult represents the result of a background render
type RenderResult struct {
RequestID string
NoteID int
RenderedLines []string
Success bool
}
// RenderManager coordinates async rendering of notes
type RenderManager struct {
app *App
organizer *Organizer
currentRequest *RenderRequest
mutex sync.RWMutex
// Channel for render results
resultCh chan RenderResult
// Lifecycle
running bool
stopCh chan struct{}
wg sync.WaitGroup
}
// NewRenderManager creates and initializes the render manager
func NewRenderManager(app *App) *RenderManager {
rm := &RenderManager{
app: app,
organizer: app.Organizer,
resultCh: make(chan RenderResult, 5),
stopCh: make(chan struct{}),
}
rm.start()
return rm
}
// start initializes the result handler goroutine
func (rm *RenderManager) start() {
rm.running = true
// Start result handler
rm.wg.Add(1)
go rm.resultHandler()
}
// Stop shuts down the render manager
func (rm *RenderManager) Stop() {
rm.running = false
close(rm.stopCh)
// Cancel current request if any
rm.mutex.Lock()
if rm.currentRequest != nil {
select {
case <-rm.currentRequest.CancelCh:
// Already closed
default:
close(rm.currentRequest.CancelCh)
}
}
rm.mutex.Unlock()
// Wait for handlers with timeout
done := make(chan struct{})
go func() {
rm.wg.Wait()
close(done)
}()
select {
case <-done:
// Clean shutdown
case <-time.After(2 * time.Second):
// Timeout, force continue
}
close(rm.resultCh)
}
// StartRender initiates async rendering of a note
// It immediately renders text-only, then starts background full render with images
// If all images are already in kitty's session cache, it skips text-only and renders directly
func (rm *RenderManager) StartRender(noteID int, markdown string, maxCols int) {
// Cancel any previous render
rm.mutex.Lock()
if rm.currentRequest != nil {
select {
case <-rm.currentRequest.CancelCh:
// Already closed
default:
close(rm.currentRequest.CancelCh)
}
}
// Create new render request
req := &RenderRequest{
RequestID: fmt.Sprintf("note_%d_%d", noteID, time.Now().UnixNano()),
NoteID: noteID,
Markdown: markdown,
MaxCols: maxCols,
CancelCh: make(chan struct{}),
CreatedAt: time.Now(),
}
rm.currentRequest = req
rm.mutex.Unlock()
// Check if images are enabled
if !app.kitty || !app.showImages {
// No images mode - just render text
textLines := rm.renderTextOnly(markdown, maxCols)
rm.organizer.note = textLines
rm.organizer.drawRenderedNote()
return
}
// Check if there are any images in the markdown
imageURLs := extractImageURLs(markdown)
if len(imageURLs) == 0 {
// No images in this note - just render text
textLines := rm.renderTextOnly(markdown, maxCols)
rm.organizer.note = textLines
rm.organizer.drawRenderedNote()
return
}
// Check if ALL images are in kitty's session cache
// If so, full render will be fast and we can skip the text-only phase
if rm.allImagesInKittyCache(imageURLs) {
// Fast path: all images cached, render directly with images
lines := rm.renderFullWithImages(req)
if lines != nil {
rm.organizer.note = lines
rm.organizer.drawRenderedNote()
}
return
}
// Slow path: some images need loading
// Phase 1: Render text-only immediately (no images)
textLines := rm.renderTextOnly(markdown, maxCols)
// Display text-only version immediately
rm.organizer.note = textLines
rm.organizer.drawRenderedNote()
// Show status that images are loading
rm.organizer.ShowMessage(BR, "Loading %d image(s)...", len(imageURLs))
// Phase 2: Start background goroutine for full render with images
go rm.backgroundRender(req)
}
// allImagesInKittyCache checks if all image URLs are in kitty's session cache
// This means they can be reused without network/disk loading
func (rm *RenderManager) allImagesInKittyCache(imageURLs []string) bool {
if globalImageCache == nil {
return false
}
for _, url := range imageURLs {
// Check if we have cached metadata with a valid image ID
entry, ok := globalImageCache.GetKittyMeta(url)
if !ok || entry.ImageID == 0 {
return false
}
// Check if this image ID is in the kitty session cache
kittySessionImageMux.RLock()
sessionEntry, inSession := kittySessionImages[entry.ImageID]
kittySessionImageMux.RUnlock()
if !inSession {
return false
}
// Check if the session entry is confirmed or we trust the cache
if !sessionEntry.confirmed && !trustKittyCache {
return false
}
}
return true
}
// renderTextOnly renders markdown without images (fast path)
func (rm *RenderManager) renderTextOnly(markdown string, maxCols int) []string {
// Render markdown without kitty images
options := []glamour.TermRendererOption{
glamour.WithStylePath(getGlamourStylePath()),
glamour.WithWordWrap(0),
// Note: NOT enabling kitty images here
}
r, err := glamour.NewTermRenderer(options...)
if err != nil {
return []string{"Error creating renderer: " + err.Error()}
}
note, err := r.Render(markdown)
if err != nil {
return []string{"Error rendering: " + err.Error()}
}
note = strings.TrimSpace(note)
// Decode any Kitty text sizing markers (OSC 66) that were protected during glamour processing
note = ansi.DecodeKittyTextSizeMarkers(note)
// Handle search highlighting
if rm.organizer.taskview == BY_FIND {
note = strings.ReplaceAll(note, "qx", "\x1b[48;5;31m")
note = strings.ReplaceAll(note, "qy", "\x1b[0m")
}
note = WordWrap(note, maxCols-PREVIEW_RIGHT_PADDING, 0)
return strings.Split(note, "\n")
}
// backgroundRender performs the full render with images in a background goroutine
func (rm *RenderManager) backgroundRender(req *RenderRequest) {
// Check for cancellation before starting
select {
case <-req.CancelCh:
return
case <-rm.stopCh:
return
default:
}
// Perform the full render using existing renderMarkdown logic
// This includes image loading, transmission, and proper placeholder sizing
lines := rm.renderFullWithImages(req)
// Check for cancellation before sending result
select {
case <-req.CancelCh:
return
case <-rm.stopCh:
return
default:
}
// Send result
select {
case rm.resultCh <- RenderResult{
RequestID: req.RequestID,
NoteID: req.NoteID,
RenderedLines: lines,
Success: true,
}:
case <-req.CancelCh:
case <-rm.stopCh:
}
}
// renderFullWithImages performs the complete render with images
// This replicates the logic from renderMarkdown but returns lines instead of setting o.note
func (rm *RenderManager) renderFullWithImages(req *RenderRequest) []string {
o := rm.organizer
markdown := req.Markdown
maxCols := req.MaxCols
// Check cancellation
select {
case <-req.CancelCh:
return nil
default:
}
// Pre-transmit kitty images (same logic as renderMarkdown)
if app.kitty && app.kittyPlace && app.showImages {
seedKittySessionFromCache()
// Clear the dimension map for this render
currentRenderImageMux.Lock()
currentRenderImageDims = make(map[uint32]struct{ cols, rows int })
currentRenderImageURLs = make(map[uint32]string)
nextImageLookupID = 1
currentRenderImageOrder = currentRenderImageOrder[:0]
currentRenderOrderIdx = 0
currentRenderImageMux.Unlock()
imageURLs := extractImageURLs(markdown)
if len(imageURLs) > 0 {
// Check cancellation before image loading
select {
case <-req.CancelCh:
return nil
default:
}
// Parallel prepare with bounded workers, then ordered transmit
preparedMap := make(map[string]*preparedImage)
type job struct{ url string }
type result struct {
prep *preparedImage
}
jobCh := make(chan job)
resCh := make(chan result, len(imageURLs))
var wg sync.WaitGroup
workers := 6
for i := 0; i < workers; i++ {
wg.Add(1)
go func() {
defer wg.Done()
for j := range jobCh {
// Check cancellation in worker
select {
case <-req.CancelCh:
return
default:
resCh <- result{prep: prepareKittyImage(j.url)}
}
}
}()
}
// Deduplicate URLs
seen := make(map[string]bool)
for _, url := range imageURLs {
if !seen[url] {
seen[url] = true
jobCh <- job{url: url}
}
}
close(jobCh)
go func() {
wg.Wait()
close(resCh)
}()
for r := range resCh {
if r.prep != nil {
preparedMap[r.prep.url] = r.prep
}
}
// Check cancellation before transmission
select {
case <-req.CancelCh:
return nil
default:
}
// Ordered transmit to keep kitty IDs aligned with markdown order
for _, url := range imageURLs {
prep := preparedMap[url]
imageID, cols, rows := transmitPreparedKittyImage(prep, o.Screen.totaleditorcols-PREVIEW_RIGHT_PADDING)
if imageID != 0 {
currentRenderImageMux.Lock()
currentRenderImageDims[imageID] = struct{ cols, rows int }{cols, rows}
currentRenderImageOrder = append(currentRenderImageOrder, imageID)
currentRenderImageURLs[imageID] = url
currentRenderImageMux.Unlock()
}
}
}
}
// Check cancellation before glamour render
select {
case <-req.CancelCh:
return nil
default:
}
// Configure renderer WITH kitty support
options := []glamour.TermRendererOption{
glamour.WithStylePath(getGlamourStylePath()),
glamour.WithWordWrap(0),
}
if app.kitty && app.kittyPlace && app.showImages {
options = append(options, glamour.WithKittyImages(true, kittyImageCacheLookup))
}
r, _ := glamour.NewTermRenderer(options...)
note, _ := r.Render(markdown)
// Replace glamour's text markers with actual Unicode placeholder grids
if app.kitty && app.kittyPlace && app.showImages {
note = replaceKittyImageMarkers(note)
}
note = strings.TrimSpace(note)
// Decode any Kitty text sizing markers (OSC 66) that were protected during glamour processing
note = ansi.DecodeKittyTextSizeMarkers(note)
// Handle search highlighting
if o.taskview == BY_FIND {
note = strings.ReplaceAll(note, "qx", "\x1b[48;5;31m")
note = strings.ReplaceAll(note, "qy", "\x1b[0m")
}
note = WordWrap(note, maxCols-PREVIEW_RIGHT_PADDING, 0)
return strings.Split(note, "\n")
}
// resultHandler processes render results and updates the display
func (rm *RenderManager) resultHandler() {
defer rm.wg.Done()
for {
select {
case <-rm.stopCh:
return
case result, ok := <-rm.resultCh:
if !ok {
return
}
// Check if result is still relevant
rm.mutex.RLock()
current := rm.currentRequest
rm.mutex.RUnlock()
if current == nil || current.RequestID != result.RequestID {
// User navigated away, discard result
continue
}
// Check organizer is still on same note
o := rm.organizer
if len(o.rows) == 0 || o.rows[o.fr].id != result.NoteID {
// User navigated away, discard
continue
}
// Apply the full render result
if result.Success && result.RenderedLines != nil {
// Erase the right screen before displaying the new content
o.Screen.eraseRightScreen()
o.note = result.RenderedLines
// Clear the loading message
o.ShowMessage(BR, "")
// Trigger redraw via notification
rm.app.addNotification("_REDRAW_PREVIEW_")
}
}
}
}