pinterest-dl 2.3.0 → 2.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,738 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'uri'
4
+ require_relative '../progress_bar'
5
+
6
+ module PinterestDL
7
+ module TUI
8
+ class Renderer
9
+ MIN_RENDER_WIDTH = 40
10
+ MIN_RENDER_HEIGHT = 12
11
+ CARD_TITLE_CHARS = 7
12
+
13
+ attr_reader :hit_regions, :kitty_overlays, :ueberzug_placements
14
+
15
+ def initialize(theme:, icons:, preview:, clock: -> { Time.now })
16
+ @theme = theme
17
+ @icons = icons
18
+ @preview = preview
19
+ @clock = clock
20
+ @hit_regions = []
21
+ @kitty_overlays = []
22
+ @ueberzug_placements = []
23
+ end
24
+
25
+ def render(state, queue_items:, width:, height:, active_speed: 0.0)
26
+ w = [width.to_i, 20].max
27
+ h = [height.to_i, 8].max
28
+ @hit_regions = []
29
+ @kitty_overlays = []
30
+ @ueberzug_placements = []
31
+
32
+ return render_too_small(w, h) if w < MIN_RENDER_WIDTH || h < MIN_RENDER_HEIGHT
33
+
34
+ lines = []
35
+ lines << render_header(state, w, active_speed)
36
+ lines.concat(render_search_row(state, w, start_y: lines.size + 1))
37
+ lines << render_category_row(state, w, row_y: lines.size + 1)
38
+
39
+ queue_h = compute_queue_height(h)
40
+ footer_h = 1
41
+ body_y = lines.size + 1
42
+ body_h = [h - lines.size - queue_h - footer_h, 6].max
43
+
44
+ right_w = compute_right_width(w)
45
+ left_w = [w - right_w - 1, 16].max
46
+ state.grid_columns = compute_grid_columns(left_w)
47
+
48
+ gallery_rows = render_gallery(state, left_w, body_h, start_y: body_y)
49
+ preview_rows = render_preview_panel(state, right_w, body_h, start_x: left_w + 2, start_y: body_y)
50
+
51
+ body_h.times do |idx|
52
+ lines << "#{gallery_rows[idx]} #{preview_rows[idx]}"
53
+ end
54
+
55
+ queue_y = lines.size + 1
56
+ lines.concat(render_download_queue(state, queue_items, w, queue_h, start_y: queue_y))
57
+ lines << render_footer(state, w)
58
+
59
+ lines = overlay_help_modal(lines, w, h) if state.mode == :help
60
+ lines << '' while lines.size < h
61
+ lines.first(h).map { |line| @theme.apply_canvas_bg(@theme.fit(line, w)) }.join("\n")
62
+ end
63
+
64
+ def region_at(col, row)
65
+ @hit_regions.reverse_each do |reg|
66
+ return reg if col >= reg[:x1] && col <= reg[:x2] && row >= reg[:y1] && row <= reg[:y2]
67
+ end
68
+ nil
69
+ end
70
+
71
+ private
72
+
73
+ def compute_queue_height(height)
74
+ return 6 if height >= 28
75
+ return 5 if height >= 20
76
+
77
+ 3
78
+ end
79
+
80
+ def compute_right_width(width)
81
+ return [[(width * 0.42).to_i, 20].max, width - 17].min if width < 72
82
+
83
+ [[(width * 0.36).to_i, 28].max, [46, width - 24].min].min
84
+ end
85
+
86
+ def register_region(x1:, y1:, x2:, y2:, action:, value: nil)
87
+ @hit_regions << { x1: x1, y1: y1, x2: x2, y2: y2, action: action, value: value }
88
+ end
89
+
90
+ def render_too_small(width, height)
91
+ msg = "Resize terminal (min #{MIN_RENDER_WIDTH}x#{MIN_RENDER_HEIGHT})"
92
+ mid = height / 2
93
+ Array.new(height) do |idx|
94
+ line = if idx == mid
95
+ txt = @theme.truncate(msg, [width - 2, 1].max)
96
+ pad = [(width - @theme.visible_length(txt)) / 2, 0].max
97
+ (' ' * pad) + @theme.paint(txt, color: :pink, bold: true)
98
+ else
99
+ ''
100
+ end
101
+ @theme.apply_canvas_bg(@theme.fit(line, width))
102
+ end.join("\n")
103
+ end
104
+
105
+ def compute_grid_columns(gallery_width)
106
+ return 4 if gallery_width >= 82
107
+ return 3 if gallery_width >= 58
108
+ return 2 if gallery_width >= 34
109
+
110
+ 1
111
+ end
112
+
113
+ def render_header(state, width, active_speed)
114
+ title = @theme.paint('Pinterest-DL', color: :pink, bold: true)
115
+ sep = @theme.paint('│', color: :border_dim)
116
+ left = if width >= 72
117
+ subtitle = @theme.paint('Browse • Preview • Download', color: :purple)
118
+ " #{title} #{sep} #{subtitle}"
119
+ else
120
+ " #{title}"
121
+ end
122
+
123
+ net = @icons.wifi(state.network_status)
124
+ speed_txt = "#{ProgressBar.format_bytes(active_speed)}/s"
125
+ bars = "#{@icons.signal_bars(active: active_speed.positive?)} #{@theme.paint(speed_txt, color: :white)}"
126
+ clock_txt = @theme.paint(@clock.call.strftime('%H:%M'), color: :soft_text)
127
+ right = if width >= 56
128
+ "#{net} #{sep} #{bars} #{sep} #{clock_txt} "
129
+ else
130
+ "#{net} #{sep} #{clock_txt} "
131
+ end
132
+
133
+ gap = [width - @theme.visible_length(left) - @theme.visible_length(right), 1].max
134
+ @theme.fit("#{left}#{' ' * gap}#{right}", width)
135
+ end
136
+
137
+ def render_search_row(state, width, start_y:)
138
+ compact = width < 64
139
+ btn_w = compact ? 8 : 10
140
+ lim_w = compact ? 8 : 13
141
+ box_w = [width - btn_w - lim_w - 2, 12].max
142
+ editing = %i[search add_url set_limit].include?(state.mode)
143
+ bc = editing ? :pink : :border_dim
144
+ b = @theme.border(selected: false)
145
+
146
+ lim_x = box_w + 2
147
+ btn_x = lim_x + lim_w + 1
148
+ register_region(x1: 1, y1: start_y, x2: box_w, y2: start_y + 2, action: :search_box)
149
+ register_region(x1: lim_x, y1: start_y, x2: lim_x + lim_w - 1, y2: start_y + 2, action: :limit_box)
150
+ register_region(x1: btn_x, y1: start_y, x2: width, y2: start_y + 2, action: :search_submit)
151
+
152
+ inner_w = box_w - 2
153
+ prompt_text = search_box_content(state, inner_w)
154
+
155
+ lim_inner = lim_w - 2
156
+ lim_label = compact ? "L:#{state.search_limit}" : "Limit: #{state.search_limit}"
157
+ lim_pad = [(lim_inner - lim_label.length) / 2, 0].max
158
+ lim_bc = state.mode == :set_limit ? :pink : :border_dim
159
+ lim_text = (' ' * lim_pad) + @theme.paint(lim_label, color: :soft_text, bold: state.mode == :set_limit)
160
+
161
+ btn_inner = btn_w - 2
162
+ btn_label = case state.mode
163
+ when :add_url then 'Add'
164
+ when :set_limit then 'OK'
165
+ else compact ? 'Go' : 'Search'
166
+ end
167
+ btn_pad = [(btn_inner - btn_label.length) / 2, 0].max
168
+ btn_bc = editing ? :pink : :purple
169
+ btn_text = (' ' * btn_pad) + @theme.paint(btn_label, color: :white, bold: true)
170
+
171
+ top = "#{@theme.paint("#{b[:tl]}#{b[:h] * inner_w}#{b[:tr]}", color: bc)} " \
172
+ "#{@theme.paint("#{b[:tl]}#{b[:h] * lim_inner}#{b[:tr]}", color: lim_bc)} " \
173
+ "#{@theme.paint("#{b[:tl]}#{b[:h] * btn_inner}#{b[:tr]}", color: btn_bc)}"
174
+ mid = "#{@theme.paint(b[:v], color: bc)}#{@theme.fit(prompt_text, inner_w)}#{@theme.paint(b[:v], color: bc)} " \
175
+ "#{@theme.paint(b[:v], color: lim_bc)}#{@theme.fit(lim_text, lim_inner)}#{@theme.paint(b[:v], color: lim_bc)} " \
176
+ "#{@theme.paint(b[:v], color: btn_bc)}#{@theme.fit(btn_text, btn_inner)}#{@theme.paint(b[:v], color: btn_bc)}"
177
+ bot = "#{@theme.paint("#{b[:bl]}#{b[:h] * inner_w}#{b[:br]}", color: bc)} " \
178
+ "#{@theme.paint("#{b[:bl]}#{b[:h] * lim_inner}#{b[:br]}", color: lim_bc)} " \
179
+ "#{@theme.paint("#{b[:bl]}#{b[:h] * btn_inner}#{b[:br]}", color: btn_bc)}"
180
+
181
+ [top, mid, bot]
182
+ end
183
+
184
+ def search_box_content(state, max_w)
185
+ case state.mode
186
+ when :search
187
+ val = @theme.truncate(state.input_buffer, [max_w - 6, 4].max)
188
+ " #{@icons.search} #{@theme.paint("#{val}_", color: :white, bold: true)}"
189
+ when :add_url
190
+ val = @theme.truncate(state.input_buffer, [max_w - 8, 4].max)
191
+ " #{@theme.paint('URL:', color: :pink, bold: true)} #{@theme.paint("#{val}_", color: :white)}"
192
+ when :set_limit
193
+ val = @theme.truncate(state.input_buffer, [max_w - 16, 4].max)
194
+ " #{@theme.paint('Limit:', color: :pink, bold: true)} #{@theme.paint("#{val}_", color: :white, bold: true)}"
195
+ else
196
+ if state.search_query.empty?
197
+ hint_txt = @theme.truncate('Press / to search (L for limit, A for URL)...', [max_w - 5, 4].max)
198
+ " #{@icons.search} #{@theme.paint(hint_txt, color: :dim_text)}"
199
+ else
200
+ " #{@icons.search} #{@theme.paint(@theme.truncate(state.search_query, [max_w - 5, 4].max), color: :white)}"
201
+ end
202
+ end
203
+ end
204
+
205
+ def render_category_row(state, width, row_y:)
206
+ out = +' '
207
+ cursor_x = 2
208
+ State::CATEGORIES.each_with_index do |cat, idx|
209
+ label = " #{cat[:label]} "
210
+ vis_w = @theme.visible_length(label)
211
+ break if cursor_x + vis_w > width
212
+
213
+ styled = if idx == state.category_index
214
+ @theme.paint(label, color: :white, background: :pink, bold: true)
215
+ else
216
+ @theme.paint(label, color: :soft_text, background: :bg_pill)
217
+ end
218
+ register_region(x1: cursor_x, y1: row_y, x2: cursor_x + vis_w - 1, y2: row_y, action: :category, value: idx)
219
+ out << styled << ' '
220
+ cursor_x += vis_w + 1
221
+ end
222
+ @theme.fit(out, width)
223
+ end
224
+
225
+ def render_gallery(state, width, height, start_y:)
226
+ return render_empty_gallery(state, width, height) if state.pins.empty?
227
+
228
+ cols = [state.grid_columns, 1].max
229
+ gutter = 1
230
+ card_w = [(width - ((cols - 1) * gutter)) / cols, 12].max
231
+ visible_rows = height >= 14 ? 2 : 1
232
+ card_h = [height / visible_rows, 5].max
233
+
234
+ selected_row = state.selected_index / cols
235
+ start_row = [selected_row - visible_rows + 1, 0].max
236
+
237
+ lines = []
238
+ visible_rows.times do |r_off|
239
+ row_idx = start_row + r_off
240
+ card_top_y = start_y + (r_off * card_h)
241
+ cards = Array.new(cols) do |col_idx|
242
+ pin_idx = (row_idx * cols) + col_idx
243
+ card_left_x = 1 + (col_idx * (card_w + gutter))
244
+ if pin_idx < state.pins.size
245
+ pin = state.pins[pin_idx]
246
+ register_card_regions(pin_idx, card_left_x, card_top_y, card_w, card_h)
247
+ render_card(
248
+ pin, card_w, card_h,
249
+ selected: pin_idx == state.selected_index,
250
+ marked: state.pin_selected?(pin),
251
+ slot_id: "card_#{r_off}_#{col_idx}",
252
+ screen_x: card_left_x + 1,
253
+ screen_y: card_top_y + 1
254
+ )
255
+ else
256
+ Array.new(card_h, ' ' * card_w)
257
+ end
258
+ end
259
+
260
+ card_h.times do |l_idx|
261
+ row_line = cards.map { |c| c[l_idx] }.join(' ' * gutter)
262
+ lines << @theme.fit(row_line, width)
263
+ end
264
+ end
265
+
266
+ lines << @theme.fit('', width) while lines.size < height
267
+ lines.first(height)
268
+ end
269
+
270
+ def register_card_regions(pin_idx, x1, y1, card_w, card_h)
271
+ register_region(x1: x1, y1: y1, x2: x1 + card_w - 1, y2: y1 + card_h - 1, action: :card, value: pin_idx)
272
+ cb_x1 = [x1 + card_w - 5, x1].max
273
+ register_region(x1: cb_x1, y1: y1, x2: x1 + card_w - 1, y2: y1, action: :card_select, value: pin_idx)
274
+ end
275
+
276
+ def render_empty_gallery(state, width, height)
277
+ msg = if state.loading
278
+ "Searching Pinterest (limit #{state.search_limit})..."
279
+ elsif state.error_banner
280
+ state.error_banner
281
+ elsif !state.search_query.empty?
282
+ "No #{state.active_category[:label].downcase} pins found"
283
+ else
284
+ 'Press [/] to search Pinterest, [L] for limit, [A] for URL'
285
+ end
286
+ color = if state.error_banner
287
+ :red
288
+ elsif state.loading
289
+ :yellow
290
+ else
291
+ :soft_text
292
+ end
293
+ b = @theme.border(selected: false)
294
+ inner_w = [width - 2, 4].max
295
+ inner_h = [height - 2, 1].max
296
+ mid = inner_h / 2
297
+
298
+ rows = Array.new(inner_h) do |idx|
299
+ if idx == mid
300
+ txt = @theme.truncate(msg, [inner_w - 2, 4].max)
301
+ pad = [(inner_w - @theme.visible_length(txt)) / 2, 0].max
302
+ (' ' * pad) + @theme.paint(txt, color: color, bold: true)
303
+ else
304
+ ''
305
+ end
306
+ end
307
+ wrap_box(rows, width: width, height: height, border: b, border_color: :border_muted)
308
+ end
309
+
310
+ def render_card(pin, width, height, selected:, marked:, slot_id:, screen_x:, screen_y:)
311
+ b = @theme.border(selected: selected)
312
+ bc = if marked
313
+ :green
314
+ elsif selected
315
+ :pink
316
+ else
317
+ :border_dim
318
+ end
319
+ inner_w = [width - 2, 6].max
320
+ is_video = !pin[:video_url].to_s.empty?
321
+ art_h = [height - 3, 2].max
322
+ art = @preview.render_pin(pin, width: inner_w, height: art_h, large: false)
323
+ maybe_add_overlays(pin, id: slot_id, x: screen_x, y: screen_y, width: inner_w, height: art_h, large: false)
324
+
325
+ glyph = is_video ? @icons.video : @icons.image
326
+ raw_title = pin_display_title(pin)
327
+ short_title = @theme.truncate_chars(raw_title, CARD_TITLE_CHARS)
328
+ cap_txt = @theme.truncate(short_title, [inner_w - 4, 4].max)
329
+ cap_line = " #{glyph} #{@theme.paint(cap_txt, color: selected ? :white : :soft_text, bold: selected)}"
330
+
331
+ top = render_card_top_border(b, bc, inner_w, marked: marked)
332
+ bot = @theme.paint("#{b[:bl]}#{b[:h] * inner_w}#{b[:br]}", color: bc)
333
+ body = (art + [cap_line]).first(height - 2)
334
+ mid_row = body.size / 2
335
+
336
+ middle = body.each_with_index.map do |row, idx|
337
+ left_edge = if selected && idx == mid_row
338
+ @theme.paint('▸', color: :white, bold: true)
339
+ else
340
+ @theme.paint(b[:v], color: bc)
341
+ end
342
+ "#{left_edge}#{@theme.fit(row, inner_w)}#{@theme.paint(b[:v], color: bc)}"
343
+ end
344
+
345
+ [top] + middle + [bot]
346
+ end
347
+
348
+ def maybe_add_overlays(pin, id:, x:, y:, width:, height:, large:)
349
+ if @preview.respond_to?(:overlay_for)
350
+ ov = @preview.overlay_for(pin, x: x, y: y, width: width, height: height, large: large)
351
+ @kitty_overlays << ov if ov
352
+ end
353
+ return unless @preview.respond_to?(:ueberzug_placement_for)
354
+
355
+ pl = @preview.ueberzug_placement_for(pin, id: id, x: x, y: y, width: width, height: height, large: large)
356
+ @ueberzug_placements << pl if pl
357
+ end
358
+
359
+ def render_card_top_border(border, color, inner_w, marked:)
360
+ badge = marked ? "[#{@icons.check}]" : @theme.paint('[ ]', color: :border_muted)
361
+ badge_w = 3
362
+ rem = [inner_w - badge_w - 1, 0].max
363
+ left_part = @theme.paint("#{border[:tl]}#{border[:h] * rem}", color: color)
364
+ right_part = @theme.paint("#{border[:h]}#{border[:tr]}", color: color)
365
+ "#{left_part}#{badge}#{right_part}"
366
+ end
367
+
368
+ def render_preview_panel(state, width, height, start_x:, start_y:)
369
+ b = @theme.border(selected: false)
370
+ inner_w = [width - 2, 10].max
371
+ inner_h = [height - 2, 4].max
372
+ pin = state.selected_pin
373
+
374
+ counter_line = render_preview_counter(state, inner_w, start_x: start_x + 1, row_y: start_y + 1)
375
+
376
+ compact_meta = inner_h < 13
377
+ btn_h = inner_h >= 10 ? 3 : 1
378
+ meta_placeholder = render_preview_metadata(
379
+ pin, state, inner_w,
380
+ start_x: start_x + 1, start_y: start_y + 2, register: false, compact: compact_meta
381
+ )
382
+ meta_h = meta_placeholder.size
383
+ art_h = [inner_h - 1 - meta_h - btn_h, 2].max
384
+ art_lines = @preview.render_pin(pin, width: inner_w, height: art_h, large: true)
385
+ maybe_add_overlays(pin, id: 'preview_main', x: start_x + 1, y: start_y + 2, width: inner_w, height: art_h, large: true)
386
+
387
+ meta_y = start_y + 2 + art_lines.size
388
+ meta_lines = render_preview_metadata(
389
+ pin, state, inner_w,
390
+ start_x: start_x + 1, start_y: meta_y, register: true, compact: compact_meta
391
+ )
392
+ btn_y = meta_y + meta_lines.size
393
+ btn_lines = render_download_button(pin, inner_w, start_x: start_x + 1, start_y: btn_y, compact: btn_h == 1)
394
+
395
+ content = [counter_line] + art_lines + meta_lines + btn_lines
396
+ wrap_box(content.first(inner_h), width: width, height: height, border: b, border_color: :purple)
397
+ end
398
+
399
+ def render_preview_counter(state, inner_w, start_x:, row_y:)
400
+ counter = if state.pins.empty?
401
+ '◂ 0 / 0 ▸'
402
+ else
403
+ "◂ #{state.selected_index + 1} / #{state.pins.size} ▸"
404
+ end
405
+ vis_w = @theme.visible_length(counter)
406
+ header_pad = [inner_w - vis_w - 1, 0].max
407
+ c_x = start_x + header_pad
408
+ register_region(x1: c_x, y1: row_y, x2: c_x + 2, y2: row_y, action: :preview_prev)
409
+ register_region(x1: c_x + vis_w - 3, y1: row_y, x2: c_x + vis_w, y2: row_y, action: :preview_next)
410
+
411
+ "#{' ' * header_pad}#{@theme.paint(counter, color: :soft_text, bold: true)}"
412
+ end
413
+
414
+ def render_preview_metadata(pin, state, width, start_x:, start_y:, register:, compact: false)
415
+ unless pin
416
+ empty_count = compact ? 2 : 6
417
+ return [@theme.paint(' No pin selected', color: :dim_text)] + Array.new(empty_count, '')
418
+ end
419
+
420
+ is_video = !pin[:video_url].to_s.empty?
421
+ title = pin_display_title(pin)
422
+ raw_desc = @theme.sanitize_display(pin[:description].to_s)
423
+ desc = if raw_desc.empty? || raw_desc.casecmp?(title) || raw_desc.casecmp?('pin')
424
+ pin[:id].to_s.empty? ? 'Pinterest media' : "ID: #{pin[:id]}"
425
+ else
426
+ raw_desc
427
+ end
428
+ creator = @theme.sanitize_display(pin[:creator].to_s)
429
+ creator = 'pinterest' if creator.empty?
430
+ qual = is_video ? state.video_quality : state.image_quality
431
+ fmt = is_video ? 'Video • MP4' : "Image • #{extract_format(pin[:image_url])}"
432
+ size_txt = format_pin_dimensions(pin)
433
+
434
+ rows = [" #{@theme.paint(@theme.truncate(title, width - 2), color: :white, bold: true)}"]
435
+ unless compact
436
+ rows << " #{@theme.paint(@theme.truncate(desc, width - 2), color: :soft_text)}"
437
+ rows << @theme.paint(" #{'─' * [width - 2, 2].max}", color: :border_muted)
438
+ end
439
+
440
+ qual_row_y = start_y + rows.size
441
+ qual_selector = "#{@theme.paint('◂', color: :pink, bold: true)} " \
442
+ "#{@theme.paint(qual.to_s, color: :white, background: :bg_pill, bold: true)} " \
443
+ "#{@theme.paint('▸', color: :pink, bold: true)}"
444
+ if register
445
+ qx = start_x + 12
446
+ register_region(x1: qx - 1, y1: qual_row_y, x2: qx + 2, y2: qual_row_y, action: :quality_prev)
447
+ register_region(x1: qx + 3, y1: qual_row_y, x2: start_x + width - 1, y2: qual_row_y, action: :quality_next)
448
+ end
449
+ rows << " #{@icons.quality_glyph} #{@theme.paint('Quality:', color: :soft_text)} #{qual_selector}"
450
+ return rows if compact
451
+
452
+ rows << " #{@icons.size_glyph} #{@theme.paint('Size: ', color: :soft_text)} #{@theme.paint(size_txt, color: :purple, bold: true)}"
453
+ rows << " #{@icons.format_glyph} #{@theme.paint('Format: ', color: :soft_text)} #{@theme.paint(fmt, color: :purple, bold: true)}"
454
+ handle = "@#{@theme.truncate(creator, [width - 14, 6].max)}"
455
+ rows << " #{@icons.creator_glyph} #{@theme.paint('Creator:', color: :soft_text)} #{@theme.paint(handle, color: :purple)}"
456
+ rows
457
+ end
458
+
459
+ def format_pin_dimensions(pin)
460
+ meta = @preview.respond_to?(:metadata_for) ? @preview.metadata_for(pin) : nil
461
+ if meta && meta[:width] && meta[:height]
462
+ size_str = meta[:bytes] ? " (#{ProgressBar.format_bytes(meta[:bytes])})" : ''
463
+ "#{meta[:width]}x#{meta[:height]}#{size_str}"
464
+ elsif meta && meta[:bytes]
465
+ ProgressBar.format_bytes(meta[:bytes])
466
+ else
467
+ 'Auto'
468
+ end
469
+ end
470
+
471
+ def render_download_button(pin, width, start_x:, start_y:, compact: false)
472
+ is_video = pin && !pin[:video_url].to_s.empty?
473
+ label = is_video ? '↓ Download Video' : '↓ Download Image'
474
+ if compact
475
+ register_region(x1: start_x, y1: start_y, x2: start_x + width - 1, y2: start_y, action: :download_current)
476
+ pad_l = [(width - @theme.visible_length(label)) / 2, 0].max
477
+ return [(' ' * pad_l) + @theme.paint(@theme.truncate(label, width), color: :white, background: :purple, bold: true)]
478
+ end
479
+
480
+ b = @theme.border(selected: false)
481
+ bw = [width - 2, 8].max
482
+ register_region(x1: start_x, y1: start_y, x2: start_x + width - 1, y2: start_y + 2, action: :download_current)
483
+
484
+ pad_l = [(bw - @theme.visible_length(label)) / 2, 0].max
485
+ text = (' ' * pad_l) + @theme.paint(@theme.truncate(label, bw), color: :white, bold: true)
486
+ [
487
+ @theme.paint("#{b[:tl]}#{b[:h] * bw}#{b[:tr]}", color: :purple),
488
+ "#{@theme.paint(b[:v], color: :purple)}#{@theme.fit(text, bw)}#{@theme.paint(b[:v], color: :purple)}",
489
+ @theme.paint("#{b[:bl]}#{b[:h] * bw}#{b[:br]}", color: :purple)
490
+ ]
491
+ end
492
+
493
+ def render_download_queue(state, queue_items, width, height, start_y:)
494
+ b = @theme.border(selected: false)
495
+ inner_w = [width - 2, 16].max
496
+ title_text = " #{@icons.download} #{@theme.paint("Download Queue (#{queue_items.size})", color: :pink, bold: true)} "
497
+ batch_btn = render_batch_badge(state)
498
+ title_vis = @theme.visible_length(title_text)
499
+ batch_vis = @theme.visible_length(batch_btn)
500
+
501
+ if batch_vis.positive? && title_vis + batch_vis + 2 <= inner_w
502
+ rem = inner_w - title_vis - batch_vis - 1
503
+ bx1 = 2 + title_vis + rem
504
+ register_region(x1: bx1, y1: start_y, x2: bx1 + batch_vis - 1, y2: start_y, action: :download_batch)
505
+ top = "#{@theme.paint(b[:tl], color: :purple)}#{title_text}" \
506
+ "#{@theme.paint(b[:h] * rem, color: :purple)}#{batch_btn}" \
507
+ "#{@theme.paint("#{b[:h]}#{b[:tr]}", color: :purple)}"
508
+ else
509
+ rem = [inner_w - title_vis, 0].max
510
+ top = "#{@theme.paint(b[:tl], color: :purple)}#{title_text}#{@theme.paint("#{b[:h] * rem}#{b[:tr]}", color: :purple)}"
511
+ end
512
+ bot = @theme.paint("#{b[:bl]}#{b[:h] * inner_w}#{b[:br]}", color: :purple)
513
+
514
+ body_h = [height - 2, 1].max
515
+ body_rows = if queue_items.empty?
516
+ render_empty_queue_rows(state, inner_w)
517
+ elsif body_h == 1 || width < 68
518
+ render_compact_queue_row(state, queue_items, inner_w, start_y: start_y + 1)
519
+ else
520
+ render_queue_split_rows(state, queue_items, inner_w, body_h, start_y: start_y + 1)
521
+ end
522
+
523
+ middle = Array.new(body_h) do |idx|
524
+ "#{@theme.paint(b[:v], color: :purple)}#{@theme.fit(body_rows[idx].to_s, inner_w)}#{@theme.paint(b[:v], color: :purple)}"
525
+ end
526
+ [top] + middle + [bot]
527
+ end
528
+
529
+ def render_compact_queue_row(state, queue_items, width, start_y:)
530
+ sel_idx = [[state.queue_selected_index, queue_items.size - 1].min, 0].max
531
+ item = queue_items[sel_idx]
532
+ bar_w = [[width / 3, 14].min, 6].max
533
+ bar = @theme.gradient_bar(item.progress_ratio, width: bar_w)
534
+ pct = format('%<p>3d%%', p: item.percent)
535
+ name = @theme.truncate(item.filename, [width - bar_w - 10, 6].max)
536
+ register_region(x1: 2, y1: start_y, x2: width + 1, y2: start_y, action: :queue_select, value: sel_idx)
537
+ [@theme.fit(" #{@theme.paint(name, color: :white, bold: true)} #{bar} #{@theme.paint(pct, color: :pink)}", width)]
538
+ end
539
+
540
+ def render_batch_badge(state)
541
+ count = state.selected_batch_count
542
+ return '' unless count.positive?
543
+
544
+ @theme.paint(" ↓ Download Selected (#{count}) ", color: :white, background: :pink, bold: true)
545
+ end
546
+
547
+ def render_empty_queue_rows(state, width)
548
+ hint1 = if state.selected_batch_count.positive?
549
+ "#{state.selected_batch_count} pins marked — press [B] or click Download Selected."
550
+ else
551
+ 'Queue empty — press [D] to download, [Space] to mark, [L] to change limit.'
552
+ end
553
+ [
554
+ @theme.fit(" #{@theme.paint(hint1, color: :dim_text)}", width),
555
+ @theme.fit(" #{@theme.paint('[Space] Mark [S] All [B] Batch [L] Limit [V] Quality', color: :border_dim)}", width),
556
+ @theme.fit('', width)
557
+ ]
558
+ end
559
+
560
+ def render_queue_split_rows(state, queue_items, width, body_h, start_y:)
561
+ sel_idx = [[state.queue_selected_index, queue_items.size - 1].min, 0].max
562
+ selected_item = queue_items[sel_idx]
563
+
564
+ list_w = [[(width * 0.34).to_i, 20].max, 36].min
565
+ detail_w = [width - list_w - 3, 22].max
566
+ sep = @theme.paint('│', color: :border_muted)
567
+
568
+ start_idx = [sel_idx - body_h + 1, 0].max
569
+ list_rows = Array.new(body_h) do |r|
570
+ idx = start_idx + r
571
+ item = queue_items[idx]
572
+ if item
573
+ register_region(x1: 2, y1: start_y + r, x2: 1 + list_w, y2: start_y + r, action: :queue_select, value: idx)
574
+ render_queue_list_row(item, list_w, selected: idx == sel_idx)
575
+ else
576
+ @theme.fit('', list_w)
577
+ end
578
+ end
579
+
580
+ detail_x = 2 + list_w + 3
581
+ detail_rows = render_queue_detail_rows(selected_item, detail_w, start_x: detail_x, start_y: start_y)
582
+
583
+ Array.new(body_h) do |idx|
584
+ "#{@theme.fit(list_rows[idx], list_w)} #{sep} #{@theme.fit(detail_rows[idx].to_s, detail_w)}"
585
+ end
586
+ end
587
+
588
+ def render_queue_list_row(item, width, selected:)
589
+ glyph = case item.status
590
+ when :completed then @icons.check
591
+ when :downloading then @icons.download
592
+ when :paused then @icons.pause
593
+ when :failed then @icons.trash
594
+ else @theme.paint('•', color: :dim_text)
595
+ end
596
+ pct = format('%<p>3d%%', p: item.percent)
597
+ name_max = [width - 9, 6].max
598
+ name = @theme.truncate(item.filename, name_max)
599
+ prefix = selected ? @theme.paint('▸', color: :pink, bold: true) : ' '
600
+ text_color = selected ? :white : :soft_text
601
+ row = "#{prefix}#{glyph} #{@theme.paint(name, color: text_color, bold: selected)}"
602
+ pad = [width - @theme.visible_length(row) - pct.length - 1, 1].max
603
+ @theme.fit("#{row}#{' ' * pad}#{@theme.paint(pct, color: selected ? :pink : :dim_text)}", width)
604
+ end
605
+
606
+ def render_queue_detail_rows(item, width, start_x:, start_y:)
607
+ btn_w = 12
608
+ stats_w = [[(width * 0.34).to_i, 18].max, 28].min
609
+ left_w = [width - stats_w - btn_w - 2, 14].max
610
+
611
+ btn_x = start_x + left_w + 1 + stats_w + 1
612
+ register_region(x1: btn_x, y1: start_y, x2: btn_x + 4, y2: start_y + 2, action: :queue_pause)
613
+ register_region(x1: btn_x + 6, y1: start_y, x2: btn_x + 10, y2: start_y + 2, action: :queue_remove)
614
+
615
+ bar_w = [left_w - 8, 6].max
616
+ bar = @theme.gradient_bar(item.progress_ratio, width: bar_w)
617
+ pct = @theme.paint(format('%<p>3d%%', p: item.percent), color: :white, bold: true)
618
+
619
+ status_detail = if item.status == :failed
620
+ @theme.paint(@theme.truncate("Error: #{item.error_message}", left_w - 1), color: :red)
621
+ else
622
+ @theme.paint("Status: #{item.status.to_s.upcase} (#{item.quality})", color: :soft_text)
623
+ end
624
+
625
+ l_rows = [
626
+ @theme.paint(@theme.truncate(item.filename, left_w - 1), color: :white, bold: true),
627
+ "#{bar} #{pct}",
628
+ status_detail
629
+ ]
630
+
631
+ rec_str = ProgressBar.format_bytes(item.bytes_received)
632
+ tot_str = item.total_bytes&.positive? ? ProgressBar.format_bytes(item.total_bytes) : '---'
633
+ spd_str = "#{ProgressBar.format_bytes(item.speed)}/s"
634
+ eta_str = item.status == :downloading ? ProgressBar.format_eta(item.eta) : '--:--'
635
+
636
+ s_rows = [
637
+ "#{@theme.paint('Speed:', color: :soft_text)} #{@theme.paint(spd_str, color: :white)}",
638
+ "#{@theme.paint('Size:', color: :soft_text)} #{@theme.paint("#{rec_str}/#{tot_str}", color: :white)}",
639
+ "#{@theme.paint('ETA:', color: :soft_text)} #{@theme.paint(eta_str, color: :white)}"
640
+ ]
641
+
642
+ pause_icon = item.status == :paused ? @icons.resume : @icons.pause
643
+ b_rows = [
644
+ "#{@theme.paint('╭───╮', color: :purple)} #{@theme.paint('╭───╮', color: :red)}",
645
+ "#{@theme.paint('│', color: :purple)} #{pause_icon} #{@theme.paint('│', color: :purple)} " \
646
+ "#{@theme.paint('│', color: :red)} #{@icons.trash} #{@theme.paint('│', color: :red)}",
647
+ "#{@theme.paint('╰───╯', color: :purple)} #{@theme.paint('╰───╯', color: :red)}"
648
+ ]
649
+
650
+ Array.new(3) do |idx|
651
+ "#{@theme.fit(l_rows[idx], left_w)} #{@theme.fit(s_rows[idx], stats_w)} #{@theme.fit(b_rows[idx], btn_w)}"
652
+ end
653
+ end
654
+
655
+ def render_footer(state, width)
656
+ if state.error_banner
657
+ return @theme.fit(" #{@theme.paint("Error: #{state.error_banner}", color: :red, bold: true)}", width)
658
+ end
659
+ if state.status_message
660
+ return @theme.fit(" #{@theme.paint(state.status_message, color: :cyan)}", width)
661
+ end
662
+
663
+ hints = [
664
+ hint('[↑↓←→/Click]', 'Nav'),
665
+ hint('[Space]', 'Mark'),
666
+ hint('[B]', 'Batch'),
667
+ hint('[L]', 'Limit'),
668
+ hint('[V]', 'Qual'),
669
+ hint('[/]', 'Search'),
670
+ hint('[D]', 'DL'),
671
+ hint('[Q]', 'Quit')
672
+ ].join(' ')
673
+ @theme.fit(" #{hints}", width)
674
+ end
675
+
676
+ def hint(key, label)
677
+ "#{@theme.paint(key, color: :soft_text, bold: true)} #{@theme.paint(label, color: :dim_text)}"
678
+ end
679
+
680
+ def wrap_box(content_lines, width:, height:, border:, border_color:)
681
+ inner_w = [width - 2, 2].max
682
+ inner_h = [height - 2, 1].max
683
+ top = @theme.paint("#{border[:tl]}#{border[:h] * inner_w}#{border[:tr]}", color: border_color)
684
+ bot = @theme.paint("#{border[:bl]}#{border[:h] * inner_w}#{border[:br]}", color: border_color)
685
+ rows = Array.new(inner_h) do |idx|
686
+ "#{@theme.paint(border[:v], color: border_color)}#{@theme.fit(content_lines[idx].to_s, inner_w)}" \
687
+ "#{@theme.paint(border[:v], color: border_color)}"
688
+ end
689
+ [top] + rows + [bot]
690
+ end
691
+
692
+ def pin_display_title(pin)
693
+ raw = @theme.sanitize_display(pin[:title].to_s)
694
+ raw = @theme.sanitize_display(pin[:description].to_s) if raw.empty?
695
+ raw.empty? ? "Pin #{pin[:id]}" : raw
696
+ end
697
+
698
+ def extract_format(url)
699
+ ext = File.extname(URI.parse(url.to_s).path.to_s).delete('.').upcase
700
+ ext.empty? ? 'JPG' : ext
701
+ rescue URI::InvalidURIError
702
+ 'JPG'
703
+ end
704
+
705
+ def overlay_help_modal(lines, width, height)
706
+ modal_w = [60, width - 4].min
707
+ help_rows = [
708
+ @theme.paint(' Pinterest-DL Shortcuts & Mouse Controls', color: :pink, bold: true),
709
+ '',
710
+ ' / or Click Search Search Pinterest pins',
711
+ ' L or Click Limit Set search result limit (default 25, max 200)',
712
+ ' A Add a Pinterest Pin or Board URL',
713
+ ' 1 - 8 / Tab / Click Switch category (All, Images, Videos, ...)',
714
+ ' Arrows / Wheel Navigate thumbnail gallery',
715
+ ' Space / Right-Click Toggle pin for batch download',
716
+ ' S / Ctrl-A Select or deselect all visible pins',
717
+ ' B / Click Batch Download all selected (or visible) pins',
718
+ ' V / Click ◂ Qual ▸ Select download quality in right panel',
719
+ ' D / Enter Download current pin into queue list',
720
+ ' P / R / Del Pause / Resume / Remove queue item',
721
+ ' ? / Esc / Q Toggle help / Close / Quit'
722
+ ]
723
+ modal = wrap_box(help_rows, width: modal_w, height: help_rows.size + 2, border: @theme.border(selected: false), border_color: :pink)
724
+ top_row = [(height - modal.size) / 2, 1].max
725
+ left_col = [(width - modal_w) / 2, 1].max
726
+
727
+ result = lines.dup
728
+ modal.each_with_index do |m_line, offset|
729
+ target = top_row + offset
730
+ next if target >= result.size
731
+
732
+ result[target] = "#{' ' * left_col}#{m_line}"
733
+ end
734
+ result
735
+ end
736
+ end
737
+ end
738
+ end