[Ruby] utf-8 ruby tk

Igor Didkovsky ididkovsky на mail.ru
Ср Ноя 12 06:31:27 MSK 2003


Nikolay Ponomarenko wrote:
> ID> Давай, попробую разобраться :)
> 
> Буду безмерно благодарен, ибо уже глаза на лоб лезут :(

Странно. Извиняюсь конечно что убрал iconv - в руби его не нашел.
У меня есть только iconv.exe :(

> Я думал это его национальная кодировка. Что такое кодировка и какие
> они бывают русские - я представляю :)

Нет, кодировка европейских языков на латинице.

Видимо не совсем... Для начяла я перекодировал твою програмульку из
cp1251 в utf-8. У меня работает немного урезанная enc_test.rb на
Tktable 2.8 и tcl/tk8.3 из дистрибутива "руби для win32" :) Так-что
сабжевый вопрос решен, как я и думал - довольно просто :)

SciTE - суперский юникод-редактор, конфиг что там стоит по умолчанию
правда никуда не годиться - замени его на приаттаченый(он позволяет
править сорцы и включает зачем-то вырубленные возможности). В принципе
эти изменения можно проделать и самому...

Пиши программы в юникоде - проблем не будет!

-- 
Best regards, Igor Didkovsky.
========================================================
My projects in www:
http://langos.lrn.ru/
http://www.prolos.net/

-------------- next part --------------
A non-text attachment was scrubbed...
Name: 01.gif
Type: image/gif
Size: 10422 bytes
Desc: отсутствует
Url : /pipermail/ruby/attachments/20031112/a5877c07/01-0001.gif
-------------- next part --------------
require 'tk'
require 'tktable'

Tk.encoding = 'utf-8'

$root = TkRoot.new {
   title "п÷я─п╦п╪п╣я─ я─п╟п╠п╬я┌я▀ я│ п▒п■"
   width 500
   height 30 
 }

 # п╢п╟п╫п╫я▀п╣ п╢п╩я▐ п╥п╟п©п╬п╩п╫п╣п╫п╦я▐ я┌п╟п╠п╩п╦я├я▀
 $ds = Array.new
 $ds =[["","п я┐я│п╬я┤п╣п╨ я┌п╣п╨я│я┌п╟"],
       ["","п░ п╥п╟пЁп╟п╩п╬п╡п╬п╨ п╡ "],
       ["","п░ п╥п╢п╣я│я▄ п╡я│п╣ п╫п╬я─п╪п╟п╩я▄п╫п╬"]];

 def q(r,c,i,s) 
    # п╣я│п╩п╦ п©п╬п╩я┐я┤п╟п╣п╪ п╥п╫п╟я┤п╣п╫п╦п╣
    if i.to_i==0
      return $ds[r.to_i][c.to_i]
    else
      # п╣я│п╩п╦ п╡п╬п╥п╡я─п╟я┴п╟п╣п╪
      $ds[r.to_i][c.to_i] = s
    end
 end

 table = TkTable.new($root)
 # п╥п╟п╢п╟п╣п╪ п©я─п╬я├п╣п╢я┐я─я┐ п©п╬п╩я┐я┤п╣п╫п╦я▐ п╢п╟п╫п╫я▀я┘ п╢п╩я▐ я┌п╟п╠п╩п╦я├я▀
 table.configure('command',[proc {|r,c,i,s| q(r,c,i,s)},'%r %c %i %s'])
 table.configure("cols"=>2,"rows"=>$ds.length,"width"=>400,"bg"=>"white")
 table.pack

 Tk.mainloop
-------------- next part --------------
# tktable.rb - tktable wrapper

# by Ferenc Engard -- ferenc на engard.hu
# TkTable (http://tktable.sourceforge.net/) wrapper.

# Parameter handling is based on TkEntry solution,

require 'tk'
#~ trap 0, proc { sleep 0.1 }


# Warning: do not try to pass command parameters (like -command) to the constructor!

# Use configure() instead. Example:

# table.configure('command',[proc {|r,c| myfun(r,c)},'%r %c'])

