Skip to content

Instantly share code, notes, and snippets.

@igrep
Created October 29, 2010 05:49
Show Gist options
  • Save igrep/652994 to your computer and use it in GitHub Desktop.
Save igrep/652994 to your computer and use it in GitHub Desktop.
Simple character counter with Gtk2.
#!/usr/bin/env ruby
# vim: set fileencoding=utf-8 :
$VERBOSE = true
=begin
Count the number of characters in the clipboard.
=end
require 'rubygems'
require 'clipboard'
require 'kconv'
require 'gtk2'
win = Gtk::Window.new
win.title = 'Clipboard Characters Counter'
win.border_width = 10
style = win.style
style.font_desc = Pango::FontDescription.new('monospace 15')
lbl1 = Gtk::Label.new('')
lbl1.justify = Gtk::JUSTIFY_RIGHT
lbl1.style = style
lbl2 = Gtk::Label.new('')
lbl2.justify = Gtk::JUSTIFY_RIGHT
lbl2.style = style
btn1 = Gtk::Button.new 'Copy'
btn2 = Gtk::Button.new 'Copy'
pack_args = [ true, true, 15 ]
hbox1 = Gtk::HBox.new
hbox1.pack_start( lbl1, *pack_args )
hbox1.pack_start( btn1 )
hbox2 = Gtk::HBox.new
hbox2.pack_start( lbl2, *pack_args )
hbox2.pack_start( btn2 )
vbox = Gtk::VBox.new
vbox.pack_start( hbox1 )
vbox.pack_start( hbox2 )
win.add vbox
win.signal_connect('delete_event') do
Gtk.main_quit
false
end
spaces = /[\s ]/u
split_regexp = //u
$chars_length = 0
$no_space_chars_length = 0
win.signal_connect('focus_in_event') do
chars = Clipboard.paste.toutf8.split(split_regexp)
no_space_chars = chars.reject{|c| c =~ spaces }
$chars_length = chars.length
$no_space_chars_length = no_space_chars.length
chars_length_s = $chars_length.to_s
no_space_chars_length_s = $no_space_chars_length.to_s
chars_digi = chars_length_s.length
no_space_chars_digi = no_space_chars_length_s.length
longer = chars_digi > no_space_chars_digi ? chars_digi : no_space_chars_digi
inc_space = 'Including white spaces: ' + chars_length_s.rjust( longer )
no_space = 'Excluding white spaces: ' + no_space_chars_length_s.rjust( longer )
lbl1.text = inc_space
lbl2.text = no_space
end
btn1.signal_connect('clicked') do
Clipboard.copy $chars_length.to_s
end
btn2.signal_connect('clicked') do
Clipboard.copy $no_space_chars_length.to_s
end
win.show_all
Gtk.main
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment