<commit_before># frozen_string_literal: true

require "json"
require "rack"
require "thin"
require "faye/websocket"

Faye::WebSocket.load_adapter("thin")

module Textbringer
  module GhostText
    class Server
      def call(env)
        if Faye::WebSocket.websocket?(env)
          accept_client(env)
        else
          json = {
            "WebSocketPort" => CONFIG[:ghost_text_port],
            "ProtocolVersion" => 1
          }.to_json
          [200, {'Content-Type' => 'application/json'}, [json]]
        end
      end

      private

      def accept_client(env)
        ws = Faye::WebSocket.new(env, nil,
                                 ping: CONFIG[:ghost_text_ping_interval])
        q = Queue.new
        next_tick do
          setup_buffer(ws)
          q.push(:done)
        end
        q.pop
        ws.rack_response
      end

      def setup_buffer(ws)
        buffer = Buffer.new_buffer("*GhostText*")
        switch_to_buffer(buffer)

        syncing_from_remote_text = false

        buffer.on_modified do
          unless syncing_from_remote_text
            pos = buffer.substring(0, buffer.point).size
            data = {
              "text" => buffer.to_s,
              "selections" => [{ "start" => pos, "end" => pos }]
            }
            ws&.send(data.to_json)
          end
        end

        buffer.on_killed do
          ws&.close
        end

        ws.on :message do |event|
          data = JSON.parse(event.data)
          next_tick do
            syncing_from_remote_text = true
            begin
              buffer.composite_edit do
                buffer.delete_region(buffer.point_min, buffer.point_max)
                buffer.insert(data["text"])
                pos = data["selections"]&.dig(0, "start")
                if pos
                  byte_pos = data["text"][0, pos].bytesize
                  buffer.goto_char(byte_pos)
                end
              end
            ensure
              syncing_from_remote_text = false
            end
          end
        end

        ws.on :close do |event|
          ws = nil
          next_tick do
            kill_buffer(buffer, force: true)
          end
        end
      end
    end
  end
end
<commit_msg>Switch to the buffer when the remote text is updated.<commit_after># frozen_string_literal: true

require "json"
require "rack"
require "thin"
require "faye/websocket"

Faye::WebSocket.load_adapter("thin")

module Textbringer
  module GhostText
    class Server
      def call(env)
        if Faye::WebSocket.websocket?(env)
          accept_client(env)
        else
          json = {
            "WebSocketPort" => CONFIG[:ghost_text_port],
            "ProtocolVersion" => 1
          }.to_json
          [200, {'Content-Type' => 'application/json'}, [json]]
        end
      end

      private

      def accept_client(env)
        ws = Faye::WebSocket.new(env, nil,
                                 ping: CONFIG[:ghost_text_ping_interval])
        q = Queue.new
        next_tick do
          setup_buffer(ws)
          q.push(:done)
        end
        q.pop
        ws.rack_response
      end

      def setup_buffer(ws)
        buffer = Buffer.new_buffer("*GhostText*")
        switch_to_buffer(buffer)

        syncing_from_remote_text = false

        buffer.on_modified do
          unless syncing_from_remote_text
            pos = buffer.substring(0, buffer.point).size
            data = {
              "text" => buffer.to_s,
              "selections" => [{ "start" => pos, "end" => pos }]
            }
            ws&.send(data.to_json)
          end
        end

        buffer.on_killed do
          ws&.close
        end

        ws.on :message do |event|
          data = JSON.parse(event.data)
          next_tick do
            syncing_from_remote_text = true
            begin
              buffer.composite_edit do
                buffer.delete_region(buffer.point_min, buffer.point_max)
                buffer.insert(data["text"])
                pos = data["selections"]&.dig(0, "start")
                if pos
                  byte_pos = data["text"][0, pos].bytesize
                  buffer.goto_char(byte_pos)
                end
              end
            ensure
              syncing_from_remote_text = false
            end
            switch_to_buffer(buffer)
          end
        end

        ws.on :close do |event|
          ws = nil
          next_tick do
            kill_buffer(buffer, force: true)
          end
        end
      end
    end
  end
end

{'fraction_non_alphanumeric': 0.08906077348066298, 'fraction_numerical': 0.0030939226519337017, 'mean_word_length': 1.4359526372443487, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 17, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 2, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '2871032', 'n_tokens_mistral': 1348, 'n_tokens_neox': 1281, 'n_words': 276}