class TkTable < TkWindow
  include Scrollable

  include TkPackage

  WidgetClassName = 'Table'.freeze
  WidgetClassNames[WidgetClassName] = self
  def self.to_eval
    WidgetClassName
  end

  # callbacks for click and dblclick events, separately for the title row(s) and the others.
  # pr: is a proc
  # Params for onClick and onDblClick's proc:
  #  row, col. The row is counted from from 0, without the title row(s). col is counted from 0.
  # Params for onTitleClick and onTitleDblClick's proc:
  #  col. counted from 0.
  def onClick=(pr) @clickHandler=pr end
  def onDblClick=(pr) @dblclickHandler=pr end
  def onTitleClick=(pr) @titleclickHandler=pr end
  def onTitleDblClick=(pr) @titledblclickHandler=pr end

  def internalClick(x,y,evnt)
    #~ debug "internalClick(#{x},#{y},#{evnt})"
    row,col=index("@#{x},#{y}").split(',').collect{|i| i.to_i}
    #~ debug "row==#{row}, col==#{col}"
    prt,pr = evnt=='click' ? [@titleclickHandler, на clickHandler] : [@titledblclickHandler, на dblclickHandler]
    if row<cget('titlerows').to_i
      prt.call(col) if prt
    else
      pr.call(row-cget('titlerows'),col) if pr
    end
  end
  
  def tagconfigure(tag,keys)
    tk_call(path,'tag','configure',tag,*hash_kv(keys))
  end
  
  def tagcol(tag,cols)
    tk_call(path,'tag','col',tag,*cols)
  end
  def tagrow(tag,rows)
    tk_call(path,'tag','row',tag,*rows)
  end
  def tagcell(tag,cells)
    tk_call(path,'tag','cell',tag,*cells)
  end
  
  def setRow(row,values)
    tk_call(path,"set","row","#{row},0",values)
  end
  
  # rowcol: 'row' or 'col'
  def index(ind='active',rowcol=nil)
    begin
      return tk_call(path,"index",ind,rowcol) if rowcol
      return tk_call(path,"index",ind)
    rescue # if there is no active cell
      raiseDebug("TkTable#index error: #{$!}")
      return nil
    end
  end
  
  def clear(option,first=nil,last=nil)
    case option
      when :cache, "cache"
        tk_call(path,"clear","cache")
    end
  end
  def clearCache() clear(:cache) end
  
  def activate(cell)
    tk_call(path,"activate",cell)
  end

  # Not-so-interesting internal stuff -------------------------------------------------------------------


  # A class whats to_eval function returns 'rb_out <id> %d %i ...'

  # It can be the value of the command attributes of tktable (-command, -browsecommand ...)
  class TableCommand
    include TkComm

    class TableCommandArgs
      def initialize(c,i,r,s,ss,ww)

        # possible command callback attributes:

        # browsecommand, coltagcommand, rowtagcommand, command, selectioncommand,

        # validatecommand

        @maxColumns=c # SelectionCommand

        @column=c # other commands

        @numRows=r # SelectionCommand

        @row=r # other commands

        @set=(i==1) # Command

        @numCells=i # SelectionCommand

        @curPos=i # other commands

        @value=s # ValidateCommand

        @defValue=s # SelectionCommand

        @lastActive=s # BrowseCommand

        @currentValue=s # Command/set

        @newValue=ss # ValidateCommand

        @newActive=ss # BrowseCommand

        @widget=ww

      end

      attr_reader :maxColumns, :column, :numRows, :row,

      :numCells, :curPos, :value, :defValue, :lastActive,

      :currentValue, :newValue, :newActive, :widget

      def set?() @set; end
      def get?() !@set; end
    end


    # Constructor.

    # cmd: proc to execute. If cmd is not given, it associates an empty proc to the callback.

    # args: if provided (e.g. "%r %c") then cmd gets the requested 

    # substitution variables (e.g. row and column) as parameters.

    # If args not provided, then cmd gets a TableCommandArgs parameter.
    def initialize(cmd = Proc.new, args=nil)
      if args
        @id = install_cmd(proc{|*arg|
          TkUtil.eval_cmd cmd, *arg
        }) + " " + args
      else
        @id = install_cmd(proc{|arg|
          TkUtil.eval_cmd cmd, TableCommandArgs.new(*arg)
        }) + ' %d %i %s %v %P %S %V %W'
      end
    end

    def to_eval
      @id
    end
  end # TableCommand


  def create_self(keys)

    require "Tktable"
    if keys and keys != None
      tk_call 'table', @path, *hash_kv(keys)
    else
      tk_call 'table', @path
    end
    bind('Button-1',proc {|x,y,e| internalClick(x,y,e)},'%x %y click')
    bind('Double-1',proc {|x,y,e| internalClick(x,y,e)},'%x %y dblclick')
  end


  # Input example 1: [aProc, '%r', '%c'] -> output: TableCommand.new(aProc, "%r %c")

  # Input example 2: aProc -> output: TableCommand.new(aProc)

  def confTransform(subj)

      if subj.kind_of? Array
        cmd, *args = subj
        subj = TableCommand.new(cmd, args.join(' '))
      elsif subj.kind_of? Proc
        subj = TableCommand.new(subj)
      end
  end
  private :confTransform



  # Possible configuration methods for command attributes:

  # configure({"command"=>[proc{|r,c|myfun(r,c)}, '%r', '%c'], "cols"=>10, ...})

  def configure(slot, value=None)

    cmdargs=['command','browsecommand','coltagcommand',

      'rowtagcommand','selectioncommand','validatecommand']
    if slot.kind_of? Hash

      cmdargs.each {|cmd|

        confTransform(slot[cmd])

      }

      super(slot)
    else
      if (cmdargs.include?(slot))
        if value.kind_of? Array
          cmd, *args = value
          value = TableCommand.new(cmd, args.join(' '))
        elsif value.kind_of? Proc
          value = TableCommand.new(value)
        end
      end
      super(slot, value)
    end
  end
