Class: Echoes::GUI

Inherits:
Object
  • Object
show all
Defined in:
lib/echoes/gui.rb

Constant Summary collapse

CRASH_LOG =
File.join(Dir.home, '.local', 'share', 'echoes', 'crash.log')

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(command: Echoes.config.shell, rows: Echoes.config.rows, cols: Echoes.config.cols, font_size: nil) ⇒ GUI

Returns a new instance of GUI.



27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
# File 'lib/echoes/gui.rb', line 27

def initialize(command: Echoes.config.shell, rows: Echoes.config.rows, cols: Echoes.config.cols, font_size: nil)
  # Advertise ourselves the way other terminals do (iTerm2,
  # WezTerm, Ghostty, …). Child shells and any program they
  # spawn inherit these via the normal env-inheritance path.
  ENV['TERM_PROGRAM']         = 'Echoes'
  ENV['TERM_PROGRAM_VERSION'] = Echoes::VERSION
  @rows = rows
  @cols = cols
  # Persisted font size wins over the config default; both wrappers
  # gracefully fall through if NSUserDefaults isn't reachable.
  @font_size = font_size || Preferences.fetch_double(:font_size, default: Echoes.config.font_size)
  @command = command
  @tabs = []
  @active_tab = 0
  @active_profile = Echoes.config.default_profile
  @colors = build_color_table
  @default_fg = make_color(*@active_profile.foreground)
  @default_bg = make_color(*@active_profile.background)
  @tab_bg = make_color(0.15, 0.15, 0.15)
  @tab_fg_active   = make_color(0.95, 0.95, 0.95)
  @tab_fg_inactive = make_color(0.55, 0.55, 0.55)
  @selection_color = make_color(*@active_profile.selection_color)
  @search_match_color = make_color(0.6, 0.5, 0.0)
  @search_current_color = make_color(0.8, 0.6, 0.0)
  @selection_anchor = nil
  @selection_end = nil
  @selection_word_anchor = nil
  @font_cache = {}
  @rgb_color_cache = {}
  @nsstring_cache = {}
  @cursor_blink_on = true
  @cursor_blink_counter = 0
  @search_mode = false
  @search_query = +""
  @search_matches = []
  @search_index = -1
  @search_regex_mode = false
  @search_case_insensitive = false
  @bell_flash = 0
  @marked_text = nil
  @current_event = nil
  @pane_divider_color = make_color(*Echoes.config.pane_divider_color)
  @active_pane_border_color = make_color(*Echoes.config.active_pane_border_color)
  @copy_mode_cursor_color = make_color(*Echoes.config.copy_mode_cursor_color)
  @window_states = []
  @view_to_ws = {}
end

Class Method Details

.capture_format_for(path) ⇒ Object

Pick raster vs vector by file extension. PDF is the default for anything other than ‘.png` — it’s both the cheaper and more useful format for terminal content.



3023
3024
3025
# File 'lib/echoes/gui.rb', line 3023

def self.capture_format_for(path)
  File.extname(path).downcase == '.png' ? :png : :pdf
end

.cwd_from_osc7_uri(uri_str) ⇒ Object



113
114
115
116
117
118
119
120
121
122
123
124
125
# File 'lib/echoes/gui.rb', line 113

def self.cwd_from_osc7_uri(uri_str)
  return nil if uri_str.nil? || uri_str.empty?
  uri = URI.parse(uri_str) rescue nil
  return nil unless uri && uri.scheme == 'file'
  host = uri.host.to_s
  local_host = Socket.gethostname
  unless host.empty? || host == 'localhost' ||
         host == local_host || host == local_host.split('.').first
    return nil
  end
  path = URI.decode_www_form_component(uri.path) rescue nil
  path if path && !path.empty? && Dir.exist?(path)
end

.file_paths_from_pasteboard(pb) ⇒ Object



2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
# File 'lib/echoes/gui.rb', line 2111

def self.file_paths_from_pasteboard(pb)
  nsurl_class = ObjC.cls('NSURL')
  class_array = ObjC::MSG_PTR_1.call(ObjC.cls('NSArray'), ObjC.sel('arrayWithObject:'), nsurl_class)
  urls = ObjC::MSG_PTR_2.call(pb, ObjC.sel('readObjectsForClasses:options:'), class_array, Fiddle::Pointer.new(0))
  return nil if urls.null?

  count = ObjC::MSG_RET_L.call(urls, ObjC.sel('count'))
  return nil if count == 0

  paths = count.times.map do |i|
    url = ObjC::MSG_PTR_L.call(urls, ObjC.sel('objectAtIndex:'), i)
    ns_path = ObjC::MSG_PTR.call(url, ObjC.sel('path'))
    ObjC.to_ruby_string(ns_path).shellescape
  end
  paths.join(' ')
end

.pane_local_cwd(pane) ⇒ Object

Convert the active pane’s OSC 7 ‘current_directory` URI into a local filesystem path, or return nil if it isn’t a usable local path (missing, malformed, points at a remote host, or doesn’t exist).



108
109
110
111
# File 'lib/echoes/gui.rb', line 108

def self.pane_local_cwd(pane)
  uri_str = pane&.screen&.current_directory
  cwd_from_osc7_uri(uri_str)
end

Instance Method Details

#activate_for_view(view_ptr) ⇒ Object



153
154
155
156
157
158
# File 'lib/echoes/gui.rb', line 153

def activate_for_view(view_ptr)
  ws = @view_to_ws[view_ptr.to_i]
  return unless ws
  save_window_state
  load_window_state(ws)
end

#apply_profile(name) ⇒ Object

Switch the active profile (color theme) by name. Releases the current NSColor cache, rebuilds default fg/bg/selection and the 256-color palette from the new profile, and triggers a full repaint so every existing cell picks up the new colors. Per-pane gradient overlays (OSC 7772 bg-* commands) are left alone — those are user-driven decoration, not theme.



2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
# File 'lib/echoes/gui.rb', line 2045

def apply_profile(name)
  profile = Echoes.config.all_profiles[name.to_s]
  return unless profile
  @active_profile = profile

  ObjC.release(@default_fg)        if @default_fg
  ObjC.release(@default_bg)        if @default_bg
  ObjC.release(@selection_color)   if @selection_color
  @colors&.each_value { |c| ObjC.release(c) }

  @colors = build_color_table
  @default_fg      = make_color(*@active_profile.foreground)
  @default_bg      = make_color(*@active_profile.background)
  @selection_color = make_color(*@active_profile.selection_color)
  @rgb_color_cache = {}  # truecolor cache stale after palette swap

  @window_states.each do |ws|
    ws[:tabs].each { |tab| tab.panes.each { |p| p.screen.mark_all_dirty } } if ws[:tabs]
    ObjC::MSG_VOID_I.call(ws[:nsview], ObjC.sel('setNeedsDisplay:'), 1) if ws[:nsview]
  end
end

#close_tab(index) ⇒ Object



127
128
129
130
131
132
133
134
135
136
137
138
139
140
# File 'lib/echoes/gui.rb', line 127

def close_tab(index)
  return if index < 0 || index >= @tabs.size

  @tabs[index].close
  @tabs.delete_at(index)

  if @tabs.empty?
    close_current_window
    return
  end

  @active_tab = @active_tab.clamp(0, @tabs.size - 1)
  reflow_to_current_view_size
end

#completion_picked(sender) ⇒ Object

