#!/usr/bin/ruby
# encoding: utf-8
#
# Cyrka (degibberish tool)
# Recovers Cyrillic text improperly transcoded from Windows charset.
# Author: Paul Philippov <themactep@gmail.com>
# License: http://creativecommons.org/licenses/BSD/
#
# Version 1.0.0, 25-Sep-2009
#  * First public release
#
# Version 1.0.1, 05-Aug-2012
#  * Support ruby 1.9, drop iconv
#
# Version 1.0.2, 30-Dec-2013
#  * Fix Encoding::UndefinedConversionError
#
# Version 1.1.0, 31-Dec-2013
#  * Switch to GTK3
#
# Version 1.2.0 01-Dec-2020
#  * Refactor deprecated code
#

require 'gtk3'

module Ppds
  class Cyrka < Gtk::Window
    def initialize
      super :toplevel

      set_size_request 350, 150
      set_border_width 8
      set_title 'Cyrka'
      signal_connect(:destroy) { Gtk::main_quit }

      button = Gtk::Button.new(label: 'degibberish')
      @source = Gtk::LabeledTextView.new
      @source.signal_connect(:focus_out_event) { # it cover :clicked, too
        @target.buffer.set_text(@source.buffer.text.from_1252_to_1251)
        false
      }

      @target = Gtk::LabeledTextView.new
      @target.set_editable false

      box = Gtk::Box.new(:vertical, 5)
      box.pack_start scrollable(@source)
      box.pack_start scrollable(@target)
      box.pack_start button, expand: false

      self.add box
      self.show_all
    end

    def scrollable(widget)
      scroll = Gtk::ScrolledWindow.new
      scroll.set_shadow_type Gtk::ShadowType::IN
      scroll.set_policy Gtk::PolicyType::AUTOMATIC, Gtk::PolicyType::AUTOMATIC
      scroll.add widget
      scroll.show_all
    end
  end
end

module Gtk
  class LabeledTextView < TextView
    def initialize
      super
      self.set_wrap_mode Gtk::WrapMode::WORD
      self.set_accepts_tab false
      self.set_right_margin 5
      self.set_left_margin 5
      self.buffer.set_text ''
    end
  end
end

class String
  def from_1252_to_1251
    self.encode('Windows-1252', 'UTF-8', invalid: :replace, undef: :replace, replace: '?')
        .encode('UTF-8', 'Windows-1251', invalid: :replace, undef: :replace, replace: '?')
  end
end

w = Ppds::Cyrka.new
Gtk::main