end # TkTable







-------------- next part --------------
# Global initialisation file for SciTE
# For Linux, place in $prefix/share/scite
# For Windows, place in same directory as SciTE.EXE (or Sc1.EXE)
# Documentation at http://www.scintilla.org/SciTEDoc.html

# Globals

# Window sizes and visibility
if PLAT_WIN
	position.left=5
	position.top=22
if PLAT_GTK
	position.left=5
	position.top=22
position.width=576
position.height=740
position.tile=1
#full.screen.hides.menu=1
minimize.to.tray=0
split.vertical=0
output.horizontal.size=200
output.vertical.size=60
#horizontal.scrollbar=0
#horizontal.scroll.width=10000
#output.horizontal.scrollbar=0
#output.horizontal.scroll.width=10000
#output.scroll=0
#end.at.last.line=0
tabbar.visible=1
#tabbar.hide.one=1
#tabbar.multiline=1
toolbar.visible=1
#undo.redo.lazy=1
statusbar.visible=1
#fileselector.width=800
#fileselector.height=600
magnification=-1
output.magnification=-1

# Sizes and visibility in edit pane
# Set line.numbers to 4 if you want to see them
line.numbers=4
margin.width=16
fold.margin.width=16
#fold.margin.colour=#FF0000
#fold.margin.highlight.colour=#0000FF
#blank.margin.left=4
#blank.margin.right=4
buffered.draw=1
#two.phase.draw=0
use.palette=0

# Element styles
#view.eol=1
#control.char.symbol=.
caret.period=500
view.whitespace=0
view.indentation.whitespace=1
view.indentation.guides=1
highlight.indentation.guides=1
#caret.fore=#FF0000
#caret.width=2
#caret.line.back=#FFFED8
#calltip.back=#FFF0FE
edge.column=200
edge.mode=0
edge.colour=#C0DCC0
braces.check=1
braces.sloppy=1
#selection.fore=#006000
# DADADA used as background because it yields standard silver C0C0C0
# on low colour displays and a reasonable light grey on higher bit depths
selection.back=#DADADA
#whitespace.fore=#FF0000
#whitespace.back=#FFF0F0
#error.marker.fore=#0000A0
#error.marker.back=#DADAFF
#bookmark.fore=#808000
#bookmark.back=#FFFFA0
#use.monospaced=1

