Class: Heathrow::Application

Inherits:
Object
  • Object
show all
Includes:
UI::ThreadedView, Rcurses, Rcurses::Cursor, Rcurses::Input
Defined in:
lib/heathrow/ui/application.rb

Constant Summary collapse

COLOR_THEMES =
{
  'Default' => { unread: 226, read: 249, accent: 10, thread: 255, dm: 201, tag: 14, star: 226,
                 quote1: 114, quote2: 180, quote3: 139, quote4: 109, sig: 242,
                 top_bg: 235, bottom_bg: 235, cmd_bg: 17,
                 source_email: 39, source_maildir: 39, source_whatsapp: 40,
                 source_discord: 99, source_reddit: 202, source_rss: 226,
                 source_telegram: 51, source_slack: 35, source_web: 208,
                 source_messenger: 33, source_instagram: 205, source_weechat: 75,
                 source_default: 15 },
  'Mutt'    => { unread: 226, read: 249, accent: 14, thread: 252, dm: 213, tag: 81,
                 quote1: 114, quote2: 180, quote3: 139, quote4: 109, sig: 243 },
  'Ocean'   => { unread: 51,  read: 249, accent: 45, thread: 45,  dm: 171, tag: 87,
                 quote1: 75, quote2: 117, quote3: 153, quote4: 189, sig: 242 },
  'Forest'  => { unread: 77,  read: 249, accent: 10, thread: 78,  dm: 176, tag: 48,
                 quote1: 114, quote2: 150, quote3: 186, quote4: 222, sig: 242 },
  'Amber'   => { unread: 220, read: 249, accent: 226, thread: 214, dm: 209, tag: 214,
                 quote1: 222, quote2: 186, quote3: 180, quote4: 174, sig: 242 },
}
CHAT_SOURCE_TYPES =
%w[weechat messenger instagram whatsapp discord telegram slack workspace].freeze

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from UI::ThreadedView

#apply_thread_mode_key, #create_section_header, #current_message_for_navigation, #cycle_view_mode, #filtered_messages_size, #finalize_line, #format_channel_header, #format_channel_message, #format_dm_header, #format_dm_message, #format_section_header, #format_thread_header, #format_thread_message, #format_thread_reply, #format_time, #get_source_icon, #initialize_threading, #move_section, #organize_current_messages, #render_channel_messages, #render_message_list_threaded, #render_thread_messages, #reset_threading, #restore_view_thread_mode, #save_section_order, #save_view_thread_mode, #section_date_range, #thread_mode_key, #thread_mode_label, #toggle_collapse, #toggle_folder_view, #toggle_thread_view

Constructor Details

#initializeApplication



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
# File 'lib/heathrow/ui/application.rb', line 58

def initialize
  # Ensure LS_COLORS is loaded (may be missing if not launched from rsh)
  if !ENV['LS_COLORS'] || ENV['LS_COLORS'].empty?
    lscolors_file = File.expand_path('~/.local/share/lscolors.sh')
    if File.exist?(lscolors_file)
      content = File.read(lscolors_file)
      ENV['LS_COLORS'] = $1 if content =~ /LS_COLORS='([^']+)'/
    end
  end

  # Initialize core components FIRST
  @db = Database.new
  @config = Config.new
  @source_manager = SourceManager.new(@db)
  @running = false
  @current_view = 'A' # Start with All messages
  initialize_threading  # Initialize threading support
  @view_names = {
    'A' => 'All Messages',
    'N' => 'New Messages',
    's' => 'Sources',
    'S' => 'Starred'
  }
  
  # UI state - RC settings override YAML config, with defaults
  @width = @config.get('ui.width', @config.rc('pane_width', 3))
  @border = @config.rc('border_style', 1)
  @sort_order = @config.rc('sort_order', 'latest')
  @sort_inverted = false
  @feedback_message = nil
  @feedback_expires_at = nil
  @date_format = @config.rc('date_format', '%b %e')
  @confirm_purge = @config.rc('confirm_purge', false) == true
  @color_theme = @config.rc('color_theme', 'Default')
  @default_view = @config.get('ui.default_view', 'A')
  @editor_args = @config.get('ui.editor_args', "-c 'set nospell' -c 'startinsert!'")
  @default_email = @config.get('default_email', @config.rc('default_email', ''))
  @smtp_command = @config.get('smtp_command', @config.rc('smtp_command', ''))

  # Message list state
  @messages = []
  @filtered_messages = []
  @index = 0
  @min_index = 0
  @source_colors = {}  # Cache for source colors
  @max_index = 0

  # Browsed message tracking for session-based read status
  @browsed_message_ids = Set.new  # Messages viewed this session
  @tagged_messages = Set.new  # Tagged messages for batch operations
  
  # View definitions
  @views = {}
  load_views
  
  # Colors (from theme, with defaults)
  @topcolor = theme[:top_bg] || 235
  @bottomcolor = theme[:bottom_bg] || 235
  @cmdcolor = theme[:cmd_bg] || 17
  
  # Load source colors
  load_source_colors

  # Load address book
  require_relative '../address_book'
  @address_book = AddressBook.new
end

Instance Attribute Details

#configObject (readonly)

Returns the value of attribute config.



56
57
58
# File 'lib/heathrow/ui/application.rb', line 56

def config
  @config
end

#dbObject (readonly)

Returns the value of attribute db.



56
57
58
# File 'lib/heathrow/ui/application.rb', line 56

def db
  @db
end

#panesObject (readonly)

Returns the value of attribute panes.



56
57
58
# File 'lib/heathrow/ui/application.rb', line 56

def panes
  @panes
end

Instance Method Details

#add_new_sourceObject



918
919
920
921
922
923
924
925
926
927
928
929
930
# File 'lib/heathrow/ui/application.rb', line 918

def add_new_source
  require_relative 'source_wizard'
  wizard = SourceWizard.new(@source_manager, @panes[:bottom], @panes[:right])
  source_id = wizard.run_wizard
  
  if source_id
    # Refresh the sources view
    show_sources
  else
    # Restore sources view
    render_sources_info
  end
end

#add_sender_to_address_bookObject



7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
# File 'lib/heathrow/ui/application.rb', line 7307

def add_sender_to_address_book
  msg = current_message
  return set_feedback("No message selected", 196, 2) unless msg

  sender = msg['sender'].to_s.strip
  sender_name = msg['sender_name'].to_s.strip
  return set_feedback("No sender", 196, 2) if sender.empty?

  # Build full address: "Name <email>" or just "email"
  full = if sender_name.empty? || sender_name == sender
           sender
         else
           "#{sender_name} <#{sender}>"
         end

  # Suggest alias from name or email local part
  suggested = if !sender_name.empty? && sender_name != sender
                sender_name.split.first.downcase
              else
                sender.split('@').first.downcase
              end

  @panes[:bottom].text = " Add: #{full}".fg(156)
  @panes[:bottom].refresh
  alias_name = @panes[:bottom].ask(" Alias: ", suggested)
  return set_feedback("Cancelled", 245, 1) if alias_name.nil? || alias_name.strip.empty?
  alias_name = alias_name.strip.gsub(/\s+/, '.')

  ab_path = File.expand_path('~/setup/addressbook')
  File.open(ab_path, 'a') { |f| f.puts "alias #{alias_name} #{full}" }
  @address_book = AddressBook.new(ab_path)
  set_feedback("Added: #{alias_name} → #{full}", 156, 3)
rescue => e
  set_feedback("Failed: #{e.message}", 196, 2)
end

#add_source_itemObject

Add an item (feed/channel) to the selected source



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
# File 'lib/heathrow/ui/application.rb', line 951

def add_source_item
  return unless @filtered_messages[@index]
  source_id = @filtered_messages[@index]['id']
  source = @db.get_source_by_id(source_id)
  return unless source

  config = source['config']
  config = JSON.parse(config) if config.is_a?(String)
  source_type = source['plugin_type'] || source['type']

  case source_type
  when 'rss'
    url = bottom_ask("Feed URL: ", "")
    return if url.nil? || url.strip.empty?
    title = bottom_ask("Title (optional): ", "")
    return if title.nil?

    feed = { 'url' => url.strip }
    feed['title'] = title.strip unless title.strip.empty?
    config['feeds'] ||= []
    config['feeds'] << feed
    @db.execute("UPDATE sources SET config = ? WHERE id = ?", [config.to_json, source_id])
    set_feedback("Added feed: #{feed['title'] || feed['url']}", 156, 3)
  when 'web'
    url = bottom_ask("Page URL: ", "")
    return if url.nil? || url.strip.empty?
    title = bottom_ask("Title (optional): ", "")
    return if title.nil?

    page = { 'url' => url.strip }
    page['title'] = title.strip unless title.strip.empty?
    config['pages'] ||= []
    config['pages'] << page
    @db.execute("UPDATE sources SET config = ? WHERE id = ?", [config.to_json, source_id])
    set_feedback("Added page: #{page['title'] || page['url']}", 156, 3)
  end

  show_sources
end

#add_source_item_for(source) ⇒ Object

Add item to a known source (called from non-Sources views)



1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
# File 'lib/heathrow/ui/application.rb', line 1093

def add_source_item_for(source)
  config = source['config']
  config = JSON.parse(config) if config.is_a?(String)
  stype = source['plugin_type'] || source['type']

  case stype
  when 'rss'
    url = bottom_ask("Feed URL: ", "")
    return if url.nil? || url.strip.empty?
    title = bottom_ask("Title (optional): ", "")
    return if title.nil?

    feed = { 'url' => url.strip }
    feed['title'] = title.strip unless title.strip.empty?
    config['feeds'] ||= []
    config['feeds'] << feed
    @db.execute("UPDATE sources SET config = ? WHERE id = ?", [config.to_json, source['id']])
    set_feedback("Added feed: #{feed['title'] || feed['url']}", 156, 3)
  when 'web'
    url = bottom_ask("Page URL: ", "")
    return if url.nil? || url.strip.empty?
    title = bottom_ask("Title (optional): ", "")
    return if title.nil?

    page = { 'url' => url.strip }
    page['title'] = title.strip unless title.strip.empty?
    config['pages'] ||= []
    config['pages'] << page
    @db.execute("UPDATE sources SET config = ? WHERE id = ?", [config.to_json, source['id']])
    set_feedback("Added page: #{page['title'] || page['url']}", 156, 3)
  end
end

#address_book_menuObject

Address book: add sender or edit file



7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
# File 'lib/heathrow/ui/application.rb', line 7293

def address_book_menu
  @panes[:bottom].text = " @: a=Add sender to address book, e=Edit address book".fg(245)
  @panes[:bottom].refresh
  chr = getchr
  case chr
  when 'a'
    add_sender_to_address_book
  when 'e'
    edit_address_book
  else
    set_feedback("Cancelled", 245, 1)
  end
end

#advance_indexObject

Advance index to next item (no wrap, no re-render)



2303
2304
2305
2306
# File 'lib/heathrow/ui/application.rb', line 2303

def advance_index
  message_size = message_count
  @index = [@index + 1, message_size - 1].min if message_size > 0
end

#ai_assistantObject

AI Assistant (I key) ==========

Interactive Claude Code integration for message-related AI tasks. Uses claude -p CLI for one-shot queries with full CLAUDE.md context.



4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
# File 'lib/heathrow/ui/application.rb', line 4688

def ai_assistant
  msg = current_message
  return unless msg && !msg['is_header'] && !msg['is_channel_header'] && !msg['is_thread_header']
  msg = ensure_full_message(msg)

  # Build message context
  context = ai_message_context(msg)

  # Show menu
  set_feedback("AI: d=Draft reply  f=Fix grammar  s=Summarize  t=Translate  a=Ask...", 226, 10)
  chr = getchr(10)
  if chr.nil? || chr == 'ESC' || chr == "\e"
    @feedback_expires_at = nil
    render_bottom_bar
    return
  end

  case chr
  when 'd'
    ai_draft_reply(msg, context)
  when 'f'
    ai_fix_grammar(msg, context)
  when 's'
    ai_summarize(msg, context)
  when 't'
    ai_translate(msg, context)
  when 'a'
    ai_freeform(msg, context)
  else
    @feedback_expires_at = nil
    render_bottom_bar
  end
end

#ai_call(prompt) ⇒ Object



4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
# File 'lib/heathrow/ui/application.rb', line 4736

def ai_call(prompt)
  require 'open3'
  @panes[:bottom].text = " AI thinking... (this may take a moment)".fg(226)
  @panes[:bottom].refresh

  env = ENV.to_h.reject { |k, _| k == 'CLAUDECODE' }

  # Log prompt for debugging
  File.open('/tmp/heathrow_ai.log', 'a') do |f|
    f.puts "=== AI CALL #{Time.now} ==="
    f.puts "Prompt length: #{prompt.length}"
  end

  result = nil
  stderr_out = nil
  status = nil
  begin
    result, stderr_out, status = Open3.capture3(env, 'claude', '-p',
      '--max-turns', '1', stdin_data: prompt)
  rescue => e
    File.open('/tmp/heathrow_ai.log', 'a') { |f| f.puts "Exception: #{e.message}" }
    set_feedback("AI error: #{e.message}", 196, 3)
    return nil
  end

  File.open('/tmp/heathrow_ai.log', 'a') do |f|
    f.puts "Exit status: #{status.exitstatus}"
    f.puts "Result length: #{result&.length}"
    f.puts "Stderr: #{stderr_out}" if stderr_out && !stderr_out.empty?
    f.puts "Result preview: #{result&.slice(0, 200)}"
  end

  render_bottom_bar

  unless status.success?
    set_feedback("AI error (exit #{status.exitstatus})", 196, 3)
    return nil
  end

  if result.nil? || result.strip.empty?
    set_feedback("AI returned empty response", 226, 3)
    return nil
  end

  result
end

#ai_draft_reply(msg, context) ⇒ Object



4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
# File 'lib/heathrow/ui/application.rb', line 4794

def ai_draft_reply(msg, context)
  identity = current_identity
  from_info = identity ? "I am: #{identity[:from]}" : ""
  prompt = "    You are drafting an email reply. Write only the reply body text, no headers.\n    Match the tone and language of the original message.\n    Keep it concise and natural. \#{from_info}\n\n    Original message:\n    \#{context}\n\n    Draft a reply:\n  PROMPT\n\n  response = ai_call(prompt)\n  return unless response\n\n  ai_show_response(\"DRAFT REPLY (press 'r' to open in editor)\", response)\n\n  # Wait for user action\n  @panes[:bottom].text = \" r=Open in editor with draft | y=Copy to clipboard | ESC=Dismiss\".fg(245)\n  @panes[:bottom].refresh\n  chr = getchr\n  case chr\n  when 'r'\n    # Start a reply with the draft pre-filled\n    ai_reply_with_draft(msg, response.strip)\n  when 'y'\n    IO.popen('xclip -selection clipboard', 'w') { |io| io.write(response.strip) } rescue nil\n    IO.popen('xclip -selection primary', 'w') { |io| io.write(response.strip) } rescue nil\n    set_feedback(\"Draft copied to clipboard\", 156, 2)\n  end\n  @panes[:right].content_update = true\n  render_all\nend\n"

#ai_fix_grammar(msg, context) ⇒ Object



4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
# File 'lib/heathrow/ui/application.rb', line 4887

def ai_fix_grammar(msg, context)
  prompt = "    Fix grammar and spelling in the following message content.\n    Return ONLY the corrected text, preserving the original language and tone.\n    If the text is already correct, return it unchanged.\n    Do not add explanations.\n\n    \#{msg['content']}\n  PROMPT\n\n  response = ai_call(prompt)\n  return unless response\n\n  # Show diff-like view\n  lines = []\n  lines << \"GRAMMAR/SPELLING FIX\".bd.fg(226)\n  lines << \"\"\n  lines << \"Original:\".fg(245)\n  lines << msg['content'].to_s\n  lines << \"\"\n  lines << \"Corrected:\".fg(156)\n  lines << response.strip\n  @panes[:right].ix = 0\n  @panes[:right].text = lines.join(\"\\n\")\n  @panes[:right].refresh\n  @panes[:right].content_update = false\n\n  @panes[:bottom].text = \" y=Copy corrected text | ESC=Dismiss\".fg(245)\n  @panes[:bottom].refresh\n  chr = getchr\n  if chr == 'y'\n    IO.popen('xclip -selection clipboard', 'w') { |io| io.write(response.strip) } rescue nil\n    IO.popen('xclip -selection primary', 'w') { |io| io.write(response.strip) } rescue nil\n    set_feedback(\"Corrected text copied to clipboard\", 156, 2)\n  end\n  @panes[:right].content_update = true\n  render_all\nend\n"

#ai_freeform(msg, context) ⇒ Object



4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
# File 'lib/heathrow/ui/application.rb', line 4955

def ai_freeform(msg, context)
  question = bottom_ask("Ask about this message: ")
  return if question.nil? || question.strip.empty?

  prompt = "    The user is reading a message in their email/messaging client and has a question.\n\n    Message context:\n    \#{context}\n\n    User's question: \#{question}\n  PROMPT\n\n  response = ai_call(prompt)\n  return unless response\n  ai_show_response(\"AI RESPONSE\", response)\nend\n"

#ai_message_context(msg) ⇒ Object



4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
# File 'lib/heathrow/ui/application.rb', line 4722

def ai_message_context(msg)
  lines = []
  lines << "Source: #{msg['source_type']}"
  lines << "From: #{msg['sender_name'] || msg['sender']}"
  lines << "To: #{msg['recipient'] || msg['recipients']}"
  lines << "Subject: #{msg['subject']}" if msg['subject']
  lines << "Date: #{msg['timestamp']}"
  folder = msg['folder']
  lines << "Folder: #{folder}" if folder
  lines << ""
  lines << msg['content'].to_s
  lines.join("\n")
end

#ai_reply_with_draft(msg, draft) ⇒ Object



4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
# File 'lib/heathrow/ui/application.rb', line 4830

def ai_reply_with_draft(msg, draft)
  source_id = msg['source_id']
  source = @source_manager.sources[source_id]
  return unless source

  stype = source['plugin_type'] || source['type']
  return unless stype == 'maildir' || stype == 'imap' || stype == 'gmail'

  require_relative '../message_composer'
  identity = current_identity
  composer = MessageComposer.new(msg, identity: identity, address_book: @address_book, editor_args: @editor_args)

  # Build the reply template, then inject the draft
  template = composer.send(:build_reply_template, false)
  # Insert draft after the blank line following headers
  lines = template.lines
  header_end = nil
  lines.each_with_index do |line, i|
    if line.strip.empty? && header_end.nil?
      header_end = i
      break
    end
  end

  if header_end
    # Replace the empty body area with draft
    before = lines[0..header_end].map(&:chomp)
    # Find the attribution line and quoted text
    after_lines = lines[(header_end + 1)..]
    after = after_lines ? after_lines.map(&:chomp) : []
    new_template = (before + ["", draft, ""] + after).join("\n")
  else
    new_template = template
  end

  # Write to temp file and open editor
  tempfile = Tempfile.new(['heathrow-ai-draft', '.eml'])
  begin
    tempfile.write(new_template)
    tempfile.flush

    cursor_line = (header_end || 0) + 2
    run_editor(tempfile.path, cursor_line: cursor_line)

    tempfile.rewind
    content = tempfile.read
    return if content.rstrip == new_template.rstrip

    composed = composer.send(:parse_composed_message, content)
    finalize_compose(source, composed) if composed
  ensure
    tempfile.close
    tempfile.unlink
  end
  render_bottom_bar
end

#ai_show_response(title, response) ⇒ Object



4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
# File 'lib/heathrow/ui/application.rb', line 4783

def ai_show_response(title, response)
  lines = []
  lines << title.bd.fg(226)
  lines << ""
  lines << response
  @panes[:right].ix = 0
  @panes[:right].text = lines.join("\n")
  @panes[:right].refresh
  @panes[:right].content_update = false
end

#ai_summarize(msg, context) ⇒ Object



4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
# File 'lib/heathrow/ui/application.rb', line 4926

def ai_summarize(msg, context)
  prompt = "    Summarize this message concisely in bullet points.\n    Keep the same language as the original.\n\n    \#{context}\n  PROMPT\n\n  response = ai_call(prompt)\n  return unless response\n  ai_show_response(\"SUMMARY\", response)\nend\n"

#ai_translate(msg, context) ⇒ Object



4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
# File 'lib/heathrow/ui/application.rb', line 4939

def ai_translate(msg, context)
  lang = bottom_ask("Translate to language: ", "English")
  return if lang.nil? || lang.strip.empty?

  prompt = "    Translate the following message to \#{lang.strip}.\n    Return only the translated text, no explanations.\n\n    \#{msg['content']}\n  PROMPT\n\n  response = ai_call(prompt)\n  return unless response\n  ai_show_response(\"TRANSLATION (\#{lang.strip})\", response)\nend\n"

#all_themesObject



199
200
201
# File 'lib/heathrow/ui/application.rb', line 199

def all_themes
  COLOR_THEMES.merge(@config.custom_themes)
end

#apply_view_filters(view) ⇒ Object



2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
# File 'lib/heathrow/ui/application.rb', line 2616

def apply_view_filters(view)
  filters = view[:filters] || {}

  # Check for special filter types
  if filters['special'] == 'uncategorized'
    # Get all messages first
    all_messages = @db.get_messages({}, 1000, 0, light: true)

    # Get messages from all other configured views
    categorized_ids = Set.new

    @views.each do |view_key, other_view|
      next if view_key == @current_view  # Skip self
      if other_view && other_view[:filters] && !other_view[:filters].empty? && other_view[:filters]['special'] != 'uncategorized'
        # Convert filters for database
        symbolized_filters = {}
        other_view[:filters].each do |key, value|
          symbolized_filters[key.to_sym] = value
        end

        view_messages = @db.get_messages(symbolized_filters, 1000, 0, light: true)
        view_messages.each { |msg| categorized_ids.add(msg['id']) }
      end
    end

    # Filter to only uncategorized messages
    @filtered_messages = all_messages.reject { |msg| categorized_ids.include?(msg['id']) }
  else
    db_filters = build_db_filters(view)

    # Legacy simple filters (no rules array)
    if !filters['rules'].is_a?(Array)
      filters.each do |key, value|
        next if key == 'rules'
        db_filters[key.to_sym] = value
      end
    end

    @filtered_messages = @db.get_messages(db_filters, 1000, 0, light: true)

    # For source_id-filtered views (e.g., RSS): ensure all feeds/channels are represented
    if db_filters[:source_id] && @show_threaded
      ensure_all_feeds_loaded(db_filters[:source_id].to_i)
    end
  end
end

#apply_view_filters_with_limit(view, limit) ⇒ Object



2459
2460
2461
2462
# File 'lib/heathrow/ui/application.rb', line 2459

def apply_view_filters_with_limit(view, limit)
  db_filters = build_db_filters(view)
  @filtered_messages = @db.get_messages(db_filters, limit, 0, light: true)
end

#auto_mark_as_read(msg) ⇒ Object

Auto-mark message as read (called when message is displayed)



274
275
276
# File 'lib/heathrow/ui/application.rb', line 274

def auto_mark_as_read(msg)
  mark_message_read(msg)
end

#bg_sync(folder: nil, &requery_block) ⇒ Object

Sync DB with Maildir filesystem (like mutt's live sync) folder: sync only one folder, or nil for full sync Run sync in background thread, re-render when done The block (if given) should return new filtered_messages, or nil to re-use apply_view_filters



8617
8618
8619
8620
8621
8622
8623
8624
8625
8626
8627
8628
8629
8630
8631
8632
8633
8634
8635
8636
# File 'lib/heathrow/ui/application.rb', line 8617

def bg_sync(folder: nil, &requery_block)
  # Kill any previous sync thread
  @bg_sync_thread&.kill if @bg_sync_thread&.alive?

  view_at_start = @current_view
  db_path = @db.instance_variable_get(:@db_path)
  @bg_sync_thread = Thread.new do
    begin
      # Use a separate DB connection so we don't block the main thread
      bg_db = Heathrow::Database.new(db_path)
      sync_maildir(folder: folder, db: bg_db)
      sync_weechat(db: bg_db) unless folder
      bg_db.close
      @bg_sync_ready = view_at_start  # Signal: sync done for this view
    rescue => e
      File.open('/tmp/heathrow_debug.log', 'a') { |f| f.puts "bg_sync error: #{e.message}\n#{e.backtrace.first(3).join("\n")}" }
    end
  end
  @bg_requery_block = requery_block
end

#bottom_ask(prompt, default = '') ⇒ Object

Ask user for input via bottom pane, then restore the status line



139
140
141
142
143
144
145
146
# File 'lib/heathrow/ui/application.rb', line 139

def bottom_ask(prompt, default = '')
  @editing = true
  result = @panes[:bottom].ask(prompt, default)
  @editing = false
  render_top_bar
  render_bottom_bar
  result
end

#build_db_filters(view) ⇒ Object



2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
# File 'lib/heathrow/ui/application.rb', line 2435

def build_db_filters(view)
  filters = view[:filters] || {}
  db_filters = {}
  if filters['rules'].is_a?(Array)
    filters['rules'].each do |rule|
      field = rule['field']
      value = rule['value']
      case rule['op']
      when '='  then db_filters[field.to_sym] = value
      when 'like'
        case field
        when 'search'  then db_filters[:search] = value
        when 'sender'  then db_filters[:sender_pattern] = value
        when 'subject' then db_filters[:subject_pattern] = value
        when 'folder'  then db_filters[:maildir_folder] = value
        when 'label'   then db_filters[:label] = value
        when 'source'  then db_filters[:source_name] = value
        end
      end
    end
  end
  db_filters
end

#build_folder_tree(folder_names) ⇒ Object

Build a tree structure from dot-separated folder names



3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
# File 'lib/heathrow/ui/application.rb', line 3798

def build_folder_tree(folder_names)
  tree = {}
  folder_names.each do |name|
    parts = name.split('.')
    node = tree
    parts.each do |part|
      node[part] ||= {}
      node = node[part]
    end
  end
  tree
end

#cached_image(url) ⇒ Object

Download image to cache, return local path



8240
8241
8242
8243
8244
8245
8246
8247
8248
8249
8250
8251
8252
8253
8254
8255
8256
8257
8258
8259
8260
8261
# File 'lib/heathrow/ui/application.rb', line 8240

def cached_image(url)
  cache_dir = File.join(Dir.home, '.heathrow', 'image_cache')
  FileUtils.mkdir_p(cache_dir)

  # Use URL hash as filename
  ext = File.extname(URI.parse(url).path)[0..4] rescue '.img'
  ext = '.jpg' if ext.empty?
  cache_path = File.join(cache_dir, Digest::MD5.hexdigest(url) + ext)

  return cache_path if File.exist?(cache_path) && File.size(cache_path) > 100

  # Download with timeout
  require 'open-uri'
  Timeout.timeout(5) do
    URI.open(url, 'rb', 'User-Agent' => 'Heathrow/1.0') do |remote|
      File.binwrite(cache_path, remote.read)
    end
  end
  cache_path
rescue => e
  nil
end

#change_widthObject

UI controls



6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
# File 'lib/heathrow/ui/application.rb', line 6403

def change_width
  @width = (@width % 6) + 1  # Cycle through 1-6 (10%-60%)
  
  # Save to config
  @config.set('ui.width', @width)
  @config.save
  
  # Update pane dimensions without recreating them
  left_width = (@w - 4) * @width / 10
  
  # Update left pane width
  @panes[:left].w = left_width

  # Update right pane position and width
  @panes[:right].x = @panes[:left].w + 4
  @panes[:right].w = @w - @panes[:left].w - 4

  # Clear entire screen to remove old border residues, then re-render
  Rcurses.clear_screen
  render_all
  
  # Show width setting in bottom bar temporarily
  width_percent = @width * 10
  @panes[:bottom].text = " Width: #{@width} (Left: #{width_percent}%, Right: #{100-width_percent}%)".fg(245)
  @panes[:bottom].refresh
end

#chat_reply_context(msg, source_type) ⇒ Object



5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
# File 'lib/heathrow/ui/application.rb', line 5238

def chat_reply_context(msg, source_type)
  meta = msg['metadata']
  meta = JSON.parse(meta) if meta.is_a?(String)
  meta = {} unless meta.is_a?(Hash)
  sender = msg['sender_name'] || msg['sender']

  # Extract target and display name based on source type
  case source_type
  when 'weechat'
    target = meta['buffer']
    display = meta['channel_name'] || meta['buffer_short'] || msg['subject']
  when 'messenger', 'instagram'
    target = meta['thread_id'] || meta['conversation_id'] || msg['thread_id']
    display = meta['conversation_name'] || msg['subject'] || sender
  when 'whatsapp'
    target = meta['chat_jid'] || msg['recipient']
    display = meta['chat_name'] || msg['subject'] || sender
  when 'discord'
    target = meta['channel_id'] || msg['recipient']
    display = meta['channel_name'] || msg['subject'] || sender
  when 'telegram'
    target = meta['chat_id'] || msg['recipient']
    display = meta['chat_name'] || msg['subject'] || sender
  when 'slack'
    target = meta['channel_id'] || msg['recipient']
    display = meta['channel_name'] || msg['subject'] || sender
  when 'workspace'
    target = meta['channel_id'] || msg['recipient']
    display = meta['channel_name'] || msg['subject'] || sender
  end

  { target: target, display: display, sender: sender }
end

#chat_reply_editor(msg, source, source_type) ⇒ Object



5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
# File 'lib/heathrow/ui/application.rb', line 5286

def chat_reply_editor(msg, source, source_type)
  ctx = chat_reply_context(msg, source_type)
  tempfile = Tempfile.new(['heathrow-chat', '.txt'])
  begin
    tempfile.write("# Reply to #{ctx[:sender]} in #{ctx[:display]}\n# Lines starting with # are ignored\n\n")
    tempfile.flush
    if run_editor(tempfile.path, cursor_line: 3, insert_mode: true)
      tempfile.rewind
      body = tempfile.read.lines.reject { |l| l.start_with?('#') }.join.strip
      if !body.empty?
        composed = { to: ctx[:target], subject: nil, body: body, original_message: msg }
        send_composed_message(source, composed)
      else
        set_feedback("Reply cancelled", 245, 1)
      end
    end
  ensure
    tempfile.close
    tempfile.unlink
  end
end

#chat_reply_inline(msg, source, source_type) ⇒ Object



5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
# File 'lib/heathrow/ui/application.rb', line 5272

def chat_reply_inline(msg, source, source_type)
  ctx = chat_reply_context(msg, source_type)
  reply = bottom_ask("Reply to #{ctx[:sender]} in #{ctx[:display]}: ", '')
  if reply && !reply.strip.empty?
    saved_index = @index
    composed = { to: ctx[:target], subject: nil, body: reply.strip, original_message: msg }
    send_composed_message(source, composed)
    @index = saved_index
    @pending_view_refresh = false  # Don't let background sync jump us
  else
    set_feedback("Reply cancelled", 245, 1)
  end
end

#check_bg_syncObject

Called from render_all — check if background sync finished



8639
8640
8641
8642
8643
8644
8645
8646
8647
8648
8649
8650
8651
8652
8653
8654
8655
8656
8657
8658
8659
8660
8661
8662
8663
8664
8665
# File 'lib/heathrow/ui/application.rb', line 8639

def check_bg_sync
  return unless @bg_sync_ready && @bg_sync_ready == @current_view
  @bg_sync_ready = nil

  old_ids = @filtered_messages.map { |m| m['id'] }

  if @bg_requery_block
    result = @bg_requery_block.call
    if result.is_a?(Array)
      @filtered_messages = result
      sort_messages
    end
    # If block returned nil (e.g. apply_view_filters sets @filtered_messages directly)
    sort_messages
  end
  @bg_requery_block = nil

  new_ids = @filtered_messages.map { |m| m['id'] }

  # Only re-render if data actually changed
  if old_ids != new_ids
    @index = 0 if @index >= @filtered_messages.size
    true  # Signal: needs re-render
  else
    false
  end
end

#check_load_moreObject



2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
# File 'lib/heathrow/ui/application.rb', line 2327

def check_load_more
  return unless @load_limit && @filtered_messages
  return if @filtered_messages.size < @load_limit  # Haven't hit the limit yet
  display_size = message_count
  return if display_size == 0
  return unless @index >= display_size - 10
  return if @last_autoload_index == @index
  @last_autoload_index = @index
  load_more_messages
end

#check_mailto_triggerObject

Check for mailto trigger file (written by wezterm or external scripts)



5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
# File 'lib/heathrow/ui/application.rb', line 5491

def check_mailto_trigger
  mailto_file = File.join(HEATHROW_HOME, 'mailto')
  return unless File.exist?(mailto_file)
  addr = File.read(mailto_file).strip
  File.delete(mailto_file)
  return if addr.empty?

  # Find the first mail source
  mail_source = @source_manager.sources.values.find do |s|
    s['enabled'] && %w[maildir gmail imap].include?(s['plugin_type'] || s['type'])
  end
  return unless mail_source

  compose_new_mail(mail_source, mailto: addr)
end

#check_new_mailObject



7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
# File 'lib/heathrow/ui/application.rb', line 7881

def check_new_mail
  now = Time.now
  @last_sync_check ||= Time.at(0)
  return if (now - @last_sync_check) < 5
  @last_sync_check = now

  @source_last_sync ||= {}

  Thread.new do
    thread_db = Heathrow::Database.new
    changed = false

    # Maildir sync: current folder every 5s (skip if no folder context)
    maildir_interval = 5
    if !@source_last_sync['maildir'] || (now - @source_last_sync['maildir']) >= maildir_interval
      folder = current_view_folder
      if folder
        changed = sync_maildir(folder: folder, db: thread_db)
      end
      @source_last_sync['maildir'] = now
    end

    # Other sources based on their poll_interval
    sources = thread_db.get_sources
    sources.each do |source|
      stype = source['plugin_type']
      next if stype == 'maildir'
      interval = (source['poll_interval'] || 900).to_i
      next if interval <= 0

      key = "#{stype}_#{source['id']}"
      next if @source_last_sync[key] && (now - @source_last_sync[key]) < interval

      src_changed = case stype
      when 'rss'       then sync_rss(db: thread_db)
      when 'web'       then sync_webwatch(db: thread_db)
      when 'messenger' then sync_messenger(db: thread_db)
      when 'instagram' then sync_instagram(db: thread_db)
      when 'weechat'   then sync_weechat(db: thread_db)
      end
      @source_last_sync[key] = now
      changed = true if src_changed
    end

    thread_db.close rescue nil
    @pending_view_refresh = true if changed
  rescue => e
    File.open('/tmp/heathrow_debug.log', 'a') { |f| f.puts "check_new_mail error: #{e.message}" }
  end
rescue => e
  # Silent fail
end

#cleanupObject



8831
8832
8833
8834
8835
# File 'lib/heathrow/ui/application.rb', line 8831

def cleanup
  @db.close if @db
  # Clear screen and restore terminal
  Rcurses.clear_screen rescue nil
end

#clear_inline_imageObject



8346
8347
8348
8349
8350
8351
8352
8353
8354
8355
8356
8357
8358
# File 'lib/heathrow/ui/application.rb', line 8346

def clear_inline_image
  return unless @showing_image && @termpix
  @termpix.clear(
    x: @panes[:right].x,
    y: @panes[:right].y,
    width: @panes[:right].w - 1,
    height: @panes[:right].h - 1,
    term_width: @w,
    term_height: @h)
  @showing_image = false
rescue
  @showing_image = false
end

#collapse_current_itemObject

Message operations



2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
# File 'lib/heathrow/ui/application.rb', line 2664

def collapse_current_item
  return unless @show_threaded && @organizer
  
  msg = current_message
  return unless msg
  
  # Save current position before collapsing
  @saved_positions ||= {}
  
  if msg['is_dm_header']
    dm_key = msg['channel_id']
    if @sort_order == 'conversation'
      return if @dm_collapsed.fetch(dm_key, true)
      @dm_collapsed[dm_key] = true
    else
      return if @dm_section_collapsed
      @dm_section_collapsed = true
    end
  elsif msg['is_channel_header']
    # Already collapsed? Do nothing
    return if @channel_collapsed[msg['channel_id']]

    # Save current position
    @saved_positions[msg['channel_id']] = @index

    # Collapse the channel
    @channel_collapsed[msg['channel_id']] = true
  elsif msg['is_thread_header']
    return if @thread_collapsed[msg['thread_id']]
    @saved_positions[msg['thread_id']] = @index
    @thread_collapsed[msg['thread_id']] = true
  elsif msg['channel_id']
    # Message inside a channel - collapse the parent channel
    return if @channel_collapsed[msg['channel_id']]
    @saved_positions[msg['channel_id']] = @index
    @channel_collapsed[msg['channel_id']] = true
    
    # Move selection to the channel header
    find_and_select_header(msg['channel_id'], 'channel')
  elsif msg['thread_id']
    # Message inside a thread - collapse the parent thread
    return if @thread_collapsed[msg['thread_id']]
    @saved_positions[msg['thread_id']] = @index
    @thread_collapsed[msg['thread_id']] = true
    
    # Move selection to the thread header
    find_and_select_header(msg['thread_id'], 'thread')
  end
  
  # Re-render
  render_message_list_threaded
  render_message_content
end

#colorize_email_content(content) ⇒ Object

Colorize email content with mutt-style quote levels and signature dimming. Detects both ">" prefix quoting and indentation-based quoting (from HTML emails rendered via w3m, where blockquotes become indented text).



8139
8140
8141
8142
8143
8144
8145
8146
8147
8148
8149
8150
8151
8152
8153
8154
8155
8156
8157
8158
8159
8160
8161
8162
8163
8164
8165
8166
8167
8168
8169
8170
8171
8172
8173
8174
8175
8176
8177
8178
8179
8180
8181
8182
8183
# File 'lib/heathrow/ui/application.rb', line 8139

def colorize_email_content(content)
  quote_colors = [theme[:quote1] || 114, theme[:quote2] || 180,
                  theme[:quote3] || 139, theme[:quote4] || 109]
  sig_color = theme[:sig] || 5       # magenta (vim PreProc)
  link_color = theme[:link] || 4     # blue (vim String)
  email_color = theme[:email] || 5   # magenta (vim Special)
  in_signature = false
  indent_quote_level = 0  # tracks nesting from "wrote:" attribution lines

  lines = content.lines
  result = []
  lines.each_with_index do |line, i|
    stripped = line.rstrip
    # Detect signature delimiter (RFC 3676: "-- " on its own line)
    if stripped == '-- ' || stripped == '--'
      in_signature = true
      indent_quote_level = 0
      result << colorize_links(stripped, sig_color, link_color)
    elsif in_signature
      result << colorize_links(stripped, sig_color, link_color)
    elsif stripped =~ /^(>{1,})\s?/
      level = $1.length
      color = quote_colors[[level - 1, quote_colors.length - 1].min]
      result << colorize_links(stripped, color, link_color)
    else
      # Detect attribution lines (start of indented quote block)
      # Matches: "wrote:", "skrev ...:", "schrieb ...:", "a écrit :", or "date ... <email>:"
      if stripped =~ /\b(wrote|skrev|schrieb|geschreven|scrisse|escribi[oó]|a\s+[eé]crit)\b.*:\s*$/ ||
         stripped =~ /\d\d[:\.]\d\d\s.*<[^>]+>:\s*$/
        indent_quote_level += 1
        color = quote_colors[[indent_quote_level - 1, quote_colors.length - 1].min]
        result << colorize_links(stripped, color, link_color)
      elsif indent_quote_level > 0 && stripped =~ /^\s{2,}/
        # Indented line inside a quote block
        color = quote_colors[[indent_quote_level - 1, quote_colors.length - 1].min]
        result << colorize_links(stripped, color, link_color)
      else
        # Non-indented line resets indent quoting
        indent_quote_level = 0 if indent_quote_level > 0 && !stripped.empty?
        result << colorize_links(stripped, nil, link_color)
      end
    end
  end
  result.join("\n")
end


8601
8602
8603
8604
8605
8606
8607
8608
8609
8610
8611
# File 'lib/heathrow/ui/application.rb', line 8601

def colorize_links(line, base_color, link_color)
  url_re = %r{https?://[^\s<>\[\]()]+}
  parts = line.split(url_re, -1)
  urls = line.scan(url_re)
  result = ""
  parts.each_with_index do |part, i|
    result += base_color ? part.fg(base_color) : part
    result += urls[i].ul.fg(link_color) if urls[i]
  end
  result
end

#colorize_markdown(text) ⇒ Object



6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
# File 'lib/heathrow/ui/application.rb', line 6747

def colorize_markdown(text)
  colored = ""
  text.lines.each do |line|
    case line
    when /^(#+)\s+(.+)$/  # Headers
      level = $1.length
      content = $2.chomp
      case level
      when 1
        colored += content.bd.fg(226) + "\n"  # Bright yellow bold for H1
      when 2
        colored += content.bd.fg(14) + "\n"   # Cyan bold for H2
      when 3
        colored += content.bd.fg(10) + "\n"   # Green bold for H3
      else
        colored += content.bd.fg(11) + "\n"   # Yellow bold for H4-H6
      end
    when /^\s*[-*+]\s+(.+)$/  # Bullet points
      indent = line[/^\s*/]
      content = line.sub(/^\s*[-*+]\s+/, '').chomp
      colored += indent + "• ".fg(14) + content + "\n"
    when /^\s*\d+\.\s+(.+)$/  # Numbered lists
      indent = line[/^\s*/]
      number = line[/\d+/]
      content = line.sub(/^\s*\d+\.\s+/, '').chomp
      colored += indent + "#{number}.".fg(14) + " " + content + "\n"
    when /^\s*\|/  # Table rows
      # Color pipe characters and header cells
      colored_line = line.gsub(/\|/, "|".fg(240))
      if line =~ /^\s*\|.*\|.*\|/  # Has multiple columns
        colored += colored_line
      else
        colored += line
      end
    when /^```/  # Code blocks
      colored += line.fg(245)  # Gray for code block markers
    when /^---+$/, /^===+$/  # Horizontal rules
      colored += line.chomp.fg(240) + "\n"
    when /^\s*$/  # Empty lines
      colored += line
    else
      # Process inline markdown
      processed = line.dup
      
      # Bold text **text** or __text__
      processed.gsub!(/\*\*(.+?)\*\*/, '\1'.bd)
      processed.gsub!(/__(.+?)__/, '\1'.bd)
      
      # Italic text *text* or _text_
      processed.gsub!(/\*([^*]+)\*/, '\1'.fg(252))
      processed.gsub!(/_([^_]+)_/, '\1'.fg(252))
      
      # Inline code `code`
      processed.gsub!(/`([^`]+)`/, '\1'.fg(245))
      
      # Links [text](url)
      processed.gsub!(/\[([^\]]+)\]\([^)]+\)/, '\1'.fg(14))
      
      # Key bindings or commands in backticks
      processed.gsub!(/`([A-Z]+)`/, '\1'.fg(10))
      
      colored += processed
    end
  end
  colored
end

#compose_new_mail(source, mailto: nil) ⇒ Object



5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
# File 'lib/heathrow/ui/application.rb', line 5507

def compose_new_mail(source, mailto: nil)
  require_relative '../message_composer'
  identity = current_identity

  # Check for postponed messages (mutt-style recall)
  pcount = @db.postponed_count
  if pcount > 0
    answer = bottom_ask("#{pcount} postponed message(s). Recall? [y/N] ")
    if answer&.strip&.downcase == 'y'
      draft = recall_postponed(source)
      if draft
        composer = MessageComposer.new(nil, identity: identity, address_book: @address_book, editor_args: @editor_args)
        composed = composer.compose_draft(draft)
      end
    end
  end

  unless composed
    composer = MessageComposer.new(nil, identity: identity, address_book: @address_book, editor_args: @editor_args)

    @panes[:bottom].text = " Opening editor for new message...".fg(226)
    @panes[:bottom].refresh

    composed = composer.compose_new(mailto)
  end
  setup_display
  create_panes
  render_all
  if composed
    finalize_compose(source, composed, "Message cancelled")
  else
    set_feedback("Message cancelled", 245, 1)
  end
end

#compose_new_messageObject



5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
# File 'lib/heathrow/ui/application.rb', line 5439

def compose_new_message
  # Build list of sendable channels from all DB sources
  channels = []

  @source_manager.sources.each_value do |s|
    stype = s['plugin_type'] || s['type']
    next unless s['enabled']
    case stype
    when 'maildir'
      channels.unshift({ name: 'Mail', source: s, type: 'mail' })
    when 'gmail', 'imap'
      channels << { name: s['name'] || 'Email', source: s, type: 'mail' }
    when 'weechat'
      config = s['config'].is_a?(String) ? (JSON.parse(s['config']) rescue {}) : (s['config'] || {})
      platform = config['platform'] || 'chat'
      channels << { name: s['name'] || platform.capitalize, source: s, type: 'weechat' }
    end
  end

  # Channel selector: TAB cycles, ENTER confirms, ESC cancels
  idx = 0
  loop do
    ch = channels[idx]
    @panes[:bottom].text = " New message via: #{ch[:name].bd}  (TAB to cycle, ENTER to confirm, ESC to cancel)".fg(226)
    @panes[:bottom].refresh

    key = getchr
    case key
    when "\t", "TAB"
      idx = (idx + 1) % channels.size
    when "ENTER", "\r", "\n"
      break
    when "ESC", "\e"
      set_feedback("Cancelled", 245, 1)
      render_bottom_bar
      return
    end
  end

  selected = channels[idx]

  case selected[:type]
  when 'mail'
    compose_new_mail(selected[:source])
  when 'weechat'
    compose_weechat_message(selected[:source])
  end

  render_bottom_bar
end

#compose_pluginsObject

Compose plugins: loaded from ~/.heathrow/plugins/compose/*.rb Each plugin file should define a hash with :key, :label, :command Example: { key: 'i', label: 'Insight', command: 'cd ~/myapp && ./picker --pick=%pick_file' }



5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
# File 'lib/heathrow/ui/application.rb', line 5712

def compose_plugins
  @_compose_plugins ||= begin
    plugins = []
    dir = File.join(Dir.home, '.heathrow', 'plugins', 'compose')
    if Dir.exist?(dir)
      Dir.glob(File.join(dir, '*.rb')).each do |f|
        begin
          plugin = eval(File.read(f))
          plugins << plugin if plugin.is_a?(Hash) && plugin[:key] && plugin[:command]
        rescue => e
          File.open('/tmp/heathrow_debug.log', 'a') { |log| log.puts "Compose plugin error (#{f}): #{e.message}" }
        end
      end
    end
    plugins
  end
end

#compose_weechat_message(source) ⇒ Object



5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
# File 'lib/heathrow/ui/application.rb', line 5542

def compose_weechat_message(source)
  config = source['config'].is_a?(String) ? (JSON.parse(source['config']) rescue {}) : (source['config'] || {})
  platform = config['platform'] || 'chat'

  prompt = "#{platform.capitalize} target (e.g. #general, username): "
  target = bottom_ask(prompt, '')
  return if target.nil? || target.strip.empty?
  target = target.strip

  # Offer inline or editor
  mode = bottom_ask("(i)nline or (e)ditor? ", 'i')
  return if mode.nil?

  body = if mode.strip.downcase.start_with?('e')
    edit_chat_in_editor(platform, target)
  else
    reply = bottom_ask("Message: ", '')
    reply&.strip
  end
  return if body.nil? || body.empty?

  require_relative '../sources/weechat'
  instance = Heathrow::Sources::Weechat.new(source)
  result = instance.send_message(target, nil, body)

  if result[:success]
    set_feedback(result[:message], 156, 3)
  else
    set_feedback(result[:message], 196, 3)
  end
end

#configure_save_shortcutsObject

── Configure save shortcuts (s=) ── Interactive editor for save folder shortcuts stored in config.yml.



4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
# File 'lib/heathrow/ui/application.rb', line 4552

def configure_save_shortcuts
  shortcuts = save_folder_shortcuts.dup

  loop do
    # Display current shortcuts in right pane
    info = []
    info << "SAVE FOLDER SHORTCUTS".bd.fg(226)
    info << ""
    if shortcuts.empty?
      info << "No shortcuts configured".fg(245)
    else
      shortcuts.sort_by { |k, _| k }.each do |key, folder|
        info << "  s#{key.to_s.ljust(4).fg(10)} → #{folder}".fg(255)
      end
    end
    info << ""
    info << "Commands:".fg(245)
    info << "  a = Add new shortcut".fg(245)
    info << "  d = Delete a shortcut".fg(245)
    info << "  ESC/q = Done".fg(245)
    @panes[:right].text = info.join("\n")
    @panes[:right].refresh

    chr = getchr
    case chr
    when 'a'
      key = bottom_ask("Shortcut key (any key except B/F/=): ")
      next if key.nil? || key.strip.empty?
      key = key.strip
      if %w[B F =].include?(key)
        set_feedback("'#{key}' is reserved", 196, 2)
        next
      end
      folder = bottom_ask("Folder name: ")
      next if folder.nil? || folder.strip.empty?
      shortcuts[key] = folder.strip
    when 'd'
      key = bottom_ask("Delete shortcut key: ")
      next if key.nil? || key.strip.empty?
      shortcuts.delete(key.strip)
    when 'q', 'ESC', "\e", 'h', 'LEFT'
      break
    end
  end

  # Save to config.yml
  @config.settings['save_folders'] = shortcuts
  @config.save
  @save_folders = shortcuts  # Update cached value
  set_feedback("Save shortcuts updated", 156, 2)
  render_all
end

#copy_message_idObject



7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
# File 'lib/heathrow/ui/application.rb', line 7266

def copy_message_id
  msg = current_message
  return unless msg && msg['id']
  id_str = "heathrow:#{msg['id']}"
  IO.popen('xclip -selection clipboard', 'w') { |io| io.write(id_str) } rescue nil
  IO.popen('xclip -selection primary', 'w') { |io| io.write(id_str) } rescue nil
  set_feedback("Message ID #{msg['id']} copied", 156, 2)
rescue => e
  set_feedback("Copy failed: #{e.message}", 196, 2)
end

#copy_right_pane_to_clipboardObject



7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
# File 'lib/heathrow/ui/application.rb', line 7277

def copy_right_pane_to_clipboard
  text = @panes[:right].text
  if text && !text.strip.empty?
    # Strip ANSI codes for clean clipboard content
    clean = text.gsub(/\e\[[0-9;]*m/, '')
    IO.popen('xclip -selection clipboard', 'w') { |io| io.write(clean) } rescue nil
    IO.popen('xclip -selection primary', 'w') { |io| io.write(clean) } rescue nil
    set_feedback("Copied to clipboard", 156, 2)
  else
    set_feedback("Nothing to copy", 196, 2)
  end
rescue => e
  set_feedback("Copy failed: #{e.message}", 196, 2)
end

#create_panesObject



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
# File 'lib/heathrow/ui/application.rb', line 148

def create_panes
  @panes = {}

  # Create main container pane
  @panes[:main] = Pane.new(1, 1, @w, @h, 0, 0)
  
  # Top bar (like RTFM's @pT)
  @panes[:top] = Pane.new(1, 1, @w, 1, 255, @topcolor)
  
  # Left pane for message list (like RTFM's @pL)
  left_width = (@w - 4) * @width / 10
  @panes[:left] = Pane.new(2, 3, left_width, @h - 4)
  
  # Right pane for message content (like RTFM's @pR)
  @panes[:right] = Pane.new(@panes[:left].w + 4, 3, @w - @panes[:left].w - 4, @h - 4)
  
  # Bottom command bar (like RTFM's @pB)
  @panes[:bottom] = Pane.new(1, @h, @w, 1, 252, @bottomcolor)
  @panes[:bottom].emoji = true
  @panes[:bottom].emoji_refresh = -> {
    @panes.each_value { |p| p.full_refresh }
  }
  
  # Command input pane (overlays bottom when active)
  @panes[:cmd] = Pane.new(1, @h, @w, 1, 255, @cmdcolor)
  
  # Initialize scroll positions to 0
  @panes[:left].ix = 0
  @panes[:right].ix = 0
  
  # Set borders
  set_borders
end

#current_identity(msg = nil) ⇒ Object

Get identity for the current message based on its Maildir folder



8126
8127
8128
8129
8130
8131
8132
8133
8134
# File 'lib/heathrow/ui/application.rb', line 8126

def current_identity(msg = nil)
  msg ||= current_message
  return nil unless msg
   = msg['metadata']
   = JSON.parse() if .is_a?(String)
  folder = .is_a?(Hash) ? ['maildir_folder'] : nil
  folder ||= @current_folder  # Use browsing folder as fallback
  Config.identity_for_folder(folder)
end

#current_messageObject

Get the current message at @index (threaded or flat view)



220
221
222
# File 'lib/heathrow/ui/application.rb', line 220

def current_message
  current_message_for_navigation
end

#current_view_folderObject

Extract the folder name for the current view (for targeted sync)



7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
# File 'lib/heathrow/ui/application.rb', line 7935

def current_view_folder
  # If browsing a specific folder, sync that
  return @current_folder if @current_folder

  # For custom views with a folder filter, sync that folder
  view = @views[@current_view]
  if view && view[:filters].is_a?(Hash) && view[:filters]['rules'].is_a?(Array)
    folder_rule = view[:filters]['rules'].find { |r| r['field'] == 'folder' && r['op'] == 'like' }
    return folder_rule['value'] if folder_rule
  end

  # For All/New/mixed views: sync the few most recent folders
  if @filtered_messages && !@filtered_messages.empty?
    folders = @filtered_messages.first(50).map { |m| m['folder'] }.compact.uniq.first(5)
    return folders unless folders.empty?
  end

  nil  # No specific folder known
end

#current_view_item_sourceObject

Detect if current view is tied to an RSS/web source (for feed management)



1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
# File 'lib/heathrow/ui/application.rb', line 1073

def current_view_item_source
  # Check if current view filters to a single source_id that is RSS or web
  view = @views && @views[@current_view]
  filters = view && view[:filters]
  return nil unless filters

  rules = filters['rules'] || filters[:rules]
  return nil unless rules

  source_rule = rules.find { |r| r['field'] == 'source_id' && r['op'] == '=' }
  return nil unless source_rule

  source = @db.get_source_by_id(source_rule['value'].to_i)
  return nil unless source

  stype = source['plugin_type'] || source['type']
  %w[rss web].include?(stype) ? source : nil
end

#custom_bindings_helpObject



7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
# File 'lib/heathrow/ui/application.rb', line 7054

def custom_bindings_help
  return "" unless @config
  bindings = @config.custom_bindings
  return "" if bindings.empty?

  lines = ["\n #{" CUSTOM BINDINGS".bd.fg(theme[:accent])}"]
  bindings.each do |key, b|
    desc = b[:description] || b[:shell] || b[:action].to_s
    lines << "   #{key.fg(10).ljust(16)}= #{desc}"
  end
  lines.join("\n")
end

#cycle_borderObject



6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
# File 'lib/heathrow/ui/application.rb', line 6430

def cycle_border
  @border = (@border + 1) % 4

  # Save to config
  @config.set('ui.border', @border)
  @config.save

  # Recreate panes (which also sets borders) and re-render
  Rcurses.clear_screen
  create_panes
  render_all
end

#cycle_date_formatObject



6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
# File 'lib/heathrow/ui/application.rb', line 6444

def cycle_date_format
  # Define available date formats
  formats = [
    ['%b %e', 'Mutt (Mon  D)'],
    ['%d/%m %H:%M', 'European (DD/MM HH:MM)'],
    ['%m/%d %H:%M', 'US (MM/DD HH:MM)'],
    ['%Y-%m-%d %H:%M', 'ISO (YYYY-MM-DD HH:MM)'],
    ['%d.%m %H:%M', 'European dot (DD.MM HH:MM)'],
    ['%d %b %H:%M', 'Short month (DD Mon HH:MM)'],
    ['%b %d %H:%M', 'US short (Mon DD HH:MM)']
  ]
  
  # Find current format index
  current_index = formats.find_index { |f| f[0] == @date_format } || 0
  
  # Cycle to next format
  next_index = (current_index + 1) % formats.length
  @date_format = formats[next_index][0]
  format_name = formats[next_index][1]
  
  # Save to config
  @config.set('ui.date_format', @date_format)
  @config.save
  
  # Show current format in bottom bar
  @panes[:bottom].text = " Date format: #{format_name}".fg(156)
  @panes[:bottom].refresh
  
  # Refresh message list to show new format
  render_message_list
end

#cycle_sort_orderObject



6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
# File 'lib/heathrow/ui/application.rb', line 6476

def cycle_sort_order
  # Cycle through: latest -> alphabetical -> sender -> from -> conversation -> unread -> source -> latest
  @sort_order = case @sort_order
  when 'latest' then 'alphabetical'
  when 'alphabetical' then 'sender'
  when 'sender' then 'from'
  when 'from' then 'conversation'
  when 'conversation' then 'unread'
  when 'unread' then 'source'
  else 'latest'  # This handles 'source' and any other value
  end
  
  # Save per-view sort for custom views, global for built-in views
  save_view_sort_order
  
  # For threaded views, we need to reload the full message list before re-sorting
  if @show_threaded && @current_view == 'A'
    # Reload all messages to ensure we have the complete list
    @filtered_messages = @db.get_messages({}, 1000, 0, light: true)
  elsif @show_threaded && @current_view == 'N'
    # Reload unread messages
    @filtered_messages = @db.get_messages({is_read: false}, 1000, 0, light: true)
  elsif @show_threaded && @current_source_filter
    # Reload messages for current source
    @filtered_messages = @db.get_messages({source_id: @current_source_filter}, nil, 0, light: true)
  end
  
  # Reset threading state to force reorganization with new sort (preserve collapsed state)
  reset_threading(true)
  
  # Re-sort and redisplay messages
  sort_messages
  
  # Force reinit the organizer with the newly sorted messages
  organize_current_messages(true)
  
  @index = 0  # Reset to top
  render_all  # Re-render everything to show the new sort
end

#delete_maildir_file(msg) ⇒ Object

Delete the Maildir file from disk (like mutt's purge)



8820
8821
8822
8823
8824
8825
8826
8827
8828
8829
# File 'lib/heathrow/ui/application.rb', line 8820

def delete_maildir_file(msg)
   = msg['metadata']
   = JSON.parse() if .is_a?(String)
  return unless .is_a?(Hash)
  file_path = ['maildir_file']
  return unless file_path && File.exist?(file_path)
  File.delete(file_path)
rescue => e
  File.open('/tmp/heathrow_debug.log', 'a') { |f| f.puts "Delete file error: #{e.message}" } if ENV['DEBUG']
end

#delete_selected_sourceObject



932
933
934
935
936
937
938
939
940
941
# File 'lib/heathrow/ui/application.rb', line 932

def delete_selected_source
  return unless @filtered_messages[@index]
  source_id = @filtered_messages[@index]['id']
  
  confirm = bottom_ask("Delete source '#{@filtered_messages[@index]['subject']}'? (y/n): ", "")
  if confirm&.downcase == 'y'
    @source_manager.remove_source(source_id)
    show_sources
  end
end

#delete_source_itemObject

Delete an item (feed/channel) from the selected source



992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
# File 'lib/heathrow/ui/application.rb', line 992

def delete_source_item
  return unless @filtered_messages[@index]
  source_id = @filtered_messages[@index]['id']
  source = @db.get_source_by_id(source_id)
  return unless source

  config = source['config']
  config = JSON.parse(config) if config.is_a?(String)
  source_type = source['plugin_type'] || source['type']

  items = case source_type
          when 'rss' then config['feeds'] || []
          when 'web' then config['pages'] || []
          else return
          end

  return if items.empty?

  item_name = source_type == 'rss' ? 'feed' : 'page'
  pick = pick_from_list(format_item_names(items),
                        title: "DELETE #{item_name.upcase}", prompt: "j/k to select, Enter to delete, ESC to cancel")
  return unless pick

  removed = items.delete_at(pick)
  name = removed['title'] || removed['url'] || 'item'

  confirm = bottom_ask("Delete '#{name}'? (y/n): ", "")
  return unless confirm&.downcase == 'y'

  case source_type
  when 'rss' then config['feeds'] = items
  when 'web' then config['pages'] = items
  end

  # Remove messages from this feed/page
  deleted_msgs = purge_item_messages(source_id, source_type, removed)

  @db.execute("UPDATE sources SET config = ? WHERE id = ?", [config.to_json, source_id])
  set_feedback("Deleted: #{name} (#{deleted_msgs} messages removed)", 156, 3)
  show_sources
end

#delete_source_item_for(source) ⇒ Object

Delete item from a known source (called from non-Sources views)



1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
# File 'lib/heathrow/ui/application.rb', line 1127

def delete_source_item_for(source)
  config = source['config']
  config = JSON.parse(config) if config.is_a?(String)
  stype = source['plugin_type'] || source['type']

  items = case stype
          when 'rss' then config['feeds'] || []
          when 'web' then config['pages'] || []
          else return
          end
  return if items.empty?

  item_name = stype == 'rss' ? 'feed' : 'page'
  pick = pick_from_list(format_item_names(items),
                        title: "DELETE #{item_name.upcase}", prompt: "j/k to select, Enter to delete, ESC to cancel")
  return unless pick

  removed = items.delete_at(pick)
  name = removed['title'] || removed['url'] || 'item'

  confirm = bottom_ask("Delete '#{name}'? (y/n): ", "")
  return unless confirm&.downcase == 'y'

  case stype
  when 'rss' then config['feeds'] = items
  when 'web' then config['pages'] = items
  end

  deleted_msgs = purge_item_messages(source['id'], stype, removed)

  @db.execute("UPDATE sources SET config = ? WHERE id = ?", [config.to_json, source['id']])
  set_feedback("Deleted: #{name} (#{deleted_msgs} messages removed)", 156, 3)

  # Re-load the view to reflect removed messages
  reset_threading
  switch_to_view(@current_view) if @current_view
end

#display_sender(msg) ⇒ Object

Extract display name from sender (prefer sender_name, strip email angle brackets)



365
366
367
368
369
370
371
372
373
374
375
376
# File 'lib/heathrow/ui/application.rb', line 365

def display_sender(msg)
  name = msg['sender_name']
  return name if name && !name.empty?

  raw = msg['sender'] || ''
  # "John Doe <[email protected]>" → "John Doe"
  if raw =~ /^(.+?)\s*<[^>]+>$/
    $1.strip
  else
    raw
  end
end

#edit_address_bookObject



7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
# File 'lib/heathrow/ui/application.rb', line 7343

def edit_address_book
  ab_path = File.expand_path('~/setup/addressbook')
  editor = ENV['EDITOR'] || 'vim'
  Rcurses.clear_screen
  system("#{editor} #{ab_path}")
  @address_book = AddressBook.new(ab_path)
  setup_display
  create_panes
  render_all
  set_feedback("Address book reloaded", 156, 2)
end

#edit_chat_in_editor(platform, target) ⇒ Object



5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
# File 'lib/heathrow/ui/application.rb', line 5574

def edit_chat_in_editor(platform, target)
  tempfile = Tempfile.new(['heathrow-chat', '.txt'])
  begin
    tempfile.write("# #{platform.capitalize} message to #{target}\n# Lines starting with # are ignored\n\n")
    tempfile.flush
    if run_editor(tempfile.path)
      tempfile.rewind
      tempfile.read.lines.reject { |l| l.start_with?('#') }.join.strip
    end
  ensure
    tempfile.close
    tempfile.unlink
  end
end

#edit_filterObject



7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
# File 'lib/heathrow/ui/application.rb', line 7608

def edit_filter
  # Only allow filter editing for configurable views (0-9, F1-F12)
  view_key = @current_view
  unless view_key =~ /^[0-9]$/ || view_key =~ /^F\d{1,2}$/
    @panes[:bottom].text = " Can only configure filters for views 0-9 and F1-F12".fg(196)
    @panes[:bottom].refresh
    sleep 2
    render_all
    return
  end

  existing_view = @views[view_key] || {}
  existing_filters = existing_view[:filters] || {}

  # Extract current rule values for defaults
  rules = existing_filters.is_a?(Hash) ? (existing_filters['rules'] || []) : []
  current_vals = {}
  rules.each do |r|
    key = "#{r['field']}_#{r['op']}"
    current_vals[key] = r['value']
  end

  # If view exists, ask if they want to edit or clear
  if existing_view[:filters] && !existing_view[:filters].empty?
    choice = bottom_ask("View #{view_key} exists. (E)dit, (C)lear, or ESC to cancel: ", '')
    return render_all if choice.nil?

    case choice.downcase
    when 'c', 'clear'
      @db.delete_view(existing_view[:id]) if existing_view[:id]
      @views.delete(view_key)
      @filtered_messages = []
      @index = 0
      render_all
      return
    when 'e', 'edit'
      # Continue to edit
    else
      render_all
      return
    end
  end

  # Filter configuration wizard
  new_rules = []

  # 1. View name
  current_name = existing_view[:name] || "View #{view_key}"
  view_name = bottom_ask("View name (ESC to cancel): ", current_name)
  return render_all if view_name.nil?
  view_name = "View #{view_key}" if view_name.empty?

  # 2. Any field (search across sender, subject, content)
  current_search = current_vals['search_like'] || ''
  search_input = bottom_ask("Any field match (searches sender/subject/content - ESC cancel): ", current_search)
  return render_all if search_input.nil?
  unless search_input.empty?
    new_rules << { 'field' => 'search', 'op' => 'like', 'value' => search_input }
  end

  # 3. Folder filter (maildir_folder)
  current_folder = current_vals['folder_like'] || current_vals['folder_='] || ''
  folder_input = bottom_ask("Folder (e.g. Personal, Work.Archive - ESC cancel): ", current_folder)
  return render_all if folder_input.nil?
  unless folder_input.empty?
    new_rules << { 'field' => 'folder', 'op' => 'like', 'value' => folder_input }
  end

  # 4. Label filter
  current_label = current_vals['label_like'] || ''
  label_input = bottom_ask("Label (e.g. Niklas, Work, Important - ESC cancel): ", current_label)
  return render_all if label_input.nil?
  unless label_input.empty?
    new_rules << { 'field' => 'label', 'op' => 'like', 'value' => label_input }
  end

  # 5. Sender pattern
  current_sender = current_vals['sender_like'] || ''
  sender_input = bottom_ask("Sender pattern (e.g. Mom|Dad|Boss - ESC cancel): ", current_sender)
  return render_all if sender_input.nil?
  unless sender_input.empty?
    new_rules << { 'field' => 'sender', 'op' => 'like', 'value' => sender_input }
  end

  # 5. Subject pattern
  current_subject = current_vals['subject_like'] || ''
  subject_input = bottom_ask("Subject pattern (ESC cancel): ", current_subject)
  return render_all if subject_input.nil?
  unless subject_input.empty?
    new_rules << { 'field' => 'subject', 'op' => 'like', 'value' => subject_input }
  end

  # 6. Source filter
  current_source = current_vals['source_like'] || ''
  source_names = @db.get_sources(true).map { |s| s['name'] }.join(', ')
  source_input = bottom_ask("Source (#{source_names} - ESC cancel): ", current_source)
  return render_all if source_input.nil?
  unless source_input.empty?
    new_rules << { 'field' => 'source', 'op' => 'like', 'value' => source_input }
  end

  # 7. Read status
  current_read = current_vals['read_=']
  default_read = current_read == false ? 'y' : (current_read == true ? 'n' : '')
  read_input = bottom_ask("Unread only? (y/n/Enter for all, ESC cancel): ", default_read)
  return render_all if read_input.nil?
  if read_input.downcase == 'y'
    new_rules << { 'field' => 'read', 'op' => '=', 'value' => false }
  elsif read_input.downcase == 'n'
    new_rules << { 'field' => 'read', 'op' => '=', 'value' => true }
  end

  # Build filters hash with rules
  filters = { 'rules' => new_rules }

  # Save the view
  view_config = {
    name: view_name,
    key_binding: view_key,
    filters: filters,
    sort_order: 'timestamp DESC'
  }
  # If updating existing view, include its id
  view_config[:id] = existing_view[:id] if existing_view[:id]

  @db.save_view(view_config)

  # Update local cache
  @views[view_key] = {
    id: view_config[:id] || @db.db.last_insert_row_id,
    name: view_name,
    filters: filters,
    sort_order: 'timestamp DESC',
    key_binding: view_key
  }

  # Apply the new filters immediately
  @current_view = view_key
  apply_view_filters(@views[view_key])
  @index = 0

  @panes[:bottom].text = " View #{view_key} configured!".fg(156)
  @panes[:bottom].refresh
  sleep(1)

  render_all
end

#edit_message_contentObject



5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
# File 'lib/heathrow/ui/application.rb', line 5339

def edit_message_content
  msg = current_message
  return unless msg
  return if header_message?(msg)
  msg = ensure_full_message(msg)

  source_id = msg['source_id']
  source = @db.get_source(source_id)
  return unless source

  require_relative '../message_composer'
  identity = current_identity(msg)
  composer = MessageComposer.new(nil, identity: identity, address_book: @address_book, editor_args: @editor_args)

  # Build draft from the message content
  draft = {
    'to' => '',
    'subject' => msg['subject'] || '',
    'body' => msg['content'] || ''
  }

  composed = composer.compose_draft(draft)
  if composed
    finalize_compose(source, composed, "Message cancelled")
  else
    set_feedback("Cancelled", 245, 1)
  end
end

#edit_selected_sourceObject

Source management methods



1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
# File 'lib/heathrow/ui/application.rb', line 1738

def edit_selected_source
  return unless @filtered_messages[@index]
  
  source_config = @filtered_messages[@index]
  source = @db.get_all_sources.find { |s| s['id'] == source_config['id'] }
  return unless source
  
  # Show edit options in right pane
  options = []
  options << "EDIT SOURCE: #{source['name']}".bd.fg(226)
  options << "=" * 40
  options << ""
  options << "What would you like to edit?"
  options << ""
  options << "1. Change color"
  options << "2. Change name"
  options << "3. Change poll interval"
  options << "4. Toggle enabled/disabled"
  options << ""
  options << "Enter number (1-4) or ESC to cancel"
  
  @panes[:right].text = options.join("\n")
  @panes[:right].refresh
  
  # Get user choice
  choice = bottom_ask("Edit option (1-4): ", "")
  
  if choice && !choice.empty?
    case choice
    when '1'
      edit_source_color(source)
    when '2'
      edit_source_name(source)
    when '3'
      edit_source_interval(source)
    when '4'
      @source_manager.toggle_source(source['id'])
    end
    
    load_source_colors
  end
  
  show_sources
end

#edit_source_color(source) ⇒ Object



1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
# File 'lib/heathrow/ui/application.rb', line 1783

def edit_source_color(source)
  # Use the same color picker as the wizard
  begin
    wizard = Heathrow::SourceWizard.new(@source_manager, @panes[:bottom], @panes[:right])
    selected_color = wizard.select_color
    
    if selected_color
      # Update the source color in database
      @db.execute("UPDATE sources SET color = ? WHERE id = ?", selected_color, source['id'])
      # Reload sources to get updated values
      @source_manager.load_sources
      
      @panes[:bottom].text = " Color updated to #{selected_color}!".fg(selected_color)
      @panes[:bottom].refresh
      sleep(1)
    end
  rescue => e
    @panes[:bottom].text = " Error: #{e.message}".fg(196)
    @panes[:bottom].refresh
    sleep(4)  # Stay longer for error messages
  end
end

#edit_source_interval(source) ⇒ Object



1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
# File 'lib/heathrow/ui/application.rb', line 1821

def edit_source_interval(source)
  current_interval = source['poll_interval']
  new_interval = bottom_ask("Poll interval in seconds (current: #{current_interval}): ", current_interval.to_s)
  
  if new_interval && !new_interval.empty? && new_interval.to_i > 0
    @db.execute("UPDATE sources SET poll_interval = ? WHERE id = ?", new_interval.to_i, source['id'])
    # Reload sources to get updated values
    @source_manager.load_sources
    
    @panes[:bottom].text = " Poll interval updated successfully!".fg(156)
    @panes[:bottom].refresh
    sleep(1)
  end
end

#edit_source_name(source) ⇒ Object



1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
# File 'lib/heathrow/ui/application.rb', line 1806

def edit_source_name(source)
  current_name = source['name']
  new_name = bottom_ask("New name (current: #{current_name}): ", current_name)
  
  if new_name && !new_name.empty? && new_name != current_name
    @db.execute("UPDATE sources SET name = ? WHERE id = ?", new_name, source['id'])
    # Reload sources to get updated values
    @source_manager.load_sources
    
    @panes[:bottom].text = " Name updated successfully!".fg(156)
    @panes[:bottom].refresh
    sleep(1)
  end
end

#ensure_all_feeds_loaded(source_id) ⇒ Object

Ensure all feeds/channels from a source have at least some messages loaded



2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
# File 'lib/heathrow/ui/application.rb', line 2382

def ensure_all_feeds_loaded(source_id)
  source = @db.get_source_by_id(source_id)
  return unless source
  config = source['config']
  config = JSON.parse(config) if config.is_a?(String)
  return unless config.is_a?(Hash)

  stype = source['plugin_type']
  return unless stype == 'rss'

  feeds = config['feeds'] || []
  return if feeds.empty?
  expected = feeds.map { |f| f['title'] || f['url'] }

  # Find which feeds are already in loaded messages
  loaded_ids = Set.new
  loaded_feeds = Set.new
  @filtered_messages.each do |msg|
    loaded_ids << msg['id']
    meta = msg['metadata']
    meta = JSON.parse(meta) if meta.is_a?(String) rescue nil
    next unless meta.is_a?(Hash)
    loaded_feeds << meta['feed_title'] if meta['feed_title']
  end

  missing = expected - loaded_feeds.to_a
  return if missing.empty?

  # Load latest 20 messages per missing feed using json_extract
  light_cols = "id, source_id, external_id, thread_id, parent_id, sender, sender_name, recipients, subject, substr(content, 1, 200) as content, timestamp, received_at, read AS is_read, starred AS is_starred, archived, labels, metadata, attachments, folder, replied"
  missing.each do |feed_name|
    rows = @db.execute(
      "SELECT #{light_cols} FROM messages WHERE source_id = ? AND json_extract(metadata, '$.feed_title') = ? ORDER BY timestamp DESC LIMIT 20",
      source_id, feed_name
    )
    rows = rows.reject { |r| loaded_ids.include?(r['id']) }
    rows = rows.map do |r|
      r = r.dup
      r['metadata'] = JSON.parse(r['metadata']) if r['metadata'].is_a?(String) rescue nil
      r['labels'] = JSON.parse(r['labels']) if r['labels'].is_a?(String) rescue nil
      r['attachments'] = JSON.parse(r['attachments']) if r['attachments'].is_a?(String) rescue nil
      r['recipients'] = JSON.parse(r['recipients']) if r['recipients'].is_a?(String) rescue nil
      r
    end
    @filtered_messages.concat(rows)
  end
rescue => e
  File.open('/tmp/heathrow-crash.log', 'a') { |f|
    f.puts "#{Time.now.strftime('%Y-%m-%d %H:%M:%S')} ensure_all_feeds_loaded: #{e.class}: #{e.message}"
    f.puts "  #{e.backtrace&.first(3)&.join("\n  ")}"
  }
end

#ensure_full_message(msg) ⇒ Object



5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
# File 'lib/heathrow/ui/application.rb', line 5175

def ensure_full_message(msg)
  if msg && msg['id'] && !msg['_full_loaded'] && !msg['is_header']
    full = @db.get_message(msg['id'])
    if full
      if msg.frozen?
        # Replace frozen hash in filtered_messages with mutable copy
        idx = @filtered_messages.index { |m| m.equal?(msg) }
        msg = full.merge('_full_loaded' => true)
        @filtered_messages[idx] = msg if idx
      else
        msg.merge!(full)
        msg['_full_loaded'] = true
      end
    end
  end
  msg
end

#expand_current_itemObject



2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
# File 'lib/heathrow/ui/application.rb', line 2718

def expand_current_item
  return unless @show_threaded && @organizer
  
  msg = current_message
  return unless msg
  
  @saved_positions ||= {}
  restore_position = nil
  
  if msg['is_dm_header']
    dm_key = msg['channel_id']
    if @sort_order == 'conversation'
      @dm_collapsed[dm_key] = !@dm_collapsed.fetch(dm_key, true)
    else
      @dm_section_collapsed = !@dm_section_collapsed
    end
  elsif msg['is_channel_header']
    # Toggle the channel collapse state
    @channel_collapsed[msg['channel_id']] = !@channel_collapsed[msg['channel_id']]

    # If expanding, restore saved position if available
    if !@channel_collapsed[msg['channel_id']] && @saved_positions[msg['channel_id']]
      restore_position = @saved_positions[msg['channel_id']]
    end
  elsif msg['is_thread_header']
    # Toggle the thread collapse state
    @thread_collapsed[msg['thread_id']] = !@thread_collapsed[msg['thread_id']]

    if !@thread_collapsed[msg['thread_id']] && @saved_positions[msg['thread_id']]
      restore_position = @saved_positions[msg['thread_id']]
    end
  end
  
  # Re-render
  render_message_list_threaded
  
  # Restore position if we had one saved
  if restore_position
    # Make sure the position is still valid
    max_index = filtered_messages_size - 1
    @index = [restore_position, max_index].min
    render_message_list
  end
  
  render_message_content
end

#extract_image_urls(html) ⇒ Object



8219
8220
8221
8222
8223
8224
8225
8226
8227
8228
8229
8230
8231
8232
8233
8234
8235
8236
8237
# File 'lib/heathrow/ui/application.rb', line 8219

def extract_image_urls(html)
  return [] unless html
  # Extract full img tags, then filter by attributes
  tags = html.scan(/<img[^>]*>/i)
  urls = []
  tags.each do |tag|
    src = tag[/src=["']([^"']+)["']/i, 1]
    next unless src
    # Skip by URL patterns (tracking, icons, social media badges)
    next if src =~ /track|pixel|spacer|beacon|\.gif$|icon|logo|badge|button|social|facebook|linkedin|twitter|instagram/i
    # Skip by HTML dimensions (tracking pixels and small icons)
    w = tag[/width=["']?(\d+)/i, 1]&.to_i
    h = tag[/height=["']?(\d+)/i, 1]&.to_i
    next if w && w <= 40
    next if h && h <= 40
    urls << src
  end
  urls
end

#extract_original_attachments(msg) ⇒ Object

Extract original attachments from a message for forwarding



5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
# File 'lib/heathrow/ui/application.rb', line 5407

def extract_original_attachments(msg)
   = msg['metadata']
   = JSON.parse() if .is_a?(String) rescue nil
  return nil unless .is_a?(Hash)

  file_path = ['maildir_file']
  return nil unless file_path && File.exist?(file_path)

  require 'mail'
  require 'tmpdir'
  mail = Mail.read(file_path)
  return nil if mail.attachments.empty?

  tmp_dir = File.join(Dir.tmpdir, "heathrow-fwd-#{Process.pid}")
  FileUtils.mkdir_p(tmp_dir)

  paths = []
  mail.attachments.each do |att|
    next unless att.filename
    out = File.join(tmp_dir, att.filename)
    File.write(out, att.decoded)
    paths << out
  end
  paths.empty? ? nil : paths
rescue => e
  File.open('/tmp/heathrow-crash.log', 'a') { |f|
    f.puts "#{Time.now.strftime('%Y-%m-%d %H:%M:%S')} extract_attachments: #{e.class}: #{e.message}"
    f.puts "  #{e.backtrace&.first(3)&.join("\n  ")}"
  }
  nil
end

#file_messageObject

── Save to folder (s key) ── Moves email on disk, updates folder + labels in DB for all types. Works on tagged messages if any are tagged; otherwise on current message. Sub-keys: any key for shortcuts (except B/F/=), B=browse all, F=browse favorites, ==configure



4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
# File 'lib/heathrow/ui/application.rb', line 4297

def file_message
  # Get target folder
  shortcuts = save_folder_shortcuts
  hint = shortcuts.map { |k, v| "s#{k}:#{v.split('.').last}" }.join(" ")
  hint = hint.empty? ? "" : " [#{hint}]"
  tagged_hint = @tagged_messages.size > 0 ? " (#{@tagged_messages.size} tagged)" : ""
  set_feedback("Save to folder:#{hint} B:Browse F:Fav =:Config#{tagged_hint}", 226, 5)
  chr = getchr(5)
  if chr.nil? || chr == 'ESC' || chr == "\e"
    @feedback_expires_at = nil
    render_bottom_bar
    return
  end

  if chr == '='
    configure_save_shortcuts
    return
  end

  if chr == 'B'
    dest = save_browse_folders
    return unless dest
  elsif chr == 'F'
    dest = save_browse_favorites
    return unless dest
  elsif shortcuts[chr]
    dest = shortcuts[chr]
  else
    initial = chr == 'ENTER' ? '' : chr.to_s
    dest = bottom_ask("Move to folder: ", initial)
    return if dest.nil? || dest.strip.empty? || dest.strip == initial.strip
    dest = dest.strip
  end

  # Validate folder exists on disk
  maildir_root = @config.get('sources.maildir.path') || File.join(Dir.home, 'Main', 'Maildir')
  folder_path = File.join(maildir_root, ".#{dest}")
  unless Dir.exist?(folder_path)
    confirm = bottom_ask("Folder '#{dest}' doesn't exist. Create it? [y/N] ")
    unless confirm&.strip&.downcase == 'y'
      set_feedback("Save cancelled", 245, 2)
      return
    end
  end

  # Collect messages to file
  msgs = if @tagged_messages.size > 0
           @filtered_messages.select { |m| m['id'] && @tagged_messages.include?(m['id']) }
         else
           msg = current_message
           return unless msg && !msg['is_header'] && !msg['is_channel_header'] && !msg['is_thread_header']
           [msg]
         end
  return if msgs.empty?

  count = 0
  failed = 0
  filed_ids = Set.new
  msgs.each do |msg|
    begin
      file_single_message(msg, dest)
      filed_ids << msg['id'] if msg['id']
      count += 1
    rescue => e
      failed += 1
    end
  end

  # Remove filed messages from current view (by id, works in both flat and threaded mode)
  @filtered_messages.reject! { |m| m['id'] && filed_ids.include?(m['id']) }
  if @show_threaded
    @display_messages&.reject! { |m| m['id'] && filed_ids.include?(m['id']) }
    # Force organizer to rebuild from updated @filtered_messages
    organize_current_messages(true)
  end
  @tagged_messages.clear if @tagged_messages.size > 0
  @index = [@index, (@filtered_messages.size - 1)].min
  @index = 0 if @index < 0 || @filtered_messages.empty?

  msg_text = "Moved #{count} message#{count > 1 ? 's' : ''} to #{dest}"
  msg_text += " (#{failed} failed)" if failed > 0
  set_feedback(msg_text, failed > 0 ? 208 : 156, 2)
  render_all
end

#file_single_message(msg, dest) ⇒ Object

Move a single message to a folder (disk + DB)



4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
# File 'lib/heathrow/ui/application.rb', line 4383

def file_single_message(msg, dest)
   = msg['metadata']
   = JSON.parse() if .is_a?(String) rescue {}
   = {} unless .is_a?(Hash)

  # Move the Maildir file on disk if this is an email
  file_path = ['maildir_file']
  if file_path && File.exist?(file_path)
    require_relative '../sources/maildir'
    require 'fileutils'
    maildir_root = @config.get('sources.maildir.path') || File.join(Dir.home, 'Main', 'Maildir')
    new_path = Heathrow::Sources::Maildir.move_to_folder(file_path, maildir_root, dest)
    if new_path
      ['maildir_file'] = new_path
      ['maildir_folder'] = dest
    end
  end

  # Preserve existing labels, set folder as first label
  existing = msg['labels']
  existing = JSON.parse(existing) if existing.is_a?(String) rescue []
  existing = [] unless existing.is_a?(Array)
  labels = ([dest] + existing).uniq

  @db.execute(
    "UPDATE messages SET folder = ?, labels = ?, metadata = ? WHERE id = ?",
    dest, labels.to_json, .to_json, msg['id']
  )
  msg['folder'] = dest
  msg['metadata'] = 
  msg['labels'] = labels

  # Mark as read (we've seen it if we're filing it)
  if msg['is_read'].to_i == 0
    @db.mark_as_read(msg['id'])
    msg['is_read'] = 1
    sync_maildir_flag(msg, 'S', true)
  end
end

#finalize_compose(source, composed, cancel_label = "cancelled") ⇒ Object

Unified send prompt loop: handles send, edit, postpone, cancel



5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
# File 'lib/heathrow/ui/application.rb', line 5761

def finalize_compose(source, composed, cancel_label = "cancelled")
  require_relative '../message_composer'
  # Rebuild panes after editor (vim leaves terminal in unknown state)
  setup_display
  create_panes
  render_all
  pending_attachments = Array(composed[:attachments]).dup
  loop do
    attachments = prompt_attachments(pending_attachments, composed: composed)
    case attachments
    when :postpone
      postpone_message(source, composed)
      return
    when :edit
      # Preserve attachments across edit
      pending_attachments = Array(composed[:attachments]).dup
      # Re-open editor with current composed data
      composer = MessageComposer.new(nil, identity: current_identity, address_book: @address_book, editor_args: @editor_args)
      re_composed = composer.compose_draft(composed.transform_keys(&:to_s))
      setup_display
      create_panes
      render_all
      if re_composed
        composed = re_composed
        composed[:attachments] = pending_attachments unless pending_attachments.empty?
      end
      # If unchanged (re_composed nil), just return to send prompt
    when nil
      set_feedback(cancel_label, 245, 1)
      return
    else
      composed[:attachments] = attachments unless attachments.empty?
      send_composed_message(source, composed)
      return
    end
  end
end

#find_and_select_header(id, type) ⇒ Object



2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
# File 'lib/heathrow/ui/application.rb', line 2982

def find_and_select_header(id, type)
  # Find the header in the display messages
  @display_messages.each_with_index do |msg, idx|
    if type == 'channel' && msg['is_channel_header'] && msg['channel_id'] == id
      @index = idx
      return
    elsif type == 'thread' && msg['is_thread_header'] && msg['thread_id'] == id
      @index = idx
      return
    end
  end
end

#find_current_group_messages(msg) ⇒ Object

Find messages in the same group as the current message/header Returns nil if not in a group context



3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
# File 'lib/heathrow/ui/application.rb', line 3600

def find_current_group_messages(msg)
  return nil unless msg && @show_threaded && @organizer

  # If standing on a header, use its section_messages directly
  if header_message?(msg)
    return msg['section_messages'] if msg['section_messages']
  end

  # Standing on a regular message: walk backward to find its section header
  idx = @index - 1
  while idx >= 0
    prev = @display_messages[idx]
    if prev && (header_message?(prev))
      return prev['section_messages'] if prev['section_messages']
      break
    end
    idx -= 1
  end

  nil
end

#find_mail_attachment(mail, att) ⇒ Object



3415
3416
3417
3418
3419
# File 'lib/heathrow/ui/application.rb', line 3415

def find_mail_attachment(mail, att)
  name = att['name'] || att['filename']
  mail.attachments.find { |a| a.filename == name } ||
    mail.attachments.find { |a| a.filename&.include?(name.to_s.split("\n").first) }
end

#flatten_folder_tree(tree, prefix = '', depth = 0, collapsed = {}) ⇒ Object

Flatten folder tree into displayable lines with indent



3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
# File 'lib/heathrow/ui/application.rb', line 3812

def flatten_folder_tree(tree, prefix = '', depth = 0, collapsed = {})
  lines = []
  tree.keys.sort.each do |key|
    full_name = prefix.empty? ? key : "#{prefix}.#{key}"
    has_children = !tree[key].empty?
    is_collapsed = collapsed[full_name]

    lines << {
      name: key,
      full_name: full_name,
      depth: depth,
      has_children: has_children,
      collapsed: is_collapsed
    }

    if has_children && !is_collapsed
      lines.concat(flatten_folder_tree(tree[key], full_name, depth + 1, collapsed))
    end
  end
  lines
end

#flush_pending_readObject

Flush any deferred read mark (call when leaving a view)



246
247
248
249
250
# File 'lib/heathrow/ui/application.rb', line 246

def flush_pending_read
  return unless @pending_mark_read
  mark_message_read(@pending_mark_read)
  @pending_mark_read = nil
end

#folder_browser_loopObject



3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
# File 'lib/heathrow/ui/application.rb', line 3959

def folder_browser_loop
  loop do
    chr = getchr
    case chr
    when 'j', 'DOWN'
      @folder_browser_index = (@folder_browser_index + 1) % @folder_display.size if @folder_display.size > 0
      render_folder_browser
    when 'k', 'UP'
      @folder_browser_index = (@folder_browser_index - 1) % @folder_display.size if @folder_display.size > 0
      render_folder_browser
    when 'l', 'RIGHT', 'ENTER'
      # RTFM-style: RIGHT/l/Enter = enter/expand
      folder = @folder_display[@folder_browser_index]
      next unless folder
      if folder[:has_children] && folder[:collapsed]
        # Expand collapsed folder
        @folder_collapsed.delete(folder[:full_name])
        @folder_display = flatten_folder_tree(@folder_tree, '', 0, @folder_collapsed)
        render_folder_browser
      elsif folder[:has_children] && !folder[:collapsed]
        # Already expanded — enter (open) the folder
        open_folder(folder[:full_name])
        break
      else
        # Leaf folder — open it
        open_folder(folder[:full_name])
        break
      end
    when 'h', 'LEFT'
      # RTFM-style: LEFT/h = collapse or go to parent
      folder = @folder_display[@folder_browser_index]
      next unless folder
      if folder[:has_children] && !folder[:collapsed]
        # Collapse this folder
        @folder_collapsed[folder[:full_name]] = true
        @folder_display = flatten_folder_tree(@folder_tree, '', 0, @folder_collapsed)
        render_folder_browser
      elsif folder[:depth] > 0
        # Go to parent folder
        parent_name = folder[:full_name].split('.')[0..-2].join('.')
        parent_idx = @folder_display.index { |f| f[:full_name] == parent_name }
        if parent_idx
          @folder_browser_index = parent_idx
          render_folder_browser
        end
      end
    when ' ', 'SPACE'
      # Toggle collapse/expand
      folder = @folder_display[@folder_browser_index]
      if folder && folder[:has_children]
        if folder[:collapsed]
          @folder_collapsed.delete(folder[:full_name])
        else
          @folder_collapsed[folder[:full_name]] = true
        end
        @folder_display = flatten_folder_tree(@folder_tree, '', 0, @folder_collapsed)
        render_folder_browser
      end
    when 'F'
      show_favorites_browser
      break
    when '+'
      # Add/remove selected folder from favorites
      folder = @folder_display[@folder_browser_index]
      if folder
        favorites = get_favorite_folders
        if favorites.include?(folder[:full_name])
          favorites.delete(folder[:full_name])
          @panes[:bottom].text = " Removed #{folder[:full_name]} from favorites".fg(226)
        else
          favorites << folder[:full_name]
          @panes[:bottom].text = " Added #{folder[:full_name]} to favorites".fg(156)
        end
        save_favorite_folders(favorites)
        @browser_favorites = favorites
        # Quick re-render left pane only (skip slow count query)
        render_folder_browser_left_only
        @panes[:bottom].refresh
      end
    when 'PgDOWN'
      @folder_browser_index = [@folder_browser_index + (@panes[:left].h - 2), @folder_display.size - 1].min
      render_folder_browser
    when 'PgUP'
      @folder_browser_index = [@folder_browser_index - (@panes[:left].h - 2), 0].max
      render_folder_browser
    when 'HOME'
      @folder_browser_index = 0
      render_folder_browser
    when 'END'
      @folder_browser_index = @folder_display.size - 1
      render_folder_browser
    when 'q', 'ESC', "\e"
      @in_folder_browser = false
      @in_favorites_browser = false
      render_all
      break
    else
      # Check folder shortcuts
      shortcuts = get_folder_shortcuts
      if shortcuts[chr]
        open_folder(shortcuts[chr])
        break
      end
    end
  end
end

#folder_message_count(folder_name) ⇒ Object

Get counts for a single folder (fast — one query)



3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
# File 'lib/heathrow/ui/application.rb', line 3835

def folder_message_count(folder_name)
  # Use range query to leverage folder index (5x faster than OR + LIKE)
  row = @db.db.get_first_row(
    "SELECT COUNT(*) as total, SUM(CASE WHEN read = 0 THEN 1 ELSE 0 END) as unread FROM messages WHERE folder = ?",
    [folder_name]
  )
  { total: (row && row['total']) || 0, unread: (row && row['unread']) || 0 }
rescue
  { total: 0, unread: 0 }
end

#format_attachments(attachments) ⇒ Object



8567
8568
8569
8570
8571
8572
8573
8574
8575
8576
8577
8578
8579
# File 'lib/heathrow/ui/application.rb', line 8567

def format_attachments(attachments)
  return nil unless attachments.is_a?(Array) && !attachments.empty?
  lines = []
  lines << "Attachments:".bd.fg(208)
  attachments.each_with_index do |att, i|
    name = att['name'] || att['filename'] || 'unnamed'
    size = att['size'] ? " (#{human_size(att['size'])})" : ''
    ctype = att['content_type']&.split(';')&.first || ''
    lines << "  [#{i + 1}] #{name}#{size}  #{ctype}".fg(250)
  end
  lines << "  Press 'v' to view/save attachments".fg(245)
  lines.join("\n")
end

#format_calendar_event(attachments) ⇒ Object

Format attachment list for display Parse and format calendar events from ICS attachments



8396
8397
8398
8399
8400
8401
8402
8403
8404
8405
8406
8407
8408
8409
8410
8411
8412
8413
8414
8415
8416
8417
8418
8419
8420
8421
8422
8423
8424
8425
8426
8427
8428
8429
8430
8431
8432
8433
8434
8435
8436
8437
8438
8439
8440
8441
8442
8443
8444
8445
8446
8447
8448
8449
8450
8451
8452
8453
8454
8455
8456
8457
8458
8459
8460
8461
8462
8463
8464
8465
8466
8467
8468
8469
8470
# File 'lib/heathrow/ui/application.rb', line 8396

def format_calendar_event(attachments)
  attachments = [] unless attachments.is_a?(Array)
  # Find ICS data from attachments or inline MIME parts
  ics_data = nil
  begin
    require 'mail'

    # First check attachments array
    ics_att = attachments.is_a?(Array) && attachments.find do |att|
      ct = (att['content_type'] || '').downcase
      name = (att['name'] || att['filename'] || '').downcase
      ct.include?('calendar') || ct.include?('ics') || name.end_with?('.ics')
    end

    # Get the maildir file path (from attachment or message metadata)
    file = ics_att['source_file'] if ics_att
    file ||= @_current_render_msg_file  # Set by render_message_content
    return nil unless file && File.exist?(file)

    # Parse MIME parts for calendar data
    mail = Mail.read(file)
    if mail.multipart?
      mail.parts.each do |part|
        ct = (part.content_type || '').downcase
        if ct.include?('calendar') || ct.include?('ics')
          ics_data = part.decoded
          break
        end
        if part.multipart?
          part.parts.each do |sub|
            sct = (sub.content_type || '').downcase
            if sct.include?('calendar') || sct.include?('ics')
              ics_data = sub.decoded
              break
            end
          end
          break if ics_data
        end
      end
    end
    ics_data ||= File.read(file) if file.end_with?('.ics')
    return nil unless ics_data && ics_data.include?('BEGIN:')

    # Use VcalView parser
    # Use basic inline ICS parser
    event = parse_ics_basic(ics_data)
    return nil unless event

    # Format the event for display
    lines = []
    lines << "Calendar Event".bd.fg(226)
    lines << ""
    lines << "WHAT:  #{event[:summary]}".fg(156) if event[:summary]
    if event[:dates]
      when_str = event[:dates]
      when_str += " (#{event[:weekday]})" if event[:weekday]
      when_str += ", #{event[:times]}" if event[:times]
      lines << "WHEN:  #{when_str}".fg(39)
    end
    lines << "WHERE: #{event[:location]}".fg(45) if event[:location] && !event[:location].to_s.empty?
    lines << "RECUR: #{event[:recurrence]}".fg(180) if event[:recurrence]
    lines << "STATUS: #{event[:status]}".fg(245) if event[:status]
    lines << ""
    lines << "ORGANIZER: #{event[:organizer]}".fg(2) if event[:organizer]
    if event[:participants] && !event[:participants].to_s.strip.empty?
      lines << "PARTICIPANTS:".fg(2)
      lines << event[:participants].fg(245)
    end
    # Skip description (email body already shows it, and ICS descriptions
    # often contain raw URLs that can overflow the pane)
    lines.join("\n")
  rescue => e
    nil  # Don't crash on calendar parse errors
  end
end

#format_item_names(items) ⇒ Object

Format item names with status indicators for picker Does a quick HTTP check for feeds without a recent status



1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
# File 'lib/heathrow/ui/application.rb', line 1167

def format_item_names(items)
  # Quick-check feeds that have no status or stale status (>1 hour)
  needs_check = items.select do |it|
    it.is_a?(Hash) && it['url'] && (it['last_status'].nil? || it['last_sync'].to_i < Time.now.to_i - 3600)
  end

  unless needs_check.empty?
    set_feedback("Checking #{needs_check.size} feeds...", 245, 0)
    needs_check.each do |it|
      ok = system("curl -sf --head --max-time 5 #{Shellwords.escape(it['url'])} >/dev/null 2>&1")
      it['last_status'] = ok ? (it['last_status'] || 'ok') : 'unreachable'
      it['last_sync'] = Time.now.to_i
    end
  end

  items.map do |it|
    name = it.is_a?(Hash) ? (it['title'] || it['url'] || it['name'] || '?') : it.to_s
    status = it.is_a?(Hash) ? it['last_status'] : nil
    if status == 'ok'
      "✓ #{name}"
    elsif status
      "✗ #{name}"
    else
      "  #{name}"
    end
  end
end

#format_message_line(msg, selected) ⇒ Object



1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
# File 'lib/heathrow/ui/application.rb', line 1509

def format_message_line(msg, selected)
  # Extract message details
  timestamp = (parse_timestamp(msg['timestamp']) || "").ljust(6)
  sender = display_sender(msg)

  # Get subject, or use content preview, or "(no subject)"
  if msg['subject'] && !msg['subject'].empty?
    subject = msg['subject']
  elsif msg['content'] && !msg['content'].empty?
    # Use first line of content, cleaned up
    content_preview = msg['content'].lines.first || msg['content']
    content_preview = content_preview.strip.gsub(/\s+/, ' ')  # Normalize whitespace
    subject = content_preview[0..50] + (content_preview.length > 50 ? '…' : '')
  else
    subject = '(no subject)'
  end
  
  # Use source color (custom or default by source type)
  source_color = get_source_color(msg)
  
  # Calculate available width accounting for border, arrow, and potential star
  available_width = @panes[:left].w - 2  # Account for border
  available_width -= 2 if @panes[:left].border  # Extra space for border chars
  available_width -= 3  # Space for N flag + replied flag + indicator column (tag/star/attachment/D)
  
  # Truncate sender to fit (use display_width for CJK characters)
  sender_max = 15
  dw = Rcurses.display_width(sender)
  sender_display = if dw > sender_max
    truncate_to_width(sender, sender_max - 1) + '…'
  else
    sender + ' ' * [sender_max - dw, 0].max
  end

  # Build the line with timestamp, icon and sender
  icon = get_source_icon(msg['source_type'])
  line_prefix = "#{timestamp} #{icon} #{sender_display} "

  # Calculate remaining space for subject (use display_width for CJK)
  prefix_dw = Rcurses.display_width(line_prefix)
  subject_width = available_width - prefix_dw - 1  # -1 for safety
  subject_dw = Rcurses.display_width(subject)
  if subject_width > 0 && subject_dw > subject_width
    subject = truncate_to_width(subject, subject_width - 1) + '…'
    subject_dw = Rcurses.display_width(subject)
  end

  prefix_part = line_prefix
  subject_part = subject.strip
  total_dw = Rcurses.display_width(prefix_part) + Rcurses.display_width(subject_part)
  padding = " " * [available_width - total_dw, 0].max
  finalize_line(msg, selected, prefix_part, subject_part, source_color, padding)
end

#format_poll_interval(seconds) ⇒ Object



7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
# File 'lib/heathrow/ui/application.rb', line 7467

def format_poll_interval(seconds)
  seconds = (seconds || 900).to_i
  return "Polling disabled" if seconds <= 0
  if seconds < 60
    "Poll every #{seconds}s"
  elsif seconds < 3600
    "Poll every #{seconds / 60}m"
  else
    "Poll every #{seconds / 3600}h"
  end
end

#format_source_line(msg, selected) ⇒ Object



1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
# File 'lib/heathrow/ui/application.rb', line 1563

def format_source_line(msg, selected)
  available_width = @panes[:left].w - 2
  available_width -= 2 if @panes[:left].border

  # Health indicator: ✓ or ✗
  health = msg['health_ok'] ? "✓".fg(40) : "✗".fg(196)

  # Source color
  src_color = get_source_color(msg)

  # Poll interval (short form)
  interval = (msg['poll_interval'] || 900).to_i
  poll_str = if interval <= 0 then "off"
             elsif interval < 60 then "#{interval}s"
             elsif interval < 3600 then "#{interval / 60}m"
             else "#{interval / 3600}h"
             end

  # Counts
  unread = msg['unread_count'].to_i
  total = msg['msg_count'].to_i
  count_str = "#{unread}/#{total}"

  # Fixed layout: [✓ ][name 20ch] [poll 3ch] [count right-aligned]
  name_max = 20
  name = msg['subject'].to_s
  name = name.length > name_max ? name[0..name_max - 2] + '…' : name.ljust(name_max)

  poll_col = poll_str.rjust(3)
  count_col = count_str.rjust(12)
  padding_len = [available_width - 2 - name_max - 1 - 3 - 1 - 12, 0].max
  padding = " " * padding_len

  line = "#{name} #{poll_col} #{count_col}#{padding}"

  if selected
    content = "#{name} #{poll_col} #{count_col}"
    health + " " + content.bd.ul.fg(src_color) + padding
  elsif msg['enabled'].to_i == 0
    health + " " + line.fg(240)
  else
    health + " " + name.fg(src_color) + " #{poll_col} #{count_col}#{padding}".fg(245)
  end
end

#forward_messageObject



5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
# File 'lib/heathrow/ui/application.rb', line 5368

def forward_message
  msg = current_message
  return unless msg
  msg = ensure_full_message(msg)
  source_id = msg['source_id']
  
  # Check if source supports sending
  source = @db.get_source_by_id(source_id)
  return unless source
  
  require_relative '../message_composer'
  identity = current_identity(msg)
  composer = MessageComposer.new(msg, identity: identity, address_book: @address_book, editor_args: @editor_args)

  # Show composing status
  @panes[:bottom].text = " Opening editor to forward message...".fg(226)
  @panes[:bottom].refresh

  # Extract attachments BEFORE editor
  orig_attachments = extract_original_attachments(msg)

  # Compose the forward
  composed = composer.compose_forward

  # Rebuild panes after editor (vim clears the screen)
  setup_display
  create_panes
  render_all

  if composed
    # Include original attachments
    composed[:attachments] = orig_attachments if orig_attachments && !orig_attachments.empty?
    finalize_compose(source, composed, "Forward cancelled")
  else
    set_feedback("Forward cancelled", 245, 1)
  end
end

#get_extended_help_textObject



6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
# File 'lib/heathrow/ui/application.rb', line 6814

def get_extended_help_text
  "\#{\"HEATHROW - COMPREHENSIVE DOCUMENTATION\".bd.fg(226)}\n\#{\"=\" * 60}\n\nHeathrow is a unified terminal interface for all your communication sources.\nIt aggregates messages from email, WhatsApp, Telegram, Discord, Reddit, \nRSS feeds, and more into a single, keyboard-driven interface.\n\n\#{\"KEYBOARD SHORTCUTS\".bd.fg(theme[:accent])}\n\n\#{\"Navigation\".fg(11)}\n  j/\u2193        Move down in message list\n  k/\u2191        Move up in message list  \n  h/\u2190        Go back / parent view\n  l/\u2192/Enter  Open message / enter\n  PgDn       Page down (10 messages)\n  PgUp       Page up (10 messages)\n  Home       Go to first message\n  End        Go to last message\n  \n\#{\"Views & Filters\".fg(11)}\n  A          Show all messages\n  N          Show new (unread) messages\n  S          Sources configuration\n  0-9        Custom filtered views\n  Ctrl-f     Edit/create filter for current view\n  K          Kill/delete a numbered view\n  \n\#{\"Message Actions\".fg(11)}\n  R          Toggle read/unread status\n  Space      Collapse/expand thread (threaded view)\n  G          Cycle view mode (flat / threaded / folder-grouped)\n  { / }      Move section up/down (reorder feeds/channels)\n  t          Tag message and move to next\n  T          Tag/untag all messages in view\n  Ctrl+t     Tag by regex (default=all, for batch ops)\n  n          Jump to next unread message\n  p          Jump to previous unread message\n  */-        Toggle star/favorite\n  d          Toggle delete mark\n  r          Reply to message (if supported)\n  g          Reply all / group reply\n  \n\#{\"Source Management\".fg(11)} (in Sources view)\n  a          Add new source\n  e          Edit selected source\n  d          Delete selected source\n  t          Test selected source\n  Space      Enable/disable source\n  Enter      Show messages from source\n  \n\#{\"UI Controls\".fg(11)}\n  w          Cycle left pane width (1-5)\n  Ctrl-b     Cycle border style (none/single/double)\n  D          Cycle date format\n  o          Cycle sort order (newest/oldest/unread)\n  P          Settings popup (theme, format, etc.)\n  r          Refresh all panes\n  ?          Show help (press again for extended help)\n  q          Quit Heathrow\n\n\#{\"AI Assistant\".fg(11)}\n  I          AI assistant (Claude Code integration)\n               d = Draft a reply\n               f = Fix grammar/spelling\n               s = Summarize message\n               t = Translate message\n               a = Ask anything about the message\n\n\#{\"FILTER SYNTAX\".bd.fg(theme[:accent])}\n  \n  Filters support powerful pattern matching:\n  - Comma (,) = AND condition - all must match\n  - Pipe (|) = OR condition - any can match\n  - Combine both for complex filters\n  \n  Examples:\n  - \"error|warning\" = matches error OR warning\n  - \"critical,production\" = matches critical AND production\n  - \"error|warning,production\" = (error OR warning) AND production\n  \n\#{\"SOURCE TYPES\".bd.fg(theme[:accent])}\n  \n\#{\"Email (IMAP)\".fg(39)}\nConnect to any IMAP email server. Supports Gmail, Outlook, Yahoo, etc.\nRequired: server, username, password\n\n\#{\"RSS/Atom Feeds\".fg(226)}\nSubscribe to RSS and Atom feeds. Supports multiple feeds per source.\nRequired: feed URLs\n\n\#{\"WhatsApp\".fg(40)}\nConnect via WhatsApp Web API (requires separate service).\nRequired: API URL\n\n\#{\"Telegram\".fg(51)}\nConnect using Telegram API credentials.\nRequired: API ID, API Hash, phone number\n\n\#{\"Discord\".fg(99)}\nConnect to Discord servers and DMs.\nRequired: Bot or user token\n\n\#{\"Reddit\".fg(202)}\nMonitor subreddits and messages.\nRequired: Client ID, client secret\n\n\#{\"Web Monitor\".fg(208)}\nMonitor web pages for changes.\nRequired: URL, optional CSS selector\n  \n\#{\"CONFIGURATION\".bd.fg(theme[:accent])}\n  \n  Config file: ~/.heathrow/config.yml\n  Database: ~/.heathrow/heathrow.db\n  \n  Settings include:\n  - UI preferences (width, borders, theme)\n  - Polling intervals\n  - Notification settings\n  - Custom key bindings\n  \n\#{\"TIPS & TRICKS\".bd.fg(theme[:accent])}\n  \n  1. Use numbered views (0-9) to organize messages by topic\n  2. Combine source filters with content patterns for precision\n  3. Star important messages for quick access\n  4. Use 'o' to change sort order based on your workflow\n  5. Press 'w' to adjust pane width for your screen size\n  \n  For more information, visit: https://github.com/yourusername/heathrow\n  HELP\nend\n"

#get_favorite_foldersObject

Favorite Folders ==========


4100
4101
4102
4103
4104
4105
4106
4107
4108
# File 'lib/heathrow/ui/application.rb', line 4100

def get_favorite_folders
  stored = nil
  begin
    result = @db.execute("SELECT value FROM settings WHERE key = 'favorite_folders'")
    stored = JSON.parse(result[0]['value']) if result && result[0]
  rescue
  end
  stored || @config.rc('favorite_folders', []).dup
end

#get_folder_shortcutsObject

Quick Folder Shortcuts ==========


4214
4215
4216
4217
4218
4219
4220
4221
4222
# File 'lib/heathrow/ui/application.rb', line 4214

def get_folder_shortcuts
  stored = nil
  begin
    result = @db.execute("SELECT value FROM settings WHERE key = 'folder_shortcuts'")
    stored = JSON.parse(result[0]['value']) if result && result[0]
  rescue
  end
  stored || @config.rc('folder_shortcuts', {}).dup
end

#get_help_textObject



6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
# File 'lib/heathrow/ui/application.rb', line 6949

def get_help_text
  " \#{\"HEATHROW - Communication Hub In The Terminal\".bd.fg(226)}\n \n \#{\"BASIC KEYS\".bd.fg(theme[:accent])}\n   \#{\"?\".fg(10)}       = Show this help text (press again for extended help)\n   \#{\"q\".fg(10)}       = Quit Heathrow\n   \#{\"Q\".fg(10)}       = QUIT (force quit without saving state)\n   \#{\"Ctrl-r\".fg(10)}   = Refresh current view (sync + reload)\n   \#{\"Ctrl-l\".fg(10)}   = Redraw panes (no fetch)\n   \n \#{\"NAVIGATION\".bd.fg(theme[:accent])}\n   \#{\"j/\u2193\".fg(10)}     = Move down in message list (rounds to top)\n   \#{\"k/\u2191\".fg(10)}     = Move up in message list (rounds to bottom)\n   \#{\"h/\u2190\".fg(10)}     = Go back / parent view\n   \#{\"l/\u2192/\u23CE\".fg(10)}   = Open message / enter\n   \#{\"PgDn\".fg(10)}    = Go one page down in message list\n   \#{\"PgUp\".fg(10)}    = Go one page up in message list\n   \#{\"Home\".fg(10)}    = Go to first message\n   \#{\"End\".fg(10)}     = Go to last message\n   \#{\"J\".fg(10)}       = Jump to date (yyyy-mm-dd)\n   \n \#{\"RIGHT PANE SCROLLING\".bd.fg(theme[:accent])}\n   \#{\"S-\u2193\".fg(10)}     = Scroll content down one line\n   \#{\"S-\u2191\".fg(10)}     = Scroll content up one line\n   \#{\"S-PgDn\".fg(10)}  = Scroll content down one page\n   \#{\"S-PgUp\".fg(10)}  = Scroll content up one page\n   \#{\"S-RIGHT\".fg(10)} = Scroll content down one page\n   \#{\"S-LEFT\".fg(10)}  = Scroll content up one page\n   \#{\"TAB\".fg(10)}     = Scroll content down one page\n \n \#{\"VIEWS & FILTERS\".bd.fg(theme[:accent])}\n   \#{\"A\".fg(10)}       = Show all messages\n   \#{\"N\".fg(10)}       = Show new (unread) messages only\n   \#{\"S\".fg(10)}       = Sources configuration and management\n   \#{\"0-9\".fg(10)}     = Custom filtered views (configurable)\n   \#{\"F1-F12\".fg(10)}  = Additional custom views (configurable)\n   \#{\"Ctrl-f\".fg(10)}  = Edit/create filter for current view (0-9, F1-F12)\n   \#{\"K\".fg(10)}       = Kill/delete a view (with confirmation)\n \n \#{\"MESSAGE ACTIONS\".bd.fg(theme[:accent])}\n   \#{\"R\".fg(10)}       = Toggle read/unread status\n   \#{\"M\".fg(10)}       = Mark all messages in view as read\n   \#{\"Space\".fg(10)}   = Collapse/expand thread (threaded view)\n   \#{\"G\".fg(10)}       = Cycle view mode (flat / threaded / folder-grouped)\n   \#{\"{ }\".fg(10)}     = Move section up/down (reorder feeds/channels)\n   \#{\"t\".fg(10)}       = Tag message and move to next\n   \#{\"T\".fg(10)}       = Tag/untag all messages in view\n   \#{\"Ctrl-t\".fg(10)}  = Tag by regex (default=all, for batch ops)\n   \#{\"n\".fg(10)}       = Jump to next unread message\n   \#{\"p\".fg(10)}       = Jump to previous unread message\n   \#{\"x\".fg(10)}       = Open in browser (HTML emails rendered, others open URL)\n   \#{\"*/\u2212\".fg(10)}     = Toggle star/favorite\n   \#{\"d\".fg(10)}       = Toggle delete mark\n   \#{\"<\".fg(10)}       = Purge delete-marked messages\n   \#{\"r\".fg(10)}       = Reply to message\n   \#{\"g\".fg(10)}       = Reply all / group reply\n   \#{\"f\".fg(10)}       = Forward message\n   \#{\"e\".fg(10)}       = Reply with editor (full headers)\n   \#{\"E\".fg(10)}       = Edit message as new (compose from content)\n   \#{\"m\".fg(10)}       = Mail/compose new message\n   \#{\"y\".fg(10)}       = Copy message ID to clipboard (for CC sessions)\n   \n \#{\"SOURCE MANAGEMENT\".bd.fg(theme[:accent])} (in Sources view with 'S')\n   \#{\"a\".fg(10)}       = Add new source\n   \#{\"e\".fg(10)}       = Edit selected source\n   \#{\"d\".fg(10)}       = Delete selected source\n   \#{\"Enter\".fg(10)}   = Show all messages from selected source\n   \#{\"Space\".fg(10)}   = Enable/disable source\n \n \#{\"FOLDER NAVIGATION\".bd.fg(theme[:accent])}\n   \#{\"B\".fg(10)}       = Browse all folders (folder tree)\n   \#{\"F\".fg(10)}       = Browse favorite folders\n   \#{\"+\".fg(10)}       = Add/remove current folder from favorites\n   \#{\"s\".fg(10)}       = Save/file message to folder (s1-s9 for shortcuts)\n   \#{\"sB\".fg(10)}      = Save by browsing all folders\n   \#{\"sF\".fg(10)}      = Save by browsing favorite folders\n   \#{\"s=\".fg(10)}      = Configure save folder shortcuts\n   \#{\"v\".fg(10)}       = View/save/open attachments\n   \#{\"V\".fg(10)}       = Toggle inline image display\n   \#{\"l\".fg(10)}       = Add/remove labels (+label / -label / ? to list)\n   \#{\"/\".fg(10)}       = Full-text search (notmuch)\n\n \#{\"AI ASSISTANT\".bd.fg(theme[:accent])}\n   \#{\"I\".fg(10)}       = AI assistant (Claude Code integration)\n   \#{\"  d\".fg(10)}     = Draft a reply\n   \#{\"  f\".fg(10)}     = Fix grammar/spelling\n   \#{\"  s\".fg(10)}     = Summarize message\n   \#{\"  t\".fg(10)}     = Translate message\n   \#{\"  a\".fg(10)}     = Ask anything about the message\n\n \#{\"UI CONTROLS\".bd.fg(theme[:accent])}\n   \#{\"w\".fg(10)}       = Change left pane width (20% \u2192 60%)\n   \#{\"Ctrl-b\".fg(10)}  = Cycle border style (none/single/double)\n   \#{\"D\".fg(10)}       = Cycle date/time format\n   \#{\"o\".fg(10)}       = Cycle sort order (newest/oldest/unread first)\n   \#{\"i\".fg(10)}       = Invert sort order (toggle reverse)\n   \#{\"Y/C-y\".fg(10)}   = Copy right pane content to clipboard\n   \#{\"P\".fg(10)}       = Settings popup (theme, format, etc.)\n   \#{\"@\".fg(10)}       = Address book (a=add sender, e=edit file)\n\#{custom_bindings_help}\n Press \#{\"?\".fg(10)} again for extended help \u2022 Any other key to continue\n  HELP\nend\n"

#get_source_color(msg) ⇒ Object



1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
# File 'lib/heathrow/ui/application.rb', line 1715

def get_source_color(msg)
  # For sources display, check if we have a custom color first
  if msg['source_color']
    c = parse_color_value(msg['source_color'])
    return c if c
  end

  # Try to get color from cache using source_id or id
  source_id = msg['source_id'] || msg['id']
  if source_id && @source_colors[source_id]
    c = parse_color_value(@source_colors[source_id])
    return c if c
  end
  
  # Fallback to theme-defined colors by source type
  source_type = (msg['source_type'] || msg['plugin_type']).to_s.downcase
  t = theme
  key = :"source_#{source_type == 'email' ? 'maildir' : source_type}"
  t[key] || t[:source_default] || 15
end

#go_firstObject



2481
2482
2483
# File 'lib/heathrow/ui/application.rb', line 2481

def go_first
  navigate { |_| @index = 0 }
end

#go_lastObject



2485
2486
2487
# File 'lib/heathrow/ui/application.rb', line 2485

def go_last
  navigate { |n| @index = n - 1 }
end

#go_to_folderObject

Go to folder via shortcut key (g key in main view)



4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
# File 'lib/heathrow/ui/application.rb', line 4233

def go_to_folder
  shortcuts = get_folder_shortcuts
  # Show shortcuts in right pane
  info = []
  info << "FOLDER SHORTCUTS".bd.fg(226)
  info << "Press a key to jump to folder:".fg(245)
  info << ""
  shortcuts.sort_by { |k, _| k }.each do |key, folder|
    info << "  #{key.ljust(4).fg(10)} → #{folder}".fg(255)
  end
  info << ""
  info << "ESC to cancel".fg(245)
  @panes[:right].text = info.join("\n")
  @panes[:right].refresh

  chr = getchr
  folder = shortcuts[chr]
  if folder
    open_folder(folder)
  else
    render_message_content  # Restore right pane
  end
end

#handle_input_key(chr) ⇒ Object



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
# File 'lib/heathrow/ui/application.rb', line 555

def handle_input_key(chr)
  
  # Handle help mode: scroll keys stay in help, everything else exits
  if @in_help_mode
    case chr
    when 'S-DOWN', 'j', 'DOWN'
      @panes[:right].linedown
      return
    when 'S-UP', 'k', 'UP'
      @panes[:right].lineup
      return
    when 'S-RIGHT', 'TAB', 'PgDOWN', 'S-PgDOWN', ' ', 'SPACE'
      @panes[:right].pagedown
      return
    when 'S-LEFT', 'S-TAB', 'PgUP', 'S-PgUP'
      @panes[:right].pageup
      return
    when 'HOME'
      @panes[:right].top
      return
    when 'END'
      @panes[:right].bottom
      return
    when '?'
      if @showing_help
        show_extended_help
        @showing_help = false
      else
        show_help
      end
      return
    when '', nil
      # Ignore empty/partial escape sequences from held keys
      return
    else
      # Any other key exits help mode
      @in_help_mode = false
      @showing_help = false
      @panes[:right].content_update = true
      render_message_content
    end
  end
  
  # Debug log key presses and state
  
  # Special handling for source view
  if @current_view == 'S'
    case chr
    when 'a'
      if selected_source_has_items?
        add_source_item
      else
        add_new_source
      end
      return
    when 'e'
      edit_selected_source
      return
    when 'd'
      if selected_source_has_items?
        delete_source_item
      else
        delete_selected_source
      end
      return
    when 't'
      test_selected_source
      return
    when ' ', 'SPACE'
      toggle_selected_source
      return
    when 'j', 'DOWN'
      move_down
      render_sources_info  # Update right pane to show new selection
      return
    when 'k', 'UP'
      move_up
      render_sources_info  # Update right pane to show new selection
      return
    when 'ENTER', "\r", "\n"
      # Show messages from selected source
      if @filtered_messages[@index]
        source_id = @filtered_messages[@index]['id']
        show_source_messages(source_id)
      end
      return
    when 'ESC', "\e", 'q'
      @in_source_view = false
      @panes[:right].content_update = true
      switch_to_default_view
      return
    when 'A', 'N', '0'..'9',
         'F1', 'F2', 'F3', 'F4', 'F5', 'F6', 'F7', 'F8', 'F9', 'F10', 'F11', 'F12'
      @in_source_view = false
      @panes[:right].content_update = true
      # Let it fall through to regular handler to switch views
    when 'Y'
      copy_right_pane_to_clipboard
      return
    when 'c'
      pick_source_color
      return
    when 'p'
      set_source_poll_interval
      return
    when 'C-R'
      refresh_all
      show_sources  # Reload source list
      return
    when 'C-L'
      redraw_panes
      return
    when 'w', 'C-B', 'o', 'i', 'D', 'P'
      # Let these fall through to regular handler for UI controls and sorting
    else
      # Don't handle other keys in source view
      return
    end
  end
  
  # Context-sensitive feed/page management in views tied to RSS/web sources
  if (chr == 'a' || chr == 'd') && @current_view != 'S' && !@in_source_view
    source = current_view_item_source
    if source
      if chr == 'a'
        add_source_item_for(source)
      else
        delete_source_item_for(source)
      end
      return
    end
  end

  # Custom keybindings from heathrowrc (checked before built-in keys)
  if @config && (binding = @config.custom_bindings[chr])
    run_custom_binding(binding)
    return
  end

  case chr
  when 'q', 'Q'
    quit
  when '?'
    if @showing_help
      show_extended_help
    else
      show_help
    end
  when 'r'
    reply_to_message
  when 'e'
    reply_to_message(force_editor: true)
  when 'E'
    edit_message_content
  when 'R'
    toggle_read_status
  when 'M'
    mark_all_view_read(force_all: true)
  when 'g'
    reply_all_to_message
  when 'f'
    forward_message
  when 'y'
    copy_message_id
  when 'm'
    compose_new_message
  when 'C-R'  # Ctrl-R: refresh current view (sync its sources + reload)
    refresh_current_view
  when 'C-L'  # Ctrl-L: redraw panes only (no fetch)
    redraw_panes
  when 'j', 'DOWN'
    move_down
  when 'k', 'UP'
    move_up
  when 'h', 'LEFT'
    collapse_current_item
  when 'l', 'RIGHT'
    expand_current_item
  when 'ENTER'
    open_message
  when 'J'
    jump_to_date
  when 'x'
    open_message_external
  when 'X'
    open_in_brrowser
  when 'HOME'
    go_first
  when 'END'
    go_last
  when 'PgDOWN'
    page_down
  when 'PgUP'
    page_up
  when 'L'
    load_more_messages
  when 'w'
    change_width
  when 'Y', 'C-Y'
    copy_right_pane_to_clipboard
  when 'c'
    set_view_top_bg
  when 'C-B'
    cycle_border
  when 'o'
    cycle_sort_order
  when 'i'
    toggle_sort_invert
  when 'D'
    cycle_date_format
  when 'P'
    show_settings_popup
  when 'S-DOWN'
    @panes[:right].linedown
    @panes[:right].content_update = false
  when 'S-UP'
    @panes[:right].lineup
    @panes[:right].content_update = false
  when 'S-RIGHT', 'TAB'
    @panes[:right].pagedown
    @panes[:right].content_update = false
  when 'S-LEFT', 'S-TAB'
    @panes[:right].pageup
    @panes[:right].content_update = false
  when 'A'
    show_all_messages
  when 'N'
    show_new_messages
  when 'S'
    # Set flag BEFORE calling show_sources
    @in_source_view = true
    show_sources
  when 'C-F'
    edit_filter
  when 'K'
    kill_view
  when '0'..'9'
    switch_to_view(chr)
  when 'F1', 'F2', 'F3', 'F4', 'F5', 'F6', 'F7', 'F8', 'F9', 'F10', 'F11', 'F12'
    switch_to_view(chr)
  when '}', 'C-DOWN'
    move_section(1)  # Move section down
  when '{', 'C-UP'
    move_section(-1)  # Move section up
  when ' ', 'SPACE'
    toggle_collapse_expand
  when 'G'
    # Cycle: flat → threaded → folder-grouped
    cycle_view_mode
  when 'u', 'U'
    # Unsee current message (remove from browsed set)
    unsee_current_message
  when 'S-SPACE'
    # Mark all browsed messages as permanently read
    mark_browsed_as_read
  when 't'
    toggle_tag
  when 'T'
    tag_all_toggle
  when 'C-T'
    tag_by_regex
  when 'n'
    jump_to_next_unread
  when 'p'
    jump_to_prev_unread
  when '*', '-'
    toggle_star
  when 'd'
    toggle_delete_mark
  when '<'
    purge_deleted
  when '/'
    notmuch_search
  when 'B'
    show_folder_browser
  when 'F'
    show_favorites_browser
  when '+'
    toggle_favorite_folder
  when 's'
    file_message
  when 'l'
    label_message
  when 'v'
    view_attachments
  when 'Z'
    open_in_timely
  when 'I'
    ai_assistant
  when 'V'
    toggle_inline_image
  when '@'
    address_book_menu
  when 'ESC', "\e"
    if @showing_image
      clear_inline_image
      @panes[:right].content_update = true
      render_message_content
    end
  end
end

#header_message?(msg) ⇒ Boolean



209
210
211
# File 'lib/heathrow/ui/application.rb', line 209

def header_message?(msg)
  msg['is_header'] || msg['is_channel_header'] || msg['is_thread_header'] || msg['is_dm_header']
end

#html_to_text(html, width = 80) ⇒ Object



8360
8361
8362
8363
8364
8365
8366
8367
8368
8369
8370
8371
8372
8373
8374
8375
8376
8377
8378
8379
8380
8381
8382
8383
8384
8385
8386
8387
8388
8389
8390
8391
8392
# File 'lib/heathrow/ui/application.rb', line 8360

def html_to_text(html, width = 80)
  return nil unless html && !html.strip.empty?
  # Override charset to UTF-8 (DB content is always UTF-8, but HTML may declare Windows-1252 etc.)
  fixed = html.gsub(/charset\s*=\s*"?[^";\s>]+/i, 'charset="UTF-8"')
  text = IO.popen(['w3m', '-T', 'text/html', '-dump', '-cols', width.to_s], 'r+') do |io|
    io.write(fixed)
    io.close_write
    io.read
  end
  return nil unless text

  # Extract links from HTML that w3m hides (URL differs from link text)
  links = []
  html.scan(/<a\s[^>]*href\s*=\s*["']([^"']+)["'][^>]*>(.*?)<\/a>/im) do |url, link_text|
    clean_text = link_text.gsub(/<[^>]+>/, '').strip
    next if url.start_with?('mailto:') || url.start_with?('#') || url.start_with?('cid:')
    next if clean_text.empty?
    next if clean_text == url || text.include?(url)
    links << [clean_text, url]
  end
  links.uniq! { |_, url| url }

  if links.any?
    text += "\n\nLinks:\n"
    links.each_with_index do |(label, url), i|
      text += "  [#{i + 1}] #{label}: #{url}\n"
    end
  end

  text
rescue => e
  nil  # Fall back to plain text content
end

#human_size(bytes) ⇒ Object



8581
8582
8583
8584
8585
8586
8587
# File 'lib/heathrow/ui/application.rb', line 8581

def human_size(bytes)
  return '0 B' unless bytes && bytes > 0
  units = ['B', 'KB', 'MB', 'GB']
  exp = (Math.log(bytes) / Math.log(1024)).to_i
  exp = units.length - 1 if exp >= units.length
  "%.1f %s" % [bytes.to_f / (1024 ** exp), units[exp]]
end

#image_urls_from_attachments(msg) ⇒ Object

Extract image URLs from HTML content Extract image URLs from message attachments (chat sources)



8201
8202
8203
8204
8205
8206
8207
8208
8209
8210
8211
8212
8213
8214
8215
8216
8217
# File 'lib/heathrow/ui/application.rb', line 8201

def image_urls_from_attachments(msg)
  raw = msg['attachments']
  return [] unless raw
  atts = raw.is_a?(String) ? (JSON.parse(raw) rescue []) : raw
  return [] unless atts.is_a?(Array)

  atts.filter_map do |att|
    url = att['url'] || att['proxy_url']
    next unless url && url.start_with?('http')
    ctype = (att['content_type'] || '').downcase
    # Include if content_type is image, or filename looks like an image
    fname = (att['filename'] || att['name'] || '').downcase
    if ctype.start_with?('image') || fname =~ /\.(jpe?g|png|gif|webp|bmp|svg)$/i
      url
    end
  end
end

#init_termpixObject

Convert HTML to readable text via w3m Initialize Termpix for inline image display



8187
8188
8189
8190
8191
8192
8193
8194
8195
8196
8197
# File 'lib/heathrow/ui/application.rb', line 8187

def init_termpix
  return @termpix if defined?(@termpix)
  begin
    require 'termpix'
    @termpix = Termpix::Display.new
    @termpix = nil unless @termpix.supported?
  rescue LoadError
    @termpix = nil
  end
  @termpix
end

#invalidate_countsObject



213
214
215
216
217
# File 'lib/heathrow/ui/application.rb', line 213

def invalidate_counts
  @cached_unread = nil
  @cached_starred = nil
  @cached_total = nil
end

#is_unread_view?Boolean

Check if current view is an unread filter



317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
# File 'lib/heathrow/ui/application.rb', line 317

def is_unread_view?
  # Check key binding
  return true if @current_view == 'N'

  # Check if custom view has unread filter
  if @views[@current_view]
    view = @views[@current_view]
    if view && view[:filters]
      filters = view[:filters]
      # Check if filtering by read = false
      return true if filters['read'] == false || filters[:read] == false
      # Check if using rules with read field
      if filters['rules'].is_a?(Array)
        return filters['rules'].any? { |rule| rule['field'] == 'read' && rule['value'] == false }
      end
    end
  end

  false
end

#jump_to_dateObject



2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
# File 'lib/heathrow/ui/application.rb', line 2489

def jump_to_date
  input = bottom_ask("Jump to date (yyyy-mm-dd): ", Time.now.strftime('%Y-%m-%d'))
  return unless input && input =~ /\d{4}-\d{2}-\d{2}/

  target_ts = Time.parse("#{input} 00:00:00").to_i rescue nil
  return set_feedback("Invalid date", 196, 2) unless target_ts

  # Load messages around this date if needed
  # Find how many messages are newer than this date
  count_newer = @db.db.get_first_value(
    "SELECT COUNT(*) FROM messages WHERE timestamp >= ? AND (archived = 0 OR archived IS NULL)",
    [target_ts]
  ) || 0

  if count_newer > @load_limit.to_i
    @load_limit = count_newer + 100
    # Reload with expanded limit
    if @current_folder
      light_cols = "id, source_id, external_id, thread_id, parent_id, sender, sender_name, recipients, subject, substr(content, 1, 200) as content, timestamp, received_at, read AS is_read, starred AS is_starred, archived, labels, metadata, attachments, folder, replied"
      @filtered_messages = @db.execute(
        "SELECT #{light_cols} FROM messages WHERE folder = ? ORDER BY timestamp DESC LIMIT ?",
        @current_folder, @load_limit
      )
    elsif @current_view == 'A'
      @filtered_messages = @db.get_messages({}, @load_limit, 0, light: true)
    elsif @current_view == 'N'
      @filtered_messages = @db.get_messages({is_read: false}, @load_limit, 0, light: true)
    elsif @views[@current_view]
      apply_view_filters_with_limit(@views[@current_view], @load_limit)
    end
    sort_messages
  end

  # Find the first message on or before this date
  idx = @filtered_messages.index { |m| m['timestamp'].to_i <= target_ts }
  if idx
    @index = idx
    set_feedback("Jumped to #{input} (#{@filtered_messages.size} messages loaded)", 156, 2)
  else
    @index = @filtered_messages.size - 1
    set_feedback("No messages found at #{input}, showing oldest", 226, 2)
  end
  render_all
end

#jump_to_next_unreadObject

Jump to next unread message (wraps around)



2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
# File 'lib/heathrow/ui/application.rb', line 2848

def jump_to_next_unread
  display = if @show_threaded && @display_messages && !@display_messages.empty?
              @display_messages
            else
              @filtered_messages
            end
  return set_feedback("No messages", 245, 2) if display.empty?

  # Search visible list for next unread after current position
  display.size.times do |i|
    idx = (@index + 1 + i) % display.size
    msg = display[idx]
    next unless msg
    next if header_message?(msg)
    if msg['is_read'].to_i == 0
      @index = idx
      track_browsed_message
      render_all
      return
    end
  end

  # In threaded view, try uncollapsing to find hidden unread
  if @show_threaded && @organizer
    # Find all unread messages in the raw list, try each one starting after current position
    unread_msgs = @filtered_messages.select { |m| m['is_read'].to_i == 0 && m['id'] }
    unread_msgs.each do |unread|
      uncollapse_for_message(unread)
    end
    if unread_msgs.any?
      # Re-render to rebuild display_messages with uncollapsed sections
      organize_current_messages(true)
      render_message_list_threaded
      new_display = @display_messages || @filtered_messages
      # Find the first visible unread after current position
      new_display.size.times do |i|
        idx = (@index + 1 + i) % new_display.size
        m = new_display[idx]
        next unless m && m['id'] && m['is_read'].to_i == 0
        next if header_message?(m)
        @index = idx
        track_browsed_message
        render_all
        return
      end
    end
  end

  set_feedback("No unread messages in this view", 208, 2)
end

#jump_to_prev_unreadObject

Jump to previous unread message (wraps around)



2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
# File 'lib/heathrow/ui/application.rb', line 2900

def jump_to_prev_unread
  display = (@show_threaded && @display_messages && !@display_messages.empty?) ? @display_messages : @filtered_messages
  size = display.size
  return if size == 0

  size.times do |i|
    idx = (@index - 1 - i) % size
    msg = display[idx]
    next unless msg
    next if header_message?(msg)
    if msg['is_read'].to_i == 0
      @index = idx
      track_browsed_message
      render_all
      return
    end
  end

  # Try uncollapsing to find hidden unread (search backwards)
  if @show_threaded && @organizer
    unread_msgs = @filtered_messages.select { |m| m['is_read'].to_i == 0 && m['id'] }
    unread_msgs.each do |unread|
      uncollapse_for_message(unread)
    end
    if unread_msgs.any?
      organize_current_messages(true)
      render_message_list_threaded
      new_display = @display_messages || @filtered_messages
      new_size = new_display.size
      new_size.times do |i|
        idx = (@index - 1 - i) % new_size
        m = new_display[idx]
        next unless m && m['id'] && m['is_read'].to_i == 0
        next if header_message?(m)
        @index = idx
        track_browsed_message
        render_all
        return
      end
    end
  end

  set_feedback("No unread messages in this view", 208, 2)
end

#kill_viewObject



7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
# File 'lib/heathrow/ui/application.rb', line 7566

def kill_view
  # Ask which view to kill
  @panes[:bottom].clear
  view_key = bottom_ask("Kill which view (1-9, F1-F12)? ", "")

  return if view_key.nil? || view_key.empty?
  # Accept 1-9 or F1-F12
  return unless view_key.match?(/^[1-9]$/) || view_key.match?(/^F\d{1,2}$/i)
  view_key = view_key.upcase if view_key =~ /^f/i  # Normalize F-keys

  view = @views[view_key]

  if view.nil?
    @panes[:bottom].text = " View #{view_key} doesn't exist".fg(196)
    @panes[:bottom].refresh
    sleep(1)
    render_bottom_bar
    return
  end

  # Confirm deletion
  @panes[:bottom].clear
  confirm = bottom_ask("Kill view '#{view[:name]}'? (y/n) ", "")

  if confirm && confirm.downcase == 'y'
    @db.delete_view(view[:id]) if view[:id]
    @views.delete(view_key)

    @panes[:bottom].text = " View #{view_key} killed".fg(40)
    @panes[:bottom].refresh
    sleep(1)

    if @current_view == view_key
      show_all_messages
    else
      render_bottom_bar
    end
  else
    render_bottom_bar
  end
end

#label_messageObject

── Label management (l key) ── Add or remove labels on the current message or all tagged messages. Labels are stored as a JSON array. A message can have many labels. Views can filter on labels: { field: "label", op: "like", value: "MyLabel" }



4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
# File 'lib/heathrow/ui/application.rb', line 4609

def label_message
  tagged_hint = @tagged_messages.size > 0 ? " (#{@tagged_messages.size} tagged)" : ""
  action = bottom_ask("Label#{tagged_hint} (+add / -remove / ? to list): ", '+')
  return if action.nil?

  if action.strip == '?'
    show_all_labels
    return
  end

  adding = !action.start_with?('-')
  label_name = action.sub(/^[+\-]\s*/, '').strip
  return if label_name.empty?

  # Collect messages to label
  msgs = if @tagged_messages.size > 0
           @filtered_messages.select { |m| m['id'] && @tagged_messages.include?(m['id']) }
         else
           msg = current_message
           return unless msg && !msg['is_header'] && !msg['is_channel_header'] && !msg['is_thread_header']
           [msg]
         end
  return if msgs.empty?

  count = 0
  msgs.each do |msg|
    labels = msg['labels']
    labels = JSON.parse(labels) if labels.is_a?(String) rescue []
    labels = [] unless labels.is_a?(Array)

    if adding
      next if labels.include?(label_name)
      labels << label_name
    else
      next unless labels.include?(label_name)
      labels.delete(label_name)
    end

    @db.execute("UPDATE messages SET labels = ? WHERE id = ?", labels.to_json, msg['id'])
    msg['labels'] = labels
    count += 1
  end

  @tagged_messages.clear if @tagged_messages.size > 0

  verb = adding ? "Added" : "Removed"
  set_feedback("#{verb} label '#{label_name}' on #{count} message#{count > 1 ? 's' : ''}", 156, 3)
  render_all
end

#load_mail_file(maildir_file) ⇒ Object



3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
# File 'lib/heathrow/ui/application.rb', line 3382

def load_mail_file(maildir_file)
  require 'mail'
  old_stderr = $stderr.dup
  $stderr.reopen(File.open(File::NULL, 'w'))
  mail = Mail.read(maildir_file)
  $stderr.reopen(old_stderr)
  old_stderr.close
  mail
rescue => e
  set_feedback("Error reading mail: #{e.message}", 196, 2)
  nil
end

#load_more_messagesObject



2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
# File 'lib/heathrow/ui/application.rb', line 2338

def load_more_messages
  return unless @load_limit
  # Remember current message so we can restore position after reload
  cur = current_message
  cur_id = cur['id'] if cur
  old_count = @filtered_messages.size
  @load_limit += 200

  if @current_folder
    light_cols = "id, source_id, external_id, thread_id, parent_id, sender, sender_name, recipients, subject, substr(content, 1, 200) as content, timestamp, received_at, read AS is_read, starred AS is_starred, archived, labels, metadata, attachments, folder, replied"
    results = @db.execute(
      "SELECT #{light_cols} FROM messages WHERE folder = ? ORDER BY timestamp DESC LIMIT ?",
      @current_folder, @load_limit
    )
    @filtered_messages = results
  elsif @current_view == 'A'
    @filtered_messages = @db.get_messages({}, @load_limit, 0, light: true)
  elsif @current_view == 'N'
    @filtered_messages = @db.get_messages({ read: false }, @load_limit, 0, light: true)
  elsif @views[@current_view]
    view = @views[@current_view]
    apply_view_filters_with_limit(view, @load_limit)
  end

  sort_messages
  new_count = @filtered_messages.size
  return if new_count <= old_count

  # In threaded mode, set pending restore so the threaded rebuild finds our position
  if @show_threaded && cur_id
    @pending_restore_id = cur_id
  end

  # Force threaded view to rebuild organizer with new messages
  if @show_threaded
    organize_current_messages(true)
  end

  set_feedback("Loaded #{new_count} messages (+#{new_count - old_count})", 156, 2)
  render_message_list
  render_top_bar
end

#load_source_colorsObject



1697
1698
1699
1700
1701
1702
1703
1704
1705
# File 'lib/heathrow/ui/application.rb', line 1697

def load_source_colors
  # Load all source colors into cache
  @source_colors = {}
  sources = @db.get_sources(false)
  
  sources.each do |source|
    @source_colors[source['id']] = source['color'] if source['color']
  end
end

#load_viewsObject



8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
# File 'lib/heathrow/ui/application.rb', line 8095

def load_views
  # Seed views from heathrowrc (INSERT OR IGNORE, won't overwrite user edits)
  @config.custom_views.each do |cv|
    now = Time.now.to_i
    filters_json = cv[:filters].is_a?(String) ? cv[:filters] : cv[:filters].to_json
    @db.execute(
      "INSERT OR IGNORE INTO views (name, key_binding, filters, sort_order, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?)",
      [cv[:name], cv[:key], filters_json, cv[:sort_order], now, now]
    )
  end

  # Load all views from database, keyed by key_binding string
  db_views = @db.get_all_views
  db_views.each do |view|
    key = view['key_binding'] || view['id'].to_s
    @views[key] = {
      id: view['id'],
      name: view['name'],
      filters: view['filters'],
      sort_order: view['sort_order'],
      key_binding: key
    }
  end
end

#mailcap_command(mime_type, file_path) ⇒ Object



3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
# File 'lib/heathrow/ui/application.rb', line 3395

def mailcap_command(mime_type, file_path)
  escaped = Shellwords.escape(file_path)
  mailcap_files = [File.expand_path('~/.mailcap'), '/etc/mailcap']
  mailcap_files.each do |mc|
    next unless File.exist?(mc)
    File.foreach(mc) do |line|
      line = line.strip
      next if line.empty? || line.start_with?('#')
      fields = line.split(';').map(&:strip)
      next if fields.size < 2
      next if fields.any? { |f| f.strip == 'copiousoutput' }
      if fields[0].casecmp?(mime_type)
        cmd = fields[1].gsub("'%s'", escaped).gsub('%s', escaped)
        return cmd
      end
    end
  end
  "xdg-open #{escaped}"
end

#mark_all_view_read(force_all: false) ⇒ Object

Mark all messages in the current view as read



3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
# File 'lib/heathrow/ui/application.rb', line 3512

def mark_all_view_read(force_all: false)
  # In threaded view on a section header: mark just that group (unless force_all)
  if !force_all && @show_threaded && !@display_messages.empty?
    msg = current_message
    group_msgs = find_current_group_messages(msg)
    if group_msgs
      count = mark_messages_read(group_msgs)
      group_name = msg['subject'] || msg['channel_name'] || 'group'
      set_feedback("Marked #{count} in #{group_name} as read", 156, 3)
      render_top_bar
      render_message_list
      return
    end
  end

  # Bulk DB update for All View or folder views (covers all messages, not just loaded subset)
  if @current_view == 'A' && !@current_folder
    rows = @db.mark_all_as_read
  elsif @current_folder
    rows = @db.mark_all_as_read(folder: @current_folder)
  else
    rows = nil
  end

  organized_sections = (@show_threaded && @organizer) ? @organizer.get_organized_view(@sort_order, @sort_inverted) : nil

  if rows
    # Sync maildir flags for all affected messages
    count = rows.size
    rows.each do |row|
       = row['metadata']
       = JSON.parse() if .is_a?(String)
      next unless .is_a?(Hash) && ['maildir_file']
      sync_maildir_flag({'metadata' => , 'id' => row['id']}, 'S', true)
    end
    # Update in-memory message lists
    [@filtered_messages, @display_messages].each do |list|
      next unless list
      list.each { |m| m['is_read'] = 1 if m['id'] && m['is_read'].to_i == 0 }
    end
    if organized_sections
      organized_sections.each do |section|
        next unless section[:messages]
        section[:messages].each { |m| m['is_read'] = 1 if m['is_read'].to_i == 0 }
      end
    end
  else
    # Custom views: mark loaded messages (subset)
    msgs = if @show_threaded && !@display_messages.empty?
             @display_messages
           else
             @filtered_messages
           end
    return if msgs.nil? || msgs.empty?
    count = mark_messages_read(msgs)
    # Also mark messages inside collapsed sections
    if organized_sections
      organized_sections.each do |section|
        next unless section[:messages]
        count += mark_messages_read(section[:messages])
      end
    end
  end

  invalidate_counts
  set_feedback("Marked #{count} messages as read", 156, 3)
  render_top_bar
  render_message_list
end

#mark_browsed_as_readObject

Mark all browsed messages as permanently read



291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
# File 'lib/heathrow/ui/application.rb', line 291

def mark_browsed_as_read
  count = @browsed_message_ids.size
  return if count == 0

  msg_by_id = @filtered_messages.each_with_object({}) { |m, h| h[m['id']] = m }
  @browsed_message_ids.each do |msg_id|
    @db.mark_as_read(msg_id)
    msg = msg_by_id[msg_id]
    msg['is_read'] = 1 if msg
  end

  @browsed_message_ids.clear
  invalidate_counts
  set_feedback("Marked #{count} browsed messages as read", 156, 3)

  # Remove from view if in unread view
  if is_unread_view?
    @filtered_messages.select! { |m| m['is_read'].to_i == 0 }
    @index = 0
    reset_threading
  end

  render_all
end

#mark_current_message_as_readObject



3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
# File 'lib/heathrow/ui/application.rb', line 3421

def mark_current_message_as_read
  msg = current_message
  return unless msg
  return if msg['is_header']  # Don't mark headers
  return if msg['is_channel_header'] || msg['is_thread_header']  # Don't mark synthetic headers
  return unless msg['id'] && !msg['id'].to_s.start_with?('header_')
  
  # Only mark as read if currently unread
  if msg['is_read'].to_i == 0
    success = @db.mark_as_read(msg['id'])
    if success
      msg['is_read'] = 1
      sync_maildir_flag(msg, 'S', true)

      # Re-sort if sorting by unread
      if @sort_order == 'unread'
        sort_messages
        # Reset threading to reorganize with new unread counts (preserve collapsed state)
        reset_threading(true)
      end
      
      # Update displays if UI is initialized
      if @panes && @w
        render_top_bar  # Update unread count
        render_message_list  # Update the list to remove background color
      end
    end
  end
end

#mark_message_read(msg) ⇒ Object

Mark a single message as read in DB, in-memory, and on disk



253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
# File 'lib/heathrow/ui/application.rb', line 253

def mark_message_read(msg)
  return unless msg && msg['id']
  return if msg['is_read'].to_i == 1

  @db.mark_as_read(msg['id'])
  msg['is_read'] = 1
  invalidate_counts
  sync_maildir_flag(msg, 'S', true)

  # Also update any other references to this message in filtered/display lists
  msg_id = msg['id']
  [@filtered_messages, @display_messages].each do |list|
    next unless list
    list.each do |m|
      next unless m && m['id'] == msg_id && m.object_id != msg.object_id
      m['is_read'] = 1
    end
  end
end

#mark_messages_read(msgs) ⇒ Object

Mark a list of messages as read, skipping headers and already-read



3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
# File 'lib/heathrow/ui/application.rb', line 3584

def mark_messages_read(msgs)
  count = 0
  msgs.each do |msg|
    next if header_message?(msg)
    next if msg['is_read'].to_i == 1
    next unless msg['id']
    @db.mark_as_read(msg['id'])
    msg['is_read'] = 1
    sync_maildir_flag(msg, 'S', true)
    count += 1
  end
  count
end

#message_countObject

Get the current message count (threaded or flat view)



225
226
227
# File 'lib/heathrow/ui/application.rb', line 225

def message_count
  filtered_messages_size
end

#message_has_html?(msg) ⇒ Boolean



3010
3011
3012
3013
3014
# File 'lib/heathrow/ui/application.rb', line 3010

def message_has_html?(msg)
  return false unless msg
  (msg['html_content'] && !msg['html_content'].to_s.strip.empty?) ||
    (msg['content'] && msg['content'] =~ /\A\s*<(!DOCTYPE|html|head|body)\b/i)
end

#move_downObject

Navigation methods



2465
2466
2467
# File 'lib/heathrow/ui/application.rb', line 2465

def move_down
  navigate { |n| @index = (@index + 1) % n }
end

#move_upObject



2469
2470
2471
# File 'lib/heathrow/ui/application.rb', line 2469

def move_up
  navigate { |n| @index = @index == 0 ? n - 1 : @index - 1 }
end

Shared navigation: update index, then re-render

Yields:

  • (msg_count)


2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
# File 'lib/heathrow/ui/application.rb', line 2309

def navigate
  clear_inline_image if @showing_image
  @panes[:right].content_update = true
  msg_count = message_count
  return if msg_count == 0
  # Flush read mark for the message we're LEAVING before changing index
  flush_pending_read
  yield msg_count
  # Auto-load more when near the end (95% threshold)
  check_load_more
  # Track the message we just arrived at
  track_browsed_message
  render_message_list
  render_top_bar
  render_message_content
  render_bottom_bar
end

#notmuch_searchObject

Notmuch full-text search



4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
# File 'lib/heathrow/ui/application.rb', line 4974

def notmuch_search
  require_relative '../notmuch'
  has_notmuch = Heathrow::Notmuch.available?

  # Source picker: let user scope the search
  sources = @db.get_sources(true)  # enabled only
  scope_hint = sources.each_with_index.map { |s, i| "#{i + 1}:#{s['name']}" }.join(' ')
  scope = bottom_ask("Search in (Enter=all, #{scope_hint}): ", "")
  return if scope == 'ESC'

  selected_source_ids = nil
  scope_label = "all"
  if scope && !scope.strip.empty?
    # Parse source selection (comma-separated numbers or name fragment)
    selected = []
    scope.split(',').each do |part|
      part = part.strip
      if part =~ /^\d+$/
        idx = part.to_i - 1
        selected << sources[idx] if idx >= 0 && idx < sources.size
      else
        # Name fragment match
        sources.each { |s| selected << s if s['name'].downcase.include?(part.downcase) }
      end
    end
    if selected.any?
      selected_source_ids = selected.map { |s| s['id'] }
      scope_label = selected.map { |s| s['name'] }.join(', ')
    end
  end

  query = bottom_ask("Search#{scope_label != 'all' ? " [#{scope_label}]" : ''}: ", "")
  return if query.nil? || query.strip.empty?

  @panes[:bottom].text = " Searching...".fg(226)
  @panes[:bottom].refresh

  results = []

  # Use notmuch for Maildir sources (fast indexed search)
  if has_notmuch && (selected_source_ids.nil? || sources.any? { |s| selected_source_ids&.include?(s['id']) && s['plugin_type'] == 'maildir' })
    files = Heathrow::Notmuch.search_files(query)
    unless files.empty?
      basenames = files.map { |f| File.basename(f) }
      basenames.each_slice(100) do |batch|
        ph = batch.map { '?' }.join(',')
        sql = "SELECT * FROM messages WHERE external_id IN (#{ph})"
        params = batch.dup
        if selected_source_ids
          sid_ph = selected_source_ids.map { '?' }.join(',')
          sql += " AND source_id IN (#{sid_ph})"
          params += selected_source_ids
        end
        rows = @db.execute(sql, *params)
        rows.each do |row|
          row['recipients'] = JSON.parse(row['recipients']) if row['recipients'].is_a?(String)
          row['metadata'] = JSON.parse(row['metadata']) if row['metadata'].is_a?(String)
          row['labels'] = JSON.parse(row['labels']) if row['labels'].is_a?(String)
          row['attachments'] = JSON.parse(row['attachments']) if row['attachments'].is_a?(String)
        end
        results.concat(rows)
      end
    end
  end

  # DB search for non-Maildir sources (or if notmuch unavailable)
  non_maildir_ids = if selected_source_ids
    selected_source_ids.select { |sid| sources.find { |s| s['id'] == sid && s['plugin_type'] != 'maildir' } }
  else
    sources.select { |s| s['plugin_type'] != 'maildir' }.map { |s| s['id'] }
  end
  if non_maildir_ids.any?
    db_filters = { search: query, source_ids: non_maildir_ids }
    db_results = @db.get_messages(db_filters, 500, 0, light: false)
    results.concat(db_results)
  end

  if results.empty?
    set_feedback("No results for: #{query}", 226, 3)
    return
  end

  # Show results as a temporary view
  @current_view = 'A'
  @in_source_view = false
  @panes[:right].content_update = true
  @current_source_filter = "Search: #{query}#{scope_label != 'all' ? " [#{scope_label}]" : ''}"
  @filtered_messages = results
  sort_messages
  @index = 0
  reset_threading
  set_feedback("#{results.size} results for: #{query}", 156, 0)
  render_all
end

#open_attachments(maildir_file, attachments, indices) ⇒ Object



3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
# File 'lib/heathrow/ui/application.rb', line 3325

def open_attachments(maildir_file, attachments, indices)
  mail = load_mail_file(maildir_file)
  return unless mail
  tmpdir = File.join(Dir.tmpdir, 'heathrow-att')
  FileUtils.mkdir_p(tmpdir)
  opened = 0
  indices.each do |i|
    att = attachments[i]
    mail_att = find_mail_attachment(mail, att)
    next unless mail_att
    tmp_path = File.join(tmpdir, mail_att.filename)
    File.open(tmp_path, 'wb') { |f| f.write(mail_att.body.decoded) }
    mime = att['content_type'] || att['mime_type'] || 'application/octet-stream'
    mime = mime.split(';').first.strip
    cmd = mailcap_command(mime, tmp_path)
    pid = Process.spawn(cmd, [:out, :err] => '/dev/null')
    Process.detach(pid)
    opened += 1
  end
  set_feedback("Opened #{opened} attachment#{opened != 1 ? 's' : ''}", 156, 2)
end

#open_folder(folder_name) ⇒ Object

Open a specific folder and show its messages



4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
# File 'lib/heathrow/ui/application.rb', line 4067

def open_folder(folder_name)
  @in_folder_browser = false
  @in_favorites_browser = false
  @current_folder = folder_name
  @current_view = 'A'
  @in_source_view = false
  @panes[:right].content_update = true
  @current_source_filter = "Folder: #{folder_name}"

  # Reset threading state so old @display_messages don't persist
  reset_threading

  # Show progress while loading
  @panes[:bottom].text = " Loading #{folder_name}...".fg(226)
  @panes[:bottom].refresh

  # Light query with limit (full content loaded lazily when viewing)
  @load_limit = 200
  light_cols = "id, source_id, external_id, thread_id, parent_id, sender, sender_name, recipients, subject, substr(content, 1, 200) as content, timestamp, received_at, read AS is_read, starred AS is_starred, archived, labels, metadata, attachments, folder, replied"
  results = @db.execute(
    "SELECT #{light_cols} FROM messages WHERE folder = ? ORDER BY timestamp DESC LIMIT ?",
    folder_name, @load_limit
  )

  @filtered_messages = results
  sort_messages
  @index = 0
  set_feedback("Folder: #{folder_name} (#{results.size} messages)", 156, 3)
  render_all
end

#open_in_brrowserObject



3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
# File 'lib/heathrow/ui/application.rb', line 3187

def open_in_brrowser
  unless system("which brrowser > /dev/null 2>&1")
    set_feedback("brrowser not installed. See https://github.com/isene/brrowser", 196, 4)
    return
  end

  msg = current_message
  return unless msg
  return if header_message?(msg)
  msg = ensure_full_message(msg)

  # Build URL from message (same logic as open_message_external)
  url = nil
  if message_has_html?(msg)
    html = msg['html_content']
    html = msg['content'] if !html || html.to_s.strip.empty?
    tmpfile = "/tmp/heathrow-view-#{msg['id']}.html"
    File.write(tmpfile, html)
    url = "file://#{tmpfile}"
  else
    meta = msg['metadata']
    if meta
      parsed = meta.is_a?(Hash) ? meta : (JSON.parse(meta) rescue {})
      url = parsed['link'] || parsed['url']
    end
    url ||= msg['url'] || msg['link'] || msg['permalink']
    url ||= msg['external_id'] if msg['external_id']&.start_with?('http')
  end

  unless url
    set_feedback("No URL or HTML content to open", 226, 3)
    return
  end

  Rcurses.clear_screen
  system("brrowser '#{url}'")
  setup_display
  create_panes
  render_all
end

#open_in_timelyObject



3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
# File 'lib/heathrow/ui/application.rb', line 3016

def open_in_timely
  msg = current_message
  return unless msg
  msg = ensure_full_message(msg)

  # Try to find a date from calendar data or message timestamp
  timely_home = File.expand_path('~/.timely')
  return set_feedback("Timely not configured (~/.timely missing)", 196, 3) unless File.directory?(timely_home)

  # Check for ICS attachment or inline calendar data
  date_str = nil
  meta = msg['metadata']
  meta = JSON.parse(meta) if meta.is_a?(String) rescue nil
  file = meta['maildir_file'] if meta.is_a?(Hash)

  if file && File.exist?(file)
    begin
      require 'mail'
      mail = Mail.read(file)
      if mail.multipart?
        mail.parts.each do |part|
          ct = (part.content_type || '').downcase
          if ct.include?('calendar') || ct.include?('ics')
            ics = part.decoded
            vevent = ics[/BEGIN:VEVENT(.*?)END:VEVENT/m, 1]
            if vevent
              vevent = vevent.gsub(/\r?\n[ \t]/, '')
              if vevent =~ /^DTSTART;TZID=[^:]*:(\d{8})/i ||
                 vevent =~ /^DTSTART:(\d{8})/i ||
                 vevent =~ /^DTSTART;VALUE=DATE:(\d{8})/i
                d = $1
                date_str = "#{d[0,4]}-#{d[4,2]}-#{d[6,2]}"
              end
            end
            break
          end
        end
      end
    rescue => e
      # Fall through to timestamp
    end
  end

  # Fallback: use message timestamp
  unless date_str
    ts = msg['timestamp'].to_i
    date_str = Time.at(ts).strftime('%Y-%m-%d') if ts > 0
  end

  return set_feedback("Could not determine date for Timely", 245, 2) unless date_str

  # Write goto file for Timely
  File.write(File.join(timely_home, 'goto'), date_str)

  # Also copy ICS to incoming if it has calendar data
  if file && File.exist?(file)
    begin
      incoming = File.join(timely_home, 'incoming')
      FileUtils.mkdir_p(incoming)
      require 'mail'
      mail = Mail.read(file)
      mail.parts.each do |part|
        ct = (part.content_type || '').downcase
        if ct.include?('calendar') || ct.include?('ics')
          ics_file = File.join(incoming, "heathrow_#{msg['id']}.ics")
          File.write(ics_file, part.decoded) unless File.exist?(ics_file)
          break
        end
      end
    rescue => e
      # Non-fatal
    end
  end

  set_feedback("Sent to Timely: #{date_str}", 156, 0)
end

#open_messageObject



2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
# File 'lib/heathrow/ui/application.rb', line 2995

def open_message
  msg = current_message
  return unless msg
  
  # Mark as read
  if msg['is_read'] == 0 || !msg['is_read']
    @db.mark_as_read(msg['id'])
    msg['is_read'] = 1
    render_message_list
  end
  
  # Show full content in right pane
  render_message_content
end

#open_message_externalObject



3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
# File 'lib/heathrow/ui/application.rb', line 3093

def open_message_external
  msg = current_message
  return unless msg
  return if header_message?(msg)
  msg = ensure_full_message(msg)

  # Mark as read
  if msg['is_read'].to_i == 0
    @db.mark_as_read(msg['id'])
    msg['is_read'] = 1
    render_message_list
  end

  # For messages with HTML content, open directly in browser
  if message_has_html?(msg)
    html = msg['html_content']
    html = msg['content'] if !html || html.to_s.strip.empty?
    tmpfile = "/tmp/heathrow-view-#{msg['id']}.html"
    File.write(tmpfile, html)
    system("xdg-open '#{tmpfile}' 2>/dev/null &")
    set_feedback("Opened HTML in browser", 156, 3)
    return
  end

  url = nil

  # Determine URL based on source type
  case msg['source_type']
  when 'discord'
    if msg['external_id'] && msg['external_id'].start_with?('discord_')
      parts = msg['external_id'].split('_')
      if parts.length >= 3
        channel_id = parts[1]
        message_id = parts[2]
        guild_id = nil
        if msg['raw_data']
          begin
            raw = JSON.parse(msg['raw_data'])
            guild_id = raw['guild_id']
          rescue; end
        end
        if guild_id
          url = "https://discord.com/channels/#{guild_id}/#{channel_id}/#{message_id}"
        else
          url = "https://discord.com/channels/@me/#{channel_id}/#{message_id}"
        end
      end
    end
  when 'slack'
    if msg['workspace'] && msg['channel_id'] && msg['timestamp']
      url = "https://#{msg['workspace']}.slack.com/archives/#{msg['channel_id']}/p#{msg['timestamp'].gsub('.', '')}"
    end
  when 'reddit'
    if msg['permalink']
      url = "https://reddit.com#{msg['permalink']}"
    elsif msg['url'] && msg['url'].start_with?('http')
      url = msg['url']
    end
  when 'rss', 'hacker_news'
    # Check metadata (where RSS link is stored)
    meta = msg['metadata']
    if meta
      begin
        parsed = meta.is_a?(Hash) ? meta : JSON.parse(meta)
        url = parsed['link'] || parsed['url']
      rescue; end
    end
    # Fallback to raw_data, then external_id
    if !url && msg['raw_data']
      begin
        raw = JSON.parse(msg['raw_data'])
        url = raw['link'] || raw['url']
      rescue; end
    end
    url ||= msg['external_id'] if msg['external_id'] && msg['external_id'].start_with?('http')
  when 'telegram'
    url = msg['link'] if msg['link']
  when 'whatsapp'
    if msg['sender'] && msg['sender'].match?(/^\+?\d+$/)
      url = "https://wa.me/#{msg['sender'].gsub(/[^\d]/, '')}"
    end
  end

  # Fallback to any URL field in the message
  url ||= msg['url'] || msg['link'] || msg['permalink']

  if url
    system("xdg-open '#{url}' 2>/dev/null &")
    set_feedback("Opened in browser: #{url[0..50]}...", 156, 3)
  else
    set_feedback("No HTML or URL available for this message", 226, 3)
  end
end

#page_downObject



2473
2474
2475
# File 'lib/heathrow/ui/application.rb', line 2473

def page_down
  navigate { |n| @index = [@index + @panes[:left].h - 2, n - 1].min }
end

#page_upObject



2477
2478
2479
# File 'lib/heathrow/ui/application.rb', line 2477

def page_up
  navigate { |n| @index = [@index - (@panes[:left].h - 2), 0].max }
end

#parse_color_value(val) ⇒ Object



1707
1708
1709
1710
1711
1712
1713
# File 'lib/heathrow/ui/application.rb', line 1707

def parse_color_value(val)
  return nil unless val
  val = val.to_s
  return val.to_i if val =~ /^\d+$/
  return val if val =~ /^[0-9a-fA-F]{6}$/
  nil
end

#parse_ics_basic(ics) ⇒ Object

Basic ICS parsing fallback (when VcalView is not available)



8473
8474
8475
8476
8477
8478
8479
8480
8481
8482
8483
8484
8485
8486
8487
8488
8489
8490
8491
8492
8493
8494
8495
8496
8497
8498
8499
8500
8501
8502
8503
8504
8505
8506
8507
8508
8509
8510
8511
8512
8513
8514
8515
8516
8517
8518
8519
8520
8521
8522
8523
8524
8525
8526
8527
8528
8529
8530
8531
8532
8533
8534
8535
8536
8537
8538
8539
8540
8541
8542
8543
8544
8545
8546
8547
8548
8549
8550
8551
8552
8553
8554
8555
8556
8557
8558
8559
8560
8561
8562
8563
8564
8565
# File 'lib/heathrow/ui/application.rb', line 8473

def parse_ics_basic(ics)
  # Extract only the VEVENT section (ignore VTIMEZONE which has dummy dates)
  vevent = ics[/BEGIN:VEVENT(.*?)END:VEVENT/m, 1]
  return nil unless vevent

  # Unfold continuation lines (RFC 5545: lines starting with space are continuations)
  vevent = vevent.gsub(/\r?\n[ \t]/, '')

  event = {}

  # SUMMARY (strip LANGUAGE= and other params before the colon-value)
  if vevent =~ /^SUMMARY[^:]*:(.*)$/i
    event[:summary] = $1.strip
  end

  # DTSTART with TZID
  if vevent =~ /^DTSTART;TZID=[^:]*:(\d{8})T?(\d{4,6})?/i
    d = $1; t = $2
    event[:dates] = "#{d[0,4]}-#{d[4,2]}-#{d[6,2]}"
    event[:times] = t ? "#{t[0,2]}:#{t[2,2]}" : "All day"
    begin
      dobj = Time.parse(event[:dates])
      event[:weekday] = dobj.strftime('%A')
    rescue; end
  elsif vevent =~ /^DTSTART;VALUE=DATE:(\d{8})/i
    d = $1
    event[:dates] = "#{d[0,4]}-#{d[4,2]}-#{d[6,2]}"
    event[:times] = "All day"
  elsif vevent =~ /^DTSTART:(\d{8})T?(\d{4,6})?(Z)?/i
    d = $1; t = $2; utc = $3
    event[:dates] = "#{d[0,4]}-#{d[4,2]}-#{d[6,2]}"
    if t
      # Convert UTC times to local
      if utc
        utc_time = Time.utc(d[0,4].to_i, d[4,2].to_i, d[6,2].to_i, t[0,2].to_i, t[2,2].to_i)
        local = utc_time.localtime
        event[:dates] = local.strftime('%Y-%m-%d')
        event[:times] = local.strftime('%H:%M')
        event[:weekday] = local.strftime('%A')
      else
        event[:times] = "#{t[0,2]}:#{t[2,2]}"
        begin
          event[:weekday] = Time.parse(event[:dates]).strftime('%A')
        rescue; end
      end
    else
      event[:times] = "All day"
    end
  end

  # DTEND
  if vevent =~ /^DTEND;TZID=[^:]*:(\d{8})T?(\d{4,6})?/i
    d = $1; t = $2
    end_date = "#{d[0,4]}-#{d[4,2]}-#{d[6,2]}"
    end_time = t ? "#{t[0,2]}:#{t[2,2]}" : nil
  elsif vevent =~ /^DTEND:(\d{8})T?(\d{4,6})?(Z)?/i
    d = $1; t = $2; utc = $3
    if t && utc
      utc_time = Time.utc(d[0,4].to_i, d[4,2].to_i, d[6,2].to_i, t[0,2].to_i, t[2,2].to_i)
      local = utc_time.localtime
      end_date = local.strftime('%Y-%m-%d')
      end_time = local.strftime('%H:%M')
    else
      end_date = "#{d[0,4]}-#{d[4,2]}-#{d[6,2]}"
      end_time = t ? "#{t[0,2]}:#{t[2,2]}" : nil
    end
    event[:dates] += " - #{end_date}" if end_date && end_date != event[:dates]
    event[:times] += " - #{end_time}" if end_time && end_time != event[:times]
  end

  # LOCATION (strip params)
  if vevent =~ /^LOCATION[^:]*:(.*)$/i
    event[:location] = $1.strip
  end

  # ORGANIZER
  if vevent =~ /^ORGANIZER.*CN=([^;:]+)/i
    event[:organizer] = $1.strip
  elsif vevent =~ /^ORGANIZER.*MAILTO:(.+)$/i
    event[:organizer] = $1.strip
  end

  # ATTENDEES
  attendees = vevent.scan(/^ATTENDEE.*CN=([^;:]+)/i).flatten
  if attendees.any?
    event[:participants] = attendees.map { |a| "   #{a.strip}" }.join("\n")
  end

  # STATUS
  event[:status] = $1.strip.capitalize if vevent =~ /^STATUS:(.*)$/i

  event.empty? ? nil : event
end

#parse_interval(str) ⇒ Object



7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
# File 'lib/heathrow/ui/application.rb', line 7456

def parse_interval(str)
  return nil if str.nil? || str.empty?
  case str.strip
  when /^(\d+)s$/i then $1.to_i
  when /^(\d+)m$/i then $1.to_i * 60
  when /^(\d+)h$/i then $1.to_i * 3600
  when /^(\d+)$/   then $1.to_i  # Raw seconds
  else nil
  end
end

#parse_timestamp(ts, format = @date_format) ⇒ Object

Helper method to parse timestamps (handles both Unix timestamps and date strings)



350
351
352
353
354
355
356
357
358
359
360
361
362
# File 'lib/heathrow/ui/application.rb', line 350

def parse_timestamp(ts, format = @date_format)
  return nil if ts.nil? || ts.to_s.empty? || ts.to_s == "0"

  if ts.is_a?(Integer) || ts.to_s.match?(/^\d+$/)
    # Unix timestamp - use Time.at
    Time.at(ts.to_i).strftime(format)
  else
    # Date string - use Time.parse
    Time.parse(ts.to_s).strftime(format)
  end
rescue => e
  nil
end

#pick_from_list(names, title: "SELECT", prompt: "j/k navigate, Enter select, ESC cancel") ⇒ Object

Generic picker: shows a list in the right pane with → cursor. Returns selected index or nil on cancel.



1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
# File 'lib/heathrow/ui/application.rb', line 1036

def pick_from_list(names, title: "SELECT", prompt: "j/k navigate, Enter select, ESC cancel")
  idx = 0

  render_pick = -> {
    lines = [title.bd.fg(226), ""]
    names.each_with_index do |name, i|
      if i == idx
        lines << "→ #{name}".bd.fg(226)
      else
        lines << "  #{name}".fg(252)
      end
    end
    lines << ""
    lines << prompt.fg(245)
    @panes[:right].text = lines.join("\n")
    @panes[:right].refresh
  }

  render_pick.call
  loop do
    chr = getchr
    case chr
    when 'j', 'DOWN', 'S-DOWN'
      idx = (idx + 1) % names.size
      render_pick.call
    when 'k', 'UP', 'S-UP'
      idx = (idx - 1) % names.size
      render_pick.call
    when 'ENTER', "\r", "\n"
      return idx
    when 'ESC', "\e", 'q'
      return nil
    end
  end
end

#pick_source_colorObject



7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
# File 'lib/heathrow/ui/application.rb', line 7179

def pick_source_color
  return unless @in_source_view && @filtered_messages[@index]
  source_id = @filtered_messages[@index]['id']
  source = @source_manager.sources[source_id]
  return unless source

  # Build a 256-color grid in the right pane
  lines = []
  lines << "COLOR PICKER for #{source['name']}".bd.fg(226)
  lines << "=" * 40
  lines << ""
  lines << "Enter color number (0-255) or RGB hex (e.g. ff8800):"
  lines << ""

  # Show standard colors 0-15
  row = ""
  (0..15).each do |c|
    row += " #{c.to_s.rjust(3)}".fg(c > 6 && c < 10 || c == 0 ? 255 : 0).bg(c)
  end
  lines << row

  lines << ""

  # Show 216-color cube (16-231) in 6 rows of 36
  (0..5).each do |g|
    row = ""
    (0..35).each do |i|
      c = 16 + g * 36 + i
      fg = (g < 3 && i < 18) ? 255 : 0
      row += "#{c.to_s.rjust(4)}".fg(fg).bg(c)
    end
    lines << row
  end

  lines << ""

  # Grayscale 232-255
  row = ""
  (232..255).each do |c|
    fg = c < 244 ? 255 : 0
    row += "#{c.to_s.rjust(4)}".fg(fg).bg(c)
  end
  lines << row
  lines << ""

  current = source['color']
  lines << "Current: #{current || 'auto'}".fg(245)

  @panes[:right].text = lines.join("\n")
  @panes[:right].refresh

  # Get input
  @panes[:bottom].prompt = "Color: "
  @panes[:bottom].text = current.to_s
  @editing = true
  @panes[:bottom].editline
  @editing = false
  input = @panes[:bottom].text.strip

  if input.empty?
    # Clear custom color
    @db.execute("UPDATE sources SET color = NULL WHERE id = ?", source_id)
    @source_colors.delete(source_id)
    set_feedback("Color reset to auto", 40, 2)
  elsif input =~ /^\d+$/ && input.to_i >= 0 && input.to_i <= 255
    @db.execute("UPDATE sources SET color = ? WHERE id = ?", input, source_id)
    @source_colors[source_id] = input.to_i
    set_feedback("Color set to #{input}", input.to_i, 2)
  elsif input =~ /^[0-9a-fA-F]{6}$/
    @db.execute("UPDATE sources SET color = ? WHERE id = ?", input, source_id)
    @source_colors[source_id] = input
    set_feedback("Color set to ##{input}", 40, 2)
  else
    set_feedback("Invalid color. Use 0-255 or 6-digit hex.", 196, 2)
  end

  # Update the pseudo-message in @filtered_messages so left pane reflects new color
  if @filtered_messages
    src_msg = @filtered_messages.find { |m| m['id'] == source_id }
    src_msg['source_color'] = @source_colors[source_id] if src_msg
  end

  # Refresh source manager cache and redraw
  @source_manager.reload
  render_all
end


7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
# File 'lib/heathrow/ui/application.rb', line 7824

def popup_add_maildir
  path = bottom_ask("Maildir path: ", File.join(Dir.home, 'Maildir'))
  return unless path && !path.strip.empty?
  path = File.expand_path(path.strip)

  unless Dir.exist?(path)
    set_feedback("Directory not found: #{path}", 196, 4)
    return
  end

  config = { 'maildir_path' => path }
  @db.add_source('Local Maildir', 'maildir', config, ['read', 'send'], true)
  @db.execute("UPDATE sources SET poll_interval = 30 WHERE name = 'Local Maildir'")

  set_feedback("Maildir source added! Syncing...", 156, 3)

  # Do initial sync
  require_relative '../sources/maildir'
  source = @db.get_source_by_name('Local Maildir')
  if source
    instance = Heathrow::Sources::Maildir.new(source)
    @panes[:bottom].text = " Syncing Maildir (this may take a moment for large collections)...".fg(226)
    @panes[:bottom].refresh
    instance.sync_all(@db, source['id'])
    count = @db.db.get_first_value("SELECT COUNT(*) FROM messages WHERE source_id = ?", [source['id']]) rescue 0
    set_feedback("Synced #{count} messages from Maildir", 156, 5)
  end
end


7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
# File 'lib/heathrow/ui/application.rb', line 7853

def popup_add_rss
  url = bottom_ask("RSS/Atom feed URL: ", '')
  return unless url && !url.strip.empty?
  url = url.strip

  title = bottom_ask("Feed name (Enter for auto): ", '')
  title = nil if title && title.strip.empty?

  config = { 'feeds' => [{ 'url' => url, 'title' => title }] }
  @db.add_source('RSS Feeds', 'rss', config, ['read'], true)
  set_feedback("RSS source added! Add more feeds via 'S' > RSS > 'a'", 156, 5)
end


7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
# File 'lib/heathrow/ui/application.rb', line 7866

def popup_add_weechat
  host = bottom_ask("WeeChat relay host: ", 'localhost')
  return unless host && !host.strip.empty?
  port = bottom_ask("Relay port: ", '8001')
  password = bottom_ask("Relay password: ", '')

  config = {
    'host' => host.strip,
    'port' => port.strip.to_i,
    'password' => password
  }
  @db.add_source('WeeChat', 'weechat', config, ['read', 'send'], true)
  set_feedback("WeeChat source added!", 156, 5)
end

#postpone_message(source, composed) ⇒ Object



5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
# File 'lib/heathrow/ui/application.rb', line 5799

def postpone_message(source, composed)
  data = {
    from: composed[:from],
    to: composed[:to],
    cc: composed[:cc],
    bcc: composed[:bcc],
    reply_to: composed[:reply_to],
    subject: composed[:subject],
    body: composed[:body],
    extra_headers: composed[:extra_headers],
    attachments: composed[:attachments],
    original_message_id: composed[:original_message]&.[]('id')
  }
  @db.save_postponed(source['id'], data)
  set_feedback("Message postponed", 156, 3)
end

#prompt_attachments(attachments = [], composed: nil) ⇒ Object

Prompt user to attach files after composing an email. Returns array of file paths, or nil if cancelled (ESC).



5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
# File 'lib/heathrow/ui/application.rb', line 5591

def prompt_attachments(attachments = [], composed: nil)
  # Show who the message is going to
  to_info = ""
  if composed && composed[:to]
    to_info = " To: #{composed[:to]}"
    to_info += ", Cc: #{composed[:cc]}" if composed[:cc] && !composed[:cc].empty?
  end

  loop do
    # Ensure terminal is in raw mode with cursor hidden (safety after external tools)
    Cursor.hide

    # Show attachments and recipients in right pane
    right_lines = []
    if composed
      right_lines << "To: #{composed[:to]}".fg(theme[:accent]) if composed[:to]
      right_lines << "Cc: #{composed[:cc]}".fg(theme[:accent]) if composed[:cc] && !composed[:cc].to_s.empty?
      right_lines << "Subject: #{composed[:subject]}".fg(theme[:accent]) if composed[:subject]
      right_lines << ""
    end
    if attachments.empty?
      right_lines << "No attachments"
    else
      total_size = attachments.sum { |f| File.size(f) rescue 0 }
      size_str = total_size < 1_000_000 ? "#{(total_size / 1024.0).round(1)}KB" : "#{(total_size / 1_000_000.0).round(1)}MB"
      right_lines << "Attachments (#{attachments.size}, #{size_str}):".bd
      attachments.each_with_index do |f, i|
        fsize = File.size(f) rescue 0
        fs = fsize < 1_000_000 ? "#{(fsize / 1024.0).round(1)}KB" : "#{(fsize / 1_000_000.0).round(1)}MB"
        right_lines << "  #{i + 1}. #{File.basename(f)} (#{fs})"
      end
    end
    @panes[:right].text = right_lines.join("\n")
    @panes[:right].refresh

    # Build prompt with compose plugin keys
    plugins = compose_plugins
    plugin_hint = plugins.map { |p| "#{p[:label]} (#{p[:key]})" }.join(" | ")
    plugin_hint = " | #{plugin_hint}" unless plugin_hint.empty?

    if attachments.empty?
      prompt = " Send (ENTER) | Edit (e) | Attach (a)#{plugin_hint} | Postpone (p) | Cancel (ESC)"
    else
      prompt = " Send (ENTER) | Edit (e) | More (a)#{plugin_hint} | Remove (x) | Postpone (p) | ESC"
    end

    @panes[:bottom].text = prompt.fg(226)
    @panes[:bottom].refresh

    chr = getchr
    case chr
    when 'ENTER'
      return attachments
    when 'ESC'
      return nil
    when 'p'
      return :postpone
    when 'e'
      composed[:attachments] = attachments.dup unless attachments.empty?
      return :edit
    when 'a', 'A'
      new_files = run_rtfm_picker
      attachments.concat(new_files) if new_files && !new_files.empty?
    when 'x', 'X'
      if attachments.size == 1
        attachments.clear
      elsif attachments.size > 1
        @panes[:bottom].text = " Remove which? (1-#{attachments.size}, or 'a' for all): ".fg(226)
        @panes[:bottom].refresh
        ans = getchr
        if ans == 'a' || ans == 'A'
          attachments.clear
        elsif ans =~ /^\d$/ && (idx = ans.to_i) >= 1 && idx <= attachments.size
          attachments.delete_at(idx - 1)
        end
      end
    else
      # Check compose plugins
      plugin = plugins.find { |p| p[:key] == chr }
      if plugin
        new_files = run_compose_plugin(plugin)
        attachments.concat(new_files) if new_files && !new_files.empty?
      end
    end
  end
end

#purge_deletedObject

Purge all delete-marked messages (like mutt '$' / sync-mailbox)



5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
# File 'lib/heathrow/ui/application.rb', line 5105

def purge_deleted
  @delete_marked ||= Set.new
  count = @delete_marked.size
  if count == 0
    set_feedback("No messages marked for deletion", 226, 2)
    return
  end

  if @confirm_purge
    confirm = bottom_ask("Purge #{count} message#{count > 1 ? 's' : ''}? ENTER to confirm, ESC to cancel: ", '')
    if confirm.nil?
      set_feedback("Purge cancelled", 245, 2)
      return
    end
  end

  # Find messages in both filtered and display lists
  all_msgs = (@filtered_messages + (@display_messages || [])).uniq { |m| m['id'] }

  @delete_marked.each do |msg_id|
    msg = all_msgs.find { |m| m['id'] == msg_id }
    if msg
      # Delete the Maildir file (like mutt) so it doesn't reappear on sync
      delete_maildir_file(msg)
      @db.execute("DELETE FROM messages WHERE id = ?", msg_id)
    end
  end

  # Find the message just above the first deleted one (by ID, survives reindexing)
  display = @display_messages || @filtered_messages
  first_deleted_idx = display.each_with_index.find { |m, _| @delete_marked.include?(m['id']) }&.last
  target_msg_id = nil
  if first_deleted_idx && first_deleted_idx > 0
    # Walk backwards to find first non-deleted message above
    (first_deleted_idx - 1).downto(0) do |i|
      unless @delete_marked.include?(display[i]['id'])
        target_msg_id = display[i]['id']
        break
      end
    end
  end

  # Remove from current view
  @filtered_messages.reject! { |m| @delete_marked.include?(m['id']) }
  purged_ids = @delete_marked.dup
  @delete_marked.clear

  # Force threaded view to rebuild with purged messages gone
  reset_threading(true)

  # Position cursor on the message above the first deleted one
  new_display = @display_messages || @filtered_messages
  if target_msg_id
    found = new_display.index { |m| m['id'] == target_msg_id }
    @index = found || 0
  else
    @index = 0
  end
  @index = [new_display.size - 1, 0].max if @index >= new_display.size

  set_feedback("Purged #{count} messages", 156, 2)
  render_all
end

#purge_item_messages(source_id, source_type, item) ⇒ Object

Remove messages belonging to a deleted feed/page



1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
# File 'lib/heathrow/ui/application.rb', line 1196

def purge_item_messages(source_id, source_type, item)
  name = item['title'] || item['url'] || item['name']
  case source_type
  when 'rss'
    # RSS messages have feed_title in metadata
    @db.execute("DELETE FROM messages WHERE source_id = ? AND json_extract(metadata, '$.feed_title') = ?",
                [source_id, name])
  when 'web'
    @db.execute("DELETE FROM messages WHERE source_id = ? AND json_extract(metadata, '$.page_title') = ?",
                [source_id, name])
  end
  @db.execute("SELECT changes() as cnt")[0]['cnt']
end

#quitObject



8120
8121
8122
8123
# File 'lib/heathrow/ui/application.rb', line 8120

def quit
  @config.save
  @running = false
end

#recall_postponed(source) ⇒ Object



5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
# File 'lib/heathrow/ui/application.rb', line 5816

def recall_postponed(source)
  count = @db.postponed_count
  return nil if count == 0

  drafts = @db.list_postponed
  if count == 1
    draft = drafts.first
    data = JSON.parse(draft['data'])
    @db.delete_postponed(draft['id'])
    return data
  end

  # Multiple drafts: show picker
  rows, cols = IO.console.winsize
  pw = [cols - 20, 60].min
  ph = [count + 5, rows - 10].min
  px = (cols - pw) / 2
  py = (rows - ph) / 2

  popup = Rcurses::Pane.new(px, py, pw, ph, 252, 0)
  popup.border = true
  popup.scroll = false
  sel = 0

  build = -> {
    popup.full_refresh
    lines = ["", "  " + "Postponed Messages".bd.fg(theme[:accent])]
    lines << "  " + "\u2500" * [pw - 6, 1].max
    drafts.each_with_index do |d, i|
      data = JSON.parse(d['data']) rescue {}
      date = Time.at(d['created_at']).strftime('%b %d %H:%M')
      subj = data['subject'] || '(no subject)'
      to = data['to'] || ''
      entry = "  #{date}  #{to.to_s[0..15].ljust(16)}  #{subj}"
      entry = entry[0..pw-6]
      lines << (i == sel ? entry.fg(theme[:accent]) : entry)
    end
    lines << ""
    lines << "  " + "ENTER:recall  d:delete  ESC:cancel".fg(245)
    popup.text = lines.join("\n")
    popup.refresh
  }

  build.call
  loop do
    k = getchr
    case k
    when 'ESC', 'q'
      render_all
      return nil
    when 'k', 'UP'
      sel = (sel - 1) % count
      build.call
    when 'j', 'DOWN'
      sel = (sel + 1) % count
      build.call
    when 'd'
      @db.delete_postponed(drafts[sel]['id'])
      drafts.delete_at(sel)
      count -= 1
      if count == 0
        render_all
        set_feedback("All postponed messages deleted", 245, 2)
        return nil
      end
      sel = [sel, count - 1].min
      build.call
    when 'ENTER'
      draft = drafts[sel]
      data = JSON.parse(draft['data'])
      @db.delete_postponed(draft['id'])
      render_all
      return data
    end
  end
end

#redraw_panesObject



8087
8088
8089
8090
8091
8092
8093
# File 'lib/heathrow/ui/application.rb', line 8087

def redraw_panes
  require 'io/console'
  @h, @w = IO.console.winsize
  Rcurses.clear_screen
  create_panes
  render_all
end

#refresh_allObject



8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
# File 'lib/heathrow/ui/application.rb', line 8067

def refresh_all
  set_feedback("Syncing all sources...", 226, 30)
  @needs_redraw = true

  Thread.new do
    thread_db = Heathrow::Database.new
    sync_maildir(folder: current_view_folder, db: thread_db)
    sync_rss(db: thread_db)
    sync_webwatch(db: thread_db)
    sync_messenger(db: thread_db)
    sync_instagram(db: thread_db)
    sync_weechat(db: thread_db)
    thread_db.close rescue nil
    @pending_view_refresh = true
    set_feedback("Synced all", 46, 2)
  rescue => e
    set_feedback("Refresh error: #{e.message}", 196, 3)
  end
end

#refresh_current_viewObject



7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
# File 'lib/heathrow/ui/application.rb', line 7969

def refresh_current_view
  view = @views[@current_view]
  source_type = nil
  if view && view[:filters] && view[:filters]['rules'].is_a?(Array)
    rule = view[:filters]['rules'].find { |r| r['field'] == 'source_type' && r['op'] == '=' }
    source_type = rule['value'] if rule
    # Also check source_id rules to determine source type
    if !source_type
      sid_rule = view[:filters]['rules'].find { |r| r['field'] == 'source_id' && r['op'] == '=' }
      if sid_rule
        src = @db.get_source_by_id(sid_rule['value'].to_i)
        source_type = src['plugin_type'] if src
      end
    end
  end
  folder = current_view_folder

  set_feedback("Syncing #{source_type || 'view'}...", 226, 30)
  @needs_redraw = true

  # Extract thread info BEFORE spawning thread (current_message depends on UI state)
  cur_msg = current_message
  cur_meta = cur_msg && cur_msg['metadata']
  cur_meta = JSON.parse(cur_meta) if cur_meta.is_a?(String) rescue nil
  cur_thread_id = cur_meta['thread_id'] if cur_meta.is_a?(Hash)
  # For thread headers, look for thread_id in section messages
  if !cur_thread_id && cur_msg && cur_msg['section_messages']
    first_msg = cur_msg['section_messages'].first
    if first_msg
      fm = first_msg['metadata']
      fm = JSON.parse(fm) if fm.is_a?(String) rescue nil
      cur_thread_id = fm['thread_id'] if fm.is_a?(Hash)
    end
  end
  cur_thread_name = cur_msg['subject'] if cur_msg
  File.open('/tmp/heathrow_sync_debug.log', 'w') { |f|
    f.puts "source_type=#{source_type}"
    f.puts "cur_msg_id=#{cur_msg&.[]('id')}"
    f.puts "cur_msg_keys=#{cur_msg&.keys}"
    f.puts "cur_meta_class=#{cur_meta.class}"
    f.puts "cur_meta=#{cur_meta.inspect}"
    f.puts "cur_thread_id=#{cur_thread_id}"
    f.puts "cur_thread_name=#{cur_thread_name}"
    f.puts "is_header=#{cur_msg&.[]('is_header')}"
    f.puts "section_messages=#{cur_msg&.[]('section_messages')&.length}"
  }

  Thread.new do
    thread_db = Heathrow::Database.new

    case source_type
    when 'maildir'   then sync_maildir(folder: folder, db: thread_db)
    when 'rss'       then sync_rss(db: thread_db)
    when 'web'       then sync_webwatch(db: thread_db)
    when 'messenger'
      if cur_thread_id && cur_thread_name
        require_relative '../sources/messenger'
        src = thread_db.get_sources.find { |s| s['plugin_type'] == 'messenger' }
        if src
          config = src['config']
          config = JSON.parse(config) if config.is_a?(String)
          instance = Heathrow::Sources::Messenger.new(src['name'], config || {}, thread_db)
          count = instance.sync_thread(src['id'], cur_thread_id.to_s, cur_thread_name)
          if instance.sync_error
            @last_sync_errors = (@last_sync_errors || []) << instance.sync_error
          else
            @_thread_sync_count = count
          end
        end
      else
        sync_messenger(db: thread_db)
      end
    when 'instagram' then sync_instagram(db: thread_db)
    when 'weechat'   then sync_weechat(db: thread_db)
    else
      sync_maildir(folder: folder, db: thread_db)
      sync_rss(db: thread_db)
      sync_webwatch(db: thread_db)
      sync_messenger(db: thread_db)
      sync_instagram(db: thread_db)
      sync_weechat(db: thread_db)
    end
    thread_db.close rescue nil
    @pending_view_refresh = true
    if @last_sync_errors && !@last_sync_errors.empty?
      set_feedback("Sync errors: #{@last_sync_errors.join('; ')}", 208, 0)
      @last_sync_errors = nil
    elsif @_thread_sync_count
      set_feedback("Fetched #{@_thread_sync_count} messages from #{cur_thread_name}", @_thread_sync_count > 0 ? 156 : 208, 0)
      @_thread_sync_count = nil
    else
      set_feedback("Synced", 46, 2)
    end
  rescue => e
    set_feedback("Refresh error: #{e.message}", 196, 3)
  end
end

#refresh_messagesObject



7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
# File 'lib/heathrow/ui/application.rb', line 7955

def refresh_messages
  case @current_view
  when 'A'
    show_all_messages
  when 'N'
    show_new_messages
  when 'S'
    # Don't refresh sources - they're static
    return
  else
    switch_to_view(@current_view)
  end
end

#refresh_panesObject



2292
2293
2294
# File 'lib/heathrow/ui/application.rb', line 2292

def refresh_panes
  @panes.each { |_, pane| pane.refresh }
end

#render_allObject



1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
# File 'lib/heathrow/ui/application.rb', line 1330

def render_all
  # Organize messages if in threaded view
  if @show_threaded && !@in_source_view && @filtered_messages && !@filtered_messages.empty?
    organize_current_messages
  end

  update_window_title
  render_message_list
  render_top_bar
  # Only re-render right pane if it's not locked by another feature
  if @in_source_view
    render_sources_info
  elsif @panes[:right].content_update
    render_message_content
  end
  render_bottom_bar
end

#render_attachment_list(attachments, idx, tagged) ⇒ Object



3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
# File 'lib/heathrow/ui/application.rb', line 3304

def render_attachment_list(attachments, idx, tagged)
  lines = ["Attachments:".bd.fg(226), ""]
  attachments.each_with_index do |att, i|
    name = att['name'] || att['filename'] || 'unnamed'
    size = att['size'] ? " (#{human_size(att['size'])})" : ''
    ctype = att['content_type']&.split(';')&.first || ''
    tag = tagged.include?(i) ? "* ".fg(226) : "  "
    if i == idx
      lines << "→ ".fg(226) + tag + "#{name}#{size}  #{ctype}".bd.fg(255)
    else
      lines << "  " + tag + "#{name}#{size}  #{ctype}".fg(250)
    end
  end
  tagged_hint = tagged.empty? ? "" : "  (#{tagged.size} tagged)"
  lines << ""
  lines << "t:Tag  T:All  o/Enter:Open  s:Save#{tagged_hint}".fg(245)
  @panes[:right].ix = 0
  @panes[:right].text = lines.join("\n")
  @panes[:right].refresh
end

#render_bottom_barObject



2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
# File 'lib/heathrow/ui/application.rb', line 2260

def render_bottom_bar
  # Check if there's an active feedback message (timed or sticky)
  if @feedback_sticky && @feedback_message
    if @panes[:bottom]
      @panes[:bottom].text = " #{@feedback_message}".fg(@feedback_color || 156)
      @panes[:bottom].refresh
    end
    return
  elsif @feedback_expires_at && Time.now < @feedback_expires_at
    if @panes[:bottom]
      @panes[:bottom].text = " #{@feedback_message}".fg(@feedback_color || 156)
      @panes[:bottom].refresh
    end
    return
  elsif @feedback_expires_at && Time.now >= @feedback_expires_at
    @feedback_message = nil
    @feedback_expires_at = nil
  end

  # Check if we should show the filter config message
  if @current_view =~ /^([0-9]|F\d{1,2})$/ && (@views[@current_view].nil? || @views[@current_view][:filters].nil? || @views[@current_view][:filters].empty?)
    @panes[:bottom].text = " View #{@current_view} not configured. Press F to set up filters.".fg(226)
    @panes[:bottom].refresh
    return
  end

  # Show key hints with context
  keys = %w[q:Quit ?:Help A:All N:New 0-9:Views Space:Fold t:Tag T:All s:Save B:Browse F:Fav]
  @panes[:bottom].text = " " + keys.join(" | ").fg(245)
  @panes[:bottom].refresh
end

#render_folder_browserObject



3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
# File 'lib/heathrow/ui/application.rb', line 3876

def render_folder_browser
  @browser_favorites ||= get_favorite_folders
  lines = []
  @folder_display.each_with_index do |folder, i|
    indent = "  " * folder[:depth]
    arrow = folder[:has_children] ? (folder[:collapsed] ? "▸ " : "▾ ") : "  "
    star = @browser_favorites.include?(folder[:full_name]) ? "* ".fg(226) : "  "

    if i == @folder_browser_index
      line = "→ ".fg(226) + indent + arrow.fg(226) + star + folder[:name].bd.ul.fg(255)
    else
      line = "  " + indent + arrow.fg(245) + star + folder[:name].fg(245)
    end
    lines << line
  end

  @panes[:left].text = lines.join("\n")

  # Scroll to keep selected item visible
  page_height = @panes[:left].h
  page_height -= 2 if @panes[:left].border
  if @folder_display.size > page_height
    scrolloff = 3
    max_scroll = @folder_display.size - page_height
    if @folder_browser_index - @panes[:left].ix < scrolloff
      @panes[:left].ix = [@folder_browser_index - scrolloff, 0].max
    elsif @panes[:left].ix + page_height - 1 - @folder_browser_index < scrolloff
      @panes[:left].ix = [@folder_browser_index + scrolloff - page_height + 1, max_scroll].min
    end
  else
    @panes[:left].ix = 0
  end

  @panes[:left].refresh

  # Show folder info in right pane (cache counts to avoid slow queries on every keystroke)
  if @folder_display[@folder_browser_index]
    folder = @folder_display[@folder_browser_index]
    @folder_count_cache ||= {}
    counts = @folder_count_cache[folder[:full_name]] ||= folder_message_count(folder[:full_name])
    info = []
    info << "FOLDER: #{folder[:full_name]}".bd.fg(226)
    info << ""
    info << "Messages: #{counts[:total]}".fg(39)
    info << "Unread: #{counts[:unread]}".fg(counts[:unread] > 0 ? 208 : 245)
    info << ""
    info << "Press Enter to open folder".fg(245)
    info << "Press h/l to collapse/expand".fg(245)
    info << "Press ESC/q to return".fg(245)
    @panes[:right].text = info.join("\n")
    @panes[:right].refresh
  end

  # Update top bar (preserve Favorites title if in favorites mode)
  browser_title = @in_favorites_browser ? "Favorites" : "Folder Browser"
  browser_color = @in_favorites_browser ? 226 : 201
  @panes[:top].text = " Heathrow - ".bd.fg(255) + browser_title.bd.fg(browser_color) + " [#{@folder_display.size} folders]".fg(246)
  @panes[:top].refresh

  # Update bottom bar
  @panes[:bottom].text = " j/k:Navigate | Enter:Open | h/l:Collapse/Expand | F:Favorites | +:Add fav | ESC:Back".fg(245)
  @panes[:bottom].refresh
end

#render_folder_browser_left_onlyObject

Fast re-render of just the left pane folder list (no DB queries)



3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
# File 'lib/heathrow/ui/application.rb', line 3941

def render_folder_browser_left_only
  @browser_favorites ||= get_favorite_folders
  lines = []
  @folder_display.each_with_index do |folder, i|
    indent = "  " * folder[:depth]
    arrow = folder[:has_children] ? (folder[:collapsed] ? "▸ " : "▾ ") : "  "
    star = @browser_favorites.include?(folder[:full_name]) ? "* ".fg(226) : "  "
    if i == @folder_browser_index
      line = "→ ".fg(226) + indent + arrow.fg(226) + star + folder[:name].bd.ul.fg(255)
    else
      line = "  " + indent + arrow.fg(245) + star + folder[:name].fg(245)
    end
    lines << line
  end
  @panes[:left].text = lines.join("\n")
  @panes[:left].refresh
end

#render_header_summary(header_msg) ⇒ Object



2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
# File 'lib/heathrow/ui/application.rb', line 2174

def render_header_summary(header_msg)
  # Render a summary view for group headers (channels, threads, etc.)
  lines = []

  # Title
  title = header_msg['subject'] || header_msg['channel_name'] || 'Group'
  lines << title.bd.fg(226)
  lines << ""

  # Message count
  count_text = header_msg['content'] || "0 messages"
  lines << count_text.fg(245)
  lines << ""

  # Unread count if available
  if header_msg['is_channel_header'] && @organizer && @organizer.respond_to?(:get_channel_info)
    begin
      channel_info = @organizer.get_channel_info(header_msg['channel_id'])
      if channel_info && channel_info[:unread_count] && channel_info[:unread_count] > 0
        lines << "#{channel_info[:unread_count]} unread".fg(208)
        lines << ""
      end
    rescue => e
      # Silently ignore if method doesn't work
    end
  elsif header_msg['is_thread_header'] && @organizer && @organizer.respond_to?(:get_thread_info)
    begin
      thread_info = @organizer.get_thread_info(header_msg['thread_id'])
      if thread_info && thread_info[:unread_count] && thread_info[:unread_count] > 0
        lines << "#{thread_info[:unread_count]} unread".fg(208)
        lines << ""
      end
    rescue => e
      # Silently ignore if method doesn't work
    end
  end

  # Hint
  lines << "Press Enter to expand/collapse".fg(240)
  lines << "Press j/k to navigate".fg(240)

  # Display at top of pane (no vertical centering)
  @panes[:right].text = lines.join("\n")
  @panes[:right].refresh
end

#render_message_contentObject



1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
# File 'lib/heathrow/ui/application.rb', line 1934

def render_message_content
  current_msg = current_message

  # Reset scroll position when switching messages
  if @last_rendered_index != @index
    @panes[:right].ix = 0
    @last_rendered_index = @index
    clear_inline_image
  end

  unless current_msg
    @panes[:right].text = ""
    @panes[:right].refresh
    return
  end

  # Auto-mark as read when content is rendered in the right pane
  mark_current_message_as_read

  msg = current_msg

  # Lazily load full content if this was a light query result
  # Light query uses substr(content,1,200), so reload if content is short or missing
  # Skip for source view (pseudo-messages share IDs with real messages)
  if msg['id'] && !msg['is_header'] && !msg['_full_loaded'] && !@in_source_view
    full = @db.get_message(msg['id'])
    if full
      msg.merge!(full)
      msg['_full_loaded'] = true
    end
  end

  # Special handling for headers (channel headers, thread headers, etc.)
  if header_message?(msg)
    render_header_summary(msg)
    return
  end
  
  # Format message header
  header = []
  
  # Special handling for RSS/HN messages
  if msg['source_type'] == 'rss' || msg['source_type'] == 'hacker_news'
    header << "📰 #{msg['subject']}".bd.fg(226) if msg['subject']
    
    # Extract metadata from raw_data if available
    if msg['raw_data']
      begin
        raw = JSON.parse(msg['raw_data'])
        
        # Add feed title and author
        if raw['feed_title']
          author_info = raw['author'] ? "#{raw['feed_title']} - #{raw['author']}" : raw['feed_title']
          header << "Source: #{author_info}".fg(39)
        elsif raw['author']
          header << "Author: #{raw['author']}".fg(39)
        end
        
        # Add categories/tags
        if raw['categories'] && raw['categories'].is_a?(Array) && !raw['categories'].empty?
          header << "Tags: #{raw['categories'].join(', ')}".fg(245)
        end
        
        # Add link
        if raw['link']
          header << "Link: #{raw['link']}".fg(33)
        end
      rescue => e
        # Fallback to regular display if JSON parsing fails
      end
    end
  else
    # Regular message display
    header << "From: #{msg['sender']}".fg(2) if msg['sender']
    # Show recipients (To field, already parsed by normalize_message_row)
    to = msg['recipients'] || msg['recipient']
    if to
      to_str = to.is_a?(Array) ? to.join(', ') : to.to_s
      header << "To: #{to_str}".fg(2) unless to_str.empty?
    end
    # Show CC recipients (already parsed by normalize_message_row)
    cc = msg['cc']
    if cc
      cc_str = cc.is_a?(Array) ? cc.join(', ') : cc.to_s
      header << "Cc: #{cc_str}".fg(2) unless cc_str.empty?
    end
    # For weechat, show channel name from metadata instead of content preview
    meta = msg['metadata']
    if meta.is_a?(Hash) && meta['channel_name']
      header << "Subject: #{meta['channel_name']}".bd.fg(1)
    elsif msg['subject']
      header << "Subject: #{msg['subject']}".bd.fg(1)
    end
  end
  
  # Parse timestamp using helper method
  date_str = parse_timestamp(msg['timestamp'], '%Y-%m-%d %H:%M:%S') || "Unknown date"

  header << "Date: #{date_str}".fg(240)
  if msg['source_type']
    source_label = case msg['source_type']
    when 'rss' then 'RSS Feed'
    when 'hacker_news' then 'Hacker News'
    else msg['source_type'].capitalize
    end
    header << "Type: #{source_label}".fg(get_source_color(msg))
  end

  # Show labels (if any beyond the folder name, already parsed by normalize_message_row)
  labels = msg['labels']
  labels = [] unless labels.is_a?(Array)
  if labels.size > 0
    # Skip folder name (first label) if it matches the folder
    display_labels = labels.reject { |l| l == msg['folder'] }
    unless display_labels.empty?
      header << "Labels: #{display_labels.join(', ')}".fg(51)
    end
  end
  
  pane_w = @panes[:right].w rescue 80
  header << ("─" * (pane_w - 2)).fg(238)

  # Format message body — prefer HTML rendered via w3m
  render_width = [pane_w - 2, 40].max
  content = nil
  if msg['html_content'] && !msg['html_content'].to_s.strip.empty?
    content = html_to_text(msg['html_content'], render_width)
  end
  content ||= msg['content'] || '(No content)'
  # Detect raw HTML in content (e.g. HTML-only emails imported before html_content existed)
  if content =~ /\A\s*(<(!DOCTYPE|html|head|body)\b)/i
    content = html_to_text(content, render_width) || content
  end

  # For RSS/HN, add extra formatting and info
  if msg['source_type'] == 'rss' || msg['source_type'] == 'hacker_news'
    content_parts = []
    content_parts << "📄 Article Summary:".bd.fg(226)
    content_parts << ""
    
    # Word wrap the content for better readability
    wrapped_lines = []
    content.split("\n").each do |line|
      if line.length > 80
        # Simple word wrapping at 80 characters
        words = line.split(' ')
        current_line = ""
        words.each do |word|
          if current_line.empty?
            current_line = word
          elsif (current_line + " " + word).length <= 80
            current_line += " " + word
          else
            wrapped_lines << current_line
            current_line = word
          end
        end
        wrapped_lines << current_line unless current_line.empty?
      else
        wrapped_lines << line
      end
    end
    
    content_parts.concat(wrapped_lines)
    
    # Add note about full content
    content_parts << ""
    content_parts << "─" * 40
    content_parts << ""
    content_parts << "📌 Note: This is a summary from the RSS feed.".fg(245)
    content_parts << "   Most RSS feeds only provide excerpts, not full articles.".fg(245)
    content_parts << "   Press 'x' to read the complete article in your browser.".fg(156)
    
    # Add helpful instructions
    content_parts << ""
    content_parts << "─" * 40
    content_parts << "💡 Keyboard Shortcuts:".bd.fg(156)
    content_parts << ""
    content_parts << "  x     - Open full article in browser".fg(250)
    content_parts << "  SPACE - Toggle read/unread status".fg(250)
    content_parts << "  s     - Star/unstar this article".fg(250)
    content_parts << "  j/k   - Navigate between messages".fg(250)
    content_parts << "  ENTER - Expand/collapse in left pane".fg(250)
    
    content = content_parts.join("\n")
  end
  
  # Ensure content is UTF-8 compatible (handle emails with various encodings)
  # Create a mutable copy if frozen, then fix encoding
  content = content.dup if content.frozen?

  if content.encoding != Encoding::UTF_8
    content = content.force_encoding('UTF-8').scrub('?')
  elsif !content.valid_encoding?
    content = content.scrub('?')
  end

  # Colorize email content (quote levels + signature)
  content = colorize_email_content(content)

  # Store maildir file path for calendar parser (metadata already parsed by normalize_message_row)
  meta = msg['metadata']
  @_current_render_msg_file = meta['maildir_file'] if meta.is_a?(Hash)

  # Attachment list under header, before body
  att_text = format_attachments(msg['attachments'])

  # Check for images (HTML <img> tags + attachment URLs) and show hint
  image_hint = nil
  img_count = 0
  # Count from attachments
  img_count += image_urls_from_attachments(msg).size
  # Count from HTML
  html = msg['html_content']
  if (!html || html.to_s.strip.empty?) && msg['content'] =~ /\A\s*<(!DOCTYPE|html|head|body)\b/i
    html = msg['content']
  end
  if html && !html.to_s.strip.empty?
    img_count += extract_image_urls(html).select { |u| u.start_with?('http') }.size
  end
  if img_count > 0
    image_hint = "#{img_count} image#{img_count > 1 ? 's' : ''}, press V to view".fg(33)
  end
  html_hint = message_has_html?(msg) ? "HTML mail, press x to open in browser".fg(39) : nil

  # Parse calendar invites (ICS attachments)
  cal_text = format_calendar_event(msg['attachments'])

  full_text = header.join("\n")
  full_text += "\n" + att_text if att_text
  full_text += "\n" + image_hint if image_hint
  full_text += "\n" + html_hint if html_hint
  full_text += "\n\n" + cal_text if cal_text
  full_text += "\n\n" + content
  
  @panes[:right].text = full_text
  @panes[:right].refresh

end

#render_message_listObject



1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
# File 'lib/heathrow/ui/application.rb', line 1454

def render_message_list
  # Use threaded view if enabled (never for source view)
  if @show_threaded && @organizer && !@in_source_view
    return render_message_list_threaded
  end
  
  if @filtered_messages.empty?
    # Show empty message in center of pane
    empty_msg = case @current_view
    when 'N'
      "No new messages"
    when /\d/
      "No messages in this view"
    else
      "No messages"
    end

    empty_text = "\n" * (@panes[:left].h / 2 - 1) +
                 empty_msg.center(@panes[:left].w - 2).fg(245)
    @panes[:left].text = empty_text
    @panes[:left].refresh
    return
  end

  # Build ALL messages into one string - let rcurses handle scrolling
  lines = []
  @filtered_messages.each_with_index do |msg, i|
    lines << (@in_source_view ? format_source_line(msg, i == @index) : format_message_line(msg, i == @index))
  end

  # Calculate scroll position
  @panes[:left].scroll = true
  new_text = lines.join("\n")

  page_height = @panes[:left].h
  page_height -= 2 if @panes[:left].border

  old_ix = @panes[:left].ix
  if @filtered_messages.size > page_height
    scrolloff = 3
    max_scroll = @filtered_messages.size - page_height

    if @index - @panes[:left].ix < scrolloff
      @panes[:left].ix = [@index - scrolloff, 0].max
    elsif @panes[:left].ix + page_height - 1 - @index < scrolloff
      @panes[:left].ix = [@index + scrolloff - page_height + 1, max_scroll].min
    end
  else
    @panes[:left].ix = 0
  end

  @panes[:left].text = new_text
  @panes[:left].full_refresh
end

#render_save_folder_picker(idx, title) ⇒ Object



4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
# File 'lib/heathrow/ui/application.rb', line 4516

def render_save_folder_picker(idx, title)
  lines = @folder_display.each_with_index.map do |folder, i|
    indent = "  " * folder[:depth]
    arrow = folder[:has_children] ? (folder[:collapsed] ? "▸ " : "▾ ") : "  "
    if i == idx
      "→ ".fg(226) + indent + arrow.fg(226) + folder[:name].bd.ul.fg(255)
    else
      "  " + indent + arrow.fg(245) + folder[:name].fg(245)
    end
  end

  @panes[:left].text = lines.join("\n")
  # Scroll to keep selected item visible
  page_height = @panes[:left].h
  page_height -= 2 if @panes[:left].border
  if @folder_display.size > page_height
    scrolloff = 3
    max_scroll = @folder_display.size - page_height
    if idx - @panes[:left].ix < scrolloff
      @panes[:left].ix = [idx - scrolloff, 0].max
    elsif @panes[:left].ix + page_height - 1 - idx < scrolloff
      @panes[:left].ix = [idx + scrolloff - page_height + 1, max_scroll].min
    end
  else
    @panes[:left].ix = 0
  end
  @panes[:left].refresh

  @panes[:top].text = " Heathrow - ".bd.fg(255) + title.bd.fg(226)
  @panes[:top].refresh
  @panes[:bottom].text = " j/k:Navigate | Enter:Save here | h/l:Collapse/Expand | ESC:Cancel".fg(245)
  @panes[:bottom].refresh
end

#render_sources_infoObject



7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
# File 'lib/heathrow/ui/application.rb', line 7067

def render_sources_info
  source_text = []
  source_text << "SOURCE MANAGEMENT".bd.fg(226)
  source_text << "=" * 40
  source_text << ""
  
  if @filtered_messages.empty?
    source_text << "No sources configured".fg(245)
    source_text << ""
    source_text << "Press 'a' to add a new source"
    source_text << ""
    source_text << "Available source types:".bd.fg(39)
    types = @source_manager.get_source_types
    types.each do |key, info|
      source_text << "• #{info[:icon]} #{info[:name]}".fg(226)
      source_text << "  #{info[:description]}".fg(245)
    end
  else
    selected = @filtered_messages[@index]
    if selected
      source = @source_manager.sources[selected['id']]
      if source
        source_text << "Selected: #{source['name']}".bd.fg(39)
        source_text << "Type: #{source['plugin_type'] || source['type']}".fg(245)
        source_text << "Status: #{source['enabled'] ? 'Enabled' : 'Disabled'}".fg(source['enabled'] ? 40 : 196)
        interval = (source['poll_interval'] || 900).to_i
        interval_str = if interval <= 0
          "Disabled"
        elsif interval < 60
          "#{interval}s"
        elsif interval < 3600
          "#{interval / 60}m"
        else
          "#{interval / 3600}h#{interval % 3600 > 0 ? " #{(interval % 3600) / 60}m" : ""}"
        end
        source_text << "Poll interval: #{interval_str}".fg(245)
        color_val = source['color']
        if color_val && !color_val.to_s.empty?
          color_num = color_val.to_s =~ /^\d+$/ ? color_val.to_i : color_val.to_s
          source_text << "Color: #{color_val}" + "  ██".fg(color_num)
        else
          auto_color = get_source_color(source)
          source_text << "Color: auto (#{auto_color})" + "  ██".fg(auto_color.to_i)
        end
        # Health status
        health = selected['health_ok'] ? "✓ OK".fg(40) : "✗ #{selected['health_msg']}".fg(196)
        source_text << "Health: #{health}"
        source_text << ""

        config = source['config']
        config = JSON.parse(config) if config.is_a?(String)
        config = {} unless config.is_a?(Hash)
        stype = source['type'] || source['plugin_type']

        if %w[rss web].include?(stype)
          item_name = stype == 'rss' ? 'feed' : 'page'
          items = config[stype == 'rss' ? 'feeds' : 'pages'] || []
          unless items.empty?
            source_text << "#{items.size} #{item_name}s:".bd.fg(245)
            items.each_with_index do |item, i|
              name = item['title'] || item['url'] || item['name'] || "Item #{i}"
              status = item['last_status']
              if status.nil?
                indicator = "  "
              elsif status == 'ok'
                indicator = "✓ ".fg(40)
              else
                indicator = "✗ ".fg(196)
              end
              source_text << "  #{indicator}#{(i+1).to_s.rjust(2)}. #{name}".fg(status == 'ok' ? 252 : (status ? 196 : 245))
              if status && status != 'ok'
                source_text << "      #{status}".fg(88)
              end
            end
            source_text << ""
          end

          # Context-sensitive actions
          source_text << "ACTIONS".bd.fg(226)
          source_text << "-" * 40
          source_text << "a - Add #{item_name}"
          source_text << "d - Remove #{item_name}"
          source_text << "e - Edit source settings"
        else
          # Show config (hide secrets)
          source_text << "Configuration:".bd.fg(39)
          config.each do |key, value|
            next if key.to_s =~ /password|secret|token/
            source_text << "  #{key}: #{value}".fg(245)
          end
          source_text << ""

          # Context-sensitive actions
          source_text << "ACTIONS".bd.fg(226)
          source_text << "-" * 40
          source_text << "a - Add new source"
          source_text << "e - Edit this source"
          source_text << "d - Delete this source"
        end
        source_text << "c - Set color"
        source_text << "p - Set poll interval"
        source_text << "t - Test this source"
        source_text << "SPACE - Enable/disable"
        source_text << "ESC - Back to messages"
      end
    end
  end
  
  @panes[:right].text = source_text.join("\n")
  @panes[:right].refresh
end

#render_top_barObject



1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
# File 'lib/heathrow/ui/application.rb', line 1348

def render_top_bar
  # Ensure we have messages loaded
  @filtered_messages ||= []
  
  # Get current view name and color
  view_name, view_color = case @current_view
  when 'A' 
    if @current_source_filter
      ["Source: #{@current_source_filter}", 39]  # Blue for source filter
    else
      ['All Messages', 226]  # Yellow for all messages
    end
  when 'N' 
    ['New Messages', 40]  # Green for new messages
  when 'S' 
    ['Sources', 201]  # Magenta for sources
  else
    view = @views[@current_view]
    if view
      ["[#{@current_view}] #{view[:name]}", 51]  # Cyan for custom views
    else
      ["View #{@current_view}", 51]
    end
  end
  
  # Get message counts
  if @current_view == 'S'
    # For sources view, show total source count
    total = @filtered_messages.size
    count_text = "#{total} sources"
  else
    # For message views, show unread/total plus starred
    if @cached_unread.nil?
      real_msgs = @filtered_messages.reject { |m| header_message?(m) }
      @cached_unread = real_msgs.count { |m| m['is_read'].to_i == 0 }
      @cached_starred = real_msgs.count { |m| m['is_starred'].to_i == 1 }
      @cached_total = real_msgs.size
    end
    unread = @cached_unread
    starred = @cached_starred
    total = @cached_total
    count_text = "#{unread} unread / #{total} msgs"
    count_text += " / #{starred}*" if starred > 0
  end
  
  # Build colored components
  title_part = " Heathrow - ".fg(248)
  view_part = view_name.bd.fg(255)

  # Add sort order info (only for message views, not Sources)
  sort_part = ""
  if @current_view != 'S'
    sort_text = case @sort_order
               when 'latest' then 'Latest'
               when 'alphabetical' then 'A-Z'
               when 'sender' then 'Sender'
               when 'from' then 'From'
               when 'unread' then 'Unread'
               when 'source' then 'Source'
               else @sort_order.capitalize
               end
    # Add arrow - ↓ for normal order (o key), ↑ for inverted (i key)
    invert_indicator = @sort_inverted ? "↑" : "↓"
    sort_part = " [#{sort_text}#{invert_indicator}]".fg(252)
  end

  # Threading mode indicator
  mode_part = ""
  if @current_view != 'S'
    mode_part = " [#{thread_mode_label}]".fg(245)
  end

  # Position indicator
  pos_text = ""
  if @current_view != 'S' && !@filtered_messages.empty?
    display = @show_threaded ? (@display_messages || @filtered_messages) : @filtered_messages
    pos_text = " [#{@index + 1}/#{display.size}]"
  end

  count_part = " #{count_text}".fg(252)
  pos_part = pos_text.fg(252)

  # Calculate padding
  mode_plain = mode_part.gsub(/\e\[[0-9;]*m/, '')
  plain_length = " Heathrow - ".length + view_name.length + sort_part.gsub(/\e\[[0-9;]*m/, '').length + mode_plain.length + pos_text.length + " #{count_text}".length
  padding = @w - plain_length - 1
  padding = 1 if padding < 1
  spaces = " " * padding

  # Combine with colors - ensure message count is always visible
  full_text = title_part + view_part + sort_part + mode_part + pos_part + spaces + count_part
  
  # Apply per-view top bar background color if set
  view = @views[@current_view]
  custom_bg = view[:filters]['top_bg'] if view && view[:filters].is_a?(Hash)
  top_bg = custom_bg ? parse_color_value(custom_bg) || @topcolor : @topcolor
  if @panes[:top].bg != top_bg
    @panes[:top].bg = top_bg
    @panes[:top].full_refresh
  end

  # Set text and refresh only if changed
  @panes[:top].text = full_text
  @panes[:top].refresh
end

#reply_all_to_messageObject



5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
# File 'lib/heathrow/ui/application.rb', line 5308

def reply_all_to_message
  msg = current_message
  return unless msg
  msg = ensure_full_message(msg)
  source_id = msg['source_id']
  
  # Check if source supports replying
  source = @db.get_source_by_id(source_id)
  return unless source
  
  require_relative '../message_composer'
  identity = current_identity(msg)
  composer = MessageComposer.new(msg, identity: identity, address_book: @address_book, editor_args: @editor_args)

  # Show composing status
  @panes[:bottom].text = " Opening editor for reply all...".fg(226)
  @panes[:bottom].refresh

  # Compose the reply
  composed = composer.compose_reply(true)

  setup_display
  create_panes
  render_all
  if composed
    finalize_compose(source, composed, "Reply-all cancelled")
  else
    set_feedback("Reply-all cancelled", 245, 1)
  end
end

#reply_to_message(force_editor: false) ⇒ Object



5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
# File 'lib/heathrow/ui/application.rb', line 5195

def reply_to_message(force_editor: false)
  msg = current_message
  return unless msg
  msg = ensure_full_message(msg)

  # Don't allow replying to header messages
  if header_message?(msg)
    set_feedback("Cannot reply to section headers. Select a message.", 226, 3)
    render_bottom_bar
    return
  end

  source_id = msg['source_id']
  source = @db.get_source_by_id(source_id)
  return unless source

  source_type = source['plugin_type'] || source['type']

  if CHAT_SOURCE_TYPES.include?(source_type) && !force_editor
    chat_reply_inline(msg, source, source_type)
  elsif CHAT_SOURCE_TYPES.include?(source_type) && force_editor
    chat_reply_editor(msg, source, source_type)
  else
    # Email reply: full editor
    require_relative '../message_composer'
    identity = current_identity(msg)
    composer = MessageComposer.new(msg, identity: identity, address_book: @address_book, editor_args: @editor_args)

    @panes[:bottom].text = " Opening editor for reply...".fg(226)
    @panes[:bottom].refresh

    composed = composer.compose_reply(false)
    setup_display
    create_panes
    render_all
    if composed
      finalize_compose(source, composed, "Reply cancelled")
    else
      set_feedback("Reply cancelled", 245, 1)
    end
  end
end

#runObject



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
# File 'lib/heathrow/ui/application.rb', line 391

def run
  # Check database size BEFORE initializing rcurses
  @total_message_count = @db.get_stats[:total_messages]

  # Show loading info before rcurses takes over the screen
  puts "Loading Heathrow..."
  puts "Database: #{@total_message_count} messages"
  if @total_message_count > 10000
    puts "Large database - loading most recent 1000 messages"
    puts "(Use views to filter, press 'N' for unread)"
    sleep 1
  end

  # EXACTLY LIKE RTFM
  # Initialize rcurses
  Rcurses.init!

  # Clear screen to remove any artifacts
  Rcurses.clear_screen

  # Get terminal size
  setup_display

  # Create panes and show skeleton immediately
  create_panes
  @current_view = @default_view || 'A'
  render_top_bar
  @panes[:left].text = "\n\n" + "  Loading...".fg(245)
  @panes[:left].refresh
  render_bottom_bar

  # First-time onboarding wizard
  if @db.get_sources(false).empty?
    run_onboarding_wizard
  end

  # Load initial view data in background so input loop starts immediately
  @initial_load_done = false
  Thread.new do
    begin
      @load_limit = 200
      case @default_view
      when 'N'
        @filtered_messages = @db.get_messages({is_read: false}, @load_limit, 0, light: true)
      when /^[0-9]$/, /^F\d+$/
        view = @views[@default_view]
        if view && view[:filters] && !view[:filters].empty?
          if view[:filters]['section_order']
            @section_order = view[:filters]['section_order'].dup
          end
          apply_view_filters(view)
        else
          @filtered_messages = @db.get_messages({}, @load_limit, 0, light: true)
          @current_view = 'A'
        end
      else
        @filtered_messages = @db.get_messages({}, @load_limit, 0, light: true)
        @current_view = 'A'
      end
      sort_messages
      @index = 0
      reset_threading
      restore_view_thread_mode
      @initial_load_done = true
      @needs_redraw = true
      # Preload the heavy mail gem so 'v' (attachments) doesn't lag
      require 'mail' rescue nil
    rescue => e
      File.open('/tmp/heathrow_debug.log', 'a') { |f| f.puts "STARTUP ERROR: #{e.message}\n#{e.backtrace.first(5).join("\n")}" }
      @filtered_messages = []
      @initial_load_done = true
      @needs_redraw = true
    end
  end

  # Wait for initial data load before entering main loop
  until @initial_load_done
    sleep 0.05
  end

  # Flush stdin before loop (CRITICAL - FROM RTFM)
  $stdin.getc while $stdin.wait_readable(0)

  # Main loop (like RTFM)
  @running = true
  @pending_view_refresh = false
  @editing = false
  @needs_redraw = true
  loop do
    if @pending_view_refresh && !@editing
      @pending_view_refresh = false
      # Only reload view data if we're in a named view (not a folder browse or source view)
      unless @current_folder || @in_source_view
        # Remember selected message by ID so we can restore position after rebuild
        selected_msg = current_message
        selected_id = selected_msg['id'] if selected_msg
        view = @views[@current_view]
        if view && view[:filters] && !view[:filters].empty?
          apply_view_filters(view)
          sort_messages
        end
        # Force re-organization in threaded mode
        if @show_threaded
          reset_threading(true)
          organize_current_messages(true)
        end
        # Defer index restoration for threaded views (display_messages is empty
        # after reset_threading; it gets populated during render). For flat views,
        # resolve immediately since @filtered_messages is the navigation list.
        if @show_threaded
          @pending_restore_id = selected_id
          @index = 0
        elsif selected_id
          new_idx = @filtered_messages.index { |m| m['id'] == selected_id }
          max_idx = @filtered_messages.size - 1
          @index = new_idx || [@index, max_idx].min
        else
          @index = [@index, @filtered_messages.size - 1].min
        end
        @index = 0 if @index < 0
      end
      @needs_redraw = true
    end
    # Check if feedback expired
    if @feedback_expires_at && Time.now >= @feedback_expires_at
      @needs_redraw = true
    end
    if @needs_redraw && !@editing
      render_all
      @needs_redraw = false
    end
    # Check for mailto trigger (from wezterm or external script)
    check_mailto_trigger

    chr = getchr(2, flush: false)  # 2s timeout to check for new mail
    begin
      if chr
        # Clear sticky feedback (errors, "message sent") on any keypress
        if @feedback_sticky
          @feedback_sticky = false
          @feedback_expires_at = Time.now  # Expire now so render_bottom_bar clears it
        end
        @needs_redraw = false  # Handlers that need redraw call render_all directly
        handle_input_key(chr)
      else
        check_new_mail
      end
    rescue => e
      # Non-fatal: log and show feedback instead of crashing
      File.open('/tmp/heathrow-crash.log', 'a') do |f|
        loc = e.backtrace&.first&.sub(/^.*lib\/heathrow\//, '')
        f.puts "#{Time.now.strftime('%Y-%m-%d %H:%M:%S')} ERROR: #{e.class}: #{e.message} at #{loc}"
        e.backtrace&.first(10)&.each { |l| f.puts "    #{l}" }
        f.puts
      end
      set_feedback("Error: #{e.message} (logged to /tmp/heathrow-crash.log)", 196, 5)
      @needs_redraw = true
    end
    break unless @running
  end
ensure
  cleanup
end

#run_compose_plugin(plugin) ⇒ Object



5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
# File 'lib/heathrow/ui/application.rb', line 5730

def run_compose_plugin(plugin)
  pick_file = "/tmp/heathrow_plugin_pick_#{Process.pid}.txt"
  File.delete(pick_file) if File.exist?(pick_file)

  # Flush any queued input, restore terminal, clear screen
  $stdin.getc while $stdin.wait_readable(0)
  system("stty sane 2>/dev/null")
  Cursor.show
  print "\e[2J\e[H"  # Clear screen + home cursor

  cmd = plugin[:command].gsub('%{pick_file}', Shellwords.escape(pick_file))
  system(cmd)

  $stdin.raw!
  $stdin.echo = false
  Cursor.hide
  Rcurses.clear_screen
  setup_display
  create_panes
  render_all

  if File.exist?(pick_file)
    files = File.read(pick_file).lines.map(&:strip).reject(&:empty?)
    File.delete(pick_file) rescue nil
    files.select { |f| File.exist?(f) && File.file?(f) }
  else
    []
  end
end

#run_custom_binding(binding) ⇒ Object

Run a custom keybinding defined in heathrowrc



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
# File 'lib/heathrow/ui/application.rb', line 858

def run_custom_binding(binding)
  if binding[:action]
    # Call a Heathrow method by name
    method_name = binding[:action].to_sym
    if respond_to?(method_name, true)
      send(method_name)
    else
      set_feedback("Unknown action: #{method_name}", 196, 3)
    end
    return
  end

  return unless binding[:shell]

  cmd = binding[:shell].dup

  # Substitute placeholders (shell-escaped for safety)
  if cmd.include?('%q')
    prompt_text = binding[:prompt] || "Query: "
    query = bottom_ask(prompt_text, "")
    return if query.nil? || query.strip.empty?
    cmd.gsub!('%q', Shellwords.escape(query))
  end
  if cmd.include?('%f')
    msg = current_message
    if msg
      meta = msg['metadata']
      meta = JSON.parse(meta) if meta.is_a?(String) rescue {}
      file_path = meta['maildir_file'] || msg['external_id'] || ''
      cmd.gsub!('%f', Shellwords.escape(file_path))
    else
      cmd.gsub!('%f', '')
    end
  end
  if cmd.include?('%i')
    msg = current_message
    msg_id = msg ? (msg['message_id'] || msg['external_id'] || '') : ''
    cmd.gsub!('%i', Shellwords.escape(msg_id))
  end
  if cmd.include?('%s')
    msg = current_message
    subject = msg ? (msg['subject'] || '') : ''
    cmd.gsub!('%s', Shellwords.escape(subject))
  end

  # Run the command with terminal restored (same pattern as run_rtfm_picker)
  system("stty sane 2>/dev/null")
  Cursor.show
  system(cmd)

  # Restore raw mode and redraw UI
  $stdin.raw!
  $stdin.echo = false
  Cursor.hide
  Rcurses.clear_screen
  setup_display
  create_panes
  render_all
end

#run_editor(path, cursor_line: nil, insert_mode: false) ⇒ Object

Run an external editor, restoring terminal state before/after



2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
# File 'lib/heathrow/ui/application.rb', line 2221

def run_editor(path, cursor_line: nil, insert_mode: false)
  editor = ENV['EDITOR'] || 'vim'
  # Restore terminal to cooked mode for the editor
  system("stty sane 2>/dev/null")
  print "\e[?25h"  # show cursor
  vim_args = ""
  if editor =~ /vim?\b/
    vim_args += " +#{cursor_line}" if cursor_line
    vim_args += " -c 'startinsert!'" if insert_mode
  end
  system("#{editor}#{vim_args} #{Shellwords.escape(path)}")
  success = $?.success?
  # Restore raw mode for rcurses
  $stdin.raw!
  $stdin.echo = false
  print "\e[?25l"  # hide cursor
  Rcurses.clear_screen
  setup_display
  create_panes
  render_all
  success
end

#run_onboarding_wizardObject

Check for new mail — called on getchr timeout (every 2s idle) Syncs each source based on its poll_interval setting

First-time Onboarding Wizard ==========


7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
# File 'lib/heathrow/ui/application.rb', line 7760

def run_onboarding_wizard
  rows, cols = IO.console.winsize
  pw = [cols - 10, 70].min
  ph = [rows - 6, 30].min
  px = (cols - pw) / 2
  py = (rows - ph) / 2

  popup = Rcurses::Pane.new(px, py, pw, ph, 252, 0)
  popup.border = true
  popup.scroll = true

  welcome = []
  welcome << ""
  welcome << "  " + "Welcome to Heathrow!".bd.fg(226)
  welcome << "  " + "Where all your messages connect.".fg(245)
  welcome << ""
  welcome << "  " + "\u2500" * [pw - 6, 1].max
  welcome << ""
  welcome << "  No message sources configured yet."
  welcome << "  Let's get you started with your first source."
  welcome << ""
  welcome << "  Available source types:".bd.fg(39)
  welcome << ""
  welcome << "  " + "1".fg(226) + " - Maildir (local email, works with offlineimap/mbsync/fetchmail)"
  welcome << "  " + "2".fg(226) + " - RSS/Atom feeds"
  welcome << "  " + "3".fg(226) + " - WeeChat relay (IRC, Slack via WeeChat)"
  welcome << "  " + "4".fg(226) + " - Discord"
  welcome << "  " + "5".fg(226) + " - Telegram"
  welcome << "  " + "6".fg(226) + " - Instagram DMs"
  welcome << "  " + "7".fg(226) + " - Messenger"
  welcome << ""
  welcome << "  " + "s".fg(226) + " - Skip (configure later via 'S' for Sources)"
  welcome << ""
  welcome << "  " + "Pick a number to add your first source.".fg(245)

  popup.text = welcome.join("\n")
  popup.refresh

  loop do
    chr = getchr
    case chr
    when '1'
      popup_add_maildir
      break
    when '2'
      popup_add_rss
      break
    when '3'
      popup_add_weechat
      break
    when '4'..'7'
      set_feedback("Configure this source via 'S' (Sources) after startup", 226, 5)
      break
    when 's', 'S', 'ESC', 'q'
      break
    end
  end

  Rcurses.clear_screen
  setup_display
  create_panes
  render_all
end

#run_rtfm_pickerObject

Launch RTFM in file picker mode, return array of selected file paths



5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
# File 'lib/heathrow/ui/application.rb', line 5679

def run_rtfm_picker
  pick_file = "/tmp/rtfm_pick_#{Process.pid}.txt"
  File.delete(pick_file) if File.exist?(pick_file)

  # Flush input, restore terminal for RTFM
  $stdin.getc while $stdin.wait_readable(0)
  system("stty sane 2>/dev/null")
  Cursor.show

  system("rtfm --pick=#{Shellwords.escape(pick_file)}")

  # Restore raw mode and redraw UI
  $stdin.raw!
  $stdin.echo = false
  Cursor.hide
  Rcurses.clear_screen
  setup_display
  create_panes
  render_all

  if File.exist?(pick_file)
    files = File.read(pick_file).lines.map(&:strip).reject(&:empty?)
    File.delete(pick_file) rescue nil
    files.select { |f| File.exist?(f) && File.file?(f) }
  else
    []
  end
end

#safe_get_messages(filters = {}, custom_limit = nil, light: true) ⇒ Object

Helper method to safely get messages with automatic pagination for large databases



339
340
341
342
343
344
345
346
347
# File 'lib/heathrow/ui/application.rb', line 339

def safe_get_messages(filters = {}, custom_limit = nil, light: true)
  # Use custom limit if provided, otherwise auto-paginate for large DBs
  limit = custom_limit
  if limit.nil? && (@total_message_count || 0) > 10000
    limit = 1000  # Default limit for large databases
  end

  @db.get_messages(filters, limit, 0, light: light)
end

#save_attachments(maildir_file, attachments, indices) ⇒ Object



3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
# File 'lib/heathrow/ui/application.rb', line 3347

def save_attachments(maildir_file, attachments, indices)
  download_dir = @download_folder || @config.get('download_folder') || '~/Downloads'
  download_dir = File.expand_path(download_dir)
  if indices.size == 1
    att = attachments[indices[0]]
    name = att['name'] || att['filename'] || 'unnamed'
    default_path = File.join(download_dir, name)
    save_path = bottom_ask("Save to: ", default_path)
    return if save_path.nil? || save_path.strip.empty?
    save_path = File.expand_path(save_path.strip)
  else
    save_path = bottom_ask("Save #{indices.size} files to folder: ", download_dir)
    return if save_path.nil? || save_path.strip.empty?
    save_path = File.expand_path(save_path.strip)
  end

  mail = load_mail_file(maildir_file)
  return unless mail
  saved = 0
  indices.each do |i|
    att = attachments[i]
    mail_att = find_mail_attachment(mail, att)
    next unless mail_att
    if indices.size == 1
      dest = save_path
    else
      dest = File.join(save_path, mail_att.filename)
    end
    FileUtils.mkdir_p(File.dirname(dest))
    File.open(dest, 'wb') { |f| f.write(mail_att.body.decoded) }
    saved += 1
  end
  set_feedback("Saved #{saved} attachment#{saved != 1 ? 's' : ''}", 156, 2)
end

#save_browse_favoritesObject

── Save by browsing favorites (sF) ──



4444
4445
4446
4447
4448
4449
4450
# File 'lib/heathrow/ui/application.rb', line 4444

def save_browse_favorites
  favorites = get_favorite_folders
  @folder_display = favorites.map do |name|
    { name: name, full_name: name, depth: 0, has_children: false, collapsed: false }
  end
  save_folder_picker_loop("Save to Favorite")
end

#save_browse_foldersObject

── Save by browsing folders (sB) ── Opens the folder browser in "save mode": Enter picks the destination folder. Returns the chosen folder name, or nil if cancelled.



4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
# File 'lib/heathrow/ui/application.rb', line 4426

def save_browse_folders
  @folder_collapsed ||= {}
  maildir_path = File.expand_path('~/Maildir')
  folder_names = ['INBOX']
  Dir.glob(File.join(maildir_path, '.*')).sort.each do |dir|
    bn = File.basename(dir)
    next if bn == '.' || bn == '..'
    next unless File.directory?(dir)
    next unless File.directory?(File.join(dir, 'cur')) || File.directory?(File.join(dir, 'new'))
    folder_names << bn.sub(/^\./, '')
  end

  @folder_tree = build_folder_tree(folder_names)
  @folder_display = flatten_folder_tree(@folder_tree, '', 0, @folder_collapsed)
  save_folder_picker_loop("Save to Folder")
end

#save_custom_theme(name, colors) ⇒ Object



6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
# File 'lib/heathrow/ui/application.rb', line 6368

def save_custom_theme(name, colors)
  rc_path = Config::HEATHROWRC
  return unless File.exist?(rc_path)

  content = File.read(rc_path)

  # Build the theme line
  # Only include keys that differ from Default
  default = COLOR_THEMES['Default']
  diff = colors.select { |k, v| v != default[k] }
  return if diff.empty?

  pairs = diff.map { |k, v| "#{k}: #{v}" }.join(", ")
  theme_line = "theme '#{name}', #{pairs}"

  # Replace existing theme definition or append
  pattern = /^theme\s+'#{Regexp.escape(name)}'.*/
  if content.match?(pattern)
    content.sub!(pattern, theme_line)
  else
    # Insert before the first blank line after the last theme line, or at end
    if content.include?("# \u2500\u2500 Views")
      content.sub!(/^(# \u2500\u2500 Views)/, "#{theme_line}\n\n\\1")
    else
      content << "\n#{theme_line}\n"
    end
  end

  File.write(rc_path, content)

  # Reload config to pick up the new theme
  @config.reload_rc
end

#save_favorite_folders(favorites) ⇒ Object



4110
4111
4112
4113
4114
4115
4116
# File 'lib/heathrow/ui/application.rb', line 4110

def save_favorite_folders(favorites)
  now = Time.now.to_i
  @db.execute(
    "INSERT OR REPLACE INTO settings (key, value, updated_at) VALUES (?, ?, ?)",
    'favorite_folders', favorites.to_json, now
  )
end

#save_folder_picker_loop(title) ⇒ Object

Shared folder picker loop for save operations. Renders the folder list in the left pane, user picks with Enter. Returns chosen folder name or nil.



4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
# File 'lib/heathrow/ui/application.rb', line 4455

def save_folder_picker_loop(title)
  return nil if @folder_display.empty?
  idx = 0

  render_save_folder_picker(idx, title)

  loop do
    chr = getchr
    case chr
    when 'j', 'DOWN'
      idx = (idx + 1) % @folder_display.size
      render_save_folder_picker(idx, title)
    when 'k', 'UP'
      idx = (idx - 1) % @folder_display.size
      render_save_folder_picker(idx, title)
    when 'l', 'RIGHT'
      folder = @folder_display[idx]
      if folder && folder[:has_children] && folder[:collapsed]
        @folder_collapsed.delete(folder[:full_name])
        @folder_display = flatten_folder_tree(@folder_tree, '', 0, @folder_collapsed)
        render_save_folder_picker(idx, title)
      elsif folder
        render_all
        return folder[:full_name]
      end
    when 'h', 'LEFT'
      folder = @folder_display[idx]
      if folder && folder[:has_children] && !folder[:collapsed]
        @folder_collapsed[folder[:full_name]] = true
        @folder_display = flatten_folder_tree(@folder_tree, '', 0, @folder_collapsed)
        render_save_folder_picker(idx, title)
      elsif folder && folder[:depth] > 0
        parent_name = folder[:full_name].split('.')[0..-2].join('.')
        parent_idx = @folder_display.index { |f| f[:full_name] == parent_name }
        idx = parent_idx if parent_idx
        render_save_folder_picker(idx, title)
      end
    when 'PgDOWN'
      idx = [idx + (@panes[:left].h - 2), @folder_display.size - 1].min
      render_save_folder_picker(idx, title)
    when 'PgUP'
      idx = [idx - (@panes[:left].h - 2), 0].max
      render_save_folder_picker(idx, title)
    when 'HOME'
      idx = 0
      render_save_folder_picker(idx, title)
    when 'END'
      idx = @folder_display.size - 1
      render_save_folder_picker(idx, title)
    when 'ENTER'
      folder = @folder_display[idx]
      render_all
      return folder[:full_name] if folder
      return nil
    when 'q', 'ESC', "\e"
      render_all
      return nil
    end
  end
end

#save_folder_shortcutsObject

Save folder shortcuts — configurable in ~/.heathrow/config.yml under save_folders:

save_folders:
"1": "Geir.Personal"
"2": "AA.Archive"
"3": "Projects.Archive"
"4": "Work.Archive"


4286
4287
4288
4289
4290
4291
4292
# File 'lib/heathrow/ui/application.rb', line 4286

def save_folder_shortcuts(shortcuts)
  now = Time.now.to_i
  @db.execute(
    "INSERT OR REPLACE INTO settings (key, value, updated_at) VALUES (?, ?, ?)",
    'folder_shortcuts', shortcuts.to_json, now
  )
end

#save_view_sort_orderObject



6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
# File 'lib/heathrow/ui/application.rb', line 6548

def save_view_sort_order
  view = @views[@current_view]
  if view && view[:filters].is_a?(Hash)
    # Save per-view
    view[:filters]['view_sort_order'] = @sort_order
    view[:filters]['view_sort_inverted'] = @sort_inverted
    @db.execute("UPDATE views SET filters = ?, updated_at = ? WHERE id = ?",
                [JSON.generate(view[:filters]), Time.now.to_i, view[:id]])
  else
    # Global fallback for built-in views (A, N)
    @config.set('ui.sort_order', @sort_order)
    @config.save
  end
end

#selected_source_has_items?Boolean

Check if the selected source has manageable sub-items (feeds, channels, etc.)



944
945
946
947
948
# File 'lib/heathrow/ui/application.rb', line 944

def selected_source_has_items?
  return false unless @filtered_messages[@index]
  source_type = @filtered_messages[@index]['source_type']
  %w[rss web].include?(source_type)
end

#send_composed_message(source, composed) ⇒ Object



5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
# File 'lib/heathrow/ui/application.rb', line 5893

def send_composed_message(source, composed)
  # Warn about empty subject (like mutt) - this part stays synchronous
  if composed[:subject] == '(no subject)'
    confirm = bottom_ask("No subject, send anyway? [y/N] ")
    unless confirm&.strip&.downcase == 'y'
      set_feedback("Send cancelled", 245, 2)
      return
    end
  end

  source_type = source['plugin_type'] || source['type']

  # Load source module and create instance (fast, keep synchronous)
  module_name = source_type == 'web' ? 'webpage' : source_type
  require_relative "../sources/#{module_name}"

  class_name = case module_name
               when 'rss' then 'RSS'
               when 'webpage' then 'Webpage'
               else module_name.capitalize
               end
  source_class = Heathrow::Sources.const_get(class_name)

  instance = begin
    config = source['config']
    config = JSON.parse(config) if config.is_a?(String)
    source_class.new(source['name'], config || {}, @db)
  rescue ArgumentError
    source_class.new(source)
  end

  unless instance.respond_to?(:send_message)
    set_feedback("This source doesn't support sending messages", 196, 4)
    return
  end

  # Show sending indicator and return control to UI immediately
  label = CHAT_SOURCE_TYPES.include?(source_type) ? "Sending #{source_type} message" : "Sending"
  set_feedback("#{label}...", 226, 0)
  render_bottom_bar

  # Capture values needed by the thread
  orig_msg = composed[:original_message]
  orig_id = orig_msg['id'] if orig_msg

  Thread.new do
    begin
      result = if CHAT_SOURCE_TYPES.include?(source_type)
        target = composed[:to]
        if target.nil? || target.empty?
          if orig_msg && orig_msg['metadata']
            meta = orig_msg['metadata']
            meta = JSON.parse(meta) if meta.is_a?(String)
            target = meta['buffer'] || meta['thread_id'] || meta['conversation_id'] ||
                     meta['chat_jid'] || meta['channel_id'] || meta['chat_id'] if meta.is_a?(Hash)
          end
        end
        instance.send_message(target, composed[:subject], composed[:body])
      else
        in_reply_to = nil
        if orig_msg && orig_msg['metadata']
           = JSON.parse(orig_msg['metadata']) rescue {}
          in_reply_to = ['message_id']
        end

        identity = current_identity(orig_msg)
        smtp_cmd = identity ? identity[:smtp] : nil
        from = composed[:from]
        from = identity[:from] if (from.nil? || from.empty?) && identity

        instance.send_message(
          composed[:to],
          composed[:subject],
          composed[:body],
          in_reply_to,
          from: from,
          cc: composed[:cc],
          bcc: composed[:bcc],
          reply_to: composed[:reply_to],
          extra_headers: composed[:extra_headers],
          smtp_command: smtp_cmd,
          attachments: composed[:attachments]
        )
      end

      if result[:success]
        if orig_id
          # Re-read metadata from DB to get current maildir_file path
          # (poller may have renamed the file since we captured orig_msg)
          fresh = @db.get_message(orig_id)
          if fresh
            orig_msg = fresh
          end
          # Sync disk flag first, then DB, to avoid poller race condition
          sync_maildir_flag(orig_msg, 'R', true) if orig_msg
          @db.execute("UPDATE messages SET replied = 1 WHERE id = ?", [orig_id])
          orig_msg['replied'] = 1 if orig_msg
        end
        msg = result[:message]
        if composed[:attachments] && !composed[:attachments].empty?
          msg += " (#{composed[:attachments].size} attachment(s))"
        end
        set_feedback(msg, 156, 0)
        render_message_list if orig_id
      else
        set_feedback(result[:message], 196, 4)
      end
    rescue => e
      set_feedback("Send error: #{e.message}", 196, 4)
      File.open('/tmp/heathrow_debug.log', 'a') { |f| f.puts "#{Time.now} send_composed_message error: #{e.message}\n#{e.backtrace.first(5).join("\n")}" }

    end
  end
end

#set_bordersObject



182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
# File 'lib/heathrow/ui/application.rb', line 182

def set_borders
  case @border
  when 0
    @panes[:left].border = false
    @panes[:right].border = false
  when 1
    @panes[:left].border = false
    @panes[:right].border = true
  when 2
    @panes[:left].border = true
    @panes[:right].border = true
  when 3
    @panes[:left].border = true
    @panes[:right].border = false
  end
end

#set_feedback(message, color = 156, duration = 3) ⇒ Object



2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
# File 'lib/heathrow/ui/application.rb', line 2244

def set_feedback(message, color = 156, duration = 3)
  @feedback_message = message
  @feedback_color = color
  # duration 0 or errors: persist until next user action (cleared by clear_sticky_feedback)
  @feedback_sticky = (duration == 0 || color == 196)
  @feedback_expires_at = if @feedback_sticky
    nil  # Never auto-expire; cleared on keypress
  else
    Time.now + duration
  end
  if @panes[:bottom]
    @panes[:bottom].text = " #{message}".fg(color)
    @panes[:bottom].refresh
  end
end

#set_source_poll_intervalObject



7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
# File 'lib/heathrow/ui/application.rb', line 7391

def set_source_poll_interval
  return unless @in_source_view && @filtered_messages[@index]
  source_id = @filtered_messages[@index]['id']
  source = @source_manager.sources[source_id]
  return unless source

  current = (source['poll_interval'] || 900).to_i
  current_str = if current <= 0
    "0 (disabled)"
  elsif current < 60
    "#{current}s"
  elsif current < 3600
    "#{current / 60}m"
  else
    "#{current / 3600}h"
  end

  lines = []
  lines << "POLL INTERVAL for #{source['name']}".bd.fg(226)
  lines << "=" * 40
  lines << ""
  lines << "Current: #{current_str}".fg(245)
  lines << ""
  lines << "Enter interval (examples):".fg(39)
  lines << "  30s   = 30 seconds"
  lines << "  5m    = 5 minutes"
  lines << "  1h    = 1 hour"
  lines << "  0     = disabled"
  lines << ""
  lines << "Recommended:".fg(245)
  lines << "  Maildir: 30s (fast local scan)"
  lines << "  RSS/Web: 15m"
  lines << "  Messenger/Instagram: 5m"
  lines << "  Weechat: 2m"

  @panes[:right].text = lines.join("\n")
  @panes[:right].refresh

  @panes[:bottom].prompt = "Interval: "
  @panes[:bottom].text = ""
  @editing = true
  @panes[:bottom].editline
  @editing = false
  input = @panes[:bottom].text.strip

  seconds = parse_interval(input)
  if seconds.nil?
    set_feedback("Invalid interval format", 196, 2)
  else
    @db.execute("UPDATE sources SET poll_interval = ? WHERE id = ?", seconds, source_id)
    @source_last_sync&.delete("#{source['plugin_type']}_#{source_id}")
    label = seconds == 0 ? "disabled" : "#{seconds}s"
    set_feedback("Poll interval set to #{label}", 40, 2)
    @source_manager.reload
    saved_index = @index
    show_sources
    @index = saved_index
    render_message_list
    render_sources_info
    return
  end

  render_sources_info
end

#set_view_top_bgObject



7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
# File 'lib/heathrow/ui/application.rb', line 7355

def set_view_top_bg
  view = @views[@current_view]
  unless view
    set_feedback("No custom view selected", 196, 2)
    return
  end

  current_bg = (view[:filters].is_a?(Hash) && view[:filters]['top_bg']) || @topcolor
  input = bottom_ask("Top bar bg (0-255/hex/empty=default): ", current_bg.to_s)
  return render_all if input.nil?

  view[:filters] ||= {}
  if input.strip.empty?
    view[:filters].delete('top_bg')
  else
    color = parse_color_value(input.strip)
    unless color
      set_feedback("Invalid color", 196, 2)
      return
    end
    view[:filters]['top_bg'] = input.strip
  end

  # Save to DB
  if view[:id]
    @db.save_view({
      id: view[:id],
      name: view[:name],
      key_binding: @current_view,
      filters: view[:filters],
      sort_order: view[:sort_order] || 'timestamp DESC'
    })
  end
  render_all
end

#setup_displayObject



126
127
128
129
130
131
132
133
134
135
136
# File 'lib/heathrow/ui/application.rb', line 126

def setup_display
  # Get terminal dimensions like GiTerm does
  require 'io/console'
  if IO.console
    @h, @w = IO.console.winsize
  else
    # Fallback for non-terminal environments
    @h = ENV['LINES']&.to_i || 24
    @w = ENV['COLUMNS']&.to_i || 80
  end
end

#show_all_labelsObject

Show all labels currently in use across all messages



4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
# File 'lib/heathrow/ui/application.rb', line 4660

def show_all_labels
  rows = @db.execute("SELECT labels FROM messages WHERE labels IS NOT NULL AND labels != '[]'")
  label_counts = Hash.new(0)
  rows.each do |row|
    labels = JSON.parse(row['labels']) rescue next
    labels.each { |l| label_counts[l] += 1 } if labels.is_a?(Array)
  end

  if label_counts.empty?
    set_feedback("No labels in use", 245, 2)
    return
  end

  lines = ["LABELS IN USE".bd.fg(226), ""]
  label_counts.sort_by { |_, c| -c }.each do |label, count|
    lines << "  #{label}".fg(51) + " (#{count})".fg(245)
  end
  lines << ""
  lines << "Use 'l' to add/remove labels.".fg(245)
  lines << "Filter views on labels with 'F' (label field).".fg(245)
  @panes[:right].text = lines.join("\n")
  @panes[:right].refresh
end

#show_all_messagesObject



1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
# File 'lib/heathrow/ui/application.rb', line 1907

def show_all_messages
  flush_pending_read
  invalidate_counts
  @current_view = 'A'
  @current_folder = nil
  @in_source_view = false
  @panes[:right].content_update = true
  @current_source_filter = nil
  @sort_order = @config.rc('sort_order', 'latest')
  @sort_inverted = false
  @last_rendered_index = nil  # Force right pane refresh

  # Restore per-view threading mode
  reset_threading
  restore_view_thread_mode

  # Show view name instantly
  render_top_bar

  @load_limit = 200
  @filtered_messages = @db.get_messages({}, @load_limit, 0, light: true)
  sort_messages
  @index = 0
  render_all
  track_browsed_message
end

#show_extended_helpObject



6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
# File 'lib/heathrow/ui/application.rb', line 6725

def show_extended_help
  @in_help_mode = true
  @panes[:right].content_update = false
  @panes[:right].ix = 0  # Reset scroll position
  
  # Try to read README.md for comprehensive help
  readme_path = File.join(File.dirname(__FILE__), '..', '..', '..', 'README.md')
  
  if File.exist?(readme_path)
    readme_text = File.read(readme_path)
    colored_text = colorize_markdown(readme_text)
    @panes[:right].text = colored_text
    @panes[:right].refresh
  else
    # Show extended help text
    @panes[:right].text = get_extended_help_text
    @panes[:right].refresh
  end
  
  @showing_help = false  # Reset for next time
end

#show_favorites_browserObject



4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
# File 'lib/heathrow/ui/application.rb', line 4118

def show_favorites_browser
  favorites = get_favorite_folders
  @in_folder_browser = true
  @in_favorites_browser = true
  @folder_browser_index = 0
  @panes[:top].bg = @topcolor
  @folder_count_cache = {}  # Fresh counts each time

  # Build display from favorites only (no DB queries — counts fetched on select)
  @folder_display = favorites.map do |name|
    {
      name: name,
      full_name: name,
      depth: 0,
      has_children: false,
      collapsed: false
    }
  end

  render_folder_browser
  @panes[:top].text = " Heathrow - ".bd.fg(255) + "Favorites".bd.fg(226) + " [#{favorites.size} folders]".fg(246)
  @panes[:top].refresh
  @panes[:bottom].text = " j/k:Navigate | Enter:Open | C-Up/C-Down:Reorder | B:All folders | +:Remove fav | ESC:Back".fg(245)
  @panes[:bottom].refresh

  loop do
    chr = getchr
    case chr
    when 'j', 'DOWN'
      @folder_browser_index = (@folder_browser_index + 1) % @folder_display.size if @folder_display.size > 0
      render_folder_browser
    when 'k', 'UP'
      @folder_browser_index = (@folder_browser_index - 1) % @folder_display.size if @folder_display.size > 0
      render_folder_browser
    when 'l', 'RIGHT', 'ENTER'
      folder = @folder_display[@folder_browser_index]
      if folder
        open_folder(folder[:full_name])
        break
      end
    when 'B'
      # Switch to full folder browser
      show_folder_browser
      break
    when '+'
      # Remove selected folder from favorites
      folder = @folder_display[@folder_browser_index]
      if folder
        favorites = get_favorite_folders
        if favorites.include?(folder[:full_name])
          favorites.delete(folder[:full_name])
          save_favorite_folders(favorites)
          @folder_display = favorites.map do |name|
            { name: name, full_name: name, depth: 0, has_children: false, collapsed: false }
          end
          @folder_browser_index = [@folder_browser_index, @folder_display.size - 1].min
          @folder_browser_index = 0 if @folder_browser_index < 0
          set_feedback("Removed #{folder[:full_name]} from favorites", 226, 2)
          render_folder_browser
          @panes[:top].text = " Heathrow - ".bd.fg(255) + "Favorites".bd.fg(226) + " [#{@folder_display.size} folders]".fg(246)
          @panes[:top].refresh
        end
      end
    when 'C-UP', '{'
      # Move favorite up
      if @folder_browser_index > 0 && @folder_display.size > 1
        favorites = get_favorite_folders
        i = @folder_browser_index
        favorites[i], favorites[i - 1] = favorites[i - 1], favorites[i]
        save_favorite_folders(favorites)
        @folder_display = favorites.map { |name| { name: name, full_name: name, depth: 0, has_children: false, collapsed: false } }
        @folder_browser_index -= 1
        render_folder_browser
      end
    when 'C-DOWN', '}'
      # Move favorite down
      if @folder_browser_index < @folder_display.size - 1 && @folder_display.size > 1
        favorites = get_favorite_folders
        i = @folder_browser_index
        favorites[i], favorites[i + 1] = favorites[i + 1], favorites[i]
        save_favorite_folders(favorites)
        @folder_display = favorites.map { |name| { name: name, full_name: name, depth: 0, has_children: false, collapsed: false } }
        @folder_browser_index += 1
        render_folder_browser
      end
    when 'q', 'ESC', "\e", 'h', 'LEFT'
      @in_folder_browser = false
      @in_favorites_browser = false
      render_all
      break
    end
  end
end

#show_filter_details(view_num, view_config) ⇒ Object



7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
# File 'lib/heathrow/ui/application.rb', line 7479

def show_filter_details(view_num, view_config)
  filter_text = []
  filter_text << "VIEW #{view_num} CONFIGURATION".bd.fg(226)
  filter_text << "=" * 40
  filter_text << ""
  
  if view_config[:filters] && !view_config[:filters].empty?
    filter_text << "Name:".bd.fg(39) + " #{view_config[:name] || 'View ' + view_num.to_s}"
    filter_text << ""
    filter_text << "Active Filters:".bd.fg(39)
    filter_text << "-" * 20
    
    filters = view_config[:filters]
    
    if filters['source_types'] || filters[:source_types]
      types = filters['source_types'] || filters[:source_types]
      filter_text << "Source Types:".fg(226) + " #{types.join(', ')}"
    end
    
    if filters['sender_pattern'] || filters[:sender_pattern]
      pattern = filters['sender_pattern'] || filters[:sender_pattern]
      filter_text << "Sender Pattern:".fg(226) + " #{pattern}"
    end
    
    if filters['subject_pattern'] || filters[:subject_pattern]
      pattern = filters['subject_pattern'] || filters[:subject_pattern]
      filter_text << "Subject Pattern:".fg(226) + " #{pattern}"
    end
    
    if filters['content_patterns'] || filters[:content_patterns]
      patterns = filters['content_patterns'] || filters[:content_patterns]
      filter_text << "Content Patterns:".fg(226) + " #{patterns.join(', ')}"
      filter_text << "  (comma=AND, pipe=OR within each)".fg(245)
    end
    
    # Legacy filter display
    if filters['content_keywords'] || filters[:content_keywords]
      keywords = filters['content_keywords'] || filters[:content_keywords]
      filter_text << "Content Keywords:".fg(226) + " #{keywords.join(', ')}"
    end
    
    if filters['content_regex'] || filters[:content_regex]
      regex = filters['content_regex'] || filters[:content_regex]
      filter_text << "Content Regex:".fg(226) + " #{regex}"
    end
    
    if filters['search'] || filters[:search]
      search = filters['search'] || filters[:search]
      filter_text << "Legacy Search:".fg(226) + " #{search}"
    end
    
    if filters.key?('is_read') || filters.key?(:is_read)
      is_read = filters['is_read'] || filters[:is_read]
      status = is_read == false ? "Unread only" : (is_read == true ? "Read only" : "All")
      filter_text << "Read Status:".fg(226) + " #{status}"
    end
    
    filter_text << ""
    filter_text << "-" * 40
    filter_text << ""
    filter_text << "Matching Messages:".bd.fg(39) + " #{@filtered_messages.size}"
  else
    filter_text << "No filters configured".fg(245)
    filter_text << ""
    filter_text << "This view will show an empty list until"
    filter_text << "you configure filters."
    filter_text << ""
    filter_text << "Available filter options:".bd.fg(39)
    filter_text << "• Source types (email, whatsapp, etc.)"
    filter_text << "• Sender pattern (pipe | for OR)"
    filter_text << "• Subject pattern (pipe | for OR)"
    filter_text << "• Content patterns (comma AND, pipe OR)"
    filter_text << "• Label (use 'l' to add labels, filter here)"
    filter_text << "• Read/unread status"
    filter_text << ""
    filter_text << "Pattern Examples:".bd.fg(39)
    filter_text << "Sender: Mom|Dad|Sister (any of them)"
    filter_text << "Content: error|warning,critical"
    filter_text << "  → (error OR warning) AND critical"
    filter_text << "Content: budget,2024|2025,report"
    filter_text << "  → budget AND (2024 OR 2025) AND report"
  end
  
  @panes[:right].text = filter_text.join("\n")
  @panes[:right].refresh
end

#show_folder_browserObject



3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
# File 'lib/heathrow/ui/application.rb', line 3846

def show_folder_browser
  @in_folder_browser = true
  @in_favorites_browser = false
  @folder_browser_index = 0
  @panes[:top].bg = @topcolor
  @folder_collapsed ||= {}
  @folder_count_cache = {}  # Fresh counts each time
  @browser_favorites = nil  # Fresh favorites read

  # Discover folders from disk (instant — no DB queries)
  maildir_path = File.expand_path('~/Maildir')
  folder_names = ['INBOX']
  Dir.glob(File.join(maildir_path, '.*')).sort.each do |dir|
    bn = File.basename(dir)
    next if bn == '.' || bn == '..'
    next unless File.directory?(dir)
    next unless File.directory?(File.join(dir, 'cur')) || File.directory?(File.join(dir, 'new'))
    folder_names << bn.sub(/^\./, '')
  end

  @folder_list = folder_names
  @folder_tree = build_folder_tree(folder_names)
  # Start with top-level collapsed for speed
  @folder_collapsed = {} if @folder_collapsed.nil?
  @folder_display = flatten_folder_tree(@folder_tree, '', 0, @folder_collapsed)

  render_folder_browser
  folder_browser_loop
end

#show_helpObject



6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
# File 'lib/heathrow/ui/application.rb', line 6710

def show_help
  @in_help_mode = true
  @panes[:right].content_update = false
  @panes[:right].ix = 0  # Reset scroll position
  help_text = get_help_text  # Use the colored version directly



  # Just set the text and let rcurses handle everything
  @panes[:right].text = help_text
  @panes[:right].refresh

  @showing_help = true
end

#show_loading(text = "Loading...") ⇒ Object

Message reply/forward functions



5170
5171
5172
5173
# File 'lib/heathrow/ui/application.rb', line 5170

def show_loading(text = "Loading...")
  @panes[:bottom].text = " #{text}".fg(245)
  @panes[:bottom].refresh
end

#show_new_messagesObject

View switching



2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
# File 'lib/heathrow/ui/application.rb', line 2535

def show_new_messages
  flush_pending_read
  invalidate_counts
  @current_view = 'N'
  @current_folder = nil
  @in_source_view = false
  @panes[:right].content_update = true
  @sort_order = @config.rc('sort_order', 'latest')
  @sort_inverted = false
  @last_rendered_index = nil  # Force right pane refresh

  # Restore per-view threading mode
  reset_threading
  restore_view_thread_mode

  render_top_bar

  @load_limit = 200
  @filtered_messages = @db.get_messages({is_read: false}, @load_limit, 0, light: true)
  sort_messages
  @index = 0
  render_all
  track_browsed_message
end

#show_settings_popupObject



6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
# File 'lib/heathrow/ui/application.rb', line 6008

def show_settings_popup
  rows, cols = IO.console.winsize
  pw = [cols - 20, 60].min
  pw = [pw, 46].max
  ph = 17
  px = (cols - pw) / 2
  py = (rows - ph) / 2

  popup = Rcurses::Pane.new(px, py, pw, ph, 252, 0)
  popup.border = true
  popup.scroll = false

  settings_rows = [:default_view, :color_theme, :date_format, :sort_order, :sort_inverted, :pane_width, :border_style, :confirm_purge, :download_folder, :editor_args, :default_email, :smtp_command]
  labels = {
    default_view: "Default View",
    color_theme: "Color Theme",
    date_format: "Date Format",
    sort_order: "Sort Order",
    sort_inverted: "Sort Inverted",
    pane_width: "Pane Width",
    border_style: "Border Style",
    confirm_purge: "Confirm Purge",
    download_folder: "Download Folder",
    editor_args: "Editor Args",
    default_email: "Default Email",
    smtp_command: "SMTP Command"
  }
  @download_folder ||= @config.get('download_folder') || '~/Downloads'

  theme_names = all_themes.keys
  date_formats = [
    ['%b %e', 'Mon  D'],
    ['%d/%m %H:%M', 'DD/MM HH:MM'],
    ['%m/%d %H:%M', 'MM/DD HH:MM'],
    ['%Y-%m-%d %H:%M', 'ISO'],
    ['%d.%m %H:%M', 'DD.MM HH:MM'],
    ['%d %b %H:%M', 'DD Mon HH:MM'],
    ['%b %d %H:%M', 'Mon DD HH:MM']
  ]
  sort_orders = ['latest', 'alphabetical', 'sender', 'from', 'conversation', 'unread', 'source']
  border_labels = ['none', 'right', 'both', 'left']
  # Build view choices: A, N, plus any user-defined views
  view_choices = [['A', 'All'], ['N', 'New/Unread']]
  @views.each do |key, v|
    view_choices << [key, "#{key}: #{v[:name]}"]
  end

  sel = 0

  build_popup = -> {
    popup.full_refresh  # Clear diff cache (theme editor/bottom_ask may have overlaid)
    inner_w = pw - 4
    lines = []
    lines << ""
    lines << "  " + "Settings".bd.fg(theme[:accent])
    lines << "  " + "\u2500" * [inner_w - 3, 1].max

    settings_rows.each_with_index do |key, i|
      label = labels[key]
      val = case key
            when :default_view
              vc = view_choices.find { |v| v[0] == @default_view }
              vc ? vc[1] : @default_view
            when :color_theme  then @color_theme
            when :date_format
              df = date_formats.find { |f| f[0] == @date_format }
              df ? df[1] : @date_format
            when :sort_order   then @sort_order
            when :sort_inverted then @sort_inverted ? "Yes" : "No"
            when :pane_width   then "#{@width * 10}%"
            when :border_style then border_labels[@border] || 'none'
            when :confirm_purge then @confirm_purge ? "Yes" : "No"
            when :download_folder then @download_folder
            when :editor_args then @editor_args.to_s.empty? ? "(none)" : @editor_args
            when :default_email then @default_email.to_s.empty? ? "(not set)" : @default_email
            when :smtp_command then @smtp_command.to_s.empty? ? "(not set)" : @smtp_command
            end
      display = "  %-18s \u25C0 %-12s \u25B6" % [label, val]
      if i == sel
        lines << display.fg(theme[:accent])
      else
        lines << display
      end
    end

    lines << ""
    lines << "  " + "\u2191\u2193:navigate  \u2190\u2192:change  ESC:close".fg(245)

    popup.text = lines.join("\n")
    popup.ix = 0
    popup.refresh
  }

  cycle_setting = ->(dir, enter: false) {
    key = settings_rows[sel]
    case key
    when :default_view
      idx = view_choices.find_index { |v| v[0] == @default_view } || 0
      idx = (idx + dir) % view_choices.length
      @default_view = view_choices[idx][0]
    when :color_theme
      if enter
        show_theme_editor
      else
        idx = theme_names.index(@color_theme) || 0
        idx = (idx + dir) % theme_names.length
        @color_theme = theme_names[idx]
      end
      @topcolor = theme[:top_bg] || 235
      @bottomcolor = theme[:bottom_bg] || 235
      @cmdcolor = theme[:cmd_bg] || 17
    when :date_format
      idx = date_formats.find_index { |f| f[0] == @date_format } || 0
      idx = (idx + dir) % date_formats.length
      @date_format = date_formats[idx][0]
    when :sort_order
      idx = sort_orders.index(@sort_order) || 0
      idx = (idx + dir) % sort_orders.length
      @sort_order = sort_orders[idx]
    when :sort_inverted
      @sort_inverted = !@sort_inverted
    when :pane_width
      @width = ((@width - 1 + dir) % 6) + 1  # Cycle 1-6
    when :border_style
      @border = (@border + dir) % 4
    when :confirm_purge
      @confirm_purge = !@confirm_purge
    when :download_folder
      # Text input, handled separately on Enter
    end
  }

  build_popup.call

  loop do
    k = getchr
    case k
    when 'ESC', 'q'
      break
    when 'k', 'UP'
      sel = (sel - 1) % settings_rows.length
      build_popup.call
    when 'j', 'DOWN'
      sel = (sel + 1) % settings_rows.length
      build_popup.call
    when 'ENTER'
      case settings_rows[sel]
      when :download_folder
        result = bottom_ask("Download folder: ", @download_folder)
        @download_folder = result.strip if result && !result.strip.empty?
      when :editor_args
        result = bottom_ask("Editor args: ", @editor_args || '')
        @editor_args = result if result
      when :default_email
        result = bottom_ask("Default email: ", @default_email || '')
        @default_email = result.strip if result && !result.strip.empty?
      when :smtp_command
        result = bottom_ask("SMTP command: ", @smtp_command || '')
        @smtp_command = result.strip if result && !result.strip.empty?
      else
        cycle_setting.call(1, enter: true)
      end
      build_popup.call
    when 'l', 'RIGHT'
      case settings_rows[sel]
      when :download_folder
        result = bottom_ask("Download folder: ", @download_folder)
        @download_folder = result.strip if result && !result.strip.empty?
      when :editor_args
        result = bottom_ask("Editor args: ", @editor_args || '')
        @editor_args = result if result
      when :default_email
        result = bottom_ask("Default email: ", @default_email || '')
        @default_email = result.strip if result && !result.strip.empty?
      when :smtp_command
        result = bottom_ask("SMTP command: ", @smtp_command || '')
        @smtp_command = result.strip if result && !result.strip.empty?
      else
        cycle_setting.call(1)
      end
      build_popup.call
    when 'h', 'LEFT'
      case settings_rows[sel]
      when :download_folder
        result = bottom_ask("Download folder: ", @download_folder)
        @download_folder = result.strip if result && !result.strip.empty?
      when :editor_args
        result = bottom_ask("Editor args: ", @editor_args || '')
        @editor_args = result if result
      when :default_email
        result = bottom_ask("Default email: ", @default_email || '')
        @default_email = result.strip if result && !result.strip.empty?
      when :smtp_command
        result = bottom_ask("SMTP command: ", @smtp_command || '')
        @smtp_command = result.strip if result && !result.strip.empty?
      else
        cycle_setting.call(-1)
      end
      build_popup.call
    end
  end

  # Save all settings
  @config.set('ui.default_view', @default_view)
  @config.set('ui.color_theme', @color_theme)
  @config.set('ui.date_format', @date_format)
  @config.set('ui.sort_order', @sort_order)
  @config.set('ui.width', @width)
  @config.set('ui.border', @border)
  @config.set('ui.confirm_purge', @confirm_purge)
  @config.set('download_folder', @download_folder)
  @config.set('ui.editor_args', @editor_args)
  @config.set('default_email', @default_email)
  @config.set('smtp_command', @smtp_command)
  @config.save

  # Apply changes
  set_borders
  left_width = (@w - 4) * @width / 10
  @panes[:left].w = left_width
  @panes[:right].x = @panes[:left].w + 4
  @panes[:right].w = @w - @panes[:left].w - 4

  # Reset threading for sort changes
  reset_threading(true)
  sort_messages
  organize_current_messages(true)

  Rcurses.clear_screen
  @panes.each_value { |p| p.cleanup if p.respond_to?(:cleanup) }
  render_all
rescue => e
  Rcurses.clear_screen
  render_all
end

#show_source_messages(source_id) ⇒ Object



1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
# File 'lib/heathrow/ui/application.rb', line 1836

def show_source_messages(source_id)
  @current_view = 'A'  # Use All Messages view but filtered
  @in_source_view = false
  @panes[:right].content_update = true
  
  # Get source name for display
  source = @source_manager.sources[source_id]
  @current_source_filter = source ? source['name'] : source_id
  
  # Get messages from this source
  @filtered_messages = @db.get_messages({source_id: source_id}, nil, 0, light: true)
  sort_messages
  @index = 0
  render_all
end

#show_sourcesObject



1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
# File 'lib/heathrow/ui/application.rb', line 1852

def show_sources
  flush_pending_read
  @current_view = 'S'
  @in_source_view = true
  @panes[:right].content_update = true
  @current_source_filter = nil
  show_loading("Loading sources...")

  # Reset threading state when changing views
  reset_threading
  
  # Reload source colors to ensure they're fresh
  load_source_colors
  
  # Convert sources to pseudo-messages for display in left pane
  sources = @db.get_all_sources
  stats = @db.get_source_stats  # Single query for all source counts
  @filtered_messages = sources.map do |source|
      s = stats[source['id']] || { count: 0, unread: 0 }
      count = s[:count]
      unread_count = s[:unread]

      # Health check
      health = source_health_check(source)

      msg = {
        'id' => source['id'],
        'source_id' => source['id'],
        'sender' => (source['plugin_type'] || 'unknown').capitalize,
        'subject' => source['name'],
        'content' => format_poll_interval(source['poll_interval']),
        'timestamp' => source['last_poll'] || Time.now.to_s,
        'is_read' => source['enabled'] == 1 ? 1 : 0,
        'is_starred' => 0,
        'source_type' => source['plugin_type'],
        'source_color' => source['color'],
        'msg_count' => count,
        'unread_count' => unread_count,
        'poll_interval' => source['poll_interval'],
        'health_ok' => health[:ok],
        'health_msg' => health[:msg],
        'enabled' => source['enabled']
      }
      msg
    end
  
  # Apply current sort order to sources
  sort_messages
  @index = 0
  
  # Render everything
  render_all
  render_sources_info
end

#show_theme_editorObject



6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
# File 'lib/heathrow/ui/application.rb', line 6244

def show_theme_editor
  rows, cols = IO.console.winsize
  # Core display keys only (source colors are set per-source via 'c' in Sources view)
  core_keys = [:unread, :read, :accent, :thread, :dm, :tag, :star,
               :quote1, :quote2, :quote3, :quote4, :sig,
               :top_bg, :bottom_bg, :cmd_bg]
  all_keys = core_keys

  # Work on a copy of current theme values
  editing = theme.dup

  # Determine if we're editing a custom theme or need a new name
  is_custom = @config.custom_themes.key?(@color_theme)
  theme_name = is_custom ? @color_theme : nil

  pw = [cols - 20, 52].min
  ph = [rows - 6, all_keys.size + 7].min
  px = (cols - pw) / 2
  py = (rows - ph) / 2

  popup = Rcurses::Pane.new(px, py, pw, ph, 252, 0)
  popup.border = true
  popup.scroll = false

  sel = 0
  scroll_offset = 0
  visible_rows = ph - 6  # header + footer lines

  key_labels = {
    unread: "Unread", read: "Read", accent: "Accent", thread: "Thread",
    dm: "DM", tag: "Tag", quote1: "Quote 1", quote2: "Quote 2",
    quote3: "Quote 3", quote4: "Quote 4", sig: "Signature",
    top_bg: "Top Bar BG", bottom_bg: "Bottom Bar BG", cmd_bg: "Command BG"
  }

  build_editor = -> {
    inner_w = pw - 4
    lines = []
    title = theme_name ? "Edit: #{theme_name}" : "Theme Editor (#{@color_theme})"
    lines << ""
    lines << "  " + title.bd.fg(editing[:accent] || 10)
    lines << "  " + "\u2500" * [inner_w - 3, 1].max

    # Ensure scroll follows selection
    scroll_offset = sel if sel < scroll_offset
    scroll_offset = sel - visible_rows + 1 if sel >= scroll_offset + visible_rows

    visible_keys = all_keys[scroll_offset, visible_rows] || []
    visible_keys.each_with_index do |key, vi|
      actual_idx = scroll_offset + vi
      val = editing[key] || 0
      label = key_labels[key] || key.to_s.sub('source_', 'Src: ').gsub('_', ' ').capitalize
      # Color swatch: two block chars in the color
      swatch = "\u2588\u2588".fg(val)
      line = "  %-16s %s %3d" % [label, swatch, val]
      lines << (actual_idx == sel ? line.fg(editing[:accent] || 10) : line)
    end

    # Scroll indicators
    lines << "  " + (scroll_offset + visible_rows < all_keys.size ? "\u2193 more".fg(245) : "")
    lines << "  " + "j/k:\u2195 h/l:\u00b11 H/L:\u00b110 #:set s:save ESC:back".fg(245)

    popup.text = lines.join("\n")
    popup.ix = 0
    popup.refresh
  }

  build_editor.call

  loop do
    k = getchr
    case k
    when 'ESC', 'q'
      break
    when 'k', 'UP'
      sel = (sel - 1) % all_keys.size
      build_editor.call
    when 'j', 'DOWN'
      sel = (sel + 1) % all_keys.size
      build_editor.call
    when 'PgUP'
      sel = [sel - visible_rows, 0].max
      build_editor.call
    when 'PgDOWN'
      sel = [sel + visible_rows, all_keys.size - 1].min
      build_editor.call
    when 'l', 'RIGHT'
      editing[all_keys[sel]] = [(editing[all_keys[sel]] || 0) + 1, 255].min
      build_editor.call
    when 'h', 'LEFT'
      editing[all_keys[sel]] = [(editing[all_keys[sel]] || 0) - 1, 0].max
      build_editor.call
    when 'L'
      editing[all_keys[sel]] = [(editing[all_keys[sel]] || 0) + 10, 255].min
      build_editor.call
    when 'H'
      editing[all_keys[sel]] = [(editing[all_keys[sel]] || 0) - 10, 0].max
      build_editor.call
    when /^[0-9]$/
      # Type a number directly
      result = bottom_ask("Color value (0-255): ", k)
      if result && result =~ /^\d+$/
        editing[all_keys[sel]] = result.to_i.clamp(0, 255)
      end
      build_editor.call
    when 's'
      # Save as custom theme
      unless theme_name
        result = bottom_ask("Theme name: ", "My Theme")
        next unless result && !result.strip.empty?
        theme_name = result.strip
      end
      # Write to heathrowrc
      save_custom_theme(theme_name, editing)
      @color_theme = theme_name
      @topcolor = editing[:top_bg] || 235
      @bottomcolor = editing[:bottom_bg] || 235
      @cmdcolor = editing[:cmd_bg] || 17
      set_feedback("Theme '#{theme_name}' saved", 46, 3)
      break
    end
  end
end

#sort_messagesObject



6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
# File 'lib/heathrow/ui/application.rb', line 6563

def sort_messages
  return if @filtered_messages.empty?

  # Make sure we have a mutable array
  @filtered_messages = @filtered_messages.dup if @filtered_messages.frozen?

  # Pre-compute timestamp cache to avoid repeated parsing in sort comparisons
  ts_cache = {}
  @filtered_messages.each { |m| ts_cache[m.object_id] = timestamp_to_time(m['timestamp']) }

  begin
    case @sort_order
    when 'alphabetical'
      # Sort alphabetically by subject/title (ignoring special chars)
      @filtered_messages.sort! do |a, b|
        # Get subjects and clean them for comparison
        subject_a_raw = (a['subject'] || a['content'] || '').to_s
        subject_b_raw = (b['subject'] || b['content'] || '').to_s
        
        # Remove special characters at the beginning for sorting
        subject_a = subject_a_raw.gsub(/^[#\[\]@\s]+/, '').downcase
        subject_b = subject_b_raw.gsub(/^[#\[\]@\s]+/, '').downcase
        
        subject_cmp = subject_a <=> subject_b
        
        if subject_cmp != 0
          subject_cmp
        elsif subject_a_raw.downcase != subject_b_raw.downcase
          # If cleaned names are same but originals differ, compare originals
          subject_a_raw.downcase <=> subject_b_raw.downcase
        else
          # If subjects are the same, sort by timestamp
          begin
            ts_cache[b.object_id] <=> ts_cache[a.object_id]
          rescue
            0
          end
        end
      end
    when 'sender'
      # Sort by sender name, then by timestamp
      @filtered_messages.sort! do |a, b|
        sender_a = (a['sender'] || '').to_s.downcase
        sender_b = (b['sender'] || '').to_s.downcase
        sender_cmp = sender_a <=> sender_b
        
        if sender_cmp != 0
          sender_cmp
        else
          # Safe timestamp comparison
          begin
            ts_cache[b.object_id] <=> ts_cache[a.object_id]
          rescue
            0
          end
        end
      end
    when 'from'
      # Group by sender, most recently active sender first
      # Within each sender group, newest message first
      latest_per_sender = {}
      @filtered_messages.each do |m|
        s = display_sender(m).downcase
        t = ts_cache[m.object_id] || Time.at(0)
        latest_per_sender[s] = t if !latest_per_sender[s] || t > latest_per_sender[s]
      end
      @filtered_messages.sort! do |a, b|
        sa = display_sender(a).downcase
        sb = display_sender(b).downcase
        if sa == sb
          (ts_cache[b.object_id] || Time.at(0)) <=> (ts_cache[a.object_id] || Time.at(0))
        else
          (latest_per_sender[sb] || Time.at(0)) <=> (latest_per_sender[sa] || Time.at(0))
        end
      end
    when 'unread'
      # Sort by unread first, then by timestamp
      @filtered_messages.sort! do |a, b|
        read_cmp = a['is_read'].to_i <=> b['is_read'].to_i
        if read_cmp != 0
          read_cmp  # Unread (0) first
        else
          # Safe timestamp comparison
          begin
            ts_cache[b.object_id] <=> ts_cache[a.object_id]
          rescue
            0  # If timestamp parsing fails, consider them equal
          end
        end
      end
    when 'conversation'
      # Group by conversation: thread_id, or sender (the other party)
      @filtered_messages.sort! do |a, b|
        conv_a = a['thread_id'] || a['sender'] || ''
        conv_b = b['thread_id'] || b['sender'] || ''
        conv_cmp = conv_a.to_s.downcase <=> conv_b.to_s.downcase

        if conv_cmp != 0
          conv_cmp
        else
          begin
            ts_cache[b.object_id] <=> ts_cache[a.object_id]
          rescue
            0
          end
        end
      end
    when 'source'
      # Sort by source type, then by timestamp
      @filtered_messages.sort! do |a, b|
        source_a = (a['source_type'] || '').to_s
        source_b = (b['source_type'] || '').to_s
        source_cmp = source_a <=> source_b

        if source_cmp != 0
          source_cmp
        else
          # Safe timestamp comparison
          begin
            ts_cache[b.object_id] <=> ts_cache[a.object_id]
          rescue
            0  # If timestamp parsing fails, consider them equal
          end
        end
      end
    else  # 'latest'
      # Sort by timestamp descending (newest first)
      @filtered_messages.sort! do |a, b|
        begin
          ts_cache[b.object_id] <=> ts_cache[a.object_id]
        rescue
          0  # If timestamp parsing fails, consider them equal
        end
      end
    end
    
    # Apply invert if flag is set
    @filtered_messages.reverse! if @sort_inverted
    
  rescue => e
    # If any error occurs during sorting, just leave the list as is
    # and show an error message
    @panes[:bottom].text = " Sort error: #{e.message}".fg(196)
    @panes[:bottom].refresh
  end
end

#source_health_check(source) ⇒ Object



1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
# File 'lib/heathrow/ui/application.rb', line 1608

def source_health_check(source)
  stype = source['plugin_type'] || source['type']

  # Check last_error
  if source['last_error'] && !source['last_error'].to_s.empty?
    return { ok: false, msg: source['last_error'] }
  end

  # Check enabled
  unless source['enabled'] == 1
    return { ok: false, msg: "Source disabled" }
  end

  config = source['config']
  config = JSON.parse(config) if config.is_a?(String)
  config = {} unless config.is_a?(Hash)

  case stype
  when 'maildir'
    path = config['path'] || config['maildir_path']
    if path && !Dir.exist?(path.to_s)
      return { ok: false, msg: "Maildir path not found" }
    end
  when 'rss'
    feeds = config['feeds'] || []
    if feeds.empty?
      return { ok: false, msg: "No feeds configured" }
    end
    bad = feeds.select { |f| f['last_status'] && f['last_status'] != 'ok' }
    unless bad.empty?
      return { ok: false, msg: "#{bad.size} feed(s) failing" }
    end
  when 'web'
    pages = config['pages'] || []
    if pages.empty?
      return { ok: false, msg: "No pages configured" }
    end
  when 'messenger'
    cookie_file = File.join(Dir.home, '.heathrow', 'cookies', 'messenger.json')
    unless File.exist?(cookie_file)
      return { ok: false, msg: "No cookies (run setup)" }
    end
    begin
      cookies = JSON.parse(File.read(cookie_file))
      unless cookies['c_user'] && cookies['xs']
        return { ok: false, msg: "Missing auth cookies" }
      end
    rescue
      return { ok: false, msg: "Corrupt cookie file" }
    end
    error_file = File.join(Dir.home, '.heathrow', 'cookies', 'messenger_error.txt')
    if File.exist?(error_file)
      last_line = File.readlines(error_file).last.to_s.strip
      if last_line.include?('login_required')
        return { ok: false, msg: "Login expired" }
      end
    end
  when 'instagram'
    cookie_file = File.join(Dir.home, '.heathrow', 'cookies', 'instagram.json')
    unless File.exist?(cookie_file)
      return { ok: false, msg: "No cookies (run setup)" }
    end
    begin
      cookies = JSON.parse(File.read(cookie_file))
      unless cookies['sessionid']
        return { ok: false, msg: "Missing session cookie" }
      end
    rescue
      return { ok: false, msg: "Corrupt cookie file" }
    end
  when 'weechat'
    host = config['host'] || config['relay_host']
    unless host && !host.to_s.empty?
      return { ok: false, msg: "No relay host configured" }
    end
  when 'workspace'
    session_file = File.join(Dir.home, '.config', 'workspace-cli', 'sessions', 'session.json')
    unless File.exist?(session_file)
      return { ok: false, msg: "No session file. Run: workspace-cli auth login" }
    end
    refresh = `secret-tool lookup service workspace-cli account session 2>/dev/null`.strip
    if refresh.empty?
      return { ok: false, msg: "No refresh token in keyring. Run: workspace-cli auth login" }
    end
  end

  { ok: true, msg: "OK" }
end

#switch_to_default_viewObject



2560
2561
2562
2563
2564
2565
2566
2567
# File 'lib/heathrow/ui/application.rb', line 2560

def switch_to_default_view
  dv = @default_view || 'A'
  case dv
  when 'A' then show_all_messages
  when 'N' then show_new_messages
  else switch_to_view(dv)
  end
end

#switch_to_view(key) ⇒ Object



2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
# File 'lib/heathrow/ui/application.rb', line 2569

def switch_to_view(key)
  flush_pending_read
  invalidate_counts
  @current_view = key
  @current_folder = nil
  @in_source_view = false
  @panes[:right].content_update = true
  @last_rendered_index = nil  # Force right pane refresh

  # Restore per-view threading mode
  reset_threading
  restore_view_thread_mode

  render_top_bar

  view = @views[key]

  # Restore per-view sort order, or use global default
  if view && view[:filters].is_a?(Hash) && view[:filters]['view_sort_order']
    @sort_order = view[:filters]['view_sort_order']
    @sort_inverted = view[:filters]['view_sort_inverted'] || false
  else
    @sort_order = @config.rc('sort_order', 'latest')
    @sort_inverted = false
  end

  # Restore saved section order for this view
  if view && view[:filters] && view[:filters]['section_order']
    @section_order = view[:filters]['section_order'].dup
  end

  @load_limit = 200
  if view && view[:filters] && !view[:filters].empty?
    apply_view_filters(view)
    sort_messages
    @index = 0
    render_all
    track_browsed_message
  else
    @filtered_messages = []
    @index = 0
    @panes[:right].text = ""
    @panes[:right].refresh
    render_all
  end
end

#sync_instagram(db: nil) ⇒ Object



8756
8757
8758
8759
8760
8761
8762
8763
8764
8765
8766
8767
8768
8769
8770
8771
8772
8773
# File 'lib/heathrow/ui/application.rb', line 8756

def sync_instagram(db: nil)
  db ||= @db
  sources = db.get_sources.select { |s| s['plugin_type'] == 'instagram' }
  return false if sources.empty?

  require_relative '../sources/instagram'
  total = 0
  sources.each do |source|
    config = source['config']
    config = JSON.parse(config) if config.is_a?(String)
    instance = Heathrow::Sources::Instagram.new(source['name'], config, db)
    total += (instance.sync(source['id']) || 0)
  end
  total > 0
rescue => e
  File.open('/tmp/heathrow_debug.log', 'a') { |f| f.puts "Instagram sync error: #{e.message}\n#{e.backtrace.first(3).join("\n")}" }
  false
end

#sync_maildir(folder: nil, db: nil, &block) ⇒ Object

Returns true if any data changed, false otherwise



8668
8669
8670
8671
8672
8673
8674
8675
8676
8677
8678
8679
8680
8681
8682
8683
8684
8685
8686
8687
8688
8689
8690
8691
8692
8693
# File 'lib/heathrow/ui/application.rb', line 8668

def sync_maildir(folder: nil, db: nil, &block)
  db ||= @db
  source = db.get_sources.find { |s| s['plugin_type'] == 'maildir' }
  return false unless source

  require_relative '../sources/maildir'
  maildir = Heathrow::Sources::Maildir.new(source)

  if folder.is_a?(Array)
    all_folders = maildir.discover_folders
    changed = false
    folder.each do |fname|
      f = all_folders.find { |fd| fd[:name] == fname }
      changed = true if f && maildir.sync_folder(db, source['id'], f[:name], f[:path])
    end
    changed
  elsif folder
    folders = maildir.discover_folders
    f = folders.find { |fd| fd[:name] == folder }
    f ? maildir.sync_folder(db, source['id'], f[:name], f[:path]) : false
  else
    maildir.sync_all(db, source['id'], &block)
  end
rescue => e
  File.open('/tmp/heathrow_debug.log', 'a') { |f| f.puts "Maildir sync error: #{e.message}\n#{e.backtrace.first(3).join("\n")}" }
end

#sync_maildir_flag(msg, flag_char, add) ⇒ Object

Sync a Maildir flag on disk after DB update flag_char: 'S' for seen, 'F' for flagged, 'T' for trashed add: true to add flag, false to remove



8797
8798
8799
8800
8801
8802
8803
8804
8805
8806
8807
8808
8809
8810
8811
8812
8813
8814
8815
8816
8817
# File 'lib/heathrow/ui/application.rb', line 8797

def sync_maildir_flag(msg, flag_char, add)
  return unless msg
   = msg['metadata']
   = JSON.parse() if .is_a?(String)
  return unless .is_a?(Hash)
  file_path = ['maildir_file']
  return unless file_path && File.exist?(file_path)

  require_relative '../sources/maildir'
  new_path = Heathrow::Sources::Maildir.rename_with_flag(file_path, flag_char, add: add)

  # Update the stored file path in metadata and DB
  if new_path != file_path
    ['maildir_file'] = new_path
    msg['metadata'] = 
    @db.execute("UPDATE messages SET metadata = ? WHERE id = ?", .to_json, msg['id'])
  end
rescue => e
  # Don't crash on flag sync failures
  File.open('/tmp/heathrow_debug.log', 'a') { |f| f.puts "Flag sync error: #{e.message}" } if ENV['DEBUG']
end

#sync_messenger(db: nil) ⇒ Object



8733
8734
8735
8736
8737
8738
8739
8740
8741
8742
8743
8744
8745
8746
8747
8748
8749
8750
8751
8752
8753
8754
# File 'lib/heathrow/ui/application.rb', line 8733

def sync_messenger(db: nil)
  db ||= @db
  sources = db.get_sources.select { |s| s['plugin_type'] == 'messenger' }
  return false if sources.empty?

  require_relative '../sources/messenger'
  total = 0
  errors = []
  sources.each do |source|
    config = source['config']
    config = JSON.parse(config) if config.is_a?(String)
    instance = Heathrow::Sources::Messenger.new(source['name'], config, db)
    total += (instance.sync(source['id']) || 0)
    errors << instance.sync_error if instance.sync_error
  end
  @last_sync_errors = (@last_sync_errors || []) + errors if errors.any?
  total > 0
rescue => e
  @last_sync_errors = (@last_sync_errors || []) << "Messenger: #{e.message}"
  File.open('/tmp/heathrow_debug.log', 'a') { |f| f.puts "Messenger sync error: #{e.message}\n#{e.backtrace.first(3).join("\n")}" }
  false
end

#sync_rss(db: nil) ⇒ Object



8695
8696
8697
8698
8699
8700
8701
8702
8703
8704
8705
8706
8707
8708
8709
8710
8711
8712
# File 'lib/heathrow/ui/application.rb', line 8695

def sync_rss(db: nil)
  db ||= @db
  sources = db.get_sources.select { |s| s['plugin_type'] == 'rss' }
  return false if sources.empty?

  require_relative '../sources/rss'
  total = 0
  sources.each do |source|
    config = source['config']
    config = JSON.parse(config) if config.is_a?(String)
    instance = Heathrow::Sources::RSS.new(source['name'], config, db)
    total += (instance.sync(source['id']) || 0)
  end
  total > 0
rescue => e
  File.open('/tmp/heathrow_debug.log', 'a') { |f| f.puts "RSS sync error: #{e.message}\n#{e.backtrace.first(3).join("\n")}" }
  false
end

#sync_webwatch(db: nil) ⇒ Object



8714
8715
8716
8717
8718
8719
8720
8721
8722
8723
8724
8725
8726
8727
8728
8729
8730
8731
# File 'lib/heathrow/ui/application.rb', line 8714

def sync_webwatch(db: nil)
  db ||= @db
  sources = db.get_sources.select { |s| s['plugin_type'] == 'web' }
  return false if sources.empty?

  require_relative '../sources/webpage'
  total = 0
  sources.each do |source|
    config = source['config']
    config = JSON.parse(config) if config.is_a?(String)
    instance = Heathrow::Sources::Webpage.new(source['name'], config, db)
    total += (instance.sync(source['id']) || 0)
  end
  total > 0
rescue => e
  File.open('/tmp/heathrow_debug.log', 'a') { |f| f.puts "Webwatch sync error: #{e.message}\n#{e.backtrace.first(3).join("\n")}" }
  false
end

#sync_weechat(db: nil) ⇒ Object



8775
8776
8777
8778
8779
8780
8781
8782
8783
8784
8785
8786
8787
8788
8789
8790
8791
8792
# File 'lib/heathrow/ui/application.rb', line 8775

def sync_weechat(db: nil)
  db ||= @db
  sources = db.get_sources.select { |s| s['plugin_type'] == 'weechat' }
  return false if sources.empty?

  require_relative '../sources/weechat'
  total = 0
  sources.each do |source|
    config = source['config']
    config = JSON.parse(config) if config.is_a?(String)
    instance = Heathrow::Sources::Weechat.new(source['name'], config, db)
    total += (instance.sync(source['id']) || 0)
  end
  total > 0
rescue => e
  File.open('/tmp/heathrow_debug.log', 'a') { |f| f.puts "WeeChat sync error: #{e.message}\n#{e.backtrace.first(3).join("\n")}" }
  false
end

#tag_all_toggleObject

Tag/untag all messages in current view



2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
# File 'lib/heathrow/ui/application.rb', line 2832

def tag_all_toggle
  msgs = @filtered_messages.reject { |m| header_message?(m) }
  ids = msgs.map { |m| m['id'] }.compact
  if ids.all? { |id| @tagged_messages.include?(id) }
    # All tagged, untag all
    ids.each { |id| @tagged_messages.delete(id) }
    set_feedback("Untagged all #{ids.size} messages", 14, 2)
  else
    # Tag all
    ids.each { |id| @tagged_messages.add(id) }
    set_feedback("Tagged all #{ids.size} messages", 14, 2)
  end
  render_message_list
end

#tag_by_regexObject

Tag/untag messages matching a regex (Ctrl+t, like RTFM)



2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
# File 'lib/heathrow/ui/application.rb', line 2800

def tag_by_regex
  pattern = bottom_ask("Tag regex (default=all): ", ".*")
  return if pattern.nil?

  begin
    regex = Regexp.new(pattern, Regexp::IGNORECASE)
  rescue RegexpError => e
    set_feedback("Invalid regex: #{e.message}", 196, 3)
    return
  end

  count = 0
  @filtered_messages.each do |msg|
    next if header_message?(msg)
    next unless msg['id']

    match = [msg['sender'], msg['subject'], msg['content']].compact.any? { |f| f.match?(regex) }
    if match
      if @tagged_messages.include?(msg['id'])
        @tagged_messages.delete(msg['id'])
      else
        @tagged_messages.add(msg['id'])
        count += 1
      end
    end
  end

  set_feedback("Toggled #{count} tags (#{@tagged_messages.size} total tagged)", 14, 3)
  render_message_list
end

#test_selected_sourceObject



1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
# File 'lib/heathrow/ui/application.rb', line 1217

def test_selected_source
  return unless @filtered_messages[@index]
  
  source_data = @filtered_messages[@index]
  source_id = source_data['id']
  source_type = source_data['source_type'] || source_data['plugin_type'] || source_data['type']
  
  @panes[:bottom].text = " Testing #{source_data['subject'] || source_data['name']}...".fg(226)
  @panes[:bottom].refresh
  
  # Try to create source instance and test
  begin
    require 'ostruct'
    
    # Get the actual source from database
    source = @db.get_source_by_id(source_id)
    
    if source
      # Load the source module
      begin
        require_relative "../sources/#{source_type}"
      rescue LoadError
        @panes[:bottom].text = " Source module not found: #{source_type}".fg(196)
        @panes[:bottom].refresh
        sleep(2)
        return
      end
      
      # Create instance with proper structure
      source_wrapper = OpenStruct.new(
        id: source['id'],
        config: source['config'].is_a?(String) ? JSON.parse(source['config']) : source['config']
      )
      
      # Get the class
      class_name = case source_type
                   when 'rss' then 'RSS'
                   when 'webpage' then 'Webpage'
                   else source_type.capitalize
                   end
      source_class = Heathrow::Sources.const_get(class_name)
      
      # Create instance and test
      instance = begin
        source_class.new(source)
      rescue ArgumentError
        config = source['config']
        config = JSON.parse(config) if config.is_a?(String)
        source_class.new(source['name'], config || {}, @db)
      end
      
      if instance.respond_to?(:test_connection)
        progress = ->(msg) {
          @panes[:bottom].text = " #{msg}".fg(226)
          @panes[:bottom].refresh
        }
        result = instance.test_connection(&progress)

        if result[:success]
          set_feedback("✓ #{result[:message]}", 156, 0)
        else
          set_feedback("✗ #{result[:message]}", 196, 0)
          # Offer to remove failed feeds (RSS/web)
          if result[:failed_feeds] && !result[:failed_feeds].empty?
            result[:failed_feeds].each do |feed_name|
              answer = bottom_ask("Remove failed feed '#{feed_name}'? [y/N] ")
              if answer&.strip&.downcase == 'y'
                feed_entry = instance.list_feeds.find { |f| (f[:title] || f[:url]) == feed_name }
                if feed_entry
                  instance.remove_feed(feed_entry[:url])
                  set_feedback("Removed #{feed_name}", 156, 3)
                  render_sources_info
                end
              end
            end
          end
        end
      else
        set_feedback("Test not available for #{source_type} sources", 226, 0)
      end
    end
  rescue => e
    set_feedback("Error: #{e.message}", 196, 0)
  end
end

#themeObject



203
204
205
206
207
# File 'lib/heathrow/ui/application.rb', line 203

def theme
  base = COLOR_THEMES['Default']
  selected = all_themes[@color_theme]
  selected ? base.merge(selected) : base
end

#timestamp_to_time(ts) ⇒ Object

Helper method to get Time object from timestamp for sorting



379
380
381
382
383
384
385
386
387
388
389
# File 'lib/heathrow/ui/application.rb', line 379

def timestamp_to_time(ts)
  return Time.at(0) if ts.nil? || ts.to_s.empty? || ts.to_s == "0"

  if ts.is_a?(Integer) || ts.to_s.match?(/^\d+$/)
    Time.at(ts.to_i)
  else
    Time.parse(ts.to_s)
  end
rescue => e
  Time.at(0)
end

#toggle_collapse_expandObject

SPACE key: toggle collapse/expand in threaded view



2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
# File 'lib/heathrow/ui/application.rb', line 2766

def toggle_collapse_expand
  return unless @show_threaded && @organizer

  msg = current_message
  return unless msg

  # For headers, toggle directly
  if msg['is_dm_header'] || msg['is_channel_header'] || msg['is_thread_header']
    expand_current_item  # This already toggles
  elsif msg['channel_id'] || msg['thread_id']
    # For messages inside a group, collapse the parent
    collapse_current_item
  end
  # Non-threaded mode: no-op
end

#toggle_delete_markObject

Toggle delete mark on current message (like mutt 'd') Does NOT immediately delete — just marks visually with strikethrough



5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
# File 'lib/heathrow/ui/application.rb', line 5071

def toggle_delete_mark
  @delete_marked ||= Set.new

  # If messages are tagged, operate on all tagged
  if @tagged_messages.size > 0
    already_marked = @tagged_messages.all? { |id| @delete_marked.include?(id) }
    if already_marked
      @tagged_messages.each { |id| @delete_marked.delete(id) }
      set_feedback("Unmarked #{@tagged_messages.size} from deletion", 156, 2)
    else
      @tagged_messages.each { |id| @delete_marked.add(id) }
      set_feedback("Marked #{@tagged_messages.size} for deletion ('<' to purge)", 196, 2)
    end
    @tagged_messages.clear
  else
    msg = current_message
    return unless msg
    return if header_message?(msg)

    if @delete_marked.include?(msg['id'])
      @delete_marked.delete(msg['id'])
      set_feedback("Undeleted", 156, 2)
    else
      @delete_marked.add(msg['id'])
      set_feedback("Marked for deletion (#{@delete_marked.size} total, '<' to purge)", 196, 2)
    end
    advance_index
  end
  render_message_list
  render_message_content
  render_bottom_bar
end

#toggle_favorite_folderObject



4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
# File 'lib/heathrow/ui/application.rb', line 4257

def toggle_favorite_folder
  # Add/remove current folder from favorites
  msg = current_message
  return unless msg
   = msg['metadata']
   = JSON.parse() if .is_a?(String)
  folder = .is_a?(Hash) ? ['maildir_folder'] : nil
  folder ||= @current_folder
  return unless folder

  favorites = get_favorite_folders
  if favorites.include?(folder)
    favorites.delete(folder)
    set_feedback("Removed #{folder} from favorites", 226, 2)
  else
    favorites << folder
    set_feedback("Added #{folder} to favorites", 156, 2)
  end
  save_favorite_folders(favorites)
end

#toggle_group_read_status(header) ⇒ Object



3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
# File 'lib/heathrow/ui/application.rb', line 3622

def toggle_group_read_status(header)
  # Use the section_messages stored in the header if available
  messages = header['section_messages']
  
  # Fallback to finding messages via organizer if not stored in header
  if !messages && @show_threaded && @organizer
    organized = @organizer.get_organized_view
    
    # Find the section this header belongs to
    section = organized.find do |s|
      if header['is_channel_header']
        s[:type] == 'channel' && s[:name] == header['channel_name']
      elsif header['is_thread_header']
        s[:type] == 'thread' && s[:subject] == header['subject']
      elsif header['is_dm_header']
        s[:type] == 'dm_section'
      else
        false
      end
    end
    
    messages = section[:messages] if section
  end
  
  return unless messages && !messages.empty?
  
  # Check if all messages are read
  all_read = messages.all? { |m| m['is_read'].to_i == 1 }
  
  # Toggle all messages in this section
  messages.each do |msg|
    next unless msg['id'] && !msg['id'].to_s.start_with?('header_')  # Skip synthetic headers

    if all_read
      @db.mark_as_unread(msg['id'])
      msg['is_read'] = 0
    else
      @db.mark_as_read(msg['id'])
      msg['is_read'] = 1
    end
  end
  invalidate_counts

  # Re-sort if sorting by unread
  if @sort_order == 'unread'
    sort_messages
    # Reset threading to reorganize with new unread counts (preserve collapsed state)
    reset_threading(true)
  end
  
  # Update displays if UI is initialized
  if @panes && @w
    render_top_bar
    render_message_list
  end
  
  # Show feedback
  action = all_read ? "unread" : "read"
  set_feedback("Marked #{messages.size} messages as #{action}", 156, 3)
end

#toggle_inline_imageObject

Toggle image display in right pane (I key)



8264
8265
8266
8267
8268
8269
8270
8271
8272
8273
8274
8275
8276
8277
8278
8279
8280
8281
8282
8283
8284
8285
8286
8287
8288
8289
8290
8291
8292
8293
8294
8295
8296
8297
8298
8299
8300
8301
8302
8303
8304
8305
8306
8307
8308
8309
8310
8311
8312
8313
8314
8315
8316
8317
8318
8319
8320
8321
8322
8323
8324
8325
8326
8327
8328
8329
8330
8331
8332
8333
8334
8335
8336
8337
8338
8339
8340
8341
8342
8343
8344
# File 'lib/heathrow/ui/application.rb', line 8264

def toggle_inline_image
  if @showing_image
    clear_inline_image
    render_message_content
    return
  end

  return unless init_termpix

  msg = current_message
  return unless msg
  msg = ensure_full_message(msg)

  http_urls = []

  # 1. Check attachments for image URLs (Discord, Messenger, Instagram, etc.)
  att_urls = image_urls_from_attachments(msg)
  http_urls.concat(att_urls)

  # 2. Check HTML content for <img> tags (email, RSS)
  html = msg['html_content']
  if (!html || html.strip.empty?) && msg['content'] =~ /\A\s*<(!DOCTYPE|html|head|body)\b/i
    html = msg['content']
  end
  if html && !html.strip.empty?
    html_urls = extract_image_urls(html).select { |u| u.start_with?('http') }
    http_urls.concat(html_urls)
  end

  http_urls.uniq!

  if http_urls.empty?
    set_feedback("No images found", 245, 2)
    return
  end

  set_feedback("Loading #{http_urls.size > 1 ? "#{http_urls.size} images" : 'image'}...", 226, 2)
  image_paths = []
  http_urls.first(10).each do |url|
    path = cached_image(url)
    image_paths << path if path && File.exist?(path) && File.size(path) > 100
  end

  if image_paths.empty?
    set_feedback("Download failed for #{http_urls.size} image(s)", 196, 2)
    return
  end

  # Clear right pane and show images
  n = image_paths.size
  label = n == 1 ? "1 image" : "#{n} images"
  @panes[:right].text = " [#{label}]  Press ESC to return".fg(245)
  @panes[:right].full_refresh  # Full refresh to clear image area

  pane_w = @panes[:right].w - 2
  pane_h = @panes[:right].h - 2
  img_x = @panes[:right].x
  base_y = @termpix.protocol == :kitty ? @panes[:right].y + 1 : @panes[:right].y

  # Composite multiple images into a grid tile so they use the full pane area
  display_path = if image_paths.size == 1
    image_paths.first
  else
    composite = File.join(Dir.home, '.heathrow', 'image_cache', 'composite.png')
    escaped = image_paths.map { |p| Shellwords.escape(p) }
    # Calculate grid columns: sqrt gives a balanced grid
    cols = Math.sqrt(image_paths.size).ceil
    system("montage #{escaped.join(' ')} -geometry +2+2 -tile #{cols}x -background none #{Shellwords.escape(composite)} 2>/dev/null")
    File.exist?(composite) ? composite : image_paths.first
  end

  @termpix.show(display_path,
    x: img_x,
    y: base_y,
    max_width: pane_w,
    max_height: pane_h)
  @showing_image = true
  @panes[:right].content_update = false
rescue => e
  set_feedback("Image error: #{e.message}", 196, 2)
end

#toggle_readObject



3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
# File 'lib/heathrow/ui/application.rb', line 3740

def toggle_read
  # Write debug log
  
  msg = current_message
  return unless msg
  return if @in_source_view  # Don't toggle read in source view
  
  # Log the message details
  
  # HOUSE DIAGNOSTIC: Check if message has an ID!
  unless msg['id']
    # Show error in bottom bar
    @panes[:bottom].text = " ERROR: Message has no ID! Cannot toggle.".fg(196)
    @panes[:bottom].refresh
    return
  end
  
  # CRITICAL FIX: Convert is_read to integer for comparison
  current_read_status = msg['is_read'].to_i
  
  # Toggle based on current state
  if current_read_status == 1
    success = @db.mark_as_unread(msg['id'])
    if success
      msg['is_read'] = 0
    end
  else
    success = @db.mark_as_read(msg['id'])
    if success
      msg['is_read'] = 1
    end
  end
  
  # Update displays immediately if UI is initialized
  if @panes && @w
    render_top_bar  # Update unread count
    render_message_list
    render_message_content
  end
end

#toggle_read_statusObject



3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
# File 'lib/heathrow/ui/application.rb', line 3451

def toggle_read_status
  # Batch mode: if messages are tagged, toggle read on all tagged
  if @tagged_messages && !@tagged_messages.empty?
    toggle_tagged_read_status
    return
  end

  msg = current_message
  return unless msg

  # Check if this is a source/channel header
  if msg['is_channel_header'] || msg['is_thread_header'] || msg['is_dm_header']
    # Toggle read status for all messages in this group
    toggle_group_read_status(msg)
  else
    # Regular message toggle
    toggle_single_message_read(msg)
  end
end

#toggle_selected_sourceObject



1210
1211
1212
1213
1214
1215
# File 'lib/heathrow/ui/application.rb', line 1210

def toggle_selected_source
  return unless @filtered_messages[@index]
  source_id = @filtered_messages[@index]['id']
  @source_manager.toggle_source(source_id)
  show_sources
end

#toggle_single_message_read(msg) ⇒ Object



3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
# File 'lib/heathrow/ui/application.rb', line 3683

def toggle_single_message_read(msg)
  # Don't try to toggle headers
  return if msg['is_header']
  return unless msg['id'] && !msg['id'].to_s.start_with?('header_')

  # Toggle the specific message
  current_read_status = msg['is_read'].to_i
  invalidate_counts

  if current_read_status == 1
    success = @db.mark_as_unread(msg['id'])
    if success
      msg['is_read'] = 0
      sync_maildir_flag(msg, 'S', false)
      set_feedback("Message marked as unread", 156, 3)
    end
  else
    success = @db.mark_as_read(msg['id'])
    if success
      msg['is_read'] = 1
      sync_maildir_flag(msg, 'S', true)
      set_feedback("Message marked as read", 156, 3)

      # Remove from Unread view if currently in it
      if is_unread_view?
        if @show_threaded
          # In threaded view, need to reload filtered messages to rebuild threads
          reset_threading
          @filtered_messages = @db.get_messages({is_read: false}, 1000, 0, light: true)
          sort_messages
          organize_current_messages(force_reinit: true)
          @index = [@index, filtered_messages_size - 1].min
          @index = 0 if @index < 0
        else
          # In flat view, just remove from list
          @filtered_messages.delete_at(@index)
          @index = [@index, @filtered_messages.size - 1].min if @index >= @filtered_messages.size
          @index = 0 if @index < 0 || @filtered_messages.empty?
        end
      end
    end
  end

  # Re-sort if sorting by unread
  if @sort_order == 'unread'
    sort_messages
    # Reset threading to reorganize with new unread counts (preserve collapsed state)
    reset_threading(true)
  end
  
  # Update displays immediately if UI is initialized
  if @panes && @w
    render_top_bar  # Update unread count
    render_message_list  # This will update the visual display including background colors
  end
end

#toggle_sort_invertObject



6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
# File 'lib/heathrow/ui/application.rb', line 6516

def toggle_sort_invert
  # Toggle the invert flag
  @sort_inverted = !@sort_inverted

  # Save per-view sort
  save_view_sort_order
  
  # For threaded views, we need to reload the full message list before re-sorting
  if @show_threaded && @current_view == 'A'
    # Reload all messages to ensure we have the complete list
    @filtered_messages = @db.get_messages({}, 1000, 0, light: true)
  elsif @show_threaded && @current_view == 'N'
    # Reload unread messages
    @filtered_messages = @db.get_messages({is_read: false}, 1000, 0, light: true)
  elsif @show_threaded && @current_source_filter
    # Reload messages for current source
    @filtered_messages = @db.get_messages({source_id: @current_source_filter}, nil, 0, light: true)
  end
  
  # Reset threading state to force reorganization with new sort (preserve collapsed state)
  reset_threading(true)
  
  # Re-sort and redisplay messages
  sort_messages
  
  # Force reinit the organizer with the newly sorted messages
  organize_current_messages(true)
  
  @index = 0  # Reset to top
  render_all  # Re-render everything
end

#toggle_starObject



3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
# File 'lib/heathrow/ui/application.rb', line 3781

def toggle_star
  msg = current_message
  return unless msg
  @db.toggle_star(msg['id'])
  msg['is_starred'] = msg['is_starred'] == 1 ? 0 : 1
  invalidate_counts

  # Sync flagged status to Maildir file
  sync_maildir_flag(msg, 'F', msg['is_starred'] == 1)

  render_message_list
  render_bottom_bar
end

#toggle_tagObject

Toggle tag on current message



2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
# File 'lib/heathrow/ui/application.rb', line 2783

def toggle_tag
  msg = current_message
  return unless msg
  return if header_message?(msg)
  return unless msg['id']

  if @tagged_messages.include?(msg['id'])
    @tagged_messages.delete(msg['id'])
  else
    @tagged_messages.add(msg['id'])
  end
  advance_index
  render_message_list
  render_message_content
end

#toggle_tagged_read_statusObject

Toggle read status on all tagged messages, then clear tags



3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
# File 'lib/heathrow/ui/application.rb', line 3472

def toggle_tagged_read_status
  tagged_msgs = @filtered_messages.select { |m| m['id'] && @tagged_messages.include?(m['id']) }
  return if tagged_msgs.empty?

  # Determine direction: if any are unread, mark all as read; otherwise mark all unread
  any_unread = tagged_msgs.any? { |m| m['is_read'].to_i == 0 }
  count = 0

  tagged_msgs.each do |msg|
    if any_unread
      next if msg['is_read'].to_i == 1  # Already read
      success = @db.mark_as_read(msg['id'])
      if success
        msg['is_read'] = 1
        sync_maildir_flag(msg, 'S', true)
        count += 1
      end
    else
      next if msg['is_read'].to_i == 0  # Already unread
      success = @db.mark_as_unread(msg['id'])
      if success
        msg['is_read'] = 0
        sync_maildir_flag(msg, 'S', false)
        count += 1
      end
    end
  end

  action = any_unread ? "read" : "unread"
  set_feedback("Marked #{count} tagged messages as #{action}", 156, 3)
  @tagged_messages.clear

  # Update displays
  if @panes && @w
    render_top_bar
    render_message_list
  end
end

#track_browsed_messageObject

Mark the previous message as read when moving away from it



230
231
232
233
234
235
236
237
238
239
240
241
242
243
# File 'lib/heathrow/ui/application.rb', line 230

def track_browsed_message
  flush_pending_read

  # Remember current message so it gets marked read when we leave it
  msg = current_message
  return unless msg
  return if header_message?(msg)
  return unless msg['id'] && !msg['id'].to_s.start_with?('header_')

  if msg['is_read'].to_i == 0
    @browsed_message_ids.add(msg['id'])
    @pending_mark_read = msg
  end
end

#truncate_to_width(str, max_width) ⇒ Object

Highlight URLs in a line, applying base_color to non-URL text Truncate a string to fit within a given display width (CJK-aware)



8591
8592
8593
8594
8595
8596
8597
8598
8599
# File 'lib/heathrow/ui/application.rb', line 8591

def truncate_to_width(str, max_width)
  w = 0
  str.each_char.with_index do |c, i|
    cw = Rcurses.display_width(c)
    return str[0...i] if w + cw > max_width
    w += cw
  end
  str
end

#uncollapse_for_message(msg) ⇒ Object



2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
# File 'lib/heathrow/ui/application.rb', line 2945

def uncollapse_for_message(msg)
  return unless msg && @organizer
  msg_id = msg['id']

  # Find which channel contains this message (use section[:name] as collapse key)
  if @channel_collapsed
    @organizer.instance_variable_get(:@channels)&.each do |_channel_id, channel_data|
      if channel_data[:messages]&.any? { |m| m['id'] == msg_id }
        @channel_collapsed[channel_data[:name]] = false
        return
      end
    end
  end

  # Find which thread contains this message
  if @thread_collapsed
    @organizer.instance_variable_get(:@threads)&.each do |_thread_id, thread_data|
      if thread_data[:messages]&.any? { |m| m['id'] == msg_id }
        @thread_collapsed[thread_data[:subject].to_s] = false
        return
      end
    end
  end

  # Uncollapse DM section if it's a DM
  if msg['is_dm']
    if @sort_order == 'conversation'
      # Find which conversation this DM belongs to
       = @organizer.send(:parse_metadata, msg['metadata']) rescue {}
      dm_key = msg['sender'] || msg['subject'] || 'Unknown'
      @dm_collapsed[dm_key] = false
    elsif @dm_section_collapsed
      @dm_section_collapsed = false
    end
  end
end

#unsee_current_messageObject

Mark message as "unseen" - remove from browsed set



279
280
281
282
283
284
285
286
287
288
# File 'lib/heathrow/ui/application.rb', line 279

def unsee_current_message
  msg = current_message
  return unless msg
  return if msg['is_header']

  if @browsed_message_ids.delete(msg['id'])
    set_feedback("Message marked as unseen", 226, 2)
    render_all
  end
end

#update_displayObject



2296
2297
2298
2299
2300
# File 'lib/heathrow/ui/application.rb', line 2296

def update_display
  # Only update panes that have changed
  # This is a placeholder for optimization
  refresh_panes
end

#update_window_titleObject



1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
# File 'lib/heathrow/ui/application.rb', line 1303

def update_window_title
  # Get view name - check for source filter first
  view_name = if @current_source_filter && @current_view == 'A'
    "Source: #{@current_source_filter}"
  elsif @views[@current_view]
    view = @views[@current_view]
    "[#{@current_view}] #{view[:name]}"
  elsif @in_source_view
    "Sources"
  else
    @view_names[@current_view] || @current_view
  end
  
  # Add message count with unread/total format if applicable (matching top bar)
  count_info = if @filtered_messages && !@filtered_messages.empty? && !@in_source_view
    total = @filtered_messages.size
    unread = @filtered_messages.count { |m| m['is_read'].to_i == 0 }
    " (#{unread}/#{total})"
  else
    ""
  end
  
  # Set window title using ANSI escape sequence (direct print, no subprocess)
  $stdout.print "\033]0;Heathrow: #{view_name}#{count_info}\007"
  $stdout.flush
end

#view_attachmentsObject



3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
# File 'lib/heathrow/ui/application.rb', line 3228

def view_attachments
  msg = current_message
  return unless msg
  return set_feedback("Select a message first", 245, 2) if header_message?(msg)

  # Load full message if needed (use numeric id only)
  msg_id = msg['id']
  if msg_id && msg_id.is_a?(Integer) && !msg.key?('attachments')
    full = @db.get_message(msg_id)
    msg.merge!(full) if full
  end

  attachments = msg['attachments']
  unless attachments.is_a?(Array) && !attachments.empty?
    set_feedback("No attachments", 226, 2)
    return
  end

  maildir_file = msg.dig('metadata', 'maildir_file') || msg.dig('metadata', :maildir_file)
  unless maildir_file && File.exist?(maildir_file.to_s)
    set_feedback("Source mail file not found", 196, 2)
    return
  end

  # Interactive attachment browser in right pane
  att_index = 0
  att_tagged = Set.new

  render_attachment_list(attachments, att_index, att_tagged)
  @panes[:bottom].text = " j/k:Navigate  t:Tag  T:Tag all  o:Open  s:Save  ESC:Back".fg(245)
  @panes[:bottom].refresh

  loop do
    chr = getchr
    case chr
    when 'j', 'DOWN'
      att_index = (att_index + 1) % attachments.size
      render_attachment_list(attachments, att_index, att_tagged)
    when 'k', 'UP'
      att_index = (att_index - 1) % attachments.size
      render_attachment_list(attachments, att_index, att_tagged)
    when 't'
      if att_tagged.include?(att_index)
        att_tagged.delete(att_index)
      else
        att_tagged.add(att_index)
      end
      att_index = (att_index + 1) % attachments.size
      render_attachment_list(attachments, att_index, att_tagged)
    when 'T'
      # Toggle all
      if att_tagged.size == attachments.size
        att_tagged.clear
      else
        attachments.each_index { |i| att_tagged.add(i) }
      end
      render_attachment_list(attachments, att_index, att_tagged)
    when 'o', 'ENTER'
      targets = att_tagged.empty? ? [att_index] : att_tagged.to_a.sort
      open_attachments(maildir_file, attachments, targets)
      render_attachment_list(attachments, att_index, att_tagged)
      @panes[:bottom].text = " j/k:Navigate  t:Tag  T:Tag all  o:Open  s:Save  ESC:Back".fg(245)
      @panes[:bottom].refresh
    when 's'
      targets = att_tagged.empty? ? [att_index] : att_tagged.to_a.sort
      save_attachments(maildir_file, attachments, targets)
      render_attachment_list(attachments, att_index, att_tagged)
    when 'q', 'ESC', "\e", 'h', 'LEFT'
      break
    end
  end

  @panes[:right].content_update = true
  render_all
end