Action callback for an NSMenuItem in the completion popup. Reads the sender’s tag, looks up the chosen candidate, and asks the pane to splice it into the input buffer. Public — invoked from the @completion_picked_closure with an explicit receiver (‘gui.completion_picked(sender)`); the rest of this section’s helpers are private (called from inside the class).



2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
# File 'lib/echoes/gui.rb', line 2297

public def completion_picked(sender)
  state = @completion_state
  return unless state
  tag = ObjC::MSG_RET_L.call(sender, ObjC.sel('tag'))
  cand = state[:candidates][tag]
  return unless cand
  state[:pane].apply_completion(word_start: state[:word_start], completion: cand)
  ObjC::MSG_VOID_I.call(@view, ObjC.sel('setNeedsDisplay:'), 1)
ensure
  @completion_state = nil
end

#copy_mode_key_down(event_ptr, pane) ⇒ Object



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
# File 'lib/echoes/gui.rb', line 1532

def copy_mode_key_down(event_ptr, pane)
  chars_ns = ObjC::MSG_PTR.call(event_ptr, ObjC.sel('characters'))
  chars = ObjC.to_ruby_string(chars_ns)
  flags = ObjC::MSG_RET_L.call(event_ptr, ObjC.sel('modifierFlags'))

  key = if (flags & ObjC::NSEventModifierFlagControl) != 0
          (chars[0].ord & 0x1F).chr
        else
          chars
        end

  result = pane.copy_mode.handle_key(key)
  case result
  when :exit
    pane.copy_mode = nil
  when :yank
    text = pane.copy_mode.selected_text
    unless text.empty?
      pb = ObjC::MSG_PTR.call(ObjC.cls('NSPasteboard'), ObjC.sel('generalPasteboard'))
      ObjC::MSG_PTR.call(pb, ObjC.sel('clearContents'))
      ObjC::MSG_PTR_2.call(pb, ObjC.sel('setString:forType:'), ObjC.nsstring(text), ObjC::NSPasteboardTypeString)
    end
    pane.copy_mode.exit
    pane.copy_mode = nil
  end
  ObjC::MSG_VOID_I.call(@view, ObjC.sel('setNeedsDisplay:'), 1)
end

#create_fontsObject



435
436
437
438
439
440
# File 'lib/echoes/gui.rb', line 435

def create_fonts
  @font = ObjC.retain(create_nsfont(@font_size))
  @bold_font = ObjC.retain(create_bold_nsfont(@font))
  @font_y_offset_cache = {}
  update_cell_metrics
end

#create_tab(editor_file: nil) ⇒ Object



84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
# File 'lib/echoes/gui.rb', line 84

def create_tab(editor_file: nil)
  cwd = self.class.pane_local_cwd(current_tab&.active_pane)
  tab = Tab.new(command: @command, rows: @rows, cols: @cols, cwd: cwd,
                embedded: embedded_mode?, editor_file: editor_file)
  tab.title = editor_file ? File.basename(editor_file) : "Tab #{@tabs.size + 1}"
  tab.panes.each { |pane| wire_screen_handlers(pane) }
  # Insert next to the current tab (Cmd+T from the middle of
  # the tab bar lands the new tab immediately to the right of
  # the active one, not at the far end) — matches Safari /
  # Chrome / iTerm2 muscle memory.
  if @tabs.empty?
    @tabs << tab
    @active_tab = 0
  else
    insert_at = @active_tab + 1
    @tabs.insert(insert_at, tab)
    @active_tab = insert_at
  end
  reflow_to_current_view_size
end

#create_view_classObject



442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
# File 'lib/echoes/gui.rb', line 442

def create_view_class
  gui = self

  @draw_rect_closure = Fiddle::Closure::BlockCaller.new(
    Fiddle::TYPE_VOID,
    [Fiddle::TYPE_VOIDP, Fiddle::TYPE_VOIDP,
     Fiddle::TYPE_DOUBLE, Fiddle::TYPE_DOUBLE, Fiddle::TYPE_DOUBLE, Fiddle::TYPE_DOUBLE]
  ) do |_self, _cmd, x, y, w, h|
    gui.activate_for_view(_self); gui.draw_rect(y, y + h)
  rescue => e
    gui.log_crash(e, context: 'draw_rect')
  end

  @key_down_closure = Fiddle::Closure::BlockCaller.new(
    Fiddle::TYPE_VOID,
    [Fiddle::TYPE_VOIDP, Fiddle::TYPE_VOIDP, Fiddle::TYPE_VOIDP]
  ) do |_self, _cmd, event|
    gui.activate_for_view(_self); gui.key_down(event)
  rescue => e
    gui.log_crash(e, context: 'key_down')
  end

  @accepts_fr_closure = Fiddle::Closure::BlockCaller.new(
    Fiddle::TYPE_INT,
    [Fiddle::TYPE_VOIDP, Fiddle::TYPE_VOIDP]
  ) { |_self, _cmd| 1 }

  @timer_fired_closure = Fiddle::Closure::BlockCaller.new(
    Fiddle::TYPE_VOID,
    [Fiddle::TYPE_VOIDP, Fiddle::TYPE_VOIDP, Fiddle::TYPE_VOIDP]
  ) do |_self, _cmd, _timer|
    gui.timer_fired
  rescue => e
    gui.log_crash(e, context: 'timer_fired')
  end

  @is_flipped_closure = Fiddle::Closure::BlockCaller.new(
    Fiddle::TYPE_INT,
    [Fiddle::TYPE_VOIDP, Fiddle::TYPE_VOIDP]
  ) { |_self, _cmd| 1 }

  # AppKit calls this when it (re)builds cursor rects for the
  # view — on key-window changes, view-resize, and explicit
  # `[window invalidateCursorRectsForView:view]` calls. Register
  # an I-beam over the entire content area so the mouse cursor
  # turns into a text-selection bar when hovering over the grid.
  @reset_cursor_rects_closure = Fiddle::Closure::BlockCaller.new(
    Fiddle::TYPE_VOID,
    [Fiddle::TYPE_VOIDP, Fiddle::TYPE_VOIDP]
  ) do |_self, _cmd|
    ibeam = ObjC::MSG_PTR.call(ObjC.cls('NSCursor'), ObjC.sel('IBeamCursor'))
    w = (@cell_width || 8.0)  * ((@cols || 80) + 1)
    h = (@cell_height || 16.0) * ((@rows || 24) + 1) + tab_bar_height
    ObjC::MSG_VOID_RECT_1.call(_self, ObjC.sel('addCursorRect:cursor:'),
                               0.0, 0.0, w, h, ibeam)
  rescue => e
    gui.log_crash(e, context: 'resetCursorRects')
  end

  @scroll_wheel_closure = Fiddle::Closure::BlockCaller.new(
    Fiddle::TYPE_VOID,
    [Fiddle::TYPE_VOIDP, Fiddle::TYPE_VOIDP, Fiddle::TYPE_VOIDP]
  ) do |_self, _cmd, event|
    gui.activate_for_view(_self); gui.scroll_wheel(event)
  rescue => e
    gui.log_crash(e, context: 'scroll_wheel')
  end

  @mouse_down_closure = Fiddle::Closure::BlockCaller.new(
    Fiddle::TYPE_VOID,
    [Fiddle::TYPE_VOIDP, Fiddle::TYPE_VOIDP, Fiddle::TYPE_VOIDP]
  ) do |_self, _cmd, event|
    gui.activate_for_view(_self); gui.mouse_down(event)
  rescue => e
    gui.log_crash(e, context: 'mouse_down')
  end

  @mouse_dragged_closure = Fiddle::Closure::BlockCaller.new(
    Fiddle::TYPE_VOID,
    [Fiddle::TYPE_VOIDP, Fiddle::TYPE_VOIDP, Fiddle::TYPE_VOIDP]
  ) do |_self, _cmd, event|
    gui.activate_for_view(_self); gui.mouse_dragged(event)
  rescue => e
    gui.log_crash(e, context: 'mouse_dragged')
  end

  @mouse_moved_closure = Fiddle::Closure::BlockCaller.new(
    Fiddle::TYPE_VOID,
    [Fiddle::TYPE_VOIDP, Fiddle::TYPE_VOIDP, Fiddle::TYPE_VOIDP]
  ) do |_self, _cmd, event|
    gui.activate_for_view(_self); gui.mouse_moved(event)
  rescue => e
    gui.log_crash(e, context: 'mouse_moved')
  end

  @mouse_up_closure = Fiddle::Closure::BlockCaller.new(
    Fiddle::TYPE_VOID,
    [Fiddle::TYPE_VOIDP, Fiddle::TYPE_VOIDP, Fiddle::TYPE_VOIDP]
  ) do |_self, _cmd, event|
    gui.activate_for_view(_self); gui.mouse_up(event)
  rescue => e
    gui.log_crash(e, context: 'mouse_up')
  end

  @right_mouse_down_closure = Fiddle::Closure::BlockCaller.new(
    Fiddle::TYPE_VOID,
    [Fiddle::TYPE_VOIDP, Fiddle::TYPE_VOIDP, Fiddle::TYPE_VOIDP]
  ) do |_self, _cmd, event|
    gui.activate_for_view(_self); gui.right_mouse_down(event)
  rescue => e
    gui.log_crash(e, context: 'right_mouse_down')
  end

  @right_mouse_dragged_closure = Fiddle::Closure::BlockCaller.new(
    Fiddle::TYPE_VOID,
    [Fiddle::TYPE_VOIDP, Fiddle::TYPE_VOIDP, Fiddle::TYPE_VOIDP]
  ) do |_self, _cmd, event|
    gui.activate_for_view(_self); gui.right_mouse_dragged(event)
  rescue => e
    gui.log_crash(e, context: 'right_mouse_dragged')
  end

  @right_mouse_up_closure = Fiddle::Closure::BlockCaller.new(
    Fiddle::TYPE_VOID,
    [Fiddle::TYPE_VOIDP, Fiddle::TYPE_VOIDP, Fiddle::TYPE_VOIDP]
  ) do |_self, _cmd, event|
    gui.activate_for_view(_self); gui.right_mouse_up(event)
  rescue => e
    gui.log_crash(e, context: 'right_mouse_up')
  end

  @other_mouse_down_closure = Fiddle::Closure::BlockCaller.new(
    Fiddle::TYPE_VOID,
    [Fiddle::TYPE_VOIDP, Fiddle::TYPE_VOIDP, Fiddle::TYPE_VOIDP]
  ) do |_self, _cmd, event|
    gui.activate_for_view(_self); gui.other_mouse_down(event)
  rescue => e
    gui.log_crash(e, context: 'other_mouse_down')
  end

  @other_mouse_dragged_closure = Fiddle::Closure::BlockCaller.new(
    Fiddle::TYPE_VOID,
    [Fiddle::TYPE_VOIDP, Fiddle::TYPE_VOIDP, Fiddle::TYPE_VOIDP]
  ) do |_self, _cmd, event|
    gui.activate_for_view(_self); gui.other_mouse_dragged(event)
  rescue => e
    gui.log_crash(e, context: 'other_mouse_dragged')
  end

  @other_mouse_up_closure = Fiddle::Closure::BlockCaller.new(
    Fiddle::TYPE_VOID,
    [Fiddle::TYPE_VOIDP, Fiddle::TYPE_VOIDP, Fiddle::TYPE_VOIDP]
  ) do |_self, _cmd, event|
    gui.activate_for_view(_self); gui.other_mouse_up(event)
  rescue => e
    gui.log_crash(e, context: 'other_mouse_up')
  end

  @perform_key_equiv_closure = Fiddle::Closure::BlockCaller.new(
    Fiddle::TYPE_INT,
    [Fiddle::TYPE_VOIDP, Fiddle::TYPE_VOIDP, Fiddle::TYPE_VOIDP]
  ) { |_self, _cmd, event| gui.activate_for_view(_self); gui.perform_key_equivalent(event) }

  # Get NSView's original setFrameSize: IMP so we can call super
  nsview_cls = ObjC.cls('NSView')
  super_imp = ObjC::GetMethodImpl.call(nsview_cls, ObjC.sel('setFrameSize:'))
  @super_set_frame_size = Fiddle::Function.new(super_imp, [ObjC::P, ObjC::P, ObjC::D, ObjC::D], ObjC::V)

  @set_frame_size_closure = Fiddle::Closure::BlockCaller.new(
    Fiddle::TYPE_VOID,
    [Fiddle::TYPE_VOIDP, Fiddle::TYPE_VOIDP, Fiddle::TYPE_DOUBLE, Fiddle::TYPE_DOUBLE]
  ) do |_self, _cmd, w, h|
    @super_set_frame_size.call(_self, _cmd, w, h)
    gui.activate_for_view(_self)
    gui.handle_resize(w, h)
  rescue => e
    gui.log_crash(e, context: 'set_frame_size')
  end

  # NSTextInputClient protocol closures for IME support
  @insert_text_closure = Fiddle::Closure::BlockCaller.new(
    Fiddle::TYPE_VOID,
    [Fiddle::TYPE_VOIDP, Fiddle::TYPE_VOIDP, Fiddle::TYPE_VOIDP, Fiddle::TYPE_LONG, Fiddle::TYPE_LONG]
  ) do |_self, _cmd, text, _rep_loc, _rep_len|
    gui.activate_for_view(_self); gui.ime_insert_text(text)
  rescue => e
    gui.log_crash(e, context: 'insert_text')
  end

  @insert_text_simple_closure = Fiddle::Closure::BlockCaller.new(
    Fiddle::TYPE_VOID,
    [Fiddle::TYPE_VOIDP, Fiddle::TYPE_VOIDP, Fiddle::TYPE_VOIDP]
  ) do |_self, _cmd, text|
    gui.activate_for_view(_self); gui.ime_insert_text(text)
  rescue => e
    gui.log_crash(e, context: 'insert_text_simple')
  end

  @do_command_closure = Fiddle::Closure::BlockCaller.new(
    Fiddle::TYPE_VOID,
    [Fiddle::TYPE_VOIDP, Fiddle::TYPE_VOIDP, Fiddle::TYPE_VOIDP]
  ) do |_self, _cmd, _selector|
    gui.activate_for_view(_self); gui.ime_do_command
  rescue => e
    gui.log_crash(e, context: 'do_command')
  end

  @set_marked_text_closure = Fiddle::Closure::BlockCaller.new(
    Fiddle::TYPE_VOID,
    [Fiddle::TYPE_VOIDP, Fiddle::TYPE_VOIDP, Fiddle::TYPE_VOIDP,
     Fiddle::TYPE_LONG, Fiddle::TYPE_LONG, Fiddle::TYPE_LONG, Fiddle::TYPE_LONG]
  ) do |_self, _cmd, text, sel_loc, sel_len, _rep_loc, _rep_len|
    gui.activate_for_view(_self); gui.ime_set_marked_text(text, sel_loc, sel_len)
  rescue => e
    gui.log_crash(e, context: 'set_marked_text')
  end

  @unmark_text_closure = Fiddle::Closure::BlockCaller.new(
    Fiddle::TYPE_VOID,
    [Fiddle::TYPE_VOIDP, Fiddle::TYPE_VOIDP]
  ) do |_self, _cmd|
    gui.activate_for_view(_self); gui.ime_unmark_text
  rescue => e
    gui.log_crash(e, context: 'unmark_text')
  end

  @has_marked_text_closure = Fiddle::Closure::BlockCaller.new(
    Fiddle::TYPE_INT,
    [Fiddle::TYPE_VOIDP, Fiddle::TYPE_VOIDP]
  ) { |_self, _cmd| gui.ime_has_marked_text }

  @marked_range_closure = Fiddle::Closure::BlockCaller.new(
    Fiddle::TYPE_LONG,
    [Fiddle::TYPE_VOIDP, Fiddle::TYPE_VOIDP]
  ) { |_self, _cmd| gui.ime_marked_range_location }

  @selected_range_closure = Fiddle::Closure::BlockCaller.new(
    Fiddle::TYPE_LONG,
    [Fiddle::TYPE_VOIDP, Fiddle::TYPE_VOIDP]
  ) { |_self, _cmd| 0x7FFFFFFFFFFFFFFF } # NSNotFound

  @valid_attrs_closure = Fiddle::Closure::BlockCaller.new(
    Fiddle::TYPE_VOIDP,
    [Fiddle::TYPE_VOIDP, Fiddle::TYPE_VOIDP]
  ) { |_self, _cmd| ObjC::MSG_PTR.call(ObjC.cls('NSArray'), ObjC.sel('array')) }

  @attr_substring_closure = Fiddle::Closure::BlockCaller.new(
    Fiddle::TYPE_VOIDP,
    [Fiddle::TYPE_VOIDP, Fiddle::TYPE_VOIDP, Fiddle::TYPE_LONG, Fiddle::TYPE_LONG, Fiddle::TYPE_VOIDP]
  ) { |_self, _cmd, _loc, _len, _actual| Fiddle::Pointer.new(0) }

  @first_rect_closure = Fiddle::Closure::BlockCaller.new(
    Fiddle::TYPE_DOUBLE,
    [Fiddle::TYPE_VOIDP, Fiddle::TYPE_VOIDP, Fiddle::TYPE_LONG, Fiddle::TYPE_LONG, Fiddle::TYPE_VOIDP]
  ) { |_self, _cmd, _loc, _len, _actual| 0.0 }

  @char_index_closure = Fiddle::Closure::BlockCaller.new(
    Fiddle::TYPE_LONG,
    [Fiddle::TYPE_VOIDP, Fiddle::TYPE_VOIDP, Fiddle::TYPE_DOUBLE, Fiddle::TYPE_DOUBLE]
  ) { |_self, _cmd, _x, _y| 0x7FFFFFFFFFFFFFFF } # NSNotFound

  menu_action = proc { |action_block|
    Fiddle::Closure::BlockCaller.new(
      Fiddle::TYPE_VOID,
      [Fiddle::TYPE_VOIDP, Fiddle::TYPE_VOIDP, Fiddle::TYPE_VOIDP]
    ) do |_self, _cmd, _sender|
      gui.activate_for_view(_self); action_block.call
    rescue => e
      gui.log_crash(e, context: 'menu_action')
    end
  }

  @show_about_closure = menu_action.call(-> { show_about_panel })

  # One closure per declared profile, indexed by name. The
  # menu builder later wires each into its own
  # `applyProfile_<n>:` selector so AppKit can deliver the
  # right one without us having to dispatch by event payload.
  @profile_closures = {}
  Echoes.config.all_profiles.each_key do |pname|
    @profile_closures[pname] = menu_action.call(-> { apply_profile(pname) })
  end
  @new_window_closure = menu_action.call(-> { open_new_window })
  @new_tab_closure = menu_action.call(-> {
    create_tab
    ObjC::MSG_VOID_I.call(@view, ObjC.sel('setNeedsDisplay:'), 1)
  })
  @edit_file_closure = menu_action.call(-> {
    path = prompt_for_file_to_edit
    if path
      create_tab(editor_file: path)
      ObjC::MSG_VOID_I.call(@view, ObjC.sel('setNeedsDisplay:'), 1)
    end
  })
  @close_tab_closure = menu_action.call(-> {
    close_tab(@active_tab)
    ObjC::MSG_VOID_I.call(@view, ObjC.sel('setNeedsDisplay:'), 1)
  })
  @copy_closure = menu_action.call(-> { copy_to_clipboard })
  @paste_closure = menu_action.call(-> { paste_from_clipboard })
  @select_all_closure = menu_action.call(-> { select_all })
  @increase_font_closure = menu_action.call(-> { update_font(@font_size + 1.0) })
  @decrease_font_closure = menu_action.call(-> { update_font(@font_size - 1.0) if @font_size > 4.0 })
  @reset_font_closure = menu_action.call(-> {
    Preferences.delete(:font_size)
    update_font(Echoes.config.font_size, persist: false)
  })
  @toggle_find_closure = menu_action.call(-> {
    toggle_search
    ObjC::MSG_VOID_I.call(@view, ObjC.sel('setNeedsDisplay:'), 1)
  })
  @find_next_closure = menu_action.call(-> {
    if @search_mode && !@search_matches.empty?
      search_next
      ObjC::MSG_VOID_I.call(@view, ObjC.sel('setNeedsDisplay:'), 1)
    end
  })
  @find_prev_closure = menu_action.call(-> {
    if @search_mode && !@search_matches.empty?
      search_prev
      ObjC::MSG_VOID_I.call(@view, ObjC.sel('setNeedsDisplay:'), 1)
    end
  })
  @prev_tab_closure = menu_action.call(-> {
    @active_tab = (@active_tab - 1) % @tabs.size
    ObjC::MSG_VOID_I.call(@view, ObjC.sel('setNeedsDisplay:'), 1)
  })
  @next_tab_closure = menu_action.call(-> {
    @active_tab = (@active_tab + 1) % @tabs.size
    ObjC::MSG_VOID_I.call(@view, ObjC.sel('setNeedsDisplay:'), 1)
  })
  @split_right_closure = menu_action.call(-> {
    tab = current_tab
    new_pane = tab.split_vertical
    wire_screen_handlers(new_pane)
    ObjC::MSG_VOID_I.call(@view, ObjC.sel('setNeedsDisplay:'), 1)
  })
  @split_down_closure = menu_action.call(-> {
    tab = current_tab
    new_pane = tab.split_horizontal
    wire_screen_handlers(new_pane)
    ObjC::MSG_VOID_I.call(@view, ObjC.sel('setNeedsDisplay:'), 1)
  })
  @close_pane_closure = menu_action.call(-> {
    tab = current_tab
    if tab.pane_tree.single_pane?
      close_tab(@active_tab)
    else
      tab.close_active_pane
    end
    ObjC::MSG_VOID_I.call(@view, ObjC.sel('setNeedsDisplay:'), 1)
  })
  @select_next_pane_closure = menu_action.call(-> {
    current_tab.next_pane
    ObjC::MSG_VOID_I.call(@view, ObjC.sel('setNeedsDisplay:'), 1)
  })
  @select_prev_pane_closure = menu_action.call(-> {
    current_tab.prev_pane
    ObjC::MSG_VOID_I.call(@view, ObjC.sel('setNeedsDisplay:'), 1)
  })
  # NSMenu items dispatched from the tab-completion popup. Unlike the
  # main-menu actions, the completion picker needs the sender so we
  # can read its tag (= candidate index); menu_action's no-arg
  # convention isn't a fit, so wire it manually.
  @completion_picked_closure = Fiddle::Closure::BlockCaller.new(
    Fiddle::TYPE_VOID,
    [Fiddle::TYPE_VOIDP, Fiddle::TYPE_VOIDP, Fiddle::TYPE_VOIDP]
  ) do |_self, _cmd, sender|
    gui.activate_for_view(_self); gui.completion_picked(sender)
  rescue => e
    gui.log_crash(e, context: 'completionPicked')
  end

  @toggle_pointer_closure = menu_action.call(-> {
    # NSCursor's hide/unhide are reference-counted; track state so
    # repeated invocations toggle cleanly. We don't use
    # `setHiddenUntilMouseMoves:` because the user wants explicit
    # control (mouse-move shouldn't undo a deliberate hide).
    if @pointer_hidden
      ObjC::MSG_VOID.call(ObjC.cls('NSCursor'), ObjC.sel('unhide'))
      @pointer_hidden = false
    else
      ObjC::MSG_VOID.call(ObjC.cls('NSCursor'), ObjC.sel('hide'))
      @pointer_hidden = true
    end
  })

  @toggle_copy_mode_closure = menu_action.call(-> {
    pane = current_tab.active_pane
    if pane.copy_mode&.active
      pane.copy_mode.exit
      pane.copy_mode = nil
    else
      pane.copy_mode = CopyMode.new(pane.screen)
      pane.copy_mode.enter
    end
    ObjC::MSG_VOID_I.call(@view, ObjC.sel('setNeedsDisplay:'), 1)
  })

  @dragging_entered_closure = Fiddle::Closure::BlockCaller.new(
    Fiddle::TYPE_LONG,
    [Fiddle::TYPE_VOIDP, Fiddle::TYPE_VOIDP, Fiddle::TYPE_VOIDP]
  ) { |_self, _cmd, _sender| 1 }  # NSDragOperationCopy

  @perform_drag_closure = Fiddle::Closure::BlockCaller.new(
    Fiddle::TYPE_INT,
    [Fiddle::TYPE_VOIDP, Fiddle::TYPE_VOIDP, Fiddle::TYPE_VOIDP]
  ) do |_self, _cmd, sender|
    gui.activate_for_view(_self); gui.perform_drag_operation(sender) ? 1 : 0
  rescue => e
    gui.log_crash(e, context: 'performDragOperation')
    0
  end

  @focus_gained_closure = Fiddle::Closure::BlockCaller.new(
    Fiddle::TYPE_VOID,
    [Fiddle::TYPE_VOIDP, Fiddle::TYPE_VOIDP, Fiddle::TYPE_VOIDP]
  ) { |_self, _cmd, _notification| gui.activate_for_view(_self); gui.window_focus_changed(true) }

  @focus_lost_closure = Fiddle::Closure::BlockCaller.new(
    Fiddle::TYPE_VOID,
    [Fiddle::TYPE_VOIDP, Fiddle::TYPE_VOIDP, Fiddle::TYPE_VOIDP]
  ) { |_self, _cmd, _notification| gui.activate_for_view(_self); gui.window_focus_changed(false) }

  @view_class = ObjC.define_class('EchoesTerminalView', 'NSView', {
    'drawRect:'             => ['v@:{CGRect=dddd}', @draw_rect_closure],
    'keyDown:'              => ['v@:@', @key_down_closure],
    'acceptsFirstResponder' => ['c@:', @accepts_fr_closure],
    'timerFired:'           => ['v@:@', @timer_fired_closure],
    'isFlipped'             => ['c@:', @is_flipped_closure],
    'resetCursorRects'      => ['v@:', @reset_cursor_rects_closure],
    'scrollWheel:'          => ['v@:@', @scroll_wheel_closure],
    'mouseDown:'            => ['v@:@', @mouse_down_closure],
    'mouseDragged:'         => ['v@:@', @mouse_dragged_closure],
    'mouseMoved:'           => ['v@:@', @mouse_moved_closure],
    'mouseUp:'              => ['v@:@', @mouse_up_closure],
    'rightMouseDown:'       => ['v@:@', @right_mouse_down_closure],
    'rightMouseDragged:'    => ['v@:@', @right_mouse_dragged_closure],
    'rightMouseUp:'         => ['v@:@', @right_mouse_up_closure],
    'otherMouseDown:'       => ['v@:@', @other_mouse_down_closure],
    'otherMouseDragged:'    => ['v@:@', @other_mouse_dragged_closure],
    'otherMouseUp:'         => ['v@:@', @other_mouse_up_closure],
    'performKeyEquivalent:' => ['c@:@', @perform_key_equiv_closure],
    'setFrameSize:'         => ['v@:{CGSize=dd}', @set_frame_size_closure],
    'windowDidBecomeKey:'   => ['v@:@', @focus_gained_closure],
    'windowDidResignKey:'   => ['v@:@', @focus_lost_closure],
    'showAbout:'             => ['v@:@', @show_about_closure],
    **profile_selectors,
    'newWindow:'             => ['v@:@', @new_window_closure],
    'newTab:'               => ['v@:@', @new_tab_closure],
    'editFile:'             => ['v@:@', @edit_file_closure],
    'closeTab:'             => ['v@:@', @close_tab_closure],
    'copy:'                 => ['v@:@', @copy_closure],
    'paste:'                => ['v@:@', @paste_closure],
    'selectAll:'            => ['v@:@', @select_all_closure],
    'increaseFontSize:'     => ['v@:@', @increase_font_closure],
    'decreaseFontSize:'     => ['v@:@', @decrease_font_closure],
    'resetFontSize:'        => ['v@:@', @reset_font_closure],
    'toggleFind:'           => ['v@:@', @toggle_find_closure],
    'findNext:'             => ['v@:@', @find_next_closure],
    'findPrevious:'         => ['v@:@', @find_prev_closure],
    'showPreviousTab:'      => ['v@:@', @prev_tab_closure],
    'showNextTab:'          => ['v@:@', @next_tab_closure],
    'splitRight:'           => ['v@:@', @split_right_closure],
    'splitDown:'            => ['v@:@', @split_down_closure],
    'closePane:'            => ['v@:@', @close_pane_closure],
    'selectNextPane:'       => ['v@:@', @select_next_pane_closure],
    'selectPreviousPane:'   => ['v@:@', @select_prev_pane_closure],
    'toggleCopyMode:'       => ['v@:@', @toggle_copy_mode_closure],
    'togglePointer:'        => ['v@:@', @toggle_pointer_closure],
    'completionPicked:'     => ['v@:@', @completion_picked_closure],
    # NSTextInputClient protocol methods for IME
    'insertText:replacementRange:'                      => ['v@:@{_NSRange=QQ}', @insert_text_closure],
    'insertText:'                                       => ['v@:@', @insert_text_simple_closure],
    'doCommandBySelector:'                              => ['v@::', @do_command_closure],
    'setMarkedText:selectedRange:replacementRange:'     => ['v@:@{_NSRange=QQ}{_NSRange=QQ}', @set_marked_text_closure],
    'unmarkText'                                        => ['v@:', @unmark_text_closure],
    'hasMarkedText'                                     => ['c@:', @has_marked_text_closure],
    'markedRange'                                       => ['{_NSRange=QQ}@:', @marked_range_closure],
    'selectedRange'                                     => ['{_NSRange=QQ}@:', @selected_range_closure],
    'validAttributesForMarkedText'                      => ['@@:', @valid_attrs_closure],
    'attributedSubstringForProposedRange:actualRange:'  => ['@@:{_NSRange=QQ}^{_NSRange=QQ}', @attr_substring_closure],
    'firstRectForCharacterRange:actualRange:'           => ['{CGRect={CGPoint=dd}{CGSize=dd}}@:{_NSRange=QQ}^{_NSRange=QQ}', @first_rect_closure],
    'characterIndexForPoint:'                           => ['Q@:{CGPoint=dd}', @char_index_closure],
    'draggingEntered:'                                  => ['Q@:@', @dragging_entered_closure],
    'performDragOperation:'                             => ['c@:@', @perform_drag_closure],
  })

  # Add NSTextInputClient protocol conformance for IME
  protocol = ObjC::GetProtocol.call('NSTextInputClient')
  ObjC::AddProtocol.call(@view_class, protocol) unless protocol.null?
end

#current_tabObject



142
143
144
# File 'lib/echoes/gui.rb', line 142

def current_tab
  @tabs[@active_tab]
end

#disable_press_and_holdObject

macOS’s “Press and Hold” feature (ApplePressAndHoldEnabled, default ON) routes every Latin letter through a state machine that waits to see if the user is summoning the accent popup — for vowels and a handful of consonants it shows variants (à á â ä …), for the rest (B, F, J, M, P, Q, V, X — letters with no diacritical variants in the US English layout) it just silently suppresses key-repeat. Terminal users want auto-repeat on every letter, so we register a defaults override scoped to this process: AppKit sees the value on the next keyDown and falls back to plain auto-repeat.



265
266
267
268
269
270
271
# File 'lib/echoes/gui.rb', line 265

def disable_press_and_hold
  std = ObjC::MSG_PTR.call(ObjC.cls('NSUserDefaults'), ObjC.sel('standardUserDefaults'))
  dict = ObjC.nsdict({
    ObjC.nsstring('ApplePressAndHoldEnabled') => ObjC.nsnumber_int(0),
  })
  ObjC::MSG_VOID_1.call(std, ObjC.sel('registerDefaults:'), dict)
end

#draw_active_pane_border(tab, pane_rects, gy_off) ⇒ Object



1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
# File 'lib/echoes/gui.rb', line 1419

def draw_active_pane_border(tab, pane_rects, gy_off)
  active_rect = pane_rects.find { |r| r[:pane] == tab.active_pane }
  return unless active_rect

  ObjC::MSG_VOID.call(@active_pane_border_color, ObjC.sel('setFill'))

  px = active_rect[:x] * @cell_width
  py = gy_off + active_rect[:y] * @cell_height
  pw = active_rect[:w] * @cell_width
  ph = active_rect[:h] * @cell_height

  # Top border
  ObjC::NSRectFill.call(px, py, pw, 2.0)
  # Bottom border
  ObjC::NSRectFill.call(px, py + ph - 2.0, pw, 2.0)
  # Left border
  ObjC::NSRectFill.call(px, py, 2.0, ph)
  # Right border
  ObjC::NSRectFill.call(px + pw - 2.0, py, 2.0, ph)
end

#draw_pane_content(pane, px, py, dirty_min_y, dirty_max_y, is_active) ⇒ Object



1029
1030
1031
1032
1033
1034
1035
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
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
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
1125
1126
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
1164
1165
1166
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
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
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
1302
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
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
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
# File 'lib/echoes/gui.rb', line 1029

def draw_pane_content(pane, px, py, dirty_min_y, dirty_max_y, is_active)
  screen = pane.screen
  scrollback = screen.scrollback
  visible_start = scrollback.size - pane.scroll_offset
  pane_rows = screen.rows
  pane_cols = screen.cols

  copy_mode = pane.copy_mode

  # Per-pane gradient background (set via OSC 7772 ;bg-gradient).
  # Drawn before any cells so cell-level bg colors paint on top.
  draw_pane_background(screen.background, px, py, pane_cols, pane_rows) if screen.background
  draw_pane_fills(screen.bg_fills, px, py, pane_cols, pane_rows) if screen.bg_fills && !screen.bg_fills.empty?

  pane_rows.times do |r|
    y = py + r * @cell_height
    next if y + @cell_height < dirty_min_y || y > dirty_max_y
    src = visible_start + r
    row = if src < scrollback.size
            scrollback[src]
          elsif src - scrollback.size < screen.grid.size
            screen.grid[src - scrollback.size]
          end
    next unless row

    # Cell-background fills snap their left/right (and
    # top/bottom) to integer pixel boundaries against the
    # *next* cell's left edge. When @cell_width is fractional
    # (most monospace fonts at most sizes), independent per-
    # cell rounding leaves sub-pixel AA seams between adjacent
    # fills, which visibly stripe solid-bg regions (selection
    # ranges, search matches, SF_DATALESS-file highlights from
    # `ls`, …). Snapping with the next-boundary trick
    # guarantees neighbors share an exact device-pixel edge,
    # which is what makes the seams disappear.
    snap_fill = lambda do |fx, fy, fw, fh|
      x0 = fx.round
      x1 = (fx + fw).round
      y0 = fy.round
      y1 = (fy + fh).round
      ObjC::NSRectFill.call(x0.to_f, y0.to_f, (x1 - x0).to_f, (y1 - y0).to_f)
    end

    # Text-run accumulator. We batch consecutive cells with
    # matching style into one drawAtPoint call so the font
    # shaper sees adjacent characters and can apply ligatures
    # (`=>`, `!=`, `<=`, etc.) on fonts that have them.
    # Anything that can't extend the run (multicell, blank
    # non-bg cell, style change) flushes it first.
    run_chars   = +''
    run_start_c = nil
    run_attrs   = nil
    run_font    = nil
    run_sig     = nil
    flush_run = lambda do
      next if run_chars.empty?
      ns_run = ObjC.nsstring(run_chars)
      run_x  = px + run_start_c * @cell_width
      run_dy = y + y_offset_for_font(run_font)
      ObjC::MSG_VOID_PT_1.call(ns_run, ObjC.sel('drawAtPoint:withAttributes:'),
                               run_x, run_dy, run_attrs)
      run_chars   = +''
      run_start_c = nil
      run_attrs   = nil
      run_font    = nil
      run_sig     = nil
    end

    row.each_with_index do |cell, c|
      if cell.width == 0 || cell.multicell == :cont
        flush_run.call
        next
      end

      fg_val = cell.fg
      bg_val = cell.bg
      default_fg = @default_fg
      default_bg = @default_bg
      if cell.inverse
        fg_val, bg_val = bg_val, fg_val
        default_fg, default_bg = default_bg, default_fg
      end

      fg_color = resolve_color(fg_val, default_fg)
      bg_color = resolve_color(bg_val, default_bg)

      if cell.bold && fg_val.is_a?(Integer) && fg_val < 8
        fg_color = @colors[fg_val + 8]
      end

      has_bg = !bg_val.nil? || cell.inverse

      selected = is_active && cell_selected?(src, c)
      is_match = is_active && @search_mode && search_match_at?(src, c)
      is_current_match = is_active && @search_mode && current_search_match_at?(src, c)

      # Copy mode selection highlight
      if copy_mode&.active && copy_mode.selecting?
        sel_start, sel_end = [copy_mode.selection_start, copy_mode.selection_end].sort_by { |p| [p[0], p[1]] }
        cm_abs_row = scrollback.size + r - pane.scroll_offset
        if cm_abs_row >= scrollback.size + sel_start[0] && cm_abs_row <= scrollback.size + sel_end[0]
          cm_row = cm_abs_row - scrollback.size
          if cm_row == sel_start[0] && cm_row == sel_end[0]
            selected = c >= sel_start[1] && c <= sel_end[1]
          elsif cm_row == sel_start[0]
            selected = c >= sel_start[1]
          elsif cm_row == sel_end[0]
            selected = c <= sel_end[1]
          else
            selected = true
          end
        end
      end

      if cell.multicell.is_a?(Hash)
        flush_run.call
        mc = cell.multicell
        x = px + c * @cell_width
        block_w = mc[:cols] * @cell_width
        block_h = mc[:rows] * @cell_height

        if selected
          ObjC::MSG_VOID.call(@selection_color, ObjC.sel('setFill'))
          snap_fill.call(x, y, block_w, block_h)
        elsif has_bg
          ObjC::MSG_VOID.call(bg_color, ObjC.sel('setFill'))
          snap_fill.call(x, y, block_w, block_h)
        end

        if mc[:sixel]
          draw_sixel_image(mc[:sixel], x, y, block_w, block_h)
          next
        end

        next if cell.char == " " && !has_bg

        # Per OSC 66 spec, n=/d= define a fraction *of* the scale.
        # Effective glyph size is `s × n/d`. The reserved block
        # stays at the full s×s*width — n=/d= shrink (or grow) the
        # glyph within that block, paired with v=/h= for placement.
        # Example: `s=2:n=1:d=2:v=2;●` reserves 2×2 cells and draws
        # a 1-cell ● centered vertically inside it.
        effective_scale = mc[:scale].to_f
        if mc[:frac_d] > 0 && mc[:frac_n] > 0
          effective_scale *= mc[:frac_n].to_f / mc[:frac_d]
        end
        scaled_font = ObjC.retain(create_nsfont(@font_size * effective_scale, family: mc[:family]))
        # Capture the regular line height *before* possibly swapping
        # in the bold variant so we can re-align the bold baseline
        # below — bold fonts often report a larger
        # defaultLineHeightForFont and otherwise sit visually lower
        # than adjacent non-bold OSC 66 cells (same fix the cell-loop
        # path does via y_offset_for_font for same-family bold).
        regular_scaled_lh = ObjC::MSG_RET_D.call(scaled_font, ObjC.sel('defaultLineHeightForFont'))
        if cell.bold
          regular = scaled_font
          scaled_font = ObjC.retain(create_bold_nsfont(regular))
          ObjC.release(regular)
        end

        draw_attrs = {
          ObjC::NSFontAttributeName => scaled_font,
          ObjC::NSForegroundColorAttributeName => fg_color,
        }
        if cell.underline
          draw_attrs[ObjC::NSUnderlineStyleAttributeName] = ObjC.nsnumber_int(1)
        end
        if cell.strikethrough
          draw_attrs[ObjC::NSStrikethroughStyleAttributeName] = ObjC.nsnumber_int(1)
        end
        ns_attrs = ObjC.nsdict(draw_attrs)
        ns_char = cached_nsstring(cell.char)

        text_w = ObjC::MSG_RET_D_1.call(ns_char, ObjC.sel('sizeWithAttributes:'), ns_attrs)

        draw_x = case mc[:halign]
                  when 1 then x + block_w - text_w
                  when 2 then x + (block_w - text_w) / 2.0
                  else x
                  end

        scaled_ascender = ObjC::MSG_RET_D.call(scaled_font, ObjC.sel('ascender'))
        scaled_descender = ObjC::MSG_RET_D.call(scaled_font, ObjC.sel('descender'))
        scaled_leading = ObjC::MSG_RET_D.call(scaled_font, ObjC.sel('leading'))
        text_h = scaled_ascender - scaled_descender + scaled_leading

        draw_y = case mc[:valign]
                  when 1 then y + block_h - text_h
                  when 2 then y + (block_h - text_h) / 2.0
                  else y
                  end

        # Baseline compensation: same-family bold variants
        # report a larger defaultLineHeightForFont; shifting
        # by LH-delta puts the bold baseline back on the same
        # row as the regular run beside it. (OSC 66 doesn't
        # mix unrelated families in a single run, so the
        # ascender-delta fork the cell-loop path needs doesn't
        # apply here.)
        drawn_lh = ObjC::MSG_RET_D.call(scaled_font, ObjC.sel('defaultLineHeightForFont'))
        draw_y += (regular_scaled_lh - drawn_lh)

        if mc[:flip_h] || mc[:flip_v]
          # Mirror the glyph(s) around the multicell block's
          # center. Negative-scale the CTM along the requested
          # axis and translate twice so the flip pivots on the
          # block midpoint rather than the origin — keeps the
          # glyph(s) inside the reserved cell rect.
          ns_ctx = ObjC::MSG_PTR.call(ObjC.cls('NSGraphicsContext'), ObjC.sel('currentContext'))
          cg_ctx = ObjC::MSG_PTR.call(ns_ctx, ObjC.sel('CGContext'))
          cx = x + block_w / 2.0
          cy = y + block_h / 2.0
          sx = mc[:flip_h] ? -1.0 : 1.0
          sy = mc[:flip_v] ? -1.0 : 1.0
          ObjC::CGContextSaveGState.call(cg_ctx)
          ObjC::CGContextTranslateCTM.call(cg_ctx, cx, cy)
          ObjC::CGContextScaleCTM.call(cg_ctx, sx, sy)
          ObjC::CGContextTranslateCTM.call(cg_ctx, -cx, -cy)
          ObjC::MSG_VOID_PT_1.call(ns_char, ObjC.sel('drawAtPoint:withAttributes:'), draw_x, draw_y, ns_attrs)
          ObjC::CGContextRestoreGState.call(cg_ctx)
        else
          ObjC::MSG_VOID_PT_1.call(ns_char, ObjC.sel('drawAtPoint:withAttributes:'), draw_x, draw_y, ns_attrs)
        end
        ObjC.release(scaled_font)
      else
        x = px + c * @cell_width
        cell_w = cell.width == 2 ? @cell_width * 2 : @cell_width

        if is_current_match
          ObjC::MSG_VOID.call(@search_current_color, ObjC.sel('setFill'))
          snap_fill.call(x, y, cell_w, @cell_height)
        elsif is_match
          ObjC::MSG_VOID.call(@search_match_color, ObjC.sel('setFill'))
          snap_fill.call(x, y, cell_w, @cell_height)
        elsif selected
          ObjC::MSG_VOID.call(@selection_color, ObjC.sel('setFill'))
          snap_fill.call(x, y, cell_w, @cell_height)
        elsif has_bg
          ObjC::MSG_VOID.call(bg_color, ObjC.sel('setFill'))
          snap_fill.call(x, y, cell_w, @cell_height)
        end

        if cell.char == " " && !has_bg && !selected && !is_match
          flush_run.call
          next
        end

        base_font = cell.bold ? @bold_font : font_for_char(cell.char)
        if cell.italic
          base_font = create_italic_nsfont(base_font)
        end
        if cell.concealed || (cell.blink && !@cursor_blink_on)
          fg_color = bg_color
        elsif cell.faint
          fg_color = make_color_with_alpha(fg_color, 0.5)
        end

        sig = [base_font.to_i, fg_color.to_i, cell.underline, cell.strikethrough]
        if run_sig != sig
          flush_run.call
          run_sig     = sig
          run_start_c = c
          run_font    = base_font
          attrs = {
            ObjC::NSFontAttributeName            => base_font,
            ObjC::NSForegroundColorAttributeName => fg_color,
            # Ligature value `2` requests all discretionary
            # ligatures (`=>`, `!=`, `<=`, `>=`, etc.) on
            # fonts like Fira Code that ship them; default
            # `0` only does fi/fl-style essential ones.
            ObjC::NSLigatureAttributeName        => ObjC.nsnumber_int(2),
          }
          attrs[ObjC::NSUnderlineStyleAttributeName]     = ObjC.nsnumber_int(1) if cell.underline
          attrs[ObjC::NSStrikethroughStyleAttributeName] = ObjC.nsnumber_int(1) if cell.strikethrough
          run_attrs = ObjC.nsdict(attrs)
        end
        run_chars << cell.char
      end
    end
    flush_run.call
  end

  # Re-blit kitty graphics placements ON TOP of the rendered
  # cells. Anchors are stored as logical cell coords on the
  # Screen; we convert to pixels here using current cell
  # metrics so font-size and pane-resize changes pick up the
  # right pixel position automatically — placements need no
  # bookkeeping when @cell_width / @cell_height shift.
  screen.placements.each do |pl|
    blit_kitty_placement(pl, px, py, pane_rows)
  end

  # Draw cursor or copy mode cursor
  if copy_mode&.active
    # Copy mode cursor (inverse block)
    cm_row = copy_mode.cursor_row
    if cm_row >= 0 && cm_row < pane_rows
      cx = px + copy_mode.cursor_col * @cell_width
      cy = py + cm_row * @cell_height
      ObjC::MSG_VOID.call(@copy_mode_cursor_color, ObjC.sel('setFill'))
      ObjC::NSRectFill.call(cx, cy, @cell_width, @cell_height)
    end
  elsif pane.scroll_offset == 0 && screen.cursor.visible
    style = screen.cursor_style
    blink = style.odd? || style == 0
    cx = px + screen.cursor.col * @cell_width
    cy = py + screen.cursor.row * @cell_height

    if @window_focused
      # Active window: filled cursor (blinking if requested)
      if !blink || (is_active ? @cursor_blink_on : true)
        cursor_color = is_active ? make_color(*@active_profile.cursor_color) : make_color(0.5, 0.5, 0.5, 0.3)
        ObjC::MSG_VOID.call(cursor_color, ObjC.sel('setFill'))
        case style
        when 3, 4 # underline
          ObjC::NSRectFill.call(cx, cy + @cell_height - 2.0, @cell_width, 2.0)
        when 5, 6 # bar
          ObjC::NSRectFill.call(cx, cy, 2.0, @cell_height)
        else # block (0, 1, 2)
          ObjC::NSRectFill.call(cx, cy, @cell_width, @cell_height)
          # Draw character under cursor with inverted colors
          if screen.cursor.row < pane_rows && screen.cursor.col < pane_cols
            cell = screen.grid[screen.cursor.row][screen.cursor.col]
            if cell.char != ' '
              inv_fg = @default_bg
              cursor_font = cell.bold ? @bold_font : font_for_char(cell.char)
              ns_attrs = ObjC.nsdict({
                ObjC::NSFontAttributeName => cursor_font,
                ObjC::NSForegroundColorAttributeName => inv_fg,
              })
              ns_char = cached_nsstring(cell.char)
              dy = cy + y_offset_for_font(cursor_font)
              ObjC::MSG_VOID_PT_1.call(ns_char, ObjC.sel('drawAtPoint:withAttributes:'), cx, dy, ns_attrs)
            end
          end
        end
      end
    else
      # Inactive window: hollow square outline (no blinking)
      ObjC::MSG_VOID.call(make_color(*@active_profile.cursor_color), ObjC.sel('setFill'))
      ObjC::NSRectFill.call(cx, cy, @cell_width, 1.0)                       # top
      ObjC::NSRectFill.call(cx, cy + @cell_height - 1.0, @cell_width, 1.0)  # bottom
      ObjC::NSRectFill.call(cx, cy, 1.0, @cell_height)                      # left
      ObjC::NSRectFill.call(cx + @cell_width - 1.0, cy, 1.0, @cell_height)  # right
    end
  end

  # Draw marked text (IME composition) at cursor position (active pane only)
  if is_active && @marked_text && pane.scroll_offset == 0
    mx = px + screen.cursor.col * @cell_width
    my = py + screen.cursor.row * @cell_height
    marked_width = @marked_text.each_char.sum { |c| c.ord > 0x7F ? @cell_width * 2 : @cell_width }

    ime_bg = make_color(0.2, 0.2, 0.35)
    ObjC::MSG_VOID.call(ime_bg, ObjC.sel('setFill'))
    ObjC::NSRectFill.call(mx, my, marked_width, @cell_height)

    ns_str = ObjC.nsstring(@marked_text)
    ns_attrs = ObjC.nsdict({
      ObjC::NSFontAttributeName => @font,
      ObjC::NSForegroundColorAttributeName => make_color(1.0, 1.0, 1.0),
      ObjC::NSUnderlineStyleAttributeName => ObjC.nsnumber_int(1),
    })
    ObjC::MSG_VOID_PT_1.call(ns_str, ObjC.sel('drawAtPoint:withAttributes:'), mx, my, ns_attrs)
  end
end

#draw_pane_dividers(pane_rects, gy_off) ⇒ Object



1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
# File 'lib/echoes/gui.rb', line 1396

def draw_pane_dividers(pane_rects, gy_off)
  return if pane_rects.size <= 1

  ObjC::MSG_VOID.call(@pane_divider_color, ObjC.sel('setFill'))

  pane_rects.each do |rect|
    px = rect[:x] * @cell_width
    py = gy_off + rect[:y] * @cell_height
    pw = rect[:w] * @cell_width
    ph = rect[:h] * @cell_height

    # Draw right edge divider (if not at the far right)
    if rect[:x] + rect[:w] < @cols
      ObjC::NSRectFill.call(px + pw - 0.5, py, 1.0, ph)
    end

    # Draw bottom edge divider (if not at the very bottom)
    if rect[:y] + rect[:h] < @rows
      ObjC::NSRectFill.call(px, py + ph - 0.5, pw, 1.0)
    end
  end
end

#draw_rect(dirty_min_y = 0.0, dirty_max_y = Float::INFINITY) ⇒ Object

— Callbacks —



954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
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
# File 'lib/echoes/gui.rb', line 954

def draw_rect(dirty_min_y = 0.0, dirty_max_y = Float::INFINITY)
  # Autorelease pool to prevent temporary object accumulation
  pool = ObjC::MSG_PTR.call(ObjC.cls('NSAutoreleasePool'), ObjC.sel('alloc'))
  pool = ObjC::MSG_PTR.call(pool, ObjC.sel('init'))

  tab = current_tab
  unless tab
    ObjC::MSG_VOID.call(pool, ObjC.sel('drain'))
    return
  end
  tbh = tab_bar_height
  gy_off = grid_y_offset

  # Fill dirty region background
  ObjC::MSG_VOID.call(@default_bg, ObjC.sel('setFill'))
  ObjC::NSRectFill.call(0.0, dirty_min_y, @cell_width * (@cols + 1), dirty_max_y - dirty_min_y)

  # Draw tab bar if it intersects the dirty region
  if tbh > 0
    tby = tab_bar_y
    if dirty_min_y < tby + tbh && dirty_max_y > tby
      draw_tab_bar(tbh, tby)
    end
  end

  # Draw all panes
  pane_rects = tab.pane_tree.layout(0, 0, @cols, @rows)
  pane_rects.each do |rect|
    pane = rect[:pane]
    px = rect[:x] * @cell_width
    py = gy_off + rect[:y] * @cell_height
    is_active = (pane == tab.active_pane)

    draw_pane_content(pane, px, py, dirty_min_y, dirty_max_y, is_active)
  end

  # Draw pane dividers and active pane border
  if !tab.pane_tree.single_pane?
    draw_pane_dividers(pane_rects, gy_off)
    draw_active_pane_border(tab, pane_rects, gy_off)
  end

  # Visual bell flash
  if @bell_flash > 0
    flash_color = make_color_with_alpha(make_color(1.0, 1.0, 1.0), 0.15)
    ObjC::MSG_VOID.call(flash_color, ObjC.sel('setFill'))
    ObjC::NSRectFill.call(0.0, gy_off, @cols * @cell_width, @rows * @cell_height)
  end


  # Draw search bar
  if @search_mode
    bar_h = @cell_height + 4.0
    bar_y = gy_off + @rows * @cell_height
    bar_bg = make_color(0.2, 0.2, 0.2)
    ObjC::MSG_VOID.call(bar_bg, ObjC.sel('setFill'))
    ObjC::NSRectFill.call(0.0, bar_y, @cols * @cell_width, bar_h)

    match_info = @search_matches.empty? ? "" : " [#{@search_index + 1}/#{@search_matches.size}]"
    mode_flags = []
    mode_flags << 'regex' if @search_regex_mode
    mode_flags << 'i'     if @search_case_insensitive
    mode_tag = mode_flags.empty? ? '' : " (#{mode_flags.join(', ')})"
    label = "Find#{mode_tag}: #{@search_query}_#{match_info}"
    ns_str = ObjC.nsstring(label)
    ns_attrs = ObjC.nsdict({
      ObjC::NSFontAttributeName => @font,
      ObjC::NSForegroundColorAttributeName => make_color(1.0, 1.0, 1.0),
    })
    ObjC::MSG_VOID_PT_1.call(ns_str, ObjC.sel('drawAtPoint:withAttributes:'), 4.0, bar_y + 2.0, ns_attrs)
  end

  ObjC::MSG_VOID.call(pool, ObjC.sel('drain'))
end

#embedded_mode?Boolean

Phase 1 launch flag for the in-process Rubish embedding. Setting ECHOES_EMBED=1 in the environment routes new Tab/Pane creation through Echoes::EmbeddedShell instead of PTY.spawn.

Returns:

  • (Boolean)


149
150
151
# File 'lib/echoes/gui.rb', line 149

def embedded_mode?
  ENV['ECHOES_EMBED'] == '1'
end

#extend_word_drag_selection(tab, pointer_pos) ⇒ Object

When dragging after a double-click, snap each end of the selection to whole-word boundaries — and never let it shrink below the originally double-clicked word. Selection start is min((anchor_word_start), (pointer’s word_start)); end is max((anchor_word_end), (pointer’s word_end)). If the pointer is sitting on whitespace the “word” at the pointer is just that single cell, so the leading edge extends one char at a time across gaps.



1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
# File 'lib/echoes/gui.rb', line 1867

def extend_word_drag_selection(tab, pointer_pos)
  a_row, a_start, a_end = @selection_word_anchor
  p_row, p_col = pointer_pos
  p_row_data = row_at(tab, p_row)
  p_bounds = p_row_data && word_boundaries_in_row(p_row_data, p_col)
  p_start = p_bounds ? p_bounds[0] : p_col
  p_end   = p_bounds ? p_bounds[1] : p_col

  sel_start =
    if p_row < a_row || (p_row == a_row && p_start < a_start)
      [p_row, p_start]
    else
      [a_row, a_start]
    end
  sel_end =
    if p_row > a_row || (p_row == a_row && p_end > a_end)
      [p_row, p_end]
    else
      [a_row, a_end]
    end
  @selection_anchor = sel_start
  @selection_end    = sel_end
end

#grid_y_offsetObject



232
233
234
# File 'lib/echoes/gui.rb', line 232

def grid_y_offset
  Echoes.config.tab_position == :bottom ? 0.0 : tab_bar_height
end

#handle_resize(w, h) ⇒ Object



1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
# File 'lib/echoes/gui.rb', line 1999

def handle_resize(w, h)
  tbh = tab_bar_height
  grid_height = h - tbh

  new_cols = (w / @cell_width).to_i
  new_rows = (grid_height / @cell_height).to_i
  new_cols = 1 if new_cols < 1
  new_rows = 1 if new_rows < 1

  return if new_rows == @rows && new_cols == @cols

  @rows = new_rows
  @cols = new_cols
  @tabs.each { |tab| tab.resize(@rows, @cols) }
end

#ime_do_commandObject



1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
# File 'lib/echoes/gui.rb', line 1576

def ime_do_command
  return unless @current_event

  tab = current_tab
  return unless tab
  pane = tab.active_pane
  return unless pane
  event_ptr = @current_event
  flags = ObjC::MSG_RET_L.call(event_ptr, ObjC.sel('modifierFlags'))
  chars_ns = ObjC::MSG_PTR.call(event_ptr, ObjC.sel('characters'))
  chars = ObjC.to_ruby_string(chars_ns)
  chars_ns2 = ObjC::MSG_PTR.call(event_ptr, ObjC.sel('charactersIgnoringModifiers'))
  chars2 = ObjC.to_ruby_string(chars_ns2)

  numpad = (flags & ObjC::NSEventModifierFlagNumericPad) != 0
  actual = chars.empty? ? chars2 : chars
  pane.write_input(map_special_keys(actual, pane.screen.application_cursor_keys?, app_keypad: numpad && pane.screen.application_keypad))
rescue Errno::EIO, IOError
  close_tab(@active_tab)
end

#ime_has_marked_textObject



1614
1615
1616
# File 'lib/echoes/gui.rb', line 1614

def ime_has_marked_text
  @marked_text ? 1 : 0
end

#ime_insert_text(text_ptr) ⇒ Object

— IME (Input Method Editor) callbacks —



1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
# File 'lib/echoes/gui.rb', line 1562

def ime_insert_text(text_ptr)
  text = nsstring_from_input(text_ptr)
  @marked_text = nil
  return if text.empty?

  tab = current_tab
  return unless tab
  pane = tab.active_pane
  return unless pane
  pane.write_input(text)
rescue Errno::EIO, IOError
  close_tab(@active_tab)
end

#ime_marked_range_locationObject



1618
1619
1620
# File 'lib/echoes/gui.rb', line 1618

def ime_marked_range_location
  @marked_text ? 0 : 0x7FFFFFFFFFFFFFFF # NSNotFound
end

#ime_set_marked_text(text_ptr, _sel_loc, _sel_len) ⇒ Object



1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
# File 'lib/echoes/gui.rb', line 1597

def ime_set_marked_text(text_ptr, _sel_loc, _sel_len)
  text = nsstring_from_input(text_ptr)

  if text.empty?
    @marked_text = nil
  else
    @marked_text = text
  end

  ObjC::MSG_VOID_I.call(@view, ObjC.sel('setNeedsDisplay:'), 1)
end

#ime_unmark_textObject



1609
1610
1611
1612
# File 'lib/echoes/gui.rb', line 1609

def ime_unmark_text
  @marked_text = nil
  ObjC::MSG_VOID_I.call(@view, ObjC.sel('setNeedsDisplay:'), 1)
end

#invalidate_dirty_rows(dirty_rows) ⇒ Object



1731
1732
1733
1734
1735
1736
1737
1738
1739
# File 'lib/echoes/gui.rb', line 1731

def invalidate_dirty_rows(dirty_rows)
  gy_off = grid_y_offset
  width = @cell_width * @cols
  dirty_rows.each do |r|
    next if r < 0 || r >= @rows
    y = gy_off + r * @cell_height
    ObjC::MSG_VOID_RECT.call(@view, ObjC.sel('setNeedsDisplayInRect:'), 0.0, y, width, @cell_height)
  end
end

#key_down(event_ptr) ⇒ Object



1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
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
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
# File 'lib/echoes/gui.rb', line 1444

def key_down(event_ptr)
  if @search_mode
    search_key_down(event_ptr)
    return
  end

  tab = current_tab
  return unless tab
  pane = tab.active_pane
  return unless pane

  # Copy mode intercepts all keys
  if pane.copy_mode&.active
    copy_mode_key_down(event_ptr, pane)
    return
  end

  @selection_anchor = nil
  @selection_end = nil
  @selection_word_anchor = nil

  flags = ObjC::MSG_RET_L.call(event_ptr, ObjC.sel('modifierFlags'))
  chars_ns = ObjC::MSG_PTR.call(event_ptr, ObjC.sel('charactersIgnoringModifiers'))
  chars = ObjC.to_ruby_string(chars_ns)
  return if chars.empty?

  # Snap-to-bottom on most key events. Exception: Cmd+Shift+Up/Down
  # is the OSC 133 jump-to-prompt nav, which sets @scroll_offset
  # itself — clobbering it here would defeat repeated presses.
  is_prompt_nav = (flags & (ObjC::NSEventModifierFlagCommand | ObjC::NSEventModifierFlagShift)) ==
                  (ObjC::NSEventModifierFlagCommand | ObjC::NSEventModifierFlagShift) &&
                  (chars == "\u{F700}" || chars == "\u{F701}")
  unless is_prompt_nav
    pane.scroll_offset = 0
    pane.scroll_accum = 0.0
  end

  # Viewer panes (rvim-backed) consume keys directly via
  # `pane.handle_key`, not via a pty. Without this branch the
  # legacy PTY path below tries to write keystrokes to a
  # non-existent pty fd, so vim never sees the input.
  if pane.editor?
    pane.handle_key(chars: chars, flags: flags)
    ObjC::MSG_VOID_I.call(@view, ObjC.sel('setNeedsDisplay:'), 1)
    return
  end

  # Embedded-shell panes don't speak the byte-stream / escape-code
  # protocol; they have an in-Echoes line editor that submits
  # finished lines to a Rubish::REPL via direct method calls.
  if pane.embedded?
    # Tab with multiple completion candidates: show a native NSMenu
    # popup at the cursor cell instead of letting Pane print the
    # candidates inline. Single-candidate completion stays inline.
    if chars == "\t" && !pane.embedded_shell.running?
      req = pane.completion_request
      if req && req[:candidates].size > 1
        show_completion_popup(pane, req)
        ObjC::MSG_VOID_I.call(@view, ObjC.sel('setNeedsDisplay:'), 1)
        return
      end
    end
    pane.handle_key(chars: chars, flags: flags)
    ObjC::MSG_VOID_I.call(@view, ObjC.sel('setNeedsDisplay:'), 1)
    return
  end

  mod = modifier_param(flags)

  if chars == "\u{19}"  # NSBackTabCharacter (Shift+Tab on macOS)
    pane.write_input("\e[Z")
  elsif mod > 1 && (seq = map_modified_key(chars, mod))
    pane.write_input(seq)
  elsif (flags & ObjC::NSEventModifierFlagControl) != 0
    ctrl_char = (chars[0].ord & 0x1F).chr
    pane.write_input(ctrl_char)
  elsif (flags & ObjC::NSEventModifierFlagOption) != 0
    pane.write_input("\e#{chars}")
  else
    # Route through input method for IME support
    @current_event = event_ptr
    arr = ObjC::MSG_PTR_1.call(ObjC.cls('NSArray'), ObjC.sel('arrayWithObject:'), event_ptr)
    ObjC::MSG_VOID_1.call(@view, ObjC.sel('interpretKeyEvents:'), arr)
  end
rescue Errno::EIO, IOError
  close_tab(@active_tab)
end

#log_crash(exception, context: nil) ⇒ Object



13
14
15
16
17
18
19
20
21
22
23
24
25
# File 'lib/echoes/gui.rb', line 13

def log_crash(exception, context: nil)
  dir = File.dirname(CRASH_LOG)
  Dir.mkdir(dir) unless Dir.exist?(dir)
  File.open(CRASH_LOG, 'a') do |f|
    f.puts "--- #{Time.now} ---"
    f.puts "Context: #{context}" if context
    f.puts "#{exception.class}: #{exception.message}"
    exception.backtrace&.each { |line| f.puts "  #{line}" }
    f.puts
  end
  STDERR.puts "echoes: #{exception.class}: #{exception.message} (logged to #{CRASH_LOG})"
rescue # log_crash itself must never raise
end

#mouse_down(event_ptr) ⇒ Object



1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
# File 'lib/echoes/gui.rb', line 1768

def mouse_down(event_ptr)
  tab = current_tab
  return unless tab
  pos = grid_position(event_ptr)
  click_count = ObjC::MSG_RET_L.call(event_ptr, ObjC.sel('clickCount'))

  flags = ObjC::MSG_RET_L.call(event_ptr, ObjC.sel('modifierFlags'))

  if pos.nil?
    # Click in tab bar
    click_x, = event_location(event_ptr)
    tab_w = (@cell_width * @cols) / @tabs.size
    clicked_tab = (click_x / tab_w).to_i.clamp(0, @tabs.size - 1)
    @active_tab = clicked_tab
  elsif (flags & ObjC::NSEventModifierFlagCommand) != 0 && pos
    # Cmd+click: open hyperlink/URL if the cell has one; otherwise
    # in an embedded pane, recall the command at this prompt row
    # into the input buffer (using OSC 133 marks as the index).
    abs_row, col = pos
    url = hyperlink_at(tab, abs_row, col)
    if url
      open_url(url)
    else
      pane = tab.active_pane
      if pane.embedded?
        mark = pane.screen.find_command_mark_at_row(abs_row)
        if mark && mark[:command_text] && !pane.embedded_shell.running?
          pane.recall_command(mark[:command_text])
        end
      end
    end
  elsif tab.screen.mouse_tracking != :off
    row, col = pos
    send_mouse_event(tab, 0, col, row)  # button 0 = left press
  elsif click_count >= 3
    # Triple-click: if the clicked row falls inside a command's
    # OSC 133 output region, select the whole region (semantic
    # copy). Otherwise fall back to selecting just this one line.
    abs_row, = pos
    region = tab.active_pane&.screen&.output_region_for_row(abs_row)
    if region
      start_row, end_row = region
      @selection_anchor = [start_row, 0]
      @selection_end    = [end_row, @cols - 1]
    else
      @selection_anchor = [abs_row, 0]
      @selection_end    = [abs_row, @cols - 1]
    end
    @selection_word_anchor = nil
  elsif click_count == 2
    # Double-click: select word, and remember the word's bounds so
    # a subsequent drag extends from those bounds (keeping the
    # double-clicked word fully selected) instead of collapsing
    # to character-level from the click point.
    abs_row, col = pos
    row_data = row_at(tab, abs_row)
    if row_data
      bounds = word_boundaries_in_row(row_data, col)
      if bounds
        @selection_anchor = [abs_row, bounds[0]]
        @selection_end = [abs_row, bounds[1]]
        @selection_word_anchor = [abs_row, bounds[0], bounds[1]]
      end
    end
  else
    # Single click: start drag selection
    @selection_anchor = pos
    @selection_end = nil
    @selection_word_anchor = nil
  end

  ObjC::MSG_VOID_I.call(@view, ObjC.sel('setNeedsDisplay:'), 1)
end

#mouse_dragged(event_ptr) ⇒ Object



1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
# File 'lib/echoes/gui.rb', line 1842

def mouse_dragged(event_ptr)
  tab = current_tab
  return unless tab
  pos = grid_position(event_ptr)
  return unless pos

  if tab.screen.mouse_tracking == :button_event || tab.screen.mouse_tracking == :any_event
    row, col = pos
    send_mouse_event(tab, 32, col, row)  # 32 = left drag (button 0 + 32)
  elsif @selection_word_anchor
    extend_word_drag_selection(tab, pos)
  else
    @selection_end = pos
  end
  ObjC::MSG_VOID_I.call(@view, ObjC.sel('setNeedsDisplay:'), 1)
end

#mouse_moved(event_ptr) ⇒ Object

Pointer-was-hidden + user-shakes-the-mouse path: when the user has hidden the cursor (Cmd+Shift+P) and then can’t find it, the OS’s own “shake to locate” feature briefly enlarges the system cursor — but ours is hidden, so there’s nothing to enlarge. We detect the shake ourselves and unhide so the user gets a cursor to look at. After this fires, @pointer_hidden is reset so re-hiding requires another deliberate Cmd+Shift+P.



1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
# File 'lib/echoes/gui.rb', line 1909

def mouse_moved(event_ptr)
  return unless @pointer_hidden
  @shake_detector ||= ShakeDetector.new
  x, y = event_location(event_ptr)
  t = Process.clock_gettime(Process::CLOCK_MONOTONIC)
  if @shake_detector.observe(t, x, y)
    ObjC::MSG_VOID.call(ObjC.cls('NSCursor'), ObjC.sel('unhide'))
    @pointer_hidden = false
    @shake_detector.reset
  end
end

#mouse_up(event_ptr) ⇒ Object



1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
# File 'lib/echoes/gui.rb', line 1891

def mouse_up(event_ptr)
  tab = current_tab
  return unless tab
  return if tab.screen.mouse_tracking == :off || tab.screen.mouse_tracking == :x10

  pos = grid_position(event_ptr)
  return unless pos
  row, col = pos
  send_mouse_event(tab, 3, col, row, release: true)  # 3 = release
end

#other_mouse_down(event_ptr) ⇒ Object



1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
# File 'lib/echoes/gui.rb', line 1960

def other_mouse_down(event_ptr)
  tab = current_tab
  return unless tab
  return if tab.screen.mouse_tracking == :off

  pos = grid_position(event_ptr)
  return unless pos
  row, col = pos
  send_mouse_event(tab, 1, col, row)  # button 1 = middle press
rescue Errno::EIO, IOError
  close_tab(@active_tab)
end

#other_mouse_dragged(event_ptr) ⇒ Object



1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
# File 'lib/echoes/gui.rb', line 1973

def other_mouse_dragged(event_ptr)
  tab = current_tab
  return unless tab
  return unless tab.screen.mouse_tracking == :button_event || tab.screen.mouse_tracking == :any_event

  pos = grid_position(event_ptr)
  return unless pos
  row, col = pos
  send_mouse_event(tab, 33, col, row)  # 33 = middle drag (button 1 + 32)
rescue Errno::EIO, IOError
  close_tab(@active_tab)
end

#other_mouse_up(event_ptr) ⇒ Object



1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
# File 'lib/echoes/gui.rb', line 1986

def other_mouse_up(event_ptr)
  tab = current_tab
  return unless tab
  return if tab.screen.mouse_tracking == :off || tab.screen.mouse_tracking == :x10

  pos = grid_position(event_ptr)
  return unless pos
  row, col = pos
  send_mouse_event(tab, 3, col, row, release: true)
rescue Errno::EIO, IOError
  close_tab(@active_tab)
end

#perform_drag_operation(sender) ⇒ Object



2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
# File 'lib/echoes/gui.rb', line 2093

def perform_drag_operation(sender)
  pb = ObjC::MSG_PTR.call(sender, ObjC.sel('draggingPasteboard'))
  str = self.class.file_paths_from_pasteboard(pb)
  return false if str.nil?

  pane = current_tab.active_pane
  if pane.screen.bracketed_paste_mode?
    pane.write_input("\e[200~")
    pane.write_input(str)
    pane.write_input("\e[201~")
  else
    pane.write_input(str)
  end
  true
rescue Errno::EIO, IOError
  false
end

#perform_key_equivalent(event_ptr) ⇒ Object



1440
1441
1442
# File 'lib/echoes/gui.rb', line 1440

def perform_key_equivalent(event_ptr)
  0
end

#reflow_to_current_view_sizeObject

Re-run handle_resize against the current view frame. Toggling tab_bar_height (when @tabs.size crosses 1↔2) changes the grid area inside an unchanged window, but AppKit’s setFrameSize: hook only fires on real frame changes — so call it ourselves so @rows reflows to the new available height.



2020
2021
2022
2023
2024
# File 'lib/echoes/gui.rb', line 2020

def reflow_to_current_view_size
  return unless @view && @cell_width && @cell_height
  _, _, w, h = nsrect_via_invocation(@view, 'frame')
  handle_resize(w, h)
end

#right_mouse_down(event_ptr) ⇒ Object



1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
# File 'lib/echoes/gui.rb', line 1921

def right_mouse_down(event_ptr)
  tab = current_tab
  return unless tab
  return if tab.screen.mouse_tracking == :off

  pos = grid_position(event_ptr)
  return unless pos
  row, col = pos
  send_mouse_event(tab, 2, col, row)  # button 2 = right press
rescue Errno::EIO, IOError
  close_tab(@active_tab)
end

#right_mouse_dragged(event_ptr) ⇒ Object



1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
# File 'lib/echoes/gui.rb', line 1934

def right_mouse_dragged(event_ptr)
  tab = current_tab
  return unless tab
  return unless tab.screen.mouse_tracking == :button_event || tab.screen.mouse_tracking == :any_event

  pos = grid_position(event_ptr)
  return unless pos
  row, col = pos
  send_mouse_event(tab, 34, col, row)  # 34 = right drag (button 2 + 32)
rescue Errno::EIO, IOError
  close_tab(@active_tab)
end

#right_mouse_up(event_ptr) ⇒ Object



1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
# File 'lib/echoes/gui.rb', line 1947

def right_mouse_up(event_ptr)
  tab = current_tab
  return unless tab
  return if tab.screen.mouse_tracking == :off || tab.screen.mouse_tracking == :x10

  pos = grid_position(event_ptr)
  return unless pos
  row, col = pos
  send_mouse_event(tab, 3, col, row, release: true)
rescue Errno::EIO, IOError
  close_tab(@active_tab)
end

#runObject



75
76
77
78
79
80
81
82
# File 'lib/echoes/gui.rb', line 75

def run
  setup_app
  create_fonts
  create_view_class
  open_new_window
  setup_timer
  start_app
end

#scroll_wheel(event_ptr) ⇒ Object



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
# File 'lib/echoes/gui.rb', line 1741

def scroll_wheel(event_ptr)
  tab = current_tab
  return unless tab
  screen = tab.screen

  if screen.mouse_tracking != :off
    delta = ObjC::MSG_RET_D.call(event_ptr, ObjC.sel('deltaY'))
    pos = grid_position(event_ptr)
    return unless pos
    row, col = pos
    button = delta > 0 ? 64 : 65  # 64=scroll up, 65=scroll down
    send_mouse_event(tab, button, col, row)
    return
  end

  delta = ObjC::MSG_RET_D.call(event_ptr, ObjC.sel('deltaY'))
  tab.scroll_accum += delta

  if tab.scroll_accum.abs >= 1.0
    lines = tab.scroll_accum.to_i
    tab.scroll_offset += lines
    tab.scroll_offset = tab.scroll_offset.clamp(0, tab.screen.scrollback.size)
    tab.scroll_accum -= lines
    ObjC::MSG_VOID_I.call(@view, ObjC.sel('setNeedsDisplay:'), 1)
  end
end

#setup_appObject



240
241
242
243
244
245
246
247
248
249
250
251
252
253
# File 'lib/echoes/gui.rb', line 240

def setup_app
  @app = ObjC::MSG_PTR.call(ObjC.cls('NSApplication'), ObjC.sel('sharedApplication'))
  ObjC::MSG_VOID_I.call(@app, ObjC.sel('setActivationPolicy:'), 0)
  disable_press_and_hold
  # Disable native NSWindow tabbing so Cmd+N always spawns a real
  # new window. Default macOS behavior in fullscreen is to fold
  # additional NSWindows into the same OS-level tabbed window —
  # but Echoes already has its own tab abstraction (with its own
  # tab bar and @tabs array per window), so that promotion creates
  # a phantom OS tab the Echoes side has no record of, leaving a
  # second clickable tab that switches to nothing.
  ObjC::MSG_VOID_I.call(ObjC.cls('NSWindow'), ObjC.sel('setAllowsAutomaticWindowTabbing:'), 0)
  setup_menu_bar
end

#setup_menu_barObject



273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
# File 'lib/echoes/gui.rb', line 273

def setup_menu_bar
  main_menu = create_menu('')

  # Application menu
  app_menu = create_menu('Echoes')
  add_menu_item(app_menu, "About Echoes", 'showAbout:', '')
  add_separator(app_menu)
  add_menu_item(app_menu, "Hide Echoes", 'hide:', 'h')
  add_menu_item(app_menu, "Hide Others", 'hideOtherApplications:', '')
  add_menu_item(app_menu, "Show All", 'unhideAllApplications:', '')
  add_separator(app_menu)
  add_menu_item(app_menu, "Quit Echoes", 'terminate:', 'q')
  add_submenu(main_menu, app_menu, 'Echoes')

  # Edit menu
  edit_menu = create_menu('Edit')
  add_menu_item(edit_menu, "Copy", 'copy:', 'c')
  add_menu_item(edit_menu, "Paste", 'paste:', 'v')
  add_menu_item(edit_menu, "Select All", 'selectAll:', 'a')
  add_submenu(main_menu, edit_menu, 'Edit')

  # View menu
  view_menu = create_menu('View')
  add_menu_item(view_menu, "Bigger", 'increaseFontSize:', '=', bind: :increase_font_size)
  add_menu_item(view_menu, "Bigger", 'increaseFontSize:', '+', bind: :increase_font_size_plus)
  add_menu_item(view_menu, "Smaller", 'decreaseFontSize:', '-', bind: :decrease_font_size)
  add_menu_item(view_menu, "Reset Font Size", 'resetFontSize:', '0', bind: :reset_font_size)
  add_separator(view_menu)
  add_menu_item(view_menu, "Find", 'toggleFind:', 'f', bind: :toggle_find)
  add_menu_item(view_menu, "Find Next", 'findNext:', 'g', bind: :find_next)
  add_menu_item(view_menu, "Find Previous", 'findPrevious:', 'g',
                modifiers: ObjC::NSEventModifierFlagCommand | ObjC::NSEventModifierFlagShift,
                bind: :find_previous)
  add_separator(view_menu)
  add_menu_item(view_menu, "Hide Mouse Pointer", 'togglePointer:', 'p',
                modifiers: ObjC::NSEventModifierFlagCommand | ObjC::NSEventModifierFlagShift,
                bind: :toggle_pointer)
  build_profiles_submenu(view_menu)
  add_submenu(main_menu, view_menu, 'View')

  # Window menu
  window_menu = create_menu('Window')
  add_menu_item(window_menu, "Minimize", 'miniaturize:', 'm')
  add_menu_item(window_menu, "Zoom", 'zoom:', '')
  add_menu_item(window_menu, "Enter Full Screen", 'toggleFullScreen:', 'f',
                modifiers: ObjC::NSEventModifierFlagCommand | ObjC::NSEventModifierFlagControl)
  add_separator(window_menu)
  add_menu_item(window_menu, "Show Previous Tab", 'showPreviousTab:', '{',
                modifiers: ObjC::NSEventModifierFlagCommand | ObjC::NSEventModifierFlagShift,
                bind: :show_previous_tab)
  add_menu_item(window_menu, "Show Next Tab", 'showNextTab:', '}',
                modifiers: ObjC::NSEventModifierFlagCommand | ObjC::NSEventModifierFlagShift,
                bind: :show_next_tab)
  add_separator(window_menu)
  add_menu_item(window_menu, "Select Next Pane", 'selectNextPane:', ']', bind: :select_next_pane)
  add_menu_item(window_menu, "Select Previous Pane", 'selectPreviousPane:', '[', bind: :select_previous_pane)
  add_separator(window_menu)
  add_menu_item(window_menu, "Toggle Copy Mode", 'toggleCopyMode:', 'c',
                modifiers: ObjC::NSEventModifierFlagCommand | ObjC::NSEventModifierFlagShift,
                bind: :toggle_copy_mode)
  add_separator(window_menu)
  # Register the menu as NSApplication's "windows menu"; AppKit
  # auto-populates it with one item per NSWindow (using the window's
  # title) and handles activation when an item is selected.
  ObjC::MSG_VOID_1.call(@app, ObjC.sel('setWindowsMenu:'), window_menu)
  add_submenu(main_menu, window_menu, 'Window')

  # Shell menu
  shell_menu = create_menu('Shell')
  add_menu_item(shell_menu, "New Window", 'newWindow:', 'n', bind: :new_window)
  add_menu_item(shell_menu, "New Tab", 'newTab:', 't', bind: :new_tab)
  add_menu_item(shell_menu, "Close Tab", 'closeTab:', 'w', bind: :close_tab)
  add_separator(shell_menu)
  add_menu_item(shell_menu, "Edit File…", 'editFile:', 'e',
                modifiers: ObjC::NSEventModifierFlagCommand | ObjC::NSEventModifierFlagShift,
                bind: :edit_file)
  add_separator(shell_menu)
  add_menu_item(shell_menu, "Split Right", 'splitRight:', 'd', bind: :split_right)
  add_menu_item(shell_menu, "Split Down", 'splitDown:', 'd',
                modifiers: ObjC::NSEventModifierFlagCommand | ObjC::NSEventModifierFlagShift,
                bind: :split_down)
  add_menu_item(shell_menu, "Close Pane", 'closePane:', 'w',
                modifiers: ObjC::NSEventModifierFlagCommand | ObjC::NSEventModifierFlagShift,
                bind: :close_pane)
  add_submenu(main_menu, shell_menu, 'Shell')

  ObjC::MSG_VOID_1.call(@app, ObjC.sel('setMainMenu:'), main_menu)
end

#setup_timerObject



935
936
937
938
939
940
941
942
943
944
945
946
# File 'lib/echoes/gui.rb', line 935

def setup_timer
  @timer_view_id = @view.to_i
  @timer = ObjC::MSG_PTR_D_P_P_P_I.call(
    ObjC.cls('NSTimer'),
    ObjC.sel('scheduledTimerWithTimeInterval:target:selector:userInfo:repeats:'),
    1.0 / 60.0,
    @view,
    ObjC.sel('timerFired:'),
    Fiddle::Pointer.new(0),
    1
  )
end

#start_appObject



948
949
950
# File 'lib/echoes/gui.rb', line 948

def start_app
  ObjC::MSG_VOID.call(@app, ObjC.sel('run'))
end

#tab_bar_heightObject



228
229
230
# File 'lib/echoes/gui.rb', line 228

def tab_bar_height
  @tabs.size > 1 ? @cell_height : 0.0
end

#tab_bar_yObject



236
237
238
# File 'lib/echoes/gui.rb', line 236

def tab_bar_y
  Echoes.config.tab_position == :bottom ? @cell_height * @rows : 0.0
end

#timer_firedObject



1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
# File 'lib/echoes/gui.rb', line 1622

def timer_fired
  save_window_state

  @cursor_blink_counter += 1
  blink_toggled = false
  if @cursor_blink_counter >= 30
    @cursor_blink_counter = 0
    @cursor_blink_on = !@cursor_blink_on
    blink_toggled = true
  end

  @window_states.each do |ws|
    load_window_state(ws)
    timer_fired_for_window(ws, blink_toggled)
  end
end

#update_font(new_size, persist: true) ⇒ Object



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
# File 'lib/echoes/gui.rb', line 2067

def update_font(new_size, persist: true)
  @font_size = new_size
  Preferences.set_double(:font_size, new_size) if persist
  old_font = @font
  old_bold = @bold_font
  @font = ObjC.retain(create_nsfont(@font_size))
  @bold_font = ObjC.retain(create_bold_nsfont(@font))
  ObjC.release(old_font) if old_font
  ObjC.release(old_bold) if old_bold
  @font_cache.each_value { |f| ObjC.release(f) unless f.to_i == old_font&.to_i }
  @font_cache = {}
  @font_y_offset_cache = {}
  @italic_font_cache&.each_value { |f| ObjC.release(f) }
  @italic_font_cache = {}
  update_cell_metrics

  @window_states.each do |ws|
    load_window_state(ws)
    win_width = @cell_width * @cols
    win_height = tab_bar_height + @cell_height * @rows
    ObjC::MSG_VOID_2D.call(@window, ObjC.sel('setContentSize:'), win_width, win_height)
    ObjC::MSG_VOID_I.call(@view, ObjC.sel('setNeedsDisplay:'), 1)
    save_window_state
  end
end

#window_focus_changed(focused) ⇒ Object



2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
# File 'lib/echoes/gui.rb', line 2026

def window_focus_changed(focused)
  @window_focused = focused
  save_window_state
  ObjC::MSG_VOID_I.call(@view, ObjC.sel('setNeedsDisplay:'), 1) if @view

  tab = current_tab
  pane = tab&.active_pane
  return unless pane&.screen&.focus_reporting?

  seq = focused ? "\e[I" : "\e[O"
  pane.write_input(seq)
end