# Checking
are.you.sure=1
#are.you.sure.for.build=1
#quit.on.close.last=1
#load.on.activate=1
#save.on.deactivate=1
#are.you.sure.on.reload=1
#reload.preserves.undo=1
#check.if.already.open=1
default.file.ext=.xml
#title.full.path=1
#title.show.buffers=1
#save.recent=1
#save.session=1
#open.dialog.in.file.directory=1
#strip.trailing.spaces=1
#ensure.final.line.end=1
#ensure.consistent.line.ends=1
#save.deletes.first=1
#buffers=10
buffers.zorder.switching=1
#api.*.cxx=d:\api\w.api
#win95.death.delay=1000
#translation.missing=***
#read.only=1

# Indentation
tabsize=8
indent.size=8
use.tabs=1
indent.automatic=1
indent.opening=0
indent.closing=0
#tab.indents=0
#backspace.unindents=0
#wrap=1
#cache.layout=3
#output.wrap=1
#output.cache.layout=3

# Folding
# enable folding, and show lines below when collapsed.
fold=1
fold.compact=1
fold.flags=16
fold.symbols=1
#fold.on.open=1

# Find and Replace
#escapes.in.find.replace=1
if PLAT_WIN
	find.command=fgrep -G -n $(find.what) $(find.files)
#find.input=$(find.what)
if PLAT_GTK
	find.command=grep --line-number "$(find.what)" $(find.files)
find.files=*.c *.cxx *.h
#find.replace.matchcase=1
#find.replace.escapes=1
#find.replace.regexp=1
#find.replace.regexp.posix=1
#find.replace.wrap=0
#find.replacewith.focus=0

# Behaviour
#eol.mode=LF
#eol.auto=1
clear.before.execute=0
#vc.home.key=1
#wrap.aware.home.end.keys=1
#autocompleteword.automatic=1
#autocomplete.choose.single=1
caret.policy.xslop=1
caret.policy.width=20
caret.policy.xstrict=0
caret.policy.xeven=0
caret.policy.xjumps=0
caret.policy.yslop=1
caret.policy.lines=1
caret.policy.ystrict=1
caret.policy.yeven=1
caret.policy.yjumps=0
#visible.policy.strict=1
#visible.policy.slop=1
#visible.policy.lines=4
#time.commands=1

# Status Bar
statusbar.number=4
statusbar.text.1=\
li=$(LineNumber) co=$(ColumnNumber) $(OverType) ($(EOLMode)) $(FileAttr)
statusbar.text.2=\
$(BufferLength) chars in $(NbOfLines) lines. Sel: $(SelLength) chars.
statusbar.text.3=\
Now is: Date=$(CurrentDate) Time=$(CurrentTime)
statusbar.text.4=\
$(FileNameExt) : $(FileDate) ≈ $(FileTime) | $(FileAttr)

if PLAT_WIN
	command.scite.help="file://$(SciteDefaultHome)\SciTEDoc.html"
	command.scite.help.subsystem=2
if PLAT_GTK
	command.print.*=a2ps $(FileNameExt)
	command.scite.help=netscape "file://$(SciteDefaultHome)/SciTEDoc.html"

# Internationalisation
# Japanese input code page 932 and ShiftJIS character set 128
#code.page=932
#character.set=128
# Unicode
code.page=65001
#code.page=0
character.set=204
# Required for Unicode to work on GTK+:
LC_CTYPE=en_US.UTF-8

# Export
#export.keep.ext=1
export.html.wysiwyg=1
#export.html.tabs=1
#export.html.folding=1
export.html.styleused=1
#export.html.title.fullpath=1
#export.rtf.tabs=1
#export.rtf.font.face=Arial
#export.rtf.font.size=9
#export.rtf.tabsize=8

