#!/usr/bin/ruby -w
# Encoding: UTF-8
# frozen_string_literal: true
# =========================================================================== #
# This has been found here:
#
#   https://ruby-gnome2.osdn.jp/hiki.cgi?tut-gtk2-txtw-itrsmrks
#
# =========================================================================== #
require 'gtk2'

::Gtk::Settings.default.gtk_font_name = 'Mono 25'

# =========================================================================== #
# === insert_text
#
# Insert the text from the GtkEntry into the GtkTextView, via this
# method.
# =========================================================================== #
def insert_text(entry, text_view)
  text_buffer = text_view.buffer
  mark = text_buffer.selection_bound # First, obtain the text-mark.
  iter = text_buffer.get_iter_at_mark(mark) # The text-mark is translated into an iter.
  insert_this_text = entry.text
  if insert_this_text.include? '\n'
    insert_this_text.gsub!(/\\n/,"\n")
  end
  text_buffer.insert(iter, insert_this_text) # Put the content of the gtk-entry into the buffer.
end

# =========================================================================== #
# Retrieve the selected text from the GtkTextView and display it to 
# the user.
# =========================================================================== #
def retrieve_text(tw)
  start_iter, end_iter, selected  = tw.buffer.selection_bounds
  if !selected
    start_iter, end_iter = tw.buffer.bounds
  end
  text = tw.buffer.get_text(start_iter, end_iter)
  puts "selected=#{selected}; TEXT=#{text}"
end

window = Gtk::Window.new("Text Iterators")
window.resizable = true
window.border_width = 10
window.signal_connect(:destroy) { Gtk.main_quit }
window.set_size_request(5000, 350)

textbuffer = Gtk::TextBuffer.new
textbuffer.set_text("Hello world!\n")
textview = Gtk::TextView.new(textbuffer)

entry    = Gtk::Entry.new
retrieve = Gtk::Button.new('Get Text')
retrieve.signal_connect(:clicked) { retrieve_text(textview) }

insert   = Gtk::Button.new('← _Insert this Text', true)
insert.signal_connect(:clicked) { insert_text(entry, textview) }

scrolled_win = Gtk::ScrolledWindow.new
scrolled_win.border_width = 5
scrolled_win.add(textview)
scrolled_win.set_policy(Gtk::POLICY_AUTOMATIC, Gtk::POLICY_ALWAYS)

hbox = Gtk::HBox.new(false, 5)
hbox.pack_start(entry, true, true, 2)
hbox.pack_start_defaults(insert)
hbox.pack_start_defaults(retrieve)
vbox = Gtk::VBox.new(false, 5)
vbox.pack_start(scrolled_win, true,  true, 0)
vbox.pack_start(hbox,         false, true, 0)
window.add(vbox)
window.move(0, 0)
window.set_size_request(800, 600)
window.show_all
Gtk.main