Class: Echoes::GUI
- Inherits:
-
Object
- Object
- Echoes::GUI
- Defined in:
- lib/echoes/gui.rb
Constant Summary collapse
- CRASH_LOG =
File.join(Dir.home, '.local', 'share', 'echoes', 'crash.log')
- IME_FORWARDED_SELECTORS =
— IME candidate-window positioning via message forwarding —
firstRectForCharacterRange:actualRange: returns NSRect (4 doubles). Fiddle::Closure can’t model a struct return — only single-register scalar returns. Without a real implementation, AppKit reads the rect from v0..v3 with only v0 set to our scalar return value, so the IME sees a garbage rect and either positions the candidate window off-screen or suppresses it entirely.
The workaround: don’t implement the selector directly; let it fall through to forwardInvocation:. Inside forward_invocation we pack four doubles into an NSRect-sized buffer and hand it to NSInvocation.setReturnValue:, which handles the struct ABI for us correctly. methodSignatureForSelector: is the gateway that tells the runtime to use the forwarding path.
['firstRectForCharacterRange:actualRange:'].freeze
- FIRST_RECT_SIG =
'{CGRect={CGPoint=dd}{CGSize=dd}}@:{_NSRange=QQ}^{_NSRange=QQ}'.freeze
- DRAG_THRESHOLD_PX =
4
Class Method Summary collapse
-
.capture_format_for(path) ⇒ Object
Pick raster vs vector by file extension.
- .cwd_from_osc7_uri(uri_str) ⇒ Object
- .file_paths_from_pasteboard(pb) ⇒ Object
-
.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).
Instance Method Summary collapse
- #activate_for_view(view_ptr) ⇒ Object
-
#apply_profile(name) ⇒ Object
Switch the active profile (color theme) by name.
- #close_tab(index) ⇒ Object
-
#completion_picked(sender) ⇒ Object
Action callback for an NSMenuItem in the completion popup.
-
#compute_drop_index(x, tab_w, num_tabs) ⇒ Object
Insertion index 0..num_tabs for a cursor at view-x.
- #copy_mode_key_down(event_ptr, pane) ⇒ Object
- #create_fonts ⇒ Object
- #create_tab(editor_file: nil) ⇒ Object
- #create_view_class ⇒ Object
- #current_tab ⇒ Object
- #decode_tab_drag_token(str) ⇒ Object
-
#disable_press_and_hold ⇒ Object
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.
- #draw_active_pane_border(tab, pane_rects, gy_off) ⇒ Object
- #draw_pane_content(pane, px, py, dirty_min_y, dirty_max_y, is_active) ⇒ Object
- #draw_pane_dividers(pane_rects, gy_off) ⇒ Object
-
#draw_rect(dirty_min_y = 0.0, dirty_max_y = Float::INFINITY) ⇒ Object
— Callbacks —.
-
#embedded_mode? ⇒ Boolean
Phase 1 launch flag for the in-process Rubish embedding.
-
#encode_tab_drag_token(view_ptr, tab_index) ⇒ Object
Token format on the pasteboard for tab drag.
-
#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.
-
#first_rect_for_marked_text_screen_coords ⇒ Object
Compute the on-screen rect for the marked-text caret, used by the IME to anchor its candidate window.
- #forward_invocation(_self_ptr, inv) ⇒ Object
- #grid_y_offset ⇒ Object
- #handle_resize(w, h) ⇒ Object
-
#handle_tab_drop(sender, token) ⇒ Object
Resolve a tab-drag token, look up source & target window-states, splice via transfer_tab, and close the source window if its last tab moved away.
- #ime_do_command ⇒ Object
- #ime_has_marked_text ⇒ Object
-
#ime_insert_text(text_ptr) ⇒ Object
— IME (Input Method Editor) callbacks —.
- #ime_marked_range_location ⇒ Object
- #ime_set_marked_text(text_ptr, _sel_loc, _sel_len) ⇒ Object
- #ime_unmark_text ⇒ Object
-
#initialize(command: Echoes.config.shell, rows: Echoes.config.rows, cols: Echoes.config.cols, font_size: nil) ⇒ GUI
constructor
A new instance of GUI.
- #invalidate_dirty_rows(dirty_rows) ⇒ Object
- #key_down(event_ptr) ⇒ Object
- #log_crash(exception, context: nil) ⇒ Object
- #method_signature_for_selector(self_ptr, sel) ⇒ Object
- #mouse_down(event_ptr) ⇒ Object
- #mouse_dragged(event_ptr) ⇒ Object
-
#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.
- #mouse_up(event_ptr) ⇒ Object
- #other_mouse_down(event_ptr) ⇒ Object
- #other_mouse_dragged(event_ptr) ⇒ Object
- #other_mouse_up(event_ptr) ⇒ Object
- #perform_drag_operation(sender) ⇒ Object
- #perform_key_equivalent(event_ptr) ⇒ Object
-
#reflow_to_current_view_size ⇒ Object
Re-run handle_resize against the current view frame.
- #responds_to_selector?(self_ptr, sel) ⇒ Boolean
- #right_mouse_down(event_ptr) ⇒ Object
- #right_mouse_dragged(event_ptr) ⇒ Object
- #right_mouse_up(event_ptr) ⇒ Object
- #run ⇒ Object
- #scroll_wheel(event_ptr) ⇒ Object
- #sel_name_string(sel) ⇒ Object
-
#select_tab(n) ⇒ Object
Switch to a tab by 1-based slot number (Cmd+N shortcuts).
- #setup_app ⇒ Object
- #setup_menu_bar ⇒ Object
- #setup_timer ⇒ Object
- #start_app ⇒ Object
- #tab_bar_height ⇒ Object
- #tab_bar_y ⇒ Object
-
#tab_font_size ⇒ Object
Tab labels render in a smaller font than the cell grid so long titles read comfortably even when the bar’s split across many narrow tabs.
- #timer_fired ⇒ Object
-
#transfer_tab(src_ws, src_index, dst_ws, dst_index) ⇒ Object
Splice a tab between window-state hashes.
- #update_font(new_size, persist: true) ⇒ Object
- #window_focus_changed(focused) ⇒ Object
-
#window_to_screen_point(x, y) ⇒ Object
- NSWindow convertPointToScreen:
-
returns NSPoint (2 doubles).
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 74 75 76 |
# 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 @drag_start_tab_index = nil @drag_start_point = nil @drag_insertion_index = 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.
3741 3742 3743 |
# File 'lib/echoes/gui.rb', line 3741 def self.capture_format_for(path) File.extname(path).downcase == '.png' ? :png : :pdf end |
.cwd_from_osc7_uri(uri_str) ⇒ Object
116 117 118 119 120 121 122 123 124 125 126 127 128 |
# File 'lib/echoes/gui.rb', line 116 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
2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 |
# File 'lib/echoes/gui.rb', line 2586 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).
111 112 113 114 |
# File 'lib/echoes/gui.rb', line 111 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
227 228 229 230 231 232 |
# File 'lib/echoes/gui.rb', line 227 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.
2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 |
# File 'lib/echoes/gui.rb', line 2438 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
130 131 132 133 134 135 136 137 138 139 140 141 142 143 |
# File 'lib/echoes/gui.rb', line 130 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).
2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 |
# File 'lib/echoes/gui.rb', line 2776 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 |
#compute_drop_index(x, tab_w, num_tabs) ⇒ Object
Insertion index 0..num_tabs for a cursor at view-x. Splits each tab in half: cursor in the left half of tab i → insert before i; right half → insert before i+1. Clamped at both ends.
158 159 160 161 |
# File 'lib/echoes/gui.rb', line 158 def compute_drop_index(x, tab_w, num_tabs) return 0 if num_tabs <= 0 || tab_w <= 0 ((x + tab_w / 2.0) / tab_w).to_i.clamp(0, num_tabs) end |
#copy_mode_key_down(event_ptr, pane) ⇒ Object
1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 |
# File 'lib/echoes/gui.rb', line 1761 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_fonts ⇒ Object
521 522 523 524 525 526 527 |
# File 'lib/echoes/gui.rb', line 521 def create_fonts @font = ObjC.retain(create_nsfont(@font_size)) @bold_font = ObjC.retain(create_bold_nsfont(@font)) @tab_font = ObjC.retain(create_nsfont(tab_font_size)) @font_y_offset_cache = {} update_cell_metrics end |
#create_tab(editor_file: nil) ⇒ Object
87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 |
# File 'lib/echoes/gui.rb', line 87 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: , 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_class ⇒ Object
537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 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 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 |
# File 'lib/echoes/gui.rb', line 537 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) + 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) } # firstRectForCharacterRange:actualRange: returns NSRect (4 # doubles). Fiddle::Closure has no way to return a struct, so # we can't implement it directly — a TYPE_DOUBLE closure only # writes one of the four NSRect fields to v0 and leaves the # rest as register garbage, which makes the IME candidate # window appear off-screen or get suppressed entirely. # # Forward it through methodSignatureForSelector: + forward- # Invocation: instead — NSInvocation.setReturnValue: handles # the struct ABI for us. We just write 4 doubles into a buffer # and hand the pointer to AppKit. The wiring lives in # @method_sig_closure / @forward_inv_closure below. @method_sig_closure = Fiddle::Closure::BlockCaller.new( Fiddle::TYPE_VOIDP, [Fiddle::TYPE_VOIDP, Fiddle::TYPE_VOIDP, Fiddle::TYPE_VOIDP] ) do |_self, _cmd, sel| gui.method_signature_for_selector(_self, sel) rescue => e gui.log_crash(e, context: 'methodSignatureForSelector') Fiddle::Pointer.new(0) end @forward_inv_closure = Fiddle::Closure::BlockCaller.new( Fiddle::TYPE_VOID, [Fiddle::TYPE_VOIDP, Fiddle::TYPE_VOIDP, Fiddle::TYPE_VOIDP] ) do |_self, _cmd, inv| gui.forward_invocation(_self, inv) rescue => e gui.log_crash(e, context: 'forwardInvocation') end # respondsToSelector: needs to claim YES for the forwarded # selector — AppKit's IME code checks before calling, and # the runtime's default class_respondsToSelector returns NO # for selectors we don't implement directly (only forward). @responds_to_sel_closure = Fiddle::Closure::BlockCaller.new( Fiddle::TYPE_CHAR, [Fiddle::TYPE_VOIDP, Fiddle::TYPE_VOIDP, Fiddle::TYPE_VOIDP] ) { |_self, _cmd, sel| gui.responds_to_selector?(_self, sel) } @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 = 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 = .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] = .call(-> { apply_profile(pname) }) end @new_window_closure = .call(-> { open_new_window }) @new_tab_closure = .call(-> { create_tab ObjC::MSG_VOID_I.call(@view, ObjC.sel('setNeedsDisplay:'), 1) }) @edit_file_closure = .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 = .call(-> { close_tab(@active_tab) ObjC::MSG_VOID_I.call(@view, ObjC.sel('setNeedsDisplay:'), 1) }) @copy_closure = .call(-> { copy_to_clipboard }) @paste_closure = .call(-> { paste_from_clipboard }) @select_all_closure = .call(-> { select_all }) @increase_font_closure = .call(-> { update_font(@font_size + 1.0) }) @decrease_font_closure = .call(-> { update_font(@font_size - 1.0) if @font_size > 4.0 }) @reset_font_closure = .call(-> { Preferences.delete(:font_size) update_font(Echoes.config.font_size, persist: false) }) @toggle_find_closure = .call(-> { toggle_search ObjC::MSG_VOID_I.call(@view, ObjC.sel('setNeedsDisplay:'), 1) }) @find_next_closure = .call(-> { if @search_mode && !@search_matches.empty? search_next ObjC::MSG_VOID_I.call(@view, ObjC.sel('setNeedsDisplay:'), 1) end }) @find_prev_closure = .call(-> { if @search_mode && !@search_matches.empty? search_prev ObjC::MSG_VOID_I.call(@view, ObjC.sel('setNeedsDisplay:'), 1) end }) @prev_tab_closure = .call(-> { @active_tab = (@active_tab - 1) % @tabs.size ObjC::MSG_VOID_I.call(@view, ObjC.sel('setNeedsDisplay:'), 1) }) @next_tab_closure = .call(-> { @active_tab = (@active_tab + 1) % @tabs.size ObjC::MSG_VOID_I.call(@view, ObjC.sel('setNeedsDisplay:'), 1) }) # Cmd+1..8 → tabs 1..8; Cmd+9 → last tab (whichever it is) — # matches Safari, Chrome, iTerm2, Ghostty. The indexing / # bounds / no-op logic lives in select_tab so it's testable # without standing up the closure + menu machinery. @select_tab_closures = (1..9).map do |n| .call(-> { ObjC::MSG_VOID_I.call(@view, ObjC.sel('setNeedsDisplay:'), 1) if select_tab(n) }) end @split_right_closure = .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 = .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 = .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 = .call(-> { current_tab.next_pane ObjC::MSG_VOID_I.call(@view, ObjC.sel('setNeedsDisplay:'), 1) }) @select_prev_pane_closure = .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 = .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 = .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] ) do |_self, _cmd, sender| gui.activate_for_view(_self); gui.update_drag_target(sender) rescue => e gui.log_crash(e, context: 'draggingEntered') 1 # fall back to NSDragOperationCopy so file-URL drops still work end @dragging_updated_closure = Fiddle::Closure::BlockCaller.new( Fiddle::TYPE_LONG, [Fiddle::TYPE_VOIDP, Fiddle::TYPE_VOIDP, Fiddle::TYPE_VOIDP] ) do |_self, _cmd, sender| gui.activate_for_view(_self); gui.update_drag_target(sender) rescue => e gui.log_crash(e, context: 'draggingUpdated') 1 end @dragging_exited_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.clear_drag_target rescue => e gui.log_crash(e, context: 'draggingExited') end @dragging_session_source_op_mask_closure = Fiddle::Closure::BlockCaller.new( Fiddle::TYPE_LONG, [Fiddle::TYPE_VOIDP, Fiddle::TYPE_VOIDP, Fiddle::TYPE_VOIDP, Fiddle::TYPE_LONG] ) { |_self, _cmd, _session, _ctx| ObjC::NSDragOperationMove } @dragging_session_ended_closure = Fiddle::Closure::BlockCaller.new( Fiddle::TYPE_VOID, [Fiddle::TYPE_VOIDP, Fiddle::TYPE_VOIDP, Fiddle::TYPE_VOIDP, Fiddle::TYPE_DOUBLE, Fiddle::TYPE_DOUBLE, Fiddle::TYPE_LONG] ) do |_self, _cmd, _session, screen_x, screen_y, operation| gui.tab_drag_ended(_self, screen_x, screen_y, operation) rescue => e gui.log_crash(e, context: 'draggingSessionEnded') end @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], **(1..9).each_with_object({}) { |n, h| h["selectTab#{n}:"] = ['v@:@', @select_tab_closures[n - 1]] }, '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: is intentionally # not in the methods dict — it returns NSRect (4 doubles) # which Fiddle::Closure can't model. The runtime falls # through to the methodSignatureForSelector / forwardInvocation # pair below, which writes the rect via NSInvocation. 'methodSignatureForSelector:' => ['@@::', @method_sig_closure], 'forwardInvocation:' => ['v@:@', @forward_inv_closure], 'respondsToSelector:' => ['c@::', @responds_to_sel_closure], 'characterIndexForPoint:' => ['Q@:{CGPoint=dd}', @char_index_closure], 'draggingEntered:' => ['Q@:@', @dragging_entered_closure], 'draggingUpdated:' => ['Q@:@', @dragging_updated_closure], 'draggingExited:' => ['v@:@', @dragging_exited_closure], 'performDragOperation:' => ['c@:@', @perform_drag_closure], 'draggingSession:sourceOperationMaskForDraggingContext:' => ['Q@:@Q', @dragging_session_source_op_mask_closure], 'draggingSession:endedAtPoint:operation:' => ['v@:@{CGPoint=dd}Q', @dragging_session_ended_closure], }) # Add NSTextInputClient protocol conformance for IME protocol = ObjC::GetProtocol.call('NSTextInputClient') ObjC::AddProtocol.call(@view_class, protocol) unless protocol.null? end |
#current_tab ⇒ Object
145 146 147 |
# File 'lib/echoes/gui.rb', line 145 def current_tab @tabs[@active_tab] end |
#decode_tab_drag_token(str) ⇒ Object
196 197 198 199 200 201 202 203 204 |
# File 'lib/echoes/gui.rb', line 196 def decode_tab_drag_token(str) return nil if str.nil? || str.empty? parts = str.split(':') return nil unless parts.size == 2 vp = Integer(parts[0], 10) rescue nil ti = Integer(parts[1], 10) rescue nil return nil if vp.nil? || ti.nil? || ti < 0 [vp, ti] end |
#disable_press_and_hold ⇒ Object
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.
345 346 347 348 349 350 351 |
# File 'lib/echoes/gui.rb', line 345 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
1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 |
# File 'lib/echoes/gui.rb', line 1648 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
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 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 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 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 1562 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 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 |
# File 'lib/echoes/gui.rb', line 1221 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? # Kitty graphics z<0 placements blit BEFORE cells, so cell glyphs # (and explicit cell bg fills) draw on top. Sorted ascending by # z so a less-negative z stacks atop a more-negative one. Cells # with the default (transparent) bg skip the fill rect — the # placement shows through; cells with an explicit ANSI bg paint # opaque and occlude the placement at those cells. below = screen.placements.select { |pl| pl[:z_index].to_i < 0 } if !below.empty? below.sort_by { |pl| pl[:z_index].to_i }.each do |pl| blit_kitty_placement(pl, px, py, pane_rows) end end 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 when 3 # Baseline-align mode (Echoes extension). All # multicells on the same anchor row that share # the same `s=` end up with their baselines on # the same y, regardless of font / scale / n/d. # Target baseline sits at "last cell's natural # baseline within the block" — i.e. the bottom # row of the block, treated as if it were a # single body cell with @font's natural metrics. # Concretely: baseline_y = block_top + # block_h - cell_h + @font_default_ascender. # We solve for draw_y from "drawAtPoint sets # line-box top, baseline = top + ascender": # draw_y = baseline_y - scaled_ascender. # Big and small spans pick different draw_y # values to land on the SAME baseline_y. # For tall scaled text whose ascender exceeds # block_h - cell_h, draw_y goes negative within # the block and the glyph top extends above — # which matches how a real baseline-shared row # with mixed sizes is supposed to look. y + block_h - @cell_height + @font_default_ascender - scaled_ascender 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 z>=0 placements ON TOP of the rendered # cells. (z<0 placements were drawn above before the cell loop, # so cell text appears in front of them.) 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 .select { |pl| pl[:z_index].to_i >= 0 } .sort_by { |pl| pl[:z_index].to_i } .each { |pl| blit_kitty_placement(pl, px, py, pane_rows) } # 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
1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 |
# File 'lib/echoes/gui.rb', line 1625 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 —
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 |
# File 'lib/echoes/gui.rb', line 1146 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 = 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 = if dirty_min_y < tby + tbh && dirty_max_y > tby (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 = @cell_height + 4.0 = gy_off + @rows * @cell_height = make_color(0.2, 0.2, 0.2) ObjC::MSG_VOID.call(, ObjC.sel('setFill')) ObjC::NSRectFill.call(0.0, , @cols * @cell_width, ) 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, + 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.
223 224 225 |
# File 'lib/echoes/gui.rb', line 223 def ENV['ECHOES_EMBED'] == '1' end |
#encode_tab_drag_token(view_ptr, tab_index) ⇒ Object
Token format on the pasteboard for tab drag. Single-process app, so identity = view pointer + tab index at the time the drag started. Decoded into integer pair or nil for malformed input.
192 193 194 |
# File 'lib/echoes/gui.rb', line 192 def encode_tab_drag_token(view_ptr, tab_index) "#{view_ptr}:#{tab_index}" 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.
2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 |
# File 'lib/echoes/gui.rb', line 2255 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 |
#first_rect_for_marked_text_screen_coords ⇒ Object
Compute the on-screen rect for the marked-text caret, used by the IME to anchor its candidate window. Returns 4 doubles
- origin_x, origin_y, width, height
-
in screen coords. Origin
is bottom-left (NSScreen convention, y from bottom).
We anchor on the active pane’s cursor (the marked text is drawn there, see draw_pane_content). When @marked_text is set, use its measured width so the candidate window aligns with the right edge of the composition; otherwise fall back to a single cell so the IME still has something sensible to anchor on.
1925 1926 1927 1928 1929 1930 1931 1932 1933 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 |
# File 'lib/echoes/gui.rb', line 1925 def first_rect_for_marked_text_screen_coords return [0.0, 0.0, 0.0, 0.0] unless @view && @window && @tabs && @tabs.any? tab = current_tab pane = tab&.active_pane return [0.0, 0.0, 0.0, 0.0] unless pane rect_info = tab.pane_tree.layout(0, 0, @cols, @rows).find { |r| r[:pane] == pane } return [0.0, 0.0, 0.0, 0.0] unless rect_info cell_w = @cell_width.to_f cell_h = @cell_height.to_f gy_off = grid_y_offset pane_px = rect_info[:x] * cell_w pane_py = gy_off + rect_info[:y] * cell_h cursor = pane.screen.cursor mx_view = pane_px + cursor.col * cell_w my_view = pane_py + cursor.row * cell_h width = if @marked_text && !@marked_text.empty? @marked_text.each_char.sum { |c| c.ord > 0x7F ? cell_w * 2 : cell_w } else cell_w end # View y is flipped (top-origin); NSWindow / NSScreen y is # bottom-origin. The rect's BOTTOM in window coords sits at # (view_frame_height − rect_bottom_in_view_coords). vfh = view_frame_height win_x = mx_view win_y = vfh - (my_view + cell_h) sx, sy = window_to_screen_point(win_x, win_y) [sx, sy, width, cell_h] end |
#forward_invocation(_self_ptr, inv) ⇒ Object
1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 |
# File 'lib/echoes/gui.rb', line 1891 def forward_invocation(_self_ptr, inv) sel = ObjC::MSG_PTR.call(inv, ObjC.sel('selector')) name = sel_name_string(sel) return unless name == 'firstRectForCharacterRange:actualRange:' rect = first_rect_for_marked_text_screen_coords buf = Fiddle::Pointer.malloc(32, Fiddle::RUBY_FREE) buf[0, 32] = rect.pack('d4') ObjC::MSG_VOID_1.call(inv, ObjC.sel('setReturnValue:'), buf) end |
#grid_y_offset ⇒ Object
312 313 314 |
# File 'lib/echoes/gui.rb', line 312 def grid_y_offset Echoes.config.tab_position == :bottom ? 0.0 : end |
#handle_resize(w, h) ⇒ Object
2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 |
# File 'lib/echoes/gui.rb', line 2392 def handle_resize(w, h) tbh = 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 |
#handle_tab_drop(sender, token) ⇒ Object
Resolve a tab-drag token, look up source & target window-states, splice via transfer_tab, and close the source window if its last tab moved away. Both windows redraw on success.
2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 |
# File 'lib/echoes/gui.rb', line 2524 def handle_tab_drop(sender, token) parsed = decode_tab_drag_token(token) return false unless parsed src_view_ptr, src_index = parsed src_ws = @view_to_ws[src_view_ptr] target_ws = @view_to_ws[@view.to_i] return false unless src_ws && target_ws # Compute insertion index from the destination view's cursor — # the same calculation update_drag_target did during hover. We # recompute rather than trusting @drag_insertion_index because # the user may have crossed back outside the bar between the # last move event and the drop. dx, dy_window = dragging_location(sender) dy = view_frame_height - dy_window tbh = = if tbh > 0 && dy >= && dy < + tbh tab_w = (@cell_width * @cols).to_f / @tabs.size dst_index = compute_drop_index(dx, tab_w, @tabs.size) else # Drop landed in the grid area of the target window — treat as # append. (Tear-out outside any window is handled separately # by the source's endedAtPoint callback.) dst_index = target_ws[:tabs].size end moved = transfer_tab(src_ws, src_index, target_ws, dst_index) clear_drag_target # Source-side stash was set by start_tab_drag; the gesture is # resolved, so clear it. src_ws.delete(:dragging_tab_index) return true unless moved # target_ws is the live current-view ws (we set it from # @view_to_ws[@view.to_i] above). transfer_tab updated the # saved-state form (ws[:active_tab]); we still need to mirror # it into the live @active_tab ivar so the on-screen active # tab actually follows the dropped tab. Without this, the # window keeps showing whatever was active before the drop. @active_tab = target_ws[:active_tab] # If source emptied, close that window. close_current_window # operates on the currently-active view, so switch to the # source view first, then switch back. if src_ws[:tabs].empty? && src_ws[:nsview] && src_view_ptr != @view.to_i save_window_state load_window_state(src_ws) close_current_window load_window_state(target_ws) end # Redraw both views. The target view is @view; mark the source # view's NSView too (no-op if it was just closed above). ObjC::MSG_VOID_I.call(@view, ObjC.sel('setNeedsDisplay:'), 1) if src_ws != target_ws && src_ws[:nsview] && !src_ws[:tabs].empty? ObjC::MSG_VOID_I.call(src_ws[:nsview], ObjC.sel('setNeedsDisplay:'), 1) end true end |
#ime_do_command ⇒ Object
1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 |
# File 'lib/echoes/gui.rb', line 1805 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_text ⇒ Object
1843 1844 1845 |
# File 'lib/echoes/gui.rb', line 1843 def ime_has_marked_text @marked_text ? 1 : 0 end |
#ime_insert_text(text_ptr) ⇒ Object
— IME (Input Method Editor) callbacks —
1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 |
# File 'lib/echoes/gui.rb', line 1791 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_location ⇒ Object
1847 1848 1849 |
# File 'lib/echoes/gui.rb', line 1847 def ime_marked_range_location @marked_text ? 0 : 0x7FFFFFFFFFFFFFFF # NSNotFound end |
#ime_set_marked_text(text_ptr, _sel_loc, _sel_len) ⇒ Object
1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 |
# File 'lib/echoes/gui.rb', line 1826 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_text ⇒ Object
1838 1839 1840 1841 |
# File 'lib/echoes/gui.rb', line 1838 def ime_unmark_text @marked_text = nil ObjC::MSG_VOID_I.call(@view, ObjC.sel('setNeedsDisplay:'), 1) end |
#invalidate_dirty_rows(dirty_rows) ⇒ Object
2095 2096 2097 2098 2099 2100 2101 2102 2103 |
# File 'lib/echoes/gui.rb', line 2095 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
1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 |
# File 'lib/echoes/gui.rb', line 1673 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. # 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..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.}" exception.backtrace&.each { |line| f.puts " #{line}" } f.puts end STDERR.puts "echoes: #{exception.class}: #{exception.} (logged to #{CRASH_LOG})" rescue # log_crash itself must never raise end |
#method_signature_for_selector(self_ptr, sel) ⇒ Object
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 1869 def method_signature_for_selector(self_ptr, sel) name = sel_name_string(sel) if name == 'firstRectForCharacterRange:actualRange:' return ObjC::MSG_PTR_1.call( ObjC.cls('NSMethodSignature'), ObjC.sel('signatureWithObjCTypes:'), Fiddle::Pointer[FIRST_RECT_SIG.b]) end # Default: defer to whatever the runtime would have computed # from the class's method table. class_getInstanceMethod walks # the hierarchy so directly-implemented + inherited methods # all resolve. self_class = ObjC::MSG_PTR.call(self_ptr, ObjC.sel('class')) method = ObjC::ClassGetInstanceMethod.call(self_class, sel) return Fiddle::Pointer.new(0) if method.null? enc = ObjC::MethodGetTypeEncoding.call(method) ObjC::MSG_PTR_1.call( ObjC.cls('NSMethodSignature'), ObjC.sel('signatureWithObjCTypes:'), enc) end |
#mouse_down(event_ptr) ⇒ Object
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 2173 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 |
# File 'lib/echoes/gui.rb', line 2132 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, click_y = 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 # Record drag intent — mouseDragged checks whether the cursor # has moved past a small threshold and, if so, hands the # gesture to AppKit's drag session. @drag_start_tab_index = clicked_tab @drag_start_point = [click_x, click_y] 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. mark = pane.screen.find_command_mark_at_row(abs_row) if mark && mark[:command_text] && !pane..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
2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 |
# File 'lib/echoes/gui.rb', line 2213 def mouse_dragged(event_ptr) tab = current_tab return unless tab # Tab-drag intent: if the press landed on the tab bar AND the # cursor has moved past a small threshold, hand the gesture to # AppKit's drag session. Tested first because the threshold can # fire while pos is still nil (cursor still inside the tab bar). if @drag_start_tab_index cx, cy = event_location(event_ptr) sx, sy = @drag_start_point if (cx - sx).abs > DRAG_THRESHOLD_PX || (cy - sy).abs > DRAG_THRESHOLD_PX tab_index = @drag_start_tab_index @drag_start_tab_index = nil @drag_start_point = nil start_tab_drag(event_ptr, tab_index) return end end 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.
2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 |
# File 'lib/echoes/gui.rb', line 2302 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
2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 |
# File 'lib/echoes/gui.rb', line 2279 def mouse_up(event_ptr) # Clear tab-drag intent so a click-without-drag doesn't leave # stale state for the next mouseDown. @drag_start_tab_index = nil @drag_start_point = nil 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
2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 |
# File 'lib/echoes/gui.rb', line 2353 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
2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 |
# File 'lib/echoes/gui.rb', line 2366 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
2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 |
# File 'lib/echoes/gui.rb', line 2379 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
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 |
# File 'lib/echoes/gui.rb', line 2489 def perform_drag_operation(sender) pb = ObjC::MSG_PTR.call(sender, ObjC.sel('draggingPasteboard')) # Our private tab-drag type takes precedence — the user is # moving a tab, not pasting a file. tab_type = ObjC.nsstring(ObjC::EchoesPasteboardTypeTab) tab_type_array = ObjC::MSG_PTR_1.call(ObjC.cls('NSArray'), ObjC.sel('arrayWithObject:'), tab_type) avail = ObjC::MSG_PTR_1.call(pb, ObjC.sel('availableTypeFromArray:'), tab_type_array) unless avail.null? token = ObjC::MSG_PTR_1.call(pb, ObjC.sel('stringForType:'), tab_type) return handle_tab_drop(sender, ObjC.to_ruby_string(token)) end # Fall through to the file-URL path. 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
1669 1670 1671 |
# File 'lib/echoes/gui.rb', line 1669 def perform_key_equivalent(event_ptr) 0 end |
#reflow_to_current_view_size ⇒ Object
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.
2413 2414 2415 2416 2417 |
# File 'lib/echoes/gui.rb', line 2413 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 |
#responds_to_selector?(self_ptr, sel) ⇒ Boolean
1902 1903 1904 1905 1906 1907 1908 |
# File 'lib/echoes/gui.rb', line 1902 def responds_to_selector?(self_ptr, sel) name = sel_name_string(sel) return 1 if IME_FORWARDED_SELECTORS.include?(name) self_class = ObjC::MSG_PTR.call(self_ptr, ObjC.sel('class')) method = ObjC::ClassGetInstanceMethod.call(self_class, sel) method.null? ? 0 : 1 end |
#right_mouse_down(event_ptr) ⇒ Object
2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 |
# File 'lib/echoes/gui.rb', line 2314 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
2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 |
# File 'lib/echoes/gui.rb', line 2327 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
2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 |
# File 'lib/echoes/gui.rb', line 2340 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 |
#run ⇒ Object
78 79 80 81 82 83 84 85 |
# File 'lib/echoes/gui.rb', line 78 def run setup_app create_fonts create_view_class open_new_window setup_timer start_app end |
#scroll_wheel(event_ptr) ⇒ Object
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 |
# File 'lib/echoes/gui.rb', line 2105 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 = delta > 0 ? 64 : 65 # 64=scroll up, 65=scroll down send_mouse_event(tab, , 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 |
#sel_name_string(sel) ⇒ Object
1910 1911 1912 1913 |
# File 'lib/echoes/gui.rb', line 1910 def sel_name_string(sel) ptr = ObjC::SelGetName.call(sel) ptr.null? ? '' : ptr.to_s end |
#select_tab(n) ⇒ Object
Switch to a tab by 1-based slot number (Cmd+N shortcuts). n=1..8 maps to that tab index; n=9 maps to the LAST tab regardless of count, matching Safari / Chrome / iTerm2 / Ghostty. Returns true when the active tab actually changed (the caller redraws on true), false when the request was a no-op — target out of range or already active.
212 213 214 215 216 217 218 |
# File 'lib/echoes/gui.rb', line 212 def select_tab(n) target = (n == 9) ? @tabs.size - 1 : n - 1 return false if target < 0 || target >= @tabs.size return false if target == @active_tab @active_tab = target true end |
#setup_app ⇒ Object
320 321 322 323 324 325 326 327 328 329 330 331 332 333 |
# File 'lib/echoes/gui.rb', line 320 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) end |
#setup_menu_bar ⇒ Object
353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 |
# File 'lib/echoes/gui.rb', line 353 def = ('') # Application menu = ('Echoes') (, "About Echoes", 'showAbout:', '') add_separator() (, "Hide Echoes", 'hide:', 'h') (, "Hide Others", 'hideOtherApplications:', '') (, "Show All", 'unhideAllApplications:', '') add_separator() (, "Quit Echoes", 'terminate:', 'q') (, , 'Echoes') # Edit menu = ('Edit') (, "Copy", 'copy:', 'c') (, "Paste", 'paste:', 'v') (, "Select All", 'selectAll:', 'a') (, , 'Edit') # View menu = ('View') (, "Bigger", 'increaseFontSize:', '=', bind: :increase_font_size) (, "Bigger", 'increaseFontSize:', '+', bind: :increase_font_size_plus) (, "Smaller", 'decreaseFontSize:', '-', bind: :decrease_font_size) (, "Reset Font Size", 'resetFontSize:', '0', bind: :reset_font_size) add_separator() (, "Find", 'toggleFind:', 'f', bind: :toggle_find) (, "Find Next", 'findNext:', 'g', bind: :find_next) (, "Find Previous", 'findPrevious:', 'g', modifiers: ObjC::NSEventModifierFlagCommand | ObjC::NSEventModifierFlagShift, bind: :find_previous) add_separator() (, "Hide Mouse Pointer", 'togglePointer:', 'p', modifiers: ObjC::NSEventModifierFlagCommand | ObjC::NSEventModifierFlagShift, bind: :toggle_pointer) () (, , 'View') # Window menu = ('Window') (, "Minimize", 'miniaturize:', 'm') (, "Zoom", 'zoom:', '') (, "Enter Full Screen", 'toggleFullScreen:', 'f', modifiers: ObjC::NSEventModifierFlagCommand | ObjC::NSEventModifierFlagControl) add_separator() (, "Show Previous Tab", 'showPreviousTab:', '{', modifiers: ObjC::NSEventModifierFlagCommand | ObjC::NSEventModifierFlagShift, bind: :show_previous_tab) (, "Show Next Tab", 'showNextTab:', '}', modifiers: ObjC::NSEventModifierFlagCommand | ObjC::NSEventModifierFlagShift, bind: :show_next_tab) # Cmd+1..8 jump to that tab index; Cmd+9 goes to the last tab. (1..9).each do |n| title = (n == 9) ? "Show Last Tab" : "Show Tab #{n}" (, title, "selectTab#{n}:", n.to_s, bind: :"select_tab_#{n}") end add_separator() (, "Select Next Pane", 'selectNextPane:', ']', bind: :select_next_pane) (, "Select Previous Pane", 'selectPreviousPane:', '[', bind: :select_previous_pane) add_separator() (, "Toggle Copy Mode", 'toggleCopyMode:', 'c', modifiers: ObjC::NSEventModifierFlagCommand | ObjC::NSEventModifierFlagShift, bind: :toggle_copy_mode) add_separator() # 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') # Shell menu = ('Shell') (, "New Window", 'newWindow:', 'n', bind: :new_window) (, "New Tab", 'newTab:', 't', bind: :new_tab) (, "Close Tab", 'closeTab:', 'w', bind: :close_tab) add_separator() (, "Edit File…", 'editFile:', 'e', modifiers: ObjC::NSEventModifierFlagCommand | ObjC::NSEventModifierFlagShift, bind: :edit_file) add_separator() (, "Split Right", 'splitRight:', 'd', bind: :split_right) (, "Split Down", 'splitDown:', 'd', modifiers: ObjC::NSEventModifierFlagCommand | ObjC::NSEventModifierFlagShift, bind: :split_down) (, "Close Pane", 'closePane:', 'w', modifiers: ObjC::NSEventModifierFlagCommand | ObjC::NSEventModifierFlagShift, bind: :close_pane) (, , 'Shell') ObjC::MSG_VOID_1.call(@app, ObjC.sel('setMainMenu:'), ) end |
#setup_timer ⇒ Object
1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 |
# File 'lib/echoes/gui.rb', line 1127 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_app ⇒ Object
1140 1141 1142 |
# File 'lib/echoes/gui.rb', line 1140 def start_app ObjC::MSG_VOID.call(@app, ObjC.sel('run')) end |
#tab_bar_height ⇒ Object
308 309 310 |
# File 'lib/echoes/gui.rb', line 308 def @tabs.size > 1 ? @cell_height : 0.0 end |
#tab_bar_y ⇒ Object
316 317 318 |
# File 'lib/echoes/gui.rb', line 316 def Echoes.config.tab_position == :bottom ? @cell_height * @rows : 0.0 end |
#tab_font_size ⇒ Object
Tab labels render in a smaller font than the cell grid so long titles read comfortably even when the bar’s split across many narrow tabs. Scales with the user’s font_size so the bar stays proportional at any zoom.
533 534 535 |
# File 'lib/echoes/gui.rb', line 533 def tab_font_size [(@font_size * 0.85).round(1), 9.0].max end |
#timer_fired ⇒ Object
1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 |
# File 'lib/echoes/gui.rb', line 1986 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 |
#transfer_tab(src_ws, src_index, dst_ws, dst_index) ⇒ Object
Splice a tab between window-state hashes. Updates the destination window’s :active_tab to land on the dropped tab. For same-array moves, treats dst==src and dst==src+1 as no-ops (both yield no movement). Returns true on a real move, false on a no-op.
167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 |
# File 'lib/echoes/gui.rb', line 167 def transfer_tab(src_ws, src_index, dst_ws, dst_index) same = src_ws.equal?(dst_ws) return false if same && (dst_index == src_index || dst_index == src_index + 1) src_tabs = src_ws[:tabs] return false if src_index < 0 || src_index >= src_tabs.size tab = src_tabs.delete_at(src_index) # Same-array: removal shifts later positions down by 1. dst_index -= 1 if same && src_index < dst_index dst_tabs = dst_ws[:tabs] dst_index = dst_index.clamp(0, dst_tabs.size) dst_tabs.insert(dst_index, tab) dst_ws[:active_tab] = dst_index unless same # Source window's active tab should stay in bounds. src_ws[:active_tab] = src_ws[:active_tab].clamp(0, [src_tabs.size - 1, 0].max) end true end |
#update_font(new_size, persist: true) ⇒ Object
2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 |
# File 'lib/echoes/gui.rb', line 2460 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 old_tab = @tab_font @font = ObjC.retain(create_nsfont(@font_size)) @bold_font = ObjC.retain(create_bold_nsfont(@font)) @tab_font = ObjC.retain(create_nsfont(tab_font_size)) ObjC.release(old_font) if old_font ObjC.release(old_bold) if old_bold ObjC.release(old_tab) if old_tab @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 = + @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
2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 |
# File 'lib/echoes/gui.rb', line 2419 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 |
#window_to_screen_point(x, y) ⇒ Object
- NSWindow convertPointToScreen:
-
returns NSPoint (2 doubles).
Same trick as event_location / dragging_location uses for the other NSPoint-returning calls — Fiddle can’t model the return directly, so go through NSInvocation.
1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 |
# File 'lib/echoes/gui.rb', line 1964 def window_to_screen_point(x, y) sig = ObjC::MSG_PTR_1.call( ObjC.cls('NSWindow'), ObjC.sel('instanceMethodSignatureForSelector:'), ObjC.sel('convertPointToScreen:')) inv = ObjC::MSG_PTR_1.call( ObjC.cls('NSInvocation'), ObjC.sel('invocationWithMethodSignature:'), sig) ObjC::MSG_VOID_1.call(inv, ObjC.sel('setSelector:'), ObjC.sel('convertPointToScreen:')) arg = Fiddle::Pointer.malloc(16, Fiddle::RUBY_FREE) arg[0, 16] = [x, y].pack('dd') # setArgument:atIndex: signature is (id, SEL, void*, NSInteger). # No existing reusable msgSend variant matches; compose inline. set_arg_sig = ObjC.new_msg([ObjC::P, ObjC::P, ObjC::P, ObjC::L], ObjC::V) set_arg_sig.call(inv, ObjC.sel('setArgument:atIndex:'), arg, 2) ObjC::MSG_VOID_1.call(inv, ObjC.sel('invokeWithTarget:'), @window) out = Fiddle::Pointer.malloc(16, Fiddle::RUBY_FREE) ObjC::MSG_VOID_1.call(inv, ObjC.sel('getReturnValue:'), out) out[0, 16].unpack('dd') end |