# Define values for use in the imported properties files
chars.alpha=abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ
chars.numeric=0123456789
#chars.accented=┼ ▄°÷ЪюЮаАбБцЦдДеЕфФгГхХиИйЙкКлЛмМнНоОпПяЯрРсСтТуУжьЬыЫзЗшШэЭщЩчЧъЖ
# This is a better set for Russian:
chars.accented=юЮаАбБцЦдДеЕ╗╦фФгГхХиИйЙкКлЛмМнНоОпПяЯрРсСтТуУжЖвВьЬыЫзЗшШэЭщЩчЧъЪ

# The open.filter setting is only used on Windows where the file selector has a menu of filters to apply
# to the types of files seen when opening.
# There is a limit (possibly 256 characters) to the length of a filter,
# so not all source extensions can be in this setting.
source.files=*.asm;*.c;*.cc;*.cpp;*.cxx;*.cs;*.h;*.hh;*.hxx;*.hpp;\
*.idl;*.odl;*.rc;*.rc2;*.dlg;*.def;\
*.vb;*.vbs;*.bas;*.frm;*.cls;*.ctl;\
*.java;*.js;*.py;*.pl;*.rb;*.cgi;*.lua;*.conf;\
make*;*.mak;\
*.properties;*.html;*.xml;*.iface;*.bat;*.e

open.filter=\
All Source|$(source.files)|\
All Files (*.*)|*.*|\
$(filter.ada)\
$(filter.conf)\
$(filter.asm)\
$(filter.ave)\
$(filter.baan)\
$(filter.cpp)\
$(filter.css)\
$(filter.eiffel)\
$(filter.fortran)\
$(filter.idl)\
$(filter.java)\
$(filter.js)\
$(filter.latex)\
$(filter.lout)\
$(filter.lua)\
$(filter.matlab)\
$(filter.mmixal)\
$(filter.nncrontab)\
$(filter.nsis)\
$(filter.pascal)\
$(filter.perl)\
$(filter.php)\
$(filter.pov)\
$(filter.properties)\
$(filter.ps)\
$(filter.python)\
$(filter.ruby)\
$(filter.sql)\
$(filter.tcl)\
$(filter.text)\
$(filter.vb)\
$(filter.web)\
$(filter.yaml)

# Give symbolic names to the set of fonts used in the standard styles.
if PLAT_WIN
	font.base=font:Verdana,size:10
	font.small=font:Verdana,size:8
	font.comment=font:Comic Sans MS,size:9
	font.code.comment.box=$(font.comment)
	font.code.comment.line=$(font.comment)
	font.code.comment.doc=$(font.comment)
	font.text=font:Times New Roman,size:11
	font.text.comment=font:Verdana,size:9
	font.embedded.base=font:Verdana,size:9
	font.embedded.comment=font:Comic Sans MS,size:8
	font.monospace=font:Courier New,size:10
	font.vbs=font:Lucida Sans Unicode,size:10
if PLAT_GTK
	font.base=font:lucidatypewriter,size:12
	font.small=font:lucidatypewriter,size:10
	font.comment=font:new century schoolbook,size:12
	font.code.comment.box=$(font.comment)
	font.code.comment.line=$(font.comment)
	font.code.comment.doc=$(font.comment)
	font.text=font:times,size:14
	font.text.comment=font:lucidatypewriter,size:10
	font.embedded.base=font:lucidatypewriter,size:12
	font.embedded.comment=font:lucidatypewriter,size:12
	font.monospace=font:courier,size:12
	font.vbs=font:new century schoolbook,size:12
font.js=$(font.comment)

# Give symbolic names to the set of colours used in the standard styles.
colour.code.comment.box=fore:#007F00
colour.code.comment.line=fore:#007F00
colour.code.comment.doc=fore:#3F703F
colour.text.comment=fore:#0000FF,back:#D0F0D0
colour.other.comment=fore:#007F00
colour.embedded.comment=back:#E0EEFF
colour.embedded.js=back:#F0F0FF
colour.notused=back:#FF0000

colour.number=fore:#007F7F
colour.keyword=fore:#00007F
colour.string=fore:#7F007F
colour.char=fore:#7F007F
colour.operator=fore:#000000
colour.preproc=fore:#7F7F00
colour.error=fore:#FFFF00,back:#FF0000

# Global default styles for all languages
# Default
style.*.32=$(font.base)
# Line number
style.*.33=back:#C0C0C0,$(font.base)
# Brace highlight
style.*.34=fore:#0000FF,bold
# Brace incomplete highlight
style.*.35=fore:#FF0000,bold
# Control characters
style.*.36=
# Indentation guides
style.*.37=fore:#C0C0C0,back:#FFFFFF

# Printing - only works on Windows
if PLAT_WIN
	#print.colour.mode=1
	print.magnification=-1
	# Setup: left, right, top, bottom margins, in local units:
	# hundredths of millimeters or thousandths of inches
	print.margins=1500,1000,1000,1500
	# Header/footer:
	# && = &; &p = current page
	# &f = file name; &F = full path
	# &d = file date; &D = current date
	# &t = file time; &T = full time
	print.header.format=$(FileNameExt) ≈ Printed on $(CurrentDate), $(CurrentTime) ≈ Page $(CurrentPage)
	print.footer.format=$(FilePath) ≈ File date: $(FileDate) ≈ File time: $(FileTime)
	# Header/footer style
	print.header.style=font:Arial,size:12,bold
	print.footer.style=font:Arial Narrow,size:10,italics

# Warnings - only works on Windows and needs to be pointed at files on machine
#if PLAT_WIN
#	warning.findwrapped=100,E:\Windows\Media\SFX\Boing.wav
#	warning.notfound=0,Effect.wav
#	warning.wrongfile=0,Glass.wav
#	warning.executeok=0,Fanfare.wav
#	warning.executeko=100,GlassBreak.wav
#	warning.nootherbookmark=100,Boing2.wav

# Define the Lexer menu,
# Each item contains three parts: menu string | file extension | key
# The only keys allowed currently are based on F-keys and alphabetic keys and look like
# [Ctrl+][Shift+][Fn|a] such as F12 or Ctrl+Shift+D.
# A '&' may be placed before a letter to be used as an accelerator. This does not work on GTK+.
menu.language=\
Text|txt|Shift+F11|\
Ada|ads||\
Apache Confi&g|conf||\
Assembler|asm||\
Avenue|ave||\
Baan|bc||\
&Batch|bat||\
Bullant|ant||\
&C / C++|c||\
C&#|cs||\
CSS|css||\
&Difference|diff||\
&Eiffel|e||\
&Errorlist|err||\
&Fortran|f90||\
H&ypertext|html|F12|\
&Java|java||\
Java&Script|js||\
La&TeX|tex||\
Lisp|lisp||\
Lout|lt||\
Lu&a|lua||\
Matlab|m||\
&Makefile|mak|Ctrl+Shift+F11|\
MMIXAL|mms||\
&nnCron crontab|tab||\
NSIS|nsis||\
Pascal|pas||\
Pe&rl|pl||\
P&HP|php||\
P&LSQL|spec||\
&Properties|properties||\
P&ostScript|ps||\
P&OV-Ray SDL|pov||\
Pytho&n|py||\
Reso&urce|rc||\
Ruby|rb||\
Shell|sh||\
S&QL|sql||\
&TCL|tcl||\
&VB|vb||\
VBScr&ipt|vbs||\
&XML|xml|Shift+F12|\
&YAML|yaml||

# User defined key commands
user.shortcuts=\
Ctrl+PageUp|IDM_PREVFILE|\
Ctrl+PageDown|IDM_NEXTFILE|
#KeypadPlus|IDM_EXPAND|\
#KeypadMinus|IDM_BLOCK_COMMENT|

# Import all the language specific properties files
import ada
import asm
import ave
import baan
import bullant
import conf
import cpp
import css
import eiffel
import escript
import fortran
import html
import latex
import lisp
import lout
import lua
import matlab
import mmixal
import nncrontab
import nsis
import others
import pascal
import perl
import pov
import ps
import python
import ruby
import scriptol
import sql
import tcl
import vb
import yaml








Подробная информация о списке рассылки Ruby