summaryrefslogtreecommitdiff
path: root/spec/ruby/language/predefined/fixtures/data2.rb
AgeCommit message (Collapse)Author
2018-03-04Update to ruby/spec@c1b568beregon
git-svn-id: svn+ssh://ci.ruby-lang.org/ruby/trunk@62656 b2dd03c8-39d4-4d8f-98ff-823fe69b080e
2017-09-20Move spec/rubyspec to spec/ruby for consistencyeregon
* Other ruby implementations use the spec/ruby directory. [Misc #13792] [ruby-core:82287] git-svn-id: svn+ssh://ci.ruby-lang.org/ruby/trunk@59979 b2dd03c8-39d4-4d8f-98ff-823fe69b080e
0.0%;'/> -rw-r--r--LEGAL21
-rw-r--r--Makefile.in310
-rw-r--r--README.EXT76
-rw-r--r--README.EXT.ja81
-rw-r--r--array.c49
-rw-r--r--bcc32/Makefile.sub381
-rw-r--r--bcc32/README.bcc3214
-rw-r--r--bcc32/configure.bat68
-rw-r--r--bcc32/setup.mak44
-rw-r--r--bignum.c77
-rwxr-xr-xbin/erb156
-rw-r--r--bin/irb4
-rw-r--r--class.c5
-rw-r--r--common.mk298
-rw-r--r--configure.in150
-rw-r--r--cygwin/GNUmakefile.in17
-rw-r--r--defines.h15
-rw-r--r--dir.c288
-rw-r--r--dln.c21
-rw-r--r--dmydln.c2
-rw-r--r--doc/irb/irb.rd.ja8
-rw-r--r--enum.c170
-rw-r--r--error.c18
-rw-r--r--eval.c789
-rw-r--r--ext/.document2
-rw-r--r--ext/Win32API/Win32API.c11
-rw-r--r--ext/Win32API/extconf.rb1
-rw-r--r--ext/Win32API/lib/win32/resolv.rb4
-rw-r--r--ext/bigdecimal/bigdecimal.c60
-rw-r--r--ext/bigdecimal/lib/bigdecimal/newton.rb4
-rw-r--r--ext/bigdecimal/lib/bigdecimal/nlsolve.rb38
-rw-r--r--ext/bigdecimal/sample/linear.rb2
-rw-r--r--ext/bigdecimal/sample/nlsolve.rb2
-rw-r--r--ext/curses/curses.c125
-rw-r--r--ext/curses/extconf.rb2
-rw-r--r--ext/curses/view.rb2
-rw-r--r--ext/dbm/dbm.c106
-rw-r--r--ext/dbm/testdbm.rb593
-rw-r--r--ext/digest/md5/md5ossl.h1
-rw-r--r--ext/digest/rmd160/rmd160ossl.h1
-rw-r--r--ext/digest/sha1/sha1ossl.h1
-rw-r--r--ext/digest/sha2/extconf.rb8
-rw-r--r--ext/dl/dl.c18
-rw-r--r--ext/dl/handle.c6
-rw-r--r--ext/dl/lib/dl/import.rb30
-rw-r--r--ext/dl/lib/dl/struct.rb9
-rw-r--r--ext/dl/lib/dl/types.rb263
-rw-r--r--ext/dl/sym.c4
-rw-r--r--ext/enumerator/enumerator.c103
-rw-r--r--ext/etc/etc.c147
-rw-r--r--ext/etc/extconf.rb13
-rw-r--r--ext/extmk.rb329
-rw-r--r--ext/fcntl/fcntl.c75
-rw-r--r--ext/gdbm/gdbm.c120
-rw-r--r--ext/gdbm/testgdbm.rb663
-rw-r--r--ext/iconv/charset_alias.rb83
-rw-r--r--ext/iconv/extconf.rb16
-rw-r--r--ext/iconv/iconv.c106
-rw-r--r--ext/io/wait/extconf.rb7
-rw-r--r--ext/io/wait/lib/nonblock.rb2
-rw-r--r--ext/io/wait/wait.c26
-rw-r--r--ext/nkf/lib/kconv.rb12
-rw-r--r--ext/nkf/nkf-utf8/nkf.c1202
-rw-r--r--ext/nkf/nkf-utf8/utf8tbl.c60
-rw-r--r--ext/nkf/nkf.c23
-rw-r--r--ext/nkf/test.rb446
-rw-r--r--ext/openssl/extconf.rb29
-rw-r--r--ext/openssl/lib/net/https.rb188
-rw-r--r--ext/openssl/lib/net/protocols.rb56
-rw-r--r--ext/openssl/lib/net/telnets.rb2
-rw-r--r--ext/openssl/lib/openssl/buffering.rb73
-rw-r--r--ext/openssl/lib/openssl/cipher.rb2
-rw-r--r--ext/openssl/lib/openssl/digest.rb9
-rw-r--r--ext/openssl/lib/openssl/ssl.rb41
-rw-r--r--ext/openssl/lib/openssl/x509.rb89
-rw-r--r--ext/openssl/openssl_missing.c5
-rw-r--r--ext/openssl/openssl_missing.h4
-rw-r--r--ext/openssl/ossl.c32
-rw-r--r--ext/openssl/ossl.h2
-rw-r--r--ext/openssl/ossl_asn1.c36
-rw-r--r--ext/openssl/ossl_asn1.h5
-rw-r--r--ext/openssl/ossl_bio.c3
-rw-r--r--ext/openssl/ossl_bn.c22
-rw-r--r--ext/openssl/ossl_cipher.c23
-rw-r--r--ext/openssl/ossl_config.c14
-rw-r--r--ext/openssl/ossl_digest.c10
-rw-r--r--ext/openssl/ossl_engine.c86
-rw-r--r--ext/openssl/ossl_hmac.c4
-rw-r--r--ext/openssl/ossl_ns_spki.c34
-rw-r--r--ext/openssl/ossl_ocsp.c30
-rw-r--r--ext/openssl/ossl_pkcs12.h2
-rw-r--r--ext/openssl/ossl_pkcs7.c183
-rw-r--r--ext/openssl/ossl_pkcs7.h3
-rw-r--r--ext/openssl/ossl_pkey.c21
-rw-r--r--ext/openssl/ossl_pkey.h15
-rw-r--r--ext/openssl/ossl_pkey_dh.c77
-rw-r--r--ext/openssl/ossl_pkey_dsa.c12
-rw-r--r--ext/openssl/ossl_pkey_rsa.c80
-rw-r--r--ext/openssl/ossl_ssl.c258
-rw-r--r--ext/openssl/ossl_x509attr.c4
-rw-r--r--ext/openssl/ossl_x509cert.c15
-rw-r--r--ext/openssl/ossl_x509crl.c12
-rw-r--r--ext/openssl/ossl_x509ext.c7
-rw-r--r--ext/openssl/ossl_x509name.c65
-rw-r--r--ext/openssl/ossl_x509req.c4
-rw-r--r--ext/openssl/ossl_x509revoked.c4
-rw-r--r--ext/openssl/ossl_x509store.c80
-rw-r--r--ext/pty/pty.c8
-rw-r--r--ext/readline/extconf.rb69
-rw-r--r--ext/readline/readline.c322
-rw-r--r--ext/sdbm/_sdbm.c2
-rw-r--r--ext/sdbm/init.c101
-rw-r--r--ext/sdbm/testsdbm.rb (renamed from test/sdbm/test_sdbm.rb)259
-rw-r--r--ext/socket/extconf.rb215
-rw-r--r--ext/socket/getaddrinfo.c7
-rw-r--r--ext/socket/socket.c504
-rw-r--r--ext/stringio/stringio.c405
-rw-r--r--ext/strscan/strscan.c35
-rw-r--r--ext/syck/bytecode.c235
-rw-r--r--ext/syck/emitter.c1067
-rw-r--r--ext/syck/gram.c1174
-rw-r--r--ext/syck/gram.h24
-rw-r--r--ext/syck/handler.c18
-rw-r--r--ext/syck/implicit.c235
-rw-r--r--ext/syck/node.c71
-rw-r--r--ext/syck/rubyext.c2059
-rw-r--r--ext/syck/syck.c18
-rw-r--r--ext/syck/syck.h107
-rw-r--r--ext/syck/token.c1427
-rw-r--r--ext/syck/yaml2byte.c17
-rw-r--r--ext/tcltklib/MANUAL.eng35
-rw-r--r--ext/tcltklib/MANUAL.euc36
-rw-r--r--ext/tcltklib/README.1st19
-rw-r--r--ext/tcltklib/depend2
-rw-r--r--ext/tcltklib/extconf.rb112
-rw-r--r--ext/tcltklib/sample/sample1.rb30
-rw-r--r--ext/tcltklib/sample/sample2.rb12
-rw-r--r--ext/tcltklib/stubs.c475
-rw-r--r--ext/tcltklib/stubs.h33
-rw-r--r--ext/tcltklib/tcltklib.c4885
-rw-r--r--ext/tk/ChangeLog.tkextlib775
-rw-r--r--ext/tk/README.1st31
-rw-r--r--ext/tk/lib/multi-tk.rb635
-rw-r--r--ext/tk/lib/remote-tk.rb56
-rw-r--r--ext/tk/lib/tk.rb868
-rw-r--r--ext/tk/lib/tk/autoload.rb3
-rw-r--r--ext/tk/lib/tk/bindtag.rb4
-rw-r--r--ext/tk/lib/tk/canvas.rb78
-rw-r--r--ext/tk/lib/tk/canvastag.rb92
-rw-r--r--ext/tk/lib/tk/clock.rb16
-rw-r--r--ext/tk/lib/tk/composite.rb12
-rw-r--r--ext/tk/lib/tk/console.rb25
-rw-r--r--ext/tk/lib/tk/dialog.rb123
-rw-r--r--ext/tk/lib/tk/encodedstr.rb8
-rw-r--r--ext/tk/lib/tk/entry.rb11
-rw-r--r--ext/tk/lib/tk/event.rb350
-rw-r--r--ext/tk/lib/tk/font.rb1115
-rw-r--r--ext/tk/lib/tk/frame.rb17
-rw-r--r--ext/tk/lib/tk/grid.rb17
-rw-r--r--ext/tk/lib/tk/image.rb69
-rw-r--r--ext/tk/lib/tk/itemconfig.rb314
-rw-r--r--ext/tk/lib/tk/itemfont.rb30
-rw-r--r--ext/tk/lib/tk/kinput.rb28
-rw-r--r--ext/tk/lib/tk/label.rb4
-rw-r--r--ext/tk/lib/tk/labelframe.rb5
-rw-r--r--ext/tk/lib/tk/listbox.rb12
-rw-r--r--ext/tk/lib/tk/macpkg.rb5
-rw-r--r--ext/tk/lib/tk/menu.rb120
-rw-r--r--ext/tk/lib/tk/menuspec.rb12
-rw-r--r--ext/tk/lib/tk/mngfocus.rb8
-rw-r--r--ext/tk/lib/tk/msgcat.rb5
-rw-r--r--ext/tk/lib/tk/namespace.rb118
-rw-r--r--ext/tk/lib/tk/optiondb.rb9
-rw-r--r--ext/tk/lib/tk/pack.rb6
-rw-r--r--ext/tk/lib/tk/palette.rb9
-rw-r--r--ext/tk/lib/tk/panedwindow.rb52
-rw-r--r--ext/tk/lib/tk/radiobutton.rb38
-rw-r--r--ext/tk/lib/tk/root.rb24
-rw-r--r--ext/tk/lib/tk/scale.rb5
-rw-r--r--ext/tk/lib/tk/spinbox.rb60
-rw-r--r--ext/tk/lib/tk/tagfont.rb12
-rw-r--r--ext/tk/lib/tk/text.rb277
-rw-r--r--ext/tk/lib/tk/textimage.rb18
-rw-r--r--ext/tk/lib/tk/textmark.rb49
-rw-r--r--ext/tk/lib/tk/texttag.rb78
-rw-r--r--ext/tk/lib/tk/textwindow.rb26
-rw-r--r--ext/tk/lib/tk/timer.rb180
-rw-r--r--ext/tk/lib/tk/toplevel.rb39
-rw-r--r--ext/tk/lib/tk/validation.rb11
-rw-r--r--ext/tk/lib/tk/variable.rb829
-rw-r--r--ext/tk/lib/tk/virtevent.rb3
-rw-r--r--ext/tk/lib/tk/winfo.rb191
-rw-r--r--ext/tk/lib/tk/winpkg.rb5
-rw-r--r--ext/tk/lib/tk/wm.rb98
-rw-r--r--ext/tk/lib/tk/xim.rb40
-rw-r--r--ext/tk/lib/tkextlib/ICONS/icons.rb11
-rw-r--r--ext/tk/lib/tkextlib/SUPPORT_STATUS142
-rw-r--r--ext/tk/lib/tkextlib/blt.rb187
-rw-r--r--ext/tk/lib/tkextlib/blt/barchart.rb79
-rw-r--r--ext/tk/lib/tkextlib/blt/bitmap.rb99
-rw-r--r--ext/tk/lib/tkextlib/blt/busy.rb82
-rw-r--r--ext/tk/lib/tkextlib/blt/component.rb1835
-rw-r--r--ext/tk/lib/tkextlib/blt/container.rb28
-rw-r--r--ext/tk/lib/tkextlib/blt/cutbuffer.rb23
-rw-r--r--ext/tk/lib/tkextlib/blt/dragdrop.rb214
-rw-r--r--ext/tk/lib/tkextlib/blt/eps.rb32
-rw-r--r--ext/tk/lib/tkextlib/blt/graph.rb67
-rw-r--r--ext/tk/lib/tkextlib/blt/htext.rb110
-rw-r--r--ext/tk/lib/tkextlib/blt/setup.rb8
-rw-r--r--ext/tk/lib/tkextlib/blt/spline.rb23
-rw-r--r--ext/tk/lib/tkextlib/blt/stripchart.rb74
-rw-r--r--ext/tk/lib/tkextlib/blt/table.rb344
-rw-r--r--ext/tk/lib/tkextlib/blt/tabnotebook.rb21
-rw-r--r--ext/tk/lib/tkextlib/blt/tabset.rb401
-rw-r--r--ext/tk/lib/tkextlib/blt/ted.rb62
-rw-r--r--ext/tk/lib/tkextlib/blt/tile.rb21
-rw-r--r--ext/tk/lib/tkextlib/blt/tile/button.rb16
-rw-r--r--ext/tk/lib/tkextlib/blt/tile/checkbutton.rb17
-rw-r--r--ext/tk/lib/tkextlib/blt/tile/frame.rb16
-rw-r--r--ext/tk/lib/tkextlib/blt/tile/label.rb16
-rw-r--r--ext/tk/lib/tkextlib/blt/tile/radiobutton.rb17
-rw-r--r--ext/tk/lib/tkextlib/blt/tile/scrollbar.rb16
-rw-r--r--ext/tk/lib/tkextlib/blt/tile/toplevel.rb16
-rw-r--r--ext/tk/lib/tkextlib/blt/tree.rb923
-rw-r--r--ext/tk/lib/tkextlib/blt/treeview.rb1146
-rw-r--r--ext/tk/lib/tkextlib/blt/unix_dnd.rb129
-rw-r--r--ext/tk/lib/tkextlib/blt/vector.rb243
-rw-r--r--ext/tk/lib/tkextlib/blt/watch.rb142
-rw-r--r--ext/tk/lib/tkextlib/blt/win_printer.rb61
-rw-r--r--ext/tk/lib/tkextlib/blt/winop.rb107
-rw-r--r--ext/tk/lib/tkextlib/bwidget.rb5
-rw-r--r--ext/tk/lib/tkextlib/bwidget/button.rb10
-rw-r--r--ext/tk/lib/tkextlib/bwidget/buttonbox.rb5
-rw-r--r--ext/tk/lib/tkextlib/bwidget/dialog.rb10
-rw-r--r--ext/tk/lib/tkextlib/bwidget/dynamichelp.rb5
-rw-r--r--ext/tk/lib/tkextlib/bwidget/entry.rb15
-rw-r--r--ext/tk/lib/tkextlib/bwidget/label.rb15
-rw-r--r--ext/tk/lib/tkextlib/bwidget/labelentry.rb43
-rw-r--r--ext/tk/lib/tkextlib/bwidget/labelframe.rb16
-rw-r--r--ext/tk/lib/tkextlib/bwidget/listbox.rb65
-rw-r--r--ext/tk/lib/tkextlib/bwidget/mainframe.rb19
-rw-r--r--ext/tk/lib/tkextlib/bwidget/messagedlg.rb11
-rw-r--r--ext/tk/lib/tkextlib/bwidget/notebook.rb48
-rw-r--r--ext/tk/lib/tkextlib/bwidget/panelframe.rb51
-rw-r--r--ext/tk/lib/tkextlib/bwidget/passwddlg.rb17
-rw-r--r--ext/tk/lib/tkextlib/bwidget/scrollview.rb5
-rw-r--r--ext/tk/lib/tkextlib/bwidget/selectfont.rb6
-rw-r--r--ext/tk/lib/tkextlib/bwidget/spinbox.rb48
-rw-r--r--ext/tk/lib/tkextlib/bwidget/statusbar.rb46
-rw-r--r--ext/tk/lib/tkextlib/bwidget/tree.rb76
-rw-r--r--ext/tk/lib/tkextlib/bwidget/widget.rb2
-rw-r--r--ext/tk/lib/tkextlib/itcl/incr_tcl.rb5
-rw-r--r--ext/tk/lib/tkextlib/itk/incr_tk.rb56
-rw-r--r--ext/tk/lib/tkextlib/iwidgets.rb5
-rw-r--r--ext/tk/lib/tkextlib/iwidgets/buttonbox.rb5
-rw-r--r--ext/tk/lib/tkextlib/iwidgets/calendar.rb20
-rw-r--r--ext/tk/lib/tkextlib/iwidgets/canvasprintbox.rb10
-rw-r--r--ext/tk/lib/tkextlib/iwidgets/checkbox.rb5
-rw-r--r--ext/tk/lib/tkextlib/iwidgets/combobox.rb5
-rw-r--r--ext/tk/lib/tkextlib/iwidgets/datefield.rb15
-rw-r--r--ext/tk/lib/tkextlib/iwidgets/dialogshell.rb5
-rw-r--r--ext/tk/lib/tkextlib/iwidgets/disjointlistbox.rb5
-rw-r--r--ext/tk/lib/tkextlib/iwidgets/entryfield.rb7
-rw-r--r--ext/tk/lib/tkextlib/iwidgets/extbutton.rb10
-rw-r--r--ext/tk/lib/tkextlib/iwidgets/extfileselectionbox.rb13
-rw-r--r--ext/tk/lib/tkextlib/iwidgets/feedback.rb5
-rw-r--r--ext/tk/lib/tkextlib/iwidgets/fileselectionbox.rb13
-rw-r--r--ext/tk/lib/tkextlib/iwidgets/finddialog.rb13
-rw-r--r--ext/tk/lib/tkextlib/iwidgets/hierarchy.rb23
-rw-r--r--ext/tk/lib/tkextlib/iwidgets/hyperhelp.rb10
-rw-r--r--ext/tk/lib/tkextlib/iwidgets/labeledframe.rb15
-rw-r--r--ext/tk/lib/tkextlib/iwidgets/labeledwidget.rb15
-rw-r--r--ext/tk/lib/tkextlib/iwidgets/mainwindow.rb15
-rw-r--r--ext/tk/lib/tkextlib/iwidgets/menubar.rb20
-rw-r--r--ext/tk/lib/tkextlib/iwidgets/messagebox.rb10
-rw-r--r--ext/tk/lib/tkextlib/iwidgets/notebook.rb23
-rw-r--r--ext/tk/lib/tkextlib/iwidgets/optionmenu.rb5
-rw-r--r--ext/tk/lib/tkextlib/iwidgets/panedwindow.rb5
-rw-r--r--ext/tk/lib/tkextlib/iwidgets/promptdialog.rb4
-rw-r--r--ext/tk/lib/tkextlib/iwidgets/pushbutton.rb5
-rw-r--r--ext/tk/lib/tkextlib/iwidgets/radiobox.rb5
-rw-r--r--ext/tk/lib/tkextlib/iwidgets/scrolledcanvas.rb46
-rw-r--r--ext/tk/lib/tkextlib/iwidgets/scrolledhtml.rb15
-rw-r--r--ext/tk/lib/tkextlib/iwidgets/scrolledlistbox.rb23
-rw-r--r--ext/tk/lib/tkextlib/iwidgets/scrolledtext.rb44
-rw-r--r--ext/tk/lib/tkextlib/iwidgets/selectionbox.rb14
-rw-r--r--ext/tk/lib/tkextlib/iwidgets/selectiondialog.rb4
-rw-r--r--ext/tk/lib/tkextlib/iwidgets/spindate.rb10
-rw-r--r--ext/tk/lib/tkextlib/iwidgets/spinint.rb10
-rw-r--r--ext/tk/lib/tkextlib/iwidgets/spinner.rb6
-rw-r--r--ext/tk/lib/tkextlib/iwidgets/spintime.rb10
-rw-r--r--ext/tk/lib/tkextlib/iwidgets/tabnotebook.rb19
-rw-r--r--ext/tk/lib/tkextlib/iwidgets/tabset.rb10
-rw-r--r--ext/tk/lib/tkextlib/iwidgets/timeentry.rb5
-rw-r--r--ext/tk/lib/tkextlib/iwidgets/timefield.rb15
-rw-r--r--ext/tk/lib/tkextlib/iwidgets/toolbar.rb25
-rw-r--r--ext/tk/lib/tkextlib/iwidgets/watch.rb11
-rw-r--r--ext/tk/lib/tkextlib/tcllib.rb37
-rw-r--r--ext/tk/lib/tkextlib/tcllib/autoscroll.rb17
-rw-r--r--ext/tk/lib/tkextlib/tcllib/ctext.rb21
-rw-r--r--ext/tk/lib/tkextlib/tcllib/cursor.rb17
-rw-r--r--ext/tk/lib/tkextlib/tcllib/datefield.rb9
-rw-r--r--ext/tk/lib/tkextlib/tcllib/dialog.rb84
-rw-r--r--ext/tk/lib/tkextlib/tcllib/getstring.rb131
-rw-r--r--ext/tk/lib/tkextlib/tcllib/history.rb73
-rw-r--r--ext/tk/lib/tkextlib/tcllib/ico.rb5
-rw-r--r--ext/tk/lib/tkextlib/tcllib/ip_entry.rb15
-rw-r--r--ext/tk/lib/tkextlib/tcllib/panelframe.rb72
-rw-r--r--ext/tk/lib/tkextlib/tcllib/plotchart.rb159
-rw-r--r--ext/tk/lib/tkextlib/tcllib/ruler.rb65
-rw-r--r--ext/tk/lib/tkextlib/tcllib/screenruler.rb68
-rw-r--r--ext/tk/lib/tkextlib/tcllib/scrollwin.rb61
-rw-r--r--ext/tk/lib/tkextlib/tcllib/style.rb6
-rw-r--r--ext/tk/lib/tkextlib/tcllib/superframe.rb51
-rw-r--r--ext/tk/lib/tkextlib/tcllib/swaplist.rb147
-rw-r--r--ext/tk/lib/tkextlib/tcllib/tablelist.rb27
-rw-r--r--ext/tk/lib/tkextlib/tcllib/tablelist_core.rb770
-rw-r--r--ext/tk/lib/tkextlib/tcllib/tablelist_tile.rb25
-rw-r--r--ext/tk/lib/tkextlib/tcllib/tkpiechart.rb21
-rw-r--r--ext/tk/lib/tkextlib/tcllib/tooltip.rb95
-rw-r--r--ext/tk/lib/tkextlib/tcllib/widget.rb48
-rw-r--r--ext/tk/lib/tkextlib/tclx/tclx.rb15
-rw-r--r--ext/tk/lib/tkextlib/tile.rb154
-rw-r--r--ext/tk/lib/tkextlib/tile/dialog.rb84
-rw-r--r--ext/tk/lib/tkextlib/tile/style.rb51
-rw-r--r--ext/tk/lib/tkextlib/tile/tbutton.rb16
-rw-r--r--ext/tk/lib/tkextlib/tile/tcheckbutton.rb17
-rw-r--r--ext/tk/lib/tkextlib/tile/tcombobox.rb55
-rw-r--r--ext/tk/lib/tkextlib/tile/tentry.rb40
-rw-r--r--ext/tk/lib/tkextlib/tile/tframe.rb30
-rw-r--r--ext/tk/lib/tkextlib/tile/tlabel.rb16
-rw-r--r--ext/tk/lib/tkextlib/tile/tlabelframe.rb30
-rw-r--r--ext/tk/lib/tkextlib/tile/tmenubutton.rb16
-rw-r--r--ext/tk/lib/tkextlib/tile/tnotebook.rb35
-rw-r--r--ext/tk/lib/tkextlib/tile/tpaned.rb188
-rw-r--r--ext/tk/lib/tkextlib/tile/tprogressbar.rb53
-rw-r--r--ext/tk/lib/tkextlib/tile/tradiobutton.rb17
-rw-r--r--ext/tk/lib/tkextlib/tile/treeview.rb280
-rw-r--r--ext/tk/lib/tkextlib/tile/tscale.rb50
-rw-r--r--ext/tk/lib/tkextlib/tile/tscrollbar.rb30
-rw-r--r--ext/tk/lib/tkextlib/tile/tseparator.rb30
-rw-r--r--ext/tk/lib/tkextlib/tile/tsquare.rb30
-rw-r--r--ext/tk/lib/tkextlib/tkDND/shape.rb6
-rw-r--r--ext/tk/lib/tkextlib/tkDND/tkdnd.rb46
-rw-r--r--ext/tk/lib/tkextlib/tkHTML/htmlwidget.rb15
-rw-r--r--ext/tk/lib/tkextlib/tkimg.rb5
-rw-r--r--ext/tk/lib/tkextlib/tkimg/bmp.rb5
-rw-r--r--ext/tk/lib/tkextlib/tkimg/gif.rb5
-rw-r--r--ext/tk/lib/tkextlib/tkimg/ico.rb5
-rw-r--r--ext/tk/lib/tkextlib/tkimg/jpeg.rb5
-rw-r--r--ext/tk/lib/tkextlib/tkimg/pcx.rb5
-rw-r--r--ext/tk/lib/tkextlib/tkimg/pixmap.rb7
-rw-r--r--ext/tk/lib/tkextlib/tkimg/png.rb5
-rw-r--r--ext/tk/lib/tkextlib/tkimg/ppm.rb5
-rw-r--r--ext/tk/lib/tkextlib/tkimg/ps.rb5
-rw-r--r--ext/tk/lib/tkextlib/tkimg/sgi.rb5
-rw-r--r--ext/tk/lib/tkextlib/tkimg/sun.rb5
-rw-r--r--ext/tk/lib/tkextlib/tkimg/tga.rb5
-rw-r--r--ext/tk/lib/tkextlib/tkimg/tiff.rb5
-rw-r--r--ext/tk/lib/tkextlib/tkimg/window.rb5
-rw-r--r--ext/tk/lib/tkextlib/tkimg/xbm.rb5
-rw-r--r--ext/tk/lib/tkextlib/tkimg/xpm.rb5
-rw-r--r--ext/tk/lib/tkextlib/tktable/tktable.rb61
-rw-r--r--ext/tk/lib/tkextlib/tktrans/tktrans.rb5
-rw-r--r--ext/tk/lib/tkextlib/treectrl/tktreectrl.rb1618
-rw-r--r--ext/tk/lib/tkextlib/trofs.rb13
-rw-r--r--ext/tk/lib/tkextlib/trofs/setup.rb8
-rw-r--r--ext/tk/lib/tkextlib/trofs/trofs.rb51
-rw-r--r--ext/tk/lib/tkextlib/vu.rb5
-rw-r--r--ext/tk/lib/tkextlib/vu/bargraph.rb10
-rw-r--r--ext/tk/lib/tkextlib/vu/charts.rb6
-rw-r--r--ext/tk/lib/tkextlib/vu/pie.rb4
-rw-r--r--ext/tk/lib/tkextlib/winico/winico.rb12
-rw-r--r--ext/tk/sample/cd_timer.rb81
-rw-r--r--ext/tk/sample/demos-en/anilabel.rb172
-rw-r--r--ext/tk/sample/demos-en/aniwave.rb115
-rw-r--r--ext/tk/sample/demos-en/bind.rb30
-rw-r--r--ext/tk/sample/demos-en/check2.rb44
-rw-r--r--ext/tk/sample/demos-en/floor.rb4
-rw-r--r--ext/tk/sample/demos-en/floor2.rb4
-rw-r--r--ext/tk/sample/demos-en/goldberg.rb1999
-rw-r--r--ext/tk/sample/demos-en/pendulum.rb223
-rw-r--r--ext/tk/sample/demos-en/tcolor17
-rw-r--r--ext/tk/sample/demos-en/tcolor.bak513
-rw-r--r--ext/tk/sample/demos-en/widget63
-rw-r--r--ext/tk/sample/demos-jp/anilabel.rb174
-rw-r--r--ext/tk/sample/demos-jp/aniwave.rb116
-rw-r--r--ext/tk/sample/demos-jp/bind.rb30
-rw-r--r--ext/tk/sample/demos-jp/check2.rb44
-rw-r--r--ext/tk/sample/demos-jp/ctext.rb2
-rw-r--r--ext/tk/sample/demos-jp/floor.rb4
-rw-r--r--ext/tk/sample/demos-jp/floor2.rb4
-rw-r--r--ext/tk/sample/demos-jp/goldberg.rb2003
-rw-r--r--ext/tk/sample/demos-jp/pendulum.rb224
-rw-r--r--ext/tk/sample/demos-jp/tcolor17
-rw-r--r--ext/tk/sample/demos-jp/widget56
-rw-r--r--ext/tk/sample/irbtk.rb30
-rw-r--r--ext/tk/sample/tkextlib/blt/barchart5.rb101
-rw-r--r--ext/tk/sample/tkextlib/blt/calendar.rb117
-rw-r--r--ext/tk/sample/tkextlib/blt/graph6.rb2222
-rw-r--r--ext/tk/sample/tkextlib/blt/graph7.rb40
-rw-r--r--ext/tk/sample/tkextlib/blt/graph7a.rb63
-rw-r--r--ext/tk/sample/tkextlib/blt/graph7b.rb41
-rw-r--r--ext/tk/sample/tkextlib/blt/graph7c.rb45
-rw-r--r--ext/tk/sample/tkextlib/blt/images/buckskin.gifbin7561 -> 0 bytes-rw-r--r--ext/tk/sample/tkextlib/blt/images/chalk.gifbin4378 -> 0 bytes-rw-r--r--ext/tk/sample/tkextlib/blt/images/qv100.t.gifbin2694 -> 0 bytes-rw-r--r--ext/tk/sample/tkextlib/blt/images/rain.gifbin3785 -> 0 bytes-rw-r--r--ext/tk/sample/tkextlib/blt/images/sample.gifbin186103 -> 0 bytes-rw-r--r--ext/tk/sample/tkextlib/blt/pareto.rb90
-rw-r--r--ext/tk/sample/tkextlib/blt/plot1.rb9
-rw-r--r--ext/tk/sample/tkextlib/blt/plot1b.rb10
-rw-r--r--ext/tk/sample/tkextlib/blt/readme.txt2
-rw-r--r--ext/tk/sample/tkextlib/blt/scripts/stipples.rb156
-rw-r--r--ext/tk/sample/tkextlib/blt/winop1.rb40
-rw-r--r--ext/tk/sample/tkextlib/blt/winop2.rb28
-rw-r--r--ext/tk/sample/tkextlib/bwidget/tree.rb2
-rw-r--r--ext/tk/sample/tkextlib/iwidgets/sample/hierarchy.rb8
-rw-r--r--ext/tk/sample/tkextlib/tile/Orig_LICENSE.txt30
-rw-r--r--ext/tk/sample/tkextlib/tile/demo.rb951
-rw-r--r--ext/tk/sample/tkextlib/tile/iconlib.tcl110
-rw-r--r--ext/tk/sample/tkextlib/tile/readme.txt3
-rw-r--r--ext/tk/sample/tkextlib/tile/repeater.tcl117
-rw-r--r--ext/tk/sample/tkextlib/tile/themes/kroc.rb197
-rw-r--r--ext/tk/sample/tkextlib/tile/themes/kroc.tcl163
-rw-r--r--ext/tk/sample/tkextlib/tile/themes/kroc/button-h.gifbin522 -> 0 bytes-rw-r--r--ext/tk/sample/tkextlib/tile/themes/kroc/button-n.gifbin554 -> 0 bytes-rw-r--r--ext/tk/sample/tkextlib/tile/themes/kroc/button-p.gifbin548 -> 0 bytes-rw-r--r--ext/tk/sample/tkextlib/tile/themes/kroc/check-hc.gifbin281 -> 0 bytes-rw-r--r--ext/tk/sample/tkextlib/tile/themes/kroc/check-hu.gifbin273 -> 0 bytes-rw-r--r--ext/tk/sample/tkextlib/tile/themes/kroc/check-nc.gifbin303 -> 0 bytes-rw-r--r--ext/tk/sample/tkextlib/tile/themes/kroc/check-nu.gifbin294 -> 0 bytes-rw-r--r--ext/tk/sample/tkextlib/tile/themes/kroc/radio-hc.gifbin652 -> 0 bytes-rw-r--r--ext/tk/sample/tkextlib/tile/themes/kroc/radio-hu.gifbin644 -> 0 bytes-rw-r--r--ext/tk/sample/tkextlib/tile/themes/kroc/radio-nc.gifbin632 -> 0 bytes-rw-r--r--ext/tk/sample/tkextlib/tile/themes/kroc/radio-nu.gifbin621 -> 0 bytes-rw-r--r--ext/tk/sample/tkextlib/tile/themes/pkgIndex.tcl15
-rw-r--r--ext/tk/sample/tkextlib/tile/toolbutton.tcl152
-rw-r--r--ext/tk/sample/tkextlib/tkHTML/hv.rb85
-rw-r--r--ext/tk/sample/tkextlib/tkHTML/ss.rb680
-rw-r--r--ext/tk/sample/tkextlib/tkimg/demo.rb1478
-rw-r--r--ext/tk/sample/tkextlib/tkimg/license_terms_of_Img_extension41
-rw-r--r--ext/tk/sample/tkextlib/tkimg/readme.txt3
-rw-r--r--ext/tk/sample/tkextlib/tktable/basic.rb4
-rw-r--r--ext/tk/sample/tkextlib/tktable/command.rb4
-rw-r--r--ext/tk/sample/tkextlib/tktable/debug.rb2
-rw-r--r--ext/tk/sample/tkextlib/tktable/maxsize.rb2
-rw-r--r--ext/tk/sample/tkextlib/treectrl/bitmaps.rb76
-rw-r--r--ext/tk/sample/tkextlib/treectrl/demo.rb1307
-rw-r--r--ext/tk/sample/tkextlib/treectrl/explorer.rb430
-rw-r--r--ext/tk/sample/tkextlib/treectrl/help.rb404
-rw-r--r--ext/tk/sample/tkextlib/treectrl/imovie.rb130
-rw-r--r--ext/tk/sample/tkextlib/treectrl/layout.rb159
-rw-r--r--ext/tk/sample/tkextlib/treectrl/mailwasher.rb269
-rw-r--r--ext/tk/sample/tkextlib/treectrl/outlook-folders.rb124
-rw-r--r--ext/tk/sample/tkextlib/treectrl/outlook-newgroup.rb448
-rw-r--r--ext/tk/sample/tkextlib/treectrl/pics/big-dll.gifbin437 -> 0 bytes-rw-r--r--ext/tk/sample/tkextlib/treectrl/pics/big-exe.gifbin368 -> 0 bytes-rw-r--r--ext/tk/sample/tkextlib/treectrl/pics/big-file.gifbin466 -> 0 bytes-rw-r--r--ext/tk/sample/tkextlib/treectrl/pics/big-folder.gifbin459 -> 0 bytes-rw-r--r--ext/tk/sample/tkextlib/treectrl/pics/big-txt.gifbin392 -> 0 bytes-rw-r--r--ext/tk/sample/tkextlib/treectrl/pics/checked.gifbin78 -> 0 bytes-rw-r--r--ext/tk/sample/tkextlib/treectrl/pics/file.gifbin279 -> 0 bytes-rw-r--r--ext/tk/sample/tkextlib/treectrl/pics/folder-closed.gifbin111 -> 0 bytes-rw-r--r--ext/tk/sample/tkextlib/treectrl/pics/folder-open.gifbin120 -> 0 bytes-rw-r--r--ext/tk/sample/tkextlib/treectrl/pics/help-book-closed.gifbin115 -> 0 bytes-rw-r--r--ext/tk/sample/tkextlib/treectrl/pics/help-book-open.gifbin128 -> 0 bytes-rw-r--r--ext/tk/sample/tkextlib/treectrl/pics/help-page.gifbin132 -> 0 bytes-rw-r--r--ext/tk/sample/tkextlib/treectrl/pics/imovie-01.gifbin5406 -> 0 bytes-rw-r--r--ext/tk/sample/tkextlib/treectrl/pics/imovie-02.gifbin5912 -> 0 bytes-rw-r--r--ext/tk/sample/tkextlib/treectrl/pics/imovie-03.gifbin4696 -> 0 bytes-rw-r--r--ext/tk/sample/tkextlib/treectrl/pics/imovie-04.gifbin5783 -> 0 bytes-rw-r--r--ext/tk/sample/tkextlib/treectrl/pics/imovie-05.gifbin3238 -> 0 bytes-rw-r--r--ext/tk/sample/tkextlib/treectrl/pics/imovie-06.gifbin3509 -> 0 bytes-rw-r--r--ext/tk/sample/tkextlib/treectrl/pics/imovie-07.gifbin2091 -> 0 bytes-rw-r--r--ext/tk/sample/tkextlib/treectrl/pics/internet-check-off.gifbin70 -> 0 bytes-rw-r--r--ext/tk/sample/tkextlib/treectrl/pics/internet-check-on.gifbin76 -> 0 bytes-rw-r--r--ext/tk/sample/tkextlib/treectrl/pics/internet-print.gifbin124 -> 0 bytes-rw-r--r--ext/tk/sample/tkextlib/treectrl/pics/internet-radio-off.gifbin68 -> 0 bytes-rw-r--r--ext/tk/sample/tkextlib/treectrl/pics/internet-radio-on.gifbin71 -> 0 bytes-rw-r--r--ext/tk/sample/tkextlib/treectrl/pics/internet-search.gifbin114 -> 0 bytes-rw-r--r--ext/tk/sample/tkextlib/treectrl/pics/internet-security.gifbin108 -> 0 bytes-rw-r--r--ext/tk/sample/tkextlib/treectrl/pics/mac-collapse.gifbin275 -> 0 bytes-rw-r--r--ext/tk/sample/tkextlib/treectrl/pics/mac-expand.gifbin277 -> 0 bytes-rw-r--r--ext/tk/sample/tkextlib/treectrl/pics/outlook-arrow.gifbin73 -> 0 bytes-rw-r--r--ext/tk/sample/tkextlib/treectrl/pics/outlook-clip.gifbin73 -> 0 bytes-rw-r--r--ext/tk/sample/tkextlib/treectrl/pics/outlook-deleted.gifbin138 -> 0 bytes-rw-r--r--ext/tk/sample/tkextlib/treectrl/pics/outlook-draft.gifbin134 -> 0 bytes-rw-r--r--ext/tk/sample/tkextlib/treectrl/pics/outlook-folder.gifbin133 -> 0 bytes-rw-r--r--ext/tk/sample/tkextlib/treectrl/pics/outlook-group.gifbin144 -> 0 bytes-rw-r--r--ext/tk/sample/tkextlib/treectrl/pics/outlook-inbox.gifbin133 -> 0 bytes-rw-r--r--ext/tk/sample/tkextlib/treectrl/pics/outlook-local.gifbin146 -> 0 bytes-rw-r--r--ext/tk/sample/tkextlib/treectrl/pics/outlook-main.gifbin174 -> 0 bytes-rw-r--r--ext/tk/sample/tkextlib/treectrl/pics/outlook-outbox.gifbin136 -> 0 bytes-rw-r--r--ext/tk/sample/tkextlib/treectrl/pics/outlook-read-2.gifbin343 -> 0 bytes-rw-r--r--ext/tk/sample/tkextlib/treectrl/pics/outlook-read.gifbin304 -> 0 bytes-rw-r--r--ext/tk/sample/tkextlib/treectrl/pics/outlook-sent.gifbin132 -> 0 bytes-rw-r--r--ext/tk/sample/tkextlib/treectrl/pics/outlook-server.gifbin163 -> 0 bytes-rw-r--r--ext/tk/sample/tkextlib/treectrl/pics/outlook-unread.gifbin303 -> 0 bytes-rw-r--r--ext/tk/sample/tkextlib/treectrl/pics/outlook-watch.gifbin98 -> 0 bytes-rw-r--r--ext/tk/sample/tkextlib/treectrl/pics/sky.gifbin6454 -> 0 bytes-rw-r--r--ext/tk/sample/tkextlib/treectrl/pics/small-dll.gifbin311 -> 0 bytes-rw-r--r--ext/tk/sample/tkextlib/treectrl/pics/small-exe.gifbin115 -> 0 bytes-rw-r--r--ext/tk/sample/tkextlib/treectrl/pics/small-file.gifbin338 -> 0 bytes-rw-r--r--ext/tk/sample/tkextlib/treectrl/pics/small-folder.gifbin307 -> 0 bytes-rw-r--r--ext/tk/sample/tkextlib/treectrl/pics/small-txt.gifbin302 -> 0 bytes-rw-r--r--ext/tk/sample/tkextlib/treectrl/pics/unchecked.gifbin72 -> 0 bytes-rw-r--r--ext/tk/sample/tkextlib/treectrl/random.rb508
-rw-r--r--ext/tk/sample/tkextlib/treectrl/readme.txt2
-rw-r--r--ext/tk/sample/tkextlib/treectrl/www-options.rb303
-rw-r--r--ext/tk/sample/tkextlib/vu/dial.rb (renamed from ext/tk/sample/tkextlib/vu/dial_demo.rb)0
-rw-r--r--ext/tk/sample/tkextlib/vu/vu.rb (renamed from ext/tk/sample/tkextlib/vu/vu_demo.rb)0
-rw-r--r--ext/tk/sample/tkrttimer.rb68
-rw-r--r--ext/tk/sample/tktextio.rb603
-rw-r--r--ext/tk/sample/tktree.rb2
-rw-r--r--ext/tk/tkutil.c397
-rw-r--r--ext/win32ole/extconf.rb14
-rw-r--r--ext/win32ole/tests/testNIL2VTEMPTY.rb28
-rw-r--r--ext/win32ole/tests/testOLEEVENT.rb58
-rw-r--r--ext/win32ole/tests/testOLEMETHOD.rb5
-rw-r--r--ext/win32ole/tests/testOLEPARAM.rb9
-rw-r--r--ext/win32ole/tests/testWIN32OLE.rb61
-rw-r--r--ext/win32ole/tests/testall.rb1
-rw-r--r--ext/win32ole/win32ole.c1269
-rw-r--r--ext/zlib/zlib.c91
-rw-r--r--file.c209
-rw-r--r--gc.c123
-rw-r--r--hash.c87
-rw-r--r--instruby.rb54
-rw-r--r--intern.h10
-rw-r--r--io.c611
-rw-r--r--lib/.document6
-rw-r--r--lib/cgi-lib.rb2
-rw-r--r--lib/cgi.rb9
-rw-r--r--lib/cgi/session.rb72
-rw-r--r--lib/cgi/session/pstore.rb5
-rw-r--r--lib/date.rb10
-rw-r--r--lib/date/format.rb49
-rw-r--r--lib/debug.rb2
-rw-r--r--lib/delegate.rb219
-rw-r--r--lib/drb/drb.rb264
-rw-r--r--lib/drb/extserv.rb5
-rw-r--r--lib/drb/extservm.rb8
-rw-r--r--lib/drb/gw.rb74
-rw-r--r--lib/drb/ssl.rb9
-rw-r--r--lib/drb/unix.rb1
-rw-r--r--lib/erb.rb383
-rw-r--r--lib/fileutils.rb1239
-rw-r--r--lib/forwardable.rb174
-rw-r--r--lib/ftools.rb53
-rw-r--r--lib/getopts.rb2
-rw-r--r--lib/importenv.rb2
-rw-r--r--lib/ipaddr.rb5
-rw-r--r--lib/irb.rb12
-rw-r--r--lib/irb/cmd/chws.rb4
-rw-r--r--lib/irb/cmd/fork.rb16
-rw-r--r--lib/irb/cmd/help.rb34
-rw-r--r--lib/irb/cmd/load.rb4
-rw-r--r--lib/irb/cmd/nop.rb4
-rw-r--r--lib/irb/cmd/pushws.rb4
-rw-r--r--lib/irb/cmd/subirb.rb4
-rw-r--r--lib/irb/context.rb41
-rw-r--r--lib/irb/ext/change-ws.rb4
-rw-r--r--lib/irb/ext/history.rb8
-rw-r--r--lib/irb/ext/loader.rb14
-rw-r--r--lib/irb/ext/math-mode.rb4
-rw-r--r--lib/irb/ext/multi-irb.rb4
-rw-r--r--lib/irb/ext/save-history.rb85
-rw-r--r--lib/irb/ext/tracer.rb4
-rw-r--r--lib/irb/ext/use-loader.rb4
-rw-r--r--lib/irb/ext/workspaces.rb4
-rw-r--r--lib/irb/extend-command.rb55
-rw-r--r--lib/irb/help.rb2
-rw-r--r--lib/irb/init.rb90
-rw-r--r--lib/irb/input-method.rb10
-rw-r--r--lib/irb/lc/error.rb4
-rw-r--r--lib/irb/lc/help-message4
-rw-r--r--lib/irb/lc/ja/error.rb6
-rw-r--r--lib/irb/lc/ja/help-message4
-rw-r--r--lib/irb/locale.rb20
-rw-r--r--lib/irb/notifier.rb145
-rw-r--r--lib/irb/output-method.rb85
-rw-r--r--lib/irb/ruby-lex.rb97
-rw-r--r--lib/irb/ruby-token.rb6
-rw-r--r--lib/irb/slex.rb361
-rw-r--r--lib/irb/version.rb6
-rw-r--r--lib/irb/workspace.rb4
-rw-r--r--lib/irb/ws-for-case-2.rb4
-rw-r--r--lib/jcode.rb3
-rw-r--r--lib/logger.rb270
-rw-r--r--lib/mathn.rb5
-rw-r--r--lib/mkmf.rb620
-rw-r--r--lib/monitor.rb12
-rw-r--r--lib/net/http.rb892
-rw-r--r--lib/net/https.rb165
-rw-r--r--lib/net/imap.rb13
-rw-r--r--lib/net/pop.rb2
-rw-r--r--lib/net/protocol.rb394
-rw-r--r--lib/net/smtp.rb2
-rw-r--r--lib/net/telnet.rb2
-rw-r--r--lib/open-uri.rb335
-rw-r--r--lib/open3.rb2
-rw-r--r--lib/optparse.rb121
-rw-r--r--lib/optparse/version.rb36
-rw-r--r--lib/ostruct.rb58
-rw-r--r--lib/parsearg.rb2
-rw-r--r--lib/pathname.rb12
-rw-r--r--lib/ping.rb2
-rw-r--r--lib/pp.rb283
-rw-r--r--lib/profiler.rb58
-rw-r--r--lib/pstore.rb222
-rw-r--r--lib/rational.rb318
-rw-r--r--lib/rdoc/README17
-rw-r--r--lib/rdoc/code_objects.rb61
-rw-r--r--lib/rdoc/generators/html_generator.rb138
-rw-r--r--lib/rdoc/generators/ri_generator.rb2
-rw-r--r--lib/rdoc/generators/template/html/html.rb602
-rw-r--r--lib/rdoc/generators/template/html/kilmer.rb14
-rw-r--r--lib/rdoc/markup/simple_markup.rb3
-rw-r--r--lib/rdoc/markup/simple_markup/preprocess.rb2
-rw-r--r--lib/rdoc/markup/simple_markup/to_flow.rb2
-rw-r--r--lib/rdoc/options.rb2
-rw-r--r--lib/rdoc/parsers/parse_c.rb234
-rw-r--r--lib/rdoc/parsers/parse_rb.rb56
-rw-r--r--lib/rdoc/parsers/parse_simple.rb6
-rw-r--r--lib/rdoc/rdoc.rb18
-rw-r--r--lib/rdoc/ri/ri_formatter.rb39
-rw-r--r--lib/rdoc/ri/ri_options.rb6
-rw-r--r--lib/rdoc/usage.rb39
-rw-r--r--lib/resolv.rb143
-rw-r--r--lib/rexml/attribute.rb6
-rw-r--r--lib/rexml/document.rb4
-rw-r--r--lib/rexml/element.rb41
-rw-r--r--lib/rexml/encoding.rb34
-rw-r--r--lib/rexml/encodings/EUC-JP.rb41
-rw-r--r--lib/rexml/encodings/ICONV.rb18
-rw-r--r--lib/rexml/encodings/ISO-8859-1.rb24
-rw-r--r--lib/rexml/encodings/SHIFT-JIS.rb43
-rw-r--r--lib/rexml/encodings/SHIFT_JIS.rb2
-rw-r--r--lib/rexml/encodings/UNILE.rb13
-rw-r--r--lib/rexml/encodings/US-ASCII.rb13
-rw-r--r--lib/rexml/encodings/UTF-16.rb13
-rw-r--r--lib/rexml/encodings/UTF-8.rb13
-rw-r--r--lib/rexml/functions.rb63
-rw-r--r--lib/rexml/instruction.rb4
-rw-r--r--lib/rexml/node.rb26
-rw-r--r--lib/rexml/parsers/baseparser.rb748
-rw-r--r--lib/rexml/parsers/pullparser.rb318
-rw-r--r--lib/rexml/parsers/sax2parser.rb25
-rw-r--r--lib/rexml/parsers/streamparser.rb5
-rw-r--r--lib/rexml/parsers/xpathparser.rb9
-rw-r--r--lib/rexml/rexml.rb8
-rw-r--r--lib/rexml/sax2listener.rb2
-rw-r--r--lib/rexml/source.rb8
-rw-r--r--lib/rexml/syncenumerator.rb33
-rw-r--r--lib/rexml/text.rb542
-rw-r--r--lib/rexml/validation/validation.rb5
-rw-r--r--lib/rexml/xmldecl.rb4
-rw-r--r--lib/rexml/xpath.rb8
-rw-r--r--lib/rexml/xpath_parser.rb844
-rw-r--r--lib/rinda/rinda.rb179
-rw-r--r--lib/rinda/ring.rb111
-rw-r--r--lib/rinda/tuplespace.rb509
-rw-r--r--lib/rss.rb16
-rw-r--r--lib/rss/0.9.rb497
-rw-r--r--lib/rss/1.0.rb293
-rw-r--r--lib/rss/2.0.rb117
-rw-r--r--lib/rss/content.rb13
-rw-r--r--lib/rss/dublincore.rb142
-rw-r--r--lib/rss/image.rb216
-rw-r--r--lib/rss/maker.rb15
-rw-r--r--lib/rss/maker/0.9.rb100
-rw-r--r--lib/rss/maker/1.0.rb76
-rw-r--r--lib/rss/maker/2.0.rb73
-rw-r--r--lib/rss/maker/base.rb282
-rw-r--r--lib/rss/maker/content.rb4
-rw-r--r--lib/rss/maker/dublincore.rb152
-rw-r--r--lib/rss/maker/image.rb145
-rw-r--r--lib/rss/maker/syndication.rb4
-rw-r--r--lib/rss/maker/trackback.rb118
-rw-r--r--lib/rss/parser.rb103
-rw-r--r--lib/rss/rexmlparser.rb2
-rw-r--r--lib/rss/rss.rb467
-rw-r--r--lib/rss/syndication.rb17
-rw-r--r--lib/rss/taxonomy.rb12
-rw-r--r--lib/rss/trackback.rb262
-rw-r--r--lib/rss/utils.rb14
-rw-r--r--lib/rss/xml-stylesheet.rb7
-rw-r--r--lib/rss/xmlscanner.rb2
-rw-r--r--lib/set.rb22
-rw-r--r--lib/shellwords.rb4
-rw-r--r--lib/singleton.rb6
-rw-r--r--lib/soap/baseData.rb229
-rw-r--r--lib/soap/element.rb37
-rw-r--r--lib/soap/encodingstyle/aspDotNetHandler.rb45
-rw-r--r--lib/soap/encodingstyle/handler.rb8
-rw-r--r--lib/soap/encodingstyle/literalHandler.rb67
-rw-r--r--lib/soap/encodingstyle/soapHandler.rb59
-rw-r--r--lib/soap/generator.rb114
-rw-r--r--lib/soap/header/handlerset.rb12
-rw-r--r--lib/soap/header/simplehandler.rb10
-rw-r--r--lib/soap/httpconfigloader.rb119
-rw-r--r--lib/soap/mapping/factory.rb141
-rw-r--r--lib/soap/mapping/mapping.rb277
-rw-r--r--lib/soap/mapping/registry.rb288
-rw-r--r--lib/soap/mapping/rubytypeFactory.rb55
-rw-r--r--lib/soap/mapping/typeMap.rb9
-rw-r--r--lib/soap/mapping/wsdlRegistry.rb155
-rw-r--r--lib/soap/mapping/wsdlencodedregistry.rb280
-rw-r--r--lib/soap/mapping/wsdlliteralregistry.rb418
-rw-r--r--lib/soap/marshal.rb5
-rw-r--r--lib/soap/mimemessage.rb4
-rw-r--r--lib/soap/netHttpClient.rb34
-rw-r--r--lib/soap/parser.rb11
-rw-r--r--lib/soap/property.rb17
-rw-r--r--lib/soap/rpc/cgistub.rb236
-rw-r--r--lib/soap/rpc/driver.rb350
-rw-r--r--lib/soap/rpc/element.rb119
-rw-r--r--lib/soap/rpc/httpserver.rb94
-rw-r--r--lib/soap/rpc/proxy.rb450
-rw-r--r--lib/soap/rpc/router.rb591
-rw-r--r--lib/soap/rpc/rpc.rb2
-rw-r--r--lib/soap/rpc/soaplet.rb212
-rw-r--r--lib/soap/soap.rb57
-rw-r--r--lib/soap/streamHandler.rb214
-rw-r--r--lib/soap/wsdlDriver.rb579
-rw-r--r--lib/tempfile.rb2
-rw-r--r--lib/test/unit.rb64
-rw-r--r--lib/test/unit/autorunner.rb37
-rw-r--r--lib/test/unit/collector/dir.rb20
-rw-r--r--lib/thread.rb104
-rw-r--r--lib/thwait.rb7
-rw-r--r--lib/time.rb272
-rw-r--r--lib/timeout.rb52
-rw-r--r--lib/un.rb52
-rw-r--r--lib/uri/common.rb22
-rw-r--r--lib/uri/generic.rb31
-rw-r--r--lib/webrick/accesslog.rb7
-rw-r--r--lib/webrick/cgi.rb42
-rw-r--r--lib/webrick/config.rb5
-rw-r--r--lib/webrick/httpauth.rb3
-rw-r--r--lib/webrick/httpauth/basicauth.rb3
-rw-r--r--lib/webrick/httpauth/digestauth.rb13
-rw-r--r--lib/webrick/httpauth/htpasswd.rb10
-rw-r--r--lib/webrick/httpproxy.rb18
-rw-r--r--lib/webrick/httprequest.rb11
-rw-r--r--lib/webrick/httpserver.rb7
-rw-r--r--lib/webrick/httpservlet/filehandler.rb27
-rw-r--r--lib/webrick/httputils.rb28
-rw-r--r--lib/webrick/server.rb54
-rw-r--r--lib/webrick/ssl.rb2
-rw-r--r--lib/webrick/utils.rb16
-rw-r--r--lib/wsdl/binding.rb2
-rw-r--r--lib/wsdl/definitions.rb30
-rw-r--r--lib/wsdl/import.rb28
-rw-r--r--lib/wsdl/importer.rb61
-rw-r--r--lib/wsdl/info.rb10
-rw-r--r--lib/wsdl/message.rb2
-rw-r--r--lib/wsdl/operation.rb23
-rw-r--r--lib/wsdl/operationBinding.rb32
-rw-r--r--lib/wsdl/param.rb15
-rw-r--r--lib/wsdl/parser.rb57
-rw-r--r--lib/wsdl/part.rb2
-rw-r--r--lib/wsdl/port.rb4
-rw-r--r--lib/wsdl/portType.rb5
-rw-r--r--lib/wsdl/service.rb2
-rw-r--r--lib/wsdl/soap/address.rb2
-rw-r--r--lib/wsdl/soap/binding.rb9
-rw-r--r--lib/wsdl/soap/body.rb12
-rw-r--r--lib/wsdl/soap/cgiStubCreator.rb21
-rw-r--r--lib/wsdl/soap/classDefCreator.rb304
-rw-r--r--lib/wsdl/soap/classDefCreatorSupport.rb28
-rw-r--r--lib/wsdl/soap/clientSkeltonCreator.rb6
-rw-r--r--lib/wsdl/soap/complexType.rb82
-rw-r--r--lib/wsdl/soap/data.rb1
-rw-r--r--lib/wsdl/soap/definitions.rb39
-rw-r--r--lib/wsdl/soap/driverCreator.rb29
-rw-r--r--lib/wsdl/soap/element.rb28
-rw-r--r--lib/wsdl/soap/fault.rb12
-rw-r--r--lib/wsdl/soap/header.rb19
-rw-r--r--lib/wsdl/soap/headerfault.rb8
-rw-r--r--lib/wsdl/soap/mappingRegistryCreator.rb16
-rw-r--r--lib/wsdl/soap/methodDefCreator.rb168
-rw-r--r--lib/wsdl/soap/operation.rb15
-rw-r--r--lib/wsdl/soap/servantSkeltonCreator.rb22
-rw-r--r--lib/wsdl/soap/standaloneServerStubCreator.rb30
-rw-r--r--lib/wsdl/soap/wsdl2ruby.rb176
-rw-r--r--lib/wsdl/xmlSchema/all.rb12
-rw-r--r--lib/wsdl/xmlSchema/annotation.rb34
-rw-r--r--lib/wsdl/xmlSchema/any.rb12
-rw-r--r--lib/wsdl/xmlSchema/attribute.rb95
-rw-r--r--lib/wsdl/xmlSchema/choice.rb12
-rw-r--r--lib/wsdl/xmlSchema/complexContent.rb5
-rw-r--r--lib/wsdl/xmlSchema/complexType.rb34
-rw-r--r--lib/wsdl/xmlSchema/content.rb4
-rw-r--r--lib/wsdl/xmlSchema/data.rb14
-rw-r--r--lib/wsdl/xmlSchema/element.rb134
-rw-r--r--lib/wsdl/xmlSchema/enumeration.rb4
-rw-r--r--lib/wsdl/xmlSchema/import.rb27
-rw-r--r--lib/wsdl/xmlSchema/importer.rb87
-rw-r--r--lib/wsdl/xmlSchema/include.rb54
-rw-r--r--lib/wsdl/xmlSchema/length.rb35
-rw-r--r--lib/wsdl/xmlSchema/parser.rb64
-rw-r--r--lib/wsdl/xmlSchema/pattern.rb36
-rw-r--r--lib/wsdl/xmlSchema/schema.rb47
-rw-r--r--lib/wsdl/xmlSchema/sequence.rb12
-rw-r--r--lib/wsdl/xmlSchema/simpleContent.rb65
-rw-r--r--lib/wsdl/xmlSchema/simpleExtension.rb54
-rw-r--r--lib/wsdl/xmlSchema/simpleRestriction.rb29
-rw-r--r--lib/wsdl/xmlSchema/simpleType.rb14
-rw-r--r--lib/wsdl/xmlSchema/xsd2ruby.rb107
-rw-r--r--lib/xmlrpc/.document1
-rw-r--r--lib/xmlrpc/client.rb29
-rw-r--r--lib/xmlrpc/create.rb17
-rw-r--r--lib/xmlrpc/datetime.rb4
-rw-r--r--lib/xmlrpc/parser.rb81
-rw-r--r--lib/xmlrpc/server.rb159
-rw-r--r--lib/xmlrpc/utils.rb9
-rw-r--r--lib/xsd/charset.rb80
-rw-r--r--lib/xsd/codegen/classdef.rb2
-rw-r--r--lib/xsd/codegen/commentdef.rb4
-rw-r--r--lib/xsd/codegen/gensupport.rb76
-rw-r--r--lib/xsd/codegen/methoddef.rb4
-rw-r--r--lib/xsd/codegen/moduledef.rb2
-rw-r--r--lib/xsd/datatypes.rb471
-rw-r--r--lib/xsd/iconvcharset.rb2
-rw-r--r--lib/xsd/mapping.rb42
-rw-r--r--lib/xsd/namedelements.rb18
-rw-r--r--lib/xsd/ns.rb38
-rw-r--r--lib/xsd/qname.rb17
-rw-r--r--lib/xsd/xmlparser.rb2
-rw-r--r--lib/xsd/xmlparser/xmlscanner.rb6
-rw-r--r--lib/yaml.rb119
-rw-r--r--lib/yaml/basenode.rb20
-rw-r--r--lib/yaml/emitter.rb107
-rw-r--r--lib/yaml/error.rb1
-rw-r--r--lib/yaml/rubytypes.rb774
-rw-r--r--lib/yaml/stream.rb18
-rw-r--r--lib/yaml/syck.rb8
-rw-r--r--lib/yaml/tag.rb89
-rw-r--r--lib/yaml/types.rb220
-rw-r--r--marshal.c4
-rw-r--r--misc/ruby-electric.el200
-rw-r--r--misc/ruby-mode.el36
-rw-r--r--missing.h7
-rw-r--r--missing/crypt.c1162
-rw-r--r--missing/erf.c3
-rw-r--r--missing/isinf.c1
-rw-r--r--missing/mkdir.c104
-rw-r--r--missing/strchr.c4
-rw-r--r--missing/vsnprintf.c17
-rw-r--r--mkconfig.rb44
-rw-r--r--node.h19
-rw-r--r--numeric.c31
-rw-r--r--object.c133
-rw-r--r--pack.c126
-rw-r--r--parse.y250
-rw-r--r--process.c412
-rw-r--r--random.c278
-rw-r--r--range.c15
-rw-r--r--re.c21
-rw-r--r--regex.c20
-rw-r--r--ruby.c133
-rw-r--r--ruby.h20
-rw-r--r--rubyio.h9
-rw-r--r--rubysig.h24
-rw-r--r--rubytest.rb11
-rwxr-xr-xrunruby.rb59
-rwxr-xr-xsample/optparse/subcommand.rb19
-rwxr-xr-xsample/rss/blend.rb73
-rw-r--r--sample/rss/list_description.rb118
-rwxr-xr-xsample/rss/re_read.rb64
-rw-r--r--sample/rss/rss_recent.rb118
-rw-r--r--sample/rss/tdiary_plugin/rss-recent.rb213
-rw-r--r--sample/soap/authheader/authmgr.rb41
-rw-r--r--sample/soap/authheader/client.rb40
-rw-r--r--sample/soap/authheader/client2.rb39
-rw-r--r--sample/soap/authheader/server.rb72
-rw-r--r--sample/soap/authheader/server2.rb77
-rw-r--r--sample/soap/babelfish.rb16
-rw-r--r--sample/soap/calc/calc.rb17
-rw-r--r--sample/soap/calc/calc2.rb29
-rw-r--r--sample/soap/calc/client.rb26
-rw-r--r--sample/soap/calc/client2.rb29
-rw-r--r--sample/soap/calc/httpd.rb20
-rw-r--r--sample/soap/calc/samplehttpd.conf2
-rw-r--r--sample/soap/calc/server.cgi15
-rw-r--r--sample/soap/calc/server.rb17
-rw-r--r--sample/soap/calc/server2.rb20
-rw-r--r--sample/soap/digraph.rb43
-rw-r--r--sample/soap/exchange/client.rb19
-rw-r--r--sample/soap/exchange/exchange.rb17
-rw-r--r--sample/soap/exchange/httpd.rb20
-rw-r--r--sample/soap/exchange/samplehttpd.conf2
-rw-r--r--sample/soap/exchange/server.cgi14
-rw-r--r--sample/soap/exchange/server.rb16
-rw-r--r--sample/soap/helloworld/hw_c.rb6
-rw-r--r--sample/soap/helloworld/hw_s.rb17
-rw-r--r--sample/soap/icd/IICD.rb17
-rw-r--r--sample/soap/icd/icd.rb46
-rw-r--r--sample/soap/raa/iRAA.rb154
-rw-r--r--sample/soap/raa/soap4r.rb30
-rw-r--r--sample/soap/raa2.4/raa.rb332
-rw-r--r--sample/soap/raa2.4/raaDriver.rb255
-rw-r--r--sample/soap/raa2.4/raaServiceClient.rb354
-rw-r--r--sample/soap/raa2.4/sample.rb115
-rw-r--r--sample/soap/sampleStruct/client.rb16
-rw-r--r--sample/soap/sampleStruct/httpd.rb20
-rw-r--r--sample/soap/sampleStruct/iSampleStruct.rb22
-rw-r--r--sample/soap/sampleStruct/sampleStruct.rb13
-rw-r--r--sample/soap/sampleStruct/samplehttpd.conf2
-rw-r--r--sample/soap/sampleStruct/server.cgi14
-rw-r--r--sample/soap/sampleStruct/server.rb20
-rw-r--r--sample/soap/ssl/files/README1
-rw-r--r--sample/soap/ssl/files/ca.cert23
-rw-r--r--sample/soap/ssl/files/client.cert19
-rw-r--r--sample/soap/ssl/files/client.key15
-rw-r--r--sample/soap/ssl/files/server.cert19
-rw-r--r--sample/soap/ssl/files/server.key15
-rw-r--r--sample/soap/ssl/files/sslclient.properties5
-rw-r--r--sample/soap/ssl/files/sslclient_require_noserverauth.properties2
-rw-r--r--sample/soap/ssl/files/sslclient_with_clientauth.properties9
-rw-r--r--sample/soap/ssl/files/subca.cert21
-rw-r--r--sample/soap/ssl/sslclient.rb12
-rw-r--r--sample/soap/ssl/sslclient_require_noserverauth.rb12
-rw-r--r--sample/soap/ssl/sslclient_with_clientauth.rb12
-rw-r--r--sample/soap/ssl/sslserver.rb49
-rw-r--r--sample/soap/ssl/sslserver_noauth.rb45
-rw-r--r--sample/soap/ssl/sslserver_require_clientauth.rb50
-rw-r--r--sample/soap/swa/client.rb13
-rw-r--r--sample/soap/swa/server.rb23
-rw-r--r--sample/soap/whois.rb14
-rw-r--r--sample/svr.rb8
-rw-r--r--sample/test.rb4
-rw-r--r--sample/webrick/httpproxy.rb26
-rw-r--r--sample/webrick/httpsd.rb4
-rw-r--r--sample/wsdl/amazon/AmazonSearch.rb3057
-rw-r--r--sample/wsdl/amazon/AmazonSearchDriver.rb536
-rw-r--r--sample/wsdl/amazon/sampleClient.rb37
-rw-r--r--sample/wsdl/amazon/wsdlDriver.rb52
-rw-r--r--sample/wsdl/googleSearch/GoogleSearch.rb258
-rw-r--r--sample/wsdl/googleSearch/GoogleSearchDriver.rb101
-rw-r--r--sample/wsdl/googleSearch/README6
-rw-r--r--sample/wsdl/googleSearch/httpd.rb20
-rw-r--r--sample/wsdl/googleSearch/sampleClient.rb56
-rw-r--r--sample/wsdl/googleSearch/samplehttpd.conf2
-rw-r--r--sample/wsdl/googleSearch/sjissearch.sh3
-rw-r--r--sample/wsdl/googleSearch/wsdlDriver.rb23
-rw-r--r--sample/wsdl/raa/raa.wsdl264
-rw-r--r--sample/wsdl/raa/soap4r.rb31
-rw-r--r--sample/wsdl/raa2.4/raa.rb332
-rw-r--r--sample/wsdl/raa2.4/wsdlDriver.rb117
-rw-r--r--signal.c5
-rw-r--r--sprintf.c18
-rw-r--r--st.c36
-rw-r--r--st.h41
-rw-r--r--string.c123
-rw-r--r--struct.c48
-rw-r--r--test/dbm/test_dbm.rb495
-rw-r--r--test/digest/test_digest.rb139
-rw-r--r--test/drb/drbtest.rb76
-rw-r--r--test/drb/ignore_test_drb.rb24
-rw-r--r--test/drb/test_drb.rb57
-rw-r--r--test/drb/test_drbssl.rb20
-rw-r--r--test/drb/test_drbunix.rb19
-rw-r--r--test/drb/ut_drb.rb19
-rw-r--r--test/drb/ut_eval.rb10
-rw-r--r--test/drb/ut_safe1.rb5
-rw-r--r--test/fileutils/fileasserts.rb34
-rw-r--r--test/fileutils/test_dryrun.rb25
-rw-r--r--test/fileutils/test_fileutils.rb585
-rw-r--r--test/fileutils/test_nowrite.rb28
-rw-r--r--test/fileutils/test_verbose.rb25
-rw-r--r--test/gdbm/test_gdbm.rb643
-rw-r--r--test/io/nonblock/test_flush.rb28
-rw-r--r--test/logger/test_logger.rb102
-rw-r--r--test/net/http/test_httpheader.rb290
-rw-r--r--test/net/http/test_https_proxy.rb30
-rw-r--r--test/nkf/test_kconv.rb71
-rw-r--r--test/nkf/test_nkf.rb16
-rw-r--r--test/openssl/ssl_server.rb14
-rw-r--r--test/openssl/test_asn1.rb197
-rw-r--r--test/openssl/test_digest.rb9
-rw-r--r--test/openssl/test_ns_spki.rb59
-rw-r--r--test/openssl/test_pair.rb144
-rw-r--r--test/openssl/test_pkcs7.rb154
-rw-r--r--test/openssl/test_pkey_rsa.rb49
-rw-r--r--test/openssl/test_ssl.rb118
-rw-r--r--test/openssl/test_x509name.rb134
-rw-r--r--test/openssl/test_x509store.rb77
-rw-r--r--test/optparse/test_noarg.rb4
-rw-r--r--test/readline/test_readline.rb84
-rw-r--r--test/rinda/test_rinda.rb144
-rw-r--r--test/rss/rss-assertions.rb351
-rw-r--r--test/rss/rss-testcase.rb14
-rw-r--r--test/rss/test_1.0.rb5
-rw-r--r--test/rss/test_dublincore.rb77
-rw-r--r--test/rss/test_image.rb165
-rw-r--r--test/rss/test_inherit.rb41
-rw-r--r--test/rss/test_maker_0.9.rb205
-rw-r--r--test/rss/test_maker_1.0.rb138
-rw-r--r--test/rss/test_maker_2.0.rb138
-rw-r--r--test/rss/test_maker_content.rb2
-rw-r--r--test/rss/test_maker_dc.rb76
-rw-r--r--test/rss/test_maker_image.rb62
-rw-r--r--test/rss/test_maker_sy.rb2
-rw-r--r--test/rss/test_maker_trackback.rb13
-rw-r--r--test/rss/test_parser.rb74
-rw-r--r--test/rss/test_setup_maker_0.9.rb221
-rw-r--r--test/rss/test_setup_maker_1.0.rb326
-rw-r--r--test/rss/test_setup_maker_2.0.rb295
-rw-r--r--test/rss/test_to_s.rb440
-rw-r--r--test/rss/test_trackback.rb10
-rw-r--r--test/rss/test_version.rb9
-rw-r--r--test/rss/test_xml-stylesheet.rb6
-rw-r--r--test/ruby/beginmainend.rb5
-rw-r--r--test/ruby/envutil.rb3
-rw-r--r--test/ruby/test_array.rb10
-rw-r--r--test/ruby/test_env.rb10
-rw-r--r--test/ruby/test_file.rb44
-rw-r--r--test/ruby/test_iterator.rb14
-rw-r--r--test/ruby/test_method.rb42
-rw-r--r--test/ruby/test_pack.rb38
-rw-r--r--test/ruby/test_rand.rb131
-rw-r--r--test/ruby/test_range.rb6
-rw-r--r--test/ruby/test_readpartial.rb74
-rw-r--r--test/ruby/test_settracefunc.rb138
-rw-r--r--test/ruby/test_signal.rb43
-rw-r--r--test/ruby/test_stringchar.rb50
-rw-r--r--test/ruby/test_super.rb117
-rw-r--r--test/ruby/test_symbol.rb50
-rw-r--r--test/ruby/ut_eof.rb13
-rw-r--r--test/runner.rb2
-rw-r--r--test/soap/asp.net/hello.wsdl96
-rw-r--r--test/soap/asp.net/test_aspdotnet.rb111
-rw-r--r--test/soap/calc/calc2.rb4
-rw-r--r--test/soap/calc/server2.rb4
-rw-r--r--test/soap/calc/test_calc.rb7
-rw-r--r--test/soap/calc/test_calc2.rb13
-rw-r--r--test/soap/calc/test_calc_cgi.rb7
-rw-r--r--test/soap/fault/test_customfault.rb58
-rw-r--r--test/soap/header/server.cgi8
-rw-r--r--test/soap/header/test_authheader.rb9
-rw-r--r--test/soap/header/test_authheader_cgi.rb7
-rw-r--r--test/soap/header/test_simplehandler.rb116
-rw-r--r--test/soap/helloworld/test_helloworld.rb7
-rw-r--r--test/soap/ssl/sslsvr.rb11
-rw-r--r--test/soap/ssl/test_ssl.rb112
-rw-r--r--test/soap/struct/test_struct.rb8
-rw-r--r--test/soap/swa/test_file.rb12
-rw-r--r--test/soap/test_basetype.rb6
-rw-r--r--test/soap/test_envelopenamespace.rb92
-rw-r--r--test/soap/test_httpconfigloader.rb39
-rw-r--r--test/soap/test_mapping.rb59
-rw-r--r--test/soap/test_no_indent.rb86
-rw-r--r--test/soap/test_property.rb46
-rw-r--r--test/soap/test_soapelement.rb5
-rw-r--r--test/soap/test_streamhandler.rb30
-rw-r--r--test/soap/test_styleuse.rb333
-rw-r--r--test/soap/wsdlDriver/calc.wsdl126
-rw-r--r--test/soap/wsdlDriver/document.wsdl54
-rw-r--r--test/soap/wsdlDriver/simpletype.wsdl6
-rw-r--r--test/soap/wsdlDriver/test_calc.rb100
-rw-r--r--test/soap/wsdlDriver/test_document.rb78
-rw-r--r--test/soap/wsdlDriver/test_simpletype.rb15
-rw-r--r--test/stringio/test_stringio.rb10
-rw-r--r--test/testunit/collector/test_dir.rb8
-rw-r--r--test/uri/test_generic.rb17
-rw-r--r--test/webrick/test_cgi.rb56
-rw-r--r--test/webrick/test_cookie.rb56
-rw-r--r--test/webrick/test_filehandler.rb65
-rw-r--r--test/webrick/test_httpauth.rb82
-rw-r--r--test/webrick/test_httprequest.rb214
-rw-r--r--test/webrick/test_httpserver.rb260
-rw-r--r--test/webrick/test_httputils.rb96
-rw-r--r--test/webrick/test_httpversion.rb40
-rw-r--r--test/webrick/test_server.rb64
-rw-r--r--test/webrick/utils.rb40
-rw-r--r--test/webrick/webrick.cgi30
-rw-r--r--test/wsdl/any/any.wsdl50
-rw-r--r--test/wsdl/any/expectedDriver.rb54
-rw-r--r--test/wsdl/any/expectedEcho.rb14
-rw-r--r--test/wsdl/any/expectedService.rb52
-rw-r--r--test/wsdl/any/test_any.rb58
-rw-r--r--test/wsdl/datetime/DatetimeService.rb42
-rw-r--r--test/wsdl/datetime/test_datetime.rb10
-rw-r--r--test/wsdl/document/document.wsdl74
-rw-r--r--test/wsdl/document/echo.rb92
-rw-r--r--test/wsdl/document/number.wsdl54
-rw-r--r--test/wsdl/document/ping_nosoapaction.wsdl66
-rw-r--r--test/wsdl/document/test_nosoapaction.rb109
-rw-r--r--test/wsdl/document/test_number.rb99
-rw-r--r--test/wsdl/document/test_rpc.rb177
-rw-r--r--test/wsdl/map/map.wsdl50
-rw-r--r--test/wsdl/map/test_map.rb70
-rw-r--r--test/wsdl/marshal/person.wsdl21
-rw-r--r--test/wsdl/marshal/person_org.rb22
-rw-r--r--test/wsdl/marshal/test_wsdlmarshal.rb80
-rw-r--r--test/wsdl/qualified/lp.rb0
-rw-r--r--test/wsdl/qualified/lp.wsdl47
-rw-r--r--test/wsdl/qualified/lp.xsd26
-rw-r--r--test/wsdl/qualified/np.wsdl50
-rw-r--r--test/wsdl/qualified/test_qualified.rb154
-rw-r--r--test/wsdl/qualified/test_unqualified.rb143
-rw-r--r--test/wsdl/raa/RAAService.rb3
-rw-r--r--test/wsdl/raa/server.rb103
-rw-r--r--test/wsdl/raa/test_raa.rb9
-rw-r--r--test/wsdl/ref/expectedProduct.rb90
-rw-r--r--test/wsdl/ref/product.wsdl86
-rw-r--r--test/wsdl/ref/test_ref.rb54
-rw-r--r--test/wsdl/rpc/echoDriver.rb55
-rw-r--r--test/wsdl/rpc/echo_serviceClient.rb23
-rw-r--r--test/wsdl/rpc/rpc.wsdl75
-rw-r--r--test/wsdl/rpc/test-rpc-lit.wsdl364
-rw-r--r--test/wsdl/rpc/test-rpc-lit12.wsdl455
-rw-r--r--test/wsdl/rpc/test_rpc.rb118
-rw-r--r--test/wsdl/rpc/test_rpc_lit.rb399
-rw-r--r--test/wsdl/simpletype/rpc/expectedClient.rb34
-rw-r--r--test/wsdl/simpletype/rpc/expectedDriver.rb62
-rw-r--r--test/wsdl/simpletype/rpc/expectedEchoVersion.rb23
-rw-r--r--test/wsdl/simpletype/rpc/expectedServant.rb32
-rw-r--r--test/wsdl/simpletype/rpc/expectedService.rb60
-rw-r--r--test/wsdl/simpletype/rpc/rpc.wsdl80
-rw-r--r--test/wsdl/simpletype/rpc/test_rpc.rb62
-rw-r--r--test/wsdl/simpletype/simpletype.wsdl38
-rw-r--r--test/wsdl/simpletype/test_simpletype.rb42
-rw-r--r--test/wsdl/soap/test_soapbodyparts.rb27
-rw-r--r--test/xmlrpc/data/bug_bool.expected3
-rw-r--r--test/xmlrpc/data/bug_bool.xml8
-rw-r--r--test/xmlrpc/data/bug_cdata.expected3
-rw-r--r--test/xmlrpc/data/bug_cdata.xml8
-rw-r--r--test/xmlrpc/data/bug_covert.expected10
-rw-r--r--test/xmlrpc/data/bug_covert.xml6
-rw-r--r--test/xmlrpc/data/datetime_iso8601.xml8
-rw-r--r--test/xmlrpc/data/fault.xml16
-rw-r--r--test/xmlrpc/data/value.expected7
-rw-r--r--test/xmlrpc/data/value.xml22
-rw-r--r--test/xmlrpc/data/xml1.expected243
-rw-r--r--test/xmlrpc/data/xml1.xml1
-rw-r--r--test/xmlrpc/test_datetime.rb159
-rw-r--r--test/xmlrpc/test_features.rb48
-rw-r--r--test/xmlrpc/test_marshal.rb93
-rw-r--r--test/xmlrpc/test_parser.rb85
-rw-r--r--test/xmlrpc/test_webrick_server.rb98
-rw-r--r--test/xmlrpc/webrick_testing.rb37
-rw-r--r--test/xsd/codegen/test_classdef.rb214
-rw-r--r--test/xsd/test_xsd.rb500
-rw-r--r--test/yaml/test_yaml.rb35
-rw-r--r--time.c25
-rw-r--r--variable.c31
-rw-r--r--version.c1
-rw-r--r--version.h16
-rw-r--r--vms/config.h102
-rw-r--r--vms/config.h_in61
-rw-r--r--vms/vms.h6
-rw-r--r--vms/vmsruby_private.c52
-rw-r--r--vms/vmsruby_private.h7
-rw-r--r--win32/Makefile.sub442
-rwxr-xr-xwin32/configure.bat60
-rwxr-xr-xwin32/ifchange.bat32
-rwxr-xr-xwin32/rm.bat8
-rw-r--r--win32/setup.mak84
-rw-r--r--win32/win32.c369
-rw-r--r--win32/win32.h62
-rw-r--r--wince/Makefile.sub477
-rw-r--r--wince/configure.bat161
-rw-r--r--wince/setup.mak14
-rw-r--r--wince/sys/types.h7
1170 files changed, 31072 insertions, 94807 deletions
diff --git a/.cvsignore b/.cvsignore
index 69a30e5f81..52a5620133 100644
--- a/.cvsignore
+++ b/.cvsignore
@@ -5,8 +5,6 @@
*~
.ccmalloc
.ppack
-.ext
-.rbconfig.time
COPYING.LIB
ChangeLog.pre-alpha
ChangeLog.pre1_1
diff --git a/ChangeLog b/ChangeLog
index bc72ba3670..027f0c2a6b 100644
--- a/ChangeLog
+++ b/ChangeLog
@@ -1,5682 +1,3 @@
-Sat Oct 29 01:58:25 2005 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * ext/etc/etc.c: document update from mathew <meta@pobox.com>.
- [ruby-core:06473]
-
- * ext/fcntl/fcntl.c: ditto.
-
-Thu Oct 27 16:45:31 2005 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * string.c (scan_once): wrong condition to use mbclen2().
- [ruby-dev:27535]
-
-Wed Oct 26 09:27:27 2005 Hirokazu Yamamoto <ocean@m2.ccsnet.ne.jp>
-
- * ext/syck/implicit.c (syck_type_id_to_uri): should return
- newly allocated memory. otherwise, type_id will be freed
- twice. [ruby-dev:27384] [ruby-core:6385]
-
-Wed Oct 26 09:04:51 2005 Hirokazu Yamamoto <ocean@m2.ccsnet.ne.jp>
-
- * ruby.h (Qfalse, Qtrue, Qnil, Qundef): make sure these immediate
- values have VALUE type. there is an environment where sizeof(VALUE)
- != sizeof(int) like IA64. if 32bit integer (Qtrue) is passed to ANYARGS
- and received by 64bit integer (VALUE), upper bits may have garbage value.
- [ruby-dev:27513]
-
-Wed Oct 26 01:58:19 2005 Nobuyoshi Nakada <nobu@ruby-lang.org>
-
- * configure.in (RUBY_EXTERN): macro to export symbols in shared
- library. [ruby-core:05528]
-
- * defines.h, {bcc32,win32,wince}/Makefile.sub (RUBY_EXTERN): moved to
- configuration pass.
-
- * ext/extmk.rb (extmake): RUBY_EXTERN for static linked extensions.
-
-Tue Oct 25 15:32:00 2005 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * lib/rational.rb: applied documentation patch from Gavin Sinclair
- <gsinclair@gmail.com>. [ruby-core:06364]
-
- * lib/irb.rb (IRB::Irb::eval_input): handle prompts with newlines
- in irb auto-indentation mode. [ruby-core:06358]
-
-Tue Oct 25 02:12:08 2005 Nobuyoshi Nakada <nobu@ruby-lang.org>
-
- * lib/rdoc/markup/simple_markup.rb (SM::SimpleMarkup::LABEL_LIST_RE):
- reduce redundant backtrack. [ruby-talk:161771]
-
-Tue Oct 25 00:27:35 2005 Masatoshi SEKI <m_seki@mva.biglobe.ne.jp>
-
- * lib/rinda/*: RDoc documentation from Eric Hodel
- <drbrain@segment7.net> added.
-
-Mon Oct 24 21:14:29 2005 Nobuyoshi Nakada <nobu@ruby-lang.org>
-
- * configure.in, io.c: use sys/syscall.h if syscall.h is not available.
- [ruby-core:06247]
-
-Mon Oct 24 20:49:45 2005 NAKAMURA Usaku <usa@ruby-lang.org>
-
- * ext/Win32API/lib/win32/resolv.rb (get_info): support multiple DNS.
- fixed: [ruby-list:40058], [ruby-dev:27479]
-
-Mon Oct 24 07:57:56 2005 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * ext/tk/lib/tk/canvas.rb (TkCanvasItemConfig::__item_val2ruby_optkeys):
- typo fixed. [ruby-talk:162187]
-
- * ext/tk/lib/tk/menu.rb (TkMenuEntryConfig::__item_val2ruby_optkeys):
- ditto. [ruby-core:06359]
-
-Sun Oct 23 21:50:15 2005 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * ext/enumerator/enumerator.c: applied documentation patch from
- James Edward Gray II <james@grayproductions.net>.
- [ruby-core:06348]
-
-Sun Oct 23 07:11:11 2005 Hidetoshi NAGAI <nagai@ai.kyutech.ac.jp>
-
- * ext/tcltklib/extconf.rb: improve messages [ruby-core:06325].
-
- * ext/tk/lib/tk.rb, ext/tk/lib/tk/canvas.rb, ext/tk/lib/tk/entry.rb,
- ext/tk/lib/tk/frame.rb, ext/tk/lib/tk/image.rb,
- ext/tk/lib/tk/itemconfig.rb, ext/tk/lib/tk/labelframe.rb,
- ext/tk/lib/tk/listbox.rb, ext/tk/lib/tk/menu.rb,
- ext/tk/lib/tk/radiobutton.rb, ext/tk/lib/tk/scale.rb,
- ext/tk/lib/tk/spinbox.rb, ext/tk/lib/tk/text.rb,
- ext/tk/lib/tk/toplevel.rb: improve conversion of option values.
-
- * ext/tk/lib/tkextlib/*: ditto.
-
- * ext/tk/lib/tkextlib/*: update to support ActiveTcl8.4.11.2.
-
- * ext/tk/lib/tkextlib/trofs/*: support Trofs 0.4.3.
-
- * ext/tk/lib/tkextlib/tile/*: support Tile 0.7.2.
-
- * ext/tk/lib/tkextlib/vu/*: support vu 2.3.0.
-
- * ext/tk/lib/tkextlib/tcllib/*: support Tcllib 1.8 (Tklib 0.3).
-
-Sat Oct 22 23:54:07 2005 Nobuyoshi Nakada <nobu@ruby-lang.org>
-
- * ext/extmk.rb, lib/mkmf.rb (with_config): support --with-extension
- options. [ruby-dev:27449]
-
-Sat Oct 22 13:26:57 2005 Nobuyoshi Nakada <nobu@ruby-lang.org>
-
- * object.c (sym_inspect), parse.y (parser_yylex, rb_symname_p): check
- if valid as a symbol name more strictly. [ruby-dev:27478]
-
- * test/ruby/test_symbol.rb: tests for [ruby-core:03573].
-
- * time.c (rb_strftime): removed meaningless volatile modifiers, and
- concatenate successive nul characters at once. [ruby-dev:27472]
-
-Fri Oct 21 19:21:56 2005 Hirokazu Yamamoto <ocean@m2.ccsnet.ne.jp>
-
- * rubysig.h (CHECK_INTS): fixed typo. (I believe bit-or is improper)
-
-Fri Oct 21 17:49:32 2005 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * bin/erb (ERB::Main::run): typo fixed. [ruby-core:06337]
-
-Fri Oct 21 15:27:17 2005 Hirokazu Yamamoto <ocean@m2.ccsnet.ne.jp>
-
- * bignum.c (bignew_1): convertion from `int' to `char' discards
- upper bits, (ie. (char)0xff00 -> 0) so it's better to test if
- nonzero and set 0 or 1 instead of simply casting ... as a flag usage.
- (but I believe this won't cause actual bug in current implementation)
- [ruby-dev:27055]
-
- * time.c: should use LONG_LONG instead of `long long'.
-
-Thu Oct 20 09:37:15 2005 Hirokazu Yamamoto <ocean@m2.ccsnet.ne.jp>
-
- * lib/mkmf.rb (create_makefile): Borland make seems not to allow
- empty dependency list. If this change is not good, please correct
- it.
-
-Thu Oct 20 07:55:09 2005 Nobuyoshi Nakada <nobu@ruby-lang.org>
-
- * lib/mkmf.rb (create_makefile): get rid of a restriction
- of Borland make. fixed: [ruby-dev:27460]
-
-Thu Oct 20 00:13:18 2005 NAKAMURA Usaku <usa@ruby-lang.org>
-
- * rubysig.h (CHECK_INTS): fix typo.
-
-Wed Oct 19 23:58:03 2005 Nobuyoshi Nakada <nobu@ruby-lang.org>
-
- * lib/mkmf.rb (create_makefile): do not create unnecessary empty
- directories. fixed: [ruby-dev:27451]
-
-Wed Oct 19 19:26:15 2005 Nobuyoshi Nakada <nobu@ruby-lang.org>
-
- * parse.y (rb_gc_mark_parser): get rid of segfault with old yacc.
- fixed: [ruby-dev:27439]
-
-Wed Oct 19 08:28:32 2005 Nobuyoshi Nakada <nobu@ruby-lang.org>
-
- * file.c (rb_file_join): elements may contain null pointer strings.
- report and fixed by Lloyd Zusman (hippoman): [ruby-core:06326]
-
-Wed Oct 19 02:34:33 2005 Nobuyoshi Nakada <nobu@ruby-lang.org>
-
- * eval.c, gc.c, time.c: made internal symbols static. [ruby-dev:27435]
-
-Wed Oct 19 01:27:07 2005 Nobuyoshi Nakada <nobu@ruby-lang.org>
-
- * regex.c (re_compile_pattern): numeric literal inside character class
- disabled succeeding backtrack. fixed: [ruby-list:41328]
-
-Mon Oct 17 21:18:50 2005 Nobuyoshi Nakada <nobu@ruby-lang.org>
-
- * parse.y (parser_heap): byacc never free parser stack.
- fixed: [ruby-dev:27428]
-
-Mon Oct 17 16:04:47 2005 NAKAMURA Usaku <usa@ruby-lang.org>
-
- * file.c (chmod_internal, lchmod_internal): fixed type of 2nd argument.
-
-Sun Oct 16 22:16:51 2005 Nobuyoshi Nakada <nobu@ruby-lang.org>
-
- * ext/extmk.rb: omit non-existing directories.
-
-Sun Oct 16 14:30:05 2005 Masatoshi SEKI <m_seki@mva.biglobe.ne.jp>
-
- * lib/rinda/rinda.rb (Rinda::Tuple#initialize): check remote hash
- tuple. fixed: [ruby-list:41227]
-
- * test/rinda/test_rinda.rb: test it.
-
-Sun Oct 16 03:38:07 2005 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * rubysig.h (CHECK_INTS): prevent signal handler to run during
- critical section. [ruby-core:04039]
-
- * eval.c (load_wait): need not to call rb_thread_schedule()
- explicitly. [ruby-core:04039]
-
- * eval.c (rb_thread_schedule): clear rb_thread_critical.
- [ruby-core:04039]
-
-Sat Oct 15 19:56:38 2005 Masatoshi SEKI <m_seki@mva.biglobe.ne.jp>
-
- * bin/erb: typo fixed, again. thanks, Doug Kearns.
-
-Fri Oct 14 22:08:26 2005 NAKAMURA Usaku <usa@ruby-lang.org>
-
- * win32/win32.c (ioctl): should set errno.
-
-Fri Oct 14 16:57:32 2005 GOTOU Yuuzou <gotoyuzo@notwork.org>
-
- * lib/webrick/config.rb (Config::FileHandler): :UserDir should be nil.
- It is harmful to permit the access to ~/public_html by default.
- suggested by Hiroyuki Iwatsuki.
-
-Thu Oct 13 23:29:51 2005 Nobuyoshi Nakada <nobu@ruby-lang.org>
-
- * parse.y (HEAPCNT): bison allocates indivisible size.
- fixed: [ruby-core:06261]
-
- * io.c, pack.c, ext/syck/rubyext.c, ext/syck/syck.h, missing/isinf.c:
- get rid of warnings. fixed: [ruby-core:06247]
-
-Wed Oct 12 12:52:57 2005 GOTOU Yuuzou <gotoyuzo@notwork.org>
-
- * ext/openssl/ossl.c (Init_openssl): should call
- OpenSSL_add_ssl_algorithms().
-
-Wed Oct 12 11:08:54 2005 WATANABE Hirofumi <eban@ruby-lang.org>
-
- * file.c (rb_f_test): typo in RDoc comments.
-
-Tue Oct 11 21:41:58 2005 Nobuyoshi Nakada <nobu@ruby-lang.org>
-
- * eval.c (rb_obj_respond_to): check if obj responds to the given
- method with the given visibility. [ruby-dev:27408]
-
- * eval.c (rb_respond_to): conform to Object#respond_to?. [ruby-dev:27411]
-
-Tue Oct 11 00:01:21 2005 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * st.c (st_free_table): do not call free() but xfree().
- [ruby-core:06205]
-
-Sat Oct 8 20:04:40 2005 Nobuyoshi Nakada <nobu@ruby-lang.org>
-
- * eval.c (Init_Binding): add Binding#dup method. [yarv-dev:666]
-
- * parse.y (rb_parser_malloc, rb_parser_free): manage parser stack on
- heap. [ruby-list:41199]
-
- * ext/iconv/charset_alias.rb: parse config.charset_alias file directly.
-
-Fri Oct 7 09:54:00 2005 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * lib/cgi.rb (CGI::Cookie::parse): Cookies from Nokia devices may
- not be parsed correctly. A patch from August Z. Flatby
- (augustzf) in [ruby-Patches-2595]. [ruby-core:06183]
-
-Thu Oct 6 20:12:16 2005 Minero Aoki <aamine@loveruby.net>
-
- * ext/strscan/strscan.c (strscan_free): remove useless code.
- [ruby-dev:26368] [ruby-dev:27389]
- (backported from trunk, rev 1.22)
-
-Wed Oct 05 04:42:38 2005 GOTOU Yuuzou <gotoyuzo@notwork.org>
-
- * lib/xmlrpc/server.rb (XMLRPC::Server#initialize): should mount the
- servlet on "/".
-
-Wed Oct 05 03:59:09 2005 GOTOU Yuuzou <gotoyuzo@notwork.org>
-
- * lib/xmlrpc/server.rb (XMLRPC::Server#serve): delete wrong call
- of "join".
-
-Mon Oct 3 00:04:00 2005 Kazuhiro NISHIYAMA <zn@mbf.nifty.com>
-
- * pack.c (EXTEND16): [ruby-dev:27383]
-
-Thu Sep 29 10:26:18 2005 Tanaka Akira <akr@m17n.org>
-
- * ext/dl/dl.c (rb_io_to_ptr): abolish sizeof(FILE).
- [ruby-dev:27317]
-
-Thu Sep 29 07:22:05 2005 Nobuyoshi Nakada <nobu@ruby-lang.org>
-
- * evalc. (rb_f_send): underscores need to be escaped.
- fixed by Doug Kearns. [ruby-core:06053]
-
-Thu Sep 29 00:57:35 2005 Nobuyoshi Nakada <nobu@ruby-lang.org>
-
- * eval.c (ev_const_get), variable.c (rb_const_get_0): retry only when
- autoload succeeded.
-
- * variable.c (rb_autoload_load): now return true if autoload
- succeeded. fixed: [ruby-dev:27331]
-
-Wed Sep 28 23:42:15 2005 Nobuyoshi Nakada <nobu@ruby-lang.org>
-
- * file.c (apply2files): add prototype.
-
- * file.c (rb_stat_inspect): constified.
-
- * class.c (rb_mod_init_copy, rb_class_init_copy), file.c (rb_stat_init_copy),
- numeric.c (num_init_copy), object.c (rb_obj_init_copy, Init_Object),
- re.c (match_init_copy, rb_reg_init_copy), time.c (time_init_copy):
- undocumented.
-
-Wed Sep 28 23:09:23 2005 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * lib/delegate.rb: document update from James Edward Gray II
- <james@grayproductions.net>. [ruby-core:06027]
-
-Wed Sep 28 15:14:19 2005 GOTOU Yuuzou <gotoyuzo@notwork.org>
-
- * lib/webrick/cgi.rb (WEBrick::CGI#start): req.query_string should
- refer the value of QUERY_STRING. [ruby-list:41186]
-
- * lib/webrick/httprequest.rb (WEBrick::HTTPRequest#query_string=):
- add new method.
-
-Wed Sep 28 10:45:44 2005 Hidetoshi NAGAI <nagai@ai.kyutech.ac.jp>
-
- * ext/tcltklib/tcltklib.c: cannot compile with Tcl/Tk8.0.x
- [ruby-dev:27335].
-
-Wed Sep 28 08:12:18 2005 Nobuyoshi Nakada <nobu@ruby-lang.org>
-
- * io.c (read_buffered_data): check if reached EOF. fixed: [ruby-dev:27334]
-
-Wed Sep 28 07:56:52 2005 Nobuyoshi Nakada <nobu@ruby-lang.org>
-
- * lib/yaml/basenode.rb (YAML::BaseNode::match_segment): fix typo.
- [ruby-dev:27237], [ruby-core:05854]
-
- * lib/yaml/tag.rb (Module#yaml_as): suppress warnings.
-
- * lib/yaml/types.rb (YAML::PrivateType, YAML::DomainType): ditto.
-
-Wed Sep 28 03:23:35 2005 NAKAMURA Usaku <usa@ruby-lang.org>
-
- * rubysig.h: fixed build problem with --enable-pthread on platforms
- which don't have setitimer().
-
-Mon Sep 26 22:32:13 2005 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * eval.c (set_trace_func): add rb_secure(4) to prevent adding
- tracing function.
-
-Sun Sep 25 12:05:10 2005 Masatoshi SEKI <m_seki@mva.biglobe.ne.jp>
-
- * bin/erb: typo fixed.
-
-Sun Sep 25 01:46:43 2005 Nobuyoshi Nakada <nobu@ruby-lang.org>
-
- * misc/ruby-mode.el (ruby-calculate-indent): arrange deep-indent
- closing parenthesis at same column as the opening.
-
-Sun Sep 25 00:42:11 2005 Nobuyoshi Nakada <nobu@ruby-lang.org>
-
- * misc/ruby-mode.el (ruby-expr-beg): deal with heredoc separately.
- fixed: [ruby-list:41168]
-
- * misc/ruby-mode.el (ruby-calculate-indent): not to deepen indent
- level for continuous line inside parentheses.
- http://nabeken.tdiary.net/20050915.html#p02
-
-Sun Sep 25 00:18:11 2005 Tanaka Akira <akr@m17n.org>
-
- * eval.c (unknown_node): show more information. [ruby-dev:26196]
-
-Sat Sep 24 08:56:01 2005 Minero Aoki <aamine@loveruby.net>
-
- * lib/fileutils.rb (cd): no longer accept :noop option, related
- code is useless (backported from trunk, rev 1.67).
- [ruby-core:05858] [ruby-Bugs:2494]
-
-Sat Sep 24 08:38:07 2005 Minero Aoki <aamine@loveruby.net>
-
- * lib/fileutils.rb: fix visibility of FileUtils::NoWrite, Verbose,
- DryRun (backported from trunk, rev 1.66). [ruby-core:05954]
-
- * test/fileutils/test_nowrite.rb: test it.
-
- * test/fileutils/test_dryrun.rb: new file.
-
- * test/fileutils/test_verbose.rb: new file.
-
-Sat Sep 24 02:40:20 2005 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * lib/delegate.rb: document update from James Edward Gray II
- <james@grayproductions.net>. [ruby-core:05942]
-
-Thu Sep 22 23:36:24 2005 Nobuyoshi Nakada <nobu@ruby-lang.org>
-
- * lib/mkmf.rb (find_executable0): default path if environment is not
- set. [ruby-dev:27281]
-
-Thu Sep 22 16:33:12 2005 Shugo Maeda <shugo@ruby-lang.org>
-
- * test/readline/test_readline.rb (TestReadline::replace_stdio):
- merged the patch of [ruby-dev:25232] instead of [ruby-dev:25223].
-
-Wed Sep 21 23:30:44 2005 Nobuyoshi Nakada <nobu@ruby-lang.org>
-
- * lib/mkmf.rb (configuration): generalized nmake dependent code.
-
-Wed Sep 21 09:07:55 2005 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * stable version 1.8.3 released.
-
-Wed Sep 21 08:52:25 2005 why the lucky stiff <why@ruby-lang.org>
-
- * ext/syck/token.c: correctly compute identation of a block
- scalar's parent node. [ruby-talk:150620]
-
-Wed Sep 21 08:20:24 2005 Nobuyoshi Nakada <nobu@ruby-lang.org>
-
- * README.EXT, README.EXT.ja: add new features.
-
-Wed Sep 21 07:43:58 2005 Nobuyoshi Nakada <nobu@ruby-lang.org>
-
- * lib/optparse.rb (default_argv, Arguable#options): defaults strings
- to be parsed to Arguable instance.
-
-Wed Sep 21 02:44:09 2005 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * file.c (path_check_0): disallow sticky world writable directory
- in PATH (and $LOAD_PATH). [ruby-dev:27226]
-
- * file.c (fpath_check): typo fixed.
-
-Tue Sep 20 22:29:49 2005 NAKAMURA, Hiroshi <nakahiro@sarion.co.jp>
-
- * test/wsdl/simpletype/rpc/test_rpc.rb, test/wsdl/ref/test_ref.rb,
- test/wsdl/any/test_any.rb test/soap/wsdlDriver/test_calc.rb:
- suppress deliberate warnings with $VERBOSE = nil.
-
-Tue Sep 20 21:26:23 2005 Nobuyoshi Nakada <nobu@ruby-lang.org>
-
- * ext/io/wait/lib/nonblock.rb: disable on platforms non-blocking flag
- is not available. fixed: [ruby-dev:27187]
-
-Tue Sep 20 18:23:04 2005 Tanaka Akira <akr@m17n.org>
-
- * eval.c (thread_mark): mark th->last_status. [ruby-dev:27179]
-
-Tue Sep 20 18:20:33 2005 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * lib/yaml.rb: require 'yaml/constants'. [ruby-core:5776]
-
-Tue Sep 20 17:48:34 2005 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * lib/xmlrpc/client.rb (XMLRPC::Client::do_rpc): add charset
- information to content-type header.[ruby-core:5127]
-
- * lib/xmlrpc/server.rb (CGIServer::serve): ditto.
-
- * lib/xmlrpc/server.rb (ModRubyServer::serve): ditto.
-
- * lib/xmlrpc/server.rb (WEBrickServlet::service): ditto.
-
-Tue Sep 20 17:34:46 2005 Hirokazu Yamamoto <ocean@m2.ccsnet.ne.jp>
-
- * test/webrick/test_cgi.rb: set ENV["PATH"] to CGIEnvPath on
- windows. bcc32's runtime is not installed into system directory,
- so it cannot be found without this setting. [ruby-dev:27166]
-
-Tue Sep 20 17:10:38 2005 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * test/dbm/test_dbm.rb (TestDBM::test_s_open_error): remove
- test_s_open_error test to detect duplicate open.
- [ruby-dev:27202]
-
-Tue Sep 20 17:08:31 2005 Hirokazu Yamamoto <ocean@m2.ccsnet.ne.jp>
-
- * io.c: PIPE_BUF is not defined on BeOS. use _POSIX_PIPE_BUF instead.
- [ruby-dev:27185]
-
-Tue Sep 20 16:53:53 2005 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * test/readline/test_readline.rb (TestReadline::replace_stdio):
- BSD seek support from [ruby-dev:25223]. fixed: [ruby-dev:27150]
-
-Tue Sep 20 15:39:40 2005 why the lucky stiff <why@ruby-lang.org>
-
- * ext/syck/emitter.c (syck_scan_scalar): prevent indicators from
- appearing alone or at the end of plain scalars. [ruby-core:5826]
-
- * ext/syck/emitter.c (syck_emit_scalar): treat typed scalar nodes
- as complex keys.
-
- * lib/syck.h: version 0.60.
-
- * lib/yaml/basenode.rb (YAML::BaseNode#at): transform keys during
- key searches.
-
- * ext/syck/rubyext.c: loading of binary-typed nodes. prevent
- emission of plain strings that look like symbols, but which aren't.
-
-Tue Sep 20 05:50:22 2005 Hirokazu Yamamoto <ocean@m2.ccsnet.ne.jp>
-
- * test/xmlrpc/test_webrick_server.rb (setup_http_server):
- should not include 'webrick/https' unless 'use_ssl' because
- it fails where openssl is not installed.
-
-Tue Sep 20 00:34:07 2005 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * io.c (io_close): call rb_io_close() directly if io is a T_FILE
- object. [ruby-dev:27156]
-
-Mon Sep 19 19:09:08 2005 Minero Aoki <aamine@loveruby.net>
-
- * file.c (rb_file_chown): should accept nil. [ruby-dev:27171]
- (backport from trunk, rev 1.208)
-
-Mon Sep 19 18:35:13 2005 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * ext/dl/dl.c (rb_io_to_ptr): fix DragonFlyBSD support.
- [ruby-dev:27151]
-
-Mon Sep 19 14:17:04 2005 Minero Aoki <aamine@loveruby.net>
-
- * ext/syck/emitter.c (syck_emit): passing an int* value to the
- long* parameter causes unaligned access on LP64 systems.
- [ruby-dev:27161]
-
-Mon Sep 19 13:44:03 2005 Masaki Suketa <masaki.suketa@nifty.ne.jp>
-
- * ext/win32ole/win32ole.c: avoid core dump with WIN32OLE_EVENT.
- [ruby-dev:27133]
-
-Mon Sep 19 10:36:06 2005 Minero Aoki <aamine@loveruby.net>
-
- * lib/fileutils.rb (cp_r): default is :dereference_root=>true for
- backward compatibility. [ruby-dev:27145]
-
- * test/fileutils/test_fileutils.rb (test_cp_r): test it.
-
-Mon Sep 19 09:57:39 2005 Minero Aoki <aamine@loveruby.net>
-
- * test/fileutils/test_fileutils.rb: backported from trunk (1.36).
- (again) [ruby-dev:27145]
-
-Mon Sep 19 07:45:37 2005 GOTOU Yuuzou <gotoyuzo@notwork.org>
-
- * ext/openssl/ossl_pkey.h, ossl_pkey_rsa.c, ossl_pkey_dsa.c:
- an instance variable "private" is added to OpenSSL::PKey class.
- this ivar is a flag that shows whether there is a private key
- in the instance.
-
- * ext/openssl/ossl_engine.c: (ossl_engine_load_privkey): set private
- key flag.
-
-Mon Sep 19 06:41:32 2005 Minero Aoki <aamine@loveruby.net>
-
- * lib/fileutils.rb: backported from trunk (rev 1.65):
-
- * lib/fileutils.rb (rm_r): new option :secure.
-
- * lib/fileutils.rb (rm_rf): new option :secure.
-
- * lib/fileutils.rb: new method #remove_entry_secure.
-
- * lib/fileutils.rb (cd): remove option :noop.
-
- * lib/fileutils.rb (cp_r): new option :dereference_root.
-
- * lib/fileutils.rb (cp_r): new option :dereference_root.
-
- * lib/fileutils.rb: new method #remove_entry.
-
- * lib/fileutils.rb: new method #chmod_R.
-
- * lib/fileutils.rb: new method #chown.
-
- * lib/fileutils.rb: new method #chown_R.
-
- * lib/fileutils.rb: new method .commands.
-
- * lib/fileutils.rb: new method .options.
-
- * lib/fileutils.rb: new method .have_option?.
-
- * lib/fileutils.rb: new method .options_of.
-
- * lib/fileutils.rb: new method .collect_method.
-
- * lib/fileutils.rb: use module_function instead of single extend.
-
- * test/fileutils/test_fileutils.rb: backported from trunk (1.36).
-
-Mon Sep 19 03:17:48 2005 Tanaka Akira <akr@m17n.org>
-
- * file.c (rb_thread_flock): wrap the flock system call by
- TRAP_BEG/TRAP_END to enable signals. [ruby-dev:27122]
-
- * ext/socket/socket.c (bsock_send): wrap the sendto and send system
- call by TRAP_BEG/TRAP_END to enable signals when writing to a socket
- which is full. [ruby-dev:27132]
-
- * io.c (rb_io_syswrite): wrap the write system call by
- TRAP_BEG/TRAP_END to enable signals when writing to a pipe which is
- full. [ruby-dev:27134]
-
-Mon Sep 19 03:02:08 2005 Tanaka Akira <akr@m17n.org>
-
- * io.c (io_fwrite): wrap the write system call by TRAP_BEG/TRAP_END to
- enable signals when writing to a pipe which is full.
-
-Sun Sep 18 02:10:47 2005 why the lucky stiff <why@ruby-lang.org>
-
- * lib/yaml/rubytypes.rb: remove comments that are bungling up
- the rdoc and ri output. output symbols as plain scalars.
-
- * ext/syck/rubyext.c (syck_emitter_reset): emit headless
- documents always.
-
- * ext/syck/emitter.c (syck_scan_scalar): quote scalars with any
- kind of surrounding line space, tabs or spaces alike.
-
- * ext/syck/token.c: accept tabs as whitespace, not for indentation,
- but strip from plain scalars.
-
- * test/yaml/test_yaml.rb: remove outdated tests.
-
-Sat Sep 17 23:25:04 2005 sheepman <sheepman@sheepman.sakura.ne.jp>
-
- * lib/mathn.rb (Rational::inspect): should preserve original
- operand. [ruby-core:05806]
-
-Sat Sep 17 23:20:27 2005 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * lib/cgi.rb (CGI::Cookie): should handle multiple values for a
- cookie name. [ruby-talk:156140]
-
-Sat Sep 17 10:42:13 2005 Hidetoshi NAGAI <nagai@ai.kyutech.ac.jp>
-
- * ext/tk/lib/multi-tk.rb: MultiTkIp#eval_string and bg_eval_string
- should call Kernel.eval on caller's safe-level instead of slave's
- safe-level (Of course, the given script should be evaluated on
- slave's safe-level).
-
-Sat Sep 17 09:45:26 2005 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * string.c (rb_str_substr): should propagate taintness even for
- empty strings. [ruby-dev:27121]
-
- * string.c (rb_str_aref): should infect result if range argument
- is tainted. [ruby-dev:27121]
-
-Sat Sep 17 08:35:39 2005 Kouhei Sutou <kou@cozmixng.org>
-
- * lib/rss/maker/base.rb (RSS::Maker::ItemsBase#normalize): fixed
- strange RSS::Maker::Item#max_size behavior.
- Thanks to Kazuhiko <kazuhiko@fdiary.net>.
-
- * test/rss/test_maker_1.0.rb (RSS::TestMaker10#test_items): ditto.
-
-Fri Sep 16 23:09:20 2005 Masaki Suketa <masaki.suketa@nifty.ne.jp>
-
- * ext/win32ole/win32ole.c (ole_search_event_at): bug fix
- in ext/win32ole/sample/ienavi.rb.
-
- * ext/win32ole/win32ole/tests/testOLEEVENT.rb: ditto.
-
-Fri Sep 16 22:41:18 2005 Nobuyoshi Nakada <nobu@ruby-lang.org>
-
- * file.c (rb_file_s_extname): empty string for path name ending with a
- period. fixed: [ruby-core:05651]
-
- * file.c (rb_file_join): smarter behavior at edge cases.
- fixed: [ruby-core:05706]
-
-Fri Sep 16 18:34:01 2005 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * ext/syck/node.c (syck_replace_str): was using return from the
- void function. a patch from MIYAMUKO Katsuyuki
- <miyamuko@mtb.biglobe.ne.jp>. [ruby-dev:27111]
-
-Fri Sep 16 14:48:48 2005 Hidetoshi NAGAI <nagai@ai.kyutech.ac.jp>
-
- * ext/tk/lib/multi-tk.rb: fix typo on MultiTkIp#bg_eval_string
-
-Fri Sep 16 12:02:12 2005 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * ext/syck/rubyext.c (syck_resolver_transfer): remove C++ style
- comment (//). [ruby-core:05793]
-
-Fri Sep 16 00:14:14 2005 NAKAMURA, Hiroshi <nakahiro@sarion.co.jp>
-
- * test/logger/test_logger.rb: unintentionally overwritten changes by
- Usa. reverted.
-
-Fri Sep 16 00:06:18 2005 GOTOU Yuuzou <gotoyuzo@notwork.org>
-
- * lib/webrick/cgi.rb (WEBrick::CGI::Socket#initialize): should set
- $stdout.binmode.
-
-Thu Sep 15 23:25:21 2005 NAKAMURA, Hiroshi <nakahiro@sarion.co.jp>
-
- * lib/{soap,wsdl,xsd}, test/{soap,wsdl,xsd}: imported soap4r/1.5.5.
-
- #nnn is a ticket number at http://dev.ctor.org/soap4r
-
- * SOAP
-
- * allow to configure an envelope namespace of SOAP request. (#124)
- TemporaryNamespace = 'http://www.w3.org/2003/05/soap-envelope'
- @client.options["soap.envelope.requestnamespace"] =
- TemporaryNamespace
- @client.options["soap.envelope.responsenamespace"] =
- TemporaryNamespace
- @client.do_proc(...)
-
- * let SOAP request XML indent space configuable. see
- "soap.envelope.no_indent" option. (#130)
-
- * let external CES configuable.
- ex. client["soap.mapping.external_ces"] = 'SJIS'. $KCODE is used
- by default. (#133)
- external CES ::= CES used in Ruby object of client and server
- internal CES ::= CES used in SOAP/OM
-
- * add iso-8859-1 external CES support. (#106)
-
- * fixed illegal 'qualified' handling of elements. it caused
- ASP.NET inteoperability problem. (#144)
-
- * added 'soap.envelope.use_numeric_character_reference' (boolean)
- option to let query XML use numeric character reference in XML,
- not plain UTF-8 character. !GoogleSearch server seems to not
- allow plain UTF-8 character since 2005-08-15 update. (#147)
-
- * SOAP::Header::SimpleHeader (de)serialization throws an exception
- on !SimpleHeader.on_(in|out)bound when header is a String. so we
- could not use a simple single element headerItem. fixed. thanks
- to emil. (#129)
-
- * out parameter of rpc operation did not work. (#132)
-
- * follow HTTP redirect only if using http-access2. (#125) (#145)
-
- * add a workaround for importing an WSDL whose path begins with
- drive letter. (#115)
-
- * WSDL
-
- * SOAP Data which is defined as a simpletype was not mapped
- correctly to Ruby obj when using wsdl2ruby.rb generated classdef
- file. (#123)
-
- * rpc/literal support. (#118)
-
- * re-implemented local element qualify/unqualify control. handles
- elementFormDefault and form in WSDL. (#119)
-
- * Array of an element which has simpleType causes a crash. (#128)
-
- * prarmeterOrder may not contain return part so it can be shorter
- than parts size. Thanks to Hugh. (#139)
-
- * Samples
-
- * added !BasicAuth client sample. (#117)
-
- * added Base64 client/server sample.
-
- * added Flickr SOAP interface client sample. (#122)
-
- * added !SalesForce client sample. (#135)
-
- * updated Thawte CA certificate for !GoogleAdWords sample.
-
- * updated a client script with the newer version made by Johan.
- thanks!
-
- * shortened long file names. (#120)
-
- * fixed typo in authheader sample. (#129)
-
- * updated deprecated method usage. (#138)
-
-Thu Sep 15 23:02:57 2005 Hirokazu Yamamoto <ocean@m2.ccsnet.ne.jp>
-
- * win32/win32.h (rb_w32_stat): added prototype.
-
-Thu Sep 15 22:35:55 2005 NAKAMURA Usaku <usa@ruby-lang.org>
-
- * test/ruby/test_signal.rb (test_exit_action): skip the test using
- fork on fork-less platforms.
-
-Thu Sep 15 11:39:18 2005 Hidetoshi NAGAI <nagai@ai.kyutech.ac.jp>
-
- * ext/tk/lib/tk/dialog.rb: If a dialog does not show up yet,
- TkDialogObj#name raises an exception. [ruby-talk:156109]
-
-Thu Sep 15 01:39:19 2005 Masatoshi SEKI <m_seki@mva.biglobe.ne.jp>
-
- * lib/rinda/tuplespace.rb (Rinda::TemplateEntry::initialize): pull
- up method. Tabs converted to spaces.
-
-Thu Sep 15 00:18:24 2005 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * lib/net/telnet.rb (Net::Telnet::waitfor): replace sysread with
- readpartial. [ruby-talk:127641]
-
-Wed Sep 14 22:40:26 2005 Nobuyoshi Nakada <nobu@ruby-lang.org>
-
- * dir.c (ruby_glob): glob function not using ruby exception system.
-
-Wed Sep 14 01:26:03 2005 Minero Aoki <aamine@loveruby.net>
-
- * lib/net/https.rb: backported from trunk, rev 1.3.
- [ruby-dev:25673] (again), [ruby-dev:26617] (again),
- [ruby-dev:27062]
-
- * ext/openssl/lib/net/https.rb: removed.
-
- * ext/openssl/lib/net/protocols.rb: removed.
-
- * lib/net/http.rb: #use_ssl?, #use_ssl are moved from net/https.
-
-Tue Sep 13 22:09:40 2005 NAKAMURA, Hiroshi <nakahiro@sarion.co.jp>
-
- * lib/logger.rb (Logger): added formatter accessor to logger for
- dictating the way in which the logger should format the messages it
- displays. Thanks to Nicholas Seckar (cf. [ruby-talk:153391]) and
- Daniel Berger.
-
- * lib/logger.rb (Logger): added VERSION constant.
-
- * lib/logger.rb: removed document for LogDevice. It is an
- implementation detail and is not a public interface.
-
- * test/logger/test_logger.rb: added tests.
-
-Tue Sep 13 21:47:17 2005 Nobuyoshi Nakada <nobu@ruby-lang.org>
-
- * eval.c (BEGIN_CALLARGS): pop halfly pushed status.
- fixed: [ruby-dev:26881]
-
-Tue Sep 13 16:26:45 2005 Minero Aoki <aamine@loveruby.net>
-
- * lib/net/http.rb: backported from trunk, rev 1.128.
- [ruby-dev:25673] [ruby-dev:26617]
-
- * lib/net/protocol.rb: backported from trunk, rev 1.78.
-
- * lib/net/protocol.rb: new method #old_open to support net/smtp
- and net/pop.
-
- * lib/net/smtp.rb: use #old_open.
-
- * lib/net/pop.rb: ditto.
-
-Tue Sep 13 12:33:05 2005 why the lucky stiff <why@ruby-lang.org>
-
- * lib/yaml.rb: reworking YAML::Stream to use the new
- emitter.
-
- * lib/yaml/stream.rb: ditto.
-
- * lib/yaml/rubytypes.rb: added Object#yaml_new.
-
- * lib/yaml/tag.rb: the tag_subclasses? method now
- shows up in the class. allow taguri to be set using an accessor.
- continue support of Object#to_yaml_type.
-
- * ext/syck/rubyext.c: new emitter code. yaml_new and yaml_initialize
- get called, should they be present. consolidated all the diaspora of internal
- node types into the family below YAML::Syck::Node -- Map,
- Seq, Scalar -- all of whom are SyckNode structs pointing to
- Ruby data. moved Object#yaml_new into the node_import and made it the
- default behavior. the target_class is always called wih yaml_new, prepended
- a parameter, which is the klass. loaded nodes through GenericResolver show their style.
- new Resolver#tagurize converts type ids to taguris.
-
- * ext/syck/implicit.re: were 'y' and 'n' seriously omitted??
-
- * ext/syck/emitter.c: renovated emitter, walks the tree in advance.
- consolidated redundant block_styles struct into
- the scalar_style struct. (this means loaded nodes can now
- be sent back to emitter and preserve at least its very basic
- formatting.)
-
- * ext/syck/gram.c: headless documents of any kind allowed.
-
- * ext/syck/node.c: new syck_replace_str methods and syck_empty_*
- methods for rewriting node contents, while keeping the ID
- and other setup info. added syck_seq_assign.
-
- * ext/syck/syck.h: reflect block_styles and new node functions.
-
-Mon Sep 12 20:53:06 2005 GOTOU Yuuzou <gotoyuzo@notwork.org>
-
- * test/openssl/test_pkcs7.rb (test_enveloped): skip this test
- to avoid a bug of PKCS7_enctypt() (only if ext/openssl is
- compiled with OpenSSL-0.9.7d or earlier versions).
- http://www.mail-archive.com/openssl-dev@openssl.org/msg17376.html
-
-Mon Sep 12 14:03:33 2005 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * test/dbm/test_dbm.rb: remove locking test, which may not be
- supported on some platforms. [ruby-dev:27030]
-
-Mon Sep 12 10:45:58 2005 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * ext/dl/dl.c (rb_io_to_ptr): merged a patch for DragonFly BSD
- from Takahiro Kambe <taca@back-street.net>. [ruby-dev:27023]
-
-Sun Sep 11 22:05:51 2005 Masatoshi SEKI <m_seki@mva.biglobe.ne.jp>
-
- * bin/erb (ERB::Main#run): set ERB#filename so that it is used
- when reporting syntax/runtime errors. Tabs converted to spaces.
-
-Sat Sep 10 10:17:03 2005 GOTOU Yuuzou <gotoyuzo@notwork.org>
-
- * ext/openssl/ossl_engine.c (ossl_engine_s_by_id):
- OpenSSL::Engine.by_id calls given block before calling
- ENGINE_init (block parameter is the return value of this method
- itself). this functionality is useful to load dynamic shared
- engines. the following code is a sample of loading a key using
- OpenSC PKCS #11 module.
-
- require "openssl"
- pkcs11 = OpenSSL::Engine.by_id("dynamic"){|e|
- e.ctrl_cmd("SO_PATH", "/usr/lib/opensc/engine_pkcs11.so")
- e.ctrl_cmd("LIST_ADD", "1")
- e.ctrl_cmd("LOAD")
- }
- pkcs11.ctrl_cmd("PIN", "secret")
- key = pkcs11.load_private_key
-
- * ext/openssl/ossl_engine.c (ossl_engine_ctrl_cmd): new method
- OpenSSL::Engine#ctrl_cmd. it wraps ENGINE_ctrl_cmd_string.
-
- * ext/openssl/ossl_engine.c (ossl_engine_get_cmds): new method
- OpenSSL::Engine#cmds. it returms engine command definitions.
-
-Sat Sep 10 10:09:47 2005 GOTOU Yuuzou <gotoyuzo@notwork.org>
-
- * ext/openssl/ossl_asn1.c (asn1str_to_str): new function.
-
- * ext/openssl/ossl_pkcs7.c: new class OpenSSL::PKCS7::RecipientInfo.
- this class wraps PKCS7_RECIP_INFO struct.
-
- * ext/openssl/ossl_pkcs7.c: OpenSSL::PKCS7::Signer is renamed to
- OpenSSL::PKCS7::SignerInfo. ("Signer" remains as an alias of
- SignerInfo.)
-
- * test/openssl/test_pkcs7.rb: new file.
-
-Sat Sep 10 10:05:51 2005 GOTOU Yuuzou <gotoyuzo@notwork.org>
-
- * ext/openssl/ossl_ns_spki.c (ossl_spki_initialize): assume that
- the argument is a DER string if Base64 decoding failed.
-
- * ext/openssl/ossl_ns_pki.c (ossl_spki_to_der): new method.
-
- * test/openssl/test_ns_spki.rb: add new file.
-
-Sat Sep 10 09:56:24 2005 GOTOU Yuuzou <gotoyuzo@notwork.org>
-
- * ext/openssl/lib/digest.rb: added SHA224, SHA256, SHA384 and SHA512.
- these features are enabled if this library is compiled with
- OpenSSL 0.9.8 or later.
-
- * test/openssl/test_digest.rb: add test for new digests.
-
-Sat Sep 10 09:51:30 2005 GOTOU Yuuzou <gotoyuzo@notwork.org>
-
- * ext/openssl/ossl.c (ossl_raise): should use ERR_peek_last_error
- to get last error on the current thread. And should report
- errors on the stack while OpenSSL.debug is true.
-
- * ext/openssl/ossl.c (ossl_get_errors): new method for debugging
- this library.
-
- * ext/openssl/ossl_ssl.c (ossl_sslctx_set_ciphers): fix error message.
-
- * ext/openssl/ossl_x509req.c (ossl_x509req_set_attributes): get rid
- of unused variable.
-
- * ext/openssl/ossl_x509store.c (ossl_x509store_initialize): should
- set @time to avoid warning.
-
- * ext/openssl/ossl_x509store.c (ossl_x509store_set_default_paths,
- X509_STORE_add_cert, X509_STORE_add_crl): should raise error if
- wrapped functions failed.
-
- * test/openssl/test_x509store.rb: add test for errors.
-
-Fri Sep 9 22:13:19 2005 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * eval.c (rb_call0): prohibit calling tainted method (>2) when
- $SAFE == 0.
-
-Fri Sep 9 16:45:25 2005 Nobuyoshi Nakada <nobu@ruby-lang.org>
-
- * string.c (rb_str_times): make empty strings to keep taintness,
- and a little improvement. [ruby-dev:26900]
-
- * ext/iconv/iconv.c (iconv_try), ext/iconv/extconf.rb: get rid of meta
- characters in command line option. fixed: [ruby-talk:155369]
-
-Thu Sep 8 14:58:11 2005 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * merged a patch from Takahiro Kambe <taca@back-street.net> to
- support DragonFly BSD. [ruby-dev:26984]
-
-Wed Sep 7 12:55:08 2005 Tanaka Akira <akr@m17n.org>
-
- * lib/open-uri.rb: abolish mod === tempfile to avoid a problem
- [ruby-dev:26967].
-
-Wed Sep 7 10:45:15 2005 Nobuyoshi Nakada <nobu@ruby-lang.org>
-
- * eval.c (rb_thread_switch): convert all exceptions to
- SystemExit. fixed: [ruby-core:05724]
-
- * eval.c (rb_thread_terminated): show backtrace before propagate
- exceptions to main thread.
-
-Wed Sep 7 08:35:04 2005 Nobuyoshi Nakada <nobu@ruby-lang.org>
-
- * Makefile.in, configure.in (MINIOBJS): miniruby on HP-UX can not load
- extension libraries.
-
- * bignum.c (bignew_1, bigadd): K&R style argument actually can't be
- defined as char.
-
- * missing/vsnprintf.c: ANSI compiler supports const keyword.
-
- * ext/digest/sha2/extconf.rb: reject platforms which has inttypes.h
- but no 64bit integer.
-
- * lib/mkmf.rb (what_type?): guesstimate type.
-
- * ext/etc/etc.c (setup_passwd), ext/etc/extconf.rb: pw_age might be
- char*. fixed: [ruby-core:05470]
-
-Wed Sep 7 08:32:47 2005 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * object.c (rb_mod_cvar_get, rb_mod_cvar_set): document fix from
- sheepman <sheepman@sheepman.sakura.ne.jp>; a bug in visibility
- description. [ruby-dev:26965]
-
- * sprintf.c (rb_f_sprintf): warn "too many argument" on verbose
- mode (-v/-w); backported from 1.9. [ruby-dev:26963]
-
-Mon Sep 5 17:03:07 2005 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * lib/ostruct.rb: a patch from Florian Gross <florgro@gmail.com>
- merged to allow recursive inspect (and to_s) for OpenStruct.
- [ruby-core:05532]
-
-Mon Sep 5 07:01:12 2005 GOTOU Yuuzou <gotoyuzo@notwork.org>
-
- * ext/openssl/openssl/lib/openssl/buffering.rb (Buffering#do_write):
- should clear data from the buffer which already been output.
-
-Fri Sep 2 23:51:54 2005 Nobuyoshi Nakada <nobu@ruby-lang.org>
-
- * lib: do not use __send__ to access private methods. [ruby-dev:26935]
-
-Fri Sep 2 03:29:00 2005 Keiju Ishitsuka <keiju@ruby-lang.org>
-
- * lib/irb/init.rb: make IRB -I option that is same befavior for ruby.
- [ruby-dev:26872], [ruby-dev: 26920]
-
- * lib/irb/locale.rb: support to print help message when OS locale is
- ja_JP.utf-8. [ruby-dev:26872]
-
-Thu Sep 1 17:11:25 2005 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * eval.c (rb_call0): wrong condition for $SAFE restoration.
-
-Thu Sep 1 14:12:45 2005 Hidetoshi NAGAI <nagai@ai.kyutech.ac.jp>
-
- * ext/tk/lib/multi-tk.rb: On Tcl8.5, MultiTkIp#invoke_hidden doesn't
- work (gives wrong order of arguments).
-
- * ext/tk/lib/multi-tk.rb: add MultiTkIp#invoke_hidden_on_namespace
- to support '-namespace' option of 'interp invokehidden' command
- on Tcl8.5.
-
-Wed Aug 31 14:43:15 2005 NAKAMURA Usaku <usa@ruby-lang.org>
-
- * win32/Makefile.sub (OPTFLAGS): default global optimization to
- disabled for all VC++ versions. fixed: [ruby-dev:26897]
-
-Wed Aug 31 11:35:43 2005 NAKAMURA Usaku <usa@ruby-lang.org>
-
- * test/gdbm/test_gdbm.rb (teardown): should remove GDBM temporary
- file.
-
-Wed Aug 31 10:30:56 2005 Hirokazu Yamamoto <ocean@m2.ccsnet.ne.jp>
-
- * process.c (proc_detach, proc_setmaxgroups): missing argument type
- declaration. (I recommend ANSI-style function)
-
-Tue Aug 30 23:20:19 2005 Nobuyoshi Nakada <nobu@ruby-lang.org>
-
- * eval.c (rb_rescue2): initialization miss. fixed: [ruby-dev:26917]
-
- * lib/mkmf.rb (xsystem, xpopen): no longer expand by Config.
-
- * lib/mkmf.rb (link_command, cc_command, cpp_command): expand
- variables at once, and quote hdrdir. fixed: [ruby-core:05680]
-
- * lib/mkmf.rb (libpathflag): quote paths.
-
-Tue Aug 30 19:34:27 2005 GOTOU Yuuzou <gotoyuzo@notwork.org>
-
- * ext/digest/md5/md5ossl.h, ext/digest/rmd160/rmd160ossl.h,
- ext/digest/sha1/sha1ossl.h: include <stddef.h> to avoid
- error in compilation with OpenSSL-0.9.8. [ruby-list:41068]
-
-Mon Aug 29 19:54:21 2005 Hirokazu Yamamoto <ocean@m2.ccsnet.ne.jp>
-
- * lib/rdoc/usage.rb: improper exceptions. [ruby-dev:26870]
-
- * lib/rdoc/usage.rb: support the case when non-ruby code exists before
- shebang. (this is needed when ri.bat is executed on windows)
-
-Mon Aug 29 17:48:17 2005 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * eval.c (method_arity): should return proper arity value.
- [ruby-dev:26390]
-
-Mon Aug 29 01:19:57 2005 Tanaka Akira <akr@m17n.org>
-
- * lib/time.rb (Time.parse): extract fractional seconds using
- Date._parse. [ruby-talk:153859]
-
-Sat Aug 27 20:20:01 2005 Hirokazu Yamamoto <ocean@m2.ccsnet.ne.jp>
-
- * ext/curses/curses.c ({curses,window}_clrtoeol): added. suggested
- by Reyn Vlietstra.
-
- * ext/curses/curses.c: chtype in curses is not `char', rahter `long'.
- [ruby-Bugs:2298]
-
- * ext/curses/view.rb: String =~ String is deprecated.
-
-Wed Aug 24 10:53:28 2005 NAKAMURA Usaku <usa@ruby-lang.org>
-
- * test/logger/test_logger.rb (test_shifting_size): should close log
- device before unlink, since some platform cannot unlink opened
- file.
-
-Sun Aug 21 00:13:27 2005 NAKAMURA, Hiroshi <nakahiro@sarion.co.jp>
-
- * lib/wsdl/xmlSchema/importer.rb (WSDL::XMLSchema::Importer#fetch): add
- a workaround for importing an WSDL whose path begins with drive
- letter. [ruby-dev:26242]
-
-Sat Aug 20 22:37:13 2005 NAKAMURA, Hiroshi <nakahiro@sarion.co.jp>
-
- * lib/logger.rb (write, shift_log?, shift_log): file shifting race
- condition bug fixed. [ruby-dev:26764]
-
- * test/logger/test_logger.rb: tests.
-
-Fri Aug 19 18:13:39 2005 Tanaka Akira <akr@m17n.org>
-
- * lib/time.rb (Time.apply_offset): fix a problem with last day of
- month. reported by Lucas Nussbaum. [ruby-talk:152866]
-
-Thu Aug 18 12:46:28 2005 Hirokazu Yamamoto <ocean@m2.ccsnet.ne.jp>
-
- * bcc32/Makefile.sub (COMMON_HEADERS): reverted 1.42.2.24.
- I misunderstood, bccwin32 on ruby_1_8 uses winsock2 originally.
- [ruby-dev:26806]
-
- * win32/win32.h: include winsock2.h instead of winsock.h. (bcc32)
-
-Wed Aug 17 23:58:05 2005 Nobuyoshi Nakada <nobu@ruby-lang.org>
-
- * object.c (rb_to_integer): argument constified.
-
- * eval.c (terminate_process): take String message.
-
- * eval.c (rb_thread_switch): propagate the exception caused thread
- termination directly. fixed: [ruby-core:05552]
-
-Wed Aug 17 00:05:46 2005 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * eval.c (rb_add_method): preserve safe level in the environment
- where a method is defined .
-
- * eval.c (rb_call0): restore preserved safe level in the method
- execution.
-
-Mon Aug 15 00:38:51 2005 Nobuyoshi Nakada <nobu@ruby-lang.org>
-
- * eval.c (rb_rescue2): reduce PUSH_TAG() as well as NODE_RESCUE.
- [ruby-dev:26800]
-
- * range.c (range_check, range_init): reduce useless exceptions.
-
-Sat Aug 13 18:51:26 2005 Nobuyoshi Nakada <nobu@ruby-lang.org>
-
- * eval.c (rb_block_pass): distinguish current block from others.
- fixed: [ruby-dev:26274]
-
- * ext/stringio/stringio.c (strio_set_string): disallow nil.
- http://www.rubyist.net/~nobu/t/20050811.html#c05
-
-Thu Aug 11 23:29:03 2005 Nobuyoshi Nakada <nobu@ruby-lang.org>
-
- * ext/stringio/stringio.c: keep holding string after closed.
-
-Thu Aug 11 13:01:48 2005 Kouhei Sutou <kou@cozmixng.org>
-
- * lib/rss: fixed sort bug. [ruby-list:41018]
-
- * lib/rss/1.0.rb (RSS::RDF::Channel#setup_maker_attributes):
- removed self.
-
- * lib/rss/maker/base.rb (RSS::Maker::ItemsBase#<=>): use #date
- instead of @date.
- (RSS::Maker::Base::self.def_array_element): added #size.
-
- * lib/rss/maker/1.0.rb
- (RSS::Maker::RSS10::Channel#to_rss,
- RSS::Maker::RSS10::Items::Item#to_rss): cleared dc_dates set
- upped by using #date.
-
- * lib/rss/maker/dublincore.rb
- (RSS::Maker::ChannelBase, RSS::Maker::ItemsBase::ItemBase):
- fixed opposite alias.
-
- * test/rss/test_setup_maker_1.0.rb
- (RSS::TestSetupMaker10::test_setup_maker_items_sort): added some
- tests for RSS::Maker::ItemsBase#do_sort.
-
-Wed Aug 10 10:29:40 2005 Hidetoshi NAGAI <nagai@ai.kyutech.ac.jp>
-
- * ext/tk/lib/tk.rb: fix bug on handling __ruby2val_optkeys().
-
- * ext/tk/lib/tk/itemconfig.rb: fix bug on handling
- __item_ruby2val_optkeys().
-
- * ext/tk/lib/tk/canvas.rb: didn't check __item_ruby2val_optkeys().
-
- * ext/tk/lib/tkextlib/blt/component.rb: ditto.
-
-Tue Aug 9 15:12:04 2005 Hidetoshi NAGAI <nagai@ai.kyutech.ac.jp>
-
- * ext/tcltklib/tcltklib.c: remove dangerous 'rb_jump_tag's.
-
- * ext/tk/lib/tk.rb: add __val2ruby_optkeys and __ruby2val_optkeys to
- help to convert option values between ruby and tcl.
-
- * ext/tk/lib/tk/itemconfig.rb: add __item_val2ruby_optkeys and
- __item_ruby2val_optkeys to help to convert option values between
- ruby and tcl.
-
- * ext/tk/lib/tk/radiobutton.rb: use __ruby2val_optkeys for 'variable'
- option (for the reason of backward compatibility).
-
- * ext/tk/lib/tk/composite.rb: clarify the arguments of super().
-
- * ext/tk/lib/tk/spinbox.rb: ditto.
-
- * ext/tk/lib/tk/text.rb: ditto.
-
- * ext/tk/lib/tk/validation.rb: ditto.
-
- * ext/tk/lib/tkextlib/*: support to treat tkvariable-type
- configure options.
-
-Tue Aug 9 20:30:19 2005 Tadashi Saito <shiba@mail2.accsnet.ne.jp>
-
- * bignum.c (rb_big_coerce): allow bignum x bignum coercing.
- [ruby-dev:26778]
-
-Mon Aug 8 20:43:02 2005 NAKAMURA, Hiroshi <nakahiro@sarion.co.jp>
-
- * test/ruby/test_method.rb: added. [ruby-dev:26761]
-
-Sun Aug 7 23:50:14 2005 NAKAMURA, Hiroshi <nakahiro@sarion.co.jp>
-
- * test/ruby/test_super.rb: added from HEAD. [ruby-dev:26743]
-
-Sun Aug 7 01:31:15 2005 Masaki Suketa <masaki.suketa@nifty.ne.jp>
-
- * ext/win32ole/win32ole.c (WIN32OLE_EVENT#on_event): should set
- only one event handler.
-
- * ext/win32ole/tests/testOLEEVENT.rb: ditto.
-
- * ext/win32ole/tests/testOLEPARAM.rb: remove re-defined
- test_ole_type_detail method.
-
-Sat Aug 6 12:35:24 2005 Hidetoshi NAGAI <nagai@ai.kyutech.ac.jp>
-
- * ext/tk/lib/{tk.rb,tk/itemconfig.rb}: configure creates
- TkVariable if key name is 'variable' or 'textvariable'
- by default. [ruby-dev:26749]
-
- * ext/tk/lib/tk/{label,radiobutton}.rb: removed its own
- {variable,textvariable} function.
-
- * ext/tk/lib/tk/variable.rb: retains backward conpatibility.
-
-Fri Aug 5 12:50:32 2005 Hirokazu Yamamoto <ocean@m2.ccsnet.ne.jp>
-
- * ext/tcltklib/tcltklib.c: fixed memory leak when tk_funcall raised
- exception. (copies argv into heap in tk_funcall instead of
- caller)
-
-Fri Aug 5 12:42:57 2005 NAKAMURA Usaku <usa@ruby-lang.org>
-
- * lib/mkmf.rb (create_makefile): need to convert path separetor
- before invoking install command.
-
-Fri Aug 5 00:27:04 2005 Hirokazu Yamamoto <ocean@m2.ccsnet.ne.jp>
-
- * ext/tcltklib/tcltklib.c: refactoring - extract ruby string <->
- tcl object conversion as get_str_from_obj and get_obj_from_str.
-
-Fri Aug 5 00:19:33 2005 Nobuyoshi Nakada <nobu@ruby-lang.org>
-
- * extmk.rb (extmake): needs to be wrapped in an Array.
-
-Thu Aug 4 18:38:36 2005 Hidetoshi NAGAI <nagai@ai.kyutech.ac.jp>
-
- * ext/tcltklib/tcltklib.c: cannot compile for Tcl7.6/Tk4.2.
-
- * ext/tcltklib/tcltklib.c: add nativethread consistency check.
-
- * ext/tcltklib/stubs.c: ditto.
-
- * ext/tk/lib/tk.rb: forgot to define TclTkIp.encoding and encoding=
- when Tcl is 7.6 or 8.0.
-
- * ext/tk/lib/tk/wm.rb: support to make some methods as options of
- root or toplevel widget. [ruby-talk:150336]
-
- * ext/tk/lib/tk/root.rb: ditto.
-
- * ext/tk/lib/tk/toplevel.rb: ditto.
-
- * ext/tk/lib/tkextlib/SUPPRT_STATUS: update RELEASE_DATE
-
-Thu Aug 4 08:03:39 2005 Nobuyoshi Nakada <nobu@ruby-lang.org>
-
- * ext/extmk.rb (extmake): should not modify $mflags for each
- extentions.
-
-Thu Aug 4 00:25:48 2005 Nobuyoshi Nakada <nobu@ruby-lang.org>
-
- * common.mk, Makefile.in, {bcc32,win32,wince}/Makefile.sub: integrated
- macro definitions.
-
- * bcc32/Makefile.sub: LIBRUBY_SO should use DLDOBJS, not EXTOBJS.
-
- * {win32,wince}/Makefile.sub: separate config.h for compiler versions.
-
-Wed Aug 3 21:59:16 2005 Hidetoshi NAGAI <nagai@ai.kyutech.ac.jp>
-
- * ext/tk/lib/tk/variable.rb: TkVariable#trace didn't work on
- TkVariable retrived from TkVariable.new_hash.ref. [ruby-dev:26721]
-
-Wed Aug 3 08:22:13 2005 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * ext/socket/socket.c (ruby_connect): revert [ruby-talk:111654]
- changes at 2004-09-07. [ruby-dev:26656]
-
-Tue Aug 2 10:20:54 2005 Hirokazu Yamamoto <ocean@m2.ccsnet.ne.jp>
-
- * ext/tcltklib/tcltklib.c: use Tcl_[GS]etVar2Ex instead of
- Tcl_Obj[GS]etVar2. (avoid Tcl_NewStringObj on supported platforms)
-
- * ext/tcltklib/tcltklib.c: use ip_{get,set,unset}_variable2_core from
- ip_{get,set,unset}_variable.
-
- * ext/tcltklib/tcltklib.c: replaced Tcl_Panic with rb_bug.
-
-Tue Aug 2 01:41:28 2005 GOTOU Yuuzou <gotoyuzo@notwork.org>
-
- * lib/ping.rb (Ping.pingecho): should rescue StandardError.
- [ruby-dev:26677]
-
-Mon Aug 1 19:09:41 2005 Hirokazu Yamamoto <ocean@m2.ccsnet.ne.jp>
-
- * ext/tcltklib/tcltklib.c: refactoring - replaced rb_ivar_defined &
- rb_ivar_get with single rb_attr_get call.
-
-Mon Aug 1 18:45:07 2005 Hirokazu Yamamoto <ocean@m2.ccsnet.ne.jp>
-
- * ext/tcltklib/tcltklib.c (Tcl_GetStringResult): refactoring - define
- alternative macro on Tcl7.x or earlier.
-
-Mon Aug 1 13:57:35 2005 Hirokazu Yamamoto <ocean@m2.ccsnet.ne.jp>
-
- * ext/tcltklib/tcltklib.c (deleted_ip): refactoring - interpreter
- deletion check. [ruby-dev:26664]
-
-Mon Aug 1 01:17:40 2005 Masatoshi SEKI <m_seki@mva.biglobe.ne.jp>
-
- * lib/drb/drb.rb (check_insecure_method): use private_methods and
- protected_methods instead of respond_to? to check method visibility.
- [ruby-dev:26616]
-
- * test/drb/drbtest.rb: ditto.
-
- * test/drb/ut_drb.rb: ditto.
-
-Mon Aug 1 00:07:32 2005 Keiju Ishitsuka <keiju@ruby-lang.org>
- * lib/irb/context.rb: fix `irb --readline` option. [ruby-list:40955]
-
-Fri Jul 29 09:59:38 2005 Nobuyoshi Nakada <nobu@ruby-lang.org>
-
- * eval.c (rb_yield_0): push yielded node instead of yielding.
- fixed: [yarv-dev:549]
-
-Thu Jul 28 18:09:55 2005 Hidetoshi NAGAI <nagai@ai.kyutech.ac.jp>
-
- * ext/tcltklib/stubs.c: When --enable-tcltk-stubs, the initialize
- routine creates a Tcl/Tk interpreter and deletes it. However,
- init cost of Tk's MainWindow is not so small. And that makes it
- impossible to use libraries written with Tcl functions only on
- an environment without a graphical display. This changes support
- delaying initalization of Tk_Stubs until the script needs Tk.
-
- * ext/tcltklib/stubs.h: New file. Define prototypes and return
- codes of functions on stubs.c.
-
- * ext/tcltklib/tcltklib.c: Support delaying initalization of
- Tk_Stubs until the script needs Tk.
-
- * ext/tcltklib/tcltklib.c: Show friendly error messages for errors
- on initialization.
-
- * ext/tcltklib/tcltklib.c: Avoid SEGV on ip_finalize() when ruby is
- exiting and $DEBUG is true. (Not fix. If you know the reason of
- why, please fix it.)
-
- * ext/tk/tkutil.c (ary2list, ary2list2): bug fix on handling of
- encoding.
-
- * ext/tk/lib/multi-tk.rb: MultiTkIp#eval_string and bg_eval_string
- don't work propery.
-
- * ext/tk/lib/tk.rb: Forget extending Tk::Encoding module to Tk.
- * ext/tk/lib/tk/variable.rb: TkVarAccess fails to initialize the
- object for an element of a Tcl's array variable.
-
-Wed Jul 27 23:23:54 2005 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * gc.c (obj_free): make message format consistent with one from
- gc_mark(). [ruby-talk:149668]
-
-Wed Jul 27 22:11:37 2005 Kouhei Sutou <kou@cozmixng.org>
-
- * sample/rss/tdiary_plugin: removed. because the plugin
- is imported in the tDiary plugin packages.
-
-Wed Jul 27 10:59:02 2005 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * dir.c (dir_each): rewinddir(3) before iteration.
- [ruby-talk:149628]
-
-Tue Jul 26 12:57:49 2005 GOTOU Yuuzou <gotoyuzo@notwork.org>
-
- * ext/openssl/openssl_missin.c: include <openssl/engine.h> before
- <openssl/x509_vfy.h> to avoid compilation error of mswin32.
- suggested by NAKAMURA Usaku.
-
-Mon Jul 25 21:30:46 2005 Nobuyoshi Nakada <nobu@ruby-lang.org>
-
- * {bcc32,win32,wince}/Makefile.sub: moved CPPFLAGS only for ruby
- source to XCFLAGS.
-
-Mon Jul 25 13:45:18 2005 NAJIMA Hiroki <najima@mickey.ai.kyutech.ac.jp>
-
- * io.c: check HAVE_SYS_IOCTL_H before including the header.
- [ruby-dev:26610]
-
-Mon Jul 25 14:10:02 2005 Hidetoshi NAGAI <nagai@ai.kyutech.ac.jp>
-
- * ext/tk/lib/multi-tk.rb: fix en-bugged part in the last commit.
-
-Sat Jul 23 16:49:04 2005 GOTOU Yuuzou <gotoyuzo@notwork.org>
-
- * ext/openssl/ossl_engine.c (ossl_engine_s_load): should check
- OPENSSL_NO_STATIC_ENGINE.
-
-Fri Jul 22 21:06:08 2005 Tadashi Saito <shiba@mail2.accsnet.ne.jp>
-
- * bignum.c (rb_big_eq): reduce isnan(). [ruby-dev:26600]
-
- * numeric.c (flo_eq, flo_gt, flo_ge, flo_lt, flo_le): ditto.
-
-Fri Jul 22 15:02:39 2005 Kouhei Sutou <kou@cozmixng.org>
-
- * lib/rss/rss.rb: moved copyright description to lib/rss.rb.
-
- * lib/rss.rb: added for convenience.
-
- * sample/rss/re_read.rb: added #to_s sample.
-
- * sample/rss/blend.rb: use 'require "rss"' instead of
- 'require "rss/*"'.
- * sample/rss/list_description.rb: ditto.
- * sample/rss/rss_recent.rb: ditto.
- * sample/rss/tdiary-plugin/rss-recent.rb: ditto.
-
- * sample/rss/tdiary-plugin/rss-recent.rb: 0.0.6 -> 0.0.7.
-
-Fri Jul 22 14:37:43 2005 Kouhei Sutou <kou@cozmixng.org>
-
- * lib/rss/parser.rb (RSS::Parser#initialize): accept HTTP/FTP
- URI and local file path too.
-
- * test/rss/test_parser.rb (RSS::TestParser#test_parse): test
- for the above.
-
-Fri Jul 22 07:01:42 2005 Hidetoshi NAGAI <nagai@ai.kyutech.ac.jp>
-
- * ext/tk/tkutil.c (tk_conv_args): forget to revert thread_critical
- and gc_disable when raise ArgumentError.
-
- * ext/tk/lib/remote-tk.rb: RemoteTkIp doesn't need to include TkUtil.
-
- * ext/tcltklib/tcltklib.c: add TclTkIp#has_mainwindow? method.
-
- * ext/tk/lib/tk.rb: add Tk.has_mainwindow? method.
-
- * ext/tk/lib/multi-tk.rb: add MultiTkIp#has_mainwindow? method.
-
- * ext/tk/lib/remote-tk.rb: add RemoteTkIp#has_mainwindow? method.
-
- * ext/tk/lib/multi-tk.rb: slave IP fail to exit itself when $SAFE==4.
-
- * ext/tk/lib/multi-tk.rb: remove constants from MultiTkIp module to
- avoid access from external.
-
- * ext/tk/lib/multi-tk.rb: check_root flag is ignored on slave IPs'
- mainloop.
-
- * ext/tk/lib/multi-tk.rb: hang-up Tk.mainloop called on a slave IP
- with $SAFE==4.
-
- * ext/tk/lib/multi-tk.rb: MultiTkIp#bg_eval_proc doesn't work
- properly.
-
- * ext/tk/lib/multi-tk.rb: add MultiTkIp#set_cb_error(proc) and
- cb_error(exc) to log errors at callbacks on safe slave IPs.
-
- * ext/tk/lib/multi-tk.rb: fail to get an available slave IP object
- when call Tk.mainloop in the block which is given to new_* method,
- because cannot finish initialize while the root widget is alive.
-
- * ext/tk/lib/multi-tk.rb: fail to control a slave IP when Tk.mainloop
- runs on the IP.
-
-Wed Jul 20 19:20:37 2005 NAKAMURA Usaku <usa@ruby-lang.org>
-
- * io.c (S_ISREG): need to define S_ISREG before it is used first.
-
-Wed Jul 20 18:40:50 2005 Hirokazu Yamamoto <ocean@m2.ccsnet.ne.jp>
-
- * io.c (wsplit_p): patch for the environment where
- fcntl(F_GETFL, O_NONBLOCK) is not supported. in that case,
- set FMODE_WSPLIT without fcntl check. [ruby-dev:26566]
-
-Wed Jul 20 18:07:11 2005 Tanaka Akira <akr@m17n.org>
-
- * io.c (rb_io_ctl): update FMODE_WSPLIT_INITIALIZED and FMODE_WSPLIT
- by F_SETFL.
-
-Wed Jul 20 10:04:51 2005 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * variable.c (rb_class_path): need to adjust snprintf() len for
- teminating NUL. [ruby-dev:26581]
-
-Wed Jul 20 04:01:55 2005 Hirokazu Yamamoto <ocean@m2.ccsnet.ne.jp>
-
- * ext/socket/socket.c: sorry, BeOS also uses HAVE_CLOSESOCKET,
- so reverted.
-
- * ext/socket/extconf.rb: should not define HAVE_CLOSESOCKET
- on windows.
-
-Wed Jul 20 03:16:43 2005 Hirokazu Yamamoto <ocean@m2.ccsnet.ne.jp>
-
- * ext/socket/socket.c: should not undef close() on win32.
- it's defined to rb_w32_close(), otherwise handle leaks.
- [ruby-Bugs-2131]
-
-Wed Jul 20 00:48:16 2005 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * error.c (syserr_initialize): don't use str before StringValue()
- check. [ruby-dev:26579]
-
-Tue Jul 19 22:47:29 2005 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * error.c (syserr_initialize): add 1 byte for snprintf() size for
- NUL at the end. [ruby-dev:26574]
-
-Tue Jul 19 16:39:46 2005 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * io.c (rb_io_inspect): replace sprintf() with "%s" format all
- over the place by snprintf() to avoid integer overflow.
-
-Tue Jul 19 14:08:22 2005 Hirokazu Yamamoto <ocean@m2.ccsnet.ne.jp>
-
- * ext/tcltklib/tcltklib.c: rbtk_eventloop_depth is used as int.
-
- * ext/tcltklib/tcltklib.c: rbtk_pending_exception is tested with
- NIL_P, so should assign Qnil instead of 0 (Qfalse).
-
- * ext/tcltklib/tcltklib.c (ip_invoke_real): fixed memory leak when
- ip is deleted.
-
-Tue Jul 19 13:19:46 2005 Hidetoshi NAGAI <nagai@ai.kyutech.ac.jp>
-
- * ext/tk/lib/tk/variable.rb: For symmetry, add TkVariable#string. It
- returns a string even if the default value type of the TkVariable
- object is not "string".
-
-Mon Jul 18 21:40:20 2005 Hirokazu Yamamoto <ocean@m2.ccsnet.ne.jp>
-
- * eval.c (rb_call0): make the pointer to NODE volatile
- instead of NODE itself.
-
-Mon Jul 18 14:32:21 2005 Tanaka Akira <akr@m17n.org>
-
- * eval.c (rb_call0): make body volatile to avoid optimization problem.
- [ruby-dev:26195]
-
-Mon Jul 18 12:23:27 2005 Hirokazu Yamamoto <ocean@m2.ccsnet.ne.jp>
-
- * ext/io/wait/wait.c: wrong backport from trunk. fixed: [ruby-dev:26562]
-
-Mon Jul 18 09:36:25 2005 Tanaka Akira <akr@m17n.org>
-
- * rubyio.h (FMODE_WSPLIT, FMODE_WSPLIT_INITIALIZED): new constant.
-
- * io.c (wsplit_p): new function.
- (io_fwrite): split writing data by PIPE_BUF if wsplit_p is true in
- multi-threaded mode.
- [ruby-dev:26540]
-
-Sun Jul 17 13:46:54 2005 Nobuyoshi Nakada <nobu@ruby-lang.org>
-
- * ext/io/wait/extconf.rb, ext/io/wait/wait.c: Win32 platforms support.
-
-Fri Jul 15 23:59:03 2005 Nobuyoshi Nakada <nobu@ruby-lang.org>
-
- * lib/rdoc/parsers/parse_c.rb (handle_class_module): handle a
- module enclosed in a built-in module. fixed: [ruby-talk:148239]
-
- * lib/rdoc/parsers/parse_c.rb (find_body): allow macros as methods.
-
- * lib/rdoc/parsers/parse_c.rb (find_call_seq): allow :nodoc: modifier
- in C. [ruby-core:04572]
-
-Fri Jul 15 18:00:01 2005 Hirokazu Yamamoto <ocean@m2.ccsnet.ne.jp>
-
- * bcc32/Makefile.sub (COMMON_HEADERS): ruby_1_8 is using winsock.h.
- failed to compile ext/socket on bcc5.6.4. [ruby-dev:26193]
-
-Fri Jul 15 07:58:56 2005 GOTOU Yuuzou <gotoyuzo@notwork.org>
-
- * lib/webrick/server.rb (WEBrick::GenericServer#accept_client):
- sockets should be non-blocking mode. [ruby-dev:26405]
-
- * lib/webrick/utils.rb (WEBrick::Utils.set_non_blocking): new method.
-
- * lib/webrick/httprequest.rb (WEBrick::HTTPRequest#read_chunked):
- should call sock.read repeatedly until the preferred size data
- is obtained.
-
-Thu Jul 14 18:27:16 2005 Hirokazu Yamamoto <ocean@m2.ccsnet.ne.jp>
-
- * win32/win32.c (rb_w32_strerror): should return correct message
- for ENAMETOOLONG and ENOTEMPTY. (bcc32) [ruby-dev:26533]
-
- * win32/win32.c (rb_w32_strerror): stripped CR LF on the tail.
- (bcc32) [ruby-dev:26533]
-
-Thu Jul 14 00:45:42 2005 Nobuyoshi Nakada <nobu@ruby-lang.org>
-
- * LEGAL (ext/nkf/nkf-utf8): updated from nkf1.7 to nkf-utf8.
-
-Wed Jul 13 19:37:47 2005 Hirokazu Yamamoto <ocean@m2.ccsnet.ne.jp>
-
- * win32/win32.c (rb_w32_mkdir): should set EEXIST (not EACCES)
- if file or directory already exists. (bcc32) [ruby-dev:26508]
-
- * win32/win32.c (rb_w32_rmdir): should set ENOTDIR (not EINVAL)
- if it is not directory. (bcc32, win32)
-
- * win32/win32.c (rb_w32_rmdir, rb_w32_unlink): restore
- FILE_ATTRIBUTE_READONLY flag on function failure.
-
-Wed Jul 13 12:40:00 2005 Hidetoshi NAGAI <nagai@ai.kyutech.ac.jp>
-
- * ext/tcltklib/tcltklib.c: TclTkLib.do_one_event doesn't work.
-
- * ext/tk/lib/tk.rb: Tk.thread_update is available.
-
-Tue Jul 12 23:32:11 2005 Nobuyoshi Nakada <nobu@ruby-lang.org>
-
- * lib/mkmf.rb: keep curdir unexpanded.
-
-Mon Jul 11 08:31:29 2005 Nobuyoshi Nakada <nobu@ruby-lang.org>
-
- * regex.c (read_special): fix parsing backslashes following \c in
- regexp. fixed: [ruby-dev:26500]
-
-Mon Jul 11 02:53:00 2005 GOTOU Yuuzou <gotoyuzo@notwork.org>
-
- * lib/webrick/cgi.rb (WEBrick::CGI::Socket#request_line):
- mistook in merging the patch of [ruby-dev:26235] at
- revision 1.4.2.6.
-
-Sun Jul 10 23:58:04 2005 Tanaka Akira <akr@m17n.org>
-
- * lib/pathname.rb (Pathname#unlink): try Dir.unlink first to
- avoid unlink a directory by root.
- cf. [ruby-dev:26237]
-
-Sun Jul 10 22:18:17 CEST 2005 Michael Neumann <mneumann@ruby-lang.org>
-
- * lib/xmlrpc/server.rb (XMLRPC::Server): Switch from GServer over to
- WEBrick. This makes file lib/xmlrpc/httpserver.rb obsolete (at least it is
- no further used by the XML-RPC library).
-
-Sun Jul 10 12:47:01 2005 Nobuyoshi Nakada <nobu@ruby-lang.org>
-
- * lib/debug.rb (debug_command): added a deficient format specifier.
- fixed: [ruby-core:05419]
-
-Sat Jul 9 21:28:46 2005 Masaki Suketa <masaki.suketa@nifty.ne.jp>
-
- * ext/win32ole/win32ole.c (ole_method_dispid): convert dispid
- in Ruby and C by INT2NUM and NUM2INT.
-
- * ext/win32ole/win32ole.c (ole_invoke2): ditto.
-
- * ext/win32ole/test/testWIN32OLE.rb: ditto.
-
- * ext/win32ole/test/testOLEMETHOD.rb: ditto.
-
-Fri Jul 8 15:45:04 2005 Kouhei Sutou <kou@cozmixng.org>
-
- * lib/rss/rss.rb (RSS::VERSION): 0.1.4 -> 0.1.5.
-
- * test/rss/test_version.rb (RSS::TestVersion#test_version):
- ditto.
-
- * lib/rss/0.9.rb (RSS::Rss::Channel::Item::Category):
- domain attribute of <category> is optional. Thanks to
- Chris Lee <clee@kde.org>.
-
- * test/rss/test_parser.rb (RSS::TestParser#test_category20):
- adjusted test case.
-
-Tue Jul 5 23:44:06 2005 Nobuyoshi Nakada <nobu@ruby-lang.org>
-
- * instruby.rb: expand source library path.
-
-Tue Jul 5 23:27:14 2005 Nobuyoshi Nakada <nobu@ruby-lang.org>
-
- * array.c (sort_2): get rid of yet another bcc's bug.
- fixed: [ruby-core:05152]
-
- * eval.c (rb_thread_save_context): must not switch contexts during
- re-allocating stack. fixed: [ruby-core:05219]
-
-Tue Jul 5 15:15:10 2005 Hidetoshi NAGAI <nagai@ai.kyutech.ac.jp>
-
- * ext/tk/tkutil.c: fix typo.
-
-Tue Jul 5 14:51:35 2005 Hidetoshi NAGAI <nagai@ai.kyutech.ac.jp>
-
- * ext/tcltklib/tcltklib.c: bug fix on treating Unicode strings.
-
- * ext/tcltklib/tcltklib.c: add methods to treat encoding mode.
-
- * ext/tcltklib/MANUAL.eng: add description of TclTkLib#encoding,
- encoding_system, and so on.
-
- * ext/tcltklib/MANUAL.euc: ditto.
-
- * ext/tk/tkutil.c: fail to create a Tcl's list string from an
- array including multiple kind of encoded strings.
-
- * ext/tk/lib/tk.rb: ditto.
-
- * ext/tk/lib/multi-tk.rb: 2nd arg of _{to|from}UTF8 is omissible.
-
- * ext/tk/lib/remote-tk.rb: ditto.
-
- * ext/tk/lib/tk.rb: override TclTkLib#encoding and encoding= to
- use TkCore::INTERP.encoding and encoding=.
-
- * ext/tk/lib/tk.rb: when "require 'tk'" and $KCODE=='NONE', check
- DEFAULT_TK_ENCODING to decide Ruby/Tk's system encoding mode.
-
- * ext/tk/lib/tk/encodedstr.rb: check both of Tk.encoding and
- Tk.encoding_system. Tk.encoding has higher priority.
-
- * ext/tk/lib/tk/optiondb.rb: ditto.
-
- * ext/tk/lib/tk/spinbox.rb: ditto.
-
- * ext/tk/lib/tk/validation.rb: ditto.
-
- * ext/tk/lib/tk/namespace.rb: arguemnts for TclTkIp#_merge_tklist
- should be UTF-8 strings.
-
-Mon Jul 4 14:35:52 2005 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * sample/svr.rb: service can be stopped by ill-behaved client; use
- tsvr.rb instead.
-
-Mon Jul 4 13:25:21 2005 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * missing/erf.c: original erf.c by prof. Okumura is confirmed to
- be public domain. reverted BSD implementation.
-
-Mon Jul 4 11:15:37 2005 NAKAMURA Usaku <usa@ruby-lang.org>
-
- * test/{dbm,gdbm,sdbm}/test_{dbm,gdbm,sdbm}.rb: skip some tests
- which using fork on fork-less platforms.
-
-Sun Jul 3 23:26:30 2005 NAKAMURA, Hiroshi <nakahiro@sarion.co.jp>
-
- * test/wsdl/document/test_rpc.rb: compare formatted time string of
- Time objects instead of comparing Time objects itself to avoid
- unintended conflict of usec part. [ruby-dev:26220]
-
-Sat Jul 2 22:41:04 2005 Tanaka Akira <akr@m17n.org>
-
- * ext/socket/socket.c (unix_send_io, unix_recv_io): support x86-64 and
- IA64.
-
-Sat Jul 2 17:06:23 2005 Tanaka Akira <akr@m17n.org>
-
- * defines.h (FLUSH_REGISTER_WINDOWS): defined for IA64.
- (flush_register_windows): declare flush_register_windows.
-
- * eval.c (flush_register_windows): new function.
-
-Fri Jul 1 17:48:52 2005 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * bignum.c (get2comp): revert all prior changes, and calculate
- proper 2's complement for negative numbers. backported from
- HEAD.
-
-Fri Jul 1 15:50:12 2005 NAKAMURA Usaku <usa@ruby-lang.org>
-
- * missing/erf.c: need to include some headers for some platforms.
-
- * win32/win32.h (copysign, scalb): define for compatibility with
- other platforms. [ruby-dev:26430]
-
-Fri Jul 1 15:37:42 2005 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * missing/crypt.c: modified to make it compilable on platforms
- other than BSD. [ruby-dev:26430]
-
- * missing/erf.c: ditto. code from <exp.c> merged.
-
-Fri Jul 1 12:44:56 2005 Tanaka Akira <akr@m17n.org>
-
- * lib/open-uri.rb (OpenURI.open_http): refine post_connection_check
- call.
-
-Fri Jul 1 11:34:08 2005 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * missing/crypt.c: replaced with 4.4BSD version.
-
- * missing/erf.c: ditto.
-
- * missing/vsnprintf.c: removed the third provision from the old
- BSD license. [ruby-core:05177]
-
-Fri Jul 1 01:45:21 2005 Nobuyoshi Nakada <nobu@ruby-lang.org>
-
- * enum.c (enum_min, enum_max): must not return Qundef.
- fixed: [ruby-core:05299]
-
-Fri Jul 1 00:18:40 2005 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * lib/delegate.rb (Delegator::respond_to): respond_to? must check
- destination object. [ruby-talk:146894]
-
-Thu Jun 30 19:00:21 2005 Keiju Ishitsuka <keiju@ruby-lang.org>
- * lib/irb/ruby-lex.rb (RubyLex::identify_number): alternative implements
- for [ruby-dev:26410]. And support a numeric form of 0d99999.
-
-Thu Jun 30 17:28:10 2005 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * lib/irb/ruby-lex.rb (RubyLex::identify_number): should not treat
- plain zero as an octal number. [ruby-dev:26410]
-
-Thu Jun 30 15:13:16 2005 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * eval.c (rb_eval): pre-evaluate argument for unambiguous
- evaluation order. [ruby-dev:26383]
-
-Thu Jun 30 09:53:56 2005 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * lib/delegate.rb (Delegator::method_missing): forward unknown
- method to the destination. suggested by
- <christophe.poucet@gmail.com>. [ruby-talk:146776]
-
-Tue Jun 28 21:59:29 2005 Kazuhiro NISHIYAMA <zn@mbf.nifty.com>
-
- * dir.c, eval.c, hash.c, process.c, ruby.c: avoid warning "unused
- variable" [ruby-dev:26387]
-
-Sat Jun 25 17:15:23 2005 GOTOU Yuuzou <gotoyuzo@notwork.org>
-
- * lib/webrick/httputils.rb (WEBrick::HTTPUtils.parse_query): should
- discard if key=val pair is empty. patch from Gary Wright.
-
-Sat Jun 25 23:30:51 2005 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * process.c (detach_process_watcher): terminate process watcher
- thread right after rb_waitpid() succeed. [ruby-talk:146430]
-
-Sat Jun 25 15:49:18 2005 Nobuyoshi Nakada <nobu@ruby-lang.org>
-
- * enum.c (enum_min, enum_max): do not ignore nil as the first element.
-
-Sat Jun 25 14:40:17 2005 Hirokazu Yamamoto <ocean@m2.ccsnet.ne.jp>
-
- * ext/sdbm/init.c (fsdbm_select): SDBM#select had returned the array
- which contained each elements twice. [ruby-dev:26358]
-
-Fri Jun 24 22:06:47 CEST 2005 Michael Neumann <mneumann@ruby-lang.org>
-
- * lib/xmlrpc/*, test/xmlrpc/*: backported changes from HEAD into 1.8
-
-Fri Jun 24 17:00:00 2005 Shigeo Kobayashi <shigeo@tinyforest.jp>
-
- * ext/bigdecimal/bigdecimal.c: patch from "NATORI Shin"
- (u-tokyo.ac.jp) applied to fix rounding bug.
-
-Fri Jun 24 13:06:45 2005 akira yamada <akira@ruby-lang.org>
-
- * lib/uri/common.rb, lib/uri/generic.rb: fixed typo in documents and
- replaced some existent domain name with "example.com".
-
-Fri Jun 24 12:23:19 2005 Hidetoshi NAGAI <nagai@ai.kyutech.ac.jp>
-
- * ext/tk/lib/tk.rb: fix typo on Tk.grid_propagate.
-
- * ext/tk/lib/tk.rb: Tk.event_generate and TkWindow#event_generate
- accept TkEvent::Event object as context argument.
-
- * ext/tk/lib/tk/event.rb: add TkEvent::Event#valid_fields and
- valid_for_generate to get field parameters of event_generate.
-
-Thu Jun 23 23:55:59 2005 Nobuyoshi Nakada <nobu@ruby-lang.org>
-
- * runruby.rb: should load built rbconfig.rb.
-
-Thu Jun 23 16:53:15 2005 Hidetoshi NAGAI <nagai@ai.kyutech.ac.jp>
-
- * ext/tk/lib/tk/canvastag.rb: TkcGroup.new cannot include given items.
- TkcGroup#exclude calls wrong method.
- Add alias TkcGroup#add [ruby-talk:146049].
-
- * ext/tk/lib/tk/canvas.rb: TkCanvas#dtag and some subcommands of
- TkCanvas#addtag fail to treat a TkcTag argument.
-
- * ext/tk/lib/tk/event.rb: add TkEvent::Event#generate to help to send
- current event to other widgets.
-
-Mon Jun 20 18:44:04 2005 Tanaka Akira <akr@m17n.org>
-
- * eval.c (FUNCTION_CALL_MAY_RETURN_TWICE): DUMMY_SETJMP is replaced
- because setjmp is not enough to fix getcontext and SPARC register
- window problem.
-
-Mon Jun 20 16:48:36 2005 NAKAMURA Usaku <usa@ruby-lang.org>
-
- * ext/dbm/dbm.c (fdbm_closed): new method DBM#closed?
-
- * ext/gdbm/gdbm.c (fgdbm_closed): new method GDBM#closed?
-
- * ext/sdbm/init.c (fsdbm_closed): new method SDBM#closed?
-
- * test/dbm/test_dbm.rb, test/gdbm/test_gdbm.rb, test/sdbm/test_sdbm.rb
- (teardown): close all db objects before deleting data files.
-
- * win32/win32.{ch} (unlink): hook runtime function to change
- file attribute before unlinking.
- fixed: [ruby-dev:26360]
-
-Mon Jun 20 02:15:35 2005 Nobuyoshi Nakada <nobu@ruby-lang.org>
-
- * gc.c (define_final): document fix: finalizers never get called
- before target object is destroyed.
-
-Mon Jun 20 01:26:49 2005 GOTOU Yuuzou <gotoyuzo@notwork.org>
-
- * ext/openssl/openssl_missing.c, ext/openssl/ossl.h,
- ext/openssl/ossl_asn1.c, ext/openssl/ossl_bio.c,
- ext/openssl/ossl_pkcs12.h, ext/openssl/ossl_x509req.c: avoid
- compiler warnings. suggested by Michal Rokos.
-
-Sun Jun 19 14:09:07 2005 Nobuyoshi Nakada <nobu@ruby-lang.org>
-
- * gc.c (run_final): reduce unnecessary object allocation during
- finalization.
-
- * gc.c (rb_gc_call_finalizer_at_exit): deferred finalizers list should
- be cleared before calling them. fixed: [ruby-talk:145790]
-
-Fri Jun 17 13:01:40 2005 Tanaka Akira <akr@m17n.org>
-
- * lib/time.rb (Time.parse): fix previous leap seconds support.
- (Time.rfc2822): ditto.
- (Time.xmlschema): ditto.
-
-Thu Jun 16 15:06:55 2005 Hirokazu Yamamoto <ocean@m2.ccsnet.ne.jp>
-
- * ext/tcltklib/tcltklib.c (ip_rb_threadVwaitCommand): Tcl_Release
- was missing.
-
-Thu Jun 16 13:34:48 2005 Hidetoshi NAGAI <nagai@ai.kyutech.ac.jp>
-
- * ext/tk/lib/tk.rb: add Tk.getMultiple{Open|Save}File() which return
- an Array of selected files.
-
-Thu Jun 16 12:53:24 2005 Tanaka Akira <akr@m17n.org>
-
- * lib/time.rb (Time.parse): "Fri Jan 1 08:59:60 +0900 1999" was
- parsed as "Fri Jan 01 09:00:00 JST 1999" even on an environment
- which supports leap seconds.
- (Time.rfc2822): ditto.
- (Time.xmlschema): ditto.
-
-Thu Jun 16 08:29:22 2005 Hirokazu Yamamoto <ocean@m2.ccsnet.ne.jp>
-
- * ext/dl/sym.c (rb_dlsym_call): needs FREE_ARGS before return.
- fixed memory leak. [ruby-Bugs-2034]
-
-Wed Jun 15 18:26:39 2005 Hidetoshi NAGAI <nagai@ai.kyutech.ac.jp>
-
- * ext/tk/lib/tk.rb: support "tk inactive" sub-command [for Tcl/Tk8.5a3]
-
- * ext/tk/lib/tk/namespace.rb: support "namespace path" sub-command and
- 'namespace ensemble' sub-command [for Tcl/Tk8.5a3]
-
-Tue Jun 14 02:02:43 2005 Hidetoshi NAGAI <nagai@ai.kyutech.ac.jp>
-
- * ext/tk/tkutil.c: add TkUtil::CallbackSubst.subst_arg(m, ...) &
- _define_attribute_aliases(hash) to get substitution-argument from
- attributes (e.g. subst_arg(:x,:y,:num,:button) --> "%x %y %b %b ").
-
- * ext/tk/lib/tk/event.rb: use _define_attribute_aliases().
-
-Mon Jun 13 13:01:05 2005 Hirokazu Yamamoto <ocean@m2.ccsnet.ne.jp>
-
- * hash.c (ruby_setenv): fixed SEGV. [ruby-dev:26186]
-
-Mon Jun 13 01:54:20 2005 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * signal.c (sigexit): call rb_thread_signal_exit() instead of
- rb_exit(). [ruby-dev:26347]
-
- * eval.c (rb_thread_signal_exit): a new function to exit on main
- thread.
-
- * eval.c (rb_thread_switch): exit status should be retrieved from
- ruby_errinfo.
-
- * eval.c (rb_f_exit): ensure exit(0) should call
- exit(EXIT_SUCCESS).
-
-Mon Jun 13 01:20:02 2005 Tanaka Akira <akr@m17n.org>
-
- * eval.c (rb_gc_mark_threads): curr_thread may not be part of the
- thread list. [ruby-dev:26312]
-
-Fri Jun 10 23:35:34 2005 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * missing/mkdir.c: remove. [ruby-core:05177]
-
-Fri Jun 10 22:54:26 2005 Nobuyoshi Nakada <nobu@ruby-lang.org>
-
- * missing.h: fd_set stuffs need sys/types.h. fixed: [ruby-core:05179]
-
-Thu Jun 9 23:58:12 2005 Nobuyoshi Nakada <nobu@ruby-lang.org>
-
- * ext/Win32API/Win32API.c (Win32API_Call): disable global
- optimization. fixed: [ruby-core:05143]
-
-Thu Jun 9 23:35:22 2005 Nobuyoshi Nakada <nobu@ruby-lang.org>
-
- * enum.c (enum_inject): default the result value to Qundef to use
- first element as initial value if not given.
-
-Thu Jun 9 19:55:41 2005 Tanaka Akira <akr@m17n.org>
-
- * eval.c (ruby_longjmp): new macro to call longjmp, setcontext, etc.
- (ruby_setjmp): new macro to call setjmp, getcontext, etc.
- (ruby_setjmp): call setjmp before getcontext to avoid IA64 register
- stack problem.
- [ruby-talk:144939]
-
- * gc.c (Init_stack): remove IA64_MAGIC_STACK_LIMIT.
-
-Thu Jun 9 11:55:34 2005 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * lib/delegate.rb (SimpleDelegator::__setobj__): need check for
- recursive delegation. [ruby-core:04940]
-
-Wed Jun 8 18:47:10 2005 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * misc/ruby-mode.el (ruby-expr-beg): fix looking point drift.
-
-Wed Jun 8 11:11:34 2005 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * bignum.c (get2comp): calculate proper 2's complement for
- negative numbers. a bug in normalizing negative numbers
- reported from Honda Hiroki <hhonda@ipflex.com>.
-
-Wed Jun 8 08:33:10 2005 Nobuyoshi Nakada <nobu@ruby-lang.org>
-
- * enum.c (enum_min_by, enum_max_by): return nil if no iteration.
- fixed: [ruby-dev:26245]
-
- * eval.c (rb_need_block): ensure a block is given.
-
- * eval.c (backtrace): skip successive frames sharing same node.
-
-Wed Jun 8 00:15:08 2005 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * ext/socket/socket.c (ruby_getaddrinfo__aix): merged a patch from
- KUBO Takehiro <kubo@jiubao.org> to support AIX. [ruby-list:40832]
-
-Wed Jun 8 00:09:01 2005 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * lib/yaml/rubytypes.rb (Array::to_yaml): merged a patch from
- Tilman Sauerbeck <tilman@code-monkey.de>. [ruby-core:05055]
-
- * lib/yaml/rubytypes.rb (Hash::to_yaml): ditto.
-
-Wed Jun 8 00:00:01 2005 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * ext/curses/curses.c (curses_insertln): merged a patch from
- TAKAHASHI Tamotsu <ttakah@lapis.plala.or.jp>. [ruby-ext:02305]
-
-Tue Jun 7 19:34:15 2005 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * lib/irb/init.rb (IRB::IRB.rc_file_generators): more flexible
- IRB.rc_file_generators. [ruby-core:05163]
-
-Tue Jun 7 18:39:31 2005 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * lib/thread.rb: RDoc documentation from Eric Hodel
- <drbrain@segment7.net> added. [ruby-core:05148]
-
-Tue Jun 7 18:30:04 2005 Nobuyoshi Nakada <nobu@ruby-lang.org>
-
- * lib/mkmf.rb (create_makefile): add .SUFFIXES from depend file.
- fixed: [ruby-dev:26294]
-
-Tue Jun 7 17:39:54 2005 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * object.c (rb_mod_cvar_get): Module#class_variable_get(): back
- ported from CVS HEAD. [ruby-talk:144741]
-
- * object.c (rb_mod_cvar_set): Module#class_variable_set().
- [ruby-talk:144741]
-
-Tue Jun 7 16:32:53 2005 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * sprintf.c (rb_f_sprintf): raise exception on debug mode (-d),
- not verbose mode (-v/-w). [ruby-core:05123]
-
-Tue Jun 7 10:30:49 2005 Hidetoshi NAGAI <nagai@ai.kyutech.ac.jp>
-
- * ext/tk/lib/multi-tk.rb: slave-ip fails to call procedures
- delegated by master-ip.
-
-Sun Jun 5 23:00:35 2005 Hidetoshi NAGAI <nagai@ai.kyutech.ac.jp>
-
- * ext/tk/lib/tk/console.rb: create console when required
-
- * ext/tk/sample/tkextlib/tile/demo.rb: fix TypeError & create Console
-
-Sat Jun 4 14:55:18 2005 Tanaka Akira <akr@m17n.org>
-
- * test/dbm/test_dbm.rb: merged from ext/dbm/testdbm.rb.
-
- * test/gdbm/test_gdbm.rb: merged from ext/gdbm/testgdbm.rb.
-
- * test/sdbm/test_sdbm.rb: renamed from ext/sdbm/testsdbm.rb with
- modification to use test/unit.
-
-Fri Jun 3 14:06:12 2005 Hidetoshi NAGAI <nagai@ai.kyutech.ac.jp>
-
- * ext/tk/lib/multi-tk.rb: fix typo.
-
-Wed Jun 1 11:32:42 2005 Hirokazu Yamamoto <ocean@m2.ccsnet.ne.jp>
-
- * bcc32/Makefile.sub: can use single quote character in DESTDIR.
- [ruby-dev:26205]
-
-Mon May 30 23:48:29 2005 Hidetoshi NAGAI <nagai@ai.kyutech.ac.jp>
-
- * ext/tk/lib/tk/macpkg.rb: add PACKAGE_NAME information of Tcl/Tk
- Extension.
-
- * ext/tk/lib/tk/msgcat.rb: ditto.
-
- * ext/tk/lib/tk/winpkg.rb: ditto.
-
- * ext/tk/lib/tkextlib/*: ditto.
-
-Sat May 28 16:40:15 2005 GOTOU Yuuzou <gotoyuzo@notwork.org>
-
- * test/openssl/test_x509store.rb: add test for expired CRL
- and refine some assertions.
-
-Sat May 28 05:15:51 2005 GOTOU Yuuzou <gotoyuzo@notwork.org>
-
- * ext/openssl/ossl_x509store.c (ossl_x509stctx_set_time): should
- not set internal flag directry.
-
-Sat May 28 02:00:11 2005 GOTOU Yuuzou <gotoyuzo@notwork.org>
-
- * lib/webrick/cgi.rb (WEBrick::CGI::Socket#request_line):
- ENV["REQUEST_URI"] is better to get correct Request-URI
- than ENV["SCRIPT_NAME"] + ENV["PATH_INFO"]. [ruby-dev:26235]
-
-Fri May 27 16:32:04 2005 WATANABE Hirofumi <eban@ruby-lang.org>
-
- * lib/mkmf.rb: use the semicolon as the path separator
- in the environment of MSYS. fixed: [ruby-dev:26232]
-
-Thu May 26 06:08:11 2005 Hidetoshi NAGAI <nagai@ai.kyutech.ac.jp>
-
- * ext/tk/lib/tk.rb: add shortcut-methods of tk_call + tk_split_list
-
-Wed May 25 22:52:42 2005 Shugo Maeda <shugo@ruby-lang.org>
-
- * lib/irb/input-method.rb: do not use Readline::HISTORY.pop.
- (backported from HEAD)
-
-Wed May 25 21:55:40 2005 Shugo Maeda <shugo@ruby-lang.org>
-
- * ext/readline/readline.c: supported libedit. (backported from HEAD)
-
- * ext/readline/extconf.rb: ditto.
-
- * test/readline/test_readline.rb: ditto.
-
-Wed May 25 20:06:27 2005 Hidetoshi NAGAI <nagai@ai.kyutech.ac.jp>
-
- * ext/tk/lib/tk.rb: TkComm#tk_split_*list fail to split a kind of SJIS
- strings. To avoid the trouble, add arguments to control converting
- encoding, and do split on a UTF8 string.
-
- * ext/tk/lib/multi-tk.rb: modify to attend encoding.
-
- * ext/tk/lib/remote-tk.rb: ditto.
-
- * ext/tk/lib/tk/itemconfig.rb: ditto.
-
- * ext/tk/lib/tk/listbox.rb: ditto.
-
- * ext/tk/lib/tk/namespace.rb: ditto.
-
- * ext/tk/lib/tk/panedwindow.rb: ditto.
-
- * ext/tk/lib/tk/text.rb: ditto.
-
- * ext/tk/lib/tk/textmark.rb: ditto.
-
- * ext/tk/lib/tk/texttag.rb: ditto.
-
- * ext/tk/lib/tk/variable.rb: ditto.
-
- * ext/tk/lib/tk/winfo.rb: ditto.
-
- * ext/tk/lib/tkextlib/iwidgets/scrolledlistbox.rb: ditto.
-
- * ext/tk/lib/tkextlib/iwidgets/scrolledtext.rb: ditto.
-
- * ext/tk/lib/tk.rb: add TkWindow#lower_window/raise_window and
- Tk#lower_window/raise_window by reason of method-name conflict
-
- * ext/tk/lib/tk/canvas.rb: bug fix on TkCanvas#delete when given
- non-TkcItem arguments.
-
- * ext/tk/lib/tkextlib/iwidgets/scrolledcanvas.rb: ditto.
-
-Wed May 25 12:59:48 2005 Tanaka Akira <akr@m17n.org>
-
- * lib/open-uri.rb (OpenURI::Meta::RE_QUOTED_STRING): a content of
- quoted-string should be zero or more characters.
-
-Tue May 24 23:42:16 2005 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * numeric.c (fix_pow): support Fixnum ** Float case directly
- without coercing. [ruby-talk:142697] [ruby-talk:143054]
-
-Tue May 24 16:57:24 2005 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * ruby.c (require_libraries): caused SEGV when continuation jumped
- in to the required library code.
-
-Tue May 24 11:56:25 2005 WATANABE Hirofumi <eban@ruby-lang.org>
-
- * lib/getopts.rb: should warn only if verbose mode.
- fixed: [ruby-dev:26201]
-
-Tue May 24 06:45:31 2005 Nobuyoshi Nakada <nobu@ruby-lang.org>
-
- * misc/ruby-mode.el (ruby-font-lock-syntactic-keywords): string
- literals to be matched non-greedy.
-
-Tue May 24 00:34:32 2005 NAKAMURA, Hiroshi <nakahiro@sarion.co.jp>
-
- * test/soap/calc: method name 'set' was able to crash with a class Set.
- [ruby-dev:26210]
-
- * test/wsdl/document/test_rpc.rb: dateTime comparison failed under
- TZ=right/Asia/Tokyo (with leap second.) [ruby-dev:26208]
-
-Mon May 23 16:24:05 2005 Hidetoshi NAGAI <nagai@ai.kyutech.ac.jp>
-
- * ext/tcltklib/extconf.rb: Framework support on MacOS X Tiger.
-
- * ext/tcltklib/README.1st: add description of Framework support options.
-
-Mon May 23 12:21:37 2005 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * re.c (make_regexp): should not return junk address during
- compile time. [ruby-dev:26206]
-
-Sun May 22 21:54:06 2005 NAKAMURA, Hiroshi <nakahiro@sarion.co.jp>
-
- * lib/{soap,wsdl,xsd}, test/{soap,wsdl,xsd}: imported soap4r/1.5.4.
-
- == SOAP client and server ==
-
- === for both client side and server side ===
-
- * improved document/literal service support.
- style(rpc,document)/use(encoding, literal) combination are all
- supported. for the detail about combination, see
- test/soap/test_style.rb.
-
- * let WSDLEncodedRegistry#soap2obj map SOAP/OM to Ruby according to
- WSDL as well as obj2soap. closes #70.
-
- * let SOAP::Mapping::Object handle XML attribute for doc/lit service.
- you can set/get XML attribute via accessor methods which as a name
- 'xmlattr_' prefixed (<foo name="bar"/> -> Foo#xmlattr_name).
-
- === client side ===
-
- * WSDLDriver capitalized name operation bug fixed. from
- 1.5.3-ruby1.8.2, operation which has capitalized name (such as
- KeywordSearchRequest in AWS) is defined as a method having
- uncapitalized name. (converted with GenSupport.safemethodname
- to handle operation name 'foo-bar'). it introduced serious
- incompatibility; in the past, it was defined as a capitalized.
- define capitalized method as well under that circumstance.
-
- * added new factory interface 'WSDLDriverFactory#create_rpc_driver'
- to create RPC::Driver, not WSDLDriver (RPC::Driver and WSDLDriver
- are merged). 'WSDLDriverFactory#create_driver' still creates
- WSDLDriver for compatibility but it warns that the method is
- deprecated. please use create_rpc_driver instead of create_driver.
-
- * allow to use an URI object as an endpoint_url even with net/http,
- not http-access2.
-
- === server side ===
-
- * added mod_ruby support to SOAP::CGIStub. rename a CGI script
- server.cgi to server.rb and let mod_ruby's RubyHandler handles the
- script. CGIStub detects if it's running under mod_ruby environment
- or not.
-
- * added fcgi support to SOAP::CGIStub. see the sample at
- sample/soap/calc/server.fcgi. (almost same as server.cgi but has
- fcgi handler at the bottom.)
-
- * allow to return a SOAPFault object to respond customized SOAP fault.
-
- * added the interface 'generate_explicit_type' for server side
- (CGIStub, HTTPServer). call 'self.generate_explicit_type = true'
- if you want to return simplified XML even if it's rpc/encoded
- service.
-
- == WSDL ==
-
- === WSDL definition ===
-
- * improved XML Schema support such as extension, restriction,
- simpleType, complexType + simpleContent, ref, length, import,
- include.
-
- * reduced "unknown element/attribute" warnings (warn only 1 time for
- each QName).
-
- * importing XSD file at schemaLocation with xsd:import.
-
- === code generation from WSDL ===
-
- * generator crashed when there's '-' in defined element/attribute
- name.
-
- * added ApacheMap WSDL definition.
-
- * sample/{soap,wsdl}: removed.
-
-Sun May 22 19:11:35 2005 GOTOU Yuuzou <gotoyuzo@notwork.org>
-
- * ext/openssl/lib/openssl/ssl.rb (OpenSSL::SSL::SSLServer#intialize):
- should initialize session id context. [ruby-core:4663]
-
- * ext/openssl/ossl_ssl.c (ossl_sslctx_setup): add session id support.
-
-Sat May 21 10:24:21 2005 Hirokazu Yamamoto <ocean@m2.ccsnet.ne.jp>
-
- * bcc32/Makefile.sub: tds files were not deleted when DESTDIR
- included '\' path delimiter. [ruby-dev:26193]
-
-Thu May 19 19:04:29 2005 speakillof <speakillof@yahoo.co.jp>
-
- * lib/rexml/encodings/SHIFT-JIS.rb: encoding and decoding were
- swapped. [ruby-core:4772]
-
-Wed May 18 23:42:25 2005 Nobuyoshi Nakada <nobu@ruby-lang.org>
-
- * error.c (exc_exception): reverted to call Exception#initialize
- directly. fixed: [ruby-dev:26177]
-
-Wed May 18 23:39:09 2005 Nobuyoshi Nakada <nobu@ruby-lang.org>
-
- * dir.c (glob_helper): get rid of using String. [ruby-dev:26180]
-
- * dir.c (push_braces): should skip balanced braces.
-
- * eval.c (ruby_options), win32/win32.c (NtInitialize): move argument
- intialization back. [ruby-dev:26180]
-
-Tue May 17 15:31:31 2005 GOTOU Yuuzou <gotoyuzo@notwork.org>
-
- * lib/webrick/httpserver.rb (WEBrick::HTTPServer#run): should
- break the loop if the socket reached to EOF. [ruby-talk:142285]
-
-Tue May 17 11:52:18 2005 NAKAMURA Usaku <usa@ruby-lang.org>
-
- * win32/win32.c (unixtime_to_filetime): use localtime() instead of
- gmtime() when using FileLocalTimeToFileTime().
-
-Mon May 16 22:28:43 2005 Nobuyoshi Nakada <nobu@ruby-lang.org>
-
- * win32/win32.h, {bcc32,win32,wince}/Makefile.sub: moved rb_[ugp]id_t
- to get rid of redefinition warnings on mingw.
-
- * class.c (rb_class_init_copy): singleton class is disallowed to copy,
- from its definition. fixed: [ruby-talk:142749]
-
-Mon May 16 08:52:29 2005 Hirokazu Yamamoto <ocean@m2.ccsnet.ne.jp>
-
- * win32/win32.{h,c}: define rb_[pgu]id_t.
-
-Mon May 16 00:21:02 2005 Tanaka Akira <akr@m17n.org>
-
- * lib/pathname.rb (Pathname#unlink): use SystemCallError instead of
- Errno::EISDIR because EISDIR is not portable.
- [ruby-core:5001]
-
-Sun May 15 22:11:33 2005 Masatoshi SEKI <m_seki@mva.biglobe.ne.jp>
-
- * lib/drb/drb.rb (DRbObject#method_missing): use raise(exception).
- [ruby-dev:26164]
-
-Sun May 15 18:56:35 2005 Nobuyoshi Nakada <nobu@ruby-lang.org>
-
- * configure.in, ruby.h: define rb_[pgu]id_t macros instead of typedefs
- to get rid of types which might not be defined yet. [ruby-dev:26165]
-
-Sun May 15 14:35:46 2005 Tanaka Akira <akr@m17n.org>
-
- * lib/pathname.rb (Pathname#unlink): unlink a symlink to a directory
- was failed. [ruby-core:4992]
-
-Sun May 15 09:57:30 2005 Nobuyoshi Nakada <nobu@ruby-lang.org>
-
- * win32/win32.c (unixtime_to_filetime): deal with DST.
- [ruby-talk:141817]
-
-Sat May 14 23:59:11 2005 Nobuyoshi Nakada <nobu@ruby-lang.org>
-
- * error.c (exc_exception, {exit,name_err,syserr}_initialize): call
- Execption#initialize. fixed: [ruby-talk:142593]
-
-Sat May 14 23:57:26 2005 Erik Huelsmann <ehuels@gmail.com>
-
- * configure.in: Check for the availability of pid_t, gid_t and uid_t and
- remove AC_TYPE_UID_T. fixed: [ruby-core:04745]
-
- * defines.h: Remove pid_t typedef.
-
- * ruby.h: Define rb_pid_t, rb_gid_t and rb_uid_t in accordance with
- the available system types.
-
- * process.c: Change instances of pid_t and gid_t to their rb_*
- counterparts.
-
- * ext/pty/pty.c: Change pid_t to rb_pid_t.
-
- * vms/config.h: Define HAVE_{P,G,U}ID_T to 1.
-
- * win32/Makefile.sub: Remove #define for {g,u}id_t.
-
- * win32/win32.c: Change pid_t to rb_pid_t.
-
- * wince/Makefile.sub: Remove #define for {g,u}id_t.
-
- * wince/sys/types.h: Remove definitions of {p,g,u}id_t.
-
-Fri May 13 23:44:22 2005 Nobuyoshi Nakada <nobu@ruby-lang.org>
-
- * ext/extmk.rb: keep srcdir unexpanded.
-
- * lib/mkmf.rb (create_makefile): quote topdir and hdrdir if necessary.
- fixed: [ruby-core:04932]
-
- * lib/mkmf.rb (configuration), {bcc32,win32,wince}/Makefile.sub: make
- also INSTALL_PROG and INSTALL_DATA system dependent.
- fixed: [ruby-core:04931]
-
-Fri May 13 17:54:39 2005 Hirokazu Yamamoto <ocean@m2.ccsnet.ne.jp>
-
- * variable.c (generic_ivar_get): rb_attr_get should not warn.
- [ruby-dev:26010]
-
-Fri May 13 12:28:43 2005 Daniel Berger <djberge@qwest.com>
-
- * array.c (rb_ary_select): can remove argc check. [ruby-core:4911]
-
- * test/ruby/test_array.rb: add test for find_all.
-
-Fri May 13 11:29:00 2005 NAKAMURA Usaku <usa@ruby-lang.org>
-
- * eval.c (unknown_node): add volatile directive to prototype.
-
-Thu May 12 17:08:48 2005 Tanaka Akira <akr@m17n.org>
-
- * io.c (rb_io_eof, remain_size, read_all, io_read, appendline)
- (swallow, rb_io_each_byte, rb_io_getc): revert previous change.
-
- * io.c (rb_io_eof, io_fread, appendline, swallow, rb_io_each_byte)
- (rb_io_getc, rb_getc): call clearerr before getc to avoid
- stdio incompatibility.
-
-Thu May 12 16:52:20 2005 Hirokazu Yamamoto <ocean@m2.ccsnet.ne.jp>
-
- * lib/rdoc/parsers/parse_c.rb: more readability for mixing
- progress "c..." and warning message.
-
-Thu May 12 16:31:00 2005 NARUSE, Yui <naruse@ruby-lang.org>
-
- * ext/nkf/nkf-utf8/nkf.c: follow nkf 2.0.5
-
-Thu May 12 16:15:01 2005 Tanaka Akira <akr@m17n.org>
-
- * io.c (rb_io_eof, remain_size, read_all, io_read, appendline)
- (swallow, rb_io_each_byte, rb_io_getc): don't rely EOF flag.
- [ruby-talk:141527]
-
-Thu May 12 15:56:20 2005 Tilman Sauerbeck <tilman@code-monkey.de>
-
- * lib/rdoc/parsers/parse_c.rb: show parsing progress for C files.
- [ruby-core:4341]
-
-Thu May 12 13:47:56 2005 Hirokazu Yamamoto <ocean@m2.ccsnet.ne.jp>
-
- * test/drb/test_drb{ssl,unix}.rb: can test drb
- before install. (backported from HEAD) [ruby-dev:26146]
-
-Thu May 12 09:53:57 2005 Nobuyoshi Nakada <nobu@ruby-lang.org>
-
- * version.c (ruby_show_version): flush for non-tty stdout.
-
-Thu May 12 09:07:07 2005 Hirokazu Yamamoto <ocean@m2.ccsnet.ne.jp>
-
- * test/ruby/envutil.rb, test/drb/drbtest.rb: can test drb
- before install. (backported from HEAD) [ruby-Bugs-1672]
-
-Thu May 12 01:23:55 2005 Nobuyoshi Nakada <nobu@ruby-lang.org>
-
- * eval.c (rb_eval), parse.y (arg): reduce fixnum range literal at
- parser. fixed: [ruby-dev:26113]
-
- * eval.c (unknown_node): ignore broken NODE to get rid of accessing
- possibly inaccessible address. fixed: [ruby-dev:26122]
- should emit more useful information like [ruby-dev:26126], though.
-
-Wed May 11 16:20:01 2005 GOTOU Yuuzou <gotoyuzo@notwork.org>
-
- * lib/webrick/cgi.rb: new methods WEBrick::CGI#[], WEBrick::CGI#logger
- and WEBrick::CGI#config. (backported from HEAD)
-
- * lib/webrick/httputils.rb (WEBrick::HTTPUtils.escape_path): should
- not use String#split("/"). (backported from HEAD)
-
-Wed May 11 15:58:39 2005 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * eval.c (break_jump): break should not cross functions.
- [ruby-list:40818]
-
-Wed May 11 10:39:37 2005 Hirokazu Yamamoto <ocean@m2.ccsnet.ne.jp>
-
- * lib/tempfile.rb (Tempfile#unlink): fixed typo.
-
-Wed May 11 01:03:36 2005 Nobuyoshi Nakada <nobu@ruby-lang.org>
-
- * eval.c (TMP_ALLOC): use macro NEW_NODE() to get rid of warnings on
- platforms which have no alloca(). fixed: [ruby-talk:141301]
-
-Sun May 8 23:17:47 2005 Hidetoshi NAGAI <nagai@ai.kyutech.ac.jp>
-
- * ext/tk/lib/tk/timer.rb: fix typo.
-
-Sun May 8 16:52:56 2005 Hirokazu Yamamoto <ocean@m2.ccsnet.ne.jp>
-
- * lib/profiler.rb: fixed "undefined method `[]' for nil:NilClass"
- [ruby-core:4775] [ruby-talk:140401] [ruby-dev:26118]
-
-Sat May 7 22:58:00 2005 Nobuyoshi Nakada <nobu@ruby-lang.org>
-
- * lib/mkmf.rb (have_var): no libs argument is given.
-
-Sun May 1 09:58:11 2005 Nobuyoshi Nakada <nobu@ruby-lang.org>
-
- * ruby.c (process_sflag): replace '-' in variable names with '_'.
- [ruby-dev:26107]
-
- * ruby.c (set_arg0): use also environment variable space for setting
- $0. [ruby-core:04774]
-
-Wed Apr 27 23:42:22 2005 Nobuyoshi Nakada <nobu@ruby-lang.org>
-
- * win32/Makefile.sub (OPTFLAGS): default global optimization to
- disabled only for VC++6.
-
-Tue Apr 26 22:58:00 2005 Hidetoshi NAGAI <nagai@ai.kyutech.ac.jp>
-
- * ext/tcltklib/tcltklib.c (ip_invoke_core): call Tcl's "::unknown"
- command when can't get information of target command.
-
-Mon Apr 25 01:18:43 2005 Tanaka Akira <akr@m17n.org>
-
- * regex.c: declare rb_warn to have variadic argument. [ruby-core:4751]
-
-Sat Apr 23 19:45:59 2005 Hirokazu Yamamoto <ocean@m2.ccsnet.ne.jp>
-
- * ext/tcltklib/tcltklib.c (ip_RubyExitCommand): exit with status code
- via TclTkIp#_eval didn't work. [ruby-talk:139390]
-
-Fri Apr 22 16:41:50 2005 Hirokazu Yamamoto <ocean@m2.ccsnet.ne.jp>
-
- * ext/tcltklib/tcltklib.c (ip_set_exc_message): fixed memory leak.
-
- * ext/tcltklib/tcltklib.c: eTkCallbackReturn was not initialized.
-
-Thu Apr 21 00:07:50 2005 Nobuyoshi Nakada <nobu@ruby-lang.org>
-
- * lib/mkmf.rb (create_makefile): support platforms have file separator
- other than /.
-
- * {bcc32,win32,wince}/Makefile.sub (BUILD_FILE_SEPARATOR): separator
- of building platform.
-
- * {bcc32,win32,wince}/Makefile.sub (CP, INSTALL): use COPY command.
-
-Wed Apr 20 23:22:39 2005 Nobuyoshi Nakada <nobu@ruby-lang.org>
-
- * Makefile.in, common.mk: miniruby depens on MINIOBJS.
-
- * dmydln.c (dln_load): dummy function to raise LoadError.
-
- * cygwin/GNUmakefile.in, {bcc32,win32,wince}/Makefile.sub: miniruby
- can't load extensions on Windows.
-
-Wed Apr 20 23:01:35 2005 Nobuyoshi Nakada <nobu@ruby-lang.org>
-
- * win32/ifchange.bat: delete testing files.
-
-Wed Apr 20 07:27:18 2005 Nobuyoshi Nakada <nobu@ruby-lang.org>
-
- * {bcc32,win32,wince}/configure.bat, {bcc32,win32,wince}/setup.mak:
- add extout option.
-
- * bcc32/setup.mak: make configuration variables overridable.
-
-Wed Apr 20 04:15:27 2005 Keiju Ishitsuka <keiju@ruby-lang.org>
-
- * lib/irb.rb lib/irb/* doc/irb: IRB 0.9.5
-
-Tue Apr 19 23:37:09 2005 WATANABE Hirofumi <eban@ruby-lang.org>
-
- * lib/ftools.rb (File.safe_unlink): do not modify a symlinked file.
-
-Tue Apr 19 00:06:20 2005 Nobuyoshi Nakada <nobu@ruby-lang.org>
-
- * ext/extmk.rb: expand path for ext/**/extconf.rb.
-
-Mon Apr 18 11:25:14 2005 Hirokazu Yamamoto <ocean@m2.ccsnet.ne.jp>
-
- * ext/zlib/zlib.c (zstream_run): fixed SEGV. [ruby-core:4712]
-
-Sun Apr 17 23:57:49 2005 Nobuyoshi Nakada <nobu@ruby-lang.org>
-
- * ext/extmk.rb (extmake, parse_args): do not expand destdir.
-
- * ext/extmk.rb (relative_from): treat mere drive letter as an absolute
- path.
-
-Sat Apr 16 17:01:16 2005 Kouhei Sutou <kou@cozmixng.org>
-
- * sample/rss/tdiary_plugin/rss-recent.rb (rss_recent_cache_rss):
- use the first date information of items as site date information
- if channel doesn't have date information.
-
-Sat Apr 16 15:27:03 2005 Nobuyoshi Nakada <nobu@ruby-lang.org>
-
- * configure.in (RUBY_PROG_INSTALL): not add -p option to INSTALL.
- files need timestamps to be kept are only ar-archive on a few
- platforms, and be installed by instruby.rb but not INSTALL.
- fixed: [ruby-core:04721]
-
- * mkconfig.rb: purge autoconf value variables.
-
-Sat Apr 16 10:36:01 2005 Hirokazu Yamamoto <ocean@m2.ccsnet.ne.jp>
-
- * bcc32/Makefile.sub: quick hack... prepend DESTDIR.
- still have restriction on DESTDIR ("", "/", "e:")
-
-Sat Apr 16 03:59:42 2005 GOTOU Yuuzou <gotoyuzo@notwork.org>
-
- * ext/openssl/extconf.rb: check for OPENSSL_cleanse.
-
- * ext/openssl/openssl_missing.h: ditto.
-
-Thu Apr 14 19:18:30 2005 Minero Aoki <aamine@loveruby.net>
-
- * lib/fileutils.rb (remove_file): ignore exceptions caused by
- chmod.
-
- * lib/fileutils.rb (remove_dir): try to get rights to rmdir.
- [ruby-Bugs:1502] (2 items backportted from HEAD, rev 1.53-54)
-
-Thu Apr 14 16:57:40 2005 Nobuyoshi Nakada <nobu@ruby-lang.org>
-
- * bcc32/Makefile.sub: failed to remove debug information files.
- fixed: [ruby-dev:26034]
-
-Wed Apr 13 23:40:21 2005 Kouhei Sutou <kou@cozmixng.org>
-
- * lib/rss/rss.rb (RSS::VERSION): 0.1.3 -> 0.1.4.
-
- * lib/rss/rss.rb (RSS::Element#converter): fixed converter
- transmission bug.
-
-Wed Apr 13 21:20:35 2005 WATANABE Hirofumi <eban@ruby-lang.org>
-
- * configure.in (mingw32): extract msvcr*.dll from objdump result.
-
-Wed Apr 13 20:24:30 2005 Nobuyoshi Nakada <nobu@ruby-lang.org>
-
- * configure.in (mingw32): use actual runtime DLL name as ruby DLL
- name and default load path.
-
- * win32/Makefile.sub, win32/setup.mak: ditto.
-
-Tue Apr 12 15:33:09 2005 Hidetoshi NAGAI <nagai@ai.kyutech.ac.jp>
-
- * ext/tcltklib/tcltklib.c (ip_finalize): better modification than the
- previous commit [ruby-dev:26029].
-
-Tue Apr 12 12:38:06 2005 Hidetoshi NAGAI <nagai@ai.kyutech.ac.jp>
-
- * ext/tcltklib/tcltklib.c (ip_finalize): fix SEGV when Tcl_GlobalEval()
- modifies the argument string to eval.
-
-Tue Apr 12 02:21:55 2005 Hidetoshi NAGAI <nagai@ai.kyutech.ac.jp>
-
- * ext/tcltklib/tcltklib.c (ip_finalize): add existence check of
- Tcl commands before calling Tcl_GlobalEval().
-
-Mon Apr 11 23:47:21 2005 Masatoshi SEKI <m_seki@mva.biglobe.ne.jp>
-
- * lib/drb/drb.rb: [druby-ja:123] fix: When reference of my object is
- loaded, the object is tainted.
-
- * test/drb/test_drb.rb: ditto.
-
-Mon Apr 11 22:18:23 2005 WATANABE Hirofumi <eban@ruby-lang.org>
-
- * dir.c, file.c (lstat): avoid warnings for mingw.
-
-Mon Apr 11 20:11:06 2005 Hidetoshi NAGAI <nagai@ai.kyutech.ac.jp>
-
- * ext/tcltklib/tcltklib.c (ip_finalize): adhoc patch to avoid SEGV
- when exit on Tcl/Tk8.3.x.
-
-Mon Apr 11 15:26:25 2005 NAKAMURA Usaku <usa@ruby-lang.org>
-
- * lib/mkmf.rb (configuration): shouldn't output hdrdir twice.
-
-Mon Apr 11 12:09:05 2005 Hirokazu Yamamoto <ocean@m2.ccsnet.ne.jp>
-
- * {bcc32,win32,wince}/Makefile.sub: ri data was not installed
- into correct path. [ruby-dev:26011]
-
- * bcc32/Makefile.sub: defaulted install-nodoc. [ruby-dev:26011]
-
-Sun Apr 10 10:12:42 2005 Masaki Suketa <masaki.suketa@nifty.ne.jp>
-
- * ext/win32ole/win32ole.c(ole_invoke): retry after converting Qnil
- to VT_EMPTY.
-
- * ext/win32ole/win32ole/tests/testWIN32OLE.rb: correct error
- message string "Unknown" => "unknown".
-
-Sat Apr 9 18:20:31 2005 Hidetoshi NAGAI <nagai@ai.kyutech.ac.jp>
-
- * ext/tk/lib/tk/image.rb: support to create TkImage object without
- creating a new image object on Tk.
-
- * ext/tk/lib/tk/menu.rb: use TkCommandNames on create_self()
-
- * ext/tk/lib/tk/root.rb: TkRoot.to_eval() returns '.'.
-
- * ext/tk/lib/tk/text.rb: add methods to create a TkText::IndexString
- from (x, y) coords.
-
- * ext/tk/lib/tkextlib/tile/: add demo and update support status.
-
-Sat Apr 9 14:42:29 2005 Kouhei Sutou <kou@cozmixng.org>
-
- * sample/rss/tdiary_plugin/rss-recent.rb: supported configuration
- via Web browser.
-
-Sat Apr 9 11:59:57 2005 Kouhei Sutou <kou@cozmixng.org>
-
- * lib/rss: backoported from HEAD.
-
- * lib/rss: refactored.
- - gave a name to 'x'.
- - undef_method -> remove_method for avoiding a warning in ruby 1.6.
-
-
- * lib/rss/parser.rb: @@setter -> @@setters.
-
- * lib/rss/parser.rb
- (RSS::BaseListener.register_uri)
- (RSS::BaseListener.uri_registered?)
- (RSS::BaseListener.install_get_text_element):
- swapped the first argument and the second argument.
-
- * lib/rss/taxonomy.rb: swapped the first argument and the second
- argument for RSS::BaseListener.install_get_text_element.
- * lib/rss/image.rb: ditto.
- * lib/rss/syndication.rb: ditto.
- * lib/rss/dublincore.rb: ditto.
- * lib/rss/parser.rb: ditto.
- * lib/rss/1.0.rb: ditto.
- * lib/rss/2.0.rb: ditto.
- * lib/rss/0.9.rb: ditto.
- * lib/rss/content.rb: ditto.
-
- * lib/rss/parser.rb
- (RSS::BaseListener.install_setter)
- (RSS::BaseListener.register_uri): changed fallback way.
-
- * lib/rss/parser.rb: added class name registry for complex model
- elements. (ex. have childlen elements, have some attributes and
- a child element and so on.)
-
-
- * lib/rss/dublincore.rb: supported multiple Dublin Core items.
- * lib/rss/maker/dublincore.rb: ditto.
-
- * lib/rss/maker/image.rb: supproted new Dublin Core API.
-
-
- * lib/rss/maker/base.rb: added default current_element implementation.
-
-
- * lib/rss/trackback.rb (RSS::TrackBackUtils.new_with_value_if_need):
- moved to RSS::Utils.
-
- * lib/rss/utils.rb (RSS::Utils.new_with_value_if_need):
- moved from RSS::TrackBackUtils.
-
-
- * lib/rss/maker/image.rb: fixed invalid argument of
- add_need_initialize_variable bug.
- * lib/rss/maker/trackback.rb: ditto.
-
-
- * lib/rss/rss.rb (Hash#merge): added for ruby 1.6.
-
- * lib/rss/rss.rb (RSS::BaseModel.date_writer): changed to accept nil
- for date value.
-
-
- * test/test_dublincore.rb: added tests for plural accessor and
- multiple Dublin Core items.
-
- * test/test_setup_maker_1.0.rb: fixed swapped actual and expected
- values.
-
- * test/rss/rss-assertions.rb (assert_multiple_dublin_core): added
- an assertion for testing multiple Dublin Core items.
-
- * test/rss/test_maker_dc.rb (test_rss10_multiple): added a test
- for making multiple Dublin Core items.
-
- * test/rss/test_maker_dc.rb (test_date): added a test for #date=
- and #dc_date=.
-
-
- * sample/rss/tdiary_plugin/rss-recent.rb:
- new option: @options['rss-recent.use-image-link']:
- use image as link instread of text if available.
-
- * sample/rss/tdiary_plugin/rss-recent.rb (RSS_RECENT_VERSION):
- 0.0.5 -> 0.0.6.
-
-Fri Apr 8 20:17:48 2005 Nobuyoshi Nakada <nobu@ruby-lang.org>
-
- * ext/extmk.rb (extmake): hdrdir needs to be defined also in
- Config::CONFIG.
-
- * lib/mkmf.rb (configuration, create_makefile): get rid of recursive
- macro reference.
-
-Fri Apr 8 18:26:56 2005 GOTOU Yuuzou <gotoyuzo@notwork.org>
-
- * ext/openssl/ossl_ssl.c: add callbacks to OpenSSL::SSL::SSLContexts.
- - SSLContext#client_cert_cb=(aProc). it is called when a client
- certificate is requested by a server and no certificate was not
- set for the SSLContext. it must return an Array which includes
- OpenSSL::X509::Certificate and OpenSSL::PKey::RSA/DSA objects.
- - SSLContext#tmp_dh_callback=(aProc). it is called in key
- exchange with DH algorithm. it must return an OpenSSL::PKey::DH
- object.
-
- * ext/openssl/ossl_ssl.c (ossl_sslctx_set_ciphers): ignore the
- argument if it's nil.
-
- * ext/openssl/ossl_pkey.c
- (GetPrivPKeyPtr, ossl_pkey_sign): should call rb_funcall first.
- (DupPrivPKeyPtr): new function.
-
- * ext/openssl/ossl_pkey_dh.c: add default DH parameters.
-
- * ext/openssl/ossl_pkey.h: ditto.
-
-Fri Apr 8 01:55:20 2005 Hidetoshi NAGAI <nagai@ai.kyutech.ac.jp>
-
- * ext/tk/sample/demos-{en,jp}/goldberg.rb: reduced window size.
- [ruby-dev:25992]
-
-Thu Apr 7 23:58:40 2005 Nobuyoshi Nakada <nobu@ruby-lang.org>
-
- * ext/extmk.rb (extmake): keep directory names in Makefile as macros.
-
- * lib/mkmf.rb (configuration, create_makefile): ditto.
-
- * lib/mkmf.rb (CXX_EXT): separate C++ extensions.
-
-Thu Apr 7 17:43:25 2005 Shugo Maeda <shugo@ruby-lang.org>
-
- * eval.c (rb_call0): "return" event hook should be always executed
- if event_hooks is set. fixed: [ruby-core:04662]
- (backported from HEAD)
-
-Mon Apr 4 23:17:52 2005 Hidetoshi NAGAI <nagai@ai.kyutech.ac.jp>
-
- * ext/tk/lib/tk.rb (TkComm#array2tk_list): accept enc-mode argument to
- decide whether convert encoding of each element or not.
-
- * ext/tk/lib/tk/variable.rb (TkVariable#value=): fail to convert the
- encoding of array elements when assign an array to an TkVariable
- object.
-
-Mon Apr 4 10:26:48 2005 Hirokazu Yamamoto <ocean@m2.ccsnet.ne.jp>
-
- * ext/tk/lib/tk/dialog.rb: fixed typo.
-
-Sun Apr 3 17:16:33 2005 Hirokazu Yamamoto <ocean@m2.ccsnet.ne.jp>
-
- * win32/win32.{h,c} (rb_w32_fdopen): avoid warning on bcc32.
- (backported from HEAD)
-
-Sat Apr 2 23:38:54 2005 Nobuyoshi Nakada <nobu@ruby-lang.org>
-
- * configure.in (CP, INSTALL): get rid of less portable options.
-
- * lib/mkmf.rb (configuration, create_makefile): correct configuration
- variable.
-
- * {bcc32,win32,wince}/{Makefile.sub,setup.mak}: leave prefix empty in
- config.status for backward compatibility. fixed: [ruby-core:04649]
-
- * lib/mkmf.rb (create_makefile): ensure library directories get made
- before copying libraries there.
-
-Sat Apr 2 16:59:46 2005 Hidetoshi NAGAI <nagai@ai.kyutech.ac.jp>
-
- * ext/tk/lib/tk.rb: forgot to update RELEASE_DATE
-
- * ext/tk/lib/tk/variable.rb: fix namespace trouble when autoloading
-
- * ext/tk/lib/tk/palette.rb: define Tcl variable 'tkPalette' as global
-
- * ext/tk/lib/tk/dialog.rb: use array2tk_list method when calling
- Tk.ip_eval.
-
- * ext/tk/lib/tk/autoload.rb: add autoload entry 'TkDialogObj' and
- 'TkWarningObj'
-
-Sat Apr 2 02:19:11 2005 Hidetoshi NAGAI <nagai@ai.kyutech.ac.jp>
-
- * ext/tk/lib/tk.rb (TkWindow.initialize): accept 'without_creating'
- option without 'widgetname' option to allow creating a widget object
- which is used as an argument of Tcl/Tk's widget allocation commands.
-
- * ext/tk/lib/tk/image.rb (TkImage.initialize): accept 'imagename'
- option to create a image object by the given name.
-
-Thu Mar 31 22:23:51 2005 Nobuyoshi Nakada <nobu@ruby-lang.org>
-
- * lib/mkmf.rb (SRC_EXT): exclude just case different suffixes on case
- insensitive file system platforms.
-
- * README.EXT, README.EXT.ja (Appendix C): utility functions.
-
-Thu Mar 31 14:15:44 2005 GOTOU Yuuzou <gotoyuzo@notwork.org>
-
- * ext/openssl/ossl_engine.c (ossl_engine_s_load): should return
- value. [ruby-dev:25971]
-
-Thu Mar 31 08:25:50 2005 Nobuyoshi Nakada <nobu@ruby-lang.org>
-
- * common.mk (RUBYOPT): clear for the environment RubyGems installed.
-
- * common.mk (clean-local): keep $(PREP) files till distclean.
-
- * common.mk (check): do all tests.
-
-Thu Mar 31 06:00:20 2005 GOTOU Yuuzou <gotoyuzo@notwork.org>
-
- * ext/openssl/ossl_engine.c (ossl_engine_s_load): should not raise
- error even if the specified engine could not be loaded. (Dynamic
- engines don't have fixed name to load.)
-
-Thu Mar 31 00:18:27 2005 Hirokazu Yamamoto <ocean@m2.ccsnet.ne.jp>
-
- * win32/ifchange.bat, win32/rm.bat: backported from HEAD.
-
-Wed Mar 30 23:44:50 2005 Nobuyoshi Nakada <nobu.nokada@softhome.net>
-
- * Makefile.in, */Makefile.sub, */configure.bat,
- cygwin/GNUmakefile.in, common.mk, configure.in, ext/extmk.rb,
- lib/mkmf.rb, instruby.rb, runruby.rb: backport extout.
- [ruby-dev:25963]
-
-Wed Mar 30 17:41:48 2005 Hidetoshi NAGAI <nagai@ai.kyutech.ac.jp>
-
- * ext/tcltklib/tcltklib.c: add TclTkIp#_create_console() method to
- create a Tcl/Tk's console window.
-
- * ext/tk/lib/multi-tk.rb: support TclTkIp#_create_console() method.
-
- * ext/tk/lib/remote-tk.rb: ditto.
-
- * ext/tk/lib/tk/console.rb: ditto.
-
- * ext/tk/lib/tk.rb: update RELEASE_DATE
-
- * ext/tk/sample/demo-*/check2.rb: use 'return' in the Proc object.
-
- * ext/tk/sample/tkextlib/**: ditto.
-
-Tue Mar 29 22:11:56 2005 Masatoshi SEKI <m_seki@mva.biglobe.ne.jp>
-
- * test/rinda/test_rinda.rb: use DRbObject.new_with instead of reinit.
- [ruby-dev:25961]
-
-Mon Mar 28 23:40:40 2005 Masatoshi SEKI <m_seki@mva.biglobe.ne.jp>
-
- * lib/drb/drb.rb: move method DRbObject#reinit to DRbObject.new_with.
- extract method DRbObject.prepare_backtrace. add DRb.regist_server,
- remove_server, fetch_server. change server in thread variable if
- in-proc server. [druby-ja:113]
-
- * lib/drb/gw.rb: ditto.
-
-Mon Mar 28 20:43:34 2005 Nobuyoshi Nakada <nobu@ruby-lang.org>
-
- * ext/syck/rubyext.c: get rid of warnings caused by a bug of VC.
-
-Mon Mar 28 08:39:49 2005 Nobuyoshi Nakada <nobu@ruby-lang.org>
-
- * ext/iconv/iconv.c (iconv_create): Iconv::Failure requires 3
- arguments. (pointed out by NaHi)
-
-Sat Mar 26 22:51:33 2005 Hidetoshi NAGAI <nagai@ai.kyutech.ac.jp>
-
- * ext/tk/lib/tk.rb (_callback_entry_class?): add for checking whether
- a class is available for a callback entry.
-
- * ext/tk/lib/tk.rb (after_cancel): add Tk.after_cancel(afterID) method.
-
- * ext/tk/lib/tk.rb (array2tk_list): change from private module method
- of TkComm to public module method.
-
- * ext/tk/lib/tk.rb (cget): add check that slot argument is not
- empty string.
-
- * ext/tk/lib/tk.rb (configinfo): ditto.
-
- * ext/tk/lib/tk/itemconfig.rb (itemcget): add check that slot argument
- is not empty string.
-
- * ext/tk/lib/tk/itemconfig.rb (itemconfiginfo): ditto.
-
- * ext/tk/lib/tk/entry.rb: add TkEntry#icursor and icursor= (alias of
- cursor and cursor= method).
-
- * ext/tk/lib/tk/font.rb: improve font treatment when the font name is
- empty string.
-
- * ext/tk/lib/tk/variable.rb: add :variable, :window and :procedure
- type.
-
- * ext/tk/lib/tk/variable.rb: improve treatment of array-type
- tkvariable.
-
- * ext/tk/lib/tkextlib/blt.rb: add commands for zooming.
-
- * ext/tk/lib/tkextlib/blt/*: bug fix.
-
- * ext/tk/lib/tkextlib/treectrl/tktreectrl.rb: bug fix and add methods
- to call TreeCtrl commands for bindings.
-
- * ext/tk/sample/tkextlib/blt/*: new sample scripts.
-
- * ext/tk/sample/tkextlib/treectrl/*: ditto.
-
-Fri Mar 25 10:53:16 2005 WATANABE Hirofumi <eban@ruby-lang.org>
-
- * configure.in (WIN32_LEAN_AND_MEAN): removed because a lot of
- troubles. [ruby-list:40721]
-
-Thu Mar 24 23:10:44 2005 Nobuyoshi Nakada <nobu@ruby-lang.org>
-
- * lib/mkmf.rb (macro_defined?): try to compile for an old compiler
- which doesn't bail out at #error directive. [ruby-dev:25818]
-
- * lib/mkmf.rb (check_sizeof): refine logging messages.
-
-Thu Mar 24 03:57:48 2005 GOTOU Yuuzou <gotoyuzo@notwork.org>
-
- * lib/webrick/utils.rb (WEBrick::Utils.create_listeners):
- - should raise ArgumentError if no port is specified.
- - even if the specified port is 0, all TCPServers should be
- initialized with the port given to the first one.
-
- * lib/webrick/server.rb (WEBrick::GenericServer#initialize): if :Port
- parameter is 0, it should be updated with the port number which
- actually listened.
-
-Wed Mar 23 00:35:10 2005 Shugo Maeda <shugo@ruby-lang.org>
-
- * test/ruby/test_settracefunc.rb (test_event): added tests for
- "class" and "end" and "raise".
-
-Tue Mar 22 22:40:18 2005 Shugo Maeda <shugo@ruby-lang.org>
-
- * eval.c (rb_call0): check event_hooks instead of trace_func.
-
-Tue Mar 22 17:30:44 2005 Shugo Maeda <shugo@ruby-lang.org>
-
- * eval.c (rb_add_event_hook): new function to add a hook function for
- interpreter events. (backported form HEAD)
-
-Sun Mar 20 22:51:19 2005 Nobuyoshi Nakada <nobu@ruby-lang.org>
-
- * lib/mkmf.rb (mkmf_failed): check if Makefile is created without
- create_makefile.
-
-Sat Mar 19 23:48:10 2005 Nobuyoshi Nakada <nobu@ruby-lang.org>
-
- * misc/ruby-mode.el (ruby-expr-beg): returned true always.
- fixed: [ruby-list:40683]
-
-Sat Mar 19 00:41:02 2005 Hidetoshi NAGAI <nagai@ai.kyutech.ac.jp>
-
- * ext/tk/lib/tk/font.rb: add some TkFont class methods to get font
- information without creating a TkFont object.
-
- * ext/tk/lib/tkextlib/treectrl/tktreectrl.rb: bug fix and define some
- classes for components of Tk::TreeCtrl
-
-Thu Mar 17 17:42:13 2005 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * struct.c (make_struct): allow non local-id field
- names. [ruby-core:04575]
-
- * struct.c (inspect_struct): ditto.
-
-Wed Mar 16 23:36:02 2005 Shugo Maeda <shugo@ruby-lang.org>
-
- * eval.c (rb_call0): call_cfunc() should be protected.
-
- * test/ruby/test_settracefunc.rb: added test for c-return.
-
-Wed Mar 16 22:20:25 2005 Hirokazu Yamamoto <ocean@m2.ccsnet.ne.jp>
-
- * object.c (str_to_id): fixed typo.
-
-Wed Mar 16 18:08:32 2005 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * eval.c (rb_call0): reorganize "return" event post.
-
-Tue Mar 15 23:49:19 2005 Nobuyoshi Nakada <nobu@ruby-lang.org>
-
- * ext/iconv/iconv.c (Init_iconv): InvalidEncoding also should include
- Iconv::Failure.
-
-Tue Mar 15 16:38:11 2005 Hidetoshi NAGAI <nagai@ai.kyutech.ac.jp>
-
- * ext/tk/tkutil.c (ary2list): give wrong arguments to hash2kv()
-
-Mon Mar 14 19:39:33 2005 Hidetoshi NAGAI <nagai@ai.kyutech.ac.jp>
-
- * ext/tk/lib/tk/timer.rb (TkTimer): forgot to clear @return_value
- when restarting
-
- * ext/tk/lib/tk/sample/cd_timer.rb: new sample of TkRTTimer
-
-Mon Mar 14 12:21:03 2005 Hidetoshi NAGAI <nagai@ai.kyutech.ac.jp>
-
- * ext/tk/lib/tk/timer.rb (TkRTTimer): forgot to reset the callback
- time. So, 'continue' do all callbacks between 'stop' and 'continue'.
-
-Mon Mar 14 08:14:56 2005 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * object.c (str_to_id): warn for NUL containing strings.
-
-Mon Mar 14 00:13:49 2005 Hidetoshi NAGAI <nagai@ai.kyutech.ac.jp>
-
- * ext/tk/lib/tk/timer.rb (TkRTTimer): correct calculation of offset
- value. get a little better accuracy.
-
- * ext/tk/sample/demos-en/widget: use a binding with no local variables
- when eval a sample script.
-
- * ext/tk/sample/demos-en/bind.rb: ditto.
-
- * ext/tk/sample/demos-en/tcolor: ditto.
-
- * ext/tk/sample/demos-jp/widget: ditto.
-
- * ext/tk/sample/demos-jp/bind.rb: ditto.
-
- * ext/tk/sample/demos-jp/tcolor: ditto.
-
-Sun Mar 13 10:04:17 2005 Masatoshi SEKI <m_seki@mva.biglobe.ne.jp>
-
- * test/rinda/test_rinda.rb: remove test_gc. [ruby-dev:25871]
-
-Thu Mar 10 19:12:06 2005 Hidetoshi NAGAI <nagai@ai.kyutech.ac.jp>
-
- * ext/tcltklib/tcltklib.c (lib_eventloop_ensure): mis-delete a timer
- handler when exit from a recursive called eventloop
-
- * ext/tk/lib/tk/timer.rb: new TkRTTimer class, which can works for a
- realtime operation
-
- * ext/tk/sample/tkrttimer.rb: sample of TkRTTimer class
-
- * ext/tk/lib/tk/textmark.rb: move TkTextMark#+ and TkTextMark#- to
- TkText::IndexModMethods
-
- * ext/tk/lib/tk/text.rb: improve TkTextMark#+ and TkTextMark#-, and
- add them to TkText::IndexModMethods module
-
- * ext/tk/sample/tktextio.rb: add test part of "seek by text index
- modifiers"
-
-Thu Mar 10 08:10:11 2005 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * re.c (make_regexp): need to free internal regexp structure when
- compilation fails. [ruby-talk:133228]
-
-Wed Mar 9 20:25:58 2005 GOTOU Yuuzou <gotoyuzo@notwork.org>
-
- * ext/openssl/ossl_ssl.c (ossl_start_ssl, ossl_ssl_write): call
- rb_sys_fail if errno isn't 0. [ruby-dev:25831]
-
- * ext/openssl/lib/openssl/cipher.rb: fix typo. [ruby-dev:24285]
-
-Wed Mar 9 15:46:35 2005 GOTOU Yuuzou <gotoyuzo@notwork.org>
-
- * lib/webrick/server.rb (WEBrick::GenericServer#start): should
- restore @token if accept failure. suggested by Dominique Brezinski.
- [ruby-core:04518]
-
-Wed Mar 9 13:37:57 2005 Hidetoshi NAGAI <nagai@ai.kyutech.ac.jp>
-
- * ext/tk/sample/tktextio.rb: fix bug of handling 'end' position.
- support initial text, overwrite setting and pos_gravity control.
-
-Tue Mar 8 18:16:55 2005 Hidetoshi NAGAI <nagai@ai.kyutech.ac.jp>
-
- * ext/tk/sample/tktextio.rb: New sample script. TkTextIO class in this
- sample supports to use a text widget as if it is a I/O stream (such
- like as StringIO class).
-
-Tue Mar 8 13:54:40 2005 NAKAMURA Usaku <usa@ruby-lang.org>
-
- * ext/socket/socket.c: workaround for some of 4.4BSD-Lite derived OSs.
-
-Tue Mar 8 12:36:17 2005 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * ext/socket/socket.c: document from Sam Roberts
- <sroberts@uniserve.com> for getsockopt and setsockopt is merged.
- [ruby-doc:824]
-
-Tue Mar 8 01:27:00 2005 NARUSE, Yui <naruse@ruby-lang.org>
-
- * ext/nkf/nkf-utf8/nkf.c: follow nkf 1.66
- fixed: [ruby-dev:25828]
-
-Mon Mar 7 21:35:02 2005 GOTOU Yuuzou <gotoyuzo@notwork.org>
-
- * sample/webrick/httpsd.rb: fix typo in comment. suggested by
- Kazuhiko Shiozaki.
-
-Mon Mar 7 14:55:43 2005 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * eval.c (block_pass): should not push unique number if a block is
- not an orphan. [ruby-dev:25808]
-
-Wed Feb 16 02:55:21 2005 GOTOU Yuuzou <gotoyuzo@notwork.org>
-
- * ext/openssl/ossl_ssl.c (ossl_start_ssl, ossl_ssl_read,
- ossl_ssl_write):
- - need to set errno on Win32 platform.
- - should call rb_sys_fail instead of rasing SSLError if
- SSL_ERROR_SYSCALL occured.
- - should wait for that the underlying IO become readable or
- writable if the error was SSL_ERROR_WANT_READ or
- SSL_ERROR_WANT_WRITE. [ruby-dev:25795]
-
- * ext/openssl/lib/openssl/buffering.rb
- (Buffering#initialize): should set @eof and @rbuffer.
- (Buffering#fill_rbuff): should rescue Errno::EAGAIN.
- (Buffering#consume_rbuf): pointless eof flag resetting is deleted.
- (Buffering#read): should return an empty string if the specified
- size is zero.
- (Buffering#readpartial): new method.
- (Buffering#readline): fix typo.
- (Buffering#getc): return the first character of string correctly.
- (Buffering#each): fix typo. suggested by Brian Ollenberger.
- (Buffering#readchar): fix typo.
- (Buffering#eof?): should read again it the input buffer is empty.
- (Buffering#do_write): should rescue Errno::EAGAIN.
- (Buffering#puts): use "\n" as the output field separator.
-
- * ext/openssl/lib/openssl/ssl.rb: set non-blocking flag to the
- underlying IO.
-
- * ext/openssl/extconf.rb: get rid of GNUmakefile generation.
-
- * text/openssl/test_pair.rb: test for IO like methods.
-
- * test/ruby/ut_eof.rb: test about empty file.
-
-Mon Mar 7 10:22:06 2005 WATANABE Hirofumi <eban@ruby-lang.org>
-
- * lib/un.rb: should use OptionParser. (backported form HEAD)
-
-Mon Mar 7 09:18:42 2005 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * string.c (rb_str_cmp_m): should not return false but nil.
- fixed: [ruby-dev:25811]
-
-Mon Mar 7 01:22:14 2005 Hidetoshi NAGAI <nagai@ai.kyutech.ac.jp>
-
- * ext/tk/tkutil.c: remove the some codes which depend on the
- difference between Ruby1.8 and 1.9, because st.c on Ruby1.9
- was changed.
-
-Mon Mar 7 00:01:04 2005 Hidetoshi NAGAI <nagai@ai.kyutech.ac.jp>
-
- * ext/tcltklib/tcltklib.c: fail to call TclTkLib.mainloop when $SAFE==4
-
-Sun Mar 6 16:41:33 2005 Minero Aoki <aamine@loveruby.net>
-
- * lib/net/http.rb: HTTPHeader holds its header fields as an array
- (backport from CVS HEAD rev 1.112-1.123). [ruby-list:40629]
-
- * test/net/http/test_httpheader.rb: new file.
-
-Sun Mar 6 11:47:10 2005 Sam Roberts <sroberts@uniserve.com>
-
- * lib/pp.rb: rdoced. [ruby-core:4490]
-
-Sun Mar 6 11:36:37 2005 Tanaka Akira <akr@m17n.org>
-
- * lib/pp.rb (File::Stat#pretty_print): Etc.getpwuid and Etc.getgrgid
- may return nil. [ruby-talk:129826]
- reported by Daniel Berger.
-
-Sat Mar 5 18:06:21 2005 Hirokazu Yamamoto <ocean@m2.ccsnet.ne.jp>
-
- * dir.c (fnmatch): removed unnecessary code. (ruby_1_8 didn't have
- String#clear, so [ruby-dev:24749] didn't affect it)
-
- * win32/win32.c (NtInitialize): ditto. (by numeric.c 1.101.2.14)
-
-Sat Mar 5 16:29:26 2005 Hidetoshi NAGAI <nagai@ai.kyutech.ac.jp>
-
- * ext/tk/lib/multi-tk.rb: freeze callback-entry objects
-
- * ext/tk/lib/tkextlib/tile.rb: support tile-0.6
-
-Fri Mar 4 19:39:28 2005 Nobuyoshi Nakada <nobu@ruby-lang.org>
-
- * lib/rdoc/parsers/parse_c.rb (RDoc::C_Parser#do_includes): replace
- also locally defined modules.
-
- * ext/iconv/iconv.c: backport Iconv::InvalidEncoding from CVS HEAD.
-
- * ext/strscan/strscan.c: moved misplaced rdoc.
-
-Fri Mar 4 15:58:12 2005 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * lib/cgi-lib.rb: add deprecation warning. [ruby-dev:25499]
- getopts.rb, parsearg.rb, importenv.rb as well.
-
-Fri Mar 4 11:17:06 2005 Hidetoshi NAGAI <nagai@ai.kyutech.ac.jp>
-
- * ext/tcltklib/tcltklib.c (ip_rbUpdateCommand): get rid of
- warnings with Tcl/Tk 8.3 or former (backport from CVS_HEAD).
-
- * ext/tcltklib/tcltklib.c (ip_rb_threadUpdateCommand): ditto.
-
-Fri Mar 4 10:15:30 2005 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * lib/set.rb (SortedSet::setup): a hack to shut up warning.
- [ruby-talk:132866]
-
-Fri Mar 4 07:07:00 2005 NARUSE, Yui <naruse@ruby-lang.org>
-
- * ext/nkf/nkf-utf8/nkf.c: follow nkf 1.63
-
-Thu Mar 3 23:49:00 2005 NARUSE, Yui <naruse@ruby-lang.org>
-
- * ext/nkf/nkf-utf8/nkf.c: follow nkf 1.62
-
-Thu Mar 3 11:49:51 2005 Kouhei Sutou <kou@cozmixng.org>
-
- * sample/rss/tdiary_plugin/rss-recent.rb: added site information.
-
-Wed Mar 2 19:53:07 2005 Nobuyoshi Nakada <nobu@ruby-lang.org>
-
- * ext/extmk.rb (parse_args): add DESTDIR only when not directed
- already. fixed: [ruby-dev:25781]
-
-Wed Mar 2 17:14:18 2005 Hidetoshi NAGAI <nagai@ai.kyutech.ac.jp>
-
- * ext/tcltklib/tcltklib.c (lib_eventloop_core): fix typo
-
-Wed Mar 2 16:00:02 2005 Hidetoshi NAGAI <nagai@ai.kyutech.ac.jp>
-
- * ext/tcltklib/tcltklib.c: enforce thread-check and exception-handling
- to avoid SEGV trouble.
- [KNOWN BUG] When supports pthread and running multiple Tk
- interpreters, an interrupt signal causes SEGV frequently. That
- may be a trouble of Ruby's signal handler.
-
- * ext/tk/tkutil/tkutil.c; fix a bug on converting a SJIS string array
- to a Tcl's list string.
-
- * ext/tk/tcltklib.c: wrap Tcl's original "namespace" command to
- protect from namespace crash.
-
- * ext/tk/lib/multi-tk.rb: enforce exception-handling.
-
- * ext/tk/lib/multi-tk.rb: catch IRB_EXIT to work on irb.
-
- * ext/tk/lib/tk.rb: ditto.
-
- * ext/tk/tcltklib.c: add TclTkLib.mainloop_thread?
-
- * ext/tk/lib/multi-tk.rb: (bug fix) callback returns a value.
-
- * ext/tk/lib/tk/canvas.rb (delete): bug fix when multiple arguments.
-
- * ext/tk/lib/clock.rb: fix 'no method error'.
-
- * ext/tk/lib/clock.rb (self.clicks): accept a Symbol argument.
-
- * ext/tk/lib/variable.rb: be able to set default_value_type; :numeric,
- :bool, :string, :symbol, :list, :numlist or nil (default; same to
- :string). If set a type, TkVariable#value returns a value of the
- type.
-
- * ext/tk/lib/tkextlib/tclx/tclx.rb: add Tk::TclX.signal to warn the
- risk of using TclX extension's 'signal' command.
-
- * ext/tk/sample/irbtk.rb: irb with Ruby/Tk.
-
- * ext/tk/sample/demos-*/anilabel.rb: bug fix on 'show code'
-
- * ext/tk/sample/demos-*/aniwave.rb: new Ruby/Tk animation demo.
-
- * ext/tk/sample/demos-*/pendulum.rb: ditto.
-
- * ext/tk/sample/demos-*/goldberg.rb: ditto.
-
- * ext/tk/sample/demos-*/widget: add entries of animation demos.
-
-Tue Mar 1 00:47:43 2005 Masatoshi SEKI <m_seki@mva.biglobe.ne.jp>
-
- * test/rinda/test_rinda.rb: backport from CVS_HEAD. use
- MockClock.sleep instead of Kernel.sleep [ruby-dev:25387]
-
-Tue Mar 1 00:34:24 2005 Masatoshi SEKI <m_seki@mva.biglobe.ne.jp>
-
- * lib/rinda/tuplespace.rb (Rinda::TupleSpace): improved keeper thread.
-
- * test/rinda/test_rinda.rb: ditto.
-
-Mon Feb 28 11:42:23 2005 Ian Macdonald <ian@caliban.org>
-
- * exception error messages updated. [ruby-core:04497]
-
-Mon Feb 28 09:03:09 2005 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * ext/socket/socket.c (Init_socket): add bunch of Socket
- constants. Patch from Sam Roberts <sroberts@uniserve.com>.
- [ruby-core:04409]
-
-Wed Feb 23 15:04:32 2005 akira yamada <akira@ruby-lang.org>
-
- * lib/uri/generic.rb (split_userinfo): should split ":pass" into ""
- and "pass". [ruby-dev:25667]
-
-Wed Feb 23 08:00:18 2005 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * array.c (rb_ary_s_create): no need for negative argc check.
- [ruby-core:04463]
-
- * array.c (rb_ary_unshift_m): ditto.
-
-Wed Feb 23 01:57:46 2005 Shugo Maeda <shugo@ruby-lang.org>
-
- * lib/net/imap.rb (initialize): handle certs correctly. Thanks,
- NABEYA Kenichi. (backported from CVS HEAD)
-
-Tue Feb 22 07:25:18 2005 Nobuyoshi Nakada <nobu@ruby-lang.org>
-
- * parse.y (parser_yylex): identfier after dot must not be a variable.
-
-Mon Feb 21 10:04:49 2005 NAKAMURA Usaku <usa@ruby-lang.org>
-
- * {bcc32,win32,wince}/Makefile.sub (config.h): add fcntl.
-
- * win32/win32.[ch] (fcntl): ditto.
-
- * win32/win32.c (rb_w32_connect): support nonblocking mode.
-
- * ext/socket/socket.c (wait_connectable, ruby_connect): support
- nonblocking connect on various platforms.
- all changes are backported from CVS HEAD. [ruby-core:3154],
- [ruby-core:4364].
-
-Sun Feb 20 00:48:48 2005 Tanaka Akira <akr@m17n.org>
-
- * lib/open-uri.rb (URI::FTP#buffer_open): access mechanism
- re-implemented according to RFC 1738.
- reported by Guillaume Marcais. [ruby-talk:131650]
-
-Sat Feb 19 18:11:47 2005 Masatoshi SEKI <m_seki@mva.biglobe.ne.jp>
-
- * lib/drb/drb.rb (DRbObject#respond_to?): take two arguments.
- [ruby-dev:25722]
-
- * test/drb/drbtest.rb: ditto.
-
-Sat Feb 19 13:52:02 2005 Tanaka Akira <akr@m17n.org>
-
- * lib/open-uri.rb: call OpenSSL::SSL::SSLSocket#post_connection_check
- after connection is made.
-
-Sat Feb 19 01:32:03 2005 Hirokazu Yamamoto <ocean@m2.ccsnet.ne.jp>
-
- * ext/bigdecimal/lib/bigdecimal/newton.rb: resolved LoadError.
- [ruby-dev:25685]
-
- * ext/bigdecimal/sample/linear.rb: ditto.
-
- * ext/bigdecimal/sample/nlsolve.rb: ditto.
-
- * ext/bigdecimal/lib/bigdecimal/nlsolve.rb: removed because this file
- is sample script and same file exists in ext/bigdecimal/sample.
-
-Fri Feb 18 17:14:00 2005 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * lib/xmlrpc/parser.rb (XMLRPC::FaultException): make it subclass
- of StandardError class, not Exception class. [ruby-core:04429]
-
-Thu Feb 17 20:11:18 2005 Hirokazu Yamamoto <ocean@m2.ccsnet.ne.jp>
-
- * lib/drb/drb.rb (DRbServer.default_safe_level): fix typo.
-
-Thu Feb 17 20:11:18 2005 Nobuyoshi Nakada <nobu@ruby-lang.org>
-
- * test/digest/test_digest.rb: separate test case for each algorithms.
- [ruby-dev:25412]
-
-Thu Feb 17 11:54:00 2005 Nathaniel Talbott <ntalbott@ruby-lang.org>
-
- * lib/test/unit/collector.rb (collect_file): now deletes paths added
- to $LOAD_PATH instead of restoring it verbatim.
-
- * lib/test/unit/autorunner.rb (AutoRunner.run): fixed so that
- 'ruby -rtest/unit -rtest1 -rtest2 -e0' will use the objectspace
- collector again. Also tried to simplify the calling convention.
-
- * test/runner.rb: adjusted for new AutoRunner semantics.
-
- * lib/test/unit.rb: ditto.
-
-Thu Feb 17 04:21:47 2005 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * lib/open3.rb (Open3::popen3): $? should not be EXIT_FAILURE.
- fixed: [ruby-core:04444]
-
-Thu Feb 17 00:09:45 2005 Masatoshi SEKI <m_seki@mva.biglobe.ne.jp>
-
- * test/drb/ignore_test_drb.rb: move TestDRbReusePort to new file
- [ruby-dev:25238]
-
- * test/drb/test_drb.rb: add method DRbService.ext_service, move
- TestDRbReusePort to new file [ruby-dev:25238]
-
- * test/drb/test_drb.rb: ditto.
-
- * test/drb/test_drbssl.rb: ditto.
-
- * test/drb/test_drbunix.rb: ditto.
-
- * test/drb/ut_drb.rb: reduce sleep.
-
-Thu Feb 17 00:02:27 2005 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * eval.c (is_defined): NODE_IASGN is an assignment.
-
-Wed Feb 16 23:34:30 2005 Masatoshi SEKI <m_seki@mva.biglobe.ne.jp>
-
- * lib/drb/drb.rb: add lazy stop_service. ([druby-ja:109])
-
- * lib/drb/extserv.rb: ditto.
-
-Wed Feb 16 17:07:57 2005 Hidetoshi NAGAI <nagai@ai.kyutech.ac.jp>
-
- * ext/tk/tkutil.c: Follow the change of st.c (st_foreach)
- [ruby-list:40623].
- Sometimes mis-convert from a Ruby's Array of SJIS Strings, which
- includes some kind of SJIS characters, to a Tcl's UTF8 list string.
-
-Mon Feb 14 23:58:17 2005 Kouhei Sutou <kou@cozmixng.org>
-
- * lib/rss/parser.rb (RSS::ListenerMixin::tag_end):
- fixed invalid namespace handling bug.
-
-Mon Feb 14 13:12:38 2005 GOTOU Yuuzou <gotoyuzo@notwork.org>
-
- * ext/openssl/lib/openssl/ssl.rb
- (OpenSSL::SSL::SSLSocket#post_connection_check): new method.
-
-Mon Feb 14 00:40:49 2005 Masatoshi SEKI <m_seki@mva.biglobe.ne.jp>
-
- * lib/drb/drb.rb (InvokeMethod.perform): pass DRb info to sub thread.
-
- * test/drb/test_drb.rb (test_01_safe1_safe4_eval): fix test case.
-
-Sun Feb 13 23:13:46 2005 Kouhei Sutou <kou@cozmixng.org>
-
- * lib/rss/dublincore.rb (RSS::DublicCoreModel#date{,=}): added
- convenient methods.
-
- * lib/rss/0.9.rb (RSS::Rss::Channel#date{,=}): ditto.
-
- * lib/rss/2.0.rb (RSS::Rss::Channel::Item#date{,=}): ditto.
-
- * test/rss/: added tests for the convenient methods.
-
-Sun Feb 13 22:43:03 2005 Masatoshi SEKI <m_seki@mva.biglobe.ne.jp>
-
- * lib/drb/drb.rb (DRbServer): add default_safe_level, safe_level,
- config[:safe_level] ([druby-ja:120])
-
- * test/drb/test_drb.rb, ut_eval.rb, ut_safe1.rb: ditto.
-
-Sun Feb 13 16:56:52 2005 GOTOU Yuuzou <gotoyuzo@notwork.org>
-
- * lib/webrick/cgi.rb (WEBrick::CGI.start): should set reason-phrase
- to the value of status header field. ([ruby-dev:40617])
-
-Sun Feb 13 00:52:33 2005 Masatoshi SEKI <m_seki@mva.biglobe.ne.jp>
-
- * lib/erb.rb (ERB::Util.h, u): make it module_function.
-
-Sat Feb 12 17:29:19 2005 Tanaka Akira <akr@m17n.org>
-
- * lib/open-uri.rb (OpenURI.open_loop): send authentication only for
- the URI directly specified.
-
-Sat Feb 12 15:07:23 2005 Nobuyoshi Nakada <nobu@ruby-lang.org>
-
- * random.c (rand_init): suppress warning.
-
-Sat Feb 12 13:54:03 2005 Tanaka Akira <akr@m17n.org>
-
- * lib/open-uri.rb: support https if the platform provides CA
- certificates.
-
-Sat Feb 12 06:18:28 2005 URABE Shyouhei <shyouhei@ice.uec.ac.jp>
-
- * ext/etc/etc.c (Init_etc): sGroup needs HAVE_ST_GR_PASSWD check.
- [ruby-dev:25675]
-
-Fri Feb 11 17:40:42 2005 GOTOU Yuuzou <gotoyuzo@notwork.org>
-
- * ext/openssl/ossl_x509store.c (ossl_x509store_set_default_paths):
- new method OpenSSL::X509::Store#set_default_paths.
-
-Fri Feb 11 11:33:53 2005 Tanaka Akira <akr@m17n.org>
-
- * lib/open-uri.rb (URI::HTTP#proxy_open): new option supported:
- :http_basic_authentication.
- suggested by Kent Sibilev. [ruby-core:4392]
-
-Fri Feb 11 06:30:07 2005 George Ogata <g_ogata@optushome.com.au>
-
- * misc/ruby-mode.el: ignore parenthesis inside heredoc.
- [ruby-core:04415]
-
-Fri Feb 11 04:54:13 2005 Tilman Sauerbeck <tilman@code-monkey.de>
-
- * lib/rdoc/generators/html_generator.rb: [ruby-core:04412]
-
- * lib/rdoc/generators/ri_generator.rb: ditto.
-
-Thu Feb 10 11:14:17 2005 NAKAMURA Usaku <usa@ruby-lang.org>
-
- * win32/Makefile.sub (COMMON_HEADERS): shouldn't include winsock2.h.
-
- * ext/socket/extconf.rb (sockaddr_storage): remove workaround for
- mswin32.
-
-Thu Feb 10 10:29:16 2005 NAKAMURA Usaku <usa@ruby-lang.org>
-
- * ext/curses/curses.c: don't need to check HAVE_WCOLOR_SET excluding
- window_color_set().
-
-Thu Feb 10 00:47:25 2005 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * struct.c (make_struct): fixed: [ruby-core:04402]
-
-Wed Feb 9 08:07:08 2005 Paul Duncan <pabs@pablotron.org>
-
- * ext/curses/curses.c (window_color_set): [ruby-core:04393]
-
-Tue Feb 8 23:51:47 2005 Masatoshi SEKI <m_seki@mva.biglobe.ne.jp>
-
- * lib/drb/drb.rb: reject :instance_eval, :class_eval, :module_eval
- [druby-ja:117]
-
-Tue Feb 8 13:06:12 2005 Sam Roberts <sroberts@uniserve.com>
-
- * ext/socket/socket.c (Init_socket): SO_REUSEPORT added.
- [ruby-talk:130092]
-
-Tue Feb 8 09:30:01 2005 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * lib/cgi.rb (CGI::Cookie): [ruby-talk:130040]
-
-Tue Feb 8 00:19:02 2005 Tanaka Akira <akr@m17n.org>
-
- * lib/resolv.rb (Resolv::DNS::Name#subdomain_of?): new method.
- (Resolv::DNS::Name#inspect): ditto.
- Suggested by Sam Roberts. [ruby-talk:129086]
-
-Mon Feb 7 10:06:30 2005 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * object.c: [ruby-doc:818]
-
-Mon Feb 7 01:56:20 2005 NAKAMURA Usaku <usa@ruby-lang.org>
-
- * instruby.rb, rubytest.rb (srcdir): no longer embed srcdir into
- rbconfig.rb. (backported from CVS HEAD)
-
- * ext/socket/extconf.rb (sockaddr_storage): winsock2.h have the
- definition of struct sockaddr_storage, but socket.c doesn't
- include it because this version of ruby still has binary level
- compatibility with winsock1.
-
- * lib/mkmf.rb (create_makefile): should support header files in
- depend file.
-
-Mon Feb 7 01:21:50 2005 Nobuyoshi Nakada <nobu@ruby-lang.org>
-
- * ext/socket/extconf.rb: check if getaddrinfo() works fine only when
- wide-getaddrinfo option is not given. fixed: [ruby-dev:25422]
-
- * lib/mkmf.rb ($extmk): check if under ext directory.
-
- * lib/mkmf.rb (Logging.postpone): allow recursive operation.
-
- * lib/mkmf.rb (try_constant): make sure if really a constant, reduce
- the number of times of compile.
-
- * lib/mkmf.rb (have_macro, have_var, byte_order): new functions.
-
- * lib/mkmf.rb (find_library): allow directory list with separators.
-
- * lib/mkmf.rb (arg_config): manage provided configuration options.
-
- * lib/mkmf.rb (dir_config): accept arrays of directory names as
- default values.
-
- * mkconfig.rb: no longer embed srcdir and compile_dir into
- rbconfig.rb.
-
- * lib/mkmf.rb (create_makefile): fix unbalanced parens.
-
-Sun Feb 6 19:23:01 2005 NAKAMURA Usaku <usa@ruby-lang.org>
-
- * eval.c (stack_extend): add prototype because VC++8 doesn't
- accept __declspec(noinline) with K&R style function definitions.
- (backported from CVS HEAD)
-
-Sun Feb 6 14:14:26 2005 Tadayoshi Funaba <tadf@dotrb.org>
-
- * lib/date.rb (new_with_hash): changed messages of exception.
-
- * lib/date/format.rb (str[fp]time): undocumented conversion
- specifications %[1-3] are now deprecated.
-
-Sun Feb 6 12:20:11 2005 Akinori MUSHA <knu@iDaemons.org>
-
- * bignum.c (rb_big2ulong_pack): One too many arguments are passed
- to big2ulong().
-
- * re.c (rb_reg_init_copy, rb_reg_initialize_m): One too many
- arguments are passed to rb_reg_initialize().
-
-Sun Feb 6 03:24:20 2005 Tanaka Akira <akr@m17n.org>
-
- * lib/resolv.rb (Resolv::DNS::Resource::TXT): multiple strings was not
- handled.
- (Resolv::DNS::Resource::TXT#strings): new method to return all
- strings.
- (Resolv::DNS::Message::MessageEncoder#put_string_list): new method.
- (Resolv::DNS::Message::MessageDecoder#get_string_list): ditto.
- based on [ruby-talk:129732] by Sam Roberts.
-
-Fri Feb 4 00:30:45 2005 Kouhei Sutou <kou@cozmixng.org>
-
- * lib/rss: supported Image module.
- http://web.resource.org/rss/1.0/modules/image/
-
-Thu Feb 3 23:42:36 2005 Nobuyoshi Nakada <nobu@ruby-lang.org>
-
- * ext/stringio/stringio.c (strio_close, strio_close_read, strio_close_write):
- should return nil instead of self as well as IO. [ruby-dev:25623]
-
- * ext/stringio/stringio.c (strio_extend, strio_putc): fill with zero
- extended portion. [ruby-dev:25626]
-
-Wed Feb 2 23:52:53 2005 sheepman <sheepman@tcn.zaq.ne.jp>
-
- * ext/stringio/stringio.c (strio_truncate): should MEMZERO an extended
- part. [ruby-dev:25618]
-
-Wed Feb 2 21:56:01 2005 Kouhei Sutou <kou@cozmixng.org>
-
- * lib/rss/rss.rb (RSS::Element#convert): added.
-
- * lib/rss/rss.rb: convert -> need_convert.
-
- * lib/rss/1.0.rb: ditto.
-
- * lib/rss/0.9.rb: ditto.
-
- * lib/rss/2.0.rb: ditto.
-
- * lib/rss/trackback.rb: ditto.
-
-Tue Feb 1 22:48:48 2005 Masatoshi SEKI <m_seki@mva.biglobe.ne.jp>
-
- * lib/drb/drb.rb (DRb::DRbObject#respond_to?): check marshal_dump and
- _dump.
-
-Tue Feb 1 00:20:23 2005 Nobuyoshi Nakada <nobu@ruby-lang.org>
-
- * configure.in (aix): fix linker flags on AIX. [ruby-talk:125460]
-
-Mon Jan 31 13:33:21 2005 Hidetoshi NAGAI <nagai@ai.kyutech.ac.jp>
-
- * ext/tcltklib/tcltklib.c: add invalid namespace check
-
- * ext/tk/lib/multi-tk.rb: add invalid_namespace? method
-
- * ext/tk/lib/remote-tk.rb: ditto
-
-Mon Jan 31 10:29:18 2005 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * lib/irb/context.rb (IRB::Context::initialize): [ruby-core:04330]
-
-Sat Jan 29 09:42:12 2005 Sam Roberts <sroberts@uniserve.com>
-
- * lib/resolv.rb (Resolv::DNS::Resource::IN::SRV): Added RFC2782 SRV
- resource record for specifying location of services.
-
-Fri Jan 28 17:16:55 2005 Tanaka Akira <akr@m17n.org>
-
- * lib/resolv.rb (Resolv::DNS::Config.parse_resolv_conf):
- parse options line for ndots option.
- (Resolv::Hosts#lazy_initialize): return self.
- (Resolv::DNS#lazy_initialize): ditto.
- (Resolv::DNS::Config#lazy_initialize): ditto.
- Suggested by Sam Roberts.
-
-Thu Jan 27 13:18:03 2005 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * st.c (st_foreach): report success/failure by return value.
- [ruby-Bugs-1396]
-
-Thu Jan 27 00:15:29 2005 Minero Aoki <aamine@loveruby.net>
-
- * test/fileutils/test_fileutils.rb (setup): support BSD-style
- directory group inheritance. (backport from HEAD, rev 1.32)
-
- * test/fileutils/fileasserts.rb (assert_same_entry): show entry
- difference. (backport from HEAD, rev 1.4)
-
-Wed Jan 26 23:09:11 2005 Minero Aoki <aamine@loveruby.net>
-
- * lib/net/protocol.rb (WriteAdapter#puts): should append \n, not
- prepend. [ruby-talk:128302] (backport from HEAD, rev 1.75)
-
-Wed Jan 26 10:51:50 2005 NAKAMURA Usaku <usa@ruby-lang.org>
-
- * win32/win32.c (flock_winnt, flock_win95): unlock file even if
- LOCK_NB is specified. (backported from CVS HEAD)
-
-Tue Jan 25 17:11:51 2005 NAKAMURA Usaku <usa@ruby-lang.org>
-
- * ruby.c (proc_options): correct -T option in RUBYOPT. (backported
- from CVS HEAD)
-
-Tue Jan 25 14:05:52 2005 Hidetoshi NAGAI <nagai@ai.kyutech.ac.jp>
-
- * ext/tcltklib/tcltklib.c: fix SEGV bug; trouble on canceling remained
- after scripts [ruby-dev:25479]: NULL current namespace when deleting
- Tk interpreter [ruby-talk:126225]
-
- * ext/tcltklib/extconf.rb: bug fix; TCL_ENABLE_THREAD flag is inverted
- [ruby-talk:126360]
-
- * ext/tcltklib/extconf.rb: add yet another native-thread check
-
- * ext/tk/tkutil.c: fix SEGV bug; NULL string pointer when finalize
- Ruby interpreter
-
- * ext/tk/lib/multi-tk.rb: avoid warning for deleted safeTk ip frame
-
- * ext/tk/lib/tk/bindtag.rb: bug fix; new method of named bindtag
- doesn't return the created object [ruby-dev:25479]
-
- * ext/tk/lib/tk/menu.rb: bug on treating arguments [ruby-dev:25479]
-
- * ext/tk/lib/tk.rb: bug fix; cannot accept a callback ID string for
- a command argument [ruby-dev:25479]
-
- * ext/tk/lib/multi-tk.rb: ditto
-
- * ext/tk/lib/tk/*.rb: ditto
-
- * ext/tk/lib/tkextlib/*.rb: ditto
-
- * ext/tk/sample/demos-jp/anilabel.rb: new demo script
-
- * ext/tk/sample/demos-en/anilabel.rb: ditto
-
- * ext/tk/sample/tkHTML/ss.rb: local variable scope bug fix
- [ruby-dev:25479]
-
-Mon Jan 24 15:44:25 2005 Tilman Sauerbeck <tilman@code-monkey.de>
-
- * lib/rdoc/parsers/parse_c.rb: allow whitespace after function names.
- [ruby-core:4296]
-
- * lib/rdoc/parsers/parse_simple.rb: adds support for private comments
- in the "simple" parser. [ruby-core:4301]
-
-Mon Jan 24 15:44:25 2005 Charles Mills <cmills@freeshell.org>
-
- * lib/rdoc/parsers/parse_c.rb: adds support for constants
- (rb_define_const), accessors (rb_define_attr), and makes a
- couple fixes. [ruby-core:4307]
-
-Mon Jan 24 15:44:25 2005 Florian Gro <florgro@gmail.com>
-
- * lib/rdoc/parsers/parse_rb.rb: Logic for def Builtin.method() end
- [ruby-core:4302]
-
-Mon Jan 24 15:44:25 2005 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * document updates - [ruby-core:04296], [ruby-core:04301],
- [ruby-core:04302], [ruby-core:04307]
-
-Sun Jan 23 12:41:16 2005 NAKAMURA, Hiroshi <nakahiro@sarion.co.jp>
-
- * lib/soap/wsdlDriver.rb: from 1.5.3-ruby1.8.2, operation which has
- capitalized name (such as KeywordSearchRequest in AWS) is defined as
- a method having uncapitalized name. (converted with
- GenSupport.safemethodname to handle operation name 'foo-bar'). it
- introduced serious incompatibility; in the past, it was defined as a
- capitalized.
-
- define capitalized method as well under that circumstance.
-
-Sun Jan 23 05:24:42 2005 GOTOU Yuuzou <gotoyuzo@notwork.org>
-
- * ext/openssl/ossl_ocsp.c (ossl_ocspreq_to_der): should call
- GetOCSPReq at first.
-
-Sat Jan 22 23:09:47 2005 Masatoshi SEKI <m_seki@mva.biglobe.ne.jp>
-
- * lib/drb/ssl.rb (accept): rescue SSLError. [druby-ja:110]
-
-Sat Jan 22 22:35:03 2005 Masatoshi SEKI <m_seki@mva.biglobe.ne.jp>
-
- * lib/drb/unix.rb: fail if UNIXFileOwner is set. [druby-ja:111]
-
-Fri Jan 21 23:58:42 2005 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * ext/stringio/stringio.c (strio_set_pos): clear EOF flag.
- [ruby-talk:127511]
-
-Fri Jan 21 20:07:02 2005 Tanaka Akira <akr@m17n.org>
-
- * lib/resolv.rb (Resolv::DNS::Config.resolv): don't raise ResolvError.
- reported by Sam Roberts. [ruby-talk:127133]
-
-Fri Jan 21 16:58:10 2005 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * dir.c (rb_push_glob): should work for NUL delimited patterns.
-
-Fri Jan 21 13:58:37 2005 Shugo Maeda <shugo@ruby-lang.org>
-
- * lib/net/imap.rb (u8tou16): fixed typo. fixed: [ruby-list:40546]
- (backported from CVS HEAD)
-
-Fri Jan 21 09:30:16 2005 NAKAMURA Usaku <usa@ruby-lang.org>
-
- * rubyio.h (rb_eof_error): should mark as NORETURN. (backported
- from CVS HEAD)
-
-Fri Jan 21 00:31:36 2005 Hirokazu Yamamoto <ocean@m2.ccsnet.ne.jp>
-
- * ext/syck/rubyext.c (syck_parser_bufsize_set): avoid VC++ warning
- "local variable 'size' used without having been initialized".
-
-Thu Jan 20 19:03:24 2005 NAKAMURA Usaku <usa@ruby-lang.org>
-
- * ext/extmk.rb (extmake): shouldn't set $extflags on mswin32.
-
- * win32/Makefile.sub (LIBRUBY_SO): should use $DLDOBJS instead of
- $EXTOBJS.
- fixed: [ruby-core:04290] (backported from CVS HEAD)
-
-Thu Jan 20 11:42:02 2005 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * string.c (rb_str_new4): should propagate taintedness.
-
- * struct.c (rb_struct_set): use original method name, not callee
- name, to retrieve member slot. [ruby-core:04268]
-
- * time.c (time_strftime): protect from format modification from GC
- finalizers.
-
-Wed Jan 19 18:06:40 2005 NAKAMURA Usaku <usa@ruby-lang.org>
-
- * lib/ipaddr.rb (to_s, test_to_s): too many colons with some cases.
- (backported from CVS HEAD)
-
-Wed Jan 19 01:16:30 2005 Tanaka Akira <akr@m17n.org>
-
- * lib/resolv.rb (Resolv::DNS::Config.parse_resolv_conf): ignore
- domain and search directive without an argument.
- reported by Sam Roberts. [ruby-talk:126781]
-
-Tue Jan 18 15:03:05 2005 GOTOU Yuuzou <gotoyuzo@notwork.org>
-
- * lib/webrick/ssl.rb (WEBrick::Config::SSL): the default value
- of :SSLEnable is false.
-
- * lib/webrick/server.rb (WEBrick::Daemon.start): prepared stdio
- don't allow changing its mode.
-
- * lib/webrick/httpproxy.rb (WEBrick::HTTPProxyServer#proxy_service):
- should delete trailing LF from the result of pack("m*").
-
- * lib/webrick/httpproxy.rb (WEBrick::HTTPProxyServer#proxy_connect):
- - should delete trailing LF from the result of pack("m*").
- - clear Request-Line not to send the response by HTTPServer#run.
-
- * lib/webrick/httputils (WEBrick::HTTPUtils.parse_qvalues):
- refine regexp (and change the name of a local variable).
-
- * lib/webrick/httputils.rb (WEBrick::HTTPUtils#escape_path): add
- new method to escape URI path component.
-
- * lib/webrick/cgi.rb (WEBrick::CGI::Socket#request_line): should
- escape SCRIPT_NAME and PATH_INFO before being parsed as a URI.
-
- * test/webrick/*, sample/webrick/httpproxy.rb: add new file.
-
-Mon Jan 17 23:33:46 2005 Nobuyoshi Nakada <nobu@ruby-lang.org>
-
- * configure.in (aix): fix typo. [ruby-talk:126401]
-
-Mon Jan 17 07:08:51 2005 Nobuyoshi Nakada <nobu@ruby-lang.org>
-
- * ext/readline/readline.c: suppress warnings.
-
- * lib/irb/extend-command.rb (IRB::ContextExtender.def_extend_command):
- ditto.
-
- * lib/irb/ext/history.rb (IRB::Context::set_last_value): ditto.
-
- * lib/irb/ext/history.rb (IRB::Context::eval_history): ditto.
-
- * lib/irb/locale.rb (IRB::Locale::real_load): ditto.
-
- * lib/irb/slex.rb (SLex::Node::create_subnode): remove garbage.
-
-Mon Jan 17 00:09:42 2005 WATANABE Hirofumi <eban@ruby-lang.org>
-
- * lib/uri/common.rb (PORT): typo fix. fixed: [ruby-core:04256]
-
-Sat Jan 15 14:57:22 2005 Nobuyoshi Nakada <nobu@ruby-lang.org>
-
- * ruby.c (proc_options): ignore trailing CRs at the end of short
- options as well as long options. fixed: [ruby-core:04232]
-
-Sat Jan 15 13:35:16 2005 Kouhei Sutou <kou@cozmixng.org>
-
- * lib/rss/rss.rb (RSS::VERSION): 0.1.2 -> 0.1.3.
-
- * lib/rss/rss.rb: accept inheritance. [ruby-talk:126104]
-
-Thu Jan 13 04:48:53 2005 Tanaka Akira <akr@m17n.org>
-
- * io.c (io_fread): don't warn nonblocking behavior by default.
-
-Wed Jan 12 00:36:29 2005 Nobuyoshi Nakada <nobu@ruby-lang.org>
-
- * object.c (rb_class_superclass): superclass of singleton class also
- should be a singleton class. fixed: [ruby-list:40519]
-
-Tue Jan 11 09:44:40 2005 Hirokazu Yamamoto <ocean@m2.ccsnet.ne.jp>
-
- * numeric.c (Init_Numeric): turn off floating point exceptions
- on bcc32. "1e300".to_f had crashed by overflow.
-
-Tue Jan 11 03:10:10 2005 Minero Aoki <aamine@loveruby.net>
-
- * lib/fileutils.rb (copy_entry): could not copy symbolic link.
- [ruby-talk:125733]
-
- * lib/fileutils.rb (copy_stream): use read/write instead of
- sysread/syswrite.
-
-Mon Jan 10 23:08:15 2005 Nobuyoshi Nakada <nobu@ruby-lang.org>
-
- * variable.c (rb_autoload): hide internal data from ruby level.
- fixed: [ruby-dev:25435], [ruby-list:40498]
-
-Mon Jan 10 01:22:55 2005 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * gc.c (rb_data_object_alloc): klass may be NULL.
- [ruby-list:40498]
-
-Sun Jan 9 03:12:58 2005 Tanaka Akira <akr@m17n.org>
-
- * io.c (io_fread): warn nonblocking behavior.
- (io_readpartial): new method IO#readpartial.
-
-Sat Jan 8 04:38:47 2005 why the lucky stiff <why@ruby-lang.org>
-
- * lib/yaml.rb: Kernel#y requires an argument.
-
-Fri Jan 7 21:12:29 2005 TAMURA Takashi <sheepman@tcn.zaq.ne.jp>
-
- * random.c (rand_init): use ALLOC_N instead of ALLOCA_N
- [ruby-dev:25426]
-
-Fri Jan 7 18:03:35 2005 Tanaka Akira <akr@m17n.org>
-
- * gc.c (mark_locations_array): avoid core dump with -O3.
- [ruby-dev:25424]
-
-Thu Jan 6 20:31:07 2005 NAKAMURA Usaku <usa@ruby-lang.org>
-
- * ext/zlib/zlib.c (zstream_end): should return value. (backported
- from CVS HEAD)
-
-Thu Jan 6 19:55:13 2005 Hirokazu Yamamoto <ocean@m2.ccsnet.ne.jp>
-
- * win32/win32.c (rb_w32_close): didn't close socket handle.
- [ruby-dev:25414]
-
- * win32/win32.c (rb_w32_open_osfhandle): bcc32's _open_osfhandle
- never set EMFILE.
-
-Thu Jan 6 17:14:31 2005 Hirokazu Yamamoto <ocean@m2.ccsnet.ne.jp>
-
- * random.c (random_seed): O_NONBLOCK isn't defined on some
- platforms. [ruby-dev:25417]
-
-Thu Jan 6 13:45:35 2005 Tanaka Akira <akr@m17n.org>
-
- * lib/time.rb: recognize +00:00 and GMT as a localtime.
-
-Thu Jan 6 07:58:28 2005 Dave Thomas <dave@pragprog.com>
-
- * lib/rdoc/usage.rb (RDoc::RDoc.usage_no_exit): Allow for colons
- in path names on DOS machines. (thanks to Johan Nilsson)
-
-Wed Jan 5 20:16:32 2005 Tanaka Akira <akr@m17n.org>
-
- * random.c (limited_big_rand): didn't work if SIZEOF_BDIGITS == 2.
- [ruby-dev:25408]
-
- * random.c (random_seed): refined.
-
-Wed Jan 5 12:49:39 2005 Nobuyoshi Nakada <nobu@ruby-lang.org>
-
- * eval.c (rb_thread_initialize): Thread objects cannot be initialized
- again. fixed: [ruby-core:04067]
-
-Wed Jan 5 10:48:16 2005 NAKAMURA Usaku <usa@ruby-lang.org>
-
- * dir.c (dir_s_mkdir): win32 special processing doesn't need any
- longer. (backported from CVS HEAD)
-
- * win32/win32.[ch] (rb_w32_mkdir): new function. POSIX.1 compatible
- interface. (backported from CVS HEAD)
-
- * win32/win32.[ch] (rb_w32_rmdir): new function. (backported from CVS
- HEAD)
-
-Wed Jan 5 02:30:11 2005 Tanaka Akira <akr@m17n.org>
-
- * random.c (init_by_array): imported from mt19937ar-cok.tgz.
- (genrand_int32): ditto.
- (genrand_real): replaced with genrand_res53 in mt19937ar-cok.
- (rand_init): support bignum for longer seed.
- (random_seed): generate longer seed.
- (make_mask): new function.
- (limited_rand): ditto.
- (limited_big_rand): ditto.
- (rb_f_rand): call limited_rand and limited_big_rand.
- [ruby-dev:25403]
-
-Tue Jan 4 23:25:29 2005 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * bignum.c (rb_big_rand): should return positive random number.
- [ruby-dev:25401]
-
-Tue Jan 4 11:15:29 2005 TAMURA Takashi <sheepman@tcn.zaq.ne.jp>
-
- * bignum.c (rb_big_rand): do not use rb_big_modulo to generate
- random bignums. [ruby-dev:25396]
-
-Mon Jan 3 14:01:54 2005 Tanaka Akira <akr@m17n.org>
-
- * random.c (random_seed): don't use /dev/urandom if it is not
- character device.
-
-Mon Jan 3 11:37:42 2005 Tanaka Akira <akr@m17n.org>
-
- * random.c (random_seed): use /dev/urandom if available.
- [ruby-dev:25392]
-
-Mon Jan 3 07:46:42 2005 GOTOU Yuuzou <gotoyuzo@notwork.org>
-
- * lib/webrick/httpauth/htpasswd.rb (WEBrick::Htpasswd#reload):
- raise NotImplementedError if password is encrypted by digest
- algorithms. This patch is contributed by sheepman. [ruby-list:40467]
-
- * lib/webrick/httpauth/digestauth.rb
- (WEBrick::HTTPAuth::DigestAuth#_authenticate): fix digest calculation.
- This patch is contributed by sheepman. [ruby-list:40482]
-
- * lib/webrick/{httpauth.rb,httpauth/basicauth.rb,httpproxy.rb}: use
- pack/unpack-template char "m" instead of lib/base64.rb to do base64
- encoding/decoding. fixed: [ruby-dev:25336]
-
- * test/webrick/test_httpauth.rb: new file.
-
-Sat Jan 1 04:20:23 2005 GOTOU Yuuzou <gotoyuzo@notwork.org>
-
- * ext/openssl/ossl_ns_spki.c (ossl_spki_set_challenge): should call
- StringValue before GetSPKI. fixed: [ruby-dev:25359].
-
-Sat Jan 1 01:13:28 2005 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * variable.c (rb_autoload): [ruby-dev:25373]
-
-Fri Dec 31 14:10:43 2004 Dave Thomas <dave@pragprog.com>
-
- * lib/rdoc/ri/ri_formatter.rb (RI::TextFormatter::display_flow_item): Fix problem
- if heading contains formatting.
-
-Thu Dec 30 00:41:42 2004 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * eval.c (svalue_to_avalue): [ruby-dev:25366]
-
- * string.c (rb_str_justify): [ruby-dev:25367]
-
-Wed Dec 29 11:07:07 2004 Dave Thomas <dave@pragprog.com>
-
- * lib/rdoc/generators/template/html/kilmer.rb: Update to use new
- sections.
-
-Tue Dec 28 22:31:46 2004 Nobuyoshi Nakada <nobu@ruby-lang.org>
-
- * string.c (rb_str_justify): create buffer string after argument type
- conversion. fixed: [ruby-dev:25341]
-
-Tue Dec 28 15:41:48 2004 Nobuyoshi Nakada <nobu@ruby-lang.org>
-
- * ext/nkf/nkf-utf8/nkf.c (reinit): should initialize all static
- variables. fixed: [ruby-list:40445]
-
-Tue Dec 28 15:25:20 2004 Nobuyoshi Nakada <nobu@ruby-lang.org>
-
- * ext/nkf/lib/kconv.rb (Kconv::RegexpEucjp): second byte is up to
- 0xfe.
-
- * ext/nkf/lib/kconv.rb (Kconv#kconv): should handle UTF8 and UTF16
- properly.
-
-Tue Dec 28 13:35:20 2004 Nobuyoshi Nakada <nobu@ruby-lang.org>
-
- * ext/zlib/zlib.c (rb_deflate_s_deflate, rb_inflate_s_inflate): ensure
- freeing internal zstreams. fixed: [ruby-dev:25309]
-
- * ext/zlib/zlib.c (rb_deflate_init_copy): replace rb_deflate_clone.
-
-Tue Dec 28 12:26:45 2004 NAKAMURA Usaku <usa@ruby-lang.org>
-
- * win32/Makefile.sub, win32/setup.mak (RDOCTARGET, install,
- install-nodoc, install-doc): rdoc support for mswin32.
-
- * win32/configure.bat (--enable-install-doc, --disable-install-doc):
- ditto.
-
-Mon Dec 27 20:02:14 2004 Hidetoshi NAGAI <nagai@ai.kyutech.ac.jp>
-
- * ext/tcltklib/tcltklib.c: fix SEGV bug when deleting Tk interp
-
- * ext/tk/lib/multi-tk.rb: ditto
-
-Mon Dec 27 16:55:17 2004 GOTOU Yuuzou <gotoyuzo@notwork.org>
-
- * ext/openssl/ossl_x509name.c (Init_ossl_x509name): should use
- rb_hash_new to get exactly a Hash. fix [ruby-dev:25325].
-
-Mon Dec 27 16:29:56 2004 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * string.c (rb_str_justify): [ruby-dev:25341]
-
-Mon Dec 27 15:47:48 2004 Minero Aoki <aamine@loveruby.net>
-
- * test/fileutils/fileasserts.rb: sync with HEAD.
-
- * test/fileutils/test_fileutils.rb: ditto.
-
- * test/fileutils/test_nowrite.rb: ditto.
-
-Mon Dec 27 15:21:07 2004 Minero Aoki <aamine@loveruby.net>
-
- * lib/fileutils.rb (mv): should raise error when moving a
- directory to the (empty) directory. [ruby-talk:124368]
- (backport from HEAD 1.48)
-
- * lib/fileutils.rb (mv): wrongly did not overwrite file on Win32
- platforms. (backport from HEAD 1.48)
-
-Sat Dec 25 11:11:48 2004 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * stable version 1.8.2 released.
-
-Sat Dec 25 04:23:49 2004 Minero Aoki <aamine@loveruby.net>
-
- * lib/fileutils.rb (mkdir, mkdir_p): should ensure directory
- permission. (backportted from HEAD, 1.47)
-
- * lib/fileutils.rb (traverse, remove_dir): untaint trasted
- objects. (backportted from HEAD, 1.46)
-
-Sat Dec 25 01:28:23 2004 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * io.c: cancel io_reopen() change on Dec. 24th.
-
- * dln.c: use <dlfcn.h> for NetBSD. [ruby-dev:25313]
-
- * io.c (rb_f_select): IO list could be altered. [ruby-dev:25312]
-
-Fri Dec 24 23:51:48 2004 Hirokazu Yamamoto <ocean@m2.ccsnet.ne.jp>
-
- * bcc32/Makefile.sub: bcc32 should use RTL dll (backport from HEAD)
- [ruby-dev:25306]
-
- * win32/win32.[ch]: ditto.
-
-Fri Dec 24 23:27:18 2004 Hidetoshi NAGAI <nagai@ai.kyutech.ac.jp>
-
- * ext/tk/lib/tk/image.rb: TkPhotoImage#cget bug fix
-
-Fri Dec 24 18:39:25 2004 Hirokazu Yamamoto <ocean@m2.ccsnet.ne.jp>
-
- * win32/win32.[ch]: failed to compile on bcc32 (and probably wince)
- [ruby-dev:25306]
-
-Fri Dec 24 02:52:52 2004 Nobuyoshi Nakada <nobu@ruby-lang.org>
-
- * io.c (io_reopen, rb_io_reopen): prohibit to change access mode for
- special IO ports. [ruby-dev:25225]
-
-Fri Dec 24 02:22:53 2004 Nobuyoshi Nakada <nobu@ruby-lang.org>
-
- * ext/syck/rubyext.c (rb_syck_io_str_read): [ruby-core:03973]
-
- * ext/syck/rubyext.c (syck_loader_transfer): check type conversion.
-
- * ext/syck/rubyext.c (syck_parser_assign_io, rb_new_syck_node): duck
- typing.
-
- * ext/syck/rubyext.c (syck_parser_s_alloc, syck_parser_initialize):
- allocation framework.
-
- * ext/syck/rubyext.c (syck_emitter_s_alloc, syck_emitter_initialize):
- ditto.
-
-Fri Dec 24 01:21:00 2004 Hidetoshi NAGAI <nagai@ai.kyutech.ac.jp>
-
- * ext/tk/lib/tkextlib/blt.rb: add BLT extension support
-
- * ext/tk/lib/tkextlib/blt/*.rb: ditto
-
- * ext/tk/lib/tkextlib/blt/tile/*.rb: ditto
-
-Thu Dec 23 23:36:28 2004 Nobuyoshi Nakada <nobu@ruby-lang.org>
-
- * process.c (proc_setgroups): check if the argument lenght is
- modified. fixed: [ruby-dev:25285]
-
-Thu Dec 23 13:13:33 2004 Hidetoshi NAGAI <nagai@ai.kyutech.ac.jp>
-
- * ext/tcltklib/tcltklib.c: define TclTkLib::COMPILE_INFO and
- RELEASE_DATE
-
- * ext/tcltklib/extconf.rb: ditto
-
- * ext/tk/tkutil.c: define TkUtil::RELEASE_DATE
-
- * ext/tk/lib/tk.rb: define Tk::RELEASE_DATE
-
-Thu Dec 23 09:38:31 2004 Nobuyoshi Nakada <nobu@ruby-lang.org>
-
- * io.c (io_reopen): restore exact mode. fixed: [ruby-core:04003]
-
-Thu Dec 23 00:16:32 2004 Nobuyoshi Nakada <nobu@ruby-lang.org>
-
- * configure.in (bsdi): use $(CC) for LDSHARED. fixed [ruby-dev:25270]
-
-Wed Dec 22 11:14:55 2004 Nobuyoshi Nakada <nobu@ruby-lang.org>
-
- * io.c (rb_io_mode_modenum): replace O_ACCMODE with O_RDWR.
- fixed: [ruby-dev:25273]
-
-Wed Dec 22 08:34:32 2004 Nobuyoshi Nakada <nobu@ruby-lang.org>
-
- * ext/dl/sym.c (rb_dlsym_initialize): extract internal pointers after
- all argument conversion. fixed: [ruby-dev:25271]
-
-Wed Dec 22 00:08:01 2004 NAKAMURA, Hiroshi <nakahiro@sarion.co.jp>
-
- * lib/soap/*, test/soap/*, sample/soap/authheader/*: eval cleanup.
-
-Tue Dec 21 22:07:33 2004 GOTOU Yuuzou <gotoyuzo@notwork.org>
-
- * ext/openssl/ossl_asn1.c (ossl_asn1_traverse, ossl_asn1_decode,
- ossl_asn1_decode_all): temporary value should be marked volatile.
-
-Tue Dec 21 14:40:02 2004 GOTOU Yuuzou <gotoyuzo@notwork.org>
-
- * ext/openssl/ossl_asn1.c (ossl_asn1_traverse, ossl_asn1_decode,
- ossl_asn1_decode_all): use rb_str_new4 to avoid SEGV.
- fix [ruby-dev:25261]
-
- * test/openssl/test_asn1.rb: add tests for OpenSSL::ASN1.
-
-Tue Dec 21 12:22:40 2004 Nobuyoshi Nakada <nobu@ruby-lang.org>
-
- * io.c (io_reopen): keep duplex pipe in correct mode for exception
- safeness. fixed: [ruby-dev:25152]
-
-Tue Dec 21 12:10:04 2004 Hidetoshi NAGAI <nagai@ai.kyutech.ac.jp>
-
- * ext/tk/lib/tk/grid.rb: rescue bug of 'grid configure' on Tcl/Tk8.3-
-
-Tue Dec 21 00:53:01 2004 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * ext/openssl/ossl_asn1.c (ossl_asn1_traverse): [ruby-dev:25261]
-
- * ext/openssl/ossl_asn1.c (ossl_asn1_decode): ditto.
-
- * ext/openssl/ossl_asn1.c (ossl_asn1_decode_all): ditto.
-
-Mon Dec 20 23:22:26 2004 NAKAMURA, Hiroshi <nakahiro@sarion.co.jp>
-
- * added files:
- * lib/soap/mapping/wsdl*.rb
- * lib/wsdl/soap/element.rb
- * lib/wsdl/xmlSchema/simpleContent.rb
-
- * modified files:
- * lib/soap/*
- * lib/wsdl/*
- * lib/xsd/*
- * test/soap/*
- * test/wsdl/*
- * test/xsd/*
- * sample/soap/*
- * sample/sdl/*
-
- * summary
- * imported from the soap4r repository. Version: 1.5.3-ruby1.8.2
-
- * added several XSD basetype support: nonPositiveInteger,
- negativeInteger, nonNegativeInteger, unsignedLong, unsignedInt,
- unsignedShort, unsignedByte, positiveInteger
-
- * HTTP client connection/send/receive timeout support.
-
- * HTTP client/server gzipped content encoding support.
-
- * improved WSDL schema definition support; still is far from
- complete, but is making step by step improovement.
-
-Mon Dec 20 22:56:39 2004 Tanaka Akira <akr@m17n.org>
-
- * gc.c (stack_end_address): gcc noinline attribute is available since
- gcc-3.1.
-
-Mon Dec 20 14:07:02 2004 Hidetoshi NAGAI <nagai@ai.kyutech.ac.jp>
-
- * ext/tk/lib/multi-tk.rb: supports new features of Tcl/Tk8.5a2
-
- * ext/tk/lib/tk/clock.rb: ditto
-
- * ext/tk/lib/tk/text.rb: ditto
-
- * ext/tk/lib/tk/panedwindow.rb: ditto
-
-Mon Dec 20 12:47:13 2004 GOTOU Yuuzou <gotoyuzo@notwork.org>
-
- * ext/openssl/lib/net/https.rb,protocols.rb,telnets.rb: delete
- doc and code about SSLContext#{key_file,cert_file}.
- fixed: [ruby-dev:25243]
-
-Mon Dec 20 12:42:17 2004 NAKAMURA Usaku <usa@ruby-lang.org>
-
- * io.c (io_fwrite): workaround for MSVCRT's bug.
- fixed: [ruby-core:03982]
-
-Mon Dec 20 11:21:04 2004 Nobuyoshi Nakada <nobu@ruby-lang.org>
-
- * io.c (rb_io_eof): check if closed before clearerr().
- fixed: [ruby-dev:25251]
-
-Mon Dec 20 03:30:40 2004 Nobuyoshi Nakada <nobu@ruby-lang.org>
-
- * lib/cgi/session.rb (CGI::Session#initialize): empty session id was
- used if request had no session key. fixed: [ruby-core:03981]
-
-Mon Dec 20 01:51:01 2004 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * struct.c (make_struct): [ruby-dev:25249]
-
-Mon Dec 20 00:28:20 2004 Kouhei Sutou <kou@cozmixng.org>
-
- * lib/rexml/encodings/SHIFT-JIS.rb: backported from CVS HEAD.
-
- * lib/rexml/encodings/SHIFT_JIS.rb: ditto.
-
-Sun Dec 19 17:19:48 2004 GOTOU Yuuzou <gotoyuzo@notwork.org>
-
- * ext/openssl/ossl_x509store.c
- (ossl_x509store_set_time): add OpenSSL::X509::Store#time=.
- (ossl_x509stctx_set_time): add OpenSSL::X509::StoreContext#time=.
-
- * test/openssl/ossl_x509store.rb: test certificate validity times.
-
- * ext/openssl/ossl_x509name.c (ossl_x509name_to_s): add optional
- second argument to specify the output format (see also
- X509_NAME_print_ex).
-
- * ext/openssl/ossl_x509name.c (ossl_x509name_init): new constants:
- OpenSSL::X509::Name::COMPAT, OpenSSL::X509::Name::RFC2253,
- OpenSSL::X509::ONELINE, OpenSSL::X509::MULTILINE.
-
- * ext/openssl/lib/openssl/x509.rb (OpenSSL::X509::Name::RFC2253DN):
- new module to provide the parse for RFC2253 DN format.
-
- * ext/openssl/lib/openssl/x509.rb (OpenSSL::X509::Name.parse_rfc2253):
- new method to parse RFC2253 DN format.
-
- * test/openssl/ossl_x509name.rb: add tests about RFC2253 DN.
-
- * text/openssl/ssl_server.rb: try to listen ports from 20443 to 20542
- while EADDRINUSE is raised.
-
- * all changes in this entry are backport from 1.9.
-
-Sun Dec 19 17:24:59 2004 Nobuyoshi Nakada <nobu@ruby-lang.org>
-
- * configure.in (enable_rpath): use rpath flag to embed the library
- path into extensions on ELF environment. [ruby-dev:25035]
-
-Sun Dec 19 11:01:25 2004 Nobuyoshi Nakada <nobu@ruby-lang.org>
-
- * lib/test/unit.rb: use standalone runner for -e.
-
- * lib/test/unit/autorunner.rb (Test::Unit::AutoRunner#options): accept
- multiple -p and -x options.
-
- * lib/test/unit/collector/dir.rb (Test::Unit::Collector::Dir#recursive_collect):
- ditto.
-
-Sat Dec 18 16:36:23 2004 Nobuyoshi Nakada <nobu@ruby-lang.org>
-
- * ext/zlib/zlib.c (rb_deflate_s_deflate, rb_inflate_s_inflate):
- disallow interrupt by type conversion. fixed: [ruby-dev:25226]
-
-Sat Dec 18 15:16:41 2004 NAKAMURA, Hiroshi <nakahiro@sarion.co.jp>
-
- * lib/webrick/httpauth.rb,
- lib/webrick/httpauth/{basicauth.rb,digestauth.rb}: use
- pack/unpack-template char "m" instead of lib/base64.rb to do base64
- encoding/decoding.
-
-Sat Dec 18 10:51:01 2004 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * dir.c (dir_open_dir): new function. [ruby-dev:25242]
-
-Fri Dec 17 18:07:01 2004 Shugo Maeda <shugo@ruby-lang.org>
-
- * test/readline/test_readline.rb: fix for BSD. Thanks, GOTOU Yuuzou.
- fixed: [ruby-dev:25218]
-
-Fri Dec 17 16:28:12 2004 Hidetoshi NAGAI <nagai@ai.kyutech.ac.jp>
-
- * ext/tk/lib/tk.rb: fix bug on setting up system encoding
-
- * ext/tk/lib/tk/event.rb: fix error on require process
-
- * ext/tk/lib/tk/font.rb: fix abnormal termination error on Windows
-
- * ext/tk/lib/tk/virtevent.rb: TkVirtualEvent::PreDefVirtEvent.new()
- accepts event-sequence arguments
-
- * ext/tk/lib/tk/text.rb: fail to dump embedded images
-
- * ext/tk/lib/tk/text.rb: tag_nextrange and tag_prevrange returns wrong
- types of values
-
- * ext/tk/lib/tk/texttag.rb: nextrange and prevrange returns wrong
- types of values
-
- * ext/tk/lib/tk/text.rb: add TkText::IndexModMethods module and
- TkText::IndexString class to treat text index modifiers
-
- * ext/tk/lib/tk/texttag.rb: use TkText::IndexModMethods module
-
- * ext/tk/lib/tk/textmark.rb: ditto
-
- * ext/tk/lib/tk/textimage.rb: ditto
-
- * ext/tk/lib/tk/textwindow.rb: ditto
-
- * ext/tk/lib/tk/textimage.rb: wrong gravity of text mark for embedded
- image
-
- * ext/tk/lib/tk/textwindow.rb: wrong gravity of text mark for
- embedded window
-
-Fri Dec 17 13:50:00 2004 Akiyoshi, Masamichi <akiyoshi@hp.com>
-
- * vms/vmsruby_private.c, vms/vmsruby_private.h: private routines
- for VMS port are added.
-
- * eval.c (ruby_init): change to call VMS private intialization routine.
-
-Fri Dec 17 13:33:58 2004 Nobuyoshi Nakada <nobu@ruby-lang.org>
-
- * lib/cgi/session.rb (CGI::Session#initialize): control adding
- session_id hidden fields. fixed: [ruby-talk:123850]
-
-Thu Dec 16 23:25:25 2004 Masatoshi SEKI <m_seki@mva.biglobe.ne.jp>
-
- * lib/drb/drb.rb, lib/drb/ssl.rb: backported from CVS HEAD.
- [druby-ja:101]
-
- * test/drb/test_drb.rb: adjust and reduce sleep (backported from
- CVS HEAD.)
-
-Thu Dec 16 18:44:58 2004 GOTOU Yuuzou <gotoyuzo@notwork.org>
-
- * lib/webrick/httpserver.rb (WEBrick::HTTPServer#run): should wait
- for reading request till data arrive. [ruby-talk:121068]
-
- * lib/webrick/server.rb (WEBrick::GenericServer#start_thread):
- should log about all accepted socket. [ruby-core:03962]
-
- * lib/webrick/accesslog.rb (WEBrick::AccessLog#setup_params):
- "%%" and "%u" are supported. [webricken:135]
-
- * lib/webrick/httpservlet/filehandler.rb
- (WEBrick::HTTPServlet::FileHandler#check_filename):
- :NondisclosureName is acceptable if it is Enumerable.
-
- * lib/webrick/config.rb (WEBrick::Config::FileHandler):
- default value of :NondisclosureName is [".ht*", "*~"].
-
-Thu Dec 16 18:36:52 2004 GOTOU Yuuzou <gotoyuzo@notwork.org>
-
- * ext/openssl/ossl.c (ossl_raise): refine message format.
-
-Thu Dec 16 16:29:44 2004 Hidetoshi NAGAI <nagai@ai.kyutech.ac.jp>
-
- * ext/tk/sample/demos-en/widget: modify version check for
- supporting features
-
-Thu Dec 16 16:03:50 2004 Hidetoshi NAGAI <nagai@ai.kyutech.ac.jp>
-
- * ext/tk/lib/tk/bindtag.rb: bug fix [ruby-talk: 123667]
-
- * ext/tk/lib/tk/timer.rb: accept :idle for the interval argument
-
- * ext/tk/lib/tk.rb: add TkComm._callback_entry?()
-
- * ext/tk/lib/multi-tk.rb: add MultiTkIp.cb_entry_class
-
- * ext/tk/lib/tk/canvas.rb: use TkComm._callback_entry?()
-
- * ext/tk/lib/tk/canvastag.rb: ditto
-
- * ext/tk/lib/tk/dialog.rb: ditto
-
- * ext/tk/lib/tk/optiondb.rb: ditto
-
- * ext/tk/lib/tk/text.rb: ditto
-
- * ext/tk/lib/tk/texttag.rb: ditto
-
- * ext/tk/lib/tk/textwindow.rb: ditto
-
- * ext/tk/lib/tk/timer.rb: ditto
-
- * ext/tk/lib/tk/validation.rb: ditto
-
- * ext/tk/lib/tkextlib/*: ditto
-
-Thu Dec 16 03:14:28 2004 Minero Aoki <aamine@loveruby.net>
-
- * lib/net/http.rb (basic_encode): return value of pack('m') may
- include multiple CR/LFs. Backported from main trunk (rev 1.112).
- [ruby-dev:25212]
-
-Thu Dec 16 00:33:37 2004 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * hash.c (Init_Hash): remove custom "hash" and "eql?".
-
-Wed Dec 15 18:57:01 2004 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * lib/set.rb (Set::eql): wrong definition. [ruby-dev:25207]
-
-Wed Dec 15 18:48:42 2004 Shugo Maeda <shugo@ruby-lang.org>
-
- * ext/curses/curses.c (window_subwin): call NUM2INT() before
- GetWINDOW(). (backported from CVS HEAD)
-
-Wed Dec 15 17:03:50 2004 NAKAMURA Usaku <usa@ruby-lang.org>
-
- * win32/win32.[ch] (rb_w32_isatty): new function to replace MSVCRT's
- isatty because it never sets errno. (backported from CVS HEAD)
-
-Wed Dec 15 15:39:32 2004 GOTOU Yuuzou <gotoyuzo@notwork.org>
-
- * ext/openssl/ossl_x509name.c (ossl_x509name_to_a): avoid SEGV
- (rollback the previous commit).
-
-Wed Dec 15 16:10:23 2004 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * object.c (rb_obj_id_obsolete): warn always.
-
- * eval.c (rb_enable_super): ditto.
-
-Wed Dec 15 15:31:02 2004 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * lib/set.rb (Set#==): [ruby-dev:25206]
-
-Wed Dec 15 14:22:10 2004 NAKAMURA Usaku <usa@ruby-lang.org>
-
- * win32/win32.c (rb_w32_fdisset): check whether the handle is valid.
- fixed: [ruby-core:03959]
-
-Wed Dec 15 10:30:37 2004 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * ext/openssl/ossl_digest.c (ossl_digest_initialize): [ruby-dev:25198]
-
-Tue Dec 14 17:10:09 2004 NAKAMURA Usaku <usa@ruby-lang.org>
-
- * win32/win32.c (rb_w32_close): need to reset osfhnd().
-
-Tue Dec 14 14:03:57 2004 GOTOU Yuuzou <gotoyuzo@notwork.org>
-
- * ext/openssl/ossl.c (ossl_raise): avoid buffer overrun.
- [ruby-dev:25187]
-
-Tue Dec 14 12:36:04 2004 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * lib/cgi/session.rb (CGI::Session::initialize): generate new
- session if given session_id does not exist. [ruby-list:40368]
-
-Mon Dec 13 18:13:52 2004 Tanaka Akira <akr@m17n.org>
-
- * gc.c (stack_end_address): new function to obtain stack end address.
- stack_end_address calls __builtin_frame_address(0) to obtain the
- frame pointer of a stack frame of stack_end_address. The address
- is the stack pointer of the caller's stack frame.
- (SET_STACK_END): use stack_end_address.
- This makes the conservative garbage collector to scan a stack frame
- of the garbage_collect function itself. This is required because
- callee-save registers may be stored in the frame.
- [ruby-dev:25158]
-
-Mon Dec 13 00:58:02 2004 Tanaka Akira <akr@m17n.org>
-
- * lib/pathname.rb (cleanpath_aggressive): make it private.
- (cleanpath_conservative): ditto.
- Suggested by Daniel Berger. [ruby-core:3914]
-
-Sun Dec 12 20:06:38 2004 Masatoshi SEKI <m_seki@mva.biglobe.ne.jp>
-
- * lib/drb/drb.rb: backported from CVS HEAD.
-
-Sun Dec 12 10:35:10 2004 Dave Thomas <dave@pragprog.com>
-
- * lib/rdoc/generators/template/html/html.rb (RDoc::Page): Don't
- show an accessor's r/w flag if none was specified
-
-Sun Dec 12 10:14:03 2004 Dave Thomas <dave@pragprog.com>
-
- * lib/rdoc/rdoc.rb (RDoc::RDoc::parse_files): Never exclude files
- explicitly given on the command line.
-
-Sat Dec 11 20:12:21 2004 Masatoshi SEKI <m_seki@mva.biglobe.ne.jp>
-
- * lib/drb/drb.rb: add DRbRemoteError. [ruby-list:40348],
- [ruby-list:40390]
-
- * test/drb/drbtest.rb: ditto.
-
- * test/drb/ut_drb.rb: ditto.
-
-Sat Dec 11 15:38:14 2004 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * lib/jcode.rb (String::succ): [ruby-dev:25156]
-
-Sat Dec 11 12:41:55 2004 NAKAMURA Usaku <usa@ruby-lang.org>
-
- * eval.c (run_trap_eval): prototype; avoid VC++ warnings.
-
- * ext/socket/getaddrinfo.c: fix typo. fixed: [ruby-core:03947]
-
- * win32/win32.c: need to include dln.h.
-
-Sat Dec 11 00:10:18 2004 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * io.c (io_reopen): [ruby-dev:25150]
-
-Fri Dec 10 08:39:27 2004 Nobuyoshi Nakada <nobu@ruby-lang.org>
-
- * ext/socket/socket.c (sock_listen): get OpenFile just before calling
- listen(2). fixed: [ruby-dev:25149]
-
-Thu Dec 9 17:00:00 2004 Akiyoshi, Masamichi <akiyoshi@hp.com>
-
- * ext/socket/socket.c, ext/socket/getaddrinfo.c: port to VMS
-
-Thu Dec 9 16:31:02 2004 NAKAMURA Usaku <usa@ruby-lang.org>
-
- * ext/sdbm/init.c (GetDBM): typo.
-
-Thu Dec 9 16:05:00 2004 Akiyoshi, Masamichi <akiyoshi@hp.com>
-
- * defines.h: change path of vms.h
- * vms/vms.h: delete reference for snprintf()
- * vms/config.h: new file
- * vms/config.h_in: deleted
-
-Thu Dec 9 14:38:35 2004 Nobuyoshi Nakada <nobu@ruby-lang.org>
-
- * string.c (rb_str_inspect): escape # which starts an expression
- substitution. fixed: [ruby-core:03922]
-
- * string.c (rb_str_dump): not escape # which isn't a substitution.
-
-Thu Dec 9 10:54:36 2004 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * ext/dbm/dbm.c (fdbm_select): [ruby-dev:25132]
-
- * ext/sdbm/init.c: ditto.
-
- * ext/gdbm/gdbm.c: ditto.
-
-Thu Dec 9 03:08:36 2004 Hidetoshi NAGAI <nagai@ai.kyutech.ac.jp>
-
- * ext/tcltklib/tcltklib.c (ip_init): set root-win title to "ruby" when
- the running script is '-e one-liner' or '-' (stdin).
-
- * ext/tcltklib/extconf.rb: add find_library("#{lib}#{ver}",..) for
- stub libs
-
- * ext/tk/lib/tk/textmark.rb: TkTextMarkCurrent and TkTextMarkAnchor
- have a wrong parent class.
-
- * ext/tk/lib/tk/dialog.rb: rename TkDialog2 --> TkDialogObj and
- TkWarning2 --> TkWarningObj (old names are changed to alias names)
-
- * ext/tk/lib/tk/dialog.rb: bug fix of treatment of 'prev_command'
- option and hashes for configuration
-
- * ext/tk/lib/tk/dialog.rb: add TkDialogObj#name to return the
- button name
-
- * ext/tk/lib/tk/radiobutton.rb: rename enbugged method value() ==>
- get_value() and value=(val) ==> set_value(val).
-
- * ext/tk/lib/tk/menu.rb: add TkMenu.new_menuspec
-
- * ext/tk/lib/tk/menu.rb: add alias (TkMenuButton = TkMenubutton,
- TkOptionMenuButton = TkOptionMenubutton)
-
- * ext/tk/lib/tk/event.rb: new method aliases (same as option keys of
- event_generate) for Event object
-
- * ext/tk/lib/tk/font.rb: configinfo returns proper types of values
-
- * ext/tk/lib/tk.rb: bind methods accept subst_args + block
-
- * ext/tk/lib/tk/canvas.rb: ditto
-
- * ext/tk/lib/tk/canvastag.rb: ditto
-
- * ext/tk/lib/tk/frame.rb: ditto
-
- * ext/tk/lib/tk/text.rb: ditto
-
- * ext/tk/lib/tk/texttag.rb: ditto
-
- * ext/tk/lib/tk/toplevel.rb: ditto
-
- * ext/tk/lib/tkextlib/*: ditto and bug fix
-
-Wed Dec 8 23:54:29 2004 Dave Thomas <dave@pragprog.com>
-
- * lib/rdoc/generators/template/html/html.rb (RDoc::Page): Typo
- meant that h2 tag was invisible.
-
-Wed Dec 8 21:56:31 2004 Kouhei Sutou <kou@cozmixng.org>
-
- * lib/rss, test/rss, sample/rss: backported from CVS HEAD.
-
-Wed Dec 8 14:31:36 2004 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * io.c (io_fwrite): change dereference for cosmetic reason.
-
- * sprintf.c (rb_f_sprintf): [ruby-dev:25104]
-
-Tue Dec 7 19:08:00 2004 Akiyoshi, Masamichi <akiyoshi@hp.com>
-
- * io.c (io_fwrite): fix offset incrementation (for VMS and Human68k)
-
-Tue Dec 7 00:27:37 2004 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * process.c (proc_setgroups): [ruby-dev:25081]
-
-Mon Dec 6 18:08:10 2004 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * re.c (rb_reg_eqq): document fix. [ruby-talk:122541]
-
-Mon Dec 6 17:19:13 2004 Nobuyoshi Nakada <nobu@ruby-lang.org>
-
- * rubysig.h (TRAP_BEG, TRAP_END): safe errno around CHECK_INTS.
- (backported from CVS HEAD) [ruby-dev:24993]
-
-Mon Dec 6 10:18:17 2004 Dave Thomas <dave@pragprog.com>
-
- * lib/rdoc/parsers/parse_rb.rb (RDoc::RubyParser::look_for_directives_in):
- Oops - 1.8 doesn't have String#clear
-
-Mon Dec 6 09:59:23 2004 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * ext/socket/socket.c (sock_connect): use rb_str_new4().
- [ruby-dev:25052]
-
-Mon Dec 6 01:42:08 2004 GOTOU Yuuzou <gotoyuzo@notwork.org>
-
- * ext/openssl/ossl_pkey_rsa.c (ossl_rsa_public_encrypt,
- ossl_rsa_public_decrypt, ossl_rsa_private_encrypt,
- ossl_rsa_private_decrypt): should take an optional argument
- to specify padding mode. [ruby-talk:122539]
-
- * ext/openssl/ossl_pkey_rsa.c (Init_ossl_rsa): add new constants
- PKCS1_PADDING, SSLV23_PADDING, NO_PADDING and PKCS1_OAEP_PADDING
- under OpenSSL::PKey::RSA.
-
- * test/openssl/test_pkey_rsa.rb: new file.
-
-Sun Dec 5 19:39:17 2004 Nobuyoshi Nakada <nobu@ruby-lang.org>
-
- * lib/optparse.rb (OptionParser::Completion#complete): new parameter
- to direct case insensitiveness.
-
- * lib/optparse.rb (OptionParser#order!): ignore case only for long
- option. [ruby-dev:25048]
-
-Sat Dec 4 22:54:15 2004 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * io.c (io_write): remove rb_str_locktmp(). [ruby-dev:25050]
-
- * io.c (io_fwrite): takes VALUE string as an argument.
- [ruby-dev:25050]
-
- * ext/socket/socket.c (sock_connect): remove rb_str_locktmp().
- [ruby-dev:25050]
-
- * ext/socket/socket.c (udp_connect): [ruby-dev:25045]
-
- * ext/socket/socket.c (udp_bind): ditto.
-
- * ext/socket/socket.c (udp_send): ditto.
-
- * ext/socket/socket.c (bsock_send): ditto.
-
- * ext/socket/socket.c (s_recvfrom): ditto.
-
- * hash.c (rb_hash_hash): should provide "hash" method where "eql?"
- is redefined. [ruby-talk:122482]
-
-Sat Dec 4 14:54:52 2004 WATANABE Hirofumi <eban@ruby-lang.org>
-
- * eval.c (proc_invoke): use volatile `tmp' rather than `args'.
- [ruby-core:03882]
-
-Sat Dec 4 14:28:56 2004 Dave Thomas <dave@pragprog.com>
-
- * lib/rdoc/code_objects.rb (RDoc::Context::Section::set_comment):
- Section comments may now be bracketed by lines which are
- ignored. You can now write
- # -----------
- # :section: Dave's Section
- # comment material
- # -----------
- The lines before :section: are removed, and identical lines at the end are
- also removed if present.
-
-Sat Dec 4 03:33:45 2004 Shugo Maeda <shugo@ruby-lang.org>
-
- * ext/readline/readline.c: check $SAFE. (backported from CVS HEAD)
-
- * test/readline/test_readline.rb: added tests for readline.
- (backported from CVS HEAD)
-
-Sat Dec 4 02:24:00 2004 NARUSE, Yui <naruse@ruby-lang.org>
-
- * ext/nkf/nkf.c: add constant NKF::VERSION
-
- * ext/nkf/nkf.c(guess): this becomes an alias of guess2
-
- * ext/nkf/test.rb(mime_out2): add --no-cp932
-
- * ext/nkf/nkf-utf8/nkf.c: original nkf2 revision 1.47
-
-Sat Dec 4 00:35:08 2004 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * ext/socket/socket.c (bsock_setsockopt): [ruby-dev:25039]
-
-Fri Dec 3 18:57:03 2004 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * lib/ostruct.rb: 1.9 marshaling support back-ported.
- [ruby-core:03871]
-
-Fri Dec 3 13:45:20 2004 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * eval.c (proc_invoke): copy arguments to frame.argv.
- [ruby-core:03861]
-
-Fri Dec 3 12:25:41 2004 Nobuyoshi Nakada <nobu@ruby-lang.org>
-
- * st.h: fix prototypes.
-
-Fri Dec 3 00:21:05 2004 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * object.c (convert_type): use rb_respond_to() again.
- [ruby-dev:25021]
-
- * eval.c (rb_respond_to): funcall respond_to? if it's redefined.
- [ruby-dev:25021]
-
-Fri Dec 3 01:55:24 2004 Hidetoshi NAGAI <nagai@ai.kyutech.ac.jp>
-
- * ext/tk/lib/tk.rb: widget configuration by TkWindow#method_missing
- returns proper object. "widget.option = val" returns val, and
- "widget.option(val)" returns self.
-
- * ext/tk/lib/tk/font.rb: TkFont#replace accepts only one font argument.
-
- * ext/tk/lib/tk/radiobutton.rb: add TkRadiobutton#value and
- TkRadiobutton#value=(val).
-
- * ext/tk/lib/tk/spinbox.rb: callback substitution support on
- command option.
-
- * ext/tk/sample/demos-en/widget: bug fix (wrong image height)
-
- * ext/tk/sample/demos-jp/widget: ditto.
-
-Fri Dec 3 00:11:48 2004 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * io.c (rb_file_initialize): [ruby-dev:25032]
-
-Thu Dec 2 16:41:03 2004 Nobuyoshi Nakada <nobu@ruby-lang.org>
-
- * eval.c (rb_protect): prevent continuations created inside from being
- called from the outside. [ruby-dev:25003]
-
- * eval.c (rb_callcc, rb_cont_call): prohibit calling from different
- signal contexts. [ruby-dev:25022]
-
-Thu Dec 2 09:57:24 2004 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * lib/ostruct.rb (OpenStruct::Marshaler): OpenStruct can be
- marshaled again. [ruby-core:03862]
-
-Thu Dec 2 09:30:06 2004 Nobuyoshi Nakada <nobu@ruby-lang.org>
-
- * eval.c (thread_mark): mark thread group. [ruby-dev:25020]
-
- * eval.c (thgroup_add): check whether the argument is really a Thread.
-
-Thu Dec 2 07:57:16 2004 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * io.c (rb_io_ctl): [ruby-dev:25019]
-
-Wed Dec 1 02:21:02 2004 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * signal.c (sighandler): call handler immediately only for default
- handlers. [ruby-dev:25003]
-
-Tue Nov 30 23:38:18 2004 Nobuyoshi Nakada <nobu@ruby-lang.org>
-
- * io.c (io_fread): need not to null terminate. [ruby-dev:24998]
-
- * io.c (read_all): remove unnecessary rb_str_resize().
- [ruby-dev:24996] (backported from CVS HEAD)
-
- * io.c (io_readpartial): ditto.
-
- * io.c (io_read): ditto.
-
-Tue Nov 30 16:18:50 2004 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * io.c (io_fread): need not to null terminate. [ruby-dev:24998]
-
- * io.c (read_all): remove unnecessary rb_str_resize().
- [ruby-dev:24996]
-
- * io.c (io_read): ditto.
-
-Tue Nov 30 00:49:08 2004 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * io.c (rb_io_sysread): use temporary lock. [ruby-dev:24992]
-
-Mon Nov 29 16:06:04 2004 Nobuyoshi Nakada <nobu@ruby-lang.org>
-
- * ext/stringio/stringio.c (strio_write): insufficiently filled string
- being extended when overwriting. [ruby-core:03836]
-
-Mon Nov 29 15:59:05 2004 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * lib/ostruct.rb (OpenStruct::method_missing): check method
- duplication for -d.
-
- * lib/ostruct.rb (OpenStruct::initialize): ditto.
-
-Mon Nov 29 15:22:28 2004 Nobuyoshi Nakada <nobu@ruby-lang.org>
-
- * test/io/nonblock/test_flush.rb: abandon tests when io/nonblock is
- not supported.
-
-Mon Nov 29 03:08:30 2004 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * object.c (convert_type): direct call conversion methods for the
- performance. [ruby-core:03845]
-
- * eval.c (rb_funcall_rescue): new function.
-
- * object.c (rb_Array): avoid using rb_respond_to().
-
- * object.c (rb_Integer): ditto.
-
- * parse.y (reduce_nodes): empty body should return nil.
-
- * string.c (rb_str_aset): the original string should not be
- affected by modifying duplicated string. [ruby-dev:24981]
-
-Mon Nov 29 13:57:38 2004 NAKAMURA Usaku <usa@ruby-lang.org>
-
- * win32/win32.c (CreateChild): search executable file if no program
- name given. (backported from CVS HEAD)
-
-Mon Nov 29 13:37:54 2004 Nobuyoshi Nakada <nobu@ruby-lang.org>
-
- * io.c (fptr_finalize): must not use FILE after fclose().
- [ruby-dev:24985]
-
-Mon Nov 29 13:16:31 2004 NAKAMURA Usaku <usa@ruby-lang.org>
-
- * win32/win32.c (CreateChild): push back the last space before next
- loop because CharNext() eats it.
-
-Mon Nov 29 01:18:18 2004 Tanaka Akira <akr@m17n.org>
-
- * io.c (rb_io_check_writable): call io_seek regardless of
- NEED_IO_SEEK_BETWEEN_RW. [ruby-dev:24986]
-
-Sat Nov 27 21:43:39 2004 Tanaka Akira <akr@m17n.org>
-
- * io.c: avoid data lost with nonblocking fd and
- stdio buffering in sync mode. [ruby-dev:24966]
- based on matz's patch [ruby-dev:24967]
- (io_fwrite): new primitive writing function which writes
- directly if sync mode.
- (rb_io_fwrite): wrapper for io_fwrite now.
- (io_write): call io_fwrite instead of rb_io_fwrite.
-
-Sat Nov 27 14:44:15 2004 Kent Sibilev <ksibilev@bellsouth.net>
-
- * lib/cgi/session.rb (CGI::Session::initialize): create_new_id is
- now a instance method. [ruby-core:03832]
-
-Sat Nov 27 09:41:21 2004 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * io.c (io_fread): old rb_io_fread with file closing checking.
- (rb_io_fread): wrapper for io_fread now.
- [ruby-dev:24964]
-
-Fri Nov 26 18:02:44 2004 Hidetoshi NAGAI <nagai@ai.kyutech.ac.jp>
-
- * ext/tk/lib/tk.rb: Tk.destroy uses TkWindow#epath
-
- * ext/tk/lib/tk/image.rb: bug fix
-
- * ext/tk/lib/tk/wm.rb: add 'iconphoto' method(Windows only)
-
- * ext/tk/lib/tkextlib/*: some methods uses TkWindow#epath
-
-Fri Nov 26 13:49:06 2004 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * eval.c (method_missing): raise TypeError for classes do not
- have allocators. [ruby-core:03752]
-
- * lib/erb.rb: add RDoc by James Edward Gray II. [ruby-core:03786]
-
-Fri Nov 26 13:29:02 2004 Dave Thomas <dave@pragprog.com>
-
- * lib/rdoc/parsers/parse_rb.rb (RDoc::RubyParser::look_for_directives_in): Break
- out of preprocessing when we find a :section: directive (previously cleared out the
- comment, but this apparently now generates an error in gsub!)
-
-Fri Nov 26 00:17:40 2004 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * io.c (io_read): move StringValue() check before GetOpenFile().
- [ruby-dev:24959]
-
-Thu Nov 25 20:14:57 2004 Nobuyoshi Nakada <nobu@ruby-lang.org>
-
- * lib/thwait.rb (ThreadsWait#join_nowait): abnormally terminated
- threads should be also processed. [ruby-talk:121320]
-
-Thu Nov 25 10:14:26 2004 Nobuyoshi Nakada <nobu@ruby-lang.org>
-
- * dir.c (push_braces): do not reuse buffer strings. [ruby-core:03806]
-
-Thu Nov 25 07:59:41 2004 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * io.c (read_all): stringify non-nil buffer argument, and always
- taint the result. [ruby-dev:24955]
-
-Wed Nov 24 01:01:31 2004 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * io.c (io_read): integer conversion should be prior to
- GetOpenFile(). [ruby-dev:24952]
-
- * configure.in, io.c: cancel [ ruby-Patches-1074 ].
-
-Tue Nov 23 08:09:50 2004 Hidetoshi NAGAI <nagai@ai.kyutech.ac.jp>
-
- * ext/tk/lib/tk/menu.rb: improve usability of TkOptionMenubutton
-
-Tue Nov 23 02:00:21 2004 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * file.c (rb_file_chown): integer conversion should be prior to
- GetOpenFile(). [ruby-dev:24949]
-
-Tue Nov 23 00:10:48 2004 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * file.c (rb_file_chown): integer conversion should be prior to
- GetOpenFile(). [ruby-dev:24947]
-
- * file.c (rb_file_truncate): ditto.
-
- * file.c (rb_file_s_truncate): ditto.
-
- * dir.c (dir_seek): use NUM2OFFT().
-
- * misc/ruby-mode.el (ruby-non-block-do-re): should not match words
- start with block keyword and underscore. [ruby-core:03719]
-
-Mon Nov 22 22:33:02 2004 Dave Thomas <dave@pragprog.com>
-
- * lib/rdoc/parsers/parse_rb.rb (RDoc::parse_require): Don't use names
- of variables or constants when oarsing 'require'
-
-Mon Nov 22 00:13:35 2004 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * dir.c (dir_seek): should retrieve dir_data after NUM2INT().
- [ruby-dev:24941]
-
-Sat Nov 20 23:57:33 2004 Dave Thomas <dave@pragprog.com>
-
- * lib/rdoc/README (et al): Add a new directive, :section:, and
- change the output format to accomodate. :section: allows to to
- group together methods, attributes, constants, etc under
- headings in the output. If used, a table of contents is
- generated.
-
-Sat Nov 20 23:56:54 2004 Dave Thomas <dave@pragprog.com>
-
- * lib/rdoc/options.rb (Options::parse): Force --inline-source if
- --one-file option given
-
-Sat Nov 20 23:55:19 2004 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * string.c (rb_str_splice): should place index wrapping after
- possible modification. [ruby-dev:24940]
-
-Sat Nov 20 13:26:03 2004 NARUSE, Yui <naruse@ruby-lang.org>
-
- * ext/nkf/nkf-utf8/utf8tbl.c: original revision 1.7
-
-Sat Nov 20 05:34:24 2004 NARUSE, Yui <naruse@ruby-lang.org>
-
- * ext/nkf/nkf-utf8/nkf.c: original nkf.c rev:1.40
-
- * ext/nkf/test.rb: add test for mime encode/decode
-
-Sat Nov 20 01:37:34 2004 Johan Holmberg <holmberg@iar.se>
-
- * eval.c (error_print): nicer traceback at interrupt.
- [ruby-core:03774]
-
-Sat Nov 20 00:07:16 2004 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * string.c (str_gsub): internal buffer should not be listed by
- ObjectSpace.each_object() by String#gsub. [ruby-dev:24931]
-
-Fri Nov 19 01:20:22 2004 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * lib/cgi/session.rb (CGI::Session::FileStore::initialize): raise
- exception if data corresponding to session specified from the
- client does not exist.
-
-Fri Nov 19 00:59:31 2004 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * string.c (str_gsub): internal buffer should not be listed by
- ObjectSpace.each_object(). [ruby-dev:24919]
-
-Thu Nov 18 18:41:08 2004 Kazuhiro NISHIYAMA <zn@mbf.nifty.com>
-
- * test/ruby/test_stringchar.rb (test_bang): added.
-
- * string.c (rb_str_upcase_bang, rb_str_capitalize_bang)
- (rb_str_swapcase_bang): missing rb_str_modify(). [ruby-dev:24915]
-
-Thu Nov 18 00:21:15 2004 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * process.c (proc_getpgrp): prohibit for $SAFE=2.
- [ruby-dev:24899]
-
- * process.c (get_pid): ditto. [ruby-dev:24904]
-
- * process.c (get_ppid): ditto.
-
- * array.c (rb_ary_delete): defer rb_ary_modify() until actual
- modification. [ruby-dev:24901]
-
-Thu Nov 18 10:10:14 2004 Nobuyoshi Nakada <nobu@ruby-lang.org>
-
- * io.c, rubyio.h (rb_io_modenum_flags): exported.
-
- * ext/stringio/stringio.c (strio_initialize): allow Fixnum as mode as
- well as IO.new does. [ruby-dev:24896]
-
-Wed Nov 17 23:42:40 2004 NAKAMURA, Hiroshi <nakahiro@sarion.co.jp>
-
- * test/ruby/test_settracefunc.rb: added. [ruby-dev:24884]
-
-Wed Nov 17 13:56:57 2004 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * parse.y (newline_node): should not use FL_SET. [ruby-dev:24874]
-
- * parse.y (string_content): should not use FL_UNSET.
-
- * node.h (NODE_NEWLINE): remove unused bit to utilize flag field
- in nodes.
-
-Wed Nov 17 13:09:40 2004 NAKAMURA Usaku <usa@ruby-lang.org>
-
- * {bcc32,win32,wince}/Makefile.sub (test): should build ruby.exe
- before running test. [ruby-core:03756]
-
-Wed Nov 17 04:33:01 2004 GOTOU Yuuzou <gotoyuzo@notwork.org>
-
- * pack.c: all features are backport from 1.9. [ruby-dev:24826]
-
- * bignum.c (rb_big2ulong_pack): new function to pack Bignums.
-
-Wed Nov 17 03:42:45 2004 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * string.c (rb_str_splice): move rb_str_modify() after
- StringValue(), which may alter the receiver. [ruby-dev:24878]
-
-Tue Nov 16 23:45:07 2004 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * numeric.c (flo_divmod): protect float values from GC by
- assignment to local variables. [ruby-dev:24873]
-
-Tue Nov 16 16:30:21 2004 NAKAMURA Usaku <usa@ruby-lang.org>
-
- * {bcc32,win32,wince}/setup.mak (-epilogue-): remove config.h and
- config.status to force updating them.
-
-Tue Nov 16 16:20:45 2004 Nobuyoshi Nakada <nobu@ruby-lang.org>
-
- * ext/stringio/stringio.c (strio_read): position was ignored when a
- buffer was passed. http://www.yo.rim.or.jp/~nov/d/?date=20041116#p03
-
-Tue Nov 16 11:19:07 2004 Nobuyoshi Nakada <nobu@ruby-lang.org>
-
- * lib/test/unit/autorunner.rb (Test::Unit::AutoRunner::options): use
- Regexp conversion.
-
-Tue Nov 16 01:41:31 2004 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * string.c (str_mod_check): frozen check should be separated.
- [ruby-core:3742]
-
- * array.c (rb_ary_update): pedantic check to detect
- rb_ary_to_ary() to modify the receiver. [ruby-dev:24861]
-
-Mon Nov 15 13:50:52 2004 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * string.c (rb_str_justify): typo fixed. [ruby-dev:24851]
-
-Mon Nov 15 11:50:32 2004 Nobuyoshi Nakada <nobu@ruby-lang.org>
-
- * misc/ruby-mode.el (ruby-special-char-p, ruby-parse-partial): handle
- operator symbols. [ruby-talk:120177]
-
-Sun Nov 14 13:27:03 2004 Nobuyoshi Nakada <nobu@ruby-lang.org>
-
- * lib/pp.rb (PP#object_address_group): remove odd number of 'f'
- prefixed to negative address.
-
-Sun Nov 14 08:51:04 2004 NAKAMURA, Hiroshi <nakahiro@sarion.co.jp>
-
- * test/logger/test_logger.rb: Logger just expects
- Logger#datetime_format to be used for Time#strftime independently of
- locale. [ruby-dev:24828]
-
-Fri Nov 12 15:03:26 2004 NAKAMURA Usaku <usa@ruby-lang.org>
-
- * eval.c (ruby_options): now we cannot call rb_glob() before
- ruby_init(), so call rb_w32_cmdvector() at ruby_options().
-
- * win32.{c,h} (rb_w32_cmdvector): rename make_cmdvector() and
- export it.
-
-Fri Nov 12 14:08:01 2004 Hidetoshi NAGAI <nagai@ai.kyutech.ac.jp>
-
- * ext/tk/lib/tk/event.rb: remove $LOADED_FEATURES trick
-
- * ext/tk/lib/tk.rb: ditto
-
-Fri Nov 12 00:31:05 2004 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * ext/gdbm/gdbm.c (fgdbm_store): StringValue() may alter string
- pointer. [ruby-dev:24783]
-
-Thu Nov 11 17:36:12 2004 Nobuyoshi Nakada <nobu@ruby-lang.org>
-
- * dir.c (rb_globi): also should call back via rb_glob_caller().
- [ruby-dev:24775]
-
-Thu Nov 11 16:47:21 2004 NAKAMURA Usaku <usa@ruby-lang.org>
-
- * test/ruby/test_file.rb (test_truncate_wbuf): we want to test
- only File#truncate, not behaviour of seek(2).
-
-Thu Nov 11 09:41:01 2004 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * dir.c (push_braces): was confusing VALUE and char*.
-
- * dir.c (rb_push_glob): Dir.glob should have called its block.
-
-Thu Nov 11 01:52:52 2004 Nobuyoshi Nakada <nobu@ruby-lang.org>
-
- * error.c (syserr_initialize): use stringified object.
- [ruby-dev:24768]
-
-Wed Nov 10 22:49:01 2004 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * lib/delegate.rb (SimpleDelegator::dup): wrong number of
- arguments.
-
- * lib/delegate.rb (DelegateClass::dup): ditto.
-
-Wed Nov 10 12:31:21 2004 Nobuyoshi Nakada <nobu@ruby-lang.org>
-
- * README.EXT (Example): extconf.rb is indispensable now.
-
-Wed Nov 10 03:33:36 2004 Hidetoshi NAGAI <nagai@ai.kyutech.ac.jp>
-
- * ext/tcltklib/tcltklib.c: fix SEGV when compiled with Tcl/Tk8.3.x
- or older
-
- * ext/tk/lib/tkextlib/tile/style.rb: bug fix
-
-Tue Nov 9 14:27:18 2004 Nobuyoshi Nakada <nobu@ruby-lang.org>
-
- * lib/optparse.rb (OptionParser::Officious): moved from DefaultList.
-
-Tue Nov 9 01:05:04 2004 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * dir.c (rb_glob2): do not allocate buffer from heap to avoid
- memory leaks. use string object for buffering instead.
- [ruby-dev:24738]
-
- * dir.c (join_path): ditto.
-
- * io.c (io_read): external input buffer may be modified even after
- rb_str_locktmp(). [ruby-dev:24735]
-
- * dir.c (fnmatch): p or s may be NULL. [ruby-dev:24749]
-
-Tue Nov 9 00:53:53 2004 WATANABE Hirofumi <eban@ruby-lang.org>
-
- * regex.c (slow_match): avoid GCC 3.4.x warnings.
-
-Tue Nov 9 00:50:06 2004 Dave Thomas <dave@pragprog.com>
-
- * lib/rdoc/rdoc.rb: Change version numbering of RDoc and ri
-
-Mon Nov 8 23:38:35 2004 Masatoshi SEKI <m_seki@mva.biglobe.ne.jp>
-
- * lib/drb/extservm.rb: add DRb::ExtServManager#uri=.
- [ruby-dev:24743]
-
-Mon Nov 8 22:20:19 2004 Dave Thomas <dave@pragprog.com>
-
- * lib/rdoc/parsers/parse_rb.rb (RDoc::RubyParser::parse_class):
- Fix bug where parent class wasn't being detected if the
- child class was defined using the A::B notation.
-
-Mon Nov 8 00:14:13 2004 WATANABE Hirofumi <eban@ruby-lang.org>
-
- * configure.in: add setup for mignw32 cross compiling.
- [ruby-talk:119413]
-
-Sun Nov 7 23:49:26 2004 Hidetoshi NAGAI <nagai@ai.kyutech.ac.jp>
-
- * ext/tk/lib/tk.rb: bind-event methods accept multi substitution
- arguments.
-
- * ext/tk/lib/tk/canvas.rb: ditto.
-
- * ext/tk/lib/tk/canvastag.rb: ditto.
-
- * ext/tk/lib/tk/text.rb: ditto.
-
- * ext/tk/lib/tk/texttag.rb: ditto.
-
- * ext/tk/lib/tkextlib: ditto.
-
-Sat Nov 6 14:58:44 2004 GOTOU Yuuzou <gotoyuzo@notwork.org>
-
- * lib/webrick/server.rb (WEBrick::HTTPServer#start): remove
- :DoNotReverseLookup option. (Socket#do_not_reverse_lookup is a
- ruby 1.9 feature)
-
-Sat Nov 6 11:31:04 2004 Tadayoshi Funaba <tadf@dotrb.org>
-
- * lib/date.rb (_parse): checks whether zone was given.
-
Sat Nov 6 00:46:27 2004 Yukihiro Matsumoto <matz@ruby-lang.org>
* string.c (rb_str_locktmp): check STR_TMPLOCK flag before
@@ -5684,7 +5,7 @@ Sat Nov 6 00:46:27 2004 Yukihiro Matsumoto <matz@ruby-lang.org>
Fri Nov 5 18:12:42 2004 Hidetoshi NAGAI <nagai@ai.kyutech.ac.jp>
- * ext/tk/lib/tk/scrollable.rb: divide Scrollable module into
+ * ext/tk/lib/tk/scrollable.rb: divide Scrollable module into
X_Scrollable and Y_Scrollable
* ext/tk/lib/tk/entry.rb: include X_Scrollable instead of Scrollable
@@ -5708,10 +29,6 @@ Fri Nov 5 08:52:48 2004 Yukihiro Matsumoto <matz@ruby-lang.org>
* gc.c (gc_mark): stricter GC stack check.
-Fri Nov 5 08:52:48 2004 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * gc.c (gc_mark): stricter GC stack check.
-
Fri Nov 5 08:34:43 2004 Yukihiro Matsumoto <matz@ruby-lang.org>
* string.c (str_gsub): should have removed rb_str_unlocktmp(str).
@@ -5746,7 +63,7 @@ Wed Nov 3 22:32:12 2004 NARUSE, Yui <naruse@ruby-lang.org>
* process.c: On NetBSD don't use setruid() and setrgid().
-Wed Nov 3 22:24:17 2004 Daigo Moriwaki <techml@sgtpepper.net>
+Wed Nov 3 22:24:17 2004 GOTOU Yuuzou <gotoyuzo@notwork.org>
* lib/webrick/httpauth/digestauth.rb: use Base64.encode64 to
avoid warnings.
@@ -5766,12 +83,12 @@ Wed Nov 3 17:13:02 2004 Hidetoshi NAGAI <nagai@ai.kyutech.ac.jp>
Wed Nov 3 16:58:07 2004 Hidetoshi NAGAI <nagai@ai.kyutech.ac.jp>
- * ext/tk/lib/tk.rb: support to use different Tcl commands between
+ * ext/tk/lib/tk.rb: support to use different Tcl commands between
configure and configinfo
* ext/tk/lib/font.rb: ditto.
- * ext/tk/lib/itemconfig.rb: support to use different Tcl commands
+ * ext/tk/lib/itemconfig.rb: support to use different Tcl commands
between item_configure and item_configinfo
* ext/tk/lib/itemfont.rb: ditto.
@@ -5789,7 +106,7 @@ Wed Nov 3 15:53:34 2004 Kouhei Sutou <kou@cozmixng.org>
* test/rss/test_maker_*.rb: added tests for RSS Maker.
* lib/rss/maker.rb: added RSS Maker.
-
+
* lib/rss/maker/*.rb: ditto.
Tue Nov 2 16:35:57 2004 Yukihiro Matsumoto <matz@ruby-lang.org>
@@ -5863,12 +180,6 @@ Fri Oct 29 10:00:30 2004 Yukihiro Matsumoto <matz@ruby-lang.org>
* eval.c (ruby_cleanup): ruby_finalize_1 may cause exception,
should be wrapped by PUSH_TAG/POP_TAG(). [ruby-dev:24627]
-Thu Oct 28 08:42:02 2004 Tanaka Akira <akr@m17n.org>
-
- * io.c (argf_forward): use ANSI style.
- (argf_read): call argf_forward with argv argument.
- [ruby-dev:24624]
-
Thu Oct 28 23:32:54 2004 akira yamada <akira@ruby-lang.org>
* ext/zlib/zlib.c (zstream_detach_input): resets klass of z->input if
@@ -5975,11 +286,6 @@ Fri Oct 22 00:20:33 2004 Nobuyoshi Nakada <nobu@ruby-lang.org>
* string.c (rb_str_include): should not treat char as negative value.
[ruby-dev:24558]
-Thu Oct 21 21:32:30 2004 IWATSUKI Hiroyuki <don@na.rim.or.jp>
-
- * lib/pstore.rb (PStore#transaction): Use the empty content when a
- file is not found. [ruby-dev:24561]
-
Thu Oct 21 19:06:15 2004 GOTOU Yuuzou <gotoyuzo@notwork.org>
* lib/webrick/httpresponse.rb (WEBrick::HTTPResponse#send_body_io):
@@ -6068,11 +374,6 @@ Mon Oct 18 15:58:01 2004 NAKAMURA Usaku <usa@ruby-lang.org>
* range.c (range_step, range_each): need cast.
-Fri Oct 29 16:34:19 2004 Daiki Ueno <ueno@unixuser.org>
-
- * misc/ruby-mode.el (ruby-parse-partial): Parse the rest of the
- line after opening heredoc identifier. [ruby-dev:24635]
-
Mon Oct 18 07:26:21 2004 Nobuyoshi Nakada <nobu@ruby-lang.org>
* file.c (rb_file_truncate): discard read buffer before truncation.
@@ -6119,14 +420,6 @@ Mon Oct 18 02:04:11 2004 GOTOU Yuuzou <gotoyuzo@notwork.org>
do_not_reverse_lookup for each socket if :DoNotReverseLookup
is set. [ruby-core:02357]
-Mon Oct 18 00:42:45 2004 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * ext/socket/socket.c (sock_s_getservbyaname): protocol string
- might be altered. [ruby-dev:24503]
-
- * string.c (rb_str_upto): check if return value from succ is a
- string. [ruby-dev:24504]
-
Sun Oct 17 23:03:48 2004 Hidetoshi NAGAI <nagai@ai.kyutech.ac.jp>
* ext/tk/lib/tk/timer.rb: TkTimer#start and restart accept a block
@@ -6219,6 +512,14 @@ Thu Oct 7 12:55:04 2004 Yukihiro Matsumoto <matz@ruby-lang.org>
switch. [ruby-dev:24442]
* pack.c (pack_unpack): string conversion should at the top of the
+Mon Oct 18 00:42:45 2004 Yukihiro Matsumoto <matz@ruby-lang.org>
+
+ * ext/socket/socket.c (sock_s_getservbyaname): protocol string
+ might be altered. [ruby-dev:24503]
+
+ * string.c (rb_str_upto): check if return value from succ is a
+ string. [ruby-dev:24504]
+
method. [ruby-dev:24439]
* io.c (io_read): buffer should be frozen only after the length
@@ -6308,7 +609,6 @@ Sat Oct 2 00:42:20 2004 Yukihiro Matsumoto <matz@ruby-lang.org>
[ruby-dev:24383]
* string.c (rb_str_sum): string may be altered. [ruby-dev:24381]
-
Mon Oct 11 17:51:34 2004 Yukihiro Matsumoto <matz@ruby-lang.org>
* io.c (rb_io_popen): get mode string via rb_io_flags_mode() to
@@ -6327,6 +627,7 @@ Mon Oct 11 17:51:34 2004 Yukihiro Matsumoto <matz@ruby-lang.org>
prevent access to recycled object (via continuation for
example). [ruby-dev:24463]
+
Fri Oct 1 11:40:14 2004 Yukihiro Matsumoto <matz@ruby-lang.org>
* eval.c (rb_f_eval): defer pointer retrieval to prevent unsafe
@@ -6357,6 +658,11 @@ Fri Oct 1 11:25:20 2004 Hidetoshi NAGAI <nagai@ai.kyutech.ac.jp>
Thu Sep 30 00:50:44 2004 Hidetoshi NAGAI <nagai@ai.kyutech.ac.jp>
+Sat Oct 9 00:25:39 2004 Tanaka Akira <akr@m17n.org>
+
+ * io.c (rb_io_fread): rb_thread_wait_fd() was lost.
+ [ruby-dev:24457]
+
* ext/tcltklib/tcltklib.c (ip_init): bug fix
* ext/tk/tkutil.c (get_eval_string_core): accept a Regexp object
@@ -6654,11 +960,6 @@ Wed Sep 8 15:19:49 2004 Hidetoshi NAGAI <nagai@ai.kyutech.ac.jp>
* ext/tk/lib/tk/text.rb: add TkText#clear and erase
-Tue Sep 7 15:17:49 2004 Nobuyoshi Nakada <nobu@ruby-lang.org>
-
- * ext/socket/socket.c (ruby_connect): break immediately if a
- socket is non-blocking. [ruby-talk:111654]
-
Mon Sep 6 11:08:50 2004 Hirokazu Yamamoto <ocean@m2.ccsnet.ne.jp>
* ext/tk/lib/tk/menu.rb(TkOptionMenubutton#insert): call correct method
@@ -6836,7 +1137,7 @@ Thu Aug 19 15:15:24 2004 Yukihiro Matsumoto <matz@ruby-lang.org>
* dir.c (free_dir): fix memory leak. reported by yamamoto
madoka.
-Thu Aug 19 11:00:00 2004 Akiyoshi, Masamichi <masamichi.akiyoshi@hp.com>
+Thu Aug 20 11:00:00 2004 Akiyoshi, Masamichi <masamichi.akiyoshi@hp.com>
* dln.c (dln_load): Modify to call lib$find_image_symbol for VMS.
* io.c (rb_io_fwrite): Use fputc() for VMS non-stream file.
@@ -7194,6 +1495,10 @@ Wed Jul 14 12:29:07 2004 Hirokazu Yamamoto <ocean@m2.ccsnet.ne.jp>
* test/ruby/test_float.rb (test_strtod): add test for bug fix.
+Wed Jul 14 01:18:45 2004 Hirokazu Yamamoto <ocean@m2.ccsnet.ne.jp>
+
+ * array.c: rdoc patch - unified margin.
+
Wed Jul 14 00:31:15 2004 Hirokazu Yamamoto <ocean@m2.ccsnet.ne.jp>
* array.c: rdoc patch. merged patch from Johan Holmberg
@@ -7713,7 +2018,7 @@ Sun Jun 13 00:23:04 2004 Hidetoshi NAGAI <nagai@ai.kyutech.ac.jp>
* ext/tcltklib/extconf.rb: [EXPERIMENTAL] MacOS X (darwin) support
* ext/tcltklib/tcltklib.c: fix thread trouble on callback proc, and
- eliminate warning about instance variable access
+ eliminate warning about instance variable access
* ext/tk/lib/tk/menubar.rb: improve supported menu_spec
@@ -7800,7 +2105,7 @@ Thu May 27 23:15:18 2004 NAKAMURA, Hiroshi <nakahiro@sarion.co.jp>
and a cell is represented as just a String or nil(NULL). this
change will cause widespread destruction.
- CSV.open("foo.csv", "r") do |row|
+ CSV.open("foo.csv", "r") do |row|
row.each do |cell|
if cell.is_null # using Cell#is_null
p "(NULL)"
@@ -8674,14 +2979,6 @@ Thu Mar 18 21:44:38 2004 Masatoshi SEKI <m_seki@mva.biglobe.ne.jp>
* lib/drb/drb.rb: backport drb.rb 1.16.
-Fri Mar 18 17:49:51 2005 Yukihiro Matsumoto <matz@ruby-lang.org>
-
- * struct.c (make_struct): allow const_id for accessor names.
- [ruby-core:04585]
-
- * eval.c (rb_attr): check if attribute name is local_id or
- const_id.
-
Thu Mar 18 16:22:38 2004 Yukihiro Matsumoto <matz@ruby-lang.org>
* eval.c (proc_eq): avoid false positive by using scope and
diff --git a/LEGAL b/LEGAL
index 908eb270f5..dce7c1acbf 100644
--- a/LEGAL
+++ b/LEGAL
@@ -134,12 +134,14 @@ st.[ch]:
x68/*:
missing/alloca.c:
missing/dup2.c:
+missing/erf.c:
missing/finite.c:
missing/hypot.c:
missing/isinf.c:
missing/isnan.c:
missing/memcmp.c:
missing/memmove.c:
+missing/mkdir.c:
missing/strcasecmp.c:
missing/strchr.c:
missing/streror.c:
@@ -184,8 +186,6 @@ missing/strtoul.c:
software for any purpose. It is provided "as is" without
express or implied warranty.
-missing/erf.c:
-missing/crypt.c:
missing/vsnprintf.c:
This file is under the old-style BSD license. Note that the
@@ -205,7 +205,11 @@ missing/vsnprintf.c:
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
- 3. Neither the name of the University nor the names of its contributors
+ 3. All advertising materials mentioning features or use of this software
+ must display the following acknowledgement:
+ This product includes software developed by the University of
+ California, Berkeley and its contributors.
+ 4. Neither the name of the University nor the names of its contributors
may be used to endorse or promote products derived from this software
without specific prior written permission.
@@ -305,20 +309,17 @@ ext/digest/sha2/sha2hl.c:
OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
SUCH DAMAGE.
-ext/nkf/nkf-utf8/config.h:
-ext/nkf/nkf-utf8/nkf.c:
-ext/nkf/nkf-utf8/utf8tbl.c:
+ext/nkf/nkf1.7/nkf.c:
- These files are under the following license. So to speak, it is
+ This file is under the following license. So to speak, it is
copyrighted semi-public-domain software.
Copyright (C) 1987, Fujitsu LTD. (Itaru ICHIKAWA)
Everyone is permitted to do anything on this program
- including copying, modifying, improving,
+ including copying, modifying, improving.
as long as you don't try to pretend that you wrote it.
i.e., the above copyright notice has to appear in all copies.
- Binary distribution requires original version messages.
- You don't have to ask before copying, redistribution or publishing.
+ You don't have to ask before copying or publishing.
THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE.
ext/socket/addrinfo.h:
diff --git a/Makefile.in b/Makefile.in
index 9dde68840e..663ba43111 100644
--- a/Makefile.in
+++ b/Makefile.in
@@ -10,7 +10,6 @@ YACC = @YACC@
PURIFY =
AUTOCONF = autoconf
@SET_MAKE@
-MKFILES = @MAKEFILES@
prefix = @prefix@
exec_prefix = @exec_prefix@
@@ -18,19 +17,10 @@ bindir = @bindir@
sbindir = @sbindir@
libdir = @libdir@
libexecdir = @libexecdir@
-datadir = @datadir@
arch = @arch@
sitearch = @sitearch@
sitedir = @sitedir@
-TESTUI = console
-TESTS =
-RDOCTARGET = @RDOCTARGET@
-
-EXTOUT = @EXTOUT@
-RIDATADIR = $(DESTDIR)$(datadir)/ri/$(MAJOR).$(MINOR)/system
-
-OUTFLAG = -o
CFLAGS = @CFLAGS@ @XCFLAGS@ @ARCH_FLAG@
CPPFLAGS = -I. -I$(srcdir) @CPPFLAGS@
LDFLAGS = @STATIC@ $(CFLAGS) @LDFLAGS@
@@ -43,7 +33,6 @@ LDSHARED = @LIBRUBY_LDSHARED@
DLDFLAGS = @LIBRUBY_DLDFLAGS@ $(EXTLDFLAGS) @ARCH_FLAG@
SOLIBS = @SOLIBS@
MAINLIBS = @MAINLIBS@
-MINIOBJS = @MINIOBJS@
RUBY_INSTALL_NAME=@RUBY_INSTALL_NAME@
RUBY_SO_NAME=@RUBY_SO_NAME@
@@ -51,7 +40,6 @@ EXEEXT = @EXEEXT@
PROGRAM=$(RUBY_INSTALL_NAME)$(EXEEXT)
RUBY = $(RUBY_INSTALL_NAME)
MINIRUBY = @MINIRUBY@
-RUNRUBY = @RUNRUBY@
#### End of system configuration section. ####
@@ -67,52 +55,135 @@ LIBRUBYARG = @LIBRUBYARG@
LIBRUBYARG_STATIC = @LIBRUBYARG_STATIC@
LIBRUBYARG_SHARED = @LIBRUBYARG_SHARED@
-PREP = @PREP@
-ARCHFILE = @ARCHFILE@
+PREP = @PREP@ @ARCHFILE@
SETUP =
EXTSTATIC = @EXTSTATIC@
-RM = rm -f
-NM = @NM@
-AR = @AR@
-ARFLAGS = rcu
-RANLIB = @RANLIB@
+EXTOBJS =
+DLDOBJS = $(DMYEXT)
+DMYEXT = dmyext.@OBJEXT@
+
+MAINOBJ = main.@OBJEXT@
+
+OBJS = array.@OBJEXT@ \
+ bignum.@OBJEXT@ \
+ class.@OBJEXT@ \
+ compar.@OBJEXT@ \
+ dir.@OBJEXT@ \
+ dln.@OBJEXT@ \
+ enum.@OBJEXT@ \
+ error.@OBJEXT@ \
+ eval.@OBJEXT@ \
+ file.@OBJEXT@ \
+ gc.@OBJEXT@ \
+ hash.@OBJEXT@ \
+ inits.@OBJEXT@ \
+ io.@OBJEXT@ \
+ marshal.@OBJEXT@ \
+ math.@OBJEXT@ \
+ numeric.@OBJEXT@ \
+ object.@OBJEXT@ \
+ pack.@OBJEXT@ \
+ parse.@OBJEXT@ \
+ process.@OBJEXT@ \
+ prec.@OBJEXT@ \
+ random.@OBJEXT@ \
+ range.@OBJEXT@ \
+ re.@OBJEXT@ \
+ regex.@OBJEXT@ \
+ ruby.@OBJEXT@ \
+ signal.@OBJEXT@ \
+ sprintf.@OBJEXT@ \
+ st.@OBJEXT@ \
+ string.@OBJEXT@ \
+ struct.@OBJEXT@ \
+ time.@OBJEXT@ \
+ util.@OBJEXT@ \
+ variable.@OBJEXT@ \
+ version.@OBJEXT@ \
+ $(MISSING)
-OBJEXT = @OBJEXT@
MANTYPE = @MANTYPE@
-#### End of variables
+SCRIPT_ARGS = --dest-dir="$(DESTDIR)" \
+ --make="$(MAKE)" \
+ --mflags="$(MFLAGS)" \
+ --make-flags="$(MAKEFLAGS)"
-all:
+all: @MAKEFILES@ miniruby$(EXEEXT) rbconfig.rb $(LIBRUBY)
+ @$(MINIRUBY) $(srcdir)/ext/extmk.rb --extstatic="$(EXTSTATIC)" $(SCRIPT_ARGS)
-.DEFAULT: all
+miniruby$(EXEEXT): config.status $(LIBRUBY_A) $(MAINOBJ) $(DMYEXT)
+ @rm -f $@
+ $(PURIFY) $(CC) $(LDFLAGS) $(MAINLIBS) $(MAINOBJ) $(DMYEXT) $(LIBRUBY_A) $(LIBS) -o $@
-# Prevent GNU make v3 from overflowing arg limit on SysV.
-.NOEXPORT:
-
-miniruby$(EXEEXT):
- @$(RM) $@
- $(PURIFY) $(CC) $(MAINOBJ) $(MINIOBJS) $(LIBRUBY_A) $(LIBS) $(OUTFLAG)$@ $(LDFLAGS) $(MAINLIBS)
-
-$(PROGRAM):
- @$(RM) $@
- $(PURIFY) $(CC) $(LDFLAGS) $(XLDFLAGS) $(MAINLIBS) $(MAINOBJ) $(EXTOBJS) $(LIBRUBYARG) $(LIBS) $(OUTFLAG)$@
+$(PROGRAM): $(LIBRUBY) $(MAINOBJ) $(EXTOBJS) $(SETUP) miniruby$(EXEEXT)
+ @rm -f $@
+ $(PURIFY) $(CC) $(LDFLAGS) $(XLDFLAGS) $(MAINLIBS) $(MAINOBJ) $(EXTOBJS) $(LIBRUBYARG) $(LIBS) -o $@
# We must `rm' the library each time this rule is invoked because "updating" a
# MAB library on Apple/NeXT (see --enable-fat-binary in configure) is not
# supported.
-$(LIBRUBY_A):
- @$(RM) $@
- $(AR) $(ARFLAGS) $@ $(OBJS) $(DMYEXT)
- @-$(RANLIB) $@ 2> /dev/null || true
+$(LIBRUBY_A): $(OBJS) $(DMYEXT)
+ @rm -f $@
+ @AR@ rcu $@ $(OBJS) $(DMYEXT)
+ @-@RANLIB@ $@ 2> /dev/null || true
-$(LIBRUBY_SO):
- $(LDSHARED) $(DLDFLAGS) $(OBJS) $(DLDOBJS) $(SOLIBS) $(OUTFLAG)$@
+$(LIBRUBY_SO): $(OBJS) $(DLDOBJS) miniruby$(EXEEXT) $(PREP)
+ $(LDSHARED) $(DLDFLAGS) $(OBJS) $(DLDOBJS) $(SOLIBS) -o $@
@-$(MINIRUBY) -e 'ARGV.each{|link| File.delete link if File.exist? link; \
File.symlink "$(LIBRUBY_SO)", link}' \
$(LIBRUBY_ALIASES) || true
-fake.rb: Makefile
+ruby.imp: $(LIBRUBY_A)
+ @@NM@ -Pgp $(LIBRUBY_A) | awk 'BEGIN{print "#!"}; $$2~/^[BD]$$/{print $$1}' | sort -u -o $@
+# $(MINIRUBY) $< $@
+
+install: install-nodoc @RDOCTARGET@
+
+install-nodoc: rbconfig.rb
+ $(MINIRUBY) $(srcdir)/instruby.rb $(SCRIPT_ARGS) --mantype="$(MANTYPE)"
+ $(MINIRUBY) $(srcdir)/ext/extmk.rb $(SCRIPT_ARGS) install
+
+what-where no-install: rbconfig.rb
+ $(MINIRUBY) $(srcdir)/instruby.rb -n $(SCRIPT_ARGS) --mantype="$(MANTYPE)"
+ $(MINIRUBY) $(srcdir)/ext/extmk.rb -n $(SCRIPT_ARGS) install
+
+install-doc:
+ @echo Generating RDoc documentation
+ $(bindir)/$(PROGRAM) $(srcdir)/bin/rdoc --all --ri-system $(srcdir)
+
+clean-ext:
+ @-$(MINIRUBY) $(srcdir)/ext/extmk.rb $(SCRIPT_ARGS) clean 2> /dev/null || true
+
+clean-local:
+ @rm -f $(OBJS) $(MAINOBJ) $(LIBRUBY_A) $(LIBRUBY_SO) $(LIBRUBY_ALIASES)
+ @rm -f ext/extinit.c ext/extinit.@OBJEXT@ dmyext.@OBJEXT@
+ @rm -f $(PROGRAM) miniruby$(EXEEXT)
+
+clean: clean-ext clean-local
+
+distclean-ext:
+ @-$(MINIRUBY) $(srcdir)/ext/extmk.rb $(SCRIPT_ARGS) distclean 2> /dev/null || true
+
+distclean-local: clean-local
+ @rm -f @MAKEFILES@ config.h rbconfig.rb
+ @rm -f ext/config.cache config.cache config.log config.status
+ @rm -f *~ core *.core gmon.out y.tab.c y.output ruby.imp
+
+distclean: distclean-ext distclean-local
+
+realclean: distclean
+ @rm -f parse.c
+ @rm -f lex.c
+
+test: miniruby$(EXEEXT) rbconfig.rb $(PROGRAM) PHONY
+ @./miniruby$(EXEEXT) $(srcdir)/rubytest.rb
+
+rbconfig.rb: miniruby$(EXEEXT) $(srcdir)/mkconfig.rb config.status $(PREP)
+ @$(MINIRUBY) $(srcdir)/mkconfig.rb rbconfig.rb
+
+fake.rb: miniruby$(EXEEXT) Makefile
@echo ' \
class Object; \
CROSS_COMPILING = RUBY_PLATFORM; \
@@ -131,7 +202,13 @@ fake.rb: Makefile
Makefile: $(srcdir)/Makefile.in
-$(MKFILES): config.status $(srcdir)/common.mk
+.PRECIOUS: @MAKEFILES@
+
+.PHONY: test install install-nodoc install-doc
+
+PHONY:
+
+@MAKEFILES@: config.status
MAKE=$(MAKE) $(SHELL) ./config.status
@{ \
echo "all:; -@rm -f conftest.mk"; \
@@ -147,8 +224,11 @@ config.status: $(srcdir)/configure
$(srcdir)/configure: $(srcdir)/configure.in
cd $(srcdir) && $(AUTOCONF)
+.c.@OBJEXT@:
+ $(CC) $(CFLAGS) $(CPPFLAGS) -c $<
+
lex.c: keywords
- @-$(RM) $@
+ @-rm -f $@
gperf -p -j1 -i 1 -g -o -t -N rb_reserved_word -k1,3,$$ $? > $@ || \
cp "$(srcdir)/$@" .
@@ -157,14 +237,144 @@ lex.c: keywords
sed '/^#/s|y\.tab\.c|$@|' y.tab.c > $@
rm -f y.tab.c
-.c.@OBJEXT@:
- $(CC) $(CFLAGS) $(CPPFLAGS) -c $<
+ext/extinit.@OBJEXT@: ext/extinit.c $(SETUP)
+ $(CC) $(CFLAGS) $(CPPFLAGS) @OUTFLAG@$@ -c ext/extinit.c
+
+acosh.@OBJEXT@: $(srcdir)/missing/acosh.c
+ $(CC) -I. $(CFLAGS) $(CPPFLAGS) -c $(srcdir)/missing/acosh.c
+
+alloca.@OBJEXT@: $(srcdir)/missing/alloca.c
+ $(CC) -I. $(CFLAGS) $(CPPFLAGS) -c $(srcdir)/missing/alloca.c
+
+crypt.@OBJEXT@: $(srcdir)/missing/crypt.c
+ $(CC) -I. $(CFLAGS) $(CPPFLAGS) -c $(srcdir)/missing/crypt.c
+
+dup2.@OBJEXT@: $(srcdir)/missing/dup2.c
+ $(CC) -I. $(CFLAGS) $(CPPFLAGS) -c $(srcdir)/missing/dup2.c
+
+fileblocks.@OBJEXT@: $(srcdir)/missing/fileblocks.c
+ $(CC) -I. $(CFLAGS) $(CPPFLAGS) -c $(srcdir)/missing/fileblocks.c
+
+finite.@OBJEXT@: $(srcdir)/missing/finite.c
+ $(CC) -I. $(CFLAGS) $(CPPFLAGS) -c $(srcdir)/missing/finite.c
+
+flock.@OBJEXT@: $(srcdir)/missing/flock.c
+ $(CC) -I. $(CFLAGS) $(CPPFLAGS) -c $(srcdir)/missing/flock.c
+
+isinf.@OBJEXT@: $(srcdir)/missing/isinf.c
+ $(CC) -I. $(CFLAGS) $(CPPFLAGS) -c $(srcdir)/missing/isinf.c
+
+isnan.@OBJEXT@: $(srcdir)/missing/isnan.c
+ $(CC) -I. $(CFLAGS) $(CPPFLAGS) -c $(srcdir)/missing/isnan.c
+
+fnmatch.@OBJEXT@: $(srcdir)/missing/fnmatch.c
+ $(CC) -I. $(CFLAGS) $(CPPFLAGS) -c $(srcdir)/missing/fnmatch.c
+
+memcmp.@OBJEXT@: $(srcdir)/missing/memcmp.c
+ $(CC) $(CFLAGS) $(CPPFLAGS) -c $(srcdir)/missing/memcmp.c
+
+memmove.@OBJEXT@: $(srcdir)/missing/memmove.c
+ $(CC) $(CFLAGS) $(CPPFLAGS) -c $(srcdir)/missing/memmove.c
+
+mkdir.@OBJEXT@: $(srcdir)/missing/mkdir.c
+ $(CC) $(CFLAGS) $(CPPFLAGS) -c $(srcdir)/missing/mkdir.c
-clean-local::
- @$(RM) ext/extinit.c ext/extinit.$(OBJEXT)
+vsnprintf.@OBJEXT@: $(srcdir)/missing/vsnprintf.c
+ $(CC) $(CFLAGS) $(CPPFLAGS) -c $(srcdir)/missing/vsnprintf.c
-distclean-local::
- @$(RM) ext/config.cache $(RBCONFIG)
+strcasecmp.@OBJEXT@: $(srcdir)/missing/strcasecmp.c
+ $(CC) $(CFLAGS) $(CPPFLAGS) -c $(srcdir)/missing/strcasecmp.c
-ext/extinit.$(OBJEXT): ext/extinit.c $(SETUP)
- $(CC) $(CFLAGS) $(XCFLAGS) $(CPPFLAGS) -o$@ -c ext/extinit.c
+strncasecmp.@OBJEXT@: $(srcdir)/missing/strncasecmp.c
+ $(CC) $(CFLAGS) $(CPPFLAGS) -c $(srcdir)/missing/strncasecmp.c
+
+strchr.@OBJEXT@: $(srcdir)/missing/strchr.c
+ $(CC) $(CFLAGS) $(CPPFLAGS) -c $(srcdir)/missing/strchr.c
+
+strerror.@OBJEXT@: $(srcdir)/missing/strerror.c
+ $(CC) $(CFLAGS) $(CPPFLAGS) -c $(srcdir)/missing/strerror.c
+
+strftime.@OBJEXT@: $(srcdir)/missing/strftime.c
+ $(CC) -I. $(CFLAGS) $(CPPFLAGS) -c $(srcdir)/missing/strftime.c
+
+strstr.@OBJEXT@: $(srcdir)/missing/strstr.c
+ $(CC) $(CFLAGS) $(CPPFLAGS) -c $(srcdir)/missing/strstr.c
+
+strtol.@OBJEXT@: $(srcdir)/missing/strtol.c
+ $(CC) $(CFLAGS) $(CPPFLAGS) -c $(srcdir)/missing/strtol.c
+
+strtoul.@OBJEXT@: $(srcdir)/missing/strtoul.c
+ $(CC) $(CFLAGS) $(CPPFLAGS) -c $(srcdir)/missing/strtoul.c
+
+x68.@OBJEXT@: $(srcdir)/missing/x68.c
+ $(CC) $(CFLAGS) $(CPPFLAGS) -c $(srcdir)/missing/x68.c
+
+os2.@OBJEXT@: $(srcdir)/missing/os2.c
+ $(CC) $(CFLAGS) $(CPPFLAGS) -c $(srcdir)/missing/os2.c
+
+dl_os2.@OBJEXT@: $(srcdir)/missing/dl_os2.c
+ $(CC) $(CFLAGS) $(CPPFLAGS) -c $(srcdir)/missing/dl_os2.c
+
+win32.@OBJEXT@: $(srcdir)/win32/win32.c
+ $(CC) $(CFLAGS) $(CPPFLAGS) -I$(srcdir)/win32 -c $(srcdir)/win32/win32.c
+
+# Prevent GNU make v3 from overflowing arg limit on SysV.
+.NOEXPORT:
+###
+array.@OBJEXT@: array.c ruby.h config.h defines.h intern.h missing.h \
+ util.h st.h
+bignum.@OBJEXT@: bignum.c ruby.h config.h defines.h intern.h missing.h
+class.@OBJEXT@: class.c ruby.h config.h defines.h intern.h missing.h \
+ rubysig.h node.h st.h
+compar.@OBJEXT@: compar.c ruby.h config.h defines.h intern.h missing.h
+dir.@OBJEXT@: dir.c ruby.h config.h defines.h intern.h missing.h util.h
+dln.@OBJEXT@: dln.c ruby.h config.h defines.h intern.h missing.h dln.h
+dmyext.@OBJEXT@: dmyext.c
+enum.@OBJEXT@: enum.c ruby.h config.h defines.h intern.h missing.h node.h \
+ util.h
+error.@OBJEXT@: error.c ruby.h config.h defines.h intern.h missing.h \
+ env.h st.h
+eval.@OBJEXT@: eval.c ruby.h config.h defines.h intern.h missing.h node.h \
+ env.h util.h rubysig.h st.h dln.h
+file.@OBJEXT@: file.c ruby.h config.h defines.h intern.h missing.h \
+ rubyio.h rubysig.h util.h dln.h
+gc.@OBJEXT@: gc.c ruby.h config.h defines.h intern.h missing.h rubysig.h \
+ st.h node.h env.h re.h regex.h
+hash.@OBJEXT@: hash.c ruby.h config.h defines.h intern.h missing.h st.h \
+ util.h rubysig.h
+inits.@OBJEXT@: inits.c ruby.h config.h defines.h intern.h missing.h
+io.@OBJEXT@: io.c ruby.h config.h defines.h intern.h missing.h rubyio.h \
+ rubysig.h env.h util.h
+main.@OBJEXT@: main.c ruby.h config.h defines.h intern.h missing.h
+marshal.@OBJEXT@: marshal.c ruby.h config.h defines.h intern.h missing.h \
+ rubyio.h st.h util.h
+math.@OBJEXT@: math.c ruby.h config.h defines.h intern.h missing.h
+numeric.@OBJEXT@: numeric.c ruby.h config.h defines.h intern.h missing.h
+object.@OBJEXT@: object.c ruby.h config.h defines.h intern.h missing.h \
+ st.h util.h
+pack.@OBJEXT@: pack.c ruby.h config.h defines.h intern.h missing.h
+parse.@OBJEXT@: parse.c ruby.h config.h defines.h intern.h missing.h \
+ env.h node.h st.h regex.h util.h lex.c
+prec.@OBJEXT@: prec.c ruby.h config.h defines.h intern.h missing.h
+process.@OBJEXT@: process.c ruby.h config.h defines.h intern.h missing.h \
+ rubysig.h st.h
+random.@OBJEXT@: random.c ruby.h config.h defines.h intern.h missing.h
+range.@OBJEXT@: range.c ruby.h config.h defines.h intern.h missing.h
+re.@OBJEXT@: re.c ruby.h config.h defines.h intern.h missing.h re.h \
+ regex.h
+regex.@OBJEXT@: regex.c config.h regex.h
+ruby.@OBJEXT@: ruby.c ruby.h config.h defines.h intern.h missing.h dln.h \
+ node.h util.h
+signal.@OBJEXT@: signal.c ruby.h config.h defines.h intern.h missing.h \
+ rubysig.h
+sprintf.@OBJEXT@: sprintf.c ruby.h config.h defines.h intern.h missing.h
+st.@OBJEXT@: st.c config.h st.h
+string.@OBJEXT@: string.c ruby.h config.h defines.h intern.h missing.h \
+ re.h regex.h
+struct.@OBJEXT@: struct.c ruby.h config.h defines.h intern.h missing.h
+time.@OBJEXT@: time.c ruby.h config.h defines.h intern.h missing.h
+util.@OBJEXT@: util.c ruby.h config.h defines.h intern.h missing.h util.h
+variable.@OBJEXT@: variable.c ruby.h config.h defines.h intern.h \
+ missing.h env.h node.h st.h util.h
+version.@OBJEXT@: version.c ruby.h config.h defines.h intern.h missing.h \
+ version.h
diff --git a/README.EXT b/README.EXT
index 4cfe80bd82..d832d1e0af 100644
--- a/README.EXT
+++ b/README.EXT
@@ -295,15 +295,6 @@ To define alias to the method,
void rb_define_alias(VALUE module, const char* new, const char* old);
-To define and undefine the `allocate' class method,
-
- void rb_define_alloc_func(VALUE klass, VALUE (*func)(VALUE klass));
- void rb_undef_alloc_func(VALUE klass);
-
-func have to take the klass as the argument and return a newly
-allocated instance. This instance should be empty as possible,
-without any expensive (including external) resources.
-
2.1.3 Constant definition
We have 2 functions to define constants:
@@ -604,7 +595,8 @@ are not exported to the Ruby world. You need to protect them by
(4) prepare extconf.rb
If the file named extconf.rb exists, it will be executed to generate
-Makefile.
+Makefile. If not, the compilation scheme will try to generate Makefile
+anyway.
extconf.rb is the file for check compilation conditions etc. You
need to put
@@ -621,14 +613,8 @@ various conditions.
The value of the variables below will affect the Makefile.
- $CFLAGS: included in CFLAGS make variable (such as -O)
- $CPPFLAGS: included in CPPFLAGS make variable (such as -I, -D)
+ $CFLAGS: included in CFLAGS make variable (such as -I)
$LDFLAGS: included in LDFLAGS make variable (such as -L)
- $objs: list of object file names
-
-In normal, object files list is automatically generated by searching
-source files, but you need directs them explicitly if any sources will
-be generated while building.
If a compilation condition is not fulfilled, you should not call
``create_makefile''. The Makefile will not generated, compilation will
@@ -786,9 +772,7 @@ NUM2INT(value)
INT2NUM(i)
NUM2DBL(value)
rb_float_new(f)
-StringValue(value)
-StringValuePtr(value)
-StringValueCStr(value)
+STR2CSTR(value)
rb_str_new2(s)
** defining class/module
@@ -1022,11 +1006,6 @@ Appendix C. Functions Available in extconf.rb
These functions are available in extconf.rb:
- have_macro(macro, headers)
-
-Checks whether macro is defined with header. Returns true if the macro
-is defined.
-
have_library(lib, func)
Checks whether the library exists, containing the specified function.
@@ -1043,61 +1022,20 @@ Checks whether func exists with header. Returns true if the function
exists. To check functions in an additional library, you need to
check that library first using have_library().
- have_var(var, header)
-
-Checks whether var exists with header. Returns true if the variable
-exists. To check variables in an additional library, you need to
-check that library first using have_library().
-
have_header(header)
Checks whether header exists. Returns true if the header file exists.
- find_header(header, path...)
-
-Checks whether header exists in path. Returns true if the header file
-exists.
-
- have_struct_member(type, member, header)
-
-Checks whether type has member with header. Returns true if the type
-is defined and has the member.
-
- have_type(type, header, opt)
-
-Checks whether type is defined with header. Returns true if the type
-is defined.
-
- check_sizeof(type, header)
-
-Checks the size of type in char with header. Returns the size if the
-type is defined, otherwise nil.
-
create_makefile(target)
Generates the Makefile for the extension library. If you don't invoke
this method, the compilation will not be done.
- find_executable(bin, path)
-
-Finds command in path, which is File::PATH_SEPARATOR-separated list of
-directories. If path is nil or omitted, environment varialbe PATH
-will be used. Returns the path name of the command if it is found,
-otherwise nil.
-
with_config(withval[, default=nil])
Parses the command line options and returns the value specified by
--with-<withval>.
- enable_config(config, *defaults)
- disable_config(config, *defaults)
-
-Parses the command line options for boolean. Returns true if
---enable-<config> is given, or false if --disable-<config> is given.
-Otherwise, yields defaults to the given block and returns the result
-if it is called with a block, or returns defaults.
-
dir_config(target[, default_dir])
dir_config(target[, default_include, default_lib])
@@ -1107,12 +1045,6 @@ to $CFLAGS and/or $LDFLAGS. --with-<target>-dir=/path is equivalent to
--with-<target>-include=/path/include --with-<target>-lib=/path/lib.
Returns an array of the added directories ([include_dir, lib_dir]).
- pkg_config(pkg)
-
-Obtains the information of pkg by pkg-config command. The actual
-command name can be overriden by --with-pkg-config command line
-option.
-
/*
* Local variables:
* fill-column: 70
diff --git a/README.EXT.ja b/README.EXT.ja
index f8b625e7ef..7a4cb5df2a 100644
--- a/README.EXT.ja
+++ b/README.EXT.ja
@@ -331,17 +331,6 @@ private¥á¥½¥Ã¥É¤È¤Ï´Ø¿ô·Á¼°¤Ç¤·¤«¸Æ¤Ó½Ð¤¹¤³¤È¤Î½ÐÍè¤Ê¤¤¥á¥½¥Ã
void rb_define_alias(VALUE module, const char* new, const char* old);
-¥¯¥é¥¹¥á¥½¥Ã¥Éallocate¤òÄêµÁ¤·¤¿¤êºï½ü¤·¤¿¤ê¤¹¤ë¤¿¤á¤Î´Ø¿ô¤Ï
-°Ê²¼¤ÎÄ̤ê¤Ç¤¹¡£
-
- void rb_define_alloc_func(VALUE klass, VALUE (*func)(VALUE klass));
- void rb_undef_alloc_func(VALUE klass);
-
-func¤Ï¥¯¥é¥¹¤ò°ú¿ô¤È¤·¤Æ¼õ¤±¼è¤Ã¤Æ¡¢¿·¤·¤¯³ä¤êÅö¤Æ¤é¤ì¤¿¥¤¥ó
-¥¹¥¿¥ó¥¹¤òÊÖ¤µ¤Ê¤¯¤Æ¤Ï¤Ê¤ê¤Þ¤»¤ó¡£¤³¤Î¥¤¥ó¥¹¥¿¥ó¥¹¤Ï¡¢³°Éô¥ê
-¥½¡¼¥¹¤Ê¤É¤ò´Þ¤Þ¤Ê¤¤¡¢¤Ç¤­¤ë¤À¤±¡Ö¶õ¡×¤Î¤Þ¤Þ¤Ë¤·¤Æ¤ª¤¤¤¿¤Û¤¦
-¤¬¤è¤¤¤Ç¤·¤ç¤¦¡£
-
2.1.3 Äê¿ôÄêµÁ
³ÈÄ¥¥é¥¤¥Ö¥é¥ê¤¬É¬ÍפÊÄê¿ô¤Ï¤¢¤é¤«¤¸¤áÄêµÁ¤·¤Æ¤ª¤¤¤¿Êý¤¬Îɤ¤
@@ -721,14 +710,8 @@ Makefile¤òºî¤ë¾ì¹ç¤Î¿÷·¿¤Ë¤Ê¤ëextconf.rb¤È¤¤¤¦¥Õ¥¡¥¤¥ë¤òºî¤ê
°Ê²¼¤ÎÊÑ¿ô¤ò»È¤¦¤³¤È¤¬¤Ç¤­¤Þ¤¹¡¥
- $CFLAGS: ¥³¥ó¥Ñ¥¤¥ë»þ¤ËÄɲÃŪ¤Ë»ØÄꤹ¤ë¥Õ¥é¥°(-O¤Ê¤É)
- $CPPFLAGS: ¥×¥ê¥×¥í¥»¥Ã¥µ¤ËÄɲÃŪ¤Ë»ØÄꤹ¤ë¥Õ¥é¥°(-I¤ä-D¤Ê¤É)
+ $CFLAGS: ¥³¥ó¥Ñ¥¤¥ë»þ¤ËÄɲÃŪ¤Ë»ØÄꤹ¤ë¥Õ¥é¥°(-I¤Ê¤É)
$LDFLAGS: ¥ê¥ó¥¯»þ¤ËÄɲÃŪ¤Ë»ØÄꤹ¤ë¥Õ¥é¥°(-L¤Ê¤É)
- $objs: ¥ê¥ó¥¯¤µ¤ì¤ë¥ª¥Ö¥¸¥§¥¯¥È¥Õ¥¡¥¤¥ë̾¤Î¥ê¥¹¥È
-
-¥ª¥Ö¥¸¥§¥¯¥È¥Õ¥¡¥¤¥ë¤Î¥ê¥¹¥È¤Ï¡¢Ä̾ï¤Ï¥½¡¼¥¹¥Õ¥¡¥¤¥ë¤ò¸¡º÷¤·
-¤Æ¼«Æ°Åª¤ËÀ¸À®¤µ¤ì¤Þ¤¹¤¬¡¢make¤ÎÅÓÃæ¤Ç¥½¡¼¥¹¤òÀ¸À®¤¹¤ë¤è¤¦¤Ê
-¾ì¹ç¤ÏÌÀ¼¨Åª¤Ë»ØÄꤹ¤ëɬÍפ¬¤¢¤ê¤Þ¤¹¡£
¥é¥¤¥Ö¥é¥ê¤ò¥³¥ó¥Ñ¥¤¥ë¤¹¤ë¾ò·ï¤¬Â·¤ï¤º¡¤¤½¤Î¥é¥¤¥Ö¥é¥ê¤ò¥³¥ó
¥Ñ¥¤¥ë¤·¤Ê¤¤»þ¤Ë¤Ïcreate_makefile¤ò¸Æ¤Ð¤Ê¤±¤ì¤ÐMakefile¤ÏÀ¸
@@ -908,9 +891,7 @@ NUM2INT(value)
INT2NUM(i)
NUM2DBL(value)
rb_float_new(f)
-StringValue(value)
-StringValuePtr(value)
-StringValueCStr(value)
+STR2CSTR(value)
rb_str_new2(s)
** ¥¯¥é¥¹/¥â¥¸¥å¡¼¥ëÄêµÁ
@@ -1142,12 +1123,6 @@ Appendix C. extconf.rb¤Ç»È¤¨¤ë´Ø¿ô¤¿¤Á
extconf.rb¤ÎÃæ¤Ç¤ÏÍøÍѲÄǽ¤Ê¥³¥ó¥Ñ¥¤¥ë¾ò·ï¥Á¥§¥Ã¥¯¤Î´Ø¿ô¤Ï°Ê
²¼¤ÎÄ̤ê¤Ç¤¢¤ë¡¥
-have_macro(macro, headers)
-
- ¥Ø¥Ã¥À¥Õ¥¡¥¤¥ëheader¤ò¥¤¥ó¥¯¥ë¡¼¥É¤·¤Æ¥Þ¥¯¥ímacro¤¬ÄêµÁ¤µ
- ¤ì¤Æ¤¤¤ë¤«¤É¤¦¤«¥Á¥§¥Ã¥¯¤¹¤ë¡¥¥Þ¥¯¥í¤¬ÄêµÁ¤µ¤ì¤Æ¤¤¤ë»þtrue
- ¤òÊÖ¤¹¡¥
-
have_library(lib, func)
´Ø¿ôfunc¤òÄêµÁ¤·¤Æ¤¤¤ë¥é¥¤¥Ö¥é¥êlib¤Î¸ºß¤ò¥Á¥§¥Ã¥¯¤¹¤ë¡¥
@@ -1165,67 +1140,21 @@ have_func(func, header)
¤ë»þ¤Ë¤ÏÀè¤Ëhave_library¤Ç¤½¤Î¥é¥¤¥Ö¥é¥ê¤ò¥Á¥§¥Ã¥¯¤·¤Æ¤ª¤¯
»ö¡¥´Ø¿ô¤¬Â¸ºß¤¹¤ë»þtrue¤òÊÖ¤¹¡¥
-have_var(var, header)
-
- ¥Ø¥Ã¥À¥Õ¥¡¥¤¥ëheader¤ò¥¤¥ó¥¯¥ë¡¼¥É¤·¤ÆÊÑ¿ôvar¤Î¸ºß¤ò¥Á¥§¥Ã
- ¥¯¤¹¤ë¡¥var¤¬É¸½à¤Ç¤Ï¥ê¥ó¥¯¤µ¤ì¤Ê¤¤¥é¥¤¥Ö¥é¥êÆâ¤Î¤â¤Î¤Ç¤¢
- ¤ë»þ¤Ë¤ÏÀè¤Ëhave_library¤Ç¤½¤Î¥é¥¤¥Ö¥é¥ê¤ò¥Á¥§¥Ã¥¯¤·¤Æ¤ª¤¯
- »ö¡¥ÊÑ¿ô¤¬Â¸ºß¤¹¤ë»þtrue¤òÊÖ¤¹¡¥
-
have_header(header)
¥Ø¥Ã¥À¥Õ¥¡¥¤¥ë¤Î¸ºß¤ò¥Á¥§¥Ã¥¯¤¹¤ë¡¥¥Ø¥Ã¥À¥Õ¥¡¥¤¥ë¤¬Â¸ºß¤¹
¤ë»þtrue¤òÊÖ¤¹¡¥
-find_header(header, path...)
-
- ¥Ø¥Ã¥À¥Õ¥¡¥¤¥ëheader¤Î¸ºß¤ò -Ipath ¤òÄɲ䷤ʤ¬¤é¥Á¥§¥Ã¥¯
- ¤¹¤ë¡¥¥Ø¥Ã¥À¥Õ¥¡¥¤¥ë¤¬¸«ÉÕ¤«¤Ã¤¿»þ¡¤true¤òÊÖ¤¹¡¥
-
-have_struct_member(type, member, header)
-
- ¥Ø¥Ã¥À¥Õ¥¡¥¤¥ëheader¤ò¥¤¥ó¥¯¥ë¡¼¥É¤·¤Æ·¿type¤Ë¥á¥ó¥Ðmember
- ¤¬Â¸ºß¤¹¤ë¤«¤ò¥Á¥§¥Ã¥¯¤¹¤ë¡¥type¤¬ÄêµÁ¤µ¤ì¤Æ¤¤¤Æ¡¤member¤ò
- »ý¤Ä¤¹¤ë»þtrue¤òÊÖ¤¹¡¥
-
-have_type(type, header, opt)
-
- ¥Ø¥Ã¥À¥Õ¥¡¥¤¥ëheader¤ò¥¤¥ó¥¯¥ë¡¼¥É¤·¤Æ·¿type¤¬Â¸ºß¤¹¤ë¤«¤ò
- ¥Á¥§¥Ã¥¯¤¹¤ë¡¥type¤¬ÄêµÁ¤µ¤ì¤Æ¤¤¤ë»þtrue¤òÊÖ¤¹¡¥
-
-check_sizeof(type, header)
-
- ¥Ø¥Ã¥À¥Õ¥¡¥¤¥ëheader¤ò¥¤¥ó¥¯¥ë¡¼¥É¤·¤Æ·¿type¤Îcharñ°Ì¥µ¥¤
- ¥º¤òÄ´¤Ù¤ë¡¥type¤¬ÄêµÁ¤µ¤ì¤Æ¤¤¤ë»þ¤½¤Î¥µ¥¤¥º¤òÊÖ¤¹¡¥ÄêµÁ¤µ
- ¤ì¤Æ¤¤¤Ê¤¤¤È¤­¤Ïnil¤òÊÖ¤¹¡¥
-
create_makefile(target)
³ÈÄ¥¥é¥¤¥Ö¥é¥êÍѤÎMakefile¤òÀ¸À®¤¹¤ë¡¥¤³¤Î´Ø¿ô¤ò¸Æ¤Ð¤Ê¤±¤ì
¤Ð¤½¤Î¥é¥¤¥Ö¥é¥ê¤Ï¥³¥ó¥Ñ¥¤¥ë¤µ¤ì¤Ê¤¤¡¥target¤Ï¥â¥¸¥å¡¼¥ë̾
¤òɽ¤¹¡¥
-find_executable(command, path)
-
- ¥³¥Þ¥ó¥Écommand¤òFile::PATH_SEPARATOR¤Ç¶èÀÚ¤é¤ì¤¿¥Ñ¥¹Ì¾¤Î
- ¥ê¥¹¥Èpath¤«¤éõ¤¹¡¥path¤¬nil¤Þ¤¿¤Ï¾Êά¤µ¤ì¤¿¾ì¹ç¤Ï¡¤´Ä¶­
- ÊÑ¿ôPATH¤ÎÃͤò»ÈÍѤ¹¤ë¡¥¼Â¹Ô²Äǽ¤Ê¥³¥Þ¥ó¥É¤¬¸«¤Ä¤«¤Ã¤¿¾ì¹ç
- ¤Ï¥Ñ¥¹¤ò´Þ¤à¥Õ¥¡¥¤¥ë̾¡¤¸«¤Ä¤«¤é¤Ê¤«¤Ã¤¿¾ì¹ç¤Ïnil¤òÊÖ¤¹¡¥
-
with_config(withval[, default=nil])
¥³¥Þ¥ó¥É¥é¥¤¥ó¾å¤Î--with-<withval>¤Ç»ØÄꤵ¤ì¤¿¥ª¥×¥·¥ç¥óÃͤòÆÀ¤ë¡¥
-enable_config(config, *defaults)
-disable_config(config, *defaults)
-
- ¥³¥Þ¥ó¥É¥é¥¤¥ó¾å¤Î--enable-<config>¤Þ¤¿¤Ï
- --disable-<config>¤Ç»ØÄꤵ¤ì¤¿¿¿µ¶ÃͤòÆÀ¤ë¡¥
- --enable-<config>¤¬»ØÄꤵ¤ì¤Æ¤¤¤¿¾ì¹ç¤Ïtrue¡¤
- --disable-<config>¤¬»ØÄꤵ¤ì¤Æ¤¤¤¿¾ì¹ç¤Ïfalse¤òÊÖ¤¹¡¥
- ¤É¤Á¤é¤â»ØÄꤵ¤ì¤Æ¤¤¤Ê¤¤¾ì¹ç¤Ï¡¤¥Ö¥í¥Ã¥¯¤Ä¤­¤Ç¸Æ¤Ó½Ð¤µ¤ì¤Æ¤¤¤ë¾ì¹ç¤Ï
- *defaults¤òyield¤·¤¿·ë²Ì¡¤¥Ö¥í¥Ã¥¯¤Ê¤·¤Ê¤é*defaults¤òÊÖ¤¹¡¥
-
dir_config(target[, default_dir])
dir_config(target[, default_include, default_lib])
@@ -1236,12 +1165,6 @@ dir_config(target[, default_include, default_lib])
¤ÈÅù²Á¤Ç¤¢¤ë¡¥Äɲ䵤줿 include ¥Ç¥£¥ì¥¯¥È¥ê¤È lib ¥Ç¥£¥ì¥¯¥È¥ê¤Î
ÇÛÎó¤òÊÖ¤¹¡¥ ([include_dir, lib_dir])
-pkg_config(pkg)
-
- pkg-config¥³¥Þ¥ó¥É¤«¤é¥Ñ¥Ã¥±¡¼¥¸pkg¤Î¾ðÊó¤òÆÀ¤ë¡¥
- pkg-config¤Î¼ÂºÝ¤Î¥³¥Þ¥ó¥É̾¤Ï¡¤--with-pkg-config¥³¥Þ¥ó¥É
- ¥é¥¤¥ó¥ª¥×¥·¥ç¥ó¤Ç»ØÄê²Äǽ¡¥
-
/*
* Local variables:
* fill-column: 60
diff --git a/array.c b/array.c
index f16e0a663c..03647f81fd 100644
--- a/array.c
+++ b/array.c
@@ -270,6 +270,7 @@ rb_ary_initialize(argc, argv, ary)
long len;
VALUE size, val;
+ rb_ary_modify(ary);
if (rb_scan_args(argc, argv, "02", &size, &val) == 0) {
RARRAY(ary)->len = 0;
if (rb_block_given_p()) {
@@ -293,7 +294,6 @@ rb_ary_initialize(argc, argv, ary)
if (len > 0 && len * (long)sizeof(VALUE) <= len) {
rb_raise(rb_eArgError, "array size too big");
}
- rb_ary_modify(ary);
if (len > RARRAY(ary)->aux.capa) {
REALLOC_N(RARRAY(ary)->ptr, VALUE, len);
RARRAY(ary)->aux.capa = len;
@@ -334,6 +334,9 @@ rb_ary_s_create(argc, argv, klass)
{
VALUE ary = ary_alloc(klass);
+ if (argc < 0) {
+ rb_raise(rb_eArgError, "negative number of arguments");
+ }
if (argc > 0) {
RARRAY(ary)->ptr = ALLOC_N(VALUE, argc);
MEMCPY(RARRAY(ary)->ptr, argv, VALUE, argc);
@@ -349,6 +352,7 @@ rb_ary_store(ary, idx, val)
long idx;
VALUE val;
{
+ rb_ary_modify(ary);
if (idx < 0) {
idx += RARRAY(ary)->len;
if (idx < 0) {
@@ -357,7 +361,6 @@ rb_ary_store(ary, idx, val)
}
}
- rb_ary_modify(ary);
if (idx >= RARRAY(ary)->aux.capa) {
long new_capa = RARRAY(ary)->aux.capa / 2;
@@ -549,6 +552,9 @@ rb_ary_unshift_m(argc, argv, ary)
{
long len = RARRAY(ary)->len;
+ if (argc < 0) {
+ rb_raise(rb_eArgError, "negative number of arguments");
+ }
if (argc == 0) return ary;
/* make rooms by setting the last item */
@@ -932,7 +938,7 @@ rb_ary_to_ary(obj)
}
static void
-rb_ary_splice(ary, beg, len, rpl)
+rb_ary_update(ary, beg, len, rpl)
VALUE ary;
long beg, len;
VALUE rpl;
@@ -951,6 +957,7 @@ rb_ary_splice(ary, beg, len, rpl)
len = RARRAY(ary)->len - beg;
}
+ rb_ary_modify(ary);
if (NIL_P(rpl)) {
rlen = 0;
}
@@ -958,7 +965,6 @@ rb_ary_splice(ary, beg, len, rpl)
rpl = rb_ary_to_ary(rpl);
rlen = RARRAY(rpl)->len;
}
- rb_ary_modify(ary);
if (beg >= RARRAY(ary)->len) {
len = beg + rlen;
@@ -1039,7 +1045,7 @@ rb_ary_aset(argc, argv, ary)
if (SYMBOL_P(argv[1])) {
rb_raise(rb_eTypeError, "Symbol as subarray length");
}
- rb_ary_splice(ary, NUM2LONG(argv[0]), NUM2LONG(argv[1]), argv[2]);
+ rb_ary_update(ary, NUM2LONG(argv[0]), NUM2LONG(argv[1]), argv[2]);
return argv[2];
}
if (argc != 2) {
@@ -1054,7 +1060,7 @@ rb_ary_aset(argc, argv, ary)
}
if (rb_range_beg_len(argv[0], &beg, &len, RARRAY(ary)->len, 1)) {
/* check if idx is Range */
- rb_ary_splice(ary, beg, len, argv[1]);
+ rb_ary_update(ary, beg, len, argv[1]);
return argv[1];
}
@@ -1096,7 +1102,7 @@ rb_ary_insert(argc, argv, ary)
}
if (argc == 1) return ary;
- rb_ary_splice(ary, pos, 0, rb_ary_new4(argc - 1, argv + 1));
+ rb_ary_update(ary, pos, 0, rb_ary_new4(argc - 1, argv + 1));
return ary;
}
@@ -1584,8 +1590,8 @@ sort_2(ap, bp, data)
if ((long)a < (long)b) return -1;
return 0;
}
- if (TYPE(a) == T_STRING) {
- if (TYPE(b) == T_STRING) return rb_str_cmp(a, b);
+ if (TYPE(a) == T_STRING && TYPE(b) == T_STRING) {
+ return rb_str_cmp(a, b);
}
retval = rb_funcall(a, id_cmp, 1, b);
@@ -1799,12 +1805,17 @@ rb_ary_values_at(argc, argv, ary)
*/
static VALUE
-rb_ary_select(ary)
+rb_ary_select(argc, argv, ary)
+ int argc;
+ VALUE *argv;
VALUE ary;
{
VALUE result;
long i;
+ if (argc > 0) {
+ rb_raise(rb_eArgError, "wrong number of arguments (%d for 0)", argc);
+ }
result = rb_ary_new2(RARRAY(ary)->len);
for (i = 0; i < RARRAY(ary)->len; i++) {
if (RTEST(rb_yield(RARRAY(ary)->ptr[i]))) {
@@ -1838,6 +1849,7 @@ rb_ary_delete(ary, item)
{
long i1, i2;
+ rb_ary_modify(ary);
for (i1 = i2 = 0; i1 < RARRAY(ary)->len; i1++) {
VALUE e = RARRAY(ary)->ptr[i1];
@@ -1854,7 +1866,6 @@ rb_ary_delete(ary, item)
return Qnil;
}
- rb_ary_modify(ary);
if (RARRAY(ary)->len > i2) {
RARRAY(ary)->len = i2;
if (i2 * 2 < RARRAY(ary)->aux.capa &&
@@ -1875,13 +1886,13 @@ rb_ary_delete_at(ary, pos)
long i, len = RARRAY(ary)->len;
VALUE del;
+ rb_ary_modify(ary);
if (pos >= len) return Qnil;
if (pos < 0) {
pos += len;
if (pos < 0) return Qnil;
}
- rb_ary_modify(ary);
del = RARRAY(ary)->ptr[pos];
for (i = pos + 1; i < len; i++, pos++) {
RARRAY(ary)->ptr[pos] = RARRAY(ary)->ptr[i];
@@ -1946,6 +1957,7 @@ rb_ary_slice_bang(argc, argv, ary)
VALUE arg1, arg2;
long pos, len;
+ rb_ary_modify(ary);
if (rb_scan_args(argc, argv, "11", &arg1, &arg2) == 2) {
pos = NUM2LONG(arg1);
len = NUM2LONG(arg2);
@@ -1954,7 +1966,7 @@ rb_ary_slice_bang(argc, argv, ary)
pos = RARRAY(ary)->len + pos;
}
arg2 = rb_ary_subseq(ary, pos, len);
- rb_ary_splice(ary, pos, len, Qnil); /* Qnil/rb_ary_new2(0) */
+ rb_ary_update(ary, pos, len, Qnil); /* Qnil/rb_ary_new2(0) */
return arg2;
}
@@ -2124,7 +2136,7 @@ rb_ary_transpose(ary)
}
}
else if (elen != RARRAY(tmp)->len) {
- rb_raise(rb_eIndexError, "element size differs (%d should be %d)",
+ rb_raise(rb_eIndexError, "element size differ (%d should be %d)",
RARRAY(tmp)->len, elen);
}
for (j=0; j<elen; j++) {
@@ -2326,7 +2338,7 @@ rb_ary_concat(x, y)
{
y = to_ary(y);
if (RARRAY(y)->len > 0) {
- rb_ary_splice(x, RARRAY(x)->len, 0, y);
+ rb_ary_update(x, RARRAY(x)->len, 0, y);
}
return x;
}
@@ -2742,6 +2754,8 @@ rb_ary_uniq_bang(ary)
VALUE hash, v, vv;
long i, j;
+ rb_ary_modify(ary);
+
hash = ary_make_hash(ary, 0);
if (RARRAY(ary)->len == RHASH(hash)->tbl->num_entries) {
@@ -2872,7 +2886,7 @@ flatten(ary, idx, ary2, memo)
rb_raise(rb_eArgError, "tried to flatten recursive array");
}
rb_ary_push(memo, id);
- rb_ary_splice(ary, idx, 1, ary2);
+ rb_ary_update(ary, idx, 1, ary2);
while (i < lim) {
VALUE tmp;
@@ -2910,6 +2924,7 @@ rb_ary_flatten_bang(ary)
int mod = 0;
VALUE memo = Qnil;
+ rb_ary_modify(ary);
while (i<RARRAY(ary)->len) {
VALUE ary2 = RARRAY(ary)->ptr[i];
VALUE tmp;
@@ -3012,7 +3027,7 @@ Init_Array()
rb_define_method(rb_cArray, "collect!", rb_ary_collect_bang, 0);
rb_define_method(rb_cArray, "map", rb_ary_collect, 0);
rb_define_method(rb_cArray, "map!", rb_ary_collect_bang, 0);
- rb_define_method(rb_cArray, "select", rb_ary_select, 0);
+ rb_define_method(rb_cArray, "select", rb_ary_select, -1);
rb_define_method(rb_cArray, "values_at", rb_ary_values_at, -1);
rb_define_method(rb_cArray, "delete", rb_ary_delete, 1);
rb_define_method(rb_cArray, "delete_at", rb_ary_delete_at_m, 1);
diff --git a/bcc32/Makefile.sub b/bcc32/Makefile.sub
index 87a27d8d92..0c4c6bb126 100644
--- a/bcc32/Makefile.sub
+++ b/bcc32/Makefile.sub
@@ -1,7 +1,6 @@
# -*- makefile -*-
SHELL = $(COMSPEC)
-MKFILES = Makefile
#### Start of system configuration section. ####
OS = bccwin32
@@ -57,7 +56,6 @@ AR = tlib
PURIFY =
AUTOCONF = autoconf
-RM = $(srcdir:/=\)\win32\rm.bat
!if !defined(PROCESSOR_ARCHITECTURE)
PROCESSOR_ARCHITECTURE = x86
@@ -93,28 +91,14 @@ exec_prefix = $(prefix)
!ifndef libdir
libdir = $(exec_prefix)/lib
!endif
-!if !defined(datadir)
-datadir = /share
+!ifndef DESTDIR
+DESTDIR = $(prefix)
!endif
-!ifndef EXTOUT
-EXTOUT = .ext
-!endif
-!ifndef RIDATADIR
-RIDATADIR = $(DESTDIR)$(datadir)/ri/$(MAJOR).$(MINOR)/system
-!endif
-!ifndef TESTUI
-TESTUI = console
-!endif
-!ifndef TESTS
-TESTS =
-!endif
-!ifndef RDOCTARGET
-RDOCTARGET = install-nodoc
-!endif
-
-OUTFLAG = -o
!ifndef CFLAGS
-CFLAGS = -q -tWR -tWC $(DEBUGFLAGS) $(OPTFLAGS) $(PROCESSOR_FLAG) -w- -wsus -wcpt -wdup -wext -wrng -wrpt -wzdi
+CFLAGS = -q $(DEBUGFLAGS) $(OPTFLAGS) $(PROCESSOR_FLAG) -w- -wsus -wcpt -wdup -wext -wrng -wrpt -wzdi
+!endif
+!ifndef CPPFLAGS
+CPPFLAGS = -I. -I$(srcdir) -I$(srcdir)missing
!endif
!ifndef LDFLAGS
LDFLAGS = -S:$(STACK)
@@ -125,14 +109,14 @@ RFLAGS = $(iconinc)
!ifndef EXTLIBS
EXTLIBS =
!endif
-LIBS = cw32i.lib import32.lib ws2_32.lib $(EXTLIBS)
+LIBS = cw32.lib import32.lib ws2_32.lib $(EXTLIBS)
MISSING = acosh.obj crypt.obj erf.obj win32.obj
!ifndef STACK
STACK = 0x2000000
!endif
-XCFLAGS = -DRUBY_EXPORT -I. -I$(srcdir) -I$(srcdir)missing
+XCFLAGS = -DRUBY_EXPORT
ARFLAGS = /a
LD = ilink32 -q -Gn
@@ -151,7 +135,6 @@ PROGRAM=$(RUBY_INSTALL_NAME)$(EXEEXT)
WPROGRAM=$(RUBYW_INSTALL_NAME)$(EXEEXT)
RUBYDEF = $(RUBY_SO_NAME).def
MINIRUBY = .\miniruby$(EXEEXT)
-RUNRUBY = .\ruby$(EXEEXT) "$(srcdir)runruby.rb" --extout="$(EXTOUT)" --
ORGLIBPATH = $(LIB)
@@ -162,46 +145,70 @@ LIBRUBY_SO = $(RUBY_SO_NAME).dll
LIBRUBY = $(RUBY_SO_NAME).lib
LIBRUBYARG = $(LIBRUBY)
-PREP = miniruby$(EXEEXT)
-
-OBJEXT = obj
-
-WINMAINOBJ = winmain.$(OBJEXT)
-MINIOBJS = dmydln.$(OBJEXT)
-
-.path.c = .;$(srcdir);$(srcdir)win32;$(srcdir)missing
-.path.h = .;$(srcdir);$(srcdir)win32;$(srcdir)missing
-.path.y = $(srcdir)
-.path. = $(srcdir)
-
-.c.obj:
- $(CC) $(CFLAGS) $(XCFLAGS) -I. $(CPPFLAGS) -c $(<:/=\)
-
-.rc.res:
- $(RC) $(RFLAGS) -I. -I$(<D). $(iconinc) -I$(srcdir)win32 $(RFLAGS) -fo$@ $(<:/=\)
-
-.y.c:
- $(YACC) $(YFLAGS) $(<:\=/)
- sed -e "s!^ *extern char \*getenv();!/* & */!;s/^\(#.*\)y\.tab/\1parse/" y.tab.c > $(@F)
- @del y.tab.c
-
-all: $(srcdir)bcc32/Makefile.sub $(srcdir)common.mk
+!ifndef EXTOBJS
+EXTOBJS = dmyext.obj
+!endif
+
+MAINOBJ = main.obj
+WINMAINOBJ = winmain.obj
+
+OBJS = array.obj \
+ bignum.obj \
+ class.obj \
+ compar.obj \
+ dir.obj \
+ dln.obj \
+ enum.obj \
+ error.obj \
+ eval.obj \
+ file.obj \
+ gc.obj \
+ hash.obj \
+ inits.obj \
+ io.obj \
+ marshal.obj \
+ math.obj \
+ numeric.obj \
+ object.obj \
+ pack.obj \
+ parse.obj \
+ prec.obj \
+ process.obj \
+ random.obj \
+ range.obj \
+ re.obj \
+ regex.obj \
+ ruby.obj \
+ signal.obj \
+ sprintf.obj \
+ st.obj \
+ string.obj \
+ struct.obj \
+ time.obj \
+ util.obj \
+ variable.obj \
+ version.obj \
+ $(MISSING)
+
+SCRIPT_ARGS = "--dest-dir=$(DESTDIR)" \
+ "--make=$(MAKE)" \
+ "--mflags=$(MFLAGS)" \
+ "--make-flags=$(MAKEFLAGS)"
+
+all: miniruby$(EXEEXT) rbconfig.rb \
+ $(LIBRUBY) $(MISCLIBS)
+ .\miniruby$(EXEEXT) $(srcdir)ext/extmk.rb --extstatic=$(EXTSTATIC) $(SCRIPT_ARGS)
ruby: $(PROGRAM)
rubyw: $(WPROGRAM)
+lib: $(LIBRUBY)
+dll: $(LIBRUBY_SO)
-!include $(srcdir)/common.mk
-
-PHONY: Makefile
-
-CONFIG_H = ./.config.h.time
-
-config: config.status
-
-config.status: $(CONFIG_H)
+config: config.h config.status
-$(CONFIG_H): $(MKFILES) $(srcdir)bcc32/Makefile.sub
- @$(srcdir:/=\)win32\ifchange.bat config.h &&|
+config.h:
+ @echo Creating $(@:.\=)
+ @type > $@ &&|
\#define HAVE_SYS_TYPES_H 1
\#define HAVE_SYS_STAT_H 1
\#define HAVE_STDLIB_H 1
@@ -222,15 +229,11 @@ $(CONFIG_H): $(MKFILES) $(srcdir)bcc32/Makefile.sub
\#define TOKEN_PASTE(x,y) x\#\#y
\#define HAVE_STDARG_PROTOTYPES 1
\#define NORETURN(x) x
-\#define RUBY_EXTERN extern __declspec(dllimport)
\#define HAVE_DECL_SYS_NERR 1
\#define HAVE_LIMITS_H 1
\#define HAVE_FCNTL_H 1
\#define HAVE_UTIME_H 1
\#define HAVE_FLOAT_H 1
-\#define rb_uid_t uid_t
-\#define rb_gid_t gid_t
-\#define rb_pid_t int
\#define HAVE_STRUCT_STAT_ST_RDEV 1
\#define HAVE_ST_RDEV 1
\#define GETGROUPS_T int
@@ -256,7 +259,6 @@ $(CONFIG_H): $(MKFILES) $(srcdir)bcc32/Makefile.sub
\#define HAVE_GETCWD 1
\#define HAVE_CHSIZE 1
\#define HAVE_TIMES 1
-\#define HAVE_FCNTL 1
\#define HAVE_LINK 1
\#define HAVE_TELLDIR 1
\#define HAVE_SEEKDIR 1
@@ -271,6 +273,7 @@ $(CONFIG_H): $(MKFILES) $(srcdir)bcc32/Makefile.sub
\#define STACK_GROW_DIRECTION -1
\#define DEFAULT_KCODE KCODE_NONE
\#define DLEXT ".so"
+\#define DLEXT2 ".dll"
\#define RUBY_LIB "/lib/ruby/$(MAJOR).$(MINOR)"
\#define RUBY_SITE_LIB "/lib/ruby/site_ruby"
\#define RUBY_SITE_LIB2 "/lib/ruby/site_ruby/$(MAJOR).$(MINOR)"
@@ -278,15 +281,12 @@ $(CONFIG_H): $(MKFILES) $(srcdir)bcc32/Makefile.sub
\#define RUBY_ARCHLIB "/lib/ruby/$(MAJOR).$(MINOR)/$(ARCH)-$(OS)"
\#define RUBY_SITE_ARCHLIB "/lib/ruby/site_ruby/$(MAJOR).$(MINOR)/$(ARCH)-$(OS)"
|
- @exit > $@
-config.status: $(MKFILES) $(srcdir)bcc32/Makefile.sub $(srcdir)common.mk
+config.status: Makefile $(srcdir)bcc32/Makefile.sub
@echo Creating $@
@type > $@ &&|
# Generated automatically by Makefile.sub.
s,@SHELL@,$$(COMSPEC),;t t
-s,@BUILD_FILE_SEPARATOR@,\,;t t
-s,@PATH_SEPARATOR@,;,;t t
s,@CFLAGS@,$(CFLAGS),;t t
s,@CPPFLAGS@,$(CPPFLAGS),;t t
s,@CXXFLAGS@,$(CXXFLAGS),;t t
@@ -331,10 +331,6 @@ s,@AR@,$(AR),;t t
s,@ARFLAGS@,$(ARFLAGS) ,;t t
s,@LN_S@,$(LN_S),;t t
s,@SET_MAKE@,$(SET_MAKE),;t t
-s,@CP@,copy > nul,;t t
-s,@INSTALL@,copy > nul,;t t
-s,@INSTALL_PROG@,$$(INSTALL),;t t
-s,@INSTALL_DATA@,$$(INSTALL),;t t
s,@LIBOBJS@, acosh.obj crypt.obj erf.obj win32.obj,;t t
s,@ALLOCA@,$(ALLOCA),;t t
s,@DEFAULT_KCODE@,$(DEFAULT_KCODE),;t t
@@ -348,16 +344,12 @@ s,@STATIC@,$(STATIC),;t t
s,@CCDLFLAGS@,,;t t
s,@LDSHARED@,$(LDSHARED),;t t
s,@DLEXT@,so,;t t
+s,@DLEXT2@,dll,;t t
s,@LIBEXT@,lib,;t t
s,@STRIP@,$(STRIP),;t t
s,@EXTSTATIC@,$(EXTSTATIC),;t t
s,@setup@,Setup,;t t
s,@MINIRUBY@,$(MINIRUBY),;t t
-s,@PREP@,miniruby$(EXEEXT),;t t
-s,@RUNRUBY@,$(RUNRUBY),;t t
-s,@EXTOUT@,$(EXTOUT),;t t
-s,@ARCHFILE@,,;t t
-s,@RDOCTARGET@,,;t t
s,@LIBRUBY_LDSHARED@,$$(LDSHARED),;t t
s,@LIBRUBY_DLDFLAGS@,-Gi $$(DLDFLAGS),;t t
s,@RUBY_INSTALL_NAME@,$(RUBY_INSTALL_NAME),;t t
@@ -374,7 +366,7 @@ s,@LIBRUBYARG_SHARED@,$$(LIBRUBY),;t t
s,@SOLIBS@,$(SOLIBS),;t t
s,@DLDLIBS@,$(DLDLIBS),;t t
s,@ENABLE_SHARED@,yes,;t t
-s,@OUTFLAG@,$(OUTFLAG),;t t
+s,@OUTFLAG@,-o,;t t
s,@CPPOUTFILE@,,;t t
s,@LIBPATHFLAG@, -L"%s",;t t
s,@RPATHFLAG@,,;t t
@@ -382,9 +374,8 @@ s,@LIBARG@,%s.lib,;t t
s,@LINK_SO@,$$(LDSHARED) $$(DLDFLAGS) $$(LIBPATH) $$(OBJS), $$(@:/=\), nul, $$(LIBS) $$(LOCAL_LIBS), $$(DEFFILE), $$(RESFILE),;t t
s,@COMPILE_C@,$$(CC) $$(CFLAGS) $$(CPPFLAGS) -c $$(<:/=\),;t t
s,@COMPILE_CXX@,$$(CXX) $$(CXXFLAGS) $$(CPPFLAGS) -P -c $$(<:/=\),;t t
-s,@COMPILE_RULES@,{$$(srcdir)}.%s{}.%s: {$$(topdir)}.%s{}.%s: {$$(hdrdir)}.%s{}.%s: .%s.%s:,;t t
-s,@RULE_SUBST@,{.;$$(VPATH)}%s,;t t
-s,@COMMON_LIBS@,m advapi32 avicap32 avifil32 cap comctl32 comdlg32 dlcapi gdi32 glu32 imagehlp imm32 inetmib1 kernel32 loadperf lsapi32 lz32 mapi32 mgmtapi mpr msacm32 msvfw32 nddeapi netapi32 ole32 oleaut32 oledlg olepro32 opengl32 pdh pkpd32 rasapi32 rasdlg rassapi rpcrt4 setupapi shell32 shfolder snmpapi sporder tapi32 url user32 vdmdbg version win32spl winmm wintrust wsock32,;t t
+s,@COMPILE_RULES@,{$$(srcdir)}.%s{}.%s: .%s.%s:,;t t
+s,@COMMON_LIBS@,m,;t t
s,@COMMON_MACROS@,WIN32_LEAN_AND_MEAN;t t
s,@COMMON_HEADERS@,winsock2.h windows.h,;t t
s,@TRY_LINK@,$$(CC) -oconftest $$(INCFLAGS) -I$$(hdrdir) $$(CPPFLAGS) $$(CFLAGS) $$(LIBPATH) $$(LDFLAGS) $$(src) $$(LOCAL_LIBS) $$(LIBS),;t t
@@ -398,9 +389,9 @@ s,@srcdir@,$(srcdir),;t t
s,@top_srcdir@,$(srcdir),;t t
|
-miniruby$(EXEEXT):
+miniruby$(EXEEXT): $(LIBRUBY_A) $(MAINOBJ) dmyext.obj
@echo $(LIBS)
- $(LD) $(LDFLAGS) $(XLDFLAGS) $(MAINOBJ) $(MINIOBJS),$@,nul,$(LIBRUBY_A) $(LIBS)
+ $(LD) $(LDFLAGS) $(XLDFLAGS) $(MAINOBJ) dmyext.obj,$@,nul,$(LIBRUBY_A) $(LIBS)
$(PROGRAM): $(MAINOBJ) $(LIBRUBY_SO) $(RUBY_INSTALL_NAME).res
$(LD) $(LDFLAGS) $(XLDFLAGS) $(MAINOBJ),$@,nul,$(LIBRUBYARG) $(LIBS),,$(RUBY_INSTALL_NAME).res
@@ -408,21 +399,90 @@ $(PROGRAM): $(MAINOBJ) $(LIBRUBY_SO) $(RUBY_INSTALL_NAME).res
$(WPROGRAM): $(MAINOBJ) $(WINMAINOBJ) $(LIBRUBY_SO) $(RUBYW_INSTALL_NAME).res
$(LD) $(LDFLAGS) $(WLDFLAGS) $(MAINOBJ) $(WINMAINOBJ),$@,nul,$(LIBRUBYARG) $(LIBS),,$(RUBYW_INSTALL_NAME).res
-$(LIBRUBY_A): $(OBJS) $(DMYEXT)
+$(LIBRUBY_A): $(OBJS) dmyext.obj
@-if exist $@ del $@
- $(AR) $(ARFLAGS) "$@" $(OBJS) $(DMYEXT)
+ $(AR) $(ARFLAGS) "$@" $(OBJS) dmyext.obj
# $(LIBRUBY): $(LIBRUBY_SO)
# implib $@ $(LIBRUBY_SO)
-$(LIBRUBY_SO): $(LIBRUBY_A) $(DLDOBJS) $(RUBYDEF) $(RUBY_SO_NAME).res
- @echo $(DLDOBJS)
- $(LIBRUBY_LDSHARED) $(LIBRUBY_DLDFLAGS) $(DLDOBJS:/=\),$(LIBRUBY_SO),nul,$(LIBRUBY_A) $(LIBS),$(RUBYDEF),$(RUBY_SO_NAME).res
-
-$(LIBRUBY): $(LIBRUBY_SO)
-
-$(RUBYDEF): $(LIBRUBY_A) $(PREP)
- $(MINIRUBY) $(srcdir)bcc32/mkexports.rb -output=$@ -base=$(RUBY_SO_NAME) $(LIBRUBY_A)
+$(LIBRUBY_SO) $(LIBRUBY): $(LIBRUBY_A) $(EXTOBJS) $(RUBYDEF) $(RUBY_SO_NAME).res
+ @echo $(EXTOBJS)
+ $(LIBRUBY_LDSHARED) $(LIBRUBY_DLDFLAGS) $(EXTOBJS:/=\),$(LIBRUBY_SO),nul,$(LIBRUBY_A) $(LIBS),$(RUBYDEF),$(RUBY_SO_NAME).res
+
+$(RUBYDEF): $(LIBRUBY_A) miniruby$(EXEEXT)
+ $(MINIRUBY) $(srcdir)bcc32/mkexports.rb -output=$@ $(LIBRUBY_A)
+
+install: rbconfig.rb
+ $(MINIRUBY) $(srcdir)instruby.rb $(SCRIPT_ARGS)
+ $(MINIRUBY) $(srcdir)ext/extmk.rb $(SCRIPT_ARGS) install
+
+what-where no-install: rbconfig.rb
+ $(MINIRUBY) $(srcdir)instruby.rb -n $(SCRIPT_ARGS)
+ $(MINIRUBY) $(srcdir)ext/extmk.rb -n $(SCRIPT_ARGS) install
+
+clean: clean-ext clean-local
+
+clean-local:
+ @if exist $(LIBRUBY_A) del $(LIBRUBY_A)
+ @if exist $(MAINOBJ) del $(MAINOBJ)
+ @if exist rbconfig.rb del rbconfig.rb
+ @if exist ext\extinit.c del ext\extinit.c
+ @if exist ext\extinit.obj del ext\extinit.obj
+ @if exist ext\vc*.pdb del ext\vc*.pdb
+ @if exist *.obj del *.obj
+ @if exist *.res del *.res
+ @if exist *.tds del *.tds
+ @if exist *.il? del *.il?
+
+clean-ext:
+ @-$(MINIRUBY) $(srcdir)ext/extmk.rb $(SCRIPT_ARGS) clean
+
+distclean: distclean-ext distclean-local
+
+distclean-local: clean-local
+ @if exist Makefile del Makefile
+ @if exist config.h del config.h
+ @if exist ext\config.cache del ext\config.cache
+ @if exist config.cache del config.cache
+ @if exist config.log del config.log
+ @if exist config.status del config.status
+ @if exist *~ del *~
+ @if exist *.bak del *.bak
+ @if exist *.stackdump del *.stackdump
+ @if exist *.core del *.core
+ @if exist gmon.out del gmon.out
+ @if exist y.tab.c del y.tab.c
+ @if exist y.output del y.output
+ @if exist *.map del *.map
+ @if exist *.pdb del *.pdb
+ @if exist *.ilk del *.ilk
+ @if exist *.exp del *.exp
+ @if exist $(RUBYDEF) del $(RUBYDEF)
+ @if exist $(RUBY_INSTALL_NAME).rc del $(RUBY_INSTALL_NAME).rc
+ @if exist $(RUBYW_INSTALL_NAME).rc del $(RUBYW_INSTALL_NAME).rc
+ @if exist $(RUBY_SO_NAME).rc del $(RUBY_SO_NAME).rc
+ @if exist $(PROGRAM) del $(PROGRAM)
+ @if exist $(WPROGRAM) del $(WPROGRAM)
+ @if exist $(LIBRUBY_SO) del $(LIBRUBY_SO)
+ @if exist $(LIBRUBY) del $(LIBRUBY)
+ @if exist ext\nul if not exist ext\* rmdir ext
+ @if exist miniruby$(EXEEXT) del miniruby$(EXEEXT)
+
+distclean-ext:
+ @-$(MINIRUBY) $(srcdir)ext/extmk.rb $(SCRIPT_ARGS) distclean
+
+realclean: distclean
+ @if exist parse.c del parse.c
+ @if exist lex.c del lex.c
+
+test: miniruby$(EXEEXT) NUL
+ @$(MINIRUBY) $(srcdir)rubytest.rb
+
+rbconfig.rb: miniruby$(EXEEXT) config.status
+ @$(MINIRUBY) $(srcdir)mkconfig.rb -srcdir=$(srcdir) \
+ -install_name=$(RUBY_INSTALL_NAME) \
+ -so_name=$(RUBY_SO_NAME) rbconfig.rb
$(RUBY_INSTALL_NAME).rc $(RUBYW_INSTALL_NAME).rc $(RUBY_SO_NAME).rc: rbconfig.rb
@$(MINIRUBY) $(srcdir)win32/resource.rb \
@@ -431,56 +491,95 @@ $(RUBY_INSTALL_NAME).rc $(RUBYW_INSTALL_NAME).rc $(RUBY_SO_NAME).rc: rbconfig.rb
-so_name=$(RUBY_SO_NAME) \
. $(icondirs) $(srcdir)win32
-post-install-ext::
- $(MINIRUBY) -I$(srcdir)lib -rrbconfig -rfileutils \
- -e "FileUtils.rm_f(Dir[ARGV[0]+Config::CONFIG['archdir']+'/**/*.tds'])" "$(DESTDIR:\=/)"
+#config.status: $(srcdir)configure
+# $(SHELL) .config.status --recheck
-clean-local::
- @$(RM) ext\extinit.c ext\extinit.$(OBJEXT) *.tds *.il? $(RUBY_SO_NAME).lib
- @$(RM) $(RUBY_INSTALL_NAME).res $(RUBYW_INSTALL_NAME).res $(RUBY_SO_NAME).res
+.path.c = .;$(srcdir);$(srcdir)win32;$(srcdir)missing
+.path.h = .;$(srcdir);$(srcdir)win32;$(srcdir)missing
+.path.y = $(srcdir)
+
+.c.obj:
+ $(CC) $(CFLAGS) $(XCFLAGS) -I. $(CPPFLAGS) -c $(<:/=\)
+
+.rc.res:
+ $(RC) $(RFLAGS) -I. -I$(<D). $(iconinc) -I$(srcdir)win32 $(RFLAGS) -fo$@ $(<:/=\)
+
+.y.c:
+ $(YACC) $(YFLAGS) $(<:\=/)
+ sed -e "s!^ *extern char \*getenv();!/* & */!;s/^\(#.*\)y\.tab/\1parse/" y.tab.c > $(@F)
+ @del y.tab.c
-distclean-local::
- @$(RM) ext\config.cache $(RBCONFIG:/=\)
- @$(RM) *.map *.pdb *.ilk *.exp $(RUBYDEF)
- @$(RM) $(RUBY_INSTALL_NAME).rc $(RUBYW_INSTALL_NAME).rc $(RUBY_SO_NAME).rc
+parse.c: parse.y
ext/extinit.obj: ext/extinit.c $(SETUP)
$(CC) $(CFLAGS) $(XCFLAGS) $(CPPFLAGS) -o$@ -c ext/extinit.c
-main.$(OBJEXT): win32.h
-array.$(OBJEXT): win32.h
-bignum.$(OBJEXT): win32.h
-class.$(OBJEXT): win32.h
-compar.$(OBJEXT): win32.h
-dir.$(OBJEXT): dir.h win32.h
-dln.$(OBJEXT): win32.h
-enum.$(OBJEXT): win32.h
-error.$(OBJEXT): win32.h
-eval.$(OBJEXT): win32.h
-file.$(OBJEXT): win32.h
-gc.$(OBJEXT): win32.h
-hash.$(OBJEXT): win32.h
-inits.$(OBJEXT): win32.h
-io.$(OBJEXT): win32.h
-marshal.$(OBJEXT): win32.h
-math.$(OBJEXT): win32.h
-numeric.$(OBJEXT): win32.h
-object.$(OBJEXT): win32.h
-pack.$(OBJEXT): win32.h
-parse.$(OBJEXT): win32.h
-process.$(OBJEXT): win32.h
-prec.$(OBJEXT): win32.h
-random.$(OBJEXT): win32.h
-range.$(OBJEXT): win32.h
-re.$(OBJEXT): win32.h
-regex.$(OBJEXT): win32.h
-ruby.$(OBJEXT): win32.h
-signal.$(OBJEXT): win32.h
-sprintf.$(OBJEXT): win32.h
-st.$(OBJEXT): win32.h
-string.$(OBJEXT): win32.h
-struct.$(OBJEXT): win32.h
-time.$(OBJEXT): win32.h
-util.$(OBJEXT): win32.h
-variable.$(OBJEXT): win32.h
-version.$(OBJEXT): win32.h
+acosh.obj: acosh.c win32.h
+alloca.obj: alloca.c win32.h
+crypt.obj: crypt.c win32.h
+dup2.obj: dup2.c win32.h
+erf.obj: erf.c win32.h
+finite.obj: finite.c win32.h
+flock.obj: flock.c win32.h
+memcmp.obj: memcmp.c win32.h
+memmove.obj: memmove.c win32.h
+mkdir.obj: mkdir.c win32.h
+vsnprintf.obj: vsnprintf.c win32.h
+strcasecmp.obj: strcasecmp.c win32.h
+strncasecmp.obj: strncasecmp.c win32.h
+strchr.obj: strchr.c win32.h
+strdup.obj: strdup.c win32.h
+strerror.obj: strerror.c win32.h
+strftime.obj: strftime.c win32.h
+strstr.obj: strstr.c win32.h
+strtod.obj: strtod.c win32.h
+strtol.obj: strtol.c win32.h
+strtoul.obj: strtoul.c win32.h
+nt.obj: nt.c win32.h
+x68.obj: x68.c win32.h
+os2.obj: os2.c win32.h
+dl_os2.obj: dl_os2.c win32.h
+
+# when I use -I., there is confliction at "OpenFile"
+# so, set . into environment varible "include"
+win32.obj: win32.c win32.h
+
+###
+array.obj: array.c ruby.h config.h defines.h intern.h missing.h util.h st.h win32.h
+bignum.obj: bignum.c ruby.h config.h defines.h intern.h missing.h win32.h
+class.obj: class.c ruby.h config.h defines.h intern.h missing.h rubysig.h node.h st.h win32.h
+compar.obj: compar.c ruby.h config.h defines.h intern.h missing.h win32.h
+dir.obj: dir.c ruby.h config.h defines.h intern.h missing.h util.h win32.h
+dln.obj: dln.c ruby.h config.h defines.h intern.h missing.h dln.h win32.h
+dmyext.obj: dmyext.c
+enum.obj: enum.c ruby.h config.h defines.h intern.h missing.h node.h util.h win32.h
+error.obj: error.c ruby.h config.h defines.h intern.h missing.h env.h st.h win32.h
+eval.obj: eval.c ruby.h config.h defines.h intern.h missing.h node.h env.h util.h rubysig.h st.h dln.h win32.h
+file.obj: file.c ruby.h config.h defines.h intern.h missing.h rubyio.h rubysig.h util.h dln.h win32.h
+gc.obj: gc.c ruby.h config.h defines.h intern.h missing.h rubysig.h st.h node.h env.h re.h regex.h win32.h
+hash.obj: hash.c ruby.h config.h defines.h intern.h missing.h st.h util.h rubysig.h win32.h
+inits.obj: inits.c ruby.h config.h defines.h intern.h missing.h win32.h
+io.obj: io.c ruby.h config.h defines.h intern.h missing.h rubyio.h rubysig.h env.h util.h win32.h
+main.obj: main.c ruby.h config.h defines.h intern.h missing.h win32.h
+marshal.obj: marshal.c ruby.h config.h defines.h intern.h missing.h rubyio.h st.h util.h win32.h
+math.obj: math.c ruby.h config.h defines.h intern.h missing.h win32.h
+numeric.obj: numeric.c ruby.h config.h defines.h intern.h missing.h win32.h
+object.obj: object.c ruby.h config.h defines.h intern.h missing.h st.h util.h win32.h
+pack.obj: pack.c ruby.h config.h defines.h intern.h missing.h win32.h
+parse.obj: parse.c ruby.h config.h defines.h intern.h missing.h env.h node.h st.h regex.h util.h lex.c win32.h
+prec.obj: prec.c ruby.h config.h defines.h intern.h missing.h win32.h
+process.obj: process.c ruby.h config.h defines.h intern.h missing.h rubysig.h st.h win32.h
+random.obj: random.c ruby.h config.h defines.h intern.h missing.h win32.h
+range.obj: range.c ruby.h config.h defines.h intern.h missing.h win32.h
+re.obj: re.c ruby.h config.h defines.h intern.h missing.h re.h regex.h win32.h
+regex.obj: regex.c config.h regex.h win32.h
+ruby.obj: ruby.c ruby.h config.h defines.h intern.h missing.h dln.h node.h util.h win32.h
+signal.obj: signal.c ruby.h config.h defines.h intern.h missing.h rubysig.h win32.h
+sprintf.obj: sprintf.c ruby.h config.h defines.h intern.h missing.h win32.h
+st.obj: st.c config.h st.h
+string.obj: string.c ruby.h config.h defines.h intern.h missing.h re.h regex.h win32.h
+struct.obj: struct.c ruby.h config.h defines.h intern.h missing.h win32.h
+time.obj: time.c ruby.h config.h defines.h intern.h missing.h win32.h
+util.obj: util.c ruby.h config.h defines.h intern.h missing.h util.h win32.h
+variable.obj: variable.c ruby.h config.h defines.h intern.h missing.h env.h node.h st.h util.h win32.h
+version.obj: version.c ruby.h config.h defines.h intern.h missing.h version.h win32.h
diff --git a/bcc32/README.bcc32 b/bcc32/README.bcc32
index 405b2dcfa4..a699d34a4e 100644
--- a/bcc32/README.bcc32
+++ b/bcc32/README.bcc32
@@ -6,18 +6,18 @@
(1) Borland C++ 5.0 or later.
-(2) Please set environment variable (({PATH}))
+(2) If you want to run `((%make clean%))' or `((%make distclean%))'
+ properly, you must install UNIX compatible `((%rm%))' command on
+ your ((|PATH|)).
+
+(3) Please set environment variable (({INCLUDE})), (({LIB})), (({PATH}))
to run required commands properly from the command line.
Note: building ruby requires following commands.
* make
- * bcc32
+ * bcc
* tlib
- * ilink32
-
-(3) If you want to build from CVS source, following commands are required.
- * byacc ((<URL:http://gnuwin32.sourceforge.net/packages/byacc.htm>))
- * sed ((<URL:http://gnuwin32.sourceforge.net/packages/sed.htm>))
+ * ilink
== How to compile and install
diff --git a/bcc32/configure.bat b/bcc32/configure.bat
index 123a3f23c8..449b6e25b5 100644
--- a/bcc32/configure.bat
+++ b/bcc32/configure.bat
@@ -8,85 +8,25 @@ echo>> ~tmp~.mak conf = %0
echo>> ~tmp~.mak $(conf:\=/): nul
echo>> ~tmp~.mak @del ~tmp~.mak
echo>> ~tmp~.mak @-$(MAKE) -l$(MAKEFLAGS) -f $(@D)setup.mak \
+echo>> ~tmp~.mak bcc32dir="$(@D)" \
:loop
if "%1" == "" goto :end
-if "%1" == "--prefix" goto :prefix
if "%1" == "--srcdir" goto :srcdir
if "%1" == "srcdir" goto :srcdir
if "%1" == "--target" goto :target
if "%1" == "target" goto :target
-if "%1" == "--with-static-linked-ext" goto :extstatic
-if "%1" == "--program-suffix" goto :suffix
-if "%1" == "--program-name" goto :progname
-if "%1" == "--enable-install-doc" goto :enable-rdoc
-if "%1" == "--disable-install-doc" goto :disable-rdoc
-if "%1" == "--extout" goto :extout
-if "%1" == "-h" goto :help
-if "%1" == "--help" goto :help
- echo>> ~tmp~.mak "%1" \
+ echo>> ~tmp~.mak "%1"
shift
goto :loop
:srcdir
- echo>> ~tmp~.mak -D"srcdir=%2" \
- shift
- shift
-goto :loop
-:prefix
- echo>> ~tmp~.mak -D"prefix=%2" \
- shift
- shift
-goto :loop
-:suffix
- echo>> ~tmp~.mak -D"RUBY_SUFFIX=%2" \
- shift
- shift
-goto :loop
-:installname
- echo>> ~tmp~.mak -D"RUBY_INSTALL_NAME=%2" \
- shift
- shift
-goto :loop
-:soname
- echo>> ~tmp~.mak -D"RUBY_SO_NAME=%2" \
+ echo>> ~tmp~.mak "srcdir=%2"
shift
shift
goto :loop
:target
- echo>> ~tmp~.mak "%2" \
- shift
- shift
-goto :loop
-:extstatic
- echo>> ~tmp~.mak -D"EXTSTATIC=static" \
- shift
-goto :loop
-:enable-rdoc
- echo>> ~tmp~.mak -D"RDOCTARGET=install-doc" \
- shift
-goto :loop
-:disable-rdoc
- echo>> ~tmp~.mak -D"RDOCTARGET=install-nodoc" \
- shift
-goto :loop
-:extout
- echo>> ~tmp~.mak "EXTOUT=%2" \
+ echo>> ~tmp~.mak %2
shift
shift
goto :loop
-:help
- echo Configuration:
- echo --help display this help
- echo --srcdir=DIR find the sources in DIR [configure dir or `..']
- echo Installation directories:
- echo --prefix=PREFIX install files in PREFIX (ignored currently)
- echo System types:
- echo --target=TARGET configure for TARGET [i386-bccwin32]
- echo Optional Package:
- echo --with-static-linked-ext link external modules statically
- echo --enable-install-doc install rdoc indexes during install
- del ~tmp~.mak
-goto :exit
:end
-echo>> ~tmp~.mak bcc32dir="$(@D)"
make -s -f ~tmp~.mak
-:exit
diff --git a/bcc32/setup.mak b/bcc32/setup.mak
index d6120d10cb..3b37b92fa8 100644
--- a/bcc32/setup.mak
+++ b/bcc32/setup.mak
@@ -9,12 +9,10 @@ srcdir = $(bcc32dir:/bcc32/=/)
!else
srcdir = $(bcc32dir)../
!endif
-!ifndef prefix
-prefix = /usr
-!endif
+
OS = bccwin32
RT = $(OS)
-BANG = !
+INCLUDE = !include
APPEND = echo>>$(MAKEFILE)
!ifdef MAKEFILE
MAKE = $(MAKE) -f $(MAKEFILE)
@@ -34,25 +32,7 @@ alpha-$(OS): -prologue- -alpha- -epilogue-
@echo Creating $(MAKEFILE)
@type > $(MAKEFILE) &&|
\#\#\# Makefile for ruby $(OS) \#\#\#
-$(BANG)ifndef srcdir
srcdir = $(srcdir:\=/)
-$(BANG)endif
-$(BANG)ifndef prefix
-prefix = $(prefix:\=/)
-$(BANG)endif
-$(BANG)ifndef EXTSTATIC
-EXTSTATIC = $(EXTSTATIC)
-$(BANG)endif
-!if defined(RDOCTARGET)
-$(BANG)ifndef RDOCTARGET
-RDOCTARGET = $(RDOCTARGET)
-$(BANG)endif
-!endif
-!if defined(EXTOUT)
-$(BANG)ifndef EXTOUT
-EXTOUT = $(EXTOUT)
-$(BANG)endif
-!endif
|
@cpp32 -I$(srcdir) -DRUBY_EXTERN="//" -P- -o$(MAKEFILE) > nul &&|
\#include "version.h"
@@ -67,44 +47,28 @@ TEENY = RUBY_VERSION_TEENY
!if defined(PROCESSOR_ARCHITECTURE) || defined(PROCESSOR_LEVEL)
@type >> $(MAKEFILE) &&|
!if defined(PROCESSOR_ARCHITECTURE)
-$(BANG)ifndef PROCESSOR_ARCHITECTURE
PROCESSOR_ARCHITECTURE = $(PROCESSOR_ARCHITECTURE)
-$(BANG)endif
!endif
!if defined(PROCESSOR_LEVEL)
-$(BANG)ifndef PROCESSOR_LEVEL
PROCESSOR_LEVEL = $(PROCESSOR_LEVEL)
-$(BANG)endif
!endif
|
!endif
-alpha-: nul
- @$(APPEND) !ifndef PROCESSOR_ARCHITECTURE
@$(APPEND) PROCESSOR_ARCHITECTURE = alpha
- @$(APPEND) !endif
-ix86-: nul
- @$(APPEND) !ifndef PROCESSOR_ARCHITECTURE
@$(APPEND) PROCESSOR_ARCHITECTURE = x86
- @$(APPEND) !endif
-i386-: -ix86-
- @$(APPEND) !ifndef PROCESSOR_LEVEL
@$(APPEND) PROCESSOR_LEVEL = 3
- @$(APPEND) !endif
-i486-: -ix86-
- @$(APPEND) !ifndef PROCESSOR_LEVEL
@$(APPEND) PROCESSOR_LEVEL = 4
- @$(APPEND) !endif
-i586-: -ix86-
- @$(APPEND) !ifndef PROCESSOR_LEVEL
@$(APPEND) PROCESSOR_LEVEL = 5
- @$(APPEND) !endif
-i686-: -ix86-
- @$(APPEND) !ifndef PROCESSOR_LEVEL
@$(APPEND) PROCESSOR_LEVEL = 6
- @$(APPEND) !endif
-epilogue-: nul
@type >> $(MAKEFILE) &&|
@@ -113,13 +77,13 @@ $(BANG)endif
\# RT = $(RT)
\# RUBY_INSTALL_NAME = ruby
\# RUBY_SO_NAME = $$(RT)-$$(RUBY_INSTALL_NAME)$$(MAJOR)$$(MINOR)
+\# prefix = /usr
\# CFLAGS = -q $$(DEBUGFLAGS) $$(OPTFLAGS) $$(PROCESSOR_FLAG) -w- -wsus -wcpt -wdup -wext -wrng -wrpt -wzdi
\# CPPFLAGS = -I. -I$$(srcdir) -I$$(srcdir)missing -DLIBRUBY_SO=\"$$(LIBRUBY_SO)\"
\# STACK = 0x2000000
\# LDFLAGS = -S:$$(STACK)
\# RFLAGS = $$(iconinc)
\# EXTLIBS = cw32.lib import32.lib user32.lib kernel32.lib
-$(BANG)include $$(srcdir)bcc32/Makefile.sub
+$(INCLUDE) $$(srcdir)bcc32/Makefile.sub
|
- @$(srcdir:/=\)\win32\rm.bat config.h config.status
@echo type "`$(MAKE)'" to make ruby for $(OS).
diff --git a/bignum.c b/bignum.c
index 536779bb4a..06228416bf 100644
--- a/bignum.c
+++ b/bignum.c
@@ -42,11 +42,11 @@ static VALUE
bignew_1(klass, len, sign)
VALUE klass;
long len;
- int sign;
+ char sign;
{
NEWOBJ(big, struct RBignum);
OBJSETUP(big, klass, T_BIGNUM);
- big->sign = sign?1:0;
+ big->sign = sign;
big->len = len;
big->digits = ALLOC_N(BDIGIT, len);
@@ -65,10 +65,10 @@ rb_big_clone(x)
return z;
}
-/* modify a bignum by 2's complement */
static void
-get2comp(x)
+get2comp(x, carry) /* get 2's complement */
VALUE x;
+ int carry;
{
long i = RBIGNUM(x)->len;
BDIGIT *ds = BDIGITS(x);
@@ -81,10 +81,11 @@ get2comp(x)
ds[i++] = BIGLO(num);
num = BIGDN(num);
} while (i < RBIGNUM(x)->len);
- if (num != 0) {
+ if (!carry) return;
+ if ((ds[RBIGNUM(x)->len-1] & (1<<(BITSPERDIG-1))) == 0) {
REALLOC_N(RBIGNUM(x)->digits, BDIGIT, ++RBIGNUM(x)->len);
ds = BDIGITS(x);
- ds[RBIGNUM(x)->len-1] = RBIGNUM(x)->sign ? ~0 : 1;
+ ds[RBIGNUM(x)->len-1] = ~0;
}
}
@@ -92,7 +93,7 @@ void
rb_big_2comp(x) /* get 2's complement */
VALUE x;
{
- get2comp(x);
+ get2comp(x, Qtrue);
}
static VALUE
@@ -747,17 +748,6 @@ big2ulong(x, type)
}
unsigned long
-rb_big2ulong_pack(x)
- VALUE x;
-{
- unsigned long num = big2ulong(x, "unsigned long");
- if (!RBIGNUM(x)->sign) {
- return -num;
- }
- return num;
-}
-
-unsigned long
rb_big2ulong(x)
VALUE x;
{
@@ -979,8 +969,8 @@ rb_big_eq(x, y)
volatile double a, b;
a = RFLOAT(y)->value;
- if (isnan(a)) return Qfalse;
b = rb_big2dbl(x);
+ if (isnan(a) || isnan(b)) return Qfalse;
return (a == b)?Qtrue:Qfalse;
}
default:
@@ -1049,15 +1039,13 @@ rb_big_neg(x)
VALUE x;
{
VALUE z = rb_big_clone(x);
- long i;
- BDIGIT *ds;
+ long i = RBIGNUM(x)->len;
+ BDIGIT *ds = BDIGITS(z);
- if (!RBIGNUM(x)->sign) get2comp(z);
- ds = BDIGITS(z);
- i = RBIGNUM(x)->len;
+ if (!RBIGNUM(x)->sign) get2comp(z, Qtrue);
while (i--) ds[i] = ~ds[i];
+ if (RBIGNUM(x)->sign) get2comp(z, Qfalse);
RBIGNUM(z)->sign = !RBIGNUM(z)->sign;
- if (RBIGNUM(x)->sign) get2comp(z);
return bignorm(z);
}
@@ -1088,7 +1076,7 @@ bigsub(x, y)
}
}
- z = bignew(RBIGNUM(x)->len, z==0);
+ z = bignew(RBIGNUM(x)->len, (z == 0)?1:0);
zds = BDIGITS(z);
for (i = 0, num = 0; i < RBIGNUM(y)->len; i++) {
@@ -1112,7 +1100,7 @@ bigsub(x, y)
static VALUE
bigadd(x, y, sign)
VALUE x, y;
- int sign;
+ char sign;
{
VALUE z;
BDIGIT_DBL num;
@@ -1649,11 +1637,11 @@ rb_big_and(xx, yy)
}
if (!RBIGNUM(y)->sign) {
y = rb_big_clone(y);
- get2comp(y);
+ get2comp(y, Qtrue);
}
if (!RBIGNUM(x)->sign) {
x = rb_big_clone(x);
- get2comp(x);
+ get2comp(x, Qtrue);
}
if (RBIGNUM(x)->len > RBIGNUM(y)->len) {
l1 = RBIGNUM(y)->len;
@@ -1678,7 +1666,7 @@ rb_big_and(xx, yy)
for (; i<l2; i++) {
zds[i] = sign?0:ds2[i];
}
- if (!RBIGNUM(z)->sign) get2comp(z);
+ if (!RBIGNUM(z)->sign) get2comp(z, Qfalse);
return bignorm(z);
}
@@ -1703,13 +1691,14 @@ rb_big_or(xx, yy)
if (FIXNUM_P(y)) {
y = rb_int2big(FIX2LONG(y));
}
+
if (!RBIGNUM(y)->sign) {
y = rb_big_clone(y);
- get2comp(y);
+ get2comp(y, Qtrue);
}
if (!RBIGNUM(x)->sign) {
x = rb_big_clone(x);
- get2comp(x);
+ get2comp(x, Qtrue);
}
if (RBIGNUM(x)->len > RBIGNUM(y)->len) {
l1 = RBIGNUM(y)->len;
@@ -1734,7 +1723,7 @@ rb_big_or(xx, yy)
for (; i<l2; i++) {
zds[i] = sign?ds2[i]:(BIGRAD-1);
}
- if (!RBIGNUM(z)->sign) get2comp(z);
+ if (!RBIGNUM(z)->sign) get2comp(z, Qfalse);
return bignorm(z);
}
@@ -1761,13 +1750,14 @@ rb_big_xor(xx, yy)
if (FIXNUM_P(y)) {
y = rb_int2big(FIX2LONG(y));
}
+
if (!RBIGNUM(y)->sign) {
y = rb_big_clone(y);
- get2comp(y);
+ get2comp(y, Qtrue);
}
if (!RBIGNUM(x)->sign) {
x = rb_big_clone(x);
- get2comp(x);
+ get2comp(x, Qtrue);
}
if (RBIGNUM(x)->len > RBIGNUM(y)->len) {
l1 = RBIGNUM(y)->len;
@@ -1794,7 +1784,7 @@ rb_big_xor(xx, yy)
for (; i<l2; i++) {
zds[i] = sign?ds2[i]:~ds2[i];
}
- if (!RBIGNUM(z)->sign) get2comp(z);
+ if (!RBIGNUM(z)->sign) get2comp(z, Qfalse);
return bignorm(z);
}
@@ -1866,7 +1856,7 @@ rb_big_rshift(x, y)
}
if (!RBIGNUM(x)->sign) {
x = rb_big_clone(x);
- get2comp(x);
+ get2comp(x, Qtrue);
}
xds = BDIGITS(x);
i = RBIGNUM(x)->len; j = i - s1;
@@ -1881,7 +1871,7 @@ rb_big_rshift(x, y)
num = BIGUP(xds[i]);
}
if (!RBIGNUM(x)->sign) {
- get2comp(z);
+ get2comp(z, Qfalse);
}
return bignorm(z);
}
@@ -1926,7 +1916,7 @@ rb_big_aref(x, y)
if (!RBIGNUM(x)->sign) {
if (s1 >= RBIGNUM(x)->len) return INT2FIX(1);
x = rb_big_clone(x);
- get2comp(x);
+ get2comp(x, Qtrue);
}
else {
if (s1 >= RBIGNUM(x)->len) return INT2FIX(0);
@@ -1969,11 +1959,8 @@ rb_big_coerce(x, y)
if (FIXNUM_P(y)) {
return rb_assoc_new(rb_int2big(FIX2LONG(y)), x);
}
- else if (TYPE(y) == T_BIGNUM) {
- return rb_assoc_new(y, x);
- }
else {
- rb_raise(rb_eTypeError, "can't coerce %s to Bignum",
+ rb_raise(rb_eTypeError, "Can't coerce %s to Bignum",
rb_obj_classname(y));
}
/* not reached */
@@ -2012,13 +1999,11 @@ rb_big_rand(max, rand_buf)
return rb_float_new(rand_buf[0]);
}
v = bignew(len,1);
- len--;
- BDIGITS(v)[len] = BDIGITS(max)[len] * rand_buf[len];
while (len--) {
BDIGITS(v)[len] = ((BDIGIT)~0) * rand_buf[len];
}
- return v;
+ return rb_big_modulo((VALUE)v, max);
}
/*
diff --git a/bin/erb b/bin/erb
index a6fcd5370c..2459d2562e 100755
--- a/bin/erb
+++ b/bin/erb
@@ -12,13 +12,13 @@ class ERB
arg = self.shift
return nil if arg == '--'
if arg =~ /^-(.)(.*)/
- return arg if $1 == '-'
- raise 'unknown switch "-"' if $2.index('-')
- self.unshift "-#{$2}" if $2.size > 0
- "-#{$1}"
+ return arg if $1 == '-'
+ raise 'unknown switch "-"' if $2.index('-')
+ self.unshift "-#{$2}" if $2.size > 0
+ "-#{$1}"
else
- self.unshift arg
- nil
+ self.unshift arg
+ nil
end
end
@@ -30,13 +30,13 @@ class ERB
return trim_mode if disable_percent
case trim_mode
when 0
- return '%'
+ return '%'
when 1
- return '%>'
+ return '%>'
when 2
- return '%<>'
+ return '%<>'
when '-'
- return '%-'
+ return '%-'
end
end
module_function :trim_mode_opt
@@ -45,91 +45,89 @@ class ERB
trim_mode = 0
disable_percent = false
begin
- while switch = ARGV.switch
- case switch
- when '-x' # ruby source
- output = true
- when '-n' # line number
- number = true
- when '-v' # verbose
- $VERBOSE = true
- when '--version' # version
- STDERR.puts factory.version
- exit
- when '-d', '--debug' # debug
- $DEBUG = true
- when '-r' # require
- require ARGV.req_arg
- when '-S' # security level
- arg = ARGV.req_arg
- raise "invalid safe_level #{arg.dump}" unless arg =~ /^[0-4]$/
- safe_level = arg.to_i
- when '-T' # trim mode
- arg = ARGV.req_arg
- if arg == '-'
- trim_mode = arg
- next
- end
- raise "invalid trim mode #{arg.dump}" unless arg =~ /^[0-2]$/
- trim_mode = arg.to_i
- when '-K' # KCODE
- arg = ARGV.req_arg
- case arg.downcase
- when 'e', '-e', 'euc'
- $KCODE = 'EUC'
- when 's', '-s', 'sjis'
- $KCODE = 'SJIS'
- when 'u', '-u', 'utf8'
- $KCODE = 'UTF8'
- when 'n', '-n', 'none'
- $KCODE = 'NONE'
- else
- raise "invalid KCODE #{arg.dump}"
- end
- when '-P'
- disable_percent = true
- when '--help'
- raise "print this help"
- else
- raise "unknown switch #{switch.dump}"
- end
- end
- rescue # usage
- STDERR.puts $!.to_s
- STDERR.puts File.basename($0) +
- " [switches] [inputfile]"
- STDERR.puts <<EOU
+ while switch = ARGV.switch
+ case switch
+ when '-x' # ruby source
+ output = true
+ when '-n' # line number
+ number = true
+ when '-v' # verbose
+ $VERBOSE = true
+ when '--version' # version
+ STDERR.puts factory.version
+ exit
+ when '-d', '--debug' # debug
+ $DEBUG = true
+ when '-r' # require
+ require ARGV.req_arg
+ when '-S' # sacurity level
+ arg = ARGV.req_arg
+ raise "invalid safe_level #{arg.dump}" unless arg =~ /^[0-4]$/
+ safe_level = arg.to_i
+ when '-T' # trim mode
+ arg = ARGV.req_arg
+ if arg == '-'
+ trim_mode = arg
+ next
+ end
+ raise "invalid trim mode #{arg.dump}" unless arg =~ /^[0-2]$/
+ trim_mode = arg.to_i
+ when '-K' # KCODE
+ arg = ARGV.req_arg
+ case arg.downcase
+ when 'e', '-e', 'euc'
+ $KCODE = 'EUC'
+ when 's', '-s', 'sjis'
+ $KCODE = 'SJIS'
+ when 'u', '-u', 'utf8'
+ $KCODE = 'UTF8'
+ when 'n', '-n', 'none'
+ $KCODE = 'NONE'
+ else
+ raise "invalid KCODE #{arg.dump}"
+ end
+ when '-P'
+ disable_percent = true
+ when '--help'
+ raise "print this help"
+ else
+ raise "unknown switch #{switch.dump}"
+ end
+ end
+ rescue # usage
+ STDERR.puts $!.to_s
+ STDERR.puts File.basename($0) +
+ " [switches] [inputfile]"
+ STDERR.puts <<EOU
-x print ruby script
-n print ruby script with line number
-v enable verbose mode
- -d set $DEBUG to true
+ -d set $DBEUG to true
-r [library] load a library
-K [kcode] specify KANJI code-set
-S [safe_level] set $SAFE (0..4)
-T [trim_mode] specify trim_mode (0..2, -)
- -P ignore lines which start with "%"
+ -P disregard the lin which starts in "%"
EOU
- exit 1
+ exit 1
end
src = $<.read
- filename = $FILENAME
exit 2 unless src
trim = trim_mode_opt(trim_mode, disable_percent)
erb = factory.new(src.untaint, safe_level, trim)
- erb.filename = filename
if output
- if number
- l = 1
- for line in erb.src
- puts "%3d %s"%[l, line]
- l += 1
- end
- else
- puts erb.src
- end
+ if number
+ l = 1
+ for line in erb.src
+ puts "%3d %s"%[l, line]
+ l += 1
+ end
+ else
+ puts erb.src
+ end
else
- erb.run(TOPLEVEL_BINDING.taint)
+ erb.run(TOPLEVEL_BINDING.taint)
end
end
module_function :run
diff --git a/bin/irb b/bin/irb
index f277bc4b69..309da52161 100644
--- a/bin/irb
+++ b/bin/irb
@@ -1,10 +1,10 @@
#!/usr/bin/env ruby
#
# irb.rb - intaractive ruby
-# $Release Version: 0.9.5 $
+# $Release Version: 0.7.3 $
# $Revision$
# $Date$
-# by Keiju ISHITSUKA(keiju@ruby-lang.org)
+# by Keiju ISHITSUKA(keiju@ishitsuka.com)
#
require "irb"
diff --git a/class.c b/class.c
index 798ecebe72..8addef7612 100644
--- a/class.c
+++ b/class.c
@@ -58,7 +58,6 @@ clone_method(mid, body, tbl)
return ST_CONTINUE;
}
-/* :nodoc: */
VALUE
rb_mod_init_copy(clone, orig)
VALUE clone, orig;
@@ -86,7 +85,6 @@ rb_mod_init_copy(clone, orig)
return clone;
}
-/* :nodoc: */
VALUE
rb_class_init_copy(clone, orig)
VALUE clone, orig;
@@ -94,9 +92,6 @@ rb_class_init_copy(clone, orig)
if (RCLASS(clone)->super != 0) {
rb_raise(rb_eTypeError, "already initialized class");
}
- if (FL_TEST(orig, FL_SINGLETON)) {
- rb_raise(rb_eTypeError, "can't copy singleton class");
- }
return rb_mod_init_copy(clone, orig);
}
diff --git a/common.mk b/common.mk
deleted file mode 100644
index 113b64c970..0000000000
--- a/common.mk
+++ /dev/null
@@ -1,298 +0,0 @@
-bin: $(PROGRAM) $(WPROGRAM)
-lib: $(LIBRUBY);
-dll: $(LIBRUBY_SO);
-
-RUBYOPT =
-
-EXTCONF = extconf.rb
-RBCONFIG = ./.rbconfig.time
-
-DMYEXT = dmyext.$(OBJEXT)
-MAINOBJ = main.$(OBJEXT)
-EXTOBJS =
-DLDOBJS = $(DMYEXT)
-
-OBJS = array.$(OBJEXT) \
- bignum.$(OBJEXT) \
- class.$(OBJEXT) \
- compar.$(OBJEXT) \
- dir.$(OBJEXT) \
- dln.$(OBJEXT) \
- enum.$(OBJEXT) \
- error.$(OBJEXT) \
- eval.$(OBJEXT) \
- file.$(OBJEXT) \
- gc.$(OBJEXT) \
- hash.$(OBJEXT) \
- inits.$(OBJEXT) \
- io.$(OBJEXT) \
- marshal.$(OBJEXT) \
- math.$(OBJEXT) \
- numeric.$(OBJEXT) \
- object.$(OBJEXT) \
- pack.$(OBJEXT) \
- parse.$(OBJEXT) \
- process.$(OBJEXT) \
- prec.$(OBJEXT) \
- random.$(OBJEXT) \
- range.$(OBJEXT) \
- re.$(OBJEXT) \
- regex.$(OBJEXT) \
- ruby.$(OBJEXT) \
- signal.$(OBJEXT) \
- sprintf.$(OBJEXT) \
- st.$(OBJEXT) \
- string.$(OBJEXT) \
- struct.$(OBJEXT) \
- time.$(OBJEXT) \
- util.$(OBJEXT) \
- variable.$(OBJEXT) \
- version.$(OBJEXT) \
- $(MISSING)
-
-SCRIPT_ARGS = --dest-dir="$(DESTDIR)" \
- --make="$(MAKE)" \
- --mflags="$(MFLAGS)" \
- --make-flags="$(MAKEFLAGS)"
-EXTMK_ARGS = $(SCRIPT_ARGS) --extout="$(EXTOUT)" --extension $(EXTS) --extstatic $(EXTSTATIC) --
-
-all: $(MKFILES) $(PREP) $(RBCONFIG) $(LIBRUBY)
- @$(MINIRUBY) $(srcdir)/ext/extmk.rb $(EXTMK_ARGS)
-prog: $(PROGRAM) $(WPROGRAM)
-
-miniruby$(EXEEXT): config.status $(LIBRUBY_A) $(MAINOBJ) $(MINIOBJS) $(OBJS) $(DMYEXT)
-
-$(PROGRAM): $(LIBRUBY) $(MAINOBJ) $(OBJS) $(EXTOBJS) $(SETUP) $(PREP)
-
-$(LIBRUBY_A): $(OBJS) $(DMYEXT)
-
-$(LIBRUBY_SO): $(OBJS) $(DLDOBJS) $(LIBRUBY_A) $(PREP) $(ARCHFILE)
-
-static-ruby: $(MAINOBJ) $(EXTOBJS) $(LIBRUBY_A)
- @$(RM) $@
- $(PURIFY) $(CC) $(LDFLAGS) $(XLDFLAGS) $(MAINLIBS) $(MAINOBJ) $(EXTOBJS) $(LIBRUBY_A) $(LIBS) $(OUTFLAG)$@
-
-ruby.imp: $(LIBRUBY_A)
- @$(NM) -Pgp $(LIBRUBY_A) | awk 'BEGIN{print "#!"}; $$2~/^[BD]$$/{print $$1}' | sort -u -o $@
-
-install: install-nodoc $(RDOCTARGET)
-install-all: install-nodoc install-doc
-
-install-nodoc: install-local install-ext
-install-local: pre-install-local do-install-local post-install-local
-install-ext: pre-install-ext do-install-ext post-install-ext
-
-do-install-local: $(RBCONFIG)
- $(MINIRUBY) $(srcdir)/instruby.rb $(SCRIPT_ARGS) --mantype="$(MANTYPE)"
-do-install-ext: $(RBCONFIG)
- $(MINIRUBY) $(srcdir)/ext/extmk.rb $(EXTMK_ARGS) install
-
-install-bin: $(RBCONFIG)
- $(MINIRUBY) $(srcdir)/instruby.rb $(SCRIPT_ARGS) --install=bin
-install-lib: $(RBCONFIG)
- $(MINIRUBY) $(srcdir)/instruby.rb $(SCRIPT_ARGS) --install=lib
-install-man: $(RBCONFIG)
- $(MINIRUBY) $(srcdir)/instruby.rb $(SCRIPT_ARGS) --install=man --mantype="$(MANTYPE)"
-
-what-where-all no-install-all: no-install no-install-doc
-what-where no-install: no-install-local no-install-ext
-what-where-local: no-install-local
-no-install-local: $(RBCONFIG)
- $(MINIRUBY) $(srcdir)/instruby.rb -n $(SCRIPT_ARGS) --mantype="$(MANTYPE)"
-what-where-ext: no-install-ext
-no-install-ext: $(RBCONFIG)
- $(MINIRUBY) $(srcdir)/ext/extmk.rb -n $(EXTMK_ARGS) install
-
-install-doc: pre-install-doc do-install-doc post-install-doc
-do-install-doc: $(PROGRAM)
- @echo Generating RDoc documentation
- $(RUNRUBY) "$(srcdir)/bin/rdoc" --all --ri --op "$(RIDATADIR)" "$(srcdir)"
-
-pre-install: pre-install-local pre-install-ext
-pre-install-local:: PHONY
-pre-install-ext:: PHONY
-pre-install-doc:: PHONY
-
-post-install: post-install-local post-install-ext
-post-install-local:: PHONY
-post-install-ext:: PHONY
-post-install-doc:: PHONY
-
-clean: clean-ext clean-local
-clean-local::
- @$(RM) $(OBJS) $(MAINOBJ) $(WINMAINOBJ) $(LIBRUBY_A) $(LIBRUBY_SO) $(LIBRUBY) $(LIBRUBY_ALIASES)
- @$(RM) $(PROGRAM) $(WPROGRAM) miniruby$(EXEEXT) dmyext.$(OBJEXT) $(ARCHFILE)
-clean-ext:
- @-$(MINIRUBY) $(srcdir)/ext/extmk.rb $(EXTMK_ARGS) clean
-
-distclean: distclean-ext distclean-local
-distclean-local:: clean-local
- @$(RM) $(MKFILES) config.h rbconfig.rb
- @$(RM) config.cache config.log config.status
- @$(RM) *~ *.bak *.stackdump core *.core gmon.out y.tab.c y.output $(PREP)
-distclean-ext:
- @-$(MINIRUBY) $(srcdir)/ext/extmk.rb $(EXTMK_ARGS) distclean
-
-realclean:: distclean
- @$(RM) parse.c lex.c
-
-check: test test-all
-
-test: miniruby$(EXEEXT) $(RBCONFIG) $(PROGRAM) PHONY
- @$(MINIRUBY) $(srcdir)/rubytest.rb
-
-test-all:
- $(RUNRUBY) -C "$(srcdir)/test" runner.rb --runner=$(TESTUI) $(TESTS)
-
-extconf:
- $(MINIRUBY) -I$(srcdir)/lib -run -e mkdir -- -p "$(EXTCONFDIR)"
- $(RUNRUBY) -C "$(EXTCONFDIR)" $(EXTCONF) $(EXTCONFARGS)
-
-$(RBCONFIG): $(srcdir)/mkconfig.rb config.status $(PREP)
- @$(MINIRUBY) $(srcdir)/mkconfig.rb -timestamp=$@ \
- -install_name=$(RUBY_INSTALL_NAME) \
- -so_name=$(RUBY_SO_NAME) rbconfig.rb
-
-.PRECIOUS: $(MKFILES)
-
-.PHONY: test install install-nodoc install-doc
-
-PHONY:
-
-{$(VPATH)}parse.c: parse.y
-
-acosh.$(OBJEXT): {$(VPATH)}acosh.c
-alloca.$(OBJEXT): {$(VPATH)}alloca.c
-crypt.$(OBJEXT): {$(VPATH)}crypt.c
-dup2.$(OBJEXT): {$(VPATH)}dup2.c
-erf.$(OBJEXT): {$(VPATH)}erf.c
-finite.$(OBJEXT): {$(VPATH)}finite.c
-flock.$(OBJEXT): {$(VPATH)}flock.c
-memcmp.$(OBJEXT): {$(VPATH)}memcmp.c
-memmove.$(OBJEXT): {$(VPATH)}memmove.c
-mkdir.$(OBJEXT): {$(VPATH)}mkdir.c
-vsnprintf.$(OBJEXT): {$(VPATH)}vsnprintf.c
-strcasecmp.$(OBJEXT): {$(VPATH)}strcasecmp.c
-strncasecmp.$(OBJEXT): {$(VPATH)}strncasecmp.c
-strchr.$(OBJEXT): {$(VPATH)}strchr.c
-strdup.$(OBJEXT): {$(VPATH)}strdup.c
-strerror.$(OBJEXT): {$(VPATH)}strerror.c
-strftime.$(OBJEXT): {$(VPATH)}strftime.c
-strstr.$(OBJEXT): {$(VPATH)}strstr.c
-strtod.$(OBJEXT): {$(VPATH)}strtod.c
-strtol.$(OBJEXT): {$(VPATH)}strtol.c
-strtoul.$(OBJEXT): {$(VPATH)}strtoul.c
-nt.$(OBJEXT): {$(VPATH)}nt.c
-x68.$(OBJEXT): {$(VPATH)}x68.c
-os2.$(OBJEXT): {$(VPATH)}os2.c
-dl_os2.$(OBJEXT): {$(VPATH)}dl_os2.c
-
-# when I use -I., there is confliction at "OpenFile"
-# so, set . into environment varible "include"
-win32.$(OBJEXT): {$(VPATH)}win32.c
-
-###
-
-array.$(OBJEXT): {$(VPATH)}array.c {$(VPATH)}ruby.h config.h \
- {$(VPATH)}defines.h {$(VPATH)}intern.h {$(VPATH)}missing.h \
- {$(VPATH)}util.h {$(VPATH)}st.h
-bignum.$(OBJEXT): {$(VPATH)}bignum.c {$(VPATH)}ruby.h config.h \
- {$(VPATH)}defines.h {$(VPATH)}intern.h {$(VPATH)}missing.h
-class.$(OBJEXT): {$(VPATH)}class.c {$(VPATH)}ruby.h config.h \
- {$(VPATH)}defines.h {$(VPATH)}intern.h {$(VPATH)}missing.h \
- {$(VPATH)}rubysig.h {$(VPATH)}node.h {$(VPATH)}st.h
-compar.$(OBJEXT): {$(VPATH)}compar.c {$(VPATH)}ruby.h config.h \
- {$(VPATH)}defines.h {$(VPATH)}intern.h {$(VPATH)}missing.h
-dir.$(OBJEXT): {$(VPATH)}dir.c {$(VPATH)}ruby.h config.h \
- {$(VPATH)}defines.h {$(VPATH)}intern.h {$(VPATH)}missing.h \
- {$(VPATH)}util.h
-dln.$(OBJEXT): {$(VPATH)}dln.c {$(VPATH)}ruby.h config.h \
- {$(VPATH)}defines.h {$(VPATH)}intern.h {$(VPATH)}missing.h \
- {$(VPATH)}dln.h
-dmydln.$(OBJEXT): {$(VPATH)}dmydln.c {$(VPATH)}dln.c {$(VPATH)}ruby.h \
- config.h {$(VPATH)}defines.h {$(VPATH)}intern.h {$(VPATH)}missing.h \
- {$(VPATH)}dln.h
-dmyext.$(OBJEXT): {$(VPATH)}dmyext.c
-enum.$(OBJEXT): {$(VPATH)}enum.c {$(VPATH)}ruby.h config.h \
- {$(VPATH)}defines.h {$(VPATH)}intern.h {$(VPATH)}missing.h \
- {$(VPATH)}node.h {$(VPATH)}util.h
-error.$(OBJEXT): {$(VPATH)}error.c {$(VPATH)}ruby.h config.h \
- {$(VPATH)}defines.h {$(VPATH)}intern.h {$(VPATH)}missing.h \
- {$(VPATH)}env.h {$(VPATH)}st.h
-eval.$(OBJEXT): {$(VPATH)}eval.c {$(VPATH)}ruby.h config.h \
- {$(VPATH)}defines.h {$(VPATH)}intern.h {$(VPATH)}missing.h \
- {$(VPATH)}node.h {$(VPATH)}env.h {$(VPATH)}util.h \
- {$(VPATH)}rubysig.h {$(VPATH)}st.h {$(VPATH)}dln.h
-file.$(OBJEXT): {$(VPATH)}file.c {$(VPATH)}ruby.h config.h \
- {$(VPATH)}defines.h {$(VPATH)}intern.h {$(VPATH)}missing.h \
- {$(VPATH)}rubyio.h {$(VPATH)}rubysig.h {$(VPATH)}util.h \
- {$(VPATH)}dln.h
-gc.$(OBJEXT): {$(VPATH)}gc.c {$(VPATH)}ruby.h config.h \
- {$(VPATH)}defines.h {$(VPATH)}intern.h {$(VPATH)}missing.h \
- {$(VPATH)}rubysig.h {$(VPATH)}st.h {$(VPATH)}node.h \
- {$(VPATH)}env.h {$(VPATH)}re.h {$(VPATH)}regex.h
-hash.$(OBJEXT): {$(VPATH)}hash.c {$(VPATH)}ruby.h config.h \
- {$(VPATH)}defines.h {$(VPATH)}intern.h {$(VPATH)}missing.h \
- {$(VPATH)}st.h {$(VPATH)}util.h {$(VPATH)}rubysig.h
-inits.$(OBJEXT): {$(VPATH)}inits.c {$(VPATH)}ruby.h config.h \
- {$(VPATH)}defines.h {$(VPATH)}intern.h {$(VPATH)}missing.h
-io.$(OBJEXT): {$(VPATH)}io.c {$(VPATH)}ruby.h config.h \
- {$(VPATH)}defines.h {$(VPATH)}intern.h {$(VPATH)}missing.h \
- {$(VPATH)}rubyio.h {$(VPATH)}rubysig.h {$(VPATH)}util.h
-main.$(OBJEXT): {$(VPATH)}main.c {$(VPATH)}ruby.h config.h \
- {$(VPATH)}defines.h {$(VPATH)}intern.h {$(VPATH)}missing.h
-marshal.$(OBJEXT): {$(VPATH)}marshal.c {$(VPATH)}ruby.h config.h \
- {$(VPATH)}defines.h {$(VPATH)}intern.h {$(VPATH)}missing.h \
- {$(VPATH)}rubyio.h {$(VPATH)}st.h {$(VPATH)}util.h
-math.$(OBJEXT): {$(VPATH)}math.c {$(VPATH)}ruby.h config.h \
- {$(VPATH)}defines.h {$(VPATH)}intern.h {$(VPATH)}missing.h
-numeric.$(OBJEXT): {$(VPATH)}numeric.c {$(VPATH)}ruby.h config.h \
- {$(VPATH)}env.h {$(VPATH)}defines.h {$(VPATH)}intern.h \
- {$(VPATH)}missing.h
-object.$(OBJEXT): {$(VPATH)}object.c {$(VPATH)}ruby.h config.h \
- {$(VPATH)}defines.h {$(VPATH)}intern.h {$(VPATH)}missing.h \
- {$(VPATH)}st.h {$(VPATH)}util.h
-pack.$(OBJEXT): {$(VPATH)}pack.c {$(VPATH)}ruby.h config.h \
- {$(VPATH)}defines.h {$(VPATH)}intern.h {$(VPATH)}missing.h
-parse.$(OBJEXT): {$(VPATH)}parse.c {$(VPATH)}ruby.h config.h \
- {$(VPATH)}defines.h {$(VPATH)}intern.h {$(VPATH)}missing.h \
- {$(VPATH)}env.h {$(VPATH)}node.h {$(VPATH)}st.h \
- {$(VPATH)}regex.h {$(VPATH)}util.h {$(VPATH)}lex.c
-prec.$(OBJEXT): {$(VPATH)}prec.c {$(VPATH)}ruby.h config.h \
- {$(VPATH)}defines.h {$(VPATH)}intern.h {$(VPATH)}missing.h
-process.$(OBJEXT): {$(VPATH)}process.c {$(VPATH)}ruby.h config.h \
- {$(VPATH)}defines.h {$(VPATH)}intern.h {$(VPATH)}missing.h \
- {$(VPATH)}rubysig.h {$(VPATH)}st.h
-random.$(OBJEXT): {$(VPATH)}random.c {$(VPATH)}ruby.h config.h \
- {$(VPATH)}defines.h {$(VPATH)}intern.h {$(VPATH)}missing.h
-range.$(OBJEXT): {$(VPATH)}range.c {$(VPATH)}ruby.h config.h \
- {$(VPATH)}defines.h {$(VPATH)}intern.h {$(VPATH)}missing.h
-re.$(OBJEXT): {$(VPATH)}re.c {$(VPATH)}ruby.h config.h \
- {$(VPATH)}defines.h {$(VPATH)}intern.h {$(VPATH)}missing.h \
- {$(VPATH)}re.h {$(VPATH)}regex.h
-regex.$(OBJEXT): {$(VPATH)}regex.c config.h {$(VPATH)}regex.h
-ruby.$(OBJEXT): {$(VPATH)}ruby.c {$(VPATH)}ruby.h config.h \
- {$(VPATH)}defines.h {$(VPATH)}intern.h {$(VPATH)}missing.h \
- {$(VPATH)}dln.h {$(VPATH)}node.h {$(VPATH)}util.h
-signal.$(OBJEXT): {$(VPATH)}signal.c {$(VPATH)}ruby.h config.h \
- {$(VPATH)}defines.h {$(VPATH)}intern.h {$(VPATH)}missing.h \
- {$(VPATH)}rubysig.h
-sprintf.$(OBJEXT): {$(VPATH)}sprintf.c {$(VPATH)}ruby.h config.h \
- {$(VPATH)}defines.h {$(VPATH)}intern.h {$(VPATH)}missing.h
-st.$(OBJEXT): {$(VPATH)}st.c config.h {$(VPATH)}st.h
-string.$(OBJEXT): {$(VPATH)}string.c {$(VPATH)}ruby.h config.h \
- {$(VPATH)}defines.h {$(VPATH)}intern.h {$(VPATH)}missing.h \
- {$(VPATH)}re.h {$(VPATH)}regex.h
-struct.$(OBJEXT): {$(VPATH)}struct.c {$(VPATH)}ruby.h config.h \
- {$(VPATH)}defines.h {$(VPATH)}intern.h {$(VPATH)}missing.h
-time.$(OBJEXT): {$(VPATH)}time.c {$(VPATH)}ruby.h config.h \
- {$(VPATH)}defines.h {$(VPATH)}intern.h {$(VPATH)}missing.h
-util.$(OBJEXT): {$(VPATH)}util.c {$(VPATH)}ruby.h config.h \
- {$(VPATH)}defines.h {$(VPATH)}intern.h {$(VPATH)}missing.h \
- {$(VPATH)}util.h
-variable.$(OBJEXT): {$(VPATH)}variable.c {$(VPATH)}ruby.h config.h \
- {$(VPATH)}defines.h {$(VPATH)}intern.h {$(VPATH)}missing.h \
- {$(VPATH)}env.h {$(VPATH)}node.h {$(VPATH)}st.h {$(VPATH)}util.h
-version.$(OBJEXT): {$(VPATH)}version.c {$(VPATH)}ruby.h config.h \
- {$(VPATH)}defines.h {$(VPATH)}intern.h {$(VPATH)}missing.h \
- {$(VPATH)}version.h
diff --git a/configure.in b/configure.in
index 2ab91c2e53..641954adfe 100644
--- a/configure.in
+++ b/configure.in
@@ -1,7 +1,7 @@
dnl Process this file with autoconf to produce a configure script.
AC_INIT()
-AC_PREREQ(2.58)
+AC_PREREQ(2.50)
AC_DEFUN(RUBY_MINGW32,
[case "$host_os" in
@@ -174,19 +174,6 @@ cygwin*|mingw*)
AC_CHECK_TOOL(WINDRES, windres)
AC_CHECK_TOOL(DLLWRAP, dllwrap)
target_cpu=`echo $target_cpu | sed s/i.86/i386/`
- case "$target_os" in
- mingw*)
- test "$rb_cv_msvcrt" = "" && unset rb_cv_msvcrt
- AC_CHECK_TOOL(OBJDUMP, objdump)
- AC_CACHE_CHECK(for mingw32 runtime DLL, rb_cv_msvcrt, [
- AC_TRY_LINK([#include <stdio.h>],
- [FILE* volatile f = stdin; return 0;],
- [rb_cv_msvcrt=`$OBJDUMP -p conftest$ac_exeext |
- tr A-Z a-z |
- sed -n '/^[[ ]]*dll name: \(msvc.*\)\.dll$/{s//\1/p;q;}'`],
- [rb_cv_msvcrt=msvcrt])])
- test "$rb_cv_msvcrt" = "" && AC_MSG_ERROR([must be linked to DLL])
- esac
: ${enable_shared=yes}
;;
aix*)
@@ -200,20 +187,11 @@ esac
AC_PROG_LN_S
AC_PROG_MAKE_SET
-AC_PROG_INSTALL
# checks for UNIX variants that set C preprocessor variables
AC_AIX
AC_MINIX
-AC_SUBST(RM, ['rm -f'])
-AC_SUBST(CP, ['cp'])
-if $as_mkdir_p; then
- AC_SUBST(MAKEDIRS, ['mkdir -p'])
-else
- AC_SUBST(MAKEDIRS, ['install -d'])
-fi
-
dnl check for large file stuff
AC_SYS_LARGEFILE
@@ -230,11 +208,6 @@ AC_CHECK_SIZEOF(float, 4)
AC_CHECK_SIZEOF(double, 8)
AC_CHECK_SIZEOF(time_t, 0)
-for id in pid_t gid_t uid_t; do
- AC_CHECK_TYPE($id, [typ=$id], [typ=int])
- AC_DEFINE_UNQUOTED(rb_$id, $typ)
-done
-
AC_CACHE_CHECK(for prototypes, rb_cv_have_prototypes,
[AC_TRY_COMPILE([int foo(int x) { return 0; }], [return foo(10);],
rb_cv_have_prototypes=yes,
@@ -273,7 +246,7 @@ if test "$rb_cv_stdarg" = yes; then
fi
AC_CACHE_CHECK([for noreturn], rb_cv_noreturn,
-[rb_cv_noreturn=x
+[rb_cv_noreturn=no
for mac in "x __attribute__ ((noreturn))" "__declspec(noreturn) x" x; do
AC_TRY_COMPILE(
[#define NORETURN(x) $mac
@@ -283,17 +256,6 @@ NORETURN(void exit(int x));],
done])
AC_DEFINE_UNQUOTED([NORETURN(x)], $rb_cv_noreturn)
-AC_CACHE_CHECK([for RUBY_EXTERN], rb_cv_ruby_extern,
-[rb_cv_ruby_extern=no
-for mac in "__attribute__((dllimport))" "__declspec(dllimport)"; do
- AC_TRY_COMPILE(
- [extern $mac void conftest(void);],
- [rb_cv_ruby_extern="extern $mac"; break])
-done])
-test "x$rb_cv_ruby_extern" = xno || AC_DEFINE_UNQUOTED(RUBY_EXTERN, $rb_cv_ruby_extern)
-
-XCFLAGS="$XCFLAGS -DRUBY_EXPORT"
-
dnl Check whether we need to define sys_nerr locally
AC_CHECK_DECLS([sys_nerr], [], [], [$ac_includes_default
#include <errno.h>])
@@ -346,11 +308,6 @@ mingw*) LIBS="-lwsock32 $LIBS"
ac_cv_func_isnan=yes
ac_cv_func_finite=yes
ac_cv_lib_crypt_crypt=no
- ac_cv_func_getpgrp_void=no
- ac_cv_func_setpgrp_void=yes
- ac_cv_func_memcmp_working=yes
- rb_cv_binary_elf=no
- rb_cv_negative_time_t=no
enable_pthread=no
;;
os2-emx*) LIBS="-lm $LIBS"
@@ -415,13 +372,14 @@ dnl Checks for header files.
AC_HEADER_DIRENT
AC_HEADER_STDC
AC_HEADER_SYS_WAIT
-AC_CHECK_HEADERS(stdlib.h string.h unistd.h limits.h sys/file.h sys/ioctl.h sys/syscall.h\
+AC_CHECK_HEADERS(stdlib.h string.h unistd.h limits.h sys/file.h sys/ioctl.h\
fcntl.h sys/fcntl.h sys/select.h sys/time.h sys/times.h sys/param.h\
syscall.h pwd.h grp.h a.out.h utime.h memory.h direct.h sys/resource.h \
sys/mkdev.h sys/utime.h netinet/in_systm.h float.h ieeefp.h pthread.h \
ucontext.h intrinsics.h)
dnl Checks for typedefs, structures, and compiler characteristics.
+AC_TYPE_UID_T
AC_TYPE_SIZE_T
AC_STRUCT_ST_BLKSIZE
AC_STRUCT_ST_BLOCKS
@@ -434,7 +392,7 @@ AC_FUNC_ALLOCA
AC_FUNC_MEMCMP
AC_FUNC_FSEEKO
AC_CHECK_FUNCS(ftello)
-AC_REPLACE_FUNCS(dup2 memmove strcasecmp strncasecmp strerror strftime\
+AC_REPLACE_FUNCS(dup2 memmove mkdir strcasecmp strncasecmp strerror strftime\
strchr strstr strtoul crypt flock vsnprintf\
isnan finite isinf hypot acosh erf)
AC_CHECK_FUNCS(fmod killpg wait4 waitpid syscall chroot fsync getcwd\
@@ -818,12 +776,20 @@ if test "$rb_cv_binary_elf" = yes; then
fi
case "$target_os" in
-linux* | gnu* | k*bsd*-gnu | bsdi*)
+linux* | gnu* | k*bsd*-gnu)
if test "$rb_cv_binary_elf" = no; then
with_dln_a_out=yes
else
LDFLAGS="$LDFLAGS -rdynamic"
fi;;
+netbsd*|openbsd*)
+ if [[ "`$CC -dM -E - </dev/null | grep __ELF__`" != "" ]]
+ then
+ netbsd_elf=yes
+ else
+ netbsd_elf=no
+ fi
+ ;;
esac
LIBEXT=a
@@ -867,7 +833,6 @@ if test "$with_dln_a_out" != yes; then
hpux*) DLDFLAGS="$DLDFLAGS -E"
: ${LDSHARED='ld -b'}
XLDFLAGS="$XLDFLAGS -Wl,-E"
- : ${LIBPATHENV=SHLIB_PATH}
rb_cv_dlopen=yes;;
solaris*) if test "$GCC" = yes; then
: ${LDSHARED='$(CC) -Wl,-G'}
@@ -891,15 +856,8 @@ if test "$with_dln_a_out" != yes; then
rb_cv_dlopen=yes ;;
osf*) : ${LDSHARED="ld -shared -expect_unresolved \"*\""}
rb_cv_dlopen=yes ;;
- bsdi3*) case "$CC" in
- *shlicc*) : ${LDSHARED="$CC -r"}
- rb_cv_dlopen=yes ;;
- esac ;;
- linux* | gnu* | k*bsd*-gnu | netbsd* | bsdi*)
- : ${LDSHARED='${CC} -shared'}
- if test "$rb_cv_binary_elf" = yes; then
- LDFLAGS="$LDFLAGS -Wl,-export-dynamic"
- fi
+ linux* | gnu* | k*bsd*-gnu)
+ : ${LDSHARED="$CC -shared"}
rb_cv_dlopen=yes ;;
interix*) : ${LDSHARED="$CC -shared"}
XLDFLAGS="$XLDFLAGS -Wl,-E"
@@ -913,11 +871,25 @@ if test "$with_dln_a_out" != yes; then
test "$GCC" = yes && test "$rb_cv_prog_gnu_ld" = yes || LDSHARED="ld -Bshareable"
fi
rb_cv_dlopen=yes ;;
+ netbsd*) : ${LDSHARED='${CC} -shared'}
+ if test "$rb_cv_binary_elf" = yes; then
+ LDFLAGS="$LDFLAGS -Wl,-export-dynamic"
+ LIBPATHFLAG=" -L'%1\$-s'"
+ RPATHFLAG=" -Wl,-R'%1\$-s'"
+ fi
+ rb_cv_dlopen=yes ;;
openbsd*) : ${LDSHARED="\$(CC) -shared ${CCDLFLAGS}"}
if test "$rb_cv_binary_elf" = yes; then
LDFLAGS="$LDFLAGS -Wl,-E"
fi
rb_cv_dlopen=yes ;;
+ bsdi3*) case "$CC" in
+ *shlicc*) : ${LDSHARED="$CC -r"}
+ rb_cv_dlopen=yes ;;
+ esac ;;
+ bsdi*) : ${LDSHARED="ld -shared"}
+ LDFLAGS="$LDFLAGS "'-rdynamic -Wl,-rpath,$(libdir)/ruby/$(MAJOR).$(MINOR)/i386-bsdi4.0'
+ rb_cv_dlopen=yes ;;
nextstep*) : ${LDSHARED='cc -r -nostdlib'}
LDFLAGS="$LDFLAGS -u libsys_s"
rb_cv_dlopen=yes ;;
@@ -929,16 +901,15 @@ if test "$with_dln_a_out" != yes; then
rb_cv_dlopen=yes ;;
darwin*) : ${LDSHARED='cc -dynamic -bundle -undefined suppress -flat_namespace'}
: ${LDFLAGS=""}
- : ${LIBPATHENV=DYLD_LIBRARY_PATH}
rb_cv_dlopen=yes ;;
aix*) : ${LDSHARED='/usr/ccs/bin/ld'}
XLDFLAGS="$XLDFLAGS -Wl,-bE:ruby.imp"
- DLDFLAGS='-brtl -eInit_$(TARGET) -bI:$(topdir)/ruby.imp -bM:SRE -T512 -H512 '"$DLDFLAGS"
- LDFLAGS="-brtl $LDFLAGS"
+ DLDFLAGS='-brtl -bI:$(topdir)/ruby.imp -bM:SRE -T512 -H512 '"$DLDFLAGS"
+ ARCH_FLAGS='-eInit_$(TARGET)'
+ : LDFLAGS="-brtl $LDFLAGS"
: ${ARCHFILE="ruby.imp"}
- TRY_LINK='$(CC) $(LDFLAGS) -oconftest $(INCFLAGS) -I$(hdrdir) $(CPPFLAGS) $(CFLAGS)'
+ TRY_LINK='$(CC) $(DLDFLAGS) -oconftest $(INCFLAGS) -I$(hdrdir) $(CPPFLAGS) $(CFLAGS)'
TRY_LINK="$TRY_LINK"' $(src) $(LIBPATH) $(LOCAL_LIBS) $(LIBS)'
- : ${LIBPATHENV=SHLIB_PATH}
rb_cv_dlopen=yes ;;
human*) : ${DLDFLAGS=''}
@@ -956,7 +927,6 @@ if test "$with_dln_a_out" != yes; then
DLDFLAGS="$DLDFLAGS -L/boot/develop/lib/x86 -lbe -lroot"
;;
esac
- : ${LIBPATHENV=LIBRARY_PATH}
rb_cv_dlopen=yes ;;
nto-qnx*) DLDFLAGS="$DLDFLAGS -L/lib -L/usr/lib -L/usr/local/lib"
: ${LDSHARED='ld -Bshareable -x'}
@@ -965,7 +935,6 @@ if test "$with_dln_a_out" != yes; then
cygwin*|mingw*) : ${LDSHARED="${CC} -shared -s"}
XLDFLAGS="$XLDFLAGS -Wl,--stack,0x02000000"
DLDFLAGS="${DLDFLAGS} -Wl,--enable-auto-import,--export-all"
- : ${LIBPATHENV=""}
rb_cv_dlopen=yes ;;
hiuxmpp) : ${LDSHARED='ld -r'} ;;
atheos*) : ${LDSHARED="$CC -shared"}
@@ -975,19 +944,10 @@ if test "$with_dln_a_out" != yes; then
*) : ${LDSHARED='ld'} ;;
esac
AC_MSG_RESULT($rb_cv_dlopen)
-
- AC_ARG_ENABLE(rpath,
- [ --disable-rpath embed run path into extension libraries.],
- [enable_rpath=$enableval], [enable_rpath="$rb_cv_binary_elf"])
- if test "$enable_rpath" = yes; then
- LIBPATHFLAG=" -L'%1\$-s'"
- RPATHFLAG=" -Wl,-R'%1\$-s'"
- fi
fi
AC_SUBST(LINK_SO)
AC_SUBST(LIBPATHFLAG)
AC_SUBST(RPATHFLAG)
-AC_SUBST(LIBPATHENV, "${LIBPATHENV-LD_LIBRARY_PATH}")
AC_SUBST(TRY_LINK)
dln_a_out_works=no
@@ -1146,16 +1106,12 @@ fi
if test x"$cross_compiling" = xyes; then
test x"$MINIRUBY" = x && MINIRUBY="${RUBY-ruby} -I`pwd` -rfake"
PREP=fake.rb
- RUNRUBY='$(MINIRUBY) -I`cd $(srcdir)/lib; pwd`'
else
MINIRUBY='./miniruby$(EXEEXT)'
- PREP='miniruby$(EXEEXT)'
- RUNRUBY='$(MINIRUBY) $(srcdir)/runruby.rb --extout=$(EXTOUT) --'
+ PREP=''
fi
AC_SUBST(MINIRUBY)
AC_SUBST(PREP)
-AC_SUBST(RUNRUBY)
-AC_SUBST(EXTOUT, [${EXTOUT-.ext}])
FIRSTMAKEFILE=""
LIBRUBY_A='lib$(RUBY_SO_NAME)-static.a'
@@ -1196,7 +1152,7 @@ if test "$enable_shared" = 'yes'; then
sunos4*)
LIBRUBY_ALIASES='lib$(RUBY_SO_NAME).so.$(MAJOR).$(MINOR) lib$(RUBY_SO_NAME).so'
;;
- linux* | gnu* | k*bsd*-gnu | atheos*)
+ linux* | gnu* | k*bsd*-gnu)
LIBRUBY_DLDFLAGS='-Wl,-soname,lib$(RUBY_SO_NAME).so.$(MAJOR).$(MINOR)'
LIBRUBY_ALIASES='lib$(RUBY_SO_NAME).so.$(MAJOR).$(MINOR) lib$(RUBY_SO_NAME).so'
;;
@@ -1212,6 +1168,7 @@ if test "$enable_shared" = 'yes'; then
SOLIBS='$(LIBS)'
LIBRUBY_SO='lib$(RUBY_SO_NAME).so.$(MAJOR)$(MINOR).$(TEENY)'
LIBRUBY_DLDFLAGS='-Wl,-soname,lib$(RUBY_SO_NAME).so.$(MAJOR)$(MINOR)'
+ LIBRUBYARG_SHARED='-Wl,-R -Wl,${libdir} -L${libdir} -L. -l$(RUBY_SO_NAME)'
if test "$rb_cv_binary_elf" = yes; then # ELF platforms
LIBRUBY_ALIASES='lib$(RUBY_SO_NAME).so.$(MAJOR)$(MINOR) lib$(RUBY_SO_NAME).so'
else # a.out platforms
@@ -1223,14 +1180,6 @@ if test "$enable_shared" = 'yes'; then
LIBRUBY_SO='lib$(RUBY_INSTALL_NAME).so.$(MAJOR).'`expr ${MINOR} \* 10 + ${TEENY}`
;;
solaris*)
- SOLIBS='$(LIBS)'
- LIBRUBY_SO='lib$(RUBY_SO_NAME).so.$(MAJOR)'
- LIBRUBY_ALIASES='lib$(RUBY_SO_NAME).so.$(MAJOR).$(MINOR).$(TEENY) lib$(RUBY_SO_NAME).so'
- if test "$GCC" = yes; then
- LIBRUBY_DLDFLAGS="$DLDFLAGS "'-Wl,-h,$(@F)'
- else
- enable_rpath=no
- fi
XLDFLAGS="$XLDFLAGS "'-R${libdir}'
;;
hpux*)
@@ -1262,6 +1211,10 @@ if test "$enable_shared" = 'yes'; then
LIBRUBY_DLDFLAGS='-install_name $(libdir)/lib$(RUBY_SO_NAME).dylib -current_version $(MAJOR).$(MINOR).$(TEENY) -compatibility_version $(MAJOR).$(MINOR)'
LIBRUBY_ALIASES='lib$(RUBY_SO_NAME).$(MAJOR).$(MINOR).dylib lib$(RUBY_SO_NAME).dylib'
;;
+ atheos*)
+ LIBRUBY_DLDFLAGS='-Wl,-soname,lib$(RUBY_SO_NAME).so.$(MAJOR).$(MINOR)'
+ LIBRUBY_ALIASES='lib$(RUBY_SO_NAME).so.$(MAJOR).$(MINOR) lib$(RUBY_SO_NAME).so'
+ ;;
interix*)
LIBRUBYARG_SHARED='-L${libdir} -L. -l$(RUBY_SO_NAME)'
;;
@@ -1269,10 +1222,6 @@ if test "$enable_shared" = 'yes'; then
;;
esac
fi
-if test "$enable_rpath" = yes; then
- LIBRUBYARG_SHARED='-Wl,-R -Wl,$(libdir) -L$(libdir) -L. '"$LIBRUBYARG_SHARED"
-fi
-
XLDFLAGS="$XLDFLAGS -L."
AC_SUBST(ARCHFILE)
@@ -1346,17 +1295,18 @@ case "$target_os" in
AC_LIBOBJ([strftime])
;;
mingw*)
- RUBY_SO_NAME=${rb_cv_msvcrt}-'$(RUBY_INSTALL_NAME)'${MAJOR}${MINOR}
+ RUBY_SO_NAME=msvcrt-'$(RUBY_INSTALL_NAME)'${MAJOR}${MINOR}
if test x"$enable_shared" = xyes; then
LIBRUBY_SO='$(RUBY_SO_NAME)'.dll
LIBRUBY='lib$(LIBRUBY_SO).a'
fi
AC_LIBOBJ([win32])
COMMON_LIBS=m
-# COMMON_MACROS="WIN32_LEAN_AND_MEAN="
+ COMMON_MACROS="WIN32_LEAN_AND_MEAN="
COMMON_HEADERS="windows.h winsock.h"
;;
esac
+ XCFLAGS="$XCFLAGS"
LIBRUBY_DLDFLAGS="${DLDFLAGS}"' -Wl,--out-implib=$(LIBRUBY)'
LIBRUBY_ALIASES=''
FIRSTMAKEFILE=GNUmakefile:cygwin/GNUmakefile.in
@@ -1366,7 +1316,6 @@ case "$target_os" in
LIBRUBY='lib$(RUBY_SO_NAME).a'
LIBRUBYARG='-l$(RUBY_SO_NAME)'
fi
- MINIOBJS=dmydln.o
;;
hpux*)
case "$YACC" in
@@ -1375,7 +1324,6 @@ case "$target_os" in
YACC="$YACC -Nl40000 -Nm40000"
;;
esac
- MINIOBJS=dmydln.o
;;
*)
;;
@@ -1408,7 +1356,6 @@ AC_SUBST(COMMON_LIBS)
AC_SUBST(COMMON_MACROS)
AC_SUBST(COMMON_HEADERS)
AC_SUBST(EXPORT_PREFIX)
-AC_SUBST(MINIOBJS)
MAKEFILES="Makefile `echo $FIRSTMAKEFILE | sed 's/:.*//'`"
MAKEFILES="`echo $MAKEFILES`"
@@ -1479,7 +1426,7 @@ else
fi
case "$target_os" in
- mingw*) sitearch="i386-$rb_cv_msvcrt" ;;
+ mingw*) sitearch="i386-msvcrt" ;;
*) sitearch="${arch}" ;;
esac
@@ -1523,10 +1470,5 @@ else
fi
: > confdefs.h
-AC_CONFIG_FILES($FIRSTMAKEFILE)
-AC_CONFIG_FILES(Makefile, [{
- echo; test x"$EXEEXT" = x || echo 'miniruby: miniruby$(EXEEXT)'
- test "$RUBY_INSTALL_NAME$EXEEXT" = ruby || echo 'ruby: $(PROGRAM);'
- sed ['s/{\$([^(){}]*)[^{}]*}//g'] ${srcdir}/common.mk
-} >> Makefile], [RUBY_INSTALL_NAME=$RUBY_INSTALL_NAME EXEEXT=$EXEEXT])
+AC_CONFIG_FILES([$FIRSTMAKEFILE Makefile])
AC_OUTPUT
diff --git a/cygwin/GNUmakefile.in b/cygwin/GNUmakefile.in
index 03208df11c..da9efaab47 100644
--- a/cygwin/GNUmakefile.in
+++ b/cygwin/GNUmakefile.in
@@ -1,14 +1,11 @@
include Makefile
ENABLE_SHARED=@ENABLE_SHARED@
-DLLWRAP = @DLLWRAP@ --target=@target_os@
ifeq (@target_os@,cygwin)
DLL_BASE_NAME := $(subst .dll,,$(LIBRUBY_SO))
else
DLL_BASE_NAME := $(RUBY_SO_NAME)
- DLLWRAP += -mno-cygwin
- VPATH += $(srcdir)/win32
endif
ifneq ($(ENABLE_SHARED),yes)
@@ -27,10 +24,6 @@ endif
WPROGRAM = $(RUBYW_INSTALL_NAME)$(EXEEXT)
SOLIBS := $(DLL_BASE_NAME).res.@OBJEXT@ $(SOLIBS)
EXTOBJS += $(@:$(EXEEXT)=.res.@OBJEXT@)
-RCFILES = $(RUBY_INSTALL_NAME).rc $(RUBYW_INSTALL_NAME).rc $(DLL_BASE_NAME).rc
-
-ruby: $(PROGRAM)
-rubyw: $(WPROGRAM)
$(LIBRUBY): $(RUBY_EXP) $(LIBRUBY_SO)
$(RUBY_EXP) $(LIBRUBY_SO): $(DLL_BASE_NAME).res.@OBJEXT@
@@ -38,7 +31,7 @@ $(RUBY_EXP) $(LIBRUBY_SO): $(DLL_BASE_NAME).res.@OBJEXT@
%.res.@OBJEXT@: %.rc
@WINDRES@ --include-dir . --include-dir $(<D) --include-dir $(srcdir)/win32 $< $@
-$(RCFILES): $(RBCONFIG)
+$(RUBY_INSTALL_NAME).rc $(RUBYW_INSTALL_NAME).rc $(DLL_BASE_NAME).rc: rbconfig.rb
@$(MINIRUBY) $(srcdir)/win32/resource.rb \
-ruby_name=$(RUBY_INSTALL_NAME) -rubyw_name=$(RUBYW_INSTALL_NAME) \
-so_name=$(DLL_BASE_NAME) \
@@ -51,7 +44,7 @@ $(WPROGRAM): $(RUBYW_INSTALL_NAME).res.@OBJEXT@
$(MAINOBJ) $(EXTOBJS) $(LIBRUBYARG) $(LIBS) -o $@
$(RUBY_EXP): $(LIBRUBY_A)
- $(DLLWRAP) \
+ @DLLWRAP@ --target=@target_os@ --driver-name=$(CC) \
--output-exp=$(RUBY_EXP) \
--export-all $(LIBRUBY_A) $(LIBS) -o $(PROGRAM)
$(LDSHARED) $(DLDFLAGS) $(OBJS) dmyext.o $(SOLIBS) -o $(PROGRAM)
@@ -70,9 +63,3 @@ cygwin-$(RUBY_INSTALL_NAME)$(MAJOR)$(MINOR).dll: $(LIBRUBY_A)
@DLLWRAP@ -s --def=rubydll.def -o $@
@rm -f rubydll.def
endif
-
-clean-local::
- @$(RM) $(RUBY_EXP) $(RCFILES:.rc=.res.@OBJEXT@)
-
-distclean-local::
- @$(RM) $(RCFILES)
diff --git a/defines.h b/defines.h
index fb221da81d..77f3f40a55 100644
--- a/defines.h
+++ b/defines.h
@@ -176,6 +176,7 @@ void xfree _((void*));
#ifndef X_OK
#define X_OK 1
#endif
+typedef int pid_t;
#endif /* __APPLE__ */
#endif /* NeXT */
@@ -184,15 +185,18 @@ void xfree _((void*));
#endif
#if defined(__VMS)
-#include "vms.h"
+#include "vms/vms.h"
#endif
#if defined(__BEOS__)
#include <net/socket.h> /* intern.h needs fd_set definition */
#endif
-#ifdef RUBY_EXPORT
#undef RUBY_EXTERN
+#if defined _WIN32 && !defined __GNUC__
+# ifndef RUBY_EXPORT
+# define RUBY_EXTERN extern __declspec(dllimport)
+# endif
#endif
#ifndef RUBY_EXTERN
@@ -221,13 +225,6 @@ flush_register_windows(void)
;
}
# define FLUSH_REGISTER_WINDOWS flush_register_windows()
-#elif defined(__ia64__)
-void flush_register_windows(void)
-# if defined(__GNUC__) && (( __GNUC__ == 3 && __GNUC_MINOR__ > 0 ) || __GNUC__ > 3)
-__attribute__ ((noinline))
-# endif
- ;
-# define FLUSH_REGISTER_WINDOWS flush_register_windows()
#else
# define FLUSH_REGISTER_WINDOWS ((void)0)
#endif
diff --git a/dir.c b/dir.c
index d058334ac9..2de990ad8a 100644
--- a/dir.c
+++ b/dir.c
@@ -63,8 +63,8 @@ char *strchr _((char*,char));
#include "util.h"
-#if !defined HAVE_LSTAT && !defined lstat
-#define lstat stat
+#ifndef HAVE_LSTAT
+#define lstat(path,st) stat(path,st)
#endif
#define FNM_NOESCAPE 0x01
@@ -303,7 +303,6 @@ dir_initialize(dir, dirname)
* the block, and <code>Dir::open</code> returns the value of the
* block.
*/
-
static VALUE
dir_s_open(klass, dirname)
VALUE klass, dirname;
@@ -409,7 +408,6 @@ dir_each(dir)
struct dirent *dp;
GetDIR(dir, dirp);
- rewinddir(dirp->dir);
for (dp = readdir(dirp->dir); dp != NULL; dp = readdir(dirp->dir)) {
rb_yield(rb_tainted_str_new(dp->d_name, NAMLEN(dp)));
if (dirp->dir == NULL) dir_closed();
@@ -465,11 +463,10 @@ dir_seek(dir, pos)
VALUE dir, pos;
{
struct dir_data *dirp;
- off_t p = NUM2OFFT(pos);
- GetDIR(dir, dirp);
#ifdef HAVE_SEEKDIR
- seekdir(dirp->dir, p);
+ GetDIR(dir, dirp);
+ seekdir(dirp->dir, NUM2INT(pos));
return dir;
#else
rb_notimplement();
@@ -760,8 +757,13 @@ dir_s_mkdir(argc, argv, obj)
}
check_dirname(&path);
+#ifndef _WIN32
if (mkdir(RSTRING(path)->ptr, mode) == -1)
rb_sys_fail(RSTRING(path)->ptr);
+#else
+ if (mkdir(RSTRING(path)->ptr) == -1)
+ rb_sys_fail(RSTRING(path)->ptr);
+#endif
return INT2FIX(0);
}
@@ -786,10 +788,6 @@ dir_s_rmdir(obj, dir)
return INT2FIX(0);
}
-#define GLOB_VERBOSE (1 << (sizeof(int) * CHAR_BIT - 1))
-#define sys_warning(val) \
- ((flags & GLOB_VERBOSE) && rb_protect((VALUE (*)_((VALUE)))rb_sys_warning, (VALUE)(val), 0))
-
/* Return nonzero if S has any special globbing chars in it. */
static int
has_magic(s, send, flags)
@@ -894,67 +892,63 @@ glob_func_caller(val)
VALUE val;
{
struct glob_args *args = (struct glob_args *)val;
-
(*args->func)(args->c, args->v);
return Qnil;
}
-#define glob_call_func(func, path, arg) (*func)(path, arg)
+static int
+glob_call_func(func, path, arg)
+ void (*func) _((const char*, VALUE));
+ const char *path;
+ VALUE arg;
+{
+ int status;
+ struct glob_args args;
+
+ args.func = func;
+ args.c = path;
+ args.v = arg;
-static int glob_helper _((const char *path, const char *sub, int flags, int (*func)(const char *,VALUE), VALUE arg));
+ rb_protect(glob_func_caller, (VALUE)&args, &status);
+ return status;
+}
static int
glob_helper(path, sub, flags, func, arg)
- const char *path;
- const char *sub;
+ char *path;
+ char *sub;
int flags;
- int (*func) _((const char *, VALUE));
+ void (*func) _((const char*, VALUE));
VALUE arg;
{
struct stat st;
- const char *p, *m;
+ char *p, *m;
int status = 0;
- char *buf = 0;
- char *newpath = 0;
p = sub ? sub : path;
if (!has_magic(p, 0, flags)) {
- if (
#if defined DOSISH
- TRUE
+ remove_backslashes(path);
#else
- !(flags & FNM_NOESCAPE)
+ if (!(flags & FNM_NOESCAPE)) remove_backslashes(p);
#endif
- )
- {
- newpath = strdup(path);
- if (sub) {
- p = newpath + (sub - path);
- remove_backslashes(newpath + (sub - path));
- sub = p;
- }
- else {
- remove_backslashes(newpath);
- p = path = newpath;
- }
- }
if (lstat(path, &st) == 0) {
status = glob_call_func(func, path, arg);
+ if (status) return status;
}
else if (errno != ENOENT) {
/* In case stat error is other than ENOENT and
we may want to know what is wrong. */
- sys_warning(path);
+ rb_sys_warning(path);
}
- xfree(newpath);
- return status;
+ return 0;
}
while (p && !status) {
if (*p == '/') p++;
m = strchr(p, '/');
if (has_magic(p, m, flags)) {
- char *dir, *base, *magic;
+ char *dir, *base, *magic, *buf;
DIR *dirp;
struct dirent *dp;
int recursive = 0;
@@ -970,8 +964,7 @@ glob_helper(path, sub, flags, func, arg)
magic = extract_elem(p);
if (stat(dir, &st) < 0) {
- if (errno != ENOENT)
- sys_warning(dir);
+ if (errno != ENOENT) rb_sys_warning(dir);
free(base);
free(magic);
break;
@@ -980,14 +973,15 @@ glob_helper(path, sub, flags, func, arg)
if (m && strcmp(magic, "**") == 0) {
int n = strlen(base);
recursive = 1;
- REALLOC_N(buf, char, n+strlen(m)+3);
+ buf = ALLOC_N(char, n+strlen(m)+3);
sprintf(buf, "%s%s", base, *base ? m : m+1);
status = glob_helper(buf, buf+n, flags, func, arg);
+ free(buf);
if (status) goto finalize;
}
dirp = opendir(dir);
if (dirp == NULL) {
- sys_warning(dir);
+ rb_sys_warning(dir);
free(base);
free(magic);
break;
@@ -1011,11 +1005,11 @@ glob_helper(path, sub, flags, func, arg)
continue;
if (fnmatch("*", dp->d_name, flags) != 0)
continue;
- REALLOC_N(buf, char, strlen(base)+NAMLEN(dp)+strlen(m)+6);
+ buf = ALLOC_N(char, strlen(base)+NAMLEN(dp)+strlen(m)+6);
sprintf(buf, "%s%s%s", base, (BASE) ? "/" : "", dp->d_name);
if (lstat(buf, &st) < 0) {
- if (errno != ENOENT)
- sys_warning(buf);
+ if (errno != ENOENT) rb_sys_warning(buf);
+ free(buf);
continue;
}
if (S_ISDIR(st.st_mode)) {
@@ -1023,22 +1017,24 @@ glob_helper(path, sub, flags, func, arg)
strcpy(t, "/**");
strcpy(t+3, m);
status = glob_helper(buf, t, flags, func, arg);
+ free(buf);
if (status) break;
continue;
}
+ free(buf);
continue;
}
if (fnmatch(magic, dp->d_name, flags) == 0) {
- REALLOC_N(buf, char, strlen(base)+NAMLEN(dp)+2);
+ buf = ALLOC_N(char, strlen(base)+NAMLEN(dp)+2);
sprintf(buf, "%s%s%s", base, (BASE) ? "/" : "", dp->d_name);
if (!m) {
status = glob_call_func(func, buf, arg);
+ free(buf);
if (status) break;
continue;
}
tmp = ALLOC(struct d_link);
tmp->path = buf;
- buf = 0;
*tail = tmp;
tail = &tmp->next;
}
@@ -1055,14 +1051,15 @@ glob_helper(path, sub, flags, func, arg)
if (S_ISDIR(st.st_mode)) {
int len = strlen(link->path);
int mlen = strlen(m);
+ char *t = ALLOC_N(char, len+mlen+1);
- REALLOC_N(buf, char, len+mlen+1);
- sprintf(buf, "%s%s", link->path, m);
- status = glob_helper(buf, buf+len, flags, func, arg);
+ sprintf(t, "%s%s", link->path, m);
+ status = glob_helper(t, t+len, flags, func, arg);
+ free(t);
}
}
else {
- sys_warning(link->path);
+ rb_sys_warning(link->path);
}
}
tmp = link;
@@ -1075,43 +1072,6 @@ glob_helper(path, sub, flags, func, arg)
}
p = m;
}
- xfree(buf);
- xfree(newpath);
- return status;
-}
-
-int
-ruby_glob(path, flags, func, arg)
- const char *path;
- int flags;
- int (*func) _((const char *, VALUE));
- VALUE arg;
-{
- return glob_helper(path, 0, flags & ~GLOB_VERBOSE, func, arg);
-}
-
-int
-ruby_globi(path, flags, func, arg)
- const char *path;
- int flags;
- int (*func) _((const char *, VALUE));
- VALUE arg;
-{
- return glob_helper(path, 0, flags | FNM_CASEFOLD, func, arg);
-}
-
-static int rb_glob_caller _((const char *, VALUE));
-
-static int
-rb_glob_caller(path, a)
- const char *path;
- VALUE a;
-{
- int status;
- struct glob_args *args = (struct glob_args *)a;
-
- args->c = path;
- rb_protect(glob_func_caller, a, &status);
return status;
}
@@ -1119,15 +1079,17 @@ static int
rb_glob2(path, flags, func, arg)
const char *path;
int flags;
- void (*func) _((const char *, VALUE));
+ void (*func) _((const char*, VALUE));
VALUE arg;
{
- struct glob_args args;
-
- args.func = func;
- args.v = arg;
+ char *buf;
+ int status;
- return glob_helper(path, 0, flags | GLOB_VERBOSE, rb_glob_caller, (VALUE)&args);
+ buf = ALLOC_N(char, strlen(path)+1);
+ strcpy(buf, path);
+ status = glob_helper(buf, 0, flags, func, arg);
+ free(buf);
+ return status;
}
void
@@ -1137,6 +1099,7 @@ rb_glob(path, func, arg)
VALUE arg;
{
int status = rb_glob2(path, 0, func, arg);
+
if (status) rb_jump_tag(status);
}
@@ -1147,6 +1110,7 @@ rb_globi(path, func, arg)
VALUE arg;
{
int status = rb_glob2(path, FNM_CASEFOLD, func, arg);
+
if (status) rb_jump_tag(status);
}
@@ -1168,19 +1132,18 @@ push_globs(ary, s, flags)
}
static int
-push_braces(ary, str, flags)
+push_braces(ary, s, flags)
VALUE ary;
- const char *str;
+ const char *s;
int flags;
{
- char *buf = 0;
- char *b;
- const char *s, *p, *t;
+ char *buf, *b;
+ const char *p, *t;
const char *lbrace, *rbrace;
int nest = 0;
int status = 0;
- s = p = str;
+ p = s;
lbrace = rbrace = 0;
while (*p) {
if (*p == '{') {
@@ -1200,31 +1163,26 @@ push_braces(ary, str, flags)
if (lbrace && rbrace) {
int len = strlen(s);
+ buf = xmalloc(len + 1);
+ memcpy(buf, s, lbrace-s);
+ b = buf + (lbrace-s);
p = lbrace;
while (*p != '}') {
t = p + 1;
for (p = t; *p!='}' && *p!=','; p++) {
/* skip inner braces */
- if (*p == '{') {
- nest = 1;
- while (*++p != '}' || --nest) {
- if (*p == '{') nest++;
- }
- }
+ if (*p == '{') while (*p!='}') p++;
}
- REALLOC_N(buf, char, len+1);
- memcpy(buf, s, lbrace-s);
- b = buf + (lbrace-s);
memcpy(b, t, p-t);
strcpy(b+(p-t), rbrace+1);
status = push_braces(ary, buf, flags);
if (status) break;
}
+ free(buf);
}
else {
- status = push_globs(ary, str, flags);
+ status = push_globs(ary, s, flags);
}
- xfree(buf);
return status;
}
@@ -1236,7 +1194,9 @@ rb_push_glob(str, flags)
VALUE str;
int flags;
{
- const char *p, *pend, *buf;
+ const char *p, *pend;
+ char *buf;
+ char *t;
int nest, maxnest;
int status = 0;
int noescape = flags & FNM_NOESCAPE;
@@ -1244,21 +1204,25 @@ rb_push_glob(str, flags)
ary = rb_ary_new();
SafeStringValue(str);
+ buf = xmalloc(RSTRING(str)->len + 1);
+
p = RSTRING(str)->ptr;
pend = p + RSTRING(str)->len;
while (p < pend) {
+ t = buf;
nest = maxnest = 0;
while (p < pend && isdelim(*p)) p++;
- buf = p;
while (p < pend && !isdelim(*p)) {
if (*p == '{') nest++, maxnest++;
if (*p == '}') nest--;
if (!noescape && *p == '\\') {
- if (++p == pend) break;
+ *t++ = *p++;
+ if (p == pend) break;
}
- p++;
+ *t++ = *p++;
}
+ *t = '\0';
if (maxnest == 0) {
status = push_globs(ary, buf, flags);
if (status) break;
@@ -1269,7 +1233,10 @@ rb_push_glob(str, flags)
}
/* else unmatched braces */
}
+ free(buf);
+
if (status) rb_jump_tag(status);
+
if (rb_block_given_p()) {
rb_ary_each(ary);
return Qnil;
@@ -1295,38 +1262,14 @@ dir_s_aref(obj, str)
/*
* call-seq:
* Dir.glob( string, [flags] ) => array
- * Dir.glob( string, [flags] ) {| filename | block } => nil
+ * Dir.glob( string, [flags] ) {| filename | block } => false
*
* Returns the filenames found by expanding the pattern given in
* <i>string</i>, either as an <i>array</i> or as parameters to the
* block. Note that this pattern is not a regexp (it's closer to a
- * shell glob). See <code>File::fnmatch</code> for the meaning of
- * the <i>flags</i> parameter.
- *
- * <code>*</code>:: Matches any file. Can be restricted by
- * other values in the glob. <code>*</code>
- * will match all files; <code>c*</code> will
- * match all files beginning with
- * <code>c</code>; <code>*c</code> will match
- * all files ending with <code>c</code>; and
- * <code>*c*</code> will match all files that
- * have <code>c</code> in them (including at
- * the beginning or end). Equivalent to
- * <code>/ .* /x</code> in regexp.
- * <code>**</code>:: Matches directories recursively.
- * <code>?</code>:: Matches any one character. Equivalent to
- * <code>/.{1}/</code> in regexp.
- * <code>[set]</code>:: Matches any one character in +set+.
- * Behaves exactly like character sets in
- * Regexp, including set negation
- * (<code>[^a-z]</code>).
- * <code>{p,q}</code>:: Matches either literal <code>p</code> or
- * literal <code>q</code>. Matching literals
- * may be more than one character in length.
- * More than two literals may be specified.
- * Equivalent to pattern alternation in
- * regexp.
- * <code>\</code>:: Escapes the next metacharacter.
+ * shell glob). See <code>File::fnmatch</code> for
+ * details of file name matching and the meaning of the <i>flags</i>
+ * parameter.
*
* Dir["config.?"] #=> ["config.h"]
* Dir.glob("config.?") #=> ["config.h"]
@@ -1336,19 +1279,6 @@ dir_s_aref(obj, str)
* Dir.glob("*") #=> ["config.h", "main.rb"]
* Dir.glob("*", File::FNM_DOTMATCH) #=> [".", "..", "config.h", "main.rb"]
*
- * rbfiles = File.join("**", "*.rb")
- * Dir.glob(rbfiles) #=> ["main.rb",
- * "lib/song.rb",
- * "lib/song/karaoke.rb"]
- * libdirs = File.join("**", "lib")
- * Dir.glob(libdirs) #=> ["lib"]
- *
- * librbfiles = File.join("**", "lib", "**", "*.rb")
- * Dir.glob(librbfiles) #=> ["lib/song.rb",
- * "lib/song/karaoke.rb"]
- *
- * librbfiles = File.join("**", "lib", "*.rb")
- * Dir.glob(librbfiles) #=> ["lib/song.rb"]
*/
static VALUE
dir_s_glob(argc, argv, obj)
@@ -1367,21 +1297,6 @@ dir_s_glob(argc, argv, obj)
return rb_push_glob(str, flags);
}
-static VALUE
-dir_open_dir(path)
- VALUE path;
-{
- VALUE dir = rb_funcall(rb_cDir, rb_intern("open"), 1, path);
-
- if (TYPE(dir) != T_DATA ||
- RDATA(dir)->dfree != (RUBY_DATA_FUNC)free_dir) {
- rb_raise(rb_eTypeError, "wrong argument type %s (expected Dir)",
- rb_obj_classname(dir));
- }
- return dir;
-}
-
-
/*
* call-seq:
* Dir.foreach( dirname ) {| filename | block } => nil
@@ -1405,7 +1320,7 @@ dir_foreach(io, dirname)
{
VALUE dir;
- dir = dir_open_dir(dirname);
+ dir = rb_funcall(rb_cDir, rb_intern("open"), 1, dirname);
rb_ensure(dir_each, dir, dir_close, dir);
return Qnil;
}
@@ -1427,7 +1342,7 @@ dir_entries(io, dirname)
{
VALUE dir;
- dir = dir_open_dir(dirname);
+ dir = rb_funcall(rb_cDir, rb_intern("open"), 1, dirname);
return rb_ensure(rb_Array, dir, dir_close, dir);
}
@@ -1441,27 +1356,8 @@ dir_entries(io, dirname)
* similar to shell filename globbing. It may contain the following
* metacharacters:
*
- * <code>*</code>:: Matches any file. Can be restricted by
- * other values in the glob. <code>*</code>
- * will match all files; <code>c*</code> will
- * match all files beginning with
- * <code>c</code>; <code>*c</code> will match
- * all files ending with <code>c</code>; and
- * <code>*c*</code> will match all files that
- * have <code>c</code> in them (including at
- * the beginning or end). Equivalent to
- * <code>/ .* /x</code> in regexp.
- * <code>?</code>:: Matches any one character. Equivalent to
- * <code>/.{1}/</code> in regexp.
- * <code>[set]</code>:: Matches any one character in +set+.
- * Behaves exactly like character sets in
- * Regexp, including set negation
- * (<code>[^a-z]</code>).
- * <code>\</code>:: Escapes the next metacharacter.
- *
- * <i>flags</i> is a bitwise OR of the <code>FNM_xxx</code>
- * parameters. The same glob pattern and flags are used by
- * <code>Dir::glob</code>.
+ * <i>flags</i> is a bitwise OR of the <code>FNM_xxx</code> parameters.
+ * The same glob pattern and flags are used by <code>Dir::glob</code>.
*
* File.fnmatch('cat', 'cat') #=> true
* File.fnmatch('cat', 'category') #=> false
diff --git a/dln.c b/dln.c
index 0993a84161..8f0b2a0409 100644
--- a/dln.c
+++ b/dln.c
@@ -91,8 +91,6 @@ char *getenv();
int eaccess();
-#ifndef NO_DLN_LOAD
-
#if defined(HAVE_DLOPEN) && !defined(USE_DLN_A_OUT) && !defined(_AIX) && !defined(__APPLE__) && !defined(_UNICOSMP)
/* dynamic load with dlopen() */
# define USE_DLN_DLOPEN
@@ -162,7 +160,7 @@ static int dln_errno;
#define DLN_ENOEXEC ENOEXEC /* Exec format error */
#define DLN_ECONFL 1201 /* Symbol name conflict */
-#define DLN_ENOINIT 1202 /* No initializer given */
+#define DLN_ENOINIT 1202 /* No inititalizer given */
#define DLN_EUNDEF 1203 /* Undefine symbol remains */
#define DLN_ENOTLIB 1204 /* Not a library file */
#define DLN_EBADLIB 1205 /* Malformed library file */
@@ -397,7 +395,7 @@ dln_init(prog)
if (c != '!') goto err_noexec;
p = buf;
- /* skip forwarding spaces */
+ /* skip forwading spaces */
while (read(fd, &c, 1) == 1) {
if (c == '\n') goto err_noexec;
if (c != '\t' && c != ' ') {
@@ -962,9 +960,8 @@ load_lib(lib)
dln_errno = DLN_EBADLIB;
if (lib[0] == '-' && lib[1] == 'l') {
- long len = strlen(lib) + 4;
- char *p = alloca(len);
- snprintf(p, len, "lib%s.a", lib+2);
+ char *p = alloca(strlen(lib) + 4);
+ sprintf(p, "lib%s.a", lib+2);
lib = p;
}
@@ -1118,7 +1115,7 @@ dln_sym(name)
#endif /* USE_DLN_A_OUT */
#ifdef USE_DLN_DLOPEN
-# if defined(__NetBSD__) && defined(__NetBSD_Version__) && __NetBSD_Version__ < 105000000
+# ifdef __NetBSD__
# include <nlist.h>
# include <link.h>
# else
@@ -1277,16 +1274,10 @@ static int vms_fileact(char *filespec, int type);
static long vms_fisexh(long *sigarr, long *mecarr);
#endif
-#endif /* NO_DLN_LOAD */
-
void*
dln_load(file)
const char *file;
{
-#ifdef NO_DLN_LOAD
- rb_raise(rb_eLoadError, "this executable file can't load extension libraries");
-#else
-
#if !defined(_AIX) && !defined(NeXT)
const char *error = 0;
#define DLN_ERROR() (error = dln_strerror(), strcpy(ALLOCA_N(char, strlen(error) + 1), error))
@@ -1642,8 +1633,6 @@ dln_load(file)
failed:
rb_loaderror("%s - %s", error, file);
#endif
-
-#endif /* NO_DLN_LOAD */
return 0; /* dummy return */
}
diff --git a/dmydln.c b/dmydln.c
deleted file mode 100644
index 09ea06806c..0000000000
--- a/dmydln.c
+++ /dev/null
@@ -1,2 +0,0 @@
-#define NO_DLN_LOAD 1
-#include "dln.c"
diff --git a/doc/irb/irb.rd.ja b/doc/irb/irb.rd.ja
index 338dcc644e..bf8ac5d517 100644
--- a/doc/irb/irb.rd.ja
+++ b/doc/irb/irb.rd.ja
@@ -1,8 +1,8 @@
irb -- interactive ruby
- $Release Version: 0.9.5 $
+ $Release Version: 0.9 $
$Revision$
$Date$
- by Keiju ISHITSUKA(keiju@ruby-lang.org)
+ by Keiju ISHITSUKA(keiju@ishitsuka.com)
=begin
= irb¤È¤Ï?
@@ -112,7 +112,6 @@ irbµ¯Æ°»þ¤Ë``~/.irbrc''¤òÆÉ¤ß¹þ¤ß¤Þ¤¹. ¤â¤·Â¸ºß¤·¤Ê¤¤¾ì¹ç¤Ï,
IRB.conf[:PROMPT][:MY_PROMPT] = { # ¥×¥í¥ó¥×¥È¥â¡¼¥É¤Î̾Á°
:PROMPT_I => nil, # Ä̾ï¤Î¥×¥í¥ó¥×¥È
- :PROMPT_N => nil, # ·Ñ³¹Ô¤Î¥×¥í¥ó¥×¥È
:PROMPT_S => nil, # ʸ»úÎó¤Ê¤É¤Î·Ñ³¹Ô¤Î¥×¥í¥ó¥×¥È
:PROMPT_C => nil, # ¼°¤¬·Ñ³¤·¤Æ¤¤¤ë»þ¤Î¥×¥í¥ó¥×¥È
:RETURN => " ==>%s\n" # ¥ê¥¿¡¼¥ó»þ¤Î¥×¥í¥ó¥×¥È
@@ -127,7 +126,7 @@ OK¤Ç¤¹.
IRB.conf[:PROMPT_MODE] = :MY_PROMPT
-PROMPT_I, PROMPT_N, PROMPT_S, PROMPT_C¤Ï, ¥Õ¥©¡¼¥Þ¥Ã¥È¤ò»ØÄꤷ¤Þ¤¹.
+PROMPT_I, PROMPT_S, PROMPT_C¤Ï, ¥Õ¥©¡¼¥Þ¥Ã¥È¤ò»ØÄꤷ¤Þ¤¹.
%N µ¯Æ°¤·¤Æ¤¤¤ë¥³¥Þ¥ó¥É̾¤¬½ÐÎϤµ¤ì¤ë.
%m main¥ª¥Ö¥¸¥§¥¯¥È(self)¤¬to_s¤Ç½ÐÎϤµ¤ì¤ë.
@@ -142,7 +141,6 @@ PROMPT_I, PROMPT_N, PROMPT_S, PROMPT_C¤Ï, ¥Õ¥©¡¼¥Þ¥Ã¥È¤ò»ØÄꤷ¤Þ¤¹.
IRB.conf[:PROMPT_MODE][:DEFAULT] = {
:PROMPT_I => "%N(%m):%03n:%i> ",
- :PROMPT_N => "%N(%m):%03n:%i> ",
:PROMPT_S => "%N(%m):%03n:%i%l ",
:PROMPT_C => "%N(%m):%03n:%i* ",
:RETURN => "%s\n"
diff --git a/enum.c b/enum.c
index a50de77a90..a745a6e604 100644
--- a/enum.c
+++ b/enum.c
@@ -80,10 +80,11 @@ enum_grep(obj, pat)
static VALUE
find_i(i, memo)
VALUE i;
- VALUE *memo;
+ NODE *memo;
{
if (RTEST(rb_yield(i))) {
- *memo = i;
+ memo->u2.value = Qtrue;
+ memo->u1.value = i;
rb_iter_break();
}
return Qnil;
@@ -110,13 +111,13 @@ enum_find(argc, argv, obj)
VALUE* argv;
VALUE obj;
{
- VALUE memo = Qundef;
+ NODE *memo = rb_node_newnode(NODE_MEMO, Qnil, Qfalse, 0);
VALUE if_none;
rb_scan_args(argc, argv, "01", &if_none);
- rb_iterate(rb_each, obj, find_i, (VALUE)&memo);
- if (memo != Qundef) {
- return memo;
+ rb_iterate(rb_each, obj, find_i, (VALUE)memo);
+ if (memo->u2.value) {
+ return memo->u1.value;
}
if (!NIL_P(if_none)) {
return rb_funcall(if_none, rb_intern("call"), 0, 0);
@@ -256,13 +257,14 @@ enum_to_a(obj)
static VALUE
inject_i(i, memo)
VALUE i;
- VALUE *memo;
+ NODE *memo;
{
- if (*memo == Qundef) {
- *memo = i;
+ if (memo->u2.value) {
+ memo->u2.value = Qfalse;
+ memo->u1.value = i;
}
else {
- *memo = rb_yield_values(2, *memo, i);
+ memo->u1.value = rb_yield_values(2, memo->u1.value, i);
}
return Qnil;
}
@@ -303,13 +305,18 @@ enum_inject(argc, argv, obj)
int argc;
VALUE *argv, obj;
{
- VALUE memo = Qundef;
+ NODE *memo;
+ VALUE n;
- if (rb_scan_args(argc, argv, "01", &memo) == 0)
- memo = Qundef;
- rb_iterate(rb_each, obj, inject_i, (VALUE)&memo);
- if (memo == Qundef) return Qnil;
- return memo;
+ if (rb_scan_args(argc, argv, "01", &n) == 1) {
+ memo = rb_node_newnode(NODE_MEMO, n, Qfalse, 0);
+ }
+ else {
+ memo = rb_node_newnode(NODE_MEMO, Qnil, Qtrue, 0);
+ }
+ rb_iterate(rb_each, obj, inject_i, (VALUE)memo);
+ n = memo->u1.value;
+ return n;
}
static VALUE
@@ -500,10 +507,10 @@ enum_sort_by(obj)
static VALUE
all_iter_i(i, memo)
VALUE i;
- VALUE *memo;
+ NODE *memo;
{
if (!RTEST(rb_yield(i))) {
- *memo = Qfalse;
+ memo->u1.value = Qfalse;
rb_iter_break();
}
return Qnil;
@@ -512,10 +519,10 @@ all_iter_i(i, memo)
static VALUE
all_i(i, memo)
VALUE i;
- VALUE *memo;
+ NODE *memo;
{
if (!RTEST(i)) {
- *memo = Qfalse;
+ memo->u1.value = Qfalse;
rb_iter_break();
}
return Qnil;
@@ -542,19 +549,22 @@ static VALUE
enum_all(obj)
VALUE obj;
{
- VALUE result = Qtrue;
+ VALUE result;
+ NODE *memo = rb_node_newnode(NODE_MEMO, Qnil, 0, 0);
- rb_iterate(rb_each, obj, rb_block_given_p() ? all_iter_i : all_i, (VALUE)&result);
+ memo->u1.value = Qtrue;
+ rb_iterate(rb_each, obj, rb_block_given_p() ? all_iter_i : all_i, (VALUE)memo);
+ result = memo->u1.value;
return result;
}
static VALUE
any_iter_i(i, memo)
VALUE i;
- VALUE *memo;
+ NODE *memo;
{
if (RTEST(rb_yield(i))) {
- *memo = Qtrue;
+ memo->u1.value = Qtrue;
rb_iter_break();
}
return Qnil;
@@ -563,10 +573,10 @@ any_iter_i(i, memo)
static VALUE
any_i(i, memo)
VALUE i;
- VALUE *memo;
+ NODE *memo;
{
if (RTEST(i)) {
- *memo = Qtrue;
+ memo->u1.value = Qtrue;
rb_iter_break();
}
return Qnil;
@@ -594,26 +604,29 @@ static VALUE
enum_any(obj)
VALUE obj;
{
- VALUE result = Qfalse;
+ VALUE result;
+ NODE *memo = rb_node_newnode(NODE_MEMO, Qnil, 0, 0);
- rb_iterate(rb_each, obj, rb_block_given_p() ? any_iter_i : any_i, (VALUE)&result);
+ memo->u1.value = Qfalse;
+ rb_iterate(rb_each, obj, rb_block_given_p() ? any_iter_i : any_i, (VALUE)memo);
+ result = memo->u1.value;
return result;
}
static VALUE
min_i(i, memo)
VALUE i;
- VALUE *memo;
+ NODE *memo;
{
VALUE cmp;
- if (*memo == Qundef) {
- *memo = i;
+ if (NIL_P(memo->u1.value)) {
+ memo->u1.value = i;
}
else {
- cmp = rb_funcall(i, id_cmp, 1, *memo);
- if (rb_cmpint(cmp, i, *memo) < 0) {
- *memo = i;
+ cmp = rb_funcall(i, id_cmp, 1, memo->u1.value);
+ if (rb_cmpint(cmp, i, memo->u1.value) < 0) {
+ memo->u1.value = i;
}
}
return Qnil;
@@ -622,17 +635,17 @@ min_i(i, memo)
static VALUE
min_ii(i, memo)
VALUE i;
- VALUE *memo;
+ NODE *memo;
{
VALUE cmp;
- if (*memo == Qundef) {
- *memo = i;
+ if (NIL_P(memo->u1.value)) {
+ memo->u1.value = i;
}
else {
- cmp = rb_yield_values(2, i, *memo);
- if (rb_cmpint(cmp, i, *memo) < 0) {
- *memo = i;
+ cmp = rb_yield_values(2, i, memo->u1.value);
+ if (rb_cmpint(cmp, i, memo->u1.value) < 0) {
+ memo->u1.value = i;
}
}
return Qnil;
@@ -657,10 +670,11 @@ static VALUE
enum_min(obj)
VALUE obj;
{
- VALUE result = Qundef;
+ VALUE result;
+ NODE *memo = rb_node_newnode(NODE_MEMO, Qnil, 0, 0);
- rb_iterate(rb_each, obj, rb_block_given_p() ? min_ii : min_i, (VALUE)&result);
- if (result == Qundef) return Qnil;
+ rb_iterate(rb_each, obj, rb_block_given_p() ? min_ii : min_i, (VALUE)memo);
+ result = memo->u1.value;
return result;
}
@@ -681,17 +695,17 @@ enum_min(obj)
static VALUE
max_i(i, memo)
VALUE i;
- VALUE *memo;
+ NODE *memo;
{
VALUE cmp;
- if (*memo == Qundef) {
- *memo = i;
+ if (NIL_P(memo->u1.value)) {
+ memo->u1.value = i;
}
else {
- cmp = rb_funcall(i, id_cmp, 1, *memo);
- if (rb_cmpint(cmp, i, *memo) > 0) {
- *memo = i;
+ cmp = rb_funcall(i, id_cmp, 1, memo->u1.value);
+ if (rb_cmpint(cmp, i, memo->u1.value) > 0) {
+ memo->u1.value = i;
}
}
return Qnil;
@@ -700,17 +714,17 @@ max_i(i, memo)
static VALUE
max_ii(i, memo)
VALUE i;
- VALUE *memo;
+ NODE *memo;
{
VALUE cmp;
- if (*memo == Qundef) {
- *memo = i;
+ if (NIL_P(memo->u1.value)) {
+ memo->u1.value = i;
}
else {
- cmp = rb_yield_values(2, i, *memo);
- if (rb_cmpint(cmp, i, *memo) > 0) {
- *memo = i;
+ cmp = rb_yield_values(2, i, memo->u1.value);
+ if (rb_cmpint(cmp, i, memo->u1.value) > 0) {
+ memo->u1.value = i;
}
}
return Qnil;
@@ -734,20 +748,21 @@ static VALUE
enum_max(obj)
VALUE obj;
{
- VALUE result = Qundef;
+ VALUE result;
+ NODE *memo = rb_node_newnode(NODE_MEMO, Qnil, 0, 0);
- rb_iterate(rb_each, obj, rb_block_given_p() ? max_ii : max_i, (VALUE)&result);
- if (result == Qundef) return Qnil;
+ rb_iterate(rb_each, obj, rb_block_given_p() ? max_ii : max_i, (VALUE)memo);
+ result = memo->u1.value;
return result;
}
static VALUE
member_i(item, memo)
VALUE item;
- VALUE *memo;
+ NODE *memo;
{
- if (rb_equal(item, memo[0])) {
- memo[1] = Qtrue;
+ if (rb_equal(item, memo->u1.value)) {
+ memo->u2.value = Qtrue;
rb_iter_break();
}
return Qnil;
@@ -770,21 +785,21 @@ static VALUE
enum_member(obj, val)
VALUE obj, val;
{
- VALUE memo[2];
+ VALUE result;
+ NODE *memo = rb_node_newnode(NODE_MEMO, val, Qfalse, 0);
- memo[0] = val;
- memo[1] = Qfalse;
rb_iterate(rb_each, obj, member_i, (VALUE)memo);
- return memo[1];
+ result = memo->u2.value;
+ return result;
}
static VALUE
each_with_index_i(val, memo)
VALUE val;
- VALUE *memo;
+ NODE *memo;
{
- rb_yield_values(2, val, INT2FIX(*memo));
- ++*memo;
+ rb_yield_values(2, val, INT2FIX(memo->u3.cnt));
+ memo->u3.cnt++;
return Qnil;
}
@@ -807,21 +822,20 @@ static VALUE
enum_each_with_index(obj)
VALUE obj;
{
- VALUE memo = 0;
+ NODE *memo = rb_node_newnode(NODE_MEMO, 0, 0, 0);
- rb_need_block();
- rb_iterate(rb_each, obj, each_with_index_i, (VALUE)&memo);
+ rb_iterate(rb_each, obj, each_with_index_i, (VALUE)memo);
return obj;
}
static VALUE
zip_i(val, memo)
VALUE val;
- VALUE *memo;
+ NODE *memo;
{
- VALUE result = memo[0];
- VALUE args = memo[1];
- int idx = memo[2]++;
+ VALUE result = memo->u1.value;
+ VALUE args = memo->u2.value;
+ int idx = memo->u3.cnt++;
VALUE tmp;
int i;
@@ -870,15 +884,13 @@ enum_zip(argc, argv, obj)
{
int i;
VALUE result;
- VALUE memo[3];
+ NODE *memo;
for (i=0; i<argc; i++) {
argv[i] = rb_convert_type(argv[i], T_ARRAY, "Array", "to_a");
}
result = rb_block_given_p() ? Qnil : rb_ary_new();
- memo[0] = result;
- memo[1] = rb_ary_new4(argc, argv);
- memo[2] = 0;
+ memo = rb_node_newnode(NODE_MEMO, result, rb_ary_new4(argc, argv), 0);
rb_iterate(rb_each, obj, zip_i, (VALUE)memo);
return result;
diff --git a/error.c b/error.c
index febaad2c87..c67fce9d34 100644
--- a/error.c
+++ b/error.c
@@ -553,7 +553,7 @@ exit_initialize(argc, argv, exc)
status = *argv++;
--argc;
}
- rb_call_super(argc, argv);
+ exc_initialize(argc, argv, exc);
rb_iv_set(exc, "status", status);
return exc;
}
@@ -633,7 +633,7 @@ name_err_initialize(argc, argv, self)
VALUE name;
name = (argc > 1) ? argv[--argc] : Qnil;
- rb_call_super(argc, argv);
+ exc_initialize(argc, argv, self);
rb_iv_set(self, "name", name);
return self;
}
@@ -678,7 +678,7 @@ name_err_to_s(exc)
* call-seq:
* NoMethodError.new(msg, name [, args]) => no_method_error
*
- * Construct a NoMethodError exception for a method of the given name
+ * Contruct a NoMethodError exception for a method of the given name
* called with the given arguments. The name may be accessed using
* the <code>#name</code> method on the resulting object, and the
* arguments using the <code>#args</code> method.
@@ -907,19 +907,16 @@ syserr_initialize(argc, argv, self)
else err = "unknown error";
if (!NIL_P(mesg)) {
VALUE str = mesg;
- size_t len;
-
StringValue(str);
- len = strlen(err)+RSTRING(str)->len+3;
- mesg = rb_str_new(0, len);
- snprintf(RSTRING(mesg)->ptr, len+1, "%s - %.*s", err,
+ mesg = rb_str_new(0, strlen(err)+RSTRING(mesg)->len+3);
+ sprintf(RSTRING(mesg)->ptr, "%s - %.*s", err,
(int)RSTRING(str)->len, RSTRING(str)->ptr);
rb_str_resize(mesg, strlen(RSTRING(mesg)->ptr));
}
else {
mesg = rb_str_new2(err);
}
- rb_call_super(1, &mesg);
+ exc_initialize(1, &mesg, self);
rb_iv_set(self, "errno", error);
return self;
}
@@ -1083,7 +1080,7 @@ void
rb_notimplement()
{
rb_raise(rb_eNotImpError,
- "the %s() function is unimplemented on this machine",
+ "The %s() function is unimplemented on this machine",
rb_id2name(ruby_frame->last_func));
}
@@ -1111,6 +1108,7 @@ void
rb_sys_fail(mesg)
const char *mesg;
{
+ extern int errno;
int n = errno;
VALUE arg;
diff --git a/eval.c b/eval.c
index e1d2c94ca2..043f349bbd 100644
--- a/eval.c
+++ b/eval.c
@@ -32,8 +32,9 @@
#if defined(HAVE_GETCONTEXT) && defined(HAVE_SETCONTEXT)
#include <ucontext.h>
#define USE_CONTEXT
-#endif
+#else
#include <setjmp.h>
+#endif
#include "st.h"
#include "dln.h"
@@ -87,16 +88,14 @@ char *strrchr _((const char*,const char));
#include "macruby_private.h"
#endif
-#ifdef __VMS
-#include "vmsruby_private.h"
-#endif
-
#ifdef USE_CONTEXT
typedef struct {
ucontext_t context;
volatile int status;
} rb_jmpbuf_t[1];
+#undef longjmp
+#undef setjmp
NORETURN(static void rb_jump_context(rb_jmpbuf_t, int));
static inline void
rb_jump_context(env, val)
@@ -107,63 +106,15 @@ rb_jump_context(env, val)
setcontext(&env->context);
abort(); /* ensure noreturn */
}
-/*
- * FUNCTION_CALL_MAY_RETURN_TWICE is a magic for getcontext, gcc,
- * IA64 register stack and SPARC register window combination problem.
- *
- * Assume following code sequence.
- *
- * 1. set a register in the register stack/window such as r32/l0.
- * 2. call getcontext.
- * 3. use the register.
- * 4. update the register for other use.
- * 5. call setcontext indirectly (or directly).
- *
- * This code should be run as 1->2->3->4->5->3->4.
- * But after second getcontext return (second 3),
- * the register is broken (updated).
- * It's because getcontext/setcontext doesn't preserve the content of the
- * register stack/window.
- *
- * setjmp also doesn't preserve the content of the register stack/window.
- * But it has not the problem because gcc knows setjmp may return twice.
- * gcc detects setjmp and generates setjmp safe code.
- *
- * So setjmp call before getcontext call makes the code somewhat safe.
- * It fix the problem on IA64.
- * It is not required that setjmp is called at run time, since the problem is
- * register usage.
- *
- * Since the magic setjmp is not enough for SPARC,
- * inline asm is used to prohibit registers in register windows.
- */
-#if defined (__GNUC__) && (defined(sparc) || defined(__sparc__))
-#define FUNCTION_CALL_MAY_RETURN_TWICE \
- ({ __asm__ volatile ("" : : : \
- "%o0", "%o1", "%o2", "%o3", "%o4", "%o5", "%o7", \
- "%l0", "%l1", "%l2", "%l3", "%l4", "%l5", "%l6", "%l7", \
- "%i0", "%i1", "%i2", "%i3", "%i4", "%i5", "%i7"); })
-#else
-static jmp_buf function_call_may_return_twice_jmp_buf;
-int function_call_may_return_twice_false = 0;
-#define FUNCTION_CALL_MAY_RETURN_TWICE \
- (function_call_may_return_twice_false ? \
- setjmp(function_call_may_return_twice_jmp_buf) : \
- 0)
-#endif
-#define ruby_longjmp(env, val) rb_jump_context(env, val)
-#define ruby_setjmp(j) ((j)->status = 0, \
- FUNCTION_CALL_MAY_RETURN_TWICE, \
- getcontext(&(j)->context), \
- (j)->status)
+#define longjmp(env, val) rb_jump_context(env, val)
+#define setjmp(j) ((j)->status = 0, getcontext(&(j)->context), (j)->status)
#else
typedef jmp_buf rb_jmpbuf_t;
-#if !defined(setjmp) && defined(HAVE__SETJMP)
-#define ruby_setjmp(env) _setjmp(env)
-#define ruby_longjmp(env,val) _longjmp(env,val)
-#else
-#define ruby_setjmp(env) setjmp(env)
-#define ruby_longjmp(env,val) longjmp(env,val)
+#ifndef setjmp
+#ifdef HAVE__SETJMP
+#define setjmp(env) _setjmp(env)
+#define longjmp(env,val) _longjmp(env,val)
+#endif
#endif
#endif
@@ -361,12 +312,7 @@ rb_clear_cache_by_class(klass)
static ID init, eqq, each, aref, aset, match, missing;
static ID added, singleton_added;
-static ID __id__, __send__, respond_to;
-
-#define NOEX_TAINTED 8
-#define NOEX_SAFE(n) ((n) >> 4)
-#define NOEX_WITH(n, v) ((n) | (v) << 4)
-#define NOEX_WITH_SAFE(n) NOEX_WITH(n, ruby_safe_level)
+static ID __id__, __send__;
void
rb_add_method(klass, mid, node, noex)
@@ -394,7 +340,7 @@ rb_add_method(klass, mid, node, noex)
}
if (OBJ_FROZEN(klass)) rb_error_frozen("class/module");
rb_clear_cache_by_id(mid);
- body = NEW_METHOD(node, NOEX_WITH_SAFE(noex));
+ body = NEW_METHOD(node, noex);
st_insert(RCLASS(klass)->m_tbl, mid, (st_data_t)body);
if (node && mid != ID_ALLOCATOR && ruby_running) {
if (FL_TEST(klass, FL_SINGLETON)) {
@@ -588,7 +534,7 @@ rb_enable_super(klass, name)
VALUE klass;
const char *name;
{
- rb_warn("rb_enable_super() is obsolete");
+ rb_warning("rb_enable_super() is obsolete");
}
static void
@@ -655,7 +601,6 @@ rb_attr(klass, id, read, write, ex)
char *buf;
ID attriv;
int noex;
- size_t len;
if (!ex) noex = NOEX_PUBLIC;
else {
@@ -673,22 +618,20 @@ rb_attr(klass, id, read, write, ex)
}
}
- if (!rb_is_local_id(id) && !rb_is_const_id(id)) {
- rb_name_error(id, "invalid attribute name `%s'", rb_id2name(id));
- }
name = rb_id2name(id);
if (!name) {
rb_raise(rb_eArgError, "argument needs to be symbol or string");
}
- len = strlen(name)+2;
- buf = ALLOCA_N(char,len);
- snprintf(buf, len, "@%s", name);
+ buf = ALLOCA_N(char,strlen(name)+2);
+ sprintf(buf, "@%s", name);
attriv = rb_intern(buf);
if (read) {
rb_add_method(klass, id, NEW_IVAR(attriv), noex);
}
if (write) {
- rb_add_method(klass, rb_id_attrset(id), NEW_ATTRSET(attriv), noex);
+ sprintf(buf, "%s=", name);
+ id = rb_intern(buf);
+ rb_add_method(klass, id, NEW_ATTRSET(attriv), noex);
}
}
@@ -936,7 +879,6 @@ static struct iter *ruby_iter;
#define ITER_NOT 0
#define ITER_PRE 1
#define ITER_CUR 2
-#define ITER_PAS 3
#define PUSH_ITER(i) do { \
struct iter _iter; \
@@ -980,12 +922,12 @@ static struct tag *prot_tag;
#define PROT_LAMBDA INT2FIX(2) /* 5 */
#define PROT_YIELD INT2FIX(3) /* 7 */
-#define EXEC_TAG() (FLUSH_REGISTER_WINDOWS, ruby_setjmp(prot_tag->buf))
+#define EXEC_TAG() (FLUSH_REGISTER_WINDOWS, setjmp(prot_tag->buf))
#define JUMP_TAG(st) do { \
ruby_frame = prot_tag->frame; \
ruby_iter = prot_tag->iter; \
- ruby_longjmp(prot_tag->buf,(st)); \
+ longjmp(prot_tag->buf,(st)); \
} while (0)
#define POP_TAG() \
@@ -1071,27 +1013,9 @@ static VALUE module_setup _((VALUE,NODE*));
static VALUE massign _((VALUE,NODE*,VALUE,int));
static void assign _((VALUE,NODE*,VALUE,int));
-typedef struct event_hook {
- rb_event_hook_func_t func;
- rb_event_t events;
- struct event_hook *next;
-} rb_event_hook_t;
-
-static rb_event_hook_t *event_hooks;
-
-#define EXEC_EVENT_HOOK(event, node, self, id, klass) \
- do { \
- rb_event_hook_t *hook; \
- \
- for (hook = event_hooks; hook; hook = hook->next) { \
- if (hook->events & event) \
- (*hook->func)(event, node, self, id, klass); \
- } \
- } while (0)
-
static VALUE trace_func = 0;
static int tracing = 0;
-static void call_trace_func _((rb_event_t,NODE*,VALUE,ID,VALUE));
+static void call_trace_func _((char*,NODE*,VALUE,ID,VALUE));
#if 0
#define SET_CURRENT_SOURCE() (ruby_sourcefile = ruby_current_node->nd_file, \
@@ -1153,9 +1077,7 @@ get_backtrace(info)
VALUE info;
{
if (NIL_P(info)) return Qnil;
- info = rb_funcall(info, rb_intern("backtrace"), 0);
- if (NIL_P(info)) return Qnil;
- return rb_check_array_type(info);
+ return rb_check_array_type(rb_funcall(info, rb_intern("backtrace"), 0));
}
static void
@@ -1224,7 +1146,6 @@ error_print()
if (elen == 0) {
warn_print(": ");
warn_print2(RSTRING(epath)->ptr, RSTRING(epath)->len);
- warn_print("\n");
}
else {
char *tail = 0;
@@ -1335,8 +1256,6 @@ ruby_init()
rb_define_global_const("TOPLEVEL_BINDING", rb_f_binding(ruby_top_self));
#ifdef __MACOS__
_macruby_init();
-#elif defined(__VMS)
- _vmsruby_init();
#endif
ruby_prog_init();
ALLOW_INTS;
@@ -1380,14 +1299,6 @@ static VALUE exception_error;
static VALUE sysstack_error;
static int
-sysexit_status(err)
- VALUE err;
-{
- VALUE st = rb_iv_get(err, "status");
- return NUM2INT(st);
-}
-
-static int
error_handle(ex)
int ex;
{
@@ -1433,7 +1344,8 @@ error_handle(ex)
case TAG_RAISE:
case TAG_FATAL:
if (rb_obj_is_kind_of(ruby_errinfo, rb_eSystemExit)) {
- status = sysexit_status(ruby_errinfo);
+ VALUE st = rb_iv_get(ruby_errinfo, "status");
+ status = NUM2INT(st);
}
else {
error_print();
@@ -1483,7 +1395,6 @@ ruby_finalize_0()
static void
ruby_finalize_1()
{
- signal(SIGINT, SIG_DFL);
ruby_errinfo = 0;
rb_gc_call_finalizer_at_exit();
trace_func = 0;
@@ -1614,7 +1525,22 @@ rb_eval_string_protect(str, state)
const char *str;
int *state;
{
- return rb_protect((VALUE (*)_((VALUE)))rb_eval_string, (VALUE)str, state);
+ VALUE result = Qnil; /* OK */
+ int status;
+
+ PUSH_TAG(PROT_NONE);
+ if ((status = EXEC_TAG()) == 0) {
+ result = rb_eval_string(str);
+ }
+ POP_TAG();
+ if (state) {
+ *state = status;
+ }
+ if (status != 0) {
+ return Qnil;
+ }
+
+ return result;
}
VALUE
@@ -1837,7 +1763,7 @@ ev_const_get(cref, id, self)
if (NIL_P(klass)) return rb_const_get(CLASS_OF(self), id);
while (RCLASS(klass)->iv_tbl && st_lookup(RCLASS(klass)->iv_tbl, id, &result)) {
if (result == Qundef) {
- if (!RTEST(rb_autoload_load(klass, id))) break;
+ rb_autoload_load(klass, id);
continue;
}
return result;
@@ -2156,8 +2082,8 @@ copy_node_scope(node, rval)
#ifdef C_ALLOCA
# define TMP_PROTECT NODE * volatile tmp__protect_tmp=0
# define TMP_ALLOC(n) \
- (tmp__protect_tmp = NEW_NODE(NODE_ALLOCA, \
- ALLOC_N(VALUE,n),tmp__protect_tmp,n), \
+ (tmp__protect_tmp = rb_node_newnode(NODE_ALLOCA, \
+ ALLOC_N(VALUE,n),tmp__protect_tmp,n), \
(void*)tmp__protect_tmp->nd_head)
#else
# define TMP_PROTECT typedef int foobazzz
@@ -2201,10 +2127,8 @@ copy_node_scope(node, rval)
#define BEGIN_CALLARGS do {\
struct BLOCK *tmp_block = ruby_block;\
int tmp_iter = ruby_iter->iter;\
- switch (tmp_iter) {\
- case ITER_PRE:\
+ if (tmp_iter == ITER_PRE) {\
ruby_block = ruby_block->outer;\
- case ITER_PAS:\
tmp_iter = ITER_NOT;\
}\
PUSH_ITER(tmp_iter)
@@ -2343,7 +2267,6 @@ is_defined(self, node, buf)
case NODE_DASGN:
case NODE_DASGN_CURR:
case NODE_GASGN:
- case NODE_IASGN:
case NODE_CDECL:
case NODE_CVDECL:
case NODE_CVASGN:
@@ -2456,45 +2379,6 @@ rb_obj_is_proc(proc)
return Qfalse;
}
-void
-rb_add_event_hook(func, events)
- rb_event_hook_func_t func;
- rb_event_t events;
-{
- rb_event_hook_t *hook;
-
- hook = ALLOC(rb_event_hook_t);
- hook->func = func;
- hook->events = events;
- hook->next = event_hooks;
- event_hooks = hook;
-}
-
-int
-rb_remove_event_hook(func)
- rb_event_hook_func_t func;
-{
- rb_event_hook_t *prev, *hook;
-
- prev = NULL;
- hook = event_hooks;
- while (hook) {
- if (hook->func == func) {
- if (prev) {
- prev->next = hook->next;
- }
- else {
- event_hooks = hook->next;
- }
- xfree(hook);
- return 0;
- }
- prev = hook;
- hook = hook->next;
- }
- return -1;
-}
-
/*
* call-seq:
* set_trace_func(proc) => proc
@@ -2543,54 +2427,19 @@ static VALUE
set_trace_func(obj, trace)
VALUE obj, trace;
{
- rb_event_hook_t *hook;
-
- rb_secure(4);
if (NIL_P(trace)) {
trace_func = 0;
- rb_remove_event_hook(call_trace_func);
return Qnil;
}
if (!rb_obj_is_proc(trace)) {
rb_raise(rb_eTypeError, "trace_func needs to be Proc");
}
- trace_func = trace;
- for (hook = event_hooks; hook; hook = hook->next) {
- if (hook->func == call_trace_func)
- return trace;
- }
- rb_add_event_hook(call_trace_func, RUBY_EVENT_ALL);
- return trace;
-}
-
-static char *
-get_event_name(rb_event_t event)
-{
- switch (event) {
- case RUBY_EVENT_LINE:
- return "line";
- case RUBY_EVENT_CLASS:
- return "class";
- case RUBY_EVENT_END:
- return "end";
- case RUBY_EVENT_CALL:
- return "call";
- case RUBY_EVENT_RETURN:
- return "return";
- case RUBY_EVENT_C_CALL:
- return "c-call";
- case RUBY_EVENT_C_RETURN:
- return "c-return";
- case RUBY_EVENT_RAISE:
- return "raise";
- default:
- return "unknown";
- }
+ return trace_func = trace;
}
static void
call_trace_func(event, node, self, id, klass)
- rb_event_t event;
+ char *event;
NODE *node;
VALUE self;
ID id;
@@ -2600,7 +2449,6 @@ call_trace_func(event, node, self, id, klass)
struct FRAME *prev;
NODE *node_save;
VALUE srcfile;
- char *event_name;
if (!trace_func) return;
if (tracing) return;
@@ -2635,8 +2483,7 @@ call_trace_func(event, node, self, id, klass)
raised = thread_reset_raised();
if ((state = EXEC_TAG()) == 0) {
srcfile = rb_str_new2(ruby_sourcefile?ruby_sourcefile:"(ruby)");
- event_name = get_event_name(event);
- proc_invoke(trace_func, rb_ary_new3(6, rb_str_new2(event_name),
+ proc_invoke(trace_func, rb_ary_new3(6, rb_str_new2(event),
srcfile,
INT2FIX(ruby_sourceline),
id?ID2SYM(id):Qnil,
@@ -2694,7 +2541,7 @@ svalue_to_avalue(v)
if (RARRAY(tmp)->len == 1) {
top = rb_check_array_type(RARRAY(tmp)->ptr[0]);
if (!NIL_P(top) && RARRAY(top)->len > 1) {
- return tmp;
+ return v;
}
return rb_ary_new3(1, v);
}
@@ -2808,23 +2655,6 @@ class_prefix(self, cpath)
NORETURN(static void return_jump _((VALUE)));
NORETURN(static void break_jump _((VALUE)));
-NORETURN(static void unknown_node _((NODE * volatile)));
-
-static void
-unknown_node(node)
- NODE *volatile node;
-{
- ruby_current_node = 0;
- if (node->flags == 0) {
- rb_bug("terminated node (0x%lx)", node);
- }
- else if (BUILTIN_TYPE(node) != T_NODE) {
- rb_bug("not a node 0x%02lx (0x%lx)", BUILTIN_TYPE(node), node);
- }
- else {
- rb_bug("unknown node type %d (0x%lx)", nd_type(node), node);
- }
-}
static VALUE
rb_eval(self, n)
@@ -2934,9 +2764,11 @@ rb_eval(self, n)
RETURN(Qfalse);
case NODE_IF:
- EXEC_EVENT_HOOK(RUBY_EVENT_LINE, node, self,
- ruby_frame->last_func,
- ruby_frame->last_class);
+ if (trace_func) {
+ call_trace_func("line", node, self,
+ ruby_frame->last_func,
+ ruby_frame->last_class);
+ }
if (RTEST(rb_eval(self, node->nd_cond))) {
node = node->nd_body;
}
@@ -2952,9 +2784,11 @@ rb_eval(self, n)
if (nd_type(node) != NODE_WHEN) goto again;
tag = node->nd_head;
while (tag) {
- EXEC_EVENT_HOOK(RUBY_EVENT_LINE, tag, self,
- ruby_frame->last_func,
- ruby_frame->last_class);
+ if (trace_func) {
+ call_trace_func("line", tag, self,
+ ruby_frame->last_func,
+ ruby_frame->last_class);
+ }
if (tag->nd_head && nd_type(tag->nd_head) == NODE_WHEN) {
VALUE v = rb_eval(self, tag->nd_head->nd_head);
long i;
@@ -2993,9 +2827,11 @@ rb_eval(self, n)
}
tag = node->nd_head;
while (tag) {
- EXEC_EVENT_HOOK(RUBY_EVENT_LINE, tag, self,
- ruby_frame->last_func,
- ruby_frame->last_class);
+ if (trace_func) {
+ call_trace_func("line", tag, self,
+ ruby_frame->last_func,
+ ruby_frame->last_class);
+ }
if (tag->nd_head && nd_type(tag->nd_head) == NODE_WHEN) {
VALUE v = rb_eval(self, tag->nd_head->nd_head);
long i;
@@ -3275,11 +3111,19 @@ rb_eval(self, n)
case NODE_DOT2:
case NODE_DOT3:
- {
- VALUE beg = rb_eval(self, node->nd_beg);
- VALUE end = rb_eval(self, node->nd_end);
- result = rb_range_new(beg, end, nd_type(node) == NODE_DOT3);
- }
+ result = rb_range_new(rb_eval(self, node->nd_beg),
+ rb_eval(self, node->nd_end),
+ nd_type(node) == NODE_DOT3);
+ if (node->nd_state) break;
+ if (nd_type(node->nd_beg) == NODE_LIT && FIXNUM_P(node->nd_beg->nd_lit) &&
+ nd_type(node->nd_end) == NODE_LIT && FIXNUM_P(node->nd_end->nd_lit))
+ {
+ nd_set_type(node, NODE_LIT);
+ node->nd_lit = result;
+ }
+ else {
+ node->nd_state = 1;
+ }
break;
case NODE_FLIP2: /* like AWK */
@@ -4026,14 +3870,16 @@ rb_eval(self, n)
break;
case NODE_NEWLINE:
- EXEC_EVENT_HOOK(RUBY_EVENT_LINE, node, self,
- ruby_frame->last_func,
- ruby_frame->last_class);
+ if (trace_func) {
+ call_trace_func("line", node, self,
+ ruby_frame->last_func,
+ ruby_frame->last_class);
+ }
node = node->nd_next;
goto again;
default:
- unknown_node(node);
+ rb_bug("unknown node type %d", nd_type(node));
}
finish:
CHECK_INTS;
@@ -4079,8 +3925,9 @@ module_setup(module, n)
PUSH_CREF(module);
PUSH_TAG(PROT_NONE);
if ((state = EXEC_TAG()) == 0) {
- EXEC_EVENT_HOOK(RUBY_EVENT_CLASS, n, ruby_cbase,
- ruby_frame->last_func, ruby_frame->last_class);
+ if (trace_func) {
+ call_trace_func("class", n, ruby_cbase, ruby_frame->last_func, ruby_frame->last_class);
+ }
result = rb_eval(ruby_cbase, node->nd_next);
}
POP_TAG();
@@ -4090,41 +3937,23 @@ module_setup(module, n)
POP_CLASS();
ruby_frame = frame.tmp;
- EXEC_EVENT_HOOK(RUBY_EVENT_END, n, 0,
- ruby_frame->last_func, ruby_frame->last_class);
+ if (trace_func) {
+ call_trace_func("end", n, 0, ruby_frame->last_func, ruby_frame->last_class);
+ }
if (state) JUMP_TAG(state);
return result;
}
-static NODE *basic_respond_to = 0;
-
-int
-rb_obj_respond_to(obj, id, priv)
- VALUE obj;
- ID id;
- int priv;
-{
- VALUE klass = CLASS_OF(obj);
-
- if (rb_method_node(klass, respond_to) == basic_respond_to) {
- return rb_method_boundp(klass, id, !priv);
- }
- else {
- VALUE args[2];
- int n = 0;
- args[n++] = ID2SYM(id);
- if (priv) args[n++] = Qtrue;
- return rb_funcall2(obj, respond_to, n, args);
- }
-}
-
int
rb_respond_to(obj, id)
VALUE obj;
ID id;
{
- return rb_obj_respond_to(obj, id, Qfalse);
+ if (rb_method_boundp(CLASS_OF(obj), id, 0)) {
+ return Qtrue;
+ }
+ return Qfalse;
}
/*
@@ -4137,7 +3966,7 @@ rb_respond_to(obj, id)
*/
static VALUE
-obj_respond_to(argc, argv, obj)
+rb_obj_respond_to(argc, argv, obj)
int argc;
VALUE *argv;
VALUE obj;
@@ -4308,15 +4137,16 @@ rb_mod_protected_method_defined(mod, mid)
return Qfalse;
}
-NORETURN(static VALUE terminate_process _((int, VALUE)));
+NORETURN(static VALUE terminate_process _((int, const char *, long)));
static VALUE
-terminate_process(status, mesg)
+terminate_process(status, mesg, mlen)
int status;
- VALUE mesg;
+ const char *mesg;
+ long mlen;
{
VALUE args[2];
args[0] = INT2NUM(status);
- args[1] = mesg;
+ args[1] = rb_str_new(mesg, mlen);
rb_exc_raise(rb_class_new_instance(2, args, rb_eSystemExit));
}
@@ -4326,7 +4156,7 @@ rb_exit(status)
int status;
{
if (prot_tag) {
- terminate_process(status, rb_str_new("exit", 4));
+ terminate_process(status, "exit", 4);
}
ruby_finalize();
exit(status);
@@ -4390,9 +4220,6 @@ rb_f_exit(argc, argv)
break;
default:
istatus = NUM2INT(status);
-#if EXIT_SUCCESS != 0
- if (istatus == 0) istatus = EXIT_SUCCESS;
-#endif
break;
}
}
@@ -4431,9 +4258,9 @@ rb_f_abort(argc, argv)
VALUE mesg;
rb_scan_args(argc, argv, "1", &mesg);
- StringValue(mesg);
- rb_io_puts(1, &mesg, rb_stderr);
- terminate_process(EXIT_FAILURE, mesg);
+ StringValue(argv[0]);
+ rb_io_puts(argc, argv, rb_stderr);
+ terminate_process(EXIT_FAILURE, RSTRING(argv[0])->ptr, RSTRING(argv[0])->len);
}
return Qnil; /* not reached */
}
@@ -4499,8 +4326,8 @@ rb_longjmp(tag, mesg)
}
rb_trap_restore_mask();
- if (tag != TAG_FATAL) {
- EXEC_EVENT_HOOK(RUBY_EVENT_RAISE, ruby_current_node,
+ if (trace_func && tag != TAG_FATAL) {
+ call_trace_func("raise", ruby_current_node,
ruby_frame->self,
ruby_frame->last_func,
ruby_frame->last_class);
@@ -4749,9 +4576,6 @@ break_jump(retval)
tt->retval = retval;
JUMP_TAG(TAG_BREAK);
break;
- case PROT_FUNC:
- tt = 0;
- continue;
default:
break;
}
@@ -4760,14 +4584,6 @@ break_jump(retval)
localjump_error("unexpected break", retval, TAG_BREAK);
}
-void
-rb_need_block()
-{
- if (!rb_block_given_p()) {
- localjump_error("no block given", Qnil, 0);
- }
-}
-
static VALUE
rb_yield_0(val, self, klass, flags, avalue)
VALUE val, self, klass; /* OK */
@@ -4785,13 +4601,14 @@ rb_yield_0(val, self, klass, flags, avalue)
int lambda = flags & YIELD_LAMBDA_CALL;
int state;
- rb_need_block();
+ if (!rb_block_given_p()) {
+ localjump_error("no block given", Qnil, 0);
+ }
PUSH_VARS();
block = ruby_block;
frame = block->frame;
frame.prev = ruby_frame;
- frame.node = cnode;
ruby_frame = &(frame);
old_cref = (VALUE)ruby_cref;
ruby_cref = block->cref;
@@ -5267,23 +5084,17 @@ rb_rescue2(b_proc, data1, r_proc, data2, va_alist)
int state;
volatile VALUE result;
volatile VALUE e_info = ruby_errinfo;
- volatile int handle = Qfalse;
- VALUE eclass;
va_list args;
PUSH_TAG(PROT_NONE);
- switch (state = EXEC_TAG()) {
- case TAG_RETRY:
- if (!handle) break;
- handle = Qfalse;
- state = 0;
- ruby_errinfo = Qnil;
- case 0:
+ if ((state = EXEC_TAG()) == 0) {
+ retry_entry:
result = (*b_proc)(data1);
- break;
- case TAG_RAISE:
- if (handle) break;
- handle = Qfalse;
+ }
+ else if (state == TAG_RAISE) {
+ int handle = Qfalse;
+ VALUE eclass;
+
va_init_list(args, data2);
while (eclass = va_arg(args, VALUE)) {
if (rb_obj_is_kind_of(ruby_errinfo, eclass)) {
@@ -5294,14 +5105,25 @@ rb_rescue2(b_proc, data1, r_proc, data2, va_alist)
va_end(args);
if (handle) {
- state = 0;
if (r_proc) {
- result = (*r_proc)(data2, ruby_errinfo);
+ PUSH_TAG(PROT_NONE);
+ if ((state = EXEC_TAG()) == 0) {
+ result = (*r_proc)(data2, ruby_errinfo);
+ }
+ POP_TAG();
+ if (state == TAG_RETRY) {
+ state = 0;
+ ruby_errinfo = Qnil;
+ goto retry_entry;
+ }
}
else {
result = Qnil;
+ state = 0;
+ }
+ if (state == 0) {
+ ruby_errinfo = e_info;
}
- ruby_errinfo = e_info;
}
}
POP_TAG();
@@ -5318,8 +5140,6 @@ rb_rescue(b_proc, data1, r_proc, data2)
return rb_rescue2(b_proc, data1, r_proc, data2, rb_eStandardError, (VALUE)0);
}
-static VALUE cont_protect;
-
VALUE
rb_protect(proc, data, state)
VALUE (*proc) _((VALUE));
@@ -5330,11 +5150,9 @@ rb_protect(proc, data, state)
int status;
PUSH_TAG(PROT_NONE);
- cont_protect = (VALUE)rb_node_newnode(NODE_MEMO, cont_protect, 0, 0);
if ((status = EXEC_TAG()) == 0) {
result = (*proc)(data);
}
- cont_protect = ((NODE *)cont_protect)->u1.value;
POP_TAG();
if (state) {
*state = status;
@@ -5523,7 +5341,7 @@ method_missing(obj, id, argc, argv, call_status)
POP_FRAME();
}
else if (id == ID_ALLOCATOR) {
- rb_raise(rb_eTypeError, "allocator undefined for %s", rb_class2name(obj));
+ rb_raise(rb_eNoMethodError, "allocator undefined for %s", rb_class2name(obj));
}
nargv = ALLOCA_N(VALUE, argc+1);
@@ -5615,32 +5433,30 @@ call_cfunc(func, recv, len, argc, argv)
argv[11], argv[12], argv[13], argv[14]);
break;
default:
- rb_raise(rb_eArgError, "too many arguments (%d)", len);
+ rb_raise(rb_eArgError, "too many arguments(%d)", len);
break;
}
return Qnil; /* not reached */
}
static VALUE
-rb_call0(klass, recv, id, oid, argc, argv, body, flags)
+rb_call0(klass, recv, id, oid, argc, argv, body, nosuper)
VALUE klass, recv;
ID id;
ID oid;
int argc; /* OK */
VALUE *argv; /* OK */
- NODE * volatile body;
- int flags;
+ NODE *body; /* OK */
+ int nosuper;
{
NODE *b2; /* OK */
volatile VALUE result = Qnil;
int itr;
static int tick;
TMP_PROTECT;
- volatile int safe = -1;
switch (ruby_iter->iter) {
case ITER_PRE:
- case ITER_PAS:
itr = ITER_CUR;
break;
case ITER_CUR:
@@ -5659,7 +5475,7 @@ rb_call0(klass, recv, id, oid, argc, argv, body, flags)
ruby_frame->last_func = id;
ruby_frame->orig_func = oid;
- ruby_frame->last_class = (flags & NOEX_NOSUPER)?0:klass;
+ ruby_frame->last_class = nosuper?0:klass;
ruby_frame->self = recv;
ruby_frame->argc = argc;
ruby_frame->argv = argv;
@@ -5670,22 +5486,20 @@ rb_call0(klass, recv, id, oid, argc, argv, body, flags)
int len = body->nd_argc;
if (len < -2) {
- rb_bug("bad argc (%d) specified for `%s(%s)'",
+ rb_bug("bad argc(%d) specified for `%s(%s)'",
len, rb_class2name(klass), rb_id2name(id));
}
- if (event_hooks) {
+ if (trace_func) {
int state;
- EXEC_EVENT_HOOK(RUBY_EVENT_C_CALL, ruby_current_node,
- recv, id, klass);
+ call_trace_func("c-call", ruby_current_node, recv, id, klass);
PUSH_TAG(PROT_FUNC);
if ((state = EXEC_TAG()) == 0) {
result = call_cfunc(body->nd_cfnc, recv, len, argc, argv);
}
POP_TAG();
ruby_current_node = ruby_frame->node;
- EXEC_EVENT_HOOK(RUBY_EVENT_C_RETURN, ruby_current_node,
- recv, id, klass);
+ call_trace_func("c-return", ruby_current_node, recv, id, klass);
if (state) JUMP_TAG(state);
}
else {
@@ -5723,6 +5537,7 @@ rb_call0(klass, recv, id, oid, argc, argv, body, flags)
NODE *saved_cref = 0;
PUSH_SCOPE();
+
if (body->nd_rval) {
saved_cref = ruby_cref;
ruby_cref = (NODE*)body->nd_rval;
@@ -5741,16 +5556,9 @@ rb_call0(klass, recv, id, oid, argc, argv, body, flags)
}
b2 = body = body->nd_next;
- if (NOEX_SAFE(flags) > ruby_safe_level) {
- if (!(flags&NOEX_TAINTED) && ruby_safe_level == 0 && NOEX_SAFE(flags) > 2) {
- rb_raise(rb_eSecurityError, "calling insecure method: %s",
- rb_id2name(id));
- }
- safe = ruby_safe_level;
- ruby_safe_level = NOEX_SAFE(flags);
- }
PUSH_VARS();
PUSH_TAG(PROT_FUNC);
+
if ((state = EXEC_TAG()) == 0) {
NODE *node = 0;
int i;
@@ -5820,8 +5628,8 @@ rb_call0(klass, recv, id, oid, argc, argv, body, flags)
}
}
- if (event_hooks) {
- EXEC_EVENT_HOOK(RUBY_EVENT_CALL, b2, recv, id, klass);
+ if (trace_func) {
+ call_trace_func("call", b2, recv, id, klass);
}
result = rb_eval(recv, body);
}
@@ -5834,9 +5642,8 @@ rb_call0(klass, recv, id, oid, argc, argv, body, flags)
POP_CLASS();
POP_SCOPE();
ruby_cref = saved_cref;
- if (safe >= 0) ruby_safe_level = safe;
- if (event_hooks) {
- EXEC_EVENT_HOOK(RUBY_EVENT_RETURN, body, recv, id, klass);
+ if (trace_func) {
+ call_trace_func("return", ruby_frame->prev->node, recv, id, klass);
}
switch (state) {
case 0:
@@ -5858,7 +5665,7 @@ rb_call0(klass, recv, id, oid, argc, argv, body, flags)
break;
default:
- unknown_node(body);
+ rb_bug("unknown node type %d", nd_type(body));
break;
}
POP_FRAME();
@@ -5917,7 +5724,7 @@ rb_call(klass, recv, mid, argc, argv, scope)
}
}
- return rb_call0(klass, recv, mid, id, argc, argv, body, noex);
+ return rb_call0(klass, recv, mid, id, argc, argv, body, noex & NOEX_NOSUPER);
}
VALUE
@@ -5941,7 +5748,7 @@ rb_apply(recv, mid, args)
* obj.__send__(symbol [, args...]) => obj
*
* Invokes the method identified by _symbol_, passing it any
- * arguments specified. You can use <code>\_\_send__</code> if the name
+ * arguments specified. You can use <code>__send__</code> if the name
* +send+ clashes with an existing method in _obj_.
*
* class Klass
@@ -5971,13 +5778,18 @@ rb_f_send(argc, argv, recv)
return vid;
}
-static VALUE
-vafuncall(recv, mid, n, ar)
+VALUE
+#ifdef HAVE_STDARG_PROTOTYPES
+rb_funcall(VALUE recv, ID mid, int n, ...)
+#else
+rb_funcall(recv, mid, n, va_alist)
VALUE recv;
ID mid;
int n;
- va_list *ar;
+ va_dcl
+#endif
{
+ va_list ar;
VALUE *argv;
if (n > 0) {
@@ -5985,10 +5797,11 @@ vafuncall(recv, mid, n, ar)
argv = ALLOCA_N(VALUE, n);
+ va_init_list(ar, n);
for (i=0;i<n;i++) {
- argv[i] = va_arg(*ar, VALUE);
+ argv[i] = va_arg(ar, VALUE);
}
- va_end(*ar);
+ va_end(ar);
}
else {
argv = 0;
@@ -5998,55 +5811,6 @@ vafuncall(recv, mid, n, ar)
}
VALUE
-#ifdef HAVE_STDARG_PROTOTYPES
-rb_funcall(VALUE recv, ID mid, int n, ...)
-#else
-rb_funcall(recv, mid, n, va_alist)
- VALUE recv;
- ID mid;
- int n;
- va_dcl
-#endif
-{
- va_list ar;
- va_init_list(ar, n);
-
- return vafuncall(recv, mid, n, &ar);
-}
-
-VALUE
-#ifdef HAVE_STDARG_PROTOTYPES
-rb_funcall_rescue(VALUE recv, ID mid, int n, ...)
-#else
-rb_funcall_rescue(recv, mid, n, va_alist)
- VALUE recv;
- ID mid;
- int n;
- va_dcl
-#endif
-{
- VALUE result = Qnil; /* OK */
- int status;
- va_list ar;
-
- va_init_list(ar, n);
-
- PUSH_TAG(PROT_NONE);
- if ((status = EXEC_TAG()) == 0) {
- result = vafuncall(recv, mid, n, &ar);
- }
- POP_TAG();
- switch (status) {
- case 0:
- return result;
- case TAG_RAISE:
- return Qundef;
- default:
- JUMP_TAG(status);
- }
-}
-
-VALUE
rb_funcall2(recv, mid, argc, argv)
VALUE recv;
ID mid;
@@ -6071,7 +5835,7 @@ rb_call_super(argc, argv)
int argc;
const VALUE *argv;
{
- VALUE result, self, klass;
+ VALUE result, self, klass, k;
if (ruby_frame->last_class == 0) {
rb_name_error(ruby_frame->last_func, "calling `super' from `%s' is prohibited",
@@ -6126,9 +5890,8 @@ backtrace(lev)
}
}
}
- for (; frame && (n = frame->node); frame = frame->prev) {
+ while (frame && (n = frame->node)) {
if (frame->prev && frame->prev->last_func) {
- if (frame->prev->node == n) continue;
snprintf(buf, BUFSIZ, "%s:%d:in `%s'",
n->nd_file, nd_line(n),
rb_id2name(frame->prev->last_func));
@@ -6137,6 +5900,7 @@ backtrace(lev)
snprintf(buf, BUFSIZ, "%s:%d", n->nd_file, nd_line(n));
}
rb_ary_push(ary, rb_str_new2(buf));
+ frame = frame->prev;
}
return ary;
@@ -6179,7 +5943,7 @@ rb_f_caller(argc, argv)
if (NIL_P(level)) lev = 1;
else lev = NUM2INT(level);
- if (lev < 0) rb_raise(rb_eArgError, "negative level (%d)", lev);
+ if (lev < 0) rb_raise(rb_eArgError, "negative level(%d)", lev);
return backtrace(lev);
}
@@ -6864,19 +6628,19 @@ rb_provide(feature)
rb_provide_feature(rb_str_new2(feature));
}
-static int
+static void
load_wait(ftptr)
char *ftptr;
{
st_data_t th;
- if (!loading_tbl) return Qfalse;
- if (!st_lookup(loading_tbl, (st_data_t)ftptr, &th)) return Qfalse;
+ if (!loading_tbl) return;
+ if (!st_lookup(loading_tbl, (st_data_t)ftptr, &th)) return;
+ if ((rb_thread_t)th == curr_thread) return;
do {
- if ((rb_thread_t)th == curr_thread) return Qtrue;
CHECK_INTS;
+ rb_thread_schedule();
} while (st_lookup(loading_tbl, (st_data_t)ftptr, &th));
- return Qtrue;
}
/*
@@ -6971,7 +6735,7 @@ static void
load_failed(fname)
VALUE fname;
{
- rb_raise(rb_eLoadError, "no such file to load -- %s", RSTRING(fname)->ptr);
+ rb_raise(rb_eLoadError, "No such file to load -- %s", RSTRING(fname)->ptr);
}
VALUE
@@ -7007,7 +6771,8 @@ rb_require_safe(fname, safe)
ruby_safe_level = safe;
found = search_required(fname, &feature, &path);
if (found) {
- if (!path || load_wait(RSTRING(path)->ptr)) {
+ if (!path) {
+ load_wait(RSTRING(feature)->ptr);
result = Qfalse;
}
else {
@@ -7770,11 +7535,8 @@ Init_eval()
rb_define_global_function("method_missing", rb_method_missing, -1);
rb_define_global_function("loop", rb_f_loop, 0);
- rb_define_method(rb_mKernel, "respond_to?", obj_respond_to, -1);
- respond_to = rb_intern("respond_to?");
- basic_respond_to = rb_method_node(rb_cObject, respond_to);
- rb_global_variable((VALUE*)&basic_respond_to);
-
+ rb_define_method(rb_mKernel, "respond_to?", rb_obj_respond_to, -1);
+
rb_define_global_function("raise", rb_f_raise, -1);
rb_define_global_function("fail", rb_f_raise, -1);
@@ -7838,11 +7600,11 @@ Init_eval()
/*
* call-seq:
* mod.autoload(name, filename) => nil
- *
+ *
* Registers _filename_ to be loaded (using <code>Kernel::require</code>)
- * the first time that _name_ (which may be a <code>String</code> or
+ * the first time that _module_ (which may be a <code>String</code> or
* a symbol) is accessed in the namespace of _mod_.
- *
+ *
* module A
* end
* A.autoload(:B, "b")
@@ -7863,16 +7625,7 @@ rb_mod_autoload(mod, sym, file)
}
/*
- * call-seq:
- * mod.autoload?(name) => String or nil
- *
- * Returns _filename_ to be loaded if _name_ is registered as
- * +autoload+ in the namespace of _mod_.
- *
- * module A
- * end
- * A.autoload(:B, "b")
- * A.autoload?(:B) # => "b"
+ * MISSING: documentation
*/
static VALUE
@@ -7902,15 +7655,9 @@ rb_f_autoload(obj, sym, file)
return rb_mod_autoload(ruby_cbase, sym, file);
}
+
/*
- * call-seq:
- * autoload(module, filename) => nil
- *
- * Registers _filename_ to be loaded (using <code>Kernel::require</code>)
- * the first time that _module_ (which may be a <code>String</code> or
- * a symbol) is accessed.
- *
- * autoload(:MyModule, "/usr/local/lib/modules/my_module.rb")
+ * MISSING: documentation
*/
static VALUE
@@ -8007,9 +7754,9 @@ blk_free(data)
struct BLOCK *data;
{
void *tmp;
-
+
while (data) {
- frame_free(&data->frame);
+ frame_free(&data->frame);
tmp = data;
data = data->prev;
free(tmp);
@@ -8336,7 +8083,6 @@ proc_invoke(proc, args, self, klass)
volatile int safe = ruby_safe_level;
volatile VALUE old_wrapper = ruby_wrapper;
volatile int pcall, avalue = Qtrue;
- volatile VALUE tmp = args;
if (rb_block_given_p() && ruby_frame->last_func) {
if (klass != ruby_frame->last_class)
@@ -8361,10 +8107,6 @@ proc_invoke(proc, args, self, klass)
_block = *data;
if (self != Qundef) _block.frame.self = self;
if (klass) _block.frame.last_class = klass;
- _block.frame.argc = RARRAY(tmp)->len;
- _block.frame.argv = ALLOCA_N(VALUE, RARRAY(tmp)->len);
- MEMCPY(_block.frame.argv, RARRAY(tmp)->ptr, VALUE, RARRAY(tmp)->len);
- _block.frame.flags = FRAME_ALLOCA;
ruby_block = &_block;
PUSH_ITER(ITER_CUR);
@@ -8455,14 +8197,15 @@ static VALUE method_arity _((VALUE));
* call-seq:
* prc.arity -> fixnum
*
- * Returns the number of arguments that would not be ignored. If the block
+ * Returns the number of arguments required by the block. If the block
* is declared to take no arguments, returns 0. If the block is known
* to take exactly n arguments, returns n. If the block has optional
* arguments, return -n-1, where n is the number of mandatory
- * arguments. A <code>proc</code> with no argument declarations
- * is the same a block declaring <code>||</code> as its arguments.
+ * arguments. A <code>proc</code> with no argument declarations
+ * returns -1, as it can accept (and ignore) an arbitrary number of
+ * parameters.
*
- * Proc.new {}.arity #=> 0
+ * Proc.new {}.arity #=> -1
* Proc.new {||}.arity #=> 0
* Proc.new {|a|}.arity #=> 1
* Proc.new {|a,b|}.arity #=> 2
@@ -8548,7 +8291,7 @@ proc_to_s(self)
struct BLOCK *data;
NODE *node;
char *cname = rb_obj_classname(self);
- const int w = (sizeof(VALUE) * CHAR_BIT) / 4;
+ const int w = (SIZEOF_LONG * CHAR_BIT) / 4;
long len = strlen(cname)+6+w; /* 6:tags 16:addr */
VALUE str;
@@ -8556,14 +8299,12 @@ proc_to_s(self)
if ((node = data->frame.node) || (node = data->body)) {
len += strlen(node->nd_file) + 2 + (SIZEOF_LONG*CHAR_BIT-NODE_LSHIFT)/3;
str = rb_str_new(0, len);
- snprintf(RSTRING(str)->ptr, len+1,
- "#<%s:0x%.*lx@%s:%d>", cname, w, (VALUE)data->body,
- node->nd_file, nd_line(node));
+ sprintf(RSTRING(str)->ptr, "#<%s:0x%.*lx@%s:%d>", cname, w, (VALUE)data->body,
+ node->nd_file, nd_line(node));
}
else {
str = rb_str_new(0, len);
- snprintf(RSTRING(str)->ptr, len+1,
- "#<%s:0x%.*lx>", cname, w, (VALUE)data->body);
+ sprintf(RSTRING(str)->ptr, "#<%s:0x%.*lx>", cname, w, (VALUE)data->body);
}
RSTRING(str)->len = strlen(RSTRING(str)->ptr);
if (OBJ_TAINTED(self)) OBJ_TAINT(str);
@@ -8656,13 +8397,14 @@ block_pass(self, node)
proc = b;
}
- if (ruby_safe_level >= 1 && OBJ_TAINTED(proc) &&
- ruby_safe_level > proc_get_safe_level(proc)) {
- rb_raise(rb_eSecurityError, "Insecure: tainted block value");
+ if (ruby_safe_level >= 1 && OBJ_TAINTED(proc)) {
+ if (ruby_safe_level > proc_get_safe_level(proc)) {
+ rb_raise(rb_eSecurityError, "Insecure: tainted block value");
+ }
}
if (ruby_block && ruby_block->block_obj == proc) {
- PUSH_ITER(ITER_PAS);
+ PUSH_ITER(ITER_PRE);
result = rb_eval(self, node->nd_iter);
POP_ITER();
return result;
@@ -8675,7 +8417,7 @@ block_pass(self, node)
old_block = ruby_block;
_block = *data;
_block.outer = ruby_block;
- if (orphan) _block.uniq = block_unique++;
+ _block.uniq = block_unique++;
ruby_block = &_block;
PUSH_ITER(ITER_PRE);
if (ruby_frame->iter == ITER_NOT)
@@ -8721,7 +8463,6 @@ struct METHOD {
VALUE klass, rklass;
VALUE recv;
ID id, oid;
- int safe_level;
NODE *body;
};
@@ -8769,7 +8510,6 @@ mnew(klass, obj, id, mklass)
data->body = body;
data->rklass = rklass;
data->oid = oid;
- data->safe_level = NOEX_WITH_SAFE(0);
OBJ_INFECT(method, klass);
return method;
@@ -8975,21 +8715,26 @@ method_call(argc, argv, method)
{
VALUE result = Qnil; /* OK */
struct METHOD *data;
- int safe;
+ int state;
+ volatile int safe = -1;
Data_Get_Struct(method, struct METHOD, data);
if (data->recv == Qundef) {
- rb_raise(rb_eTypeError, "can't call unbound method; bind first");
+ rb_raise(rb_eTypeError, "you cannot call unbound method; bind first");
}
+ PUSH_ITER(rb_block_given_p()?ITER_PRE:ITER_NOT);
+ PUSH_TAG(PROT_NONE);
if (OBJ_TAINTED(method)) {
- safe = NOEX_WITH(data->safe_level, 4)|NOEX_TAINTED;
+ safe = ruby_safe_level;
+ if (ruby_safe_level < 4) ruby_safe_level = 4;
}
- else {
- safe = data->safe_level;
+ if ((state = EXEC_TAG()) == 0) {
+ result = rb_call0(data->klass,data->recv,data->id,data->oid,argc,argv,data->body,0);
}
- PUSH_ITER(rb_block_given_p()?ITER_PRE:ITER_NOT);
- result = rb_call0(data->klass,data->recv,data->id,data->oid,argc,argv,data->body,safe);
+ POP_TAG();
POP_ITER();
+ if (safe >= 0) ruby_safe_level = safe;
+ if (state) JUMP_TAG(state);
return result;
}
@@ -9164,9 +8909,8 @@ method_arity(method)
case NODE_IVAR:
return INT2FIX(0);
case NODE_BMETHOD:
- return proc_arity(body->nd_cval);
case NODE_DMETHOD:
- return method_arity(body->nd_cval);
+ return proc_arity(body->nd_cval);
default:
body = body->nd_next; /* skip NODE_SCOPE */
if (nd_type(body) == NODE_BLOCK)
@@ -9402,7 +9146,6 @@ rb_mod_define_method(argc, argv, mod)
noex = NOEX_PUBLIC;
}
rb_add_method(mod, id, node, noex);
- rb_define_method(rb_cBinding, "dup", proc_dup, 0);
return body;
}
@@ -9761,15 +9504,6 @@ thread_reset_raised()
static void rb_thread_ready _((rb_thread_t));
-static VALUE run_trap_eval _((VALUE));
-static VALUE
-run_trap_eval(arg)
- VALUE arg;
-{
- VALUE *p = (VALUE *)arg;
- return rb_eval_cmd(p[0], p[1], (int)p[2]);
-}
-
static VALUE
rb_trap_eval(cmd, sig, safe)
VALUE cmd;
@@ -9778,16 +9512,16 @@ rb_trap_eval(cmd, sig, safe)
int state;
VALUE val = Qnil; /* OK */
volatile struct thread_status_t save;
- VALUE arg[3];
- arg[0] = cmd;
- arg[1] = rb_ary_new3(1, INT2FIX(sig));
- arg[2] = (VALUE)safe;
THREAD_COPY_STATUS(curr_thread, &save);
rb_thread_ready(curr_thread);
+ PUSH_TAG(PROT_NONE);
PUSH_ITER(ITER_NOT);
- val = rb_protect(run_trap_eval, (VALUE)&arg, &state);
+ if ((state = EXEC_TAG()) == 0) {
+ val = rb_eval_cmd(cmd, rb_ary_new3(1, INT2FIX(sig)), safe);
+ }
POP_ITER();
+ POP_TAG();
THREAD_COPY_STATUS(&save, curr_thread);
if (state) {
@@ -9903,11 +9637,9 @@ thread_mark(th)
rb_gc_mark((VALUE)th->scope);
rb_gc_mark((VALUE)th->dyna_vars);
rb_gc_mark(th->errinfo);
- rb_gc_mark(th->last_status);
rb_gc_mark(th->last_line);
rb_gc_mark(th->last_match);
rb_mark_tbl(th->locals);
- rb_gc_mark(th->thgroup);
/* mark data in copied stack */
if (th == curr_thread) return;
@@ -9956,9 +9688,9 @@ rb_gc_mark_threads()
rb_gc_mark((VALUE)ruby_cref);
if (!curr_thread) return;
- FOREACH_THREAD_FROM(main_thread, th) {
+ FOREACH_THREAD(th) {
rb_gc_mark(th->thread);
- } END_FOREACH_FROM(main_thread, th);
+ } END_FOREACH(th);
}
static void
@@ -10020,9 +9752,7 @@ rb_thread_save_context(th)
th->stk_len = 0;
th->stk_pos = pos;
if (len > th->stk_max) {
- VALUE *ptr = realloc(th->stk_ptr, sizeof(VALUE) * len);
- if (!ptr) rb_memerror();
- th->stk_ptr = ptr;
+ REALLOC_N(th->stk_ptr, VALUE, len);
th->stk_max = len;
}
th->stk_len = len;
@@ -10102,10 +9832,8 @@ rb_thread_switch(n)
case RESTORE_EXIT:
ruby_errinfo = th_raise_exception;
ruby_current_node = th_raise_node;
- if (!rb_obj_is_kind_of(ruby_errinfo, rb_eSystemExit)) {
- terminate_process(EXIT_FAILURE, ruby_errinfo);
- }
- rb_exc_raise(th_raise_exception);
+ error_print();
+ terminate_process(EXIT_FAILURE, 0, 0);
break;
case RESTORE_NORMAL:
default:
@@ -10116,12 +9844,12 @@ rb_thread_switch(n)
#define THREAD_SAVE_CONTEXT(th) \
(rb_thread_save_context(th),\
- rb_thread_switch((FLUSH_REGISTER_WINDOWS, ruby_setjmp((th)->context))))
+ rb_thread_switch((FLUSH_REGISTER_WINDOWS, setjmp((th)->context))))
NORETURN(static void rb_thread_restore_context _((rb_thread_t,int)));
# if _MSC_VER >= 1300
-__declspec(noinline) static void stack_extend(rb_thread_t, int);
+__declspec(noinline)
# endif
static void
stack_extend(th, exit)
@@ -10197,7 +9925,7 @@ rb_thread_restore_context(th, exit)
rb_backref_set(tmp->last_match);
tmp->last_match = tval;
- ruby_longjmp(tmp->context, ex);
+ longjmp(tmp->context, ex);
}
static void
@@ -10704,9 +10432,7 @@ rb_thread_select(max, read, write, except, timeout)
fd_set *read, *write, *except;
struct timeval *timeout;
{
-#ifndef linux
double limit;
-#endif
int n;
if (!read && !write && !except) {
@@ -10718,12 +10444,10 @@ rb_thread_select(max, read, write, except, timeout)
return 0;
}
-#ifndef linux
if (timeout) {
limit = timeofday()+
(double)timeout->tv_sec+(double)timeout->tv_usec*1e-6;
}
-#endif
if (rb_thread_critical ||
curr_thread == curr_thread->next ||
@@ -11569,7 +11293,7 @@ rb_thread_start_0(fn, arg, th)
{
volatile rb_thread_t th_save = th;
volatile VALUE thread = th->thread;
- struct BLOCK *volatile saved_block = 0;
+ struct BLOCK *volatile saved_block = 0, *block;
enum thread_status status;
int state;
@@ -11661,7 +11385,6 @@ rb_thread_start_0(fn, arg, th)
}
else if (th->safe < 4 && (ruby_thread_abort || th->abort || RTEST(ruby_debug))) {
/* exit on main_thread */
- error_print();
rb_thread_main_jump(ruby_errinfo, RESTORE_EXIT);
}
else {
@@ -11767,21 +11490,10 @@ static VALUE
rb_thread_initialize(thread, args)
VALUE thread, args;
{
- rb_thread_t th;
-
if (!rb_block_given_p()) {
rb_raise(rb_eThreadError, "must be called with a block");
}
- th = rb_thread_check(thread);
- if (th->stk_max) {
- NODE *node = th->node;
- if (!node) {
- rb_raise(rb_eThreadError, "already initialized thread");
- }
- rb_raise(rb_eThreadError, "already initialized thread - %s:%d",
- node->nd_file, nd_line(node));
- }
- return rb_thread_start_0(rb_thread_yield, args, th);
+ return rb_thread_start_0(rb_thread_yield, args, rb_thread_check(thread));
}
@@ -12042,10 +11754,6 @@ rb_thread_trap_eval(cmd, sig, safe)
int sig, safe;
{
rb_thread_critical = 0;
- if (curr_thread == main_thread) {
- rb_trap_eval(cmd, sig, safe);
- return;
- }
if (!rb_thread_dead(curr_thread)) {
if (THREAD_SAVE_CONTEXT(curr_thread)) {
return;
@@ -12058,28 +11766,6 @@ rb_thread_trap_eval(cmd, sig, safe)
rb_thread_restore_context(curr_thread, RESTORE_TRAP);
}
-void
-rb_thread_signal_exit()
-{
- VALUE args[2];
-
- rb_thread_critical = 0;
- if (curr_thread == main_thread) {
- rb_thread_ready(curr_thread);
- rb_exit(EXIT_SUCCESS);
- }
- args[0] = INT2NUM(EXIT_SUCCESS);
- args[1] = rb_str_new2("exit");
- rb_thread_ready(main_thread);
- if (!rb_thread_dead(curr_thread)) {
- if (THREAD_SAVE_CONTEXT(curr_thread)) {
- return;
- }
- }
- rb_thread_main_jump(rb_class_new_instance(2, args, rb_eSystemExit),
- RESTORE_EXIT);
-}
-
static VALUE
rb_thread_raise(argc, argv, th)
int argc;
@@ -12315,10 +12001,9 @@ rb_thread_inspect(thread)
rb_thread_t th = rb_thread_check(thread);
const char *status = thread_status_name(th->status);
VALUE str;
- size_t len = strlen(cname)+7+16+9+1;
- str = rb_str_new(0, len); /* 7:tags 16:addr 9:status 1:nul */
- snprintf(RSTRING(str)->ptr, len, "#<%s:0x%lx %s>", cname, thread, status);
+ str = rb_str_new(0, strlen(cname)+7+16+9+1); /* 7:tags 16:addr 9:status 1:nul */
+ sprintf(RSTRING(str)->ptr, "#<%s:0x%lx %s>", cname, thread, status);
RSTRING(str)->len = strlen(RSTRING(str)->ptr);
OBJ_INFECT(str, thread);
@@ -12415,6 +12100,7 @@ rb_callcc(self)
volatile rb_thread_t th_save;
struct tag *tag;
struct RVarmap *vars;
+ struct BLOCK *blk;
THREAD_ALLOC(th);
cont = Data_Wrap_Struct(rb_cCont, thread_mark, thread_free, th);
@@ -12424,7 +12110,6 @@ rb_callcc(self)
scope_dup(tag->scope);
}
th->thread = curr_thread->thread;
- th->thgroup = cont_protect;
for (vars = ruby_dyna_vars; vars; vars = vars->next) {
if (FL_TEST(vars, DVAR_DONT_RECYCLE)) break;
@@ -12466,9 +12151,6 @@ rb_cont_call(argc, argv, cont)
if (th->thread != curr_thread->thread) {
rb_raise(rb_eRuntimeError, "continuation called across threads");
}
- if (th->thgroup != cont_protect) {
- rb_raise(rb_eRuntimeError, "continuation called across trap");
- }
switch (argc) {
case 0:
th->result = Qnil;
@@ -12569,7 +12251,7 @@ thgroup_list(group)
* ThreadError: can't move from the enclosed thread group
*/
-static VALUE
+VALUE
thgroup_enclose(group)
VALUE group;
{
@@ -12637,10 +12319,6 @@ thgroup_add(group, thread)
rb_secure(4);
th = rb_thread_check(thread);
- if (!th->next || !th->prev) {
- rb_raise(rb_eTypeError, "wrong argument type %s (expected Thread)",
- rb_obj_classname(thread));
- }
if (OBJ_FROZEN(group)) {
rb_raise(rb_eThreadError, "can't move to the frozen thread group");
@@ -12736,7 +12414,6 @@ Init_Thread()
rb_define_method(rb_cCont, "call", rb_cont_call, -1);
rb_define_method(rb_cCont, "[]", rb_cont_call, -1);
rb_define_global_function("callcc", rb_callcc, 0);
- rb_global_variable(&cont_protect);
cThGroup = rb_define_class("ThreadGroup", rb_cObject);
rb_define_alloc_func(cThGroup, thgroup_s_alloc);
@@ -12879,13 +12556,3 @@ rb_throw(tag, val)
argv[1] = val;
rb_f_throw(2, argv);
}
-
-/* flush_register_windows must not be inlined because flushrs doesn't flush
- * current frame in register stack. */
-#ifdef __ia64__
-void flush_register_windows(void)
-{
- __asm__ ("flushrs");
-}
-#endif
-
diff --git a/ext/.document b/ext/.document
index 0f5b1fb1b7..797d8dcef8 100644
--- a/ext/.document
+++ b/ext/.document
@@ -1,7 +1,5 @@
# Add files to this as they become documented
-enumerator/enumerator.c
iconv/iconv.c
-stringio/stringio.c
strscan/strscan.c
zlib/zlib.c
diff --git a/ext/Win32API/Win32API.c b/ext/Win32API/Win32API.c
index 96ce8c6636..776df56ecb 100644
--- a/ext/Win32API/Win32API.c
+++ b/ext/Win32API/Win32API.c
@@ -53,12 +53,12 @@ Win32API_initialize(self, dllname, proc, import, export)
hdll = LoadLibrary(RSTRING(dllname)->ptr);
if (!hdll)
rb_raise(rb_eRuntimeError, "LoadLibrary: %s\n", RSTRING(dllname)->ptr);
- rb_iv_set(self, "__hdll__", Data_Wrap_Struct(rb_cData, 0, Win32API_FreeLibrary, (void*)hdll));
- hproc = (HANDLE)GetProcAddress(hdll, RSTRING(proc)->ptr);
+ rb_iv_set(self, "__hdll__", Data_Wrap_Struct(rb_cData, 0, Win32API_FreeLibrary, hdll));
+ hproc = GetProcAddress(hdll, RSTRING(proc)->ptr);
if (!hproc) {
str = rb_str_new3(proc);
str = rb_str_cat(str, "A", 1);
- hproc = (HANDLE)GetProcAddress(hdll, RSTRING(str)->ptr);
+ hproc = GetProcAddress(hdll, RSTRING(str)->ptr);
if (!hproc)
rb_raise(rb_eRuntimeError, "GetProcAddress: %s or %s\n",
RSTRING(proc)->ptr, RSTRING(str)->ptr);
@@ -137,9 +137,6 @@ Win32API_initialize(self, dllname, proc, import, export)
return Qnil;
}
-#ifdef _MSC_VER
-#pragma optimize("g", off)
-#endif
static VALUE
Win32API_Call(argc, argv, obj)
int argc;
@@ -163,7 +160,7 @@ Win32API_Call(argc, argv, obj)
if (items != nimport)
- rb_raise(rb_eRuntimeError, "wrong number of parameters: expected %d, got %d",
+ rb_raise(rb_eRuntimeError, "Wrong number of parameters: expected %d, got %d.\n",
nimport, items);
for (i = 0; i < nimport; i++) {
diff --git a/ext/Win32API/extconf.rb b/ext/Win32API/extconf.rb
index 865788556f..134a6e5b92 100644
--- a/ext/Win32API/extconf.rb
+++ b/ext/Win32API/extconf.rb
@@ -1,6 +1,5 @@
require 'mkmf'
-dir_config("win32")
if have_header("windows.h") and have_library("kernel32")
create_makefile("Win32API")
end
diff --git a/ext/Win32API/lib/win32/resolv.rb b/ext/Win32API/lib/win32/resolv.rb
index 6534d20760..5a99d04d55 100644
--- a/ext/Win32API/lib/win32/resolv.rb
+++ b/ext/Win32API/lib/win32/resolv.rb
@@ -84,7 +84,7 @@ if info.unpack('V5')[4] == 2 # VER_PLATFORM_WIN32_NT
[ 'NameServer', 'DhcpNameServer' ].each do |key|
ns = regif.read_s(key)
unless ns.empty?
- nameserver.concat(ns.split(/[,\s]\s*/))
+ nameserver.concat(ns.split(/\s+/))
break
end
end
@@ -141,7 +141,7 @@ else
slist = reg.read_s("SearchList")
search << domain unless domain.empty?
search.concat(slist.split(/,\s*/))
- nameserver.concat(ns.split(/[,\s]\s*/))
+ nameserver.concat(ns.split(/,\s*/))
end
end
rescue Registry::Error
diff --git a/ext/bigdecimal/bigdecimal.c b/ext/bigdecimal/bigdecimal.c
index 7f3f1520ee..4ccba8809a 100644
--- a/ext/bigdecimal/bigdecimal.c
+++ b/ext/bigdecimal/bigdecimal.c
@@ -202,7 +202,7 @@ BigDecimal_load(VALUE self, VALUE str)
/* First get max prec */
while((*pch)!=(unsigned char)'\0' && (ch=*pch++)!=(unsigned char)':') {
if(!ISDIGIT(ch)) {
- rb_raise(rb_eTypeError, "load failed: invalid character in the marshaled string");
+ rb_raise(rb_eTypeError, "Load failed: invalid character in the marshaled string");
}
m = m*10 + (unsigned long)(ch-'0');
}
@@ -230,7 +230,7 @@ BigDecimal_mode(int argc, VALUE *argv, VALUE self)
fo = VpGetException();
if(val==Qnil) return INT2FIX(fo);
if(val!=Qfalse && val!=Qtrue) {
- rb_raise(rb_eTypeError, "second argument must be true or false");
+ rb_raise(rb_eTypeError, "The second argument must be true or false.");
return Qnil; /* Not reached */
}
if(f&VP_EXCEPTION_INFINITY) {
@@ -250,13 +250,13 @@ BigDecimal_mode(int argc, VALUE *argv, VALUE self)
if(val==Qnil) return INT2FIX(fo);
Check_Type(val, T_FIXNUM);
if(!VpIsRoundMode(FIX2INT(val))) {
- rb_raise(rb_eTypeError, "invalid rounding mode");
+ rb_raise(rb_eTypeError, "Invalid rounding mode.");
return Qnil;
}
fo = VpSetRoundMode((unsigned long)FIX2INT(val));
return INT2FIX(fo);
}
- rb_raise(rb_eTypeError, "first argument for BigDecimal#mode invalid");
+ rb_raise(rb_eTypeError, "The first argument for BigDecimal#mode is invalid.");
return Qnil;
}
@@ -412,7 +412,7 @@ BigDecimal_to_f(VALUE self)
errno = 0;
d2 = pow(10.0,(double)e);
if((errno == ERANGE && e>0) || (d2>1.0 && (fabs(d) > (DBL_MAX / d2)))) {
- VpException(VP_EXCEPTION_OVERFLOW,"BigDecimal to Float conversion",0);
+ VpException(VP_EXCEPTION_OVERFLOW,"BigDecimal to Float conversion.",0);
if(d>0.0) return rb_float_new(DBL_MAX);
else return rb_float_new(-DBL_MAX);
}
@@ -940,7 +940,7 @@ BigDecimal_round(int argc, VALUE *argv, VALUE self)
Check_Type(vRound, T_FIXNUM);
sw = FIX2INT(vRound);
if(!VpIsRoundMode(sw)) {
- rb_raise(rb_eTypeError, "invalid rounding mode");
+ rb_raise(rb_eTypeError, "Invalid rounding mode.");
return Qnil;
}
break;
@@ -3304,7 +3304,7 @@ VpCtoV(Real *a, char *int_chr, U_LONG ni, char *frac, U_LONG nf, char *exp_chr,
es = e*((S_INT)BASE_FIG);
e = e * 10 + exp_chr[i] - '0';
if(es>e*((S_INT)BASE_FIG)) {
- return VpException(VP_EXCEPTION_INFINITY,"exponent overflow",0);
+ return VpException(VP_EXCEPTION_INFINITY,"Exponent overflow",0);
}
++i;
}
@@ -3723,45 +3723,28 @@ VpMidRound(Real *y, int f, int nf)
* nf: digit location to round from the the decimal point.
*/
{
- /* fracf: any positive digit under rounding position? */
- /* exptoadd: number of digits needed to compensate negative nf */
- int n,i,ix,ioffset,fracf,exptoadd;
- U_LONG v,shifter;
+ int n,i,ix,ioffset;
+ U_LONG v;
U_LONG div;
nf += y->exponent*((int)BASE_FIG);
- exptoadd=0;
- if (nf < 0) {
- exptoadd = -nf;
- nf = 0;
- }
/* ix: x->fraq[ix] contains round position */
ix = nf/(int)BASE_FIG;
- if(((U_LONG)ix)>=y->Prec) return 0; /* Unable to round */
+ if(ix<0 || ((U_LONG)ix)>=y->Prec) return 0; /* Unable to round */
ioffset = nf - ix*((int)BASE_FIG);
+ memset(y->frac+ix+1, 0, (y->Prec - (ix+1)) * sizeof(U_LONG));
v = y->frac[ix];
/* drop digits after pointed digit */
n = BASE_FIG - ioffset - 1;
- for(shifter=1,i=0;i<n;++i) shifter *= 10;
- fracf = (v%(shifter*10) > 0);
- v /= shifter;
+ for(i=0;i<n;++i) v /= 10;
div = v/10;
v = v - div*10;
- if (fracf == 0) {
- for(i=ix+1;i<y->Prec;i++) {
- if (y->frac[i]%BASE) {
- fracf = 1;
- break;
- }
- }
- }
- memset(y->frac+ix+1, 0, (y->Prec - (ix+1)) * sizeof(U_LONG));
switch(f) {
case VP_ROUND_DOWN: /* Truncate */
break;
case VP_ROUND_UP: /* Roundup */
- if(fracf) ++div;
+ if(v) ++div;
break;
case VP_ROUND_HALF_UP: /* Round half up */
if(v>=5) ++div;
@@ -3770,10 +3753,10 @@ VpMidRound(Real *y, int f, int nf)
if(v>=6) ++div;
break;
case VP_ROUND_CEIL: /* ceil */
- if(fracf && (VpGetSign(y)>0)) ++div;
+ if(v && (VpGetSign(y)>0)) ++div;
break;
case VP_ROUND_FLOOR: /* floor */
- if(fracf && (VpGetSign(y)<0)) ++div;
+ if(v && (VpGetSign(y)<0)) ++div;
break;
case VP_ROUND_HALF_EVEN: /* Banker's rounding */
if(v>5) ++div;
@@ -3793,26 +3776,13 @@ VpMidRound(Real *y, int f, int nf)
VpRdup(y,ix);
} else {
S_INT s = VpGetSign(y);
- int e = y->exponent;
VpSetOne(y);
VpSetSign(y,s);
- y->exponent = e+1;
}
} else {
y->frac[ix] = div;
VpNmlz(y);
}
- if (exptoadd > 0) {
- y->exponent += exptoadd/BASE_FIG;
- exptoadd %= BASE_FIG;
- for(i=0;i<exptoadd;i++) {
- y->frac[0] *= 10;
- if (y->frac[0] >= BASE) {
- y->frac[0] /= BASE;
- y->exponent++;
- }
- }
- }
return 1;
}
diff --git a/ext/bigdecimal/lib/bigdecimal/newton.rb b/ext/bigdecimal/lib/bigdecimal/newton.rb
index f88fabe5dc..67a92474ac 100644
--- a/ext/bigdecimal/lib/bigdecimal/newton.rb
+++ b/ext/bigdecimal/lib/bigdecimal/newton.rb
@@ -20,8 +20,8 @@
# f.eps convergence criterion
# x ... initial values
#
-require "bigdecimal/ludcmp"
-require "bigdecimal/jacobian"
+require "ludcmp"
+require "jacobian"
module Newton
include LUSolve
diff --git a/ext/bigdecimal/lib/bigdecimal/nlsolve.rb b/ext/bigdecimal/lib/bigdecimal/nlsolve.rb
new file mode 100644
index 0000000000..08f17f9ecd
--- /dev/null
+++ b/ext/bigdecimal/lib/bigdecimal/nlsolve.rb
@@ -0,0 +1,38 @@
+#!/usr/local/bin/ruby
+
+#
+# nlsolve.rb
+# An example for solving nonlinear algebraic equation system.
+#
+
+require "bigdecimal"
+require "newton"
+include Newton
+
+class Function
+ def initialize()
+ @zero = BigDecimal::new("0.0")
+ @one = BigDecimal::new("1.0")
+ @two = BigDecimal::new("2.0")
+ @ten = BigDecimal::new("10.0")
+ @eps = BigDecimal::new("1.0e-16")
+ end
+ def zero;@zero;end
+ def one ;@one ;end
+ def two ;@two ;end
+ def ten ;@ten ;end
+ def eps ;@eps ;end
+ def values(x) # <= defines functions solved
+ f = []
+ f1 = x[0]*x[0] + x[1]*x[1] - @two # f1 = x**2 + y**2 - 2 => 0
+ f2 = x[0] - x[1] # f2 = x - y => 0
+ f <<= f1
+ f <<= f2
+ f
+ end
+end
+ f = BigDecimal::limit(100)
+ f = Function.new
+ x = [f.zero,f.zero] # Initial values
+ n = nlsolve(f,x)
+ p x
diff --git a/ext/bigdecimal/sample/linear.rb b/ext/bigdecimal/sample/linear.rb
index 88a62ffa71..7c8ca263eb 100644
--- a/ext/bigdecimal/sample/linear.rb
+++ b/ext/bigdecimal/sample/linear.rb
@@ -11,7 +11,7 @@
#
require "bigdecimal"
-require "bigdecimal/ludcmp"
+require "ludcmp"
#
# NOTE:
diff --git a/ext/bigdecimal/sample/nlsolve.rb b/ext/bigdecimal/sample/nlsolve.rb
index 7f729e6aaa..08f17f9ecd 100644
--- a/ext/bigdecimal/sample/nlsolve.rb
+++ b/ext/bigdecimal/sample/nlsolve.rb
@@ -6,7 +6,7 @@
#
require "bigdecimal"
-require "bigdecimal/newton"
+require "newton"
include Newton
class Function
diff --git a/ext/curses/curses.c b/ext/curses/curses.c
index b54b07126d..106c43da4c 100644
--- a/ext/curses/curses.c
+++ b/ext/curses/curses.c
@@ -21,11 +21,7 @@
#elif defined(HAVE_NCURSES_CURSES_H)
# include <ncurses/curses.h>
#elif defined(HAVE_CURSES_COLR_CURSES_H)
-# ifdef HAVE_STDARG_PROTOTYPES
-# include <stdarg.h>
-# else
-# include <varargs.h>
-# endif
+# include <varargs.h>
# include <curses_colr/curses.h>
#else
# include <curses.h>
@@ -54,9 +50,6 @@
# define USE_MOUSE 1
#endif
-#define NUM2CH NUM2LONG
-#define CH2FIX LONG2FIX
-
static VALUE mCurses;
static VALUE mKey;
static VALUE cWindow;
@@ -127,7 +120,7 @@ curses_init_screen()
if (rb_stdscr) return rb_stdscr;
initscr();
if (stdscr == 0) {
- rb_raise(rb_eRuntimeError, "can't initialize curses");
+ rb_raise(rb_eRuntimeError, "cannot initialize curses");
}
clear();
rb_stdscr = prep_window(cWindow, stdscr);
@@ -186,15 +179,6 @@ curses_clear(obj)
return Qnil;
}
-/* def clrtoeol */
-static VALUE
-curses_clrtoeol()
-{
- curses_stdscr();
- clrtoeol();
- return Qnil;
-}
-
/* def refresh */
static VALUE
curses_refresh(obj)
@@ -374,7 +358,7 @@ curses_inch(obj)
VALUE obj;
{
curses_stdscr();
- return CH2FIX(inch());
+ return CHR2FIX(inch());
}
/* def addch(ch) */
@@ -384,7 +368,7 @@ curses_addch(obj, ch)
VALUE ch;
{
curses_stdscr();
- addch(NUM2CH(ch));
+ addch(NUM2CHR(ch));
return Qnil;
}
@@ -395,7 +379,7 @@ curses_insch(obj, ch)
VALUE ch;
{
curses_stdscr();
- insch(NUM2CH(ch));
+ insch(NUM2CHR(ch));
return Qnil;
}
@@ -458,17 +442,6 @@ curses_deleteln(obj)
return Qnil;
}
-/* def insertln */
-static VALUE
-curses_insertln(obj)
- VALUE obj;
-{
-#if defined(HAVE_INSERTLN) || defined(insertln)
- insertln();
-#endif
- return Qnil;
-}
-
/* def keyname */
static VALUE
curses_keyname(obj, c)
@@ -559,7 +532,7 @@ static VALUE
curses_bkgdset(VALUE obj, VALUE ch)
{
#ifdef HAVE_BKGDSET
- bkgdset(NUM2CH(ch));
+ bkgdset(NUM2CHR(ch));
#endif
return Qnil;
}
@@ -568,7 +541,7 @@ static VALUE
curses_bkgd(VALUE obj, VALUE ch)
{
#ifdef HAVE_BKGD
- return (bkgd(NUM2CH(ch)) == OK) ? Qtrue : Qfalse;
+ return (bkgd(NUM2CHR(ch)) == OK) ? Qtrue : Qfalse;
#else
return Qfalse;
#endif
@@ -789,26 +762,22 @@ window_initialize(obj, h, w, top, left)
return obj;
}
-/* def subwin(height, width, top, left) */
+/* def subwin(h, w, top, left) */
static VALUE
-window_subwin(obj, height, width, top, left)
+window_subwin(obj, h, w, top, left)
VALUE obj;
- VALUE height;
- VALUE width;
+ VALUE h;
+ VALUE w;
VALUE top;
VALUE left;
{
struct windata *winp;
WINDOW *window;
VALUE win;
- int h, w, t, l;
- h = NUM2INT(height);
- w = NUM2INT(width);
- t = NUM2INT(top);
- l = NUM2INT(left);
GetWINDOW(obj, winp);
- window = subwin(winp->window, h, w, t, l);
+ window = subwin(winp->window, NUM2INT(h), NUM2INT(w),
+ NUM2INT(top), NUM2INT(left));
win = prep_window(rb_obj_class(obj), window);
return win;
@@ -841,19 +810,6 @@ window_clear(obj)
return Qnil;
}
-/* def clrtoeol */
-static VALUE
-window_clrtoeol(obj)
- VALUE obj;
-{
- struct windata *winp;
-
- GetWINDOW(obj, winp);
- wclrtoeol(winp->window);
-
- return Qnil;
-}
-
/* def refresh */
static VALUE
window_refresh(obj)
@@ -1027,13 +983,13 @@ window_box(argc, argv, self)
rb_scan_args(argc, argv, "21", &vert, &hor, &corn);
GetWINDOW(self, winp);
- box(winp->window, NUM2CH(vert), NUM2CH(hor));
+ box(winp->window, NUM2CHR(vert), NUM2CHR(hor));
if (!NIL_P(corn)) {
int cur_x, cur_y, x, y;
- chtype c;
+ char c;
- c = NUM2CH(corn);
+ c = NUM2CHR(corn);
getyx(winp->window, cur_y, cur_x);
x = NUM2INT(window_maxx(self)) - 1;
y = NUM2INT(window_maxy(self)) - 1;
@@ -1083,7 +1039,7 @@ window_inch(obj)
struct windata *winp;
GetWINDOW(obj, winp);
- return CH2FIX(winch(winp->window));
+ return CHR2FIX(winch(winp->window));
}
/* def addch(ch) */
@@ -1095,7 +1051,7 @@ window_addch(obj, ch)
struct windata *winp;
GetWINDOW(obj, winp);
- waddch(winp->window, NUM2CH(ch));
+ waddch(winp->window, NUM2CHR(ch));
return Qnil;
}
@@ -1109,7 +1065,7 @@ window_insch(obj, ch)
struct windata *winp;
GetWINDOW(obj, winp);
- winsch(winp->window, NUM2CH(ch));
+ winsch(winp->window, NUM2CHR(ch));
return Qnil;
}
@@ -1195,20 +1151,6 @@ window_deleteln(obj)
return Qnil;
}
-/* def insertln */
-static VALUE
-window_insertln(obj)
- VALUE obj;
-{
-#if defined(HAVE_WINSERTLN) || defined(winsertln)
- struct windata *winp;
-
- GetWINDOW(obj, winp);
- winsertln(winp->window);
-#endif
- return Qnil;
-}
-
static VALUE
window_scrollok(VALUE obj, VALUE bf)
{
@@ -1245,20 +1187,6 @@ window_setscrreg(VALUE obj, VALUE top, VALUE bottom)
#endif
}
-#if defined(USE_COLOR) && defined(HAVE_WCOLOR_SET)
-static VALUE
-window_color_set(VALUE obj, VALUE col)
-{
- struct windata *winp;
- int res;
-
- GetWINDOW(obj, winp);
- res = wcolor_set(winp->window, NUM2INT(col), NULL);
- return (res == OK) ? Qtrue : Qfalse;
- return Qfalse;
-}
-#endif /* USE_COLOR */
-
static VALUE
window_scroll(VALUE obj)
{
@@ -1338,7 +1266,7 @@ window_bkgdset(VALUE obj, VALUE ch)
struct windata *winp;
GetWINDOW(obj,winp);
- wbkgdset(winp->window, NUM2CH(ch));
+ wbkgdset(winp->window, NUM2CHR(ch));
#endif
return Qnil;
}
@@ -1350,7 +1278,7 @@ window_bkgd(VALUE obj, VALUE ch)
struct windata *winp;
GetWINDOW(obj,winp);
- return (wbkgd(winp->window, NUM2CH(ch)) == OK) ? Qtrue : Qfalse;
+ return (wbkgd(winp->window, NUM2CHR(ch)) == OK) ? Qtrue : Qfalse;
#else
return Qfalse;
#endif
@@ -1360,11 +1288,11 @@ static VALUE
window_getbkgd(VALUE obj)
{
#ifdef HAVE_WGETBKGD
- chtype c;
+ char c;
struct windata *winp;
GetWINDOW(obj,winp);
- return (c = getbkgd(winp->window) != ERR) ? CH2FIX(c) : Qnil;
+ return (c = getbkgd(winp->window) != ERR) ? CHR2FIX(c) : Qnil;
#else
return Qnil;
#endif
@@ -1464,7 +1392,6 @@ Init_curses()
rb_define_module_function(mCurses, "refresh", curses_refresh, 0);
rb_define_module_function(mCurses, "doupdate", curses_doupdate, 0);
rb_define_module_function(mCurses, "clear", curses_clear, 0);
- rb_define_module_function(mCurses, "clrtoeol", curses_clrtoeol, 0);
rb_define_module_function(mCurses, "echo", curses_echo, 0);
rb_define_module_function(mCurses, "noecho", curses_noecho, 0);
rb_define_module_function(mCurses, "raw", curses_raw, 0);
@@ -1489,7 +1416,6 @@ Init_curses()
rb_define_module_function(mCurses, "getstr", curses_getstr, 0);
rb_define_module_function(mCurses, "delch", curses_delch, 0);
rb_define_module_function(mCurses, "deleteln", curses_deleteln, 0);
- rb_define_module_function(mCurses, "insertln", curses_insertln, 0);
rb_define_module_function(mCurses, "keyname", curses_keyname, 1);
rb_define_module_function(mCurses, "lines", curses_lines, 0);
rb_define_module_function(mCurses, "cols", curses_cols, 0);
@@ -1532,15 +1458,11 @@ Init_curses()
rb_define_method(cWindow, "subwin", window_subwin, 4);
rb_define_method(cWindow, "close", window_close, 0);
rb_define_method(cWindow, "clear", window_clear, 0);
- rb_define_method(cWindow, "clrtoeol", window_clrtoeol, 0);
rb_define_method(cWindow, "refresh", window_refresh, 0);
rb_define_method(cWindow, "noutrefresh", window_noutrefresh, 0);
rb_define_method(cWindow, "box", window_box, -1);
rb_define_method(cWindow, "move", window_move, 2);
rb_define_method(cWindow, "setpos", window_setpos, 2);
-#if defined(USE_COLOR) && defined(HAVE_WCOLOR_SET)
- rb_define_method(cWindow, "color_set", window_color_set, 1);
-#endif /* USE_COLOR && HAVE_WCOLOR_SET */
rb_define_method(cWindow, "cury", window_cury, 0);
rb_define_method(cWindow, "curx", window_curx, 0);
rb_define_method(cWindow, "maxy", window_maxy, 0);
@@ -1558,7 +1480,6 @@ Init_curses()
rb_define_method(cWindow, "getstr", window_getstr, 0);
rb_define_method(cWindow, "delch", window_delch, 0);
rb_define_method(cWindow, "deleteln", window_deleteln, 0);
- rb_define_method(cWindow, "insertln", window_insertln, 0);
rb_define_method(cWindow, "scroll", window_scroll, 0);
rb_define_method(cWindow, "scrollok", window_scrollok, 1);
rb_define_method(cWindow, "idlok", window_idlok, 1);
diff --git a/ext/curses/extconf.rb b/ext/curses/extconf.rb
index 01fe971093..9b319ba30e 100644
--- a/ext/curses/extconf.rb
+++ b/ext/curses/extconf.rb
@@ -19,7 +19,7 @@ elsif have_header(*curses=%w"curses.h") and have_library("curses", "initscr")
end
if make
- for f in %w(beep bkgd bkgdset curs_set deleteln doupdate flash getbkgd getnstr init isendwin keyname keypad resizeterm scrl set setscrreg ungetch wattroff wattron wattrset wbkgd wbkgdset wdeleteln wgetnstr wresize wscrl wsetscrreg def_prog_mode reset_prog_mode timeout wtimeout nodelay init_color wcolor_set)
+ for f in %w(beep bkgd bkgdset curs_set deleteln doupdate flash getbkgd getnstr init isendwin keyname keypad resizeterm scrl set setscrreg ungetch wattroff wattron wattrset wbkgd wbkgdset wdeleteln wgetnstr wresize wscrl wsetscrreg def_prog_mode reset_prog_mode timeout wtimeout nodelay init_color)
have_func(f)
end
flag = "-D_XOPEN_SOURCE_EXTENDED"
diff --git a/ext/curses/view.rb b/ext/curses/view.rb
index d9a82a57db..5ba1a8413c 100644
--- a/ext/curses/view.rb
+++ b/ext/curses/view.rb
@@ -49,7 +49,7 @@ while TRUE
n = 0
while TRUE
c = getch.chr
- if c =~ /[0-9]/
+ if c =~ "[0-9]" then
n = 10 * n + c.to_i
else
break
diff --git a/ext/dbm/dbm.c b/ext/dbm/dbm.c
index 69b7a6e7a7..e609327c46 100644
--- a/ext/dbm/dbm.c
+++ b/ext/dbm/dbm.c
@@ -43,11 +43,6 @@ closed_dbm()
if (dbmp->di_dbm == 0) closed_dbm();\
}
-#define GetDBM2(obj, data, dbm) {\
- GetDBM(obj, data);\
- (dbm) = dbmp->di_dbm;\
-}
-
static void
free_dbm(dbmp)
struct dbmdata *dbmp;
@@ -71,21 +66,6 @@ fdbm_close(obj)
return Qnil;
}
-static VALUE
-fdbm_closed(obj)
- VALUE obj;
-{
- struct dbmdata *dbmp;
-
- Data_Get_Struct(obj, struct dbmdata, dbmp);
- if (dbmp == 0)
- return Qtrue;
- if (dbmp->di_dbm == 0)
- return Qtrue;
-
- return Qfalse;
-}
-
static VALUE fdbm_alloc _((VALUE));
static VALUE
fdbm_alloc(klass)
@@ -181,7 +161,8 @@ fdbm_fetch(obj, keystr, ifnone)
key.dptr = RSTRING(keystr)->ptr;
key.dsize = RSTRING(keystr)->len;
- GetDBM2(obj, dbmp, dbm);
+ GetDBM(obj, dbmp);
+ dbm = dbmp->di_dbm;
value = dbm_fetch(dbm, key);
if (value.dptr == 0) {
if (ifnone == Qnil && rb_block_given_p())
@@ -226,7 +207,8 @@ fdbm_index(obj, valstr)
val.dptr = RSTRING(valstr)->ptr;
val.dsize = RSTRING(valstr)->len;
- GetDBM2(obj, dbmp, dbm);
+ GetDBM(obj, dbmp);
+ dbm = dbmp->di_dbm;
for (key = dbm_firstkey(dbm); key.dptr; key = dbm_nextkey(dbm)) {
val = dbm_fetch(dbm, key);
if (val.dsize == RSTRING(valstr)->len &&
@@ -271,18 +253,17 @@ fdbm_select(argc, argv, obj)
if (argc > 0) {
rb_raise(rb_eArgError, "wrong number arguments(%d for 0)", argc);
}
- GetDBM2(obj, dbmp, dbm);
+ GetDBM(obj, dbmp);
+ dbm = dbmp->di_dbm;
+
for (key = dbm_firstkey(dbm); key.dptr; key = dbm_nextkey(dbm)) {
- VALUE assoc, v;
+ VALUE assoc;
val = dbm_fetch(dbm, key);
assoc = rb_assoc_new(rb_tainted_str_new(key.dptr, key.dsize),
rb_tainted_str_new(val.dptr, val.dsize));
- v = rb_yield(assoc);
- if (RTEST(v)) {
- rb_ary_push(new, assoc);
- }
- GetDBM2(obj, dbmp, dbm);
- }
+ if (RTEST(rb_yield(assoc)))
+ rb_ary_push(new, assoc);
+ }
}
else {
rb_warn("DBM#select(index..) is deprecated; use DBM#values_at");
@@ -333,7 +314,9 @@ fdbm_delete(obj, keystr)
key.dptr = RSTRING(keystr)->ptr;
key.dsize = RSTRING(keystr)->len;
- GetDBM2(obj, dbmp, dbm);
+ GetDBM(obj, dbmp);
+ dbm = dbmp->di_dbm;
+
value = dbm_fetch(dbm, key);
if (value.dptr == 0) {
if (rb_block_given_p()) return rb_yield(keystr);
@@ -363,7 +346,8 @@ fdbm_shift(obj)
VALUE keystr, valstr;
fdbm_modify(obj);
- GetDBM2(obj, dbmp, dbm);
+ GetDBM(obj, dbmp);
+ dbm = dbmp->di_dbm;
dbmp->di_size = -1;
key = dbm_firstkey(dbm);
@@ -388,7 +372,8 @@ fdbm_delete_if(obj)
int i, status = 0, n;
fdbm_modify(obj);
- GetDBM2(obj, dbmp, dbm);
+ GetDBM(obj, dbmp);
+ dbm = dbmp->di_dbm;
n = dbmp->di_size;
dbmp->di_size = -1;
@@ -399,7 +384,6 @@ fdbm_delete_if(obj)
ret = rb_protect(rb_yield, rb_assoc_new(rb_str_dup(keystr), valstr), &status);
if (status != 0) break;
if (RTEST(ret)) rb_ary_push(ary, keystr);
- GetDBM2(obj, dbmp, dbm);
}
for (i = 0; i < RARRAY(ary)->len; i++) {
@@ -426,7 +410,8 @@ fdbm_clear(obj)
DBM *dbm;
fdbm_modify(obj);
- GetDBM2(obj, dbmp, dbm);
+ GetDBM(obj, dbmp);
+ dbm = dbmp->di_dbm;
dbmp->di_size = -1;
while (key = dbm_firstkey(dbm), key.dptr) {
if (dbm_delete(dbm, key)) {
@@ -448,7 +433,8 @@ fdbm_invert(obj)
VALUE keystr, valstr;
VALUE hash = rb_hash_new();
- GetDBM2(obj, dbmp, dbm);
+ GetDBM(obj, dbmp);
+ dbm = dbmp->di_dbm;
for (key = dbm_firstkey(dbm); key.dptr; key = dbm_nextkey(dbm)) {
val = dbm_fetch(dbm, key);
keystr = rb_tainted_str_new(key.dptr, key.dsize);
@@ -508,16 +494,17 @@ fdbm_store(obj, keystr, valstr)
fdbm_modify(obj);
keystr = rb_obj_as_string(keystr);
- valstr = rb_obj_as_string(valstr);
key.dptr = RSTRING(keystr)->ptr;
key.dsize = RSTRING(keystr)->len;
+ valstr = rb_obj_as_string(valstr);
val.dptr = RSTRING(valstr)->ptr;
val.dsize = RSTRING(valstr)->len;
- GetDBM2(obj, dbmp, dbm);
+ GetDBM(obj, dbmp);
dbmp->di_size = -1;
+ dbm = dbmp->di_dbm;
if (dbm_store(dbm, key, val, DBM_REPLACE)) {
#ifdef HAVE_DBM_CLEARERR
dbm_clearerr(dbm);
@@ -538,8 +525,9 @@ fdbm_length(obj)
DBM *dbm;
int i = 0;
- GetDBM2(obj, dbmp, dbm);
+ GetDBM(obj, dbmp);
if (dbmp->di_size > 0) return INT2FIX(dbmp->di_size);
+ dbm = dbmp->di_dbm;
for (key = dbm_firstkey(dbm); key.dptr; key = dbm_nextkey(dbm)) {
i++;
@@ -558,7 +546,7 @@ fdbm_empty_p(obj)
DBM *dbm;
int i = 0;
- GetDBM2(obj, dbmp, dbm);
+ GetDBM(obj, dbmp);
if (dbmp->di_size < 0) {
dbm = dbmp->di_dbm;
@@ -581,11 +569,11 @@ fdbm_each_value(obj)
struct dbmdata *dbmp;
DBM *dbm;
- GetDBM2(obj, dbmp, dbm);
+ GetDBM(obj, dbmp);
+ dbm = dbmp->di_dbm;
for (key = dbm_firstkey(dbm); key.dptr; key = dbm_nextkey(dbm)) {
val = dbm_fetch(dbm, key);
rb_yield(rb_tainted_str_new(val.dptr, val.dsize));
- GetDBM2(obj, dbmp, dbm);
}
return obj;
}
@@ -598,10 +586,10 @@ fdbm_each_key(obj)
struct dbmdata *dbmp;
DBM *dbm;
- GetDBM2(obj, dbmp, dbm);
+ GetDBM(obj, dbmp);
+ dbm = dbmp->di_dbm;
for (key = dbm_firstkey(dbm); key.dptr; key = dbm_nextkey(dbm)) {
rb_yield(rb_tainted_str_new(key.dptr, key.dsize));
- GetDBM2(obj, dbmp, dbm);
}
return obj;
}
@@ -615,14 +603,14 @@ fdbm_each_pair(obj)
struct dbmdata *dbmp;
VALUE keystr, valstr;
- GetDBM2(obj, dbmp, dbm);
+ GetDBM(obj, dbmp);
+ dbm = dbmp->di_dbm;
for (key = dbm_firstkey(dbm); key.dptr; key = dbm_nextkey(dbm)) {
val = dbm_fetch(dbm, key);
keystr = rb_tainted_str_new(key.dptr, key.dsize);
valstr = rb_tainted_str_new(val.dptr, val.dsize);
rb_yield(rb_assoc_new(keystr, valstr));
- GetDBM2(obj, dbmp, dbm);
}
return obj;
@@ -637,7 +625,8 @@ fdbm_keys(obj)
DBM *dbm;
VALUE ary;
- GetDBM2(obj, dbmp, dbm);
+ GetDBM(obj, dbmp);
+ dbm = dbmp->di_dbm;
ary = rb_ary_new();
for (key = dbm_firstkey(dbm); key.dptr; key = dbm_nextkey(dbm)) {
@@ -656,7 +645,9 @@ fdbm_values(obj)
DBM *dbm;
VALUE ary;
- GetDBM2(obj, dbmp, dbm);
+ GetDBM(obj, dbmp);
+ dbm = dbmp->di_dbm;
+
ary = rb_ary_new();
for (key = dbm_firstkey(dbm); key.dptr; key = dbm_nextkey(dbm)) {
val = dbm_fetch(dbm, key);
@@ -678,7 +669,8 @@ fdbm_has_key(obj, keystr)
key.dptr = RSTRING(keystr)->ptr;
key.dsize = RSTRING(keystr)->len;
- GetDBM2(obj, dbmp, dbm);
+ GetDBM(obj, dbmp);
+ dbm = dbmp->di_dbm;
val = dbm_fetch(dbm, key);
if (val.dptr) return Qtrue;
return Qfalse;
@@ -696,7 +688,8 @@ fdbm_has_value(obj, valstr)
val.dptr = RSTRING(valstr)->ptr;
val.dsize = RSTRING(valstr)->len;
- GetDBM2(obj, dbmp, dbm);
+ GetDBM(obj, dbmp);
+ dbm = dbmp->di_dbm;
for (key = dbm_firstkey(dbm); key.dptr; key = dbm_nextkey(dbm)) {
val = dbm_fetch(dbm, key);
if (val.dsize == RSTRING(valstr)->len &&
@@ -715,12 +708,14 @@ fdbm_to_a(obj)
DBM *dbm;
VALUE ary;
- GetDBM2(obj, dbmp, dbm);
+ GetDBM(obj, dbmp);
+ dbm = dbmp->di_dbm;
+
ary = rb_ary_new();
for (key = dbm_firstkey(dbm); key.dptr; key = dbm_nextkey(dbm)) {
val = dbm_fetch(dbm, key);
rb_ary_push(ary, rb_assoc_new(rb_tainted_str_new(key.dptr, key.dsize),
- rb_tainted_str_new(val.dptr, val.dsize)));
+ rb_tainted_str_new(val.dptr, val.dsize)));
}
return ary;
@@ -735,7 +730,9 @@ fdbm_to_hash(obj)
DBM *dbm;
VALUE hash;
- GetDBM2(obj, dbmp, dbm);
+ GetDBM(obj, dbmp);
+ dbm = dbmp->di_dbm;
+
hash = rb_hash_new();
for (key = dbm_firstkey(dbm); key.dptr; key = dbm_nextkey(dbm)) {
val = dbm_fetch(dbm, key);
@@ -765,7 +762,6 @@ Init_dbm()
rb_define_method(rb_cDBM, "initialize", fdbm_initialize, -1);
rb_define_method(rb_cDBM, "close", fdbm_close, 0);
- rb_define_method(rb_cDBM, "closed?", fdbm_closed, 0);
rb_define_method(rb_cDBM, "[]", fdbm_aref, 1);
rb_define_method(rb_cDBM, "fetch", fdbm_fetch_m, -1);
rb_define_method(rb_cDBM, "[]=", fdbm_store, 2);
@@ -773,7 +769,7 @@ Init_dbm()
rb_define_method(rb_cDBM, "index", fdbm_index, 1);
rb_define_method(rb_cDBM, "indexes", fdbm_indexes, -1);
rb_define_method(rb_cDBM, "indices", fdbm_indexes, -1);
- rb_define_method(rb_cDBM, "select", fdbm_select, -1);
+ rb_define_method(rb_cDBM, "select", fdbm_select, 0);
rb_define_method(rb_cDBM, "values_at", fdbm_values_at, -1);
rb_define_method(rb_cDBM, "length", fdbm_length, 0);
rb_define_method(rb_cDBM, "size", fdbm_length, 0);
diff --git a/ext/dbm/testdbm.rb b/ext/dbm/testdbm.rb
new file mode 100644
index 0000000000..4942ffb64a
--- /dev/null
+++ b/ext/dbm/testdbm.rb
@@ -0,0 +1,593 @@
+require 'runit/testcase'
+require 'runit/cui/testrunner'
+
+if $".grep(/\bdbm.so\b/).empty?
+ begin
+ require './dbm'
+ rescue LoadError
+ require 'dbm'
+ end
+end
+
+def uname_s
+ require 'rbconfig'
+ case Config::CONFIG['host_os']
+ when 'cygwin'
+ require 'Win32API'
+ uname = Win32API.new('cygwin1', 'uname', 'P', 'I')
+ utsname = ' ' * 100
+ raise 'cannot get system name' if uname.call(utsname) == -1
+
+ utsname.unpack('A20' * 5)[0]
+ else
+ Config::CONFIG['host_os']
+ end
+end
+
+SYSTEM = uname_s
+
+class TestDBM < RUNIT::TestCase
+ def setup
+ @path = "tmptest_dbm_"
+ assert_instance_of(DBM, @dbm = DBM.new(@path))
+
+ # prepare to make readonly DBM file
+ DBM.open("tmptest_dbm_rdonly") {|dbm|
+ dbm['foo'] = 'FOO'
+ }
+
+ File.chmod(0400, *Dir.glob("tmptest_dbm_rdonly.*"))
+
+ assert_instance_of(DBM, @dbm_rdonly = DBM.new("tmptest_dbm_rdonly", nil))
+ end
+ def teardown
+ assert_nil(@dbm.close)
+ assert_nil(@dbm_rdonly.close)
+ GC.start
+ File.delete *Dir.glob("tmptest_dbm*").to_a
+ p Dir.glob("tmptest_dbm*") if $DEBUG
+ end
+
+ def check_size(expect, dbm=@dbm)
+ assert_equals(expect, dbm.size)
+ n = 0
+ dbm.each { n+=1 }
+ assert_equals(expect, n)
+ if expect == 0
+ assert_equals(true, dbm.empty?)
+ else
+ assert_equals(false, dbm.empty?)
+ end
+ end
+
+ def test_version
+ STDERR.print DBM::VERSION
+ end
+
+ def test_s_new_has_no_block
+ # DBM.new ignore the block
+ foo = true
+ assert_instance_of(DBM, dbm = DBM.new("tmptest_dbm") { foo = false })
+ assert_equals(foo, true)
+ assert_nil(dbm.close)
+ end
+ def test_s_open_no_create
+ assert_nil(dbm = DBM.open("tmptest_dbm", nil))
+ ensure
+ dbm.close if dbm
+ end
+ def test_s_open_with_block
+ assert_equals(DBM.open("tmptest_dbm") { :foo }, :foo)
+ end
+ def test_s_open_lock
+ fork() {
+ assert_instance_of(DBM, dbm = DBM.open("tmptest_dbm", 0644))
+ sleep 2
+ }
+ begin
+ sleep 1
+ assert_exception(Errno::EWOULDBLOCK, "NEVER MIND IF YOU USE Berkeley DB3") {
+ begin
+ assert_instance_of(DBM, dbm2 = DBM.open("tmptest_dbm", 0644))
+ rescue Errno::EAGAIN, Errno::EACCES, Errno::EINVAL
+ raise Errno::EWOULDBLOCK
+ end
+ }
+ ensure
+ Process.wait
+ end
+ end
+
+=begin
+ # Is it guaranteed on many OS?
+ def test_s_open_lock_one_process
+ # locking on one process
+ assert_instance_of(DBM, dbm = DBM.open("tmptest_dbm", 0644))
+ assert_exception(Errno::EWOULDBLOCK) {
+ begin
+ DBM.open("tmptest_dbm", 0644)
+ rescue Errno::EAGAIN
+ raise Errno::EWOULDBLOCK
+ end
+ }
+ end
+=end
+
+ def test_s_open_nolock
+ # dbm 1.8.0 specific
+ if not defined? DBM::NOLOCK
+ return
+ end
+
+ fork() {
+ assert_instance_of(DBM, dbm = DBM.open("tmptest_dbm", 0644,
+ DBM::NOLOCK))
+ sleep 2
+ }
+ sleep 1
+ begin
+ dbm2 = nil
+ assert_no_exception(Errno::EWOULDBLOCK, Errno::EAGAIN, Errno::EACCES) {
+ assert_instance_of(DBM, dbm2 = DBM.open("tmptest_dbm", 0644))
+ }
+ ensure
+ Process.wait
+ dbm2.close if dbm2
+ end
+
+ p Dir.glob("tmptest_dbm*") if $DEBUG
+
+ fork() {
+ assert_instance_of(DBM, dbm = DBM.open("tmptest_dbm", 0644))
+ sleep 2
+ }
+ begin
+ sleep 1
+ dbm2 = nil
+ assert_no_exception(Errno::EWOULDBLOCK, Errno::EAGAIN, Errno::EACCES) {
+ # this test is failed on Cygwin98 (???)
+ assert_instance_of(DBM, dbm2 = DBM.open("tmptest_dbm", 0644,
+ DBM::NOLOCK))
+ }
+ ensure
+ Process.wait
+ dbm2.close if dbm2
+ end
+ end
+
+ def test_s_open_error
+ assert_instance_of(DBM, dbm = DBM.open("tmptest_dbm", 0))
+ assert_exception(Errno::EACCES, "NEVER MIND IF YOU USE Berkeley DB3") {
+ DBM.open("tmptest_dbm", 0)
+ }
+ dbm.close
+ end
+
+ def test_close
+ assert_instance_of(DBM, dbm = DBM.open("tmptest_dbm"))
+ assert_nil(dbm.close)
+
+ # closed DBM file
+ assert_exception(DBMError) { dbm.close }
+ end
+
+ def test_aref
+ assert_equals('bar', @dbm['foo'] = 'bar')
+ assert_equals('bar', @dbm['foo'])
+
+ assert_nil(@dbm['bar'])
+ end
+
+ def test_fetch
+ assert_equals('bar', @dbm['foo']='bar')
+ assert_equals('bar', @dbm.fetch('foo'))
+
+ # key not found
+ assert_exception(IndexError) {
+ @dbm.fetch('bar')
+ }
+
+ # test for `ifnone' arg
+ assert_equals('baz', @dbm.fetch('bar', 'baz'))
+
+ # test for `ifnone' block
+ assert_equals('foobar', @dbm.fetch('bar') {|key| 'foo' + key })
+ end
+
+ def test_aset
+ num = 0
+ 2.times {|i|
+ assert_equals('foo', @dbm['foo'] = 'foo')
+ assert_equals('foo', @dbm['foo'])
+ assert_equals('bar', @dbm['foo'] = 'bar')
+ assert_equals('bar', @dbm['foo'])
+
+ num += 1 if i == 0
+ assert_equals(num, @dbm.size)
+
+ # assign nil
+ assert_equals('', @dbm['bar'] = '')
+ assert_equals('', @dbm['bar'])
+
+ num += 1 if i == 0
+ assert_equals(num, @dbm.size)
+
+ # empty string
+ assert_equals('', @dbm[''] = '')
+ assert_equals('', @dbm[''])
+
+ num += 1 if i == 0
+ assert_equals(num, @dbm.size)
+
+ # Fixnum
+ assert_equals('200', @dbm['100'] = '200')
+ assert_equals('200', @dbm['100'])
+
+ num += 1 if i == 0
+ assert_equals(num, @dbm.size)
+
+ # Big key and value
+ assert_equals('y' * 100, @dbm['x' * 100] = 'y' * 100)
+ assert_equals('y' * 100, @dbm['x' * 100])
+
+ num += 1 if i == 0
+ assert_equals(num, @dbm.size)
+ }
+ end
+
+ def test_index
+ assert_equals('bar', @dbm['foo'] = 'bar')
+ assert_equals('foo', @dbm.index('bar'))
+ assert_nil(@dbm['bar'])
+ end
+
+ def test_indexes
+ keys = %w(foo bar baz)
+ values = %w(FOO BAR BAZ)
+ @dbm[keys[0]], @dbm[keys[1]], @dbm[keys[2]] = values
+ assert_equals(values.reverse, @dbm.indexes(*keys.reverse))
+ end
+
+ def test_values_at
+ keys = %w(foo bar baz)
+ values = %w(FOO BAR BAZ)
+ @dbm[keys[0]], @dbm[keys[1]], @dbm[keys[2]] = values
+ assert_equals(values.reverse, @dbm.values_at(*keys.reverse))
+ end
+
+ def test_select_with_block
+ keys = %w(foo bar baz)
+ values = %w(FOO BAR BAZ)
+ @dbm[keys[0]], @dbm[keys[1]], @dbm[keys[2]] = values
+ ret = @dbm.select {|k,v|
+ assert_equals(k.upcase, v)
+ k != "bar"
+ }
+ assert_equals([['baz', 'BAZ'], ['foo', 'FOO']],
+ ret.sort)
+ end
+
+ def test_length
+ num = 10
+ assert_equals(0, @dbm.size)
+ num.times {|i|
+ i = i.to_s
+ @dbm[i] = i
+ }
+ assert_equals(num, @dbm.size)
+
+ @dbm.shift
+
+ assert_equals(num - 1, @dbm.size)
+ end
+
+ def test_empty?
+ assert_equals(true, @dbm.empty?)
+ @dbm['foo'] = 'FOO'
+ assert_equals(false, @dbm.empty?)
+ end
+
+ def test_each_pair
+ n = 0
+ @dbm.each_pair { n += 1 }
+ assert_equals(0, n)
+
+ keys = %w(foo bar baz)
+ values = %w(FOO BAR BAZ)
+
+ @dbm[keys[0]], @dbm[keys[1]], @dbm[keys[2]] = values
+
+ n = 0
+ ret = @dbm.each_pair {|key, val|
+ assert_not_nil(i = keys.index(key))
+ assert_equals(val, values[i])
+
+ n += 1
+ }
+ assert_equals(keys.size, n)
+ assert_equals(@dbm, ret)
+ end
+
+ def test_each_value
+ n = 0
+ @dbm.each_value { n += 1 }
+ assert_equals(0, n)
+
+ keys = %w(foo bar baz)
+ values = %w(FOO BAR BAZ)
+
+ @dbm[keys[0]], @dbm[keys[1]], @dbm[keys[2]] = values
+
+ n = 0
+ ret = @dbm.each_value {|val|
+ assert_not_nil(key = @dbm.index(val))
+ assert_not_nil(i = keys.index(key))
+ assert_equals(val, values[i])
+
+ n += 1
+ }
+ assert_equals(keys.size, n)
+ assert_equals(@dbm, ret)
+ end
+
+ def test_each_key
+ n = 0
+ @dbm.each_key { n += 1 }
+ assert_equals(0, n)
+
+ keys = %w(foo bar baz)
+ values = %w(FOO BAR BAZ)
+
+ @dbm[keys[0]], @dbm[keys[1]], @dbm[keys[2]] = values
+
+ n = 0
+ ret = @dbm.each_key {|key|
+ assert_not_nil(i = keys.index(key))
+ assert_equals(@dbm[key], values[i])
+
+ n += 1
+ }
+ assert_equals(keys.size, n)
+ assert_equals(@dbm, ret)
+ end
+
+ def test_keys
+ assert_equals([], @dbm.keys)
+
+ keys = %w(foo bar baz)
+ values = %w(FOO BAR BAZ)
+
+ @dbm[keys[0]], @dbm[keys[1]], @dbm[keys[2]] = values
+
+ assert_equals(keys.sort, @dbm.keys.sort)
+ assert_equals(values.sort, @dbm.values.sort)
+ end
+
+ def test_values
+ test_keys
+ end
+
+ def test_shift
+ assert_nil(@dbm.shift)
+ assert_equals(0, @dbm.size)
+
+ keys = %w(foo bar baz)
+ values = %w(FOO BAR BAZ)
+
+ @dbm[keys[0]], @dbm[keys[1]], @dbm[keys[2]] = values
+
+ ret_keys = []
+ ret_values = []
+ while ret = @dbm.shift
+ ret_keys.push ret[0]
+ ret_values.push ret[1]
+
+ assert_equals(keys.size - ret_keys.size, @dbm.size)
+ end
+
+ assert_equals(keys.sort, ret_keys.sort)
+ assert_equals(values.sort, ret_values.sort)
+ end
+
+ def test_delete
+ keys = %w(foo bar baz)
+ values = %w(FOO BAR BAZ)
+ key = keys[1]
+
+ assert_nil(@dbm.delete(key))
+ assert_equals(0, @dbm.size)
+
+ @dbm[keys[0]], @dbm[keys[1]], @dbm[keys[2]] = values
+
+ assert_equals('BAR', @dbm.delete(key))
+ assert_nil(@dbm[key])
+ assert_equals(2, @dbm.size)
+
+ assert_nil(@dbm.delete(key))
+
+ if /^CYGWIN_9/ !~ SYSTEM
+ assert_exception(DBMError) {
+ @dbm_rdonly.delete("foo")
+ }
+
+ assert_nil(@dbm_rdonly.delete("bar"))
+ end
+ end
+ def test_delete_with_block
+ key = 'no called block'
+ @dbm[key] = 'foo'
+ assert_equals('foo', @dbm.delete(key) {|k| k.replace 'called block'})
+ assert_equals('no called block', key)
+ assert_equals(0, @dbm.size)
+
+ key = 'no called block'
+ assert_equals(:blockval,
+ @dbm.delete(key) {|k| k.replace 'called block'; :blockval})
+ assert_equals('called block', key)
+ assert_equals(0, @dbm.size)
+ end
+
+ def test_delete_if
+ v = "0"
+ 100.times {@dbm[v] = v; v = v.next}
+
+ ret = @dbm.delete_if {|key, val| key.to_i < 50}
+ assert_equals(@dbm, ret)
+ check_size(50, @dbm)
+
+ ret = @dbm.delete_if {|key, val| key.to_i >= 50}
+ assert_equals(@dbm, ret)
+ check_size(0, @dbm)
+
+ # break
+ v = "0"
+ 100.times {@dbm[v] = v; v = v.next}
+ check_size(100, @dbm)
+ n = 0;
+ @dbm.delete_if {|key, val|
+ break if n > 50
+ n+=1
+ true
+ }
+ assert_equals(51, n)
+ check_size(49, @dbm)
+
+ @dbm.clear
+
+ # raise
+ v = "0"
+ 100.times {@dbm[v] = v; v = v.next}
+ check_size(100, @dbm)
+ n = 0;
+ begin
+ @dbm.delete_if {|key, val|
+ raise "runtime error" if n > 50
+ n+=1
+ true
+ }
+ rescue
+ end
+ assert_equals(51, n)
+ check_size(49, @dbm)
+ end
+
+ def test_reject
+ v = "0"
+ 100.times {@dbm[v] = v; v = v.next}
+
+ hash = @dbm.reject {|key, val| key.to_i < 50}
+ assert_instance_of(Hash, hash)
+ assert_equals(100, @dbm.size)
+
+ assert_equals(50, hash.size)
+ hash.each_pair {|key,val|
+ assert_equals(false, key.to_i < 50)
+ assert_equals(key, val)
+ }
+
+ hash = @dbm.reject {|key, val| key.to_i < 100}
+ assert_instance_of(Hash, hash)
+ assert_equals(true, hash.empty?)
+ end
+
+ def test_clear
+ v = "1"
+ 100.times {v = v.next; @dbm[v] = v}
+
+ assert_equals(@dbm, @dbm.clear)
+
+ # validate DBM#size
+ i = 0
+ @dbm.each { i += 1 }
+ assert_equals(@dbm.size, i)
+ assert_equals(0, i)
+ end
+
+ def test_invert
+ v = "0"
+ 100.times {@dbm[v] = v; v = v.next}
+
+ hash = @dbm.invert
+ assert_instance_of(Hash, hash)
+ assert_equals(100, hash.size)
+ hash.each_pair {|key, val|
+ assert_equals(key.to_i, val.to_i)
+ }
+ end
+
+ def test_update
+ hash = {}
+ v = "0"
+ 100.times {v = v.next; hash[v] = v}
+
+ @dbm["101"] = "101"
+ @dbm.update hash
+ assert_equals(101, @dbm.size)
+ @dbm.each_pair {|key, val|
+ assert_equals(key.to_i, val.to_i)
+ }
+ end
+
+ def test_replace
+ hash = {}
+ v = "0"
+ 100.times {v = v.next; hash[v] = v}
+
+ @dbm["101"] = "101"
+ @dbm.replace hash
+ assert_equals(100, @dbm.size)
+ @dbm.each_pair {|key, val|
+ assert_equals(key.to_i, val.to_i)
+ }
+ end
+
+ def test_haskey?
+ assert_equals('bar', @dbm['foo']='bar')
+ assert_equals(true, @dbm.has_key?('foo'))
+ assert_equals(false, @dbm.has_key?('bar'))
+ end
+
+ def test_has_value?
+ assert_equals('bar', @dbm['foo']='bar')
+ assert_equals(true, @dbm.has_value?('bar'))
+ assert_equals(false, @dbm.has_value?('foo'))
+ end
+
+ def test_to_a
+ v = "0"
+ 100.times {v = v.next; @dbm[v] = v}
+
+ ary = @dbm.to_a
+ assert_instance_of(Array, ary)
+ assert_equals(100, ary.size)
+ ary.each {|key,val|
+ assert_equals(key.to_i, val.to_i)
+ }
+ end
+
+ def test_to_hash
+ v = "0"
+ 100.times {v = v.next; @dbm[v] = v}
+
+ hash = @dbm.to_hash
+ assert_instance_of(Hash, hash)
+ assert_equals(100, hash.size)
+ hash.each {|key,val|
+ assert_equals(key.to_i, val.to_i)
+ }
+ end
+end
+
+if $0 == __FILE__
+ if ARGV.size == 0
+ suite = RUNIT::TestSuite.new
+ suite.add_test(TestDBM.suite)
+ else
+ suite = RUNIT::TestSuite.new
+ ARGV.each do |testmethod|
+ suite.add_test(TestDBM.new(testmethod))
+ end
+ end
+
+ RUNIT::CUI::TestRunner.run(suite)
+end
diff --git a/ext/digest/md5/md5ossl.h b/ext/digest/md5/md5ossl.h
index 610f58db06..dda7c743ed 100644
--- a/ext/digest/md5/md5ossl.h
+++ b/ext/digest/md5/md5ossl.h
@@ -3,7 +3,6 @@
#ifndef MD5OSSL_H_INCLUDED
#define MD5OSSL_H_INCLUDED
-#include <stddef.h>
#include <openssl/md5.h>
void MD5_End(MD5_CTX *pctx, unsigned char *hexdigest);
diff --git a/ext/digest/rmd160/rmd160ossl.h b/ext/digest/rmd160/rmd160ossl.h
index e8928d164b..824a1bf32f 100644
--- a/ext/digest/rmd160/rmd160ossl.h
+++ b/ext/digest/rmd160/rmd160ossl.h
@@ -3,7 +3,6 @@
#ifndef RMD160OSSL_H_INCLUDED
#define RMD160OSSL_H_INCLUDED
-#include <stddef.h>
#include <openssl/ripemd.h>
#define RMD160_CTX RIPEMD160_CTX
diff --git a/ext/digest/sha1/sha1ossl.h b/ext/digest/sha1/sha1ossl.h
index c271cc47c6..e8d7e74baf 100644
--- a/ext/digest/sha1/sha1ossl.h
+++ b/ext/digest/sha1/sha1ossl.h
@@ -3,7 +3,6 @@
#ifndef SHA1OSSL_H_INCLUDED
#define SHA1OSSL_H_INCLUDED
-#include <stddef.h>
#include <openssl/sha.h>
#define SHA1_CTX SHA_CTX
diff --git a/ext/digest/sha2/extconf.rb b/ext/digest/sha2/extconf.rb
index 17fb9f2d1a..c982aa64de 100644
--- a/ext/digest/sha2/extconf.rb
+++ b/ext/digest/sha2/extconf.rb
@@ -17,6 +17,12 @@ have_header("inttypes.h")
have_header("unistd.h")
-if have_type("uint64_t", "defs.h", $defs.join(' '))
+if try_cpp(<<SRC, $defs.join(' '))
+#include "defs.h"
+#ifdef NO_UINT64_T
+ #error ** Cannot find a 64bit integer type - skipping the SHA2 module.
+#endif
+SRC
+then
create_makefile("digest/sha2")
end
diff --git a/ext/dl/dl.c b/ext/dl/dl.c
index 4a31660980..22abb754d2 100644
--- a/ext/dl/dl.c
+++ b/ext/dl/dl.c
@@ -435,15 +435,7 @@ c_parray(VALUE v, long *size)
ary[i] = (void*)(pdata->ptr);
}
else{
- e = rb_funcall(e, rb_intern("to_ptr"), 0);
- if (rb_obj_is_kind_of(e, rb_cDLPtrData)) {
- struct ptr_data *pdata;
- Data_Get_Struct(e, struct ptr_data, pdata);
- ary[i] = (void*)(pdata->ptr);
- }
- else{
- rb_raise(rb_eDLTypeError, "unexpected type of the element #%d", i);
- }
+ rb_raise(rb_eDLTypeError, "unexpected type of the element #%d", i);
}
break;
}
@@ -503,12 +495,6 @@ rb_ary2cary(char t, VALUE v, long *size)
if (rb_obj_is_kind_of(val0, rb_cDLPtrData)) {
return (void*)c_parray(v,size);
}
- else{
- val0 = rb_funcall(val0, rb_intern("to_ptr"), 0);
- if (rb_obj_is_kind_of(val0, rb_cDLPtrData)) {
- return (void*)c_parray(v,size);
- }
- }
rb_raise(rb_eDLTypeError, "type mismatch");
case T_NIL:
return (void*)c_parray(v, size);
@@ -557,7 +543,7 @@ rb_io_to_ptr(VALUE self)
GetOpenFile(self, fptr);
fp = fptr->f;
- return fp ? rb_dlptr_new(fp, 0, 0) : Qnil;
+ return fp ? rb_dlptr_new(fp, sizeof(FILE), 0) : Qnil;
}
VALUE
diff --git a/ext/dl/handle.c b/ext/dl/handle.c
index 7a05115ec5..95b6dc74dc 100644
--- a/ext/dl/handle.c
+++ b/ext/dl/handle.c
@@ -161,7 +161,7 @@ rb_dlhandle_sym(int argc, VALUE argv[], VALUE self)
Data_Get_Struct(self, struct dl_handle, dlhandle);
if (!dlhandle->open) {
- rb_raise(rb_eRuntimeError, "closed handle");
+ rb_raise(rb_eRuntimeError, "Closed handle.");
}
handle = dlhandle->ptr;
@@ -187,11 +187,11 @@ rb_dlhandle_sym(int argc, VALUE argv[], VALUE self)
if (!func)
#endif
{
- rb_raise(rb_eRuntimeError, "unknown symbol \"%sA\"", name);
+ rb_raise(rb_eRuntimeError, "Unknown symbol \"%sA\".", name);
}
}
#else
- rb_raise(rb_eRuntimeError, "unknown symbol \"%s\"", name);
+ rb_raise(rb_eRuntimeError, "Unknown symbol \"%s\".", name);
#endif
}
val = rb_dlsym_new(func, name, stype);
diff --git a/ext/dl/lib/dl/import.rb b/ext/dl/lib/dl/import.rb
index 63c9b2c050..1ab5145def 100644
--- a/ext/dl/lib/dl/import.rb
+++ b/ext/dl/lib/dl/import.rb
@@ -38,10 +38,10 @@ module DL
case proto
when /^([\d\w\*_\s]+)\(([\d\w\*_\s\,\[\]]*)\)$/
ret = $1
- args = $2.strip()
+ args = $2
ret = ret.split(/\s+/)
args = args.split(/\s*,\s*/)
- func = ret.pop()
+ func = ret.pop
if( func =~ /^\*/ )
func.gsub!(/^\*+/,"")
ret.push("*")
@@ -70,11 +70,8 @@ module DL
init_types()
init_sym()
- rty,renc,rdec = @types.encode_return_type(ret)
- if( !rty )
- raise(TypeError, "unsupported type: #{ret}")
- end
- ty,enc,dec = encode_argument_types(args)
+ rty,renc,rdec = @types.encode_type(ret)
+ ty,enc,dec = encode_types(args)
symty = rty + ty
module_eval("module_function :#{func}")
@@ -99,10 +96,9 @@ module DL
# example:
# typealias("uint", "unsigned int")
#
- def typealias(alias_type, ty1, enc1=nil, dec1=nil, ty2=nil, enc2=nil, dec2=nil)
+ def typealias(*args)
init_types()
- @types.typealias(alias_type, ty1, enc1, dec1,
- ty2||ty1, enc2, dec2)
+ @types.typealias(*args)
end
# example:
@@ -135,11 +131,8 @@ module DL
init_types()
init_sym()
- rty,_,rdec = @types.encode_return_type(rettype)
- if( !rty )
- raise(TypeError, "unsupported type: #{rettype}")
- end
- ty,enc,dec = encode_argument_types(argtypes)
+ rty,_,rdec = @types.encode_type(rettype)
+ ty,enc,dec = encode_types(argtypes)
symty = rty + ty
sym = symbol(name, symty)
@@ -185,16 +178,13 @@ module DL
return @retval
end
- def encode_argument_types(tys)
+ def encode_types(tys)
init_types()
encty = []
enc = nil
dec = nil
tys.each_with_index{|ty,idx|
- ty,c1,c2 = @types.encode_argument_type(ty)
- if( !ty )
- raise(TypeError, "unsupported type: #{ty}")
- end
+ ty,c1,c2,_,_ = @types.encode_type(ty)
encty.push(ty)
if( enc )
if( c1 )
diff --git a/ext/dl/lib/dl/struct.rb b/ext/dl/lib/dl/struct.rb
index 33f303fe22..2c52d5040d 100644
--- a/ext/dl/lib/dl/struct.rb
+++ b/ext/dl/lib/dl/struct.rb
@@ -33,7 +33,7 @@ module DL
"def #{name}",
" v = @ptr[\"#{name}\"]",
" if( @len[\"#{name}\"] )",
- " v = v.collect{|x| @dec[\"#{name}\"] ? @dec[\"#{name}\"].call(x) : x }",
+ " v = v.collect{|x| @dec[\"#{name}\"].call(x) if @dec[\"#{name}\"] }",
" else",
" v = @dec[\"#{name}\"].call(v) if @dec[\"#{name}\"]",
" end",
@@ -41,7 +41,7 @@ module DL
"end",
"def #{name}=(v)",
" if( @len[\"#{name}\"] )",
- " v = v.collect{|x| @enc[\"#{name}\"] ? @enc[\"#{name}\"].call(x) : x }",
+ " v = v.collect{|x| @enc[\"#{name}\"].call(x) if @enc[\"#{name}\"] }",
" else",
" v = @enc[\"#{name}\"].call(v) if @enc[\"#{name}\"]",
" end",
@@ -128,10 +128,7 @@ module DL
else
raise(RuntimeError, "invalid element: #{elem}")
end
- ty,enc,dec = @types.encode_struct_type(ty)
- if( !ty )
- raise(TypeError, "unsupported type: #{ty}")
- end
+ ty,_,_,enc,dec = @types.encode_type(ty)
return [name,ty,num,enc,dec]
end
end # class Struct
diff --git a/ext/dl/lib/dl/types.rb b/ext/dl/lib/dl/types.rb
index 1144917dae..139426473a 100644
--- a/ext/dl/lib/dl/types.rb
+++ b/ext/dl/lib/dl/types.rb
@@ -6,240 +6,175 @@ module DL
class Types
TYPES = [
# FORMAT:
- # ["alias name",
- # "type name", encoding_method, decoding_method, for function prototypes
- # "type name", encoding_method, decoding_method] for structures (not implemented)
+ # ["alias name", "type name",
+ # encoding_method, decoding_method, for function prototypes
+ # encoding_method, decoding_method] for structures (not implemented)
# for Windows
- ["DWORD", "unsigned long", nil, nil,
- "unsigned long", nil, nil],
- ["PDWORD", "unsigned long *", nil, nil,
- "unsigned long *", nil, nil],
- ["WORD", "unsigned short", nil, nil,
- "unsigned short", nil, nil],
- ["PWORD", "unsigned int *", nil, nil,
- "unsigned int *", nil, nil],
- ["BYTE", "unsigned char", nil, nil,
- "unsigned char", nil, nil],
- ["PBYTE", "unsigned char *", nil, nil,
- "unsigned char *", nil, nil],
- ["BOOL", "ibool", nil, nil,
- "ibool", nil, nil],
- ["ATOM", "int", nil, nil,
- "int", nil, nil],
- ["BYTE", "unsigned char", nil, nil,
- "unsigned char", nil, nil],
- ["PBYTE", "unsigned char *", nil, nil,
- "unsigned char *", nil, nil],
- ["UINT", "unsigned int", nil, nil,
- "unsigned int", nil, nil],
- ["ULONG", "unsigned long", nil, nil,
- "unsigned long", nil, nil],
- ["UCHAR", "unsigned char", nil, nil,
- "unsigned char", nil, nil],
- ["HANDLE", "unsigned long", nil, nil,
- "unsigned long", nil, nil],
- ["PHANDLE","void*", nil, nil,
- "void*", nil, nil],
- ["PVOID", "void*", nil, nil,
- "void*", nil, nil],
- ["LPCSTR", "char*", nil, nil,
- "char*", nil, nil],
- ["HDC", "unsigned int", nil, nil,
- "unsigned int", nil, nil],
- ["HWND", "unsigned int", nil, nil,
- "unsigned int", nil, nil],
+ ["DWORD", "unsigned long", nil, nil, nil, nil],
+ ["PDWORD", "unsigned long *", nil, nil, nil, nil],
+ ["WORD", "unsigned short", nil, nil, nil, nil],
+ ["PWORD", "unsigned int *", nil, nil, nil, nil],
+ ["BYTE", "unsigned char", nil, nil, nil, nil],
+ ["PBYTE", "unsigned char *", nil, nil, nil, nil],
+ ["BOOL", "ibool", nil, nil, nil, nil],
+ ["ATOM", "int", nil, nil, nil, nil],
+ ["BYTE", "unsigned char", nil, nil, nil, nil],
+ ["PBYTE", "unsigned char *", nil, nil, nil, nil],
+ ["UINT", "unsigned int", nil, nil, nil, nil],
+ ["ULONG", "unsigned long", nil, nil, nil, nil],
+ ["UCHAR", "unsigned char", nil, nil, nil, nil],
+ ["HANDLE", "unsigned long", nil, nil, nil, nil],
+ ["PHANDLE","void*", nil, nil, nil, nil],
+ ["PVOID", "void*", nil, nil, nil, nil],
+ ["LPCSTR", "char*", nil, nil, nil, nil],
+ ["HDC", "unsigned int", nil, nil, nil, nil],
+ ["HWND", "unsigned int", nil, nil, nil, nil],
# Others
- ["uint", "unsigned int", nil, nil,
- "unsigned int", nil, nil],
- ["u_int", "unsigned int", nil, nil,
- "unsigned int", nil, nil],
- ["ulong", "unsigned long", nil, nil,
- "unsigned long", nil, nil],
- ["u_long", "unsigned long", nil, nil,
- "unsigned long", nil, nil],
+ ["uint", "unsigned int", nil, nil, nil, nil],
+ ["u_int", "unsigned int", nil, nil, nil, nil],
+ ["ulong", "unsigned long", nil, nil, nil, nil],
+ ["u_long", "unsigned long", nil, nil, nil, nil],
# DL::Importable primitive types
- ["ibool",
- "I",
+ ["ibool", "I",
proc{|v| v ? 1 : 0},
proc{|v| (v != 0) ? true : false},
- "I",
proc{|v| v ? 1 : 0 },
proc{|v| (v != 0) ? true : false} ],
- ["cbool",
- "C",
+ ["cbool", "C",
proc{|v| v ? 1 : 0},
proc{|v| (v != 0) ? true : false},
- "C",
proc{|v,len| v ? 1 : 0},
proc{|v,len| (v != 0) ? true : false}],
- ["lbool",
- "L",
+ ["lbool", "L",
proc{|v| v ? 1 : 0},
proc{|v| (v != 0) ? true : false},
- "L",
proc{|v,len| v ? 1 : 0},
proc{|v,len| (v != 0) ? true : false}],
- ["unsigned char",
- "C",
+ ["unsigned char", "C",
proc{|v| [v].pack("C").unpack("c")[0]},
proc{|v| [v].pack("c").unpack("C")[0]},
- "C",
proc{|v| [v].pack("C").unpack("c")[0]},
proc{|v| [v].pack("c").unpack("C")[0]}],
- ["unsigned short",
- "H",
+ ["unsigned short", "H",
proc{|v| [v].pack("S").unpack("s")[0]},
proc{|v| [v].pack("s").unpack("S")[0]},
- "H",
proc{|v| [v].pack("S").unpack("s")[0]},
proc{|v| [v].pack("s").unpack("S")[0]}],
- ["unsigned int",
- "I",
+ ["unsigned int", "I",
proc{|v| [v].pack("I").unpack("i")[0]},
proc{|v| [v].pack("i").unpack("I")[0]},
- "I",
proc{|v| [v].pack("I").unpack("i")[0]},
proc{|v| [v].pack("i").unpack("I")[0]}],
- ["unsigned long",
- "L",
+ ["unsigned long", "L",
proc{|v| [v].pack("L").unpack("l")[0]},
proc{|v| [v].pack("l").unpack("L")[0]},
- "L",
proc{|v| [v].pack("L").unpack("l")[0]},
proc{|v| [v].pack("l").unpack("L")[0]}],
- ["unsigned char ref",
- "c",
+ ["unsigned char ref", "c",
proc{|v| [v].pack("C").unpack("c")[0]},
proc{|v| [v].pack("c").unpack("C")[0]},
- nil, nil, nil],
- ["unsigned int ref",
- "i",
+ nil, nil],
+ ["unsigned int ref", "i",
proc{|v| [v].pack("I").unpack("i")[0]},
proc{|v| [v].pack("i").unpack("I")[0]},
- nil, nil, nil],
- ["unsigned long ref",
- "l",
+ nil, nil],
+ ["unsigned long ref", "l",
proc{|v| [v].pack("L").unpack("l")[0]},
proc{|v| [v].pack("l").unpack("L")[0]},
- nil, nil, nil],
- ["char ref", "c", nil, nil,
- nil, nil, nil],
- ["short ref", "h", nil, nil,
- nil, nil, nil],
- ["int ref", "i", nil, nil,
- nil, nil, nil],
- ["long ref", "l", nil, nil,
- nil, nil, nil],
- ["float ref", "f", nil, nil,
- nil, nil, nil],
- ["double ref","d", nil, nil,
- nil, nil, nil],
- ["char", "C", nil, nil,
- "C", nil, nil],
- ["short", "H", nil, nil,
- "H", nil, nil],
- ["int", "I", nil, nil,
- "I", nil, nil],
- ["long", "L", nil, nil,
- "L", nil, nil],
- ["float", "F", nil, nil,
- "F", nil, nil],
- ["double", "D", nil, nil,
- "D", nil, nil],
- [/^char\s*\*$/,"s",nil, nil,
- "S",nil, nil],
- [/^const char\s*\*$/,"S",nil, nil,
- "S",nil, nil],
- [/^.+\*$/, "P", nil, nil,
- "P", nil, nil],
- [/^.+\[\]$/, "a", nil, nil,
- "a", nil, nil],
- ["void", "0", nil, nil,
- nil, nil, nil],
+ nil, nil],
+ ["char ref", "c", nil, nil, nil, nil],
+ ["short ref", "h", nil, nil, nil, nil],
+ ["int ref", "i", nil, nil, nil, nil],
+ ["long ref", "l", nil, nil, nil, nil],
+ ["float ref", "f", nil, nil, nil, nil],
+ ["double ref","d", nil, nil, nil, nil],
+ ["char", "C", nil, nil, nil, nil],
+ ["short", "H", nil, nil, nil, nil],
+ ["int", "I", nil, nil, nil, nil],
+ ["long", "L", nil, nil, nil, nil],
+ ["float", "F", nil, nil, nil, nil],
+ ["double", "D", nil, nil, nil, nil],
+ [/^char\s*\*$/,"s",nil, nil, nil, nil],
+ [/^const char\s*\*$/,"S",nil, nil, nil, nil],
+ [/^.+\*$/, "p", nil, nil, nil, nil],
+ [/^.+\[\]$/, "a", nil, nil, nil, nil],
+ ["void", "0", nil, nil, nil, nil],
]
def initialize
init_types()
end
- def typealias(ty1, ty2, enc=nil, dec=nil, ty3=nil, senc=nil, sdec=nil)
- @TYDEFS.unshift([ty1, ty2, enc, dec, ty3, senc, sdec])
+ def typealias(ty1, ty2, enc=nil, dec=nil, senc=nil, sdec=nil)
+ @TYDEFS.unshift([ty1,ty2, enc,dec, senc, sdec])
end
def init_types
@TYDEFS = TYPES.dup
end
- def encode_argument_type(alias_type)
- proc_encode = nil
- proc_decode = nil
- @TYDEFS.each{|aty,ty,enc,dec,_,_,_|
- if( (aty.is_a?(Regexp) && (aty =~ alias_type)) || (aty == alias_type) )
- alias_type = alias_type.gsub(aty,ty) if ty
- alias_type.strip! if alias_type
- if( proc_encode )
- if( enc )
- conv1 = proc_encode
- proc_encode = proc{|v| enc.call(conv1.call(v))}
+ def encode_type(ty)
+ orig_ty = ty
+ enc = nil
+ dec = nil
+ senc = nil
+ sdec = nil
+ @TYDEFS.each{|t1,t2,c1,c2,c3,c4|
+# if( t1.is_a?(String) )
+# t1 = Regexp.new("^" + t1 + "$")
+# end
+ if( (t1.is_a?(Regexp) && (t1 =~ ty)) || (t1 == ty) )
+ ty = ty.gsub(t1,t2)
+ if( enc )
+ if( c1 )
+ conv1 = enc
+ enc = proc{|v| c1.call(conv1.call(v))}
end
else
- if( enc )
- proc_encode = enc
+ if( c1 )
+ enc = c1
end
end
- if( proc_decode )
- if( dec )
- conv2 = proc_decode
- proc_decode = proc{|v| dec.call(conv2.call(v))}
+ if( dec )
+ if( c2 )
+ conv2 = dec
+ dec = proc{|v| c2.call(conv2.call(v))}
end
else
- if( dec )
- proc_decode = dec
+ if( c2 )
+ dec = c2
end
end
- end
- }
- return [alias_type, proc_encode, proc_decode]
- end
-
- def encode_return_type(ty)
- ty, enc, dec = encode_argument_type(ty)
- return [ty, enc, dec]
- end
-
- def encode_struct_type(alias_type)
- proc_encode = nil
- proc_decode = nil
- @TYDEFS.each{|aty,_,_,_,ty,enc,dec|
- if( (aty.is_a?(Regexp) && (aty =~ alias_type)) || (aty == alias_type) )
- alias_type = alias_type.gsub(aty,ty) if ty
- alias_type.strip! if alias_type
- if( proc_encode )
- if( enc )
- conv1 = proc_encode
- proc_encode = proc{|v| enc.call(conv1.call(v))}
+ if( senc )
+ if( c3 )
+ conv3 = senc
+ senc = proc{|v| c3.call(conv3.call(v))}
end
else
- if( enc )
- proc_encode = enc
+ if( c3 )
+ senc = c3
end
end
- if( proc_decode )
- if( dec )
- conv2 = proc_decode
- proc_decode = proc{|v| dec.call(conv2.call(v))}
+ if( sdec )
+ if( c4 )
+ conv4 = sdec
+ sdec = proc{|v| c4.call(conv4.call(v))}
end
else
- if( dec )
- proc_decode = dec
+ if( c4 )
+ sdec = c4
end
end
end
}
- return [alias_type, proc_encode, proc_decode]
+ ty = ty.strip
+ if( ty.length != 1 )
+ raise(TypeError, "unknown type: #{orig_ty}.")
+ end
+ return [ty,enc,dec,senc,sdec]
end
end # end of Types
end
diff --git a/ext/dl/sym.c b/ext/dl/sym.c
index 40b2035c00..c2f5434c61 100644
--- a/ext/dl/sym.c
+++ b/ext/dl/sym.c
@@ -154,9 +154,8 @@ rb_dlsym_initialize(int argc, VALUE argv[], VALUE self)
rb_scan_args(argc, argv, "12", &addr, &name, &type);
saddr = (void*)(DLNUM2LONG(rb_Integer(addr)));
- if (!NIL_P(name)) StringValue(name);
+ sname = NIL_P(name) ? NULL : StringValuePtr(name);
stype = NIL_P(type) ? NULL : StringValuePtr(type);
- sname = NIL_P(name) ? NULL : RSTRING(name)->ptr;
if( saddr ){
Data_Get_Struct(self, struct sym_data, data);
@@ -941,7 +940,6 @@ rb_dlsym_call(int argc, VALUE argv[], VALUE self)
}
}
- FREE_ARGS;
#undef FREE_ARGS
return rb_assoc_new(val,dvals);
}
diff --git a/ext/enumerator/enumerator.c b/ext/enumerator/enumerator.c
index 1c6e1d1ace..74785569e7 100644
--- a/ext/enumerator/enumerator.c
+++ b/ext/enumerator/enumerator.c
@@ -15,34 +15,10 @@
#include "ruby.h"
#include "node.h"
-/*
- * Document-class: Enumerable::Enumerator
- *
- * A class which provides a method `each' to be used as an Enumerable
- * object.
- */
static VALUE rb_cEnumerator;
static ID sym_each, sym_each_with_index, sym_each_slice, sym_each_cons;
static ID id_new, id_enum_obj, id_enum_method, id_enum_args;
-/*
- * call-seq:
- * obj.to_enum(method = :each, *args)
- * obj.enum_for(method = :each, *args)
- *
- * Returns Enumerable::Enumerator.new(self, method, *args).
- *
- * e.g.:
- * str = "xyz"
- *
- * enum = str.enum_for(:each_byte)
- * a = enum.map {|b| '%02x' % b } #=> ["78", "79", "7a"]
- *
- * # protects an array from being modified
- * a = [1, 2, 3]
- * some_method(a.to_enum)
- *
- */
static VALUE
obj_to_enum(obj, enum_args)
VALUE obj, enum_args;
@@ -52,13 +28,6 @@ obj_to_enum(obj, enum_args)
return rb_apply(rb_cEnumerator, id_new, enum_args);
}
-/*
- * call-seq:
- * enum_with_index
- *
- * Returns Enumerable::Enumerator.new(self, :each_with_index).
- *
- */
static VALUE
enumerator_enum_with_index(obj)
VALUE obj;
@@ -84,21 +53,6 @@ each_slice_i(val, memo)
return Qnil;
}
-/*
- * call-seq:
- * e.each_slice(n) {...}
- *
- * Iterates the given block for each slice of <n> elements.
- *
- * e.g.:
- * (1..10).each_slice(3) {|a| p a}
- * # outputs below
- * [1, 2, 3]
- * [4, 5, 6]
- * [7, 8, 9]
- * [10]
- *
- */
static VALUE
enum_each_slice(obj, n)
VALUE obj, n;
@@ -119,13 +73,6 @@ enum_each_slice(obj, n)
return Qnil;
}
-/*
- * call-seq:
- * e.enum_slice(n)
- *
- * Returns Enumerable::Enumerator.new(self, :each_slice, n).
- *
- */
static VALUE
enumerator_enum_slice(obj, n)
VALUE obj, n;
@@ -151,26 +98,6 @@ each_cons_i(val, memo)
return Qnil;
}
-/*
- * call-seq:
- * each_cons(n) {...}
- *
- * Iterates the given block for each array of consecutive <n>
- * elements.
- *
- * e.g.:
- * (1..10).each_cons(3) {|a| p a}
- * # outputs below
- * [1, 2, 3]
- * [2, 3, 4]
- * [3, 4, 5]
- * [4, 5, 6]
- * [5, 6, 7]
- * [6, 7, 8]
- * [7, 8, 9]
- * [8, 9, 10]
- *
- */
static VALUE
enum_each_cons(obj, n)
VALUE obj, n;
@@ -186,13 +113,6 @@ enum_each_cons(obj, n)
return Qnil;
}
-/*
- * call-seq:
- * e.enum_cons(n)
- *
- * Returns Enumerable::Enumerator.new(self, :each_cons, n).
- *
- */
static VALUE
enumerator_enum_cons(obj, n)
VALUE obj, n;
@@ -200,21 +120,6 @@ enumerator_enum_cons(obj, n)
return rb_funcall(rb_cEnumerator, id_new, 3, obj, sym_each_cons, n);
}
-/*
- * call-seq:
- * Enumerable::Enumerator.new(obj, method = :each, *args)
- *
- * Creates a new Enumerable::Enumerator object, which is to be
- * used as an Enumerable object using the given object's given
- * method with the given arguments.
- *
- * e.g.:
- * str = "xyz"
- *
- * enum = Enumerable::Enumerator.new(str, :each_byte)
- * a = enum.map {|b| '%02x' % b } #=> ["78", "79", "7a"]
- *
- */
static VALUE
enumerator_initialize(argc, argv, obj)
int argc;
@@ -242,14 +147,6 @@ enumerator_iter(memo)
return rb_apply(memo->u1.value, memo->u2.id, memo->u3.value);
}
-/*
- * call-seq:
- * enum.each {...}
- *
- * Iterates the given block using the object and the method specified
- * in the first place.
- *
- */
static VALUE
enumerator_each(obj)
VALUE obj;
diff --git a/ext/etc/etc.c b/ext/etc/etc.c
index 94196e066a..c42f279d58 100644
--- a/ext/etc/etc.c
+++ b/ext/etc/etc.c
@@ -23,10 +23,6 @@
#include <grp.h>
#endif
-#ifndef HAVE_TYPE_UID_T
-#define uid_t int
-#endif
-
static VALUE sPasswd, sGroup;
#ifndef _WIN32
@@ -34,11 +30,6 @@ char *getenv();
#endif
char *getlogin();
-/* Returns the short user name of the currently logged in user.
- *
- * e.g.
- * Etc.getlogin -> 'guest'
- */
static VALUE
etc_getlogin(obj)
VALUE obj;
@@ -93,7 +84,7 @@ setup_passwd(pwd)
INT2FIX(pwd->pw_quota),
#endif
#ifdef HAVE_ST_PW_AGE
- PW_AGE2VAL(pwd->pw_age),
+ INT2FIX(pwd->pw_age),
#endif
#ifdef HAVE_ST_PW_CLASS
safe_setup_str(pwd->pw_class),
@@ -109,15 +100,6 @@ setup_passwd(pwd)
}
#endif
-/* Returns the /etc/passwd information for the user with specified integer
- * user id (uid).
- *
- * The information is returned as a Struct::Passwd; see getpwent above for
- * details.
- *
- * e.g. * Etc.getpwuid(0) -> #<struct Struct::Passwd name="root",
- * passwd="x", uid=0, gid=0, gecos="root",dir="/root", shell="/bin/bash">
- */
static VALUE
etc_getpwuid(argc, argv, obj)
int argc;
@@ -144,14 +126,6 @@ etc_getpwuid(argc, argv, obj)
#endif
}
-/* Returns the /etc/passwd information for the user with specified login name.
- *
- * The information is returned as a Struct::Passwd; see getpwent above for
- * details.
- *
- * e.g. * Etc.getpwnam('root') -> #<struct Struct::Passwd name="root",
- * passwd="x", uid=0, gid=0, gecos="root",dir="/root", shell="/bin/bash">
- */
static VALUE
etc_getpwnam(obj, nam)
VALUE obj, nam;
@@ -191,21 +165,6 @@ passwd_iterate()
}
#endif
-/* Provides a convenient Ruby iterator which executes a block for each entry
- * in the /etc/passwd file.
- *
- * The code block is passed an Etc::Passwd struct; see getpwent above for
- * details.
- *
- * Example:
- *
- * require 'etc'
- *
- * Etc.passwd {|u|
- * puts u.name + " = " + u.gecos
- * }
- *
- */
static VALUE
etc_passwd(obj)
VALUE obj;
@@ -228,9 +187,6 @@ etc_passwd(obj)
return Qnil;
}
-/* Resets the process of reading the /etc/passwd file, so that the next call
- * to getpwent will return the first entry again.
- */
static VALUE
etc_setpwent(obj)
VALUE obj;
@@ -241,9 +197,6 @@ etc_setpwent(obj)
return Qnil;
}
-/* Ends the process of scanning through the /etc/passwd file begun with
- * getpwent, and closes the file.
- */
static VALUE
etc_endpwent(obj)
VALUE obj;
@@ -254,32 +207,6 @@ etc_endpwent(obj)
return Qnil;
}
-/* Returns an entry from the /etc/passwd file. The first time it is called it
- * opens the file and returns the first entry; each successive call returns
- * the next entry, or nil if the end of the file has been reached.
- *
- * To close the file when processing is complete, call endpwent.
- *
- * Each entry is returned as a Struct::Passwd:
- *
- * - Passwd#name contains the short login name of the user as a String.
- *
- * - Passwd#passwd contains the encrypted password of the user as a String.
- * an 'x' is returned if shadow passwords are in use. An '*' is returned
- * if the user cannot log in using a password.
- *
- * - Passwd#uid contains the integer user ID (uid) of the user.
- *
- * - Passwd#gid contains the integer group ID (gid) of the user's primary group.
- *
- * - Passwd#gecos contains a longer String description of the user, such as
- * a full name. Some Unix systems provide structured information in the
- * gecos field, but this is system-dependent.
- *
- * - Passwd#dir contains the path to the home directory of the user as a String.
- *
- * - Passwd#shell contains the path to the login shell of the user as a String.
- */
static VALUE
etc_getpwent(obj)
VALUE obj;
@@ -318,16 +245,6 @@ setup_group(grp)
}
#endif
-/* Returns information about the group with specified integer group id (gid),
- * as found in /etc/group.
- *
- * The information is returned as a Struct::Group; see getgrent above for
- * details.
- *
- * e.g. Etc.getgrgid(100) -> #<struct Struct::Group name="users", passwd="x",
- * gid=100, mem=["meta", "root"]>
- *
- */
static VALUE
etc_getgrgid(obj, id)
VALUE obj, id;
@@ -346,16 +263,6 @@ etc_getgrgid(obj, id)
#endif
}
-/* Returns information about the group with specified String name, as found
- * in /etc/group.
- *
- * The information is returned as a Struct::Group; see getgrent above for
- * details.
- *
- * e.g. Etc.getgrnam('users') -> #<struct Struct::Group name="users",
- * passwd="x", gid=100, mem=["meta", "root"]>
- *
- */
static VALUE
etc_getgrnam(obj, nam)
VALUE obj, nam;
@@ -396,21 +303,6 @@ group_iterate()
}
#endif
-/* Provides a convenient Ruby iterator which executes a block for each entry
- * in the /etc/group file.
- *
- * The code block is passed an Etc::Group struct; see getgrent above for
- * details.
- *
- * Example:
- *
- * require 'etc'
- *
- * Etc.group {|g|
- * puts g.name + ": " + g.mem.join(', ')
- * }
- *
- */
static VALUE
etc_group(obj)
VALUE obj;
@@ -433,9 +325,6 @@ etc_group(obj)
return Qnil;
}
-/* Resets the process of reading the /etc/group file, so that the next call
- * to getgrent will return the first entry again.
- */
static VALUE
etc_setgrent(obj)
VALUE obj;
@@ -446,9 +335,6 @@ etc_setgrent(obj)
return Qnil;
}
-/* Ends the process of scanning through the /etc/group file begun by
- * getgrent, and closes the file.
- */
static VALUE
etc_endgrent(obj)
VALUE obj;
@@ -459,26 +345,6 @@ etc_endgrent(obj)
return Qnil;
}
-/* Returns an entry from the /etc/group file. The first time it is called it
- * opens the file and returns the first entry; each successive call returns
- * the next entry, or nil if the end of the file has been reached.
- *
- * To close the file when processing is complete, call endgrent.
- *
- * Each entry is returned as a Struct::Group:
- *
- * - Group#name contains the name of the group as a String.
- *
- * - Group#passwd contains the encrypted password as a String. An 'x' is
- * returned if password access to the group is not available; an empty
- * string is returned if no password is needed to obtain membership of
- * the group.
- *
- * - Group#gid contains the group's numeric ID as an integer.
- *
- * - Group#mem is an Array of Strings containing the short login names of the
- * members of the group.
- */
static VALUE
etc_getgrent(obj)
VALUE obj;
@@ -495,11 +361,6 @@ etc_getgrent(obj)
static VALUE mEtc;
-/* The etc module provides access to information from the /etc/passwd and
- * /etc/group files on Linux and Unix systems.
- *
- * Documented by mathew <meta@pobox.com>.
- */
void
Init_etc()
{
@@ -549,11 +410,7 @@ Init_etc()
rb_global_variable(&sPasswd);
#ifdef HAVE_GETGRENT
- sGroup = rb_struct_define("Group", "name",
-#ifdef HAVE_ST_GR_PASSWD
- "passwd",
-#endif
- "gid", "mem", NULL);
+ sGroup = rb_struct_define("Group", "name", "passwd", "gid", "mem", NULL);
rb_global_variable(&sGroup);
#endif
}
diff --git a/ext/etc/extconf.rb b/ext/etc/extconf.rb
index 0dc8e7ddac..16f2da352b 100644
--- a/ext/etc/extconf.rb
+++ b/ext/etc/extconf.rb
@@ -8,22 +8,11 @@ if a or b or c
have_struct_member('struct passwd', 'pw_gecos', 'pwd.h')
have_struct_member('struct passwd', 'pw_change', 'pwd.h')
have_struct_member('struct passwd', 'pw_quota', 'pwd.h')
- if have_struct_member('struct passwd', 'pw_age', 'pwd.h')
- case what_type?('struct passwd', 'pw_age', 'pwd.h')
- when "string"
- f = "safe_setup_str"
- when "long long"
- f = "LL2NUM"
- else
- f = "INT2NUM"
- end
- $defs.push("-DPW_AGE2VAL="+f)
- end
+ have_struct_member('struct passwd', 'pw_age', 'pwd.h')
have_struct_member('struct passwd', 'pw_class', 'pwd.h')
have_struct_member('struct passwd', 'pw_comment', 'pwd.h') unless /cygwin/ === RUBY_PLATFORM
have_struct_member('struct passwd', 'pw_expire', 'pwd.h')
have_struct_member('struct passwd', 'pw_passwd', 'pwd.h')
have_struct_member('struct group', 'gr_passwd', 'grp.h')
- have_type("uid_t");
create_makefile("etc")
end
diff --git a/ext/extmk.rb b/ext/extmk.rb
index 79e44b9e63..5d26b43e13 100644
--- a/ext/extmk.rb
+++ b/ext/extmk.rb
@@ -16,73 +16,26 @@ alias $PROGRAM_NAME $0
alias $0 $progname
$extlist = []
-$extupdate = false
-$compiled = {}
-$:.replace([Dir.pwd])
+$:.replace ["."]
require 'rbconfig'
srcdir = File.dirname(File.dirname(__FILE__))
-$:.unshift(srcdir, File.expand_path("lib", srcdir))
+$:.replace [srcdir, srcdir+"/lib", "."]
+
+require 'mkmf'
+require 'getopts'
$topdir = "."
$top_srcdir = srcdir
-
-require 'mkmf'
-require 'optparse/shellwords'
+$hdrdir = $top_srcdir
def sysquote(x)
@quote ||= /human|os2|macos/ =~ (CROSS_COMPILING || RUBY_PLATFORM)
@quote ? x.quote : x
end
-def relative_from(path, base)
- dir = File.join(path, "")
- if File.expand_path(dir) == File.expand_path(dir, base)
- path
- else
- File.join(base, path)
- end
-end
-
-def extract_makefile(makefile, keep = true)
- m = File.read(makefile)
- if !(target = m[/^TARGET[ \t]*=[ \t]*(\S*)/, 1])
- return keep
- end
- installrb = {}
- m.scan(/^install-rb-default:[ \t]*(\S+)\n\1:[ \t]*(\S+)/) {installrb[$2] = $1}
- oldrb = installrb.keys.sort
- newrb = install_rb(nil, "").collect {|d, *f| f}.flatten.sort
- if target_prefix = m[/^target_prefix[ \t]*=[ \t]*\/(.*)/, 1]
- target = "#{target_prefix}/#{target}"
- end
- unless oldrb == newrb
- if $extout
- newrb.each {|f| installrb.delete(f)}
- unless installrb.empty?
- config = CONFIG.dup
- install_dirs(target_prefix).each {|var, val| config[var] = val}
- FileUtils.rm_f(installrb.values.collect {|f| Config.expand(f, config)}, :verbose => true)
- end
- end
- return false
- end
- $target = target
- /^STATIC_LIB[ \t]*=[ \t]*\S+/ =~ m or $static = nil
- $preload = Shellwords.shellwords(m[/^preload[ \t]*=[ \t]*(.*)/, 1] || "")
- $DLDFLAGS += " " + (m[/^DLDFLAGS[ \t]*=[ \t]*(.*)/, 1] || "")
- if s = m[/^LIBS[ \t]*=[ \t]*(.*)/, 1]
- s.sub!(/^#{Regexp.quote($LIBRUBYARG)} */, "")
- s.sub!(/ *#{Regexp.quote($LIBS)}$/, "")
- $libs = s
- end
- $LOCAL_LIBS = m[/^LOCAL_LIBS[ \t]*=[ \t]*(.*)/, 1] || ""
- $LIBPATH = Shellwords.shellwords(m[/^libpath[ \t]*=[ \t]*(.*)/, 1] || "") - %w[$(libdir) $(topdir)]
- true
-end
-
def extmake(target)
print "#{$message} #{target}\n"
$stdout.flush
@@ -96,42 +49,35 @@ def extmake(target)
return true if $nodynamic and not $static
end
- FileUtils.mkpath target unless File.directory?(target)
+ init_mkmf
+
begin
dir = Dir.pwd
FileUtils.mkpath target unless File.directory?(target)
Dir.chdir target
top_srcdir = $top_srcdir
topdir = $topdir
- mk_srcdir = CONFIG["srcdir"]
- mk_topdir = CONFIG["topdir"]
prefix = "../" * (target.count("/")+1)
- $hdrdir = $top_srcdir = relative_from(top_srcdir, prefix)
+ if File.expand_path(top_srcdir) != File.expand_path(top_srcdir, dir)
+ $hdrdir = $top_srcdir = prefix + top_srcdir
+ end
$topdir = prefix + $topdir
$target = target
$mdir = target
$srcdir = File.join($top_srcdir, "ext", $mdir)
$preload = nil
- $compiled[target] = false
makefile = "./Makefile"
- ok = File.exist?(makefile)
unless $ignore
- Config::CONFIG["hdrdir"] = $hdrdir
- Config::CONFIG["srcdir"] = $srcdir
- Config::CONFIG["topdir"] = $topdir
- CONFIG["hdrdir"] = ($hdrdir == top_srcdir) ? top_srcdir : "$(topdir)"+top_srcdir[2..-1]
- CONFIG["srcdir"] = "$(hdrdir)/ext/#{$mdir}"
- CONFIG["topdir"] = $topdir
- begin
- if (!(ok &&= extract_makefile(makefile)) ||
- !(t = modified?(makefile, MTIMES)) ||
- %W"#{$srcdir}/makefile.rb #{$srcdir}/extconf.rb #{$srcdir}/depend".any? {|f| modified?(f, [t])})
- then
- ok = false
- init_mkmf
- $defs << "-DRUBY_EXPORT" if $static
- Logging::logfile 'mkmf.log'
- rm_f makefile
+ if $static ||
+ !(t = modified?(makefile, MTIMES)) ||
+ %W<#{$srcdir}/makefile.rb #{$srcdir}/extconf.rb
+ #{$srcdir}/depend>.any? {|f| modified?(f, [t])}
+ then
+ $defs = []
+ Logging::logfile 'mkmf.log'
+ Config::CONFIG["srcdir"] = $srcdir
+ rm_f makefile
+ begin
if File.exist?($0 = "#{$srcdir}/makefile.rb")
load $0
elsif File.exist?($0 = "#{$srcdir}/extconf.rb")
@@ -139,118 +85,64 @@ def extmake(target)
else
create_makefile(target)
end
- $extupdate = true
- ok = File.exist?(makefile)
+ File.exist?(makefile)
+ rescue SystemExit
+ # ignore
+ ensure
+ rm_f "conftest*"
+ $0 = $PROGRAM_NAME
+ Config::CONFIG["srcdir"] = $top_srcdir
end
- rescue SystemExit
- # ignore
- ensure
- rm_f "conftest*"
- config = $0
- $0 = $PROGRAM_NAME
- end
- end
- ok = yield(ok) if block_given?
- unless ok
- open(makefile, "w") do |f|
- f.print dummy_makefile(CONFIG["srcdir"])
+ else
+ true
end
+ else
+ File.exist?(makefile)
+ end or open(makefile, "w") do |f|
+ f.print dummy_makefile($srcdir)
return true
end
args = sysquote($mflags)
- unless $destdir.to_s.empty? or $mflags.include?("DESTDIR")
- args += [sysquote("DESTDIR=" + relative_from($destdir, "../"+prefix))]
- end
if $static
- args += ["static"] unless $clean
+ args += ["static"]
$extlist.push [$static, $target, File.basename($target), $preload]
end
unless system($make, *args)
$ignore or $continue or return false
end
- $compiled[target] = true
- if $clean and $clean != true
- File.unlink(makefile) rescue nil
- end
if $static
$extflags ||= ""
$extlibs ||= []
$extpath ||= []
- unless $mswin
- $extflags = ($extflags.split | $DLDFLAGS.split | $LDFLAGS.split).join(" ")
- end
+ $extflags += " " + $DLDFLAGS unless $DLDFLAGS.empty?
+ $extflags += " " + $LDFLAGS unless $LDFLAGS.empty?
$extlibs = merge_libs($extlibs, $libs.split, $LOCAL_LIBS.split)
$extpath |= $LIBPATH
end
ensure
$hdrdir = $top_srcdir = top_srcdir
- Config::CONFIG["topdir"] = topdir
- CONFIG["srcdir"] = mk_srcdir
- CONFIG["topdir"] = mk_topdir
- CONFIG.delete("hdrdir")
$topdir = topdir
Dir.chdir dir
end
- begin
- Dir.rmdir target
- target = File.dirname(target)
- rescue SystemCallError
- break
- end while true
true
end
-def compiled?(target)
- $compiled[target]
-end
-
def parse_args()
- $mflags = []
-
- opts = nil
- $optparser ||= OptionParser.new do |opts|
- opts.on('-n') {$dryrun = true}
- opts.on('--[no-]extension [EXTS]', Array) do |v|
- $extension = (v == false ? [] : v)
- end
- opts.on('--[no-]extstatic [STATIC]', Array) do |v|
- if ($extstatic = v) == false
- $extstatic = []
- elsif v
- $force_static = true
- $extstatic.delete("static")
- $extstatic = nil if $extstatic.empty?
- end
- end
- opts.on('--dest-dir=DIR') do |v|
- $destdir = v
- end
- opts.on('--extout=DIR') do |v|
- $extout = (v unless v.empty?)
- end
- opts.on('--make=MAKE') do |v|
- $make = v || 'make'
- end
- opts.on('--make-flags=FLAGS', '--mflags', Shellwords) do |v|
- if arg = v.first
- arg.insert(0, '-') if /\A[^-][^=]*\Z/ =~ arg
- end
- $mflags.concat(v)
- end
- opts.on('--message [MESSAGE]', String) do |v|
- $message = v
- end
- end
- begin
- $optparser.parse!(ARGV)
- rescue OptionParser::InvalidOption => e
- retry if /^--/ =~ e.args[0]
- $optparser.warn(e)
- abort opts.to_s
+ getopts('n', 'extstatic:', 'dest-dir:',
+ 'make:', 'make-flags:', 'mflags:')
+
+ $dryrun = $OPT['n']
+ $force_static = $OPT['extstatic'] == 'static'
+ $destdir = $OPT['dest-dir'] || ''
+ $make = $OPT['make'] || $make || 'make'
+ mflags = ($OPT['make-flags'] || '').strip
+ mflags = ($OPT['mflags'] || '').strip if mflags.empty?
+
+ $mflags = Shellwords.shellwords(mflags)
+ if arg = $mflags.first
+ arg.insert(0, '-') if /\A[^-][^=]*\Z/ =~ arg
end
- $destdir ||= ''
-
$make, *rest = Shellwords.shellwords($make)
$mflags.unshift(*rest) unless rest.empty?
@@ -258,10 +150,6 @@ def parse_args()
grep(/\A-(?!-).*#{'%c' % flag}/i) { return true }
false
end
- def $mflags.defined?(var)
- grep(/\A#{var}=(.*)/) {return $1}
- false
- end
if $mflags.set?(?n)
$dryrun = true
@@ -270,33 +158,25 @@ def parse_args()
end
$continue = $mflags.set?(?k)
- if $extout
- $extout = '$(topdir)/'+$extout
- $extout_prefix = $extout ? "$(extout)$(target_prefix)/" : ""
- $mflags << "extout=#$extout" << "extout_prefix=#$extout_prefix"
- end
+ $mflags |= ["DESTDIR=#{$destdir}"]
end
parse_args()
-if target = ARGV.shift and /^[a-z-]+$/ =~ target
- $mflags.push(target)
- target = target.sub(/^(dist|real)(?=(?:clean)?$)/, '')
- case target
- when /clean/
- $ignore ||= true
- $clean = $1 ? $1[0] : true
- when /^install\b/
- $install = true
- $ignore ||= true
- $mflags.unshift("INSTALL_PROG=install -c -p -m 0755",
- "INSTALL_DATA=install -c -p -m 0644",
- "MAKEDIRS=mkdir -p") if $dryrun
- end
-end
unless $message
- if target
- $message = target.sub(/^(\w+)e?\b/, '\1ing').tr('-', ' ')
+ if $message = ARGV.shift and /^[a-z]+$/ =~ $message
+ $mflags.push($message)
+ $message = $message.sub(/^(?:dist|real)(?=(?:clean)?$)/, '\1')
+ case $message
+ when "clean"
+ $ignore ||= true
+ when "install"
+ $ignore ||= true
+ $mflags.unshift("INSTALL_PROG=install -c -p -m 0755",
+ "INSTALL_DATA=install -c -p -m 0644",
+ "MAKEDIRS=mkdir -p") if $dryrun
+ end
+ $message.sub!(/e?$/, "ing")
else
$message = "compiling"
end
@@ -310,19 +190,13 @@ elsif $nmake
else
$ruby = '$(topdir)/miniruby' + EXEEXT
end
-$ruby << " -I'$(topdir)' -I'$(hdrdir)/lib'"
+$ruby << " -I$(topdir) -I$(hdrdir)/lib"
$config_h = '$(topdir)/config.h'
MTIMES = [__FILE__, 'rbconfig.rb', srcdir+'/lib/mkmf.rb'].collect {|f| File.mtime(f)}
# get static-link modules
$static_ext = {}
-if $extstatic
- $extstatic.each do |target|
- target = target.downcase if /mswin32|bccwin32/ =~ RUBY_PLATFORM
- $static_ext[target] = $static_ext.size
- end
-end
for dir in ["ext", File::join($top_srcdir, "ext")]
setup = File::join(dir, CONFIG['setup'])
if File.file? setup
@@ -340,72 +214,34 @@ for dir in ["ext", File::join($top_srcdir, "ext")]
next
end
target = target.downcase if /mswin32|bccwin32/ =~ RUBY_PLATFORM
- $static_ext[target] = $static_ext.size
+ $static_ext[target] = true
end
MTIMES << f.mtime
$setup = setup
f.close
break
end
-end unless $extstatic
-
-ext_prefix = "#{$top_srcdir}/ext"
-exts = $static_ext.sort_by {|t, i| i}.collect {|t, i| t}
-if $extension
- exts |= $extension.select {|d| File.directory?("#{ext_prefix}/#{d}")}
-else
- withes, withouts = %w[--with --without].collect {|w|
- if not (w = %w[-extensions -ext].collect {|opt|arg_config(w+opt)}).any?
- proc {false}
- elsif (w = w.grep(String)).empty?
- proc {true}
- else
- w.collect {|opt| opt.split(/,/)}.flatten.method(:any?)
- end
- }
- cond = proc {|ext|
- cond1 = proc {|n| File.fnmatch(n, ext, File::FNM_PATHNAME)}
- withes.call(&cond1) or !withouts.call(&cond1)
- }
- exts |= Dir.glob("#{ext_prefix}/*/**/extconf.rb").collect {|d|
- d = File.dirname(d)
- d.slice!(0, ext_prefix.length + 1)
- d
- }.find_all {|ext|
- with_config(ext, &cond)
- }.sort
-end
-
-if $extout
- Config.expand(extout = "#$extout", Config::CONFIG.merge("topdir"=>$topdir))
- if $install
- Config.expand(dest = "#{$destdir}#{$rubylibdir}")
- FileUtils.cp_r(extout+"/.", dest, :verbose => true, :noop => $dryrun)
- exit
- end
- unless $ignore
- FileUtils.mkpath(extout)
- end
end
dir = Dir.pwd
FileUtils::makedirs('ext')
Dir::chdir('ext')
-$hdrdir = $top_srcdir = relative_from(srcdir, $topdir = "..")
-exts.each do |d|
- extmake(d) or abort
+if File.expand_path(srcdir) != File.expand_path(srcdir, dir)
+ $hdrdir = $top_srcdir = "../" + srcdir
+end
+$topdir = ".."
+ext_prefix = "#{$top_srcdir}/ext"
+Dir.glob("#{ext_prefix}/*/**/extconf.rb") do |d|
+ d = File.dirname(d)
+ d.slice!(0, ext_prefix.length + 1)
+ extmake(d) or exit(1)
end
$hdrdir = $top_srcdir = srcdir
$topdir = "."
if $ignore
- FileUtils.rm_f(%W"extinit.c extinit.#{$OBJEXT}") if $clean
Dir.chdir ".."
- if $clean
- Dir.rmdir('ext') rescue nil
- FileUtils.rm_rf(extout) if $extout
- end
exit
end
@@ -447,8 +283,7 @@ SRC
$extpath.delete("$(topdir)")
$extflags = libpathflag($extpath) << " " << $extflags.strip
conf = [
- ['SETUP', $setup],
- [enable_config("shared", $enable_shared) ? 'DLDOBJS' : 'EXTOBJS', $extobjs],
+ ['SETUP', $setup], [$enable_shared ? 'DLDOBJS' : 'EXTOBJS', $extobjs],
['EXTLIBS', $extlibs.join(' ')], ['EXTLDFLAGS', $extflags]
].map {|n, v|
"#{n}=#{v}" if v and !(v = v.strip).empty?
@@ -459,25 +294,17 @@ SRC
end
rubies = []
%w[RUBY RUBYW].each {|r|
- if r = arg_config("--"+r.downcase) || config_string(r+"_INSTALL_NAME")
- rubies << r+EXEEXT
- end
+ config_string(r+"_INSTALL_NAME") {|r| rubies << r+EXEEXT}
}
Dir.chdir ".."
-unless $destdir.to_s.empty?
- $mflags.defined?("DESTDIR") or $mflags << "DESTDIR=#{$destdir}"
-end
-if !$extlist.empty? and $extupdate
+if $extlist.size > 0
rm_f(Config::CONFIG["LIBRUBY_SO"])
end
puts "making #{rubies.join(', ')}"
$stdout.flush
$mflags.concat(rubies)
-if $nmake == ?b
- $mflags.collect {|flag| flag.sub!(/\A(?=\w+=)/, "-D")}
-end
system($make, *sysquote($mflags)) or exit($?.exitstatus)
#Local variables:
diff --git a/ext/fcntl/fcntl.c b/ext/fcntl/fcntl.c
index 57cca103f4..d48630fc66 100644
--- a/ext/fcntl/fcntl.c
+++ b/ext/fcntl/fcntl.c
@@ -34,81 +34,6 @@ pack up your own arguments to pass as args for locking functions, etc.
#include "ruby.h"
#include <fcntl.h>
-/* Fcntl loads the constants defined in the system's <fcntl.h> C header
- * file, and used with both the fcntl(2) and open(2) POSIX system calls.
- *
- * Copyright (C) 1997-2001 Yukihiro Matsumoto
- *
- * Documented by mathew <meta@pobox.com>
- *
- * = Usage
- *
- * To perform a fcntl(2) operation, use IO::fcntl in the core classes.
- *
- * To perform an open(2) operation, use IO::sysopen.
- *
- * The set of operations and constants available depends upon specific OS
- * platform. Some values listed below may not be supported on your system.
- *
- * The constants supported by Ruby for use with IO::fcntl are:
- *
- * - F_DUPFD - duplicate a close-on-exec file handle to a non-close-on-exec
- * file handle.
- *
- * - F_GETFD - read the close-on-exec flag of a file handle.
- *
- * - F_SETFD - set the close-on-exec flag of a file handle.
- *
- * - FD_CLOEXEC - the value of the close-on-exec flag.
- *
- * - F_GETFL - get file descriptor flags.
- *
- * - F_SETFL - set file descriptor flags.
- *
- * - O_APPEND, O_NONBLOCK, etc (see below) - file descriptor flag
- * values for the above.
- *
- * - F_GETLK - determine whether a given region of a file is locked.
- *
- * - F_SETLK - acquire a lock on a region of a file.
- *
- * - F_SETLKW - acquire a lock on a region of a file, waiting if necessary.
- *
- * - F_RDLCK, F_WRLCK, F_UNLCK - types of lock for the above.
- *
- * The constants supported by Ruby for use with IO::sysopen are:
- *
- * - O_APPEND - open file in append mode.
- *
- * - O_NOCTTY - open tty without it becoming controlling tty.
- *
- * - O_CREAT - create file if it doesn't exist.
- *
- * - O_EXCL - used with O_CREAT, fail if file exists.
- *
- * - O_TRUNC - truncate file on open.
- *
- * - O_NONBLOCK / O_NDELAY - open in non-blocking mode.
- *
- * - O_RDONLY - open read-only.
- *
- * - O_WRONLY - open write-only.
- *
- * - O_RDWR - open read-write.
- *
- * - O_ACCMODE - mask to extract read/write flags.
- *
- * Example:
- *
- * require 'fcntl'
- *
- * fd = IO::sysopen('/tmp/tempfile',
- * Fcntl::O_WRONLY | Fcntl::O_EXCL | Fcntl::O_CREAT)
- * f = IO.open(fd)
- * f.syswrite("TEMP DATA")
- * f.close
- *
- */
void
Init_fcntl()
{
diff --git a/ext/gdbm/gdbm.c b/ext/gdbm/gdbm.c
index d50cb91eed..799445a89c 100644
--- a/ext/gdbm/gdbm.c
+++ b/ext/gdbm/gdbm.c
@@ -44,11 +44,6 @@ closed_dbm()
if (dbmp->di_dbm == 0) closed_dbm();\
} while (0)
-#define GetDBM2(obj, data, dbm) {\
- GetDBM(obj, data);\
- (dbm) = dbmp->di_dbm;\
-}
-
static void
free_dbm(dbmp)
struct dbmdata *dbmp;
@@ -72,21 +67,6 @@ fgdbm_close(obj)
return Qnil;
}
-static VALUE
-fgdbm_closed(obj)
- VALUE obj;
-{
- struct dbmdata *dbmp;
-
- Data_Get_Struct(obj, struct dbmdata, dbmp);
- if (dbmp == 0)
- return Qtrue;
- if (dbmp->di_dbm == 0)
- return Qtrue;
-
- return Qfalse;
-}
-
static VALUE fgdbm_s_alloc _((VALUE));
static VALUE
@@ -222,7 +202,8 @@ rb_gdbm_fetch3(obj, keystr)
struct dbmdata *dbmp;
GDBM_FILE dbm;
- GetDBM2(obj, dbmp, dbm);
+ GetDBM(obj, dbmp);
+ dbm = dbmp->di_dbm;
return rb_gdbm_fetch2(dbm, keystr);
}
@@ -318,7 +299,8 @@ fgdbm_index(obj, valstr)
VALUE keystr, valstr2;
StringValue(valstr);
- GetDBM2(obj, dbmp, dbm);
+ GetDBM(obj, dbmp);
+ dbm = dbmp->di_dbm;
for (keystr = rb_gdbm_firstkey(dbm); RTEST(keystr);
keystr = rb_gdbm_nextkey(dbm, keystr)) {
@@ -367,16 +349,15 @@ fgdbm_select(argc, argv, obj)
if (argc > 0) {
rb_raise(rb_eArgError, "wrong number arguments(%d for 0)", argc);
}
- GetDBM2(obj, dbmp, dbm);
+ GetDBM(obj, dbmp);
+ dbm = dbmp->di_dbm;
+
for (keystr = rb_gdbm_firstkey(dbm); RTEST(keystr);
keystr = rb_gdbm_nextkey(dbm, keystr)) {
VALUE assoc = rb_assoc_new(keystr, rb_gdbm_fetch2(dbm, keystr));
- VALUE v = rb_yield(assoc);
- if (RTEST(v)) {
- rb_ary_push(new, assoc);
- }
- GetDBM2(obj, dbmp, dbm);
+ if (RTEST(rb_yield(assoc)))
+ rb_ary_push(new, assoc);
}
}
else {
@@ -427,7 +408,9 @@ rb_gdbm_delete(obj, keystr)
key.dptr = RSTRING(keystr)->ptr;
key.dsize = RSTRING(keystr)->len;
- GetDBM2(obj, dbmp, dbm);
+ GetDBM(obj, dbmp);
+ dbm = dbmp->di_dbm;
+
if (!gdbm_exists(dbm, key)) {
return Qnil;
}
@@ -462,7 +445,9 @@ fgdbm_shift(obj)
VALUE keystr, valstr;
rb_gdbm_modify(obj);
- GetDBM2(obj, dbmp, dbm);
+ GetDBM(obj, dbmp);
+ dbm = dbmp->di_dbm;
+
keystr = rb_gdbm_firstkey(dbm);
if (NIL_P(keystr)) return Qnil;
valstr = rb_gdbm_fetch2(dbm, keystr);
@@ -482,7 +467,8 @@ fgdbm_delete_if(obj)
int i, status = 0, n;
rb_gdbm_modify(obj);
- GetDBM2(obj, dbmp, dbm);
+ GetDBM(obj, dbmp);
+ dbm = dbmp->di_dbm;
n = dbmp->di_size;
dbmp->di_size = -1;
@@ -493,7 +479,6 @@ fgdbm_delete_if(obj)
ret = rb_protect(rb_yield, rb_assoc_new(keystr, valstr), &status);
if (status != 0) break;
if (RTEST(ret)) rb_ary_push(ary, keystr);
- GetDBM2(obj, dbmp, dbm);
}
for (i = 0; i < RARRAY(ary)->len; i++)
@@ -513,7 +498,8 @@ fgdbm_clear(obj)
GDBM_FILE dbm;
rb_gdbm_modify(obj);
- GetDBM2(obj, dbmp, dbm);
+ GetDBM(obj, dbmp);
+ dbm = dbmp->di_dbm;
dbmp->di_size = -1;
#if 0
@@ -551,7 +537,8 @@ fgdbm_invert(obj)
VALUE keystr, valstr;
VALUE hash = rb_hash_new();
- GetDBM2(obj, dbmp, dbm);
+ GetDBM(obj, dbmp);
+ dbm = dbmp->di_dbm;
for (keystr = rb_gdbm_firstkey(dbm); RTEST(keystr);
keystr = rb_gdbm_nextkey(dbm, keystr)) {
valstr = rb_gdbm_fetch2(dbm, keystr);
@@ -611,16 +598,16 @@ fgdbm_store(obj, keystr, valstr)
rb_gdbm_modify(obj);
StringValue(keystr);
- StringValue(valstr);
-
key.dptr = RSTRING(keystr)->ptr;
key.dsize = RSTRING(keystr)->len;
+ StringValue(valstr);
val.dptr = RSTRING(valstr)->ptr;
val.dsize = RSTRING(valstr)->len;
- GetDBM2(obj, dbmp, dbm);
+ GetDBM(obj, dbmp);
dbmp->di_size = -1;
+ dbm = dbmp->di_dbm;
if (gdbm_store(dbm, key, val, GDBM_REPLACE)) {
if (errno == EPERM) rb_sys_fail(0);
rb_raise(rb_eGDBMError, "%s", gdbm_strerror(gdbm_errno));
@@ -638,8 +625,9 @@ fgdbm_length(obj)
GDBM_FILE dbm;
int i = 0;
- GetDBM2(obj, dbmp, dbm);
+ GetDBM(obj, dbmp);
if (dbmp->di_size > 0) return INT2FIX(dbmp->di_size);
+ dbm = dbmp->di_dbm;
for (key = gdbm_firstkey(dbm); key.dptr; key = nextkey) {
nextkey = gdbm_nextkey(dbm, key);
@@ -683,12 +671,13 @@ fgdbm_each_value(obj)
GDBM_FILE dbm;
VALUE keystr;
- GetDBM2(obj, dbmp, dbm);
+ GetDBM(obj, dbmp);
+ dbm = dbmp->di_dbm;
+
for (keystr = rb_gdbm_firstkey(dbm); RTEST(keystr);
keystr = rb_gdbm_nextkey(dbm, keystr)) {
rb_yield(rb_gdbm_fetch2(dbm, keystr));
- GetDBM2(obj, dbmp, dbm);
}
return obj;
}
@@ -701,12 +690,13 @@ fgdbm_each_key(obj)
GDBM_FILE dbm;
VALUE keystr;
- GetDBM2(obj, dbmp, dbm);
+ GetDBM(obj, dbmp);
+ dbm = dbmp->di_dbm;
+
for (keystr = rb_gdbm_firstkey(dbm); RTEST(keystr);
keystr = rb_gdbm_nextkey(dbm, keystr)) {
rb_yield(keystr);
- GetDBM2(obj, dbmp, dbm);
}
return obj;
}
@@ -719,12 +709,13 @@ fgdbm_each_pair(obj)
struct dbmdata *dbmp;
VALUE keystr;
- GetDBM2(obj, dbmp, dbm);
+ GetDBM(obj, dbmp);
+ dbm = dbmp->di_dbm;
+
for (keystr = rb_gdbm_firstkey(dbm); RTEST(keystr);
keystr = rb_gdbm_nextkey(dbm, keystr)) {
rb_yield(rb_assoc_new(keystr, rb_gdbm_fetch2(dbm, keystr)));
- GetDBM2(obj, dbmp, dbm);
}
return obj;
@@ -738,7 +729,9 @@ fgdbm_keys(obj)
GDBM_FILE dbm;
VALUE keystr, ary;
- GetDBM2(obj, dbmp, dbm);
+ GetDBM(obj, dbmp);
+ dbm = dbmp->di_dbm;
+
ary = rb_ary_new();
for (keystr = rb_gdbm_firstkey(dbm); RTEST(keystr);
keystr = rb_gdbm_nextkey(dbm, keystr)) {
@@ -758,7 +751,9 @@ fgdbm_values(obj)
GDBM_FILE dbm;
VALUE valstr, ary;
- GetDBM2(obj, dbmp, dbm);
+ GetDBM(obj, dbmp);
+ dbm = dbmp->di_dbm;
+
ary = rb_ary_new();
for (key = gdbm_firstkey(dbm); key.dptr; key = nextkey) {
nextkey = gdbm_nextkey(dbm, key);
@@ -782,7 +777,8 @@ fgdbm_has_key(obj, keystr)
key.dptr = RSTRING(keystr)->ptr;
key.dsize = RSTRING(keystr)->len;
- GetDBM2(obj, dbmp, dbm);
+ GetDBM(obj, dbmp);
+ dbm = dbmp->di_dbm;
if (gdbm_exists(dbm, key))
return Qtrue;
return Qfalse;
@@ -797,7 +793,8 @@ fgdbm_has_value(obj, valstr)
VALUE keystr, valstr2;
StringValue(valstr);
- GetDBM2(obj, dbmp, dbm);
+ GetDBM(obj, dbmp);
+ dbm = dbmp->di_dbm;
for (keystr = rb_gdbm_firstkey(dbm); RTEST(keystr);
keystr = rb_gdbm_nextkey(dbm, keystr)) {
@@ -821,7 +818,9 @@ fgdbm_to_a(obj)
GDBM_FILE dbm;
VALUE keystr, ary;
- GetDBM2(obj, dbmp, dbm);
+ GetDBM(obj, dbmp);
+ dbm = dbmp->di_dbm;
+
ary = rb_ary_new();
for (keystr = rb_gdbm_firstkey(dbm); RTEST(keystr);
keystr = rb_gdbm_nextkey(dbm, keystr)) {
@@ -840,7 +839,8 @@ fgdbm_reorganize(obj)
GDBM_FILE dbm;
rb_gdbm_modify(obj);
- GetDBM2(obj, dbmp, dbm);
+ GetDBM(obj, dbmp);
+ dbm = dbmp->di_dbm;
gdbm_reorganize(dbm);
return obj;
}
@@ -853,7 +853,8 @@ fgdbm_sync(obj)
GDBM_FILE dbm;
rb_gdbm_modify(obj);
- GetDBM2(obj, dbmp, dbm);
+ GetDBM(obj, dbmp);
+ dbm = dbmp->di_dbm;
gdbm_sync(dbm);
return obj;
}
@@ -866,7 +867,9 @@ fgdbm_set_cachesize(obj, val)
GDBM_FILE dbm;
int optval;
- GetDBM2(obj, dbmp, dbm);
+ GetDBM(obj, dbmp);
+ dbm = dbmp->di_dbm;
+
optval = FIX2INT(val);
if (gdbm_setopt(dbm, GDBM_CACHESIZE, &optval, sizeof(optval)) == -1) {
rb_raise(rb_eGDBMError, "%s", gdbm_strerror(gdbm_errno));
@@ -882,7 +885,9 @@ fgdbm_set_fastmode(obj, val)
GDBM_FILE dbm;
int optval;
- GetDBM2(obj, dbmp, dbm);
+ GetDBM(obj, dbmp);
+ dbm = dbmp->di_dbm;
+
optval = 0;
if (RTEST(val))
optval = 1;
@@ -905,7 +910,9 @@ fgdbm_set_syncmode(obj, val)
GDBM_FILE dbm;
int optval;
- GetDBM2(obj, dbmp, dbm);
+ GetDBM(obj, dbmp);
+ dbm = dbmp->di_dbm;
+
optval = 0;
if (RTEST(val))
optval = 1;
@@ -925,7 +932,9 @@ fgdbm_to_hash(obj)
GDBM_FILE dbm;
VALUE keystr, hash;
- GetDBM2(obj, dbmp, dbm);
+ GetDBM(obj, dbmp);
+ dbm = dbmp->di_dbm;
+
hash = rb_hash_new();
for (keystr = rb_gdbm_firstkey(dbm); RTEST(keystr);
keystr = rb_gdbm_nextkey(dbm, keystr)) {
@@ -956,7 +965,6 @@ Init_gdbm()
rb_define_method(rb_cGDBM, "initialize", fgdbm_initialize, -1);
rb_define_method(rb_cGDBM, "close", fgdbm_close, 0);
- rb_define_method(rb_cGDBM, "closed?", fgdbm_closed, 0);
rb_define_method(rb_cGDBM, "[]", fgdbm_aref, 1);
rb_define_method(rb_cGDBM, "fetch", fgdbm_fetch_m, -1);
rb_define_method(rb_cGDBM, "[]=", fgdbm_store, 2);
diff --git a/ext/gdbm/testgdbm.rb b/ext/gdbm/testgdbm.rb
new file mode 100644
index 0000000000..a435498640
--- /dev/null
+++ b/ext/gdbm/testgdbm.rb
@@ -0,0 +1,663 @@
+require 'runit/testcase'
+require 'runit/cui/testrunner'
+
+if $".grep(/\bgdbm.so\b/).empty?
+ begin
+ require './gdbm'
+ rescue LoadError
+ require 'gdbm'
+ end
+end
+
+def uname_s
+ require 'rbconfig'
+ case Config::CONFIG['host_os']
+ when 'cygwin'
+ require 'Win32API'
+ uname = Win32API.new('cygwin1', 'uname', 'P', 'I')
+ utsname = ' ' * 100
+ raise 'cannot get system name' if uname.call(utsname) == -1
+
+ utsname.unpack('A20' * 5)[0]
+ else
+ Config::CONFIG['host_os']
+ end
+end
+
+SYSTEM = uname_s
+
+class TestGDBM < RUNIT::TestCase
+ def setup
+ @path = "tmptest_gdbm_"
+ assert_instance_of(GDBM, @gdbm = GDBM.new(@path))
+
+ # prepare to make readonly GDBM file
+ GDBM.open("tmptest_gdbm_rdonly", 0400) {|gdbm|
+ gdbm['foo'] = 'FOO'
+ }
+ assert_instance_of(GDBM, @gdbm_rdonly = GDBM.new("tmptest_gdbm_rdonly", nil))
+ end
+ def teardown
+ assert_nil(@gdbm.close)
+ assert_nil(@gdbm_rdonly.close)
+ GC.start
+ File.delete *Dir.glob("tmptest_gdbm*").to_a
+ p Dir.glob("tmptest_gdbm*") if $DEBUG
+ end
+
+ def check_size(expect, gdbm=@gdbm)
+ assert_equals(expect, gdbm.size)
+ n = 0
+ gdbm.each { n+=1 }
+ assert_equals(expect, n)
+ if expect == 0
+ assert_equals(true, gdbm.empty?)
+ else
+ assert_equals(false, gdbm.empty?)
+ end
+ end
+
+ def test_version
+ STDERR.print GDBM::VERSION
+ end
+
+ def test_s_new_has_no_block
+ # GDBM.new ignore the block
+ foo = true
+ assert_instance_of(GDBM, gdbm = GDBM.new("tmptest_gdbm") { foo = false })
+ assert_equals(foo, true)
+ assert_nil(gdbm.close)
+ end
+ def test_s_open_create_new
+ return if /^CYGWIN_9/ =~ SYSTEM
+
+ save_mask = File.umask(0)
+ begin
+ assert_instance_of(GDBM, gdbm = GDBM.open("tmptest_gdbm"))
+ gdbm.close
+ assert_equals(File.stat("tmptest_gdbm").mode & 0777, 0666)
+ assert_instance_of(GDBM, gdbm = GDBM.open("tmptest_gdbm2", 0644))
+ gdbm.close
+ assert_equals(File.stat("tmptest_gdbm2").mode & 0777, 0644)
+ ensure
+ File.umask save_mask
+ end
+ end
+ def test_s_open_no_create
+ # this test is failed on libgdbm 1.8.0
+ assert_nil(gdbm = GDBM.open("tmptest_gdbm", nil))
+ ensure
+ gdbm.close if gdbm
+ end
+ def test_s_open_3rd_arg
+ assert_instance_of(GDBM, gdbm = GDBM.open("tmptest_gdbm", 0644,
+ GDBM::FAST))
+ gdbm.close
+
+ # gdbm 1.8.0 specific
+ if defined? GDBM::SYNC
+ assert_instance_of(GDBM, gdbm = GDBM.open("tmptest_gdbm", 0644,
+ GDBM::SYNC))
+ gdbm.close
+ end
+ # gdbm 1.8.0 specific
+ if defined? GDBM::NOLOCK
+ assert_instance_of(GDBM, gdbm = GDBM.open("tmptest_gdbm", 0644,
+ GDBM::NOLOCK))
+ gdbm.close
+ end
+ end
+ def test_s_open_with_block
+ assert_equals(GDBM.open("tmptest_gdbm") { :foo }, :foo)
+ end
+ def test_s_open_lock
+ fork() {
+ assert_instance_of(GDBM, gdbm = GDBM.open("tmptest_gdbm", 0644))
+ sleep 2
+ }
+ begin
+ sleep 1
+ assert_exception(Errno::EWOULDBLOCK) {
+ begin
+ assert_instance_of(GDBM, gdbm2 = GDBM.open("tmptest_gdbm", 0644))
+ rescue Errno::EAGAIN, Errno::EACCES
+ raise Errno::EWOULDBLOCK
+ end
+ }
+ ensure
+ Process.wait
+ end
+ end
+
+=begin
+ # Is it guaranteed on many OS?
+ def test_s_open_lock_one_process
+ # locking on one process
+ assert_instance_of(GDBM, gdbm = GDBM.open("tmptest_gdbm", 0644))
+ assert_exception(Errno::EWOULDBLOCK) {
+ begin
+ GDBM.open("tmptest_gdbm", 0644)
+ rescue Errno::EAGAIN
+ raise Errno::EWOULDBLOCK
+ end
+ }
+ end
+=end
+
+ def test_s_open_nolock
+ # gdbm 1.8.0 specific
+ if not defined? GDBM::NOLOCK
+ return
+ end
+
+ fork() {
+ assert_instance_of(GDBM, gdbm = GDBM.open("tmptest_gdbm", 0644,
+ GDBM::NOLOCK))
+ sleep 2
+ }
+ sleep 1
+ begin
+ gdbm2 = nil
+ assert_no_exception(Errno::EWOULDBLOCK, Errno::EAGAIN, Errno::EACCES) {
+ assert_instance_of(GDBM, gdbm2 = GDBM.open("tmptest_gdbm", 0644))
+ }
+ ensure
+ Process.wait
+ gdbm2.close if gdbm2
+ end
+
+ p Dir.glob("tmptest_gdbm*") if $DEBUG
+
+ fork() {
+ assert_instance_of(GDBM, gdbm = GDBM.open("tmptest_gdbm", 0644))
+ sleep 2
+ }
+ begin
+ sleep 1
+ gdbm2 = nil
+ assert_no_exception(Errno::EWOULDBLOCK, Errno::EAGAIN, Errno::EACCES) {
+ # this test is failed on Cygwin98 (???)
+ assert_instance_of(GDBM, gdbm2 = GDBM.open("tmptest_gdbm", 0644,
+ GDBM::NOLOCK))
+ }
+ ensure
+ Process.wait
+ gdbm2.close if gdbm2
+ end
+ end
+
+ def test_s_open_error
+ assert_instance_of(GDBM, gdbm = GDBM.open("tmptest_gdbm", 0))
+ assert_exception(Errno::EACCES) {
+ GDBM.open("tmptest_gdbm", 0)
+ }
+ gdbm.close
+ end
+
+ def test_close
+ assert_instance_of(GDBM, gdbm = GDBM.open("tmptest_gdbm"))
+ assert_nil(gdbm.close)
+
+ # closed GDBM file
+ assert_exception(RuntimeError) { gdbm.close }
+ end
+
+ def test_aref
+ assert_equals('bar', @gdbm['foo'] = 'bar')
+ assert_equals('bar', @gdbm['foo'])
+
+ assert_nil(@gdbm['bar'])
+ end
+
+ def test_fetch
+ assert_equals('bar', @gdbm['foo']='bar')
+ assert_equals('bar', @gdbm.fetch('foo'))
+
+ # key not found
+ assert_exception(IndexError) {
+ @gdbm.fetch('bar')
+ }
+
+ # test for `ifnone' arg
+ assert_equals('baz', @gdbm.fetch('bar', 'baz'))
+
+ # test for `ifnone' block
+ assert_equals('foobar', @gdbm.fetch('bar') {|key| 'foo' + key })
+ end
+
+ def test_aset
+ num = 0
+ 2.times {|i|
+ assert_equals('foo', @gdbm['foo'] = 'foo')
+ assert_equals('foo', @gdbm['foo'])
+ assert_equals('bar', @gdbm['foo'] = 'bar')
+ assert_equals('bar', @gdbm['foo'])
+
+ num += 1 if i == 0
+ assert_equals(num, @gdbm.size)
+
+ # assign nil
+ assert_equals('', @gdbm['bar'] = '')
+ assert_equals('', @gdbm['bar'])
+
+ num += 1 if i == 0
+ assert_equals(num, @gdbm.size)
+
+ # empty string
+ assert_equals('', @gdbm[''] = '')
+ assert_equals('', @gdbm[''])
+
+ num += 1 if i == 0
+ assert_equals(num, @gdbm.size)
+
+ # Fixnum
+ assert_equals('200', @gdbm['100'] = '200')
+ assert_equals('200', @gdbm['100'])
+
+ num += 1 if i == 0
+ assert_equals(num, @gdbm.size)
+
+ # Big key and value
+ assert_equals('y' * 100, @gdbm['x' * 100] = 'y' * 100)
+ assert_equals('y' * 100, @gdbm['x' * 100])
+
+ num += 1 if i == 0
+ assert_equals(num, @gdbm.size)
+ }
+ end
+
+ def test_index
+ assert_equals('bar', @gdbm['foo'] = 'bar')
+ assert_equals('foo', @gdbm.index('bar'))
+ assert_nil(@gdbm['bar'])
+ end
+
+ def test_indexes
+ keys = %w(foo bar baz)
+ values = %w(FOO BAR BAZ)
+ @gdbm[keys[0]], @gdbm[keys[1]], @gdbm[keys[2]] = values
+ assert_equals(values.reverse, @gdbm.indexes(*keys.reverse))
+ end
+
+ def test_values_at
+ keys = %w(foo bar baz)
+ values = %w(FOO BAR BAZ)
+ @gdbm[keys[0]], @gdbm[keys[1]], @gdbm[keys[2]] = values
+ assert_equals(values.reverse, @gdbm.values_at(*keys.reverse))
+ end
+
+ def test_select_with_block
+ keys = %w(foo bar baz)
+ values = %w(FOO BAR BAZ)
+ @gdbm[keys[0]], @gdbm[keys[1]], @gdbm[keys[2]] = values
+ ret = @gdbm.select {|k,v|
+ assert_equals(k.upcase, v)
+ k != "bar"
+ }
+ assert_equals([['baz', 'BAZ'], ['foo', 'FOO']],
+ ret.sort)
+ end
+
+ def test_length
+ num = 10
+ assert_equals(0, @gdbm.size)
+ num.times {|i|
+ i = i.to_s
+ @gdbm[i] = i
+ }
+ assert_equals(num, @gdbm.size)
+
+ @gdbm.shift
+
+ assert_equals(num - 1, @gdbm.size)
+ end
+
+ def test_empty?
+ assert_equals(true, @gdbm.empty?)
+ @gdbm['foo'] = 'FOO'
+ assert_equals(false, @gdbm.empty?)
+ end
+
+ def test_each_pair
+ n = 0
+ @gdbm.each_pair { n += 1 }
+ assert_equals(0, n)
+
+ keys = %w(foo bar baz)
+ values = %w(FOO BAR BAZ)
+
+ @gdbm[keys[0]], @gdbm[keys[1]], @gdbm[keys[2]] = values
+
+ n = 0
+ ret = @gdbm.each_pair {|key, val|
+ assert_not_nil(i = keys.index(key))
+ assert_equals(val, values[i])
+
+ n += 1
+ }
+ assert_equals(keys.size, n)
+ assert_equals(@gdbm, ret)
+ end
+
+ def test_each_value
+ n = 0
+ @gdbm.each_value { n += 1 }
+ assert_equals(0, n)
+
+ keys = %w(foo bar baz)
+ values = %w(FOO BAR BAZ)
+
+ @gdbm[keys[0]], @gdbm[keys[1]], @gdbm[keys[2]] = values
+
+ n = 0
+ ret = @gdbm.each_value {|val|
+ assert_not_nil(key = @gdbm.index(val))
+ assert_not_nil(i = keys.index(key))
+ assert_equals(val, values[i])
+
+ n += 1
+ }
+ assert_equals(keys.size, n)
+ assert_equals(@gdbm, ret)
+ end
+
+ def test_each_key
+ n = 0
+ @gdbm.each_key { n += 1 }
+ assert_equals(0, n)
+
+ keys = %w(foo bar baz)
+ values = %w(FOO BAR BAZ)
+
+ @gdbm[keys[0]], @gdbm[keys[1]], @gdbm[keys[2]] = values
+
+ n = 0
+ ret = @gdbm.each_key {|key|
+ assert_not_nil(i = keys.index(key))
+ assert_equals(@gdbm[key], values[i])
+
+ n += 1
+ }
+ assert_equals(keys.size, n)
+ assert_equals(@gdbm, ret)
+ end
+
+ def test_keys
+ assert_equals([], @gdbm.keys)
+
+ keys = %w(foo bar baz)
+ values = %w(FOO BAR BAZ)
+
+ @gdbm[keys[0]], @gdbm[keys[1]], @gdbm[keys[2]] = values
+
+ assert_equals(keys.sort, @gdbm.keys.sort)
+ assert_equals(values.sort, @gdbm.values.sort)
+ end
+
+ def test_values
+ test_keys
+ end
+
+ def test_shift
+ assert_nil(@gdbm.shift)
+ assert_equals(0, @gdbm.size)
+
+ keys = %w(foo bar baz)
+ values = %w(FOO BAR BAZ)
+
+ @gdbm[keys[0]], @gdbm[keys[1]], @gdbm[keys[2]] = values
+
+ ret_keys = []
+ ret_values = []
+ while ret = @gdbm.shift
+ ret_keys.push ret[0]
+ ret_values.push ret[1]
+
+ assert_equals(keys.size - ret_keys.size, @gdbm.size)
+ end
+
+ assert_equals(keys.sort, ret_keys.sort)
+ assert_equals(values.sort, ret_values.sort)
+ end
+
+ def test_delete
+ keys = %w(foo bar baz)
+ values = %w(FOO BAR BAZ)
+ key = keys[1]
+
+ assert_nil(@gdbm.delete(key))
+ assert_equals(0, @gdbm.size)
+
+ @gdbm[keys[0]], @gdbm[keys[1]], @gdbm[keys[2]] = values
+
+ assert_equals('BAR', @gdbm.delete(key))
+ assert_nil(@gdbm[key])
+ assert_equals(2, @gdbm.size)
+
+ assert_nil(@gdbm.delete(key))
+
+ if /^CYGWIN_9/ !~ SYSTEM
+ assert_exception(GDBMError) {
+ @gdbm_rdonly.delete("foo")
+ }
+
+ assert_nil(@gdbm_rdonly.delete("bar"))
+ end
+ end
+ def test_delete_with_block
+ key = 'no called block'
+ @gdbm[key] = 'foo'
+ assert_equals('foo', @gdbm.delete(key) {|k| k.replace 'called block'})
+ assert_equals('no called block', key)
+ assert_equals(0, @gdbm.size)
+
+ key = 'no called block'
+ assert_equals(:blockval,
+ @gdbm.delete(key) {|k| k.replace 'called block'; :blockval})
+ assert_equals('called block', key)
+ assert_equals(0, @gdbm.size)
+ end
+
+ def test_delete_if
+ v = "0"
+ 100.times {@gdbm[v] = v; v = v.next}
+
+ ret = @gdbm.delete_if {|key, val| key.to_i < 50}
+ assert_equals(@gdbm, ret)
+ check_size(50, @gdbm)
+
+ ret = @gdbm.delete_if {|key, val| key.to_i >= 50}
+ assert_equals(@gdbm, ret)
+ check_size(0, @gdbm)
+
+ # break
+ v = "0"
+ 100.times {@gdbm[v] = v; v = v.next}
+ check_size(100, @gdbm)
+ n = 0;
+ @gdbm.delete_if {|key, val|
+ break if n > 50
+ n+=1
+ true
+ }
+ assert_equals(51, n)
+ check_size(49, @gdbm)
+
+ @gdbm.clear
+
+ # raise
+ v = "0"
+ 100.times {@gdbm[v] = v; v = v.next}
+ check_size(100, @gdbm)
+ n = 0;
+ begin
+ @gdbm.delete_if {|key, val|
+ raise "runtime error" if n > 50
+ n+=1
+ true
+ }
+ rescue
+ end
+ assert_equals(51, n)
+ check_size(49, @gdbm)
+ end
+
+ def test_reject
+ v = "0"
+ 100.times {@gdbm[v] = v; v = v.next}
+
+ hash = @gdbm.reject {|key, val| key.to_i < 50}
+ assert_instance_of(Hash, hash)
+ assert_equals(100, @gdbm.size)
+
+ assert_equals(50, hash.size)
+ hash.each_pair {|key,val|
+ assert_equals(false, key.to_i < 50)
+ assert_equals(key, val)
+ }
+
+ hash = @gdbm.reject {|key, val| key.to_i < 100}
+ assert_instance_of(Hash, hash)
+ assert_equals(true, hash.empty?)
+ end
+
+ def test_clear
+ v = "1"
+ 100.times {v = v.next; @gdbm[v] = v}
+
+ assert_equals(@gdbm, @gdbm.clear)
+
+ # validate GDBM#size
+ i = 0
+ @gdbm.each { i += 1 }
+ assert_equals(@gdbm.size, i)
+ assert_equals(0, i)
+ end
+
+ def test_invert
+ v = "0"
+ 100.times {@gdbm[v] = v; v = v.next}
+
+ hash = @gdbm.invert
+ assert_instance_of(Hash, hash)
+ assert_equals(100, hash.size)
+ hash.each_pair {|key, val|
+ assert_equals(key.to_i, val.to_i)
+ }
+ end
+
+ def test_update
+ hash = {}
+ v = "0"
+ 100.times {v = v.next; hash[v] = v}
+
+ @gdbm["101"] = "101"
+ @gdbm.update hash
+ assert_equals(101, @gdbm.size)
+ @gdbm.each_pair {|key, val|
+ assert_equals(key.to_i, val.to_i)
+ }
+ end
+
+ def test_replace
+ hash = {}
+ v = "0"
+ 100.times {v = v.next; hash[v] = v}
+
+ @gdbm["101"] = "101"
+ @gdbm.replace hash
+ assert_equals(100, @gdbm.size)
+ @gdbm.each_pair {|key, val|
+ assert_equals(key.to_i, val.to_i)
+ }
+ end
+
+ def test_reorganize
+ size1 = File.size(@path)
+ i = "1"
+ 1000.times {i = i.next; @gdbm[i] = i}
+ @gdbm.clear
+ @gdbm.sync
+
+ size2 = File.size(@path)
+ @gdbm.reorganize
+ size3 = File.size(@path)
+
+ # p [size1, size2, size3]
+ assert_equals(true, size1 < size2)
+ # this test is failed on Cygwin98. `GDBM version 1.8.0, as of May 19, 1999'
+ assert_equals(true, size3 < size2)
+ assert_equals(size1, size3)
+ end
+
+ def test_sync
+ assert_instance_of(GDBM, gdbm = GDBM.open('tmptest_gdbm', 0666, GDBM::FAST))
+ assert_equals(gdbm.sync, gdbm)
+ gdbm.close
+ assert_instance_of(GDBM, gdbm = GDBM.open('tmptest_gdbm', 0666))
+ assert_equals(gdbm.sync, gdbm)
+ gdbm.close
+ end
+
+ def test_cachesize=
+ assert_equals(@gdbm.cachesize = 1024, 1024)
+ end
+
+ def test_fastmode=
+ assert_equals(@gdbm.fastmode = true, true)
+ end
+
+ def test_syncmode=
+ assert_equals(@gdbm.syncmode = true, true)
+ end
+
+ def test_haskey?
+ assert_equals('bar', @gdbm['foo']='bar')
+ assert_equals(true, @gdbm.has_key?('foo'))
+ assert_equals(false, @gdbm.has_key?('bar'))
+ end
+
+ def test_has_value?
+ assert_equals('bar', @gdbm['foo']='bar')
+ assert_equals(true, @gdbm.has_value?('bar'))
+ assert_equals(false, @gdbm.has_value?('foo'))
+ end
+
+ def test_to_a
+ v = "0"
+ 100.times {v = v.next; @gdbm[v] = v}
+
+ ary = @gdbm.to_a
+ assert_instance_of(Array, ary)
+ assert_equals(100, ary.size)
+ ary.each {|key,val|
+ assert_equals(key.to_i, val.to_i)
+ }
+ end
+
+ def test_to_hash
+ v = "0"
+ 100.times {v = v.next; @gdbm[v] = v}
+
+ hash = @gdbm.to_hash
+ assert_instance_of(Hash, hash)
+ assert_equals(100, hash.size)
+ hash.each {|key,val|
+ assert_equals(key.to_i, val.to_i)
+ }
+ end
+end
+
+if $0 == __FILE__
+ if ARGV.size == 0
+ suite = RUNIT::TestSuite.new
+ suite.add_test(TestGDBM.suite)
+ else
+ suite = RUNIT::TestSuite.new
+ ARGV.each do |testmethod|
+ suite.add_test(TestGDBM.new(testmethod))
+ end
+ end
+
+ RUNIT::CUI::TestRunner.run(suite)
+end
diff --git a/ext/iconv/charset_alias.rb b/ext/iconv/charset_alias.rb
index aed4644290..65fd41759b 100644
--- a/ext/iconv/charset_alias.rb
+++ b/ext/iconv/charset_alias.rb
@@ -1,12 +1,11 @@
#! /usr/bin/ruby
# :stopdoc:
require 'rbconfig'
-require 'optparse'
# http://www.ctan.org/tex-archive/macros/texinfo/texinfo/intl/config.charset
# Fri, 30 May 2003 00:09:00 GMT'
-OS = Config::CONFIG["target_os"]
+OS = Config::CONFIG["target"]
SHELL = Config::CONFIG['SHELL']
class Hash::Ordered < Hash
@@ -15,89 +14,39 @@ class Hash::Ordered < Hash
end
def []=(key, val)
ary = fetch(key) {return super(key, [self.size, key, val])} and
- ary << val
+ ary.last = val
end
- def sort
- values.sort.collect {|i, *rest| rest}
- end
- def each(&block)
- sort.each(&block)
+ def each
+ values.sort.each {|i, key, val| yield key, val}
end
end
def charset_alias(config_charset, mapfile, target = OS)
map = Hash::Ordered.new
comments = []
- open(config_charset) do |input|
- input.find {|line| /^case "\$os" in/ =~ line} or break
- input.find {|line|
- /^\s*([-\w\*]+(?:\s*\|\s*[-\w\*]+)*)(?=\))/ =~ line and
- $&.split('|').any? {|pattern| File.fnmatch?(pattern.strip, target)}
- } or break
- input.find do |line|
- case line
- when /^\s*echo "(?:\$\w+\.)?([-\w*]+)\s+([-\w]+)"/
- sys, can = $1, $2
- can.downcase!
- map[can] = sys
- false
- when /^\s*;;/
- true
- else
- false
- end
- end
+ IO.foreach("|#{SHELL} #{config_charset} #{target}") do |list|
+ next comments << list if /^\#/ =~ list
+ next unless /^(\S+)\s+(\S+)$/ =~ list
+ sys, can = $1, $2
+ can.downcase!
+ map[can] = sys
end
case target
when /linux|-gnu/
- # map.delete('ascii')
- when /cygwin|os2-emx/
+ map.delete('ascii')
+ when /cygwin/
# get rid of tilde/yen problem.
map['shift_jis'] = 'cp932'
end
- st = Hash.new(0)
- map = map.sort.collect do |can, *sys|
- if sys.grep(/^en_us(?=.|$)/i) {break true} == true
- noen = %r"^(?!en_us)\w+_\w+#{Regexp.new($')}$"i #"
- sys.reject! {|s| noen =~ s}
- end
- sys = sys.first
- st[sys] += 1
- [can, sys]
- end
- st.delete_if {|sys, i| i == 1}.empty?
- st.keys.each {|sys| st[sys] = nil}
- st.default = nil
- writer = proc do |f|
+ open(mapfile, "w") do |f|
f.puts("require 'iconv.so'")
f.puts
f.puts(comments)
f.puts("class Iconv")
- i = 0
- map.each do |can, sys|
- if s = st[sys]
- sys = s
- elsif st.key?(sys)
- sys = (st[sys] = "sys#{i+=1}") + " = '#{sys}'.freeze"
- else
- sys = "'#{sys}'.freeze"
- end
- f.puts(" charset_map['#{can}'] = #{sys}")
- end
+ map.each {|can, sys| f.puts(" charset_map['#{can}'.freeze] = '#{sys}'.freeze")}
f.puts("end")
end
- if mapfile
- open(mapfile, "w", &writer)
- else
- writer[STDOUT]
- end
end
-target = OS
-opt = nil
-ARGV.options do |opt|
- opt.banner << " config.status map.rb"
- opt.on("--target OS") {|t| target = t}
- opt.parse! and (1..2) === ARGV.size
-end or abort opt.to_s
-charset_alias(ARGV[0], ARGV[1], target)
+(2..3) === ARGV.size or abort "usage: #$0 config.status map.rb [target]"
+charset_alias(*ARGV)
diff --git a/ext/iconv/extconf.rb b/ext/iconv/extconf.rb
index 359771e8a9..65ea327950 100644
--- a/ext/iconv/extconf.rb
+++ b/ext/iconv/extconf.rb
@@ -21,22 +21,20 @@ if have_func("iconv", "iconv.h") or
/\bconst\b/ =~ second
end
end
- $defs.push('-DICONV_INPTR_CONST')
+ $defs.push('-DICONV_INPTR_CAST=""')
+ else
+ $defs.push('-DICONV_INPTR_CAST="(char **)"')
end
if conf
prefix = '$(srcdir)'
prefix = $nmake ? "{#{prefix}}" : "#{prefix}/"
- if $extout
- wrapper = "$(RUBYARCHDIR)/iconv.rb"
- else
- wrapper = "./iconv.rb"
- $INSTALLFILES = [[wrapper, "$(RUBYARCHDIR)"]]
- end
+ wrapper = "./iconv.rb"
+ $INSTALLFILES = [[wrapper, "$(RUBYARCHDIR)"]]
if String === conf
require 'uri'
scheme = URI.parse(conf).scheme
else
- conf = "$(srcdir)/config.charset"
+ conf = prefix + "config.charset"
end
$cleanfiles << wrapper
end
@@ -45,7 +43,7 @@ if have_func("iconv", "iconv.h") or
open("Makefile", "a") do |mf|
mf.print("\nall: #{wrapper}\n\n#{wrapper}: #{prefix}charset_alias.rb")
mf.print(" ", conf) unless scheme
- mf.print("\n\t$(RUBY) $(srcdir)/charset_alias.rb #{conf} $@\n")
+ mf.print("\n\t$(RUBY) ", prefix, "charset_alias.rb ", conf, " $@\n")
end
end
end
diff --git a/ext/iconv/iconv.c b/ext/iconv/iconv.c
index 5715b8fbde..29ab2c7d7b 100644
--- a/ext/iconv/iconv.c
+++ b/ext/iconv/iconv.c
@@ -83,7 +83,6 @@ struct iconv_env_t
VALUE (*append)_((VALUE, VALUE));
};
-static VALUE rb_eIconvInvalidEncoding;
static VALUE rb_eIconvFailure;
static VALUE rb_eIconvIllegalSeq;
static VALUE rb_eIconvInvalidChar;
@@ -112,12 +111,6 @@ static VALUE iconv_iconv _((int argc, VALUE *argv, VALUE self));
static VALUE charset_map;
-/*
- * Document-method: charset_map
- * call-seq: Iconv.charset_map
- *
- * Returns the map from canonical name to system dependent name.
- */
static VALUE charset_map_get _((void))
{
return charset_map;
@@ -168,18 +161,10 @@ iconv_create
cd = iconv_open(tocode, fromcode);
}
if (cd == (iconv_t)-1) {
- int inval = errno == EINVAL;
- char *s = inval ? "invalid encoding " : "iconv";
- volatile VALUE msg = rb_str_new(0, strlen(s) + RSTRING(to)->len +
- RSTRING(from)->len + 8);
-
- sprintf(RSTRING(msg)->ptr, "%s(\"%s\", \"%s\")",
- s, RSTRING(to)->ptr, RSTRING(from)->ptr);
- s = RSTRING(msg)->ptr;
- RSTRING(msg)->len = strlen(s);
- if (!inval) rb_sys_fail(s);
- iconv_fail(rb_eIconvInvalidEncoding,
- Qnil, rb_ary_new3(2, to, from), NULL, s);
+ volatile VALUE msg = rb_str_new2("iconv(\"");
+ rb_str_buf_cat2(rb_str_buf_append(msg, to), "\", \"");
+ rb_str_buf_cat2(rb_str_buf_append(msg, from), "\")");
+ rb_sys_fail(StringValuePtr(msg));
}
}
@@ -243,11 +228,6 @@ iconv_try
size_t *outlen;
#endif /* HAVE_PROTOTYPES */
{
-#ifdef ICONV_INPTR_CONST
-#define ICONV_INPTR_CAST
-#else
-#define ICONV_INPTR_CAST (char **)
-#endif
size_t ret = iconv(cd, ICONV_INPTR_CAST inptr, inlen, outptr, outlen);
if (ret == (size_t)-1) {
if (!*inlen)
@@ -524,8 +504,8 @@ iconv_s_allocate
* === Exceptions
*
* TypeError:: if +to+ or +from+ aren't String
- * InvalidEncoding:: if designated converter couldn't find out
- * SystemCallError:: if <tt>iconv_open(3)</tt> fails
+ * ArgumentError:: if designated converter couldn't find out
+ * SystemCallError:: if <tt>iconv_open3</tt> fails
*/
static VALUE
iconv_initialize
@@ -616,7 +596,7 @@ iconv_s_convert
* === Exceptions
*
* Exceptions thrown by Iconv.new, Iconv.open and Iconv#iconv.
- */
+*/
static VALUE
iconv_s_iconv
#ifdef HAVE_PROTOTYPES
@@ -645,9 +625,7 @@ iconv_s_iconv
* Document-method: Iconv::conv
* call-seq: Iconv.iconv(to, from, *strs)
*
- * Shorthand for
- * Iconv.iconv(to, from, str).join
- * See Iconv.iconv.
+ * See Iconv.iconv ???
*/
static VALUE
iconv_s_conv
@@ -677,8 +655,8 @@ iconv_s_conv
* multiple calls of #close are guaranteed to end successfully.
*
* Returns a string containing the byte sequence to change the output buffer to
- * its initial shift state.
- */
+ * its initial shift state. <i>???</i>
+*/
static VALUE
iconv_init_state
#ifdef HAVE_PROTOTYPES
@@ -734,7 +712,7 @@ iconv_finish
* === Examples
*
* See the Iconv documentation.
- */
+*/
static VALUE
iconv_iconv
#ifdef HAVE_PROTOTYPES
@@ -754,7 +732,7 @@ iconv_iconv
return iconv_convert(VALUE2ICONV(cd), str,
NIL_P(n1) ? 0 : NUM2INT(n1),
- NIL_P(n2) ? -1 : NUM2INT(n2),
+ NIL_P(n2) ? -1 : NUM2INT(n1),
NULL);
}
@@ -762,16 +740,22 @@ iconv_iconv
* Document-class: Iconv::Failure
*
* Base attributes for Iconv exceptions.
- */
-
-/*
- * Document-method: success
- * call-seq: success
+ *
+ * === Iconv::Failure#success
*
* Returns string(s) translated successfully until the exception occurred.
* * In the case of failure occurred within Iconv.iconv, returned
* value is an array of strings translated successfully preceding
* failure and the last element is string on the way.
+ *
+ * === Iconv::Failure#failed
+ *
+ * Returns substring of the original string passed to Iconv that starts at the
+ * character caused the exception.
+ *
+ * === Iconv::Failure#inspect
+ *
+ * Returns inspected string like as: #<_class_: _success_, _failed_>
*/
static VALUE
iconv_failure_success
@@ -786,11 +770,7 @@ iconv_failure_success
}
/*
- * Document-method: failed
- * call-seq: failed
- *
- * Returns substring of the original string passed to Iconv that starts at the
- * character caused the exception.
+ * Comment!
*/
static VALUE
iconv_failure_failed
@@ -804,12 +784,6 @@ iconv_failure_failed
return rb_attr_get(self, rb_failed);
}
-/*
- * Document-method: inspect
- * call-seq: inspect
- *
- * Returns inspected string like as: #<_class_: _success_, _failed_>
- */
static VALUE
iconv_failure_inspect
#ifdef HAVE_PROTOTYPES
@@ -831,17 +805,19 @@ iconv_failure_inspect
}
/*
- * Document-class: Iconv::InvalidEncoding
- *
- * Requested coding-system is not available on this system.
- */
-
-/*
* Document-class: Iconv::IllegalSequence
*
* Input conversion stopped due to an input byte that does not belong to
* the input codeset, or the output codeset does not contain the
* character.
+ *
+ * === Superclass
+ *
+ * ArgumentError
+ *
+ * === Included Modules
+ *
+ * Iconv::Failure
*/
/*
@@ -849,12 +825,28 @@ iconv_failure_inspect
*
* Input conversion stopped due to an incomplete character or shift
* sequence at the end of the input buffer.
+ *
+ * === Superclass
+ *
+ * ArgumentError
+ *
+ * === Included Modules
+ *
+ * Iconv::Failure
*/
/*
* Document-class: Iconv::OutOfRange
*
* Iconv library internal error. Must not occur.
+ *
+ * === Superclass
+ *
+ * RuntimeError
+ *
+ * === Included Modules
+ *
+ * Iconv::Failure
*/
void
@@ -876,11 +868,9 @@ Init_iconv _((void))
rb_define_method(rb_eIconvFailure, "failed", iconv_failure_failed, 0);
rb_define_method(rb_eIconvFailure, "inspect", iconv_failure_inspect, 0);
- rb_eIconvInvalidEncoding = rb_define_class_under(rb_cIconv, "InvalidEncoding", rb_eArgError);
rb_eIconvIllegalSeq = rb_define_class_under(rb_cIconv, "IllegalSequence", rb_eArgError);
rb_eIconvInvalidChar = rb_define_class_under(rb_cIconv, "InvalidCharacter", rb_eArgError);
rb_eIconvOutOfRange = rb_define_class_under(rb_cIconv, "OutOfRange", rb_eRuntimeError);
- rb_include_module(rb_eIconvInvalidEncoding, rb_eIconvFailure);
rb_include_module(rb_eIconvIllegalSeq, rb_eIconvFailure);
rb_include_module(rb_eIconvInvalidChar, rb_eIconvFailure);
rb_include_module(rb_eIconvOutOfRange, rb_eIconvFailure);
diff --git a/ext/io/wait/extconf.rb b/ext/io/wait/extconf.rb
index 1352ef202e..ea7dc9f6cf 100644
--- a/ext/io/wait/extconf.rb
+++ b/ext/io/wait/extconf.rb
@@ -3,15 +3,10 @@ target = "io/wait"
unless macro_defined?("DOSISH", "#include <ruby.h>")
fionread = %w[sys/ioctl.h sys/filio.h].find do |h|
- checking_for("FIONREAD") {have_macro("FIONREAD", h)}
+ checking_for("FIONREAD") {macro_defined?("FIONREAD", "#include <#{h}>\n")}
end
if fionread
$defs << "-DFIONREAD_HEADER=\"<#{fionread}>\""
create_makefile(target)
end
-else
- if have_func("rb_w32_ioctlsocket", "ruby.h")
- have_func("rb_w32_is_socket", "ruby.h")
- create_makefile(target)
- end
end
diff --git a/ext/io/wait/lib/nonblock.rb b/ext/io/wait/lib/nonblock.rb
index 2103fdf25b..46511fb40c 100644
--- a/ext/io/wait/lib/nonblock.rb
+++ b/ext/io/wait/lib/nonblock.rb
@@ -20,4 +20,4 @@ class IO
ensure
self.nonblock = nb
end
-end if defined?(Fcntl::F_GETFL)
+end
diff --git a/ext/io/wait/wait.c b/ext/io/wait/wait.c
index 61d6527b36..53d5bd7d18 100644
--- a/ext/io/wait/wait.c
+++ b/ext/io/wait/wait.c
@@ -15,24 +15,7 @@
#include "rubyio.h"
#include <sys/types.h>
-#if defined(FIONREAD_HEADER)
#include FIONREAD_HEADER
-#endif
-
-#ifdef HAVE_RB_W32_IOCTLSOCKET
-#define ioctl ioctlsocket
-#define ioctl_arg u_long
-#define ioctl_arg2num(i) ULONG2NUM(i)
-#else
-#define ioctl_arg int
-#define ioctl_arg2num(i) INT2NUM(i)
-#endif
-
-#ifdef HAVE_RB_W32_IS_SOCKET
-#define FIONREAD_POSSIBLE_P(fd) rb_w32_is_socket(fd)
-#else
-#define FIONREAD_POSSIBLE_P(fd) ((fd),Qtrue)
-#endif
static VALUE io_ready_p _((VALUE io));
static VALUE io_wait _((int argc, VALUE *argv, VALUE io));
@@ -58,16 +41,15 @@ io_ready_p(io)
{
OpenFile *fptr;
FILE *fp;
- ioctl_arg n;
+ int n;
GetOpenFile(io, fptr);
rb_io_check_readable(fptr);
- if (!FIONREAD_POSSIBLE_P(fileno(fptr->f))) return Qfalse;
fp = fptr->f;
if (feof(fp)) return Qfalse;
if (rb_read_pending(fp)) return Qtrue;
if (ioctl(fileno(fp), FIONREAD, &n)) rb_sys_fail(0);
- if (n > 0) return ioctl_arg2num(n);
+ if (n > 0) return INT2NUM(n);
return Qnil;
}
@@ -87,8 +69,7 @@ io_wait(argc, argv, io)
OpenFile *fptr;
fd_set rd;
FILE *fp;
- int fd;
- ioctl_arg n;
+ int fd, n;
VALUE timeout;
struct timeval *tp, timerec;
@@ -112,7 +93,6 @@ io_wait(argc, argv, io)
if (rb_thread_select(fd + 1, &rd, NULL, NULL, tp) < 0)
rb_sys_fail(0);
rb_io_check_closed(fptr);
- if (!FIONREAD_POSSIBLE_P(fileno(fptr->f))) return Qfalse;
if (ioctl(fileno(fp), FIONREAD, &n)) rb_sys_fail(0);
if (n > 0) return io;
return Qnil;
diff --git a/ext/nkf/lib/kconv.rb b/ext/nkf/lib/kconv.rb
index 3512135ecc..1fd28a5a59 100644
--- a/ext/nkf/lib/kconv.rb
+++ b/ext/nkf/lib/kconv.rb
@@ -74,8 +74,8 @@ module Kconv
RegexpEucjp = /\A(?:
[\x00-\x7f] |
\x8e [\xa1-\xdf] |
- \x8f [\xa1-\xdf] [\xa1-\xfe] |
- [\xa1-\xdf] [\xa1-\xfe]
+ \x8f [\xa1-\xdf] [\xa1-\xdf] |
+ [\xa1-\xdf] [\xa1-\xdf]
)*\z/nx
RegexpUtf8 = /\A(?:
[\x00-\x7f] |
@@ -101,9 +101,8 @@ module Kconv
when ::NKF::SJIS
opt << 'S'
when ::NKF::UTF8
- opt << 'W'
when ::NKF::UTF16
- opt << 'W16'
+ opt << 'W'
end
case out_code
@@ -114,9 +113,8 @@ module Kconv
when ::NKF::SJIS
opt << 's'
when ::NKF::UTF8
- opt << 'w'
when ::NKF::UTF16
- opt << 'w16'
+ opt << 'w'
when ::NKF::NOCONV
return str
end
@@ -166,7 +164,7 @@ module Kconv
module_function :guess
def guess_old(str)
- ::NKF::guess1(str)
+ ::NKF::guess_old(str)
end
module_function :guess_old
diff --git a/ext/nkf/nkf-utf8/nkf.c b/ext/nkf/nkf-utf8/nkf.c
index 2973799fb2..aa7c459b83 100644
--- a/ext/nkf/nkf-utf8/nkf.c
+++ b/ext/nkf/nkf-utf8/nkf.c
@@ -39,14 +39,14 @@
** E-Mail: furukawa@tcp-ip.or.jp
** $B$^$G8fO"Mm$r$*4j$$$7$^$9!#(B
***********************************************************************/
-/* $Id$ */
-#define NKF_VERSION "2.0.5"
-#define NKF_RELEASE_DATE "2005-04-10"
#include "config.h"
static char *CopyRight =
- "Copyright (C) 1987, FUJITSU LTD. (I.Ichikawa),2000 S. Kono, COW, 2002-2005 Kono, Furukawa, Naruse";
-
+ "Copyright (C) 1987, FUJITSU LTD. (I.Ichikawa),2000 S. Kono, COW, 2002-2004 Kono, Furukawa";
+static char *Version =
+ "2.0";
+static char *Patchlevel =
+ "4/0401/Shinji Kono";
/*
**
@@ -110,8 +110,6 @@ static char *CopyRight =
#include <stdio.h>
#endif
-#include <stdlib.h>
-
#if defined(MSDOS) || defined(__OS2__)
#include <fcntl.h>
#include <io.h>
@@ -144,25 +142,18 @@ static char *CopyRight =
#ifdef OVERWRITE
/* added by satoru@isoternet.org */
+#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#ifndef MSDOS /* UNIX, OS/2 */
#include <unistd.h>
#include <utime.h>
-#else /* defined(MSDOS) */
-#ifdef __WIN32__
-#ifdef __BORLANDC__ /* BCC32 */
-#include <utime.h>
-#else /* !defined(__BORLANDC__) */
-#include <sys/utime.h>
-#endif /* (__BORLANDC__) */
-#else /* !defined(__WIN32__) */
+#else
#if defined(_MSC_VER) || defined(__MINGW32__) /* VC++, MinGW */
#include <sys/utime.h>
#elif defined(__TURBOC__) /* BCC */
#include <utime.h>
#elif defined(LSI_C) /* LSI C */
-#endif /* (__WIN32__) */
#endif
#endif
#endif
@@ -190,7 +181,6 @@ static char *CopyRight =
#define X0201 2
#define ISO8859_1 8
#define NO_X0201 3
-#define X0212 16
/* Input Assumption */
@@ -208,15 +198,14 @@ static char *CopyRight =
#define UTF8 12
#define UTF8_INPUT 13
-#define UTF16BE_INPUT 14
-#define UTF16LE_INPUT 15
+#define UTF16_INPUT 14
+#define UTF16BE_INPUT 15
#define WISH_TRUE 15
/* ASCII CODE */
#define BS 0x08
-#define TAB 0x09
#define NL 0x0a
#define CR 0x0d
#define ESC 0x1b
@@ -227,7 +216,6 @@ static char *CopyRight =
#define SI 0x0f
#define SO 0x0e
#define SSO 0x8e
-#define SS3 0x8f
#define is_alnum(c) \
(('a'<=c && c<='z')||('A'<= c && c<='Z')||('0'<=c && c<='9'))
@@ -290,7 +278,7 @@ STATIC int noconvert PROTO((FILE *f));
STATIC int kanji_convert PROTO((FILE *f));
STATIC int h_conv PROTO((FILE *f,int c2,int c1));
STATIC int push_hold_buf PROTO((int c2));
-STATIC void set_iconv PROTO((int f, int (*iconv_func)(int c2,int c1,int c0)));
+STATIC void set_iconv PROTO((int f, int (*iconv_func)()));
STATIC int s_iconv PROTO((int c2,int c1,int c0));
STATIC int s2e_conv PROTO((int c2, int c1, int *p2, int *p1));
STATIC int e_iconv PROTO((int c2,int c1,int c0));
@@ -307,7 +295,7 @@ STATIC void w_oconv PROTO((int c2,int c1));
STATIC void w_oconv16 PROTO((int c2,int c1));
#endif
STATIC void e_oconv PROTO((int c2,int c1));
-STATIC int e2s_conv PROTO((int c2, int c1, int *p2, int *p1));
+STATIC void e2s_conv PROTO((int c2, int c1, int *p2, int *p1));
STATIC void s_oconv PROTO((int c2,int c1));
STATIC void j_oconv PROTO((int c2,int c1));
STATIC void fold_conv PROTO((int c2,int c1));
@@ -340,14 +328,13 @@ STATIC int mime_ungetc_buf PROTO((int c,FILE *f));
STATIC int mime_integrity PROTO((FILE *f,unsigned char *p));
STATIC int base64decode PROTO((int c));
-STATIC void mime_prechar PROTO((int c2, int c1));
STATIC void mime_putc PROTO((int c));
STATIC void open_mime PROTO((int c));
STATIC void close_mime PROTO(());
STATIC void usage PROTO(());
STATIC void version PROTO(());
STATIC void options PROTO((unsigned char *c));
-#if defined(PERL_XS) || defined(WIN32DLL)
+#ifdef PERL_XS
STATIC void reinit PROTO(());
#endif
@@ -378,7 +365,6 @@ static int hira_f = FALSE; /* hira/kata henkan */
static int input_f = FALSE; /* non fixed input code */
static int alpha_f = FALSE; /* convert JIx0208 alphbet to ASCII */
static int mime_f = STRICT_MIME; /* convert MIME B base64 or Q */
-static int mime_decode_f = FALSE; /* mime decode is explicitly on */
static int mimebuf_f = FALSE; /* MIME buffered input */
static int broken_f = FALSE; /* convert ESC-less broken JIS */
static int iso8859_f = FALSE; /* ISO8859 through */
@@ -390,9 +376,8 @@ static int x0201_f = NO_X0201; /* Assume NO JISX0201 */
#endif
static int iso2022jp_f = FALSE; /* convert ISO-2022-JP */
#ifdef UTF8_OUTPUT_ENABLE
-static int unicode_bom_f= 0; /* Output Unicode BOM */
+static int w_oconv16_begin_f= 0; /* utf-16 header */
static int w_oconv16_LE = 0; /* utf-16 little endian */
-static int ms_ucs_map_f = FALSE; /* Microsoft UCS Mapping Compatible */
#endif
@@ -444,19 +429,12 @@ STATIC int cp932_f = TRUE;
#define CP932_TABLE_BEGIN (0xfa)
#define CP932_TABLE_END (0xfc)
-STATIC int cp932inv_f = TRUE;
+STATIC int cp932inv_f = FALSE;
#define CP932INV_TABLE_BEGIN (0xed)
#define CP932INV_TABLE_END (0xee)
-/* STATIC int cp932_conv PROTO((int c2, int c1)); */
#endif /* SHIFTJIS_CP932 */
-#ifdef X0212_ENABLE
-STATIC int x0212_f = FALSE;
-static int x0212_shift PROTO((int c));
-static int x0212_unshift PROTO((int c));
-#endif
-
STATIC unsigned char prefix_table[256];
STATIC void e_status PROTO((struct input_code *, int));
@@ -465,7 +443,7 @@ STATIC void s_status PROTO((struct input_code *, int));
#ifdef UTF8_INPUT_ENABLE
STATIC void w_status PROTO((struct input_code *, int));
STATIC void w16_status PROTO((struct input_code *, int));
-static int utf16_mode = UTF16BE_INPUT;
+static int utf16_mode = UTF16_INPUT;
#endif
struct input_code input_code_list[] = {
@@ -489,8 +467,8 @@ static int fold_f = FALSE;
static int fold_len = 0;
/* options */
-static unsigned char kanji_intro = DEFAULT_J;
-static unsigned char ascii_intro = DEFAULT_R;
+static unsigned char kanji_intro = DEFAULT_J,
+ ascii_intro = DEFAULT_R;
/* Folding */
@@ -656,14 +634,7 @@ static int crmode_f = 0; /* CR, NL, CRLF */
static int end_check;
#endif /*Easy Win */
-#define STD_GC_BUFSIZE (256)
-int std_gc_buf[STD_GC_BUFSIZE];
-int std_gc_ndx;
-
-#ifdef WIN32DLL
-#include "nkf32dll.c"
-#elif defined(PERL_XS)
-#else /* WIN32DLL */
+#ifndef PERL_XS
int
main(argc, argv)
int argc;
@@ -672,7 +643,7 @@ main(argc, argv)
FILE *fin;
unsigned char *cp;
- char *outfname = NULL;
+ char *outfname;
char *origfname;
#ifdef EASYWIN /*Easy Win */
@@ -743,16 +714,13 @@ main(argc, argv)
} else {
int nfiles = argc;
while (argc--) {
- is_inputcode_mixed = FALSE;
- is_inputcode_set = FALSE;
- input_codename = "";
if ((fin = fopen((origfname = *argv++), "r")) == NULL) {
perror(*--argv);
return(-1);
} else {
#ifdef OVERWRITE
- int fd = 0;
- int fd_backup = 0;
+ int fd;
+ int fd_backup;
#endif
/* reopen file for stdout */
@@ -835,7 +803,7 @@ main(argc, argv)
#ifdef OVERWRITE
if (overwrite) {
struct stat sb;
-#if defined(MSDOS) && !defined(__MINGW32__) && !defined(__WIN32__)
+#if defined(MSDOS) && !defined(__MINGW32__)
time_t tb[2];
#else
struct utimbuf tb;
@@ -855,7 +823,7 @@ main(argc, argv)
}
/* $B%?%$%`%9%?%s%W$rI|85(B */
-#if defined(MSDOS) && !defined(__MINGW32__) && !defined(__WIN32__)
+#if defined(MSDOS) && !defined(__MINGW32__)
tb[0] = tb[1] = sb.st_mtime;
if (utime(outfname, tb)) {
fprintf(stderr, "Can't set timestamp %s\n", outfname);
@@ -891,10 +859,10 @@ main(argc, argv)
#else /* for Other OS */
if (file_out == TRUE)
fclose(stdout);
-#endif /*Easy Win */
+#endif
return (0);
}
-#endif /* WIN32DLL */
+#endif
static
struct {
@@ -921,15 +889,9 @@ struct {
{"katakana","h2"},
{"katakana-hiragana","h3"},
{"guess", "g"},
- {"cp932", ""},
- {"no-cp932", ""},
-#ifdef X0212_ENABLE
- {"x0212", ""},
-#endif
#ifdef UTF8_OUTPUT_ENABLE
{"utf8", "w"},
{"utf16", "w16"},
- {"ms-ucs-map", ""},
#endif
#ifdef UTF8_INPUT_ENABLE
{"utf8-input", "W"},
@@ -950,6 +912,7 @@ struct {
{"debug", ""},
#endif
#ifdef SHIFTJIS_CP932
+ {"no-cp932", ""},
{"cp932inv", ""},
#endif
#ifdef EXEC_IO
@@ -959,24 +922,20 @@ struct {
{"prefix=", ""},
};
-static int option_mode = 0;
+static int option_mode;
void
options(cp)
unsigned char *cp;
{
int i;
- unsigned char *p = NULL;
+ unsigned char *p;
if (option_mode==1)
return;
if (*cp++ != '-')
return;
while (*cp) {
- if (p && !*cp) {
- cp = p;
- p = 0;
- }
switch (*cp++) {
case '-': /* literal options */
if (!*cp) { /* ignore the rest of arguments */
@@ -988,8 +947,8 @@ options(cp)
p = (unsigned char *)long_option[i].name;
for (j=0;*p && (*p != '=') && *p == cp[j];p++, j++);
if (*p == cp[j]){
- p = &cp[j];
- break;
+ p = &cp[j];
+ break;
}
p = 0;
}
@@ -1029,40 +988,16 @@ options(cp)
continue;
}
#endif
- if (strcmp(long_option[i].name, "cp932") == 0){
#ifdef SHIFTJIS_CP932
- cp932_f = TRUE;
- cp932inv_f = TRUE;
-#endif
-#ifdef UTF8_OUTPUT_ENABLE
- ms_ucs_map_f = TRUE;
-#endif
- continue;
- }
if (strcmp(long_option[i].name, "no-cp932") == 0){
-#ifdef SHIFTJIS_CP932
cp932_f = FALSE;
- cp932inv_f = FALSE;
-#endif
-#ifdef UTF8_OUTPUT_ENABLE
- ms_ucs_map_f = FALSE;
-#endif
continue;
}
-#ifdef SHIFTJIS_CP932
if (strcmp(long_option[i].name, "cp932inv") == 0){
cp932inv_f = TRUE;
continue;
}
#endif
-
-#ifdef X0212_ENABLE
- if (strcmp(long_option[i].name, "x0212") == 0){
- x0212_f = TRUE;
- continue;
- }
-#endif
-
#ifdef EXEC_IO
if (strcmp(long_option[i].name, "exec-in") == 0){
exec_f = 1;
@@ -1073,12 +1008,6 @@ options(cp)
return;
}
#endif
-#ifdef UTF8_OUTPUT_ENABLE
- if (strcmp(long_option[i].name, "ms-ucs-map") == 0){
- ms_ucs_map_f = TRUE;
- continue;
- }
-#endif
if (strcmp(long_option[i].name, "prefix=") == 0){
if (*p == '=' && ' ' < p[1] && p[1] < 128){
for (i = 2; ' ' < p[i] && p[i] < 128; i++){
@@ -1153,23 +1082,17 @@ options(cp)
if ('1'== cp[0] && '6'==cp[1]) {
output_conv = w_oconv16; cp+=2;
if (cp[0]=='L') {
- unicode_bom_f=2; cp++;
+ w_oconv16_begin_f=2; cp++;
w_oconv16_LE = 1;
if (cp[0] == '0'){
- unicode_bom_f=1; cp++;
+ w_oconv16_begin_f=1; cp++;
}
} else if (cp[0] == 'B') {
- unicode_bom_f=2; cp++;
+ w_oconv16_begin_f=2; cp++;
if (cp[0] == '0'){
- unicode_bom_f=1; cp++;
+ w_oconv16_begin_f=1; cp++;
}
- }
- } else if (cp[0] == '8') {
- output_conv = w_oconv; cp++;
- unicode_bom_f=2;
- if (cp[0] == '0'){
- unicode_bom_f=1; cp++;
- }
+ }
} else
output_conv = w_oconv;
continue;
@@ -1177,21 +1100,7 @@ options(cp)
#ifdef UTF8_INPUT_ENABLE
case 'W': /* UTF-8 input */
if ('1'== cp[0] && '6'==cp[1]) {
- input_f = UTF16BE_INPUT;
- utf16_mode = UTF16BE_INPUT;
- cp += 2;
- if (cp[0]=='L') {
- cp++;
- input_f = UTF16LE_INPUT;
- utf16_mode = UTF16LE_INPUT;
- } else if (cp[0] == 'B') {
- cp++;
- input_f = UTF16BE_INPUT;
- utf16_mode = UTF16BE_INPUT;
- }
- } else if (cp[0] == '8') {
- cp++;
- input_f = UTF8_INPUT;
+ input_f = UTF16_INPUT;
} else
input_f = UTF8_INPUT;
continue;
@@ -1254,7 +1163,6 @@ options(cp)
}
continue;
case 'm': /* MIME support */
- /* mime_decode_f = TRUE; */ /* this has too large side effects... */
if (*cp=='B'||*cp=='Q') {
mime_decode_mode = *cp++;
mimebuf_f = FIXED_MIME;
@@ -1263,7 +1171,6 @@ options(cp)
} else if (*cp=='S') {
mime_f = STRICT_MIME; cp++;
} else if (*cp=='0') {
- mime_decode_f = FALSE;
mime_f = FALSE; cp++;
}
continue;
@@ -1349,10 +1256,6 @@ struct input_code * find_inputcode_byfunc(iconv_func)
return 0;
}
-#ifdef CHECK_OPTION
-static int (*iconv_for_check)() = 0;
-#endif
-
#ifdef ANSI_C_PROTOTYPE
void set_iconv(int f, int (*iconv_func)(int c2,int c1,int c0))
#else
@@ -1361,6 +1264,9 @@ void set_iconv(f, iconv_func)
int (*iconv_func)();
#endif
{
+#ifdef CHECK_OPTION
+ static int (*iconv_for_check)() = 0;
+#endif
#ifdef INPUT_CODE_FIX
if (f || !input_f)
#endif
@@ -1530,11 +1436,6 @@ void s_status(ptr, c)
ptr->stat = 2;
status_push_ch(ptr, c);
#endif /* SHIFTJIS_CP932 */
-#ifdef X0212_ENABLE
- }else if (x0212_f && 0xf0 <= c && c <= 0xfc){
- ptr->stat = 1;
- status_push_ch(ptr, c);
-#endif /* X0212_ENABLE */
}else{
status_disable(ptr);
}
@@ -1549,8 +1450,8 @@ void s_status(ptr, c)
status_disable(ptr);
}
break;
- case 2:
#ifdef SHIFTJIS_CP932
+ case 2:
if ((0x40 <= c && c <= 0x7e) || (0x80 <= c && c <= 0xfc)){
status_push_ch(ptr, c);
if (s2e_conv(ptr->buf[0], ptr->buf[1], &ptr->buf[0], &ptr->buf[1]) == 0){
@@ -1559,11 +1460,9 @@ void s_status(ptr, c)
break;
}
}
-#endif /* SHIFTJIS_CP932 */
-#ifndef X0212_ENABLE
status_disable(ptr);
break;
-#endif
+#endif /* SHIFTJIS_CP932 */
}
}
@@ -1585,11 +1484,6 @@ void e_status(ptr, c)
}else if (SSO == c || (0xa1 <= c && c <= 0xfe)){
ptr->stat = 1;
status_push_ch(ptr, c);
-#ifdef X0212_ENABLE
- }else if (0x8f == c){
- ptr->stat = 2;
- status_push_ch(ptr, c);
-#endif /* X0212_ENABLE */
}else{
status_disable(ptr);
}
@@ -1603,15 +1497,6 @@ void e_status(ptr, c)
status_disable(ptr);
}
break;
-#ifdef X0212_ENABLE
- case 2:
- if (0xa1 <= c && c <= 0xfe){
- ptr->stat = 1;
- status_push_ch(ptr, c);
- }else{
- status_disable(ptr);
- }
-#endif /* X0212_ENABLE */
}
}
@@ -1745,31 +1630,39 @@ code_status(c)
}
}
-#ifndef WIN32DLL
+#ifdef PERL_XS
+#define STD_GC_BUFSIZE (256)
+int std_gc_buf[STD_GC_BUFSIZE];
+int std_gc_ndx;
+#endif
+
int
std_getc(f)
FILE *f;
{
+#ifdef PERL_XS
if (std_gc_ndx){
return std_gc_buf[--std_gc_ndx];
}
+#endif
return getc(f);
}
-#endif /*WIN32DLL*/
int
std_ungetc(c,f)
int c;
FILE *f;
{
+#ifdef PERL_XS
if (std_gc_ndx == STD_GC_BUFSIZE){
return EOF;
}
std_gc_buf[std_gc_ndx++] = c;
return c;
+#endif
+ return ungetc(c,f);
}
-#ifndef WIN32DLL
void
std_putc(c)
int c;
@@ -1777,7 +1670,6 @@ int c;
if(c!=EOF)
putchar(c);
}
-#endif /*WIN32DLL*/
int
noconvert(f)
@@ -1868,9 +1760,7 @@ module_connection()
#ifdef UTF8_INPUT_ENABLE
} else if (input_f == UTF8_INPUT) {
set_iconv(-TRUE, w_iconv);
- } else if (input_f == UTF16BE_INPUT) {
- set_iconv(-TRUE, w_iconv16);
- } else if (input_f == UTF16LE_INPUT) {
+ } else if (input_f == UTF16_INPUT) {
set_iconv(-TRUE, w_iconv16);
#endif
} else {
@@ -1895,7 +1785,6 @@ kanji_convert(f)
{
int c1,
c2, c3;
- int is_8bit = FALSE;
module_connection();
c2 = 0;
@@ -1915,7 +1804,7 @@ kanji_convert(f)
/* second byte */
if (c2 > DEL) {
/* in case of 8th bit is on */
- if (!estab_f&&!mime_decode_mode) {
+ if (!estab_f) {
/* in case of not established yet */
/* It is still ambiguious */
if (h_conv(f, c2, c1)==EOF)
@@ -1960,7 +1849,6 @@ kanji_convert(f)
/* 8 bit code */
if (!estab_f && !iso8859_f) {
/* not established yet */
- if (!is_8bit) is_8bit = TRUE;
c2 = c1;
NEXT;
} else { /* estab_f==TRUE */
@@ -2086,12 +1974,6 @@ kanji_convert(f)
input_mode = X0208;
shift_mode = FALSE;
NEXT;
-#ifdef X0212_ENABLE
- } else if (c1 == 'D'){
- input_mode = X0212;
- shift_mode = FALSE;
- NEXT;
-#endif /* X0212_ENABLE */
} else {
/* could be some special code */
(*oconv)(0, ESC);
@@ -2157,42 +2039,12 @@ kanji_convert(f)
} else if ((c1 == NL || c1 == CR) && broken_f&4) {
input_mode = ASCII; set_iconv(FALSE, 0);
SEND;
- } else if (c1 == NL && mime_decode_f && !mime_decode_mode ) {
- if ((c1=(*i_getc)(f))!=EOF && c1 == SPACE) {
- i_ungetc(SPACE,f);
- continue;
- } else {
- i_ungetc(c1,f);
- }
- c1 = NL;
- SEND;
- } else if (c1 == CR && mime_decode_f && !mime_decode_mode ) {
- if ((c1=(*i_getc)(f))!=EOF) {
- if (c1==SPACE) {
- i_ungetc(SPACE,f);
- continue;
- } else if (c1 == NL && (c1=(*i_getc)(f))!=EOF && c1 == SPACE) {
- i_ungetc(SPACE,f);
- continue;
- } else {
- i_ungetc(c1,f);
- }
- i_ungetc(NL,f);
- } else {
- i_ungetc(c1,f);
- }
- c1 = CR;
- SEND;
} else
SEND;
}
/* send: */
if (input_mode == X0208)
(*oconv)(c2, c1); /* this is JIS, not SJIS/EUC case */
-#ifdef X0212_ENABLE
- else if (input_mode == X0212)
- (*oconv)((0x8f << 8) | c2, c1);
-#endif /* X0212_ENABLE */
else if (input_mode)
(*oconv)(input_mode, c1); /* other special case */
else if ((*iconv)(c2, c1, 0) < 0){ /* can be EUC/SJIS */
@@ -2210,18 +2062,6 @@ kanji_convert(f)
/* epilogue */
(*iconv)(EOF, 0, 0);
- if (!is_inputcode_set)
- {
- if (is_8bit) {
- struct input_code *p = input_code_list;
- struct input_code *result = p;
- while (p->name){
- if (p->score < result->score) result = p;
- ++p;
- }
- set_input_codename(result->name);
- }
- }
return 1;
}
@@ -2339,35 +2179,15 @@ int s2e_conv(c2, c1, p2, p1)
int c2, c1;
int *p2, *p1;
{
- int val;
#ifdef SHIFTJIS_CP932
if (cp932_f && CP932_TABLE_BEGIN <= c2 && c2 <= CP932_TABLE_END){
extern unsigned short shiftjis_cp932[3][189];
- val = shiftjis_cp932[c2 - CP932_TABLE_BEGIN][c1 - 0x40];
- if (val){
- c2 = val >> 8;
- c1 = val & 0xff;
- }
+ c1 = shiftjis_cp932[c2 - CP932_TABLE_BEGIN][c1 - 0x40];
+ if (c1 == 0) return 1;
+ c2 = c1 >> 8;
+ c1 &= 0xff;
}
#endif /* SHIFTJIS_CP932 */
-#ifdef X0212_ENABLE
- if (x0212_f && 0xfa <= c2 && c2 <= 0xfc){
- extern unsigned short shiftjis_x0212[3][189];
- val = shiftjis_x0212[c2 - 0xfa][c1 - 0x40];
- if (val){
- if (val & 0x8000){
- c2 = (0x8f << 8) | (val >> 8);
- c1 = val & 0xff;
- }else{
- c2 = val >> 8;
- c1 = val & 0xff;
- }
- if (p2) *p2 = c2;
- if (p1) *p1 = c1;
- return 0;
- }
- }
-#endif
c2 = c2 + c2 - ((c2 <= 0x9f) ? SJ0162 : SJ6394);
if (c1 < 0x9f)
c1 = c1 - ((c1 > DEL) ? SPACE : 0x1f);
@@ -2375,12 +2195,6 @@ int s2e_conv(c2, c1, p2, p1)
c1 = c1 - 0x7e;
c2++;
}
-
-#ifdef X0212_ENABLE
- if (x0212_f){
- c2 = x0212_unshift(c2);
- }
-#endif
if (p2) *p2 = c2;
if (p1) *p1 = c1;
return 0;
@@ -2410,26 +2224,6 @@ e_iconv(c2, c1, c0)
{
if (c2 == X0201) {
c1 &= 0x7f;
-#ifdef X0212_ENABLE
- }else if (c2 == 0x8f){
- if (c0 == 0){
- return -1;
- }
- c2 = (c2 << 8) | (c1 & 0x7f);
- c1 = c0 & 0x7f;
-#ifdef SHIFTJIS_CP932
- if (cp932_f){
- int s2, s1;
- if (e2s_conv(c2, c1, &s2, &s1) == 0){
- s2e_conv(s2, s1, &c2, &c1);
- if ((c2 & 0xff00) == 0){
- c1 &= 0x7f;
- c2 &= 0x7f;
- }
- }
- }
-#endif /* SHIFTJIS_CP932 */
-#endif /* X0212_ENABLE */
} else if (c2 == SSO){
c2 = X0201;
c1 &= 0x7f;
@@ -2522,7 +2316,7 @@ ww16_conv(c2, c1, c0)
val |= (c0 & 0x3f);
}else if (c2 >= 0xc0){
val = (c2 & 0x1f) << 6;
- val |= (c1 & 0x3f);
+ val |= (c1 & 0x3f) << 6;
}else{
val = c2;
}
@@ -2559,9 +2353,6 @@ w16e_conv(val, p2, p1)
ret = 0;
}
#endif
- }else{
- *p2 = 0;
- *p1 = c2;
}
return ret;
}
@@ -2573,13 +2364,13 @@ w_iconv16(c2, c1, c0)
int ret;
if (c2==0376 && c1==0377){
- utf16_mode = UTF16BE_INPUT;
+ utf16_mode = UTF16_INPUT;
return 0;
} else if (c2==0377 && c1==0376){
- utf16_mode = UTF16LE_INPUT;
+ utf16_mode = UTF16BE_INPUT;
return 0;
}
- if (c2 != EOF && utf16_mode == UTF16LE_INPUT) {
+ if (c2 != EOF && utf16_mode == UTF16BE_INPUT) {
int tmp;
tmp=c1; c1=c2; c2=tmp;
}
@@ -2617,10 +2408,6 @@ w_iconv_common(c1, c0, pp, psize, p2, p1)
if (val == 0) return 1;
c2 = val >> 8;
- if (val & 0x8000){
- c2 &= 0x7f;
- c2 |= 0x8f00;
- }
if (c2 == SO) c2 = X0201;
c1 = val & 0x7f;
if (p2) *p2 = c2;
@@ -2637,25 +2424,15 @@ e2w_conv(c2, c1)
{
extern unsigned short euc_to_utf8_1byte[];
extern unsigned short * euc_to_utf8_2bytes[];
- extern unsigned short * euc_to_utf8_2bytes_ms[];
unsigned short *p;
if (c2 == X0201) {
p = euc_to_utf8_1byte;
-#ifdef X0212_ENABLE
- } else if (c2 >> 8 == 0x8f){
- extern unsigned short * x0212_to_utf8_2bytes[];
- c2 = (c2&0x7f) - 0x21;
- if (0<=c2 && c2<sizeof_euc_to_utf8_2bytes)
- p = x0212_to_utf8_2bytes[c2];
- else
- return 0;
-#endif
} else {
c2 &= 0x7f;
c2 = (c2&0x7f) - 0x21;
if (0<=c2 && c2<sizeof_euc_to_utf8_2bytes)
- p = ms_ucs_map_f ? euc_to_utf8_2bytes_ms[c2] : euc_to_utf8_2bytes[c2];
+ p = euc_to_utf8_2bytes[c2];
else
return 0;
}
@@ -2672,18 +2449,6 @@ w_oconv(c2, c1)
c1;
{
int c0;
- if (c2 == EOF) {
- (*o_putc)(EOF);
- return;
- }
-
- if (unicode_bom_f==2) {
- (*o_putc)('\357');
- (*o_putc)('\273');
- (*o_putc)('\277');
- unicode_bom_f=1;
- }
-
#ifdef NUMCHAR_OPTION
if (c2 == 0 && (c1 & CLASS_MASK) == CLASS_UTF16){
w16w_conv(c1, &c2, &c1, &c0);
@@ -2692,27 +2457,24 @@ w_oconv(c2, c1)
(*o_putc)(c1);
if (c0) (*o_putc)(c0);
}
- return;
}
#endif
-
- if (c2 == 0) {
+ if (c2 == EOF) {
+ (*o_putc)(EOF);
+ return;
+ } else if (c2 == 0) {
output_mode = ASCII;
(*o_putc)(c1);
} else if (c2 == ISO8859_1) {
output_mode = ISO8859_1;
(*o_putc)(c1 | 0x080);
} else {
- unsigned short val;
output_mode = UTF8;
- val = e2w_conv(c2, c1);
- if (val){
- w16w_conv(val, &c2, &c1, &c0);
- (*o_putc)(c2);
- if (c1){
- (*o_putc)(c1);
- if (c0) (*o_putc)(c0);
- }
+ w16w_conv((unsigned short)e2w_conv(c2, c1), &c2, &c1, &c0);
+ (*o_putc)(c2);
+ if (c1){
+ (*o_putc)(c1);
+ if (c0) (*o_putc)(c0);
}
}
}
@@ -2727,7 +2489,7 @@ w_oconv16(c2, c1)
return;
}
- if (unicode_bom_f==2) {
+ if (w_oconv16_begin_f==2) {
if (w_oconv16_LE){
(*o_putc)((unsigned char)'\377');
(*o_putc)('\376');
@@ -2735,7 +2497,7 @@ w_oconv16(c2, c1)
(*o_putc)('\376');
(*o_putc)((unsigned char)'\377');
}
- unicode_bom_f=1;
+ w_oconv16_begin_f=1;
}
if (c2 == ISO8859_1) {
@@ -2747,7 +2509,7 @@ w_oconv16(c2, c1)
c1 &= 0xff;
#endif
} else if (c2) {
- unsigned short val = e2w_conv(c2, c1);
+ unsigned short val = (unsigned short)e2w_conv(c2, c1);
c2 = (val >> 8) & 0xff;
c1 = val & 0xff;
}
@@ -2770,9 +2532,6 @@ e_oconv(c2, c1)
#ifdef NUMCHAR_OPTION
if (c2 == 0 && (c1 & CLASS_MASK) == CLASS_UTF16){
w16e_conv(c1, &c2, &c1);
- if (c2 == 0 && (c1 & CLASS_MASK) == CLASS_UTF16){
- return;
- }
}
#endif
if (c2 == EOF) {
@@ -2787,28 +2546,6 @@ e_oconv(c2, c1)
} else if (c2 == ISO8859_1) {
output_mode = ISO8859_1;
(*o_putc)(c1 | 0x080);
-#ifdef X0212_ENABLE
- } else if ((c2 & 0xff00) >> 8 == 0x8f){
- output_mode = JAPANESE_EUC;
-#ifdef SHIFTJIS_CP932
- if (cp932_f){
- int s2, s1;
- if (e2s_conv(c2, c1, &s2, &s1) == 0){
- s2e_conv(s2, s1, &c2, &c1);
- }
- }
-#endif
- if ((c2 & 0xff00) >> 8 == 0x8f){
- if (x0212_f){
- (*o_putc)(0x8f);
- (*o_putc)((c2 & 0x7f) | 0x080);
- (*o_putc)(c1 | 0x080);
- }
- }else{
- (*o_putc)((c2 & 0x7f) | 0x080);
- (*o_putc)(c1 | 0x080);
- }
-#endif
} else {
if ((c1<0x21 || 0x7e<c1) ||
(c2<0x21 || 0x7e<c2)) {
@@ -2821,71 +2558,12 @@ e_oconv(c2, c1)
}
}
-#ifdef X0212_ENABLE
-int x0212_shift(c)
- int c;
-{
- int ret = c;
- c &= 0x7f;
- if ((ret & 0xff00) == 0x8f00){
- if (0x75 <= c && c <= 0x7f){
- ret = c + (0x109 - 0x75);
- }
- }else{
- if (0x75 <= c && c <= 0x7f){
- ret = c + (0x113 - 0x75);
- }
- }
- return ret;
-}
-
-
-int x0212_unshift(c)
- int c;
-{
- int ret = c;
- if (0x7f <= c && c <= 0x88){
- ret = c + (0x75 - 0x7f);
- }else if (0x89 <= c && c <= 0x92){
- ret = (0x8f << 8) | 0x80 | (c + (0x75 - 0x89));
- }
- return ret;
-}
-#endif /* X0212_ENABLE */
-
-int
+void
e2s_conv(c2, c1, p2, p1)
int c2, c1, *p2, *p1;
{
- int val = 0;
- unsigned short *ptr;
- int ndx;
- extern unsigned short *x0212_shiftjis[];
-#ifdef X0212_ENABLE
- if ((c2 & 0xff00) == 0x8f00){
- ndx = c2 & 0x7f;
- if (0x21 <= ndx && ndx <= 0x7e){
- ptr = x0212_shiftjis[ndx - 0x21];
- if (ptr){
- val = ptr[(c1 & 0x7f) - 0x21];
- }
- if (val){
- c2 = val >> 8;
- c1 = val & 0xff;
- if (p2) *p2 = c2;
- if (p1) *p1 = c1;
- return 0;
- }
- }
- c2 = x0212_shift(c2);
- }
-#endif /* X0212_ENABLE */
- if ((c2 & 0xff00) == 0x8f00){
- return 1;
- }
if (p2) *p2 = ((c2 - 1) >> 1) + ((c2 <= 0x5e) ? 0x71 : 0xb1);
if (p1) *p1 = c1 + ((c2 & 1) ? ((c1 < 0x60) ? 0x1f : 0x20) : 0x7e);
- return 0;
}
void
@@ -2910,14 +2588,6 @@ s_oconv(c2, c1)
} else if (c2 == ISO8859_1) {
output_mode = ISO8859_1;
(*o_putc)(c1 | 0x080);
-#ifdef X0212_ENABLE
- } else if ((c2 & 0xff00) >> 8 == 0x8f){
- output_mode = SHIFT_JIS;
- if (e2s_conv(c2, c1, &c2, &c1) == 0){
- (*o_putc)(c2);
- (*o_putc)(c1);
- }
-#endif
} else {
if ((c1<0x20 || 0x7e<c1) ||
(c2<0x20 || 0x7e<c2)) {
@@ -2965,18 +2635,6 @@ j_oconv(c2, c1)
output_mode = ASCII;
}
(*o_putc)(EOF);
-#ifdef X0212_ENABLE
- } else if ((c2 & 0xff00) >> 8 == 0x8f){
- if (output_mode!=X0212) {
- output_mode = X0212;
- (*o_putc)(ESC);
- (*o_putc)('$');
- (*o_putc)('(');
- (*o_putc)('D');
- }
- (*o_putc)(c2 & 0x7f);
- (*o_putc)(c1);
-#endif
} else if (c2==X0201) {
if (output_mode!=X0201) {
output_mode = X0201;
@@ -3020,7 +2678,13 @@ base64_conv(c2, c1)
int c2,
c1;
{
- mime_prechar(c2, c1);
+ if (base64_count>50 && !mimeout_mode && c2==0 && c1==SPACE) {
+ (*o_putc)(NL);
+ } else if (base64_count>66 && mimeout_mode) {
+ (*o_base64conv)(EOF,0);
+ (*o_putc)(NL);
+ (*o_putc)('\t'); base64_count += 7;
+ }
(*o_base64conv)(c2,c1);
}
@@ -3521,10 +3185,6 @@ int mime_encode_method[] = {
#define nkf_toupper(c) (('a'<=c && c<='z')?(c-('a'-'A')):c)
#define nkf_isdigit(c) ('0'<=c && c<='9')
#define nkf_isxdigit(c) (nkf_isdigit(c) || ('a'<=c && c<='f') || ('A'<=c && c <= 'F'))
-#define nkf_isblank(c) (c == SPACE || c == TAB)
-#define nkf_isspace(c) (nkf_isblank(c) || c == CR || c == NL)
-#define nkf_isalpha(c) (('a' <= c && c <= 'z') || ('A' <= c && c <= 'Z'))
-#define nkf_isalnum(c) (nkf_isdigit(c) || nkf_isalpha(c))
void
switch_mime_getc()
@@ -3585,7 +3245,6 @@ FILE *f;
}
mime_decode_mode = p[i-2];
- set_iconv(FALSE, mime_priority_func[j]);
clr_code_score(find_inputcode_byfunc(mime_priority_func[j]), SCORE_iMIME);
if (mime_decode_mode=='B') {
@@ -3712,7 +3371,6 @@ set_input_codename (codename)
is_inputcode_set = TRUE;
}
-#ifndef WIN32DLL
void
print_guessed_code (filename)
char *filename;
@@ -3728,7 +3386,6 @@ print_guessed_code (filename)
if (filename != NULL) printf("%s:", filename);
printf("%s\n", codename);
}
-#endif /*WIN32DLL*/
int
hex2bin(x)
@@ -3873,10 +3530,6 @@ FILE *f;
{
int c1, c2, c3, c4, cc;
int t1, t2, t3, t4, mode, exit_mode;
- int lwsp_count;
- char *lwsp_buf;
- char *lwsp_buf_new;
- int lwsp_size = 128;
if (mime_top != mime_last) { /* Something is in FIFO */
return Fifo(mime_top++);
@@ -3905,69 +3558,8 @@ restart_mime_q:
if (c1=='?'&&c2=='=' && mimebuf_f != FIXED_MIME) {
/* end Q encoding */
input_mode = exit_mode;
- lwsp_count = 0;
- lwsp_buf = malloc((lwsp_size+5)*sizeof(char));
- if (lwsp_buf==NULL) {
- perror("can't malloc");
- return -1;
- }
- while ((c1=(*i_getc)(f))!=EOF) {
- switch (c1) {
- case NL:
- case CR:
- if (c1==NL) {
- if ((c1=(*i_getc)(f))!=EOF && (c1==SPACE||c1==TAB)) {
- i_ungetc(SPACE,f);
- continue;
- } else {
- i_ungetc(c1,f);
- }
- c1 = NL;
- } else {
- if ((c1=(*i_getc)(f))!=EOF && c1 == NL) {
- if ((c1=(*i_getc)(f))!=EOF && (c1==SPACE||c1==TAB)) {
- i_ungetc(SPACE,f);
- continue;
- } else {
- i_ungetc(c1,f);
- }
- i_ungetc(NL,f);
- } else {
- i_ungetc(c1,f);
- }
- c1 = CR;
- }
- break;
- case SPACE:
- case TAB:
- lwsp_buf[lwsp_count] = c1;
- if (lwsp_count++>lwsp_size){
- lwsp_size *= 2;
- lwsp_buf_new = realloc(lwsp_buf, (lwsp_size+5)*sizeof(char));
- if (lwsp_buf_new==NULL) {
- free(lwsp_buf);
- lwsp_buf = NULL;
- perror("can't realloc");
- return -1;
- }
- lwsp_buf = lwsp_buf_new;
- }
- continue;
- }
- break;
- }
- if (lwsp_count > 0) {
- if (c1=='=' && (lwsp_buf[lwsp_count-1]==SPACE||lwsp_buf[lwsp_count-1]==TAB)) {
- lwsp_count = 0;
- } else {
- i_ungetc(c1,f);
- for(lwsp_count--;lwsp_count>0;lwsp_count--)
- i_ungetc(lwsp_buf[lwsp_count],f);
- c1 = lwsp_buf[0];
- }
- }
- free(lwsp_buf);
- lwsp_buf = NULL;
+ while((c1=(*i_getc)(f))!=EOF && c1==SPACE
+ /* && (c1==NL||c1==TAB||c1=='\r') */ ) ;
return c1;
}
if (c1=='='&&c2<' ') { /* this is soft wrap */
@@ -4021,72 +3613,8 @@ mime_c2_retry:
}
if ((c1 == '?') && (c2 == '=')) {
input_mode = ASCII;
- lwsp_count = 0;
- lwsp_buf = malloc((lwsp_size+5)*sizeof(char));
- if (lwsp_buf==NULL) {
- perror("can't malloc");
- return -1;
- }
- while ((c1=(*i_getc)(f))!=EOF) {
- switch (c1) {
- case NL:
- case CR:
- if (c1==NL) {
- if ((c1=(*i_getc)(f))!=EOF && (c1==SPACE||c1==TAB)) {
- i_ungetc(SPACE,f);
- continue;
- } else {
- i_ungetc(c1,f);
- }
- c1 = NL;
- } else {
- if ((c1=(*i_getc)(f))!=EOF) {
- if (c1==SPACE) {
- i_ungetc(SPACE,f);
- continue;
- } else if ((c1=(*i_getc)(f))!=EOF && (c1==SPACE||c1==TAB)) {
- i_ungetc(SPACE,f);
- continue;
- } else {
- i_ungetc(c1,f);
- }
- i_ungetc(NL,f);
- } else {
- i_ungetc(c1,f);
- }
- c1 = CR;
- }
- break;
- case SPACE:
- case TAB:
- lwsp_buf[lwsp_count] = c1;
- if (lwsp_count++>lwsp_size){
- lwsp_size *= 2;
- lwsp_buf_new = realloc(lwsp_buf, (lwsp_size+5)*sizeof(char));
- if (lwsp_buf_new==NULL) {
- free(lwsp_buf);
- lwsp_buf = NULL;
- perror("can't realloc");
- return -1;
- }
- lwsp_buf = lwsp_buf_new;
- }
- continue;
- }
- break;
- }
- if (lwsp_count > 0) {
- if (c1=='=' && (lwsp_buf[lwsp_count-1]==SPACE||lwsp_buf[lwsp_count-1]==TAB)) {
- lwsp_count = 0;
- } else {
- i_ungetc(c1,f);
- for(lwsp_count--;lwsp_count>0;lwsp_count--)
- i_ungetc(lwsp_buf[lwsp_count],f);
- c1 = lwsp_buf[0];
- }
- }
- free(lwsp_buf);
- lwsp_buf = NULL;
+ while((c1=(*i_getc)(f))!=EOF && c1==SPACE
+ /* && (c1==NL||c1==TAB||c1=='\r') */ ) ;
return c1;
}
mime_c3_retry:
@@ -4204,11 +3732,6 @@ static char basis_64[] =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
static int b64c;
-#define MIMEOUT_BUF_LENGTH (60)
-char mimeout_buf[MIMEOUT_BUF_LENGTH+1];
-int mimeout_buf_count = 0;
-int mimeout_preserve_space = 0;
-#define itoh4(c) (c>=10?c+'A'-10:c+'0')
void
open_mime(mode)
@@ -4216,53 +3739,20 @@ int mode;
{
unsigned char *p;
int i;
- int j;
p = mime_pattern[0];
for(i=0;mime_encode[i];i++) {
if (mode == mime_encode[i]) {
p = mime_pattern[i];
- break;
- }
- }
- mimeout_mode = mime_encode_method[i];
-
- i = 0;
- if (base64_count>45) {
- if (mimeout_buf_count>0 && nkf_isblank(mimeout_buf[i])){
- (*o_mputc)(mimeout_buf[i]);
- i++;
- }
- (*o_mputc)(NL);
- (*o_mputc)(SPACE);
- base64_count = 1;
- if (!mimeout_preserve_space && mimeout_buf_count>0
- && (mimeout_buf[i]==SPACE || mimeout_buf[i]==TAB
- || mimeout_buf[i]==CR || mimeout_buf[i]==NL )) {
- i++;
- }
- }
- if (!mimeout_preserve_space) {
- for (;i<mimeout_buf_count;i++) {
- if (mimeout_buf[i]==SPACE || mimeout_buf[i]==TAB
- || mimeout_buf[i]==CR || mimeout_buf[i]==NL ) {
- (*o_mputc)(mimeout_buf[i]);
- base64_count ++;
- } else {
break;
- }
}
}
- mimeout_preserve_space = FALSE;
-
+ mimeout_mode = mime_encode_method[i];
+
+ /* (*o_mputc)(' '); */
while(*p) {
(*o_mputc)(*p++);
base64_count ++;
}
- j = mimeout_buf_count;
- mimeout_buf_count = 0;
- for (;i<j;i++) {
- mime_putc(mimeout_buf[i]);
- }
}
void
@@ -4270,57 +3760,80 @@ close_mime()
{
(*o_mputc)('?');
(*o_mputc)('=');
- base64_count += 2;
+ (*o_mputc)(' ');
+ base64_count += 3;
mimeout_mode = 0;
}
-void
-eof_mime()
-{
- switch(mimeout_mode) {
- case 'Q':
- case 'B':
- break;
- case 2:
- (*o_mputc)(basis_64[((b64c & 0x3)<< 4)]);
- (*o_mputc)('=');
- (*o_mputc)('=');
- base64_count += 3;
- break;
- case 1:
- (*o_mputc)(basis_64[((b64c & 0xF) << 2)]);
- (*o_mputc)('=');
- base64_count += 2;
- break;
- }
- if (mimeout_mode) {
- if (mimeout_f!=FIXED_MIME) {
- close_mime();
- } else if (mimeout_mode != 'Q')
- mimeout_mode = 'B';
- }
-}
+#define itoh4(c) (c>=10?c+'A'-10:c+'0')
void
-mimeout_addchar(c)
+mime_putc(c)
int c;
{
+ if (mimeout_f==FIXED_MIME) {
+ if (base64_count>71) {
+ (*o_mputc)('\n');
+ base64_count=0;
+ }
+ } else if (c==NL) {
+ base64_count=0;
+ }
+ if (c!=EOF) {
+ if ( c<=DEL &&(output_mode==ASCII ||output_mode == ISO8859_1 )
+ && mimeout_f!=FIXED_MIME) {
+ if (mimeout_mode=='Q') {
+ if (c<=SPACE) {
+ close_mime();
+ }
+ (*o_mputc)(c);
+ return;
+ }
+ if (mimeout_mode!='B' || c!=SPACE) {
+ if (mimeout_mode) {
+ mime_putc(EOF);
+ mimeout_mode=0;
+ }
+ (*o_mputc)(c);
+ base64_count ++;
+ return;
+ }
+ } else if (!mimeout_mode && mimeout_f!=FIXED_MIME) {
+ open_mime(output_mode);
+ }
+ } else { /* c==EOF */
+ switch(mimeout_mode) {
+ case 'Q':
+ case 'B':
+ break;
+ case 2:
+ (*o_mputc)(basis_64[((b64c & 0x3)<< 4)]);
+ (*o_mputc)('=');
+ (*o_mputc)('=');
+ base64_count += 3;
+ break;
+ case 1:
+ (*o_mputc)(basis_64[((b64c & 0xF) << 2)]);
+ (*o_mputc)('=');
+ base64_count += 2;
+ break;
+ }
+ if (mimeout_mode) {
+ if (mimeout_f!=FIXED_MIME) {
+ close_mime();
+ } else if (mimeout_mode != 'Q')
+ mimeout_mode = 'B';
+ }
+ return;
+ }
switch(mimeout_mode) {
case 'Q':
- if(c==SPACE){
- (*o_mputc)('_');
- base64_count++;
- } else if (c==CR||c==NL) {
- (*o_mputc)(c);
- base64_count = 0;
- } else if(c<SPACE||c=='='||c=='?'||c=='_'||DEL<=c) {
+ if(c>=DEL) {
(*o_mputc)('=');
(*o_mputc)(itoh4(((c>>4)&0xf)));
(*o_mputc)(itoh4((c&0xf)));
- base64_count += 3;
} else {
(*o_mputc)(c);
- base64_count++;
}
break;
case 'B':
@@ -4341,346 +3854,105 @@ mimeout_addchar(c)
mimeout_mode='B';
base64_count += 2;
break;
- default:
- (*o_mputc)(c);
- base64_count++;
- break;
- }
-}
-
-int mime_lastchar2, mime_lastchar1;
-
-void mime_prechar(c2, c1)
- int c2, c1;
-{
- if (mimeout_mode){
- if (c2){
- if (base64_count + mimeout_buf_count/3*4> 66){
- (*o_base64conv)(EOF,0);
- (*o_base64conv)(0,NL);
- (*o_base64conv)(0,SPACE);
- }
- }/*else if (mime_lastchar2){
- if (c1 <=DEL && !nkf_isspace(c1)){
- (*o_base64conv)(0,SPACE);
- }
- }*/
- }/*else{
- if (c2 && mime_lastchar2 == 0
- && mime_lastchar1 && !nkf_isspace(mime_lastchar1)){
- (*o_base64conv)(0,SPACE);
- }
- }*/
- mime_lastchar2 = c2;
- mime_lastchar1 = c1;
-}
-
-void
-mime_putc(c)
- int c;
-{
- int i = 0;
- int j = 0;
- int lastchar;
-
- if (mimeout_f == FIXED_MIME){
- if (mimeout_mode == 'Q'){
- if (base64_count > 71){
- if (c!=CR && c!=NL) {
- (*o_mputc)('=');
- (*o_mputc)(NL);
- }
- base64_count = 0;
- }
- }else{
- if (base64_count > 71){
- eof_mime();
- (*o_mputc)(NL);
- base64_count = 0;
- }
- if (c == EOF) { /* c==EOF */
- eof_mime();
- }
- }
- if (c != EOF) { /* c==EOF */
- mimeout_addchar(c);
- }
- return;
- }
-
- /* mimeout_f != FIXED_MIME */
-
- if (c == EOF) { /* c==EOF */
- j = mimeout_buf_count;
- mimeout_buf_count = 0;
- i = 0;
- for (;i<j;i++) {
- /*if (nkf_isspace(mimeout_buf[i])){
- break;
- }*/
- mimeout_addchar(mimeout_buf[i]);
- }
- eof_mime();
- for (;i<j;i++) {
- (*o_mputc)(mimeout_buf[i]);
- base64_count++;
- }
- return;
- }
-
- if (mimeout_mode=='Q') {
- if (c <= DEL && (output_mode==ASCII ||output_mode == ISO8859_1 ) ) {
- if (c <= SPACE) {
- close_mime();
- (*o_mputc)(SPACE);
- base64_count++;
- }
- (*o_mputc)(c);
- base64_count++;
- }
- return;
- }
-
- if (mimeout_buf_count > 0){
- lastchar = mimeout_buf[mimeout_buf_count - 1];
- }else{
- lastchar = -1;
- }
-
- if (!mimeout_mode) {
- if (c <= DEL && (output_mode==ASCII ||output_mode == ISO8859_1)) {
- if (nkf_isspace(c)) {
- if (c==CR || c==NL) {
- base64_count=0;
- }
- for (i=0;i<mimeout_buf_count;i++) {
- (*o_mputc)(mimeout_buf[i]);
- if (mimeout_buf[i] == CR || mimeout_buf[i] == NL){
- base64_count = 0;
- }else{
- base64_count++;
- }
- }
- mimeout_buf[0] = c;
- mimeout_buf_count = 1;
- }else{
- if (base64_count > 1
- && base64_count + mimeout_buf_count > 76){
- (*o_mputc)(NL);
- base64_count = 0;
- if (!nkf_isspace(mimeout_buf[0])){
- (*o_mputc)(SPACE);
- base64_count++;
- }
- }
- mimeout_buf[mimeout_buf_count++] = c;
- if (mimeout_buf_count>MIMEOUT_BUF_LENGTH) {
- open_mime(output_mode);
- }
- }
- return;
- }else{
- if (lastchar==CR || lastchar == NL){
- for (i=0;i<mimeout_buf_count;i++) {
- (*o_mputc)(mimeout_buf[i]);
- }
- base64_count = 0;
- mimeout_buf_count = 0;
- }
- if (lastchar==SPACE) {
- for (i=0;i<mimeout_buf_count-1;i++) {
- (*o_mputc)(mimeout_buf[i]);
- base64_count++;
- }
- mimeout_buf[0] = SPACE;
- mimeout_buf_count = 1;
- }
- open_mime(output_mode);
- }
- }else{
- /* mimeout_mode == 'B', 1, 2 */
- if ( c<=DEL && (output_mode==ASCII ||output_mode == ISO8859_1 ) ) {
- if (lastchar == CR || lastchar == NL){
- if (nkf_isblank(c)) {
- for (i=0;i<mimeout_buf_count;i++) {
- mimeout_addchar(mimeout_buf[i]);
- }
- mimeout_buf_count = 0;
- } else if (SPACE<c && c<DEL) {
- eof_mime();
- for (i=0;i<mimeout_buf_count;i++) {
- (*o_mputc)(mimeout_buf[i]);
- }
- base64_count = 0;
- mimeout_buf_count = 0;
- }
- }
- if (c==SPACE || c==TAB || c==CR || c==NL) {
- for (i=0;i<mimeout_buf_count;i++) {
- if (SPACE<mimeout_buf[i] && mimeout_buf[i]<DEL) {
- eof_mime();
- for (i=0;i<mimeout_buf_count;i++) {
- (*o_mputc)(mimeout_buf[i]);
- base64_count++;
- }
- mimeout_buf_count = 0;
- }
- }
- mimeout_buf[mimeout_buf_count++] = c;
- if (mimeout_buf_count>MIMEOUT_BUF_LENGTH) {
- eof_mime();
- for (i=0;i<mimeout_buf_count;i++) {
- (*o_mputc)(mimeout_buf[i]);
- base64_count++;
- }
- mimeout_buf_count = 0;
- }
- return;
- }
- if (mimeout_buf_count>0 && SPACE<c && c!='=') {
- mimeout_buf[mimeout_buf_count++] = c;
- if (mimeout_buf_count>MIMEOUT_BUF_LENGTH) {
- j = mimeout_buf_count;
- mimeout_buf_count = 0;
- for (i=0;i<j;i++) {
- mimeout_addchar(mimeout_buf[i]);
- }
- }
- return;
- }
- }
- }
- if (mimeout_buf_count>0) {
- j = mimeout_buf_count;
- mimeout_buf_count = 0;
- for (i=0;i<j;i++) {
- if (mimeout_buf[i]==CR || mimeout_buf[i]==NL)
- break;
- mimeout_addchar(mimeout_buf[i]);
- }
- if (i<j) {
- eof_mime();
- base64_count=0;
- for (;i<j;i++) {
- (*o_mputc)(mimeout_buf[i]);
- }
- open_mime(output_mode);
- }
}
- mimeout_addchar(c);
}
-#if defined(PERL_XS) || defined(WIN32DLL)
+#ifdef PERL_XS
void
reinit()
{
- {
- struct input_code *p = input_code_list;
- while (p->name){
- status_reinit(p++);
- }
- }
unbuf_f = FALSE;
estab_f = FALSE;
nop_f = FALSE;
- binmode_f = TRUE;
- rot_f = FALSE;
- hira_f = FALSE;
- input_f = FALSE;
- alpha_f = FALSE;
- mime_f = STRICT_MIME;
- mime_decode_f = FALSE;
- mimebuf_f = FALSE;
- broken_f = FALSE;
- iso8859_f = FALSE;
- mimeout_f = FALSE;
-#if defined(MSDOS) || defined(__OS2__)
- x0201_f = TRUE;
+ binmode_f = TRUE;
+ rot_f = FALSE;
+ hira_f = FALSE;
+ input_f = FALSE;
+ alpha_f = FALSE;
+ mime_f = STRICT_MIME;
+ mimebuf_f = FALSE;
+ broken_f = FALSE;
+ iso8859_f = FALSE;
+#if defined(MSDOS) || defined(__OS2__)
+ x0201_f = TRUE;
#else
x0201_f = NO_X0201;
#endif
iso2022jp_f = FALSE;
-#ifdef UTF8_OUTPUT_ENABLE
- unicode_bom_f = 0;
- w_oconv16_LE = 0;
- ms_ucs_map_f = FALSE;
-#endif
-#ifdef INPUT_OPTION
- cap_f = FALSE;
- url_f = FALSE;
- numchar_f = FALSE;
-#endif
-#ifdef CHECK_OPTION
- noout_f = FALSE;
- debug_f = FALSE;
-#endif
- guess_f = FALSE;
- is_inputcode_mixed = FALSE;
- is_inputcode_set = FALSE;
-#ifdef EXEC_IO
- exec_f = 0;
-#endif
-#ifdef SHIFTJIS_CP932
- cp932_f = TRUE;
- cp932inv_f = TRUE;
-#endif
- {
- int i;
- for (i = 0; i < 256; i++){
- prefix_table[i] = 0;
- }
- }
-#ifdef UTF8_INPUT_ENABLE
- utf16_mode = UTF16BE_INPUT;
-#endif
- mimeout_buf_count = 0;
- mimeout_mode = 0;
- base64_count = 0;
- f_line = 0;
- f_prev = 0;
- fold_preserve_f = FALSE;
- fold_f = FALSE;
- fold_len = 0;
+
kanji_intro = DEFAULT_J;
ascii_intro = DEFAULT_R;
- fold_margin = FOLD_MARGIN;
- output_conv = DEFAULT_CONV;
- oconv = DEFAULT_CONV;
- o_zconv = no_connection;
- o_fconv = no_connection;
- o_crconv = no_connection;
- o_rot_conv = no_connection;
- o_hira_conv = no_connection;
- o_base64conv = no_connection;
- o_iso2022jp_check_conv = no_connection;
+
+ output_conv = DEFAULT_CONV;
+ oconv = DEFAULT_CONV;
+
+ i_mgetc = std_getc;
+ i_mungetc = std_ungetc;
+ i_mgetc_buf = std_getc;
+ i_mungetc_buf = std_ungetc;
+
+ i_getc= std_getc;
+ i_ungetc=std_ungetc;
+
+ i_bgetc= std_getc;
+ i_bungetc= std_ungetc;
+
o_putc = std_putc;
+ o_mputc = std_putc;
+ o_crconv = no_connection;
+ o_rot_conv = no_connection;
+ o_iso2022jp_check_conv = no_connection;
+ o_hira_conv = no_connection;
+ o_fconv = no_connection;
+ o_zconv = no_connection;
+
i_getc = std_getc;
i_ungetc = std_ungetc;
- i_bgetc = std_getc;
- i_bungetc = std_ungetc;
- o_mputc = std_putc;
- i_mgetc = std_getc;
- i_mungetc = std_ungetc;
- i_mgetc_buf = std_getc;
- i_mungetc_buf = std_ungetc;
+ i_mgetc = std_getc;
+ i_mungetc = std_ungetc;
+
output_mode = ASCII;
input_mode = ASCII;
shift_mode = FALSE;
- mime_decode_mode = FALSE;
+ mime_decode_mode = FALSE;
file_out = FALSE;
- crmode_f = 0;
+ mimeout_mode = 0;
+ mimeout_f = FALSE;
+ base64_count = 0;
option_mode = 0;
+ crmode_f = 0;
+
+ {
+ struct input_code *p = input_code_list;
+ while (p->name){
+ status_reinit(p++);
+ }
+ }
+#ifdef UTF8_OUTPUT_ENABLE
+ if (w_oconv16_begin_f) {
+ w_oconv16_begin_f = 2;
+ }
+#endif
+ f_line = 0;
+ f_prev = 0;
+ fold_preserve_f = FALSE;
+ fold_f = FALSE;
+ fold_len = 0;
+ fold_margin = FOLD_MARGIN;
broken_counter = 0;
broken_last = 0;
z_prev2=0,z_prev1=0;
-#ifdef CHECK_OPTION
- iconv_for_check = 0;
-#endif
+
+ {
+ int i;
+ for (i = 0; i < 256; i++){
+ prefix_table[i] = 0;
+ }
+ }
input_codename = "";
-#ifdef WIN32DLL
- reinitdll();
-#endif /*WIN32DLL*/
+ is_inputcode_mixed = FALSE;
+ is_inputcode_set = FALSE;
}
#endif
@@ -4697,13 +3969,9 @@ int c2,c1,c0;
{
fprintf(stderr,"nkf internal module connection failure.\n");
exit(1);
- return 0; /* LINT */
}
#ifndef PERL_XS
-#ifdef WIN32DLL
-#define fprintf dllprintf
-#endif
void
usage()
{
@@ -4722,13 +3990,7 @@ usage()
#ifdef DEFAULT_CODE_UTF8
fprintf(stderr,"j,s,e,w Outout code is JIS 7 bit, Shift JIS, AT&T JIS (EUC), UTF-8 (DEFAULT)\n");
#endif
-#ifdef UTF8_OUTPUT_ENABLE
- fprintf(stderr," After 'w' you can add more options. (80?|16((B|L)0?)?) \n");
-#endif
fprintf(stderr,"J,S,E,W Input assumption is JIS 7 bit , Shift JIS, AT&T JIS (EUC), UTF-8\n");
-#ifdef UTF8_INPUT_ENABLE
- fprintf(stderr," After 'W' you can add more options. (8|16(B|L)?) \n");
-#endif
fprintf(stderr,"t no conversion\n");
fprintf(stderr,"i_/o_ Output sequence to designate JIS-kanji/ASCII (DEFAULT B)\n");
fprintf(stderr,"r {de/en}crypt ROT13/47\n");
@@ -4750,24 +4012,12 @@ usage()
fprintf(stderr,"I Convert non ISO-2022-JP charactor to GETA\n");
fprintf(stderr,"-L[uwm] line mode u:LF w:CRLF m:CR (DEFAULT noconversion)\n");
fprintf(stderr,"long name options\n");
- fprintf(stderr," --fj,--unix,--mac,--windows convert for the system\n");
+ fprintf(stderr," --fj,--unix,--mac,--windows convert for the system\n");
fprintf(stderr," --jis,--euc,--sjis,--utf8,--utf16,--mime,--base64 convert for the code\n");
- fprintf(stderr," --hiragana, --katakana Hiragana/Katakana Conversion\n");
- fprintf(stderr," --x0212 Convert JISX0212\n");
- fprintf(stderr," --cp932, --no-cp932 CP932 compatibility\n");
-#ifdef INPUT_OPTION
- fprintf(stderr," --cap-input, --url-input Convert hex after ':' or '%%'\n");
-#endif
-#ifdef NUMCHAR_OPTION
- fprintf(stderr," --numchar-input Convert Unicode Character Reference\n");
-#endif
-#ifdef UTF8_OUTPUT_ENABLE
- fprintf(stderr," --ms-ucs-map Microsoft UCS Mapping Compatible\n");
-#endif
#ifdef OVERWRITE
- fprintf(stderr," --overwrite Overwrite original listed files by filtered result\n");
+ fprintf(stderr," --overwrite Overwrite original listed files by filtered result\n");
#endif
- fprintf(stderr," -g, --guess Guess the input code\n");
+ fprintf(stderr," -g, --guess Guess the input code\n");
fprintf(stderr," --help,--version\n");
version();
}
@@ -4788,10 +4038,10 @@ version()
#ifdef __OS2__
"for OS/2"
#endif
- ,NKF_VERSION,NKF_RELEASE_DATE);
+ ,Version,Patchlevel);
fprintf(stderr,"\n%s\n",CopyRight);
}
-#endif /*PERL_XS*/
+#endif
/**
** $B%Q%C%A@):n<T(B
diff --git a/ext/nkf/nkf-utf8/utf8tbl.c b/ext/nkf/nkf-utf8/utf8tbl.c
index 7969081b4f..b2e49c49d2 100644
--- a/ext/nkf/nkf-utf8/utf8tbl.c
+++ b/ext/nkf/nkf-utf8/utf8tbl.c
@@ -15,23 +15,6 @@ unsigned short euc_to_utf8_A1[] = {
0xFF04, 0x00A2, 0x00A3, 0xFF05, 0xFF03, 0xFF06, 0xFF0A, 0xFF20,
0x00A7, 0x2606, 0x2605, 0x25CB, 0x25CF, 0x25CE, 0x25C7,
};
-
-/* Microsoft UCS Mapping Compatible */
-unsigned short euc_to_utf8_A1_ms[] = {
- 0x3000, 0x3001, 0x3002, 0xFF0C, 0xFF0E, 0x30FB, 0xFF1A,
- 0xFF1B, 0xFF1F, 0xFF01, 0x309B, 0x309C, 0x00B4, 0xFF40, 0x00A8,
- 0xFF3E, 0xFFE3, 0xFF3F, 0x30FD, 0x30FE, 0x309D, 0x309E, 0x3003,
- 0x4EDD, 0x3005, 0x3006, 0x3007, 0x30FC, 0x2015, 0x2010, 0xFF0F,
- 0xFF3C, 0xFF5E, 0x2225, 0xFF5C, 0x2026, 0x2025, 0x2018, 0x2019,
- 0x201C, 0x201D, 0xFF08, 0xFF09, 0x3014, 0x3015, 0xFF3B, 0xFF3D,
- 0xFF5B, 0xFF5D, 0x3008, 0x3009, 0x300A, 0x300B, 0x300C, 0x300D,
- 0x300E, 0x300F, 0x3010, 0x3011, 0xFF0B, 0xFF0D, 0x00B1, 0x00D7,
- 0x00F7, 0xFF1D, 0x2260, 0xFF1C, 0xFF1E, 0x2266, 0x2267, 0x221E,
- 0x2234, 0x2642, 0x2640, 0x00B0, 0x2032, 0x2033, 0x2103, 0xFFE5,
- 0xFF04, 0xFFE0, 0xFFE1, 0xFF05, 0xFF03, 0xFF06, 0xFF0A, 0xFF20,
- 0x00A7, 0x2606, 0x2605, 0x25CB, 0x25CF, 0x25CE, 0x25C7,
-};
-
unsigned short euc_to_utf8_A2[] = {
0x25C6, 0x25A1, 0x25A0, 0x25B3, 0x25B2, 0x25BD, 0x25BC,
0x203B, 0x3012, 0x2192, 0x2190, 0x2191, 0x2193, 0x3013, 0,
@@ -46,22 +29,6 @@ unsigned short euc_to_utf8_A2[] = {
0, 0, 0x212B, 0x2030, 0x266F, 0x266D, 0x266A, 0x2020,
0x2021, 0x00B6, 0, 0, 0, 0, 0x25EF,
};
-
-/* Microsoft UCS Mapping Compatible */
-unsigned short euc_to_utf8_A2_ms[] = {
- 0x25C6, 0x25A1, 0x25A0, 0x25B3, 0x25B2, 0x25BD, 0x25BC,
- 0x203B, 0x3012, 0x2192, 0x2190, 0x2191, 0x2193, 0x3013, 0,
- 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0x2208, 0x220B, 0x2286, 0x2287, 0x2282, 0x2283,
- 0x222A, 0x2229, 0, 0, 0, 0, 0, 0,
- 0, 0, 0x2227, 0x2228, 0xFFE2, 0x21D2, 0x21D4, 0x2200,
- 0x2203, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0x2220, 0x22A5, 0x2312, 0x2202,
- 0x2207, 0x2261, 0x2252, 0x226A, 0x226B, 0x221A, 0x223D, 0x221D,
- 0x2235, 0x222B, 0x222C, 0, 0, 0, 0, 0,
- 0, 0, 0x212B, 0x2030, 0x266F, 0x266D, 0x266A, 0x2020,
- 0x2021, 0x00B6, 0, 0, 0, 0, 0x25EF,
-};
unsigned short euc_to_utf8_A3[] = {
0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
@@ -1320,33 +1287,6 @@ unsigned short * euc_to_utf8_2bytes[] = {
0, euc_to_utf8_F9, euc_to_utf8_FA, euc_to_utf8_FB,
euc_to_utf8_FC, 0, 0,
};
-/* Microsoft UCS Mapping Compatible */
-unsigned short * euc_to_utf8_2bytes_ms[] = {
- euc_to_utf8_A1_ms,euc_to_utf8_A2_ms, euc_to_utf8_A3,
- euc_to_utf8_A4, euc_to_utf8_A5, euc_to_utf8_A6, euc_to_utf8_A7,
- euc_to_utf8_A8, euc_to_utf8_A9, euc_to_utf8_AA, euc_to_utf8_AB,
- euc_to_utf8_AC, euc_to_utf8_AD, euc_to_utf8_AE, euc_to_utf8_AF,
- euc_to_utf8_B0, euc_to_utf8_B1, euc_to_utf8_B2, euc_to_utf8_B3,
- euc_to_utf8_B4, euc_to_utf8_B5, euc_to_utf8_B6, euc_to_utf8_B7,
- euc_to_utf8_B8, euc_to_utf8_B9, euc_to_utf8_BA, euc_to_utf8_BB,
- euc_to_utf8_BC, euc_to_utf8_BD, euc_to_utf8_BE, euc_to_utf8_BF,
- euc_to_utf8_C0, euc_to_utf8_C1, euc_to_utf8_C2, euc_to_utf8_C3,
- euc_to_utf8_C4, euc_to_utf8_C5, euc_to_utf8_C6, euc_to_utf8_C7,
- euc_to_utf8_C8, euc_to_utf8_C9, euc_to_utf8_CA, euc_to_utf8_CB,
- euc_to_utf8_CC, euc_to_utf8_CD, euc_to_utf8_CE, euc_to_utf8_CF,
- euc_to_utf8_D0, euc_to_utf8_D1, euc_to_utf8_D2, euc_to_utf8_D3,
- euc_to_utf8_D4, euc_to_utf8_D5, euc_to_utf8_D6, euc_to_utf8_D7,
- euc_to_utf8_D8, euc_to_utf8_D9, euc_to_utf8_DA, euc_to_utf8_DB,
- euc_to_utf8_DC, euc_to_utf8_DD, euc_to_utf8_DE, euc_to_utf8_DF,
- euc_to_utf8_E0, euc_to_utf8_E1, euc_to_utf8_E2, euc_to_utf8_E3,
- euc_to_utf8_E4, euc_to_utf8_E5, euc_to_utf8_E6, euc_to_utf8_E7,
- euc_to_utf8_E8, euc_to_utf8_E9, euc_to_utf8_EA, euc_to_utf8_EB,
- euc_to_utf8_EC, euc_to_utf8_ED, euc_to_utf8_EE, euc_to_utf8_EF,
- euc_to_utf8_F0, euc_to_utf8_F1, euc_to_utf8_F2, euc_to_utf8_F3,
- euc_to_utf8_F4, euc_to_utf8_F5, 0, 0,
- 0, euc_to_utf8_F9, euc_to_utf8_FA, euc_to_utf8_FB,
- euc_to_utf8_FC, 0, 0,
-};
#endif /* UTF8_OUTPUT_ENABLE */
#ifdef UTF8_INPUT_ENABLE
diff --git a/ext/nkf/nkf.c b/ext/nkf/nkf.c
index 65442a130c..6517b3aba1 100644
--- a/ext/nkf/nkf.c
+++ b/ext/nkf/nkf.c
@@ -1,14 +1,11 @@
/*
* NKF Module for Ruby base on nkf 2.x
*
- * original nkf2.x is maintained at http://sourceforge.jp/projects/nkf/
- *
- * $Id$
+ * original nkf2.0 is maintained at http://sourceforge.jp/projects/nkf/
*
*/
-#define RUBY_NKF_REVISION "$Revision$"
-#define RUBY_NKF_VERSION NKF_VERSION " (" NKF_RELEASE_DATE ")"
+static char *RVersion = "2.0.4.1r1";
#include "ruby.h"
@@ -74,7 +71,6 @@ rb_nkf_putchar(c)
/* getchar and putchar will be replaced during inclusion */
#define PERL_XS 1
-#include "nkf-utf8/config.h"
#include "nkf-utf8/utf8tbl.c"
#include "nkf-utf8/nkf.c"
@@ -89,7 +85,12 @@ rb_nkf_kconv(obj, opt, src)
StringValue(opt);
opt_ptr = RSTRING(opt)->ptr;
opt_end = opt_ptr + RSTRING(opt)->len;
- options(opt_ptr);
+ for (; opt_ptr < opt_end; opt_ptr++) {
+ if (*opt_ptr != '-') {
+ continue;
+ }
+ options(opt_ptr);
+ }
incsize = INCSIZE;
@@ -269,7 +270,7 @@ Init_nkf()
VALUE mKconv = rb_define_module("NKF");
rb_define_module_function(mKconv, "nkf", rb_nkf_kconv, 2);
- rb_define_module_function(mKconv, "guess", rb_nkf_guess2, 1);
+ rb_define_module_function(mKconv, "guess", rb_nkf_guess1, 1);
rb_define_module_function(mKconv, "guess1", rb_nkf_guess1, 1);
rb_define_module_function(mKconv, "guess2", rb_nkf_guess2, 1);
@@ -284,9 +285,5 @@ Init_nkf()
rb_define_const(mKconv, "UTF16", INT2FIX(_UTF16));
rb_define_const(mKconv, "UTF32", INT2FIX(_UTF32));
rb_define_const(mKconv, "UNKNOWN", INT2FIX(_UNKNOWN));
- rb_define_const(mKconv, "VERSION", rb_str_new2(RUBY_NKF_VERSION));
- /* for debug */
- rb_define_const(mKconv, "NKF_VERSION", rb_str_new2(NKF_VERSION));
- rb_define_const(mKconv, "NKF_RELEASE_DATE", rb_str_new2(NKF_RELEASE_DATE));
- rb_define_const(mKconv, "REVISION", rb_str_new2(RUBY_NKF_REVISION));
+ rb_define_const(mKconv, "VERSION", rb_str_new2(RVersion));
}
diff --git a/ext/nkf/test.rb b/ext/nkf/test.rb
index b3406cbb6c..7a2390d649 100644
--- a/ext/nkf/test.rb
+++ b/ext/nkf/test.rb
@@ -1,9 +1,6 @@
#!/usr/local/bin/ruby
#
-# nkf test program for nkf-2
-#
-# $Id$
-#
+# nkf test program for nkf 1.7
# Shinji KONO <kono@ie.u-ryukyu.ac.jp>
# Sun Aug 18 12:25:40 JST 1996
# Sun Nov 8 00:16:06 JST 1998
@@ -72,24 +69,19 @@ def test(opt, input, expects)
print "\nINPUT:\n", input if $detail
print "\nEXPECT:\n", expects.to_s if $detail
result = nkf(opt, input)
- result.delete!(' ') if opt.include?('-m')
print "\nGOT:\n", result if $detail
expects.each do |e|
- e.delete!(' ') if opt.include?('-m')
if result == e then
puts "Ok"
return result
end
end
puts "Fail"
- puts result.unpack('H*').first
- puts expects.map{|x|x.unpack('H*').first}.join("\n\n")
end
-$example = Hash.new
-
+example = Hash.new
# Basic Conversion
print "\nBasic Conversion test\n\n";
@@ -98,173 +90,127 @@ print "\nBasic Conversion test\n\n";
# on perl4 and perl5 on literal quote. Of course we cannot use
# jperl.
-$example['jis'] = <<'eofeof'.unpack('u')[0]
+example['jis'] = <<'eofeof'.unpack('u')[0]
M1FER<W0@4W1A9V4@&R1"(3DQ(3%^2R%+?D]3&RA"(%-E8V]N9"!3=&%G92`;
M)$)0)TU:&RA"($AI<F%G86YA(!LD0B0B)"0D)B0H)"HD;R1R)',;*$(*2V%T
M86MA;F$@&R1")2(E)"4F)2@E*B5O)7(E<QLH0B!+:6=O=2`;)$(A)B%G(S`C
/029!)E@G(B=!*$`;*$(*
eofeof
-$example['sjis'] = <<'eofeof'.unpack('u')[0]
+example['sjis'] = <<'eofeof'.unpack('u')[0]
M1FER<W0@4W1A9V4@@5B)0(F>ED"6GIAR(%-E8V]N9"!3=&%G92"8I9=Y($AI
M<F%G86YA((*@@J*"I(*F@JB"[8+P@O$*2V%T86MA;F$@@T&#0X-%@T>#28./
>@Y*#DR!+:6=O=2"!18&'@D^"8(._@]:$081@A+X*
eofeof
-$example['euc'] = <<'eofeof'.unpack('u')[0]
+example['euc'] = <<'eofeof'.unpack('u')[0]
M1FER<W0@4W1A9V4@H;FQH;'^RZ'+_L_3(%-E8V]N9"!3=&%G92#0I\W:($AI
M<F%G86YA(*2BI*2DIJ2HI*JD[Z3RI/,*2V%T86MA;F$@I:*EI*6FI:BEJJ7O
>I?*E\R!+:6=O=2"AIJ'GH["CP:;!IMBGHJ?!J,`*
eofeof
-$example['utf8'] = <<'eofeof'.unpack('u')[0]
-M[[N_1FER<W0@4W1A9V4@XX"%Z9FBY;^<YK.5YKJ`Z(65(%-E8V]N9"!3=&%G
-M92#DN+SI@:4@2&ER86=A;F$@XX&"XX&$XX&&XX&(XX&*XX*/XX*2XX*3"DMA
-M=&%K86YA(.."HN."I.."IN."J.."JN.#K^.#LN.#LR!+:6=O=2#C@[OBB)[O
-1O)#OO*'.L<^)T)'0K^*5@@H`
-eofeof
-
-$example['utf8N'] = <<'eofeof'.unpack('u')[0]
+example['utf'] = <<'eofeof'.unpack('u')[0]
M1FER<W0@4W1A9V4@XX"%Z9FBY;^<YK.5YKJ`Z(65(%-E8V]N9"!3=&%G92#D
MN+SI@:4@2&ER86=A;F$@XX&"XX&$XX&&XX&(XX&*XX*/XX*2XX*3"DMA=&%K
M86YA(.."HN."I.."IN."J.."JN.#K^.#LN.#LR!+:6=O=2#C@[OBB)[OO)#O
.O*'.L<^)T)'0K^*5@@H`
eofeof
-$example['u16L'] = <<'eofeof'.unpack('u')[0]
-M__Y&`&D`<@!S`'0`(`!3`'0`80!G`&4`(``%,&*6W%_5;(!N58$@`%,`90!C
-M`&\`;@!D`"``4P!T`&$`9P!E`"``/$YED"``2`!I`'(`80!G`&$`;@!A`"``
-M0C!$,$8P2#!*,(\PDC"3,`H`2P!A`'0`80!K`&$`;@!A`"``HC"D,*8PJ#"J
-I,.\P\C#S,"``2P!I`&<`;P!U`"``^S`>(A#_(?^Q`\D#$00O!$(E"@``
-eofeof
-
-$example['u16L0'] = <<'eofeof'.unpack('u')[0]
-M1@!I`'(`<P!T`"``4P!T`&$`9P!E`"``!3!BEMQ?U6R`;E6!(`!3`&4`8P!O
-M`&X`9``@`%,`=`!A`&<`90`@`#Q.99`@`$@`:0!R`&$`9P!A`&X`80`@`$(P
-M1#!&,$@P2C"/,)(PDS`*`$L`80!T`&$`:P!A`&X`80`@`*(PI#"F,*@PJC#O
-G,/(P\S`@`$L`:0!G`&\`=0`@`/LP'B(0_R'_L0/)`Q$$+P1")0H`
-eofeof
-
-$example['u16B'] = <<'eofeof'.unpack('u')[0]
-M_O\`1@!I`'(`<P!T`"``4P!T`&$`9P!E`"`P!99B7]QLU6Z`@54`(`!3`&4`
-M8P!O`&X`9``@`%,`=`!A`&<`90`@3CR090`@`$@`:0!R`&$`9P!A`&X`80`@
-M,$(P1#!&,$@P2C"/,)(PDP`*`$L`80!T`&$`:P!A`&X`80`@,*(PI#"F,*@P
-IJC#O,/(P\P`@`$L`:0!G`&\`=0`@,/LB'O\0_R$#L0/)!!$$+R5"``H`
-eofeof
-
-$example['u16B0'] = <<'eofeof'.unpack('u')[0]
-M`$8`:0!R`',`=``@`%,`=`!A`&<`90`@,`668E_<;-5N@(%5`"``4P!E`&,`
-M;P!N`&0`(`!3`'0`80!G`&4`($X\D&4`(`!(`&D`<@!A`&<`80!N`&$`(#!"
-M,$0P1C!(,$HPCS"2,),`"@!+`&$`=`!A`&L`80!N`&$`(#"B,*0PIC"H,*HP
-G[S#R,/,`(`!+`&D`9P!O`'4`(##[(A[_$/\A`[$#R001!"\E0@`*
-eofeof
-$example['jis1'] = <<'eofeof'.unpack('u')[0]
+example['jis1'] = <<'eofeof'.unpack('u')[0]
M&R1";3%Q<$$L&RA""ALD0F4Z3F\;*$(*&R1"<FT;*$()&R1"/F5.3D]+&RA"
#"0D*
eofeof
-$example['sjis1'] = <<'eofeof'.unpack('u')[0]
+example['sjis1'] = <<'eofeof'.unpack('u')[0]
8YU#ID)%+"N-9E^T*Z>L)C^.7S)AJ"0D*
eofeof
-$example['euc1'] = <<'eofeof'.unpack('u')[0]
+example['euc1'] = <<'eofeof'.unpack('u')[0]
8[;'Q\,&L"N6ZSN\*\NT)ON7.SL_+"0D*
eofeof
-$example['utf1'] = <<'eofeof'.unpack('u')[0]
+example['utf1'] = <<'eofeof'.unpack('u')[0]
AZ+J%Z:N/Z8JM"N>VNNFZEPKIM(D)Y+B*Z:"8Y+J8"0D*
eofeof
-$example['jis2'] = <<'eofeof'.unpack('u')[0]
+example['jis2'] = <<'eofeof'.unpack('u')[0]
+&R1".EA&(QLH0@H`
eofeof
-$example['sjis2'] = <<'eofeof'.unpack('u')[0]
+example['sjis2'] = <<'eofeof'.unpack('u')[0]
%C=:3H0H`
eofeof
-$example['euc2'] = <<'eofeof'.unpack('u')[0]
+example['euc2'] = <<'eofeof'.unpack('u')[0]
%NMC&HPH`
eofeof
-$example['utf2'] = <<'eofeof'.unpack('u')[0]
+example['utf2'] = <<'eofeof'.unpack('u')[0]
'YI:.Z)>D"@``
eofeof
# From JIS
-print "JIS to JIS ... ";test("-j",$example['jis'],[$example['jis']])
-print "JIS to SJIS... ";test("-s",$example['jis'],[$example['sjis']])
-print "JIS to EUC ... ";test("-e",$example['jis'],[$example['euc']])
-print "JIS to UTF8... ";test("-w",$example['jis'],[$example['utf8N']])
-print "JIS to U16L... ";test("-w16L",$example['jis'],[$example['u16L']])
-print "JIS to U16B... ";test("-w16B",$example['jis'],[$example['u16B']])
+print "JIS to JIS ... ";test('-j',example['jis'],[example['jis']]);
+print "JIS to SJIS... ";test('-s',example['jis'],[example['sjis']]);
+print "JIS to EUC ... ";test('-e',example['jis'],[example['euc']]);
+print "JIS to UTF8... ";test('-w',example['jis'],[example['utf']]);
# From SJIS
-print "SJIS to JIS ... ";test("-j",$example['sjis'],[$example['jis']])
-print "SJIS to SJIS... ";test("-s",$example['sjis'],[$example['sjis']])
-print "SJIS to EUC ... ";test("-e",$example['sjis'],[$example['euc']])
-print "SJIS to UTF8... ";test("-w",$example['sjis'],[$example['utf8N']])
-print "SJIS to U16L... ";test("-w16L",$example['sjis'],[$example['u16L']])
-print "SJIS to U16B... ";test("-w16B",$example['sjis'],[$example['u16B']])
+print "SJIS to JIS ... ";test('-j',example['sjis'],[example['jis']]);
+print "SJIS to SJIS... ";test('-s',example['sjis'],[example['sjis']]);
+print "SJIS to EUC ... ";test('-e',example['sjis'],[example['euc']]);
+print "SJIS to UTF8... ";test('-w',example['sjis'],[example['utf']]);
# From EUC
-print "EUC to JIS ... ";test("-j",$example['euc'],[$example['jis']])
-print "EUC to SJIS... ";test("-s",$example['euc'],[$example['sjis']])
-print "EUC to EUC ... ";test("-e",$example['euc'],[$example['euc']])
-print "EUC to UTF8... ";test("-w",$example['euc'],[$example['utf8N']])
-print "EUC to U16L... ";test("-w16L",$example['euc'],[$example['u16L']])
-print "EUC to U16B... ";test("-w16B",$example['euc'],[$example['u16B']])
+print "EUC to JIS ... ";test('-j',example['euc'],[example['jis']]);
+print "EUC to SJIS... ";test('-s',example['euc'],[example['sjis']]);
+print "EUC to EUC ... ";test('-e',example['euc'],[example['euc']]);
+print "EUC to UTF8... ";test('-w',example['euc'],[example['utf']]);
# From UTF8
-print "UTF8 to JIS ... ";test("-j", $example['utf8N'],[$example['jis']])
-print "UTF8 to SJIS... ";test("-s", $example['utf8N'],[$example['sjis']])
-print "UTF8 to EUC ... ";test("-e", $example['utf8N'],[$example['euc']])
-print "UTF8 to UTF8N.. ";test("-w", $example['utf8N'],[$example['utf8N']])
-print "UTF8 to UTF8... ";test("-w8", $example['utf8N'],[$example['utf8']])
-print "UTF8 to UTF8N.. ";test("-w80", $example['utf8N'],[$example['utf8N']])
-print "UTF8 to U16L... ";test("-w16L", $example['utf8N'],[$example['u16L']])
-print "UTF8 to U16L0.. ";test("-w16L0", $example['utf8N'],[$example['u16L0']])
-print "UTF8 to U16B... ";test("-w16B", $example['utf8N'],[$example['u16B']])
-print "UTF8 to U16B0.. ";test("-w16B0", $example['utf8N'],[$example['u16B0']])
+print "UTF8 to JIS ... ";test('-j',example['utf'],[example['jis']]);
+print "UTF8 to SJIS... ";test('-s',example['utf'],[example['sjis']]);
+print "UTF8 to EUC ... ";test('-e',example['utf'],[example['euc']]);
+print "UTF8 to UTF8... ";test('-w',example['utf'],[example['utf']]);
# From JIS
-print "JIS to JIS ... ";test("-j",$example['jis1'],[$example['jis1']])
-print "JIS to SJIS... ";test("-s",$example['jis1'],[$example['sjis1']])
-print "JIS to EUC ... ";test("-e",$example['jis1'],[$example['euc1']])
-print "JIS to UTF8... ";test("-w",$example['jis1'],[$example['utf1']])
+print "JIS to JIS ... ";test('-j',example['jis1'],[example['jis1']]);
+print "JIS to SJIS... ";test('-s',example['jis1'],[example['sjis1']]);
+print "JIS to EUC ... ";test('-e',example['jis1'],[example['euc1']]);
+print "JIS to UTF8... ";test('-w',example['jis1'],[example['utf1']]);
# From SJIS
-print "SJIS to JIS ... ";test("-j",$example['sjis1'],[$example['jis1']])
-print "SJIS to SJIS... ";test("-s",$example['sjis1'],[$example['sjis1']])
-print "SJIS to EUC ... ";test("-e",$example['sjis1'],[$example['euc1']])
-print "SJIS to UTF8... ";test("-w",$example['sjis1'],[$example['utf1']])
+print "SJIS to JIS ... ";test('-j',example['sjis1'],[example['jis1']]);
+print "SJIS to SJIS... ";test('-s',example['sjis1'],[example['sjis1']]);
+print "SJIS to EUC ... ";test('-e',example['sjis1'],[example['euc1']]);
+print "SJIS to UTF8... ";test('-w',example['sjis1'],[example['utf1']]);
# From EUC
-print "EUC to JIS ... ";test("-j",$example['euc1'],[$example['jis1']])
-print "EUC to SJIS... ";test("-s",$example['euc1'],[$example['sjis1']])
-print "EUC to EUC ... ";test("-e",$example['euc1'],[$example['euc1']])
-print "EUC to UTF8... ";test("-w",$example['euc1'],[$example['utf1']])
+print "EUC to JIS ... ";test('-j',example['euc1'],[example['jis1']]);
+print "EUC to SJIS... ";test('-s',example['euc1'],[example['sjis1']]);
+print "EUC to EUC ... ";test('-e',example['euc1'],[example['euc1']]);
+print "EUC to UTF8... ";test('-w',example['euc1'],[example['utf1']]);
# From UTF8
-print "UTF8 to JIS ... ";test("-j",$example['utf1'],[$example['jis1']])
-print "UTF8 to SJIS... ";test("-s",$example['utf1'],[$example['sjis1']])
-print "UTF8 to EUC ... ";test("-e",$example['utf1'],[$example['euc1']])
-print "UTF8 to UTF8... ";test("-w",$example['utf1'],[$example['utf1']])
+print "UTF8 to JIS ... ";test('-j',example['utf1'],[example['jis1']]);
+print "UTF8 to SJIS... ";test('-s',example['utf1'],[example['sjis1']]);
+print "UTF8 to EUC ... ";test('-e',example['utf1'],[example['euc1']]);
+print "UTF8 to UTF8... ";test('-w',example['utf1'],[example['utf1']]);
# Ambigous Case
-$example['amb'] = <<'eofeof'.unpack('u')[0]
+example['amb'] = <<'eofeof'.unpack('u')[0]
MI<*PL:7"L+&EPK"QI<*PL:7"L+&EPK"QI<*PL:7"L+&EPK"QI<*PL:7"L+&E
MPK"QI<*PL:7"L+&EPK"QI<(*I<*PL:7"L+&EPK"QI<*PL:7"L+&EPK"QI<*P
ML:7"L+&EPK"QI<*PL:7"L+&EPK"QI<*PL:7"L+&EPK"QI<(*I<*PL:7"L+&E
@@ -274,7 +220,7 @@ MI<*PL:7"L+&EPK"QI<*PL:7"L+&EPK"QI<(*I<*PL:7"L+&EPK"QI<*PL:7"
ML+&EPK"QI<*PL:7"L+&EPK"QI<*PL:7"L+&EPK"QI<*PL:7"L+&EPK"QI<(*
eofeof
-$example['amb.euc'] = <<'eofeof'.unpack('u')[0]
+example['amb.euc'] = <<'eofeof'.unpack('u')[0]
M&R1")4(P,25",#$E0C`Q)4(P,25",#$E0C`Q)4(P,25",#$E0C`Q)4(P,25"
M,#$E0C`Q)4(P,25",#$E0C`Q)4(;*$(*&R1")4(P,25",#$E0C`Q)4(P,25"
M,#$E0C`Q)4(P,25",#$E0C`Q)4(P,25",#$E0C`Q)4(P,25",#$E0C`Q)4(;
@@ -285,7 +231,7 @@ M)4(;*$(*&R1")4(P,25",#$E0C`Q)4(P,25",#$E0C`Q)4(P,25",#$E0C`Q
>)4(P,25",#$E0C`Q)4(P,25",#$E0C`Q)4(;*$(*
eofeof
-$example['amb.sjis'] = <<'eofeof'.unpack('u')[0]
+example['amb.sjis'] = <<'eofeof'.unpack('u')[0]
M&RA))4(P,25",#$E0C`Q)4(P,25",#$E0C`Q)4(P,25",#$E0C`Q)4(P,25"
M,#$E0C`Q)4(P,25",#$E0C`Q)4(;*$(*&RA))4(P,25",#$E0C`Q)4(P,25"
M,#$E0C`Q)4(P,25",#$E0C`Q)4(P,25",#$E0C`Q)4(P,25",#$E0C`Q)4(;
@@ -297,78 +243,22 @@ M)4(;*$(*&RA))4(P,25",#$E0C`Q)4(P,25",#$E0C`Q)4(P,25",#$E0C`Q
eofeof
print "Ambiguous Case. ";
- test("-j",$example['amb'],[$example['amb.euc']])
+ test('-j',example['amb'],[example['amb.euc']]);
# Input assumption
print "SJIS Input assumption ";
- test("-jSx",$example['amb'],[$example['amb.sjis']])
+ test('-jSx',example['amb'],[example['amb.sjis']]);
# Broken JIS
print "Broken JIS ";
- $input = $example['jis'];
- $input.gsub!("\033",'')
- test("-Be",$input,[$example['euc']]);
+ $input = example['jis'];
+ $input.gsub("\033",'');
+ test('-Be',$input,[example['euc']]);
print "Broken JIS is safe on Normal JIS? ";
- $input = $example['jis'];
- test("-Be",$input,[$example['euc']]);
-
-# test_data/cp932
-
-$example['test_data/cp932'] = <<'eofeof'.unpack('u')[0]
-%^D`@_$L`
-eofeof
-
-$example['test_data/cp932.ans'] = <<'eofeof'.unpack('u')[0]
-%_/$@_.X`
-eofeof
-
-print "test_data/cp932 ";
- test("-eS",$example['test_data/cp932'],[$example['test_data/cp932.ans']])
-
-# test_data/cp932inv
-print "test_data/cp932inv ";
- test("-sE --cp932inv",$example['test_data/cp932.ans'],[$example['test_data/cp932']])
-
-# test_data/no-cp932inv
-
-$example['test_data/no-cp932inv.ans'] = <<'eofeof'.unpack('u')[0]
-%[N\@[NP`
-eofeof
-
-print "test_data/no-cp932inv ";
-test("-sE --no-cp932",$example['test_data/cp932.ans'],[$example['test_data/no-cp932inv.ans']])
-
-# test_data/irv
-
-# $example['test_data/irv'] = <<'eofeof'.unpack('u')[0]
-# %#B`/(!L`
-# eofeof
-#
-# $example['test_data/irv.ans'] = <<'eofeof'.unpack('u')[0]
-# %#B`/(!L`
-# eofeof
-#
-# print "test_data/irv ";
-# test("-wE",$example['test_data/irv'],[$example['test_data/irv.ans']])
-
-
-# UCS Mapping Test
-print "\n\nUCS Mapping Test\n";
-
-print "Shift_JIS to UTF-16\n";
-$example['ms_ucs_map_1_sjis'] = "\x81\x60\x81\x61\x81\x7C\x81\x91\x81\x92\x81\xCA";
-$example['ms_ucs_map_1_utf16'] = "\x30\x1C\x20\x16\x22\x12\x00\xA2\x00\xA3\x00\xAC";
-$example['ms_ucs_map_1_utf16_ms'] = "\xFF\x5E\x22\x25\xFF\x0D\xFF\xE0\xFF\xE1\xFF\xE2";
-
-print "Normal UCS Mapping : ";
- test("-w16B0 -S",$example['ms_ucs_map_1_sjis'],[$example['ms_ucs_map_1_utf16']])
-
-print "Microsoft UCS Mapping : ";
- test("-w16B0 -S --ms-ucs-map",$example['ms_ucs_map_1_sjis'],[$example['ms_ucs_map_1_utf16_ms']])
-
-print"\n";
+ $input = example['jis'];
+ test('-Be',$input,[example['euc']]);
# X0201 ²¾Ì¾
# X0201->X0208 conversion
@@ -377,7 +267,7 @@ print"\n";
print "\nX0201 test\n\n";
-$example['x0201.sjis'] = <<'eofeof'.unpack('u')[0]
+example['x0201.sjis'] = <<'eofeof'.unpack('u')[0]
MD5.*<(-*@TR#3H-0@U*#2X--@T^#48-3"I%3B7""8()A@F*"8X)D@F6"9H*!
M@H*"@X*$@H6"AH*'"I%3BTR-AH%)@9>!E(&0@9.!3X&5@9:!:8%J@7R!>X&!
M@6V!;H%O@7"!CPJ4O(IPMK>X/;FZMMZWWKC>N=ZZWH+&"I2\BG#*W\O?S-_-
@@ -385,7 +275,7 @@ MW\[?M]^QW@K*W\O?S`IH86YK86MU(,K?R]_,I`K*W\O?S-VA"I2\BG""S(SC
!"@!"
eofeof
-$example['x0201.euc'] = <<'eofeof'.unpack('u')[0]
+example['x0201.euc'] = <<'eofeof'.unpack('u')[0]
MP;2ST:6KI:VEKZ6QI;.EK*6NI;"ELJ6T"L&TL=&CP:/"H\.CQ*/%H\:CQZ/A
MH^*CXZ/DH^6CYJ/G"L&TM:VYYJ&JH?>A]*'PH?.AL*'UH?:ARJ'+H=VAW*'A
MH<ZASZ'0H=&A[PK(OK/1CK:.MXZX/8ZYCKJ.MH[>CK>.WHZXCMZ.N8[>CKJ.
@@ -394,7 +284,7 @@ MCLP*:&%N:V%K=2".RH[?CLN.WX[,CJ0*CLJ.WX[+CM^.S([=CJ$*R+ZST:3.
#N.4*
eofeof
-$example['x0201.utf'] = <<'eofeof'.unpack('u')[0]
+example['x0201.utf'] = <<'eofeof'.unpack('u')[0]
MY86HZ*>2XX*KXX*MXX*OXX*QXX*SXX*LXX*NXX*PXX*RXX*T"N6%J.B+L>^\
MH>^\HN^\H^^\I.^\I>^\IN^\I^^]@>^]@N^]@^^]A.^]A>^]AN^]APKEA:CH
MJ)CEC[?OO('OO*#OO(/OO(3OO(7OO+[OO(;OO(KOO(COO(GBB)+OO(OOO)WO
@@ -405,7 +295,7 @@ M"FAA;FMA:W4@[[Z*[[Z?[[Z+[[Z?[[Z,[[VD"N^^BN^^G^^^B^^^G^^^C.^^
2G>^]H0KEC8KHIY+C@:[EOHP*
eofeof
-$example['x0201.jis'] = <<'eofeof'.unpack('u')[0]
+example['x0201.jis'] = <<'eofeof'.unpack('u')[0]
M&R1"030S424K)2TE+R4Q)3,E+"4N)3`E,B4T&RA""ALD0D$T,5$C02-"(T,C
M1"-%(T8C1R-A(V(C8R-D(V4C9B-G&RA""ALD0D$T-2TY9B$J(7<A="%P(7,A
M,"%U(78A2B%+(5TA7"%A(4XA3R%0(5$A;QLH0@H;)$)(/C-1&RA)-C<X&RA"
@@ -414,7 +304,7 @@ M-U\Q7ALH0@H;*$E*7TM?3!LH0@IH86YK86MU(!LH24I?2U],)!LH0@H;*$E*
97TM?3%TA&RA""ALD0D@^,U$D3CAE&RA""@``
eofeof
-$example['x0201.sosi'] = <<'eofeof'.unpack('u')[0]
+example['x0201.sosi'] = <<'eofeof'.unpack('u')[0]
M&R1"030S424K)2TE+R4Q)3,E+"4N)3`E,B4T&RA*"ALD0D$T,5$C02-"(T,C
M1"-%(T8C1R-A(V(C8R-D(V4C9B-G&RA*"ALD0D$T-2TY9B$J(7<A="%P(7,A
M,"%U(78A2B%+(5TA7"%A(4XA3R%0(5$A;QLH2@H;)$)(/C-1&RA*#C8W.`\;
@@ -423,7 +313,7 @@ M3E\W7S%>#PH.2E]+7TP/&RA*"FAA;FMA:W4@#DI?2U],)`\;*$H*#DI?2U],
672$/&RA*"ALD0D@^,U$D3CAE&RA""@``
eofeof
-$example['x0201.x0208'] = <<'eofeof'.unpack('u')[0]
+example['x0201.x0208'] = <<'eofeof'.unpack('u')[0]
M&R1"030S424K)2TE+R4Q)3,E+"4N)3`E,B4T&RA""ALD0D$T,5$;*$)!0D-$
M149'86)C9&5F9PH;)$)!-#4M.68;*$(A0",D)5XF*B@I+2L]6UU[?1LD0B%O
M&RA""ALD0D@^,U$E*R4M)2\;*$(]&R1")3$E,R4L)2XE,"4R)30D2!LH0@H;
@@ -435,24 +325,24 @@ eofeof
# -X is necessary to allow X0201 in SJIS
# -Z convert X0208 alphabet to ASCII
print "X0201 conversion: SJIS ";
- test("-jXZ",$example['x0201.sjis'],[$example['x0201.x0208']])
+ test('-jXZ',example['x0201.sjis'],[example['x0201.x0208']]);
print "X0201 conversion: JIS ";
- test("-jZ",$example['x0201.jis'],[$example['x0201.x0208']])
+ test('-jZ',example['x0201.jis'],[example['x0201.x0208']]);
print "X0201 conversion:SI/SO ";
- test("-jZ",$example['x0201.sosi'],[$example['x0201.x0208']])
+ test('-jZ',example['x0201.sosi'],[example['x0201.x0208']]);
print "X0201 conversion: EUC ";
- test("-jZ",$example['x0201.euc'],[$example['x0201.x0208']])
+ test('-jZ',example['x0201.euc'],[example['x0201.x0208']]);
print "X0201 conversion: UTF8 ";
- test("-jZ",$example['x0201.utf'],[$example['x0201.x0208']])
+ test('-jZ',example['x0201.utf'],[example['x0201.x0208']]);
# -x means X0201 output
print "X0201 output: SJIS ";
- test("-xs",$example['x0201.euc'],[$example['x0201.sjis']])
+ test('-xs',example['x0201.euc'],[example['x0201.sjis']]);
print "X0201 output: JIS ";
- test("-xj",$example['x0201.sjis'],[$example['x0201.jis']])
+ test('-xj',example['x0201.sjis'],[example['x0201.jis']]);
print "X0201 output: EUC ";
- test("-xe",$example['x0201.jis'],[$example['x0201.euc']])
+ test('-xe',example['x0201.jis'],[example['x0201.euc']]);
print "X0201 output: UTF8 ";
- test("-xw",$example['x0201.jis'],[$example['x0201.utf']])
+ test('-xw',example['x0201.jis'],[example['x0201.utf']]);
# MIME decode
@@ -460,7 +350,7 @@ print "\nMIME test\n\n";
# MIME ISO-2022-JP
-$example['mime.iso2022'] = <<'eofeof'.unpack('u')[0]
+example['mime.iso2022'] = <<'eofeof'.unpack('u')[0]
M/3])4T\M,C`R,BU*4#]"/T=Y4D%.144W96E23TI566Q/4U9)1WEH2S\]"CT_
M:7-O+3(P,C(M2E`_0C]'>5)!3D5%-V5I4D]*55EL3U-624=Y:$L_/0H]/VES
M;RTR,#(R+4I0/U$_/3%")$(D1B11/3%"*$)?96YD/ST*&R1`)#TD)B0K)$H;
@@ -473,7 +363,7 @@ M96E23U!Y:S=D:'-O4V<]/3\]"CT_25-/+3(P,C(M2E`_0C]'>5)!3D5%-V5I
44D]*55EL3QM;2U-624=Y:$L_/0H_
eofeof
-$example['mime.ans.strict'] = <<'eofeof'.unpack('u')[0]
+example['mime.ans.strict'] = <<'eofeof'.unpack('u')[0]
M&R1"-$$[>B1.)48E.25(&RA""ALD0C1!.WHD3B5&)3DE2!LH0@H;)$(D1B11
M&RA"(&5N9`H;)$(D/20F)"LD2ALH0B`;)$(T03MZ)$X_*3MV&RA"96YD(&]F
M(&QI;F4*&R1"-$$[>B1./RD[=C1!.WHD3C\I.W8;*$(*0G)O:V5N(&-A<V4*
@@ -482,7 +372,7 @@ M/TE33RTR,`HR,BU*4#]"/T=Y4D%.144W96E23U!Y:S=D:'-O4V<]/3\]"CT_
L25-/+3(P,C(M2E`_0C]'>5)!3D5%-V5I4D]*55EL3QM;2U-624=Y:$L_/0H_
eofeof
-$example['mime.unbuf.strict'] = <<'eofeof'.unpack('u')[0]
+example['mime.unbuf.strict'] = <<'eofeof'.unpack('u')[0]
M&R1"-$$[>B1.)48E.25(&RA""ALD0C1!.WHD3B5&)3DE2!LH0@H;)$(D1B11
M&RA"(&5N9`H;)$(D/20F)"LD2ALH0B`;)$(T03MZ)$X_*3MV&RA"96YD(&]F
M(&QI;F4*&R1"-$$[>B1./RD[=C1!.WHD3C\I.W8;*$(*0G)O:V5N(&-A<V4*
@@ -491,7 +381,7 @@ M3D5%-V5I4D]0>6LW9&AS;U-G/3T_/0H;)$(T03MZ)$XE1ALH0EM+4U9)1WEH
$2S\]"F5I
eofeof
-$example['mime.ans'] = <<'eofeof'.unpack('u')[0]
+example['mime.ans'] = <<'eofeof'.unpack('u')[0]
M&R1"-$$[>B1.)48E.25(&RA""ALD0C1!.WHD3B5&)3DE2!LH0@H;)$(D1B11
M&RA"(&5N9`H;)$(D/20F)"LD2ALH0B`;)$(T03MZ)$X_*3MV&RA"96YD(&]F
M(&QI;F4*&R1"-$$[>B1./RD[=C1!.WHD3C\I.W8;*$(*0G)O:V5N(&-A<V4*
@@ -499,7 +389,7 @@ M&R1"-$$[>B1./RD;*$)H<V]39ST]/ST@&R1"-$$[>B1./RD[=ALH0@H;)$(T
603MZ)$XE1ALH0EM+4U9)1WEH2S\]"@`*
eofeof
-$example['mime.unbuf'] = <<'eofeof'.unpack('u')[0]
+example['mime.unbuf'] = <<'eofeof'.unpack('u')[0]
M&R1"-$$[>B1.)48E.25(&RA""ALD0C1!.WHD3B5&)3DE2!LH0@H;)$(D1B11
M&RA"(&5N9`H;)$(D/20F)"LD2ALH0B`;)$(T03MZ)$X_*3MV&RA"96YD(&]F
M(&QI;F4*&R1"-$$[>B1./RD[=C1!.WHD3C\I.W8;*$(*0G)O:V5N(&-A<V4*
@@ -507,13 +397,13 @@ M&R1"-$$[>B1./RD;*$)H<V]39ST]/ST@&R1"-$$[>B1./RD[=ALH0@H;)$(T
603MZ)$XE1ALH0EM+4U9)1WEH2S\]"@`*
eofeof
-$example['mime.base64'] = <<'eofeof'.unpack('u')[0]
+example['mime.base64'] = <<'eofeof'.unpack('u')[0]
M9W-M5"])3&YG<FU#>$I+-&=Q=4,S24LS9W%Q0E%:3TUI-39,,S0Q-&=S5T)1
M43!+9VUA1%9O3T@*9S)+1%1O3'=K8C)1;$E+;V=Q2T-X24MG9W5M0W%*3EEG
<<T=#>$E+9V=U;4,X64Q&9W)70S592VMG<6U""F=Q
eofeof
-$example['mime.base64.ans'] = <<'eofeof'.unpack('u')[0]
+example['mime.base64.ans'] = <<'eofeof'.unpack('u')[0]
M&R1")$M&?B1I)#LD1D0Z)"TD7B0Y)"PA(D5L-7XV83E9)$<A(ALH0@T*&R1"
M(T<E-R5G)4,E+R1R0C\_="0J)"0D1B0B)&LD*D4Y)$,D1B0B)&LD<R1')#<D
(9R0F)"L;*$(E
@@ -521,16 +411,16 @@ eofeof
# print "Next test is expected to Fail.\n";
print "MIME decode (strict) ";
- $tmp = test("-j -mS",$example['mime.iso2022'],[$example['mime.ans.strict']])
+ $tmp = test('-jmS',example['mime.iso2022'],[example['mime.ans.strict']]);
-$example['mime.ans.alt'] = <<'eofeof'.unpack('u')[0]
+example['mime.ans.alt'] = <<'eofeof'.unpack('u')[0]
M&R1"-$$[>B1.)48E.25(&RA""ALD0C1!.WHD3B5&)3DE2!LH0@H;)$(D1B11
M&RA"96YD"ALD0B0])"8D*R1*&RA"&R1"-$$[>B1./RD[=ALH0F5N9&]F;&EN
M90H;)$(T03MZ)$X_*3MV-$$[>B1./RD[=ALH0@I"<F]K96YC87-E"ALD0C1!
H.WHD3C\I.W8T03MZ)$X_*3MV&RA""ALD0C1!.WHD3B5&)3DE)!LH0@``
eofeof
-$example['mime.unbuf.alt'] = <<'eofeof'.unpack('u')[0]
+example['mime.unbuf.alt'] = <<'eofeof'.unpack('u')[0]
M&R1"-$$[>B1.)48E.25(&RA""ALD0C1!.WHD3B5&)3DE2!LH0@H;)$(D1B11
M&RA"96YD"ALD0B0])"8D*R1*&RA"&R1"-$$[>B1./RD[=ALH0F5N9&]F;&EN
M90H;)$(T03MZ)$X_*3MV-$$[>B1./RD[=ALH0@I"<F]K96YC87-E"ALD0C1!
@@ -538,25 +428,25 @@ H.WHD3C\I.W8T03MZ)$X_*3MV&RA""ALD0C1!.WHD3B5&)3DE)!LH0@``
eofeof
print "MIME decode (nonstrict)";
- $tmp = test("-j -mN",$example['mime.iso2022'],[$example['mime.ans'],$example['mime.ans.alt']])
+ $tmp = test('-jmN',example['mime.iso2022'],[example['mime.ans'],example['mime.ans.alt']]);
# open(OUT,">tmp1");print OUT pack('u',$tmp);close(OUT);
# unbuf mode implies more pessimistic decode
print "MIME decode (unbuf) ";
- $tmp = test("-j -mNu",$example['mime.iso2022'],[$example['mime.unbuf'],$example['mime.unbuf.alt']])
+ $tmp = test('-jmNu',example['mime.iso2022'],[example['mime.unbuf'],example['mime.unbuf.alt']]);
# open(OUT,">tmp2");print OUT pack('u',$tmp);close(OUT);
print "MIME decode (base64) ";
- test("-j -mB",$example['mime.base64'],[$example['mime.base64.ans']])
+ test('-jTmB',example['mime.base64'],[example['mime.base64.ans']]);
# MIME ISO-8859-1
-$example['mime.is8859'] = <<'eofeof'.unpack('u')[0]
+example['mime.is8859'] = <<'eofeof'.unpack('u')[0]
M/3])4T\M.#@U.2TQ/U$_*CU#-V%V83\_/2`*4&5E<B!4]G)N9W)E;@I,87-S
M92!(:6QL97+X92!0971E<G-E;B`@7"`B36EN(&MA97!H97-T(&AA<B!F86%E
M="!E="!F;V5L(2(*06%R:'5S(%5N:79E<G-I='DL($1%3DU!4DL@(%P@(DUI
<;B!KYG!H97-T(&AA<B!FY65T(&5T(&;X;"$B"@!K
eofeof
-$example['mime.is8859.ans'] = <<'eofeof'.unpack('u')[0]
+example['mime.is8859.ans'] = <<'eofeof'.unpack('u')[0]
M*L=A=F$_(`I0965R(%3V<FYG<F5N"DQA<W-E($AI;&QE<OAE(%!E=&5R<V5N
M("!<(")-:6X@:V%E<&AE<W0@:&%R(&9A865T(&5T(&9O96PA(@I!87)H=7,@
M56YI=F5R<VET>2P@1$5.34%22R`@7"`B36EN(&OF<&AE<W0@:&%R(&;E970@
@@ -566,7 +456,7 @@ eofeof
# Without -l, ISO-8859-1 was handled as X0201.
print "MIME ISO-8859-1 (Q) ";
- test("-ml",$example['mime.is8859'],[$example['mime.is8859.ans']])
+ test('-ml',example['mime.is8859'],[example['mime.is8859.ans']]);
# test for -f is not so simple.
@@ -574,32 +464,32 @@ print "\nBug Fixes\n\n";
# test_data/cr
-$example['test_data/cr'] = <<'eofeof'.unpack('u')[0]
+example['test_data/cr'] = <<'eofeof'.unpack('u')[0]
1I,:DN:3(#71E<W0-=&5S=`T`
eofeof
-$example['test_data/cr.ans'] = <<'eofeof'.unpack('u')[0]
+example['test_data/cr.ans'] = <<'eofeof'.unpack('u')[0]
7&R1")$8D.21(&RA""G1E<W0*=&5S=`H`
eofeof
print "test_data/cr ";
- test("-jd",$example['test_data/cr'],[$example['test_data/cr.ans']])
+ test('-jd',example['test_data/cr'],[example['test_data/cr.ans']]);
# test_data/fixed-qencode
-$example['test_data/fixed-qencode'] = <<'eofeof'.unpack('u')[0]
+example['test_data/fixed-qencode'] = <<'eofeof'.unpack('u')[0]
M("`@("`@("`],4(D0CYE/STS1#TQ0BA""B`@("`@("`@/3%")$(^93TS1CTS
'1#TQ0BA""@``
eofeof
-$example['test_data/fixed-qencode.ans'] = <<'eofeof'.unpack('u')[0]
+example['test_data/fixed-qencode.ans'] = <<'eofeof'.unpack('u')[0]
F("`@("`@("`;)$(^93\]&RA""B`@("`@("`@&R1"/F4_/1LH0@H`
eofeof
print "test_data/fixed-qencode ";
- test("-jmQ",$example['test_data/fixed-qencode'],[$example['test_data/fixed-qencode.ans']])
+ test('-jmQ',example['test_data/fixed-qencode'],[example['test_data/fixed-qencode.ans']]);
# test_data/long-fold-1
-$example['test_data/long-fold-1'] = <<'eofeof'.unpack('u')[0]
+example['test_data/long-fold-1'] = <<'eofeof'.unpack('u')[0]
MI,JDK*2DI,JDK*2DI,JDK*'!I*2DKJ3GI*:DK*2BI.JDWJ2WI,:AHJ2SI.RD
M\J2]I,ZDWJ3>I**DQ*2KI*:DR*&BI,FDIJ3BI-^DT*2HI*RD[Z3KI*2DMZ&B
MI,BDP:3EI*:DQZ3!I.>D\Z2NI.RDZZ2KI.*DMZ3SI,JDI*&C"J2SI+.DSR!#
@@ -607,7 +497,7 @@ M4B],1B"DSKG4H:,-"J2SI+.DSR!#4B"DSKG4H:,-I+.DLZ3/($Q&+T-2(*3.
9N=2AHPH-"J2SI+.DSR!,1B"DSKG4H:,*"@``
eofeof
-$example['test_data/long-fold-1.ans'] = <<'eofeof'.unpack('u')[0]
+example['test_data/long-fold-1.ans'] = <<'eofeof'.unpack('u')[0]
M&R1")$HD+"0D)$HD+"0D)$HD+"%!)"0D+B1G)"8D+"0B)&HD7B0W)$8A(B0S
M)&PD<B0])$XD7B1>)"(D1"0K&RA""ALD0B0F)$@A(B1))"8D8B1?)%`D*"0L
M)&\D:R0D)#<A(B1()$$D920F)$<D021G)',D+B1L)&LD*R1B)#<D<QLH0@H;
@@ -618,17 +508,17 @@ M4B`;)$(D3CE4(2,;*$(*"ALD0B0S)#,D3QLH0B!,1B`;)$(D3CE4(2,;*$(*
eofeof
print "test_data/long-fold-1 ";
- test("-jF60",$example['test_data/long-fold-1'],[$example['test_data/long-fold-1.ans']])
+ test('-jTF60',example['test_data/long-fold-1'],[example['test_data/long-fold-1.ans']]);
# test_data/long-fold
-$example['test_data/long-fold'] = <<'eofeof'.unpack('u')[0]
+example['test_data/long-fold'] = <<'eofeof'.unpack('u')[0]
MI,JDK*2DI,JDK*2DI,JDK*'!I*2DKJ3GI*:DK*2BI.JDWJ2WI,:AHJ2SI.RD
M\J2]I,ZDWJ3>I**DQ*2KI*:DR*&BI,FDIJ3BI-^DT*2HI*RD[Z3KI*2DMZ&B
MI,BDP:3EI*:DQZ3!I.>D\Z2NI.RDZZ2KI.*DMZ3SI,JDI*&C"J2SI+.DS\.[
'I*2YU*&C"@``
eofeof
-$example['test_data/long-fold.ans'] = <<'eofeof'.unpack('u')[0]
+example['test_data/long-fold.ans'] = <<'eofeof'.unpack('u')[0]
M&R1")$HD+"0D)$HD+"0D)$HD+"%!)"0D+B1G)"8D+"0B)&HD7B0W)$8A(B0S
M)&PD<B0])$XD7B1>)"(D1"0K&RA""ALD0B0F)$@A(B1))"8D8B1?)%`D*"0L
M)&\D:R0D)#<A(B1()$$D920F)$<D021G)',D+B1L)&LD*R1B)#<D<QLH0@H;
@@ -636,10 +526,10 @@ M)&\D:R0D)#<A(B1()$$D920F)$<D021G)',D+B1L)&LD*R1B)#<D<QLH0@H;
eofeof
print "test_data/long-fold ";
- test("-jf60",$example['test_data/long-fold'],[$example['test_data/long-fold.ans']])
+ test('-jTf60',example['test_data/long-fold'],[example['test_data/long-fold.ans']]);
# test_data/mime_out
-$example['test_data/mime_out'] = <<'eofeof'.unpack('u')[0]
+example['test_data/mime_out'] = <<'eofeof'.unpack('u')[0]
M"BTM+2T*4W5B:F5C=#H@86%A82!A86%A(&%A86$@86%A82!A86%A(&%A86$@
M86%A82!A86%A(&%A86$@86%A82!A86%A(&%A86$@86%A82!A86%A"BTM+2T*
M4W5B:F5C=#H@I**DI*2FI*BDJJ2KI*VDKZ2QI+.DM:2WI+FDNZ2]I+^DP:3$
@@ -648,78 +538,31 @@ M+2TM+0I3=6)J96-T.B!A86%A(&%A86$@86%A82!A86%A(&%A86$@86%A82!A
I86%A(*2BI*2DIJ2HI*H@86%A82!A86%A(&%A86$@86%A80HM+2TM"@H`
eofeof
-$example['test_data/mime_out.ans'] = <<'eofeof'.unpack('u')[0]
+example['test_data/mime_out.ans'] = <<'eofeof'.unpack('u')[0]
M"BTM+2T*4W5B:F5C=#H@86%A82!A86%A(&%A86$@86%A82!A86%A(&%A86$@
-M86%A82!A86%A(&%A86$@86%A80H@86%A82!A86%A(&%A86$@86%A82!A86%A
-M"BTM+2T*4W5B:F5C=#H@/3])4T\M,C`R,BU*4#]"/T=Y4D-*0TEK2D-1;4I#
-M9VM+:5%R2D,P:TQY47A*1$UK3E-1,T=Y:$,_/0H@/3])4T\M,C`R,BU*4#]"
-M/T=Y4D-*1&MK3WE1.4I$.&M14U)%2D59:U-#4DM*17-K5$-23DI%-&M4>5)3
-M2D95:U=#4F)'>6A#/ST*(#T_25-/+3(P,C(M2E`_0C]'>5)#2D8T:UAY4F=*
-M1T5K66E2:TI#46M::5%O2D=G8DM%23T_/0HM+2TM"E-U8FIE8W0Z(&%A86$@
-M86%A82!A86%A(&%A86$@86%A82!A86%A(&%A86$*(#T_25-/+3(P,C(M2E`_
-M0C]'>5)#2D-):TI#46U*0V=K2VAS;U%G/3T_/2!A86%A(&%A86$@86%A82!A
-086%A"B!A86%A"BTM+2T*"@``
+M86%A82!A86%A(&%A86$*(&%A86$@86%A82!A86%A(&%A86$@86%A80HM+2TM
+M"E-U8FIE8W0Z(#T_25-/+3(P,C(M2E`_0C]'>5)#2D-):TI#46U*0V=K2VE1
+M<DI#,&M,>5%X2D1-:TY343-*1&MK3WAS;U%G/3T_/2`*"3T_25-/+3(P,C(M
+M2E`_0C]'>5)#2D0P:U!Y4D)*15%K4FE224I%;VM3>5)-2D4P:U1I4E!*1DEK
+M5E-264=Y:$,_/2`*"3T_25-/+3(P,C(M2E`_0C]'>5)#2D9S:UAI4F9*1T%K
+M65-2:4I'46M*0U)M2D-G:V%"<V]19ST]/ST@"BTM+2T*4W5B:F5C=#H@86%A
+M82!A86%A(&%A86$@86%A82!A86%A(&%A86$@86%A82`]/TE33RTR,#(R+4I0
+M/T(_1WE20TI#26)+14D]/ST@"@D]/TE33RTR,#(R+4I0/T(_1WE20TI#46M*
+J:5%O2D-O8DM%23T_/2`@86%A80H@86%A82!A86%A(&%A86$*+2TM+0H*
eofeof
print "test_data/mime_out ";
- test("-jM",$example['test_data/mime_out'],[$example['test_data/mime_out.ans']])
-# test_data/mime_out2
-
-$example['test_data/mime_out2'] = <<'eofeof'.unpack('u')[0]
-M5&AI<R!M96UO(&1E<V-R:6)E<R!S:6UI;&%R('1E8VAN:7%U97,@=&\@86QL
-M;W<@=&AE(&5N8V]D:6YG(&]F(&YO;BU!4T-)22!T97AT(&EN('9A<FEO=7,@
-M<&]R=&EO;G,@;V8@82!21D,@.#(R(%LR72!M97-S86=E(&AE861E<BP@:6X@
-M82!M86YN97(@=VAI8V@@:7,@=6YL:6ME;'D@=&\@8V]N9G5S92!E>&ES=&EN
-M9R!M97-S86=E(&AA;F1L:6YG('-O9G1W87)E+@H*4W5B:F5C=#H@=&5S=#$@
-M=&5S=#(@@L2"MX+&@J<@=&5S=#,@@L2"MX+&@O$@=&5S=#0*"E-U8FIE8W0Z
-M('1E<W0Q("!T97-T,B""Q"""MR""QB""IR!T97-T,R`@@L2"MX+&@O$@('1E
-M<W0T"@I!4T-)22"3^I9[C.H@05-#24D@05-#24D@D_J6>XSJ()/ZEGN,ZB!!
-M4T-)22!!4T-)29/ZEGN,ZB!!4T-)20H*@J`@@J(@@J0@@J8@@J@@@JD@@JL@
-M@JT@@J\@@K$@@K,@@K4@@K<@@KD@@KL@@KT@@K\@@L(@@L0@@L8@@L@@@LD@
-8@LH@@LL@@LP*"@H*"@H*"@H*"@H*"@H*
-eofeof
-
-$example['test_data/mime_out2.ans'] = <<'eofeof'.unpack('u')[0]
-M5&AI<R!M96UO(&1E<V-R:6)E<R!S:6UI;&%R('1E8VAN:7%U97,@=&\@86QL
-M;W<@=&AE(&5N8V]D:6YG(&5N8V]D:6YG"B!O9B!N;VXM05-#24D@=&5X="!I
-M;B!V87)I;W5S('!O<G1I;VYS(&]F(&$@80H@4D9#(#@R,B!;,ET@;65S<V%G
-M92!H96%D97(L(&EN(&$@;6%N;F5R('=H:6-H(&ES('5N;&EK96QY('5N;&EK
-M96QY"B!T;R!C;VYF=7-E(&5X:7-T:6YG(&UE<W-A9V4@:&%N9&QI;F<@<V]F
-M='=A<F4N"@I3=6)J96-T.B!T97-T,2!T97-T,B`]/TE33RTR,#(R+4I0/T(_
-M1WE20TI%66M/4U))2D-K8DM%23T_/2!T97-T,PH@/3])4T\M,C`R,BU*4#]"
-M/T=Y4D-*15EK3U-224I(36)+14D]/ST@=&5S=#0*"E-U8FIE8W0Z('1E<W0Q
-M("!T97-T,B`]/TE33RTR,#(R+4I0/T(_1WE20TI%66)+14EG1WE20TI$:V)+
-M14EG1WE20TI%9V)+14D]/ST*(#T_25-/+3(P,C(M2E`_0C]'>5)#1WEH0TE"
-M<VM1:5%P1WEH0S\]('1E<W0S(`H@/3])4T\M,C`R,BU*4#]"/T=Y4D-*15EK
-M3U-224I(36)+14D]/ST@('1E<W0T"@I!4T-)22`]/TE33RTR,#(R+4I0/T(_
-M1WE20U)N>$Q81&AS1WEH0S\]($%30TE)($%30TE)"B`]/TE33RTR,#(R+4I0
-M/T(_1WE20U)N>$Q81&AS1WEH0TE"<VM1:UHX4S%W-&)"<V]19ST]/ST@05-#
-M24D*(#T_25-/+3(P,C(M2E`_0C]15DY$4U5K8DI%2D=F171C3T=W8DM%23T_
-M/2!!4T-)20H*/3])4T\M,C`R,BU*4#]"/T=Y4D-*0TEB2T5)9T=Y4D-*0U%B
-M2T5)9T=Y4D-*0UEB2T5)9T=Y4D-*0V=B2T5)/3\]"B`]/TE33RTR,#(R+4I0
-M/T(_24)S:U%I47%'>6A#24)S:U%I47)'>6A#24)S:U%I471'>6A#24)S:U%I
-M479'>6A#/ST*(#T_25-/+3(P,C(M2E`_0C])0G-K46E1>$=Y:$-)0G-K46E1
-M>D=Y:$-)0G-K46E1,4=Y:$-)0G-K46E1,T=Y:$,_/0H@/3])4T\M,C`R,BU*
-M4#]"/TE"<VM1:5$U1WEH0TE"<VM1:5$W1WEH0TE"<VM1:5$Y1WEH0TE"<VM1
-M:5$O1WEH0S\]"B`]/TE33RTR,#(R+4I0/T(_24)S:U%I4D)'>6A#24)S:U%I
-M4D5'>6A#24)S:U%I4D='>6A#24)S:U%I4DE'>6A#/ST*(#T_25-/+3(P,C(M
-M2E`_0C])0G-K46E22T=Y:$-)0G-K46E23$=Y:$-)0G-K46E234=Y:$-)0G-K
-M46E23D=Y:$,_/0H@/3])4T\M,C`R,BU*4#]"/TE"<VM1:5)/1WEH0S\]"@H*
--"@H*"@H*"@H*"@H*"@``
-eofeof
-
-print "test_data/mime_out2 ";
- test("-jM",$example['test_data/mime_out2'],[$example['test_data/mime_out2.ans']])
+ test('-jM',example['test_data/mime_out'],[example['test_data/mime_out.ans']]);
# test_data/multi-line
-$example['test_data/multi-line'] = <<'eofeof'.unpack('u')[0]
+example['test_data/multi-line'] = <<'eofeof'.unpack('u')[0]
MI,JDK*2DI,JDK*2DI,JDK*'!I*2DKJ3GI*:DK*2BI.JDWJ2WI,:AH@"DLZ3L
MI/*DO:3.I-ZDWJ2BI,2DJZ2FI,BAHJ3)I*:DXJ3?I-"DJ*2LI.^DZZ2DI+>A
MHJ3(I,&DY:2FI,>DP:3GI/.DKJ3LI.NDJZ3BI+>D\Z3*I*2AHPJDLZ2SI,_#
8NZ2DN=2AHP`*I+.DLZ3/P[NDI+G4H:,*
eofeof
-$example['test_data/multi-line.ans'] = <<'eofeof'.unpack('u')[0]
+example['test_data/multi-line.ans'] = <<'eofeof'.unpack('u')[0]
MI,JDK*2DI,JDK*2DI,JDK*'!I*2DKJ3GI*:DK*2BI.JDWJ2WI,:AH@"DLZ3L
MI/*DO:3.I-ZDWJ2BI,2DJZ2FI,BAHJ3)I*:DXJ3?I-"DJ*2LI.^DZZ2DI+>A
MHJ3(I,&DY:2FI,>DP:3GI/.DKJ3LI.NDJZ3BI+>D\Z3*I*2AHPJDLZ2SI,_#
@@ -727,73 +570,73 @@ MHJ3(I,&DY:2FI,>DP:3GI/.DKJ3LI.NDJZ3BI+>D\Z3*I*2AHPJDLZ2SI,_#
eofeof
print "test_data/multi-line ";
- test("-e",$example['test_data/multi-line'],[$example['test_data/multi-line.ans']])
+ test('-e',example['test_data/multi-line'],[example['test_data/multi-line.ans']]);
# test_data/nkf-19-bug-1
-$example['test_data/nkf-19-bug-1'] = <<'eofeof'.unpack('u')[0]
+example['test_data/nkf-19-bug-1'] = <<'eofeof'.unpack('u')[0]
,I*:DJZ2D"KK8QJ,*
eofeof
-$example['test_data/nkf-19-bug-1.ans'] = <<'eofeof'.unpack('u')[0]
+example['test_data/nkf-19-bug-1.ans'] = <<'eofeof'.unpack('u')[0]
8&R1")"8D*R0D&RA""ALD0CI81B,;*$(*
eofeof
print "test_data/nkf-19-bug-1 ";
- test("-Ej",$example['test_data/nkf-19-bug-1'],[$example['test_data/nkf-19-bug-1.ans']])
+ test('-Ej',example['test_data/nkf-19-bug-1'],[example['test_data/nkf-19-bug-1.ans']]);
# test_data/nkf-19-bug-2
-$example['test_data/nkf-19-bug-2'] = <<'eofeof'.unpack('u')[0]
+example['test_data/nkf-19-bug-2'] = <<'eofeof'.unpack('u')[0]
%I-NDL@H`
eofeof
-$example['test_data/nkf-19-bug-2.ans'] = <<'eofeof'.unpack('u')[0]
+example['test_data/nkf-19-bug-2.ans'] = <<'eofeof'.unpack('u')[0]
%I-NDL@H`
eofeof
print "test_data/nkf-19-bug-2 ";
- test("-Ee",$example['test_data/nkf-19-bug-2'],[$example['test_data/nkf-19-bug-2.ans']])
+ test('-Ee',example['test_data/nkf-19-bug-2'],[example['test_data/nkf-19-bug-2.ans']]);
# test_data/nkf-19-bug-3
-$example['test_data/nkf-19-bug-3'] = <<'eofeof'.unpack('u')[0]
+example['test_data/nkf-19-bug-3'] = <<'eofeof'.unpack('u')[0]
8[;'Q\,&L"N6ZSN\*\NT)ON7.SL_+"0D*
eofeof
-$example['test_data/nkf-19-bug-3.ans'] = <<'eofeof'.unpack('u')[0]
+example['test_data/nkf-19-bug-3.ans'] = <<'eofeof'.unpack('u')[0]
8[;'Q\,&L"N6ZSN\*\NT)ON7.SL_+"0D*
eofeof
print "test_data/nkf-19-bug-3 ";
- test("-e",$example['test_data/nkf-19-bug-3'],[$example['test_data/nkf-19-bug-3.ans']])
+ test('-e',example['test_data/nkf-19-bug-3'],[example['test_data/nkf-19-bug-3.ans']]);
# test_data/non-strict-mime
-$example['test_data/non-strict-mime'] = <<'eofeof'.unpack('u')[0]
+example['test_data/non-strict-mime'] = <<'eofeof'.unpack('u')[0]
M/3])4T\M,C`R,BU*4#]"/PIG<U-#;V]+.6=R-D-O;TQ%9W1Y0W0T1D-$46].
M0V\V16=S,D]N;T999S1Y1%=)3$IG=4-0:UD*2W!G<FU#>$E+:6=R,D-V;TMI
,9W-30V]O3&,*/ST*
eofeof
-$example['test_data/non-strict-mime.ans'] = <<'eofeof'.unpack('u')[0]
+example['test_data/non-strict-mime.ans'] = <<'eofeof'.unpack('u')[0]
M&R1")$8D)"0_)$`D)"1&)%XD.2$C&RA"#0H-"ALD0CMD)$\[?B$Y)6PE.21+
<)&(]<20K)#LD1B0D)#\D0"0D)$8D)"1>&RA""@``
eofeof
print "test_data/non-strict-mime ";
- test("-jmN",$example['test_data/non-strict-mime'],[$example['test_data/non-strict-mime.ans']])
+ test('-jTmN',example['test_data/non-strict-mime'],[example['test_data/non-strict-mime.ans']]);
# test_data/q-encode-softrap
-$example['test_data/q-encode-softrap'] = <<'eofeof'.unpack('u')[0]
+example['test_data/q-encode-softrap'] = <<'eofeof'.unpack('u')[0]
H/3%")$(T03MZ)3T*,R$\)4DD3CTQ0BA""CTQ0B1"2E$T.3TQ0BA""@``
eofeof
-$example['test_data/q-encode-softrap.ans'] = <<'eofeof'.unpack('u')[0]
+example['test_data/q-encode-softrap.ans'] = <<'eofeof'.unpack('u')[0]
>&R1"-$$[>B4S(3PE221.&RA""ALD0DI1-#D;*$(*
eofeof
print "test_data/q-encode-softrap ";
- test("-jmQ",$example['test_data/q-encode-softrap'],[$example['test_data/q-encode-softrap.ans']])
+ test('-jTmQ',example['test_data/q-encode-softrap'],[example['test_data/q-encode-softrap.ans']]);
# test_data/rot13
-$example['test_data/rot13'] = <<'eofeof'.unpack('u')[0]
+example['test_data/rot13'] = <<'eofeof'.unpack('u')[0]
MI+.D\Z3+I,&DSZ&BS:W"]*3(I*2DI*3>I+FAHPH*;FMF('9E<BXQ+CDR(*3R
MS?C-T:2UI+NDQJ2DI+^DP*2DI,:DI*3>I+FDK*&B05-#24D@I,O"T*2WI,8@
M4D]4,3,@I*P*P+6DMZ2OQK"DI*3&I*2DRJ2DI.BDIJ3'H:*PRK*\I,ZDZ*2F
@@ -801,7 +644,7 @@ MI,O*T;2YI+6D[*3>I+ND\Z&C"@HE(&5C:&\@)VAO9V4G('P@;FMF("UR"FAO
#9V4*
eofeof
-$example['test_data/rot13.ans'] = <<'eofeof'.unpack('u')[0]
+example['test_data/rot13.ans'] = <<'eofeof'.unpack('u')[0]
M&R1"4V)31%-Z4W!3?E!1?%QQ15-W4U-34U,O4VA04ALH0@H*87AS(&ER92XQ
M+CDR(!LD0E-#?$E\(E-D4VI3=5-34VY3;U-34W534U,O4VA36U!1&RA"3D90
M5E8@&R1"4WIQ(5-F4W4;*$(@14)',3,@&R1"4UL;*$(*&R1";V139E->=5]3
@@ -810,55 +653,54 @@ A&RA""@HE(')P=6(@)W5B='(G('P@87AS("UE"G5B='(*
eofeof
print "test_data/rot13 ";
- test("-jr",$example['test_data/rot13'],[$example['test_data/rot13.ans']])
+ test('-jr',example['test_data/rot13'],[example['test_data/rot13.ans']]);
# test_data/slash
-$example['test_data/slash'] = <<'eofeof'.unpack('u')[0]
+example['test_data/slash'] = <<'eofeof'.unpack('u')[0]
7("`]/U8\5"U5.5=%2RTK.U<U32LE+PH`
eofeof
-$example['test_data/slash.ans'] = <<'eofeof'.unpack('u')[0]
+example['test_data/slash.ans'] = <<'eofeof'.unpack('u')[0]
7("`]/U8\5"U5.5=%2RTK.U<U32LE+PH`
eofeof
print "test_data/slash ";
- test(" ",$example['test_data/slash'],[$example['test_data/slash.ans']])
+ test(' ',example['test_data/slash'],[example['test_data/slash.ans']]);
# test_data/z1space-0
-$example['test_data/z1space-0'] = <<'eofeof'.unpack('u')[0]
+example['test_data/z1space-0'] = <<'eofeof'.unpack('u')[0]
"H:$`
eofeof
-$example['test_data/z1space-0.ans'] = <<'eofeof'.unpack('u')[0]
+example['test_data/z1space-0.ans'] = <<'eofeof'.unpack('u')[0]
"H:$`
eofeof
print "test_data/z1space-0 ";
- test("-e -Z",$example['test_data/z1space-0'],[$example['test_data/z1space-0.ans']])
+ test('-e -Z',example['test_data/z1space-0'],[example['test_data/z1space-0.ans']]);
# test_data/z1space-1
-$example['test_data/z1space-1'] = <<'eofeof'.unpack('u')[0]
+example['test_data/z1space-1'] = <<'eofeof'.unpack('u')[0]
"H:$`
eofeof
-$example['test_data/z1space-1.ans'] = <<'eofeof'.unpack('u')[0]
+example['test_data/z1space-1.ans'] = <<'eofeof'.unpack('u')[0]
!(```
eofeof
print "test_data/z1space-1 ";
- test("-e -Z1",$example['test_data/z1space-1'],[$example['test_data/z1space-1.ans']])
+ test('-e -Z1',example['test_data/z1space-1'],[example['test_data/z1space-1.ans']]);
# test_data/z1space-2
-$example['test_data/z1space-2'] = <<'eofeof'.unpack('u')[0]
+example['test_data/z1space-2'] = <<'eofeof'.unpack('u')[0]
"H:$`
eofeof
-$example['test_data/z1space-2.ans'] = <<'eofeof'.unpack('u')[0]
+example['test_data/z1space-2.ans'] = <<'eofeof'.unpack('u')[0]
"("``
eofeof
print "test_data/z1space-2 ";
- test("-e -Z2",$example['test_data/z1space-2'],[$example['test_data/z1space-2.ans']])
-
+ test('-e -Z2',example['test_data/z1space-2'],[example['test_data/z1space-2.ans']]);
# end
diff --git a/ext/openssl/extconf.rb b/ext/openssl/extconf.rb
index 2ced7f62ce..d587116c82 100644
--- a/ext/openssl/extconf.rb
+++ b/ext/openssl/extconf.rb
@@ -89,7 +89,6 @@ have_func("X509_CRL_set_version")
have_func("X509_CRL_sort")
have_func("X509_STORE_get_ex_data")
have_func("X509_STORE_set_ex_data")
-have_func("OPENSSL_cleanse")
if try_compile("#define FOO(a, ...) foo(a, ##__VA_ARGS__)\n int x(){FOO(1);FOO(1,2);FOO(1,2,3);}\n")
$defs.push("-DHAVE_VA_ARGS_MACRO")
end
@@ -114,5 +113,33 @@ have_struct_member("EVP_CIPHER_CTX", "engine", "openssl/evp.h")
have_struct_member("X509_ATTRIBUTE", "single", "openssl/x509.h")
message "=== Checking done. ===\n"
+$distcleanfiles << "GNUmakefile" << "dep"
create_makefile("openssl")
+if /gcc/ =~ CONFIG["CC"]
+ File.open("GNUmakefile", "w") {|f|
+ f.print <<EOD
+include Makefile
+
+SRCS = $(OBJS:.o=.c)
+
+test-link: $(OBJS)
+ $(CC) $(DLDFLAGS) #{OUTFLAG}.testlink $(OBJS) $(LIBPATH) $(LIBS) $(LOCAL_LIBS)
+ @$(RM) .testlink
+ @echo "Done."
+
+dep:
+ $(CC) $(CFLAGS) $(CPPFLAGS) -c $(SRCS) -MM | \\
+ $(RUBY) -p -e 'BEGIN{S = []' \\
+ -e 'while !ARGV.empty? and /^(\\w+)=(.*)/ =~ ARGV[0]' \\
+ -e 'S << [/\#{Regexp.quote($$2)}\\//, "$$(\#{$$1})/"]' \\
+ -e 'ARGV.shift' \\
+ -e 'end' \\
+ -e '}' -e 'S.each(&method(:gsub!))' -- \\
+ 'topdir=$(topdir)' 'srcdir=$(srcdir)' 'hdrdir=$(hdrdir)' \\
+ > dep
+
+include dep
+EOD
+ }
+end
message "Done.\n"
diff --git a/ext/openssl/lib/net/https.rb b/ext/openssl/lib/net/https.rb
new file mode 100644
index 0000000000..fb7f53c555
--- /dev/null
+++ b/ext/openssl/lib/net/https.rb
@@ -0,0 +1,188 @@
+=begin
+= $RCSfile$ -- SSL/TLS enhancement for Net::HTTP.
+
+= Info
+ 'OpenSSL for Ruby 2' project
+ Copyright (C) 2001 GOTOU Yuuzou <gotoyuzo@notwork.org>
+ All rights reserved.
+
+= Licence
+ This program is licenced under the same licence as Ruby.
+ (See the file 'LICENCE'.)
+
+= Requirements
+ This program requires Net 1.2.0 or higher version.
+ You can get it from RAA or Ruby's CVS repository.
+
+= Version
+ $Id$
+
+ 2001/11/06: Contiributed to Ruby/OpenSSL project.
+
+== class Net::HTTP
+
+== Example
+
+Simple HTTP client is here:
+
+ require 'net/http'
+ host, port, path = "localhost", 80, "/"
+ if %r!http://(.*?)(?::(\d+))?(/.*)! =~ ARGV[0]
+ host = $1
+ port = $2.to_i if $2
+ path = $3
+ end
+ h = Net::HTTP.new(host, port)
+ h.get2(path){ |resp| print resp.body }
+
+It can be replaced by follow one:
+
+ require 'net/https'
+ host, port, path = "localhost", 80, "/"
+ if %r!(https?)://(.*?)(?::(\d+))?(/.*)! =~ ARGV[0]
+ scheme = $1
+ host = $2
+ port = $3 ? $3.to_i : ((scheme == "http") ? 80 : 443)
+ path = $4
+ end
+ h = Net::HTTP.new(host, port)
+ h.use_ssl = true if scheme == "https" # enable SSL/TLS
+ h.get2(path){ |resp| print resp.body }
+
+=== Instance Methods
+
+: use_ssl
+ returns ture if use SSL/TLS with HTTP.
+
+: use_ssl=((|true_or_false|))
+ sets use_ssl.
+
+: peer_cert
+ return the X.509 certificates the server presented.
+
+: key=((|key|))
+ Sets an OpenSSL::PKey::RSA or OpenSSL::PKey::DSA object.
+ (This method is appeared in Michal Rokos's OpenSSL extention.)
+
+: key_file=((|path|))
+ Sets a private key file to use in PEM format.
+
+: cert=((|cert|))
+ Sets an OpenSSL::X509::Certificate object as client certificate.
+ (This method is appeared in Michal Rokos's OpenSSL extention.)
+
+: cert_file=((|path|))
+ Sets pathname of a X.509 certification file in PEM format.
+
+: ca_file=((|path|))
+ Sets path of a CA certification file in PEM format.
+ The file can contrain several CA certificats.
+
+: ca_path=((|path|))
+ Sets path of a CA certification directory containing certifications
+ in PEM format.
+
+: verify_mode=((|mode|))
+ Sets the flags for server the certification verification at
+ begining of SSL/TLS session.
+ OpenSSL::SSL::VERIFY_NONE or OpenSSL::SSL::VERIFY_PEER is acceptable.
+
+: verify_callback=((|proc|))
+ Sets the verify callback for the server certification verification.
+
+: verify_depth=((|num|))
+ Sets the maximum depth for the certificate chain verification.
+
+: cert_store=((|store|))
+ Sets the X509::Store to verify peer certificate.
+
+=end
+
+require 'net/protocols'
+require 'net/http'
+
+module Net
+ class HTTP
+ class Conn < HTTPRequest
+ REQUEST_HAS_BODY=false
+ RESPONSE_HAS_BODY=false
+ METHOD="connect"
+
+ def initialize
+ super nil, nil
+ end
+
+ def exec( sock, addr, port, ver )
+ @socket = sock
+ request(addr, port, ver)
+ end
+
+ def request( addr, port, ver )
+ @socket.writeline sprintf('CONNECT %s:%s HTTP/%s', addr, port, ver)
+ @socket.writeline ''
+ end
+ end
+
+ module ProxyMod
+ def edit_path( path )
+ if use_ssl
+ 'https://' + addr_port + path
+ else
+ 'http://' + addr_port + path
+ end
+ end
+ end
+
+ def self.socket_type
+ SSLIO
+ end
+
+ attr_reader :use_ssl
+ attr_writer :key, :cert
+ attr_writer :ca_file, :ca_path
+ attr_writer :verify_mode, :verify_callback, :verify_depth
+ attr_writer :cert_store, :timeout
+ attr_reader :peer_cert
+
+ alias :default_initialize :initialize
+
+ def initialize(*args)
+ default_initialize(*args)
+ @key = @cert = @ca_file = @ca_path = @verify_mode =
+ @verify_callback = @verify_depth = @timeout = @cert_store = nil
+ @already_connected = false
+ end
+
+ def use_ssl=(flag)
+ if @already_connected && !@use_ssl
+ raise ProtocolError, "connection is alrady set up"
+ end
+ @use_ssl = flag
+ end
+
+ def on_connect
+ if use_ssl
+ if proxy?
+ Conn.new.exec(@socket, @address, @port, "1.0")
+ resp = HTTPResponse.read_new(@socket)
+ if resp.code != '200'
+ raise resp.message
+ end
+ end
+ @socket.key = @key if @key
+ @socket.cert = @cert if @cert
+ @socket.ca_file = @ca_file
+ @socket.ca_path = @ca_path
+ @socket.verify_mode = @verify_mode
+ @socket.verify_callback = @verify_callback
+ @socket.verify_depth = @verify_depth
+ @socket.timeout = @timeout
+ @socket.cert_store = @cert_store
+ @socket.ssl_connect
+ @peer_cert = @socket.peer_cert
+ end
+ @already_connected = true
+ end
+
+ end
+end
diff --git a/ext/openssl/lib/net/protocols.rb b/ext/openssl/lib/net/protocols.rb
new file mode 100644
index 0000000000..073d4f3027
--- /dev/null
+++ b/ext/openssl/lib/net/protocols.rb
@@ -0,0 +1,56 @@
+=begin
+= $RCSfile$ -- SSL/TLS enhancement for Net.
+
+= Info
+ 'OpenSSL for Ruby 2' project
+ Copyright (C) 2001 GOTOU YUUZOU <gotoyuzo@notwork.org>
+ All rights reserved.
+
+= Licence
+ This program is licenced under the same licence as Ruby.
+ (See the file 'LICENCE'.)
+
+= Requirements
+ This program requires Net 1.2.0 or higher version.
+ You can get it from RAA or Ruby's CVS repository.
+
+= Version
+ $Id$
+
+ 2001/11/06: Contiributed to Ruby/OpenSSL project.
+=end
+
+require 'net/protocol'
+require 'forwardable'
+require 'openssl'
+
+module Net
+ class SSLIO < InternetMessageIO
+ extend Forwardable
+
+ def_delegators(:@ssl_context,
+ :key=, :cert=, :key_file=, :cert_file=,
+ :ca_file=, :ca_path=,
+ :verify_mode=, :verify_callback=, :verify_depth=,
+ :timeout=, :cert_store=)
+
+ def initialize(addr, port, otime = nil, rtime = nil, dout = nil)
+ super
+ @ssl_context = OpenSSL::SSL::SSLContext.new()
+ end
+
+ def ssl_connect()
+ unless @ssl_context.verify_mode
+ warn "warning: peer certificate won't be verified in this SSL session."
+ @ssl_context.verify_mode = OpenSSL::SSL::VERIFY_NONE
+ end
+ @socket = OpenSSL::SSL::SSLSocket.new(@socket, @ssl_context)
+ @socket.sync_close = true
+ @socket.connect
+ end
+
+ def peer_cert
+ @socket.peer_cert
+ end
+ end
+end
diff --git a/ext/openssl/lib/net/telnets.rb b/ext/openssl/lib/net/telnets.rb
index a872f41e6a..c7ecbd717a 100644
--- a/ext/openssl/lib/net/telnets.rb
+++ b/ext/openssl/lib/net/telnets.rb
@@ -124,7 +124,9 @@ module Net
elsif SB[0] == $1[0] # respond to "IAC SB xxx IAC SE"
if OPT_STARTTLS[0] == $1[1] && TLS_FOLLOWS[0] == $2[0]
@sock = OpenSSL::SSL::SSLSocket.new(@sock)
+ @sock.cert_file = @options['CertFile']
@sock.cert = @options['Cert'] unless @sock.cert
+ @sock.key_file = @options['KeyFile']
@sock.key = @options['Key'] unless @sock.key
@sock.ca_cert = @options['CACert']
@sock.ca_file = @options['CAFile']
diff --git a/ext/openssl/lib/openssl/buffering.rb b/ext/openssl/lib/openssl/buffering.rb
index 761a017487..31dcdf1f9a 100644
--- a/ext/openssl/lib/openssl/buffering.rb
+++ b/ext/openssl/lib/openssl/buffering.rb
@@ -20,8 +20,6 @@ module Buffering
BLOCK_SIZE = 1024*16
def initialize(*args)
- @eof = false
- @rbuffer = ""
@sync = @io.sync
end
@@ -31,17 +29,17 @@ module Buffering
private
def fill_rbuff
+ @rbuffer = "" unless defined? @rbuffer
begin
@rbuffer << self.sysread(BLOCK_SIZE)
- rescue Errno::EAGAIN
- retry
rescue EOFError
@eof = true
end
end
def consume_rbuff(size=nil)
- if @rbuffer.empty?
+ if @rbuffer.size == 0
+ @eof = nil
nil
else
size = @rbuffer.size unless size
@@ -54,14 +52,8 @@ module Buffering
public
def read(size=nil, buf=nil)
- if size == 0
- if buf
- buf.clear
- else
- buf = ""
- end
- return @eof ? nil : buf
- end
+ fill_rbuff unless defined? @rbuffer
+ @eof ||= nil
until @eof
break if size && size <= @rbuffer.size
fill_rbuff
@@ -74,33 +66,10 @@ module Buffering
(size && ret.empty?) ? nil : ret
end
- def readpartial(maxlen, buf=nil)
- if maxlen == 0
- if buf
- buf.clear
- else
- buf = ""
- end
- return @eof ? nil : buf
- end
- if @rbuffer.empty?
- begin
- return sysread(maxlen, buf)
- rescue Errno::EAGAIN
- retry
- end
- end
- ret = consume_rbuff(maxlen)
- if buf
- buf.replace(ret)
- ret = buf
- end
- raise EOFError if ret.empty?
- ret
- end
-
def gets(eol=$/)
+ fill_rbuff unless defined? @rbuffer
idx = @rbuffer.index(eol)
+ @eof ||= nil
until @eof
break if idx
fill_rbuff
@@ -115,7 +84,7 @@ module Buffering
end
def each(eol=$/)
- while line = self.gets(eol)
+ while line = self.gets(eol?)
yield line
end
end
@@ -130,13 +99,13 @@ module Buffering
end
def readline(eol=$/)
- raise EOFError if eof?
+ raise EOFErorr if eof?
gets(eol)
end
def getc
c = read(1)
- c ? c[0] : nil
+ c ? c.to_i : nil
end
def each_byte
@@ -146,7 +115,7 @@ module Buffering
end
def readchar
- raise EOFError if eof?
+ raise EOFErorr if eof?
getc
end
@@ -155,8 +124,8 @@ module Buffering
end
def eof?
- fill_rbuff if !@eof && @rbuffer.empty?
- @eof && @rbuffer.empty?
+ @eof ||= nil
+ @eof && @rbuffer.size == 0
end
alias eof eof?
@@ -173,16 +142,11 @@ module Buffering
remain = idx ? idx + $/.size : @wbuffer.length
nwritten = 0
while remain > 0
- str = @wbuffer[nwritten,remain]
- begin
- nwrote = syswrite(str)
- rescue Errno::EAGAIN
- retry
- end
+ nwrote = syswrite(@wbuffer[nwritten,remain])
remain -= nwrote
nwritten += nwrote
end
- @wbuffer[0,nwritten] = ""
+ @wbuffer = ""
end
end
@@ -200,13 +164,10 @@ module Buffering
def puts(*args)
s = ""
- if args.empty?
- s << "\n"
- end
args.each{|arg|
s << arg.to_s
- if $/ && /\n\z/ !~ s
- s << "\n"
+ unless /#{$/}\z/o =~ s
+ s << $/
end
}
do_write(s)
diff --git a/ext/openssl/lib/openssl/cipher.rb b/ext/openssl/lib/openssl/cipher.rb
index 9f8776d6fc..11153104ee 100644
--- a/ext/openssl/lib/openssl/cipher.rb
+++ b/ext/openssl/lib/openssl/cipher.rb
@@ -20,7 +20,7 @@
module OpenSSL
module Cipher
- %w(AES CAST5 BF DES IDEA RC2 RC4 RC5).each{|cipher|
+ %w(AES Cast5 BF DES Idea RC2 RC4 RC5).each{|cipher|
eval(<<-EOD)
class #{cipher} < Cipher
def initialize(*args)
diff --git a/ext/openssl/lib/openssl/digest.rb b/ext/openssl/lib/openssl/digest.rb
index 5745661c3c..58622f543e 100644
--- a/ext/openssl/lib/openssl/digest.rb
+++ b/ext/openssl/lib/openssl/digest.rb
@@ -21,13 +21,8 @@
module OpenSSL
module Digest
- alg = %w(DSS DSS1 MD2 MD4 MD5 MDC2 RIPEMD160 SHA SHA1)
- if OPENSSL_VERSION_NUMBER > 0x00908000
- alg += %w(SHA224 SHA256 SHA384 SHA512)
- end
-
- alg.each{|digest|
- self.module_eval(<<-EOD)
+ %w(DSS DSS1 MD2 MD4 MD5 MDC2 RIPEMD160 SHA SHA1).each{|digest|
+ eval(<<-EOD)
class #{digest} < Digest
def initialize(data=nil)
super(\"#{digest}\", data)
diff --git a/ext/openssl/lib/openssl/ssl.rb b/ext/openssl/lib/openssl/ssl.rb
index 9b287fc939..629109a1de 100644
--- a/ext/openssl/lib/openssl/ssl.rb
+++ b/ext/openssl/lib/openssl/ssl.rb
@@ -16,7 +16,6 @@
require "openssl"
require "openssl/buffering"
-require "fcntl"
module OpenSSL
module SSL
@@ -50,45 +49,9 @@ module OpenSSL
end
end
- module Nonblock
- def initialize(*args)
- flag = File::NONBLOCK
- flag |= @io.fcntl(Fcntl::F_GETFL) if defined?(Fcntl::F_GETFL)
- @io.fcntl(Fcntl::F_SETFL, flag)
- super
- end
- end
-
class SSLSocket
include Buffering
include SocketForwarder
- include Nonblock
-
- def post_connection_check(hostname)
- check_common_name = true
- cert = peer_cert
- cert.extensions.each{|ext|
- next if ext.oid != "subjectAltName"
- ext.value.split(/,\s+/).each{|general_name|
- if /\ADNS:(.*)/ =~ general_name
- check_common_name = false
- reg = Regexp.escape($1).gsub(/\\\*/, "[^.]+")
- return true if /\A#{reg}\z/i =~ hostname
- elsif /\AIP Address:(.*)/ =~ general_name
- check_common_name = false
- return true if $1 == hostname
- end
- }
- }
- if check_common_name
- cert.subject.to_a.each{|oid, value|
- if oid == "CN" && value.casecmp(hostname) == 0
- return true
- end
- }
- end
- raise SSLError, "hostname not match"
- end
end
class SSLServer
@@ -98,10 +61,6 @@ module OpenSSL
def initialize(svr, ctx)
@svr = svr
@ctx = ctx
- unless ctx.session_id_context
- session_id = OpenSSL::Digest::MD5.hexdigest($0)
- @ctx.session_id_context = session_id
- end
@start_immediately = true
end
diff --git a/ext/openssl/lib/openssl/x509.rb b/ext/openssl/lib/openssl/x509.rb
index e711bda39c..6dd469827a 100644
--- a/ext/openssl/lib/openssl/x509.rb
+++ b/ext/openssl/lib/openssl/x509.rb
@@ -62,92 +62,9 @@ module OpenSSL
end
class Name
- module RFC2253DN
- Special = ',=+<>#;'
- HexChar = /[0-9a-fA-F]/
- HexPair = /#{HexChar}#{HexChar}/
- HexString = /#{HexPair}+/
- Pair = /\\(?:[#{Special}]|\\|"|#{HexPair})/
- StringChar = /[^#{Special}\\"]/
- QuoteChar = /[^\\"]/
- AttributeType = /[a-zA-Z][0-9a-zA-Z]*|[0-9]+(?:\.[0-9]+)*/
- AttributeValue = /
- (?!["#])((?:#{StringChar}|#{Pair})*)|
- \#(#{HexString})|
- "((?:#{QuoteChar}|#{Pair})*)"
- /x
- TypeAndValue = /\A(#{AttributeType})=#{AttributeValue}/
-
- module_function
-
- def expand_pair(str)
- return nil unless str
- return str.gsub(Pair){|pair|
- case pair.size
- when 2 then pair[1,1]
- when 3 then Integer("0x#{pair[1,2]}").chr
- else raise OpenSSL::X509::NameError, "invalid pair: #{str}"
- end
- }
- end
-
- def expand_hexstring(str)
- return nil unless str
- der = str.gsub(HexPair){|hex| Integer("0x#{hex}").chr }
- a1 = OpenSSL::ASN1.decode(der)
- return a1.value, a1.tag
- end
-
- def expand_value(str1, str2, str3)
- value = expand_pair(str1)
- value, tag = expand_hexstring(str2) unless value
- value = expand_pair(str3) unless value
- return value, tag
- end
-
- def scan(dn)
- str = dn
- ary = []
- while true
- if md = TypeAndValue.match(str)
- matched = md.to_s
- remain = md.post_match
- type = md[1]
- value, tag = expand_value(md[2], md[3], md[4]) rescue nil
- if value
- type_and_value = [type, value]
- type_and_value.push(tag) if tag
- ary.unshift(type_and_value)
- if remain.length > 2 && remain[0] == ?,
- str = remain[1..-1]
- next
- elsif remain.length > 2 && remain[0] == ?+
- raise OpenSSL::X509::NameError,
- "multi-valued RDN is not supported: #{dn}"
- elsif remain.empty?
- break
- end
- end
- end
- msg_dn = dn[0, dn.length - str.length] + " =>" + str
- raise OpenSSL::X509::NameError, "malformed RDN: #{msg_dn}"
- end
- return ary
- end
- end
-
- class <<self
- def parse_rfc2253(str, template=OBJECT_TYPE_TEMPLATE)
- ary = OpenSSL::X509::Name::RFC2253DN.scan(str)
- self.new(ary, template)
- end
-
- def parse_openssl(str, template=OBJECT_TYPE_TEMPLATE)
- ary = str.scan(/\s*([^\/,]+)\s*/).collect{|i| i[0].split("=", 2) }
- self.new(ary, template)
- end
-
- alias parse parse_openssl
+ def self.parse(str, template=OBJECT_TYPE_TEMPLATE)
+ ary = str.scan(/\s*([^\/,]+)\s*/).collect{|i| i[0].split("=", 2) }
+ self.new(ary, template)
end
end
end
diff --git a/ext/openssl/openssl_missing.c b/ext/openssl/openssl_missing.c
index 3b8083c257..dfa5f90012 100644
--- a/ext/openssl/openssl_missing.c
+++ b/ext/openssl/openssl_missing.c
@@ -8,10 +8,6 @@
* This program is licenced under the same licence as Ruby.
* (See the file 'LICENCE'.)
*/
-#if defined(HAVE_OPENSSL_ENGINE_H) && defined(HAVE_ST_ENGINE)
-# include <openssl/engine.h>
-#endif
-#include <openssl/x509_vfy.h>
#if !defined(OPENSSL_NO_HMAC)
#include <string.h> /* memcpy() */
@@ -34,6 +30,7 @@ HMAC_CTX_copy(HMAC_CTX *out, HMAC_CTX *in)
#endif /* NO_HMAC */
#if !defined(HAVE_X509_STORE_SET_EX_DATA)
+#include <openssl/x509_vfy.h>
int X509_STORE_set_ex_data(X509_STORE *str, int idx, void *data)
{
diff --git a/ext/openssl/openssl_missing.h b/ext/openssl/openssl_missing.h
index e8c75ca42c..2a082f3fe0 100644
--- a/ext/openssl/openssl_missing.h
+++ b/ext/openssl/openssl_missing.h
@@ -103,10 +103,6 @@ int EVP_CIPHER_CTX_copy(EVP_CIPHER_CTX *out, EVP_CIPHER_CTX *in);
# define PKCS7_type_is_encrypted(a) (OBJ_obj2nid((a)->type) == NID_pkcs7_encrypted)
#endif
-#if !defined(HAVE_OPENSSL_CLEANSE)
-#define OPENSSL_cleanse(p, l) memset(p, 0, l)
-#endif
-
void *X509_STORE_get_ex_data(X509_STORE *str, int idx);
int X509_STORE_set_ex_data(X509_STORE *str, int idx, void *data);
int X509_CRL_set_version(X509_CRL *x, long version);
diff --git a/ext/openssl/ossl.c b/ext/openssl/ossl.c
index b7eb79f053..36a7aa5042 100644
--- a/ext/openssl/ossl.c
+++ b/ext/openssl/ossl.c
@@ -278,47 +278,27 @@ ossl_raise(VALUE exc, const char *fmt, ...)
va_list args;
char buf[BUFSIZ];
const char *msg;
- long e = ERR_peek_last_error();
+ long e = ERR_get_error();
int len = 0;
if (fmt) {
va_start(args, fmt);
len = vsnprintf(buf, BUFSIZ, fmt, args);
va_end(args);
+ len += snprintf(buf+len, BUFSIZ-len, ": ");
}
- if (len < BUFSIZ && e) {
+ if (e) {
if (dOSSL == Qtrue) /* FULL INFO */
msg = ERR_error_string(e, NULL);
else
msg = ERR_reason_error_string(e);
- fmt = len ? ": %s" : "%s";
- len += snprintf(buf+len, BUFSIZ-len, fmt, msg);
+ ERR_clear_error();
+ len += snprintf(buf+len, BUFSIZ-len, "%s", msg);
}
- if (dOSSL == Qtrue){ /* show all errors on the stack */
- while ((e = ERR_get_error()) != 0){
- rb_warn("error on stack: %s", ERR_error_string(e, NULL));
- }
- }
- ERR_clear_error();
- if(len > BUFSIZ) len = strlen(buf);
rb_exc_raise(rb_exc_new(exc, buf, len));
}
-VALUE
-ossl_get_errors()
-{
- VALUE ary;
- long e;
-
- ary = rb_ary_new();
- while ((e = ERR_get_error()) != 0){
- rb_ary_push(ary, rb_str_new2(ERR_error_string(e, NULL)));
- }
-
- return ary;
-}
-
/*
* Debug
*/
@@ -382,7 +362,6 @@ Init_openssl()
*/
/* CRYPTO_malloc_init(); */
/* ENGINE_load_builtin_engines(); */
- OpenSSL_add_ssl_algorithms();
OpenSSL_add_all_algorithms();
ERR_load_crypto_strings();
SSL_load_error_strings();
@@ -431,7 +410,6 @@ Init_openssl()
dOSSL = Qfalse;
rb_define_module_function(mOSSL, "debug", ossl_debug_get, 0);
rb_define_module_function(mOSSL, "debug=", ossl_debug_set, 1);
- rb_define_module_function(mOSSL, "errors", ossl_get_errors, 0);
/*
* Get ID of to_der
diff --git a/ext/openssl/ossl.h b/ext/openssl/ossl.h
index f678ac1188..c5054beba2 100644
--- a/ext/openssl/ossl.h
+++ b/ext/openssl/ossl.h
@@ -45,7 +45,7 @@ extern "C" {
#include <openssl/conf_api.h>
#undef X509_NAME
#undef PKCS7_SIGNER_INFO
-#if defined(HAVE_OPENSSL_ENGINE_H) && defined(HAVE_ST_ENGINE)
+#if defined(HAVE_OPENSSL_ENGINE_H) && !defined(OPENSSL_NO_ENGINE)
# define OSSL_ENGINE_ENABLED
# include <openssl/engine.h>
#endif
diff --git a/ext/openssl/ossl_asn1.c b/ext/openssl/ossl_asn1.c
index 8d6bd014ca..a961c16bc0 100644
--- a/ext/openssl/ossl_asn1.c
+++ b/ext/openssl/ossl_asn1.c
@@ -42,19 +42,21 @@ asn1time_to_time(ASN1_TIME *time)
} else {
tm.tm_year += 1900;
}
+ tm.tm_mon -= 1;
break;
case V_ASN1_GENERALIZEDTIME:
if (sscanf(time->data, "%4d%2d%2d%2d%2d%2dZ", &tm.tm_year, &tm.tm_mon,
&tm.tm_mday, &tm.tm_hour, &tm.tm_min, &tm.tm_sec) != 6) {
ossl_raise(rb_eTypeError, "bad GENERALIZEDTIME format" );
}
+ tm.tm_mon -= 1;
break;
default:
rb_warning("unknown time format");
return Qnil;
}
argv[0] = INT2NUM(tm.tm_year);
- argv[1] = INT2NUM(tm.tm_mon);
+ argv[1] = INT2NUM(tm.tm_mon+1);
argv[2] = INT2NUM(tm.tm_mday);
argv[3] = INT2NUM(tm.tm_hour);
argv[4] = INT2NUM(tm.tm_min);
@@ -75,15 +77,6 @@ time_to_time_t(VALUE time)
}
/*
- * STRING conversion
- */
-VALUE
-asn1str_to_str(ASN1_STRING *str)
-{
- return rb_str_new(str->data, str->length);
-}
-
-/*
* ASN1_INTEGER conversions
* TODO: Make a decision what's the right way to do this.
*/
@@ -820,14 +813,13 @@ ossl_asn1_traverse(VALUE self, VALUE obj)
{
unsigned char *p;
long offset = 0;
- volatile VALUE tmp;
obj = ossl_to_der_if_possible(obj);
- tmp = rb_str_new4(StringValue(obj));
- p = RSTRING(tmp)->ptr;
- ossl_asn1_decode0(&p, RSTRING(tmp)->len, &offset, 0, 0, 1);
+ StringValue(obj);
+ p = RSTRING(obj)->ptr;
+ ossl_asn1_decode0(&p, RSTRING(obj)->len, &offset, 0, 0, 1);
- return Qnil;
+ return obj;
}
static VALUE
@@ -836,12 +828,11 @@ ossl_asn1_decode(VALUE self, VALUE obj)
VALUE ret, ary;
unsigned char *p;
long offset = 0;
- volatile VALUE tmp;
obj = ossl_to_der_if_possible(obj);
- tmp = rb_str_new4(StringValue(obj));
- p = RSTRING(tmp)->ptr;
- ary = ossl_asn1_decode0(&p, RSTRING(tmp)->len, &offset, 0, 1, 0);
+ StringValue(obj);
+ p = RSTRING(obj)->ptr;
+ ary = ossl_asn1_decode0(&p, RSTRING(obj)->len, &offset, 0, 1, 0);
ret = rb_ary_entry(ary, 0);
return ret;
@@ -853,12 +844,11 @@ ossl_asn1_decode_all(VALUE self, VALUE obj)
VALUE ret;
unsigned char *p;
long offset = 0;
- volatile VALUE tmp;
obj = ossl_to_der_if_possible(obj);
- tmp = rb_str_new4(StringValue(obj));
- p = RSTRING(tmp)->ptr;
- ret = ossl_asn1_decode0(&p, RSTRING(tmp)->len, &offset, 0, 0, 0);
+ StringValue(obj);
+ p = RSTRING(obj)->ptr;
+ ret = ossl_asn1_decode0(&p, RSTRING(obj)->len, &offset, 0, 0, 0);
return ret;
}
diff --git a/ext/openssl/ossl_asn1.h b/ext/openssl/ossl_asn1.h
index 8aad9f970d..919ede0f3b 100644
--- a/ext/openssl/ossl_asn1.h
+++ b/ext/openssl/ossl_asn1.h
@@ -18,11 +18,6 @@ VALUE asn1time_to_time(ASN1_TIME *);
time_t time_to_time_t(VALUE);
/*
- * ASN1_STRING conversions
- */
-VALUE asn1str_to_str(ASN1_STRING *);
-
-/*
* ASN1_INTEGER conversions
*/
VALUE asn1integer_to_num(ASN1_INTEGER *);
diff --git a/ext/openssl/ossl_bio.c b/ext/openssl/ossl_bio.c
index 9c9aa24197..8e80f412ee 100644
--- a/ext/openssl/ossl_bio.c
+++ b/ext/openssl/ossl_bio.c
@@ -9,9 +9,6 @@
* (See the file 'LICENCE'.)
*/
#include "ossl.h"
-#ifdef HAVE_UNISTD_H
-#include <unistd.h>
-#endif
BIO *
ossl_obj2bio(VALUE obj)
diff --git a/ext/openssl/ossl_bn.c b/ext/openssl/ossl_bn.c
index 47a607e60f..c3a371a008 100644
--- a/ext/openssl/ossl_bn.c
+++ b/ext/openssl/ossl_bn.c
@@ -107,11 +107,11 @@ ossl_bn_initialize(int argc, VALUE *argv, VALUE self)
VALUE str, bs;
int base = 10;
+ GetBN(self, bn);
+
if (rb_scan_args(argc, argv, "11", &str, &bs) == 2) {
base = NUM2INT(bs);
}
- StringValue(str);
- GetBN(self, bn);
if (RTEST(rb_obj_is_kind_of(str, cBN))) {
BIGNUM *other;
@@ -121,6 +121,8 @@ ossl_bn_initialize(int argc, VALUE *argv, VALUE self)
}
return self;
}
+ str = rb_String(str);
+ StringValue(str);
switch (base) {
case 0:
@@ -157,10 +159,11 @@ ossl_bn_to_s(int argc, VALUE *argv, VALUE self)
int base = 10, len;
char *buf;
+ GetBN(self, bn);
+
if (rb_scan_args(argc, argv, "01", &bs) == 1) {
base = NUM2INT(bs);
}
- GetBN(self, bn);
switch (base) {
case 0:
len = BN_bn2mpi(bn, NULL);
@@ -377,12 +380,11 @@ BIGNUM_BIT(mask_bits);
static VALUE
ossl_bn_is_bit_set(VALUE self, VALUE bit)
{
- int b;
BIGNUM *bn;
- b = NUM2INT(bit);
GetBN(self, bn);
- if (BN_is_bit_set(bn, b)) {
+
+ if (BN_is_bit_set(bn, NUM2INT(bit))) {
return Qtrue;
}
return Qfalse;
@@ -395,8 +397,8 @@ ossl_bn_is_bit_set(VALUE self, VALUE bit)
BIGNUM *bn, *result; \
int b; \
VALUE obj; \
- b = NUM2INT(bits); \
GetBN(self, bn); \
+ b = NUM2INT(bits); \
if (!(result = BN_new())) { \
ossl_raise(eBNError, NULL); \
} \
@@ -548,10 +550,11 @@ ossl_bn_is_prime(int argc, VALUE *argv, VALUE self)
VALUE vchecks;
int checks = BN_prime_checks;
+ GetBN(self, bn);
+
if (rb_scan_args(argc, argv, "01", &vchecks) == 0) {
checks = NUM2INT(vchecks);
}
- GetBN(self, bn);
switch (BN_is_prime(bn, checks, NULL, ossl_bn_ctx, NULL)) {
case 1:
return Qtrue;
@@ -571,12 +574,13 @@ ossl_bn_is_prime_fasttest(int argc, VALUE *argv, VALUE self)
VALUE vchecks, vtrivdiv;
int checks = BN_prime_checks, do_trial_division = 1;
+ GetBN(self, bn);
+
rb_scan_args(argc, argv, "02", &vchecks, &vtrivdiv);
if (!NIL_P(vchecks)) {
checks = NUM2INT(vchecks);
}
- GetBN(self, bn);
/* handle true/false */
if (vtrivdiv == Qfalse) {
do_trial_division = 0;
diff --git a/ext/openssl/ossl_cipher.c b/ext/openssl/ossl_cipher.c
index cb5fee6aee..98468e0f28 100644
--- a/ext/openssl/ossl_cipher.c
+++ b/ext/openssl/ossl_cipher.c
@@ -91,10 +91,12 @@ ossl_cipher_initialize(VALUE self, VALUE str)
const EVP_CIPHER *cipher;
char *name;
- name = StringValuePtr(str);
GetCipher(self, ctx);
+
+ name = StringValuePtr(str);
+
if (!(cipher = EVP_get_cipherbyname(name))) {
- ossl_raise(rb_eRuntimeError, "unsupported cipher algorithm (%s)", name);
+ ossl_raise(rb_eRuntimeError, "Unsupported cipher algorithm (%s).", name);
}
if (EVP_CipherInit_ex(ctx, cipher, NULL, NULL, NULL, -1) != 1)
ossl_raise(eCipherError, NULL);
@@ -137,6 +139,7 @@ ossl_cipher_init(int argc, VALUE *argv, VALUE self, int mode)
unsigned char iv[EVP_MAX_IV_LENGTH], *p_iv = NULL;
VALUE pass, init_v;
+ GetCipher(self, ctx);
if(rb_scan_args(argc, argv, "02", &pass, &init_v) > 0){
/*
* oops. this code mistakes salt for IV.
@@ -144,7 +147,6 @@ ossl_cipher_init(int argc, VALUE *argv, VALUE self, int mode)
* keeping this behaviour for backward compatibility.
*/
StringValue(pass);
- GetCipher(self, ctx);
if (NIL_P(init_v)) memcpy(iv, "OpenSSL for Ruby rulez!", sizeof(iv));
else{
char *cname = rb_class2name(rb_obj_class(self));
@@ -162,9 +164,6 @@ ossl_cipher_init(int argc, VALUE *argv, VALUE self, int mode)
p_key = key;
p_iv = iv;
}
- else {
- GetCipher(self, ctx);
- }
if (EVP_CipherInit_ex(ctx, NULL, NULL, p_key, p_iv, mode) != 1) {
ossl_raise(eCipherError, NULL);
}
@@ -193,17 +192,17 @@ ossl_cipher_pkcs5_keyivgen(int argc, VALUE *argv, VALUE self)
unsigned char key[EVP_MAX_KEY_LENGTH], iv[EVP_MAX_IV_LENGTH], *salt = NULL;
int iter;
+ GetCipher(self, ctx);
rb_scan_args(argc, argv, "13", &vpass, &vsalt, &viter, &vdigest);
StringValue(vpass);
if(!NIL_P(vsalt)){
StringValue(vsalt);
if(RSTRING(vsalt)->len != PKCS5_SALT_LEN)
- rb_raise(eCipherError, "salt must be an 8-octet string");
+ rb_raise(eCipherError, "salt must be an 8-octet string.");
salt = RSTRING(vsalt)->ptr;
}
iter = NIL_P(viter) ? 2048 : NUM2INT(viter);
digest = NIL_P(vdigest) ? EVP_md5() : GetDigestPtr(vdigest);
- GetCipher(self, ctx);
EVP_BytesToKey(EVP_CIPHER_CTX_cipher(ctx), digest, salt,
RSTRING(vpass)->ptr, RSTRING(vpass)->len, iter, key, iv);
if (EVP_CipherInit_ex(ctx, NULL, NULL, key, iv, -1) != 1)
@@ -222,10 +221,10 @@ ossl_cipher_update(VALUE self, VALUE data)
int in_len, out_len;
VALUE str;
+ GetCipher(self, ctx);
StringValue(data);
in = RSTRING(data)->ptr;
in_len = RSTRING(data)->len;
- GetCipher(self, ctx);
str = rb_str_new(0, in_len+EVP_CIPHER_CTX_block_size(ctx));
if (!EVP_CipherUpdate(ctx, RSTRING(str)->ptr, &out_len, in, in_len))
ossl_raise(eCipherError, NULL);
@@ -312,10 +311,9 @@ static VALUE
ossl_cipher_set_key_length(VALUE self, VALUE key_length)
{
EVP_CIPHER_CTX *ctx;
- int len = NUM2INT(key_length);
GetCipher(self, ctx);
- if (EVP_CIPHER_CTX_set_key_length(ctx, len) != 1)
+ if (EVP_CIPHER_CTX_set_key_length(ctx, NUM2INT(key_length)) != 1)
ossl_raise(eCipherError, NULL);
return key_length;
@@ -326,10 +324,9 @@ ossl_cipher_set_padding(VALUE self, VALUE padding)
{
#if defined(HAVE_EVP_CIPHER_CTX_SET_PADDING)
EVP_CIPHER_CTX *ctx;
- int pad = NUM2INT(padding);
GetCipher(self, ctx);
- if (EVP_CIPHER_CTX_set_padding(ctx, pad) != 1)
+ if (EVP_CIPHER_CTX_set_padding(ctx, NUM2INT(padding)) != 1)
ossl_raise(eCipherError, NULL);
#else
rb_notimplement();
diff --git a/ext/openssl/ossl_config.c b/ext/openssl/ossl_config.c
index ef89fdfe0d..37abff508b 100644
--- a/ext/openssl/ossl_config.c
+++ b/ext/openssl/ossl_config.c
@@ -119,8 +119,8 @@ ossl_config_copy(VALUE self, VALUE other)
VALUE str;
CONF *conf;
- str = rb_funcall(self, rb_intern("to_s"), 0);
GetConfig(other, conf);
+ str = rb_funcall(self, rb_intern("to_s"), 0);
parse_config(str, conf);
return self;
@@ -134,11 +134,11 @@ ossl_config_initialize(int argc, VALUE *argv, VALUE self)
char *filename;
VALUE path;
+ GetConfig(self, conf);
rb_scan_args(argc, argv, "01", &path);
if(!NIL_P(path)){
SafeStringValue(path);
filename = StringValuePtr(path);
- GetConfig(self, conf);
if (!NCONF_load(conf, filename, &eline)){
if (eline <= 0)
ossl_raise(eConfigError, "wrong config file %s", filename);
@@ -149,10 +149,7 @@ ossl_config_initialize(int argc, VALUE *argv, VALUE self)
#ifdef OSSL_NO_CONF_API
else rb_raise(rb_eArgError, "wrong number of arguments (0 for 1)");
#else
- else {
- GetConfig(self, conf);
- _CONF_new_data(conf);
- }
+ else _CONF_new_data(conf);
#endif
return self;
@@ -167,10 +164,10 @@ ossl_config_add_value(VALUE self, VALUE section, VALUE name, VALUE value)
CONF *conf;
CONF_VALUE *sv, *cv;
+ GetConfig(self, conf);
StringValue(section);
StringValue(name);
StringValue(value);
- GetConfig(self, conf);
if(!(sv = _CONF_get_section(conf, RSTRING(section)->ptr))){
if(!(sv = _CONF_new_section(conf, RSTRING(section)->ptr))){
ossl_raise(eConfigError, NULL);
@@ -198,9 +195,9 @@ ossl_config_get_value(VALUE self, VALUE section, VALUE name)
CONF *conf;
char *str;
+ GetConfig(self, conf);
StringValue(section);
StringValue(name);
- GetConfig(self, conf);
str = NCONF_get_string(conf, RSTRING(section)->ptr, RSTRING(name)->ptr);
if(!str){
ERR_clear_error();
@@ -264,7 +261,6 @@ ossl_config_get_section(VALUE self, VALUE section)
VALUE hash;
hash = rb_hash_new();
- StringValue(section);
GetConfig(self, conf);
if (!(sk = NCONF_get_section(conf, StringValuePtr(section)))) {
ERR_clear_error();
diff --git a/ext/openssl/ossl_digest.c b/ext/openssl/ossl_digest.c
index d22f022442..8ad9f01dc4 100644
--- a/ext/openssl/ossl_digest.c
+++ b/ext/openssl/ossl_digest.c
@@ -85,16 +85,16 @@ ossl_digest_initialize(int argc, VALUE *argv, VALUE self)
char *name;
VALUE type, data;
+ GetDigest(self, ctx);
+
rb_scan_args(argc, argv, "11", &type, &data);
- StringValue(type);
- if (!NIL_P(data)) StringValue(data);
name = StringValuePtr(type);
+ if (!NIL_P(data)) StringValue(data);
md = EVP_get_digestbyname(name);
if (!md) {
ossl_raise(rb_eRuntimeError, "Unsupported digest algorithm (%s).", name);
}
- GetDigest(self, ctx);
EVP_DigestInit_ex(ctx, md, NULL);
if (!NIL_P(data)) return ossl_digest_update(self, data);
@@ -134,8 +134,8 @@ ossl_digest_update(VALUE self, VALUE data)
{
EVP_MD_CTX *ctx;
- StringValue(data);
GetDigest(self, ctx);
+ StringValue(data);
EVP_DigestUpdate(ctx, RSTRING(data)->ptr, RSTRING(data)->len);
return self;
@@ -218,13 +218,13 @@ ossl_digest_equal(VALUE self, VALUE other)
EVP_MD_CTX *ctx;
VALUE str1, str2;
+ GetDigest(self, ctx);
if (rb_obj_is_kind_of(other, cDigest) == Qtrue) {
str2 = ossl_digest_digest(other);
} else {
StringValue(other);
str2 = other;
}
- GetDigest(self, ctx);
if (RSTRING(str2)->len == EVP_MD_CTX_size(ctx)) {
str1 = ossl_digest_digest(self);
} else {
diff --git a/ext/openssl/ossl_engine.c b/ext/openssl/ossl_engine.c
index 71586e3620..91025941b9 100644
--- a/ext/openssl/ossl_engine.c
+++ b/ext/openssl/ossl_engine.c
@@ -55,12 +55,9 @@ ossl_engine_s_load(int argc, VALUE *argv, VALUE klass)
VALUE name;
rb_scan_args(argc, argv, "01", &name);
- if(NIL_P(name)){
- ENGINE_load_builtin_engines();
- return Qtrue;
- }
+ if(NIL_P(name)) ENGINE_load_builtin_engines();
StringValue(name);
-#ifndef OPENSSL_NO_STATIC_ENGINE
+ OSSL_ENGINE_LOAD_IF_MATCH(openssl);
OSSL_ENGINE_LOAD_IF_MATCH(dynamic);
OSSL_ENGINE_LOAD_IF_MATCH(cswift);
OSSL_ENGINE_LOAD_IF_MATCH(chil);
@@ -70,13 +67,10 @@ ossl_engine_s_load(int argc, VALUE *argv, VALUE klass)
OSSL_ENGINE_LOAD_IF_MATCH(aep);
OSSL_ENGINE_LOAD_IF_MATCH(sureware);
OSSL_ENGINE_LOAD_IF_MATCH(4758cca);
-#endif
#ifdef HAVE_ENGINE_LOAD_OPENBSD_DEV_CRYPTO
OSSL_ENGINE_LOAD_IF_MATCH(openbsd_dev_crypto);
#endif
- OSSL_ENGINE_LOAD_IF_MATCH(openssl);
- rb_warning("no such builtin loader for `%s'", RSTRING(name)->ptr);
- return Qnil;
+ rb_raise(eEngineError, "no such engine `%s'", RSTRING(name)->ptr);
#endif /* HAVE_ENGINE_LOAD_BUILTIN_ENGINES */
}
@@ -114,13 +108,12 @@ ossl_engine_s_by_id(VALUE klass, VALUE id)
ossl_engine_s_load(1, &id, klass);
if(!(e = ENGINE_by_id(RSTRING(id)->ptr)))
ossl_raise(eEngineError, NULL);
- WrapEngine(klass, obj, e);
- if(rb_block_given_p()) rb_yield(obj);
if(!ENGINE_init(e))
ossl_raise(eEngineError, NULL);
ENGINE_ctrl(e, ENGINE_CTRL_SET_PASSWORD_CALLBACK,
0, NULL, (void(*)())ossl_pem_passwd_cb);
ERR_clear_error();
+ WrapEngine(klass, obj, e);
return obj;
}
@@ -217,11 +210,11 @@ ossl_engine_load_privkey(int argc, VALUE *argv, VALUE self)
{
ENGINE *e;
EVP_PKEY *pkey;
- VALUE id, data, obj;
+ VALUE id, data;
char *sid, *sdata;
- rb_scan_args(argc, argv, "02", &id, &data);
- sid = NIL_P(id) ? NULL : StringValuePtr(id);
+ rb_scan_args(argc, argv, "11", &id, &data);
+ sid = StringValuePtr(id);
sdata = NIL_P(data) ? NULL : StringValuePtr(data);
GetEngine(self, e);
#if OPENSSL_VERSION_NUMBER < 0x00907000L
@@ -230,10 +223,8 @@ ossl_engine_load_privkey(int argc, VALUE *argv, VALUE self)
pkey = ENGINE_load_private_key(e, sid, NULL, sdata);
#endif
if (!pkey) ossl_raise(eEngineError, NULL);
- obj = ossl_pkey_new(pkey);
- OSSL_PKEY_SET_PRIVATE(obj);
- return obj;
+ return ossl_pkey_new(pkey);
}
static VALUE
@@ -244,8 +235,8 @@ ossl_engine_load_pubkey(int argc, VALUE *argv, VALUE self)
VALUE id, data;
char *sid, *sdata;
- rb_scan_args(argc, argv, "02", &id, &data);
- sid = NIL_P(id) ? NULL : StringValuePtr(id);
+ rb_scan_args(argc, argv, "11", &id, &data);
+ sid = StringValuePtr(id);
sdata = NIL_P(data) ? NULL : StringValuePtr(data);
GetEngine(self, e);
#if OPENSSL_VERSION_NUMBER < 0x00907000L
@@ -262,67 +253,14 @@ static VALUE
ossl_engine_set_default(VALUE self, VALUE flag)
{
ENGINE *e;
- int f = NUM2INT(flag);
GetEngine(self, e);
- ENGINE_set_default(e, f);
+ ENGINE_set_default(e, NUM2INT(flag));
return Qtrue;
}
static VALUE
-ossl_engine_ctrl_cmd(int argc, VALUE *argv, VALUE self)
-{
- ENGINE *e;
- VALUE cmd, val;
- int ret;
-
- GetEngine(self, e);
- rb_scan_args(argc, argv, "11", &cmd, &val);
- StringValue(cmd);
- if (!NIL_P(val)) StringValue(val);
- ret = ENGINE_ctrl_cmd_string(e, RSTRING(cmd)->ptr,
- NIL_P(val) ? NULL : RSTRING(val)->ptr, 0);
- if (!ret) ossl_raise(eEngineError, NULL);
-
- return self;
-}
-
-static VALUE
-ossl_engine_cmd_flag_to_name(int flag)
-{
- switch(flag){
- case ENGINE_CMD_FLAG_NUMERIC: return rb_str_new2("NUMERIC");
- case ENGINE_CMD_FLAG_STRING: return rb_str_new2("STRING");
- case ENGINE_CMD_FLAG_NO_INPUT: return rb_str_new2("NO_INPUT");
- case ENGINE_CMD_FLAG_INTERNAL: return rb_str_new2("INTERNAL");
- default: return rb_str_new2("UNKNOWN");
- }
-}
-
-static VALUE
-ossl_engine_get_cmds(VALUE self)
-{
- ENGINE *e;
- const ENGINE_CMD_DEFN *defn, *p;
- VALUE ary, tmp;
-
- GetEngine(self, e);
- ary = rb_ary_new();
- if ((defn = ENGINE_get_cmd_defns(e)) != NULL){
- for (p = defn; p->cmd_num > 0; p++){
- tmp = rb_ary_new();
- rb_ary_push(tmp, rb_str_new2(p->cmd_name));
- rb_ary_push(tmp, rb_str_new2(p->cmd_desc));
- rb_ary_push(tmp, ossl_engine_cmd_flag_to_name(p->cmd_flags));
- rb_ary_push(ary, tmp);
- }
- }
-
- return ary;
-}
-
-static VALUE
ossl_engine_inspect(VALUE self)
{
VALUE str;
@@ -362,8 +300,6 @@ Init_ossl_engine()
rb_define_method(cEngine, "load_private_key", ossl_engine_load_privkey, -1);
rb_define_method(cEngine, "load_public_key", ossl_engine_load_pubkey, -1);
rb_define_method(cEngine, "set_default", ossl_engine_set_default, 1);
- rb_define_method(cEngine, "ctrl_cmd", ossl_engine_ctrl_cmd, -1);
- rb_define_method(cEngine, "cmds", ossl_engine_get_cmds, 0);
rb_define_method(cEngine, "inspect", ossl_engine_inspect, 0);
DefEngineConst(METHOD_RSA);
diff --git a/ext/openssl/ossl_hmac.c b/ext/openssl/ossl_hmac.c
index ca5917518f..fb3d0a6a8f 100644
--- a/ext/openssl/ossl_hmac.c
+++ b/ext/openssl/ossl_hmac.c
@@ -62,8 +62,8 @@ ossl_hmac_initialize(VALUE self, VALUE key, VALUE digest)
{
HMAC_CTX *ctx;
- StringValue(key);
GetHMAC(self, ctx);
+ StringValue(key);
HMAC_Init_ex(ctx, RSTRING(key)->ptr, RSTRING(key)->len,
GetDigestPtr(digest), NULL);
@@ -92,8 +92,8 @@ ossl_hmac_update(VALUE self, VALUE data)
{
HMAC_CTX *ctx;
- StringValue(data);
GetHMAC(self, ctx);
+ StringValue(data);
HMAC_Update(ctx, RSTRING(data)->ptr, RSTRING(data)->len);
return self;
diff --git a/ext/openssl/ossl_ns_spki.c b/ext/openssl/ossl_ns_spki.c
index 5cba529850..9aed773edc 100644
--- a/ext/openssl/ossl_ns_spki.c
+++ b/ext/openssl/ossl_ns_spki.c
@@ -56,17 +56,12 @@ ossl_spki_initialize(int argc, VALUE *argv, VALUE self)
{
NETSCAPE_SPKI *spki;
VALUE buffer;
- unsigned char *p;
if (rb_scan_args(argc, argv, "01", &buffer) == 0) {
return self;
}
- StringValue(buffer);
- if (!(spki = NETSCAPE_SPKI_b64_decode(RSTRING(buffer)->ptr, -1))) {
- p = RSTRING(buffer)->ptr;
- if (!(spki = d2i_NETSCAPE_SPKI(NULL, &p, RSTRING(buffer)->len))) {
- ossl_raise(eSPKIError, NULL);
- }
+ if (!(spki = NETSCAPE_SPKI_b64_decode(StringValuePtr(buffer), -1))) {
+ ossl_raise(eSPKIError, NULL);
}
NETSCAPE_SPKI_free(DATA_PTR(self));
DATA_PTR(self) = spki;
@@ -75,26 +70,6 @@ ossl_spki_initialize(int argc, VALUE *argv, VALUE self)
}
static VALUE
-ossl_spki_to_der(VALUE self)
-{
- NETSCAPE_SPKI *spki;
- VALUE str;
- long len;
- unsigned char *p;
-
- GetSPKI(self, spki);
- if ((len = i2d_NETSCAPE_SPKI(spki, NULL)) <= 0)
- ossl_raise(eX509CertError, NULL);
- str = rb_str_new(0, len);
- p = RSTRING(str)->ptr;
- if (i2d_NETSCAPE_SPKI(spki, &p) <= 0)
- ossl_raise(eX509CertError, NULL);
- ossl_str_adjust(str, p);
-
- return str;
-}
-
-static VALUE
ossl_spki_to_pem(VALUE self)
{
NETSCAPE_SPKI *spki;
@@ -180,8 +155,8 @@ ossl_spki_set_challenge(VALUE self, VALUE str)
{
NETSCAPE_SPKI *spki;
- StringValue(str);
GetSPKI(self, spki);
+ StringValue(str);
if (!ASN1_STRING_set(spki->spkac->challenge, RSTRING(str)->ptr,
RSTRING(str)->len)) {
ossl_raise(eSPKIError, NULL);
@@ -197,9 +172,9 @@ ossl_spki_sign(VALUE self, VALUE key, VALUE digest)
EVP_PKEY *pkey;
const EVP_MD *md;
+ GetSPKI(self, spki);
pkey = GetPrivPKeyPtr(key); /* NO NEED TO DUP */
md = GetDigestPtr(digest);
- GetSPKI(self, spki);
if (!NETSCAPE_SPKI_sign(spki, pkey, md)) {
ossl_raise(eSPKIError, NULL);
}
@@ -242,7 +217,6 @@ Init_ossl_ns_spki()
rb_define_alloc_func(cSPKI, ossl_spki_alloc);
rb_define_method(cSPKI, "initialize", ossl_spki_initialize, -1);
- rb_define_method(cSPKI, "to_der", ossl_spki_to_der, 0);
rb_define_method(cSPKI, "to_pem", ossl_spki_to_pem, 0);
rb_define_alias(cSPKI, "to_s", "to_pem");
rb_define_method(cSPKI, "to_text", ossl_spki_print, 0);
diff --git a/ext/openssl/ossl_ocsp.c b/ext/openssl/ossl_ocsp.c
index b1e721c24c..d1f1b84127 100644
--- a/ext/openssl/ossl_ocsp.c
+++ b/ext/openssl/ossl_ocsp.c
@@ -127,13 +127,11 @@ ossl_ocspreq_add_nonce(int argc, VALUE *argv, VALUE self)
int ret;
rb_scan_args(argc, argv, "01", &val);
- if(NIL_P(val)) {
- GetOCSPReq(self, req);
+ GetOCSPReq(self, req);
+ if(NIL_P(val))
ret = OCSP_request_add1_nonce(req, NULL, -1);
- }
else{
StringValue(val);
- GetOCSPReq(self, req);
ret = OCSP_request_add1_nonce(req, RSTRING(val)->ptr, RSTRING(val)->len);
}
if(!ret) ossl_raise(eOCSPError, NULL);
@@ -216,6 +214,7 @@ ossl_ocspreq_sign(int argc, VALUE *argv, VALUE self)
int ret;
rb_scan_args(argc, argv, "22", &signer_cert, &signer_key, &certs, &flags);
+ GetOCSPReq(self, req);
signer = GetX509CertPtr(signer_cert);
key = GetPrivPKeyPtr(signer_key);
flg = NIL_P(flags) ? 0 : NUM2INT(flags);
@@ -224,7 +223,6 @@ ossl_ocspreq_sign(int argc, VALUE *argv, VALUE self)
flags |= OCSP_NOCERTS;
}
else x509s = ossl_x509_ary2sk(certs);
- GetOCSPReq(self, req);
ret = OCSP_request_sign(req, signer, key, EVP_sha1(), x509s, flg);
sk_X509_pop_free(x509s, X509_free);
if(!ret) ossl_raise(eOCSPError, NULL);
@@ -242,10 +240,10 @@ ossl_ocspreq_verify(int argc, VALUE *argv, VALUE self)
int flg, result;
rb_scan_args(argc, argv, "21", &certs, &store, &flags);
+ GetOCSPReq(self, req);
x509st = GetX509StorePtr(store);
flg = NIL_P(flags) ? 0 : INT2NUM(flags);
x509s = ossl_x509_ary2sk(certs);
- GetOCSPReq(self, req);
result = OCSP_request_verify(req, x509s, x509st, flg);
sk_X509_pop_free(x509s, X509_free);
if(!result) rb_warn("%s", ERR_error_string(ERR_peek_error(), NULL));
@@ -262,6 +260,7 @@ ossl_ocspreq_to_der(VALUE self)
long len;
GetOCSPReq(self, req);
+
if((len = i2d_OCSP_REQUEST(req, NULL)) <= 0)
ossl_raise(eOCSPError, NULL);
str = rb_str_new(0, len);
@@ -282,11 +281,10 @@ ossl_ocspres_s_create(VALUE klass, VALUE status, VALUE basic_resp)
OCSP_BASICRESP *bs;
OCSP_RESPONSE *res;
VALUE obj;
- int st = NUM2INT(status);
if(NIL_P(basic_resp)) bs = NULL;
else GetOCSPBasicRes(basic_resp, bs); /* NO NEED TO DUP */
- if(!(res = OCSP_response_create(st, bs)))
+ if(!(res = OCSP_response_create(NUM2INT(status), bs)))
ossl_raise(eOCSPError, NULL);
WrapOCSPRes(klass, obj, res);
@@ -428,14 +426,12 @@ ossl_ocspbres_add_nonce(int argc, VALUE *argv, VALUE self)
VALUE val;
int ret;
+ GetOCSPBasicRes(self, bs);
rb_scan_args(argc, argv, "01", &val);
- if(NIL_P(val)) {
- GetOCSPBasicRes(self, bs);
+ if(NIL_P(val))
ret = OCSP_basic_add1_nonce(bs, NULL, -1);
- }
else{
StringValue(val);
- GetOCSPBasicRes(self, bs);
ret = OCSP_basic_add1_nonce(bs, RSTRING(val)->ptr, RSTRING(val)->len);
}
if(!ret) ossl_raise(eOCSPError, NULL);
@@ -456,6 +452,8 @@ ossl_ocspbres_add_status(VALUE self, VALUE cid, VALUE status,
int error, i, rstatus = 0;
VALUE tmp;
+ GetOCSPBasicRes(self, bs);
+ SafeGetOCSPCertId(cid, id);
st = NUM2INT(status);
rsn = NIL_P(status) ? 0 : NUM2INT(reason);
if(!NIL_P(ext)){
@@ -479,8 +477,6 @@ ossl_ocspbres_add_status(VALUE self, VALUE cid, VALUE status,
if(rstatus) goto err;
nxt = X509_gmtime_adj(NULL, NUM2INT(tmp));
- GetOCSPBasicRes(self, bs);
- SafeGetOCSPCertId(cid, id);
if(!(single = OCSP_basic_add1_status(bs, id, st, rsn, rev, ths, nxt))){
error = 1;
goto err;
@@ -568,6 +564,7 @@ ossl_ocspbres_sign(int argc, VALUE *argv, VALUE self)
int ret;
rb_scan_args(argc, argv, "22", &signer_cert, &signer_key, &certs, &flags);
+ GetOCSPBasicRes(self, bs);
signer = GetX509CertPtr(signer_cert);
key = GetPrivPKeyPtr(signer_key);
flg = NIL_P(flags) ? 0 : NUM2INT(flags);
@@ -578,7 +575,6 @@ ossl_ocspbres_sign(int argc, VALUE *argv, VALUE self)
else{
x509s = ossl_x509_ary2sk(certs);
}
- GetOCSPBasicRes(self, bs);
ret = OCSP_basic_sign(bs, signer, key, EVP_sha1(), x509s, flg);
sk_X509_pop_free(x509s, X509_free);
if(!ret) ossl_raise(eOCSPError, NULL);
@@ -596,10 +592,10 @@ ossl_ocspbres_verify(int argc, VALUE *argv, VALUE self)
int flg, result;
rb_scan_args(argc, argv, "21", &certs, &store, &flags);
+ GetOCSPBasicRes(self, bs);
x509st = GetX509StorePtr(store);
flg = NIL_P(flags) ? 0 : INT2NUM(flags);
x509s = ossl_x509_ary2sk(certs);
- GetOCSPBasicRes(self, bs);
result = OCSP_basic_verify(bs, x509s, x509st, flg);
sk_X509_pop_free(x509s, X509_free);
if(!result) rb_warn("%s", ERR_error_string(ERR_peek_error(), NULL));
@@ -629,11 +625,11 @@ ossl_ocspcid_initialize(VALUE self, VALUE subject, VALUE issuer)
OCSP_CERTID *id, *newid;
X509 *x509s, *x509i;
+ GetOCSPCertId(self, id);
x509s = GetX509CertPtr(subject); /* NO NEED TO DUP */
x509i = GetX509CertPtr(issuer); /* NO NEED TO DUP */
if(!(newid = OCSP_cert_to_id(NULL, x509s, x509i)))
ossl_raise(eOCSPError, NULL);
- GetOCSPCertId(self, id);
OCSP_CERTID_free(id);
RDATA(self)->data = newid;
diff --git a/ext/openssl/ossl_pkcs12.h b/ext/openssl/ossl_pkcs12.h
index 01dde2bc30..fa73c4bec5 100644
--- a/ext/openssl/ossl_pkcs12.h
+++ b/ext/openssl/ossl_pkcs12.h
@@ -4,7 +4,7 @@
* $Id$
*/
#if !defined(_OSSL_PKCS12_H_)
-#define _OSSL_PKCS12_H_
+#define _OSSL_PKCS7_H_
extern VALUE mPKCS12;
extern VALUE cPKCS12;
diff --git a/ext/openssl/ossl_pkcs7.c b/ext/openssl/ossl_pkcs7.c
index 38a7dce7a2..57825e8bb1 100644
--- a/ext/openssl/ossl_pkcs7.c
+++ b/ext/openssl/ossl_pkcs7.c
@@ -44,23 +44,6 @@
GetPKCS7si(obj, p7si); \
} while (0)
-#define WrapPKCS7ri(klass, obj, p7ri) do { \
- if (!p7ri) { \
- ossl_raise(rb_eRuntimeError, "PKCS7ri wasn't initialized."); \
- } \
- obj = Data_Wrap_Struct(klass, 0, PKCS7_RECIP_INFO_free, p7ri); \
-} while (0)
-#define GetPKCS7ri(obj, p7ri) do { \
- Data_Get_Struct(obj, PKCS7_RECIP_INFO, p7ri); \
- if (!p7ri) { \
- ossl_raise(rb_eRuntimeError, "PKCS7ri wasn't initialized."); \
- } \
-} while (0)
-#define SafeGetPKCS7ri(obj, p7ri) do { \
- OSSL_Check_Kind(obj, cPKCS7Recipient); \
- GetPKCS7ri(obj, p7ri); \
-} while (0)
-
#define numberof(ary) (sizeof(ary)/sizeof(ary[0]))
#define ossl_pkcs7_set_data(o,v) rb_iv_set((o), "@data", (v))
@@ -74,7 +57,6 @@
VALUE mPKCS7;
VALUE cPKCS7;
VALUE cPKCS7Signer;
-VALUE cPKCS7Recipient;
VALUE ePKCS7Error;
/*
@@ -107,32 +89,6 @@ DupPKCS7SignerPtr(VALUE obj)
return pkcs7;
}
-static VALUE
-ossl_pkcs7ri_new(PKCS7_RECIP_INFO *p7ri)
-{
- PKCS7_RECIP_INFO *pkcs7;
- VALUE obj;
-
- pkcs7 = p7ri ? PKCS7_RECIP_INFO_dup(p7ri) : PKCS7_RECIP_INFO_new();
- if (!pkcs7) ossl_raise(ePKCS7Error, NULL);
- WrapPKCS7ri(cPKCS7Recipient, obj, pkcs7);
-
- return obj;
-}
-
-static PKCS7_RECIP_INFO *
-DupPKCS7RecipientPtr(VALUE obj)
-{
- PKCS7_RECIP_INFO *p7ri, *pkcs7;
-
- SafeGetPKCS7ri(obj, p7ri);
- if (!(pkcs7 = PKCS7_RECIP_INFO_dup(p7ri))) {
- ossl_raise(ePKCS7Error, NULL);
- }
-
- return pkcs7;
-}
-
/*
* Private
*/
@@ -166,9 +122,9 @@ ossl_pkcs7_s_write_smime(int argc, VALUE *argv, VALUE klass)
int flg;
rb_scan_args(argc, argv, "12", &pkcs7, &data, &flags);
+ SafeGetPKCS7(pkcs7, p7);
flg = NIL_P(flags) ? 0 : NUM2INT(flags);
if(NIL_P(data)) data = ossl_pkcs7_get_data(pkcs7);
- SafeGetPKCS7(pkcs7, p7);
if(!NIL_P(data) && PKCS7_is_detached(p7))
flg |= PKCS7_DETACHED;
in = NIL_P(data) ? NULL : ossl_obj2bio(data);
@@ -444,8 +400,8 @@ ossl_pkcs7_add_signer(VALUE self, VALUE signer)
PKCS7 *pkcs7;
PKCS7_SIGNER_INFO *p7si;
- p7si = DupPKCS7SignerPtr(signer); /* NEED TO DUP */
GetPKCS7(self, pkcs7);
+ p7si = DupPKCS7SignerPtr(signer); /* NEED TO DUP */
if (!PKCS7_add_signer(pkcs7, p7si)) {
PKCS7_SIGNER_INFO_free(p7si);
ossl_raise(ePKCS7Error, "Could not add signer.");
@@ -485,50 +441,30 @@ ossl_pkcs7_get_signer(VALUE self)
}
static VALUE
-ossl_pkcs7_add_recipient(VALUE self, VALUE recip)
+ossl_pkcs7_add_recipient(VALUE self, VALUE cert)
{
PKCS7 *pkcs7;
PKCS7_RECIP_INFO *ri;
-
- ri = DupPKCS7RecipientPtr(recip); /* NEED TO DUP */
+ X509 *x509;
+
GetPKCS7(self, pkcs7);
+ x509 = GetX509CertPtr(cert); /* NO NEED TO DUP */
+ if (!(ri = PKCS7_RECIP_INFO_new())) {
+ ossl_raise(ePKCS7Error, NULL);
+ }
+ if (!PKCS7_RECIP_INFO_set(ri, x509)) {
+ PKCS7_RECIP_INFO_free(ri);
+ ossl_raise(ePKCS7Error, NULL);
+ }
if (!PKCS7_add_recipient_info(pkcs7, ri)) {
PKCS7_RECIP_INFO_free(ri);
- ossl_raise(ePKCS7Error, "Could not add recipient.");
+ ossl_raise(ePKCS7Error, NULL);
}
return self;
}
static VALUE
-ossl_pkcs7_get_recipient(VALUE self)
-{
- PKCS7 *pkcs7;
- STACK_OF(PKCS7_RECIP_INFO) *sk;
- PKCS7_RECIP_INFO *si;
- int num, i;
- VALUE ary;
-
- GetPKCS7(self, pkcs7);
- if (PKCS7_type_is_enveloped(pkcs7))
- sk = pkcs7->d.enveloped->recipientinfo;
- else if (PKCS7_type_is_signedAndEnveloped(pkcs7))
- sk = pkcs7->d.signed_and_enveloped->recipientinfo;
- else sk = NULL;
- if (!sk) return rb_ary_new();
- if ((num = sk_PKCS7_RECIP_INFO_num(sk)) < 0) {
- ossl_raise(ePKCS7Error, "Negative number of recipient!");
- }
- ary = rb_ary_new2(num);
- for (i=0; i<num; i++) {
- si = sk_PKCS7_RECIP_INFO_value(sk, i);
- rb_ary_push(ary, ossl_pkcs7ri_new(si));
- }
-
- return ary;
-}
-
-static VALUE
ossl_pkcs7_add_certificate(VALUE self, VALUE cert)
{
PKCS7 *pkcs7;
@@ -646,7 +582,9 @@ ossl_pkcs7_verify(int argc, VALUE *argv, VALUE self)
VALUE data;
const char *msg;
+ GetPKCS7(self, p7);
rb_scan_args(argc, argv, "22", &certs, &store, &indata, &flags);
+ x509st = GetX509StorePtr(store);
flg = NIL_P(flags) ? 0 : NUM2INT(flags);
if(NIL_P(indata)) indata = ossl_pkcs7_get_data(self);
in = NIL_P(indata) ? NULL : ossl_obj2bio(indata);
@@ -658,8 +596,6 @@ ossl_pkcs7_verify(int argc, VALUE *argv, VALUE self)
rb_jump_tag(status);
}
}
- x509st = GetX509StorePtr(store);
- GetPKCS7(self, p7);
if(!(out = BIO_new(BIO_s_mem()))){
BIO_free(in);
sk_X509_pop_free(x509s, X509_free);
@@ -688,10 +624,10 @@ ossl_pkcs7_decrypt(int argc, VALUE *argv, VALUE self)
VALUE str;
rb_scan_args(argc, argv, "21", &pkey, &cert, &flags);
+ GetPKCS7(self, p7);
key = GetPrivPKeyPtr(pkey); /* NO NEED TO DUP */
x509 = GetX509CertPtr(cert); /* NO NEED TO DUP */
flg = NIL_P(flags) ? 0 : NUM2INT(flags);
- GetPKCS7(self, p7);
if(!(out = BIO_new(BIO_s_mem())))
ossl_raise(ePKCS7Error, NULL);
if(!PKCS7_decrypt(p7, key, x509, out, flg)){
@@ -711,12 +647,13 @@ ossl_pkcs7_add_data(VALUE self, VALUE data)
char buf[4096];
int len;
- in = ossl_obj2bio(data);
+ in = out = NULL;
GetPKCS7(self, pkcs7);
if(PKCS7_type_is_signed(pkcs7)){
if(!PKCS7_content_new(pkcs7, NID_pkcs7_data))
ossl_raise(ePKCS7Error, NULL);
}
+ in = ossl_obj2bio(data);
if(!(out = PKCS7_dataInit(pkcs7, NULL))) goto err;
for(;;){
if((len = BIO_read(in, buf, sizeof(buf))) <= 0)
@@ -802,10 +739,10 @@ ossl_pkcs7si_initialize(VALUE self, VALUE cert, VALUE key, VALUE digest)
X509 *x509;
const EVP_MD *md;
+ GetPKCS7si(self, p7si);
pkey = GetPrivPKeyPtr(key); /* NO NEED TO DUP */
x509 = GetX509CertPtr(cert); /* NO NEED TO DUP */
md = GetDigestPtr(digest);
- GetPKCS7si(self, p7si);
if (!(PKCS7_SIGNER_INFO_set(p7si, x509, pkey, (EVP_MD*)md))) {
ossl_raise(ePKCS7Error, NULL);
}
@@ -814,7 +751,7 @@ ossl_pkcs7si_initialize(VALUE self, VALUE cert, VALUE key, VALUE digest)
}
static VALUE
-ossl_pkcs7si_get_issuer(VALUE self)
+ossl_pkcs7si_get_name(VALUE self)
{
PKCS7_SIGNER_INFO *p7si;
@@ -857,68 +794,6 @@ ossl_pkcs7si_get_signed_time(VALUE self)
}
/*
- * RECIPIENT INFO
- */
-static VALUE
-ossl_pkcs7ri_alloc(VALUE klass)
-{
- PKCS7_RECIP_INFO *p7ri;
- VALUE obj;
-
- if (!(p7ri = PKCS7_RECIP_INFO_new())) {
- ossl_raise(ePKCS7Error, NULL);
- }
- WrapPKCS7ri(klass, obj, p7ri);
-
- return obj;
-}
-
-static VALUE
-ossl_pkcs7ri_initialize(VALUE self, VALUE cert)
-{
- PKCS7_RECIP_INFO *p7ri;
- X509 *x509;
-
- x509 = GetX509CertPtr(cert); /* NO NEED TO DUP */
- GetPKCS7ri(self, p7ri);
- if (!PKCS7_RECIP_INFO_set(p7ri, x509)) {
- ossl_raise(ePKCS7Error, NULL);
- }
-
- return self;
-}
-
-static VALUE
-ossl_pkcs7ri_get_issuer(VALUE self)
-{
- PKCS7_RECIP_INFO *p7ri;
-
- GetPKCS7ri(self, p7ri);
-
- return ossl_x509name_new(p7ri->issuer_and_serial->issuer);
-}
-
-static VALUE
-ossl_pkcs7ri_get_serial(VALUE self)
-{
- PKCS7_RECIP_INFO *p7ri;
-
- GetPKCS7ri(self, p7ri);
-
- return asn1integer_to_num(p7ri->issuer_and_serial->serial);
-}
-
-static VALUE
-ossl_pkcs7ri_get_enc_key(VALUE self)
-{
- PKCS7_RECIP_INFO *p7ri;
-
- GetPKCS7ri(self, p7ri);
-
- return asn1str_to_str(p7ri->enc_key);
-}
-
-/*
* INIT
*/
void
@@ -947,7 +822,6 @@ Init_ossl_pkcs7()
rb_define_method(cPKCS7, "add_signer", ossl_pkcs7_add_signer, 1);
rb_define_method(cPKCS7, "signers", ossl_pkcs7_get_signer, 0);
rb_define_method(cPKCS7, "add_recipient", ossl_pkcs7_add_recipient, 1);
- rb_define_method(cPKCS7, "recipients", ossl_pkcs7_get_recipient, 0);
rb_define_method(cPKCS7, "add_certificate", ossl_pkcs7_add_certificate, 1);
rb_define_method(cPKCS7, "certificates=", ossl_pkcs7_set_certificates, 1);
rb_define_method(cPKCS7, "certificates", ossl_pkcs7_get_certificates, 0);
@@ -962,21 +836,12 @@ Init_ossl_pkcs7()
rb_define_alias(cPKCS7, "to_s", "to_pem");
rb_define_method(cPKCS7, "to_der", ossl_pkcs7_to_der, 0);
- cPKCS7Signer = rb_define_class_under(mPKCS7, "SignerInfo", rb_cObject);
- rb_define_const(mPKCS7, "Signer", cPKCS7Signer);
+ cPKCS7Signer = rb_define_class_under(mPKCS7, "Signer", rb_cObject);
rb_define_alloc_func(cPKCS7Signer, ossl_pkcs7si_alloc);
rb_define_method(cPKCS7Signer, "initialize", ossl_pkcs7si_initialize,3);
- rb_define_method(cPKCS7Signer, "issuer", ossl_pkcs7si_get_issuer, 0);
- rb_define_alias(cPKCS7Signer, "name", "issuer");
+ rb_define_method(cPKCS7Signer, "name", ossl_pkcs7si_get_name,0);
rb_define_method(cPKCS7Signer, "serial", ossl_pkcs7si_get_serial,0);
- rb_define_method(cPKCS7Signer,"signed_time",ossl_pkcs7si_get_signed_time,0);
-
- cPKCS7Recipient = rb_define_class_under(mPKCS7,"RecipientInfo",rb_cObject);
- rb_define_alloc_func(cPKCS7Recipient, ossl_pkcs7ri_alloc);
- rb_define_method(cPKCS7Recipient, "initialize", ossl_pkcs7ri_initialize,1);
- rb_define_method(cPKCS7Recipient, "issuer", ossl_pkcs7ri_get_issuer,0);
- rb_define_method(cPKCS7Recipient, "serial", ossl_pkcs7ri_get_serial,0);
- rb_define_method(cPKCS7Recipient, "enc_key", ossl_pkcs7ri_get_enc_key,0);
+ rb_define_method(cPKCS7Signer, "signed_time", ossl_pkcs7si_get_signed_time,0);
#define DefPKCS7Const(x) rb_define_const(mPKCS7, #x, INT2NUM(PKCS7_##x))
diff --git a/ext/openssl/ossl_pkcs7.h b/ext/openssl/ossl_pkcs7.h
index f5942d65db..9378397f25 100644
--- a/ext/openssl/ossl_pkcs7.h
+++ b/ext/openssl/ossl_pkcs7.h
@@ -13,8 +13,7 @@
extern VALUE mPKCS7;
extern VALUE cPKCS7;
-extern VALUE cPKCS7Signer;
-extern VALUE cPKCS7Recipient;
+extern VALUE cPKCS7SignerInfo;
extern VALUE ePKCS7Error;
void Init_ossl_pkcs7(void);
diff --git a/ext/openssl/ossl_pkey.c b/ext/openssl/ossl_pkey.c
index db70333047..1a38a2c1d7 100644
--- a/ext/openssl/ossl_pkey.c
+++ b/ext/openssl/ossl_pkey.c
@@ -96,21 +96,10 @@ GetPrivPKeyPtr(VALUE obj)
{
EVP_PKEY *pkey;
- if (rb_funcall(obj, id_private_q, 0, NULL) != Qtrue) {
+ SafeGetPKey(obj, pkey);
+ if (rb_funcall(obj, id_private_q, 0, NULL) != Qtrue) { /* returns Qtrue */
ossl_raise(rb_eArgError, "Private key is needed.");
}
- SafeGetPKey(obj, pkey);
-
- return pkey;
-}
-
-EVP_PKEY *
-DupPKeyPtr(VALUE obj)
-{
- EVP_PKEY *pkey;
-
- SafeGetPKey(obj, pkey);
- CRYPTO_add(&pkey->references, 1, CRYPTO_LOCK_EVP_PKEY);
return pkey;
}
@@ -120,10 +109,10 @@ DupPrivPKeyPtr(VALUE obj)
{
EVP_PKEY *pkey;
- if (rb_funcall(obj, id_private_q, 0, NULL) != Qtrue) {
+ SafeGetPKey(obj, pkey);
+ if (rb_funcall(obj, id_private_q, 0, NULL) != Qtrue) { /* returns Qtrue */
ossl_raise(rb_eArgError, "Private key is needed.");
}
- SafeGetPKey(obj, pkey);
CRYPTO_add(&pkey->references, 1, CRYPTO_LOCK_EVP_PKEY);
return pkey;
@@ -163,10 +152,10 @@ ossl_pkey_sign(VALUE self, VALUE digest, VALUE data)
int buf_len;
VALUE str;
+ GetPKey(self, pkey);
if (rb_funcall(self, id_private_q, 0, NULL) != Qtrue) {
ossl_raise(rb_eArgError, "Private key is needed.");
}
- GetPKey(self, pkey);
EVP_SignInit(&ctx, GetDigestPtr(digest));
StringValue(data);
EVP_SignUpdate(&ctx, RSTRING(data)->ptr, RSTRING(data)->len);
diff --git a/ext/openssl/ossl_pkey.h b/ext/openssl/ossl_pkey.h
index 880a104675..189573546e 100644
--- a/ext/openssl/ossl_pkey.h
+++ b/ext/openssl/ossl_pkey.h
@@ -16,16 +16,11 @@ extern VALUE cPKey;
extern VALUE ePKeyError;
extern ID id_private_q;
-#define OSSL_PKEY_SET_PRIVATE(obj) rb_iv_set((obj), "private", Qtrue)
-#define OSSL_PKEY_SET_PUBLIC(obj) rb_iv_set((obj), "private", Qfalse)
-#define OSSL_PKEY_IS_PRIVATE(obj) (rb_iv_get((obj), "private") == Qtrue)
-
#define WrapPKey(klass, obj, pkey) do { \
if (!pkey) { \
rb_raise(rb_eRuntimeError, "PKEY wasn't initialized!"); \
} \
obj = Data_Wrap_Struct(klass, 0, EVP_PKEY_free, pkey); \
- OSSL_PKEY_SET_PUBLIC(obj); \
} while (0)
#define GetPKey(obj, pkey) do {\
Data_Get_Struct(obj, EVP_PKEY, pkey);\
@@ -43,7 +38,7 @@ void ossl_generate_cb(int, int, void *);
VALUE ossl_pkey_new(EVP_PKEY *);
VALUE ossl_pkey_new_from_file(VALUE);
EVP_PKEY *GetPKeyPtr(VALUE);
-EVP_PKEY *DupPKeyPtr(VALUE);
+/*EVP_PKEY *DupPKeyPtr(VALUE);*/
EVP_PKEY *GetPrivPKeyPtr(VALUE);
EVP_PKEY *DupPrivPKeyPtr(VALUE);
void Init_ossl_pkey(void);
@@ -71,8 +66,6 @@ void Init_ossl_dsa(void);
*/
extern VALUE cDH;
extern VALUE eDHError;
-extern DH *OSSL_DEFAULT_DH_512;
-extern DH *OSSL_DEFAULT_DH_1024;
VALUE ossl_dh_new(EVP_PKEY *);
void Init_ossl_dh(void);
@@ -111,10 +104,10 @@ static VALUE ossl_##keytype##_set_##name(VALUE self, VALUE bignum) \
return bignum; \
}
-#define DEF_OSSL_PKEY_BN(class, keytype, name) \
-do { \
+#define DEF_OSSL_PKEY_BN(class, keytype, name) \
+do { \
rb_define_method(class, #name, ossl_##keytype##_get_##name, 0); \
- rb_define_method(class, #name "=", ossl_##keytype##_set_##name, 1);\
+ rb_define_method(class, #name "=", ossl_##keytype##_set_##name, 1); \
} while (0)
#endif /* _OSSL_PKEY_H_ */
diff --git a/ext/openssl/ossl_pkey_dh.c b/ext/openssl/ossl_pkey_dh.c
index 5b728ba353..7070cf03f4 100644
--- a/ext/openssl/ossl_pkey_dh.c
+++ b/ext/openssl/ossl_pkey_dh.c
@@ -350,78 +350,18 @@ OSSL_PKEY_BN(dh, pub_key);
OSSL_PKEY_BN(dh, priv_key);
/*
- * -----BEGIN DH PARAMETERS-----
- * MEYCQQD0zXHljRg/mJ9PYLACLv58Cd8VxBxxY7oEuCeURMiTqEhMym16rhhKgZG2
- * zk2O9uUIBIxSj+NKMURHGaFKyIvLAgEC
- * -----END DH PARAMETERS-----
- */
-static unsigned char DEFAULT_DH_512_PRIM[] = {
- 0xf4, 0xcd, 0x71, 0xe5, 0x8d, 0x18, 0x3f, 0x98,
- 0x9f, 0x4f, 0x60, 0xb0, 0x02, 0x2e, 0xfe, 0x7c,
- 0x09, 0xdf, 0x15, 0xc4, 0x1c, 0x71, 0x63, 0xba,
- 0x04, 0xb8, 0x27, 0x94, 0x44, 0xc8, 0x93, 0xa8,
- 0x48, 0x4c, 0xca, 0x6d, 0x7a, 0xae, 0x18, 0x4a,
- 0x81, 0x91, 0xb6, 0xce, 0x4d, 0x8e, 0xf6, 0xe5,
- 0x08, 0x04, 0x8c, 0x52, 0x8f, 0xe3, 0x4a, 0x31,
- 0x44, 0x47, 0x19, 0xa1, 0x4a, 0xc8, 0x8b, 0xcb,
-};
-static unsigned char DEFAULT_DH_512_GEN[] = { 0x02 };
-DH *OSSL_DEFAULT_DH_512 = NULL;
-
-/*
- * -----BEGIN DH PARAMETERS-----
- * MIGHAoGBAJ0lOVy0VIr/JebWn0zDwY2h+rqITFOpdNr6ugsgvkDXuucdcChhYExJ
- * AV/ZD2AWPbrTqV76mGRgJg4EddgT1zG0jq3rnFdMj2XzkBYx3BVvfR0Arnby0RHR
- * T4h7KZ/2zmjvV+eF8kBUHBJAojUlzxKj4QeO2x20FP9X5xmNUXeDAgEC
- * -----END DH PARAMETERS-----
- */
-static unsigned char DEFAULT_DH_1024_PRIM[] = {
- 0x9d, 0x25, 0x39, 0x5c, 0xb4, 0x54, 0x8a, 0xff,
- 0x25, 0xe6, 0xd6, 0x9f, 0x4c, 0xc3, 0xc1, 0x8d,
- 0xa1, 0xfa, 0xba, 0x88, 0x4c, 0x53, 0xa9, 0x74,
- 0xda, 0xfa, 0xba, 0x0b, 0x20, 0xbe, 0x40, 0xd7,
- 0xba, 0xe7, 0x1d, 0x70, 0x28, 0x61, 0x60, 0x4c,
- 0x49, 0x01, 0x5f, 0xd9, 0x0f, 0x60, 0x16, 0x3d,
- 0xba, 0xd3, 0xa9, 0x5e, 0xfa, 0x98, 0x64, 0x60,
- 0x26, 0x0e, 0x04, 0x75, 0xd8, 0x13, 0xd7, 0x31,
- 0xb4, 0x8e, 0xad, 0xeb, 0x9c, 0x57, 0x4c, 0x8f,
- 0x65, 0xf3, 0x90, 0x16, 0x31, 0xdc, 0x15, 0x6f,
- 0x7d, 0x1d, 0x00, 0xae, 0x76, 0xf2, 0xd1, 0x11,
- 0xd1, 0x4f, 0x88, 0x7b, 0x29, 0x9f, 0xf6, 0xce,
- 0x68, 0xef, 0x57, 0xe7, 0x85, 0xf2, 0x40, 0x54,
- 0x1c, 0x12, 0x40, 0xa2, 0x35, 0x25, 0xcf, 0x12,
- 0xa3, 0xe1, 0x07, 0x8e, 0xdb, 0x1d, 0xb4, 0x14,
- 0xff, 0x57, 0xe7, 0x19, 0x8d, 0x51, 0x77, 0x83
-};
-static unsigned char DEFAULT_DH_1024_GEN[] = { 0x02 };
-DH *OSSL_DEFAULT_DH_1024 = NULL;
-
-static DH*
-ossl_create_dh(unsigned char *p, size_t plen, unsigned char *g, size_t glen)
-{
- DH *dh;
-
- if ((dh = DH_new()) == NULL) ossl_raise(eDHError, NULL);
- dh->p = BN_bin2bn(p, plen, NULL);
- dh->g = BN_bin2bn(g, glen, NULL);
- if (dh->p == NULL || dh->g == NULL){
- DH_free(dh);
- ossl_raise(eDHError, NULL);
- }
-
- return dh;
-}
-
-/*
* INIT
*/
void
Init_ossl_dh()
{
eDHError = rb_define_class_under(mPKey, "DHError", ePKeyError);
+
cDH = rb_define_class_under(mPKey, "DH", cPKey);
+
rb_define_singleton_method(cDH, "generate", ossl_dh_s_generate, -1);
rb_define_method(cDH, "initialize", ossl_dh_initialize, -1);
+
rb_define_method(cDH, "public?", ossl_dh_is_public, 0);
rb_define_method(cDH, "private?", ossl_dh_is_private, 0);
rb_define_method(cDH, "to_text", ossl_dh_to_text, 0);
@@ -430,25 +370,22 @@ Init_ossl_dh()
rb_define_alias(cDH, "to_s", "export");
rb_define_method(cDH, "to_der", ossl_dh_to_der, 0);
rb_define_method(cDH, "public_key", ossl_dh_to_public_key, 0);
+
rb_define_method(cDH, "params_ok?", ossl_dh_check_params, 0);
rb_define_method(cDH, "generate_key!", ossl_dh_generate_key, 0);
rb_define_method(cDH, "compute_key", ossl_dh_compute_key, 1);
+
DEF_OSSL_PKEY_BN(cDH, dh, p);
DEF_OSSL_PKEY_BN(cDH, dh, g);
DEF_OSSL_PKEY_BN(cDH, dh, pub_key);
DEF_OSSL_PKEY_BN(cDH, dh, priv_key);
- rb_define_method(cDH, "params", ossl_dh_get_params, 0);
- OSSL_DEFAULT_DH_512 = ossl_create_dh(
- DEFAULT_DH_512_PRIM, sizeof(DEFAULT_DH_512_PRIM),
- DEFAULT_DH_512_GEN, sizeof(DEFAULT_DH_512_GEN));
- OSSL_DEFAULT_DH_1024 = ossl_create_dh(
- DEFAULT_DH_1024_PRIM, sizeof(DEFAULT_DH_1024_PRIM),
- DEFAULT_DH_1024_GEN, sizeof(DEFAULT_DH_1024_GEN));
+ rb_define_method(cDH, "params", ossl_dh_get_params, 0);
}
#else /* defined NO_DH */
# warning >>> OpenSSL is compiled without DH support <<<
+
void
Init_ossl_dh()
{
diff --git a/ext/openssl/ossl_pkey_dsa.c b/ext/openssl/ossl_pkey_dsa.c
index 39b1902d57..daa0f4cd83 100644
--- a/ext/openssl/ossl_pkey_dsa.c
+++ b/ext/openssl/ossl_pkey_dsa.c
@@ -20,7 +20,13 @@
} while (0)
#define DSA_HAS_PRIVATE(dsa) ((dsa)->priv_key)
-#define DSA_PRIVATE(obj,dsa) (DSA_HAS_PRIVATE(dsa)||OSSL_PKEY_IS_PRIVATE(obj))
+
+#ifdef OSSL_ENGINE_ENABLED
+# define DSA_PRIVATE(dsa) (DSA_HAS_PRIVATE(dsa) || (dsa)->engine)
+#else
+# define DSA_PRIVATE(dsa) DSA_HAS_PRIVATE(dsa)
+#endif
+
/*
* Classes
@@ -184,7 +190,7 @@ ossl_dsa_is_private(VALUE self)
GetPKeyDSA(self, pkey);
- return (DSA_PRIVATE(self, pkey->pkey.dsa)) ? Qtrue : Qfalse;
+ return (DSA_PRIVATE(pkey->pkey.dsa)) ? Qtrue : Qfalse;
}
static VALUE
@@ -330,7 +336,7 @@ ossl_dsa_sign(VALUE self, VALUE data)
GetPKeyDSA(self, pkey);
StringValue(data);
- if (!DSA_PRIVATE(self, pkey->pkey.dsa)) {
+ if (!DSA_PRIVATE(pkey->pkey.dsa)) {
ossl_raise(eDSAError, "Private DSA key needed!");
}
str = rb_str_new(0, ossl_dsa_buf_size(pkey));
diff --git a/ext/openssl/ossl_pkey_rsa.c b/ext/openssl/ossl_pkey_rsa.c
index 17bec2b7bb..f8b3ae1387 100644
--- a/ext/openssl/ossl_pkey_rsa.c
+++ b/ext/openssl/ossl_pkey_rsa.c
@@ -20,7 +20,12 @@
} while (0)
#define RSA_HAS_PRIVATE(rsa) ((rsa)->p && (rsa)->q)
-#define RSA_PRIVATE(obj,rsa) (RSA_HAS_PRIVATE(rsa)||OSSL_PKEY_IS_PRIVATE(obj))
+
+#ifdef OSSL_ENGINE_ENABLED
+# define RSA_PRIVATE(rsa) (RSA_HAS_PRIVATE(rsa) || (rsa)->engine)
+#else
+# define RSA_PRIVATE(rsa) RSA_HAS_PRIVATE(rsa)
+#endif
/*
* Classes
@@ -176,8 +181,8 @@ ossl_rsa_is_private(VALUE self)
EVP_PKEY *pkey;
GetPKeyRSA(self, pkey);
-
- return (RSA_PRIVATE(self, pkey->pkey.rsa)) ? Qtrue : Qfalse;
+
+ return (RSA_PRIVATE(pkey->pkey.rsa)) ? Qtrue : Qfalse;
}
static VALUE
@@ -247,20 +252,18 @@ ossl_rsa_to_der(VALUE self)
#define ossl_rsa_buf_size(pkey) (RSA_size((pkey)->pkey.rsa)+16)
static VALUE
-ossl_rsa_public_encrypt(int argc, VALUE *argv, VALUE self)
+ossl_rsa_public_encrypt(VALUE self, VALUE buffer)
{
EVP_PKEY *pkey;
- int buf_len, pad;
- VALUE str, buffer, padding;
-
+ int buf_len;
+ VALUE str;
+
GetPKeyRSA(self, pkey);
- rb_scan_args(argc, argv, "11", &buffer, &padding);
- pad = (argc == 1) ? RSA_PKCS1_PADDING : NUM2INT(padding);
StringValue(buffer);
str = rb_str_new(0, ossl_rsa_buf_size(pkey));
buf_len = RSA_public_encrypt(RSTRING(buffer)->len, RSTRING(buffer)->ptr,
RSTRING(str)->ptr, pkey->pkey.rsa,
- pad);
+ RSA_PKCS1_PADDING);
if (buf_len < 0) ossl_raise(eRSAError, NULL);
RSTRING(str)->len = buf_len;
RSTRING(str)->ptr[buf_len] = 0;
@@ -269,21 +272,19 @@ ossl_rsa_public_encrypt(int argc, VALUE *argv, VALUE self)
}
static VALUE
-ossl_rsa_public_decrypt(int argc, VALUE *argv, VALUE self)
+ossl_rsa_public_decrypt(VALUE self, VALUE buffer)
{
EVP_PKEY *pkey;
- int buf_len, pad;
- VALUE str, buffer, padding;
+ int buf_len;
+ VALUE str;
GetPKeyRSA(self, pkey);
- rb_scan_args(argc, argv, "11", &buffer, &padding);
- pad = (argc == 1) ? RSA_PKCS1_PADDING : NUM2INT(padding);
StringValue(buffer);
str = rb_str_new(0, ossl_rsa_buf_size(pkey));
buf_len = RSA_public_decrypt(RSTRING(buffer)->len, RSTRING(buffer)->ptr,
RSTRING(str)->ptr, pkey->pkey.rsa,
- pad);
- if (buf_len < 0) ossl_raise(eRSAError, NULL);
+ RSA_PKCS1_PADDING);
+ if(buf_len < 0) ossl_raise(eRSAError, NULL);
RSTRING(str)->len = buf_len;
RSTRING(str)->ptr[buf_len] = 0;
@@ -291,23 +292,21 @@ ossl_rsa_public_decrypt(int argc, VALUE *argv, VALUE self)
}
static VALUE
-ossl_rsa_private_encrypt(int argc, VALUE *argv, VALUE self)
+ossl_rsa_private_encrypt(VALUE self, VALUE buffer)
{
EVP_PKEY *pkey;
- int buf_len, pad;
- VALUE str, buffer, padding;
-
+ int buf_len;
+ VALUE str;
+
GetPKeyRSA(self, pkey);
- if (!RSA_PRIVATE(self, pkey->pkey.rsa)) {
- ossl_raise(eRSAError, "private key needed.");
+ if (!RSA_PRIVATE(pkey->pkey.rsa)) {
+ ossl_raise(eRSAError, "PRIVATE key needed for this operation!");
}
- rb_scan_args(argc, argv, "11", &buffer, &padding);
- pad = (argc == 1) ? RSA_PKCS1_PADDING : NUM2INT(padding);
StringValue(buffer);
str = rb_str_new(0, ossl_rsa_buf_size(pkey));
buf_len = RSA_private_encrypt(RSTRING(buffer)->len, RSTRING(buffer)->ptr,
RSTRING(str)->ptr, pkey->pkey.rsa,
- pad);
+ RSA_PKCS1_PADDING);
if (buf_len < 0) ossl_raise(eRSAError, NULL);
RSTRING(str)->len = buf_len;
RSTRING(str)->ptr[buf_len] = 0;
@@ -316,23 +315,21 @@ ossl_rsa_private_encrypt(int argc, VALUE *argv, VALUE self)
}
static VALUE
-ossl_rsa_private_decrypt(int argc, VALUE *argv, VALUE self)
+ossl_rsa_private_decrypt(VALUE self, VALUE buffer)
{
EVP_PKEY *pkey;
- int buf_len, pad;
- VALUE str, buffer, padding;
+ int buf_len;
+ VALUE str;
GetPKeyRSA(self, pkey);
- if (!RSA_PRIVATE(self, pkey->pkey.rsa)) {
- ossl_raise(eRSAError, "private key needed.");
+ if (!RSA_PRIVATE(pkey->pkey.rsa)) {
+ ossl_raise(eRSAError, "Private RSA key needed!");
}
- rb_scan_args(argc, argv, "11", &buffer, &padding);
- pad = (argc == 1) ? RSA_PKCS1_PADDING : NUM2INT(padding);
StringValue(buffer);
str = rb_str_new(0, ossl_rsa_buf_size(pkey));
buf_len = RSA_private_decrypt(RSTRING(buffer)->len, RSTRING(buffer)->ptr,
RSTRING(str)->ptr, pkey->pkey.rsa,
- pad);
+ RSA_PKCS1_PADDING);
if (buf_len < 0) ossl_raise(eRSAError, NULL);
RSTRING(str)->len = buf_len;
RSTRING(str)->ptr[buf_len] = 0;
@@ -454,8 +451,6 @@ OSSL_PKEY_BN(rsa, iqmp);
/*
* INIT
*/
-#define DefRSAConst(x) rb_define_const(cRSA, #x,INT2FIX(RSA_##x))
-
void
Init_ossl_rsa()
{
@@ -474,10 +469,10 @@ Init_ossl_rsa()
rb_define_alias(cRSA, "to_s", "export");
rb_define_method(cRSA, "to_der", ossl_rsa_to_der, 0);
rb_define_method(cRSA, "public_key", ossl_rsa_to_public_key, 0);
- rb_define_method(cRSA, "public_encrypt", ossl_rsa_public_encrypt, -1);
- rb_define_method(cRSA, "public_decrypt", ossl_rsa_public_decrypt, -1);
- rb_define_method(cRSA, "private_encrypt", ossl_rsa_private_encrypt, -1);
- rb_define_method(cRSA, "private_decrypt", ossl_rsa_private_decrypt, -1);
+ rb_define_method(cRSA, "public_encrypt", ossl_rsa_public_encrypt, 1);
+ rb_define_method(cRSA, "public_decrypt", ossl_rsa_public_decrypt, 1);
+ rb_define_method(cRSA, "private_encrypt", ossl_rsa_private_encrypt, 1);
+ rb_define_method(cRSA, "private_decrypt", ossl_rsa_private_decrypt, 1);
DEF_OSSL_PKEY_BN(cRSA, rsa, n);
DEF_OSSL_PKEY_BN(cRSA, rsa, e);
@@ -490,11 +485,6 @@ Init_ossl_rsa()
rb_define_method(cRSA, "params", ossl_rsa_get_params, 0);
- DefRSAConst(PKCS1_PADDING);
- DefRSAConst(SSLV23_PADDING);
- DefRSAConst(NO_PADDING);
- DefRSAConst(PKCS1_OAEP_PADDING);
-
/*
* TODO: Test it
rb_define_method(cRSA, "blinding_on!", ossl_rsa_blinding_on, 0);
diff --git a/ext/openssl/ossl_ssl.c b/ext/openssl/ossl_ssl.c
index 640c3386df..4d8a64fc11 100644
--- a/ext/openssl/ossl_ssl.c
+++ b/ext/openssl/ossl_ssl.c
@@ -45,9 +45,6 @@ VALUE cSSLSocket;
#define ossl_sslctx_set_options(o,v) rb_iv_set((o),"@options",(v))
#define ossl_sslctx_set_cert_store(o,v) rb_iv_set((o),"@cert_store",(v))
#define ossl_sslctx_set_extra_cert(o,v) rb_iv_set((o),"@extra_chain_cert",(v))
-#define ossl_sslctx_set_client_cert_cb(o,v) rb_iv_set((o),"@client_cert_cb",(v))
-#define ossl_sslctx_set_tmp_dh_cb(o,v) rb_iv_set((o),"@tmp_dh_callback",(v))
-#define ossl_sslctx_set_sess_id_ctx(o, v) rb_iv_get((o),"@session_id_context"(v))
#define ossl_sslctx_get_cert(o) rb_iv_get((o),"@cert")
#define ossl_sslctx_get_key(o) rb_iv_get((o),"@key")
@@ -61,37 +58,13 @@ VALUE cSSLSocket;
#define ossl_sslctx_get_options(o) rb_iv_get((o),"@options")
#define ossl_sslctx_get_cert_store(o) rb_iv_get((o),"@cert_store")
#define ossl_sslctx_get_extra_cert(o) rb_iv_get((o),"@extra_chain_cert")
-#define ossl_sslctx_get_client_cert_cb(o) rb_iv_get((o),"@client_cert_cb")
-#define ossl_sslctx_get_tmp_dh_cb(o) rb_iv_get((o),"@tmp_dh_callback")
-#define ossl_sslctx_get_sess_id_ctx(o) rb_iv_get((o),"@session_id_context")
static char *ossl_sslctx_attrs[] = {
"cert", "key", "client_ca", "ca_file", "ca_path",
"timeout", "verify_mode", "verify_depth",
- "verify_callback", "options", "cert_store", "extra_chain_cert",
- "client_cert_cb", "tmp_dh_callback", "session_id_context",
+ "verify_callback", "options", "cert_store", "extra_chain_cert"
};
-#define ossl_ssl_get_io(o) rb_iv_get((o),"@io")
-#define ossl_ssl_get_ctx(o) rb_iv_get((o),"@context")
-#define ossl_ssl_get_sync_close(o) rb_iv_get((o),"@sync_close")
-#define ossl_ssl_get_x509(o) rb_iv_get((o),"@x509")
-#define ossl_ssl_get_key(o) rb_iv_get((o),"@key")
-#define ossl_ssl_get_tmp_dh(o) rb_iv_get((o),"@tmp_dh")
-
-#define ossl_ssl_set_io(o,v) rb_iv_set((o),"@io",(v))
-#define ossl_ssl_set_ctx(o,v) rb_iv_set((o),"@context",(v))
-#define ossl_ssl_set_sync_close(o,v) rb_iv_set((o),"@sync_close",(v))
-#define ossl_ssl_set_x509(o,v) rb_iv_set((o),"@x509",(v))
-#define ossl_ssl_set_key(o,v) rb_iv_set((o),"@key",(v))
-#define ossl_ssl_set_tmp_dh(o,v) rb_iv_set((o),"@tmp_dh",(v))
-
-static char *ossl_ssl_attr_readers[] = { "io", "context", };
-static char *ossl_ssl_attrs[] = { "sync_close", };
-
-/*
- * SSLContext class
- */
struct {
const char *name;
SSL_METHOD *(*func)(void);
@@ -114,9 +87,6 @@ struct {
int ossl_ssl_ex_vcb_idx;
int ossl_ssl_ex_store_p;
-int ossl_ssl_ex_ptr_idx;
-int ossl_ssl_ex_client_cert_cb_idx;
-int ossl_ssl_ex_tmp_dh_callback_idx;
static void
ossl_sslctx_free(SSL_CTX *ctx)
@@ -149,6 +119,8 @@ ossl_sslctx_initialize(int argc, VALUE *argv, VALUE self)
int i;
char *s;
+ Data_Get_Struct(self, SSL_CTX, ctx);
+
for(i = 0; i < numberof(ossl_sslctx_attrs); i++){
char buf[32];
snprintf(buf, sizeof(buf), "@%s", ossl_sslctx_attrs[i]);
@@ -170,7 +142,6 @@ ossl_sslctx_initialize(int argc, VALUE *argv, VALUE self)
if (!method) {
ossl_raise(rb_eArgError, "unknown SSL method `%s'.", s);
}
- Data_Get_Struct(self, SSL_CTX, ctx);
if (SSL_CTX_set_ssl_version(ctx, method) != 1) {
ossl_raise(eSSLError, "SSL_CTX_set_ssl_version:");
}
@@ -178,89 +149,6 @@ ossl_sslctx_initialize(int argc, VALUE *argv, VALUE self)
return self;
}
-static VALUE
-ossl_call_client_cert_cb(VALUE obj)
-{
- VALUE cb, ary, cert, key;
- SSL *ssl;
-
- Data_Get_Struct(obj, SSL, ssl);
- cb = (VALUE)SSL_get_ex_data(ssl, ossl_ssl_ex_client_cert_cb_idx);
- if (NIL_P(cb)) return Qfalse;
- ary = rb_funcall(cb, rb_intern("call"), 1, obj);
- Check_Type(ary, T_ARRAY);
- GetX509CertPtr(cert = rb_ary_entry(ary, 0));
- GetPKeyPtr(key = rb_ary_entry(ary, 1));
- ossl_ssl_set_x509(obj, cert);
- ossl_ssl_set_key(obj, key);
-
- return Qtrue;
-}
-
-static int
-ossl_client_cert_cb(SSL *ssl, X509 **x509, EVP_PKEY **pkey)
-{
- VALUE obj;
- int status, success;
-
- obj = (VALUE)SSL_get_ex_data(ssl, ossl_ssl_ex_ptr_idx);
- success = rb_protect((VALUE(*)_((VALUE)))ossl_call_client_cert_cb,
- obj, &status);
- if (status || !success) return 0;
- *x509 = DupX509CertPtr(ossl_ssl_get_x509(obj));
- *pkey = DupPKeyPtr(ossl_ssl_get_key(obj));
-
- return 1;
-}
-
-#if !defined(OPENSSL_NO_DH)
-static VALUE
-ossl_call_tmp_dh_callback(VALUE *args)
-{
- SSL *ssl;
- VALUE cb, dh;
- EVP_PKEY *pkey;
-
- Data_Get_Struct(args[0], SSL, ssl);
- cb = (VALUE)SSL_get_ex_data(ssl, ossl_ssl_ex_tmp_dh_callback_idx);
- if (NIL_P(cb)) return Qfalse;
- dh = rb_funcall(cb, rb_intern("call"), 3, args[0], args[1], args[2]);
- pkey = GetPKeyPtr(dh);
- if (EVP_PKEY_type(pkey->type) != EVP_PKEY_DH) return Qfalse;
- ossl_ssl_set_tmp_dh(args[0], dh);
-
- return Qtrue;
-}
-
-static DH*
-ossl_tmp_dh_callback(SSL *ssl, int is_export, int keylength)
-{
- VALUE args[3];
- int status, success;
-
- args[0] = (VALUE)SSL_get_ex_data(ssl, ossl_ssl_ex_ptr_idx);
- args[1] = INT2FIX(is_export);
- args[2] = INT2FIX(keylength);
- success = rb_protect((VALUE(*)_((VALUE)))ossl_call_tmp_dh_callback,
- (VALUE)args, &status);
- if (status || !success) return NULL;
-
- return GetPKeyPtr(ossl_ssl_get_tmp_dh(args[0]))->pkey.dh;
-}
-
-static DH*
-ossl_default_tmp_dh_callback(SSL *ssl, int is_export, int keylength)
-{
- switch(keylength){
- case 512:
- return OSSL_DEFAULT_DH_512;
- case 1024:
- return OSSL_DEFAULT_DH_1024;
- }
- return NULL;
-}
-#endif /* OPENSSL_NO_DH */
-
static int
ossl_ssl_verify_callback(int preverify_ok, X509_STORE_CTX *ctx)
{
@@ -302,16 +190,6 @@ ossl_sslctx_setup(VALUE self)
if(OBJ_FROZEN(self)) return Qnil;
Data_Get_Struct(self, SSL_CTX, ctx);
-#if !defined(OPENSSL_NO_DH)
- if (RTEST(ossl_sslctx_get_tmp_dh_cb(self))){
- SSL_CTX_set_tmp_dh_callback(ctx, ossl_tmp_dh_callback);
- }
- else{
- rb_warning("using default DH parameters.");
- SSL_CTX_set_tmp_dh_callback(ctx, ossl_default_tmp_dh_callback);
- }
-#endif
-
val = ossl_sslctx_get_cert_store(self);
if(!NIL_P(val)){
/*
@@ -381,8 +259,6 @@ ossl_sslctx_setup(VALUE self)
val = ossl_sslctx_get_verify_mode(self);
verify_mode = NIL_P(val) ? SSL_VERIFY_NONE : NUM2INT(val);
SSL_CTX_set_verify(ctx, verify_mode, ossl_ssl_verify_callback);
- if (RTEST(ossl_sslctx_get_client_cert_cb(self)))
- SSL_CTX_set_client_cert_cb(ctx, ossl_client_cert_cb);
val = ossl_sslctx_get_timeout(self);
if(!NIL_P(val)) SSL_CTX_set_timeout(ctx, NUM2LONG(val));
@@ -394,15 +270,6 @@ ossl_sslctx_setup(VALUE self)
if(!NIL_P(val)) SSL_CTX_set_options(ctx, NUM2LONG(val));
rb_obj_freeze(self);
- val = ossl_sslctx_get_sess_id_ctx(self);
- if (!NIL_P(val)){
- StringValue(val);
- if (!SSL_CTX_set_session_id_context(ctx, RSTRING(val)->ptr,
- RSTRING(val)->len)){
- ossl_raise(eSSLError, "SSL_CTX_set_session_id_context:");
- }
- }
-
return Qtrue;
}
@@ -458,9 +325,13 @@ ossl_sslctx_set_ciphers(VALUE self, VALUE v)
int i;
rb_check_frozen(self);
- if (NIL_P(v))
- return v;
- else if (TYPE(v) == T_ARRAY) {
+ Data_Get_Struct(self, SSL_CTX, ctx);
+ if(!ctx){
+ ossl_raise(eSSLError, "SSL_CTX is not initialized.");
+ return Qnil;
+ }
+
+ if (TYPE(v) == T_ARRAY) {
str = rb_str_new2(NULL);
for (i = 0; i < RARRAY(v)->len; i++) {
elem = rb_ary_entry(v, i);
@@ -474,21 +345,26 @@ ossl_sslctx_set_ciphers(VALUE self, VALUE v)
StringValue(str);
}
- Data_Get_Struct(self, SSL_CTX, ctx);
- if(!ctx){
- ossl_raise(eSSLError, "SSL_CTX is not initialized.");
- return Qnil;
- }
if (!SSL_CTX_set_cipher_list(ctx, RSTRING(str)->ptr)) {
- ossl_raise(eSSLError, "SSL_CTX_set_cipher_list:");
+ ossl_raise(eSSLError, "SSL_CTX_set_ciphers:");
}
-
- return v;
+ return Qnil;
}
/*
* SSLSocket class
*/
+#define ossl_ssl_get_io(o) rb_iv_get((o),"@io")
+#define ossl_ssl_get_ctx(o) rb_iv_get((o),"@context")
+#define ossl_ssl_get_sync_close(o) rb_iv_get((o),"@sync_close")
+
+#define ossl_ssl_set_io(o,v) rb_iv_set((o),"@io",(v))
+#define ossl_ssl_set_ctx(o,v) rb_iv_set((o),"@context",(v))
+#define ossl_ssl_set_sync_close(o,v) rb_iv_set((o),"@sync_close",(v))
+
+static char *ossl_ssl_attr_readers[] = { "io", "context", };
+static char *ossl_ssl_attrs[] = { "sync_close", };
+
static void
ossl_ssl_shutdown(SSL *ssl)
{
@@ -533,7 +409,7 @@ ossl_ssl_initialize(int argc, VALUE *argv, VALUE self)
static VALUE
ossl_ssl_setup(VALUE self)
{
- VALUE io, v_ctx, cb;
+ VALUE io, v_ctx;
SSL_CTX *ctx;
SSL *ssl;
OpenFile *fptr;
@@ -554,65 +430,57 @@ ossl_ssl_setup(VALUE self)
rb_io_check_readable(fptr);
rb_io_check_writable(fptr);
SSL_set_fd(ssl, TO_SOCKET(fileno(fptr->f)));
- SSL_set_ex_data(ssl, ossl_ssl_ex_ptr_idx, (void*)self);
- cb = ossl_sslctx_get_verify_cb(v_ctx);
- SSL_set_ex_data(ssl, ossl_ssl_ex_vcb_idx, (void*)cb);
- cb = ossl_sslctx_get_client_cert_cb(v_ctx);
- SSL_set_ex_data(ssl, ossl_ssl_ex_client_cert_cb_idx, (void*)cb);
- cb = ossl_sslctx_get_tmp_dh_cb(v_ctx);
- SSL_set_ex_data(ssl, ossl_ssl_ex_tmp_dh_callback_idx, (void*)cb);
}
return Qtrue;
}
-#ifdef _WIN32
-#define ssl_get_error(ssl, ret) \
- (errno = WSAGetLastError(), SSL_get_error(ssl, ret))
-#else
-#define ssl_get_error(ssl, ret) SSL_get_error(ssl, ret)
-#endif
-
-static VALUE
-ossl_start_ssl(VALUE self, int (*func)())
+static void
+ossl_start_ssl(SSL *ssl, int (*func)())
{
- SSL *ssl;
- OpenFile *fptr;
int ret;
- Data_Get_Struct(self, SSL, ssl);
- GetOpenFile(ossl_ssl_get_io(self), fptr);
for(;;){
if((ret = func(ssl)) > 0) break;
- switch(ssl_get_error(ssl, ret)){
+ switch(SSL_get_error(ssl, ret)){
case SSL_ERROR_WANT_WRITE:
- rb_io_wait_writable(fileno(fptr->f));
- continue;
case SSL_ERROR_WANT_READ:
- rb_io_wait_readable(fileno(fptr->f));
- continue;
- case SSL_ERROR_SYSCALL:
- if (errno) rb_sys_fail(0);
+ rb_thread_schedule();
+ continue;
default:
ossl_raise(eSSLError, NULL);
}
}
-
- return self;
}
static VALUE
ossl_ssl_connect(VALUE self)
{
+ SSL *ssl;
+ VALUE cb;
+
ossl_ssl_setup(self);
- return ossl_start_ssl(self, SSL_connect);
+ Data_Get_Struct(self, SSL, ssl);
+ cb = ossl_sslctx_get_verify_cb(ossl_ssl_get_ctx(self));
+ SSL_set_ex_data(ssl, ossl_ssl_ex_vcb_idx, (void *)cb);
+ ossl_start_ssl(ssl, SSL_connect);
+
+ return self;
}
static VALUE
ossl_ssl_accept(VALUE self)
{
+ SSL *ssl;
+ VALUE cb;
+
ossl_ssl_setup(self);
- return ossl_start_ssl(self, SSL_accept);
+ Data_Get_Struct(self, SSL, ssl);
+ cb = ossl_sslctx_get_verify_cb(ossl_ssl_get_ctx(self));
+ SSL_set_ex_data(ssl, ossl_ssl_ex_vcb_idx, (void *)cb);
+ ossl_start_ssl(ssl, SSL_accept);
+
+ return self;
}
static VALUE
@@ -623,6 +491,8 @@ ossl_ssl_read(int argc, VALUE *argv, VALUE self)
VALUE len, str;
OpenFile *fptr;
+ Data_Get_Struct(self, SSL, ssl);
+ GetOpenFile(ossl_ssl_get_io(self), fptr);
rb_scan_args(argc, argv, "11", &len, &str);
ilen = NUM2INT(len);
if(NIL_P(str)) str = rb_str_new(0, ilen);
@@ -633,27 +503,23 @@ ossl_ssl_read(int argc, VALUE *argv, VALUE self)
}
if(ilen == 0) return str;
- Data_Get_Struct(self, SSL, ssl);
- GetOpenFile(ossl_ssl_get_io(self), fptr);
if (ssl) {
if(SSL_pending(ssl) <= 0)
rb_thread_wait_fd(fileno(fptr->f));
for (;;){
nread = SSL_read(ssl, RSTRING(str)->ptr, RSTRING(str)->len);
- switch(ssl_get_error(ssl, nread)){
+ switch(SSL_get_error(ssl, nread)){
case SSL_ERROR_NONE:
goto end;
case SSL_ERROR_ZERO_RETURN:
rb_eof_error();
case SSL_ERROR_WANT_WRITE:
- rb_io_wait_writable(fileno(fptr->f));
- continue;
case SSL_ERROR_WANT_READ:
- rb_io_wait_readable(fileno(fptr->f));
+ rb_thread_schedule();
continue;
case SSL_ERROR_SYSCALL:
if(ERR_peek_error() == 0 && nread == 0) rb_eof_error();
- rb_sys_fail(0);
+ ossl_raise(eSSLError, "SSL_read: %s", strerror(errno));
default:
ossl_raise(eSSLError, "SSL_read:");
}
@@ -678,26 +544,21 @@ ossl_ssl_write(VALUE self, VALUE str)
{
SSL *ssl;
int nwrite = 0;
- OpenFile *fptr;
+ FILE *fp;
- StringValue(str);
Data_Get_Struct(self, SSL, ssl);
- GetOpenFile(ossl_ssl_get_io(self), fptr);
+ StringValue(str);
if (ssl) {
for (;;){
nwrite = SSL_write(ssl, RSTRING(str)->ptr, RSTRING(str)->len);
- switch(ssl_get_error(ssl, nwrite)){
+ switch(SSL_get_error(ssl, nwrite)){
case SSL_ERROR_NONE:
goto end;
case SSL_ERROR_WANT_WRITE:
- rb_io_wait_writable(fileno(fptr->f));
- continue;
case SSL_ERROR_WANT_READ:
- rb_io_wait_readable(fileno(fptr->f));
- continue;
- case SSL_ERROR_SYSCALL:
- if (errno) rb_sys_fail(0);
+ rb_thread_schedule();
+ continue;
default:
ossl_raise(eSSLError, "SSL_write:");
}
@@ -857,11 +718,6 @@ Init_ossl_ssl()
ossl_ssl_ex_vcb_idx = SSL_get_ex_new_index(0,"ossl_ssl_ex_vcb_idx",0,0,0);
ossl_ssl_ex_store_p = SSL_get_ex_new_index(0,"ossl_ssl_ex_store_p",0,0,0);
- ossl_ssl_ex_ptr_idx = SSL_get_ex_new_index(0,"ossl_ssl_ex_ptr_idx",0,0,0);
- ossl_ssl_ex_client_cert_cb_idx =
- SSL_get_ex_new_index(0,"ossl_ssl_ex_client_cert_cb_idx",0,0,0);
- ossl_ssl_ex_tmp_dh_callback_idx =
- SSL_get_ex_new_index(0,"ossl_ssl_ex_tmp_dh_callback_idx",0,0,0);
mSSL = rb_define_module_under(mOSSL, "SSL");
eSSLError = rb_define_class_under(mSSL, "SSLError", eOSSLError);
diff --git a/ext/openssl/ossl_x509attr.c b/ext/openssl/ossl_x509attr.c
index 7b88e294a9..f03302d352 100644
--- a/ext/openssl/ossl_x509attr.c
+++ b/ext/openssl/ossl_x509attr.c
@@ -115,11 +115,11 @@ ossl_x509attr_set_oid(VALUE self, VALUE oid)
ASN1_OBJECT *obj;
char *s;
+ GetX509Attr(self, attr);
s = StringValuePtr(oid);
obj = OBJ_txt2obj(s, 0);
if(!obj) obj = OBJ_txt2obj(s, 1);
if(!obj) ossl_raise(eX509AttrError, NULL);
- GetX509Attr(self, attr);
X509_ATTRIBUTE_set1_object(attr, obj);
return oid;
@@ -162,13 +162,13 @@ ossl_x509attr_set_value(VALUE self, VALUE value)
X509_ATTRIBUTE *attr;
ASN1_TYPE *a1type;
+ GetX509Attr(self, attr);
if(!(a1type = ossl_asn1_get_asn1type(value)))
ossl_raise(eASN1Error, "could not get ASN1_TYPE");
if(ASN1_TYPE_get(a1type) == V_ASN1_SEQUENCE){
ASN1_TYPE_free(a1type);
ossl_raise(eASN1Error, "couldn't set SEQUENCE for attribute value.");
}
- GetX509Attr(self, attr);
if(attr->value.set){
if(OSSL_X509ATTR_IS_SINGLE(attr)) ASN1_TYPE_free(attr->value.single);
else sk_ASN1_TYPE_free(attr->value.set);
diff --git a/ext/openssl/ossl_x509cert.c b/ext/openssl/ossl_x509cert.c
index fc587a31f3..443a2ba4c3 100644
--- a/ext/openssl/ossl_x509cert.c
+++ b/ext/openssl/ossl_x509cert.c
@@ -268,10 +268,10 @@ ossl_x509_set_version(VALUE self, VALUE version)
X509 *x509;
long ver;
+ GetX509(self, x509);
if ((ver = NUM2LONG(version)) < 0) {
ossl_raise(eX509CertError, "version must be >= 0!");
}
- GetX509(self, x509);
if (!X509_set_version(x509, ver)) {
ossl_raise(eX509CertError, NULL);
}
@@ -310,6 +310,7 @@ ossl_x509_get_signature_algorithm(VALUE self)
VALUE str;
GetX509(self, x509);
+
out = BIO_new(BIO_s_mem());
if (!out) ossl_raise(eX509CertError, NULL);
@@ -396,8 +397,8 @@ ossl_x509_set_not_before(VALUE self, VALUE time)
X509 *x509;
time_t sec;
- sec = time_to_time_t(time);
GetX509(self, x509);
+ sec = time_to_time_t(time);
if (!X509_time_adj(X509_get_notBefore(x509), 0, &sec)) {
ossl_raise(eX509CertError, NULL);
}
@@ -425,8 +426,8 @@ ossl_x509_set_not_after(VALUE self, VALUE time)
X509 *x509;
time_t sec;
- sec = time_to_time_t(time);
GetX509(self, x509);
+ sec = time_to_time_t(time);
if (!X509_time_adj(X509_get_notAfter(x509), 0, &sec)) {
ossl_raise(eX509CertError, NULL);
}
@@ -468,9 +469,9 @@ ossl_x509_sign(VALUE self, VALUE key, VALUE digest)
EVP_PKEY *pkey;
const EVP_MD *md;
+ GetX509(self, x509);
pkey = GetPrivPKeyPtr(key); /* NO NEED TO DUP */
md = GetDigestPtr(digest);
- GetX509(self, x509);
if (!X509_sign(x509, pkey, md)) {
ossl_raise(eX509CertError, NULL);
}
@@ -488,8 +489,8 @@ ossl_x509_verify(VALUE self, VALUE key)
EVP_PKEY *pkey;
int i;
- pkey = GetPKeyPtr(key); /* NO NEED TO DUP */
GetX509(self, x509);
+ pkey = GetPKeyPtr(key); /* NO NEED TO DUP */
if ((i = X509_verify(x509, pkey)) < 0) {
ossl_raise(eX509CertError, NULL);
}
@@ -509,9 +510,9 @@ ossl_x509_check_private_key(VALUE self, VALUE key)
X509 *x509;
EVP_PKEY *pkey;
+ GetX509(self, x509);
/* not needed private key, but should be */
pkey = GetPrivPKeyPtr(key); /* NO NEED TO DUP */
- GetX509(self, x509);
if (!X509_check_private_key(x509, pkey)) {
OSSL_Warning("Check private key:%s", OSSL_ErrMsg());
return Qfalse;
@@ -555,12 +556,12 @@ ossl_x509_set_extensions(VALUE self, VALUE ary)
X509_EXTENSION *ext;
int i;
+ GetX509(self, x509);
Check_Type(ary, T_ARRAY);
/* All ary's members should be X509Extension */
for (i=0; i<RARRAY(ary)->len; i++) {
OSSL_Check_Kind(RARRAY(ary)->ptr[i], cX509Ext);
}
- GetX509(self, x509);
sk_X509_EXTENSION_pop_free(x509->cert_info->extensions, X509_EXTENSION_free);
x509->cert_info->extensions = NULL;
for (i=0; i<RARRAY(ary)->len; i++) {
diff --git a/ext/openssl/ossl_x509crl.c b/ext/openssl/ossl_x509crl.c
index 0dc22416e7..a7746aa2b3 100644
--- a/ext/openssl/ossl_x509crl.c
+++ b/ext/openssl/ossl_x509crl.c
@@ -146,10 +146,11 @@ ossl_x509crl_set_version(VALUE self, VALUE version)
X509_CRL *crl;
long ver;
+ GetX509CRL(self, crl);
+
if ((ver = NUM2LONG(version)) < 0) {
ossl_raise(eX509CRLError, "version must be >= 0!");
}
- GetX509CRL(self, crl);
if (!X509_CRL_set_version(crl, ver)) {
ossl_raise(eX509CRLError, NULL);
}
@@ -166,6 +167,7 @@ ossl_x509crl_get_signature_algorithm(VALUE self)
VALUE str;
GetX509CRL(self, crl);
+
if (!(out = BIO_new(BIO_s_mem()))) {
ossl_raise(eX509CRLError, NULL);
}
@@ -218,8 +220,8 @@ ossl_x509crl_set_last_update(VALUE self, VALUE time)
X509_CRL *crl;
time_t sec;
- sec = time_to_time_t(time);
GetX509CRL(self, crl);
+ sec = time_to_time_t(time);
if (!X509_time_adj(crl->crl->lastUpdate, 0, &sec)) {
ossl_raise(eX509CRLError, NULL);
}
@@ -243,8 +245,8 @@ ossl_x509crl_set_next_update(VALUE self, VALUE time)
X509_CRL *crl;
time_t sec;
- sec = time_to_time_t(time);
GetX509CRL(self, crl);
+ sec = time_to_time_t(time);
/* This must be some thinko in OpenSSL */
if (!(crl->crl->nextUpdate = X509_time_adj(crl->crl->nextUpdate, 0, &sec))){
ossl_raise(eX509CRLError, NULL);
@@ -285,12 +287,12 @@ ossl_x509crl_set_revoked(VALUE self, VALUE ary)
X509_REVOKED *rev;
int i;
+ GetX509CRL(self, crl);
Check_Type(ary, T_ARRAY);
/* All ary members should be X509 Revoked */
for (i=0; i<RARRAY(ary)->len; i++) {
OSSL_Check_Kind(RARRAY(ary)->ptr[i], cX509Rev);
}
- GetX509CRL(self, crl);
sk_X509_REVOKED_pop_free(crl->crl->revoked, X509_REVOKED_free);
crl->crl->revoked = NULL;
for (i=0; i<RARRAY(ary)->len; i++) {
@@ -459,12 +461,12 @@ ossl_x509crl_set_extensions(VALUE self, VALUE ary)
X509_EXTENSION *ext;
int i;
+ GetX509CRL(self, crl);
Check_Type(ary, T_ARRAY);
/* All ary members should be X509 Extensions */
for (i=0; i<RARRAY(ary)->len; i++) {
OSSL_Check_Kind(RARRAY(ary)->ptr[i], cX509Ext);
}
- GetX509CRL(self, crl);
sk_X509_EXTENSION_pop_free(crl->crl->extensions, X509_EXTENSION_free);
crl->crl->extensions = NULL;
for (i=0; i<RARRAY(ary)->len; i++) {
diff --git a/ext/openssl/ossl_x509ext.c b/ext/openssl/ossl_x509ext.c
index 8ba555d3e0..57e005489a 100644
--- a/ext/openssl/ossl_x509ext.c
+++ b/ext/openssl/ossl_x509ext.c
@@ -215,6 +215,7 @@ ossl_x509extfactory_create_ext(int argc, VALUE *argv, VALUE self)
VALUE oid, value, critical, valstr, obj;
int nid;
+ GetX509ExtFactory(self, ctx);
rb_scan_args(argc, argv, "21", &oid, &value, &critical);
StringValue(oid);
StringValue(value);
@@ -225,7 +226,6 @@ ossl_x509extfactory_create_ext(int argc, VALUE *argv, VALUE self)
if(!nid) ossl_raise(eX509ExtError, "unknown OID `%s'", RSTRING(oid)->ptr);
valstr = rb_str_new2(RTEST(critical) ? "critical," : "");
rb_str_append(valstr, value);
- GetX509ExtFactory(self, ctx);
ext = X509V3_EXT_conf_nid(NULL, ctx, nid, RSTRING(valstr)->ptr);
if (!ext){
ossl_raise(eX509ExtError, "%s = %s",
@@ -284,11 +284,11 @@ ossl_x509ext_set_oid(VALUE self, VALUE oid)
ASN1_OBJECT *obj;
char *s;
+ GetX509Ext(self, ext);
s = StringValuePtr(oid);
obj = OBJ_txt2obj(s, 0);
if(!obj) obj = OBJ_txt2obj(s, 1);
if(!obj) ossl_raise(eX509ExtError, NULL);
- GetX509Ext(self, ext);
X509_EXTENSION_set_object(ext, obj);
return oid;
@@ -301,6 +301,7 @@ ossl_x509ext_set_value(VALUE self, VALUE data)
ASN1_OCTET_STRING *asn1s;
char *s;
+ GetX509Ext(self, ext);
data = ossl_to_der_if_possible(data);
StringValue(data);
if(!(s = OPENSSL_malloc(RSTRING(data)->len)))
@@ -315,7 +316,6 @@ ossl_x509ext_set_value(VALUE self, VALUE data)
ASN1_OCTET_STRING_free(asn1s);
ossl_raise(eX509ExtError, NULL);
}
- GetX509Ext(self, ext);
X509_EXTENSION_set_data(ext, asn1s);
return data;
@@ -376,7 +376,6 @@ static VALUE
ossl_x509ext_get_critical(VALUE obj)
{
X509_EXTENSION *ext;
-
GetX509Ext(obj, ext);
return X509_EXTENSION_get_critical(ext) ? Qtrue : Qfalse;
}
diff --git a/ext/openssl/ossl_x509name.c b/ext/openssl/ossl_x509name.c
index c5ed8b5457..b198157504 100644
--- a/ext/openssl/ossl_x509name.c
+++ b/ext/openssl/ossl_x509name.c
@@ -119,22 +119,19 @@ ossl_x509name_initialize(int argc, VALUE *argv, VALUE self)
if (rb_scan_args(argc, argv, "02", &arg, &template) == 0) {
return self;
}
- else {
- VALUE tmp = rb_check_array_type(arg);
- if (!NIL_P(tmp)) {
- VALUE args;
- if(NIL_P(template)) template = OBJECT_TYPE_TEMPLATE;
- args = rb_ary_new3(2, self, template);
- rb_iterate(rb_each, tmp, ossl_x509name_init_i, args);
- }
- else{
- unsigned char *p;
- VALUE str = ossl_to_der_if_possible(arg);
- StringValue(str);
- p = RSTRING(str)->ptr;
- if(!d2i_X509_NAME((X509_NAME**)&DATA_PTR(self), &p, RSTRING(str)->len)){
- ossl_raise(eX509NameError, NULL);
- }
+ else if (rb_obj_is_kind_of(arg, rb_cArray) == Qtrue){
+ VALUE args;
+ if(NIL_P(template)) template = OBJECT_TYPE_TEMPLATE;
+ args = rb_ary_new3(2, self, template);
+ rb_iterate(rb_each, arg, ossl_x509name_init_i, args);
+ }
+ else{
+ unsigned char *p;
+ VALUE str = ossl_to_der_if_possible(arg);
+ StringValue(str);
+ p = RSTRING(str)->ptr;
+ if(!d2i_X509_NAME((X509_NAME**)&DATA_PTR(self), &p, RSTRING(str)->len)){
+ ossl_raise(eX509NameError, NULL);
}
}
@@ -161,7 +158,7 @@ VALUE ossl_x509name_add_entry(int argc, VALUE *argv, VALUE self)
}
static VALUE
-ossl_x509name_to_s_old(VALUE self)
+ossl_x509name_to_s(VALUE self)
{
X509_NAME *name;
char *buf;
@@ -175,30 +172,6 @@ ossl_x509name_to_s_old(VALUE self)
return str;
}
-static VALUE
-ossl_x509name_to_s(int argc, VALUE *argv, VALUE self)
-{
- X509_NAME *name;
- VALUE flag, str;
- BIO *out;
- unsigned long iflag;
-
- rb_scan_args(argc, argv, "01", &flag);
- if (NIL_P(flag))
- return ossl_x509name_to_s_old(self);
- else iflag = NUM2ULONG(flag);
- if (!(out = BIO_new(BIO_s_mem())))
- rb_raise(eX509NameError, NULL);
- GetX509Name(self, name);
- if (!X509_NAME_print_ex(out, name, 0, iflag)){
- BIO_free(out);
- rb_raise(eX509NameError, NULL);
- }
- str = ossl_membio2str(out);
-
- return str;
-}
-
static VALUE
ossl_x509name_to_a(VALUE self)
{
@@ -314,7 +287,7 @@ Init_ossl_x509name()
rb_define_alloc_func(cX509Name, ossl_x509name_alloc);
rb_define_method(cX509Name, "initialize", ossl_x509name_initialize, -1);
rb_define_method(cX509Name, "add_entry", ossl_x509name_add_entry, -1);
- rb_define_method(cX509Name, "to_s", ossl_x509name_to_s, -1);
+ rb_define_method(cX509Name, "to_s", ossl_x509name_to_s, 0);
rb_define_method(cX509Name, "to_a", ossl_x509name_to_a, 0);
rb_define_method(cX509Name, "cmp", ossl_x509name_cmp, 1);
rb_define_alias(cX509Name, "<=>", "cmp");
@@ -326,8 +299,7 @@ Init_ossl_x509name()
ptrstr = INT2NUM(V_ASN1_PRINTABLESTRING);
ia5str = INT2NUM(V_ASN1_IA5STRING);
rb_define_const(cX509Name, "DEFAULT_OBJECT_TYPE", utf8str);
- hash = rb_hash_new();
- RHASH(hash)->ifnone = utf8str;
+ hash = rb_funcall(rb_cHash, rb_intern("new"), 1, DEFAULT_OBJECT_TYPE);
rb_hash_aset(hash, rb_str_new2("C"), ptrstr);
rb_hash_aset(hash, rb_str_new2("countryName"), ptrstr);
rb_hash_aset(hash, rb_str_new2("serialNumber"), ptrstr);
@@ -336,9 +308,4 @@ Init_ossl_x509name()
rb_hash_aset(hash, rb_str_new2("domainComponent"), ia5str);
rb_hash_aset(hash, rb_str_new2("emailAddress"), ia5str);
rb_define_const(cX509Name, "OBJECT_TYPE_TEMPLATE", hash);
-
- rb_define_const(cX509Name, "COMPAT", ULONG2NUM(XN_FLAG_COMPAT));
- rb_define_const(cX509Name, "RFC2253", ULONG2NUM(XN_FLAG_RFC2253));
- rb_define_const(cX509Name, "ONELINE", ULONG2NUM(XN_FLAG_ONELINE));
- rb_define_const(cX509Name, "MULTILINE", ULONG2NUM(XN_FLAG_MULTILINE));
}
diff --git a/ext/openssl/ossl_x509req.c b/ext/openssl/ossl_x509req.c
index d644250433..c532739997 100644
--- a/ext/openssl/ossl_x509req.c
+++ b/ext/openssl/ossl_x509req.c
@@ -240,10 +240,10 @@ ossl_x509req_set_version(VALUE self, VALUE version)
X509_REQ *req;
long ver;
+ GetX509Req(self, req);
if ((ver = FIX2LONG(version)) < 0) {
ossl_raise(eX509ReqError, "version must be >= 0!");
}
- GetX509Req(self, req);
if (!X509_REQ_set_version(req, ver)) {
ossl_raise(eX509ReqError, NULL);
}
@@ -402,11 +402,11 @@ ossl_x509req_set_attributes(VALUE self, VALUE ary)
int i;
VALUE item;
+ GetX509Req(self, req);
Check_Type(ary, T_ARRAY);
for (i=0;i<RARRAY(ary)->len; i++) {
OSSL_Check_Kind(RARRAY(ary)->ptr[i], cX509Attr);
}
- GetX509Req(self, req);
sk_X509_ATTRIBUTE_pop_free(req->req_info->attributes, X509_ATTRIBUTE_free);
req->req_info->attributes = NULL;
for (i=0;i<RARRAY(ary)->len; i++) {
diff --git a/ext/openssl/ossl_x509revoked.c b/ext/openssl/ossl_x509revoked.c
index 3ccac8d26a..30ce75207f 100644
--- a/ext/openssl/ossl_x509revoked.c
+++ b/ext/openssl/ossl_x509revoked.c
@@ -129,8 +129,8 @@ ossl_x509revoked_set_time(VALUE self, VALUE time)
X509_REVOKED *rev;
time_t sec;
- sec = time_to_time_t(time);
GetX509Rev(self, rev);
+ sec = time_to_time_t(time);
if (!X509_time_adj(rev->revocationDate, 0, &sec)) {
ossl_raise(eX509RevError, NULL);
}
@@ -174,11 +174,11 @@ ossl_x509revoked_set_extensions(VALUE self, VALUE ary)
int i;
VALUE item;
+ GetX509Rev(self, rev);
Check_Type(ary, T_ARRAY);
for (i=0; i<RARRAY(ary)->len; i++) {
OSSL_Check_Kind(RARRAY(ary)->ptr[i], cX509Ext);
}
- GetX509Rev(self, rev);
sk_X509_EXTENSION_pop_free(rev->extensions, X509_EXTENSION_free);
rev->extensions = NULL;
for (i=0; i<RARRAY(ary)->len; i++) {
diff --git a/ext/openssl/ossl_x509store.c b/ext/openssl/ossl_x509store.c
index cea845a1cc..4c5f0624a9 100644
--- a/ext/openssl/ossl_x509store.c
+++ b/ext/openssl/ossl_x509store.c
@@ -137,7 +137,6 @@ ossl_x509store_initialize(int argc, VALUE *argv, VALUE self)
rb_iv_set(self, "@error", Qnil);
rb_iv_set(self, "@error_string", Qnil);
rb_iv_set(self, "@chain", Qnil);
- rb_iv_set(self, "@time", Qnil);
return self;
}
@@ -147,10 +146,9 @@ ossl_x509store_set_flags(VALUE self, VALUE flags)
{
#if (OPENSSL_VERSION_NUMBER >= 0x00907000L)
X509_STORE *store;
- long f = NUM2LONG(flags);
GetX509Store(self, store);
- X509_STORE_set_flags(store, f);
+ X509_STORE_set_flags(store, NUM2LONG(flags));
#else
rb_iv_set(self, "@flags", flags);
#endif
@@ -163,10 +161,9 @@ ossl_x509store_set_purpose(VALUE self, VALUE purpose)
{
#if (OPENSSL_VERSION_NUMBER >= 0x00907000L)
X509_STORE *store;
- long p = NUM2LONG(purpose);
GetX509Store(self, store);
- X509_STORE_set_purpose(store, p);
+ X509_STORE_set_purpose(store, NUM2LONG(purpose));
#else
rb_iv_set(self, "@purpose", purpose);
#endif
@@ -179,10 +176,9 @@ ossl_x509store_set_trust(VALUE self, VALUE trust)
{
#if (OPENSSL_VERSION_NUMBER >= 0x00907000L)
X509_STORE *store;
- long t = NUM2LONG(trust);
GetX509Store(self, store);
- X509_STORE_set_trust(store, t);
+ X509_STORE_set_trust(store, NUM2LONG(trust));
#else
rb_iv_set(self, "@trust", trust);
#endif
@@ -191,13 +187,6 @@ ossl_x509store_set_trust(VALUE self, VALUE trust)
}
static VALUE
-ossl_x509store_set_time(VALUE self, VALUE time)
-{
- rb_iv_set(self, "@time", time);
- return time;
-}
-
-static VALUE
ossl_x509store_add_file(VALUE self, VALUE file)
{
X509_STORE *store;
@@ -240,19 +229,6 @@ ossl_x509store_add_path(VALUE self, VALUE dir)
}
static VALUE
-ossl_x509store_set_default_paths(VALUE self)
-{
- X509_STORE *store;
-
- GetX509Store(self, store);
- if (X509_STORE_set_default_paths(store) != 1){
- ossl_raise(eX509StoreError, NULL);
- }
-
- return Qnil;
-}
-
-static VALUE
ossl_x509store_add_cert(VALUE self, VALUE arg)
{
X509_STORE *store;
@@ -260,9 +236,7 @@ ossl_x509store_add_cert(VALUE self, VALUE arg)
cert = GetX509CertPtr(arg); /* NO NEED TO DUP */
GetX509Store(self, store);
- if (X509_STORE_add_cert(store, cert) != 1){
- ossl_raise(eX509StoreError, NULL);
- }
+ X509_STORE_add_cert(store, cert);
return self;
}
@@ -275,9 +249,7 @@ ossl_x509store_add_crl(VALUE self, VALUE arg)
crl = GetX509CRLPtr(arg); /* NO NEED TO DUP */
GetX509Store(self, store);
- if (X509_STORE_add_crl(store, crl) != 1){
- ossl_raise(eX509StoreError, NULL);
- }
+ X509_STORE_add_crl(store, crl);
return self;
}
@@ -357,22 +329,17 @@ ossl_x509stctx_alloc(VALUE klass)
return obj;
}
-static VALUE ossl_x509stctx_set_flags(VALUE, VALUE);
-static VALUE ossl_x509stctx_set_purpose(VALUE, VALUE);
-static VALUE ossl_x509stctx_set_trust(VALUE, VALUE);
-static VALUE ossl_x509stctx_set_time(VALUE, VALUE);
-
static VALUE
ossl_x509stctx_initialize(int argc, VALUE *argv, VALUE self)
{
- VALUE store, cert, chain, t;
+ VALUE store, cert, chain;
X509_STORE_CTX *ctx;
X509_STORE *x509st;
X509 *x509 = NULL;
STACK_OF(X509) *x509s = NULL;
- rb_scan_args(argc, argv, "12", &store, &cert, &chain);
GetX509StCtx(self, ctx);
+ rb_scan_args(argc, argv, "12", &store, &cert, &chain);
SafeGetX509Store(store, x509st);
if(!NIL_P(cert)) x509 = DupX509CertPtr(cert); /* NEED TO DUP */
if(!NIL_P(chain)) x509s = ossl_x509_ary2sk(chain);
@@ -383,12 +350,10 @@ ossl_x509stctx_initialize(int argc, VALUE *argv, VALUE self)
}
#else
X509_STORE_CTX_init(ctx, x509st, x509, x509s);
- ossl_x509stctx_set_flags(self, rb_iv_get(store, "@flags"));
- ossl_x509stctx_set_purpose(self, rb_iv_get(store, "@purpose"));
- ossl_x509stctx_set_trust(self, rb_iv_get(store, "@trust"));
+ X509_STORE_CTX_set_flags(ctx, NUM2INT(rb_iv_get(store, "@flags")));
+ X509_STORE_CTX_set_purpose(ctx, NUM2INT(rb_iv_get(store, "@purpose")));
+ X509_STORE_CTX_set_trust(ctx, NUM2INT(rb_iv_get(store, "@trust")));
#endif
- if (!NIL_P(t = rb_iv_get(store, "@time")))
- ossl_x509stctx_set_time(self, t);
rb_iv_set(self, "@verify_callback", rb_iv_get(store, "@verify_callback"));
rb_iv_set(self, "@cert", cert);
@@ -518,10 +483,9 @@ static VALUE
ossl_x509stctx_set_flags(VALUE self, VALUE flags)
{
X509_STORE_CTX *store;
- long f = NUM2LONG(flags);
GetX509StCtx(self, store);
- X509_STORE_CTX_set_flags(store, f);
+ X509_STORE_CTX_set_flags(store, NUM2LONG(flags));
return flags;
}
@@ -530,10 +494,9 @@ static VALUE
ossl_x509stctx_set_purpose(VALUE self, VALUE purpose)
{
X509_STORE_CTX *store;
- long p = NUM2LONG(purpose);
GetX509StCtx(self, store);
- X509_STORE_CTX_set_purpose(store, p);
+ X509_STORE_CTX_set_purpose(store, NUM2LONG(purpose));
return purpose;
}
@@ -542,27 +505,13 @@ static VALUE
ossl_x509stctx_set_trust(VALUE self, VALUE trust)
{
X509_STORE_CTX *store;
- long t = NUM2LONG(trust);
GetX509StCtx(self, store);
- X509_STORE_CTX_set_trust(store, t);
+ X509_STORE_CTX_set_trust(store, NUM2LONG(trust));
return trust;
}
-static VALUE
-ossl_x509stctx_set_time(VALUE self, VALUE time)
-{
- X509_STORE_CTX *store;
- long t;
-
- t = NUM2LONG(rb_Integer(time));
- GetX509StCtx(self, store);
- X509_STORE_CTX_set_time(store, 0, t);
-
- return time;
-}
-
/*
* INIT
*/
@@ -584,10 +533,8 @@ Init_ossl_x509store()
rb_define_method(cX509Store, "flags=", ossl_x509store_set_flags, 1);
rb_define_method(cX509Store, "purpose=", ossl_x509store_set_purpose, 1);
rb_define_method(cX509Store, "trust=", ossl_x509store_set_trust, 1);
- rb_define_method(cX509Store, "time=", ossl_x509store_set_time, 1);
rb_define_method(cX509Store, "add_path", ossl_x509store_add_path, 1);
rb_define_method(cX509Store, "add_file", ossl_x509store_add_file, 1);
- rb_define_method(cX509Store, "set_default_paths", ossl_x509store_set_default_paths, 0);
rb_define_method(cX509Store, "add_cert", ossl_x509store_add_cert, 1);
rb_define_method(cX509Store, "add_crl", ossl_x509store_add_crl, 1);
rb_define_method(cX509Store, "verify", ossl_x509store_verify, -1);
@@ -608,6 +555,5 @@ Init_ossl_x509store()
rb_define_method(x509stctx,"flags=", ossl_x509stctx_set_flags, 1);
rb_define_method(x509stctx,"purpose=", ossl_x509stctx_set_purpose, 1);
rb_define_method(x509stctx,"trust=", ossl_x509stctx_set_trust, 1);
- rb_define_method(x509stctx,"time=", ossl_x509stctx_set_time, 1);
}
diff --git a/ext/pty/pty.c b/ext/pty/pty.c
index db072744d6..cfd7e4854e 100644
--- a/ext/pty/pty.c
+++ b/ext/pty/pty.c
@@ -103,6 +103,8 @@ char *MasterDevice = "/dev/pty%s",
static char SlaveName[DEVICELEN];
+extern int errno;
+
#ifndef HAVE_SETEUID
# ifdef HAVE_SETREUID
# define seteuid(e) setreuid(-1, (e))
@@ -126,7 +128,7 @@ echild_status(self)
struct pty_info {
int fd;
- rb_pid_t child_pid;
+ pid_t child_pid;
VALUE thread;
};
@@ -373,7 +375,7 @@ getDevice(master,slave)
}
close(i);
}
- rb_raise(rb_eRuntimeError, "can't get Master/Slave device");
+ rb_raise(rb_eRuntimeError, "Cannot get Master/Slave device");
#else
char **p;
char MasterName[DEVICELEN];
@@ -392,7 +394,7 @@ getDevice(master,slave)
close(i);
}
}
- rb_raise(rb_eRuntimeError, "can't get %s", SlaveName);
+ rb_raise(rb_eRuntimeError, "Cannot get %s", SlaveName);
#endif
}
#endif /* HAVE__GETPTY */
diff --git a/ext/readline/extconf.rb b/ext/readline/extconf.rb
index b67a443dad..d8d8643d08 100644
--- a/ext/readline/extconf.rb
+++ b/ext/readline/extconf.rb
@@ -1,63 +1,30 @@
require "mkmf"
-$readline_headers = ["stdio.h"]
-
-def have_readline_header(header)
- if have_header(header)
- $readline_headers.push(header)
- return true
- else
- return false
- end
-end
-
-def have_readline_var(var)
- return have_var(var, $readline_headers)
-end
-
dir_config('curses')
dir_config('ncurses')
dir_config('termcap')
dir_config("readline")
-enable_libedit = enable_config("libedit")
have_library("user32", nil) if /cygwin/ === RUBY_PLATFORM
-have_library("ncurses", "tgetnum") ||
- have_library("termcap", "tgetnum") ||
+have_library("ncurses", "tgetnum") or
+ have_library("termcap", "tgetnum") or
have_library("curses", "tgetnum")
-if enable_libedit
- unless (have_readline_header("editline/readline.h") ||
- have_readline_header("readline/readline.h")) &&
- have_library("edit", "readline")
- exit
+if have_header("readline/readline.h") and
+ have_header("readline/history.h") and
+ have_library("readline", "readline")
+ if have_func("rl_filename_completion_function")
+ $CFLAGS += " -DREADLINE_42_OR_LATER"
end
-else
- unless ((have_readline_header("readline/readline.h") &&
- have_readline_header("readline/history.h")) &&
- (have_library("readline", "readline") ||
- have_library("edit", "readline"))) ||
- (have_readline_header("editline/readline.h") &&
- have_library("edit", "readline"))
- exit
+ if have_func("rl_cleanup_after_signal")
+ $CFLAGS += " -DREADLINE_40_OR_LATER"
end
+ if try_link(<<EOF, $libs)
+#include <stdio.h>
+#include <readline/readline.h>
+main() {rl_completion_append_character = 1;}
+EOF
+ # this feature is implemented in readline-2.1 or later.
+ $CFLAGS += " -DREADLINE_21_OR_LATER"
+ end
+ create_makefile("readline")
end
-
-have_readline_var("rl_filename_completion_function")
-have_readline_var("rl_deprep_term_function")
-have_readline_var("rl_completion_append_character")
-have_readline_var("rl_basic_word_break_characters")
-have_readline_var("rl_completer_word_break_characters")
-have_readline_var("rl_basic_quote_characters")
-have_readline_var("rl_completer_quote_characters")
-have_readline_var("rl_filename_quote_characters")
-have_readline_var("rl_attempted_completion_over")
-have_readline_var("rl_library_version")
-have_readline_var("rl_event_hook")
-have_func("rl_cleanup_after_signal")
-have_func("rl_clear_signals")
-have_func("rl_vi_editing_mode")
-have_func("rl_emacs_editing_mode")
-have_func("rl_clear_signals")
-have_func("replace_history_entry")
-have_func("remove_history")
-create_makefile("readline")
diff --git a/ext/readline/readline.c b/ext/readline/readline.c
index b78a911b7c..78a8b17fe5 100644
--- a/ext/readline/readline.c
+++ b/ext/readline/readline.c
@@ -3,20 +3,10 @@
#include <errno.h>
#include <stdio.h>
-#include <ctype.h>
-#include <string.h>
-#ifdef HAVE_READLINE_READLINE_H
#include <readline/readline.h>
-#endif
-#ifdef HAVE_READLINE_HISTORY_H
#include <readline/history.h>
-#endif
-#ifdef HAVE_EDITLINE_READLINE_H
-#include <editline/readline.h>
-#endif
#include "ruby.h"
-#include "rubyio.h"
#include "rubysig.h"
#ifdef HAVE_UNISTD_H
@@ -29,18 +19,13 @@ static VALUE mReadline;
#define COMPLETION_PROC "completion_proc"
#define COMPLETION_CASE_FOLD "completion_case_fold"
-static ID completion_proc, completion_case_fold;
-#ifndef HAVE_RL_FILENAME_COMPLETION_FUNCTION
+#ifndef READLINE_42_OR_LATER
# define rl_filename_completion_function filename_completion_function
# define rl_username_completion_function username_completion_function
# define rl_completion_matches completion_matches
#endif
-static int readline_event(void);
-static char **readline_attempted_completion_function(const char *text,
- int start, int end);
-
static int
readline_event()
{
@@ -59,27 +44,20 @@ readline_readline(argc, argv, self)
char *prompt = NULL;
char *buff;
int status;
- OpenFile *ofp, *ifp;
- rb_secure(4);
if (rb_scan_args(argc, argv, "02", &tmp, &add_hist) > 0) {
- SafeStringValue(tmp);
- prompt = RSTRING(tmp)->ptr;
+ prompt = StringValuePtr(tmp);
}
if (!isatty(0) && errno == EBADF) rb_raise(rb_eIOError, "stdin closed");
- GetOpenFile(rb_stdout, ofp);
- rl_outstream = ofp->f;
- GetOpenFile(rb_stdin, ifp);
- rl_instream = ifp->f;
buff = (char*)rb_protect((VALUE(*)_((VALUE)))readline, (VALUE)prompt,
&status);
if (status) {
-#if defined HAVE_RL_CLEANUP_AFTER_SIGNAL
+#if defined READLINE_40_OR_LATER
/* restore terminal mode and signal handler*/
rl_cleanup_after_signal();
-#elif defined HAVE_RL_DEPREP_TERM_FUNCTION
+#elif defined READLINE_21_OR_LATER
/* restore terminal mode */
(*rl_deprep_term_function)();
#else
@@ -104,18 +82,16 @@ readline_s_set_completion_proc(self, proc)
VALUE self;
VALUE proc;
{
- rb_secure(4);
if (!rb_respond_to(proc, rb_intern("call")))
rb_raise(rb_eArgError, "argument must respond to `call'");
- return rb_ivar_set(mReadline, completion_proc, proc);
+ return rb_iv_set(mReadline, COMPLETION_PROC, proc);
}
static VALUE
readline_s_get_completion_proc(self)
VALUE self;
{
- rb_secure(4);
- return rb_attr_get(mReadline, completion_proc);
+ return rb_iv_get(mReadline, COMPLETION_PROC);
}
static VALUE
@@ -123,21 +99,19 @@ readline_s_set_completion_case_fold(self, val)
VALUE self;
VALUE val;
{
- rb_secure(4);
- return rb_ivar_set(mReadline, completion_case_fold, val);
+ return rb_iv_set(mReadline, COMPLETION_CASE_FOLD, val);
}
static VALUE
readline_s_get_completion_case_fold(self)
VALUE self;
{
- rb_secure(4);
- return rb_attr_get(mReadline, completion_case_fold);
+ return rb_iv_get(mReadline, COMPLETION_CASE_FOLD);
}
static char **
readline_attempted_completion_function(text, start, end)
- const char *text;
+ char *text;
int start;
int end;
{
@@ -146,13 +120,11 @@ readline_attempted_completion_function(text, start, end)
int case_fold;
int i, matches;
- proc = rb_attr_get(mReadline, completion_proc);
+ proc = rb_iv_get(mReadline, COMPLETION_PROC);
if (NIL_P(proc))
return NULL;
-#ifdef HAVE_RL_ATTEMPTED_COMPLETION_OVER
rl_attempted_completion_over = 1;
-#endif
- case_fold = RTEST(rb_attr_get(mReadline, completion_case_fold));
+ case_fold = RTEST(rb_iv_get(mReadline, COMPLETION_CASE_FOLD));
ary = rb_funcall(proc, rb_intern("call"), 1, rb_tainted_str_new2(text));
if (TYPE(ary) != T_ARRAY)
ary = rb_Array(ary);
@@ -168,9 +140,9 @@ readline_attempted_completion_function(text, start, end)
result[matches + 1] = NULL;
if (matches == 1) {
- result[0] = strdup(result[1]);
- }
- else {
+ result[0] = result[1];
+ result[1] = NULL;
+ } else {
register int i = 1;
int low = 100000;
@@ -206,83 +178,62 @@ static VALUE
readline_s_vi_editing_mode(self)
VALUE self;
{
-#ifdef HAVE_RL_VI_EDITING_MODE
- rb_secure(4);
rl_vi_editing_mode(1,0);
return Qnil;
-#else
- rb_notimplement();
- return Qnil; /* not reached */
-#endif /* HAVE_RL_VI_EDITING_MODE */
}
static VALUE
readline_s_emacs_editing_mode(self)
VALUE self;
{
-#ifdef HAVE_RL_EMACS_EDITING_MODE
- rb_secure(4);
rl_emacs_editing_mode(1,0);
return Qnil;
-#else
- rb_notimplement();
- return Qnil; /* not reached */
-#endif /* HAVE_RL_EMACS_EDITING_MODE */
}
static VALUE
readline_s_set_completion_append_character(self, str)
VALUE self, str;
{
-#ifdef HAVE_RL_COMPLETION_APPEND_CHARACTER
- rb_secure(4);
- if (NIL_P(str)) {
+#ifdef READLINE_21_OR_LATER
+ if (NIL_P(str) || !StringValuePtr(str) || !RSTRING(str)->len) {
rl_completion_append_character = '\0';
+ } else {
+ rl_completion_append_character = RSTRING(str)->ptr[0];
}
- else {
- SafeStringValue(str);
- if (RSTRING(str)->len == 0) {
- rl_completion_append_character = '\0';
- } else {
- rl_completion_append_character = RSTRING(str)->ptr[0];
- }
- }
+
return self;
#else
rb_notimplement();
- return Qnil; /* not reached */
-#endif /* HAVE_RL_COMPLETION_APPEND_CHARACTER */
+#endif /* READLINE_21_OR_LATER */
}
static VALUE
readline_s_get_completion_append_character(self)
VALUE self;
{
-#ifdef HAVE_RL_COMPLETION_APPEND_CHARACTER
+#ifdef READLINE_21_OR_LATER
VALUE str;
- rb_secure(4);
if (rl_completion_append_character == '\0')
return Qnil;
str = rb_str_new("", 1);
RSTRING(str)->ptr[0] = rl_completion_append_character;
+
return str;
#else
rb_notimplement();
- return Qnil; /* not reached */
-#endif /* HAVE_RL_COMPLETION_APPEND_CHARACTER */
+#endif /* READLINE_21_OR_LATER */
}
static VALUE
readline_s_set_basic_word_break_characters(self, str)
VALUE self, str;
{
-#ifdef HAVE_RL_BASIC_WORD_BREAK_CHARACTERS
+#ifdef READLINE_21_OR_LATER
static char *basic_word_break_characters = NULL;
- rb_secure(4);
- SafeStringValue(str);
+ StringValue(str);
if (basic_word_break_characters == NULL) {
basic_word_break_characters =
ALLOC_N(char, RSTRING(str)->len + 1);
@@ -294,37 +245,34 @@ readline_s_set_basic_word_break_characters(self, str)
RSTRING(str)->ptr, RSTRING(str)->len);
basic_word_break_characters[RSTRING(str)->len] = '\0';
rl_basic_word_break_characters = basic_word_break_characters;
+
return self;
#else
rb_notimplement();
- return Qnil; /* not reached */
-#endif /* HAVE_RL_BASIC_WORD_BREAK_CHARACTERS */
+#endif /* READLINE_21_OR_LATER */
}
static VALUE
readline_s_get_basic_word_break_characters(self, str)
VALUE self, str;
{
-#ifdef HAVE_RL_BASIC_WORD_BREAK_CHARACTERS
- rb_secure(4);
+#ifdef READLINE_21_OR_LATER
if (rl_basic_word_break_characters == NULL)
return Qnil;
- return rb_tainted_str_new2(rl_basic_word_break_characters);
+ return rb_str_new2(rl_basic_word_break_characters);
#else
rb_notimplement();
- return Qnil; /* not reached */
-#endif /* HAVE_RL_BASIC_WORD_BREAK_CHARACTERS */
+#endif /* READLINE_21_OR_LATER */
}
static VALUE
readline_s_set_completer_word_break_characters(self, str)
VALUE self, str;
{
-#ifdef HAVE_RL_COMPLETER_WORD_BREAK_CHARACTERS
+#ifdef READLINE_21_OR_LATER
static char *completer_word_break_characters = NULL;
- rb_secure(4);
- SafeStringValue(str);
+ StringValue(str);
if (completer_word_break_characters == NULL) {
completer_word_break_characters =
ALLOC_N(char, RSTRING(str)->len + 1);
@@ -336,37 +284,34 @@ readline_s_set_completer_word_break_characters(self, str)
RSTRING(str)->ptr, RSTRING(str)->len);
completer_word_break_characters[RSTRING(str)->len] = '\0';
rl_completer_word_break_characters = completer_word_break_characters;
+
return self;
#else
rb_notimplement();
- return Qnil; /* not reached */
-#endif /* HAVE_RL_COMPLETER_WORD_BREAK_CHARACTERS */
+#endif /* READLINE_21_OR_LATER */
}
static VALUE
readline_s_get_completer_word_break_characters(self, str)
VALUE self, str;
{
-#ifdef HAVE_RL_COMPLETER_WORD_BREAK_CHARACTERS
- rb_secure(4);
+#ifdef READLINE_21_OR_LATER
if (rl_completer_word_break_characters == NULL)
return Qnil;
- return rb_tainted_str_new2(rl_completer_word_break_characters);
+ return rb_str_new2(rl_completer_word_break_characters);
#else
rb_notimplement();
- return Qnil; /* not reached */
-#endif /* HAVE_RL_COMPLETER_WORD_BREAK_CHARACTERS */
+#endif /* READLINE_21_OR_LATER */
}
static VALUE
readline_s_set_basic_quote_characters(self, str)
VALUE self, str;
{
-#ifdef HAVE_RL_BASIC_QUOTE_CHARACTERS
+#ifdef READLINE_21_OR_LATER
static char *basic_quote_characters = NULL;
- rb_secure(4);
- SafeStringValue(str);
+ StringValue(str);
if (basic_quote_characters == NULL) {
basic_quote_characters =
ALLOC_N(char, RSTRING(str)->len + 1);
@@ -382,34 +327,30 @@ readline_s_set_basic_quote_characters(self, str)
return self;
#else
rb_notimplement();
- return Qnil; /* not reached */
-#endif /* HAVE_RL_BASIC_QUOTE_CHARACTERS */
+#endif /* READLINE_21_OR_LATER */
}
static VALUE
readline_s_get_basic_quote_characters(self, str)
VALUE self, str;
{
-#ifdef HAVE_RL_BASIC_QUOTE_CHARACTERS
- rb_secure(4);
+#ifdef READLINE_21_OR_LATER
if (rl_basic_quote_characters == NULL)
return Qnil;
- return rb_tainted_str_new2(rl_basic_quote_characters);
+ return rb_str_new2(rl_basic_quote_characters);
#else
rb_notimplement();
- return Qnil; /* not reached */
-#endif /* HAVE_RL_BASIC_QUOTE_CHARACTERS */
+#endif /* READLINE_21_OR_LATER */
}
static VALUE
readline_s_set_completer_quote_characters(self, str)
VALUE self, str;
{
-#ifdef HAVE_RL_COMPLETER_QUOTE_CHARACTERS
+#ifdef READLINE_21_OR_LATER
static char *completer_quote_characters = NULL;
- rb_secure(4);
- SafeStringValue(str);
+ StringValue(str);
if (completer_quote_characters == NULL) {
completer_quote_characters =
ALLOC_N(char, RSTRING(str)->len + 1);
@@ -425,34 +366,30 @@ readline_s_set_completer_quote_characters(self, str)
return self;
#else
rb_notimplement();
- return Qnil; /* not reached */
-#endif /* HAVE_RL_COMPLETER_QUOTE_CHARACTERS */
+#endif /* READLINE_21_OR_LATER */
}
static VALUE
readline_s_get_completer_quote_characters(self, str)
VALUE self, str;
{
-#ifdef HAVE_RL_COMPLETER_QUOTE_CHARACTERS
- rb_secure(4);
+#ifdef READLINE_21_OR_LATER
if (rl_completer_quote_characters == NULL)
return Qnil;
- return rb_tainted_str_new2(rl_completer_quote_characters);
+ return rb_str_new2(rl_completer_quote_characters);
#else
rb_notimplement();
- return Qnil; /* not reached */
-#endif /* HAVE_RL_COMPLETER_QUOTE_CHARACTERS */
+#endif /* READLINE_21_OR_LATER */
}
static VALUE
readline_s_set_filename_quote_characters(self, str)
VALUE self, str;
{
-#ifdef HAVE_RL_FILENAME_QUOTE_CHARACTERS
+#ifdef READLINE_21_OR_LATER
static char *filename_quote_characters = NULL;
- rb_secure(4);
- SafeStringValue(str);
+ StringValue(str);
if (filename_quote_characters == NULL) {
filename_quote_characters =
ALLOC_N(char, RSTRING(str)->len + 1);
@@ -468,23 +405,37 @@ readline_s_set_filename_quote_characters(self, str)
return self;
#else
rb_notimplement();
- return Qnil; /* not reached */
-#endif /* HAVE_RL_FILENAME_QUOTE_CHARACTERS */
+#endif /* READLINE_21_OR_LATER */
}
static VALUE
readline_s_get_filename_quote_characters(self, str)
VALUE self, str;
{
-#ifdef HAVE_RL_FILENAME_QUOTE_CHARACTERS
- rb_secure(4);
+#ifdef READLINE_21_OR_LATER
if (rl_filename_quote_characters == NULL)
return Qnil;
- return rb_tainted_str_new2(rl_filename_quote_characters);
+ return rb_str_new2(rl_filename_quote_characters);
#else
rb_notimplement();
- return Qnil; /* not reached */
-#endif /* HAVE_RL_FILENAME_QUOTE_CHARACTERS */
+#endif /* READLINE_21_OR_LATER */
+}
+
+static VALUE
+rb_remove_history(index)
+ int index;
+{
+ HIST_ENTRY *entry;
+ VALUE val;
+
+ entry = remove_history(index);
+ if (entry) {
+ val = rb_tainted_str_new2(entry->line);
+ free(entry->line);
+ free(entry);
+ return val;
+ }
+ return Qnil;
}
static VALUE
@@ -499,19 +450,18 @@ hist_get(self, index)
VALUE self;
VALUE index;
{
- HIST_ENTRY *entry;
+ HISTORY_STATE *state;
int i;
- rb_secure(4);
+ state = history_get_history_state();
i = NUM2INT(index);
if (i < 0) {
- i += history_length;
+ i += state->length;
}
- entry = history_get(history_base + i);
- if (entry == NULL) {
- rb_raise(rb_eIndexError, "invalid index");
+ if (i < 0 || i > state->length - 1) {
+ rb_raise(rb_eIndexError, "Invalid index");
}
- return rb_tainted_str_new2(entry->line);
+ return rb_tainted_str_new2(state->entries[i]->line);
}
static VALUE
@@ -520,25 +470,20 @@ hist_set(self, index, str)
VALUE index;
VALUE str;
{
-#ifdef HAVE_REPLACE_HISTORY_ENTRY
- HIST_ENTRY *entry;
+ HISTORY_STATE *state;
+ VALUE s = str;
int i;
- rb_secure(4);
+ state = history_get_history_state();
i = NUM2INT(index);
- SafeStringValue(str);
if (i < 0) {
- i += history_length;
+ i += state->length;
}
- entry = replace_history_entry(i, RSTRING(str)->ptr, NULL);
- if (entry == NULL) {
- rb_raise(rb_eIndexError, "invalid index");
+ if (i < 0 || i > state->length - 1) {
+ rb_raise(rb_eIndexError, "Invalid index");
}
+ replace_history_entry(i, StringValuePtr(s), NULL);
return str;
-#else
- rb_notimplement();
- return Qnil; /* not reached */
-#endif
}
static VALUE
@@ -546,9 +491,7 @@ hist_push(self, str)
VALUE self;
VALUE str;
{
- rb_secure(4);
- SafeStringValue(str);
- add_history(RSTRING(str)->ptr);
+ add_history(StringValuePtr(str));
return self;
}
@@ -560,45 +503,22 @@ hist_push_method(argc, argv, self)
{
VALUE str;
- rb_secure(4);
while (argc--) {
str = *argv++;
- SafeStringValue(str);
- add_history(RSTRING(str)->ptr);
+ add_history(StringValuePtr(str));
}
return self;
}
static VALUE
-rb_remove_history(index)
- int index;
-{
-#ifdef HAVE_REMOVE_HISTORY
- HIST_ENTRY *entry;
- VALUE val;
-
- rb_secure(4);
- entry = remove_history(index);
- if (entry) {
- val = rb_tainted_str_new2(entry->line);
- free(entry->line);
- free(entry);
- return val;
- }
- return Qnil;
-#else
- rb_notimplement();
- return Qnil; /* not reached */
-#endif
-}
-
-static VALUE
hist_pop(self)
VALUE self;
{
- rb_secure(4);
- if (history_length > 0) {
- return rb_remove_history(history_length - 1);
+ HISTORY_STATE *state;
+
+ state = history_get_history_state();
+ if (state->length > 0) {
+ return rb_remove_history(state->length - 1);
} else {
return Qnil;
}
@@ -608,8 +528,10 @@ static VALUE
hist_shift(self)
VALUE self;
{
- rb_secure(4);
- if (history_length > 0) {
+ HISTORY_STATE *state;
+
+ state = history_get_history_state();
+ if (state->length > 0) {
return rb_remove_history(0);
} else {
return Qnil;
@@ -620,15 +542,12 @@ static VALUE
hist_each(self)
VALUE self;
{
- HIST_ENTRY *entry;
+ HISTORY_STATE *state;
int i;
- rb_secure(4);
- for (i = 0; i < history_length; i++) {
- entry = history_get(history_base + i);
- if (entry == NULL)
- break;
- rb_yield(rb_tainted_str_new2(entry->line));
+ state = history_get_history_state();
+ for (i = 0; i < state->length; i++) {
+ rb_yield(rb_tainted_str_new2(state->entries[i]->line));
}
return self;
}
@@ -637,16 +556,23 @@ static VALUE
hist_length(self)
VALUE self;
{
- rb_secure(4);
- return INT2NUM(history_length);
+ HISTORY_STATE *state;
+
+ state = history_get_history_state();
+ return INT2NUM(state->length);
}
static VALUE
hist_empty_p(self)
VALUE self;
{
- rb_secure(4);
- return history_length == 0 ? Qtrue : Qfalse;
+ HISTORY_STATE *state;
+
+ state = history_get_history_state();
+ if (state->length == 0)
+ return Qtrue;
+ else
+ return Qfalse;
}
static VALUE
@@ -654,14 +580,15 @@ hist_delete_at(self, index)
VALUE self;
VALUE index;
{
+ HISTORY_STATE *state;
int i;
- rb_secure(4);
+ state = history_get_history_state();
i = NUM2INT(index);
if (i < 0)
- i += history_length;
- if (i < 0 || i > history_length - 1) {
- rb_raise(rb_eIndexError, "invalid index");
+ i += state->length;
+ if (i < 0 || i > state->length - 1) {
+ rb_raise(rb_eIndexError, "Invalid index");
}
return rb_remove_history(i);
}
@@ -730,9 +657,6 @@ Init_readline()
using_history();
- completion_proc = rb_intern(COMPLETION_PROC);
- completion_case_fold = rb_intern(COMPLETION_CASE_FOLD);
-
mReadline = rb_define_module("Readline");
rb_define_module_function(mReadline, "readline",
readline_readline, -1);
@@ -785,6 +709,7 @@ Init_readline()
rb_define_singleton_method(history,"each", hist_each, 0);
rb_define_singleton_method(history,"length", hist_length, 0);
rb_define_singleton_method(history,"size", hist_length, 0);
+
rb_define_singleton_method(history,"empty?", hist_empty_p, 0);
rb_define_singleton_method(history,"delete_at", hist_delete_at, 1);
rb_define_const(mReadline, "HISTORY", history);
@@ -798,18 +723,21 @@ Init_readline()
rb_define_singleton_method(ucomp, "call",
username_completion_proc_call, 1);
rb_define_const(mReadline, "USERNAME_COMPLETION_PROC", ucomp);
-#if defined HAVE_RL_LIBRARY_VERSION
+#if defined READLINE_21_OR_LATER
rb_define_const(mReadline, "VERSION", rb_str_new2(rl_library_version));
#else
rb_define_const(mReadline, "VERSION",
rb_str_new2("2.0 or before version"));
#endif
- rl_attempted_completion_function = readline_attempted_completion_function;
-#ifdef HAVE_RL_EVENT_HOOK
+#if defined READLINE_42_OR_LATER
+ rl_attempted_completion_function
+ = (rl_completion_func_t *)readline_attempted_completion_function;
+ rl_event_hook = (rl_hook_func_t *)readline_event;
+#else
+ rl_attempted_completion_function
+ = (CPPFunction *) readline_attempted_completion_function;
rl_event_hook = readline_event;
#endif
-#ifdef HAVE_RL_CLEAR_SIGNALS
rl_clear_signals();
-#endif
}
diff --git a/ext/sdbm/_sdbm.c b/ext/sdbm/_sdbm.c
index d4cf621ea5..d8bfae80b2 100644
--- a/ext/sdbm/_sdbm.c
+++ b/ext/sdbm/_sdbm.c
@@ -103,7 +103,7 @@ static int duppair proto((char *, datum));
/*
* externals
*/
-#if !defined sun && !defined MSDOS && !defined _WIN32 && !defined __CYGWIN__ && !defined(errno)
+#if !defined sun && !defined MSDOS && !defined _WIN32 && !defined __CYGWIN__
extern int errno;
#endif
diff --git a/ext/sdbm/init.c b/ext/sdbm/init.c
index acadc9b26a..ed39769e7a 100644
--- a/ext/sdbm/init.c
+++ b/ext/sdbm/init.c
@@ -31,15 +31,9 @@ closed_sdbm()
#define GetDBM(obj, dbmp) {\
Data_Get_Struct(obj, struct dbmdata, dbmp);\
- if (dbmp == 0) closed_sdbm();\
if (dbmp->di_dbm == 0) closed_sdbm();\
}
-#define GetDBM2(obj, data, dbm) {\
- GetDBM(obj, data);\
- (dbm) = dbmp->di_dbm;\
-}
-
static void
free_sdbm(dbmp)
struct dbmdata *dbmp;
@@ -62,21 +56,6 @@ fsdbm_close(obj)
return Qnil;
}
-static VALUE
-fsdbm_closed(obj)
- VALUE obj;
-{
- struct dbmdata *dbmp;
-
- Data_Get_Struct(obj, struct dbmdata, dbmp);
- if (dbmp == 0)
- return Qtrue;
- if (dbmp->di_dbm == 0)
- return Qtrue;
-
- return Qfalse;
-}
-
static VALUE fsdbm_alloc _((VALUE));
static VALUE
fsdbm_alloc(klass)
@@ -159,7 +138,8 @@ fsdbm_fetch(obj, keystr, ifnone)
key.dptr = RSTRING(keystr)->ptr;
key.dsize = RSTRING(keystr)->len;
- GetDBM2(obj, dbmp, dbm);
+ GetDBM(obj, dbmp);
+ dbm = dbmp->di_dbm;
value = sdbm_fetch(dbm, key);
if (value.dptr == 0) {
if (ifnone == Qnil && rb_block_given_p())
@@ -204,7 +184,8 @@ fsdbm_index(obj, valstr)
val.dptr = RSTRING(valstr)->ptr;
val.dsize = RSTRING(valstr)->len;
- GetDBM2(obj, dbmp, dbm);
+ GetDBM(obj, dbmp);
+ dbm = dbmp->di_dbm;
for (key = sdbm_firstkey(dbm); key.dptr; key = sdbm_nextkey(dbm)) {
val = sdbm_fetch(dbm, key);
if (val.dsize == RSTRING(valstr)->len &&
@@ -248,17 +229,16 @@ fsdbm_select(argc, argv, obj)
if (argc > 0) {
rb_raise(rb_eArgError, "wrong number of arguments (%d for 0)", argc);
}
- GetDBM2(obj, dbmp, dbm);
+ GetDBM(obj, dbmp);
+ dbm = dbmp->di_dbm;
+
for (key = sdbm_firstkey(dbm); key.dptr; key = sdbm_nextkey(dbm)) {
- VALUE assoc, v;
+ VALUE assoc;
val = sdbm_fetch(dbm, key);
assoc = rb_assoc_new(rb_tainted_str_new(key.dptr, key.dsize),
rb_tainted_str_new(val.dptr, val.dsize));
- v = rb_yield(assoc);
- if (RTEST(v)) {
- rb_ary_push(new, assoc);
- }
- GetDBM2(obj, dbmp, dbm);
+ if (RTEST(rb_yield(assoc)))
+ rb_ary_push(new, assoc);
}
}
else {
@@ -310,7 +290,8 @@ fsdbm_delete(obj, keystr)
key.dptr = RSTRING(keystr)->ptr;
key.dsize = RSTRING(keystr)->len;
- GetDBM2(obj, dbmp, dbm);
+ GetDBM(obj, dbmp);
+ dbm = dbmp->di_dbm;
dbmp->di_size = -1;
value = sdbm_fetch(dbm, key);
@@ -342,7 +323,9 @@ fsdbm_shift(obj)
VALUE keystr, valstr;
fdbm_modify(obj);
- GetDBM2(obj, dbmp, dbm);
+ GetDBM(obj, dbmp);
+ dbm = dbmp->di_dbm;
+
key = sdbm_firstkey(dbm);
if (!key.dptr) return Qnil;
val = sdbm_fetch(dbm, key);
@@ -368,7 +351,8 @@ fsdbm_delete_if(obj)
int i, status = 0, n;
fdbm_modify(obj);
- GetDBM2(obj, dbmp, dbm);
+ GetDBM(obj, dbmp);
+ dbm = dbmp->di_dbm;
n = dbmp->di_size;
dbmp->di_size = -1;
for (key = sdbm_firstkey(dbm); key.dptr; key = sdbm_nextkey(dbm)) {
@@ -378,7 +362,6 @@ fsdbm_delete_if(obj)
ret = rb_protect(rb_yield, rb_assoc_new(rb_str_dup(keystr), valstr), &status);
if (status != 0) break;
if (RTEST(ret)) rb_ary_push(ary, keystr);
- GetDBM2(obj, dbmp, dbm);
}
for (i = 0; i < RARRAY(ary)->len; i++) {
@@ -405,7 +388,8 @@ fsdbm_clear(obj)
DBM *dbm;
fdbm_modify(obj);
- GetDBM2(obj, dbmp, dbm);
+ GetDBM(obj, dbmp);
+ dbm = dbmp->di_dbm;
dbmp->di_size = -1;
while (key = sdbm_firstkey(dbm), key.dptr) {
if (sdbm_delete(dbm, key)) {
@@ -427,7 +411,8 @@ fsdbm_invert(obj)
VALUE keystr, valstr;
VALUE hash = rb_hash_new();
- GetDBM2(obj, dbmp, dbm);
+ GetDBM(obj, dbmp);
+ dbm = dbmp->di_dbm;
for (key = sdbm_firstkey(dbm); key.dptr; key = sdbm_nextkey(dbm)) {
val = sdbm_fetch(dbm, key);
keystr = rb_tainted_str_new(key.dptr, key.dsize);
@@ -492,16 +477,17 @@ fsdbm_store(obj, keystr, valstr)
fdbm_modify(obj);
StringValue(keystr);
- StringValue(valstr);
key.dptr = RSTRING(keystr)->ptr;
key.dsize = RSTRING(keystr)->len;
+ StringValue(valstr);
val.dptr = RSTRING(valstr)->ptr;
val.dsize = RSTRING(valstr)->len;
- GetDBM2(obj, dbmp, dbm);
+ GetDBM(obj, dbmp);
dbmp->di_size = -1;
+ dbm = dbmp->di_dbm;
if (sdbm_store(dbm, key, val, DBM_REPLACE)) {
#ifdef HAVE_DBM_CLAERERR
sdbm_clearerr(dbm);
@@ -522,8 +508,9 @@ fsdbm_length(obj)
DBM *dbm;
int i = 0;
- GetDBM2(obj, dbmp, dbm);
+ GetDBM(obj, dbmp);
if (dbmp->di_size > 0) return INT2FIX(dbmp->di_size);
+ dbm = dbmp->di_dbm;
for (key = sdbm_firstkey(dbm); key.dptr; key = sdbm_nextkey(dbm)) {
i++;
@@ -565,11 +552,11 @@ fsdbm_each_value(obj)
struct dbmdata *dbmp;
DBM *dbm;
- GetDBM2(obj, dbmp, dbm);
+ GetDBM(obj, dbmp);
+ dbm = dbmp->di_dbm;
for (key = sdbm_firstkey(dbm); key.dptr; key = sdbm_nextkey(dbm)) {
val = sdbm_fetch(dbm, key);
rb_yield(rb_tainted_str_new(val.dptr, val.dsize));
- GetDBM2(obj, dbmp, dbm);
}
return obj;
}
@@ -582,10 +569,10 @@ fsdbm_each_key(obj)
struct dbmdata *dbmp;
DBM *dbm;
- GetDBM2(obj, dbmp, dbm);
+ GetDBM(obj, dbmp);
+ dbm = dbmp->di_dbm;
for (key = sdbm_firstkey(dbm); key.dptr; key = sdbm_nextkey(dbm)) {
rb_yield(rb_tainted_str_new(key.dptr, key.dsize));
- GetDBM2(obj, dbmp, dbm);
}
return obj;
}
@@ -599,13 +586,14 @@ fsdbm_each_pair(obj)
struct dbmdata *dbmp;
VALUE keystr, valstr;
- GetDBM2(obj, dbmp, dbm);
+ GetDBM(obj, dbmp);
+ dbm = dbmp->di_dbm;
+
for (key = sdbm_firstkey(dbm); key.dptr; key = sdbm_nextkey(dbm)) {
val = sdbm_fetch(dbm, key);
keystr = rb_tainted_str_new(key.dptr, key.dsize);
valstr = rb_tainted_str_new(val.dptr, val.dsize);
rb_yield(rb_assoc_new(keystr, valstr));
- GetDBM2(obj, dbmp, dbm);
}
return obj;
@@ -620,7 +608,9 @@ fsdbm_keys(obj)
DBM *dbm;
VALUE ary;
- GetDBM2(obj, dbmp, dbm);
+ GetDBM(obj, dbmp);
+ dbm = dbmp->di_dbm;
+
ary = rb_ary_new();
for (key = sdbm_firstkey(dbm); key.dptr; key = sdbm_nextkey(dbm)) {
rb_ary_push(ary, rb_tainted_str_new(key.dptr, key.dsize));
@@ -638,7 +628,9 @@ fsdbm_values(obj)
DBM *dbm;
VALUE ary;
- GetDBM2(obj, dbmp, dbm);
+ GetDBM(obj, dbmp);
+ dbm = dbmp->di_dbm;
+
ary = rb_ary_new();
for (key = sdbm_firstkey(dbm); key.dptr; key = sdbm_nextkey(dbm)) {
val = sdbm_fetch(dbm, key);
@@ -660,7 +652,8 @@ fsdbm_has_key(obj, keystr)
key.dptr = RSTRING(keystr)->ptr;
key.dsize = RSTRING(keystr)->len;
- GetDBM2(obj, dbmp, dbm);
+ GetDBM(obj, dbmp);
+ dbm = dbmp->di_dbm;
val = sdbm_fetch(dbm, key);
if (val.dptr) return Qtrue;
return Qfalse;
@@ -678,7 +671,8 @@ fsdbm_has_value(obj, valstr)
val.dptr = RSTRING(valstr)->ptr;
val.dsize = RSTRING(valstr)->len;
- GetDBM2(obj, dbmp, dbm);
+ GetDBM(obj, dbmp);
+ dbm = dbmp->di_dbm;
for (key = sdbm_firstkey(dbm); key.dptr; key = sdbm_nextkey(dbm)) {
val = sdbm_fetch(dbm, key);
if (val.dsize == RSTRING(valstr)->len &&
@@ -697,7 +691,9 @@ fsdbm_to_a(obj)
DBM *dbm;
VALUE ary;
- GetDBM2(obj, dbmp, dbm);
+ GetDBM(obj, dbmp);
+ dbm = dbmp->di_dbm;
+
ary = rb_ary_new();
for (key = sdbm_firstkey(dbm); key.dptr; key = sdbm_nextkey(dbm)) {
val = sdbm_fetch(dbm, key);
@@ -717,7 +713,9 @@ fsdbm_to_hash(obj)
DBM *dbm;
VALUE hash;
- GetDBM2(obj, dbmp, dbm);
+ GetDBM(obj, dbmp);
+ dbm = dbmp->di_dbm;
+
hash = rb_hash_new();
for (key = sdbm_firstkey(dbm); key.dptr; key = sdbm_nextkey(dbm)) {
val = sdbm_fetch(dbm, key);
@@ -747,7 +745,6 @@ Init_sdbm()
rb_define_method(rb_cDBM, "initialize", fsdbm_initialize, -1);
rb_define_method(rb_cDBM, "close", fsdbm_close, 0);
- rb_define_method(rb_cDBM, "closed?", fsdbm_closed, 0);
rb_define_method(rb_cDBM, "[]", fsdbm_aref, 1);
rb_define_method(rb_cDBM, "fetch", fsdbm_fetch_m, -1);
rb_define_method(rb_cDBM, "[]=", fsdbm_store, 2);
diff --git a/test/sdbm/test_sdbm.rb b/ext/sdbm/testsdbm.rb
index 17b3d3c4e7..5a185fd5c4 100644
--- a/test/sdbm/test_sdbm.rb
+++ b/ext/sdbm/testsdbm.rb
@@ -1,42 +1,52 @@
-require 'test/unit'
+require 'runit/testcase'
+require 'runit/cui/testrunner'
-begin
- require 'sdbm'
-rescue LoadError
+if $".grep(/\bsdbm.so\b/).empty?
+ begin
+ require './sdbm'
+ rescue LoadError
+ require 'sdbm'
+ end
+end
+
+def uname_s
+ require 'rbconfig'
+ case Config::CONFIG['host_os']
+ when 'cygwin'
+ require 'Win32API'
+ uname = Win32API.new('cygwin1', 'uname', 'P', 'I')
+ utsname = ' ' * 100
+ raise 'cannot get system name' if uname.call(utsname) == -1
+
+ utsname.unpack('A20' * 5)[0]
+ else
+ Config::CONFIG['host_os']
+ end
end
-class TestSDBM < Test::Unit::TestCase
+SYSTEM = uname_s
+
+class TestSDBM < RUNIT::TestCase
def setup
@path = "tmptest_sdbm_"
assert_instance_of(SDBM, @sdbm = SDBM.new(@path))
end
def teardown
assert_nil(@sdbm.close)
- ObjectSpace.each_object(SDBM) do |obj|
- obj.close unless obj.closed?
- end
+ GC.start
File.delete *Dir.glob("tmptest_sdbm*").to_a
p Dir.glob("tmptest_sdbm*") if $DEBUG
end
def check_size(expect, sdbm=@sdbm)
- assert_equal(expect, sdbm.size)
+ assert_equals(expect, sdbm.size)
n = 0
sdbm.each { n+=1 }
- assert_equal(expect, n)
+ assert_equals(expect, n)
if expect == 0
- assert_equal(true, sdbm.empty?)
+ assert_equals(true, sdbm.empty?)
else
- assert_equal(false, sdbm.empty?)
- end
- end
-
- def have_fork?
- begin
- fork{}
- true
- rescue NotImplementedError
- false
+ assert_equals(false, sdbm.empty?)
end
end
@@ -48,7 +58,7 @@ class TestSDBM < Test::Unit::TestCase
# SDBM.new ignore the block
foo = true
assert_instance_of(SDBM, sdbm = SDBM.new("tmptest_sdbm") { foo = false })
- assert_equal(foo, true)
+ assert_equals(foo, true)
assert_nil(sdbm.close)
end
def test_s_open_no_create
@@ -57,14 +67,14 @@ class TestSDBM < Test::Unit::TestCase
sdbm.close if sdbm
end
def test_s_open_with_block
- assert_equal(SDBM.open("tmptest_sdbm") { :foo }, :foo)
+ assert_equals(SDBM.open("tmptest_sdbm") { :foo }, :foo)
end
=begin
# Is it guaranteed on many OS?
def test_s_open_lock_one_process
# locking on one process
assert_instance_of(SDBM, sdbm = SDBM.open("tmptest_sdbm", 0644))
- assert_raise(Errno::EWOULDBLOCK) {
+ assert_exception(Errno::EWOULDBLOCK) {
begin
SDBM.open("tmptest_sdbm", 0644)
rescue Errno::EAGAIN
@@ -79,7 +89,6 @@ class TestSDBM < Test::Unit::TestCase
if not defined? SDBM::NOLOCK
return
end
- return unless have_fork? # snip this test
fork() {
assert_instance_of(SDBM, sdbm = SDBM.open("tmptest_sdbm", 0644,
@@ -119,7 +128,7 @@ class TestSDBM < Test::Unit::TestCase
def test_s_open_error
assert_instance_of(SDBM, sdbm = SDBM.open("tmptest_sdbm", 0))
- assert_raise(Errno::EACCES) {
+ assert_exception(Errno::EACCES) {
SDBM.open("tmptest_sdbm", 0)
}
sdbm.close
@@ -130,76 +139,76 @@ class TestSDBM < Test::Unit::TestCase
assert_nil(sdbm.close)
# closed SDBM file
- assert_raise(SDBMError) { sdbm.close }
+ assert_exception(SDBMError) { sdbm.close }
end
def test_aref
- assert_equal('bar', @sdbm['foo'] = 'bar')
- assert_equal('bar', @sdbm['foo'])
+ assert_equals('bar', @sdbm['foo'] = 'bar')
+ assert_equals('bar', @sdbm['foo'])
assert_nil(@sdbm['bar'])
end
def test_fetch
- assert_equal('bar', @sdbm['foo']='bar')
- assert_equal('bar', @sdbm.fetch('foo'))
+ assert_equals('bar', @sdbm['foo']='bar')
+ assert_equals('bar', @sdbm.fetch('foo'))
# key not found
- assert_raise(IndexError) {
+ assert_exception(IndexError) {
@sdbm.fetch('bar')
}
# test for `ifnone' arg
- assert_equal('baz', @sdbm.fetch('bar', 'baz'))
+ assert_equals('baz', @sdbm.fetch('bar', 'baz'))
# test for `ifnone' block
- assert_equal('foobar', @sdbm.fetch('bar') {|key| 'foo' + key })
+ assert_equals('foobar', @sdbm.fetch('bar') {|key| 'foo' + key })
end
def test_aset
num = 0
2.times {|i|
- assert_equal('foo', @sdbm['foo'] = 'foo')
- assert_equal('foo', @sdbm['foo'])
- assert_equal('bar', @sdbm['foo'] = 'bar')
- assert_equal('bar', @sdbm['foo'])
+ assert_equals('foo', @sdbm['foo'] = 'foo')
+ assert_equals('foo', @sdbm['foo'])
+ assert_equals('bar', @sdbm['foo'] = 'bar')
+ assert_equals('bar', @sdbm['foo'])
num += 1 if i == 0
- assert_equal(num, @sdbm.size)
+ assert_equals(num, @sdbm.size)
# assign nil
- assert_equal('', @sdbm['bar'] = '')
- assert_equal('', @sdbm['bar'])
+ assert_equals('', @sdbm['bar'] = '')
+ assert_equals('', @sdbm['bar'])
num += 1 if i == 0
- assert_equal(num, @sdbm.size)
+ assert_equals(num, @sdbm.size)
# empty string
- assert_equal('', @sdbm[''] = '')
- assert_equal('', @sdbm[''])
+ assert_equals('', @sdbm[''] = '')
+ assert_equals('', @sdbm[''])
num += 1 if i == 0
- assert_equal(num, @sdbm.size)
+ assert_equals(num, @sdbm.size)
# Fixnum
- assert_equal('200', @sdbm['100'] = '200')
- assert_equal('200', @sdbm['100'])
+ assert_equals('200', @sdbm['100'] = '200')
+ assert_equals('200', @sdbm['100'])
num += 1 if i == 0
- assert_equal(num, @sdbm.size)
+ assert_equals(num, @sdbm.size)
# Big key and value
- assert_equal('y' * 100, @sdbm['x' * 100] = 'y' * 100)
- assert_equal('y' * 100, @sdbm['x' * 100])
+ assert_equals('y' * 100, @sdbm['x' * 100] = 'y' * 100)
+ assert_equals('y' * 100, @sdbm['x' * 100])
num += 1 if i == 0
- assert_equal(num, @sdbm.size)
+ assert_equals(num, @sdbm.size)
}
end
def test_index
- assert_equal('bar', @sdbm['foo'] = 'bar')
- assert_equal('foo', @sdbm.index('bar'))
+ assert_equals('bar', @sdbm['foo'] = 'bar')
+ assert_equals('foo', @sdbm.index('bar'))
assert_nil(@sdbm['bar'])
end
@@ -207,14 +216,14 @@ class TestSDBM < Test::Unit::TestCase
keys = %w(foo bar baz)
values = %w(FOO BAR BAZ)
@sdbm[keys[0]], @sdbm[keys[1]], @sdbm[keys[2]] = values
- assert_equal(values.reverse, @sdbm.indexes(*keys.reverse))
+ assert_equals(values.reverse, @sdbm.indexes(*keys.reverse))
end
def test_values_at
keys = %w(foo bar baz)
values = %w(FOO BAR BAZ)
@sdbm[keys[0]], @sdbm[keys[1]], @sdbm[keys[2]] = values
- assert_equal(values.reverse, @sdbm.values_at(*keys.reverse))
+ assert_equals(values.reverse, @sdbm.values_at(*keys.reverse))
end
def test_select_with_block
@@ -222,37 +231,37 @@ class TestSDBM < Test::Unit::TestCase
values = %w(FOO BAR BAZ)
@sdbm[keys[0]], @sdbm[keys[1]], @sdbm[keys[2]] = values
ret = @sdbm.select {|k,v|
- assert_equal(k.upcase, v)
+ assert_equals(k.upcase, v)
k != "bar"
}
- assert_equal([['baz', 'BAZ'], ['foo', 'FOO']],
+ assert_equals([['baz', 'BAZ'], ['foo', 'FOO']],
ret.sort)
end
def test_length
num = 10
- assert_equal(0, @sdbm.size)
+ assert_equals(0, @sdbm.size)
num.times {|i|
i = i.to_s
@sdbm[i] = i
}
- assert_equal(num, @sdbm.size)
+ assert_equals(num, @sdbm.size)
@sdbm.shift
- assert_equal(num - 1, @sdbm.size)
+ assert_equals(num - 1, @sdbm.size)
end
def test_empty?
- assert_equal(true, @sdbm.empty?)
+ assert_equals(true, @sdbm.empty?)
@sdbm['foo'] = 'FOO'
- assert_equal(false, @sdbm.empty?)
+ assert_equals(false, @sdbm.empty?)
end
def test_each_pair
n = 0
@sdbm.each_pair { n += 1 }
- assert_equal(0, n)
+ assert_equals(0, n)
keys = %w(foo bar baz)
values = %w(FOO BAR BAZ)
@@ -262,18 +271,18 @@ class TestSDBM < Test::Unit::TestCase
n = 0
ret = @sdbm.each_pair {|key, val|
assert_not_nil(i = keys.index(key))
- assert_equal(val, values[i])
+ assert_equals(val, values[i])
n += 1
}
- assert_equal(keys.size, n)
- assert_equal(@sdbm, ret)
+ assert_equals(keys.size, n)
+ assert_equals(@sdbm, ret)
end
def test_each_value
n = 0
@sdbm.each_value { n += 1 }
- assert_equal(0, n)
+ assert_equals(0, n)
keys = %w(foo bar baz)
values = %w(FOO BAR BAZ)
@@ -284,18 +293,18 @@ class TestSDBM < Test::Unit::TestCase
ret = @sdbm.each_value {|val|
assert_not_nil(key = @sdbm.index(val))
assert_not_nil(i = keys.index(key))
- assert_equal(val, values[i])
+ assert_equals(val, values[i])
n += 1
}
- assert_equal(keys.size, n)
- assert_equal(@sdbm, ret)
+ assert_equals(keys.size, n)
+ assert_equals(@sdbm, ret)
end
def test_each_key
n = 0
@sdbm.each_key { n += 1 }
- assert_equal(0, n)
+ assert_equals(0, n)
keys = %w(foo bar baz)
values = %w(FOO BAR BAZ)
@@ -305,24 +314,24 @@ class TestSDBM < Test::Unit::TestCase
n = 0
ret = @sdbm.each_key {|key|
assert_not_nil(i = keys.index(key))
- assert_equal(@sdbm[key], values[i])
+ assert_equals(@sdbm[key], values[i])
n += 1
}
- assert_equal(keys.size, n)
- assert_equal(@sdbm, ret)
+ assert_equals(keys.size, n)
+ assert_equals(@sdbm, ret)
end
def test_keys
- assert_equal([], @sdbm.keys)
+ assert_equals([], @sdbm.keys)
keys = %w(foo bar baz)
values = %w(FOO BAR BAZ)
@sdbm[keys[0]], @sdbm[keys[1]], @sdbm[keys[2]] = values
- assert_equal(keys.sort, @sdbm.keys.sort)
- assert_equal(values.sort, @sdbm.values.sort)
+ assert_equals(keys.sort, @sdbm.keys.sort)
+ assert_equals(values.sort, @sdbm.values.sort)
end
def test_values
@@ -331,7 +340,7 @@ class TestSDBM < Test::Unit::TestCase
def test_shift
assert_nil(@sdbm.shift)
- assert_equal(0, @sdbm.size)
+ assert_equals(0, @sdbm.size)
keys = %w(foo bar baz)
values = %w(FOO BAR BAZ)
@@ -344,11 +353,11 @@ class TestSDBM < Test::Unit::TestCase
ret_keys.push ret[0]
ret_values.push ret[1]
- assert_equal(keys.size - ret_keys.size, @sdbm.size)
+ assert_equals(keys.size - ret_keys.size, @sdbm.size)
end
- assert_equal(keys.sort, ret_keys.sort)
- assert_equal(values.sort, ret_values.sort)
+ assert_equals(keys.sort, ret_keys.sort)
+ assert_equals(values.sort, ret_values.sort)
end
def test_delete
@@ -357,28 +366,28 @@ class TestSDBM < Test::Unit::TestCase
key = keys[1]
assert_nil(@sdbm.delete(key))
- assert_equal(0, @sdbm.size)
+ assert_equals(0, @sdbm.size)
@sdbm[keys[0]], @sdbm[keys[1]], @sdbm[keys[2]] = values
- assert_equal('BAR', @sdbm.delete(key))
+ assert_equals('BAR', @sdbm.delete(key))
assert_nil(@sdbm[key])
- assert_equal(2, @sdbm.size)
+ assert_equals(2, @sdbm.size)
assert_nil(@sdbm.delete(key))
end
def test_delete_with_block
key = 'no called block'
@sdbm[key] = 'foo'
- assert_equal('foo', @sdbm.delete(key) {|k| k.replace 'called block'})
- assert_equal('no called block', key)
- assert_equal(0, @sdbm.size)
+ assert_equals('foo', @sdbm.delete(key) {|k| k.replace 'called block'})
+ assert_equals('no called block', key)
+ assert_equals(0, @sdbm.size)
key = 'no called block'
- assert_equal(:blockval,
+ assert_equals(:blockval,
@sdbm.delete(key) {|k| k.replace 'called block'; :blockval})
- assert_equal('called block', key)
- assert_equal(0, @sdbm.size)
+ assert_equals('called block', key)
+ assert_equals(0, @sdbm.size)
end
def test_delete_if
@@ -386,11 +395,11 @@ class TestSDBM < Test::Unit::TestCase
100.times {@sdbm[v] = v; v = v.next}
ret = @sdbm.delete_if {|key, val| key.to_i < 50}
- assert_equal(@sdbm, ret)
+ assert_equals(@sdbm, ret)
check_size(50, @sdbm)
ret = @sdbm.delete_if {|key, val| key.to_i >= 50}
- assert_equal(@sdbm, ret)
+ assert_equals(@sdbm, ret)
check_size(0, @sdbm)
# break
@@ -403,7 +412,7 @@ class TestSDBM < Test::Unit::TestCase
n+=1
true
}
- assert_equal(51, n)
+ assert_equals(51, n)
check_size(49, @sdbm)
@sdbm.clear
@@ -421,7 +430,7 @@ class TestSDBM < Test::Unit::TestCase
}
rescue
end
- assert_equal(51, n)
+ assert_equals(51, n)
check_size(49, @sdbm)
end
@@ -431,30 +440,30 @@ class TestSDBM < Test::Unit::TestCase
hash = @sdbm.reject {|key, val| key.to_i < 50}
assert_instance_of(Hash, hash)
- assert_equal(100, @sdbm.size)
+ assert_equals(100, @sdbm.size)
- assert_equal(50, hash.size)
+ assert_equals(50, hash.size)
hash.each_pair {|key,val|
- assert_equal(false, key.to_i < 50)
- assert_equal(key, val)
+ assert_equals(false, key.to_i < 50)
+ assert_equals(key, val)
}
hash = @sdbm.reject {|key, val| key.to_i < 100}
assert_instance_of(Hash, hash)
- assert_equal(true, hash.empty?)
+ assert_equals(true, hash.empty?)
end
def test_clear
v = "1"
100.times {v = v.next; @sdbm[v] = v}
- assert_equal(@sdbm, @sdbm.clear)
+ assert_equals(@sdbm, @sdbm.clear)
# validate SDBM#size
i = 0
@sdbm.each { i += 1 }
- assert_equal(@sdbm.size, i)
- assert_equal(0, i)
+ assert_equals(@sdbm.size, i)
+ assert_equals(0, i)
end
def test_invert
@@ -463,9 +472,9 @@ class TestSDBM < Test::Unit::TestCase
hash = @sdbm.invert
assert_instance_of(Hash, hash)
- assert_equal(100, hash.size)
+ assert_equals(100, hash.size)
hash.each_pair {|key, val|
- assert_equal(key.to_i, val.to_i)
+ assert_equals(key.to_i, val.to_i)
}
end
@@ -476,9 +485,9 @@ class TestSDBM < Test::Unit::TestCase
@sdbm["101"] = "101"
@sdbm.update hash
- assert_equal(101, @sdbm.size)
+ assert_equals(101, @sdbm.size)
@sdbm.each_pair {|key, val|
- assert_equal(key.to_i, val.to_i)
+ assert_equals(key.to_i, val.to_i)
}
end
@@ -489,22 +498,22 @@ class TestSDBM < Test::Unit::TestCase
@sdbm["101"] = "101"
@sdbm.replace hash
- assert_equal(100, @sdbm.size)
+ assert_equals(100, @sdbm.size)
@sdbm.each_pair {|key, val|
- assert_equal(key.to_i, val.to_i)
+ assert_equals(key.to_i, val.to_i)
}
end
def test_haskey?
- assert_equal('bar', @sdbm['foo']='bar')
- assert_equal(true, @sdbm.has_key?('foo'))
- assert_equal(false, @sdbm.has_key?('bar'))
+ assert_equals('bar', @sdbm['foo']='bar')
+ assert_equals(true, @sdbm.has_key?('foo'))
+ assert_equals(false, @sdbm.has_key?('bar'))
end
def test_has_value?
- assert_equal('bar', @sdbm['foo']='bar')
- assert_equal(true, @sdbm.has_value?('bar'))
- assert_equal(false, @sdbm.has_value?('foo'))
+ assert_equals('bar', @sdbm['foo']='bar')
+ assert_equals(true, @sdbm.has_value?('bar'))
+ assert_equals(false, @sdbm.has_value?('foo'))
end
def test_to_a
@@ -513,9 +522,9 @@ class TestSDBM < Test::Unit::TestCase
ary = @sdbm.to_a
assert_instance_of(Array, ary)
- assert_equal(100, ary.size)
+ assert_equals(100, ary.size)
ary.each {|key,val|
- assert_equal(key.to_i, val.to_i)
+ assert_equals(key.to_i, val.to_i)
}
end
@@ -525,9 +534,23 @@ class TestSDBM < Test::Unit::TestCase
hash = @sdbm.to_hash
assert_instance_of(Hash, hash)
- assert_equal(100, hash.size)
+ assert_equals(100, hash.size)
hash.each {|key,val|
- assert_equal(key.to_i, val.to_i)
+ assert_equals(key.to_i, val.to_i)
}
end
end
+
+if $0 == __FILE__
+ if ARGV.size == 0
+ suite = RUNIT::TestSuite.new
+ suite.add_test(TestSDBM.suite)
+ else
+ suite = RUNIT::TestSuite.new
+ ARGV.each do |testmethod|
+ suite.add_test(TestSDBM.new(testmethod))
+ end
+ end
+
+ RUNIT::CUI::TestRunner.run(suite)
+end
diff --git a/ext/socket/extconf.rb b/ext/socket/extconf.rb
index 28f38140b4..4f7b49407f 100644
--- a/ext/socket/extconf.rb
+++ b/ext/socket/extconf.rb
@@ -4,9 +4,11 @@ case RUBY_PLATFORM
when /bccwin32/
test_func = "WSACleanup"
have_library("ws2_32", "WSACleanup")
+ have_func("closesocket")
when /mswin32|mingw/
test_func = "WSACleanup"
have_library("wsock32", "WSACleanup")
+ have_func("closesocket")
when /cygwin/
test_func = "socket"
when /beos/
@@ -22,18 +24,10 @@ else
have_library("socket", "socket")
end
-unless $mswin or $bccwin or $mingw
- headers = %w<sys/types.h netdb.h string.h sys/socket.h netinet/in.h>
-end
-if /solaris/ =~ RUBY_PLATFORM and !try_compile("")
- # bug of gcc 3.0 on Solaris 8 ?
- headers << "sys/feature_tests.h"
-end
-
$ipv6 = false
default_ipv6 = /cygwin/ !~ RUBY_PLATFORM
if enable_config("ipv6", default_ipv6)
- if checking_for("ipv6") {try_link(<<EOF)}
+ if try_link(<<EOF)
#include <sys/types.h>
#include <sys/socket.h>
main()
@@ -111,26 +105,90 @@ EOS
end
end
-if have_struct_member("struct sockaddr_in", "sin_len", headers)
- $defs[-1] = "-DHAVE_SIN_LEN"
+ if try_link(<<EOF)
+#ifdef _WIN32
+# include <windows.h>
+# include <winsock.h>
+#else
+# include <sys/types.h>
+# include <netdb.h>
+# include <string.h>
+# include <sys/socket.h>
+# include <netinet/in.h>
+#endif
+int
+main()
+{
+ struct sockaddr_in sin;
+
+ sin.sin_len;
+ return 0;
+}
+EOF
+ $CFLAGS="-DHAVE_SIN_LEN "+$CFLAGS
end
-# doug's fix, NOW add -Dss_family... only if required!
-[nil, " -Dss_family=__ss_family -Dss_len=__ss_len"].each do |flags|
- if flags
- cppflags = $CPPFLAGS
- $CPPFLAGS += flags
- end
- if have_struct_member("struct sockaddr_storage", "ss_family", headers)
- $defs[-1] = "-DHAVE_SOCKADDR_STORAGE"
- break
- elsif flags
- $CPPFLAGS = cppflags
- end
+ if try_link(<<EOF)
+#ifdef _WIN32
+# include <windows.h>
+# include <winsock.h>
+#else
+# include <sys/types.h>
+# include <netdb.h>
+# include <string.h>
+# include <sys/socket.h>
+#endif
+int
+main()
+{
+ struct sockaddr_storage ss;
+
+ ss.ss_family;
+ return 0;
+}
+EOF
+ $CFLAGS="-DHAVE_SOCKADDR_STORAGE "+$CFLAGS
+else # doug's fix, NOW add -Dss_family... only if required!
+$CPPFLAGS += " -Dss_family=__ss_family -Dss_len=__ss_len"
+ if try_link(<<EOF)
+#ifdef _WIN32
+# include <windows.h>
+# include <winsock.h>
+#else
+# include <sys/types.h>
+# include <netdb.h>
+# include <string.h>
+# include <sys/socket.h>
+#endif
+int
+main()
+{
+ struct sockaddr_storage ss;
+
+ ss.ss_family;
+ return 0;
+}
+EOF
+ $CFLAGS="-DHAVE_SOCKADDR_STORAGE "+$CFLAGS
+end
end
-if have_struct_member("struct sockaddr", "sa_len", headers)
- $defs[-1] = "-DHAVE_SA_LEN "
+ if try_link(<<EOF)
+#include <sys/types.h>
+#include <netdb.h>
+#include <string.h>
+#include <sys/socket.h>
+#include <netinet/in.h>
+int
+main()
+{
+ struct sockaddr sa;
+
+ sa.sa_len;
+ return 0;
+}
+EOF
+ $CFLAGS="-DHAVE_SA_LEN "+$CFLAGS
end
have_header("netinet/tcp.h") if not /cygwin/ =~ RUBY_PLATFORM # for cygwin 1.1.5
@@ -141,17 +199,13 @@ if have_func("sendmsg") | have_func("recvmsg")
have_struct_member('struct msghdr', 'msg_accrights', ['sys/types.h', 'sys/socket.h'])
end
-getaddr_info_ok = enable_config("wide-getaddrinfo") do
- checking_for("wide getaddrinfo") {try_run(<<EOF)}
-#{cpp_include(headers)}
-#include <stdlib.h>
-
-#ifndef EXIT_SUCCESS
-#define EXIT_SUCCESS 0
-#endif
-#ifndef EXIT_FAILURE
-#define EXIT_FAILURE 1
-#endif
+$getaddr_info_ok = false
+if !enable_config("wide-getaddrinfo", false) and try_run(<<EOF)
+#include <sys/types.h>
+#include <netdb.h>
+#include <string.h>
+#include <sys/socket.h>
+#include <netinet/in.h>
#ifndef AF_LOCAL
#define AF_LOCAL AF_UNIX
@@ -175,13 +229,8 @@ main()
}
for (ai = aitop; ai; ai = ai->ai_next) {
if (ai->ai_family == AF_LOCAL) continue;
- if (ai->ai_addr == NULL)
- goto bad;
-#if defined(_AIX)
- ai->ai_addr->sa_len = ai->ai_addrlen;
- ai->ai_addr->sa_family = ai->ai_family;
-#endif
- if (ai->ai_addrlen == 0 ||
+ if (ai->ai_addr == NULL ||
+ ai->ai_addrlen == 0 ||
getnameinfo(ai->ai_addr, ai->ai_addrlen,
straddr, sizeof(straddr), strport, sizeof(strport),
NI_NUMERICHOST|NI_NUMERICSERV) != 0) {
@@ -232,46 +281,79 @@ main()
if (aitop)
freeaddrinfo(aitop);
- exit(EXIT_SUCCESS);
+ exit(0);
bad:
if (aitop)
freeaddrinfo(aitop);
- exit(EXIT_FAILURE);
+ exit(1);
}
EOF
+ $getaddr_info_ok = true
end
-if $ipv6 and not getaddr_info_ok
- abort <<EOS
+if $ipv6 and not $getaddr_info_ok
+ print <<EOS
Fatal: --enable-ipv6 is specified, and your OS seems to support IPv6 feature.
But your getaddrinfo() and getnameinfo() are appeared to be broken. Sorry,
you cannot compile IPv6 socket classes with broken these functions.
You can try --enable-wide-getaddrinfo.
EOS
+ exit
end
-
+
case with_config("lookup-order-hack", "UNSPEC")
when "INET"
- $defs << "-DLOOKUP_ORDER_HACK_INET"
+ $CFLAGS="-DLOOKUP_ORDER_HACK_INET "+$CFLAGS
when "INET6"
- $defs << "-DLOOKUP_ORDER_HACK_INET6"
+ $CFLAGS="-DLOOKUP_ORDER_HACK_INET6 "+$CFLAGS
when "UNSPEC"
# nothing special
else
- abort <<EOS
+ print <<EOS
Fatal: invalid value for --with-lookup-order-hack (expected INET, INET6 or UNSPEC)
EOS
+ exit
end
$objs = ["socket.#{$OBJEXT}"]
-
-unless getaddr_info_ok and have_func("getnameinfo", "netdb.h") and have_func("getaddrinfo", "netdb.h")
- if have_struct_member("struct in6_addr", "s6_addr8", headers)
- $defs[-1] = "-DHAVE_ADDR8"
+
+if $getaddr_info_ok and have_func("getaddrinfo", "netdb.h") and have_func("getnameinfo", "netdb.h")
+ have_getaddrinfo = true
+else
+ if try_link(<<EOF)
+#ifndef _WIN32
+# include <sys/types.h>
+# include <netdb.h>
+# include <string.h>
+# include <sys/socket.h>
+# include <netinet/in.h>
+#else
+# include <windows.h>
+# ifdef _WIN32_WCE
+# include <winsock.h>
+# else
+# include <winsock.h>
+# endif
+#endif
+int
+main()
+{
+ struct in6_addr addr;
+ unsigned char c;
+ c = addr.s6_addr8;
+ return 0;
+}
+EOF
+ $CFLAGS="-DHAVE_ADDR8 "+$CFLAGS
end
- $CPPFLAGS="-I. "+$CPPFLAGS
+end
+
+if have_getaddrinfo
+ $CFLAGS="-DHAVE_GETADDRINFO "+$CFLAGS
+else
+ $CFLAGS="-I. "+$CFLAGS
$objs += ["getaddrinfo.#{$OBJEXT}"]
$objs += ["getnameinfo.#{$OBJEXT}"]
have_func("inet_ntop") or have_func("inet_ntoa")
@@ -282,8 +364,20 @@ unless getaddr_info_ok and have_func("getnameinfo", "netdb.h") and have_func("ge
have_header("resolv.h")
end
-unless have_type("socklen_t", headers)
- $defs << "-Dsocklen_t=int"
+if !try_link(<<EOF)
+#include <sys/types.h>
+#include <netdb.h>
+#include <string.h>
+#include <sys/socket.h>
+#include <netinet/in.h>
+int
+main()
+{
+ socklen_t len;
+ return 0;
+}
+EOF
+ $CFLAGS="-Dsocklen_t=int "+$CFLAGS
end
have_header("sys/un.h")
@@ -292,15 +386,14 @@ have_header("sys/uio.h")
if have_func(test_func)
have_func("hsterror")
have_func("getipnodebyname") or have_func("gethostbyname2")
- have_func("socketpair")
unless have_func("gethostname")
have_func("uname")
end
if enable_config("socks", ENV["SOCKS_SERVER"])
if have_library("socks5", "SOCKSinit")
- $defs << "-DSOCKS5" << "-DSOCKS"
+ $CFLAGS+=" -DSOCKS5 -DSOCKS"
elsif have_library("socks", "Rconnect")
- $defs << "-DSOCKS"
+ $CFLAGS+=" -DSOCKS"
end
end
create_makefile("socket")
diff --git a/ext/socket/getaddrinfo.c b/ext/socket/getaddrinfo.c
index 9fb4ebcb06..14bedb2e9b 100644
--- a/ext/socket/getaddrinfo.c
+++ b/ext/socket/getaddrinfo.c
@@ -40,7 +40,7 @@
#include "config.h"
#include <sys/types.h>
-#if !defined(_WIN32) && !defined(__VMS)
+#ifndef _WIN32
#include <sys/param.h>
#if defined(__BEOS__)
# include <net/socket.h>
@@ -62,11 +62,6 @@
#include <resolv.h>
#endif
#include <unistd.h>
-#elif defined(__VMS )
-#include <socket.h>
-#include <inet.h>
-#include <in.h>
-#include <netdb.h>
#else
#include <winsock2.h>
#include <io.h>
diff --git a/ext/socket/socket.c b/ext/socket/socket.c
index 09326ce16f..1df7cb988c 100644
--- a/ext/socket/socket.c
+++ b/ext/socket/socket.c
@@ -30,7 +30,6 @@
# include <net/socket.h>
#else
# include <sys/socket.h>
-# define pseudo_AF_FTIP pseudo_AF_RTIP /* workaround for NetBSD and etc. */
#endif
#include <netinet/in.h>
#ifdef HAVE_NETINET_IN_SYSTM_H
@@ -53,16 +52,10 @@
#ifdef HAVE_SYS_SELECT_H
#include <sys/select.h>
#endif
-#ifdef HAVE_SYS_TYPES_H
#include <sys/types.h>
-#endif
-#ifdef HAVE_SYS_TIME_H
#include <sys/time.h>
-#endif
-#ifdef HAVE_FCNTL_H
#include <fcntl.h>
#endif
-#endif
#ifndef EWOULDBLOCK
#define EWOULDBLOCK EAGAIN
#endif
@@ -71,10 +64,6 @@
#endif
#include "sockport.h"
-#if defined(__vms)
-#include <tcp.h>
-#endif
-
static int do_not_reverse_lookup = 0;
VALUE rb_cBasicSocket;
@@ -173,30 +162,6 @@ ruby_getaddrinfo(nodename, servname, hints, res)
#define getaddrinfo(node,serv,hints,res) ruby_getaddrinfo((node),(serv),(hints),(res))
#endif
-#if defined(_AIX)
-static int
-ruby_getaddrinfo__aix(nodename, servname, hints, res)
- char *nodename;
- char *servname;
- struct addrinfo *hints;
- struct addrinfo **res;
-{
- int error = getaddrinfo(nodename, servname, hints, res);
- struct addrinfo *r;
- if (error)
- return error;
- for (r = *res; r != NULL; r = r->ai_next) {
- if (r->ai_addr->sa_family == 0)
- r->ai_addr->sa_family = r->ai_family;
- if (r->ai_addr->sa_len == 0)
- r->ai_addr->sa_len = r->ai_addrlen;
- }
- return 0;
-}
-#undef getaddrinfo
-#define getaddrinfo(node,serv,hints,res) ruby_getaddrinfo__aix((node),(serv),(hints),(res))
-#endif
-
#ifdef HAVE_CLOSESOCKET
#undef close
#define close closesocket
@@ -297,51 +262,6 @@ bsock_close_write(sock)
return Qnil;
}
-/*
- * Document-method: setsockopt
- * call-seq: setsockopt(level, optname, optval)
- *
- * Sets a socket option. These are protocol and system specific, see your
- * local sytem documentation for details.
- *
- * === Parameters
- * * +level+ is an integer, usually one of the SOL_ constants such as
- * Socket::SOL_SOCKET, or a protocol level.
- * * +optname+ is an integer, usually one of the SO_ constants, such
- * as Socket::SO_REUSEADDR.
- * * +optval+ is the value of the option, it is passed to the underlying
- * setsockopt() as a pointer to a certain number of bytes. How this is
- * done depends on the type:
- * - Fixnum: value is assigned to an int, and a pointer to the int is
- * passed, with length of sizeof(int).
- * - true or false: 1 or 0 (respectively) is assigned to an int, and the
- * int is passed as for a Fixnum. Note that +false+ must be passed,
- * not +nil+.
- * - String: the string's data and length is passed to the socket.
- *
- * === Examples
- *
- * Some socket options are integers with boolean values, in this case
- * #setsockopt could be called like this:
- * sock.setsockopt(Socket::SOL_SOCKET,Socket::SO_REUSEADDR, true)
- *
- * Some socket options are integers with numeric values, in this case
- * #setsockopt could be called like this:
- * sock.setsockopt(Socket::IPPROTO_IP, Socket::IP_TTL, 255)
- *
- * Option values may be structs. Passing them can be complex as it involves
- * examining your system headers to determine the correct definition. An
- * example is an +ip_mreq+, which may be defined in your system headers as:
- * struct ip_mreq {
- * struct in_addr imr_multiaddr;
- * struct in_addr imr_interface;
- * };
- *
- * In this case #setsockopt could be called like this:
- * optval = IPAddr.new("224.0.0.251") + Socket::INADDR_ANY
- * sock.setsockopt(Socket::IPPROTO_IP, Socket::IP_ADD_MEMBERSHIP, optval)
- *
-*/
static VALUE
bsock_setsockopt(sock, lev, optname, val)
VALUE sock, lev, optname, val;
@@ -355,6 +275,7 @@ bsock_setsockopt(sock, lev, optname, val)
rb_secure(2);
level = NUM2INT(lev);
option = NUM2INT(optname);
+ GetOpenFile(sock, fptr);
switch (TYPE(val)) {
case T_FIXNUM:
@@ -375,53 +296,12 @@ bsock_setsockopt(sock, lev, optname, val)
break;
}
- GetOpenFile(sock, fptr);
if (setsockopt(fileno(fptr->f), level, option, v, vlen) < 0)
rb_sys_fail(fptr->path);
return INT2FIX(0);
}
-/*
- * Document-method: getsockopt
- * call-seq: getsockopt(level, optname)
- *
- * Gets a socket option. These are protocol and system specific, see your
- * local sytem documentation for details. The option is returned as
- * a String with the data being the binary value of the socket option.
- *
- * === Parameters
- * * +level+ is an integer, usually one of the SOL_ constants such as
- * Socket::SOL_SOCKET, or a protocol level.
- * * +optname+ is an integer, usually one of the SO_ constants, such
- * as Socket::SO_REUSEADDR.
- *
- * === Examples
- *
- * Some socket options are integers with boolean values, in this case
- * #getsockopt could be called like this:
- * optval = sock.getsockopt(Socket::SOL_SOCKET,Socket::SO_REUSEADDR)
- * optval = optval.unpack "i"
- * reuseaddr = optval[0] == 0 ? false : true
- *
- * Some socket options are integers with numeric values, in this case
- * #getsockopt could be called like this:
- * optval = sock.getsockopt(Socket::IPPROTO_IP, Socket::IP_TTL)
- * ipttl = optval.unpack("i")[0]
- *
- * Option values may be structs. Decoding them can be complex as it involves
- * examining your system headers to determine the correct definition. An
- * example is a +struct linger+, which may be defined in your system headers
- * as:
- * struct linger {
- * int l_onoff;
- * int l_linger;
- * };
- *
- * In this case #getsockopt could be called like this:
- * optval = sock.getsockopt(Socket::SOL_SOCKET, Socket::SO_LINGER)
- * onoff, linger = optval.unpack "ii"
-*/
static VALUE
bsock_getsockopt(sock, lev, optname)
VALUE sock, lev, optname;
@@ -436,7 +316,6 @@ bsock_getsockopt(sock, lev, optname)
option = NUM2INT(optname);
len = 256;
buf = ALLOCA_N(char,len);
- GetOpenFile(sock, fptr);
GetOpenFile(sock, fptr);
if (getsockopt(fileno(fptr->f), level, option, buf, &len) < 0)
@@ -491,23 +370,19 @@ bsock_send(argc, argv, sock)
rb_secure(4);
rb_scan_args(argc, argv, "21", &mesg, &flags, &to);
- StringValue(mesg);
- if (!NIL_P(to)) StringValue(to);
GetOpenFile(sock, fptr);
f = GetWriteFile(fptr);
fd = fileno(f);
rb_thread_fd_writable(fd);
+ StringValue(mesg);
retry:
if (!NIL_P(to)) {
- TRAP_BEG;
+ StringValue(to);
n = sendto(fd, RSTRING(mesg)->ptr, RSTRING(mesg)->len, NUM2INT(flags),
(struct sockaddr*)RSTRING(to)->ptr, RSTRING(to)->len);
- TRAP_END;
}
else {
- TRAP_BEG;
n = send(fd, RSTRING(mesg)->ptr, RSTRING(mesg)->len, NUM2INT(flags));
- TRAP_END;
}
if (n < 0) {
if (rb_io_wait_writable(fd)) {
@@ -550,7 +425,6 @@ s_recvfrom(sock, argc, argv, from)
if (flg == Qnil) flags = 0;
else flags = NUM2INT(flg);
- buflen = NUM2INT(len);
GetOpenFile(sock, fptr);
if (rb_read_pending(fptr->f)) {
@@ -558,6 +432,7 @@ s_recvfrom(sock, argc, argv, from)
}
fd = fileno(fptr->f);
+ buflen = NUM2INT(len);
str = rb_tainted_str_new(0, buflen);
retry:
@@ -875,40 +750,15 @@ ruby_socket(domain, type, proto)
return fd;
}
-static int
-wait_connectable(fd)
+static void
+thread_write_select(fd)
int fd;
{
- int sockerr;
- socklen_t sockerrlen;
- fd_set fds_w;
- fd_set fds_e;
-
- for (;;) {
- FD_ZERO(&fds_w);
- FD_ZERO(&fds_e);
-
- FD_SET(fd, &fds_w);
- FD_SET(fd, &fds_e);
-
- rb_thread_select(fd+1, 0, &fds_w, &fds_e, 0);
-
- if (FD_ISSET(fd, &fds_w)) {
- return 0;
- }
- else if (FD_ISSET(fd, &fds_e)) {
- sockerrlen = sizeof(sockerr);
- if (getsockopt(fd, SOL_SOCKET, SO_ERROR, (void *)&sockerr,
- &sockerrlen) == 0) {
- if (sockerr == 0)
- continue; /* workaround for winsock */
- errno = sockerr;
- }
- return -1;
- }
- }
+ fd_set fds;
- return 0;
+ FD_ZERO(&fds);
+ FD_SET(fd, &fds);
+ rb_thread_select(fd+1, 0, &fds, 0, 0);
}
#ifdef __CYGWIN__
@@ -941,11 +791,7 @@ ruby_connect(fd, sockaddr, len, socks)
#endif
#if defined(HAVE_FCNTL)
-# if defined(F_GETFL)
mode = fcntl(fd, F_GETFL, 0);
-# else
- mode = 0;
-# endif
#ifdef O_NDELAY
# define NONBLOCKING O_NDELAY
@@ -994,11 +840,7 @@ ruby_connect(fd, sockaddr, len, socks)
#if WAIT_IN_PROGRESS > 0
wait_in_progress = WAIT_IN_PROGRESS;
#endif
- status = wait_connectable(fd);
- if (status) {
- break;
- }
- errno = 0;
+ thread_write_select(fd);
continue;
#if WAIT_IN_PROGRESS > 0
@@ -1539,8 +1381,8 @@ udp_connect(sock, host, port)
VALUE ret;
rb_secure(3);
- arg.res = sock_addrinfo(host, port, SOCK_DGRAM, 0);
GetOpenFile(sock, fptr);
+ arg.res = sock_addrinfo(host, port, SOCK_DGRAM, 0);
arg.fd = fileno(fptr->f);
ret = rb_ensure(udp_connect_internal, (VALUE)&arg,
RUBY_METHOD_FUNC(freeaddrinfo), (VALUE)arg.res);
@@ -1556,8 +1398,8 @@ udp_bind(sock, host, port)
struct addrinfo *res0, *res;
rb_secure(3);
- res0 = sock_addrinfo(host, port, SOCK_DGRAM, 0);
GetOpenFile(sock, fptr);
+ res0 = sock_addrinfo(host, port, SOCK_DGRAM, 0);
for (res = res0; res; res = res->ai_next) {
if (bind(fileno(fptr->f), res->ai_addr, res->ai_addrlen) < 0) {
continue;
@@ -1588,10 +1430,10 @@ udp_send(argc, argv, sock)
rb_secure(4);
rb_scan_args(argc, argv, "4", &mesg, &flags, &host, &port);
- StringValue(mesg);
- res0 = sock_addrinfo(host, port, SOCK_DGRAM, 0);
GetOpenFile(sock, fptr);
+ res0 = sock_addrinfo(host, port, SOCK_DGRAM, 0);
f = GetWriteFile(fptr);
+ StringValue(mesg);
for (res = res0; res; res = res->ai_next) {
retry:
n = sendto(fileno(f), RSTRING(mesg)->ptr, RSTRING(mesg)->len, NUM2INT(flags),
@@ -1689,7 +1531,7 @@ unix_send_io(sock, val)
fd = FIX2INT(val);
}
else {
- rb_raise(rb_eTypeError, "neither IO nor file descriptor");
+ rb_raise(rb_eTypeError, "IO nor file descriptor");
}
GetOpenFile(sock, fptr);
@@ -1706,9 +1548,9 @@ unix_send_io(sock, val)
#if FD_PASSING_BY_MSG_CONTROL
msg.msg_control = (caddr_t)&cmsg;
- msg.msg_controllen = CMSG_SPACE(sizeof(int));
+ msg.msg_controllen = sizeof(struct cmsghdr) + sizeof(int);
msg.msg_flags = 0;
- cmsg.hdr.cmsg_len = CMSG_LEN(sizeof(int));
+ cmsg.hdr.cmsg_len = sizeof(struct cmsghdr) + sizeof(int);
cmsg.hdr.cmsg_level = SOL_SOCKET;
cmsg.hdr.cmsg_type = SCM_RIGHTS;
cmsg.fd = fd;
@@ -1781,9 +1623,9 @@ unix_recv_io(argc, argv, sock)
#if FD_PASSING_BY_MSG_CONTROL
msg.msg_control = (caddr_t)&cmsg;
- msg.msg_controllen = CMSG_SPACE(sizeof(int));
+ msg.msg_controllen = sizeof(struct cmsghdr) + sizeof(int);
msg.msg_flags = 0;
- cmsg.hdr.cmsg_len = CMSG_LEN(sizeof(int));
+ cmsg.hdr.cmsg_len = sizeof(struct cmsghdr) + sizeof(int);
cmsg.hdr.cmsg_level = SOL_SOCKET;
cmsg.hdr.cmsg_type = SCM_RIGHTS;
cmsg.fd = -1;
@@ -1796,34 +1638,18 @@ unix_recv_io(argc, argv, sock)
if (recvmsg(fileno(fptr->f), &msg, 0) == -1)
rb_sys_fail("recvmsg(2)");
+ if (
#if FD_PASSING_BY_MSG_CONTROL
- if (msg.msg_controllen != CMSG_SPACE(sizeof(int))) {
- rb_raise(rb_eSocket,
- "file descriptor was not passed (msg_controllen : %d != %d)",
- msg.msg_controllen, CMSG_SPACE(sizeof(int)));
- }
- if (cmsg.hdr.cmsg_len != CMSG_SPACE(0) + sizeof(int)) {
- rb_raise(rb_eSocket,
- "file descriptor was not passed (cmsg_len : %d != %d)",
- cmsg.hdr.cmsg_len, CMSG_SPACE(0) + sizeof(int));
- }
- if (cmsg.hdr.cmsg_level != SOL_SOCKET) {
- rb_raise(rb_eSocket,
- "file descriptor was not passed (cmsg_level : %d != %d)",
- cmsg.hdr.cmsg_level, SOL_SOCKET);
- }
- if (cmsg.hdr.cmsg_type != SCM_RIGHTS) {
- rb_raise(rb_eSocket,
- "file descriptor was not passed (cmsg_type : %d != %d)",
- cmsg.hdr.cmsg_type, SCM_RIGHTS);
- }
+ msg.msg_controllen != sizeof(struct cmsghdr) + sizeof(int) ||
+ cmsg.hdr.cmsg_len != sizeof(struct cmsghdr) + sizeof(int) ||
+ cmsg.hdr.cmsg_level != SOL_SOCKET ||
+ cmsg.hdr.cmsg_type != SCM_RIGHTS
#else
- if (msg.msg_accrightslen != sizeof(fd)) {
- rb_raise(rb_eSocket,
- "file descriptor was not passed (accrightslen) : %d != %d",
- msg.msg_accrightslen, sizeof(fd));
- }
+ msg.msg_accrightslen != sizeof(fd)
#endif
+ ) {
+ rb_raise(rb_eSocket, "File descriptor was not passed");
+ }
#if FD_PASSING_BY_MSG_CONTROL
fd = cmsg.fd;
@@ -1972,7 +1798,7 @@ setup_domain_and_type(domain, dv, type, tv)
*dv = PF_IPX;
#endif
else
- rb_raise(rb_eSocket, "unknown socket domain %s", ptr);
+ rb_raise(rb_eSocket, "Unknown socket domain %s", ptr);
}
else {
*dv = NUM2INT(domain);
@@ -2003,7 +1829,7 @@ setup_domain_and_type(domain, dv, type, tv)
*tv = SOCK_PACKET;
#endif
else
- rb_raise(rb_eSocket, "unknown socket type %s", ptr);
+ rb_raise(rb_eSocket, "Unknown socket type %s", ptr);
}
else {
*tv = NUM2INT(type);
@@ -2029,7 +1855,7 @@ static VALUE
sock_s_socketpair(klass, domain, type, protocol)
VALUE klass, domain, type, protocol;
{
-#if !defined(_WIN32) && !defined(__BEOS__) && !defined(__EMX__) && !defined(__QNXNTO__) && !defined(__VMS)
+#if !defined(_WIN32) && !defined(__BEOS__) && !defined(__EMX__) && !defined(__QNXNTO__)
int d, t, sp[2];
setup_domain_and_type(domain, &d, type, &t);
@@ -2077,7 +1903,8 @@ sock_connect(sock, addr)
int fd;
StringValue(addr);
- addr = rb_str_new4(addr);
+ rb_str_modify(addr);
+
GetOpenFile(sock, fptr);
fd = fileno(fptr->f);
if (ruby_connect(fd, (struct sockaddr*)RSTRING(addr)->ptr, RSTRING(addr)->len, 0) < 0) {
@@ -2094,6 +1921,8 @@ sock_bind(sock, addr)
OpenFile *fptr;
StringValue(addr);
+ rb_str_modify(addr);
+
GetOpenFile(sock, fptr);
if (bind(fileno(fptr->f), (struct sockaddr*)RSTRING(addr)->ptr, RSTRING(addr)->len) < 0)
rb_sys_fail("bind(2)");
@@ -2106,12 +1935,10 @@ sock_listen(sock, log)
VALUE sock, log;
{
OpenFile *fptr;
- int backlog;
rb_secure(4);
- backlog = NUM2INT(log);
GetOpenFile(sock, fptr);
- if (listen(fileno(fptr->f), backlog) < 0)
+ if (listen(fileno(fptr->f), NUM2INT(log)) < 0)
rb_sys_fail("listen(2)");
return INT2FIX(0);
@@ -2458,9 +2285,7 @@ sock_s_getnameinfo(argc, argv)
* 4th element holds numeric form, don't resolve.
* see ipaddr().
*/
-#ifdef AI_NUMERICHOST /* AIX 4.3.3 doesn't have AI_NUMERICHOST. */
hints.ai_flags |= AI_NUMERICHOST;
-#endif
}
}
else {
@@ -2775,195 +2600,6 @@ Init_socket()
#ifdef INET6
sock_define_const("PF_INET6", PF_INET6);
#endif
-#ifdef AF_LOCAL
- sock_define_const("AF_LOCAL", AF_LOCAL);
-#endif
-#ifdef PF_LOCAL
- sock_define_const("PF_LOCAL", PF_LOCAL);
-#endif
-#ifdef AF_IMPLINK
- sock_define_const("AF_IMPLINK", AF_IMPLINK);
-#endif
-#ifdef PF_IMPLINK
- sock_define_const("PF_IMPLINK", PF_IMPLINK);
-#endif
-#ifdef AF_PUP
- sock_define_const("AF_PUP", AF_PUP);
-#endif
-#ifdef PF_PUP
- sock_define_const("PF_PUP", PF_PUP);
-#endif
-#ifdef AF_CHAOS
- sock_define_const("AF_CHAOS", AF_CHAOS);
-#endif
-#ifdef PF_CHAOS
- sock_define_const("PF_CHAOS", PF_CHAOS);
-#endif
-#ifdef AF_NS
- sock_define_const("AF_NS", AF_NS);
-#endif
-#ifdef PF_NS
- sock_define_const("PF_NS", PF_NS);
-#endif
-#ifdef AF_ISO
- sock_define_const("AF_ISO", AF_ISO);
-#endif
-#ifdef PF_ISO
- sock_define_const("PF_ISO", PF_ISO);
-#endif
-#ifdef AF_OSI
- sock_define_const("AF_OSI", AF_OSI);
-#endif
-#ifdef PF_OSI
- sock_define_const("PF_OSI", PF_OSI);
-#endif
-#ifdef AF_ECMA
- sock_define_const("AF_ECMA", AF_ECMA);
-#endif
-#ifdef PF_ECMA
- sock_define_const("PF_ECMA", PF_ECMA);
-#endif
-#ifdef AF_DATAKIT
- sock_define_const("AF_DATAKIT", AF_DATAKIT);
-#endif
-#ifdef PF_DATAKIT
- sock_define_const("PF_DATAKIT", PF_DATAKIT);
-#endif
-#ifdef AF_CCITT
- sock_define_const("AF_CCITT", AF_CCITT);
-#endif
-#ifdef PF_CCITT
- sock_define_const("PF_CCITT", PF_CCITT);
-#endif
-#ifdef AF_SNA
- sock_define_const("AF_SNA", AF_SNA);
-#endif
-#ifdef PF_SNA
- sock_define_const("PF_SNA", PF_SNA);
-#endif
-#ifdef AF_DEC
- sock_define_const("AF_DEC", AF_DEC);
-#endif
-#ifdef PF_DEC
- sock_define_const("PF_DEC", PF_DEC);
-#endif
-#ifdef AF_DLI
- sock_define_const("AF_DLI", AF_DLI);
-#endif
-#ifdef PF_DLI
- sock_define_const("PF_DLI", PF_DLI);
-#endif
-#ifdef AF_LAT
- sock_define_const("AF_LAT", AF_LAT);
-#endif
-#ifdef PF_LAT
- sock_define_const("PF_LAT", PF_LAT);
-#endif
-#ifdef AF_HYLINK
- sock_define_const("AF_HYLINK", AF_HYLINK);
-#endif
-#ifdef PF_HYLINK
- sock_define_const("PF_HYLINK", PF_HYLINK);
-#endif
-#ifdef AF_ROUTE
- sock_define_const("AF_ROUTE", AF_ROUTE);
-#endif
-#ifdef PF_ROUTE
- sock_define_const("PF_ROUTE", PF_ROUTE);
-#endif
-#ifdef AF_LINK
- sock_define_const("AF_LINK", AF_LINK);
-#endif
-#ifdef PF_LINK
- sock_define_const("PF_LINK", PF_LINK);
-#endif
-#ifdef AF_COIP
- sock_define_const("AF_COIP", AF_COIP);
-#endif
-#ifdef PF_COIP
- sock_define_const("PF_COIP", PF_COIP);
-#endif
-#ifdef AF_CNT
- sock_define_const("AF_CNT", AF_CNT);
-#endif
-#ifdef PF_CNT
- sock_define_const("PF_CNT", PF_CNT);
-#endif
-#ifdef AF_SIP
- sock_define_const("AF_SIP", AF_SIP);
-#endif
-#ifdef PF_SIP
- sock_define_const("PF_SIP", PF_SIP);
-#endif
-#ifdef AF_NDRV
- sock_define_const("AF_NDRV", AF_NDRV);
-#endif
-#ifdef PF_NDRV
- sock_define_const("PF_NDRV", PF_NDRV);
-#endif
-#ifdef AF_ISDN
- sock_define_const("AF_ISDN", AF_ISDN);
-#endif
-#ifdef PF_ISDN
- sock_define_const("PF_ISDN", PF_ISDN);
-#endif
-#ifdef AF_NATM
- sock_define_const("AF_NATM", AF_NATM);
-#endif
-#ifdef PF_NATM
- sock_define_const("PF_NATM", PF_NATM);
-#endif
-#ifdef AF_SYSTEM
- sock_define_const("AF_SYSTEM", AF_SYSTEM);
-#endif
-#ifdef PF_SYSTEM
- sock_define_const("PF_SYSTEM", PF_SYSTEM);
-#endif
-#ifdef AF_NETBIOS
- sock_define_const("AF_NETBIOS", AF_NETBIOS);
-#endif
-#ifdef PF_NETBIOS
- sock_define_const("PF_NETBIOS", PF_NETBIOS);
-#endif
-#ifdef AF_PPP
- sock_define_const("AF_PPP", AF_PPP);
-#endif
-#ifdef PF_PPP
- sock_define_const("PF_PPP", PF_PPP);
-#endif
-#ifdef AF_ATM
- sock_define_const("AF_ATM", AF_ATM);
-#endif
-#ifdef PF_ATM
- sock_define_const("PF_ATM", PF_ATM);
-#endif
-#ifdef AF_NETGRAPH
- sock_define_const("AF_NETGRAPH", AF_NETGRAPH);
-#endif
-#ifdef PF_NETGRAPH
- sock_define_const("PF_NETGRAPH", PF_NETGRAPH);
-#endif
-#ifdef AF_MAX
- sock_define_const("AF_MAX", AF_MAX);
-#endif
-#ifdef PF_MAX
- sock_define_const("PF_MAX", PF_MAX);
-#endif
-#ifdef AF_E164
- sock_define_const("AF_E164", AF_E164);
-#endif
-#ifdef PF_XTP
- sock_define_const("PF_XTP", PF_XTP);
-#endif
-#ifdef PF_RTIP
- sock_define_const("PF_RTIP", PF_RTIP);
-#endif
-#ifdef PF_PIP
- sock_define_const("PF_PIP", PF_PIP);
-#endif
-#ifdef PF_KEY
- sock_define_const("PF_KEY", PF_KEY);
-#endif
sock_define_const("MSG_OOB", MSG_OOB);
#ifdef MSG_PEEK
@@ -2972,42 +2608,6 @@ Init_socket()
#ifdef MSG_DONTROUTE
sock_define_const("MSG_DONTROUTE", MSG_DONTROUTE);
#endif
-#ifdef MSG_EOR
- sock_define_const("MSG_EOR", MSG_EOR);
-#endif
-#ifdef MSG_TRUNC
- sock_define_const("MSG_TRUNC", MSG_TRUNC);
-#endif
-#ifdef MSG_CTRUNC
- sock_define_const("MSG_CTRUNC", MSG_CTRUNC);
-#endif
-#ifdef MSG_WAITALL
- sock_define_const("MSG_WAITALL", MSG_WAITALL);
-#endif
-#ifdef MSG_DONTWAIT
- sock_define_const("MSG_DONTWAIT", MSG_DONTWAIT);
-#endif
-#ifdef MSG_EOF
- sock_define_const("MSG_EOF", MSG_EOF);
-#endif
-#ifdef MSG_FLUSH
- sock_define_const("MSG_FLUSH", MSG_FLUSH);
-#endif
-#ifdef MSG_HOLD
- sock_define_const("MSG_HOLD", MSG_HOLD);
-#endif
-#ifdef MSG_SEND
- sock_define_const("MSG_SEND", MSG_SEND);
-#endif
-#ifdef MSG_HAVEMORE
- sock_define_const("MSG_HAVEMORE", MSG_HAVEMORE);
-#endif
-#ifdef MSG_RCVMORE
- sock_define_const("MSG_RCVMORE", MSG_RCVMORE);
-#endif
-#ifdef MSG_COMPAT
- sock_define_const("MSG_COMPAT", MSG_COMPAT);
-#endif
sock_define_const("SOL_SOCKET", SOL_SOCKET);
#ifdef SOL_IP
@@ -3192,9 +2792,6 @@ Init_socket()
sock_define_const("SO_DEBUG", SO_DEBUG);
#endif
sock_define_const("SO_REUSEADDR", SO_REUSEADDR);
-#ifdef SO_REUSEPORT
- sock_define_const("SO_REUSEPORT", SO_REUSEPORT);
-#endif
#ifdef SO_TYPE
sock_define_const("SO_TYPE", SO_TYPE);
#endif
@@ -3246,33 +2843,6 @@ Init_socket()
#ifdef SO_SNDTIMEO
sock_define_const("SO_SNDTIMEO", SO_SNDTIMEO);
#endif
-#ifdef SO_ACCEPTCONN
- sock_define_const("SO_ACCEPTCONN", SO_ACCEPTCONN);
-#endif
-#ifdef SO_USELOOPBACK
- sock_define_const("SO_USELOOPBACK", SO_USELOOPBACK);
-#endif
-#ifdef SO_ACCEPTFILTER
- sock_define_const("SO_ACCEPTFILTER", SO_ACCEPTFILTER);
-#endif
-#ifdef SO_DONTTRUNC
- sock_define_const("SO_DONTTRUNC", SO_DONTTRUNC);
-#endif
-#ifdef SO_WANTMORE
- sock_define_const("SO_WANTMORE", SO_WANTMORE);
-#endif
-#ifdef SO_WANTOOBFLAG
- sock_define_const("SO_WANTOOBFLAG", SO_WANTOOBFLAG);
-#endif
-#ifdef SO_NREAD
- sock_define_const("SO_NREAD", SO_NREAD);
-#endif
-#ifdef SO_NKE
- sock_define_const("SO_NKE", SO_NKE);
-#endif
-#ifdef SO_NOSIGPIPE
- sock_define_const("SO_NOSIGPIPE", SO_NOSIGPIPE);
-#endif
#ifdef SO_SECURITY_AUTHENTICATION
sock_define_const("SO_SECURITY_AUTHENTICATION", SO_SECURITY_AUTHENTICATION);
diff --git a/ext/stringio/stringio.c b/ext/stringio/stringio.c
index a64aaf837c..790e567608 100644
--- a/ext/stringio/stringio.c
+++ b/ext/stringio/stringio.c
@@ -14,11 +14,6 @@
#include "ruby.h"
#include "rubyio.h"
-#if defined(HAVE_FCNTL_H) || defined(_WIN32)
-#include <fcntl.h>
-#elif defined(HAVE_SYS_FCNTL_H)
-#include <sys/fcntl.h>
-#endif
#define STRIO_EOF FMODE_SYNC
@@ -78,7 +73,7 @@ check_strio(self)
{
Check_Type(self, T_DATA);
if (!IS_STRIO(self)) {
- rb_raise(rb_eTypeError, "wrong argument type %s (expected StringIO)",
+ rb_raise(rb_eTypeError, "wrong argument type %s (expected String::IO)",
rb_class2name(CLASS_OF(self)));
}
return DATA_PTR(self);
@@ -98,9 +93,9 @@ get_strio(self)
#define StringIO(obj) get_strio(obj)
-#define CLOSED(ptr) (!((ptr)->flags & FMODE_READWRITE))
-#define READABLE(ptr) ((ptr)->flags & FMODE_READABLE)
-#define WRITABLE(ptr) ((ptr)->flags & FMODE_WRITABLE)
+#define CLOSED(ptr) NIL_P((ptr)->string)
+#define READABLE(ptr) (!CLOSED(ptr) && ((ptr)->flags & FMODE_READABLE))
+#define WRITABLE(ptr) (!CLOSED(ptr) && ((ptr)->flags & FMODE_WRITABLE))
static struct StringIO*
readable(ptr)
@@ -187,13 +182,6 @@ strio_s_allocate(klass)
return Data_Wrap_Struct(klass, strio_mark, strio_free, 0);
}
-/*
- * call-seq: StringIO.open(string=""[, mode]) {|strio| ...}
- *
- * Equivalent to StringIO.new except that when it is called with a block, it
- * yields with the new instance and closes it, and returns the result which
- * returned from the block.
- */
static VALUE
strio_s_open(argc, argv, klass)
int argc;
@@ -205,11 +193,6 @@ strio_s_open(argc, argv, klass)
return rb_ensure(rb_yield, obj, strio_finalize, obj);
}
-/*
- * call-seq: StringIO.new(string=""[, mode])
- *
- * Creates new StringIO instance from with _string_ and _mode_.
- */
static VALUE
strio_initialize(argc, argv, self)
int argc;
@@ -218,7 +201,7 @@ strio_initialize(argc, argv, self)
{
struct StringIO *ptr = check_strio(self);
VALUE string, mode;
- int trunc = Qfalse;
+ const char* m;
if (!ptr) {
DATA_PTR(self) = ptr = strio_alloc();
@@ -226,23 +209,21 @@ strio_initialize(argc, argv, self)
rb_call_super(0, 0);
switch (rb_scan_args(argc, argv, "02", &string, &mode)) {
case 2:
- if (FIXNUM_P(mode)) {
- int flags = FIX2INT(mode);
- ptr->flags = rb_io_modenum_flags(flags);
- trunc = flags & O_TRUNC;
- }
- else {
- const char *m = StringValueCStr(mode);
- ptr->flags = rb_io_mode_flags(m);
- trunc = *m == 'w';
- }
+ StringValue(mode);
StringValue(string);
+ if (!(m = RSTRING(mode)->ptr)) m = "";
+ ptr->flags = rb_io_mode_flags(m);
if ((ptr->flags & FMODE_WRITABLE) && OBJ_FROZEN(string)) {
errno = EACCES;
rb_sys_fail(0);
}
- if (trunc) {
+ switch (*m) {
+ case 'a':
+ ptr->flags |= FMODE_APPEND;
+ break;
+ case 'w':
rb_str_resize(string, 0);
+ break;
}
break;
case 1:
@@ -268,9 +249,6 @@ strio_finalize(self)
return self;
}
-/*
- * Returns +false+. Just for compatibility to IO.
- */
static VALUE
strio_false(self)
VALUE self;
@@ -279,9 +257,6 @@ strio_false(self)
return Qfalse;
}
-/*
- * Returns +nil+. Just for compatibility to IO.
- */
static VALUE
strio_nil(self)
VALUE self;
@@ -290,9 +265,6 @@ strio_nil(self)
return Qnil;
}
-/*
- * Returns *strio* itself. Just for compatibility to IO.
- */
static VALUE
strio_self(self)
VALUE self;
@@ -301,9 +273,6 @@ strio_self(self)
return self;
}
-/*
- * Returns 0. Just for compatibility to IO.
- */
static VALUE
strio_0(self)
VALUE self;
@@ -312,9 +281,6 @@ strio_0(self)
return INT2FIX(0);
}
-/*
- * Returns the argument unchanged. Just for compatibility to IO.
- */
static VALUE
strio_first(self, arg)
VALUE self, arg;
@@ -323,9 +289,6 @@ strio_first(self, arg)
return arg;
}
-/*
- * Raises NotImplementedError.
- */
static VALUE
strio_unimpl(argc, argv, self)
int argc;
@@ -337,11 +300,6 @@ strio_unimpl(argc, argv, self)
return Qnil; /* not reached */
}
-/*
- * call-seq: strio.string -> string
- *
- * Returns underlying String object, the subject of IO.
- */
static VALUE
strio_get_string(self)
VALUE self;
@@ -349,12 +307,6 @@ strio_get_string(self)
return StringIO(self)->string;
}
-/*
- * call-seq:
- * strio.string = string -> string
- *
- * Changes underlying String object, the subject of IO.
- */
static VALUE
strio_set_string(self, string)
VALUE self, string;
@@ -363,20 +315,15 @@ strio_set_string(self, string)
if (!OBJ_TAINTED(self)) rb_secure(4);
ptr->flags &= ~FMODE_READWRITE;
- StringValue(string);
- ptr->flags = OBJ_FROZEN(string) ? FMODE_READABLE : FMODE_READWRITE;
+ if (!NIL_P(string)) {
+ StringValue(string);
+ ptr->flags = OBJ_FROZEN(string) ? FMODE_READABLE : FMODE_READWRITE;
+ }
ptr->pos = 0;
ptr->lineno = 0;
return ptr->string = string;
}
-/*
- * call-seq:
- * strio.close -> nil
- *
- * Closes strio. The *strio* is unavailable for any further data
- * operations; an +IOError+ is raised if such an attempt is made.
- */
static VALUE
strio_close(self)
VALUE self;
@@ -385,17 +332,11 @@ strio_close(self)
if (CLOSED(ptr)) {
rb_raise(rb_eIOError, "closed stream");
}
+ ptr->string = Qnil;
ptr->flags &= ~FMODE_READWRITE;
- return Qnil;
+ return self;
}
-/*
- * call-seq:
- * strio.close_read -> nil
- *
- * Closes the read end of a StringIO. Will raise an +IOError+ if the
- * *strio* is not readable.
- */
static VALUE
strio_close_read(self)
VALUE self;
@@ -404,17 +345,12 @@ strio_close_read(self)
if (!READABLE(ptr)) {
rb_raise(rb_eIOError, "closing non-duplex IO for reading");
}
- ptr->flags &= ~FMODE_READABLE;
- return Qnil;
+ if (!((ptr->flags &= ~FMODE_READABLE) & FMODE_READWRITE)) {
+ ptr->string = Qnil;
+ }
+ return self;
}
-/*
- * call-seq:
- * strio.close_write -> nil
- *
- * Closes the write end of a StringIO. Will raise an +IOError+ if the
- * *strio* is not writeable.
- */
static VALUE
strio_close_write(self)
VALUE self;
@@ -423,16 +359,12 @@ strio_close_write(self)
if (!WRITABLE(ptr)) {
rb_raise(rb_eIOError, "closing non-duplex IO for writing");
}
- ptr->flags &= ~FMODE_WRITABLE;
- return Qnil;
+ if (!((ptr->flags &= ~FMODE_WRITABLE) & FMODE_READWRITE)) {
+ ptr->string = Qnil;
+ }
+ return self;
}
-/*
- * call-seq:
- * strio.closed? -> true or false
- *
- * Returns +true+ if *strio* is completely closed, +false+ otherwise.
- */
static VALUE
strio_closed(self)
VALUE self;
@@ -442,12 +374,6 @@ strio_closed(self)
return Qtrue;
}
-/*
- * call-seq:
- * strio.closed_read? -> true or false
- *
- * Returns +true+ if *strio* is not readable, +false+ otherwise.
- */
static VALUE
strio_closed_read(self)
VALUE self;
@@ -457,12 +383,6 @@ strio_closed_read(self)
return Qtrue;
}
-/*
- * call-seq:
- * strio.closed_write? -> true or false
- *
- * Returns +true+ if *strio* is not writable, +false+ otherwise.
- */
static VALUE
strio_closed_write(self)
VALUE self;
@@ -472,14 +392,6 @@ strio_closed_write(self)
return Qtrue;
}
-/*
- * call-seq:
- * strio.eof -> true or false
- * strio.eof? -> true or false
- *
- * Returns true if *strio* is at end of file. The stringio must be
- * opened for reading or an +IOError+ will be raised.
- */
static VALUE
strio_eof(self)
VALUE self;
@@ -489,7 +401,6 @@ strio_eof(self)
return Qtrue;
}
-/* :nodoc: */
static VALUE
strio_copy(copy, orig)
VALUE copy, orig;
@@ -508,16 +419,6 @@ strio_copy(copy, orig)
return copy;
}
-/*
- * call-seq:
- * strio.lineno -> integer
- *
- * Returns the current line number in *strio*. The stringio must be
- * opened for reading. +lineno+ counts the number of times +gets+ is
- * called, rather than the number of newlines encountered. The two
- * values will differ if +gets+ is called with a separator other than
- * newline. See also the <code>$.</code> variable.
- */
static VALUE
strio_get_lineno(self)
VALUE self;
@@ -525,13 +426,6 @@ strio_get_lineno(self)
return LONG2NUM(StringIO(self)->lineno);
}
-/*
- * call-seq:
- * strio.lineno = integer -> integer
- *
- * Manually sets the current line number to the given value.
- * <code>$.</code> is updated only on the next read.
- */
static VALUE
strio_set_lineno(self, lineno)
VALUE self, lineno;
@@ -540,26 +434,14 @@ strio_set_lineno(self, lineno)
return lineno;
}
-/* call-seq: strio.binmode -> true */
#define strio_binmode strio_self
-/* call-seq: strio.fcntl */
#define strio_fcntl strio_unimpl
-/* call-seq: strio.flush -> strio */
#define strio_flush strio_self
-/* call-seq: strio.fsync -> 0 */
#define strio_fsync strio_0
-/*
- * call-seq:
- * strio.reopen(other_StrIO) -> strio
- * strio.reopen(string, mode) -> strio
- *
- * Reinitializes *strio* with the given <i>other_StrIO</i> or _string_
- * and _mode_ (see StringIO#new).
- */
static VALUE
strio_reopen(argc, argv, self)
int argc;
@@ -573,13 +455,6 @@ strio_reopen(argc, argv, self)
return strio_initialize(argc, argv, self);
}
-/*
- * call-seq:
- * strio.pos -> integer
- * strio.tell -> integer
- *
- * Returns the current offset (in bytes) of *strio*.
- */
static VALUE
strio_get_pos(self)
VALUE self;
@@ -587,12 +462,6 @@ strio_get_pos(self)
return LONG2NUM(StringIO(self)->pos);
}
-/*
- * call-seq:
- * strio.pos = integer -> integer
- *
- * Seeks to the given position (in bytes) in *strio*.
- */
static VALUE
strio_set_pos(self, pos)
VALUE self;
@@ -604,17 +473,9 @@ strio_set_pos(self, pos)
error_inval(0);
}
ptr->pos = p;
- ptr->flags &= ~STRIO_EOF;
return pos;
}
-/*
- * call-seq:
- * strio.rewind -> 0
- *
- * Positions *strio* to the beginning of input, resetting
- * +lineno+ to zero.
- */
static VALUE
strio_rewind(self)
VALUE self;
@@ -626,13 +487,6 @@ strio_rewind(self)
return INT2FIX(0);
}
-/*
- * call-seq:
- * strio.seek(amount, whence=SEEK_SET) -> 0
- *
- * Seeks to a given offset _amount_ in the stream according to
- * the value of _whence_ (see IO#seek).
- */
static VALUE
strio_seek(argc, argv, self)
int argc;
@@ -665,12 +519,6 @@ strio_seek(argc, argv, self)
return INT2FIX(0);
}
-/*
- * call-seq:
- * strio.sync -> true
- *
- * Returns +true+ always.
- */
static VALUE
strio_get_sync(self)
VALUE self;
@@ -679,17 +527,10 @@ strio_get_sync(self)
return Qtrue;
}
-/* call-seq: strio.sync = boolean -> boolean */
#define strio_set_sync strio_first
#define strio_tell strio_get_pos
-/*
- * call-seq:
- * strio.each_byte {|byte| block } -> strio
- *
- * See IO#each_byte.
- */
static VALUE
strio_each_byte(self)
VALUE self;
@@ -702,12 +543,6 @@ strio_each_byte(self)
return Qnil;
}
-/*
- * call-seq:
- * strio.getc -> fixnum or nil
- *
- * See IO#getc.
- */
static VALUE
strio_getc(self)
VALUE self;
@@ -722,35 +557,6 @@ strio_getc(self)
return CHR2FIX(c);
}
-static void
-strio_extend(ptr, pos, len)
- struct StringIO *ptr;
- long pos, len;
-{
- long olen;
-
- check_modifiable(ptr);
- olen = RSTRING(ptr->string)->len;
- if (pos + len > olen) {
- rb_str_resize(ptr->string, pos + len);
- if (pos > olen)
- MEMZERO(RSTRING(ptr->string)->ptr + olen, char, pos - olen);
- }
- else {
- rb_str_modify(ptr->string);
- }
-}
-
-/*
- * call-seq:
- * strio.ungetc(integer) -> nil
- *
- * Pushes back one character (passed as a parameter) onto *strio*
- * such that a subsequent buffered read will return it. Pushing back
- * behind the beginning of the buffer string is not possible. Nothing
- * will be done if such an attempt is made.
- * In other case, there is no limitation for multiple pushbacks.
- */
static VALUE
strio_ungetc(self, ch)
VALUE self, ch;
@@ -760,11 +566,18 @@ strio_ungetc(self, ch)
long len, pos = ptr->pos;
if (cc != EOF && pos > 0) {
- if ((len = RSTRING(ptr->string)->len) < pos-- ||
- (unsigned char)RSTRING(ptr->string)->ptr[pos] !=
+ if ((len = RSTRING(ptr->string)->len) < pos ||
+ (unsigned char)RSTRING(ptr->string)->ptr[pos - 1] !=
(unsigned char)cc) {
- strio_extend(ptr, pos, 1);
- RSTRING(ptr->string)->ptr[pos] = cc;
+ check_modifiable(ptr);
+ if (len < pos) {
+ rb_str_resize(ptr->string, pos);
+ MEMZERO(RSTRING(ptr->string)->ptr + len, char, pos - len - 1);
+ }
+ else {
+ rb_str_modify(ptr->string);
+ }
+ RSTRING(ptr->string)->ptr[pos - 1] = cc;
OBJ_INFECT(ptr->string, self);
}
--ptr->pos;
@@ -773,12 +586,6 @@ strio_ungetc(self, ch)
return Qnil;
}
-/*
- * call-seq:
- * strio.readchar -> fixnum
- *
- * See IO#readchar.
- */
static VALUE
strio_readchar(self)
VALUE self;
@@ -865,7 +672,8 @@ strio_getline(argc, argv, ptr)
}
}
s = p;
- while ((p = memchr(p, '\n', e - p)) && (p != e)) {
+ while (p = memchr(p, '\n', e - p)) {
+ if (p == e) break;
if (*++p == '\n') {
e = p;
break;
@@ -874,7 +682,7 @@ strio_getline(argc, argv, ptr)
str = rb_str_substr(ptr->string, s - RSTRING(ptr->string)->ptr, e - s);
}
else if (n == 1) {
- if ((p = memchr(s, RSTRING(str)->ptr[0], e - s)) != 0) {
+ if (p = memchr(s, RSTRING(str)->ptr[0], e - s)) {
e = p + 1;
}
str = rb_str_substr(ptr->string, ptr->pos, e - s);
@@ -905,12 +713,6 @@ strio_getline(argc, argv, ptr)
return str;
}
-/*
- * call-seq:
- * strio.gets(sep_string=$/) -> string or nil
- *
- * See IO#gets.
- */
static VALUE
strio_gets(argc, argv, self)
int argc;
@@ -923,12 +725,6 @@ strio_gets(argc, argv, self)
return str;
}
-/*
- * call-seq:
- * strio.readline(sep_string=$/) -> string
- *
- * See IO#readline.
- */
static VALUE
strio_readline(argc, argv, self)
int argc;
@@ -940,13 +736,6 @@ strio_readline(argc, argv, self)
return line;
}
-/*
- * call-seq:
- * strio.each(sep_string=$/) {|line| block } -> strio
- * strio.each_line(sep_string=$/) {|line| block } -> strio
- *
- * See IO#each.
- */
static VALUE
strio_each(argc, argv, self)
int argc;
@@ -962,12 +751,6 @@ strio_each(argc, argv, self)
return self;
}
-/*
- * call-seq:
- * strio.readlines(sep_string=$/) -> array
- *
- * See IO#readlines.
- */
static VALUE
strio_readlines(argc, argv, self)
int argc;
@@ -982,16 +765,6 @@ strio_readlines(argc, argv, self)
return ary;
}
-/*
- * call-seq:
- * strio.write(string) -> integer
- * strio.syswrite(string) -> integer
- *
- * Appends the given string to the underlying buffer string of *strio*.
- * The stream must be opened for writing. If the argument is not a
- * string, it will be converted to a string using <code>to_s</code>.
- * Returns the number of bytes written. See IO#write.
- */
static VALUE
strio_write(self, str)
VALUE self, str;
@@ -1012,7 +785,13 @@ strio_write(self, str)
rb_str_cat(ptr->string, RSTRING(str)->ptr, len);
}
else {
- strio_extend(ptr, ptr->pos, len);
+ if (ptr->pos + len > olen) {
+ rb_str_resize(ptr->string, ptr->pos + len);
+ MEMZERO(RSTRING(ptr->string)->ptr + olen, char, ptr->pos - olen);
+ }
+ else {
+ rb_str_modify(ptr->string);
+ }
rb_str_update(ptr->string, ptr->pos, len, str);
}
OBJ_INFECT(ptr->string, self);
@@ -1020,70 +799,36 @@ strio_write(self, str)
return LONG2NUM(len);
}
-/*
- * call-seq:
- * strio << obj -> strio
- *
- * See IO#<<.
- */
#define strio_addstr rb_io_addstr
-/*
- * call-seq:
- * strio.print() -> nil
- * strio.print(obj, ...) -> nil
- *
- * See IO#print.
- */
#define strio_print rb_io_print
-/*
- * call-seq:
- * strio.printf(format_string [, obj, ...] ) -> nil
- *
- * See IO#printf.
- */
#define strio_printf rb_io_printf
-/*
- * call-seq:
- * strio.putc(obj) -> obj
- *
- * See IO#putc.
- */
static VALUE
strio_putc(self, ch)
VALUE self, ch;
{
struct StringIO *ptr = writable(StringIO(self));
int c = NUM2CHR(ch);
- long olen;
check_modifiable(ptr);
- olen = RSTRING(ptr->string)->len;
if (ptr->flags & FMODE_APPEND) {
- ptr->pos = olen;
+ ptr->pos = RSTRING(ptr->string)->len;
+ }
+ if (ptr->pos >= RSTRING(ptr->string)->len) {
+ rb_str_resize(ptr->string, ptr->pos + 1);
+ }
+ else {
+ rb_str_modify(ptr->string);
}
- strio_extend(ptr, ptr->pos, 1);
RSTRING(ptr->string)->ptr[ptr->pos++] = c;
OBJ_INFECT(ptr->string, self);
return ch;
}
-/*
- * call-seq:
- * strio.puts(obj, ...) -> nil
- *
- * See IO#puts.
- */
#define strio_puts rb_io_puts
-/*
- * call-seq:
- * strio.read([length [, buffer]]) -> string, buffer, or nil
- *
- * See IO#read.
- */
static VALUE
strio_read(argc, argv, self)
int argc;
@@ -1144,7 +889,7 @@ strio_read(argc, argv, self)
long rest = RSTRING(ptr->string)->len - ptr->pos;
if (len > rest) len = rest;
rb_str_resize(str, len);
- MEMCPY(RSTRING(str)->ptr, RSTRING(ptr->string)->ptr + ptr->pos, char, len);
+ MEMCPY(RSTRING(str)->ptr, RSTRING(ptr->string)->ptr, char, len);
}
if (NIL_P(str)) {
if (!(ptr->flags & STRIO_EOF)) str = rb_str_new(0, 0);
@@ -1157,13 +902,6 @@ strio_read(argc, argv, self)
return str;
}
-/*
- * call-seq:
- * strio.sysread(integer[, outbuf]) -> string
- *
- * Similar to #read, but raises +EOFError+ at end of string instead of
- * returning +nil+, as well as IO#sysread does.
- */
static VALUE
strio_sysread(argc, argv, self)
int argc;
@@ -1179,29 +917,14 @@ strio_sysread(argc, argv, self)
#define strio_syswrite strio_write
-/* call-seq: strio.path -> nil */
#define strio_path strio_nil
-/*
- * call-seq:
- * strio.isatty -> nil
- * strio.tty? -> nil
- *
- */
#define strio_isatty strio_false
-/* call-seq: strio.pid -> nil */
#define strio_pid strio_nil
-/* call-seq: strio.fileno -> nil */
#define strio_fileno strio_nil
-/*
- * call-seq:
- * strio.size -> integer
- *
- * Returns the size of the buffer string.
- */
static VALUE
strio_size(self)
VALUE self;
@@ -1213,33 +936,19 @@ strio_size(self)
return ULONG2NUM(RSTRING(string)->len);
}
-/*
- * call-seq:
- * strio.truncate(integer) -> 0
- *
- * Truncates the buffer string to at most _integer_ bytes. The *strio*
- * must be opened for writing.
- */
static VALUE
strio_truncate(self, len)
VALUE self, len;
{
VALUE string = writable(StringIO(self))->string;
long l = NUM2LONG(len);
- long plen = RSTRING(string)->len;
if (l < 0) {
error_inval("negative legnth");
}
rb_str_resize(string, l);
- if (plen < l) {
- MEMZERO(RSTRING(string)->ptr + plen, char, l - plen);
- }
return len;
}
-/*
- * Pseudo I/O on String object.
- */
void
Init_stringio()
{
diff --git a/ext/strscan/strscan.c b/ext/strscan/strscan.c
index a5a4ff7ba6..227ed92305 100644
--- a/ext/strscan/strscan.c
+++ b/ext/strscan/strscan.c
@@ -176,6 +176,7 @@ strscan_free(p)
struct strscanner *p;
{
re_free_registers(&(p->regs));
+ memset(p, sizeof(struct strscanner), 0);
free(p);
}
@@ -268,8 +269,7 @@ strscan_terminate(self)
}
/*
- * Equivalent to #terminate.
- * This method is obsolete; use #terminate instead.
+ * Returns the string being scanned.
*/
static VALUE
strscan_clear(self)
@@ -279,9 +279,6 @@ strscan_clear(self)
return strscan_terminate(self);
}
-/*
- * Returns the string being scanned.
- */
static VALUE
strscan_get_string(self)
VALUE self;
@@ -722,10 +719,6 @@ strscan_get_byte(self)
p->prev + p->regs.end[0]);
}
-/*
- * Equivalent to #get_byte.
- * This method is obsolete; use #get_byte instead.
- */
static VALUE
strscan_getbyte(self)
VALUE self;
@@ -764,18 +757,6 @@ strscan_peek(self, vlen)
}
/*
- * Equivalent to #peek.
- * This method is obsolete; use #peek instead.
- */
-static VALUE
-strscan_peep(self, vlen)
- VALUE self, vlen;
-{
- rb_warning("StringScanner#peep is obsolete; use #peek instead");
- return strscan_peek(self, vlen);
-}
-
-/*
* Set the scan pointer to the previous position. Only one previous position is
* remembered, and it changes with each scanning operation.
*
@@ -784,9 +765,17 @@ strscan_peep(self, vlen)
* s.unscan
* s.scan(/../) # => "te"
* s.scan(/\d/) # => nil
- * s.unscan # ScanError: can't unscan: prev match had failed
+ * s.unscan # ScanError: cannot unscan: prev match had failed
*/
static VALUE
+strscan_peep(self, vlen)
+ VALUE self, vlen;
+{
+ rb_warning("StringScanner#peep is obsolete; use #peek instead");
+ return strscan_peek(self, vlen);
+}
+
+static VALUE
strscan_unscan(self)
VALUE self;
{
@@ -794,7 +783,7 @@ strscan_unscan(self)
GET_SCANNER(self, p);
if (! MATCHED_P(p))
- rb_raise(ScanError, "can't unscan: prev match had failed");
+ rb_raise(ScanError, "cannot unscan: prev match had failed");
p->curr = p->prev;
CLEAR_MATCH_STATUS(p);
diff --git a/ext/syck/bytecode.c b/ext/syck/bytecode.c
index 567aaf52a8..ae5f19d7da 100644
--- a/ext/syck/bytecode.c
+++ b/ext/syck/bytecode.c
@@ -1,4 +1,4 @@
-/* Generated by re2c 0.9.10 on Mon Sep 19 23:21:26 2005 */
+/* Generated by re2c 0.9.3 on Fri Aug 13 11:47:50 2004 */
#line 1 "bytecode.re"
/*
* bytecode.re
@@ -89,7 +89,7 @@ char *get_inline( SyckParser *parser );
#define ENSURE_YAML_IOPEN(last_lvl, lvl_type, to_len, reset) \
if ( last_lvl->spaces < to_len ) \
{ \
- if ( last_lvl->status == syck_lvl_iseq || last_lvl->status == syck_lvl_imap ) \
+ if ( last_lvl->status == syck_lvl_inline ) \
{ \
goto Document; \
} \
@@ -135,6 +135,7 @@ int
sycklex_bytecode_utf8( YYSTYPE *sycklval, SyckParser *parser )
{
SyckLevel *lvl;
+ int doc_level = 0;
syck_parser_ptr = parser;
if ( YYCURSOR == NULL )
{
@@ -148,7 +149,7 @@ sycklex_bytecode_utf8( YYSTYPE *sycklval, SyckParser *parser )
return t;
}
-#line 172 "bytecode.re"
+#line 173 "bytecode.re"
lvl = CURRENT_LEVEL();
@@ -157,22 +158,22 @@ sycklex_bytecode_utf8( YYSTYPE *sycklval, SyckParser *parser )
goto Document;
}
-/* Header: */
+Header:
YYTOKEN = YYCURSOR;
-#line 165 "<stdout>"
+#line 7 "<stdout>"
{
YYCTYPE yych;
unsigned int yyaccept;
goto yy0;
- ++YYCURSOR;
+yy1: ++YYCURSOR;
yy0:
if((YYLIMIT - YYCURSOR) < 3) YYFILL(3);
yych = *YYCURSOR;
switch(yych){
- case 0x00: goto yy2;
+ case '\000': goto yy2;
case 'D': goto yy3;
default: goto yy5;
}
@@ -183,22 +184,22 @@ yy2: YYCURSOR = YYMARKER;
yy3: yyaccept = 0;
yych = *(YYMARKER = ++YYCURSOR);
switch(yych){
- case 0x0A: goto yy6;
- case 0x0D: goto yy8;
+ case '\n': goto yy6;
+ case '\r': goto yy8;
default: goto yy4;
}
yy4:
-#line 199 "bytecode.re"
+#line 200 "bytecode.re"
{ YYPOS(0);
goto Document;
}
-#line 195 "<stdout>"
+#line 37 "<stdout>"
yy5: yych = *++YYCURSOR;
goto yy4;
yy6: ++YYCURSOR;
goto yy7;
yy7:
-#line 186 "bytecode.re"
+#line 187 "bytecode.re"
{ if ( lvl->status == syck_lvl_header )
{
CHK_NL(YYCURSOR);
@@ -211,14 +212,14 @@ yy7:
return 0;
}
}
-#line 214 "<stdout>"
+#line 56 "<stdout>"
yy8: ++YYCURSOR;
switch((yych = *YYCURSOR)) {
- case 0x0A: goto yy6;
+ case '\n': goto yy6;
default: goto yy2;
}
}
-#line 203 "bytecode.re"
+#line 204 "bytecode.re"
Document:
@@ -232,18 +233,19 @@ Document:
YYTOKEN = YYCURSOR;
-#line 235 "<stdout>"
+#line 65 "<stdout>"
{
YYCTYPE yych;
+ unsigned int yyaccept;
goto yy9;
- ++YYCURSOR;
+yy10: ++YYCURSOR;
yy9:
if((YYLIMIT - YYCURSOR) < 3) YYFILL(3);
yych = *YYCURSOR;
switch(yych){
- case 0x00: goto yy30;
- case 0x0A: goto yy27;
- case 0x0D: goto yy29;
+ case '\000': goto yy30;
+ case '\n': goto yy27;
+ case '\r': goto yy29;
case 'A': goto yy19;
case 'D': goto yy12;
case 'E': goto yy16;
@@ -258,68 +260,68 @@ yy9:
}
yy11:yy12: yych = *++YYCURSOR;
switch(yych){
- case 0x0A: goto yy41;
- case 0x0D: goto yy44;
+ case '\n': goto yy41;
+ case '\r': goto yy44;
default: goto yy11;
}
yy13: yych = *++YYCURSOR;
switch(yych){
- case 0x0A: goto yy41;
- case 0x0D: goto yy43;
+ case '\n': goto yy41;
+ case '\r': goto yy43;
default: goto yy11;
}
yy14: yych = *++YYCURSOR;
switch(yych){
- case 0x0A: goto yy38;
- case 0x0D: goto yy40;
+ case '\n': goto yy38;
+ case '\r': goto yy40;
default: goto yy11;
}
yy15: yych = *++YYCURSOR;
switch(yych){
- case 0x0A: goto yy35;
- case 0x0D: goto yy37;
+ case '\n': goto yy35;
+ case '\r': goto yy37;
default: goto yy11;
}
yy16: yych = *++YYCURSOR;
switch(yych){
- case 0x0A: goto yy32;
- case 0x0D: goto yy34;
+ case '\n': goto yy32;
+ case '\r': goto yy34;
default: goto yy11;
}
yy17: ++YYCURSOR;
goto yy18;
yy18:
-#line 288 "bytecode.re"
+#line 289 "bytecode.re"
{ ADD_BYTE_LEVEL(lvl, lvl->spaces + 1, syck_lvl_str);
goto Scalar;
}
-#line 296 "<stdout>"
+#line 127 "<stdout>"
yy19: ++YYCURSOR;
goto yy20;
yy20:
-#line 292 "bytecode.re"
+#line 293 "bytecode.re"
{ ADD_BYTE_LEVEL(lvl, lvl->spaces + 1, syck_lvl_open);
sycklval->name = get_inline( parser );
syck_hdlr_remove_anchor( parser, sycklval->name );
CHK_NL(YYCURSOR);
return YAML_ANCHOR;
}
-#line 307 "<stdout>"
+#line 138 "<stdout>"
yy21: ++YYCURSOR;
goto yy22;
yy22:
-#line 299 "bytecode.re"
+#line 300 "bytecode.re"
{ ADD_BYTE_LEVEL(lvl, lvl->spaces + 1, syck_lvl_str);
sycklval->name = get_inline( parser );
POP_LEVEL();
if ( *( YYCURSOR - 1 ) == '\n' ) YYCURSOR--;
return YAML_ALIAS;
}
-#line 318 "<stdout>"
+#line 149 "<stdout>"
yy23: ++YYCURSOR;
goto yy24;
yy24:
-#line 306 "bytecode.re"
+#line 307 "bytecode.re"
{ char *qstr;
ADD_BYTE_LEVEL(lvl, lvl->spaces + 1, syck_lvl_open);
qstr = get_inline( parser );
@@ -379,17 +381,17 @@ yy24:
sycklval->name = qstr;
return YAML_TAGURI;
}
-#line 382 "<stdout>"
+#line 213 "<stdout>"
yy25: ++YYCURSOR;
goto yy26;
yy26:
-#line 366 "bytecode.re"
+#line 367 "bytecode.re"
{ goto Comment; }
-#line 388 "<stdout>"
+#line 219 "<stdout>"
yy27: ++YYCURSOR;
goto yy28;
yy28:
-#line 368 "bytecode.re"
+#line 369 "bytecode.re"
{ CHK_NL(YYCURSOR);
if ( lvl->status == syck_lvl_seq )
{
@@ -402,25 +404,25 @@ yy28:
}
goto Document;
}
-#line 405 "<stdout>"
+#line 236 "<stdout>"
yy29: yych = *++YYCURSOR;
switch(yych){
- case 0x0A: goto yy27;
+ case '\n': goto yy27;
default: goto yy11;
}
yy30: ++YYCURSOR;
goto yy31;
yy31:
-#line 381 "bytecode.re"
+#line 382 "bytecode.re"
{ ENSURE_YAML_IEND(lvl, -1);
YYPOS(0);
return 0;
}
-#line 419 "<stdout>"
+#line 250 "<stdout>"
yy32: ++YYCURSOR;
goto yy33;
yy33:
-#line 252 "bytecode.re"
+#line 253 "bytecode.re"
{ if ( lvl->status == syck_lvl_seq && lvl->ncount == 0 )
{
lvl->ncount++;
@@ -456,16 +458,16 @@ yy33:
CHK_NL(YYCURSOR);
return YAML_IEND;
}
-#line 459 "<stdout>"
+#line 290 "<stdout>"
yy34: yych = *++YYCURSOR;
switch(yych){
- case 0x0A: goto yy32;
+ case '\n': goto yy32;
default: goto yy11;
}
yy35: ++YYCURSOR;
goto yy36;
yy36:
-#line 237 "bytecode.re"
+#line 238 "bytecode.re"
{ int complex = 0;
if ( lvl->ncount % 2 == 0 && ( lvl->status == syck_lvl_map || lvl->status == syck_lvl_seq ) )
{
@@ -480,16 +482,16 @@ yy36:
}
return YAML_IOPEN;
}
-#line 483 "<stdout>"
+#line 314 "<stdout>"
yy37: yych = *++YYCURSOR;
switch(yych){
- case 0x0A: goto yy35;
+ case '\n': goto yy35;
default: goto yy11;
}
yy38: ++YYCURSOR;
goto yy39;
yy39:
-#line 222 "bytecode.re"
+#line 223 "bytecode.re"
{ int complex = 0;
if ( lvl->ncount % 2 == 0 && ( lvl->status == syck_lvl_map || lvl->status == syck_lvl_seq ) )
{
@@ -504,33 +506,33 @@ yy39:
}
return YAML_IOPEN;
}
-#line 507 "<stdout>"
+#line 338 "<stdout>"
yy40: yych = *++YYCURSOR;
switch(yych){
- case 0x0A: goto yy38;
+ case '\n': goto yy38;
default: goto yy11;
}
yy41: ++YYCURSOR;
goto yy42;
yy42:
-#line 217 "bytecode.re"
+#line 218 "bytecode.re"
{ ENSURE_YAML_IEND(lvl, -1);
YYPOS(0);
return 0;
}
-#line 521 "<stdout>"
+#line 352 "<stdout>"
yy43: yych = *++YYCURSOR;
switch(yych){
- case 0x0A: goto yy41;
+ case '\n': goto yy41;
default: goto yy11;
}
yy44: ++YYCURSOR;
switch((yych = *YYCURSOR)) {
- case 0x0A: goto yy41;
+ case '\n': goto yy41;
default: goto yy11;
}
}
-#line 386 "bytecode.re"
+#line 387 "bytecode.re"
}
@@ -540,17 +542,17 @@ Directive:
YYTOKEN = YYCURSOR;
-#line 543 "<stdout>"
+#line 366 "<stdout>"
{
YYCTYPE yych;
unsigned int yyaccept;
goto yy45;
- ++YYCURSOR;
+yy46: ++YYCURSOR;
yy45:
if((YYLIMIT - YYCURSOR) < 2) YYFILL(2);
yych = *YYCURSOR;
switch(yych){
- case 0x00: goto yy47;
+ case '\000': goto yy47;
case 'V': goto yy48;
default: goto yy50;
}
@@ -639,15 +641,15 @@ yy48: yyaccept = 0;
default: goto yy49;
}
yy49:
-#line 399 "bytecode.re"
+#line 400 "bytecode.re"
{ YYCURSOR = YYTOKEN;
return YAML_DOCSEP;
}
-#line 646 "<stdout>"
+#line 469 "<stdout>"
yy50: yych = *++YYCURSOR;
goto yy49;
yy51: ++YYCURSOR;
- if((YYLIMIT - YYCURSOR) < 2) YYFILL(2);
+ if(YYLIMIT == YYCURSOR) YYFILL(1);
yych = *YYCURSOR;
goto yy52;
yy52: switch(yych){
@@ -807,12 +809,12 @@ yy53: yych = *++YYCURSOR;
default: goto yy47;
}
yy54: ++YYCURSOR;
- if((YYLIMIT - YYCURSOR) < 2) YYFILL(2);
+ if(YYLIMIT == YYCURSOR) YYFILL(1);
yych = *YYCURSOR;
goto yy55;
yy55: switch(yych){
- case 0x0A: goto yy56;
- case 0x0D: goto yy58;
+ case '\n': goto yy56;
+ case '\r': goto yy58;
case '.':
case '/':
case '0':
@@ -893,17 +895,17 @@ yy55: switch(yych){
yy56: ++YYCURSOR;
goto yy57;
yy57:
-#line 396 "bytecode.re"
+#line 397 "bytecode.re"
{ CHK_NL(YYCURSOR);
goto Directive; }
-#line 899 "<stdout>"
+#line 724 "<stdout>"
yy58: ++YYCURSOR;
switch((yych = *YYCURSOR)) {
- case 0x0A: goto yy56;
+ case '\n': goto yy56;
default: goto yy47;
}
}
-#line 402 "bytecode.re"
+#line 403 "bytecode.re"
}
@@ -913,43 +915,44 @@ Comment:
YYTOKEN = YYCURSOR;
-#line 916 "<stdout>"
+#line 733 "<stdout>"
{
YYCTYPE yych;
+ unsigned int yyaccept;
goto yy59;
- ++YYCURSOR;
+yy60: ++YYCURSOR;
yy59:
if((YYLIMIT - YYCURSOR) < 2) YYFILL(2);
yych = *YYCURSOR;
switch(yych){
- case 0x00: goto yy61;
- case 0x0A: goto yy62;
- case 0x0D: goto yy64;
+ case '\000': goto yy61;
+ case '\n': goto yy62;
+ case '\r': goto yy64;
default: goto yy66;
}
yy61:yy62: ++YYCURSOR;
goto yy63;
yy63:
-#line 412 "bytecode.re"
+#line 413 "bytecode.re"
{ CHK_NL(YYCURSOR);
goto Document; }
-#line 936 "<stdout>"
+#line 754 "<stdout>"
yy64: ++YYCURSOR;
switch((yych = *YYCURSOR)) {
- case 0x0A: goto yy67;
+ case '\n': goto yy67;
default: goto yy65;
}
yy65:
-#line 415 "bytecode.re"
+#line 416 "bytecode.re"
{ goto Comment; }
-#line 945 "<stdout>"
+#line 763 "<stdout>"
yy66: yych = *++YYCURSOR;
goto yy65;
yy67: ++YYCURSOR;
yych = *YYCURSOR;
goto yy63;
}
-#line 417 "bytecode.re"
+#line 418 "bytecode.re"
}
@@ -967,18 +970,19 @@ Scalar2:
tok = YYCURSOR;
-#line 970 "<stdout>"
+#line 771 "<stdout>"
{
YYCTYPE yych;
+ unsigned int yyaccept;
goto yy68;
- ++YYCURSOR;
+yy69: ++YYCURSOR;
yy68:
if((YYLIMIT - YYCURSOR) < 3) YYFILL(3);
yych = *YYCURSOR;
switch(yych){
- case 0x00: goto yy74;
- case 0x0A: goto yy70;
- case 0x0D: goto yy72;
+ case '\000': goto yy74;
+ case '\n': goto yy70;
+ case '\r': goto yy72;
default: goto yy76;
}
yy70: ++YYCURSOR;
@@ -989,30 +993,30 @@ yy70: ++YYCURSOR;
default: goto yy71;
}
yy71:
-#line 461 "bytecode.re"
+#line 462 "bytecode.re"
{ YYCURSOR = tok;
goto ScalarEnd;
}
-#line 996 "<stdout>"
+#line 798 "<stdout>"
yy72: ++YYCURSOR;
switch((yych = *YYCURSOR)) {
- case 0x0A: goto yy77;
+ case '\n': goto yy77;
default: goto yy73;
}
yy73:
-#line 469 "bytecode.re"
+#line 470 "bytecode.re"
{ CAT(str, cap, idx, tok[0]);
goto Scalar2;
}
-#line 1007 "<stdout>"
+#line 809 "<stdout>"
yy74: ++YYCURSOR;
goto yy75;
yy75:
-#line 465 "bytecode.re"
+#line 466 "bytecode.re"
{ YYCURSOR = tok;
goto ScalarEnd;
}
-#line 1015 "<stdout>"
+#line 817 "<stdout>"
yy76: yych = *++YYCURSOR;
goto yy73;
yy77: yych = *++YYCURSOR;
@@ -1025,10 +1029,10 @@ yy77: yych = *++YYCURSOR;
yy78: ++YYCURSOR;
goto yy79;
yy79:
-#line 435 "bytecode.re"
+#line 436 "bytecode.re"
{ CHK_NL(tok+1);
goto Scalar2; }
-#line 1031 "<stdout>"
+#line 833 "<stdout>"
yy80: ++YYCURSOR;
if(YYLIMIT == YYCURSOR) YYFILL(1);
yych = *YYCURSOR;
@@ -1047,7 +1051,7 @@ yy81: switch(yych){
default: goto yy82;
}
yy82:
-#line 438 "bytecode.re"
+#line 439 "bytecode.re"
{ CHK_NL(tok+1);
if ( tok + 2 < YYCURSOR )
{
@@ -1065,18 +1069,18 @@ yy82:
}
goto Scalar2;
}
-#line 1068 "<stdout>"
+#line 871 "<stdout>"
yy83: ++YYCURSOR;
goto yy84;
yy84:
-#line 456 "bytecode.re"
+#line 457 "bytecode.re"
{ CHK_NL(tok+1);
CAT(str, cap, idx, '\0');
goto Scalar2;
}
-#line 1077 "<stdout>"
+#line 880 "<stdout>"
}
-#line 473 "bytecode.re"
+#line 474 "bytecode.re"
ScalarEnd:
@@ -1111,53 +1115,54 @@ Inline:
tok = YYCURSOR;
-#line 1114 "<stdout>"
+#line 884 "<stdout>"
{
YYCTYPE yych;
+ unsigned int yyaccept;
goto yy85;
- ++YYCURSOR;
+yy86: ++YYCURSOR;
yy85:
if((YYLIMIT - YYCURSOR) < 2) YYFILL(2);
yych = *YYCURSOR;
switch(yych){
- case 0x00: goto yy91;
- case 0x0A: goto yy87;
- case 0x0D: goto yy89;
+ case '\000': goto yy91;
+ case '\n': goto yy87;
+ case '\r': goto yy89;
default: goto yy93;
}
yy87: ++YYCURSOR;
goto yy88;
yy88:
-#line 508 "bytecode.re"
+#line 509 "bytecode.re"
{ CHK_NL(YYCURSOR);
return str; }
-#line 1134 "<stdout>"
+#line 905 "<stdout>"
yy89: ++YYCURSOR;
switch((yych = *YYCURSOR)) {
- case 0x0A: goto yy94;
+ case '\n': goto yy94;
default: goto yy90;
}
yy90:
-#line 515 "bytecode.re"
+#line 516 "bytecode.re"
{ CAT(str, cap, idx, tok[0]);
goto Inline;
}
-#line 1145 "<stdout>"
+#line 916 "<stdout>"
yy91: ++YYCURSOR;
goto yy92;
yy92:
-#line 511 "bytecode.re"
+#line 512 "bytecode.re"
{ YYCURSOR = tok;
return str;
}
-#line 1153 "<stdout>"
+#line 924 "<stdout>"
yy93: yych = *++YYCURSOR;
goto yy90;
yy94: ++YYCURSOR;
yych = *YYCURSOR;
goto yy88;
}
-#line 519 "bytecode.re"
+#line 520 "bytecode.re"
}
diff --git a/ext/syck/emitter.c b/ext/syck/emitter.c
index f5de4b841a..25437b230c 100644
--- a/ext/syck/emitter.c
+++ b/ext/syck/emitter.c
@@ -18,11 +18,16 @@
#define DEFAULT_ANCHOR_FORMAT "id%03d"
-const char hex_table[] =
-"0123456789ABCDEF";
static char b64_table[] =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
+struct adjust_arg {
+ /* Position to start adjusting */
+ long startpos;
+ /* Adjusting by an offset */
+ int offset;
+};
+
/*
* Built-in base64 (from Ruby's pack.c)
*/
@@ -31,7 +36,7 @@ syck_base64enc( char *s, long len )
{
long i = 0;
int padding = '=';
- char *buff = S_ALLOC_N(char, len * 4 / 3 + 6);
+ char *buff = S_ALLOCA_N(char, len * 4 / 3 + 6);
while (len >= 3) {
buff[i++] = b64_table[077 & (*s >> 2)];
@@ -111,29 +116,25 @@ syck_new_emitter()
SyckEmitter *e;
e = S_ALLOC( SyckEmitter );
e->headless = 0;
+ e->seq_map = 0;
e->use_header = 0;
e->use_version = 0;
e->sort_keys = 0;
e->anchor_format = NULL;
e->explicit_typing = 0;
e->best_width = 80;
- e->style = scalar_none;
+ e->block_style = block_arbitrary;
e->stage = doc_open;
e->indent = 2;
e->level = -1;
+ e->ignore_id = 0;
e->anchors = NULL;
e->markers = NULL;
- e->anchored = NULL;
e->bufsize = SYCK_BUFFERSIZE;
e->buffer = NULL;
e->marker = NULL;
e->bufpos = 0;
- e->emitter_handler = NULL;
- e->output_handler = NULL;
- e->lvl_idx = 0;
- e->lvl_capa = ALLOC_CT;
- e->levels = S_ALLOC_N( SyckLevel, e->lvl_capa );
- syck_emitter_reset_levels( e );
+ e->handler = NULL;
e->bonus = NULL;
return e;
}
@@ -145,6 +146,13 @@ syck_st_free_anchors( char *key, char *name, char *arg )
return ST_CONTINUE;
}
+int
+syck_st_free_markers( char *key, SyckEmitterNode *n, char *arg )
+{
+ S_FREE( n );
+ return ST_CONTINUE;
+}
+
void
syck_emitter_st_free( SyckEmitter *e )
{
@@ -158,94 +166,27 @@ syck_emitter_st_free( SyckEmitter *e )
e->anchors = NULL;
}
- if ( e->anchored != NULL )
- {
- st_free_table( e->anchored );
- e->anchored = NULL;
- }
-
/*
* Free the markers tables
*/
if ( e->markers != NULL )
{
+ st_foreach( e->markers, syck_st_free_markers, 0 );
st_free_table( e->markers );
e->markers = NULL;
}
}
-SyckLevel *
-syck_emitter_current_level( SyckEmitter *e )
-{
- return &e->levels[e->lvl_idx-1];
-}
-
-SyckLevel *
-syck_emitter_parent_level( SyckEmitter *e )
-{
- return &e->levels[e->lvl_idx-2];
-}
-
void
-syck_emitter_pop_level( SyckEmitter *e )
+syck_emitter_ignore_id( SyckEmitter *e, SYMID id )
{
- ASSERT( e != NULL );
-
- /* The root level should never be popped */
- if ( e->lvl_idx <= 1 ) return;
-
- e->lvl_idx -= 1;
- free( e->levels[e->lvl_idx].domain );
-}
-
-void
-syck_emitter_add_level( SyckEmitter *e, int len, enum syck_level_status status )
-{
- ASSERT( e != NULL );
- if ( e->lvl_idx + 1 > e->lvl_capa )
- {
- e->lvl_capa += ALLOC_CT;
- S_REALLOC_N( e->levels, SyckLevel, e->lvl_capa );
- }
-
- ASSERT( len > e->levels[e->lvl_idx-1].spaces );
- e->levels[e->lvl_idx].spaces = len;
- e->levels[e->lvl_idx].ncount = 0;
- e->levels[e->lvl_idx].domain = syck_strndup( e->levels[e->lvl_idx-1].domain, strlen( e->levels[e->lvl_idx-1].domain ) );
- e->levels[e->lvl_idx].status = status;
- e->levels[e->lvl_idx].anctag = 0;
- e->lvl_idx += 1;
+ e->ignore_id = id;
}
void
-syck_emitter_reset_levels( SyckEmitter *e )
+syck_emitter_handler( SyckEmitter *e, SyckOutputHandler hdlr )
{
- while ( e->lvl_idx > 1 )
- {
- syck_emitter_pop_level( e );
- }
-
- if ( e->lvl_idx < 1 )
- {
- e->lvl_idx = 1;
- e->levels[0].spaces = -1;
- e->levels[0].ncount = 0;
- e->levels[0].domain = syck_strndup( "", 0 );
- e->levels[0].anctag = 0;
- }
- e->levels[0].status = syck_lvl_header;
-}
-
-void
-syck_emitter_handler( SyckEmitter *e, SyckEmitterHandler hdlr )
-{
- e->emitter_handler = hdlr;
-}
-
-void
-syck_output_handler( SyckEmitter *e, SyckOutputHandler hdlr )
-{
- e->output_handler = hdlr;
+ e->handler = hdlr;
}
void
@@ -255,9 +196,6 @@ syck_free_emitter( SyckEmitter *e )
* Free tables
*/
syck_emitter_st_free( e );
- syck_emitter_reset_levels( e );
- S_FREE( e->levels[0].domain );
- S_FREE( e->levels );
if ( e->buffer != NULL )
{
S_FREE( e->buffer );
@@ -314,7 +252,6 @@ syck_emitter_write( SyckEmitter *e, char *str, long len )
*/
S_MEMCPY( e->marker, str, char, len );
e->marker += len;
- e->marker[0] = '\0';
}
/*
@@ -339,911 +276,169 @@ syck_emitter_flush( SyckEmitter *e, long check_room )
}
/*
- * Commit buffer.
- */
- if ( check_room > e->marker - e->buffer )
- {
- check_room = e->marker - e->buffer;
- }
- (e->output_handler)( e, e->buffer, check_room );
- e->bufpos += check_room;
- e->marker -= check_room;
-}
-
-/*
- * Start emitting from the given node, check for anchoring and then
- * issue the callback to the emitter handler.
- */
-void
-syck_emit( SyckEmitter *e, st_data_t n )
-{
- SYMID oid;
- char *anchor_name = NULL;
- int indent = 0;
- long x = 0;
- SyckLevel *lvl = syck_emitter_current_level( e );
-
- /*
* Determine headers.
*/
- if ( e->stage == doc_open && ( e->headless == 0 || e->use_header == 1 ) )
+ if ( ( e->stage == doc_open && ( e->headless == 0 || e->use_header == 1 ) ) ||
+ e->stage == doc_need_header )
{
if ( e->use_version == 1 )
{
char *header = S_ALLOC_N( char, 64 );
S_MEMZERO( header, char, 64 );
sprintf( header, "--- %%YAML:%d.%d ", SYCK_YAML_MAJOR, SYCK_YAML_MINOR );
- syck_emitter_write( e, header, strlen( header ) );
+ (e->handler)( e, header, strlen( header ) );
S_FREE( header );
}
else
{
- syck_emitter_write( e, "--- ", 4 );
+ (e->handler)( e, "--- ", 4 );
}
e->stage = doc_processing;
}
- /* Add new level */
- if ( lvl->spaces >= 0 ) {
- indent = lvl->spaces + e->indent;
- }
- syck_emitter_add_level( e, indent, syck_lvl_open );
- lvl = syck_emitter_current_level( e );
-
- /* Look for anchor */
- if ( e->anchors != NULL &&
- st_lookup( e->markers, n, (st_data_t *)&oid ) &&
- st_lookup( e->anchors, (st_data_t)oid, (st_data_t *)&anchor_name ) )
+ /*
+ * Commit buffer.
+ */
+ if ( check_room > e->marker - e->buffer )
{
- if ( e->anchored == NULL )
- {
- e->anchored = st_init_numtable();
- }
-
- if ( ! st_lookup( e->anchored, (st_data_t)anchor_name, (st_data_t *)&x ) )
- {
- char *an = S_ALLOC_N( char, strlen( anchor_name ) + 3 );
- sprintf( an, "&%s ", anchor_name );
- syck_emitter_write( e, an, strlen( anchor_name ) + 2 );
- free( an );
-
- x = 1;
- st_insert( e->anchored, (st_data_t)anchor_name, (st_data_t)x );
- lvl->anctag = 1;
- }
- else
- {
- char *an = S_ALLOC_N( char, strlen( anchor_name ) + 2 );
- sprintf( an, "*%s", anchor_name );
- syck_emitter_write( e, an, strlen( anchor_name ) + 1 );
- free( an );
-
- goto end_emit;
- }
- }
-
- (e->emitter_handler)( e, n );
-
- /* Pop the level */
-end_emit:
- syck_emitter_pop_level( e );
- if ( e->lvl_idx == 1 ) {
- syck_emitter_write( e, "\n", 1 );
- e->headless = 0;
- e->stage = doc_open;
+ check_room = e->marker - e->buffer;
}
+ (e->handler)( e, e->buffer, check_room );
+ e->bufpos += check_room;
+ e->marker -= check_room;
}
/*
- * Determine what tag needs to be written, based on the taguri of the node
- * and the implicit tag which would be assigned to this node. If a tag is
- * required, write the tag.
- */
-void syck_emit_tag( SyckEmitter *e, char *tag, char *ignore )
-{
- SyckLevel *lvl;
- if ( tag == NULL ) return;
- if ( ignore != NULL && syck_tagcmp( tag, ignore ) == 0 && e->explicit_typing == 0 ) return;
- lvl = syck_emitter_current_level( e );
-
- /* implicit */
- if ( strlen( tag ) == 0 ) {
- syck_emitter_write( e, "! ", 2 );
-
- /* global types */
- } else if ( strncmp( tag, "tag:", 4 ) == 0 ) {
- int taglen = strlen( tag );
- syck_emitter_write( e, "!", 1 );
- if ( strncmp( tag + 4, YAML_DOMAIN, strlen( YAML_DOMAIN ) ) == 0 ) {
- int skip = 4 + strlen( YAML_DOMAIN ) + 1;
- syck_emitter_write( e, tag + skip, taglen - skip );
- } else {
- char *subd = tag + 4;
- while ( *subd != ':' && *subd != '\0' ) subd++;
- if ( *subd == ':' ) {
- if ( subd - tag > ( strlen( YAML_DOMAIN ) + 5 ) &&
- strncmp( subd - strlen( YAML_DOMAIN ), YAML_DOMAIN, strlen( YAML_DOMAIN ) ) == 0 ) {
- syck_emitter_write( e, tag + 4, subd - strlen( YAML_DOMAIN ) - ( tag + 4 ) - 1 );
- syck_emitter_write( e, "/", 1 );
- syck_emitter_write( e, subd + 1, ( tag + taglen ) - ( subd + 1 ) );
- } else {
- syck_emitter_write( e, tag + 4, subd - ( tag + 4 ) );
- syck_emitter_write( e, "/", 1 );
- syck_emitter_write( e, subd + 1, ( tag + taglen ) - ( subd + 1 ) );
- }
- } else {
- /* TODO: Invalid tag (no colon after domain) */
- return;
- }
- }
- syck_emitter_write( e, " ", 1 );
-
- /* private types */
- } else if ( strncmp( tag, "x-private:", 10 ) == 0 ) {
- syck_emitter_write( e, "!!", 2 );
- syck_emitter_write( e, tag + 10, strlen( tag ) - 10 );
- syck_emitter_write( e, " ", 1 );
- }
- lvl->anctag = 1;
-}
-
-/*
- * Emit a newline and an appropriately spaced indent.
+ * Emit a simple, unquoted string.
*/
-void syck_emit_indent( SyckEmitter *e )
+void
+syck_emitter_simple( SyckEmitter *e, char *str, long len )
{
- int i;
- SyckLevel *lvl = syck_emitter_current_level( e );
- if ( e->bufpos == 0 && ( e->marker - e->buffer ) == 0 ) return;
- if ( lvl->spaces >= 0 ) {
- char *spcs = S_ALLOC_N( char, lvl->spaces + 2 );
-
- spcs[0] = '\n'; spcs[lvl->spaces + 1] = '\0';
- for ( i = 0; i < lvl->spaces; i++ ) spcs[i+1] = ' ';
- syck_emitter_write( e, spcs, lvl->spaces + 1 );
- free( spcs );
- }
+ e->seq_map = 0;
+ syck_emitter_write( e, str, len );
}
-/* Clear the scan */
-#define SCAN_NONE 0
-/* All printable characters? */
-#define SCAN_NONPRINT 1
-/* Any indented lines? */
-#define SCAN_INDENTED 2
-/* Larger than the requested width? */
-#define SCAN_WIDE 4
-/* Opens or closes with whitespace? */
-#define SCAN_WHITEEDGE 8
-/* Contains a newline */
-#define SCAN_NEWLINE 16
-/* Contains a single quote */
-#define SCAN_SINGLEQ 32
-/* Contains a double quote */
-#define SCAN_DOUBLEQ 64
-/* Starts with a token */
-#define SCAN_INDIC_S 128
-/* Contains a flow indicator */
-#define SCAN_INDIC_C 256
-/* Ends without newlines */
-#define SCAN_NONL_E 512
-/* Ends with many newlines */
-#define SCAN_MANYNL_E 1024
-/* Contains flow map indicators */
-#define SCAN_FLOWMAP 2048
-/* Contains flow seq indicators */
-#define SCAN_FLOWSEQ 4096
-/* Contains a valid doc separator */
-#define SCAN_DOCSEP 8192
-
/*
- * Basic printable test for LATIN-1 characters.
+ * Shift the offsets of all applicable anchors
*/
int
-syck_scan_scalar( int req_width, char *cursor, long len )
-{
- long i = 0, start = 0;
- int flags = SCAN_NONE;
-
- if ( len < 1 ) return flags;
-
- /* c-indicators from the spec */
- if ( cursor[0] == '[' || cursor[0] == ']' ||
- cursor[0] == '{' || cursor[0] == '}' ||
- cursor[0] == '!' || cursor[0] == '*' ||
- cursor[0] == '&' || cursor[0] == '|' ||
- cursor[0] == '>' || cursor[0] == '\'' ||
- cursor[0] == '"' || cursor[0] == '#' ||
- cursor[0] == '%' || cursor[0] == '@' ||
- cursor[0] == '&' ) {
- flags |= SCAN_INDIC_S;
- }
- if ( ( cursor[0] == '-' || cursor[0] == ':' ||
- cursor[0] == '?' || cursor[0] == ',' ) &&
- ( cursor[1] == ' ' || cursor[1] == '\n' || len == 1 ) )
- {
- flags |= SCAN_INDIC_S;
- }
-
- /* whitespace edges */
- if ( cursor[len-1] != '\n' ) {
- flags |= SCAN_NONL_E;
- } else if ( len > 1 && cursor[len-2] == '\n' ) {
- flags |= SCAN_MANYNL_E;
- }
- if (
- ( len > 0 && ( cursor[0] == ' ' || cursor[0] == '\t' ) ) ||
- ( len > 1 && ( cursor[len-1] == ' ' || cursor[len-1] == '\t' ) )
- ) {
- flags |= SCAN_WHITEEDGE;
- }
-
- /* opening doc sep */
- if ( len >= 3 && strncmp( cursor, "---", 3 ) == 0 )
- flags |= SCAN_DOCSEP;
-
- /* scan string */
- for ( i = 0; i < len; i++ ) {
-
- if ( ! ( cursor[i] == 0x9 ||
- cursor[i] == 0xA ||
- cursor[i] == 0xD ||
- ( cursor[i] >= 0x20 && cursor[i] <= 0x7E ) )
- ) {
- flags |= SCAN_NONPRINT;
- }
- else if ( cursor[i] == '\n' ) {
- flags |= SCAN_NEWLINE;
- if ( len - i >= 3 && strncmp( &cursor[i+1], "---", 3 ) == 0 )
- flags |= SCAN_DOCSEP;
- if ( cursor[i+1] == ' ' || cursor[i+1] == '\t' )
- flags |= SCAN_INDENTED;
- if ( req_width > 0 && i - start > req_width )
- flags |= SCAN_WIDE;
- start = i;
- }
- else if ( cursor[i] == '\'' )
- {
- flags |= SCAN_SINGLEQ;
- }
- else if ( cursor[i] == '"' )
- {
- flags |= SCAN_DOUBLEQ;
- }
- else if ( cursor[i] == ']' )
- {
- flags |= SCAN_FLOWSEQ;
- }
- else if ( cursor[i] == '}' )
- {
- flags |= SCAN_FLOWMAP;
- }
- /* remember, if plain collections get implemented, to add nb-plain-flow-char */
- else if ( ( cursor[i] == ' ' && cursor[i+1] == '#' ) ||
- ( cursor[i] == ':' &&
- ( cursor[i+1] == ' ' || cursor[i+1] == '\n' || i == len - 1 ) ) )
- {
- flags |= SCAN_INDIC_C;
- }
- else if ( cursor[i] == ',' &&
- ( cursor[i+1] == ' ' || cursor[i+1] == '\n' || i == len - 1 ) )
- {
- flags |= SCAN_FLOWMAP;
- flags |= SCAN_FLOWSEQ;
- }
- }
-
- /* printf( "---STR---\n%s\nFLAGS: %d\n", cursor, flags ); */
- return flags;
-}
-/*
- * All scalars should be emitted through this function, which determines an appropriate style,
- * tag and indent.
- */
-void syck_emit_scalar( SyckEmitter *e, char *tag, enum scalar_style force_style, int force_indent, int force_width,
- char keep_nl, char *str, long len )
-{
- enum scalar_style favor_style = scalar_literal;
- SyckLevel *parent = syck_emitter_parent_level( e );
- SyckLevel *lvl = syck_emitter_current_level( e );
- int scan = 0;
- char *implicit;
-
- if ( str == NULL ) str = "";
-
- /* No empty nulls as map keys */
- if ( len == 0 && ( parent->status == syck_lvl_map || parent->status == syck_lvl_imap ) &&
- parent->ncount % 2 == 1 && syck_tagcmp( tag, "tag:yaml.org,2002:null" ) == 0 )
- {
- str = "~";
- len = 1;
- }
-
- scan = syck_scan_scalar( force_width, str, len );
- implicit = syck_match_implicit( str, len );
-
- /* quote strings which default to implicits */
- implicit = syck_taguri( YAML_DOMAIN, implicit, strlen( implicit ) );
- if ( syck_tagcmp( tag, implicit ) != 0 && syck_tagcmp( tag, "tag:yaml.org,2002:str" ) == 0 ) {
- force_style = scalar_2quote;
- } else {
- /* complex key */
- if ( parent->status == syck_lvl_map && parent->ncount % 2 == 1 &&
- ( !( tag == NULL ||
- ( implicit != NULL && syck_tagcmp( tag, implicit ) == 0 && e->explicit_typing == 0 ) ) ) )
- {
- syck_emitter_write( e, "? ", 2 );
- parent->status = syck_lvl_mapx;
- }
- syck_emit_tag( e, tag, implicit );
- }
- S_FREE( implicit );
-
- /* if still arbitrary, sniff a good block style. */
- if ( force_style == scalar_none ) {
- if ( scan & SCAN_NEWLINE ) {
- force_style = scalar_literal;
- } else {
- force_style = scalar_plain;
- }
- }
-
- if ( e->style == scalar_fold ) {
- favor_style = scalar_fold;
- }
-
- /* Determine block style */
- if ( scan & SCAN_NONPRINT ) {
- force_style = scalar_2quote;
- } else if ( scan & SCAN_WHITEEDGE ) {
- force_style = scalar_2quote;
- } else if ( force_style != scalar_fold && ( scan & SCAN_INDENTED ) ) {
- force_style = scalar_literal;
- } else if ( force_style == scalar_plain && ( scan & SCAN_NEWLINE ) ) {
- force_style = favor_style;
- } else if ( force_style == scalar_plain && parent->status == syck_lvl_iseq && ( scan & SCAN_FLOWSEQ ) ) {
- force_style = scalar_2quote;
- } else if ( force_style == scalar_plain && parent->status == syck_lvl_imap && ( scan & SCAN_FLOWMAP ) ) {
- force_style = scalar_2quote;
- /* } else if ( force_style == scalar_fold && ( ! ( scan & SCAN_WIDE ) ) ) {
- force_style = scalar_literal; */
- } else if ( force_style == scalar_plain && ( scan & SCAN_INDIC_S || scan & SCAN_INDIC_C ) ) {
- if ( scan & SCAN_NEWLINE ) {
- force_style = favor_style;
- } else {
- force_style = scalar_2quote;
- }
- }
-
- if ( force_indent > 0 ) {
- lvl->spaces = parent->spaces + force_indent;
- } else if ( scan & SCAN_DOCSEP ) {
- lvl->spaces = parent->spaces + e->indent;
- }
-
- /* For now, all ambiguous keys are going to be double-quoted */
- if ( ( parent->status == syck_lvl_map || parent->status == syck_lvl_mapx ) && parent->ncount % 2 == 1 ) {
- if ( force_style != scalar_plain ) {
- force_style = scalar_2quote;
- }
- }
-
- /* If the parent is an inline, double quote anything complex */
- if ( parent->status == syck_lvl_imap || parent->status == syck_lvl_iseq ) {
- if ( force_style != scalar_plain && force_style != scalar_1quote ) {
- force_style = scalar_2quote;
- }
- }
-
- /* Fix the ending newlines */
- if ( scan & SCAN_NONL_E ) {
- keep_nl = NL_CHOMP;
- } else if ( scan & SCAN_MANYNL_E ) {
- keep_nl = NL_KEEP;
- }
-
- /* Write the text node */
- switch ( force_style )
- {
- case scalar_1quote:
- syck_emit_1quoted( e, force_width, str, len );
- break;
-
- case scalar_none:
- case scalar_2quote:
- syck_emit_2quoted( e, force_width, str, len );
- break;
-
- case scalar_fold:
- syck_emit_folded( e, force_width, keep_nl, str, len );
- break;
-
- case scalar_literal:
- syck_emit_literal( e, keep_nl, str, len );
- break;
-
- case scalar_plain:
- syck_emitter_write( e, str, len );
- break;
- }
-
- if ( parent->status == syck_lvl_mapx )
- {
- syck_emitter_write( e, "\n", 1 );
- }
-}
-
-void
-syck_emitter_escape( SyckEmitter *e, char *src, long len )
+syck_adjust_anchors( char *key, SyckEmitterNode *n, struct adjust_arg *arg )
{
- int i;
- for( i = 0; i < len; i++ )
+ if ( arg->startpos < n->pos )
{
- if( (src[i] < 0x20) || (0x7E < src[i]) )
- {
- syck_emitter_write( e, "\\", 1 );
- if( '\0' == src[i] )
- syck_emitter_write( e, "0", 1 );
- else
- {
- syck_emitter_write( e, "x", 1 );
- syck_emitter_write( e, (char *)hex_table + ((src[i] & 0xF0) >> 4), 1 );
- syck_emitter_write( e, (char *)hex_table + (src[i] & 0x0F), 1 );
- }
- }
- else
- {
- syck_emitter_write( e, src + i, 1 );
- if( '\\' == src[i] )
- syck_emitter_write( e, "\\", 1 );
- }
- }
-}
-
-/*
- * Outputs a single-quoted block.
- */
-void syck_emit_1quoted( SyckEmitter *e, int width, char *str, long len )
-{
- char do_indent = 0;
- char *mark = str;
- char *start = str;
- char *end = str;
- syck_emitter_write( e, "'", 1 );
- while ( mark < str + len ) {
- if ( do_indent ) {
- syck_emit_indent( e );
- do_indent = 0;
- }
- switch ( *mark ) {
- case '\'': syck_emitter_write( e, "'", 1 ); break;
-
- case '\n':
- end = mark + 1;
- if ( *start != ' ' && *start != '\n' && *end != '\n' && *end != ' ' ) {
- syck_emitter_write( e, "\n\n", 2 );
- } else {
- syck_emitter_write( e, "\n", 1 );
- }
- do_indent = 1;
- start = mark + 1;
- break;
-
- case ' ':
- if ( width > 0 && *start != ' ' && mark - end > width ) {
- do_indent = 1;
- end = mark + 1;
- } else {
- syck_emitter_write( e, " ", 1 );
- }
- break;
-
- default:
- syck_emitter_write( e, mark, 1 );
- break;
- }
- mark++;
- }
- syck_emitter_write( e, "'", 1 );
-}
-
-/*
- * Outputs a double-quoted block.
- */
-void syck_emit_2quoted( SyckEmitter *e, int width, char *str, long len )
-{
- char do_indent = 0;
- char *mark = str;
- char *start = str;
- char *end = str;
- syck_emitter_write( e, "\"", 1 );
- while ( mark < str + len ) {
- if ( do_indent > 0 ) {
- if ( do_indent == 2 ) {
- syck_emitter_write( e, "\\", 1 );
- }
- syck_emit_indent( e );
- do_indent = 0;
- }
- switch ( *mark ) {
-
- /* Escape sequences allowed within double quotes. */
- case '"': syck_emitter_write( e, "\\\"", 2 ); break;
- case '\\': syck_emitter_write( e, "\\\\", 2 ); break;
- case '\0': syck_emitter_write( e, "\\0", 2 ); break;
- case '\a': syck_emitter_write( e, "\\a", 2 ); break;
- case '\b': syck_emitter_write( e, "\\b", 2 ); break;
- case '\f': syck_emitter_write( e, "\\f", 2 ); break;
- case '\r': syck_emitter_write( e, "\\r", 2 ); break;
- case '\t': syck_emitter_write( e, "\\t", 2 ); break;
- case '\v': syck_emitter_write( e, "\\v", 2 ); break;
- case 0x1b: syck_emitter_write( e, "\\e", 2 ); break;
-
- case '\n':
- end = mark + 1;
- syck_emitter_write( e, "\\n", 2 );
- do_indent = 2;
- start = mark + 1;
- if ( start < str + len && ( *start == ' ' || *start == '\n' ) ) {
- do_indent = 0;
- }
- break;
-
- case ' ':
- if ( width > 0 && *start != ' ' && mark - end > width ) {
- do_indent = 1;
- end = mark + 1;
- } else {
- syck_emitter_write( e, " ", 1 );
- }
- break;
-
- default:
- syck_emitter_escape( e, mark, 1 );
- break;
- }
- mark++;
- }
- syck_emitter_write( e, "\"", 1 );
-}
-
-/*
- * Outputs a literal block.
- */
-void syck_emit_literal( SyckEmitter *e, char keep_nl, char *str, long len )
-{
- char *mark = str;
- char *start = str;
- char *end = str;
- syck_emitter_write( e, "|", 1 );
- if ( keep_nl == NL_CHOMP ) {
- syck_emitter_write( e, "-", 1 );
- } else if ( keep_nl == NL_KEEP ) {
- syck_emitter_write( e, "+", 1 );
- }
- syck_emit_indent( e );
- while ( mark < str + len ) {
- if ( *mark == '\n' ) {
- end = mark;
- if ( *start != ' ' && *start != '\n' && *end != '\n' && *end != ' ' ) end += 1;
- syck_emitter_write( e, start, end - start );
- if ( mark + 1 == str + len ) {
- if ( keep_nl != NL_KEEP ) syck_emitter_write( e, "\n", 1 );
- } else {
- syck_emit_indent( e );
- }
- start = mark + 1;
- }
- mark++;
- }
- end = str + len;
- if ( start < end ) {
- syck_emitter_write( e, start, end - start );
- }
-}
-
-/*
- * Outputs a folded block.
- */
-void syck_emit_folded( SyckEmitter *e, int width, char keep_nl, char *str, long len )
-{
- char *mark = str;
- char *start = str;
- char *end = str;
- syck_emitter_write( e, ">", 1 );
- if ( keep_nl == NL_CHOMP ) {
- syck_emitter_write( e, "-", 1 );
- } else if ( keep_nl == NL_KEEP ) {
- syck_emitter_write( e, "+", 1 );
- }
- syck_emit_indent( e );
- if ( width <= 0 ) width = e->best_width;
- while ( mark < str + len ) {
- switch ( *mark ) {
- case '\n':
- syck_emitter_write( e, end, mark - end );
- end = mark + 1;
- if ( *start != ' ' && *start != '\n' && *end != '\n' && *end != ' ' ) {
- syck_emitter_write( e, "\n", 1 );
- }
- if ( mark + 1 == str + len ) {
- if ( keep_nl != NL_KEEP ) syck_emitter_write( e, "\n", 1 );
- } else {
- syck_emit_indent( e );
- }
- start = mark + 1;
- break;
-
- case ' ':
- if ( *start != ' ' ) {
- if ( mark - end > width ) {
- syck_emitter_write( e, end, mark - end );
- syck_emit_indent( e );
- end = mark + 1;
- }
- }
- break;
- }
- mark++;
- }
- if ( end < mark ) {
- syck_emitter_write( e, end, mark - end );
- }
-}
-
-/*
- * Begins emission of a sequence.
- */
-void syck_emit_seq( SyckEmitter *e, char *tag, enum seq_style style )
-{
- SyckLevel *parent = syck_emitter_parent_level( e );
- SyckLevel *lvl = syck_emitter_current_level( e );
- syck_emit_tag( e, tag, "tag:yaml.org,2002:seq" );
- if ( style == seq_inline || ( parent->status == syck_lvl_imap || parent->status == syck_lvl_iseq ) ) {
- syck_emitter_write( e, "[", 1 );
- lvl->status = syck_lvl_iseq;
- } else {
- lvl->status = syck_lvl_seq;
+ n->pos += arg->offset;
}
+ return ST_CONTINUE;
}
/*
- * Begins emission of a mapping.
+ * call on start of an object's marshalling
+ * (handles anchors, returns an alias)
*/
-void syck_emit_map( SyckEmitter *e, char *tag, enum map_style style )
+char *
+syck_emitter_start_obj( SyckEmitter *e, SYMID oid )
{
- SyckLevel *parent = syck_emitter_parent_level( e );
- SyckLevel *lvl = syck_emitter_current_level( e );
- syck_emit_tag( e, tag, "tag:yaml.org,2002:map" );
- if ( style == map_inline || ( parent->status == syck_lvl_imap || parent->status == syck_lvl_iseq ) ) {
- syck_emitter_write( e, "{", 1 );
- lvl->status = syck_lvl_imap;
- } else {
- lvl->status = syck_lvl_map;
- }
-}
+ SyckEmitterNode *n = NULL;
+ char *anchor_name = NULL;
-/*
- * Handles emitting of a collection item (for both
- * sequences and maps)
- */
-void syck_emit_item( SyckEmitter *e, st_data_t n )
-{
- SyckLevel *lvl = syck_emitter_current_level( e );
- switch ( lvl->status )
+ e->level++;
+ if ( oid != e->ignore_id )
{
- case syck_lvl_seq:
+ /*
+ * Look for anchors
+ */
+ if ( e->markers == NULL )
{
- SyckLevel *parent = syck_emitter_parent_level( e );
-
- /* seq-in-map shortcut */
- if ( parent->status == syck_lvl_map && lvl->ncount == 0 ) {
- /* complex key */
- if ( parent->ncount % 2 == 1 ) {
- syck_emitter_write( e, "?", 1 );
- parent->status = syck_lvl_mapx;
- /* shortcut -- the lvl->anctag check should be unneccesary but
- * there is a nasty shift/reduce in the parser on this point and
- * i'm not ready to tickle it. */
- } else if ( lvl->anctag == 0 ) {
- lvl->spaces = parent->spaces;
- }
- }
-
- /* seq-in-seq shortcut */
- else if ( lvl->anctag == 0 && parent->status == syck_lvl_seq && lvl->ncount == 0 ) {
- int spcs = ( lvl->spaces - parent->spaces ) - 2;
- if ( spcs >= 0 ) {
- int i = 0;
- for ( i = 0; i < spcs; i++ ) {
- syck_emitter_write( e, " ", 1 );
- }
- syck_emitter_write( e, "- ", 2 );
- break;
- }
- }
-
- syck_emit_indent( e );
- syck_emitter_write( e, "- ", 2 );
+ e->markers = st_init_numtable();
}
- break;
- case syck_lvl_iseq:
+ /*
+ * Markers table initially marks the string position of the
+ * object. Doesn't yet create an anchor, simply notes the
+ * position.
+ */
+ if ( ! st_lookup( e->markers, (st_data_t)oid, (st_data_t *)&n ) )
{
- if ( lvl->ncount > 0 ) {
- syck_emitter_write( e, ", ", 2 );
- }
+ /*
+ * Store all markers
+ */
+ n = S_ALLOC( SyckEmitterNode );
+ n->is_shortcut = 0;
+ n->indent = e->level * e->indent;
+ n->pos = e->bufpos + ( e->marker - e->buffer );
+ st_insert( e->markers, (st_data_t)oid, (st_data_t)n );
}
- break;
-
- case syck_lvl_map:
+ else
{
- SyckLevel *parent = syck_emitter_parent_level( e );
-
- /* map-in-map */
- if ( parent->status == syck_lvl_map && lvl->ncount == 0 ) {
- /* complex key */
- if ( parent->ncount % 2 == 1 ) {
- syck_emitter_write( e, "?", 1 );
- parent->status = syck_lvl_mapx;
- }
- }
-
- /* map-in-seq shortcut */
- if ( lvl->anctag == 0 && parent->status == syck_lvl_seq && lvl->ncount == 0 ) {
- int spcs = ( lvl->spaces - parent->spaces ) - 2;
- if ( spcs >= 0 ) {
- int i = 0;
- for ( i = 0; i < spcs; i++ ) {
- syck_emitter_write( e, " ", 1 );
- }
- break;
- }
- }
-
- if ( lvl->ncount % 2 == 0 ) {
- syck_emit_indent( e );
- } else {
- syck_emitter_write( e, ": ", 2 );
+ if ( e->anchors == NULL )
+ {
+ e->anchors = st_init_numtable();
}
- }
- break;
-
- case syck_lvl_mapx:
- {
- if ( lvl->ncount % 2 == 0 ) {
- syck_emit_indent( e );
- lvl->status = syck_lvl_map;
- } else {
- int i;
- if ( lvl->spaces > 0 ) {
- char *spcs = S_ALLOC_N( char, lvl->spaces + 1 );
- spcs[lvl->spaces] = '\0';
- for ( i = 0; i < lvl->spaces; i++ ) spcs[i] = ' ';
- syck_emitter_write( e, spcs, lvl->spaces );
- S_FREE( spcs );
+ if ( ! st_lookup( e->anchors, (st_data_t)oid, (st_data_t *)&anchor_name ) )
+ {
+ int idx = 0;
+ /*
+ * Second time hitting this object, let's give it an anchor
+ */
+ idx = e->anchors->num_entries + 1;
+
+ /*
+ * Create the anchor tag
+ */
+ if ( n->pos >= e->bufpos )
+ {
+ int alen;
+ struct adjust_arg *args = S_ALLOC( struct adjust_arg );
+ char *start = e->buffer + ( n->pos - e->bufpos );
+
+ char *anc = ( e->anchor_format == NULL ? DEFAULT_ANCHOR_FORMAT : e->anchor_format );
+ anchor_name = S_ALLOC_N( char, strlen( anc ) + 10 );
+ S_MEMZERO( anchor_name, char, strlen( anc ) + 10 );
+ sprintf( anchor_name, anc, idx );
+
+ /*
+ * Need to flush the buffer some, if there is not room for the anchor.
+ */
+ alen = strlen( anchor_name ) + 2;
+ syck_emitter_flush( e, alen );
+
+ /*
+ * Write the anchor into the buffer
+ */
+ S_MEMMOVE( start + alen, start, char, e->marker - start );
+ S_MEMCPY( start + 1, anchor_name, char, strlen( anchor_name ) );
+ start[0] = '&';
+ start[alen - 1] = ' ';
+ e->marker += alen;
+
+ /*
+ * Cycle through anchors, modify for the size of the anchor.
+ */
+ args->startpos = n->pos;
+ args->offset = alen;
+ st_foreach( e->markers, syck_adjust_anchors, (st_data_t)args );
+ S_FREE( args );
+
+ /*
+ * Insert into anchors table
+ */
+ st_insert( e->anchors, (st_data_t)oid, (st_data_t)anchor_name );
}
- syck_emitter_write( e, ": ", 2 );
}
- }
- break;
- case syck_lvl_imap:
- {
- if ( lvl->ncount > 0 ) {
- if ( lvl->ncount % 2 == 0 ) {
- syck_emitter_write( e, ", ", 2 );
- } else {
- syck_emitter_write( e, ": ", 2 );
- }
- }
}
- break;
-
- default: break;
}
- lvl->ncount++;
- syck_emit( e, n );
+ return anchor_name;
}
/*
- * Closes emission of a collection.
+ * call on completion of an object's marshalling
*/
-void syck_emit_end( SyckEmitter *e )
-{
- SyckLevel *lvl = syck_emitter_current_level( e );
- SyckLevel *parent = syck_emitter_parent_level( e );
- switch ( lvl->status )
- {
- case syck_lvl_seq:
- if ( lvl->ncount == 0 ) {
- syck_emitter_write( e, "[]\n", 3 );
- } else if ( parent->status == syck_lvl_mapx ) {
- syck_emitter_write( e, "\n", 1 );
- }
- break;
-
- case syck_lvl_iseq:
- syck_emitter_write( e, "]\n", 1 );
- break;
-
- case syck_lvl_map:
- if ( lvl->ncount == 0 ) {
- syck_emitter_write( e, "{}\n", 3 );
- } else if ( lvl->ncount % 2 == 1 ) {
- syck_emitter_write( e, ":\n", 1 );
- } else if ( parent->status == syck_lvl_mapx ) {
- syck_emitter_write( e, "\n", 1 );
- }
- break;
-
- case syck_lvl_imap:
- syck_emitter_write( e, "}\n", 1 );
- break;
-
- default: break;
- }
-}
-
-/*
- * Fill markers table with emitter nodes in the
- * soon-to-be-emitted tree.
- */
-SYMID
-syck_emitter_mark_node( SyckEmitter *e, st_data_t n )
+void
+syck_emitter_end_obj( SyckEmitter *e )
{
- SYMID oid = 0;
- char *anchor_name = NULL;
-
- /*
- * Ensure markers table is initialized.
- */
- if ( e->markers == NULL )
- {
- e->markers = st_init_numtable();
- }
-
- /*
- * Markers table initially marks the string position of the
- * object. Doesn't yet create an anchor, simply notes the
- * position.
- */
- if ( ! st_lookup( e->markers, n, (st_data_t *)&oid ) )
- {
- /*
- * Store all markers
- */
- oid = e->markers->num_entries + 1;
- st_insert( e->markers, n, (st_data_t)oid );
- }
- else
- {
- if ( e->anchors == NULL )
- {
- e->anchors = st_init_numtable();
- }
-
- if ( ! st_lookup( e->anchors, (st_data_t)oid, (st_data_t *)&anchor_name ) )
- {
- int idx = 0;
- char *anc = ( e->anchor_format == NULL ? DEFAULT_ANCHOR_FORMAT : e->anchor_format );
-
- /*
- * Second time hitting this object, let's give it an anchor
- */
- idx = e->anchors->num_entries + 1;
- anchor_name = S_ALLOC_N( char, strlen( anc ) + 10 );
- S_MEMZERO( anchor_name, char, strlen( anc ) + 10 );
- sprintf( anchor_name, anc, idx );
-
- /*
- * Insert into anchors table
- */
- st_insert( e->anchors, (st_data_t)oid, (st_data_t)anchor_name );
- }
- }
- return oid;
+ e->level--;
}
diff --git a/ext/syck/gram.c b/ext/syck/gram.c
index 615a594f61..dd65ea1deb 100644
--- a/ext/syck/gram.c
+++ b/ext/syck/gram.c
@@ -1,7 +1,7 @@
-/* A Bison parser, made by GNU Bison 1.875d. */
+/* A Bison parser, made from gram.y, by GNU bison 1.75. */
/* Skeleton parser for Yacc-like parsing with Bison,
- Copyright (C) 1984, 1989, 1990, 2000, 2001, 2002, 2003, 2004 Free Software Foundation, Inc.
+ Copyright (C) 1984, 1989, 1990, 2000, 2001, 2002 Free Software Foundation, Inc.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
@@ -34,13 +34,10 @@
USER NAME SPACE" below. */
/* Identify Bison output. */
-#define YYBISON 1
-
-/* Skeleton name. */
-#define YYSKELETON_NAME "yacc.c"
+#define YYBISON 1
/* Pure parsers. */
-#define YYPURE 1
+#define YYPURE 1
/* Using locations. */
#define YYLSP_NEEDED 0
@@ -98,8 +95,6 @@
#include "syck.h"
-void apply_seq_in_map( SyckParser *parser, SyckNode *n );
-
#define YYPARSE_PARAM parser
#define YYLEX_PARAM parser
@@ -128,49 +123,51 @@ void apply_seq_in_map( SyckParser *parser, SyckNode *n );
# define YYERROR_VERBOSE 0
#endif
-#if ! defined (YYSTYPE) && ! defined (YYSTYPE_IS_DECLARED)
-#line 35 "gram.y"
-typedef union YYSTYPE {
+#ifndef YYSTYPE
+#line 33 "gram.y"
+typedef union {
SYMID nodeId;
SyckNode *nodeData;
char *name;
-} YYSTYPE;
-/* Line 191 of yacc.c. */
-#line 140 "gram.c"
-# define yystype YYSTYPE /* obsolescent; will be withdrawn */
-# define YYSTYPE_IS_DECLARED 1
+} yystype;
+/* Line 193 of /usr/local/share/bison/yacc.c. */
+#line 135 "y.tab.c"
+# define YYSTYPE yystype
# define YYSTYPE_IS_TRIVIAL 1
#endif
-
+#ifndef YYLTYPE
+typedef struct yyltype
+{
+ int first_line;
+ int first_column;
+ int last_line;
+ int last_column;
+} yyltype;
+# define YYLTYPE yyltype
+# define YYLTYPE_IS_TRIVIAL 1
+#endif
/* Copy the second part of user declarations. */
-/* Line 214 of yacc.c. */
-#line 152 "gram.c"
+/* Line 213 of /usr/local/share/bison/yacc.c. */
+#line 156 "y.tab.c"
#if ! defined (yyoverflow) || YYERROR_VERBOSE
-# ifndef YYFREE
-# define YYFREE free
-# endif
-# ifndef YYMALLOC
-# define YYMALLOC malloc
-# endif
-
/* The parser invokes alloca or malloc; define the necessary symbols. */
-# ifdef YYSTACK_USE_ALLOCA
-# if YYSTACK_USE_ALLOCA
-# define YYSTACK_ALLOC alloca
-# endif
+# if YYSTACK_USE_ALLOCA
+# define YYSTACK_ALLOC alloca
# else
-# if defined (alloca) || defined (_ALLOCA_H)
-# define YYSTACK_ALLOC alloca
-# else
-# ifdef __GNUC__
-# define YYSTACK_ALLOC __builtin_alloca
+# ifndef YYSTACK_USE_ALLOCA
+# if defined (alloca) || defined (_ALLOCA_H)
+# define YYSTACK_ALLOC alloca
+# else
+# ifdef __GNUC__
+# define YYSTACK_ALLOC __builtin_alloca
+# endif
# endif
# endif
# endif
@@ -183,36 +180,36 @@ typedef union YYSTYPE {
# include <stdlib.h> /* INFRINGES ON USER NAME SPACE */
# define YYSIZE_T size_t
# endif
-# define YYSTACK_ALLOC YYMALLOC
-# define YYSTACK_FREE YYFREE
+# define YYSTACK_ALLOC malloc
+# define YYSTACK_FREE free
# endif
#endif /* ! defined (yyoverflow) || YYERROR_VERBOSE */
#if (! defined (yyoverflow) \
&& (! defined (__cplusplus) \
- || (defined (YYSTYPE_IS_TRIVIAL) && YYSTYPE_IS_TRIVIAL)))
+ || (YYLTYPE_IS_TRIVIAL && YYSTYPE_IS_TRIVIAL)))
/* A type that is properly aligned for any stack member. */
union yyalloc
{
- short int yyss;
+ short yyss;
YYSTYPE yyvs;
};
/* The size of the maximum gap between one aligned stack and the next. */
-# define YYSTACK_GAP_MAXIMUM (sizeof (union yyalloc) - 1)
+# define YYSTACK_GAP_MAX (sizeof (union yyalloc) - 1)
/* The size of an array large to enough to hold all stacks, each with
N elements. */
# define YYSTACK_BYTES(N) \
- ((N) * (sizeof (short int) + sizeof (YYSTYPE)) \
- + YYSTACK_GAP_MAXIMUM)
+ ((N) * (sizeof (short) + sizeof (YYSTYPE)) \
+ + YYSTACK_GAP_MAX)
/* Copy COUNT objects from FROM to TO. The source and destination do
not overlap. */
# ifndef YYCOPY
-# if defined (__GNUC__) && 1 < __GNUC__
+# if 1 < __GNUC__
# define YYCOPY(To, From, Count) \
__builtin_memcpy (To, From, (Count) * sizeof (*(From)))
# else
@@ -221,7 +218,7 @@ union yyalloc
{ \
register YYSIZE_T yyi; \
for (yyi = 0; yyi < (Count); yyi++) \
- (To)[yyi] = (From)[yyi]; \
+ (To)[yyi] = (From)[yyi]; \
} \
while (0)
# endif
@@ -238,7 +235,7 @@ union yyalloc
YYSIZE_T yynewbytes; \
YYCOPY (&yyptr->Stack, Stack, yysize); \
Stack = &yyptr->Stack; \
- yynewbytes = yystacksize * sizeof (*Stack) + YYSTACK_GAP_MAXIMUM; \
+ yynewbytes = yystacksize * sizeof (*Stack) + YYSTACK_GAP_MAX; \
yyptr += yynewbytes / sizeof (*yyptr); \
} \
while (0)
@@ -248,20 +245,19 @@ union yyalloc
#if defined (__STDC__) || defined (__cplusplus)
typedef signed char yysigned_char;
#else
- typedef short int yysigned_char;
+ typedef short yysigned_char;
#endif
/* YYFINAL -- State number of the termination state. */
-#define YYFINAL 52
-/* YYLAST -- Last index in YYTABLE. */
-#define YYLAST 396
+#define YYFINAL 38
+#define YYLAST 422
/* YYNTOKENS -- Number of terminals. */
#define YYNTOKENS 23
/* YYNNTS -- Number of nonterminals. */
-#define YYNNTS 29
+#define YYNNTS 28
/* YYNRULES -- Number of rules. */
-#define YYNRULES 79
+#define YYNRULES 75
/* YYNRULES -- Number of states. */
#define YYNSTATES 128
@@ -269,8 +265,8 @@ union yyalloc
#define YYUNDEFTOK 2
#define YYMAXUTOK 269
-#define YYTRANSLATE(YYX) \
- ((unsigned int) (YYX) <= YYMAXUTOK ? yytranslate[YYX] : YYUNDEFTOK)
+#define YYTRANSLATE(X) \
+ ((unsigned)(X) <= YYMAXUTOK ? yytranslate[X] : YYUNDEFTOK)
/* YYTRANSLATE[YYLEX] -- Bison symbol number corresponding to YYLEX. */
static const unsigned char yytranslate[] =
@@ -309,55 +305,54 @@ static const unsigned char yytranslate[] =
YYRHS. */
static const unsigned char yyprhs[] =
{
- 0, 0, 3, 5, 8, 9, 11, 13, 15, 18,
- 21, 24, 28, 30, 32, 36, 37, 40, 43, 46,
- 49, 51, 54, 56, 58, 60, 63, 66, 69, 72,
- 75, 77, 79, 81, 85, 87, 89, 91, 93, 95,
- 99, 103, 106, 110, 113, 117, 120, 124, 127, 129,
- 133, 136, 140, 143, 145, 149, 151, 153, 157, 161,
- 165, 168, 172, 175, 179, 182, 184, 188, 190, 194,
- 196, 200, 204, 207, 211, 215, 218, 220, 224, 226
+ 0, 0, 3, 5, 8, 9, 11, 13, 15, 19,
+ 21, 24, 27, 30, 34, 36, 39, 40, 42, 45,
+ 47, 49, 51, 54, 57, 60, 63, 66, 68, 70,
+ 72, 76, 78, 80, 82, 84, 86, 90, 93, 95,
+ 99, 102, 106, 109, 113, 116, 118, 122, 125, 129,
+ 132, 134, 138, 140, 142, 146, 150, 154, 157, 161,
+ 164, 168, 171, 175, 177, 183, 185, 189, 193, 196,
+ 200, 204, 207, 209, 213, 215
};
/* YYRHS -- A `-1'-separated list of the rules' RHS. */
static const yysigned_char yyrhs[] =
{
- 24, 0, -1, 25, -1, 11, 27, -1, -1, 33,
- -1, 26, -1, 34, -1, 5, 26, -1, 6, 26,
- -1, 3, 26, -1, 29, 26, 32, -1, 25, -1,
- 28, -1, 29, 28, 30, -1, -1, 7, 28, -1,
- 5, 28, -1, 6, 28, -1, 3, 28, -1, 12,
- -1, 29, 13, -1, 14, -1, 13, -1, 14, -1,
- 31, 32, -1, 5, 33, -1, 6, 33, -1, 7,
- 33, -1, 3, 33, -1, 4, -1, 8, -1, 9,
- -1, 29, 33, 32, -1, 10, -1, 35, -1, 39,
- -1, 42, -1, 49, -1, 29, 37, 30, -1, 29,
- 38, 30, -1, 15, 27, -1, 5, 31, 38, -1,
- 5, 37, -1, 6, 31, 38, -1, 6, 37, -1,
- 3, 31, 38, -1, 3, 37, -1, 36, -1, 38,
- 31, 36, -1, 38, 31, -1, 17, 40, 18, -1,
- 17, 18, -1, 41, -1, 40, 21, 41, -1, 25,
- -1, 48, -1, 29, 43, 30, -1, 29, 47, 30,
- -1, 5, 31, 47, -1, 5, 43, -1, 6, 31,
- 47, -1, 6, 43, -1, 3, 31, 47, -1, 3,
- 43, -1, 33, -1, 22, 25, 31, -1, 27, -1,
- 44, 16, 45, -1, 46, -1, 47, 31, 36, -1,
- 47, 31, 46, -1, 47, 31, -1, 25, 16, 27,
- -1, 19, 50, 20, -1, 19, 20, -1, 51, -1,
- 50, 21, 51, -1, 25, -1, 48, -1
+ 24, 0, -1, 26, -1, 11, 28, -1, -1, 33,
+ -1, 27, -1, 34, -1, 29, 26, 32, -1, 34,
+ -1, 5, 27, -1, 6, 27, -1, 3, 27, -1,
+ 29, 27, 32, -1, 25, -1, 29, 30, -1, -1,
+ 12, -1, 29, 13, -1, 14, -1, 13, -1, 14,
+ -1, 31, 32, -1, 5, 33, -1, 6, 33, -1,
+ 7, 33, -1, 3, 33, -1, 4, -1, 8, -1,
+ 9, -1, 29, 33, 32, -1, 10, -1, 35, -1,
+ 39, -1, 42, -1, 48, -1, 29, 37, 30, -1,
+ 15, 28, -1, 38, -1, 5, 31, 37, -1, 5,
+ 37, -1, 6, 31, 37, -1, 6, 37, -1, 3,
+ 31, 37, -1, 3, 37, -1, 36, -1, 38, 31,
+ 36, -1, 38, 31, -1, 17, 40, 18, -1, 17,
+ 18, -1, 41, -1, 40, 21, 41, -1, 25, -1,
+ 47, -1, 29, 43, 30, -1, 29, 46, 30, -1,
+ 5, 31, 46, -1, 5, 43, -1, 6, 31, 46,
+ -1, 6, 43, -1, 3, 31, 46, -1, 3, 43,
+ -1, 33, 16, 28, -1, 44, -1, 22, 25, 31,
+ 16, 28, -1, 45, -1, 46, 31, 36, -1, 46,
+ 31, 45, -1, 46, 31, -1, 25, 16, 28, -1,
+ 19, 49, 20, -1, 19, 20, -1, 50, -1, 49,
+ 21, 50, -1, 25, -1, 47, -1
};
/* YYRLINE[YYN] -- source line where rule number YYN was defined. */
-static const unsigned short int yyrline[] =
+static const unsigned short yyrline[] =
{
- 0, 56, 56, 60, 65, 70, 71, 74, 75, 80,
- 85, 94, 100, 101, 104, 109, 113, 121, 126, 131,
- 145, 146, 149, 152, 155, 156, 164, 169, 174, 182,
- 186, 194, 207, 208, 218, 219, 220, 221, 222, 228,
- 232, 238, 244, 249, 254, 259, 264, 268, 274, 278,
- 283, 292, 296, 302, 306, 313, 314, 320, 325, 332,
- 337, 342, 347, 352, 356, 362, 363, 369, 379, 396,
- 397, 409, 417, 426, 434, 438, 444, 445, 454, 461
+ 0, 54, 54, 58, 62, 68, 69, 72, 73, 79,
+ 80, 85, 90, 99, 105, 106, 111, 121, 122, 125,
+ 128, 131, 132, 140, 145, 150, 158, 162, 170, 183,
+ 184, 194, 195, 196, 197, 198, 204, 210, 216, 217,
+ 222, 227, 232, 237, 241, 247, 251, 256, 265, 269,
+ 275, 279, 286, 287, 293, 298, 305, 310, 315, 320,
+ 325, 329, 335, 350, 351, 368, 369, 381, 389, 398,
+ 406, 410, 416, 417, 426, 433
};
#endif
@@ -366,24 +361,24 @@ static const unsigned short int yyrline[] =
First, the terminals, then, starting at YYNTOKENS, nonterminals. */
static const char *const yytname[] =
{
- "$end", "error", "$undefined", "YAML_ANCHOR", "YAML_ALIAS",
- "YAML_TRANSFER", "YAML_TAGURI", "YAML_ITRANSFER", "YAML_WORD",
- "YAML_PLAIN", "YAML_BLOCK", "YAML_DOCSEP", "YAML_IOPEN", "YAML_INDENT",
- "YAML_IEND", "'-'", "':'", "'['", "']'", "'{'", "'}'", "','", "'?'",
- "$accept", "doc", "atom", "ind_rep", "atom_or_empty", "empty",
- "indent_open", "indent_end", "indent_sep", "indent_flex_end", "word_rep",
- "struct_rep", "implicit_seq", "basic_seq", "top_imp_seq",
- "in_implicit_seq", "inline_seq", "in_inline_seq", "inline_seq_atom",
- "implicit_map", "top_imp_map", "complex_key", "complex_value",
- "complex_mapping", "in_implicit_map", "basic_mapping", "inline_map",
- "in_inline_map", "inline_map_atom", 0
+ "$end", "error", "$undefined", "YAML_ANCHOR", "YAML_ALIAS",
+ "YAML_TRANSFER", "YAML_TAGURI", "YAML_ITRANSFER", "YAML_WORD",
+ "YAML_PLAIN", "YAML_BLOCK", "YAML_DOCSEP", "YAML_IOPEN", "YAML_INDENT",
+ "YAML_IEND", "'-'", "':'", "'['", "']'", "'{'", "'}'", "','", "'?'",
+ "$accept", "doc", "atom", "doc_struct_rep", "ind_rep", "atom_or_empty",
+ "indent_open", "indent_end", "indent_sep", "indent_flex_end",
+ "word_rep", "struct_rep", "implicit_seq", "basic_seq", "top_imp_seq",
+ "in_implicit_seq", "inline_seq", "in_inline_seq", "inline_seq_atom",
+ "implicit_map", "top_imp_map", "basic_mapping", "complex_mapping",
+ "in_implicit_map", "basic_mapping2", "inline_map", "in_inline_map",
+ "inline_map_atom", 0
};
#endif
# ifdef YYPRINT
/* YYTOKNUM[YYLEX-NUM] -- Internal token number corresponding to
token YYLEX-NUM. */
-static const unsigned short int yytoknum[] =
+static const unsigned short yytoknum[] =
{
0, 256, 257, 258, 259, 260, 261, 262, 263, 264,
265, 266, 267, 268, 269, 45, 58, 91, 93, 123,
@@ -394,27 +389,27 @@ static const unsigned short int yytoknum[] =
/* YYR1[YYN] -- Symbol number of symbol that rule YYN derives. */
static const unsigned char yyr1[] =
{
- 0, 23, 24, 24, 24, 25, 25, 26, 26, 26,
- 26, 26, 27, 27, 28, 28, 28, 28, 28, 28,
- 29, 29, 30, 31, 32, 32, 33, 33, 33, 33,
- 33, 33, 33, 33, 34, 34, 34, 34, 34, 35,
- 35, 36, 37, 37, 37, 37, 37, 37, 38, 38,
- 38, 39, 39, 40, 40, 41, 41, 42, 42, 43,
- 43, 43, 43, 43, 43, 44, 44, 45, 46, 47,
- 47, 47, 47, 48, 49, 49, 50, 50, 51, 51
+ 0, 23, 24, 24, 24, 25, 25, 26, 26, 27,
+ 27, 27, 27, 27, 28, 28, 28, 29, 29, 30,
+ 31, 32, 32, 33, 33, 33, 33, 33, 33, 33,
+ 33, 34, 34, 34, 34, 34, 35, 36, 37, 37,
+ 37, 37, 37, 37, 37, 38, 38, 38, 39, 39,
+ 40, 40, 41, 41, 42, 42, 43, 43, 43, 43,
+ 43, 43, 44, 45, 45, 46, 46, 46, 46, 47,
+ 48, 48, 49, 49, 50, 50
};
/* YYR2[YYN] -- Number of symbols composing right hand side of rule YYN. */
static const unsigned char yyr2[] =
{
- 0, 2, 1, 2, 0, 1, 1, 1, 2, 2,
- 2, 3, 1, 1, 3, 0, 2, 2, 2, 2,
- 1, 2, 1, 1, 1, 2, 2, 2, 2, 2,
- 1, 1, 1, 3, 1, 1, 1, 1, 1, 3,
- 3, 2, 3, 2, 3, 2, 3, 2, 1, 3,
- 2, 3, 2, 1, 3, 1, 1, 3, 3, 3,
- 2, 3, 2, 3, 2, 1, 3, 1, 3, 1,
- 3, 3, 2, 3, 3, 2, 1, 3, 1, 1
+ 0, 2, 1, 2, 0, 1, 1, 1, 3, 1,
+ 2, 2, 2, 3, 1, 2, 0, 1, 2, 1,
+ 1, 1, 2, 2, 2, 2, 2, 1, 1, 1,
+ 3, 1, 1, 1, 1, 1, 3, 2, 1, 3,
+ 2, 3, 2, 3, 2, 1, 3, 2, 3, 2,
+ 1, 3, 1, 1, 3, 3, 3, 2, 3, 2,
+ 3, 2, 3, 1, 5, 1, 3, 3, 2, 3,
+ 3, 2, 1, 3, 1, 1
};
/* YYDEFACT[STATE-NAME] -- Default rule to reduce with in state
@@ -422,167 +417,173 @@ static const unsigned char yyr2[] =
means the default is an error. */
static const unsigned char yydefact[] =
{
- 4, 0, 30, 0, 0, 0, 31, 32, 34, 15,
- 20, 0, 0, 0, 2, 6, 0, 5, 7, 35,
- 36, 37, 38, 10, 29, 8, 26, 9, 27, 0,
- 0, 0, 0, 28, 15, 15, 15, 15, 12, 3,
- 13, 15, 52, 55, 0, 53, 56, 75, 78, 79,
- 0, 76, 1, 0, 0, 0, 21, 15, 0, 0,
- 65, 48, 0, 0, 0, 0, 69, 0, 0, 19,
- 17, 18, 15, 15, 15, 16, 15, 15, 15, 15,
- 0, 15, 51, 0, 74, 0, 23, 0, 47, 64,
- 0, 43, 60, 0, 45, 62, 41, 0, 24, 0,
- 11, 33, 22, 39, 40, 50, 57, 15, 58, 72,
- 14, 73, 54, 77, 65, 46, 63, 42, 59, 44,
- 61, 66, 25, 49, 67, 68, 70, 71
+ 4, 31, 16, 17, 0, 0, 0, 2, 0, 7,
+ 32, 33, 34, 35, 0, 27, 0, 0, 0, 28,
+ 29, 14, 6, 3, 0, 5, 9, 49, 52, 0,
+ 0, 50, 53, 71, 74, 75, 0, 72, 1, 0,
+ 0, 0, 18, 16, 0, 0, 0, 0, 45, 0,
+ 38, 0, 63, 65, 0, 12, 26, 10, 23, 11,
+ 24, 0, 0, 0, 0, 25, 0, 0, 0, 19,
+ 0, 15, 0, 16, 48, 0, 70, 0, 20, 0,
+ 44, 61, 0, 40, 57, 0, 42, 59, 37, 0,
+ 21, 0, 8, 16, 36, 47, 54, 55, 68, 0,
+ 13, 30, 69, 51, 73, 0, 0, 0, 43, 60,
+ 39, 56, 41, 58, 0, 22, 62, 46, 66, 67,
+ 0, 0, 0, 16, 0, 0, 0, 64
};
/* YYDEFGOTO[NTERM-NUM]. */
static const yysigned_char yydefgoto[] =
{
- -1, 13, 38, 15, 39, 40, 16, 103, 99, 101,
- 17, 18, 19, 61, 62, 63, 20, 44, 45, 21,
- 64, 65, 125, 66, 67, 46, 22, 50, 51
+ -1, 6, 21, 45, 22, 23, 64, 71, 91, 101,
+ 25, 26, 10, 48, 49, 50, 11, 30, 31, 12,
+ 51, 52, 53, 54, 32, 13, 36, 37
};
/* YYPACT[STATE-NUM] -- Index in YYTABLE of the portion describing
STATE-NUM. */
-#define YYPACT_NINF -97
-static const short int yypact[] =
+#define YYPACT_NINF -77
+static const short yypact[] =
{
- 250, 318, -97, 318, 318, 374, -97, -97, -97, 335,
- -97, 267, 232, 7, -97, -97, 192, -97, -97, -97,
- -97, -97, -97, -97, -97, -97, -97, -97, -97, 374,
- 374, 374, 352, -97, 335, 335, 335, 384, -97, -97,
- -97, 212, -97, 10, 0, -97, -97, -97, 10, -97,
- -4, -97, -97, 284, 284, 284, -97, 335, 318, 30,
- 30, -97, -2, 36, -2, 16, -97, 36, 30, -97,
- -97, -97, 384, 384, 384, -97, 363, 301, 301, 301,
- -2, 335, -97, 318, -97, 318, -97, 158, -97, -97,
- 158, -97, -97, 158, -97, -97, -97, 24, -97, 30,
- -97, -97, -97, -97, -97, 26, -97, 335, -97, 158,
- -97, -97, -97, -97, -97, 24, 24, 24, 24, 24,
- 24, -97, -97, -97, -97, -97, -97, -97
+ 163, -77, 356, -77, 339, 304, 7, -77, 224, -77,
+ -77, -77, -77, -77, 356, -77, 356, 356, 410, -77,
+ -77, -77, -77, -77, 204, -77, -77, -77, -15, 244,
+ 24, -77, -77, -77, -15, -77, 30, -77, -77, 373,
+ 373, 373, -77, 356, 356, 41, 224, -3, -77, 18,
+ 21, 18, -77, -77, 46, -77, -77, -77, -77, -77,
+ -77, 410, 410, 410, 399, -77, 322, 322, 322, -77,
+ 41, -77, 14, 356, -77, 356, -77, 356, -77, 264,
+ -77, -77, 264, -77, -77, 264, -77, -77, -77, 21,
+ -77, 41, -77, 356, -77, 33, -77, -77, 284, 41,
+ -77, -77, -77, -77, -77, 386, 386, 386, -77, 21,
+ -77, 21, -77, 21, 22, -77, -77, -77, -77, -77,
+ 20, 20, 20, 356, 91, 91, 91, -77
};
/* YYPGOTO[NTERM-NUM]. */
-static const yysigned_char yypgoto[] =
+static const short yypgoto[] =
{
- -97, -97, 8, 81, -56, 109, 33, -53, 74, -54,
- -1, -97, -97, -96, -31, -32, -97, -97, -44, -97,
- 77, -97, -97, -52, 9, -6, -97, -97, -29
+ -77, -77, 5, 56, 138, -40, 0, 25, 59, -34,
+ 23, 12, -77, -76, 71, -77, -77, -77, -14, -77,
+ 75, -77, -33, -64, 1, -77, -77, -7
};
/* YYTABLE[YYPACT[STATE-NUM]]. What to do in state STATE-NUM. If
positive, shift that token. If negative, reduce the rule which
number is the opposite. If zero, do what YYDEFACT says.
- If YYTABLE_NINF, syntax error. */
+ If YYTABLE_NINF, parse error. */
#define YYTABLE_NINF -1
static const unsigned char yytable[] =
{
- 24, 96, 26, 28, 33, 100, 49, 52, 14, 123,
- 104, 106, 102, 126, 108, 60, 84, 85, 82, 43,
- 48, 83, 88, 91, 94, 111, 81, 110, 24, 26,
- 28, 68, 107, 24, 26, 28, 33, 86, 32, 112,
- 60, 57, 41, 86, 98, 122, 88, 91, 94, 86,
- 102, 124, 24, 26, 28, 115, 113, 127, 117, 0,
- 0, 119, 32, 32, 32, 32, 97, 41, 41, 41,
- 76, 24, 26, 28, 41, 68, 24, 26, 28, 49,
- 0, 0, 23, 0, 25, 27, 114, 0, 0, 114,
- 41, 43, 114, 48, 0, 0, 116, 59, 0, 118,
- 0, 0, 120, 0, 0, 76, 76, 76, 114, 76,
- 41, 41, 41, 0, 41, 23, 25, 27, 0, 0,
- 32, 0, 59, 32, 0, 0, 32, 87, 90, 93,
- 89, 92, 95, 0, 23, 25, 27, 105, 0, 0,
- 41, 109, 32, 69, 70, 71, 75, 0, 0, 0,
- 80, 87, 90, 93, 89, 92, 95, 0, 23, 25,
- 27, 29, 2, 30, 31, 5, 6, 7, 0, 0,
- 10, 121, 0, 57, 0, 0, 0, 0, 0, 0,
- 58, 69, 70, 71, 0, 80, 69, 70, 71, 105,
- 109, 105, 109, 105, 109, 53, 2, 54, 55, 5,
- 6, 7, 8, 0, 10, 56, 0, 57, 0, 11,
- 0, 12, 0, 0, 58, 77, 2, 78, 79, 37,
- 6, 7, 8, 0, 10, 56, 0, 57, 0, 11,
- 0, 12, 0, 0, 58, 1, 2, 3, 4, 5,
- 6, 7, 8, 0, 10, 0, 0, 0, 0, 11,
- 0, 12, 47, 1, 2, 3, 4, 5, 6, 7,
- 8, 9, 10, 0, 0, 0, 0, 11, 0, 12,
- 1, 2, 3, 4, 5, 6, 7, 8, 0, 10,
- 0, 0, 0, 0, 11, 42, 12, 53, 2, 54,
- 55, 5, 6, 7, 8, 0, 10, 86, 0, 0,
- 0, 11, 0, 12, 77, 2, 78, 79, 37, 6,
- 7, 8, 0, 10, 86, 0, 0, 0, 11, 0,
- 12, 1, 2, 3, 4, 5, 6, 7, 8, 0,
- 10, 0, 0, 0, 0, 11, 0, 12, 34, 2,
- 35, 36, 37, 6, 7, 8, 0, 10, 0, 0,
- 0, 0, 11, 0, 12, 29, 2, 30, 31, 5,
- 6, 7, 0, 0, 10, 56, 72, 2, 73, 74,
- 37, 6, 7, 0, 0, 10, 56, 29, 2, 30,
- 31, 5, 6, 7, 0, 0, 10, 72, 2, 73,
- 74, 37, 6, 7, 0, 0, 10
+ 8, 73, 24, 88, 29, 29, 35, 38, 46, 28,
+ 34, 92, 9, 93, 29, 109, 29, 29, 111, 117,
+ 9, 113, 118, 124, 29, 125, 126, 78, 90, 29,
+ 93, 47, 69, 102, 78, 43, 100, 56, 123, 58,
+ 60, 65, 74, 24, 29, 75, 46, 72, 43, 89,
+ 76, 77, 72, 116, 78, 90, 7, 115, 9, 78,
+ 69, 103, 56, 58, 60, 119, 29, 29, 29, 72,
+ 104, 0, 0, 24, 94, 29, 96, 29, 35, 97,
+ 28, 0, 34, 127, 56, 58, 60, 99, 0, 56,
+ 58, 60, 0, 24, 124, 0, 125, 126, 79, 82,
+ 85, 0, 47, 0, 78, 47, 43, 0, 47, 95,
+ 80, 83, 86, 98, 81, 84, 87, 0, 0, 0,
+ 0, 47, 0, 24, 0, 79, 82, 85, 56, 58,
+ 60, 0, 0, 0, 0, 0, 0, 80, 83, 86,
+ 0, 81, 84, 87, 0, 0, 0, 0, 114, 0,
+ 108, 0, 55, 110, 57, 59, 112, 0, 0, 0,
+ 0, 0, 70, 0, 120, 121, 122, 70, 98, 0,
+ 98, 0, 98, 1, 2, 3, 80, 83, 86, 0,
+ 4, 0, 5, 120, 121, 122, 0, 0, 0, 0,
+ 0, 108, 110, 112, 0, 80, 83, 86, 0, 0,
+ 0, 0, 0, 0, 55, 57, 59, 66, 15, 67,
+ 68, 18, 19, 20, 1, 0, 3, 42, 69, 43,
+ 0, 4, 0, 5, 0, 0, 44, 39, 15, 40,
+ 41, 18, 19, 20, 1, 0, 3, 42, 0, 43,
+ 0, 4, 0, 5, 0, 0, 44, 66, 15, 67,
+ 68, 18, 19, 20, 1, 0, 3, 42, 0, 43,
+ 0, 4, 0, 5, 0, 0, 44, 105, 15, 106,
+ 107, 18, 19, 20, 0, 0, 3, 0, 0, 43,
+ 0, 0, 0, 0, 0, 0, 44, 61, 15, 62,
+ 63, 18, 19, 20, 0, 0, 3, 0, 0, 43,
+ 0, 0, 0, 0, 0, 0, 44, 14, 15, 16,
+ 17, 18, 19, 20, 1, 0, 3, 0, 0, 0,
+ 0, 4, 0, 5, 33, 66, 15, 67, 68, 18,
+ 19, 20, 1, 0, 3, 78, 0, 43, 0, 4,
+ 0, 5, 14, 15, 16, 17, 18, 19, 20, 1,
+ 0, 3, 0, 0, 0, 0, 4, 27, 5, 14,
+ 15, 16, 17, 18, 19, 20, 1, 0, 3, 0,
+ 0, 0, 0, 4, 0, 5, 39, 15, 40, 41,
+ 18, 19, 20, 0, 0, 3, 78, 0, 43, 105,
+ 15, 106, 107, 18, 19, 20, 0, 0, 3, 78,
+ 0, 43, 61, 15, 62, 63, 18, 19, 20, 0,
+ 0, 3, 42, 61, 15, 62, 63, 18, 19, 20,
+ 0, 0, 3
};
static const yysigned_char yycheck[] =
{
- 1, 57, 3, 4, 5, 59, 12, 0, 0, 105,
- 63, 64, 14, 109, 67, 16, 20, 21, 18, 11,
- 12, 21, 53, 54, 55, 81, 16, 80, 29, 30,
- 31, 32, 16, 34, 35, 36, 37, 13, 5, 83,
- 41, 15, 9, 13, 14, 99, 77, 78, 79, 13,
- 14, 107, 53, 54, 55, 87, 85, 109, 90, -1,
- -1, 93, 29, 30, 31, 32, 58, 34, 35, 36,
- 37, 72, 73, 74, 41, 76, 77, 78, 79, 85,
- -1, -1, 1, -1, 3, 4, 87, -1, -1, 90,
- 57, 83, 93, 85, -1, -1, 87, 16, -1, 90,
- -1, -1, 93, -1, -1, 72, 73, 74, 109, 76,
- 77, 78, 79, -1, 81, 34, 35, 36, -1, -1,
- 87, -1, 41, 90, -1, -1, 93, 53, 54, 55,
- 53, 54, 55, -1, 53, 54, 55, 63, -1, -1,
- 107, 67, 109, 34, 35, 36, 37, -1, -1, -1,
- 41, 77, 78, 79, 77, 78, 79, -1, 77, 78,
- 79, 3, 4, 5, 6, 7, 8, 9, -1, -1,
- 12, 97, -1, 15, -1, -1, -1, -1, -1, -1,
- 22, 72, 73, 74, -1, 76, 77, 78, 79, 115,
- 116, 117, 118, 119, 120, 3, 4, 5, 6, 7,
- 8, 9, 10, -1, 12, 13, -1, 15, -1, 17,
- -1, 19, -1, -1, 22, 3, 4, 5, 6, 7,
+ 0, 16, 2, 43, 4, 5, 5, 0, 8, 4,
+ 5, 45, 0, 16, 14, 79, 16, 17, 82, 95,
+ 8, 85, 98, 3, 24, 5, 6, 13, 14, 29,
+ 16, 8, 14, 73, 13, 15, 70, 14, 16, 16,
+ 17, 18, 18, 43, 44, 21, 46, 24, 15, 44,
+ 20, 21, 29, 93, 13, 14, 0, 91, 46, 13,
+ 14, 75, 39, 40, 41, 98, 66, 67, 68, 46,
+ 77, -1, -1, 73, 49, 75, 51, 77, 77, 54,
+ 75, -1, 77, 123, 61, 62, 63, 64, -1, 66,
+ 67, 68, -1, 93, 3, -1, 5, 6, 39, 40,
+ 41, -1, 79, -1, 13, 82, 15, -1, 85, 50,
+ 39, 40, 41, 54, 39, 40, 41, -1, -1, -1,
+ -1, 98, -1, 123, -1, 66, 67, 68, 105, 106,
+ 107, -1, -1, -1, -1, -1, -1, 66, 67, 68,
+ -1, 66, 67, 68, -1, -1, -1, -1, 89, -1,
+ 79, -1, 14, 82, 16, 17, 85, -1, -1, -1,
+ -1, -1, 24, -1, 105, 106, 107, 29, 109, -1,
+ 111, -1, 113, 10, 11, 12, 105, 106, 107, -1,
+ 17, -1, 19, 124, 125, 126, -1, -1, -1, -1,
+ -1, 120, 121, 122, -1, 124, 125, 126, -1, -1,
+ -1, -1, -1, -1, 66, 67, 68, 3, 4, 5,
+ 6, 7, 8, 9, 10, -1, 12, 13, 14, 15,
+ -1, 17, -1, 19, -1, -1, 22, 3, 4, 5,
+ 6, 7, 8, 9, 10, -1, 12, 13, -1, 15,
+ -1, 17, -1, 19, -1, -1, 22, 3, 4, 5,
+ 6, 7, 8, 9, 10, -1, 12, 13, -1, 15,
+ -1, 17, -1, 19, -1, -1, 22, 3, 4, 5,
+ 6, 7, 8, 9, -1, -1, 12, -1, -1, 15,
+ -1, -1, -1, -1, -1, -1, 22, 3, 4, 5,
+ 6, 7, 8, 9, -1, -1, 12, -1, -1, 15,
+ -1, -1, -1, -1, -1, -1, 22, 3, 4, 5,
+ 6, 7, 8, 9, 10, -1, 12, -1, -1, -1,
+ -1, 17, -1, 19, 20, 3, 4, 5, 6, 7,
8, 9, 10, -1, 12, 13, -1, 15, -1, 17,
- -1, 19, -1, -1, 22, 3, 4, 5, 6, 7,
- 8, 9, 10, -1, 12, -1, -1, -1, -1, 17,
- -1, 19, 20, 3, 4, 5, 6, 7, 8, 9,
- 10, 11, 12, -1, -1, -1, -1, 17, -1, 19,
- 3, 4, 5, 6, 7, 8, 9, 10, -1, 12,
- -1, -1, -1, -1, 17, 18, 19, 3, 4, 5,
- 6, 7, 8, 9, 10, -1, 12, 13, -1, -1,
- -1, 17, -1, 19, 3, 4, 5, 6, 7, 8,
- 9, 10, -1, 12, 13, -1, -1, -1, 17, -1,
- 19, 3, 4, 5, 6, 7, 8, 9, 10, -1,
- 12, -1, -1, -1, -1, 17, -1, 19, 3, 4,
- 5, 6, 7, 8, 9, 10, -1, 12, -1, -1,
- -1, -1, 17, -1, 19, 3, 4, 5, 6, 7,
- 8, 9, -1, -1, 12, 13, 3, 4, 5, 6,
- 7, 8, 9, -1, -1, 12, 13, 3, 4, 5,
- 6, 7, 8, 9, -1, -1, 12, 3, 4, 5,
- 6, 7, 8, 9, -1, -1, 12
+ -1, 19, 3, 4, 5, 6, 7, 8, 9, 10,
+ -1, 12, -1, -1, -1, -1, 17, 18, 19, 3,
+ 4, 5, 6, 7, 8, 9, 10, -1, 12, -1,
+ -1, -1, -1, 17, -1, 19, 3, 4, 5, 6,
+ 7, 8, 9, -1, -1, 12, 13, -1, 15, 3,
+ 4, 5, 6, 7, 8, 9, -1, -1, 12, 13,
+ -1, 15, 3, 4, 5, 6, 7, 8, 9, -1,
+ -1, 12, 13, 3, 4, 5, 6, 7, 8, 9,
+ -1, -1, 12
};
/* YYSTOS[STATE-NUM] -- The (internal number of the) accessing
symbol of state STATE-NUM. */
static const unsigned char yystos[] =
{
- 0, 3, 4, 5, 6, 7, 8, 9, 10, 11,
- 12, 17, 19, 24, 25, 26, 29, 33, 34, 35,
- 39, 42, 49, 26, 33, 26, 33, 26, 33, 3,
- 5, 6, 29, 33, 3, 5, 6, 7, 25, 27,
- 28, 29, 18, 25, 40, 41, 48, 20, 25, 48,
- 50, 51, 0, 3, 5, 6, 13, 15, 22, 26,
- 33, 36, 37, 38, 43, 44, 46, 47, 33, 28,
- 28, 28, 3, 5, 6, 28, 29, 3, 5, 6,
- 28, 16, 18, 21, 20, 21, 13, 31, 37, 43,
- 31, 37, 43, 31, 37, 43, 27, 25, 14, 31,
- 32, 32, 14, 30, 30, 31, 30, 16, 30, 31,
- 30, 27, 41, 51, 33, 38, 47, 38, 47, 38,
- 47, 31, 32, 36, 27, 45, 36, 46
+ 0, 10, 11, 12, 17, 19, 24, 26, 29, 34,
+ 35, 39, 42, 48, 3, 4, 5, 6, 7, 8,
+ 9, 25, 27, 28, 29, 33, 34, 18, 25, 29,
+ 40, 41, 47, 20, 25, 47, 49, 50, 0, 3,
+ 5, 6, 13, 15, 22, 26, 29, 33, 36, 37,
+ 38, 43, 44, 45, 46, 27, 33, 27, 33, 27,
+ 33, 3, 5, 6, 29, 33, 3, 5, 6, 14,
+ 27, 30, 33, 16, 18, 21, 20, 21, 13, 31,
+ 37, 43, 31, 37, 43, 31, 37, 43, 28, 25,
+ 14, 31, 32, 16, 30, 31, 30, 30, 31, 33,
+ 32, 32, 28, 41, 50, 3, 5, 6, 37, 46,
+ 37, 46, 37, 46, 31, 32, 28, 36, 36, 45,
+ 31, 31, 31, 16, 3, 5, 6, 28
};
#if ! defined (YYSIZE_T) && defined (__SIZE_TYPE__)
@@ -603,13 +604,12 @@ static const unsigned char yystos[] =
#define yyerrok (yyerrstatus = 0)
#define yyclearin (yychar = YYEMPTY)
-#define YYEMPTY (-2)
+#define YYEMPTY -2
#define YYEOF 0
#define YYACCEPT goto yyacceptlab
#define YYABORT goto yyabortlab
-#define YYERROR goto yyerrorlab
-
+#define YYERROR goto yyerrlab1
/* Like YYERROR except do call yyerror. This remains here temporarily
to ease the transition to the new meaning of YYERROR, for GCC.
@@ -625,13 +625,13 @@ do \
{ \
yychar = (Token); \
yylval = (Value); \
- yytoken = YYTRANSLATE (yychar); \
+ yychar1 = YYTRANSLATE (yychar); \
YYPOPSTACK; \
goto yybackup; \
} \
else \
{ \
- yyerror ("syntax error: cannot back up");\
+ yyerror ("syntax error: cannot back up"); \
YYERROR; \
} \
while (0)
@@ -643,19 +643,19 @@ while (0)
are run). */
#ifndef YYLLOC_DEFAULT
-# define YYLLOC_DEFAULT(Current, Rhs, N) \
- ((Current).first_line = (Rhs)[1].first_line, \
- (Current).first_column = (Rhs)[1].first_column, \
- (Current).last_line = (Rhs)[N].last_line, \
- (Current).last_column = (Rhs)[N].last_column)
+# define YYLLOC_DEFAULT(Current, Rhs, N) \
+ Current.first_line = Rhs[1].first_line; \
+ Current.first_column = Rhs[1].first_column; \
+ Current.last_line = Rhs[N].last_line; \
+ Current.last_column = Rhs[N].last_column;
#endif
/* YYLEX -- calling `yylex' with the right arguments. */
#ifdef YYLEX_PARAM
-# define YYLEX yylex (&yylval, YYLEX_PARAM)
+# define YYLEX yylex (&yylval, YYLEX_PARAM)
#else
-# define YYLEX yylex (&yylval)
+# define YYLEX yylex (&yylval)
#endif
/* Enable debugging if requested. */
@@ -671,93 +671,19 @@ do { \
if (yydebug) \
YYFPRINTF Args; \
} while (0)
-
# define YYDSYMPRINT(Args) \
do { \
if (yydebug) \
yysymprint Args; \
} while (0)
-
-# define YYDSYMPRINTF(Title, Token, Value, Location) \
-do { \
- if (yydebug) \
- { \
- YYFPRINTF (stderr, "%s ", Title); \
- yysymprint (stderr, \
- Token, Value); \
- YYFPRINTF (stderr, "\n"); \
- } \
-} while (0)
-
-/*------------------------------------------------------------------.
-| yy_stack_print -- Print the state stack from its BOTTOM up to its |
-| TOP (included). |
-`------------------------------------------------------------------*/
-
-#if defined (__STDC__) || defined (__cplusplus)
-static void
-yy_stack_print (short int *bottom, short int *top)
-#else
-static void
-yy_stack_print (bottom, top)
- short int *bottom;
- short int *top;
-#endif
-{
- YYFPRINTF (stderr, "Stack now");
- for (/* Nothing. */; bottom <= top; ++bottom)
- YYFPRINTF (stderr, " %d", *bottom);
- YYFPRINTF (stderr, "\n");
-}
-
-# define YY_STACK_PRINT(Bottom, Top) \
-do { \
- if (yydebug) \
- yy_stack_print ((Bottom), (Top)); \
-} while (0)
-
-
-/*------------------------------------------------.
-| Report that the YYRULE is going to be reduced. |
-`------------------------------------------------*/
-
-#if defined (__STDC__) || defined (__cplusplus)
-static void
-yy_reduce_print (int yyrule)
-#else
-static void
-yy_reduce_print (yyrule)
- int yyrule;
-#endif
-{
- int yyi;
- unsigned int yylno = yyrline[yyrule];
- YYFPRINTF (stderr, "Reducing stack by rule %d (line %u), ",
- yyrule - 1, yylno);
- /* Print the symbols being reduced, and their result. */
- for (yyi = yyprhs[yyrule]; 0 <= yyrhs[yyi]; yyi++)
- YYFPRINTF (stderr, "%s ", yytname [yyrhs[yyi]]);
- YYFPRINTF (stderr, "-> %s\n", yytname [yyr1[yyrule]]);
-}
-
-# define YY_REDUCE_PRINT(Rule) \
-do { \
- if (yydebug) \
- yy_reduce_print (Rule); \
-} while (0)
-
/* Nonzero means print parse trace. It is left uninitialized so that
multiple parsers can coexist. */
int yydebug;
#else /* !YYDEBUG */
# define YYDPRINTF(Args)
# define YYDSYMPRINT(Args)
-# define YYDSYMPRINTF(Title, Token, Value, Location)
-# define YY_STACK_PRINT(Bottom, Top)
-# define YY_REDUCE_PRINT(Rule)
#endif /* !YYDEBUG */
-
/* YYINITDEPTH -- initial size of the parser's stacks. */
#ifndef YYINITDEPTH
# define YYINITDEPTH 200
@@ -770,7 +696,7 @@ int yydebug;
SIZE_MAX < YYSTACK_BYTES (YYMAXDEPTH)
evaluated with infinite-precision integer arithmetic. */
-#if defined (YYMAXDEPTH) && YYMAXDEPTH == 0
+#if YYMAXDEPTH == 0
# undef YYMAXDEPTH
#endif
@@ -836,111 +762,102 @@ yystpcpy (yydest, yysrc)
#if YYDEBUG
-/*--------------------------------.
-| Print this symbol on YYOUTPUT. |
-`--------------------------------*/
+/*-----------------------------.
+| Print this symbol on YYOUT. |
+`-----------------------------*/
-#if defined (__STDC__) || defined (__cplusplus)
static void
-yysymprint (FILE *yyoutput, int yytype, YYSTYPE *yyvaluep)
+#if defined (__STDC__) || defined (__cplusplus)
+yysymprint (FILE* yyout, int yytype, YYSTYPE yyvalue)
#else
-static void
-yysymprint (yyoutput, yytype, yyvaluep)
- FILE *yyoutput;
+yysymprint (yyout, yytype, yyvalue)
+ FILE* yyout;
int yytype;
- YYSTYPE *yyvaluep;
+ YYSTYPE yyvalue;
#endif
{
/* Pacify ``unused variable'' warnings. */
- (void) yyvaluep;
+ (void) yyvalue;
if (yytype < YYNTOKENS)
{
- YYFPRINTF (yyoutput, "token %s (", yytname[yytype]);
+ YYFPRINTF (yyout, "token %s (", yytname[yytype]);
# ifdef YYPRINT
- YYPRINT (yyoutput, yytoknum[yytype], *yyvaluep);
+ YYPRINT (yyout, yytoknum[yytype], yyvalue);
# endif
}
else
- YYFPRINTF (yyoutput, "nterm %s (", yytname[yytype]);
+ YYFPRINTF (yyout, "nterm %s (", yytname[yytype]);
switch (yytype)
{
default:
break;
}
- YYFPRINTF (yyoutput, ")");
+ YYFPRINTF (yyout, ")");
}
+#endif /* YYDEBUG. */
+
-#endif /* ! YYDEBUG */
/*-----------------------------------------------.
| Release the memory associated to this symbol. |
`-----------------------------------------------*/
-#if defined (__STDC__) || defined (__cplusplus)
static void
-yydestruct (int yytype, YYSTYPE *yyvaluep)
+#if defined (__STDC__) || defined (__cplusplus)
+yydestruct (int yytype, YYSTYPE yyvalue)
#else
-static void
-yydestruct (yytype, yyvaluep)
+yydestruct (yytype, yyvalue)
int yytype;
- YYSTYPE *yyvaluep;
+ YYSTYPE yyvalue;
#endif
{
/* Pacify ``unused variable'' warnings. */
- (void) yyvaluep;
+ (void) yyvalue;
switch (yytype)
{
-
default:
break;
}
}
+
-/* Prevent warnings from -Wmissing-prototypes. */
+/* The user can define YYPARSE_PARAM as the name of an argument to be passed
+ into yyparse. The argument should have type void *.
+ It should actually point to an object.
+ Grammar actions can access the variable by casting it
+ to the proper pointer type. */
#ifdef YYPARSE_PARAM
# if defined (__STDC__) || defined (__cplusplus)
-int yyparse (void *YYPARSE_PARAM);
+# define YYPARSE_PARAM_ARG void *YYPARSE_PARAM
+# define YYPARSE_PARAM_DECL
# else
-int yyparse ();
+# define YYPARSE_PARAM_ARG YYPARSE_PARAM
+# define YYPARSE_PARAM_DECL void *YYPARSE_PARAM;
# endif
-#else /* ! YYPARSE_PARAM */
-#if defined (__STDC__) || defined (__cplusplus)
+#else /* !YYPARSE_PARAM */
+# define YYPARSE_PARAM_ARG
+# define YYPARSE_PARAM_DECL
+#endif /* !YYPARSE_PARAM */
+
+/* Prevent warning if -Wstrict-prototypes. */
+#ifdef __GNUC__
+# ifdef YYPARSE_PARAM
+int yyparse (void *);
+# else
int yyparse (void);
-#else
-int yyparse ();
+# endif
#endif
-#endif /* ! YYPARSE_PARAM */
-
-
-/*----------.
-| yyparse. |
-`----------*/
-
-#ifdef YYPARSE_PARAM
-# if defined (__STDC__) || defined (__cplusplus)
-int yyparse (void *YYPARSE_PARAM)
-# else
-int yyparse (YYPARSE_PARAM)
- void *YYPARSE_PARAM;
-# endif
-#else /* ! YYPARSE_PARAM */
-#if defined (__STDC__) || defined (__cplusplus)
int
-yyparse (void)
-#else
-int
-yyparse ()
-
-#endif
-#endif
+yyparse (YYPARSE_PARAM_ARG)
+ YYPARSE_PARAM_DECL
{
/* The lookahead symbol. */
int yychar;
@@ -948,7 +865,7 @@ int yychar;
/* The semantic value of the lookahead symbol. */
YYSTYPE yylval;
-/* Number of syntax errors so far. */
+/* Number of parse errors so far. */
int yynerrs;
register int yystate;
@@ -957,7 +874,7 @@ int yynerrs;
/* Number of tokens to shift before error messages enabled. */
int yyerrstatus;
/* Lookahead token as an internal (translated) token number. */
- int yytoken = 0;
+ int yychar1 = 0;
/* Three stacks and their tools:
`yyss': related to states,
@@ -968,9 +885,9 @@ int yynerrs;
to reallocate them elsewhere. */
/* The state stack. */
- short int yyssa[YYINITDEPTH];
- short int *yyss = yyssa;
- register short int *yyssp;
+ short yyssa[YYINITDEPTH];
+ short *yyss = yyssa;
+ register short *yyssp;
/* The semantic value stack. */
YYSTYPE yyvsa[YYINITDEPTH];
@@ -1007,7 +924,6 @@ int yynerrs;
yyssp = yyss;
yyvsp = yyvs;
-
goto yysetstate;
/*------------------------------------------------------------.
@@ -1022,7 +938,7 @@ int yynerrs;
yysetstate:
*yyssp = yystate;
- if (yyss + yystacksize - 1 <= yyssp)
+ if (yyssp >= yyss + yystacksize - 1)
{
/* Get the current used size of the three stacks, in elements. */
YYSIZE_T yysize = yyssp - yyss + 1;
@@ -1033,7 +949,7 @@ int yynerrs;
these so that the &'s don't force the real ones into
memory. */
YYSTYPE *yyvs1 = yyvs;
- short int *yyss1 = yyss;
+ short *yyss1 = yyss;
/* Each stack pointer address is followed by the size of the
@@ -1054,14 +970,14 @@ int yynerrs;
goto yyoverflowlab;
# else
/* Extend the stack our own way. */
- if (YYMAXDEPTH <= yystacksize)
+ if (yystacksize >= YYMAXDEPTH)
goto yyoverflowlab;
yystacksize *= 2;
- if (YYMAXDEPTH < yystacksize)
+ if (yystacksize > YYMAXDEPTH)
yystacksize = YYMAXDEPTH;
{
- short int *yyss1 = yyss;
+ short *yyss1 = yyss;
union yyalloc *yyptr =
(union yyalloc *) YYSTACK_ALLOC (YYSTACK_BYTES (yystacksize));
if (! yyptr)
@@ -1083,7 +999,7 @@ int yynerrs;
YYDPRINTF ((stderr, "Stack size increased to %lu\n",
(unsigned long int) yystacksize));
- if (yyss + yystacksize - 1 <= yyssp)
+ if (yyssp >= yyss + yystacksize - 1)
YYABORT;
}
@@ -1108,28 +1024,39 @@ yybackup:
/* Not known => get a lookahead token if don't already have one. */
- /* YYCHAR is either YYEMPTY or YYEOF or a valid lookahead symbol. */
+ /* yychar is either YYEMPTY or YYEOF
+ or a valid token in external form. */
+
if (yychar == YYEMPTY)
{
YYDPRINTF ((stderr, "Reading a token: "));
yychar = YYLEX;
}
- if (yychar <= YYEOF)
+ /* Convert token to internal form (in yychar1) for indexing tables with. */
+
+ if (yychar <= 0) /* This means end of input. */
{
- yychar = yytoken = YYEOF;
+ yychar1 = 0;
+ yychar = YYEOF; /* Don't call YYLEX any more. */
+
YYDPRINTF ((stderr, "Now at end of input.\n"));
}
else
{
- yytoken = YYTRANSLATE (yychar);
- YYDSYMPRINTF ("Next token is", yytoken, &yylval, &yylloc);
+ yychar1 = YYTRANSLATE (yychar);
+
+ /* We have to keep this `#if YYDEBUG', since we use variables
+ which are defined only if `YYDEBUG' is set. */
+ YYDPRINTF ((stderr, "Next token is "));
+ YYDSYMPRINT ((stderr, yychar1, yylval));
+ YYDPRINTF ((stderr, "\n"));
}
- /* If the proper action on seeing token YYTOKEN is to reduce or to
+ /* If the proper action on seeing token YYCHAR1 is to reduce or to
detect an error, take that action. */
- yyn += yytoken;
- if (yyn < 0 || YYLAST < yyn || yycheck[yyn] != yytoken)
+ yyn += yychar1;
+ if (yyn < 0 || YYLAST < yyn || yycheck[yyn] != yychar1)
goto yydefault;
yyn = yytable[yyn];
if (yyn <= 0)
@@ -1144,7 +1071,8 @@ yybackup:
YYACCEPT;
/* Shift the lookahead token. */
- YYDPRINTF ((stderr, "Shifting token %s, ", yytname[yytoken]));
+ YYDPRINTF ((stderr, "Shifting token %d (%s), ",
+ yychar, yytname[yychar1]));
/* Discard the token being shifted unless it is eof. */
if (yychar != YYEOF)
@@ -1190,48 +1118,71 @@ yyreduce:
yyval = yyvsp[1-yylen];
- YY_REDUCE_PRINT (yyn);
+
+#if YYDEBUG
+ /* We have to keep this `#if YYDEBUG', since we use variables which
+ are defined only if `YYDEBUG' is set. */
+ if (yydebug)
+ {
+ int yyi;
+
+ YYFPRINTF (stderr, "Reducing via rule %d (line %d), ",
+ yyn - 1, yyrline[yyn]);
+
+ /* Print the symbols being reduced, and their result. */
+ for (yyi = yyprhs[yyn]; yyrhs[yyi] >= 0; yyi++)
+ YYFPRINTF (stderr, "%s ", yytname[yyrhs[yyi]]);
+ YYFPRINTF (stderr, " -> %s\n", yytname[yyr1[yyn]]);
+ }
+#endif
switch (yyn)
{
case 2:
-#line 57 "gram.y"
+#line 55 "gram.y"
{
((SyckParser *)parser)->root = syck_hdlr_add_node( (SyckParser *)parser, yyvsp[0].nodeData );
}
break;
case 3:
-#line 61 "gram.y"
+#line 59 "gram.y"
{
((SyckParser *)parser)->root = syck_hdlr_add_node( (SyckParser *)parser, yyvsp[0].nodeData );
}
break;
case 4:
-#line 65 "gram.y"
+#line 63 "gram.y"
{
((SyckParser *)parser)->eof = 1;
}
break;
case 8:
-#line 76 "gram.y"
+#line 74 "gram.y"
+ {
+ yyval.nodeData = yyvsp[-1].nodeData;
+ }
+ break;
+
+ case 10:
+#line 81 "gram.y"
{
syck_add_transfer( yyvsp[-1].name, yyvsp[0].nodeData, ((SyckParser *)parser)->taguri_expansion );
yyval.nodeData = yyvsp[0].nodeData;
}
break;
- case 9:
-#line 81 "gram.y"
+ case 11:
+#line 86 "gram.y"
{
syck_add_transfer( yyvsp[-1].name, yyvsp[0].nodeData, 0 );
yyval.nodeData = yyvsp[0].nodeData;
}
break;
- case 10:
-#line 86 "gram.y"
+ case 12:
+#line 91 "gram.y"
{
/*
* _Anchors_: The language binding must keep a separate symbol table
@@ -1242,22 +1193,15 @@ yyreduce:
}
break;
- case 11:
-#line 95 "gram.y"
+ case 13:
+#line 100 "gram.y"
{
yyval.nodeData = yyvsp[-1].nodeData;
}
break;
- case 14:
-#line 105 "gram.y"
- {
- yyval.nodeData = yyvsp[-1].nodeData;
- }
- break;
-
case 15:
-#line 109 "gram.y"
+#line 107 "gram.y"
{
NULL_NODE( parser, n );
yyval.nodeData = n;
@@ -1265,62 +1209,31 @@ yyreduce:
break;
case 16:
-#line 114 "gram.y"
- {
- if ( ((SyckParser *)parser)->implicit_typing == 1 )
- {
- try_tag_implicit( yyvsp[0].nodeData, ((SyckParser *)parser)->taguri_expansion );
- }
- yyval.nodeData = yyvsp[0].nodeData;
- }
- break;
-
- case 17:
-#line 122 "gram.y"
- {
- syck_add_transfer( yyvsp[-1].name, yyvsp[0].nodeData, ((SyckParser *)parser)->taguri_expansion );
- yyval.nodeData = yyvsp[0].nodeData;
- }
- break;
-
- case 18:
-#line 127 "gram.y"
+#line 112 "gram.y"
{
- syck_add_transfer( yyvsp[-1].name, yyvsp[0].nodeData, 0 );
- yyval.nodeData = yyvsp[0].nodeData;
- }
- break;
-
- case 19:
-#line 132 "gram.y"
- {
- /*
- * _Anchors_: The language binding must keep a separate symbol table
- * for anchors. The actual ID in the symbol table is returned to the
- * higher nodes, though.
- */
- yyval.nodeData = syck_hdlr_add_anchor( (SyckParser *)parser, yyvsp[-1].name, yyvsp[0].nodeData );
+ NULL_NODE( parser, n );
+ yyval.nodeData = n;
}
break;
- case 26:
-#line 165 "gram.y"
+ case 23:
+#line 141 "gram.y"
{
syck_add_transfer( yyvsp[-1].name, yyvsp[0].nodeData, ((SyckParser *)parser)->taguri_expansion );
yyval.nodeData = yyvsp[0].nodeData;
}
break;
- case 27:
-#line 170 "gram.y"
+ case 24:
+#line 146 "gram.y"
{
syck_add_transfer( yyvsp[-1].name, yyvsp[0].nodeData, 0 );
yyval.nodeData = yyvsp[0].nodeData;
}
break;
- case 28:
-#line 175 "gram.y"
+ case 25:
+#line 151 "gram.y"
{
if ( ((SyckParser *)parser)->implicit_typing == 1 )
{
@@ -1330,15 +1243,15 @@ yyreduce:
}
break;
- case 29:
-#line 183 "gram.y"
+ case 26:
+#line 159 "gram.y"
{
yyval.nodeData = syck_hdlr_add_anchor( (SyckParser *)parser, yyvsp[-1].name, yyvsp[0].nodeData );
}
break;
- case 30:
-#line 187 "gram.y"
+ case 27:
+#line 163 "gram.y"
{
/*
* _Aliases_: The anchor symbol table is scanned for the anchor name.
@@ -1348,8 +1261,8 @@ yyreduce:
}
break;
- case 31:
-#line 195 "gram.y"
+ case 28:
+#line 171 "gram.y"
{
SyckNode *n = yyvsp[0].nodeData;
if ( ((SyckParser *)parser)->taguri_expansion == 1 )
@@ -1364,212 +1277,207 @@ yyreduce:
}
break;
- case 33:
-#line 209 "gram.y"
+ case 30:
+#line 185 "gram.y"
{
yyval.nodeData = yyvsp[-1].nodeData;
}
break;
- case 39:
-#line 229 "gram.y"
+ case 36:
+#line 205 "gram.y"
{
yyval.nodeData = yyvsp[-1].nodeData;
}
break;
- case 40:
-#line 233 "gram.y"
- {
- yyval.nodeData = yyvsp[-1].nodeData;
- }
- break;
-
- case 41:
-#line 239 "gram.y"
+ case 37:
+#line 211 "gram.y"
{
yyval.nodeId = syck_hdlr_add_node( (SyckParser *)parser, yyvsp[0].nodeData );
}
break;
- case 42:
-#line 245 "gram.y"
+ case 39:
+#line 218 "gram.y"
{
syck_add_transfer( yyvsp[-2].name, yyvsp[0].nodeData, ((SyckParser *)parser)->taguri_expansion );
yyval.nodeData = yyvsp[0].nodeData;
}
break;
- case 43:
-#line 250 "gram.y"
+ case 40:
+#line 223 "gram.y"
{
syck_add_transfer( yyvsp[-1].name, yyvsp[0].nodeData, ((SyckParser *)parser)->taguri_expansion );
yyval.nodeData = yyvsp[0].nodeData;
}
break;
- case 44:
-#line 255 "gram.y"
+ case 41:
+#line 228 "gram.y"
{
syck_add_transfer( yyvsp[-2].name, yyvsp[0].nodeData, 0 );
yyval.nodeData = yyvsp[0].nodeData;
}
break;
- case 45:
-#line 260 "gram.y"
+ case 42:
+#line 233 "gram.y"
{
syck_add_transfer( yyvsp[-1].name, yyvsp[0].nodeData, 0 );
yyval.nodeData = yyvsp[0].nodeData;
}
break;
- case 46:
-#line 265 "gram.y"
+ case 43:
+#line 238 "gram.y"
{
yyval.nodeData = syck_hdlr_add_anchor( (SyckParser *)parser, yyvsp[-2].name, yyvsp[0].nodeData );
}
break;
- case 47:
-#line 269 "gram.y"
+ case 44:
+#line 242 "gram.y"
{
yyval.nodeData = syck_hdlr_add_anchor( (SyckParser *)parser, yyvsp[-1].name, yyvsp[0].nodeData );
}
break;
- case 48:
-#line 275 "gram.y"
+ case 45:
+#line 248 "gram.y"
{
yyval.nodeData = syck_new_seq( yyvsp[0].nodeId );
}
break;
- case 49:
-#line 279 "gram.y"
+ case 46:
+#line 252 "gram.y"
{
syck_seq_add( yyvsp[-2].nodeData, yyvsp[0].nodeId );
yyval.nodeData = yyvsp[-2].nodeData;
}
break;
- case 50:
-#line 284 "gram.y"
+ case 47:
+#line 257 "gram.y"
{
yyval.nodeData = yyvsp[-1].nodeData;
}
break;
- case 51:
-#line 293 "gram.y"
+ case 48:
+#line 266 "gram.y"
{
yyval.nodeData = yyvsp[-1].nodeData;
}
break;
- case 52:
-#line 297 "gram.y"
+ case 49:
+#line 270 "gram.y"
{
yyval.nodeData = syck_alloc_seq();
}
break;
- case 53:
-#line 303 "gram.y"
+ case 50:
+#line 276 "gram.y"
{
yyval.nodeData = syck_new_seq( syck_hdlr_add_node( (SyckParser *)parser, yyvsp[0].nodeData ) );
}
break;
- case 54:
-#line 307 "gram.y"
+ case 51:
+#line 280 "gram.y"
{
syck_seq_add( yyvsp[-2].nodeData, syck_hdlr_add_node( (SyckParser *)parser, yyvsp[0].nodeData ) );
yyval.nodeData = yyvsp[-2].nodeData;
}
break;
- case 57:
-#line 321 "gram.y"
+ case 54:
+#line 294 "gram.y"
{
apply_seq_in_map( (SyckParser *)parser, yyvsp[-1].nodeData );
yyval.nodeData = yyvsp[-1].nodeData;
}
break;
- case 58:
-#line 326 "gram.y"
+ case 55:
+#line 299 "gram.y"
{
apply_seq_in_map( (SyckParser *)parser, yyvsp[-1].nodeData );
yyval.nodeData = yyvsp[-1].nodeData;
}
break;
- case 59:
-#line 333 "gram.y"
+ case 56:
+#line 306 "gram.y"
{
syck_add_transfer( yyvsp[-2].name, yyvsp[0].nodeData, ((SyckParser *)parser)->taguri_expansion );
yyval.nodeData = yyvsp[0].nodeData;
}
break;
- case 60:
-#line 338 "gram.y"
+ case 57:
+#line 311 "gram.y"
{
syck_add_transfer( yyvsp[-1].name, yyvsp[0].nodeData, ((SyckParser *)parser)->taguri_expansion );
yyval.nodeData = yyvsp[0].nodeData;
}
break;
- case 61:
-#line 343 "gram.y"
+ case 58:
+#line 316 "gram.y"
{
syck_add_transfer( yyvsp[-2].name, yyvsp[0].nodeData, 0 );
yyval.nodeData = yyvsp[0].nodeData;
}
break;
- case 62:
-#line 348 "gram.y"
+ case 59:
+#line 321 "gram.y"
{
syck_add_transfer( yyvsp[-1].name, yyvsp[0].nodeData, 0 );
yyval.nodeData = yyvsp[0].nodeData;
}
break;
- case 63:
-#line 353 "gram.y"
+ case 60:
+#line 326 "gram.y"
{
yyval.nodeData = syck_hdlr_add_anchor( (SyckParser *)parser, yyvsp[-2].name, yyvsp[0].nodeData );
}
break;
- case 64:
-#line 357 "gram.y"
+ case 61:
+#line 330 "gram.y"
{
yyval.nodeData = syck_hdlr_add_anchor( (SyckParser *)parser, yyvsp[-1].name, yyvsp[0].nodeData );
}
break;
- case 66:
-#line 364 "gram.y"
+ case 62:
+#line 336 "gram.y"
{
- yyval.nodeData = yyvsp[-1].nodeData;
+ yyval.nodeData = syck_new_map(
+ syck_hdlr_add_node( (SyckParser *)parser, yyvsp[-2].nodeData ),
+ syck_hdlr_add_node( (SyckParser *)parser, yyvsp[0].nodeData ) );
}
break;
- case 68:
-#line 380 "gram.y"
+ case 64:
+#line 352 "gram.y"
{
yyval.nodeData = syck_new_map(
- syck_hdlr_add_node( (SyckParser *)parser, yyvsp[-2].nodeData ),
+ syck_hdlr_add_node( (SyckParser *)parser, yyvsp[-3].nodeData ),
syck_hdlr_add_node( (SyckParser *)parser, yyvsp[0].nodeData ) );
}
break;
- case 70:
-#line 398 "gram.y"
- {
+ case 66:
+#line 370 "gram.y"
+ {
if ( yyvsp[-2].nodeData->shortcut == NULL )
{
yyvsp[-2].nodeData->shortcut = syck_new_seq( yyvsp[0].nodeId );
@@ -1582,9 +1490,9 @@ yyreduce:
}
break;
- case 71:
-#line 410 "gram.y"
- {
+ case 67:
+#line 382 "gram.y"
+ {
apply_seq_in_map( (SyckParser *)parser, yyvsp[-2].nodeData );
syck_map_update( yyvsp[-2].nodeData, yyvsp[0].nodeData );
syck_free_node( yyvsp[0].nodeData );
@@ -1593,15 +1501,15 @@ yyreduce:
}
break;
- case 72:
-#line 418 "gram.y"
- {
+ case 68:
+#line 390 "gram.y"
+ {
yyval.nodeData = yyvsp[-1].nodeData;
}
break;
- case 73:
-#line 427 "gram.y"
+ case 69:
+#line 399 "gram.y"
{
yyval.nodeData = syck_new_map(
syck_hdlr_add_node( (SyckParser *)parser, yyvsp[-2].nodeData ),
@@ -1609,22 +1517,22 @@ yyreduce:
}
break;
- case 74:
-#line 435 "gram.y"
+ case 70:
+#line 407 "gram.y"
{
yyval.nodeData = yyvsp[-1].nodeData;
}
break;
- case 75:
-#line 439 "gram.y"
+ case 71:
+#line 411 "gram.y"
{
yyval.nodeData = syck_alloc_map();
}
break;
- case 77:
-#line 446 "gram.y"
+ case 73:
+#line 418 "gram.y"
{
syck_map_update( yyvsp[-2].nodeData, yyvsp[0].nodeData );
syck_free_node( yyvsp[0].nodeData );
@@ -1633,8 +1541,8 @@ yyreduce:
}
break;
- case 78:
-#line 455 "gram.y"
+ case 74:
+#line 427 "gram.y"
{
NULL_NODE( parser, n );
yyval.nodeData = syck_new_map(
@@ -1646,14 +1554,23 @@ yyreduce:
}
-/* Line 1010 of yacc.c. */
-#line 1651 "gram.c"
+/* Line 1016 of /usr/local/share/bison/yacc.c. */
+#line 1559 "y.tab.c"
yyvsp -= yylen;
yyssp -= yylen;
- YY_STACK_PRINT (yyss, yyssp);
+#if YYDEBUG
+ if (yydebug)
+ {
+ short *yyssp1 = yyss - 1;
+ YYFPRINTF (stderr, "state stack now");
+ while (yyssp1 != yyssp)
+ YYFPRINTF (stderr, " %d", *++yyssp1);
+ YYFPRINTF (stderr, "\n");
+ }
+#endif
*++yyvsp = yyval;
@@ -1688,118 +1605,88 @@ yyerrlab:
{
YYSIZE_T yysize = 0;
int yytype = YYTRANSLATE (yychar);
- const char* yyprefix;
char *yymsg;
- int yyx;
+ int yyx, yycount;
+ yycount = 0;
/* Start YYX at -YYN if negative to avoid negative indexes in
YYCHECK. */
- int yyxbegin = yyn < 0 ? -yyn : 0;
-
- /* Stay within bounds of both yycheck and yytname. */
- int yychecklim = YYLAST - yyn;
- int yyxend = yychecklim < YYNTOKENS ? yychecklim : YYNTOKENS;
- int yycount = 0;
-
- yyprefix = ", expecting ";
- for (yyx = yyxbegin; yyx < yyxend; ++yyx)
+ for (yyx = yyn < 0 ? -yyn : 0;
+ yyx < (int) (sizeof (yytname) / sizeof (char *)); yyx++)
if (yycheck[yyx + yyn] == yyx && yyx != YYTERROR)
- {
- yysize += yystrlen (yyprefix) + yystrlen (yytname [yyx]);
- yycount += 1;
- if (yycount == 5)
- {
- yysize = 0;
- break;
- }
- }
- yysize += (sizeof ("syntax error, unexpected ")
- + yystrlen (yytname[yytype]));
+ yysize += yystrlen (yytname[yyx]) + 15, yycount++;
+ yysize += yystrlen ("parse error, unexpected ") + 1;
+ yysize += yystrlen (yytname[yytype]);
yymsg = (char *) YYSTACK_ALLOC (yysize);
if (yymsg != 0)
{
- char *yyp = yystpcpy (yymsg, "syntax error, unexpected ");
+ char *yyp = yystpcpy (yymsg, "parse error, unexpected ");
yyp = yystpcpy (yyp, yytname[yytype]);
if (yycount < 5)
{
- yyprefix = ", expecting ";
- for (yyx = yyxbegin; yyx < yyxend; ++yyx)
+ yycount = 0;
+ for (yyx = yyn < 0 ? -yyn : 0;
+ yyx < (int) (sizeof (yytname) / sizeof (char *));
+ yyx++)
if (yycheck[yyx + yyn] == yyx && yyx != YYTERROR)
{
- yyp = yystpcpy (yyp, yyprefix);
+ const char *yyq = ! yycount ? ", expecting " : " or ";
+ yyp = yystpcpy (yyp, yyq);
yyp = yystpcpy (yyp, yytname[yyx]);
- yyprefix = " or ";
+ yycount++;
}
}
yyerror (yymsg);
YYSTACK_FREE (yymsg);
}
else
- yyerror ("syntax error; also virtual memory exhausted");
+ yyerror ("parse error; also virtual memory exhausted");
}
else
#endif /* YYERROR_VERBOSE */
- yyerror ("syntax error");
+ yyerror ("parse error");
}
+ goto yyerrlab1;
-
+/*----------------------------------------------------.
+| yyerrlab1 -- error raised explicitly by an action. |
+`----------------------------------------------------*/
+yyerrlab1:
if (yyerrstatus == 3)
{
/* If just tried and failed to reuse lookahead token after an
error, discard it. */
- if (yychar <= YYEOF)
+ /* Return failure if at end of input. */
+ if (yychar == YYEOF)
{
- /* If at end of input, pop the error token,
- then the rest of the stack, then return failure. */
- if (yychar == YYEOF)
- for (;;)
- {
- YYPOPSTACK;
- if (yyssp == yyss)
- YYABORT;
- YYDSYMPRINTF ("Error: popping", yystos[*yyssp], yyvsp, yylsp);
- yydestruct (yystos[*yyssp], yyvsp);
- }
+ /* Pop the error token. */
+ YYPOPSTACK;
+ /* Pop the rest of the stack. */
+ while (yyssp > yyss)
+ {
+ YYDPRINTF ((stderr, "Error: popping "));
+ YYDSYMPRINT ((stderr,
+ yystos[*yyssp],
+ *yyvsp));
+ YYDPRINTF ((stderr, "\n"));
+ yydestruct (yystos[*yyssp], *yyvsp);
+ YYPOPSTACK;
+ }
+ YYABORT;
}
- else
- {
- YYDSYMPRINTF ("Error: discarding", yytoken, &yylval, &yylloc);
- yydestruct (yytoken, &yylval);
- yychar = YYEMPTY;
- }
+ YYDPRINTF ((stderr, "Discarding token %d (%s).\n",
+ yychar, yytname[yychar1]));
+ yydestruct (yychar1, yylval);
+ yychar = YYEMPTY;
}
/* Else will try to reuse lookahead token after shifting the error
token. */
- goto yyerrlab1;
-
-
-/*---------------------------------------------------.
-| yyerrorlab -- error raised explicitly by YYERROR. |
-`---------------------------------------------------*/
-yyerrorlab:
-
-#ifdef __GNUC__
- /* Pacify GCC when the user code never invokes YYERROR and the label
- yyerrorlab therefore never appears in user code. */
- if (0)
- goto yyerrorlab;
-#endif
-
- yyvsp -= yylen;
- yyssp -= yylen;
- yystate = *yyssp;
- goto yyerrlab1;
-
-/*-------------------------------------------------------------.
-| yyerrlab1 -- common code for both syntax error and YYERROR. |
-`-------------------------------------------------------------*/
-yyerrlab1:
yyerrstatus = 3; /* Each real token shifted decrements this. */
for (;;)
@@ -1820,11 +1707,26 @@ yyerrlab1:
if (yyssp == yyss)
YYABORT;
- YYDSYMPRINTF ("Error: popping", yystos[*yyssp], yyvsp, yylsp);
- yydestruct (yystos[yystate], yyvsp);
- YYPOPSTACK;
- yystate = *yyssp;
- YY_STACK_PRINT (yyss, yyssp);
+ YYDPRINTF ((stderr, "Error: popping "));
+ YYDSYMPRINT ((stderr,
+ yystos[*yyssp], *yyvsp));
+ YYDPRINTF ((stderr, "\n"));
+
+ yydestruct (yystos[yystate], *yyvsp);
+ yyvsp--;
+ yystate = *--yyssp;
+
+
+#if YYDEBUG
+ if (yydebug)
+ {
+ short *yyssp1 = yyss - 1;
+ YYFPRINTF (stderr, "Error: state stack now");
+ while (yyssp1 != yyssp)
+ YYFPRINTF (stderr, " %d", *++yyssp1);
+ YYFPRINTF (stderr, "\n");
+ }
+#endif
}
if (yyn == YYFINAL)
@@ -1872,7 +1774,7 @@ yyreturn:
}
-#line 464 "gram.y"
+#line 436 "gram.y"
void
diff --git a/ext/syck/gram.h b/ext/syck/gram.h
index 547149ab4b..4c0e199832 100644
--- a/ext/syck/gram.h
+++ b/ext/syck/gram.h
@@ -1,7 +1,7 @@
-/* A Bison parser, made by GNU Bison 1.875d. */
+/* A Bison parser, made from gram.y, by GNU bison 1.75. */
/* Skeleton parser for Yacc-like parsing with Bison,
- Copyright (C) 1984, 1989, 1990, 2000, 2001, 2002, 2003, 2004 Free Software Foundation, Inc.
+ Copyright (C) 1984, 1989, 1990, 2000, 2001, 2002 Free Software Foundation, Inc.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
@@ -23,6 +23,9 @@
This special exception was added by the Free Software Foundation
in version 1.24 of Bison. */
+#ifndef BISON_Y_TAB_H
+# define BISON_Y_TAB_H
+
/* Tokens. */
#ifndef YYTOKENTYPE
# define YYTOKENTYPE
@@ -59,21 +62,20 @@
-#if ! defined (YYSTYPE) && ! defined (YYSTYPE_IS_DECLARED)
-#line 35 "gram.y"
-typedef union YYSTYPE {
+#ifndef YYSTYPE
+#line 33 "gram.y"
+typedef union {
SYMID nodeId;
SyckNode *nodeData;
char *name;
-} YYSTYPE;
-/* Line 1285 of yacc.c. */
-#line 71 "gram.h"
-# define yystype YYSTYPE /* obsolescent; will be withdrawn */
-# define YYSTYPE_IS_DECLARED 1
-# define YYSTYPE_IS_TRIVIAL 1
+} yystype;
+/* Line 1281 of /usr/local/share/bison/yacc.c. */
+#line 74 "y.tab.h"
+# define YYSTYPE yystype
#endif
+#endif /* not BISON_Y_TAB_H */
diff --git a/ext/syck/handler.c b/ext/syck/handler.c
index 56fe838fbd..563feb10ae 100644
--- a/ext/syck/handler.c
+++ b/ext/syck/handler.c
@@ -31,8 +31,6 @@ syck_hdlr_add_node( SyckParser *p, SyckNode *n )
SyckNode *
syck_hdlr_add_anchor( SyckParser *p, char *a, SyckNode *n )
{
- SyckNode *ntmp = NULL;
-
n->anchor = a;
if ( p->bad_anchors != NULL )
{
@@ -50,13 +48,6 @@ syck_hdlr_add_anchor( SyckParser *p, char *a, SyckNode *n )
{
p->anchors = st_init_strtable();
}
- if ( st_lookup( p->anchors, (st_data_t)a, (st_data_t *)&ntmp ) )
- {
- if ( ntmp != (void *)1 )
- {
- syck_free_node( ntmp );
- }
- }
st_insert( p->anchors, (st_data_t)a, (st_data_t)n );
return n;
}
@@ -64,19 +55,10 @@ syck_hdlr_add_anchor( SyckParser *p, char *a, SyckNode *n )
void
syck_hdlr_remove_anchor( SyckParser *p, char *a )
{
- char *atmp = a;
- SyckNode *ntmp;
if ( p->anchors == NULL )
{
p->anchors = st_init_strtable();
}
- if ( st_delete( p->anchors, (st_data_t *)&atmp, (st_data_t *)&ntmp ) )
- {
- if ( ntmp != (void *)1 )
- {
- syck_free_node( ntmp );
- }
- }
st_insert( p->anchors, (st_data_t)a, (st_data_t)1 );
}
diff --git a/ext/syck/implicit.c b/ext/syck/implicit.c
index d356faf7d9..66f0520233 100644
--- a/ext/syck/implicit.c
+++ b/ext/syck/implicit.c
@@ -1,4 +1,4 @@
-/* Generated by re2c 0.9.10 on Mon Sep 19 21:46:50 2005 */
+/* Generated by re2c 0.9.3 on Fri Aug 13 11:47:51 2004 */
#line 1 "implicit.re"
/*
* implicit.re
@@ -36,7 +36,6 @@ try_tag_implicit( SyckNode *n, int taguri )
tid = "map";
break;
}
- if ( n->type_id != NULL ) S_FREE( n->type_id );
if ( taguri == 1 )
{
n->type_id = syck_taguri( YAML_DOMAIN, tid, strlen( tid ) );
@@ -52,17 +51,17 @@ char *syck_match_implicit( char *str, size_t len )
limit = str + len;
-#line 55 "<stdout>"
+#line 6 "<stdout>"
{
YYCTYPE yych;
unsigned int yyaccept;
goto yy0;
- ++YYCURSOR;
+yy1: ++YYCURSOR;
yy0:
if((YYLIMIT - YYCURSOR) < 26) YYFILL(26);
yych = *YYCURSOR;
switch(yych){
- case 0x00: goto yy6;
+ case '\000': goto yy6;
case '+': goto yy16;
case '-': goto yy17;
case '.': goto yy20;
@@ -92,12 +91,12 @@ yy0:
default: goto yy23;
}
yy2: ++YYCURSOR;
- if((yych = *YYCURSOR) <= 0x00) goto yy6;
+ if((yych = *YYCURSOR) <= '\000') goto yy6;
goto yy3;
yy3:
-#line 123 "implicit.re"
+#line 122 "implicit.re"
{ return "str"; }
-#line 100 "<stdout>"
+#line 51 "<stdout>"
yy4: yyaccept = 0;
yych = *(YYMARKER = ++YYCURSOR);
switch(yych){
@@ -116,9 +115,9 @@ yy5: yyaccept = 0;
yy6: ++YYCURSOR;
goto yy7;
yy7:
-#line 85 "implicit.re"
+#line 84 "implicit.re"
{ return "null"; }
-#line 121 "<stdout>"
+#line 72 "<stdout>"
yy8: yyaccept = 0;
yych = *(YYMARKER = ++YYCURSOR);
switch(yych){
@@ -208,7 +207,7 @@ yy17: yyaccept = 0;
yy18: yyaccept = 0;
yych = *(YYMARKER = ++YYCURSOR);
switch(yych){
- case 0x00: goto yy52;
+ case '\000': goto yy52;
case ',': goto yy142;
case '.': goto yy50;
case '0':
@@ -228,7 +227,7 @@ yy18: yyaccept = 0;
yy19: yyaccept = 0;
yych = *(YYMARKER = ++YYCURSOR);
switch(yych){
- case 0x00: goto yy52;
+ case '\000': goto yy52;
case ',': goto yy47;
case '.': goto yy50;
case '0':
@@ -254,7 +253,7 @@ yy20: yyaccept = 0;
default: goto yy3;
}
yy21: yych = *++YYCURSOR;
- if(yych <= 0x00) goto yy28;
+ if(yych <= '\000') goto yy28;
goto yy3;
yy22: yyaccept = 0;
yych = *(YYMARKER = ++YYCURSOR);
@@ -265,7 +264,7 @@ yy22: yyaccept = 0;
yy23: yych = *++YYCURSOR;
goto yy3;
yy24: yych = *++YYCURSOR;
- if(yych <= 0x00) goto yy26;
+ if(yych <= '\000') goto yy26;
goto yy25;
yy25: YYCURSOR = YYMARKER;
switch(yyaccept){
@@ -274,15 +273,15 @@ yy25: YYCURSOR = YYMARKER;
yy26: ++YYCURSOR;
goto yy27;
yy27:
-#line 121 "implicit.re"
+#line 120 "implicit.re"
{ return "merge"; }
-#line 279 "<stdout>"
+#line 230 "<stdout>"
yy28: ++YYCURSOR;
goto yy29;
yy29:
-#line 119 "implicit.re"
+#line 118 "implicit.re"
{ return "default"; }
-#line 285 "<stdout>"
+#line 236 "<stdout>"
yy30: yych = *++YYCURSOR;
switch(yych){
case 'a': goto yy45;
@@ -316,14 +315,14 @@ yy35: yych = *++YYCURSOR;
default: goto yy25;
}
yy36: yych = *++YYCURSOR;
- if(yych >= 0x01) goto yy25;
+ if(yych >= '\001') goto yy25;
goto yy37;
yy37: ++YYCURSOR;
goto yy38;
yy38:
-#line 105 "implicit.re"
+#line 104 "implicit.re"
{ return "float#inf"; }
-#line 326 "<stdout>"
+#line 277 "<stdout>"
yy39: yych = *++YYCURSOR;
switch(yych){
case 'f': goto yy36;
@@ -340,14 +339,14 @@ yy41: yych = *++YYCURSOR;
default: goto yy25;
}
yy42: yych = *++YYCURSOR;
- if(yych >= 0x01) goto yy25;
+ if(yych >= '\001') goto yy25;
goto yy43;
yy43: ++YYCURSOR;
goto yy44;
yy44:
-#line 109 "implicit.re"
+#line 108 "implicit.re"
{ return "float#nan"; }
-#line 350 "<stdout>"
+#line 301 "<stdout>"
yy45: yych = *++YYCURSOR;
switch(yych){
case 'n': goto yy42;
@@ -372,7 +371,7 @@ yy47: ++YYCURSOR;
yych = *YYCURSOR;
goto yy48;
yy48: switch(yych){
- case 0x00: goto yy52;
+ case '\000': goto yy52;
case ',': case '0':
case '1':
case '2':
@@ -404,11 +403,11 @@ yy49: ++YYCURSOR;
default: goto yy25;
}
yy50: ++YYCURSOR;
- if((YYLIMIT - YYCURSOR) < 3) YYFILL(3);
+ if(YYLIMIT == YYCURSOR) YYFILL(1);
yych = *YYCURSOR;
goto yy51;
yy51: switch(yych){
- case 0x00: goto yy56;
+ case '\000': goto yy56;
case ',': goto yy54;
case '.': goto yy58;
case '0':
@@ -427,15 +426,15 @@ yy51: switch(yych){
yy52: ++YYCURSOR;
goto yy53;
yy53:
-#line 97 "implicit.re"
+#line 96 "implicit.re"
{ return "int"; }
-#line 432 "<stdout>"
+#line 386 "<stdout>"
yy54: ++YYCURSOR;
if(YYLIMIT == YYCURSOR) YYFILL(1);
yych = *YYCURSOR;
goto yy55;
yy55: switch(yych){
- case 0x00: goto yy56;
+ case '\000': goto yy56;
case ',': case '0':
case '1':
case '2':
@@ -451,11 +450,11 @@ yy55: switch(yych){
yy56: ++YYCURSOR;
goto yy57;
yy57:
-#line 99 "implicit.re"
+#line 98 "implicit.re"
{ return "float#fix"; }
-#line 456 "<stdout>"
+#line 411 "<stdout>"
yy58: ++YYCURSOR;
- if((YYLIMIT - YYCURSOR) < 3) YYFILL(3);
+ if(YYLIMIT == YYCURSOR) YYFILL(1);
yych = *YYCURSOR;
goto yy59;
yy59: switch(yych){
@@ -478,14 +477,14 @@ yy60: yych = *++YYCURSOR;
default: goto yy25;
}
yy61: yych = *++YYCURSOR;
- if(yych <= 0x00) goto yy25;
+ if(yych <= '\000') goto yy25;
goto yy63;
yy62: ++YYCURSOR;
if(YYLIMIT == YYCURSOR) YYFILL(1);
yych = *YYCURSOR;
goto yy63;
yy63: switch(yych){
- case 0x00: goto yy64;
+ case '\000': goto yy64;
case '0':
case '1':
case '2':
@@ -501,14 +500,14 @@ yy63: switch(yych){
yy64: ++YYCURSOR;
goto yy65;
yy65:
-#line 101 "implicit.re"
+#line 100 "implicit.re"
{ return "float#exp"; }
-#line 506 "<stdout>"
+#line 463 "<stdout>"
yy66: ++YYCURSOR;
if(YYLIMIT == YYCURSOR) YYFILL(1);
yych = *YYCURSOR;
switch(yych){
- case 0x00: goto yy70;
+ case '\000': goto yy70;
case '.': goto yy68;
case '0':
case '1':
@@ -527,7 +526,7 @@ yy67: ++YYCURSOR;
if(YYLIMIT == YYCURSOR) YYFILL(1);
yych = *YYCURSOR;
switch(yych){
- case 0x00: goto yy70;
+ case '\000': goto yy70;
case '.': goto yy68;
case ':': goto yy49;
default: goto yy25;
@@ -537,7 +536,7 @@ yy68: ++YYCURSOR;
yych = *YYCURSOR;
goto yy69;
yy69: switch(yych){
- case 0x00: goto yy72;
+ case '\000': goto yy72;
case ',': case '0':
case '1':
case '2':
@@ -553,15 +552,15 @@ yy69: switch(yych){
yy70: ++YYCURSOR;
goto yy71;
yy71:
-#line 95 "implicit.re"
+#line 94 "implicit.re"
{ return "int#base60"; }
-#line 558 "<stdout>"
+#line 518 "<stdout>"
yy72: ++YYCURSOR;
goto yy73;
yy73:
-#line 103 "implicit.re"
+#line 102 "implicit.re"
{ return "float#base60"; }
-#line 564 "<stdout>"
+#line 524 "<stdout>"
yy74: yych = *++YYCURSOR;
switch(yych){
case '0':
@@ -644,7 +643,7 @@ yy80: yych = *++YYCURSOR;
}
yy81: yych = *++YYCURSOR;
switch(yych){
- case 0x00: goto yy82;
+ case '\000': goto yy82;
case '0':
case '1':
case '2':
@@ -662,9 +661,9 @@ yy81: yych = *++YYCURSOR;
yy82: ++YYCURSOR;
goto yy83;
yy83:
-#line 111 "implicit.re"
+#line 110 "implicit.re"
{ return "timestamp#ymd"; }
-#line 667 "<stdout>"
+#line 627 "<stdout>"
yy84: yych = *++YYCURSOR;
switch(yych){
case '0':
@@ -694,11 +693,11 @@ yy85: yych = *++YYCURSOR;
default: goto yy25;
}
yy86: ++YYCURSOR;
- if((YYLIMIT - YYCURSOR) < 9) YYFILL(9);
+ if(YYLIMIT == YYCURSOR) YYFILL(1);
yych = *YYCURSOR;
goto yy87;
yy87: switch(yych){
- case 0x09: case ' ': goto yy86;
+ case '\t': case ' ': goto yy86;
case '0':
case '1':
case '2':
@@ -793,7 +792,7 @@ yy94: yych = *++YYCURSOR;
}
yy95: yych = *++YYCURSOR;
switch(yych){
- case 0x09: case ' ': goto yy98;
+ case '\t': case ' ': goto yy98;
case '.': goto yy96;
default: goto yy25;
}
@@ -802,7 +801,7 @@ yy96: ++YYCURSOR;
yych = *YYCURSOR;
goto yy97;
yy97: switch(yych){
- case 0x09: case ' ': goto yy98;
+ case '\t': case ' ': goto yy98;
case '0':
case '1':
case '2':
@@ -816,17 +815,17 @@ yy97: switch(yych){
default: goto yy25;
}
yy98: ++YYCURSOR;
- if((YYLIMIT - YYCURSOR) < 7) YYFILL(7);
+ if(YYLIMIT == YYCURSOR) YYFILL(1);
yych = *YYCURSOR;
goto yy99;
yy99: switch(yych){
- case 0x09: case ' ': goto yy98;
+ case '\t': case ' ': goto yy98;
case '+': case '-': goto yy101;
case 'Z': goto yy100;
default: goto yy25;
}
yy100: yych = *++YYCURSOR;
- if(yych <= 0x00) goto yy105;
+ if(yych <= '\000') goto yy105;
goto yy25;
yy101: yych = *++YYCURSOR;
switch(yych){
@@ -858,7 +857,7 @@ yy102: yych = *++YYCURSOR;
}
yy103: yych = *++YYCURSOR;
switch(yych){
- case 0x00: goto yy105;
+ case '\000': goto yy105;
case ':': goto yy104;
default: goto yy25;
}
@@ -879,9 +878,9 @@ yy104: yych = *++YYCURSOR;
yy105: ++YYCURSOR;
goto yy106;
yy106:
-#line 115 "implicit.re"
+#line 114 "implicit.re"
{ return "timestamp#spaced"; }
-#line 884 "<stdout>"
+#line 847 "<stdout>"
yy107: yych = *++YYCURSOR;
switch(yych){
case '0':
@@ -992,7 +991,7 @@ yy115: yych = *++YYCURSOR;
default: goto yy117;
}
yy116: ++YYCURSOR;
- if((YYLIMIT - YYCURSOR) < 7) YYFILL(7);
+ if(YYLIMIT == YYCURSOR) YYFILL(1);
yych = *YYCURSOR;
goto yy117;
yy117: switch(yych){
@@ -1011,7 +1010,7 @@ yy117: switch(yych){
default: goto yy25;
}
yy118: yych = *++YYCURSOR;
- if(yych <= 0x00) goto yy123;
+ if(yych <= '\000') goto yy123;
goto yy25;
yy119: yych = *++YYCURSOR;
switch(yych){
@@ -1043,7 +1042,7 @@ yy120: yych = *++YYCURSOR;
}
yy121: yych = *++YYCURSOR;
switch(yych){
- case 0x00: goto yy123;
+ case '\000': goto yy123;
case ':': goto yy122;
default: goto yy25;
}
@@ -1064,9 +1063,9 @@ yy122: yych = *++YYCURSOR;
yy123: ++YYCURSOR;
goto yy124;
yy124:
-#line 113 "implicit.re"
+#line 112 "implicit.re"
{ return "timestamp#iso8601"; }
-#line 1069 "<stdout>"
+#line 1033 "<stdout>"
yy125: yych = *++YYCURSOR;
switch(yych){
case '0':
@@ -1197,7 +1196,7 @@ yy135: switch(yych){
default: goto yy25;
}
yy136: yych = *++YYCURSOR;
- if(yych >= 0x01) goto yy25;
+ if(yych >= '\001') goto yy25;
goto yy137;
yy137: yych = *++YYCURSOR;
goto yy124;
@@ -1253,7 +1252,7 @@ yy142: ++YYCURSOR;
yych = *YYCURSOR;
goto yy143;
yy143: switch(yych){
- case 0x00: goto yy149;
+ case '\000': goto yy149;
case ',': case '0':
case '1':
case '2':
@@ -1269,14 +1268,14 @@ yy143: switch(yych){
default: goto yy25;
}
yy144: yych = *++YYCURSOR;
- if(yych <= 0x00) goto yy25;
+ if(yych <= '\000') goto yy25;
goto yy146;
yy145: ++YYCURSOR;
if(YYLIMIT == YYCURSOR) YYFILL(1);
yych = *YYCURSOR;
goto yy146;
yy146: switch(yych){
- case 0x00: goto yy147;
+ case '\000': goto yy147;
case ',': case '0':
case '1':
case '2':
@@ -1302,15 +1301,15 @@ yy146: switch(yych){
yy147: ++YYCURSOR;
goto yy148;
yy148:
-#line 91 "implicit.re"
+#line 90 "implicit.re"
{ return "int#hex"; }
-#line 1307 "<stdout>"
+#line 1275 "<stdout>"
yy149: ++YYCURSOR;
goto yy150;
yy150:
-#line 93 "implicit.re"
+#line 92 "implicit.re"
{ return "int#oct"; }
-#line 1313 "<stdout>"
+#line 1281 "<stdout>"
yy151: ++YYCURSOR;
if(YYLIMIT == YYCURSOR) YYFILL(1);
yych = *YYCURSOR;
@@ -1376,7 +1375,7 @@ yy157: yych = *++YYCURSOR;
}
yy158: yych = *++YYCURSOR;
switch(yych){
- case 0x00: goto yy52;
+ case '\000': goto yy52;
case 'x': goto yy144;
default: goto yy143;
}
@@ -1402,14 +1401,14 @@ yy162: yych = *++YYCURSOR;
default: goto yy25;
}
yy163: yych = *++YYCURSOR;
- if(yych >= 0x01) goto yy25;
+ if(yych >= '\001') goto yy25;
goto yy164;
yy164: ++YYCURSOR;
goto yy165;
yy165:
-#line 107 "implicit.re"
+#line 106 "implicit.re"
{ return "float#neginf"; }
-#line 1412 "<stdout>"
+#line 1381 "<stdout>"
yy166: yych = *++YYCURSOR;
switch(yych){
case 'f': goto yy163;
@@ -1442,14 +1441,14 @@ yy171: yych = *++YYCURSOR;
default: goto yy25;
}
yy172: yych = *++YYCURSOR;
- if(yych >= 0x01) goto yy25;
+ if(yych >= '\001') goto yy25;
goto yy173;
yy173: ++YYCURSOR;
goto yy174;
yy174:
-#line 89 "implicit.re"
+#line 88 "implicit.re"
{ return "bool#no"; }
-#line 1452 "<stdout>"
+#line 1421 "<stdout>"
yy175: yych = *++YYCURSOR;
switch(yych){
case 'S': goto yy176;
@@ -1486,14 +1485,14 @@ yy181: yych = *++YYCURSOR;
default: goto yy25;
}
yy182: yych = *++YYCURSOR;
- if(yych >= 0x01) goto yy25;
+ if(yych >= '\001') goto yy25;
goto yy183;
yy183: ++YYCURSOR;
goto yy184;
yy184:
-#line 87 "implicit.re"
+#line 86 "implicit.re"
{ return "bool#yes"; }
-#line 1496 "<stdout>"
+#line 1465 "<stdout>"
yy185: yych = *++YYCURSOR;
switch(yych){
case 'f': goto yy172;
@@ -1560,7 +1559,7 @@ yy197: yych = *++YYCURSOR;
default: goto yy25;
}
yy198: yych = *++YYCURSOR;
- if(yych <= 0x00) goto yy6;
+ if(yych <= '\000') goto yy6;
goto yy25;
yy199: yych = *++YYCURSOR;
switch(yych){
@@ -1578,34 +1577,9 @@ yy201: ++YYCURSOR;
default: goto yy25;
}
}
-#line 125 "implicit.re"
-
+#line 124 "implicit.re"
-}
-/* Remove ending fragment and compare types */
-int
-syck_tagcmp( char *tag1, char *tag2 )
-{
- if ( tag1 == tag2 ) return 1;
- if ( tag1 == NULL || tag2 == NULL ) return 0;
- else {
- int i;
- char *othorpe;
- char *tmp1 = syck_strndup( tag1, strlen( tag1 ) );
- char *tmp2 = syck_strndup( tag2, strlen( tag2 ) );
- othorpe = strstr( tmp1, "#" );
- if ( othorpe != NULL ) {
- othorpe[0] = '\0';
- }
- othorpe = strstr( tmp2, "#" );
- if ( othorpe != NULL ) {
- othorpe[0] = '\0';
- }
- i = strcmp( tmp1, tmp2 );
- S_FREE( tmp1 ); S_FREE( tmp2 );
- return i;
- }
}
char *
@@ -1617,17 +1591,17 @@ syck_type_id_to_uri( char *type_id )
limit = type_id + strlen( type_id );
-#line 1620 "<stdout>"
+#line 1552 "<stdout>"
{
YYCTYPE yych;
unsigned int yyaccept;
goto yy202;
- ++YYCURSOR;
+yy203: ++YYCURSOR;
yy202:
- if((YYLIMIT - YYCURSOR) < 11) YYFILL(11);
+ if((YYLIMIT - YYCURSOR) < 21) YYFILL(21);
yych = *YYCURSOR;
switch(yych){
- case 0x00: goto yy204;
+ case '\000': goto yy204;
case '!': goto yy208;
case '0':
case '1':
@@ -1763,9 +1737,9 @@ yy205: yyaccept = 0;
default: goto yy206;
}
yy206:
-#line 202 "implicit.re"
+#line 176 "implicit.re"
{ return syck_taguri( YAML_DOMAIN, type_id, strlen( type_id ) ); }
-#line 1768 "<stdout>"
+#line 1700 "<stdout>"
yy207: yyaccept = 0;
yych = *(YYMARKER = ++YYCURSOR);
switch(yych){
@@ -1837,9 +1811,9 @@ yy207: yyaccept = 0;
yy208: ++YYCURSOR;
goto yy209;
yy209:
-#line 176 "implicit.re"
+#line 150 "implicit.re"
{ return syck_xprivate( type_id + 1, strlen( type_id ) - 1 ); }
-#line 1842 "<stdout>"
+#line 1774 "<stdout>"
yy210: yyaccept = 0;
yych = *(YYMARKER = ++YYCURSOR);
switch(yych){
@@ -1980,7 +1954,7 @@ yy213: switch(yych){
default: goto yy204;
}
yy214: ++YYCURSOR;
- if((YYLIMIT - YYCURSOR) < 2) YYFILL(2);
+ if(YYLIMIT == YYCURSOR) YYFILL(1);
yych = *YYCURSOR;
goto yy215;
yy215: switch(yych){
@@ -2133,7 +2107,7 @@ yy217: ++YYCURSOR;
yy218: ++YYCURSOR;
goto yy219;
yy219:
-#line 178 "implicit.re"
+#line 152 "implicit.re"
{ char *domain = S_ALLOC_N( char, ( YYCURSOR - type_id ) + 15 );
char *uri;
@@ -2146,9 +2120,9 @@ yy219:
S_FREE( domain );
return uri;
}
-#line 2149 "<stdout>"
+#line 2084 "<stdout>"
yy220: ++YYCURSOR;
- if((YYLIMIT - YYCURSOR) < 12) YYFILL(12);
+ if((YYLIMIT - YYCURSOR) < 2) YYFILL(2);
yych = *YYCURSOR;
goto yy221;
yy221: switch(yych){
@@ -2351,7 +2325,7 @@ yy228: yych = *++YYCURSOR;
yy229: ++YYCURSOR;
goto yy230;
yy230:
-#line 191 "implicit.re"
+#line 165 "implicit.re"
{ char *domain = S_ALLOC_N( char, YYCURSOR - type_id );
char *uri;
@@ -2362,7 +2336,7 @@ yy230:
S_FREE( domain );
return uri;
}
-#line 2365 "<stdout>"
+#line 2302 "<stdout>"
yy231: yych = *++YYCURSOR;
switch(yych){
case '0':
@@ -2480,9 +2454,9 @@ yy243: yych = *++YYCURSOR;
yy244: ++YYCURSOR;
goto yy245;
yy245:
-#line 174 "implicit.re"
-{ return syck_strndup( type_id, strlen( type_id ) ); }
-#line 2485 "<stdout>"
+#line 148 "implicit.re"
+{ return type_id; }
+#line 2422 "<stdout>"
yy246: yych = *++YYCURSOR;
switch(yych){
case ',': goto yy216;
@@ -2507,7 +2481,7 @@ yy248: yych = *++YYCURSOR;
default: goto yy250;
}
yy249: ++YYCURSOR;
- if((YYLIMIT - YYCURSOR) < 2) YYFILL(2);
+ if(YYLIMIT == YYCURSOR) YYFILL(1);
yych = *YYCURSOR;
goto yy250;
yy250: switch(yych){
@@ -2725,7 +2699,7 @@ yy254: ++YYCURSOR;
default: goto yy204;
}
yy255: ++YYCURSOR;
- if((YYLIMIT - YYCURSOR) < 12) YYFILL(12);
+ if((YYLIMIT - YYCURSOR) < 2) YYFILL(2);
yych = *YYCURSOR;
goto yy256;
yy256: switch(yych){
@@ -2927,9 +2901,9 @@ yy263: yych = *++YYCURSOR;
yy264: ++YYCURSOR;
goto yy265;
yy265:
-#line 172 "implicit.re"
-{ return syck_strndup( type_id, strlen( type_id ) ); }
-#line 2932 "<stdout>"
+#line 146 "implicit.re"
+{ return type_id; }
+#line 2874 "<stdout>"
yy266: yych = *++YYCURSOR;
switch(yych){
case '0':
@@ -2984,7 +2958,8 @@ yy270: ++YYCURSOR;
default: goto yy204;
}
}
-#line 204 "implicit.re"
+#line 178 "implicit.re"
}
+
diff --git a/ext/syck/node.c b/ext/syck/node.c
index 28fc78c077..500ede2a4c 100644
--- a/ext/syck/node.c
+++ b/ext/syck/node.c
@@ -33,15 +33,9 @@ syck_free_node( SyckNode *n )
{
syck_free_members( n );
if ( n->type_id != NULL )
- {
S_FREE( n->type_id );
- n->type_id = NULL;
- }
if ( n->anchor != NULL )
- {
S_FREE( n->anchor );
- n->anchor = NULL;
- }
S_FREE( n );
}
@@ -52,7 +46,6 @@ syck_alloc_map()
struct SyckMap *m;
m = S_ALLOC( struct SyckMap );
- m->style = map_none;
m->idx = 0;
m->capa = ALLOC_CT;
m->keys = S_ALLOC_N( SYMID, m->capa );
@@ -71,7 +64,6 @@ syck_alloc_seq()
struct SyckSeq *s;
s = S_ALLOC( struct SyckSeq );
- s->style = seq_none;
s->idx = 0;
s->capa = ALLOC_CT;
s->items = S_ALLOC_N( SYMID, s->capa );
@@ -121,28 +113,6 @@ syck_new_str2( char *str, long len, enum scalar_style style )
}
void
-syck_replace_str( SyckNode *n, char *str, enum scalar_style style )
-{
- syck_replace_str2( n, str, strlen( str ), style );
-}
-
-void
-syck_replace_str2( SyckNode *n, char *str, long len, enum scalar_style style )
-{
- if ( n->data.str != NULL )
- {
- S_FREE( n->data.str->ptr );
- n->data.str->ptr = NULL;
- n->data.str->len = 0;
- }
- n->data.str->ptr = S_ALLOC_N( char, len + 1 );
- n->data.str->len = len;
- n->data.str->style = style;
- memcpy( n->data.str->ptr, str, len );
- n->data.str->ptr[len] = '\0';
-}
-
-void
syck_str_blow_away_commas( SyckNode *n )
{
char *go, *end;
@@ -179,22 +149,6 @@ syck_new_map( SYMID key, SYMID value )
}
void
-syck_map_empty( SyckNode *n )
-{
- struct SyckMap *m;
- ASSERT( n != NULL );
- ASSERT( n->data.list != NULL );
-
- S_FREE( n->data.pairs->keys );
- S_FREE( n->data.pairs->values );
- m = n->data.pairs;
- m->idx = 0;
- m->capa = ALLOC_CT;
- m->keys = S_ALLOC_N( SYMID, m->capa );
- m->values = S_ALLOC_N( SYMID, m->capa );
-}
-
-void
syck_map_add( SyckNode *map, SYMID key, SYMID value )
{
struct SyckMap *m;
@@ -304,20 +258,6 @@ syck_new_seq( SYMID value )
}
void
-syck_seq_empty( SyckNode *n )
-{
- struct SyckSeq *s;
- ASSERT( n != NULL );
- ASSERT( n->data.list != NULL );
-
- S_FREE( n->data.list->items );
- s = n->data.list;
- s->idx = 0;
- s->capa = ALLOC_CT;
- s->items = S_ALLOC_N( SYMID, s->capa );
-}
-
-void
syck_seq_add( SyckNode *arr, SYMID value )
{
struct SyckSeq *s;
@@ -345,17 +285,6 @@ syck_seq_count( SyckNode *seq )
return seq->data.list->idx;
}
-void
-syck_seq_assign( SyckNode *seq, long idx, SYMID id )
-{
- struct SyckSeq *s;
-
- ASSERT( map != NULL );
- s = seq->data.list;
- ASSERT( m != NULL );
- s->items[idx] = id;
-}
-
SYMID
syck_seq_read( SyckNode *seq, long idx )
{
diff --git a/ext/syck/rubyext.c b/ext/syck/rubyext.c
index 6ae73a9714..c54deea618 100644
--- a/ext/syck/rubyext.c
+++ b/ext/syck/rubyext.c
@@ -1,11 +1,11 @@
-/* -*- indent-tabs-mode: nil -*- */
+/* -*- indent-tabs-mode: nil -*-
/*
* rubyext.c
*
* $Author$
* $Date$
*
- * Copyright (C) 2003-2005 why the lucky stiff
+ * Copyright (C) 2003 why the lucky stiff
*/
#include "ruby.h"
@@ -16,23 +16,23 @@
typedef struct RVALUE {
union {
#if 0
- struct {
- unsigned long flags; /* always 0 for freed obj */
- struct RVALUE *next;
- } free;
+ struct {
+ unsigned long flags; /* always 0 for freed obj */
+ struct RVALUE *next;
+ } free;
#endif
- struct RBasic basic;
- struct RObject object;
- struct RClass klass;
- /*struct RFloat flonum;*/
- /*struct RString string;*/
- struct RArray array;
- /*struct RRegexp regexp;*/
- struct RHash hash;
- /*struct RData data;*/
- struct RStruct rstruct;
- /*struct RBignum bignum;*/
- /*struct RFile file;*/
+ struct RBasic basic;
+ struct RObject object;
+ struct RClass klass;
+ /*struct RFloat flonum;*/
+ /*struct RString string;*/
+ struct RArray array;
+ /*struct RRegexp regexp;*/
+ struct RHash hash;
+ /*struct RData data;*/
+ struct RStruct rstruct;
+ /*struct RBignum bignum;*/
+ /*struct RFile file;*/
} as;
} RVALUE;
@@ -49,13 +49,12 @@ typedef struct {
/*
* symbols and constants
*/
-static ID s_new, s_utc, s_at, s_to_f, s_to_i, s_read, s_binmode, s_call, s_cmp, s_transfer, s_update, s_dup, s_haskey, s_match, s_keys, s_unpack, s_tr_bang, s_default_set, s_tag_read_class, s_tag_subclasses, s_resolver, s_push, s_emitter, s_level, s_detect_implicit, s_node_import, s_out, s_input, s_intern, s_transform, s_yaml_new, s_yaml_initialize, s_node_export, s_to_yaml, s_write, s_set_resolver;
-static ID s_tags, s_domain, s_kind, s_name, s_options, s_type_id, s_type_id_set, s_style, s_style_set, s_value, s_value_set;
+static ID s_new, s_utc, s_at, s_to_f, s_to_i, s_read, s_binmode, s_call, s_cmp, s_transfer, s_update, s_dup, s_match, s_keys, s_to_str, s_unpack, s_tr_bang, s_anchors, s_default_set;
+static ID s_anchors, s_domain, s_families, s_kind, s_name, s_options, s_private_types, s_type_id, s_value;
static VALUE sym_model, sym_generic, sym_input, sym_bytecode;
static VALUE sym_scalar, sym_seq, sym_map;
-static VALUE sym_1quote, sym_2quote, sym_fold, sym_literal, sym_plain, sym_inline;
-static VALUE cDate, cNode, cMap, cSeq, cScalar, cOut, cParser, cResolver, cPrivateType, cDomainType, cYObject, cBadAlias, cDefaultKey, cMergeKey, cEmitter;
-static VALUE oDefaultResolver, oGenericResolver;
+VALUE cDate, cParser, cLoader, cNode, cPrivateType, cDomainType, cBadAlias, cDefaultKey, cMergeKey, cEmitter;
+VALUE oDefaultLoader;
/*
* my private collection of numerical oddities.
@@ -70,35 +69,25 @@ static VALUE syck_node_transform( VALUE );
/*
* handler prototypes
*/
+SYMID rb_syck_parse_handler _((SyckParser *, SyckNode *));
SYMID rb_syck_load_handler _((SyckParser *, SyckNode *));
void rb_syck_err_handler _((SyckParser *, char *));
SyckNode * rb_syck_bad_anchor_handler _((SyckParser *, char *));
void rb_syck_output_handler _((SyckEmitter *, char *, long));
-void rb_syck_emitter_handler _((SyckEmitter *, st_data_t));
int syck_parser_assign_io _((SyckParser *, VALUE));
-VALUE syck_scalar_alloc _((VALUE class));
-VALUE syck_seq_alloc _((VALUE class));
-VALUE syck_map_alloc _((VALUE class));
struct parser_xtra {
VALUE data; /* Borrowed this idea from marshal.c to fix [ruby-core:8067] problem */
VALUE proc;
- VALUE resolver;
int taint;
};
-struct emitter_xtra {
- VALUE oid;
- VALUE data;
- VALUE port;
-};
-
/*
* Convert YAML to bytecode
*/
VALUE
rb_syck_compile(self, port)
- VALUE self, port;
+ VALUE self, port;
{
SYMID oid;
int taint;
@@ -107,7 +96,7 @@ rb_syck_compile(self, port)
bytestring_t *sav;
SyckParser *parser = syck_new_parser();
- taint = syck_parser_assign_io(parser, port);
+ taint = syck_parser_assign_io(parser, port);
syck_parser_handler( parser, syck_yaml2byte_handler );
syck_parser_error_handler( parser, NULL );
syck_parser_implicit_typing( parser, 0 );
@@ -149,7 +138,6 @@ rb_syck_io_str_read( char *buf, SyckIoStr *str, long max_size, long skip )
VALUE str2 = rb_funcall2(src, s_read, 1, &n);
if (!NIL_P(str2))
{
- StringValue(str2);
len = RSTRING(str2)->len;
memcpy( buf + skip, RSTRING(str2)->ptr, len );
}
@@ -165,15 +153,14 @@ rb_syck_io_str_read( char *buf, SyckIoStr *str, long max_size, long skip )
*/
int
syck_parser_assign_io(parser, port)
- SyckParser *parser;
- VALUE port;
+ SyckParser *parser;
+ VALUE port;
{
int taint = Qtrue;
- VALUE tmp;
- if (!NIL_P(tmp = rb_check_string_type(port))) {
- taint = OBJ_TAINTED(port); /* original taintedness */
- port = tmp;
- syck_parser_str( parser, RSTRING(port)->ptr, RSTRING(port)->len, NULL );
+ if (rb_respond_to(port, s_to_str)) {
+ taint = OBJ_TAINTED(port); /* original taintedness */
+ StringValue(port); /* possible conversion */
+ syck_parser_str( parser, RSTRING(port)->ptr, RSTRING(port)->len, NULL );
}
else if (rb_respond_to(port, s_read)) {
if (rb_respond_to(port, s_binmode)) {
@@ -207,70 +194,52 @@ syck_get_hash_aref(hsh, key)
* creating timestamps
*/
SYMID
-rb_syck_mktime(str, len)
+rb_syck_mktime(str)
char *str;
- long len;
{
VALUE time;
char *ptr = str;
- VALUE year = INT2FIX(0);
- VALUE mon = INT2FIX(0);
- VALUE day = INT2FIX(0);
- VALUE hour = INT2FIX(0);
- VALUE min = INT2FIX(0);
- VALUE sec = INT2FIX(0);
+ VALUE year, mon, day, hour, min, sec;
long usec;
/* Year*/
- if ( ptr[0] != '\0' && len > 0 ) {
- year = INT2FIX(strtol(ptr, NULL, 10));
- }
+ ptr[4] = '\0';
+ year = INT2FIX(strtol(ptr, NULL, 10));
/* Month*/
ptr += 4;
- if ( ptr[0] != '\0' && len > ptr - str ) {
- while ( !ISDIGIT( *ptr ) ) ptr++;
- mon = INT2FIX(strtol(ptr, NULL, 10));
- }
+ while ( !ISDIGIT( *ptr ) ) ptr++;
+ mon = INT2FIX(strtol(ptr, NULL, 10));
/* Day*/
ptr += 2;
- if ( ptr[0] != '\0' && len > ptr - str ) {
- while ( !ISDIGIT( *ptr ) ) ptr++;
- day = INT2FIX(strtol(ptr, NULL, 10));
- }
+ while ( !ISDIGIT( *ptr ) ) ptr++;
+ day = INT2FIX(strtol(ptr, NULL, 10));
/* Hour*/
ptr += 2;
- if ( ptr[0] != '\0' && len > ptr - str ) {
- while ( !ISDIGIT( *ptr ) ) ptr++;
- hour = INT2FIX(strtol(ptr, NULL, 10));
- }
+ while ( !ISDIGIT( *ptr ) ) ptr++;
+ hour = INT2FIX(strtol(ptr, NULL, 10));
/* Minute */
ptr += 2;
- if ( ptr[0] != '\0' && len > ptr - str ) {
- while ( !ISDIGIT( *ptr ) ) ptr++;
- min = INT2FIX(strtol(ptr, NULL, 10));
- }
+ while ( !ISDIGIT( *ptr ) ) ptr++;
+ min = INT2FIX(strtol(ptr, NULL, 10));
/* Second */
ptr += 2;
- if ( ptr[0] != '\0' && len > ptr - str ) {
- while ( !ISDIGIT( *ptr ) ) ptr++;
- sec = INT2FIX(strtol(ptr, NULL, 10));
- }
+ while ( !ISDIGIT( *ptr ) ) ptr++;
+ sec = INT2FIX(strtol(ptr, NULL, 10));
/* Millisecond */
ptr += 2;
- if ( len > ptr - str && *ptr == '.' )
+ if ( *ptr == '.' )
{
char *padded = syck_strndup( "000000", 6 );
char *end = ptr + 1;
while ( isdigit( *end ) ) end++;
MEMCPY(padded, ptr + 1, char, end - (ptr + 1));
usec = strtol(padded, NULL, 10);
- S_FREE(padded);
}
else
{
@@ -278,10 +247,10 @@ rb_syck_mktime(str, len)
}
/* Time Zone*/
- while ( len > ptr - str && *ptr != 'Z' && *ptr != '+' && *ptr != '-' && *ptr != '\0' ) ptr++;
- if ( len > ptr - str && ( *ptr == '-' || *ptr == '+' ) )
+ while ( *ptr != 'Z' && *ptr != '+' && *ptr != '-' && *ptr != '\0' ) ptr++;
+ if ( *ptr == '-' || *ptr == '+' )
{
- time_t tz_offset = strtol(ptr, NULL, 10) * 3600;
+ time_t tz_offset = strtol(ptr, NULL, 10) * 3600;
time_t tmp;
while ( *ptr != ':' && *ptr != '\0' ) ptr++;
@@ -299,15 +268,76 @@ rb_syck_mktime(str, len)
}
/* Make TZ time*/
- time = rb_funcall(rb_cTime, s_utc, 6, year, mon, day, hour, min, sec);
- tmp = NUM2LONG(rb_funcall(time, s_to_i, 0)) - tz_offset;
- return rb_funcall(rb_cTime, s_at, 2, LONG2NUM(tmp), LONG2NUM(usec));
+ time = rb_funcall(rb_cTime, s_utc, 6, year, mon, day, hour, min, sec);
+ tmp = NUM2LONG(rb_funcall(time, s_to_i, 0)) - tz_offset;
+ return rb_funcall(rb_cTime, s_at, 2, LONG2NUM(tmp), LONG2NUM(usec));
+ }
+ else
+ {
+ /* Make UTC time*/
+ return rb_funcall(rb_cTime, s_utc, 7, year, mon, day, hour, min, sec, LONG2NUM(usec));
+
}
- else
+}
+
+/*
+ * {generic mode} node handler
+ * - Loads data into Node classes
+ */
+SYMID
+rb_syck_parse_handler(p, n)
+ SyckParser *p;
+ SyckNode *n;
+{
+ VALUE t, obj, v = Qnil;
+ int i;
+ struct parser_xtra *bonus;
+
+ obj = rb_obj_alloc(cNode);
+ if ( n->type_id != NULL )
{
- /* Make UTC time*/
- return rb_funcall(rb_cTime, s_utc, 7, year, mon, day, hour, min, sec, LONG2NUM(usec));
+ t = rb_str_new2(n->type_id);
+ rb_ivar_set(obj, s_type_id, t);
+ }
+
+ switch (n->kind)
+ {
+ case syck_str_kind:
+ rb_ivar_set(obj, s_kind, sym_scalar);
+ v = rb_str_new( n->data.str->ptr, n->data.str->len );
+ break;
+
+ case syck_seq_kind:
+ rb_ivar_set(obj, s_kind, sym_seq);
+ v = rb_ary_new2( n->data.list->idx );
+ for ( i = 0; i < n->data.list->idx; i++ )
+ {
+ rb_ary_store( v, i, syck_seq_read( n, i ) );
+ }
+ break;
+
+ case syck_map_kind:
+ rb_ivar_set(obj, s_kind, sym_map);
+ v = rb_hash_new();
+ for ( i = 0; i < n->data.pairs->idx; i++ )
+ {
+ VALUE key = syck_node_transform( syck_map_read( n, map_key, i ) );
+ VALUE val = rb_ary_new();
+ rb_ary_push(val, syck_map_read( n, map_key, i ));
+ rb_ary_push(val, syck_map_read( n, map_value, i ));
+
+ rb_hash_aset( v, key, val );
+ }
+ break;
}
+
+ bonus = (struct parser_xtra *)p->bonus;
+ if ( bonus->taint) OBJ_TAINT( obj );
+ if ( bonus->proc != 0 ) rb_funcall(bonus->proc, s_call, 1, v);
+
+ rb_ivar_set(obj, s_value, v);
+ rb_hash_aset(bonus->data, INT2FIX(RHASH(bonus->data)->tbl->num_entries), obj);
+ return obj;
}
/*
@@ -318,13 +348,57 @@ VALUE
syck_merge_i( entry, hsh )
VALUE entry, hsh;
{
- VALUE tmp;
- if ( !NIL_P(tmp = rb_check_convert_type(entry, T_HASH, "Hash", "to_hash")) )
+ if ( rb_obj_is_kind_of( entry, rb_cHash ) )
+ {
+ rb_funcall( hsh, s_update, 1, entry );
+ }
+ return Qnil;
+}
+
+/*
+ * build a syck node from a Ruby VALUE
+ */
+SyckNode *
+rb_new_syck_node( obj, type_id )
+ VALUE obj, type_id;
+{
+ long i = 0;
+ SyckNode *n = NULL;
+
+ if (rb_respond_to(obj, s_to_str))
{
- entry = tmp;
- rb_funcall( hsh, s_update, 1, entry );
+ StringValue(obj); /* possible conversion */
+ n = syck_alloc_str();
+ n->data.str->ptr = RSTRING(obj)->ptr;
+ n->data.str->len = RSTRING(obj)->len;
}
- return Qnil;
+ else if ( rb_obj_is_kind_of( obj, rb_cArray ) )
+ {
+ n = syck_alloc_seq();
+ for ( i = 0; i < RARRAY(obj)->len; i++ )
+ {
+ syck_seq_add(n, rb_ary_entry(obj, i));
+ }
+ }
+ else if ( rb_obj_is_kind_of( obj, rb_cHash ) )
+ {
+ VALUE keys;
+ n = syck_alloc_map();
+ keys = rb_funcall( obj, s_keys, 0 );
+ for ( i = 0; i < RARRAY(keys)->len; i++ )
+ {
+ VALUE key = rb_ary_entry(keys, i);
+ syck_map_add(n, key, rb_hash_aref(obj, key));
+ }
+ }
+
+ if ( n!= NULL && rb_respond_to( type_id, s_to_str ) )
+ {
+ StringValue(type_id);
+ n->type_id = syck_strndup( RSTRING(type_id)->ptr, RSTRING(type_id)->len );
+ }
+
+ return n;
}
/*
@@ -340,11 +414,6 @@ yaml_org_handler( n, ref )
long i = 0;
VALUE obj = Qnil;
- if ( type_id != NULL && strncmp( type_id, "tag:yaml.org,2002:", 18 ) == 0 )
- {
- type_id += 18;
- }
-
switch (n->kind)
{
case syck_str_kind:
@@ -399,7 +468,7 @@ yaml_org_handler( n, ref )
{
colon--;
}
- if ( colon >= ptr && *colon == ':' ) *colon = '\0';
+ if ( *colon == ':' ) *colon = '\0';
bnum = strtol( colon + 1, NULL, 10 );
total += bnum * sixty;
@@ -429,7 +498,7 @@ yaml_org_handler( n, ref )
{
colon--;
}
- if ( colon >= ptr && *colon == ':' ) *colon = '\0';
+ if ( *colon == ':' ) *colon = '\0';
bnum = strtod( colon + 1, NULL );
total += bnum * sixty;
@@ -459,11 +528,11 @@ yaml_org_handler( n, ref )
}
else if ( strcmp( type_id, "timestamp#iso8601" ) == 0 )
{
- obj = rb_syck_mktime( n->data.str->ptr, n->data.str->len );
+ obj = rb_syck_mktime( n->data.str->ptr );
}
else if ( strcmp( type_id, "timestamp#spaced" ) == 0 )
{
- obj = rb_syck_mktime( n->data.str->ptr, n->data.str->len );
+ obj = rb_syck_mktime( n->data.str->ptr );
}
else if ( strcmp( type_id, "timestamp#ymd" ) == 0 )
{
@@ -496,22 +565,22 @@ yaml_org_handler( n, ref )
}
else if ( strncmp( type_id, "timestamp", 9 ) == 0 )
{
- obj = rb_syck_mktime( n->data.str->ptr, n->data.str->len );
- }
- else if ( strncmp( type_id, "merge", 5 ) == 0 )
- {
- obj = rb_funcall( cMergeKey, s_new, 0 );
- }
- else if ( strncmp( type_id, "default", 7 ) == 0 )
- {
- obj = rb_funcall( cDefaultKey, s_new, 0 );
+ obj = rb_syck_mktime( n->data.str->ptr );
}
+ else if ( strncmp( type_id, "merge", 5 ) == 0 )
+ {
+ obj = rb_funcall( cMergeKey, s_new, 0 );
+ }
+ else if ( strncmp( type_id, "default", 7 ) == 0 )
+ {
+ obj = rb_funcall( cDefaultKey, s_new, 0 );
+ }
else if ( n->data.str->style == scalar_plain &&
n->data.str->len > 1 &&
strncmp( n->data.str->ptr, ":", 1 ) == 0 )
{
- obj = rb_funcall( oDefaultResolver, s_transfer, 2,
- rb_str_new2( "tag:ruby.yaml.org,2002:sym" ),
+ obj = rb_funcall( oDefaultLoader, s_transfer, 2,
+ rb_str_new2( "ruby/sym" ),
rb_str_new( n->data.str->ptr + 1, n->data.str->len - 1 ) );
}
else if ( strcmp( type_id, "str" ) == 0 )
@@ -545,48 +614,46 @@ yaml_org_handler( n, ref )
obj = rb_hash_new();
for ( i = 0; i < n->data.pairs->idx; i++ )
{
- VALUE k = syck_map_read( n, map_key, i );
- VALUE v = syck_map_read( n, map_value, i );
- int skip_aset = 0;
-
- /*
- * Handle merge keys
- */
- if ( rb_obj_is_kind_of( k, cMergeKey ) )
- {
- VALUE tmp;
- if ( !NIL_P(tmp = rb_check_convert_type(v, T_HASH, "Hash", "to_hash")) )
- {
- VALUE dup = rb_funcall( tmp, s_dup, 0 );
- rb_funcall( dup, s_update, 1, obj );
- obj = dup;
- skip_aset = 1;
- }
- else if ( !NIL_P(tmp = rb_check_array_type(v)) )
- {
- VALUE end = rb_ary_pop( tmp );
- VALUE tmph = rb_check_convert_type(end, T_HASH, "Hash", "to_hash");
- if ( !NIL_P(tmph) )
- {
- VALUE dup = rb_funcall( tmph, s_dup, 0 );
- tmp = rb_ary_reverse( tmp );
- rb_ary_push( tmp, obj );
- rb_iterate( rb_each, tmp, syck_merge_i, dup );
- obj = dup;
- skip_aset = 1;
- }
- }
- }
+ VALUE k = syck_map_read( n, map_key, i );
+ VALUE v = syck_map_read( n, map_value, i );
+ int skip_aset = 0;
+
+ /*
+ * Handle merge keys
+ */
+ if ( rb_obj_is_kind_of( k, cMergeKey ) )
+ {
+ if ( rb_obj_is_kind_of( v, rb_cHash ) )
+ {
+ VALUE dup = rb_funcall( v, s_dup, 0 );
+ rb_funcall( dup, s_update, 1, obj );
+ obj = dup;
+ skip_aset = 1;
+ }
+ else if ( rb_obj_is_kind_of( v, rb_cArray ) )
+ {
+ VALUE end = rb_ary_pop( v );
+ if ( rb_obj_is_kind_of( end, rb_cHash ) )
+ {
+ VALUE dup = rb_funcall( end, s_dup, 0 );
+ v = rb_ary_reverse( v );
+ rb_ary_push( v, obj );
+ rb_iterate( rb_each, v, syck_merge_i, dup );
+ obj = dup;
+ skip_aset = 1;
+ }
+ }
+ }
else if ( rb_obj_is_kind_of( k, cDefaultKey ) )
{
rb_funcall( obj, s_default_set, 1, v );
skip_aset = 1;
}
- if ( ! skip_aset )
- {
- rb_hash_aset( obj, k, v );
- }
+ if ( ! skip_aset )
+ {
+ rb_hash_aset( obj, k, v );
+ }
}
break;
}
@@ -605,17 +672,16 @@ rb_syck_load_handler(p, n)
SyckNode *n;
{
VALUE obj = Qnil;
- struct parser_xtra *bonus = (struct parser_xtra *)p->bonus;
- VALUE resolver = bonus->resolver;
- if ( NIL_P( resolver ) )
- {
- resolver = oDefaultResolver;
- }
+ struct parser_xtra *bonus;
/*
- * Create node,
+ * Attempt common transfers
*/
- obj = rb_funcall( resolver, s_node_import, 1, Data_Wrap_Struct( cNode, NULL, NULL, n ) );
+ int transferred = yaml_org_handler(n, &obj);
+ if ( transferred == 0 && n->type_id != NULL )
+ {
+ obj = rb_funcall( oDefaultLoader, s_transfer, 2, rb_str_new2( n->type_id ), obj );
+ }
/*
* ID already set, let's alter the symbol table to accept the new object
@@ -627,8 +693,9 @@ rb_syck_load_handler(p, n)
obj = n->id;
}
+ bonus = (struct parser_xtra *)p->bonus;
if ( bonus->taint) OBJ_TAINT( obj );
- if ( bonus->proc != 0 ) rb_funcall(bonus->proc, s_call, 1, obj);
+ if ( bonus->proc != 0 ) rb_funcall(bonus->proc, s_call, 1, obj);
rb_hash_aset(bonus->data, INT2FIX(RHASH(bonus->data)->tbl->num_entries), obj);
return obj;
@@ -673,32 +740,26 @@ rb_syck_bad_anchor_handler(p, a)
* data loaded based on the model requested.
*/
void
-syck_set_model( p, input, model )
- VALUE p, input, model;
-{
- SyckParser *parser;
- Data_Get_Struct(p, SyckParser, parser);
- syck_parser_handler( parser, rb_syck_load_handler );
- /* WARN: gonna be obsoleted soon!! */
- if ( model == sym_generic )
- {
- rb_funcall( p, s_set_resolver, 1, oGenericResolver );
- }
- syck_parser_implicit_typing( parser, 1 );
- syck_parser_taguri_expansion( parser, 1 );
-
- if ( NIL_P( input ) )
- {
- input = rb_ivar_get( p, s_input );
- }
+syck_set_model( parser, input, model )
+ SyckParser *parser;
+ VALUE input, model;
+{
+ if ( model == sym_generic )
+ {
+ syck_parser_handler( parser, rb_syck_parse_handler );
+ syck_parser_implicit_typing( parser, 1 );
+ syck_parser_taguri_expansion( parser, 1 );
+ }
+ else
+ {
+ syck_parser_handler( parser, rb_syck_load_handler );
+ syck_parser_implicit_typing( parser, 1 );
+ syck_parser_taguri_expansion( parser, 0 );
+ }
if ( input == sym_bytecode )
{
syck_parser_set_input_type( parser, syck_bytecode_utf8 );
}
- else
- {
- syck_parser_set_input_type( parser, syck_yaml_utf8 );
- }
syck_parser_error_handler( parser, rb_syck_err_handler );
syck_parser_bad_anchor_handler( parser, rb_syck_bad_anchor_handler );
}
@@ -710,67 +771,45 @@ static void
syck_mark_parser(parser)
SyckParser *parser;
{
- struct parser_xtra *bonus;
rb_gc_mark(parser->root);
rb_gc_mark(parser->root_on_error);
- if ( parser->bonus != NULL )
- {
- bonus = (struct parser_xtra *)parser->bonus;
- rb_gc_mark( bonus->data );
- rb_gc_mark( bonus->proc );
- }
}
/*
- * Free the parser and any bonus attachment.
+ * YAML::Syck::Parser.new
*/
-void
-rb_syck_free_parser(p)
- SyckParser *p;
-{
- struct parser_xtra *bonus = (struct parser_xtra *)p->bonus;
- if ( bonus != NULL ) S_FREE( bonus );
- syck_free_parser(p);
-}
-
-/*
- * YAML::Syck::Parser.allocate
- */
-VALUE syck_parser_s_alloc _((VALUE));
VALUE
-syck_parser_s_alloc(class)
- VALUE class;
+syck_parser_new(argc, argv, class)
+ int argc;
+ VALUE *argv;
+ VALUE class;
{
- VALUE pobj;
+ VALUE pobj, options, init_argv[1];
SyckParser *parser = syck_new_parser();
- pobj = Data_Wrap_Struct( class, syck_mark_parser, rb_syck_free_parser, parser );
+ rb_scan_args(argc, argv, "01", &options);
+ pobj = Data_Wrap_Struct( class, syck_mark_parser, syck_free_parser, parser );
syck_parser_set_root_on_error( parser, Qnil );
- return pobj;
+ if ( ! rb_obj_is_instance_of( options, rb_cHash ) )
+ {
+ options = rb_hash_new();
+ }
+ init_argv[0] = options;
+ rb_obj_call_init(pobj, 1, init_argv);
+ return pobj;
}
/*
- * YAML::Syck::Parser.initialize( resolver, options )
+ * YAML::Syck::Parser.initialize( options )
*/
static VALUE
-syck_parser_initialize(argc, argv, self)
- int argc;
- VALUE *argv;
- VALUE self;
+syck_parser_initialize( self, options )
+ VALUE self, options;
{
- VALUE options;
- if (rb_scan_args(argc, argv, "01", &options) == 0)
- {
- options = rb_hash_new();
- }
- else
- {
- Check_Type(options, T_HASH);
- }
rb_ivar_set(self, s_options, options);
- return self;
+ return self;
}
/*
@@ -780,14 +819,13 @@ static VALUE
syck_parser_bufsize_set( self, size )
VALUE self, size;
{
- SyckParser *parser;
+ SyckParser *parser;
+ Data_Get_Struct(self, SyckParser, parser);
if ( rb_respond_to( size, s_to_i ) ) {
- int n = NUM2INT(rb_funcall(size, s_to_i, 0));
- Data_Get_Struct(self, SyckParser, parser);
- parser->bufsize = n;
+ parser->bufsize = NUM2INT(rb_funcall(size, s_to_i, 0));
}
- return self;
+ return self;
}
/*
@@ -797,10 +835,10 @@ static VALUE
syck_parser_bufsize_get( self )
VALUE self;
{
- SyckParser *parser;
+ SyckParser *parser;
- Data_Get_Struct(self, SyckParser, parser);
- return INT2FIX( parser->bufsize );
+ Data_Get_Struct(self, SyckParser, parser);
+ return INT2FIX( parser->bufsize );
}
/*
@@ -810,27 +848,26 @@ VALUE
syck_parser_load(argc, argv, self)
int argc;
VALUE *argv;
- VALUE self;
+ VALUE self;
{
VALUE port, proc, model, input;
- SyckParser *parser;
- struct parser_xtra *bonus = S_ALLOC_N( struct parser_xtra, 1 );
- volatile VALUE hash; /* protect from GC */
+ SyckParser *parser;
+ struct parser_xtra bonus;
+ volatile VALUE hash; /* protect from GC */
rb_scan_args(argc, argv, "11", &port, &proc);
+ Data_Get_Struct(self, SyckParser, parser);
input = rb_hash_aref( rb_attr_get( self, s_options ), sym_input );
model = rb_hash_aref( rb_attr_get( self, s_options ), sym_model );
- Data_Get_Struct(self, SyckParser, parser);
- syck_set_model( self, input, model );
-
- bonus->taint = syck_parser_assign_io(parser, port);
- bonus->data = hash = rb_hash_new();
- bonus->resolver = rb_attr_get( self, s_resolver );
- if ( NIL_P( proc ) ) bonus->proc = 0;
- else bonus->proc = proc;
+ syck_set_model( parser, input, model );
+
+ bonus.taint = syck_parser_assign_io(parser, port);
+ bonus.data = hash = rb_hash_new();
+ if ( NIL_P( proc ) ) bonus.proc = 0;
+ else bonus.proc = proc;
- parser->bonus = (void *)bonus;
+ parser->bonus = (void *)&bonus;
return syck_parse( parser );
}
@@ -842,372 +879,155 @@ VALUE
syck_parser_load_documents(argc, argv, self)
int argc;
VALUE *argv;
- VALUE self;
+ VALUE self;
{
VALUE port, proc, v, input, model;
- SyckParser *parser;
- struct parser_xtra *bonus = S_ALLOC_N( struct parser_xtra, 1 );
+ SyckParser *parser;
+ struct parser_xtra bonus;
volatile VALUE hash;
rb_scan_args(argc, argv, "1&", &port, &proc);
+ Data_Get_Struct(self, SyckParser, parser);
input = rb_hash_aref( rb_attr_get( self, s_options ), sym_input );
model = rb_hash_aref( rb_attr_get( self, s_options ), sym_model );
- Data_Get_Struct(self, SyckParser, parser);
- syck_set_model( self, input, model );
+ syck_set_model( parser, input, model );
- bonus->taint = syck_parser_assign_io(parser, port);
- bonus->resolver = rb_attr_get( self, s_resolver );
- bonus->proc = 0;
- parser->bonus = (void *)bonus;
-
+ bonus.taint = syck_parser_assign_io(parser, port);
while ( 1 )
- {
+ {
/* Reset hash for tracking nodes */
- bonus->data = hash = rb_hash_new();
+ bonus.data = hash = rb_hash_new();
+ bonus.proc = 0;
+ parser->bonus = (void *)&bonus;
/* Parse a document */
- v = syck_parse( parser );
+ v = syck_parse( parser );
if ( parser->eof == 1 )
{
break;
}
/* Pass document to block */
- rb_funcall( proc, s_call, 1, v );
- }
+ rb_funcall( proc, s_call, 1, v );
+ }
return Qnil;
}
/*
- * YAML::Syck::Parser#set_resolver
- */
-VALUE
-syck_parser_set_resolver( self, resolver )
- VALUE self, resolver;
-{
- rb_ivar_set( self, s_resolver, resolver );
- return self;
-}
-
-/*
- * YAML::Syck::Resolver.initialize
+ * YAML::Syck::Loader.initialize
*/
static VALUE
-syck_resolver_initialize( self )
+syck_loader_initialize( self )
VALUE self;
{
- VALUE tags = rb_hash_new();
- rb_ivar_set(self, s_tags, rb_hash_new());
+ VALUE families;
+
+ families = rb_hash_new();
+ rb_ivar_set(self, s_families, families);
+ rb_ivar_set(self, s_private_types, rb_hash_new());
+ rb_ivar_set(self, s_anchors, rb_hash_new());
+
+ rb_hash_aset(families, rb_str_new2( YAML_DOMAIN ), rb_hash_new());
+ rb_hash_aset(families, rb_str_new2( RUBY_DOMAIN ), rb_hash_new());
+
return self;
}
/*
- * YAML::Syck::Resolver#add_type
+ * Add type family, used by add_*_type methods.
*/
VALUE
-syck_resolver_add_type( self, taguri, cls )
- VALUE self, taguri, cls;
+syck_loader_add_type_family( self, domain, type_re, proc )
+ VALUE self, domain, type_re, proc;
{
- VALUE tags = rb_attr_get(self, s_tags);
- rb_hash_aset( tags, taguri, cls );
+ VALUE families, domain_types;
+
+ families = rb_attr_get(self, s_families);
+ domain_types = syck_get_hash_aref(families, domain);
+ rb_hash_aset( domain_types, type_re, proc );
return Qnil;
}
/*
- * YAML::Syck::Resolver#use_types_at
+ * YAML::Syck::Loader.add_domain_type
*/
VALUE
-syck_resolver_use_types_at( self, hsh )
- VALUE self, hsh;
+syck_loader_add_domain_type( argc, argv, self )
+ int argc;
+ VALUE *argv;
+ VALUE self;
{
- rb_ivar_set( self, s_tags, hsh );
+ VALUE domain, type_re, proc;
+
+ rb_scan_args(argc, argv, "2&", &domain, &type_re, &proc);
+ syck_loader_add_type_family( self, domain, type_re, proc );
return Qnil;
}
-/*
- * YAML::Syck::Resolver#detect_implicit
- */
-VALUE
-syck_resolver_detect_implicit( self, val )
- VALUE self, val;
-{
- char *type_id;
- return rb_str_new2( "" );
-}
/*
- * YAML::Syck::Resolver#node_import
+ * YAML::Syck::Loader.add_builtin_type
*/
VALUE
-syck_resolver_node_import( self, node )
- VALUE self, node;
+syck_loader_add_builtin_type( argc, argv, self )
+ int argc;
+ VALUE *argv;
+ VALUE self;
{
- SyckNode *n;
- VALUE obj;
- int i = 0;
- Data_Get_Struct(node, SyckNode, n);
-
- switch (n->kind)
- {
- case syck_str_kind:
- obj = rb_str_new( n->data.str->ptr, n->data.str->len );
- break;
+ VALUE type_re, proc;
- case syck_seq_kind:
- obj = rb_ary_new2( n->data.list->idx );
- for ( i = 0; i < n->data.list->idx; i++ )
- {
- rb_ary_store( obj, i, syck_seq_read( n, i ) );
- }
- break;
-
- case syck_map_kind:
- obj = rb_hash_new();
- for ( i = 0; i < n->data.pairs->idx; i++ )
- {
- VALUE k = syck_map_read( n, map_key, i );
- VALUE v = syck_map_read( n, map_value, i );
- int skip_aset = 0;
-
- /*
- * Handle merge keys
- */
- if ( rb_obj_is_kind_of( k, cMergeKey ) )
- {
- if ( rb_obj_is_kind_of( v, rb_cHash ) )
- {
- VALUE dup = rb_funcall( v, s_dup, 0 );
- rb_funcall( dup, s_update, 1, obj );
- obj = dup;
- skip_aset = 1;
- }
- else if ( rb_obj_is_kind_of( v, rb_cArray ) )
- {
- VALUE end = rb_ary_pop( v );
- if ( rb_obj_is_kind_of( end, rb_cHash ) )
- {
- VALUE dup = rb_funcall( end, s_dup, 0 );
- v = rb_ary_reverse( v );
- rb_ary_push( v, obj );
- rb_iterate( rb_each, v, syck_merge_i, dup );
- obj = dup;
- skip_aset = 1;
- }
- }
- }
- else if ( rb_obj_is_kind_of( k, cDefaultKey ) )
- {
- rb_funcall( obj, s_default_set, 1, v );
- skip_aset = 1;
- }
-
- if ( ! skip_aset )
- {
- rb_hash_aset( obj, k, v );
- }
- }
- break;
- }
-
- if ( n->type_id != NULL )
- {
- obj = rb_funcall( self, s_transfer, 2, rb_str_new2( n->type_id ), obj );
- }
- return obj;
-}
-
-/*
- * Set instance variables
- */
-VALUE
-syck_set_ivars( vars, obj )
- VALUE vars, obj;
-{
- VALUE ivname = rb_ary_entry( vars, 0 );
- char *ivn;
- StringValue( ivname );
- ivn = S_ALLOC_N( char, RSTRING(ivname)->len + 2 );
- ivn[0] = '@';
- ivn[1] = '\0';
- strncat( ivn, RSTRING(ivname)->ptr, RSTRING(ivname)->len );
- rb_iv_set( obj, ivn, rb_ary_entry( vars, 1 ) );
- S_FREE( ivn );
+ rb_scan_args(argc, argv, "1&", &type_re, &proc);
+ syck_loader_add_type_family( self, rb_str_new2( YAML_DOMAIN ), type_re, proc );
return Qnil;
}
/*
- * YAML::Syck::Resolver#const_find
+ * YAML::Syck::Loader.add_ruby_type
*/
VALUE
-syck_const_find( const_name )
- VALUE const_name;
-{
- VALUE tclass = rb_cObject;
- VALUE tparts = rb_str_split( const_name, "::" );
- int i = 0;
- for ( i = 0; i < RARRAY(tparts)->len; i++ ) {
- VALUE tpart = rb_to_id( rb_ary_entry( tparts, i ) );
- if ( !rb_const_defined( tclass, tpart ) ) return Qnil;
- tclass = rb_const_get( tclass, tpart );
- }
- return tclass;
-}
-
-/*
- * YAML::Syck::Resolver#transfer
- */
-VALUE
-syck_resolver_transfer( self, type, val )
- VALUE self, type, val;
+syck_loader_add_ruby_type( argc, argv, self )
+ int argc;
+ VALUE *argv;
+ VALUE self;
{
- if (NIL_P(type) || RSTRING(StringValue(type))->len == 0)
- {
- type = rb_funcall( self, s_detect_implicit, 1, val );
- }
-
- if ( ! (NIL_P(type) || RSTRING(StringValue(type))->len == 0) )
- {
- VALUE str_xprivate = rb_str_new2( "x-private" );
- VALUE colon = rb_str_new2( ":" );
- VALUE tags = rb_attr_get(self, s_tags);
- VALUE target_class = rb_hash_aref( tags, type );
- VALUE subclass = target_class;
- VALUE obj = Qnil;
-
- /*
- * Should no tag match exactly, check for subclass format
- */
- if ( NIL_P( target_class ) )
- {
- VALUE subclass_parts = rb_ary_new();
- VALUE parts = rb_str_split( type, ":" );
-
- while ( RARRAY(parts)->len > 1 )
- {
- VALUE partial;
- rb_ary_unshift( subclass_parts, rb_ary_pop( parts ) );
- partial = rb_ary_join( parts, colon );
- target_class = rb_hash_aref( tags, partial );
- if ( NIL_P( target_class ) )
- {
- rb_str_append( partial, colon );
- target_class = rb_hash_aref( tags, partial );
- }
-
- /*
- * Possible subclass found, see if it supports subclassing
- */
- if ( ! NIL_P( target_class ) )
- {
- subclass = target_class;
- if ( RARRAY(subclass_parts)->len > 0 && rb_respond_to( target_class, s_tag_subclasses ) &&
- RTEST( rb_funcall( target_class, s_tag_subclasses, 0 ) ) )
- {
- VALUE subclass_v;
- subclass = rb_ary_join( subclass_parts, colon );
- subclass = rb_funcall( target_class, s_tag_read_class, 1, subclass );
- subclass_v = syck_const_find( subclass );
-
- if ( subclass_v != Qnil )
- {
- subclass = subclass_v;
- }
- else if ( rb_cObject == target_class && subclass_v == Qnil )
- {
- target_class = cYObject;
- type = subclass;
- subclass = cYObject;
- }
- }
- break;
- }
- }
- }
-
- /* rb_raise(rb_eTypeError, "invalid typing scheme: %s given",
- * scheme);
- */
-
- if ( rb_respond_to( target_class, s_call ) )
- {
- obj = rb_funcall( target_class, s_call, 2, type, val );
- }
- else
- {
- if ( rb_respond_to( target_class, s_yaml_new ) )
- {
- obj = rb_funcall( target_class, s_yaml_new, 3, subclass, type, val );
- }
- else if ( !NIL_P( target_class ) )
- {
- obj = rb_obj_alloc( subclass );
- if ( rb_respond_to( obj, s_yaml_initialize ) )
- {
- rb_funcall( obj, s_yaml_initialize, 2, type, val );
- }
- else if ( !NIL_P( obj ) && rb_obj_is_instance_of( val, rb_cHash ) )
- {
- rb_iterate( rb_each, val, syck_set_ivars, obj );
- }
- }
- else
- {
- VALUE parts = rb_str_split( type, ":" );
- VALUE scheme = rb_ary_shift( parts );
- if ( rb_str_cmp( scheme, str_xprivate ) == 0 )
- {
- VALUE name = rb_ary_join( parts, colon );
- obj = rb_funcall( cPrivateType, s_new, 2, name, val );
- }
- else
- {
- VALUE domain = rb_ary_shift( parts );
- VALUE name = rb_ary_join( parts, colon );
- obj = rb_funcall( cDomainType, s_new, 3, domain, name, val );
- }
- }
- }
- val = obj;
- }
+ VALUE type_re, proc;
- return val;
+ rb_scan_args(argc, argv, "1&", &type_re, &proc);
+ syck_loader_add_type_family( self, rb_str_new2( RUBY_DOMAIN ), type_re, proc );
+ return Qnil;
}
/*
- * YAML::Syck::Resolver#tagurize
+ * YAML::Syck::Loader.add_private_type
*/
VALUE
-syck_resolver_tagurize( self, val )
- VALUE self, val;
+syck_loader_add_private_type( argc, argv, self )
+ int argc;
+ VALUE *argv;
+ VALUE self;
{
- VALUE tmp = rb_check_string_type(val);
+ VALUE type_re, proc, priv_types;
- if ( !NIL_P(tmp) )
- {
- char *taguri;
- val = tmp;
- taguri = syck_type_id_to_uri( RSTRING(val)->ptr );
- return rb_str_new2( taguri );
- }
+ rb_scan_args(argc, argv, "1&", &type_re, &proc);
- return val;
+ priv_types = rb_attr_get(self, s_private_types);
+ rb_hash_aset( priv_types, type_re, proc );
+ return Qnil;
}
/*
- * YAML::Syck::DefaultResolver#detect_implicit
+ * YAML::Syck::Loader#detect
*/
VALUE
-syck_defaultresolver_detect_implicit( self, val )
+syck_loader_detect_implicit( self, val )
VALUE self, val;
{
char *type_id;
- VALUE tmp = rb_check_string_type(val);
- if ( !NIL_P(tmp) )
+ if ( TYPE(val) == T_STRING )
{
- val = tmp;
type_id = syck_match_implicit( RSTRING(val)->ptr, RSTRING(val)->len );
return rb_str_new2( type_id );
}
@@ -1216,98 +1036,129 @@ syck_defaultresolver_detect_implicit( self, val )
}
/*
- * YAML::Syck::DefaultResolver#node_import
+ * iterator to search a type hash for a match.
*/
-VALUE
-syck_defaultresolver_node_import( self, node )
- VALUE self, node;
-{
- SyckNode *n;
- VALUE obj;
- Data_Get_Struct( node, SyckNode, n );
- if ( !yaml_org_handler( n, &obj ) )
- {
- obj = rb_funcall( self, s_transfer, 2, rb_str_new2( n->type_id ), obj );
- }
- return obj;
+static VALUE
+transfer_find_i(entry, col)
+ VALUE entry, col;
+{
+ VALUE key = rb_ary_entry( entry, 0 );
+ VALUE tid = rb_ary_entry( col, 0 );
+ if ( rb_respond_to( key, s_match ) )
+ {
+ VALUE match = rb_funcall( key, rb_intern("match"), 1, tid );
+ if ( ! NIL_P( match ) )
+ {
+ rb_ary_push( col, rb_ary_entry( entry, 1 ) );
+ rb_iter_break();
+ }
+ }
+ return Qnil;
}
/*
- * YAML::Syck::GenericResolver#node_import
+ * YAML::Syck::Loader#transfer
*/
VALUE
-syck_genericresolver_node_import( self, node )
- VALUE self, node;
+syck_loader_transfer( self, type, val )
+ VALUE self, type, val;
{
- SyckNode *n;
- int i = 0;
- VALUE t = Qnil, obj = Qnil, v = Qnil, style = Qnil;
- Data_Get_Struct(node, SyckNode, n);
+ char *taguri = NULL;
- if ( n->type_id != NULL )
+ if (NIL_P(type) || !RSTRING(type)->ptr || RSTRING(type)->len == 0)
{
- t = rb_str_new2(n->type_id);
+ /*
+ * Empty transfer, detect type
+ */
+ if ( TYPE(val) == T_STRING )
+ {
+ StringValue(val);
+ taguri = syck_match_implicit( RSTRING(val)->ptr, RSTRING(val)->len );
+ taguri = syck_taguri( YAML_DOMAIN, taguri, strlen( taguri ) );
+ }
+ }
+ else
+ {
+ taguri = syck_type_id_to_uri( RSTRING(type)->ptr );
}
- switch (n->kind)
+ if ( taguri != NULL )
{
- case syck_str_kind:
+ int transferred = 0;
+ VALUE scheme, name, type_hash, domain = Qnil, type_proc = Qnil;
+ VALUE type_uri = rb_str_new2( taguri );
+ VALUE str_taguri = rb_str_new2("tag");
+ VALUE str_xprivate = rb_str_new2("x-private");
+ VALUE str_yaml_domain = rb_str_new2(YAML_DOMAIN);
+ VALUE parts = rb_str_split( type_uri, ":" );
+
+ scheme = rb_ary_shift( parts );
+
+ if ( rb_str_cmp( scheme, str_xprivate ) == 0 )
{
- v = rb_str_new( n->data.str->ptr, n->data.str->len );
- if ( n->data.str->style == scalar_1quote )
- {
- style = sym_1quote;
- }
- else if ( n->data.str->style == scalar_2quote )
- {
- style = sym_2quote;
- }
- else if ( n->data.str->style == scalar_fold )
- {
- style = sym_fold;
- }
- else if ( n->data.str->style == scalar_literal )
- {
- style = sym_literal;
- }
- else if ( n->data.str->style == scalar_plain )
+ name = rb_ary_join( parts, rb_str_new2( ":" ) );
+ type_hash = rb_attr_get(self, s_private_types);
+ }
+ else if ( rb_str_cmp( scheme, str_taguri ) == 0 )
+ {
+ domain = rb_ary_shift( parts );
+ name = rb_ary_join( parts, rb_str_new2( ":" ) );
+ type_hash = rb_attr_get(self, s_families);
+ type_hash = rb_hash_aref(type_hash, domain);
+
+ /*
+ * Route yaml.org types through the transfer
+ * method here in this extension
+ */
+ if ( rb_str_cmp( domain, str_yaml_domain ) == 0 )
{
- style = sym_plain;
+ SyckNode *n = rb_new_syck_node(val, name);
+ if ( n != NULL )
+ {
+ transferred = yaml_org_handler(n, &val);
+ S_FREE( n );
+ }
}
- obj = rb_funcall( cScalar, s_new, 3, t, v, style );
+
+ }
+ else
+ {
+ rb_raise(rb_eTypeError, "invalid typing scheme: %s given",
+ scheme);
}
- break;
- case syck_seq_kind:
- rb_iv_set(obj, "@kind", sym_seq);
- v = rb_ary_new2( syck_seq_count( n ) );
- for ( i = 0; i < syck_seq_count( n ); i++ )
+ if ( ! transferred )
+ {
+ if ( rb_obj_is_instance_of( type_hash, rb_cHash ) )
{
- rb_ary_store( v, i, syck_seq_read( n, i ) );
+ type_proc = rb_hash_aref( type_hash, name );
+ if ( NIL_P( type_proc ) )
+ {
+ VALUE col = rb_ary_new();
+ rb_ary_push( col, name );
+ rb_iterate(rb_each, type_hash, transfer_find_i, col );
+ name = rb_ary_shift( col );
+ type_proc = rb_ary_shift( col );
+ }
}
- if ( n->data.list->style == seq_inline )
- {
- style = sym_inline;
- }
- obj = rb_funcall( cSeq, s_new, 3, t, v, style );
- break;
- case syck_map_kind:
- rb_iv_set(obj, "@kind", sym_map);
- v = rb_hash_new();
- for ( i = 0; i < syck_map_count( n ); i++ )
+ if ( rb_respond_to( type_proc, s_call ) )
{
- rb_hash_aset( v, syck_map_read( n, map_key, i ), syck_map_read( n, map_value, i ) );
+ val = rb_funcall(type_proc, s_call, 2, type_uri, val);
}
- if ( n->data.pairs->style == map_inline )
+ else if ( rb_str_cmp( scheme, str_xprivate ) == 0 )
{
- style = sym_inline;
- }
- obj = rb_funcall( cMap, s_new, 3, t, v, style );
- break;
+ val = rb_funcall(cPrivateType, s_new, 2, name, val);
+ }
+ else
+ {
+ val = rb_funcall(cDomainType, s_new, 3, domain, name, val);
+ }
+ transferred = 1;
+ }
}
- return obj;
+ return val;
}
/*
@@ -1317,7 +1168,7 @@ VALUE
syck_badalias_initialize( self, val )
VALUE self, val;
{
- rb_iv_set( self, "@name", val );
+ rb_ivar_set( self, s_name, val );
return self;
}
@@ -1335,461 +1186,60 @@ syck_badalias_cmp( alias1, alias2 )
}
/*
- * YAML::DomainType.initialize
+ * YAML::Syck::DomainType.initialize
*/
VALUE
syck_domaintype_initialize( self, domain, type_id, val )
- VALUE self, domain, type_id, val;
-{
- rb_iv_set( self, "@domain", domain );
- rb_iv_set( self, "@type_id", type_id );
- rb_iv_set( self, "@value", val );
- return self;
-}
-
-/*
- * YAML::Object.initialize
- */
-VALUE
-syck_yobject_initialize( self, klass, ivars )
- VALUE self, klass, ivars;
+ VALUE self, type_id, val;
{
- rb_iv_set( self, "@class", klass );
- rb_iv_set( self, "@ivars", ivars );
+ rb_ivar_set( self, s_domain, domain );
+ rb_ivar_set( self, s_type_id, type_id );
+ rb_ivar_set( self, s_value, val );
return self;
}
/*
- * YAML::PrivateType.initialize
+ * YAML::Syck::PrivateType.initialize
*/
VALUE
syck_privatetype_initialize( self, type_id, val )
VALUE self, type_id, val;
{
- rb_iv_set( self, "@type_id", type_id );
- rb_iv_set( self, "@value", val );
+ rb_ivar_set( self, s_type_id, type_id );
+ rb_ivar_set( self, s_value, val );
return self;
}
/*
- * Mark node contents.
- */
-static void
-syck_node_mark( n )
- SyckNode *n;
-{
- int i;
- switch ( n->kind )
- {
- case syck_seq_kind:
- for ( i = 0; i < n->data.list->idx; i++ )
- {
- rb_gc_mark( syck_seq_read( n, i ) );
- }
- break;
-
- case syck_map_kind:
- for ( i = 0; i < n->data.pairs->idx; i++ )
- {
- rb_gc_mark( syck_map_read( n, map_key, i ) );
- rb_gc_mark( syck_map_read( n, map_value, i ) );
- }
- break;
- }
-}
-
-/*
- * Don't free Ruby data, Ruby will do that
- */
-void
-rb_syck_free_node( SyckNode *n )
-{
- switch ( n->kind )
- {
- case syck_str_kind:
- S_FREE( n->data.str );
- n->data.str = NULL;
- break;
-
- case syck_seq_kind:
- if ( n->data.list != NULL )
- {
- S_FREE( n->data.list->items );
- S_FREE( n->data.list );
- n->data.list = NULL;
- }
- break;
-
- case syck_map_kind:
- if ( n->data.pairs != NULL )
- {
- S_FREE( n->data.pairs->keys );
- S_FREE( n->data.pairs->values );
- S_FREE( n->data.pairs );
- n->data.pairs = NULL;
- }
- break;
- }
-
- S_FREE( n );
-}
-
-/*
- * YAML::Syck::Scalar.allocate
- */
-VALUE
-syck_scalar_alloc( class )
- VALUE class;
-{
- SyckNode *node = syck_alloc_str();
- VALUE obj = Data_Wrap_Struct( class, syck_node_mark, rb_syck_free_node, node );
- node->id = obj;
- return obj;
-}
-
-/*
- * YAML::Syck::Scalar.initialize
- */
-VALUE
-syck_scalar_initialize( self, type_id, val, style )
- VALUE self, type_id, val, style;
-{
- rb_iv_set( self, "@kind", sym_scalar );
- rb_funcall( self, s_type_id_set, 1, type_id );
- rb_funcall( self, s_value_set, 1, val );
- rb_funcall( self, s_style_set, 1, style );
- return self;
-}
-
-/*
- * YAML::Syck::Scalar.style=
- */
-VALUE
-syck_scalar_style_set( self, style )
- VALUE self, style;
-{
- SyckNode *node;
- Data_Get_Struct( self, SyckNode, node );
-
- if ( NIL_P( style ) )
- {
- node->data.str->style = scalar_none;
- }
- else if ( style == sym_1quote )
- {
- node->data.str->style = scalar_1quote;
- }
- else if ( style == sym_2quote )
- {
- node->data.str->style = scalar_2quote;
- }
- else if ( style == sym_fold )
- {
- node->data.str->style = scalar_fold;
- }
- else if ( style == sym_literal )
- {
- node->data.str->style = scalar_literal;
- }
- else if ( style == sym_plain )
- {
- node->data.str->style = scalar_plain;
- }
-
- rb_iv_set( self, "@style", style );
- return self;
-}
-
-/*
- * YAML::Syck::Scalar.value=
- */
-VALUE
-syck_scalar_value_set( self, val )
- VALUE self, val;
-{
- SyckNode *node;
- Data_Get_Struct( self, SyckNode, node );
-
- StringValue( val );
- node->data.str->ptr = RSTRING(val)->ptr;
- node->data.str->len = RSTRING(val)->len;
- node->data.str->style = scalar_none;
-
- rb_iv_set( self, "@value", val );
- return val;
-}
-
-/*
- * YAML::Syck::Seq.allocate
- */
-VALUE
-syck_seq_alloc( class )
- VALUE class;
-{
- SyckNode *node;
- VALUE obj;
- node = syck_alloc_seq();
- obj = Data_Wrap_Struct( class, syck_node_mark, rb_syck_free_node, node );
- node->id = obj;
- return obj;
-}
-
-/*
- * YAML::Syck::Seq.initialize
- */
-VALUE
-syck_seq_initialize( self, type_id, val, style )
- VALUE self, type_id, val, style;
-{
- SyckNode *node;
- Data_Get_Struct( self, SyckNode, node );
-
- rb_iv_set( self, "@kind", sym_seq );
- rb_funcall( self, s_type_id_set, 1, type_id );
- rb_funcall( self, s_value_set, 1, val );
- rb_funcall( self, s_style_set, 1, style );
- return self;
-}
-
-/*
- * YAML::Syck::Seq.value=
- */
-VALUE
-syck_seq_value_set( self, val )
- VALUE self, val;
-{
- SyckNode *node;
- Data_Get_Struct( self, SyckNode, node );
-
- val = rb_check_array_type( val );
- if ( !NIL_P( val ) ) {
- int i;
- syck_seq_empty( node );
- for ( i = 0; i < RARRAY( val )->len; i++ )
- {
- syck_seq_add( node, rb_ary_entry(val, i) );
- }
- }
-
- rb_iv_set( self, "@value", val );
- return val;
-}
-
-/*
- * YAML::Syck::Seq.add
- */
-VALUE
-syck_seq_add_m( self, val )
- VALUE self, val;
-{
- SyckNode *node;
- VALUE emitter = rb_ivar_get( self, s_emitter );
- Data_Get_Struct( self, SyckNode, node );
-
- if ( rb_respond_to( emitter, s_node_export ) ) {
- val = rb_funcall( emitter, s_node_export, 1, val );
- }
- syck_seq_add( node, val );
- rb_ary_push( rb_ivar_get( self, s_value ), val );
-
- return self;
-}
-
-/*
- * YAML::Syck::Seq.style=
- */
-VALUE
-syck_seq_style_set( self, style )
- VALUE self, style;
-{
- SyckNode *node;
- Data_Get_Struct( self, SyckNode, node );
-
- if ( style == sym_inline )
- {
- node->data.list->style = seq_inline;
- }
- else
- {
- node->data.list->style = seq_none;
- }
-
- rb_iv_set( self, "@style", style );
- return self;
-}
-
-/*
- * YAML::Syck::Map.allocate
- */
-VALUE
-syck_map_alloc( class )
- VALUE class;
-{
- SyckNode *node;
- VALUE obj;
- node = syck_alloc_map();
- obj = Data_Wrap_Struct( class, syck_node_mark, rb_syck_free_node, node );
- node->id = obj;
- return obj;
-}
-
-/*
- * YAML::Syck::Map.initialize
- */
-VALUE
-syck_map_initialize( self, type_id, val, style )
- VALUE self, type_id, val, style;
-{
- SyckNode *node;
- Data_Get_Struct( self, SyckNode, node );
-
- if ( !NIL_P( val ) )
- {
- VALUE hsh = rb_check_convert_type(val, T_HASH, "Hash", "to_hash");
- VALUE keys;
- int i;
- if ( NIL_P(hsh) )
- {
- rb_raise( rb_eTypeError, "wrong argument type" );
- }
-
- keys = rb_funcall( hsh, s_keys, 0 );
- for ( i = 0; i < RARRAY(keys)->len; i++ )
- {
- VALUE key = rb_ary_entry(keys, i);
- syck_map_add( node, key, rb_hash_aref(hsh, key) );
- }
- }
-
- rb_iv_set( self, "@kind", sym_seq );
- rb_funcall( self, s_type_id_set, 1, type_id );
- rb_funcall( self, s_value_set, 1, val );
- rb_funcall( self, s_style_set, 1, style );
- return self;
-}
-
-/*
- * YAML::Syck::Map.value=
- */
-VALUE
-syck_map_value_set( self, val )
- VALUE self, val;
-{
- SyckNode *node;
- Data_Get_Struct( self, SyckNode, node );
-
- if ( !NIL_P( val ) )
- {
- VALUE hsh = rb_check_convert_type(val, T_HASH, "Hash", "to_hash");
- VALUE keys;
- int i;
- if ( NIL_P(hsh) )
- {
- rb_raise( rb_eTypeError, "wrong argument type" );
- }
-
- syck_map_empty( node );
- keys = rb_funcall( hsh, s_keys, 0 );
- for ( i = 0; i < RARRAY(keys)->len; i++ )
- {
- VALUE key = rb_ary_entry(keys, i);
- syck_map_add( node, key, rb_hash_aref(hsh, key) );
- }
- }
-
- rb_iv_set( self, "@value", val );
- return val;
-}
-
-/*
- * YAML::Syck::Map.add
- */
-VALUE
-syck_map_add_m( self, key, val )
- VALUE self, key, val;
-{
- SyckNode *node;
- VALUE emitter = rb_ivar_get( self, s_emitter );
- Data_Get_Struct( self, SyckNode, node );
-
- if ( rb_respond_to( emitter, s_node_export ) ) {
- key = rb_funcall( emitter, s_node_export, 1, key );
- val = rb_funcall( emitter, s_node_export, 1, val );
- }
- syck_map_add( node, key, val );
- rb_hash_aset( rb_ivar_get( self, s_value ), key, val );
-
- return self;
-}
-
-/*
- * YAML::Syck::Map.style=
+ * YAML::Syck::Node.initialize
*/
VALUE
-syck_map_style_set( self, style )
- VALUE self, style;
+syck_node_initialize( self, type_id, val )
+ VALUE self, type_id, val;
{
- SyckNode *node;
- Data_Get_Struct( self, SyckNode, node );
-
- if ( style == sym_inline )
- {
- node->data.pairs->style = map_inline;
- }
- else
- {
- node->data.pairs->style = map_none;
- }
-
- rb_iv_set( self, "@style", style );
+ rb_ivar_set( self, s_type_id, type_id );
+ rb_ivar_set( self, s_value, val );
return self;
}
-/*
- * Cloning method for all node types
- */
VALUE
-syck_node_init_copy( copy, orig )
- VALUE copy, orig;
+syck_node_thash( entry, t )
+ VALUE entry, t;
{
- SyckNode *copy_n;
- SyckNode *orig_n;
-
- if ( copy == orig )
- return copy;
-
- if ( TYPE( orig ) != T_DATA ||
- RDATA( orig )->dfree != ( RUBY_DATA_FUNC )rb_syck_free_node )
- {
- rb_raise( rb_eTypeError, "wrong argument type" );
- }
-
- Data_Get_Struct( orig, SyckNode, orig_n );
- Data_Get_Struct( copy, SyckNode, copy_n );
- MEMCPY( copy_n, orig_n, SyckNode, 1 );
- return copy;
+ VALUE key, val;
+ key = rb_ary_entry( entry, 0 );
+ val = syck_node_transform( rb_ary_entry( rb_ary_entry( entry, 1 ), 1 ) );
+ rb_hash_aset( t, key, val );
+ return Qnil;
}
-/*
- * YAML::Syck::Node#type_id=
- */
VALUE
-syck_node_type_id_set( self, type_id )
- VALUE self, type_id;
+syck_node_ahash( entry, t )
+ VALUE entry, t;
{
- SyckNode *node;
- Data_Get_Struct( self, SyckNode, node );
-
- if ( node->type_id != NULL ) S_FREE( node->type_id );
-
- if ( NIL_P( type_id ) ) {
- node->type_id = NULL;
- } else {
- node->type_id = StringValuePtr( type_id );
- }
-
- rb_iv_set( self, "@type_id", type_id );
- return type_id;
+ VALUE val = syck_node_transform( entry );
+ rb_ary_push( t, val );
+ return Qnil;
}
/*
@@ -1799,102 +1249,24 @@ VALUE
syck_node_transform( self )
VALUE self;
{
- VALUE t;
- SyckNode *n;
- SyckNode *orig_n;
- Data_Get_Struct(self, SyckNode, orig_n);
-
- switch (orig_n->kind)
+ VALUE t = Qnil;
+ VALUE type_id = rb_attr_get( self, s_type_id );
+ VALUE val = rb_attr_get( self, s_value );
+ if ( rb_obj_is_instance_of( val, rb_cHash ) )
{
- case syck_map_kind:
- {
- int i;
- n = syck_alloc_map();
- for ( i = 0; i < orig_n->data.pairs->idx; i++ )
- {
- syck_map_add( n, rb_funcall( syck_map_read( orig_n, map_key, i ), s_transform, 0 ),
- rb_funcall( syck_map_read( orig_n, map_value, i ), s_transform, 0 ) );
- }
- }
- break;
-
- case syck_seq_kind:
- {
- int i;
- n = syck_alloc_seq();
- for ( i = 0; i < orig_n->data.list->idx; i++ )
- {
- syck_seq_add( n, rb_funcall( syck_seq_read( orig_n, i ), s_transform, 0 ) );
- }
- }
- break;
-
- case syck_str_kind:
- n = syck_new_str2( orig_n->data.str->ptr, orig_n->data.str->len, orig_n->data.str->style );
- break;
+ t = rb_hash_new();
+ rb_iterate( rb_each, val, syck_node_thash, t );
}
-
- if ( orig_n->type_id != NULL )
+ else if ( rb_obj_is_instance_of( val, rb_cArray ) )
{
- n->type_id = syck_strndup( orig_n->type_id, strlen( orig_n->type_id ) );
+ t = rb_ary_new();
+ rb_iterate( rb_each, val, syck_node_ahash, t );
}
- if ( orig_n->anchor != NULL )
+ else
{
- n->anchor = syck_strndup( orig_n->anchor, strlen( orig_n->anchor ) );
- }
- t = Data_Wrap_Struct( cNode, NULL, NULL, n );
- n->id = t;
- t = rb_funcall( oDefaultResolver, s_node_import, 1, t );
- syck_free_node( n );
- return t;
-}
-
-/*
- * Emitter callback: assembles YAML document events from
- * Ruby symbols. This is a brilliant way to do it.
- * No one could possibly object.
- */
-void
-rb_syck_emitter_handler(e, data)
- SyckEmitter *e;
- st_data_t data;
-{
- SyckNode *n;
- Data_Get_Struct((VALUE)data, SyckNode, n);
-
- switch (n->kind)
- {
- case syck_map_kind:
- {
- int i;
- syck_emit_map( e, n->type_id, n->data.pairs->style );
- for ( i = 0; i < n->data.pairs->idx; i++ )
- {
- syck_emit_item( e, syck_map_read( n, map_key, i ) );
- syck_emit_item( e, syck_map_read( n, map_value, i ) );
- }
- syck_emit_end( e );
- }
- break;
-
- case syck_seq_kind:
- {
- int i;
- syck_emit_seq( e, n->type_id, n->data.list->style );
- for ( i = 0; i < n->data.list->idx; i++ )
- {
- syck_emit_item( e, syck_seq_read( n, i ) );
- }
- syck_emit_end( e );
- }
- break;
-
- case syck_str_kind:
- {
- syck_emit_scalar( e, n->type_id, n->data.str->style, 0, 0, 0, n->data.str->ptr, n->data.str->len );
- }
- break;
+ t = val;
}
+ return rb_funcall( oDefaultLoader, s_transfer, 2, type_id, t );
}
/*
@@ -1906,9 +1278,8 @@ rb_syck_output_handler( emitter, str, len )
char *str;
long len;
{
- struct emitter_xtra *bonus = (struct emitter_xtra *)emitter->bonus;
- VALUE dest = bonus->port;
- if (TYPE(dest) == T_STRING) {
+ VALUE dest = (VALUE)emitter->bonus;
+ if ( rb_respond_to( dest, s_to_str ) ) {
rb_str_cat( dest, str, len );
} else {
rb_io_write( dest, rb_str_new( str, len ) );
@@ -1916,251 +1287,152 @@ rb_syck_output_handler( emitter, str, len )
}
/*
- * Helper function for marking nodes in the anchor
- * symbol table.
- */
-void
-syck_out_mark( emitter, node )
- VALUE emitter, node;
-{
- SyckEmitter *emitterPtr;
- struct emitter_xtra *bonus;
- Data_Get_Struct(emitter, SyckEmitter, emitterPtr);
- bonus = (struct emitter_xtra *)emitterPtr->bonus;
- rb_ivar_set( node, s_emitter, emitter );
- /* syck_emitter_mark_node( emitterPtr, (st_data_t)node ); */
- if ( !NIL_P( bonus->oid ) ) {
- rb_hash_aset( bonus->data, bonus->oid, node );
- }
-}
-
-/*
* Mark emitter values.
*/
static void
syck_mark_emitter(emitter)
SyckEmitter *emitter;
{
- struct emitter_xtra *bonus;
+ rb_gc_mark(emitter->ignore_id);
if ( emitter->bonus != NULL )
{
- bonus = (struct emitter_xtra *)emitter->bonus;
- rb_gc_mark( bonus->data );
- rb_gc_mark( bonus->port );
+ rb_gc_mark( (VALUE)emitter->bonus );
}
}
/*
- * Free the emitter and any bonus attachment.
- */
-void
-rb_syck_free_emitter(e)
- SyckEmitter *e;
-{
- struct emitter_xtra *bonus = (struct emitter_xtra *)e->bonus;
- if ( bonus != NULL ) S_FREE( bonus );
- syck_free_emitter(e);
-}
-
-/*
- * YAML::Syck::Emitter.allocate
+ * YAML::Syck::Emitter.new
*/
-VALUE syck_emitter_s_alloc _((VALUE));
VALUE
-syck_emitter_s_alloc(class)
- VALUE class;
-{
- VALUE pobj;
- SyckEmitter *emitter = syck_new_emitter();
-
- pobj = Data_Wrap_Struct( class, syck_mark_emitter, rb_syck_free_emitter, emitter );
- syck_emitter_handler( emitter, rb_syck_emitter_handler );
- syck_output_handler( emitter, rb_syck_output_handler );
-
- rb_ivar_set( pobj, s_out, rb_funcall( cOut, s_new, 1, pobj ) );
- return pobj;
-}
-
-/*
- * YAML::Syck::Emitter.reset( options )
- */
-VALUE
-syck_emitter_reset( argc, argv, self )
+syck_emitter_new(argc, argv, class)
int argc;
VALUE *argv;
- VALUE self;
+ VALUE class;
{
- VALUE options, tmp;
- SyckEmitter *emitter;
- struct emitter_xtra *bonus;
- volatile VALUE hash; /* protect from GC */
-
- Data_Get_Struct(self, SyckEmitter, emitter);
- bonus = (struct emitter_xtra *)emitter->bonus;
- if ( bonus != NULL ) S_FREE( bonus );
+ VALUE pobj, options, init_argv[1];
+ SyckEmitter *emitter = syck_new_emitter();
+ rb_scan_args(argc, argv, "01", &options);
- bonus = S_ALLOC_N( struct emitter_xtra, 1 );
- bonus->port = rb_str_new2( "" );
- bonus->data = hash = rb_hash_new();
+ pobj = Data_Wrap_Struct( class, syck_mark_emitter, syck_free_emitter, emitter );
+ syck_emitter_ignore_id( emitter, Qnil );
+ syck_emitter_handler( emitter, rb_syck_output_handler );
+ emitter->bonus = (void *)rb_str_new2( "" );
- if (rb_scan_args(argc, argv, "01", &options) == 0)
+ if ( ! rb_obj_is_instance_of( options, rb_cHash ) )
{
options = rb_hash_new();
- rb_ivar_set(self, s_options, options);
- }
- else if ( !NIL_P(tmp = rb_check_string_type(options)) )
- {
- bonus->port = tmp;
- }
- else if ( rb_respond_to( options, s_write ) )
- {
- bonus->port = options;
- }
- else
- {
- Check_Type(options, T_HASH);
- rb_ivar_set(self, s_options, options);
}
-
- emitter->headless = 1;
- emitter->bonus = (void *)bonus;
- rb_ivar_set(self, s_level, INT2FIX(0));
- rb_ivar_set(self, s_resolver, Qnil);
- return self;
+ init_argv[0] = options;
+ rb_obj_call_init(pobj, 1, init_argv);
+ return pobj;
}
/*
- * YAML::Syck::Emitter.emit( object_id ) { |out| ... }
+ * YAML::Syck::Emitter.initialize( options )
*/
-VALUE
-syck_emitter_emit( argc, argv, self )
- int argc;
- VALUE *argv;
- VALUE self;
+static VALUE
+syck_emitter_initialize( self, options )
+ VALUE self, options;
{
- VALUE oid, proc;
- char *anchor_name;
- SyckEmitter *emitter;
- struct emitter_xtra *bonus;
- SYMID symple;
- int level = FIX2INT(rb_ivar_get(self, s_level)) + 1;
- rb_ivar_set(self, s_level, INT2FIX(level));
-
- rb_scan_args(argc, argv, "1&", &oid, &proc);
- Data_Get_Struct(self, SyckEmitter, emitter);
- bonus = (struct emitter_xtra *)emitter->bonus;
-
- /* Calculate anchors, normalize nodes, build a simpler symbol table */
- bonus->oid = oid;
- if ( !NIL_P( oid ) && RTEST( rb_funcall( bonus->data, s_haskey, 1, oid ) ) ) {
- symple = rb_hash_aref( bonus->data, oid );
- } else {
- symple = rb_funcall( proc, s_call, 1, rb_ivar_get( self, s_out ) );
- }
- syck_emitter_mark_node( emitter, (st_data_t)symple );
-
- /* Second pass, build emitted string */
- level -= 1;
- rb_ivar_set(self, s_level, INT2FIX(level));
- if ( level == 0 )
- {
- syck_emit(emitter, (st_data_t)symple);
- syck_emitter_flush(emitter, 0);
-
- return bonus->port;
- }
-
- return symple;
+ rb_ivar_set(self, s_options, options);
+ return self;
}
/*
- * YAML::Syck::Emitter#node_export
+ * YAML::Syck::Emitter.level
*/
VALUE
-syck_emitter_node_export( self, node )
- VALUE self, node;
+syck_emitter_level_m( self )
+ VALUE self;
{
- return rb_funcall( node, s_to_yaml, 1, self );
+ SyckEmitter *emitter;
+
+ Data_Get_Struct(self, SyckEmitter, emitter);
+ return LONG2NUM( emitter->level );
}
/*
- * YAML::Syck::Emitter#set_resolver
+ * YAML::Syck::Emitter.flush
*/
VALUE
-syck_emitter_set_resolver( self, resolver )
- VALUE self, resolver;
+syck_emitter_flush_m( self )
+ VALUE self;
{
- rb_ivar_set( self, s_resolver, resolver );
+ SyckEmitter *emitter;
+
+ Data_Get_Struct(self, SyckEmitter, emitter);
+ syck_emitter_flush( emitter, 0 );
return self;
}
/*
- * YAML::Syck::Out::initialize
+ * YAML::Syck::Emitter.write( str )
*/
VALUE
-syck_out_initialize( self, emitter )
- VALUE self, emitter;
+syck_emitter_write_m( self, str )
+ VALUE self, str;
{
- rb_ivar_set( self, s_emitter, emitter );
+ SyckEmitter *emitter;
+
+ Data_Get_Struct(self, SyckEmitter, emitter);
+ StringValue(str);
+ syck_emitter_write( emitter, RSTRING(str)->ptr, RSTRING(str)->len );
return self;
}
/*
- * YAML::Syck::Out::map
+ * YAML::Syck::Emitter.simple( str )
*/
VALUE
-syck_out_map( argc, argv, self )
- int argc;
- VALUE *argv;
- VALUE self;
+syck_emitter_simple_write( self, str )
+ VALUE self, str;
{
- VALUE type_id, style, map;
- if (rb_scan_args(argc, argv, "11", &type_id, &style) == 1) {
- style = Qnil;
- }
- map = rb_funcall( cMap, s_new, 3, type_id, rb_hash_new(), style );
- syck_out_mark( rb_ivar_get( self, s_emitter ), map );
- rb_yield( map );
- return map;
+ SyckEmitter *emitter;
+
+ Data_Get_Struct(self, SyckEmitter, emitter);
+ StringValue(str);
+ syck_emitter_simple( emitter, RSTRING(str)->ptr, RSTRING(str)->len );
+ return self;
}
/*
- * YAML::Syck::Out::seq
+ * YAML::Syck::Emitter.start_object( object_id )
*/
VALUE
-syck_out_seq( argc, argv, self )
- int argc;
- VALUE *argv;
- VALUE self;
+syck_emitter_start_object( self, oid )
+ VALUE self, oid;
{
- VALUE type_id, style, seq;
- if (rb_scan_args(argc, argv, "11", &type_id, &style) == 1) {
- style = Qnil;
+ char *anchor_name;
+ SyckEmitter *emitter;
+
+ Data_Get_Struct(self, SyckEmitter, emitter);
+ anchor_name = syck_emitter_start_obj( emitter, oid );
+
+ if ( anchor_name == NULL )
+ {
+ return Qnil;
}
- seq = rb_funcall( cSeq, s_new, 3, type_id, rb_ary_new(), style );
- syck_out_mark( rb_ivar_get( self, s_emitter ), seq );
- rb_yield( seq );
- return seq;
+
+ return rb_str_new2( anchor_name );
}
/*
- * YAML::Syck::Out::scalar
-syck_out_scalar( self, type_id, str, style )
- VALUE self, type_id, str, style;
+ * YAML::Syck::Emitter.end_object
*/
VALUE
-syck_out_scalar( argc, argv, self )
- int argc;
- VALUE *argv;
+syck_emitter_end_object( self )
VALUE self;
{
- VALUE type_id, str, style, scalar;
- if (rb_scan_args(argc, argv, "21", &type_id, &str, &style) == 2) {
- style = Qnil;
+ SyckEmitter *emitter;
+
+ Data_Get_Struct(self, SyckEmitter, emitter);
+ syck_emitter_end_obj( emitter );
+
+ if ( emitter->level < 0 )
+ {
+ syck_emitter_flush( emitter, 0 );
}
- scalar = rb_funcall( cScalar, s_new, 3, type_id, str, style );
- syck_out_mark( rb_ivar_get( self, s_emitter ), scalar );
- return scalar;
+ return (VALUE)emitter->bonus;
}
/*
@@ -2174,169 +1446,106 @@ Init_syck()
rb_define_const( rb_syck, "VERSION", rb_str_new2( SYCK_VERSION ) );
rb_define_module_function( rb_syck, "compile", rb_syck_compile, 1 );
- /*
- * Global symbols
- */
+ /*
+ * Global symbols
+ */
s_new = rb_intern("new");
s_utc = rb_intern("utc");
s_at = rb_intern("at");
s_to_f = rb_intern("to_f");
s_to_i = rb_intern("to_i");
s_read = rb_intern("read");
+ s_anchors = rb_intern("anchors");
s_binmode = rb_intern("binmode");
s_transfer = rb_intern("transfer");
s_call = rb_intern("call");
s_cmp = rb_intern("<=>");
- s_intern = rb_intern("intern");
- s_update = rb_intern("update");
- s_detect_implicit = rb_intern("detect_implicit");
- s_dup = rb_intern("dup");
+ s_update = rb_intern("update");
+ s_dup = rb_intern("dup");
s_default_set = rb_intern("default=");
- s_match = rb_intern("match");
- s_push = rb_intern("push");
- s_haskey = rb_intern("has_key?");
- s_keys = rb_intern("keys");
- s_node_import = rb_intern("node_import");
- s_tr_bang = rb_intern("tr!");
+ s_match = rb_intern("match");
+ s_keys = rb_intern("keys");
+ s_to_str = rb_intern("to_str");
+ s_tr_bang = rb_intern("tr!");
s_unpack = rb_intern("unpack");
- s_write = rb_intern("write");
- s_tag_read_class = rb_intern( "yaml_tag_read_class" );
- s_tag_subclasses = rb_intern( "yaml_tag_subclasses?" );
- s_emitter = rb_intern( "emitter" );
- s_set_resolver = rb_intern( "set_resolver" );
- s_node_export = rb_intern( "node_export" );
- s_to_yaml = rb_intern( "to_yaml" );
- s_transform = rb_intern( "transform" );
- s_yaml_new = rb_intern("yaml_new");
- s_yaml_initialize = rb_intern("yaml_initialize");
-
- s_tags = rb_intern("@tags");
+
+ s_anchors = rb_intern("@anchors");
+ s_domain = rb_intern("@domain");
+ s_families = rb_intern("@families");
+ s_kind = rb_intern("@kind");
s_name = rb_intern("@name");
s_options = rb_intern("@options");
- s_kind = rb_intern("@kind");
+ s_private_types = rb_intern("@private_types");
s_type_id = rb_intern("@type_id");
- s_type_id_set = rb_intern("type_id=");
- s_resolver = rb_intern("@resolver");
- s_level = rb_intern( "@level" );
- s_style = rb_intern("@style");
- s_style_set = rb_intern("style=");
s_value = rb_intern("@value");
- s_value_set = rb_intern("value=");
- s_out = rb_intern("@out");
- s_input = rb_intern("@input");
- sym_model = ID2SYM(rb_intern("Model"));
- sym_generic = ID2SYM(rb_intern("Generic"));
- sym_bytecode = ID2SYM(rb_intern("bytecode"));
+ sym_model = ID2SYM(rb_intern("Model"));
+ sym_generic = ID2SYM(rb_intern("Generic"));
+ sym_input = ID2SYM(rb_intern("Input"));
+ sym_bytecode = ID2SYM(rb_intern("Bytecode"));
sym_map = ID2SYM(rb_intern("map"));
sym_scalar = ID2SYM(rb_intern("scalar"));
sym_seq = ID2SYM(rb_intern("seq"));
- sym_1quote = ID2SYM(rb_intern("quote1"));
- sym_2quote = ID2SYM(rb_intern("quote2"));
- sym_fold = ID2SYM(rb_intern("fold"));
- sym_literal = ID2SYM(rb_intern("literal"));
- sym_plain = ID2SYM(rb_intern("plain"));
- sym_inline = ID2SYM(rb_intern("inline"));
/*
- * Define YAML::Syck::Resolver class
+ * Define YAML::Syck::Loader class
*/
- cResolver = rb_define_class_under( rb_syck, "Resolver", rb_cObject );
- rb_define_attr( cResolver, "tags", 1, 1 );
- rb_define_method( cResolver, "initialize", syck_resolver_initialize, 0 );
- rb_define_method( cResolver, "add_type", syck_resolver_add_type, 2 );
- rb_define_method( cResolver, "use_types_at", syck_resolver_use_types_at, 1 );
- rb_define_method( cResolver, "detect_implicit", syck_resolver_detect_implicit, 1 );
- rb_define_method( cResolver, "transfer", syck_resolver_transfer, 2 );
- rb_define_method( cResolver, "node_import", syck_resolver_node_import, 1 );
- rb_define_method( cResolver, "tagurize", syck_resolver_tagurize, 1 );
-
- oDefaultResolver = rb_funcall( cResolver, rb_intern( "new" ), 0 );
- rb_define_singleton_method( oDefaultResolver, "node_import", syck_defaultresolver_node_import, 1 );
- rb_define_singleton_method( oDefaultResolver, "detect_implicit", syck_defaultresolver_detect_implicit, 1 );
- rb_define_const( rb_syck, "DefaultResolver", oDefaultResolver );
- oGenericResolver = rb_funcall( cResolver, rb_intern( "new" ), 0 );
- rb_define_singleton_method( oGenericResolver, "node_import", syck_genericresolver_node_import, 1 );
- rb_define_const( rb_syck, "GenericResolver", oGenericResolver );
+ cLoader = rb_define_class_under( rb_syck, "Loader", rb_cObject );
+ rb_define_attr( cLoader, "families", 1, 1 );
+ rb_define_attr( cLoader, "private_types", 1, 1 );
+ rb_define_attr( cLoader, "anchors", 1, 1 );
+ rb_define_method( cLoader, "initialize", syck_loader_initialize, 0 );
+ rb_define_method( cLoader, "add_domain_type", syck_loader_add_domain_type, -1 );
+ rb_define_method( cLoader, "add_builtin_type", syck_loader_add_builtin_type, -1 );
+ rb_define_method( cLoader, "add_ruby_type", syck_loader_add_ruby_type, -1 );
+ rb_define_method( cLoader, "add_private_type", syck_loader_add_private_type, -1 );
+ rb_define_method( cLoader, "bufsize=", syck_parser_bufsize_set, 1 );
+ rb_define_method( cLoader, "bufsize", syck_parser_bufsize_get, 0 );
+ rb_define_method( cLoader, "detect_implicit", syck_loader_detect_implicit, 1 );
+ rb_define_method( cLoader, "transfer", syck_loader_transfer, 2 );
+
+ oDefaultLoader = rb_funcall( cLoader, rb_intern( "new" ), 0 );
+ rb_define_const( rb_syck, "DefaultLoader", oDefaultLoader );
/*
* Define YAML::Syck::Parser class
*/
cParser = rb_define_class_under( rb_syck, "Parser", rb_cObject );
rb_define_attr( cParser, "options", 1, 1 );
- rb_define_attr( cParser, "resolver", 1, 1 );
- rb_define_attr( cParser, "input", 1, 1 );
- rb_define_alloc_func( cParser, syck_parser_s_alloc );
- rb_define_method(cParser, "initialize", syck_parser_initialize, -1 );
- rb_define_method(cParser, "bufsize=", syck_parser_bufsize_set, 1 );
- rb_define_method(cParser, "bufsize", syck_parser_bufsize_get, 0 );
+ rb_define_singleton_method( cParser, "new", syck_parser_new, -1 );
+ rb_define_method(cParser, "initialize", syck_parser_initialize, 1);
rb_define_method(cParser, "load", syck_parser_load, -1);
rb_define_method(cParser, "load_documents", syck_parser_load_documents, -1);
- rb_define_method(cParser, "set_resolver", syck_parser_set_resolver, 1);
/*
* Define YAML::Syck::Node class
*/
cNode = rb_define_class_under( rb_syck, "Node", rb_cObject );
- rb_define_method( cNode, "initialize_copy", syck_node_init_copy, 1 );
- rb_define_attr( cNode, "emitter", 1, 1 );
- rb_define_attr( cNode, "resolver", 1, 1 );
- rb_define_attr( cNode, "kind", 1, 0 );
- rb_define_attr( cNode, "type_id", 1, 0 );
- rb_define_attr( cNode, "value", 1, 0 );
- rb_define_method( cNode, "type_id=", syck_node_type_id_set, 1 );
+ rb_define_attr( cNode, "kind", 1, 1 );
+ rb_define_attr( cNode, "type_id", 1, 1 );
+ rb_define_attr( cNode, "value", 1, 1 );
+ rb_define_attr( cNode, "anchor", 1, 1 );
+ rb_define_method( cNode, "initialize", syck_node_initialize, 2);
rb_define_method( cNode, "transform", syck_node_transform, 0);
/*
- * Define YAML::Syck::Scalar, YAML::Syck::Seq, YAML::Syck::Map --
- * all are the publicly usable variants of YAML::Syck::Node
- */
- cScalar = rb_define_class_under( rb_syck, "Scalar", cNode );
- rb_define_alloc_func( cScalar, syck_scalar_alloc );
- rb_define_attr( cNode, "value", 1, 0 );
- rb_define_method( cScalar, "initialize", syck_scalar_initialize, 3 );
- rb_define_method( cScalar, "value=", syck_scalar_value_set, 1 );
- rb_define_method( cScalar, "style=", syck_scalar_style_set, 1 );
- cSeq = rb_define_class_under( rb_syck, "Seq", cNode );
- rb_define_alloc_func( cSeq, syck_seq_alloc );
- rb_define_method( cSeq, "initialize", syck_seq_initialize, 3 );
- rb_define_method( cSeq, "value=", syck_seq_value_set, 1 );
- rb_define_method( cSeq, "add", syck_seq_add_m, 1 );
- rb_define_method( cSeq, "style=", syck_seq_style_set, 1 );
- cMap = rb_define_class_under( rb_syck, "Map", cNode );
- rb_define_alloc_func( cMap, syck_map_alloc );
- rb_define_method( cMap, "initialize", syck_map_initialize, 3 );
- rb_define_method( cMap, "value=", syck_map_value_set, 1 );
- rb_define_method( cMap, "add", syck_map_add_m, 2 );
- rb_define_method( cMap, "style=", syck_map_style_set, 1 );
-
- /*
- * Define YAML::PrivateType class
+ * Define YAML::Syck::PrivateType class
*/
- cPrivateType = rb_define_class_under( rb_yaml, "PrivateType", rb_cObject );
+ cPrivateType = rb_define_class_under( rb_syck, "PrivateType", rb_cObject );
rb_define_attr( cPrivateType, "type_id", 1, 1 );
rb_define_attr( cPrivateType, "value", 1, 1 );
rb_define_method( cPrivateType, "initialize", syck_privatetype_initialize, 2);
/*
- * Define YAML::DomainType class
+ * Define YAML::Syck::DomainType class
*/
- cDomainType = rb_define_class_under( rb_yaml, "DomainType", rb_cObject );
+ cDomainType = rb_define_class_under( rb_syck, "DomainType", rb_cObject );
rb_define_attr( cDomainType, "domain", 1, 1 );
rb_define_attr( cDomainType, "type_id", 1, 1 );
rb_define_attr( cDomainType, "value", 1, 1 );
rb_define_method( cDomainType, "initialize", syck_domaintype_initialize, 3);
/*
- * Define YAML::Object class
- */
- cYObject = rb_define_class_under( rb_yaml, "Object", rb_cObject );
- rb_define_attr( cYObject, "class", 1, 1 );
- rb_define_attr( cYObject, "ivars", 1, 1 );
- rb_define_method( cYObject, "initialize", syck_yobject_initialize, 2);
- rb_define_method( cYObject, "yaml_initialize", syck_yobject_initialize, 2);
-
- /*
* Define YAML::Syck::BadAlias class
*/
cBadAlias = rb_define_class_under( rb_syck, "BadAlias", rb_cObject );
@@ -2345,36 +1554,28 @@ Init_syck()
rb_define_method( cBadAlias, "<=>", syck_badalias_cmp, 1);
rb_include_module( cBadAlias, rb_const_get( rb_cObject, rb_intern("Comparable") ) );
- /*
- * Define YAML::Syck::MergeKey class
- */
- cMergeKey = rb_define_class_under( rb_syck, "MergeKey", rb_cObject );
-
- /*
- * Define YAML::Syck::DefaultKey class
- */
- cDefaultKey = rb_define_class_under( rb_syck, "DefaultKey", rb_cObject );
+ /*
+ * Define YAML::Syck::MergeKey class
+ */
+ cMergeKey = rb_define_class_under( rb_syck, "MergeKey", rb_cObject );
- /*
- * Define YAML::Syck::Out classes
- */
- cOut = rb_define_class_under( rb_syck, "Out", rb_cObject );
- rb_define_attr( cOut, "emitter", 1, 1 );
- rb_define_method( cOut, "initialize", syck_out_initialize, 1 );
- rb_define_method( cOut, "map", syck_out_map, -1 );
- rb_define_method( cOut, "seq", syck_out_seq, -1 );
- rb_define_method( cOut, "scalar", syck_out_scalar, -1 );
+ /*
+ * Define YAML::Syck::DefaultKey class
+ */
+ cDefaultKey = rb_define_class_under( rb_syck, "DefaultKey", rb_cObject );
/*
* Define YAML::Syck::Emitter class
*/
cEmitter = rb_define_class_under( rb_syck, "Emitter", rb_cObject );
- rb_define_attr( cEmitter, "level", 1, 1 );
- rb_define_alloc_func( cEmitter, syck_emitter_s_alloc );
- rb_define_method( cEmitter, "initialize", syck_emitter_reset, -1 );
- rb_define_method( cEmitter, "reset", syck_emitter_reset, -1 );
- rb_define_method( cEmitter, "emit", syck_emitter_emit, -1 );
- rb_define_method( cEmitter, "set_resolver", syck_emitter_set_resolver, 1);
- rb_define_method( cEmitter, "node_export", syck_emitter_node_export, 1);
+ rb_define_singleton_method( cEmitter, "new", syck_emitter_new, -1 );
+ rb_define_method( cEmitter, "initialize", syck_emitter_initialize, 1 );
+ rb_define_method( cEmitter, "level", syck_emitter_level_m, 0 );
+ rb_define_method( cEmitter, "write", syck_emitter_write_m, 1 );
+ rb_define_method( cEmitter, "<<", syck_emitter_write_m, 1 );
+ rb_define_method( cEmitter, "simple", syck_emitter_simple_write, 1 );
+ rb_define_method( cEmitter, "flush", syck_emitter_flush_m, 0 );
+ rb_define_method( cEmitter, "start_object", syck_emitter_start_object, 1 );
+ rb_define_method( cEmitter, "end_object", syck_emitter_end_object, 0 );
}
diff --git a/ext/syck/syck.c b/ext/syck/syck.c
index 33f9bf23e8..5a15ab4947 100644
--- a/ext/syck/syck.c
+++ b/ext/syck/syck.c
@@ -209,6 +209,15 @@ void
syck_st_free( SyckParser *p )
{
/*
+ * Free the adhoc symbol table
+ */
+ if ( p->syms != NULL )
+ {
+ st_free_table( p->syms );
+ p->syms = NULL;
+ }
+
+ /*
* Free the anchor tables
*/
if ( p->anchors != NULL )
@@ -230,15 +239,6 @@ void
syck_free_parser( SyckParser *p )
{
/*
- * Free the adhoc symbol table
- */
- if ( p->syms != NULL )
- {
- st_free_table( p->syms );
- p->syms = NULL;
- }
-
- /*
* Free tables, levels
*/
syck_st_free( p );
diff --git a/ext/syck/syck.h b/ext/syck/syck.h
index f7ac39fc94..02dbce9835 100644
--- a/ext/syck/syck.h
+++ b/ext/syck/syck.h
@@ -13,7 +13,7 @@
#define SYCK_YAML_MAJOR 1
#define SYCK_YAML_MINOR 0
-#define SYCK_VERSION "0.60"
+#define SYCK_VERSION "0.45"
#define YAML_DOMAIN "yaml.org,2002"
#include <stdio.h>
@@ -63,16 +63,12 @@ extern "C" {
#define BLOCK_FOLD 10
#define BLOCK_LIT 20
#define BLOCK_PLAIN 30
-#define NL_CHOMP 40
-#define NL_KEEP 50
+#define NL_CHOMP 130
+#define NL_KEEP 140
/*
* Node definitions
*/
-#ifndef ST_DATA_T_DEFINED
-typedef long st_data_t;
-#endif
-
#define SYMID unsigned long
typedef struct _syck_node SyckNode;
@@ -88,23 +84,12 @@ enum map_part {
map_value
};
-enum map_style {
- map_none,
- map_inline
-};
-
-enum seq_style {
- seq_none,
- seq_inline
-};
-
enum scalar_style {
scalar_none,
+ scalar_plain,
scalar_1quote,
scalar_2quote,
- scalar_fold,
- scalar_literal,
- scalar_plain
+ scalar_block
};
/*
@@ -122,7 +107,6 @@ struct _syck_node {
union {
/* Storage for map data */
struct SyckMap {
- enum map_style style;
SYMID *keys;
SYMID *values;
long capa;
@@ -130,7 +114,6 @@ struct _syck_node {
} *pairs;
/* Storage for sequence data */
struct SyckSeq {
- enum seq_style style;
SYMID *items;
long capa;
long idx;
@@ -180,13 +163,9 @@ enum syck_level_status {
syck_lvl_map,
syck_lvl_block,
syck_lvl_str,
- syck_lvl_iseq,
- syck_lvl_imap,
+ syck_lvl_inline,
syck_lvl_end,
- syck_lvl_pause,
- syck_lvl_anctag,
- syck_lvl_mapx,
- syck_lvl_seqx
+ syck_lvl_pause
};
/*
@@ -207,16 +186,9 @@ struct _syck_str {
};
struct _syck_level {
- /* Indent */
int spaces;
- /* Counts nodes emitted at this level, useful for parsing
- * keys and pairs in bytecode */
int ncount;
- /* Does node have anchors or tags? */
- int anctag;
- /* Domain prefixing at the given level */
char *domain;
- /* Keeps a node status */
enum syck_level_status status;
};
@@ -259,7 +231,6 @@ struct _syck_parser {
SyckLevel *levels;
int lvl_idx;
int lvl_capa;
- /* Pointer for extension's use */
void *bonus;
};
@@ -270,19 +241,27 @@ typedef struct _syck_emitter SyckEmitter;
typedef struct _syck_emitter_node SyckEmitterNode;
typedef void (*SyckOutputHandler)(SyckEmitter *, char *, long);
-typedef void (*SyckEmitterHandler)(SyckEmitter *, st_data_t);
enum doc_stage {
doc_open,
+ doc_need_header,
doc_processing
};
+enum block_styles {
+ block_arbitrary,
+ block_fold,
+ block_literal
+};
+
/*
* Emitter struct
*/
struct _syck_emitter {
/* Headerless doc flag */
int headless;
+ /* Sequence map shortcut flag */
+ int seq_map;
/* Force header? */
int use_header;
/* Force version? */
@@ -296,7 +275,7 @@ struct _syck_emitter {
/* Best width on folded scalars */
int best_width;
/* Use literal[1] or folded[2] blocks on all text? */
- enum scalar_style style;
+ enum block_styles block_style;
/* Stage of written document */
enum doc_stage stage;
/* Level counter */
@@ -306,21 +285,15 @@ struct _syck_emitter {
/* Object ignore ID */
SYMID ignore_id;
/* Symbol table for anchors */
- st_table *markers, *anchors, *anchored;
+ st_table *markers, *anchors;
/* Custom buffer size */
size_t bufsize;
/* Buffer */
char *buffer, *marker;
/* Absolute position of the buffer */
long bufpos;
- /* Handler for emitter nodes */
- SyckEmitterHandler emitter_handler;
/* Handler for output */
- SyckOutputHandler output_handler;
- /* Levels of indentation */
- SyckLevel *levels;
- int lvl_idx;
- int lvl_capa;
+ SyckOutputHandler handler;
/* Pointer for extension's use */
void *bonus;
};
@@ -347,7 +320,6 @@ SyckNode *syck_hdlr_get_anchor( SyckParser *, char * );
void syck_add_transfer( char *, SyckNode *, int );
char *syck_xprivate( char *, int );
char *syck_taguri( char *, char *, int );
-int syck_tagcmp( char *, char * );
int syck_add_sym( SyckParser *, char * );
int syck_lookup_sym( SyckParser *, SYMID, char ** );
int syck_try_implicit( SyckNode * );
@@ -364,38 +336,20 @@ long syck_io_str_read( char *, SyckIoStr *, long, long );
char *syck_base64enc( char *, long );
char *syck_base64dec( char *, long );
SyckEmitter *syck_new_emitter();
-SYMID syck_emitter_mark_node( SyckEmitter *, st_data_t );
void syck_emitter_ignore_id( SyckEmitter *, SYMID );
-void syck_output_handler( SyckEmitter *, SyckOutputHandler );
-void syck_emitter_handler( SyckEmitter *, SyckEmitterHandler );
+void syck_emitter_handler( SyckEmitter *, SyckOutputHandler );
void syck_free_emitter( SyckEmitter * );
void syck_emitter_clear( SyckEmitter * );
+void syck_emitter_simple( SyckEmitter *, char *, long );
void syck_emitter_write( SyckEmitter *, char *, long );
-void syck_emitter_escape( SyckEmitter *, char *, long );
void syck_emitter_flush( SyckEmitter *, long );
-void syck_emit( SyckEmitter *, st_data_t );
-void syck_emit_scalar( SyckEmitter *, char *, enum scalar_style, int, int, char, char *, long );
-void syck_emit_1quoted( SyckEmitter *, int, char *, long );
-void syck_emit_2quoted( SyckEmitter *, int, char *, long );
-void syck_emit_folded( SyckEmitter *, int, char, char *, long );
-void syck_emit_literal( SyckEmitter *, char, char *, long );
-void syck_emit_seq( SyckEmitter *, char *, enum seq_style );
-void syck_emit_item( SyckEmitter *, st_data_t );
-void syck_emit_map( SyckEmitter *, char *, enum map_style );
-void syck_emit_end( SyckEmitter * );
-void syck_emit_tag( SyckEmitter *, char *, char * );
-void syck_emit_indent( SyckEmitter * );
-SyckLevel *syck_emitter_current_level( SyckEmitter * );
-SyckLevel *syck_emitter_parent_level( SyckEmitter * );
-void syck_emitter_pop_level( SyckEmitter * );
-void syck_emitter_add_level( SyckEmitter *, int, enum syck_level_status );
-void syck_emitter_reset_levels( SyckEmitter * );
+char *syck_emitter_start_obj( SyckEmitter *, SYMID );
+void syck_emitter_end_obj( SyckEmitter * );
SyckParser *syck_new_parser();
void syck_free_parser( SyckParser * );
void syck_parser_set_root_on_error( SyckParser *, SYMID );
void syck_parser_implicit_typing( SyckParser *, int );
void syck_parser_taguri_expansion( SyckParser *, int );
-int syck_scan_scalar( int, char *, long );
void syck_parser_handler( SyckParser *, SyckNodeHandler );
void syck_parser_error_handler( SyckParser *, SyckErrorHandler );
void syck_parser_bad_anchor_handler( SyckParser *, SyckBadAnchorHandler );
@@ -408,6 +362,7 @@ void syck_parser_pop_level( SyckParser * );
void free_any_io( SyckParser * );
long syck_parser_read( SyckParser * );
long syck_parser_readlen( SyckParser *, long );
+void syck_parser_init( SyckParser *, int );
SYMID syck_parse( SyckParser * );
void syck_default_error_handler( SyckParser *, char * );
SYMID syck_yaml2byte_handler( SyckParser *, SyckNode * );
@@ -423,31 +378,29 @@ void syck_free_node( SyckNode * );
void syck_free_members( SyckNode * );
SyckNode *syck_new_str( char *, enum scalar_style );
SyckNode *syck_new_str2( char *, long, enum scalar_style );
-void syck_replace_str( SyckNode *, char *, enum scalar_style );
-void syck_replace_str2( SyckNode *, char *, long, enum scalar_style );
void syck_str_blow_away_commas( SyckNode * );
char *syck_str_read( SyckNode * );
SyckNode *syck_new_map( SYMID, SYMID );
-void syck_map_empty( SyckNode * );
void syck_map_add( SyckNode *, SYMID, SYMID );
SYMID syck_map_read( SyckNode *, enum map_part, long );
void syck_map_assign( SyckNode *, enum map_part, long, SYMID );
long syck_map_count( SyckNode * );
void syck_map_update( SyckNode *, SyckNode * );
SyckNode *syck_new_seq( SYMID );
-void syck_seq_empty( SyckNode * );
void syck_seq_add( SyckNode *, SYMID );
-void syck_seq_assign( SyckNode *, long, SYMID );
SYMID syck_seq_read( SyckNode *, long );
long syck_seq_count( SyckNode * );
+void apply_seq_in_map( SyckParser *, SyckNode * );
+
/*
* Lexer prototypes
*/
void syckerror( char * );
-int syckparse( void * );
-union YYSTYPE;
-int sycklex( union YYSTYPE *, SyckParser * );
+
+#ifndef ST_DATA_T_DEFINED
+typedef long st_data_t;
+#endif
#if defined(__cplusplus)
} /* extern "C" { */
diff --git a/ext/syck/token.c b/ext/syck/token.c
index 3c6cd1a9cf..85a4e103ab 100644
--- a/ext/syck/token.c
+++ b/ext/syck/token.c
@@ -1,4 +1,4 @@
-/* Generated by re2c 0.9.10 on Tue Sep 20 17:46:17 2005 */
+/* Generated by re2c 0.9.3 on Fri Aug 13 11:47:50 2004 */
#line 1 "token.re"
/*
* token.re
@@ -61,7 +61,7 @@
#define ENSURE_YAML_IOPEN(last_lvl, to_len, reset) \
if ( last_lvl->spaces < to_len ) \
{ \
- if ( last_lvl->status == syck_lvl_iseq || last_lvl->status == syck_lvl_imap ) \
+ if ( last_lvl->status == syck_lvl_inline ) \
{ \
goto Document; \
} \
@@ -131,25 +131,6 @@
return YAML_PLAIN; \
}
-/* concat the inline characters to the plain scalar */
-#define PLAIN_NOT_INL() \
- if ( *(YYCURSOR - 1) == ' ' || is_newline( YYCURSOR - 1 ) ) \
- { \
- YYCURSOR--; \
- } \
- QUOTECATS(qstr, qcapa, qidx, YYTOKEN, YYCURSOR - YYTOKEN); \
- goto Plain2;
-
-/* trim spaces off the end in case of indent */
-#define PLAIN_IS_INL() \
- char *walker = qstr + qidx - 1; \
- while ( walker > qstr && ( *walker == '\n' || *walker == ' ' || *walker == '\t' ) ) \
- { \
- qidx--; \
- walker[0] = '\0'; \
- walker--; \
- }
-
/*
* Keep or chomp block?
* * Use only in "ScalarBlock" section *
@@ -157,21 +138,10 @@
#define RETURN_YAML_BLOCK() \
{ \
SyckNode *n = syck_alloc_str(); \
- if ( ((SyckParser *)parser)->taguri_expansion == 1 ) \
- { \
- n->type_id = syck_taguri( YAML_DOMAIN, "str", 3 ); \
- } \
- else \
- { \
- n->type_id = syck_strndup( "str", 3 ); \
- } \
+ n->type_id = syck_strndup( "str", 3 ); \
n->data.str->ptr = qstr; \
n->data.str->len = qidx; \
- if ( blockType == BLOCK_LIT ) { \
- n->data.str->style = scalar_literal; \
- } else { \
- n->data.str->style = scalar_fold; \
- } \
+ n->data.str->style = scalar_block; \
if ( qidx > 0 ) \
{ \
if ( nlDoWhat != NL_KEEP ) \
@@ -218,7 +188,7 @@
{ \
SyckLevel *lvl_deep = CURRENT_LEVEL(); \
indt_len = lvl_deep->spaces; \
- if ( lvl_deep->status == syck_lvl_seq || ( indt_len == YYCURSOR - YYLINEPTR && lvl_deep->status != syck_lvl_map ) ) \
+ if ( indt_len == YYTOKEN - YYLINEPTR ) \
{ \
SyckLevel *lvl_over; \
parser->lvl_idx--; \
@@ -268,7 +238,6 @@ sycklex( YYSTYPE *sycklval, SyckParser *parser )
case syck_bytecode_utf8:
return sycklex_bytecode_utf8( sycklval, parser );
}
- return YAML_DOCSEP;
}
/*
@@ -291,7 +260,7 @@ sycklex_yaml_utf8( YYSTYPE *sycklval, SyckParser *parser )
return t;
}
-#line 315 "token.re"
+#line 279 "token.re"
if ( YYLINEPTR != YYCURSOR )
@@ -304,20 +273,20 @@ Header:
YYTOKEN = YYCURSOR;
-#line 307 "<stdout>"
+#line 7 "<stdout>"
{
YYCTYPE yych;
unsigned int yyaccept;
goto yy0;
- ++YYCURSOR;
+yy1: ++YYCURSOR;
yy0:
if((YYLIMIT - YYCURSOR) < 5) YYFILL(5);
yych = *YYCURSOR;
switch(yych){
- case 0x00: goto yy7;
- case 0x09: case ' ': goto yy12;
- case 0x0A: goto yy9;
- case 0x0D: goto yy11;
+ case '\000': goto yy7;
+ case '\n': goto yy9;
+ case '\r': goto yy11;
+ case ' ': goto yy12;
case '#': goto yy5;
case '-': goto yy2;
case '.': goto yy4;
@@ -330,11 +299,11 @@ yy2: yyaccept = 0;
default: goto yy3;
}
yy3:
-#line 374 "token.re"
+#line 338 "token.re"
{ YYPOS(0);
goto Document;
}
-#line 337 "<stdout>"
+#line 37 "<stdout>"
yy4: yyaccept = 0;
yych = *(YYMARKER = ++YYCURSOR);
switch(yych){
@@ -344,44 +313,44 @@ yy4: yyaccept = 0;
yy5: ++YYCURSOR;
goto yy6;
yy6:
-#line 356 "token.re"
+#line 320 "token.re"
{ eat_comments( parser );
goto Header;
}
-#line 351 "<stdout>"
+#line 51 "<stdout>"
yy7: ++YYCURSOR;
goto yy8;
yy8:
-#line 360 "token.re"
+#line 324 "token.re"
{ SyckLevel *lvl = CURRENT_LEVEL();
ENSURE_YAML_IEND(lvl, -1);
YYPOS(0);
return 0;
}
-#line 361 "<stdout>"
+#line 61 "<stdout>"
yy9: yyaccept = 1;
yych = *(YYMARKER = ++YYCURSOR);
goto yy18;
yy10:
-#line 366 "token.re"
+#line 330 "token.re"
{ GOBBLE_UP_YAML_INDENT( doc_level, YYTOKEN );
goto Header;
}
-#line 370 "<stdout>"
+#line 70 "<stdout>"
yy11: yych = *++YYCURSOR;
switch(yych){
- case 0x0A: goto yy17;
+ case '\n': goto yy17;
default: goto yy3;
}
yy12: ++YYCURSOR;
yych = *YYCURSOR;
goto yy16;
yy13:
-#line 370 "token.re"
+#line 334 "token.re"
{ doc_level = YYCURSOR - YYLINEPTR;
goto Header;
}
-#line 384 "<stdout>"
+#line 83 "<stdout>"
yy14: yych = *++YYCURSOR;
goto yy3;
yy15: ++YYCURSOR;
@@ -389,7 +358,7 @@ yy15: ++YYCURSOR;
yych = *YYCURSOR;
goto yy16;
yy16: switch(yych){
- case 0x09: case ' ': goto yy15;
+ case ' ': goto yy15;
default: goto yy13;
}
yy17: yyaccept = 1;
@@ -398,15 +367,15 @@ yy17: yyaccept = 1;
yych = *YYCURSOR;
goto yy18;
yy18: switch(yych){
- case 0x0A: case ' ': goto yy17;
- case 0x0D: goto yy19;
+ case '\n': case ' ': goto yy17;
+ case '\r': goto yy19;
default: goto yy10;
}
yy19: ++YYCURSOR;
if(YYLIMIT == YYCURSOR) YYFILL(1);
yych = *YYCURSOR;
switch(yych){
- case 0x0A: goto yy17;
+ case '\n': goto yy17;
default: goto yy20;
}
yy20: YYCURSOR = YYMARKER;
@@ -421,15 +390,15 @@ yy21: yych = *++YYCURSOR;
}
yy22: yych = *++YYCURSOR;
switch(yych){
- case 0x0A: goto yy23;
- case 0x0D: goto yy27;
+ case '\n': goto yy23;
+ case '\r': goto yy27;
case ' ': goto yy25;
default: goto yy20;
}
yy23: ++YYCURSOR;
goto yy24;
yy24:
-#line 342 "token.re"
+#line 306 "token.re"
{ SyckLevel *lvl = CURRENT_LEVEL();
if ( lvl->status == syck_lvl_header )
{
@@ -443,7 +412,7 @@ yy24:
}
return 0;
}
-#line 446 "<stdout>"
+#line 147 "<stdout>"
yy25: ++YYCURSOR;
if(YYLIMIT == YYCURSOR) YYFILL(1);
yych = *YYCURSOR;
@@ -454,7 +423,7 @@ yy26: switch(yych){
}
yy27: yych = *++YYCURSOR;
switch(yych){
- case 0x0A: goto yy23;
+ case '\n': goto yy23;
default: goto yy20;
}
yy28: yych = *++YYCURSOR;
@@ -464,15 +433,15 @@ yy28: yych = *++YYCURSOR;
}
yy29: yych = *++YYCURSOR;
switch(yych){
- case 0x0A: goto yy30;
- case 0x0D: goto yy34;
+ case '\n': goto yy30;
+ case '\r': goto yy34;
case ' ': goto yy32;
default: goto yy20;
}
yy30: ++YYCURSOR;
goto yy31;
yy31:
-#line 328 "token.re"
+#line 292 "token.re"
{ SyckLevel *lvl = CURRENT_LEVEL();
if ( lvl->status == syck_lvl_header )
{
@@ -486,7 +455,7 @@ yy31:
return 0;
}
}
-#line 489 "<stdout>"
+#line 191 "<stdout>"
yy32: ++YYCURSOR;
if(YYLIMIT == YYCURSOR) YYFILL(1);
yych = *YYCURSOR;
@@ -497,11 +466,11 @@ yy33: switch(yych){
}
yy34: ++YYCURSOR;
switch((yych = *YYCURSOR)) {
- case 0x0A: goto yy30;
+ case '\n': goto yy30;
default: goto yy20;
}
}
-#line 378 "token.re"
+#line 342 "token.re"
Document:
@@ -515,39 +484,38 @@ Document:
YYTOKEN = YYCURSOR;
-#line 518 "<stdout>"
+#line 209 "<stdout>"
{
YYCTYPE yych;
unsigned int yyaccept;
goto yy35;
- ++YYCURSOR;
+yy36: ++YYCURSOR;
yy35:
if((YYLIMIT - YYCURSOR) < 3) YYFILL(3);
yych = *YYCURSOR;
switch(yych){
- case 0x00: goto yy62;
- case 0x09: case ' ': goto yy60;
- case 0x0A: goto yy37;
- case 0x0D: goto yy39;
- case '!': goto yy51;
- case '"': goto yy55;
- case '#': goto yy58;
- case '&': goto yy49;
- case '\'': goto yy53;
- case '*': goto yy50;
- case ',': case ':': goto yy47;
- case '-': case '?': goto yy48;
- case '>': case '|': goto yy57;
- case '[': goto yy41;
- case ']': case '}': goto yy45;
- case '{': goto yy43;
- default: goto yy64;
+ case '\000': goto yy60;
+ case '\n': goto yy37;
+ case '\r': goto yy39;
+ case ' ': goto yy58;
+ case '!': goto yy49;
+ case '"': goto yy53;
+ case '#': goto yy56;
+ case '&': goto yy47;
+ case '\'': goto yy51;
+ case '*': goto yy48;
+ case ',': case ':': goto yy45;
+ case '-': case '?': goto yy46;
+ case '>': case '|': goto yy55;
+ case '[': case '{': goto yy41;
+ case ']': case '}': goto yy43;
+ default: goto yy62;
}
yy37: yyaccept = 0;
yych = *(YYMARKER = ++YYCURSOR);
- goto yy92;
+ goto yy90;
yy38:
-#line 392 "token.re"
+#line 356 "token.re"
{ /* Isolate spaces */
int indt_len;
GOBBLE_UP_YAML_INDENT( indt_len, YYTOKEN );
@@ -561,7 +529,7 @@ yy38:
}
/* Ignore indentation inside inlines */
- if ( lvl->status == syck_lvl_iseq || lvl->status == syck_lvl_imap )
+ if ( lvl->status == syck_lvl_inline )
{
goto Document;
}
@@ -575,63 +543,53 @@ yy38:
}
return YAML_INDENT;
}
-#line 578 "<stdout>"
+#line 268 "<stdout>"
yy39: ++YYCURSOR;
switch((yych = *YYCURSOR)) {
- case 0x0A: goto yy91;
+ case '\n': goto yy89;
default: goto yy40;
}
yy40:
-#line 497 "token.re"
+#line 454 "token.re"
{ ENSURE_YAML_IOPEN(lvl, doc_level, 1);
goto Plain;
}
-#line 589 "<stdout>"
+#line 279 "<stdout>"
yy41: ++YYCURSOR;
goto yy42;
yy42:
-#line 420 "token.re"
+#line 384 "token.re"
{ ENSURE_YAML_IOPEN(lvl, doc_level, 1);
lvl = CURRENT_LEVEL();
- ADD_LEVEL(lvl->spaces + 1, syck_lvl_iseq);
+ ADD_LEVEL(lvl->spaces + 1, syck_lvl_inline);
return YYTOKEN[0];
}
-#line 599 "<stdout>"
+#line 289 "<stdout>"
yy43: ++YYCURSOR;
goto yy44;
yy44:
-#line 426 "token.re"
-{ ENSURE_YAML_IOPEN(lvl, doc_level, 1);
- lvl = CURRENT_LEVEL();
- ADD_LEVEL(lvl->spaces + 1, syck_lvl_imap);
- return YYTOKEN[0];
- }
-#line 609 "<stdout>"
-yy45: ++YYCURSOR;
- goto yy46;
-yy46:
-#line 432 "token.re"
+#line 390 "token.re"
{ POP_LEVEL();
return YYTOKEN[0];
}
-#line 617 "<stdout>"
-yy47: yyaccept = 1;
+#line 297 "<stdout>"
+yy45: yyaccept = 1;
yych = *(YYMARKER = ++YYCURSOR);
switch(yych){
- case 0x0A: goto yy86;
- case 0x0D: goto yy90;
- case ' ': goto yy88;
+ case '\n': goto yy84;
+ case '\r': goto yy88;
+ case ' ': goto yy86;
default: goto yy40;
}
-yy48: yyaccept = 1;
+yy46: yyaccept = 1;
yych = *(YYMARKER = ++YYCURSOR);
switch(yych){
- case 0x0A: goto yy81;
- case 0x0D: goto yy85;
- case ' ': goto yy83;
+ case '\n': goto yy79;
+ case '\r': goto yy83;
+ case ' ': goto yy81;
default: goto yy40;
}
-yy49: yych = *++YYCURSOR;
+yy47: yych = *++YYCURSOR;
switch(yych){
case '-': case '0':
case '1':
@@ -692,10 +650,10 @@ yy49: yych = *++YYCURSOR;
case 'w':
case 'x':
case 'y':
- case 'z': goto yy78;
+ case 'z': goto yy76;
default: goto yy40;
}
-yy50: yych = *++YYCURSOR;
+yy48: yych = *++YYCURSOR;
switch(yych){
case '-': case '0':
case '1':
@@ -756,35 +714,35 @@ yy50: yych = *++YYCURSOR;
case 'w':
case 'x':
case 'y':
- case 'z': goto yy75;
+ case 'z': goto yy73;
default: goto yy40;
}
+yy49: ++YYCURSOR;
+ goto yy50;
+yy50:
+#line 428 "token.re"
+{ goto TransferMethod; }
+#line 447 "<stdout>"
yy51: ++YYCURSOR;
goto yy52;
yy52:
-#line 471 "token.re"
-{ goto TransferMethod; }
-#line 767 "<stdout>"
+#line 430 "token.re"
+{ ENSURE_YAML_IOPEN(lvl, doc_level, 1);
+ goto SingleQuote; }
+#line 454 "<stdout>"
yy53: ++YYCURSOR;
goto yy54;
yy54:
-#line 473 "token.re"
-{ ENSURE_YAML_IOPEN(lvl, doc_level, 1);
- goto SingleQuote; }
-#line 774 "<stdout>"
-yy55: ++YYCURSOR;
- goto yy56;
-yy56:
-#line 476 "token.re"
+#line 433 "token.re"
{ ENSURE_YAML_IOPEN(lvl, doc_level, 1);
goto DoubleQuote; }
-#line 781 "<stdout>"
-yy57: yyaccept = 1;
+#line 461 "<stdout>"
+yy55: yyaccept = 1;
yych = *(YYMARKER = ++YYCURSOR);
switch(yych){
- case 0x0A: goto yy70;
- case 0x0D: goto yy74;
- case ' ': goto yy72;
+ case '\n': goto yy68;
+ case '\r': goto yy72;
+ case ' ': goto yy70;
case '+': case '-': case '0':
case '1':
case '2':
@@ -794,51 +752,51 @@ yy57: yyaccept = 1;
case '6':
case '7':
case '8':
- case '9': goto yy67;
+ case '9': goto yy65;
default: goto yy40;
}
-yy58: ++YYCURSOR;
- goto yy59;
-yy59:
-#line 486 "token.re"
+yy56: ++YYCURSOR;
+ goto yy57;
+yy57:
+#line 443 "token.re"
{ eat_comments( parser );
goto Document;
}
-#line 807 "<stdout>"
-yy60: ++YYCURSOR;
+#line 487 "<stdout>"
+yy58: ++YYCURSOR;
yych = *YYCURSOR;
- goto yy66;
-yy61:
-#line 490 "token.re"
+ goto yy64;
+yy59:
+#line 447 "token.re"
{ goto Document; }
-#line 814 "<stdout>"
-yy62: ++YYCURSOR;
- goto yy63;
-yy63:
-#line 492 "token.re"
+#line 493 "<stdout>"
+yy60: ++YYCURSOR;
+ goto yy61;
+yy61:
+#line 449 "token.re"
{ ENSURE_YAML_IEND(lvl, -1);
YYPOS(0);
return 0;
}
-#line 823 "<stdout>"
-yy64: yych = *++YYCURSOR;
+#line 502 "<stdout>"
+yy62: yych = *++YYCURSOR;
goto yy40;
+yy63: ++YYCURSOR;
+ if(YYLIMIT == YYCURSOR) YYFILL(1);
+ yych = *YYCURSOR;
+ goto yy64;
+yy64: switch(yych){
+ case ' ': goto yy63;
+ default: goto yy59;
+ }
yy65: ++YYCURSOR;
if(YYLIMIT == YYCURSOR) YYFILL(1);
yych = *YYCURSOR;
goto yy66;
yy66: switch(yych){
- case 0x09: case ' ': goto yy65;
- default: goto yy61;
- }
-yy67: ++YYCURSOR;
- if((YYLIMIT - YYCURSOR) < 2) YYFILL(2);
- yych = *YYCURSOR;
- goto yy68;
-yy68: switch(yych){
- case 0x0A: goto yy70;
- case 0x0D: goto yy74;
- case ' ': goto yy72;
+ case '\n': goto yy68;
+ case '\r': goto yy72;
+ case ' ': goto yy70;
case '+': case '-': case '0':
case '1':
case '2':
@@ -848,43 +806,43 @@ yy68: switch(yych){
case '6':
case '7':
case '8':
- case '9': goto yy67;
- default: goto yy69;
+ case '9': goto yy65;
+ default: goto yy67;
}
-yy69: YYCURSOR = YYMARKER;
+yy67: YYCURSOR = YYMARKER;
switch(yyaccept){
case 0: goto yy38;
case 1: goto yy40;
}
-yy70: ++YYCURSOR;
- goto yy71;
-yy71:
-#line 479 "token.re"
+yy68: ++YYCURSOR;
+ goto yy69;
+yy69:
+#line 436 "token.re"
{ if ( is_newline( YYCURSOR - 1 ) )
{
YYCURSOR--;
}
goto ScalarBlock;
}
-#line 869 "<stdout>"
-yy72: ++YYCURSOR;
+#line 550 "<stdout>"
+yy70: ++YYCURSOR;
if(YYLIMIT == YYCURSOR) YYFILL(1);
yych = *YYCURSOR;
- goto yy73;
-yy73: switch(yych){
- case ' ': goto yy72;
- default: goto yy71;
+ goto yy71;
+yy71: switch(yych){
+ case ' ': goto yy70;
+ default: goto yy69;
}
-yy74: yych = *++YYCURSOR;
+yy72: yych = *++YYCURSOR;
switch(yych){
- case 0x0A: goto yy70;
- default: goto yy69;
+ case '\n': goto yy68;
+ default: goto yy67;
}
-yy75: ++YYCURSOR;
+yy73: ++YYCURSOR;
if(YYLIMIT == YYCURSOR) YYFILL(1);
yych = *YYCURSOR;
- goto yy76;
-yy76: switch(yych){
+ goto yy74;
+yy74: switch(yych){
case '-': case '0':
case '1':
case '2':
@@ -944,21 +902,21 @@ yy76: switch(yych){
case 'w':
case 'x':
case 'y':
- case 'z': goto yy75;
- default: goto yy77;
+ case 'z': goto yy73;
+ default: goto yy75;
}
-yy77:
-#line 466 "token.re"
+yy75:
+#line 423 "token.re"
{ ENSURE_YAML_IOPEN(lvl, doc_level, 1);
sycklval->name = syck_strndup( YYTOKEN + 1, YYCURSOR - YYTOKEN - 1 );
return YAML_ALIAS;
}
-#line 956 "<stdout>"
-yy78: ++YYCURSOR;
+#line 639 "<stdout>"
+yy76: ++YYCURSOR;
if(YYLIMIT == YYCURSOR) YYFILL(1);
yych = *YYCURSOR;
- goto yy79;
-yy79: switch(yych){
+ goto yy77;
+yy77: switch(yych){
case '-': case '0':
case '1':
case '2':
@@ -1018,11 +976,11 @@ yy79: switch(yych){
case 'w':
case 'x':
case 'y':
- case 'z': goto yy78;
- default: goto yy80;
+ case 'z': goto yy76;
+ default: goto yy78;
}
-yy80:
-#line 455 "token.re"
+yy78:
+#line 412 "token.re"
{ sycklval->name = syck_strndup( YYTOKEN + 1, YYCURSOR - YYTOKEN - 1 );
/*
@@ -1033,79 +991,78 @@ yy80:
syck_hdlr_remove_anchor(parser, sycklval->name);
return YAML_ANCHOR;
}
-#line 1036 "<stdout>"
-yy81: ++YYCURSOR;
- goto yy82;
-yy82:
-#line 441 "token.re"
+#line 720 "<stdout>"
+yy79: ++YYCURSOR;
+ goto yy80;
+yy80:
+#line 398 "token.re"
{ ENSURE_YAML_IOPEN(lvl, YYTOKEN - YYLINEPTR, 1);
FORCE_NEXT_TOKEN(YAML_IOPEN);
if ( *YYCURSOR == '#' || is_newline( YYCURSOR ) || is_newline( YYCURSOR - 1 ) )
{
YYCURSOR--;
- ADD_LEVEL((YYTOKEN + 1) - YYLINEPTR, syck_lvl_seq);
+ ADD_LEVEL((YYTOKEN + 1) - YYLINEPTR, syck_lvl_doc);
}
else /* spaces followed by content uses the space as indentation */
{
- ADD_LEVEL(YYCURSOR - YYLINEPTR, syck_lvl_seq);
+ ADD_LEVEL(YYCURSOR - YYLINEPTR, syck_lvl_doc);
}
return YYTOKEN[0];
}
-#line 1054 "<stdout>"
-yy83: ++YYCURSOR;
+#line 738 "<stdout>"
+yy81: ++YYCURSOR;
if(YYLIMIT == YYCURSOR) YYFILL(1);
yych = *YYCURSOR;
- goto yy84;
-yy84: switch(yych){
- case ' ': goto yy83;
- default: goto yy82;
+ goto yy82;
+yy82: switch(yych){
+ case ' ': goto yy81;
+ default: goto yy80;
}
-yy85: yych = *++YYCURSOR;
+yy83: yych = *++YYCURSOR;
switch(yych){
- case 0x0A: goto yy81;
- default: goto yy69;
- }
-yy86: ++YYCURSOR;
- goto yy87;
-yy87:
-#line 436 "token.re"
-{ if ( *YYTOKEN == ':' && lvl->status != syck_lvl_imap ) lvl->status = syck_lvl_map;
- YYPOS(1);
+ case '\n': goto yy79;
+ default: goto yy67;
+ }
+yy84: ++YYCURSOR;
+ goto yy85;
+yy85:
+#line 394 "token.re"
+{ YYPOS(1);
return YYTOKEN[0];
}
-#line 1076 "<stdout>"
-yy88: ++YYCURSOR;
+#line 760 "<stdout>"
+yy86: ++YYCURSOR;
if(YYLIMIT == YYCURSOR) YYFILL(1);
yych = *YYCURSOR;
- goto yy89;
-yy89: switch(yych){
- case ' ': goto yy88;
- default: goto yy87;
+ goto yy87;
+yy87: switch(yych){
+ case ' ': goto yy86;
+ default: goto yy85;
}
-yy90: yych = *++YYCURSOR;
+yy88: yych = *++YYCURSOR;
switch(yych){
- case 0x0A: goto yy86;
- default: goto yy69;
+ case '\n': goto yy84;
+ default: goto yy67;
}
-yy91: yyaccept = 0;
+yy89: yyaccept = 0;
YYMARKER = ++YYCURSOR;
if(YYLIMIT == YYCURSOR) YYFILL(1);
yych = *YYCURSOR;
- goto yy92;
-yy92: switch(yych){
- case 0x0A: case ' ': goto yy91;
- case 0x0D: goto yy93;
+ goto yy90;
+yy90: switch(yych){
+ case '\n': case ' ': goto yy89;
+ case '\r': goto yy91;
default: goto yy38;
}
-yy93: ++YYCURSOR;
+yy91: ++YYCURSOR;
if(YYLIMIT == YYCURSOR) YYFILL(1);
yych = *YYCURSOR;
switch(yych){
- case 0x0A: goto yy91;
- default: goto yy69;
+ case '\n': goto yy89;
+ default: goto yy67;
}
}
-#line 501 "token.re"
+#line 458 "token.re"
}
@@ -1114,26 +1071,26 @@ Directive:
YYTOKTMP = YYCURSOR;
-#line 1117 "<stdout>"
+#line 796 "<stdout>"
{
YYCTYPE yych;
unsigned int yyaccept;
- goto yy94;
- ++YYCURSOR;
-yy94:
+ goto yy92;
+yy93: ++YYCURSOR;
+yy92:
if((YYLIMIT - YYCURSOR) < 2) YYFILL(2);
yych = *YYCURSOR;
switch(yych){
- case 0x00: goto yy96;
- case 0x09: case ' ': goto yy99;
- case '%': goto yy97;
- default: goto yy101;
+ case '\000': goto yy94;
+ case ' ': goto yy97;
+ case '%': goto yy95;
+ default: goto yy99;
}
-yy96: YYCURSOR = YYMARKER;
+yy94: YYCURSOR = YYMARKER;
switch(yyaccept){
- case 0: goto yy98;
+ case 0: goto yy96;
}
-yy97: yyaccept = 0;
+yy95: yyaccept = 0;
yych = *(YYMARKER = ++YYCURSOR);
switch(yych){
case '.':
@@ -1210,37 +1167,37 @@ yy97: yyaccept = 0;
case 'w':
case 'x':
case 'y':
- case 'z': goto yy104;
- default: goto yy98;
+ case 'z': goto yy102;
+ default: goto yy96;
}
-yy98:
-#line 514 "token.re"
+yy96:
+#line 471 "token.re"
{ YYCURSOR = YYTOKTMP;
return YAML_DOCSEP;
}
-#line 1221 "<stdout>"
-yy99: ++YYCURSOR;
+#line 900 "<stdout>"
+yy97: ++YYCURSOR;
yych = *YYCURSOR;
- goto yy103;
-yy100:
-#line 512 "token.re"
+ goto yy101;
+yy98:
+#line 469 "token.re"
{ goto Directive; }
-#line 1228 "<stdout>"
-yy101: yych = *++YYCURSOR;
- goto yy98;
+#line 906 "<stdout>"
+yy99: yych = *++YYCURSOR;
+ goto yy96;
+yy100: ++YYCURSOR;
+ if(YYLIMIT == YYCURSOR) YYFILL(1);
+ yych = *YYCURSOR;
+ goto yy101;
+yy101: switch(yych){
+ case ' ': goto yy100;
+ default: goto yy98;
+ }
yy102: ++YYCURSOR;
if(YYLIMIT == YYCURSOR) YYFILL(1);
yych = *YYCURSOR;
goto yy103;
yy103: switch(yych){
- case 0x09: case ' ': goto yy102;
- default: goto yy100;
- }
-yy104: ++YYCURSOR;
- if((YYLIMIT - YYCURSOR) < 2) YYFILL(2);
- yych = *YYCURSOR;
- goto yy105;
-yy105: switch(yych){
case '.':
case '/':
case '0':
@@ -1313,11 +1270,11 @@ yy105: switch(yych){
case 'w':
case 'x':
case 'y':
- case 'z': goto yy104;
- case ':': goto yy106;
- default: goto yy96;
+ case 'z': goto yy102;
+ case ':': goto yy104;
+ default: goto yy94;
}
-yy106: yych = *++YYCURSOR;
+yy104: yych = *++YYCURSOR;
switch(yych){
case '.':
case '/':
@@ -1393,14 +1350,14 @@ yy106: yych = *++YYCURSOR;
case 'w':
case 'x':
case 'y':
- case 'z': goto yy107;
- default: goto yy96;
+ case 'z': goto yy105;
+ default: goto yy94;
}
-yy107: ++YYCURSOR;
+yy105: ++YYCURSOR;
if(YYLIMIT == YYCURSOR) YYFILL(1);
yych = *YYCURSOR;
- goto yy108;
-yy108: switch(yych){
+ goto yy106;
+yy106: switch(yych){
case '.':
case '/':
case '0':
@@ -1475,15 +1432,15 @@ yy108: switch(yych){
case 'w':
case 'x':
case 'y':
- case 'z': goto yy107;
- default: goto yy109;
+ case 'z': goto yy105;
+ default: goto yy107;
}
-yy109:
-#line 510 "token.re"
+yy107:
+#line 467 "token.re"
{ goto Directive; }
-#line 1484 "<stdout>"
+#line 1165 "<stdout>"
}
-#line 517 "token.re"
+#line 474 "token.re"
}
@@ -1506,32 +1463,30 @@ Plain2:
Plain3:
-#line 1509 "<stdout>"
+#line 1169 "<stdout>"
{
YYCTYPE yych;
unsigned int yyaccept;
- goto yy110;
- ++YYCURSOR;
-yy110:
+ goto yy108;
+yy109: ++YYCURSOR;
+yy108:
if((YYLIMIT - YYCURSOR) < 3) YYFILL(3);
yych = *YYCURSOR;
switch(yych){
- case 0x00: goto yy124;
- case 0x09: goto yy126;
- case 0x0A: goto yy112;
- case 0x0D: goto yy114;
- case ' ': goto yy122;
+ case '\000': goto yy120;
+ case '\n': goto yy110;
+ case '\r': goto yy112;
+ case ' ': goto yy118;
case ',': goto yy117;
- case ':': goto yy116;
- case ']': goto yy120;
- case '}': goto yy118;
- default: goto yy127;
+ case ':': goto yy114;
+ case ']': case '}': goto yy115;
+ default: goto yy122;
}
-yy112: yyaccept = 0;
+yy110: yyaccept = 0;
yych = *(YYMARKER = ++YYCURSOR);
- goto yy142;
-yy113:
-#line 540 "token.re"
+ goto yy136;
+yy111:
+#line 497 "token.re"
{ int indt_len, nl_count = 0;
SyckLevel *lvl;
char *tok = YYTOKEN;
@@ -1545,8 +1500,8 @@ yy113:
while ( YYTOKEN < YYCURSOR )
{
- int nl_len = newline_len( YYTOKEN++ );
- if ( nl_len )
+ int nl_len = 0;
+ if ( nl_len = newline_len( YYTOKEN++ ) )
{
nl_count++;
YYTOKEN += nl_len - 1;
@@ -1567,114 +1522,112 @@ yy113:
goto Plain2;
}
-#line 1570 "<stdout>"
-yy114: ++YYCURSOR;
+#line 1228 "<stdout>"
+yy112: ++YYCURSOR;
switch((yych = *YYCURSOR)) {
- case 0x0A: goto yy141;
- default: goto yy115;
+ case '\n': goto yy135;
+ default: goto yy113;
}
-yy115:
-#line 627 "token.re"
+yy113:
+#line 566 "token.re"
{ QUOTECATS(qstr, qcapa, qidx, YYTOKEN, YYCURSOR - YYTOKEN);
goto Plain2;
}
-#line 1581 "<stdout>"
-yy116: yyaccept = 1;
- yych = *(YYMARKER = ++YYCURSOR);
- switch(yych){
- case 0x0A: goto yy136;
- case 0x0D: goto yy140;
- case ' ': goto yy138;
- default: goto yy115;
- }
-yy117: yyaccept = 1;
+#line 1239 "<stdout>"
+yy114: yyaccept = 1;
yych = *(YYMARKER = ++YYCURSOR);
switch(yych){
- case 0x0A: goto yy130;
- case 0x0D: goto yy134;
+ case '\n': goto yy130;
+ case '\r': goto yy134;
case ' ': goto yy132;
- default: goto yy115;
+ default: goto yy113;
}
-yy118: ++YYCURSOR;
- goto yy119;
-yy119:
-#line 589 "token.re"
-{ if ( plvl->status != syck_lvl_imap )
+yy115: ++YYCURSOR;
+ goto yy116;
+yy116:
+#line 535 "token.re"
+{ if ( plvl->status != syck_lvl_inline )
{
- PLAIN_NOT_INL();
+ if ( *(YYCURSOR - 1) == ' ' || is_newline( YYCURSOR - 1 ) )
+ {
+ YYCURSOR--;
+ }
+ QUOTECATS(qstr, qcapa, qidx, YYTOKEN, YYCURSOR - YYTOKEN);
+ goto Plain2;
}
else
{
- PLAIN_IS_INL();
+ /* trim spaces off the end in case of indent */
+ char *walker = qstr + qidx - 1;
+ while ( walker > qstr && ( *walker == '\n' || *walker == ' ' ) )
+ {
+ qidx--;
+ walker[0] = '\0';
+ walker--;
+ }
}
RETURN_IMPLICIT();
}
-#line 1612 "<stdout>"
+#line 1274 "<stdout>"
+yy117: yyaccept = 1;
+ yych = *(YYMARKER = ++YYCURSOR);
+ switch(yych){
+ case '\n': goto yy125;
+ case '\r': goto yy128;
+ case ' ': goto yy126;
+ default: goto yy113;
+ }
+yy118: ++YYCURSOR;
+ switch((yych = *YYCURSOR)) {
+ case '#': goto yy123;
+ default: goto yy119;
+ }
+yy119:
+#line 564 "token.re"
+{ goto Plain3; }
+#line 1291 "<stdout>"
yy120: ++YYCURSOR;
goto yy121;
yy121:
-#line 600 "token.re"
-{ if ( plvl->status != syck_lvl_iseq )
- {
- PLAIN_NOT_INL();
- }
- else
- {
- PLAIN_IS_INL();
- }
- RETURN_IMPLICIT();
- }
-#line 1627 "<stdout>"
-yy122: ++YYCURSOR;
- switch((yych = *YYCURSOR)) {
- case '#': goto yy128;
- default: goto yy123;
- }
-yy123:
-#line 617 "token.re"
-{ if ( qidx == 0 )
- {
- goto Plain2;
- }
- else
- {
- goto Plain3;
- }
- }
-#line 1644 "<stdout>"
-yy124: ++YYCURSOR;
- goto yy125;
-yy125:
-#line 615 "token.re"
+#line 562 "token.re"
{ RETURN_IMPLICIT(); }
-#line 1650 "<stdout>"
-yy126: yych = *++YYCURSOR;
- goto yy123;
-yy127: yych = *++YYCURSOR;
- goto yy115;
-yy128: ++YYCURSOR;
- goto yy129;
-yy129:
-#line 611 "token.re"
+#line 1297 "<stdout>"
+yy122: yych = *++YYCURSOR;
+ goto yy113;
+yy123: ++YYCURSOR;
+ goto yy124;
+yy124:
+#line 558 "token.re"
{ eat_comments( parser );
RETURN_IMPLICIT();
}
-#line 1662 "<stdout>"
+#line 1307 "<stdout>"
+yy125: yych = *++YYCURSOR;
+ goto yy116;
+yy126: ++YYCURSOR;
+ if(YYLIMIT == YYCURSOR) YYFILL(1);
+ yych = *YYCURSOR;
+ goto yy127;
+yy127: switch(yych){
+ case ' ': goto yy126;
+ default: goto yy116;
+ }
+yy128: yych = *++YYCURSOR;
+ switch(yych){
+ case '\n': goto yy125;
+ default: goto yy129;
+ }
+yy129: YYCURSOR = YYMARKER;
+ switch(yyaccept){
+ case 0: goto yy111;
+ case 1: goto yy113;
+ }
yy130: ++YYCURSOR;
goto yy131;
yy131:
-#line 578 "token.re"
-{ if ( plvl->status != syck_lvl_iseq && plvl->status != syck_lvl_imap )
- {
- PLAIN_NOT_INL();
- }
- else
- {
- PLAIN_IS_INL();
- }
- RETURN_IMPLICIT();
- }
-#line 1677 "<stdout>"
+#line 533 "token.re"
+{ RETURN_IMPLICIT(); }
+#line 1334 "<stdout>"
yy132: ++YYCURSOR;
if(YYLIMIT == YYCURSOR) YYFILL(1);
yych = *YYCURSOR;
@@ -1685,52 +1638,28 @@ yy133: switch(yych){
}
yy134: yych = *++YYCURSOR;
switch(yych){
- case 0x0A: goto yy130;
- default: goto yy135;
- }
-yy135: YYCURSOR = YYMARKER;
- switch(yyaccept){
- case 0: goto yy113;
- case 1: goto yy115;
- }
-yy136: ++YYCURSOR;
- goto yy137;
-yy137:
-#line 576 "token.re"
-{ RETURN_IMPLICIT(); }
-#line 1701 "<stdout>"
-yy138: ++YYCURSOR;
- if(YYLIMIT == YYCURSOR) YYFILL(1);
- yych = *YYCURSOR;
- goto yy139;
-yy139: switch(yych){
- case ' ': goto yy138;
- default: goto yy137;
- }
-yy140: yych = *++YYCURSOR;
- switch(yych){
- case 0x0A: goto yy136;
- default: goto yy135;
+ case '\n': goto yy130;
+ default: goto yy129;
}
-yy141: yyaccept = 0;
+yy135: yyaccept = 0;
YYMARKER = ++YYCURSOR;
if(YYLIMIT == YYCURSOR) YYFILL(1);
yych = *YYCURSOR;
- goto yy142;
-yy142: switch(yych){
- case 0x0A: case ' ': goto yy141;
- case 0x0D: goto yy143;
- default: goto yy113;
+ goto yy136;
+yy136: switch(yych){
+ case '\n': case ' ': goto yy135;
+ case '\r': goto yy137;
+ default: goto yy111;
}
-yy143: ++YYCURSOR;
+yy137: ++YYCURSOR;
if(YYLIMIT == YYCURSOR) YYFILL(1);
yych = *YYCURSOR;
switch(yych){
- case 0x0A: goto yy141;
- default: goto yy135;
+ case '\n': goto yy135;
+ default: goto yy129;
}
}
-#line 631 "token.re"
+#line 570 "token.re"
}
@@ -1744,27 +1673,27 @@ SingleQuote2:
YYTOKEN = YYCURSOR;
-#line 1747 "<stdout>"
+#line 1370 "<stdout>"
{
YYCTYPE yych;
unsigned int yyaccept;
- goto yy144;
- ++YYCURSOR;
-yy144:
+ goto yy138;
+yy139: ++YYCURSOR;
+yy138:
if((YYLIMIT - YYCURSOR) < 2) YYFILL(2);
yych = *YYCURSOR;
switch(yych){
- case 0x00: goto yy152;
- case 0x0A: goto yy146;
- case 0x0D: goto yy148;
- case '\'': goto yy150;
- default: goto yy153;
+ case '\000': goto yy146;
+ case '\n': goto yy140;
+ case '\r': goto yy142;
+ case '\'': goto yy144;
+ default: goto yy147;
}
-yy146: yyaccept = 0;
+yy140: yyaccept = 0;
yych = *(YYMARKER = ++YYCURSOR);
- goto yy157;
-yy147:
-#line 645 "token.re"
+ goto yy151;
+yy141:
+#line 584 "token.re"
{ int indt_len;
int nl_count = 0;
SyckLevel *lvl;
@@ -1782,8 +1711,8 @@ yy147:
while ( YYTOKEN < YYCURSOR )
{
- int nl_len = newline_len( YYTOKEN++ );
- if ( nl_len )
+ int nl_len = 0;
+ if ( nl_len = newline_len( YYTOKEN++ ) )
{
nl_count++;
YYTOKEN += nl_len - 1;
@@ -1804,25 +1733,25 @@ yy147:
goto SingleQuote2;
}
-#line 1807 "<stdout>"
-yy148: ++YYCURSOR;
+#line 1430 "<stdout>"
+yy142: ++YYCURSOR;
switch((yych = *YYCURSOR)) {
- case 0x0A: goto yy156;
- default: goto yy149;
+ case '\n': goto yy150;
+ default: goto yy143;
}
-yy149:
-#line 712 "token.re"
+yy143:
+#line 644 "token.re"
{ QUOTECAT(qstr, qcapa, qidx, *(YYCURSOR - 1));
goto SingleQuote2;
}
-#line 1818 "<stdout>"
-yy150: ++YYCURSOR;
+#line 1441 "<stdout>"
+yy144: ++YYCURSOR;
switch((yych = *YYCURSOR)) {
- case '\'': goto yy154;
- default: goto yy151;
+ case '\'': goto yy148;
+ default: goto yy145;
}
-yy151:
-#line 689 "token.re"
+yy145:
+#line 628 "token.re"
{ SyckLevel *lvl;
SyckNode *n = syck_alloc_str();
lvl = CURRENT_LEVEL();
@@ -1831,56 +1760,49 @@ yy151:
{
POP_LEVEL();
}
- if ( ((SyckParser *)parser)->taguri_expansion == 1 )
- {
- n->type_id = syck_taguri( YAML_DOMAIN, "str", 3 );
- }
- else
- {
- n->type_id = syck_strndup( "str", 3 );
- }
+ n->type_id = syck_strndup( "str", 3 );
n->data.str->ptr = qstr;
n->data.str->len = qidx;
n->data.str->style = scalar_1quote;
sycklval->nodeData = n;
return YAML_PLAIN;
}
-#line 1848 "<stdout>"
-yy152: yych = *++YYCURSOR;
- goto yy151;
-yy153: yych = *++YYCURSOR;
+#line 1464 "<stdout>"
+yy146: yych = *++YYCURSOR;
+ goto yy145;
+yy147: yych = *++YYCURSOR;
+ goto yy143;
+yy148: ++YYCURSOR;
goto yy149;
-yy154: ++YYCURSOR;
- goto yy155;
-yy155:
-#line 685 "token.re"
+yy149:
+#line 624 "token.re"
{ QUOTECAT(qstr, qcapa, qidx, '\'');
goto SingleQuote2;
}
-#line 1860 "<stdout>"
-yy156: yyaccept = 0;
+#line 1476 "<stdout>"
+yy150: yyaccept = 0;
YYMARKER = ++YYCURSOR;
if(YYLIMIT == YYCURSOR) YYFILL(1);
yych = *YYCURSOR;
- goto yy157;
-yy157: switch(yych){
- case 0x0A: case ' ': goto yy156;
- case 0x0D: goto yy158;
- default: goto yy147;
+ goto yy151;
+yy151: switch(yych){
+ case '\n': case ' ': goto yy150;
+ case '\r': goto yy152;
+ default: goto yy141;
}
-yy158: ++YYCURSOR;
+yy152: ++YYCURSOR;
if(YYLIMIT == YYCURSOR) YYFILL(1);
yych = *YYCURSOR;
switch(yych){
- case 0x0A: goto yy156;
- default: goto yy159;
+ case '\n': goto yy150;
+ default: goto yy153;
}
-yy159: YYCURSOR = YYMARKER;
+yy153: YYCURSOR = YYMARKER;
switch(yyaccept){
- case 0: goto yy147;
+ case 0: goto yy141;
}
}
-#line 716 "token.re"
+#line 648 "token.re"
}
@@ -1898,28 +1820,28 @@ DoubleQuote2:
-#line 1901 "<stdout>"
+#line 1502 "<stdout>"
{
YYCTYPE yych;
unsigned int yyaccept;
- goto yy160;
- ++YYCURSOR;
-yy160:
+ goto yy154;
+yy155: ++YYCURSOR;
+yy154:
if((YYLIMIT - YYCURSOR) < 4) YYFILL(4);
yych = *YYCURSOR;
switch(yych){
- case 0x00: goto yy167;
- case 0x0A: goto yy162;
- case 0x0D: goto yy164;
- case '"': goto yy169;
- case '\\': goto yy166;
- default: goto yy170;
- }
-yy162: yyaccept = 0;
+ case '\000': goto yy161;
+ case '\n': goto yy156;
+ case '\r': goto yy158;
+ case '"': goto yy163;
+ case '\\': goto yy160;
+ default: goto yy164;
+ }
+yy156: yyaccept = 0;
yych = *(YYMARKER = ++YYCURSOR);
- goto yy184;
-yy163:
-#line 734 "token.re"
+ goto yy178;
+yy157:
+#line 666 "token.re"
{ int indt_len;
int nl_count = 0;
SyckLevel *lvl;
@@ -1939,8 +1861,8 @@ yy163:
{
while ( YYTOKEN < YYCURSOR )
{
- int nl_len = newline_len( YYTOKEN++ );
- if ( nl_len )
+ int nl_len = 0;
+ if ( nl_len = newline_len( YYTOKEN++ ) )
{
nl_count++;
YYTOKEN += nl_len - 1;
@@ -1963,34 +1885,34 @@ yy163:
keep_nl = 1;
goto DoubleQuote2;
}
-#line 1966 "<stdout>"
-yy164: ++YYCURSOR;
+#line 1567 "<stdout>"
+yy158: ++YYCURSOR;
switch((yych = *YYCURSOR)) {
- case 0x0A: goto yy183;
- default: goto yy165;
+ case '\n': goto yy177;
+ default: goto yy159;
}
-yy165:
-#line 820 "token.re"
+yy159:
+#line 745 "token.re"
{ QUOTECAT(qstr, qcapa, qidx, *(YYCURSOR - 1));
goto DoubleQuote2;
}
-#line 1977 "<stdout>"
-yy166: yyaccept = 1;
+#line 1578 "<stdout>"
+yy160: yyaccept = 1;
yych = *(YYMARKER = ++YYCURSOR);
switch(yych){
- case 0x0A: goto yy174;
- case 0x0D: goto yy176;
- case ' ': goto yy171;
+ case '\n': goto yy168;
+ case '\r': goto yy170;
+ case ' ': goto yy165;
case '"': case '0': case '\\': case 'a':
case 'b': case 'e':
- case 'f': case 'n': case 'r': case 't': case 'v': goto yy178;
- case 'x': goto yy177;
- default: goto yy165;
- }
-yy167: ++YYCURSOR;
- goto yy168;
-yy168:
-#line 797 "token.re"
+ case 'f': case 'n': case 'r': case 't': case 'v': goto yy172;
+ case 'x': goto yy171;
+ default: goto yy159;
+ }
+yy161: ++YYCURSOR;
+ goto yy162;
+yy162:
+#line 729 "token.re"
{ SyckLevel *lvl;
SyckNode *n = syck_alloc_str();
lvl = CURRENT_LEVEL();
@@ -1999,55 +1921,48 @@ yy168:
{
POP_LEVEL();
}
- if ( ((SyckParser *)parser)->taguri_expansion == 1 )
- {
- n->type_id = syck_taguri( YAML_DOMAIN, "str", 3 );
- }
- else
- {
- n->type_id = syck_strndup( "str", 3 );
- }
+ n->type_id = syck_strndup( "str", 3 );
n->data.str->ptr = qstr;
n->data.str->len = qidx;
n->data.str->style = scalar_2quote;
sycklval->nodeData = n;
return YAML_PLAIN;
}
-#line 2016 "<stdout>"
-yy169: yych = *++YYCURSOR;
- goto yy168;
-yy170: yych = *++YYCURSOR;
- goto yy165;
-yy171: ++YYCURSOR;
- if((YYLIMIT - YYCURSOR) < 2) YYFILL(2);
+#line 1610 "<stdout>"
+yy163: yych = *++YYCURSOR;
+ goto yy162;
+yy164: yych = *++YYCURSOR;
+ goto yy159;
+yy165: ++YYCURSOR;
+ if(YYLIMIT == YYCURSOR) YYFILL(1);
yych = *YYCURSOR;
- goto yy172;
-yy172: switch(yych){
- case 0x0A: goto yy174;
- case 0x0D: goto yy176;
- case ' ': goto yy171;
- default: goto yy173;
- }
-yy173: YYCURSOR = YYMARKER;
+ goto yy166;
+yy166: switch(yych){
+ case '\n': goto yy168;
+ case '\r': goto yy170;
+ case ' ': goto yy165;
+ default: goto yy167;
+ }
+yy167: YYCURSOR = YYMARKER;
switch(yyaccept){
- case 0: goto yy163;
- case 1: goto yy165;
+ case 0: goto yy157;
+ case 1: goto yy159;
}
-yy174: ++YYCURSOR;
- goto yy175;
-yy175:
-#line 792 "token.re"
+yy168: ++YYCURSOR;
+ goto yy169;
+yy169:
+#line 724 "token.re"
{ keep_nl = 0;
YYCURSOR--;
goto DoubleQuote2;
}
-#line 2044 "<stdout>"
-yy176: yych = *++YYCURSOR;
+#line 1639 "<stdout>"
+yy170: yych = *++YYCURSOR;
switch(yych){
- case 0x0A: goto yy174;
- default: goto yy173;
+ case '\n': goto yy168;
+ default: goto yy167;
}
-yy177: yych = *++YYCURSOR;
+yy171: yych = *++YYCURSOR;
switch(yych){
case '0':
case '1':
@@ -2068,19 +1983,19 @@ yy177: yych = *++YYCURSOR;
case 'c':
case 'd':
case 'e':
- case 'f': goto yy180;
- default: goto yy173;
+ case 'f': goto yy174;
+ default: goto yy167;
}
-yy178: ++YYCURSOR;
- goto yy179;
-yy179:
-#line 778 "token.re"
+yy172: ++YYCURSOR;
+ goto yy173;
+yy173:
+#line 710 "token.re"
{ char ch = *( YYCURSOR - 1 );
QUOTECAT(qstr, qcapa, qidx, escape_seq( ch ));
goto DoubleQuote2;
}
-#line 2082 "<stdout>"
-yy180: yych = *++YYCURSOR;
+#line 1677 "<stdout>"
+yy174: yych = *++YYCURSOR;
switch(yych){
case '0':
case '1':
@@ -2101,13 +2016,13 @@ yy180: yych = *++YYCURSOR;
case 'c':
case 'd':
case 'e':
- case 'f': goto yy181;
- default: goto yy173;
+ case 'f': goto yy175;
+ default: goto yy167;
}
-yy181: ++YYCURSOR;
- goto yy182;
-yy182:
-#line 783 "token.re"
+yy175: ++YYCURSOR;
+ goto yy176;
+yy176:
+#line 715 "token.re"
{ long ch;
char *chr_text = syck_strndup( YYTOKEN, 4 );
chr_text[0] = '0';
@@ -2116,26 +2031,26 @@ yy182:
QUOTECAT(qstr, qcapa, qidx, ch);
goto DoubleQuote2;
}
-#line 2119 "<stdout>"
-yy183: yyaccept = 0;
+#line 1714 "<stdout>"
+yy177: yyaccept = 0;
YYMARKER = ++YYCURSOR;
if(YYLIMIT == YYCURSOR) YYFILL(1);
yych = *YYCURSOR;
- goto yy184;
-yy184: switch(yych){
- case 0x0A: case ' ': goto yy183;
- case 0x0D: goto yy185;
- default: goto yy163;
+ goto yy178;
+yy178: switch(yych){
+ case '\n': case ' ': goto yy177;
+ case '\r': goto yy179;
+ default: goto yy157;
}
-yy185: ++YYCURSOR;
+yy179: ++YYCURSOR;
if(YYLIMIT == YYCURSOR) YYFILL(1);
yych = *YYCURSOR;
switch(yych){
- case 0x0A: goto yy183;
- default: goto yy173;
+ case '\n': goto yy177;
+ default: goto yy167;
}
}
-#line 824 "token.re"
+#line 749 "token.re"
}
@@ -2149,27 +2064,31 @@ TransferMethod2:
YYTOKTMP = YYCURSOR;
-#line 2152 "<stdout>"
+#line 1736 "<stdout>"
{
YYCTYPE yych;
unsigned int yyaccept;
- goto yy186;
- ++YYCURSOR;
-yy186:
+ goto yy180;
+yy181: ++YYCURSOR;
+yy180:
if((YYLIMIT - YYCURSOR) < 4) YYFILL(4);
yych = *YYCURSOR;
switch(yych){
- case 0x00: goto yy188;
- case 0x0A: goto yy190;
- case 0x0D: goto yy192;
- case ' ': goto yy191;
- case '\\': goto yy194;
- default: goto yy195;
- }
-yy188: ++YYCURSOR;
- goto yy189;
-yy189:
-#line 838 "token.re"
+ case '\000': goto yy182;
+ case '\n': goto yy183;
+ case '\r': goto yy186;
+ case ' ': goto yy185;
+ case '\\': goto yy188;
+ default: goto yy189;
+ }
+yy182: YYCURSOR = YYMARKER;
+ switch(yyaccept){
+ case 0: goto yy187;
+ }
+yy183: ++YYCURSOR;
+ goto yy184;
+yy184:
+#line 763 "token.re"
{ SyckLevel *lvl;
YYCURSOR = YYTOKTMP;
if ( YYCURSOR == YYTOKEN + 1 )
@@ -2219,34 +2138,32 @@ yy189:
return YAML_TRANSFER;
}
-#line 2222 "<stdout>"
-yy190: yych = *++YYCURSOR;
- goto yy189;
-yy191: yych = *++YYCURSOR;
- goto yy204;
-yy192: ++YYCURSOR;
+#line 1810 "<stdout>"
+yy185: yych = *++YYCURSOR;
+ goto yy198;
+yy186: ++YYCURSOR;
switch((yych = *YYCURSOR)) {
- case 0x0A: goto yy188;
- default: goto yy193;
+ case '\n': goto yy196;
+ default: goto yy187;
}
-yy193:
-#line 905 "token.re"
+yy187:
+#line 830 "token.re"
{ QUOTECAT(qstr, qcapa, qidx, *(YYCURSOR - 1));
goto TransferMethod2;
}
-#line 2237 "<stdout>"
-yy194: yyaccept = 0;
+#line 1823 "<stdout>"
+yy188: yyaccept = 0;
yych = *(YYMARKER = ++YYCURSOR);
switch(yych){
case '"': case '0': case '\\': case 'a':
case 'b': case 'e':
- case 'f': case 'n': case 'r': case 't': case 'v': goto yy198;
- case 'x': goto yy196;
- default: goto yy193;
+ case 'f': case 'n': case 'r': case 't': case 'v': goto yy191;
+ case 'x': goto yy190;
+ default: goto yy187;
}
-yy195: yych = *++YYCURSOR;
- goto yy193;
-yy196: yych = *++YYCURSOR;
+yy189: yych = *++YYCURSOR;
+ goto yy187;
+yy190: yych = *++YYCURSOR;
switch(yych){
case '0':
case '1':
@@ -2267,23 +2184,19 @@ yy196: yych = *++YYCURSOR;
case 'c':
case 'd':
case 'e':
- case 'f': goto yy200;
- default: goto yy197;
- }
-yy197: YYCURSOR = YYMARKER;
- switch(yyaccept){
- case 0: goto yy193;
+ case 'f': goto yy193;
+ default: goto yy182;
}
-yy198: ++YYCURSOR;
- goto yy199;
-yy199:
-#line 891 "token.re"
+yy191: ++YYCURSOR;
+ goto yy192;
+yy192:
+#line 816 "token.re"
{ char ch = *( YYCURSOR - 1 );
QUOTECAT(qstr, qcapa, qidx, escape_seq( ch ));
goto TransferMethod2;
}
-#line 2285 "<stdout>"
-yy200: yych = *++YYCURSOR;
+#line 1867 "<stdout>"
+yy193: yych = *++YYCURSOR;
switch(yych){
case '0':
case '1':
@@ -2304,13 +2217,13 @@ yy200: yych = *++YYCURSOR;
case 'c':
case 'd':
case 'e':
- case 'f': goto yy201;
- default: goto yy197;
+ case 'f': goto yy194;
+ default: goto yy182;
}
-yy201: ++YYCURSOR;
- goto yy202;
-yy202:
-#line 896 "token.re"
+yy194: ++YYCURSOR;
+ goto yy195;
+yy195:
+#line 821 "token.re"
{ long ch;
char *chr_text = syck_strndup( YYTOKTMP, 4 );
chr_text[0] = '0';
@@ -2319,17 +2232,19 @@ yy202:
QUOTECAT(qstr, qcapa, qidx, ch);
goto TransferMethod2;
}
-#line 2322 "<stdout>"
-yy203: ++YYCURSOR;
+#line 1904 "<stdout>"
+yy196: yych = *++YYCURSOR;
+ goto yy184;
+yy197: ++YYCURSOR;
if(YYLIMIT == YYCURSOR) YYFILL(1);
yych = *YYCURSOR;
- goto yy204;
-yy204: switch(yych){
- case ' ': goto yy203;
- default: goto yy189;
+ goto yy198;
+yy198: switch(yych){
+ case ' ': goto yy197;
+ default: goto yy184;
}
}
-#line 910 "token.re"
+#line 835 "token.re"
}
@@ -2344,7 +2259,8 @@ ScalarBlock:
int forceIndent = -1;
char *yyt = YYTOKEN;
SyckLevel *lvl = CURRENT_LEVEL();
- int parentIndent = -1;
+ int parentIndent;
+ GET_TRUE_YAML_INDENT(parentIndent);
switch ( *yyt )
{
@@ -2364,7 +2280,7 @@ ScalarBlock:
}
else if ( isdigit( *yyt ) )
{
- forceIndent = strtol( yyt, NULL, 10 );
+ forceIndent = strtol( yyt, NULL, 10 ) + parentIndent;
}
}
@@ -2375,51 +2291,46 @@ ScalarBlock2:
YYTOKEN = YYCURSOR;
-#line 2378 "<stdout>"
+#line 1919 "<stdout>"
{
YYCTYPE yych;
unsigned int yyaccept;
- goto yy205;
- ++YYCURSOR;
-yy205:
+ goto yy199;
+yy200: ++YYCURSOR;
+yy199:
if((YYLIMIT - YYCURSOR) < 5) YYFILL(5);
yych = *YYCURSOR;
switch(yych){
- case 0x00: goto yy213;
- case 0x0A: goto yy207;
- case 0x0D: goto yy209;
- case '#': goto yy211;
- case '-': goto yy215;
- default: goto yy216;
- }
-yy207: yyaccept = 0;
+ case '\000': goto yy207;
+ case '\n': goto yy201;
+ case '\r': goto yy203;
+ case '#': goto yy205;
+ case '-': goto yy209;
+ default: goto yy210;
+ }
+yy201: yyaccept = 0;
yych = *(YYMARKER = ++YYCURSOR);
- goto yy226;
-yy208:
-#line 956 "token.re"
+ goto yy220;
+yy202:
+#line 882 "token.re"
{ char *pacer;
char *tok = YYTOKEN;
int indt_len = 0, nl_count = 0, fold_nl = 0, nl_begin = 0;
GOBBLE_UP_YAML_INDENT( indt_len, tok );
lvl = CURRENT_LEVEL();
- if ( lvl->status != syck_lvl_block )
+ if ( indt_len > parentIndent && lvl->status != syck_lvl_block )
{
- GET_TRUE_YAML_INDENT(parentIndent);
- if ( forceIndent > 0 ) forceIndent += parentIndent;
- if ( indt_len > parentIndent )
- {
- int new_spaces = forceIndent > 0 ? forceIndent : indt_len;
- ADD_LEVEL( new_spaces, syck_lvl_block );
- lastIndent = indt_len - new_spaces;
- nl_begin = 1;
- lvl = CURRENT_LEVEL();
- }
- else
- {
- YYCURSOR = YYTOKEN;
- RETURN_YAML_BLOCK();
- }
+ int new_spaces = forceIndent > 0 ? forceIndent : indt_len;
+ ADD_LEVEL( new_spaces, syck_lvl_block );
+ lastIndent = indt_len - new_spaces;
+ nl_begin = 1;
+ lvl = CURRENT_LEVEL();
+ }
+ else if ( lvl->status != syck_lvl_block )
+ {
+ YYCURSOR = YYTOKEN;
+ RETURN_YAML_BLOCK();
}
/*
@@ -2434,8 +2345,8 @@ yy208:
pacer = YYTOKEN;
while ( pacer < YYCURSOR )
{
- int nl_len = newline_len( pacer++ );
- if ( nl_len )
+ int nl_len = 0;
+ if ( nl_len = newline_len( pacer++ ) )
{
nl_count++;
pacer += nl_len - 1;
@@ -2471,22 +2382,22 @@ yy208:
}
goto ScalarBlock2;
}
-#line 2474 "<stdout>"
-yy209: ++YYCURSOR;
+#line 2010 "<stdout>"
+yy203: ++YYCURSOR;
switch((yych = *YYCURSOR)) {
- case 0x0A: goto yy225;
- default: goto yy210;
+ case '\n': goto yy219;
+ default: goto yy204;
}
-yy210:
-#line 1070 "token.re"
+yy204:
+#line 991 "token.re"
{ QUOTECAT(qstr, qcapa, qidx, *YYTOKEN);
goto ScalarBlock2;
}
-#line 2485 "<stdout>"
-yy211: ++YYCURSOR;
- goto yy212;
-yy212:
-#line 1032 "token.re"
+#line 2021 "<stdout>"
+yy205: ++YYCURSOR;
+ goto yy206;
+yy206:
+#line 953 "token.re"
{ lvl = CURRENT_LEVEL();
if ( lvl->status != syck_lvl_block )
{
@@ -2499,45 +2410,45 @@ yy212:
}
goto ScalarBlock2;
}
-#line 2502 "<stdout>"
-yy213: ++YYCURSOR;
- goto yy214;
-yy214:
-#line 1046 "token.re"
+#line 2038 "<stdout>"
+yy207: ++YYCURSOR;
+ goto yy208;
+yy208:
+#line 967 "token.re"
{ YYCURSOR--;
POP_LEVEL();
RETURN_YAML_BLOCK();
}
-#line 2511 "<stdout>"
-yy215: yyaccept = 1;
+#line 2047 "<stdout>"
+yy209: yyaccept = 1;
yych = *(YYMARKER = ++YYCURSOR);
switch(yych){
- case '-': goto yy217;
- default: goto yy210;
+ case '-': goto yy211;
+ default: goto yy204;
}
-yy216: yych = *++YYCURSOR;
- goto yy210;
-yy217: yych = *++YYCURSOR;
+yy210: yych = *++YYCURSOR;
+ goto yy204;
+yy211: yych = *++YYCURSOR;
switch(yych){
- case '-': goto yy219;
- default: goto yy218;
+ case '-': goto yy213;
+ default: goto yy212;
}
-yy218: YYCURSOR = YYMARKER;
+yy212: YYCURSOR = YYMARKER;
switch(yyaccept){
- case 0: goto yy208;
- case 1: goto yy210;
+ case 0: goto yy202;
+ case 1: goto yy204;
}
-yy219: yych = *++YYCURSOR;
+yy213: yych = *++YYCURSOR;
switch(yych){
- case 0x0A: goto yy220;
- case 0x0D: goto yy224;
- case ' ': goto yy222;
- default: goto yy218;
- }
-yy220: ++YYCURSOR;
- goto yy221;
-yy221:
-#line 1051 "token.re"
+ case '\n': goto yy214;
+ case '\r': goto yy218;
+ case ' ': goto yy216;
+ default: goto yy212;
+ }
+yy214: ++YYCURSOR;
+ goto yy215;
+yy215:
+#line 972 "token.re"
{ if ( YYTOKEN == YYLINEPTR )
{
if ( blockType == BLOCK_FOLD && qidx > 0 )
@@ -2556,39 +2467,39 @@ yy221:
goto ScalarBlock2;
}
}
-#line 2559 "<stdout>"
-yy222: ++YYCURSOR;
+#line 2095 "<stdout>"
+yy216: ++YYCURSOR;
if(YYLIMIT == YYCURSOR) YYFILL(1);
yych = *YYCURSOR;
- goto yy223;
-yy223: switch(yych){
- case ' ': goto yy222;
- default: goto yy221;
+ goto yy217;
+yy217: switch(yych){
+ case ' ': goto yy216;
+ default: goto yy215;
}
-yy224: yych = *++YYCURSOR;
+yy218: yych = *++YYCURSOR;
switch(yych){
- case 0x0A: goto yy220;
- default: goto yy218;
+ case '\n': goto yy214;
+ default: goto yy212;
}
-yy225: yyaccept = 0;
+yy219: yyaccept = 0;
YYMARKER = ++YYCURSOR;
if(YYLIMIT == YYCURSOR) YYFILL(1);
yych = *YYCURSOR;
- goto yy226;
-yy226: switch(yych){
- case 0x0A: case ' ': goto yy225;
- case 0x0D: goto yy227;
- default: goto yy208;
+ goto yy220;
+yy220: switch(yych){
+ case '\n': case ' ': goto yy219;
+ case '\r': goto yy221;
+ default: goto yy202;
}
-yy227: ++YYCURSOR;
+yy221: ++YYCURSOR;
if(YYLIMIT == YYCURSOR) YYFILL(1);
yych = *YYCURSOR;
switch(yych){
- case 0x0A: goto yy225;
- default: goto yy218;
+ case '\n': goto yy219;
+ default: goto yy212;
}
}
-#line 1075 "token.re"
+#line 996 "token.re"
}
@@ -2604,67 +2515,67 @@ Comment:
YYTOKEN = YYCURSOR;
-#line 2607 "<stdout>"
+#line 2131 "<stdout>"
{
YYCTYPE yych;
unsigned int yyaccept;
- goto yy228;
- ++YYCURSOR;
-yy228:
+ goto yy222;
+yy223: ++YYCURSOR;
+yy222:
if((YYLIMIT - YYCURSOR) < 2) YYFILL(2);
yych = *YYCURSOR;
switch(yych){
- case 0x00: goto yy230;
- case 0x0A: goto yy232;
- case 0x0D: goto yy233;
- default: goto yy235;
- }
-yy230: ++YYCURSOR;
- goto yy231;
-yy231:
-#line 1091 "token.re"
+ case '\000': goto yy224;
+ case '\n': goto yy226;
+ case '\r': goto yy227;
+ default: goto yy229;
+ }
+yy224: ++YYCURSOR;
+ goto yy225;
+yy225:
+#line 1012 "token.re"
{ YYCURSOR = YYTOKEN;
return;
}
-#line 2629 "<stdout>"
-yy232: yyaccept = 0;
+#line 2153 "<stdout>"
+yy226: yyaccept = 0;
yych = *(YYMARKER = ++YYCURSOR);
- goto yy237;
-yy233: ++YYCURSOR;
+ goto yy231;
+yy227: ++YYCURSOR;
switch((yych = *YYCURSOR)) {
- case 0x0A: goto yy236;
- default: goto yy234;
+ case '\n': goto yy230;
+ default: goto yy228;
}
-yy234:
-#line 1095 "token.re"
+yy228:
+#line 1016 "token.re"
{ goto Comment;
}
-#line 2642 "<stdout>"
-yy235: yych = *++YYCURSOR;
- goto yy234;
-yy236: yyaccept = 0;
+#line 2166 "<stdout>"
+yy229: yych = *++YYCURSOR;
+ goto yy228;
+yy230: yyaccept = 0;
YYMARKER = ++YYCURSOR;
if(YYLIMIT == YYCURSOR) YYFILL(1);
yych = *YYCURSOR;
- goto yy237;
-yy237: switch(yych){
- case 0x0A: goto yy236;
- case 0x0D: goto yy238;
- default: goto yy231;
+ goto yy231;
+yy231: switch(yych){
+ case '\n': goto yy230;
+ case '\r': goto yy232;
+ default: goto yy225;
}
-yy238: ++YYCURSOR;
+yy232: ++YYCURSOR;
if(YYLIMIT == YYCURSOR) YYFILL(1);
yych = *YYCURSOR;
switch(yych){
- case 0x0A: goto yy236;
- default: goto yy239;
+ case '\n': goto yy230;
+ default: goto yy233;
}
-yy239: YYCURSOR = YYMARKER;
+yy233: YYCURSOR = YYMARKER;
switch(yyaccept){
- case 0: goto yy231;
+ case 0: goto yy225;
}
}
-#line 1098 "token.re"
+#line 1019 "token.re"
}
diff --git a/ext/syck/yaml2byte.c b/ext/syck/yaml2byte.c
index 61cd8c8eac..b2dc450ffa 100644
--- a/ext/syck/yaml2byte.c
+++ b/ext/syck/yaml2byte.c
@@ -1,5 +1,5 @@
/*
- * yaml2byte.c
+ * ybext.c
*
* $Author$
* $Date$
@@ -226,17 +226,12 @@ syck_yaml2byte(char *yamlstr)
syck_parser_implicit_typing( parser, 1 );
syck_parser_taguri_expansion( parser, 1 );
oid = syck_parse( parser );
+ syck_lookup_sym( parser, oid, (char **)&sav );
- if ( syck_lookup_sym( parser, oid, (char **)&sav ) == 1 ) {
- ret = S_ALLOC_N( char, strlen( sav->buffer ) + 3 );
- ret[0] = '\0';
- strcat( ret, "D\n" );
- strcat( ret, sav->buffer );
- }
- else
- {
- ret = NULL;
- }
+ ret = S_ALLOC_N( char, strlen( sav->buffer ) + 3 );
+ ret[0] = '\0';
+ strcat( ret, "D\n" );
+ strcat( ret, sav->buffer );
syck_free_parser( parser );
return ret;
diff --git a/ext/tcltklib/MANUAL.eng b/ext/tcltklib/MANUAL.eng
index 1db61f228e..d3417f5dff 100644
--- a/ext/tcltklib/MANUAL.eng
+++ b/ext/tcltklib/MANUAL.eng
@@ -1,5 +1,5 @@
(tof)
- 2005/07/05 Hidetoshi NAGAI
+ 2004/03/28 Hidetoshi NAGAI
This document discribes about the 'tcltklib' library. Although there
is the 'tcltk' library (tcltk.rb) under this directory, no description
@@ -132,16 +132,6 @@ module TclTklib
: If 'check_root' is false, doen't return by the other
: reasons than exceptions.
- mainloop_thread?
- : Returns whether the current thread executes the eventloop.
- : If true, the eventloop is working on the current thread.
- : If no eventloop is working, this method returns nil.
- : And if the other thread executes the eventloop, returns false.
- :
- : *** ATTENTION ***
- : When this methods returns false, it is dangerous to call a Tk
- : interpreter directly.
-
mainloop_watchdog(check_root = true)
: On the normal eventloop, some kinds of callback operations
: cause deadlock. To avoid some of such deadlocks, this
@@ -227,8 +217,8 @@ module TclTklib
: Convert the argument to a valid Tcl list element with
: Tcl/Tk's library function.
- _toUTF8(str, encoding=nil)
- _fromUTF8(str, encoding=nil)
+ _toUTF8(str, encoding)
+ _fromUTF8(str, encoding)
: Call the function (which is internal function of Tcl/Tk) to
: convert to/from a UTF8 string.
@@ -239,16 +229,6 @@ module TclTklib
: _subst_Tcl_backslash method parses all backslash sequence.
: _subst_UTF_backslash method parses \uhhhh only.
- encoding_system
- encoding_system=(encoding)
- : Get and set Tcl's system encoding.
-
- encoding
- encoding=(encoding)
- : alias of encoding_system / encoding_system=
- : ( probably, Ruby/Tk's tk.rb will override them )
-
-
class TclTkIp
[class methods]
new(ip_name=nil, options='')
@@ -310,11 +290,6 @@ class TclTkIp
: Check whether the interpreter is already deleted.
: If deleted, returns true.
- has_mainwindow?
- : Check whether the interpreter has a MainWindow (root widget).
- : If has, returns true. If doesn't, returns false.
- : If IP is already deleted, returns nil.
-
restart
: Restart Tk part of the interpreter.
: Use this when you need Tk functions after destroying the
@@ -337,8 +312,8 @@ class TclTkIp
: to _eval and regist the command once, after that, the
: command can be called by _invoke.
- _toUTF8(str, encoding=nil)
- _fromUTF8(str, encoding=nil)
+ _toUTF8(str, encoding)
+ _fromUTF8(str, encoding)
: Call the function (which is internal function of Tcl/Tk) to
: convert to/from a UTF8 string.
diff --git a/ext/tcltklib/MANUAL.euc b/ext/tcltklib/MANUAL.euc
index 5dd36726ba..a0d7e42307 100644
--- a/ext/tcltklib/MANUAL.euc
+++ b/ext/tcltklib/MANUAL.euc
@@ -1,5 +1,5 @@
(tof)
- 2005/07/05 Hidetoshi NAGAI
+ 2004/03/28 Hidetoshi NAGAI
Ëܥɥ­¥å¥á¥ó¥È¤Ë¤Ï¸Å¤¤ tcltk ¥é¥¤¥Ö¥é¥ê¡¤tcltklib ¥é¥¤¥Ö¥é¥ê¤ÎÀâÌÀ
¤¬´Þ¤Þ¤ì¤Æ¤¤¤Þ¤¹¤¬¡¤¤½¤Îµ­½ÒÆâÍÆ¤Ï¸Å¤¤¤â¤Î¤È¤Ê¤Ã¤Æ¤¤¤Þ¤¹¡¥
@@ -230,15 +230,6 @@ require "tcltklib" ¤¹¤ë¤È, °Ê²¼¤Î¥â¥¸¥å¡¼¥ë, ¥¯¥é¥¹¤¬ÍøÍѲÄǽ¤Ç¤¹.
: WINDOW °Ê³°¤Î¥¤¥Ù¥ó¥È¤ÏȯÀ¸¤·¤¦¤ë¤¿¤á )¡¥½ªÎ»¤Ë¤Ï¡¤³°Éô
: ¤«¤é¤ÎƯ¤­³Ý¤± ( ¥¹¥ì¥Ã¥É¤ò³èÍѤ¹¤ë¤Ê¤É ) ¤¬É¬Íס¥
- mainloop_thread?
- : ¥«¥ì¥ó¥È¥¹¥ì¥Ã¥É¤¬¥¤¥Ù¥ó¥È¥ë¡¼¥×¤ò¼Â¹Ô¤·¤Æ¤¤¤ë¥¹¥ì¥Ã¥É
- : ¤«¤É¤¦¤«¤òÊÖ¤¹¡¥
- : ¥¤¥Ù¥ó¥È¥ë¡¼¥×¤ò¼Â¹Ô¤·¤Æ¤¤¤ë¥¹¥ì¥Ã¥É¤Ç¤¢¤ì¤Ð true ¤ò¡¤
- : ¤É¤Î¥¹¥ì¥Ã¥É¤Ç¤â¥¤¥Ù¥ó¥È¥ë¡¼¥×¤¬¼Â¹Ô¤µ¤ì¤Æ¤¤¤Ê¤¤¾ì¹ç¤Ï
- : nil ¤ò¡¤Â¾¤Î¥¹¥ì¥Ã¥É¤Ç¥¤¥Ù¥ó¥È¥ë¡¼¥×¤¬¼Â¹Ô¤µ¤ì¤Æ¤¤¤ë¾ì
- : ¹ç¤Ï false ¤òÊÖ¤¹¡¥
- : false ¤ÎºÝ¤Ë Tk ¥¤¥ó¥¿¡¼¥×¥ê¥¿¤òľÀÜ¸Æ¤Ö¤Î¤Ï´í¸±¤Ç¤¢¤ë¡¥
-
mainloop_watchdog(check_root = true)
: Ä̾ï¤Î¥¤¥Ù¥ó¥È¥ë¡¼¥×¤Ç¤Ï¡¤¥¤¥Ù¥ó¥È½èÍý¤ÎÆâÍÆ¤Ë¤è¤Ã¤Æ¤Ï
: ¥Ç¥Ã¥É¥í¥Ã¥¯¤ò°ú¤­µ¯¤³¤¹²ÄǽÀ­¤¬¤¢¤ë (Î㤨¤Ð¥¤¥Ù¥ó¥È¤Ë
@@ -341,8 +332,8 @@ require "tcltklib" ¤¹¤ë¤È, °Ê²¼¤Î¥â¥¸¥å¡¼¥ë, ¥¯¥é¥¹¤¬ÍøÍѲÄǽ¤Ç¤¹.
: °ì¤Ä¤Î¥ê¥¹¥ÈÍ×ÁǤȤ·¤ÆÅ¬ÀÚ¤Êɽ¸½¤Ë¤Ê¤ë¤è¤¦¤ËÊÑ´¹¤·¤¿Ê¸
: »úÎó¤òÊÖ¤¹¡¥
- _toUTF8(str, encoding=nil)
- _fromUTF8(str, encoding=nil)
+ _toUTF8(str, encoding)
+ _fromUTF8(str, encoding)
: Tcl/Tk ¤¬Æâ¢¤·¤Æ¤¤¤ë UTF8 ÊÑ´¹½èÍý¤ò¸Æ¤Ó½Ð¤¹¡¥
_subst_UTF_backslash(str)
@@ -353,16 +344,6 @@ require "tcltklib" ¤¹¤ë¤È, °Ê²¼¤Î¥â¥¸¥å¡¼¥ë, ¥¯¥é¥¹¤¬ÍøÍѲÄǽ¤Ç¤¹.
: ÃÖ¤­´¹¤¨¤ë¤Î¤ËÂФ·¡¤_subst_UTF_backslash ¤Ï \uhhhh
: ¤Ë¤è¤ë Unicode ʸ»úɽ¸½¤À¤±¤òÃÖ¤­´¹¤¨¤ë¡¥
- encoding_system
- encoding_system=(encoding)
- : Tcl ¤Î system encoding ¤Î³ÍÆÀ¤ª¤è¤ÓÀßÄê
-
- encoding
- encoding=(encoding)
- : encoding_system / encoding_system= ¤Î alias
- : ( Ruby/Tk ¤Î tk.rb ¤Ç¤ÏÃÖ¤­´¹¤¨¤é¤ì¤ëͽÄê¤Î¤â¤Î¡¥)
-
-
¥¯¥é¥¹ TclTkIp
¥¯¥é¥¹¥á¥½¥Ã¥É
new(ip_name=nil, options='')
@@ -396,7 +377,7 @@ require "tcltklib" ¤¹¤ë¤È, °Ê²¼¤Î¥â¥¸¥å¡¼¥ë, ¥¯¥é¥¹¤¬ÍøÍѲÄǽ¤Ç¤¹.
: ¼ºÇÔ¤·¤¿¾ì¹ç¤Ï RuntimeError ¤ÎÎã³°¤òȯÀ¸¤¹¤ë¡¥
safe?
- : Tcl/Tk ¥¤¥ó¥¿¡¼¥×¥ê¥¿¤¬ safe ¥¤¥ó¥¿¡¼¥×¥ê¥¿¤Ç¤¢¤ë¤«¤òÄ´¤Ù¤ë¡¥
+ : Tcl/Tk ¥¤¥ó¥¿¡¼¥×¥ê¥¿¤ò safe ¥¤¥ó¥¿¡¼¥×¥ê¥¿¤Ç¤¢¤ë¤«¤òÄ´¤Ù¤ë¡¥
: safe ¥¤¥ó¥¿¡¼¥×¥ê¥¿¤Ç¤¢¤ì¤Ð true ¤òÊÖ¤¹¡¥
allow_ruby_exit?
@@ -422,11 +403,6 @@ require "tcltklib" ¤¹¤ë¤È, °Ê²¼¤Î¥â¥¸¥å¡¼¥ë, ¥¯¥é¥¹¤¬ÍøÍѲÄǽ¤Ç¤¹.
: delete ºÑ¤ß¤Ç¥³¥Þ¥ó¥É¤ò¼õ¤±ÉÕ¤±¤Ê¤¤¾õÂ֤ˤʤäƤ¤¤ë¤Ê¤é¤Ð
: true ¤òÊÖ¤¹¡¥
- has_mainwindow?
- : Tcl/Tk ¥¤¥ó¥¿¡¼¥×¥ê¥¿¤Ë¥á¥¤¥ó¥¦¥£¥ó¥É¥¦ (root widget) ¤¬
- : ¸ºß¤¹¤ì¤Ð true ¤ò¡¤Â¸ºß¤·¤Ê¤±¤ì¤Ð false ¤òÊÖ¤¹¡¥
- : ¥¤¥ó¥¿¡¼¥×¥ê¥¿¤¬´û¤Ë delete ºÑ¤ß¤Ç¤¢¤ì¤Ð nil ¤òÊÖ¤¹¡¥
-
restart
: Tcl/Tk ¥¤¥ó¥¿¡¼¥×¥ê¥¿¤Î Tk Éôʬ¤Î½é´ü²½¡¤ºÆµ¯Æ°¤ò¹Ô¤¦¡¥
: °ìö root widget ¤òÇ˲õ¤·¤¿¸å¤ËºÆÅÙ Tk ¤Îµ¡Ç½¤¬É¬ÍפÈ
@@ -448,8 +424,8 @@ require "tcltklib" ¤¹¤ë¤È, °Ê²¼¤Î¥â¥¸¥å¡¼¥ë, ¥¯¥é¥¹¤¬ÍøÍѲÄǽ¤Ç¤¹.
: ¤·¤ÆÅÐÏ¿¤ËÀ®¸ù¤·¤µ¤¨¤¹¤ì¤Ð¡¤°Ê¹ß¤Ï _invoke ¤Ç¤âÍøÍѤÇ
: ¤­¤ë¤è¤¦¤Ë¤Ê¤ë¡¥
- _toUTF8(str, encoding=nil)
- _fromUTF8(str, encoding=nil)
+ _toUTF8(str, encoding)
+ _fromUTF8(str, encoding)
: Tcl/Tk ¤¬Æâ¢¤·¤Æ¤¤¤ë UTF8 ÊÑ´¹½èÍý¤ò¸Æ¤Ó½Ð¤¹¡¥
_thread_vwait(var_name)
diff --git a/ext/tcltklib/README.1st b/ext/tcltklib/README.1st
index 5d1da48a45..4d5cd93283 100644
--- a/ext/tcltklib/README.1st
+++ b/ext/tcltklib/README.1st
@@ -22,24 +22,7 @@ some or all of the following options.
--with-tcl-lib=<dir> the directry containts 'libtcl<version>.so'
--with-tk-lib=<dir> the directry containts 'libtk<version>.so'
- --enable-mac-tcltk-framework (MacOS X) use Tcl/Tk framework
- (Obsolete. Please use '--enable-tcltk-framework'.)
-
- --enable-tcltk-framework use Tcl/Tk framework
-
- --with-tcltk-framework=<dir> the directory containts Tcl/Tk framework;
- "<dir>/Tcl.framework" and "<dir>/Tk.framework".
- When this option is given, it is assumed that
- --enable-tcltk-framework option is given also.
-
- --with-tcl-framework-header=<dir>
- Tcl framework headers directory
- (e.g. "/Library/Frameworks/Tcl.framework/Headers")
-
- --with-tk-framework-header=<dir>
- Tk framework headers directory
- (e.g. "/Library/Frameworks/Tk.framework/Headers")
-
+ --enable-mac-tcltk-framework (Mac OSX only) use Tcl/Tk framework
If you forgot to give the options when do 'configure' on toplevel
directry of Ruby sources, please try something like as the followings.
diff --git a/ext/tcltklib/depend b/ext/tcltklib/depend
index 526a7b871c..2cd9c400f7 100644
--- a/ext/tcltklib/depend
+++ b/ext/tcltklib/depend
@@ -1,2 +1,2 @@
tcltklib.o: tcltklib.c $(hdrdir)/ruby.h $(topdir)/config.h $(hdrdir)/defines.h
-stubs.o: stubs.c stubs.h $(hdrdir)/ruby.h $(topdir)/config.h $(hdrdir)/defines.h
+stubs.o: stubs.c $(hdrdir)/ruby.h $(topdir)/config.h $(hdrdir)/defines.h
diff --git a/ext/tcltklib/extconf.rb b/ext/tcltklib/extconf.rb
index 94c817e39f..8ec34f0214 100644
--- a/ext/tcltklib/extconf.rb
+++ b/ext/tcltklib/extconf.rb
@@ -3,34 +3,13 @@
require 'mkmf'
is_win32 = (/mswin32|mingw|cygwin|bccwin32/ =~ RUBY_PLATFORM)
-#is_macosx = (/darwin/ =~ RUBY_PLATFORM)
+is_macosx = (/darwin/ =~ RUBY_PLATFORM)
-def find_framework(tcl_hdr, tk_hdr)
- if framework_dir = with_config("tcltk-framework")
- paths = [framework_dir]
- else
- unless tcl_hdr || tk_hdr ||
- enable_config("tcltk-framework", false) ||
- enable_config("mac-tcltk-framework", false)
- return false
- end
- paths = ["/Library/Frameworks", "/System/Library/Frameworks"]
- end
-
- checking_for('Tcl/Tk Framework') {
- paths.find{|dir|
- dir.strip!
- dir.chomp!('/')
- (tcl_hdr || FileTest.directory?(dir + "/Tcl.framework/") ) &&
- (tk_hdr || FileTest.directory?(dir + "/Tk.framework/") )
- }
- }
-end
-
-tcl_framework_header = with_config("tcl-framework-header")
-tk_framework_header = with_config("tk-framework-header")
-
-tcltk_framework = find_framework(tcl_framework_header, tk_framework_header)
+mac_need_framework =
+ is_macosx &&
+ enable_config("mac-tcltk-framework", false) &&
+ FileTest.directory?("/Library/Frameworks/Tcl.framework/") &&
+ FileTest.directory?("/Library/Frameworks/Tk.framework/")
unless is_win32
have_library("nsl", "t_open")
@@ -62,9 +41,7 @@ def find_tcl(tcllib, stubs)
true
else
%w[8.5 8.4 8.3 8.2 8.1 8.0 7.6].find { |ver|
- find_library("#{lib}#{ver}", func, *paths) or
- find_library("#{lib}#{ver.delete('.')}", func, *paths) or
- find_library("tcl#{ver}", func, *paths) or
+ find_library("tcl#{ver}", func, *paths) or
find_library("tcl#{ver.delete('.')}", func, *paths)
}
end
@@ -85,9 +62,7 @@ def find_tk(tklib, stubs)
true
else
%w[8.5 8.4 8.3 8.2 8.1 8.0 4.2].find { |ver|
- find_library("#{lib}#{ver}", func, *paths) or
- find_library("#{lib}#{ver.delete('.')}", func, *paths) or
- find_library("tk#{ver}", func, *paths) or
+ find_library("tk#{ver}", func, *paths) or
find_library("tk#{ver.delete('.')}", func, *paths)
}
end
@@ -172,11 +147,10 @@ def pthread_check()
** PTHREAD SUPPORT CHECK WARNING:
**
** We cannot check the consistency of pthread support between Ruby
-** and the Tcl/Tk library in your environment (are you perhaps
-** cross-compiling?). If pthread support for these 2 packages is
-** inconsistent you may find you get errors when running Ruby/Tk
-** (e.g. hangs or segmentation faults). We strongly recommend
-** you to check the consistency manually.
+** and Tcl/Tk library on your environment (do coss-compile?). If the
+** consistency is not kept, some memory troubles (e.g. "Hang-up" or
+** "Segmentation Fault") may bother you. We strongly you to check the
+** consistency by your own hand.
**
*****************************************************************************
')
@@ -188,15 +162,6 @@ def pthread_check()
# tcl-thread is unknown
if try_run(<<EOF)
#include <tcl.h>
-int main() {
- Tcl_Interp *ip;
- ip = Tcl_CreateInterp();
- exit((Tcl_Eval(ip, "set tcl_platform(threaded)") == TCL_OK)? 0: 1);
-}
-EOF
- tcl_enable_thread = true
- elsif try_run(<<EOF)
-#include <tcl.h>
static Tcl_ThreadDataKey dataKey;
int main() { exit((Tcl_GetThreadData(&dataKey, 1) == dataKey)? 1: 0); }
EOF
@@ -216,29 +181,23 @@ EOF
**
** PTHREAD SUPPORT MODE WARNING:
**
-** Ruby is compiled with --enable-pthread, but your Tcl/Tk library
-** seems to be compiled without pthread support. Although you can
-** create the tcltklib library, this combination may cause errors
-** (e.g. hangs or segmentation faults). If you have no reason to
-** keep the current pthread support status, we recommend you reconfigure
-** and recompile the libraries so that both or neither support pthreads.
+** Ruby is compiled with --enable-pthread, but your Tcl/Tk libraries
+** seems to be compiled without "pthread support". Although You can
+** create tcltklib library, this combination may cause memory trouble
+** (e.g. "Hang-up" or "Segmentation Fault"). If you have no reason you
+** must have to keep current pthread support status, we recommend you
+** to make both or neither libraries to support pthread.
**
** If you want change the status of pthread support, please recompile
** Ruby without "--enable-pthread" configure option or recompile Tcl/Tk
** with "--enable-threads" configure option (if your Tcl/Tk is later
-** than or equal to Tcl/Tk 8.1).
+** than or equal to Tcl/Tk8.1).
**
*****************************************************************************
')
end
# ruby -> enable && tcl -> enable/disable
- if tcl_enable_thread
- $CPPFLAGS += ' -DWITH_TCL_ENABLE_THREAD=1'
- else
- $CPPFLAGS += ' -DWITH_TCL_ENABLE_THREAD=0'
- end
-
return true
else
@@ -248,30 +207,28 @@ EOF
puts(%Q'\
*****************************************************************************
**
-** PTHREAD SUPPORT MODE ERROR:
+** PTHREAD SUPPORT MODE ERRROR:
**
** Ruby is not compiled with --enable-pthread, but your Tcl/Tk
-** library seems to be compiled with pthread support. This
-** combination may cause frequent hang or segmentation fault
-** errors when Ruby/Tk is working. We recommend that you NEVER
-** create the library with such a combination of pthread support.
+** libararies seems to be compiled with "pthread support". This
+** combination possibly cause "Hang-up" or "Segmentation Fault"
+** frequently when Ruby/Tk is working. We NEVER recommend you to
+** create the library under such combination of pthread support.
**
-** Please recompile Ruby with the "--enable-pthread" configure option
-** or recompile Tcl/Tk with the "--disable-threads" configure option.
+** Please recompile Ruby with "--enable-pthread" configure option
+** or recompile Tcl/Tk with "--disable-threads" configure option.
**
*****************************************************************************
')
- $CPPFLAGS += ' -DWITH_TCL_ENABLE_THREAD=1'
return false
else
# ruby -> disable && tcl -> disable
- $CPPFLAGS += ' -DWITH_TCL_ENABLE_THREAD=0'
return true
end
end
end
-if tcltk_framework ||
+if mac_need_framework ||
(have_header("tcl.h") && have_header("tk.h") &&
(is_win32 || find_library("X11", "XOpenDisplay",
"/usr/X11/lib", "/usr/lib/X11", "/usr/X11R6/lib", "/usr/openwin/lib")) &&
@@ -280,19 +237,8 @@ if tcltk_framework ||
$CPPFLAGS += ' -DUSE_TCL_STUBS -DUSE_TK_STUBS' if stubs
$CPPFLAGS += ' -D_WIN32' if /cygwin/ =~ RUBY_PLATFORM
- if tcltk_framework
- if tcl_framework_header
- $CPPFLAGS += " -I#{tcl_framework_header}"
- else
- $CPPFLAGS += " -I#{tcltk_framework}/Tcl.framework/Headers"
- end
-
- if tk_framework_header
- $CPPFLAGS += " -I#{tk_framework_header}"
- else
- $CPPFLAGS += " -I#{tcltk_framework}/Tk.framework/Headers"
- end
-
+ if mac_need_framework
+ $CPPFLAGS += ' -I/Library/Frameworks/Tcl.framework/headers -I/Library/Frameworks/Tk.framework/Headers'
$LDFLAGS += ' -framework Tk -framework Tcl'
end
diff --git a/ext/tcltklib/sample/sample1.rb b/ext/tcltklib/sample/sample1.rb
index 13df440751..77b79e6dbf 100644
--- a/ext/tcltklib/sample/sample1.rb
+++ b/ext/tcltklib/sample/sample1.rb
@@ -24,7 +24,7 @@ class Test1
c = ip.commands()
# »ÈÍѤ¹¤ë¥³¥Þ¥ó¥É¤ËÂбþ¤¹¤ë¥ª¥Ö¥¸¥§¥¯¥È¤ÏÊÑ¿ô¤ËÆþ¤ì¤Æ¤ª¤¯.
append, bind, button, destroy, incr, info, label, place, set, wm =
- c.values_at(
+ c.indexes(
"append", "bind", "button", "destroy", "incr", "info", "label", "place",
"set", "wm")
@@ -136,7 +136,7 @@ class Test1
# ¥µ¥ó¥×¥ë¤Î¤¿¤á¤Î¥¦¥£¥¸¥§¥Ã¥È¤òÀ¸À®¤¹¤ë.
def sample(ip, parent)
- bind, button, destroy, grid, toplevel, wm = ip.commands().values_at(
+ bind, button, destroy, grid, toplevel, wm = ip.commands().indexes(
"bind", "button", "destroy", "grid", "toplevel", "wm")
## toplevel
@@ -207,7 +207,7 @@ class Test1
# parent: ¿Æ¥¦¥£¥¸¥§¥Ã¥È
# title: toplevel ¥¦¥£¥¸¥§¥Ã¥È¤Î¥¦¥¤¥ó¥É¥¦¤Î¥¿¥¤¥È¥ë
def inittoplevel(ip, parent, title)
- bind, button, destroy, toplevel, wm = ip.commands().values_at(
+ bind, button, destroy, toplevel, wm = ip.commands().indexes(
"bind", "button", "destroy", "toplevel", "wm")
# ¿·¤·¤¤¥¦¥¤¥ó¥É¥¦¤ò³«¤¯¤Ë¤Ï, toplevel ¤ò»È¤¦.
@@ -229,7 +229,7 @@ class Test1
# label ¤Î¥µ¥ó¥×¥ë.
def test_label(ip, parent)
- button, global, label, pack = ip.commands().values_at(
+ button, global, label, pack = ip.commands().indexes(
"button", "global", "label", "pack")
t1, b1, cb = inittoplevel(ip, parent, "label")
@@ -272,7 +272,7 @@ class Test1
# button ¤Î¥µ¥ó¥×¥ë.
def test_button(ip, parent)
- button, pack = ip.commands().values_at("button", "pack")
+ button, pack = ip.commands().indexes("button", "pack")
t1, b1, cb = inittoplevel(ip, parent, "button")
## button
@@ -290,7 +290,7 @@ class Test1
# checkbutton ¤Î¥µ¥ó¥×¥ë.
def test_checkbutton(ip, parent)
- checkbutton, global, pack = ip.commands().values_at(
+ checkbutton, global, pack = ip.commands().indexes(
"checkbutton", "global", "pack")
t1, b1, cb = inittoplevel(ip, parent, "checkbutton")
@@ -306,7 +306,7 @@ class Test1
# radiobutton ¤Î¥µ¥ó¥×¥ë.
def test_radiobutton(ip, parent)
- global, label, pack, radiobutton = ip.commands().values_at(
+ global, label, pack, radiobutton = ip.commands().indexes(
"global", "label", "pack", "radiobutton")
t1, b1, cb = inittoplevel(ip, parent, "radiobutton")
@@ -330,7 +330,7 @@ class Test1
# scale ¤Î¥µ¥ó¥×¥ë.
def test_scale(ip, parent)
- global, pack, scale = ip.commands().values_at(
+ global, pack, scale = ip.commands().indexes(
"global", "pack", "scale")
t1, b1, cb = inittoplevel(ip, parent, "scale")
@@ -350,7 +350,7 @@ class Test1
# entry ¤Î¥µ¥ó¥×¥ë.
def test_entry(ip, parent)
- button, entry, global, pack = ip.commands().values_at(
+ button, entry, global, pack = ip.commands().indexes(
"button", "entry", "global", "pack")
t1, b1, cb = inittoplevel(ip, parent, "entry")
@@ -369,7 +369,7 @@ class Test1
# text ¤Î¥µ¥ó¥×¥ë.
def test_text(ip, parent)
- button, pack, text = ip.commands().values_at(
+ button, pack, text = ip.commands().indexes(
"button", "pack", "text")
t1, b1, cb = inittoplevel(ip, parent, "text")
@@ -385,7 +385,7 @@ class Test1
# raise/lower ¤Î¥µ¥ó¥×¥ë.
def test_raise(ip, parent)
- button, frame, lower, pack, raise = ip.commands().values_at(
+ button, frame, lower, pack, raise = ip.commands().indexes(
"button", "frame", "lower", "pack", "raise")
t1, b1, cb = inittoplevel(ip, parent, "raise/lower")
@@ -408,7 +408,7 @@ class Test1
# modal ¤Ê¥¦¥£¥¸¥§¥Ã¥È¤Î¥µ¥ó¥×¥ë.
def test_modal(ip, parent)
button, frame, message, pack, tk_chooseColor, tk_getOpenFile,
- tk_messageBox = ip.commands().values_at(
+ tk_messageBox = ip.commands().indexes(
"button", "frame", "message", "pack", "tk_chooseColor",
"tk_getOpenFile", "tk_messageBox")
# ºÇ½é¤Ë load ¤µ¤ì¤Æ¤¤¤Ê¤¤¥é¥¤¥Ö¥é¥ê¤Ï ip.commands() ¤Ë¸ºß¤·¤Ê¤¤¤Î¤Ç,
@@ -451,7 +451,7 @@ class Test1
# menu ¤Î¥µ¥ó¥×¥ë.
def test_menu(ip, parent)
- global, menu, menubutton, pack = ip.commands().values_at(
+ global, menu, menubutton, pack = ip.commands().indexes(
"global", "menu", "menubutton", "pack")
tk_optionMenu = TclTkLibCommand.new(ip, "tk_optionMenu")
t1, b1, cb = inittoplevel(ip, parent, "menu")
@@ -498,7 +498,7 @@ class Test1
# listbox ¤Î¥µ¥ó¥×¥ë.
def test_listbox(ip, parent)
clipboard, frame, grid, listbox, lower, menu, menubutton, pack, scrollbar,
- selection = ip.commands().values_at(
+ selection = ip.commands().indexes(
"clipboard", "frame", "grid", "listbox", "lower", "menu", "menubutton",
"pack", "scrollbar", "selection")
t1, b1, cb = inittoplevel(ip, parent, "listbox")
@@ -559,7 +559,7 @@ class Test1
# canvas ¤Î¥µ¥ó¥×¥ë.
def test_canvas(ip, parent)
- canvas, lower, pack = ip.commands().values_at("canvas", "lower", "pack")
+ canvas, lower, pack = ip.commands().indexes("canvas", "lower", "pack")
t1, b1, cb = inittoplevel(ip, parent, "canvas")
## canvas
diff --git a/ext/tcltklib/sample/sample2.rb b/ext/tcltklib/sample/sample2.rb
index 444bb1eef7..5d43470de3 100644
--- a/ext/tcltklib/sample/sample2.rb
+++ b/ext/tcltklib/sample/sample2.rb
@@ -19,7 +19,7 @@ require "tcltk"
$ip = TclTkInterpreter.new()
$root = $ip.rootwidget()
$button, $canvas, $checkbutton, $frame, $label, $pack, $update, $wm =
- $ip.commands().values_at(
+ $ip.commands().indexes(
"button", "canvas", "checkbutton", "frame", "label", "pack", "update", "wm")
class Othello
@@ -196,12 +196,10 @@ class Othello
def initialize(view, row, col)
@view = view
- @id = @view.e("create rectangle",
- *(view.tk_rect(view.left + col,
- view.top + row,
- view.left + col + 1,
- view.top + row + 1) \
- << "-fill #{BACK_GROUND_COLOR}") )
+ @id = @view.e("create rectangle", *view.tk_rect(view.left + col,
+ view.top + row,
+ view.left + col + 1,
+ view.top + row + 1))
@row = row
@col = col
@view.e("itemconfigure", @id,
diff --git a/ext/tcltklib/stubs.c b/ext/tcltklib/stubs.c
index 050333cf63..3913abb570 100644
--- a/ext/tcltklib/stubs.c
+++ b/ext/tcltklib/stubs.c
@@ -1,61 +1,7 @@
-#include "stubs.h"
-#include "ruby.h"
-#include <tcl.h>
-#include <tk.h>
-
-/*------------------------------*/
-
-#ifdef __MACOS__
-# include <tkMac.h>
-# include <Quickdraw.h>
-
-static int call_macinit = 0;
-
-static void
-_macinit()
-{
- if (!call_macinit) {
- tcl_macQdPtr = &qd; /* setup QuickDraw globals */
- Tcl_MacSetEventProc(TkMacConvertEvent); /* setup event handler */
- call_macinit = 1;
- }
-}
-#endif
-
-/*------------------------------*/
-
-static int nativethread_checked = 0;
-
-static void
-_nativethread_consistency_check(ip)
- Tcl_Interp *ip;
-{
- if (nativethread_checked || ip == (Tcl_Interp *)NULL) {
- return;
- }
-
- if (Tcl_Eval(ip, "set ::tcl_platform(threaded)") == TCL_OK) {
-#ifdef HAVE_NATIVETHREAD
- /* consistent */
-#else
- rb_warn("Inconsistency. Loaded Tcl/Tk libraries are enabled nativethread-support. But `tcltklib' is not. The inconsistency causes SEGV or other troubles frequently.");
-#endif
- } else {
-#ifdef HAVE_NATIVETHREAD
- rb_warning("Inconsistency.`tcltklib' is enabled nativethread-support. But loaded Tcl/Tk libraries are not. (Probably, the inconsistency doesn't cause any troubles.)");
-#else
- /* consistent */
-#endif
- }
-
- Tcl_ResetResult(ip);
-
- nativethread_checked = 1;
-}
-
-/*------------------------------*/
+int ruby_tcltk_stubs();
#if defined USE_TCL_STUBS && defined USE_TK_STUBS
+#include "ruby.h"
#if defined _WIN32 || defined __CYGWIN__
# include "util.h"
@@ -80,33 +26,42 @@ _nativethread_consistency_check(ip)
# define TK_NAME "libtk8.9%s"
#endif
-static DL_HANDLE tcl_dll = (DL_HANDLE)0;
-static DL_HANDLE tk_dll = (DL_HANDLE)0;
+#include <tcl.h>
+#include <tk.h>
int
-ruby_open_tcl_dll(appname)
- char *appname;
+ruby_tcltk_stubs()
{
+ DL_HANDLE tcl_dll;
+ DL_HANDLE tk_dll;
void (*p_Tcl_FindExecutable)(const char *);
+ Tcl_Interp *(*p_Tcl_CreateInterp)();
+ int (*p_Tk_Init)(Tcl_Interp *);
+ Tcl_Interp *tcl_ip;
int n;
char *ruby_tcl_dll = 0;
+ char *ruby_tk_dll = 0;
char tcl_name[20];
-
- if (tcl_dll) return TCLTK_STUBS_OK;
+ char tk_name[20];
ruby_tcl_dll = getenv("RUBY_TCL_DLL");
#if defined _WIN32
if (ruby_tcl_dll) ruby_tcl_dll = ruby_strdup(ruby_tcl_dll);
#endif
- if (ruby_tcl_dll) {
+ ruby_tk_dll = getenv("RUBY_TK_DLL");
+ if (ruby_tcl_dll && ruby_tk_dll) {
tcl_dll = (DL_HANDLE)DL_OPEN(ruby_tcl_dll);
+ tk_dll = (DL_HANDLE)DL_OPEN(ruby_tk_dll);
} else {
snprintf(tcl_name, sizeof tcl_name, TCL_NAME, DLEXT);
+ snprintf(tk_name, sizeof tk_name, TK_NAME, DLEXT);
/* examine from 8.9 to 8.1 */
for (n = '9'; n > '0'; n--) {
tcl_name[TCL_INDEX] = n;
+ tk_name[TK_INDEX] = n;
tcl_dll = (DL_HANDLE)DL_OPEN(tcl_name);
- if (tcl_dll)
+ tk_dll = (DL_HANDLE)DL_OPEN(tk_name);
+ if (tcl_dll && tk_dll)
break;
}
}
@@ -115,393 +70,35 @@ ruby_open_tcl_dll(appname)
if (ruby_tcl_dll) ruby_xfree(ruby_tcl_dll);
#endif
- if (!tcl_dll)
- return NO_TCL_DLL;
+ if (!tcl_dll || !tk_dll)
+ return -1;
p_Tcl_FindExecutable = (void (*)(const char *))DL_SYM(tcl_dll, "Tcl_FindExecutable");
if (!p_Tcl_FindExecutable)
- return NO_FindExecutable;
-
- if (appname) {
- p_Tcl_FindExecutable(appname);
- } else {
- p_Tcl_FindExecutable("ruby");
- }
-
- return TCLTK_STUBS_OK;
-}
-
-int
-ruby_open_tk_dll()
-{
- int n;
- char *ruby_tk_dll = 0;
- char tk_name[20];
-
- if (!tcl_dll) {
- int ret = ruby_open_tcl_dll(RSTRING(rb_argv0)->ptr);
- if (ret != TCLTK_STUBS_OK) return ret;
- }
-
- if (tk_dll) return TCLTK_STUBS_OK;
-
- ruby_tk_dll = getenv("RUBY_TK_DLL");
- if (ruby_tk_dll) {
- tk_dll = (DL_HANDLE)DL_OPEN(ruby_tk_dll);
- } else {
- snprintf(tk_name, sizeof tk_name, TK_NAME, DLEXT);
- /* examine from 8.9 to 8.1 */
- for (n = '9'; n > '0'; n--) {
- tk_name[TK_INDEX] = n;
- tk_dll = (DL_HANDLE)DL_OPEN(tk_name);
- if (tk_dll)
- break;
- }
- }
-
- if (!tk_dll)
- return NO_TK_DLL;
-
- return TCLTK_STUBS_OK;
-}
-
-int
-ruby_open_tcltk_dll(appname)
- char *appname;
-{
- return( ruby_open_tcl_dll(appname) || ruby_open_tk_dll() );
-}
-
-int
-tcl_stubs_init_p()
-{
- return(tclStubsPtr != (TclStubs*)NULL);
-}
-
-int
-tk_stubs_init_p()
-{
- return(tkStubsPtr != (TkStubs*)NULL);
-}
-
-
-Tcl_Interp *
-ruby_tcl_create_ip_and_stubs_init(st)
- int *st;
-{
- Tcl_Interp *tcl_ip;
-
- if (st) *st = 0;
-
- if (tcl_stubs_init_p()) {
- tcl_ip = Tcl_CreateInterp();
-
- if (!tcl_ip) {
- if (st) *st = FAIL_CreateInterp;
- return (Tcl_Interp*)NULL;
- }
-
- _nativethread_consistency_check(tcl_ip);
-
- return tcl_ip;
-
- } else {
- Tcl_Interp *(*p_Tcl_CreateInterp)();
- Tcl_Interp *(*p_Tcl_DeleteInterp)();
-
- if (!tcl_dll) {
- int ret = ruby_open_tcl_dll(RSTRING(rb_argv0)->ptr);
- if (ret != TCLTK_STUBS_OK) {
- if (st) *st = ret;
- return (Tcl_Interp*)NULL;
- }
- }
-
- p_Tcl_CreateInterp
- = (Tcl_Interp *(*)())DL_SYM(tcl_dll, "Tcl_CreateInterp");
- if (!p_Tcl_CreateInterp) {
- if (st) *st = NO_CreateInterp;
- return (Tcl_Interp*)NULL;
- }
-
- p_Tcl_DeleteInterp
- = (Tcl_Interp *(*)())DL_SYM(tcl_dll, "Tcl_DeleteInterp");
- if (!p_Tcl_DeleteInterp) {
- if (st) *st = NO_DeleteInterp;
- return (Tcl_Interp*)NULL;
- }
-
- tcl_ip = (*p_Tcl_CreateInterp)();
- if (!tcl_ip) {
- if (st) *st = FAIL_CreateInterp;
- return (Tcl_Interp*)NULL;
- }
-
- _nativethread_consistency_check(tcl_ip);
-
- if (!Tcl_InitStubs(tcl_ip, "8.1", 0)) {
- if (st) *st = FAIL_Tcl_InitStubs;
- (*p_Tcl_DeleteInterp)(tcl_ip);
- return (Tcl_Interp*)NULL;
- }
-
- return tcl_ip;
- }
-}
-
-int
-ruby_tcl_stubs_init()
-{
- int st;
- Tcl_Interp *tcl_ip;
-
- if (!tcl_stubs_init_p()) {
- tcl_ip = ruby_tcl_create_ip_and_stubs_init(&st);
-
- if (!tcl_ip) return st;
-
- Tcl_DeleteInterp(tcl_ip);
- }
-
- return TCLTK_STUBS_OK;
-}
-
-int
-ruby_tk_stubs_init(tcl_ip)
- Tcl_Interp *tcl_ip;
-{
- Tcl_ResetResult(tcl_ip);
-
- if (tk_stubs_init_p()) {
- if (Tk_Init(tcl_ip) == TCL_ERROR) {
- return FAIL_Tk_Init;
- }
- } else {
- int (*p_Tk_Init)(Tcl_Interp *);
-
- if (!tk_dll) {
- int ret = ruby_open_tk_dll();
- if (ret != TCLTK_STUBS_OK) return ret;
- }
-
- p_Tk_Init = (int (*)(Tcl_Interp *))DL_SYM(tk_dll, "Tk_Init");
- if (!p_Tk_Init)
- return NO_Tk_Init;
-
- if ((*p_Tk_Init)(tcl_ip) == TCL_ERROR)
- return FAIL_Tk_Init;
-
- if (!Tk_InitStubs(tcl_ip, "8.1", 0))
- return FAIL_Tk_InitStubs;
-
-#ifdef __MACOS__
- _macinit();
-#endif
- }
-
- return TCLTK_STUBS_OK;
-}
-
-int
-ruby_tk_stubs_safeinit(tcl_ip)
- Tcl_Interp *tcl_ip;
-{
- Tcl_ResetResult(tcl_ip);
-
- if (tk_stubs_init_p()) {
- if (Tk_SafeInit(tcl_ip) == TCL_ERROR)
- return FAIL_Tk_Init;
- } else {
- int (*p_Tk_SafeInit)(Tcl_Interp *);
-
- if (!tk_dll) {
- int ret = ruby_open_tk_dll();
- if (ret != TCLTK_STUBS_OK) return ret;
- }
-
- p_Tk_SafeInit = (int (*)(Tcl_Interp *))DL_SYM(tk_dll, "Tk_SafeInit");
- if (!p_Tk_SafeInit)
- return NO_Tk_Init;
-
- if ((*p_Tk_SafeInit)(tcl_ip) == TCL_ERROR)
- return FAIL_Tk_Init;
+ return -7;
- if (!Tk_InitStubs(tcl_ip, "8.1", 0))
- return FAIL_Tk_InitStubs;
+ p_Tcl_FindExecutable("ruby");
-#ifdef __MACOS__
- _macinit();
-#endif
- }
-
- return TCLTK_STUBS_OK;
-}
+ p_Tcl_CreateInterp = (Tcl_Interp *(*)())DL_SYM(tcl_dll, "Tcl_CreateInterp");
+ if (!p_Tcl_CreateInterp)
+ return -2;
-int
-ruby_tcltk_stubs()
-{
- int st;
- Tcl_Interp *tcl_ip;
+ tcl_ip = (*p_Tcl_CreateInterp)();
+ if (!tcl_ip)
+ return -3;
- st = ruby_open_tcltk_dll(RSTRING(rb_argv0)->ptr);
- switch(st) {
- case NO_FindExecutable:
- return -7;
- case NO_TCL_DLL:
- case NO_TK_DLL:
- return -1;
- }
-
- tcl_ip = ruby_tcl_create_ip_and_stubs_init(&st);
- if (!tcl_ip) {
- switch(st) {
- case NO_CreateInterp:
- case NO_DeleteInterp:
- return -2;
- case FAIL_CreateInterp:
- return -3;
- case FAIL_Tcl_InitStubs:
- return -5;
- }
- }
-
- st = ruby_tk_stubs_init(tcl_ip);
- switch(st) {
- case NO_Tk_Init:
- Tcl_DeleteInterp(tcl_ip);
+ p_Tk_Init = (int (*)(Tcl_Interp *))DL_SYM(tk_dll, "Tk_Init");
+ if (!p_Tk_Init)
return -4;
- case FAIL_Tk_Init:
- case FAIL_Tk_InitStubs:
- Tcl_DeleteInterp(tcl_ip);
+ (*p_Tk_Init)(tcl_ip);
+
+ if (!Tcl_InitStubs(tcl_ip, "8.1", 0))
+ return -5;
+ if (!Tk_InitStubs(tcl_ip, "8.1", 0))
return -6;
- }
Tcl_DeleteInterp(tcl_ip);
return 0;
}
-
-/*###################################################*/
-#else /* ! USE_TCL_STUBS || ! USE_TK_STUBS) */
-/*###################################################*/
-
-static int open_tcl_dll = 0;
-static int call_tk_stubs_init = 0;
-
-int
-ruby_open_tcl_dll(appname)
- char *appname;
-{
- if (appname) {
- Tcl_FindExecutable(appname);
- } else {
- Tcl_FindExecutable("ruby");
- }
- open_tcl_dll = 1;
-
- return TCLTK_STUBS_OK;
-}
-
-int ruby_open_tk_dll()
-{
- if (!open_tcl_dll) {
- ruby_open_tcl_dll(RSTRING(rb_argv0)->ptr);
- }
-
- return TCLTK_STUBS_OK;
-}
-
-int ruby_open_tcltk_dll(appname)
- char *appname;
-{
- return( ruby_open_tcl_dll(appname) || ruby_open_tk_dll() );
-}
-
-int
-tcl_stubs_init_p()
-{
- return 1;
-}
-
-int
-tk_stubs_init_p()
-{
- return call_tk_stubs_init;
-}
-
-Tcl_Interp *
-ruby_tcl_create_ip_and_stubs_init(st)
- int *st;
-{
- Tcl_Interp *tcl_ip;
-
- if (!open_tcl_dll) {
- ruby_open_tcl_dll(RSTRING(rb_argv0)->ptr);
- }
-
- if (st) *st = 0;
- tcl_ip = Tcl_CreateInterp();
- if (!tcl_ip) {
- if (st) *st = FAIL_CreateInterp;
- return (Tcl_Interp*)NULL;
- }
-
- _nativethread_consistency_check(tcl_ip);
-
- return tcl_ip;
-}
-
-int
-ruby_tcl_stubs_init()
-{
- return TCLTK_STUBS_OK;
-}
-
-int
-ruby_tk_stubs_init(tcl_ip)
- Tcl_Interp *tcl_ip;
-{
- if (Tk_Init(tcl_ip) == TCL_ERROR)
- return FAIL_Tk_Init;
-
- if (!call_tk_stubs_init) {
-#ifdef __MACOS__
- _macinit();
-#endif
- call_tk_stubs_init = 1;
- }
-
- return TCLTK_STUBS_OK;
-}
-
-int
-ruby_tk_stubs_safeinit(tcl_ip)
- Tcl_Interp *tcl_ip;
-{
-#if TCL_MAJOR_VERSION >= 8
- if (Tk_SafeInit(tcl_ip) == TCL_ERROR)
- return FAIL_Tk_Init;
-
- if (!call_tk_stubs_init) {
-#ifdef __MACOS__
- _macinit();
-#endif
- call_tk_stubs_init = 1;
- }
-
- return TCLTK_STUBS_OK;
-
-#else /* TCL_MAJOR_VERSION < 8 */
-
- return FAIL_Tk_Init;
-#endif
-}
-
-int
-ruby_tcltk_stubs()
-{
- Tcl_FindExecutable(RSTRING(rb_argv0)->ptr);
- return 0;
-}
-
#endif
diff --git a/ext/tcltklib/stubs.h b/ext/tcltklib/stubs.h
deleted file mode 100644
index 7c913fb393..0000000000
--- a/ext/tcltklib/stubs.h
+++ /dev/null
@@ -1,33 +0,0 @@
-#include <tcl.h>
-
-extern int ruby_open_tcl_dll(char *);
-extern int ruby_open_tk_dll();
-extern int ruby_open_tcltk_dll(char *);
-extern int tcl_stubs_init_p();
-extern int tk_stubs_init_p();
-extern Tcl_Interp *ruby_tcl_create_ip_and_stubs_init(int*);
-extern int ruby_tcl_stubs_init();
-extern int ruby_tk_stubs_init(Tcl_Interp*);
-extern int ruby_tk_stubs_safeinit(Tcl_Interp*);
-extern int ruby_tcltk_stubs();
-
-/* no error */
-#define TCLTK_STUBS_OK (0)
-
-/* return value of ruby_open_tcl_dll() */
-#define NO_TCL_DLL (1)
-#define NO_FindExecutable (2)
-
-/* return value of ruby_open_tk_dll() */
-#define NO_TK_DLL (-1)
-
-/* status value of ruby_tcl_create_ip_and_stubs_init(st) */
-#define NO_CreateInterp (3)
-#define NO_DeleteInterp (4)
-#define FAIL_CreateInterp (5)
-#define FAIL_Tcl_InitStubs (6)
-
-/* return value of ruby_tk_stubs_init() */
-#define NO_Tk_Init (7)
-#define FAIL_Tk_Init (8)
-#define FAIL_Tk_InitStubs (9)
diff --git a/ext/tcltklib/tcltklib.c b/ext/tcltklib/tcltklib.c
index a6374cb0dc..765417d925 100644
--- a/ext/tcltklib/tcltklib.c
+++ b/ext/tcltklib/tcltklib.c
@@ -4,11 +4,8 @@
* Oct. 24, 1997 Y. Matsumoto
*/
-#define TCLTKLIB_RELEASE_DATE "2005-09-28"
-
#include "ruby.h"
#include "rubysig.h"
-#include "version.h"
#undef EXTERN /* avoid conflict with tcl.h of tcl8.2 or before */
#include <stdio.h>
#ifdef HAVE_STDARG_PROTOTYPES
@@ -22,12 +19,9 @@
#include <tcl.h>
#include <tk.h>
-#include "stubs.h"
-
-#ifndef TCL_ALPHA_RELEASE
-#define TCL_ALPHA_RELEASE 0
-#define TCL_BETA_RELEASE 1
-#define TCL_FINAL_RELEASE 2
+#ifdef __MACOS__
+# include <tkMac.h>
+# include <Quickdraw.h>
#endif
#if TCL_MAJOR_VERSION >= 8
@@ -65,23 +59,14 @@
#define DUMP1(ARG1) if (ruby_debug) { fprintf(stderr, "tcltklib: %s\n", ARG1); fflush(stderr); }
#define DUMP2(ARG1, ARG2) if (ruby_debug) { fprintf(stderr, "tcltklib: ");\
fprintf(stderr, ARG1, ARG2); fprintf(stderr, "\n"); fflush(stderr); }
-#define DUMP3(ARG1, ARG2, ARG3) if (ruby_debug) { fprintf(stderr, "tcltklib: ");\
-fprintf(stderr, ARG1, ARG2, ARG3); fprintf(stderr, "\n"); fflush(stderr); }
/*
#define DUMP1(ARG1)
#define DUMP2(ARG1, ARG2)
-#define DUMP3(ARG1, ARG2, ARG3)
*/
-/* release date */
-const char tcltklib_release_date[] = TCLTKLIB_RELEASE_DATE;
-
-/* finalize_proc_name */
+/*finalize_proc_name */
static char *finalize_hook_name = "INTERP_FINALIZE_HOOK";
-static void ip_finalize _((Tcl_Interp*));
-
-
/* for callback break & continue */
static VALUE eTkCallbackReturn;
static VALUE eTkCallbackBreak;
@@ -89,19 +74,12 @@ static VALUE eTkCallbackContinue;
static VALUE eLocalJumpError;
-static VALUE eTkLocalJumpError;
-static VALUE eTkCallbackRetry;
-static VALUE eTkCallbackRedo;
-static VALUE eTkCallbackThrow;
-
static ID ID_at_enc;
static ID ID_at_interp;
static ID ID_stop_p;
-static ID ID_alive_p;
static ID ID_kill;
static ID ID_join;
-static ID ID_value;
static ID ID_call;
static ID ID_backtrace;
@@ -118,108 +96,6 @@ static ID ID_inspect;
static VALUE ip_invoke_real _((int, VALUE*, VALUE));
static VALUE ip_invoke _((int, VALUE*, VALUE));
-static VALUE tk_funcall _((VALUE(), int, VALUE*, VALUE));
-
-/* safe Tcl_Eval and Tcl_GlobalEval */
-static int
-tcl_eval(interp, cmd)
- Tcl_Interp *interp;
- const char *cmd; /* don't have to be writable */
-{
- char *buf = strdup(cmd);
- const int ret = Tcl_Eval(interp, buf);
- free(buf);
- return ret;
-}
-
-#undef Tcl_Eval
-#define Tcl_Eval tcl_eval
-
-static int
-tcl_global_eval(interp, cmd)
- Tcl_Interp *interp;
- const char *cmd; /* don't have to be writable */
-{
- char *buf = strdup(cmd);
- const int ret = Tcl_GlobalEval(interp, buf);
- free(buf);
- return ret;
-}
-
-#undef Tcl_GlobalEval
-#define Tcl_GlobalEval tcl_global_eval
-
-/* Tcl_{Incr|Decr}RefCount for tcl7.x or earlier */
-#if TCL_MAJOR_VERSION < 8
-#define Tcl_IncrRefCount(obj) (1)
-#define Tcl_DecrRefCount(obj) (1)
-#endif
-
-/* Tcl_GetStringResult for tcl7.x or earlier */
-#if TCL_MAJOR_VERSION < 8
-#define Tcl_GetStringResult(interp) ((interp)->result)
-#endif
-
-/* Tcl_[GS]etVar2Ex for tcl8.0 */
-#if TCL_MAJOR_VERSION == 8 && TCL_MINOR_VERSION == 0
-static Tcl_Obj *
-Tcl_GetVar2Ex(interp, name1, name2, flags)
- Tcl_Interp *interp;
- CONST char *name1;
- CONST char *name2;
- int flags;
-{
- Tcl_Obj *nameObj1, *nameObj2 = NULL, *retObj;
-
- nameObj1 = Tcl_NewStringObj((char*)name1, -1);
- Tcl_IncrRefCount(nameObj1);
-
- if (name2) {
- nameObj2 = Tcl_NewStringObj((char*)name2, -1);
- Tcl_IncrRefCount(nameObj2);
- }
-
- retObj = Tcl_ObjGetVar2(interp, nameObj1, nameObj2, flags);
-
- if (name2) {
- Tcl_DecrRefCount(nameObj2);
- }
-
- Tcl_DecrRefCount(nameObj1);
-
- return retObj;
-}
-
-static Tcl_Obj *
-Tcl_SetVar2Ex(interp, name1, name2, newValObj, flags)
- Tcl_Interp *interp;
- CONST char *name1;
- CONST char *name2;
- Tcl_Obj *newValObj;
- int flags;
-{
- Tcl_Obj *nameObj1, *nameObj2 = NULL, *retObj;
-
- nameObj1 = Tcl_NewStringObj((char*)name1, -1);
- Tcl_IncrRefCount(nameObj1);
-
- if (name2) {
- nameObj2 = Tcl_NewStringObj((char*)name2, -1);
- Tcl_IncrRefCount(nameObj2);
- }
-
- retObj = Tcl_ObjSetVar2(interp, nameObj1, nameObj2, newValObj, flags);
-
- if (name2) {
- Tcl_DecrRefCount(nameObj2);
- }
-
- Tcl_DecrRefCount(nameObj1);
-
- return retObj;
-}
-#endif
-
/* from tkAppInit.c */
#if TCL_MAJOR_VERSION < 8 || (TCL_MAJOR_VERSION == 8 && TCL_MINOR_VERSION < 4)
@@ -262,18 +138,6 @@ struct eval_queue {
VALUE thread;
};
-struct call_queue {
- Tcl_Event ev;
- VALUE (*func)();
- int argc;
- VALUE *argv;
- VALUE interp;
- int *done;
- int safe_level;
- VALUE result;
- VALUE thread;
-};
-
void
invoke_queue_mark(struct invoke_queue *q)
{
@@ -290,28 +154,10 @@ eval_queue_mark(struct eval_queue *q)
rb_gc_mark(q->thread);
}
-void
-call_queue_mark(struct call_queue *q)
-{
- int i;
-
- for(i = 0; i < q->argc; i++) {
- rb_gc_mark(q->argv[i]);
- }
-
- rb_gc_mark(q->interp);
- rb_gc_mark(q->result);
- rb_gc_mark(q->thread);
-}
-
-
+
static VALUE eventloop_thread;
-static VALUE eventloop_stack;
-
static VALUE watchdog_thread;
-
Tcl_Interp *current_interp;
-
/*
* 'event_loop_max' is a maximum events which the eventloop processes in one
@@ -340,8 +186,6 @@ static int loop_counter = 0;
static int check_rootwidget_flag = 0;
-
-/* call ruby interpreter */
#if TCL_MAJOR_VERSION >= 8
static int ip_ruby_eval _((ClientData, Tcl_Interp *, int, Tcl_Obj *CONST*));
static int ip_ruby_cmd _((ClientData, Tcl_Interp *, int, Tcl_Obj *CONST*));
@@ -350,221 +194,14 @@ static int ip_ruby_eval _((ClientData, Tcl_Interp *, int, char **));
static int ip_ruby_cmd _((ClientData, Tcl_Interp *, int, char **));
#endif
-struct cmd_body_arg {
- VALUE receiver;
- ID method;
- VALUE args;
-};
-
-
-/*----------------------------*/
-/* use Tcl internal functions */
-/*----------------------------*/
-#ifndef TCL_NAMESPACE_DEBUG
-#define TCL_NAMESPACE_DEBUG 0
-#endif
-
-#if TCL_NAMESPACE_DEBUG
-
-#if TCL_MAJOR_VERSION >= 8
-EXTERN struct TclIntStubs *tclIntStubsPtr;
-#endif
-
-/*-- Tcl_GetCurrentNamespace --*/
-#if TCL_MAJOR_VERSION == 8 && TCL_MINOR_VERSION < 5
-/* Tcl7.x doesn't have namespace support. */
-/* Tcl8.5+ has definition of Tcl_GetCurrentNamespace() in tclDecls.h */
-# ifndef Tcl_GetCurrentNamespace
-EXTERN Tcl_Namespace * Tcl_GetCurrentNamespace _((Tcl_Interp *));
-# endif
-# if defined(USE_TCL_STUBS) && !defined(USE_TCL_STUB_PROCS)
-# ifndef Tcl_GetCurrentNamespace
-# ifndef FunctionNum_of_GetCurrentNamespace
-#define FunctionNum_of_GetCurrentNamespace 124
-# endif
-struct DummyTclIntStubs_for_GetCurrentNamespace {
- int magic;
- struct TclIntStubHooks *hooks;
- void (*func[FunctionNum_of_GetCurrentNamespace])();
- Tcl_Namespace * (*tcl_GetCurrentNamespace) _((Tcl_Interp *));
-};
-
-#define Tcl_GetCurrentNamespace \
- (((struct DummyTclIntStubs_for_GetCurrentNamespace *)tclIntStubsPtr)->tcl_GetCurrentNamespace)
-# endif
-# endif
-#endif
-
-/* namespace check */
-/* ip_null_namespace(Tcl_Interp *interp) */
-#if TCL_MAJOR_VERSION < 8
-#define ip_null_namespace(interp) (0)
-#else /* support namespace */
-#define ip_null_namespace(interp) \
- (Tcl_GetCurrentNamespace(interp) == (Tcl_Namespace *)NULL)
-#endif
-
-/* rbtk_invalid_namespace(tcltkip *ptr) */
-#if TCL_MAJOR_VERSION < 8
-#define rbtk_invalid_namespace(ptr) (0)
-#else /* support namespace */
-#define rbtk_invalid_namespace(ptr) \
- ((ptr)->default_ns == (Tcl_Namespace*)NULL || Tcl_GetCurrentNamespace((ptr)->ip) != (ptr)->default_ns)
-#endif
-
-/*-- Tcl_PopCallFrame & Tcl_PushCallFrame --*/
-#if TCL_MAJOR_VERSION >= 8
-# ifndef CallFrame
-typedef struct CallFrame {
- Tcl_Namespace *nsPtr;
- int dummy1;
- int dummy2;
- char *dummy3;
- struct CallFrame *callerPtr;
- struct CallFrame *callerVarPtr;
- int level;
- char *dummy7;
- char *dummy8;
- int dummy9;
- char* dummy10;
-} CallFrame;
-# endif
-
-# if !defined(TclGetFrame) && !defined(TclGetFrame_TCL_DECLARED)
-EXTERN int TclGetFrame _((Tcl_Interp *, CONST char *, CallFrame **));
-# endif
-# if defined(USE_TCL_STUBS) && !defined(USE_TCL_STUB_PROCS)
-# ifndef TclGetFrame
-# ifndef FunctionNum_of_GetFrame
-#define FunctionNum_of_GetFrame 32
-# endif
-struct DummyTclIntStubs_for_GetFrame {
- int magic;
- struct TclIntStubHooks *hooks;
- void (*func[FunctionNum_of_GetFrame])();
- int (*tclGetFrame) _((Tcl_Interp *, CONST char *, CallFrame **));
-};
-#define TclGetFrame \
- (((struct DummyTclIntStubs_for_GetFrame *)tclIntStubsPtr)->tclGetFrame)
-# endif
-# endif
-
-# if !defined(Tcl_PopCallFrame) && !defined(Tcl_PopCallFrame_TCL_DECLARED)
-EXTERN void Tcl_PopCallFrame _((Tcl_Interp *));
-EXTERN int Tcl_PushCallFrame _((Tcl_Interp *, Tcl_CallFrame *, Tcl_Namespace *, int));
-# endif
-# if defined(USE_TCL_STUBS) && !defined(USE_TCL_STUB_PROCS)
-# ifndef Tcl_PopCallFrame
-# ifndef FunctionNum_of_PopCallFrame
-#define FunctionNum_of_PopCallFrame 128
-# endif
-struct DummyTclIntStubs_for_PopCallFrame {
- int magic;
- struct TclIntStubHooks *hooks;
- void (*func[FunctionNum_of_PopCallFrame])();
- void (*tcl_PopCallFrame) _((Tcl_Interp *));
- int (*tcl_PushCallFrame) _((Tcl_Interp *, Tcl_CallFrame *, Tcl_Namespace *, int));
-};
-
-#define Tcl_PopCallFrame \
- (((struct DummyTclIntStubs_for_PopCallFrame *)tclIntStubsPtr)->tcl_PopCallFrame)
-#define Tcl_PushCallFrame \
- (((struct DummyTclIntStubs_for_PopCallFrame *)tclIntStubsPtr)->tcl_PushCallFrame)
-# endif
-# endif
-
-#else /* Tcl7.x */
-# ifndef CallFrame
-typedef struct CallFrame {
- Tcl_HashTable varTable;
- int level;
- int argc;
- char **argv;
- struct CallFrame *callerPtr;
- struct CallFrame *callerVarPtr;
-} CallFrame;
-# endif
-# ifndef Tcl_CallFrame
-#define Tcl_CallFrame CallFrame
-# endif
-
-# if !defined(TclGetFrame) && !defined(TclGetFrame_TCL_DECLARED)
-EXTERN int TclGetFrame _((Tcl_Interp *, CONST char *, CallFrame **));
-# endif
-
-# if !defined(Tcl_PopCallFrame) && !defined(Tcl_PopCallFrame_TCL_DECLARED)
-typedef struct DummyInterp {
- char *dummy1;
- char *dummy2;
- int dummy3;
- Tcl_HashTable dummy4;
- Tcl_HashTable dummy5;
- Tcl_HashTable dummy6;
- int numLevels;
- int maxNestingDepth;
- CallFrame *framePtr;
- CallFrame *varFramePtr;
-} DummyInterp;
-
-static void
-Tcl_PopCallFrame(interp)
- Tcl_Interp *interp;
-{
- DummyInterp *iPtr = (DummyInterp*)interp;
- CallFrame *frame = iPtr->varFramePtr;
-
- /* **** DUMMY **** */
- iPtr->framePtr = frame.callerPtr;
- iPtr->varFramePtr = frame.callerVarPtr;
-
- return TCL_OK;
-}
-
-/* dummy */
-#define Tcl_Namespace char
-
-static int
-Tcl_PushCallFrame(interp, framePtr, nsPtr, isProcCallFrame)
- Tcl_Interp *interp;
- Tcl_CallFrame *framePtr;
- Tcl_Namespace *nsPtr;
- int isProcCallFrame;
-{
- DummyInterp *iPtr = (DummyInterp*)interp;
- CallFrame *frame = (CallFrame *)framePtr;
-
- /* **** DUMMY **** */
- Tcl_InitHashTable(&frame.varTable, TCL_STRING_KEYS);
- if (iPtr->varFramePtr != NULL) {
- frame.level = iPtr->varFramePtr->level + 1;
- } else {
- frame.level = 1;
- }
- frame.callerPtr = iPtr->framePtr;
- frame.callerVarPtr = iPtr->varFramePtr;
- iPtr->framePtr = &frame;
- iPtr->varFramePtr = &frame;
-
- return TCL_OK;
-}
-# endif
-
-#endif
-
-#endif /* TCL_NAMESPACE_DEBUG */
-
-
/*---- class TclTkIp ----*/
struct tcltkip {
- Tcl_Interp *ip; /* the interpreter */
-#if TCL_NAMESPACE_DEBUG
- Tcl_Namespace *default_ns; /* default namespace */
-#endif
- int has_orig_exit; /* has original 'exit' command ? */
- Tcl_CmdInfo orig_exit_info; /* command info of original 'exit' command */
- int ref_count; /* reference count of rbtk_preserve_ip call */
- int allow_ruby_exit; /* allow exiting ruby by 'exit' function */
- int return_value; /* return value */
+ Tcl_Interp *ip; /* the interpreter */
+ int has_orig_exit; /* has original 'exit' command ? */
+ Tcl_CmdInfo orig_exit_info; /* command info of original 'exit' command */
+ int ref_count; /* reference count of rbtk_preserve_ip call */
+ int allow_ruby_exit; /* allow exiting ruby by 'exit' function */
+ int return_value; /* return value */
};
static struct tcltkip *
@@ -575,43 +212,18 @@ get_ip(self)
Data_Get_Struct(self, struct tcltkip, ptr);
if (ptr == 0) {
- /* rb_raise(rb_eTypeError, "uninitialized TclTkIp"); */
- return((struct tcltkip *)NULL);
- }
- if (ptr->ip == (Tcl_Interp*)NULL) {
- /* rb_raise(rb_eRuntimeError, "deleted IP"); */
- return((struct tcltkip *)NULL);
+ rb_raise(rb_eTypeError, "uninitialized TclTkIp");
}
return ptr;
}
-static int
-deleted_ip(ptr)
- struct tcltkip *ptr;
-{
- if (!ptr || !ptr->ip || Tcl_InterpDeleted(ptr->ip)
-#if TCL_NAMESPACE_DEBUG
- || rbtk_invalid_namespace(ptr)
-#endif
- ) {
- DUMP1("ip is deleted");
- return Qtrue;
- }
- return Qfalse;
-}
-
/* increment/decrement reference count of tcltkip */
static int
rbtk_preserve_ip(ptr)
struct tcltkip *ptr;
{
ptr->ref_count++;
- if (ptr->ip == (Tcl_Interp*)NULL) {
- /* deleted IP */
- ptr->ref_count = 0;
- } else {
- Tcl_Preserve((ClientData)ptr->ip);
- }
+ Tcl_Preserve((ClientData)ptr->ip);
return(ptr->ref_count);
}
@@ -622,213 +234,12 @@ rbtk_release_ip(ptr)
ptr->ref_count--;
if (ptr->ref_count < 0) {
ptr->ref_count = 0;
- } else if (ptr->ip == (Tcl_Interp*)NULL) {
- /* deleted IP */
- ptr->ref_count = 0;
} else {
Tcl_Release((ClientData)ptr->ip);
}
return(ptr->ref_count);
}
-
-static VALUE
-#ifdef HAVE_STDARG_PROTOTYPES
-create_ip_exc(VALUE interp, VALUE exc, const char *fmt, ...)
-#else
-create_ip_exc(interp, exc, fmt, va_alist)
- VALUE interp:
- VALUE exc;
- const char *fmt;
- va_dcl
-#endif
-{
- va_list args;
- char buf[BUFSIZ];
- VALUE einfo;
- struct tcltkip *ptr = get_ip(interp);
-
- va_init_list(args,fmt);
- vsnprintf(buf, BUFSIZ, fmt, args);
- buf[BUFSIZ - 1] = '\0';
- va_end(args);
- einfo = rb_exc_new2(exc, buf);
- rb_ivar_set(einfo, ID_at_interp, interp);
- if (ptr) {
- Tcl_ResetResult(ptr->ip);
- }
-
- return einfo;
-}
-
-
-/* stub status */
-static void
-tcl_stubs_check()
-{
- if (!tcl_stubs_init_p()) {
- int st = ruby_tcl_stubs_init();
- switch(st) {
- case TCLTK_STUBS_OK:
- break;
- case NO_TCL_DLL:
- rb_raise(rb_eLoadError, "tcltklib: fail to open tcl_dll");
- case NO_FindExecutable:
- rb_raise(rb_eLoadError, "tcltklib: can't find Tcl_FindExecutable");
- case NO_CreateInterp:
- rb_raise(rb_eLoadError, "tcltklib: can't find Tcl_CreateInterp()");
- case NO_DeleteInterp:
- rb_raise(rb_eLoadError, "tcltklib: can't find Tcl_DeleteInterp()");
- case FAIL_CreateInterp:
- rb_raise(rb_eRuntimeError, "tcltklib: fail to create a new IP to call Tcl_InitStubs()");
- case FAIL_Tcl_InitStubs:
- rb_raise(rb_eRuntimeError, "tcltklib: fail to Tcl_InitStubs()");
- default:
- rb_raise(rb_eRuntimeError, "tcltklib: unknown error(%d) on ruby_tcl_stubs_init()", st);
- }
- }
-}
-
-
-static VALUE
-tcltkip_init_tk(interp)
- VALUE interp;
-{
- struct tcltkip *ptr = get_ip(interp);
-
-#if TCL_MAJOR_VERSION >= 8
- int st;
-
- if (Tcl_IsSafe(ptr->ip)) {
- DUMP1("Tk_SafeInit");
- st = ruby_tk_stubs_safeinit(ptr->ip);
- switch(st) {
- case TCLTK_STUBS_OK:
- break;
- case NO_Tk_Init:
- return rb_exc_new2(rb_eLoadError,
- "tcltklib: can't find Tk_SafeInit()");
- case FAIL_Tk_Init:
- return create_ip_exc(interp, rb_eRuntimeError,
- "tcltklib: fail to Tk_SafeInit(). %s",
- Tcl_GetStringResult(ptr->ip));
- case FAIL_Tk_InitStubs:
- return create_ip_exc(interp, rb_eRuntimeError,
- "tcltklib: fail to Tk_InitStubs(). %s",
- Tcl_GetStringResult(ptr->ip));
- default:
- return create_ip_exc(interp, rb_eRuntimeError,
- "tcltklib: unknown error(%d) on ruby_tk_stubs_safeinit", st);
- }
- } else {
- DUMP1("Tk_Init");
- st = ruby_tk_stubs_init(ptr->ip);
- switch(st) {
- case TCLTK_STUBS_OK:
- break;
- case NO_Tk_Init:
- return rb_exc_new2(rb_eLoadError,
- "tcltklib: can't find Tk_Init()");
- case FAIL_Tk_Init:
- return create_ip_exc(interp, rb_eRuntimeError,
- "tcltklib: fail to Tk_Init(). %s",
- Tcl_GetStringResult(ptr->ip));
- case FAIL_Tk_InitStubs:
- return create_ip_exc(interp, rb_eRuntimeError,
- "tcltklib: fail to Tk_InitStubs(). %s",
- Tcl_GetStringResult(ptr->ip));
- default:
- return create_ip_exc(interp, rb_eRuntimeError,
- "tcltklib: unknown error(%d) on ruby_tk_stubs_init", st);
- }
- }
-
-#else /* TCL_MAJOR_VERSION < 8 */
- DUMP1("Tk_Init");
- if (ruby_tk_stubs_init(ptr->ip) != TCLTK_STUBS_OK) {
- return rb_exc_new2(rb_eRuntimeError, ptr->ip->result);
- }
-#endif
-
- return Qnil;
-}
-
-
-/* treat excetiopn on Tcl side */
-static VALUE rbtk_pending_exception;
-static int rbtk_eventloop_depth = 0;
-
-
-static int
-pending_exception_check0()
-{
- volatile VALUE exc = rbtk_pending_exception;
-
- if (!NIL_P(exc) && rb_obj_is_kind_of(exc, rb_eException)) {
- DUMP1("find a pending exception");
- if (rbtk_eventloop_depth > 0) {
- return 1; /* pending */
- } else {
- rbtk_pending_exception = Qnil;
-
- if (rb_obj_is_kind_of(exc, eTkCallbackRetry)) {
- DUMP1("pending_exception_check0: call rb_jump_tag(retry)");
- rb_jump_tag(TAG_RETRY);
- } else if (rb_obj_is_kind_of(exc, eTkCallbackRedo)) {
- DUMP1("pending_exception_check0: call rb_jump_tag(redo)");
- rb_jump_tag(TAG_REDO);
- } else if (rb_obj_is_kind_of(exc, eTkCallbackThrow)) {
- DUMP1("pending_exception_check0: call rb_jump_tag(throw)");
- rb_jump_tag(TAG_THROW);
- }
-
- rb_exc_raise(exc);
- }
- } else {
- return 0;
- }
-}
-
-static int
-pending_exception_check1(thr_crit_bup, ptr)
- int thr_crit_bup;
- struct tcltkip *ptr;
-{
- volatile VALUE exc = rbtk_pending_exception;
-
- if (!NIL_P(exc) && rb_obj_is_kind_of(exc, rb_eException)) {
- DUMP1("find a pending exception");
-
- if (rbtk_eventloop_depth > 0) {
- return 1; /* pending */
- } else {
- rbtk_pending_exception = Qnil;
-
- if (ptr != (struct tcltkip *)NULL) {
- /* Tcl_Release(ptr->ip); */
- rbtk_release_ip(ptr);
- }
-
- rb_thread_critical = thr_crit_bup;
-
- if (rb_obj_is_kind_of(exc, eTkCallbackRetry)) {
- DUMP1("pending_exception_check1: call rb_jump_tag(retry)");
- rb_jump_tag(TAG_RETRY);
- } else if (rb_obj_is_kind_of(exc, eTkCallbackRedo)) {
- DUMP1("pending_exception_check1: call rb_jump_tag(redo)");
- rb_jump_tag(TAG_REDO);
- } else if (rb_obj_is_kind_of(exc, eTkCallbackThrow)) {
- DUMP1("pending_exception_check1: call rb_jump_tag(throw)");
- rb_jump_tag(TAG_THROW);
- }
- rb_exc_raise(exc);
- }
- } else {
- return 0;
- }
-}
-
-
/* call original 'exit' command */
static void
call_original_exit(ptr, state)
@@ -872,8 +283,7 @@ call_original_exit(ptr, state)
char **argv;
argv = (char **)ALLOC_N(char *, 3);
argv[0] = "exit";
- /* argv[1] = Tcl_GetString(state_obj); */
- argv[1] = Tcl_GetStringFromObj(state_obj, (int*)NULL);
+ argv[1] = Tcl_GetString(state_obj);
argv[2] = (char *)NULL;
ptr->return_value = (*(info->proc))(info->clientData, ptr->ip,
@@ -917,18 +327,18 @@ _timer_for_tcl(clientData)
/* struct invoke_queue *q, *tmp; */
/* VALUE thread; */
- DUMP1("call _timer_for_tcl");
+ DUMP1("called timer_for_tcl");
thr_crit_bup = rb_thread_critical;
rb_thread_critical = Qtrue;
- Tcl_DeleteTimerHandler(timer_token);
+ Tk_DeleteTimerHandler(timer_token);
run_timer_flag = 1;
if (timer_tick > 0) {
- timer_token = Tcl_CreateTimerHandler(timer_tick, _timer_for_tcl,
- (ClientData)0);
+ timer_token = Tk_CreateTimerHandler(timer_tick, _timer_for_tcl,
+ (ClientData)0);
} else {
timer_token = (Tcl_TimerToken)NULL;
}
@@ -958,13 +368,13 @@ set_eventloop_tick(self, tick)
rb_thread_critical = Qtrue;
/* delete old timer callback */
- Tcl_DeleteTimerHandler(timer_token);
+ Tk_DeleteTimerHandler(timer_token);
timer_tick = req_timer_tick = ttick;
if (timer_tick > 0) {
/* start timer callback */
- timer_token = Tcl_CreateTimerHandler(timer_tick, _timer_for_tcl,
- (ClientData)0);
+ timer_token = Tk_CreateTimerHandler(timer_tick, _timer_for_tcl,
+ (ClientData)0);
} else {
timer_token = (Tcl_TimerToken)NULL;
}
@@ -989,7 +399,8 @@ ip_set_eventloop_tick(self, tick)
struct tcltkip *ptr = get_ip(self);
/* ip is deleted? */
- if (deleted_ip(ptr)) {
+ if (Tcl_InterpDeleted(ptr->ip)) {
+ DUMP1("ip is deleted");
return get_eventloop_tick(self);
}
@@ -1041,7 +452,8 @@ ip_set_no_event_wait(self, wait)
struct tcltkip *ptr = get_ip(self);
/* ip is deleted? */
- if (deleted_ip(ptr)) {
+ if (Tcl_InterpDeleted(ptr->ip)) {
+ DUMP1("ip is deleted");
return get_no_event_wait(self);
}
@@ -1096,7 +508,8 @@ ip_set_eventloop_weight(self, loop_max, no_event)
struct tcltkip *ptr = get_ip(self);
/* ip is deleted? */
- if (deleted_ip(ptr)) {
+ if (Tcl_InterpDeleted(ptr->ip)) {
+ DUMP1("ip is deleted");
return get_eventloop_weight(self);
}
@@ -1148,19 +561,6 @@ set_max_block_time(self, time)
}
static VALUE
-lib_evloop_thread_p(self)
- VALUE self;
-{
- if (NIL_P(eventloop_thread)) {
- return Qnil; /* no eventloop */
- } else if (rb_thread_current() == eventloop_thread) {
- return Qtrue; /* is eventloop */
- } else {
- return Qfalse; /* not eventloop */
- }
-}
-
-static VALUE
lib_evloop_abort_on_exc(self)
VALUE self;
{
@@ -1204,7 +604,8 @@ ip_evloop_abort_on_exc_set(self, val)
rb_secure(4);
/* ip is deleted? */
- if (deleted_ip(ptr)) {
+ if (Tcl_InterpDeleted(ptr->ip)) {
+ DUMP1("ip is deleted");
return lib_evloop_abort_on_exc(self);
}
@@ -1219,55 +620,9 @@ static VALUE
lib_num_of_mainwindows(self)
VALUE self;
{
- if (tk_stubs_init_p()) {
- return INT2FIX(Tk_GetNumMainWindows());
- } else {
- return INT2FIX(0);
- }
+ return INT2FIX(Tk_GetNumMainWindows());
}
-
-static VALUE
-call_DoOneEvent(flag_val)
- VALUE flag_val;
-{
- int flag;
-
- flag = FIX2INT(flag_val);
- if (Tcl_DoOneEvent(flag)) {
- return Qtrue;
- } else {
- return Qfalse;
- }
-}
-
-static VALUE
-eventloop_sleep(dummy)
- VALUE dummy;
-{
- struct timeval t;
-
- t.tv_sec = (time_t)0;
- t.tv_usec = (time_t)(no_event_wait*1000.0);
-
-#ifdef HAVE_NATIVETHREAD
- if (!is_ruby_native_thread()) {
- rb_bug("cross-thread violation on eventloop_sleep()");
- }
-#endif
-
- rb_thread_wait_for(t);
-
-#ifdef HAVE_NATIVETHREAD
- if (!is_ruby_native_thread()) {
- rb_bug("cross-thread violation on eventloop_sleep()");
- }
-#endif
-
- return Qnil;
-}
-
-
static int
lib_eventloop_core(check_root, update_flag, check_var)
int check_root;
@@ -1279,8 +634,6 @@ lib_eventloop_core(check_root, update_flag, check_var)
int event_flag;
struct timeval t;
int thr_crit_bup;
- int status;
- int depth = rbtk_eventloop_depth;
if (update_flag) DUMP1("update loop start!!");
@@ -1288,13 +641,13 @@ lib_eventloop_core(check_root, update_flag, check_var)
t.tv_sec = (time_t)0;
t.tv_usec = (time_t)(no_event_wait*1000.0);
- Tcl_DeleteTimerHandler(timer_token);
+ Tk_DeleteTimerHandler(timer_token);
run_timer_flag = 0;
if (timer_tick > 0) {
thr_crit_bup = rb_thread_critical;
rb_thread_critical = Qtrue;
- timer_token = Tcl_CreateTimerHandler(timer_tick, _timer_for_tcl,
- (ClientData)0);
+ timer_token = Tk_CreateTimerHandler(timer_tick, _timer_for_tcl,
+ (ClientData)0);
rb_thread_critical = thr_crit_bup;
} else {
timer_token = (Tcl_TimerToken)NULL;
@@ -1313,9 +666,9 @@ lib_eventloop_core(check_root, update_flag, check_var)
if (timer_tick == 0 && update_flag == 0) {
timer_tick = NO_THREAD_INTERRUPT_TIME;
- timer_token = Tcl_CreateTimerHandler(timer_tick,
- _timer_for_tcl,
- (ClientData)0);
+ timer_token = Tk_CreateTimerHandler(timer_tick,
+ _timer_for_tcl,
+ (ClientData)0);
}
if (check_var != (int *)NULL) {
@@ -1324,53 +677,7 @@ lib_eventloop_core(check_root, update_flag, check_var)
}
}
- /* found_event = Tcl_DoOneEvent(event_flag); */
- found_event = RTEST(rb_protect(call_DoOneEvent,
- INT2FIX(event_flag), &status));
- if (status) {
- switch (status) {
- case TAG_RAISE:
- if (NIL_P(ruby_errinfo)) {
- rbtk_pending_exception
- = rb_exc_new2(rb_eException, "unknown exception");
- } else {
- rbtk_pending_exception = ruby_errinfo;
-
- if (!NIL_P(rbtk_pending_exception)) {
- if (rbtk_eventloop_depth == 0) {
- VALUE exc = rbtk_pending_exception;
- rbtk_pending_exception = Qnil;
- rb_exc_raise(exc);
- } else {
- return 0;
- }
- }
- }
- break;
-
- case TAG_FATAL:
- if (NIL_P(ruby_errinfo)) {
- rb_exc_raise(rb_exc_new2(rb_eFatal, "FATAL"));
- } else {
- rb_exc_raise(ruby_errinfo);
- }
- }
- }
-
- if (depth != rbtk_eventloop_depth) {
- DUMP2("DoOneEvent(1) abnormal exit!! %d",
- rbtk_eventloop_depth);
- }
-
- if (check_var != (int*)NULL && !NIL_P(rbtk_pending_exception)) {
- DUMP1("exception on wait");
- return 0;
- }
-
- if (pending_exception_check0()) {
- /* pending -> upper level */
- return 0;
- }
+ found_event = Tcl_DoOneEvent(event_flag);
if (update_flag != 0) {
if (found_event) {
@@ -1382,27 +689,11 @@ lib_eventloop_core(check_root, update_flag, check_var)
}
}
- DUMP1("trap check");
- if (rb_trap_pending) {
- run_timer_flag = 0;
- if (rb_prohibit_interrupt || check_var != (int*)NULL) {
- /* pending or on wait command */
- return 0;
- } else {
- rb_trap_exec();
- }
- }
-
DUMP1("check Root Widget");
- if (check_root && tk_stubs_init_p() && Tk_GetNumMainWindows() == 0) {
+ if (check_root && Tk_GetNumMainWindows() == 0) {
run_timer_flag = 0;
- if (rb_trap_pending) {
- if (rb_prohibit_interrupt || check_var != (int*)NULL) {
- /* pending or on wait command */
- return 0;
- } else {
- rb_trap_exec();
- }
+ if (!rb_prohibit_interrupt) {
+ if (rb_trap_pending) rb_trap_exec();
}
return 1;
}
@@ -1435,153 +726,35 @@ lib_eventloop_core(check_root, update_flag, check_var)
}
}
- if (NIL_P(eventloop_thread) || current == eventloop_thread) {
- int st;
- int status;
-
- /* st = Tcl_DoOneEvent(event_flag); */
- st = RTEST(rb_protect(call_DoOneEvent,
- INT2FIX(event_flag), &status));
- if (status) {
- switch (status) {
- case TAG_RAISE:
- if (NIL_P(ruby_errinfo)) {
- rbtk_pending_exception
- = rb_exc_new2(rb_eException,
- "unknown exception");
- } else {
- rbtk_pending_exception = ruby_errinfo;
-
- if (!NIL_P(rbtk_pending_exception)) {
- if (rbtk_eventloop_depth == 0) {
- VALUE exc = rbtk_pending_exception;
- rbtk_pending_exception = Qnil;
- rb_exc_raise(exc);
- } else {
- return 0;
- }
- }
- }
- break;
-
- case TAG_FATAL:
- if (NIL_P(ruby_errinfo)) {
- rb_exc_raise(rb_exc_new2(rb_eFatal, "FATAL"));
- } else {
- rb_exc_raise(ruby_errinfo);
- }
- }
- }
-
- if (depth != rbtk_eventloop_depth) {
- DUMP2("DoOneEvent(2) abnormal exit!! %d",
- rbtk_eventloop_depth);
- return 0;
- }
-
- DUMP1("trap check");
- if (rb_trap_pending) {
- run_timer_flag = 0;
- if (rb_prohibit_interrupt || check_var != (int*)NULL) {
- /* pending or on wait command */
- return 0;
- } else {
- rb_trap_exec();
- }
- }
-
- if (check_var != (int*)NULL
- && !NIL_P(rbtk_pending_exception)) {
- DUMP1("exception on wait");
- return 0;
- }
-
- if (pending_exception_check0()) {
- /* pending -> upper level */
+ if (Tcl_DoOneEvent(event_flag)) {
+ tick_counter++;
+ } else {
+ if (update_flag != 0) {
+ DUMP1("update complete");
return 0;
}
-
- if (st) {
- tick_counter++;
- } else {
- if (update_flag != 0) {
- DUMP1("update complete");
- return 0;
- }
-
- tick_counter += no_event_tick;
-
- /* rb_thread_wait_for(t); */
- rb_protect(eventloop_sleep, Qnil, &status);
-
- if (status) {
- switch (status) {
- case TAG_RAISE:
- if (NIL_P(ruby_errinfo)) {
- rbtk_pending_exception
- = rb_exc_new2(rb_eException,
- "unknown exception");
- } else {
- rbtk_pending_exception = ruby_errinfo;
-
- if (!NIL_P(rbtk_pending_exception)) {
- if (rbtk_eventloop_depth == 0) {
- VALUE exc = rbtk_pending_exception;
- rbtk_pending_exception = Qnil;
- rb_exc_raise(exc);
- } else {
- return 0;
- }
- }
- }
- break;
-
- case TAG_FATAL:
- if (NIL_P(ruby_errinfo)) {
- rb_exc_raise(rb_exc_new2(rb_eFatal,
- "FATAL"));
- } else {
- rb_exc_raise(ruby_errinfo);
- }
- }
- }
- }
-
- } else {
- DUMP2("sleep eventloop %lx", current);
- DUMP2("eventloop thread is %lx", eventloop_thread);
- rb_thread_stop();
+ tick_counter += no_event_tick;
+ rb_thread_wait_for(t);
}
- if (!NIL_P(watchdog_thread) && eventloop_thread != current) {
+ if (watchdog_thread != 0 && eventloop_thread != current) {
return 1;
}
- DUMP1("trap check");
- if (rb_trap_pending) {
- run_timer_flag = 0;
- if (rb_prohibit_interrupt || check_var != (int*)NULL) {
- /* pending or on wait command */
- return 0;
- } else {
- rb_trap_exec();
- }
- }
-
DUMP1("check Root Widget");
- if (check_root && tk_stubs_init_p() && Tk_GetNumMainWindows() == 0) {
+ if (check_root && Tk_GetNumMainWindows() == 0) {
run_timer_flag = 0;
- if (rb_trap_pending) {
- if (rb_prohibit_interrupt || check_var != (int*)NULL) {
- /* pending or on wait command */
- return 0;
- } else {
- rb_trap_exec();
- }
+ if (!rb_prohibit_interrupt) {
+ if (rb_trap_pending) rb_trap_exec();
}
return 1;
}
+ DUMP1("trap check");
+ if (!rb_prohibit_interrupt) {
+ if (rb_trap_pending) rb_trap_exec();
+ }
+
if (loop_counter++ > 30000) {
/* fprintf(stderr, "loop_counter > 30000\n"); */
loop_counter = 0;
@@ -1604,24 +777,13 @@ lib_eventloop_core(check_root, update_flag, check_var)
return 1;
}
-
-struct evloop_params {
- int check_root;
- int update_flag;
- int *check_var;
-};
-
VALUE
-lib_eventloop_main_core(args)
- VALUE args;
+lib_eventloop_main(check_rootwidget)
+ VALUE check_rootwidget;
{
- struct evloop_params *params = (struct evloop_params *)args;
+ check_rootwidget_flag = RTEST(check_rootwidget);
- check_rootwidget_flag = params->check_root;
-
- if (lib_eventloop_core(params->check_root,
- params->update_flag,
- params->check_var)) {
+ if (lib_eventloop_core(check_rootwidget_flag, 0, (int *)NULL)) {
return Qtrue;
} else {
return Qfalse;
@@ -1629,121 +791,35 @@ lib_eventloop_main_core(args)
}
VALUE
-lib_eventloop_main(args)
- VALUE args;
-{
- volatile VALUE ret;
- int status = 0;
-
- /* ret = rb_protect(lib_eventloop_main_core, args, &status); */
- ret = lib_eventloop_main_core(args);
-
- switch (status) {
- case TAG_RAISE:
- if (NIL_P(ruby_errinfo)) {
- rbtk_pending_exception
- = rb_exc_new2(rb_eException, "unknown exception");
- } else {
- rbtk_pending_exception = ruby_errinfo;
- }
- return Qnil;
-
- case TAG_FATAL:
- if (NIL_P(ruby_errinfo)) {
- rbtk_pending_exception = rb_exc_new2(rb_eFatal, "FATAL");
- } else {
- rbtk_pending_exception = ruby_errinfo;
- }
- return Qnil;
- }
-
- return ret;
-}
-
-VALUE
-lib_eventloop_ensure(args)
- VALUE args;
+lib_eventloop_ensure(parent_evloop)
+ VALUE parent_evloop;
{
- struct evloop_params *ptr = (struct evloop_params *)args;
- volatile VALUE current_evloop = rb_thread_current();
-
- DUMP2("eventloop_ensure: current-thread : %lx", current_evloop);
- DUMP2("eventloop_ensure: eventloop-thread : %lx", eventloop_thread);
- if (eventloop_thread != current_evloop) {
- DUMP2("finish eventloop %lx (NOT current eventloop)", current_evloop);
- return Qnil;
- }
-
- while(eventloop_thread = rb_ary_pop(eventloop_stack)) {
- DUMP2("eventloop-ensure: new eventloop-thread -> %lx",
- eventloop_thread);
-
- if (eventloop_thread == current_evloop) {
- rbtk_eventloop_depth--;
- DUMP2("eventloop %lx : back from recursive call", current_evloop);
- break;
- }
-
- if (NIL_P(eventloop_thread)) {
- Tcl_DeleteTimerHandler(timer_token);
- timer_token = (Tcl_TimerToken)NULL;
-
- break;
- }
-
- if (RTEST(rb_funcall(eventloop_thread, ID_alive_p, 0, 0))) {
- DUMP2("eventloop-enshure: wake up parent %lx", eventloop_thread);
- rb_thread_wakeup(eventloop_thread);
-
- break;
- }
+ Tk_DeleteTimerHandler(timer_token);
+ timer_token = (Tcl_TimerToken)NULL;
+ DUMP2("eventloop-ensure: current-thread : %lx\n", rb_thread_current());
+ DUMP2("eventloop-ensure: eventloop-thread : %lx\n", eventloop_thread);
+ if (eventloop_thread == rb_thread_current()) {
+ DUMP2("eventloop-thread -> %lx\n", parent_evloop);
+ eventloop_thread = parent_evloop;
}
-
- free(ptr);
-
- DUMP2("finish current eventloop %lx", current_evloop);
return Qnil;
}
static VALUE
-lib_eventloop_launcher(check_root, update_flag, check_var)
- int check_root;
- int update_flag;
- int *check_var;
+lib_eventloop_launcher(check_rootwidget)
+ VALUE check_rootwidget;
{
- volatile VALUE parent_evloop = eventloop_thread;
- int depth = rbtk_eventloop_depth;
- struct evloop_params *args = ALLOC(struct evloop_params);
-
- tcl_stubs_check();
+ VALUE parent_evloop = eventloop_thread;
eventloop_thread = rb_thread_current();
- if (parent_evloop == eventloop_thread) {
- DUMP2("eventloop: recursive call on %lx", parent_evloop);
- rbtk_eventloop_depth++;
- }
-
- if (!NIL_P(parent_evloop) && parent_evloop != eventloop_thread) {
- DUMP2("wait for stop of parent_evloop %lx", parent_evloop);
- while(!RTEST(rb_funcall(parent_evloop, ID_stop_p, 0))) {
- DUMP2("parent_evloop %lx doesn't stop", parent_evloop);
- rb_thread_run(parent_evloop);
- }
- DUMP1("succeed to stop parent");
- }
-
- rb_ary_push(eventloop_stack, parent_evloop);
-
- DUMP3("tcltklib: eventloop-thread : %lx -> %lx\n",
+ if (ruby_debug) {
+ fprintf(stderr, "tcltklib: eventloop-thread : %lx -> %lx\n",
parent_evloop, eventloop_thread);
+ }
- args->check_root = check_root;
- args->update_flag = update_flag;
- args->check_var = check_var;
-
- return rb_ensure(lib_eventloop_main, (VALUE)args,
- lib_eventloop_ensure, (VALUE)args);
+ return rb_ensure(lib_eventloop_main, check_rootwidget,
+ lib_eventloop_ensure, parent_evloop);
}
/* execute Tk_MainLoop */
@@ -1763,7 +839,7 @@ lib_mainloop(argc, argv, self)
check_rootwidget = Qfalse;
}
- return lib_eventloop_launcher(RTEST(check_rootwidget), 0, (int*)NULL);
+ return lib_eventloop_launcher(check_rootwidget);
}
static VALUE
@@ -1775,7 +851,8 @@ ip_mainloop(argc, argv, self)
struct tcltkip *ptr = get_ip(self);
/* ip is deleted? */
- if (deleted_ip(ptr)) {
+ if (Tcl_InterpDeleted(ptr->ip)) {
+ DUMP1("ip is deleted");
return Qnil;
}
@@ -1786,17 +863,7 @@ ip_mainloop(argc, argv, self)
return lib_mainloop(argc, argv, self);
}
-
-static VALUE
-watchdog_evloop_launcher(check_rootwidget)
- VALUE check_rootwidget;
-{
- return lib_eventloop_launcher(RTEST(check_rootwidget), 0, (int*)NULL);
-}
-
-#define EVLOOP_WAKEUP_CHANCE 3
-
-static VALUE
+VALUE
lib_watchdog_core(check_rootwidget)
VALUE check_rootwidget;
{
@@ -1812,7 +879,7 @@ lib_watchdog_core(check_rootwidget)
t1.tv_usec = (time_t)((WATCHDOG_INTERVAL)*1000.0);
/* check other watchdog thread */
- if (!NIL_P(watchdog_thread)) {
+ if (watchdog_thread != 0) {
if (RTEST(rb_funcall(watchdog_thread, ID_stop_p, 0))) {
rb_funcall(watchdog_thread, ID_kill, 0);
} else {
@@ -1823,24 +890,23 @@ lib_watchdog_core(check_rootwidget)
/* watchdog start */
do {
- if (NIL_P(eventloop_thread)
- || (loop_counter == prev_val && chance >= EVLOOP_WAKEUP_CHANCE)) {
+ if (eventloop_thread == 0
+ || (loop_counter == prev_val
+ && RTEST(rb_funcall(eventloop_thread, ID_stop_p, 0))
+ && ++chance >= 3 )
+ ) {
/* start new eventloop thread */
DUMP2("eventloop thread %lx is sleeping or dead",
eventloop_thread);
- evloop = rb_thread_create(watchdog_evloop_launcher,
+ evloop = rb_thread_create(lib_eventloop_launcher,
(void*)&check_rootwidget);
DUMP2("create new eventloop thread %lx", evloop);
loop_counter = -1;
chance = 0;
rb_thread_run(evloop);
} else {
- prev_val = loop_counter;
- if (RTEST(rb_funcall(eventloop_thread, ID_stop_p, 0))) {
- ++chance;
- } else {
- chance = 0;
- }
+ loop_counter = prev_val;
+ chance = 0;
if (event_loop_wait_event) {
rb_thread_wait_for(t0);
} else {
@@ -1848,7 +914,7 @@ lib_watchdog_core(check_rootwidget)
}
/* rb_thread_schedule(); */
}
- } while(!check || !tk_stubs_init_p() || Tk_GetNumMainWindows() != 0);
+ } while(!check || Tk_GetNumMainWindows() != 0);
return Qnil;
}
@@ -1857,7 +923,7 @@ VALUE
lib_watchdog_ensure(arg)
VALUE arg;
{
- eventloop_thread = Qnil; /* stop eventloops */
+ eventloop_thread = 0; /* stop eventloops */
return Qnil;
}
@@ -1890,7 +956,8 @@ ip_mainloop_watchdog(argc, argv, self)
struct tcltkip *ptr = get_ip(self);
/* ip is deleted? */
- if (deleted_ip(ptr)) {
+ if (Tcl_InterpDeleted(ptr->ip)) {
+ DUMP1("ip is deleted");
return Qnil;
}
@@ -1901,108 +968,6 @@ ip_mainloop_watchdog(argc, argv, self)
return lib_mainloop_watchdog(argc, argv, self);
}
-
-/* thread-safe(?) interaction between Ruby and Tk */
-struct thread_call_proc_arg {
- VALUE proc;
- int *done;
-};
-
-void
-_thread_call_proc_arg_mark(struct thread_call_proc_arg *q)
-{
- rb_gc_mark(q->proc);
-}
-
-static VALUE
-_thread_call_proc_core(arg)
- VALUE arg;
-{
- struct thread_call_proc_arg *q = (struct thread_call_proc_arg*)arg;
- return rb_funcall(q->proc, ID_call, 0);
-}
-
-static VALUE
-_thread_call_proc_ensure(arg)
- VALUE arg;
-{
- struct thread_call_proc_arg *q = (struct thread_call_proc_arg*)arg;
- *(q->done) = 1;
- return Qnil;
-}
-
-static VALUE
-_thread_call_proc(arg)
- VALUE arg;
-{
- struct thread_call_proc_arg *q = (struct thread_call_proc_arg*)arg;
-
- return rb_ensure(_thread_call_proc_core, (VALUE)q,
- _thread_call_proc_ensure, (VALUE)q);
-}
-
-static VALUE
-_thread_call_proc_value(th)
- VALUE th;
-{
- return rb_funcall(th, ID_value, 0);
-}
-
-static VALUE
-lib_thread_callback(argc, argv, self)
- int argc;
- VALUE *argv;
- VALUE self;
-{
- struct thread_call_proc_arg *q;
- VALUE proc, th, ret;
- int status, foundEvent;
-
- if (rb_scan_args(argc, argv, "01", &proc) == 0) {
- proc = rb_block_proc();
- }
-
- q = (struct thread_call_proc_arg *)ALLOC(struct thread_call_proc_arg);
- q->proc = proc;
- q->done = (int*)ALLOC(int);
- *(q->done) = 0;
-
- /* create call-proc thread */
- th = rb_thread_create(_thread_call_proc, (void*)q);
-
- rb_thread_schedule();
-
- /* start sub-eventloop */
- foundEvent = lib_eventloop_launcher(/* not check root-widget */0, 0,
- q->done);
-
- if (RTEST(rb_funcall(th, ID_alive_p, 0))) {
- rb_funcall(th, ID_kill, 0);
- ret = Qnil;
- } else {
- ret = rb_protect(_thread_call_proc_value, th, &status);
- }
-
- free(q->done);
- free(q);
-
- if (NIL_P(rbtk_pending_exception)) {
- /* return ruby_errinfo; */
- if (status) {
- rb_exc_raise(ruby_errinfo);
- }
- } else {
- VALUE exc = rbtk_pending_exception;
- rbtk_pending_exception = Qnil;
- /* return exc; */
- rb_exc_raise(exc);
- }
-
- return ret;
-}
-
-
-/* do_one_event */
static VALUE
lib_do_one_event_core(argc, argv, self, is_ip)
int argc;
@@ -2014,12 +979,6 @@ lib_do_one_event_core(argc, argv, self, is_ip)
int flags;
int found_event;
- if (!NIL_P(eventloop_thread)) {
- rb_raise(rb_eRuntimeError, "eventloop is already running");
- }
-
- tcl_stubs_check();
-
if (rb_scan_args(argc, argv, "01", &vflags) == 0) {
flags = TCL_ALL_EVENTS | TCL_DONT_WAIT;
} else {
@@ -2036,7 +995,8 @@ lib_do_one_event_core(argc, argv, self, is_ip)
struct tcltkip *ptr = get_ip(self);
/* ip is deleted? */
- if (deleted_ip(ptr)) {
+ if (Tcl_InterpDeleted(ptr->ip)) {
+ DUMP1("ip is deleted");
return Qfalse;
}
@@ -2049,10 +1009,6 @@ lib_do_one_event_core(argc, argv, self, is_ip)
/* found_event = Tcl_DoOneEvent(TCL_ALL_EVENTS | TCL_DONT_WAIT); */
found_event = Tcl_DoOneEvent(flags);
- if (pending_exception_check0()) {
- return Qfalse;
- }
-
if (found_event) {
return Qtrue;
} else {
@@ -2100,9 +1056,12 @@ ip_set_exc_message(interp, exc)
msg = rb_funcall(exc, ID_message, 0, 0);
#if TCL_MAJOR_VERSION > 8 || (TCL_MAJOR_VERSION == 8 && TCL_MINOR_VERSION > 0)
- enc = rb_attr_get(exc, ID_at_enc);
- if (NIL_P(enc)) {
- enc = rb_attr_get(msg, ID_at_enc);
+ enc = Qnil;
+ if (RTEST(rb_ivar_defined(exc, ID_at_enc))) {
+ enc = rb_ivar_get(exc, ID_at_enc);
+ }
+ if (NIL_P(enc) && RTEST(rb_ivar_defined(msg, ID_at_enc))) {
+ enc = rb_ivar_get(msg, ID_at_enc);
}
if (NIL_P(enc)) {
encoding = (Tcl_Encoding)NULL;
@@ -2115,7 +1074,7 @@ ip_set_exc_message(interp, exc)
/* to avoid a garbled error message dialog */
buf = ALLOC_N(char, (RSTRING(msg)->len)+1);
- memcpy(buf, RSTRING(msg)->ptr, RSTRING(msg)->len);
+ strncpy(buf, RSTRING(msg)->ptr, RSTRING(msg)->len);
buf[RSTRING(msg)->len] = 0;
Tcl_DStringInit(&dstr);
@@ -2124,7 +1083,6 @@ ip_set_exc_message(interp, exc)
Tcl_AppendResult(interp, Tcl_DStringValue(&dstr), (char*)NULL);
DUMP2("error message:%s", Tcl_DStringValue(&dstr));
- Tcl_DStringFree(&dstr);
free(buf);
#else /* TCL_VERSION <= 8.0 */
@@ -2163,88 +1121,130 @@ TkStringValue(obj)
return rb_funcall(obj, ID_inspect, 0, 0);
}
-static int
-tcl_protect_core(interp, proc, data) /* should not raise exception */
- Tcl_Interp *interp;
- VALUE (*proc)();
- VALUE data;
+/* Tcl command `ruby'|`ruby_eval' */
+static VALUE
+ip_ruby_eval_rescue(failed, einfo)
+ VALUE failed;
+ VALUE einfo;
+{
+ DUMP1("call ip_ruby_eval_rescue");
+ RARRAY(failed)->ptr[0] = einfo;
+ return Qnil;
+}
+
+struct eval_body_arg {
+ char *string;
+ VALUE failed;
+};
+
+static VALUE
+ip_ruby_eval_body(arg)
+ struct eval_body_arg *arg;
{
- volatile VALUE ret, exc = Qnil;
+ volatile VALUE ret;
int status = 0;
- int thr_crit_bup = rb_thread_critical;
+ int thr_crit_bup;
+
+ thr_crit_bup = rb_thread_critical;
+ rb_thread_critical = Qtrue;
+
+ DUMP1("call ip_ruby_eval_body");
+ rb_trap_immediate = 0;
+
+#if 0
+ ret = rb_rescue2(rb_eval_string, (VALUE)arg->string,
+ ip_ruby_eval_rescue, arg->failed,
+ rb_eStandardError, rb_eScriptError, rb_eSystemExit,
+ (VALUE)0);
+#else
rb_thread_critical = Qfalse;
- ret = rb_protect(proc, data, &status);
+ ret = rb_eval_string_protect(arg->string, &status);
rb_thread_critical = Qtrue;
if (status) {
- char *buf;
- VALUE old_gc, type, str;
+ char *errtype, *buf;
+ int errtype_len, len;
+ VALUE old_gc;
old_gc = rb_gc_disable();
switch(status) {
case TAG_RETURN:
- type = eTkCallbackReturn;
- goto error;
+ errtype = "LocalJumpError: ";
+ errtype_len = strlen(errtype);
+ len = errtype_len + RSTRING(rb_obj_as_string(ruby_errinfo))->len;
+ buf = ALLOC_N(char, len + 1);
+ strncpy(buf, errtype, errtype_len);
+ strncpy(buf + errtype_len,
+ RSTRING(rb_obj_as_string(ruby_errinfo))->ptr,
+ RSTRING(rb_obj_as_string(ruby_errinfo))->len);
+ *(buf + len) = 0;
+
+ RARRAY(arg->failed)->ptr[0] = rb_exc_new2(eTkCallbackReturn, buf);
+ free(buf);
+ break;
+
case TAG_BREAK:
- type = eTkCallbackBreak;
- goto error;
- case TAG_NEXT:
- type = eTkCallbackContinue;
- goto error;
- error:
- str = rb_str_new2("LocalJumpError: ");
- rb_str_append(str, rb_obj_as_string(ruby_errinfo));
- exc = rb_exc_new3(type, str);
+ errtype = "LocalJumpError: ";
+ errtype_len = strlen(errtype);
+ len = errtype_len + RSTRING(rb_obj_as_string(ruby_errinfo))->len;
+ buf = ALLOC_N(char, len + 1);
+ strncpy(buf, errtype, errtype_len);
+ strncpy(buf + errtype_len,
+ RSTRING(rb_obj_as_string(ruby_errinfo))->ptr,
+ RSTRING(rb_obj_as_string(ruby_errinfo))->len);
+ *(buf + len) = 0;
+
+ RARRAY(arg->failed)->ptr[0] = rb_exc_new2(eTkCallbackBreak, buf);
+ free(buf);
break;
- case TAG_RETRY:
- if (NIL_P(ruby_errinfo)) {
- DUMP1("rb_protect: retry");
- exc = rb_exc_new2(eTkCallbackRetry, "retry jump error");
- } else {
- exc = ruby_errinfo;
- }
+ case TAG_NEXT:
+ errtype = "LocalJumpError: ";
+ errtype_len = strlen(errtype);
+ len = errtype_len + RSTRING(rb_obj_as_string(ruby_errinfo))->len;
+ buf = ALLOC_N(char, len + 1);
+ strncpy(buf, errtype, errtype_len);
+ strncpy(buf + errtype_len,
+ RSTRING(rb_obj_as_string(ruby_errinfo))->ptr,
+ RSTRING(rb_obj_as_string(ruby_errinfo))->len);
+ *(buf + len) = 0;
+
+ RARRAY(arg->failed)->ptr[0] = rb_exc_new2(eTkCallbackContinue,buf);
+ free(buf);
break;
+ case TAG_RETRY:
case TAG_REDO:
if (NIL_P(ruby_errinfo)) {
- DUMP1("rb_protect: redo");
- exc = rb_exc_new2(eTkCallbackRedo, "redo jump error");
+ rb_jump_tag(status);
} else {
- exc = ruby_errinfo;
+ RARRAY(arg->failed)->ptr[0] = ruby_errinfo;
}
break;
case TAG_RAISE:
- if (NIL_P(ruby_errinfo)) {
- exc = rb_exc_new2(rb_eException, "unknown exception");
- } else {
- exc = ruby_errinfo;
- }
- break;
-
case TAG_FATAL:
if (NIL_P(ruby_errinfo)) {
- exc = rb_exc_new2(rb_eFatal, "FATAL");
+ RARRAY(arg->failed)->ptr[0]
+ = rb_exc_new2(rb_eException, "unknown exception");
} else {
- exc = ruby_errinfo;
+ RARRAY(arg->failed)->ptr[0] = ruby_errinfo;
}
break;
case TAG_THROW:
if (NIL_P(ruby_errinfo)) {
- DUMP1("rb_protect: throw");
- exc = rb_exc_new2(eTkCallbackThrow, "throw jump error");
+ rb_jump_tag(TAG_THROW);
} else {
- exc = ruby_errinfo;
+ RARRAY(arg->failed)->ptr[0] = ruby_errinfo;
}
break;
default:
buf = ALLOC_N(char, 256);
sprintf(buf, "unknown loncaljmp status %d", status);
- exc = rb_exc_new2(rb_eException, buf);
+ RARRAY(arg->failed)->ptr[0] = rb_exc_new2(rb_eException, buf);
free(buf);
break;
}
@@ -2253,108 +1253,22 @@ tcl_protect_core(interp, proc, data) /* should not raise exception */
ret = Qnil;
}
+#endif
rb_thread_critical = thr_crit_bup;
- Tcl_ResetResult(interp);
-
- /* status check */
- if (!NIL_P(exc)) {
- volatile VALUE eclass = rb_obj_class(exc);
- volatile VALUE backtrace;
-
- DUMP1("(failed)");
-
- thr_crit_bup = rb_thread_critical;
- rb_thread_critical = Qtrue;
-
- DUMP1("set backtrace");
- if (!NIL_P(backtrace = rb_funcall(exc, ID_backtrace, 0, 0))) {
- backtrace = rb_ary_join(backtrace, rb_str_new2("\n"));
- Tcl_AddErrorInfo(interp, StringValuePtr(backtrace));
- }
-
- rb_thread_critical = thr_crit_bup;
-
- ip_set_exc_message(interp, exc);
-
- if (eclass == eTkCallbackReturn)
- return TCL_RETURN;
-
- if (eclass == eTkCallbackBreak)
- return TCL_BREAK;
-
- if (eclass == eTkCallbackContinue)
- return TCL_CONTINUE;
-
- if (eclass == rb_eSystemExit || eclass == rb_eInterrupt) {
- rbtk_pending_exception = exc;
- return TCL_RETURN;
- }
-
- if (rb_obj_is_kind_of(exc, eTkLocalJumpError)) {
- rbtk_pending_exception = exc;
- return TCL_ERROR;
- }
-
- if (rb_obj_is_kind_of(exc, eLocalJumpError)) {
- VALUE reason = rb_ivar_get(exc, ID_at_reason);
-
- if (TYPE(reason) == T_SYMBOL) {
- if (SYM2ID(reason) == ID_return)
- return TCL_RETURN;
-
- if (SYM2ID(reason) == ID_break)
- return TCL_BREAK;
-
- if (SYM2ID(reason) == ID_next)
- return TCL_CONTINUE;
- }
- }
-
- return TCL_ERROR;
- }
-
- /* result must be string or nil */
- if (!NIL_P(ret)) {
- /* copy result to the tcl interpreter */
- thr_crit_bup = rb_thread_critical;
- rb_thread_critical = Qtrue;
-
- ret = TkStringValue(ret);
- DUMP1("Tcl_AppendResult");
- Tcl_AppendResult(interp, RSTRING(ret)->ptr, (char *)NULL);
-
- rb_thread_critical = thr_crit_bup;
- }
-
- DUMP2("(result) %s", NIL_P(ret) ? "nil" : RSTRING(ret)->ptr);
-
- return TCL_OK;
+ return ret;
}
-static int
-tcl_protect(interp, proc, data)
- Tcl_Interp *interp;
- VALUE (*proc)();
- VALUE data;
+static VALUE
+ip_ruby_eval_ensure(trapflag)
+ VALUE trapflag;
{
- int old_trapflag = rb_trap_immediate;
- int code;
-
-#ifdef HAVE_NATIVETHREAD
- if (!is_ruby_native_thread()) {
- rb_bug("cross-thread violation on tcl_protect()");
- }
-#endif
-
- rb_trap_immediate = 0;
- code = tcl_protect_core(interp, proc, data);
- rb_trap_immediate = old_trapflag;
-
- return code;
+ rb_trap_immediate = NUM2INT(trapflag);
+ return Qnil;
}
+
static int
#if TCL_MAJOR_VERSION >= 8
ip_ruby_eval(clientData, interp, argc, argv)
@@ -2370,33 +1284,21 @@ ip_ruby_eval(clientData, interp, argc, argv)
char *argv[];
#endif
{
- char *arg;
+ volatile VALUE res;
+ volatile VALUE exception = rb_ary_new2(1);
+ int old_trapflag;
+ struct eval_body_arg *arg;
int thr_crit_bup;
- int code;
-
- if (interp == (Tcl_Interp*)NULL) {
- rbtk_pending_exception = rb_exc_new2(rb_eRuntimeError,
- "IP is deleted");
- return TCL_ERROR;
- }
/* ruby command has 1 arg. */
if (argc != 2) {
-#if 0
- rb_raise(rb_eArgError,
- "wrong number of arguments (%d for 1)", argc - 1);
-#else
- char buf[sizeof(int)*8 + 1];
- Tcl_ResetResult(interp);
- sprintf(buf, "%d", argc-1);
- Tcl_AppendResult(interp, "wrong number of arguments (",
- buf, " for 1)", (char *)NULL);
- rbtk_pending_exception = rb_exc_new2(rb_eArgError,
- Tcl_GetStringResult(interp));
- return TCL_ERROR;
-#endif
+ rb_raise(rb_eArgError, "wrong number of arguments (%d for 1)",
+ argc - 1);
}
+ /* allocate */
+ arg = ALLOC(struct eval_body_arg);
+
/* get C string from Tcl object */
#if TCL_MAJOR_VERSION >= 8
{
@@ -2407,31 +1309,158 @@ ip_ruby_eval(clientData, interp, argc, argv)
rb_thread_critical = Qtrue;
str = Tcl_GetStringFromObj(argv[1], &len);
- arg = ALLOC_N(char, len + 1);
- memcpy(arg, str, len);
- arg[len] = 0;
+ arg->string = ALLOC_N(char, len + 1);
+ strncpy(arg->string, str, len);
+ arg->string[len] = 0;
rb_thread_critical = thr_crit_bup;
}
#else /* TCL_MAJOR_VERSION < 8 */
- arg = argv[1];
+ arg->string = argv[1];
#endif
+ /* arg.failed = 0; */
+ RARRAY(exception)->ptr[0] = Qnil;
+ RARRAY(exception)->len = 1;
+ arg->failed = exception;
/* evaluate the argument string by ruby */
- DUMP2("rb_eval_string(%s)", arg);
-
- code = tcl_protect(interp, rb_eval_string, (VALUE)arg);
+ DUMP2("rb_eval_string(%s)", arg->string);
+ old_trapflag = rb_trap_immediate;
+#ifdef HAVE_NATIVETHREAD
+ if (!is_ruby_native_thread()) {
+ rb_bug("cross-thread violation on ip_ruby_eval()");
+ }
+#endif
+ res = rb_ensure(ip_ruby_eval_body, (VALUE)arg,
+ ip_ruby_eval_ensure, INT2FIX(old_trapflag));
#if TCL_MAJOR_VERSION >= 8
- free(arg);
+ free(arg->string);
#endif
- return code;
+ free(arg);
+
+ /* status check */
+ /* if (arg.failed) { */
+ if (!NIL_P(RARRAY(exception)->ptr[0])) {
+ VALUE eclass;
+ volatile VALUE bt_ary;
+ volatile VALUE backtrace;
+
+ DUMP1("(rb_eval_string result) failed");
+
+ Tcl_ResetResult(interp);
+
+ res = RARRAY(exception)->ptr[0];
+ eclass = rb_obj_class(res);
+
+ thr_crit_bup = rb_thread_critical;
+ rb_thread_critical = Qtrue;
+
+ DUMP1("set backtrace");
+ if (!NIL_P(bt_ary = rb_funcall(res, ID_backtrace, 0, 0))) {
+ backtrace = rb_ary_join(bt_ary, rb_str_new2("\n"));
+ StringValue(backtrace);
+ Tcl_AddErrorInfo(interp, RSTRING(backtrace)->ptr);
+ }
+
+ rb_thread_critical = thr_crit_bup;
+
+ if (eclass == eTkCallbackReturn) {
+ ip_set_exc_message(interp, res);
+ return TCL_RETURN;
+
+ } else if (eclass == eTkCallbackBreak) {
+ ip_set_exc_message(interp, res);
+ return TCL_BREAK;
+
+ } else if (eclass == eTkCallbackContinue) {
+ ip_set_exc_message(interp, res);
+ return TCL_CONTINUE;
+
+ } else if (eclass == rb_eSystemExit) {
+ thr_crit_bup = rb_thread_critical;
+ rb_thread_critical = Qtrue;
+
+ /* Tcl_Eval(interp, "destroy ."); */
+ if (Tk_GetNumMainWindows() > 0) {
+ Tk_Window main_win = Tk_MainWindow(interp);
+ if (main_win != (Tk_Window)NULL) {
+ Tk_DestroyWindow(main_win);
+ }
+ }
+
+ /* StringValue(res); */
+ res = rb_funcall(res, ID_message, 0, 0);
+
+ Tcl_AppendResult(interp, RSTRING(res)->ptr, (char*)NULL);
+
+ rb_thread_critical = thr_crit_bup;
+
+ rb_raise(rb_eSystemExit, RSTRING(res)->ptr);
+
+ } else if (rb_obj_is_kind_of(res, eLocalJumpError)) {
+ VALUE reason = rb_ivar_get(res, ID_at_reason);
+
+ if (TYPE(reason) != T_SYMBOL) {
+ ip_set_exc_message(interp, res);
+ return TCL_ERROR;
+ }
+
+ if (SYM2ID(reason) == ID_return) {
+ ip_set_exc_message(interp, res);
+ return TCL_RETURN;
+
+ } else if (SYM2ID(reason) == ID_break) {
+ ip_set_exc_message(interp, res);
+ return TCL_BREAK;
+
+ } else if (SYM2ID(reason) == ID_next) {
+ ip_set_exc_message(interp, res);
+ return TCL_CONTINUE;
+
+ } else {
+ ip_set_exc_message(interp, res);
+ return TCL_ERROR;
+ }
+ } else {
+ ip_set_exc_message(interp, res);
+ return TCL_ERROR;
+ }
+ }
+
+ /* result must be string or nil */
+ if (NIL_P(res)) {
+ DUMP1("(rb_eval_string result) nil");
+ Tcl_ResetResult(interp);
+ return TCL_OK;
+ }
+
+ /* copy result to the tcl interpreter */
+ thr_crit_bup = rb_thread_critical;
+ rb_thread_critical = Qtrue;
+
+ res = TkStringValue(res);
+ DUMP2("(rb_eval_string result) %s", RSTRING(res)->ptr);
+ DUMP1("Tcl_AppendResult");
+ Tcl_ResetResult(interp);
+ Tcl_AppendResult(interp, RSTRING(res)->ptr, (char *)NULL);
+
+ rb_thread_critical = thr_crit_bup;
+
+ return TCL_OK;
}
/* Tcl command `ruby_cmd' */
+struct cmd_body_arg {
+ VALUE receiver;
+ ID method;
+ VALUE args;
+ VALUE failed;
+};
+
static VALUE
ip_ruby_cmd_core(arg)
struct cmd_body_arg *arg;
@@ -2449,6 +1478,150 @@ ip_ruby_cmd_core(arg)
return ret;
}
+static VALUE
+ip_ruby_cmd_rescue(failed, einfo)
+ VALUE failed;
+ VALUE einfo;
+{
+ DUMP1("call ip_ruby_cmd_rescue");
+ RARRAY(failed)->ptr[0] = einfo;
+ return Qnil;
+}
+
+static VALUE
+ip_ruby_cmd_body(arg)
+ struct cmd_body_arg *arg;
+{
+ volatile VALUE ret;
+ int status = 0;
+ int thr_crit_bup;
+ VALUE old_gc;
+
+ volatile VALUE receiver = arg->receiver;
+ volatile VALUE args = arg->args;
+ volatile VALUE failed = arg->failed;
+
+ thr_crit_bup = rb_thread_critical;
+ rb_thread_critical = Qtrue;
+
+ DUMP1("call ip_ruby_cmd_body");
+ rb_trap_immediate = 0;
+
+#if 0
+ ret = rb_rescue2(ip_ruby_cmd_core, (VALUE)arg,
+ ip_ruby_cmd_rescue, arg->failed,
+ rb_eStandardError, rb_eScriptError, rb_eSystemExit,
+ (VALUE)0);
+#else
+ ret = rb_protect(ip_ruby_cmd_core, (VALUE)arg, &status);
+
+ if (status) {
+ char *errtype, *buf;
+ int errtype_len, len;
+
+ old_gc = rb_gc_disable();
+
+ switch(status) {
+ case TAG_RETURN:
+ errtype = "LocalJumpError: ";
+ errtype_len = strlen(errtype);
+ len = errtype_len + RSTRING(rb_obj_as_string(ruby_errinfo))->len;
+ buf = ALLOC_N(char, len + 1);
+ strncpy(buf, errtype, errtype_len);
+ strncpy(buf + errtype_len,
+ RSTRING(rb_obj_as_string(ruby_errinfo))->ptr,
+ RSTRING(rb_obj_as_string(ruby_errinfo))->len);
+ *(buf + len) = 0;
+
+ RARRAY(arg->failed)->ptr[0] = rb_exc_new2(eTkCallbackReturn, buf);
+ free(buf);
+ break;
+
+ case TAG_BREAK:
+ errtype = "LocalJumpError: ";
+ errtype_len = strlen(errtype);
+ len = errtype_len + RSTRING(rb_obj_as_string(ruby_errinfo))->len;
+ buf = ALLOC_N(char, len + 1);
+ strncpy(buf, errtype, errtype_len);
+ strncpy(buf + errtype_len,
+ RSTRING(rb_obj_as_string(ruby_errinfo))->ptr,
+ RSTRING(rb_obj_as_string(ruby_errinfo))->len);
+ *(buf + len) = 0;
+
+ RARRAY(arg->failed)->ptr[0] = rb_exc_new2(eTkCallbackBreak, buf);
+ free(buf);
+ break;
+
+ case TAG_NEXT:
+ errtype = "LocalJumpError: ";
+ errtype_len = strlen(errtype);
+ len = errtype_len + RSTRING(rb_obj_as_string(ruby_errinfo))->len;
+ buf = ALLOC_N(char, len + 1);
+ strncpy(buf, errtype, errtype_len);
+ strncpy(buf + errtype_len,
+ RSTRING(rb_obj_as_string(ruby_errinfo))->ptr,
+ RSTRING(rb_obj_as_string(ruby_errinfo))->len);
+ *(buf + len) = 0;
+
+ RARRAY(arg->failed)->ptr[0] = rb_exc_new2(eTkCallbackContinue,buf);
+ free(buf);
+ break;
+
+ case TAG_RETRY:
+ case TAG_REDO:
+ if (NIL_P(ruby_errinfo)) {
+ rb_jump_tag(status);
+ } else {
+ RARRAY(arg->failed)->ptr[0] = ruby_errinfo;
+ }
+ break;
+
+ case TAG_RAISE:
+ case TAG_FATAL:
+ if (NIL_P(ruby_errinfo)) {
+ RARRAY(arg->failed)->ptr[0]
+ = rb_exc_new2(rb_eException, "unknown exception");
+ } else {
+ RARRAY(arg->failed)->ptr[0] = ruby_errinfo;
+ }
+ break;
+
+ case TAG_THROW:
+ if (NIL_P(ruby_errinfo)) {
+ rb_jump_tag(TAG_THROW);
+ } else {
+ RARRAY(arg->failed)->ptr[0] = ruby_errinfo;
+ }
+ break;
+
+ default:
+ buf = ALLOC_N(char, 256);
+ rb_warn(buf, "unknown loncaljmp status %d", status);
+ RARRAY(arg->failed)->ptr[0] = rb_exc_new2(rb_eException, buf);
+ free(buf);
+ break;
+ }
+
+ if (old_gc == Qfalse) rb_gc_enable();
+
+ ret = Qnil;
+ }
+#endif
+
+ rb_thread_critical = thr_crit_bup;
+ DUMP1("finish ip_ruby_cmd_body");
+
+ return ret;
+}
+
+static VALUE
+ip_ruby_cmd_ensure(trapflag)
+ VALUE trapflag;
+{
+ rb_trap_immediate = NUM2INT(trapflag);
+ return Qnil;
+}
+
/* ruby_cmd receiver method arg ... */
static int
#if TCL_MAJOR_VERSION >= 8
@@ -2465,33 +1638,21 @@ ip_ruby_cmd(clientData, interp, argc, argv)
char *argv[];
#endif
{
+ volatile VALUE res;
volatile VALUE receiver;
volatile ID method;
- volatile VALUE args;
+ volatile VALUE args = rb_ary_new2(argc - 2);
+ volatile VALUE exception = rb_ary_new2(1);
char *str;
int i;
int len;
+ int old_trapflag;
struct cmd_body_arg *arg;
int thr_crit_bup;
VALUE old_gc;
- int code;
-
- if (interp == (Tcl_Interp*)NULL) {
- rbtk_pending_exception = rb_exc_new2(rb_eRuntimeError,
- "IP is deleted");
- return TCL_ERROR;
- }
if (argc < 3) {
-#if 0
rb_raise(rb_eArgError, "too few arguments");
-#else
- Tcl_ResetResult(interp);
- Tcl_AppendResult(interp, "too few arguments", (char *)NULL);
- rbtk_pending_exception = rb_exc_new2(rb_eArgError,
- Tcl_GetStringResult(interp));
- return TCL_ERROR;
-#endif
}
/* allocate */
@@ -2522,23 +1683,14 @@ ip_ruby_cmd(clientData, interp, argc, argv)
len = strlen(str);
buf = ALLOC_N(char, len + 2);
buf[0] = '$';
- memcpy(buf + 1, str, len);
+ strncpy(buf + 1, str, len);
buf[len + 1] = 0;
receiver = rb_gv_get(buf);
free(buf);
}
if (NIL_P(receiver)) {
-#if 0
- rb_raise(rb_eArgError,
- "unknown class/module/global-variable '%s'", str);
-#else
- Tcl_ResetResult(interp);
- Tcl_AppendResult(interp, "unknown class/module/global-variable '",
- str, "'", (char *)NULL);
- rbtk_pending_exception = rb_exc_new2(rb_eArgError,
- Tcl_GetStringResult(interp));
- return TCL_ERROR;
-#endif
+ rb_raise(rb_eArgError, "unknown class/module/global-variable '%s'",
+ str);
}
/* get metrhod */
@@ -2550,7 +1702,6 @@ ip_ruby_cmd(clientData, interp, argc, argv)
method = rb_intern(str);
/* get args */
- args = rb_ary_new2(argc - 2);
RARRAY(args)->len = 0;
for(i = 3; i < argc; i++) {
#if TCL_MAJOR_VERSION >= 8
@@ -2566,22 +1717,145 @@ ip_ruby_cmd(clientData, interp, argc, argv)
if (old_gc == Qfalse) rb_gc_enable();
rb_thread_critical = thr_crit_bup;
+ RARRAY(exception)->ptr[0] = Qnil;
+ RARRAY(exception)->len = 1;
+
arg->receiver = receiver;
arg->method = method;
arg->args = args;
+ arg->failed = exception;
/* evaluate the argument string by ruby */
- code = tcl_protect(interp, ip_ruby_cmd_core, (VALUE)arg);
+ old_trapflag = rb_trap_immediate;
+#ifdef HAVE_NATIVETHREAD
+ if (!is_ruby_native_thread()) {
+ rb_bug("cross-thread violation on ip_ruby_cmd()");
+ }
+#endif
+
+ res = rb_ensure(ip_ruby_cmd_body, (VALUE)arg,
+ ip_ruby_cmd_ensure, INT2FIX(old_trapflag));
free(arg);
- return code;
+ /* status check */
+ /* if (arg.failed) { */
+ if (!NIL_P(RARRAY(exception)->ptr[0])) {
+ VALUE eclass;
+ volatile VALUE bt_ary;
+ volatile VALUE backtrace;
+
+ DUMP1("(rb_eval_cmd result) failed");
+
+ Tcl_ResetResult(interp);
+
+ res = RARRAY(exception)->ptr[0];
+ eclass = rb_obj_class(res);
+
+ thr_crit_bup = rb_thread_critical;
+ rb_thread_critical = Qtrue;
+
+ DUMP1("set backtrace");
+ if (!NIL_P(bt_ary = rb_funcall(res, ID_backtrace, 0, 0))) {
+ backtrace = rb_ary_join(bt_ary, rb_str_new2("\n"));
+ StringValue(backtrace);
+ Tcl_AddErrorInfo(interp, RSTRING(backtrace)->ptr);
+ }
+
+ rb_thread_critical = thr_crit_bup;
+
+ if (eclass == eTkCallbackReturn) {
+ ip_set_exc_message(interp, res);
+ return TCL_RETURN;
+
+ } else if (eclass == eTkCallbackBreak) {
+ ip_set_exc_message(interp, res);
+ return TCL_BREAK;
+
+ } else if (eclass == eTkCallbackContinue) {
+ ip_set_exc_message(interp, res);
+ return TCL_CONTINUE;
+
+ } else if (eclass == rb_eSystemExit) {
+ thr_crit_bup = rb_thread_critical;
+ rb_thread_critical = Qtrue;
+
+ /* Tcl_Eval(interp, "destroy ."); */
+ if (Tk_GetNumMainWindows() > 0) {
+ Tk_Window main_win = Tk_MainWindow(interp);
+ if (main_win != (Tk_Window)NULL) {
+ Tk_DestroyWindow(main_win);
+ }
+ }
+
+ /* StringValue(res); */
+ res = rb_funcall(res, ID_message, 0, 0);
+
+ Tcl_AppendResult(interp, RSTRING(res)->ptr, (char*)NULL);
+
+ rb_thread_critical = thr_crit_bup;
+
+ rb_raise(rb_eSystemExit, RSTRING(res)->ptr);
+
+ } else if (rb_obj_is_kind_of(res, eLocalJumpError)) {
+ VALUE reason = rb_ivar_get(res, ID_at_reason);
+
+ if (TYPE(reason) != T_SYMBOL) {
+ ip_set_exc_message(interp, res);
+ return TCL_ERROR;
+ }
+
+ if (SYM2ID(reason) == ID_return) {
+ ip_set_exc_message(interp, res);
+ return TCL_RETURN;
+
+ } else if (SYM2ID(reason) == ID_break) {
+ ip_set_exc_message(interp, res);
+ return TCL_BREAK;
+
+ } else if (SYM2ID(reason) == ID_next) {
+ ip_set_exc_message(interp, res);
+ return TCL_CONTINUE;
+
+ } else {
+ ip_set_exc_message(interp, res);
+ return TCL_ERROR;
+ }
+ } else {
+ ip_set_exc_message(interp, res);
+ return TCL_ERROR;
+ }
+ }
+
+ /* result must be string or nil */
+ if (NIL_P(res)) {
+ DUMP1("(rb_eval_cmd result) nil");
+ Tcl_ResetResult(interp);
+ return TCL_OK;
+ }
+
+
+ /* copy result to the tcl interpreter */
+ thr_crit_bup = rb_thread_critical;
+ rb_thread_critical = Qtrue;
+
+ old_gc = rb_gc_disable();
+
+ res = TkStringValue(res);
+
+ if (old_gc == Qfalse) rb_gc_enable();
+ DUMP2("(rb_eval_cmd result) '%s'", RSTRING(res)->ptr);
+ DUMP1("Tcl_AppendResult");
+ Tcl_ResetResult(interp);
+ Tcl_AppendResult(interp, RSTRING(res)->ptr, (char *)NULL);
+
+ rb_thread_critical = thr_crit_bup;
+
+ DUMP1("end of ip_ruby_cmd");
+ return TCL_OK;
}
-/*****************************/
-/* relpace of 'exit' command */
-/*****************************/
static int
#if TCL_MAJOR_VERSION >= 8
ip_InterpExitObjCmd(clientData, interp, argc, argv)
@@ -2597,18 +1871,9 @@ ip_InterpExitCommand(clientData, interp, argc, argv)
char *argv[];
#endif
{
- DUMP1("start ip_InterpExitCommand");
- if (interp != (Tcl_Interp*)NULL
- && !Tcl_InterpDeleted(interp)
-#if TCL_NAMESPACE_DEBUG
- && !ip_null_namespace(interp)
-#endif
- ) {
- Tcl_ResetResult(interp);
- /* Tcl_Preserve(interp); */
- /* Tcl_Eval(interp, "interp eval {} {destroy .}; interp delete {}"); */
- ip_finalize(interp);
- Tcl_DeleteInterp(interp);
+ if (!Tcl_InterpDeleted(interp)) {
+ Tcl_Preserve(interp);
+ Tcl_Eval(interp, "interp eval {} {destroy .}; interp delete {}");
Tcl_Release(interp);
}
return TCL_OK;
@@ -2631,77 +1896,62 @@ ip_RubyExitCommand(clientData, interp, argc, argv)
{
int state;
char *cmd, *param;
-#if TCL_MAJOR_VERSION < 8
+
+#if TCL_MAJOR_VERSION >= 8
+ cmd = Tcl_GetString(argv[0]);
+
+#else /* TCL_MAJOR_VERSION < 8 */
char *endptr;
cmd = argv[0];
#endif
- DUMP1("start ip_RubyExitCommand");
-
-#if TCL_MAJOR_VERSION >= 8
- /* cmd = Tcl_GetString(argv[0]); */
- cmd = Tcl_GetStringFromObj(argv[0], (int*)NULL);
+ if (rb_safe_level() >= 4) {
+ rb_raise(rb_eSecurityError,
+ "Insecure operation `exit' at level %d",
+ rb_safe_level());
+ } else if (Tcl_IsSafe(interp)) {
+ rb_raise(rb_eSecurityError,
+ "Insecure operation `exit' on a safe interpreter");
+#if 0
+ } else if (Tcl_GetMaster(interp) != (Tcl_Interp *)NULL) {
+ Tcl_Preserve(interp);
+ Tcl_Eval(interp, "interp eval {} {destroy .}");
+ Tcl_Eval(interp, "interp delete {}");
+ Tcl_Release(interp);
+ return TCL_OK;
#endif
-
- if (argc < 1 || argc > 2) {
- /* arguemnt error */
- Tcl_AppendResult(interp,
- "wrong number of arguments: should be \"",
- cmd, " ?returnCode?\"", (char *)NULL);
- return TCL_ERROR;
}
- if (interp == (Tcl_Interp*)NULL) return TCL_OK;
-
Tcl_ResetResult(interp);
- if (rb_safe_level() >= 4 || Tcl_IsSafe(interp)) {
- ip_finalize(interp);
- Tcl_DeleteInterp(interp);
- Tcl_Release(interp);
- return TCL_OK;
- }
-
switch(argc) {
case 1:
- /* rb_exit(0); */ /* not return if succeed */
+ rb_exit(0); /* not return if succeed */
+
Tcl_AppendResult(interp,
"fail to call \"", cmd, "\"", (char *)NULL);
-
- rbtk_pending_exception = rb_exc_new2(rb_eSystemExit,
- Tcl_GetStringResult(interp));
- rb_iv_set(rbtk_pending_exception, "status", INT2FIX(0));
-
- return TCL_RETURN;
+ return TCL_ERROR;
case 2:
#if TCL_MAJOR_VERSION >= 8
- if (Tcl_GetIntFromObj(interp, argv[1], &state) == TCL_ERROR) {
+ if (!Tcl_GetIntFromObj(interp, argv[1], &state)) {
return TCL_ERROR;
}
- /* param = Tcl_GetString(argv[1]); */
- param = Tcl_GetStringFromObj(argv[1], (int*)NULL);
+ param = Tcl_GetString(argv[1]);
#else /* TCL_MAJOR_VERSION < 8 */
state = (int)strtol(argv[1], &endptr, 0);
- if (*endptr) {
+ if (endptr) {
Tcl_AppendResult(interp,
"expected integer but got \"",
argv[1], "\"", (char *)NULL);
- return TCL_ERROR;
}
param = argv[1];
#endif
- /* rb_exit(state); */ /* not return if succeed */
+ rb_exit(state); /* not return if succeed */
Tcl_AppendResult(interp, "fail to call \"", cmd, " ",
param, "\"", (char *)NULL);
-
- rbtk_pending_exception = rb_exc_new2(rb_eSystemExit,
- Tcl_GetStringResult(interp));
- rb_iv_set(rbtk_pending_exception, "status", INT2FIX(state));
-
- return TCL_RETURN;
-
+ return TCL_ERROR;
default:
/* arguemnt error */
Tcl_AppendResult(interp,
@@ -2716,6 +1966,13 @@ ip_RubyExitCommand(clientData, interp, argc, argv)
/* based on tclEvent.c */
/**************************/
+#if 0 /*
+ Disable the following "update" and "thread_update". Bcause,
+ they don't work in a callback-proc. After calling update in
+ a callback-proc, the callback proc never be worked.
+ If the problem will be fixed in the future, may enable the
+ functions.
+ */
/*********************/
/* replace of update */
/*********************/
@@ -2739,30 +1996,19 @@ ip_rbUpdateCommand(clientData, interp, objc, objv)
#endif
{
int optionIndex;
- int ret;
+ int ret, done;
int flags = 0;
static CONST char *updateOptions[] = {"idletasks", (char *) NULL};
enum updateOptions {REGEXP_IDLETASKS};
+ char *nameString;
int dummy;
DUMP1("Ruby's 'update' is called");
- if (interp == (Tcl_Interp*)NULL) {
- rbtk_pending_exception = rb_exc_new2(rb_eRuntimeError,
- "IP is deleted");
- return TCL_ERROR;
- }
-#ifdef HAVE_NATIVETHREAD
- if (!is_ruby_native_thread()) {
- rb_bug("cross-thread violation on ip_ruby_eval()");
- }
-#endif
-
if (objc == 1) {
flags = TCL_ALL_EVENTS|TCL_DONT_WAIT;
} else if (objc == 2) {
-#if TCL_MAJOR_VERSION >= 8
- if (Tcl_GetIndexFromObj(interp, objv[1], (CONST84 char **)updateOptions,
+ if (Tcl_GetIndexFromObj(interp, objv[1], updateOptions,
"option", 0, &optionIndex) != TCL_OK) {
return TCL_ERROR;
}
@@ -2772,17 +2018,9 @@ ip_rbUpdateCommand(clientData, interp, objc, objv)
break;
}
default: {
- rb_bug("ip_rbUpdateObjCmd: bad option index to UpdateOptions");
+ Tcl_Panic("ip_rbUpdateObjCmd: bad option index to UpdateOptions");
}
}
-#else
- if (strncmp(objv[1], "idletasks", strlen(objv[1])) != 0) {
- Tcl_AppendResult(interp, "bad option \"", objv[1],
- "\": must be idletasks", (char *) NULL);
- return TCL_ERROR;
- }
- flags = TCL_WINDOW_EVENTS|TCL_IDLE_EVENTS|TCL_DONT_WAIT;
-#endif
} else {
#ifdef Tcl_WrongNumArgs
Tcl_WrongNumArgs(interp, 1, objv, "[ idletasks ]");
@@ -2800,33 +2038,12 @@ ip_rbUpdateCommand(clientData, interp, objc, objv)
return TCL_ERROR;
}
- Tcl_Preserve(interp);
-
/* call eventloop */
- /* ret = lib_eventloop_core(0, flags, (int *)NULL);*/ /* ignore result */
- ret = lib_eventloop_launcher(0, flags, (int *)NULL); /* ignore result */
-
- /* exception check */
- if (!NIL_P(rbtk_pending_exception)) {
- Tcl_Release(interp);
-
- /*
- if (rb_obj_is_kind_of(rbtk_pending_exception, rb_eSystemExit)) {
- */
- if (rb_obj_is_kind_of(rbtk_pending_exception, rb_eSystemExit)
- || rb_obj_is_kind_of(rbtk_pending_exception, rb_eInterrupt)) {
- return TCL_RETURN;
- } else{
- return TCL_ERROR;
- }
- }
-
- /* trap check */
- if (rb_trap_pending) {
- Tcl_Release(interp);
-
- return TCL_RETURN;
- }
+#if 1
+ ret = lib_eventloop_core(0, flags, (int *)NULL); /* ignore result */
+#else
+ Tcl_UpdateObjCmd(clientData, interp, objc, objv);
+#endif
/*
* Must clear the interpreter's result because event handlers could
@@ -2835,8 +2052,6 @@ ip_rbUpdateCommand(clientData, interp, objc, objv)
DUMP2("last result '%s'", Tcl_GetStringResult(interp));
Tcl_ResetResult(interp);
- Tcl_Release(interp);
-
DUMP1("finish Ruby's 'update'");
return TCL_OK;
}
@@ -2885,7 +2100,7 @@ ip_rb_threadUpdateCommand(clientData, interp, objc, objv)
#endif
{
int optionIndex;
- int ret;
+ int ret, done;
int flags = 0;
int dummy;
struct th_update_param *param;
@@ -2894,25 +2109,25 @@ ip_rb_threadUpdateCommand(clientData, interp, objc, objv)
volatile VALUE current_thread = rb_thread_current();
DUMP1("Ruby's 'thread_update' is called");
- if (interp == (Tcl_Interp*)NULL) {
- rbtk_pending_exception = rb_exc_new2(rb_eRuntimeError,
- "IP is deleted");
- return TCL_ERROR;
- }
-#ifdef HAVE_NATIVETHREAD
- if (!is_ruby_native_thread()) {
- rb_bug("cross-thread violation on ip_ruby_eval()");
- }
-#endif
- if (rb_thread_alone()
- || NIL_P(eventloop_thread) || eventloop_thread == current_thread) {
+ if (rb_thread_alone() || eventloop_thread == current_thread) {
+#define USE_TCL_UPDATE 0
#if TCL_MAJOR_VERSION >= 8
+# if USE_TCL_UPDATE
+ DUMP1("call Tcl_UpdateObjCmd");
+ return Tcl_UpdateObjCmd(clientData, interp, objc, objv);
+# else
DUMP1("call ip_rbUpdateObjCmd");
return ip_rbUpdateObjCmd(clientData, interp, objc, objv);
+# endif
#else /* TCL_MAJOR_VERSION < 8 */
+# if USE_TCL_UPDATE
+ DUMP1("call ip_rbUpdateCommand");
+ return Tcl_UpdateCommand(clientData, interp, objc, objv);
+# else
DUMP1("call ip_rbUpdateCommand");
return ip_rbUpdateCommand(clientData, interp, objc, objv);
+# endif
#endif
}
@@ -2922,8 +2137,7 @@ ip_rb_threadUpdateCommand(clientData, interp, objc, objv)
flags = TCL_ALL_EVENTS|TCL_DONT_WAIT;
} else if (objc == 2) {
-#if TCL_MAJOR_VERSION >= 8
- if (Tcl_GetIndexFromObj(interp, objv[1], (CONST84 char **)updateOptions,
+ if (Tcl_GetIndexFromObj(interp, objv[1], updateOptions,
"option", 0, &optionIndex) != TCL_OK) {
return TCL_ERROR;
}
@@ -2933,17 +2147,9 @@ ip_rb_threadUpdateCommand(clientData, interp, objc, objv)
break;
}
default: {
- rb_bug("ip_rb_threadUpdateObjCmd: bad option index to UpdateOptions");
+ Tcl_Panic("ip_rb_threadUpdateObjCmd: bad option index to UpdateOptions");
}
}
-#else
- if (strncmp(objv[1], "idletasks", strlen(objv[1])) != 0) {
- Tcl_AppendResult(interp, "bad option \"", objv[1],
- "\": must be idletasks", (char *) NULL);
- return TCL_ERROR;
- }
- flags = TCL_WINDOW_EVENTS|TCL_IDLE_EVENTS|TCL_DONT_WAIT;
-#endif
} else {
#ifdef Tcl_WrongNumArgs
Tcl_WrongNumArgs(interp, 1, objv, "[ idletasks ]");
@@ -2982,6 +2188,7 @@ ip_rb_threadUpdateCommand(clientData, interp, objc, objv)
DUMP1("finish Ruby's 'thread_update'");
return TCL_OK;
}
+#endif /* update and thread_update don't work */
/***************************/
@@ -3014,7 +2221,6 @@ VwaitVarProc(clientData, interp, name1, name2, flags)
return (char *) NULL;
}
-
#if TCL_MAJOR_VERSION >= 8
static int ip_rbVwaitObjCmd _((ClientData, Tcl_Interp *, int,
Tcl_Obj *CONST []));
@@ -3040,18 +2246,7 @@ ip_rbVwaitCommand(clientData, interp, objc, objv)
int thr_crit_bup;
DUMP1("Ruby's 'vwait' is called");
- if (interp == (Tcl_Interp*)NULL) {
- rbtk_pending_exception = rb_exc_new2(rb_eRuntimeError,
- "IP is deleted");
- return TCL_ERROR;
- }
-
Tcl_Preserve(interp);
-#ifdef HAVE_NATIVETHREAD
- if (!is_ruby_native_thread()) {
- rb_bug("cross-thread violation on ip_ruby_eval()");
- }
-#endif
if (objc != 2) {
#ifdef Tcl_WrongNumArgs
@@ -3107,11 +2302,8 @@ ip_rbVwaitCommand(clientData, interp, objc, objv)
Tcl_Release(interp);
return TCL_ERROR;
}
-
done = 0;
-
- foundEvent
- = lib_eventloop_launcher(/* not check root-widget */0, 0, &done);
+ foundEvent = lib_eventloop_core(/* not check root-widget */0, 0, &done);
thr_crit_bup = rb_thread_critical;
rb_thread_critical = Qtrue;
@@ -3122,34 +2314,6 @@ ip_rbVwaitCommand(clientData, interp, objc, objv)
rb_thread_critical = thr_crit_bup;
- /* exception check */
- if (!NIL_P(rbtk_pending_exception)) {
-#if TCL_MAJOR_VERSION >= 8
- Tcl_DecrRefCount(objv[1]);
-#endif
- Tcl_Release(interp);
-
-/*
- if (rb_obj_is_kind_of(rbtk_pending_exception, rb_eSystemExit)) {
-*/
- if (rb_obj_is_kind_of(rbtk_pending_exception, rb_eSystemExit)
- || rb_obj_is_kind_of(rbtk_pending_exception, rb_eInterrupt)) {
- return TCL_RETURN;
- } else{
- return TCL_ERROR;
- }
- }
-
- /* trap check */
- if (rb_trap_pending) {
-#if TCL_MAJOR_VERSION >= 8
- Tcl_DecrRefCount(objv[1]);
-#endif
- Tcl_Release(interp);
-
- return TCL_RETURN;
- }
-
/*
* Clear out the interpreter's result, since it may have been set
* by event handlers.
@@ -3270,11 +2434,6 @@ ip_rbTkWaitCommand(clientData, interp, objc, objv)
int thr_crit_bup;
DUMP1("Ruby's 'tkwait' is called");
- if (interp == (Tcl_Interp*)NULL) {
- rbtk_pending_exception = rb_exc_new2(rb_eRuntimeError,
- "IP is deleted");
- return TCL_ERROR;
- }
Tcl_Preserve(interp);
@@ -3384,10 +2543,8 @@ ip_rbTkWaitCommand(clientData, interp, objc, objv)
Tcl_Release(interp);
return TCL_ERROR;
}
-
done = 0;
- /* lib_eventloop_core(check_rootwidget_flag, 0, &done); */
- lib_eventloop_launcher(check_rootwidget_flag, 0, &done);
+ lib_eventloop_core(check_rootwidget_flag, 0, &done);
thr_crit_bup = rb_thread_critical;
rb_thread_critical = Qtrue;
@@ -3402,44 +2559,19 @@ ip_rbTkWaitCommand(clientData, interp, objc, objv)
rb_thread_critical = thr_crit_bup;
- /* exception check */
- if (!NIL_P(rbtk_pending_exception)) {
- Tcl_Release(interp);
-
- /*
- if (rb_obj_is_kind_of(rbtk_pending_exception, rb_eSystemExit)) {
- */
- if (rb_obj_is_kind_of(rbtk_pending_exception, rb_eSystemExit)
- || rb_obj_is_kind_of(rbtk_pending_exception, rb_eInterrupt)) {
- return TCL_RETURN;
- } else{
- return TCL_ERROR;
- }
- }
-
- /* trap check */
- if (rb_trap_pending) {
- Tcl_Release(interp);
-
- return TCL_RETURN;
- }
-
break;
case TKWAIT_VISIBILITY:
thr_crit_bup = rb_thread_critical;
rb_thread_critical = Qtrue;
- if (!tk_stubs_init_p() || Tk_MainWindow(interp) == (Tk_Window)NULL) {
+ if (Tk_MainWindow(interp) == (Tk_Window)NULL) {
window = NULL;
} else {
window = Tk_NameToWindow(interp, nameString, tkwin);
}
if (window == NULL) {
- Tcl_AppendResult(interp, "tkwait: ",
- "no main-window (not Tk application?)",
- (char*)NULL);
rb_thread_critical = thr_crit_bup;
#if TCL_MAJOR_VERSION >= 8
Tcl_DecrRefCount(objv[2]);
@@ -3455,37 +2587,7 @@ ip_rbTkWaitCommand(clientData, interp, objc, objv)
rb_thread_critical = thr_crit_bup;
done = 0;
- /* lib_eventloop_core(check_rootwidget_flag, 0, &done); */
- lib_eventloop_launcher(check_rootwidget_flag, 0, &done);
-
- /* exception check */
- if (!NIL_P(rbtk_pending_exception)) {
-#if TCL_MAJOR_VERSION >= 8
- Tcl_DecrRefCount(objv[2]);
-#endif
- Tcl_Release(interp);
-
- /*
- if (rb_obj_is_kind_of(rbtk_pending_exception, rb_eSystemExit)) {
- */
- if (rb_obj_is_kind_of(rbtk_pending_exception, rb_eSystemExit)
- || rb_obj_is_kind_of(rbtk_pending_exception, rb_eInterrupt)) {
- return TCL_RETURN;
- } else{
- return TCL_ERROR;
- }
- }
-
- /* trap check */
- if (rb_trap_pending) {
-#if TCL_MAJOR_VERSION >= 8
- Tcl_DecrRefCount(objv[2]);
-#endif
- Tcl_Release(interp);
-
- return TCL_RETURN;
- }
-
+ lib_eventloop_core(check_rootwidget_flag, 0, &done);
if (done != 1) {
/*
* Note that we do not delete the event handler because it
@@ -3527,7 +2629,7 @@ ip_rbTkWaitCommand(clientData, interp, objc, objv)
thr_crit_bup = rb_thread_critical;
rb_thread_critical = Qtrue;
- if (!tk_stubs_init_p() || Tk_MainWindow(interp) == (Tk_Window)NULL) {
+ if (Tk_MainWindow(interp) == (Tk_Window)NULL) {
window = NULL;
} else {
window = Tk_NameToWindow(interp, nameString, tkwin);
@@ -3538,9 +2640,6 @@ ip_rbTkWaitCommand(clientData, interp, objc, objv)
#endif
if (window == NULL) {
- Tcl_AppendResult(interp, "tkwait: ",
- "no main-window (not Tk application?)",
- (char*)NULL);
rb_thread_critical = thr_crit_bup;
Tcl_Release(interp);
return TCL_ERROR;
@@ -3552,31 +2651,7 @@ ip_rbTkWaitCommand(clientData, interp, objc, objv)
rb_thread_critical = thr_crit_bup;
done = 0;
- /* lib_eventloop_core(check_rootwidget_flag, 0, &done); */
- lib_eventloop_launcher(check_rootwidget_flag, 0, &done);
-
- /* exception check */
- if (!NIL_P(rbtk_pending_exception)) {
- Tcl_Release(interp);
-
- /*
- if (rb_obj_is_kind_of(rbtk_pending_exception, rb_eSystemExit)) {
- */
- if (rb_obj_is_kind_of(rbtk_pending_exception, rb_eSystemExit)
- || rb_obj_is_kind_of(rbtk_pending_exception, rb_eInterrupt)) {
- return TCL_RETURN;
- } else{
- return TCL_ERROR;
- }
- }
-
- /* trap check */
- if (rb_trap_pending) {
- Tcl_Release(interp);
-
- return TCL_RETURN;
- }
-
+ lib_eventloop_core(check_rootwidget_flag, 0, &done);
/*
* Note: there's no need to delete the event handler. It was
* deleted automatically when the window was destroyed.
@@ -3697,11 +2772,6 @@ ip_rb_threadVwaitCommand(clientData, interp, objc, objv)
volatile VALUE current_thread = rb_thread_current();
DUMP1("Ruby's 'thread_vwait' is called");
- if (interp == (Tcl_Interp*)NULL) {
- rbtk_pending_exception = rb_exc_new2(rb_eRuntimeError,
- "IP is deleted");
- return TCL_ERROR;
- }
if (rb_thread_alone() || eventloop_thread == current_thread) {
#if TCL_MAJOR_VERSION >= 8
@@ -3767,9 +2837,6 @@ ip_rb_threadVwaitCommand(clientData, interp, objc, objv)
rb_thread_critical = thr_crit_bup;
if (ret != TCL_OK) {
- Tcl_Release(param);
- Tcl_Free((char *)param);
-
#if TCL_MAJOR_VERSION >= 8
Tcl_DecrRefCount(objv[1]);
#endif
@@ -3836,11 +2903,6 @@ ip_rb_threadTkWaitCommand(clientData, interp, objc, objv)
volatile VALUE current_thread = rb_thread_current();
DUMP1("Ruby's 'thread_tkwait' is called");
- if (interp == (Tcl_Interp*)NULL) {
- rbtk_pending_exception = rb_exc_new2(rb_eRuntimeError,
- "IP is deleted");
- return TCL_ERROR;
- }
if (rb_thread_alone() || eventloop_thread == current_thread) {
#if TCL_MAJOR_VERSION >= 8
@@ -4000,17 +3062,13 @@ ip_rb_threadTkWaitCommand(clientData, interp, objc, objv)
thr_crit_bup = rb_thread_critical;
rb_thread_critical = Qtrue;
- if (!tk_stubs_init_p() || Tk_MainWindow(interp) == (Tk_Window)NULL) {
+ if (Tk_MainWindow(interp) == (Tk_Window)NULL) {
window = NULL;
} else {
window = Tk_NameToWindow(interp, nameString, tkwin);
}
if (window == NULL) {
- Tcl_AppendResult(interp, "thread_tkwait: ",
- "no main-window (not Tk application?)",
- (char*)NULL);
-
rb_thread_critical = thr_crit_bup;
Tcl_Release(param);
@@ -4089,7 +3147,7 @@ ip_rb_threadTkWaitCommand(clientData, interp, objc, objv)
thr_crit_bup = rb_thread_critical;
rb_thread_critical = Qtrue;
- if (!tk_stubs_init_p() || Tk_MainWindow(interp) == (Tk_Window)NULL) {
+ if (Tk_MainWindow(interp) == (Tk_Window)NULL) {
window = NULL;
} else {
window = Tk_NameToWindow(interp, nameString, tkwin);
@@ -4100,10 +3158,6 @@ ip_rb_threadTkWaitCommand(clientData, interp, objc, objv)
#endif
if (window == NULL) {
- Tcl_AppendResult(interp, "thread_tkwait: ",
- "no main-window (not Tk application?)",
- (char*)NULL);
-
rb_thread_critical = thr_crit_bup;
Tcl_Release(param);
@@ -4171,7 +3225,6 @@ ip_thread_vwait(self, var)
argv[0] = cmd_str;
argv[1] = var;
-
return ip_invoke_real(2, argv, self);
}
@@ -4187,229 +3240,148 @@ ip_thread_tkwait(self, mode, target)
argv[0] = cmd_str;
argv[1] = mode;
argv[2] = target;
-
return ip_invoke_real(3, argv, self);
}
-
-/* delete slave interpreters */
-#if TCL_MAJOR_VERSION >= 8
-static void
-delete_slaves(ip)
+/* destroy interpreter */
+VALUE del_root(ip)
Tcl_Interp *ip;
{
- int thr_crit_bup;
- Tcl_Interp *slave;
- Tcl_Obj *slave_list, *elem;
- char *slave_name;
- int i, len;
-
- DUMP1("delete slaves");
- thr_crit_bup = rb_thread_critical;
- rb_thread_critical = Qtrue;
-
- if (!Tcl_InterpDeleted(ip) && Tcl_Eval(ip, "interp slaves") == TCL_OK) {
- slave_list = Tcl_GetObjResult(ip);
- Tcl_IncrRefCount(slave_list);
-
- if (Tcl_ListObjLength((Tcl_Interp*)NULL, slave_list, &len) == TCL_OK) {
- for(i = 0; i < len; i++) {
- Tcl_ListObjIndex((Tcl_Interp*)NULL, slave_list, i, &elem);
- Tcl_IncrRefCount(elem);
-
- if (elem == (Tcl_Obj*)NULL) continue;
-
- /* get slave */
- /* slave_name = Tcl_GetString(elem); */
- slave_name = Tcl_GetStringFromObj(elem, (int*)NULL);
- DUMP2("delete slave:'%s'", slave_name);
-
- Tcl_DecrRefCount(elem);
+ Tk_Window main_win;
- slave = Tcl_GetSlave(ip, slave_name);
- if (slave == (Tcl_Interp*)NULL) continue;
-
- /* call ip_finalize */
- ip_finalize(slave);
-
- Tcl_DeleteInterp(slave);
- /* Tcl_Release(slave); */
- }
+ if (!Tcl_InterpDeleted(ip)) {
+ Tcl_Preserve(ip);
+ while((main_win = Tk_MainWindow(ip)) != (Tk_Window)NULL) {
+ DUMP1("wait main_win is destroyed");
+ Tk_DestroyWindow(main_win);
}
-
- Tcl_DecrRefCount(slave_list);
+ Tcl_Release(ip);
}
-
- rb_thread_critical = thr_crit_bup;
+ return Qnil;
}
-#else /* TCL_MAJOR_VERSION < 8 */
+
+
static void
delete_slaves(ip)
Tcl_Interp *ip;
{
- int thr_crit_bup;
Tcl_Interp *slave;
- int argc;
- char **argv;
- char *slave_list;
+ Tcl_Obj *slave_list, *elem;
char *slave_name;
int i, len;
- DUMP1("delete slaves");
- thr_crit_bup = rb_thread_critical;
- rb_thread_critical = Qtrue;
-
- if (!Tcl_InterpDeleted(ip) && Tcl_Eval(ip, "interp slaves") == TCL_OK) {
- slave_list = ip->result;
- if (Tcl_SplitList((Tcl_Interp*)NULL,
- slave_list, &argc, &argv) == TCL_OK) {
- for(i = 0; i < argc; i++) {
- slave_name = argv[i];
+ DUMP2("delete slaves of ip(%lx)", ip);
- DUMP2("delete slave:'%s'", slave_name);
-
- slave = Tcl_GetSlave(ip, slave_name);
- if (slave == (Tcl_Interp*)NULL) continue;
-
- /* call ip_finalize */
- ip_finalize(slave);
+ Tcl_Preserve(ip);
- Tcl_DeleteInterp(slave);
- }
- }
+ if (Tcl_Eval(ip, "info slaves") == TCL_ERROR) {
+ DUMP2("ip(%lx) cannot get a list of slave IPs", ip);
+ return;
}
- rb_thread_critical = thr_crit_bup;
-}
-#endif
+ slave_list = Tcl_GetObjResult(ip);
+ Tcl_IncrRefCount(slave_list);
-
-/* finalize operation */
-static void
-ip_finalize(ip)
- Tcl_Interp *ip;
-{
- Tcl_CmdInfo info;
- int thr_crit_bup;
- int rb_debug_bup; /* When ruby is exiting, printing debug messages in
- some callback operations from Tcl-IP sometimes
- cause SEGV. I don't know the reason. But I got
- SEGV when calling "rb_io_write(rb_stdout, ...)".
- So, in some part of this function, debug mode is
- disabled. If you know the reason, please fix it.
- -- Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp) */
-
- DUMP1("start ip_finalize");
-
- if (ip == (Tcl_Interp*)NULL) {
- DUMP1("ip is NULL");
+ if (Tcl_ListObjLength((Tcl_Interp*)NULL, slave_list, &len) == TCL_ERROR) {
+ DUMP1("slave_list is not a list object");
+ Tcl_DecrRefCount(slave_list);
return;
}
-#if TCL_NAMESPACE_DEBUG
- if (ip_null_namespace(ip)) {
- DUMP2("ip(%lx) has null namespace", ip);
- return;
- }
-#endif
+ for(i = 0; i < len; i++) {
+ Tcl_ListObjIndex((Tcl_Interp*)NULL, slave_list, i, &elem);
+ Tcl_IncrRefCount(elem);
- thr_crit_bup = rb_thread_critical;
- rb_thread_critical = Qtrue;
+ if (elem == (Tcl_Obj*)NULL) continue;
- rb_debug_bup = ruby_debug;
+ /* get slave */
+ slave_name = Tcl_GetString(elem);
+ slave = Tcl_GetSlave(ip, slave_name);
+ if (slave == (Tcl_Interp*)NULL) {
+ DUMP2("slave \"%s\" does not exist", slave_name);
+ continue;
+ }
- Tcl_Preserve(ip);
+ Tcl_DecrRefCount(elem);
- /* delete slaves */
- delete_slaves(ip);
+ Tcl_Preserve(slave);
- /* delete root widget */
-#if 0
- DUMP1("check `destroy'");
- if (Tcl_GetCommandInfo(ip, "destroy", &info)) {
- DUMP1("call `destroy'");
- Tcl_GlobalEval(ip, "destroy .");
- }
-#endif
-#if 1
- DUMP1("destroy root widget");
- if (tk_stubs_init_p() && Tk_MainWindow(ip) != (Tk_Window)NULL) {
- DUMP1("call Tk_DestroyWindow");
- ruby_debug = 0;
- Tk_DestroyWindow(Tk_MainWindow(ip));
- ruby_debug = rb_debug_bup;
- }
-#endif
+ if (!Tcl_InterpDeleted(slave)) {
+ Tcl_Eval(slave, "foreach i [after info] { after cancel $i }");
+ }
- /* call finalize-hook-proc */
- DUMP1("check `finalize-hook-proc'");
- if (Tcl_GetCommandInfo(ip, finalize_hook_name, &info)) {
- DUMP2("call finalize hook proc '%s'", finalize_hook_name);
- ruby_debug = 0;
- Tcl_GlobalEval(ip, finalize_hook_name);
- ruby_debug = rb_debug_bup;
- }
+ /* delete slaves of slave */
+ delete_slaves(slave);
- DUMP1("check `foreach' & `after'");
- if ( Tcl_GetCommandInfo(ip, "foreach", &info)
- && Tcl_GetCommandInfo(ip, "after", &info) ) {
- DUMP1("cancel after callbacks");
- ruby_debug = 0;
- Tcl_GlobalEval(ip, "foreach id [after info] {after cancel $id}");
- ruby_debug = rb_debug_bup;
+ /* delete slave */
+ del_root(slave);
+ while(!Tcl_InterpDeleted(slave)) {
+ DUMP1("wait ip is deleted");
+ Tcl_DeleteInterp(slave);
+ }
+
+ Tcl_Release(slave);
}
- Tcl_Release(ip);
+ Tcl_DecrRefCount(slave_list);
- DUMP1("finish ip_finalize");
- ruby_debug = rb_debug_bup;
- rb_thread_critical = thr_crit_bup;
+ Tcl_Release(ip);
}
-
-/* destroy interpreter */
static void
ip_free(ptr)
struct tcltkip *ptr;
{
- int thr_crit_bup;
+ Tcl_CmdInfo info;
+ int thr_crit_bup;
DUMP2("free Tcl Interp %lx", ptr->ip);
if (ptr) {
thr_crit_bup = rb_thread_critical;
rb_thread_critical = Qtrue;
- if ( ptr->ip != (Tcl_Interp*)NULL
- && !Tcl_InterpDeleted(ptr->ip)
- && Tcl_GetMaster(ptr->ip) != (Tcl_Interp*)NULL
- && !Tcl_InterpDeleted(Tcl_GetMaster(ptr->ip)) ) {
- DUMP2("parent IP(%lx) is not deleted", Tcl_GetMaster(ptr->ip));
- DUMP2("slave IP(%lx) should not be deleted", ptr->ip);
- free(ptr);
- rb_thread_critical = thr_crit_bup;
- return;
- }
+ DUMP2("IP ref_count = %d", ptr->ref_count);
- if (ptr->ip == (Tcl_Interp*)NULL) {
- DUMP1("ip_free is called for deleted IP");
- free(ptr);
- rb_thread_critical = thr_crit_bup;
- return;
+ if (!Tcl_InterpDeleted(ptr->ip)) {
+ DUMP2("IP(%lx) is not deleted", ptr->ip);
+ /* Tcl_Preserve(ptr->ip); */
+ rbtk_preserve_ip(ptr);
+
+ delete_slaves(ptr->ip);
+
+ Tcl_ResetResult(ptr->ip);
+
+ if (Tcl_GetCommandInfo(ptr->ip, finalize_hook_name, &info)) {
+ DUMP2("call finalize hook proc '%s'", finalize_hook_name);
+ Tcl_Eval(ptr->ip, finalize_hook_name);
+ }
+
+ if (!Tcl_InterpDeleted(ptr->ip)) {
+ Tcl_Eval(ptr->ip, "foreach i [after info] {after cancel $i}");
+ }
+
+ del_root(ptr->ip);
+
+ DUMP1("delete interp");
+ while(!Tcl_InterpDeleted(ptr->ip)) {
+ DUMP1("wait ip is deleted");
+ Tcl_DeleteInterp(ptr->ip);
+ }
+
+ /* Tcl_Release(ptr->ip); */
+ rbtk_release_ip(ptr);
}
- ip_finalize(ptr->ip);
- Tcl_DeleteInterp(ptr->ip);
- Tcl_Release(ptr->ip);
+ rbtk_release_ip(ptr);
+ DUMP2("IP ref_count = %d", ptr->ref_count);
free(ptr);
rb_thread_critical = thr_crit_bup;
}
-
DUMP1("complete freeing Tcl Interp");
}
-
/* create and initialize interpreter */
static VALUE ip_alloc _((VALUE));
static VALUE
@@ -4419,180 +3391,6 @@ ip_alloc(self)
return Data_Wrap_Struct(self, 0, ip_free, 0);
}
-static void
-ip_replace_wait_commands(interp, mainWin)
- Tcl_Interp *interp;
- Tk_Window mainWin;
-{
- /* replace 'vwait' command */
-#if TCL_MAJOR_VERSION >= 8
- DUMP1("Tcl_CreateObjCommand(\"vwait\")");
- Tcl_CreateObjCommand(interp, "vwait", ip_rbVwaitObjCmd,
- (ClientData)mainWin, (Tcl_CmdDeleteProc *)NULL);
-#else /* TCL_MAJOR_VERSION < 8 */
- DUMP1("Tcl_CreateCommand(\"vwait\")");
- Tcl_CreateCommand(interp, "vwait", ip_rbVwaitCommand,
- (ClientData)mainWin, (Tcl_CmdDeleteProc *)NULL);
-#endif
-
- /* replace 'tkwait' command */
-#if TCL_MAJOR_VERSION >= 8
- DUMP1("Tcl_CreateObjCommand(\"tkwait\")");
- Tcl_CreateObjCommand(interp, "tkwait", ip_rbTkWaitObjCmd,
- (ClientData)mainWin, (Tcl_CmdDeleteProc *)NULL);
-#else /* TCL_MAJOR_VERSION < 8 */
- DUMP1("Tcl_CreateCommand(\"tkwait\")");
- Tcl_CreateCommand(interp, "tkwait", ip_rbTkWaitCommand,
- (ClientData)mainWin, (Tcl_CmdDeleteProc *)NULL);
-#endif
-
- /* add 'thread_vwait' command */
-#if TCL_MAJOR_VERSION >= 8
- DUMP1("Tcl_CreateObjCommand(\"thread_vwait\")");
- Tcl_CreateObjCommand(interp, "thread_vwait", ip_rb_threadVwaitObjCmd,
- (ClientData)mainWin, (Tcl_CmdDeleteProc *)NULL);
-#else /* TCL_MAJOR_VERSION < 8 */
- DUMP1("Tcl_CreateCommand(\"thread_vwait\")");
- Tcl_CreateCommand(interp, "thread_vwait", ip_rb_threadVwaitCommand,
- (ClientData)mainWin, (Tcl_CmdDeleteProc *)NULL);
-#endif
-
- /* add 'thread_tkwait' command */
-#if TCL_MAJOR_VERSION >= 8
- DUMP1("Tcl_CreateObjCommand(\"thread_tkwait\")");
- Tcl_CreateObjCommand(interp, "thread_tkwait", ip_rb_threadTkWaitObjCmd,
- (ClientData)mainWin, (Tcl_CmdDeleteProc *)NULL);
-#else /* TCL_MAJOR_VERSION < 8 */
- DUMP1("Tcl_CreateCommand(\"thread_tkwait\")");
- Tcl_CreateCommand(interp, "thread_tkwait", ip_rb_threadTkWaitCommand,
- (ClientData)mainWin, (Tcl_CmdDeleteProc *)NULL);
-#endif
-
- /* replace 'update' command */
-#if TCL_MAJOR_VERSION >= 8
- DUMP1("Tcl_CreateObjCommand(\"update\")");
- Tcl_CreateObjCommand(interp, "update", ip_rbUpdateObjCmd,
- (ClientData)mainWin, (Tcl_CmdDeleteProc *)NULL);
-#else /* TCL_MAJOR_VERSION < 8 */
- DUMP1("Tcl_CreateCommand(\"update\")");
- Tcl_CreateCommand(interp, "update", ip_rbUpdateCommand,
- (ClientData)mainWin, (Tcl_CmdDeleteProc *)NULL);
-#endif
-
- /* add 'thread_update' command */
-#if TCL_MAJOR_VERSION >= 8
- DUMP1("Tcl_CreateObjCommand(\"thread_update\")");
- Tcl_CreateObjCommand(interp, "thread_update", ip_rb_threadUpdateObjCmd,
- (ClientData)mainWin, (Tcl_CmdDeleteProc *)NULL);
-#else /* TCL_MAJOR_VERSION < 8 */
- DUMP1("Tcl_CreateCommand(\"thread_update\")");
- Tcl_CreateCommand(interp, "thread_update", ip_rb_threadUpdateCommand,
- (ClientData)mainWin, (Tcl_CmdDeleteProc *)NULL);
-#endif
-}
-
-
-
-#if TCL_MAJOR_VERSION >= 8
-static int ip_rbNamespaceObjCmd _((ClientData, Tcl_Interp *, int,
- Tcl_Obj *CONST []));
-static int
-ip_rbNamespaceObjCmd(clientData, interp, objc, objv)
- ClientData clientData;
- Tcl_Interp *interp;
- int objc;
- Tcl_Obj *CONST objv[];
-{
- Tcl_CmdInfo info;
- int ret;
-
- if (!Tcl_GetCommandInfo(interp, "__orig_namespace_command__", &(info))) {
- Tcl_ResetResult(interp);
- Tcl_AppendResult(interp,
- "invalid command name \"namespace\"", (char*)NULL);
- return TCL_ERROR;
- }
-
- rbtk_eventloop_depth++;
- DUMP2("namespace wrapper enter depth == %d", rbtk_eventloop_depth);
-
- if (info.isNativeObjectProc) {
- ret = (*(info.objProc))(info.objClientData, interp, objc, objv);
- } else {
- /* string interface */
- int i;
- char **argv;
-
- argv = (char **)Tcl_Alloc(sizeof(char *) * (objc + 1));
-
- for(i = 0; i < objc; i++) {
- /* argv[i] = Tcl_GetString(objv[i]); */
- argv[i] = Tcl_GetStringFromObj(objv[i], (int*)NULL);
- }
- argv[objc] = (char *)NULL;
-
- ret = (*(info.proc))(info.clientData, interp,
- objc, (CONST84 char **)argv);
-
- Tcl_Free((char*)argv);
- }
-
- DUMP2("namespace wrapper exit depth == %d", rbtk_eventloop_depth);
- rbtk_eventloop_depth--;
-
- return ret;
-}
-#endif
-
-static void
-ip_wrap_namespace_command(interp)
- Tcl_Interp *interp;
-{
-#if TCL_MAJOR_VERSION >= 8
- Tcl_CmdInfo orig_info;
-
- if (!Tcl_GetCommandInfo(interp, "namespace", &(orig_info))) {
- return;
- }
-
- if (orig_info.isNativeObjectProc) {
- Tcl_CreateObjCommand(interp, "__orig_namespace_command__",
- orig_info.objProc, orig_info.objClientData,
- orig_info.deleteProc);
- } else {
- Tcl_CreateCommand(interp, "__orig_namespace_command__",
- orig_info.proc, orig_info.clientData,
- orig_info.deleteProc);
- }
-
- Tcl_CreateObjCommand(interp, "namespace", ip_rbNamespaceObjCmd,
- (ClientData) 0, (Tcl_CmdDeleteProc *)NULL);
-#endif
-}
-
-
-/* call when interpreter is deleted */
-static void
-ip_CallWhenDeleted(clientData, ip)
- ClientData clientData;
- Tcl_Interp *ip;
-{
- int thr_crit_bup;
- Tcl_CmdInfo info;
- Tk_Window main_win = (Tk_Window) clientData;
-
- DUMP1("start ip_CallWhenDeleted");
- thr_crit_bup = rb_thread_critical;
- rb_thread_critical = Qtrue;
-
- ip_finalize(ip);
-
- DUMP1("finish ip_CallWhenDeleted");
- rb_thread_critical = thr_crit_bup;
-}
-
-
-/* initialize interpreter */
static VALUE
ip_init(argc, argv, self)
int argc;
@@ -4602,15 +3400,12 @@ ip_init(argc, argv, self)
struct tcltkip *ptr; /* tcltkip data struct */
VALUE argv0, opts;
int cnt;
- int st;
int with_tk = 1;
- Tk_Window mainWin = (Tk_Window)NULL;
+ Tk_Window mainWin;
/* security check */
if (ruby_safe_level >= 4) {
- rb_raise(rb_eSecurityError,
- "Cannot create a TclTkIp object at level %d",
- ruby_safe_level);
+ rb_raise(rb_eSecurityError, "Cannot create a TclTkIp object at level %d", ruby_safe_level);
}
/* create object */
@@ -4623,38 +3418,11 @@ ip_init(argc, argv, self)
/* from Tk_Main() */
DUMP1("Tcl_CreateInterp");
- ptr->ip = ruby_tcl_create_ip_and_stubs_init(&st);
+ ptr->ip = Tcl_CreateInterp();
if (ptr->ip == NULL) {
- switch(st) {
- case TCLTK_STUBS_OK:
- break;
- case NO_TCL_DLL:
- rb_raise(rb_eLoadError, "tcltklib: fail to open tcl_dll");
- case NO_FindExecutable:
- rb_raise(rb_eLoadError, "tcltklib: can't find Tcl_FindExecutable");
- case NO_CreateInterp:
- rb_raise(rb_eLoadError, "tcltklib: can't find Tcl_CreateInterp()");
- case NO_DeleteInterp:
- rb_raise(rb_eLoadError, "tcltklib: can't find Tcl_DeleteInterp()");
- case FAIL_CreateInterp:
- rb_raise(rb_eRuntimeError, "tcltklib: fail to create a new IP");
- case FAIL_Tcl_InitStubs:
- rb_raise(rb_eRuntimeError, "tcltklib: fail to Tcl_InitStubs()");
- default:
- rb_raise(rb_eRuntimeError, "tcltklib: unknown error(%d) on ruby_tcl_create_ip_and_stubs_init", st);
- }
+ rb_raise(rb_eRuntimeError, "fail to create a new Tk interpreter");
}
-#if TCL_MAJOR_VERSION >= 8
-#if TCL_NAMESPACE_DEBUG
- DUMP1("get current namespace");
- if ((ptr->default_ns = Tcl_GetCurrentNamespace(ptr->ip))
- == (Tcl_Namespace*)NULL) {
- rb_raise(rb_eRuntimeError, "a new Tk interpreter has a NULL namespace");
- }
-#endif
-#endif
-
rbtk_preserve_ip(ptr);
DUMP2("IP ref_count = %d", ptr->ref_count);
current_interp = ptr->ip;
@@ -4665,7 +3433,11 @@ ip_init(argc, argv, self)
/* from Tcl_AppInit() */
DUMP1("Tcl_Init");
if (Tcl_Init(ptr->ip) == TCL_ERROR) {
+#if TCL_MAJOR_VERSION >= 8
rb_raise(rb_eRuntimeError, "%s", Tcl_GetStringResult(ptr->ip));
+#else /* TCL_MAJOR_VERSION < 8 */
+ rb_raise(rb_eRuntimeError, "%s", ptr->ip->result);
+#endif
}
/* set variables */
@@ -4683,14 +3455,8 @@ ip_init(argc, argv, self)
case 1:
/* argv0 */
if (!NIL_P(argv0)) {
- if (strncmp(StringValuePtr(argv0), "-e", 3) == 0
- || strncmp(StringValuePtr(argv0), "-", 2) == 0) {
- Tcl_SetVar(ptr->ip, "argv0", "ruby", TCL_GLOBAL_ONLY);
- } else {
- /* Tcl_SetVar(ptr->ip, "argv0", StringValuePtr(argv0), 0); */
- Tcl_SetVar(ptr->ip, "argv0", StringValuePtr(argv0),
- TCL_GLOBAL_ONLY);
- }
+ /* Tcl_SetVar(ptr->ip, "argv0", StringValuePtr(argv0), 0); */
+ Tcl_SetVar(ptr->ip, "argv0", StringValuePtr(argv0), TCL_GLOBAL_ONLY);
}
case 0:
/* no args */
@@ -4700,22 +3466,13 @@ ip_init(argc, argv, self)
/* from Tcl_AppInit() */
if (with_tk) {
DUMP1("Tk_Init");
- st = ruby_tk_stubs_init(ptr->ip);
- switch(st) {
- case TCLTK_STUBS_OK:
- break;
- case NO_Tk_Init:
- rb_raise(rb_eLoadError, "tcltklib: can't find Tk_Init()");
- case FAIL_Tk_Init:
- rb_raise(rb_eRuntimeError, "tcltklib: fail to Tk_Init(). %s",
- Tcl_GetStringResult(ptr->ip));
- case FAIL_Tk_InitStubs:
- rb_raise(rb_eRuntimeError, "tcltklib: fail to Tk_InitStubs(). %s",
- Tcl_GetStringResult(ptr->ip));
- default:
- rb_raise(rb_eRuntimeError, "tcltklib: unknown error(%d) on ruby_tk_stubs_init", st);
+ if (Tk_Init(ptr->ip) == TCL_ERROR) {
+#if TCL_MAJOR_VERSION >= 8
+ rb_raise(rb_eRuntimeError, "%s", Tcl_GetStringResult(ptr->ip));
+#else /* TCL_MAJOR_VERSION < 8 */
+ rb_raise(rb_eRuntimeError, "%s", ptr->ip->result);
+#endif
}
-
DUMP1("Tcl_StaticPackage(\"Tk\")");
#if TCL_MAJOR_VERSION >= 8
Tcl_StaticPackage(ptr->ip, "Tk", Tk_Init, Tk_SafeInit);
@@ -4723,12 +3480,12 @@ ip_init(argc, argv, self)
Tcl_StaticPackage(ptr->ip, "Tk", Tk_Init,
(Tcl_PackageInitProc *) NULL);
#endif
-
- /* get main window */
- mainWin = Tk_MainWindow(ptr->ip);
- Tk_Preserve((ClientData)mainWin);
}
+ /* get main window */
+ mainWin = Tk_MainWindow(ptr->ip);
+ Tk_Preserve((ClientData)mainWin);
+
/* add ruby command to the interpreter */
#if TCL_MAJOR_VERSION >= 8
DUMP1("Tcl_CreateObjCommand(\"ruby\")");
@@ -4775,29 +3532,92 @@ ip_init(argc, argv, self)
(ClientData)mainWin, (Tcl_CmdDeleteProc *)NULL);
#endif
- /* replace vwait and tkwait */
- ip_replace_wait_commands(ptr->ip, mainWin);
+#if 0 /*
+ Disable the following "update" and "thread_update". Bcause,
+ they don't work in a callback-proc. After calling update in
+ a callback-proc, the callback proc never be worked.
+ If the problem will be fixed in the future, may enable the
+ functions.
+ */
+ /* replace 'update' command */
+# if TCL_MAJOR_VERSION >= 8
+ DUMP1("Tcl_CreateObjCommand(\"update\")");
+ Tcl_CreateObjCommand(ptr->ip, "update", ip_rbUpdateObjCmd,
+ (ClientData)mainWin, (Tcl_CmdDeleteProc *)NULL);
+# else /* TCL_MAJOR_VERSION < 8 */
+ DUMP1("Tcl_CreateCommand(\"update\")");
+ Tcl_CreateCommand(ptr->ip, "update", ip_rbUpdateCommand,
+ (ClientData)mainWin, (Tcl_CmdDeleteProc *)NULL);
+# endif
- /* wrap namespace command */
- ip_wrap_namespace_command(ptr->ip);
+ /* add 'thread_update' command */
+# if TCL_MAJOR_VERSION >= 8
+ DUMP1("Tcl_CreateObjCommand(\"thread_update\")");
+ Tcl_CreateObjCommand(ptr->ip, "thread_update", ip_rb_threadUpdateObjCmd,
+ (ClientData)mainWin, (Tcl_CmdDeleteProc *)NULL);
+# else /* TCL_MAJOR_VERSION < 8 */
+ DUMP1("Tcl_CreateCommand(\"thread_update\")");
+ Tcl_CreateCommand(ptr->ip, "thread_update", ip_rb_threadUpdateCommand,
+ (ClientData)mainWin, (Tcl_CmdDeleteProc *)NULL);
+# endif
+#endif
- /* set finalizer */
- Tcl_CallWhenDeleted(ptr->ip, ip_CallWhenDeleted, (ClientData)mainWin);
+ /* replace 'vwait' command */
+#if TCL_MAJOR_VERSION >= 8
+ DUMP1("Tcl_CreateObjCommand(\"vwait\")");
+ Tcl_CreateObjCommand(ptr->ip, "vwait", ip_rbVwaitObjCmd,
+ (ClientData)mainWin, (Tcl_CmdDeleteProc *)NULL);
+#else /* TCL_MAJOR_VERSION < 8 */
+ DUMP1("Tcl_CreateCommand(\"vwait\")");
+ Tcl_CreateCommand(ptr->ip, "vwait", ip_rbVwaitCommand,
+ (ClientData)mainWin, (Tcl_CmdDeleteProc *)NULL);
+#endif
- if (mainWin != (Tk_Window)NULL) {
- Tk_Release((ClientData)mainWin);
- }
+ /* replace 'tkwait' command */
+#if TCL_MAJOR_VERSION >= 8
+ DUMP1("Tcl_CreateObjCommand(\"tkwait\")");
+ Tcl_CreateObjCommand(ptr->ip, "tkwait", ip_rbTkWaitObjCmd,
+ (ClientData)mainWin, (Tcl_CmdDeleteProc *)NULL);
+#else /* TCL_MAJOR_VERSION < 8 */
+ DUMP1("Tcl_CreateCommand(\"tkwait\")");
+ Tcl_CreateCommand(ptr->ip, "tkwait", ip_rbTkWaitCommand,
+ (ClientData)mainWin, (Tcl_CmdDeleteProc *)NULL);
+#endif
+
+ /* add 'thread_vwait' command */
+#if TCL_MAJOR_VERSION >= 8
+ DUMP1("Tcl_CreateObjCommand(\"thread_vwait\")");
+ Tcl_CreateObjCommand(ptr->ip, "thread_vwait", ip_rb_threadVwaitObjCmd,
+ (ClientData)mainWin, (Tcl_CmdDeleteProc *)NULL);
+#else /* TCL_MAJOR_VERSION < 8 */
+ DUMP1("Tcl_CreateCommand(\"thread_vwait\")");
+ Tcl_CreateCommand(ptr->ip, "thread_vwait", ip_rb_threadVwaitCommand,
+ (ClientData)mainWin, (Tcl_CmdDeleteProc *)NULL);
+#endif
+
+ /* add 'thread_tkwait' command */
+#if TCL_MAJOR_VERSION >= 8
+ DUMP1("Tcl_CreateObjCommand(\"thread_tkwait\")");
+ Tcl_CreateObjCommand(ptr->ip, "thread_tkwait", ip_rb_threadTkWaitObjCmd,
+ (ClientData)mainWin, (Tcl_CmdDeleteProc *)NULL);
+#else /* TCL_MAJOR_VERSION < 8 */
+ DUMP1("Tcl_CreateCommand(\"thread_tkwait\")");
+ Tcl_CreateCommand(ptr->ip, "thread_tkwait", ip_rb_threadTkWaitCommand,
+ (ClientData)mainWin, (Tcl_CmdDeleteProc *)NULL);
+#endif
+
+ Tk_Release((ClientData)mainWin);
return self;
}
static VALUE
-ip_create_slave_core(interp, argc, argv)
- VALUE interp;
+ip_create_slave(argc, argv, self)
int argc;
VALUE *argv;
+ VALUE self;
{
- struct tcltkip *master = get_ip(interp);
+ struct tcltkip *master = get_ip(self);
struct tcltkip *slave = ALLOC(struct tcltkip);
VALUE safemode;
VALUE name;
@@ -4805,20 +3625,15 @@ ip_create_slave_core(interp, argc, argv)
int thr_crit_bup;
Tk_Window mainWin;
- /* ip is deleted? */
- if (deleted_ip(master)) {
- return rb_exc_new2(rb_eRuntimeError,
- "deleted master cannot create a new slave");
+ /* safe-mode check */
+ if (rb_scan_args(argc, argv, "11", &name, &safemode) == 1) {
+ safemode = Qfalse;
}
-
- name = argv[0];
- safemode = argv[1];
-
if (Tcl_IsSafe(master->ip) == 1) {
safe = 1;
} else if (safemode == Qfalse || NIL_P(safemode)) {
safe = 0;
- /* rb_secure(4); */ /* already checked */
+ rb_secure(4);
} else {
safe = 1;
}
@@ -4826,43 +3641,30 @@ ip_create_slave_core(interp, argc, argv)
thr_crit_bup = rb_thread_critical;
rb_thread_critical = Qtrue;
-#if 0
- /* init Tk */
- if (RTEST(with_tk)) {
- volatile VALUE exc;
- if (!tk_stubs_init_p()) {
- exc = tcltkip_init_tk(interp);
- if (!NIL_P(exc)) {
- rb_thread_critical = thr_crit_bup;
- return exc;
- }
- }
+ /* ip is deleted? */
+ if (Tcl_InterpDeleted(master->ip)) {
+ DUMP1("master-ip is deleted");
+ rb_thread_critical = thr_crit_bup;
+ rb_raise(rb_eRuntimeError, "deleted master cannot create a new slave interpreter");
}
-#endif
/* create slave-ip */
slave->ref_count = 0;
slave->allow_ruby_exit = 0;
slave->return_value = 0;
- slave->ip = Tcl_CreateSlave(master->ip, RSTRING(name)->ptr, safe);
+ slave->ip = Tcl_CreateSlave(master->ip, StringValuePtr(name), safe);
if (slave->ip == NULL) {
rb_thread_critical = thr_crit_bup;
- return rb_exc_new2(rb_eRuntimeError,
- "fail to create the new slave interpreter");
+ rb_raise(rb_eRuntimeError, "fail to create the new slave interpreter");
}
-#if TCL_MAJOR_VERSION >= 8
-#if TCL_NAMESPACE_DEBUG
- slave->default_ns = Tcl_GetCurrentNamespace(slave->ip);
-#endif
-#endif
rbtk_preserve_ip(slave);
slave->has_orig_exit
= Tcl_GetCommandInfo(slave->ip, "exit", &(slave->orig_exit_info));
/* replace 'exit' command --> 'interp_exit' command */
- mainWin = (tk_stubs_init_p())? Tk_MainWindow(slave->ip): (Tk_Window)NULL;
+ mainWin = Tk_MainWindow(slave->ip);
#if TCL_MAJOR_VERSION >= 8
DUMP1("Tcl_CreateObjCommand(\"exit\") --> \"interp_exit\"");
Tcl_CreateObjCommand(slave->ip, "exit", ip_InterpExitObjCmd,
@@ -4873,155 +3675,37 @@ ip_create_slave_core(interp, argc, argv)
(ClientData)mainWin, (Tcl_CmdDeleteProc *)NULL);
#endif
- /* replace vwait and tkwait */
- ip_replace_wait_commands(slave->ip, mainWin);
-
- /* wrap namespace command */
- ip_wrap_namespace_command(slave->ip);
-
- /* set finalizer */
- Tcl_CallWhenDeleted(slave->ip, ip_CallWhenDeleted, (ClientData)mainWin);
-
rb_thread_critical = thr_crit_bup;
- return Data_Wrap_Struct(CLASS_OF(interp), 0, ip_free, slave);
+ return Data_Wrap_Struct(CLASS_OF(self), 0, ip_free, slave);
}
+/* make ip "safe" */
static VALUE
-ip_create_slave(argc, argv, self)
- int argc;
- VALUE *argv;
- VALUE self;
-{
- struct tcltkip *master = get_ip(self);
- VALUE safemode;
- VALUE name;
- VALUE callargv[2];
-
- /* ip is deleted? */
- if (deleted_ip(master)) {
- rb_raise(rb_eRuntimeError,
- "deleted master cannot create a new slave interpreter");
- }
-
- /* argument check */
- if (rb_scan_args(argc, argv, "11", &name, &safemode) == 1) {
- safemode = Qfalse;
- }
- if (Tcl_IsSafe(master->ip) != 1
- && (safemode == Qfalse || NIL_P(safemode))) {
- rb_secure(4);
- }
-
- StringValue(name);
- callargv[0] = name;
- callargv[1] = safemode;
-
- return tk_funcall(ip_create_slave_core, 2, callargv, self);
-}
-
-#if defined(MAC_TCL) || defined(__WIN32__)
-#if TCL_MAJOR_VERSION < 8 \
- || (TCL_MAJOR_VERSION == 8 && TCL_MINOR_VERSION == 0) \
- || (TCL_MAJOR_VERSION == 8 && TCL_MINOR_VERSION == 1 \
- && (TCL_RELEASE_LEVEL == TCL_ALPHA_RELEASE \
- || (TCL_RELEASE_LEVEL == TCL_BETA_RELEASE \
- && TCL_RELEASE_SERIAL < 2) ) )
-EXTERN void TkConsoleCreate _((void));
-#endif
-#if TCL_MAJOR_VERSION == 8 && TCL_MINOR_VERSION == 1 \
- && ( (TCL_RELEASE_LEVEL == TCL_FINAL_RELEASE \
- && TCL_RELEASE_SERIAL == 0) \
- || (TCL_RELEASE_LEVEL == TCL_BETA_RELEASE \
- && TCL_RELEASE_SERIAL >= 2) )
-EXTERN void TkConsoleCreate_ _((void));
-#endif
-#endif
-static VALUE
-ip_create_console_core(interp, argc, argv)
- VALUE interp;
- int argc; /* dummy */
- VALUE *argv; /* dummy */
-{
- struct tcltkip *ptr = get_ip(interp);
-
- if (!tk_stubs_init_p()) {
- tcltkip_init_tk(interp);
- }
-
- if (Tcl_GetVar(ptr->ip,"tcl_interactive",TCL_GLOBAL_ONLY) == (char*)NULL) {
- Tcl_SetVar(ptr->ip, "tcl_interactive", "0", TCL_GLOBAL_ONLY);
- }
-
-#if TCL_MAJOR_VERSION > 8 \
- || (TCL_MAJOR_VERSION == 8 \
- && (TCL_MINOR_VERSION > 1 \
- || (TCL_MINOR_VERSION == 1 \
- && TCL_RELEASE_LEVEL == TCL_FINAL_RELEASE \
- && TCL_RELEASE_SERIAL >= 1) ) )
- Tk_InitConsoleChannels(ptr->ip);
-
- if (Tk_CreateConsoleWindow(ptr->ip) != TCL_OK) {
- rb_raise(rb_eRuntimeError, "fail to create console-window");
- }
-#else
-#if defined(MAC_TCL) || defined(__WIN32__)
-#if TCL_MAJOR_VERSION == 8 && TCL_MINOR_VERSION == 1 \
- && ( (TCL_RELEASE_LEVEL == TCL_FINAL_RELEASE && TCL_RELEASE_SERIAL == 0) \
- || (TCL_RELEASE_LEVEL == TCL_BETA_RELEASE && TCL_RELEASE_SERIAL >= 2) )
- TkConsoleCreate_();
-#else
- TkConsoleCreate();
-#endif
-
- if (TkConsoleInit(ptr->ip) != TCL_OK) {
- rb_raise(rb_eRuntimeError, "fail to create console-window");
- }
-#else
- rb_notimplement();
-#endif
-#endif
-
- return interp;
-}
-
-static VALUE
-ip_create_console(self)
+ip_make_safe(self)
VALUE self;
{
struct tcltkip *ptr = get_ip(self);
-
- /* ip is deleted? */
- if (deleted_ip(ptr)) {
- rb_raise(rb_eRuntimeError, "interpreter is deleted");
- }
-
- return tk_funcall(ip_create_console_core, 0, (VALUE*)NULL, self);
-}
-
-/* make ip "safe" */
-static VALUE
-ip_make_safe_core(interp, argc, argv)
- VALUE interp;
- int argc; /* dummy */
- VALUE *argv; /* dummy */
-{
- struct tcltkip *ptr = get_ip(interp);
Tk_Window mainWin;
/* ip is deleted? */
- if (deleted_ip(ptr)) {
- return rb_exc_new2(rb_eRuntimeError, "interpreter is deleted");
+ if (Tcl_InterpDeleted(ptr->ip)) {
+ DUMP1("ip is deleted");
+ rb_raise(rb_eRuntimeError, "interpreter is deleted");
}
if (Tcl_MakeSafe(ptr->ip) == TCL_ERROR) {
- return rb_exc_new2(rb_eRuntimeError, Tcl_GetStringResult(ptr->ip));
+#if TCL_MAJOR_VERSION >= 8
+ rb_raise(rb_eRuntimeError, "%s", Tcl_GetStringResult(ptr->ip));
+#else /* TCL_MAJOR_VERSION < 8 */
+ rb_raise(rb_eRuntimeError, "%s", ptr->ip->result);
+#endif
}
ptr->allow_ruby_exit = 0;
/* replace 'exit' command --> 'interp_exit' command */
- mainWin = (tk_stubs_init_p())? Tk_MainWindow(ptr->ip): (Tk_Window)NULL;
+ mainWin = Tk_MainWindow(ptr->ip);
#if TCL_MAJOR_VERSION >= 8
DUMP1("Tcl_CreateObjCommand(\"exit\") --> \"interp_exit\"");
Tcl_CreateObjCommand(ptr->ip, "exit", ip_InterpExitObjCmd,
@@ -5032,21 +3716,7 @@ ip_make_safe_core(interp, argc, argv)
(ClientData)mainWin, (Tcl_CmdDeleteProc *)NULL);
#endif
- return interp;
-}
-
-static VALUE
-ip_make_safe(self)
- VALUE self;
-{
- struct tcltkip *ptr = get_ip(self);
-
- /* ip is deleted? */
- if (deleted_ip(ptr)) {
- rb_raise(rb_eRuntimeError, "interpreter is deleted");
- }
-
- return tk_funcall(ip_make_safe_core, 0, (VALUE*)NULL, self);
+ return self;
}
/* is safe? */
@@ -5057,7 +3727,8 @@ ip_is_safe_p(self)
struct tcltkip *ptr = get_ip(self);
/* ip is deleted? */
- if (deleted_ip(ptr)) {
+ if (Tcl_InterpDeleted(ptr->ip)) {
+ DUMP1("ip is deleted");
rb_raise(rb_eRuntimeError, "interpreter is deleted");
}
@@ -5076,7 +3747,8 @@ ip_allow_ruby_exit_p(self)
struct tcltkip *ptr = get_ip(self);
/* ip is deleted? */
- if (deleted_ip(ptr)) {
+ if (Tcl_InterpDeleted(ptr->ip)) {
+ DUMP1("ip is deleted");
rb_raise(rb_eRuntimeError, "interpreter is deleted");
}
@@ -5098,7 +3770,8 @@ ip_allow_ruby_exit_set(self, val)
rb_secure(4);
/* ip is deleted? */
- if (deleted_ip(ptr)) {
+ if (Tcl_InterpDeleted(ptr->ip)) {
+ DUMP1("ip is deleted");
rb_raise(rb_eRuntimeError, "interpreter is deleted");
}
@@ -5107,7 +3780,7 @@ ip_allow_ruby_exit_set(self, val)
"insecure operation on a safe interpreter");
}
- mainWin = (tk_stubs_init_p())? Tk_MainWindow(ptr->ip): (Tk_Window)NULL;
+ mainWin = Tk_MainWindow(ptr->ip);
if (RTEST(val)) {
ptr->allow_ruby_exit = 1;
@@ -5142,355 +3815,116 @@ static VALUE
ip_delete(self)
VALUE self;
{
- int thr_crit_bup;
struct tcltkip *ptr = get_ip(self);
- Tcl_CmdInfo info;
- if (ptr == (struct tcltkip *)NULL || ptr->ip == (Tcl_Interp*)NULL) {
- DUMP1("delete deleted IP");
- return Qnil;
- }
+ /* Tcl_Preserve(ptr->ip); */
+ rbtk_preserve_ip(ptr);
- thr_crit_bup = rb_thread_critical;
- rb_thread_critical = Qtrue;
+ if (!Tcl_InterpDeleted(ptr->ip)) {
+ Tcl_Eval(ptr->ip, "foreach i [after info] { after cancel $i }");
+ }
- DUMP1("call ip_finalize");
- ip_finalize(ptr->ip);
+ del_root(ptr->ip);
DUMP1("delete interp");
- Tcl_DeleteInterp(ptr->ip);
- Tcl_Release(ptr->ip);
-
- ptr->ip = (Tcl_Interp*)NULL;
+ while(!Tcl_InterpDeleted(ptr->ip)) {
+ DUMP1("wait ip is deleted");
+ Tcl_DeleteInterp(ptr->ip);
+ }
- rb_thread_critical = thr_crit_bup;
+ /* Tcl_Release(ptr->ip); */
+ rbtk_release_ip(ptr);
return Qnil;
}
-
/* is deleted? */
static VALUE
-ip_has_invalid_namespace_p(self)
- VALUE self;
-{
- struct tcltkip *ptr = get_ip(self);
-
- if (ptr == (struct tcltkip *)NULL || ptr->ip == (Tcl_Interp *)NULL) {
- /* deleted IP */
- return Qtrue;
- }
-
-#if TCL_NAMESPACE_DEBUG
- if (rbtk_invalid_namespace(ptr)) {
- return Qtrue;
- } else {
- return Qfalse;
- }
-#else
- return Qfalse;
-#endif
-}
-
-static VALUE
ip_is_deleted_p(self)
VALUE self;
{
struct tcltkip *ptr = get_ip(self);
- if (deleted_ip(ptr)) {
+ if (Tcl_InterpDeleted(ptr->ip)) {
return Qtrue;
} else {
return Qfalse;
}
}
-static VALUE
-ip_has_mainwindow_p(self)
- VALUE self;
-{
- struct tcltkip *ptr = get_ip(self);
-
- if (deleted_ip(ptr) || !tk_stubs_init_p()) {
- return Qnil;
- } else if (Tk_MainWindow(ptr->ip) == (Tk_Window)NULL) {
- return Qfalse;
- } else {
- return Qtrue;
- }
-}
-/*** ruby string <=> tcl object ***/
-#if TCL_MAJOR_VERSION >= 8
static VALUE
-get_str_from_obj(obj)
- Tcl_Obj *obj;
-{
- int len, binary = 0;
- const char *s;
- volatile VALUE str;
-
-#if TCL_MAJOR_VERSION == 8 && TCL_MINOR_VERSION == 0
- s = Tcl_GetStringFromObj(obj, &len);
-#else /* TCL_VERSION >= 8.1 */
- if (Tcl_GetCharLength(obj) != Tcl_UniCharLen(Tcl_GetUnicode(obj))) {
- /* possibly binary string */
- s = Tcl_GetByteArrayFromObj(obj, &len);
- binary = 1;
- } else {
- /* possibly text string */
- s = Tcl_GetStringFromObj(obj, &len);
- }
+#ifdef HAVE_STDARG_PROTOTYPES
+create_ip_exc(VALUE interp, VALUE exc, const char *fmt, ...)
+#else
+create_ip_exc(interp, exc, fmt, va_alist)
+ VALUE interp:
+ VALUE exc;
+ const char *fmt;
+ va_dcl
#endif
- str = s ? rb_str_new(s, len) : rb_str_new2("");
- if (binary) rb_ivar_set(str, ID_at_enc, rb_str_new2("binary"));
- return str;
-}
-
-static Tcl_Obj *
-get_obj_from_str(str)
- VALUE str;
{
- const char *s = StringValuePtr(str);
+ va_list args;
+ char buf[BUFSIZ];
+ VALUE einfo;
-#if TCL_MAJOR_VERSION == 8 && TCL_MINOR_VERSION == 0
- return Tcl_NewStringObj((char*)s, RSTRING(str)->len);
-#else /* TCL_VERSION >= 8.1 */
- VALUE enc = rb_attr_get(str, ID_at_enc);
+ va_init_list(args,fmt);
+ vsnprintf(buf, BUFSIZ, fmt, args);
+ buf[BUFSIZ - 1] = '\0';
+ va_end(args);
+ einfo = rb_exc_new2(exc, buf);
+ rb_ivar_set(einfo, ID_at_interp, interp);
+ Tcl_ResetResult(get_ip(interp)->ip);
- if (!NIL_P(enc)) {
- StringValue(enc);
- if (strcmp(RSTRING(enc)->ptr, "binary") == 0) {
- /* binary string */
- return Tcl_NewByteArrayObj(s, RSTRING(str)->len);
- } else {
- /* text string */
- return Tcl_NewStringObj(s, RSTRING(str)->len);
- }
- } else if (strlen(s) != RSTRING(str)->len) {
- /* probably binary string */
- return Tcl_NewByteArrayObj(s, RSTRING(str)->len);
- } else {
- /* probably text string */
- return Tcl_NewStringObj(s, RSTRING(str)->len);
- }
-#endif
+ return einfo;
}
-#endif /* ruby string <=> tcl object */
static VALUE
ip_get_result_string_obj(interp)
Tcl_Interp *interp;
{
#if TCL_MAJOR_VERSION >= 8
- Tcl_Obj *retObj;
- volatile VALUE strval;
-
- retObj = Tcl_GetObjResult(interp);
- Tcl_IncrRefCount(retObj);
- strval = get_str_from_obj(retObj);
- OBJ_TAINT(strval);
- Tcl_DecrRefCount(retObj);
- return strval;
-#else
- return rb_tainted_str_new2(interp->result);
-#endif
-}
-
-/* call Tcl/Tk functions on the eventloop thread */
-static VALUE
-callq_safelevel_handler(arg, callq)
- VALUE arg;
- VALUE callq;
-{
- struct call_queue *q;
-
- Data_Get_Struct(callq, struct call_queue, q);
- DUMP2("(safe-level handler) $SAFE = %d", q->safe_level);
- rb_set_safe_level(q->safe_level);
- return((q->func)(q->interp, q->argc, q->argv));
-}
-
-static int call_queue_handler _((Tcl_Event *, int));
-static int
-call_queue_handler(evPtr, flags)
- Tcl_Event *evPtr;
- int flags;
-{
- struct call_queue *q = (struct call_queue *)evPtr;
- volatile VALUE ret;
- volatile VALUE q_dat;
- struct tcltkip *ptr;
-
- DUMP2("do_call_queue_handler : evPtr = %p", evPtr);
- DUMP2("queue_handler thread : %lx", rb_thread_current());
- DUMP2("added by thread : %lx", q->thread);
-
- if (*(q->done)) {
- DUMP1("processed by another event-loop");
- return 0;
- } else {
- DUMP1("process it on current event-loop");
- }
-
- /* process it */
- *(q->done) = 1;
-
- /* deleted ipterp ? */
- ptr = get_ip(q->interp);
- if (deleted_ip(ptr)) {
- /* deleted IP --> ignore */
- return 1;
- }
-
- /* check safe-level */
- if (rb_safe_level() != q->safe_level) {
- /* q_dat = Data_Wrap_Struct(rb_cData,0,0,q); */
- q_dat = Data_Wrap_Struct(rb_cData,call_queue_mark,0,q);
- ret = rb_funcall(rb_proc_new(callq_safelevel_handler, q_dat),
- ID_call, 0);
- rb_gc_force_recycle(q_dat);
- } else {
- DUMP2("call function (for caller thread:%lx)", q->thread);
- DUMP2("call function (current thread:%lx)", rb_thread_current());
- ret = (q->func)(q->interp, q->argc, q->argv);
- }
-
- /* set result */
- RARRAY(q->result)->ptr[0] = ret;
-
- /* complete */
- *(q->done) = -1;
-
- /* back to caller */
- DUMP2("back to caller (caller thread:%lx)", q->thread);
- DUMP2(" (current thread:%lx)", rb_thread_current());
- rb_thread_run(q->thread);
- DUMP1("finish back to caller");
-
- /* end of handler : remove it */
- return 1;
-}
-
-static VALUE
-tk_funcall(func, argc, argv, obj)
- VALUE (*func)();
- int argc;
- VALUE *argv;
- VALUE obj;
-{
- struct call_queue *callq;
- int *alloc_done;
- int thr_crit_bup;
- volatile VALUE current = rb_thread_current();
- volatile VALUE ip_obj = obj;
- volatile VALUE result;
- volatile VALUE ret;
-
+ int len;
+ char *s;
- if (!NIL_P(ip_obj) && deleted_ip(get_ip(ip_obj))) {
- return Qnil;
- }
+# if TCL_MAJOR_VERSION == 8 && TCL_MINOR_VERSION == 0
+ s = Tcl_GetStringFromObj(Tcl_GetObjResult(interp), &len);
+ return(rb_tainted_str_new(s, len));
- if (NIL_P(eventloop_thread) || current == eventloop_thread) {
- if (NIL_P(eventloop_thread)) {
- DUMP2("tk_funcall from thread:%lx but no eventloop", current);
- } else {
- DUMP2("tk_funcall from current eventloop %lx", current);
- }
- result = (func)(ip_obj, argc, argv);
- if (rb_obj_is_kind_of(result, rb_eException)) {
- rb_exc_raise(result);
- }
- return result;
- }
+# else /* TCL_VERSION >= 8.1 */
+ volatile VALUE strval;
+ Tcl_Obj *retobj = Tcl_GetObjResult(interp);
+ int thr_crit_bup;
- DUMP2("tk_funcall from thread %lx (NOT current eventloop)", current);
+ Tcl_IncrRefCount(retobj);
thr_crit_bup = rb_thread_critical;
rb_thread_critical = Qtrue;
- /* allocate memory (argv cross over thread : must be in heap) */
- if (argv) {
- VALUE *temp = ALLOC_N(VALUE, argc);
- MEMCPY(temp, argv, VALUE, argc);
- argv = temp;
+ if (Tcl_GetCharLength(retobj) != Tcl_UniCharLen(Tcl_GetUnicode(retobj))) {
+ /* possibly binary string */
+ s = Tcl_GetByteArrayFromObj(retobj, &len);
+ strval = rb_tainted_str_new(s, len);
+ rb_ivar_set(strval, ID_at_enc, rb_str_new2("binary"));
+ } else {
+ /* possibly text string */
+ s = Tcl_GetStringFromObj(retobj, &len);
+ strval = rb_tainted_str_new(s, len);
}
- /* allocate memory (keep result) */
- alloc_done = (int*)ALLOC(int);
- *alloc_done = 0;
-
- /* allocate memory (freed by Tcl_ServiceEvent) */
- callq = (struct call_queue *)Tcl_Alloc(sizeof(struct call_queue));
- Tcl_Preserve(callq);
-
- /* allocate result obj */
- result = rb_ary_new2(1);
- RARRAY(result)->ptr[0] = Qnil;
- RARRAY(result)->len = 1;
-
- /* construct event data */
- callq->done = alloc_done;
- callq->func = func;
- callq->argc = argc;
- callq->argv = argv;
- callq->interp = ip_obj;
- callq->result = result;
- callq->thread = current;
- callq->safe_level = rb_safe_level();
- callq->ev.proc = call_queue_handler;
-
- /* add the handler to Tcl event queue */
- DUMP1("add handler");
- Tcl_QueueEvent(&(callq->ev), TCL_QUEUE_HEAD);
-
rb_thread_critical = thr_crit_bup;
- /* wait for the handler to be processed */
- DUMP2("wait for handler (current thread:%lx)", current);
- while(*alloc_done >= 0) {
- rb_thread_stop();
- }
- DUMP2("back from handler (current thread:%lx)", current);
+ Tcl_DecrRefCount(retobj);
- /* get result & free allocated memory */
- ret = RARRAY(result)->ptr[0];
- free(alloc_done);
- if (argv) free(argv);
-
- Tcl_Release(callq);
-
- /* exception? */
- if (rb_obj_is_kind_of(ret, rb_eException)) {
- DUMP1("raise exception");
- rb_exc_raise(ret);
- }
+ return(strval);
- DUMP1("exit tk_funcall");
- return ret;
+# endif
+#else /* TCL_MAJOR_VERSION < 8 */
+ return(rb_tainted_str_new2(interp->result));
+#endif
}
-
/* eval string in tcl by Tcl_Eval() */
-#if TCL_MAJOR_VERSION >= 8
-struct call_eval_info {
- struct tcltkip *ptr;
- Tcl_Obj *cmd;
-};
-
-static VALUE
-call_tcl_eval(arg)
- VALUE arg;
-{
- struct call_eval_info *inf = (struct call_eval_info *)arg;
-
- inf->ptr->return_value = Tcl_EvalObj(inf->ptr->ip, inf->cmd);
-
- return Qnil;
-}
-#endif
-
static VALUE
ip_eval_real(self, cmd_str, cmd_len)
VALUE self;
@@ -5498,6 +3932,8 @@ ip_eval_real(self, cmd_str, cmd_len)
int cmd_len;
{
volatile VALUE ret;
+ char *s;
+ int len;
struct tcltkip *ptr = get_ip(self);
int thr_crit_bup;
@@ -5513,77 +3949,39 @@ ip_eval_real(self, cmd_str, cmd_len)
Tcl_IncrRefCount(cmd);
/* ip is deleted? */
- if (deleted_ip(ptr)) {
+ if (Tcl_InterpDeleted(ptr->ip)) {
+ DUMP1("ip is deleted");
Tcl_DecrRefCount(cmd);
rb_thread_critical = thr_crit_bup;
ptr->return_value = TCL_OK;
return rb_tainted_str_new2("");
} else {
- int status;
- struct call_eval_info inf;
-
/* Tcl_Preserve(ptr->ip); */
rbtk_preserve_ip(ptr);
-
-#if 0
+
ptr->return_value = Tcl_EvalObj(ptr->ip, cmd);
/* ptr->return_value = Tcl_GlobalEvalObj(ptr->ip, cmd); */
-#else
- inf.ptr = ptr;
- inf.cmd = cmd;
- ret = rb_protect(call_tcl_eval, (VALUE)&inf, &status);
- switch(status) {
- case TAG_RAISE:
- if (NIL_P(ruby_errinfo)) {
- rbtk_pending_exception = rb_exc_new2(rb_eException,
- "unknown exception");
- } else {
- rbtk_pending_exception = ruby_errinfo;
- }
- break;
-
- case TAG_FATAL:
- if (NIL_P(ruby_errinfo)) {
- rbtk_pending_exception = rb_exc_new2(rb_eFatal, "FATAL");
- } else {
- rbtk_pending_exception = ruby_errinfo;
- }
- }
-#endif
}
Tcl_DecrRefCount(cmd);
}
- if (pending_exception_check1(thr_crit_bup, ptr)) {
+ if (ptr->return_value == TCL_ERROR) {
+ volatile VALUE exc;
+ exc = create_ip_exc(self, rb_eRuntimeError,
+ "%s", Tcl_GetStringResult(ptr->ip));
+ /* Tcl_Release(ptr->ip); */
rbtk_release_ip(ptr);
- return rbtk_pending_exception;
- }
- if (ptr->return_value == TCL_ERROR) {
- if (event_loop_abort_on_exc > 0 && !Tcl_InterpDeleted(ptr->ip)) {
- volatile VALUE exc;
- exc = create_ip_exc(self, rb_eRuntimeError,
- "%s", Tcl_GetStringResult(ptr->ip));
- rbtk_release_ip(ptr);
- rb_thread_critical = thr_crit_bup;
- return exc;
- } else {
- if (event_loop_abort_on_exc < 0) {
- rb_warning("%s (ignore)", Tcl_GetStringResult(ptr->ip));
- } else {
- rb_warn("%s (ignore)", Tcl_GetStringResult(ptr->ip));
- }
- Tcl_ResetResult(ptr->ip);
- rbtk_release_ip(ptr);
- rb_thread_critical = thr_crit_bup;
- return rb_tainted_str_new2("");
- }
+ rb_thread_critical = thr_crit_bup;
+ rb_exc_raise(exc);
}
+ DUMP2("(TCL_Eval result) %d", ptr->return_value);
/* pass back the result (as string) */
ret = ip_get_result_string_obj(ptr->ip);
+ /* Tcl_Release(ptr->ip); */
rbtk_release_ip(ptr);
rb_thread_critical = thr_crit_bup;
return ret;
@@ -5592,7 +3990,8 @@ ip_eval_real(self, cmd_str, cmd_len)
DUMP2("Tcl_Eval(%s)", cmd_str);
/* ip is deleted? */
- if (deleted_ip(ptr)) {
+ if (Tcl_InterpDeleted(ptr->ip)) {
+ DUMP1("ip is deleted");
ptr->return_value = TCL_OK;
return rb_tainted_str_new2("");
} else {
@@ -5602,23 +4001,18 @@ ip_eval_real(self, cmd_str, cmd_len)
/* ptr->return_value = Tcl_GlobalEval(ptr->ip, cmd_str); */
}
- if (pending_exception_check1(thr_crit_bup, ptr)) {
- rbtk_release_ip(ptr);
- return rbtk_pending_exception;
- }
-
if (ptr->return_value == TCL_ERROR) {
volatile VALUE exc;
-
exc = create_ip_exc(self, rb_eRuntimeError, "%s", ptr->ip->result);
-
+ /* Tcl_Release(ptr->ip); */
rbtk_release_ip(ptr);
- return exc;
+ rb_exc_raise(exc);
}
DUMP2("(TCL_Eval result) %d", ptr->return_value);
/* pass back the result (as string) */
ret = ip_get_result_string_obj(ptr->ip);
+ /* Tcl_Release(ptr->ip); */
rbtk_release_ip(ptr);
return ret;
#endif
@@ -5647,6 +4041,10 @@ eval_queue_handler(evPtr, flags)
volatile VALUE ret;
volatile VALUE q_dat;
+ DUMP2("do_eval_queue_handler : evPtr = %p", evPtr);
+ DUMP2("eval queue_thread : %lx", rb_thread_current());
+ DUMP2("added by thread : %lx", q->thread);
+
if (*(q->done)) {
DUMP1("processed by another event-loop");
return 0;
@@ -5670,6 +4068,8 @@ eval_queue_handler(evPtr, flags)
ID_call, 0);
rb_gc_force_recycle(q_dat);
} else {
+ DUMP2("call eval_real (for caller thread:%lx)", q->thread);
+ DUMP2("call eval_real (current thread:%lx)", rb_thread_current());
ret = ip_eval_real(q->interp, q->str, q->len);
}
@@ -5709,11 +4109,11 @@ ip_eval(self, str)
StringValue(str);
rb_thread_critical = thr_crit_bup;
- if (NIL_P(eventloop_thread) || current == eventloop_thread) {
- if (NIL_P(eventloop_thread)) {
- DUMP2("eval from thread:%lx but no eventloop", current);
- } else {
+ if (eventloop_thread == 0 || current == eventloop_thread) {
+ if (eventloop_thread) {
DUMP2("eval from current eventloop %lx", current);
+ } else {
+ DUMP2("eval from thread:%lx but no eventloop", current);
}
result = ip_eval_real(self, RSTRING(str)->ptr, RSTRING(str)->len);
if (rb_obj_is_kind_of(result, rb_eException)) {
@@ -5732,7 +4132,7 @@ ip_eval(self, str)
*alloc_done = 0;
eval_str = ALLOC_N(char, RSTRING(str)->len + 1);
- memcpy(eval_str, RSTRING(str)->ptr, RSTRING(str)->len);
+ strncpy(eval_str, RSTRING(str)->ptr, RSTRING(str)->len);
eval_str[RSTRING(str)->len] = 0;
/* allocate memory (freed by Tcl_ServiceEvent) */
@@ -5753,7 +4153,6 @@ ip_eval(self, str)
evq->thread = current;
evq->safe_level = rb_safe_level();
evq->ev.proc = eval_queue_handler;
-
position = TCL_QUEUE_TAIL;
/* add the handler to Tcl event queue */
@@ -5786,23 +4185,19 @@ ip_eval(self, str)
/* restart Tk */
static VALUE
-lib_restart_core(interp, argc, argv)
- VALUE interp;
- int argc; /* dummy */
- VALUE *argv; /* dummy */
+lib_restart(self)
+ VALUE self;
{
volatile VALUE exc;
- struct tcltkip *ptr = get_ip(interp);
+ struct tcltkip *ptr = get_ip(self);
int thr_crit_bup;
- int st;
-
- /* rb_secure(4); */ /* already checked */
- /* tcl_stubs_check(); */ /* already checked */
+ rb_secure(4);
/* ip is deleted? */
- if (deleted_ip(ptr)) {
- return rb_exc_new2(rb_eRuntimeError, "interpreter is deleted");
+ if (Tcl_InterpDeleted(ptr->ip)) {
+ DUMP1("ip is deleted");
+ rb_raise(rb_eRuntimeError, "interpreter is deleted");
}
thr_crit_bup = rb_thread_critical;
@@ -5817,13 +4212,11 @@ lib_restart_core(interp, argc, argv)
DUMP2("(TCL_Eval result) %d", ptr->return_value);
Tcl_ResetResult(ptr->ip);
-#if TCL_MAJOR_VERSION >= 8
/* delete namespace ( tested on tk8.4.5 ) */
ptr->return_value = Tcl_Eval(ptr->ip, "namespace delete ::tk::msgcat");
/* ignore ERROR */
DUMP2("(TCL_Eval result) %d", ptr->return_value);
Tcl_ResetResult(ptr->ip);
-#endif
/* delete trace proc ( tested on tk8.4.5 ) */
ptr->return_value = Tcl_Eval(ptr->ip, "trace vdelete ::tk_strictMotif w ::tk::EventMotifBindings");
@@ -5831,41 +4224,43 @@ lib_restart_core(interp, argc, argv)
DUMP2("(TCL_Eval result) %d", ptr->return_value);
Tcl_ResetResult(ptr->ip);
- /* execute Tk_Init or Tk_SafeInit */
- exc = tcltkip_init_tk(interp);
- if (!NIL_P(exc)) {
- rb_thread_critical = thr_crit_bup;
+ /* execute Tk_Init of Tk_SafeInit */
+#if TCL_MAJOR_VERSION >= 8
+ if (Tcl_IsSafe(ptr->ip)) {
+ DUMP1("Tk_SafeInit");
+ if (Tk_SafeInit(ptr->ip) == TCL_ERROR) {
+ exc = rb_exc_new2(rb_eRuntimeError, Tcl_GetStringResult(ptr->ip));
+ /* Tcl_Release(ptr->ip); */
+ rbtk_release_ip(ptr);
+ rb_thread_critical = thr_crit_bup;
+ rb_exc_raise(exc);
+ }
+ } else {
+ DUMP1("Tk_Init");
+ if (Tk_Init(ptr->ip) == TCL_ERROR) {
+ exc = rb_exc_new2(rb_eRuntimeError, Tcl_GetStringResult(ptr->ip));
+ /* Tcl_Release(ptr->ip); */
+ rbtk_release_ip(ptr);
+ rb_thread_critical = thr_crit_bup;
+ rb_exc_raise(exc);
+ }
+ }
+#else /* TCL_MAJOR_VERSION < 8 */
+ DUMP1("Tk_Init");
+ if (Tk_Init(ptr->ip) == TCL_ERROR) {
+ exc = rb_exc_new2(rb_eRuntimeError, ptr->ip->result);
+ /* Tcl_Release(ptr->ip); */
rbtk_release_ip(ptr);
- return exc;
+ rb_exc_raise(exc);
}
+#endif
/* Tcl_Release(ptr->ip); */
rbtk_release_ip(ptr);
rb_thread_critical = thr_crit_bup;
- /* return Qnil; */
- return interp;
-}
-
-static VALUE
-lib_restart(self)
- VALUE self;
-{
- volatile VALUE exc;
- struct tcltkip *ptr = get_ip(self);
- int thr_crit_bup;
-
- rb_secure(4);
-
- tcl_stubs_check();
-
- /* ip is deleted? */
- if (deleted_ip(ptr)) {
- rb_raise(rb_eRuntimeError, "interpreter is deleted");
- }
-
- return tk_funcall(lib_restart_core, 0, (VALUE*)NULL, self);
+ return Qnil;
}
@@ -5877,10 +4272,9 @@ ip_restart(self)
rb_secure(4);
- tcl_stubs_check();
-
/* ip is deleted? */
- if (deleted_ip(ptr)) {
+ if (Tcl_InterpDeleted(ptr->ip)) {
+ DUMP1("ip is deleted");
rb_raise(rb_eRuntimeError, "interpreter is deleted");
}
@@ -5907,25 +4301,16 @@ lib_toUTF8_core(ip_obj, src, encodename)
struct tcltkip *ptr;
char *buf;
int thr_crit_bup;
-#endif
-
- tcl_stubs_check();
-
- if (NIL_P(src)) {
- return rb_str_new2("");
- }
-#ifdef TCL_UTF_MAX
if (NIL_P(ip_obj)) {
interp = (Tcl_Interp *)NULL;
} else {
- ptr = get_ip(ip_obj);
+ interp = get_ip(ip_obj)->ip;
/* ip is deleted? */
- if (deleted_ip(ptr)) {
+ if (Tcl_InterpDeleted(interp)) {
+ DUMP1("ip is deleted");
interp = (Tcl_Interp *)NULL;
- } else {
- interp = ptr->ip;
}
}
@@ -5935,12 +4320,18 @@ lib_toUTF8_core(ip_obj, src, encodename)
if (NIL_P(encodename)) {
if (TYPE(str) == T_STRING) {
volatile VALUE enc;
- enc = rb_attr_get(str, ID_at_enc);
+
+ enc = Qnil;
+ if (RTEST(rb_ivar_defined(str, ID_at_enc))) {
+ enc = rb_ivar_get(str, ID_at_enc);
+ }
if (NIL_P(enc)) {
if (NIL_P(ip_obj)) {
encoding = (Tcl_Encoding)NULL;
} else {
- enc = rb_attr_get(ip_obj, ID_at_enc);
+ if (RTEST(rb_ivar_defined(ip_obj, ID_at_enc))) {
+ enc = rb_ivar_get(ip_obj, ID_at_enc);
+ }
if (NIL_P(enc)) {
encoding = (Tcl_Encoding)NULL;
} else {
@@ -5983,8 +4374,9 @@ lib_toUTF8_core(ip_obj, src, encodename)
rb_thread_critical = thr_crit_bup;
return str;
}
+
buf = ALLOC_N(char,(RSTRING(str)->len)+1);
- memcpy(buf, RSTRING(str)->ptr, RSTRING(str)->len);
+ strncpy(buf, RSTRING(str)->ptr, RSTRING(str)->len);
buf[RSTRING(str)->len] = 0;
Tcl_DStringInit(&dstr);
@@ -5993,8 +4385,7 @@ lib_toUTF8_core(ip_obj, src, encodename)
Tcl_ExternalToUtfDString(encoding, buf, RSTRING(str)->len, &dstr);
/* str = rb_tainted_str_new2(Tcl_DStringValue(&dstr)); */
- /* str = rb_str_new2(Tcl_DStringValue(&dstr)); */
- str = rb_str_new(Tcl_DStringValue(&dstr), Tcl_DStringLength(&dstr));
+ str = rb_str_new2(Tcl_DStringValue(&dstr));
rb_ivar_set(str, ID_at_enc, rb_tainted_str_new2("utf-8"));
if (taint_flag) OBJ_TAINT(str);
@@ -6054,19 +4445,9 @@ lib_fromUTF8_core(ip_obj, src, encodename)
int taint_flag = OBJ_TAINTED(str);
char *buf;
int thr_crit_bup;
-#endif
- tcl_stubs_check();
-
- if (NIL_P(src)) {
- return rb_str_new2("");
- }
-
-#ifdef TCL_UTF_MAX
if (NIL_P(ip_obj)) {
interp = (Tcl_Interp *)NULL;
- } else if (get_ip(ip_obj) == (struct tcltkip *)NULL) {
- interp = (Tcl_Interp *)NULL;
} else {
interp = get_ip(ip_obj)->ip;
}
@@ -6078,20 +4459,23 @@ lib_fromUTF8_core(ip_obj, src, encodename)
volatile VALUE enc;
if (TYPE(str) == T_STRING) {
- enc = rb_attr_get(str, ID_at_enc);
- if (!NIL_P(enc)) {
- StringValue(enc);
- if (strcmp(RSTRING(enc)->ptr, "binary") == 0) {
- rb_thread_critical = thr_crit_bup;
- return str;
- }
+ enc = Qnil;
+ if (RTEST(rb_ivar_defined(str, ID_at_enc))) {
+ enc = rb_ivar_get(str, ID_at_enc);
+ }
+ if (!NIL_P(enc) && strcmp(StringValuePtr(enc), "binary") == 0) {
+ rb_thread_critical = thr_crit_bup;
+ return str;
}
}
if (NIL_P(ip_obj)) {
encoding = (Tcl_Encoding)NULL;
} else {
- enc = rb_attr_get(ip_obj, ID_at_enc);
+ enc = Qnil;
+ if (RTEST(rb_ivar_defined(ip_obj, ID_at_enc))) {
+ enc = rb_ivar_get(ip_obj, ID_at_enc);
+ }
if (NIL_P(enc)) {
encoding = (Tcl_Encoding)NULL;
} else {
@@ -6142,7 +4526,7 @@ lib_fromUTF8_core(ip_obj, src, encodename)
}
buf = ALLOC_N(char,strlen(RSTRING(str)->ptr)+1);
- memcpy(buf, RSTRING(str)->ptr, RSTRING(str)->len);
+ strncpy(buf, RSTRING(str)->ptr, RSTRING(str)->len);
buf[RSTRING(str)->len] = 0;
Tcl_DStringInit(&dstr);
@@ -6151,8 +4535,7 @@ lib_fromUTF8_core(ip_obj, src, encodename)
Tcl_UtfToExternalDString(encoding,buf,RSTRING(str)->len,&dstr);
/* str = rb_tainted_str_new2(Tcl_DStringValue(&dstr)); */
- /* str = rb_str_new2(Tcl_DStringValue(&dstr)); */
- str = rb_str_new(Tcl_DStringValue(&dstr), Tcl_DStringLength(&dstr));
+ str = rb_str_new2(Tcl_DStringValue(&dstr));
rb_ivar_set(str, ID_at_enc, encodename);
if (taint_flag) OBJ_TAINT(str);
@@ -6210,8 +4593,6 @@ lib_UTF_backslash_core(self, str, all_bs)
int taint_flag = OBJ_TAINTED(str);
int thr_crit_bup;
- tcl_stubs_check();
-
StringValue(str);
if (!RSTRING(str)->len) {
return str;
@@ -6221,7 +4602,7 @@ lib_UTF_backslash_core(self, str, all_bs)
rb_thread_critical = Qtrue;
src_buf = ALLOC_N(char,(RSTRING(str)->len)+1);
- memcpy(src_buf, RSTRING(str)->ptr, RSTRING(str)->len);
+ strncpy(src_buf, RSTRING(str)->ptr, RSTRING(str)->len);
src_buf[RSTRING(str)->len] = 0;
dst_buf = ALLOC_N(char,(RSTRING(str)->len)+1);
@@ -6264,111 +4645,6 @@ lib_Tcl_backslash(self, str)
return lib_UTF_backslash_core(self, str, 1);
}
-static VALUE
-lib_get_system_encoding(self)
- VALUE self;
-{
-#if TCL_MAJOR_VERSION > 8 || (TCL_MAJOR_VERSION == 8 && TCL_MINOR_VERSION > 0)
- tcl_stubs_check();
- return rb_str_new2(Tcl_GetEncodingName((Tcl_Encoding)NULL));
-#else
- return Qnil;
-#endif
-}
-
-static VALUE
-lib_set_system_encoding(self, enc_name)
- VALUE self;
- VALUE enc_name;
-{
-#if TCL_MAJOR_VERSION > 8 || (TCL_MAJOR_VERSION == 8 && TCL_MINOR_VERSION > 0)
- tcl_stubs_check();
-
- if (NIL_P(enc_name)) {
- Tcl_SetSystemEncoding((Tcl_Interp *)NULL, (CONST char *)NULL);
- return lib_get_system_encoding(self);
- }
-
- enc_name = rb_funcall(enc_name, ID_to_s, 0, 0);
- if (Tcl_SetSystemEncoding((Tcl_Interp *)NULL,
- RSTRING(enc_name)->ptr) != TCL_OK) {
- rb_raise(rb_eArgError, "unknown encoding name '%s'",
- RSTRING(enc_name)->ptr);
- }
-
- return enc_name;
-#else
- return Qnil;
-#endif
-}
-
-
-/* invoke Tcl proc */
-struct invoke_info {
- struct tcltkip *ptr;
- Tcl_CmdInfo cmdinfo;
-#if TCL_MAJOR_VERSION >= 8
- int objc;
- Tcl_Obj **objv;
-#else
- int argc;
- char **argv;
-#endif
-};
-
-static VALUE
-invoke_tcl_proc(arg)
- VALUE arg;
-{
- struct invoke_info *inf = (struct invoke_info *)arg;
- int i, len;
-#if TCL_MAJOR_VERSION >= 8
- int argc = inf->objc;
- char **argv = (char **)NULL;
-#endif
-
- /* memory allocation for arguments of this command */
-#if TCL_MAJOR_VERSION >= 8
- if (!inf->cmdinfo.isNativeObjectProc) {
- /* string interface */
- argv = (char **)ALLOC_N(char *, argc+1);
- for (i = 0; i < argc; ++i) {
- argv[i] = Tcl_GetStringFromObj(inf->objv[i], &len);
- }
- argv[argc] = (char *)NULL;
- }
-#endif
-
- Tcl_ResetResult(inf->ptr->ip);
-
- /* Invoke the C procedure */
-#if TCL_MAJOR_VERSION >= 8
- if (inf->cmdinfo.isNativeObjectProc) {
- inf->ptr->return_value
- = (*(inf->cmdinfo.objProc))(inf->cmdinfo.objClientData,
- inf->ptr->ip, inf->objc, inf->objv);
- }
- else
-#endif
- {
-#if TCL_MAJOR_VERSION >= 8
- inf->ptr->return_value
- = (*(inf->cmdinfo.proc))(inf->cmdinfo.clientData, inf->ptr->ip,
- argc, (CONST84 char **)argv);
-
- free(argv);
-
-#else /* TCL_MAJOR_VERSION < 8 */
- inf->ptr->return_value
- = (*(inf->cmdinfo.proc))(inf->cmdinfo.clientData, inf->ptr->ip,
- inf->argc, inf->argv);
-#endif
- }
-
- return Qnil;
-}
-
-
#if TCL_MAJOR_VERSION >= 8
static VALUE
ip_invoke_core(interp, objc, objv)
@@ -6390,10 +4666,6 @@ ip_invoke_core(interp, argc, argv)
char *s;
int len;
int thr_crit_bup;
- struct invoke_info inf;
- int status;
- int unknown_flag = 0;
- VALUE ret;
#if TCL_MAJOR_VERSION >= 8
int argc = objc;
@@ -6412,67 +4684,28 @@ ip_invoke_core(interp, argc, argv)
ptr = get_ip(interp);
/* ip is deleted? */
- if (deleted_ip(ptr)) {
+ if (Tcl_InterpDeleted(ptr->ip)) {
+ DUMP1("ip is deleted");
return rb_tainted_str_new2("");
}
- /* Tcl_Preserve(ptr->ip); */
- rbtk_preserve_ip(ptr);
-
/* map from the command name to a C procedure */
DUMP2("call Tcl_GetCommandInfo, %s", cmd);
if (!Tcl_GetCommandInfo(ptr->ip, cmd, &info)) {
DUMP1("error Tcl_GetCommandInfo");
- DUMP1("try auto_load (call 'unknown' command)");
- if (!Tcl_GetCommandInfo(ptr->ip,
-#if TCL_MAJOR_VERSION >= 8
- "::unknown",
-#else
- "unknown",
-#endif
- &info)) {
- DUMP1("fail to get 'unknown' command");
- /* if (event_loop_abort_on_exc || cmd[0] != '.') { */
- if (event_loop_abort_on_exc > 0) {
- /* Tcl_Release(ptr->ip); */
- rbtk_release_ip(ptr);
- /*rb_ip_raise(obj,rb_eNameError,"invalid command name `%s'",cmd);*/
- return create_ip_exc(interp, rb_eNameError,
- "invalid command name `%s'", cmd);
+ /* if (event_loop_abort_on_exc || cmd[0] != '.') { */
+ if (event_loop_abort_on_exc > 0) {
+ /*rb_ip_raise(obj,rb_eNameError,"invalid command name `%s'",cmd);*/
+ return create_ip_exc(interp, rb_eNameError,
+ "invalid command name `%s'", cmd);
+ } else {
+ if (event_loop_abort_on_exc < 0) {
+ rb_warning("invalid command name `%s' (ignore)", cmd);
} else {
- if (event_loop_abort_on_exc < 0) {
- rb_warning("invalid command name `%s' (ignore)", cmd);
- } else {
- rb_warn("invalid command name `%s' (ignore)", cmd);
- }
- Tcl_ResetResult(ptr->ip);
- /* Tcl_Release(ptr->ip); */
- rbtk_release_ip(ptr);
- return rb_tainted_str_new2("");
+ rb_warn("invalid command name `%s' (ignore)", cmd);
}
- } else {
-#if TCL_MAJOR_VERSION >= 8
- Tcl_Obj **unknown_objv;
-#else
- char **unknown_argv;
-#endif
- DUMP1("find 'unknown' command -> set arguemnts");
- unknown_flag = 1;
-
-#if TCL_MAJOR_VERSION >= 8
- unknown_objv = (Tcl_Obj **)ALLOC_N(Tcl_Obj *, objc+2);
- unknown_objv[0] = Tcl_NewStringObj("::unknown", 9);
- Tcl_IncrRefCount(unknown_objv[0]);
- memcpy(unknown_objv + 1, objv, sizeof(Tcl_Obj *)*objc);
- unknown_objv[++objc] = (Tcl_Obj*)NULL;
- objv = unknown_objv;
-#else
- unknown_argv = (char **)ALLOC_N(char *, argc+2);
- unknown_argv[0] = strdup("unknown");
- memcpy(unknown_argv + 1, argv, sizeof(char *)*argc);
- unknown_argv[++argc] = (char *)NULL;
- argv = unknown_argv;
-#endif
+ Tcl_ResetResult(ptr->ip);
+ return rb_tainted_str_new2("");
}
}
DUMP1("end Tcl_GetCommandInfo");
@@ -6480,41 +4713,6 @@ ip_invoke_core(interp, argc, argv)
thr_crit_bup = rb_thread_critical;
rb_thread_critical = Qtrue;
-
-#if 1 /* wrap tcl-proc call */
- /* setup params */
- inf.ptr = ptr;
- inf.cmdinfo = info;
-#if TCL_MAJOR_VERSION >= 8
- inf.objc = objc;
- inf.objv = objv;
-#else
- inf.argc = argc;
- inf.argv = argv;
-#endif
-
- /* invoke tcl-proc */
- ret = rb_protect(invoke_tcl_proc, (VALUE)&inf, &status);
- switch(status) {
- case TAG_RAISE:
- if (NIL_P(ruby_errinfo)) {
- rbtk_pending_exception = rb_exc_new2(rb_eException,
- "unknown exception");
- } else {
- rbtk_pending_exception = ruby_errinfo;
- }
- break;
-
- case TAG_FATAL:
- if (NIL_P(ruby_errinfo)) {
- rbtk_pending_exception = rb_exc_new2(rb_eFatal, "FATAL");
- } else {
- rbtk_pending_exception = ruby_errinfo;
- }
- }
-
-#else /* !wrap tcl-proc call */
-
/* memory allocation for arguments of this command */
#if TCL_MAJOR_VERSION >= 8
if (!info.isNativeObjectProc) {
@@ -6555,36 +4753,32 @@ ip_invoke_core(interp, argc, argv)
argc, argv);
#endif
}
-#endif /* ! wrap tcl-proc call */
-
- /* free allocated memory for calling 'unknown' command */
- if (unknown_flag) {
-#if TCL_MAJOR_VERSION >= 8
- Tcl_DecrRefCount(objv[0]);
- free(objv);
-#else
- free(argv[0]);
- free(argv);
-#endif
- }
-
- /* exception on mainloop */
- if (pending_exception_check1(thr_crit_bup, ptr)) {
- return rbtk_pending_exception;
- }
rb_thread_critical = thr_crit_bup;
+ /* exception on mainloop */
if (ptr->return_value == TCL_ERROR) {
if (event_loop_abort_on_exc > 0 && !Tcl_InterpDeleted(ptr->ip)) {
-
+#if TCL_MAJOR_VERSION >= 8
return create_ip_exc(interp, rb_eRuntimeError,
"%s", Tcl_GetStringResult(ptr->ip));
+#else /* TCL_MAJOR_VERSION < 8 */
+ return create_ip_exc(interp, rb_eRuntimeError,
+ "%s", ptr->ip->result);
+#endif
} else {
if (event_loop_abort_on_exc < 0) {
+#if TCL_MAJOR_VERSION >= 8
rb_warning("%s (ignore)", Tcl_GetStringResult(ptr->ip));
+#else /* TCL_MAJOR_VERSION < 8 */
+ rb_warning("%s (ignore)", ptr->ip->result);
+#endif
} else {
+#if TCL_MAJOR_VERSION >= 8
rb_warn("%s (ignore)", Tcl_GetStringResult(ptr->ip));
+#else /* TCL_MAJOR_VERSION < 8 */
+ rb_warn("%s (ignore)", ptr->ip->result);
+#endif
}
Tcl_ResetResult(ptr->ip);
return rb_tainted_str_new2("");
@@ -6606,12 +4800,15 @@ alloc_invoke_arguments(argc, argv)
VALUE *argv;
{
int i;
+ VALUE v;
+ char *s;
int thr_crit_bup;
#if TCL_MAJOR_VERSION >= 8
- Tcl_Obj **av;
+ Tcl_Obj **av = (Tcl_Obj **)NULL;
+ Tcl_Obj *resultPtr;
#else /* TCL_MAJOR_VERSION < 8 */
- char **av;
+ char **av = (char **)NULL;
#endif
thr_crit_bup = rb_thread_critical;
@@ -6619,20 +4816,45 @@ alloc_invoke_arguments(argc, argv)
/* memory allocation */
#if TCL_MAJOR_VERSION >= 8
- av = ALLOC_N(Tcl_Obj *, argc+1);
+ av = (Tcl_Obj **)ALLOC_N(Tcl_Obj *, argc+1);
for (i = 0; i < argc; ++i) {
- av[i] = get_obj_from_str(argv[i]);
+ VALUE enc;
+
+ v = argv[i];
+ s = StringValuePtr(v);
+
+# if TCL_MAJOR_VERSION == 8 && TCL_MINOR_VERSION == 0
+ av[i] = Tcl_NewStringObj(s, RSTRING(v)->len);
+# else /* TCL_VERSION >= 8.1 */
+ enc = Qnil;
+ if (RTEST(rb_ivar_defined(v, ID_at_enc))) {
+ enc = rb_ivar_get(v, ID_at_enc);
+ }
+ if (!NIL_P(enc) && strcmp(StringValuePtr(enc), "binary") == 0) {
+ /* binary string */
+ av[i] = Tcl_NewByteArrayObj(s, RSTRING(v)->len);
+ } else if (strlen(s) != RSTRING(v)->len) {
+ /* probably binary string */
+ av[i] = Tcl_NewByteArrayObj(s, RSTRING(v)->len);
+ } else {
+ /* probably text string */
+ av[i] = Tcl_NewStringObj(s, RSTRING(v)->len);
+ }
+# endif
Tcl_IncrRefCount(av[i]);
}
- av[argc] = NULL;
+ av[argc] = (Tcl_Obj *)NULL;
#else /* TCL_MAJOR_VERSION < 8 */
/* string interface */
- av = ALLOC_N(char *, argc+1);
+ av = (char **)ALLOC_N(char *, argc+1);
for (i = 0; i < argc; ++i) {
- av[i] = strdup(StringValuePtr(argv[i]));
+ v = argv[i];
+ s = StringValuePtr(v);
+ av[i] = ALLOC_N(char, strlen(s)+1);
+ strcpy(av[i], s);
}
- av[argc] = NULL;
+ av[argc] = (char *)NULL;
#endif
rb_thread_critical = thr_crit_bup;
@@ -6669,26 +4891,33 @@ ip_invoke_real(argc, argv, interp)
{
VALUE v;
struct tcltkip *ptr; /* tcltkip data struct */
+ int i;
+ Tcl_CmdInfo info;
+ char *s;
+ int len;
+ int thr_crit_bup;
#if TCL_MAJOR_VERSION >= 8
Tcl_Obj **av = (Tcl_Obj **)NULL;
+ Tcl_Obj *resultPtr;
#else /* TCL_MAJOR_VERSION < 8 */
char **av = (char **)NULL;
#endif
DUMP2("invoke_real called by thread:%lx", rb_thread_current());
+ /* allocate memory for arguments */
+ av = alloc_invoke_arguments(argc, argv);
+
/* get the data struct */
ptr = get_ip(interp);
/* ip is deleted? */
- if (deleted_ip(ptr)) {
+ if (Tcl_InterpDeleted(ptr->ip)) {
+ DUMP1("ip is deleted");
return rb_tainted_str_new2("");
}
- /* allocate memory for arguments */
- av = alloc_invoke_arguments(argc, argv);
-
/* Invoke the C procedure */
Tcl_ResetResult(ptr->ip);
v = ip_invoke_core(interp, argc, av);
@@ -6792,11 +5021,11 @@ ip_invoke_with_position(argc, argv, obj, position)
if (argc < 1) {
rb_raise(rb_eArgError, "command name missing");
}
- if (NIL_P(eventloop_thread) || current == eventloop_thread) {
- if (NIL_P(eventloop_thread)) {
- DUMP2("invoke from thread:%lx but no eventloop", current);
- } else {
+ if (eventloop_thread == 0 || current == eventloop_thread) {
+ if (eventloop_thread) {
DUMP2("invoke from current eventloop %lx", current);
+ } else {
+ DUMP2("invoke from thread:%lx but no eventloop", current);
}
result = ip_invoke_real(argc, argv, ip_obj);
if (rb_obj_is_kind_of(result, rb_eException)) {
@@ -6880,7 +5109,8 @@ ip_retval(self)
ptr = get_ip(self);
/* ip is deleted? */
- if (deleted_ip(ptr)) {
+ if (Tcl_InterpDeleted(ptr->ip)) {
+ DUMP1("ip is deleted");
return rb_tainted_str_new2("");
}
@@ -6905,89 +5135,122 @@ ip_invoke_immediate(argc, argv, obj)
return ip_invoke_with_position(argc, argv, obj, TCL_QUEUE_HEAD);
}
-
/* access Tcl variables */
static VALUE
-ip_get_variable2_core(interp, argc, argv)
- VALUE interp;
- int argc;
- VALUE *argv;
+ip_get_variable(self, varname_arg, flag_arg)
+ VALUE self;
+ VALUE varname_arg;
+ VALUE flag_arg;
{
- struct tcltkip *ptr = get_ip(interp);
+ struct tcltkip *ptr = get_ip(self);
int thr_crit_bup;
- volatile VALUE varname, index, flag;
+ volatile VALUE varname, flag;
- varname = argv[0];
- index = argv[1];
- flag = argv[2];
+ varname = varname_arg;
+ flag = flag_arg;
- /*
StringValue(varname);
- if (!NIL_P(index)) StringValue(index);
- */
#if TCL_MAJOR_VERSION >= 8
{
- Tcl_Obj *ret;
+ Tcl_Obj *nameobj, *ret;
+ char *s;
+ int len;
volatile VALUE strval;
thr_crit_bup = rb_thread_critical;
rb_thread_critical = Qtrue;
+ nameobj = Tcl_NewStringObj(RSTRING(varname)->ptr,
+ RSTRING(varname)->len);
+ Tcl_IncrRefCount(nameobj);
+
/* ip is deleted? */
- if (deleted_ip(ptr)) {
+ if (Tcl_InterpDeleted(ptr->ip)) {
+ DUMP1("ip is deleted");
+ Tcl_DecrRefCount(nameobj);
rb_thread_critical = thr_crit_bup;
return rb_tainted_str_new2("");
} else {
/* Tcl_Preserve(ptr->ip); */
rbtk_preserve_ip(ptr);
- ret = Tcl_GetVar2Ex(ptr->ip, RSTRING(varname)->ptr,
- NIL_P(index) ? NULL : RSTRING(index)->ptr,
- FIX2INT(flag));
+ ret = Tcl_ObjGetVar2(ptr->ip, nameobj, (Tcl_Obj*)NULL,
+ FIX2INT(flag));
}
+ Tcl_DecrRefCount(nameobj);
+
if (ret == (Tcl_Obj*)NULL) {
volatile VALUE exc;
+#if TCL_MAJOR_VERSION >= 8
exc = rb_exc_new2(rb_eRuntimeError, Tcl_GetStringResult(ptr->ip));
+#else /* TCL_MAJOR_VERSION < 8 */
+ exc = rb_exc_new2(rb_eRuntimeError, ptr->ip->result);
+#endif
/* Tcl_Release(ptr->ip); */
rbtk_release_ip(ptr);
rb_thread_critical = thr_crit_bup;
- return exc;
+ rb_exc_raise(exc);
}
Tcl_IncrRefCount(ret);
- strval = get_str_from_obj(ret);
- OBJ_TAINT(strval);
+
+# if TCL_MAJOR_VERSION == 8 && TCL_MINOR_VERSION == 0
+ s = Tcl_GetStringFromObj(ret, &len);
+ strval = rb_tainted_str_new(s, len);
Tcl_DecrRefCount(ret);
+ /* Tcl_Release(ptr->ip); */
+ rbtk_release_ip(ptr);
+ rb_thread_critical = thr_crit_bup;
+ return(strval);
+# else /* TCL_VERSION >= 8.1 */
+ if (Tcl_GetCharLength(ret)
+ != Tcl_UniCharLen(Tcl_GetUnicode(ret))) {
+ /* possibly binary string */
+ s = Tcl_GetByteArrayFromObj(ret, &len);
+ strval = rb_tainted_str_new(s, len);
+ rb_ivar_set(strval, ID_at_enc, rb_tainted_str_new2("binary"));
+ } else {
+ /* possibly text string */
+ s = Tcl_GetStringFromObj(ret, &len);
+ strval = rb_tainted_str_new(s, len);
+ }
+
+ Tcl_DecrRefCount(ret);
/* Tcl_Release(ptr->ip); */
rbtk_release_ip(ptr);
rb_thread_critical = thr_crit_bup;
+
return(strval);
+# endif
}
#else /* TCL_MAJOR_VERSION < 8 */
{
char *ret;
- volatile VALUE strval;
/* ip is deleted? */
- if (deleted_ip(ptr)) {
+ if (Tcl_InterpDeleted(ptr->ip)) {
+ DUMP1("ip is deleted");
return rb_tainted_str_new2("");
} else {
/* Tcl_Preserve(ptr->ip); */
rbtk_preserve_ip(ptr);
ret = Tcl_GetVar2(ptr->ip, RSTRING(varname)->ptr,
- NIL_P(index) ? NULL : RSTRING(index)->ptr,
- FIX2INT(flag));
+ (char*)NULL, FIX2INT(flag));
}
if (ret == (char*)NULL) {
volatile VALUE exc;
+#if TCL_MAJOR_VERSION >= 8
exc = rb_exc_new2(rb_eRuntimeError, Tcl_GetStringResult(ptr->ip));
+#else /* TCL_MAJOR_VERSION < 8 */
+ exc = rb_exc_new2(rb_eRuntimeError, ptr->ip->result);
+#endif
/* Tcl_Release(ptr->ip); */
rbtk_release_ip(ptr);
rb_thread_critical = thr_crit_bup;
- return exc;
+ rb_exc_raise(exc);
}
strval = rb_tainted_str_new2(ret);
@@ -7001,99 +5264,260 @@ ip_get_variable2_core(interp, argc, argv)
}
static VALUE
-ip_get_variable2(self, varname, index, flag)
+ip_get_variable2(self, varname_arg, index_arg, flag_arg)
VALUE self;
- VALUE varname;
- VALUE index;
- VALUE flag;
+ VALUE varname_arg;
+ VALUE index_arg;
+ VALUE flag_arg;
{
- VALUE argv[3];
- VALUE retval;
+ struct tcltkip *ptr = get_ip(self);
+ int thr_crit_bup;
+ volatile VALUE varname, index, flag;
+
+ if (NIL_P(index_arg)) {
+ return ip_get_variable(self, varname_arg, flag_arg);
+ }
+
+ varname = varname_arg;
+ index = index_arg;
+ flag = flag_arg;
StringValue(varname);
- if (!NIL_P(index)) StringValue(index);
+ StringValue(index);
- argv[0] = varname;
- argv[1] = index;
- argv[2] = flag;
+#if TCL_MAJOR_VERSION >= 8
+ {
+ Tcl_Obj *nameobj, *idxobj, *ret;
+ char *s;
+ int len;
+ volatile VALUE strval;
- retval = tk_funcall(ip_get_variable2_core, 3, argv, self);
+ thr_crit_bup = rb_thread_critical;
+ rb_thread_critical = Qtrue;
- if (NIL_P(retval)) {
- return rb_tainted_str_new2("");
- } else {
- return retval;
+ nameobj = Tcl_NewStringObj(RSTRING(varname)->ptr,
+ RSTRING(varname)->len);
+ Tcl_IncrRefCount(nameobj);
+ idxobj = Tcl_NewStringObj(RSTRING(index)->ptr, RSTRING(index)->len);
+ Tcl_IncrRefCount(idxobj);
+
+ /* ip is deleted? */
+ if (Tcl_InterpDeleted(ptr->ip)) {
+ DUMP1("ip is deleted");
+ Tcl_DecrRefCount(nameobj);
+ Tcl_DecrRefCount(idxobj);
+ rb_thread_critical = thr_crit_bup;
+ return rb_tainted_str_new2("");
+ } else {
+ /* Tcl_Preserve(ptr->ip); */
+ rbtk_preserve_ip(ptr);
+ ret = Tcl_ObjGetVar2(ptr->ip, nameobj, idxobj, FIX2INT(flag));
+ }
+
+ Tcl_DecrRefCount(nameobj);
+ Tcl_DecrRefCount(idxobj);
+
+ if (ret == (Tcl_Obj*)NULL) {
+ volatile VALUE exc;
+#if TCL_MAJOR_VERSION >= 8
+ exc = rb_exc_new2(rb_eRuntimeError, Tcl_GetStringResult(ptr->ip));
+#else /* TCL_MAJOR_VERSION < 8 */
+ exc = rb_exc_new2(rb_eRuntimeError, ptr->ip->result);
+#endif
+ /* Tcl_Release(ptr->ip); */
+ rbtk_release_ip(ptr);
+ rb_thread_critical = thr_crit_bup;
+ rb_exc_raise(exc);
+ }
+
+ Tcl_IncrRefCount(ret);
+
+# if TCL_MAJOR_VERSION == 8 && TCL_MINOR_VERSION == 0
+ s = Tcl_GetStringFromObj(ret, &len);
+ strval = rb_tainted_str_new(s, len);
+ Tcl_DecrRefCount(ret);
+ /* Tcl_Release(ptr->ip); */
+ rbtk_release_ip(ptr);
+ rb_thread_critical = thr_crit_bup;
+ return(strval);
+
+# else /* TCL_VERSION >= 8.1 */
+ if (Tcl_GetCharLength(ret)
+ != Tcl_UniCharLen(Tcl_GetUnicode(ret))) {
+ /* possibly binary string */
+ s = Tcl_GetByteArrayFromObj(ret, &len);
+ strval = rb_tainted_str_new(s, len);
+ rb_ivar_set(strval, ID_at_enc, rb_tainted_str_new2("binary"));
+ } else {
+ /* possibly text string */
+ s = Tcl_GetStringFromObj(ret, &len);
+ strval = rb_tainted_str_new(s, len);
+ }
+
+ Tcl_DecrRefCount(ret);
+ /* Tcl_Release(ptr->ip); */
+ rbtk_release_ip(ptr);
+ rb_thread_critical = thr_crit_bup;
+
+ return(strval);
+# endif
}
-}
+#else /* TCL_MAJOR_VERSION < 8 */
+ {
+ char *ret;
-static VALUE
-ip_get_variable(self, varname, flag)
- VALUE self;
- VALUE varname;
- VALUE flag;
-{
- return ip_get_variable2(self, varname, Qnil, flag);
+ /* ip is deleted? */
+ if (Tcl_InterpDeleted(ptr->ip)) {
+ DUMP1("ip is deleted");
+ return rb_tainted_str_new2("");
+ } else {
+ /* Tcl_Preserve(ptr->ip); */
+ rbtk_preserve_ip(ptr);
+ ret = Tcl_GetVar2(ptr->ip, RSTRING(varname)->ptr,
+ RSTRING(index)->ptr, FIX2INT(flag));
+ }
+
+ if (ret == (char*)NULL) {
+ volatile VALUE exc;
+#if TCL_MAJOR_VERSION >= 8
+ exc = rb_exc_new2(rb_eRuntimeError, Tcl_GetStringResult(ptr->ip));
+#else /* TCL_MAJOR_VERSION < 8 */
+ exc = rb_exc_new2(rb_eRuntimeError, ptr->ip->result);
+#endif
+ /* Tcl_Release(ptr->ip); */
+ rbtk_release_ip(ptr);
+ rb_thread_critical = thr_crit_bup;
+ rb_exc_raise(exc);
+ }
+
+ strval = rb_tainted_str_new2(ret);
+ /* Tcl_Release(ptr->ip); */
+ rbtk_release_ip(ptr);
+ rb_thread_critical = thr_crit_bup;
+
+ return(strval);
+ }
+#endif
}
static VALUE
-ip_set_variable2_core(interp, argc, argv)
- VALUE interp;
- int argc;
- VALUE *argv;
+ip_set_variable(self, varname_arg, value_arg, flag_arg)
+ VALUE self;
+ VALUE varname_arg;
+ VALUE value_arg;
+ VALUE flag_arg;
{
- struct tcltkip *ptr = get_ip(interp);
+ struct tcltkip *ptr = get_ip(self);
int thr_crit_bup;
- volatile VALUE varname, index, value, flag;
-
- varname = argv[0];
- index = argv[1];
- value = argv[2];
- flag = argv[3];
+ volatile VALUE varname, value, flag;
- /*
+ varname = varname_arg;
+ value = value_arg;
+ flag = flag_arg;
+
StringValue(varname);
- if (!NIL_P(index)) StringValue(index);
StringValue(value);
- */
#if TCL_MAJOR_VERSION >= 8
{
- Tcl_Obj *valobj, *ret;
+ Tcl_Obj *nameobj, *valobj, *ret;
+ char *s;
+ int len;
volatile VALUE strval;
thr_crit_bup = rb_thread_critical;
rb_thread_critical = Qtrue;
- valobj = get_obj_from_str(value);
+ nameobj = Tcl_NewStringObj(RSTRING(varname)->ptr,
+ RSTRING(varname)->len);
+
+ Tcl_IncrRefCount(nameobj);
+
+# if TCL_MAJOR_VERSION == 8 && TCL_MINOR_VERSION == 0
+ valobj = Tcl_NewStringObj(RSTRING(value)->ptr,
+ RSTRING(value)->len);
Tcl_IncrRefCount(valobj);
+# else /* TCL_VERSION >= 8.1 */
+ {
+ volatile VALUE enc = Qnil;
+
+ if (RTEST(rb_ivar_defined(value, ID_at_enc))) {
+ enc = rb_ivar_get(value, ID_at_enc);
+ }
+
+ if (!NIL_P(enc) && strcmp(StringValuePtr(enc), "binary") == 0) {
+ /* binary string */
+ valobj = Tcl_NewByteArrayObj(RSTRING(value)->ptr,
+ RSTRING(value)->len);
+ } else if (strlen(RSTRING(value)->ptr) != RSTRING(value)->len) {
+ /* probably binary string */
+ valobj = Tcl_NewByteArrayObj(RSTRING(value)->ptr,
+ RSTRING(value)->len);
+ } else {
+ /* probably text string */
+ valobj = Tcl_NewStringObj(RSTRING(value)->ptr,
+ RSTRING(value)->len);
+ }
+
+ Tcl_IncrRefCount(valobj);
+ }
+# endif
/* ip is deleted? */
- if (deleted_ip(ptr)) {
+ if (Tcl_InterpDeleted(ptr->ip)) {
+ DUMP1("ip is deleted");
+ Tcl_DecrRefCount(nameobj);
Tcl_DecrRefCount(valobj);
rb_thread_critical = thr_crit_bup;
return rb_tainted_str_new2("");
} else {
/* Tcl_Preserve(ptr->ip); */
rbtk_preserve_ip(ptr);
- ret = Tcl_SetVar2Ex(ptr->ip, RSTRING(varname)->ptr,
- NIL_P(index) ? NULL : RSTRING(index)->ptr,
- valobj, FIX2INT(flag));
+ ret = Tcl_ObjSetVar2(ptr->ip, nameobj, (Tcl_Obj*)NULL, valobj,
+ FIX2INT(flag));
}
+ Tcl_DecrRefCount(nameobj);
Tcl_DecrRefCount(valobj);
if (ret == (Tcl_Obj*)NULL) {
volatile VALUE exc;
+#if TCL_MAJOR_VERSION >= 8
exc = rb_exc_new2(rb_eRuntimeError, Tcl_GetStringResult(ptr->ip));
+#else /* TCL_MAJOR_VERSION < 8 */
+ exc = rb_exc_new2(rb_eRuntimeError, ptr->ip->result);
+#endif
/* Tcl_Release(ptr->ip); */
rbtk_release_ip(ptr);
rb_thread_critical = thr_crit_bup;
- return exc;
+ rb_exc_raise(exc);
}
Tcl_IncrRefCount(ret);
- strval = get_str_from_obj(ret);
- OBJ_TAINT(strval);
+
+# if TCL_MAJOR_VERSION == 8 && TCL_MINOR_VERSION == 0
+ s = Tcl_GetStringFromObj(ret, &len);
+ strval = rb_tainted_str_new(s, len);
+# else /* TCL_VERSION >= 8.1 */
+ {
+ VALUE old_gc;
+
+ old_gc = rb_gc_disable();
+
+ if (Tcl_GetCharLength(ret) != Tcl_UniCharLen(Tcl_GetUnicode(ret))) {
+ /* possibly binary string */
+ s = Tcl_GetByteArrayFromObj(ret, &len);
+ strval = rb_tainted_str_new(s, len);
+ rb_ivar_set(strval, ID_at_enc, rb_str_new2("binary"));
+ } else {
+ /* possibly text string */
+ s = Tcl_GetStringFromObj(ret, &len);
+ strval = rb_tainted_str_new(s, len);
+ }
+ if (old_gc == Qfalse) rb_gc_enable();
+ }
+# endif
+
Tcl_DecrRefCount(ret);
/* Tcl_Release(ptr->ip); */
@@ -7105,25 +5529,23 @@ ip_set_variable2_core(interp, argc, argv)
#else /* TCL_MAJOR_VERSION < 8 */
{
CONST char *ret;
- volatile VALUE strval;
/* ip is deleted? */
- if (deleted_ip(ptr)) {
+ if (Tcl_InterpDeleted(ptr->ip)) {
+ DUMP1("ip is deleted");
return rb_tainted_str_new2("");
} else {
/* Tcl_Preserve(ptr->ip); */
rbtk_preserve_ip(ptr);
- ret = Tcl_SetVar2(ptr->ip, RSTRING(varname)->ptr,
- NIL_P(index) ? NULL : RSTRING(index)->ptr,
- RSTRING(value)->ptr, FIX2INT(flag));
+ ret = Tcl_SetVar2(ptr->ip, RSTRING(varname)->ptr, (char*)NULL,
+ RSTRING(value)->ptr, (int)FIX2INT(flag));
}
- if (ret == (char*)NULL) {
- return rb_exc_new2(rb_eRuntimeError, ptr->ip->result);
+ if (ret == NULL) {
+ rb_raise(rb_eRuntimeError, "%s", ptr->ip->result);
}
strval = rb_tainted_str_new2(ret);
-
/* Tcl_Release(ptr->ip); */
rbtk_release_ip(ptr);
rb_thread_critical = thr_crit_bup;
@@ -7134,74 +5556,197 @@ ip_set_variable2_core(interp, argc, argv)
}
static VALUE
-ip_set_variable2(self, varname, index, value, flag)
+ip_set_variable2(self, varname_arg, index_arg, value_arg, flag_arg)
VALUE self;
- VALUE varname;
- VALUE index;
- VALUE value;
- VALUE flag;
+ VALUE varname_arg;
+ VALUE index_arg;
+ VALUE value_arg;
+ VALUE flag_arg;
{
- VALUE argv[4];
- VALUE retval;
+ struct tcltkip *ptr = get_ip(self);
+ int thr_crit_bup;
+ volatile VALUE varname, index, value, flag;
+
+ if (NIL_P(index_arg)) {
+ return ip_set_variable(self, varname_arg, value_arg, flag_arg);
+ }
+
+ varname = varname_arg;
+ index = index_arg;
+ value = value_arg;
+ flag = flag_arg;
StringValue(varname);
- if (!NIL_P(index)) StringValue(index);
+ StringValue(index);
StringValue(value);
- argv[0] = varname;
- argv[1] = index;
- argv[2] = value;
- argv[3] = flag;
+#if TCL_MAJOR_VERSION >= 8
+ {
+ Tcl_Obj *nameobj, *idxobj, *valobj, *ret;
+ char *s;
+ int len;
+ volatile VALUE strval;
+
+ thr_crit_bup = rb_thread_critical;
+ rb_thread_critical = Qtrue;
- retval = tk_funcall(ip_set_variable2_core, 4, argv, self);
+ nameobj = Tcl_NewStringObj(RSTRING(varname)->ptr,
+ RSTRING(varname)->len);
+ Tcl_IncrRefCount(nameobj);
- if (NIL_P(retval)) {
- return rb_tainted_str_new2("");
- } else {
- return retval;
+ idxobj = Tcl_NewStringObj(RSTRING(index)->ptr,
+ RSTRING(index)->len);
+ Tcl_IncrRefCount(idxobj);
+
+# if TCL_MAJOR_VERSION == 8 && TCL_MINOR_VERSION == 0
+ valobj = Tcl_NewStringObj(RSTRING(value)->ptr,
+ RSTRING(value)->len);
+# else /* TCL_VERSION >= 8.1 */
+ {
+ VALUE enc = Qnil;
+
+ if (RTEST(rb_ivar_defined(value, ID_at_enc))) {
+ enc = rb_ivar_get(value, ID_at_enc);
+ }
+
+ if (!NIL_P(enc) && strcmp(StringValuePtr(enc), "binary") == 0) {
+ /* binary string */
+ valobj = Tcl_NewByteArrayObj(RSTRING(value)->ptr,
+ RSTRING(value)->len);
+ } else if (strlen(RSTRING(value)->ptr) != RSTRING(value)->len) {
+ /* probably binary string */
+ valobj = Tcl_NewByteArrayObj(RSTRING(value)->ptr,
+ RSTRING(value)->len);
+ } else {
+ /* probably text string */
+ valobj = Tcl_NewStringObj(RSTRING(value)->ptr,
+ RSTRING(value)->len);
+ }
+ }
+
+# endif
+ Tcl_IncrRefCount(valobj);
+
+ /* ip is deleted? */
+ if (Tcl_InterpDeleted(ptr->ip)) {
+ DUMP1("ip is deleted");
+ Tcl_DecrRefCount(nameobj);
+ Tcl_DecrRefCount(idxobj);
+ Tcl_DecrRefCount(valobj);
+ rb_thread_critical = thr_crit_bup;
+ return rb_tainted_str_new2("");
+ } else {
+ /* Tcl_Preserve(ptr->ip); */
+ rbtk_preserve_ip(ptr);
+ ret = Tcl_ObjSetVar2(ptr->ip, nameobj, idxobj, valobj,
+ FIX2INT(flag));
+ }
+
+ Tcl_DecrRefCount(nameobj);
+ Tcl_DecrRefCount(idxobj);
+ Tcl_DecrRefCount(valobj);
+
+ if (ret == (Tcl_Obj*)NULL) {
+ volatile VALUE exc;
+#if TCL_MAJOR_VERSION >= 8
+ exc = rb_exc_new2(rb_eRuntimeError, Tcl_GetStringResult(ptr->ip));
+#else /* TCL_MAJOR_VERSION < 8 */
+ exc = rb_exc_new2(rb_eRuntimeError, ptr->ip->result);
+#endif
+ /* Tcl_Release(ptr->ip); */
+ rbtk_release_ip(ptr);
+ rb_thread_critical = thr_crit_bup;
+ rb_exc_raise(exc);
+ }
+
+ Tcl_IncrRefCount(ret);
+
+# if TCL_MAJOR_VERSION == 8 && TCL_MINOR_VERSION == 0
+ s = Tcl_GetStringFromObj(ret, &len);
+ strval = rb_tainted_str_new(s, len);
+# else /* TCL_VERSION >= 8.1 */
+ if (Tcl_GetCharLength(ret) != Tcl_UniCharLen(Tcl_GetUnicode(ret))) {
+ /* possibly binary string */
+ s = Tcl_GetByteArrayFromObj(ret, &len);
+ strval = rb_tainted_str_new(s, len);
+ rb_ivar_set(strval, ID_at_enc, rb_str_new2("binary"));
+ } else {
+ /* possibly text string */
+ s = Tcl_GetStringFromObj(ret, &len);
+ strval = rb_tainted_str_new(s, len);
+ }
+# endif
+
+ Tcl_DecrRefCount(ret);
+ /* Tcl_Release(ptr->ip); */
+ rbtk_release_ip(ptr);
+ rb_thread_critical = thr_crit_bup;
+
+ return(strval);
}
-}
+#else /* TCL_MAJOR_VERSION < 8 */
+ {
+ CONST char *ret;
-static VALUE
-ip_set_variable(self, varname, value, flag)
- VALUE self;
- VALUE varname;
- VALUE value;
- VALUE flag;
-{
- return ip_set_variable2(self, varname, Qnil, value, flag);
+ /* ip is deleted? */
+ if (Tcl_InterpDeleted(ptr->ip)) {
+ DUMP1("ip is deleted");
+ return rb_tainted_str_new2("");
+ } else {
+ /* Tcl_Preserve(ptr->ip); */
+ rbtk_preserve_ip(ptr);
+ ret = Tcl_SetVar2(ptr->ip, RSTRING(varname)->ptr,
+ RSTRING(index)->ptr,
+ RSTRING(value)->ptr, FIX2INT(flag));
+ }
+
+ if (ret == (char*)NULL) {
+ rb_raise(rb_eRuntimeError, "%s", ptr->ip->result);
+ }
+
+ Tcl_IncrRefCount(ret);
+
+ strval = rb_tainted_str_new2(ret);
+
+ Tcl_DecrRefCount(ret);
+ /* Tcl_Release(ptr->ip); */
+ rbtk_release_ip(ptr);
+ rb_thread_critical = thr_crit_bup;
+
+ return(strval);
+ }
+#endif
}
static VALUE
-ip_unset_variable2_core(interp, argc, argv)
- VALUE interp;
- int argc;
- VALUE *argv;
+ip_unset_variable(self, varname_arg, flag_arg)
+ VALUE self;
+ VALUE varname_arg;
+ VALUE flag_arg;
{
- struct tcltkip *ptr = get_ip(interp);
- volatile VALUE varname, index, flag;
+ struct tcltkip *ptr = get_ip(self);
+ volatile VALUE varname, value, flag;
- varname = argv[0];
- index = argv[1];
- flag = argv[2];
+ varname = varname_arg;
+ flag = flag_arg;
- /*
StringValue(varname);
- if (!NIL_P(index)) StringValue(index);
- */
/* ip is deleted? */
- if (deleted_ip(ptr)) {
+ if (Tcl_InterpDeleted(ptr->ip)) {
+ DUMP1("ip is deleted");
return Qtrue;
}
- ptr->return_value = Tcl_UnsetVar2(ptr->ip, RSTRING(varname)->ptr,
- NIL_P(index) ? NULL : RSTRING(index)->ptr,
- FIX2INT(flag));
-
+ ptr->return_value = Tcl_UnsetVar(ptr->ip, RSTRING(varname)->ptr,
+ FIX2INT(flag));
if (ptr->return_value == TCL_ERROR) {
if (FIX2INT(flag) & TCL_LEAVE_ERR_MSG) {
- return rb_exc_new2(rb_eRuntimeError, Tcl_GetStringResult(ptr->ip));
+#if TCL_MAJOR_VERSION >= 8
+ rb_raise(rb_eRuntimeError, "%s", Tcl_GetStringResult(ptr->ip));
+#else /* TCL_MAJOR_VERSION < 8 */
+ rb_raise(rb_eRuntimeError, "%s", ptr->ip->result);
+#endif
}
return Qfalse;
}
@@ -7209,38 +5754,45 @@ ip_unset_variable2_core(interp, argc, argv)
}
static VALUE
-ip_unset_variable2(self, varname, index, flag)
+ip_unset_variable2(self, varname_arg, index_arg, flag_arg)
VALUE self;
- VALUE varname;
- VALUE index;
- VALUE flag;
+ VALUE varname_arg;
+ VALUE index_arg;
+ VALUE flag_arg;
{
- VALUE argv[3];
- VALUE retval;
+ struct tcltkip *ptr = get_ip(self);
+ volatile VALUE varname, index, value, flag;
- StringValue(varname);
- if (!NIL_P(index)) StringValue(index);
+ if (NIL_P(index_arg)) {
+ return ip_unset_variable(self, varname_arg, flag_arg);
+ }
- argv[0] = varname;
- argv[1] = index;
- argv[2] = flag;
+ varname = varname_arg;
+ index = index_arg;
+ flag = flag_arg;
- retval = tk_funcall(ip_unset_variable2_core, 3, argv, self);
+ StringValue(varname);
+ StringValue(index);
- if (NIL_P(retval)) {
- return rb_tainted_str_new2("");
- } else {
- return retval;
+ /* ip is deleted? */
+ if (Tcl_InterpDeleted(ptr->ip)) {
+ DUMP1("ip is deleted");
+ return Qtrue;
}
-}
-static VALUE
-ip_unset_variable(self, varname, flag)
- VALUE self;
- VALUE varname;
- VALUE flag;
-{
- return ip_unset_variable2(self, varname, Qnil, flag);
+ ptr->return_value = Tcl_UnsetVar2(ptr->ip, RSTRING(varname)->ptr,
+ RSTRING(index)->ptr, FIX2INT(flag));
+ if (ptr->return_value == TCL_ERROR) {
+ if (FIX2INT(flag) & TCL_LEAVE_ERR_MSG) {
+#if TCL_MAJOR_VERSION >= 8
+ rb_raise(rb_eRuntimeError, "%s", Tcl_GetStringResult(ptr->ip));
+#else /* TCL_MAJOR_VERSION < 8 */
+ rb_raise(rb_eRuntimeError, "%s", ptr->ip->result);
+#endif
+ }
+ return Qfalse;
+ }
+ return Qtrue;
}
static VALUE
@@ -7316,12 +5868,8 @@ lib_split_tklist_core(ip_obj, list_str)
int result;
VALUE old_gc;
- tcl_stubs_check();
-
if (NIL_P(ip_obj)) {
interp = (Tcl_Interp *)NULL;
- } else if (get_ip(ip_obj) == (struct tcltkip *)NULL) {
- interp = (Tcl_Interp *)NULL;
} else {
interp = get_ip(ip_obj)->ip;
}
@@ -7336,7 +5884,43 @@ lib_split_tklist_core(ip_obj, list_str)
Tcl_Obj **objv;
int thr_crit_bup;
- listobj = get_obj_from_str(list_str);
+# if 1
+# if TCL_MAJOR_VERSION == 8 && TCL_MINOR_VERSION == 0
+ listobj = Tcl_NewStringObj(RSTRING(list_str)->ptr,
+ RSTRING(list_str)->len);
+# else /* TCL_VERSION >= 8.1 */
+ thr_crit_bup = rb_thread_critical;
+ rb_thread_critical = Qtrue;
+
+ {
+ VALUE enc = Qnil;
+
+ if (RTEST(rb_ivar_defined(list_str, ID_at_enc))) {
+ enc = rb_ivar_get(list_str, ID_at_enc);
+ }
+
+ if (!NIL_P(enc) && strcmp(StringValuePtr(enc), "binary") == 0) {
+ /* binary string */
+ listobj = Tcl_NewByteArrayObj(RSTRING(list_str)->ptr,
+ RSTRING(list_str)->len);
+ } else if (strlen(RSTRING(list_str)->ptr)
+ != RSTRING(list_str)->len) {
+ /* probably binary string */
+ listobj = Tcl_NewByteArrayObj(RSTRING(list_str)->ptr,
+ RSTRING(list_str)->len);
+ } else {
+ /* probably text string */
+ listobj = Tcl_NewStringObj(RSTRING(list_str)->ptr,
+ RSTRING(list_str)->len);
+ }
+ }
+
+ rb_thread_critical = thr_crit_bup;
+# endif
+# else
+ listobj = Tcl_NewStringObj(RSTRING(list_str)->ptr,
+ RSTRING(list_str)->len);
+# endif
Tcl_IncrRefCount(listobj);
@@ -7345,9 +5929,13 @@ lib_split_tklist_core(ip_obj, list_str)
if (result == TCL_ERROR) {
Tcl_DecrRefCount(listobj);
if (interp == (Tcl_Interp*)NULL) {
- rb_raise(rb_eRuntimeError, "can't get elements from list");
+ rb_raise(rb_eRuntimeError, "cannot get elements from list");
} else {
+#if TCL_MAJOR_VERSION >= 8
rb_raise(rb_eRuntimeError, "%s", Tcl_GetStringResult(interp));
+#else /* TCL_MAJOR_VERSION < 8 */
+ rb_raise(rb_eRuntimeError, "%s", interp->result);
+#endif
}
}
@@ -7364,7 +5952,31 @@ lib_split_tklist_core(ip_obj, list_str)
old_gc = rb_gc_disable();
for(idx = 0; idx < objc; idx++) {
- elem = get_str_from_obj(objv[idx]);
+ char *str;
+ int len;
+
+# if 1
+# if TCL_MAJOR_VERSION == 8 && TCL_MINOR_VERSION == 0
+ str = Tcl_GetStringFromObj(objv[idx], &len);
+ elem = rb_str_new(str, len);
+# else /* TCL_VERSION >= 8.1 */
+ if (Tcl_GetCharLength(objv[idx])
+ != Tcl_UniCharLen(Tcl_GetUnicode(objv[idx]))) {
+ /* possibly binary string */
+ str = Tcl_GetByteArrayFromObj(objv[idx], &len);
+ elem = rb_str_new(str, len);
+ rb_ivar_set(elem, ID_at_enc, rb_tainted_str_new2("binary"));
+ } else {
+ /* possibly text string */
+ str = Tcl_GetStringFromObj(objv[idx], &len);
+ elem = rb_str_new(str, len);
+ }
+# endif
+# else
+ str = Tcl_GetStringFromObj(objv[idx], &len);
+ elem = rb_str_new(str, len);
+# endif
+
if (taint_flag) OBJ_TAINT(elem);
RARRAY(ary)->ptr[idx] = elem;
}
@@ -7389,7 +6001,7 @@ lib_split_tklist_core(ip_obj, list_str)
if (Tcl_SplitList(interp, RSTRING(list_str)->ptr,
&argc, &argv) == TCL_ERROR) {
if (interp == (Tcl_Interp*)NULL) {
- rb_raise(rb_eRuntimeError, "can't get elements from list");
+ rb_raise(rb_eRuntimeError, "cannot get elements from list");
} else {
rb_raise(rb_eRuntimeError, "%s", interp->result);
}
@@ -7451,8 +6063,6 @@ lib_merge_tklist(argc, argv, obj)
if (argc == 0) return rb_str_new2("");
- tcl_stubs_check();
-
thr_crit_bup = rb_thread_critical;
rb_thread_critical = Qtrue;
old_gc = rb_gc_disable();
@@ -7517,8 +6127,6 @@ lib_conv_listelement(self, src)
int taint_flag = OBJ_TAINTED(src);
int thr_crit_bup;
- tcl_stubs_check();
-
thr_crit_bup = rb_thread_critical;
rb_thread_critical = Qtrue;
@@ -7546,73 +6154,20 @@ lib_conv_listelement(self, src)
}
-static VALUE
-tcltklib_compile_info()
+#ifdef __MACOS__
+static void
+_macinit()
{
- volatile VALUE ret;
- int size;
- char form[]
- = "tcltklib %s :: Ruby%s (%s) %s pthread :: Tcl%s(%s)/Tk%s(%s) %s";
- char *info;
-
- size = strlen(form)
- + strlen(TCLTKLIB_RELEASE_DATE)
- + strlen(RUBY_VERSION)
- + strlen(RUBY_RELEASE_DATE)
- + strlen("without")
- + strlen(TCL_PATCH_LEVEL)
- + strlen("without stub")
- + strlen(TK_PATCH_LEVEL)
- + strlen("without stub")
- + strlen("unknown tcl_threads");
-
- info = ALLOC_N(char, size);
-
- sprintf(info, form,
- TCLTKLIB_RELEASE_DATE,
- RUBY_VERSION, RUBY_RELEASE_DATE,
-#ifdef HAVE_NATIVETHREAD
- "with",
-#else
- "without",
-#endif
- TCL_PATCH_LEVEL,
-#ifdef USE_TCL_STUBS
- "with stub",
-#else
- "without stub",
-#endif
- TK_PATCH_LEVEL,
-#ifdef USE_TK_STUBS
- "with stub",
-#else
- "without stub",
-#endif
-#ifdef WITH_TCL_ENABLE_THREAD
-# if WITH_TCL_ENABLE_THREAD
- "with tcl_threads"
-# else
- "without tcl_threads"
-# endif
-#else
- "unknown tcl_threads"
-#endif
- );
-
- ret = rb_obj_freeze(rb_str_new2(info));
-
- free(info);
-
- return ret;
+ tcl_macQdPtr = &qd; /* setup QuickDraw globals */
+ Tcl_MacSetEventProc(TkMacConvertEvent); /* setup event handler */
}
-
+#endif
/*---- initialization ----*/
void
Init_tcltklib()
{
int thr_crit_bup;
- int ret;
VALUE lib = rb_define_module("TclTkLib");
VALUE ip = rb_define_class("TclTkIp", rb_cObject);
@@ -7622,23 +6177,25 @@ Init_tcltklib()
/* --------------------------------------------------------------- */
+#if defined USE_TCL_STUBS && defined USE_TK_STUBS
+ extern int ruby_tcltk_stubs();
+ int ret = ruby_tcltk_stubs();
+
+ if (ret)
+ rb_raise(rb_eLoadError, "tcltklib: tcltk_stubs init error(%d)", ret);
+#endif
+
+ /* --------------------------------------------------------------- */
+
rb_global_variable(&eTkCallbackReturn);
rb_global_variable(&eTkCallbackBreak);
rb_global_variable(&eTkCallbackContinue);
rb_global_variable(&eventloop_thread);
- rb_global_variable(&eventloop_stack);
rb_global_variable(&watchdog_thread);
- rb_global_variable(&rbtk_pending_exception);
-
/* --------------------------------------------------------------- */
- rb_define_const(lib, "COMPILE_INFO", tcltklib_compile_info());
-
- rb_define_const(lib, "RELEASE_DATE",
- rb_obj_freeze(rb_str_new2(tcltklib_release_date)));
-
rb_define_const(lib, "FINALIZE_PROC_NAME",
rb_str_new2(finalize_hook_name));
@@ -7672,7 +6229,7 @@ Init_tcltklib()
/* --------------------------------------------------------------- */
- eTkCallbackReturn = rb_define_class("TkCallbackReturn", rb_eStandardError);
+ eTkCallbackBreak = rb_define_class("TkCallbackReturn", rb_eStandardError);
eTkCallbackBreak = rb_define_class("TkCallbackBreak", rb_eStandardError);
eTkCallbackContinue = rb_define_class("TkCallbackContinue",
rb_eStandardError);
@@ -7681,22 +6238,12 @@ Init_tcltklib()
eLocalJumpError = rb_const_get(rb_cObject, rb_intern("LocalJumpError"));
- eTkLocalJumpError = rb_define_class("TkLocalJumpError", eLocalJumpError);
-
- eTkCallbackRetry = rb_define_class("TkCallbackRetry", eTkLocalJumpError);
- eTkCallbackRedo = rb_define_class("TkCallbackRedo", eTkLocalJumpError);
- eTkCallbackThrow = rb_define_class("TkCallbackThrow", eTkLocalJumpError);
-
- /* --------------------------------------------------------------- */
-
ID_at_enc = rb_intern("@encoding");
ID_at_interp = rb_intern("@interp");
ID_stop_p = rb_intern("stop?");
- ID_alive_p = rb_intern("alive?");
ID_kill = rb_intern("kill");
ID_join = rb_intern("join");
- ID_value = rb_intern("value");
ID_call = rb_intern("call");
ID_backtrace = rb_intern("backtrace");
@@ -7713,12 +6260,8 @@ Init_tcltklib()
/* --------------------------------------------------------------- */
rb_define_module_function(lib, "mainloop", lib_mainloop, -1);
- rb_define_module_function(lib, "mainloop_thread?",
- lib_evloop_thread_p, 0);
rb_define_module_function(lib, "mainloop_watchdog",
lib_mainloop_watchdog, -1);
- rb_define_module_function(lib, "do_thread_callback",
- lib_thread_callback, -1);
rb_define_module_function(lib, "do_one_event", lib_do_one_event, -1);
rb_define_module_function(lib, "mainloop_abort_on_exception",
lib_evloop_abort_on_exc, 0);
@@ -7749,15 +6292,6 @@ Init_tcltklib()
rb_define_module_function(lib, "_subst_Tcl_backslash",
lib_Tcl_backslash, 1);
- rb_define_module_function(lib, "encoding_system",
- lib_get_system_encoding, 0);
- rb_define_module_function(lib, "encoding_system=",
- lib_set_system_encoding, 1);
- rb_define_module_function(lib, "encoding",
- lib_get_system_encoding, 0);
- rb_define_module_function(lib, "encoding=",
- lib_set_system_encoding, 1);
-
/* --------------------------------------------------------------- */
rb_define_alloc_func(ip, ip_alloc);
@@ -7769,8 +6303,6 @@ Init_tcltklib()
rb_define_method(ip, "allow_ruby_exit=", ip_allow_ruby_exit_set, 1);
rb_define_method(ip, "delete", ip_delete, 0);
rb_define_method(ip, "deleted?", ip_is_deleted_p, 0);
- rb_define_method(ip, "has_mainwindow?", ip_has_mainwindow_p, 0);
- rb_define_method(ip, "invalid_namespace?", ip_has_invalid_namespace_p, 0);
rb_define_method(ip, "_eval", ip_eval, 1);
rb_define_method(ip, "_toUTF8", ip_toUTF8, -1);
rb_define_method(ip, "_fromUTF8", ip_fromUTF8, -1);
@@ -7779,8 +6311,6 @@ Init_tcltklib()
rb_define_method(ip, "_invoke", ip_invoke, -1);
rb_define_method(ip, "_return_value", ip_retval, 0);
- rb_define_method(ip, "_create_console", ip_create_console, 0);
-
/* --------------------------------------------------------------- */
rb_define_method(ip, "_get_variable", ip_get_variable, 2);
@@ -7822,37 +6352,18 @@ Init_tcltklib()
/* --------------------------------------------------------------- */
- eventloop_thread = Qnil;
-
-#ifndef DEFAULT_EVENTLOOP_DEPTH
-#define DEFAULT_EVENTLOOP_DEPTH 7
-#endif
- eventloop_stack = rb_ary_new2(DEFAULT_EVENTLOOP_DEPTH);
- OBJ_TAINT(eventloop_stack);
-
- watchdog_thread = Qnil;
-
- rbtk_pending_exception = Qnil;
+ eventloop_thread = 0;
+ watchdog_thread = 0;
/* --------------------------------------------------------------- */
- /* if ruby->nativethread-supprt and tcltklib->doen't,
- the following will cause link-error. */
- is_ruby_native_thread();
-
- /* --------------------------------------------------------------- */
+#ifdef __MACOS__
+ _macinit();
+#endif
- ret = ruby_open_tcl_dll(RSTRING(rb_argv0)->ptr);
- switch(ret) {
- case TCLTK_STUBS_OK:
- break;
- case NO_TCL_DLL:
- rb_raise(rb_eLoadError, "tcltklib: fail to open tcl_dll");
- case NO_FindExecutable:
- rb_raise(rb_eLoadError, "tcltklib: can't find Tcl_FindExecutable");
- default:
- rb_raise(rb_eLoadError, "tcltklib: unknown error(%d) on ruby_open_tcl_dll", ret);
- }
+ /* from Tk_Main() */
+ DUMP1("Tcl_FindExecutable");
+ Tcl_FindExecutable(RSTRING(rb_argv0)->ptr);
/* --------------------------------------------------------------- */
}
diff --git a/ext/tk/ChangeLog.tkextlib b/ext/tk/ChangeLog.tkextlib
index a4e8d87398..6386f727f6 100644
--- a/ext/tk/ChangeLog.tkextlib
+++ b/ext/tk/ChangeLog.tkextlib
@@ -1,789 +1,44 @@
-2005-10-23 Hidetoshi NAGAI <nagai@ai.kyutech.ac.jp>
-
- * ext/tk/lib/tkextlib/*: update to support ActiveTcl8.4.11.2
-
- * ext/tk/lib/tkextlib/trofs/*: support Trofs 0.4.3
-
- * ext/tk/lib/tkextlib/tile/*: support Tile 0.7.2
-
- * ext/tk/lib/tkextlib/vu/*: support vu 2.3.0
-
- * ext/tk/lib/tkextlib/tcllib/*: support Tcllib 1.8 (Tklib 0.3)
-
- * ext/tk/lib/tkextlib/*: improve conversion of option values
-
-2005-10-04 Hidetoshi NAGAI <nagai@ai.kyutech.ac.jp>
-
- * ext/tk/lib/tkextlib/tktable/tktable.rb: border_* instance methods
- don't call 'border' subcommands.
-
-2005-08-10 Hidetoshi NAGAI <nagai@ai.kyutech.ac.jp>
-
- * ext/tk/lib/tkextlib/blt/component.rb: didn't check
- __item_ruby2val_optkeys().
-
-2005-08-09 Hidetoshi NAGAI <nagai@ai.kyutech.ac.jp>
-
- * ext/tk/lib/tkextlib/blt/barchart.rb: support to treat tkvariable-type
- configure options.
-
- * ext/tk/lib/tkextlib/blt/component.rb: ditto.
-
- * ext/tk/lib/tkextlib/blt/dragdrop.rb: ditto.
-
- * ext/tk/lib/tkextlib/blt/treeview.rb: ditto.
-
- * ext/tk/lib/tkextlib/bwidget/button.rb: ditto.
-
- * ext/tk/lib/tkextlib/bwidget/entry.rb: ditto.
-
- * ext/tk/lib/tkextlib/bwidget/label.rb: ditto.
-
- * ext/tk/lib/tkextlib/bwidget/labelentry.rb: ditto.
-
- * ext/tk/lib/tkextlib/bwidget/labelframe.rb: ditto.
-
- * ext/tk/lib/tkextlib/bwidget/mainframe.rb: ditto.
-
- * ext/tk/lib/tkextlib/bwidget/passwddlg.rb: ditto.
-
- * ext/tk/lib/tkextlib/bwidget/spinbox.rb: ditto.
-
- * ext/tk/lib/tkextlib/bwidget/tree.rb: ditto.
-
- * ext/tk/lib/tkextlib/iwidgets/calendar.rb: ditto.
-
- * ext/tk/lib/tkextlib/iwidgets/entryfield.rb: ditto.
-
- * ext/tk/lib/tkextlib/iwidgets/hierarchy.rb: ditto.
-
- * ext/tk/lib/tkextlib/iwidgets/labeledframe.rb: ditto.
-
- * ext/tk/lib/tkextlib/iwidgets/labeledwidget.rb: ditto.
-
- * ext/tk/lib/tkextlib/iwidgets/menubar.rb: ditto.
-
- * ext/tk/lib/tkextlib/iwidgets/scrolledlistbox.rb: ditto.
-
- * ext/tk/lib/tkextlib/iwidgets/spinner.rb: ditto.
-
- * ext/tk/lib/tkextlib/iwidgets/toolbar.rb: ditto.
-
- * ext/tk/lib/tkextlib/tkimg/pixmap.rb: ditto.
-
- * ext/tk/lib/tkextlib/tktable/tktable.rb: ditto.
-
-2005-08-06 ocean <ocean@ruby-lang.org>
-
- * sample/tkextlib/tile/demo.rb: use Tk::Tile::Scale#variable.
-
-2005-08-04 ocean <ocean@ruby-lang.org>
-
- * sample/tkextlib/tile/demo.rb: followed previous changes.
-
-2005-08-04 Hidetoshi NAGAI <nagai@ai.kyutech.ac.jp>
-
- * lib/tkextlib/tile/t*.rb: aliased class names starting with 'T'
- to non 'T' ones. (ie. Tk::Tile::TButton -> Tk::Tile::Button)
- [ruby-dev:26724]
-
- * lib/tkextlib/tile.rb: ditto. (autoload support)
-
-2005-08-04 ocean <ocean@ruby-lang.org>
-
- * sample/tkextlib/tile/demo.rb: fixed: Tk::Tile::TProgressbar is
- supported on tile 0.6 or later, not tile 0.5.
-
- * sample/tkextlib/tile/demo.rb: updated scales demo to use
- Tk::Tile::TProgressbar for tile 0.6 or later.
-
- * sample/tkextlib/tile/demo.rb: set some TkVariable default values.
-
-2005-08-03 Hidetoshi NAGAI <nagai@ai.kyutech.ac.jp>
-
- * lib/tkextlib/tile/treeview.rb: Tk::Tile::Treeview#headingconfigure
- is now working and more. [ruby-dev:26716]
-
- * sample/tkextlib/tile/demo.rb: use Tk::Tile::Treeview#headingconfigure instead of direct Tk.tk_call.
-
-2005-08-02 ocean <ocean@ruby-lang.org>
-
- * lib/tkextlib/tile/tprogressbar.rb: Tk::Tile::TProgressbar#start
- takes optional argument `interval'.
-
- * sample/tkextlib/tile/demo.rb: emulate Tk::Tile::TProgressbar
- with Tk::Tile::TProgress in tile 0.4. (repeating buttons demo)
-
-2005-08-02 ocean <ocean@ruby-lang.org>
-
- * sample/tkextlib/tile/demo.rb: added repeating buttons demo.
-
- * sample/tkextlib/tile/repeater.tcl: ditto. (new file)
-
-2005-08-01 ocean <ocean@ruby-lang.org>
-
- * lib/tkextlib/tile.rb: fixed autoload for Treeview.
-
- * lib/tkextlib/tile/treeview.rb: replaced `ary2tk_list(items)' with
- `*items'.
-
- * sample/tkextlib/tile/demo.rb: added treeview demo. (tile 0.5 or
- later is required) [ruby-dev:26668]
-
-2005-08-01 ocean <ocean@ruby-lang.org>
-
- * sample/tkextlib/tile/demo.rb: added combobox demo.
-
-2005-07-27 ocean <ocean@ruby-lang.org>
-
- * sample/tkextlib/tile/demo.rb: fixed typo.
-
-2005-06-16 Hidetoshi NAGAI <nagai@ai.kyutech.ac.jp>
-
- * lib/tkextlib/SUPPOPRT_STATUS: add RELEASE_DATE information.
-
- * lib/tkextlib/tile/style.rb: add "style element options <elem>"
- command support.
-
-2005-06-08 Hidetoshi NAGAI <nagai@ai.kyutech.ac.jp>
-
- * lib/tkextlib/ICONS/icons.rb: fail to create instances of
- Tk::ICONS [ruby-dev:26305].
-
-2005-06-07 ocean <ocean@ruby-lang.org>
-
- * sample/tkextlib/tile/themes/kroc.{rb,tcl}: also support tile 0.4.
-
-2005-06-07 ocean <ocean@ruby-lang.org>
-
- * sample/tkextlib/tile/themes/kroc.{rb,tcl}: support tile 0.5 or later.
- ("pixmap" element constructor replaced by "image")
-
-2005-06-05 Hidetoshi NAGAI <nagai@ai.kyutech.ac.jp>
-
- * sample/tkextlib/tile/demo.rb: fix TypeError & create Console
-
-2005-05-30 Hidetoshi NAGAI <nagai@ai.kyutech.ac.jp>
-
- * lib/tkextlib/blt.rb: add PACKAGE_NAME information of Tcl/Tk
- Extension.
-
- * lib/tkextlib/bwidget.rb: ditto.
-
- * lib/tkextlib/iwidgets.rb: ditto.
-
- * lib/tkextlib/tile.rb: ditto.
-
- * lib/tkextlib/tkimg.rb: ditto.
-
- * lib/tkextlib/vu.rb: ditto.
-
- * lib/tkextlib/ICONS/icons.rb: ditto.
-
- * lib/tkextlib/itcl/incr_tcl.rb: ditto.
-
- * lib/tkextlib/itk/incr_tk.rb: ditto.
-
- * lib/tkextlib/tcllib/autoscroll.rb: ditto.
-
- * lib/tkextlib/tcllib/ctext.rb: ditto.
-
- * lib/tkextlib/tcllib/cursor.rb: ditto.
-
- * lib/tkextlib/tcllib/datefield.rb: ditto.
-
- * lib/tkextlib/tcllib/ico.rb: ditto.
-
- * lib/tkextlib/tcllib/ip_entry.rb: ditto.
-
- * lib/tkextlib/tcllib/plotchart.rb: ditto.
-
- * lib/tkextlib/tcllib/style.rb: ditto.
-
- * lib/tkextlib/tcllib/tkpiechart.rb: ditto.
-
- * lib/tkextlib/tclx/tclx.rb: ditto.
-
- * lib/tkextlib/tkDND/shape.rb: ditto.
-
- * lib/tkextlib/tkDND/tkdnd.rb: ditto.
-
- * lib/tkextlib/tkHTML/htmlwidget.rb: ditto.
-
- * lib/tkextlib/tkimg/bmp.rb: ditto.
-
- * lib/tkextlib/tkimg/gif.rb: ditto.
-
- * lib/tkextlib/tkimg/ico.rb: ditto.
-
- * lib/tkextlib/tkimg/jpeg.rb: ditto.
-
- * lib/tkextlib/tkimg/pcx.rb: ditto.
-
- * lib/tkextlib/tkimg/pixmap.rb: ditto.
-
- * lib/tkextlib/tkimg/png.rb: ditto.
-
- * lib/tkextlib/tkimg/ppm.rb: ditto.
-
- * lib/tkextlib/tkimg/ps.rb: ditto.
-
- * lib/tkextlib/tkimg/sgi.rb: ditto.
-
- * lib/tkextlib/tkimg/sun.rb: ditto.
-
- * lib/tkextlib/tkimg/tga.rb: ditto.
-
- * lib/tkextlib/tkimg/tiff.rb: ditto.
-
- * lib/tkextlib/tkimg/window.rb: ditto.
-
- * lib/tkextlib/tkimg/xbm.rb: ditto.
-
- * lib/tkextlib/tkimg/xpm.rb: ditto.
-
- * lib/tkextlib/tktable/tktable.rb: ditto.
-
- * lib/tkextlib/tktrans/tktrans.rb: ditto.
-
- * lib/tkextlib/treectrl/tktreectrl.rb: ditto.
-
- * lib/tkextlib/winico/winico.rb: ditto.
-
-2005-05-25 Hidetoshi NAGAI <nagai@ai.kyutech.ac.jp>
-
- * lib/tkextlib/iwidgets/scrolledlistbox.rb: follow the change
- of tk.rb. modify to attend encoding.
-
- * lib/tkextlib/iwidgets/scrolledtext.rb: ditto.
-
- * lib/tkextlib/iwidgets/scrolledcanvas.rb: bug fix on
- TkCanvas#delete when given non-TkcItem arguments.
-
-2005-05-10 Hidetoshi NAGAI <nagai@ai.kyutech.ac.jp>
-
- * lib/tkextlib/blt/winop.rb: fix typo
-
-2005-05-08 Hidetoshi NAGAI <nagai@ai.kyutech.ac.jp>
-
- * lib/tkextlib/vu/pie.rb: fix typo
-
-2005-04-10 ocean <ocean@ruby-lang.org>
-
- * sample/tkextlib/treectrl/mailwasher.rb: fixed typo. [ruby-dev:26008]
-
-2005-04-09 Hidetoshi NAGAI <nagai@ai.kyutech.ac.jp>
-
- * sample/tkextlib/tile/demo.rb: new demo of Tile extension.
-
- * sample/tkextlib/tile/iconlib.tcl: part of the demo.
-
- * sample/tkextlib/tile/toolbutton.tcl: ditto.
-
- * sample/tkextlib/tile/readme.txt: document of the demo.
-
- * sample/tkextlib/tile/Orig_LICENSE.txt: ditto.
-
- * sample/tkextlib/tile/themes/kroc.tcl: sample theme written with Tcl.
-
- * sample/tkextlib/tile/themes/pkgIndex.tcl: pkgIndex of kroc.tcl.
-
- * sample/tkextlib/tile/themes/kroc.rb: Kroc theme written with Ruby.
-
- * sample/tkextlib/tile/themes/kroc/button-h.gif: images for Kroc theme.
-
- * sample/tkextlib/tile/themes/kroc/button-n.gif: ditto.
-
- * sample/tkextlib/tile/themes/kroc/button-p.gif: ditto.
-
- * sample/tkextlib/tile/themes/kroc/check-hc.gif: ditto.
-
- * sample/tkextlib/tile/themes/kroc/check-hu.gif: ditto.
-
- * sample/tkextlib/tile/themes/kroc/check-nc.gif: ditto.
-
- * sample/tkextlib/tile/themes/kroc/check-nu.gif: ditto.
-
- * sample/tkextlib/tile/themes/kroc/radio-hc.gif: ditto.
-
- * sample/tkextlib/tile/themes/kroc/radio-hu.gif: ditto.
-
- * sample/tkextlib/tile/themes/kroc/radio-nc.gif: ditto.
-
- * sample/tkextlib/tile/themes/kroc/radio-nu.gif: ditto.
-
- * lib/tkextlib/tile.rb: bug fix (tested on the new demo).
-
- * lib/tkextlib/tile/style.rb: ditto.
-
- * lib/tkextlib/tile/tbutton.rb: ditto.
-
- * lib/tkextlib/tile/tcheckbutton.rb: ditto.
-
- * lib/tkextlib/tile/tcombobox.rb: ditto.
-
- * lib/tkextlib/tile/tentry.rb: ditto.
-
- * lib/tkextlib/tile/tframe.rb: ditto.
-
- * lib/tkextlib/tile/tlabel.rb: ditto.
-
- * lib/tkextlib/tile/tlabelframe.rb: ditto.
-
- * lib/tkextlib/tile/tmenubutton.rb: ditto.
-
- * lib/tkextlib/tile/tnotebook.rb: ditto.
-
- * lib/tkextlib/tile/tprogressbar.rb: ditto.
-
- * lib/tkextlib/tile/tradiobutton.rb: ditto.
-
- * lib/tkextlib/tile/treeview.rb: ditto.
-
- * lib/tkextlib/tile/tscrollbar.rb: ditto.
-
- * lib/tkextlib/tile/tseparator.rb: ditto.
-
- * lib/tkextlib/tile/tsquare.rb: ditto.
-
- * lib/tkextlib/tile/tpaned.rb: new library
-
- * lib/tkextlib/tile/tscale.rb: ditto.
-
- * lib/tkextlib/SUPPORT_STATUS: update support status of Tile extension.
-
- * lib/tkextlib/tcllib/ctext.rb: use TkCommandNames on create_self().
-
- * lib/tkextlib/tcllib/datefield.rb: ditto.
-
- * lib/tkextlib/tcllib/ip_entry.rb: ditto.
-
- * lib/tkextlib/tkHTML/htmlwidget.rb: ditto.
-
- * lib/tkextlib/treectrl/tktreectrl.rb: ditto.
-
-2005-04-09 ocean <ocean@ruby-lang.org>
-
- * sample/tkextlib/treectrl/explorer.rb: File.executable? returns true
- even if it's plain text file. (this function only checks access right)
-
-2005-04-09 ocean <ocean@ruby-lang.org>
-
- * sample/tkextlib/treectrl/{help,www-options}.rb: fixed typo.
- (click or resize column header)
-
-2005-04-09 ocean <ocean@ruby-lang.org>
-
- * sample/tkextlib/treectrl/imovie.rb: fixed typo. (click on clip title)
-
-2005-04-08 ocean <ocean@ruby-lang.org>
-
- * sample/tkextlib/treectrl/random.rb: fixed typo. (drop node outside of
- widget, or reenter widget while draggging)
-
-2005-04-08 ocean <ocean@ruby-lang.org>
-
- * sample/tkextlib/treectrl/outlook-newgrounp.rb: image had disappered when
- node was selected.
-
-2005-04-08 ocean <ocean@ruby-lang.org>
-
- * sample/tkextlib/treectrl/{random,outlook-newgroup}.rb:
- tk::treectrl uses 'afterId' not 'afterID'.
-
- * sample/tkextlib/treectrl/{random,outlook-newgroup}.rb:
- item_firstchild can return empty string. (drop node to leaf node)
-
- * sample/tkextlib/treectrl/random.rb: Enumerable#find didn't work properly
- because tried to compare String with Integer. (drag node and leave widget)
-
- * sample/tkextlib/treectrl/random.rb: and some fixes.
-
-2005-04-08 ocean <ocean@ruby-lang.org>
-
- * lib/tkextlib/treectrl/tktreectrl.rb (selection_clear): fixed typo.
-
- * sample/tkextlib/treectrl/random.rb: node deselection now works.
-
- * sample/tkextlib/treectrl/demo.rb: fixed typo. (popup menu on column header)
-
-2005-04-08 ocean <ocean@ruby-lang.org>
-
- * sample/tkextlib/treectrl/help.rb: fixed typo. (wrong color)
-
-2005-04-08 ocean <ocean@ruby-lang.org>
-
- * sample/tkextlib/treectrl/random.rb: fixed typo. (wrong itemheight)
-
- * sample/tkextlib/treectrl/outlook-newgroup.rb: ditto.
-
- * sample/tkextlib/treectrl/explorer.rb: ditto.
-
- * sample/tkextlib/treectrl/help.rb: ditto.
-
-2005-04-07 ocean <ocean@ruby-lang.org>
-
- * sample/tkextlib/treectrl/*.rb: some speed up... cache the result of
- version checking.
-
-2005-04-07 Hidetoshi NAGAI <nagai@ai.kyutech.ac.jp>
-
- * lib/tkextlib/treectrl/tktreectrl.rb: performance tuning by calling
- tk_send_without_enc. [ruby-dev:25997]
-
-2005-04-04 ocean <ocean@ruby-lang.org>
-
- * lib/tkextlib/tktable/tktable.rb: added Tk::TkTable#selection_present.
-
-2005-04-02 Hidetoshi NAGAI <nagai@ai.kyutech.ac.jp>
-
- * lib/tkextlib/treectrl/tktreectrl.rb: support TreeCtrl's cvs head.
-
-2005-04-02 Hidetoshi NAGAI <nagai@ai.kyutech.ac.jp>
-
- * lib/tkextlib/blt/component.rb: add TreeCtrl#legend_window_create().
-
- * sample/tkextlib/blt/graph6.rb: use legend_window_create().
-
- * lib/tkextlib/blt/tree.rb: forget to call tagid().
-
- * lib/tkextlib/blt/treeview.rb: ditto.
-
-2005-04-01 Hidetoshi NAGAI <nagai@ai.kyutech.ac.jp>
-
- * sample/tkextlib/treectrl/demo.rb: bridge the gap of
- Hash#index or Hash#key between ruby 1.8 and 1.9
-
-2005-04-01 Hidetoshi NAGAI <nagai@ai.kyutech.ac.jp>
-
- * lib/tkextlib/blt/component.rb: bug fix on treatment of
- component objects.
-
- * sample/tkextlib/blt/graph6.rb: a new sample script.
-
-2005-03-31 ocean <ocean@ruby-lang.org>
-
- * sample/tkextlib/treectrl/demo.rb: should use Hash#index.
-
- * sample/tkextlib/treectrl/demo.rb: TkImage was not
- cached properly.
-
- * sample/tkextlib/treectrl/random.rb: fixed typo.
-
-2005-03-31 Hidetoshi NAGAI <nagai@ai.kyutech.ac.jp>
-
- * sample/tkextlib/iwidgets/sample/hierarchy.rb: show basename
- only [ruby-dev:25970]
-
- * sample/tkextlib/treectrl/demo.rb: add check for existence of
- 'backgroundimage' option.
-
- * sample/tkextlib/treectrl/bitmaps.rb: ditto.
-
- * sample/tkextlib/treectrl/outlook-newgroup.rb: lack of '%I'
- event callback argument.
-
-2005-03-31 Hidetoshi NAGAI <nagai@ai.kyutech.ac.jp>
-
- * sample/tkextlib/iwidgets/sample/hierarchy.rb: fail to treat
- Japanese (i18n?) filenames.
-
-2005-03-30 Hidetoshi NAGAI <nagai@ai.kyutech.ac.jp>
-
- * sample/tkextlib/bwidget/tree.rb: use 'return' in the Proc object.
-
- * sample/tkextlib/tkHTML/hv.rb: ditto.
-
- * sample/tkextlib/tkHTML/ss.rb: ditto.
-
- * sample/tkextlib/tktable/basic.rb: ditto.
-
- * sample/tkextlib/tktable/command.rb: ditto.
-
- * sample/tkextlib/tktable/debug.rb: ditto.
-
- * sample/tkextlib/tktable/maxsize.rb: ditto.
-
- * sample/tkextlib/treectrl/demo.rb: ditto.
-
-2005-03-29 Hidetoshi NAGAI <nagai@ai.kyutech.ac.jp>
-
- * lib/tkextlib/blt/component.rb: cannot create elements except
- default type of element.
-
- * lib/tkextlib/blt/barchart.rb: ditto.
-
- * lib/tkextlib/blt/graph.rb: ditto.
-
- * lib/tkextlib/blt/stripchart.rb: ditto.
-
- * lib/tkextlib/blt/component.rb: axis command option gets
- proper object type of arguments.
-
- * sample/tkextlib/blt/calendar.rb: new sample.
-
- * sample/tkextlib/blt/pareto.rb: ditto.
-
-2005-03-28 ocean <ocean@ruby-lang.org>
-
- * lib/tkextlib/iwidgets/notebook.rb: fixed typo.
-
-2005-03-26 Hidetoshi NAGAI <nagai@ai.kyutech.ac.jp>
-
- * lib/tkextlib/blt.rb: add commands for zooming.
-
- * lib/tkextlib/blt/bitmap.rb (new_with_name): add for using
- given name.
-
- * lib/tkextlib/blt/busy.rb: bug fix on Tk::BLT::Busy::Shild class.
-
- * lib/tkextlib/blt/component.rb: typo fix.
-
- * lib/tkextlib/blt/component.rb: fix lack of *_create methods
-
- * lib/tkextlib/blt/component.rb: proper call on xaxis_* and so on.
-
- * lib/tkextlib/blt/htext.rb: add TkVariable object to access
- special Tcl variables.
-
- * lib/tkextlib/treectrl/tktreectrl.rb: typo fix.
-
- * lib/tkextlib/treectrl/tktreectrl.rb: proper treatment
- of 'font' option of element_configure.
-
- * lib/tkextlib/treectrl/tktreectrl.rb: bug fix on item_sort.
-
- * lib/tkextlib/treectrl/tktreectrl.rb: add methods to
- call TreeCtrl commands for bindings.
-
- * sample/tkextlib/blt/*: add some sample scripts.
-
- * sample/tkextlib/treectrl/*: add some sample scripts.
-
-2005-03-18 Hidetoshi NAGAI <nagai@ai.kyutech.ac.jp>
-
- * lib/tkextlib/treectrl/tktreectrl.rb: bug fix and define some
- classes for components of Tk::TreeCtrl
-
-2005-03-17 Hidetoshi NAGAI <nagai@ai.kyutech.ac.jp>
-
- * lib/tkextlib/treectrl/tktreectrl.rb: call wrong method in
- Tk::TreeCtrl#*_configinfo and current_*_configinfo method
-
-2005-03-16 Hidetoshi NAGAI <nagai@ai.kyutech.ac.jp>
-
- * lib/tkextlib/SUPPORT_STATUS: change the status of TkImg
-
- * lib/tkextlib/treectrl/tktreectrl.rb: bug fix and support
- TkTreeCtrl-1.1
-
- * lib/tkextlib/SUPPORT_STATUS: change the supported version of
- TkTreeCtrl
-
-2005-03-15 Hidetoshi NAGAI <nagai@ai.kyutech.ac.jp>
-
- * sample/tkextlib/tkimg: add sample
-
-2005-03-06 Hidetoshi NAGAI <nagai@ai.kyutech.ac.jp>
-
- * lib/tkextlib/SUPPORT_STATUS: add version info of each extension
-
-2005-03-05 Hidetoshi NAGAI <nagai@ai.kyutech.ac.jp>
-
- * lib/tkextlib/tile.rb: lack of "autoload TProgressbar"
-
-2005-03-05 Hidetoshi NAGAI <nagai@ai.kyutech.ac.jp>
-
- * lib/tkextlib/tile.rb: support tile-0.6
-
- * lib/tkextlib/tile/tbutton.rb: ditto
-
- * lib/tkextlib/tile/tcheckbutton.rb: ditto
-
- * lib/tkextlib/tile/tlabel.rb: ditto
-
- * lib/tkextlib/tile/tmenubutton.rb: ditto
-
- * lib/tkextlib/tile/tnotebook.rb: ditto
-
- * lib/tkextlib/tile/tradiobutton.rb: ditto
-
- * lib/tkextlib/tile/tcombobox.rb: [new] ditto
-
- * lib/tkextlib/tile/tentry.rb: [new] ditto
-
- * lib/tkextlib/tile/tframe.rb: [new] ditto
-
- * lib/tkextlib/tile/tlabelframe.rb: [new] ditto
-
- * lib/tkextlib/tile/tprogressbar.rb: [new] ditto
-
- * lib/tkextlib/tile/treeview.rb: [new] ditto
-
- * lib/tkextlib/tile/tscrollbar.rb: [new] ditto
-
- * lib/tkextlib/tile/tseparator.rb: [new] ditto
-
- * lib/tkextlib/tile/tsquare.rb: [new] ditto
-
-2005-02-20 Hidetoshi NAGAI <nagai@ai.kyutech.ac.jp>
-
- * lib/tkextlib/tclx/tclx.rb: warning TclX's 'signal' command.
-
-2005-01-25 Hidetoshi NAGAI <nagai@ai.kyutech.ac.jp>
-
- * lib/tkextlib/blt/component.rb: bug fix. cannot accept
- a callback ID string for a command argument. [ruby-dev:25479]
-
- * lib/tkextlib/blt/tabset.rb: ditto
-
- * lib/tkextlib/blt/treeview.rb: ditto
-
- * lib/tkextlib/bwidget/labelentry.rb: ditto
-
- * lib/tkextlib/bwidget/listbox.rb: ditto
-
- * lib/tkextlib/bwidget/notebook.rb: ditto
-
- * lib/tkextlib/bwidget/spinbox.rb: ditto
-
- * lib/tkextlib/bwidget/tree.rb: ditto
-
- * lib/tkextlib/itk/incr_tk.rb: ditto
-
- * lib/tkextlib/iwidgets/scrolledcanvas.rb: ditto
-
- * lib/tkextlib/tkDND/tkdnd.rb: ditto
-
- * lib/tkextlib/treectrl/tktreectrl.rb: ditto
-
- * sample/tkextlib/tkHTML/ss.rb: local variable scope bug fix
- [ruby-dev:25479]
-
- * sample/tkextlib/vu/vu_demo.rb: rename from vu.rb; avoid the bug on
- Windows version of Tcl/Tk. The trouble based on the bug occurs when
- the script name (without extension) is a same name as a Tcl/Tk's
- library file name (without extension) required in the script.
-
-2004-12-24 Hidetoshi NAGAI <nagai@ai.kyutech.ac.jp>
-
- * lib/tkextlib/blt: add BLT extension support
-
-2004-12-16 Hidetoshi NAGAI <nagai@ai.kyutech.ac.jp>
-
- * lib/tkextlib/bwidget/labelentry.rb: use TkCore.callback_obj?()
-
- * lib/tkextlib/bwidget/listbox.rb: ditto
-
- * lib/tkextlib/bwidget/notebook.rb: ditto
-
- * lib/tkextlib/bwidget/spinbox.rb: ditto
-
- * lib/tkextlib/itk/incr_tk.rb: ditto
-
- * lib/tkextlib/iwidgets/scrolledcanvas.rb: ditto
-
- * lib/tkextlib/tkDND/tkdnd.rb: ditto
-
- * lib/tkextlib/treectrl/tktreectrl.rb: ditto
-
- * lib/tkextlib/winico/winico.rb: ditto
-
-2004-12-10 Hidetoshi NAGAI <nagai@ai.kyutech.ac.jp>
-
- * lib/tkextlib/tile/style.rb: 'theme_use' method bug fix
-
-2004-12-08 Hidetoshi NAGAI <nagai@ai.kyutech.ac.jp>
-
- * lib/tkextlib/bwidget/notebook.rb: raise method cannot return
- the raised page.
-
- * lib/tkextlib/bwidget/labelentry.rb: bind methods accept
- subst_args + block
-
- * lib/tkextlib/bwidget/listbox.rb: ditto
-
- * lib/tkextlib/bwidget/notebook.rb: ditto
-
- * lib/tkextlib/bwidget/spinbox.rb: ditto
-
- * lib/tkextlib/bwidget/tree.rb: ditto
-
- * lib/tkextlib/itk/incr_tk.rb: ditto
-
- * lib/tkextlib/iwidgets/scrolledcanvas.rb: ditto
-
- * lib/tkextlib/tkDND/tkdnd.rb: ditto
-
- * lib/tkextlib/treectrl/tktreectrl.rb: ditto
-
-2004-11-26 Hidetoshi NAGAI <nagai@ai.kyutech.ac.jp>
-
- * lib/tkextlib/bwidget/notebook.rb: uses epath
-
- * lib/tkextlib/bwidget/widget.rb: ditto
-
- * lib/tkextlib/tktable/tktable.rb: ditto
-
- * lib/tkextlib/tcllib/cursor.rb: ditto, and bug fix
-
-2004-11-10 Hidetoshi NAGAI <nagai@ai.kyutech.ac.jp>
-
- * lib/tkextlib/tile/style.rb: bug fix
-
-2004-11-07 Hidetoshi NAGAI <nagai@ai.kyutech.ac.jp>
-
- * lib/tkextlib/iwidgets/scrolledcanvas.rb: bind-event methods
- accept multi substitution arguments.
-
- * lib/tkextlib/tktable/tktable.rb: ditto.
-
- * lib/tkextlib/treectrl/tktreectrl.rb: ditto
-
2004-11-03 Hidetoshi NAGAI <nagai@ai.kyutech.ac.jp>
- * lib/tkextlib/SUPPORT_STATUS: BLT moves to 'plan to support'
- from 'not determined'
+ * SUPPORT_STATUS: BLT moves to 'plan to support' from 'not determined'
- * lib/tkextlib/itk/incr_tk.rb: __cget_cmd and __config_cmd are
- private methods
+ * itk/incr_tk.rb: __cget_cmd and __config_cmd are private methods
- * lib/tkextlib/tcllib/autoscroll.rb: extend TkCore
+ * tcllib/autoscroll.rb: extend TkCore
- * lib/tkextlib/tcllib/cursor.rb: ditto.
+ * tcllib/cursor.rb: ditto.
- * lib/tkextlib/tcllib/plotchart.rb: ditto.
+ * tcllib/plotchart.rb: ditto.
- * lib/tkextlib/tcllib/style.rb: ditto.
+ * tcllib/style.rb: ditto.
- * lib/tkextlib/tile/style.rb: ditto.
+ * tile/style.rb: ditto.
- * lib/tkextlib/tkDND/shape.rb: ditto.
+ * tkDND/shape.rb: ditto.
2004-10-24 Hidetoshi NAGAI <nagai@ai.kyutech.ac.jp>
- * lib/tkextlib/bwidget/tree.rb: bug fix on Windows
+ * bwidget/tree.rb: bug fix on Windows
2004-10-16 Hidetoshi NAGAI <nagai@ai.kyutech.ac.jp>
- * lib/tkextlib/tcllib/ico.rb: new library (Tk::Tcllib:ICO)
+ * tcllib/ico.rb: new library (Tk::Tcllib:ICO)
- * lib/tkextlib/tcllib.rb: add Tk::Tcllib::ICO (based on tcllib 1.7)
+ * tcllib.rb: add Tk::Tcllib::ICO (based on tcllib 1.7)
2004-10-06 Hidetoshi NAGAI <nagai@ai.kyutech.ac.jp>
- * lib/tkextlib/bwidget.rb (BWidget.grab): bug fix
+ * bwidget.rb (BWidget.grab): bug fix
- * lib/tkextlib/tcllib.rb: typo fix
+ * tcllib.rb: typo fix
2004-07-28 Hidetoshi NAGAI <nagai@ai.kyutech.ac.jp>
- * lib/tkextlib/add winico support
+ * add winico support
2004-07-23 Hidetoshi NAGAI <nagai@ai.kyutech.ac.jp>
- * lib/tkextlib/add TclX support (partially; infox command and
- XPG/3 MsgCat only)
+ * add TclX support (partially; infox command and XPG/3 MsgCat only)
2004-07-15 Hidetoshi NAGAI <nagai@ai.kyutech.ac.jp>
diff --git a/ext/tk/README.1st b/ext/tk/README.1st
index df6c819d26..038528e553 100644
--- a/ext/tk/README.1st
+++ b/ext/tk/README.1st
@@ -1,22 +1,23 @@
-If you want to use Ruby/Tk (tk.rb and so on), you must have tcltklib.so
-which is working correctly. If you fail to call 'require "tcltklib"',
-you may not have tcltklib.so. When you have some troubles on compiling
-tcltklib, please read README files on tcltklib.
-Even if there is a tcltklib.so on your Ruby library directry, it will not
-work without Tcl/Tk libraries (e.g. libtcl8.4.so) on your environment.
-You must also check that your Tcl/Tk is installed properly.
+If you want to use Ruby/Tk (tk.rb and so on), you must have
+tcltklib.so which is working collectry. If you fail to call
+'require "tcltklib"', you may not have tcltklib.so.
+( see also README files of tcltklib )
+Even if there is a tcltklib.so on your Ruby library directry,
+it will not work without Tcl/Tk libraries (e.g. libtcl8.4.so)
+on your environment. You must also check that your Tcl/Tk is
+installed properly.
--------------------------------------------
( the following is written in EUC-JP )
-Ruby/Tk (tk.rb ¤Ê¤É) ¤ò»È¤¤¤¿¤¤¾ì¹ç¤Ë¤Ï¡¤tcltklib.so ¤¬Àµ¤·¤¯Æ°¤¤¤Æ
-¤¤¤Ê¤±¤ì¤Ð¤Ê¤ê¤Þ¤»¤ó¡¥¤â¤· 'require "tcltklib"' ¤Ë¼ºÇÔ¤¹¤ë¤è¤¦¤Ê¤é¡¤
-tcltklib.so ¤¬¥¤¥ó¥¹¥È¡¼¥ë¤µ¤ì¤Æ¤¤¤Ê¤¤¤Î¤«¤â¤·¤ì¤Þ¤»¤ó¡¥tcltklib ¤Î
-¥³¥ó¥Ñ¥¤¥ë»þ¤Ë²¿¤«ÌäÂ꤬À¸¤¸¤Æ¤¤¤ë¾ì¹ç¤Ï¡¤tcltklib ¤Î README ¥Õ¥¡¥¤¥ë
-¤ò¸«¤Æ¤¯¤À¤µ¤¤¡¥
-¤¿¤È¤¨ Ruby ¤Î¥é¥¤¥Ö¥é¥ê¥Ç¥£¥ì¥¯¥È¥ê¤Ë tcltklib.so ¤¬Â¸ºß¤·¤Æ¤¤¤¿¤È¤·¤Æ
-¤â¡¤¼Â¹Ô´Ä¶­¤Ë Tcl/Tk ¥é¥¤¥Ö¥é¥ê (libtcl8.4.so ¤Ê¤É) ¤¬¤Ê¤±¤ì¤Ðµ¡Ç½¤·¤Þ
-¤»¤ó¡¥Tcl/Tk ¤¬Àµ¤·¤¯¥¤¥ó¥¹¥È¡¼¥ë¤µ¤ì¤Æ¤¤¤ë¤«¤â¥Á¥§¥Ã¥¯¤·¤Æ¤¯¤À¤µ¤¤¡¥
+Ruby/Tk (tk.rb ¤Ê¤É) ¤ò»È¤¤¤¿¤¤¾ì¹ç¤Ë¤Ï¡¤tcltklib.so ¤¬Àµ¤·¤¯
+ư¤¤¤Æ¤¤¤Ê¤±¤ì¤Ð¤Ê¤ê¤Þ¤»¤ó¡¥¤â¤· require "tcltklib" ¤Ë¼ºÇÔ¤¹¤ë
+¤è¤¦¤Ê¤é¡¤tcltklib.so ¤¬Â¸ºß¤·¤Æ¤¤¤Ê¤¤¤Î¤«¤â¤·¤ì¤Þ¤»¤ó¡¥
+( tcltklib ¤Î README ¥Õ¥¡¥¤¥ë¤â¸«¤Æ¤¯¤À¤µ¤¤ )
+¤¿¤È¤¨ Ruby ¤Î¥é¥¤¥Ö¥é¥ê¥Ç¥£¥ì¥¯¥È¥ê¤Ë tcltklib.so ¤¬Â¸ºß¤·¤Æ
+¤¤¤¿¤È¤·¤Æ¤â¡¤¼Â¹Ô´Ä¶­¤Ë Tcl/Tk ¥é¥¤¥Ö¥é¥ê (libtcl8.4.so ¤Ê¤É)
+¤¬¤Ê¤±¤ì¤Ðµ¡Ç½¤·¤Þ¤»¤ó¡¥Tcl/Tk ¤¬Àµ¤·¤¯¥¤¥ó¥¹¥È¡¼¥ë¤µ¤ì¤Æ¤¤¤ë¤«
+¤É¤¦¤«¤â¥Á¥§¥Ã¥¯¤·¤Æ¤¯¤À¤µ¤¤¡¥
==========================================================
Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)
diff --git a/ext/tk/lib/multi-tk.rb b/ext/tk/lib/multi-tk.rb
index d10e304a3d..38e4b28dec 100644
--- a/ext/tk/lib/multi-tk.rb
+++ b/ext/tk/lib/multi-tk.rb
@@ -7,7 +7,7 @@ require 'tkutil'
require 'thread'
if defined? Tk
- fail RuntimeError,"'multi-tk' library must be required before requiring 'tk'"
+ fail RuntimeError, "'multi-tk' library must be required before requiring 'tk'"
end
################################################
@@ -54,7 +54,7 @@ MultiTkIp_OK.freeze
################################################
# methods for construction
class MultiTkIp
- @@SLAVE_IP_ID = ['slave'.freeze, '0'.taint].freeze
+ SLAVE_IP_ID = ['slave'.freeze, '0'.taint].freeze
@@IP_TABLE = {}.taint unless defined?(@@IP_TABLE)
@@ -71,46 +71,23 @@ class MultiTkIp
def initialize(ip, cmd)
@ip = ip
@cmd = cmd
- freeze
end
attr_reader :ip, :cmd
def inspect
cmd.inspect
end
def call(*args)
- unless @ip.deleted?
- current = Thread.current
- backup_ip = current['callback_ip']
- current['callback_ip'] = @ip
- begin
- @ip.cb_eval(@cmd, *args)
- rescue TkCallbackBreak, TkCallbackContinue => e
+ begin
+ unless @ip.deleted?
+ @ip.cb_eval(@cmd, *args)
+ end
+ rescue TkCallbackBreak, TkCallbackContinue => e
+ fail e
+ rescue Exception => e
+ if @ip.safe?
+ # ignore
+ else
fail e
- rescue SecurityError => e
- # in 'exit', 'exit!', and 'abort' : security error --> delete IP
- if e.backtrace[0] =~ /^(.+?):(\d+):in `(exit|exit!|abort)'/
- @ip.delete
- elsif @ip.safe?
- if @ip.respond_to?(:cb_error)
- @ip.cb_error(e)
- else
- nil # ignore
- end
- else
- fail e
- end
- rescue Exception => e
- if @ip.safe?
- if @ip.respond_to?(:cb_error)
- @ip.cb_error(e)
- else
- nil # ignore
- end
- else
- fail e
- end
- ensure
- current['callback_ip'] = backup_ip
end
end
end
@@ -128,23 +105,19 @@ class MultiTkIp
def _check_and_return(thread, exception, wait=0)
unless thread
- unless exception.kind_of?(MultiTkIp_OK)
+ unless exception.kind_of?(MultiTkIp_OK) || safe?
msg = "#{exception.class}: #{exception.message}"
-
- if @interp.deleted?
- warn("Warning (#{self}): " + msg)
- return nil
- end
-
- if safe?
- warn("Warning (#{self}): " + msg) if $DEBUG
- return nil
- end
-
begin
- @interp._eval_without_enc(@interp._merge_tklist('bgerror', msg))
+ if @interp.deleted?
+ warn('Warning: ' + msg)
+ elsif @interp._eval_without_enc('info command bgerror').size != 0
+ @interp._eval(@interp._merge_tklist('bgerror', msg))
+ else
+ warn('Warning: ' + msg)
+ end
rescue Exception => e
- warn("Warning (#{self}): " + msg)
+ warn('Warning: ' + msg)
+ warn('Warning: ' + e.message)
end
end
return nil
@@ -178,18 +151,6 @@ class MultiTkIp
######################################
- def set_cb_error(cmd = Proc.new)
- @cb_error_proc[0] = cmd
- end
-
- def cb_error(e)
- if @cb_error_proc[0].respond_to?(:call)
- @cb_error_proc[0].call(e)
- end
- end
-
- ######################################
-
def set_safe_level(safe)
if safe > @safe_level[0]
@safe_level[0] = safe
@@ -221,18 +182,14 @@ class MultiTkIp
end
def running_mainloop?
- @wait_on_mainloop[1] > 0
+ @wait_on_mainloop[1]
end
def _destroy_slaves_of_slaveIP(ip)
unless ip.deleted?
- # ip._split_tklist(ip._invoke('interp', 'slaves')).each{|name|
- ip._split_tklist(ip._invoke_without_enc('interp', 'slaves')).each{|name|
- name = _fromUTF8(name)
+ ip._split_tklist(ip._invoke('interp', 'slaves')).each{|name|
begin
- # ip._eval_without_enc("#{name} eval {foreach i [after info] {after cancel $i}}")
- after_ids = ip._eval_without_enc("#{name} eval {after info}")
- ip._eval_without_enc("#{name} eval {foreach i {#{after_ids}} {after cancel $i}}")
+ ip._eval_without_enc("#{name} eval {foreach i [after info] {after cancel $i}}")
rescue Exception
end
begin
@@ -271,27 +228,15 @@ class MultiTkIp
def _receiver_eval_proc_core(safe_level, thread, cmd, *args)
begin
#ret = proc{$SAFE = safe_level; cmd.call(*args)}.call
- #ret = cmd.call(safe_level, *args)
- normal_ret = false
- ret = catch(:IRB_EXIT) do # IRB hack
- retval = cmd.call(safe_level, *args)
- normal_ret = true
- retval
- end
- unless normal_ret
- # catch IRB_EXIT
- exit(ret)
- end
- ret
+ ret = cmd.call(safe_level, *args)
+
rescue SystemExit => e
# delete IP
unless @interp.deleted?
@slave_ip_tbl.each{|name, subip|
_destroy_slaves_of_slaveIP(subip)
begin
- # subip._eval_without_enc("foreach i [after info] {after cancel $i}")
- after_ids = subip._eval_without_enc("after info")
- subip._eval_without_enc("foreach i {#{after_ids}} {after cancel $i}")
+ subip._eval_without_enc("foreach i [after info] {after cancel $i}")
rescue Exception
end
=begin
@@ -325,9 +270,7 @@ class MultiTkIp
}
begin
- # @interp._eval_without_enc("foreach i [after info] {after cancel $i}")
- after_ids = @interp._eval_without_enc("after info")
- @interp._eval_without_enc("foreach i {#{after_ids}} {after cancel $i}")
+ @interp._eval_without_enc("foreach i [after info] {after cancel $i}")
rescue Exception
end
begin
@@ -348,8 +291,7 @@ class MultiTkIp
_check_and_return(thread, MultiTkIp_OK.new(nil))
end
- # if master? && !safe? && allow_ruby_exit?
- if !@interp.deleted? && master? && !safe? && allow_ruby_exit?
+ if master? && !safe? && allow_ruby_exit?
=begin
ObjectSpace.each_object(TclTkIp){|obj|
obj.delete unless obj.deleted?
@@ -368,9 +310,7 @@ class MultiTkIp
@slave_ip_tbl.each{|name, subip|
_destroy_slaves_of_slaveIP(subip)
begin
- # subip._eval_without_enc("foreach i [after info] {after cancel $i}")
- after_ids = subip._eval_without_enc("after info")
- subip._eval_without_enc("foreach i {#{after_ids}} {after cancel $i}")
+ subip._eval_without_enc("foreach i [after info] {after cancel $i}")
rescue Exception
end
=begin
@@ -404,9 +344,7 @@ class MultiTkIp
}
begin
- # @interp._eval_without_enc("foreach i [after info] {after cancel $i}")
- after_ids = @interp._eval_without_enc("after info")
- @interp._eval_without_enc("foreach i {#{after_ids}} {after cancel $i}")
+ @interp._eval_without_enc("foreach i [after info] {after cancel $i}")
rescue Exception
end
=begin
@@ -432,16 +370,6 @@ class MultiTkIp
rescue Exception => e
# raise exception
- begin
- bt = _toUTF8(e.backtrace.join("\n"))
- bt.instance_variable_set(:@encoding, 'utf-8')
- rescue Exception
- bt = e.backtrace.join("\n")
- end
- begin
- @interp._set_global_var('errorInfo', bt)
- rescue Exception
- end
_check_and_return(thread, e)
else
@@ -471,21 +399,12 @@ class MultiTkIp
private :_receiver_eval_proc, :_receiver_eval_proc_core
def _receiver_mainloop(check_root)
- if @evloop_thread[0] && @evloop_thread[0].alive?
- @evloop_thread[0]
- else
- @evloop_thread[0] = Thread.new{
- while !@interp.deleted?
- #if check_root
- # inf = @interp._invoke_without_enc('info', 'command', '.')
- # break if !inf.kind_of?(String) || inf != '.'
- #end
- break if check_root && !@interp.has_mainwindow?
- sleep 0.5
- end
- }
- @evloop_thread[0]
- end
+ Thread.new{
+ while !@interp.deleted?
+ break if @interp._invoke_without_enc('info', 'command', '.').size == 0
+ sleep 0.5
+ end
+ }
end
def _create_receiver_and_watchdog(lvl = $SAFE)
@@ -493,7 +412,7 @@ class MultiTkIp
# command-procedures receiver
receiver = Thread.new(lvl){|safe_level|
- last_thread = {}
+ last_thread = nil
loop do
break if @interp.deleted?
@@ -516,9 +435,8 @@ class MultiTkIp
else
# procedure
- last_thread[thread] = _receiver_eval_proc(last_thread[thread],
- safe_level, thread,
- cmd, *args)
+ last_thread = _receiver_eval_proc(last_thread, safe_level,
+ thread, cmd, *args)
end
end
}
@@ -577,8 +495,6 @@ class MultiTkIp
@slave_ip_top = {}.taint
- @evloop_thread = [].taint
-
unless keys.kind_of? Hash
fail ArgumentError, "expecting a Hash object for the 2nd argument"
end
@@ -588,7 +504,7 @@ class MultiTkIp
@system = Object.new
- @wait_on_mainloop = [true, 0].taint
+ @wait_on_mainloop = [true, false]
@threadgroup = Thread.current.group
@@ -697,7 +613,7 @@ class MultiTkIp
######################################
- @@SAFE_OPT_LIST = [
+ SAFE_OPT_LIST = [
'accessPath'.freeze,
'statics'.freeze,
'nested'.freeze,
@@ -716,7 +632,7 @@ class MultiTkIp
name = v
elsif k_str == 'safe'
safe = v
- elsif @@SAFE_OPT_LIST.member?(k_str)
+ elsif SAFE_OPT_LIST.member?(k_str)
safe_opts[k_str] = v
else
tk_opts[k_str] = v
@@ -732,8 +648,8 @@ class MultiTkIp
private :_parse_slaveopts
def _create_slave_ip_name
- name = @@SLAVE_IP_ID.join('')
- @@SLAVE_IP_ID[1].succ!
+ name = SLAVE_IP_ID.join('')
+ SLAVE_IP_ID[1].succ!
name
end
private :_create_slave_ip_name
@@ -774,7 +690,7 @@ class MultiTkIp
else
begin
pathname = @interp._invoke('winfo', 'pathname', new_keys['use'])
- assoc_display = @interp._invoke('winfo', 'screen', pathname)
+ assco_display = @interp._invoke('winfo', 'screen', pathname)
rescue
assoc_display = new_keys['display']
end
@@ -782,7 +698,7 @@ class MultiTkIp
# match display?
if assoc_display != new_keys['display']
- if optkeys.key?(:display) || optkeys.key?('display')
+ if optkeys.keys?(:display) || optkeys.keys?('display')
fail RuntimeError,
"conflicting 'display'=>#{new_keys['display']} " +
"and display '#{assoc_display}' on 'use'=>#{new_keys['use']}"
@@ -816,8 +732,8 @@ class MultiTkIp
# create toplevel widget
begin
top = TkToplevel.new(toplevel_keys)
- rescue NameError => e
- fail e unless @interp.safe?
+ rescue NameError
+ fail unless @interp.safe?
fail SecurityError, "unable create toplevel on the safe interpreter"
end
msg = "Untrusted Ruby/Tk applet (#{slave_name})"
@@ -836,11 +752,7 @@ class MultiTkIp
#slave_ip.delete
slave_ip._eval_without_enc('exit')
end
- begin
- top.destroy if top.winfo_exist?
- rescue
- # ignore
- end
+ top.destroy if top.winfo_exist?
}
tag = TkBindTag.new.bind('Destroy', slave_delete_proc)
@@ -944,11 +856,7 @@ class MultiTkIp
fail SecurityError, "cannot create a master-ip at level #{$SAFE}"
end
- if master.deleted? && safeip == nil
- fail RuntimeError, "cannot create a slave of a deleted interpreter"
- end
-
- if !master.deleted? && !master.master? && master.safe?
+ if !master.master? && master.safe?
fail SecurityError, "safe-slave-ip cannot create a new interpreter"
end
@@ -964,15 +872,11 @@ class MultiTkIp
@tk_table_list = []
@slave_ip_tbl = {}
@slave_ip_top = {}
- @cb_error_proc = []
- @evloop_thread = []
@tk_windows.taint unless @tk_windows.tainted?
@tk_table_list.taint unless @tk_table_list.tainted?
@slave_ip_tbl.taint unless @slave_ip_tbl.tainted?
@slave_ip_top.taint unless @slave_ip_top.tainted?
- @cb_error_proc.taint unless @cb_error_proc.tainted?
- @evloop_thread.taint unless @evloop_thread.tainted?
name, safe, safe_opts, tk_opts = _parse_slaveopts(keys)
@@ -1019,8 +923,7 @@ class MultiTkIp
@system = Object.new
- @wait_on_mainloop = [true, 0].taint
- # @wait_on_mainloop = [false, 0].taint
+ @wait_on_mainloop = [true, false]
@threadgroup = ThreadGroup.new
@@ -1047,20 +950,15 @@ class MultiTkIp
undef :instance_eval
end
- # dummy call for initialization
- self.eval_proc{ Tk.tk_call('set', 'tcl_patchLevel') }
-
self.freeze # defend against modification
end
######################################
def _default_delete_hook(slave)
- @slave_ip_tbl.delete(slave)
- top = @slave_ip_top.delete(slave)
- if top.kind_of?(String)
+ if @slave_ip_top[slave].kind_of?(String)
# call default hook of safetk.tcl (ignore exceptions)
- if top == ''
+ if @slave_ip_top[slave] == ''
begin
@interp._eval("::safe::disallowTk #{slave}")
rescue
@@ -1068,19 +966,20 @@ class MultiTkIp
end
else # toplevel path
begin
- @interp._eval("::safe::tkDelete {} #{top} #{slave}")
+ @interp._eval("::safe::tkDelete {} #{@slave_ip_top[slave]} #{slave}")
rescue
warn("Waring: fail to call '::safe::tkDelete'") if $DEBUG
begin
- @interp._eval("destroy #{top}")
+ @interp._eval("destroy #{@slave_ip_top[slave]}")
rescue
warn("Waring: fail to destroy toplevel") if $DEBUG
end
end
end
end
+ @slave_ip_tbl.delete(slave)
+ @slave_ip_top.delete(slave)
end
-
end
@@ -1094,14 +993,10 @@ class MultiTkIp
end
def self.__getip
- current = Thread.current
- if TclTkLib.mainloop_thread? != false && current['callback_ip']
- return current['callback_ip']
- end
- if current.group == ThreadGroup::Default
+ if Thread.current.group == ThreadGroup::Default
@@DEFAULT_MASTER
else
- ip = @@IP_TABLE[current.group]
+ ip = @@IP_TABLE[Thread.current.group]
unless ip
fail SecurityError,
"cannot call Tk methods on #{Thread.current.inspect}"
@@ -1133,10 +1028,7 @@ class << MultiTkIp
end
ip = __new(__getip, nil, keys)
- #ip.eval_proc(proc{$SAFE=ip.safe_level; Proc.new}.call) if block_given?
- if block_given?
- Thread.new{ip.eval_proc(proc{$SAFE=ip.safe_level; Proc.new}.call)}
- end
+ ip.eval_proc(proc{$SAFE=ip.safe_level; Proc.new}.call) if block_given?
ip
end
@@ -1157,10 +1049,7 @@ class << MultiTkIp
end
ip = __new(__getip, false, keys)
- # ip.eval_proc(proc{$SAFE=ip.safe_level; Proc.new}.call) if block_given?
- if block_given?
- Thread.new{ip.eval_proc(proc{$SAFE=ip.safe_level; Proc.new}.call)}
- end
+ ip.eval_proc(proc{$SAFE=ip.safe_level; Proc.new}.call) if block_given?
ip
end
alias new_trusted_slave new_slave
@@ -1178,10 +1067,7 @@ class << MultiTkIp
end
ip = __new(__getip, true, keys)
- # ip.eval_proc(proc{$SAFE=ip.safe_level; Proc.new}.call) if block_given?
- if block_given?
- Thread.new{ip.eval_proc(proc{$SAFE=ip.safe_level; Proc.new}.call)}
- end
+ ip.eval_proc(proc{$SAFE=ip.safe_level; Proc.new}.call) if block_given?
ip
end
alias new_safeTk new_safe_slave
@@ -1193,15 +1079,9 @@ class MultiTkIp
def inspect
s = self.to_s.chop!
if master?
- if @interp.deleted?
- s << ':deleted-master'
- else
- s << ':master'
- end
+ s << ':master'
else
- if @interp.deleted?
- s << ':deleted-slave'
- elsif @interp.safe?
+ if @interp.safe?
s << ':safe-slave'
else
s << ':trusted-slave'
@@ -1376,9 +1256,6 @@ end
# for callback operation
class MultiTkIp
- def self.cb_entry_class
- @@CB_ENTRY_CLASS
- end
def self.get_cb_entry(cmd)
@@CB_ENTRY_CLASS.new(__getip, cmd).freeze
end
@@ -1387,13 +1264,11 @@ class MultiTkIp
#self.eval_callback{ TkComm._get_eval_string(TkUtil.eval_cmd(cmd, *args)) }
#ret = self.eval_callback{ TkComm._get_eval_string(TkUtil.eval_cmd(cmd, *args)) }
ret = self.eval_callback(*args){|safe, *params|
- $SAFE=safe if $SAFE < safe
- TkComm._get_eval_string(TkUtil.eval_cmd(cmd, *params))
+ $SAFE=safe; TkComm._get_eval_string(TkUtil.eval_cmd(cmd, *params))
}
if ret.kind_of?(Exception)
- raise ret
+ raise ret
end
- ret
end
end
@@ -1408,11 +1283,10 @@ class MultiTkIp
end
# on IP thread
- if @cmd_receiver == Thread.current ||
- (!req_val && TclTkLib.mainloop_thread? != false) # callback
+ if (@cmd_receiver == Thread.current)
begin
- ret = cmd.call(safe_level, *args)
- rescue SystemExit => e
+ ret = cmd.call(*args)
+ rescue SystemExit
# exit IP
warn("Warning: "+ $! + " on " + self.inspect) if $DEBUG
begin
@@ -1427,18 +1301,6 @@ class MultiTkIp
((e.message.length > 0)? ' "' + e.message + '"': '') +
" on " + self.inspect)
end
-=begin
- begin
- bt = _toUTF8(e.backtrace.join("\n"))
- bt.instance_variable_set(:@encoding, 'utf-8')
- rescue Exception
- bt = e.backtrace.join("\n")
- end
- begin
- @interp._set_global_var('errorInfo', bt)
- rescue Exception
- end
-=end
ret = e
end
return ret
@@ -1450,7 +1312,7 @@ class MultiTkIp
@cmd_queue.enq([nil, cmd, *args])
rescue Exception => e
# ignore
- if $DEBUG
+ if $DEBUG || true
warn("Warning: " + e.class.inspect +
((e.message.length > 0)? ' "' + e.message + '"': '') +
" on " + self.inspect)
@@ -1474,7 +1336,7 @@ class MultiTkIp
self._eval_without_enc('exit')
rescue Exception
end
- if !self.deleted? && !safe? && allow_ruby_exit?
+ if !safe? && allow_ruby_exit?
self.delete
fail e
else
@@ -1492,25 +1354,35 @@ class MultiTkIp
end
private :eval_proc_core
+=begin
def eval_callback(*args)
if block_given?
- cmd = Proc.new
+ eval_proc_core(false, proc{$SAFE=@safe_level[0]; Proc.new}.call, *args)
else
- cmd = args.shift
+ eval_proc_core(false, *args)
end
- current = Thread.current
- backup_ip = current['callback_ip']
- current['callback_ip'] = self
- begin
- eval_proc_core(false, cmd, *args)
- ensure
- current['callback_ip'] = backup_ip
+ end
+=end
+ def eval_callback(*args)
+ if block_given?
+ eval_proc_core(false, Proc.new, *args)
+ else
+ eval_proc_core(false, *args)
end
end
+=begin
+ def eval_proc(*args)
+ if block_given?
+ eval_proc_core(true, proc{$SAFE=@safe_level[0]; Proc.new}.call, *args)
+ else
+ eval_proc_core(true, *args)
+ end
+ end
+=end
def eval_proc(*args)
# The scope of the eval-block of 'eval_proc' method is different from
- # the external. If you want to pass local values to the eval-block,
+ # the enternal. If you want to pass local values to the eval-block,
# use arguments of eval_proc method. They are passed to block-arguments.
if block_given?
cmd = Proc.new
@@ -1519,28 +1391,11 @@ class MultiTkIp
fail ArgumentError, "A Proc or Method object is expected for 1st argument"
end
end
- if TclTkLib.mainloop_thread? == true
- # call from eventloop
- current = Thread.current
- backup_ip = current['callback_ip']
- current['callback_ip'] = self
- begin
- eval_proc_core(false,
- proc{|safe, *params|
- $SAFE=safe if $SAFE < safe
- cmd.call(*params)
- }, *args)
- ensure
- current['callback_ip'] = backup_ip
- end
- else
- eval_proc_core(true,
- proc{|safe, *params|
- $SAFE=safe if $SAFE < safe
- Thread.new(*params, &cmd).value
- },
- *args)
- end
+ eval_proc_core(true,
+ proc{|safe, *params|
+ $SAFE=safe; Thread.new(*params, &cmd).value
+ },
+ *args)
end
alias call eval_proc
@@ -1553,19 +1408,14 @@ class MultiTkIp
end
end
Thread.new{
- eval_proc(cmd, *args)
-=begin
eval_proc_core(false,
proc{|safe, *params|
- $SAFE=safe if $SAFE < safe
- Thread.new(*params, &cmd).value
+ $SAFE=safe; Thread.new(*params, &cmd).value
},
- safe_level, *args)
-=end
+ *args)
}
end
alias background_eval_proc bg_eval_proc
- alias thread_eval_proc bg_eval_proc
alias bg_call bg_eval_proc
alias background_call bg_eval_proc
@@ -1575,25 +1425,18 @@ class MultiTkIp
raise RuntimeError, "A String object is expected for the 'cmd' argument"
end
- eval_proc_core(true,
- proc{|safe|
- Kernel.eval("$SAFE=#{safe} if $SAFE < #{safe};" << cmd,
- *eval_args)
- })
+ eval_proc_core(true, proc{|safe| $SAFE=safe; Kernel.eval(cmd, *eval_args)})
end
alias eval_str eval_string
- def bg_eval_string(cmd, *eval_args)
+ def bg_eval_string(*args)
# cmd string ==> proc
unless cmd.kind_of?(String)
raise RuntimeError, "A String object is expected for the 'cmd' argument"
end
Thread.new{
eval_proc_core(true,
- proc{|safe|
- Kernel.eval("$SAFE=#{safe} if $SAFE < #{safe};" << cmd,
- *eval_args)
- })
+ proc{|safe| $SAFE=safe; Kernel.eval(cmd, *eval_args)})
}
end
alias background_eval_string bg_eval_string
@@ -1603,10 +1446,28 @@ end
class << MultiTkIp
# class method
+=begin
+ def eval_proc(cmd = proc{$SAFE=__getip.safe_level; Proc.new}.call, *args)
+ # class ==> interp object
+ __getip.eval_proc(cmd, *args)
+ end
+=end
+=begin
+ def eval_proc(*args)
+ # class ==> interp object
+ if block_given?
+ __getip.eval_proc(proc{$SAFE=__getip.safe_level; Proc.new}.call, *args)
+ else
+ __getip.eval_proc(*args)
+ end
+ end
+=end
+#=begin
def eval_proc(*args, &blk)
# class ==> interp object
__getip.eval_proc(*args, &blk)
end
+#=end
alias call eval_proc
alias eval_string eval_proc
end
@@ -1686,18 +1547,10 @@ class << MultiTkIp
__getip.delete
end
- def deleted?
+ def deleteed?
__getip.deleted?
end
- def has_mainwindow?
- __getip.has_mainwindow?
- end
-
- def invalid_namespace?
- __getip.invalid_namespace?
- end
-
def abort(msg = nil)
__getip.abort(msg)
end
@@ -1745,11 +1598,11 @@ class << MultiTkIp
__getip._invoke_with_enc(*args)
end
- def _toUTF8(str, encoding=nil)
+ def _toUTF8(str, encoding)
__getip._toUTF8(str, encoding)
end
- def _fromUTF8(str, encoding=nil)
+ def _fromUTF8(str, encoding)
__getip._fromUTF8(str, encoding)
end
@@ -1812,10 +1665,6 @@ class << MultiTkIp
def _conv_listelement(arg)
__getip._conv_listelement(arg)
end
-
- def _create_console
- __getip._create_console
- end
end
@@ -1869,109 +1718,71 @@ end
# depend on TclTkIp
class MultiTkIp
- def mainloop(check_root = true, restart_on_dead = true)
+ def mainloop(check_root = true, restart_on_dead = false)
#return self if self.slave?
#return self if self != @@DEFAULT_MASTER
if self != @@DEFAULT_MASTER
if @wait_on_mainloop[0]
begin
- @wait_on_mainloop[1] += 1
- if $SAFE >= 4
- _receiver_mainloop(check_root).join
- else
- @cmd_queue.enq([@system, 'call_mainloop',
- Thread.current, check_root])
- Thread.stop
- end
+ @wait_on_mainloop[1] = true
+ @cmd_queue.enq([@system, 'call_mainloop',
+ Thread.current, check_root])
+ Thread.stop
rescue MultiTkIp_OK => ret
# return value
- if ret.value.kind_of?(Thread)
- return ret.value.value
- else
- return ret.value
- end
- rescue SystemExit => e
+ @wait_on_mainloop[1] = false
+ return ret.value.value
+ rescue SystemExit
# exit IP
warn("Warning: " + $! + " on " + self.inspect) if $DEBUG
+ @wait_on_mainloop[1] = false
begin
self._eval_without_enc('exit')
rescue Exception
end
self.delete
- rescue StandardError => e
+ rescue Exception => e
if $DEBUG
warn("Warning: " + e.class.inspect +
((e.message.length > 0)? ' "' + e.message + '"': '') +
" on " + self.inspect)
end
+ @wait_on_mainloop[1] = false
return e
- rescue Exception => e
- return e
ensure
- @wait_on_mainloop[1] -= 1
+ @wait_on_mainloop[1] = false
end
end
return
end
unless restart_on_dead
- @wait_on_mainloop[1] += 1
-=begin
- begin
- @interp.mainloop(check_root)
- rescue StandardError => e
- if $DEBUG
- warn("Warning: " + e.class.inspect +
- ((e.message.length > 0)? ' "' + e.message + '"': '') +
- " on " + self.inspect)
- end
- end
-=end
- begin
- @interp.mainloop(check_root)
- ensure
- @wait_on_mainloop[1] -= 1
- end
+ @wait_on_mainloop[1] = true
+ @interp.mainloop(check_root)
+ @wait_on_mainloop[1] = false
else
- loop do
- break unless self.alive?
- if check_root
- begin
- break if TclTkLib.num_of_mainwindows == 0
- rescue StandardError
- break
- end
- end
- break if @interp.deleted?
- begin
- @wait_on_mainloop[1] += 1
- @interp.mainloop(check_root)
- rescue StandardError => e
- if TclTkLib.mainloop_abort_on_exception != nil
- #STDERR.print("Warning: Tk mainloop receives ", $!.class.inspect,
- # " exception (ignore) : ", $!.message, "\n");
- if $DEBUG
- warn("Warning: Tk mainloop receives " << e.class.inspect <<
- " exception (ignore) : " << e.message);
- end
- end
- #raise e
- rescue Exception => e
-=begin
- if TclTkLib.mainloop_abort_on_exception != nil
- #STDERR.print("Warning: Tk mainloop receives ", $!.class.inspect,
- # " exception (ignore) : ", $!.message, "\n");
- if $DEBUG
- warn("Warning: Tk mainloop receives " << e.class.inspect <<
- " exception (ignore) : " << e.message);
+ begin
+ @wait_on_mainloop[1] = true
+ loop do
+ break unless self.alive?
+ if check_root
+ begin
+ break if TclTkLib.num_of_mainwindows == 0
+ rescue Exception
+ break
end
end
-=end
- raise e
- ensure
- @wait_on_mainloop[1] -= 1
- Thread.pass # avoid eventloop conflict
+ @interp.mainloop(check_root)
+ end
+ #rescue StandardError
+ rescue Exception
+ if TclTkLib.mainloop_abort_on_exception != nil
+ STDERR.print("Warning: Tk mainloop receives ", $!.class.inspect,
+ " exception (ignore) : ", $!.message, "\n");
end
+ retry
+ ensure
+ @wait_on_mainloop[1] = false
end
end
self
@@ -2007,11 +1818,7 @@ class MultiTkIp
end
=end
begin
- # subip._eval_without_enc("foreach i [after info] {after cancel $i}")
- unless subip.deleted?
- after_ids = subip._eval_without_enc("after info")
- subip._eval_without_enc("foreach i {#{after_ids}} {after cancel $i}")
- end
+ subip._eval_without_enc("foreach i [after info] {after cancel $i}")
rescue Exception
end
@@ -2040,22 +1847,21 @@ class MultiTkIp
}
begin
- # @interp._eval_without_enc("foreach i [after info] {after cancel $i}")
- after_ids = @interp._eval_without_enc("after info")
- @interp._eval_without_enc("foreach i {#{after_ids}} {after cancel $i}")
+ @interp._eval_without_enc("foreach i [after info] {after cancel $i}")
rescue Exception
end
-
+=begin
begin
@interp._invoke('destroy', '.') unless @interp.deleted?
rescue Exception
end
-
+=end
if @safe_base && !@interp.deleted?
# do 'exit' to call the delete_hook procedure
@interp._eval_without_enc('exit')
+ else
+ @interp.delete unless @interp.deleted?
end
- @interp.delete
self
end
@@ -2063,14 +1869,6 @@ class MultiTkIp
@interp.deleted?
end
- def has_mainwindow?
- @interp.has_mainwindow?
- end
-
- def invalid_namespace?
- @interp.invalid_namespace?
- end
-
def abort(msg = nil)
if master?
if msg
@@ -2146,11 +1944,11 @@ class MultiTkIp
@interp._invoke_with_enc(*args)
end
- def _toUTF8(str, encoding=nil)
+ def _toUTF8(str, encoding)
@interp._toUTF8(str, encoding)
end
- def _fromUTF8(str, encoding=nil)
+ def _fromUTF8(str, encoding)
@interp._fromUTF8(str, encoding)
end
@@ -2255,7 +2053,7 @@ class MultiTkIp
elsif slave.kind_of?(String)
slave
else
- slave.to_s
+ cmd_name.to_s
end
end
private :_slavearg
@@ -2355,61 +2153,20 @@ class MultiTkIp
end
def invoke_hidden(slave, cmd, *args)
- if args[-1].kind_of?(Hash)
- keys = _symbolkey2str(args.pop)
- else
- keys = []
- end
- keys << _slavearg(slave)
- if Tk::TCL_MAJOR_VERSION > 8 ||
- (Tk::TCL_MAJOR_VERSION == 8 && Tk::TCL_MINOR_VERSION >= 5)
- keys << '--'
- end
- keys << cmd
- keys.concat(args)
- @interp._invoke('interp', 'invokehidden', *keys)
+ @interp._invoke('interp', 'invokehidden', _slavearg(slave), cmd, *args)
end
def self.invoke_hidden(slave, cmd, *args)
__getip.invoke_hidden(slave, cmd, *args)
end
def invoke_hidden_on_global(slave, cmd, *args)
- if args[-1].kind_of?(Hash)
- keys = _symbolkey2str(args.pop)
- else
- keys = []
- end
- keys << _slavearg(slave)
- keys << '-global'
- if Tk::TCL_MAJOR_VERSION > 8 ||
- (Tk::TCL_MAJOR_VERSION == 8 && Tk::TCL_MINOR_VERSION >= 5)
- keys << '--'
- end
- keys << cmd
- keys.concat(args)
- @interp._invoke('interp', 'invokehidden', *keys)
+ @interp._invoke('interp', 'invokehidden', _slavearg(slave),
+ '-global', cmd, *args)
end
def self.invoke_hidden_on_global(slave, cmd, *args)
__getip.invoke_hidden_on_global(slave, cmd, *args)
end
- def invoke_hidden_on_namespace(slave, ns, cmd, *args)
- # for Tcl8.5 or later
- if args[-1].kind_of?(Hash)
- keys = _symbolkey2str(args.pop)
- else
- keys = []
- end
- keys << _slavearg(slave)
- keys << '-namespace' << TkComm._get_eval_string(ns)
- keys << '--' << cmd
- keys.concat(args)
- @interp._invoke('interp', 'invokehidden', *keys)
- end
- def self.invoke_hidden_on_namespace(slave, ns, cmd, *args)
- __getip.invoke_hidden_on_namespace(slave, ns, cmd, *args)
- end
-
def mark_trusted(slave = '')
@interp._invoke('interp', 'marktrusted', _slavearg(slave))
self
@@ -2419,58 +2176,6 @@ class MultiTkIp
self
end
- def set_bgerror_handler(cmd = Proc.new, slave = nil, &b)
- unless TkComm._callback_entry?(cmd)
- if !slave && b
- slave = cmd
- cmd = Proc.new(&b)
- end
- end
- slave = '' unless slave
-
- @interp._invoke('interp', 'bgerror', _slavearg(slave), cmd)
- end
- def self.bgerror(cmd = Proc.new, slave = nil, &b)
- __getip.bgerror(cmd, slave, &b)
- end
-
- def get_bgerror_handler(slave = '')
- procedure(@interp._invoke('interp', 'bgerror', _slavearg(slave)))
- end
- def self.bgerror(slave = '')
- __getip.bgerror(slave)
- end
-
- def set_limit(limit_type, slave = '', opts = {})
- @interp._invoke('interp', 'limit', _slavearg(slave), limit_type, opts)
- end
- def self.set_limit(limit_type, slave = '', opts = {})
- __getip.set_limit(limit_type, slave, opts)
- end
-
- def get_limit(limit_type, slave = '', slot = nil)
- if slot
- num_or_str(@interp._invoke('interp', 'limit', _slavearg(slave),
- limit_type, slot))
- else
- l = @interp._split_tklist(@interp._invoke_without_enc('interp', 'limit',
- _slavearg(slave),
- limit_type))
- l.map!{|s| _fromUTF8(s)}
- r = {}
- until l.empty?
- key = l.shift[1..-1]
- val = l.shift
- val = num_or_str(val) if val
- r[key] = val
- end
- r
- end
- end
- def self.get_limit(limit_type, slave = '', slot = nil)
- __getip.get_limit(limit_type, slave, slot)
- end
-
def recursion_limit(slave = '', limit = None)
number(@interp._invoke('interp', 'recursionlimit',
_slavearg(slave), limit))
diff --git a/ext/tk/lib/remote-tk.rb b/ext/tk/lib/remote-tk.rb
index 6e64a1ca2d..1ef5310bde 100644
--- a/ext/tk/lib/remote-tk.rb
+++ b/ext/tk/lib/remote-tk.rb
@@ -60,6 +60,8 @@ class << RemoteTkIp
end
class RemoteTkIp
+ include TkUtil
+
def initialize(remote_ip, displayof=nil, timeout=5)
if $SAFE >= 4
fail SecurityError, "cannot access another interpreter at level #{$SAFE}"
@@ -68,7 +70,7 @@ class RemoteTkIp
@interp = MultiTkIp.__getip
@interp.allow_ruby_exit = false
@appname = @interp._invoke('tk', 'appname')
- @remote = remote_ip.to_s.dup.freeze
+ @remote = remote_ip.dup.freeze
if displayof.kind_of?(TkWindow)
@displayof = displayof.path.dup.freeze
else
@@ -94,7 +96,7 @@ class RemoteTkIp
@safe_level = [$SAFE]
- @wait_on_mainloop = [true, 0]
+ @wait_on_mainloop = [true, false]
@cmd_queue = Queue.new
@@ -177,7 +179,7 @@ class RemoteTkIp
fail SecurityError, "cannot send tainted commands at level #{$SAFE}"
end
- cmds = @interp._merge_tklist(*TkUtil::_conv_args([], enc_mode, *cmds))
+ cmds = @interp._merge_tklist(*_conv_args([], enc_mode, *cmds))
if @displayof
if async
@interp.__invoke('send', '-async', '-displayof', @displayof,
@@ -273,31 +275,13 @@ class RemoteTkIp
else
lst = @interp._invoke_without_enc('winfo', 'interps')
end
- # unless @interp._split_tklist(lst).index(@remote)
- unless @interp._split_tklist(lst).index(_toUTF8(@remote))
+ unless @interp._split_tklist(lst).index(@remote)
true
else
false
end
end
- def has_mainwindow?
- begin
- inf = @interp._invoke_without_enc('info', 'command', '.')
- rescue Exception
- return nil
- end
- if !inf.kind_of?(String) || inf != '.'
- false
- else
- true
- end
- end
-
- def invalid_namespace?
- false
- end
-
def restart
fail RuntimeError, 'cannot restart the remote interpreter'
end
@@ -332,11 +316,11 @@ class RemoteTkIp
_appsend(true, false, *args)
end
- def _toUTF8(str, encoding=nil)
+ def _toUTF8(str, encoding)
@interp._toUTF8(str, encoding)
end
- def _fromUTF8(str, encoding=nil)
+ def _fromUTF8(str, encoding)
@interp._fromUTF8(str, encoding)
end
@@ -354,25 +338,25 @@ class RemoteTkIp
def _get_variable(var_name, flag)
# ignore flag
- _appsend(false, 'set', TkComm::_get_eval_string(var_name))
+ _appsend(false, 'set', _get_eval_string(var_name))
end
def _get_variable2(var_name, index_name, flag)
# ignore flag
- _appsend(false, 'set', "#{TkComm::_get_eval_string(var_name)}(#{TkComm::_get_eval_string(index_name)})")
+ _appsend(false, 'set', "#{_get_eval_string(var_name)}(#{_get_eval_string(index_name)})")
end
def _set_variable(var_name, value, flag)
# ignore flag
- _appsend(false, 'set', TkComm::_get_eval_string(var_name), TkComm::_get_eval_string(value))
+ _appsend(false, 'set', _get_eval_string(var_name), _get_eval_string(value))
end
def _set_variable2(var_name, index_name, value, flag)
# ignore flag
- _appsend(false, 'set', "#{TkComm::_get_eval_string(var_name)}(#{TkComm::_get_eval_string(index_name)})", TkComm::_get_eval_string(value))
+ _appsend(false, 'set', "#{_get_eval_string(var_name)}(#{_get_eval_string(index_name)})", _get_eval_string(value))
end
def _unset_variable(var_name, flag)
# ignore flag
- _appsend(false, 'unset', TkComm::_get_eval_string(var_name))
+ _appsend(false, 'unset', _get_eval_string(var_name))
end
def _unset_variable2(var_name, index_name, flag)
# ignore flag
@@ -380,21 +364,21 @@ class RemoteTkIp
end
def _get_global_var(var_name)
- _appsend(false, 'set', TkComm::_get_eval_string(var_name))
+ _appsend(false, 'set', _get_eval_string(var_name))
end
def _get_global_var2(var_name, index_name)
- _appsend(false, 'set', "#{TkComm::_get_eval_string(var_name)}(#{TkComm::_get_eval_string(index_name)})")
+ _appsend(false, 'set', "#{_get_eval_string(var_name)}(#{_get_eval_string(index_name)})")
end
def _set_global_var(var_name, value)
- _appsend(false, 'set', TkComm::_get_eval_string(var_name), TkComm::_get_eval_string(value))
+ _appsend(false, 'set', _get_eval_string(var_name), _get_eval_string(value))
end
def _set_global_var2(var_name, index_name, value)
- _appsend(false, 'set', "#{TkComm::_get_eval_string(var_name)}(#{TkComm::_get_eval_string(index_name)})", TkComm::_get_eval_string(value))
+ _appsend(false, 'set', "#{_get_eval_string(var_name)}(#{_get_eval_string(index_name)})", _get_eval_string(value))
end
def _unset_global_var(var_name)
- _appsend(false, 'unset', TkComm::_get_eval_string(var_name))
+ _appsend(false, 'unset', _get_eval_string(var_name))
end
def _unset_global_var2(var_name, index_name)
_appsend(false, 'unset', "#{var_name}(#{index_name})")
@@ -412,10 +396,6 @@ class RemoteTkIp
@interp._conv_listelement(str)
end
- def _create_console
- fail RuntimeError, 'not support "_create_console" on the remote interpreter'
- end
-
def mainloop
fail RuntimeError, 'not support "mainloop" on the remote interpreter'
end
diff --git a/ext/tk/lib/tk.rb b/ext/tk/lib/tk.rb
index 7e501753e2..807ccd2285 100644
--- a/ext/tk/lib/tk.rb
+++ b/ext/tk/lib/tk.rb
@@ -219,12 +219,8 @@ module TkComm
val.gsub(/\\ /, ' ')
when /[^\\] /
if listobj
- #tk_split_escstr(val).collect{|elt|
- # tk_tcl2ruby(elt, enc_mode, listobj)
- #}
- val = _toUTF8(val) unless enc_mode
- tk_split_escstr(val, false, false).collect{|elt|
- tk_tcl2ruby(elt, true, listobj)
+ tk_split_escstr(val).collect{|elt|
+ tk_tcl2ruby(elt, enc_mode, listobj)
}
elsif enc_mode
_fromUTF8(val)
@@ -253,20 +249,13 @@ if USE_TCLs_LIST_FUNCTIONS
# use Tcl function version of split_list
###########################################################################
- def tk_split_escstr(str, src_enc=true, dst_enc=true)
- str = _toUTF8(str) if src_enc
- if dst_enc
- TkCore::INTERP._split_tklist(str).map!{|s| _fromUTF8(s)}
- else
- TkCore::INTERP._split_tklist(str)
- end
+ def tk_split_escstr(str)
+ TkCore::INTERP._split_tklist(str)
end
- def tk_split_sublist(str, depth=-1, src_enc=true, dst_enc=true)
+ def tk_split_sublist(str, depth=-1)
# return [] if str == ""
# list = TkCore::INTERP._split_tklist(str)
- str = _toUTF8(str) if src_enc
-
if depth == 0
return "" if str == ""
list = [str]
@@ -275,82 +264,45 @@ if USE_TCLs_LIST_FUNCTIONS
list = TkCore::INTERP._split_tklist(str)
end
if list.size == 1
- # tk_tcl2ruby(list[0], nil, false)
- tk_tcl2ruby(list[0], dst_enc, false)
+ tk_tcl2ruby(list[0], nil, false)
else
- list.collect{|token| tk_split_sublist(token, depth - 1, false, dst_enc)}
+ list.collect{|token| tk_split_sublist(token, depth - 1)}
end
end
- def tk_split_list(str, depth=0, src_enc=true, dst_enc=true)
+ def tk_split_list(str, depth=0)
return [] if str == ""
- str = _toUTF8(str) if src_enc
- TkCore::INTERP._split_tklist(str).map!{|token|
- tk_split_sublist(token, depth - 1, false, dst_enc)
+ TkCore::INTERP._split_tklist(str).collect{|token|
+ tk_split_sublist(token, depth - 1)
}
end
- def tk_split_simplelist(str, src_enc=true, dst_enc=true)
+ def tk_split_simplelist(str)
#lst = TkCore::INTERP._split_tklist(str)
#if (lst.size == 1 && lst =~ /^\{.*\}$/)
# TkCore::INTERP._split_tklist(str[1..-2])
#else
# lst
#end
-
- str = _toUTF8(str) if src_enc
- if dst_enc
- TkCore::INTERP._split_tklist(str).map!{|s| _fromUTF8(s)}
- else
- TkCore::INTERP._split_tklist(str)
- end
+ TkCore::INTERP._split_tklist(str)
end
- def array2tk_list(ary, enc=nil)
+ def array2tk_list(ary)
return "" if ary.size == 0
- sys_enc = TkCore::INTERP.encoding
- sys_enc = TclTkLib.encoding_system unless sys_enc
-
- dst_enc = (enc == nil)? sys_enc: enc
-
dst = ary.collect{|e|
if e.kind_of? Array
- s = array2tk_list(e, enc)
+ array2tk_list(e)
elsif e.kind_of? Hash
tmp_ary = []
#e.each{|k,v| tmp_ary << k << v }
e.each{|k,v| tmp_ary << "-#{_get_eval_string(k)}" << v }
- s = array2tk_list(tmp_ary, enc)
+ array2tk_list(tmp_ary)
else
- s = _get_eval_string(e, enc)
- end
-
- if dst_enc != true && dst_enc != false
- if (s_enc = s.instance_variable_get(:@encoding))
- s_enc = s_enc.to_s
- else
- s_enc = sys_enc
- end
- dst_enc = true if s_enc != dst_enc
+ _get_eval_string(e)
end
-
- s
}
-
- if sys_enc && dst_enc
- dst.map!{|s| _toUTF8(s)}
- ret = TkCore::INTERP._merge_tklist(*dst)
- if dst_enc.kind_of?(String)
- ret = _fromUTF8(ret, dst_enc)
- ret.instance_variable_set(:@encoding, dst_enc)
- else
- ret.instance_variable_set(:@encoding, 'utf-8')
- end
- ret
- else
- TkCore::INTERP._merge_tklist(*dst)
- end
+ TkCore::INTERP._merge_tklist(*dst)
end
else
@@ -358,7 +310,7 @@ else
# use Ruby script version of split_list (traditional methods)
###########################################################################
- def tk_split_escstr(str, src_enc=true, dst_enc=true)
+ def tk_split_escstr(str)
return [] if str == ""
list = []
token = nil
@@ -379,7 +331,7 @@ else
list
end
- def tk_split_sublist(str, depth=-1, src_enc=true, dst_enc=true)
+ def tk_split_sublist(str, depth=-1)
#return [] if str == ""
#return [tk_split_sublist(str[1..-2])] if str =~ /^\{.*\}$/
#list = tk_split_escstr(str)
@@ -399,11 +351,9 @@ else
end
end
- def tk_split_list(str, depth=0, src_enc=true, dst_enc=true)
+ def tk_split_list(str, depth=0)
return [] if str == ""
- tk_split_escstr(str).collect{|token|
- tk_split_sublist(token, depth - 1)
- }
+ tk_split_escstr(str).collect{|token| tk_split_sublist(token, depth - 1)}
end
=begin
def tk_split_list(str)
@@ -446,7 +396,7 @@ else
end
=end
- def tk_split_simplelist(str, src_enc=true, dst_enc=true)
+ def tk_split_simplelist(str)
return [] if str == ""
list = []
token = nil
@@ -472,16 +422,16 @@ else
list
end
- def array2tk_list(ary, enc=nil)
+ def array2tk_list(ary)
ary.collect{|e|
if e.kind_of? Array
- "{#{array2tk_list(e, enc)}}"
+ "{#{array2tk_list(e)}}"
elsif e.kind_of? Hash
# "{#{e.to_a.collect{|ee| array2tk_list(ee)}.join(' ')}}"
e.each{|k,v| tmp_ary << "-#{_get_eval_string(k)}" << v }
- array2tk_list(tmp_ary, enc)
+ array2tk_list(tmp_ary)
else
- s = _get_eval_string(e, enc)
+ s = _get_eval_string(e)
(s.index(/\s/) || s.size == 0)? "{#{s}}": s
end
}.join(" ")
@@ -498,7 +448,7 @@ end
private_class_method :tk_split_escstr, :tk_split_sublist
private_class_method :tk_split_list, :tk_split_simplelist
-# private_class_method :array2tk_list
+ private_class_method :array2tk_list
=begin
### --> definition is moved to TkUtil module
@@ -578,11 +528,11 @@ end
end
=end
- def list(val, depth=0, enc=true)
- tk_split_list(val, depth, enc, enc)
+ def list(val, depth=0)
+ tk_split_list(val, depth)
end
- def simplelist(val, src_enc=true, dst_enc=true)
- tk_split_simplelist(val, src_enc, dst_enc)
+ def simplelist(val)
+ tk_split_simplelist(val)
end
def window(val)
if val =~ /^\./
@@ -615,15 +565,6 @@ end
module_function :bool, :number, :num_or_str, :string
module_function :list, :simplelist, :window, :image_obj, :procedure
- def subst(str, *opts)
- # opts := :nobackslashes | :nocommands | novariables
- tk_call('subst',
- *(opts.collect{|opt|
- opt = opt.to_s
- (opt[0] == ?-)? opt: '-' << opt
- } << str))
- end
-
def _toUTF8(str, encoding = nil)
TkCore::INTERP._toUTF8(str, encoding)
end
@@ -633,18 +574,6 @@ end
private :_toUTF8, :_fromUTF8
module_function :_toUTF8, :_fromUTF8
- def _callback_entry_class?(cls)
- cls <= Proc || cls <= Method || cls <= TkCallbackEntry
- end
- private :_callback_entry_class?
- module_function :_callback_entry_class?
-
- def _callback_entry?(obj)
- obj.kind_of?(Proc) || obj.kind_of?(Method) || obj.kind_of?(TkCallbackEntry)
- end
- private :_callback_entry?
- module_function :_callback_entry?
-
=begin
### --> definition is moved to TkUtil module
def _get_eval_string(str, enc_mode = nil)
@@ -889,8 +818,8 @@ module TkComm
end
end
- def _bind_core(mode, what, context, cmd, *args)
- id = install_bind(cmd, *args) if cmd
+ def _bind_core(mode, what, context, cmd, args=nil)
+ id = install_bind(cmd, args) if cmd
begin
tk_call_without_enc(*(what + ["<#{tk_event_sequence(context)}>",
mode + id]))
@@ -900,12 +829,12 @@ module TkComm
end
end
- def _bind(what, context, cmd, *args)
- _bind_core('', what, context, cmd, *args)
+ def _bind(what, context, cmd, args=nil)
+ _bind_core('', what, context, cmd, args)
end
- def _bind_append(what, context, cmd, *args)
- _bind_core('+', what, context, cmd, *args)
+ def _bind_append(what, context, cmd, args=nil)
+ _bind_core('+', what, context, cmd, args)
end
def _bind_remove(what, context)
@@ -939,8 +868,8 @@ module TkComm
end
end
- def _bind_core_for_event_class(klass, mode, what, context, cmd, *args)
- id = install_bind_for_event_class(klass, cmd, *args) if cmd
+ def _bind_core_for_event_class(klass, mode, what, context, cmd, args=nil)
+ id = install_bind_for_event_class(klass, cmd, args) if cmd
begin
tk_call_without_enc(*(what + ["<#{tk_event_sequence(context)}>",
mode + id]))
@@ -950,12 +879,12 @@ module TkComm
end
end
- def _bind_for_event_class(klass, what, context, cmd, *args)
- _bind_core_for_event_class(klass, '', what, context, cmd, *args)
+ def _bind_for_event_class(klass, what, context, cmd, args=nil)
+ _bind_core_for_event_class(klass, '', what, context, cmd, args)
end
- def _bind_append_for_event_class(klass, what, context, cmd, *args)
- _bind_core_for_event_class(klass, '+', what, context, cmd, *args)
+ def _bind_append_for_event_class(klass, what, context, cmd, args=nil)
+ _bind_core_for_event_class(klass, '+', what, context, cmd, args)
end
def _bind_remove_for_event_class(klass, what, context)
@@ -972,33 +901,13 @@ module TkComm
:_bind_append_for_event_class, :_bind_remove_for_event_class,
:_bindinfo_for_event_class
- #def bind(tagOrClass, context, cmd=Proc.new, *args)
- # _bind(["bind", tagOrClass], context, cmd, *args)
- # tagOrClass
- #end
- def bind(tagOrClass, context, *args)
- # if args[0].kind_of?(Proc) || args[0].kind_of?(Method)
- if TkComm._callback_entry?(args[0]) || !block_given?
- cmd = args.shift
- else
- cmd = Proc.new
- end
- _bind(["bind", tagOrClass], context, cmd, *args)
+ def bind(tagOrClass, context, cmd=Proc.new, args=nil)
+ _bind(["bind", tagOrClass], context, cmd, args)
tagOrClass
end
- #def bind_append(tagOrClass, context, cmd=Proc.new, *args)
- # _bind_append(["bind", tagOrClass], context, cmd, *args)
- # tagOrClass
- #end
- def bind_append(tagOrClass, context, *args)
- # if args[0].kind_of?(Proc) || args[0].kind_of?(Method)
- if TkComm._callback_entry?(args[0]) || !block_given?
- cmd = args.shift
- else
- cmd = Proc.new
- end
- _bind_append(["bind", tagOrClass], context, cmd, *args)
+ def bind_append(tagOrClass, context, cmd=Proc.new, args=nil)
+ _bind_append(["bind", tagOrClass], context, cmd, args)
tagOrClass
end
@@ -1011,33 +920,13 @@ module TkComm
_bindinfo(['bind', tagOrClass], context)
end
- #def bind_all(context, cmd=Proc.new, *args)
- # _bind(['bind', 'all'], context, cmd, *args)
- # TkBindTag::ALL
- #end
- def bind_all(context, *args)
- # if args[0].kind_of?(Proc) || args[0].kind_of?(Method)
- if TkComm._callback_entry?(args[0]) || !block_given?
- cmd = args.shift
- else
- cmd = Proc.new
- end
- _bind(['bind', 'all'], context, cmd, *args)
+ def bind_all(context, cmd=Proc.new, args=nil)
+ _bind(['bind', 'all'], context, cmd, args)
TkBindTag::ALL
end
- #def bind_append_all(context, cmd=Proc.new, *args)
- # _bind_append(['bind', 'all'], context, cmd, *args)
- # TkBindTag::ALL
- #end
- def bind_append_all(context, *args)
- # if args[0].kind_of?(Proc) || args[0].kind_of?(Method)
- if TkComm._callback_entry?(args[0]) || !block_given?
- cmd = args.shift
- else
- cmd = Proc.new
- end
- _bind_append(['bind', 'all'], context, cmd, *args)
+ def bind_append_all(context, cmd=Proc.new, args=nil)
+ _bind_append(['bind', 'all'], context, cmd, args)
TkBindTag::ALL
end
@@ -1171,22 +1060,21 @@ module TkCore
WIDGET_DESTROY_HOOK = '<WIDGET_DESTROY_HOOK>'
INTERP._invoke_without_enc('event', 'add',
- "<#{WIDGET_DESTROY_HOOK}>", '<Destroy>')
+ "<#{WIDGET_DESTROY_HOOK}>", 'Destroy')
INTERP._invoke_without_enc('bind', 'all', "<#{WIDGET_DESTROY_HOOK}>",
- install_cmd(proc{|path|
+ install_bind(proc{|xpath|
+ path = xpath[1..-1]
unless TkCore::INTERP.deleted?
- begin
- if (widget=TkCore::INTERP.tk_windows[path])
- if widget.respond_to?(:__destroy_hook__)
+ if (widget = TkCore::INTERP.tk_windows[path])
+ if widget.respond_to?(:__destroy_hook__)
+ begin
widget.__destroy_hook__
+ rescue Exception
end
end
- rescue Exception=>e
- p e if $DEBUG
end
end
- }) << ' %W')
-
+ }, 'x%W'))
INTERP.add_tk_procs(TclTkLib::FINALIZE_PROC_NAME, '',
"bind all <#{WIDGET_DESTROY_HOOK}> {}")
@@ -1241,24 +1129,11 @@ module TkCore
def TkCore.callback(*arg)
begin
- if TkCore::INTERP.tk_cmd_tbl.kind_of?(Hash)
- #TkCore::INTERP.tk_cmd_tbl[arg.shift].call(*arg)
- normal_ret = false
- ret = catch(:IRB_EXIT) do # IRB hack
- retval = TkCore::INTERP.tk_cmd_tbl[arg.shift].call(*arg)
- normal_ret = true
- retval
- end
- unless normal_ret
- # catch IRB_EXIT
- exit(ret)
- end
- ret
- end
- rescue SystemExit=>e
- exit(e.status)
- rescue Interrupt=>e
- fail(e)
+ TkCore::INTERP.tk_cmd_tbl[arg.shift].call(*arg)
+ rescue SystemExit
+ exit(0)
+ rescue Interrupt
+ exit!(1)
rescue Exception => e
begin
msg = _toUTF8(e.class.inspect) + ': ' +
@@ -1273,8 +1148,6 @@ module TkCore
e.backtrace.join("\n") +
"\n---< backtrace of Tk side >-------"
end
- # TkCore::INTERP._set_global_var('errorInfo', msg)
- # fail(e)
fail(e, msg)
end
end
@@ -1357,10 +1230,6 @@ module TkCore
tk_call_without_enc('after','idle',cmdid)
end
- def after_cancel(afterId)
- tk_call_without_enc('after','cancel',afterId)
- end
-
def windowingsystem
tk_call_without_enc('tk', 'windowingsystem')
end
@@ -1380,19 +1249,6 @@ module TkCore
end
end
- def inactive
- Integer(tk_call_without_enc('tk', 'inactive'))
- end
- def inactive_displayof(win)
- Integer(tk_call_without_enc('tk', 'inactive', '-displayof', win))
- end
- def reset_inactive
- tk_call_without_enc('tk', 'inactive', 'reset')
- end
- def reset_inactive_displayof(win)
- tk_call_without_enc('tk', 'inactive', '-displayof', win, 'reset')
- end
-
def appname(name=None)
tk_call('tk', 'appname', name)
end
@@ -1481,22 +1337,6 @@ module TkCore
TclTkLib.mainloop(check_root)
end
- def mainloop_thread?
- # true : current thread is mainloop
- # nil : there is no mainloop
- # false : mainloop is running on the other thread
- # ( At then, it is dangerous to call Tk interpreter directly. )
- TclTkLib.mainloop_thread?
- end
-
- def mainloop_exist?
- TclTkLib.mainloop_thread? != nil
- end
-
- def is_mainloop?
- TclTkLib.mainloop_thread? == true
- end
-
def mainloop_watchdog(check_root = true)
# watchdog restarts mainloop when mainloop is dead
TclTkLib.mainloop_watchdog(check_root)
@@ -1543,16 +1383,14 @@ module TkCore
nil
end
- def event_generate(win, context, keys=nil)
- #win = win.path if win.kind_of?(TkObject)
- if context.kind_of?(TkEvent::Event)
- context.generate(win, ((keys)? keys: {}))
- elsif keys
- tk_call_without_enc('event', 'generate', win,
+ def event_generate(window, context, keys=nil)
+ #window = window.path if window.kind_of?(TkObject)
+ if keys
+ tk_call_without_enc('event', 'generate', window,
"<#{tk_event_sequence(context)}>",
*hash_kv(keys, true))
else
- tk_call_without_enc('event', 'generate', win,
+ tk_call_without_enc('event', 'generate', window,
"<#{tk_event_sequence(context)}>")
end
nil
@@ -1565,16 +1403,10 @@ module TkCore
def getOpenFile(keys = nil)
tk_call('tk_getOpenFile', *hash_kv(keys))
end
- def getMultipleOpenFile(keys = nil)
- simplelist(tk_call('tk_getOpenFile', '-multiple', '1', *hash_kv(keys)))
- end
def getSaveFile(keys = nil)
tk_call('tk_getSaveFile', *hash_kv(keys))
end
- def getMultipleSaveFile(keys = nil)
- simplelist(tk_call('tk_getSaveFile', '-multiple', '1', *hash_kv(keys)))
- end
def chooseColor(keys = nil)
tk_call('tk_chooseColor', *hash_kv(keys))
@@ -1685,41 +1517,6 @@ module TkCore
def tk_call_with_enc(*args)
_tk_call_core(true, *args)
end
-
- def _tk_call_to_list_core(depth, arg_enc, val_enc, *args)
- args = _conv_args([], arg_enc, *args)
- val = _tk_call_core(false, *args)
- if !depth.kind_of?(Integer) || depth == 0
- tk_split_simplelist(val, false, val_enc)
- else
- tk_split_list(val, depth, false, val_enc)
- end
- end
- #private :_tk_call_to_list_core
-
- def tk_call_to_list(*args)
- _tk_call_to_list_core(-1, nil, true, *args)
- end
-
- def tk_call_to_list_without_enc(*args)
- _tk_call_to_list_core(-1, false, false, *args)
- end
-
- def tk_call_to_list_with_enc(*args)
- _tk_call_to_list_core(-1, true, true, *args)
- end
-
- def tk_call_to_simplelist(*args)
- _tk_call_to_list_core(0, nil, true, *args)
- end
-
- def tk_call_to_simplelist_without_enc(*args)
- _tk_call_to_list_core(0, false, false, *args)
- end
-
- def tk_call_to_simplelist_with_enc(*args)
- _tk_call_to_list_core(0, true, true, *args)
- end
end
@@ -1833,10 +1630,6 @@ module Tk
code
end
- def Tk.has_mainwindow?
- INTERP.has_mainwindow?
- end
-
def root
TkRoot.new
end
@@ -1884,14 +1677,7 @@ module Tk
end
def Tk.destroy(*wins)
- #tk_call_without_enc('destroy', *wins)
- tk_call_without_enc('destroy', *(wins.collect{|win|
- if win.kind_of?(TkWindow)
- win.epath
- else
- win
- end
- }))
+ tk_call_without_enc('destroy', *wins)
end
def Tk.exit
@@ -1899,34 +1685,13 @@ module Tk
end
def Tk.pack(*args)
- TkPack.configure(*args)
- end
- def Tk.pack_forget(*args)
- TkPack.forget(*args)
- end
- def Tk.unpack(*args)
- TkPack.forget(*args)
+ #TkPack.configure(*args)
+ TkPack(*args)
end
def Tk.grid(*args)
TkGrid.configure(*args)
end
- def Tk.grid_forget(*args)
- TkGrid.forget(*args)
- end
- def Tk.ungrid(*args)
- TkGrid.forget(*args)
- end
-
- def Tk.place(*args)
- TkPlace.configure(*args)
- end
- def Tk.place_forget(*args)
- TkPlace.forget(*args)
- end
- def Tk.unplace(*args)
- TkPlace.forget(*args)
- end
def Tk.update(idle=nil)
if idle
@@ -1944,10 +1709,8 @@ module Tk
self
end
- # NOTE::
- # If no eventloop-thread is running, "thread_update" method is same
- # to "update" method. Else, "thread_update" method waits to complete
- # idletask operation on the eventloop-thread.
+=begin
+ # See tcltklib.c for the reason of why the following methods are disabled.
def Tk.thread_update(idle=nil)
if idle
tk_call_without_enc('thread_update', 'idletasks')
@@ -1958,15 +1721,7 @@ module Tk
def Tk.thread_update_idletasks
thread_update(true)
end
-
- def Tk.lower_window(win, below=None)
- tk_call('lower', _epath(win), _epath(below))
- nil
- end
- def Tk.raise_window(win, above=None)
- tk_call('raise', _epath(win), _epath(above))
- nil
- end
+=end
def Tk.current_grabs(win = nil)
if win
@@ -2004,8 +1759,8 @@ module Tk
TkManageFocus.prev(win)
end
- def Tk.strictMotif(mode=None)
- bool(tk_call_without_enc('set', 'tk_strictMotif', mode))
+ def Tk.strictMotif(bool=None)
+ bool(tk_call_without_enc('set', 'tk_strictMotif', bool))
end
def Tk.show_kinsoku(mode='both')
@@ -2197,15 +1952,6 @@ if (/^(8\.[1-9]|9\.|[1-9][0-9])/ =~ Tk::TCL_VERSION && !Tk::JAPANIZED_TK)
=end
end
- module TclTkLib
- def self.encoding=(name)
- TkCore::INTERP.encoding = name
- end
- def self.encoding
- TkCore::INTERP.encoding
- end
- end
-
module Tk
module Encoding
extend Encoding
@@ -2233,13 +1979,10 @@ if (/^(8\.[1-9]|9\.|[1-9][0-9])/ =~ Tk::TCL_VERSION && !Tk::JAPANIZED_TK)
end
def encoding_convertfrom(str, enc=nil)
- # str is an usual enc string or a Tcl's internal string expression
- # in enc (which is returned from 'encoding_convertto' method).
+ # str must be a Tcl's internal string expression in enc.
# the return value is a UTF-8 string.
enc = encoding_system unless enc
- ret = TkCore::INTERP.__invoke('encoding', 'convertfrom', enc, str)
- ret.instance_variable_set('@encoding', 'utf-8')
- ret
+ TkCore::INTERP.__invoke('encoding', 'convertfrom', enc, str)
end
alias encoding_convert_from encoding_convertfrom
@@ -2248,9 +1991,7 @@ if (/^(8\.[1-9]|9\.|[1-9][0-9])/ =~ Tk::TCL_VERSION && !Tk::JAPANIZED_TK)
# The return value is a Tcl's internal string expression in enc.
# To get an usual enc string, use Tk.fromUTF8(ret_val, enc).
enc = encoding_system unless enc
- ret = TkCore::INTERP.__invoke('encoding', 'convertto', enc, str)
- ret.instance_variable_set('@encoding', 'binary')
- ret
+ TkCore::INTERP.__invoke('encoding', 'convertto', enc, str)
end
alias encoding_convert_to encoding_convertto
end
@@ -2262,39 +2003,21 @@ if (/^(8\.[1-9]|9\.|[1-9][0-9])/ =~ Tk::TCL_VERSION && !Tk::JAPANIZED_TK)
case $KCODE
when /^e/i # EUC
Tk.encoding = 'euc-jp'
- Tk.encoding_system = 'euc-jp'
when /^s/i # SJIS
- begin
- if Tk.encoding_system == 'cp932'
- Tk.encoding = 'cp932'
- else
- Tk.encoding = 'shiftjis'
- Tk.encoding_system = 'shiftjis'
- end
- rescue StandardError, NameError
- Tk.encoding = 'shiftjis'
- Tk.encoding_system = 'shiftjis'
- end
+ Tk.encoding = 'shiftjis'
when /^u/i # UTF8
Tk.encoding = 'utf-8'
- Tk.encoding_system = 'utf-8'
else # NONE
- if defined? DEFAULT_TK_ENCODING
- Tk.encoding_system = DEFAULT_TK_ENCODING
- end
begin
Tk.encoding = Tk.encoding_system
rescue StandardError, NameError
Tk.encoding = 'utf-8'
- Tk.encoding_system = 'utf-8'
end
end
else
# dummy methods
class TclTkIp
- attr_accessor :encoding
-
alias __eval _eval
alias __invoke _invoke
@@ -2332,37 +2055,17 @@ else
end
alias encoding_convert_to encoding_convertto
end
-
- extend Encoding
end
end
module TkBindCore
- #def bind(context, cmd=Proc.new, *args)
- # Tk.bind(self, context, cmd, *args)
- #end
- def bind(context, *args)
- # if args[0].kind_of?(Proc) || args[0].kind_of?(Method)
- if TkComm._callback_entry?(args[0]) || !block_given?
- cmd = args.shift
- else
- cmd = Proc.new
- end
- Tk.bind(self, context, cmd, *args)
+ def bind(context, cmd=Proc.new, args=nil)
+ Tk.bind(self, context, cmd, args)
end
- #def bind_append(context, cmd=Proc.new, *args)
- # Tk.bind_append(self, context, cmd, *args)
- #end
- def bind_append(context, *args)
- # if args[0].kind_of?(Proc) || args[0].kind_of?(Method)
- if TkComm._callback_entry?(args[0]) || !block_given?
- cmd = args.shift
- else
- cmd = Proc.new
- end
- Tk.bind_append(self, context, cmd, *args)
+ def bind_append(context, cmd=Proc.new, args=nil)
+ Tk.bind_append(self, context, cmd, args)
end
def bind_remove(context)
@@ -2586,18 +2289,18 @@ module TkTreatFont
self
end
- def font_copy(win, wintag=nil, winkey=nil, targetkey=nil)
+ def font_copy(window, wintag=nil, winkey=nil, targetkey=nil)
if wintag
if winkey
- fnt = win.tagfontobj(wintag, winkey).dup
+ fnt = window.tagfontobj(wintag, winkey).dup
else
- fnt = win.tagfontobj(wintag).dup
+ fnt = window.tagfontobj(wintag).dup
end
else
if winkey
- fnt = win.fontobj(winkey).dup
+ fnt = window.fontobj(winkey).dup
else
- fnt = win.fontobj.dup
+ fnt = window.fontobj.dup
end
end
@@ -2609,7 +2312,7 @@ module TkTreatFont
self
end
- def latinfont_copy(win, wintag=nil, winkey=nil, targetkey=nil)
+ def latinfont_copy(window, wintag=nil, winkey=nil, targetkey=nil)
if targetkey
fontobj(targetkey).dup.call_font_configure([__pathname, targetkey],
*(__config_cmd << {}))
@@ -2619,22 +2322,22 @@ module TkTreatFont
if wintag
if winkey
- fontobj.latin_replace(win.tagfontobj(wintag, winkey).latin_font_id)
+ fontobj.latin_replace(window.tagfontobj(wintag, winkey).latin_font_id)
else
- fontobj.latin_replace(win.tagfontobj(wintag).latin_font_id)
+ fontobj.latin_replace(window.tagfontobj(wintag).latin_font_id)
end
else
if winkey
- fontobj.latin_replace(win.fontobj(winkey).latin_font_id)
+ fontobj.latin_replace(window.fontobj(winkey).latin_font_id)
else
- fontobj.latin_replace(win.fontobj.latin_font_id)
+ fontobj.latin_replace(window.fontobj.latin_font_id)
end
end
self
end
alias asciifont_copy latinfont_copy
- def kanjifont_copy(win, wintag=nil, winkey=nil, targetkey=nil)
+ def kanjifont_copy(window, wintag=nil, winkey=nil, targetkey=nil)
if targetkey
fontobj(targetkey).dup.call_font_configure([__pathname, targetkey],
*(__config_cmd << {}))
@@ -2644,15 +2347,15 @@ module TkTreatFont
if wintag
if winkey
- fontobj.kanji_replace(win.tagfontobj(wintag, winkey).kanji_font_id)
+ fontobj.kanji_replace(window.tagfontobj(wintag, winkey).kanji_font_id)
else
- fontobj.kanji_replace(win.tagfontobj(wintag).kanji_font_id)
+ fontobj.kanji_replace(window.tagfontobj(wintag).kanji_font_id)
end
else
if winkey
- fontobj.kanji_replace(win.fontobj(winkey).kanji_font_id)
+ fontobj.kanji_replace(window.fontobj(winkey).kanji_font_id)
else
- fontobj.kanji_replace(win.fontobj.kanji_font_id)
+ fontobj.kanji_replace(window.fontobj.kanji_font_id)
end
end
self
@@ -2696,18 +2399,12 @@ module TkConfigMethod
private :__numstrval_optkeys
def __boolval_optkeys
- ['exportselection', 'jump', 'setgrid', 'takefocus']
+ []
end
private :__boolval_optkeys
def __strval_optkeys
- [
- 'text', 'label', 'show', 'data', 'file',
- 'activebackground', 'activeforeground', 'background',
- 'disabledforeground', 'disabledbackground', 'foreground',
- 'highlightbackground', 'highlightcolor', 'insertbackground',
- 'selectbackground', 'selectforeground', 'troughcolor'
- ]
+ ['text', 'label', 'show', 'data', 'file']
end
private :__strval_optkeys
@@ -2721,29 +2418,7 @@ module TkConfigMethod
end
private :__numlistval_optkeys
- def __tkvariable_optkeys
- ['variable', 'textvariable']
- end
- private :__tkvariable_optkeys
-
- def __val2ruby_optkeys # { key=>proc, ... }
- # The method is used to convert a opt-value to a ruby's object.
- # When get the value of the option "key", "proc.call(value)" is called.
- {}
- end
- private :__val2ruby_optkeys
-
- def __ruby2val_optkeys # { key=>proc, ... }
- # The method is used to convert a ruby's object to a opt-value.
- # When set the value of the option "key", "proc.call(value)" is called.
- # That is, "-#{key} #{proc.call(value)}".
- {}
- end
- private :__ruby2val_optkeys
-
def __methodcall_optkeys # { key=>method, ... }
- # The method is used to both of get and set.
- # Usually, the 'key' will not be a widget option.
{}
end
private :__methodcall_optkeys
@@ -2791,22 +2466,7 @@ module TkConfigMethod
end
def cget(slot)
- orig_slot = slot
slot = slot.to_s
-
- if slot.length == 0
- fail ArgumentError, "Invalid option `#{orig_slot.inspect}'"
- end
-
- if ( method = _symbolkey2str(__val2ruby_optkeys())[slot] )
- optval = tk_call_without_enc(*(__cget_cmd << "-#{slot}"))
- begin
- return method.call(optval)
- rescue => e
- warn("Warning:: #{e.message} (when #{method}.call(#{optval.inspect})") if $DEBUG
- return optval
- end
- end
if ( method = _symbolkey2str(__methodcall_optkeys)[slot] )
return self.__send__(method)
@@ -2858,10 +2518,6 @@ module TkConfigMethod
fnt
end
- when /^(#{__tkvariable_optkeys.join('|')})$/
- v = tk_call_without_enc(*(__cget_cmd << "-#{slot}"))
- (v.empty?)? nil: TkVarAccess.new(v)
-
else
tk_tcl2ruby(tk_call_without_enc(*(__cget_cmd << "-#{slot}")), true)
end
@@ -2876,11 +2532,6 @@ module TkConfigMethod
self.__send__(method, value) if value
}
- __ruby2val_optkeys.each{|key, method|
- key = key.to_s
- slot[key] = method.call(slot[key]) if slot.has_key?(key)
- }
-
__keyonly_optkeys.each{|defkey, undefkey|
conf = slot.find{|kk, vv| kk == defkey.to_s}
if conf
@@ -2901,12 +2552,7 @@ module TkConfigMethod
end
else
- orig_slot = slot
slot = slot.to_s
- if slot.length == 0
- fail ArgumentError, "Invalid option `#{orig_slot.inspect}'"
- end
-
if ( conf = __keyonly_optkeys.find{|k, v| k.to_s == slot} )
defkey, undefkey = conf
if value
@@ -2914,8 +2560,6 @@ module TkConfigMethod
elsif undefkey
tk_call(*(__config_cmd << "-#{undefkey}"))
end
- elsif ( method = _symbolkey2str(__ruby2val_optkeys)[slot] )
- tk_call(*(__config_cmd << "-#{slot}" << method.call(value)))
elsif ( method = _symbolkey2str(__methodcall_optkeys)[slot] )
self.__send__(method, value)
elsif (slot =~ /^(|latin|ascii|kanji)(#{__font_optkeys.join('|')})$/)
@@ -2937,11 +2581,9 @@ module TkConfigMethod
def configinfo(slot = nil)
if TkComm::GET_CONFIGINFO_AS_ARRAY
- if (slot &&
- slot.to_s =~ /^(|latin|ascii|kanji)(#{__font_optkeys.join('|')})$/)
+ if (slot.to_s =~ /^(|latin|ascii|kanji)(#{__font_optkeys.join('|')})$/)
fontkey = $2
- # conf = tk_split_simplelist(_fromUTF8(tk_call_without_enc(*(__confinfo_cmd << "-#{fontkey}"))))
- conf = tk_split_simplelist(tk_call_without_enc(*(__confinfo_cmd << "-#{fontkey}")), false, true)
+ conf = tk_split_simplelist(_fromUTF8(tk_call_without_enc(*(__confinfo_cmd << "-#{fontkey}"))))
conf[__configinfo_struct[:key]] =
conf[__configinfo_struct[:key]][1..-1]
if ( ! __configinfo_struct[:alias] \
@@ -2958,38 +2600,12 @@ module TkConfigMethod
if slot
slot = slot.to_s
case slot
- when /^(#{__val2ruby_optkeys().keys.join('|')})$/
- method = _symbolkey2str(__val2ruby_optkeys())[slot]
- conf = tk_split_simplelist(tk_call_without_enc(*(__confinfo_cmd() << "-#{slot}")), false, true)
- if ( __configinfo_struct[:default_value] \
- && conf[__configinfo_struct[:default_value]] )
- optval = conf[__configinfo_struct[:default_value]]
- begin
- val = method.call(optval)
- rescue => e
- warn("Warning:: #{e.message} (when #{method}.call(#{optval.inspect})") if $DEBUG
- val = optval
- end
- conf[__configinfo_struct[:default_value]] = val
- end
- if ( conf[__configinfo_struct[:current_value]] )
- optval = conf[__configinfo_struct[:current_value]]
- begin
- val = method.call(optval)
- rescue => e
- warn("Warning:: #{e.message} (when #{method}.call(#{optval.inspect})") if $DEBUG
- val = optval
- end
- conf[__configinfo_struct[:current_value]] = val
- end
-
when /^(#{__methodcall_optkeys.keys.join('|')})$/
method = _symbolkey2str(__methodcall_optkeys)[slot]
return [slot, '', '', '', self.__send__(method)]
when /^(#{__numval_optkeys.join('|')})$/
- # conf = tk_split_simplelist(_fromUTF8(tk_call_without_enc(*(__confinfo_cmd << "-#{slot}"))))
- conf = tk_split_simplelist(tk_call_without_enc(*(__confinfo_cmd << "-#{slot}")), false, true)
+ conf = tk_split_simplelist(_fromUTF8(tk_call_without_enc(*(__confinfo_cmd << "-#{slot}"))))
if ( __configinfo_struct[:default_value] \
&& conf[__configinfo_struct[:default_value]])
@@ -3010,8 +2626,7 @@ module TkConfigMethod
end
when /^(#{__numstrval_optkeys.join('|')})$/
- # conf = tk_split_simplelist(_fromUTF8(tk_call_without_enc(*(__confinfo_cmd << "-#{slot}"))))
- conf = tk_split_simplelist(tk_call_without_enc(*(__confinfo_cmd << "-#{slot}")), false, true)
+ conf = tk_split_simplelist(_fromUTF8(tk_call_without_enc(*(__confinfo_cmd << "-#{slot}"))))
if ( __configinfo_struct[:default_value] \
&& conf[__configinfo_struct[:default_value]])
@@ -3024,8 +2639,7 @@ module TkConfigMethod
end
when /^(#{__boolval_optkeys.join('|')})$/
- # conf = tk_split_simplelist(_fromUTF8(tk_call_without_enc(*(__confinfo_cmd << "-#{slot}"))))
- conf = tk_split_simplelist(tk_call_without_enc(*(__confinfo_cmd << "-#{slot}")), false, true)
+ conf = tk_split_simplelist(_fromUTF8(tk_call_without_enc(*(__confinfo_cmd << "-#{slot}"))))
if ( __configinfo_struct[:default_value] \
&& conf[__configinfo_struct[:default_value]])
@@ -3046,8 +2660,7 @@ module TkConfigMethod
end
when /^(#{__listval_optkeys.join('|')})$/
- # conf = tk_split_simplelist(_fromUTF8(tk_call_without_enc(*(__confinfo_cmd << "-#{slot}"))))
- conf = tk_split_simplelist(tk_call_without_enc(*(__confinfo_cmd << "-#{slot}")), false, true)
+ conf = tk_split_simplelist(_fromUTF8(tk_call_without_enc(*(__confinfo_cmd << "-#{slot}"))))
if ( __configinfo_struct[:default_value] \
&& conf[__configinfo_struct[:default_value]])
@@ -3060,8 +2673,7 @@ module TkConfigMethod
end
when /^(#{__numlistval_optkeys.join('|')})$/
- # conf = tk_split_simplelist(_fromUTF8(tk_call_without_enc(*(__confinfo_cmd << "-#{slot}"))))
- conf = tk_split_simplelist(tk_call_without_enc(*(__confinfo_cmd << "-#{slot}")), false, true)
+ conf = tk_split_simplelist(_fromUTF8(tk_call_without_enc(*(__confinfo_cmd << "-#{slot}"))))
if ( __configinfo_struct[:default_value] \
&& conf[__configinfo_struct[:default_value]] \
@@ -3076,33 +2688,9 @@ module TkConfigMethod
end
when /^(#{__strval_optkeys.join('|')})$/
- # conf = tk_split_simplelist(_fromUTF8(tk_call_without_enc(*(__confinfo_cmd << "-#{slot}"))))
- conf = tk_split_simplelist(tk_call_without_enc(*(__confinfo_cmd << "-#{slot}")), false, true)
-
- when /^(#{__tkvariable_optkeys.join('|')})$/
- conf = tk_split_simplelist(tk_call_without_enc(*(__confinfo_cmd << "-#{slot}")), false, true)
-
- if ( __configinfo_struct[:default_value] \
- && conf[__configinfo_struct[:default_value]])
- v = conf[__configinfo_struct[:default_value]]
- if v.empty?
- conf[__configinfo_struct[:default_value]] = nil
- else
- conf[__configinfo_struct[:default_value]] = TkVarAccess.new(v)
- end
- end
- if ( conf[__configinfo_struct[:current_value]] )
- v = conf[__configinfo_struct[:current_value]]
- if v.empty?
- conf[__configinfo_struct[:current_value]] = nil
- else
- conf[__configinfo_struct[:current_value]] = TkVarAccess.new(v)
- end
- end
-
+ conf = tk_split_simplelist(_fromUTF8(tk_call_without_enc(*(__confinfo_cmd << "-#{slot}"))))
else
- # conf = tk_split_list(_fromUTF8(tk_call_without_enc(*(__confinfo_cmd << "-#{slot}"))))
- conf = tk_split_list(tk_call_without_enc(*(__confinfo_cmd << "-#{slot}")), 0, false, true)
+ conf = tk_split_list(_fromUTF8(tk_call_without_enc(*(__confinfo_cmd << "-#{slot}"))))
end
conf[__configinfo_struct[:key]] =
conf[__configinfo_struct[:key]][1..-1]
@@ -3117,39 +2705,12 @@ module TkConfigMethod
conf
else
- # ret = tk_split_simplelist(_fromUTF8(tk_call_without_enc(*__confinfo_cmd))).collect{|conflist|
- # conf = tk_split_simplelist(conflist)
- ret = tk_split_simplelist(tk_call_without_enc(*__confinfo_cmd), false, false).collect{|conflist|
- conf = tk_split_simplelist(conflist, false, true)
+ ret = tk_split_simplelist(_fromUTF8(tk_call_without_enc(*__confinfo_cmd))).collect{|conflist|
+ conf = tk_split_simplelist(conflist)
conf[__configinfo_struct[:key]] =
conf[__configinfo_struct[:key]][1..-1]
- optkey = conf[__configinfo_struct[:key]]
- case optkey
- when /^(#{__val2ruby_optkeys().keys.join('|')})$/
- method = _symbolkey2str(__val2ruby_optkeys())[optkey]
- if ( __configinfo_struct[:default_value] \
- && conf[__configinfo_struct[:default_value]] )
- optval = conf[__configinfo_struct[:default_value]]
- begin
- val = method.call(optval)
- rescue => e
- warn("Warning:: #{e.message} (when #{method}.call(#{optval.inspect})") if $DEBUG
- val = optval
- end
- conf[__configinfo_struct[:default_value]] = val
- end
- if ( conf[__configinfo_struct[:current_value]] )
- optval = conf[__configinfo_struct[:current_value]]
- begin
- val = method.call(optval)
- rescue => e
- warn("Warning:: #{e.message} (when #{method}.call(#{optval.inspect})") if $DEBUG
- val = optval
- end
- conf[__configinfo_struct[:current_value]] = val
- end
-
+ case conf[__configinfo_struct[:key]]
when /^(#{__strval_optkeys.join('|')})$/
# do nothing
@@ -3226,25 +2787,6 @@ module TkConfigMethod
list(conf[__configinfo_struct[:current_value]])
end
- when /^(#{__tkvariable_optkeys.join('|')})$/
- if ( __configinfo_struct[:default_value] \
- && conf[__configinfo_struct[:default_value]] )
- v = conf[__configinfo_struct[:default_value]]
- if v.empty?
- conf[__configinfo_struct[:default_value]] = nil
- else
- conf[__configinfo_struct[:default_value]] = TkVarAccess.new(v)
- end
- end
- if ( conf[__configinfo_struct[:current_value]] )
- v = conf[__configinfo_struct[:current_value]]
- if v.empty?
- conf[__configinfo_struct[:current_value]] = nil
- else
- conf[__configinfo_struct[:current_value]] = TkVarAccess.new(v)
- end
- end
-
else
if ( __configinfo_struct[:default_value] \
&& conf[__configinfo_struct[:default_value]] )
@@ -3296,11 +2838,9 @@ module TkConfigMethod
end
else # ! TkComm::GET_CONFIGINFO_AS_ARRAY
- if (slot &&
- slot.to_s =~ /^(|latin|ascii|kanji)(#{__font_optkeys.join('|')})$/)
+ if (slot.to_s =~ /^(|latin|ascii|kanji)(#{__font_optkeys.join('|')})$/)
fontkey = $2
- # conf = tk_split_simplelist(_fromUTF8(tk_call_without_enc(*(__confinfo_cmd << "-#{fontkey}"))))
- conf = tk_split_simplelist(tk_call_without_enc(*(__confinfo_cmd << "-#{fontkey}")), false, true)
+ conf = tk_split_simplelist(_fromUTF8(tk_call_without_enc(*(__confinfo_cmd << "-#{fontkey}"))))
conf[__configinfo_struct[:key]] =
conf[__configinfo_struct[:key]][1..-1]
@@ -3322,38 +2862,12 @@ module TkConfigMethod
if slot
slot = slot.to_s
case slot
- when /^(#{__val2ruby_optkeys().keys.join('|')})$/
- method = _symbolkey2str(__val2ruby_optkeys())[slot]
- conf = tk_split_simplelist(tk_call_without_enc(*(__confinfo_cmd << "-#{slot}")), false, true)
- if ( __configinfo_struct[:default_value] \
- && conf[__configinfo_struct[:default_value]] )
- optval = conf[__configinfo_struct[:default_value]]
- begin
- val = method.call(optval)
- rescue => e
- warn("Warning:: #{e.message} (when #{method}.call(#{optval.inspect})") if $DEBUG
- val = optval
- end
- conf[__configinfo_struct[:default_value]] = val
- end
- if ( conf[__configinfo_struct[:current_value]] )
- optval = conf[__configinfo_struct[:current_value]]
- begin
- val = method.call(optval)
- rescue => e
- warn("Warning:: #{e.message} (when #{method}.call(#{optval.inspect})") if $DEBUG
- val = optval
- end
- conf[__configinfo_struct[:current_value]] = val
- end
-
when /^(#{__methodcall_optkeys.keys.join('|')})$/
method = _symbolkey2str(__methodcall_optkeys)[slot]
return {slot => ['', '', '', self.__send__(method)]}
when /^(#{__numval_optkeys.join('|')})$/
- # conf = tk_split_simplelist(_fromUTF8(tk_call_without_enc(*(__confinfo_cmd << "-#{slot}"))))
- conf = tk_split_simplelist(tk_call_without_enc(*(__confinfo_cmd << "-#{slot}")), false, true)
+ conf = tk_split_simplelist(_fromUTF8(tk_call_without_enc(*(__confinfo_cmd << "-#{slot}"))))
if ( __configinfo_struct[:default_value] \
&& conf[__configinfo_struct[:default_value]] )
@@ -3374,8 +2888,7 @@ module TkConfigMethod
end
when /^(#{__numstrval_optkeys.join('|')})$/
- # conf = tk_split_simplelist(_fromUTF8(tk_call_without_enc(*(__confinfo_cmd << "-#{slot}"))))
- conf = tk_split_simplelist(tk_call_without_enc(*(__confinfo_cmd << "-#{slot}")), false, true)
+ conf = tk_split_simplelist(_fromUTF8(tk_call_without_enc(*(__confinfo_cmd << "-#{slot}"))))
if ( __configinfo_struct[:default_value] \
&& conf[__configinfo_struct[:default_value]] )
@@ -3388,8 +2901,7 @@ module TkConfigMethod
end
when /^(#{__boolval_optkeys.join('|')})$/
- # conf = tk_split_simplelist(_fromUTF8(tk_call_without_enc(*(__confinfo_cmd << "-#{slot}"))))
- conf = tk_split_simplelist(tk_call_without_enc(*(__confinfo_cmd << "-#{slot}")), false, true)
+ conf = tk_split_simplelist(_fromUTF8(tk_call_without_enc(*(__confinfo_cmd << "-#{slot}"))))
if ( __configinfo_struct[:default_value] \
&& conf[__configinfo_struct[:default_value]] )
@@ -3410,8 +2922,7 @@ module TkConfigMethod
end
when /^(#{__listval_optkeys.join('|')})$/
- # conf = tk_split_simplelist(_fromUTF8(tk_call_without_enc(*(__confinfo_cmd << "-#{slot}"))))
- conf = tk_split_simplelist(tk_call_without_enc(*(__confinfo_cmd << "-#{slot}")), false, true)
+ conf = tk_split_simplelist(_fromUTF8(tk_call_without_enc(*(__confinfo_cmd << "-#{slot}"))))
if ( __configinfo_struct[:default_value] \
&& conf[__configinfo_struct[:default_value]] )
@@ -3424,8 +2935,7 @@ module TkConfigMethod
end
when /^(#{__numlistval_optkeys.join('|')})$/
- # conf = tk_split_simplelist(_fromUTF8(tk_call_without_enc(*(__confinfo_cmd << "-#{slot}"))))
- conf = tk_split_simplelist(tk_call_without_enc(*(__confinfo_cmd << "-#{slot}")), false, true)
+ conf = tk_split_simplelist(_fromUTF8(tk_call_without_enc(*(__confinfo_cmd << "-#{slot}"))))
if ( __configinfo_struct[:default_value] \
&& conf[__configinfo_struct[:default_value]] \
@@ -3439,33 +2949,10 @@ module TkConfigMethod
list(conf[__configinfo_struct[:current_value]])
end
- when /^(#{__tkvariable_optkeys.join('|')})$/
- conf = tk_split_simplelist(tk_call_without_enc(*(__confinfo_cmd << "-#{slot}")), false, true)
-
- if ( __configinfo_struct[:default_value] \
- && conf[__configinfo_struct[:default_value]] )
- v = conf[__configinfo_struct[:default_value]]
- if v.empty?
- conf[__configinfo_struct[:default_value]] = nil
- else
- conf[__configinfo_struct[:default_value]] = TkVarAccess.new(v)
- end
- end
- if ( conf[__configinfo_struct[:current_value]] )
- v = conf[__configinfo_struct[:current_value]]
- if v.empty?
- conf[__configinfo_struct[:current_value]] = nil
- else
- conf[__configinfo_struct[:current_value]] = TkVarAccess.new(v)
- end
- end
-
when /^(#{__strval_optkeys.join('|')})$/
- # conf = tk_split_simplelist(_fromUTF8(tk_call_without_enc(*(__confinfo_cmd << "-#{slot}"))))
- conf = tk_split_simplelist(tk_call_without_enc(*(__confinfo_cmd << "-#{slot}")), false, true)
+ conf = tk_split_simplelist(_fromUTF8(tk_call_without_enc(*(__confinfo_cmd << "-#{slot}"))))
else
- # conf = tk_split_list(_fromUTF8(tk_call_without_enc(*(__confinfo_cmd << "-#{slot}"))))
- conf = tk_split_list(tk_call_without_enc(*(__confinfo_cmd << "-#{slot}")), 0, false, true)
+ conf = tk_split_list(_fromUTF8(tk_send_without_enc(*(__confinfo_cmd << "-#{slot}"))))
end
conf[__configinfo_struct[:key]] =
conf[__configinfo_struct[:key]][1..-1]
@@ -3483,39 +2970,12 @@ module TkConfigMethod
else
ret = {}
- # tk_split_simplelist(_fromUTF8(tk_call_without_enc(*__confinfo_cmd))).each{|conflist|
- # conf = tk_split_simplelist(conflist)
- tk_split_simplelist(tk_call_without_enc(*__confinfo_cmd), false, false).each{|conflist|
- conf = tk_split_simplelist(conflist, false, true)
+ tk_split_simplelist(_fromUTF8(tk_call_without_enc(*__confinfo_cmd))).each{|conflist|
+ conf = tk_split_simplelist(conflist)
conf[__configinfo_struct[:key]] =
conf[__configinfo_struct[:key]][1..-1]
- optkey = conf[__configinfo_struct[:key]]
- case optkey
- when /^(#{__val2ruby_optkeys().keys.join('|')})$/
- method = _symbolkey2str(__val2ruby_optkeys())[optkey]
- if ( __configinfo_struct[:default_value] \
- && conf[__configinfo_struct[:default_value]] )
- optval = conf[__configinfo_struct[:default_value]]
- begin
- val = method.call(optval)
- rescue => e
- warn("Warning:: #{e.message} (when #{method}.call(#{optval.inspect})") if $DEBUG
- val = optval
- end
- conf[__configinfo_struct[:default_value]] = val
- end
- if ( conf[__configinfo_struct[:current_value]] )
- optval = conf[__configinfo_struct[:current_value]]
- begin
- val = method.call(optval)
- rescue => e
- warn("Warning:: #{e.message} (when #{method}.call(#{optval.inspect})") if $DEBUG
- val = optval
- end
- conf[__configinfo_struct[:current_value]] = val
- end
-
+ case conf[__configinfo_struct[:key]]
when /^(#{__strval_optkeys.join('|')})$/
# do nothing
@@ -3592,25 +3052,6 @@ module TkConfigMethod
list(conf[__configinfo_struct[:current_value]])
end
- when /^(#{__tkvariable_optkeys.join('|')})$/
- if ( __configinfo_struct[:default_value] \
- && conf[__configinfo_struct[:default_value]] )
- v = conf[__configinfo_struct[:default_value]]
- if v.empty?
- conf[__configinfo_struct[:default_value]] = nil
- else
- conf[__configinfo_struct[:default_value]] = TkVarAccess.new
- end
- end
- if ( conf[__configinfo_struct[:current_value]] )
- v = conf[__configinfo_struct[:current_value]]
- if v.empty?
- conf[__configinfo_struct[:current_value]] = nil
- else
- conf[__configinfo_struct[:current_value]] = TkVarAccess.new
- end
- end
-
else
if ( __configinfo_struct[:default_value] \
&& conf[__configinfo_struct[:default_value]] )
@@ -3732,35 +3173,14 @@ class TkObject<TkKernel
end
# private :tk_send, :tk_send_without_enc, :tk_send_with_enc
- def tk_send_to_list(cmd, *rest)
- tk_call_to_list(path, cmd, *rest)
- end
- def tk_send_to_list_without_enc(cmd, *rest)
- tk_call_to_list_without_enc(path, cmd, *rest)
- end
- def tk_send_to_list_with_enc(cmd, *rest)
- tk_call_to_list_with_enc(path, cmd, *rest)
- end
- def tk_send_to_simplelist(cmd, *rest)
- tk_call_to_simplelist(path, cmd, *rest)
- end
- def tk_send_to_simplelist_without_enc(cmd, *rest)
- tk_call_to_simplelist_without_enc(path, cmd, *rest)
- end
- def tk_send_to_simplelist_with_enc(cmd, *rest)
- tk_call_to_simplelist_with_enc(path, cmd, *rest)
- end
-
def method_missing(id, *args)
name = id.id2name
case args.length
when 1
if name[-1] == ?=
configure name[0..-2], args[0]
- args[0]
else
configure name, args[0]
- self
end
when 0
begin
@@ -3787,9 +3207,7 @@ class TkObject<TkKernel
=end
def event_generate(context, keys=nil)
- if context.kind_of?(TkEvent::Event)
- context.generate(self, ((keys)? keys: {}))
- elsif keys
+ if keys
#tk_call('event', 'generate', path,
# "<#{tk_event_sequence(context)}>", *hash_kv(keys))
tk_call_without_enc('event', 'generate', path,
@@ -3837,19 +3255,19 @@ class TkWindow<TkObject
widgetname = keys.delete('widgetname')
install_win(if parent then parent.path end, widgetname)
without_creating = keys.delete('without_creating')
- # if without_creating && !widgetname
- # fail ArgumentError,
- # "if set 'without_creating' to true, need to define 'widgetname'"
- # end
+ if without_creating && !widgetname
+ fail ArgumentError,
+ "if set 'without_creating' to true, need to define 'widgetname'"
+ end
elsif keys
keys = _symbolkey2str(keys)
widgetname = keys.delete('widgetname')
install_win(if parent then parent.path end, widgetname)
without_creating = keys.delete('without_creating')
- # if without_creating && !widgetname
- # fail ArgumentError,
- # "if set 'without_creating' to true, need to define 'widgetname'"
- # end
+ if without_creating && !widgetname
+ fail ArgumentError,
+ "if set 'without_creating' to true, need to define 'widgetname'"
+ end
else
install_win(if parent then parent.path end)
end
@@ -3886,11 +3304,6 @@ class TkWindow<TkObject
key = key.to_s
methodkeys[key] = keys.delete(key) if keys.key?(key)
}
-
- __ruby2val_optkeys.each{|key, method|
- key = key.to_s
- keys[key] = method.call(keys[key]) if keys.has_key?(key)
- }
end
if without_creating && keys
#configure(keys)
@@ -4042,7 +3455,7 @@ class TkWindow<TkObject
self
end
- def grid_forget
+ def grid_forget
#tk_call('grid', 'forget', epath)
TkGrid.forget(self)
self
@@ -4126,9 +3539,9 @@ class TkWindow<TkObject
# self
#end
if mode == None
- TkGrid.propagate(self)
+ TkGrid.propagete(self)
else
- TkGrid.propagate(self, mode)
+ TkGrid.propagete(self, mode)
self
end
end
@@ -4279,14 +3692,12 @@ class TkWindow<TkObject
tk_call 'lower', epath, below
self
end
- alias lower_window lower
def raise(above=None)
#above = above.epath if above.kind_of?(TkObject)
above = _epath(above)
tk_call 'raise', epath, above
self
end
- alias raise_window raise
def command(cmd=nil, &b)
if cmd
@@ -4443,8 +3854,6 @@ end
#Tk.freeze
module Tk
- RELEASE_DATE = '2005-10-24'.freeze
-
autoload :AUTO_PATH, 'tk/variable'
autoload :TCL_PACKAGE_PATH, 'tk/variable'
autoload :PACKAGE_PATH, 'tk/variable'
@@ -4453,6 +3862,7 @@ module Tk
autoload :TCL_PRECISION, 'tk/variable'
end
+
# call setup script for Tk extension libraries (base configuration)
begin
require 'tkextlib/setup.rb'
diff --git a/ext/tk/lib/tk/autoload.rb b/ext/tk/lib/tk/autoload.rb
index 73544e1d23..3006b559d6 100644
--- a/ext/tk/lib/tk/autoload.rb
+++ b/ext/tk/lib/tk/autoload.rb
@@ -47,10 +47,8 @@ autoload :TkConsole, 'tk/console'
autoload :TkDialog, 'tk/dialog'
autoload :TkDialog2, 'tk/dialog'
-autoload :TkDialogObj, 'tk/dialog'
autoload :TkWarning, 'tk/dialog'
autoload :TkWarning2, 'tk/dialog'
-autoload :TkWarningObj, 'tk/dialog'
autoload :TkEntry, 'tk/entry'
@@ -150,7 +148,6 @@ autoload :TkTextWindow, 'tk/textwindow'
autoload :TkAfter, 'tk/timer'
autoload :TkTimer, 'tk/timer'
-autoload :TkRTTimer, 'tk/timer'
autoload :TkToplevel, 'tk/toplevel'
diff --git a/ext/tk/lib/tk/bindtag.rb b/ext/tk/lib/tk/bindtag.rb
index 9023a08e06..adf96b9e3d 100644
--- a/ext/tk/lib/tk/bindtag.rb
+++ b/ext/tk/lib/tk/bindtag.rb
@@ -18,12 +18,10 @@ class TkBindTag
def TkBindTag.new_by_name(name, *args, &b)
return BTagID_TBL[name] if BTagID_TBL[name]
- self.new.instance_eval{
+ self.new(*args, &b).instance_eval{
BTagID_TBL.delete @id
@id = name
BTagID_TBL[@id] = self
- bind(*args, &b) if args != []
- self
}
end
diff --git a/ext/tk/lib/tk/canvas.rb b/ext/tk/lib/tk/canvas.rb
index 02b4a8cb20..1a8a7927d3 100644
--- a/ext/tk/lib/tk/canvas.rb
+++ b/ext/tk/lib/tk/canvas.rb
@@ -11,25 +11,11 @@ require 'tk/scrollable'
module TkCanvasItemConfig
include TkItemConfigMethod
- def __item_strval_optkeys(id)
- # maybe need to override
- super(id) + [
- 'fill', 'activefill', 'disabledfill',
- 'outline', 'activeoutline', 'disabledoutline'
- ]
- end
- private :__item_strval_optkeys
-
def __item_methodcall_optkeys(id)
{'coords'=>'coords'}
end
private :__item_methodcall_optkeys
- def __item_val2ruby_optkeys(id) # { key=>proc, ... }
- super(id).update('window'=>proc{|i, v| window(v)})
- end
- private :__item_val2ruby_optkeys
-
def __item_pathname(tagOrId)
if tagOrId.kind_of?(TkcItem) || tagOrId.kind_of?(TkcTag)
self.path + ';' + tagOrId.id.to_s
@@ -61,16 +47,6 @@ class TkCanvas<TkWindow
#end
#private :create_self
- def __numval_optkeys
- super() + ['closeenough']
- end
- private :__numval_optkeys
-
- def __boolval_optkeys
- super() + ['confine']
- end
- private :__boolval_optkeys
-
def tagid(tag)
if tag.kind_of?(TkcItem) || tag.kind_of?(TkcTag)
tag.id
@@ -88,10 +64,6 @@ class TkCanvas<TkWindow
def addtag(tag, mode, *args)
- mode = mode.to_s
- if args[0] && mode =~ /^(above|below|with(tag)?)$/
- args[0] = tagid(args[0])
- end
tk_send_without_enc('addtag', tagid(tag), mode, *args)
self
end
@@ -122,33 +94,13 @@ class TkCanvas<TkWindow
*tags.collect{|t| tagid(t)}))
end
- #def itembind(tag, context, cmd=Proc.new, *args)
- # _bind([path, "bind", tagid(tag)], context, cmd, *args)
- # self
- #end
- def itembind(tag, context, *args)
- # if args[0].kind_of?(Proc) || args[0].kind_of?(Method)
- if TkComm._callback_entry?(args[0]) || !block_given?
- cmd = args.shift
- else
- cmd = Proc.new
- end
- _bind([path, "bind", tagid(tag)], context, cmd, *args)
+ def itembind(tag, context, cmd=Proc.new, args=nil)
+ _bind([path, "bind", tagid(tag)], context, cmd, args)
self
end
- #def itembind_append(tag, context, cmd=Proc.new, *args)
- # _bind_append([path, "bind", tagid(tag)], context, cmd, *args)
- # self
- #end
- def itembind_append(tag, context, *args)
- # if args[0].kind_of?(Proc) || args[0].kind_of?(Method)
- if TkComm._callback_entry?(args[0]) || !block_given?
- cmd = args.shift
- else
- cmd = Proc.new
- end
- _bind_append([path, "bind", tagid(tag)], context, cmd, *args)
+ def itembind_append(tag, context, cmd=Proc.new, args=nil)
+ _bind_append([path, "bind", tagid(tag)], context, cmd, args)
self
end
@@ -187,12 +139,8 @@ class TkCanvas<TkWindow
def delete(*args)
if TkcItem::CItemID_TBL[self.path]
- args.each{|tag|
- find('withtag', tag).each{|item|
- if item.kind_of?(TkcItem)
- TkcItem::CItemID_TBL[self.path].delete(item.id)
- end
- }
+ find('withtag', *args).each{|item|
+ TkcItem::CItemID_TBL[self.path].delete(item.id)
}
end
tk_send_without_enc('delete', *args.collect{|t| tagid(t)})
@@ -201,10 +149,9 @@ class TkCanvas<TkWindow
alias remove delete
def dtag(tag, tag_to_del=None)
- tk_send_without_enc('dtag', tagid(tag), tagid(tag_to_del))
+ tk_send_without_enc('dtag', tagid(tag), tag_to_del)
self
end
- alias deltag dtag
def find(mode, *args)
list(tk_send_without_enc('find', mode, *args)).collect!{|id|
@@ -258,8 +205,8 @@ class TkCanvas<TkWindow
self
end
- def index(tagOrId, idx)
- number(tk_send_without_enc('index', tagid(tagOrId), idx))
+ def index(tagOrId, index)
+ number(tk_send_without_enc('index', tagid(tagOrId), index))
end
def insert(tagOrId, index, string)
@@ -630,11 +577,6 @@ class TkcItem<TkObject
methodkeys[key] = keys.delete(key) if keys.key?(key)
}
- __item_ruby2val_optkeys(nil).each{|key, method|
- key = key.to_s
- keys[key] = method.call(keys[key]) if keys.has_key?(key)
- }
-
#args = args.flatten.concat(hash_kv(keys))
args = args.flatten.concat(itemconfig_hash_kv(nil, keys))
else
@@ -659,7 +601,7 @@ class TkcItem<TkObject
def initialize(parent, *args)
#unless parent.kind_of?(TkCanvas)
- # fail ArgumentError, "expect TkCanvas for 1st argument"
+ # fail ArguemntError, "expect TkCanvas for 1st argument"
#end
@parent = @c = parent
@path = parent.path
diff --git a/ext/tk/lib/tk/canvastag.rb b/ext/tk/lib/tk/canvastag.rb
index a5650ee68b..f27111bd84 100644
--- a/ext/tk/lib/tk/canvastag.rb
+++ b/ext/tk/lib/tk/canvastag.rb
@@ -13,7 +13,7 @@ require 'tk/canvas'
module TkcTagAccess
def addtag(tag)
- @c.addtag(tag, 'withtag', @id)
+ @c.addtag(tag, 'with', @id)
self
end
@@ -21,51 +21,31 @@ module TkcTagAccess
@c.bbox(@id)
end
- #def bind(seq, cmd=Proc.new, *args)
- # @c.itembind(@id, seq, cmd, *args)
- # self
- #end
- def bind(seq, *args)
- # if args[0].kind_of?(Proc) || args[0].kind_of?(Method)
- if TkComm._callback_entry?(args[0]) || !block_given?
- cmd = args.shift
- else
- cmd = Proc.new
- end
- @c.itembind(@id, seq, cmd, *args)
+ def bind(seq, cmd=Proc.new, args=nil)
+ @c.itembind @id, seq, cmd, args
self
end
- #def bind_append(seq, cmd=Proc.new, *args)
- # @c.itembind_append(@id, seq, cmd, *args)
- # self
- #end
- def bind_append(seq, *args)
- # if args[0].kind_of?(Proc) || args[0].kind_of?(Method)
- if TkComm._callback_entry?(args[0]) || !block_given?
- cmd = args.shift
- else
- cmd = Proc.new
- end
- @c.itembind_append(@id, seq, cmd, *args)
+ def bind_append(seq, cmd=Proc.new, args=nil)
+ @c.itembind_append @id, seq, cmd, args
self
end
def bind_remove(seq)
- @c.itembind_remove(@id, seq)
+ @c.itembind_remove @id, seq
self
end
def bindinfo(seq=nil)
- @c.itembindinfo(@id, seq)
+ @c.itembindinfo @id, seq
end
def cget(option)
- @c.itemcget(@id, option)
+ @c.itemcget @id, option
end
def configure(key, value=None)
- @c.itemconfigure(@id, key, value)
+ @c.itemconfigure @id, key, value
self
end
# def configure(keys)
@@ -73,72 +53,71 @@ module TkcTagAccess
# end
def configinfo(key=nil)
- @c.itemconfiginfo(@id, key)
+ @c.itemconfiginfo @id, key
end
def current_configinfo(key=nil)
- @c.current_itemconfiginfo(@id, key)
+ @c.current_itemconfiginfo @id, key
end
def coords(*args)
- @c.coords(@id, *args)
+ @c.coords @id, *args
end
def dchars(first, last=None)
- @c.dchars(@id, first, last)
+ @c.dchars @id, first, last
self
end
def dtag(tag_to_del=None)
- @c.dtag(@id, tag_to_del)
+ @c.dtag @id, tag_to_del
self
end
- alias deltag dtag
def find
- @c.find('withtag', @id)
+ @c.find 'withtag', @id
end
alias list find
def focus
- @c.itemfocus(@id)
+ @c.itemfocus @id
end
def gettags
- @c.gettags(@id)
+ @c.gettags @id
end
def icursor(index)
- @c.icursor(@id, index)
+ @c.icursor @id, index
self
end
- def index(idx)
- @c.index(@id, idx)
+ def index(index)
+ @c.index @id, index
end
def insert(beforethis, string)
- @c.insert(@id, beforethis, string)
+ @c.insert @id, beforethis, string
self
end
def lower(belowthis=None)
- @c.lower(@id, belowthis)
+ @c.lower @id, belowthis
self
end
def move(xamount, yamount)
- @c.move(@id, xamount, yamount)
+ @c.move @id, xamount, yamount
self
end
def raise(abovethis=None)
- @c.raise(@id, abovethis)
+ @c.raise @id, abovethis
self
end
def scale(xorigin, yorigin, xscale, yscale)
- @c.scale(@id, xorigin, yorigin, xscale, yscale)
+ @c.scale @id, xorigin, yorigin, xscale, yscale
self
end
@@ -156,7 +135,7 @@ module TkcTagAccess
end
def itemtype
- @c.itemtype(@id)
+ @c.itemtype @id
end
# Following operators support logical expressions of canvas tags
@@ -211,7 +190,7 @@ class TkcTag<TkObject
def initialize(parent, mode=nil, *args)
#unless parent.kind_of?(TkCanvas)
- # fail ArgumentError, "expect TkCanvas for 1st argument"
+ # fail ArguemntError, "expect TkCanvas for 1st argument"
#end
@c = parent
@cpath = parent.path
@@ -298,7 +277,7 @@ class TkcTagString<TkcTag
def initialize(parent, name, mode=nil, *args)
#unless parent.kind_of?(TkCanvas)
- # fail ArgumentError, "expect TkCanvas for 1st argument"
+ # fail ArguemntError, "expect TkCanvas for 1st argument"
#end
@c = parent
@cpath = parent.path
@@ -315,7 +294,7 @@ TkcNamedTag = TkcTagString
class TkcTagAll<TkcTag
def initialize(parent)
#unless parent.kind_of?(TkCanvas)
- # fail ArgumentError, "expect TkCanvas for 1st argument"
+ # fail ArguemntError, "expect TkCanvas for 1st argument"
#end
@c = parent
@cpath = parent.path
@@ -328,7 +307,7 @@ end
class TkcTagCurrent<TkcTag
def initialize(parent)
#unless parent.kind_of?(TkCanvas)
- # fail ArgumentError, "expect TkCanvas for 1st argument"
+ # fail ArguemntError, "expect TkCanvas for 1st argument"
#end
@c = parent
@cpath = parent.path
@@ -343,7 +322,7 @@ class TkcGroup<TkcTag
#def create_self(parent, *args)
def initialize(parent, *args)
#unless parent.kind_of?(TkCanvas)
- # fail ArgumentError, "expect TkCanvas for 1st argument"
+ # fail ArguemntError, "expect TkCanvas for 1st argument"
#end
@c = parent
@cpath = parent.path
@@ -352,23 +331,20 @@ class TkcGroup<TkcTag
CTagID_TBL[@cpath] = {} unless CTagID_TBL[@cpath]
CTagID_TBL[@cpath][@id] = self
Tk_cGroup_ID[1].succ!
- include(*args) if args != []
+ add(*args) if args != []
end
#private :create_self
def include(*tags)
for i in tags
- #i.addtag(@id)
- @c.addtag_withtag(@id, i)
+ i.addtag @id
end
self
end
- alias add include
def exclude(*tags)
for i in tags
- #i.dtag(@id)
- @c.dtag(i, @id)
+ i.delete @id
end
self
end
diff --git a/ext/tk/lib/tk/clock.rb b/ext/tk/lib/tk/clock.rb
index 4e9438f5ab..823b8a6341 100644
--- a/ext/tk/lib/tk/clock.rb
+++ b/ext/tk/lib/tk/clock.rb
@@ -5,17 +5,9 @@ require 'tk'
module Tk
module Clock
- include Tk
- extend TkCore
-
- def self.add(clk, *args)
- tk_call_without_enc('clock','add', clk, *args).to_i
- end
-
def self.clicks(ms=nil)
- ms = ms.to_s if ms.kind_of?(Symbol)
case ms
- when nil, ''
+ when nil
tk_call_without_enc('clock','clicks').to_i
when /^mic/
tk_call_without_enc('clock','clicks','-microseconds').to_i
@@ -61,11 +53,5 @@ module Tk
def self.seconds
tk_call_without_enc('clock','seconds').to_i
end
- def self.milliseconds
- tk_call_without_enc('clock','milliseconds').to_i
- end
- def self.microseconds
- tk_call_without_enc('clock','microseconds').to_i
- end
end
end
diff --git a/ext/tk/lib/tk/composite.rb b/ext/tk/lib/tk/composite.rb
index 58cca736db..d85b815dd7 100644
--- a/ext/tk/lib/tk/composite.rb
+++ b/ext/tk/lib/tk/composite.rb
@@ -97,7 +97,7 @@ module TkComposite
rescue
end
- super(slot)
+ super
end
def configure(slot, value=None)
@@ -134,7 +134,7 @@ module TkComposite
rescue
end
- super(slot, value)
+ super
end
def configinfo(slot = nil)
@@ -171,10 +171,10 @@ module TkComposite
rescue
end
- super(slot)
+ super
else # slot == nil
- info_list = super(slot)
+ info_list = super
tbl = @delegates['DEFAULT']
if tbl
@@ -250,10 +250,10 @@ module TkComposite
rescue
end
- super(slot)
+ super
else # slot == nil
- info_list = super(slot)
+ info_list = super
tbl = @delegates['DEFAULT']
if tbl
diff --git a/ext/tk/lib/tk/console.rb b/ext/tk/lib/tk/console.rb
index 26ce262caa..f0d2c7aa87 100644
--- a/ext/tk/lib/tk/console.rb
+++ b/ext/tk/lib/tk/console.rb
@@ -7,12 +7,7 @@ module TkConsole
include Tk
extend Tk
- TkCommandNames = ['console'.freeze, 'consoleinterp'.freeze].freeze
-
- def self.create
- TkCore::INTERP._create_console
- end
- self.create # initialize console
+ TkCommandNames = ['console'.freeze].freeze
def self.title(str=None)
tk_call 'console', str
@@ -31,22 +26,4 @@ module TkConsole
_fromUTF8(tk_call_without_enc('console', 'eval',
_get_eval_enc_str(tcl_script)))
end
- def self.maininterp_eval(tcl_script)
- #
- # supports a Tcl script only
- # I have no idea to support a Ruby script seamlessly.
- #
- _fromUTF8(tk_call_without_enc('consoleinterp', 'eval',
- _get_eval_enc_str(tcl_script)))
-
- end
- def self.maininterp_record(tcl_script)
- #
- # supports a Tcl script only
- # I have no idea to support a Ruby script seamlessly.
- #
- _fromUTF8(tk_call_without_enc('consoleinterp', 'record',
- _get_eval_enc_str(tcl_script)))
-
- end
end
diff --git a/ext/tk/lib/tk/dialog.rb b/ext/tk/lib/tk/dialog.rb
index 180da101e3..2ced26b193 100644
--- a/ext/tk/lib/tk/dialog.rb
+++ b/ext/tk/lib/tk/dialog.rb
@@ -2,9 +2,8 @@
# tk/dialog.rb : create dialog boxes
#
require 'tk'
-require 'tk/variable.rb'
-class TkDialogObj < TkWindow
+class TkDialog2 < TkWindow
extend Tk
TkCommandNames = ['tk_dialog'.freeze].freeze
@@ -24,40 +23,37 @@ class TkDialogObj < TkWindow
c.delete('command'); c.delete(:command)
# @config << Kernel.format("%s.button%s configure %s; ",
# @path, i, hash_kv(c).join(' '))
- # @config << @path+'.button'+i.to_s+' configure '+hash_kv(c).join(' ')+'; '
- @config << @path+'.button'+i.to_s+' configure '+
- array2tk_list(hash_kv(c))+'; '
+ @config << @path+'.button'+i.to_s+'configure '+hash_kv(c).join(' ')+'; '
}
case configs
when Proc
@buttons.each_index{|i|
- if (c = configs.call(i)).kind_of?(Hash)
+ if (c = configs.call(i)).kind_of? Hash
set_config.call(c,i)
end
}
when Array
@buttons.each_index{|i|
- if (c = configs[i]).kind_of?(Hash)
+ if (c = configs[i]).kind_of? Hash
set_config.call(c,i)
end
}
when Hash
@buttons.each_with_index{|s,i|
- if (c = configs[s]).kind_of?(Hash)
+ if (c = configs[s]).kind_of? Hash
set_config.call(c,i)
end
}
end
- # @config = 'after idle {' + @config + '};' if @config != ""
- @config = array2tk_list(['after', 'idle', @config]) << ';' if @config != ""
+ @config = 'after idle {' + @config + '};' if @config != ""
end
private :_set_button_config
# initialize tk_dialog
def create_self(keys)
- # @var = TkVariable.new
+ #@var = TkVariable.new
@val = nil
@title = title
@@ -78,18 +74,17 @@ class TkDialogObj < TkWindow
#@config = "puts [winfo children .w0000];"
@config = ""
- @command = prev_command
+ @command = nil
- if keys.kind_of?(Hash)
+ if keys.kind_of? Hash
@title = keys['title'] if keys.key? 'title'
@message = keys['message'] if keys.key? 'message'
@bitmap = keys['bitmap'] if keys.key? 'bitmap'
- # @bitmap = '{}' if @bitmap == nil || @bitmap == ""
- @bitmap = '' unless @bitmap
+ @bitmap = '{}' if @bitmap == nil || @bitmap == ""
@default_button = keys['default'] if keys.key? 'default'
@buttons = keys['buttons'] if keys.key? 'buttons'
- @command = keys['prev_command'] if keys.key? 'prev_command'
+ @command = keys['prev_command']
@message_config = keys['message_config'] if keys.key? 'message_config'
@msgframe_config = keys['msgframe_config'] if keys.key? 'msgframe_config'
@@ -98,24 +93,22 @@ class TkDialogObj < TkWindow
@btnframe_config = keys['btnframe_config'] if keys.key? 'btnframe_config'
end
- #if @title.include? ?\s
- # @title = '{' + @title + '}'
- #end
+ if @title.include? ?\s
+ @title = '{' + @title + '}'
+ end
- if @buttons.kind_of?(Array)
+ if @buttons.kind_of? Array
_set_button_config(@buttons.collect{|cfg|
(cfg.kind_of? Array)? cfg[1]: nil})
@buttons = @buttons.collect{|cfg| (cfg.kind_of? Array)? cfg[0]: cfg}
end
- if @buttons.kind_of?(Hash)
+ if @buttons.kind_of? Hash
_set_button_config(@buttons)
@buttons = @buttons.keys
end
- @buttons = tk_split_simplelist(@buttons) if @buttons.kind_of?(String)
- @buttons = [] unless @buttons
-=begin
+ @buttons = tk_split_simplelist(@buttons) if @buttons.kind_of? String
@buttons = @buttons.collect{|s|
- if s.kind_of?(Array)
+ if s.kind_of? Array
s = s.join(' ')
end
if s.include? ?\s
@@ -124,57 +117,46 @@ class TkDialogObj < TkWindow
s
end
}
-=end
- if @message_config.kind_of?(Hash)
+ if @message_config.kind_of? Hash
# @config << Kernel.format("%s.msg configure %s;",
# @path, hash_kv(@message_config).join(' '))
- # @config << @path+'.msg configure '+hash_kv(@message_config).join(' ')+';'
- @config << @path+'.msg configure '+
- array2tk_list(hash_kv(@message_config))+';'
+ @config << @path+'.msg configure '+hash_kv(@message_config).join(' ')+';'
end
- if @msgframe_config.kind_of?(Hash)
+ if @msgframe_config.kind_of? Hash
# @config << Kernel.format("%s.top configure %s;",
# @path, hash_kv(@msgframe_config).join(' '))
- # @config << @path+'.top configure '+hash_kv(@msgframe_config).join(' ')+';'
- @config << @path+'.top configure '+
- array2tk_list(hash_kv(@msgframe_config))+';'
+ @config << @path+'.top configure '+hash_kv(@msgframe_config).join(' ')+';'
end
- if @btnframe_config.kind_of?(Hash)
+ if @btnframe_config.kind_of? Hash
# @config << Kernel.format("%s.bot configure %s;",
# @path, hash_kv(@btnframe_config).join(' '))
- # @config << @path+'.bot configure '+hash_kv(@btnframe_config).join(' ')+';'
- @config << @path+'.bot configure '+
- array2tk_list(hash_kv(@btnframe_config))+';'
+ @config << @path+'.bot configure '+hash_kv(@btnframe_config).join(' ')+';'
end
- if @bitmap_config.kind_of?(Hash)
+ if @bitmap_config.kind_of? Hash
# @config << Kernel.format("%s.bitmap configure %s;",
# @path, hash_kv(@bitmap_config).join(' '))
- # @config << @path+'.bitmap configure '+hash_kv(@bitmap_config).join(' ')+';'
- @config << @path+'.bitmap configure '+
- array2tk_list(hash_kv(@bitmap_config))+';'
+ @config << @path+'.bitmap configure '+hash_kv(@bitmap_config).join(' ')+';'
end
_set_button_config(@button_configs) if @button_configs
- end
- private :create_self
- def show
- # if @command.kind_of?(Proc)
- if TkComm._callback_entry?(@command)
+ if @command.kind_of? Proc
@command.call(self)
end
+ end
+ private :create_self
- if @default_button.kind_of?(String)
+ def show
+ if @default_button.kind_of? String
default_button = @buttons.index(@default_button)
else
default_button = @default_button
end
- # default_button = '{}' if default_button == nil
- default_button = '' if default_button == nil
+ default_button = '{}' if default_button == nil
#Tk.ip_eval('eval {global '+@var.id+';'+@config+
# 'set '+@var.id+' [tk_dialog '+
# @path+" "+@title+" {#{@message}} "+@bitmap+" "+
@@ -183,30 +165,20 @@ class TkDialogObj < TkWindow
# @val = Tk.ip_eval('tk_dialog ' + @path + ' ' + @title +
# ' {' + @message + '} ' + @bitmap + ' ' +
# String(default_button) + ' ' + @buttons.join(' ')).to_i
- # @val = Tk.ip_eval(self.class::TkCommandNames[0] + ' ' + @path + ' ' +
- # @title + ' {' + @message + '} ' + @bitmap + ' ' +
- # String(default_button) + ' ' + @buttons.join(' ')).to_i
- @val = Tk.ip_eval(array2tk_list([
- self.class::TkCommandNames[0],
- @path, @title, @message, @bitmap,
- String(default_button)
- ].concat(@buttons))).to_i
+ @val = Tk.ip_eval(self.class::TkCommandNames[0] + ' ' + @path + ' ' +
+ @title + ' {' + @message + '} ' + @bitmap + ' ' +
+ String(default_button) + ' ' + @buttons.join(' ')).to_i
end
def value
# @var.value.to_i
@val
end
-
- def name
- (@val)? @buttons[@val]: nil
- end
-
- ############################################################
- # #
- # following methods should be overridden for each dialog #
- # #
- ############################################################
+ ######################################################
+ # #
+ # these methods must be overridden for each dialog #
+ # #
+ ######################################################
private
def title
@@ -251,17 +223,13 @@ class TkDialogObj < TkWindow
# returns nil or a Hash {option=>value, ...} for the button frame
return nil
end
- def prev_command
- # returns nil or a Proc
- return nil
- end
end
-TkDialog2 = TkDialogObj
+
#
# TkDialog : with showing at initialize
#
-class TkDialog < TkDialogObj
+class TkDialog < TkDialog2
def self.show(*args)
self.new(*args)
end
@@ -276,10 +244,10 @@ end
#
# dialog for warning
#
-class TkWarningObj < TkDialogObj
+class TkWarning2 < TkDialog2
def initialize(parent = nil, mes = nil)
if !mes
- if parent.kind_of?(TkWindow)
+ if parent.kind_of? TkWindow
mes = ""
else
mes = parent.to_s
@@ -313,9 +281,8 @@ class TkWarningObj < TkDialogObj
return "OK";
end
end
-TkWarning2 = TkWarningObj
-class TkWarning < TkWarningObj
+class TkWarning < TkWarning2
def self.show(*args)
self.new(*args)
end
diff --git a/ext/tk/lib/tk/encodedstr.rb b/ext/tk/lib/tk/encodedstr.rb
index 797e514a4c..aed0e7524e 100644
--- a/ext/tk/lib/tk/encodedstr.rb
+++ b/ext/tk/lib/tk/encodedstr.rb
@@ -67,13 +67,9 @@ module Tk
def initialize(str, enc = nil)
super(str)
- # @encoding = ( enc ||
- # ((self.class::Encoding)?
- # self.class::Encoding : Tk.encoding_system) )
@encoding = ( enc ||
- ((self.class::Encoding)?
- self.class::Encoding :
- ((Tk.encoding)? Tk.encoding : Tk.encoding_system) ) )
+ ((self.class::Encoding)?
+ self.class::Encoding : Tk.encoding_system) )
end
attr_reader :encoding
diff --git a/ext/tk/lib/tk/entry.rb b/ext/tk/lib/tk/entry.rb
index 4ac3f28229..a3c0e51cdd 100644
--- a/ext/tk/lib/tk/entry.rb
+++ b/ext/tk/lib/tk/entry.rb
@@ -21,26 +21,19 @@ class TkEntry<TkLabel
#end
#private :create_self
- def __strval_optkeys
- super() + ['show', 'disabledbackground', 'readonlybackground']
- end
- private :__strval_optkeys
-
def bbox(index)
list(tk_send_without_enc('bbox', index))
end
def cursor
number(tk_send_without_enc('index', 'insert'))
end
- alias icursor cursor
def cursor=(index)
tk_send_without_enc('icursor', index)
#self
index
end
- alias icursor= cursor=
- def index(idx)
- number(tk_send_without_enc('index', idx))
+ def index(index)
+ number(tk_send_without_enc('index', index))
end
def insert(pos,text)
tk_send_without_enc('insert', pos, _get_eval_enc_str(text))
diff --git a/ext/tk/lib/tk/event.rb b/ext/tk/lib/tk/event.rb
index b538bfd63d..16adeedc6c 100644
--- a/ext/tk/lib/tk/event.rb
+++ b/ext/tk/lib/tk/event.rb
@@ -2,295 +2,55 @@
# tk/event.rb - module for event
#
-module TkEvent
-end
+unless $LOADED_FEATURES.member?('tk.rb')
+ # change loading order
-########################
+ $LOADED_FEATURES.delete('tk/event.rb')
-require 'tkutil'
-require 'tk'
+ require 'tkutil'
+ require 'tk'
-########################
+else
+################################################
module TkEvent
class Event < TkUtil::CallbackSubst
- module Grp
- KEY = 0x1
- BUTTON = 0x2
- MOTION = 0x4
- CROSSING = 0x8
- FOCUS = 0x10
- EXPOSE = 0x20
- VISIBILITY = 0x40
- CREATE = 0x80
- DESTROY = 0x100
- UNMAP = 0x200
- MAP = 0x400
- REPARENT = 0x800
- CONFIG = 0x1000
- GRAVITY = 0x2000
- CIRC = 0x4000
- PROP = 0x8000
- COLORMAP = 0x10000
- VIRTUAL = 0x20000
- ACTIVATE = 0x40000
- MAPREQ = 0x80000
- CONFIGREQ = 0x100000
- RESIZEREQ = 0x200000
- CIRCREQ = 0x400000
-
- MWHEEL = 0x10000000
-
- ALL = 0xFFFFFFFF
-
- KEY_BUTTON_MOTION_VIRTUAL = (KEY|MWHEEL|BUTTON|MOTION|VIRTUAL)
- KEY_BUTTON_MOTION_CROSSING = (KEY|MWHEEL|BUTTON|MOTION|CROSSING|VIRTUAL)
- end
-
- type_data = [
- #-----+-------------------+------------------+-----------------------#
- # ID | const | group_flag | context_name #
- #-----+-------------------+------------------+-----------------------#
- [ 2, :KeyPress, Grp::KEY, 'KeyPress', 'Key' ],
- [ 3, :KeyRelease, Grp::KEY, 'KeyRelease' ],
- [ 4, :ButtonPress, Grp::BUTTON, 'ButtonPress', 'Button' ],
- [ 5, :ButtonRelease, Grp::BUTTON, 'ButtonRelease' ],
- [ 6, :MotionNotify, Grp::MOTION, 'Motion' ],
- [ 7, :EnterNotify, Grp::CROSSING, 'Enter' ],
- [ 8, :LeaveNotify, Grp::CROSSING, 'Leave' ],
- [ 9, :FocusIn, Grp::FOCUS, 'FocusIn' ],
- [ 10, :FocusOut, Grp::FOCUS, 'FocusOut' ],
- [ 11, :KeymapNotify, 0, ],
- [ 12, :Expose, Grp::EXPOSE, 'Expose' ],
- [ 13, :GraphicsExpose, Grp::EXPOSE, ],
- [ 14, :NoExpose, 0, ],
- [ 15, :VisibilityNotify, Grp::VISIBILITY, 'Visibility' ],
- [ 16, :CreateNotify, Grp::CREATE, 'Create' ],
- [ 17, :DestroyNotify, Grp::DESTROY, 'Destroy' ],
- [ 18, :UnmapNotify, Grp::UNMAP, 'Unmap' ],
- [ 19, :MapNotify, Grp::MAP, 'Map' ],
- [ 20, :MapRequest, Grp::MAPREQ, 'MapRequest' ],
- [ 21, :ReparentNotify, Grp::REPARENT, 'Reparent' ],
- [ 22, :ConfigureNotify, Grp::CONFIG, 'Configure' ],
- [ 23, :ConfigureRequest, Grp::CONFIGREQ, 'ConfigureRequest' ],
- [ 24, :GravityNotify, Grp::GRAVITY, 'Gravity' ],
- [ 25, :ResizeRequest, Grp::RESIZEREQ, 'ResizeRequest' ],
- [ 26, :CirculateNotify, Grp::CIRC, 'Circulate' ],
- [ 27, :CirculateRequest, 0, 'CirculateRequest' ],
- [ 28, :PropertyNotify, Grp::PROP, 'Property' ],
- [ 29, :SelectionClear, 0, ],
- [ 30, :SelectionRequest, 0, ],
- [ 31, :SelectionNotify, 0, ],
- [ 32, :ColormapNotify, Grp::COLORMAP, 'Colormap' ],
- [ 33, :ClientMessage, 0, ],
- [ 34, :MappingNotify, 0, ],
- [ 35, :VirtualEvent, Grp::VIRTUAL, ],
- [ 36, :ActivateNotify, Grp::ACTIVATE, 'Activate' ],
- [ 37, :DeactivateNotify, Grp::ACTIVATE, 'Deactivate' ],
- [ 38, :MouseWheelEvent, Grp::MWHEEL, 'MouseWheel' ],
- [ 39, :TK_LASTEVENT, 0, ]
- ]
-
module TypeNum
+ KeyPress = 2
+ KeyRelease = 3
+ ButtonPress = 4
+ ButtonRelease = 5
+ MotionNotify = 6
+ EnterNotify = 7
+ LeaveNotify = 8
+ FocusIn = 9
+ FocusOut = 10
+ KeymapNotify = 11
+ Expose = 12
+ GraphicsExpose = 13
+ NoExpose = 14
+ VisibilityNotify = 15
+ CreateNotify = 16
+ DestroyNotify = 17
+ UnmapNotify = 18
+ MapNotify = 19
+ MapRequest = 20
+ ReparentNotify = 21
+ ConfigureNotify = 22
+ ConfigureRequest = 23
+ GravityNotify = 24
+ ResizeRequest = 25
+ CirculateNotify = 26
+ CirculateRequest = 27
+ PropertyNotify = 28
+ SelectionClear = 29
+ SelectionRequest = 30
+ SelectionNotify = 31
+ ColormapNotify = 32
+ ClientMessage = 33
+ MappingNotify = 34
end
- TYPE_NAME_TBL = Hash.new
- TYPE_ID_TBL = Hash.new
- TYPE_GROUP_TBL = Hash.new
-
- type_data.each{|id, c_name, g_flag, *t_names|
- TypeNum.const_set(c_name, id)
- t_names.each{|t_name| t_name.freeze; TYPE_NAME_TBL[t_name] = id }
- TYPE_ID_TBL[id] = t_names
- TYPE_GROUP_TBL[id] = g_flag
- }
-
- TYPE_NAME_TBL.freeze
- TYPE_ID_TBL.freeze
-
- def self.type_id(name)
- TYPE_NAME_TBL[name.to_s]
- end
-
- def self.type_name(id)
- TYPE_ID_TBL[id] && TYPE_ID_TBL[id][0]
- end
-
- def self.group_flag(id)
- TYPE_GROUP_TBL[id] || 0
- end
-
- #############################################
-
- module StateMask
- ShiftMask = (1<<0)
- LockMask = (1<<1)
- ControlMask = (1<<2)
- Mod1Mask = (1<<3)
- Mod2Mask = (1<<4)
- Mod3Mask = (1<<5)
- Mod4Mask = (1<<6)
- Mod5Mask = (1<<7)
- Button1Mask = (1<<8)
- Button2Mask = (1<<9)
- Button3Mask = (1<<10)
- Button4Mask = (1<<11)
- Button5Mask = (1<<12)
-
- AnyModifier = (1<<15)
-
- META_MASK = (AnyModifier<<1)
- ALT_MASK = (AnyModifier<<2)
- EXTENDED_MASK = (AnyModifier<<3)
-
- CommandMask = Mod1Mask
- OptionMask = Mod2Mask
- end
-
- #############################################
-
- FIELD_FLAG = {
- # key => flag
- 'above' => Grp::CONFIG,
- 'borderwidth' => (Grp::CREATE|Grp::CONFIG),
- 'button' => Grp::BUTTON,
- 'count' => Grp::EXPOSE,
- 'data' => Grp::VIRTUAL,
- 'delta' => Grp::MWHEEL,
- 'detail' => (Grp::FOCUS|Grp::CROSSING),
- 'focus' => Grp::CROSSING,
- 'height' => (Grp::EXPOSE|Grp::CONFIG),
- 'keycode' => Grp::KEY,
- 'keysym' => Grp::KEY,
- 'mode' => (Grp::CROSSING|Grp::FOCUS),
- 'override' => (Grp::CREATE|Grp::MAP|Grp::REPARENT|Grp::CONFIG),
- 'place' => Grp::CIRC,
- 'root' => (Grp::KEY_BUTTON_MOTION_VIRTUAL|Grp::CROSSING),
- 'rootx' => (Grp::KEY_BUTTON_MOTION_VIRTUAL|Grp::CROSSING),
- 'rooty' => (Grp::KEY_BUTTON_MOTION_VIRTUAL|Grp::CROSSING),
- 'sendevent' => Grp::ALL,
- 'serial' => Grp::ALL,
- 'state' => (Grp::KEY_BUTTON_MOTION_VIRTUAL|
- Grp::CROSSING|Grp::VISIBILITY),
- 'subwindow' => (Grp::KEY_BUTTON_MOTION_VIRTUAL|Grp::CROSSING),
- 'time' => (Grp::KEY_BUTTON_MOTION_VIRTUAL|Grp::CROSSING|
- Grp::PROP),
- 'warp' => Grp::KEY_BUTTON_MOTION_VIRTUAL,
- 'width' => (Grp::EXPOSE|Grp::CREATE|Grp::CONFIG),
- 'window' => (Grp::CREATE|Grp::UNMAP|Grp::MAP|Grp::REPARENT|
- Grp::CONFIG|Grp::GRAVITY|Grp::CIRC),
- 'when' => Grp::ALL,
- 'x' => (Grp::KEY_BUTTON_MOTION_VIRTUAL|Grp::CROSSING|
- Grp::EXPOSE|Grp::CREATE|Grp::CONFIG|Grp::GRAVITY|
- Grp::REPARENT),
- 'y' => (Grp::KEY_BUTTON_MOTION_VIRTUAL|Grp::CROSSING|
- Grp::EXPOSE|Grp::CREATE|Grp::CONFIG|Grp::GRAVITY|
- Grp::REPARENT),
- }
-
- FIELD_OPERATION = {
- 'root' => proc{|val|
- begin
- Tk.tk_call_without_enc('winfo', 'pathname', val)
- val
- rescue
- nil
- end
- },
-
- 'subwindow' => proc{|val|
- begin
- Tk.tk_call_without_enc('winfo', 'pathname', val)
- val
- rescue
- nil
- end
- },
-
- 'window' => proc{|val| nil}
- }
-
- #-------------------------------------------
-
- def valid_fields(group_flag=nil)
- group_flag = self.class.group_flag(self.type) unless group_flag
-
- fields = {}
- FIELD_FLAG.each{|key, flag|
- next if (flag & group_flag) == 0
- begin
- val = self.__send__(key)
- rescue
- next
- end
- next if !val || val == '??'
- fields[key] = val
- }
-
- fields
- end
-
- def valid_for_generate(group_flag=nil)
- fields = valid_fields(group_flag)
-
- FIELD_OPERATION.each{|key, cmd|
- next unless fields.has_key?(key)
- val = FIELD_OPERATION[key].call(fields[key])
- if val
- fields[key] = val
- else
- fields.delete(key)
- end
- }
-
- fields
- end
-
- def generate(win, modkeys={})
- klass = self.class
-
- if modkeys.has_key?(:type) || modkeys.has_key?('type')
- modkeys = TkComm._symbolkey2str(modkeys)
- type_id = modkeys.delete('type')
- else
- type_id = self.type
- end
-
- type_name = klass.type_name(type_id)
- unless type_name
- fail RuntimeError, "type_id #{type_id} is invalid"
- end
-
- group_flag = klass.group_flag(type_id)
-
- opts = valid_for_generate(group_flag)
-
- modkeys.each{|key, val|
- if val
- opts[key.to_s] = val
- else
- opts.delete(key.to_s)
- end
- }
-
- if group_flag != Grp::KEY
- Tk.event_generate(win, type_name, opts)
- else
- # If type is KEY event, focus should be set to target widget.
- # If not set, original widget will get the same event.
- # That will make infinite loop.
- w = Tk.tk_call_without_enc('focus')
- begin
- Tk.tk_call_without_enc('focus', win)
- Tk.event_generate(win, type_name, opts)
- ensure
- Tk.tk_call_without_enc('focus', w)
- end
- end
- end
-
- #############################################
-
# [ <'%' subst-key char>, <proc type char>, <instance var (accessor) name>]
KEY_TBL = [
[ ?#, ?n, :serial ],
@@ -316,7 +76,6 @@ module TkEvent
[ ?E, ?b, :send_event ],
[ ?K, ?s, :keysym ],
[ ?N, ?n, :keysym_num ],
- [ ?P, ?s, :property ],
[ ?R, ?s, :rootwin_id ],
[ ?S, ?s, :subwindow ],
[ ?T, ?n, :type ],
@@ -372,34 +131,8 @@ module TkEvent
# []
#end
-=begin
- alias button num
- alias delta wheel_delta
- alias root rootwin_id
- alias rootx x_root
- alias root_x x_root
- alias rooty y_root
- alias root_y y_root
- alias sendevent send_event
-=end
- ALIAS_TBL = {
- :button => :num,
- :delta => :wheel_delta,
- :root => :rootwin_id,
- :rootx => :x_root,
- :root_x => :x_root,
- :rooty => :y_root,
- :root_y => :y_root,
- :sendevent => :send_event,
- :window => :widget
- }
-
- _define_attribute_aliases(ALIAS_TBL)
-
end
- ###############################################
-
def install_bind_for_event_class(klass, cmd, *args)
extra_args_tbl = klass._get_extra_args_tbl
@@ -442,3 +175,6 @@ module TkEvent
install_bind_for_event_class(TkEvent::Event, cmd, *args)
end
end
+
+################################################
+end
diff --git a/ext/tk/lib/tk/font.rb b/ext/tk/lib/tk/font.rb
index 8e63558cae..02e09c6066 100644
--- a/ext/tk/lib/tk/font.rb
+++ b/ext/tk/lib/tk/font.rb
@@ -20,17 +20,6 @@ class TkFont
Tk_FontUseTBL.clear
}
- # option_type : default => string
- OptionType = Hash.new(?s)
- OptionType['size'] = ?n
- OptionType['pointadjust'] = ?n
- OptionType['underline'] = ?b
- OptionType['overstrike'] = ?b
-
- # metric_type : default => num_or_str
- MetricType = Hash.new(?n)
- MetricType['fixed'] = ?b
-
# set default font
case Tk::TK_VERSION
when /^4\.*/
@@ -53,8 +42,7 @@ class TkFont
'-compound'))
else
# unknown Tcl/Tk-JP
- #platform = tk_call('set', 'tcl_platform(platform)')
- platform = Tk::PLATFORM['platform']
+ platform = tk_call('set', 'tcl_platform(platform)')
case platform
when 'unix'
ltn = {'family'=>'Helvetica'.freeze,
@@ -80,8 +68,7 @@ class TkFont
else # not JAPANIZED_TK
begin
- #platform = tk_call('set', 'tcl_platform(platform)')
- platform = Tk::PLATFORM['platform']
+ platform = tk_call('set', 'tcl_platform(platform)')
case platform
when 'unix'
ltn = {'family'=>'Helvetica'.freeze,
@@ -125,8 +112,6 @@ class TkFont
case type
when 'kanji', 'latin', 'ascii'
@type = type
- when :kanji, :latin, :ascii
- @type = type.to_s
else
fail ArgumentError, "unknown type '#{type}'"
end
@@ -163,96 +148,14 @@ class TkFont
###################################
# class methods
###################################
- def TkFont.actual(fnt, option=nil)
- fnt = '{}' if fnt == ''
- if fnt.kind_of?(TkFont)
- fnt.actual(option)
- else
- actual_core(fnt, nil, option)
- end
- end
-
- def TkFont.actual_displayof(fnt, win, option=nil)
- fnt = '{}' if fnt == ''
- if fnt.kind_of?(TkFont)
- fnt.actual_displayof(win, option)
- else
- win = '.' unless win
- actual_core(fnt, win, option)
- end
- end
-
- def TkFont.configure(fnt, slot, value=None)
- if fnt.kind_of?(TkFont)
- fnt.configure(fnt, slot, value)
- else
- configure_core(fnt, slot, value)
- end
- fnt
- end
-
- def TkFont.configinfo(fnt, slot=nil)
- if fnt.kind_of?(TkFont)
- fnt.configinfo(fnt, slot)
- else
- configinfo_core(fnt, slot)
- end
- end
-
- def TkFont.current_configinfo(fnt, slot=nil)
- if fnt.kind_of?(TkFont)
- fnt.current_configinfo(fnt, slot)
- else
- current_configinfo_core(fnt, slot)
- end
- end
-
- def TkFont.measure(fnt, text)
- fnt = '{}' if fnt == ''
- if fnt.kind_of?(TkFont)
- fnt.measure(text)
- else
- measure_core(fnt, nil, text)
- end
- end
-
- def TkFont.measure_displayof(fnt, win, text)
- fnt = '{}' if fnt == ''
- if fnt.kind_of?(TkFont)
- fnt.measure_displayof(win, text)
- else
- win = '.' unless win
- measure_core(fnt, win, text)
- end
- end
-
- def TkFont.metrics(fnt, option=nil)
- fnt = '{}' if fnt == ''
- if fnt.kind_of?(TkFont)
- fnt.metrics(option)
- else
- metrics_core(fnt, nil, option)
- end
- end
-
- def TkFont.metrics_displayof(fnt, win, option=nil)
- fnt = '{}' if fnt == ''
- if fnt.kind_of?(TkFont)
- font.metrics_displayof(win, option=nil)
- else
- win = '.' unless win
- metrics_core(fnt, win, option)
- end
- end
-
- def TkFont.families(win=nil)
+ def TkFont.families(window=nil)
case (Tk::TK_VERSION)
when /^4\.*/
['fixed']
when /^8\.*/
- if win
- tk_split_simplelist(tk_call('font', 'families', '-displayof', win))
+ if window
+ tk_split_simplelist(tk_call('font', 'families', '-displayof', window))
else
tk_split_simplelist(tk_call('font', 'families'))
end
@@ -344,17 +247,13 @@ class TkFont
fnt = nil if fnt == [] || fnt == ""
unless fnt
- # create dummy
- # TkFont.new(nil, nil).call_font_configure([path, key], *args)
- dummy_fnt = TkFont.allocate
- dummy_fnt.instance_eval{ init_dummy_fontobj() }
- dummy_fnt
+ TkFont.new(nil, nil).call_font_configure([path, key], *args)
else
begin
compound = tk_split_simplelist(
Hash[*tk_split_simplelist(tk_call('font', 'configure',
- fnt))].collect{|k,v|
- [k[1..-1], v]
+ fnt))].collect{|key,value|
+ [key[1..-1], value]
}.assoc('compound')[1])
rescue
compound = []
@@ -391,51 +290,7 @@ class TkFont
###################################
private
###################################
- def init_dummy_fontobj
- @id = Tk_FontID.join(TkCore::INTERP._ip_id_)
- Tk_FontID[1].succ!
- Tk_FontNameTBL[@id] = self
-
- @latin_desscendant = nil
- @kanji_desscendant = nil
-
- case (Tk::TK_VERSION)
- when /^4\.*/
- @latinfont = ""
- @kanjifont = ""
- if JAPANIZED_TK
- @compoundfont = [[@latinfont], [@kanjifont]]
- @fontslot = {'font'=>@latinfont, 'kanjifont'=>@kanjifont}
- else
- @compoundfont = @latinfont
- @fontslot = {'font'=>@latinfont}
- end
- else
- @latinfont = @id + 'l'
- @kanjifont = @id + 'k'
- @compoundfont = @id + 'c'
-
- if JAPANIZED_TK
- tk_call('font', 'create', @latinfont, '-charset', 'iso8859')
- tk_call('font', 'create', @kanjifont, '-charset', 'jisx0208.1983')
- tk_call('font', 'create', @compoundfont,
- '-compound', [@latinfont, @kanjifont])
- else
- tk_call('font', 'create', @latinfont)
- tk_call('font', 'create', @kanjifont)
- tk_call('font', 'create', @compoundfont)
- end
-
- @fontslot = {'font'=>@compoundfont}
- end
-
- self
- end
-
def initialize(ltn=nil, knj=nil, keys=nil)
- ltn = '{}' if ltn == ''
- knj = '{}' if knj == ''
-
# @id = Tk_FontID.join('')
@id = Tk_FontID.join(TkCore::INTERP._ip_id_)
Tk_FontID[1].succ!
@@ -711,17 +566,10 @@ class TkFont
end
def create_compoundfont_tk8x(ltn, knj, keys)
- if knj
- create_latinfont(ltn)
- create_kanjifont(knj)
- else
- cfnt = ltn
- create_kanjifont(cfnt)
- create_latinfont(cfnt)
- end
+ create_latinfont(ltn)
+ create_kanjifont(knj)
@compoundfont = @id + 'c'
-
if JAPANIZED_TK
unless keys
keys = {}
@@ -789,471 +637,53 @@ class TkFont
begin
actual_core(@latinfont).each{|key,val| latinkeys[key] = val}
rescue
- latinkeys = {}
+ latinkeys {}
end
if latinkeys != {}
tk_call('font', 'configure', @compoundfont, *hash_kv(latinkeys))
end
if knj
- compoundkeys = nil
kanjikeys = {}
begin
actual_core(@kanjifont).each{|key,val| kanjikeys[key] = val}
rescue
- kanjikeys = {}
+ kanjikeys {}
end
if kanjikeys != {}
tk_call('font', 'configure', @compoundfont, *hash_kv(kanjikeys))
end
end
- if cfnt
- if cfnt.kind_of?(Hash)
- compoundkeys = cfnt.dup
- else
- compoundkeys = {}
- actual_core(cfnt).each{|key,val| compoundkeys[key] = val}
- end
- compoundkeys.update(_symbolkey2str(keys))
- keys = compoundkeys
- end
-
@fontslot = {'font'=>@compoundfont}
tk_call('font', 'configure', @compoundfont, *hash_kv(keys))
end
end
- ###################################
- public
- ###################################
- def inspect
- sprintf("#<%s:%0x:%s>", self.class.inspect, self.__id__, @compoundfont)
- end
-
- def method_missing(id, *args)
- name = id.id2name
- case args.length
- when 1
- if name[-1] == ?=
- configure name[0..-2], args[0]
- args[0]
- else
- configure name, args[0]
- self
- end
- when 0
- begin
- configinfo name
- rescue
- fail NameError, "undefined local variable or method `#{name}' for #{self.to_s}", error_at
- end
- else
- fail NameError, "undefined method `#{name}' for #{self.to_s}", error_at
- end
- end
-
- def call_font_configure(path, *args)
- if path.kind_of?(Array)
- # [path, optkey]
- win, tag = path[0].split(';')
- optkey = path[1].to_s
- else
- win, tag, optkey = path.split(';')
- end
-
- fontslot = _symbolkey2str(@fontslot)
- if optkey && optkey != ""
- ltn = fontslot.delete('font')
- knj = fontslot.delete('kanjifont')
- fontslot[optkey] = ltn if ltn
- fontslot["kanji#{optkey}"] = knj if knj
- end
-
- keys = _symbolkey2str(args.pop).update(fontslot)
- args.concat(hash_kv(keys))
- tk_call(*args)
- Tk_FontUseTBL[[win, tag, optkey].join(';')] = self
- self
- end
-
- def used
- ret = []
- Tk_FontUseTBL.each{|key,value|
- next unless self == value
- if key.include?(';')
- win, tag, optkey = key.split(';')
- winobj = tk_tcl2ruby(win)
- if winobj.kind_of? TkText
- if optkey
- ret.push([winobj, winobj.tagid2obj(tag), optkey])
- else
- ret.push([winobj, winobj.tagid2obj(tag)])
- end
- elsif winobj.kind_of? TkCanvas
- if (tagobj = TkcTag.id2obj(winobj, tag)).kind_of? TkcTag
- if optkey
- ret.push([winobj, tagobj, optkey])
- else
- ret.push([winobj, tagobj])
- end
- elsif (tagobj = TkcItem.id2obj(winobj, tag)).kind_of? TkcItem
- if optkey
- ret.push([winobj, tagobj, optkey])
- else
- ret.push([winobj, tagobj])
- end
- else
- if optkey
- ret.push([winobj, tag, optkey])
- else
- ret.push([winobj, tag])
- end
- end
- elsif winobj.kind_of? TkMenu
- if optkey
- ret.push([winobj, tag, optkey])
- else
- ret.push([winobj, tag])
- end
- else
- if optkey
- ret.push([win, tag, optkey])
- else
- ret.push([win, tag])
- end
- end
- else
- ret.push(tk_tcl2ruby(key))
- end
- }
- ret
- end
-
- def id
- @id
- end
-
- def to_eval
- font
- end
-
- def font
- @compoundfont
- end
- alias font_id font
-
- def latin_font_id
- @latinfont
- end
-
- def latin_font
- # @latinfont
- if @latin_descendant
- @latin_descendant
- else
- @latin_descendant = DescendantFont.new(self, 'latin')
- end
- end
- alias latinfont latin_font
-
- def kanji_font_id
- @kanjifont
- end
-
- def kanji_font
- # @kanjifont
- if @kanji_descendant
- @kanji_descendant
- else
- @kanji_descendant = DescendantFont.new(self, 'kanji')
- end
- end
- alias kanjifont kanji_font
-
- def actual(option=nil)
- actual_core(@compoundfont, nil, option)
- end
-
- def actual_displayof(win, option=nil)
- win = '.' unless win
- actual_core(@compoundfont, win, option)
- end
-
- def latin_actual(option=nil)
- actual_core(@latinfont, nil, option)
- end
-
- def latin_actual_displayof(win, option=nil)
- win = '.' unless win
- actual_core(@latinfont, win, option)
- end
-
- def kanji_actual(option=nil)
- #if JAPANIZED_TK
- if @kanjifont != ""
- actual_core(@kanjifont, nil, option)
- else
- actual_core_tk4x(nil, nil, option)
- end
- end
-
- def kanji_actual_displayof(win, option=nil)
- #if JAPANIZED_TK
- if @kanjifont != ""
- win = '.' unless win
- actual_core(@kanjifont, win, option)
- else
- actual_core_tk4x(nil, win, option)
- end
- end
-
- def [](slot)
- configinfo slot
- end
-
- def []=(slot, val)
- configure slot, val
- val
- end
-
- def configure(slot, value=None)
- configure_core(@compoundfont, slot, value)
- self
- end
-
- def configinfo(slot=nil)
- configinfo_core(@compoundfont, slot)
- end
-
- def current_configinfo(slot=nil)
- current_configinfo_core(@compoundfont, slot)
- end
-
- def delete
- delete_core
- end
-
- def latin_configure(slot, value=None)
- if JAPANIZED_TK
- configure_core(@latinfont, slot, value)
- else
- configure(slot, value)
- end
- self
- end
-
- def latin_configinfo(slot=nil)
- if JAPANIZED_TK
- configinfo_core(@latinfont, slot)
- else
- configinfo(slot)
- end
- end
-
- def kanji_configure(slot, value=None)
- #if JAPANIZED_TK
- if @kanjifont != ""
- configure_core(@kanjifont, slot, value)
- configure('size'=>configinfo('size')) # to reflect new configuration
- else
- #""
- configure(slot, value)
- end
- self
- end
-
- def kanji_configinfo(slot=nil)
- #if JAPANIZED_TK
- if @kanjifont != ""
- configinfo_core(@kanjifont, slot)
- else
- #[]
- configinfo(slot)
- end
- end
-
- def replace(ltn, knj=None)
- knj = ltn if knj == None
- latin_replace(ltn)
- kanji_replace(knj)
- self
- end
-
- def latin_replace(ltn)
- latin_replace_core(ltn)
- reset_pointadjust
- self
- end
-
- def kanji_replace(knj)
- kanji_replace_core(knj)
- reset_pointadjust
- self
- end
-
- def measure(text)
- measure_core(@compoundfont, nil, text)
- end
-
- def measure_displayof(win, text)
- win = '.' unless win
- measure_core(@compoundfont, win, text)
- end
-
- def metrics(option=nil)
- metrics_core(@compoundfont, nil, option)
- end
-
- def metrics_displayof(win, option=nil)
- win = '.' unless win
- metrics_core(@compoundfont, win, option)
- end
-
- def latin_metrics(option=nil)
- metrics_core(@latinfont, nil, option)
- end
-
- def latin_metrics_displayof(win, option=nil)
- win = '.' unless win
- metrics_core(@latinfont, win, option)
- end
-
- def kanji_metrics(option=nil)
- if JAPANIZED_TK
- metrics_core(@kanjifont, nil, option)
- else
- metrics_core_tk4x(nil, nil, option)
- end
- end
-
- def kanji_metrics_displayof(win, option=nil)
- if JAPANIZED_TK
- win = '.' unless win
- metrics_core(@kanjifont, win, option)
- else
- metrics_core_tk4x(nil, win, option)
- end
- end
-
- def reset_pointadjust
- begin
- if /^8\.*/ === Tk::TK_VERSION && JAPANIZED_TK
- configure('pointadjust' => latin_actual.assoc('size')[1].to_f /
- kanji_actual.assoc('size')[1].to_f )
- end
- rescue
- end
- self
- end
-
- ###################################
- # private alias
- ###################################
- case (Tk::TK_VERSION)
- when /^4\.*/
- alias create_latinfont create_latinfont_tk4x
- alias create_kanjifont create_kanjifont_tk4x
- alias create_compoundfont create_compoundfont_tk4x
-
- when /^8\.[0-5]/
- alias create_latinfont create_latinfont_tk8x
- alias create_kanjifont create_kanjifont_tk8x
- alias create_compoundfont create_compoundfont_tk8x
-
- else
- alias create_latinfont create_latinfont_tk8x
- alias create_kanjifont create_kanjifont_tk8x
- alias create_compoundfont create_compoundfont_tk8x
-
- end
-
- ###################################
- # public alias
- ###################################
- alias ascii_font latin_font
- alias asciifont latinfont
- alias create_asciifont create_latinfont
- alias ascii_actual latin_actual
- alias ascii_actual_displayof latin_actual_displayof
- alias ascii_configure latin_configure
- alias ascii_configinfo latin_configinfo
- alias ascii_replace latin_replace
- alias ascii_metrics latin_metrics
-
- ###################################
-=begin
- def dup
- src = self
- obj = super()
- obj.instance_eval{ initialize(src) }
- obj
- end
- def clone
- src = self
- obj = super()
- obj.instance_eval{ initialize(src) }
- obj
- end
-=end
- def dup
- TkFont.new(self)
- end
- def clone
- TkFont.new(self)
- end
-end
-
-module TkFont::CoreMethods
- include Tk
- extend TkCore
-
- private
-
- def actual_core_tk4x(font, win=nil, option=nil)
+ def actual_core_tk4x(font, window=nil, option=nil)
# dummy
- if option == 'pointadjust' || option == :pointadjust
- 1.0
- elsif option
- case TkFont::OptionType[option.to_s]
- when ?n
- 0
- when ?b
- false
- else
- ''
- end
+ if option
+ ""
else
- [['family',''], ['size',0], ['weight',''], ['slant',''],
- ['underline',false], ['overstrike',false], ['charset',''],
- ['pointadjust',0]]
+ [['family',[]], ['size',[]], ['weight',[]], ['slant',[]],
+ ['underline',[]], ['overstrike',[]], ['charset',[]],
+ ['pointadjust',[]]]
end
end
- def actual_core_tk8x(font, win=nil, option=nil)
- font = '{}' if font == ''
-
- if option == 'compound' || option == :compound
+ def actual_core_tk8x(font, window=nil, option=nil)
+ if option == 'compound'
""
elsif option
- if win
- val = tk_call('font', 'actual', font,
- "-displayof", win, "-#{option}")
- else
- val = tk_call('font', 'actual', font, "-#{option}")
- end
- case TkFont::OptionType[option.to_s]
- when ?n
- num_or_str(val)
- when ?b
- bool(val)
+ if window
+ tk_call('font', 'actual', font, "-displayof", window, "-#{option}")
else
- val
+ tk_call('font', 'actual', font, "-#{option}")
end
else
- l = tk_split_simplelist(if win
+ l = tk_split_simplelist(if window
tk_call('font', 'actual', font,
- "-displayof", win)
+ "-displayof", window)
else
tk_call('font', 'actual', font)
end)
@@ -1262,16 +692,7 @@ module TkFont::CoreMethods
if key == '-compound'
l.shift
else
- key = key[1..-1]
- val = l.shift
- case TkFont::OptionType[key]
- when ?n
- r.push [key, num_or_str(val)]
- when ?b
- r.push [key, bool(val)]
- else
- r.push [key, val]
- end
+ r.push [key[1..-1], l.shift]
end
end
r
@@ -1286,21 +707,12 @@ module TkFont::CoreMethods
def configinfo_core_tk4x(font, option=nil)
# dummy
if TkComm::GET_CONFIGINFOwoRES_AS_ARRAY
- if option == 'pointadjust' || option == :pointadjust
- 1.0
- elsif option
- case TkFont::OptionType[option.to_s]
- when ?n
- 0
- when ?b
- false
- else
- ''
- end
+ if option
+ ""
else
- [['family',''], ['size',0], ['weight',''], ['slant',''],
- ['underline',false], ['overstrike',false], ['charset',''],
- ['pointadjust',1.0]]
+ [['family',[]], ['size',[]], ['weight',[]], ['slant',[]],
+ ['underline',[]], ['overstrike',[]], ['charset',[]],
+ ['pointadjust',[]]]
end
else # ! TkComm::GET_CONFIGINFOwoRES_AS_ARRAY
current_configinfo_core_tk4x(font, option)
@@ -1309,18 +721,10 @@ module TkFont::CoreMethods
def current_configinfo_core_tk4x(font, option=nil)
if option
- case TkFont::OptionType[option.to_s]
- when ?n
- 0
- when ?b
- false
- else
- ''
- end
+ ""
else
- {'family'=>'', 'size'=>0, 'weight'=>'', 'slant'=>'',
- 'underline'=>false, 'overstrike'=>false,
- 'charset'=>false, 'pointadjust'=>1.0}
+ {'family'=>'', 'size'=>'', 'weight'=>'', 'slant'=>'',
+ 'underline'=>'', 'overstrike'=>'', 'charset'=>'', 'pointadjust'=>''}
end
end
@@ -1393,18 +797,10 @@ module TkFont::CoreMethods
def configinfo_core_tk8x(font, option=nil)
if TkComm::GET_CONFIGINFOwoRES_AS_ARRAY
- if option == 'compound' || option == :compound
+ if option == 'compound'
""
elsif option
- val = tk_call('font', 'configure', font, "-#{option}")
- case TkFont::OptionType[option.to_s]
- when ?n
- num_or_str(val)
- when ?b
- bool(val)
- else
- val
- end
+ tk_call('font', 'configure', font, "-#{option}")
else
l = tk_split_simplelist(tk_call('font', 'configure', font))
r = []
@@ -1412,16 +808,7 @@ module TkFont::CoreMethods
if key == '-compound'
l.shift
else
- key = key[1..-1]
- val = l.shift
- case TkFont::OptionType[key]
- when ?n
- r.push [key, num_or_str(val)]
- when ?b
- r.push [key, bool(val)]
- else
- r.push [key, val]
- end
+ r.push [key[1..-1], l.shift]
end
end
r
@@ -1435,15 +822,7 @@ module TkFont::CoreMethods
if option == 'compound'
""
elsif option
- val = tk_call('font', 'configure', font, "-#{option}")
- case TkFont::OptionType[option.to_s]
- when ?n
- num_or_str(val)
- when ?b
- bool(val)
- else
- val
- end
+ tk_call('font', 'configure', font, "-#{option}")
else
l = tk_split_simplelist(tk_call('font', 'configure', font))
r = {}
@@ -1451,16 +830,7 @@ module TkFont::CoreMethods
if key == '-compound'
l.shift
else
- key = key[1..-1]
- val = l.shift
- case TkFont::OptionType[key]
- when ?n
- r.push [key, num_or_str(val)]
- when ?b
- r.push [key, bool(val)]
- else
- r.push [key, val]
- end
+ r[key[1..-1]] = l.shift
end
end
r
@@ -1468,8 +838,8 @@ module TkFont::CoreMethods
end
def delete_core_tk4x
- TkFont::Tk_FontNameTBL.delete(@id)
- TkFont::Tk_FontUseTBL.delete_if{|key,value| value == self}
+ Tk_FontNameTBL.delete(@id)
+ Tk_FontUseTBL.delete_if{|key,value| value == self}
end
def delete_core_tk8x
@@ -1485,15 +855,15 @@ module TkFont::CoreMethods
tk_call('font', 'delete', @compoundfont)
rescue
end
- TkFont::Tk_FontNameTBL.delete(@id)
- TkFont::Tk_FontUseTBL.delete_if{|key,value| value == self}
+ Tk_FontNameTBL.delete(@id)
+ Tk_FontUseTBL.delete_if{|key,value| value == self}
end
def latin_replace_core_tk4x(ltn)
create_latinfont_tk4x(ltn)
@compoundfont[0] = [@latinfont] if JAPANIZED_TK
@fontslot['font'] = @latinfont
- TkFont::Tk_FontUseTBL.dup.each{|w, fobj|
+ Tk_FontUseTBL.dup.each{|w, fobj|
if self == fobj
begin
if w.include?(';')
@@ -1515,7 +885,7 @@ module TkFont::CoreMethods
tk_call(w, 'configure', '-font', @latinfont)
end
rescue
- TkFont::Tk_FontUseTBL.delete(w)
+ Tk_FontUseTBL.delete(w)
end
end
}
@@ -1528,7 +898,7 @@ module TkFont::CoreMethods
create_kanjifont_tk4x(knj)
@compoundfont[1] = [@kanjifont]
@fontslot['kanjifont'] = @kanjifont
- TkFont::Tk_FontUseTBL.dup.each{|w, fobj|
+ Tk_FontUseTBL.dup.each{|w, fobj|
if self == fobj
begin
if w.include?(';')
@@ -1550,7 +920,7 @@ module TkFont::CoreMethods
tk_call(w, 'configure', '-kanjifont', @kanjifont)
end
rescue
- TkFont::Tk_FontUseTBL.delete(w)
+ Tk_FontUseTBL.delete(w)
end
end
}
@@ -1558,8 +928,6 @@ module TkFont::CoreMethods
end
def latin_replace_core_tk8x(ltn)
- ltn = '{}' if ltn == ''
-
if JAPANIZED_TK
begin
tk_call('font', 'delete', '@font_tmp')
@@ -1569,7 +937,7 @@ module TkFont::CoreMethods
fnt_bup = tk_call('font', 'create', '@font_tmp', '-copy', @latinfont)
rescue
#fnt_bup = ''
- fnt_bup = TkFont::DEFAULT_LATIN_FONT_NAME
+ fnt_bup = DEFAULT_LATIN_FONT_NAME
end
end
@@ -1590,7 +958,7 @@ module TkFont::CoreMethods
begin
actual_core(@latinfont).each{|key,val| latinkeys[key] = val}
rescue
- latinkeys = {}
+ latinkeys {}
end
if latinkeys != {}
tk_call('font', 'configure', @compoundfont, *hash_kv(latinkeys))
@@ -1613,7 +981,7 @@ module TkFont::CoreMethods
begin
actual_core(@latinfont).each{|key,val| latinkeys[key] = val}
rescue
- latinkeys = {}
+ latinkeys {}
end
if latinkeys != {}
tk_call('font', 'configure', @compoundfont, *hash_kv(latinkeys))
@@ -1623,8 +991,6 @@ module TkFont::CoreMethods
end
def kanji_replace_core_tk8x(knj)
- knj = '{}' if knj == ''
-
if JAPANIZED_TK
begin
tk_call('font', 'delete', '@font_tmp')
@@ -1634,7 +1000,7 @@ module TkFont::CoreMethods
fnt_bup = tk_call('font', 'create', '@font_tmp', '-copy', @kanjifont)
rescue
#fnt_bup = ''
- fnt_bup = TkFont::DEFAULT_KANJI_FONT_NAME
+ fnt_bup = DEFAULT_KANJI_FONT_NAME
end
end
@@ -1665,22 +1031,20 @@ module TkFont::CoreMethods
self
end
- def measure_core_tk4x(font, win, text)
+ def measure_core_tk4x(window, text)
0
end
- def measure_core_tk8x(font, win, text)
- font = '{}' if font == ''
-
- if win
- number(tk_call('font', 'measure', font,
- '-displayof', win, text))
+ def measure_core_tk8x(window, text)
+ if window
+ number(tk_call('font', 'measure', @compoundfont,
+ '-displayof', window, text))
else
- number(tk_call('font', 'measure', font, text))
+ number(tk_call('font', 'measure', @compoundfont, text))
end
end
- def metrics_core_tk4x(font, win, option=nil)
+ def metrics_core_tk4x(font, window, option=nil)
# dummy
if option
""
@@ -1689,19 +1053,17 @@ module TkFont::CoreMethods
end
end
- def metrics_core_tk8x(font, win, option=nil)
- font = '{}' if font == ''
-
+ def metrics_core_tk8x(font, window, option=nil)
if option
- if win
+ if window
number(tk_call('font', 'metrics', font,
- "-displayof", win, "-#{option}"))
+ "-displayof", window, "-#{option}"))
else
number(tk_call('font', 'metrics', font, "-#{option}"))
end
else
- l = tk_split_list(if win
- tk_call('font','metrics',font,"-displayof",win)
+ l = tk_split_list(if window
+ tk_call('font','metrics',font,"-displayof",window)
else
tk_call('font','metrics',font)
end)
@@ -1718,6 +1080,9 @@ module TkFont::CoreMethods
###################################
case (Tk::TK_VERSION)
when /^4\.*/
+ alias create_latinfont create_latinfont_tk4x
+ alias create_kanjifont create_kanjifont_tk4x
+ alias create_compoundfont create_compoundfont_tk4x
alias actual_core actual_core_tk4x
alias configure_core configure_core_tk4x
alias configinfo_core configinfo_core_tk4x
@@ -1729,6 +1094,9 @@ module TkFont::CoreMethods
alias metrics_core metrics_core_tk4x
when /^8\.[0-5]/
+ alias create_latinfont create_latinfont_tk8x
+ alias create_kanjifont create_kanjifont_tk8x
+ alias create_compoundfont create_compoundfont_tk8x
alias actual_core actual_core_tk8x
alias configure_core configure_core_tk8x
alias configinfo_core configinfo_core_tk8x
@@ -1740,6 +1108,9 @@ module TkFont::CoreMethods
alias metrics_core metrics_core_tk8x
else
+ alias create_latinfont create_latinfont_tk8x
+ alias create_kanjifont create_kanjifont_tk8x
+ alias create_compoundfont create_compoundfont_tk8x
alias actual_core actual_core_tk8x
alias configure_core configure_core_tk8x
alias configinfo_core configinfo_core_tk8x
@@ -1751,9 +1122,343 @@ module TkFont::CoreMethods
alias metrics_core metrics_core_tk8x
end
-end
-class TkFont
- include TkFont::CoreMethods
- extend TkFont::CoreMethods
+ ###################################
+ public
+ ###################################
+ def method_missing(id, *args)
+ name = id.id2name
+ case args.length
+ when 1
+ configure name, args[0]
+ when 0
+ begin
+ configinfo name
+ rescue
+ fail NameError, "undefined local variable or method `#{name}' for #{self.to_s}", error_at
+ end
+ else
+ fail NameError, "undefined method `#{name}' for #{self.to_s}", error_at
+ end
+ end
+
+ def call_font_configure(path, *args)
+ if path.kind_of?(Array)
+ # [path, optkey]
+ win, tag = path[0].split(';')
+ optkey = path[1].to_s
+ else
+ win, tag, optkey = path.split(';')
+ end
+
+ fontslot = _symbolkey2str(@fontslot)
+ if optkey && optkey != ""
+ ltn = fontslot.delete('font')
+ knj = fontslot.delete('kanjifont')
+ fontslot[optkey] = ltn if ltn
+ fontslot["kanji#{optkey}"] = knj if knj
+ end
+
+ keys = _symbolkey2str(args.pop).update(fontslot)
+ args.concat(hash_kv(keys))
+ tk_call(*args)
+ Tk_FontUseTBL[[win, tag, optkey].join(';')] = self
+ self
+ end
+
+ def used
+ ret = []
+ Tk_FontUseTBL.each{|key,value|
+ next unless self == value
+ if key.include?(';')
+ win, tag, optkey = key.split(';')
+ winobj = tk_tcl2ruby(win)
+ if winobj.kind_of? TkText
+ if optkey
+ ret.push([winobj, winobj.tagid2obj(tag), optkey])
+ else
+ ret.push([winobj, winobj.tagid2obj(tag)])
+ end
+ elsif winobj.kind_of? TkCanvas
+ if (tagobj = TkcTag.id2obj(winobj, tag)).kind_of? TkcTag
+ if optkey
+ ret.push([winobj, tagobj, optkey])
+ else
+ ret.push([winobj, tagobj])
+ end
+ elsif (tagobj = TkcItem.id2obj(winobj, tag)).kind_of? TkcItem
+ if optkey
+ ret.push([winobj, tagobj, optkey])
+ else
+ ret.push([winobj, tagobj])
+ end
+ else
+ if optkey
+ ret.push([winobj, tag, optkey])
+ else
+ ret.push([winobj, tag])
+ end
+ end
+ elsif winobj.kind_of? TkMenu
+ if optkey
+ ret.push([winobj, tag, optkey])
+ else
+ ret.push([winobj, tag])
+ end
+ else
+ if optkey
+ ret.push([win, tag, optkey])
+ else
+ ret.push([win, tag])
+ end
+ end
+ else
+ ret.push(tk_tcl2ruby(key))
+ end
+ }
+ ret
+ end
+
+ def id
+ @id
+ end
+
+ def to_eval
+ font
+ end
+
+ def font
+ @compoundfont
+ end
+ alias font_id font
+
+ def latin_font_id
+ @latinfont
+ end
+
+ def latin_font
+ # @latinfont
+ if @latin_descendant
+ @latin_descendant
+ else
+ @latin_descendant = DescendantFont.new(self, 'latin')
+ end
+ end
+ alias latinfont latin_font
+
+ def kanji_font_id
+ @kanjifont
+ end
+
+ def kanji_font
+ # @kanjifont
+ if @kanji_descendant
+ @kanji_descendant
+ else
+ @kanji_descendant = DescendantFont.new(self, 'kanji')
+ end
+ end
+ alias kanjifont kanji_font
+
+ def actual(option=nil)
+ actual_core(@compoundfont, nil, option)
+ end
+
+ def actual_displayof(window, option=nil)
+ window = '.' unless window
+ actual_core(@compoundfont, window, option)
+ end
+
+ def latin_actual(option=nil)
+ actual_core(@latinfont, nil, option)
+ end
+
+ def latin_actual_displayof(window, option=nil)
+ window = '.' unless window
+ actual_core(@latinfont, window, option)
+ end
+
+ def kanji_actual(option=nil)
+ #if JAPANIZED_TK
+ if @kanjifont != ""
+ actual_core(@kanjifont, nil, option)
+ else
+ actual_core_tk4x(nil, nil, option)
+ end
+ end
+
+ def kanji_actual_displayof(window, option=nil)
+ #if JAPANIZED_TK
+ if @kanjifont != ""
+ window = '.' unless window
+ actual_core(@kanjifont, window, option)
+ else
+ actual_core_tk4x(nil, window, option)
+ end
+ end
+
+ def [](slot)
+ configinfo slot
+ end
+
+ def []=(slot, val)
+ configure slot, val
+ val
+ end
+
+ def configure(slot, value=None)
+ configure_core(@compoundfont, slot, value)
+ self
+ end
+
+ def configinfo(slot=nil)
+ configinfo_core(@compoundfont, slot)
+ end
+
+ def current_configinfo(slot=nil)
+ current_configinfo_core(@compoundfont, slot)
+ end
+
+ def delete
+ delete_core
+ end
+
+ def latin_configure(slot, value=None)
+ if JAPANIZED_TK
+ configure_core(@latinfont, slot, value)
+ else
+ configure(slot, value)
+ end
+ self
+ end
+
+ def latin_configinfo(slot=nil)
+ if JAPANIZED_TK
+ configinfo_core(@latinfont, slot)
+ else
+ configinfo(slot)
+ end
+ end
+
+ def kanji_configure(slot, value=None)
+ #if JAPANIZED_TK
+ if @kanjifont != ""
+ configure_core(@kanjifont, slot, value)
+ configure('size'=>configinfo('size')) # to reflect new configuration
+ else
+ #""
+ configure(slot, value)
+ end
+ self
+ end
+
+ def kanji_configinfo(slot=nil)
+ #if JAPANIZED_TK
+ if @kanjifont != ""
+ configinfo_core(@kanjifont, slot)
+ else
+ #[]
+ configinfo(slot)
+ end
+ end
+
+ def replace(ltn, knj)
+ latin_replace(ltn)
+ kanji_replace(knj)
+ self
+ end
+
+ def latin_replace(ltn)
+ latin_replace_core(ltn)
+ reset_pointadjust
+ self
+ end
+
+ def kanji_replace(knj)
+ kanji_replace_core(knj)
+ reset_pointadjust
+ self
+ end
+
+ def measure(text)
+ measure_core(nil, text)
+ end
+
+ def measure_displayof(window, text)
+ window = '.' unless window
+ measure_core(window, text)
+ end
+
+ def metrics(option=nil)
+ metrics_core(@compoundfont, nil, option)
+ end
+
+ def metrics_displayof(window, option=nil)
+ window = '.' unless window
+ metrics_core(@compoundfont, window, option)
+ end
+
+ def latin_metrics(option=nil)
+ metrics_core(@latinfont, nil, option)
+ end
+
+ def latin_metrics_displayof(window, option=nil)
+ window = '.' unless window
+ metrics_core(@latinfont, window, option)
+ end
+
+ def kanji_metrics(option=nil)
+ if JAPANIZED_TK
+ metrics_core(@kanjifont, nil, option)
+ else
+ metrics_core_tk4x(nil, nil, option)
+ end
+ end
+
+ def kanji_metrics_displayof(window, option=nil)
+ if JAPANIZED_TK
+ window = '.' unless window
+ metrics_core(@kanjifont, window, option)
+ else
+ metrics_core_tk4x(nil, window, option)
+ end
+ end
+
+ def reset_pointadjust
+ begin
+ if /^8\.*/ === Tk::TK_VERSION && JAPANIZED_TK
+ configure('pointadjust' => latin_actual.assoc('size')[1].to_f /
+ kanji_actual.assoc('size')[1].to_f )
+ end
+ rescue
+ end
+ self
+ end
+
+ ###################################
+ # public alias
+ ###################################
+ alias ascii_font latin_font
+ alias asciifont latinfont
+ alias create_asciifont create_latinfont
+ alias ascii_actual latin_actual
+ alias ascii_actual_displayof latin_actual_displayof
+ alias ascii_configure latin_configure
+ alias ascii_configinfo latin_configinfo
+ alias ascii_replace latin_replace
+ alias ascii_metrics latin_metrics
+
+ ###################################
+ def dup
+ src = self
+ obj = super()
+ obj.instance_eval{ initialize(src) }
+ obj
+ end
+ def clone
+ src = self
+ obj = super()
+ obj.instance_eval{ initialize(src) }
+ obj
+ end
end
diff --git a/ext/tk/lib/tk/frame.rb b/ext/tk/lib/tk/frame.rb
index 6636fef5b5..4f01825da9 100644
--- a/ext/tk/lib/tk/frame.rb
+++ b/ext/tk/lib/tk/frame.rb
@@ -30,11 +30,6 @@ class TkFrame<TkWindow
# end
#################
- def __boolval_optkeys
- super() << 'container'
- end
- private :__boolval_optkeys
-
def initialize(parent=nil, keys=nil)
my_class_name = nil
if self.class < WidgetClassNames[self.class::WidgetClassName]
@@ -97,18 +92,18 @@ class TkFrame<TkWindow
self.database_class.name
end
- def self.bind(*args, &b)
+ def self.bind(*args)
if self == WidgetClassNames[WidgetClassName] || self.name == ''
- super(*args, &b)
+ super(*args)
else
- TkDatabaseClass.new(self.name).bind(*args, &b)
+ TkDatabaseClass.new(self.name).bind(*args)
end
end
- def self.bind_append(*args, &b)
+ def self.bind_append(*args)
if self == WidgetClassNames[WidgetClassName] || self.name == ''
- super(*args, &b)
+ super(*args)
else
- TkDatabaseClass.new(self.name).bind_append(*args, &b)
+ TkDatabaseClass.new(self.name).bind_append(*args)
end
end
def self.bind_remove(*args)
diff --git a/ext/tk/lib/tk/grid.rb b/ext/tk/lib/tk/grid.rb
index 10fdf3569b..74287d43bd 100644
--- a/ext/tk/lib/tk/grid.rb
+++ b/ext/tk/lib/tk/grid.rb
@@ -42,16 +42,7 @@ module TkGrid
params.push("-#{k}")
params.push((v.kind_of?(TkObject))? v.epath: v)
}
- if Tk::TCL_MAJOR_VERSION < 8 ||
- (Tk::TCL_MAJOR_VERSION == 8 && Tk::TCL_MINOR_VERSION <= 3)
- if params[0] == '-' || params[0] == 'x' || params[0] == '^'
- tk_call_without_enc('grid', *params)
- else
- tk_call_without_enc('grid', 'configure', *params)
- end
- else
- tk_call_without_enc('grid', 'configure', *params)
- end
+ tk_call_without_enc("grid", 'configure', *params)
end
alias grid configure
@@ -158,13 +149,13 @@ module TkGrid
list(tk_call_without_enc('grid', 'location', master, x, y))
end
- def propagate(master, mode=None)
+ def propagate(master, bool=None)
# master = master.epath if master.kind_of?(TkObject)
master = _epath(master)
- if mode == None
+ if bool == None
bool(tk_call_without_enc('grid', 'propagate', master))
else
- tk_call_without_enc('grid', 'propagate', master, mode)
+ tk_call_without_enc('grid', 'propagate', master, bool)
end
end
diff --git a/ext/tk/lib/tk/image.rb b/ext/tk/lib/tk/image.rb
index 35e2c4e394..7fd61eff5d 100644
--- a/ext/tk/lib/tk/image.rb
+++ b/ext/tk/lib/tk/image.rb
@@ -14,55 +14,11 @@ class TkImage<TkObject
TkCore::INTERP.init_ip_env{ Tk_IMGTBL.clear }
- def self.new(keys=nil)
- if keys.kind_of?(Hash)
- name = nil
- if keys.key?(:imagename)
- name = keys[:imagename]
- elsif keys.key?('imagename')
- name = keys['imagename']
- end
- if name
- if name.kind_of?(TkImage)
- obj = name
- else
- name = _get_eval_string(name)
- obj = Tk_IMGTBL[name]
- end
- if obj
- if !(keys[:without_creating] || keys['without_creating'])
- keys = _symbolkey2str(keys)
- keys.delete('imagename')
- keys.delete('without_creating')
- obj.instance_eval{
- tk_call_without_enc('image', 'create',
- @type, @path, *hash_kv(keys, true))
- }
- end
- return obj
- end
- end
- end
- super(keys)
- end
-
def initialize(keys=nil)
- @path = nil
- without_creating = false
- if keys.kind_of?(Hash)
- keys = _symbolkey2str(keys)
- @path = keys.delete('imagename')
- without_creating = keys.delete('without_creating')
- end
- unless @path
- # @path = Tk_Image_ID.join('')
- @path = Tk_Image_ID.join(TkCore::INTERP._ip_id_)
- Tk_Image_ID[1].succ!
- end
- unless without_creating
- tk_call_without_enc('image', 'create',
- @type, @path, *hash_kv(keys, true))
- end
+ # @path = Tk_Image_ID.join('')
+ @path = Tk_Image_ID.join(TkCore::INTERP._ip_id_)
+ Tk_Image_ID[1].succ!
+ tk_call_without_enc('image', 'create', @type, @path, *hash_kv(keys, true))
Tk_IMGTBL[@path] = self
end
@@ -96,14 +52,9 @@ class TkImage<TkObject
end
class TkBitmapImage<TkImage
- def __strval_optkeys
- super() + ['maskdata', 'maskfile']
- end
- private :__strval_optkeys
-
def initialize(*args)
@type = 'bitmap'
- super(*args)
+ super
end
end
@@ -119,15 +70,13 @@ class TkPhotoImage<TkImage
keys.delete(opt)
end
}
- keys.collect{|k,v|
- ['-' << k, v]
- }.flatten
+ hash_kv(keys).flatten
end
private :_photo_hash_kv
def initialize(*args)
@type = 'photo'
- super(*args)
+ super
end
def blank
@@ -138,9 +87,9 @@ class TkPhotoImage<TkImage
def cget(option)
case option.to_s
when 'data', 'file'
- tk_send 'cget', '-' << option.to_s
+ tk_send 'cget', option
else
- tk_tcl2ruby(tk_send('cget', '-' << option.to_s))
+ tk_tcl2ruby(tk_send('cget', option))
end
end
diff --git a/ext/tk/lib/tk/itemconfig.rb b/ext/tk/lib/tk/itemconfig.rb
index 0b84be38b8..f0f13e63bd 100644
--- a/ext/tk/lib/tk/itemconfig.rb
+++ b/ext/tk/lib/tk/itemconfig.rb
@@ -6,8 +6,6 @@ require 'tkutil'
require 'tk/itemfont.rb'
module TkItemConfigOptkeys
- include TkUtil
-
def __item_numval_optkeys(id)
[]
end
@@ -19,19 +17,13 @@ module TkItemConfigOptkeys
private :__item_numstrval_optkeys
def __item_boolval_optkeys(id)
- ['exportselection', 'jump', 'setgrid', 'takefocus']
+ []
end
private :__item_boolval_optkeys
def __item_strval_optkeys(id)
# maybe need to override
- [
- 'text', 'label', 'show', 'data', 'file', 'maskdata', 'maskfile',
- 'activebackground', 'activeforeground', 'background',
- 'disabledforeground', 'disabledbackground', 'foreground',
- 'highlightbackground', 'highlightcolor', 'insertbackground',
- 'selectbackground', 'selectforeground', 'troughcolor'
- ]
+ ['text', 'label', 'show', 'data', 'file', 'maskdata', 'maskfile']
end
private :__item_strval_optkeys
@@ -46,30 +38,7 @@ module TkItemConfigOptkeys
end
private :__item_numlistval_optkeys
- def __item_tkvariable_optkeys(id)
- ['variable', 'textvariable']
- end
- private :__item_tkvariable_optkeys
-
- def __item_val2ruby_optkeys(id) # { key=>method, ... }
- # The method is used to convert a opt-value to a ruby's object.
- # When get the value of the option "key", "method.call(id, val)" is called.
- {}
- end
- private :__item_val2ruby_optkeys
-
- def __item_ruby2val_optkeys(id) # { key=>method, ... }
- # The method is used to convert a ruby's object to a opt-value.
- # When set the value of the option "key", "method.call(id, val)" is called.
- # That is, "-#{key} #{method.call(id, value)}".
- {}
- end
- private :__item_ruby2val_optkeys
-
def __item_methodcall_optkeys(id) # { key=>method, ... }
- # Use the method for both of get and set.
- # Usually, the 'key' will not be a widget option.
- #
# maybe need to override
# {'coords'=>'coords'}
{}
@@ -150,23 +119,8 @@ module TkItemConfigMethod
################################################
def itemcget(tagOrId, option)
- orig_opt = option
option = option.to_s
- if option.length == 0
- fail ArgumentError, "Invalid option `#{orig_opt.inspect}'"
- end
-
- if ( method = _symbolkey2str(__item_val2ruby_optkeys(tagid(tagOrId)))[option] )
- optval = tk_call_without_enc(*(__item_cget_cmd(tagid(tagOrId)) << "-#{option}"))
- begin
- return method.call(tagOrId, optval)
- rescue => e
- warn("Warning:: #{e.message} (when #{method}.call(#{tagOrId.inspect}, #{optval.inspect})") if $DEBUG
- return optval
- end
- end
-
if ( method = _symbolkey2str(__item_methodcall_optkeys(tagid(tagOrId)))[option] )
return self.__send__(method, tagOrId)
end
@@ -200,10 +154,6 @@ module TkItemConfigMethod
conf
end
- when /^(#{__item_tkvariable_optkeys(tagid(tagOrId)).join('|')})$/
- v = tk_call_without_enc(*(__item_cget_cmd(tagid(tagOrId)) << "-#{option}"))
- (v.empty?)? nil: TkVarAccess.new(v)
-
when /^(#{__item_strval_optkeys(tagid(tagOrId)).join('|')})$/
_fromUTF8(tk_call_without_enc(*(__item_cget_cmd(tagid(tagOrId)) << "-#{option}")))
@@ -234,11 +184,6 @@ module TkItemConfigMethod
self.__send__(method, tagOrId, value) if value
}
- __item_ruby2val_optkeys(tagid(tagOrId)).each{|key, method|
- key = key.to_s
- slot[key] = method.call(tagOrId, slot[key]) if slot.has_key?(key)
- }
-
__item_keyonly_optkeys(tagid(tagOrId)).each{|defkey, undefkey|
conf = slot.find{|kk, vv| kk == defkey.to_s}
if conf
@@ -259,12 +204,7 @@ module TkItemConfigMethod
end
else
- orig_slot = slot
slot = slot.to_s
- if slot.length == 0
- fail ArgumentError, "Invalid option `#{orig_slot.inspect}'"
- end
-
if ( conf = __item_keyonly_optkeys(tagid(tagOrId)).find{|k, v| k.to_s == slot } )
defkey, undefkey = conf
if value
@@ -272,8 +212,6 @@ module TkItemConfigMethod
elsif undefkey
tk_call(*(__item_config_cmd(tagid(tagOrId)) << "-#{undefkey}"))
end
- elsif ( method = _symbolkey2str(__item_ruby2val_optkeys(tagid(tagOrId)))[slot] )
- tk_call(*(__item_config_cmd(tagid(tagOrId)) << "-#{slot}" << method.call(tagOrId, value)))
elsif ( method = _symbolkey2str(__item_methodcall_optkeys(tagid(tagOrId)))[slot] )
self.__send__(method, tagOrId, value)
elsif (slot =~ /^(|latin|ascii|kanji)(#{__item_font_optkeys(tagid(tagOrId)).join('|')})$/)
@@ -291,10 +229,9 @@ module TkItemConfigMethod
def itemconfiginfo(tagOrId, slot = nil)
if TkComm::GET_CONFIGINFO_AS_ARRAY
- if (slot && slot.to_s =~ /^(|latin|ascii|kanji)(#{__item_font_optkeys(tagid(tagOrId)).join('|')})$/)
+ if (slot.to_s =~ /^(|latin|ascii|kanji)(#{__item_font_optkeys(tagid(tagOrId)).join('|')})$/)
fontkey = $2
- # conf = tk_split_simplelist(_fromUTF8(tk_call_without_enc(*(__item_confinfo_cmd(tagid(tagOrId)) << "-#{fontkey}"))))
- conf = tk_split_simplelist(tk_call_without_enc(*(__item_confinfo_cmd(tagid(tagOrId)) << "-#{fontkey}")), false, true)
+ conf = tk_split_simplelist(_fromUTF8(tk_call_without_enc(*(__item_confinfo_cmd(tagid(tagOrId)) << "-#{fontkey}"))))
conf[__item_configinfo_struct(tagid(tagOrId))[:key]] =
conf[__item_configinfo_struct(tagid(tagOrId))[:key]][1..-1]
if ( ! __item_configinfo_struct(tagid(tagOrId))[:alias] \
@@ -311,38 +248,12 @@ module TkItemConfigMethod
if slot
slot = slot.to_s
case slot
- when /^(#{__item_val2ruby_optkeys(tagid(tagOrId)).keys.join('|')})$/
- method = _symbolkey2str(__item_val2ruby_optkeys(tagid(tagOrId)))[slot]
- conf = tk_split_simplelist(tk_call_without_enc(*(__item_confinfo_cmd(tagid(tagOrId)) << "-#{slot}")), false, true)
- if ( __item_configinfo_struct(tagid(tagOrId))[:default_value] \
- && conf[__item_configinfo_struct(tagid(tagOrId))[:default_value]] )
- optval = conf[__item_configinfo_struct(tagid(tagOrId))[:default_value]]
- begin
- val = method.call(tagOrId, optval)
- rescue => e
- warn("Warning:: #{e.message} (when #{method}.call(#{tagOrId.inspect}, #{optval.inspect})") if $DEBUG
- val = optval
- end
- conf[__item_configinfo_struct(tagid(tagOrId))[:default_value]] = val
- end
- if ( conf[__item_configinfo_struct(tagid(tagOrId))[:current_value]] )
- optval = conf[__item_configinfo_struct(tagid(tagOrId))[:current_value]]
- begin
- val = method.call(tagOrId, optval)
- rescue => e
- warn("Warning:: #{e.message} (when #{method}lcall(#{tagOrId.inspect}, #{optval.inspect})") if $DEBUG
- val = optval
- end
- conf[__item_configinfo_struct(tagid(tagOrId))[:current_value]] = val
- end
-
when /^(#{__item_methodcall_optkeys(tagid(tagOrId)).keys.join('|')})$/
method = _symbolkey2str(__item_methodcall_optkeys(tagid(tagOrId)))[slot]
return [slot, '', '', '', self.__send__(method, tagOrId)]
when /^(#{__item_numval_optkeys(tagid(tagOrId)).join('|')})$/
- # conf = tk_split_simplelist(_fromUTF8(tk_call_without_enc(*(__item_confinfo_cmd(tagid(tagOrId)) << "-#{slot}"))))
- conf = tk_split_simplelist(tk_call_without_enc(*(__item_confinfo_cmd(tagid(tagOrId)) << "-#{slot}")), false, true)
+ conf = tk_split_simplelist(_fromUTF8(tk_call_without_enc(*(__item_confinfo_cmd(tagid(tagOrId)) << "-#{slot}"))))
if ( __item_configinfo_struct(tagid(tagOrId))[:default_value] \
&& conf[__item_configinfo_struct(tagid(tagOrId))[:default_value]] )
@@ -363,8 +274,7 @@ module TkItemConfigMethod
end
when /^(#{__item_numstrval_optkeys(tagid(tagOrId)).join('|')})$/
- # conf = tk_split_simplelist(_fromUTF8(tk_call_without_enc(*(__item_confinfo_cmd(tagid(tagOrId)) << "-#{slot}"))))
- conf = tk_split_simplelist(tk_call_without_enc(*(__item_confinfo_cmd(tagid(tagOrId)) << "-#{slot}")), false, true)
+ conf = tk_split_simplelist(_fromUTF8(tk_call_without_enc(*(__item_confinfo_cmd(tagid(tagOrId)) << "-#{slot}"))))
if ( __item_configinfo_struct(tagid(tagOrId))[:default_value] \
&& conf[__item_configinfo_struct(tagid(tagOrId))[:default_value]] )
@@ -377,8 +287,7 @@ module TkItemConfigMethod
end
when /^(#{__item_boolval_optkeys(tagid(tagOrId)).join('|')})$/
- # conf = tk_split_simplelist(_fromUTF8(tk_call_without_enc(*(__item_confinfo_cmd(tagid(tagOrId)) << "-#{slot}"))))
- conf = tk_split_simplelist(tk_call_without_enc(*(__item_confinfo_cmd(tagid(tagOrId)) << "-#{slot}")), false, true)
+ conf = tk_split_simplelist(_fromUTF8(tk_call_without_enc(*(__item_confinfo_cmd(tagid(tagOrId)) << "-#{slot}"))))
if ( __item_configinfo_struct(tagid(tagOrId))[:default_value] \
&& conf[__item_configinfo_struct(tagid(tagOrId))[:default_value]] )
@@ -399,8 +308,7 @@ module TkItemConfigMethod
end
when /^(#{__item_listval_optkeys(tagid(tagOrId)).join('|')})$/
- # conf = tk_split_simplelist(_fromUTF8(tk_call_without_enc(*(__item_confinfo_cmd(tagid(tagOrId)) << "-#{slot}"))))
- conf = tk_split_simplelist(tk_call_without_enc(*(__item_confinfo_cmd(tagid(tagOrId)) << "-#{slot}")), false, true)
+ conf = tk_split_simplelist(_fromUTF8(tk_call_without_enc(*(__item_confinfo_cmd(tagid(tagOrId)) << "-#{slot}"))))
if ( __item_configinfo_struct(tagid(tagOrId))[:default_value] \
&& conf[__item_configinfo_struct(tagid(tagOrId))[:default_value]] )
@@ -413,8 +321,7 @@ module TkItemConfigMethod
end
when /^(#{__item_numlistval_optkeys(tagid(tagOrId)).join('|')})$/
- # conf = tk_split_simplelist(_fromUTF8(tk_call_without_enc(*(__item_confinfo_cmd(tagid(tagOrId)) << "-#{slot}"))))
- conf = tk_split_simplelist(tk_call_without_enc(*(__item_confinfo_cmd(tagid(tagOrId)) << "-#{slot}")), false, true)
+ conf = tk_split_simplelist(_fromUTF8(tk_call_without_enc(*(__item_confinfo_cmd(tagid(tagOrId)) << "-#{slot}"))))
if ( __item_configinfo_struct(tagid(tagOrId))[:default_value] \
&& conf[__item_configinfo_struct(tagid(tagOrId))[:default_value]] \
@@ -429,33 +336,10 @@ module TkItemConfigMethod
end
when /^(#{__item_strval_optkeys(tagid(tagOrId)).join('|')})$/
- # conf = tk_split_simplelist(_fromUTF8(tk_call_without_enc(*(__item_confinfo_cmd(tagid(tagOrId)) << "-#{slot}"))))
- conf = tk_split_simplelist(tk_call_without_enc(*(__item_confinfo_cmd(tagid(tagOrId)) << "-#{slot}")), false, true)
-
- when /^(#{__item_tkvariable_optkeys(tagid(tagOrId)).join('|')})$/
- conf = tk_split_simplelist(tk_call_without_enc(*(__item_confinfo_cmd(tagid(tagOrId)) << "-#{slot}")), false, true)
-
- if ( __item_configinfo_struct(tagid(tagOrId))[:default_value] \
- && conf[__item_configinfo_struct(tagid(tagOrId))[:default_value]] )
- v = conf[__item_configinfo_struct(tagid(tagOrId))[:default_value]]
- if v.empty?
- conf[__item_configinfo_struct(tagid(tagOrId))[:default_value]] = nil
- else
- conf[__item_configinfo_struct(tagid(tagOrId))[:default_value]] = TkVarAccess.new(v)
- end
- end
- if ( conf[__item_configinfo_struct(tagid(tagOrId))[:current_value]] )
- v = conf[__item_configinfo_struct(tagid(tagOrId))[:current_value]]
- if v.empty?
- conf[__item_configinfo_struct(tagid(tagOrId))[:current_value]] = nil
- else
- conf[__item_configinfo_struct(tagid(tagOrId))[:current_value]] = TkVarAccess.new(v)
- end
- end
+ conf = tk_split_simplelist(_fromUTF8(tk_call_without_enc(*(__item_confinfo_cmd(tagid(tagOrId)) << "-#{slot}"))))
else
- # conf = tk_split_list(_fromUTF8(tk_call_without_enc(*(__item_confinfo_cmd(tagid(tagOrId)) << "-#{slot}"))))
- conf = tk_split_list(tk_call_without_enc(*(__item_confinfo_cmd(tagid(tagOrId)) << "-#{slot}")), 0, false, true)
+ conf = tk_split_list(_fromUTF8(tk_call_without_enc(*(__item_confinfo_cmd(tagid(tagOrId)) << "-#{slot}"))))
end
conf[__item_configinfo_struct(tagid(tagOrId))[:key]] =
conf[__item_configinfo_struct(tagid(tagOrId))[:key]][1..-1]
@@ -470,39 +354,12 @@ module TkItemConfigMethod
conf
else
- # ret = tk_split_simplelist(_fromUTF8(tk_call_without_enc(*(__item_confinfo_cmd(tagid(tagOrId)))))).collect{|conflist|
- # conf = tk_split_simplelist(conflist)
- ret = tk_split_simplelist(tk_call_without_enc(*(__item_confinfo_cmd(tagid(tagOrId)))), false, false).collect{|conflist|
- conf = tk_split_simplelist(conflist, false, true)
+ ret = tk_split_simplelist(_fromUTF8(tk_call_without_enc(*(__item_confinfo_cmd(tagid(tagOrId)))))).collect{|conflist|
+ conf = tk_split_simplelist(conflist)
conf[__item_configinfo_struct(tagid(tagOrId))[:key]] =
conf[__item_configinfo_struct(tagid(tagOrId))[:key]][1..-1]
- optkey = conf[__item_configinfo_struct(tagid(tagOrId))[:key]]
- case optkey
- when /^(#{__item_val2ruby_optkeys(tagid(tagOrId)).keys.join('|')})$/
- method = _symbolkey2str(__item_val2ruby_optkeys(tagid(tagOrId)))[optkey]
- if ( __item_configinfo_struct(tagid(tagOrId))[:default_value] \
- && conf[__item_configinfo_struct(tagid(tagOrId))[:default_value]] )
- optval = conf[__item_configinfo_struct(tagid(tagOrId))[:default_value]]
- begin
- val = method(tagOrId, optval)
- rescue => e
- warn("Warning:: #{e.message} (when #{method}.call(#{tagOrId.inspect}, #{optval.inspect})") if $DEBUG
- val = optval
- end
- conf[__item_configinfo_struct(tagid(tagOrId))[:default_value]] = val
- end
- if ( conf[__item_configinfo_struct(tagid(tagOrId))[:current_value]] )
- optval = conf[__item_configinfo_struct(tagid(tagOrId))[:current_value]]
- begin
- val = method.call(tagOrId, optval)
- rescue => e
- warn("Warning:: #{e.message} (when #{method}.call(#{tagOrId.inspect}, #{optval.inspect})") if $DEBUG
- val = optval
- end
- conf[__item_configinfo_struct(tagid(tagOrId))[:current_value]] = val
- end
-
+ case conf[__item_configinfo_struct(tagid(tagOrId))[:key]]
when /^(#{__item_strval_optkeys(tagid(tagOrId)).join('|')})$/
# do nothing
@@ -579,25 +436,6 @@ module TkItemConfigMethod
list(conf[__item_configinfo_struct(tagid(tagOrId))[:current_value]])
end
- when /^(#{__item_tkvariable_optkeys(tagid(tagOrId)).join('|')})$/
- if ( __item_configinfo_struct(tagid(tagOrId))[:default_value] \
- && conf[__item_configinfo_struct(tagid(tagOrId))[:default_value]] )
- v = conf[__item_configinfo_struct(tagid(tagOrId))[:default_value]]
- if v.empty?
- conf[__item_configinfo_struct(tagid(tagOrId))[:default_value]] = nil
- else
- conf[__item_configinfo_struct(tagid(tagOrId))[:default_value]] = TkVarAccess.new(v)
- end
- end
- if ( conf[__item_configinfo_struct(tagid(tagOrId))[:current_value]] )
- v = conf[__item_configinfo_struct(tagid(tagOrId))[:current_value]]
- if v.empty?
- conf[__item_configinfo_struct(tagid(tagOrId))[:current_value]] = nil
- else
- conf[__item_configinfo_struct(tagid(tagOrId))[:current_value]] = TkVarAccess.new
- end
- end
-
else
if ( __item_configinfo_struct(tagid(tagOrId))[:default_value] \
&& conf[__item_configinfo_struct(tagid(tagOrId))[:default_value]] )
@@ -649,10 +487,9 @@ module TkItemConfigMethod
end
else # ! TkComm::GET_CONFIGINFO_AS_ARRAY
- if (slot && slot.to_s =~ /^(|latin|ascii|kanji)(#{__item_font_optkeys(tagid(tagOrId)).join('|')})$/)
+ if (slot.to_s =~ /^(|latin|ascii|kanji)(#{__item_font_optkeys(tagid(tagOrId)).join('|')})$/)
fontkey = $2
- # conf = tk_split_simplelist(_fromUTF8(tk_call_without_enc(*(__item_confinfo_cmd(tagid(tagOrId)) << "-#{fontkey}"))))
- conf = tk_split_simplelist(tk_call_without_enc(*(__item_confinfo_cmd(tagid(tagOrId)) << "-#{fontkey}")), false, true)
+ conf = tk_split_simplelist(_fromUTF8(tk_call_without_enc(*(__item_confinfo_cmd(tagid(tagOrId)) << "-#{fontkey}"))))
conf[__item_configinfo_struct(tagid(tagOrId))[:key]] =
conf[__item_configinfo_struct(tagid(tagOrId))[:key]][1..-1]
@@ -674,38 +511,12 @@ module TkItemConfigMethod
if slot
slot = slot.to_s
case slot
- when /^(#{__item_val2ruby_optkeys(tagid(tagOrId)).keys.join('|')})$/
- method = _symbolkey2str(__item_val2ruby_optkeys(tagid(tagOrId)))[slot]
- conf = tk_split_simplelist(tk_call_without_enc(*(__item_confinfo_cmd(tagid(tagOrId)) << "-#{slot}")), false, true)
- if ( __item_configinfo_struct(tagid(tagOrId))[:default_value] \
- && conf[__item_configinfo_struct(tagid(tagOrId))[:default_value]] )
- optval = conf[__item_configinfo_struct(tagid(tagOrId))[:default_value]]
- begin
- val = method.call(tagOrId, optval)
- rescue => e
- warn("Warning:: #{e.message} (when #{method}.call(#{tagOrId.inspect}, #{optval.inspect})") if $DEBUG
- val = optval
- end
- conf[__item_configinfo_struct(tagid(tagOrId))[:default_value]] = val
- end
- if ( conf[__item_configinfo_struct(tagid(tagOrId))[:current_value]] )
- optval = conf[__item_configinfo_struct(tagid(tagOrId))[:current_value]]
- begin
- val = method.call(tagOrId, optval)
- rescue => e
- warn("Warning:: #{e.message} (when #{method}.call(#{tagOrId.inspect}, #{optval.inspect})") if $DEBUG
- val = optval
- end
- conf[__item_configinfo_struct(tagid(tagOrId))[:current_value]] = val
- end
-
when /^(#{__item_methodcall_optkeys(tagid(tagOrId)).keys.join('|')})$/
method = _symbolkey2str(__item_methodcall_optkeys(tagid(tagOrId)))[slot]
return {slot => ['', '', '', self.__send__(method, tagOrId)]}
when /^(#{__item_numval_optkeys(tagid(tagOrId)).join('|')})$/
- # conf = tk_split_simplelist(_fromUTF8(tk_call_without_enc(*(__item_confinfo_cmd(tagid(tagOrId)) << "-#{slot}"))))
- conf = tk_split_simplelist(tk_call_without_enc(*(__item_confinfo_cmd(tagid(tagOrId)) << "-#{slot}")), false, true)
+ conf = tk_split_simplelist(_fromUTF8(tk_call_without_enc(*(__item_confinfo_cmd(tagid(tagOrId)) << "-#{slot}"))))
if ( __item_configinfo_struct(tagid(tagOrId))[:default_value] \
&& conf[__item_configinfo_struct(tagid(tagOrId))[:default_value]] )
@@ -726,8 +537,7 @@ module TkItemConfigMethod
end
when /^(#{__item_numstrval_optkeys(tagid(tagOrId)).join('|')})$/
- # conf = tk_split_simplelist(_fromUTF8(tk_call_without_enc(*(__item_confinfo_cmd(tagid(tagOrId)) << "-#{slot}"))))
- conf = tk_split_simplelist(tk_call_without_enc(*(__item_confinfo_cmd(tagid(tagOrId)) << "-#{slot}")), false, true)
+ conf = tk_split_simplelist(_fromUTF8(tk_call_without_enc(*(__item_confinfo_cmd(tagid(tagOrId)) << "-#{slot}"))))
if ( __item_configinfo_struct(tagid(tagOrId))[:default_value] \
&& conf[__item_configinfo_struct(tagid(tagOrId))[:default_value]] )
@@ -740,8 +550,7 @@ module TkItemConfigMethod
end
when /^(#{__item_boolval_optkeys(tagid(tagOrId)).join('|')})$/
- # conf = tk_split_simplelist(_fromUTF8(tk_call_without_enc(*(__item_confinfo_cmd(tagid(tagOrId)) << "-#{slot}"))))
- conf = tk_split_simplelist(tk_call_without_enc(*(__item_confinfo_cmd(tagid(tagOrId)) << "-#{slot}")), false, true)
+ conf = tk_split_simplelist(_fromUTF8(tk_call_without_enc(*(__item_confinfo_cmd(tagid(tagOrId)) << "-#{slot}"))))
if ( __item_configinfo_struct(tagid(tagOrId))[:default_value] \
&& conf[__item_configinfo_struct(tagid(tagOrId))[:default_value]] )
@@ -762,8 +571,7 @@ module TkItemConfigMethod
end
when /^(#{__item_listval_optkeys(tagid(tagOrId)).join('|')})$/
- # conf = tk_split_simplelist(_fromUTF8(tk_call_without_enc(*(__item_confinfo_cmd(tagid(tagOrId)) << "-#{slot}"))))
- conf = tk_split_simplelist(tk_call_without_enc(*(__item_confinfo_cmd(tagid(tagOrId)) << "-#{slot}")), false, true)
+ conf = tk_split_simplelist(_fromUTF8(tk_call_without_enc(*(__item_confinfo_cmd(tagid(tagOrId)) << "-#{slot}"))))
if ( __item_configinfo_struct(tagid(tagOrId))[:default_value] \
&& conf[__item_configinfo_struct(tagid(tagOrId))[:default_value]] )
@@ -776,8 +584,7 @@ module TkItemConfigMethod
end
when /^(#{__item_numlistval_optkeys(tagid(tagOrId)).join('|')})$/
- # conf = tk_split_simplelist(_fromUTF8(tk_call_without_enc(*(__item_confinfo_cmd(tagid(tagOrId)) << "-#{slot}"))))
- conf = tk_split_simplelist(tk_call_without_enc(*(__item_confinfo_cmd(tagid(tagOrId)) << "-#{slot}")), false, true)
+ conf = tk_split_simplelist(_fromUTF8(tk_call_without_enc(*(__item_confinfo_cmd(tagid(tagOrId)) << "-#{slot}"))))
if ( __item_configinfo_struct(tagid(tagOrId))[:default_value] \
&& conf[__item_configinfo_struct(tagid(tagOrId))[:default_value]] \
@@ -792,33 +599,10 @@ module TkItemConfigMethod
end
when /^(#{__item_strval_optkeys(tagid(tagOrId)).join('|')})$/
- # conf = tk_split_simplelist(_fromUTF8(tk_call_without_enc(*(__item_confinfo_cmd(tagid(tagOrId)) << "-#{slot}"))))
- conf = tk_split_simplelist(tk_call_without_enc(*(__item_confinfo_cmd(tagid(tagOrId)) << "-#{slot}")), false, true)
-
- when /^(#{__item_tkvariable_optkeys(tagid(tagOrId)).join('|')})$/
- conf = tk_split_simplelist(tk_call_without_enc(*(__item_confinfo_cmd(tagid(tagOrId)) << "-#{slot}")), false, true)
-
- if ( __item_configinfo_struct(tagid(tagOrId))[:default_value] \
- && conf[__item_configinfo_struct(tagid(tagOrId))[:default_value]] )
- v = conf[__item_configinfo_struct(tagid(tagOrId))[:default_value]]
- if v.empty?
- conf[__item_configinfo_struct(tagid(tagOrId))[:default_value]] = nil
- else
- conf[__item_configinfo_struct(tagid(tagOrId))[:default_value]] = TkVarAccess.new(v)
- end
- end
- if ( conf[__item_configinfo_struct(tagid(tagOrId))[:current_value]] )
- v = conf[__item_configinfo_struct(tagid(tagOrId))[:current_value]]
- if v.empty?
- conf[__item_configinfo_struct(tagid(tagOrId))[:current_value]] = nil
- else
- conf[__item_configinfo_struct(tagid(tagOrId))[:current_value]] = TkVarAccess.new(v)
- end
- end
+ conf = tk_split_simplelist(_fromUTF8(tk_call_without_enc(*(__item_confinfo_cmd(tagid(tagOrId)) << "-#{slot}"))))
else
- # conf = tk_split_list(_fromUTF8(tk_call_without_enc(*(__item_confinfo_cmd(tagid(tagOrId)) << "-#{slot}"))))
- conf = tk_split_list(tk_call_without_enc(*(__item_confinfo_cmd(tagid(tagOrId)) << "-#{slot}")), 0, false, true)
+ conf = tk_split_list(_fromUTF8(tk_call_without_enc(*(__item_confinfo_cmd(tagid(tagOrId)) << "-#{slot}"))))
end
conf[__item_configinfo_struct(tagid(tagOrId))[:key]] =
conf[__item_configinfo_struct(tagid(tagOrId))[:key]][1..-1]
@@ -836,39 +620,12 @@ module TkItemConfigMethod
else
ret = {}
- # tk_split_simplelist(_fromUTF8(tk_call_without_enc(*(__item_confinfo_cmd(tagid(tagOrId)))))).each{|conflist|
- # conf = tk_split_simplelist(conflist)
- tk_split_simplelist(tk_call_without_enc(*(__item_confinfo_cmd(tagid(tagOrId)))), false, false).each{|conflist|
- conf = tk_split_simplelist(conflist, false, true)
+ tk_split_simplelist(_fromUTF8(tk_call_without_enc(*(__item_confinfo_cmd(tagid(tagOrId)))))).each{|conflist|
+ conf = tk_split_simplelist(conflist)
conf[__item_configinfo_struct(tagid(tagOrId))[:key]] =
conf[__item_configinfo_struct(tagid(tagOrId))[:key]][1..-1]
- optkey = conf[__item_configinfo_struct(tagid(tagOrId))[:key]]
- case optkey
- when /^(#{__item_val2ruby_optkeys(tagid(tagOrId)).keys.join('|')})$/
- method = _symbolkey2str(__item_val2ruby_optkeys(tagid(tagOrId)))[optkey]
- if ( __item_configinfo_struct(tagid(tagOrId))[:default_value] \
- && conf[__item_configinfo_struct(tagid(tagOrId))[:default_value]] )
- optval = conf[__item_configinfo_struct(tagid(tagOrId))[:default_value]]
- begin
- val = method.call(tagOrId, optval)
- rescue => e
- warn("Warning:: #{e.message} (when #{method}.call(#{tagOrId.inspect}, #{optval.inspect})") if $DEBUG
- val = optval
- end
- conf[__item_configinfo_struct(tagid(tagOrId))[:default_value]] = val
- end
- if ( conf[__item_configinfo_struct(tagid(tagOrId))[:current_value]] )
- optval = conf[__item_configinfo_struct(tagid(tagOrId))[:current_value]]
- begin
- val = method.call(tagOrId, optval)
- rescue => e
- warn("Warning:: #{e.message} (when #{method}.call(#{tagOrId.inspect}, #{optval.inspect})") if $DEBUG
- val = optval
- end
- conf[__item_configinfo_struct(tagid(tagOrId))[:current_value]] = val
- end
-
+ case conf[__item_configinfo_struct(tagid(tagOrId))[:key]]
when /^(#{__item_strval_optkeys(tagid(tagOrId)).join('|')})$/
# do nothing
@@ -945,25 +702,6 @@ module TkItemConfigMethod
list(conf[__item_configinfo_struct(tagid(tagOrId))[:current_value]])
end
- when /^(#{__item_tkvariable_optkeys(tagid(tagOrId)).join('|')})$/
- if ( __item_configinfo_struct(tagid(tagOrId))[:default_value] \
- && conf[__item_configinfo_struct(tagid(tagOrId))[:default_value]] )
- v = conf[__item_configinfo_struct(tagid(tagOrId))[:default_value]]
- if v.empty?
- conf[__item_configinfo_struct(tagid(tagOrId))[:default_value]] = nil
- else
- conf[__item_configinfo_struct(tagid(tagOrId))[:default_value]] = TkVarAccess.new(v)
- end
- end
- if ( conf[__item_configinfo_struct(tagid(tagOrId))[:current_value]] )
- v = conf[__item_configinfo_struct(tagid(tagOrId))[:current_value]]
- if v.empty?
- conf[__item_configinfo_struct(tagid(tagOrId))[:current_value]] = nil
- else
- conf[__item_configinfo_struct(tagid(tagOrId))[:current_value]] = TkVarAccess.new(v)
- end
- end
-
else
if ( __item_configinfo_struct(tagid(tagOrId))[:default_value] \
&& conf[__item_configinfo_struct(tagid(tagOrId))[:default_value]] )
diff --git a/ext/tk/lib/tk/itemfont.rb b/ext/tk/lib/tk/itemfont.rb
index ab9e3ff6c9..e4a1a50912 100644
--- a/ext/tk/lib/tk/itemfont.rb
+++ b/ext/tk/lib/tk/itemfont.rb
@@ -221,18 +221,18 @@ module TkTreatItemFont
self
end
- def tagfont_copy(tagOrId, win, wintag=nil, winkey=nil, targetkey=nil)
+ def tagfont_copy(tagOrId, window, wintag=nil, winkey=nil, targetkey=nil)
if wintag
if winkey
- fnt = win.tagfontobj(wintag, winkey).dup
+ fnt = window.tagfontobj(wintag, winkey).dup
else
- fnt = win.tagfontobj(wintag).dup
+ fnt = window.tagfontobj(wintag).dup
end
else
if winkey
- fnt = win.fontobj(winkey).dup
+ fnt = window.fontobj(winkey).dup
else
- fnt = win.fontobj.dup
+ fnt = window.fontobj.dup
end
end
@@ -247,7 +247,7 @@ module TkTreatItemFont
end
- def latintagfont_copy(tagOrId, win, wintag=nil, winkey=nil, targetkey=nil)
+ def latintagfont_copy(tagOrId, window, wintag=nil, winkey=nil, targetkey=nil)
if targetkey
fontobj(targetkey).dup.call_font_configure([__item_pathname(tagid(tagOrId)), targetkey],
*(__item_config_cmd(tagid(tagOrId)) << {}))
@@ -258,22 +258,22 @@ module TkTreatItemFont
if wintag
if winkey
- fontobj.latin_replace(win.tagfontobj(wintag, winkey).latin_font_id)
+ fontobj.latin_replace(window.tagfontobj(wintag, winkey).latin_font_id)
else
- fontobj.latin_replace(win.tagfontobj(wintag).latin_font_id)
+ fontobj.latin_replace(window.tagfontobj(wintag).latin_font_id)
end
else
if winkey
- fontobj.latin_replace(win.fontobj(winkey).latin_font_id)
+ fontobj.latin_replace(window.fontobj(winkey).latin_font_id)
else
- fontobj.latin_replace(win.fontobj.latin_font_id)
+ fontobj.latin_replace(window.fontobj.latin_font_id)
end
end
self
end
alias asciitagfont_copy latintagfont_copy
- def kanjifont_copy(tagOrId, win, wintag=nil, winkey=nil, targetkey=nil)
+ def kanjifont_copy(tagOrId, window, wintag=nil, winkey=nil, targetkey=nil)
if targetkey
fontobj(targetkey).dup.call_font_configure([__item_pathname(tagid(tagOrId)), targetkey],
*(__item_config_cmd(tagid(tagOrId)) << {}))
@@ -284,15 +284,15 @@ module TkTreatItemFont
if wintag
if winkey
- fontobj.kanji_replace(win.tagfontobj(wintag, winkey).kanji_font_id)
+ fontobj.kanji_replace(window.tagfontobj(wintag, winkey).kanji_font_id)
else
- fontobj.kanji_replace(win.tagfontobj(wintag).kanji_font_id)
+ fontobj.kanji_replace(window.tagfontobj(wintag).kanji_font_id)
end
else
if winkey
- fontobj.kanji_replace(win.fontobj(winkey).kanji_font_id)
+ fontobj.kanji_replace(window.fontobj(winkey).kanji_font_id)
else
- fontobj.kanji_replace(win.fontobj.kanji_font_id)
+ fontobj.kanji_replace(window.fontobj.kanji_font_id)
end
end
self
diff --git a/ext/tk/lib/tk/kinput.rb b/ext/tk/lib/tk/kinput.rb
index a29dbcdb72..fc731b6569 100644
--- a/ext/tk/lib/tk/kinput.rb
+++ b/ext/tk/lib/tk/kinput.rb
@@ -13,46 +13,46 @@ module TkKinput
'kanjiInput'.freeze
].freeze
- def TkKinput.start(win, style=None)
- tk_call('kinput_start', win, style)
+ def TkKinput.start(window, style=None)
+ tk_call('kinput_start', window, style)
end
def kinput_start(style=None)
TkKinput.start(self, style)
end
- def TkKinput.send_spot(win)
- tk_call('kinput_send_spot', win)
+ def TkKinput.send_spot(window)
+ tk_call('kinput_send_spot', window)
end
def kinput_send_spot
TkKinput.send_spot(self)
end
- def TkKinput.input_start(win, keys=nil)
- tk_call('kanjiInput', 'start', win, *hash_kv(keys))
+ def TkKinput.input_start(window, keys=nil)
+ tk_call('kanjiInput', 'start', window, *hash_kv(keys))
end
def kanji_input_start(keys=nil)
TkKinput.input_start(self, keys)
end
- def TkKinput.attribute_config(win, slot, value=None)
+ def TkKinput.attribute_config(window, slot, value=None)
if slot.kind_of? Hash
- tk_call('kanjiInput', 'attribute', win, *hash_kv(slot))
+ tk_call('kanjiInput', 'attribute', window, *hash_kv(slot))
else
- tk_call('kanjiInput', 'attribute', win, "-#{slot}", value)
+ tk_call('kanjiInput', 'attribute', window, "-#{slot}", value)
end
end
def kinput_attribute_config(slot, value=None)
TkKinput.attribute_config(self, slot, value)
end
- def TkKinput.attribute_info(win, slot=nil)
+ def TkKinput.attribute_info(window, slot=nil)
if slot
conf = tk_split_list(tk_call('kanjiInput', 'attribute',
- win, "-#{slot}"))
+ window, "-#{slot}"))
conf[0] = conf[0][1..-1]
conf
else
- tk_split_list(tk_call('kanjiInput', 'attribute', win)).collect{|conf|
+ tk_split_list(tk_call('kanjiInput', 'attribute', window)).collect{|conf|
conf[0] = conf[0][1..-1]
conf
}
@@ -62,8 +62,8 @@ module TkKinput
TkKinput.attribute_info(self, slot)
end
- def TkKinput.input_end(win)
- tk_call('kanjiInput', 'end', win)
+ def TkKinput.input_end(window)
+ tk_call('kanjiInput', 'end', window)
end
def kanji_input_end
TkKinput.input_end(self)
diff --git a/ext/tk/lib/tk/label.rb b/ext/tk/lib/tk/label.rb
index 8b45db9b30..ea669d576e 100644
--- a/ext/tk/lib/tk/label.rb
+++ b/ext/tk/lib/tk/label.rb
@@ -15,4 +15,8 @@ class TkLabel<TkWindow
# end
#end
#private :create_self
+
+ def textvariable(v)
+ configure 'textvariable', tk_trace_variable(v)
+ end
end
diff --git a/ext/tk/lib/tk/labelframe.rb b/ext/tk/lib/tk/labelframe.rb
index 73d5603200..fd16d3419d 100644
--- a/ext/tk/lib/tk/labelframe.rb
+++ b/ext/tk/lib/tk/labelframe.rb
@@ -16,10 +16,5 @@ class TkLabelFrame<TkFrame
# end
#end
#private :create_self
-
- def __val2ruby_optkeys # { key=>proc, ... }
- super().update('labelwidget'=>proc{|v| window(v)})
- end
- private :__val2ruby_optkeys
end
TkLabelframe = TkLabelFrame
diff --git a/ext/tk/lib/tk/listbox.rb b/ext/tk/lib/tk/listbox.rb
index 41d02d279e..f00db19239 100644
--- a/ext/tk/lib/tk/listbox.rb
+++ b/ext/tk/lib/tk/listbox.rb
@@ -32,11 +32,6 @@ class TkListbox<TkTextWin
#end
#private :create_self
- def __tkvariable_optkeys
- super() << 'listvariable'
- end
- private :__tkvariable_optkeys
-
def tagid(id)
#id.to_s
_get_eval_string(id)
@@ -51,8 +46,7 @@ class TkListbox<TkTextWin
end
def get(first, last=nil)
if last
- # tk_split_simplelist(_fromUTF8(tk_send_without_enc('get', first, last)))
- tk_split_simplelist(tk_send_without_enc('get', first, last), false, true)
+ tk_split_simplelist(_fromUTF8(tk_send_without_enc('get', first, last)))
else
_fromUTF8(tk_send_without_enc('get', first))
end
@@ -79,8 +73,8 @@ class TkListbox<TkTextWin
self
end
- def index(idx)
- tk_send_without_enc('index', idx).to_i
+ def index(index)
+ tk_send_without_enc('index', index).to_i
end
def value
diff --git a/ext/tk/lib/tk/macpkg.rb b/ext/tk/lib/tk/macpkg.rb
index 1802073f46..d67a19745b 100644
--- a/ext/tk/lib/tk/macpkg.rb
+++ b/ext/tk/lib/tk/macpkg.rb
@@ -26,11 +26,6 @@ module TkMacResource
TkCommandNames = ['resource'.freeze].freeze
- PACKAGE_NAME = 'resource'.freeze
- def self.package_name
- PACKAGE_NAME
- end
-
tk_call_without_enc('package', 'require', 'resource')
def close(rsrcRef)
diff --git a/ext/tk/lib/tk/menu.rb b/ext/tk/lib/tk/menu.rb
index be8ec2ddee..5014dea603 100644
--- a/ext/tk/lib/tk/menu.rb
+++ b/ext/tk/lib/tk/menu.rb
@@ -3,7 +3,6 @@
#
require 'tk'
require 'tk/itemconfig'
-require 'tk/menuspec'
module TkMenuEntryConfig
include TkItemConfigMethod
@@ -18,21 +17,11 @@ module TkMenuEntryConfig
end
private :__item_config_cmd
- def __item_strval_optkeys(id)
- super(id) << 'selectcolor'
- end
- private :__item_strval_optkeys
-
def __item_listval_optkeys(id)
[]
end
private :__item_listval_optkeys
- def __item_val2ruby_optkeys(id) # { key=>proc, ... }
- super(id).update('menu'=>proc{|i, v| window(v)})
- end
- private :__item_val2ruby_optkeys
-
alias entrycget itemcget
alias entryconfigure itemconfigure
alias entryconfiginfo itemconfiginfo
@@ -44,7 +33,6 @@ end
class TkMenu<TkWindow
include TkMenuEntryConfig
- extend TkMenuSpec
TkCommandNames = ['menu'.freeze].freeze
WidgetClassName = 'Menu'.freeze
@@ -59,34 +47,6 @@ class TkMenu<TkWindow
#end
#private :create_self
- def __strval_optkeys
- super() << 'selectcolor' << 'title'
- end
- private :__strval_optkeys
-
- def __boolval_optkeys
- super() << 'tearoff'
- end
- private :__boolval_optkeys
-
- def self.new_menuspec(menu_spec, parent = nil, tearoff = false, keys = nil)
- if parent.kind_of?(Hash)
- keys = _symbolkey2str(parent)
- parent = keys.delete('parent')
- tearoff = keys.delete('tearoff')
- elsif tearoff.kind_of?(Hash)
- keys = _symbolkey2str(tearoff)
- tearoff = keys.delete('tearoff')
- elsif keys
- keys = _symbolkey2str(keys)
- else
- keys = {}
- end
-
- widgetname = keys.delete('widgetname')
- _create_menu(parent, menu_spec, widgetname, tearoff, keys)
- end
-
def tagid(id)
#id.to_s
_get_eval_string(id)
@@ -115,8 +75,8 @@ class TkMenu<TkWindow
def add_separator(keys=nil)
add('separator', keys)
end
- def index(idx)
- ret = tk_send_without_enc('index', _get_eval_enc_str(idx))
+ def index(index)
+ ret = tk_send_without_enc('index', _get_eval_enc_str(index))
(ret == 'none')? nil: number(ret)
end
def invoke(index)
@@ -422,23 +382,13 @@ class TkMenubutton<TkLabel
WidgetClassNames[WidgetClassName] = self
def create_self(keys)
if keys and keys != None
- # tk_call_without_enc('menubutton', @path, *hash_kv(keys, true))
- tk_call_without_enc(self.class::TkCommandNames[0], @path,
- *hash_kv(keys, true))
+ tk_call_without_enc('menubutton', @path, *hash_kv(keys, true))
else
- # tk_call_without_enc('menubutton', @path)
- tk_call_without_enc(self.class::TkCommandNames[0], @path)
+ tk_call_without_enc('menubutton', @path)
end
end
private :create_self
-
- def __boolval_optkeys
- super() << 'indicatoron'
- end
- private :__boolval_optkeys
-
end
-TkMenuButton = TkMenubutton
class TkOptionMenubutton<TkMenubutton
@@ -452,58 +402,33 @@ class TkOptionMenubutton<TkMenubutton
end
end
- def initialize(*args)
- # args :: [parent,] [var,] [value[, ...],] [keys]
- # parent --> TkWindow or nil
- # var --> TkVariable or nil
- # keys --> Hash
- # keys[:parent] or keys['parent'] --> parent
- # keys[:variable] or keys['variable'] --> var
- # keys[:values] or keys['values'] --> value, ...
- # other Hash keys are menubutton options
- keys = {}
- keys = args.pop if args[-1].kind_of?(Hash)
- keys = _symbolkey2str(keys)
-
- parent = nil
- if args[0].kind_of?(TkWindow) || args[0] == nil
- keys.delete('parent') # ignore
- parent = args.shift
- else
- parent = keys.delete('parent')
- end
-
- @variable = nil
- if args[0].kind_of?(TkVariable) || args[0] == nil
- keys.delete('variable') # ignore
- @variable = args.shift
- else
- @variable = keys.delete('variable')
+ def initialize(parent=nil, var=nil, firstval=nil, *vals)
+ if parent.kind_of? Hash
+ keys = _symbolkey2str(parent)
+ parent = keys['parent']
+ var = keys['variable'] if keys['variable']
+ firstval, *vals = keys['values']
end
- @variable = TkVariable.new unless @variable
-
- (args = keys.delete('values') || []) if args.empty?
- if args.empty?
- args << @variable.value
- else
- @variable.value = args[0]
+ if parent.kind_of? TkVariable
+ vals.unshift(firstval) if firstval
+ firstval = var
+ var = parent
+ parent = nil
end
-
+ var = TkVariable.new unless var
+ fail 'variable option must be TkVariable' unless var.kind_of? TkVariable
+ @variable = var
+ firstval = @variable.value unless firstval
+ @variable.value = firstval
install_win(if parent then parent.path end)
- @menu = OptionMenu.new(tk_call('tk_optionMenu',
- @path, @variable.id, *args))
-
- configure(keys) if keys
+ @menu = OptionMenu.new(tk_call('tk_optionMenu', @path, @variable.id,
+ firstval, *vals))
end
def value
@variable.value
end
- def value=(val)
- @variable.value = val
- end
-
def activate(index)
@menu.activate(index)
self
@@ -561,4 +486,3 @@ class TkOptionMenubutton<TkMenubutton
@menu.current_entryconfiginfo(index, key)
end
end
-TkOptionMenuButton = TkOptionMenubutton
diff --git a/ext/tk/lib/tk/menuspec.rb b/ext/tk/lib/tk/menuspec.rb
index 118a4f42b1..c8819f8e41 100644
--- a/ext/tk/lib/tk/menuspec.rb
+++ b/ext/tk/lib/tk/menuspec.rb
@@ -12,12 +12,12 @@
# And the format of the menu_info is:
# [
# [text, underline, configs], # menu button/entry (*1)
-# [label, command, underline, accelerator, configs], # command entry
-# [label, TkVar_obj, underline, accelerator, configs], # checkbutton entry
+# [label, command, underline, accelerator, configs], # command entry
+# [label, TkVar_obj, underline, accelerator, configs], # checkbutton entry
# [label, [TkVar_obj, value],
-# underline, accelerator, configs], # radiobutton entry
+# underline, accelerator, configs], # radiobutton entry
# [label, [[...menu_info...], [...menu_info...], ...],
-# underline, accelerator, configs], # cascade entry (*2)
+# underline, accelerator, configs], # cascade entry
# '---', # separator
# ...
# ]
@@ -33,10 +33,6 @@
# and *.apple for Mac), append 'menu_name'=>name (name is 'help' for UNIX,
# 'system' for Win, and 'apple' for Mac) option to the configs hash of
# menu button/entry information.
-#
-# NOTE: (*2)
-# If you want to configure a cascade menu, add :menu_config=>{...configs..}
-# to the configs of the cascade entry.
module TkMenuSpec
def _create_menu(parent, menu_info, menu_name = nil,
diff --git a/ext/tk/lib/tk/mngfocus.rb b/ext/tk/lib/tk/mngfocus.rb
index 1a2049c8a8..a0f18233be 100644
--- a/ext/tk/lib/tk/mngfocus.rb
+++ b/ext/tk/lib/tk/mngfocus.rb
@@ -17,15 +17,15 @@ module TkManageFocus
tk_call_without_enc('tk_focusFollowsMouse')
end
- def TkManageFocus.next(win)
- tk_tcl2ruby(tk_call('tk_focusNext', win))
+ def TkManageFocus.next(window)
+ tk_tcl2ruby(tk_call('tk_focusNext', window))
end
def focusNext
TkManageFocus.next(self)
end
- def TkManageFocus.prev(win)
- tk_tcl2ruby(tk_call('tk_focusPrev', win))
+ def TkManageFocus.prev(window)
+ tk_tcl2ruby(tk_call('tk_focusPrev', window))
end
def focusPrev
TkManageFocus.prev(self)
diff --git a/ext/tk/lib/tk/msgcat.rb b/ext/tk/lib/tk/msgcat.rb
index eee331650d..4e095c6fc0 100644
--- a/ext/tk/lib/tk/msgcat.rb
+++ b/ext/tk/lib/tk/msgcat.rb
@@ -23,11 +23,6 @@ class TkMsgCatalog < TkObject
tk_call_without_enc('package', 'require', 'Tcl', '8.2')
- PACKAGE_NAME = 'msgcat'.freeze
- def self.package_name
- PACKAGE_NAME
- end
-
if self.const_defined? :FORCE_VERSION
tk_call_without_enc('package', 'require', 'msgcat', FORCE_VERSION)
else
diff --git a/ext/tk/lib/tk/namespace.rb b/ext/tk/lib/tk/namespace.rb
index 85a94372b9..a236fb6a99 100644
--- a/ext/tk/lib/tk/namespace.rb
+++ b/ext/tk/lib/tk/namespace.rb
@@ -14,99 +14,6 @@ class TkNamespace < TkObject
Tk_Namespace_ID_TBL = TkCore::INTERP.create_table
Tk_Namespace_ID = ["ns".freeze, "00000".taint].freeze
- class Ensemble < TkObject
- def __cget_cmd
- ['namespace', 'ensemble', 'configure', self.path]
- end
- private :__cget_cmd
-
- def __config_cmd
- ['namespace', 'ensemble', 'configure', self.path]
- end
- private :__config_cmd
-
- def __configinfo_struct
- {:key=>0, :alias=>nil, :db_name=>nil, :db_class=>nil,
- :default_value=>nil, :current_value=>2}
- end
- private :__configinfo_struct
-
- def __boolval_optkeys
- ['prefixes']
- end
- private :__boolval_optkeys
-
- def __listval_optkeys
- ['map', 'subcommands', 'unknown']
- end
- private :__listval_optkeys
-
- def self.exist?(ensemble)
- bool(tk_call('namespace', 'ensemble', 'exists', ensemble))
- end
-
- def initialize(keys = {})
- @ensemble = @path = tk_call('namespace', 'ensemble', 'create', keys)
- end
-
- def cget(slot)
- if slot == :namespace || slot == 'namespace'
- ns = super(slot)
- if TkNamespace::Tk_Namespace_ID_TBL.key?(ns)
- TkNamespace::Tk_Namespace_ID_TBL[ns]
- else
- ns
- end
- else
- super(slot)
- end
- end
-
- def configinfo(slot = nil)
- if slot
- if slot == :namespace || slot == 'namespace'
- val = super(slot)
- if TkNamespace::Tk_Namespace_ID_TBL.key?(val)
- val = TkNamespace::Tk_Namespace_ID_TBL[val]
- end
- else
- val = super(slot)
- end
-
- if TkComm::GET_CONFIGINFO_AS_ARRAY
- [slot.to_s, val]
- else # ! TkComm::GET_CONFIGINFO_AS_ARRAY
- {slot.to_s => val}
- end
-
- else
- info = super()
-
- if TkComm::GET_CONFIGINFO_AS_ARRAY
- info.map!{|inf|
- if inf[0] == 'namespace' &&
- TkNamespace::Tk_Namespace_ID_TBL.key?(inf[-1])
- [inf[0], TkNamespace::Tk_Namespace_ID_TBL[inf[-1]]]
- else
- inf
- end
- }
- else # ! TkComm::GET_CONFIGINFO_AS_ARRAY
- val = info['namespace']
- if TkNamespace::Tk_Namespace_ID_TBL.key?(val)
- info['namespace'] = TkNamespace::Tk_Namespace_ID_TBL[val]
- end
- end
-
- info
- end
- end
-
- def exists?
- bool(tk_call('namespace', 'ensemble', 'exists', @path))
- end
- end
-
class ScopeArgs < Array
include Tk
@@ -115,19 +22,19 @@ class TkNamespace < TkObject
# alias __tk_call_with_enc tk_call_with_enc
def tk_call(*args)
#super('namespace', 'eval', @namespace, *args)
- args = args.collect{|arg| (s = _get_eval_string(arg, true))? s: ''}
+ args = args.collect{|arg| (s = _get_eval_string(arg))? s: ''}
super('namespace', 'eval', @namespace,
TkCore::INTERP._merge_tklist(*args))
end
def tk_call_without_enc(*args)
#super('namespace', 'eval', @namespace, *args)
- args = args.collect{|arg| (s = _get_eval_string(arg, true))? s: ''}
+ args = args.collect{|arg| (s = _get_eval_string(arg))? s: ''}
super('namespace', 'eval', @namespace,
TkCore::INTERP._merge_tklist(*args))
end
def tk_call_with_enc(*args)
#super('namespace', 'eval', @namespace, *args)
- args = args.collect{|arg| (s = _get_eval_string(arg, true))? s: ''}
+ args = args.collect{|arg| (s = _get_eval_string(arg))? s: ''}
super('namespace', 'eval', @namespace,
TkCore::INTERP._merge_tklist(*args))
end
@@ -159,19 +66,19 @@ class TkNamespace < TkObject
alias __tk_call_with_enc tk_call_with_enc
def tk_call(*args)
#super('namespace', 'eval', @fullname, *args)
- args = args.collect{|arg| (s = _get_eval_string(arg, true))? s: ''}
+ args = args.collect{|arg| (s = _get_eval_string(arg))? s: ''}
super('namespace', 'eval', @fullname,
TkCore::INTERP._merge_tklist(*args))
end
def tk_call_without_enc(*args)
#super('namespace', 'eval', @fullname, *args)
- args = args.collect{|arg| (s = _get_eval_string(arg, true))? s: ''}
+ args = args.collect{|arg| (s = _get_eval_string(arg))? s: ''}
super('namespace', 'eval', @fullname,
TkCore::INTERP._merge_tklist(*args))
end
def tk_call_with_enc(*args)
#super('namespace', 'eval', @fullname, *args)
- args = args.collect{|arg| (s = _get_eval_string(arg, true))? s: ''}
+ args = args.collect{|arg| (s = _get_eval_string(arg))? s: ''}
super('namespace', 'eval', @fullname,
TkCore::INTERP._merge_tklist(*args))
end
@@ -300,8 +207,7 @@ class TkNamespace < TkObject
#ns_tk_call(cmd, *args)
code_obj = code(cmd)
ret = code_obj.call(*args)
- # uninstall_cmd(TkCore::INTERP._split_tklist(code_obj.path)[-1])
- uninstall_cmd(_fromUTF8(TkCore::INTERP._split_tklist(_toUTF8(code_obj.path))[-1]))
+ uninstall_cmd(TkCore::INTERP._split_tklist(code_obj.path)[-1])
ret
end
@@ -368,16 +274,6 @@ class TkNamespace < TkObject
tk_call('namespace', 'parent', @fullname)
end
- def self.get_path
- tk_call('namespace', 'path')
- end
- def self.set_path(*namespace_list)
- tk_call('namespace', 'path', array2tk_list(namespace_list))
- end
- def set_path
- tk_call('namespace', 'path', @fullname)
- end
-
def self.qualifiers(str)
tk_call('namespace', 'qualifiers', str)
end
diff --git a/ext/tk/lib/tk/optiondb.rb b/ext/tk/lib/tk/optiondb.rb
index a806f3971d..1484671920 100644
--- a/ext/tk/lib/tk/optiondb.rb
+++ b/ext/tk/lib/tk/optiondb.rb
@@ -44,7 +44,7 @@ module TkOptionDB
"can't call 'TkOptionDB.read_entries' on a safe interpreter"
end
- i_enc = ((Tk.encoding)? Tk.encoding : Tk.encoding_system)
+ i_enc = Tk.encoding()
unless f_enc
f_enc = i_enc
@@ -178,8 +178,7 @@ module TkOptionDB
proc_source = TkOptionDB.get(self::CARRIER, id.id2name, '').strip
res_proc = nil if proc_str != proc_source # resource is changed
- # unless res_proc.kind_of?(Proc)
- unless TkComm._callback_entry?(res_proc)
+ unless res_proc.kind_of? Proc
#if id == :new || !(self::METHOD_TBL.has_key?(id) || self::ADD_METHOD)
if id == :new || !(@method_tbl.has_key?(id) || @add_method)
raise NoMethodError,
@@ -254,7 +253,7 @@ module TkOptionDB
CmdClassID[1].succ!
parent = nil # ignore parent
else
- klass = klass.to_s if klass.kind_of?(Symbol)
+ klass = klass.to_s if klass.kind_of? Symbol
unless (?A..?Z) === klass[0]
fail ArgumentError, "bad string '#{klass}' for class name"
end
@@ -270,7 +269,7 @@ module TkOptionDB
carrier = Tk.tk_call_without_enc('frame', @path, '-class', klass)
end
- unless func.kind_of?(Array)
+ unless func.kind_of? Array
fail ArgumentError, "method-list must be Array"
end
func_str = func.join(' ')
diff --git a/ext/tk/lib/tk/pack.rb b/ext/tk/lib/tk/pack.rb
index 8fab363121..d592fa1c80 100644
--- a/ext/tk/lib/tk/pack.rb
+++ b/ext/tk/lib/tk/pack.rb
@@ -51,13 +51,13 @@ module TkPack
return info
end
- def propagate(master, mode=None)
+ def propagate(master, bool=None)
# master = master.epath if master.kind_of?(TkObject)
master = _epath(master)
- if mode == None
+ if bool == None
bool(tk_call_without_enc('pack', 'propagate', master))
else
- tk_call_without_enc('pack', 'propagate', master, mode)
+ tk_call_without_enc('pack', 'propagate', master, bool)
end
end
diff --git a/ext/tk/lib/tk/palette.rb b/ext/tk/lib/tk/palette.rb
index 2b6fdf5d90..dfe46940f3 100644
--- a/ext/tk/lib/tk/palette.rb
+++ b/ext/tk/lib/tk/palette.rb
@@ -30,23 +30,22 @@ module TkPalette
tk_call('tkDarken', color, percent)
end
- def TkPalette.recolorTree(win, colors)
+ def TkPalette.recolorTree(window, colors)
if not colors.kind_of?(Hash)
fail "2nd arg need to be Hash"
end
- tk_call('global', "tkPalette")
colors.each{|key, value|
begin
- if win.cget(key) == tk_call('set', "tkPalette(#{key})")
- win[key] = colors[key]
+ if window.cget(key) == tk_call('set', "tkPalette(#{key})")
+ window[key] = colors[key]
end
rescue
# ignore
end
}
- TkWinfo.children(win).each{|w| TkPalette.recolorTree(w, colors)}
+ TkWinfo.children(window).each{|w| TkPalette.recolorTree(w, colors)}
end
def recolorTree(colors)
diff --git a/ext/tk/lib/tk/panedwindow.rb b/ext/tk/lib/tk/panedwindow.rb
index 3f4266e4f9..37be77508f 100644
--- a/ext/tk/lib/tk/panedwindow.rb
+++ b/ext/tk/lib/tk/panedwindow.rb
@@ -107,38 +107,24 @@ class TkPanedWindow<TkWindow
# win = win.epath if win.kind_of?(TkObject)
win = _epath(win)
if key
- #conf = tk_split_list(tk_send_without_enc('paneconfigure',
- # win, "-#{key}"))
conf = tk_split_list(tk_send_without_enc('paneconfigure',
- win, "-#{key}"),
- false, true)
+ win, "-#{key}"))
conf[0] = conf[0][1..-1]
- if conf[0] == 'hide'
- conf[3] = bool(conf[3]) unless conf[3].empty?
- conf[4] = bool(conf[4]) unless conf[4].empty?
- end
conf
else
- #tk_split_simplelist(tk_send_without_enc('paneconfigure',
- # win)).collect{|conflist|
- # conf = tk_split_simplelist(conflist)
- tk_split_simplelist(tk_send_without_enc('paneconfigure', win),
- false, false).collect{|conflist|
- conf = tk_split_simplelist(conflist, false, true)
+ tk_split_simplelist(tk_send_without_enc('paneconfigure',
+ win)).collect{|conflist|
+ conf = tk_split_simplelist(conflist)
conf[0] = conf[0][1..-1]
if conf[3]
- if conf[0] == 'hide'
- conf[3] = bool(conf[3]) unless conf[3].empty?
- elsif conf[3].index('{')
+ if conf[3].index('{')
conf[3] = tk_split_list(conf[3])
else
conf[3] = tk_tcl2ruby(conf[3])
end
end
if conf[4]
- if conf[0] == 'hide'
- conf[4] = bool(conf[4]) unless conf[4].empty?
- elsif conf[4].index('{')
+ if conf[4].index('{')
conf[4] = tk_split_list(conf[4])
else
conf[4] = tk_tcl2ruby(conf[4])
@@ -152,39 +138,25 @@ class TkPanedWindow<TkWindow
# win = win.epath if win.kind_of?(TkObject)
win = _epath(win)
if key
- #conf = tk_split_list(tk_send_without_enc('paneconfigure',
- # win, "-#{key}"))
conf = tk_split_list(tk_send_without_enc('paneconfigure',
- win, "-#{key}"),
- false, true)
+ win, "-#{key}"))
key = conf.shift[1..-1]
- if key == 'hide'
- conf[2] = bool(conf[2]) unless conf[2].empty?
- conf[3] = bool(conf[3]) unless conf[3].empty?
- end
{ key => conf }
else
ret = {}
- #tk_split_simplelist(tk_send_without_enc('paneconfigure',
- # win)).each{|conflist|
- # conf = tk_split_simplelist(conflist)
- tk_split_simplelist(tk_send_without_enc('paneconfigure', win),
- false, false).each{|conflist|
- conf = tk_split_simplelist(conflist, false, true)
+ tk_split_simplelist(tk_send_without_enc('paneconfigure',
+ win)).each{|conflist|
+ conf = tk_split_simplelist(conflist)
key = conf.shift[1..-1]
if key
- if key == 'hide'
- conf[2] = bool(conf[2]) unless conf[2].empty?
- elsif conf[2].index('{')
+ if conf[2].index('{')
conf[2] = tk_split_list(conf[2])
else
conf[2] = tk_tcl2ruby(conf[2])
end
end
if conf[3]
- if key == 'hide'
- conf[3] = bool(conf[3]) unless conf[3].empty?
- elsif conf[3].index('{')
+ if conf[3].index('{')
conf[3] = tk_split_list(conf[3])
else
conf[3] = tk_tcl2ruby(conf[3])
diff --git a/ext/tk/lib/tk/radiobutton.rb b/ext/tk/lib/tk/radiobutton.rb
index f8f67d709a..697c021283 100644
--- a/ext/tk/lib/tk/radiobutton.rb
+++ b/ext/tk/lib/tk/radiobutton.rb
@@ -17,24 +17,6 @@ class TkRadioButton<TkButton
#end
#private :create_self
- def __boolval_optkeys
- super() << 'indicatoron'
- end
- private :__boolval_optkeys
-
- def __strval_optkeys
- super() << 'selectcolor'
- end
- private :__strval_optkeys
-
- def __ruby2val_optkeys # { key=>proc, ... }
- {
- 'variable'=>proc{|v| tk_trace_variable(v)} # for backward compatibility
- }
- end
- private :__ruby2val_optkeys
-
-
def deselect
tk_send_without_enc('deselect')
self
@@ -43,24 +25,8 @@ class TkRadioButton<TkButton
tk_send_without_enc('select')
self
end
-
- def get_value
- var = tk_send_without_enc('cget', '-variable')
- if TkVariable::USE_TCLs_SET_VARIABLE_FUNCTIONS
- _fromUTF8(INTERP._get_global_var(var))
- else
- INTERP._eval(Kernel.format('global %s; set %s', var, var))
- end
- end
-
- def set_value(val)
- var = tk_send_without_enc('cget', '-variable')
- if TkVariable::USE_TCLs_SET_VARIABLE_FUNCTIONS
- _fromUTF8(INTERP._set_global_var(var, _get_eval_string(val, true)))
- else
- s = '"' + _get_eval_string(val).gsub(/[\[\]$"\\]/, '\\\\\&') + '"'
- INTERP._eval(Kernel.format('global %s; set %s %s', var, var, s))
- end
+ def variable(v)
+ configure 'variable', tk_trace_variable(v)
end
end
TkRadiobutton = TkRadioButton
diff --git a/ext/tk/lib/tk/root.rb b/ext/tk/lib/tk/root.rb
index 0e5584c7c1..24a5cf1ea0 100644
--- a/ext/tk/lib/tk/root.rb
+++ b/ext/tk/lib/tk/root.rb
@@ -9,11 +9,6 @@ class TkRoot<TkWindow
include Wm
include TkMenuSpec
- def __methodcall_optkeys # { key=>method, ... }
- TOPLEVEL_METHODCALL_OPTKEYS
- end
- private :__methodcall_optkeys
-
=begin
ROOT = []
def TkRoot.new(keys=nil)
@@ -41,18 +36,7 @@ class TkRoot<TkWindow
super(:without_creating=>true, :widgetname=>'.'){}
end
root = TkCore::INTERP.tk_windows['.']
-
- keys = _symbolkey2str(keys)
-
- # wm commands
- root.instance_eval{
- __methodcall_optkeys.each{|key, method|
- value = keys.delete(key.to_s)
- self.__send__(method, value) if value
- }
- }
-
- if keys # wm commands ( for backward comaptibility )
+ if keys # wm commands
keys.each{|k,v|
if v.kind_of? Array
root.__send__(k,*v)
@@ -61,7 +45,6 @@ class TkRoot<TkWindow
end
}
end
-
root.instance_eval(&b) if block_given?
root
end
@@ -69,11 +52,6 @@ class TkRoot<TkWindow
WidgetClassName = 'Tk'.freeze
WidgetClassNames[WidgetClassName] = self
- def self.to_eval
- # self::WidgetClassName
- '.'
- end
-
def create_self
@path = '.'
end
diff --git a/ext/tk/lib/tk/scale.rb b/ext/tk/lib/tk/scale.rb
index 0b703aa055..7214c46f5e 100644
--- a/ext/tk/lib/tk/scale.rb
+++ b/ext/tk/lib/tk/scale.rb
@@ -24,11 +24,6 @@ class TkScale<TkWindow
end
private :create_self
- def __strval_optkeys
- super() << 'label'
- end
- private :__strval_optkeys
-
def _wrap_command_arg(cmd)
proc{|val|
if val.kind_of?(String)
diff --git a/ext/tk/lib/tk/spinbox.rb b/ext/tk/lib/tk/spinbox.rb
index 9a10977d12..f4febb05b1 100644
--- a/ext/tk/lib/tk/spinbox.rb
+++ b/ext/tk/lib/tk/spinbox.rb
@@ -11,51 +11,6 @@ class TkSpinbox<TkEntry
WidgetClassName = 'Spinbox'.freeze
WidgetClassNames[WidgetClassName] = self
- class SpinCommand < TkValidateCommand
- class ValidateArgs < TkUtil::CallbackSubst
- KEY_TBL = [
- [ ?d, ?s, :direction ],
- [ ?s, ?e, :current ],
- [ ?W, ?w, :widget ],
- nil
- ]
-
- PROC_TBL = [
- [ ?s, TkComm.method(:string) ],
- [ ?w, TkComm.method(:window) ],
-
- [ ?e, proc{|val|
- #enc = Tk.encoding
- enc = ((Tk.encoding)? Tk.encoding : Tk.encoding_system)
- if enc
- Tk.fromUTF8(TkComm::string(val), enc)
- else
- TkComm::string(val)
- end
- }
- ],
-
- nil
- ]
-
- _setup_subst_table(KEY_TBL, PROC_TBL);
-
- def self.ret_val(val)
- (val)? '1': '0'
- end
- end
-
- def self._config_keys
- ['command']
- end
- end
-
- def __validation_class_list
- super() << SpinCommand
- end
-
- Tk::ValidateConfigure.__def_validcmd(binding, SpinCommand)
-
#def create_self(keys)
# tk_call_without_enc('spinbox', @path)
# if keys and keys != None
@@ -64,21 +19,6 @@ class TkSpinbox<TkEntry
#end
#private :create_self
- def __boolval_optkeys
- super() << 'wrap'
- end
- private :__boolval_optkeys
-
- def __strval_optkeys
- super() << 'buttonbackground' << 'format'
- end
- private :__strval_optkeys
-
- def __listval_optkeys
- super() << 'values'
- end
- private :__listval_optkeys
-
def identify(x, y)
tk_send_without_enc('identify', x, y)
end
diff --git a/ext/tk/lib/tk/tagfont.rb b/ext/tk/lib/tk/tagfont.rb
index a1807395d2..a106f814be 100644
--- a/ext/tk/lib/tk/tagfont.rb
+++ b/ext/tk/lib/tk/tagfont.rb
@@ -25,19 +25,19 @@ module TkTreatTagFont
self
end
- def font_copy(win, wintag=nil)
- @parent.tagfont_copy(@id, win, wintag)
+ def font_copy(window, wintag=nil)
+ @parent.tagfont_copy(@id, window, wintag)
self
end
- def latinfont_copy(win, wintag=nil)
- @parent.latintagfont_copy(@id, win, wintag)
+ def latinfont_copy(window, wintag=nil)
+ @parent.latintagfont_copy(@id, window, wintag)
self
end
alias asciifont_copy latinfont_copy
- def kanjifont_copy(win, wintag=nil)
- @parent.kanjitagfont_copy(@id, win, wintag)
+ def kanjifont_copy(window, wintag=nil)
+ @parent.kanjitagfont_copy(@id, window, wintag)
self
end
end
diff --git a/ext/tk/lib/tk/text.rb b/ext/tk/lib/tk/text.rb
index bd5de278cf..efede9861f 100644
--- a/ext/tk/lib/tk/text.rb
+++ b/ext/tk/lib/tk/text.rb
@@ -66,92 +66,6 @@ class TkText<TkTextWin
include TkTextTagConfig
include Scrollable
- #######################################
-
- module IndexModMethods
- def +(mod)
- return chars(mod) if mod.kind_of?(Numeric)
-
- mod = mod.to_s
- if mod =~ /^\s*[+-]?\d/
- TkText::IndexString.new(String.new(id) << ' + ' << mod)
- else
- TkText::IndexString.new(String.new(id) << ' ' << mod)
- end
- end
-
- def -(mod)
- return chars(-mod) if mod.kind_of?(Numeric)
-
- mod = mod.to_s
- if mod =~ /^\s*[+-]?\d/
- TkText::IndexString.new(String.new(id) << ' - ' << mod)
- elsif mod =~ /^\s*[-]\s+(\d.*)$/
- TkText::IndexString.new(String.new(id) << ' - -' << $1)
- else
- TkText::IndexString.new(String.new(id) << ' ' << mod)
- end
- end
-
- def chars(mod)
- fail ArgumentError, 'expect Integer' unless mod.kind_of?(Integer)
- if mod < 0
- TkText::IndexString.new(String.new(id) << ' ' << mod.to_s << ' chars')
- else
- TkText::IndexString.new(String.new(id) << ' + ' << mod.to_s << ' chars')
- end
- end
- alias char chars
-
- def lines(mod)
- fail ArgumentError, 'expect Integer' unless mod.kind_of?(Integer)
- if mod < 0
- TkText::IndexString.new(String.new(id) << ' ' << mod.to_s << ' lines')
- else
- TkText::IndexString.new(String.new(id) << ' + ' << mod.to_s << ' lines')
- end
- end
- alias line lines
-
- def linestart
- TkText::IndexString.new(String.new(id) << ' linestart')
- end
- def lineend
- TkText::IndexString.new(String.new(id) << ' lineend')
- end
-
- def wordstart
- TkText::IndexString.new(String.new(id) << ' wordstart')
- end
- def wordend
- TkText::IndexString.new(String.new(id) << ' wordend')
- end
- end
-
- class IndexString < String
- include IndexModMethods
-
- def self.at(x,y)
- self.new("@#{x},#{y}")
- end
-
- def self.new(str)
- if str.kind_of?(String)
- super(str)
- elsif str.kind_of?(Symbol)
- super(str.to_s)
- else
- str
- end
- end
-
- def id
- self
- end
- end
-
- #######################################
-
TkCommandNames = ['text'.freeze].freeze
WidgetClassName = 'Text'.freeze
WidgetClassNames[WidgetClassName] = self
@@ -187,22 +101,8 @@ class TkText<TkTextWin
end
private :create_self
- def __strval_optkeys
- super() << 'inactiveseletcionbackground'
- end
- private :__strval_optkeys
-
- def self.at(x, y)
- TkText::IndexString.at(x, y)
- end
-
- def at(x, y)
- TkText::IndexString.at(x, y)
- end
-
- def index(idx)
- TkText::IndexString.new(tk_send_without_enc('index',
- _get_eval_enc_str(idx)))
+ def index(index)
+ tk_send_without_enc('index', _get_eval_enc_str(index))
end
def get_displaychars(*index)
@@ -255,15 +155,13 @@ class TkText<TkTextWin
end
def tag_names(index=None)
- #tk_split_simplelist(_fromUTF8(tk_send_without_enc('tag', 'names', _get_eval_enc_str(index)))).collect{|elt|
- tk_split_simplelist(tk_send_without_enc('tag', 'names', _get_eval_enc_str(index)), false, true).collect{|elt|
+ tk_split_simplelist(_fromUTF8(tk_send_without_enc('tag', 'names', _get_eval_enc_str(index)))).collect{|elt|
tagid2obj(elt)
}
end
def mark_names
- #tk_split_simplelist(_fromUTF8(tk_send_without_enc('mark', 'names'))).collect{|elt|
- tk_split_simplelist(tk_send_without_enc('mark', 'names'), false, true).collect{|elt|
+ tk_split_simplelist(_fromUTF8(tk_send_without_enc('mark', 'names'))).collect{|elt|
tagid2obj(elt)
}
end
@@ -317,7 +215,7 @@ class TkText<TkTextWin
end
def image_configure(index, slot, value=None)
- if slot.kind_of?(Hash)
+ if slot.kind_of? Hash
_fromUTF8(tk_send_without_enc('image', 'configure',
_get_eval_enc_str(index),
*hash_kv(slot, true)))
@@ -335,19 +233,15 @@ class TkText<TkTextWin
if slot
case slot.to_s
when 'text', 'label', 'show', 'data', 'file'
- #conf = tk_split_simplelist(_fromUTF8(tk_send_without_enc('image', 'configure', _get_eval_enc_str(index), "-#{slot}")))
- conf = tk_split_simplelist(tk_send_without_enc('image', 'configure', _get_eval_enc_str(index), "-#{slot}"), false, true)
+ conf = tk_split_simplelist(_fromUTF8(tk_send_without_enc('image', 'configure', _get_eval_enc_str(index), "-#{slot}")))
else
- #conf = tk_split_list(_fromUTF8(tk_send_without_enc('image', 'configure', _get_eval_enc_str(index), "-#{slot}")))
- conf = tk_split_list(tk_send_without_enc('image', 'configure', _get_eval_enc_str(index), "-#{slot}"), 0, false, true)
+ conf = tk_split_list(_fromUTF8(tk_send_without_enc('image', 'configure', _get_eval_enc_str(index), "-#{slot}")))
end
conf[0] = conf[0][1..-1]
conf
else
- # tk_split_simplelist(_fromUTF8(tk_send_without_enc('image', 'configure', _get_eval_enc_str(index)))).collect{|conflist|
- # conf = tk_split_simplelist(conflist)
- tk_split_simplelist(tk_send_without_enc('image', 'configure', _get_eval_enc_str(index)), false, false).collect{|conflist|
- conf = tk_split_simplelist(conflist, false, true)
+ tk_split_simplelist(_fromUTF8(tk_send_without_enc('image', 'configure', _get_eval_enc_str(index)))).collect{|conflist|
+ conf = tk_split_simplelist(conflist)
conf[0] = conf[0][1..-1]
case conf[0]
when 'text', 'label', 'show', 'data', 'file'
@@ -375,20 +269,16 @@ class TkText<TkTextWin
if slot
case slot.to_s
when 'text', 'label', 'show', 'data', 'file'
- #conf = tk_split_simplelist(_fromUTF8(tk_send_without_enc('image', 'configure', _get_eval_enc_str(index), "-#{slot}")))
- conf = tk_split_simplelist(tk_send_without_enc('image', 'configure', _get_eval_enc_str(index), "-#{slot}"), false, true)
+ conf = tk_split_simplelist(_fromUTF8(tk_send_without_enc('image', 'configure', _get_eval_enc_str(index), "-#{slot}")))
else
- #conf = tk_split_list(_fromUTF8(tk_send_without_enc('image', 'configure', _get_eval_enc_str(index), "-#{slot}")))
- conf = tk_split_list(tk_send_without_enc('image', 'configure', _get_eval_enc_str(index), "-#{slot}"), 0, false, true)
+ conf = tk_split_list(_fromUTF8(tk_send_without_enc('image', 'configure', _get_eval_enc_str(index), "-#{slot}")))
end
key = conf.shift[1..-1]
{ key => conf }
else
ret = {}
- #tk_split_simplelist(_fromUTF8(tk_send_without_enc('image', 'configure', _get_eval_enc_str(index)))).each{|conflist|
- # conf = tk_split_simplelist(conflist)
- tk_split_simplelist(tk_send_without_enc('image', 'configure', _get_eval_enc_str(index)), false, false).each{|conflist|
- conf = tk_split_simplelist(conflist, false, true)
+ tk_split_simplelist(_fromUTF8(tk_send_without_enc('image', 'configure', _get_eval_enc_str(index)))).each{|conflist|
+ conf = tk_split_simplelist(conflist)
key = conf.shift[1..-1]
case key
when 'text', 'label', 'show', 'data', 'file'
@@ -441,8 +331,7 @@ class TkText<TkTextWin
end
def image_names
- #tk_split_simplelist(_fromUTF8(tk_send_without_enc('image', 'names'))).collect{|elt|
- tk_split_simplelist(tk_send_without_enc('image', 'names'), false, true).collect{|elt|
+ tk_split_simplelist(_fromUTF8(tk_send_without_enc('image', 'names'))).collect{|elt|
tagid2obj(elt)
}
end
@@ -458,20 +347,20 @@ class TkText<TkTextWin
end
def insert(index, chars, *tags)
- if tags[0].kind_of?(Array)
+ if tags[0].kind_of? Array
# multiple chars-taglist argument :: str, [tag,...], str, [tag,...], ...
args = [chars]
while tags.size > 0
args << tags.shift.collect{|x|_get_eval_string(x)}.join(' ') # taglist
args << tags.shift if tags.size > 0 # chars
end
- super(index, *args)
+ super index, *args
else
# single chars-taglist argument :: str, tag, tag, ...
if tags.size == 0
- super(index, chars)
+ super index, chars
else
- super(index, chars, tags.collect{|x|_get_eval_string(x)}.join(' '))
+ super index, chars, tags.collect{|x|_get_eval_string(x)}.join(' ')
end
end
end
@@ -481,7 +370,7 @@ class TkText<TkTextWin
@tags.each_value do |t|
t.destroy
end
- super()
+ super
end
def backspace
@@ -529,11 +418,6 @@ class TkText<TkTextWin
info
end
- def peer_names()
- # Tk8.5 feature
- list(tk_send_without_enc('peer', 'names'))
- end
-
def replace(idx1, idx2, *opts)
tk_send('replace', idx1, idx2, *opts)
self
@@ -623,7 +507,7 @@ class TkText<TkTextWin
*(tags.collect{|tag| _get_eval_enc_str(tag)}))
if TkTextTag::TTagID_TBL[@path]
tags.each{|tag|
- if tag.kind_of?(TkTextTag)
+ if tag.kind_of? TkTextTag
TkTextTag::TTagID_TBL[@path].delete(tag.id)
else
TkTextTag::TTagID_TBL[@path].delete(tag)
@@ -635,33 +519,13 @@ class TkText<TkTextWin
alias deltag tag_delete
alias delete_tag tag_delete
- #def tag_bind(tag, seq, cmd=Proc.new, *args)
- # _bind([@path, 'tag', 'bind', tag], seq, cmd, *args)
- # self
- #end
- def tag_bind(tag, seq, *args)
- # if args[0].kind_of?(Proc) || args[0].kind_of?(Method)
- if TkComm._callback_entry?(args[0]) || !block_given?
- cmd = args.shift
- else
- cmd = Proc.new
- end
- _bind([@path, 'tag', 'bind', tag], seq, cmd, *args)
+ def tag_bind(tag, seq, cmd=Proc.new, args=nil)
+ _bind([@path, 'tag', 'bind', tag], seq, cmd, args)
self
end
- #def tag_bind_append(tag, seq, cmd=Proc.new, *args)
- # _bind_append([@path, 'tag', 'bind', tag], seq, cmd, *args)
- # self
- #end
- def tag_bind_append(tag, seq, *args)
- # if args[0].kind_of?(Proc) || args[0].kind_of?(Method)
- if TkComm._callback_entry?(args[0]) || !block_given?
- cmd = args.shift
- else
- cmd = Proc.new
- end
- _bind_append([@path, 'tag', 'bind', tag], seq, cmd, *args)
+ def tag_bind_append(tag, seq, cmd=Proc.new, args=nil)
+ _bind_append([@path, 'tag', 'bind', tag], seq, cmd, args)
self
end
@@ -698,7 +562,7 @@ class TkText<TkTextWin
end
def tag_configure(tag, key, val=None)
- if key.kind_of?(Hash)
+ if key.kind_of? Hash
key = _symbolkey2str(key)
if ( key['font'] || key['kanjifont'] \
|| key['latinfont'] || key['asciifont'] )
@@ -869,34 +733,27 @@ class TkText<TkTextWin
end
def tag_ranges(tag)
- #l = tk_split_simplelist(tk_send_without_enc('tag', 'ranges',
- # _get_eval_enc_str(tag)))
l = tk_split_simplelist(tk_send_without_enc('tag', 'ranges',
- _get_eval_enc_str(tag)),
- false, true)
+ _get_eval_enc_str(tag)))
r = []
while key=l.shift
- r.push [TkText::IndexString.new(key), TkText::IndexString.new(l.shift)]
+ r.push [key, l.shift]
end
r
end
def tag_nextrange(tag, first, last=None)
- simplelist(tk_send_without_enc('tag', 'nextrange',
- _get_eval_enc_str(tag),
- _get_eval_enc_str(first),
- _get_eval_enc_str(last))).collect{|idx|
- TkText::IndexString.new(idx)
- }
+ tk_split_list(tk_send_without_enc('tag', 'nextrange',
+ _get_eval_enc_str(tag),
+ _get_eval_enc_str(first),
+ _get_eval_enc_str(last)))
end
def tag_prevrange(tag, first, last=None)
- simplelist(tk_send_without_enc('tag', 'prevrange',
- _get_eval_enc_str(tag),
- _get_eval_enc_str(first),
- _get_eval_enc_str(last))).collect{|idx|
- TkText::IndexString.new(idx)
- }
+ tk_split_list(tk_send_without_enc('tag', 'prevrange',
+ _get_eval_enc_str(tag),
+ _get_eval_enc_str(first),
+ _get_eval_enc_str(last)))
end
=begin
@@ -923,17 +780,17 @@ class TkText<TkTextWin
end
def window_configure(index, slot, value=None)
- if index.kind_of?(TkTextWindow)
+ if index.kind_of? TkTextWindow
index.configure(slot, value)
else
- if slot.kind_of?(Hash)
+ if slot.kind_of? Hash
slot = _symbolkey2str(slot)
win = slot['window']
# slot['window'] = win.epath if win.kind_of?(TkWindow)
slot['window'] = _epath(win) if win
if slot['create']
p_create = slot['create']
- if p_create.kind_of?(Proc)
+ if p_create.kind_of? Proc
#=begin
slot['create'] = install_cmd(proc{
id = p_create.call
@@ -958,7 +815,7 @@ class TkText<TkTextWin
end
if slot == 'create' || slot == :create
p_create = value
- if p_create.kind_of?(Proc)
+ if p_create.kind_of? Proc
#=begin
value = install_cmd(proc{
id = p_create.call
@@ -1084,8 +941,7 @@ class TkText<TkTextWin
=end
def window_names
- # tk_split_simplelist(_fromUTF8(tk_send_without_enc('window', 'names'))).collect{|elt|
- tk_split_simplelist(tk_send_without_enc('window', 'names'), false, true).collect{|elt|
+ tk_split_simplelist(_fromUTF8(tk_send_without_enc('window', 'names'))).collect{|elt|
tagid2obj(elt)
}
end
@@ -1140,7 +996,7 @@ class TkText<TkTextWin
if ret == ""
nil
else
- TkText::IndexString.new(ret)
+ ret
end
end
@@ -1175,12 +1031,12 @@ class TkText<TkTextWin
if ret == ""
nil
else
- TkText::IndexString.new(ret)
+ ret
end
end
def search_with_length(pat,start,stop=None)
- pat = pat.chr if pat.kind_of?(Integer)
+ pat = pat.chr if pat.kind_of? Integer
if stop != None
return ["", 0] if compare(start,'>=',stop)
txt = get(start,stop)
@@ -1188,7 +1044,7 @@ class TkText<TkTextWin
match = $&
#pos = txt[0..(pos-1)].split('').length if pos > 0
pos = _ktext_length(txt[0..(pos-1)]) if pos > 0
- if pat.kind_of?(String)
+ if pat.kind_of? String
#return [index(start + " + #{pos} chars"), pat.split('').length]
return [index(start + " + #{pos} chars"),
_ktext_length(pat), pat.dup]
@@ -1206,7 +1062,7 @@ class TkText<TkTextWin
match = $&
#pos = txt[0..(pos-1)].split('').length if pos > 0
pos = _ktext_length(txt[0..(pos-1)]) if pos > 0
- if pat.kind_of?(String)
+ if pat.kind_of? String
#return [index(start + " + #{pos} chars"), pat.split('').length]
return [index(start + " + #{pos} chars"),
_ktext_length(pat), pat.dup]
@@ -1221,7 +1077,7 @@ class TkText<TkTextWin
match = $&
#pos = txt[0..(pos-1)].split('').length if pos > 0
pos = _ktext_length(txt[0..(pos-1)]) if pos > 0
- if pat.kind_of?(String)
+ if pat.kind_of? String
#return [index("1.0 + #{pos} chars"), pat.split('').length]
return [index("1.0 + #{pos} chars"),
_ktext_length(pat), pat.dup]
@@ -1241,7 +1097,7 @@ class TkText<TkTextWin
end
def rsearch_with_length(pat,start,stop=None)
- pat = pat.chr if pat.kind_of?(Integer)
+ pat = pat.chr if pat.kind_of? Integer
if stop != None
return ["", 0] if compare(start,'<=',stop)
txt = get(stop,start)
@@ -1249,7 +1105,7 @@ class TkText<TkTextWin
match = $&
#pos = txt[0..(pos-1)].split('').length if pos > 0
pos = _ktext_length(txt[0..(pos-1)]) if pos > 0
- if pat.kind_of?(String)
+ if pat.kind_of? String
#return [index(stop + " + #{pos} chars"), pat.split('').length]
return [index(stop + " + #{pos} chars"), _ktext_length(pat), pat.dup]
else
@@ -1265,7 +1121,7 @@ class TkText<TkTextWin
match = $&
#pos = txt[0..(pos-1)].split('').length if pos > 0
pos = _ktext_length(txt[0..(pos-1)]) if pos > 0
- if pat.kind_of?(String)
+ if pat.kind_of? String
#return [index("1.0 + #{pos} chars"), pat.split('').length]
return [index("1.0 + #{pos} chars"), _ktext_length(pat), pat.dup]
else
@@ -1278,7 +1134,7 @@ class TkText<TkTextWin
match = $&
#pos = txt[0..(pos-1)].split('').length if pos > 0
pos = _ktext_length(txt[0..(pos-1)]) if pos > 0
- if pat.kind_of?(String)
+ if pat.kind_of? String
#return [index("1.0 + #{pos} chars"), pat.split('').length]
return [index("1.0 + #{pos} chars"), _ktext_length(pat), pat.dup]
else
@@ -1297,11 +1153,6 @@ class TkText<TkTextWin
end
def dump(type_info, *index, &block)
- if type_info.kind_of?(Symbol)
- type_info = [ type_info.to_s ]
- elsif type_info.kind_of?(String)
- type_info = [ type_info ]
- end
args = type_info.collect{|inf| '-' + inf}
args << '-command' << block if block
str = tk_send('dump', *(args + index))
@@ -1355,8 +1206,6 @@ class TkText<TkTextWin
result.push tk_tcl2ruby(val)
when 'window'
result.push tk_tcl2ruby(val)
- when 'image'
- result.push tk_tcl2ruby(val)
end
i = idx + 1
end
@@ -1364,10 +1213,10 @@ class TkText<TkTextWin
# retrieve index
idx = str.index(/ /, i)
if idx
- result.push(TkText::IndexString.new(str[i..(idx-1)]))
+ result.push str[i..(idx-1)]
i = idx + 1
else
- result.push(TkText::IndexString.new(str[i..-1]))
+ result.push str[i..-1]
break
end
end
@@ -1434,25 +1283,3 @@ class TkText<TkTextWin
dump(['image'], *index, &block)
end
end
-
-#######################################
-
-class TkText::Peer < TkText
- # Tk8.5 feature
- def initialize(text, parent=nil, keys={})
- unless text.kind_of?(TkText)
- fail ArgumentError, "TkText is expected for 1st argument"
- end
- @src_text = text
- super(parent, keys)
- end
-
- def create_self(keys)
- if keys and keys != None
- tk_call_without_enc(@src_text.path, 'peer', 'create', @path)
- else
- tk_call_without_enc(@src_text.path, 'peer', 'create', @path)
- end
- end
- private :create_self
-end
diff --git a/ext/tk/lib/tk/textimage.rb b/ext/tk/lib/tk/textimage.rb
index a29b23c7dd..bd92387e3c 100644
--- a/ext/tk/lib/tk/textimage.rb
+++ b/ext/tk/lib/tk/textimage.rb
@@ -5,14 +5,12 @@ require 'tk'
require 'tk/text'
class TkTextImage<TkObject
- include TkText::IndexModMethods
-
def initialize(parent, index, keys)
#unless parent.kind_of?(TkText)
- # fail ArgumentError, "expect TkText for 1st argument"
+ # fail ArguemntError, "expect TkText for 1st argument"
#end
@t = parent
- if index == 'end' || index == :end
+ if index == 'end'
@path = TkTextMark.new(@t, tk_call(@t.path, 'index', 'end - 1 chars'))
elsif index.kind_of? TkTextMark
if tk_call_without_enc(@t.path,'index',index.path) == tk_call_without_enc(@t.path,'index','end')
@@ -29,15 +27,7 @@ class TkTextImage<TkObject
@path.gravity = 'left'
@index = @path.path
@id = tk_call_without_enc(@t.path, 'image', 'create', @index,
- *hash_kv(keys, true)).freeze
- @path.gravity = 'right'
- end
-
- def id
- TkText::IndexString.new(@id)
- end
- def mark
- @path
+ *hash_kv(keys, true))
end
def [](slot)
@@ -69,7 +59,7 @@ class TkTextImage<TkObject
end
def image
- img = tk_call_without_enc(@t.path, 'image', 'cget', @index, '-image')
+ img = tk_call_without_enc(@t.path, 'image', 'configure', @index, '-image')
TkImage::Tk_IMGTBL[img]? TkImage::Tk_IMGTBL[img] : img
end
diff --git a/ext/tk/lib/tk/textmark.rb b/ext/tk/lib/tk/textmark.rb
index 650d95af70..6004b86028 100644
--- a/ext/tk/lib/tk/textmark.rb
+++ b/ext/tk/lib/tk/textmark.rb
@@ -5,8 +5,6 @@ require 'tk'
require 'tk/text'
class TkTextMark<TkObject
- include TkText::IndexModMethods
-
TMarkID_TBL = TkCore::INTERP.create_table
Tk_TextMark_ID = ['mark'.freeze, '00000'.taint].freeze
@@ -20,12 +18,12 @@ class TkTextMark<TkObject
def initialize(parent, index)
#unless parent.kind_of?(TkText)
- # fail ArgumentError, "expect TkText for 1st argument"
+ # fail ArguemntError, "expect TkText for 1st argument"
#end
@parent = @t = parent
@tpath = parent.path
# @path = @id = Tk_TextMark_ID.join('')
- @path = @id = Tk_TextMark_ID.join(TkCore::INTERP._ip_id_).freeze
+ @path = @id = Tk_TextMark_ID.join(TkCore::INTERP._ip_id_)
TMarkID_TBL[@id] = self
TMarkID_TBL[@tpath] = {} unless TMarkID_TBL[@tpath]
TMarkID_TBL[@tpath][@id] = self
@@ -36,51 +34,22 @@ class TkTextMark<TkObject
end
def id
- TkText::IndexString.new(@id)
+ @id
end
def exist?
- #if ( tk_split_simplelist(_fromUTF8(tk_call_without_enc(@t.path, 'mark', 'names'))).find{|id| id == @id } )
- if ( tk_split_simplelist(tk_call_without_enc(@t.path, 'mark', 'names'), false, true).find{|id| id == @id } )
+ if ( tk_split_simplelist(_fromUTF8(tk_call_without_enc(@t.path, 'mark', 'names'))).find{|id| id == @id } )
true
else
false
end
end
-=begin
- # move to TkText::IndexModMethods module
def +(mod)
- return chars(mod) if mod.kind_of?(Numeric)
-
- mod = mod.to_s
- if mod =~ /^\s*[+-]?\d/
- TkText::IndexString.new(@id + ' + ' + mod)
- else
- TkText::IndexString.new(@id + ' ' + mod)
- end
+ @id + ' + ' + mod
end
-
def -(mod)
- return chars(-mod) if mod.kind_of?(Numeric)
-
- mod = mod.to_s
- if mod =~ /^\s*[+-]?\d/
- TkText::IndexString.new(@id + ' - ' + mod)
- elsif mod =~ /^\s*[-]\s+(\d.*)$/
- TkText::IndexString.new(@id + ' - -' + $1)
- else
- TkText::IndexString.new(@id + ' ' + mod)
- end
- end
-=end
-
- def pos
- @t.index(@id)
- end
-
- def pos=(where)
- set(where)
+ @id + ' - ' + mod
end
def set(where)
@@ -133,7 +102,7 @@ class TkTextNamedMark<TkTextMark
def initialize(parent, name, index=nil)
#unless parent.kind_of?(TkText)
- # fail ArgumentError, "expect TkText for 1st argument"
+ # fail ArguemntError, "expect TkText for 1st argument"
#end
@parent = @t = parent
@tpath = parent.path
@@ -153,13 +122,13 @@ class TkTextMarkInsert<TkTextNamedMark
end
end
-class TkTextMarkCurrent<TkTextNamedMark
+class TkTextMarkCurrent<TkTextMark
def self.new(parent,*args)
super(parent, 'current', *args)
end
end
-class TkTextMarkAnchor<TkTextNamedMark
+class TkTextMarkAnchor<TkTextMark
def self.new(parent,*args)
super(parent, 'anchor', *args)
end
diff --git a/ext/tk/lib/tk/texttag.rb b/ext/tk/lib/tk/texttag.rb
index cc2c56210f..d2611509a4 100644
--- a/ext/tk/lib/tk/texttag.rb
+++ b/ext/tk/lib/tk/texttag.rb
@@ -7,7 +7,6 @@ require 'tk/tagfont'
class TkTextTag<TkObject
include TkTreatTagFont
- include TkText::IndexModMethods
TTagID_TBL = TkCore::INTERP.create_table
Tk_TextTag_ID = ['tag'.freeze, '00000'.taint].freeze
@@ -22,20 +21,20 @@ class TkTextTag<TkObject
def initialize(parent, *args)
#unless parent.kind_of?(TkText)
- # fail ArgumentError, "expect TkText for 1st argument"
+ # fail ArguemntError, "expect TkText for 1st argument"
#end
@parent = @t = parent
@tpath = parent.path
# @path = @id = Tk_TextTag_ID.join('')
- @path = @id = Tk_TextTag_ID.join(TkCore::INTERP._ip_id_).freeze
+ @path = @id = Tk_TextTag_ID.join(TkCore::INTERP._ip_id_)
# TTagID_TBL[@id] = self
TTagID_TBL[@tpath] = {} unless TTagID_TBL[@tpath]
TTagID_TBL[@tpath][@id] = self
Tk_TextTag_ID[1].succ!
#tk_call @t.path, "tag", "configure", @id, *hash_kv(keys)
- if args != []
+ if args != [] then
keys = args.pop
- if keys.kind_of?(Hash)
+ if keys.kind_of? Hash then
add(*args) if args != []
configure(keys)
else
@@ -47,12 +46,11 @@ class TkTextTag<TkObject
end
def id
- TkText::IndexString.new(@id)
+ @id
end
def exist?
- #if ( tk_split_simplelist(_fromUTF8(tk_call_without_enc(@t.path, 'tag', 'names'))).find{|id| id == @id } )
- if ( tk_split_simplelist(tk_call_without_enc(@t.path, 'tag', 'names'), false, true).find{|id| id == @id } )
+ if ( tk_split_simplelist(_fromUTF8(tk_call_without_enc(@t.path, 'tag', 'names'))).find{|id| id == @id } )
true
else
false
@@ -60,11 +58,11 @@ class TkTextTag<TkObject
end
def first
- TkText::IndexString.new(@id + '.first')
+ @id + '.first'
end
def last
- TkText::IndexString.new(@id + '.last')
+ @id + '.last'
end
def add(*indices)
@@ -83,25 +81,21 @@ class TkTextTag<TkObject
l = tk_split_simplelist(tk_call_without_enc(@t.path, 'tag', 'ranges', @id))
r = []
while key=l.shift
- r.push [TkText::IndexString.new(key), TkText::IndexString.new(l.shift)]
+ r.push [key, l.shift]
end
r
end
def nextrange(first, last=None)
- simplelist(tk_call_without_enc(@t.path, 'tag', 'nextrange', @id,
- _get_eval_enc_str(first),
- _get_eval_enc_str(last))).collect{|idx|
- TkText::IndexString.new(idx)
- }
+ tk_split_list(tk_call_without_enc(@t.path, 'tag', 'nextrange', @id,
+ _get_eval_enc_str(first),
+ _get_eval_enc_str(last)))
end
def prevrange(first, last=None)
- simplelist(tk_call_without_enc(@t.path, 'tag', 'prevrange', @id,
- _get_eval_enc_str(first),
- _get_eval_enc_str(last))).collect{|idx|
- TkText::IndexString.new(idx)
- }
+ tk_split_list(tk_call_without_enc(@t.path, 'tag', 'prevrange', @id,
+ _get_eval_enc_str(first),
+ _get_eval_enc_str(last)))
end
def [](key)
@@ -145,7 +139,7 @@ class TkTextTag<TkObject
@t.tag_configure @id, key, val
end
# def configure(key, val=None)
-# if key.kind_of?(Hash)
+# if key.kind_of? Hash
# tk_call @t.path, 'tag', 'configure', @id, *hash_kv(key)
# else
# tk_call @t.path, 'tag', 'configure', @id, "-#{key}", val
@@ -154,7 +148,7 @@ class TkTextTag<TkObject
# def configure(key, value)
# if value == FALSE
# value = "0"
-# elsif value.kind_of?(Proc)
+# elsif value.kind_of? Proc
# value = install_cmd(value)
# end
# tk_call @t.path, 'tag', 'configure', @id, "-#{key}", value
@@ -168,33 +162,13 @@ class TkTextTag<TkObject
@t.current_tag_configinfo @id, key
end
- #def bind(seq, cmd=Proc.new, *args)
- # _bind([@t.path, 'tag', 'bind', @id], seq, cmd, *args)
- # self
- #end
- def bind(seq, *args)
- # if args[0].kind_of?(Proc) || args[0].kind_of?(Method)
- if TkComm._callback_entry?(args[0]) || !block_given?
- cmd = args.shift
- else
- cmd = Proc.new
- end
- _bind([@t.path, 'tag', 'bind', @id], seq, cmd, *args)
+ def bind(seq, cmd=Proc.new, args=nil)
+ _bind([@t.path, 'tag', 'bind', @id], seq, cmd, args)
self
end
- #def bind_append(seq, cmd=Proc.new, *args)
- # _bind_append([@t.path, 'tag', 'bind', @id], seq, cmd, *args)
- # self
- #end
- def bind_append(seq, *args)
- # if args[0].kind_of?(Proc) || args[0].kind_of?(Method)
- if TkComm._callback_entry?(args[0]) || !block_given?
- cmd = args.shift
- else
- cmd = Proc.new
- end
- _bind_append([@t.path, 'tag', 'bind', @id], seq, cmd, *args)
+ def bind_append(seq, cmd=Proc.new, args=nil)
+ _bind_append([@t.path, 'tag', 'bind', @id], seq, cmd, args)
self
end
@@ -230,9 +204,9 @@ class TkTextNamedTag<TkTextTag
def self.new(parent, name, *args)
if TTagID_TBL[parent.path] && TTagID_TBL[parent.path][name]
tagobj = TTagID_TBL[parent.path][name]
- if args != []
+ if args != [] then
keys = args.pop
- if keys.kind_of?(Hash)
+ if keys.kind_of? Hash then
tagobj.add(*args) if args != []
tagobj.configure(keys)
else
@@ -248,7 +222,7 @@ class TkTextNamedTag<TkTextTag
def initialize(parent, name, *args)
#unless parent.kind_of?(TkText)
- # fail ArgumentError, "expect TkText for 1st argument"
+ # fail ArguemntError, "expect TkText for 1st argument"
#end
@parent = @t = parent
@tpath = parent.path
@@ -258,9 +232,9 @@ class TkTextNamedTag<TkTextTag
#if mode
# tk_call @t.path, "addtag", @id, *args
#end
- if args != []
+ if args != [] then
keys = args.pop
- if keys.kind_of?(Hash)
+ if keys.kind_of? Hash then
add(*args) if args != []
configure(keys)
else
diff --git a/ext/tk/lib/tk/textwindow.rb b/ext/tk/lib/tk/textwindow.rb
index 605c40addd..59fafff181 100644
--- a/ext/tk/lib/tk/textwindow.rb
+++ b/ext/tk/lib/tk/textwindow.rb
@@ -5,17 +5,15 @@ require 'tk'
require 'tk/text'
class TkTextWindow<TkObject
- include TkText::IndexModMethods
-
- def initialize(parent, index, keys = {})
+ def initialize(parent, index, keys)
#unless parent.kind_of?(TkText)
- # fail ArgumentError, "expect TkText for 1st argument"
+ # fail ArguemntError, "expect TkText for 1st argument"
#end
@t = parent
- if index == 'end' || index == :end
+ if index == 'end'
@path = TkTextMark.new(@t, tk_call_without_enc(@t.path, 'index',
'end - 1 chars'))
- elsif index.kind_of?(TkTextMark)
+ elsif index.kind_of? TkTextMark
if tk_call_without_enc(@t.path,'index',index.path) == tk_call_without_enc(@t.path,'index','end')
@path = TkTextMark.new(@t, tk_call_without_enc(@t.path, 'index',
'end - 1 chars'))
@@ -34,8 +32,7 @@ class TkTextWindow<TkObject
keys['window'] = _epath(@id) if @id
if keys['create']
@p_create = keys['create']
- # if @p_create.kind_of?(Proc)
- if TkComm._callback_entry?(@p_create)
+ if @p_create.kind_of? Proc
=begin
keys['create'] = install_cmd(proc{
@id = @p_create.call
@@ -51,14 +48,6 @@ class TkTextWindow<TkObject
end
tk_call_without_enc(@t.path, 'window', 'create', @index,
*hash_kv(keys, true))
- @path.gravity = 'right'
- end
-
- def id
- TkText::IndexString.new(_epath(@id))
- end
- def mark
- @path
end
def [](slot)
@@ -74,7 +63,7 @@ class TkTextWindow<TkObject
end
def configure(slot, value=None)
- if slot.kind_of?(Hash)
+ if slot.kind_of? Hash
slot = _symbolkey2str(slot)
if slot['window']
@id = slot['window']
@@ -131,8 +120,7 @@ class TkTextWindow<TkObject
def create=(value)
@p_create = value
- # if @p_create.kind_of?(Proc)
- if TkComm._callback_entry?(@p_create)
+ if @p_create.kind_of? Proc
value = install_cmd(proc{
@id = @p_create.call
if @id.kind_of?(TkWindow)
diff --git a/ext/tk/lib/tk/timer.rb b/ext/tk/lib/tk/timer.rb
index 47f2b79350..f3b6465f78 100644
--- a/ext/tk/lib/tk/timer.rb
+++ b/ext/tk/lib/tk/timer.rb
@@ -122,8 +122,7 @@ class TkTimer
@current_args = args
- # if @sleep_time.kind_of?(Proc)
- if TkComm._callback_entry?(@sleep_time)
+ if @sleep_time.kind_of? Proc
sleep = @sleep_time.call(self)
else
sleep = @sleep_time
@@ -245,28 +244,23 @@ class TkTimer
end
def set_interval(interval)
- #if interval != 'idle' && interval != :idle \
- # && !interval.kind_of?(Integer) && !interval.kind_of?(Proc)
- if interval != 'idle' && interval != :idle \
- && !interval.kind_of?(Integer) && !TkComm._callback_entry?(interval)
- fail ArgumentError, "expect Integer or Proc"
+ if interval != 'idle' \
+ && !interval.kind_of?(Integer) && !interval.kind_of?(Proc)
+ fail ArguemntError, "expect Integer or Proc"
end
@sleep_time = interval
end
def set_procs(interval, loop_exec, *procs)
- #if interval != 'idle' && interval != :idle \
- # && !interval.kind_of?(Integer) && !interval.kind_of?(Proc)
- if interval != 'idle' && interval != :idle \
- && !interval.kind_of?(Integer) && !TkComm._callback_entry?(interval)
- fail ArgumentError, "expect Integer or Proc for 1st argument"
+ if interval != 'idle' \
+ && !interval.kind_of?(Integer) && !interval.kind_of?(Proc)
+ fail ArguemntError, "expect Integer or Proc for 1st argument"
end
@sleep_time = interval
@loop_proc = []
procs.each{|e|
- # if e.kind_of?(Proc)
- if TkComm._callback_entry?(e)
+ if e.kind_of? Proc
@loop_proc.push([e])
else
@loop_proc.push(e)
@@ -283,7 +277,7 @@ class TkTimer
@loop_exec = 0
else
if not loop_exec.kind_of?(Integer)
- fail ArgumentError, "expect Integer for 2nd argument"
+ fail ArguemntError, "expect Integer for 2nd argument"
end
@loop_exec = loop_exec
end
@@ -294,8 +288,7 @@ class TkTimer
def add_procs(*procs)
procs.each{|e|
- # if e.kind_of?(Proc)
- if TkComm._callback_entry?(e)
+ if e.kind_of? Proc
@loop_proc.push([e])
else
@loop_proc.push(e)
@@ -308,8 +301,7 @@ class TkTimer
def delete_procs(*procs)
procs.each{|e|
- # if e.kind_of?(Proc)
- if TkComm._callback_entry?(e)
+ if e.kind_of? Proc
@loop_proc.delete([e])
else
@loop_proc.delete(e)
@@ -333,8 +325,8 @@ class TkTimer
# set parameters for 'restart'
sleep = @init_sleep unless sleep
- if sleep != 'idle' && sleep != :idle && !sleep.kind_of?(Integer)
- fail ArgumentError, "expect Integer or 'idle' for 1st argument"
+ if !sleep == 'idle' && !sleep.kind_of?(Integer)
+ fail ArguemntError, "expect Integer or 'idle' for 1st argument"
end
@init_sleep = sleep
@@ -353,7 +345,6 @@ class TkTimer
Tk_CBTBL[@id] = self
@do_loop = @loop_exec
@current_pos = 0
- @return_value = nil
@after_id = nil
@init_sleep = 0
@@ -363,8 +354,8 @@ class TkTimer
argc = init_args.size
if argc > 0
sleep = init_args.shift
- if sleep != 'idle' && sleep != :idle && !sleep.kind_of?(Integer)
- fail ArgumentError, "expect Integer or 'idle' for 1st argument"
+ if !sleep == 'idle' && !sleep.kind_of?(Integer)
+ fail ArguemntError, "expect Integer or 'idle' for 1st argument"
end
@init_sleep = sleep
end
@@ -377,8 +368,7 @@ class TkTimer
@current_sleep = @init_sleep
@running = true
if @init_proc
- # if not @init_proc.kind_of?(Proc)
- if !TkComm._callback_entry?(@init_proc)
+ if not @init_proc.kind_of? Proc
fail ArgumentError, "Argument '#{@init_proc}' need to be Proc"
end
@current_proc = @init_proc
@@ -402,8 +392,6 @@ class TkTimer
@current_pos = 0
@current_args = @init_args
- @current_script = []
-
@set_next = false if @in_callback
self
@@ -423,7 +411,6 @@ class TkTimer
@wait_var.value = 0
tk_call 'after', 'cancel', @after_id if @after_id
@after_id = nil
-
Tk_CBTBL.delete(@id) ;# for GC
self
end
@@ -431,12 +418,11 @@ class TkTimer
def continue(wait=nil)
fail RuntimeError, "is already running" if @running
- return restart() if @current_script.empty?
sleep, cmd = @current_script
fail RuntimeError, "no procedure to continue" unless cmd
if wait
- unless wait.kind_of?(Integer)
- fail ArgumentError, "expect Integer for 1st argument"
+ unless wait.kind_of? Integer
+ fail ArguemntError, "expect Integer for 1st argument"
end
sleep = wait
end
@@ -502,133 +488,3 @@ class TkTimer
end
TkAfter = TkTimer
-
-
-class TkRTTimer < TkTimer
- DEFAULT_OFFSET_LIST_SIZE = 5
-
- def initialize(*args, &b)
- super(*args, &b)
-
- @offset_list = Array.new(DEFAULT_OFFSET_LIST_SIZE){ [0, 0] }
- @offset_s = 0
- @offset_u = 0
- @est_time = nil
- end
-
- def start(*args, &b)
- return nil if @running
- @est_time = nil
- @cb_start_time = Time.now
- super(*args, &b)
- end
-
- def cancel
- super()
- @est_time = nil
- @cb_start_time = Time.now
- self
- end
- alias stop cancel
-
- def continue(wait=nil)
- fail RuntimeError, "is already running" if @running
- @cb_start_time = Time.now
- super(wait)
- end
-
- def set_interval(interval)
- super(interval)
- @est_time = nil
- end
-
- def _offset_ave
- size = 0
- d_sec = 0; d_usec = 0
- @offset_list.each_with_index{|offset, idx|
- # weight = 1
- weight = idx + 1
- size += weight
- d_sec += offset[0] * weight
- d_usec += offset[1] * weight
- }
- offset_s, mod = d_sec.divmod(size)
- offset_u = ((mod * 1000000 + d_usec) / size.to_f).round
- [offset_s, offset_u]
- end
- private :_offset_ave
-
- def set_next_callback(args)
- if @running == false || @proc_max == 0 || @do_loop == 0
- Tk_CBTBL.delete(@id) ;# for GC
- @running = false
- @wait_var.value = 0
- return
- end
- if @current_pos >= @proc_max
- if @do_loop < 0 || (@do_loop -= 1) > 0
- @current_pos = 0
- else
- Tk_CBTBL.delete(@id) ;# for GC
- @running = false
- @wait_var.value = 0
- return
- end
- end
-
- @current_args = args
-
- cmd, *cmd_args = @loop_proc[@current_pos]
- @current_pos += 1
- @current_proc = cmd
-
- @offset_s, @offset_u = _offset_ave
-
- if TkComm._callback_entry?(@sleep_time)
- sleep = @sleep_time.call(self)
- else
- sleep = @sleep_time
- end
-
- if @est_time
- @est_time = Time.at(@est_time.to_i, @est_time.usec + sleep*1000)
- else
- @est_time = Time.at(@cb_start_time.to_i,
- @cb_start_time.usec + sleep*1000)
- end
-
- now = Time.now
- real_sleep = ((@est_time.to_i - now.to_i + @offset_s)*1000.0 +
- (@est_time.usec - now.usec + @offset_u)/1000.0).round
- if real_sleep <= 0
- real_sleep = 0
- @offset_s = now.to_i
- @offset_u = now.usec
- end
- @current_sleep = real_sleep
-
- set_callback(real_sleep, cmd_args)
- end
-
- def cb_call
- if @est_time
- @offset_list.shift
-
- @cb_start_time = Time.now
-
- if @current_sleep == 0
- @offset_list.push([
- @offset_s - @cb_start_time.to_i,
- @offset_u - @cb_start_time.usec
- ])
- else
- @offset_list.push([
- @offset_s + (@est_time.to_i - @cb_start_time.to_i),
- @offset_u + (@est_time.usec - @cb_start_time.usec)
- ])
- end
- end
-
- @cb_cmd.call
- end
-end
diff --git a/ext/tk/lib/tk/toplevel.rb b/ext/tk/lib/tk/toplevel.rb
index 5e199e1330..b96e184aab 100644
--- a/ext/tk/lib/tk/toplevel.rb
+++ b/ext/tk/lib/tk/toplevel.rb
@@ -45,37 +45,12 @@ class TkToplevel<TkWindow
# end
#################
- def __boolval_optkeys
- super() << 'container'
- end
- private :__boolval_optkeys
-
- def __strval_optkeys
- super() << 'screen'
- end
- private :__strval_optkeys
-
- def __val2ruby_optkeys # { key=>proc, ... }
- super().update('menu'=>proc{|v| window(v)})
- end
- private :__val2ruby_optkeys
-
- def __methodcall_optkeys # { key=>method, ... }
- TOPLEVEL_METHODCALL_OPTKEYS
- end
- private :__methodcall_optkeys
-
def _wm_command_option_chk(keys)
keys = {} unless keys
new_keys = {}
wm_cmds = {}
-
- conf_methods = _symbolkey2str(__methodcall_optkeys())
-
keys.each{|k,v|
- if conf_methods.key?(k)
- wm_cmds[conf_methods[k]] = v
- elsif Wm.method_defined?(k)
+ if Wm.method_defined?(k)
case k
when 'screen','class','colormap','container','use','visual'
new_keys[k] = v
@@ -226,18 +201,18 @@ class TkToplevel<TkWindow
self.database_class.name
end
- def self.bind(*args, &b)
+ def self.bind(*args)
if self == WidgetClassNames[WidgetClassName] || self.name == ''
- super(*args, &b)
+ super(*args)
else
- TkDatabaseClass.new(self.name).bind(*args, &b)
+ TkDatabaseClass.new(self.name).bind(*args)
end
end
- def self.bind_append(*args, &b)
+ def self.bind_append(*args)
if self == WidgetClassNames[WidgetClassName] || self.name == ''
- super(*args, &b)
+ super(*args)
else
- TkDatabaseClass.new(self.name).bind_append(*args, &b)
+ TkDatabaseClass.new(self.name).bind_append(*args)
end
end
def self.bind_remove(*args)
diff --git a/ext/tk/lib/tk/validation.rb b/ext/tk/lib/tk/validation.rb
index 0c5b5c61b9..5a50de456d 100644
--- a/ext/tk/lib/tk/validation.rb
+++ b/ext/tk/lib/tk/validation.rb
@@ -51,8 +51,7 @@ module Tk
if keys[key].kind_of?(Array)
cmd, *args = keys[key]
keys[key] = klass.new(cmd, args.join(' '))
- # elsif keys[key].kind_of?(Proc) || keys[key].kind_of?(Method)
- elsif TkComm._callback_entry?(keys[key])
+ elsif keys[key].kind_of?(Proc) || keys[key].kind_of?(Method)
keys[key] = klass.new(keys[key])
end
}
@@ -152,8 +151,7 @@ module Tk
if keys[key].kind_of?(Array)
cmd, *args = keys[key]
keys[key] = klass.new(cmd, args.join(' '))
- # elsif keys[key].kind_of?(Proc) || keys[key].kind_of?(Method)
- elsif TkComm._callback_entry?(keys[key])
+ elsif keys[key].kind_of?(Proc) || keys[key].kind_of?(Method)
keys[key] = klass.new(keys[key])
end
}
@@ -226,8 +224,7 @@ class TkValidateCommand
[ ?w, TkComm.method(:window) ],
[ ?e, proc{|val|
- #enc = Tk.encoding
- enc = ((Tk.encoding)? Tk.encoding : Tk.encoding_system)
+ enc = Tk.encoding
if enc
Tk.fromUTF8(TkComm::string(val), enc)
else
@@ -337,7 +334,7 @@ module TkValidation
#####################################
def __validation_class_list
- super() << ValidateCmd
+ super << ValidateCmd
end
Tk::ValidateConfigure.__def_validcmd(binding, ValidateCmd)
diff --git a/ext/tk/lib/tk/variable.rb b/ext/tk/lib/tk/variable.rb
index 1ea41b729b..62d4ec29ae 100644
--- a/ext/tk/lib/tk/variable.rb
+++ b/ext/tk/lib/tk/variable.rb
@@ -41,13 +41,13 @@ TkCore::INTERP.add_tk_procs('rb_var', 'args', <<-'EOL')
EOL
#def TkVariable.callback(args)
- def TkVariable.callback(id, name1, name2, op)
+ def TkVariable.callback(name1, name2, op)
#name1,name2,op = tk_split_list(args)
#name1,name2,op = tk_split_simplelist(args)
- if TkVar_CB_TBL[id]
+ if TkVar_CB_TBL[name1]
#_get_eval_string(TkVar_CB_TBL[name1].trace_callback(name2,op))
begin
- _get_eval_string(TkVar_CB_TBL[id].trace_callback(name2, op))
+ _get_eval_string(TkVar_CB_TBL[name1].trace_callback(name2, op))
rescue SystemExit
exit(0)
rescue Interrupt
@@ -109,12 +109,11 @@ TkCore::INTERP.add_tk_procs('rb_var', 'args', <<-'EOL')
end
self
end
- def set_default_value(val)
+ def default_value=(val)
@def_default = :val
@default_val = val
self
end
- alias default_value= set_default_value
def default_proc(cmd = Proc.new)
@def_default = :proc
@default_val = cmd
@@ -127,152 +126,12 @@ TkCore::INTERP.add_tk_procs('rb_var', 'args', <<-'EOL')
self
end
- def default_value_type
- @type
- end
- def default_element_value_type(idxs)
- if idxs.kind_of?(Array)
- index = idxs.collect{|idx| _get_eval_string(idx, true)}.join(',')
- else
- index = _get_eval_string(idxs, true)
- end
- @element_type[index]
- end
-
- def _set_default_value_type_core(type, idxs)
- if type.kind_of?(Class)
- if type == NilClass
- type = nil
- elsif type == Numeric
- type = :numeric
- elsif type == TrueClass || type == FalseClass
- type = :bool
- elsif type == String
- type = :string
- elsif type == Symbol
- type = :symbol
- elsif type == Array
- type = :list
- elsif type <= TkVariable
- type = :variable
- elsif type <= TkWindow
- type = :window
- elsif TkComm._callback_entry_class?(type)
- type = :procedure
- else
- type = nil
- end
- else
- case(type)
- when nil
- type = nil
- when :numeric, 'numeric'
- type = :numeric
- when true, false, :bool, 'bool'
- type = :bool
- when :string, 'string'
- type = :string
- when :symbol, 'symbol'
- type = :symbol
- when :list, 'list'
- type = :list
- when :numlist, 'numlist'
- type = :numlist
- when :variable, 'variable'
- type = :variable
- when :window, 'window'
- type = :window
- when :procedure, 'procedure'
- type = :procedure
- else
- return _set_default_value_type_core(type.class, idxs)
- end
- end
- if idxs
- if idxs.kind_of?(Array)
- index = idxs.collect{|idx| _get_eval_string(idx, true)}.join(',')
- else
- index = _get_eval_string(idxs, true)
- end
- @element_type[index] = type
- else
- @type = type
- end
- type
- end
- private :_set_default_value_type_core
-
- def set_default_value_type(type)
- _set_default_value_type_core(type, nil)
- self
- end
- alias default_value_type= set_default_value_type
-
- def set_default_element_value_type(idxs, type)
- _set_default_value_type_core(type, idxs)
- self
- end
-
- def _to_default_type(val, idxs = nil)
- if idxs
- if idxs.kind_of?(Array)
- index = idxs.collect{|idx| _get_eval_string(idx, true)}.join(',')
- else
- index = _get_eval_string(idxs, true)
- end
- type = @element_type[index]
- else
- type = @type
- end
- return val unless type
- if val.kind_of?(Hash)
- val.keys.each{|k| val[k] = _to_default_type(val[k], idxs) }
- val
- else
- begin
- case(type)
- when :numeric
- number(val)
- when :bool
- TkComm.bool(val)
- when :string
- val
- when :symbol
- val.intern
- when :list
- tk_split_simplelist(val)
- when :numlist
- tk_split_simplelist(val).collect!{|v| number(v)}
- when :variable
- TkVarAccess.new(val)
- when :window
- TkComm.window(val)
- when :procedure
- TkComm.procedure(val)
- else
- val
- end
- rescue
- val
- end
- end
- end
- private :_to_default_type
-
- def _to_default_element_type(idxs, val)
- _to_default_type(val, idxs)
- end
- private :_to_default_element_type
-
- def initialize(val="", type=nil)
+ def initialize(val="")
# @id = Tk_VARIABLE_ID.join('')
@id = Tk_VARIABLE_ID.join(TkCore::INTERP._ip_id_)
Tk_VARIABLE_ID[1].succ!
TkVar_ID_TBL[@id] = self
- @var = @id
- @elem = nil
-
@def_default = false
@default_val = nil
@@ -280,12 +139,6 @@ TkCore::INTERP.add_tk_procs('rb_var', 'args', <<-'EOL')
@trace_elem = nil
@trace_opts = nil
- @type = nil
- var = self
- @element_type = Hash.new{|k,v| var.default_value_type }
-
- self.default_value_type = type
-
begin
INTERP._unset_global_var(@id)
rescue
@@ -389,40 +242,20 @@ TkCore::INTERP.add_tk_procs('rb_var', 'args', <<-'EOL')
def is_hash?
#ITNERP._eval("global #{@id}; array exist #{@id}") == '1'
INTERP._invoke_without_enc('global', @id)
- # INTERP._invoke_without_enc('array', 'exist', @id) == '1'
- TkComm.bool(INTERP._invoke_without_enc('array', 'exist', @id))
+ INTERP._invoke_without_enc('array', 'exist', @id) == '1'
end
def is_scalar?
! is_hash?
end
- def exist?(*elems)
- INTERP._invoke_without_enc('global', @id)
- if elems.empty?
- TkComm.bool(tk_call('info', 'exist', @id))
- else
- # array
- index = elems.collect{|idx| _get_eval_string(idx, true)}.join(',')
- TkComm.bool(tk_call('info', 'exist', "#{@id}")) &&
- TkComm.bool(tk_call('info', 'exist', "#{@id}(#{index})"))
- end
- end
-
def keys
if (is_scalar?)
fail RuntimeError, 'cannot get keys from a scalar variable'
end
#tk_split_simplelist(INTERP._eval("global #{@id}; array get #{@id}"))
INTERP._invoke_without_enc('global', @id)
- #tk_split_simplelist(INTERP._fromUTF8(INTERP._invoke_without_enc('array', 'names', @id)))
- tk_split_simplelist(INTERP._invoke_without_enc('array', 'names', @id),
- false, true)
- end
-
- def size
- INTERP._invoke_without_enc('global', @id)
- TkComm.number(INTERP._invoke_without_enc('array', 'size', @id))
+ tk_split_simplelist(INTERP._fromUTF8(INTERP._invoke_without_enc('array', 'names', @id)))
end
def clear
@@ -441,6 +274,7 @@ TkCore::INTERP.add_tk_procs('rb_var', 'args', <<-'EOL')
self
end
+
unless const_defined?(:USE_TCLs_SET_VARIABLE_FUNCTIONS)
USE_TCLs_SET_VARIABLE_FUNCTIONS = true
end
@@ -450,11 +284,10 @@ if USE_TCLs_SET_VARIABLE_FUNCTIONS
# use Tcl function version of set tkvariable
###########################################################################
- def _value
+ def value
#if INTERP._eval("global #{@id}; array exist #{@id}") == '1'
INTERP._invoke_without_enc('global', @id)
- # if INTERP._invoke('array', 'exist', @id) == '1'
- if TkComm.bool(INTERP._invoke('array', 'exist', @id))
+ if INTERP._invoke('array', 'exist', @id) == '1'
#Hash[*tk_split_simplelist(INTERP._eval("global #{@id}; array get #{@id}"))]
Hash[*tk_split_simplelist(INTERP._invoke('array', 'get', @id))]
else
@@ -463,7 +296,6 @@ if USE_TCLs_SET_VARIABLE_FUNCTIONS
end
def value=(val)
- val = val._value if !@type && @type != :variable && val.kind_of?(TkVariable)
if val.kind_of?(Hash)
self.clear
val.each{|k, v|
@@ -473,8 +305,7 @@ if USE_TCLs_SET_VARIABLE_FUNCTIONS
_get_eval_string(v, true))
}
self.value
-# elsif val.kind_of?(Array)
-=begin
+ elsif val.kind_of?(Array)
INTERP._set_global_var(@id, '')
val.each{|v|
#INTERP._set_variable(@id, _toUTF8(_get_eval_string(v)),
@@ -485,15 +316,13 @@ if USE_TCLs_SET_VARIABLE_FUNCTIONS
TclTkLib::VarAccessFlag::LIST_ELEMENT)
}
self.value
-=end
-# _fromUTF8(INTERP._set_global_var(@id, array2tk_list(val, true)))
else
#_fromUTF8(INTERP._set_global_var(@id, _toUTF8(_get_eval_string(val))))
_fromUTF8(INTERP._set_global_var(@id, _get_eval_string(val, true)))
end
end
- def _element_value(*idxs)
+ def [](*idxs)
index = idxs.collect{|idx| _get_eval_string(idx, true)}.join(',')
begin
_fromUTF8(INTERP._get_global_var2(@id, index))
@@ -514,8 +343,6 @@ if USE_TCLs_SET_VARIABLE_FUNCTIONS
def []=(*args)
val = args.pop
- type = default_element_value_type(args)
- val = val._value if !type && type != :variable && val.kind_of?(TkVariable)
index = args.collect{|idx| _get_eval_string(idx, true)}.join(',')
_fromUTF8(INTERP._set_global_var2(@id, index, _get_eval_string(val, true)))
#_fromUTF8(INTERP._set_global_var2(@id, _toUTF8(_get_eval_string(index)),
@@ -524,12 +351,11 @@ if USE_TCLs_SET_VARIABLE_FUNCTIONS
# _get_eval_string(val, true)))
end
- def unset(*elems)
- if elems.empty?
- INTERP._unset_global_var(@id)
+ def unset(elem=nil)
+ if elem
+ INTERP._unset_global_var2(@id, _get_eval_string(elem, true))
else
- index = elems.collect{|idx| _get_eval_string(idx, true)}.join(',')
- INTERP._unset_global_var2(@id, index)
+ INTERP._unset_global_var(@id)
end
end
alias remove unset
@@ -539,7 +365,7 @@ else
# use Ruby script version of set tkvariable (traditional methods)
###########################################################################
- def _value
+ def value
begin
INTERP._eval(Kernel.format('global %s; set %s', @id, @id))
#INTERP._eval(Kernel.format('set %s', @id))
@@ -558,7 +384,6 @@ else
end
def value=(val)
- val = val._value if !@type && @type != :variable && val.kind_of?(TkVariable)
begin
#s = '"' + _get_eval_string(val).gsub(/[\[\]$"]/, '\\\\\&') + '"'
s = '"' + _get_eval_string(val).gsub(/[\[\]$"\\]/, '\\\\\&') + '"'
@@ -581,7 +406,7 @@ else
#INTERP._invoke_without_enc('unset', @id+'(0)')
elsif val.kind_of?(Array)
a = []
- val.each_with_index{|e,i| a.push(i); a.push(array2tk_list(e, true))}
+ val.each_with_index{|e,i| a.push(i); a.push(array2tk_list(e))}
#s = '"' + a.join(" ").gsub(/[\[\]$"]/, '\\\\\&') + '"'
s = '"' + a.join(" ").gsub(/[\[\]$"\\]/, '\\\\\&') + '"'
INTERP._eval(Kernel.format('global %s; unset %s; array set %s %s',
@@ -593,7 +418,7 @@ else
elsif val.kind_of?(Hash)
#s = '"' + val.to_a.collect{|e| array2tk_list(e)}.join(" ")\
# .gsub(/[\[\]$"]/, '\\\\\&') + '"'
- s = '"' + val.to_a.collect{|e| array2tk_list(e, true)}.join(" ")\
+ s = '"' + val.to_a.collect{|e| array2tk_list(e)}.join(" ")\
.gsub(/[\[\]$\\"]/, '\\\\\&') + '"'
INTERP._eval(Kernel.format('global %s; unset %s; array set %s %s',
@id, @id, @id, s))
@@ -608,7 +433,7 @@ else
end
end
- def _element_value(*idxs)
+ def [](*idxs)
index = idxs.collect{|idx| _get_eval_string(idx)}.join(',')
begin
INTERP._eval(Kernel.format('global %s; set %s(%s)', @id, @id, index))
@@ -631,8 +456,6 @@ else
def []=(*args)
val = args.pop
- type = default_element_value_type(args)
- val = val._value if !type && type != :variable && val.kind_of?(TkVariable)
index = args.collect{|idx| _get_eval_string(idx)}.join(',')
INTERP._eval(Kernel.format('global %s; set %s(%s) %s', @id, @id,
index, _get_eval_string(val)))
@@ -644,73 +467,26 @@ else
# _get_eval_string(val))
end
- def unset(*elems)
- if elems.empty?
+ def unset(elem=nil)
+ if elem
+ INTERP._eval(Kernel.format('global %s; unset %s(%s)',
+ @id, @id, _get_eval_string(elem)))
+ #INTERP._eval(Kernel.format('unset %s(%s)', @id, tk_tcl2ruby(elem)))
+ #INTERP._eval('unset ' + @id + '(' + _get_eval_string(elem) + ')')
+ else
INTERP._eval(Kernel.format('global %s; unset %s', @id, @id))
#INTERP._eval(Kernel.format('unset %s', @id))
#INTERP._eval('unset ' + @id)
- else
- index = elems.collect{|idx| _get_eval_string(idx, true)}.join(',')
- INTERP._eval(Kernel.format('global %s; unset %s(%s)', @id, @id, index))
- #INTERP._eval(Kernel.format('global %s; unset %s(%s)',
- # @id, @id, _get_eval_string(elem)))
- #INTERP._eval(Kernel.format('unset %s(%s)', @id, tk_tcl2ruby(elem)))
- #INTERP._eval('unset ' + @id + '(' + _get_eval_string(elem) + ')')
end
end
alias remove unset
end
- protected :_value, :_element_value
-
- def value
- _to_default_type(_value)
- end
-
- def [](*idxs)
- _to_default_element_type(idxs, _element_value(*idxs))
- end
-
- def set_value(val)
- self.value = val
- self
- end
-
- def set_element_value(idxs, val)
- if idxs.kind_of?(Array)
- self[*idxs]=val
- else
- self[idxs]=val
- end
- self
- end
-
- def set_value_type(val)
- self.default_value_type = val.class
- self.value = val
- self
- end
-
- alias value_type= set_value_type
-
- def set_element_value_type(idxs, val)
- self.set_default_element_value_type(idxs, val.class)
- if idxs.kind_of?(Array)
- self[*idxs]=val
- else
- self[idxs]=val
- end
- self
- end
-
def numeric
- number(_value)
+ number(value)
end
- def numeric_element(*idxs)
- number(_element_value(*idxs))
- end
- def set_numeric(val)
+ def numeric=(val)
case val
when Numeric
self.value=(val)
@@ -719,52 +495,20 @@ end
else
raise ArgumentError, "Numeric is expected"
end
- self
- end
- alias numeric= set_numeric
- def set_numeric_element(idxs, val)
- case val
- when Numeric
- val
- when TkVariable
- val = val.numeric
- else
- raise ArgumentError, "Numeric is expected"
- end
- if idxs.kind_of?(Array)
- self[*idxs]=val
- else
- self[idxs]=val
- end
- self
- end
- def set_numeric_type(val)
- @type = :numeric
- self.numeric=(val)
- self
- end
- alias numeric_type= set_numeric_type
- def set_numeric_element_type(idxs, val)
- self.set_default_element_value_type(idxs, :numeric)
- self.set_numeric_element(idxs, val)
+ val
end
def bool
- TkComm.bool(_value)
-=begin
# see Tcl_GetBoolean man-page
- case _value.downcase
+ case value.downcase
when '0', 'false', 'no', 'off'
false
else
true
end
-=end
end
- def bool_element(*idxs)
- TkComm.bool(_element_value(*idxs))
- end
- def set_bool(val)
+
+ def bool=(val)
if ! val
self.value = '0'
else
@@ -775,238 +519,32 @@ end
self.value = '1'
end
end
- self
- end
- alias bool= set_bool
- def set_bool_element(idxs, val)
- if ! val
- val = '0'
- else
- case val.to_s.downcase
- when 'false', '0', 'no', 'off'
- val = '0'
- else
- val = '1'
- end
- end
- if idxs.kind_of?(Array)
- self[*idxs]=val
- else
- self[idxs]=val
- end
- self
- end
- def set_bool_type(val)
- @type = :bool
- self.bool=(val)
- self
- end
- alias bool_type= set_bool_type
- def set_bool_element_type(idxs, val)
- self.set_default_element_value_type(idxs, :bool)
- self.set_bool_element(idxs, val)
- end
-
- def variable
- # keeps a Tcl's variable name
- TkVarAccess.new(self._value)
- end
- def variable_element(*idxs)
- TkVarAccess.new(_element_value(*idxs))
- end
- def set_variable(var)
- var = var.id if var.kind_of?(TkVariable)
- self.value = var
- self
- end
- alias variable= set_variable
- def set_variable_element(idxs, var)
- var = var.id if var.kind_of?(TkVariable)
- if idxs.kind_of?(Array)
- self[*idxs]=var
- else
- self[idxs]=var
- end
- self
- end
- def set_variable_type(var)
- @type = :variable
- var = var.id if var.kind_of?(TkVariable)
- self.value = var
- self
- end
- alias variable_type= set_variable_type
- def set_variable_element_type(idxs, var)
- self.set_default_element_value_type(idxs, :variable)
- self.set_variable_element(idxs, var)
- end
-
- def window
- TkComm.window(self._value)
- end
- def window_element(*idxs)
- TkComm.window(_element_value(*idxs))
- end
- def set_window(win)
- win = win._value if win.kind_of?(TkVariable)
- self.value = win
- self
- end
- alias window= set_window
- def set_window_element(idxs, win)
- win = win._value if win.kind_of?(TkVariable)
- if idxs.kind_of?(Array)
- self[*idxs]=win
- else
- self[idxs]=win
- end
- self
- end
- def set_window_type(win)
- @type = :window
- self.window=(win)
- self
- end
- alias window_type= set_window_type
- def set_window_element_type(idxs, win)
- self.set_default_element_value_type(idxs, :window)
- self.set_window_element(idxs, win)
- end
-
- def procedure
- TkComm.procedure(self._value)
- end
- def procedure_element(*idxs)
- TkComm.procedure(_element_value(*idxs))
- end
- def set_procedure(cmd)
- self.value = cmd
- self
- end
- alias procedure= set_procedure
- def set_procedure_element(idxs, cmd)
- cmd = cmd._value if cmd.kind_of?(TkVariable)
- if idxs.kind_of?(Array)
- self[*idxs]=cmd
- else
- self[idxs]=cmd
- end
- self
- end
- def set_procedure_type(cmd)
- @type = :procedure
- self.procedure=(cmd)
- self
- end
- alias procedure_type= set_procedure_type
- def set_procedure_element_type(idxs, cmd)
- self.set_default_element_value_type(idxs, :procedure)
- self.set_proceure_element(idxs, cmd)
end
def to_i
- number(_value).to_i
- end
- def element_to_i(*idxs)
- number(_element_value(*idxs)).to_i
+ number(value).to_i
end
def to_f
- number(_value).to_f
- end
- def element_to_f(*idxs)
- number(_element_value(*idxs)).to_f
+ number(value).to_f
end
def to_s
#string(value).to_s
- _value
- end
- alias string to_s
- def element_to_s(*idxs)
- _element_value(*idxs)
- end
- def string_element(*idxs)
- _element_value(*idxs)
- end
- def set_string(val)
- val = val._value if val.kind_of?(TkVariable)
- self.value=val
- self
- end
- alias string= set_string
- def set_string_element(idxs, val)
- val = val._value if val.kind_of?(TkVariable)
- if idxs.kind_of?(Array)
- self[*idxs]=val
- else
- self[idxs]=val
- end
- self
- end
- def set_string_type(val)
- @type = :string
- self.string=(val)
- self
- end
- alias string_type= set_string_type
- def set_string_element_type(idxs, val)
- self.set_default_element_value_type(idxs, :string)
- self.set_string_element(idxs, val)
+ value
end
def to_sym
- _value.intern
- end
- alias symbol to_sym
- def element_to_sym(*idxs)
- _element_value(*idxs).intern
- end
- alias symbol_element element_to_sym
- def set_symbol(val)
- val = val._value if val.kind_of?(TkVariable)
- self.value=val
- self
- end
- alias symbol= set_symbol
- def set_symbol_element(idxs, val)
- val = val._value if val.kind_of?(TkVariable)
- if idxs.kind_of?(Array)
- self[*idxs]=val
- else
- self[idxs]=val
- end
- self
- end
- def set_symbol_type(val)
- @type = :symbol
- self.value=(val)
- self
- end
- alias symbol_type= set_symbol_type
- def set_symbol_element_type(idxs, val)
- self.set_default_element_value_type(idxs, :symbol)
- self.set_symbol_element(idxs, val)
+ value.intern
end
def list
#tk_split_list(value)
- tk_split_simplelist(_value)
+ tk_split_simplelist(value)
end
alias to_a list
- def list_element(*idxs)
- tk_split_simplelist(_element_value(*idxs))
- end
- alias element_to_a list_element
-
- def numlist
- list.collect!{|val| number(val)}
- end
- def numlist_element(*idxs)
- list_element(*idxs).collect!{|val| number(val)}
- end
- def set_list(val)
+ def list=(val)
case val
when Array
self.value=(val)
@@ -1015,102 +553,7 @@ end
else
raise ArgumentError, "Array is expected"
end
- self
- end
- alias list= set_list
-
- alias set_numlist set_list
- alias numlist= set_numlist
-
- def set_list_element(idxs, val)
- case val
- when Array
- val
- when TkVariable
- val = val.list
- else
- raise ArgumentError, "Array is expected"
- end
- if idxs.kind_of?(Array)
- self[*idxs]=val
- else
- self[idxs]=val
- end
- self
- end
- alias set_numlist_element set_list_element
-
- def set_list_type(val)
- @type = :list
- self.list=(val)
- self
- end
- alias list_type= set_list_type
- def set_list_element_type(idxs, val)
- self.set_default_element_value_type(idxs, :list)
- self.set_list_element(idxs, val)
- end
- def set_numlist_type(val)
- @type = :numlist
- self.numlist=(val)
- self
- end
- alias numlist_type= set_numlist_type
- def set_numlist_element_type(idxs, val)
- self.set_default_element_value_type(idxs, :numlist)
- self.set_numlist_element(idxs, val)
- end
-
- def lappend(*elems)
- tk_call('lappend', @id, *elems)
- self
- end
- def element_lappend(idxs, *elems)
- if idxs.kind_of?(Array)
- idxs = idxs.collect{|idx| _get_eval_string(idx, true)}.join(',')
- end
- tk_call('lappend', "#{@id}(#{idxs})", *elems)
- self
- end
-
- def lindex(idx)
- tk_call('lindex', self._value, idx)
- end
- alias lget lindex
- def element_lindex(elem_idxs, idx)
- if elem_idxs.kind_of?(Array)
- val = _element_value(*elem_idxs)
- else
- val = _element_value(elem_idxs)
- end
- tk_call('lindex', val, idx)
- end
- alias element_lget element_lindex
-
- def lget_i(idx)
- number(lget(idx)).to_i
- end
- def element_lget_i(elem_idxs, idx)
- number(element_lget(elem_idxs, idx)).to_i
- end
-
- def lget_f(idx)
- number(lget(idx)).to_f
- end
- def element_lget_f(elem_idxs, idx)
- number(element_lget(elem_idxs, idx)).to_f
- end
-
- def lset(idx, val)
- tk_call('lset', @id, idx, val)
- self
- end
- def element_lset(elem_idxs, idx, val)
- if elem_idxs.kind_of?(Array)
- idxs = elem_idxs.collect{|i| _get_eval_string(i, true)}.join(',')
- end
- tk_call('lset', "#{@id}(#{idxs})", idx, val)
- self
+ val
end
def inspect
@@ -1121,7 +564,7 @@ end
def coerce(other)
case other
when TkVariable
- [other._value, self._value]
+ [other.value, self.value]
when String
[other, self.to_s]
when Symbol
@@ -1133,7 +576,7 @@ end
when Array
[other, self.to_a]
else
- [other, self._value]
+ [other, self.value]
end
end
@@ -1156,12 +599,12 @@ end
when Array
self.to_a + other
when String
- self._value + other
+ self.value + other
else
begin
- number(self._value) + other
+ number(self.value) + other
rescue
- self._value + other.to_s
+ self.value + other.to_s
end
end
end
@@ -1169,40 +612,37 @@ end
if other.kind_of?(Array)
self.to_a - other
else
- number(self._value) - other
+ number(self.value) - other
end
end
def *(other)
- num_or_str(self._value) * other.to_i
- #begin
- # number(self._value) * other
- #rescue
- # self._value * other
- #end
+ begin
+ number(self.value) * other
+ rescue
+ self.value * other
+ end
end
def /(other)
- number(self._value) / other
+ number(self.value) / other
end
def %(other)
- num_or_str(self._value) % other.to_i
- #begin
- # number(self._value) % other
- #rescue
- # self._value % other
- #end
+ begin
+ number(self.value) % other
+ rescue
+ self.value % other
+ end
end
def **(other)
- number(self._value) ** other
+ number(self.value) ** other
end
def =~(other)
- self._value =~ other
+ self.value =~ other
end
def ==(other)
case other
when TkVariable
- #self.equal?(other)
- self._value == other._value
+ self.equal?(other)
when String
self.to_s == other
when Symbol
@@ -1214,11 +654,9 @@ end
when Array
self.to_a == other
when Hash
- # false if self is not an assoc array
- self._value == other
+ self.value == other
else
- # false
- self._value == _get_eval_string(other)
+ false
end
end
@@ -1235,18 +673,17 @@ end
val = other.numeric
other = val
rescue
- other = other._value
+ other = other.value
end
- elsif other.kind_of?(Numeric)
+ end
+ if other.kind_of?(Numeric)
begin
return self.numeric <=> other
rescue
- return self._value <=> other.to_s
+ return self.value <=> other.to_s
end
- elsif other.kind_of?(Array)
- return self.list <=> other
else
- return self._value <=> other
+ return self.value <=> other
end
end
@@ -1268,14 +705,12 @@ end
def trace(opts, cmd = Proc.new)
@trace_var = [] if @trace_var == nil
#opts = ['r','w','u'].find_all{|c| opts.index(c)}.join('')
- opts = opts.to_s
- opts = ['r','w','u'].find_all{|c| opts.index(c)}.join('')
+ opts = ['r','w','u'].find_all{|c| opts.to_s.index(c)}.join('')
@trace_var.unshift([opts,cmd])
if @trace_opts == nil
TkVar_CB_TBL[@id] = self
@trace_opts = opts.dup
- Tk.tk_call_without_enc('trace', 'variable', @id, @trace_opts,
- 'rb_var ' << @id)
+ Tk.tk_call_without_enc('trace', 'variable', @id, @trace_opts, 'rb_var')
=begin
if /^(8\.([4-9]|[1-9][0-9])|9\.|[1-9][0-9])/ =~ Tk::TCL_VERSION
# TCL_VERSION >= 8.4
@@ -1291,11 +726,9 @@ end
#opts.each_byte{|c| newopts += c.chr unless newopts.index(c)}
opts.each_byte{|c| newopts.concat(c.chr) unless newopts.index(c)}
if newopts != @trace_opts
- Tk.tk_call_without_enc('trace', 'vdelete', @id, @trace_opts,
- 'rb_var ' << @id)
+ Tk.tk_call_without_enc('trace', 'vdelete', @id, @trace_opts, 'rb_var')
@trace_opts.replace(newopts)
- Tk.tk_call_without_enc('trace', 'variable', @id, @trace_opts,
- 'rb_var ' << @id)
+ Tk.tk_call_without_enc('trace', 'variable', @id, @trace_opts, 'rb_var')
=begin
if /^(8\.([4-9]|[1-9][0-9])|9\.|[1-9][0-9])/ =~ Tk::TCL_VERSION
# TCL_VERSION >= 8.4
@@ -1319,20 +752,15 @@ end
end
def trace_element(elem, opts, cmd = Proc.new)
- if @elem
- fail(RuntimeError,
- "invalid for a TkVariable which denotes an element of Tcl's array")
- end
@trace_elem = {} if @trace_elem == nil
@trace_elem[elem] = [] if @trace_elem[elem] == nil
- opts = opts.to_s
- opts = ['r','w','u'].find_all{|c| opts.index(c)}.join('')
+ #opts = ['r','w','u'].find_all{|c| opts.index(c)}.join('')
+ opts = ['r','w','u'].find_all{|c| opts.to_s.index(c)}.join('')
@trace_elem[elem].unshift([opts,cmd])
if @trace_opts == nil
TkVar_CB_TBL[@id] = self
@trace_opts = opts.dup
- Tk.tk_call_without_enc('trace', 'variable', @id, @trace_opts,
- 'rb_var ' << @id)
+ Tk.tk_call_without_enc('trace', 'variable', @id, @trace_opts, 'rb_var')
=begin
if /^(8\.([4-9]|[1-9][0-9])|9\.|[1-9][0-9])/ =~ Tk::TCL_VERSION
# TCL_VERSION >= 8.4
@@ -1349,11 +777,9 @@ end
# opts.each_byte{|c| newopts += c.chr unless newopts.index(c)}
opts.each_byte{|c| newopts.concat(c.chr) unless newopts.index(c)}
if newopts != @trace_opts
- Tk.tk_call_without_enc('trace', 'vdelete', @id, @trace_opts,
- 'rb_var ' << @id)
+ Tk.tk_call_without_enc('trace', 'vdelete', @id, @trace_opts, 'rb_var')
@trace_opts.replace(newopts)
- Tk.tk_call_without_enc('trace', 'variable', @id, @trace_opts,
- 'rb_var ' << @id)
+ Tk.tk_call_without_enc('trace', 'variable', @id, @trace_opts, 'rb_var')
=begin
if /^(8\.([4-9]|[1-9][0-9])|9\.|[1-9][0-9])/ =~ Tk::TCL_VERSION
# TCL_VERSION >= 8.4
@@ -1380,12 +806,7 @@ end
return [] unless @trace_var
@trace_var.dup
end
-
- def _trace_vinfo_for_element(elem)
- if @elem
- fail(RuntimeError,
- "invalid for a TkVariable which denotes an element of Tcl's array")
- end
+ def trace_vinfo_for_element(elem)
return [] unless @trace_elem
return [] unless @trace_elem[elem]
@trace_elem[elem].dup
@@ -1393,8 +814,8 @@ end
def trace_vdelete(opts,cmd)
return self unless @trace_var.kind_of? Array
- opts = opts.to_s
- opts = ['r','w','u'].find_all{|c| opts.index(c)}.join('')
+ #opts = ['r','w','u'].find_all{|c| opts.index(c)}.join('')
+ opts = ['r','w','u'].find_all{|c| opts.to_s.index(c)}.join('')
idx = -1
newopts = ''
@trace_var.each_with_index{|e,i|
@@ -1418,11 +839,10 @@ end
}
}
- newopts = newopts.to_s
- newopts = ['r','w','u'].find_all{|c| newopts.index(c)}.join('')
+ #newopts = ['r','w','u'].find_all{|c| newopts.index(c)}.join('')
+ newopts = ['r','w','u'].find_all{|c| newopts.to_s.index(c)}.join('')
if newopts != @trace_opts
- Tk.tk_call_without_enc('trace', 'vdelete', @id, @trace_opts,
- 'rb_var ' << @id)
+ Tk.tk_call_without_enc('trace', 'vdelete', @id, @trace_opts, 'rb_var')
=begin
if /^(8\.([4-9]|[1-9][0-9])|9\.|[1-9][0-9])/ =~ Tk::TCL_VERSION
# TCL_VERSION >= 8.4
@@ -1436,8 +856,7 @@ end
=end
@trace_opts.replace(newopts)
if @trace_opts != ''
- Tk.tk_call_without_enc('trace', 'variable', @id, @trace_opts,
- 'rb_var ' << @id)
+ Tk.tk_call_without_enc('trace', 'variable', @id, @trace_opts, 'rb_var')
=begin
if /^(8\.([4-9]|[1-9][0-9])|9\.|[1-9][0-9])/ =~ Tk::TCL_VERSION
# TCL_VERSION >= 8.4
@@ -1456,14 +875,10 @@ end
end
def trace_vdelete_for_element(elem,opts,cmd)
- if @elem
- fail(RuntimeError,
- "invalid for a TkVariable which denotes an element of Tcl's array")
- end
return self unless @trace_elem.kind_of? Hash
return self unless @trace_elem[elem].kind_of? Array
- opts = opts.to_s
- opts = ['r','w','u'].find_all{|c| opts.index(c)}.join('')
+ # opts = ['r','w','u'].find_all{|c| opts.index(c)}.join('')
+ opts = ['r','w','u'].find_all{|c| opts.to_s.index(c)}.join('')
idx = -1
@trace_elem[elem].each_with_index{|e,i|
if idx < 0 && e[0] == opts && e[1] == cmd
@@ -1489,11 +904,10 @@ end
}
}
- newopts = newopts.to_s
- newopts = ['r','w','u'].find_all{|c| newopts.index(c)}.join('')
+ #newopts = ['r','w','u'].find_all{|c| newopts.index(c)}.join('')
+ newopts = ['r','w','u'].find_all{|c| newopts.to_s.index(c)}.join('')
if newopts != @trace_opts
- Tk.tk_call_without_enc('trace', 'vdelete', @id, @trace_opts,
- 'rb_var ' << @id)
+ Tk.tk_call_without_enc('trace', 'vdelete', @id, @trace_opts, 'rb_var')
=begin
if /^(8\.([4-9]|[1-9][0-9])|9\.|[1-9][0-9])/ =~ Tk::TCL_VERSION
# TCL_VERSION >= 8.4
@@ -1507,8 +921,7 @@ end
=end
@trace_opts.replace(newopts)
if @trace_opts != ''
- Tk.tk_call_without_enc('trace', 'variable', @id, @trace_opts,
- 'rb_var ' << @id)
+ Tk.tk_call_without_enc('trace', 'variable', @id, @trace_opts, 'rb_var')
=begin
if /^(8\.([4-9]|[1-9][0-9])|9\.|[1-9][0-9])/ =~ Tk::TCL_VERSION
# TCL_VERSION >= 8.4
@@ -1527,38 +940,15 @@ end
end
end
+
class TkVarAccess<TkVariable
def self.new(name, *args)
- if name.kind_of?(TkVariable)
- name.value = args[0] unless args.empty?
- return name
- end
-
- if v = TkVar_ID_TBL[name]
- v.value = args[0] unless args.empty?
- return v
- end
-
+ return TkVar_ID_TBL[name] if TkVar_ID_TBL[name]
super(name, *args)
end
def self.new_hash(name, *args)
- if name.kind_of?(TkVariable)
- unless name.is_hash?
- fail ArgumentError, "already exist as a scalar variable"
- end
- name.value = args[0] unless args.empty?
- return name
- end
-
- if v = TkVar_ID_TBL[name]
- unless v.is_hash?
- fail ArgumentError, "already exist as a scalar variable"
- end
- v.value = args[0] unless args.empty?
- return v
- end
-
+ return TkVar_ID_TBL[name] if TkVar_ID_TBL[name]
INTERP._invoke_without_enc('global', name)
if args.empty? && INTERP._invoke_without_enc('array', 'exist', name) == '0'
self.new(name, {}) # force creating
@@ -1571,9 +961,6 @@ class TkVarAccess<TkVariable
@id = varname
TkVar_ID_TBL[@id] = self
- @var = @id
- @elem = nil
-
@def_default = false
@default_val = nil
@@ -1581,31 +968,8 @@ class TkVarAccess<TkVariable
@trace_elem = nil
@trace_opts = nil
- @type = nil
- var = self
- @element_type = Hash.new{|k,v| var.default_value_type }
-
- # is an element?
- if @id =~ /^([^(]+)\((.+)\)$/
- # is an element --> var == $1, elem == $2
- @var = $1
- @elem = $2
- end
-
# teach Tk-ip that @id is global var
- INTERP._invoke_without_enc('global', @var)
-=begin
- begin
- INTERP._invoke_without_enc('global', @id)
- rescue => e
- if @id =~ /^(.+)\([^()]+\)$/
- # is an element --> varname == $1
- INTERP._invoke_without_enc('global', $1)
- else
- fail e
- end
- end
-=end
+ INTERP._invoke_without_enc('global', @id)
if val
if val.kind_of?(Hash)
@@ -1622,15 +986,14 @@ class TkVarAccess<TkVariable
end
end
+
module Tk
begin
- INTERP._invoke_without_enc('global', 'auto_path')
auto_path = INTERP._invoke('set', 'auto_path')
- rescue => e
+ rescue
begin
- INTERP._invoke_without_enc('global', 'env')
auto_path = INTERP._invoke('set', 'env(TCLLIBPATH)')
- rescue => e
+ rescue
auto_path = Tk::LIBRARY
end
end
diff --git a/ext/tk/lib/tk/virtevent.rb b/ext/tk/lib/tk/virtevent.rb
index a1a94d3c55..c82cfe46e8 100644
--- a/ext/tk/lib/tk/virtevent.rb
+++ b/ext/tk/lib/tk/virtevent.rb
@@ -15,10 +15,9 @@ class TkVirtualEvent<TkObject
TkCore::INTERP.init_ip_env{ TkVirtualEventTBL.clear }
class PreDefVirtEvent<self
- def initialize(event, *sequences)
+ def initialize(event)
@path = @id = event
TkVirtualEvent::TkVirtualEventTBL[@id] = self
- add(*sequences)
end
end
diff --git a/ext/tk/lib/tk/winfo.rb b/ext/tk/lib/tk/winfo.rb
index c649b4a0c9..948042558d 100644
--- a/ext/tk/lib/tk/winfo.rb
+++ b/ext/tk/lib/tk/winfo.rb
@@ -36,30 +36,30 @@ module TkWinfo
TkWinfo.atomname(id, self)
end
- def TkWinfo.cells(win)
- number(tk_call_without_enc('winfo', 'cells', win))
+ def TkWinfo.cells(window)
+ number(tk_call_without_enc('winfo', 'cells', window))
end
def winfo_cells
TkWinfo.cells self
end
- def TkWinfo.children(win)
- list(tk_call_without_enc('winfo', 'children', win))
+ def TkWinfo.children(window)
+ list(tk_call_without_enc('winfo', 'children', window))
end
def winfo_children
TkWinfo.children self
end
- def TkWinfo.classname(win)
- tk_call_without_enc('winfo', 'class', win)
+ def TkWinfo.classname(window)
+ tk_call_without_enc('winfo', 'class', window)
end
def winfo_classname
TkWinfo.classname self
end
alias winfo_class winfo_classname
- def TkWinfo.colormapfull(win)
- bool(tk_call_without_enc('winfo', 'colormapfull', win))
+ def TkWinfo.colormapfull(window)
+ bool(tk_call_without_enc('winfo', 'colormapfull', window))
end
def winfo_colormapfull
TkWinfo.colormapfull self
@@ -77,88 +77,83 @@ module TkWinfo
TkWinfo.containing(x, y, self)
end
- def TkWinfo.depth(win)
- number(tk_call_without_enc('winfo', 'depth', win))
+ def TkWinfo.depth(window)
+ number(tk_call_without_enc('winfo', 'depth', window))
end
def winfo_depth
TkWinfo.depth self
end
- def TkWinfo.exist?(win)
- bool(tk_call_without_enc('winfo', 'exists', win))
+ def TkWinfo.exist?(window)
+ bool(tk_call_without_enc('winfo', 'exists', window))
end
def winfo_exist?
TkWinfo.exist? self
end
- def TkWinfo.fpixels(win, dist)
- number(tk_call_without_enc('winfo', 'fpixels', win, dist))
+ def TkWinfo.fpixels(window, dist)
+ number(tk_call_without_enc('winfo', 'fpixels', window, dist))
end
def winfo_fpixels(dist)
TkWinfo.fpixels self, dist
end
- def TkWinfo.geometry(win)
- tk_call_without_enc('winfo', 'geometry', win)
+ def TkWinfo.geometry(window)
+ tk_call_without_enc('winfo', 'geometry', window)
end
def winfo_geometry
TkWinfo.geometry self
end
- def TkWinfo.height(win)
- number(tk_call_without_enc('winfo', 'height', win))
+ def TkWinfo.height(window)
+ number(tk_call_without_enc('winfo', 'height', window))
end
def winfo_height
TkWinfo.height self
end
- def TkWinfo.id(win)
- tk_call_without_enc('winfo', 'id', win)
+ def TkWinfo.id(window)
+ tk_call_without_enc('winfo', 'id', window)
end
def winfo_id
TkWinfo.id self
end
- def TkWinfo.interps(win=nil)
- if win
- #tk_split_simplelist(tk_call_without_enc('winfo', 'interps',
- # '-displayof', win))
+ def TkWinfo.interps(window=nil)
+ if window
tk_split_simplelist(tk_call_without_enc('winfo', 'interps',
- '-displayof', win),
- false, true)
+ '-displayof', window))
else
- #tk_split_simplelist(tk_call_without_enc('winfo', 'interps'))
- tk_split_simplelist(tk_call_without_enc('winfo', 'interps'),
- false, true)
+ tk_split_simplelist(tk_call_without_enc('winfo', 'interps'))
end
end
def winfo_interps
TkWinfo.interps self
end
- def TkWinfo.mapped?(win)
- bool(tk_call_without_enc('winfo', 'ismapped', win))
+ def TkWinfo.mapped?(window)
+ bool(tk_call_without_enc('winfo', 'ismapped', window))
end
def winfo_mapped?
TkWinfo.mapped? self
end
- def TkWinfo.manager(win)
- tk_call_without_enc('winfo', 'manager', win)
+ def TkWinfo.manager(window)
+ tk_call_without_enc('winfo', 'manager', window)
end
def winfo_manager
TkWinfo.manager self
end
- def TkWinfo.appname(win)
- tk_call('winfo', 'name', win)
+ def TkWinfo.appname(window)
+ tk_call('winfo', 'name', window)
end
def winfo_appname
TkWinfo.appname self
end
- def TkWinfo.parent(win)
- window(tk_call_without_enc('winfo', 'parent', win))
+ def TkWinfo.parent(window)
+ window(tk_call_without_enc('winfo', 'parent', window))
end
def winfo_parent
TkWinfo.parent self
@@ -175,216 +170,216 @@ module TkWinfo
TkWinfo.widget id, self
end
- def TkWinfo.pixels(win, dist)
- number(tk_call_without_enc('winfo', 'pixels', win, dist))
+ def TkWinfo.pixels(window, dist)
+ number(tk_call_without_enc('winfo', 'pixels', window, dist))
end
def winfo_pixels(dist)
TkWinfo.pixels self, dist
end
- def TkWinfo.reqheight(win)
- number(tk_call_without_enc('winfo', 'reqheight', win))
+ def TkWinfo.reqheight(window)
+ number(tk_call_without_enc('winfo', 'reqheight', window))
end
def winfo_reqheight
TkWinfo.reqheight self
end
- def TkWinfo.reqwidth(win)
- number(tk_call_without_enc('winfo', 'reqwidth', win))
+ def TkWinfo.reqwidth(window)
+ number(tk_call_without_enc('winfo', 'reqwidth', window))
end
def winfo_reqwidth
TkWinfo.reqwidth self
end
- def TkWinfo.rgb(win, color)
- list(tk_call_without_enc('winfo', 'rgb', win, color))
+ def TkWinfo.rgb(window, color)
+ list(tk_call_without_enc('winfo', 'rgb', window, color))
end
def winfo_rgb(color)
TkWinfo.rgb self, color
end
- def TkWinfo.rootx(win)
- number(tk_call_without_enc('winfo', 'rootx', win))
+ def TkWinfo.rootx(window)
+ number(tk_call_without_enc('winfo', 'rootx', window))
end
def winfo_rootx
TkWinfo.rootx self
end
- def TkWinfo.rooty(win)
- number(tk_call_without_enc('winfo', 'rooty', win))
+ def TkWinfo.rooty(window)
+ number(tk_call_without_enc('winfo', 'rooty', window))
end
def winfo_rooty
TkWinfo.rooty self
end
- def TkWinfo.screen(win)
- tk_call('winfo', 'screen', win)
+ def TkWinfo.screen(window)
+ tk_call('winfo', 'screen', window)
end
def winfo_screen
TkWinfo.screen self
end
- def TkWinfo.screencells(win)
- number(tk_call_without_enc('winfo', 'screencells', win))
+ def TkWinfo.screencells(window)
+ number(tk_call_without_enc('winfo', 'screencells', window))
end
def winfo_screencells
TkWinfo.screencells self
end
- def TkWinfo.screendepth(win)
- number(tk_call_without_enc('winfo', 'screendepth', win))
+ def TkWinfo.screendepth(window)
+ number(tk_call_without_enc('winfo', 'screendepth', window))
end
def winfo_screendepth
TkWinfo.screendepth self
end
- def TkWinfo.screenheight (win)
- number(tk_call_without_enc('winfo', 'screenheight', win))
+ def TkWinfo.screenheight (window)
+ number(tk_call_without_enc('winfo', 'screenheight', window))
end
def winfo_screenheight
TkWinfo.screenheight self
end
- def TkWinfo.screenmmheight(win)
- number(tk_call_without_enc('winfo', 'screenmmheight', win))
+ def TkWinfo.screenmmheight(window)
+ number(tk_call_without_enc('winfo', 'screenmmheight', window))
end
def winfo_screenmmheight
TkWinfo.screenmmheight self
end
- def TkWinfo.screenmmwidth(win)
- number(tk_call_without_enc('winfo', 'screenmmwidth', win))
+ def TkWinfo.screenmmwidth(window)
+ number(tk_call_without_enc('winfo', 'screenmmwidth', window))
end
def winfo_screenmmwidth
TkWinfo.screenmmwidth self
end
- def TkWinfo.screenvisual(win)
- tk_call_without_enc('winfo', 'screenvisual', win)
+ def TkWinfo.screenvisual(window)
+ tk_call_without_enc('winfo', 'screenvisual', window)
end
def winfo_screenvisual
TkWinfo.screenvisual self
end
- def TkWinfo.screenwidth(win)
- number(tk_call_without_enc('winfo', 'screenwidth', win))
+ def TkWinfo.screenwidth(window)
+ number(tk_call_without_enc('winfo', 'screenwidth', window))
end
def winfo_screenwidth
TkWinfo.screenwidth self
end
- def TkWinfo.server(win)
- tk_call('winfo', 'server', win)
+ def TkWinfo.server(window)
+ tk_call('winfo', 'server', window)
end
def winfo_server
TkWinfo.server self
end
- def TkWinfo.toplevel(win)
- window(tk_call_without_enc('winfo', 'toplevel', win))
+ def TkWinfo.toplevel(window)
+ window(tk_call_without_enc('winfo', 'toplevel', window))
end
def winfo_toplevel
TkWinfo.toplevel self
end
- def TkWinfo.visual(win)
- tk_call_without_enc('winfo', 'visual', win)
+ def TkWinfo.visual(window)
+ tk_call_without_enc('winfo', 'visual', window)
end
def winfo_visual
TkWinfo.visual self
end
- def TkWinfo.visualid(win)
- tk_call_without_enc('winfo', 'visualid', win)
+ def TkWinfo.visualid(window)
+ tk_call_without_enc('winfo', 'visualid', window)
end
def winfo_visualid
TkWinfo.visualid self
end
- def TkWinfo.visualsavailable(win, includeids=false)
+ def TkWinfo.visualsavailable(window, includeids=false)
if includeids
list(tk_call_without_enc('winfo', 'visualsavailable',
- win, "includeids"))
+ window, "includeids"))
else
- list(tk_call_without_enc('winfo', 'visualsavailable', win))
+ list(tk_call_without_enc('winfo', 'visualsavailable', window))
end
end
def winfo_visualsavailable(includeids=false)
TkWinfo.visualsavailable self, includeids
end
- def TkWinfo.vrootheight(win)
- number(tk_call_without_enc('winfo', 'vrootheight', win))
+ def TkWinfo.vrootheight(window)
+ number(tk_call_without_enc('winfo', 'vrootheight', window))
end
def winfo_vrootheight
TkWinfo.vrootheight self
end
- def TkWinfo.vrootwidth(win)
- number(tk_call_without_enc('winfo', 'vrootwidth', win))
+ def TkWinfo.vrootwidth(window)
+ number(tk_call_without_enc('winfo', 'vrootwidth', window))
end
def winfo_vrootwidth
TkWinfo.vrootwidth self
end
- def TkWinfo.vrootx(win)
- number(tk_call_without_enc('winfo', 'vrootx', win))
+ def TkWinfo.vrootx(window)
+ number(tk_call_without_enc('winfo', 'vrootx', window))
end
def winfo_vrootx
TkWinfo.vrootx self
end
- def TkWinfo.vrooty(win)
- number(tk_call_without_enc('winfo', 'vrooty', win))
+ def TkWinfo.vrooty(window)
+ number(tk_call_without_enc('winfo', 'vrooty', window))
end
def winfo_vrooty
TkWinfo.vrooty self
end
- def TkWinfo.width(win)
- number(tk_call_without_enc('winfo', 'width', win))
+ def TkWinfo.width(window)
+ number(tk_call_without_enc('winfo', 'width', window))
end
def winfo_width
TkWinfo.width self
end
- def TkWinfo.x(win)
- number(tk_call_without_enc('winfo', 'x', win))
+ def TkWinfo.x(window)
+ number(tk_call_without_enc('winfo', 'x', window))
end
def winfo_x
TkWinfo.x self
end
- def TkWinfo.y(win)
- number(tk_call_without_enc('winfo', 'y', win))
+ def TkWinfo.y(window)
+ number(tk_call_without_enc('winfo', 'y', window))
end
def winfo_y
TkWinfo.y self
end
- def TkWinfo.viewable(win)
- bool(tk_call_without_enc('winfo', 'viewable', win))
+ def TkWinfo.viewable(window)
+ bool(tk_call_without_enc('winfo', 'viewable', window))
end
def winfo_viewable
TkWinfo.viewable self
end
- def TkWinfo.pointerx(win)
- number(tk_call_without_enc('winfo', 'pointerx', win))
+ def TkWinfo.pointerx(window)
+ number(tk_call_without_enc('winfo', 'pointerx', window))
end
def winfo_pointerx
TkWinfo.pointerx self
end
- def TkWinfo.pointery(win)
- number(tk_call_without_enc('winfo', 'pointery', win))
+ def TkWinfo.pointery(window)
+ number(tk_call_without_enc('winfo', 'pointery', window))
end
def winfo_pointery
TkWinfo.pointery self
end
- def TkWinfo.pointerxy(win)
- list(tk_call_without_enc('winfo', 'pointerxy', win))
+ def TkWinfo.pointerxy(window)
+ list(tk_call_without_enc('winfo', 'pointerxy', window))
end
def winfo_pointerxy
TkWinfo.pointerxy self
diff --git a/ext/tk/lib/tk/winpkg.rb b/ext/tk/lib/tk/winpkg.rb
index 737fb959b5..d6f7a0e9d4 100644
--- a/ext/tk/lib/tk/winpkg.rb
+++ b/ext/tk/lib/tk/winpkg.rb
@@ -13,11 +13,6 @@ module TkWinDDE
TkCommandNames = ['dde'.freeze].freeze
- PACKAGE_NAME = 'dde'.freeze
- def self.package_name
- PACKAGE_NAME
- end
-
if self.const_defined? :FORCE_VERSION
tk_call_without_enc('package', 'require', 'dde', FORCE_VERSION)
else
diff --git a/ext/tk/lib/tk/wm.rb b/ext/tk/lib/tk/wm.rb
index 1f432a3848..a1002f7b96 100644
--- a/ext/tk/lib/tk/wm.rb
+++ b/ext/tk/lib/tk/wm.rb
@@ -9,18 +9,14 @@ module Tk
TkCommandNames = ['wm'.freeze].freeze
- TOPLEVEL_METHODCALL_OPTKEYS = {}
-
def aspect(*args)
if args.length == 0
list(tk_call_without_enc('wm', 'aspect', path))
else
- args = args[0] if args.length == 1 && args[0].kind_of?(Array)
tk_call('wm', 'aspect', path, *args)
self
end
end
- TOPLEVEL_METHODCALL_OPTKEYS['aspect'] = 'aspect'
def attributes(slot=nil,value=None)
if slot == nil
@@ -40,7 +36,6 @@ module Tk
self
end
end
- TOPLEVEL_METHODCALL_OPTKEYS['attributes'] = 'attributes'
def client(name=None)
if name == None
@@ -51,18 +46,15 @@ module Tk
self
end
end
- TOPLEVEL_METHODCALL_OPTKEYS['client'] = 'client'
def colormapwindows(*args)
if args.size == 0
list(tk_call_without_enc('wm', 'colormapwindows', path))
else
- args = args[0] if args.length == 1 && args[0].kind_of?(Array)
tk_call_without_enc('wm', 'colormapwindows', path, *args)
self
end
end
- TOPLEVEL_METHODCALL_OPTKEYS['colormapwindows'] = 'colormapwindows'
def wm_command(value=nil)
if value
@@ -73,14 +65,9 @@ module Tk
tk_call('wm', 'command', path)
end
end
- TOPLEVEL_METHODCALL_OPTKEYS['wm_command'] = 'wm_command'
def deiconify(ex = true)
- if ex
- tk_call_without_enc('wm', 'deiconify', path)
- else
- self.iconify
- end
+ tk_call_without_enc('wm', 'deiconify', path) if ex
self
end
@@ -92,7 +79,6 @@ module Tk
tk_call_without_enc('wm', 'focusmodel', path)
end
end
- TOPLEVEL_METHODCALL_OPTKEYS['focusmodel'] = 'focusmodel'
def frame
tk_call_without_enc('wm', 'frame', path)
@@ -106,18 +92,15 @@ module Tk
tk_call_without_enc('wm', 'geometry', path)
end
end
- TOPLEVEL_METHODCALL_OPTKEYS['geometry'] = 'geometry'
def wm_grid(*args)
if args.size == 0
list(tk_call_without_enc('wm', 'grid', path))
else
- args = args[0] if args.length == 1 && args[0].kind_of?(Array)
tk_call_without_enc('wm', 'grid', path, *args)
self
end
end
- TOPLEVEL_METHODCALL_OPTKEYS['wm_grid'] = 'wm_grid'
def group(leader = nil)
if leader
@@ -127,7 +110,6 @@ module Tk
window(tk_call('wm', 'group', path))
end
end
- TOPLEVEL_METHODCALL_OPTKEYS['group'] = 'group'
def iconbitmap(bmp=nil)
if bmp
@@ -137,33 +119,9 @@ module Tk
image_obj(tk_call_without_enc('wm', 'iconbitmap', path))
end
end
- TOPLEVEL_METHODCALL_OPTKEYS['iconbitmap'] = 'iconbitmap'
-
- def iconphoto(*imgs)
- if imgs.empty?
- @wm_iconphoto = nil unless defined? @wm_iconphoto
- return @wm_iconphoto
- end
-
- imgs = imgs[0] if imgs.length == 1 && imgs[0].kind_of?(Array)
- tk_call_without_enc('wm', 'iconphoto', path, *imgs)
- @wm_iconphoto = imgs
- self
- end
- TOPLEVEL_METHODCALL_OPTKEYS['iconphoto'] = 'iconphoto'
-
- def iconphoto_default(*imgs)
- imgs = imgs[0] if imgs.length == 1 && imgs[0].kind_of?(Array)
- tk_call_without_enc('wm', 'iconphoto', path, '-default', *imgs)
- self
- end
def iconify(ex = true)
- if ex
- tk_call_without_enc('wm', 'iconify', path)
- else
- self.deiconify
- end
+ tk_call_without_enc('wm', 'iconify', path) if ex
self
end
@@ -175,7 +133,6 @@ module Tk
image_obj(tk_call_without_enc('wm', 'iconmask', path))
end
end
- TOPLEVEL_METHODCALL_OPTKEYS['iconmask'] = 'iconmask'
def iconname(name=nil)
if name
@@ -185,18 +142,15 @@ module Tk
tk_call('wm', 'iconname', path)
end
end
- TOPLEVEL_METHODCALL_OPTKEYS['iconname'] = 'iconname'
def iconposition(*args)
if args.size == 0
list(tk_call_without_enc('wm', 'iconposition', path))
else
- args = args[0] if args.length == 1 && args[0].kind_of?(Array)
tk_call_without_enc('wm', 'iconposition', path, *args)
self
end
end
- TOPLEVEL_METHODCALL_OPTKEYS['iconposition'] = 'iconposition'
def iconwindow(win = nil)
if win
@@ -207,39 +161,33 @@ module Tk
(w == '')? nil: window(w)
end
end
- TOPLEVEL_METHODCALL_OPTKEYS['iconwindow'] = 'iconwindow'
def maxsize(*args)
if args.size == 0
list(tk_call_without_enc('wm', 'maxsize', path))
else
- args = args[0] if args.length == 1 && args[0].kind_of?(Array)
tk_call_without_enc('wm', 'maxsize', path, *args)
self
end
end
- TOPLEVEL_METHODCALL_OPTKEYS['maxsize'] = 'maxsize'
def minsize(*args)
if args.size == 0
list(tk_call_without_enc('wm', 'minsize', path))
else
- args = args[0] if args.length == 1 && args[0].kind_of?(Array)
tk_call_without_enc('wm', 'minsize', path, *args)
self
end
end
- TOPLEVEL_METHODCALL_OPTKEYS['minsize'] = 'minsize'
- def overrideredirect(mode=None)
- if mode == None
+ def overrideredirect(bool=None)
+ if bool == None
bool(tk_call_without_enc('wm', 'overrideredirect', path))
else
- tk_call_without_enc('wm', 'overrideredirect', path, mode)
+ tk_call_without_enc('wm', 'overrideredirect', path, bool)
self
end
end
- TOPLEVEL_METHODCALL_OPTKEYS['overrideredirect'] = 'overrideredirect'
def positionfrom(who=None)
if who == None
@@ -250,7 +198,6 @@ module Tk
self
end
end
- TOPLEVEL_METHODCALL_OPTKEYS['positionfrom'] = 'positionfrom'
def protocol(name=nil, cmd=nil, &b)
if cmd
@@ -267,33 +214,14 @@ module Tk
end
end
- def protocols(kv=nil)
- unless kv
- ret = {}
- self.protocol.each{|name|
- ret[name] = self.protocol(name)
- }
- return ret
- end
-
- unless kv.kind_of?(Hash)
- fail ArgumentError, 'expect a hash of protocol=>command'
- end
- kv.each{|k, v| self.protocol(k, v)}
- self
- end
- TOPLEVEL_METHODCALL_OPTKEYS['protocols'] = 'protocols'
-
def resizable(*args)
if args.length == 0
list(tk_call_without_enc('wm', 'resizable', path)).collect{|e| bool(e)}
else
- args = args[0] if args.length == 1 && args[0].kind_of?(Array)
tk_call_without_enc('wm', 'resizable', path, *args)
self
end
end
- TOPLEVEL_METHODCALL_OPTKEYS['resizable'] = 'resizable'
def sizefrom(who=None)
if who == None
@@ -304,7 +232,6 @@ module Tk
self
end
end
- TOPLEVEL_METHODCALL_OPTKEYS['sizefrom'] = 'sizefrom'
def stackorder
list(tk_call('wm', 'stackorder', path))
@@ -318,15 +245,14 @@ module Tk
bool(tk_call('wm', 'stackorder', path, 'isbelow', win))
end
- def state(st=nil)
- if st
- tk_call_without_enc('wm', 'state', path, st)
+ def state(state=nil)
+ if state
+ tk_call_without_enc('wm', 'state', path, state)
self
else
tk_call_without_enc('wm', 'state', path)
end
end
- TOPLEVEL_METHODCALL_OPTKEYS['state'] = 'state'
def title(str=nil)
if str
@@ -336,7 +262,6 @@ module Tk
tk_call('wm', 'title', path)
end
end
- TOPLEVEL_METHODCALL_OPTKEYS['title'] = 'title'
def transient(master=nil)
if master
@@ -346,14 +271,9 @@ module Tk
window(tk_call_without_enc('wm', 'transient', path))
end
end
- TOPLEVEL_METHODCALL_OPTKEYS['transient'] = 'transient'
def withdraw(ex = true)
- if ex
- tk_call_without_enc('wm', 'withdraw', path)
- else
- self.deiconify
- end
+ tk_call_without_enc('wm', 'withdraw', path) if ex
self
end
end
diff --git a/ext/tk/lib/tk/xim.rb b/ext/tk/lib/tk/xim.rb
index 0ac8559bb9..701cd7531c 100644
--- a/ext/tk/lib/tk/xim.rb
+++ b/ext/tk/lib/tk/xim.rb
@@ -9,34 +9,34 @@ module TkXIM
TkCommandNames = ['imconfigure'.freeze].freeze
- def TkXIM.useinputmethods(value = None, win = nil)
+ def TkXIM.useinputmethods(value = None, window = nil)
if value == None
- if win
+ if window
bool(tk_call_without_enc('tk', 'useinputmethods',
- '-displayof', win))
+ '-displayof', window))
else
bool(tk_call_without_enc('tk', 'useinputmethods'))
end
else
- if win
+ if window
bool(tk_call_without_enc('tk', 'useinputmethods',
- '-displayof', win, value))
+ '-displayof', window, value))
else
bool(tk_call_without_enc('tk', 'useinputmethods', value))
end
end
end
- def TkXIM.useinputmethods_displayof(win, value = None)
- TkXIM.useinputmethods(value, win)
+ def TkXIM.useinputmethods_displayof(window, value = None)
+ TkXIM.useinputmethods(value, window)
end
- def TkXIM.caret(win, keys=nil)
+ def TkXIM.caret(window, keys=nil)
if keys
- tk_call_without_enc('tk', 'caret', win, *hash_kv(keys))
+ tk_call_without_enc('tk', 'caret', window, *hash_kv(keys))
self
else
- lst = tk_split_list(tk_call_without_enc('tk', 'caret', win))
+ lst = tk_split_list(tk_call_without_enc('tk', 'caret', window))
info = {}
while key = lst.shift
info[key[1..-1]] = lst.shift
@@ -45,29 +45,29 @@ module TkXIM
end
end
- def TkXIM.configure(win, slot, value=None)
+ def TkXIM.configure(window, slot, value=None)
begin
if /^8\.*/ === Tk::TK_VERSION && JAPANIZED_TK
if slot.kind_of? Hash
- tk_call('imconfigure', win, *hash_kv(slot))
+ tk_call('imconfigure', window, *hash_kv(slot))
else
- tk_call('imconfigure', win, "-#{slot}", value)
+ tk_call('imconfigure', window, "-#{slot}", value)
end
end
rescue
end
end
- def TkXIM.configinfo(win, slot=nil)
+ def TkXIM.configinfo(window, slot=nil)
if TkComm::GET_CONFIGINFOwoRES_AS_ARRAY
begin
if /^8\.*/ === Tk::TK_VERSION && JAPANIZED_TK
if slot
- conf = tk_split_list(tk_call('imconfigure', win, "-#{slot}"))
+ conf = tk_split_list(tk_call('imconfigure', window, "-#{slot}"))
conf[0] = conf[0][1..-1]
conf
else
- tk_split_list(tk_call('imconfigure', win)).collect{|conf|
+ tk_split_list(tk_call('imconfigure', window)).collect{|conf|
conf[0] = conf[0][1..-1]
conf
}
@@ -79,19 +79,19 @@ module TkXIM
[]
end
else # ! TkComm::GET_CONFIGINFOwoRES_AS_ARRAY
- TkXIM.current_configinfo(win, slot)
+ TkXIM.current_configinfo(window, slot)
end
end
- def TkXIM.current_configinfo(win, slot=nil)
+ def TkXIM.current_configinfo(window, slot=nil)
begin
if /^8\.*/ === Tk::TK_VERSION && JAPANIZED_TK
if slot
- conf = tk_split_list(tk_call('imconfigure', win, "-#{slot}"))
+ conf = tk_split_list(tk_call('imconfigure', window, "-#{slot}"))
{ conf[0][1..-1] => conf[1] }
else
ret = {}
- tk_split_list(tk_call('imconfigure', win)).each{|conf|
+ tk_split_list(tk_call('imconfigure', window)).each{|conf|
ret[conf[0][1..-1]] = conf[1]
}
ret
diff --git a/ext/tk/lib/tkextlib/ICONS/icons.rb b/ext/tk/lib/tkextlib/ICONS/icons.rb
index 8a37e35ebf..20d706df65 100644
--- a/ext/tk/lib/tkextlib/ICONS/icons.rb
+++ b/ext/tk/lib/tkextlib/ICONS/icons.rb
@@ -18,11 +18,6 @@ module Tk
class ICONS < TkImage
extend Tk
- PACKAGE_NAME = 'icons'.freeze
- def self.package_name
- PACKAGE_NAME
- end
-
def self.package_version
begin
TkPackage.require('icons')
@@ -76,11 +71,7 @@ module Tk
##########################################
def self.new(name, keys=nil)
- unless obj = Tk_IMGTBL["::icon::#{name}"]
- obj = allocate()
- obj.instance_eval{initialize(name, keys)}
- end
- obj
+ Tk_IMGTBL["::icon::#{name}"] || super
end
def initialize(name, keys=nil)
diff --git a/ext/tk/lib/tkextlib/SUPPORT_STATUS b/ext/tk/lib/tkextlib/SUPPORT_STATUS
index 33eded5050..6bc87bab98 100644
--- a/ext/tk/lib/tkextlib/SUPPORT_STATUS
+++ b/ext/tk/lib/tkextlib/SUPPORT_STATUS
@@ -1,8 +1,6 @@
[ current support status of Tcl/Tk extensions ]
- *******<<< RELEASE_DATE of the libraries : 2005/10/23 >>>*******
-
The following list shows *CURRENT* status when this file was modifyed
at last. If you want to add other Tcl/Tk extensions to the planed list
(or change its status position), please request them at the ruby-talk,
@@ -20,13 +18,6 @@ script may give you some hints about that.
'not support' does *NOT* mean that the extension doesn't work
on Ruby/Tk.
- The version number of each extension means the latest version
- which is checked its feature. That is, it does NOT means only
- version of working. Library files maybe include some features
- which is included in the former version but removed from the
- latest, and maybe able to support the later version then the
- shown version.
-
Even if the status of the extension is 'not support', you can
control the functions/widgets of the extension without wrapper
libraries by Tk.tk_call(), Tk.ip_eval(), and so on.
@@ -55,141 +46,128 @@ script may give you some hints about that.
===< support with some examples (may be beta quality) >=======================
-Tcllib 1.8 http://sf.net/projects/tcllib
- ==> tcllib (partial support; Tklib part only)
-
-IWidgets 4.0.2 http://sf.net/projects/incrTcl ==> iwidgets
-
-BWidgets 1.7 http://sf.net/projects/tcllib ==> bwidget
-
-TkTable 2.9 http://sf.net/projects/tktable ==> tktable
- * see also <http://www.korus.hu/~fery/ruby/tktable.rb>
- written by Ferenc Engard (ferenc@engard.hu)
+Tcllib http://sf.net/projects/tcllib
+ ==> tcllib (partial support; Tklib part only)
-vu 2.3.0 http://tktable.sourceforge.net ==> vu
+IWidgets http://sf.net/projects/incrTcl ==> iwidgets
-TkHTML 2.0 http://www.hwaci.com/sw/tkhtml/index.html ==> tkHTML
+BWidgets http://sf.net/projects/tcllib ==> bwidget
-ICONS 1.0 http://www.satisoft.com/tcltk/icons/ ==> ICONS
+TkTable http://sf.net/projects/tktable ==> tktable
+ [ * see also <http://www.korus.hu/~fery/ruby/tktable.rb>
+ written by Ferenc Engard (ferenc@engard.hu) ]
-TkImg 1.3 http://sf.net/projects/tkimg ==> tkimg
+vu http://tktable.sourceforge.net ==> vu
+TkHTML http://www.hwaci.com/sw/tkhtml/index.html ==> tkHTML
-BLT 2.4z http://sourceforge.net/projects/blt
- * see also tcltk-ext library on RAA
- (http://raa.ruby-lang.org/)
- ==> blt
+ICONS http://www.satisoft.com/tcltk/icons/ ==> ICONS
-TkTreeCtrl CVS/Hd(2005-03-25)
- http://tktreectrl.sourceforge.net/ ==> treectrl
-Tile 0.7.2 http://tktable.sourceforge.net/tile/ ==> tile
+===< support (may be alpha or beta quality) >=================================
+IncrTcl http://sf.net/projects/incrTcl ==> itcl, itk
-===< support (may be alpha or beta quality) >=================================
+TclX http://sf.net/projects/tclx
+ ==> tclx (partial support; infox command and
+ XPG/3 message catalogs only)
-IncrTcl CVS/Hd(2005-02-14)
- http://sf.net/projects/incrTcl ==> itcl, itk
+TkImg http://sf.net/projects/tkimg ==> tkimg
-TclX CVS/Hd(2005-02-07)
- http://sf.net/projects/tclx
- ==> tclx (partial support; infox command and
- XPG/3 message catalogs only)
+TkTreeCtrl http://tktreectrl.sourceforge.net/ ==> treectrl
-Trofs 0.4.3 http://math.nist.gov/~DPorter/tcltk/trofs/
+Tile http://tktable.sourceforge.net/tile/ ==> tile
===< possibly available (not tested; alpha quality) >=========================
-winico 0.6
- http://tktable.sourceforge.net
- ==> winico (win32 only)
+winico http://tktable.sourceforge.net
+ ==> winico (win32 only)
-TkTrans latest(2004-10-11)
- http://www2.cmp.uea.ac.uk/~fuzz/tktrans/default.html
- ==> tktrans (win32 only)
+TkTrans http://www2.cmp.uea.ac.uk/~fuzz/tktrans/default.html
+ ==> tktrans (win32 only)
-TkDND 1.0a2 http://sourceforge.net/projects/tkdnd ==> tkDND
+TkDND http://sourceforge.net/projects/tkdnd ==> tkDND
===< plan to support (alpha quality libraries may be included) >==============
-GraphViz *** http://www.graphviz.org/
+BLT http://sourceforge.net/projects/blt
+ * see tcltk-ext library on RAA (http://raa.ruby-lang.org/)
-Tkgeomap *** http://tkgeomap.sourceforge.net/index.html
+GraphViz http://www.graphviz.org/
+
+Tkgeomap http://tkgeomap.sourceforge.net/index.html
===< not determined to supprt or not >========================================
-Tix *** http://tixlibrary.sourceforge.net/
- * see also tcltk-ext library on RAA
- (http://raa.ruby-lang.org/)
+Tix http://tixlibrary.sourceforge.net/
+ * see tcltk-ext library on RAA (http://raa.ruby-lang.org/)
-TkZinc *** http://www.tkzinc.org/
+TkZinc http://www.tkzinc.org/
-Wbc *** http://home.t-online.de/home/csaba.nemethi/
+Wbc http://home.t-online.de/home/csaba.nemethi/
-Mentry *** http://home.t-online.de/home/csaba.nemethi/
+Mentry http://home.t-online.de/home/csaba.nemethi/
-Tablelist *** http://home.t-online.de/home/csaba.nemethi/
+Tablelist http://home.t-online.de/home/csaba.nemethi/
-ANIGIF *** http://cardtable.sourceforge.net/tcltk/
+ANIGIF http://cardtable.sourceforge.net/tcltk/
-IMG_ROTATE *** http://cardtable.sourceforge.net/tcltk/
+IMG_ROTATE http://cardtable.sourceforge.net/tcltk/
-TclVfs *** http://sourceforge.net/projects/tclvfs/
+TclVfs http://sourceforge.net/projects/tclvfs/
-vfwtcl *** http://sourceforge.net/projects/avicaptcl
- * Win32 only
+vfwtcl http://sourceforge.net/projects/avicaptcl
+ * Win32 only
-multicast *** http://sourceforge.net/projects/avicaptcl
- * Win32 only
+multicast http://sourceforge.net/projects/avicaptcl
+ * Win32 only
-XBit *** http://www.geocities.com/~chengye/
- * current implementation is for Windows only
+XBit http://www.geocities.com/~chengye/
+ * current implementation is for Windows only
-QuickTimeTcl *** http://hem.fyristorg.com/matben/qt/
- * works under Mac OS (8,9,X) or Windows
+QuickTimeTcl http://hem.fyristorg.com/matben/qt/
+ * works under Mac OS (8,9,X) or Windows
===< may not support (already exist, out of Ruby/Tk scope, and so on) >=======
-TkCon *** http://sf.net/projects/tkcon
+TkCon http://sf.net/projects/tkcon
-Expect *** http://sf.net/projects/expect
+Expect http://sf.net/projects/expect
-TclXML *** http://sf.net/projects/tclxml
+TclXML http://sf.net/projects/tclxml
-TclXSLT *** http://sf.net/projects/tclxml
+TclXSLT http://sf.net/projects/tclxml
-TclDOM *** http://sf.net/projects/tclxml
+TclDOM http://sf.net/projects/tclxml
-TclSOAP *** http://sf.net/projects/tclsoap
+TclSOAP http://sf.net/projects/tclsoap
-Snack *** http://www.speech.kth.se/~kare/snack2.2.tar.gz
- * use Snack for Ruby
- (see http://rbsnack.sourceforge.net/)
+Snack http://www.speech.kth.se/~kare/snack2.2.tar.gz
+ * use Snack for Ruby (see http://rbsnack.sourceforge.net/)
-Tcom *** http://www.vex.net/~cthuang/tcom/
+Tcom http://www.vex.net/~cthuang/tcom/
-tDOM *** http://www.tdom.org
+tDOM http://www.tdom.org
-Mk4tcl *** http://www.equi4.com/metakit/tcl.html
+Mk4tcl http://www.equi4.com/metakit/tcl.html
-Memchan *** http://memchan.sourceforge.net/
+Memchan http://memchan.sourceforge.net/
-XOTcl *** http://www.xotcl.org/
===< tool (may not supprt) >==================================================
-tbcload/tclcompiler
- *** http://www.tcl.tk/software/tclpro/
+tbcload/tclcompiler http://www.tcl.tk/software/tclpro/
+
-(End of List)
+(End of List) \ No newline at end of file
diff --git a/ext/tk/lib/tkextlib/blt.rb b/ext/tk/lib/tkextlib/blt.rb
deleted file mode 100644
index 8ac8605513..0000000000
--- a/ext/tk/lib/tkextlib/blt.rb
+++ /dev/null
@@ -1,187 +0,0 @@
-#
-# BLT support
-# by Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)
-#
-
-require 'tk'
-require 'tk/variable'
-
-# call setup script for general 'tkextlib' libraries
-require 'tkextlib/setup.rb'
-
-# call setup script
-require 'tkextlib/blt/setup.rb'
-
-# load all image format handlers
-#TkPackage.require('BLT', '2.4')
-TkPackage.require('BLT')
-
-module Tk
- module BLT
- TkComm::TkExtlibAutoloadModule.unshift(self)
-
- extend TkCore
-
- VERSION = tk_call('set', 'blt_version')
- PATCH_LEVEL = tk_call('set', 'blt_patchLevel')
-
- begin
- lib = INTERP._invoke('set', 'blt_library')
- rescue
- lib = ''
- end
- LIBRARY = TkVarAccess.new('blt_library', lib)
-
- begin
- lib = INTERP._invoke('set', 'blt_libPath')
- rescue
- lib = ''
- end
- LIB_PATH = TkVarAccess.new('blt_libPath', lib)
-
- PACKAGE_NAME = 'BLT'.freeze
- def self.package_name
- PACKAGE_NAME
- end
-
- def self.package_version
- begin
- TkPackage.require('BLT')
- rescue
- ''
- end
- end
-
- ####################################################
-
- def self.beep(percent = 50)
- tk_call('::blt::beep', percent)
- end
-
- def self.bgexec(*args)
- if args[0].kind_of?(TkVariable)
- var = args.shift
- else
- var = TkVariable.new
- end
- params = [var]
-
- params.concat(hash_kv(args.shift, true)) if args[0].kind_of?(Hash)
-
- params << '--'
- params.concat(args)
-
- tk_call('::blt::bgexec', *params)
- var
- end
-
- def self.detach_bgexec(*args)
- if args[0].kind_of?(TkVariable)
- var = args.shift
- else
- var = TkVariable.new
- end
- params = [var]
-
- params.concat(hash_kv(args.shift, true)) if args[0].kind_of?(Hash)
-
- params << '--'
- params.concat(args)
- params << '&'
-
- [var, tk_split_list(tk_call('::blt::bgexec', *params))]
- end
-
- def self.bltdebug(lvl = nil)
- if lvl
- tk_call('::blt::bltdebug', lvl)
- else
- number(tk_call('::blt::bltdebug'))
- end
- end
-
- def self.crc32_file(name)
- tk_call_without_enc('::blt::crc32', name)
- end
- def self.crc32_data(dat)
- tk_call_without_enc('::blt::crc32', '-data', dat)
- end
-
- ####################################################
-
- def self.active_legend(graph)
- tk_call_without_enc('Blt_ActiveLegend', graph)
- end
- def self.crosshairs(graph)
- tk_call_without_enc('Blt_Crosshairs', graph)
- end
- def self.zoom_stack(graph)
- tk_call_without_enc('Blt_ZoomStack', graph)
- end
- def self.print_key(graph)
- tk_call_without_enc('Blt_PrintKey', graph)
- end
- def self.closest_point(graph)
- tk_call_without_enc('Blt_ClosestPoint', graph)
- end
-
- module GraphCommand
- def active_legend
- tk_call_without_enc('Blt_ActiveLegend', @path)
- self
- end
- def crosshairs
- tk_call_without_enc('Blt_Crosshairs', @path)
- self
- end
- def zoom_stack
- tk_call_without_enc('Blt_ZoomStack', @path)
- self
- end
- def print_key
- tk_call_without_enc('Blt_PrintKey', @path)
- self
- end
- def closest_point
- tk_call_without_enc('Blt_ClosestPoint', @path)
- self
- end
- end
-
- ####################################################
-
- autoload :PlotComponent,'tkextlib/blt/component.rb'
-
- autoload :Barchart, 'tkextlib/blt/barchart.rb'
- autoload :Bitmap, 'tkextlib/blt/bitmap.rb'
- autoload :Busy, 'tkextlib/blt/busy.rb'
- autoload :Container, 'tkextlib/blt/container.rb'
- autoload :CutBuffer, 'tkextlib/blt/cutbuffer.rb'
- autoload :DragDrop, 'tkextlib/blt/dragdrop.rb'
- autoload :EPS, 'tkextlib/blt/eps.rb'
- autoload :Htext, 'tkextlib/blt/htext.rb'
- autoload :Graph, 'tkextlib/blt/graph.rb'
- autoload :Spline, 'tkextlib/blt/spline.rb'
- autoload :Stripchart, 'tkextlib/blt/stripchart.rb'
- autoload :Table, 'tkextlib/blt/table.rb'
- autoload :Tabnotebook, 'tkextlib/blt/tabnotebook.rb'
- autoload :Tabset, 'tkextlib/blt/tabset.rb'
- autoload :Ted, 'tkextlib/blt/ted.rb'
- autoload :Tile, 'tkextlib/blt/tile.rb'
- autoload :Tree, 'tkextlib/blt/tree.rb'
- autoload :TreeView, 'tkextlib/blt/treeview.rb'
- autoload :Hiertable, 'tkextlib/blt/treeview.rb'
- # Hierbox is obsolete
- autoload :Vector, 'tkextlib/blt/vector.rb'
- autoload :VectorAccess, 'tkextlib/blt/vector.rb'
- autoload :Watch, 'tkextlib/blt/watch.rb'
- autoload :Winop, 'tkextlib/blt/winop.rb'
- autoload :WinOp, 'tkextlib/blt/winop.rb'
-
- # Unix only
- autoload :DnD, 'tkextlib/blt/unix_dnd.rb'
-
- # Windows only
- autoload :Printer, 'tkextlib/blt/win_printer.rb'
- end
-end
diff --git a/ext/tk/lib/tkextlib/blt/barchart.rb b/ext/tk/lib/tkextlib/blt/barchart.rb
deleted file mode 100644
index cb481c5889..0000000000
--- a/ext/tk/lib/tkextlib/blt/barchart.rb
+++ /dev/null
@@ -1,79 +0,0 @@
-#
-# tkextlib/blt/barchart.rb
-# by Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)
-#
-
-require 'tk'
-require 'tkextlib/blt.rb'
-require 'tkextlib/blt/component.rb'
-
-module Tk::BLT
- class Barchart < TkWindow
- TkCommandNames = ['::blt::barchart'.freeze].freeze
- WidgetClassName = 'Barchart'.freeze
- WidgetClassNames[WidgetClassName] = self
-
- include PlotComponent
- include GraphCommand
-
- def __boolval_optkeys
- ['bufferelements', 'buffergraph', 'invertxy']
- end
- private :__boolval_optkeys
-
- def __strval_optkeys
- ['text', 'label', 'title', 'file',
- 'background', 'plotbackground']
- end
- private :__strval_optkeys
-
- def __tkvariable_optkeys
- super() << 'colormap' << 'fontmap'
- end
- private :__tkvariable_optkeys
-
-=begin
- BarElement_ID = ['blt_barchart_bar'.freeze, '00000'.taint].freeze
-
- def bar(elem=nil, keys={})
- if elem.kind_of?(Hash)
- keys = elem
- elem = nil
- end
- unless elem
- elem = BarElement_ID.join(TkCore::INTERP._ip_id_).freeze
- BarElement_ID[1].succ!
- end
- tk_send('bar', elem, keys)
- Element.new(self, elem, :without_creating=>true)
- end
-=end
-
- def extents(item)
- num_or_str(tk_send_without_enc('extents', item))
- end
-
- def invtransform(x, y)
- list(tk_send_without_enc('invtransform', x, y))
- end
-
- def inside(x, y)
- bool(tk_send_without_enc('inside', x, y))
- end
-
- def metafile(file=None)
- # Windows only
- tk_send('metafile', file)
- self
- end
-
- def snap(output, keys={})
- tk_send_without_enc('snap', *(hash_kv(keys, false) + output))
- self
- end
-
- def transform(x, y)
- list(tk_send_without_enc('transform', x, y))
- end
- end
-end
diff --git a/ext/tk/lib/tkextlib/blt/bitmap.rb b/ext/tk/lib/tkextlib/blt/bitmap.rb
deleted file mode 100644
index 31cf8d4229..0000000000
--- a/ext/tk/lib/tkextlib/blt/bitmap.rb
+++ /dev/null
@@ -1,99 +0,0 @@
-#
-# tkextlib/blt/bitmap.rb
-# by Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)
-#
-
-require 'tk'
-require 'tkextlib/blt.rb'
-
-module Tk::BLT
- class Bitmap < TkObject
- extend TkCore
-
- TkCommandNames = ['::blt::bitmap'.freeze].freeze
-
- BITMAP_ID_TBL = TkCore::INTERP.create_table
- BITMAP_ID = ['blt_bitmap_id'.freeze, '00000'.taint].freeze
-
- def self.data(name)
- dat = tk_simple_list(tk_call('::blt::bitmap', 'data', name))
- [ tk_split_list(dat[0]), tk_simple_list(dat[1]) ]
- end
-
- def self.exist?(name)
- bool(tk_call('::blt::bitmap', 'exists', name))
- end
-
- def self.height(name)
- number(tk_call('::blt::bitmap', 'height', name))
- end
-
- def self.width(name)
- number(tk_call('::blt::bitmap', 'width', name))
- end
-
- def self.source(name)
- tk_simple_list(tk_call('::blt::bitmap', 'source', name))
- end
-
- #################################
-
- class << self
- alias _new new
-
- def new(data, keys={})
- _new(:data, nil, data, keys)
- end
- alias define new
-
- def new_with_name(name, data, keys={})
- _new(:data, name, data, keys)
- end
- alias define_with_name new_with_name
-
- def compose(text, keys={})
- _new(:text, nil, text, keys)
- end
-
- def compose_with_name(name, text, keys={})
- _new(:text, name, text, keys)
- end
- end
-
- def initialize(type, name, data, keys = {})
- if name
- @id = name
- else
- @id = BITMAP_ID.join(TkCore::INTERP._ip_id_)
- BITMAP_ID[1].succ!
- BITMAP_ID_TBL[@id] = self
- end
-
- @path = @id
-
- unless bool(tk_call('::blt::bitmap', 'exists', @id))
- if type == :text
- tk_call('::blt::bitmap', 'compose', @id, data, *hash_kv(keys))
- else # :data
- tk_call('::blt::bitmap', 'define', @id, data, *hash_kv(keys))
- end
- end
- end
-
- def exist?
- bool(tk_call('::blt::bitmap', 'exists', @id))
- end
-
- def height
- number(tk_call('::blt::bitmap', 'height', @id))
- end
-
- def width
- number(tk_call('::blt::bitmap', 'width', @id))
- end
-
- def source
- tk_simple_list(tk_call('::blt::bitmap', 'source', @id))
- end
- end
-end
diff --git a/ext/tk/lib/tkextlib/blt/busy.rb b/ext/tk/lib/tkextlib/blt/busy.rb
deleted file mode 100644
index 4726e466f4..0000000000
--- a/ext/tk/lib/tkextlib/blt/busy.rb
+++ /dev/null
@@ -1,82 +0,0 @@
-#
-# tkextlib/blt/busy.rb
-# by Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)
-#
-
-require 'tk'
-require 'tk/itemconfig.rb'
-require 'tkextlib/blt.rb'
-
-module Tk::BLT
- module Busy
- extend TkCore
- extend TkItemConfigMethod
-
- TkCommandNames = ['::blt::busy'.freeze].freeze
-
- ###########################
-
- class Shield < TkWindow
- def self.shield_path(win)
- win = window(win) unless win.kind_of?(TkWindow)
- if win.kind_of?(TkToplevel)
- win.path + '._Busy'
- else
- win.path + '_Busy'
- end
- end
-
- def initialize(win)
- @path = self.class.shield_path(win)
- end
- end
-
- def self.shield_path(win)
- Tk::BLT::Busy::Shield.shield_path(win)
- end
- end
-end
-
-class << Tk::BLT::Busy
- def __item_config_cmd(win)
- ['::blt::busy', 'configure', win]
- end
- private :__item_config_cmd
-
- undef itemcget
- alias configure itemconfigure
- alias configinfo itemconfiginfo
- alias current_configinfo current_itemconfiginfo
- private :itemconfigure, :itemconfiginfo, :current_itemconfiginfo
-
- ##################################
-
- def hold(win, keys={})
- tk_call('::blt::busy', 'hold', win, *hash_kv(keys))
- end
-
- def release(*wins)
- tk_call('::blt::busy', 'release', *wins)
- end
-
- def forget(*wins)
- tk_call('::blt::busy', 'forget', *wins)
- end
-
- def is_busy(pat=None)
- tk_split_list(tk_call('::blt::busy', 'isbusy', pat))
- end
-
- def names(pat=None)
- tk_split_list(tk_call('::blt::busy', 'names', pat))
- end
- alias windows names
-
- def check(win)
- bool(tk_call('::blt::busy', 'check', win))
- end
-
- def status(win)
- bool(tk_call('::blt::busy', 'status', win))
- end
-end
diff --git a/ext/tk/lib/tkextlib/blt/component.rb b/ext/tk/lib/tkextlib/blt/component.rb
deleted file mode 100644
index ad78a5430b..0000000000
--- a/ext/tk/lib/tkextlib/blt/component.rb
+++ /dev/null
@@ -1,1835 +0,0 @@
-#
-# tkextlib/blt/component.rb
-# by Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)
-#
-
-require 'tk'
-require 'tkextlib/blt.rb'
-
-module Tk::BLT
- module PlotComponent
- include TkItemConfigMethod
-
- module OptKeys
- def __item_font_optkeys(id)
- ['font', 'tickfont', 'titlefont']
- end
- private :__item_font_optkeys
-
- def __item_numstrval_optkeys(id)
- ['xoffset', 'yoffset']
- end
- private :__item_numstrval_optkeys
-
- def __item_boolval_optkeys(id)
- ['hide', 'under', 'descending', 'logscale', 'loose', 'showticks',
- 'titlealternate', 'scalesymbols', 'minor', 'raised',
- 'center', 'decoration', 'landscape', 'maxpect']
- end
- private :__item_boolval_optkeys
-
- def __item_strval_optkeys(id)
- ['text', 'label', 'limits', 'title',
- 'show', 'file', 'maskdata', 'maskfile',
- 'color', 'titlecolor', 'fill', 'outline', 'offdash']
- end
- private :__item_strval_optkeys
-
- def __item_listval_optkeys(id)
- ['bindtags']
- end
- private :__item_listval_optkeys
-
- def __item_numlistval_optkeys(id)
- ['dashes', 'majorticks', 'minorticks']
- end
- private :__item_numlistval_optkeys
-
- def __item_tkvariable_optkeys(id)
- ['variable', 'textvariable', 'colormap', 'fontmap']
- end
- private :__item_tkvariable_optkeys
- end
-
- include OptKeys
-
- def __item_cget_cmd(id)
- if id.kind_of?(Array)
- # id := [ type, name ]
- [self.path, id[0], 'cget', id[1]]
- else
- [self.path, id, 'cget']
- end
- end
- private :__item_cget_cmd
-
- def __item_config_cmd(id)
- if id.kind_of?(Array)
- # id := [ type, name, ... ]
- type, *names = id
- [self.path, type, 'configure'].concat(names)
- else
- [self.path, id, 'configure']
- end
- end
- private :__item_config_cmd
-
- def __item_pathname(id)
- if id.kind_of?(Array)
- id = tagid(id[1])
- end
- [self.path, id].join(';')
- end
- private :__item_pathname
-
- def axis_cget(id, option)
- ret = itemcget(['axis', tagid(id)], option)
- end
- def axis_configure(*args)
- slot = args.pop
- if slot.kind_of?(Hash)
- value = None
- slot = _symbolkey2str(slot)
- if cmd = slot.delete('command')
- slot['command'] = proc{|w, tick|
- cmd.call(TkComm.window(w), TkComm.num_or_str(tick))
- }
- end
- else
- value = slot
- slot = args.pop
- if slot == :command || slot == 'command'
- cmd = value
- value = proc{|w, tick|
- cmd.call(TkComm.window(w), TkComm.num_or_str(tick))
- }
- end
- end
- id_list = args.flatten.collect!{|id| tagid(id)}.unshift('axis')
- itemconfigure(id_list, slot, value)
- end
- def axis_configinfo(id, slot=nil)
- itemconfiginfo(['axis', tagid(id)], slot)
- end
- def current_axis_configinfo(id, slot=nil)
- current_itemconfiginfo(['axis', tagid(id)], slot)
- end
-
- def crosshairs_cget(option)
- itemcget('crosshairs', option)
- end
- def crosshairs_configure(slot, value=None)
- itemconfigure('crosshairs', slot, value)
- end
- def crosshairs_configinfo(slot=nil)
- itemconfiginfo('crosshairs', slot)
- end
- def current_crosshairs_configinfo(slot=nil)
- current_itemconfiginfo('crosshairs', slot)
- end
-
- def element_cget(id, option)
- itemcget(['element', tagid(id)], option)
- end
- def element_configure(*args)
- slot = args.pop
- if slot.kind_of?(Hash)
- value = None
- else
- value = slot
- slot = args.pop
- end
- id_list = args.flatten.collect!{|id| tagid(id)}.unshift('element')
- itemconfigure(id_list, slot, value)
- end
- def element_configinfo(id, slot=nil)
- itemconfiginfo(['element', tagid(id)], slot)
- end
- def current_element_configinfo(id, slot=nil)
- current_itemconfiginfo(['element', tagid(id)], slot)
- end
-
- def bar_cget(id, option)
- itemcget(['bar', tagid(id)], option)
- end
- def bar_configure(*args)
- slot = args.pop
- if slot.kind_of?(Hash)
- value = None
- else
- value = slot
- slot = args.pop
- end
- id_list = args.flatten.collect!{|id| tagid(id)}.unshift('bar')
- itemconfigure(id_list, slot, value)
- end
- def bar_configinfo(id, slot=nil)
- itemconfiginfo(['bar', tagid(id)], slot)
- end
- def current_bar_configinfo(id, slot=nil)
- current_itemconfiginfo(['bar', tagid(id)], slot)
- end
-
- def line_cget(id, option)
- itemcget(['line', tagid(id)], option)
- end
- def line_configure(*args)
- slot = args.pop
- if slot.kind_of?(Hash)
- value = None
- else
- value = slot
- slot = args.pop
- end
- id_list = args.flatten.collect!{|id| tagid(id)}.unshift('line')
- itemconfigure(id_list, slot, value)
- end
- def line_configinfo(id, slot=nil)
- itemconfiginfo(['line', tagid(id)], slot)
- end
- def current_line_configinfo(id, slot=nil)
- current_itemconfiginfo(['line', tagid(id)], slot)
- end
-
- def gridline_cget(option)
- itemcget('grid', option)
- end
- def gridline_configure(slot, value=None)
- itemconfigure('grid', slot, value)
- end
- def gridline_configinfo(slot=nil)
- itemconfiginfo('grid', slot)
- end
- def current_gridline_configinfo(slot=nil)
- current_itemconfiginfo('grid', slot)
- end
-
- def legend_cget(option)
- itemcget('legend', option)
- end
- def legend_configure(slot, value=None)
- itemconfigure('legend', slot, value)
- end
- def legend_configinfo(slot=nil)
- itemconfiginfo('legend', slot)
- end
- def current_legend_configinfo(slot=nil)
- current_itemconfiginfo('legend', slot)
- end
-
- def pen_cget(id, option)
- itemcget(['pen', tagid(id)], option)
- end
- def pen_configure(*args)
- slot = args.pop
- if slot.kind_of?(Hash)
- value = None
- else
- value = slot
- slot = args.pop
- end
- id_list = args.flatten.collect!{|id| tagid(id)}.unshift('pen')
- itemconfigure(id_list, slot, value)
- end
- def pen_configinfo(id, slot=nil)
- itemconfiginfo(['pen', tagid(id)], slot)
- end
- def current_pen_configinfo(id, slot=nil)
- current_itemconfiginfo(['pen', tagid(id)], slot)
- end
-
- def postscript_cget(option)
- itemcget('postscript', option)
- end
- def postscript_configure(slot, value=None)
- itemconfigure('postscript', slot, value)
- end
- def postscript_configinfo(slot=nil)
- itemconfiginfo('postscript', slot)
- end
- def current_postscript_configinfo(slot=nil)
- current_itemconfiginfo('postscript', slot)
- end
-
- def marker_cget(id, option)
- itemcget(['marker', tagid(id)], option)
- end
- def marker_configure(*args)
- slot = args.pop
- if slot.kind_of?(Hash)
- value = None
- else
- value = slot
- slot = args.pop
- end
- id_list = args.flatten.collect!{|id| tagid(id)}.unshift('marker')
- itemconfigure(id_list, slot, value)
- end
- def marker_configinfo(id, slot=nil)
- itemconfiginfo(['marker', tagid(id)], slot)
- end
- def current_marker_configinfo(id, slot=nil)
- current_itemconfiginfo(['marker', tagid(id)], slot)
- end
-
- alias __itemcget itemcget
- alias __itemconfiginfo itemconfiginfo
- alias __current_itemconfiginfo current_itemconfiginfo
- private :__itemcget, :__itemconfiginfo, :__current_itemconfiginfo
-
- def itemcget(tagOrId, option)
- ret = __itemcget(tagid(tagOrId), option)
- if option == 'bindtags' || option == :bindtags
- ret.collect{|tag| TkBindTag.id2obj(tag)}
- else
- ret
- end
- end
- def itemconfiginfo(tagOrId, slot = nil)
- ret = __itemconfiginfo(tagid(tagOrId), slot)
-
- if TkComm::GET_CONFIGINFO_AS_ARRAY
- if slot
- if slot == 'bindtags' || slot == :bindtags
- ret[-2] = ret[-2].collect{|tag| TkBindTag.id2obj(tag)}
- ret[-1] = ret[-1].collect{|tag| TkBindTag.id2obj(tag)}
- end
- else
- if (inf = ret.assoc('bindtags'))
- inf[-2] = inf[-2].collect{|tag| TkBindTag.id2obj(tag)}
- inf[-1] = inf[-1].collect{|tag| TkBindTag.id2obj(tag)}
- end
- end
-
- else # ! TkComm::GET_CONFIGINFO_AS_ARRAY
- if (inf = ret['bindtags'])
- inf[-2] = inf[-2].collect{|tag| TkBindTag.id2obj(tag)}
- inf[-1] = inf[-1].collect{|tag| TkBindTag.id2obj(tag)}
- ret['bindtags'] = inf
- end
- end
-
- ret
- end
- def current_itemconfiginfo(tagOrId, slot = nil)
- ret = __current_itemconfiginfo(tagid(tagOrId), slot)
-
- if (val = ret['bindtags'])
- ret['bindtags'] = val.collect{|tag| TkBindTag.id2obj(tag)}
- end
-
- ret
- end
-
- private :itemcget, :itemconfigure
- private :itemconfiginfo, :current_itemconfiginfo
-
- #################
-
- class Axis < TkObject
- OBJ_ID = ['blt_chart_axis'.freeze, '00000'.taint].freeze
- OBJ_TBL={}
-
- def self.id2obj(chart, id)
- cpath = chart.path
- return id unless OBJ_TBL[cpath]
- OBJ_TBL[cpath][id]? OBJ_TBL[cpath][id]: id
- end
-
- def self.new(chart, axis=nil, keys={})
- if axis.kind_of?(Hash)
- keys = axis
- axis = nil
- end
- OBJ_TBL[chart.path] = {} unless OBJ_TBL[chart.path]
- return OBJ_TBL[chart.path][axis] if axis && OBJ_TBL[chart.path][axis]
- super(chart, axis, keys)
- end
-
- def initialize(chart, axis=nil, keys={})
- if axis.kind_of?(Hash)
- keys = axis
- axis = nil
- end
- if axis
- @axis = @id = axis.to_s
- else
- @axis = @id = OBJ_ID.join(TkCore::INTERP._ip_id_).freeze
- OBJ_ID[1].succ!
- end
- @path = @id
- @parent = @chart = chart
- @cpath = @chart.path
- Axis::OBJ_TBL[@cpath][@axis] = self
- keys = _symbolkey2str(keys)
- unless keys.delete('without_creating')
- # @chart.axis_create(@axis, keys)
- tk_call(@chart, 'axis', 'create', @axis, keys)
- end
- end
-
- def id
- @id
- end
-
- def to_eval
- @id
- end
-
- def cget(option)
- @chart.axis_cget(@id, option)
- end
- def configure(key, value=None)
- @chart.axis_configure(@id, key, value)
- self
- end
- def configinfo(key=nil)
- @chart.axis_configinfo(@id, key)
- end
- def current_configinfo(key=nil)
- @chart.current_axis_configinfo(@id, key)
- end
-
- def command(cmd=nil, &b)
- if cmd
- configure('command', cmd)
- elsif b
- configure('command', Proc.new(&b))
- else
- cget('command')
- end
- end
-
- def delete
- @chart.axis_delete(@id)
- self
- end
-
- def invtransform(val)
- @chart.axis_invtransform(@id, val)
- end
-
- def limits
- @chart.axis_limits(@id)
- end
-
- def name
- @axis
- end
-
- def transform(val)
- @chart.axis_transform(@id, val)
- end
-
- def view
- @chart.axis_view(@id)
- self
- end
-
- def use(name=None) # if @id == xaxis | x2axis | yaxis | y2axis
- @chart.axis_use(@id, name)
- end
-
- def use_as(axis) # axis := xaxis | x2axis | yaxis | y2axis
- @chart.axis_use(axis, @id)
- end
- end
-
- #################
-
- class Crosshairs < TkObject
- OBJ_TBL={}
-
- def self.new(chart, keys={})
- return OBJ_TBL[chart.path] if OBJ_TBL[chart.path]
- super(chart, keys)
- end
-
- def initialize(chart, keys={})
- @parent = @chart = chart
- @cpath = @chart.path
- Crosshairs::OBJ_TBL[@cpath] = self
- @chart.crosshair_configure(keys) unless keys.empty?
- @path = @id = 'crosshairs'
- end
-
- def id
- @id
- end
-
- def to_eval
- @id
- end
-
- def cget(option)
- @chart.crosshair_cget(option)
- end
- def configure(key, value=None)
- @chart.crosshair_configure(key, value)
- self
- end
- def configinfo(key=nil)
- @chart.crosshair_configinfo(key)
- end
- def current_configinfo(key=nil)
- @chart.current_crosshair_configinfo(key)
- end
-
- def off
- @chart.crosshair_off
- self
- end
- def on
- @chart.crosshair_on
- self
- end
- def toggle
- @chart.crosshair_toggle
- self
- end
- end
-
- #################
-
- class Element < TkObject
- extend Tk
- extend TkItemFontOptkeys
- extend TkItemConfigOptkeys
-
- extend Tk::BLT::PlotComponent::OptKeys
-
- ElementTypeName = 'element'
- ElementTypeToClass = { ElementTypeName=>self }
- ElementID_TBL = TkCore::INTERP.create_table
-
- TkCore::INTERP.init_ip_env{ ElementID_TBL.clear }
-
- OBJ_ID = ['blt_chart_element'.freeze, '00000'.taint].freeze
- OBJ_TBL={}
-
- def Element.type2class(type)
- ElementTypeToClass[type]
- end
-
- def Element.id2obj(chart, id)
- cpath = chart.path
- return id unless OBJ_TBL[cpath]
- OBJ_TBL[cpath][id]? OBJ_TBL[cpath][id]: id
- end
-
- def self.new(chart, element=nil, keys={})
- if element.kind_of?(Hash)
- keys = element
- element = nil
- end
- OBJ_TBL[chart.path] = {} unless OBJ_TBL[chart.path]
- if element && OBJ_TBL[chart.path][element]
- return OBJ_TBL[chart.path][element]
- end
- super(chart, element, keys)
- end
-
- def initialize(chart, element=nil, keys={})
- if element.kind_of?(Hash)
- keys = element
- element = nil
- end
- if element
- @element = @id = element.to_s
- else
- @element = @id = OBJ_ID.join(TkCore::INTERP._ip_id_).freeze
- OBJ_ID[1].succ!
- end
- @path = @id
- @parent = @chart = chart
- @cpath = @chart.path
- @typename = self.class::ElementTypeName
- Element::OBJ_TBL[@cpath][@element] = self
- keys = _symbolkey2str(keys)
- unless keys.delete('without_creating')
- # @chart.element_create(@element, keys)
- tk_call(@chart, @typename, 'create', @element, keys)
- end
- end
-
- def id
- @id
- end
-
- def to_eval
- @id
- end
-
- def cget(option)
- # @chart.element_cget(@id, option)
- @chart.__send__(@typename + '_cget', @id, option)
- end
- def configure(key, value=None)
- # @chart.element_configure(@id, key, value)
- @chart.__send__(@typename + '_configure', @id, key, value)
- self
- end
- def configinfo(key=nil)
- # @chart.element_configinfo(@id, key)
- @chart.__send__(@typename + '_configinfo', @id, key)
- end
- def current_configinfo(key=nil)
- # @chart.current_element_configinfo(@id, key)
- @chart.__send__('current_' << @typename << '_configinfo', @id, key)
- end
-
- def activate(*args)
- @chart.element_activate(@id, *args)
- end
-
- def closest(x, y, var, keys={})
- # @chart.element_closest(x, y, var, @id, keys)
- @chart.__send__(@typename + '_closest', x, y, var, @id, keys)
- end
-
- def deactivate
- @chart.element_deactivate(@id)
- self
- end
-
- def delete
- @chart.element_delete(@id)
- self
- end
-
- def exist?
- @chart.element_exist?(@id)
- end
-
- def name
- @element
- end
-
- def type
- @chart.element_type(@id)
- end
- end
-
- class Bar < Element
- ElementTypeName = 'bar'.freeze
- ElementTypeToClass[ElementTypeName] = self
- end
- class Line < Element
- ElementTypeName = 'line'.freeze
- ElementTypeToClass[ElementTypeName] = self
- end
-
- #################
-
- class GridLine < TkObject
- OBJ_TBL={}
-
- def self.new(chart, keys={})
- return OBJ_TBL[chart.path] if OBJ_TBL[chart.path]
- super(chart, keys)
- end
-
- def initialize(chart, keys={})
- @parent = @chart = chart
- @cpath = @chart.path
- GridLine::OBJ_TBL[@cpath] = self
- @chart.gridline_configure(keys) unless keys.empty?
- @path = @id = 'grid'
- end
-
- def id
- @id
- end
-
- def to_eval
- @id
- end
-
- def cget(option)
- @chart.gridline_cget(option)
- end
- def configure(key, value=None)
- @chart.gridline_configure(key, value)
- self
- end
- def configinfo(key=nil)
- @chart.gridline_configinfo(key)
- end
- def current_configinfo(key=nil)
- @chart.current_gridline_configinfo(key)
- end
-
- def off
- @chart.gridline_off
- self
- end
- def on
- @chart.gridline_on
- self
- end
- def toggle
- @chart.gridline_toggle
- self
- end
- end
-
- #################
-
- class Legend < TkObject
- OBJ_TBL={}
-
- def self.new(chart, keys={})
- return OBJ_TBL[chart.path] if OBJ_TBL[chart.path]
- super(chart, keys)
- end
-
- def initialize(chart, keys={})
- @parent = @chart = chart
- @cpath = @chart.path
- Crosshairs::OBJ_TBL[@cpath] = self
- @chart.crosshair_configure(keys) unless keys.empty?
- @path = @id = 'legend'
- end
-
- def id
- @id
- end
-
- def to_eval
- @id
- end
-
- def cget(option)
- @chart.legend_cget(option)
- end
- def configure(key, value=None)
- @chart.legend_configure(key, value)
- self
- end
- def configinfo(key=nil)
- @chart.legend_configinfo(key)
- end
- def current_configinfo(key=nil)
- @chart.current_legend_configinfo(key)
- end
-
- def activate(*args)
- @chart.legend_activate(*args)
- end
-
- def deactivate(*args)
- @chart.legend_deactivate(*args)
- end
-
- def get(pos, y=nil)
- @chart.legend_get(pos, y)
- end
- end
-
- #################
-
- class Pen < TkObject
- OBJ_ID = ['blt_chart_pen'.freeze, '00000'.taint].freeze
- OBJ_TBL={}
-
- def self.id2obj(chart, id)
- cpath = chart.path
- return id unless OBJ_TBL[cpath]
- OBJ_TBL[cpath][id]? OBJ_TBL[cpath][id]: id
- end
-
- def self.new(chart, pen=nil, keys={})
- if pen.kind_of?(Hash)
- keys = pen
- pen = nil
- end
- OBJ_TBL[chart.path] = {} unless OBJ_TBL[chart.path]
- return OBJ_TBL[chart.path][pen] if pen && OBJ_TBL[chart.path][pen]
- super(chart, pen, keys)
- end
-
- def initialize(chart, pen=nil, keys={})
- if pen.kind_of?(Hash)
- keys = pen
- pen = nil
- end
- if pen
- @pen = @id = pen.to_s
- else
- @pen = @id = OBJ_ID.join(TkCore::INTERP._ip_id_).freeze
- OBJ_ID[1].succ!
- end
- @path = @id
- @parent = @chart = chart
- @cpath = @chart.path
- Pen::OBJ_TBL[@cpath][@pen] = self
- keys = _symbolkey2str(keys)
- unless keys.delete('without_creating')
- # @chart.pen_create(@pen, keys)
- tk_call(@chart, 'pen', 'create', @pen, keys)
- end
- end
-
- def id
- @id
- end
-
- def to_eval
- @id
- end
-
- def cget(option)
- @chart.pen_cget(@id, option)
- end
- def configure(key, value=None)
- @chart.pen_configure(@id, key, value)
- self
- end
- def configinfo(key=nil)
- @chart.pen_configinfo(@id, key)
- end
- def current_configinfo(key=nil)
- @chart.current_pen_configinfo(@id, key)
- end
-
- def delete
- @chart.pen_delete(@id)
- self
- end
-
- def name
- @pen
- end
- end
-
- #################
-
- class Postscript < TkObject
- OBJ_TBL={}
-
- def self.new(chart, keys={})
- return OBJ_TBL[chart.path] if OBJ_TBL[chart.path]
- super(chart, keys)
- end
-
- def initialize(chart, keys={})
- @parent = @chart = chart
- @cpath = @chart.path
- Postscript::OBJ_TBL[@cpath] = self
- @chart.postscript_configure(keys) unless keys.empty?
- @path = @id = 'postscript'
- end
-
- def id
- @id
- end
-
- def to_eval
- @id
- end
-
- def cget(option)
- @chart.postscript_cget(option)
- end
- def configure(key, value=None)
- @chart.postscript_configure(key, value)
- self
- end
- def configinfo(key=nil)
- @chart.postscript_configinfo(key)
- end
- def current_configinfo(key=nil)
- @chart.current_postscript_configinfo(key)
- end
-
- def output(file=nil, keys={})
- if file.kind_of?(Hash)
- keys = file
- file = nil
- end
-
- ret = @chart.postscript_output(file, keys)
-
- if file
- self
- else
- ret
- end
- end
- end
-
- #################
- class Marker < TkObject
- extend Tk
- extend TkItemFontOptkeys
- extend TkItemConfigOptkeys
-
- extend Tk::BLT::PlotComponent::OptKeys
-
- MarkerTypeName = nil
- MarkerTypeToClass = {}
- MarkerID_TBL = TkCore::INTERP.create_table
-
- TkCore::INTERP.init_ip_env{ MarkerID_TBL.clear }
-
- def Marker.type2class(type)
- MarkerTypeToClass[type]
- end
-
- def Marker.id2obj(chart, id)
- cpath = chart.path
- return id unless MarkerID_TBL[cpath]
- MarkerID_TBL[cpath][id]? MarkerID_TBL[cpath][id]: id
- end
-
- def self._parse_create_args(keys)
- fontkeys = {}
- methodkeys = {}
- if keys.kind_of? Hash
- keys = _symbolkey2str(keys)
-
- __item_font_optkeys(nil).each{|key|
- fkey = key.to_s
- fontkeys[fkey] = keys.delete(fkey) if keys.key?(fkey)
-
- fkey = "kanji#{key}"
- fontkeys[fkey] = keys.delete(fkey) if keys.key?(fkey)
-
- fkey = "latin#{key}"
- fontkeys[fkey] = keys.delete(fkey) if keys.key?(fkey)
-
- fkey = "ascii#{key}"
- fontkeys[fkey] = keys.delete(fkey) if keys.key?(fkey)
- }
-
- __item_methodcall_optkeys(nil).each{|key|
- key = key.to_s
- methodkeys[key] = keys.delete(key) if keys.key?(key)
- }
-
- __item_ruby2val_optkeys(nil).each{|key, method|
- key = key.to_s
- keys[key] = method.call(keys[key]) if keys.has_key?(key)
- }
-
- args = itemconfig_hash_kv(nil, keys)
- else
- args = []
- end
-
- [args, fontkeys]
- end
- private_class_method :_parse_create_args
-
- def self.create(chart, keys={})
- unless self::MarkerTypeName
- fail RuntimeError, "#{self} is an abstract class"
- end
- args, fontkeys = _parse_create_args(keys)
- idnum = tk_call_without_enc(chart.path, 'marker', 'create',
- self::MarkerTypeName, *args)
- chart.marker_configure(idnum, fontkeys) unless fontkeys.empty?
- idnum.to_i # 'item id' is an integer number
- end
-
- def self.create_type(chart, type, keys={})
- args, fontkeys = _parse_create_args(keys)
- idnum = tk_call_without_enc(chart.path, 'marker', 'create',
- type, *args)
- chart.marker_configure(idnum, fontkeys) unless fontkeys.empty?
- id = idnum.to_i # 'item id' is an integer number
- obj = self.allocate
- obj.instance_eval{
- @parent = @chart = chart
- @cpath = chart.path
- @id = id
- unless Tk::BLT::PlotComponent::Marker::MarkerID_TBL[@cpath]
- Tk::BLT::PlotComponent::Marker::MarkerID_TBL[@cpath] = {}
- end
- Tk::BLT::PlotComponent::Marker::MarkerID_TBL[@cpath][@id] = self
- }
- obj
- end
-
- def initialize(parent, *args)
- @parent = @chart = parent
- @cpath = parent.path
-
- @path = @id = create_self(*args) # an integer number as 'item id'
- unless Tk::BLT::PlotComponent::Marker::MarkerID_TBL[@cpath]
- Tk::BLT::PlotComponent::Marker::MarkerID_TBL[@cpath] = {}
- end
- Tk::BLT::PlotComponent::Marker::MarkerID_TBL[@cpath][@id] = self
- end
- def create_self(*args)
- self.class.create(@chart, *args) # return an integer as 'item id'
- end
- private :create_self
-
- def id
- @id
- end
-
- def to_eval
- @id
- end
-
- def cget(option)
- @chart.marker_cget(@id, option)
- end
- def configure(key, value=None)
- @chart.marker_configure(@id, key, value)
- self
- end
- def configinfo(key=nil)
- @chart.marker_configinfo(@id, key)
- end
- def current_configinfo(key=nil)
- @chart.current_marker_configinfo(@id, key)
- end
-
- def after(target=None)
- @chart.marker_after(@id, target)
- end
-
- def before(target=None)
- @chart.marker_before(@id, target)
- end
-
- def delete
- @chart.marker_delete(@id)
- end
-
- def exist?
- @chart.marker_exist(@id)
- end
-
- def type
- @chart.marker_type(@id)
- end
- end
-
- class TextMarker < Marker
- MarkerTypeName = 'text'.freeze
- MarkerTypeToClass[MarkerTypeName] = self
- end
- class LineMarker < Marker
- MarkerTypeName = 'line'.freeze
- MarkerTypeToClass[MarkerTypeName] = self
- end
- class BitmapMarker < Marker
- MarkerTypeName = 'bitmap'.freeze
- MarkerTypeToClass[MarkerTypeName] = self
- end
- class ImageMarker < Marker
- MarkerTypeName = 'image'.freeze
- MarkerTypeToClass[MarkerTypeName] = self
- end
- class PolygonMarker < Marker
- MarkerTypeName = 'polygon'.freeze
- MarkerTypeToClass[MarkerTypeName] = self
- end
- class WindowMarker < Marker
- MarkerTypeName = 'window'.freeze
- MarkerTypeToClass[MarkerTypeName] = self
- end
-
- #################
-
- def __destroy_hook__
- Axis::OBJ_TBL.delete(@path)
- Crosshairs::OBJ_TBL.delete(@path)
- Element::OBJ_TBL.delete(@path)
- GridLine::OBJ_TBL.delete(@path)
- Legend::OBJ_TBL.delete(@path)
- Pen::OBJ_TBL.delete(@path)
- Postscript::OBJ_TBL.delete(@path)
- Marker::OBJ_TBL.delete(@path)
- super()
- end
-
- #################
-
- def tagid(tag)
- if tag.kind_of?(Axis) ||
- tag.kind_of?(Crosshairs) ||
- tag.kind_of?(Element) ||
- tag.kind_of?(GridLine) ||
- tag.kind_of?(Legend) ||
- tag.kind_of?(Pen) ||
- tag.kind_of?(Postscript) ||
- tag.kind_of?(Marker)
- tag.id
- else
- tag # maybe an Array of configure paramters
- end
- end
-
- def _component_bind(target, tag, context, *args)
- if TkComm._callback_entry?(args[0]) || !block_given?
- cmd = args.shift
- else
- cmd = Proc.new
- end
- _bind([path, target, 'bind', tagid(tag)], context, cmd, *args)
- self
- end
- def _component_bind_append(target, tag, context, *args)
- if TkComm._callback_entry?(args[0]) || !block_given?
- cmd = args.shift
- else
- cmd = Proc.new
- end
- _bind_append([path, target, 'bind', tagid(tag)], context, cmd, *args)
- self
- end
- def _component_bind_remove(target, tag, context)
- _bind_remove([path, target, 'bind', tagid(tag)], context)
- self
- end
- def _component_bindinfo(target, tag, context=nil)
- _bindinfo([path, target, 'bind', tagid(tag)], context)
- end
- private :_component_bind, :_component_bind_append
- private :_component_bind_remove, :_component_bindinfo
-
- def axis_bind(tag, context, *args)
- _component_bind('axis', tag, context, *args)
- end
- def axis_bind_append(tag, context, *args)
- _component_bind_append('axis', tag, context, *args)
- end
- def axis_bind_remove(tag, context)
- _component_bind_remove('axis', tag, context)
- end
- def axis_bindinfo(tag, context=nil)
- _component_bindinfo('axis', tag, context)
- end
-
- def element_bind(tag, context, *args)
- _component_bind('element', tag, context, *args)
- end
- def element_bind_append(tag, context, *args)
- _component_bind_append('element', tag, context, *args)
- end
- def element_bind_remove(tag, context)
- _component_bind_remove('element', tag, context)
- end
- def element_bindinfo(tag, context=nil)
- _component_bindinfo('element', tag, context)
- end
-
- def bar_bind(tag, context, *args)
- _component_bind('bar', tag, context, *args)
- end
- def bar_bind_append(tag, context, *args)
- _component_bind_append('bar', tag, context, *args)
- end
- def bar_bind_remove(tag, context)
- _component_bind_remove('bar', tag, context)
- end
- def bar_bindinfo(tag, context=nil)
- _component_bindinfo('bar', tag, context)
- end
-
- def line_bind(tag, context, *args)
- _component_bind('line', tag, context, *args)
- end
- def line_bind_append(tag, context, *args)
- _component_bind_append('line', tag, context, *args)
- end
- def line_bind_remove(tag, context)
- _component_bind_remove('line', tag, context)
- end
- def line_bindinfo(tag, context=nil)
- _component_bindinfo('line', tag, context)
- end
-
- def legend_bind(tag, context, *args)
- _component_bind('legend', tag, context, *args)
- end
- def legend_bind_append(tag, context, *args)
- _component_bind_append('legend', tag, context, *args)
- end
- def legend_bind_remove(tag, context)
- _component_bind_remove('legend', tag, context)
- end
- def legend_bindinfo(tag, context=nil)
- _component_bindinfo('legend', tag, context)
- end
-
- def marker_bind(tag, context, *args)
- _component_bind('marker', tag, context, *args)
- end
- def marker_bind_append(tag, context, *args)
- _component_bind_append('marker', tag, context, *args)
- end
- def marker_bind_remove(tag, context)
- _component_bind_remove('marker', tag, context)
- end
- def marker_bindinfo(tag, context=nil)
- _component_bindinfo('marker', tag, context)
- end
-
- ###################
-
- def axis_create(id=nil, keys={})
- # tk_send('axis', 'create', tagid(id), keys)
- Tk::BLT::PlotComponent::Axis.new(self, tagid(id), keys)
- end
- def axis_delete(*ids)
- tk_send('axis', 'delete', *(ids.collect{|id| tagid(id)}))
- self
- end
- def axis_invtransform(id, val)
- list(tk_send('axis', 'invtransform', tagid(id), val))
- end
- def axis_limits(id)
- list(tk_send('axis', 'limits', tagid(id)))
- end
- def axis_names(*pats)
- simplelist(tk_send('axis', 'names',
- *(pats.collect{|pat| tagid(pat)}))).collect{|axis|
- Tk::BLT::PlotComponent::Axis.id2obj(self, axis)
- }
- end
- def axis_transform(id, val)
- list(tk_send('axis', 'transform', tagid(id), val))
- end
- def axis_view(id)
- tk_send('axis', 'view', tagid(id))
- self
- end
- def axis_use(id, target=nil)
- if target
- Tk::BLT::PlotComponent::Axis.id2obj(self,
- tk_send('axis', 'use',
- tagid(id), tagid(target)))
- else
- Tk::BLT::PlotComponent::Axis.id2obj(self,
- tk_send('axis', 'use', tagid(id)))
- end
- end
-
- ###################
-
- def crosshairs_off
- tk_send_without_enc('crosshairs', 'off')
- self
- end
- def crosshairs_on
- tk_send_without_enc('crosshairs', 'on')
- self
- end
- def crosshairs_toggle
- tk_send_without_enc('crosshairs', 'toggle')
- self
- end
-
- ###################
-
- def element_create(id=nil, keys={})
- # tk_send('element', 'create', tagid(id), keys)
- Tk::BLT::PlotComponent::Element.new(self, tagid(id), keys)
- end
- def element_activate(*args)
- if args.empty?
- list(tk_send('element', 'activate')).collect{|elem|
- Tk::BLT::PlotComponent::Element.id2obj(self, elem)
- }
- else
- # id, *indices
- id = args.shift
- tk_send('element', 'activate', tagid(id), *args)
- end
- end
- def element_closest(x, y, var, *args)
- if args[-1].kind_of?(Hash)
- keys = args.pop
- bool(tk_send('element', 'closest', x, y, var,
- *(hash_kv(keys).concat(args.collect{|id| tagid(id)}))))
- else
- bool(tk_send('element', 'closest', x, y, var,
- *(args.collect{|id| tagid(id)})))
- end
- end
- def element_deactivate(*ids)
- tk_send('element', 'deactivate', *(ids.collect{|id| tagid(id)}))
- self
- end
- def element_delete(*ids)
- tk_send('element', 'delete', *(ids.collect{|id| tagid(id)}))
- self
- end
- def element_exist?(id)
- bool(tk_send('element', 'exists', tagid(id)))
- end
- def element_names(*pats)
- simplelist(tk_send('element', 'names',
- *(pats.collect{|pat| tagid(pat)}))).collect{|elem|
- Tk::BLT::PlotComponent::Element.id2obj(self, elem)
- }
- end
- def element_show(*names)
- if names.empty?
- simplelist(tk_send('element', 'show'))
- else
- tk_send('element', 'show', *(names.collect{|n| tagid(n)}))
- self
- end
- end
- def element_type(id)
- tk_send('element', 'type', tagid(id))
- end
-
- ###################
-
- def bar_create(id=nil, keys={})
- # tk_send('bar', 'create', tagid(id), keys)
- Tk::BLT::PlotComponent::Bar.new(self, tagid(id), keys)
- end
- alias bar bar_create
- def bar_activate(*args)
- if args.empty?
- list(tk_send('bar', 'activate')).collect{|elem|
- Tk::BLT::PlotComponent::Element.id2obj(self, elem)
- }
- else
- # id, *indices
- id = args.shift
- tk_send('bar', 'activate', tagid(id), *args)
- end
- end
- def bar_closest(x, y, var, *args)
- if args[-1].kind_of?(Hash)
- keys = args.pop
- bool(tk_send('bar', 'closest', x, y, var,
- *(hash_kv(keys).concat(args.collect{|id| tagid(id)}))))
- else
- bool(tk_send('bar', 'closest', x, y, var,
- *(args.collect{|id| tagid(id)})))
- end
- end
- def bar_deactivate(*ids)
- tk_send('bar', 'deactivate', *(ids.collect{|id| tagid(id)}))
- self
- end
- def bar_delete(*ids)
- tk_send('bar', 'delete', *(ids.collect{|id| tagid(id)}))
- self
- end
- def bar_exist?(id)
- bool(tk_send('bar', 'exists', tagid(id)))
- end
- def bar_names(*pats)
- simplelist(tk_send('bar', 'names',
- *(pats.collect{|pat| tagid(pat)}))).collect{|elem|
- Tk::BLT::PlotComponent::Element.id2obj(self, elem)
- }
- end
- def bar_show(*names)
- if names.empty?
- simplelist(tk_send('bar', 'show'))
- else
- tk_send('bar', 'show', *(names.collect{|n| tagid(n)}))
- self
- end
- end
- def bar_type(id)
- tk_send('bar', 'type', tagid(id))
- end
-
- ###################
-
- def line_create(id=nil, keys={})
- # tk_send('line', 'create', tagid(id), keys)
- Tk::BLT::PlotComponent::Line.new(self, tagid(id), keys)
- end
- alias bar line_create
- def line_activate(*args)
- if args.empty?
- list(tk_send('line', 'activate')).collect{|elem|
- Tk::BLT::PlotComponent::Element.id2obj(self, elem)
- }
- else
- # id, *indices
- id = args.shift
- tk_send('line', 'activate', tagid(id), *args)
- end
- end
- def line_closest(x, y, var, *args)
- if args[-1].kind_of?(Hash)
- keys = args.pop
- bool(tk_send('line', 'closest', x, y, var,
- *(hash_kv(keys).concat(args.collect{|id| tagid(id)}))))
- else
- bool(tk_send('line', 'closest', x, y, var,
- *(args.collect{|id| tagid(id)})))
- end
- end
- def line_deactivate(*ids)
- tk_send('line', 'deactivate', *(ids.collect{|id| tagid(id)}))
- self
- end
- def line_delete(*ids)
- tk_send('line', 'delete', *(ids.collect{|id| tagid(id)}))
- self
- end
- def line_exist?(id)
- bool(tk_send('line', 'exists', tagid(id)))
- end
- def line_names(*pats)
- simplelist(tk_send('line', 'names',
- *(pats.collect{|pat| tagid(pat)}))).collect{|elem|
- Tk::BLT::PlotComponent::Element.id2obj(self, elem)
- }
- end
- def line_show(*names)
- if names.empty?
- simplelist(tk_send('line', 'show'))
- else
- tk_send('line', 'show', *(names.collect{|n| tagid(n)}))
- self
- end
- end
- def line_type(id)
- tk_send('line', 'type', tagid(id))
- end
-
- ###################
-
- def gridline_off
- tk_send_without_enc('grid', 'off')
- self
- end
- def gridline_on
- tk_send_without_enc('grid', 'on')
- self
- end
- def gridline_toggle
- tk_send_without_enc('grid', 'toggle')
- self
- end
-
- ###################
-
- def legend_window_create(parent=nil, keys=nil)
- if parent.kind_of?(Hash)
- keys = _symbolkey2str(parent)
- parent = keys.delete('parent')
- widgetname = keys.delete('widgetname')
- keys.delete('without_creating')
- elsif keys
- keys = _symbolkey2str(keys)
- widgetname = keys.delete('widgetname')
- keys.delete('without_creating')
- end
-
- legend = self.class.new(parent, :without_creating=>true,
- :widgetname=>widgetname)
- class << legend
- def __destroy_hook__
- TkCore::INTERP.tk_windows.delete(@path)
- end
- end
-
- if keys
- self.legend_configure(keys.update('position'=>legend))
- else
- self.legend_configure('position'=>legend)
- end
- legend
- end
-
- def legend_activate(*pats)
- list(tk_send('legend', 'activate',
- *(pats.collect{|pat| tagid(pat)}))).collect{|elem|
- Tk::BLT::PlotComponent::Element.id2obj(self, elem)
- }
- end
- def legend_deactivate(*pats)
- list(tk_send('legend', 'deactivate',
- *(pats.collect{|pat| tagid(pat)}))).collect{|elem|
- Tk::BLT::PlotComponent::Element.id2obj(self, elem)
- }
- end
- def legend_get(pos, y=nil)
- if y
- Tk::BLT::PlotComponent::Element.id2obj(self,
- tk_send('legend', 'get',
- _at(pos, y)))
- else
- Tk::BLT::PlotComponent::Element.id2obj(self,
- tk_send('legend', 'get', pos))
- end
- end
-
- ###################
-
- def pen_create(id=nil, keys={})
- # tk_send('pen', 'create', tagid(id), keys)
- Tk::BLT::PlotComponent::Pen.new(self, tagid(id), keys)
- end
- def pen_delete(*ids)
- tk_send('pen', 'delete', *(ids.collect{|id| tagid(id)}))
- self
- end
- def pen_names(*pats)
- simplelist(tk_send('pen', 'names',
- *(pats.collect{|pat| tagid(pat)}))).collect{|pen|
- Tk::BLT::PlotComponent::Pen.id2obj(self, pen)
- }
- end
-
- ###################
-
- def postscript_output(file=nil, keys={})
- if file.kind_of?(Hash)
- keys = file
- file = nil
- end
-
- if file
- tk_send('postscript', 'output', file, keys)
- self
- else
- tk_send('postscript', 'output', keys)
- end
- end
-
- ###################
-
- def marker_create(type, keys={})
- case type
- when :text, 'text'
- Tk::BLT::PlotComponent::TextMarker.new(self, keys)
- when :line, 'line'
- Tk::BLT::PlotComponent::LineMarker.new(self, keys)
- when :bitmap, 'bitmap'
- Tk::BLT::PlotComponent::BitmapMarker.new(self, keys)
- when :image, 'image'
- Tk::BLT::PlotComponent::ImageMarker.new(self, keys)
- when :polygon, 'polygon'
- Tk::BLT::PlotComponent::PolygonMarker.new(self, keys)
- when :window, 'window'
- Tk::BLT::PlotComponent::WindowMarker.new(self, keys)
- else
- if type.kind_of?(Tk::BLT::PlotComponent::Marker)
- type.new(self, keys)
- else
- Tk::BLT::PlotComponent::Marker.create_type(self, type, keys)
- end
- end
- end
- def marker_after(id, target=nil)
- if target
- tk_send_without_enc('marker', 'after', tagid(id), tagid(target))
- else
- tk_send_without_enc('marker', 'after', tagid(id))
- end
- self
- end
- def marker_before(id, target=None)
- if target
- tk_send_without_enc('marker', 'before', tagid(id), tagid(target))
- else
- tk_send_without_enc('marker', 'before', tagid(id))
- end
- self
- end
- def marker_delete(*ids)
- tk_send('marker', 'delete', *(ids.collect{|id| tagid(id)}))
- self
- end
- def marker_exist?(id)
- bool(tk_send('marker', 'exists', tagid(id)))
- end
- def marker_names(*pats)
- simplelist(tk_send('marker', 'names',
- *(pats.collect{|pat| tagid(pat)}))).collect{|id|
- Tk::BLT::PlotComponent::Marker.id2obj(self, id)
- }
- end
- def marker_type(id)
- tk_send('marker', 'type', tagid(id))
- end
-
- ###################
-
- def xaxis_cget(option)
- itemcget('xaxis', option)
- end
- def xaxis_configure(slot, value=None)
- if slot.kind_of?(Hash)
- slot = _symbolkey2str(slot)
- if cmd = slot.delete('command')
- slot['command'] = proc{|w, tick|
- cmd.call(TkComm.window(w), TkComm.num_or_str(tick))
- }
- end
- elsif slot == :command || slot == 'command'
- cmd = value
- value = proc{|w, tick|
- cmd.call(TkComm.window(w), TkComm.num_or_str(tick))
- }
- end
- itemconfigure('xaxis', slot, value)
- end
- def xaxis_configinfo(slot=nil)
- itemconfiginfo('xaxis', slot)
- end
- def current_xaxis_configinfo(slot=nil)
- current_itemconfiginfo('xaxis', slot)
- end
- def xaxis_bind(context, *args)
- if TkComm._callback_entry?(args[0]) || !block_given?
- cmd = args.shift
- else
- cmd = Proc.new
- end
- _bind([path, 'xaxis', 'bind'], context, cmd, *args)
- self
- end
- def xaxis_bind_append(context, *args)
- if TkComm._callback_entry?(args[0]) || !block_given?
- cmd = args.shift
- else
- cmd = Proc.new
- end
- _bind_append([path, 'xaxis', 'bind'], context, cmd, *args)
- self
- end
- def xaxis_bind_remove(context)
- _bind_remove([path, 'xaxis', 'bind'], context)
- self
- end
- def xaxis_bindinfo(context=nil)
- _bindinfo([path, 'xaxis', 'bind'], context)
- end
- def xaxis_invtransform(val)
- list(tk_send('xaxis', 'invtransform', val))
- end
- def xaxis_limits
- list(tk_send('xaxis', 'limits'))
- end
- def xaxis_transform(val)
- list(tk_send('xaxis', 'transform', val))
- end
- def xaxis_use(target=nil)
- if target
- Tk::BLT::PlotComponent::Axis.id2obj(self,
- tk_send('xaxis', 'use',
- tagid(target)))
- else
- Tk::BLT::PlotComponent::Axis.id2obj(self, tk_send('xaxis', 'use'))
- end
- end
-
- def x2axis_cget(option)
- itemcget('x2axis', option)
- end
- def x2axis_configure(slot, value=None)
- if slot.kind_of?(Hash)
- slot = _symbolkey2str(slot)
- if cmd = slot.delete('command')
- slot['command'] = proc{|w, tick|
- cmd.call(TkComm.window(w), TkComm.num_or_str(tick))
- }
- end
- elsif slot == :command || slot == 'command'
- cmd = value
- value = proc{|w, tick|
- cmd.call(TkComm.window(w), TkComm.num_or_str(tick))
- }
- end
- itemconfigure('x2axis', slot, value)
- end
- def x2axis_configinfo(slot=nil)
- itemconfiginfo('x2axis', slot)
- end
- def current_x2axis_configinfo(slot=nil)
- current_itemconfiginfo('x2axis', slot)
- end
- def x2axis_bind(context, *args)
- if TkComm._callback_entry?(args[0]) || !block_given?
- cmd = args.shift
- else
- cmd = Proc.new
- end
- _bind([path, 'x2axis', 'bind'], context, cmd, *args)
- self
- end
- def x2axis_bind_append(context, *args)
- if TkComm._callback_entry?(args[0]) || !block_given?
- cmd = args.shift
- else
- cmd = Proc.new
- end
- _bind_append([path, 'x2axis', 'bind'], context, cmd, *args)
- self
- end
- def x2axis_bind_remove(context)
- _bind_remove([path, 'x2axis', 'bind'], context)
- self
- end
- def x2axis_bindinfo(context=nil)
- _bindinfo([path, 'x2axis', 'bind'], context)
- end
- def x2axis_invtransform(val)
- list(tk_send('x2axis', 'invtransform', val))
- end
- def x2axis_limits
- list(tk_send('x2axis', 'limits'))
- end
- def x2axis_transform(val)
- list(tk_send('x2axis', 'transform', val))
- end
- def x2axis_use(target=nil)
- if target
- Tk::BLT::PlotComponent::Axis.id2obj(self,
- tk_send('x2axis', 'use',
- tagid(target)))
- else
- Tk::BLT::PlotComponent::Axis.id2obj(self, tk_send('x2axis', 'use'))
- end
- end
-
- def yaxis_cget(option)
- itemcget('yaxis', option)
- end
- def yaxis_configure(slot, value=None)
- if slot.kind_of?(Hash)
- slot = _symbolkey2str(slot)
- if cmd = slot.delete('command')
- slot['command'] = proc{|w, tick|
- cmd.call(TkComm.window(w), TkComm.num_or_str(tick))
- }
- end
- elsif slot == :command || slot == 'command'
- cmd = value
- value = proc{|w, tick|
- cmd.call(TkComm.window(w), TkComm.num_or_str(tick))
- }
- end
- itemconfigure('yaxis', slot, value)
- end
- def yaxis_configinfo(slot=nil)
- itemconfiginfo('yaxis', slot)
- end
- def current_yaxis_configinfo(slot=nil)
- current_itemconfiginfo('yaxis', slot)
- end
- def yaxis_bind(context, *args)
- if TkComm._callback_entry?(args[0]) || !block_given?
- cmd = args.shift
- else
- cmd = Proc.new
- end
- _bind([path, 'yaxis', 'bind'], context, cmd, *args)
- self
- end
- def yaxis_bind_append(context, *args)
- if TkComm._callback_entry?(args[0]) || !block_given?
- cmd = args.shift
- else
- cmd = Proc.new
- end
- _bind_append([path, 'yaxis', 'bind'], context, cmd, *args)
- self
- end
- def yaxis_bind_remove(context)
- _bind_remove([path, 'yaxis', 'bind'], context)
- self
- end
- def yaxis_bindinfo(context=nil)
- _bindinfo([path, 'yaxis', 'bind'], context)
- end
- def yaxis_invtransform(val)
- list(tk_send('yaxis', 'invtransform', val))
- end
- def yaxis_limits
- list(tk_send('yaxis', 'limits'))
- end
- def yaxis_transform(val)
- list(tk_send('yaxis', 'transform', val))
- end
- def yaxis_use(target=nil)
- if target
- Tk::BLT::PlotComponent::Axis.id2obj(self,
- tk_send('yaxis', 'use',
- tagid(target)))
- else
- Tk::BLT::PlotComponent::Axis.id2obj(self, tk_send('yaxis', 'use'))
- end
- end
-
- def y2axis_cget(option)
- itemcget('y2axis', option)
- end
- def y2axis_configure(slot, value=None)
- if slot.kind_of?(Hash)
- slot = _symbolkey2str(slot)
- if cmd = slot.delete('command')
- slot['command'] = proc{|w, tick|
- cmd.call(TkComm.window(w), TkComm.num_or_str(tick))
- }
- end
- elsif slot == :command || slot == 'command'
- cmd = value
- value = proc{|w, tick|
- cmd.call(TkComm.window(w), TkComm.num_or_str(tick))
- }
- end
- itemconfigure('y2axis', slot, value)
- end
- def y2axis_configinfo(slot=nil)
- axis_configinfo('y2axis', slot)
- end
- def current_y2axis_configinfo(slot=nil)
- current_itemconfiginfo('y2axis', slot)
- end
- def y2axis_bind(context, *args)
- if TkComm._callback_entry?(args[0]) || !block_given?
- cmd = args.shift
- else
- cmd = Proc.new
- end
- _bind([path, 'y2axis', 'bind'], context, cmd, *args)
- self
- end
- def y2axis_bind_append(context, *args)
- if TkComm._callback_entry?(args[0]) || !block_given?
- cmd = args.shift
- else
- cmd = Proc.new
- end
- _bind_append([path, 'y2axis', 'bind'], context, cmd, *args)
- self
- end
- def y2axis_bind_remove(context)
- _bind_remove([path, 'y2axis', 'bind'], context)
- self
- end
- def y2axis_bindinfo(context=nil)
- _bindinfo([path, 'y2axis', 'bind'], context)
- end
- def y2axis_invtransform(val)
- list(tk_send('y2axis', 'invtransform', val))
- end
- def y2axis_limits
- list(tk_send('y2axis', 'limits'))
- end
- def y2axis_transform(val)
- list(tk_send('y2axis', 'transform', val))
- end
- def y2axis_use(target=nil)
- if target
- Tk::BLT::PlotComponent::Axis.id2obj(self,
- tk_send('y2axis', 'use',
- tagid(target)))
- else
- Tk::BLT::PlotComponent::Axis.id2obj(self, tk_send('y2axis', 'use'))
- end
- end
- end
-end
diff --git a/ext/tk/lib/tkextlib/blt/container.rb b/ext/tk/lib/tkextlib/blt/container.rb
deleted file mode 100644
index 60ba1dec1e..0000000000
--- a/ext/tk/lib/tkextlib/blt/container.rb
+++ /dev/null
@@ -1,28 +0,0 @@
-#
-# tkextlib/blt/container.rb
-# by Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)
-#
-
-require 'tk'
-require 'tkextlib/blt.rb'
-
-module Tk::BLT
- class Container < TkWindow
- TkCommandNames = ['::blt::container'.freeze].freeze
- WidgetClassName = 'Container'.freeze
- WidgetClassNames[WidgetClassName] = self
- end
-
- def __strval_optkeys
- super() << 'name'
- end
- private :__strval_optkeys
-
- def find_command(pat)
- list(tk_send_without_enc(tk_call(self.path, 'find', '-command', pat)))
- end
-
- def find_name(pat)
- list(tk_send_without_enc(tk_call(self.path, 'find', '-name', pat)))
- end
-end
diff --git a/ext/tk/lib/tkextlib/blt/cutbuffer.rb b/ext/tk/lib/tkextlib/blt/cutbuffer.rb
deleted file mode 100644
index 1cc39dfb94..0000000000
--- a/ext/tk/lib/tkextlib/blt/cutbuffer.rb
+++ /dev/null
@@ -1,23 +0,0 @@
-#
-# tkextlib/blt/cutbuffer.rb
-# by Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)
-#
-
-require 'tk'
-require 'tkextlib/blt.rb'
-
-module Tk::BLT
- module CutBuffer
- TkCommandNames = ['::blt::cutbuffer'.freeze].freeze
-
- def self.get(num = 0)
- Tk.tk_call('::blt::cutbuffer', 'get', num)
- end
- def self.rotate(count = 1)
- Tk.tk_call('::blt::cutbuffer', 'rotate', count)
- end
- def self.set(val, num = 0)
- Tk.tk_call('::blt::cutbuffer', 'set', val, num)
- end
- end
-end
diff --git a/ext/tk/lib/tkextlib/blt/dragdrop.rb b/ext/tk/lib/tkextlib/blt/dragdrop.rb
deleted file mode 100644
index 68fb9e591a..0000000000
--- a/ext/tk/lib/tkextlib/blt/dragdrop.rb
+++ /dev/null
@@ -1,214 +0,0 @@
-#
-# tkextlib/blt/dragdrop.rb
-# by Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)
-#
-
-require 'tk'
-require 'tk/itemconfig'
-require 'tkextlib/blt.rb'
-
-module Tk::BLT
- module DragDrop
- extend TkCore
-
- TkCommandNames = ['::blt::drag&drop'.freeze].freeze
-
- class Token < TkWindow
- WidgetClassName = 'DragDropToken'.freeze
- WidgetClassNames[WidgetClassName] = self
-
- def initialize(arg)
- if arg.kind_of?(Hash) # arg is a hash includes the widgetpath of token
- arg = _symbolkey2str(arg)
- install_win(nil, arg['widgetname'])
- else # arg is a drag&drop source
- tk_call('::blt::drag&drop', 'source', arg)
- install_win(nil, tk_call('::blt::drag&drop', 'token', arg))
- end
- end
- end
-
- ###################################
-
- extend TkItemConfigMethod
- extend Tk::ValidateConfigure
-
- class << self
- def __item_config_cmd(id) # id := ['source'|'target', win]
- ['::blt::drag&drop', id[0], id[1]]
- end
- private :__item_config_cmd
-
- def __item_boolval_optkeys(id)
- super(id) << 'selftarget'
- end
- private :__item_boolval_optkeys
-
- def __item_listval_optkeys(id)
- super(id) << 'send'
- end
- private :__item_listval_optkeys
-
- def __item_strval_optkeys(id)
- super(id) << 'rejectbg' << 'rejectfg' << 'tokenbg'
- end
- private :__item_strval_optkeys
-
- undef itemcget
- private :itemconfigure, :itemconfiginfo, :current_itemconfiginfo
-
- def source_configure(win, slot, value=None)
- itemconfigure(['source', win], slot, value)
- end
- def source_configinfo(win, slot=nil)
- itemconfiginfo(['source', win], slot)
- end
- def current_source_configinfo(win, slot=nil)
- current_itemconfiginfo(['source', win], slot)
- end
- end
-
- class PackageCommand < TkValidateCommand
- class ValidateArgs < TkUtil::CallbackSubst
- KEY_TBL = [
- [ ?t, ?w, :token ],
- [ ?W, ?w, :widget ],
- nil
- ]
-
- PROC_TBL = [
- [ ?w, TkComm.method(:window) ],
- nil
- ]
-
- _setup_subst_table(KEY_TBL, PROC_TBL)
-
- def self.ret_val(val)
- val
- end
- end
-
- def self._config_keys
- ['packagecmd']
- end
- end
-
- class SiteCommand < TkValidateCommand
- class ValidateArgs < TkUtil::CallbackSubst
- KEY_TBL = [
- [ ?s, ?b, :compatible ],
- [ ?t, ?w, :token ],
- nil
- ]
-
- PROC_TBL = [
- [ ?b, TkComm.method(:bool) ],
- [ ?w, TkComm.method(:window) ],
- nil
- ]
-
- _setup_subst_table(KEY_TBL, PROC_TBL)
-
- def self.ret_val(val)
- val
- end
- end
-
- def self._config_keys
- ['sitecmd']
- end
- end
-
- def self.__validation_class_list
- super() << PackageCommand << SiteCommand
- end
-
- class << self
- Tk::ValidateConfigure.__def_validcmd(binding, PackageCommand)
- Tk::ValidateConfigure.__def_validcmd(binding, SiteCommand)
- end
-
- ###################################
-
- class DnD_Handle < TkUtil::CallbackSubst
- KEY_TBL = [
- [ ?i, ?s, :ip_name ],
- [ ?v, ?v, :value ],
- [ ?W, ?w, :widget ],
- nil
- ]
-
- PROC_TBL = [
- [ ?i, TkComm.method(:string) ],
- [ ?v, TkComm.method(:tk_tcl2ruby) ],
- [ ?w, TkComm.method(:window) ],
- nil
- ]
-
- _setup_subst_table(KEY_TBL, PROC_TBL)
- end
-
- def self.source_handler(win, datatype, cmd=Proc.new, *args)
- _bind_for_event_class(DnD_Handle,
- ['::blt::drag&drop', 'source', win, 'handler'],
- cmd, *args)
- end
-
- def self.target_handler(win, datatype, cmd=Proc.new, *args)
- _bind_for_event_class(DnD_Handle,
- ['::blt::drag&drop', 'target', win, 'handler'],
- cmd, *args)
- end
-
- ###################################
-
- def self.init_source(win)
- tk_call('::blt::drag&drop', 'source', win)
- end
-
- def self.source()
- list(tk_call('::blt::drag&drop', 'source'))
- end
-
- def self.source_handler_list(win)
- simplelist(tk_call('::blt::drag&drop', 'source', win, 'handler'))
- end
- def self.source_handler_info(win, type)
- tk_tcl2ruby(tk_call('::blt::drag&drop', 'source', win, 'handler', type))
- end
-
- def self.target
- list(tk_call('::blt::drag&drop', 'target'))
- end
- def self.target_handler_list(win)
- simplelist(tk_call('::blt::drag&drop', 'target', win, 'handler'))
- end
-
- def self.handle_target(win, type, val=None)
- tk_call('::blt::drag&drop', 'target', win, 'handle', type, val)
- end
-
- def self.token(win)
- window(tk_call('::blt::drag&drop', 'token', win))
- end
-
- def self.drag(win, x, y)
- tk_call('::blt::drag&drop', 'drag', win, x, y)
- end
- def self.drop(win, x, y)
- tk_call('::blt::drag&drop', 'drop', win, x, y)
- end
-
- def self.errors(cmd=Proc.new)
- tk_call('::blt::drag&drop', 'errors', cmd)
- end
-
- def self.active
- bool(tk_call('::blt::drag&drop', 'active'))
- end
-
- def self.location(x=None, y=None)
- list(tk_call('::blt::drag&drop', 'location', x, y))
- end
- end
-end
diff --git a/ext/tk/lib/tkextlib/blt/eps.rb b/ext/tk/lib/tkextlib/blt/eps.rb
deleted file mode 100644
index 586a42470c..0000000000
--- a/ext/tk/lib/tkextlib/blt/eps.rb
+++ /dev/null
@@ -1,32 +0,0 @@
-#
-# tkextlib/blt/eps.rb
-# by Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)
-#
-
-require 'tk'
-require 'tk/canvas'
-require 'tkextlib/blt.rb'
-
-module Tk::BLT
- class EPS < TkcItem
- CItemTypeName = 'eps'.freeze
- CItemTypeToClass[CItemTypeName] = self
- end
-end
-
-class TkCanvas
- alias __BLT_EPS_item_strval_optkeys __item_strval_optkeys
- def __item_strval_optkeys(id)
- __BLT_EPS_item_strval_optkeys(id) + [
- 'shadowcolor', 'title', 'titlecolor'
- ]
- end
- private :__item_strval_optkeys
-
- alias __BLT_EPS_item_boolval_optkeys __item_boolval_optkeys
- def __item_boolval_optkeys(id)
- __BLT_EPS_item_boolval_optkeys(id) + ['showimage']
- end
- private :__item_boolval_optkeys
-end
-
diff --git a/ext/tk/lib/tkextlib/blt/graph.rb b/ext/tk/lib/tkextlib/blt/graph.rb
deleted file mode 100644
index 9ae99bff5c..0000000000
--- a/ext/tk/lib/tkextlib/blt/graph.rb
+++ /dev/null
@@ -1,67 +0,0 @@
-#
-# tkextlib/blt/graph.rb
-# by Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)
-#
-
-require 'tk'
-require 'tkextlib/blt.rb'
-require 'tkextlib/blt/component.rb'
-
-module Tk::BLT
- class Graph < TkWindow
- TkCommandNames = ['::blt::graph'.freeze].freeze
- WidgetClassName = 'Graph'.freeze
- WidgetClassNames[WidgetClassName] = self
-
- include PlotComponent
- include GraphCommand
-
- def __boolval_optkeys
- ['bufferelements', 'invertxy']
- end
- private :__boolval_optkeys
-
- def __strval_optkeys
- ['text', 'label', 'title', 'file', 'plotbackground']
- end
- private :__strval_optkeys
-
-=begin
- BarElement_ID = ['blt_graph_bar'.freeze, '00000'.taint].freeze
-
- def bar(elem=nil, keys={})
- if elem.kind_of?(Hash)
- keys = elem
- elem = nil
- end
- unless elem
- elem = BarElement_ID.join(TkCore::INTERP._ip_id_).freeze
- BarElement_ID[1].succ!
- end
- tk_send('bar', elem, keys)
- Element.new(self, elem, :without_creating=>true)
- end
-=end
-
- def extents(item)
- num_or_str(tk_send_without_enc('extents', item))
- end
-
- def invtransform(x, y)
- list(tk_send_without_enc('invtransform', x, y))
- end
-
- def inside(x, y)
- bool(tk_send_without_enc('inside', x, y))
- end
-
- def snap(output, keys={})
- tk_send_without_enc('snap', *(hash_kv(keys, false) + output))
- self
- end
-
- def transform(x, y)
- list(tk_send_without_enc('transform', x, y))
- end
- end
-end
diff --git a/ext/tk/lib/tkextlib/blt/htext.rb b/ext/tk/lib/tkextlib/blt/htext.rb
deleted file mode 100644
index a0cf3dc036..0000000000
--- a/ext/tk/lib/tkextlib/blt/htext.rb
+++ /dev/null
@@ -1,110 +0,0 @@
-#
-# tkextlib/blt/htext.rb
-# by Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)
-#
-
-require 'tk'
-require 'tk/itemconfig.rb'
-require 'tkextlib/blt.rb'
-
-module Tk::BLT
- class Htext<TkWindow
- Htext_Var = TkVarAccess.new_hash('htext')
- Htext_Widget = TkVarAccess.new('htext(widget)', :window)
- Htext_File = TkVarAccess.new('htext(file)')
- Htext_Line = TkVarAccess.new('htext(line)')
-
- include TkItemConfigMethod
- include Scrollable
-
- TkCommandNames = ['::blt::htext'.freeze].freeze
- WidgetClassName = 'Htext'.freeze
- WidgetClassNames[WidgetClassName] = self
-
- alias window_cget itemcget
- alias window_configure itemconfigure
- alias window_configuinfo itemconfiginfo
- alias current_window_configuinfo current_itemconfiginfo
-
- def __strval_optkeys
- super() << 'filename'
- end
- private :__strval_optkeys
-
- def append(win, keys={})
- tk_send('append', _epath(win), keys)
- self
- end
-
- def goto_line(idx)
- tk_send_without_enc('gotoline', idx)
- self
- end
- def current_line
- number(tk_send_without_enc('gotoline'))
- end
-
- def index(str)
- number(tk_send('index', str))
- end
-
- def line_pos(str)
- tk_send('linepos', str)
- end
-
- def range(from=None, to=None)
- tk_send_without_enc('range', from, to)
- end
-
- def scan_mark(pos)
- tk_send_without_enc('scan', 'mark', pos)
- self
- end
-
- def scan_dragto(pos)
- tk_send_without_enc('scan', 'dragto', pos)
- self
- end
-
- def search(pat, from=None, to=None)
- num = number(tk_send('search', pat, from, to))
- (num < 0)? nil: num
- end
-
- def selection_adjust(index)
- tk_send_without_enc('selection', 'adjust', index)
- self
- end
- def selection_clear()
- tk_send_without_enc('selection', 'clear')
- self
- end
- def selection_from(index)
- tk_send_without_enc('selection', 'from', index)
- self
- end
- def selection_line(index)
- tk_send_without_enc('selection', 'line', index)
- self
- end
- def selection_present()
- bool(tk_send_without_enc('selection', 'present'))
- end
- def selection_range(first, last)
- tk_send_without_enc('selection', 'range', first, last)
- self
- end
- def selection_to(index)
- tk_send_without_enc('selection', 'to', index)
- self
- end
- def selection_word(index)
- tk_send_without_enc('selection', 'word', index)
- self
- end
-
- def windows(pat=None)
- list(tk_send('windows', pat))
- end
- end
-end
diff --git a/ext/tk/lib/tkextlib/blt/setup.rb b/ext/tk/lib/tkextlib/blt/setup.rb
deleted file mode 100644
index ce0f0bd4d4..0000000000
--- a/ext/tk/lib/tkextlib/blt/setup.rb
+++ /dev/null
@@ -1,8 +0,0 @@
-#
-# setup.rb -- setup script before calling TkPackage.require()
-#
-# If you need some setup operations (for example, add a library path
-# to the library search path) before using Tcl/Tk library packages
-# wrapped by Ruby scripts in this directory, please write the setup
-# operations in this file.
-#
diff --git a/ext/tk/lib/tkextlib/blt/spline.rb b/ext/tk/lib/tkextlib/blt/spline.rb
deleted file mode 100644
index 9f75a0b217..0000000000
--- a/ext/tk/lib/tkextlib/blt/spline.rb
+++ /dev/null
@@ -1,23 +0,0 @@
-#
-# tkextlib/blt/spline.rb
-# by Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)
-#
-
-require 'tk'
-require 'tkextlib/blt.rb'
-
-module Tk::BLT
- module Spline
- extend TkCore
-
- TkCommandNames = ['::blt::spline'.freeze].freeze
-
- def self.natural(x, y, sx, sy)
- tk_call('::blt::spline', 'natural', x, y, sx, sy)
- end
-
- def self.quadratic(x, y, sx, sy)
- tk_call('::blt::spline', 'quadratic', x, y, sx, sy)
- end
- end
-end
diff --git a/ext/tk/lib/tkextlib/blt/stripchart.rb b/ext/tk/lib/tkextlib/blt/stripchart.rb
deleted file mode 100644
index fe5afbb095..0000000000
--- a/ext/tk/lib/tkextlib/blt/stripchart.rb
+++ /dev/null
@@ -1,74 +0,0 @@
-#
-# tkextlib/blt/stripchart.rb
-# by Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)
-#
-
-require 'tk'
-require 'tkextlib/blt.rb'
-require 'tkextlib/blt/component.rb'
-
-module Tk::BLT
- class Stripchart < TkWindow
- TkCommandNames = ['::blt::stripchart'.freeze].freeze
- WidgetClassName = 'Stripchart'.freeze
- WidgetClassNames[WidgetClassName] = self
-
- include PlotComponent
- include GraphCommand
-
- def __boolval_optkeys
- ['bufferelements', 'buffergraph', 'invertxy']
- end
- private :__boolval_optkeys
-
- def __strval_optkeys
- ['text', 'label', 'title', 'file',
- 'background', 'plotbackground']
- end
- private :__strval_optkeys
-
-=begin
- BarElement_ID = ['blt_stripchart_bar'.freeze, '00000'.taint].freeze
-
- def bar(elem=nil, keys={})
- if elem.kind_of?(Hash)
- keys = elem
- elem = nil
- end
- unless elem
- elem = BarElement_ID.join(TkCore::INTERP._ip_id_).freeze
- BarElement_ID[1].succ!
- end
- tk_send('bar', elem, keys)
- Element.new(self, elem, :without_creating=>true)
- end
-=end
-
- def extents(item)
- num_or_str(tk_send_without_enc('extents', item))
- end
-
- def invtransform(x, y)
- list(tk_send_without_enc('invtransform', x, y))
- end
-
- def inside(x, y)
- bool(tk_send_without_enc('inside', x, y))
- end
-
- def metafile(file=None)
- # Windows only
- tk_send('metafile', file)
- self
- end
-
- def snap(output, keys={})
- tk_send_without_enc('snap', *(hash_kv(keys, false) + output))
- self
- end
-
- def transform(x, y)
- list(tk_send_without_enc('transform', x, y))
- end
- end
-end
diff --git a/ext/tk/lib/tkextlib/blt/table.rb b/ext/tk/lib/tkextlib/blt/table.rb
deleted file mode 100644
index fc1bf54e65..0000000000
--- a/ext/tk/lib/tkextlib/blt/table.rb
+++ /dev/null
@@ -1,344 +0,0 @@
-#
-# tkextlib/blt/table.rb
-# by Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)
-#
-
-require 'tk'
-require 'tk/itemconfig.rb'
-require 'tkextlib/blt.rb'
-
-module Tk::BLT
- module Table
- include Tk
- extend Tk
- extend TkItemConfigMethod
-
- TkCommandNames = ['::blt::table'.freeze].freeze
-
- module TableContainer
- def blt_table_add(*args)
- Tk::BLT::Table.add(@path, *args)
- self
- end
-
- def blt_table_arrange()
- Tk::BLT::Table.arrange(@path)
- self
- end
-
- def blt_table_cget(*args)
- Tk::BLT::Table.cget(@path, *args)
- end
-
- def blt_table_configure(*args)
- Tk::BLT::Table.configure(@path, *args)
- self
- end
-
- def blt_table_configinfo(*args)
- Tk::BLT::Table.configinfo(@path, *args)
- end
-
- def blt_table_current_configinfo(*args)
- Tk::BLT::Table.current_configinfo(@path, *args)
- end
-
- def blt_table_locate(x, y)
- Tk::BLT::Table.locate(@path, x, y)
- end
-
- def blt_table_delete(*args)
- Tk::BLT::Table.delete(@path, *args)
- self
- end
-
- def blt_table_extents(item)
- Tk::BLT::Table.extents(@path, item)
- end
-
- def blt_table_insert(*args)
- Tk::BLT::Table.insert(@path, *args)
- self
- end
-
- def blt_table_insert_before(*args)
- Tk::BLT::Table.insert_before(@path, *args)
- self
- end
-
- def blt_table_insert_after(*args)
- Tk::BLT::Table.insert_after(@path, *args)
- self
- end
-
- def blt_table_join(first, last)
- Tk::BLT::Table.join(@path, first, last)
- self
- end
-
- def blt_table_save()
- Tk::BLT::Table.save(@path)
- end
-
- def blt_table_search(*args)
- Tk::BLT::Table.search(@path, *args)
- end
-
- def blt_table_split(*args)
- Tk::BLT::Table.split(@path, *args)
- self
- end
-
- def blt_table_itemcget(*args)
- Tk::BLT::Table.itemcget(@path, *args)
- end
-
- def blt_table_itemconfigure(*args)
- Tk::BLT::Table.itemconfigure(@path, *args)
- self
- end
-
- def blt_table_itemconfiginfo(*args)
- Tk::BLT::Table.itemconfiginfo(@path, *args)
- end
-
- def blt_table_current_itemconfiginfo(*args)
- Tk::BLT::Table.current_itemconfiginfo(@path, *args)
- end
-
- def blt_table_iteminfo(item)
- Tk::BLT::Table.iteminfo(@path, item)
- end
- end
- end
-end
-
-
-############################################
-class << Tk::BLT::Table
- def __item_cget_cmd(id) # id := [ container, item ]
- ['::blt::table', 'cget', id[0].path, id[1]]
- end
- private :__item_cget_cmd
-
- def __item_config_cmd(id) # id := [ container, item, ... ]
- container, *items = id
- ['::blt::table', 'configure', container.path, *items]
- end
- private :__item_config_cmd
-
- def __item_pathname(id)
- id[0].path + ';'
- end
- private :__item_pathname
-
- alias __itemcget itemcget
- alias __itemconfigure itemconfigure
- alias __itemconfiginfo itemconfiginfo
- alias __current_itemconfiginfo current_itemconfiginfo
-
- private :__itemcget, :__itemconfigure
- private :__itemconfiginfo, :__current_itemconfiginfo
-
- def __boolval_optkeys
- super() << 'propagate'
- end
- private :__boolval_optkeys
-
- def tagid(tag)
- if tag.kind_of?(Array)
- case tag[0]
- when Integer
- # [row, col]
- tag.join(',')
- when :c, :C, 'c', 'C', :r, :R, 'r', 'R'
- # c0 or r1 or C*, and so on
- tag.collect{|elem| elem.to_s}.join('')
- else
- tag
- end
- elsif tag.kind_of?(TkWindow)
- _epath(tag)
- else
- tag
- end
- end
-
- def tagid2obj(tagid)
- tagid
- end
-
- ############################################
-
- def cget(container, option)
- __itemcget([container], option)
- end
-
- def configure(container, *args)
- __itemconfigure([container], *args)
- end
-
- def configinfo(container, *args)
- __itemconfiginfo([container], *args)
- end
-
- def current_configinfo(container, *args)
- __current_itemconfiginfo([container], *args)
- end
-
- def itemcget(container, item, option)
- __itemcget([container, tagid(item)], option)
- end
-
- def itemconfigure(container, *args)
- if args[-1].kind_of?(Hash)
- # container, item, item, ... , hash_optkeys
- keys = args.pop
- id = [container]
- args.each{|item| id << tagid(item)}
- __itemconfigure(id, keys)
- else
- # container, item, item, ... , option, value
- val = args.pop
- opt = args.pop
- id = [container]
- args.each{|item| id << tagid(item)}
- __itemconfigure(id, opt, val)
- end
- end
-
- def itemconfiginfo(container, *args)
- slot = args[-1]
- if slot.kind_of?(String) || slot.kind_of?(Symbol)
- slot = slot.to_s
- if slot[0] == ?. || slot =~ /^\d+,\d+$/ || slot =~ /^(c|C|r|R)(\*|\d+)/
- # widget || row,col || Ci or Ri
- slot = nil
- else
- # option
- slot = args.pop
- end
- else
- slot = nil
- end
-
- id = [container]
- args.each{|item| id << tagid(item)}
- __itemconfiginfo(id, slot)
- end
-
- def info(container)
- ret = {}
- inf = list(tk_call('::blt::table', 'info', container))
- until inf.empty?
- opt = inf.slice!(0..1)
- ret[opt[1..-1]] = opt[1]
- end
- ret
- end
-
- def iteminfo(container, item)
- ret = {}
- inf = list(tk_call('::blt::table', 'info', container, tagid(item)))
- until inf.empty?
- opt = inf.slice!(0..1)
- ret[opt[1..-1]] = opt[1]
- end
- ret
- end
-
- ############################################
-
- def create_container(container)
- tk_call('::blt::table', container)
- begin
- class << container
- include Tk::BLT::TABLE::TableContainer
- end
- rescue
- warn('fail to include TableContainer methods (frozen object?)')
- end
- container
- end
-
- def add(container, *args)
- if args.empty?
- tk_call('::blt::table', container)
- else
- args = args.collect{|arg|
- if arg.kind_of?(TkWindow)
- _epath(arg)
- elsif arg.kind_of?(Array) # index
- arg.join(',')
- else
- arg
- end
- }
- tk_call('::blt::table', container, *args)
- end
- end
-
- def arrange(container)
- tk_call('::blt::table', 'arrange', container)
- end
-
- def delete(container, *args)
- tk_call('::blt::table', 'delete', container, *args)
- end
-
- def extents(container, item)
- ret = []
- inf = list(tk_call('::blt::table', 'extents', container, item))
- ret << inf.slice!(0..4) until inf.empty?
- ret
- end
-
- def forget(*wins)
- wins = wins.collect{|win| _epath(win)}
- tk_call('::blt::table', 'forget', *wins)
- end
-
- def insert(container, *args)
- tk_call('::blt::table', 'insert', container, *args)
- end
-
- def insert_before(container, *args)
- tk_call('::blt::table', 'insert', container, '-before', *args)
- end
-
- def insert_after(container, *args)
- tk_call('::blt::table', 'insert', container, '-after', *args)
- end
-
- def join(container, first, last)
- tk_call('::blt::table', 'join', container, first, last)
- end
-
- def locate(container, x, y)
- tk_call('::blt::table', 'locate', container, x, y)
- end
-
- def containers(arg={})
- list(tk_call('::blt::table', 'containers', *hash_kv(arg)))
- end
-
- def containers_pattern(pat)
- list(tk_call('::blt::table', 'containers', '-pattern', pat))
- end
-
- def containers_slave(win)
- list(tk_call('::blt::table', 'containers', '-slave', win))
- end
-
- def save(container)
- tk_call('::blt::table', 'save', container)
- end
-
- def search(container, keys={})
- list(tk_call('::blt::table', 'containers', *hash_kv(keys)))
- end
-
- def split(container, *args)
- tk_call('::blt::table', 'split', container, *args)
- end
-end
diff --git a/ext/tk/lib/tkextlib/blt/tabnotebook.rb b/ext/tk/lib/tkextlib/blt/tabnotebook.rb
deleted file mode 100644
index 508fa2b82f..0000000000
--- a/ext/tk/lib/tkextlib/blt/tabnotebook.rb
+++ /dev/null
@@ -1,21 +0,0 @@
-#
-# tkextlib/blt/tabnotebook.rb
-# by Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)
-#
-
-require 'tk'
-require 'tkextlib/blt.rb'
-require 'tkextlib/blt/tabset.rb'
-
-module Tk::BLT
- class Tabnotebook < Tabset
- TkCommandNames = ['::blt::tabnotebook'.freeze].freeze
- WidgetClassName = 'Tabnotebook'.freeze
- WidgetClassNames[WidgetClassName] = self
-
- def get_tab(index)
- Tk::BLT::Tabset::Tab.id2obj(tk_send_without_enc('id', tagindex(index)))
- end
- alias get_id get_tab
- end
-end
diff --git a/ext/tk/lib/tkextlib/blt/tabset.rb b/ext/tk/lib/tkextlib/blt/tabset.rb
deleted file mode 100644
index c26b6ee001..0000000000
--- a/ext/tk/lib/tkextlib/blt/tabset.rb
+++ /dev/null
@@ -1,401 +0,0 @@
-#
-# tkextlib/blt/tabset.rb
-# by Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)
-#
-
-require 'tk'
-require 'tkextlib/blt.rb'
-
-module Tk::BLT
- class Tabset < TkWindow
- class Tab < TkObject
- include TkTreatItemFont
-
- TabID_TBL = TkCore::INTERP.create_table
- TabsetTab_ID = ['blt_tabset_tab'.freeze, '00000'.taint].freeze
-
- TkCore::INTERP.init_ip_env{ TabID_TBL.clear }
-
- def self.id2obj(tabset, id)
- tpath = tabset.path
- return id unless TabID_TBL[tpath]
- TabID_TBL[tpath][id]? TabID_TBL[tpath]: id
- end
-
- def self.new(parent, pos=nil, name=nil, keys={})
- if pos.kind_of?(Hash)
- keys = pos
- name = nil
- pos = nil
- end
- if name.kind_of?(Hash)
- keys = name
- name = nil
- end
-
- if name && TabID_TBL[parent.path] && TabID_TBL[parent.path][name]
- TabID_TBL[parent.path][name]
- else
- super(parent, pos, name, keys)
- end
- end
-
- def initialize(parent, pos, name, keys)
- @t = parent
- @tpath = parent.path
- if name
- @path = @id = name
- TabID_TBL[@tpath] = {} unless TabID_TBL[@tpath]
- TabID_TBL[@tpath][@id] = self
-
- unless (list(tk_call(@tpath, 'tab', 'names', @id)).empty?)
- if pos
- idx = tk_call(@tpath, 'index', '-name', @id)
- if pos.to_s == 'end'
- tk_call(@tpath, idx, 'moveto', 'after', 'end')
- else
- tk_call(@tpath, idx, 'moveto', 'before', pos)
- end
- end
- tk_call(@tpath, 'tab', 'configure', @id, keys)
- return
- end
-
- else
- @path = @id = TabsetTab_ID.join(TkCore::INTERP._ip_id_)
- TabID_TBL[@tpath] = {} unless TabID_TBL[@tpath]
- TabID_TBL[@tpath][@id] = self
- TabsetTab_ID[1].succ!
- end
-
- pos = 'end' unless pos
- tk_call(@tpath, 'insert', pos, @id, keys)
- end
-
- #def bind(context, cmd=Proc.new, *args)
- # @t.tab_bind(@id, context, cmd, *args)
- # self
- #end
- def bind(context, *args)
- # if args[0].kind_of?(Proc) || args[0].kind_of?(Method)
- if TkComm._callback_entry?(args[0]) || !block_given?
- cmd = args.shift
- else
- cmd = Proc.new
- end
- @t.tab_bind(@id, context, cmd, *args)
- self
- end
- #def bind_append(context, cmd=Proc.new, *args)
- # @t.tab_bind_append(@id, context, cmd, *args)
- # self
- #end
- def bind_append(context, *args)
- # if args[0].kind_of?(Proc) || args[0].kind_of?(Method)
- if TkComm._callback_entry?(args[0]) || !block_given?
- cmd = args.shift
- else
- cmd = Proc.new
- end
- @t.tab_bind_append(@id, context, cmd, *args)
- self
- end
- def bind_remove(context)
- @t.tab_bind_remove(@id, context)
- self
- end
- def bindinfo(context=nil)
- @t.tab_bindinfo(@id, context)
- end
-
- def cget(*args)
- @t.tab_cget(@id, *args)
- end
- def configure(*args)
- @t.tab_configure(@id, *args)
- end
- def configinfo(*args)
- @t.tab_configinfo(@id, *args)
- end
- def current_configinfo(*args)
- @t.current_tab_configinfo(@id, *args)
- end
-
- def delete()
- @t.delete(@id)
- TabID_TBL[@tpath].delete(@id)
- self
- end
-
- def get_name()
- @id.dup
- end
-
- def focus()
- @t.focus(self.index)
- end
-
- def index()
- @t.index_name(@id)
- end
-
- def invoke()
- @t.invoke(self.index)
- end
-
- def move_before(idx)
- @t.move_before(self.index, idx)
- end
- def move_after(idx)
- @t.move_after(self.index, idx)
- end
-
- def perforation_highlight(mode)
- @t.perforation.highlight(self.index, mode)
- end
- def perforation_invoke()
- @t.perforation.invoke(self.index)
- end
-
- def see()
- @t.see(self.index)
- end
-
- def tearoff(name=None)
- @t.tab_tearoff(self.index, *args)
- end
- end
-
- ########################################
-
- class NamedTab < Tab
- def self.new(parent, name)
- super(parent, nil, name, {})
- end
- end
-
- ########################################
-
- include X_Scrollable
- include TkItemConfigMethod
-
- TkCommandNames = ['::blt::tabset'.freeze].freeze
- WidgetClassName = 'Tabset'.freeze
- WidgetClassNames[WidgetClassName] = self
-
- def __destroy_hook__
- Tk::BLT::Tabset::Tab::TabID_TBL.delete(@path)
- end
-
- ########################################
-
- def __boolval_optkeys
- super() << 'samewidth' << 'tearoff'
- end
- private :__strval_optkeys
-
- def __strval_optkeys
- super() << 'tabbackground' << 'tabforeground'
- end
- private :__strval_optkeys
-
- def __item_cget_cmd(id)
- [self.path, 'tab', 'cget', id]
- end
- private :__item_cget_cmd
-
- def __item_config_cmd(id)
- [self.path, 'tab', 'configure', id]
- end
- private :__item_config_cmd
-
- def __item_pathname(tagOrId)
- if tagOrId.kind_of?(Tk::BLT::Tabset::Tab)
- self.path + ';' + tagOrId.id.to_s
- else
- self.path + ';' + tagOrId.to_s
- end
- end
- private :__item_pathname
-
- alias tab_cget itemcget
- alias tab_configure itemconfigure
- alias tab_configinfo itemconfiginfo
- alias current_tab_configinfo current_itemconfiginfo
-
- def __item_strval_optkeys(id)
- super(id) << 'shadow'
- end
- private :__item_strval_optkeys
-
- def tagid(tab)
- if tab.kind_of?(Tk::BLT::Tabset::Tab)
- tab.id
- else
- tab
- end
- end
-
- def tagindex(tab)
- if tab.kind_of?(Tk::BLT::Tabset::Tab)
- tab.index
- else
- tab
- end
- end
-
- ########################################
-
- def activate(index)
- tk_send('activate', tagindex(index))
- self
- end
- alias highlight activate
-
- #def tabbind(tag, context, cmd=Proc.new, *args)
- # _bind([path, "bind", tagid(tag)], context, cmd, *args)
- # self
- #end
- def tabbind(tag, context, *args)
- # if args[0].kind_of?(Proc) || args[0].kind_of?(Method)
- if TkComm._callback_entry?(args[0]) || !block_given?
- cmd = args.shift
- else
- cmd = Proc.new
- end
- _bind([path, "bind", tagid(tag)], context, cmd, *args)
- self
- end
- #def tabbind_append(tag, context, cmd=Proc.new, *args)
- # _bind_append([path, "bind", tagid(tag)], context, cmd, *args)
- # self
- #end
- def tabbind_append(tag, context, *args)
- # if args[0].kind_of?(Proc) || args[0].kind_of?(Method)
- if TkComm._callback_entry?(args[0]) || !block_given?
- cmd = args.shift
- else
- cmd = Proc.new
- end
- _bind_append([path, "bind", tagid(tag)], context, cmd, *args)
- self
- end
- def tabbind_remove(tag, context)
- _bind_remove([path, "bind", tagid(tag)], context)
- self
- end
- def tabbindinfo(tag, context=nil)
- _bindinfo([path, "bind", tagid(tag)], context)
- end
-
- def delete(first, last=None)
- tk_send('delete', tagindex(first), tagindex(last))
- if first.kind_of?(Tk::BLT::Tabset::Tab)
- TabID_TBL[@path].delete(first.id)
- end
- # middle tabs of the range are unknown
- if last.kind_of?(Tk::BLT::Tabset::Tab)
- TabID_TBL[@path].delete(last.id)
- end
- self
- end
-
- def focus(index)
- tk_send('focus', tagindex(index))
- self
- end
-
- def get_tab(index)
- Tk::BLT::Tabset::Tab.id2obj(tk_send_without_enc('get', tagindex(index)))
- end
-
- def index(str)
- num_or_str(tk_send('index', str))
- end
- def index_name(tab)
- num_or_str(tk_send('index', '-mame', tagid(tab)))
- end
-
- def insert(pos, tab, keys={})
- Tk::BLT::Tabset::Tab.new(self, tagindex(pos), tagid(tab), keys)
- end
-
- def invoke(index)
- tk_send('invoke', tagindex(index))
- end
-
- def move_before(index, base_idx)
- tk_send('move', tagindex(index), 'before', tagindex(base_idx))
- self
- end
- def move_after(index, base_idx)
- tk_send('move', tagindex(index), 'after', tagindex(base_idx))
- self
- end
-
- def nearest(x, y)
- Tk::BLT::Tabset::Tab.id2obj(num_or_str(tk_send_without_enc('nearest', x, y)))
- end
-
- def perforation_highlight(index, mode)
- tk_send('perforation', 'highlight', tagindex(index), mode)
- self
- end
- def perforation_invoke(index)
- tk_send('perforation', 'invoke', tagindex(index))
- end
-
- def scan_mark(x, y)
- tk_send_without_enc('scan', 'mark', x, y)
- self
- end
- def scan_dragto(x, y)
- tk_send_without_enc('scan', 'dragto', x, y)
- self
- end
-
- def see(index)
- tk_send('see', tagindex(index))
- self
- end
-
- def size()
- number(tk_send_without_enc('size'))
- end
-
- def select(index)
- tk_send('select', tagindex(index))
- self
- end
-
- def tab_names(pat=None)
- simplelist(tk_send('tab', 'names', pat)).collect{|name|
- Tk::BLT::Tabset::Tab.id2obj(name)
- }
- end
-
- def tab_tearoff(index, name=None)
- window(tk_send('tab', 'tearoff', tagindex(index), name))
- end
-
- def xscrollcommand(cmd=Proc.new)
- configure_cmd 'scrollcommand', cmd
- self
- end
- alias scrollcommand xscrollcommand
-
- def xview(*index)
- if index.empty?
- list(tk_send_without_enc('view'))
- else
- tk_send_without_enc('view', *index)
- self
- end
- end
- alias view xview
- alias view_moveto xview_moveto
- alias view_scroll xview_scroll
-
- alias scrollbar xscrollbar
- end
-end
diff --git a/ext/tk/lib/tkextlib/blt/ted.rb b/ext/tk/lib/tkextlib/blt/ted.rb
deleted file mode 100644
index 39495842b4..0000000000
--- a/ext/tk/lib/tkextlib/blt/ted.rb
+++ /dev/null
@@ -1,62 +0,0 @@
-#
-# tkextlib/blt/ted.rb
-#
-# *** This is alpha version, because there is no document on BLT. ***
-#
-# by Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)
-#
-
-require 'tk'
-require 'tkextlib/blt.rb'
-
-module Tk::BLT
- module Ted
- extend TkCore
-
- TkCommandNames = ['::blt::ted'.freeze].freeze
-
- ##############################
-
- extend TkItemConfigMethod
-
- class << self
- def __item_cget_cmd(id)
- ['::blt::ted', 'cget', id]
- end
- private :__item_cget_cmd
-
- def __item_config_cmd(id)
- ['::blt::ted', 'configure', id]
- end
- private :__item_config_cmd
-
- private :itemcget, :itemconfigure
- private :itemconfiginfo, :current_itemconfiginfo
-
- def cget(master, option)
- itemconfigure(master, slot, value)
- end
- def configure(master, slot, value=None)
- itemconfigure(master, slot, value)
- end
- def configinfo(master, slot=nil)
- itemconfiginfo(master, slot)
- end
- def current_configinfo(master, slot=nil)
- current_itemconfiginfo(master, slot)
- end
- end
-
- ##############################
-
- def self.edit(master, *args)
- tk_call('::blt::ted', 'edit', master, *args)
- end
- def self.rep(master, *args)
- tk_call('::blt::ted', 'rep', master, *args)
- end
- def self.select(master, *args)
- tk_call('::blt::ted', 'select', master, *args)
- end
- end
-end
diff --git a/ext/tk/lib/tkextlib/blt/tile.rb b/ext/tk/lib/tkextlib/blt/tile.rb
deleted file mode 100644
index 5f5242f299..0000000000
--- a/ext/tk/lib/tkextlib/blt/tile.rb
+++ /dev/null
@@ -1,21 +0,0 @@
-#
-# tkextlib/blt/tile.rb
-# by Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)
-#
-
-require 'tk'
-require 'tkextlib/blt.rb'
-
-module Tk::BLT
- module Tile
- autoload :Button, 'tkextlib/blt/tile/button.rb'
- autoload :CheckButton, 'tkextlib/blt/tile/checkbutton.rb'
- autoload :Checkbutton, 'tkextlib/blt/tile/checkbutton.rb'
- autoload :Radiobutton, 'tkextlib/blt/tile/radiobutton.rb'
- autoload :RadioButton, 'tkextlib/blt/tile/radiobutton.rb'
- autoload :Frame, 'tkextlib/blt/tile/frame.rb'
- autoload :Label, 'tkextlib/blt/tile/label.rb'
- autoload :Scrollbar, 'tkextlib/blt/tile/scrollbar.rb'
- autoload :Toplevel, 'tkextlib/blt/tile/toplevel.rb'
- end
-end
diff --git a/ext/tk/lib/tkextlib/blt/tile/button.rb b/ext/tk/lib/tkextlib/blt/tile/button.rb
deleted file mode 100644
index dd715c8b98..0000000000
--- a/ext/tk/lib/tkextlib/blt/tile/button.rb
+++ /dev/null
@@ -1,16 +0,0 @@
-#
-# tkextlib/blt/tile/button.rb
-# by Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)
-#
-
-require 'tk'
-require 'tk/button'
-require 'tkextlib/blt/tile.rb'
-
-module Tk::BLT
- module Tile
- class Button < TkButton
- TkCommandNames = ['::blt::tile::button'.freeze].freeze
- end
- end
-end
diff --git a/ext/tk/lib/tkextlib/blt/tile/checkbutton.rb b/ext/tk/lib/tkextlib/blt/tile/checkbutton.rb
deleted file mode 100644
index ebe79179a5..0000000000
--- a/ext/tk/lib/tkextlib/blt/tile/checkbutton.rb
+++ /dev/null
@@ -1,17 +0,0 @@
-#
-# tkextlib/blt/tile/checkbutton.rb
-# by Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)
-#
-
-require 'tk'
-require 'tk/checkbutton'
-require 'tkextlib/blt/tile.rb'
-
-module Tk::BLT
- module Tile
- class Checkbutton < TkCheckbutton
- TkCommandNames = ['::blt::tile::checkbutton'.freeze].freeze
- end
- CheckButton = Checkbutton
- end
-end
diff --git a/ext/tk/lib/tkextlib/blt/tile/frame.rb b/ext/tk/lib/tkextlib/blt/tile/frame.rb
deleted file mode 100644
index 10469fd35f..0000000000
--- a/ext/tk/lib/tkextlib/blt/tile/frame.rb
+++ /dev/null
@@ -1,16 +0,0 @@
-#
-# tkextlib/blt/tile/frame.rb
-# by Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)
-#
-
-require 'tk'
-require 'tk/frame'
-require 'tkextlib/blt/tile.rb'
-
-module Tk::BLT
- module Tile
- class Frame < TkFrame
- TkCommandNames = ['::blt::tile::frame'.freeze].freeze
- end
- end
-end
diff --git a/ext/tk/lib/tkextlib/blt/tile/label.rb b/ext/tk/lib/tkextlib/blt/tile/label.rb
deleted file mode 100644
index ec67babd58..0000000000
--- a/ext/tk/lib/tkextlib/blt/tile/label.rb
+++ /dev/null
@@ -1,16 +0,0 @@
-#
-# tkextlib/blt/tile/label.rb
-# by Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)
-#
-
-require 'tk'
-require 'tk/label'
-require 'tkextlib/blt/tile.rb'
-
-module Tk::BLT
- module Tile
- class Label < TkLabel
- TkCommandNames = ['::blt::tile::label'.freeze].freeze
- end
- end
-end
diff --git a/ext/tk/lib/tkextlib/blt/tile/radiobutton.rb b/ext/tk/lib/tkextlib/blt/tile/radiobutton.rb
deleted file mode 100644
index 7573aa08d6..0000000000
--- a/ext/tk/lib/tkextlib/blt/tile/radiobutton.rb
+++ /dev/null
@@ -1,17 +0,0 @@
-#
-# tkextlib/blt/tile/radiobutton.rb
-# by Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)
-#
-
-require 'tk'
-require 'tk/radiobutton'
-require 'tkextlib/blt/tile.rb'
-
-module Tk::BLT
- module Tile
- class Radiobutton < TkRadiobutton
- TkCommandNames = ['::blt::tile::radiobutton'.freeze].freeze
- end
- RadioButton = Radiobutton
- end
-end
diff --git a/ext/tk/lib/tkextlib/blt/tile/scrollbar.rb b/ext/tk/lib/tkextlib/blt/tile/scrollbar.rb
deleted file mode 100644
index ba3bf316f0..0000000000
--- a/ext/tk/lib/tkextlib/blt/tile/scrollbar.rb
+++ /dev/null
@@ -1,16 +0,0 @@
-#
-# tkextlib/blt/tile/scrollbar.rb
-# by Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)
-#
-
-require 'tk'
-require 'tk/scrollbar'
-require 'tkextlib/blt/tile.rb'
-
-module Tk::BLT
- module Tile
- class Scrollbar < TkScrollbar
- TkCommandNames = ['::blt::tile::scrollbar'.freeze].freeze
- end
- end
-end
diff --git a/ext/tk/lib/tkextlib/blt/tile/toplevel.rb b/ext/tk/lib/tkextlib/blt/tile/toplevel.rb
deleted file mode 100644
index 6cc2c91415..0000000000
--- a/ext/tk/lib/tkextlib/blt/tile/toplevel.rb
+++ /dev/null
@@ -1,16 +0,0 @@
-#
-# tkextlib/blt/tile/toplevel.rb
-# by Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)
-#
-
-require 'tk'
-require 'tk/toplevel'
-require 'tkextlib/blt/tile.rb'
-
-module Tk::BLT
- module Tile
- class Toplevel < TkToplevel
- TkCommandNames = ['::blt::tile::toplevel'.freeze].freeze
- end
- end
-end
diff --git a/ext/tk/lib/tkextlib/blt/tree.rb b/ext/tk/lib/tkextlib/blt/tree.rb
deleted file mode 100644
index 07dc7ef7e8..0000000000
--- a/ext/tk/lib/tkextlib/blt/tree.rb
+++ /dev/null
@@ -1,923 +0,0 @@
-#
-# tkextlib/blt/tree.rb
-# by Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)
-#
-
-require 'tk'
-require 'tkextlib/blt.rb'
-
-module Tk::BLT
- class Tree < TkObject
- TkCommandNames = ['::blt::tree'.freeze].freeze
-
- ###################################
-
- class Node < TkObject
- TreeNodeID_TBL = TkCore::INTERP.create_table
- TkCore::INTERP.init_ip_env{ TreeNodeID_TBL.clear }
-
- def self.id2obj(tree, id)
- tpath = tree.path
- return id unless TreeNodeID_TBL[tpath]
- if TreeNodeID_TBL[tpath][id]
- TreeNodeID_TBL[tpath][id]
- else
- begin
- self.new(tree, nil, 'node'=>Integer(id))
- rescue
- id
- end
- end
- end
-
- def self.new(tree, parent, keys={})
- keys = _symbolkey2str(keys)
- tpath = tree.path
-
- if (id = keys['node']) && (obj = TreeNodeID_TBL[tpath][id])
- keys.delete('node')
- tk_call(tree.path, 'move', id, parent, keys) if parent
- return obj
- end
-
- super(tree, parent, keys)
- end
-
- def initialize(tree, parent, keys={})
- @parent = @tree = tree
- @tpath = @parent.path
-
- parent = tk_call(@tpath, 'root') unless parent
-
- if (id = keys['node']) && bool(tk_call(@tpath, 'exists', id))
- @path = @id = id
- keys.delete('node')
- tk_call(@tpath, 'move', @id, parent, keys) if parent
- else
- @path = @id = tk_call(@tpath, 'insert', parent, keys)
- end
-
- TreeNodeID_TBL[@tpath] = {} unless TreeNodeID_TBL[@tpath]
- TreeNodeID_TBL[@tpath][@id] = self
- end
-
- def id
- @id
- end
-
- def apply(keys={})
- @tree.apply(@id, keys)
- self
- end
-
- def children()
- @tree.children(@id)
- end
-
- def copy(parent, keys={})
- @tree.copy(@id, parent, keys)
- end
- def copy_to(dest_tree, parent, keys={})
- @tree.copy_to(@id, dest_tree, parent, keys)
- end
-
- def degree()
- @tree.degree(@id)
- end
-
- def delete()
- @tree.delete(@id)
- self
- end
-
- def depth()
- @tree.depth(@id)
- end
-
- def dump()
- @tree.dump(@id)
- end
-
- def dump_to_file(file)
- @tree.dump_to_file(@id, file)
- self
- end
-
- def exist?(keys={})
- @tree.exist?(@id, keys)
- end
-
- def find(keys={})
- @tree.find(@id, keys)
- end
-
- def find_child(label)
- @tree.find_child(@id, label)
- end
-
- def first_child()
- @tree.first_child(@id)
- end
-
- def get()
- @tree.get(@id)
- end
- def get_value(key, default_val=None)
- @tree.get_value(@id, key, default_val)
- end
-
- def index()
- @tree.index(@id)
- end
-
- def leaf?()
- @tree.leaf?(@id)
- end
- def link?()
- @tree.link?(@id)
- end
- def root?()
- @tree.root?(@id)
- end
-
- def keys()
- @tree.keys(@id)
- end
-
- def label(text = nil)
- @tree.label(@id, nil)
- end
- def label=(text)
- @tree.label(@id, text)
- end
-
- def last_child()
- @tree.last_child(@id)
- end
-
- def move(dest, keys={})
- @tree.keys(@id, dest, keys)
- self
- end
-
- def next()
- @tree.next(@id)
- end
-
- def next_sibling()
- @tree.next_sibling(@id)
- end
-
- def parent()
- @tree.parent(@id)
- end
-
- def fullpath()
- @tree.fullpath(@id)
- end
-
- def position()
- @tree.position(@id)
- end
-
- def previous()
- @tree.previous(@id)
- end
-
- def prev_sibling()
- @tree.prev_sibling(@id)
- end
-
- def restore(str, keys={})
- @tree.restore(@id, str, keys)
- self
- end
- def restore_overwrite(str, keys={})
- @tree.restore_overwrite(@id, str, keys)
- self
- end
-
- def restore_from_file(file, keys={})
- @tree.restore_from_file(@id, file, keys)
- self
- end
- def restore_overwrite_from_file(file, keys={})
- @tree.restore_overwrite_from_file(@id, file, keys)
- self
- end
-
- def root()
- @tree.root(@id)
- self
- end
-
- def set(data)
- @tree.set(@id, data)
- self
- end
-
- def size()
- @tree.size(@id)
- end
-
- def sort(keys={})
- @tree.sort(@id, keys)
- self
- end
-
- def type(key)
- @tree.type(@id, key)
- end
-
- def unset(*keys)
- @tree.unset(@id, *keys)
- self
- end
-
- def values(key=None)
- @tree.values(@id, key)
- end
- end
-
- ###################################
-
- class Tag < TkObject
- TreeTagID_TBL = TkCore::INTERP.create_table
- TkCore::INTERP.init_ip_env{ TreeTagID_TBL.clear }
- TreeTag_ID = ['blt_tree_tag'.freeze, '00000'.taint].freeze
-
- def self.id2obj(tree, id)
- tpath = tree.path
- return id unless TreeTagID_TBL[tpath]
- if TreeTagID_TBL[tpath][id]
- TreeTagID_TBL[tpath][id]
- else
- self.new(tree, id)
- end
- end
-
- def initialize(tree, tag_str = nil)
- @parent = @tree = tree
- @tpath = @parent.path
-
- if tag_str
- @path = @id = tag_str.dup.freeze
- else
- @path = @id = TreeTag_ID.join(TkCore::INTERP._ip_id_)
- TreeTagID_TBL[@id] = self
- TreeTag_ID[1].succ!
- end
- TreeTagID_TBL[@tpath] = {} unless TreeTagID_TBL[@tpath]
- TreeTagID_TBL[@tpath][@id] = self
- end
-
- def id
- @id
- end
-
- def add(*nodes)
- tk_call(@tpath, 'tag', 'add', @id, *nodes)
- self
- end
-
- def delete(*nodes)
- tk_call(@tpath, 'tag', 'delete', @id, *nodes)
- self
- end
-
- def forget()
- tk_call(@tpath, 'tag', 'forget', @id)
- TreeTagID_TBL[@tpath].delete(@id)
- self
- end
-
- def nodes()
- simplelist(tk_call(@tpath, 'tag', 'nodes', @id)).collect{|node|
- Tk::BLT::Tree::Node.id2obj(@path, node)
- }
- end
-
- def set(node)
- tk_call(@tpath, 'tag', 'set', node, @id)
- self
- end
-
- def unset(node)
- tk_call(@tpath, 'tag', 'unset', node, @id)
- self
- end
- end
-
- ###################################
-
- class Notify < TkObject
- NotifyID_TBL = TkCore::INTERP.create_table
- TkCore::INTERP.init_ip_env{ NotifyID_TBL.clear }
-
- def self.id2obj(tree, id)
- tpath = tree.path
- return id unless NotifyID_TBL[tpath]
- if NotifyID_TBL[tpath][id]
- NotifyID_TBL[tpath][id]
- else
- begin
- self.new([tree, id])
- rescue
- id
- end
- end
- end
-
- def self.new(tree, *args, &b)
- if tree.kind_of?(Array)
- # not create
- if obj = NotifyID_TBL[tree[0].path][tree[1]]
- return obj
- else
- return super(false, tree[0], tree[1])
- end
- end
-
- super(true, tree, *args, &b)
- end
-
- def initialize(create, tree, *args, &b)
- @parent = @tree = tree
- @tpath = @parent.path
-
- unless create
- @path = @id = args[0]
- return
- end
-
- # if args[0].kind_of?(Proc) || args[0].kind_of?(Method)
- if TkComm._callback_entry?(args[0])
- cmd = args.shift
- # elsif args[-1].kind_of?(Proc) || args[-1].kind_of?(Method)
- elsif TkComm._callback_entry?(args[-1])
- cmd = args.pop
- elsif b
- cmd = Proc.new(&b)
- else
- fail ArgumentError, "lack of 'command' argument"
- end
-
- args = args.collect{|arg| '-' << arg.to_s}
-
- args << proc{|id, type|
- cmd.call(Tk::BLT::Tree::Node.id2obj(@tree, id),
- ((type[0] == ?-)? type[1..-1]: type))
- }
-
- @path = @id = tk_call(@tpath, 'notify', 'create', *args)
- end
-
- def id
- @id
- end
-
- def delete()
- tk_call(@tpath, 'notify', 'delete', @id)
- NotifyID_TBL[tpath].delete(@id)
- self
- end
-
- def info()
- lst = simplelist(tk_call(@tpath, 'notify', 'info', id))
- lst[0] = Tk::BLT::Tree::Notify.id2obj(@tree, lst[0])
- lst[1] = simplelist(lst[1]).collect{|flag| flag[1..-1]}
- lst[2] = tk_tcl2ruby(lst[2])
- lst
- end
- end
-
- ###################################
-
- class Trace < TkObject
- TraceID_TBL = TkCore::INTERP.create_table
- TkCore::INTERP.init_ip_env{ TraceID_TBL.clear }
-
- def self.id2obj(tree, id)
- tpath = tree.path
- return id unless TraceID_TBL[tpath]
- if TraceID_TBL[tpath][id]
- TraceID_TBL[tpath][id]
- else
- begin
- self.new([tree, id])
- rescue
- id
- end
- end
- end
-
- def self.new(tree, *args, &b)
- if tree.kind_of?(Array)
- # not create
- if obj = TraceID_TBL[tree[0].path][tree[1]]
- return obj
- else
- return super(false, tree[0], tree[1])
- end
- end
-
- super(true, tree, *args, &b)
- end
-
- def initialize(create, tree, node, key, opts, cmd=nil, &b)
- @parent = @tree = tree
- @tpath = @parent.path
-
- unless create
- @path = @id = node # == traceID
- return
- end
-
- if !cmd
- if b
- cmd = Proc.new(&b)
- else
- fail ArgumentError, "lack of 'command' argument"
- end
- end
-
- @path = @id = tk_call(@tpath, 'trace', 'create', node, key, opts,
- proc{|t, id, k, ops|
- tobj = Tk::BLT::Tree.id2obj(t)
- if tobj.kind_of?(Tk::BLT::Tree)
- nobj = Tk::BLT::Tree::Node.id2obj(tobj, id)
- else
- nobj = id
- end
- cmd.call(tobj, nobj, k, ops)
- })
- end
-
- def id
- @id
- end
-
- def delete()
- tk_call(@tpath, 'trace', 'delete', @id)
- TraceID_TBL[tpath].delete(@id)
- self
- end
-
- def info()
- lst = simplelist(tk_call(@tpath, 'trace', 'info', id))
- lst[0] = Tk::BLT::Tree::Trace.id2obj(@tree, lst[0])
- lst[2] = simplelist(lst[2])
- lst[3] = tk_tcl2ruby(lst[3])
- lst
- end
- end
-
- ###################################
-
- TreeID_TBL = TkCore::INTERP.create_table
- Tree_ID = ['blt_tree'.freeze, '00000'.taint].freeze
-
- def __keyonly_optkeys
- {
- # apply / find command
- 'invert'=>nil, 'leafonly'=>nil, 'nocase'=>nil,
-
- # apply / find / sort command
- 'path'=>nil,
-
- # copy / restore / restorefile command
- 'overwrite'=>nil,
-
- # copy command
- 'recurse'=>nil, 'tags'=>nil,
-
- # sort command
- 'ascii'=>nil, 'decreasing'=>nil, 'disctionary'=>nil,
- 'integer'=>nil, 'real'=>nil, 'recurse'=>nil, 'reorder'=>nil,
- }
- end
-
- def self.id2obj(id)
- TreeID_TBL[id]? TreeID_TBL[id]: id
- end
-
- def self.names(pat = None)
- simplelist(tk_call('::blt::tree', 'names', pat)).collect{|name|
- id2obj(name)
- }
- end
-
- def self.destroy(*names)
- tk_call('::blt::tree', 'destroy',
- *(names.collect{|n| (n.kind_of?(Tk::BLT::Tree))? n.id: n }) )
- end
-
- def self.new(name = nil)
- return TreeID_TBL[name] if name && TreeID_TBL[name]
- super(name)
- end
-
- def initialzie(name = nil)
- if name
- @path = @id = name
- else
- @path = @id = Tree_ID.join(TkCore::INTERP._ip_id_)
- TreeID_TBL[@id] = self
- Tree_ID[1].succ!
- end
- TreeID_TBL[@id] = self
- tk_call('::blt::tree', 'create', @id)
- end
-
- def __destroy_hook__
- Tk::BLT::Tree::Node::TreeNodeID_TBL.delete(@path)
- Tk::BLT::Tree::Tag::TreeTagID_TBL.delete(@path)
- Tk::BLT::Tree::Notify::NotifyID_TBL.delete(@path)
- Tk::BLT::Tree::Trace::TraceID_TBL.delete(@path)
- end
-
- def tagid(tag)
- if tag.kind_of?(Tk::BLT::Tree::Node) ||
- tag.kind_of?(Tk::BLT::Tree::Tag) ||
- tag.kind_of?(Tk::BLT::Tree::Notify) ||
- tag.kind_of?(Tk::BLT::Tree::Trace)
- tag.id
- else
- tag # maybe an Array of configure paramters
- end
- end
-
- def destroy()
- tk_call('::blt::tree', 'destroy', @id)
- self
- end
-
- def ancestor(node1, node2)
- Tk::BLT::Tree::Node.id2obj(self, tk_call('::blt::tree', 'ancestor',
- tagid(node1), tagid(node2)))
- end
-
- def apply(node, keys={})
- tk_call('::blt::tree', 'apply', tagid(node), __conv_keyonly_opts(keys))
- self
- end
-
- def attach(tree_obj)
- tk_call('::blt::tree', 'attach', tree_obj)
- self
- end
-
- def children(node)
- simplelist(tk_call('::blt::tree', 'children', tagid(node))).collect{|n|
- Tk::BLT::Tree::Node.id2obj(self, n)
- }
- end
-
- def copy(src, parent, keys={})
- id = tk_call('::blt::tree', 'copy', tagid(src), tagid(parent),
- __conv_keyonly_opts(keys))
- Tk::BLT::Tree::Node.new(self, nil, 'node'=>id)
- end
- def copy_to(src, dest_tree, parent, keys={})
- return copy(src, parent, keys={}) unless dest_tree
-
- id = tk_call('::blt::tree', 'copy', tagid(src), dest_tree,
- tagid(parent), __conv_keyonly_opts(keys))
- Tk::BLT::Tree::Node.new(dest_tree, nil, 'node'=>id)
- end
-
- def degree(node)
- number(tk_call('::blt::tree', 'degree', tagid(node)))
- end
-
- def delete(*nodes)
- tk_call('::blt::tree', 'delete', *(nodes.collect{|node| tagid(node)}))
- nodes.each{|node|
- if node.kind_of?(Tk::BLT::Tree::Node)
- Tk::BLT::Tree::Node::TreeNodeID_TBL[@path].delete(node.id)
- else
- Tk::BLT::Tree::Node::TreeNodeID_TBL[@path].delete(node.to_s)
- end
- }
- self
- end
-
- def depth(node)
- number(tk_call('::blt::tree', 'depth', tagid(node)))
- end
-
- def dump(node)
- simplelist(tk_call('::blt::tree', 'dump', tagid(node))).collect{|n|
- simplelist(n)
- }
- end
-
- def dump_to_file(node, file)
- tk_call('::blt::tree', 'dumpfile', tagid(node), file)
- self
- end
-
- def exist?(node, key=None)
- bool(tk_call('::blt::tree', 'exists', tagid(node), key))
- end
-
- def find(node, keys={})
- simplelist(tk_call('::blt::tree', 'find', tagid(node),
- __conv_keyonly_opts(keys))).collect{|n|
- Tk::BLT::Tree::Node.id2obj(self, n)
- }
- end
-
- def find_child(node, label)
- ret = tk_call('::blt::tree', 'findchild', tagid(node), label)
- (ret == '-1')? nil: Tk::BLT::Tree::Node.id2obj(self, ret)
- end
-
- def first_child(node)
- ret = tk_call('::blt::tree', 'firstchild', tagid(node))
- (ret == '-1')? nil: Tk::BLT::Tree::Node.id2obj(self, ret)
- end
-
- def get(node)
- Hash[*simplelist(tk_call('::blt::tree', 'get', tagid(node)))]
- end
- def get_value(node, key, default_val=None)
- tk_call('::blt::tree', 'get', tagid(node), key, default_val)
- end
-
- def index(node)
- Tk::BLT::Tree::Node.id2obj(self,
- tk_call('::blt::tree', 'index', tagid(node)))
- end
-
- def insert(parent, keys={})
- id = tk_call('::blt::tree', 'insert', tagid(parent), keys)
- Tk::BLT::Tree::Node.new(self, nil, 'node'=>id)
- end
-
- def ancestor?(node1, node2)
- bool(tk_call('::blt::tree', 'is', 'ancestor',
- tagid(node1), tagid(node2)))
- end
- def before?(node1, node2)
- bool(tk_call('::blt::tree', 'is', 'before',
- tagid(node1), tagid(node2)))
- end
- def leaf?(node)
- bool(tk_call('::blt::tree', 'is', 'leaf', tagid(node)))
- end
- def link?(node)
- bool(tk_call('::blt::tree', 'is', 'link', tagid(node)))
- end
- def root?(node)
- bool(tk_call('::blt::tree', 'is', 'root', tagid(node)))
- end
-
- def keys(node, *nodes)
- if nodes.empty?
- simplelist(tk_call('blt::tree', 'keys', tagid(node)))
- else
- simplelist(tk_call('blt::tree', 'keys', tagid(node),
- *(nodes.collect{|n| tagid(n)}))).collect{|lst|
- simplelist(lst)
- }
- end
- end
-
- def label(node, text=nil)
- if text
- tk_call('::blt::tree', 'label', tagid(node), text)
- text
- else
- tk_call('::blt::tree', 'label', tagid(node))
- end
- end
-
- def last_child(node)
- ret = tk_call('::blt::tree', 'lastchild', tagid(node))
- (ret == '-1')? nil: Tk::BLT::Tree::Node.id2obj(self, ret)
- end
-
- def link(parent, node, keys={})
- ret = tk_call('::blt::tree', 'link', tagid(parent), tagid(node),
- __conv_keyonly_opts(keys))
- (ret == '-1')? nil: Tk::BLT::Tree::Node.id2obj(self, ret)
- end
-
- def move(node, dest, keys={})
- tk_call('::blt::tree', 'move', tagid(node), tagid(dest), keys)
- self
- end
-
- def next(node)
- ret = tk_call('::blt::tree', 'next', tagid(node))
- (ret == '-1')? nil: Tk::BLT::Tree::Node.id2obj(self, ret)
- end
-
- def next_sibling(node)
- ret = tk_call('::blt::tree', 'nextsibling', tagid(node))
- (ret == '-1')? nil: Tk::BLT::Tree::Node.id2obj(self, ret)
- end
-
- def notify_create(*args, &b)
- Tk::BLT::Tree::Notify.new(self, *args, &b)
- end
-
- def notify_delete(id)
- if id.kind_of?(Tk::BLT::Tree::Notify)
- id.delete
- else
- tk_call(@path, 'notify', 'delete', id)
- Tk::BLT::Tree::Notify::NotifyID_TBL[@path].delete(id.to_s)
- end
- self
- end
-
- def notify_info(id)
- lst = simplelist(tk_call(@path, 'notify', 'info', tagid(id)))
- lst[0] = Tk::BLT::Tree::Notify.id2obj(self, lst[0])
- lst[1] = simplelist(lst[1]).collect{|flag| flag[1..-1]}
- lst[2] = tk_tcl2ruby(lst[2])
- lst
- end
-
- def notify_names()
- tk_call(@path, 'notify', 'names').collect{|id|
- Tk::BLT::Tree::Notify.id2obj(self, id)
- }
- end
-
- def parent(node)
- ret = tk_call('::blt::tree', 'parent', tagid(node))
- (ret == '-1')? nil: Tk::BLT::Tree::Node.id2obj(self, ret)
- end
-
- def fullpath(node)
- tk_call('::blt::tree', 'path', tagid(node))
- end
-
- def position(node)
- number(tk_call('::blt::tree', 'position', tagid(node)))
- end
-
- def previous(node)
- ret = tk_call('::blt::tree', 'previous', tagid(node))
- (ret == '-1')? nil: Tk::BLT::Tree::Node.id2obj(self, ret)
- end
-
- def prev_sibling(node)
- ret = tk_call('::blt::tree', 'prevsibling', tagid(node))
- (ret == '-1')? nil: Tk::BLT::Tree::Node.id2obj(self, ret)
- end
-
- def restore(node, str, keys={})
- tk_call('::blt::tree', 'restore', tagid(node), str,
- __conv_keyonly_opts(keys))
- self
- end
- def restore_overwrite(node, str, keys={})
- keys = __conv_keyonly_opts(keys)
- keys.delete('overwrite')
- keys.delete(:overwrite)
- tk_call('::blt::tree', 'restore', tagid(node), str, '-overwrite', keys)
- self
- end
-
- def restore_from_file(node, file, keys={})
- tk_call('::blt::tree', 'restorefile', tagid(node), file,
- __conv_keyonly_opts(keys))
- self
- end
- def restore_overwrite_from_file(node, file, keys={})
- keys = __conv_keyonly_opts(keys)
- keys.delete('overwrite')
- keys.delete(:overwrite)
- tk_call('::blt::tree', 'restorefile', tagid(node), file,
- '-overwrite', keys)
- self
- end
-
- def root(node=None)
- Tk::BLT::Tree::Node.id2obj(self, tk_call('::blt::tree', 'root',
- tagid(node)))
- end
-
- def set(node, data)
- unless data.kind_of?(Hash)
- fail ArgumentError, 'Hash is expected for data'
- end
- args = []
- data.each{|k, v| args << k << v}
- tk_call('::blt::tree', 'set', tagid(node), *args)
- self
- end
-
- def size(node)
- number(tk_call('::blt::tree', 'size', tagid(node)))
- end
-
- def sort(node, keys={})
- tk_call('::blt::tree', 'sort', tagid(node), __conv_keyonly_opts(keys))
- self
- end
-
- def tag_add(tag, *nodes)
- tk_call(@path, 'tag', 'add', tagid(tag), *(nodes.collect{|n| tagid(n)}))
- self
- end
-
- def tag_delete(tag, *nodes)
- tk_call(@path, 'tag', 'delete', tagid(tag),
- *(nodes.collect{|n| tagid(n)}))
- self
- end
-
- def tag_forget(tag)
- tag = tag.id if tag.kind_of?(Tk::BLT::Tree::Tag)
- tk_call(@path, 'tag', 'forget', tag)
- TreeTagID_TBL[@path].delete(tag)
- self
- end
-
- def tag_get(node, *patterns)
- simplelist(tk_call(@tpath, 'tag', 'get', tagid(node),
- *(patterns.collect{|pat| tagid(pat)}))).collect{|str|
- Tk::BLT::Tree::Tag.id2obj(self, str)
- }
- end
-
- def tag_names(node = None)
- simplelist(tk_call(@tpath, 'tag', 'names', tagid(node))).collect{|str|
- Tk::BLT::Tree::Tag.id2obj(self, str)
- }
- end
-
- def tag_nodes(tag)
- simplelist(tk_call(@tpath, 'tag', 'nodes', tagid(tag))).collect{|node|
- Tk::BLT::Tree::Node.id2obj(self, node)
- }
- end
-
- def tag_set(node, *tags)
- tk_call(@path, 'tag', 'set', tagid(node), *(tags.collect{|t| tagid(t)}))
- self
- end
-
- def tag_unset(node, *tags)
- tk_call(@path, 'tag', 'unset', tagid(node),
- *(tags.collect{|t| tagid(t)}))
- self
- end
-
- def trace_create(*args, &b)
- Tk::BLT::Tree::Trace.new(self, *args, &b)
- end
-
-=begin
- def trace_delete(*args)
- args.each{|id|
- if id.kind_of?(Tk::BLT::Tree::Trace)
- id.delete
- else
- tk_call(@path, 'trace', 'delete', id)
- Tk::BLT::Tree::Trace::TraceID_TBL[@path].delete(id.to_s)
- end
- self
- }
- end
-=end
- def trace_delete(*args)
- args = args.collect{|id| tagid(id)}
- tk_call(@path, 'trace', 'delete', *args)
- args.each{|id| Tk::BLT::Tree::Trace::TraceID_TBL[@path].delete(id.to_s)}
- self
- end
-
- def trace_info(id)
- lst = simplelist(tk_call(@path, 'trace', 'info', tagid(id)))
- lst[0] = Tk::BLT::Tree::Trace.id2obj(self, lst[0])
- lst[2] = simplelist(lst[2])
- lst[3] = tk_tcl2ruby(lst[3])
- lst
- end
-
- def trace_names()
- tk_call(@path, 'trace', 'names').collect{|id|
- Tk::BLT::Tree::Trace.id2obj(self, id)
- }
- end
-
- def type(node, key)
- tk_call('::blt::tree', 'type', tagid(node), key)
- end
-
- def unset(node, *keys)
- tk_call('::blt::tree', 'unset', tagid(node), *keys)
- self
- end
-
- def values(node, key=None)
- simplelist(tk_call('::blt::tree', 'values', tagid(node), key))
- end
- end
-end
diff --git a/ext/tk/lib/tkextlib/blt/treeview.rb b/ext/tk/lib/tkextlib/blt/treeview.rb
deleted file mode 100644
index 0343d28b9c..0000000000
--- a/ext/tk/lib/tkextlib/blt/treeview.rb
+++ /dev/null
@@ -1,1146 +0,0 @@
-#
-# tkextlib/blt/treeview.rb
-# by Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)
-#
-
-require 'tk'
-require 'tkextlib/blt.rb'
-require 'tk/validation.rb'
-
-module Tk::BLT
- class Treeview < TkWindow
- module ConfigMethod
- end
-
- module TagOrID_Methods
- end
-
- class Node < TkObject
- end
-
- class Tag < TkObject
- end
- end
-
- class Hiertable < Treeview
- end
-end
-
-######################################
-
-module Tk::BLT::Treeview::ConfigMethod
- include TkItemConfigMethod
-
- def __item_boolval_optkeys(id)
- case id
- when Array
- # id := [ 'column', name ]
- ['edit', 'hide']
- when 'sort'
- ['decreasing']
- else
- []
- end
- end
- private :__item_boolval_optkeys
-
- def __item_strval_optkeys(id)
- case id
- when Array
- # id := [ 'column', name ]
- super() << 'titleforeground' << 'titleshadow'
- when 'sort'
- ['decreasing']
- else
- []
- end
- end
- private :__item_strval_optkeys
-
- def __item_listval_optkeys(id)
- case id
- when 'entry'
- ['bindtags']
- else
- []
- end
- end
- private :__item_listval_optkeys
-
- def __item_cget_cmd(id)
- if id.kind_of?(Array)
- # id := [ type, name ]
- [self.path, id[0], 'cget', id[1]]
- else
- [self.path, id, 'cget']
- end
- end
- private :__item_cget_cmd
-
- def __item_config_cmd(id)
- if id.kind_of?(Array)
- # id := [ type, name ]
- [self.path, id[0], 'configure', id[1]]
- else
- [self.path, id, 'configure']
- end
- end
- private :__item_config_cmd
-
- def __item_pathname(id)
- if id.kind_of?(Array)
- id = tagid(id[1])
- end
- [self.path, id].join(';')
- end
- private :__item_pathname
-
- def column_cget(name, option)
- itemcget(['column', name], option)
- end
- def column_configure(name, slot, value=None)
- itemconfigure(['column', name], slot, value)
- end
- def column_configinfo(name, slot=nil)
- itemconfiginfo(['column', name], slot)
- end
- def current_column_configinfo(name, slot=nil)
- current_itemconfiginfo(['column', name], slot)
- end
-
- def button_cget(option)
- itemcget('button', option)
- end
- def button_configure(slot, value=None)
- itemconfigure('button', slot, value)
- end
- def button_configinfo(slot=nil)
- itemconfiginfo('button', slot)
- end
- def current_button_configinfo(slot=nil)
- current_itemconfiginfo('button', slot)
- end
-
- def entry_cget(option)
- ret = itemcget('entry', option)
- if option == 'bindtags' || option == :bindtags
- ret.collect{|tag| TkBindTag.id2obj(tag)}
- else
- ret
- end
- end
- def entry_configure(slot, value=None)
- itemconfigure('entry', slot, value)
- end
- def entry_configinfo(slot=nil)
- ret = itemconfiginfo('entry', slot)
-
- if TkComm::GET_CONFIGINFO_AS_ARRAY
- if slot
- if slot == 'bindtags' || slot == :bindtags
- ret[-2] = ret[-2].collect{|tag| TkBindTag.id2obj(tag)}
- ret[-1] = ret[-1].collect{|tag| TkBindTag.id2obj(tag)}
- end
- else
- inf = ret.assoc('bindtags')
- inf[-2] = inf[-2].collect{|tag| TkBindTag.id2obj(tag)}
- inf[-1] = inf[-1].collect{|tag| TkBindTag.id2obj(tag)}
- end
-
- else # ! TkComm::GET_CONFIGINFO_AS_ARRAY
- if (inf = ret['bindtags'])
- inf[-2] = inf[-2].collect{|tag| TkBindTag.id2obj(tag)}
- inf[-1] = inf[-1].collect{|tag| TkBindTag.id2obj(tag)}
- ret['bindtags'] = inf
- end
- end
-
- ret
- end
- def current_entry_configinfo(slot=nil)
- ret = current_itemconfiginfo('entry', slot)
-
- if (val = ret['bindtags'])
- ret['bindtags'] = val.collect{|tag| TkBindTag.id2obj(tag)}
- end
-
- ret
- end
-
- def sort_cget(option)
- itemcget('sort', option)
- end
- def sort_configure(slot, value=None)
- itemconfigure('sort', slot, value)
- end
- def sort_configinfo(slot=nil)
- itemconfiginfo('sort', slot)
- end
- def current_sort_configinfo(slot=nil)
- current_itemconfiginfo('sort', slot)
- end
-
- def text_cget(option)
- itemcget('text', option)
- end
- def text_configure(slot, value=None)
- itemconfigure('text', slot, value)
- end
- def text_configinfo(slot=nil)
- itemconfiginfo('text', slot)
- end
- def current_text_configinfo(slot=nil)
- current_itemconfiginfo('text', slot)
- end
-
- private :itemcget, :itemconfigure
- private :itemconfiginfo, :current_itemconfiginfo
-end
-
-class Tk::BLT::Treeview
- TkCommandNames = ['::blt::treeview'.freeze].freeze
- WidgetClassName = 'TreeView'.freeze
- WidgetClassNames[WidgetClassName] = self
-
- include Scrollable
- include ValidateConfigure
- include ItemValidateConfigure
- include Tk::BLT::Treeview::ConfigMethod
-
- ########################
-
- def __boolval_optkeys
- ['autocreate', 'allowduplicates', 'exportselection', 'flat', 'hideroot',
- 'newtags', 'showtitles', 'sortselection']
- end
- private :__boolval_optkeys
-
- def __strval_optkeys
- super() + ['focusforeground', 'linecolor', 'separator', 'trim']
- end
- private :__strval_optkeys
-
- ########################
-
- class OpenCloseCommand < TkValidateCommand
- class ValidateArgs < TkUtil::CallbackSubst
- KEY_TBL = [
- [ ?W, ?w, :widget ],
- [ ?p, ?s, :name ],
- [ ?P, ?s, :fullpath ],
- [ ?#, ?x, :node_id ],
- nil
- ]
-
- PROC_TBL = [
- [ ?x, TkComm.method(:num_or_str) ],
- [ ?s, TkComm.method(:string) ],
- [ ?w, TkComm.method(:window) ],
- nil
- ]
-
- _setup_subst_table(KEY_TBL, PROC_TBL);
-
- def self.ret_val(val)
- val
- end
- end
-
- def self._config_keys
- ['opencommand', 'closecomand']
- end
- end
-
- def __validation_class_list
- super() << OpenCloseCommand
- end
-
- Tk::ValidateConfigure.__def_validcmd(binding, OpenCloseCommand)
-
- ########################
-
- def __item_validation_class_list(id)
- case id
- when 'entry'
- super(id) << OpenCloseCommand
- else
- super(id)
- end
- end
-
- Tk::ItemValidateConfigure.__def_validcmd(binding, OpenCloseCommand)
-
- ########################
-
- def __destroy_hook__
- Tk::BLT::Treeview::Node::TreeNodeID_TBL.delete(@path)
- Tk::BLT::Treeview::Tag::TreeTagID_TBL.delete(@path)
- end
-
- def tagid(tag)
- if tag.kind_of?(Tk::BLT::Treeview::Node) \
- || tag.kind_of?(Tk::BLT::Treeview::Tag)
- tag.id
- else
- tag # maybe an Array of configure paramters
- end
- end
- private :tagid
-
- def tagid2obj(tagid)
- if tagid.kind_of?(Integer)
- Tk::BLT::Treeview::Node.id2obj(self, tagid.to_s)
- elsif tagid.kind_of?(String)
- if tagid =~ /^\d+$/
- Tk::BLT::Treeview::Node.id2obj(self, tagid)
- else
- Tk::BLT::Treeview::Tag.id2obj(self, tagid)
- end
- else
- tagid
- end
- end
-
- def bbox(*tags)
- list(tk_send('bbox', *(tags.collect{|tag| tagid(tag)})))
- end
-
- def screen_bbox(*tags)
- list(tk_send('bbox', '-screen', *(tags.collect{|tag| tagid(tag)})))
- end
-
- def tag_bind(tag, seq, *args)
- if TkComm._callback_entry?(args[0]) || !block_given?
- cmd = args.shift
- else
- cmd = Proc.new
- end
- _bind([@path, 'bind', tagid(tag)], seq, cmd, *args)
- self
- end
- def tag_bind_append(tag, seq, *args)
- if TkComm._callback_entry?(args[0]) || !block_given?
- cmd = args.shift
- else
- cmd = Proc.new
- end
- _bind_append([@path, 'bind', tagid(tag)], seq, cmd, *args)
- self
- end
- def tag_bind_remove(tag, seq)
- _bind_remove([@path, 'bind', tagid(tag)], seq)
- self
- end
- def tag_bindinfo(tag, seq=nil)
- _bindinfo([@path, 'bind', tagid(tag)], seq)
- end
-
- def button_activate(tag)
- tk_send('button', 'activate', tagid(tag))
- self
- end
-
- def button_bind(tag, seq, *args)
- if TkComm._callback_entry?(args[0]) || !block_given?
- cmd = args.shift
- else
- cmd = Proc.new
- end
- _bind([@path, 'button', 'bind', tagid(tag)], seq, cmd, *args)
- self
- end
- def button_bind_append(tag, seq, *args)
- if TkComm._callback_entry?(args[0]) || !block_given?
- cmd = args.shift
- else
- cmd = Proc.new
- end
- _bind_append([@path, 'button', 'bind', tagid(tag)], seq, cmd, *args)
- self
- end
- def button_bind_remove(tag, seq)
- _bind_remove([@path, 'button', 'bind', tagid(tag)], seq)
- self
- end
- def button_bindinfo(tag, seq=nil)
- _bindinfo([@path, 'button', 'bind', tagid(tag)], seq)
- end
-
- def close(*tags)
- tk_send('close', *(tags.collect{|tag| tagid(tag)}))
- self
- end
- def close_recurse(*tags)
- tk_send('close', '-recurse', *(tags.collect{|tag| tagid(tag)}))
- self
- end
-
- def column_activate(column=None)
- if column == None
- tk_send('column', 'activate')
- else
- tk_send('column', 'activate', column)
- self
- end
- end
-
- def column_delete(*fields)
- tk_send('column', 'delete', *fields)
- self
- end
- def column_insert(pos, field, *opts)
- tk_send('column', 'insert', pos, field, *opts)
- self
- end
- def column_invoke(field)
- tk_send('column', 'invoke', field)
- self
- end
- def column_move(name, dest)
- tk_send('column', 'move', name, dest)
- self
- end
- def column_names()
- simplelist(tk_send('column', 'names'))
- end
- def column_nearest(x, y=None)
- tk_send('column', 'nearest', x, y)
- end
-
- def curselection
- simplelist(tk_send('curselection')).collect{|id| tagid2obj(id)}
- end
-
- def delete(*tags)
- tk_send('delete', *(tags.collect{|tag| tagid(tag)}))
- self
- end
-
- def entry_activate(tag)
- tk_send('entry', 'activate', tagid(tag))
- self
- end
- def entry_children(tag, first=None, last=None)
- simplelist(tk_send('entry', 'children', tagid(tag),
- first, last)).collect{|id| tagid2obj(id)}
- end
- def entry_delete(tag, first=None, last=None)
- tk_send('entry', 'delete', tagid(tag), first, last)
- end
- def entry_before?(tag1, tag2)
- bool(tk_send('entry', 'isbefore', tagid(tag1), tagid(tag2)))
- end
- def entry_hidden?(tag)
- bool(tk_send('entry', 'ishidden', tagid(tag)))
- end
- def entry_open?(tag)
- bool(tk_send('entry', 'isopen', tagid(tag)))
- end
-
- def entry_size(tag)
- number(tk_send('entry', 'size', tagid(tag)))
- end
- def entry_size_recurse(tag)
- number(tk_send('entry', 'size', '-recurse', tagid(tag)))
- end
-
- def _search_flags(keys)
- keys = _symbolkey2str(keys)
- keys['exact'] = None if keys.delete('exact')
- keys['glob'] = None if keys.delete('glob')
- keys['regexp'] = None if keys.delete('regexp')
- keys['nonmatching'] = None if keys.delete('nonmatching')
- end
- private :_search_flags
-
- ################################
-
- class FindExecFlagValue < TkValidateCommand
- class ValidateArgs < TkUtil::CallbackSubst
- KEY_TBL = [
- [ ?W, ?w, :widget ],
- [ ?p, ?s, :name ],
- [ ?P, ?s, :fullpath ],
- [ ?#, ?x, :node_id ],
- nil
- ]
-
- PROC_TBL = [
- [ ?x, TkComm.method(:num_or_str) ],
- [ ?s, TkComm.method(:string) ],
- [ ?w, TkComm.method(:window) ],
- nil
- ]
-
- _setup_subst_table(KEY_TBL, PROC_TBL);
-
- def self.ret_val(val)
- val
- end
- end
-
- def self._config_keys
- []
- end
- end
-
- def _find_exec_flag_value(val)
- if val.kind_of?(Array)
- cmd, *args = val
- FindExecFlagValue.new(cmd, args.join(' '))
- elsif TkComm._callback_entry?(val)
- FindExecFlagValue.new(val)
- else
- val
- end
- end
-
- ################################
-
- def find(first, last, keys={})
- keys = _search_flags(keys)
- keys['exec'] = _find_exec_flag_value(keys['exec']) if keys.key?('exec')
- args = hash_kv(keys) << '--' << tagid(first) << tagid(last)
- simplelist(tk_send('find', *args)).collect{|id| tagid2obj(id)}
- end
-
- def tag_focus(tag)
- tk_send('focus', tagid(tag))
- self
- end
- def get(*tags)
- simplelist(tk_send('get', *(tags.collect{|tag| tagid(tag)})))
- end
- def get_full(*tags)
- simplelist(tk_send('get', '-full', *(tags.collect{|tag| tagid(tag)})))
- end
-
- def hide(*tags)
- if tags[-1].kind_of?(Hash)
- keys = tags.pop
- else
- keys = {}
- end
- keys = _search_flags(keys)
- args = hash_kv(keys) << '--'
- args.concat(tags.collect{|t| tagid(t)})
- tk_send('hide', *args)
- self
- end
-
- def index(str)
- tagid2obj(tk_send('index', str))
- end
- def index_at(tag, str)
- tagid2obj(tk_send('index', '-at', tagid(tag), str))
- end
- def index_at_path(tag, str)
- tagid2obj(tk_send('index', '-at', tagid(tag), '-path', str))
- end
-
- def insert(pos, parent=nil, keys={})
- Tk::BLT::Treeview::Node.new(pos, parent, keys)
- end
- def insert_at(tag, pos, parent=nil, keys={})
- if parent.kind_of?(Hash)
- keys = parent
- parent = nil
- end
-
- keys = _symbolkey2str(keys)
- keys['at'] = tagid(tag)
-
- Tk::BLT::Treeview::Node.new(pos, parent, keys)
- end
-
- def move_before(tag, dest)
- tk_send('move', tagid(tag), 'before', tagid(dest))
- self
- end
- def move_after(tag, dest)
- tk_send('move', tagid(tag), 'after', tagid(dest))
- self
- end
- def move_into(tag, dest)
- tk_send('move', tagid(tag), 'into', tagid(dest))
- self
- end
-
- def nearest(x, y, var=None)
- tagid2obj(tk_send('nearest', x, y, var))
- end
-
- def open(*tags)
- tk_send('open', *(tags.collect{|tag| tagid(tag)}))
- self
- end
- def open_recurse(*tags)
- tk_send('open', '-recurse', *(tags.collect{|tag| tagid(tag)}))
- self
- end
-
- def range(first, last)
- simplelist(tk_send('range', tagid(first), tagid(last))).collect{|id|
- tagid2obj(id)
- }
- end
- def range_open(first, last)
- simplelist(tk_send('range', '-open',
- tagid(first), tagid(last))).collect{|id|
- tagid2obj(id)
- }
- end
-
- def scan_mark(x, y)
- tk_send_without_enc('scan', 'mark', x, y)
- self
- end
- def scan_dragto(x, y)
- tk_send_without_enc('scan', 'dragto', x, y)
- self
- end
-
- def see(tag)
- tk_send_without_enc('see', tagid(tag))
- self
- end
- def see_anchor(anchor, tag)
- tk_send_without_enc('see', '-anchor', anchor, tagid(tag))
- self
- end
-
- def selection_anchor(tag)
- tk_send_without_enc('selection', 'anchor', tagid(tag))
- self
- end
- def selection_cancel()
- tk_send_without_enc('selection', 'cancel')
- self
- end
- def selection_clear(first, last=None)
- tk_send_without_enc('selection', 'clear', tagid(first), tagid(last))
- self
- end
- def selection_clear_all()
- tk_send_without_enc('selection', 'clearall')
- self
- end
- def selection_mark(tag)
- tk_send_without_enc('selection', 'mark', tagid(tag))
- self
- end
- def selection_include?(tag)
- bool(tk_send('selection', 'include', tagid(tag)))
- end
- def selection_present?()
- bool(tk_send('selection', 'present'))
- end
- def selection_set(first, last=None)
- tk_send_without_enc('selection', 'set', tagid(first), tagid(last))
- self
- end
- def selection_toggle(first, last=None)
- tk_send_without_enc('selection', 'toggle', tagid(first), tagid(last))
- self
- end
-
- def show(*tags)
- if tags[-1].kind_of?(Hash)
- keys = tags.pop
- else
- keys = {}
- end
- keys = _search_flags(keys)
- args = hash_kv(keys) << '--'
- args.concat(tags.collect{|t| tagid(t)})
- tk_send('show', *args)
- self
- end
-
- def sort_auto(mode)
- tk_send('sort', 'auto', mode)
- self
- end
- def sort_auto=(mode)
- tk_send('sort', 'auto', mode)
- mode
- end
- def sort_auto?
- bool(tk_send('sort', 'auto'))
- end
- def sort_once(*tags)
- tk_send('sort', 'once', *(tags.collect{|tag| tagid(tag)}))
- self
- end
- def sort_once_recurse(*tags)
- tk_send('sort', 'once', '-recurse', *(tags.collect{|tag| tagid(tag)}))
- self
- end
-
- def tag_add(tag, *ids)
- tk_send('tag', 'add', tagid(tag), *ids)
- self
- end
- def tag_delete(tag, *ids)
- tk_send('tag', 'delete', tagid(tag), *ids)
- self
- end
- def tag_forget(tag)
- tk_send('tag', 'forget', tagid(tag))
- self
- end
- def tag_names(id=nil)
- id = (id)? tagid(id): None
-
- simplelist(tk_send('tag', 'nodes', id)).collect{|tag|
- Tk::BLT::Treeview::Tag.id2obj(self, tag)
- }
- end
- def tag_nodes(tag)
- simplelist(tk_send('tag', 'nodes', tagid(tag))).collect{|id|
- Tk::BLT::Treeview::Node.id2obj(self, id)
- }
- end
-
- def text_apply
- tk_send('text', 'apply')
- self
- end
- def text_cancel
- tk_send('text', 'cancel')
- self
- end
-
- def text_delete(first, last)
- tk_send('text', 'delete', first, last)
- self
- end
- def text_get(x, y)
- tk_send('text', 'get', x, y)
- end
- def text_get_root(x, y)
- tk_send('text', 'get', '-root', x, y)
- end
- def text_icursor(idx)
- tk_send('text', 'icursor', idx)
- self
- end
- def text_index(idx)
- num_or_str(tk_send('text', 'index', idx))
- end
- def text_insert(idx, str)
- tk_send('text', 'insert', idx, str)
- self
- end
-
- def text_selection_adjust(idx)
- tk_send('text', 'selection', 'adjust', idx)
- self
- end
- def text_selection_clear
- tk_send('text', 'selection', 'clear')
- self
- end
- def text_selection_from(idx)
- tk_send('text', 'selection', 'from', idx)
- self
- end
- def text_selection_present
- num_or_str(tk_send('text', 'selection', 'present'))
- end
- def text_selection_range(start, last)
- tk_send('text', 'selection', 'range', start, last)
- self
- end
- def text_selection_to(idx)
- tk_send('text', 'selection', 'to', idx)
- self
- end
-
- def toggle(tag)
- tk_send('toggle', tagid(tag))
- self
- end
-end
-
-######################################
-
-module Tk::BLT::Treeview::TagOrID_Methods
- def bbox
- @tree.bbox(self)
- end
- def screen_bbox
- @tree.screen_bbox(self)
- end
-
- def bind(seq, *args)
- @tree.tag_bind(self, seq, *args)
- self
- end
- def bind_append(seq, *args)
- @tree.tag_bind_append(self, seq, *args)
- self
- end
- def bind_remove(seq)
- @tree.tag_bind_remove(self, seq)
- self
- end
- def bindinfo(seq=nil)
- @tree.tag_bindinfo(self, seq)
- end
-
- def button_activate
- @tree.button_activate(self)
- self
- end
-
- def button_bind(seq, *args)
- @tree.button_bind(self, seq, *args)
- self
- end
- def button_bind_append(seq, *args)
- @tree.button_bind_append(self, seq, *args)
- self
- end
- def button_bind_remove(seq)
- @tree.button_bind_remove(self, seq)
- self
- end
- def button_bindinfo(seq=nil)
- @tree.button_bindinfo(self, seq)
- end
-
- def close
- @tree.close(self)
- self
- end
- def close_recurse
- @tree.close_recurse(self)
- self
- end
-
- def delete
- @tree.delete(self)
- self
- end
-
- def entry_activate
- @tree.entry_activate(self)
- self
- end
- def entry_children(first=None, last=None)
- @tree.entry_children(self, first, last)
- end
- def entry_delete(first=None, last=None)
- @tree.entry_delete(self, first, last)
- end
- def entry_before?(tag)
- @tree.entry_before?(self, tag)
- end
- def entry_hidden?
- @tree.entry_before?(self)
- end
- def entry_open?
- @tree.entry_open?(self)
- end
-
- def entry_size
- @tree.entry_size(self)
- end
- def entry_size_recurse
- @tree.entry_size_recurse(self)
- end
-
- def focus
- @tree.tag_focus(self)
- self
- end
-
- def get
- @tree.get(self)
- end
- def get_full
- @tree.get_full(self)
- end
-
- def hide
- @tree.hide(self)
- self
- end
-
- def index(str)
- @tree.index_at(self, str)
- end
- def index_path(str)
- @tree.index_at_path(self, str)
- end
-
- def insert(pos, parent=nil, keys={})
- @tree.insert_at(self, pos, parent, keys)
- end
-
- def move_before(dest)
- @tree.move_before(self, dest)
- self
- end
- def move_after(dest)
- @tree.move_after(self, dest)
- self
- end
- def move_into(dest)
- @tree.move_into(self, dest)
- self
- end
-
- def open
- @tree.open(self)
- self
- end
- def open_recurse
- @tree.open_recurse(self)
- self
- end
-
- def range_to(tag)
- @tree.range(self, tag)
- end
- def range_open_to(tag)
- @tree.range(self, tag)
- end
-
- def see
- @tree.see(self)
- self
- end
- def see_anchor(anchor)
- @tree.see_anchor(anchor, self)
- self
- end
-
- def selection_anchor
- @tree.selection_anchor(self)
- self
- end
- def selection_clear
- @tree.selection_clear(self)
- self
- end
- def selection_mark
- @tree.selection_mark(self)
- self
- end
- def selection_include?
- @tree.selection_include?(self)
- end
- def selection_set
- @tree.selection_set(self)
- self
- end
- def selection_toggle
- @tree.selection_toggle(self)
- self
- end
-
- def show
- @tree.show(self)
- self
- end
-
- def sort_once
- @tree.sort_once(self)
- self
- end
- def sort_once_recurse
- @tree.sort_once_recurse(self)
- self
- end
-
- def toggle
- @tree.toggle(self)
- self
- end
-end
-
-######################################
-
-class Tk::BLT::Treeview::Node < TkObject
- include Tk::BLT::Treeview::TagOrID_Methods
-
- TreeNodeID_TBL = TkCore::INTERP.create_table
- TreeNode_ID = ['blt_treeview_node'.freeze, '00000'.taint].freeze
-
- TkCore::INTERP.init_ip_env{ TreeNodeID_TBL.clear }
-
- def self.id2obj(tree, id)
- tpath = tree.path
- return id unless TreeNodeID_TBL[tpath]
- if TreeNodeID_TBL[tpath][id]
- TreeNodeID_TBL[tpath][id]
- else
- begin
- self.new(tree, nil, nil, 'node'=>Integer(id))
- rescue
- id
- end
- end
- end
-
- def self.new(tree, pos, parent=nil, keys={})
- if parent.kind_of?(Hash)
- keys = parent
- parent = nil
- end
-
- keys = _symbolkey2str(keys)
- tpath = tree.path
-
- if (id = keys['node']) && (obj = TreeNodeID_TBL[tpath][id])
- keys.delete('node')
- tk_call(tree.path, 'move', id, pos, parent) if parent
- return obj
- end
-
- super(tree, pos, parent, keys)
- end
-
- def initialize(tree, pos, parent, keys)
- @parent = @tree = tree
- @tpath = @parent.path
-
- if (id = keys['node'])
- @path = @id = id
- tk_call(@tpath, 'move', @id, pos, tagid(parent)) if parent
- else
- name = TreeNode_ID.join(TkCore::INTERP._ip_id_).freeze
- TreeNode_ID[1].succ!
-
- at = keys.delete['at']
-
- if parent
- if parent.kind_of?(Tk::BLT::Treeview::Node) ||
- parent.kind_of?(Tk::BLT::Treeview::Tag)
- path = [get_full(parent.id)[0], name]
- at = nil # ignore 'at' option
- else
- path = [parent.to_s, name]
- end
- else
- path = name
- end
-
- if at
- @id = tk_call(@tpath, 'insert', '-at', tagid(at), pos, path, keys)
- else
- @id = tk_call(@tpath, 'insert', pos, path, keys)
- end
- @path = @id
- end
-
- TreeNodeID_TBL[@tpath] = {} unless TreeNodeID_TBL[@tpath]
- TreeNodeID_TBL[@tpath][@id] = self
- end
-
- def id
- @id
- end
-end
-
-######################################
-
-class Tk::BLT::Treeview::Tag < TkObject
- include Tk::BLT::Treeview::TagOrID_Methods
-
- TreeTagID_TBL = TkCore::INTERP.create_table
- TreeTag_ID = ['blt_treeview_tag'.freeze, '00000'.taint].freeze
-
- TkCore::INTERP.init_ip_env{ TreeTagID_TBL.clear }
-
- def self.id2obj(tree, id)
- tpath = tree.path
- return id unless TreeTagID_TBL[tpath]
- if TreeTagID_TBL[tpath][id]
- TreeTagID_TBL[tpath][id]
- else
- begin
- self.new(tree, nil, nil, 'name'=>Integer(id))
- rescue
- id
- end
- end
- end
-
- def self.new_by_name(tree, name, *ids)
- if (obj = TreeTagID_TBL[tree.path][name])
- return obj
- end
- new([tree, name], ids)
- end
-
- def self.new(tree, *ids)
- if tree.kind_of?(Array)
- super(tree[0], tree[1], ids)
- else
- super(tree, nil, ids)
- end
- end
-
- def initialize(tree, name, ids)
- @parent = @tree = tree
- @tpath = @parent.path
-
- if name
- @path = @id = name
- else
- @path = @id = TreeTag_ID.join(TkCore::INTERP._ip_id_).freeze
- TreeTag_ID[1].succ!
- end
-
- TreeTagID_TBL[@tpath] = {} unless TreeTagID_TBL[@tpath]
- TreeTagID_TBL[@tpath][@id] = self
-
- unless ids.empty?
- tk_call(@tpath, 'tag', 'add', @id, *(ids.collect{|id| tagid(id)}))
- end
- end
-
- def tagid(tag)
- if tag.kind_of?(Tk::BLT::Treeview::Node) \
- || tag.kind_of?(Tk::BLT::Treeview::Tag)
- tag.id
- else
- tag
- end
- end
- private :tagid
-
- def id
- @id
- end
-
- def add(*ids)
- tk_call(@tpath, 'tag', 'add', @id, *(ids{|id| tagid(id)}))
- self
- end
-
- def remove(*ids)
- tk_call(@tpath, 'tag', 'delete', @id, *(ids{|id| tagid(id)}))
- self
- end
-
- def forget
- tk_call(@tpath, 'tag', 'forget', @id)
- self
- end
-
- def nodes
- simplelist(tk_call(@tpath, 'tag', 'nodes', @id)).collect{|id|
- Tk::BLT::Treeview::Node.id2obj(@tree, id)
- }
- end
-end
-
-class Tk::BLT::Hiertable
- TkCommandNames = ['::blt::hiertable'.freeze].freeze
- WidgetClassName = 'Hiertable'.freeze
- WidgetClassNames[WidgetClassName] = self
-end
diff --git a/ext/tk/lib/tkextlib/blt/unix_dnd.rb b/ext/tk/lib/tkextlib/blt/unix_dnd.rb
deleted file mode 100644
index 3130c1e56f..0000000000
--- a/ext/tk/lib/tkextlib/blt/unix_dnd.rb
+++ /dev/null
@@ -1,129 +0,0 @@
-#
-# tkextlib/blt/unix_dnd.rb
-#
-# *** This is alpha version, because there is no document on BLT. ***
-#
-# by Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)
-#
-
-require 'tk'
-require 'tkextlib/blt.rb'
-
-module Tk::BLT
- module DnD
- extend TkCore
-
- TkCommandNames = ['::blt::dnd'.freeze].freeze
-
- ##############################
-
- extend TkItemConfigMethod
-
- class << self
- def __item_cget_cmd(id)
- ['::blt::dnd', *id]
- end
- private :__item_cget_cmd
-
- def __item_config_cmd(id)
- ['::blt::dnd', *id]
- end
- private :__item_config_cmd
-
- private :itemcget, :itemconfigure
- private :itemconfiginfo, :current_itemconfiginfo
-
- def cget(win, option)
- itemconfigure(['cget', win], slot, value)
- end
- def configure(win, slot, value=None)
- itemconfigure(['configure', win], slot, value)
- end
- def configinfo(win, slot=nil)
- itemconfiginfo(['configure', win], slot)
- end
- def current_configinfo(win, slot=nil)
- current_itemconfiginfo(['configure', win], slot)
- end
-
- def tokwn_cget(win, option)
- itemconfigure(['token', 'cget', win], slot, value)
- end
- def token_configure(win, slot, value=None)
- itemconfigure(['token', 'configure', win], slot, value)
- end
- def token_configinfo(win, slot=nil)
- itemconfiginfo(['token', 'configure', win], slot)
- end
- def current_token_configinfo(win, slot=nil)
- current_itemconfiginfo(['token', 'configure', win], slot)
- end
-
- def token_windowconfigure(win, slot, value=None)
- itemconfigure(['token', 'window', win], slot, value)
- end
- def token_windowconfiginfo(win, slot=nil)
- itemconfiginfo(['token', 'window', win], slot)
- end
- def current_token_windowconfiginfo(win, slot=nil)
- current_itemconfiginfo(['token', 'window', win], slot)
- end
- end
-
- ##############################
-
- def self.cancel(win)
- tk_call('::blt::dnd', 'cancel', *wins)
- end
- def self.delete(*wins)
- tk_call('::blt::dnd', 'delete', *wins)
- end
- def self.delete_source(*wins)
- tk_call('::blt::dnd', 'delete', '-source', *wins)
- end
- def self.delete_target(*wins)
- tk_call('::blt::dnd', 'delete', '-target', *wins)
- end
- def self.drag(win, x, y, token=None)
- tk_call('::blt::dnd', 'drag', win, x, y, token)
- end
- def self.drop(win, x, y, token=None)
- tk_call('::blt::dnd', 'drop', win, x, y, token)
- end
- def self.get_data(win, fmt=nil, cmd=nil)
- if fmt
- tk_call('::blt::dnd', 'getdata', win, fmt, cmd)
- else
- list(tk_call('::blt::dnd', 'getdata', win))
- end
- end
- def self.names(pat=None)
- list(tk_call('::blt::dnd', 'names', pat))
- end
- def self.source_names(pat=None)
- list(tk_call('::blt::dnd', 'names', '-source', pat))
- end
- def self.target_names(pat=None)
- list(tk_call('::blt::dnd', 'names', '-target', pat))
- end
- def self.pull(win, fmt)
- tk_call('::blt::dnd', 'pull', win, fmt)
- end
- def self.register(win, keys={})
- tk_call('::blt::dnd', 'register', win, keys)
- end
- def self.select(win, x, y, timestamp)
- tk_call('::blt::dnd', 'select', win, x, y, timestamp)
- end
- def self.set_data(win, fmt=nil, cmd=nil)
- if fmt
- tk_call('::blt::dnd', 'setdata', win, fmt, cmd)
- else
- list(tk_call('::blt::dnd', 'setdata', win))
- end
- end
- def self.token(*args)
- tk_call('::blt::dnd', 'token', *args)
- end
- end
-end
diff --git a/ext/tk/lib/tkextlib/blt/vector.rb b/ext/tk/lib/tkextlib/blt/vector.rb
deleted file mode 100644
index 540b6b9102..0000000000
--- a/ext/tk/lib/tkextlib/blt/vector.rb
+++ /dev/null
@@ -1,243 +0,0 @@
-#
-# tkextlib/blt/vector.rb
-# by Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)
-#
-
-require 'tk'
-require 'tkextlib/blt.rb'
-
-module Tk::BLT
- class Vector < TkVariable
- TkCommandNames = ['::blt::vector'.freeze].freeze
-
- def self.create(*args)
- tk_call('::blt::vector', 'create', *args)
- end
-
- def self.destroy(*args)
- tk_call('::blt::vector', 'destroy', *args)
- end
-
- def self.expr(expression)
- tk_call('::blt::vector', 'expr', expression)
- end
-
- def self.names(pat=None)
- simplelist(tk_call('::blt::vector', 'names', pat)).collect{|name|
- if TkVar_ID_TBL[name]
- TkVar_ID_TBL[name]
- elsif name[0..1] == '::' && TkVar_ID_TBL[name[2..-1]]
- TkVar_ID_TBL[name[2..-1]]
- else
- name
- end
- }
- end
-
- ####################################
-
- def initialize(size=nil, keys={})
- if size.kind_of?(Hash)
- keys = size
- size = nil
- end
- if size.kind_of?(Array)
- # [first, last]
- size = size.join(':')
- end
- if size
- @id = INTERP._invoke('::blt::vector', 'create',
- "#auto(#{size})", *hash_kv(keys))
- else
- @id = INTERP._invoke('::blt::vector', 'create',
- "#auto", *hash_kv(keys))
- end
-
- TkVar_ID_TBL[@id] = self
-
- @def_default = false
- @default_val = nil
-
- @trace_var = nil
- @trace_elem = nil
- @trace_opts = nil
-
- # teach Tk-ip that @id is global var
- INTERP._invoke_without_enc('global', @id)
- end
-
- def destroy
- tk_call('::blt::vector', 'destroy', @id)
- end
-
- def inspect
- '#<Tk::BLT::Vector: ' + @id + '>'
- end
-
- def to_s
- @id
- end
-
- def *(item)
- list(tk_call(@id, '*', item))
- end
-
- def +(item)
- list(tk_call(@id, '+', item))
- end
-
- def -(item)
- list(tk_call(@id, '-', item))
- end
-
- def /(item)
- list(tk_call(@id, '/', item))
- end
-
- def append(*vectors)
- tk_call(@id, 'append', *vectors)
- end
-
- def binread(channel, len=None, keys={})
- if len.kind_of?(Hash)
- keys = len
- len = None
- end
- keys = _symbolkey2str(keys)
- keys['swap'] = None if keys.delete('swap')
- tk_call(@id, 'binread', channel, len, keys)
- end
-
- def clear()
- tk_call(@id, 'clear')
- self
- end
-
- def delete(*indices)
- tk_call(@id, 'delete', *indices)
- self
- end
-
- def dup_vector(vec)
- tk_call(@id, 'dup', vec)
- self
- end
-
- def expr(expression)
- tk_call(@id, 'expr', expression)
- self
- end
-
- def index(idx, val=None)
- number(tk_call(@id, 'index', idx, val))
- end
-
- def [](idx)
- index(idx)
- end
-
- def []=(idx, val)
- index(idx, val)
- end
-
- def length()
- number(tk_call(@id, 'length'))
- end
-
- def length=(size)
- number(tk_call(@id, 'length', size))
- end
-
- def merge(*vectors)
- tk_call(@id, 'merge', *vectors)
- self
- end
-
- def normalize(vec=None)
- tk_call(@id, 'normalize', vec)
- self
- end
-
- def notify(keyword)
- tk_call(@id, 'notify', keyword)
- self
- end
-
- def offset()
- number(tk_call(@id, 'offset'))
- end
-
- def offset=(val)
- number(tk_call(@id, 'offset', val))
- end
-
- def random()
- tk_call(@id, 'random')
- end
-
- def populate(vector, density=None)
- tk_call(@id, 'populate', vector, density)
- self
- end
-
- def range(first, last=None)
- list(tk_call(@id, 'range', first, last))
- end
-
- def search(val1, val2=None)
- list(tk_call(@id, 'search', val1, val2))
- end
-
- def set(item)
- tk_call(@id, 'set', item)
- self
- end
-
- def seq(start, finish=None, step=None)
- tk_call(@id, 'seq', start, finish, step)
- self
- end
-
- def sort(*vectors)
- tk_call(@id, 'sort', *vectors)
- self
- end
-
- def sort_reverse(*vectors)
- tk_call(@id, 'sort', '-reverse', *vectors)
- self
- end
-
- def split(*vectors)
- tk_call(@id, 'split', *vectors)
- self
- end
-
- def variable(var)
- tk_call(@id, 'variable', var)
- self
- end
- end
-
- class VectorAccess < Vector
- def self.new(name)
- return TkVar_ID_TBL[name] if TkVar_ID_TBL[name]
- super(name, size=nil, keys={})
- end
-
- def initialize(vec_name)
- @id = vec_name
- TkVar_ID_TBL[@id] = self
-
- @def_default = false
- @default_val = nil
-
- @trace_var = nil
- @trace_elem = nil
- @trace_opts = nil
-
- # teach Tk-ip that @id is global var
- INTERP._invoke_without_enc('global', @id)
- end
- end
-end
diff --git a/ext/tk/lib/tkextlib/blt/watch.rb b/ext/tk/lib/tkextlib/blt/watch.rb
deleted file mode 100644
index ae5e50f126..0000000000
--- a/ext/tk/lib/tkextlib/blt/watch.rb
+++ /dev/null
@@ -1,142 +0,0 @@
-#
-# tkextlib/blt/watch.rb
-# by Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)
-#
-
-require 'tk'
-require 'tkextlib/blt.rb'
-
-module Tk::BLT
- class Watch < TkObject
- extend TkCore
-
- TkCommandNames = ['::blt::watch'.freeze].freeze
-
- WATCH_ID_TBL = TkCore::INTERP.create_table
- BLT_WATCH_ID = ['blt_watch_id'.freeze, '00000'.taint].freeze
-
- def self.names(state = None)
- tk_split_list(tk_call('::blt::watch', 'names', state)).collect{|name|
- WATCH_ID_TBL[name] || name
- }
- end
-
- def __numval_optkeys
- ['maxlevel']
- end
- private :__numval_optkeys
-
- def __boolval_optkeys
- ['active']
- end
- private :__boolval_optkeys
-
- def __config_cmd
- ['::blt::watch', 'configure', self.path]
- end
- private :__config_cmd
-
- def initialize(name = nil, keys = {})
- if name.kind_of?(Hash)
- keys = name
- name = nil
- end
-
- if name
- @id = name.to_s
- else
- @id = BLT_WATCH_ID.join(TkCore::INTERP._ip_id_)
- BLT_WATCH_ID[1].succ!
- end
-
- @path = @id
-
- WATCH_ID_TBL[@id] = self
- tk_call('::blt::watch', 'create', @id, *hash_kv(keys))
- end
-
- def activate
- tk_call('::blt::watch', 'activate', @id)
- self
- end
- def deactivate
- tk_call('::blt::watch', 'deactivate', @id)
- self
- end
- def delete
- tk_call('::blt::watch', 'delete', @id)
- self
- end
- def info
- ret = []
- lst = tk_split_simplelist(tk_call('::blt::watch', 'info', @id))
- until lst.empty?
- k, v, *lst = lst
- k = k[1..-1]
- case k
- when /^(#{__strval_optkeys.join('|')})$/
- # do nothing
-
- when /^(#{__numval_optkeys.join('|')})$/
- begin
- v = number(v)
- rescue
- v = nil
- end
-
- when /^(#{__numstrval_optkeys.join('|')})$/
- v = num_or_str(v)
-
- when /^(#{__boolval_optkeys.join('|')})$/
- begin
- v = bool(v)
- rescue
- v = nil
- end
-
- when /^(#{__listval_optkeys.join('|')})$/
- v = simplelist(v)
-
- when /^(#{__numlistval_optkeys.join('|')})$/
- v = list(v)
-
- else
- if v.index('{')
- v = tk_split_list(v)
- else
- v = tk_tcl2ruby(v)
- end
- end
-
- ret << [k, v]
- end
-
- ret
- end
- def configinfo(slot = nil)
- if slot
- slot = slot.to_s
- v = cget(slot)
- if TkComm::GET_CONFIGINFO_AS_ARRAY
- [slot, v]
- else
- {slot=>v}
- end
- else
- if TkComm::GET_CONFIGINFO_AS_ARRAY
- info
- else
- Hash[*(info.flatten)]
- end
- end
- end
- def cget(key)
- key = key.to_s
- begin
- info.assoc(key)[1]
- rescue
- fail ArgumentError, "unknown option '#{key}'"
- end
- end
- end
-end
diff --git a/ext/tk/lib/tkextlib/blt/win_printer.rb b/ext/tk/lib/tkextlib/blt/win_printer.rb
deleted file mode 100644
index 7ac6a0dcfc..0000000000
--- a/ext/tk/lib/tkextlib/blt/win_printer.rb
+++ /dev/null
@@ -1,61 +0,0 @@
-#
-# tkextlib/blt/win_printer.rb
-#
-# *** Windows only ***
-#
-# by Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)
-#
-
-require 'tk'
-require 'tkextlib/blt.rb'
-
-module Tk::BLT
- class Printer < TkObject
- extend TkCore
-
- TkCommandNames = ['::blt::printer'.freeze].freeze
-
- def self.enum(attribute)
- simplelist(tk_call('::blt::printer', 'enum', attribute))
- end
-
- def self.names(pat=None)
- simplelist(tk_call('::blt::printer', 'names', pat))
- end
-
- def self.open(printer)
- self.new(printer)
- end
-
- #################################
-
- def initialize(printer)
- @printer_id = tk_call('::blt::printer', 'open', printer)
- end
-
- def close
- tk_call('::blt::print', 'close', @printer_id)
- self
- end
- def get_attrs(var)
- tk_call('::blt::print', 'getattrs', @printer_id, var)
- var
- end
- def set_attrs(var)
- tk_call('::blt::print', 'setattrs', @printer_id, var)
- self
- end
- def snap(win)
- tk_call('::blt::print', 'snap', @printer_id, win)
- self
- end
- def write(str)
- tk_call('::blt::print', 'write', @printer_id, str)
- self
- end
- def write_with_title(title, str)
- tk_call('::blt::print', 'write', @printer_id, title, str)
- self
- end
- end
-end
diff --git a/ext/tk/lib/tkextlib/blt/winop.rb b/ext/tk/lib/tkextlib/blt/winop.rb
deleted file mode 100644
index e371d28ab7..0000000000
--- a/ext/tk/lib/tkextlib/blt/winop.rb
+++ /dev/null
@@ -1,107 +0,0 @@
-#
-# tkextlib/blt/winop.rb
-# by Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)
-#
-
-require 'tk'
-require 'tkextlib/blt.rb'
-
-module Tk::BLT
- module Winop
- extend TkCore
-
- TkCommandNames = ['::blt::winop'.freeze].freeze
- end
- WinOp = Winop
-end
-
-class << Tk::BLT::Winop
- def changes(win)
- tk_call('::blt::winop', 'changes', win)
- end
-
- def colormap(win)
- Hash[*list(tk_call('::blt::winop', 'colormap', win))]
- end
-
- def convolve(src, dest, filter)
- tk_call('::blt::winop', 'convolve', src, dest, filter)
- end
-
- def image_convolve(src, dest, filter)
- tk_call('::blt::winop', 'image', 'convolve', src, dest, filter)
- end
- def image_gradient(photo, left, right, type)
- tk_call('::blt::winop', 'image', 'gradient', photo, left, right, type)
- end
- def image_read_jpeg(file, photo)
- tk_call('::blt::winop', 'image', 'readjpeg', file, photo)
- end
- def image_resample(src, dest, horiz_filter=None, vert_filter=None)
- tk_call('::blt::winop', 'image', 'resample',
- src, dest, horiz_filter, vert_filter)
- end
- def image_rotate(src, dest, angle)
- tk_call('::blt::winop', 'image', 'rotate', src, dest, angle)
- end
- def image_snap(win, photo, width=None, height=None)
- tk_call('::blt::winop', 'image', 'snap', win, photo, width, height)
- end
- def image_subsample(src, dest, x, y, width, height,
- horiz_filter=None, vert_filter=None)
- tk_call('::blt::winop', 'image', 'subsample',
- src, dest, x, y, width, height, horiz_filter, vert_filter)
- end
-
- def quantize(src, dest, colors)
- tk_call('::blt::winop', 'quantize', src, dest, colors)
- end
-
- def query()
- tk_call('::blt::winop', 'query')
- end
-
- def read_jpeg(file, photo)
- tk_call('::blt::winop', 'readjpeg', file, photo)
- end
-
- def resample(src, dest, horiz_filter=None, vert_filter=None)
- tk_call('::blt::winop', 'resample',
- src, dest, horiz_filter, vert_filter)
- end
-
- def subsample(src, dest, x, y, width, height,
- horiz_filter=None, vert_filter=None)
- tk_call('::blt::winop', 'subsample',
- src, dest, x, y, width, height, horiz_filter, vert_filter)
- end
-
- def raise(*wins)
- tk_call('::blt::winop', 'raise', *wins)
- end
-
- def lower(*wins)
- tk_call('::blt::winop', 'lower', *wins)
- end
-
- def map(*wins)
- tk_call('::blt::winop', 'map', *wins)
- end
-
- def unmap(*wins)
- tk_call('::blt::winop', 'unmap', *wins)
- end
-
- def move(win, x, y)
- tk_call('::blt::winop', 'move', win, x, y)
- end
-
- def snap(win, photo)
- tk_call('::blt::winop', 'snap', win, photo)
- end
-
- def warpto(win = None)
- tk_call('::blt::winop', 'warpto', win)
- end
- alias warp_to warpto
-end
diff --git a/ext/tk/lib/tkextlib/bwidget.rb b/ext/tk/lib/tkextlib/bwidget.rb
index 62631d8b54..56009f4694 100644
--- a/ext/tk/lib/tkextlib/bwidget.rb
+++ b/ext/tk/lib/tkextlib/bwidget.rb
@@ -23,11 +23,6 @@ module Tk
LIBRARY = tk_call('set', '::BWIDGET::LIBRARY')
- PACKAGE_NAME = 'BWidget'.freeze
- def self.package_name
- PACKAGE_NAME
- end
-
def self.package_version
begin
TkPackage.require('BWidget')
diff --git a/ext/tk/lib/tkextlib/bwidget/button.rb b/ext/tk/lib/tkextlib/bwidget/button.rb
index 4a9d4a7948..246afebe29 100644
--- a/ext/tk/lib/tkextlib/bwidget/button.rb
+++ b/ext/tk/lib/tkextlib/bwidget/button.rb
@@ -18,14 +18,4 @@ class Tk::BWidget::Button
TkCommandNames = ['Button'.freeze].freeze
WidgetClassName = 'Button'.freeze
WidgetClassNames[WidgetClassName] = self
-
- def __strval_optkeys
- super() << 'helptext'
- end
- private :__strval_optkeys
-
- def __tkvariable_optkeys
- super() << 'helpvar'
- end
- private :__tkvariable_optkeys
end
diff --git a/ext/tk/lib/tkextlib/bwidget/buttonbox.rb b/ext/tk/lib/tkextlib/bwidget/buttonbox.rb
index ef999239f9..477de8a61f 100644
--- a/ext/tk/lib/tkextlib/bwidget/buttonbox.rb
+++ b/ext/tk/lib/tkextlib/bwidget/buttonbox.rb
@@ -21,11 +21,6 @@ class Tk::BWidget::ButtonBox
include TkItemConfigMethod
- def __boolval_optkeys
- super() << 'homogeneous'
- end
- private :__boolval_optkeys
-
def tagid(tagOrId)
if tagOrId.kind_of?(Tk::BWidget::Button)
name = tagOrId[:name]
diff --git a/ext/tk/lib/tkextlib/bwidget/dialog.rb b/ext/tk/lib/tkextlib/bwidget/dialog.rb
index 2790d88d24..d175a2d8bb 100644
--- a/ext/tk/lib/tkextlib/bwidget/dialog.rb
+++ b/ext/tk/lib/tkextlib/bwidget/dialog.rb
@@ -22,16 +22,6 @@ class Tk::BWidget::Dialog
include TkItemConfigMethod
- def __strval_optkeys
- super() << 'title'
- end
- private :__strval_optkeys
-
- def __boolval_optkeys
- super() << 'transient' << 'homogeneous'
- end
- private :__boolval_optkeys
-
def initialize(parent=nil, keys=nil)
@relative = ''
if parent.kind_of?(Hash)
diff --git a/ext/tk/lib/tkextlib/bwidget/dynamichelp.rb b/ext/tk/lib/tkextlib/bwidget/dynamichelp.rb
index 224304f2ab..4766a1ec6d 100644
--- a/ext/tk/lib/tkextlib/bwidget/dynamichelp.rb
+++ b/ext/tk/lib/tkextlib/bwidget/dynamichelp.rb
@@ -21,11 +21,6 @@ module Tk::BWidget::DynamicHelp
'DynamicHelp::configure'
end
- def __strval_optkeys
- super() << 'topbackground'
- end
- private :__strval_optkeys
-
def self.__cget_cmd
['DynamicHelp::configure']
end
diff --git a/ext/tk/lib/tkextlib/bwidget/entry.rb b/ext/tk/lib/tkextlib/bwidget/entry.rb
index aafb4aa7ff..9867a1ac36 100644
--- a/ext/tk/lib/tkextlib/bwidget/entry.rb
+++ b/ext/tk/lib/tkextlib/bwidget/entry.rb
@@ -21,21 +21,6 @@ class Tk::BWidget::Entry
WidgetClassName = 'Entry'.freeze
WidgetClassNames[WidgetClassName] = self
- def __strval_optkeys
- super() << 'helptext' << 'insertbackground'
- end
- private :__strval_optkeys
-
- def __boolval_optkeys
- super() << 'dragenabled' << 'dropenabled' << 'editable'
- end
- private :__boolval_optkeys
-
- def __tkvariable_optkeys
- super() << 'helpvar'
- end
- private :__tkvariable_optkeys
-
def invoke
tk_send_without_enc('invoke')
self
diff --git a/ext/tk/lib/tkextlib/bwidget/label.rb b/ext/tk/lib/tkextlib/bwidget/label.rb
index ce10ecaf8b..1d4c638705 100644
--- a/ext/tk/lib/tkextlib/bwidget/label.rb
+++ b/ext/tk/lib/tkextlib/bwidget/label.rb
@@ -19,21 +19,6 @@ class Tk::BWidget::Label
WidgetClassName = 'Label'.freeze
WidgetClassNames[WidgetClassName] = self
- def __strval_optkeys
- super() << 'helptext'
- end
- private :__strval_optkeys
-
- def __boolval_optkeys
- super() << 'dragenabled' << 'dropenabled'
- end
- private :__boolval_optkeys
-
- def __tkvariable_optkeys
- super() << 'helpvar'
- end
- private :__tkvariable_optkeys
-
def set_focus
tk_send_without_enc('setfocus')
self
diff --git a/ext/tk/lib/tkextlib/bwidget/labelentry.rb b/ext/tk/lib/tkextlib/bwidget/labelentry.rb
index 931feb9b48..7a6a7f01d6 100644
--- a/ext/tk/lib/tkextlib/bwidget/labelentry.rb
+++ b/ext/tk/lib/tkextlib/bwidget/labelentry.rb
@@ -23,48 +23,13 @@ class Tk::BWidget::LabelEntry
WidgetClassName = 'LabelEntry'.freeze
WidgetClassNames[WidgetClassName] = self
- def __strval_optkeys
- super() << 'helptext' << 'insertbackground' << 'entryfg' << 'entrybg'
- end
- private :__strval_optkeys
-
- def __tkvariable_optkeys
- super() << 'helpvar'
- end
- private :__tkvariable_optkeys
-
- def __font_optkeys
- super() << 'labelfont'
- end
- private :__font_optkeys
-
- #def entrybind(*args)
- # _bind([path, 'bind'], *args)
- # self
- #end
- def entrybind(context, *args)
- # if args[0].kind_of?(Proc) || args[0].kind_of?(Method)
- if TkComm._callback_entry?(args[0]) || !block_given?
- cmd = args.shift
- else
- cmd = Proc.new
- end
- _bind([path, 'bind'], context, cmd, *args)
+ def entrybind(*args)
+ _bind([path, 'bind'], *args)
self
end
- #def entrybind_append(*args)
- # _bind_append([path, 'bind'], *args)
- # self
- #end
- def entrybind_append(context, *args)
- #if args[0].kind_of?(Proc) || args[0].kind_of?(Method)
- if TkComm._callback_entry?(args[0]) || !block_given?
- cmd = args.shift
- else
- cmd = Proc.new
- end
- _bind_append([path, 'bind'], context, cmd, *args)
+ def entrybind_append(*args)
+ _bind_append([path, 'bind'], *args)
self
end
diff --git a/ext/tk/lib/tkextlib/bwidget/labelframe.rb b/ext/tk/lib/tkextlib/bwidget/labelframe.rb
index f7b267eebb..453756a163 100644
--- a/ext/tk/lib/tkextlib/bwidget/labelframe.rb
+++ b/ext/tk/lib/tkextlib/bwidget/labelframe.rb
@@ -6,7 +6,6 @@
require 'tk'
require 'tk/frame'
require 'tkextlib/bwidget.rb'
-require 'tkextlib/bwidget/label'
module Tk
module BWidget
@@ -20,21 +19,6 @@ class Tk::BWidget::LabelFrame
WidgetClassName = 'LabelFrame'.freeze
WidgetClassNames[WidgetClassName] = self
- def __strval_optkeys
- super() << 'helptext'
- end
- private :__strval_optkeys
-
- def __boolval_optkeys
- super() << 'dragenabled' << 'dropenabled'
- end
- private :__boolval_optkeys
-
- def __tkvariable_optkeys
- super() << 'helpvar'
- end
- private :__tkvariable_optkeys
-
def self.align(*args)
tk_call('LabelFrame::align', *args)
end
diff --git a/ext/tk/lib/tkextlib/bwidget/listbox.rb b/ext/tk/lib/tkextlib/bwidget/listbox.rb
index 1267500661..9f505703f2 100644
--- a/ext/tk/lib/tkextlib/bwidget/listbox.rb
+++ b/ext/tk/lib/tkextlib/bwidget/listbox.rb
@@ -35,11 +35,6 @@ class Tk::BWidget::ListBox
end
end
- def __boolval_optkeys
- super() << 'autofocus' << 'dragenabled' << 'dropenabled' << 'selectfill'
- end
- private :__boolval_optkeys
-
def tagid(tag)
if tag.kind_of?(Tk::BWidget::ListBox::Item)
tag.id
@@ -49,35 +44,13 @@ class Tk::BWidget::ListBox
end
end
- #def imagebind(*args)
- # _bind_for_event_class(Event_for_Items, [path, 'bindImage'], *args)
- # self
- #end
- def imagebind(context, *args)
- #if args[0].kind_of?(Proc) || args[0].kind_of?(Method)
- if TkComm._callback_entry?(args[0]) || !block_given?
- cmd = args.shift
- else
- cmd = Proc.new
- end
- _bind_for_event_class(Event_for_Items, [path, 'bindImage'],
- context, cmd, *args)
+ def imagebind(*args)
+ _bind_for_event_class(Event_for_Items, [path, 'bindImage'], *args)
self
end
- #def imagebind_append(*args)
- # _bind_append_for_event_class(Event_for_Items, [path, 'bindImage'], *args)
- # self
- #end
- def imagebind_append(context, *args)
- #if args[0].kind_of?(Proc) || args[0].kind_of?(Method)
- if TkComm._callback_entry?(args[0]) || !block_given?
- cmd = args.shift
- else
- cmd = Proc.new
- end
- _bind_append_for_event_class(Event_for_Items, [path, 'bindImage'],
- context, cmd, *args)
+ def imagebind_append(*args)
+ _bind_append_for_event_class(Event_for_Items, [path, 'bindImage'], *args)
self
end
@@ -90,35 +63,13 @@ class Tk::BWidget::ListBox
_bindinfo_for_event_class(Event_for_Items, [path, 'bindImage'], *args)
end
- #def textbind(*args)
- # _bind_for_event_class(Event_for_Items, [path, 'bindText'], *args)
- # self
- #end
- def textbind(context, *args)
- #if args[0].kind_of?(Proc) || args[0].kind_of?(Method)
- if TkComm._callback_entry?(args[0]) || !block_given?
- cmd = args.shift
- else
- cmd = Proc.new
- end
- _bind_for_event_class(Event_for_Items, [path, 'bindText'],
- context, cmd, *args)
+ def textbind(*args)
+ _bind_for_event_class(Event_for_Items, [path, 'bindText'], *args)
self
end
- #def textbind_append(*args)
- # _bind_append_for_event_class(Event_for_Items, [path, 'bindText'], *args)
- # self
- #end
- def textbind_append(context, *args)
- #if args[0].kind_of?(Proc) || args[0].kind_of?(Method)
- if TkComm._callback_entry?(args[0]) || !block_given?
- cmd = args.shift
- else
- cmd = Proc.new
- end
- _bind_append_for_event_class(Event_for_Items, [path, 'bindText'],
- context, cmd, *args)
+ def textbind_append(*args)
+ _bind_append_for_event_class(Event_for_Items, [path, 'bindText'], *args)
self
end
diff --git a/ext/tk/lib/tkextlib/bwidget/mainframe.rb b/ext/tk/lib/tkextlib/bwidget/mainframe.rb
index c54e878557..e52f4b2f4c 100644
--- a/ext/tk/lib/tkextlib/bwidget/mainframe.rb
+++ b/ext/tk/lib/tkextlib/bwidget/mainframe.rb
@@ -20,25 +20,6 @@ class Tk::BWidget::MainFrame
WidgetClassName = 'MainFrame'.freeze
WidgetClassNames[WidgetClassName] = self
- def __strval_optkeys
- super() << 'progressfg'
- end
- private :__strval_optkeys
-
- def __tkvariable_optkeys
- super() << 'progressvar'
- end
- private :__tkvariable_optkeys
-
- def __val2ruby_optkeys # { key=>proc, ... }
- # The method is used to convert a opt-value to a ruby's object.
- # When get the value of the option "key", "proc.call(value)" is called.
- {
- 'menu'=>proc{|v| simplelist(v).collect!{|elem| simplelist(v)}}
- }
- end
- private :__val2ruby_optkeys
-
def add_indicator(keys={}, &b)
win = window(tk_send('addindicator', *hash_kv(keys)))
win.instance_eval(&b) if b
diff --git a/ext/tk/lib/tkextlib/bwidget/messagedlg.rb b/ext/tk/lib/tkextlib/bwidget/messagedlg.rb
index 9c946d0630..d7b2bbc32b 100644
--- a/ext/tk/lib/tkextlib/bwidget/messagedlg.rb
+++ b/ext/tk/lib/tkextlib/bwidget/messagedlg.rb
@@ -5,7 +5,6 @@
require 'tk'
require 'tkextlib/bwidget.rb'
-require 'tkextlib/bwidget/dialog.rb'
module Tk
module BWidget
@@ -44,16 +43,6 @@ class Tk::BWidget::MessageDlg
end
private :create_self
- def __strval_optkeys
- super() << 'message' << 'title'
- end
- private :__strval_optkeys
-
- def __listval_optkeys
- super() << 'buttons'
- end
- private :__listval_optkeys
-
def cget(slot)
slot = slot.to_s
if slot == 'relative'
diff --git a/ext/tk/lib/tkextlib/bwidget/notebook.rb b/ext/tk/lib/tkextlib/bwidget/notebook.rb
index 5146d4915d..e0cc04d30e 100644
--- a/ext/tk/lib/tkextlib/bwidget/notebook.rb
+++ b/ext/tk/lib/tkextlib/bwidget/notebook.rb
@@ -29,15 +29,9 @@ class Tk::BWidget::NoteBook
end
end
- def __boolval_optkeys
- super() << 'homogeneous'
- end
- private :__boolval_optkeys
-
def tagid(id)
if id.kind_of?(TkWindow)
- #id.path
- id.epath
+ id.path
elsif id.kind_of?(TkObject)
id.to_eval
else
@@ -46,35 +40,13 @@ class Tk::BWidget::NoteBook
end
end
- #def tabbind(*args)
- # _bind_for_event_class(Event_for_Tabs, [path, 'bindtabs'], *args)
- # self
- #end
- def tabbind(context, *args)
- #if args[0].kind_of?(Proc) || args[0].kind_of?(Method)
- if TkComm._callback_entry?(args[0]) || !block_given?
- cmd = args.shift
- else
- cmd = Proc.new
- end
- _bind_for_event_class(Event_for_Tabs, [path, 'bindtabs'],
- context, cmd, *args)
+ def tabbind(*args)
+ _bind_for_event_class(Event_for_Tabs, [path, 'bindtabs'], *args)
self
end
- #def tabbind_append(*args)
- # _bind_append_for_event_class(Event_for_Tabs, [path, 'bindtabs'], *args)
- # self
- #end
- def tabbind_append(context, *args)
- #if args[0].kind_of?(Proc) || args[0].kind_of?(Method)
- if TkComm._callback_entry?(args[0]) || !block_given?
- cmd = args.shift
- else
- cmd = Proc.new
- end
- _bind_append_for_event_class(Event_for_Tabs, [path, 'bindtabs'],
- context, cmd, *args)
+ def tabbind_append(*args)
+ _bind_append_for_event_class(Event_for_Tabs, [path, 'bindtabs'], *args)
self
end
@@ -132,13 +104,9 @@ class Tk::BWidget::NoteBook
list(tk_send('pages', first, last))
end
- def raise(page=nil)
- if page
- tk_send('raise', page)
- self
- else
- tk_send('raise')
- end
+ def raise(page=None)
+ tk_send('raise', page)
+ self
end
def see(page)
diff --git a/ext/tk/lib/tkextlib/bwidget/panelframe.rb b/ext/tk/lib/tkextlib/bwidget/panelframe.rb
deleted file mode 100644
index 13f8817d74..0000000000
--- a/ext/tk/lib/tkextlib/bwidget/panelframe.rb
+++ /dev/null
@@ -1,51 +0,0 @@
-#
-# tkextlib/bwidget/panelframe.rb
-# by Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)
-#
-
-require 'tk'
-require 'tk/frame'
-require 'tkextlib/bwidget.rb'
-
-module Tk
- module BWidget
- class PanelFrame < TkWindow
- end
- end
-end
-
-class Tk::BWidget::PanelFrame
- TkCommandNames = ['PanelFrame'.freeze].freeze
- WidgetClassName = 'PanelFrame'.freeze
- WidgetClassNames[WidgetClassName] = self
-
- def __strval_optkeys
- super() + ['panelforeground', 'panelbackground']
- end
- private :__strval_optkeys
-
- def add(win, keys={})
- tk_send('add', win, keys)
- self
- end
-
- def delete(*wins)
- tk_send('delete', *wins)
- self
- end
-
- def get_frame(&b)
- win = window(tk_send_without_enc('getframe'))
- win.instance_eval(&b) if b
- win
- end
-
- def items
- list(tk_send('items'))
- end
-
- def remove(*wins)
- tk_send('remove', *wins)
- self
- end
-end
diff --git a/ext/tk/lib/tkextlib/bwidget/passwddlg.rb b/ext/tk/lib/tkextlib/bwidget/passwddlg.rb
index 0b635d97bb..7136ae8d72 100644
--- a/ext/tk/lib/tkextlib/bwidget/passwddlg.rb
+++ b/ext/tk/lib/tkextlib/bwidget/passwddlg.rb
@@ -19,23 +19,6 @@ class Tk::BWidget::PasswdDlg
WidgetClassName = 'PasswdDlg'.freeze
WidgetClassNames[WidgetClassName] = self
- def __strval_optkeys
- super() << 'loginhelptext' << 'loginlabel' << 'logintext' <<
- 'passwdlabel' << 'passwdtext'
- end
- private :__strval_optkeys
-
- def __boolval_optkeys
- super() << 'passwdeditable' << 'homogeneous'
- end
- private :__boolval_optkeys
-
- def __tkvariable_optkeys
- super() << 'loginhelpvar' << 'logintextvariable' <<
- 'passwdhelpvar' << 'passwdtextvariable'
- end
- private :__tkvariable_optkeys
-
def create
login, passwd = simplelist(tk_call(self.class::TkCommandNames[0],
@path, *hash_kv(@keys)))
diff --git a/ext/tk/lib/tkextlib/bwidget/scrollview.rb b/ext/tk/lib/tkextlib/bwidget/scrollview.rb
index 0546af2c43..5da528bd49 100644
--- a/ext/tk/lib/tkextlib/bwidget/scrollview.rb
+++ b/ext/tk/lib/tkextlib/bwidget/scrollview.rb
@@ -17,9 +17,4 @@ class Tk::BWidget::ScrollView
TkCommandNames = ['ScrollView'.freeze].freeze
WidgetClassName = 'ScrollView'.freeze
WidgetClassNames[WidgetClassName] = self
-
- def __strval_optkeys
- super() << 'fill'
- end
- private :__strval_optkeys
end
diff --git a/ext/tk/lib/tkextlib/bwidget/selectfont.rb b/ext/tk/lib/tkextlib/bwidget/selectfont.rb
index 478787602a..46ca0dbca8 100644
--- a/ext/tk/lib/tkextlib/bwidget/selectfont.rb
+++ b/ext/tk/lib/tkextlib/bwidget/selectfont.rb
@@ -25,15 +25,9 @@ class Tk::BWidget::SelectFont
WidgetClassName = 'SelectFont'.freeze
WidgetClassNames[WidgetClassName] = self
- def __strval_optkeys
- super() << 'sampletext' << 'title'
- end
- private :__strval_optkeys
-
def __font_optkeys
[] # without fontobj operation
end
- private :__font_optkeys
def create
tk_call(self.class::TkCommandNames[0], @path, *hash_kv(@keys))
diff --git a/ext/tk/lib/tkextlib/bwidget/spinbox.rb b/ext/tk/lib/tkextlib/bwidget/spinbox.rb
index ca4c046e5c..4380e38355 100644
--- a/ext/tk/lib/tkextlib/bwidget/spinbox.rb
+++ b/ext/tk/lib/tkextlib/bwidget/spinbox.rb
@@ -22,53 +22,13 @@ class Tk::BWidget::SpinBox
WidgetClassName = 'SpinBox'.freeze
WidgetClassNames[WidgetClassName] = self
- def __strval_optkeys
- super() << 'helptext' << 'insertbackground' << 'entryfg' << 'entrybg'
- end
- private :__strval_optkeys
-
- def __boolval_optkeys
- super() << 'dragenabled' << 'dropenabled' << 'editable'
- end
- private :__boolval_optkeys
-
- def __listval_optkeys
- super() << 'values'
- end
- private :__listval_optkeys
-
- def __tkvariable_optkeys
- super() << 'helpvar'
- end
- private :__tkvariable_optkeys
-
- #def entrybind(*args)
- # _bind([path, 'bind'], *args)
- # self
- #end
- def entrybind(context, *args)
- #if args[0].kind_of?(Proc) || args[0].kind_of?(Method)
- if TkComm._callback_entry?(args[0]) || !block_given?
- cmd = args.shift
- else
- cmd = Proc.new
- end
- _bind([path, 'bind'], context, cmd, *args)
+ def entrybind(*args)
+ _bind([path, 'bind'], *args)
self
end
- #def entrybind_append(*args)
- # _bind_append([path, 'bind'], *args)
- # self
- #end
- def entrybind_append(context, *args)
- #if args[0].kind_of?(Proc) || args[0].kind_of?(Method)
- if TkComm._callback_entry?(args[0]) || !block_given?
- cmd = args.shift
- else
- cmd = Proc.new
- end
- _bind_append([path, 'bind'], context, cmd, *args)
+ def entrybind_append(*args)
+ _bind_append([path, 'bind'], *args)
self
end
diff --git a/ext/tk/lib/tkextlib/bwidget/statusbar.rb b/ext/tk/lib/tkextlib/bwidget/statusbar.rb
deleted file mode 100644
index df16e4c0b7..0000000000
--- a/ext/tk/lib/tkextlib/bwidget/statusbar.rb
+++ /dev/null
@@ -1,46 +0,0 @@
-#
-# tkextlib/bwidget/statusbar.rb
-# by Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)
-#
-
-require 'tk'
-require 'tk/frame'
-require 'tkextlib/bwidget.rb'
-
-module Tk
- module BWidget
- class StatusBar < TkWindow
- end
- end
-end
-
-class Tk::BWidget::StatusBar
- TkCommandNames = ['StatusBar'.freeze].freeze
- WidgetClassName = 'StatusBar'.freeze
- WidgetClassNames[WidgetClassName] = self
-
- def __boolval_optkeys
- super() << 'showresize'
- end
- private :__boolval_optkeys
-
- def add(win, keys={})
- tk_send('add', win, keys)
- self
- end
-
- def delete(*wins)
- tk_send('delete', *wins)
- self
- end
-
- def get_frame(&b)
- win = window(tk_send_without_enc('getframe'))
- win.instance_eval(&b) if b
- win
- end
-
- def items
- list(tk_send('items'))
- end
-end
diff --git a/ext/tk/lib/tkextlib/bwidget/tree.rb b/ext/tk/lib/tkextlib/bwidget/tree.rb
index e7178debe2..9a49a96bb7 100644
--- a/ext/tk/lib/tkextlib/bwidget/tree.rb
+++ b/ext/tk/lib/tkextlib/bwidget/tree.rb
@@ -32,22 +32,6 @@ class Tk::BWidget::Tree
end
end
- def __strval_optkeys
- super() << 'crossfill' << 'linesfill'
- end
- private :__strval_optkeys
-
- def __boolval_optkeys
- super() << 'dragenabled' << 'dropenabled' <<
- 'redraw' << 'selectfill' << 'showlines'
- end
- private :__boolval_optkeys
-
- def __tkvariable_optkeys
- super() << 'helpvar'
- end
- private :__tkvariable_optkeys
-
def tagid(tag)
if tag.kind_of?(Tk::BWidget::Tree::Node)
tag.id
@@ -57,35 +41,13 @@ class Tk::BWidget::Tree
end
end
- #def imagebind(*args)
- # _bind_for_event_class(Event_for_Items, [path, 'bindImage'], *args)
- # self
- #end
- def imagebind(context, *args)
- #if args[0].kind_of?(Proc) || args[0].kind_of?(Method)
- if TkComm._callback_entry?(args[0]) || !block_given?
- cmd = args.shift
- else
- cmd = Proc.new
- end
- _bind_for_event_class(Event_for_Items, [path, 'bindImage'],
- context, cmd, *args)
+ def imagebind(*args)
+ _bind_for_event_class(Event_for_Items, [path, 'bindImage'], *args)
self
end
- #def imagebind_append(*args)
- # _bind_append_for_event_class(Event_for_Items, [path, 'bindImage'], *args)
- # self
- #end
- def imagebind_append(context, *args)
- #if args[0].kind_of?(Proc) || args[0].kind_of?(Method)
- if TkComm._callback_entry?(args[0]) || !block_given?
- cmd = args.shift
- else
- cmd = Proc.new
- end
- _bind_append_for_event_class(Event_for_Items, [path, 'bindImage'],
- context, cmd, *args)
+ def imagebind_append(*args)
+ _bind_append_for_event_class(Event_for_Items, [path, 'bindImage'], *args)
self
end
@@ -98,35 +60,13 @@ class Tk::BWidget::Tree
_bindinfo_for_event_class(Event_for_Items, [path, 'bindImage'], *args)
end
- #def textbind(*args)
- # _bind_for_event_class(Event_for_Items, [path, 'bindText'], *args)
- # self
- #end
- def textbind(context, *args)
- #if args[0].kind_of?(Proc) || args[0].kind_of?(Method)
- if TkComm._callback_entry?(args[0]) || !block_given?
- cmd = args.shift
- else
- cmd = Proc.new
- end
- _bind_for_event_class(Event_for_Items, [path, 'bindText'],
- context, cmd, *args)
+ def textbind(*args)
+ _bind_for_event_class(Event_for_Items, [path, 'bindText'], *args)
self
end
- #def textbind_append(*args)
- # _bind_append_for_event_class(Event_for_Items, [path, 'bindText'], *args)
- # self
- #end
- def textbind_append(context, *args)
- #if args[0].kind_of?(Proc) || args[0].kind_of?(Method)
- if TkComm._callback_entry?(args[0]) || !block_given?
- cmd = args.shift
- else
- cmd = Proc.new
- end
- _bind_append_for_event_class(Event_for_Items, [path, 'bindText'],
- context, cmd, *args)
+ def textbind_append(*args)
+ _bind_append_for_event_class(Event_for_Items, [path, 'bindText'], *args)
self
end
diff --git a/ext/tk/lib/tkextlib/bwidget/widget.rb b/ext/tk/lib/tkextlib/bwidget/widget.rb
index 568e503a8b..eadf59c11c 100644
--- a/ext/tk/lib/tkextlib/bwidget/widget.rb
+++ b/ext/tk/lib/tkextlib/bwidget/widget.rb
@@ -56,7 +56,7 @@ module Tk::BWidget::Widget
end
def self.destroy(win)
- tk_call('Widget::destroy', _epath(win))
+ tk_call('Widget::destroy', win)
end
def self.focus_next(win)
diff --git a/ext/tk/lib/tkextlib/itcl/incr_tcl.rb b/ext/tk/lib/tkextlib/itcl/incr_tcl.rb
index 07abf3a7bf..c03f3c36cb 100644
--- a/ext/tk/lib/tkextlib/itcl/incr_tcl.rb
+++ b/ext/tk/lib/tkextlib/itcl/incr_tcl.rb
@@ -22,11 +22,6 @@ module Tk
VERSION = TkCore::INTERP._invoke("set", "::itcl::version").freeze
PATCHLEVEL = TkCore::INTERP._invoke("set", "::itcl::patchLevel").freeze
- PACKAGE_NAME = 'Itcl'.freeze
- def self.package_name
- PACKAGE_NAME
- end
-
def self.package_version
begin
TkPackage.require('Itcl')
diff --git a/ext/tk/lib/tkextlib/itk/incr_tk.rb b/ext/tk/lib/tkextlib/itk/incr_tk.rb
index d37fd12a7c..f11d9d7913 100644
--- a/ext/tk/lib/tkextlib/itk/incr_tk.rb
+++ b/ext/tk/lib/tkextlib/itk/incr_tk.rb
@@ -20,11 +20,6 @@ module Tk
LIBRARY = TkVarAccess.new('::itk::library')
- PACKAGE_NAME = 'Itk'.freeze
- def self.package_name
- PACKAGE_NAME
- end
-
def self.package_version
begin
TkPackage.require('Itk')
@@ -115,11 +110,6 @@ module Tk
include Wm
include TkMenuSpec
-
- def __strval_optkeys
- super() << 'title'
- end
- private :__strval_optkeys
end
############################
@@ -340,18 +330,7 @@ module Tk
end
end
- #def bind(*args)
- # unless @widget
- # begin
- # @widget = window(tk_call(@master, 'component', @component))
- # @path = @widget.path
- # rescue
- # fail RuntimeError, 'component is not assigned to a widget'
- # end
- # end
- # @widget.bind(*args)
- #end
- def bind(context, *args)
+ def bind(*args)
unless @widget
begin
@widget = window(tk_call(@master, 'component', @component))
@@ -360,27 +339,10 @@ module Tk
fail RuntimeError, 'component is not assigned to a widget'
end
end
- # if args[0].kind_of?(Proc) || args[0].kind_of?(Method)
- if TkComm._callback_entry?(args[0]) || !block_given?
- cmd = args.shift
- else
- cmd = Proc.new
- end
- @widget.bind(context, cmd, *args)
- end
-
- #def bind_append(*args)
- # unless @widget
- # begin
- # @widget = window(tk_call(@master, 'component', @component))
- # @path = @widget.path
- # rescue
- # fail RuntimeError, 'component is not assigned to a widget'
- # end
- # end
- # @widget.bind_append(*args)
- #end
- def bind_append(context, *args)
+ @widget.bind(*args)
+ end
+
+ def bind_append(*args)
unless @widget
begin
@widget = window(tk_call(@master, 'component', @component))
@@ -389,13 +351,7 @@ module Tk
fail RuntimeError, 'component is not assigned to a widget'
end
end
- # if args[0].kind_of?(Proc) || args[0].kind_of?(Method)
- if TkComm._callback_entry?(args[0]) || !block_given?
- cmd = args.shift
- else
- cmd = Proc.new
- end
- @widget.bind_append(context, cmd, *args)
+ @widget.bind_append(*args)
end
def bind_remove(*args)
diff --git a/ext/tk/lib/tkextlib/iwidgets.rb b/ext/tk/lib/tkextlib/iwidgets.rb
index ebd4cf7507..5ef82f68ca 100644
--- a/ext/tk/lib/tkextlib/iwidgets.rb
+++ b/ext/tk/lib/tkextlib/iwidgets.rb
@@ -23,11 +23,6 @@ module Tk
extend TkCore
- PACKAGE_NAME = 'Iwidgets'.freeze
- def self.package_name
- PACKAGE_NAME
- end
-
def self.package_version
begin
TkPackage.require('Iwidgets')
diff --git a/ext/tk/lib/tkextlib/iwidgets/buttonbox.rb b/ext/tk/lib/tkextlib/iwidgets/buttonbox.rb
index a055e07ac9..1ff190b9ff 100644
--- a/ext/tk/lib/tkextlib/iwidgets/buttonbox.rb
+++ b/ext/tk/lib/tkextlib/iwidgets/buttonbox.rb
@@ -32,11 +32,6 @@ class Tk::Iwidgets::Buttonbox
end
private :__item_config_cmd
- def __item_boolval_optkeys(id)
- super(id) << 'defaultring'
- end
- private :__item_boolval_optkeys
-
def tagid(tagOrId)
if tagOrId.kind_of?(Tk::Itk::Component)
tagOrId.name
diff --git a/ext/tk/lib/tkextlib/iwidgets/calendar.rb b/ext/tk/lib/tkextlib/iwidgets/calendar.rb
index 0152f8593a..f382cfd143 100644
--- a/ext/tk/lib/tkextlib/iwidgets/calendar.rb
+++ b/ext/tk/lib/tkextlib/iwidgets/calendar.rb
@@ -18,24 +18,6 @@ class Tk::Iwidgets::Calendar
WidgetClassName = 'Calendar'.freeze
WidgetClassNames[WidgetClassName] = self
- def __strval_optkeys
- super() + [
- 'buttonforeground', 'outline', 'selectcolor',
- 'weekdaybackground', 'weekendbackground'
- ]
- end
- private :__strval_optkeys
-
- def __listval_optkeys
- super() << 'days'
- end
- private :__listval_optkeys
-
- def __font_optkeys
- super() + ['currentdatefont', 'datefont', 'dayfont', 'titlefont']
- end
- private :__font_optkeys
-
####################################
include Tk::ValidateConfigure
@@ -63,7 +45,7 @@ class Tk::Iwidgets::Calendar
end
def __validation_class_list
- super() << CalendarCommand
+ super << CalendarCommand
end
Tk::ValidateConfigure.__def_validcmd(binding, CalendarCommand)
diff --git a/ext/tk/lib/tkextlib/iwidgets/canvasprintbox.rb b/ext/tk/lib/tkextlib/iwidgets/canvasprintbox.rb
index fa5e90ad05..1e2a476591 100644
--- a/ext/tk/lib/tkextlib/iwidgets/canvasprintbox.rb
+++ b/ext/tk/lib/tkextlib/iwidgets/canvasprintbox.rb
@@ -18,16 +18,6 @@ class Tk::Iwidgets::Canvasprintbox
WidgetClassName = 'Canvasprintbox'.freeze
WidgetClassNames[WidgetClassName] = self
- def __strval_optkeys
- super() << 'filename'
- end
- private :__strval_optkeys
-
- def __boolval_optkeys
- super() << 'stretch'
- end
- private :__boolval_optkeys
-
def get_output
tk_call(@path, 'getoutput')
end
diff --git a/ext/tk/lib/tkextlib/iwidgets/checkbox.rb b/ext/tk/lib/tkextlib/iwidgets/checkbox.rb
index abd23299a8..05d0e1d813 100644
--- a/ext/tk/lib/tkextlib/iwidgets/checkbox.rb
+++ b/ext/tk/lib/tkextlib/iwidgets/checkbox.rb
@@ -32,11 +32,6 @@ class Tk::Iwidgets::Checkbox
end
private :__item_config_cmd
- def __item_boolval_optkeys(id)
- super(id) << 'defaultring'
- end
- private :__item_boolval_optkeys
-
def tagid(tagOrId)
if tagOrId.kind_of?(Tk::Itk::Component)
tagOrId.name
diff --git a/ext/tk/lib/tkextlib/iwidgets/combobox.rb b/ext/tk/lib/tkextlib/iwidgets/combobox.rb
index a6d54d78fa..1cf10b4004 100644
--- a/ext/tk/lib/tkextlib/iwidgets/combobox.rb
+++ b/ext/tk/lib/tkextlib/iwidgets/combobox.rb
@@ -18,11 +18,6 @@ class Tk::Iwidgets::Combobox
WidgetClassName = 'Combobox'.freeze
WidgetClassNames[WidgetClassName] = self
- def __boolval_optkeys
- super() << 'completion' << 'dropdown' << 'editable' << 'unique'
- end
- private :__boolval_optkeys
-
def clear(component=None)
tk_call(@path, 'clear', component)
self
diff --git a/ext/tk/lib/tkextlib/iwidgets/datefield.rb b/ext/tk/lib/tkextlib/iwidgets/datefield.rb
index 632f3334dc..924aef9c4d 100644
--- a/ext/tk/lib/tkextlib/iwidgets/datefield.rb
+++ b/ext/tk/lib/tkextlib/iwidgets/datefield.rb
@@ -18,21 +18,6 @@ class Tk::Iwidgets::Datefield
WidgetClassName = 'Datefield'.freeze
WidgetClassNames[WidgetClassName] = self
- def __boolval_optkeys
- super() << 'gmt'
- end
- private :__boolval_optkeys
-
- def __strval_optkeys
- super() << 'textbackground'
- end
- private :__strval_optkeys
-
- def __font_optkeys
- super() << 'textfont'
- end
- private :__font_optkeys
-
def get_string
tk_call(@path, 'get', '-string')
end
diff --git a/ext/tk/lib/tkextlib/iwidgets/dialogshell.rb b/ext/tk/lib/tkextlib/iwidgets/dialogshell.rb
index d6c668621d..88b9a97094 100644
--- a/ext/tk/lib/tkextlib/iwidgets/dialogshell.rb
+++ b/ext/tk/lib/tkextlib/iwidgets/dialogshell.rb
@@ -32,11 +32,6 @@ class Tk::Iwidgets::Dialogshell
end
private :__item_config_cmd
- def __item_boolval_optkeys(id)
- super(id) << 'defaultring'
- end
- private :__item_boolval_optkeys
-
def tagid(tagOrId)
if tagOrId.kind_of?(Tk::Itk::Component)
tagOrId.name
diff --git a/ext/tk/lib/tkextlib/iwidgets/disjointlistbox.rb b/ext/tk/lib/tkextlib/iwidgets/disjointlistbox.rb
index 9bc063ba69..8418467925 100644
--- a/ext/tk/lib/tkextlib/iwidgets/disjointlistbox.rb
+++ b/ext/tk/lib/tkextlib/iwidgets/disjointlistbox.rb
@@ -18,11 +18,6 @@ class Tk::Iwidgets::Disjointlistbox
WidgetClassName = 'Disjointlistbox'.freeze
WidgetClassNames[WidgetClassName] = self
- def __strval_optkeys
- super() << 'lhslabeltext' << 'rhslabeltext' << 'lhsbuttonlabel' << 'rhsbuttonlabel'
- end
- private :__strval_optkeys
-
def set_lhs(*items)
tk_call(@path, 'setlhs', items)
self
diff --git a/ext/tk/lib/tkextlib/iwidgets/entryfield.rb b/ext/tk/lib/tkextlib/iwidgets/entryfield.rb
index 6aa933ce06..ae7d63f3f3 100644
--- a/ext/tk/lib/tkextlib/iwidgets/entryfield.rb
+++ b/ext/tk/lib/tkextlib/iwidgets/entryfield.rb
@@ -18,11 +18,6 @@ class Tk::Iwidgets::Entryfield
WidgetClassName = 'Entryfield'.freeze
WidgetClassNames[WidgetClassName] = self
- def __font_optkeys
- super() << 'textfont'
- end
- private :__font_optkeys
-
####################################
include Tk::ValidateConfigure
@@ -51,7 +46,7 @@ class Tk::Iwidgets::Entryfield
end
def __validation_class_list
- super() << EntryfieldValidate
+ super << EntryfieldValidate
end
Tk::ValidateConfigure.__def_validcmd(binding, EntryfieldValidate)
diff --git a/ext/tk/lib/tkextlib/iwidgets/extbutton.rb b/ext/tk/lib/tkextlib/iwidgets/extbutton.rb
index 158d9d474a..7b1e35aa2d 100644
--- a/ext/tk/lib/tkextlib/iwidgets/extbutton.rb
+++ b/ext/tk/lib/tkextlib/iwidgets/extbutton.rb
@@ -18,16 +18,6 @@ class Tk::Iwidgets::Extbutton
WidgetClassName = 'Extbutton'.freeze
WidgetClassNames[WidgetClassName] = self
- def __strval_optkeys
- super() << 'bitmapforeground' << 'ringbackground'
- end
- private :__strval_optkeys
-
- def __boolval_optkeys
- super() << 'defaultring'
- end
- private :__boolval_optkeys
-
def invoke
tk_call(@path, 'invoke')
self
diff --git a/ext/tk/lib/tkextlib/iwidgets/extfileselectionbox.rb b/ext/tk/lib/tkextlib/iwidgets/extfileselectionbox.rb
index 501f4c90a0..282647893c 100644
--- a/ext/tk/lib/tkextlib/iwidgets/extfileselectionbox.rb
+++ b/ext/tk/lib/tkextlib/iwidgets/extfileselectionbox.rb
@@ -18,19 +18,6 @@ class Tk::Iwidgets::Extfileselectionbox
WidgetClassName = 'Extfileselectionbox'.freeze
WidgetClassNames[WidgetClassName] = self
- def __strval_optkeys
- super() + [
- 'dirslabel', 'fileslabel', 'filterlabel', 'mask', 'nomatchstring',
- 'selectionlabel'
- ]
- end
- private :__strval_optkeys
-
- def __boolval_optkeys
- super() + ['dirson', 'fileson', 'filteron', 'selectionon']
- end
- private :__boolval_optkeys
-
def child_site
window(tk_call(@path, 'childsite'))
end
diff --git a/ext/tk/lib/tkextlib/iwidgets/feedback.rb b/ext/tk/lib/tkextlib/iwidgets/feedback.rb
index 0a25237a24..d7439d818a 100644
--- a/ext/tk/lib/tkextlib/iwidgets/feedback.rb
+++ b/ext/tk/lib/tkextlib/iwidgets/feedback.rb
@@ -18,11 +18,6 @@ class Tk::Iwidgets::Feedback
WidgetClassName = 'Feedback'.freeze
WidgetClassNames[WidgetClassName] = self
- def __strval_optkeys
- super() << 'barcolor'
- end
- private :__strval_optkeys
-
def reset
tk_call(@path, 'reset')
self
diff --git a/ext/tk/lib/tkextlib/iwidgets/fileselectionbox.rb b/ext/tk/lib/tkextlib/iwidgets/fileselectionbox.rb
index 7b331d0b40..46de13d1b2 100644
--- a/ext/tk/lib/tkextlib/iwidgets/fileselectionbox.rb
+++ b/ext/tk/lib/tkextlib/iwidgets/fileselectionbox.rb
@@ -18,19 +18,6 @@ class Tk::Iwidgets::Fileselectionbox
WidgetClassName = 'Fileselectionbox'.freeze
WidgetClassNames[WidgetClassName] = self
- def __strval_optkeys
- super() + [
- 'directory', 'dirslabel', 'fileslabel', 'filterlabel', 'mask',
- 'nomatchstring', 'selectionlabel'
- ]
- end
- private :__strval_optkeys
-
- def __boolval_optkeys
- super() + ['dirson', 'fileson', 'filteron', 'selectionon']
- end
- private :__boolval_optkeys
-
def child_site
window(tk_call(@path, 'childsite'))
end
diff --git a/ext/tk/lib/tkextlib/iwidgets/finddialog.rb b/ext/tk/lib/tkextlib/iwidgets/finddialog.rb
index 75e219c37e..a161c3c2a4 100644
--- a/ext/tk/lib/tkextlib/iwidgets/finddialog.rb
+++ b/ext/tk/lib/tkextlib/iwidgets/finddialog.rb
@@ -18,19 +18,6 @@ class Tk::Iwidgets::Finddialog
WidgetClassName = 'Finddialog'.freeze
WidgetClassNames[WidgetClassName] = self
- def __strval_optkeys
- super() + [
- 'patternbackground', 'patternforeground',
- 'searchbackground', 'searchforeground'
- ]
- end
- private :__strval_optkeys
-
- def __val2ruby_optkeys # { key=>proc, ... }
- super().update('textwidget'=>proc{|v| window(v)})
- end
- private :__val2ruby_optkeys
-
def clear
tk_call(@path, 'clear')
self
diff --git a/ext/tk/lib/tkextlib/iwidgets/hierarchy.rb b/ext/tk/lib/tkextlib/iwidgets/hierarchy.rb
index 4cc6aeecbd..077d84c7a4 100644
--- a/ext/tk/lib/tkextlib/iwidgets/hierarchy.rb
+++ b/ext/tk/lib/tkextlib/iwidgets/hierarchy.rb
@@ -92,7 +92,7 @@ class Tk::Iwidgets::Hierarchy
end
def __validation_class_list
- super() << QueryCommand << IndicatorCommand << IconCommand
+ super << QueryCommand << IndicatorCommand << IconCommand
end
Tk::ValidateConfigure.__def_validcmd(binding, QueryCommand)
@@ -101,21 +101,6 @@ class Tk::Iwidgets::Hierarchy
####################################
- def __boolval_optkeys
- super() << 'alwaysquery' << 'expanded' << 'filter'
- end
- private :__boolval_optkeys
-
- def __strval_optkeys
- super() << 'markbackground' << 'markforeground' << 'textbackground'
- end
- private :__strval_optkeys
-
- def __font_optkeys
- super() << 'textfont'
- end
- private :__font_optkeys
-
def clear
tk_call(@path, 'clear')
self
@@ -252,13 +237,13 @@ class Tk::Iwidgets::Hierarchy
args << tags.shift.collect{|x|_get_eval_string(x)}.join(' ') # taglist
args << tags.shift if tags.size > 0 # chars
end
- super(index, *args)
+ super index, *args
else
# single chars-taglist argument :: str, tag, tag, ...
if tags.size == 0
- super(index, chars)
+ super index, chars
else
- super(index, chars, tags.collect{|x|_get_eval_string(x)}.join(' '))
+ super index, chars, tags.collect{|x|_get_eval_string(x)}.join(' ')
end
end
end
diff --git a/ext/tk/lib/tkextlib/iwidgets/hyperhelp.rb b/ext/tk/lib/tkextlib/iwidgets/hyperhelp.rb
index 77b0e090cd..22e86339a6 100644
--- a/ext/tk/lib/tkextlib/iwidgets/hyperhelp.rb
+++ b/ext/tk/lib/tkextlib/iwidgets/hyperhelp.rb
@@ -18,16 +18,6 @@ class Tk::Iwidgets::Hyperhelp
WidgetClassName = 'Hyperhelp'.freeze
WidgetClassNames[WidgetClassName] = self
- def __strval_optkeys
- super() << 'helpdir'
- end
- private :__strval_optkeys
-
- def __listval_optkeys
- super() << 'topics'
- end
- private :__listval_optkeys
-
def show_topic(topic)
tk_call(@path, 'showtopic', topic)
self
diff --git a/ext/tk/lib/tkextlib/iwidgets/labeledframe.rb b/ext/tk/lib/tkextlib/iwidgets/labeledframe.rb
index e77e85045d..89669ea815 100644
--- a/ext/tk/lib/tkextlib/iwidgets/labeledframe.rb
+++ b/ext/tk/lib/tkextlib/iwidgets/labeledframe.rb
@@ -18,21 +18,6 @@ class Tk::Iwidgets::Labeledframe
WidgetClassName = 'Labeledframe'.freeze
WidgetClassNames[WidgetClassName] = self
- def __strval_optkeys
- super() << 'labeltext'
- end
- private :__strval_optkeys
-
- def __tkvariable_optkeys
- super() << 'labelvariable'
- end
- private :__tkvariable_optkeys
-
- def __font_optkeys
- super() << 'labelfont'
- end
- private :__font_optkeys
-
def child_site
window(tk_call(@path, 'childsite'))
end
diff --git a/ext/tk/lib/tkextlib/iwidgets/labeledwidget.rb b/ext/tk/lib/tkextlib/iwidgets/labeledwidget.rb
index 99387710cb..f847922386 100644
--- a/ext/tk/lib/tkextlib/iwidgets/labeledwidget.rb
+++ b/ext/tk/lib/tkextlib/iwidgets/labeledwidget.rb
@@ -20,21 +20,6 @@ class Tk::Iwidgets::Labeledwidget
WidgetClassName = 'Labeledwidget'.freeze
WidgetClassNames[WidgetClassName] = self
- def __strval_optkeys
- super() << 'labeltext'
- end
- private :__strval_optkeys
-
- def __tkvariable_optkeys
- super() << 'labelvariable'
- end
- private :__tkvariable_optkeys
-
- def __font_optkeys
- super() << 'labelfont'
- end
- private :__font_optkeys
-
def self.alignlabels(*wins)
tk_call('::iwidgets::Labeledwidget::alignlabels', *wins)
end
diff --git a/ext/tk/lib/tkextlib/iwidgets/mainwindow.rb b/ext/tk/lib/tkextlib/iwidgets/mainwindow.rb
index 4b2541b997..4570afc6d0 100644
--- a/ext/tk/lib/tkextlib/iwidgets/mainwindow.rb
+++ b/ext/tk/lib/tkextlib/iwidgets/mainwindow.rb
@@ -18,21 +18,6 @@ class Tk::Iwidgets::Mainwindow
WidgetClassName = 'Mainwindow'.freeze
WidgetClassNames[WidgetClassName] = self
- def __boolval_optkeys
- super() << 'helpline' << 'statusline'
- end
- private :__boolval_optkeys
-
- def __strval_optkeys
- super() << 'menubarbackground' << 'menubarforeground' << 'toolbarforeground'
- end
- private :__strval_optkeys
-
- def __font_optkeys
- super() << 'menubarfont' << 'toolbarfont'
- end
- private :__font_optkeys
-
def child_site
window(tk_call(@path, 'childsite'))
end
diff --git a/ext/tk/lib/tkextlib/iwidgets/menubar.rb b/ext/tk/lib/tkextlib/iwidgets/menubar.rb
index dea3d34c2a..b60349be17 100644
--- a/ext/tk/lib/tkextlib/iwidgets/menubar.rb
+++ b/ext/tk/lib/tkextlib/iwidgets/menubar.rb
@@ -18,16 +18,6 @@ class Tk::Iwidgets::Menubar
WidgetClassName = 'Menubar'.freeze
WidgetClassNames[WidgetClassName] = self
- def __strval_optkeys
- super() << 'menubuttons'
- end
- private :__strval_optkeys
-
- def __tkvariable_optkeys
- super() << 'helpvariable'
- end
- private :__tkvariable_optkeys
-
####################################
include TkItemConfigMethod
@@ -42,16 +32,6 @@ class Tk::Iwidgets::Menubar
end
private :__item_config_cmd
- def __item_strval_optkeys(id)
- super(id) << 'selectcolor'
- end
- private :__item_strval_optkeys
-
- def __item_tkvariable_optkeys(id)
- super(id) << 'helpstr'
- end
- private :__item_tkvariable_optkeys
-
def tagid(tagOrId)
if tagOrId.kind_of?(Tk::Itk::Component)
tagOrId.name
diff --git a/ext/tk/lib/tkextlib/iwidgets/messagebox.rb b/ext/tk/lib/tkextlib/iwidgets/messagebox.rb
index 2bbbec7666..608f6f7adb 100644
--- a/ext/tk/lib/tkextlib/iwidgets/messagebox.rb
+++ b/ext/tk/lib/tkextlib/iwidgets/messagebox.rb
@@ -41,11 +41,6 @@ class Tk::Iwidgets::Messagebox
end
end
- def __item_boolval_optkeys(id)
- super(id) << 'bell' << 'show'
- end
- private :__item_boolval_optkeys
-
alias typecget itemcget
alias typeconfigure itemconfigure
alias typeconfiginfo itemconfiginfo
@@ -56,11 +51,6 @@ class Tk::Iwidgets::Messagebox
####################################
- def __strval_optkeys
- super() << 'filename' << 'savedir'
- end
- private :__strval_optkeys
-
def type_add(tag=nil, keys={})
if tag.kind_of?(Hash)
keys = tag
diff --git a/ext/tk/lib/tkextlib/iwidgets/notebook.rb b/ext/tk/lib/tkextlib/iwidgets/notebook.rb
index 0f9d713ea1..d9abf1b02b 100644
--- a/ext/tk/lib/tkextlib/iwidgets/notebook.rb
+++ b/ext/tk/lib/tkextlib/iwidgets/notebook.rb
@@ -23,12 +23,12 @@ class Tk::Iwidgets::Notebook
include TkItemConfigMethod
def __item_cget_cmd(id)
- [self.path, 'pagecget', id]
+ [self.path, 'tabcget', id]
end
private :__item_cget_cmd
def __item_config_cmd(id)
- [self.path, 'pageconfigure', id]
+ [self.path, 'tabconfigure', id]
end
private :__item_config_cmd
@@ -51,11 +51,6 @@ class Tk::Iwidgets::Notebook
####################################
- def __boolval_optkeys
- super() << 'auto'
- end
- private :__boolval_optkeys
-
def add(keys={})
window(tk_call(@path, 'add', *hash_kv(keys)))
end
@@ -144,24 +139,24 @@ class Tk::Iwidgets::Notebook
end
alias scrollbar yscrollbar
- def view(*idxs)
- if idxs.size == 0
+ def view(*index)
+ if index.size == 0
window(tk_send_without_enc('view'))
else
- tk_send_without_enc('view', *idxs)
+ tk_send_without_enc('view', *index)
self
end
end
alias xview view
alias yview view
- def view_moveto(*idxs)
- view('moveto', *idxs)
+ def view_moveto(*index)
+ view('moveto', *index)
end
alias xview_moveto view_moveto
alias yview_moveto view_moveto
- def view_scroll(*idxs)
- view('scroll', *idxs)
+ def view_scroll(*index)
+ view('scroll', *index)
end
alias xview_scroll view_scroll
alias yview_scroll view_scroll
diff --git a/ext/tk/lib/tkextlib/iwidgets/optionmenu.rb b/ext/tk/lib/tkextlib/iwidgets/optionmenu.rb
index 0c74440be7..226163a150 100644
--- a/ext/tk/lib/tkextlib/iwidgets/optionmenu.rb
+++ b/ext/tk/lib/tkextlib/iwidgets/optionmenu.rb
@@ -18,11 +18,6 @@ class Tk::Iwidgets::Optionmenu
WidgetClassName = 'Optionmenu'.freeze
WidgetClassNames[WidgetClassName] = self
- def __boolval_optkeys
- super() << 'cyclicon'
- end
- private :__boolval_optkeys
-
def delete(first, last=nil)
if last
tk_call(@path, 'delete', first, last)
diff --git a/ext/tk/lib/tkextlib/iwidgets/panedwindow.rb b/ext/tk/lib/tkextlib/iwidgets/panedwindow.rb
index 035df0a5b8..a205036239 100644
--- a/ext/tk/lib/tkextlib/iwidgets/panedwindow.rb
+++ b/ext/tk/lib/tkextlib/iwidgets/panedwindow.rb
@@ -51,11 +51,6 @@ class Tk::Iwidgets::Panedwindow
####################################
- def __boolval_optkeys
- super() << 'showhandle'
- end
- private :__boolval_optkeys
-
def add(tag=nil, keys={})
if tag.kind_of?(Hash)
keys = tag
diff --git a/ext/tk/lib/tkextlib/iwidgets/promptdialog.rb b/ext/tk/lib/tkextlib/iwidgets/promptdialog.rb
index 620b14b5d5..ec18647511 100644
--- a/ext/tk/lib/tkextlib/iwidgets/promptdialog.rb
+++ b/ext/tk/lib/tkextlib/iwidgets/promptdialog.rb
@@ -73,8 +73,8 @@ class Tk::Iwidgets::Promptdialog
end
alias icursor cursor=
- def index(idx)
- number(tk_send_without_enc('index', idx))
+ def index(index)
+ number(tk_send_without_enc('index', index))
end
def insert(pos,text)
diff --git a/ext/tk/lib/tkextlib/iwidgets/pushbutton.rb b/ext/tk/lib/tkextlib/iwidgets/pushbutton.rb
index c21007ca6c..25d3633507 100644
--- a/ext/tk/lib/tkextlib/iwidgets/pushbutton.rb
+++ b/ext/tk/lib/tkextlib/iwidgets/pushbutton.rb
@@ -18,11 +18,6 @@ class Tk::Iwidgets::Pushbutton
WidgetClassName = 'Pushbutton'.freeze
WidgetClassNames[WidgetClassName] = self
- def __boolval_optkeys
- super() << 'defaultring'
- end
- private :__boolval_optkeys
-
def invoke
tk_call_without_enc(@path, 'invoke')
self
diff --git a/ext/tk/lib/tkextlib/iwidgets/radiobox.rb b/ext/tk/lib/tkextlib/iwidgets/radiobox.rb
index d4316754f2..84c15082d6 100644
--- a/ext/tk/lib/tkextlib/iwidgets/radiobox.rb
+++ b/ext/tk/lib/tkextlib/iwidgets/radiobox.rb
@@ -32,11 +32,6 @@ class Tk::Iwidgets::Radiobox
end
private :__item_config_cmd
- def __item_boolval_optkeys(id)
- super(id) << 'defaultring'
- end
- private :__item_boolval_optkeys
-
def tagid(tagOrId)
if tagOrId.kind_of?(Tk::Itk::Component)
tagOrId.name
diff --git a/ext/tk/lib/tkextlib/iwidgets/scrolledcanvas.rb b/ext/tk/lib/tkextlib/iwidgets/scrolledcanvas.rb
index 407c8f2aad..c26eda1586 100644
--- a/ext/tk/lib/tkextlib/iwidgets/scrolledcanvas.rb
+++ b/ext/tk/lib/tkextlib/iwidgets/scrolledcanvas.rb
@@ -21,16 +21,6 @@ class Tk::Iwidgets::Scrolledcanvas
################################
- def __boolval_optkeys
- super() << 'autoresize'
- end
- private :__boolval_optkeys
-
- def __strval_optkeys
- super() << 'textbackground'
- end
- private :__strval_optkeys
-
def initialize(*args)
super(*args)
@canvas = component_widget('canvas')
@@ -107,33 +97,13 @@ class Tk::Iwidgets::Scrolledcanvas
*tags.collect{|t| tagid(t)}))
end
- #def itembind(tag, context, cmd=Proc.new, *args)
- # _bind([path, "bind", tagid(tag)], context, cmd, *args)
- # self
- #end
- def itembind(tag, context, *args)
- # if args[0].kind_of?(Proc) || args[0].kind_of?(Method)
- if TkComm._callback_entry?(args[0]) || !block_given?
- cmd = args.shift
- else
- cmd = Proc.new
- end
- _bind([path, "bind", tagid(tag)], context, cmd, *args)
+ def itembind(tag, context, cmd=Proc.new, args=nil)
+ _bind([path, "bind", tagid(tag)], context, cmd, args)
self
end
- #def itembind_append(tag, context, cmd=Proc.new, *args)
- # _bind_append([path, "bind", tagid(tag)], context, cmd, *args)
- # self
- #end
- def itembind_append(tag, context, *args)
- # if args[0].kind_of?(Proc) || args[0].kind_of?(Method)
- if TkComm._callback_entry?(args[0]) || !block_given?
- cmd = args.shift
- else
- cmd = Proc.new
- end
- _bind_append([path, "bind", tagid(tag)], context, cmd, *args)
+ def itembind_append(tag, context, cmd=Proc.new, args=nil)
+ _bind_append([path, "bind", tagid(tag)], context, cmd, args)
self
end
@@ -173,9 +143,7 @@ class Tk::Iwidgets::Scrolledcanvas
def delete(*args)
if TkcItem::CItemID_TBL[self.path]
find('withtag', *args).each{|item|
- if item.kind_of?(TkcItem)
- TkcItem::CItemID_TBL[self.path].delete(item.id)
- end
+ TkcItem::CItemID_TBL[self.path].delete(item.id)
}
end
tk_send_without_enc('delete', *args.collect{|t| tagid(t)})
@@ -240,8 +208,8 @@ class Tk::Iwidgets::Scrolledcanvas
self
end
- def index(tagOrId, idx)
- number(tk_send_without_enc('index', tagid(tagOrId), idx))
+ def index(tagOrId, index)
+ number(tk_send_without_enc('index', tagid(tagOrId), index))
end
def insert(tagOrId, index, string)
diff --git a/ext/tk/lib/tkextlib/iwidgets/scrolledhtml.rb b/ext/tk/lib/tkextlib/iwidgets/scrolledhtml.rb
index 9b69ef07fe..7023d889d1 100644
--- a/ext/tk/lib/tkextlib/iwidgets/scrolledhtml.rb
+++ b/ext/tk/lib/tkextlib/iwidgets/scrolledhtml.rb
@@ -18,21 +18,6 @@ class Tk::Iwidgets::Scrolledhtml
WidgetClassName = 'Scrolledhtml'.freeze
WidgetClassNames[WidgetClassName] = self
- def __boolval_optkeys
- super() << 'update'
- end
- private :__boolval_optkeys
-
- def __strval_optkeys
- super() << 'fontname' << 'link' << 'alink' << 'textbackground'
- end
- private :__strval_optkeys
-
- def __font_optkeys
- super() << 'fixedfont'
- end
- private :__font_optkeys
-
def import(href)
tk_call(@path, 'import', href)
self
diff --git a/ext/tk/lib/tkextlib/iwidgets/scrolledlistbox.rb b/ext/tk/lib/tkextlib/iwidgets/scrolledlistbox.rb
index cd1f6f0f79..9fe23b4edc 100644
--- a/ext/tk/lib/tkextlib/iwidgets/scrolledlistbox.rb
+++ b/ext/tk/lib/tkextlib/iwidgets/scrolledlistbox.rb
@@ -19,21 +19,6 @@ class Tk::Iwidgets::Scrolledlistbox
WidgetClassName = 'Scrolledlistbox'.freeze
WidgetClassNames[WidgetClassName] = self
- def __strval_optkeys
- super() << 'textbackground'
- end
- private :__strval_optkeys
-
- def __tkvariable_optkeys
- super() << 'listvariable'
- end
- private :__tkvariable_optkeys
-
- def __font_optkeys
- super() << 'textfont'
- end
- private :__font_optkeys
-
################################
def initialize(*args)
@@ -140,9 +125,7 @@ class Tk::Iwidgets::Scrolledlistbox
end
def get(first, last=nil)
if last
- # tk_split_simplelist(_fromUTF8(tk_send_without_enc('get', first, last)))
- tk_split_simplelist(tk_send_without_enc('get', first, last),
- false, true)
+ tk_split_simplelist(_fromUTF8(tk_send_without_enc('get', first, last)))
else
_fromUTF8(tk_send_without_enc('get', first))
end
@@ -169,8 +152,8 @@ class Tk::Iwidgets::Scrolledlistbox
self
end
- def index(idx)
- tk_send_without_enc('index', idx).to_i
+ def index(index)
+ tk_send_without_enc('index', index).to_i
end
#####################################
diff --git a/ext/tk/lib/tkextlib/iwidgets/scrolledtext.rb b/ext/tk/lib/tkextlib/iwidgets/scrolledtext.rb
index fdafc8dc7f..39a9ed63c8 100644
--- a/ext/tk/lib/tkextlib/iwidgets/scrolledtext.rb
+++ b/ext/tk/lib/tkextlib/iwidgets/scrolledtext.rb
@@ -19,16 +19,6 @@ class Tk::Iwidgets::Scrolledtext
WidgetClassName = 'Scrolledtext'.freeze
WidgetClassNames[WidgetClassName] = self
- def __strval_optkeys
- super() << 'textbackground'
- end
- private :__strval_optkeys
-
- def __font_optkeys
- super() << 'textfont'
- end
- private :__font_optkeys
-
################################
def initialize(*args)
@@ -147,19 +137,15 @@ class Tk::Iwidgets::Scrolledtext
if slot
case slot.to_s
when 'text', 'label', 'show', 'data', 'file'
- #conf = tk_split_simplelist(_fromUTF8(tk_send_without_enc('image', 'configure', _get_eval_enc_str(index), "-#{slot}")))
- conf = tk_split_simplelist(tk_send_without_enc('image', 'configure', _get_eval_enc_str(index), "-#{slot}"), false, true)
+ conf = tk_split_simplelist(_fromUTF8(tk_send_without_enc('image', 'configure', _get_eval_enc_str(index), "-#{slot}")))
else
- #conf = tk_split_list(_fromUTF8(tk_send_without_enc('image', 'configure', _get_eval_enc_str(index), "-#{slot}")))
- conf = tk_split_list(tk_send_without_enc('image', 'configure', _get_eval_enc_str(index), "-#{slot}"), 0, false, true)
+ conf = tk_split_list(_fromUTF8(tk_send_without_enc('image', 'configure', _get_eval_enc_str(index), "-#{slot}")))
end
conf[0] = conf[0][1..-1]
conf
else
- #tk_split_simplelist(_fromUTF8(tk_send_without_enc('image', 'configure', _get_eval_enc_str(index)))).collect{|conflist|
- # conf = tk_split_simplelist(conflist)
- tk_split_simplelist(tk_send_without_enc('image', 'configure', _get_eval_enc_str(index)), false, false).collect{|conflist|
- conf = tk_split_simplelist(conflist, false, true)
+ tk_split_simplelist(_fromUTF8(tk_send_without_enc('image', 'configure', _get_eval_enc_str(index)))).collect{|conflist|
+ conf = tk_split_simplelist(conflist)
conf[0] = conf[0][1..-1]
case conf[0]
when 'text', 'label', 'show', 'data', 'file'
@@ -187,20 +173,16 @@ class Tk::Iwidgets::Scrolledtext
if slot
case slot.to_s
when 'text', 'label', 'show', 'data', 'file'
- #conf = tk_split_simplelist(_fromUTF8(tk_send_without_enc('image', 'configure', _get_eval_enc_str(index), "-#{slot}")))
- conf = tk_split_simplelist(tk_send_without_enc('image', 'configure', _get_eval_enc_str(index), "-#{slot}"), false, true)
+ conf = tk_split_simplelist(_fromUTF8(tk_send_without_enc('image', 'configure', _get_eval_enc_str(index), "-#{slot}")))
else
- #conf = tk_split_list(_fromUTF8(tk_send_without_enc('image', 'configure', _get_eval_enc_str(index), "-#{slot}")))
- conf = tk_split_list(tk_send_without_enc('image', 'configure', _get_eval_enc_str(index), "-#{slot}"), 0, false, true)
+ conf = tk_split_list(_fromUTF8(tk_send_without_enc('image', 'configure', _get_eval_enc_str(index), "-#{slot}")))
end
key = conf.shift[1..-1]
{ key => conf }
else
ret = {}
- #tk_split_simplelist(_fromUTF8(tk_send_without_enc('image', 'configure', _get_eval_enc_str(index)))).each{|conflist|
- # conf = tk_split_simplelist(conflist)
- tk_split_simplelist(tk_send_without_enc('image', 'configure', _get_eval_enc_str(index)), false, false).each{|conflist|
- conf = tk_split_simplelist(conflist, false, true)
+ tk_split_simplelist(_fromUTF8(tk_send_without_enc('image', 'configure', _get_eval_enc_str(index)))).each{|conflist|
+ conf = tk_split_simplelist(conflist)
key = conf.shift[1..-1]
case key
when 'text', 'label', 'show', 'data', 'file'
@@ -253,14 +235,13 @@ class Tk::Iwidgets::Scrolledtext
end
def image_names
- #tk_split_simplelist(_fromUTF8(tk_send_without_enc('image', 'names'))).collect{|elt|
- tk_split_simplelist(tk_send_without_enc('image', 'names'), false, true).collect{|elt|
+ tk_split_simplelist(_fromUTF8(tk_send_without_enc('image', 'names'))).collect{|elt|
tagid2obj(elt)
}
end
- def index(idx)
- tk_send_without_enc('index', _get_eval_enc_str(idx))
+ def index(index)
+ tk_send_without_enc('index', _get_eval_enc_str(index))
end
def insert(index, *args)
@@ -269,8 +250,7 @@ class Tk::Iwidgets::Scrolledtext
end
def mark_names
- #tk_split_simplelist(_fromUTF8(tk_send_without_enc('mark', 'names'))).collect{|elt|
- tk_split_simplelist(tk_send_without_enc('mark', 'names'), false, true).collect{|elt|
+ tk_split_simplelist(_fromUTF8(tk_send_without_enc('mark', 'names'))).collect{|elt|
tagid2obj(elt)
}
end
diff --git a/ext/tk/lib/tkextlib/iwidgets/selectionbox.rb b/ext/tk/lib/tkextlib/iwidgets/selectionbox.rb
index bb81fcca5e..91ba9248e1 100644
--- a/ext/tk/lib/tkextlib/iwidgets/selectionbox.rb
+++ b/ext/tk/lib/tkextlib/iwidgets/selectionbox.rb
@@ -18,16 +18,6 @@ class Tk::Iwidgets::Selectionbox
WidgetClassName = 'Selectionbox'.freeze
WidgetClassNames[WidgetClassName] = self
- def __boolval_optkeys
- super() << 'itemson' << 'selectionon'
- end
- private :__boolval_optkeys
-
- def __strval_optkeys
- super() << 'itemslabel' << 'selectionlabel'
- end
- private :__strval_optkeys
-
def child_site
window(tk_call(@path, 'childsite'))
end
@@ -67,8 +57,8 @@ class Tk::Iwidgets::Selectionbox
tk_send_without_enc('delete', first, last)
self
end
- def index(idx)
- tk_send_without_enc('index', idx).to_i
+ def index(index)
+ tk_send_without_enc('index', index).to_i
end
def nearest(y)
tk_send_without_enc('nearest', y).to_i
diff --git a/ext/tk/lib/tkextlib/iwidgets/selectiondialog.rb b/ext/tk/lib/tkextlib/iwidgets/selectiondialog.rb
index ab790e97a6..794da5d61c 100644
--- a/ext/tk/lib/tkextlib/iwidgets/selectiondialog.rb
+++ b/ext/tk/lib/tkextlib/iwidgets/selectiondialog.rb
@@ -57,8 +57,8 @@ class Tk::Iwidgets::Selectiondialog
tk_send_without_enc('delete', first, last)
self
end
- def index(idx)
- tk_send_without_enc('index', idx).to_i
+ def index(index)
+ tk_send_without_enc('index', index).to_i
end
def nearest(y)
tk_send_without_enc('nearest', y).to_i
diff --git a/ext/tk/lib/tkextlib/iwidgets/spindate.rb b/ext/tk/lib/tkextlib/iwidgets/spindate.rb
index 2c98eb4629..6099ba77b9 100644
--- a/ext/tk/lib/tkextlib/iwidgets/spindate.rb
+++ b/ext/tk/lib/tkextlib/iwidgets/spindate.rb
@@ -18,16 +18,6 @@ class Tk::Iwidgets::Spindate
WidgetClassName = 'Spindate'.freeze
WidgetClassNames[WidgetClassName] = self
- def __boolval_optkeys
- super() << 'dayon' << 'monthon' << 'yearon'
- end
- private :__boolval_optkeys
-
- def __strval_optkeys
- super() << 'daylabel' << 'monthformat' << 'monthlabel' << 'yearlabel'
- end
- private :__strval_optkeys
-
def get_string
tk_call(@path, 'get', '-string')
end
diff --git a/ext/tk/lib/tkextlib/iwidgets/spinint.rb b/ext/tk/lib/tkextlib/iwidgets/spinint.rb
index 5eb944d081..071b6ab8f7 100644
--- a/ext/tk/lib/tkextlib/iwidgets/spinint.rb
+++ b/ext/tk/lib/tkextlib/iwidgets/spinint.rb
@@ -17,14 +17,4 @@ class Tk::Iwidgets::Spinint
TkCommandNames = ['::iwidgets::spinint'.freeze].freeze
WidgetClassName = 'Spinint'.freeze
WidgetClassNames[WidgetClassName] = self
-
- def __boolval_optkeys
- super() << 'wrap'
- end
- private :__boolval_optkeys
-
- def __numlistval_optkeys
- super() << 'range'
- end
- private :__numlistval_optkeys
end
diff --git a/ext/tk/lib/tkextlib/iwidgets/spinner.rb b/ext/tk/lib/tkextlib/iwidgets/spinner.rb
index 174b9bd506..b5c72b4df8 100644
--- a/ext/tk/lib/tkextlib/iwidgets/spinner.rb
+++ b/ext/tk/lib/tkextlib/iwidgets/spinner.rb
@@ -46,7 +46,7 @@ class Tk::Iwidgets::Spinner
end
def __validation_class_list
- super() << EntryfieldValidate
+ super << EntryfieldValidate
end
Tk::ValidateConfigure.__def_validcmd(binding, EntryfieldValidate)
@@ -91,8 +91,8 @@ class Tk::Iwidgets::Spinner
end
alias icursor cursor=
- def index(idx)
- number(tk_send_without_enc('index', idx))
+ def index(index)
+ number(tk_send_without_enc('index', index))
end
def insert(pos,text)
diff --git a/ext/tk/lib/tkextlib/iwidgets/spintime.rb b/ext/tk/lib/tkextlib/iwidgets/spintime.rb
index 0ff683ab56..c1e1f5e5f1 100644
--- a/ext/tk/lib/tkextlib/iwidgets/spintime.rb
+++ b/ext/tk/lib/tkextlib/iwidgets/spintime.rb
@@ -18,16 +18,6 @@ class Tk::Iwidgets::Spintime
WidgetClassName = 'Spintime'.freeze
WidgetClassNames[WidgetClassName] = self
- def __boolval_optkeys
- super() << 'houron' << 'militaryon' << 'minutelabel' << 'secondlabel'
- end
- private :__boolval_optkeys
-
- def __strval_optkeys
- super() << 'hourlabel' << 'minuteon' << 'secondon'
- end
- private :__strval_optkeys
-
def get_string
tk_call(@path, 'get', '-string')
end
diff --git a/ext/tk/lib/tkextlib/iwidgets/tabnotebook.rb b/ext/tk/lib/tkextlib/iwidgets/tabnotebook.rb
index 0d9715f87b..5321331551 100644
--- a/ext/tk/lib/tkextlib/iwidgets/tabnotebook.rb
+++ b/ext/tk/lib/tkextlib/iwidgets/tabnotebook.rb
@@ -23,20 +23,15 @@ class Tk::Iwidgets::Tabnotebook
include TkItemConfigMethod
def __item_cget_cmd(id)
- [self.path, 'pagecget', id]
+ [self.path, 'tabcget', id]
end
private :__item_cget_cmd
def __item_config_cmd(id)
- [self.path, 'pageconfigure', id]
+ [self.path, 'tabconfigure', id]
end
private :__item_config_cmd
- def __item_strval_optkeys(id)
- super(id) << 'tabbackground' << 'tabforeground'
- end
- private :__item_strval_optkeys
-
def tagid(tagOrId)
if tagOrId.kind_of?(Tk::Itk::Component)
tagOrId.name
@@ -56,16 +51,6 @@ class Tk::Iwidgets::Tabnotebook
####################################
- def __boolval_optkeys
- super() << 'auto' << 'equaltabs' << 'raiseselect' << 'tabborders'
- end
- private :__boolval_optkeys
-
- def __strval_optkeys
- super() << 'backdrop' << 'tabbackground' << 'tabforeground'
- end
- private :__strval_optkeys
-
def initialize(*args)
super(*args)
@tabset = self.component_widget('tabset')
diff --git a/ext/tk/lib/tkextlib/iwidgets/tabset.rb b/ext/tk/lib/tkextlib/iwidgets/tabset.rb
index 54e56d0514..1b76916ab7 100644
--- a/ext/tk/lib/tkextlib/iwidgets/tabset.rb
+++ b/ext/tk/lib/tkextlib/iwidgets/tabset.rb
@@ -51,16 +51,6 @@ class Tk::Iwidgets::Tabset
####################################
- def __boolval_optkeys
- super() << 'equaltabs' << 'raiseselect' << 'tabborders'
- end
- private :__boolval_optkeys
-
- def __strval_optkeys
- super() << 'backdrop'
- end
- private :__strval_optkeys
-
def add(keys={})
window(tk_call(@path, 'add', *hash_kv(keys)))
end
diff --git a/ext/tk/lib/tkextlib/iwidgets/timeentry.rb b/ext/tk/lib/tkextlib/iwidgets/timeentry.rb
index 588da77dc8..987cddc1e0 100644
--- a/ext/tk/lib/tkextlib/iwidgets/timeentry.rb
+++ b/ext/tk/lib/tkextlib/iwidgets/timeentry.rb
@@ -17,9 +17,4 @@ class Tk::Iwidgets::Timeentry
TkCommandNames = ['::iwidgets::timeentry'.freeze].freeze
WidgetClassName = 'Timeentry'.freeze
WidgetClassNames[WidgetClassName] = self
-
- def __strval_optkeys
- super() << 'closetext'
- end
- private :__strval_optkeys
end
diff --git a/ext/tk/lib/tkextlib/iwidgets/timefield.rb b/ext/tk/lib/tkextlib/iwidgets/timefield.rb
index 28e1504797..602093eb7e 100644
--- a/ext/tk/lib/tkextlib/iwidgets/timefield.rb
+++ b/ext/tk/lib/tkextlib/iwidgets/timefield.rb
@@ -18,21 +18,6 @@ class Tk::Iwidgets::Timefield
WidgetClassName = 'Timefield'.freeze
WidgetClassNames[WidgetClassName] = self
- def __boolval_optkeys
- super() << 'gmt'
- end
- private :__boolval_optkeys
-
- def __strval_optkeys
- super() << 'textbackground'
- end
- private :__strval_optkeys
-
- def __font_optkeys
- super() << 'textfont'
- end
- private :__font_optkeys
-
def get_string
tk_call(@path, 'get', '-string')
end
diff --git a/ext/tk/lib/tkextlib/iwidgets/toolbar.rb b/ext/tk/lib/tkextlib/iwidgets/toolbar.rb
index 17cfa62156..a2a7f31627 100644
--- a/ext/tk/lib/tkextlib/iwidgets/toolbar.rb
+++ b/ext/tk/lib/tkextlib/iwidgets/toolbar.rb
@@ -18,11 +18,6 @@ class Tk::Iwidgets::Toolbar
WidgetClassName = 'Toolbar'.freeze
WidgetClassNames[WidgetClassName] = self
- def __tkvariable_optkeys
- super() << 'helpvariable'
- end
- private :__tkvariable_optkeys
-
####################################
include TkItemConfigMethod
@@ -37,11 +32,6 @@ class Tk::Iwidgets::Toolbar
end
private :__item_config_cmd
- def __item_strval_optkeys(id)
- super(id) << 'helpstr' << 'balloonstr'
- end
- private :__item_strval_optkeys
-
def tagid(tagOrId)
if tagOrId.kind_of?(Tk::Itk::Component)
tagOrId.name
@@ -53,21 +43,6 @@ class Tk::Iwidgets::Toolbar
####################################
- def __strval_optkeys
- super() << 'balloonbackground' << 'balloonforeground'
- end
- private :__strval_optkeys
-
- def __tkvariable_optkeys
- super() << 'helpvariable'
- end
- private :__tkvariable_optkeys
-
- def __font_optkeys
- super() << 'balloonfont'
- end
- private :__font_optkeys
-
def add(type, tag=nil, keys={})
if tag.kind_of?(Hash)
keys = tag
diff --git a/ext/tk/lib/tkextlib/iwidgets/watch.rb b/ext/tk/lib/tkextlib/iwidgets/watch.rb
index ab2b687cf9..f62c0b931e 100644
--- a/ext/tk/lib/tkextlib/iwidgets/watch.rb
+++ b/ext/tk/lib/tkextlib/iwidgets/watch.rb
@@ -18,17 +18,6 @@ class Tk::Iwidgets::Watch
WidgetClassName = 'Watch'.freeze
WidgetClassNames[WidgetClassName] = self
- def __boolval_optkeys
- super() << 'showampm'
- end
- private :__boolval_optkeys
-
- def __strval_optkeys
- super() << 'clockcolor' << 'hourcolor' << 'minutecolor' <<
- 'pivotcolor' << 'secondcolor' << 'tickcolor'
- end
- private :__strval_optkeys
-
def get_string
tk_call(@path, 'get', '-string')
end
diff --git a/ext/tk/lib/tkextlib/tcllib.rb b/ext/tk/lib/tkextlib/tcllib.rb
index c6138f4275..f238a975a4 100644
--- a/ext/tk/lib/tkextlib/tcllib.rb
+++ b/ext/tk/lib/tkextlib/tcllib.rb
@@ -43,45 +43,24 @@ module Tk
TkComm::TkExtlibAutoloadModule.unshift(self)
# package:: ctext
- autoload :CText, 'tkextlib/tcllib/ctext'
-
- # package:: getstring
- autoload :GetString_Dialog, 'tkextlib/tcllib/getstring'
-
- # package:: history
- autoload :History, 'tkextlib/tcllib/history'
+ autoload :CText, 'tkextlib/tcllib/ctext'
# package:: datefield
- autoload :Datefield, 'tkextlib/tcllib/datefield'
- autoload :DateField, 'tkextlib/tcllib/datefield'
+ autoload :Datefield, 'tkextlib/tcllib/datefield'
+ autoload :DateField, 'tkextlib/tcllib/datefield'
# package:: ico
- autoload :ICO, 'tkextlib/tcllib/ico'
+ autoload :ICO, 'tkextlib/tcllib/ico'
# package:: ipentry
- autoload :IP_Entry, 'tkextlib/tcllib/ip_entry'
- autoload :IPEntry, 'tkextlib/tcllib/ip_entry'
-
- # package:: swaplist
- autoload :Swaplist_Dialog, 'tkextlib/tcllib/swaplist'
+ autoload :IP_Entry, 'tkextlib/tcllib/ip_entry'
+ autoload :IPEntry, 'tkextlib/tcllib/ip_entry'
# package:: Plotchart
- autoload :Plotchart, 'tkextlib/tcllib/plotchart'
-
- # package:: tablelist
- autoload :Tablelist, 'tkextlib/tcllib/tablelist'
- autoload :TableList, 'tkextlib/tcllib/tablelist'
- autoload :Tablelist_Tile, 'tkextlib/tcllib/tablelist_tile'
- autoload :TableList_Tile, 'tkextlib/tcllib/tablelist_tile'
+ autoload :Plotchart, 'tkextlib/tcllib/plotchart'
# package:: tkpiechart
- autoload :Tkpiechart, 'tkextlib/tcllib/tkpiechart'
-
- # package:: tooltip
- autoload :Tooltip, 'tkextlib/tcllib/tooltip'
-
- # package:: widget
- autoload :Wdiget, 'tkextlib/tcllib/widget'
+ autoload :Tkpiechart, 'tkextlib/tcllib/tkpiechart'
end
end
diff --git a/ext/tk/lib/tkextlib/tcllib/autoscroll.rb b/ext/tk/lib/tkextlib/tcllib/autoscroll.rb
index 6940a9174c..256b01ba87 100644
--- a/ext/tk/lib/tkextlib/tcllib/autoscroll.rb
+++ b/ext/tk/lib/tkextlib/tcllib/autoscroll.rb
@@ -31,11 +31,6 @@ require 'tkextlib/tcllib.rb'
module Tk
module Tcllib
module Autoscroll
- PACKAGE_NAME = 'autoscroll'.freeze
- def self.package_name
- PACKAGE_NAME
- end
-
def self.package_version
begin
TkPackage.require('autoscroll')
@@ -125,7 +120,6 @@ class TkScrollbar
end
# TkPackage.require('autoscroll', '1.0')
-# TkPackage.require('autoscroll', '1.1')
TkPackage.require('autoscroll')
module Tk
@@ -143,16 +137,7 @@ module Tk
def self.unautoscroll(win)
tk_call_without_enc('::autoscroll::unautoscroll', win.path)
end
-
- def self.wrap
- # v1.1
- tk_call_without_enc('::autoscroll::wrap')
- end
-
- def self.unwrap
- # v1.1
- tk_call_without_enc('::autoscroll::unwrap')
- end
end
end
end
+
diff --git a/ext/tk/lib/tkextlib/tcllib/ctext.rb b/ext/tk/lib/tkextlib/tcllib/ctext.rb
index 70a45dd8e7..89bfeff0f3 100644
--- a/ext/tk/lib/tkextlib/tcllib/ctext.rb
+++ b/ext/tk/lib/tkextlib/tcllib/ctext.rb
@@ -16,11 +16,6 @@ TkPackage.require('ctext')
module Tk
module Tcllib
class CText < TkText
- PACKAGE_NAME = 'ctext'.freeze
- def self.package_name
- PACKAGE_NAME
- end
-
def self.package_version
begin
TkPackage.require('ctext')
@@ -39,25 +34,13 @@ class Tk::Tcllib::CText
def create_self(keys)
if keys and keys != None
- tk_call_without_enc(self.class::TkCommandNames[0], @path,
- *hash_kv(keys, true))
+ tk_call_without_enc('ctext', @path, *hash_kv(keys, true))
else
- tk_call_without_enc(self.class::TkCommandNames[0], @path)
+ tk_call_without_enc('ctext', @path)
end
end
private :create_self
- def __strval_optkeys
- super() << 'linemapfg' << 'linemapbg' <<
- 'linemap_select_fg' << 'linemap_select_bg'
- end
- private :__strval_optkeys
-
- def __boolval_optkeys
- super() << 'highlight' << 'linemap_markable'
- end
- private :__boolval_optkeys
-
def append(*args)
tk_send('append', *args)
end
diff --git a/ext/tk/lib/tkextlib/tcllib/cursor.rb b/ext/tk/lib/tkextlib/tcllib/cursor.rb
index 9bb828e8dd..92fd7a62b5 100644
--- a/ext/tk/lib/tkextlib/tcllib/cursor.rb
+++ b/ext/tk/lib/tkextlib/tcllib/cursor.rb
@@ -12,11 +12,6 @@ require 'tkextlib/tcllib.rb'
module Tk
module Tcllib
module Cursor
- PACKAGE_NAME = 'cursor'.freeze
- def self.package_name
- PACKAGE_NAME
- end
-
def self.package_version
begin
TkPackage.require('cursor')
@@ -56,7 +51,7 @@ class TkWindow
def cursor_propagate(cursor)
# Sets the cursor for self and all its descendants to cursor.
#tk_call_without_enc('::cursor::propagate', @path, cursor)
- Tk::Tcllib::Cursor.cursor_propagate(self, cursor)
+ Tk::Tcllib::Cursor.cursor_propagate(cursor)
end
def cursor_restore(cursor = None)
# Restore the original or previously set cursor for self and all its
@@ -64,7 +59,7 @@ class TkWindow
# widget that did not have a preset cursor (set by a previous call
# to TkWindow#cursor_propagate).
#tk_call_without_enc('::cursor::restore', @path, cursor)
- Tk::Tcllib::Cursor.cursor_restore(self, cursor)
+ Tk::Tcllib::Cursor.cursor_restore(cursor)
end
end
@@ -80,17 +75,15 @@ module Tk
module Cursor
extend TkCore
def self.cursor_display(win=None)
- tk_call_without_enc('::cursor::display', _epath(win))
+ tk_call_without_enc('::cursor::display', win)
end
def self.cursor_propagate(win, cursor)
- #tk_call_without_enc('::cursor::propagate', win.path, cursor)
- tk_call_without_enc('::cursor::propagate', _epath(win), cursor)
+ tk_call_without_enc('::cursor::propagate', win.path, cursor)
end
def self.cursor_restore(win, cursor = None)
- #tk_call_without_enc('::cursor::restore', win.path, cursor)
- tk_call_without_enc('::cursor::restore', _epath(win), cursor)
+ tk_call_without_enc('::cursor::restore', win.path, cursor)
end
end
end
diff --git a/ext/tk/lib/tkextlib/tcllib/datefield.rb b/ext/tk/lib/tkextlib/tcllib/datefield.rb
index bd84488101..1d029e4569 100644
--- a/ext/tk/lib/tkextlib/tcllib/datefield.rb
+++ b/ext/tk/lib/tkextlib/tcllib/datefield.rb
@@ -25,11 +25,6 @@ TkPackage.require('datefield')
module Tk
module Tcllib
class Datefield < TkEntry
- PACKAGE_NAME = 'datefield'.freeze
- def self.package_name
- PACKAGE_NAME
- end
-
def self.package_version
begin
TkPackage.require('datefield')
@@ -47,10 +42,10 @@ class Tk::Tcllib::Datefield
def create_self(keys)
if keys and keys != None
- tk_call_without_enc(self.class::TkCommandNames[0], @path,
+ tk_call_without_enc('::datefield::datefield', @path,
*hash_kv(keys, true))
else
- tk_call_without_enc(self.class::TkCommandNames[0], @path)
+ tk_call_without_enc('::datefield::datefield', @path)
end
end
private :create_self
diff --git a/ext/tk/lib/tkextlib/tcllib/dialog.rb b/ext/tk/lib/tkextlib/tcllib/dialog.rb
deleted file mode 100644
index 825621b5a1..0000000000
--- a/ext/tk/lib/tkextlib/tcllib/dialog.rb
+++ /dev/null
@@ -1,84 +0,0 @@
-#
-# tkextlib/tcllib/dialog.rb
-# by Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)
-#
-# * Part of tcllib extension
-# * Generic dialog widget (themed)
-#
-
-require 'tk'
-require 'tkextlib/tcllib.rb'
-
-# TkPackage.require('widget::dialog', '1.2')
-TkPackage.require('widget::dialog')
-
-module Tk::Tcllib
- module Widget
- class Dialog < TkWindow
- PACKAGE_NAME = 'widget::dialog'.freeze
- def self.package_name
- PACKAGE_NAME
- end
-
- def self.package_version
- begin
- TkPackage.require('widget::dialog')
- rescue
- ''
- end
- end
- end
- end
-end
-
-class Tk::Tcllib::Widget::Dialog
- TkCommandNames = ['::widget::dialog'.freeze].freeze
-
- def __boolval_optkeys
- ['separator', 'synchronous', 'transient']
- end
- private :__boolval_optkeys
-
- def create_self(keys)
- if keys and keys != None
- tk_call_without_enc(self.class::TkCommandNames[0], @path,
- *hash_kv(keys, true))
- else
- tk_call_without_enc(self.class::TkCommandNames[0], @path)
- end
- end
- private :create_self
-
- def add(what, *args)
- window(tk_send('add', *args))
- end
-
- def get_frame
- window(tk_send('getframe'))
- end
-
- def set_widget(widget)
- tk_send('setwidget', widget)
- self
- end
-
- def display
- tk_send('display')
- self
- end
- alias show display
-
- def cancel
- tk_send('cancel')
- self
- end
-
- def close(reason = None)
- tk_send('close', reason)
- end
-
- def withdraw
- tk_send('withdraw')
- self
- end
-end
diff --git a/ext/tk/lib/tkextlib/tcllib/getstring.rb b/ext/tk/lib/tkextlib/tcllib/getstring.rb
deleted file mode 100644
index bf5e54e8cf..0000000000
--- a/ext/tk/lib/tkextlib/tcllib/getstring.rb
+++ /dev/null
@@ -1,131 +0,0 @@
-#
-# tkextlib/tcllib/getstring.rb
-# by Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)
-#
-# * Part of tcllib extension
-# * A dialog which consists of an Entry, OK, and Cancel buttons.
-#
-
-require 'tk'
-require 'tk/entry'
-require 'tkextlib/tcllib.rb'
-
-# TkPackage.require('getstring', '0.1')
-TkPackage.require('getstring')
-
-module Tk::Tcllib
- class GetString_Dialog < TkWindow
- PACKAGE_NAME = 'getstring'.freeze
- def self.package_name
- PACKAGE_NAME
- end
-
- def self.package_version
- begin
- TkPackage.require('getstring')
- rescue
- ''
- end
- end
- end
-end
-
-
-class Tk::Tcllib::GetString_Dialog
- TkCommandNames = ['::getstring::tk_getString'.freeze].freeze
- WidgetClassName = 'TkSDialog'.freeze
- WidgetClassNames[WidgetClassName] = self
-
- def self.show(*args)
- dialog = self.new(*args)
- dialog.show
- [dialog.status, dialog.value]
- end
- def self.display(*args)
- self.show(*args)
- end
-
- def initialize(*args) # args = (parent=nil, text='', keys=nil)
- keys = args.pop
- if keys.kind_of?(Hash)
- text = args.pop
- @keys = _symbolkey2str(keys)
- args.push(keys)
- else
- text = keys
- @keys = {}
- end
- if text
- @text = text.dup
- else
- @text = ''
- end
-
- @variable = TkVariable.new
- @status = nil
-
- super(*args)
- end
-
- def create_self(keys)
- # dummy
- end
- private :create_self
-
- def show
- @variable.value = ''
- @status = bool(tk_call(self.class::TkCommandNames[0],
- @path, @variable, @text, *hash_kv(@keys)))
- end
- alias display show
-
- def status
- @status
- end
-
- def value
- @variable.value
- end
-
- def cget(slot)
- slot = slot.to_s
- if slot == 'text'
- @text
- else
- @keys[slot]
- end
- end
-
- def configure(slot, value=None)
- if slot.kind_of?(Hash)
- slot.each{|k, v| configure(k, v)}
- else
- slot = slot.to_s
- value = _symbolkey2str(value) if value.kind_of?(Hash)
- if value && value != None
- if slot == 'text'
- @text = value.to_s
- else
- @keys[slot] = value
- end
- else
- if slot == 'text'
- @text = ''
- else
- @keys.delete(slot)
- end
- end
- end
- self
- end
-
- def configinfo(slot = nil)
- if slot
- slot = slot.to_s
- [ slot, nil, nil, nil, ( (slot == 'text')? @text: @keys[slot] ) ]
- else
- @keys.collect{|k, v| [ k, nil, nil, nil, v ] } \
- << [ 'text', nil, nil, nil, @text ]
- end
- end
-end
diff --git a/ext/tk/lib/tkextlib/tcllib/history.rb b/ext/tk/lib/tkextlib/tcllib/history.rb
deleted file mode 100644
index a01a4ebfcc..0000000000
--- a/ext/tk/lib/tkextlib/tcllib/history.rb
+++ /dev/null
@@ -1,73 +0,0 @@
-#
-# tkextlib/tcllib/history.rb
-# by Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)
-#
-# * Part of tcllib extension
-# * Provides a history for Entry widgets
-#
-
-require 'tk'
-require 'tk/entry'
-require 'tkextlib/tcllib.rb'
-
-# TkPackage.require('history', '0.1')
-TkPackage.require('history')
-
-module Tk::Tcllib
- module History
- PACKAGE_NAME = 'history'.freeze
- def self.package_name
- PACKAGE_NAME
- end
-
- def self.package_version
- begin
- TkPackage.require('history')
- rescue
- ''
- end
- end
- end
-end
-
-module Tk::Tcllib::History
- extend TkCore
-
- def self.init(entry, length=None)
- tk_call_without_enc('::history::init', entry.path, length)
- entry.extend(self) # add methods to treat history to the entry widget
- end
-
- def self.remove(entry)
- tk_call_without_enc('::history::remove', entry.path)
- entry
- end
-
- def history_remove
- tk_call_without_enc('::history::remove', @path)
- self
- end
-
- def history_add(text)
- tk_call('::history::add', @path, text)
- self
- end
-
- def history_get
- simplelist(tk_call_without_enc('::history::get', @path))
- end
-
- def history_clear
- tk_call_without_enc('::history::clear', @path)
- self
- end
-
- def history_configure(opt, value)
- tk_call('::history::configure', @path, opt, value)
- self
- end
-
- def history_configinfo(opt)
- tk_call('::history::configure', @path, opt)
- end
-end
diff --git a/ext/tk/lib/tkextlib/tcllib/ico.rb b/ext/tk/lib/tkextlib/tcllib/ico.rb
index 3beeb11a4d..c87275126e 100644
--- a/ext/tk/lib/tkextlib/tcllib/ico.rb
+++ b/ext/tk/lib/tkextlib/tcllib/ico.rb
@@ -16,11 +16,6 @@ TkPackage.require('ico')
module Tk
module Tcllib
class ICO < TkImage
- PACKAGE_NAME = 'ico'.freeze
- def self.package_name
- PACKAGE_NAME
- end
-
def self.package_version
begin
TkPackage.require('ico')
diff --git a/ext/tk/lib/tkextlib/tcllib/ip_entry.rb b/ext/tk/lib/tkextlib/tcllib/ip_entry.rb
index 8c9e0bd683..da9f1eb3a8 100644
--- a/ext/tk/lib/tkextlib/tcllib/ip_entry.rb
+++ b/ext/tk/lib/tkextlib/tcllib/ip_entry.rb
@@ -19,11 +19,6 @@ TkPackage.require('ipentry')
module Tk
module Tcllib
class IP_Entry < TkEntry
- PACKAGE_NAME = 'ipentry'.freeze
- def self.package_name
- PACKAGE_NAME
- end
-
def self.package_version
begin
TkPackage.require('ipentry')
@@ -43,19 +38,13 @@ class Tk::Tcllib::IP_Entry
def create_self(keys)
if keys and keys != None
- tk_call_without_enc(self.class::TkCommandNames[0], @path,
- *hash_kv(keys, true))
+ tk_call_without_enc('::ipentry::ipentry', @path, *hash_kv(keys, true))
else
- tk_call_without_enc(self.class::TkCommandNames[0], @path)
+ tk_call_without_enc('::ipentry::ipentry', @path)
end
end
private :create_self
- def __strval_optkeys
- super() << 'fg' << 'bg' << 'insertbackground'
- end
- private :__strval_optkeys
-
def complete?
bool(tk_send_without_enc('complete'))
end
diff --git a/ext/tk/lib/tkextlib/tcllib/panelframe.rb b/ext/tk/lib/tkextlib/tcllib/panelframe.rb
deleted file mode 100644
index 2a4562e779..0000000000
--- a/ext/tk/lib/tkextlib/tcllib/panelframe.rb
+++ /dev/null
@@ -1,72 +0,0 @@
-#
-# tkextlib/tcllib/panelframe.rb
-# by Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)
-#
-# * Part of tcllib extension
-# * Create PanelFrame widgets.
-#
-
-require 'tk'
-require 'tkextlib/tcllib.rb'
-
-# TkPackage.require('widget::panelframe', '1.0')
-TkPackage.require('widget::panelframe')
-
-module Tk::Tcllib
- module Widget
- class PanelFrame < TkWindow
- PACKAGE_NAME = 'widget::panelframe'.freeze
- def self.package_name
- PACKAGE_NAME
- end
-
- def self.package_version
- begin
- TkPackage.require('widget::panelframe')
- rescue
- ''
- end
- end
- end
- Panelframe = PanelFrame
- end
-end
-
-class Tk::Tcllib::Widget::PanelFrame
- TkCommandNames = ['::widget::panelframe'.freeze].freeze
-
- def create_self(keys)
- if keys and keys != None
- tk_call_without_enc(self.class::TkCommandNames[0], @path,
- *hash_kv(keys, true))
- else
- tk_call_without_enc(self.class::TkCommandNames[0], @path)
- end
- end
- private :create_self
-
- def add(what, *args)
- window(tk_send('add', *args))
- end
-
- #def get_frame
- # window(tk_send('getframe'))
- #end
-
- def set_widget(widget)
- tk_send('setwidget', widget)
- self
- end
-
- def remove(*wins)
- tk_send('remove', *wins)
- end
- def remove_destroy(*wins)
- tk_send('remove', '-destroy', *wins)
- end
- alias delete remove_destroy
-
- def items
- simplelist(tk_send('items')).collect!{|w| window(w)}
- end
-end
diff --git a/ext/tk/lib/tkextlib/tcllib/plotchart.rb b/ext/tk/lib/tkextlib/tcllib/plotchart.rb
index f5f344ceb3..5603ce1283 100644
--- a/ext/tk/lib/tkextlib/tcllib/plotchart.rb
+++ b/ext/tk/lib/tkextlib/tcllib/plotchart.rb
@@ -61,17 +61,11 @@ require 'tk'
require 'tkextlib/tcllib.rb'
# TkPackage.require('Plotchart', '0.9')
-# TkPackage.require('Plotchart', '1.1')
TkPackage.require('Plotchart')
module Tk
module Tcllib
module Plotchart
- PACKAGE_NAME = 'Plotchart'.freeze
- def self.package_name
- PACKAGE_NAME
- end
-
def self.package_version
begin
TkPackage.require('Plotchart')
@@ -273,51 +267,6 @@ module Tk::Tcllib::Plotchart
self
end
- def contourlines(xcrd, ycrd, vals, clss=None)
- xcrd = array2tk_list(xcrd) if xcrd.kind_of?(Array)
- ycrd = array2tk_list(ycrd) if ycrd.kind_of?(Array)
- vals = array2tk_list(vals) if vals.kind_of?(Array)
- clss = array2tk_list(clss) if clss.kind_of?(Array)
-
- tk_call_without_enc(@chart, 'contourlines', xcrd, ycrd, vals, clss)
- self
- end
-
- def contourfill(xcrd, ycrd, vals, klasses=None)
- xcrd = array2tk_list(xcrd) if xcrd.kind_of?(Array)
- ycrd = array2tk_list(ycrd) if ycrd.kind_of?(Array)
- vals = array2tk_list(vals) if vals.kind_of?(Array)
- clss = array2tk_list(clss) if clss.kind_of?(Array)
-
- tk_call_without_enc(@chart, 'contourfill', xcrd, ycrd, vals, clss)
- self
- end
-
- def contourbox(xcrd, ycrd, vals, klasses=None)
- xcrd = array2tk_list(xcrd) if xcrd.kind_of?(Array)
- ycrd = array2tk_list(ycrd) if ycrd.kind_of?(Array)
- vals = array2tk_list(vals) if vals.kind_of?(Array)
- clss = array2tk_list(clss) if clss.kind_of?(Array)
-
- tk_call_without_enc(@chart, 'contourbox', xcrd, ycrd, vals, clss)
- self
- end
-
- def color_map(colors)
- colors = array2tk_list(colors) if colors.kind_of?(Array)
-
- tk_call_without_enc(@chart, 'colorMap', colors)
- self
- end
-
- def grid_cells(xcrd, ycrd)
- xcrd = array2tk_list(xcrd) if xcrd.kind_of?(Array)
- ycrd = array2tk_list(ycrd) if ycrd.kind_of?(Array)
-
- tk_call_without_enc(@chart, 'grid', xcrd, ycrd)
- self
- end
-
def dataconfig(series, key, value=None)
if key.kind_of?(Hash)
tk_call_without_enc(@chart, 'dataconfig', series, *hash_kv(key, true))
@@ -525,13 +474,6 @@ module Tk::Tcllib::Plotchart
self
end
- def plot_funcont(conts, cmd=Proc.new)
- conts = array2tk_list(conts) if conts.kind_of?(Array)
- Tk.ip_eval("proc #{@path}_#{@chart} {x y} {#{install_cmd(cmd)} $x $y}")
- tk_call_without_enc(@chart, 'plotfuncont', "#{@path}_#{@chart}", conts)
- self
- end
-
def grid_size(nxcells, nycells)
tk_call_without_enc(@chart, 'gridsize', nxcells, nycells)
self
@@ -686,7 +628,7 @@ module Tk::Tcllib::Plotchart
# time_end := String of time format (e.g. "1 january 2004")
# items := Expected/maximum number of items
# ( This determines the vertical spacing. )
- if args[0].kind_of?(String)
+ if args[0].kind_of?(Array)
@time_begin = args.shift
@time_end = args.shift
@items = args.shift
@@ -733,105 +675,6 @@ module Tk::Tcllib::Plotchart
end
############################
- class Gnattchart < TkCanvas
- include ChartMethod
-
- TkCommandNames = [
- 'canvas'.freeze,
- '::Plotchart::createGnattchart'.freeze
- ].freeze
-
- def initialize(*args)
- # args := ([parent,] time_begin, time_end, items [, text_width] [, keys])
- # time_begin := String of time format (e.g. "1 january 2004")
- # time_end := String of time format (e.g. "1 january 2004")
- # items := Expected/maximum number of items
- # ( This determines the vertical spacing. )
- if args[0].kind_of?(String)
- @time_begin = args.shift
- @time_end = args.shift
- @items = args.shift
-
- if args[0].kind_of?(Fixnum)
- @text_width = args.shift
- else
- @text_width = None
- end
-
- super(*args) # create canvas widget
- else
- parent = args.shift
-
- @time_begin = args.shift
- @time_end = args.shift
- @items = args.shift
-
- if args[0].kind_of?(Fixnum)
- @text_width = args.shift
- else
- @text_width = None
- end
-
- if parent.kind_of?(TkCanvas)
- @path = parent.path
- else
- super(parent, *args) # create canvas widget
- end
- end
-
- @chart = _create_chart
- end
-
- def _create_chart
- p self.class::TkCommandNames[1] if $DEBUG
- tk_call_without_enc(self.class::TkCommandNames[1], @path,
- @time_begin, @time_end, @items, @text_width)
- end
- private :_create_chart
-
- def task(txt, time_begin, time_end, completed=0.0)
- list(tk_call_without_enc(@chart, 'task', txt, time_begin, time_end,
- completed)).collect!{|id|
- TkcItem.id2obj(self, id)
- }
- end
-
- def milestone(txt, time, col=None)
- tk_call_without_enc(@chart, 'milestone', txt, time, col)
- self
- end
-
- def vertline(txt, time)
- tk_call_without_enc(@chart, 'vertline', txt, time)
- self
- end
-
- def connect(from_task, to_task)
- from_task = array2tk_list(from_task) if from_task.kind_of?(Array)
- to_task = array2tk_list(to_task) if to_task.kind_of?(Array)
-
- tk_call_without_enc(@chart, 'connect', from_task, to_task)
- self
- end
-
- def summary(txt, tasks)
- tasks = array2tk_list(tasks) if tasks.kind_of?(Array)
- tk_call_without_enc(@chart, 'summary', tasks)
- self
- end
-
- def color_of_part(keyword, newcolor)
- tk_call_without_enc(@chart, 'color', keyword, newcolor)
- self
- end
-
- def font_of_part(keyword, newfont)
- tk_call_without_enc(@chart, 'font', keyword, newfont)
- self
- end
- end
-
- ############################
class PlotSeries < TkObject
SeriesID_TBL = TkCore::INTERP.create_table
Series_ID = ['series'.freeze, '00000'.taint].freeze
diff --git a/ext/tk/lib/tkextlib/tcllib/ruler.rb b/ext/tk/lib/tkextlib/tcllib/ruler.rb
deleted file mode 100644
index 88ffb2c912..0000000000
--- a/ext/tk/lib/tkextlib/tcllib/ruler.rb
+++ /dev/null
@@ -1,65 +0,0 @@
-#
-# tkextlib/tcllib/ruler.rb
-# by Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)
-#
-# * Part of tcllib extension
-# * ruler widget
-#
-
-require 'tk'
-require 'tkextlib/tcllib.rb'
-
-# TkPackage.require('widget::ruler', '1.0')
-TkPackage.require('widget::ruler')
-
-module Tk::Tcllib
- module Widget
- class Ruler < TkWindow
- PACKAGE_NAME = 'widget::ruler'.freeze
- def self.package_name
- PACKAGE_NAME
- end
-
- def self.package_version
- begin
- TkPackage.require('widget::ruler')
- rescue
- ''
- end
- end
- end
- end
-end
-
-class Tk::Tcllib::Widget::Ruler
- TkCommandNames = ['::widget::ruler'.freeze].freeze
-
- def __boolval_optkeys
- ['showvalues', 'outline', 'grid']
- end
- private :__boolval_optkeys
-
- def __numlistval_optkeys
- ['interval', 'sizes']
- end
- private :__numlistval_optkeys
-
- def create_self(keys)
- if keys and keys != None
- tk_call_without_enc(self.class::TkCommandNames[0], @path,
- *hash_kv(keys, true))
- else
- tk_call_without_enc(self.class::TkCommandNames[0], @path)
- end
- end
- private :create_self
-
- def redraw
- tk_send('redraw')
- self
- end
-
- def shade(org, dest, frac)
- tk_send('shade', org, dest, frac)
- end
-end
diff --git a/ext/tk/lib/tkextlib/tcllib/screenruler.rb b/ext/tk/lib/tkextlib/tcllib/screenruler.rb
deleted file mode 100644
index 1b4067e2f0..0000000000
--- a/ext/tk/lib/tkextlib/tcllib/screenruler.rb
+++ /dev/null
@@ -1,68 +0,0 @@
-#
-# tkextlib/tcllib/screenruler.rb
-# by Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)
-#
-# * Part of tcllib extension
-# * screenruler dialog
-#
-
-require 'tk'
-require 'tkextlib/tcllib.rb'
-
-# TkPackage.require('widget::screenruler', '1.1')
-TkPackage.require('widget::screenruler')
-
-module Tk::Tcllib
- module Widget
- class ScreenRuler < TkWindow
- PACKAGE_NAME = 'widget::ruler'.freeze
- def self.package_name
- PACKAGE_NAME
- end
-
- def self.package_version
- begin
- TkPackage.require('widget::screenruler')
- rescue
- ''
- end
- end
- end
- Screenruler = ScreenRuler
- end
-end
-
-class Tk::Tcllib::Widget::ScreenRuler
- TkCommandNames = ['::widget::screenruler'.freeze].freeze
-
- def __boolval_optkeys
- ['topmost', 'reflect']
- end
- private :__boolval_optkeys
-
- def __numlistval_optkeys
- ['alpha']
- end
- private :__numlistval_optkeys
-
- def create_self(keys)
- if keys and keys != None
- tk_call_without_enc(self.class::TkCommandNames[0], @path,
- *hash_kv(keys, true))
- else
- tk_call_without_enc(self.class::TkCommandNames[0], @path)
- end
- end
- private :create_self
-
- def display
- tk_send('display')
- self
- end
- alias show display
-
- def hide
- tk_send('hide')
- self
- end
-end
diff --git a/ext/tk/lib/tkextlib/tcllib/scrollwin.rb b/ext/tk/lib/tkextlib/tcllib/scrollwin.rb
deleted file mode 100644
index 717728e34a..0000000000
--- a/ext/tk/lib/tkextlib/tcllib/scrollwin.rb
+++ /dev/null
@@ -1,61 +0,0 @@
-#
-# tkextlib/tcllib/scrollwin.rb
-# by Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)
-#
-# * Part of tcllib extension
-# * Scrolled widget
-#
-
-require 'tk'
-require 'tkextlib/tcllib.rb'
-
-# TkPackage.require('widget::scrolledwindow', '1.0')
-TkPackage.require('widget::scrolledwindow')
-
-module Tk::Tcllib
- module Widget
- class ScrolledWindow < TkWindow
- PACKAGE_NAME = 'widget::scrolledwindow'.freeze
- def self.package_name
- PACKAGE_NAME
- end
-
- def self.package_version
- begin
- TkPackage.require('widget::scrolledwindow')
- rescue
- ''
- end
- end
- end
- Scrolledwindow = ScrolledWindow
- end
-end
-
-class Tk::Tcllib::Widget::ScrolledWindow
- TkCommandNames = ['::widget::scrolledwindow'.freeze].freeze
-
- def __numlistval_optkeys
- ['ipad']
- end
- private :__numlistval_optkeys
-
- def create_self(keys)
- if keys and keys != None
- tk_call_without_enc(self.class::TkCommandNames[0], @path,
- *hash_kv(keys, true))
- else
- tk_call_without_enc(self.class::TkCommandNames[0], @path)
- end
- end
- private :create_self
-
- def get_frame
- window(tk_send('getframe'))
- end
-
- def set_widget(widget)
- tk_send('setwidget', widget)
- self
- end
-end
diff --git a/ext/tk/lib/tkextlib/tcllib/style.rb b/ext/tk/lib/tkextlib/tcllib/style.rb
index dac6916e46..72a99d80fc 100644
--- a/ext/tk/lib/tkextlib/tcllib/style.rb
+++ b/ext/tk/lib/tkextlib/tcllib/style.rb
@@ -11,11 +11,6 @@ require 'tkextlib/tcllib.rb'
module Tk::Tcllib
module Style
- PACKAGE_NAME = 'style'.freeze
- def self.package_name
- PACKAGE_NAME
- end
-
def self.package_version
begin
TkPackage.require('style')
@@ -39,7 +34,6 @@ module Tk::Tcllib
end
# TkPackage.require('style', '0.1')
-# TkPackage.require('style', '0.3')
TkPackage.require('style')
module Tk::Tcllib
diff --git a/ext/tk/lib/tkextlib/tcllib/superframe.rb b/ext/tk/lib/tkextlib/tcllib/superframe.rb
deleted file mode 100644
index 35da37efbf..0000000000
--- a/ext/tk/lib/tkextlib/tcllib/superframe.rb
+++ /dev/null
@@ -1,51 +0,0 @@
-#
-# tkextlib/tcllib/superframe.rb
-# by Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)
-#
-# * Part of tcllib extension
-# * Superframe widget - enhanced labelframe widget
-#
-
-require 'tk'
-require 'tkextlib/tcllib.rb'
-
-# TkPackage.require('widget::superframe', '1.0')
-TkPackage.require('widget::superframe')
-
-module Tk::Tcllib
- module Widget
- class SuperFrame < TkWindow
- PACKAGE_NAME = 'widget::superframe'.freeze
- def self.package_name
- PACKAGE_NAME
- end
-
- def self.package_version
- begin
- TkPackage.require('widget::superframe')
- rescue
- ''
- end
- end
- end
- Superframe = SuperlFrame
- end
-end
-
-class Tk::Tcllib::Widget::SuperFrame
- TkCommandNames = ['::widget::superframe'.freeze].freeze
-
- def create_self(keys)
- if keys and keys != None
- tk_call_without_enc(self.class::TkCommandNames[0], @path,
- *hash_kv(keys, true))
- else
- tk_call_without_enc(self.class::TkCommandNames[0], @path)
- end
- end
- private :create_self
-
- def labelwidget
- window(tk_send('labelwidget'))
- end
-end
diff --git a/ext/tk/lib/tkextlib/tcllib/swaplist.rb b/ext/tk/lib/tkextlib/tcllib/swaplist.rb
deleted file mode 100644
index 97de0a27c1..0000000000
--- a/ext/tk/lib/tkextlib/tcllib/swaplist.rb
+++ /dev/null
@@ -1,147 +0,0 @@
-#
-# tkextlib/tcllib/swaplist.rb
-# by Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)
-#
-# * Part of tcllib extension
-# * A dialog which allows a user to move options between two lists
-#
-
-require 'tk'
-require 'tkextlib/tcllib.rb'
-
-# TkPackage.require('swaplist', '0.1')
-TkPackage.require('swaplist')
-
-module Tk::Tcllib
- class Swaplist_Dialog < TkWindow
- PACKAGE_NAME = 'swaplist'.freeze
- def self.package_name
- PACKAGE_NAME
- end
-
- def self.package_version
- begin
- TkPackage.require('swaplist')
- rescue
- ''
- end
- end
- end
-end
-
-
-class Tk::Tcllib::Swaplist_Dialog
- TkCommandNames = ['::swaplist::swaplist'.freeze].freeze
- WidgetClassName = 'Swaplist'.freeze
- WidgetClassNames[WidgetClassName] = self
-
- def self.show(*args)
- dialog = self.new(*args)
- dialog.show
- [dialog.status, dialog.value]
- end
- def self.display(*args)
- self.show(*args)
- end
-
- def initialize(*args)
- # args = (parent=nil, complete_list=[], selected_list=[], keys=nil)
- keys = args.pop
- if keys.kind_of?(Hash)
- @selected_list = args.pop
- @complete_list = args.pop
- @keys = _symbolkey2str(keys)
- args.push(keys)
- else
- @selected_list = keys
- @complete_list = args.pop
- @keys = {}
- end
-
- @selected_list = [] unless @selected_list
- @complete_list = [] unless @complete_list
-
- @variable = TkVariable.new
- @status = nil
-
- super(*args)
- end
-
- def create_self(keys)
- # dummy
- end
- private :create_self
-
- def show
- @variable.value = ''
- @status = bool(tk_call(self.class::TkCommandNames[0],
- @path, @variable,
- @complete_list, @selected_list,
- *hash_kv(@keys)))
- end
- alias display show
-
- def status
- @status
- end
-
- def value
- @variable.list
- end
- alias selected value
-
- def cget(slot)
- slot = slot.to_s
- if slot == 'complete_list'
- @complete_list
- elsif slot == 'selected_list'
- @selected_list
- else
- @keys[slot]
- end
- end
-
- def configure(slot, value=None)
- if slot.kind_of?(Hash)
- slot.each{|k, v| configure(k, v)}
- else
- slot = slot.to_s
- value = _symbolkey2str(value) if value.kind_of?(Hash)
- if value && value != None
- if slot == 'complete_list'
- @complete_list = value
- elsif slot == 'selected_list'
- @selected_list = value
- else
- @keys[slot] = value
- end
- else
- if slot == 'complete_list'
- @complete_list = []
- elsif slot == 'selected_list'
- @selected_list = []
- else
- @keys.delete(slot)
- end
- end
- end
- self
- end
-
- def configinfo(slot = nil)
- if slot
- slot = slot.to_s
- if slot == 'complete_list'
- [ slot, nil, nil, nil, @complete_list ]
- elsif slot == 'selected_list'
- [ slot, nil, nil, nil, @selected_list ]
- else
- [ slot, nil, nil, nil, @keys[slot] ]
- end
- else
- @keys.collect{|k, v| [ k, nil, nil, nil, v ] } \
- << [ 'complete_list', nil, nil, nil, @complete_list ] \
- << [ 'selected_list', nil, nil, nil, @selected_list ]
- end
- end
-end
diff --git a/ext/tk/lib/tkextlib/tcllib/tablelist.rb b/ext/tk/lib/tkextlib/tcllib/tablelist.rb
deleted file mode 100644
index 42435a1971..0000000000
--- a/ext/tk/lib/tkextlib/tcllib/tablelist.rb
+++ /dev/null
@@ -1,27 +0,0 @@
-#
-# tkextlib/tcllib/tablelist.rb
-# by Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)
-#
-# * Part of tcllib extension
-# * A multi-column listbox
-
-require 'tk'
-require 'tkextlib/tcllib.rb'
-
-# check Tile extension :: If already loaded, use tablelist_tile.
-unless defined? Tk::Tcllib::Tablelist_usingTile
- Tk::Tcllib::Tablelist_usingTile = TkPackage.provide('tile')
-end
-
-if Tk::Tcllib::Tablelist_usingTile
- # with Tile
- require 'tkextlib/tcllib/tablelist_tile'
-
-else
- # without Tile
-
- # TkPackage.require('Tablelist', '4.2')
- TkPackage.require('Tablelist')
-
- requrie 'tkextlib/tcllib/tablelist_core'
-end
diff --git a/ext/tk/lib/tkextlib/tcllib/tablelist_core.rb b/ext/tk/lib/tkextlib/tcllib/tablelist_core.rb
deleted file mode 100644
index a939a58331..0000000000
--- a/ext/tk/lib/tkextlib/tcllib/tablelist_core.rb
+++ /dev/null
@@ -1,770 +0,0 @@
-#
-# tkextlib/tcllib/tablelist_core.rb
-#
-# by Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)
-#
-# * Part of tcllib extension
-# * This file is required by 'tkextlib/tcllib/tablelist.rb' or
-# 'tkextlib/tcllib/tablelist_tile.rb'.
-#
-
-module Tk
- module Tcllib
- class Tablelist < TkWindow
- if Tk::Tcllib::Tablelist_usingTile
- PACKAGE_NAME = 'Tablelist_tile'.freeze
- else
- PACKAGE_NAME = 'Tablelist'.freeze
- end
- def self.package_name
- PACKAGE_NAME
- end
-
- def self.package_version
- begin
- TkPackage.require(self.package_name)
- rescue
- ''
- end
- end
-
- def self.use_Tile?
- (Tk::Tcllib::Tablelist_usingTile)? true: false
- end
- end
- TableList = Tablelist
- end
-end
-
-module Tk::Tcllib::TablelistItemConfig
- include TkItemConfigMethod
-
- def _to_idx(idx)
- if idx.kind_of?(Array)
- idx.collect{|elem| _get_eval_string(elem)}.join(',')
- else
- idx
- end
- end
- def _from_idx(idx)
- return idx unless idx.kind_of?(String)
-
- if idx[0] == ?@ # '@x,y'
- idx
- elsif idx =~ /([^,]+),([^,]+)/
- row = $1, column = $2
- [num_or_str(row), num_or_str(column)]
- else
- num_or_str(idx)
- end
- end
- private :_to_idx, :_from_idx
-
- def __item_cget_cmd(mixed_id)
- [self.path, mixed_id[0] + 'cget', _to_idx(mixed_id[1])]
- end
- def __item_config_cmd(mixed_id)
- [self.path, mixed_id[0] + 'configure', _to_idx(mixed_id[1])]
- end
-
- def cell_cget(tagOrId, option)
- itemcget(['cell', tagOrId], option)
- end
- def cell_configure(tagOrId, slot, value=None)
- itemconfigure(['cell', tagOrId], slot, value)
- end
- def cell_configinfo(tagOrId, slot=nil)
- itemconfiginfo(['cell', tagOrId], slot)
- end
- def current_cell_configinfo(tagOrId, slot=nil)
- current_itemconfiginfo(['cell', tagOrId], slot)
- end
- alias cellcget cell_cget
- alias cellconfigure cell_configure
- alias cellconfiginfo cell_configinfo
- alias current_cellconfiginfo current_cell_configinfo
-
- def column_cget(tagOrId, option)
- itemcget(['column', tagOrId], option)
- end
- def column_configure(tagOrId, slot, value=None)
- itemconfigure(['column', tagOrId], slot, value)
- end
- def column_configinfo(tagOrId, slot=nil)
- itemconfiginfo(['column', tagOrId], slot)
- end
- def current_column_configinfo(tagOrId, slot=nil)
- current_itemconfiginfo(['column', tagOrId], slot)
- end
- alias columncget column_cget
- alias columnconfigure column_configure
- alias columnconfiginfo column_configinfo
- alias current_columnconfiginfo current_column_configinfo
-
- def row_cget(tagOrId, option)
- itemcget(['row', tagOrId], option)
- end
- def row_configure(tagOrId, slot, value=None)
- itemconfigure(['row', tagOrId], slot, value)
- end
- def row_configinfo(tagOrId, slot=nil)
- itemconfiginfo(['row', tagOrId], slot)
- end
- def current_row_configinfo(tagOrId, slot=nil)
- current_itemconfiginfo(['row', tagOrId], slot)
- end
- alias rowcget row_cget
- alias rowconfigure row_configure
- alias rowconfiginfo row_configinfo
- alias current_rowconfiginfo current_row_configinfo
-
- private :itemcget, :itemconfigure
- private :itemconfiginfo, :current_itemconfiginfo
-end
-
-class Tk::Tcllib::Tablelist
- include Tk::Tcllib::TablelistItemConfig
- include Scrollable
-
- TkCommandNames = ['::tablelist::tablelist'.freeze].freeze
- WidgetClassName = 'Tablelist'.freeze
- WidgetClassNames[WidgetClassName] = self
-
- def create_self(keys)
- if keys and keys != None
- tk_call_without_enc(self.class::TkCommandNames[0], @path,
- *hash_kv(keys, true))
- else
- tk_call_without_enc(self.class::TkCommandNames[0], @path)
- end
- end
- private :create_self
-
- ##########################
-
- def __numval_optkeys
- super() + ['titlecolumns']
- end
- private :__numval_optkeys
-
- def __strval_optkeys
- super() + ['snipstring']
- end
- private :__strval_optkeys
-
- def __boolval_optkeys
- super() + [
- 'forceeditendcommand', 'movablecolumns', 'movablerows',
- 'protecttitlecolumns', 'resizablecolumns',
- 'showarrow', 'showlabels', 'showseparators'
- ]
- end
- private :__boolval_optkeys
-
- def __listval_optkeys
- super() + ['columns']
- end
- private :__listval_optkeys
-
- def __tkvariable_optkeys
- super() + ['listvariable']
- end
- private :__tkvariable_optkeys
-
- def __val2ruby_optkeys # { key=>proc, ... }
- # The method is used to convert a opt-value to a ruby's object.
- # When get the value of the option "key", "proc.call(value)" is called.
- super().update('stretch'=>proc{|v| (v == 'all')? v: simplelist(v)})
- end
- private :__val2ruby_optkeys
-
- def __ruby2val_optkeys # { key=>proc, ... }
- # The method is used to convert a ruby's object to a opt-value.
- # When set the value of the option "key", "proc.call(value)" is called.
- # That is, "-#{key} #{proc.call(value)}".
- super().update('stretch'=>proc{|v|
- (v.kind_of?(Array))? v.collect{|e| _to_idx(e)}: v
- })
- end
- private :__ruby2val_optkeys
-
- def __font_optkeys
- super() + ['labelfont']
- end
- private :__font_optkeys
-
- ##########################
-
- def __item_strval_optkeys(id)
- if id[0] == 'cell'
- super(id) + ['title']
- else
- super(id) - ['text'] + ['title']
- end
- end
- private :__item_strval_optkeys
-
- def __item_boolval_optkeys(id)
- super(id) + [
- 'editable', 'hide', 'resizable', 'showarrow', 'stretchable',
- ]
- end
- private :__item_boolval_optkeys
-
- def __item_listval_optkeys(id)
- if id[0] == 'cell'
- super(id)
- else
- super(id) + ['text']
- end
- end
- private :__item_listval_optkeys
-
- def __item_font_optkeys(id)
- # maybe need to override
- super(id) + ['labelfont']
- end
- private :__item_font_optkeys
-
- ##########################
-
- def activate(index)
- tk_send('activate', _to_idx(index))
- self
- end
-
- def activate_cell(index)
- tk_send('activatecell', _to_idx(index))
- self
- end
- alias activatecell activate_cell
-
- def get_attrib(name=nil)
- if name && name != None
- tk_send('attrib', name)
- else
- ret = []
- lst = simplelist(tk_send('attrib'))
- until lst.empty?
- ret << ( [lst.shift] << lst.shift )
- end
- ret
- end
- end
- def set_attrib(*args)
- tk_send('attrib', *(args.flatten))
- self
- end
-
- def bbox(index)
- list(tk_send('bbox', _to_idx(index)))
- end
-
- def bodypath
- window(tk_send('bodypath'))
- end
-
- def bodytag
- TkBindTag.new_by_name(tk_send('bodytag'))
- end
-
- def cancel_editing
- tk_send('cancelediting')
- self
- end
- alias cancelediting cancel_editing
-
- def cellindex(idx)
- _from_idx(tk_send('cellindex', _to_idx(idx)))
- end
-
- def cellselection_anchor(idx)
- tk_send('cellselection', 'anchor', _to_idx(idx))
- self
- end
-
- def cellselection_clear(first, last=nil)
- if first.kind_of?(Array)
- tk_send('cellselection', 'clear', first.collect{|idx| _to_idx(idx)})
- else
- first = _to_idx(first)
- last = (last)? _to_idx(last): first
- tk_send('cellselection', 'clear', first, last)
- end
- self
- end
-
- def cellselection_includes(idx)
- bool(tk_send('cellselection', 'includes', _to_idx(idx)))
- end
-
- def cellselection_set(first, last=nil)
- if first.kind_of?(Array)
- tk_send('cellselection', 'set', first.collect{|idx| _to_idx(idx)})
- else
- first = _to_idx(first)
- last = (last)? _to_idx(last): first
- tk_send('cellselection', 'set', first, last)
- end
- self
- end
-
- def columncount
- number(tk_send('columncount'))
- end
-
- def columnindex(idx)
- number(tk_send('columnindex', _to_idx(idx)))
- end
-
- def containing(y)
- idx = num_or_str(tk_send('containing', y))
- (idx.kind_of?(Fixnum) && idx < 0)? nil: idx
- end
-
- def containing_cell(x, y)
- idx = _from_idx(tk_send('containingcell', x, y))
- if idx.kind_of?(Array)
- [
- ((idx[0].kind_of?(Fixnum) && idx[0] < 0)? nil: idx[0]),
- ((idx[1].kind_of?(Fixnum) && idx[1] < 0)? nil: idx[1])
- ]
- else
- idx
- end
- end
- alias containingcell containing_cell
-
- def containing_column(x)
- idx = num_or_str(tk_send('containingcolumn', x))
- (idx.kind_of?(Fixnum) && idx < 0)? nil: idx
- end
- alias containingcolumn containing_column
-
- def curcellselection
- simplelist(tk_send('curcellselection')).collect!{|idx| _from_idx(idx)}
- end
-
- def curselection
- list(tk_send('curselection'))
- end
-
- def delete_items(first, last=nil)
- if first.kind_of?(Array)
- tk_send('delete', first.collect{|idx| _to_idx(idx)})
- else
- first = _to_idx(first)
- last = (last)? _to_idx(last): first
- tk_send('delete', first, last)
- end
- self
- end
- alias delete delete_items
- alias deleteitems delete_items
-
- def delete_columns(first, last=nil)
- if first.kind_of?(Array)
- tk_send('deletecolumns', first.collect{|idx| _to_idx(idx)})
- else
- first = _to_idx(first)
- last = (last)? _to_idx(last): first
- tk_send('deletecolumns', first, last)
- end
- self
- end
- alias deletecolumns delete_columns
-
- def edit_cell(idx)
- tk_send('editcell', _to_idx(idx))
- self
- end
- alias editcell edit_cell
-
- def editwinpath
- window(tk_send('editwinpath'))
- end
-
- def entrypath
- window(tk_send('entrypath'))
- end
-
- def fill_column(idx, txt)
- tk_send('fillcolumn', _to_idx(idx), txt)
- self
- end
- alias fillcolumn fill_column
-
- def finish_editing
- tk_send('finishediting')
- self
- end
- alias finishediting finish_editing
-
- def get(first, last=nil)
- if first.kind_of?(Array)
- simplelist(tk_send('get', first.collect{|idx| _to_idx(idx)})).collect!{|elem| simplelist(elem) }
- else
- first = _to_idx(first)
- last = (last)? _to_idx(last): first
- simplelist(tk_send('get', first, last))
- end
- end
-
- def get_cells(first, last=nil)
- if first.kind_of?(Array)
- simplelist(tk_send('getcells', first.collect{|idx| _to_idx(idx)})).collect!{|elem| simplelist(elem) }
- else
- first = _to_idx(first)
- last = (last)? _to_idx(last): first
- simplelist(tk_send('getcells', first, last))
- end
- end
- alias getcells get_cells
-
- def get_columns(first, last=nil)
- if first.kind_of?(Array)
- simplelist(tk_send('getcolumns', first.collect{|idx| _to_idx(idx)})).collect!{|elem| simplelist(elem) }
- else
- first = _to_idx(first)
- last = (last)? _to_idx(last): first
- simplelist(tk_send('getcolumns', first, last))
- end
- end
- alias getcolumns get_columns
-
- def get_keys(first, last=nil)
- if first.kind_of?(Array)
- simplelist(tk_send('getkeys', first.collect{|idx| _to_idx(idx)})).collect!{|elem| simplelist(elem) }
- else
- first = _to_idx(first)
- last = (last)? _to_idx(last): first
- simplelist(tk_send('getkeys', first, last))
- end
- end
- alias getkeys get_keys
-
- def imagelabelpath(idx)
- window(tk_send('imagelabelpath', _to_idx(idx)))
- end
-
- def index(idx)
- number(tk_send('index', _to_idx(idx)))
- end
-
- def insert(idx, *items)
- tk_send('insert', _to_idx(idx), *items)
- self
- end
-
- def insert_columnlist(idx, columnlist)
- tk_send('insertcolumnlist', _to_idx(idx), columnlist)
- self
- end
- alias insertcolumnlist insert_columnlist
-
- def insert_columns(idx, *args)
- tk_send('insertcolums', _to_idx(idx), *args)
- self
- end
- alias insertcolumns insert_columns
-
- def insert_list(idx, list)
- tk_send('insertlist', _to_idx(idx), list)
- self
- end
- alias insertlist insert_list
-
- def itemlistvar
- TkVarAccess.new(tk_send('itemlistvar'))
- end
-
- def labelpath(idx)
- window(tk_send('labelpath', _to_idx(idx)))
- end
-
- def labels
- simplelist(tk_send('labels'))
- end
-
- def move(src, target)
- tk_send('move', _to_idx(src), _to_idx(target))
- self
- end
-
- def move_column(src, target)
- tk_send('movecolumn', _to_idx(src), _to_idx(target))
- self
- end
- alias movecolumn move_column
-
- def nearest(y)
- _from_idx(tk_send('nearest', y))
- end
-
- def nearest_cell(x, y)
- _from_idx(tk_send('nearestcell', x, y))
- end
- alias nearestcell nearest_cell
-
- def nearest_column(x)
- _from_idx(tk_send('nearestcolumn', x))
- end
- alias nearestcolumn nearest_column
-
- def reject_input
- tk_send('rejectinput')
- self
- end
- alias rejectinput reject_input
-
- def reset_sortinfo
- tk_send('resetsortinfo')
- self
- end
- alias resetsortinfo reset_sortinfo
-
- def scan_mark(x, y)
- tk_send('scan', 'mark', x, y)
- self
- end
-
- def scan_dragto(x, y)
- tk_send('scan', 'dragto', x, y)
- self
- end
-
- def see(idx)
- tk_send('see', _to_idx(idx))
- self
- end
-
- def see_cell(idx)
- tk_send('seecell', _to_idx(idx))
- self
- end
- alias seecell see_cell
-
- def see_column(idx)
- tk_send('seecolumn', _to_idx(idx))
- self
- end
- alias seecolumn see_column
-
- def selection_anchor(idx)
- tk_send('selection', 'anchor', _to_idx(idx))
- self
- end
-
- def selection_clear(first, last=nil)
- if first.kind_of?(Array)
- tk_send('selection', 'clear', first.collect{|idx| _to_idx(idx)})
- else
- first = _to_idx(first)
- last = (last)? _to_idx(last): first
- tk_send('selection', 'clear', first, last)
- end
- self
- end
-
- def selection_includes(idx)
- bool(tk_send('selection', 'includes', _to_idx(idx)))
- end
-
- def selection_set(first, last=nil)
- if first.kind_of?(Array)
- tk_send('selection', 'set', first.collect{|idx| _to_idx(idx)})
- else
- first = _to_idx(first)
- last = (last)? _to_idx(last): first
- tk_send('selection', 'set', first, last)
- end
- self
- end
-
- def separatorpath(idx=nil)
- if idx
- window(tk_send('separatorpath', _to_idx(idx)))
- else
- window(tk_send('separatorpath'))
- end
- end
-
- def separators
- simplelist(tk_send('separators')).collect!{|w| window(w)}
- end
-
- def size
- number(tk_send('size'))
- end
-
- def sort(order=nil)
- if order
- order = order.to_s
- order = '-' << order if order[0] != ?-
- if order.length < 2
- order = nil
- end
- end
- if order
- tk_send('sort', order)
- else
- tk_send('sort')
- end
- self
- end
- def sort_increasing
- tk_send('sort', '-increasing')
- self
- end
- def sort_decreasing
- tk_send('sort', '-decreasing')
- self
- end
-
- DEFAULT_sortByColumn_cmd = '::tablelist::sortByColumn'
-
- def sort_by_column(idx, order=nil)
- if order
- order = order.to_s
- order = '-' << order if order[0] != ?-
- if order.length < 2
- order = nil
- end
- end
- if order
- tk_send('sortbycolumn', _to_idx(idx), order)
- else
- tk_send('sortbycolumn', _to_idx(idx))
- end
- self
- end
- def sort_by_column_increasing(idx)
- tk_send('sortbycolumn', _to_idx(idx), '-increasing')
- self
- end
- def sort_by_column_decreasing(idx)
- tk_send('sortbycolumn', _to_idx(idx), '-decreasing')
- self
- end
-
- def sortcolumn
- idx = num_or_str(tk_send('sortcolum'))
- (idx.kind_of?(Fixnum) && idx < 0)? nil: idx
- end
-
- def sortorder
- tk_send('sortorder')
- end
-
- def toggle_visibility(first, last=nil)
- if first.kind_of?(Array)
- tk_send('togglevisibility', first.collect{|idx| _to_idx(idx)})
- else
- first = _to_idx(first)
- last = (last)? _to_idx(last): first
- tk_send('togglevisibility', first, last)
- end
- self
- end
- alias togglevisibility toggle_visibility
-
- def windowpath(idx)
- window(tk_send('windowpath', _to_idx(idx)))
- end
-end
-
-class << Tk::Tcllib::Tablelist
- ############################################################
- # helper commands
- def getTablelistPath(descendant)
- window(Tk.tk_call('::tablelist::getTablelistPath', descendant))
- end
-
- def convEventFields(descendant, x, y)
- window(Tk.tk_call('::tablelist::convEventFields', descendant, x, y))
- end
-
-
- ############################################################
- # with the BWidget package
- def addBWidgetEntry(name=None)
- Tk.tk_call('::tablelist::addBWidgetEntry', name)
- end
-
- def addBWidgetSpinBox(name=None)
- Tk.tk_call('::tablelist::addBWidgetSpinBox', name)
- end
-
- def addBWidgetComboBox(name=None)
- Tk.tk_call('::tablelist::addBWidgetComboBox', name)
- end
-
-
- ############################################################
- # with the Iwidgets ([incr Widgets]) package
- def addIncrEntryfield(name=None)
- Tk.tk_call('::tablelist::addIncrEntry', name)
- end
-
- def addIncrDateTimeWidget(type, seconds=false, name=None)
- # type := 'datefield'|'dateentry'|timefield'|'timeentry'
- if seconds && seconds != None
- seconds = '-seconds'
- else
- seconds = None
- end
- Tk.tk_call('::tablelist::addDateTimeWidget', type, seconds, name)
- end
-
- def addIncrSpinner(name=None)
- Tk.tk_call('::tablelist::addIncrSpinner', name)
- end
-
- def addIncrSpinint(name=None)
- Tk.tk_call('::tablelist::addIncrSpinint', name)
- end
-
- def addIncrCombobox(name=None)
- Tk.tk_call('::tablelist::addIncrCombobox', name)
- end
-
-
- ############################################################
- # with Bryan Oakley's combobox package
- def addOakleyCombobox(name=None)
- Tk.tk_call('::tablelist::addOakleyCombobox', name)
- end
-
- ############################################################
- # with the multi-entry package Mentry is a library extension
- def addDateMentry(format, separator, gmt=false, name=None)
- if gmt && gmt != None
- gmt = '-gmt'
- else
- gmt = None
- end
- Tk.tk_call('::tablelist::addDateMentry', format, separator, gmt, name)
- end
-
- def addTimeMentry(format, separator, gmt=false, name=None)
- if gmt && gmt != None
- gmt = '-gmt'
- else
- gmt = None
- end
- Tk.tk_call('::tablelist::addTimeMentry', format, separator, gmt, name)
- end
-
- def addFixedPointMentry(count1, count2, comma=false, name=None)
- if comma && comma != None
- comma = '-comma'
- else
- comma = None
- end
- Tk.tk_call('::tablelist::addFixedPoingMentry', count1, count2, comma, name)
- end
-
- def addIPAddrMentry(name=None)
- Tk.tk_call('::tablelist::addIPAddrMentry', name)
- end
-end
diff --git a/ext/tk/lib/tkextlib/tcllib/tablelist_tile.rb b/ext/tk/lib/tkextlib/tcllib/tablelist_tile.rb
deleted file mode 100644
index 0cb4eb735d..0000000000
--- a/ext/tk/lib/tkextlib/tcllib/tablelist_tile.rb
+++ /dev/null
@@ -1,25 +0,0 @@
-#
-# tkextlib/tcllib/tablelist_tlie.rb
-# by Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)
-#
-# * Part of tcllib extension
-# * A multi-column listbox
-
-require 'tk'
-require 'tkextlib/tcllib.rb'
-
-# TkPackage.require('tablelist_tile', '4.2')
-TkPackage.require('Tablelist_tile')
-
-unless defined? Tk::Tcllib::Tablelist_usingTile
- Tk::Tcllib::Tablelist_usingTile = true
-end
-
-requrie 'tkextlib/tcllib/tablelist_core'
-
-module Tk
- module Tcllib
- Tablelist_Tile = Tablelist
- TableList_Tile = Tablelist
- end
-end
diff --git a/ext/tk/lib/tkextlib/tcllib/tkpiechart.rb b/ext/tk/lib/tkextlib/tcllib/tkpiechart.rb
index 92dde65ce7..4e6008bb3b 100644
--- a/ext/tk/lib/tkextlib/tcllib/tkpiechart.rb
+++ b/ext/tk/lib/tkextlib/tcllib/tkpiechart.rb
@@ -21,11 +21,6 @@ module Tk
end
module Tk::Tcllib::Tkpiechart
- PACKAGE_NAME = 'tkpiechart'.freeze
- def self.package_name
- PACKAGE_NAME
- end
-
def self.package_version
begin
TkPackage.require('tkpiechart')
@@ -56,22 +51,6 @@ module Tk::Tcllib::Tkpiechart
:default_value=>1, :current_value=>2}
end
private :__configinfo_struct
-
- def __boolval_optkeys
- super() << 'select' << 'autoupdate' << 'selectable'
- end
- private :__boolval_optkeys
-
- def __strval_optkeys
- super() << 'bordercolor' << 'textbackground' <<
- 'widestvaluetext' << 'title'
- end
- private :__strval_optkeys
-
- def __listval_optkeys
- super() << 'colors'
- end
- private :__listval_optkeys
end
####################################
diff --git a/ext/tk/lib/tkextlib/tcllib/tooltip.rb b/ext/tk/lib/tkextlib/tcllib/tooltip.rb
deleted file mode 100644
index 4301b39fd3..0000000000
--- a/ext/tk/lib/tkextlib/tcllib/tooltip.rb
+++ /dev/null
@@ -1,95 +0,0 @@
-#
-# tkextlib/tcllib/tooltip.rb
-# by Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)
-#
-# * Part of tcllib extension
-# * Provides tooltips, a small text message that is displayed when the
-# mouse hovers over a widget.
-#
-
-require 'tk'
-require 'tkextlib/tcllib.rb'
-
-# TkPackage.require('tooltip', '1.1')
-TkPackage.require('tooltip')
-
-module Tk::Tcllib
- module Tooltip
- PACKAGE_NAME = 'tooltip'.freeze
- def self.package_name
- PACKAGE_NAME
- end
-
- def self.package_version
- begin
- TkPackage.require('tooltip')
- rescue
- ''
- end
- end
- end
-end
-
-module Tk::Tcllib::Tooltip
- extend TkCore
-
- WidgetClassName = 'Tooltip'.freeze
- def self.database_classname
- self::WidgetClassName
- end
- def self.database_class
- WidgetClassNames[self::WidgetClassName]
- end
-
- def self.clear(glob_path_pat = None)
- self.clear_glob(glob_path_pat)
- end
-
- def self.clear_glob(glob_path_pat)
- tk_call_without_enc('::tooltip::tooltip', 'clear', glob_path_pat)
- end
-
- def self.clear_widgets(*args)
- self.clear_glob("{#{args.collect{|w| _get_eval_string(w)}.join(',')}}")
- end
-
- def self.clear_children(*args)
- self.clear_glob("{#{args.collect{|w| s = _get_eval_string(w); "#{s},#{s}.*"}.join(',')}}")
- end
-
- def self.delay(millisecs=None)
- number(tk_call_without_enc('::tooltip::tooltip', 'delay', millisecs))
- end
- def self.delay=(millisecs)
- self.delay(millisecs)
- end
-
- def self.disable
- tk_call_without_enc('::tooltip::tooltip', 'disable')
- false
- end
- def self.off
- self.disable
- end
-
- def self.enable
- tk_call_without_enc('::tooltip::tooltip', 'enable')
- true
- end
- def self.on
- self.enable
- end
-
- def self.register(widget, msg, keys=nil)
- if keys.kind_of?(Hash)
- args = hash_kv(keys) << msg
- else
- args = msg
- end
- tk_call_without_enc('::tooltip::tooltip', widget.path, *args)
- end
-
- def self.erase(widget)
- tk_call_without_enc('::tooltip::tooltip', widget.path, '')
- end
-end
diff --git a/ext/tk/lib/tkextlib/tcllib/widget.rb b/ext/tk/lib/tkextlib/tcllib/widget.rb
deleted file mode 100644
index ed69f67ce6..0000000000
--- a/ext/tk/lib/tkextlib/tcllib/widget.rb
+++ /dev/null
@@ -1,48 +0,0 @@
-#
-# tkextlib/tcllib/widget.rb
-# by Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)
-#
-# * Part of tcllib extension
-# * megawidget package that uses snit as the object system (snidgets)
-#
-
-require 'tk'
-require 'tkextlib/tcllib.rb'
-
-# TkPackage.require('widget', '3.0')
-TkPackage.require('widget')
-
-module Tk::Tcllib
- module Widget
- PACKAGE_NAME = 'widget'.freeze
- def self.package_name
- PACKAGE_NAME
- end
-
- def self.package_version
- begin
- TkPackage.require('widget')
- rescue
- ''
- end
- end
- end
-end
-
-module Tk::Tcllib::Widget
- autoload :Dialog, 'tkextlib/tcllib/dialog'
-
- autoload :Panelframe, 'tkextlib/tcllib/panelframe'
- autoload :PanelFrame, 'tkextlib/tcllib/panelframe'
-
- autoload :Ruler, 'tkextlib/tcllib/ruler'
-
- autoload :Screenruler, 'tkextlib/tcllib/screenruler'
- autoload :ScreenRuler, 'tkextlib/tcllib/screenruler'
-
- autoload :Scrolledwindow, 'tkextlib/tcllib/scrollwin'
- autoload :ScrolledWindow, 'tkextlib/tcllib/scrollwin'
-
- autoload :Superframe, 'tkextlib/tcllib/superframe'
- autoload :SuperFrame, 'tkextlib/tcllib/superframe'
-end
diff --git a/ext/tk/lib/tkextlib/tclx/tclx.rb b/ext/tk/lib/tkextlib/tclx/tclx.rb
index 5a908fcd0b..760ebd92b1 100644
--- a/ext/tk/lib/tkextlib/tclx/tclx.rb
+++ b/ext/tk/lib/tkextlib/tclx/tclx.rb
@@ -15,11 +15,6 @@ TkPackage.require('Tclx')
module Tk
module TclX
- PACKAGE_NAME = 'Tclx'.freeze
- def self.package_name
- PACKAGE_NAME
- end
-
def self.package_version
begin
TkPackage.require('Tclx')
@@ -32,16 +27,6 @@ module Tk
Tk.tk_call('infox', *args)
end
- def self.signal(*args)
- warn("Warning: Don't recommend to use TclX's 'signal' command. Please use Ruby's 'Signal.trap' method")
- Tk.tk_call('signal', *args)
- end
-
- def self.signal_restart(*args)
- warn("Warning: Don't recommend to use TclX's 'signal' command. Please use Ruby's 'Signal.trap' method")
- Tk.tk_call('signal', '-restart', *args)
- end
-
##############################
class XPG3_MsgCat
diff --git a/ext/tk/lib/tkextlib/tile.rb b/ext/tk/lib/tkextlib/tile.rb
index de079ca53d..80a9083694 100644
--- a/ext/tk/lib/tkextlib/tile.rb
+++ b/ext/tk/lib/tkextlib/tile.rb
@@ -13,45 +13,13 @@ require 'tkextlib/tile/setup.rb'
# load package
# TkPackage.require('tile', '0.4')
-# TkPackage.require('tile', '0.6')
-verstr = TkPackage.require('tile')
-ver = verstr.split('.')
-if ver[0].to_i == 0 && ver[1].to_i <= 4
- # version 0.4 or former
- module Tk
- module Tile
- USE_TILE_NAMESPACE = true
- TILE_SPEC_VERSION_ID = 0
- end
- end
-elsif ver[0].to_i == 0 && ver[1].to_i <= 6
- # version 0.5 -- version 0.6
- module Tk
- module Tile
- USE_TILE_NAMESPACE = true
- TILE_SPEC_VERSION_ID = 5
- end
- end
-else
- # version 0.7 or later
- module Tk
- module Tile
- USE_TILE_NAMESPACE = false
- TILE_SPEC_VERSION_ID = 7
- end
- end
-end
+TkPackage.require('tile')
# autoload
module Tk
module Tile
TkComm::TkExtlibAutoloadModule.unshift(self)
- PACKAGE_NAME = 'tile'.freeze
- def self.package_name
- PACKAGE_NAME
- end
-
def self.package_version
begin
TkPackage.require('tile')
@@ -60,83 +28,7 @@ module Tk
end
end
- def self.__Import_Tile_Widgets__!
- Tk.tk_call('namespace', 'import', 'ttk::*')
- end
-
- def self.load_images(imgdir, pat=TkComm::None)
- images = Hash[*TkComm.simplelist(Tk.tk_call('::tile::LoadImages',
- imgdir, pat))]
- images.keys.each{|k|
- images[k] = TkPhotoImage.new(:imagename=>images[k],
- :without_creating=>true)
- }
-
- images
- end
-
- def self.style(*args)
- args.map!{|arg| TkComm._get_eval_string(arg)}.join('.')
- end
-
- module KeyNav
- def self.enableMnemonics(w)
- Tk.tk_call('::keynav::enableMnemonics', w)
- end
- def self.defaultButton(w)
- Tk.tk_call('::keynav::defaultButton', w)
- end
- end
-
- module Font
- Default = 'TkDefaultFont'
- Text = 'TkTextFont'
- Heading = 'TkHeadingFont'
- Caption = 'TkCaptionFont'
- Tooltip = 'TkTooltipFont'
-
- Fixed = 'TkFixedFont'
- Menu = 'TkMenuFont'
- SmallCaption = 'TkSmallCaptionFont'
- Icon = 'TkIconFont'
- end
-
- module ParseStyleLayout
- def _style_layout(lst)
- ret = []
- until lst.empty?
- sub = [lst.shift]
- keys = {}
-
- until lst.empty?
- if lst[0][0] == ?-
- k = lst.shift[1..-1]
- children = lst.shift
- children = _style_layout(children) if children.kind_of?(Array)
- keys[k] = children
- else
- break
- end
- end
-
- sub << keys unless keys.empty?
- ret << sub
- end
- ret
- end
- private :_style_layout
- end
-
module TileWidget
- include Tk::Tile::ParseStyleLayout
-
- def __val2ruby_optkeys # { key=>proc, ... }
- # The method is used to convert a opt-value to a ruby's object.
- # When get the value of the option "key", "proc.call(value)" is called.
- super().update('style'=>proc{|v| _style_layout(list(v))})
- end
- private :__val2ruby_optkeys
-
def instate(state, script=nil, &b)
if script
tk_send('instate', state, script)
@@ -159,62 +51,18 @@ module Tk
######################################
autoload :TButton, 'tkextlib/tile/tbutton'
- autoload :Button, 'tkextlib/tile/tbutton'
autoload :TCheckButton, 'tkextlib/tile/tcheckbutton'
- autoload :CheckButton, 'tkextlib/tile/tcheckbutton'
autoload :TCheckbutton, 'tkextlib/tile/tcheckbutton'
- autoload :Checkbutton, 'tkextlib/tile/tcheckbutton'
-
- autoload :Dialog, 'tkextlib/tile/dialog'
-
- autoload :TEntry, 'tkextlib/tile/tentry'
- autoload :Entry, 'tkextlib/tile/tentry'
-
- autoload :TCombobox, 'tkextlib/tile/tcombobox'
- autoload :Combobox, 'tkextlib/tile/tcombobox'
-
- autoload :TFrame, 'tkextlib/tile/tframe'
- autoload :Frame, 'tkextlib/tile/tframe'
-
- autoload :TLabelframe, 'tkextlib/tile/tlabelframe'
- autoload :Labelframe, 'tkextlib/tile/tlabelframe'
autoload :TLabel, 'tkextlib/tile/tlabel'
- autoload :Label, 'tkextlib/tile/tlabel'
autoload :TMenubutton, 'tkextlib/tile/tmenubutton'
- autoload :Menubutton, 'tkextlib/tile/tmenubutton'
autoload :TNotebook, 'tkextlib/tile/tnotebook'
- autoload :Notebook, 'tkextlib/tile/tnotebook'
-
- autoload :TPaned, 'tkextlib/tile/tpaned'
- autoload :Paned, 'tkextlib/tile/tpaned'
-
- autoload :TProgressbar, 'tkextlib/tile/tprogressbar'
- autoload :Progressbar, 'tkextlib/tile/tprogressbar'
autoload :TRadioButton, 'tkextlib/tile/tradiobutton'
- autoload :RadioButton, 'tkextlib/tile/tradiobutton'
autoload :TRadiobutton, 'tkextlib/tile/tradiobutton'
- autoload :Radiobutton, 'tkextlib/tile/tradiobutton'
-
- autoload :TScale, 'tkextlib/tile/tscale'
- autoload :Scale, 'tkextlib/tile/tscale'
- autoload :TProgress, 'tkextlib/tile/tscale'
- autoload :Progress, 'tkextlib/tile/tscale'
-
- autoload :TScrollbar, 'tkextlib/tile/tscrollbar'
- autoload :Scrollbar, 'tkextlib/tile/tscrollbar'
-
- autoload :TSeparator, 'tkextlib/tile/tseparator'
- autoload :Separator, 'tkextlib/tile/tseparator'
-
- autoload :TSquare, 'tkextlib/tile/tsquare'
- autoload :Square, 'tkextlib/tile/tsquare'
-
- autoload :Treeview, 'tkextlib/tile/treeview'
autoload :Style, 'tkextlib/tile/style'
end
diff --git a/ext/tk/lib/tkextlib/tile/dialog.rb b/ext/tk/lib/tkextlib/tile/dialog.rb
deleted file mode 100644
index f8ddf62598..0000000000
--- a/ext/tk/lib/tkextlib/tile/dialog.rb
+++ /dev/null
@@ -1,84 +0,0 @@
-#
-# ttk::dialog (tile-0.7+)
-# by Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)
-#
-require 'tk'
-require 'tkextlib/tile.rb'
-
-module Tk
- module Tile
- class Dialog < TkWindow
- end
- end
-end
-
-class Tk::Tile::Dialog
- TkCommandNames = ['::ttk::dialog'.freeze].freeze
-
- def self.show(*args)
- dialog = self.new(*args)
- dialog.show
- [dialog.status, dialog.value]
- end
- def self.display(*args)
- self.show(*args)
- end
-
- def self.define_dialog_type(name, keys)
- Tk.tk_call('::ttk::dialog::define', name, keys)
- name
- end
-
- def self.style(*args)
- ['Dialog', *(args.map!{|a| _get_eval_string(a)})].join('.')
- end
-
- #########################
-
- def initialize(keys={})
- @keys = _symbolkey2str(keys)
- super(*args)
- end
-
- def create_self(keys)
- # dummy
- end
- private :create_self
-
- def show
- tk_call(self.class::TkCommandNames[0], @path, *hash_kv(@keys))
- end
- alias display show
-
- def client_frame
- window(tk_call_without_enc('::ttk::dialog::clientframe'))
- end
-
- def cget(slot)
- @keys[slot]
- end
-
- def configure(slot, value=None)
- if slot.kind_of?(Hash)
- slot.each{|k, v| configure(k, v)}
- else
- slot = slot.to_s
- value = _symbolkey2str(value) if value.kind_of?(Hash)
- if value && value != None
- @keys[slot] = value
- else
- @keys.delete(slot)
- end
- end
- self
- end
-
- def configinfo(slot = nil)
- if slot
- slot = slot.to_s
- [ slot, nil, nil, nil, @keys[slot] ]
- else
- @keys.collect{|k, v| [ k, nil, nil, nil, v ] }
- end
- end
-end
diff --git a/ext/tk/lib/tkextlib/tile/style.rb b/ext/tk/lib/tkextlib/tile/style.rb
index 485a36d7d6..1e399182da 100644
--- a/ext/tk/lib/tkextlib/tile/style.rb
+++ b/ext/tk/lib/tkextlib/tile/style.rb
@@ -17,34 +17,15 @@ module Tk::Tile::Style
end
class << Tk::Tile::Style
- def configure(style=nil, keys=nil)
- if style.kind_of?(Hash)
- keys = style
- style = nil
- end
- style = '.' unless style
-
- if Tk::Tile::TILE_SPEC_VERSION_ID < 7
- sub_cmd = 'default'
- else
- sub_cmd = 'configure'
- end
-
+ def default(style, keys=nil)
if keys && keys != None
- tk_call('style', sub_cmd, style, *hash_kv(keys))
+ tk_call('style', 'default', style, *hash_kv(keys))
else
- tk_call('style', sub_cmd, style)
+ tk_call('style', 'default', style)
end
end
- alias default configure
-
- def map(style=nil, keys=nil)
- if style.kind_of?(Hash)
- keys = style
- style = nil
- end
- style = '.' unless style
+ def map(style, keys=nil)
if keys && keys != None
tk_call('style', 'map', style, *hash_kv(keys))
else
@@ -52,19 +33,11 @@ class << Tk::Tile::Style
end
end
- include Tk::Tile::ParseStyleLayout
-
- def layout(style=nil, spec=nil)
- if style.kind_of?(Hash)
- spec = style
- style = nil
- end
- style = '.' unless style
-
+ def layout(style, spec=nil)
if spec
tk_call('style', 'layout', style, spec)
else
- _style_layout(list(tk_call('style', 'layout', style)))
+ tk_call('style', 'layout', style)
end
end
@@ -76,21 +49,15 @@ class << Tk::Tile::Style
list(tk_call('style', 'element', 'names'))
end
- def element_options(elem)
- simplelist(tk_call('style', 'element', 'options', elem))
- end
-
def theme_create(name, keys=nil)
if keys && keys != None
- tk_call('style', 'theme', 'create', name, *hash_kv(keys))
+ tk_call('style', 'theme', 'create', name, type, *hash_kv(keys))
else
- tk_call('style', 'theme', 'create', name)
+ tk_call('style', 'theme', 'create', name, type)
end
end
def theme_settings(name, cmd=nil, &b)
- cmd = Proc.new(&b) if !cmd && b
- tk_call('style', 'theme', 'settings', name, cmd)
end
def theme_names()
@@ -98,6 +65,6 @@ class << Tk::Tile::Style
end
def theme_use(name)
- tk_call('style', 'theme', 'use', name)
+ tk_call('style', 'use', name)
end
end
diff --git a/ext/tk/lib/tkextlib/tile/tbutton.rb b/ext/tk/lib/tkextlib/tile/tbutton.rb
index 1142a27100..b5c3475692 100644
--- a/ext/tk/lib/tkextlib/tile/tbutton.rb
+++ b/ext/tk/lib/tkextlib/tile/tbutton.rb
@@ -9,22 +9,22 @@ module Tk
module Tile
class TButton < TkButton
end
- Button = TButton
end
end
class Tk::Tile::TButton < TkButton
include Tk::Tile::TileWidget
- if Tk::Tile::USE_TTK_NAMESPACE
- TkCommandNames = ['::ttk::button'.freeze].freeze
- else
- TkCommandNames = ['::tbutton'.freeze].freeze
- end
+ TkCommandNames = ['tbutton'.freeze].freeze
WidgetClassName = 'TButton'.freeze
WidgetClassNames[WidgetClassName] = self
- def self.style(*args)
- [self::WidgetClassName, *(args.map!{|a| _get_eval_string(a)})].join('.')
+ def create_self(keys)
+ if keys and keys != None
+ tk_call_without_enc('tbutton', @path, *hash_kv(keys, true))
+ else
+ tk_call_without_enc('tbutton', @path)
+ end
end
+ private :create_self
end
diff --git a/ext/tk/lib/tkextlib/tile/tcheckbutton.rb b/ext/tk/lib/tkextlib/tile/tcheckbutton.rb
index fce799683d..4ba77d95d3 100644
--- a/ext/tk/lib/tkextlib/tile/tcheckbutton.rb
+++ b/ext/tk/lib/tkextlib/tile/tcheckbutton.rb
@@ -10,23 +10,22 @@ module Tk
class TCheckButton < TkCheckButton
end
TCheckbutton = TCheckButton
- CheckButton = TCheckButton
- Checkbutton = TCheckButton
end
end
class Tk::Tile::TCheckButton < TkCheckButton
include Tk::Tile::TileWidget
- if Tk::Tile::USE_TTK_NAMESPACE
- TkCommandNames = ['::ttk::checkbutton'.freeze].freeze
- else
- TkCommandNames = ['::tcheckbutton'.freeze].freeze
- end
+ TkCommandNames = ['tcheckbutton'.freeze].freeze
WidgetClassName = 'TCheckbutton'.freeze
WidgetClassNames[WidgetClassName] = self
- def self.style(*args)
- [self::WidgetClassName, *(args.map!{|a| _get_eval_string(a)})].join('.')
+ def create_self(keys)
+ if keys and keys != None
+ tk_call_without_enc('tcheckbutton', @path, *hash_kv(keys, true))
+ else
+ tk_call_without_enc('tcheckbutton', @path)
+ end
end
+ private :create_self
end
diff --git a/ext/tk/lib/tkextlib/tile/tcombobox.rb b/ext/tk/lib/tkextlib/tile/tcombobox.rb
deleted file mode 100644
index c63ab94dbe..0000000000
--- a/ext/tk/lib/tkextlib/tile/tcombobox.rb
+++ /dev/null
@@ -1,55 +0,0 @@
-#
-# tcombobox widget
-# by Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)
-#
-require 'tk'
-require 'tkextlib/tile.rb'
-
-module Tk
- module Tile
- class TCombobox < Tk::Tile::TEntry
- end
- Combobox = TCombobox
- end
-end
-
-class Tk::Tile::TCombobox < Tk::Tile::TEntry
- include Tk::Tile::TileWidget
-
- if Tk::Tile::USE_TTK_NAMESPACE
- TkCommandNames = ['::ttk::combobox'.freeze].freeze
- else
- TkCommandNames = ['::tcombobox'.freeze].freeze
- end
- WidgetClassName = 'TCombobox'.freeze
- WidgetClassNames[WidgetClassName] = self
-
- def __boolval_optkeys
- super() << 'exportselection'
- end
- private :__boolval_optkeys
-
- def __listval_optkeys
- super() << 'values'
- end
- private :__listval_optkeys
-
- def self.style(*args)
- [self::WidgetClassName, *(args.map!{|a| _get_eval_string(a)})].join('.')
- end
-
- def current
- number(tk_send_without_enc('current', idx))
- end
- def current=(idx)
- tk_send_without_enc('current', idx)
- end
-
- def identify(x, y)
- tk_send_without_enc('identify', x, y)
- end
-
- def set(val)
- tk_send('set', val)
- end
-end
diff --git a/ext/tk/lib/tkextlib/tile/tentry.rb b/ext/tk/lib/tkextlib/tile/tentry.rb
deleted file mode 100644
index 4d57ce7756..0000000000
--- a/ext/tk/lib/tkextlib/tile/tentry.rb
+++ /dev/null
@@ -1,40 +0,0 @@
-#
-# tentry widget
-# by Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)
-#
-require 'tk'
-require 'tkextlib/tile.rb'
-
-module Tk
- module Tile
- class TEntry < TkEntry
- end
- Entry = TEntry
- end
-end
-
-class Tk::Tile::TEntry < TkEntry
- include Tk::Tile::TileWidget
-
- if Tk::Tile::USE_TTK_NAMESPACE
- TkCommandNames = ['::ttk::entry'.freeze].freeze
- else
- TkCommandNames = ['::tentry'.freeze].freeze
- end
- WidgetClassName = 'TEntry'.freeze
- WidgetClassNames[WidgetClassName] = self
-
- def __boolval_optkeys
- super() << 'exportselection'
- end
- private :__boolval_optkeys
-
- def __strval_optkeys
- super() << 'show'
- end
- private :__strval_optkeys
-
- def self.style(*args)
- [self::WidgetClassName, *(args.map!{|a| _get_eval_string(a)})].join('.')
- end
-end
diff --git a/ext/tk/lib/tkextlib/tile/tframe.rb b/ext/tk/lib/tkextlib/tile/tframe.rb
deleted file mode 100644
index 691c9c42af..0000000000
--- a/ext/tk/lib/tkextlib/tile/tframe.rb
+++ /dev/null
@@ -1,30 +0,0 @@
-#
-# tframe widget
-# by Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)
-#
-require 'tk'
-require 'tkextlib/tile.rb'
-
-module Tk
- module Tile
- class TFrame < TkFrame
- end
- Frame = TFrame
- end
-end
-
-class Tk::Tile::TFrame < TkFrame
- include Tk::Tile::TileWidget
-
- if Tk::Tile::USE_TTK_NAMESPACE
- TkCommandNames = ['::ttk::frame'.freeze].freeze
- else
- TkCommandNames = ['::tframe'.freeze].freeze
- end
- WidgetClassName = 'TFrame'.freeze
- WidgetClassNames[WidgetClassName] = self
-
- def self.style(*args)
- [self::WidgetClassName, *(args.map!{|a| _get_eval_string(a)})].join('.')
- end
-end
diff --git a/ext/tk/lib/tkextlib/tile/tlabel.rb b/ext/tk/lib/tkextlib/tile/tlabel.rb
index 4111d1906a..d2eaf45273 100644
--- a/ext/tk/lib/tkextlib/tile/tlabel.rb
+++ b/ext/tk/lib/tkextlib/tile/tlabel.rb
@@ -9,22 +9,22 @@ module Tk
module Tile
class TLabel < TkLabel
end
- Label = TLabel
end
end
class Tk::Tile::TLabel < TkLabel
include Tk::Tile::TileWidget
- if Tk::Tile::USE_TTK_NAMESPACE
- TkCommandNames = ['::ttk::label'.freeze].freeze
- else
- TkCommandNames = ['::tlabel'.freeze].freeze
- end
+ TkCommandNames = ['tlabel'.freeze].freeze
WidgetClassName = 'TLabel'.freeze
WidgetClassNames[WidgetClassName] = self
- def self.style(*args)
- [self::WidgetClassName, *(args.map!{|a| _get_eval_string(a)})].join('.')
+ def create_self(keys)
+ if keys and keys != None
+ tk_call_without_enc('tlabel', @path, *hash_kv(keys, true))
+ else
+ tk_call_without_enc('tlabel', @path)
+ end
end
+ private :create_self
end
diff --git a/ext/tk/lib/tkextlib/tile/tlabelframe.rb b/ext/tk/lib/tkextlib/tile/tlabelframe.rb
deleted file mode 100644
index 8981232b25..0000000000
--- a/ext/tk/lib/tkextlib/tile/tlabelframe.rb
+++ /dev/null
@@ -1,30 +0,0 @@
-#
-# tlabelframe widget
-# by Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)
-#
-require 'tk'
-require 'tkextlib/tile.rb'
-
-module Tk
- module Tile
- class TLabelframe < Tk::Tile::TFrame
- end
- Labelframe = TLabelframe
- end
-end
-
-class Tk::Tile::TLabelframe < Tk::Tile::TFrame
- include Tk::Tile::TileWidget
-
- if Tk::Tile::USE_TTK_NAMESPACE
- TkCommandNames = ['::ttk::labelframe'.freeze].freeze
- else
- TkCommandNames = ['::tlabelframe'.freeze].freeze
- end
- WidgetClassName = 'TLabelframe'.freeze
- WidgetClassNames[WidgetClassName] = self
-
- def self.style(*args)
- [self::WidgetClassName, *(args.map!{|a| _get_eval_string(a)})].join('.')
- end
-end
diff --git a/ext/tk/lib/tkextlib/tile/tmenubutton.rb b/ext/tk/lib/tkextlib/tile/tmenubutton.rb
index 4b81fa1c81..332db2b74e 100644
--- a/ext/tk/lib/tkextlib/tile/tmenubutton.rb
+++ b/ext/tk/lib/tkextlib/tile/tmenubutton.rb
@@ -9,22 +9,22 @@ module Tk
module Tile
class TMenubutton < TkMenubutton
end
- Menubutton = TMenubutton
end
end
class Tk::Tile::TMenubutton < TkMenubutton
include Tk::Tile::TileWidget
- if Tk::Tile::USE_TTK_NAMESPACE
- TkCommandNames = ['::ttk::menubutton'.freeze].freeze
- else
- TkCommandNames = ['::tmenubutton'.freeze].freeze
- end
+ TkCommandNames = ['tmenubutton'.freeze].freeze
WidgetClassName = 'TMenubutton'.freeze
WidgetClassNames[WidgetClassName] = self
- def self.style(*args)
- [self::WidgetClassName, *(args.map!{|a| _get_eval_string(a)})].join('.')
+ def create_self(keys)
+ if keys and keys != None
+ tk_call_without_enc('tmenubutton', @path, *hash_kv(keys, true))
+ else
+ tk_call_without_enc('tmenubutton', @path)
+ end
end
+ private :create_self
end
diff --git a/ext/tk/lib/tkextlib/tile/tnotebook.rb b/ext/tk/lib/tkextlib/tile/tnotebook.rb
index da4fa203c7..c693d5ce2b 100644
--- a/ext/tk/lib/tkextlib/tile/tnotebook.rb
+++ b/ext/tk/lib/tkextlib/tile/tnotebook.rb
@@ -9,7 +9,6 @@ module Tk
module Tile
class TNotebook < TkWindow
end
- Notebook = TNotebook
end
end
@@ -18,15 +17,16 @@ class Tk::Tile::TNotebook < TkWindow
include TkItemConfigMethod
def __item_cget_cmd(id)
- [self.path, 'tab', id]
+ [self.path, 'tabcget', id]
end
private :__item_cget_cmd
def __item_config_cmd(id)
- [self.path, 'tab', id]
+ [self.path, 'tabconfigure', id]
end
private :__item_config_cmd
+
def __item_listval_optkeys
[]
end
@@ -37,38 +37,29 @@ class Tk::Tile::TNotebook < TkWindow
end
private :__item_listval_optkeys
- #alias tabcget itemcget
+ alias tabcget itemcget
alias tabconfigure itemconfigure
alias tabconfiginfo itemconfiginfo
alias current_tabconfiginfo current_itemconfiginfo
-
- def tabcget(tagOrId, option)
- tabconfigure(tagOrId, option)[-1]
- end
################################
include Tk::Tile::TileWidget
- if Tk::Tile::USE_TTK_NAMESPACE
- TkCommandNames = ['::ttk::notebook'.freeze].freeze
- else
- TkCommandNames = ['::tnotebook'.freeze].freeze
- end
+ TkCommandNames = ['tnotebook'.freeze].freeze
WidgetClassName = 'TNotebook'.freeze
WidgetClassNames[WidgetClassName] = self
- def self.style(*args)
- [self::WidgetClassName, *(args.map!{|a| _get_eval_string(a)})].join('.')
+ def create_self(keys)
+ if keys and keys != None
+ tk_call_without_enc('tnotebook', @path, *hash_kv(keys, true))
+ else
+ tk_call_without_enc('tnotebook', @path)
+ end
end
+ private :create_self
def enable_traversal()
- if Tk::Tile::TILE_SPEC_VERSION_ID < 5
- tk_call_without_enc('::tile::enableNotebookTraversal', @path)
- elsif Tk::Tile::TILE_SPEC_VERSION_ID < 7
- tk_call_without_enc('::tile::notebook::enableTraversal', @path)
- else
- tk_call_without_enc('::ttk::notebook::enableTraversal', @path)
- end
+ tk_call_without_end('tile::enableNotebookTraversal', @path)
self
end
diff --git a/ext/tk/lib/tkextlib/tile/tpaned.rb b/ext/tk/lib/tkextlib/tile/tpaned.rb
deleted file mode 100644
index 11178b19d3..0000000000
--- a/ext/tk/lib/tkextlib/tile/tpaned.rb
+++ /dev/null
@@ -1,188 +0,0 @@
-#
-# tpaned widget
-# by Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)
-#
-require 'tk'
-require 'tkextlib/tile.rb'
-
-module Tk
- module Tile
- class TPaned < TkWindow
- end
- Paned = TPaned
- end
-end
-
-class Tk::Tile::TPaned < TkWindow
- include Tk::Tile::TileWidget
-
- if Tk::Tile::USE_TTK_NAMESPACE
- TkCommandNames = ['::ttk::paned'.freeze].freeze
- else
- TkCommandNames = ['::tpaned'.freeze].freeze
- end
- WidgetClassName = 'TPaned'.freeze
- WidgetClassNames[WidgetClassName] = self
-
- def self.style(*args)
- [self::WidgetClassName, *(args.map!{|a| _get_eval_string(a)})].join('.')
- end
-
- def add(win, keys)
- win = _epath(win)
- tk_send_without_enc('add', win, *hash_kv(keys))
- self
- end
-
- def forget(pane)
- pane = _epath(pane)
- tk_send_without_enc('forget', pane)
- self
- end
-
- def insert(pos, win, keys)
- win = _epath(win)
- tk_send_without_enc('insert', pos, win, *hash_kv(keys))
- self
- end
-
- def panecget(pane, slot)
- pane = _epath(pane)
- tk_tcl2ruby(tk_send_without_enc('pane', pane, "-#{slot}"))
- end
- alias pane_cget panecget
-
- def paneconfigure(pane, key, value=nil)
- pane = _epath(pane)
- if key.kind_of? Hash
- params = []
- key.each{|k, v|
- params.push("-#{k}")
- # params.push((v.kind_of?(TkObject))? v.epath: v)
- params.push(_epath(v))
- }
- tk_send_without_enc('pane', pane, *params)
- else
- # value = value.epath if value.kind_of?(TkObject)
- value = _epath(value)
- tk_send_without_enc('pane', pane, "-#{key}", value)
- end
- self
- end
- alias pane_config paneconfigure
- alias pane_configure paneconfigure
-
- def paneconfiginfo(win)
- if TkComm::GET_CONFIGINFO_AS_ARRAY
- win = _epath(win)
- if key
- conf = tk_split_list(tk_send_without_enc('pane', win, "-#{key}"))
- conf[0] = conf[0][1..-1]
- if conf[0] == 'hide'
- conf[3] = bool(conf[3]) unless conf[3].empty?
- conf[4] = bool(conf[4]) unless conf[4].empty?
- end
- conf
- else
- tk_split_simplelist(tk_send_without_enc('pane',
- win)).collect{|conflist|
- conf = tk_split_simplelist(conflist)
- conf[0] = conf[0][1..-1]
- if conf[3]
- if conf[0] == 'hide'
- conf[3] = bool(conf[3]) unless conf[3].empty?
- elsif conf[3].index('{')
- conf[3] = tk_split_list(conf[3])
- else
- conf[3] = tk_tcl2ruby(conf[3])
- end
- end
- if conf[4]
- if conf[0] == 'hide'
- conf[4] = bool(conf[4]) unless conf[4].empty?
- elsif conf[4].index('{')
- conf[4] = tk_split_list(conf[4])
- else
- conf[4] = tk_tcl2ruby(conf[4])
- end
- end
- conf[1] = conf[1][1..-1] if conf.size == 2 # alias info
- conf
- }
- end
- else # ! TkComm::GET_CONFIGINFO_AS_ARRAY
- win = _epath(win)
- if key
- conf = tk_split_list(tk_send_without_enc('pane', win, "-#{key}"))
- key = conf.shift[1..-1]
- if key == 'hide'
- conf[2] = bool(conf[2]) unless conf[2].empty?
- conf[3] = bool(conf[3]) unless conf[3].empty?
- end
- { key => conf }
- else
- ret = {}
- tk_split_simplelist(tk_send_without_enc('pane',
- win)).each{|conflist|
- conf = tk_split_simplelist(conflist)
- key = conf.shift[1..-1]
- if key
- if key == 'hide'
- conf[2] = bool(conf[2]) unless conf[2].empty?
- elsif conf[2].index('{')
- conf[2] = tk_split_list(conf[2])
- else
- conf[2] = tk_tcl2ruby(conf[2])
- end
- end
- if conf[3]
- if key == 'hide'
- conf[3] = bool(conf[3]) unless conf[3].empty?
- elsif conf[3].index('{')
- conf[3] = tk_split_list(conf[3])
- else
- conf[3] = tk_tcl2ruby(conf[3])
- end
- end
- if conf.size == 1
- ret[key] = conf[0][1..-1] # alias info
- else
- ret[key] = conf
- end
- }
- ret
- end
- end
- end
- alias pane_configinfo paneconfiginfo
-
- def current_paneconfiginfo(win, key=nil)
- if TkComm::GET_CONFIGINFO_AS_ARRAY
- if key
- conf = paneconfiginfo(win, key)
- {conf[0] => conf[4]}
- else
- ret = {}
- paneconfiginfo(win).each{|conf|
- ret[conf[0]] = conf[4] if conf.size > 2
- }
- ret
- end
- else # ! TkComm::GET_CONFIGINFO_AS_ARRAY
- ret = {}
- paneconfiginfo(win, key).each{|k, conf|
- ret[k] = conf[-1] if conf.kind_of?(Array)
- }
- ret
- end
- end
- alias current_pane_configinfo current_paneconfiginfo
-
- def identify(x, y)
- list(tk_send_without_enc('identify', x, y))
- end
-
- def sashpos(idx, newpos=None)
- num_or_str(tk_send_without_enc('sashpos', idx, newpos))
- end
-end
diff --git a/ext/tk/lib/tkextlib/tile/tprogressbar.rb b/ext/tk/lib/tkextlib/tile/tprogressbar.rb
deleted file mode 100644
index 36c1c75c23..0000000000
--- a/ext/tk/lib/tkextlib/tile/tprogressbar.rb
+++ /dev/null
@@ -1,53 +0,0 @@
-#
-# tprogressbar widget
-# by Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)
-#
-require 'tk'
-require 'tkextlib/tile.rb'
-
-module Tk
- module Tile
- class TProgressbar < TkWindow
- end
- Progressbar = TProgressbar
- end
-end
-
-class Tk::Tile::TProgressbar
- include Tk::Tile::TileWidget
-
- if Tk::Tile::USE_TTK_NAMESPACE
- TkCommandNames = ['::ttk::progressbar'.freeze].freeze
- else
- TkCommandNames = ['::tprogressbar'.freeze].freeze
- end
- WidgetClassName = 'TProgressbar'.freeze
- WidgetClassNames[WidgetClassName] = self
-
- def self.style(*args)
- [self::WidgetClassName, *(args.map!{|a| _get_eval_string(a)})].join('.')
- end
-
- def step(amount=None)
- tk_send_without_enc('step', amount).to_f
- end
- #def step=(amount)
- # tk_send_without_enc('step', amount)
- #end
-
- def start(interval=None)
- if Tk::Tile::TILE_SPEC_VERSION_ID < 5
- tk_call_without_enc('::tile::progressbar::start', @path, interval)
- else
- tk_send_without_enc('start', interval)
- end
- end
-
- def stop(amount=None)
- if Tk::Tile::TILE_SPEC_VERSION_ID < 5
- tk_call_without_enc('::tile::progressbar::stop', @path)
- else
- tk_send_without_enc('stop', amount)
- end
- end
-end
diff --git a/ext/tk/lib/tkextlib/tile/tradiobutton.rb b/ext/tk/lib/tkextlib/tile/tradiobutton.rb
index e2f614cb97..66cba62960 100644
--- a/ext/tk/lib/tkextlib/tile/tradiobutton.rb
+++ b/ext/tk/lib/tkextlib/tile/tradiobutton.rb
@@ -10,23 +10,22 @@ module Tk
class TRadioButton < TkRadioButton
end
TRadiobutton = TRadioButton
- RadioButton = TRadioButton
- Radiobutton = TRadioButton
end
end
class Tk::Tile::TRadioButton < TkRadioButton
include Tk::Tile::TileWidget
- if Tk::Tile::USE_TTK_NAMESPACE
- TkCommandNames = ['::ttk::radiobutton'.freeze].freeze
- else
- TkCommandNames = ['::tradiobutton'.freeze].freeze
- end
+ TkCommandNames = ['tradiobutton'.freeze].freeze
WidgetClassName = 'TRadiobutton'.freeze
WidgetClassNames[WidgetClassName] = self
- def self.style(*args)
- [self::WidgetClassName, *(args.map!{|a| _get_eval_string(a)})].join('.')
+ def create_self(keys)
+ if keys and keys != None
+ tk_call_without_enc('tradiobutton', @path, *hash_kv(keys, true))
+ else
+ tk_call_without_enc('tradiobutton', @path)
+ end
end
+ private :create_self
end
diff --git a/ext/tk/lib/tkextlib/tile/treeview.rb b/ext/tk/lib/tkextlib/tile/treeview.rb
deleted file mode 100644
index d3ffbbfa6b..0000000000
--- a/ext/tk/lib/tkextlib/tile/treeview.rb
+++ /dev/null
@@ -1,280 +0,0 @@
-#
-# treeview widget
-# by Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)
-#
-require 'tk'
-require 'tkextlib/tile.rb'
-
-module Tk
- module Tile
- class Treeview < TkWindow
- end
-
- module TreeviewConfig
- include TkItemConfigMethod
-
- def __item_cget_cmd(id)
- [self.path, id[0], id[1]]
- end
- private :__item_cget_cmd
-
- def __item_config_cmd(id)
- [self.path, id[0], id[1]]
- end
- private :__item_config_cmd
-
- def __item_numstrval_optkeys(id)
- case id[0]
- when :item, 'item'
- ['width']
- when :column, 'column'
- super(id[1])
- when :heading, 'heading'
- super(id[1])
- end
- end
- private :__item_numstrval_optkeys
-
- def __item_strval_optkeys(id)
- case id[0]
- when :item, 'item'
- super(id) + ['id']
- when :column, 'column'
- super(id[1])
- when :heading, 'heading'
- super(id[1])
- end
- end
- private :__item_strval_optkeys
-
- def __item_boolval_optkeys(id)
- case id[0]
- when :item, 'item'
- ['open']
- when :column, 'column'
- super(id[1])
- when :heading, 'heading'
- super(id[1])
- end
- end
- private :__item_boolval_optkeys
-
- def __item_listval_optkeys(id)
- case id[0]
- when :item, 'item'
- ['values']
- when :column, 'column'
- []
- when :heading, 'heading'
- []
- end
- end
- private :__item_listval_optkeys
-
- alias __itemcget itemcget
- alias __itemconfigure itemconfigure
- alias __itemconfiginfo itemconfiginfo
- alias __current_itemconfiginfo current_itemconfiginfo
-
- private :__itemcget, :__itemconfigure
- private :__itemconfiginfo, :__current_itemconfiginfo
-
- # Treeview Item
- def itemcget(tagOrId, option)
- __itemcget([:item, tagOrId], option)
- end
- def itemconfigure(tagOrId, slot, value=None)
- __itemconfigure([:item, tagOrId], slot, value)
- end
- def itemconfiginfo(tagOrId, slot=nil)
- __itemconfiginfo([:item, tagOrId], slot)
- end
- def current_itemconfiginfo(tagOrId, slot=nil)
- __current_itemconfiginfo([:item, tagOrId], slot)
- end
-
- # Treeview Column
- def columncget(tagOrId, option)
- __itemcget([:column, tagOrId], option)
- end
- def columnconfigure(tagOrId, slot, value=None)
- __itemconfigure([:column, tagOrId], slot, value)
- end
- def columnconfiginfo(tagOrId, slot=nil)
- __itemconfiginfo([:column, tagOrId], slot)
- end
- def current_columnconfiginfo(tagOrId, slot=nil)
- __current_itemconfiginfo([:column, tagOrId], slot)
- end
- alias column_cget columncget
- alias column_configure columnconfigure
- alias column_configinfo columnconfiginfo
- alias current_column_configinfo current_columnconfiginfo
-
- # Treeview Heading
- def headingcget(tagOrId, option)
- __itemcget([:heading, tagOrId], option)
- end
- def headingconfigure(tagOrId, slot, value=None)
- __itemconfigure([:heading, tagOrId], slot, value)
- end
- def headingconfiginfo(tagOrId, slot=nil)
- __itemconfiginfo([:heading, tagOrId], slot)
- end
- def current_headingconfiginfo(tagOrId, slot=nil)
- __current_itemconfiginfo([:heading, tagOrId], slot)
- end
- alias heading_cget headingcget
- alias heading_configure headingconfigure
- alias heading_configinfo headingconfiginfo
- alias current_heading_configinfo current_headingconfiginfo
- end
- end
-end
-
-class Tk::Tile::Treeview < TkWindow
- include Tk::Tile::TileWidget
- include Scrollable
-
- include Tk::Tile::TreeviewConfig
-
- if Tk::Tile::USE_TTK_NAMESPACE
- TkCommandNames = ['::ttk::treeview'.freeze].freeze
- else
- TkCommandNames = ['::treeview'.freeze].freeze
- end
- WidgetClassName = 'Treeview'.freeze
- WidgetClassNames[WidgetClassName] = self
-
- def self.style(*args)
- [self::WidgetClassName, *(args.map!{|a| _get_eval_string(a)})].join('.')
- end
-
- def tagid(id)
- if id.kind_of?(Array)
- [id[0], _get_eval_string(id[1])]
- else
- _get_eval_string(id)
- end
- end
-
- def children(item)
- simplelist(tk_send_without_enc('children', item))
- end
- def set_children(item, *items)
- tk_send_without_enc('children', item,
- array2tk_list(items.flatten, true))
- self
- end
-
- def delete(*items)
- tk_send_without_enc('delete', array2tk_list(items.flatten, true))
- self
- end
-
- def detach(*items)
- tk_send_without_enc('detach', array2tk_list(items.flatten, true))
- self
- end
-
- def exist?(item)
- bool(tk_send_without_enc('exists', _get_eval_enc_str(item)))
- end
-
- def focus_item(item = None)
- tk_send('focus', item)
- end
-
- def identify(x, y)
- ret = simplelist(tk_send('identify', x, y))
- case ret[0]
- when 'heading', 'separator', 'cell'
- ret[-1] = num_or_str(ret[-1])
- end
- end
-
- def index(item)
- number(tk_send('index', item))
- end
-
- def insert(parent, idx, keys={})
- keys = _symbolkey2str(keys)
- id = keys.delete('id')
- if id
- tk_send('insert', parent, idx, '-id', id, *hash_kv(keys))
- else
- tk_send('insert', parent, idx, *hash_kv(keys))
- end
- self
- end
-
- def instate(spec, cmd=Proc.new)
- tk_send('instate', spec, cmd)
- end
- def state(spec=None)
- tk_send('state', spec)
- end
-
- def move(item, parent, idx)
- tk_send('move', item, parent, idx)
- self
- end
-
- def next(item)
- tk_send('next', item)
- end
-
- def parent(item)
- tk_send('parent', item)
- end
-
- def prev(item)
- tk_send('prev', item)
- end
-
- def see(item)
- tk_send('see', item)
- self
- end
-
- def selection
- simplelist(tk_send('selection'))
- end
- alias selection_get selection
-
- def selection_add(*items)
- tk_send('selection', 'add', array2tk_list(items.flatten, true))
- self
- end
- def selection_remove(*items)
- tk_send('selection', 'remove', array2tk_list(items.flatten, true))
- self
- end
- def selection_set(*items)
- tk_send('selection', 'set', array2tk_list(items.flatten, true))
- self
- end
- def selection_toggle(*items)
- tk_send('selection', 'toggle', array2tk_list(items.flatten, true))
- self
- end
-
- def get_directory(item)
- # tile-0.7+
- ret = []
- lst = simplelist(tk_send('set', item))
- until lst.empty?
- col = lst.shift
- val = lst.shift
- ret << [col, val]
- end
- ret
- end
- def get(item, col)
- tk_send('set', item, col)
- end
- def set(item, col, value)
- tk_send('set', item, col, value)
- self
- end
-end
diff --git a/ext/tk/lib/tkextlib/tile/tscale.rb b/ext/tk/lib/tkextlib/tile/tscale.rb
deleted file mode 100644
index 7ec72e3515..0000000000
--- a/ext/tk/lib/tkextlib/tile/tscale.rb
+++ /dev/null
@@ -1,50 +0,0 @@
-#
-# tscale & tprogress widget
-# by Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)
-#
-require 'tk'
-require 'tkextlib/tile.rb'
-
-module Tk
- module Tile
- class TScale < TkScale
- end
- Scale = TScale
-
- class TProgress < TScale
- end
- Progress = TProgress
- end
-end
-
-class Tk::Tile::TScale < TkScale
- include Tk::Tile::TileWidget
-
- if Tk::Tile::USE_TTK_NAMESPACE
- TkCommandNames = ['::ttk::scale'.freeze].freeze
- else
- TkCommandNames = ['::tscale'.freeze].freeze
- end
- WidgetClassName = 'TScale'.freeze
- WidgetClassNames[WidgetClassName] = self
-
- def self.style(*args)
- [self::WidgetClassName, *(args.map!{|a| _get_eval_string(a)})].join('.')
- end
-end
-
-class Tk::Tile::TProgress < Tk::Tile::TScale
- include Tk::Tile::TileWidget
-
- if Tk::Tile::USE_TTK_NAMESPACE
- TkCommandNames = ['::ttk::progress'.freeze].freeze
- else
- TkCommandNames = ['::tprogress'.freeze].freeze
- end
- WidgetClassName = 'TProgress'.freeze
- WidgetClassNames[WidgetClassName] = self
-
- def self.style(*args)
- [self::WidgetClassName, *(args.map!{|a| _get_eval_string(a)})].join('.')
- end
-end
diff --git a/ext/tk/lib/tkextlib/tile/tscrollbar.rb b/ext/tk/lib/tkextlib/tile/tscrollbar.rb
deleted file mode 100644
index bd49ae18e3..0000000000
--- a/ext/tk/lib/tkextlib/tile/tscrollbar.rb
+++ /dev/null
@@ -1,30 +0,0 @@
-#
-# tscrollbar widget
-# by Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)
-#
-require 'tk'
-require 'tkextlib/tile.rb'
-
-module Tk
- module Tile
- class TScrollbar < TkScrollbar
- end
- Scrollbar = TScrollbar
- end
-end
-
-class Tk::Tile::TScrollbar < TkScrollbar
- include Tk::Tile::TileWidget
-
- if Tk::Tile::USE_TTK_NAMESPACE
- TkCommandNames = ['::ttk::scrollbar'.freeze].freeze
- else
- TkCommandNames = ['::tscrollbar'.freeze].freeze
- end
- WidgetClassName = 'TScrollbar'.freeze
- WidgetClassNames[WidgetClassName] = self
-
- def self.style(*args)
- [self::WidgetClassName, *(args.map!{|a| _get_eval_string(a)})].join('.')
- end
-end
diff --git a/ext/tk/lib/tkextlib/tile/tseparator.rb b/ext/tk/lib/tkextlib/tile/tseparator.rb
deleted file mode 100644
index ca731d4e5b..0000000000
--- a/ext/tk/lib/tkextlib/tile/tseparator.rb
+++ /dev/null
@@ -1,30 +0,0 @@
-#
-# tseparator widget
-# by Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)
-#
-require 'tk'
-require 'tkextlib/tile.rb'
-
-module Tk
- module Tile
- class TSeparator < TkWindow
- end
- Separator = TSeparator
- end
-end
-
-class Tk::Tile::TSeparator < TkWindow
- include Tk::Tile::TileWidget
-
- if Tk::Tile::USE_TTK_NAMESPACE
- TkCommandNames = ['::ttk::separator'.freeze].freeze
- else
- TkCommandNames = ['::tseparator'.freeze].freeze
- end
- WidgetClassName = 'TSeparator'.freeze
- WidgetClassNames[WidgetClassName] = self
-
- def self.style(*args)
- [self::WidgetClassName, *(args.map!{|a| _get_eval_string(a)})].join('.')
- end
-end
diff --git a/ext/tk/lib/tkextlib/tile/tsquare.rb b/ext/tk/lib/tkextlib/tile/tsquare.rb
deleted file mode 100644
index 600b55e4e7..0000000000
--- a/ext/tk/lib/tkextlib/tile/tsquare.rb
+++ /dev/null
@@ -1,30 +0,0 @@
-#
-# tsquare widget
-# by Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)
-#
-require 'tk'
-require 'tkextlib/tile.rb'
-
-module Tk
- module Tile
- class TSquare < TkWindow
- end
- Square = TSquare
- end
-end
-
-class Tk::Tile::TSquare < TkWindow
- include Tk::Tile::TileWidget
-
- if Tk::Tile::USE_TTK_NAMESPACE
- TkCommandNames = ['::ttk::square'.freeze].freeze
- else
- TkCommandNames = ['::tsquare'.freeze].freeze
- end
- WidgetClassName = 'TSquare'.freeze
- WidgetClassNames[WidgetClassName] = self
-
- def self.style(*args)
- [self::WidgetClassName, *(args.map!{|a| _get_eval_string(a)})].join('.')
- end
-end
diff --git a/ext/tk/lib/tkextlib/tkDND/shape.rb b/ext/tk/lib/tkextlib/tkDND/shape.rb
index 570c93b0d9..0f6a5f0a30 100644
--- a/ext/tk/lib/tkextlib/tkDND/shape.rb
+++ b/ext/tk/lib/tkextlib/tkDND/shape.rb
@@ -18,12 +18,6 @@ module Tk
module TkDND
module Shape
extend TkCore
-
- PACKAGE_NAME = 'shape'.freeze
- def self.package_name
- PACKAGE_NAME
- end
-
=begin
def self.package_version
begin
diff --git a/ext/tk/lib/tkextlib/tkDND/tkdnd.rb b/ext/tk/lib/tkextlib/tkDND/tkdnd.rb
index a040532eb6..78381f8df0 100644
--- a/ext/tk/lib/tkextlib/tkDND/tkdnd.rb
+++ b/ext/tk/lib/tkextlib/tkDND/tkdnd.rb
@@ -15,11 +15,6 @@ TkPackage.require('tkdnd')
module Tk
module TkDND
- PACKAGE_NAME = 'tkdnd'.freeze
- def self.package_name
- PACKAGE_NAME
- end
-
def self.package_version
begin
TkPackage.require('tkdnd')
@@ -80,29 +75,7 @@ module Tk
end
end
- #def dnd_bindtarget(type, event, cmd=Proc.new, prior=50, *args)
- # event = tk_event_sequence(event)
- # if prior.kind_of?(Numeric)
- # tk_call('dnd', 'bindtarget', @path, type, event,
- # install_bind_for_event_class(DND_Subst, cmd, *args),
- # prior)
- # else
- # tk_call('dnd', 'bindtarget', @path, type, event,
- # install_bind_for_event_class(DND_Subst, cmd, prior, *args))
- # end
- # self
- #end
- def dnd_bindtarget(type, event, *args)
- # if args[0].kind_of?(Proc) || args[0].kind_of?(Method)
- if TkComm._callback_entry?(args[0]) || !block_given?
- cmd = args.shift
- else
- cmd = Proc.new
- end
-
- prior = 50
- prior = args.shift unless args.empty?
-
+ def dnd_bindtarget(type, event, cmd=Proc.new, prior=50, *args)
event = tk_event_sequence(event)
if prior.kind_of?(Numeric)
tk_call('dnd', 'bindtarget', @path, type, event,
@@ -128,21 +101,8 @@ module Tk
end
end
- #def dnd_bindsource(type, cmd=Proc.new, prior=None)
- # tk_call('dnd', 'bindsource', @path, type, cmd, prior)
- # self
- #end
- def dnd_bindsource(type, *args)
- # if args[0].kind_of?(Proc) || args[0].kind_of?(Method)
- if TkComm._callback_entry?(args[0]) || !block_given?
- cmd = args.shift
- else
- cmd = Proc.new
- end
-
- args = [None] if args.empty
-
- tk_call('dnd', 'bindsource', @path, type, cmd, *args)
+ def dnd_bindsource(type, cmd=Proc.new, prior=None)
+ tk_call('dnd', 'bindsource', @path, type, cmd, prior)
self
end
diff --git a/ext/tk/lib/tkextlib/tkHTML/htmlwidget.rb b/ext/tk/lib/tkextlib/tkHTML/htmlwidget.rb
index 8527f61df1..b9a203575a 100644
--- a/ext/tk/lib/tkextlib/tkHTML/htmlwidget.rb
+++ b/ext/tk/lib/tkextlib/tkHTML/htmlwidget.rb
@@ -16,11 +16,6 @@ TkPackage.require('Tkhtml')
module Tk
class HTML_Widget < TkWindow
- PACKAGE_NAME = 'Tkhtml'.freeze
- def self.package_name
- PACKAGE_NAME
- end
-
def self.package_version
begin
TkPackage.require('Tkhtml')
@@ -96,19 +91,13 @@ class Tk::HTML_Widget
def create_self(keys)
if keys and keys != None
- tk_call_without_enc(self.class::TkCommandNames[0], @path,
- *hash_kv(keys, true))
+ tk_call_without_enc('html', @path, *hash_kv(keys, true))
else
- tk_call_without_enc(self.class::TkCommandNames[0], @path)
+ tk_call_without_enc('html', @path)
end
end
private :create_self
- def __strval_optkeys
- super() << 'base' << 'selectioncolor' << 'unvisitedcolor' << 'visitedcolor'
- end
- private :__strval_optkeys
-
###################################
# class methods
###################################
diff --git a/ext/tk/lib/tkextlib/tkimg.rb b/ext/tk/lib/tkextlib/tkimg.rb
index c01359d3ef..ffeafbb58e 100644
--- a/ext/tk/lib/tkextlib/tkimg.rb
+++ b/ext/tk/lib/tkextlib/tkimg.rb
@@ -17,11 +17,6 @@ TkPackage.require('Img')
module Tk
module Img
- PACKAGE_NAME = 'Img'.freeze
- def self.package_name
- PACKAGE_NAME
- end
-
def self.package_version
begin
TkPackage.require('Img')
diff --git a/ext/tk/lib/tkextlib/tkimg/bmp.rb b/ext/tk/lib/tkextlib/tkimg/bmp.rb
index ea90181aa3..581483f8f4 100644
--- a/ext/tk/lib/tkextlib/tkimg/bmp.rb
+++ b/ext/tk/lib/tkextlib/tkimg/bmp.rb
@@ -16,11 +16,6 @@ TkPackage.require('img::bmp')
module Tk
module Img
module BMP
- PACKAGE_NAME = 'img::bmp'.freeze
- def self.package_name
- PACKAGE_NAME
- end
-
def self.package_version
begin
TkPackage.require('img::bmp')
diff --git a/ext/tk/lib/tkextlib/tkimg/gif.rb b/ext/tk/lib/tkextlib/tkimg/gif.rb
index d542d47561..6ef18f8e90 100644
--- a/ext/tk/lib/tkextlib/tkimg/gif.rb
+++ b/ext/tk/lib/tkextlib/tkimg/gif.rb
@@ -16,11 +16,6 @@ TkPackage.require('img::gif')
module Tk
module Img
module GIF
- PACKAGE_NAME = 'img::gif'.freeze
- def self.package_name
- PACKAGE_NAME
- end
-
def self.package_version
begin
TkPackage.require('img::gif')
diff --git a/ext/tk/lib/tkextlib/tkimg/ico.rb b/ext/tk/lib/tkextlib/tkimg/ico.rb
index e79bdf45e9..1e3cb5f497 100644
--- a/ext/tk/lib/tkextlib/tkimg/ico.rb
+++ b/ext/tk/lib/tkextlib/tkimg/ico.rb
@@ -16,11 +16,6 @@ TkPackage.require('img::ico')
module Tk
module Img
module ICO
- PACKAGE_NAME = 'img::ico'.freeze
- def self.package_name
- PACKAGE_NAME
- end
-
def self.package_version
begin
TkPackage.require('img::ico')
diff --git a/ext/tk/lib/tkextlib/tkimg/jpeg.rb b/ext/tk/lib/tkextlib/tkimg/jpeg.rb
index 2126120161..017c93ee0e 100644
--- a/ext/tk/lib/tkextlib/tkimg/jpeg.rb
+++ b/ext/tk/lib/tkextlib/tkimg/jpeg.rb
@@ -16,11 +16,6 @@ TkPackage.require('img::jpeg')
module Tk
module Img
module JPEG
- PACKAGE_NAME = 'img::jpeg'.freeze
- def self.package_name
- PACKAGE_NAME
- end
-
def self.package_version
begin
TkPackage.require('img::jpeg')
diff --git a/ext/tk/lib/tkextlib/tkimg/pcx.rb b/ext/tk/lib/tkextlib/tkimg/pcx.rb
index 6831f4d35b..e924d48869 100644
--- a/ext/tk/lib/tkextlib/tkimg/pcx.rb
+++ b/ext/tk/lib/tkextlib/tkimg/pcx.rb
@@ -16,11 +16,6 @@ TkPackage.require('img::pcx')
module Tk
module Img
module PCX
- PACKAGE_NAME = 'img::pcx'.freeze
- def self.package_name
- PACKAGE_NAME
- end
-
def self.package_version
begin
TkPackage.require('img::pcx')
diff --git a/ext/tk/lib/tkextlib/tkimg/pixmap.rb b/ext/tk/lib/tkextlib/tkimg/pixmap.rb
index bd1b870af7..f9aaa65a9b 100644
--- a/ext/tk/lib/tkextlib/tkimg/pixmap.rb
+++ b/ext/tk/lib/tkextlib/tkimg/pixmap.rb
@@ -16,11 +16,6 @@ TkPackage.require('img::pixmap')
module Tk
module Img
module PIXMAP
- PACKAGE_NAME = 'img::pixmap'.freeze
- def self.package_name
- PACKAGE_NAME
- end
-
def self.package_version
begin
TkPackage.require('img::pixmap')
@@ -39,6 +34,6 @@ class TkPixmapImage<TkImage
def initialize(*args)
@type = 'pixmap'
- super(*args)
+ super
end
end
diff --git a/ext/tk/lib/tkextlib/tkimg/png.rb b/ext/tk/lib/tkextlib/tkimg/png.rb
index 5c829f48d2..b155836395 100644
--- a/ext/tk/lib/tkextlib/tkimg/png.rb
+++ b/ext/tk/lib/tkextlib/tkimg/png.rb
@@ -16,11 +16,6 @@ TkPackage.require('img::png')
module Tk
module Img
module PNG
- PACKAGE_NAME = 'img::png'.freeze
- def self.package_name
- PACKAGE_NAME
- end
-
def self.package_version
begin
TkPackage.require('img::png')
diff --git a/ext/tk/lib/tkextlib/tkimg/ppm.rb b/ext/tk/lib/tkextlib/tkimg/ppm.rb
index eacfae467d..df56baee4a 100644
--- a/ext/tk/lib/tkextlib/tkimg/ppm.rb
+++ b/ext/tk/lib/tkextlib/tkimg/ppm.rb
@@ -16,11 +16,6 @@ TkPackage.require('img::ppm')
module Tk
module Img
module PPM
- PACKAGE_NAME = 'img::ppm'.freeze
- def self.package_name
- PACKAGE_NAME
- end
-
def self.package_version
begin
TkPackage.require('img::ppm')
diff --git a/ext/tk/lib/tkextlib/tkimg/ps.rb b/ext/tk/lib/tkextlib/tkimg/ps.rb
index 68e9178ac0..3025066eb4 100644
--- a/ext/tk/lib/tkextlib/tkimg/ps.rb
+++ b/ext/tk/lib/tkextlib/tkimg/ps.rb
@@ -16,11 +16,6 @@ TkPackage.require('img::ps')
module Tk
module Img
module PS
- PACKAGE_NAME = 'img::ps'.freeze
- def self.package_name
- PACKAGE_NAME
- end
-
def self.package_version
begin
TkPackage.require('img::ps')
diff --git a/ext/tk/lib/tkextlib/tkimg/sgi.rb b/ext/tk/lib/tkextlib/tkimg/sgi.rb
index ec7038bf0e..e505c87e8b 100644
--- a/ext/tk/lib/tkextlib/tkimg/sgi.rb
+++ b/ext/tk/lib/tkextlib/tkimg/sgi.rb
@@ -16,11 +16,6 @@ TkPackage.require('img::sgi')
module Tk
module Img
module SGI
- PACKAGE_NAME = 'img::sgi'.freeze
- def self.package_name
- PACKAGE_NAME
- end
-
def self.package_version
begin
TkPackage.require('img::sgi')
diff --git a/ext/tk/lib/tkextlib/tkimg/sun.rb b/ext/tk/lib/tkextlib/tkimg/sun.rb
index 651f946497..25bfea8fb7 100644
--- a/ext/tk/lib/tkextlib/tkimg/sun.rb
+++ b/ext/tk/lib/tkextlib/tkimg/sun.rb
@@ -16,11 +16,6 @@ TkPackage.require('img::sun')
module Tk
module Img
module SUN
- PACKAGE_NAME = 'img::sun'.freeze
- def self.package_name
- PACKAGE_NAME
- end
-
def self.package_version
begin
TkPackage.require('img::sun')
diff --git a/ext/tk/lib/tkextlib/tkimg/tga.rb b/ext/tk/lib/tkextlib/tkimg/tga.rb
index 1eae407c0a..e3f84c3714 100644
--- a/ext/tk/lib/tkextlib/tkimg/tga.rb
+++ b/ext/tk/lib/tkextlib/tkimg/tga.rb
@@ -16,11 +16,6 @@ TkPackage.require('img::tga')
module Tk
module Img
module TGA
- PACKAGE_NAME = 'img::tga'.freeze
- def self.package_name
- PACKAGE_NAME
- end
-
def self.package_version
begin
TkPackage.require('img::tga')
diff --git a/ext/tk/lib/tkextlib/tkimg/tiff.rb b/ext/tk/lib/tkextlib/tkimg/tiff.rb
index ed271c2600..e7e12406ac 100644
--- a/ext/tk/lib/tkextlib/tkimg/tiff.rb
+++ b/ext/tk/lib/tkextlib/tkimg/tiff.rb
@@ -16,11 +16,6 @@ TkPackage.require('img::tiff')
module Tk
module Img
module TIFF
- PACKAGE_NAME = 'img::tiff'.freeze
- def self.package_name
- PACKAGE_NAME
- end
-
def self.package_version
begin
TkPackage.require('img::tiff')
diff --git a/ext/tk/lib/tkextlib/tkimg/window.rb b/ext/tk/lib/tkextlib/tkimg/window.rb
index 3b5906fab6..00ed7d1b86 100644
--- a/ext/tk/lib/tkextlib/tkimg/window.rb
+++ b/ext/tk/lib/tkextlib/tkimg/window.rb
@@ -16,11 +16,6 @@ TkPackage.require('img::window')
module Tk
module Img
module WINDOW
- PACKAGE_NAME = 'img::window'.freeze
- def self.package_name
- PACKAGE_NAME
- end
-
def self.package_version
begin
TkPackage.require('img::window')
diff --git a/ext/tk/lib/tkextlib/tkimg/xbm.rb b/ext/tk/lib/tkextlib/tkimg/xbm.rb
index f4bea030be..08b1b9876b 100644
--- a/ext/tk/lib/tkextlib/tkimg/xbm.rb
+++ b/ext/tk/lib/tkextlib/tkimg/xbm.rb
@@ -16,11 +16,6 @@ TkPackage.require('img::xbm')
module Tk
module Img
module XBM
- PACKAGE_NAME = 'img::xbm'.freeze
- def self.package_name
- PACKAGE_NAME
- end
-
def self.package_version
begin
TkPackage.require('img::xbm')
diff --git a/ext/tk/lib/tkextlib/tkimg/xpm.rb b/ext/tk/lib/tkextlib/tkimg/xpm.rb
index 5119c8710b..e29c1d554f 100644
--- a/ext/tk/lib/tkextlib/tkimg/xpm.rb
+++ b/ext/tk/lib/tkextlib/tkimg/xpm.rb
@@ -16,11 +16,6 @@ TkPackage.require('img::xpm')
module Tk
module Img
module XPM
- PACKAGE_NAME = 'img::xpm'.freeze
- def self.package_name
- PACKAGE_NAME
- end
-
def self.package_version
begin
TkPackage.require('img::xpm')
diff --git a/ext/tk/lib/tkextlib/tktable/tktable.rb b/ext/tk/lib/tkextlib/tktable/tktable.rb
index 4edaabc847..2f2b14a69f 100644
--- a/ext/tk/lib/tkextlib/tktable/tktable.rb
+++ b/ext/tk/lib/tkextlib/tktable/tktable.rb
@@ -17,11 +17,6 @@ TkPackage.require('Tktable')
module Tk
class TkTable < TkWindow
- PACKAGE_NAME = 'Tktable'.freeze
- def self.package_name
- PACKAGE_NAME
- end
-
def self.package_version
begin
TkPackage.require('Tktable')
@@ -59,21 +54,6 @@ module Tk::TkTable::ConfigMethod
end
private :__item_pathname
- def __item_boolval_optkeys(id)
- super(id) << 'multiline' << 'showtext' << 'wrap'
- end
- private :__item_boolval_optkeys
-
- def __item_strval_optkeys(id)
- super(id) << 'ellipsis'
- end
- private :__item_strval_optkeys
-
- def __item_val2ruby_optkeys(id) # { key=>method, ... }
- super(id).update('window'=>proc{|v| window(v)})
- end
- private :__item_val2ruby_optkeys
-
def tag_cget(tagOrId, option)
itemcget(['tag', tagid(tagOrId)], option)
end
@@ -81,31 +61,23 @@ module Tk::TkTable::ConfigMethod
itemconfigure(['tag', tagid(tagOrId)], slot, value)
end
def tag_configinfo(tagOrId, slot=nil)
- itemconfiginfo(['tag', tagid(tagOrId)], slot)
+ itemconfigure(['tag', tagid(tagOrId)], slot)
end
def current_tag_configinfo(tagOrId, slot=nil)
- current_itemconfiginfo(['tag', tagid(tagOrId)], slot)
+ itemconfigure(['tag', tagid(tagOrId)], slot)
end
def window_cget(tagOrId, option)
itemcget(['window', tagid(tagOrId)], option)
end
def window_configure(tagOrId, slot, value=None)
- if slot == :window || slot == 'window'
- value = _epath(value)
- elsif slot.kind_of?(Hash)
- if slot.key?(:window) || slot.key?('window')
- slot = _symbolkey2str(slot)
- slot['window'] = _epath(slot['window'])
- end
- end
itemconfigure(['window', tagid(tagOrId)], slot, value)
end
def window_configinfo(tagOrId, slot=nil)
- itemconfiginfo(['window', tagid(tagOrId)], slot)
+ itemconfigure(['window', tagid(tagOrId)], slot)
end
def current_window_configinfo(tagOrId, slot=nil)
- current_itemconfiginfo(['window', tagid(tagOrId)], slot)
+ itemconfigure(['window', tagid(tagOrId)], slot)
end
private :itemcget, :itemconfigure
@@ -223,18 +195,6 @@ class Tk::TkTable
Tk::TkTable::CelTag::CellTagID_TBL.delete(@path)
end
- def __boolval_optkeys
- super() << 'autoclear' << 'flashmode' << 'invertselected' <<
- 'multiline' << 'selecttitle' << 'wrap'
- end
- private :__boolval_optkeys
-
- def __strval_optkeys
- super() << 'colseparator' << 'ellipsis' << 'rowseparator' << 'sparsearray'
- end
- private :__strval_optkeys
-
-
#################################
class BrowseCommand < TkValidateCommand
@@ -367,7 +327,7 @@ class Tk::TkTable
#################################
def __validation_class_list
- super() <<
+ super <<
BrowseCommand << CellCommand << SelectionCommand << ValidateCommand
end
@@ -387,16 +347,16 @@ class Tk::TkTable
end
def border_mark(x, y)
- simplelist(tk_send('border', 'mark', x, y))
+ simplelist(tk_send('scan', 'mark', x, y))
end
def border_mark_row(x, y)
- tk_send('border', 'mark', x, y, 'row')
+ tk_send('scan', 'mark', x, y, 'row')
end
def border_mark_col(x, y)
- tk_send('border', 'mark', x, y, 'col')
+ tk_send('scan', 'mark', x, y, 'col')
end
def border_dragto(x, y)
- tk_send('border', 'dragto', x, y)
+ tk_send('scan', 'dragto', x, y)
end
def clear_cache(first=None, last=None)
@@ -579,9 +539,6 @@ class Tk::TkTable
def selection_include?(idx)
bool(tk_send('selection', 'includes', tagid(idx)))
end
- def selection_present
- bool(tk_send('selection', 'present'))
- end
def selection_set(first, last=None)
tk_send('selection', 'set', tagid(first), tagid(last))
self
diff --git a/ext/tk/lib/tkextlib/tktrans/tktrans.rb b/ext/tk/lib/tkextlib/tktrans/tktrans.rb
index 665c57af0c..55ac03e563 100644
--- a/ext/tk/lib/tkextlib/tktrans/tktrans.rb
+++ b/ext/tk/lib/tkextlib/tktrans/tktrans.rb
@@ -14,11 +14,6 @@ TkPackage.require('tktrans') rescue Tk.load_tcllibrary('tktrans')
module Tk
module TkTrans
- PACKAGE_NAME = 'tktrans'.freeze
- def self.package_name
- PACKAGE_NAME
- end
-
def self.package_version
begin
TkPackage.require('tktrans')
diff --git a/ext/tk/lib/tkextlib/treectrl/tktreectrl.rb b/ext/tk/lib/tkextlib/treectrl/tktreectrl.rb
index 12f7cffabf..cc23857c5f 100644
--- a/ext/tk/lib/tkextlib/treectrl/tktreectrl.rb
+++ b/ext/tk/lib/tkextlib/treectrl/tktreectrl.rb
@@ -12,18 +12,10 @@ require 'tkextlib/setup.rb'
require 'tkextlib/treectrl/setup.rb'
# TkPackage.require('treectrl', '1.0')
-# TkPackage.require('treectrl', '1.1')
TkPackage.require('treectrl')
module Tk
class TreeCtrl < TkWindow
- BindTag_FileList = TkBindTag.new_by_name('TreeCtrlFileList')
-
- PACKAGE_NAME = 'treectrl'.freeze
- def self.package_name
- PACKAGE_NAME
- end
-
def self.package_version
begin
TkPackage.require('treectrl')
@@ -32,9 +24,6 @@ module Tk
end
end
- HasColumnCreateCommand =
- (TkPackage.vcompare(self.package_version, '1.1') >= 0)
-
# dummy ::
# pkgIndex.tcl of TreeCtrl-1.0 doesn't support auto_load for
# 'loupe' command (probably it is bug, I think).
@@ -54,14 +43,6 @@ module Tk
Tk.tk_call_without_enc('loupe', img, x, y, w, h, zoom)
end
- def self.text_layout(font, text, keys={})
- TkComm.list(Tk.tk_call_without_enc('textlayout', font, text, keys))
- end
-
- def self.image_tint(img, color, alpha)
- Tk.tk_call_without_enc('imagetint', img, color, alpha)
- end
-
class NotifyEvent < TkUtil::CallbackSubst
end
@@ -81,14 +62,12 @@ class Tk::TreeCtrl::NotifyEvent
[ ?D, ?l, :items ],
[ ?e, ?e, :event ],
[ ?I, ?n, :id ],
- [ ?l, ?n, :lower_bound ],
+ [ ?l, ?b, :lower_bound ],
[ ?p, ?n, :active_id ],
- [ ?P, ?e, :pattern ],
[ ?S, ?l, :sel_items ],
[ ?T, ?w, :widget ],
- [ ?u, ?n, :upper_bound ],
+ [ ?U, ?b, :upper_bound ],
[ ?W, ?o, :object ],
- [ ??, ?x, :parm_info ],
nil
]
@@ -99,6 +78,8 @@ class Tk::TreeCtrl::NotifyEvent
[ ?l, TkComm.method(:list) ],
[ ?w, TkComm.method(:window) ],
+ [ ?b, proc{|val| list(val)} ],
+
[ ?e, proc{|val|
case val
when /^<<[^<>]+>>$/
@@ -111,28 +92,7 @@ class Tk::TreeCtrl::NotifyEvent
}
],
- [ ?o, proc{|val| TkComm.tk_tcl2ruby(val)} ],
-
- [ ?x, proc{|val|
- begin
- inf = {}
- Hash[*(TkComm.list(val))].each{|k, v|
- if keyinfo = KEY_TBL.assoc(k[0])
- if cmd = PROC_TBL.assoc(keyinfo[1])
- begin
- new_v = cmd.call(v)
- v = new_v
- rescue
- end
- end
- end
- inf[k] = v
- }
- inf
- rescue
- val
- end
- } ],
+ [ ?o, proc{|val| tk_tcl2ruby(val)} ],
nil
]
@@ -164,22 +124,12 @@ module Tk::TreeCtrl::ConfigMethod
key = key.to_s
end
- if (obj.kind_of?(Tk::TreeCtrl::Column) ||
- obj.kind_of?(Tk::TreeCtrl::Element) ||
- obj.kind_of?(Tk::TreeCtrl::Item) ||
- obj.kind_of?(Tk::TreeCtrl::Style))
- obj = obj.id
- end
-
case key
when 'column'
obj
- when 'debug'
- None
-
when 'dragimage'
- None
+ obj
when 'element'
obj
@@ -188,7 +138,7 @@ module Tk::TreeCtrl::ConfigMethod
obj
when 'marquee'
- None
+ obj
when 'notify'
obj
@@ -202,24 +152,15 @@ module Tk::TreeCtrl::ConfigMethod
end
def tagid(mixed_id)
- if mixed_id == 'debug'
- ['debug', None]
- elsif mixed_id == 'dragimage'
- ['dragimage', None]
- elsif mixed_id == 'marquee'
- ['marquee', None]
- elsif mixed_id.kind_of?(Array)
+ if mixed_id.kind_of?(Array)
[mixed_id[0], treectrl_tagid(*mixed_id)]
else
tagid(mixed_id.split(':'))
end
+ fail ArgumentError, "unknown id format"
end
def __item_cget_cmd(mixed_id)
- if mixed_id[0] == 'column' && mixed_id[1] == 'drag'
- return [self.path, 'column', 'dragcget']
- end
-
if mixed_id[1].kind_of?(Array)
id = mixed_id[1]
else
@@ -235,10 +176,6 @@ module Tk::TreeCtrl::ConfigMethod
private :__item_cget_cmd
def __item_config_cmd(mixed_id)
- if mixed_id[0] == 'column' && mixed_id[1] == 'drag'
- return [self.path, 'column', 'dragconfigure']
- end
-
if mixed_id[1].kind_of?(Array)
id = mixed_id[1]
else
@@ -282,104 +219,8 @@ module Tk::TreeCtrl::ConfigMethod
end
private :__item_configinfo_struct
-
- def __item_font_optkeys(id)
- if id.kind_of?(Array) && (id[0] == 'element' ||
- (id[0].kind_of?(Array) && id[0][1] == 'element'))
- []
- else
- ['font']
- end
- end
- private :__item_font_optkeys
-
- def __item_numstrval_optkeys(id)
- if id == 'debug'
- ['displaydelay']
- else
- super(id)
- end
- end
- private :__item_numstrval_optkeys
-
- def __item_boolval_optkeys(id)
- if id == 'debug'
- ['data', 'display', 'enable']
- elsif id == 'dragimage'
- ['visible']
- elsif id == 'marquee'
- ['visible']
- elsif id.kind_of?(Array)
- case id[0]
- when 'item'
- ['button', 'visible']
- when 'column'
- if id[1] == 'drag'
- ['enable']
- else
- ['button', 'expand', 'resize', 'squeeze', 'sunken',
- 'visible', 'widthhack']
- end
- when 'element'
- ['draw', 'filled', 'showfocus', 'destroy']
- when 'notify'
- ['active']
- when 'style'
- ['detach']
- else
- if id[0].kind_of?(Array) && id[0][1] == 'element'
- ['filled', 'showfocus']
- else
- super(id)
- end
- end
- else
- super(id)
- end
- end
- private :__item_boolval_optkeys
-
- def __item_strval_optkeys(id)
- if id == 'debug'
- ['erasecolor']
- elsif id.kind_of?(Array)
- case id[0]
- when 'column'
- if id[1] == 'drag'
- ['indicatorcolor']
- else
- super(id) << 'textcolor'
- end
- when 'element'
- super(id) << 'fill' << 'outline' << 'format'
- else
- super(id)
- end
- else
- super(id)
- end
- end
- private :__item_strval_optkeys
-
def __item_listval_optkeys(id)
- if id.kind_of?(Array)
- case id[0]
- when 'column'
- ['itembackground']
- when 'element'
- ['relief']
- when 'style'
- ['union']
- else
- if id[0].kind_of?(Array) && id[0][1] == 'element'
- ['relief']
- else
- []
- end
- end
- else
- []
- end
+ []
end
private :__item_listval_optkeys
@@ -403,49 +244,23 @@ module Tk::TreeCtrl::ConfigMethod
itemconfigure(['column', tagOrId], slot, value)
end
def column_configinfo(tagOrId, slot=nil)
- itemconfiginfo(['column', tagOrId], slot)
+ itemconfigure(['column', tagOrId], slot)
end
def current_column_configinfo(tagOrId, slot=nil)
- current_itemconfiginfo(['column', tagOrId], slot)
- end
-
- def column_dragcget(option)
- itemcget(['column', 'drag'], option)
- end
- def column_dragconfigure(slot, value=None)
- itemconfigure(['column', 'drag'], slot, value)
- end
- def column_dragconfiginfo(slot=nil)
- itemconfiginfo(['column', 'drag'], slot)
- end
- def current_column_dragconfiginfo(slot=nil)
- current_itemconfiginfo(['column', 'drag'], slot)
+ itemconfigure(['column', tagOrId], slot)
end
- def debug_cget(option)
- itemcget('debug', option)
+ def dragimage_cget(tagOrId, option)
+ itemcget(['dragimage', tagOrId], option)
end
- def debug_configure(slot, value=None)
- itemconfigure('debug', slot, value)
+ def dragimage_configure(tagOrId, slot, value=None)
+ itemconfigure(['dragimage', tagOrId], slot, value)
end
- def debug_configinfo(slot=nil)
- itemconfiginfo('debug', slot)
+ def dragimage_configinfo(tagOrId, slot=nil)
+ itemconfigure(['dragimage', tagOrId], slot)
end
- def current_debug_configinfo(slot=nil)
- current_itemconfiginfo('debug', slot)
- end
-
- def dragimage_cget(option)
- itemcget('dragimage', option)
- end
- def dragimage_configure(slot, value=None)
- itemconfigure('dragimage', slot, value)
- end
- def dragimage_configinfo(slot=nil)
- itemconfiginfo('dragimage', slot)
- end
- def current_dragimage_configinfo(slot=nil)
- current_itemconfiginfo('dragimage', slot)
+ def current_dragimage_configinfo(tagOrId, slot=nil)
+ itemconfigure(['dragimage', tagOrId], slot)
end
def element_cget(tagOrId, option)
@@ -455,62 +270,46 @@ module Tk::TreeCtrl::ConfigMethod
itemconfigure(['element', tagOrId], slot, value)
end
def element_configinfo(tagOrId, slot=nil)
- itemconfiginfo(['element', tagOrId], slot)
+ itemconfigure(['element', tagOrId], slot)
end
def current_element_configinfo(tagOrId, slot=nil)
- current_itemconfiginfo(['element', tagOrId], slot)
- end
-
- def item_cget(tagOrId, option)
- itemcget(['item', tagOrId], option)
- end
- def item_configure(tagOrId, slot, value=None)
- itemconfigure(['item', tagOrId], slot, value)
- end
- def item_configinfo(tagOrId, slot=nil)
- itemconfiginfo(['item', tagOrId], slot)
- end
- def current_item_configinfo(tagOrId, slot=nil)
- current_itemconfiginfo(['item', tagOrId], slot)
+ itemconfigure(['element', tagOrId], slot)
end
- def item_element_cget(item, column, elem, option)
- itemcget([['item', 'element'], [item, column, elem]], option)
+ def item_element_cget(tagOrId, option)
+ itemcget([['item', 'element'], tagOrId], option)
end
- def item_element_configure(item, column, elem, slot, value=None)
- itemconfigure([['item', 'element'], [item, column, elem]], slot, value)
+ def item_element_configure(tagOrId, slot, value=None)
+ itemconfigure([['item', 'element'], tagOrId], slot, value)
end
- def item_element_configinfo(item, column, elem, slot=nil)
- itemconfiginfo([['item', 'element'], [item, column, elem]], slot)
+ def item_element_configinfo(tagOrId, slot=nil)
+ itemconfigure([['item', 'element'], tagOrId], slot)
end
- def current_item_element_configinfo(item, column, elem, slot=nil)
- current_itemconfiginfo([['item', 'element'], [item, column, elem]], slot)
+ def current_item_element_configinfo(tagOrId, slot=nil)
+ itemconfigure([['item', 'element'], tagOrId], slot)
end
- def marquee_cget(option)
- itemcget('marquee', option)
+ def marquee_cget(tagOrId, option)
+ itemcget(['marquee', tagOrId], option)
end
- def marquee_configure(slot, value=None)
- itemconfigure('marquee', slot, value)
+ def marquee_configure(tagOrId, slot, value=None)
+ itemconfigure(['marquee', tagOrId], slot, value)
end
- def marquee_configinfo(slot=nil)
- itemconfiginfo('marquee', slot)
+ def marquee_configinfo(tagOrId, slot=nil)
+ itemconfigure(['marquee', tagOrId], slot)
end
- def current_marquee_configinfo(slot=nil)
- current_itemconfiginfo('marquee', slot)
+ def current_marquee_configinfo(tagOrId, slot=nil)
+ itemconfigure(['marquee', tagOrId], slot)
end
def notify_cget(win, pattern, option)
- pattern = "<#{pattern}>"
itemconfigure(['notify', [win, pattern]], option)
end
def notify_configure(win, pattern, slot, value=None)
- pattern = "<#{pattern}>"
itemconfigure(['notify', [win, pattern]], slot, value)
end
def notify_configinfo(win, pattern, slot=nil)
- pattern = "<#{pattern}>"
- itemconfiginfo(['notify', [win, pattern]], slot)
+ itemconfigure(['notify', [win, pattern]], slot)
end
alias current_notify_configinfo notify_configinfo
@@ -521,10 +320,10 @@ module Tk::TreeCtrl::ConfigMethod
itemconfigure(['style', tagOrId], slot, value)
end
def style_configinfo(tagOrId, slot=nil)
- itemconfiginfo(['style', tagOrId], slot)
+ itemconfigure(['style', tagOrId], slot)
end
def current_style_configinfo(tagOrId, slot=nil)
- current_itemconfiginfo(['style', tagOrId], slot)
+ itemconfigure(['style', tagOrId], slot)
end
private :itemcget, :itemconfigure
@@ -538,43 +337,9 @@ class Tk::TreeCtrl
include Scrollable
TkCommandNames = ['treectrl'.freeze].freeze
- WidgetClassName = 'TreeCtrl'.freeze
+ WidgetClassName = ''.freeze
WidgetClassNames[WidgetClassName] = self
- #########################
-
- def __destroy_hook__
- Tk::TreeCtrl::Column::TreeCtrlColumnID_TBL.delete(@path)
- Tk::TreeCtrl::Element::TreeCtrlElementID_TBL.delete(@path)
- Tk::TreeCtrl::Item::TreeCtrlItemID_TBL.delete(@path)
- Tk::TreeCtrl::Style::TreeCtrlStyleID_TBL.delete(@path)
- end
-
- #########################
-
- def __strval_optkeys
- super() + [
- 'buttoncolor', 'columnprefix', 'itemprefix', 'linecolor'
- ]
- end
- private :__strval_optkeys
-
- def __boolval_optkeys
- [
- 'itemwidthequal', 'usetheme',
- 'showbuttons', 'showheader', 'showlines', 'showroot',
- 'showrootbutton', 'showrootlines',
- ]
- end
- private :__boolval_optkeys
-
- def __listval_optkeys
- [ 'defaultstyle' ]
- end
- private :__listval_optkeys
-
- #########################
-
def install_bind(cmd, *args)
install_bind_for_event_class(Tk::TreeCtrl::NotifyEvent, cmd, *args)
end
@@ -583,10 +348,9 @@ class Tk::TreeCtrl
def create_self(keys)
if keys and keys != None
- tk_call_without_enc(self.class::TkCommandNames[0], @path,
- *hash_kv(keys, true))
+ tk_call_without_enc('treectrl', @path, *hash_kv(keys, true))
else
- tk_call_without_enc(self.class::TkCommandNames[0], @path)
+ tk_call_without_enc('treectrl', @path)
end
end
private :create_self
@@ -607,13 +371,12 @@ class Tk::TreeCtrl
end
def collapse(*dsc)
- tk_send_without_enc('collapse', *(dsc.map!{|d| _get_eval_string(d, true)}))
+ tk_send('collapse', *dsc)
self
end
def collapse_recurse(*dsc)
- tk_send_without_enc('collapse', '-recurse',
- *(dsc.map!{|d| _get_eval_string(d, true)}))
+ tk_send('collapse', '-recurse', *dsc)
self
end
@@ -621,26 +384,7 @@ class Tk::TreeCtrl
list(tk_send('column', 'bbox', idx))
end
- def column_compare(column1, op, column2)
- bool(tk_send('column', 'compare', column1, op, column2))
- end
-
- def column_count
- num_or_str(tk_send('column', 'count'))
- end
-
- def column_create(keys=nil)
- if keys && keys.kind_of?(Hash)
- num_or_str(tk_send('column', 'create', *hash_kv(keys)))
- else
- num_or_str(tk_send('column', 'create'))
- end
- end
-
def column_delete(idx)
- if Tk::TreeCtrl::Column::TreeCtrlColumnID_TBL[self.path]
- Tk::TreeCtrl::Column::TreeCtrlColumnID_TBL[self.path].delete(idx)
- end
tk_send('column', 'delete', idx)
self
end
@@ -649,23 +393,8 @@ class Tk::TreeCtrl
num_or_str(tk_send('column', 'index', idx))
end
- def column_id(idx)
- tk_send('column', 'id', idx)
- end
-
- def column_list(visible=false)
- if visible
- simplelist(tk_send('column', 'list', '-visible'))
- else
- simplelist(tk_send('column', 'list'))
- end
- end
- def column_visible_list
- column_list(true)
- end
-
- def column_move(idx, before)
- tk_send('column', 'move', idx, before)
+ def column_move(idx, to)
+ tk_send('column', 'move', idx, to)
self
end
@@ -674,23 +403,12 @@ class Tk::TreeCtrl
end
alias column_neededwidth column_needed_width
- def column_order(column, visible=false)
- if visible
- num_or_str(tk_send('column', 'order', column, '-visible'))
- else
- num_or_str(tk_send('column', 'order', column))
- end
- end
- def column_visible_order(column)
- column_order(column, true)
- end
-
def column_width(idx)
num_or_str(tk_send('column', 'width', idx))
end
def compare(item1, op, item2)
- bool(tk_send('compare', item1, op, item2))
+ number(tk_send('compare', item1, op, item2))
end
def contentbox()
@@ -698,7 +416,7 @@ class Tk::TreeCtrl
end
def depth(item=None)
- num_or_str(tk_send_without_enc('depth', _get_eval_string(item, true)))
+ num_or_str(tk_send('depth', item))
end
def dragimage_add(item, *args)
@@ -732,15 +450,6 @@ class Tk::TreeCtrl
dragimage_visible()
end
- def debug_dinfo
- tk_send('debug', 'dinfo')
- self
- end
-
- def debug_scroll
- tk_send('debug', 'scroll')
- end
-
def element_create(elem, type, keys=nil)
if keys && keys.kind_of?(Hash)
tk_send('element', 'create', elem, type, *hash_kv(keys))
@@ -750,45 +459,18 @@ class Tk::TreeCtrl
end
def element_delete(*elems)
- if Tk::TreeCtrl::Element::TreeCtrlElementID_TBL[self.path]
- elems.each{|elem|
- Tk::TreeCtrl::Element::TreeCtrlElementID_TBL[self.path].delete(elem)
- }
- end
tk_send('element', 'delete', *elems)
self
end
def element_names()
- list(tk_send('element', 'names')).collect!{|elem|
- Tk::TreeCtrl::Element.id2obj(self, elem)
- }
- end
-
- def _conv_element_perstate_val(opt, val)
- case opt
- when 'background', 'foreground', 'fill', 'outline', 'format'
- val
- when 'draw', 'filled', 'showfocus', 'destroy'
- bool(val)
- else
- tk_tcl2ruby(val)
- end
- end
- private :_conv_element_perstate_val
-
- def element_perstate(elem, opt, st_list)
- tk_send('element', 'perstate', elem, "-{opt}", st_list)
+ list(tk_send('element', 'names'))
end
def element_type(elem)
tk_send('element', 'type', elem)
end
- def element_class(elem)
- Tk::TreeCtrl::Element.type2class(element_type(elem))
- end
-
def expand(*dsc)
tk_send('expand', *dsc)
self
@@ -800,37 +482,7 @@ class Tk::TreeCtrl
end
def identify(x, y)
- lst = list(tk_send('identify', x, y))
-
- if lst[0] == 'item'
- lst[1] = Tk::TreeCtrl::Item.id2obj(self, lst[1])
- size = lst.size
- i = 2
- while i < size
- case lst[i]
- when 'line'
- i += 1
- lst[i] = Tk::TreeCtrl::Item.id2obj(self, lst[i])
- i += 1
-
- when 'button'
- i += 1
-
- when 'column'
- i += 2
-
- when 'elem'
- i += 1
- lst[i] = Tk::TreeCtrl::Element.id2obj(self, lst[i])
- i += 1
-
- else
- i += 1
- end
- end
- end
-
- lst
+ list(tk_send('identify', x, y))
end
def index(idx)
@@ -838,9 +490,7 @@ class Tk::TreeCtrl
end
def item_ancestors(item)
- list(tk_send('item', 'ancestors', item)).collect!{|id|
- Tk::TreeCtrl::Item.id2obj(self, id)
- }
+ list(tk_send('item', 'ancestors', item))
end
def item_bbox(item, *args)
@@ -848,59 +498,19 @@ class Tk::TreeCtrl
end
def item_children(item)
- list(tk_send('item', 'children', item)).collect!{|id|
- Tk::TreeCtrl::Item.id2obj(self, id)
- }
- end
-
- def item_collapse(item)
- tk_send_without_enc('item', 'collapse', _get_eval_string(item, true))
- self
- end
-
- def item_collapse_recurse(item)
- tk_send_without_enc('item', 'collapse',
- _get_eval_string(item, true), '-recurse')
- self
- end
-
- def item_compare(item1, op, item2)
- bool(tk_send('item', 'compare', item1, op, item2))
+ list(tk_send('item', 'children', item))
end
def item_complex(item, *args)
- tk_send_without_enc('item', 'complex',
- _get_eval_string(item, true),
- *(args.map!{|arg| _get_eval_string(arg, true)}))
+ tk_send('item', 'complex', item, *args)
self
end
- def item_count
- num_or_str(tk_send('item', 'count'))
- end
-
- def item_create(keys={})
- num_or_str(tk_send_without_enc('item', 'create', *hash_kv(keys, true)))
- end
-
- def _erase_children(item)
- item_children(item).each{|i| _erase_children(i)}
- Tk::TreeCtrl::Item::TreeCtrlItemID_TBL[self.path].delete(item)
+ def item_create()
+ num_or_str(tk_send('item', 'create'))
end
- private :_erase_children
def item_delete(first, last=None)
- if Tk::TreeCtrl::Item::TreeCtrlItemID_TBL[self.path]
- if first == 'all' || first == :all || last == 'all' || last == :all
- Tk::TreeCtrl::Item::TreeCtrlItemID_TBL[self.path].clear
- elsif last == None
- _erase_children(first)
- else
- self.range(first, last).each{|id|
- _erase_children(id)
- }
- end
- end
tk_send('item', 'delete', first, last)
self
end
@@ -909,84 +519,30 @@ class Tk::TreeCtrl
list(tk_send('item', 'dump', item))
end
- def item_dump_hash(item)
- Hash[*list(tk_send('item', 'dump', item))]
- end
-
def item_element_actual(item, column, elem, key)
tk_send('item', 'element', 'actual', item, column, elem, "-#{key}")
end
- def item_element_perstate(elem, opt, st_list)
- tk_send('item', 'element', 'perstate', elem, "-{opt}", st_list)
- end
-
- def item_expand(item)
- tk_send('item', 'expand', item)
- self
- end
-
- def item_expand_recurse(item)
- tk_send('item', 'expand', item, '-recurse')
- self
- end
-
def item_firstchild(parent, child=nil)
if child
- tk_send_without_enc('item', 'firstchild',
- _get_eval_string(parent, true),
- _get_eval_string(child, true))
+ tk_send('item', 'firstchild', parent, child)
self
else
- id = num_or_str(tk_send_without_enc('item', 'firstchild',
- _get_eval_string(parent, true)))
- Tk::TreeCtrl::Item.id2obj(self, id)
+ num_or_str(tk_send('item', 'firstchild', parent))
end
end
alias item_first_child item_firstchild
- def item_hasbutton(item, st=None)
+ def item_hashbutton(item, st=None)
if st == None
- bool(tk_send_without_enc('item', 'hasbutton',
- _get_eval_string(item, true)))
+ bool(tk_send('item', 'hashbutton'))
else
- tk_send_without_enc('item', 'hasbutton',
- _get_eval_string(item, true),
- _get_eval_string(st))
+ tk_send('item', 'hashbutton', st)
self
end
end
- alias item_has_button item_hasbutton
-
- def item_hasbutton?(item)
- item_hasbutton(item)
- end
- alias item_has_button? item_hasbutton?
-
- def item_id(item)
- tk_send('item', 'id', item)
- end
-
- def item_image(item, column=nil, *args)
- if args.empty?
- if column
- img = tk_send('item', 'image', item, column)
- TkImage::Tk_IMGTBL[img]? TkImage::Tk_IMGTBL[img] : img
- else
- simplelist(tk_send('item', 'image', item)).collect!{|img|
- TkImage::Tk_IMGTBL[img]? TkImage::Tk_IMGTBL[img] : img
- }
- end
- else
- tk_send('item', 'image', item, column, *args)
- self
- end
- end
- def get_item_image(item, column=nil)
- item_image(item, column)
- end
- def set_item_image(item, col, img, *args)
- item_image(item, col, img, *args)
+ def item_hashbutton?(item)
+ item_hashbutton(item)
end
def item_index(item)
@@ -1011,14 +567,10 @@ class Tk::TreeCtrl
def item_lastchild(parent, child=nil)
if child
- tk_send_without_enc('item', 'lastchild',
- _get_eval_string(parent, true),
- _get_eval_string(child, true))
+ tk_send('item', 'lastchild', parent, child)
self
else
- id = num_or_str(tk_send_without_enc('item', 'lastchild',
- _get_eval_string(parent, true)))
- Tk::TreeCtrl::Item.id2obj(self, id)
+ num_or_str(tk_send('item', 'lastchild', parent))
end
end
alias item_last_child item_lastchild
@@ -1028,35 +580,19 @@ class Tk::TreeCtrl
tk_send('item', 'nextsibling', sibling, nxt)
self
else
- id = num_or_str(tk_send('item', 'nextsibling', sibling))
- Tk::TreeCtrl::Item.id2obj(self, id)
+ num_or_str(tk_send('item', 'nextsibling', sibling))
end
end
alias item_next_sibling item_nextsibling
- def item_numchildren(item)
- number(tk_send_without_enc('item', 'numchildren',
- _get_eval_string(item, true)))
+ def item_numchildren()
+ number(tk_send('item', 'numchildren'))
end
alias item_num_children item_numchildren
alias item_children_size item_numchildren
- def item_order(item, visible=false)
- if visible
- ret = num_or_str(tk_send('item', 'order', item, '-visible'))
- else
- ret = num_or_str(tk_send('item', 'order', item))
- end
-
- (ret.kind_of?(Fixnum) && ret < 0)? nil: ret
- end
- def item_visible_order(item)
- item_order(item, true)
- end
-
def item_parent(item)
- id = num_or_str(tk_send('item', 'parent', item))
- Tk::TreeCtrl::Item.id2obj(self, id)
+ num_or_str(tk_send('item', 'parent', item))
end
def item_prevsibling(sibling, prev=nil)
@@ -1064,111 +600,44 @@ class Tk::TreeCtrl
tk_send('item', 'prevsibling', sibling, prev)
self
else
- id = num_or_str(tk_send('item', 'prevsibling', sibling))
- Tk::TreeCtrl::Item.id2obj(self, id)
+ num_or_str(tk_send('item', 'prevsibling', sibling))
end
end
alias item_prev_sibling item_prevsibling
- def item_range(first, last)
- simplelist(tk_send('item', 'range', first, last))
- end
-
def item_remove(item)
- tk_send('item', 'remove', item)
- self
+ list(tk_send('item', 'remove', item))
end
def item_rnc(item)
list(tk_send('item', 'rnc', item))
end
- def _item_sort_core(real_sort, item, *opts)
- # opts ::= sort_param [, sort_param, ... ]
- # sort_param ::= {key=>val, ...}
- # [type, desc, {key=>val, ...}]
- # param
- opts = opts.collect{|param|
- if param.kind_of?(Hash)
- param = _symbolkey2str(param)
- if param.key?('column')
- key = '-column'
- desc = param.delete('column')
- elsif param.key?('element')
- key = '-element'
- desc = param.delete('element')
- else
- key = nil
- end
-
- if param.empty?
- param = None
- else
- param = hash_kv(__conv_item_keyonly_opts(item, param))
- end
-
- if key
- [key, desc].concat(param)
- else
- param
- end
-
- elsif param.kind_of?(Array)
- if param[2].kind_of?(Hash)
- param[2] = hash_kv(__conv_item_keyonly_opts(item, param[2]))
- end
- param
-
- elsif param.kind_of?(String) && param =~ /\A[a-z]+\Z/
- '-' << param
-
- elsif param.kind_of?(Symbol)
- '-' << param.to_s
+ def item_sort(item, *opts)
+ flag = false
+ if opts[-1].kind_of?(Hash)
+ opts[-1,1] = __conv_item_keyonly_opts(item, opts[-1]).to_a
+ end
+ opts = opts.collect{|opt|
+ if opt.kind_of?(Array)
+ key = "-#{opt[0]}"
+ flag = true if key == '-notreally'
+ ["-#{opt[0]}", opt[1]]
else
- param
+ key = "-#{opt}"
+ flag = true if key == '-notreally'
+ key
end
}.flatten
- if real_sort
- tk_send('item', 'sort', item, *opts)
- self
- else
- list(tk_send('item', 'sort', item, '-notreally', *opts))
- end
- end
- private :_item_sort_core
-
- def item_sort(item, *opts)
- _item_sort_core(true, item, *opts)
- end
- def item_sort_not_really(item, *opts)
- _item_sort_core(false, item, *opts)
- end
-
- def item_span(item, column=nil, *args)
- if args.empty?
- if column
- list(tk_send('item', 'span', item, column))
- else
- simplelist(tk_send('item', 'span', item)).collect!{|elem| list(elem)}
- end
+ ret = tk_send('item', 'sort', item, *opts)
+ if flag
+ list(ret)
else
- tk_send('item', 'span', item, column, *args)
- self
+ ret
end
end
- def get_item_span(item, column=nil)
- item_span(item, column)
- end
- def set_item_span(item, col, num, *args)
- item_span(item, col, num, *args)
- end
-
- def item_state_forcolumn(item, column, *args)
- tk_send('item', 'state', 'forcolumn', item, column, *args)
- end
- alias item_state_for_column item_state_forcolumn
def item_state_get(item, *args)
if args.empty?
@@ -1179,13 +648,12 @@ class Tk::TreeCtrl
end
def item_state_set(item, *args)
- tk_send('item', 'state', 'set', item, *args)
+ tk_send('item', 'state', 'set', *args)
+ self
end
- def item_style_elements(item, column)
- list(tk_send('item', 'style', 'elements', item, column)).collect!{|id|
- Tk::TreeCtrl::Style.id2obj(self, id)
- }
+ def item_style_elements(item, colun)
+ list(tk_send('item', 'style', 'elements', item, column))
end
def item_style_map(item, column, style, map)
@@ -1196,23 +664,12 @@ class Tk::TreeCtrl
def item_style_set(item, column=nil, *args)
if args.empty?
if column
- id = tk_send_without_enc('item', 'style', 'set',
- _get_eval_string(item, true),
- _get_eval_string(column, true))
- Tk::TreeCtrl::Style.id2obj(self, id)
+ tk_send('item', 'style', 'set', item, column)
else
- list(tk_send_without_enc('item', 'style', 'set',
- _get_eval_string(item, true))).collect!{|id|
- Tk::TreeCtrl::Style.id2obj(self, id)
- }
+ list(tk_send('item', 'style', 'set', item))
end
else
- tk_send_without_enc('item', 'style', 'set',
- _get_eval_string(item, true),
- _get_eval_string(column, true),
- *(args.flatten.map!{|arg|
- _get_eval_string(arg, true)
- }))
+ tk_send('item', 'style', 'set', item, *(args.flatten))
self
end
end
@@ -1226,21 +683,11 @@ class Tk::TreeCtrl
tk_send('item', 'text', item, column)
end
else
- tk_send('item', 'text', item, column, txt, *args)
+ tk_send('item', 'text', item, txt, *args)
self
end
end
- def item_toggle(item)
- tk_send('item', 'toggle', item)
- self
- end
-
- def item_toggle_recurse(item)
- tk_send('item', 'toggle', item, '-recurse')
- self
- end
-
def item_visible(item, st=None)
if st == None
bool(tk_send('item', 'visible', item))
@@ -1281,9 +728,7 @@ class Tk::TreeCtrl
end
def marquee_identify()
- list(tk_send('marquee', 'identify')).collect!{|id|
- Tk::TreeCtrl::Item.id2obj(self, id)
- }
+ list(tk_send('marquee', 'identify'))
end
def marquee_visible(st=None)
@@ -1298,38 +743,13 @@ class Tk::TreeCtrl
marquee_visible()
end
- #def notify_bind(obj, event, cmd=Proc.new, *args)
- # _bind([@path, 'notify', 'bind', obj], event, cmd, *args)
- # self
- #end
- def notify_bind(obj, event, *args)
- # if args[0].kind_of?(Proc) || args[0].kind_of?(Method)
- if TkComm._callback_entry?(args[0]) || !block_given?
- cmd = args.shift
- else
- cmd = Proc.new
- end
- _bind([@path, 'notify', 'bind', obj], event, cmd, *args)
- self
- end
-
- #def notify_bind_append(obj, event, cmd=Proc.new, *args)
- # _bind_append([@path, 'notify', 'bind', obj], event, cmd, *args)
- # self
- #end
- def notify_bind_append(obj, event, *args)
- # if args[0].kind_of?(Proc) || args[0].kind_of?(Method)
- if TkComm._callback_entry?(args[0]) || !block_given?
- cmd = args.shift
- else
- cmd = Proc.new
- end
- _bind_append([@path, 'notify', 'bind', obj], event, cmd, *args)
+ def notify_bind(obj, event, cmd=Proc.new, args=nil)
+ _bind([@path, 'notify', 'bind', obj], event, cmd, args)
self
end
- def notify_bind_remove(obj, event)
- _bind_remove([@path, 'notify', 'bind', obj], event)
+ def notify_bind_append(obj, event, cmd=Proc.new, args=nil)
+ _bind([@path, 'notify', 'bind', obj], event, cmd, args)
self
end
@@ -1345,22 +765,11 @@ class Tk::TreeCtrl
list(tk_send('notify', 'eventnames'))
end
- def notify_generate(pattern, char_map=None, percents_cmd=None)
- pattern = "<#{pattern}>"
- tk_send('notify', 'generate', pattern, char_map, percents_cmd)
+ def notify_generate(pattern, char_map=None)
+ tk_send('notify', 'generate', pattern, char_map)
self
end
- def notify_install(pattern, percents_cmd=nil, &b)
- pattern = "<#{pattern}>"
- percents_cmd = Proc.new(&b) if !percents_cmd && b
- if percents_cmd
- procedure(tk_send('notify', 'install', pattern, percents_cmd))
- else
- procedure(tk_send('notify', 'install', pattern))
- end
- end
-
def notify_install_detail(event, detail, percents_cmd=nil, &b)
percents_cmd = Proc.new(&b) if !percents_cmd && b
if percents_cmd
@@ -1379,45 +788,8 @@ class Tk::TreeCtrl
end
end
- def notify_linkage(pattern, detail=None)
- if detail != None
- tk_send('notify', 'linkage', pattern, detail)
- else
- begin
- if pattern.to_s.index(?-)
- # TreeCtrl 1.1 format?
- begin
- tk_send('notify', 'linkage', "<#{pattern}>")
- rescue
- # TreeCtrl 1.0?
- tk_send('notify', 'linkage', pattern)
- end
- else
- # TreeCtrl 1.0 format?
- begin
- tk_send('notify', 'linkage', pattern)
- rescue
- # TreeCtrl 1.1?
- tk_send('notify', 'linkage', "<#{pattern}>")
- end
- end
- end
- end
- end
-
- def notify_unbind(pattern=nil)
- if pattern
- tk_send('notify', 'unbind', "<#{pattern}>")
- else
- tk_send('notify', 'unbind')
- end
- self
- end
-
- def notify_uninstall(pattern)
- pattern = "<#{pattern}>"
- tk_send('notify', 'uninstall', pattern)
- self
+ def notify_linkage(event, detail=None)
+ tk_send('notify', 'linkage', event, detail)
end
def notify_uninstall_detail(event, detail)
@@ -1433,25 +805,17 @@ class Tk::TreeCtrl
def numcolumns()
num_or_str(tk_send('numcolumns'))
end
- alias num_columns numcolumns
- alias columns_size numcolumns
def numitems()
num_or_str(tk_send('numitems'))
end
- alias num_items numitems
- alias items_size numitems
def orphans()
- list(tk_send('orphans')).collect!{|id|
- Tk::TreeCtrl::Item.id2obj(self, id)
- }
+ list(tk_send('orphans'))
end
def range(first, last)
- list(tk_send('range', first, last)).collect!{|id|
- Tk::TreeCtrl::Item.id2obj(self, id)
- }
+ list(tk_send('range', first, last))
end
def state_define(name)
@@ -1483,12 +847,11 @@ class Tk::TreeCtrl
end
def selection_anchor(item=None)
- id = num_or_str(tk_send('selection', 'anchor', item))
- Tk::TreeCtrl::Item.id2obj(self, id)
+ num_or_str(tk_send('selection', 'anchor', item))
end
def selection_clear(*args) # first, last
- tk_send('selection', 'clear', *args)
+ tk_send('selection', 'clear' *args)
self
end
@@ -1497,9 +860,7 @@ class Tk::TreeCtrl
end
def selection_get()
- list(tk_send('selection', 'get')).collect!{|id|
- Tk::TreeCtrl::Item.id2obj(self, id)
- }
+ list(tk_send('selection', 'get'))
end
def selection_includes(item)
@@ -1520,77 +881,34 @@ class Tk::TreeCtrl
end
def style_delete(*args)
- if Tk::TreeCtrl::Style::TreeCtrlStyleID_TBL[self.path]
- args.each{|sty|
- Tk::TreeCtrl::Style::TreeCtrlStyleID_TBL[self.path].delete(sty)
- }
- end
tk_send('style', 'delete', *args)
self
end
def style_elements(style, *elems)
if elems.empty?
- list(tk_send('style', 'elements', style)).collect!{|id|
- Tk::TreeCtrl::Element.id2obj(self, id)
- }
+ list(tk_send('style', 'elements', style))
else
tk_send('style', 'elements', style, elems.flatten)
self
end
end
- def _conv_style_layout_val(sty, val)
- case sty.to_s
- when 'padx', 'pady', 'ipadx', 'ipady'
- lst = list(val)
- (lst.size == 1)? lst[0]: lst
- when 'detach', 'indent'
- bool(val)
- when 'union'
- simplelist(val).collect!{|elem|
- Tk::TreeCtrl::Element.id2obj(self, elem)
- }
- else
- val
- end
- end
- private :_conv_style_layout_val
-
def style_layout(style, elem, keys=None)
if keys && keys != None
if keys.kind_of?(Hash)
tk_send('style', 'layout', style, elem, *hash_kv(keys))
self
else
- _conv_style_layout_val(keys,
- tk_send('style', 'layout',
- style, elem, "-#{keys}"))
+ tk_send('style', 'layout', style, elem, "-#{keys}")
end
else
- ret = Hash.new
- Hash[*simplelist(tk_send('style', 'layout', style, elem))].each{|k, v|
- k = k[1..-1]
- ret[k] = _conv_style_layout_val(k, v)
- }
- ret
- end
- end
- def get_style_layout(style, elem, opt=None)
- style_layout(style, elem, opt)
- end
- def set_style_layout(style, elem, slot, value=None)
- if slot.kind_of?(Hash)
- style_layout(style, elem, slot)
- else
- style_layout(style, elem, {slot=>value})
+ list(tk_send('style', 'layout', style, elem))
end
end
def style_names()
- list(tk_send('style', 'names')).collect!{|id|
- Tk::TreeCtrl::Style.id2obj(self, id)
- }
+ list(tk_send('style', 'names'))
end
def toggle(*items)
@@ -1603,709 +921,3 @@ class Tk::TreeCtrl
self
end
end
-
-#####################
-
-class Tk::TreeCtrl::Column < TkObject
- TreeCtrlColumnID_TBL = TkCore::INTERP.create_table
- TreeCtrlColumnID = ['treectrl_column'.freeze, '00000'.taint].freeze
-
- TkCore::INTERP.init_ip_env{Tk::TreeCtrl::Column::TreeCtrlColumnID_TBL.clear}
-
- def self.id2obj(tree, id)
- tpath = tree.path
- return id unless Tk::TreeCtrl::Column::TreeCtrlColumnID_TBL[tpath]
- Tk::TreeCtrl::Column::TreeCtrlColumnID_TBL[tpath][id]? \
- Tk::TreeCtrl::Column::TreeCtrlColumnID_TBL[tpath][id] : id
- end
-
- def initialize(parent, keys={})
- @tree = parent
- @tpath = parent.path
-
- keys = _symbolkey2str(keys)
-
- @path = @id =
- keys.delete('tag') ||
- Tk::TreeCtrl::Column::TreeCtrlColumnID.join(TkCore::INTERP._ip_id_)
-
- keys['tag'] = @id
-
- unless Tk::TreeCtrl::Column::TreeCtrlColumnID_TBL[@tpath]
- Tk::TreeCtrl::Column::TreeCtrlColumnID_TBL[@tpath] = {}
- end
- Tk::TreeCtrl::Column::TreeCtrlColumnID_TBL[@tpath][@id] = self
- Tk::TreeCtrl::Column::TreeCtrlColumnID[1].succ!
-
- @tree.column_create(keys)
- end
-
- def id
- @id
- end
-
- def to_s
- @id.to_s.dup
- end
-
- def cget(opt)
- @tree.column_cget(@tree.column_index(@id), opt)
- end
-
- def configure(*args)
- @tree.column_configure(@tree.column_index(@id), *args)
- end
-
- def configinfo(*args)
- @tree.column_configinfo(@tree.column_index(@id), *args)
- end
-
- def current_configinfo(*args)
- @tree.current_column_configinfo(@tree.column_index(@id), *args)
- end
-
- def delete
- @tree.column_delete(@tree.column_index(@id))
- self
- end
-
- def index
- @tree.column_index(@id)
- end
-
- def move(before)
- @tree.column_move(@tree.column_index(@id), before)
- self
- end
-
- def needed_width
- @tree.column_needed_width(@tree.column_index(@id))
- end
- alias neededwidth needed_width
-
- def current_width
- @tree.column_width(@tree.column_index(@id))
- end
-end
-
-#####################
-
-class Tk::TreeCtrl::Element < TkObject
- TreeCtrlElementID_TBL = TkCore::INTERP.create_table
- TreeCtrlElementID = ['treectrl_element'.freeze, '00000'.taint].freeze
- TreeCtrlElemTypeToClass = {}
-
- TkCore::INTERP.init_ip_env{
- Tk::TreeCtrl::Element::TreeCtrlElementID_TBL.clear
- }
-
- def self.type2class(type)
- TreeCtrlElemTypeToClass[type] || type
- end
-
- def self.id2obj(tree, id)
- tpath = tree.path
- return id unless Tk::TreeCtrl::Element::TreeCtrlElementID_TBL[tpath]
- Tk::TreeCtrl::Element::TreeCtrlElementID_TBL[tpath][id]? \
- Tk::TreeCtrl::Element::TreeCtrlElementID_TBL[tpath][id] : id
- end
-
- def initialize(parent, type, keys=nil)
- @tree = parent
- @tpath = parent.path
- @type = type.to_s
- @path = @id =
- Tk::TreeCtrl::Element::TreeCtrlElementID.join(TkCore::INTERP._ip_id_)
- unless Tk::TreeCtrl::Element::TreeCtrlElementID_TBL[@tpath]
- Tk::TreeCtrl::Element::TreeCtrlElementID_TBL[@tpath] = {}
- end
- Tk::TreeCtrl::Element::TreeCtrlElementID_TBL[@tpath][@id] = self
- Tk::TreeCtrl::Element::TreeCtrlElementID[1].succ!
-
- @tree.element_create(@id, @type, keys)
- end
-
- def id
- @id
- end
-
- def to_s
- @id.dup
- end
-
- def cget(opt)
- @tree.element_cget(@id, opt)
- end
-
- def configure(*args)
- @tree.element_configure(@id, *args)
- end
-
- def configinfo(*args)
- @tree.element_configinfo(@id, *args)
- end
-
- def current_configinfo(*args)
- @tree.current_element_configinfo(@id, *args)
- end
-
- def delete
- @tree.element_delete(@id)
- self
- end
-
- def element_type
- @tree.element_type(@id)
- end
-
- def element_class
- @tree.element_class(@id)
- end
-end
-
-class Tk::TreeCtrl::BitmapElement < Tk::TreeCtrl::Element
- TreeCtrlElemTypeToClass['bitmap'] = self
-
- def initialize(parent, keys=nil)
- super(parent, 'bitmap', keys)
- end
-end
-
-class Tk::TreeCtrl::BorderElement < Tk::TreeCtrl::Element
- TreeCtrlElemTypeToClass['border'] = self
-
- def initialize(parent, keys=nil)
- super(parent, 'border', keys)
- end
-end
-
-class Tk::TreeCtrl::ImageElement < Tk::TreeCtrl::Element
- TreeCtrlElemTypeToClass['image'] = self
-
- def initialize(parent, keys=nil)
- super(parent, 'image', keys)
- end
-end
-
-class Tk::TreeCtrl::RectangleElement < Tk::TreeCtrl::Element
- TreeCtrlElemTypeToClass['rect'] = self
-
- def initialize(parent, keys=nil)
- super(parent, 'rect', keys)
- end
-end
-
-#####################
-
-class Tk::TreeCtrl::Item < TkObject
- TreeCtrlItemID_TBL = TkCore::INTERP.create_table
-
- TkCore::INTERP.init_ip_env{Tk::TreeCtrl::Item::TreeCtrlItemID_TBL.clear}
-
- def self.id2obj(tree, id)
- tpath = tree.path
- return id unless Tk::TreeCtrl::Item::TreeCtrlItemID_TBL[tpath]
- Tk::TreeCtrl::Item::TreeCtrlItemID_TBL[tpath][id]? \
- Tk::TreeCtrl::Item::TreeCtrlItemID_TBL[tpath][id] : id
- end
-
- def initialize(parent, keys={})
- @tree = parent
- @tpath = parent.path
- @path = @id = @tree.item_create(keys)
-
- unless Tk::TreeCtrl::Item::TreeCtrlItemID_TBL[@tpath]
- Tk::TreeCtrl::Item::TreeCtrlItemID_TBL[@tpath] = {}
- end
- Tk::TreeCtrl::Item::TreeCtrlItemID_TBL[@tpath][@id] = self
- end
-
- def id
- @id
- end
-
- def to_s
- @id.to_s.dup
- end
-
- def ancestors
- @tree.item_ancestors(@id)
- end
-
- def bbox(*args)
- @tree.item_bbox(@id, *args)
- end
-
- def children
- @tree.item_children(@id)
- end
-
- def collapse
- @tree.item_collapse(@id)
- self
- end
-
- def collapse_recurse
- @tree.item_collapse_recurse(@id)
- self
- end
-
- def complex(*args)
- @tree.item_complex(@id, *args)
- self
- end
-
- def cget(opt)
- @tree.item_cget(@id, opt)
- end
-
- def configure(*args)
- @tree.item_configure(@id, *args)
- end
-
- def configinfo(*args)
- @tree.item_configinfo(@id, *args)
- end
-
- def current_configinfo(*args)
- @tree.current_item_configinfo(@id, *args)
- end
-
- def delete
- @tree.item_delete(@id)
- self
- end
-
- def element_dump
- @tree.item_dump(@id)
- end
-
- def element_dump_hash
- @tree.item_dump_hash(@id)
- end
-
- def element_actual(column, elem, key)
- @tree.item_element_actual(@id, column, elem, key)
- end
-
- def element_cget(opt)
- @tree.item_element_cget(@id, opt)
- end
-
- def element_configure(*args)
- @tree.item_element_configure(@id, *args)
- end
-
- def element_configinfo(*args)
- @tree.item_element_configinfo(@id, *args)
- end
-
- def current_element_configinfo(*args)
- @tree.current_item_element_configinfo(@id, *args)
- end
-
- def expand
- @tree.item_expand(@id)
- self
- end
-
- def expand_recurse
- @tree.item_expand_recurse(@id)
- self
- end
-
- def firstchild(child=nil)
- if child
- @tree.item_firstchild(@id, child)
- self
- else
- @tree.item_firstchild(@id)
- end
- end
- alias first_child firstchild
-
- def hasbutton(st=None)
- if st == None
- @tree.item_hasbutton(@id)
- else
- @tree.item_hasbutton(@id, st)
- self
- end
- end
- alias has_button hasbutton
-
- def hasbutton?
- @tree.item_hasbutton(@id)
- end
- alias has_button? hasbutton?
-
- def index
- @tree.item_index(@id)
- end
-
- def isancestor(des)
- @tree.item_isancestor(@id, des)
- end
- alias is_ancestor isancestor
- alias isancestor? isancestor
- alias is_ancestor? isancestor
- alias ancestor? isancestor
-
- def isopen
- @tree.item_isopen(@id)
- end
- alias is_open isopen
- alias isopen? isopen
- alias is_open? isopen
- alias isopened? isopen
- alias is_opened? isopen
- alias open? isopen
-
- def lastchild(child=nil)
- if child
- @tree.item_lastchild(@id, child)
- self
- else
- @tree.item_lastchild(@id)
- end
- end
- alias last_child lastchild
-
- def nextsibling(nxt=nil)
- if nxt
- @tree.item_nextsibling(@id, nxt)
- self
- else
- @tree.item_nextsibling(@id)
- end
- end
- alias next_sibling nextsibling
-
- def numchildren
- @tree.item_numchildren(@id)
- end
- alias num_children numchildren
- alias children_size numchildren
-
- def parent_index
- @tree.item_parent(@id)
- end
-
- def prevsibling(nxt=nil)
- if nxt
- @tree.item_prevsibling(@id, nxt)
- self
- else
- @tree.item_prevsibling(@id)
- end
- end
- alias prev_sibling prevsibling
-
- def remove
- @tree.item_remove(@id)
- end
-
- def rnc
- @tree.item_rnc(@id)
- end
-
- def sort(*opts)
- @tree.item_sort(@id, *opts)
- end
- def sort_not_really(*opts)
- @tree.item_sort_not_really(@id, *opts)
- self
- end
-
- def state_forcolumn(column, *args)
- @tree.item_state_forcolumn(@id, column, *args)
- self
- end
- alias state_for_column state_forcolumn
-
- def state_get(*args)
- @tree.item_state_get(@id, *args)
- end
-
- def state_set(*args)
- @tree.item_state_set(@id, *args)
- self
- end
-
- def style_elements(column)
- @tree.item_style_elements(@id, column)
- end
-
- def style_map(column, style, map)
- @tree.item_style_map(@id, column, style, map)
- self
- end
-
- def style_set(column=nil, *args)
- if args.empty?
- @tree.item_style_set(@id, column)
- else
- @tree.item_style_set(@id, column, *args)
- self
- end
- end
-
- def item_text(column, txt=nil, *args)
- if args.empty?
- if txt
- @tree.item_text(@id, column, txt)
- self
- else
- @tree.item_text(@id, column)
- end
- else
- @tree.item_text(@id, column, txt, *args)
- self
- end
- end
-
- def toggle
- @tree.item_toggle(@id)
- self
- end
-
- def toggle_recurse
- @tree.item_toggle_recurse(@id)
- self
- end
-
- def visible(st=None)
- if st == None
- @tree.item_visible(@id)
- else
- @tree.item_visible(@id, st)
- self
- end
- end
-end
-
-#####################
-
-class Tk::TreeCtrl::Style < TkObject
- TreeCtrlStyleID_TBL = TkCore::INTERP.create_table
- TreeCtrlStyleID = ['treectrl_style'.freeze, '00000'.taint].freeze
-
- TkCore::INTERP.init_ip_env{ Tk::TreeCtrl::Style::TreeCtrlStyleID_TBL.clear }
-
- def self.id2obj(tree, id)
- tpath = tree.path
- return id unless Tk::TreeCtrl::Style::TreeCtrlStyleID_TBL[tpath]
- Tk::TreeCtrl::Style::TreeCtrlStyleID_TBL[tpath][id]? \
- Tk::TreeCtrl::Style::TreeCtrlStyleID_TBL[tpath][id] : id
- end
-
- def initialize(parent, keys=nil)
- @tree = parent
- @tpath = parent.path
- @path = @id =
- Tk::TreeCtrl::Style::TreeCtrlStyleID.join(TkCore::INTERP._ip_id_)
- unless Tk::TreeCtrl::Style::TreeCtrlStyleID_TBL[@tpath]
- Tk::TreeCtrl::Style::TreeCtrlStyleID_TBL[@tpath] = {}
- end
- Tk::TreeCtrl::Style::TreeCtrlStyleID_TBL[@tpath][@id] = self
- Tk::TreeCtrl::Style::TreeCtrlStyleID[1].succ!
-
- @tree.style_create(@id, keys)
- end
-
- def id
- @id
- end
-
- def to_s
- @id.dup
- end
-
- def cget(opt)
- @tree.style_cget(@id, opt)
- end
-
- def configure(*args)
- @tree.style_configure(@id, *args)
- end
-
- def configinfo(*args)
- @tree.style_configinfo(@id, *args)
- end
-
- def current_configinfo(*args)
- @tree.current_style_configinfo(@id, *args)
- end
-
- def delete
- @tree.style_delete(@id)
- self
- end
-
- def elements(*elems)
- if elems.empty?
- @tree.style_elements(@id)
- else
- @tree.style_elements(@id, *elems)
- self
- end
- end
-
- def layout(elem, keys=None)
- if keys && keys != None && keys.kind_of?(Hash)
- @tree.style_layout(@id, elem, keys)
- self
- else
- @tree.style_layout(@id, elem, keys)
- end
- end
-end
-
-module Tk::TreeCtrl::BindCallback
- include Tk
- extend Tk
-end
-
-class << Tk::TreeCtrl::BindCallback
- def percentsCmd(*args)
- tk_call('::TreeCtrl::PercentsCmd', *args)
- end
- def cursorCheck(w, x, y)
- tk_call('::TreeCtrl::CursorCheck', w, x, y)
- end
- def cursorCheckAux(w)
- tk_call('::TreeCtrl::CursorCheckAux', w)
- end
- def cursorCancel(w)
- tk_call('::TreeCtrl::CursorCancel', w)
- end
- def buttonPress1(w, x, y)
- tk_call('::TreeCtrl::ButtonPress1', w, x, y)
- end
- def doubleButton1(w, x, y)
- tk_call('::TreeCtrl::DoubleButton1', w, x, y)
- end
- def motion1(w, x, y)
- tk_call('::TreeCtrl::Motion1', w, x, y)
- end
- def leave1(w, x, y)
- tk_call('::TreeCtrl::Leave1', w, x, y)
- end
- def release1(w, x, y)
- tk_call('::TreeCtrl::Release1', w, x, y)
- end
- def beginSelect(w, el)
- tk_call('::TreeCtrl::BeginSelect', w, el)
- end
- def motion(w, le)
- tk_call('::TreeCtrl::Motion', w, el)
- end
- def beginExtend(w, el)
- tk_call('::TreeCtrl::BeginExtend', w, el)
- end
- def beginToggle(w, el)
- tk_call('::TreeCtrl::BeginToggle', w, el)
- end
- def cancelRepeat
- tk_call('::TreeCtrl::CancelRepeat')
- end
- def autoScanCheck(w, x, y)
- tk_call('::TreeCtrl::AutoScanCheck', w, x, y)
- end
- def autoScanCheckAux(w)
- tk_call('::TreeCtrl::AutoScanCheckAux', w)
- end
- def autoScanCancel(w)
- tk_call('::TreeCtrl::AutoScanCancel', w)
- end
- def up_down(w, n)
- tk_call('::TreeCtrl::UpDown', w, n)
- end
- def left_right(w, n)
- tk_call('::TreeCtrl::LeftRight', w, n)
- end
- def setActiveItem(w, idx)
- tk_call('::TreeCtrl::SetActiveItem', w, idx)
- end
- def extendUpDown(w, amount)
- tk_call('::TreeCtrl::ExtendUpDown', w, amount)
- end
- def dataExtend(w, el)
- tk_call('::TreeCtrl::DataExtend', w, el)
- end
- def cancel(w)
- tk_call('::TreeCtrl::Cancel', w)
- end
- def selectAll(w)
- tk_call('::TreeCtrl::selectAll', w)
- end
- def marqueeBegin(w, x, y)
- tk_call('::TreeCtrl::MarqueeBegin', w, x, y)
- end
- def marqueeUpdate(w, x, y)
- tk_call('::TreeCtrl::MarqueeUpdate', w, x, y)
- end
- def marqueeEnd(w, x, y)
- tk_call('::TreeCtrl::MarqueeEnd', w, x, y)
- end
- def scanMark(w, x, y)
- tk_call('::TreeCtrl::ScanMark', w, x, y)
- end
- def scanDrag(w, x, y)
- tk_call('::TreeCtrl::ScanDrag', w, x, y)
- end
-
- # filelist-bindings
- def fileList_button1(w, x, y)
- tk_call('::TreeCtrl::FileListButton1', w, x, y)
- end
- def fileList_motion1(w, x, y)
- tk_call('::TreeCtrl::FileListMotion1', w, x, y)
- end
- def fileList_motion(w, x, y)
- tk_call('::TreeCtrl::FileListMotion', w, x, y)
- end
- def fileList_leave1(w, x, y)
- tk_call('::TreeCtrl::FileListLeave1', w, x, y)
- end
- def fileList_release1(w, x, y)
- tk_call('::TreeCtrl::FileListRelease1', w, x, y)
- end
- def fileList_edit(w, i, s, e)
- tk_call('::TreeCtrl::FileListEdit', w, i, s, e)
- end
- def fileList_editCancel(w)
- tk_call('::TreeCtrl::FileListEditCancel', w)
- end
- def fileList_autoScanCheck(w, x, y)
- tk_call('::TreeCtrl::FileListAutoScanCheck', w, x, y)
- end
- def fileList_autoScanCheckAux(w)
- tk_call('::TreeCtrl::FileListAutoScanCheckAux', w)
- end
-
- def entryOpen(w, item, col, elem)
- tk_call('::TreeCtrl::EntryOpen', w, item, col, elem)
- end
- def entryExpanderOpen(w, item, col, elem)
- tk_call('::TreeCtrl::EntryExpanderOpen', w, item, col, elem)
- end
- def entryClose(w, accept)
- tk_call('::TreeCtrl::EntryClose', w, accept)
- end
- def entryExpanderKeypress(w)
- tk_call('::TreeCtrl::EntryExpanderKeypress', w)
- end
- def textOpen(w, item, col, elem, width=0, height=0)
- tk_call('::TreeCtrl::TextOpen', w, item, col, elem, width, height)
- end
- def textExpanderOpen(w, item, col, elem, width)
- tk_call('::TreeCtrl::TextOpen', w, item, col, elem, width)
- end
- def textClose(w, accept)
- tk_call('::TreeCtrl::TextClose', w, accept)
- end
- def textExpanderKeypress(w)
- tk_call('::TreeCtrl::TextExpanderKeypress', w)
- end
-end
diff --git a/ext/tk/lib/tkextlib/trofs.rb b/ext/tk/lib/tkextlib/trofs.rb
deleted file mode 100644
index 5914e5165f..0000000000
--- a/ext/tk/lib/tkextlib/trofs.rb
+++ /dev/null
@@ -1,13 +0,0 @@
-#
-# trofs support
-# by Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)
-#
-
-# call setup script for general 'tkextlib' libraries
-require 'tkextlib/setup.rb'
-
-# call setup script
-require 'tkextlib/trofs/setup.rb'
-
-# load library
-require 'tkextlib/trofs/trofs.rb'
diff --git a/ext/tk/lib/tkextlib/trofs/setup.rb b/ext/tk/lib/tkextlib/trofs/setup.rb
deleted file mode 100644
index ce0f0bd4d4..0000000000
--- a/ext/tk/lib/tkextlib/trofs/setup.rb
+++ /dev/null
@@ -1,8 +0,0 @@
-#
-# setup.rb -- setup script before calling TkPackage.require()
-#
-# If you need some setup operations (for example, add a library path
-# to the library search path) before using Tcl/Tk library packages
-# wrapped by Ruby scripts in this directory, please write the setup
-# operations in this file.
-#
diff --git a/ext/tk/lib/tkextlib/trofs/trofs.rb b/ext/tk/lib/tkextlib/trofs/trofs.rb
deleted file mode 100644
index 7a2606a275..0000000000
--- a/ext/tk/lib/tkextlib/trofs/trofs.rb
+++ /dev/null
@@ -1,51 +0,0 @@
-#
-# tkextlib/trofs/trofs.rb
-# by Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)
-#
-
-require 'tk'
-
-# call setup script for general 'tkextlib' libraries
-require 'tkextlib/setup.rb'
-
-# call setup script
-require 'tkextlib/trofs/setup.rb'
-
-# TkPackage.require('trofs', '0.4')
-TkPackage.require('trofs')
-
-module Tk
- module Trofs
- extend TkCore
-
- PACKAGE_NAME = 'trofs'.freeze
- def self.package_name
- PACKAGE_NAME
- end
-
- def self.package_version
- begin
- TkPackage.require('trofs')
- rescue
- ''
- end
- end
-
- ##############################################
-
- def self.create_archive(dir, archive)
- tk_call('::trofs::archive', dir, archive)
- archive
- end
-
- def self.mount(archive, mountpoint=None)
- # returns the normalized path to mountpoint
- tk_call('::trofs::mount', archive, mountpoint)
- end
-
- def self.umount(mountpoint)
- tk_call('::trofs::umount', mountpoint)
- mountpoint
- end
- end
-end
diff --git a/ext/tk/lib/tkextlib/vu.rb b/ext/tk/lib/tkextlib/vu.rb
index d2234eb2a8..c4ea1b86e6 100644
--- a/ext/tk/lib/tkextlib/vu.rb
+++ b/ext/tk/lib/tkextlib/vu.rb
@@ -20,11 +20,6 @@ module Tk
module Vu
TkComm::TkExtlibAutoloadModule.unshift(self)
- PACKAGE_NAME = 'vu'.freeze
- def self.package_name
- PACKAGE_NAME
- end
-
def self.package_version
begin
TkPackage.require('vu')
diff --git a/ext/tk/lib/tkextlib/vu/bargraph.rb b/ext/tk/lib/tkextlib/vu/bargraph.rb
index 27ff3c7cd0..3ac08a26a5 100644
--- a/ext/tk/lib/tkextlib/vu/bargraph.rb
+++ b/ext/tk/lib/tkextlib/vu/bargraph.rb
@@ -28,16 +28,6 @@ class Tk::Vu::Bargraph < TkWindow
end
private :__boolval_optkeys
- def __strval_optkeys
- super() + [
- 'title',
- 'barbackground', 'barcolor', 'barcolour',
- 'tickcolor', 'tickcolour',
- 'textcolor', 'textcolour',
- ]
- end
- private :__strval_optkeys
-
def __listval_optkeys
['alabels', 'blabels']
end
diff --git a/ext/tk/lib/tkextlib/vu/charts.rb b/ext/tk/lib/tkextlib/vu/charts.rb
index ee4298fa1c..a578c6979b 100644
--- a/ext/tk/lib/tkextlib/vu/charts.rb
+++ b/ext/tk/lib/tkextlib/vu/charts.rb
@@ -17,12 +17,6 @@ module Tk
end
private :__item_boolval_optkeys
- def __item_strval_optkeys(id)
- super(id) << 'bar' << 'color' << 'outline' <<
- 'fill' << 'scaleline' << 'stripline'
- end
- private :__item_strval_optkeys
-
def __item_listval_optkeys(id)
super(id) << 'values' << 'tags'
end
diff --git a/ext/tk/lib/tkextlib/vu/pie.rb b/ext/tk/lib/tkextlib/vu/pie.rb
index 78f3fa54da..dc676ad765 100644
--- a/ext/tk/lib/tkextlib/vu/pie.rb
+++ b/ext/tk/lib/tkextlib/vu/pie.rb
@@ -127,7 +127,7 @@ class Tk::Vu::PieSlice
def initialize(parent, *args)
unless parent.kind_of?(Tk::Vu::Pie)
- fail ArgumentError, "expect a Tk::Vu::Pie instance for 1st argument"
+ fail ArguemntError, "expect a Tk::Vu::Pie instance for 1st argument"
end
@parent = @pie = parent
@ppath = parent.path
@@ -218,7 +218,7 @@ class Tk::Vu::NamedPieSlice
def initialize(parent, name, *args)
unless parent.kind_of?(Tk::Vu::Pie)
- fail ArgumentError, "expect a Tk::Vu::Pie instance for 1st argument"
+ fail ArguemntError, "expect a Tk::Vu::Pie instance for 1st argument"
end
@parent = @pie = parent
@ppath = parent.path
diff --git a/ext/tk/lib/tkextlib/winico/winico.rb b/ext/tk/lib/tkextlib/winico/winico.rb
index c53a3ff48c..8a71cbb401 100644
--- a/ext/tk/lib/tkextlib/winico/winico.rb
+++ b/ext/tk/lib/tkextlib/winico/winico.rb
@@ -12,16 +12,10 @@ require 'tkextlib/setup.rb'
require 'tkextlib/winico/setup.rb'
# TkPackage.require('winico', '0.5')
-# TkPackage.require('winico', '0.6')
TkPackage.require('winico')
module Tk
class Winico < TkObject
- PACKAGE_NAME = 'winico'.freeze
- def self.package_name
- PACKAGE_NAME
- end
-
def self.package_version
begin
TkPackage.require('winico')
@@ -155,8 +149,7 @@ class Tk::Winico
if keys[k].kind_of?(Array)
cmd, *args = keys[k]
keys[k] = Winico_callback.new(cmd, args.join(' '))
- # elsif keys[k].kind_of?(Proc)
- elsif TkComm._callback_entry?(keys[k])
+ elsif keys[k].kind_of?(Proc)
keys[k] = Winico_callback.new(keys[k])
end
}
@@ -171,8 +164,7 @@ class Tk::Winico
if keys[k].kind_of?(Array)
cmd, *args = keys[k]
keys[k] = Winico_callback.new(cmd, args.join(' '))
- # elsif keys[k].kind_of?(Proc)
- elsif TkComm._callback_entry?(keys[k])
+ elsif keys[k].kind_of?(Proc)
keys[k] = Winico_callback.new(keys[k])
end
}
diff --git a/ext/tk/sample/cd_timer.rb b/ext/tk/sample/cd_timer.rb
deleted file mode 100644
index 9154e89bfe..0000000000
--- a/ext/tk/sample/cd_timer.rb
+++ /dev/null
@@ -1,81 +0,0 @@
-#!/usr/bin/env ruby
-#
-# countdown timer
-# usage: cd_timer min [, min ... ]
-# ( e.g. cd_timer 0.5 1 3 5 10 )
-#
-require 'tk'
-
-if ARGV.empty?
- $stderr.puts 'Error:: No time arguments for counting down'
- exit(1)
-end
-
-width = 10
-
-TkButton.new(:text=>'exit',
- :command=>proc{exit}).pack(:side=>:bottom, :fill=>:x)
-
-b = TkButton.new(:text=>'start').pack(:side=>:top, :fill=>:x)
-
-f = TkFrame.new(:relief=>:ridge, :borderwidth=>2).pack(:fill=>:x)
-TkLabel.new(f, :relief=>:flat, :pady=>3,
- :background=>'black', :foreground=>'white',
- :text=>' elapsed: ').pack(:fill=>:x, :side=>:left, :expand=>true)
-now = TkLabel.new(f, :width=>width, :relief=>:flat, :pady=>3, :anchor=>:w,
- :background=>'black', :foreground=>'white',
- :text=>'%4d:%02d.00' % [0, 0]).pack(:side=>:right)
-
-timers = [ TkRTTimer.new(10){|tm|
- t = (tm.return_value || 0) + 1
- s, u = t.divmod(100)
- m, s = s.divmod(60)
- now.text('%4d:%02d.%02d' % [m, s, u])
- t
- }.set_start_proc(0, proc{
- now.text('%4d:%02d.00' % [0,0])
- now.foreground('white')
- 0
- })
-]
-
-ARGV.collect{|arg| (Float(arg) * 60).to_i}.sort.each_with_index{|time, idx|
- f = TkFrame.new(:relief=>:ridge, :borderwidth=>2).pack(:fill=>:x)
- TkLabel.new(f, :relief=>:flat, :pady=>3,
- :text=>' %4d:%02d --> ' % (time.divmod(60))).pack(:side=>:left)
- l = TkLabel.new(f, :width=>width, :relief=>:flat, :pady=>3, :anchor=>:w,
- :text=>'%4d:%02d' % (time.divmod(60))).pack(:side=>:right)
- timers << TkRTTimer.new(1000){|tm|
- t = (tm.return_value || time) - 1
- if t < 0
- l.text('%4d:%02d' % ((-t).divmod(60)))
- else
- l.text('%4d:%02d' % (t.divmod(60)))
- end
- if t.zero?
- l.foreground('red')
- idx.times{Tk.bell}
- end
- t
- }.set_start_proc(0, proc{
- l.text('%4d:%02d' % (time.divmod(60)))
- l.foreground('black')
- time
- })
-}
-
-mode = :start
-b.command(proc{
- if mode == :start
- timers.each{|timer| timer.restart}
- b.text('reset')
- mode = :reset
- else
- timers.each{|timer| timer.stop.reset}
- b.text('start')
- mode = :start
- end
- })
-
-Tk.mainloop
-
diff --git a/ext/tk/sample/demos-en/anilabel.rb b/ext/tk/sample/demos-en/anilabel.rb
deleted file mode 100644
index f063bc53a4..0000000000
--- a/ext/tk/sample/demos-en/anilabel.rb
+++ /dev/null
@@ -1,172 +0,0 @@
-#
-# animated label widget demo (called by 'widget')
-#
-# based on Tcl/Tk8.5a2 widget demos
-
-if defined?($anilabel_demo) && $anilabel_demo
- $anilabel_demo.destroy
- $anilabel_demo = nil
-end
-
-# demo toplevel widget
-$anilabel_demo = TkToplevel.new {|w|
- title("Animated Label Demonstration")
- iconname("anilabel")
- positionWindow(w)
-}
-
-# label
-msg = TkLabel.new($anilabel_demo) {
- font $font
- wraplength '4i'
- justify 'left'
- text "Four animated labels are displayed below; each of the labels on the left is animated by making the text message inside it appear to scroll, and the label on the right is animated by animating the image that it displays."
-}
-msg.pack('side'=>'top')
-
-# frame
-TkFrame.new($anilabel_demo) {|frame|
- TkButton.new(frame) {
- text 'Dismiss'
- command proc{
- tmppath = $anilabel_demo
- $anilabel_demo = nil
- tmppath.destroy
- }
- }.pack('side'=>'left', 'expand'=>'yes')
-
- TkButton.new(frame) {
- text 'See Code'
- command proc{showCode 'anilabel'}
- }.pack('side'=>'left', 'expand'=>'yes')
-
-}.pack('side'=>'bottom', 'fill'=>'x', 'pady'=>'2m')
-
-# create frame for label demo
-f_left = TkLabelFrame.new($anilabel_demo, :text=>'Scrolling Texts')
-f_right = TkLabelFrame.new($anilabel_demo, :text=>'GIF Image')
-Tk.pack(f_left, f_right, 'side'=>'left', 'expand'=>'yes', 'fill'=>'both',
- 'padx'=>10, 'pady'=>10)
-
-# animated label
-class AnimatedTextLabel < TkLabel
- def initialize(*args)
- super(*args)
- @timer = TkTimer.new{ _animation_callback }
- @timer.loop_exec = -1
- # bind('Destroy'){ @timer.stop }
- @btag = TkBindTag.new('Destroy'){ @timer.stop }
- self.bindtags_unshift(@btag)
- end
-
- def _animation_callback()
- txt = self.text
- self.text = (txt[1..-1] << txt[0])
- end
- private :_animation_callback
-
- def start(interval)
- @timer.set_interval(interval)
- @timer.start
- end
-
- def stop
- @timer.stop
- end
-end
-
-# animated image
-class AnimatedImageLabel < AnimatedTextLabel
- def initialize(*args)
- super(*args)
- @destroy_image = false
- @btag.bind_append('Destroy'){
- if @destroy_image
- begin
- self.image.delete
- rescue
- end
- end
- }
- end
- attr_accessor :destroy_image
-
- def _animation_callback()
- img = self.image
-
- fmt = img.format
- if fmt.kind_of?(Array)
- if fmt[1].kind_of?(Hash)
- # fmt == ['GIF', {'index'=>idx}]
- idx = fmt[1]['index']
- else
- # fmt == ['GIF', '-index', idx] :: Ruby1.8.2 returns this.
- idx = fmt[2]
- end
- elsif fmt.kind_of?(String) && fmt =~ /GIF -index (\d+)/
- idx = $1.to_i
- else
- idx = -1
- end
-
- begin
- img.format("GIF -index #{idx + 1}")
- rescue => e
- img.format("GIF -index 0")
- end
- end
- private :_animation_callback
-end
-
-# create labels
-l1 = AnimatedTextLabel.new(f_left, :borderwidth=>4, :relief=>:ridge,
- :font=>{:family=>'Courier', :size=>10})
-l2 = AnimatedTextLabel.new(f_left, :borderwidth=>4, :relief=>:groove,
- :font=>{:family=>'Courier', :size=>10})
-l3 = AnimatedTextLabel.new(f_left, :borderwidth=>4, :relief=>:flat,
- :font=>{:family=>'Courier', :size=>10}, :width=>18)
-Tk.pack(l1, l2, l3,
- :side=>:top, :expand=>true, :anchor=>:w, :padx=>10, :pady=>10)
-
-limg = AnimatedImageLabel.new(f_right, :borderwidth=>0)
-limg.pack(:side=>:top, :expand=>true, :padx=>10, :pady=>10)
-
-# base64-encoded animated GIF file
-tclPowerdData = <<EOD
- R0lGODlhKgBAAPQAAP//////zP//AP/MzP/Mmf/MAP+Zmf+ZZv+ZAMz//8zM
- zMyZmcyZZsxmZsxmAMwzAJnMzJmZzJmZmZlmmZlmZplmM5kzM2aZzGZmzGZm
- mWZmZmYzZmYzMzNmzDMzZgAzmSH+IE1hZGUgd2l0aCBHSU1QIGJ5IExARGVt
- YWlsbHkuY29tACH5BAVkAAEALAAAAAAqAEAAAAX+YCCOZEkyTKM2jOm66yPP
- dF03bx7YcuHIDkGBR7SZeIyhTID4FZ+4Es8nQyCe2EeUNJ0peY2s9mi7PhAM
- ngEAMGRbUpvzSxskLh1J+Hkg134OdDIDEB+GHxtYMEQMTjMGEYeGFoomezaC
- DZGSHFmLXTQKkh8eNQVpZ2afmDQGHaOYSoEyhhcklzVmMpuHnaZmDqiGJbg0
- qFqvh6UNAwB7VA+OwydEjgujkgrPNhbTI8dFvNgEYcHcHx0lB1kX2IYeA2G6
- NN0YfkXJ2BsAMuAzHB9cZMk3qoEbRzUACsRCUBK5JxsC3iMiKd8GN088SIyT
- 0RAFSROyeEg38caDiB/+JEgqxsODrZJ1BkT0oHKSmI0ceQxo94HDpg0qsuDk
- UmRAMgu8OgwQ+uIJgUMVeGXA+IQkzEeHGvD8cIGlDXsLiRjQ+EHroQhea7xY
- 8IQBSgYYDi1IS+OFBCgaDMGVS3fGi5BPJpBaENdQ0EomKGD56IHwO39EXiSC
- Ysgxor5+Xfgq0qByYUpiXmwuoredB2aYH4gWWda0B7SeNENpEJHC1ghi+pS4
- AJpIAwWvKPBi+8YEht5EriEqpFfMlhEdkBNpx0HUhwypx5T4IB1MBg/Ws2sn
- wV3MSQOkzI8fUd48Aw3dOZto71x85hHtHijYv18Gf/3GqCdDCXHNoICBobSo
- IqBqJLyCoH8JPrLgdh88CKCFD0CGmAiGYPgffwceZh6FC2ohIIklnkhehTNY
- 4CIHHGzgwYw01ujBBhvAqKOLLq5AAk9kuSPkkKO40NB+h1gnypJIIvkBf09a
- N5QIRz5p5ZJXJpmlIVhOGQA2TmIJZZhKKmmll2BqyWSXWUrZpQtpatlmk1c2
- KaWRHeTZEJF8SqLDn/hhsOeQgBbqAh6DGqronxeARUIIACH5BAUeAAAALAUA
- LgAFAAUAAAUM4CeKz/OV5YmqaRkCACH5BAUeAAEALAUALgAKAAUAAAUUICCK
- z/OdJVCaa7p+7aOWcDvTZwgAIfkEBR4AAQAsCwAuAAkABQAABRPgA4zP95zA
- eZqoWqqpyqLkZ38hACH5BAUKAAEALAcALgANAA4AAAU7ICA+jwiUJEqeKau+
- r+vGaTmac63v/GP9HM7GQyx+jsgkkoRUHJ3Qx0cK/VQVTKtWwbVKn9suNunc
- WkMAIfkEBQoAAAAsBwA3AAcABQAABRGgIHzk842j+Yjlt5KuO8JmCAAh+QQF
- CgAAACwLADcABwAFAAAFEeAnfN9TjqP5oOWziq05lmUIACH5BAUKAAAALA8A
- NwAHAAUAAAUPoPCJTymS3yiQj4qOcPmEACH5BAUKAAAALBMANwAHAAUAAAUR
- oCB+z/MJX2o+I2miKimiawgAIfkEBQoAAAAsFwA3AAcABQAABRGgIHzfY47j
- Q4qk+aHl+pZmCAAh+QQFCgAAACwbADcABwAFAAAFEaAgfs/zCV9qPiNJouo7
- ll8IACH5BAUKAAAALB8ANwADAAUAAAUIoCB8o0iWZggAOw==
-EOD
-
-l1.text('* Slow Animation *').start(300)
-l2.text('* Fast Animation *').start(80)
-l3.text('This is a longer scrolling text in a widget that will not show the whole message at once. ').start(150)
-
-limg.destroy_image = true
-limg.image(TkPhotoImage.new(:format=>'GIF', :data=>tclPowerdData)).start(100)
diff --git a/ext/tk/sample/demos-en/aniwave.rb b/ext/tk/sample/demos-en/aniwave.rb
deleted file mode 100644
index ebe27b875f..0000000000
--- a/ext/tk/sample/demos-en/aniwave.rb
+++ /dev/null
@@ -1,115 +0,0 @@
-#
-# animated wave demo (called by 'widget')
-#
-# based on Tcl/Tk8.5a2 widget demos
-
-# destroy toplevel widget for this demo script
-if defined?($aniwave_demo) && $aniwave_demo
- $aniwave_demo.destroy
- $aniwave_demo = nil
-end
-
-# create toplevel widget
-$aniwave_demo = TkToplevel.new {|w|
- title("Animated Wave Demonstration")
- iconname("aniwave")
- positionWindow(w)
-}
-
-# create label
-msg = TkLabel.new($aniwave_demo) {
- font $font
- wraplength '4i'
- justify 'left'
- text 'This demonstration contains a canvas widget with a line item inside it. The animation routines work by adjusting the coordinates list of the line.'
-}
-msg.pack('side'=>'top')
-
-# create frame
-TkFrame.new($aniwave_demo) {|frame|
- TkButton.new(frame) {
- text 'Dismiss'
- command proc{
- tmppath = $aniwave_demo
- $aniwave_demo = nil
- tmppath.destroy
- }
- }.pack('side'=>'left', 'expand'=>'yes')
-
- TkButton.new(frame) {
- text 'See Code'
- command proc{showCode 'aniwave'}
- }.pack('side'=>'left', 'expand'=>'yes')
-
-}.pack('side'=>'bottom', 'fill'=>'x', 'pady'=>'2m')
-
-# animated wave
-class AnimatedWaveDemo
- def initialize(frame, dir=:left)
- @direction = dir
-
- # create canvas widget
- @c = TkCanvas.new(frame, :width=>300, :height=>200,
- :background=>'black')
- @c.pack(:padx=>10, :pady=>10, :expand=>true)
-
- # Creates a coordinates list of a wave.
- @waveCoords = []
- @backupCoords = []
- n = 0
- (-10..300).step(5){|n| @waveCoords << [n, 100]; @backupCoords << [n, 100] }
- @waveCoords << [n, 0]; @backupCoords << [n, 0]
- @waveCoords << [n+5, 200]; @backupCoords << [n+5, 200]
- @coordsLen = @waveCoords.length
-
- # Create a smoothed line and arrange for its coordinates to be the
- # contents of the variable waveCoords.
- @line = TkcLine.new(@c, @waveCoords,
- :width=>1, :fill=>'green', :smooth=>true)
-
- # Main animation "loop".
- # Theoretically 100 frames-per-second (==10ms between frames)
- @timer = TkTimer.new(10){ basicMotion; reverser }
-
- # Arrange for the animation loop to stop when the canvas is deleted
- @c.bindtags_unshift(TkBindTag.new('Destroy'){ @timer.stop })
- end
-
- # Basic motion handler. Given what direction the wave is travelling
- # in, it advances the y coordinates in the coordinate-list one step in
- # that direction.
- def basicMotion
- @backupCoords, @waveCoords = @waveCoords, @backupCoords
- (0...@coordsLen).each{|idx|
- if @direction == :left
- @waveCoords[idx][1] = @backupCoords[(idx+1 == @coordsLen)? 0: idx+1][1]
- else
- @waveCoords[idx][1] = @backupCoords[(idx == 0)? -1: idx-1][1]
- end
- }
- @line.coords(@waveCoords)
- end
-
- # Oscillation handler. This detects whether to reverse the direction
- # of the wave by checking to see if the peak of the wave has moved off
- # the screen (whose size we know already.)
- def reverser
- if @waveCoords[0][1] < 10
- @direction = :right
- elsif @waveCoords[-1][1] < 10
- @direction = :left
- end
- end
-
- # animation control
- def move
- @timer.start
- end
-
- def stop
- @timer.stop
- end
-end
-
-# Start the animation processing
-AnimatedWaveDemo.new($aniwave_demo, :left).move
diff --git a/ext/tk/sample/demos-en/bind.rb b/ext/tk/sample/demos-en/bind.rb
index aabe7f0849..0bd1f0ca6f 100644
--- a/ext/tk/sample/demos-en/bind.rb
+++ b/ext/tk/sample/demos-en/bind.rb
@@ -93,35 +93,17 @@ TkText.new($bind_demo){|t|
tag_binding_for_bind_demo(tag, tagstyle_bold, tagstyle_normal)
}
d1.bind('1',
- proc{
- eval(`cat #{[$demo_dir,'items.rb'].join(File::Separator)}`,
- _null_binding)
- })
+ proc{eval `cat #{[$demo_dir,'items.rb'].join(File::Separator)}`})
d2.bind('1',
- proc{
- eval(`cat #{[$demo_dir,'plot.rb'].join(File::Separator)}`,
- _null_binding)
- })
+ proc{eval `cat #{[$demo_dir,'plot.rb'].join(File::Separator)}`})
d3.bind('1',
- proc{
- eval(`cat #{[$demo_dir,'ctext.rb'].join(File::Separator)}`,
- _null_binding)
- })
+ proc{eval `cat #{[$demo_dir,'ctext.rb'].join(File::Separator)}`})
d4.bind('1',
- proc{
- eval(`cat #{[$demo_dir,'arrow.rb'].join(File::Separator)}`,
- _null_binding)
- })
+ proc{eval `cat #{[$demo_dir,'arrow.rb'].join(File::Separator)}`})
d5.bind('1',
- proc{
- eval(`cat #{[$demo_dir,'ruler.rb'].join(File::Separator)}`,
- _null_binding)
- })
+ proc{eval `cat #{[$demo_dir,'ruler.rb'].join(File::Separator)}`})
d6.bind('1',
- proc{
- eval(`cat #{[$demo_dir,'cscroll.rb'].join(File::Separator)}`,
- _null_binding)
- })
+ proc{eval `cat #{[$demo_dir,'cscroll.rb'].join(File::Separator)}`})
TkTextMarkInsert.new(t, '0.0')
configure('state','disabled')
diff --git a/ext/tk/sample/demos-en/check2.rb b/ext/tk/sample/demos-en/check2.rb
index 97d61fba0c..e2d5982d2d 100644
--- a/ext/tk/sample/demos-en/check2.rb
+++ b/ext/tk/sample/demos-en/check2.rb
@@ -76,31 +76,31 @@ TkCheckButton.new($check2_demo, :text=>'Safety Check', :variable=>safety,
# tristate check
in_check = false
tristate_check = proc{|n1,n2,op|
- unless in_check
- in_check = true
- begin
- if n1 == safety
- if safety == 'none'
- wipers.value = 0
- brakes.value = 0
- sober.value = 0
- elsif safety == 'all'
- wipers.value = 1
- brakes.value = 1
- sober.value = 1
- end
+ return if in_check
+
+ in_check = true
+ begin
+ if n1 == safety
+ if safety == 'none'
+ wipers.value = 0
+ brakes.value = 0
+ sober.value = 0
+ elsif safety == 'all'
+ wipers.value = 1
+ brakes.value = 1
+ sober.value = 1
+ end
+ else
+ if wipers == 1 && brakes == 1 && sober == 1
+ safety.value = 'all'
+ elsif wipers == 1 || brakes == 1 || sober == 1
+ safety.value = 'partial'
else
- if wipers == 1 && brakes == 1 && sober == 1
- safety.value = 'all'
- elsif wipers == 1 || brakes == 1 || sober == 1
- safety.value = 'partial'
- else
- safety.value = 'none'
- end
+ safety.value = 'none'
end
- ensure
- in_check = false
end
+ ensure
+ in_check = false
end
}
diff --git a/ext/tk/sample/demos-en/floor.rb b/ext/tk/sample/demos-en/floor.rb
index 53adcf96b6..15c56a154e 100644
--- a/ext/tk/sample/demos-en/floor.rb
+++ b/ext/tk/sample/demos-en/floor.rb
@@ -1667,8 +1667,8 @@ else
pack('expand'=>'yes', 'fill'=>'both', 'padx'=>1, 'pady'=>1)
- v.command(proc{|*args| $floor_canvas.yview(*args)})
- h.command(proc{|*args| $floor_canvas.xview(*args)})
+ v.command(proc{|*args| c.yview(*args)})
+ h.command(proc{|*args| c.xview(*args)})
}
end
diff --git a/ext/tk/sample/demos-en/floor2.rb b/ext/tk/sample/demos-en/floor2.rb
index efaf9e250d..ab8659a628 100644
--- a/ext/tk/sample/demos-en/floor2.rb
+++ b/ext/tk/sample/demos-en/floor2.rb
@@ -1667,8 +1667,8 @@ else
pack('expand'=>'yes', 'fill'=>'both', 'padx'=>1, 'pady'=>1)
- v.command(proc{|*args| $floor2_canvas.yview(*args)})
- h.command(proc{|*args| $floor2_canvas.xview(*args)})
+ v.command(proc{|*args| c.yview(*args)})
+ h.command(proc{|*args| c.xview(*args)})
}
end
diff --git a/ext/tk/sample/demos-en/goldberg.rb b/ext/tk/sample/demos-en/goldberg.rb
deleted file mode 100644
index 8d3f6d14f7..0000000000
--- a/ext/tk/sample/demos-en/goldberg.rb
+++ /dev/null
@@ -1,1999 +0,0 @@
-#
-# Ruby/Tk Goldverg demo (called by 'widget')
-#
-# Based on Tcl/Tk8.5a2 widget demos.
-# The following is the original comment of TkGoldberg.tcl.
-#
-#>>##+#################################################################
-#>>#
-#>># TkGoldberg.tcl
-#>># by Keith Vetter, March 13, 2003
-#>>#
-#>># "Man will always find a difficult means to perform a simple task"
-#>># Rube Goldberg
-#>>#
-#>># Reproduced here with permission.
-#>>#
-#>>##+#################################################################
-#>>#
-#>># Keith Vetter 2003-03-21: this started out as a simple little program
-#>># but was so much fun that it grew and grew. So I apologize about the
-#>># size but I just couldn't resist sharing it.
-#>>#
-#>># This is a whizzlet that does a Rube Goldberg type animation, the
-#>># design of which comes from an New Years e-card from IncrediMail.
-#>># That version had nice sound effects which I eschewed. On the other
-#>># hand, that version was in black and white (actually dark blue and
-#>># light blue) and this one is fully colorized.
-#>>#
-#>># One thing I learned from this project is that drawing filled complex
-#>># objects on a canvas is really hard. More often than not I had to
-#>># draw each item twice--once with the desired fill color but no
-#>># outline, and once with no fill but with the outline. Another trick
-#>># is erasing by drawing with the background color. Having a flood fill
-#>># command would have been extremely helpful.
-#>>#
-#>># Two wiki pages were extremely helpful: Drawing rounded rectangles
-#>># which I generalized into Drawing rounded polygons, and regular
-#>># polygons which allowed me to convert ovals and arcs into polygons
-#>># which could then be rotated (see Canvas Rotation). I also wrote
-#>># Named Colors to aid in the color selection.
-#>>#
-#>># I could comment on the code, but it's just 26 state machines with
-#>># lots of canvas create and move calls.
-
-if defined?($goldberg_demo) && $goldberg_demo
- $goldberg_demo.destroy
- $goldberg_demo = nil
-end
-
-# demo toplevel widget
-$goldberg_demo = TkToplevel.new {|w|
- title("Tk Goldberg (demonstration)")
- iconname("goldberg")
-# positionWindow(w)
-}
-
-=begin
-# label
-msg = TkLabel.new($goldberg_demo) {
- font 'Arial 10'
- wraplength '4i'
- justify 'left'
- text "This is a demonstration of just how complex you can make your animations become. Click the ball to start things moving!\n\n\"Man will always find a difficult means to perform a simple task\"\n - Rube Goldberg"
-}
-msg.pack('side'=>'top')
-=end
-
-=begin
-# frame
-TkFrame.new($goldberg_demo) {|frame|
- TkButton.new(frame) {
- text 'Dismiss'
- command proc{
- tmppath = $goldberg_demo
- $goldberg_demo = nil
- tmppath.destroy
- }
- }.pack('side'=>'left', 'expand'=>'yes')
-
- TkButton.new(frame) {
- text 'See Code'
- command proc{showCode 'goldberg'}
- }.pack('side'=>'left', 'expand'=>'yes')
-
-}.pack('side'=>'bottom', 'fill'=>'x', 'pady'=>'2m')
-=end
-
-#########################################
-
-class TkGoldberg_Demo
- def initialize(parent)
- @parent = parent
-
- @S = {}
- @S['title'] = 'Tk Goldberg'
- @S['speed'] = TkVariable.new(5)
- @S['cnt'] = TkVariable.new(0)
- @S['message'] = TkVariable.new("\\nWelcome\\nto\\nRuby/Tk")
- @S['pause'] = TkVariable.new
- @S['details'] = TkVariable.new(true)
-
- @S['mode'] = TkVariable.new(:MSTART, :symbol)
- # :MSTART, :MGO, :MPAUSE, :MSSTEP, :MBSTEP, :MDONE, :MDEBUG
-
- # 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
- @speed = [1, 10, 20, 50, 80, 100, 150, 200, 300, 400, 500]
-
- # colors
- @C = {}
- @C['fg'] = 'black'
- # @C['bg'] = 'gray75'
- @C['bg'] = 'cornflowerblue'
-
- @C['0'] = 'white'; @C['1a'] = 'darkgreen'; @C['1b'] = 'yellow'
- @C['2'] = 'red'; @C['3a'] = 'green'; @C['3b'] = 'darkblue'
- @C['4'] = @C['fg']; @C['5a'] = 'brown'; @C['5b'] = 'white'
- @C['6'] = 'magenta'; @C['7'] = 'green'; @C['8'] = @C['fg']
- @C['9'] = 'blue4'; @C['10a'] = 'white'; @C['10b'] = 'cyan'
- @C['11a'] = 'yellow'; @C['11b'] = 'mediumblue'; @C['12'] = 'tan2'
- @C['13a'] = 'yellow'; @C['13b'] = 'red'; @C['14'] = 'white'
- @C['15a'] = 'green'; @C['15b'] = 'yellow'; @C['16'] = 'gray65'
- @C['17'] = '#A65353'; @C['18'] = @C['fg']; @C['19'] = 'gray50'
- @C['20'] = 'cyan'; @C['21'] = 'gray65'; @C['22'] = @C['20']
- @C['23a'] = 'blue'; @C['23b'] = 'red'; @C['23c'] = 'yellow'
- @C['24a'] = 'red'; @C['24b'] = 'white';
-
- @STEP = TkVariable.new_hash
- @STEP.default_value_type = :numeric
-
- @XY = {}
-
- @XY6 = {
- '-1'=>[366, 207], '-2'=>[349, 204], '-3'=>[359, 193], '-4'=>[375, 192],
- '-5'=>[340, 190], '-6'=>[349, 177], '-7'=>[366, 177], '-8'=>[380, 176],
- '-9'=>[332, 172], '-10'=>[342, 161], '-11'=>[357, 164],
- '-12'=>[372, 163], '-13'=>[381, 149], '-14'=>[364, 151],
- '-15'=>[349, 146], '-16'=>[333, 148], '0'=>[357, 219],
- '1'=>[359, 261], '2'=>[359, 291], '3'=>[359, 318], '4'=>[361, 324],
- '5'=>[365, 329], '6'=>[367, 334], '7'=>[367, 340], '8'=>[366, 346],
- '9'=>[364, 350], '10'=>[361, 355], '11'=>[359, 370], '12'=>[359, 391],
- '13,0'=>[360, 456], '13,1'=>[376, 456], '13,2'=>[346, 456],
- '13,3'=>[330, 456], '13,4'=>[353, 444], '13,5'=>[368, 443],
- '13,6'=>[339, 442], '13,7'=>[359, 431], '13,8'=>[380, 437],
- '13,9'=>[345, 428], '13,10'=>[328, 434], '13,11'=>[373, 424],
- '13,12'=>[331, 420], '13,13'=>[360, 417], '13,14'=>[345, 412],
- '13,15'=>[376, 410], '13,16'=>[360, 403]
- }
-
- @timer = TkTimer.new(@speed[@S['speed'].numeric]){|timer|
- timer.set_interval(go)
- }
-
- do_display
- reset
-
- # Start everything going
- @timer.start
- end
-
- def do_display()
- @ctrl = TkFrame.new(@parent, :relief=>:ridge, :bd=>2, :padx=>5, :pady=>5)
- @screen = TkFrame.new(@parent, :bd=>2,
- :relief=>:raised).pack(:side=>:left, :fill=>:both,
- :expand=>true)
-
- @canvas = TkCanvas.new(@parent, :width=>850, :height=>700,
- :bg=>@C['bg'], :highlightthickness=>0){
- scrollregion([0, 0, 1000, 1000]) # Kludge to move everything up
- yview_moveto(0.05)
- }.pack(:in=>@screen, :side=>:top, :fill=>:both, :expand=>true)
-
- @canvas.bind('3'){ @pause.invoke }
- @canvas.bind('Destroy'){ @timer.stop }
-
- do_ctrl_frame
- do_detail_frame
-
- msg = TkLabel.new(@parent, :bg=>@C['bg'], :fg=>'white') {
- font 'Arial 10'
- wraplength 600
- justify 'left'
- text "This is a demonstration of just how complex you can make your animations become. Click the ball to start things moving!\n\"Man will always find a difficult means to perform a simple task\" - Rube Goldberg"
- }
- msg.place(:in=>@canvas, :relx=>0, :rely=>0, :anchor=>:nw)
-
- frame = TkFrame.new(@parent, :bg=>@C['bg'])
-
- TkButton.new(frame, :bg=>@C['bg'], :activebackground=>@C['bg']) {
- text 'Dismiss'
- command proc{
- tmppath = $goldberg_demo
- $goldberg_demo = nil
- tmppath.destroy
- }
- }.pack('side'=>'left')
-
- TkButton.new(frame, :bg=>@C['bg'], :activebackground=>@C['bg']) {
- text 'See Code'
- command proc{showCode 'goldberg'}
- }.pack('side'=>'left', 'padx'=>5)
-
- @show = TkButton.new(frame, :text=>'>>', :command=>proc{show_ctrl},
- :bg=>@C['bg'], :activebackground=>@C['bg'])
- @show.pack('side'=>'left')
- frame.place(:in=>@canvas, :relx=>1, :rely=>0, :anchor=>:ne)
-
- Tk.update
- end
-
- def do_ctrl_frame
- @start = TkButton.new(@parent, :text=>'Start', :bd=>6,
- :command=>proc{do_button(0)})
- @start.font(@start['font'].weight('bold'))
- font = @start['font']
-
- @pause = TkCheckbutton.new(@parent, :text=>'Pause', :font=>font,
- :command=>proc{do_button(1)}, :relief=>:raised,
- :variable=>@S['pause'])
-
- @step = TkButton.new(@parent, :text=>'Single Step', :font=>font,
- :command=>proc{do_button(2)})
- @bstep = TkButton.new(@parent, :text=>'Big Step', :font=>font,
- :command=>proc{do_button(4)})
- @reset = TkButton.new(@parent, :text=>'Reset', :font=>font,
- :command=>proc{do_button(3)})
-
- @details = TkFrame.new(@parent, :bd=>2, :relief=>:ridge)
- @detail = TkCheckbutton.new(@parent, :text=>'Details', :font=>font,
- :relief=>:raised, :variable=>@S['details'])
-
- @msg_entry = TkEntry.new(@parent, :textvariable=>@S['message'],
- :justify=>:center)
- @speed_scale = TkScale.new(@parent, :orient=>:horizontal,
- :from=>1, :to=>10, :font=>font,
- :variable=>@S['speed'], :bd=>2,
- :relief=>:ridge, :showvalue=>false)
- @about = TkButton.new(@parent, :text=>'About',
- :command=>proc{about}, :font=>font)
-
- Tk.grid(@start, :in=>@ctrl, :row=>0, :sticky=>:ew)
- @ctrl.grid_rowconfigure(1, :minsize=>10)
- Tk.grid(@pause, :in=>@ctrl, :row=>2, :sticky=>:ew)
- Tk.grid(@step, :in=>@ctrl, :sticky=>:ew)
- Tk.grid(@bstep, :in=>@ctrl, :sticky=>:ew)
- Tk.grid(@reset, :in=>@ctrl, :sticky=>:ew)
- @ctrl.grid_rowconfigure(10, :minsize=>20)
- Tk.grid(@details, :in=>@ctrl, :row=>11, :sticky=>:ew)
- Tk.grid(@detail, :in=>@details, :row=>0, :sticky=>:ew)
- @ctrl.grid_rowconfigure(50, :weight=>1)
-
- @S['mode'].trace('w', proc{|*args| active_GUI(*args)})
- @S['details'].trace('w', proc{|*args| active_GUI(*args)})
- @S['speed'].trace('w', proc{|*args| active_GUI(*args)})
-
- Tk.grid(@msg_entry, :in=>@ctrl, :row=>98, :sticky=>:ew, :pady=>5)
- Tk.grid(@speed_scale, :in=>@ctrl, :row=>99, :sticky=>:ew)
- Tk.grid(@about, :in=>@ctrl, :row=>100, :sticky=>:ew)
-
- @reset.bind('3'){@S['mode'].value = -1} # Debugging
- end
-
- def do_detail_frame
- @f_details = TkFrame.new(@details)
-
- @label = TkLabel.new(@f_details, :textvariable=>@S['cnt'],
- :bd=>1, :relief=>:solid, :bg=>'white')
- Tk.grid(@label, '-', '-', '-', :sticky=>:ew, :row=>0)
-
- idx = 1
- loop {
- break unless respond_to?("move#{idx}")
- l = TkLabel.new(@f_details, :text=>idx, :anchor=>:e,
- :width=>2, :bd=>1, :relief=>:solid, :bg=>'white')
- @STEP[idx] = 0
- ll = TkLabel.new(@f_details, :textvariable=>@STEP.ref(idx),
- :width=>5, :bd=>1, :relief=>:solid, :bg=>'white')
- row = (idx + 1)/2
- col = ((idx + 1) & 1) * 2
- Tk.grid(l, :sticky=>:ew, :row=>row, :column=>col)
- Tk.grid(ll, :sticky=>:ew, :row=>row, :column=>(col + 1))
- idx += 1
- }
- @f_details.grid_columnconfigure(1, :weight=>1)
- end
-
- def show_ctrl
- if @ctrl.winfo_mapped?
- @ctrl.pack_forget
- @show.text('>>')
- else
- @ctrl.pack(:side=>:right, :fill=>:both, :ipady=>5)
- @show.text('<<')
- end
- end
-
- def draw_all
- reset_step
- @canvas.delete(:all)
- idx = 0
- loop{
- m = "draw#{idx}"
- break unless respond_to?(m)
- send(m)
- idx += 1
- }
- end
-
- def active_GUI(var1, var2, op)
- st = {false=>:disabled, true=>:normal}
-
- m = @S['mode'].to_sym
- @S['pause'].value = (m == :MPAUSE)
- @start.state(st[m != :MGO])
- @pause.state(st[m != :MSTART && m != :MDONE])
- @step.state(st[m != :MGO && m != :MDONE])
- @bstep.state(st[m != :MGO && m != :MDONE])
- @reset.state(st[m != :MSTART])
-
- if @S['details'].bool
- Tk.grid(@f_details, :in=>@details, :row=>2, :sticky=>:ew)
- else
- Tk.grid_forget(@f_details)
- end
- @speed_scale.label("Speed: #{@S['speed'].value}")
- end
-
- def start
- @S['mode'].value = :MGO
- end
-
- def do_button(what)
- case what
- when 0 # Start
- reset if @S['mode'].to_sym == :MDONE
- @S['mode'].value = :MGO
-
- when 1 # Pause
- @S['mode'].value = ((@S['pause'].bool)? :MPAUSE: :MGO)
-
- when 2 # Step
- @S['mode'].value = :MSSTEP
-
- when 3 # Reset
- reset
-
- when 4 # Big step
- @S['mode'].value = :MBSTEP
- end
- end
-
- def go(who = nil)
- now = Tk::Clock.clicks(:miliseconds)
- if who # Start here for debugging
- @S['active'] = [who]
- @S['mode'].value = :MGO
- end
- return if @S['mode'].to_sym == :MDEBUG # Debugging
- # If not paused, do the next move
- n = next_step if @S['mode'].to_sym != :MPAUSE
- @S['mode'].value = :MPAUSE if @S['mode'].to_sym == :MSSTEP # Single step
- @S['mode'].value = :MSSTEP if @S['mode'].to_sym == :MBSTEP && n # big step
- elapsed = Tk::Clock.clicks(:miliseconds) - now
- delay = @speed[@S['speed'].to_i] - elapsed
- delay = 1 if delay <= 0
- return delay
- end
-
- def next_step
- retval = false # Return value
-
- if @S['mode'].to_sym != :MSTART && @S['mode'].to_sym != :MDONE
- @S['cnt'].numeric += 1
- end
- alive = []
- @S['active'].each{|who|
- who = who.to_i
- n = send("move#{who}")
- if (n & 1).nonzero? # This guy still alive
- alive << who
- end
- if (n & 2).nonzero? # Next guy is active
- alive << (who + 1)
- retval = true
- end
- if (n & 4).nonzero? # End of puzzle flag
- @S['mode'].value = :MDONE # Done mode
- @S['active'] = [] # No more animation
- return true
- end
- }
- @S['active'] = alive
- return retval
- end
-
- def about
- msg = "Ruby/Tk Version ::\nby Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)\n\n"
- msg += "Original Version ::\n"
- msg += "#{@S['title']}\nby Keith Vetter, March 2003\n(Reproduced by kind permission of the author)\n\n"
- msg += "Man will always find a difficult means to perform a simple task"
- msg += "\nRube Goldberg"
- Tk.messageBox(:message=>msg, :title=>'About')
- end
-
- ################################################################
- #
- # All the drawing and moving routines
- #
-
- # START HERE! banner
- def draw0
- color = @C['0']
- TkcText.new(@canvas, [579, 119], :text=>'START HERE!',
- :fill=>color, :anchor=>:w,
- :tag=>'I0', :font=>['Times Roman', 12, :italic, :bold])
- TkcLine.new(@canvas, [719, 119, 763, 119], :tag=>'I0', :fill=>color,
- :width=>5, :arrow=>:last, :arrowshape=>[18, 18, 5])
- @canvas.itembind('I0', '1'){ start }
- end
-
- def move0(step = nil)
- step = get_step(0, step)
-
- if @S['mode'].to_sym != :MSTART # Start the ball rolling
- move_abs('I0', [-100, -100]) # Hide the banner
- return 2
- end
-
- pos = [
- [673, 119], [678, 119], [683, 119], [688, 119],
- [693, 119], [688, 119], [683, 119], [678, 119]
- ]
- step = step % pos.length
- move_abs('I0', pos[step])
- return 1
- end
-
- # Dropping ball
- def draw1
- color = @C['1a']
- color2 = @C['1b']
- TkcPolygon.new(@canvas,
- [ 844, 133, 800, 133, 800, 346, 820, 346,
- 820, 168, 844, 168, 844, 133 ],
- :width=>3, :fill=>color, :outline=>'')
- TkcPolygon.new(@canvas,
- [ 771, 133, 685, 133, 685, 168, 751, 168,
- 751, 346, 771, 346, 771, 133 ],
- :width=>3, :fill=>color, :outline=>'')
- TkcOval.new(@canvas, box(812, 122, 9),
- :tag=>'I1', :fill=>color2, :outline=>'')
-
- @canvas.itembind('I1', '1'){ start }
- end
-
- def move1(step = nil)
- step = get_step(1, step)
- pos = [
- [807, 122], [802, 122], [797, 123], [793, 124], [789, 129], [785, 153],
- [785, 203], [785, 278, :x], [785, 367], [810, 392], [816, 438],
- [821, 503], [824, 585, :y], [838, 587], [848, 593], [857, 601],
- [-100, -100]
- ]
- return 0 if step >= pos.length
- where = pos[step]
- move_abs('I1', where)
- move15a if where[2] == :y
- return 3 if where[2] == :x
- return 1
- end
-
- # Lighting the match
- def draw2
- color = @C['2']
-
- # Fulcrum
- TkcPolygon.new(@canvas, [750, 369, 740, 392, 760, 392],
- :fill=>@C['fg'], :outline=>@C['fg'])
-
- # Strike box
- TkcRectangle.new(@canvas, [628, 335, 660, 383],
- :fill=>'', :outline=>@C['fg'])
- (0..2).each{|y|
- yy = 335 + y*16
- TkcBitmap.new(@canvas, [628, yy], :bitmap=>'gray25',
- :anchor=>:nw, :foreground=>@C['fg'])
- TkcBitmap.new(@canvas, [644, yy], :bitmap=>'gray25',
- :anchor=>:nw, :foreground=>@C['fg'])
- }
-
- # Lever
- TkcLine.new(@canvas, [702, 366, 798, 366],
- :fill=>@C['fg'], :width=>6, :tag=>'I2_0')
-
- # R strap
- TkcLine.new(@canvas, [712, 363, 712, 355],
- :fill=>@C['fg'], :width=>3, :tag=>'I2_1')
-
- # L strap
- TkcLine.new(@canvas, [705, 363, 705, 355],
- :fill=>@C['fg'], :width=>3, :tag=>'I2_2')
-
- # Match stick
- TkcLine.new(@canvas, [679, 356, 679, 360, 717, 360, 717, 356, 679, 356],
- :fill=>@C['fg'], :width=>3, :tag=>'I2_3')
-
- # Match head
- TkcPolygon.new(@canvas,
- [ 671, 352, 677.4, 353.9, 680, 358.5, 677.4, 363.1,
- 671, 365, 664.6, 363.1, 662, 358.5, 664.6, 353.9 ],
- :fill=>color, :outline=>color, :tag=>'I2_4')
- end
-
- def move2(step = nil)
- step = get_step(2, step)
-
- stages = [0, 0, 1, 2, 0, 2, 1, 0, 1, 2, 0, 2, 1]
- xy = []
- xy[0] = [
- 686, 333, 692, 323, 682, 316, 674, 309, 671, 295, 668, 307,
- 662, 318, 662, 328, 671, 336
- ]
- xy[1] = [
- 687, 331, 698, 322, 703, 295, 680, 320, 668, 297, 663, 311,
- 661, 327, 671, 335
- ]
- xy[2] = [
- 686, 331, 704, 322, 688, 300, 678, 283, 678, 283, 674, 298,
- 666, 309, 660, 324, 672, 336
- ]
-
- if step >= stages.length
- @canvas.delete('I2')
- return 0
- end
-
- if step == 0 # Rotate the match
- beta = 20
-
- ox, oy = anchor('I2_0', :s) # Where to pivot
-
- i = 0
- until @canvas.find_withtag("I2_#{i}").empty?
- rotate_item("I2_#{i}", ox, oy, beta)
- i += 1
- end
-
- # For the flame
- TkcPolygon.new(@canvas, [], :tag=>'I2', :smooth=>true, :fill=>@C['2'])
-
- return 1
- end
- @canvas.coords('I2', xy[stages[step]])
- return ((step == 7)? 3: 1)
- end
-
- # Weight and pulleys
- def draw3
- color = @C['3a']
- color2 = @C['3b']
-
- xy = [ [602, 296], [577, 174], [518, 174] ]
- xy.each{|x, y| # 3 Pulleys
- TkcOval.new(@canvas, box(x, y, 13),
- :fill=>color, :outline=>@C['fg'], :width=>3)
- TkcOval.new(@canvas, box(x, y, 2), :fill=>@C['fg'], :outline=>@C['fg'])
- }
-
- # Wall to flame
- TkcLine.new(@canvas, [750, 309, 670, 309], :tag=>'I3_s',
- :width=>3, :fill=>@C['fg'], :smooth=>true)
-
- # Flame to pulley 1
- TkcLine.new(@canvas, [670, 309, 650, 309], :tag=>'I3_0',
- :width=>3, :fill=>@C['fg'], :smooth=>true)
- TkcLine.new(@canvas, [650, 309, 600, 309], :tag=>'I3_1',
- :width=>3, :fill=>@C['fg'], :smooth=>true)
-
- # Pulley 1 half way to 2
- TkcLine.new(@canvas, [589, 296, 589, 235], :tag=>'I3_2',
- :width=>3, :fill=>@C['fg'])
-
- # Pulley 1 other half to 2
- TkcLine.new(@canvas, [589, 235, 589, 174], :width=>3, :fill=>@C['fg'])
-
- # Across the top
- TkcLine.new(@canvas, [577, 161, 518, 161], :width=>3, :fill=>@C['fg'])
-
- # Down to weight
- TkcLine.new(@canvas, [505, 174, 505, 205], :tag=>'I3_w',
- :width=>3, :fill=>@C['fg'])
-
- # Draw the weight as 2 circles, two rectangles and 1 rounded rectangle
- x1, y1, x2, y2 = [515, 207, 495, 207]
- TkcOval.new(@canvas, box(x1, y1, 6),
- :tag=>'I3_', :fill=>color2, :outline=>color2)
- TkcOval.new(@canvas, box(x2, y2, 6),
- :tag=>'I3_', :fill=>color2, :outline=>color2)
- TkcRectangle.new(@canvas, x1, y1 - 6, x2, y2 + 6,
- :tag=>'I3_', :fill=>color2, :outline=>color2)
-
- TkcPolygon.new(@canvas, round_rect([492, 220, 518, 263], 15),
- :smooth=>true, :tag=>'I3_', :fill=>color2, :outline=>color2)
-
- TkcLine.new(@canvas, [500, 217, 511, 217],
- :tag=>'I3_', :fill=>color2, :width=>10)
-
- # Bottom weight target
- TkcLine.new(@canvas, [502, 393, 522, 393, 522, 465],
- :tag=>'I3__', :fill=>@C['fg'], :joinstyle=>:miter, :width=>10)
- end
-
- def move3(step = nil)
- step = get_step(3, step)
-
- pos = [ [505, 247], [505, 297], [505, 386.5], [505, 386.5] ]
- rope = []
- rope[0] = [750, 309, 729, 301, 711, 324, 690, 300]
- rope[1] = [750, 309, 737, 292, 736, 335, 717, 315, 712, 320]
- rope[2] = [750, 309, 737, 309, 740, 343, 736, 351, 725, 340]
- rope[3] = [750, 309, 738, 321, 746, 345, 742, 356]
-
- return 0 if step >= pos.length
-
- @canvas.delete("I3_#{step}") # Delete part of the rope
- move_abs('I3_', pos[step]) # Move weight down
- @canvas.coords('I3_s', rope[step]) # Flapping rope end
- @canvas.coords('I3_w', [505, 174].concat(pos[step]))
- if step == 2
- @canvas.move('I3__', 0, 30)
- return 2
- end
- return 1
- end
-
- # Cage and door
- def draw4
- color = @C['4']
- x0, y0, x1, y1 = [527, 356, 611, 464]
-
- # Horizontal bars
- y0.step(y1, 12){|y|
- TkcLine.new(@canvas, [x0, y, x1, y], :fill=>color, :width=>1)
- }
-
- # Vertical bars
- x0.step(x1, 12){|x|
- TkcLine.new(@canvas, [x, y0, x, y1], :fill=>color, :width=>1)
- }
-
- # Swing gate
- TkcLine.new(@canvas, [518, 464, 518, 428],
- :tag=>'I4', :fill=>color, :width=>1)
- end
-
- def move4(step = nil)
- step = get_step(4, step)
-
- angles = [-10, -20, -30, -30]
- return 0 if step >= angles.length
-
- rotate_item('I4', 518, 464, angles[step])
- @canvas.raise('I4')
-
- return((step == 3)? 3: 1)
- end
-
- # Mouse
- def draw5
- color = @C['5a']
- color2 = @C['5b']
-
- xy = [377, 248, 410, 248, 410, 465, 518, 465] # Mouse course
- xy.concat [518, 428, 451, 428, 451, 212, 377, 212]
-
- TkcPolygon.new(@canvas, xy, :fill=>color2, :outline=>@C['fg'], :width=>3)
-
- xy = [
- 534.5, 445.5, 541, 440, 552, 436, 560, 436, 569, 440, 574, 446,
- 575, 452, 574, 454, 566, 456, 554, 456, 545, 456, 537, 454, 530, 452
- ]
- TkcPolygon.new(@canvas, xy, :tag=>['I5', 'I5_0'], :fill=>color)
-
- TkcLine.new(@canvas, [573, 452, 592, 458, 601, 460, 613, 456], # Tail
- :tag=>['I5', 'I5_1'], :fill=>color, :smooth=>true, :width=>3)
-
- xy = box(540, 446, 2) # Eye
- xy = [540, 444, 541, 445, 541, 447, 540, 448, 538, 447, 538, 445]
- TkcPolygon.new(@canvas, xy, :tag=>['I5', 'I5_2'], :fill=>@C['bg'],
- :outline=>'', :smooth=>true)
-
- xy = [538, 454, 535, 461] # Front leg
- TkcLine.new(@canvas, xy, :tag=>['I5', 'I5_3'], :fill=>color, :width=>2)
-
- xy = [566, 455, 569, 462] # Back leg
- TkcLine.new(@canvas, xy, :tag=>['I5', 'I5_4'], :fill=>color, :width=>2)
-
- xy = [544, 455, 545, 460] # 2nd front leg
- TkcLine.new(@canvas, xy, :tag=>['I5', 'I5_5'], :fill=>color, :width=>2)
-
- xy = [560, 455, 558, 460] # 2nd back leg
- TkcLine.new(@canvas, xy, :tag=>['I5', 'I5_6'], :fill=>color, :width=>2)
- end
-
- def move5(step = nil)
- step = get_step(5, step)
-
- pos = [
- [553, 452], [533, 452], [513, 452], [493, 452], [473, 452],
- [463, 442, 30], [445.5, 441.5, 30], [425.5, 434.5, 30], [422, 414],
- [422, 394], [422, 374], [422, 354], [422, 334], [422, 314], [422, 294],
- [422, 274, -30], [422, 260.5, -30, :x], [422.5, 248.5, -28], [425, 237]
- ]
-
- return 0 if step >= pos.length
-
- x, y, beta, nxt = pos[step]
- move_abs('I5', [x, y])
- if beta
- ox, oy = centroid('I5_0')
- (0..6).each{|id| rotate_item("I5_#{id}", ox, oy, beta) }
- end
- return 3 if nxt == :x
- return 1
- end
-
- # Dropping gumballs
- def draw6
- color = @C['6']
- xy = [324, 130, 391, 204] # Ball holder
- xy = round_rect(xy, 10)
- TkcPolygon.new(@canvas, xy, :smooth=>true,
- :outline=>@C['fg'], :width=>3, :fill=>color)
- xy = [339, 204, 376, 253] # Below the ball holder
- TkcRectangle.new(@canvas, xy, :outline=>@C['fg'], :width=>3,
- :fill=>color, :tag=>'I6c')
- xy = box(346, 339, 28)
- TkcOval.new(@canvas, xy, :fill=>color, :outline=>'') # Roter
- TkcArc.new(@canvas, xy, :outline=>@C['fg'], :width=>2, :style=>:arc,
- :start=>80, :extent=>205)
- TkcArc.new(@canvas, xy, :outline=>@C['fg'], :width=>2, :style=>:arc,
- :start=>-41, :extent=>85)
-
- xy = box(346, 339, 15) # Center of rotor
- TkcOval.new(@canvas, xy, :outline=>@C['fg'], :fill=>@C['fg'], :tag=>'I6m')
- xy = [352, 312, 352, 254, 368, 254, 368, 322] # Top drop to rotor
- TkcPolygon.new(@canvas, xy, :fill=>color, :outline=>'')
- TkcLine.new(@canvas, xy, :fill=>@C['fg'], :width=>2)
-
- xy = [353, 240, 367, 300] # Poke bottom hole
- TkcRectangle.new(@canvas, xy, :fill=>color, :outline=>'')
- xy = [341, 190, 375, 210] # Poke another hole
- TkcRectangle.new(@canvas, xy, :fill=>color, :outline=>'')
-
- xy = [
- 368, 356, 368, 403, 389, 403, 389, 464, 320, 464, 320, 403,
- 352, 403, 352, 366
- ]
- TkcPolygon.new(@canvas, xy, :fill=>color, :outline=>'',
- :width=>2) # Below rotor
- TkcLine.new(@canvas, xy, :fill=>@C['fg'], :width=>2)
- xy = box(275, 342, 7) # On/off rotor
- TkcOval.new(@canvas, xy, :outline=>@C['fg'], :fill=>@C['fg'])
- xy = [276, 334, 342, 325] # Fan belt top
- TkcLine.new(@canvas, xy, :fill=>@C['fg'], :width=>3)
- xy = [276, 349, 342, 353] # Fan belt bottom
- TkcLine.new(@canvas, xy, :fill=>@C['fg'], :width=>3)
-
- xy = [337, 212, 337, 247] # What the mouse pushes
- TkcLine.new(@canvas, xy, :fill=>@C['fg'], :width=>3, :tag=>'I6_')
- xy = [392, 212, 392, 247]
- TkcLine.new(@canvas, xy, :fill=>@C['fg'], :width=>3, :tag=>'I6_')
- xy = [337, 230, 392, 230]
- TkcLine.new(@canvas, xy, :fill=>@C['fg'], :width=>7, :tag=>'I6_')
-
- who = -1 # All the balls
- colors = %w(red cyan orange green blue darkblue)
- colors *= 3
-
- (0..16).each{|i|
- loc = -i
- color = colors[i]
- x, y = @XY6["#{loc}"]
- TkcOval.new(@canvas, box(x, y, 5),
- :fill=>color, :outline=>color, :tag=>"I6_b#{i}")
- }
- draw6a(12) # The wheel
- end
-
- def draw6a(beta)
- @canvas.delete('I6_0')
- ox, oy = [346, 339]
- (0..3).each{|i|
- b = beta + i * 45
- x, y = rotate_c(28, 0, 0, 0, b)
- xy = [ox + x, oy + y, ox - x, oy - y]
- TkcLine.new(@canvas, xy, :tag=>'I6_0', :fill=>@C['fg'], :width=>2)
- }
- end
-
- def move6(step = nil)
- step = get_step(6, step)
-
- return 0 if step > 62
-
- if step < 2 # Open gate for balls to drop
- @canvas.move('I6_', -7, 0)
- if step == 1 # Poke a hole
- xy = [348, 226, 365, 240]
- TkcRectangle.new(@canvas, xy, :fill=>@canvas.itemcget('I6c', :fill),
- :outline=>'')
- end
- return 1
- end
-
- s = step - 1 # Do the gumball drop dance
- (0..(((s - 1)/3).to_i)).each{|i|
- tag = "I6_b#{i}"
- break if @canvas.find_withtag(tag).empty?
- loc = s - 3*i
-
- if @XY6["#{loc},#{i}"]
- move_abs(tag, @XY6["#{loc},#{i}"])
- elsif @XY6["#{loc}"]
- move_abs(tag, @XY6["#{loc}"])
- end
- }
- if s % 3 == 1
- first = (s + 2)/3
- i = first
- loop {
- tag = "I6_b#{i}"
- break if @canvas.find_withtag(tag).empty?
- loc = first - i
- move_abs(tag, @XY6["#{loc}"])
- i += 1
- }
- end
- if s >= 3 # Rotate the motor
- idx = s % 3
- draw6a(12 + s * 15)
- end
- return((s == 3)? 3 : 1)
- end
-
- # On/off switch
- def draw7
- color = @C['7']
- xy = [198, 306, 277, 374] # Box
- TkcRectangle.new(@canvas, xy, :outline=>@C['fg'], :width=>2,
- :fill=>color, :tag=>'I7z')
- @canvas.lower('I7z')
- xy = [275, 343, 230, 349]
- TkcLine.new(@canvas, xy, :tag=>'I7', :fill=>@C['fg'], :arrow=>:last,
- :arrowshape=>[23, 23, 8], :width=>6)
- xy = [225, 324] # On button
- x, y = xy
- TkcOval.new(@canvas, box(x, y, 3), :fill=>@C['fg'], :outline=>@C['fg'])
- xy = [218, 323] # On text
- font = ['Times Roman', 8]
- TkcText.new(@canvas, xy, :text=>'on', :anchor=>:e,
- :fill=>@C['fg'], :font=>font)
- xy = [225, 350] # Off button
- x, y = xy
- TkcOval.new(@canvas, box(x, y, 3), :fill=>@C['fg'], :outline=>@C['fg'])
- xy = [218, 349] # Off text
- TkcText.new(@canvas, xy, :text=>'off', :anchor=>:e,
- :fill=>@C['fg'], :font=>font)
- end
-
- def move7(step = nil)
- step = get_step(7, step)
-
- numsteps = 30
- return 0 if step > numsteps
- beta = 30.0 / numsteps
- rotate_item('I7', 275, 343, beta)
-
- return((step == numsteps)? 3: 1)
- end
-
- # Electricity to the fan
- def draw8
- sine([271, 248, 271, 306], 5, 8, :tag=>'I8_s', :fill=>@C['8'], :width=>3)
- end
-
- def move8(step = nil)
- step = get_step(8, step)
-
- return 0 if step > 3
- if step == 0
- sparkle(anchor('I8_s', :s), 'I8')
- return 1
- elsif step == 1
- move_abs('I8', anchor('I8_s', :c))
- elsif step == 2
- move_abs('I8', anchor('I8_s', :n))
- else
- @canvas.delete('I8')
- end
- return((step == 2)? 3: 1)
- end
-
- # Fan
- def draw9
- color = @C['9']
- xy = [266, 194, 310, 220]
- TkcOval.new(@canvas, xy, :outline=>color, :fill=>color)
- xy = [280, 209, 296, 248]
- TkcOval.new(@canvas, xy, :outline=>color, :fill=>color)
- xy = [
- 288, 249, 252, 249, 260, 240, 280, 234,
- 296, 234, 316, 240, 324, 249, 288, 249
- ]
- TkcPolygon.new(@canvas, xy, :fill=>color, :smooth=>true)
-
- xy = [248, 205, 265, 214, 264, 205, 265, 196] # Spinner
- TkcPolygon.new(@canvas, xy, :fill=>color)
-
- xy = [255, 206, 265, 234] # Fan blades
- TkcOval.new(@canvas, xy, :fill=>'', :outline=>@C['fg'],
- :width=>3, :tag=>'I9_0')
- xy = [255, 176, 265, 204]
- TkcOval.new(@canvas, xy, :fill=>'', :outline=>@C['fg'],
- :width=>3, :tag=>'I9_0')
- xy = [255, 206, 265, 220]
- TkcOval.new(@canvas, xy, :fill=>'', :outline=>@C['fg'],
- :width=>1, :tag=>'I9_1')
- xy = [255, 190, 265, 204]
- TkcOval.new(@canvas, xy, :fill=>'', :outline=>@C['fg'],
- :width=>1, :tag=>'I9_1')
- end
-
- def move9(step = nil)
- step = get_step(9, step)
-
- if (step & 1).nonzero?
- @canvas.itemconfigure('I9_0', :width=>4)
- @canvas.itemconfigure('I9_1', :width=>1)
- @canvas.lower('I9_1', 'I9_0')
- else
- @canvas.itemconfigure('I9_0', :width=>1)
- @canvas.itemconfigure('I9_1', :width=>4)
- @canvas.lower('I9_0', 'I9_1')
- end
- return 3 if step == 0
- return 1
- end
-
- # Boat
- def draw10
- color = @C['10a']
- color2 = @C['10b']
- xy = [191, 230, 233, 230, 233, 178, 191, 178] # Sail
- TkcPolygon.new(@canvas, xy, :fill=>color, :width=>3, :outline=>@C['fg'],
- :tag=>'I10')
- xy = box(209, 204, 31) # Front
- TkcArc.new(@canvas, xy, :outline=>'', :fill=>color, :style=>:pie,
- :start=>120, :extent=>120, :tag=>'I10')
- TkcArc.new(@canvas, xy, :outline=>@C['fg'], :width=>3, :style=>:arc,
- :start=>120, :extent=>120, :tag=>'I10')
- xy = box(249, 204, 31) # Back
- TkcArc.new(@canvas, xy, :outline=>'', :fill=>@C['bg'], :width=>3,
- :style=>:pie, :start=>120, :extent=>120, :tag=>'I10')
- TkcArc.new(@canvas, xy, :outline=>@C['fg'], :width=>3, :style=>:arc,
- :start=>120, :extent=>120, :tag=>'I10')
-
- xy = [200, 171, 200, 249] # Mast
- TkcLine.new(@canvas, xy, :fill=>@C['fg'], :width=>3, :tag=>'I10')
- xy = [159, 234, 182, 234] # Bow sprit
- TkcLine.new(@canvas, xy, :fill=>@C['fg'], :width=>3, :tag=>'I10')
- xy = [180, 234, 180, 251, 220, 251] # Hull
- TkcLine.new(@canvas, xy, :fill=>@C['fg'], :width=>6, :tag=>'I10')
-
- xy = [92, 255, 221, 255] # Waves
- sine(xy, 2, 25, :fill=>color2, :width=>1, :tag=>'I10w')
-
- xy = @canvas.coords('I10w')[4..-5] # Water
- xy.concat([222, 266, 222, 277, 99, 277])
- TkcPolygon.new(@canvas, xy, :fill=>color2, :outline=>color2)
- xy = [222, 266, 222, 277, 97, 277, 97, 266] # Water bottom
- TkcLine.new(@canvas, xy, :fill=>@C['fg'], :width=>3)
-
- xy = box(239, 262, 17)
- TkcArc.new(@canvas, xy, :outline=>@C['fg'], :width=>3, :style=>:arc,
- :start=>95, :extent=>103)
- xy = box(76, 266, 21)
- TkcArc.new(@canvas, xy, :outline=>@C['fg'], :width=>3, :style=>:arc,
- :extent=>190)
- end
-
- def move10(step = nil)
- step = get_step(10, step)
-
- pos = [
- [195, 212], [193, 212], [190, 212], [186, 212], [181, 212], [176, 212],
- [171, 212], [166, 212], [161, 212], [156, 212], [151, 212], [147, 212],
- [142, 212], [137, 212], [132, 212, :x], [127, 212], [121, 212],
- [116, 212], [111, 212]
- ]
-
- return 0 if step >= pos.length
-
- where = pos[step]
- move_abs('I10', where)
-
- return 3 if where[2] == :x
- return 1
- end
-
- # 2nd ball drop
- def draw11
- color = @C['11a']
- color2 = @C['11b']
- xy = [23, 264, 55, 591] # Color the down tube
- TkcRectangle.new(@canvas, xy, :fill=>color, :outline=>'')
- xy = box(71, 460, 48) # Color the outer loop
- TkcOval.new(@canvas, xy, :fill=>color, :outline=>'')
-
- xy = [55, 264, 55, 458] # Top right side
- TkcLine.new(@canvas, xy, :fill=>@C['fg'], :width=>3)
- xy = [55, 504, 55, 591] # Bottom right side
- TkcLine.new(@canvas, xy, :fill=>@C['fg'], :width=>3)
- xy = box(71, 460, 48) # Outer loop
- TkcArc.new(@canvas, xy, :outline=>@C['fg'], :width=>3, :style=>:arc,
- :start=>110, :extent=>-290, :tag=>'I11i')
- xy = box(71, 460, 16) # Inner loop
- TkcOval.new(@canvas, xy, :outline=>@C['fg'], :fill=>'',
- :width=>3, :tag=>'I11i')
- TkcOval.new(@canvas, xy, :outline=>@C['fg'], :fill=>@C['bg'], :width=>3)
-
- xy = [23, 264, 23, 591] # Left side
- TkcLine.new(@canvas, xy, :fill=>@C['fg'], :width=>3)
- xy = box(1, 266, 23) # Top left curve
- TkcArc.new(@canvas, xy, :outline=>@C['fg'], :width=>3,
- :style=>:arc, :extent=>90)
-
- xy = box(75, 235, 9) # The ball
- TkcOval.new(@canvas, xy, :fill=>color2, :outline=>'',
- :width=>3, :tag=>'I11')
- end
-
- def move11(step = nil)
- step = get_step(11, step)
-
- pos = [
- [75, 235], [70, 235], [65, 237], [56, 240], [46, 247], [38, 266],
- [38, 296], [38, 333], [38, 399], [38, 475], [74, 496], [105, 472],
- [100, 437], [65, 423], [-100, -100], [38, 505], [38, 527, :x], [38, 591]
- ]
-
- return 0 if step >= pos.length
- where = pos[step]
- move_abs('I11', where)
- return 3 if where[2] == :x
- return 1
- end
-
- # Hand
- def draw12
- xy = [
- 20, 637, 20, 617, 20, 610, 20, 590, 40, 590, 40, 590,
- 60, 590, 60, 610, 60, 610
- ]
- xy.concat([60, 610, 65, 620, 60, 631]) # Thumb
- xy.concat([60, 631, 60, 637, 60, 662, 60, 669, 52, 669,
- 56, 669, 50, 669, 50, 662, 50, 637])
-
- y0 = 637 # Bumps for fingers
- y1 = 645
- 50.step(21, -10){|x|
- x1 = x - 5
- x2 = x - 10
- xy << x << y0 << x1 << y1 << x2 << y0
- }
- TkcPolygon.new(@canvas, xy, :fill=>@C['12'], :outline=>@C['fg'],
- :smooth=>true, :tag=>'I12', :width=>3)
- end
-
- def move12(step = nil)
- step = get_step(12, step)
-
- pos = [[42.5, 641, :x]]
- return 0 if step >= pos.length
- where = pos[step]
- move_abs('I12', where)
- return 3 if where[2] == :x
- return 1
- end
-
- # Fax
- def draw13
- color = @C['13a']
- xy = [86, 663, 149, 663, 149, 704, 50, 704, 50, 681, 64, 681, 86, 671]
- xy2 = [
- 784, 663, 721, 663, 721, 704, 820, 704, 820, 681, 806, 681, 784, 671
- ]
- radii = [2, 9, 9, 8, 5, 5, 2]
-
- round_poly(@canvas, xy, radii, :width=>3,
- :outline=>@C['fg'], :fill=>color)
- round_poly(@canvas, xy2, radii, :width=>3,
- :outline=>@C['fg'], :fill=>color)
-
- xy = [56, 677]
- x, y = xy
- TkcRectangle.new(@canvas, box(x, y, 4), :fill=>'', :outline=>@C['fg'],
- :width=>3, :tag=>'I13')
- xy = [809, 677]
- x, y = xy
- TkcRectangle.new(@canvas, box(x, y, 4), :fill=>'', :outline=>@C['fg'],
- :width=>3, :tag=>'I13R')
-
- xy = [112, 687] # Label
- TkcText.new(@canvas, xy, :text=>'FAX', :fill=>@C['fg'],
- :font=>['Times Roman', 12, :bold])
- xy = [762, 687]
- TkcText.new(@canvas, xy, :text=>'FAX', :fill=>@C['fg'],
- :font=>['Times Roman', 12, :bold])
-
- xy = [138, 663, 148, 636, 178, 636] # Paper guide
- TkcLine.new(@canvas, xy, :smooth=>true, :fill=>@C['fg'], :width=>3)
- xy = [732, 663, 722, 636, 692, 636]
- TkcLine.new(@canvas, xy, :smooth=>true, :fill=>@C['fg'], :width=>3)
-
- sine([149, 688, 720, 688], 5, 15,
- :tag=>'I13_s', :fill=>@C['fg'], :width=>3)
- end
-
- def move13(step = nil)
- step = get_step(13, step)
-
- numsteps = 7
-
- if step == numsteps + 2
- move_abs('I13_star', [-100, -100])
- @canvas.itemconfigure('I13R', :fill=>@C['13b'], :width=>2)
- return 2
- end
- if step == 0 # Button down
- @canvas.delete('I13')
- sparkle([-100, -100], 'I13_star') # Create off screen
- return 1
- end
- x0, y0 = anchor('I13_s', :w)
- x1, y1 = anchor('I13_s', :e)
- x = x0 + (x1 - x0) * (step - 1) / numsteps.to_f
- move_abs('I13_star', [x, y0])
- return 1
- end
-
- # Paper in fax
- def draw14
- color = @C['14']
- xy = [102, 661, 113, 632, 130, 618] # Left paper edge
- TkcLine.new(@canvas, xy, :smooth=>true, :fill=>color,
- :width=>3, :tag=>'I14L_0')
- xy = [148, 629, 125, 640, 124, 662] # Right paper edge
- TkcLine.new(@canvas, xy, :smooth=>true, :fill=>color,
- :width=>3, :tag=>'I14L_1')
- draw14a('L')
-
- xy = [
- 768.0, 662.5, 767.991316225, 662.433786215, 767.926187912, 662.396880171
- ]
- TkcLine.new(@canvas, xy, :smooth=>true, :fill=>color,
- :width=>3, :tag=>'I14R_0')
- @canvas.lower('I14R_0')
- # NB. these numbers are VERY sensitive, you must start with final size
- # and shrink down to get the values
- xy = [
- 745.947897349, 662.428358855, 745.997829056, 662.452239237, 746.0, 662.5
- ]
- TkcLine.new(@canvas, xy, :smooth=>true, :fill=>color,
- :width=>3, :tag=>'I14R_1')
- @canvas.lower('I14R_1')
- end
-
- def draw14a(side)
- color = @C['14']
- xy = @canvas.coords("I14#{side}_0")
- xy2 = @canvas.coords("I14#{side}_1")
- x0, y0, x1, y1, x2, y2 = xy
- x3, y3, x4, y4, x5, y5 = xy2
-
- zz = [
- x0, y0, x0, y0, xy, x2, y2, x2, y2,
- x3, y3, x3, y3, xy2, x5, y5, x5, y5
- ].flatten
- @canvas.delete("I14#{side}")
- TkcPolygon.new(@canvas, zz, :tag=>"I14#{side}", :smooth=>true,
- :fill=>color, :outline=>color, :width=>3)
- @canvas.lower("I14#{side}")
- end
-
- def move14(step = nil)
- step = get_step(14, step)
-
- # Paper going down
- sc = 0.9 - 0.05*step
- if sc < 0.3
- @canvas.delete('I14L')
- return 0
- end
-
- ox, oy = @canvas.coords('I14L_0')
- @canvas.scale('I14L_0', ox, oy, sc, sc)
- ox, oy = @canvas.coords('I14L_1')[-2..-1]
- @canvas.scale('I14L_1', ox, oy, sc, sc)
- draw14a('L')
-
- # Paper going up
- sc = 0.35 + 0.05*step
- sc = 1/sc
-
- ox, oy = @canvas.coords('I14R_0')
- @canvas.scale('I14R_0', ox, oy, sc, sc)
- ox, oy = @canvas.coords('I14R_1')[-2..-1]
- @canvas.scale('I14R_1', ox, oy, sc, sc)
- draw14a('R')
-
- return((step == 10)? 3: 1)
- end
-
- # Light beam
- def draw15
- color = @C['15a']
- xy = [824, 599, 824, 585, 820, 585, 829, 585]
- TkcLine.new(@canvas, xy, :fill=>@C['fg'], :width=>3, :tag=>'I15a')
- xy = [789, 599, 836, 643]
- TkcRectangle.new(@canvas, xy, :fill=>color, :outline=>@C['fg'], :width=>3)
- xy = [778, 610, 788, 632]
- TkcRectangle.new(@canvas, xy, :fill=>color, :outline=>@C['fg'], :width=>3)
- xy = [766, 617, 776, 625]
- TkcRectangle.new(@canvas, xy, :fill=>color, :outline=>@C['fg'], :width=>3)
-
- xy = [633, 600, 681, 640]
- TkcRectangle.new(@canvas, xy, :fill=>color, :outline=>@C['fg'], :width=>3)
- xy = [635, 567, 657, 599]
- TkcRectangle.new(@canvas, xy, :fill=>color, :outline=>@C['fg'], :width=>2)
- xy = [765, 557, 784, 583]
- TkcRectangle.new(@canvas, xy, :fill=>color, :outline=>@C['fg'], :width=>2)
-
- sine([658, 580, 765, 580], 3, 15,
- :tag=>'I15_s', :fill=>@C['fg'], :width=>3)
- end
-
- def move15a
- color = @C['15b']
- @canvas.scale('I15a', 824, 599, 1, 0.3) # Button down
- xy = [765, 621, 681, 621]
- TkcLine.new(@canvas, xy, :dash=>'-', :width=>3, :fill=>color, :tag=>'I15')
- end
-
- def move15(step = nil)
- step = get_step(15, step)
-
- numsteps = 6
-
- if step == numsteps + 2
- move_abs('I15_star', [-100, -100])
- return 2
- end
- if step == 0 # Break the light beam
- sparkle([-100, -100], 'I15_star')
- xy = [765, 621, 745, 621]
- @canvas.coords('I15', xy)
- return 1
- end
- x0, y0 = anchor('I15_s', :w)
- x1, y1 = anchor('I15_s', :e)
- x = x0 + (x1 - x0) * (step - 1) / numsteps.to_f
- move_abs('I15_star', [x, y0])
- return 1
- end
-
- # Bell
- def draw16
- color = @C['16']
- xy = [722, 485, 791, 556]
- TkcRectangle.new(@canvas, xy, :fill=>'', :outline=>@C['fg'], :width=>3)
- xy = box(752, 515, 25) # Bell
- TkcOval.new(@canvas, xy, :fill=>color, :outline=>'black',
- :tag=>'I16b', :width=>2)
- xy = box(752, 515, 5) # Bell button
- TkcOval.new(@canvas, xy, :fill=>'black', :outline=>'black', :tag=>'I16b')
-
- xy = [784, 523, 764, 549] # Clapper
- TkcLine.new(@canvas, xy, :width=>3, :tag=>'I16c', :fill=>@C['fg'])
- xy = box(784, 523, 4)
- TkcOval.new(@canvas, xy, :fill=>@C['fg'], :outline=>@C['fg'], :tag=>'I16d')
- end
-
- def move16(step = nil)
- step = get_step(16, step)
-
- # Note: we never stop
- ox, oy = [760, 553]
- if (step & 1).nonzero?
- beta = 12
- @canvas.move('I16b', 3, 0)
- else
- beta = -12
- @canvas.move('I16b', -3, 0)
- end
- rotate_item('I16c', ox, oy, beta)
- rotate_item('I16d', ox, oy, beta)
-
- return ((step == 1)? 3: 1)
- end
-
- # Cat
- def draw17
- color = @C['17']
-
- xy = [584, 556, 722, 556]
- TkcLine.new(@canvas, xy, :fill=>@C['fg'], :width=>3)
- xy = [584, 485, 722, 485]
- TkcLine.new(@canvas, xy, :fill=>@C['fg'], :width=>3)
-
- xy = [664, 523, 717, 549] # Body
- TkcArc.new(@canvas, xy, :outline=>@C['fg'], :fill=>color, :width=>3,
- :style=>:chord, :start=>128, :extent=>260, :tag=>'I17')
-
- xy = [709, 554, 690, 543] # Paw
- TkcOval.new(@canvas, xy, :outline=>@C['fg'], :fill=>color,
- :width=>3, :tag=>'I17')
- xy = [657, 544, 676, 555]
- TkcOval.new(@canvas, xy, :outline=>@C['fg'], :fill=>color,
- :width=>3, :tag=>'I17')
-
- xy = box(660, 535, 15) # Lower face
- TkcArc.new(@canvas, xy, :outline=>@C['fg'], :width=>3, :style=>:arc,
- :start=>150, :extent=>240, :tag=>'I17_')
- TkcArc.new(@canvas, xy, :outline=>'', :fill=>color, :width=>1,
- :style=>:chord, :start=>150, :extent=>240, :tag=>'I17_')
- xy = [674, 529, 670, 513, 662, 521, 658, 521, 650, 513, 647, 529] # Ears
- TkcLine.new(@canvas, xy, :fill=>@C['fg'], :width=>3, :tag=>'I17_')
- TkcPolygon.new(@canvas, xy, :fill=>color, :outline=>'', :width=>1,
- :tag=>['I17_', 'I17_c'])
- xy = [652, 542, 628, 539] # Whiskers
- TkcLine.new(@canvas, xy, :fill=>@C['fg'], :width=>3, :tag=>'I17_')
- xy = [652, 543, 632, 545]
- TkcLine.new(@canvas, xy, :fill=>@C['fg'], :width=>3, :tag=>'I17_')
- xy = [652, 546, 632, 552]
- TkcLine.new(@canvas, xy, :fill=>@C['fg'], :width=>3, :tag=>'I17_')
-
- xy = [668, 543, 687, 538]
- TkcLine.new(@canvas, xy, :fill=>@C['fg'], :width=>3,
- :tag=>['I17_', 'I17_w'])
- xy = [668, 544, 688, 546]
- TkcLine.new(@canvas, xy, :fill=>@C['fg'], :width=>3,
- :tag=>['I17_', 'I17_w'])
- xy = [668, 547, 688, 553]
- TkcLine.new(@canvas, xy, :fill=>@C['fg'], :width=>3,
- :tag=>['I17_', 'I17_w'])
-
- xy = [649, 530, 654, 538, 659, 530] # Left eye
- TkcLine.new(@canvas, xy, :fill=>@C['fg'], :width=>2,
- :smooth=>true, :tag=>'I17')
- xy = [671, 530, 666, 538, 661, 530] # Right eye
- TkcLine.new(@canvas, xy, :fill=>@C['fg'], :width=>2,
- :smooth=>true, :tag=>'I17')
- xy = [655, 543, 660, 551, 665, 543] # Mouth
- TkcLine.new(@canvas, xy, :fill=>@C['fg'], :width=>2,
- :smooth=>true, :tag=>'I17')
- end
-
- def move17(step = nil)
- step = get_step(17, step)
-
- if step == 0
- @canvas.delete('I17') # Delete most of the cat
- xy = [655, 543, 660, 535, 665, 543] # Mouth
- TkcLine.new(@canvas, xy, :fill=>@C['fg'], :width=>3,
- :smooth=>true, :tag=>'I17_')
- xy = box(654, 530, 4) # Left eye
- TkcOval.new(@canvas, xy, :outline=>@C['fg'], :width=>3, :fill=>'',
- :tag=>'I17_')
- xy = box(666, 530, 4) # Right eye
- TkcOval.new(@canvas, xy, :outline=>@C['fg'], :width=>3, :fill=>'',
- :tag=>'I17_')
-
- @canvas.move('I17_', 0, -20) # Move face up
- xy = [652, 528, 652, 554] # Front leg
- TkcLine.new(@canvas, xy, :fill=>@C['fg'], :width=>3, :tag=>'I17_')
- xy = [670, 528, 670, 554] # 2nd front leg
- TkcLine.new(@canvas, xy, :fill=>@C['fg'], :width=>3, :tag=>'I17_')
-
- xy = [ # Body
- 675, 506, 694, 489, 715, 513, 715, 513, 715, 513, 716, 525,
- 716, 525, 716, 525, 706, 530, 695, 530, 679, 535, 668, 527,
- 668, 527, 668, 527, 675, 522, 676, 517, 677, 512
- ]
- TkcPolygon.new(@canvas, xy, :fill=>@canvas.itemcget('I17_c', :fill),
- :outline=>@C['fg'], :width=>3, :smooth=>true,
- :tag=>'I17_')
- xy = [716, 514, 716, 554] # Back leg
- TkcLine.new(@canvas, xy, :fill=>@C['fg'], :width=>3, :tag=>'I17_')
- xy = [694, 532, 694, 554] # 2nd back leg
- TkcLine.new(@canvas, xy, :fill=>@C['fg'], :width=>3, :tag=>'I17_')
- xy = [715, 514, 718, 506, 719, 495, 716, 488] # Tail
- TkcLine.new(@canvas, xy, :fill=>@C['fg'], :width=>3,
- :smooth=>true, :tag=>'I17_')
-
- @canvas.raise('I17w') # Make whiskers visible
- @canvas.move('I17_', -5, 0) # Move away from the wall a bit
- return 2
- end
- return 0
- end
-
- # Sling shot
- def draw18
- color = @C['18']
- xy = [721, 506, 627, 506] # Sling hold
- TkcLine.new(@canvas, xy, :width=>4, :fill=>@C['fg'], :tag=>'I18')
-
- xy = [607, 500, 628, 513] # Sling rock
- TkcOval.new(@canvas, xy, :fill=>color, :outline=>'', :tag=>'I18a')
-
- xy = [526, 513, 606, 507, 494, 502] # Sling band
- TkcLine.new(@canvas, xy, :fill=>@C['fg'], :width=>4, :tag=>'I18b')
- xy = [485, 490, 510, 540, 510, 575, 510, 540, 535, 491] # Sling
- TkcLine.new(@canvas, xy, :fill=>@C['fg'], :width=>6)
- end
-
- def move18(step = nil)
- step = get_step(18, step)
-
- pos = [
- [587, 506], [537, 506], [466, 506], [376, 506], [266, 506, :x],
- [136, 506], [16, 506], [-100, -100]
- ]
-
- b = []
- b[0] = [490, 502, 719, 507, 524, 512] # Band collapsing
- b[1] = [
- 491, 503, 524, 557, 563, 505, 559, 496, 546, 506, 551, 525,
- 553, 536, 538, 534, 532, 519, 529, 499
- ]
- b[2] = [
- 491, 503, 508, 563, 542, 533, 551, 526, 561, 539, 549, 550, 530, 500
- ]
- b[3] = [
- 491, 503, 508, 563, 530, 554, 541, 562, 525, 568, 519, 544, 530, 501
- ]
-
- return 0 if step >= pos.length
-
- if step == 0
- @canvas.delete('I18')
- @canvas.itemconfigure('I18b', :smooth=>true)
- end
- if b[step]
- @canvas.coords('I18b', b[step])
- end
-
- where = pos[step]
- move_abs('I18a', where)
- return 3 if where[2] == :x
- return 1
- end
-
- # Water pipe
- def draw19
- color = @C['19']
- xx = [[249, 181], [155, 118], [86, 55], [22, 0]]
- xx.each{|x1, x2|
- TkcRectangle.new(@canvas, x1, 453, x2, 467,
- :fill=>color, :outline=>'', :tag=>'I19')
- TkcLine.new(@canvas, x1, 453, x2, 453,
- :fill=>@C['fg'], :width=>1) # Pipe top
- TkcLine.new(@canvas, x1, 467, x2, 467,
- :fill=>@C['fg'], :width=>1) # Pipe bottom
- }
- @canvas.raise('I11i')
-
- xy = box(168, 460, 16) # Bulge by the joint
- TkcOval.new(@canvas, xy, :fill=>color, :outline=>'')
- TkcArc.new(@canvas, xy, :outline=>@C['fg'], :width=>1, :style=>:arc,
- :start=>21, :extent=>136)
- TkcArc.new(@canvas, xy, :outline=>@C['fg'], :width=>1, :style=>:arc,
- :start=>-21, :extent=>-130)
-
- xy = [249, 447, 255, 473] # First joint 26x6
- TkcRectangle.new(@canvas, xy, :fill=>color, :outline=>@C['fg'], :width=>1)
-
- xy = box(257, 433, 34) # Bend up
- TkcArc.new(@canvas, xy, :outline=>'', :fill=>color, :width=>1,
- :style=>:pie, :start=>0, :extent=>-91)
- TkcArc.new(@canvas, xy, :outline=>@C['fg'], :width=>1,
- :style=>:arc, :start=>0, :extent=>-90)
- xy = box(257, 433, 20)
- TkcArc.new(@canvas, xy, :outline=>'', :fill=>@C['bg'], :width=>1,
- :style=>:pie, :start=>0, :extent=>-92)
- TkcArc.new(@canvas, xy, :outline=>@C['fg'], :width=>1,
- :style=>:arc, :start=>0, :extent=>-90)
- xy = box(257, 421, 34) # Bend left
- TkcArc.new(@canvas, xy, :outline=>'', :fill=>color, :width=>1,
- :style=>:pie, :start=>0, :extent=>91)
- TkcArc.new(@canvas, xy, :outline=>@C['fg'], :width=>1,
- :style=>:arc, :start=>0, :extent=>90)
- xy = box(257, 421, 20)
- TkcArc.new(@canvas, xy, :outline=>'', :fill=>@C['bg'], :width=>1,
- :style=>:pie, :start=>0, :extent=>90)
- TkcArc.new(@canvas, xy, :outline=>@C['fg'], :width=>1,
- :style=>:arc, :start=>0, :extent=>90)
- xy = box(243, 421, 34) # Bend down
- TkcArc.new(@canvas, xy, :outline=>'', :fill=>color, :width=>1,
- :style=>:pie, :start=>90, :extent=>90)
- TkcArc.new(@canvas, xy, :outline=>@C['fg'], :width=>1,
- :style=>:arc, :start=>90, :extent=>90)
- xy = box(243, 421, 20)
- TkcArc.new(@canvas, xy, :outline=>'', :fill=>@C['bg'], :width=>1,
- :style=>:pie, :start=>90, :extent=>90)
- TkcArc.new(@canvas, xy, :outline=>@C['fg'], :width=>1,
- :style=>:arc, :start=>90, :extent=>90)
-
- xy = [270, 427, 296, 433] # 2nd joint bottom
- TkcRectangle.new(@canvas, xy, :fill=>color, :outline=>@C['fg'], :width=>1)
- xy = [270, 421, 296, 427] # 2nd joint top
- TkcRectangle.new(@canvas, xy, :fill=>color, :outline=>@C['fg'], :width=>1)
- xy = [249, 382, 255, 408] # Third joint right
- TkcRectangle.new(@canvas, xy, :fill=>color, :outline=>@C['fg'], :width=>1)
- xy = [243, 382, 249, 408] # Third joint left
- TkcRectangle.new(@canvas, xy, :fill=>color, :outline=>@C['fg'], :width=>1)
- xy = [203, 420, 229, 426] # Last joint
- TkcRectangle.new(@canvas, xy, :fill=>color, :outline=>@C['fg'], :width=>1)
-
- xy = box(168, 460, 6) # Handle joint
- TkcOval.new(@canvas, xy, :fill=>@C['fg'], :outline=>'', :tag=>'I19a')
- xy = [168, 460, 168, 512] # Handle bar
- TkcLine.new(@canvas, xy, :fill=>@C['fg'], :width=>5, :tag=>'I19b')
- end
-
- def move19(step = nil)
- step = get_step(19, step)
-
- angles = [30, 30, 30]
- return 2 if step == angles.length
- ox, oy = centroid('I19a')
- rotate_item('I19b', ox, oy, angles[step])
-
- return 1
- end
-
- # Water pouring
- def draw20
- # do nothing
- end
-
- def move20(step = nil)
- step = get_step(20, step)
-
- pos = [451, 462, 473, 484, 496, 504, 513, 523, 532]
- freq = [20, 40, 40, 40, 40, 40, 40, 40, 40]
- pos = [
- [451, 20], [462, 40], [473, 40], [484, 40], [496, 40],
- [504, 40], [513, 40], [523, 40], [532, 40, :x]
- ]
- return 0 if step >= pos.length
-
- @canvas.delete('I20')
- where = pos[step]
- y, f = where
- h20(y, f)
- return 3 if where[2] == :x
- return 1
- end
-
- def h20(y, f)
- color = @C['20']
- @canvas.delete('I20')
-
- sine([208, 428, 208, y], 4, f, :tag=>['I20', 'I20s'],
- :width=>3, :fill=>color, :smooth=>true)
- TkcLine.new(@canvas, @canvas.coords('I20s'), :width=>3,
- :fill=>color, :smooth=>1, :tag=>['I20', 'I20a'])
- TkcLine.new(@canvas, @canvas.coords('I20s'), :width=>3,
- :fill=>color, :smooth=>1, :tag=>['I20', 'I20b'])
- @canvas.move('I20a', 8, 0)
- @canvas.move('I20b', 16, 0)
- end
-
- # Bucket
- def draw21
- color = @C['21']
- xy = [217, 451, 244, 490] # Right handle
- TkcLine.new(@canvas, xy, :fill=>@C['fg'], :width=>2, :tag=>'I21_a')
- xy = [201, 467, 182, 490] # Left handle
- TkcLine.new(@canvas, xy, :fill=>@C['fg'], :width=>2, :tag=>'I21_a')
-
- xy = [245, 490, 237, 535] # Right side
- xy2 = [189, 535, 181, 490] # Left side
- TkcPolygon.new(@canvas, xy + xy2, :fill=>color, :outline=>'',
- :tag=>['I21', 'I21f'])
- TkcLine.new(@canvas, xy, :fill=>@C['fg'], :width=>2, :tag=>'I21')
- TkcLine.new(@canvas, xy2, :fill=>@C['fg'], :width=>2, :tag=>'I21')
-
- xy = [182, 486, 244, 498] # Top
- TkcOval.new(@canvas, xy, :fill=>color, :outline=>'', :width=>2,
- :tag=>['I21', 'I21f'])
- TkcOval.new(@canvas, xy, :fill=>'', :outline=>@C['fg'], :width=>2,
- :tag=>['I21', 'I21t'])
- xy = [189, 532, 237, 540] # Bottom
- TkcOval.new(@canvas, xy, :fill=>color, :outline=>@C['fg'], :width=>2,
- :tag=>['I21', 'I21b'])
- end
-
- def move21(step = nil)
- step = get_step(21, step)
-
- numsteps = 30
- return 0 if step >= numsteps
-
- x1, y1, x2, y2 = @canvas.coords('I21b')
- # lx1, ly1, lx2, ly2 = @canvas.coords('I21t')
- lx1, ly1, lx2, ly2 = [183, 492, 243, 504]
-
- f = step / numsteps.to_f
- y2 = y2 - 3
- xx1 = x1 + (lx1 - x1) * f
- yy1 = y1 + (ly1 - y1) * f
- xx2 = x2 + (lx2 - x2) * f
- yy2 = y2 + (ly2 - y2) * f
-
- @canvas.itemconfigure('I21b', :fill=>@C['20'])
- @canvas.delete('I21w')
- TkcPolygon.new(@canvas, x2, y2, x1, y1, xx1, yy1, xx2, yy1,
- :tag=>['I21', 'I21w'], :outline=>'', :fill=>@C['20'])
- @canvas.lower('I21w', 'I21')
- @canvas.raise('I21b')
- @canvas.lower('I21f')
-
- return((step == numsteps - 1)? 3: 1)
- end
-
- # Bucket drop
- def draw22
- # do nothing
- end
-
- def move22(step = nil)
- step = get_step(22, step)
- pos = [[213, 513], [213, 523], [213, 543, :x], [213, 583], [213, 593]]
-
- @canvas.itemconfigure('I21f', :fill=>@C['22']) if step == 0
- return 0 if step >= pos.length
- where = pos[step]
- move_abs('I21', where)
- h20(where[1], 40)
- @canvas.delete('I21_a') # Delete handles
-
- return 3 if where[2] == :x
- return 1
- end
-
- # Blow dart
- def draw23
- color = @C['23a']
- color2 = @C['23b']
- color3 = @C['23c']
-
- xy = [185, 623, 253, 650] # Block
- TkcRectangle.new(@canvas, xy, :fill=>'black', :outline=>@C['fg'],
- :width=>2, :tag=>'I23a')
- xy = [187, 592, 241, 623] # Balloon
- TkcOval.new(@canvas, xy, :outline=>'', :fill=>color, :tag=>'I23b')
- TkcArc.new(@canvas, xy, :outline=>@C['fg'], :width=>3, :tag=>'I23b',
- :style=>:arc, :start=>12, :extent=>336)
- xy = [239, 604, 258, 589, 258, 625, 239, 610] # Balloon nozzle
- TkcPolygon.new(@canvas, xy, :outline=>'', :fill=>color, :tag=>'I23b')
- TkcLine.new(@canvas, xy, :fill=>@C['fg'], :width=>3, :tag=>'I23b')
-
- xy = [285, 611, 250, 603] # Dart body
- TkcOval.new(@canvas, xy, :fill=>color2, :outline=>@C['fg'],
- :width=>3, :tag=>'I23d')
- xy = [249, 596, 249, 618, 264, 607, 249, 596] # Dart tail
- TkcPolygon.new(@canvas, xy, :fill=>color3, :outline=>@C['fg'],
- :width=>3, :tag=>'I23d')
- xy = [249, 607, 268, 607] # Dart detail
- TkcLine.new(@canvas, xy, :fill=>@C['fg'], :width=>3, :tag=>'I23d')
- xy = [285, 607, 305, 607] # Dart needle
- TkcLine.new(@canvas, xy, :fill=>@C['fg'], :width=>3, :tag=>'I23d')
- end
-
- def move23(step = nil)
- step = get_step(23, step)
-
- pos = [
- [277, 607], [287, 607], [307, 607, :x], [347, 607], [407, 607],
- [487, 607], [587, 607], [687, 607], [787, 607], [-100, -100]
- ]
-
- return 0 if step >= pos.length
- if step <= 1
- ox, oy = anchor('I23a', :n)
- @canvas.scale('I23b', ox, oy, 0.9, 0.5)
- end
- where = pos[step]
- move_abs('I23d', where)
-
- return 3 if where[2] == :x
- return 1
- end
-
- # Balloon
- def draw24
- color = @C['24a']
- xy = [366, 518, 462, 665] # Balloon
- TkcOval.new(@canvas, xy, :fill=>color, :outline=>@C['fg'],
- :width=>3, :tag=>'I24')
- xy = [414, 666, 414, 729] # String
- TkcLine.new(@canvas, xy, :fill=>@C['fg'], :width=>3, :tag=>'I24')
- xy = [410, 666, 404, 673, 422, 673, 418, 666] # Nozzle
- TkcPolygon.new(@canvas, xy, :fill=>color, :outline=>@C['fg'],
- :width=>3, :tag=>'I24')
-
- xy = [387, 567, 390, 549, 404, 542] # Reflections
- TkcLine.new(@canvas, xy, :fill=>@C['fg'], :smooth=>true,
- :width=>2, :tag=>'I24')
- xy = [395, 568, 399, 554, 413, 547]
- TkcLine.new(@canvas, xy, :fill=>@C['fg'], :smooth=>true,
- :width=>2, :tag=>'I24')
- xy = [403, 570, 396, 555, 381, 553]
- TkcLine.new(@canvas, xy, :fill=>@C['fg'], :smooth=>true,
- :width=>2, :tag=>'I24')
- xy = [408, 564, 402, 547, 386, 545]
- TkcLine.new(@canvas, xy, :fill=>@C['fg'], :smooth=>true,
- :width=>2, :tag=>'I24')
- end
-
- def move24(step = nil)
- step = get_step(24, step)
-
- return 0 if step > 4
- return 2 if step == 4
-
- if step == 0
- @canvas.delete('I24') # Exploding balloon
- xy = [
- 347, 465, 361, 557, 271, 503, 272, 503, 342, 574, 259, 594,
- 259, 593, 362, 626, 320, 737, 320, 740, 398, 691, 436, 738,
- 436, 739, 476, 679, 528, 701, 527, 702, 494, 627, 548, 613,
- 548, 613, 480, 574, 577, 473, 577, 473, 474, 538, 445, 508,
- 431, 441, 431, 440, 400, 502, 347, 465, 347, 465
- ]
- TkcPolygon.new(@canvas, xy, :tag=>'I24', :fill=>@C['24b'],
- :outline=>@C['24a'], :width=>10, :smooth=>true)
- msg = Tk.subst(@S['message'].value)
- TkcText.new(@canvas, centroid('I24'), :text=>msg, :tag=>['I24', 'I24t'],
- :justify=>:center, :font=>['Times Roman', 18, :bold])
- return 1
- end
-
- @canvas.itemconfigure('I24t', :font=>['Times Roman', 18 + 6*step, :bold])
- @canvas.move('I24', 0, -60)
- ox, oy = centroid('I24')
- @canvas.scale('I24', ox, oy, 1.25, 1.25)
- return 1
- end
-
- # Displaying the message
- def move25(step = nil)
- step = get_step(25, step)
-
- if step == 0
- @XY['25'] = Tk::Clock.clicks(:miliseconds)
- return 1
- end
- elapsed = Tk::Clock.clicks(:miliseconds) - @XY['25']
- return 1 if elapsed < 5000
- return 2
- end
-
- # Collapsing balloon
- def move26(step = nil)
- step = get_step(26, step)
-
- if step >= 3
- @canvas.delete('I24', 'I26')
- TkcText.new(@canvas, 430, 740, :anchor=>:s, :tag=>'I26',
- :text=>'click to continue',
- :font=>['Times Roman', 24, :bold])
- @canvas.bind('1', proc{reset})
- return 4
- end
-
- ox, oy = centroid('I24')
- @canvas.scale('I24', ox, oy, 0.8, 0.8)
- @canvas.move('I24', 0, 60)
- @canvas.itemconfigure('I24t', :font=>['Times Roman', 30 - 6*step, :bold])
- return 1
- end
-
- ################################################################
- #
- # Helper functions
- #
- def box(x, y, r)
- [x - r, y - r, x + r, y + r]
- end
-
- def move_abs(item, xy)
- x, y = xy
- ox, oy = centroid(item)
- dx = x - ox
- dy = y - oy
- @canvas.move(item, dx, dy)
- end
-
- def rotate_item(item, ox, oy, beta)
- xy = @canvas.coords(item)
- xy2 = []
- 0.step(xy.length - 1, 2){|idx|
- x, y = xy[idx, 2]
- xy2.concat(rotate_c(x, y, ox, oy, beta))
- }
- @canvas.coords(item, xy2)
- end
-
- def rotate_c(x, y, ox, oy, beta)
- # rotates vector (ox,oy)->(x,y) by beta degrees clockwise
-
- x -= ox # Shift to origin
- y -= oy
-
- beta = beta * Math.atan(1) * 4 / 180.0 # Radians
- xx = x * Math.cos(beta) - y * Math.sin(beta) # Rotate
- yy = x * Math.sin(beta) + y * Math.cos(beta)
-
- xx += ox # Shift back
- yy += oy
-
- [xx, yy]
- end
-
- def reset
- draw_all
- @canvas.bind_remove('1')
- @S['mode'].value = :MSTART
- @S['active'] = [0]
- end
-
- # Each Move## keeps its state info in STEP, this retrieves and increments it
- def get_step(who, step)
- if step
- @STEP[who] = step
- else
- if !@STEP.exist?(who) || @STEP[who] == ""
- @STEP[who] = 0
- else
- @STEP[who] += 1
- end
- end
- @STEP[who]
- end
-
- def reset_step
- @S['cnt'].value = 0
- @STEP.keys.each{|k| @STEP[k] = ''}
- end
-
- def sine(xy0, amp, freq, opts = {})
- x0, y0, x1, y1 = xy0
- step = 2
- xy = []
- if y0 == y1 # Horizontal
- x0.step(x1, step){|x|
- beta = (x - x0) * 2 * Math::PI / freq
- y = y0 + amp * Math.sin(beta)
- xy << x << y
- }
- else
- y0.step(y1, step){|y|
- beta = (y - y0) * 2 * Math::PI / freq
- x = x0 + amp * Math.sin(beta)
- xy << x << y
- }
- end
- TkcLine.new(@canvas, xy, opts)
- end
-
- def round_rect(xy, radius, opts={})
- x0, y0, x3, y3 = xy
- r = @canvas.winfo_pixels(radius)
- d = 2 * r
-
- # Make sure that the radius of the curve is less than 3/8 size of the box!
- maxr = 0.75
- if d > maxr * (x3 - x0)
- d = maxr * (x3 - x0)
- end
- if d > maxr * (y3 - y0)
- d = maxr * (y3 - y0)
- end
-
- x1 = x0 + d
- x2 = x3 - d
- y1 = y0 + d
- y2 = y3 - d
-
- xy = [x0, y0, x1, y0, x2, y0, x3, y0, x3, y1, x3, y2]
- xy.concat([x3, y3, x2, y3, x1, y3, x0, y3, x0, y2, x0, y1])
- return xy
- end
-
- def round_poly(canv, xy, radii, opts)
- lenXY = xy.length
- lenR = radii.length
- if lenXY != 2*lenR
- raise "wrong number of vertices and radii"
- end
-
- knots = []
- x0 = xy[-2]; y0 = xy[-1]
- x1 = xy[0]; y1 = xy[1]
- xy << xy[0] << xy[1]
-
- 0.step(lenXY - 1, 2){|i|
- radius = radii[i/2]
- r = canv.winfo_pixels(radius)
-
- x2 = xy[i+2]; y2 = xy[i+3]
- z = _round_poly2(x0, y0, x1, y1, x2, y2, r)
- knots.concat(z)
-
- x0 = x1; y0 = y1
- x1 = x2; y1 = y2
- }
- TkcPolygon.new(canv, knots, {:smooth=>true}.update(opts))
- end
-
- def _round_poly2(x0, y0, x1, y1, x2, y2, radius)
- d = 2 * radius
- maxr = 0.75
-
- v1x = x0 - x1
- v1y = y0 - y1
- v2x = x2 - x1
- v2y = y2 - y1
-
- vlen1 = Math.sqrt(v1x*v1x + v1y*v1y)
- vlen2 = Math.sqrt(v2x*v2x + v2y*v2y)
-
- if d > maxr * vlen1
- d = maxr * vlen1
- end
- if d > maxr * vlen2
- d = maxr * vlen2
- end
-
- xy = []
- xy << (x1 + d * v1x / vlen1) << (y1 + d * v1y / vlen1)
- xy << x1 << y1
- xy << (x1 + d * v2x / vlen2) << (y1 + d * v2y / vlen2)
-
- return xy
- end
-
- def sparkle(oxy, tag)
- xy = [
- [299, 283], [298, 302], [295, 314], [271, 331],
- [239, 310], [242, 292], [256, 274], [281, 273]
- ]
- xy.each{|x, y|
- TkcLine.new(@canvas, 271, 304, x, y,
- :fill=>'white', :width=>3, :tag=>tag)
- }
- move_abs(tag, oxy)
- end
-
- def centroid(item)
- anchor(item, :c)
- end
-
- def anchor(item, where)
- x1, y1, x2, y2 = @canvas.bbox(item)
- case(where)
- when :n
- y = y1
- when :s
- y = y2
- else
- y = (y1 + y2) / 2.0
- end
- case(where)
- when :w
- x = x1
- when :e
- x = x2
- else
- x = (x1 + x2) / 2.0
- end
- return [x, y]
- end
-end
-
-TkGoldberg_Demo.new($goldberg_demo)
diff --git a/ext/tk/sample/demos-en/pendulum.rb b/ext/tk/sample/demos-en/pendulum.rb
deleted file mode 100644
index 36bb44edec..0000000000
--- a/ext/tk/sample/demos-en/pendulum.rb
+++ /dev/null
@@ -1,223 +0,0 @@
-#
-# This demonstration illustrates how Tcl/Tk can be used to construct
-# simulations of physical systems.
-# (called by 'widget')
-#
-# based on Tcl/Tk8.5a2 widget demos
-
-# destroy toplevel widget for this demo script
-if defined?($pendulum_demo) && $pendulum_demo
- $pendulum_demo.destroy
- $pendulum_demo = nil
-end
-
-# create toplevel widget
-$pendulum_demo = TkToplevel.new {|w|
- title("Pendulum Animation Demonstration")
- iconname("pendulum")
- positionWindow(w)
-}
-
-# create label
-msg = TkLabel.new($pendulum_demo) {
- font $font
- wraplength '4i'
- justify 'left'
- text 'This demonstration shows how Ruby/Tk can be used to carry out animations that are linked to simulations of physical systems. In the left canvas is a graphical representation of the physical system itself, a simple pendulum, and in the right canvas is a graph of the phase space of the system, which is a plot of the angle (relative to the vertical) against the angular velocity. The pendulum bob may be repositioned by clicking and dragging anywhere on the left canvas.'
-}
-msg.pack('side'=>'top')
-
-# create frame
-TkFrame.new($pendulum_demo) {|frame|
- TkButton.new(frame) {
- text 'Dismiss'
- command proc{
- tmppath = $pendulum_demo
- $pendulum_demo = nil
- tmppath.destroy
- }
- }.pack('side'=>'left', 'expand'=>'yes')
-
- TkButton.new(frame) {
- text 'See Code'
- command proc{showCode 'pendulum'}
- }.pack('side'=>'left', 'expand'=>'yes')
-
-}.pack('side'=>'bottom', 'fill'=>'x', 'pady'=>'2m')
-
-# animated wave
-class PendulumAnimationDemo
- def initialize(frame)
- # Create some structural widgets
- pane = TkPanedWindow.new(frame).pack(:fill=>:both, :expand=>true)
- pane.add(@lf1 = TkLabelFrame.new(pane, :text=>'Pendulum Simulation'))
- pane.add(@lf2 = TkLabelFrame.new(pane, :text=>'Phase Space'))
-
- # Create the canvas containing the graphical representation of the
- # simulated system.
- @c = TkCanvas.new(@lf1, :width=>320, :height=>200, :background=>'white',
- :borderwidth=>2, :relief=>:sunken)
- TkcText.new(@c, 5, 5, :anchor=>:nw,
- :text=>'Click to Adjust Bob Start Position')
- # Coordinates of these items don't matter; they will be set properly below
- @plate = TkcLine.new(@c, 0, 25, 320, 25, :width=>2, :fill=>'grey50')
- @rod = TkcLine.new(@c, 1, 1, 1, 1, :width=>3, :fill=>'black')
- @bob = TkcOval.new(@c, 1, 1, 2, 2,
- :width=>3, :fill=>'yellow', :outline=>'black')
- TkcOval.new(@c, 155, 20, 165, 30, :fill=>'grey50', :outline=>'')
-
- # pack
- @c.pack(:fill=>:both, :expand=>true)
-
- # Create the canvas containing the phase space graph; this consists of
- # a line that gets gradually paler as it ages, which is an extremely
- # effective visual trick.
- @k = TkCanvas.new(@lf2, :width=>320, :height=>200, :background=>'white',
- :borderwidth=>2, :relief=>:sunken)
- @y_axis = TkcLine.new(@k, 160, 200, 160, 0, :fill=>'grey75', :arrow=>:last)
- @x_axis = TkcLine.new(@k, 0, 100, 320, 100, :fill=>'grey75', :arrow=>:last)
-
- @graph = {}
- 90.step(0, -10){|i|
- # Coordinates of these items don't matter;
- # they will be set properly below
- @graph[i] = TkcLine.new(@k, 0, 0, 1, 1, :smooth=>true, :fill=>"grey#{i}")
- }
-
- # labels
- @label_theta = TkcText.new(@k, 0, 0, :anchor=>:ne,
- :text=>'q', :font=>'Symbol 8')
- @label_dtheta = TkcText.new(@k, 0, 0, :anchor=>:ne,
- :text=>'dq', :font=>'Symbol 8')
-
- # pack
- @k.pack(:fill=>:both, :expand=>true)
-
- # Initialize some variables
- @points = []
- @theta = 45.0
- @dTheta = 0.0
- @length = 150
-
- # init display
- showPendulum
-
- # animation loop
- @timer = TkTimer.new(15){ repeat }
-
- # binding
- @c.bindtags_unshift(btag = TkBindTag.new)
- btag.bind('Destroy'){ @timer.stop }
- btag.bind('1', proc{|x, y| @timer.stop; showPendulum(x, y)}, '%x %y')
- btag.bind('B1-Motion', proc{|x, y| showPendulum(x, y)}, '%x %y')
- btag.bind('ButtonRelease-1',
- proc{|x, y| showPendulum(x, y); @timer.start }, '%x %y')
-
- btag.bind('Configure', proc{|w| @plate.coords(0, 25, w, 25)}, '%w')
-
- @k.bind('Configure', proc{|h, w|
- @psh = h/2;
- @psw = w/2
- @x_axis.coords(2, @psh, w-2, @psh)
- @y_axis.coords(@psw, h-2, @psw, 2)
- @label_theta.coords(@psw-4, 6)
- @label_dtheta.coords(w-6, @psh+4)
- }, '%h %w')
-
- # animation start
- @timer.start(500)
- end
-
- # This procedure makes the pendulum appear at the correct place on the
- # canvas. If the additional arguments x, y are passed instead of computing
- # the position of the pendulum from the length of the pendulum rod and its
- # angle, the length and angle are computed in reverse from the given
- # location (which is taken to be the centre of the pendulum bob.)
- def showPendulum(x=nil, y=nil)
- if x && y && (x != 160 || y != 25)
- @dTheta = 0.0
- x2 = x - 160
- y2 = y - 25
- @length = Math.hypot(x2, y2)
- @theta = Math.atan2(x2,y2)*180/Math::PI
- else
- angle = @theta*Math::PI/180
- x = 160 + @length*Math.sin(angle)
- y = 25 + @length*Math.cos(angle)
- end
-
- @rod.coords(160, 25, x, y)
- @bob.coords(x-15, y-15, x+15, y+15)
- end
-
- # Update the phase-space graph according to the current angle and the
- # rate at which the angle is changing (the first derivative with
- # respect to time.)
- def showPhase
- @points << @theta + @psw << -20*@dTheta + @psh
- if @points.length > 100
- @points = @points[-100..-1]
- end
- (0...100).step(10){|i|
- first = - i
- last = 11 - i
- last = -1 if last >= 0
- next if first > last
- lst = @points[first..last]
- @graph[i].coords(lst) if lst && lst.length >= 4
- }
- end
-
- # This procedure is the "business" part of the simulation that does
- # simple numerical integration of the formula for a simple rotational
- # pendulum.
- def recomputeAngle
- scaling = 3000.0/@length/@length
-
- # To estimate the integration accurately, we really need to
- # compute the end-point of our time-step. But to do *that*, we
- # need to estimate the integration accurately! So we try this
- # technique, which is inaccurate, but better than doing it in a
- # single step. What we really want is bound up in the
- # differential equation:
- # .. - sin theta
- # theta + theta = -----------
- # length
- # But my math skills are not good enough to solve this!
-
- # first estimate
- firstDDTheta = -Math.sin(@theta * Math::PI/180) * scaling
- midDTheta = @dTheta + firstDDTheta
- midTheta = @theta + (@dTheta + midDTheta)/2
- # second estimate
- midDDTheta = -Math.sin(midTheta * Math::PI/180) * scaling
- midDTheta = @dTheta + (firstDDTheta + midDDTheta)/2
- midTheta = @theta + (@dTheta + midDTheta)/2
- # Now we do a double-estimate approach for getting the final value
- # first estimate
- midDDTheta = -Math.sin(midTheta * Math::PI/180) * scaling
- lastDTheta = midDTheta + midDDTheta
- lastTheta = midTheta + (midDTheta+ lastDTheta)/2
- # second estimate
- lastDDTheta = -Math.sin(lastTheta * Math::PI/180) * scaling
- lastDTheta = midDTheta + (midDDTheta + lastDDTheta)/2
- lastTheta = midTheta + (midDTheta + lastDTheta)/2
- # Now put the values back in our globals
- @dTheta = lastDTheta
- @theta = lastTheta
- end
-
- # This method ties together the simulation engine and the graphical
- # display code that visualizes it.
- def repeat
- # Simulate
- recomputeAngle
-
- # Update the display
- showPendulum
- showPhase
- end
-end
-
-# Start the animation processing
-PendulumAnimationDemo.new($pendulum_demo)
diff --git a/ext/tk/sample/demos-en/tcolor b/ext/tk/sample/demos-en/tcolor
index 3c63d6730d..5b29797906 100644
--- a/ext/tk/sample/demos-en/tcolor
+++ b/ext/tk/sample/demos-en/tcolor
@@ -121,14 +121,9 @@ def hsbToRgb(hue,sat,value)
end
-def _null_binding
- Module.new.instance_eval{binding}
-end
-private :_null_binding
-
def doUpdate
newCmd = $command.to_s.gsub("%%","\"#{$color}\"")
- eval(newCmd, _null_binding)
+ eval(newCmd)
end
@@ -213,21 +208,21 @@ def tc_loadNamedColor(name)
else
case name.length
when 4
- fmt = /#(.{1})(.{1})(.{1})/
+ format = /#(.{1})(.{1})(.{1})/
shift = 12
when 7
- fmt = /#(.{2})(.{2})(.{2})/
+ format = /#(.{2})(.{2})(.{2})/
shift = 8
when 10
- fmt = /#(.{3})(.{3})(.{3})/
+ format = /#(.{3})(.{3})(.{3})/
shift = 4
when 13
- fmt = /#(.{4})(.{4})(.{4})/
+ format = /#(.{4})(.{4})(.{4})/
shift = 0
else
raise(eException,"syntax error in color name \"#{name}\"")
end
- name.scan(fmt){|strlist|
+ name.scan(format){|strlist|
if strlist.length != 3
raise(eException,"syntax error in color name \"#{name}\"")
end
diff --git a/ext/tk/sample/demos-en/tcolor.bak b/ext/tk/sample/demos-en/tcolor.bak
new file mode 100644
index 0000000000..5464aebae2
--- /dev/null
+++ b/ext/tk/sample/demos-en/tcolor.bak
@@ -0,0 +1,513 @@
+#!/usr/local/bin/ruby
+#
+# tcolor --
+# ¤³¤Î¥¹¥¯¥ê¥×¥È¤ÏRGB,HSB,CYM·Á¼°¤ò¥µ¥Ý¡¼¥È¤¹¤ë
+# ´Ê°×¥«¥é¡¼¥¨¥Ç¥£¥¿¤Ç¤¹¡£
+#
+# Copyright (C) 1998 Takaaki Tateishi(ttate@jaist.ac.jp)
+# last update: Thu Jun 18 06:32:35 JST 1998
+#
+
+# ¤Þ¤º¤Ïtk.rb¤òÆÉ¤ß¹þ¤à¡£
+
+require "tk"
+
+
+# Tk¤Ë¤è¤Ã¤ÆÊѹ¹¤µ¤ì¤ëÊÑ¿ô¤ÏTkVariable¤Î¥¤¥ó¥¹¥¿¥ó¥¹¤ò»È¤¦¡£
+
+$colorSpace = TkVariable.new(:rgb)
+$red = 65535
+$green = 0
+$blue = 0
+$color = "#ffff00000000"
+$updating = TkVariable.new(0)
+$autoUpdate = TkVariable.new(1)
+$name = TkVariable.new("")
+# $command = TkVariable.new("print(%%,\"\n\")")
+$command = TkVariable.new("")
+$label1 = TkVariable.new("label1")
+$label2 = TkVariable.new("label2")
+$label3 = TkVariable.new("label3")
+
+
+# ³Æ¥¤¥Ù¥ó¥ÈÍѤΥ᥽¥Ã¥É
+
+def rgbToHsv(red,green,blue)
+
+ if ( red > green )
+ max = red
+ min = green
+ else
+ max = green
+ min = red
+ end
+
+ if ( blue > max )
+ max = blue
+ else
+ if ( blue < min )
+ min = blue
+ end
+ end
+
+ range = max - min
+
+ if ( max == 0 )
+ sat = 0.0
+ else
+ sat = (max-min)/max
+ end
+
+ if ( sat == 0 )
+ hue = 0.0
+ else
+ rc = (max-red)/range
+ gc = (max-green)/range
+ bc = (max-blue)/range
+ if ( red == max )
+ hue = 0.166667 * (bc - gc)
+ else
+ if ( green == max )
+ hue = 0.166667 * (2.0 + rc - bc)
+ else
+ hue = 0.166667 * (4.0 + gc - rc)
+ end
+ end
+ if ( hue < 0.0 )
+ hue = hue + 1.0
+ end
+ end
+
+ [hue,sat,max/65535]
+end
+
+
+def hsbToRgb(hue,sat,value)
+ v = 65535.0 * value
+ if( sat == 0 )
+ ans = [v,v,v]
+ else
+ hue = hue*6.0
+ if ( hue >= 6 )
+ hue = 0.0
+ end
+ i = hue.to_i
+ f = hue - i
+ p = 65535.0 * value * (1.0 - sat)
+ q = 65535.0 * value * (1.0 - (sat * f))
+ t = 65535.0 * value * (1.0 - (sat * (1.0 - f)))
+ case i
+ when 0
+ ans = [v,t,p]
+ when 1
+ ans = [q,v,p]
+ when 2
+ ans = [p,v,t]
+ when 3
+ ans = [p,q,v]
+ when 4
+ ans = [t,p,v]
+ when 5
+ ans = [v,p,q]
+ else
+ raise(eException,"i value #{i} is out of range")
+ end
+ end
+ return ans
+end
+
+
+def doUpdate
+ newCmd = $command.to_s.gsub("%%","\"#{$color}\"")
+ eval(newCmd)
+end
+
+
+def tc_scaleChanged
+ if( $updating.to_i == 1 )
+ return
+ end
+
+ scale1 = $root.middle.middle.scale1
+ scale2 = $root.middle.middle.scale2
+ scale3 = $root.middle.middle.scale3
+
+ case $colorSpace.to_i
+ when :rgb
+ $red = (scale1.get * 65.535).to_i
+ $green = (scale2.get * 65.535).to_i
+ $blue = (scale3.get * 65.535).to_i
+ when :cmy
+ $red = (65535 - scale1.get * 65.535).to_i
+ $green = (65535 - scale2.get * 65.535).to_i
+ $blue = (65535 - scale3.get * 65.535).to_i
+ when :hsb
+ list = hsbToRgb(scale1.get / 1000.0,
+ scale2.get / 1000.0,
+ scale3.get / 1000.0)
+ $red = list[0]
+ $green = list[1]
+ $blue = list[2]
+ else
+ raise(Exception,"unknown colorSpace")
+ end
+ $color = format("#%04x%04x%04x",$red.to_i,$green.to_i,$blue.to_i)
+ $root.middle.right.set_color($color)
+ if( $autoUpdate.to_i == 1 )
+ doUpdate
+ end
+ Tk.update(TRUE)
+end
+
+
+def tc_setScales
+ $updating.value = 1
+
+ scale1 = $root.middle.middle.scale1
+ scale2 = $root.middle.middle.scale2
+ scale3 = $root.middle.middle.scale3
+
+ case $colorSpace.to_i
+ when :rgb
+ scale1.set($red / 65.535)
+ scale2.set($green / 65.535)
+ scale3.set($blue / 65.535)
+ when :cmy
+ scale1.set((65535 - $red) / 65.535)
+ scale2.set((65535 - $green) / 65.535)
+ scale3.set((65535 - $blue) / 65.535)
+ when :hsb
+ list = rgbToHsv($red,$green,$blue)
+ scale1.set( list[0] * 1000.0 )
+ scale2.set( list[1] * 1000.0 )
+ scale3.set( list[2] * 1000.0 )
+ else
+ raise(Exception,"unknown colorSpace")
+ end
+
+ $updating.value = 0
+end
+
+
+def tc_loadNamedColor(name)
+ if name[0,1] != "#"
+ list = TkWinfo.rgb($root.middle.right.swatch,name)
+ $red = list[0]
+ $green = list[1]
+ $blue = list[2]
+ else
+ case name.length
+ when 4
+ format = /#(.{1})(.{1})(.{1})/
+ shift = 12
+ when 7
+ format = /#(.{2})(.{2})(.{2})/
+ shift = 8
+ when 10
+ format = /#(.{3})(.{3})(.{3})/
+ shift = 4
+ when 13
+ format = /#(.{4})(.{4})(.{4})/
+ shift = 0
+ else
+ raise(eException,"syntax error in color name \"#{name}\"")
+ end
+ name.scan(format){|strlist|
+ if strlist.length != 3
+ raise(eException,"syntax error in color name \"#{name}\"")
+ end
+ $red = strlist[0].to_i
+ $green = strlist[1].to_i
+ $blue = strlist[2].to_i
+ }
+ $red = $red << shift
+ $green = $green << shift
+ $blue = $blue << shift
+ end
+
+ tc_setScales
+ $color = format("#%04x%04x%04x",$red,$green,$blue)
+ $root.middle.right.set_color($color)
+ if $autoUpdate.to_i == 1
+ doUpdate
+ end
+end
+
+
+def changeColorSpace(space)
+ case space
+ when :rgb
+ $label1.value = "Red"
+ $label2.value = "Green"
+ $label3.value = "Blue"
+ when :cmy
+ $label1.value = "Cyan"
+ $label2.value = "Magenta"
+ $label3.value = "Yellow"
+ when :hsb
+ $label1.value = "Hue"
+ $label2.value = "Saturation"
+ $label3.value = "Brightness"
+ end
+ tc_setScales
+end
+
+
+
+
+
+# tcolorÍѤΥá¥Ë¥å¡¼
+
+class TkColorMenuFrame<TkFrame
+ def initialize(parent)
+ super(parent,
+ "relief"=>"raised",
+ "borderwidth"=>"2")
+
+ # File¥á¥Ë¥å¡¼¥Ü¥¿¥ó¤ÎÀ¸À®
+ @file = TkMenubutton.new(self){|button|
+
+ # File¥á¥Ë¥å¡¼¤ÎºîÀ®
+ @file_menu = TkMenu.new(button){
+ add "radio",
+ "label" => "RGB color space",
+ "variable" => $colorSpace,
+ "value" => :rgb,
+ "underline" => "0",
+ "command" => proc{changeColorSpace(:rgb)}
+ add "radio",
+ "label" => "CMY color space",
+ "variable" => $colorSpace,
+ "value" => :cmy,
+ "underline" => "0",
+ "command" => proc{changeColorSpace(:cmy)}
+ add "radio",
+ "label" => "HSB color space",
+ "variable" => $colorSpace,
+ "value" => :hsb,
+ "underline" => "0",
+ "command" => proc{changeColorSpace(:hsb)}
+ add "separator"
+ add "radio",
+ "label" => "Qutomatic updates",
+ "variable" => $autoUpdate,
+ "value" => "1",
+ "underline" => "0"
+ add "radio",
+ "label" => "Manual updates",
+ "variable" => $autoUpdate,
+ "value" => "0",
+ "underline" => "0"
+ add "separator"
+ add "command",
+ "label" => "Exit program",
+ "underline" => "0",
+ "command" => proc{exit}
+ }
+
+ # File¥á¥Ë¥å¡¼¤ÈFile¥Ü¥¿¥ó¤ò´ØÏ¢ÉÕ¤±¤ë
+ menu @file_menu
+
+ text "File"
+ underline "0"
+ }.pack("side"=>"left")
+
+ self
+ end
+end
+
+
+# ²¼Éô¤Î¥Õ¥ì¡¼¥à¤Î¤¿¤á¤Î¥¯¥é¥¹
+class TkColorBotFrame<TkFrame
+ def initialize(parent)
+ super(parent,
+ "relief"=> "raised",
+ "borderwidth"=> 2)
+
+ @commandLabel = TkLabel.new(self,
+ "text"=> "Command:")
+ @command = TkEntry.new(self,
+ "relief"=> "sunken",
+ "borderwidth"=> "2",
+ "textvariable"=> $command,
+ "font"=> "-Adobe-Courier-Medium-R-Normal--*-120-*-*-*-*-*-*")
+ @update = TkButton.new(self,
+ "text"=> "Update",
+ "command"=> proc{doUpdate})
+ @commandLabel.pack("side"=>"left")
+ @update.pack("side"=>"right","pady"=>".1c","padx"=>".25c")
+ @command.pack("expand"=>"yes","fill"=>"x","ipadx"=>".25c")
+
+ self
+ end
+end
+
+
+# ÃæÃʺ¸¤Î¥Õ¥ì¡¼¥à
+class TkColorMiddleLeftFrame<TkFrame
+ def initialize(parent)
+ super(parent)
+
+ for i in ["/usr/local/lib/X11rgb.txt","/usr/lib/X11/rgb.txt",
+ "/X11/R5/lib/X11/rgb.txt","/X11/R4/lib/rgb/rgb.txt",
+ "/usr/openwin/lib/X11/rgb.txt"]
+ if !File.readable?(i)
+ next
+ end
+ f = File.open(i)
+ @scroll = TkScrollbar.new(self,
+ "orient"=>"vertical",
+ "relief"=>"sunken",
+ "borderwidth"=>"2")
+ @scroll.pack("side"=>"right","fill"=>"y")
+ @names = TkListbox.new(self,
+ "width"=>"20",
+ "height"=>"12",
+ "yscrollcommand"=> proc{|first,last| @scroll.set first,last},
+ "relief"=>"sunken",
+ "borderwidth"=>"2",
+ "exportselection"=>"false")
+ @scroll.command(proc{|*args| @names.yview *args})
+ @names.bind("Double-1",proc{
+ tc_loadNamedColor(@names.get(@names.curselection))})
+ @names.pack("side"=>"left")
+ while (line = f.gets)
+ line.chop!
+ linelist = line.split(/[ \t]+/)
+ if linelist.length == 4
+ @names.insert("end",linelist[3])
+ end
+ end
+ f.close
+ break
+ end
+
+ self
+ end
+end
+
+
+# ÃæÃÊÃæ±û¤Î¥Õ¥ì¡¼¥à
+class TkColorMiddleMiddleFrame<TkFrame
+ # @scale1,@scale2,@scale3¤ò³°Éô¤«¤é»²¾È¤Î¤ßµö²Ä¤¹¤ë¡£(Êѹ¹ÉÔ²Ä)
+ attr_reader :scale1, :scale2, :scale3
+
+ def initialize(parent)
+ super(parent)
+
+ @f1 = TkFrame.new(self)
+ @f2 = TkFrame.new(self)
+ @f3 = TkFrame.new(self)
+ @f4 = TkFrame.new(self)
+
+ for f in [@f1,@f2,@f3]
+ f.pack("side"=>"top","expand"=>"yes")
+ end
+ @f4.pack("side"=>"top","expand"=>"yes","fill"=>"x")
+
+ @label1 = TkLabel.new(self,"textvariable"=>$label1)
+ @scale1 = TkScale.new(self,"from"=>"0","to"=>"1000","length"=>"6c",
+ "orient"=>"horizontal",
+ "command"=>proc{tc_scaleChanged})
+ @scale1.pack("side"=>"top","anchor"=>"w")
+ @label1.pack("side"=>"top","anchor"=>"w")
+
+ @label2 = TkLabel.new(self,"textvariable"=>$label2)
+ @scale2 = TkScale.new(self,"from"=>"0","to"=>"1000","length"=>"6c",
+ "orient"=>"horizontal",
+ "command"=>proc{tc_scaleChanged})
+ @scale2.pack("side"=>"top","anchor"=>"w")
+ @label2.pack("side"=>"top","anchor"=>"w")
+
+ @label3 = TkLabel.new(self,"textvariable"=>$label3)
+ @scale3 = TkScale.new(self,"from"=>"0","to"=>"1000","length"=>"6c",
+ "orient"=>"horizontal",
+ "command"=>proc{tc_scaleChanged})
+ @scale3.pack("side"=>"top","anchor"=>"w")
+ @label3.pack("side"=>"top","anchor"=>"w")
+
+ @nameLabel = TkLabel.new(self,"text"=>"Name:")
+ @name = TkEntry.new(self,"relief"=>"sunken","borderwidth"=>"2",
+ "textvariable"=>$name,"width"=>"10",
+ "font"=>"-Adobe-Courier-Medium-R-Normal--*-120-*-*-*-*-*-*")
+ @nameLabel.pack("side"=>"left")
+ @name.pack("side"=>"right", "expand"=>"1", "fill"=>"x")
+ @name.bind("Return",proc{tc_loadNamedColor $name.to_s})
+
+ self
+ end
+end
+
+
+class TkColorMiddleRightFrame<TkFrame
+ attr_reader :swatch
+
+ def initialize(parent)
+ super(parent)
+ @swatch = TkFrame.new(self, "width"=>"2c", "height"=>"5c",
+ "background"=>$color)
+ @value = TkLabel.new(self,
+ "text"=>$color,
+ "width"=>"13",
+ "font"=>"-Adobe-Courier-Medium-R-Normal--*-120-*-*-*-*-*-*")
+ @swatch.pack("side"=>"top","expand"=>"yes","fill"=>"both")
+ @value.pack("side"=>"bottom","pady"=>".25c")
+
+ self
+ end
+
+ def set_color(color)
+ @swatch["background"] = color
+ @value["text"] = color
+ end
+end
+
+
+
+# ÃæÃʤΥե졼¥à
+class TkColorMiddleFrame<TkFrame
+ attr_reader :left, :middle, :right
+
+ def initialize(parent)
+ super(parent,
+ "relief"=> "raised",
+ "borderwidth"=> "2")
+
+ @left = TkColorMiddleLeftFrame.new(self)
+ @left.pack("side"=>"left","padx"=>".25c","pady"=>".25c")
+
+ @middle = TkColorMiddleMiddleFrame.new(self)
+ @middle.pack("side"=>"left","expand"=>"yes","fill"=>"y")
+
+ @right = TkColorMiddleRightFrame.new(self)
+ @right.pack("side"=>"left","padx"=>".25c","pady"=>".25c","anchor"=>"s")
+
+ self
+ end
+end
+
+
+class TkColor<TkRoot
+ attr_reader :menu, :bottom, :middle
+
+ def initialize
+ super
+ @menu = TkColorMenuFrame.new(self)
+ @menu.pack("side"=>"top", "fill"=>"x")
+
+ @bottom = TkColorBotFrame.new(self)
+ @bottom.pack("side"=>"bottom","fill"=>"x")
+
+ @middle = TkColorMiddleFrame.new(self)
+ @middle.pack("side"=>"top","fill"=>"both")
+
+ self
+ end
+end
+
+
+$root = TkColor.new
+
+# ¥¤¥Ù¥ó¥È¤òÂԤİ٤˥롼¥×¤ËÆþ¤ë¡£
+changeColorSpace :rgb
+Tk.mainloop
diff --git a/ext/tk/sample/demos-en/widget b/ext/tk/sample/demos-en/widget
index b57f260f6e..133d151d46 100644
--- a/ext/tk/sample/demos-en/widget
+++ b/ext/tk/sample/demos-en/widget
@@ -72,7 +72,7 @@ EOD
end
if $tk_major_ver >= 8
-$image['print'] = TkPhotoImage.new(:height=>19, :format=>'GIF', :data=><<EOD)
+$image['print'] = TkPhotoImage.new(:height=>16, :format=>'GIF', :data=><<EOD)
R0lGODlhGgATAPcAACEQOTEpQjEpUkIpc0IxY0I5c0oxjEo5SlJCY1JCe1JK
UlpChFpCjFpGkFpSc1paa2NKc2NKnGNja2tapWtjc29KnHNanHNjc3NjrXNr
jHNrnHNzc3tjpXtrtXtzhICAgIRzvYSEjIZzqox7tYyEnIyMjJSEtZSEvZSM
@@ -389,17 +389,6 @@ txt.insert('end', "3. Color picker.\n", tag_demo, "demo-clrpick")
txt.insert('end', " \n ", tag_demospace)
txt.insert('end', "\n")
-txt.insert('end', "Animation\n", tag_title)
-txt.insert('end', " \n ", tag_demospace)
-txt.insert('end', "1. Animated labels (if supported)\n", tag_demo, "demo-anilabel")
-txt.insert('end', " \n ", tag_demospace)
-txt.insert('end', "2. Animated wave (if supported)\n", tag_demo, "demo-aniwave")
-txt.insert('end', " \n ", tag_demospace)
-txt.insert('end', "3. Pendulum simulation (if supported)\n", tag_demo, "demo-pendulum")
-txt.insert('end', " \n ", tag_demospace)
-txt.insert('end', "4. A celebration of Rube Goldberg (if supported)\n", tag_demo, "demo-goldberg")
-
-txt.insert('end', "\n")
txt.insert('end', "Miscellaneous\n", tag_title)
txt.insert('end', " \n ", tag_demospace)
txt.insert('end', "1. The built-in bitmaps.\n", tag_demo, "demo-bitmap")
@@ -503,18 +492,12 @@ end
if $tk_major_ver < 8
alias showVars showVars1
-elsif $tk_major_ver == 8 && $tk_minor_ver < 4
+elsif $tk_major_ver == 8 && $tk_minor_ver < 5
alias showVars showVars1
-else # ver >= 8.4
+else # ver >= 8.5
alias showVars showVars2
end
-def _null_binding
- # binding
- Module.new.instance_eval{binding}
-end
-private :_null_binding
-
# invoke --
# This procedure is called when the user clicks on a demo description.
# It is responsible for invoking the demonstration.
@@ -522,24 +505,11 @@ private :_null_binding
# Arguments:
# txt - Name of text widget
# index - The index of the character that the user clicked on.
-def invoke(txt, idx)
- tag = txt.tag_names(idx).find{|t| t.kind_of?(String) && t =~ /^demo-/}
- return unless tag
-
- cursor = txt.cget('cursor')
- txt.cursor('watch')
- Tk.update
- eval(IO.readlines("#{[$demo_dir, tag[5..-1]].join(File::Separator)}.rb").join, _null_binding)
- Tk.update
- txt.cursor(cursor)
- $tag_visited.add("#{idx} linestart +1 chars", "#{idx} lineend +1 chars")
-end
-=begin
-def invoke (txt, idx)
- tag = txt.tag_names(idx).find{|t| t.kind_of?(String) && t =~ /^demo-/}
+def invoke (txt, index)
+ tag = txt.tag_names(index).find{|t| t.kind_of?(String) && t =~ /^demo-/}
return unless tag
- current_cursor = txt.cget('cursor')
+ cursor = txt.cget('cursor')
txt.cursor('watch')
Tk.update
# eval `cat #{tag[5..-1]}.rb`
@@ -547,11 +517,11 @@ def invoke (txt, idx)
eval IO.readlines("#{[$demo_dir, tag[5..-1]].join(File::Separator)}.rb").join
Tk.update
# txt.cursor('xterm')
- txt.cursor(current_cursor)
+ txt.cursor(cursor)
- $tag_visited.add("#{idx} linestart +1 chars", "#{idx} lineend +1 chars")
+ $tag_visited.add("#{index} linestart +1 chars", "#{index} lineend +1 chars")
end
-=end
+
# showStatus --
#
# Show the name of the demo program in the status bar. This procedure
@@ -596,7 +566,7 @@ def showCode1(demo)
}.pack('side'=>'left', 'expand'=>'yes', 'pady'=>2)
TkButton.new(f) {
text "Rerun Demo"
- command proc{eval($code_text.get('1.0','end'), _null_binding)}
+ command proc{eval($code_text.get('1.0','end'))}
}.pack('side'=>'left', 'expand'=>'yes', 'pady'=>2)
# f.pack('side'=>'bottom', 'expand'=>'yes', 'fill'=>'x')
f.pack('side'=>'bottom', 'fill'=>'x')
@@ -689,9 +659,7 @@ def showCode2(demo)
:command=>proc{printCode($code_text, file)},
:image=>$image['print'], :compound=>:left)
b_run = TkButton.new(bf, :text=>'Rerun Demo',
- :command=>proc{
- eval($code_text.get('1.0','end'), _null_binding)
- },
+ :command=>proc{eval($code_text.get('1.0','end'))},
:image=>$image['refresh'], :compound=>:left)
TkGrid('x', b_run, b_prn, b_dis, :padx=>4, :pady=>[6,4])
@@ -724,9 +692,9 @@ end
if $tk_major_ver < 8
alias showCode showCode1
-elsif $tk_major_ver == 8 && $tk_minor_ver < 4
+elsif $tk_major_ver == 8 && $tk_minor_ver < 5
alias showCode showCode1
-else # ver >= 8.4
+else # ver >= 8.5
alias showCode showCode2
end
@@ -812,7 +780,7 @@ end
#
def aboutBox
Tk.messageBox('icon'=>'info', 'type'=>'ok', 'title'=>'About Widget Demo',
- 'message'=>"Ruby/Tk widget demonstration Ver.1.5.4-en\n\n" +
+ 'message'=>"Ruby/Tk widget demonstration Ver.1.4.3-en\n\n" +
"based on demos of Tk8.1 -- 8.5 " +
"( Copyright:: " +
"(c) 1996-1997 Sun Microsystems, Inc. / " +
@@ -833,8 +801,7 @@ ARGV.each{|cmd|
if cmd =~ /(.*).rb/
cmd = $1
end
- eval(IO.readlines("#{[$demo_dir, cmd].join(File::Separator)}.rb").join,
- _null_binding)
+ eval IO.readlines("#{[$demo_dir, cmd].join(File::Separator)}.rb").join
}
if no_launcher
$root.withdraw # hide root window
diff --git a/ext/tk/sample/demos-jp/anilabel.rb b/ext/tk/sample/demos-jp/anilabel.rb
deleted file mode 100644
index 97781fbe77..0000000000
--- a/ext/tk/sample/demos-jp/anilabel.rb
+++ /dev/null
@@ -1,174 +0,0 @@
-#
-# animated label widget demo (called by 'widget')
-#
-# based on Tcl/Tk8.5a2 widget demos
-
-# toplevel widget ¤¬Â¸ºß¤¹¤ì¤Ðºï½ü¤¹¤ë
-if defined?($anilabel_demo) && $anilabel_demo
- $anilabel_demo.destroy
- $anilabel_demo = nil
-end
-
-# demo ÍѤΠtoplevel widget ¤òÀ¸À®
-$anilabel_demo = TkToplevel.new {|w|
- title("Animated Label Demonstration")
- iconname("anilabel")
- positionWindow(w)
-}
-
-# label À¸À®
-msg = TkLabel.new($anilabel_demo) {
- font $font
- wraplength '4i'
- justify 'left'
- text "²¼¤Ë¤Ï4¤Ä¤Î¥¢¥Ë¥á¡¼¥·¥ç¥ó¥é¥Ù¥ë¤¬É½¼¨¤µ¤ì¤Æ¤¤¤Þ¤¹¡£º¸Â¦¤Ë¤¢¤ë¥é¥Ù¥ë¤Ï¡¢ÆâÉô¤Î¥Æ¥­¥¹¥È¥á¥Ã¥»¡¼¥¸¤ò¥¹¥¯¥í¡¼¥ë¤·¤¿¤è¤¦¤Ë¸«¤»¤ë¤³¤È¤Çư¤­¤òÉÕ¤±¤Æ¤¤¤Þ¤¹¡£±¦Â¦¤Î¥é¥Ù¥ë¤Ï¡¢É½¼¨¤¹¤ë¥¤¥á¡¼¥¸¤òÊѲ½¤µ¤»¤ë¤³¤È¤Çư¤­¤òÍ¿¤¨¤Æ¤¤¤Þ¤¹¡£"
-}
-msg.pack('side'=>'top')
-
-# frame À¸À®
-TkFrame.new($anilabel_demo) {|frame|
- TkButton.new(frame) {
- #text 'λ²ò'
- text 'ÊĤ¸¤ë'
- command proc{
- tmppath = $anilabel_demo
- $anilabel_demo = nil
- tmppath.destroy
- }
- }.pack('side'=>'left', 'expand'=>'yes')
-
- TkButton.new(frame) {
- text '¥³¡¼¥É»²¾È'
- command proc{showCode 'anilabel'}
- }.pack('side'=>'left', 'expand'=>'yes')
-
-}.pack('side'=>'bottom', 'fill'=>'x', 'pady'=>'2m')
-
-# label demo Íѥե졼¥àÀ¸À®
-f_left = TkLabelFrame.new($anilabel_demo, :text=>'Scrolling Texts')
-f_right = TkLabelFrame.new($anilabel_demo, :text=>'GIF Image')
-Tk.pack(f_left, f_right, 'side'=>'left', 'expand'=>'yes', 'fill'=>'both',
- 'padx'=>10, 'pady'=>10)
-
-# animated label
-class AnimatedTextLabel < TkLabel
- def initialize(*args)
- super(*args)
- @timer = TkTimer.new{ _animation_callback }
- @timer.loop_exec = -1
- # bind('Destroy'){ @timer.stop }
- @btag = TkBindTag.new('Destroy'){ @timer.stop }
- self.bindtags_unshift(@btag)
- end
-
- def _animation_callback()
- txt = self.text
- self.text = (txt[1..-1] << txt[0])
- end
- private :_animation_callback
-
- def start(interval)
- @timer.set_interval(interval)
- @timer.start
- end
-
- def stop
- @timer.stop
- end
-end
-
-# animated image
-class AnimatedImageLabel < AnimatedTextLabel
- def initialize(*args)
- super(*args)
- @destroy_image = false
- @btag.bind_append('Destroy'){
- if @destroy_image
- begin
- self.image.delete
- rescue
- end
- end
- }
- end
- attr_accessor :destroy_image
-
- def _animation_callback()
- img = self.image
-
- fmt = img.format
- if fmt.kind_of?(Array)
- if fmt[1].kind_of?(Hash)
- # fmt == ['GIF', {'index'=>idx}]
- idx = fmt[1]['index']
- else
- # fmt == ['GIF', '-index', idx] :: Ruby1.8.2 returns this.
- idx = fmt[2]
- end
- elsif fmt.kind_of?(String) && fmt =~ /GIF -index (\d+)/
- idx = $1.to_i
- else
- idx = -1
- end
-
- begin
- img.format("GIF -index #{idx + 1}")
- rescue => e
- img.format("GIF -index 0")
- end
- end
- private :_animation_callback
-end
-
-# label À¸À®
-l1 = AnimatedTextLabel.new(f_left, :borderwidth=>4, :relief=>:ridge,
- :font=>{:family=>'Courier', :size=>10})
-l2 = AnimatedTextLabel.new(f_left, :borderwidth=>4, :relief=>:groove,
- :font=>{:family=>'Courier', :size=>10})
-l3 = AnimatedTextLabel.new(f_left, :borderwidth=>4, :relief=>:flat,
- :font=>{:family=>'Courier', :size=>10}, :width=>18)
-Tk.pack(l1, l2, l3,
- :side=>:top, :expand=>true, :anchor=>:w, :padx=>10, :pady=>10)
-
-limg = AnimatedImageLabel.new(f_right, :borderwidth=>0)
-limg.pack(:side=>:top, :expand=>true, :padx=>10, :pady=>10)
-
-# base64-encoded animated GIF file
-tclPowerdData = <<EOD
- R0lGODlhKgBAAPQAAP//////zP//AP/MzP/Mmf/MAP+Zmf+ZZv+ZAMz//8zM
- zMyZmcyZZsxmZsxmAMwzAJnMzJmZzJmZmZlmmZlmZplmM5kzM2aZzGZmzGZm
- mWZmZmYzZmYzMzNmzDMzZgAzmSH+IE1hZGUgd2l0aCBHSU1QIGJ5IExARGVt
- YWlsbHkuY29tACH5BAVkAAEALAAAAAAqAEAAAAX+YCCOZEkyTKM2jOm66yPP
- dF03bx7YcuHIDkGBR7SZeIyhTID4FZ+4Es8nQyCe2EeUNJ0peY2s9mi7PhAM
- ngEAMGRbUpvzSxskLh1J+Hkg134OdDIDEB+GHxtYMEQMTjMGEYeGFoomezaC
- DZGSHFmLXTQKkh8eNQVpZ2afmDQGHaOYSoEyhhcklzVmMpuHnaZmDqiGJbg0
- qFqvh6UNAwB7VA+OwydEjgujkgrPNhbTI8dFvNgEYcHcHx0lB1kX2IYeA2G6
- NN0YfkXJ2BsAMuAzHB9cZMk3qoEbRzUACsRCUBK5JxsC3iMiKd8GN088SIyT
- 0RAFSROyeEg38caDiB/+JEgqxsODrZJ1BkT0oHKSmI0ceQxo94HDpg0qsuDk
- UmRAMgu8OgwQ+uIJgUMVeGXA+IQkzEeHGvD8cIGlDXsLiRjQ+EHroQhea7xY
- 8IQBSgYYDi1IS+OFBCgaDMGVS3fGi5BPJpBaENdQ0EomKGD56IHwO39EXiSC
- Ysgxor5+Xfgq0qByYUpiXmwuoredB2aYH4gWWda0B7SeNENpEJHC1ghi+pS4
- AJpIAwWvKPBi+8YEht5EriEqpFfMlhEdkBNpx0HUhwypx5T4IB1MBg/Ws2sn
- wV3MSQOkzI8fUd48Aw3dOZto71x85hHtHijYv18Gf/3GqCdDCXHNoICBobSo
- IqBqJLyCoH8JPrLgdh88CKCFD0CGmAiGYPgffwceZh6FC2ohIIklnkhehTNY
- 4CIHHGzgwYw01ujBBhvAqKOLLq5AAk9kuSPkkKO40NB+h1gnypJIIvkBf09a
- N5QIRz5p5ZJXJpmlIVhOGQA2TmIJZZhKKmmll2BqyWSXWUrZpQtpatlmk1c2
- KaWRHeTZEJF8SqLDn/hhsOeQgBbqAh6DGqronxeARUIIACH5BAUeAAAALAUA
- LgAFAAUAAAUM4CeKz/OV5YmqaRkCACH5BAUeAAEALAUALgAKAAUAAAUUICCK
- z/OdJVCaa7p+7aOWcDvTZwgAIfkEBR4AAQAsCwAuAAkABQAABRPgA4zP95zA
- eZqoWqqpyqLkZ38hACH5BAUKAAEALAcALgANAA4AAAU7ICA+jwiUJEqeKau+
- r+vGaTmac63v/GP9HM7GQyx+jsgkkoRUHJ3Qx0cK/VQVTKtWwbVKn9suNunc
- WkMAIfkEBQoAAAAsBwA3AAcABQAABRGgIHzk842j+Yjlt5KuO8JmCAAh+QQF
- CgAAACwLADcABwAFAAAFEeAnfN9TjqP5oOWziq05lmUIACH5BAUKAAAALA8A
- NwAHAAUAAAUPoPCJTymS3yiQj4qOcPmEACH5BAUKAAAALBMANwAHAAUAAAUR
- oCB+z/MJX2o+I2miKimiawgAIfkEBQoAAAAsFwA3AAcABQAABRGgIHzfY47j
- Q4qk+aHl+pZmCAAh+QQFCgAAACwbADcABwAFAAAFEaAgfs/zCV9qPiNJouo7
- ll8IACH5BAUKAAAALB8ANwADAAUAAAUIoCB8o0iWZggAOw==
-EOD
-
-l1.text('* Slow Animation *').start(300)
-l2.text('* Fast Animation *').start(80)
-l3.text('This is a longer scrolling text in a widget that will not show the whole message at once. ').start(150)
-
-limg.destroy_image = true
-limg.image(TkPhotoImage.new(:format=>'GIF', :data=>tclPowerdData)).start(100)
diff --git a/ext/tk/sample/demos-jp/aniwave.rb b/ext/tk/sample/demos-jp/aniwave.rb
deleted file mode 100644
index 81e2d76b30..0000000000
--- a/ext/tk/sample/demos-jp/aniwave.rb
+++ /dev/null
@@ -1,116 +0,0 @@
-#
-# animated wave demo (called by 'widget')
-#
-# based on Tcl/Tk8.5a2 widget demos
-
-# destroy toplevel widget for this demo script
-if defined?($aniwave_demo) && $aniwave_demo
- $aniwave_demo.destroy
- $aniwave_demo = nil
-end
-
-# create toplevel widget
-$aniwave_demo = TkToplevel.new {|w|
- title("Animated Wave Demonstration")
- iconname("aniwave")
- positionWindow(w)
-}
-
-# create label
-msg = TkLabel.new($aniwave_demo) {
- font $font
- wraplength '4i'
- justify 'left'
- text '¤³¤Î¥Ç¥â¤Ç¤Ï¡¢¥é¥¤¥ó¥¢¥¤¥Æ¥à¤¬°ì¤Ä¤À¤±ÉÁ¤«¤ì¤¿¥­¥ã¥ó¥Ð¥¹¥¦¥£¥¸¥§¥Ã¥È¤¬É½¼¨¤µ¤ì¤Æ¤¤¤Þ¤¹¡£¥¢¥Ë¥á¡¼¥·¥ç¥ó½èÍý¤Ï¡¢¤½¤Î¥é¥¤¥ó¥¢¥¤¥Æ¥à¤ÎºÂɸÃͤòÊѹ¹¤¹¤ë¤³¤È¤Ç¼Â¸½¤·¤Æ¤¤¤Þ¤¹¡£'
-}
-msg.pack('side'=>'top')
-
-# create frame
-TkFrame.new($aniwave_demo) {|frame|
- TkButton.new(frame) {
- #text 'λ²ò'
- text 'ÊĤ¸¤ë'
- command proc{
- tmppath = $aniwave_demo
- $aniwave_demo = nil
- tmppath.destroy
- }
- }.pack('side'=>'left', 'expand'=>'yes')
-
- TkButton.new(frame) {
- text '¥³¡¼¥É»²¾È'
- command proc{showCode 'aniwave'}
- }.pack('side'=>'left', 'expand'=>'yes')
-
-}.pack('side'=>'bottom', 'fill'=>'x', 'pady'=>'2m')
-
-# animated wave
-class AnimatedWaveDemo
- def initialize(frame, dir=:left)
- @direction = dir
-
- # create canvas widget
- @c = TkCanvas.new(frame, :width=>300, :height=>200,
- :background=>'black')
- @c.pack(:padx=>10, :pady=>10, :expand=>true)
-
- # Creates a coordinates list of a wave.
- @waveCoords = []
- @backupCoords = []
- n = 0
- (-10..300).step(5){|n| @waveCoords << [n, 100]; @backupCoords << [n, 100] }
- @waveCoords << [n, 0]; @backupCoords << [n, 0]
- @waveCoords << [n+5, 200]; @backupCoords << [n+5, 200]
- @coordsLen = @waveCoords.length
-
- # Create a smoothed line and arrange for its coordinates to be the
- # contents of the variable waveCoords.
- @line = TkcLine.new(@c, @waveCoords,
- :width=>1, :fill=>'green', :smooth=>true)
-
- # Main animation "loop".
- # Theoretically 100 frames-per-second (==10ms between frames)
- @timer = TkTimer.new(10){ basicMotion; reverser }
-
- # Arrange for the animation loop to stop when the canvas is deleted
- @c.bindtags_unshift(TkBindTag.new('Destroy'){ @timer.stop })
- end
-
- # Basic motion handler. Given what direction the wave is travelling
- # in, it advances the y coordinates in the coordinate-list one step in
- # that direction.
- def basicMotion
- @backupCoords, @waveCoords = @waveCoords, @backupCoords
- (0...@coordsLen).each{|idx|
- if @direction == :left
- @waveCoords[idx][1] = @backupCoords[(idx+1 == @coordsLen)? 0: idx+1][1]
- else
- @waveCoords[idx][1] = @backupCoords[(idx == 0)? -1: idx-1][1]
- end
- }
- @line.coords(@waveCoords)
- end
-
- # Oscillation handler. This detects whether to reverse the direction
- # of the wave by checking to see if the peak of the wave has moved off
- # the screen (whose size we know already.)
- def reverser
- if @waveCoords[0][1] < 10
- @direction = :right
- elsif @waveCoords[-1][1] < 10
- @direction = :left
- end
- end
-
- # animation control
- def move
- @timer.start
- end
-
- def stop
- @timer.stop
- end
-end
-
-# Start the animation processing
-AnimatedWaveDemo.new($aniwave_demo, :left).move
diff --git a/ext/tk/sample/demos-jp/bind.rb b/ext/tk/sample/demos-jp/bind.rb
index e1e23b9893..70127424c5 100644
--- a/ext/tk/sample/demos-jp/bind.rb
+++ b/ext/tk/sample/demos-jp/bind.rb
@@ -90,35 +90,17 @@ TkText.new($bind_demo){|t|
tag_binding_for_bind_demo(tag, tagstyle_bold, tagstyle_normal)
}
d1.bind('1',
- proc{
- eval(`cat #{[$demo_dir,'items.rb'].join(File::Separator)}`,
- _null_binding)
- })
+ proc{eval `cat #{[$demo_dir,'items.rb'].join(File::Separator)}`})
d2.bind('1',
- proc{
- eval(`cat #{[$demo_dir,'plot.rb'].join(File::Separator)}`,
- _null_binding)
- })
+ proc{eval `cat #{[$demo_dir,'plot.rb'].join(File::Separator)}`})
d3.bind('1',
- proc{
- eval(`cat #{[$demo_dir,'ctext.rb'].join(File::Separator)}`,
- _null_binding)
- })
+ proc{eval `cat #{[$demo_dir,'ctext.rb'].join(File::Separator)}`})
d4.bind('1',
- proc{
- eval(`cat #{[$demo_dir,'arrow.rb'].join(File::Separator)}`,
- _null_binding)
- })
+ proc{eval `cat #{[$demo_dir,'arrow.rb'].join(File::Separator)}`})
d5.bind('1',
- proc{
- eval(`cat #{[$demo_dir,'ruler.rb'].join(File::Separator)}`,
- _null_binding)
- })
+ proc{eval `cat #{[$demo_dir,'ruler.rb'].join(File::Separator)}`})
d6.bind('1',
- proc{
- eval(`cat #{[$demo_dir,'cscroll.rb'].join(File::Separator)}`,
- _null_binding)
- })
+ proc{eval `cat #{[$demo_dir,'cscroll.rb'].join(File::Separator)}`})
TkTextMarkInsert.new(t, '0.0')
configure('state','disabled')
diff --git a/ext/tk/sample/demos-jp/check2.rb b/ext/tk/sample/demos-jp/check2.rb
index f681a4d684..5d0c74a743 100644
--- a/ext/tk/sample/demos-jp/check2.rb
+++ b/ext/tk/sample/demos-jp/check2.rb
@@ -76,31 +76,31 @@ TkCheckButton.new($check2_demo, :text=>'°ÂÁ´À­¸¡ºº', :variable=>safety,
# tristate check
in_check = false
tristate_check = proc{|n1,n2,op|
- unless in_check
- in_check = true
- begin
- if n1 == safety
- if safety == 'none'
- wipers.value = 0
- brakes.value = 0
- sober.value = 0
- elsif safety == 'all'
- wipers.value = 1
- brakes.value = 1
- sober.value = 1
- end
+ return if in_check
+
+ in_check = true
+ begin
+ if n1 == safety
+ if safety == 'none'
+ wipers.value = 0
+ brakes.value = 0
+ sober.value = 0
+ elsif safety == 'all'
+ wipers.value = 1
+ brakes.value = 1
+ sober.value = 1
+ end
+ else
+ if wipers == 1 && brakes == 1 && sober == 1
+ safety.value = 'all'
+ elsif wipers == 1 || brakes == 1 || sober == 1
+ safety.value = 'partial'
else
- if wipers == 1 && brakes == 1 && sober == 1
- safety.value = 'all'
- elsif wipers == 1 || brakes == 1 || sober == 1
- safety.value = 'partial'
- else
- safety.value = 'none'
- end
+ safety.value = 'none'
end
- ensure
- in_check = false
end
+ ensure
+ in_check = false
end
}
diff --git a/ext/tk/sample/demos-jp/ctext.rb b/ext/tk/sample/demos-jp/ctext.rb
index 66e1fe8107..a71b6f2cb0 100644
--- a/ext/tk/sample/demos-jp/ctext.rb
+++ b/ext/tk/sample/demos-jp/ctext.rb
@@ -60,7 +60,7 @@ TkcRectangle.new($ctext_canvas, 245, 195, 255, 205,
$ctag_text = TkcTag.new($ctext_canvas)
$ctag_text.withtag(TkcText.new($ctext_canvas, 250, 200,
- 'text'=>"¤³¤ì¤Ï¥­¥ã¥ó¥Ð¥¹widget¤Î¥Æ¥­¥¹¥Èµ¡Ç½¤ò¥Ç¥â¤¹¤ë¤¿¤á¤Îʸ»úÎó¤Ç¤¹¡£\n¾å¤Ç½Ò¤Ù¤¿¤è¤¦¤ÊÊÔ½¸¤ò²Äǽ¤È¤¹¤ë¤¿¤á¤Î¥Ð¥¤¥ó¥Ç¥£¥ó¥°¤ò»Ü¤·¤Æ¤¤¤Þ¤¹¡£",
+ 'text'=>"¤³¤ì¤Ï¥­¥ã¥ó¥Ð¥¹widget¤Î¥Æ¥­¥¹¥Èµ¡Ç½¤ò¥Ç¥â¤¹¤ë¤¿¤á¤Îʸ»úÎó¤Ç¤¹¡£¥Þ¥¦¥¹¤ò»ý¤Ã¤Æ¤¤¤­¡¢¥¯¥ê¥Ã¥¯¤·¤ÆÆþÎϤǤ­¤Þ¤¹¡£ÁªÂò¤·¤Æ¥³¥ó¥È¥í¡¼¥ë-D¤Ç¾Ãµî¤¹¤ë¤³¤È¤â¤Ç¤­¤Þ¤¹¡£",
'width'=>440, 'anchor'=>'n',
'font'=>'-*-Helvetica-Medium-R-Normal--*-240-*-*-*-*-*-*',
'kanjifont'=>'-*-r-*--24-*-jisx0208.1983-0',
diff --git a/ext/tk/sample/demos-jp/floor.rb b/ext/tk/sample/demos-jp/floor.rb
index b029580bd6..517600de92 100644
--- a/ext/tk/sample/demos-jp/floor.rb
+++ b/ext/tk/sample/demos-jp/floor.rb
@@ -1664,8 +1664,8 @@ else
pack('expand'=>'yes', 'fill'=>'both', 'padx'=>1, 'pady'=>1)
- v.command(proc{|*args| $floor_canvas.yview(*args)})
- h.command(proc{|*args| $floor_canvas.xview(*args)})
+ v.command(proc{|*args| c.yview(*args)})
+ h.command(proc{|*args| c.xview(*args)})
}
end
diff --git a/ext/tk/sample/demos-jp/floor2.rb b/ext/tk/sample/demos-jp/floor2.rb
index a20b31d45c..fcf208b61f 100644
--- a/ext/tk/sample/demos-jp/floor2.rb
+++ b/ext/tk/sample/demos-jp/floor2.rb
@@ -1664,8 +1664,8 @@ else
pack('expand'=>'yes', 'fill'=>'both', 'padx'=>1, 'pady'=>1)
- v.command(proc{|*args| $floor2_canvas.yview(*args)})
- h.command(proc{|*args| $floor2_canvas.xview(*args)})
+ v.command(proc{|*args| c.yview(*args)})
+ h.command(proc{|*args| c.xview(*args)})
}
end
diff --git a/ext/tk/sample/demos-jp/goldberg.rb b/ext/tk/sample/demos-jp/goldberg.rb
deleted file mode 100644
index 592b69f775..0000000000
--- a/ext/tk/sample/demos-jp/goldberg.rb
+++ /dev/null
@@ -1,2003 +0,0 @@
-#
-# Ruby/Tk Goldverg demo (called by 'widget')
-#
-# Based on Tcl/Tk8.5a2 widget demos.
-# The following is the original comment of TkGoldberg.tcl.
-#
-#>>##+#################################################################
-#>>#
-#>># TkGoldberg.tcl
-#>># by Keith Vetter, March 13, 2003
-#>>#
-#>># "Man will always find a difficult means to perform a simple task"
-#>># Rube Goldberg
-#>>#
-#>># Reproduced here with permission.
-#>>#
-#>>##+#################################################################
-#>>#
-#>># Keith Vetter 2003-03-21: this started out as a simple little program
-#>># but was so much fun that it grew and grew. So I apologize about the
-#>># size but I just couldn't resist sharing it.
-#>>#
-#>># This is a whizzlet that does a Rube Goldberg type animation, the
-#>># design of which comes from an New Years e-card from IncrediMail.
-#>># That version had nice sound effects which I eschewed. On the other
-#>># hand, that version was in black and white (actually dark blue and
-#>># light blue) and this one is fully colorized.
-#>>#
-#>># One thing I learned from this project is that drawing filled complex
-#>># objects on a canvas is really hard. More often than not I had to
-#>># draw each item twice--once with the desired fill color but no
-#>># outline, and once with no fill but with the outline. Another trick
-#>># is erasing by drawing with the background color. Having a flood fill
-#>># command would have been extremely helpful.
-#>>#
-#>># Two wiki pages were extremely helpful: Drawing rounded rectangles
-#>># which I generalized into Drawing rounded polygons, and regular
-#>># polygons which allowed me to convert ovals and arcs into polygons
-#>># which could then be rotated (see Canvas Rotation). I also wrote
-#>># Named Colors to aid in the color selection.
-#>>#
-#>># I could comment on the code, but it's just 26 state machines with
-#>># lots of canvas create and move calls.
-
-if defined?($goldberg_demo) && $goldberg_demo
- $goldberg_demo.destroy
- $goldberg_demo = nil
-end
-
-# demo toplevel widget
-$goldberg_demo = TkToplevel.new {|w|
- title("Tk Goldberg (demonstration)")
- iconname("goldberg")
-# positionWindow(w)
-}
-
-=begin
-# label
-msg = TkLabel.new($goldberg_demo) {
- font 'Arial 10'
- wraplength '4i'
- justify 'left'
- text "¤³¤ì¤Ï¡¢¤¢¤Ê¤¿¤¬¼«Ê¬¤Î¥¢¥Ë¥á¡¼¥·¥ç¥ó¤ò¤¤¤«¤ËÆþ¤êÁȤó¤À¤â¤Î¤Ë¤Ç¤­¤ë¤«¤ò¼¨¤¹¤È¤¤¤¦¤À¤±¤Î¤¿¤á¤Î¥Ç¥â¤Ç¤¹¡£¥Ü¡¼¥ë¤ò¥¯¥ê¥Ã¥¯¤¹¤ì¤Ðʪ¤¬Æ°¤­»Ï¤á¤Þ¤¹¡ª\n\n\"Man will always find a difficult means to perform a simple task\"\n - Rube Goldberg"
-}
-msg.pack('side'=>'top')
-=end
-
-=begin
-# frame
-TkFrame.new($goldberg_demo) {|frame|
- TkButton.new(frame) {
- text 'ÊĤ¸¤ë'
- command proc{
- tmppath = $goldberg_demo
- $goldberg_demo = nil
- tmppath.destroy
- }
- }.pack('side'=>'left', 'expand'=>'yes')
-
- TkButton.new(frame) {
- text '¥³¡¼¥É»²¾È'
- command proc{showCode 'goldberg'}
- }.pack('side'=>'left', 'expand'=>'yes')
-
-}.pack('side'=>'bottom', 'fill'=>'x', 'pady'=>'2m')
-=end
-
-#########################################
-
-class TkGoldberg_Demo
- def initialize(parent)
- @parent = parent
-
- @S = {}
- @S['title'] = 'Tk Goldberg'
- @S['speed'] = TkVariable.new(5)
- @S['cnt'] = TkVariable.new(0)
- # @S['message'] = TkVariable.new("\\nWelcome\\nto\\nRuby/Tk")
- @S['message'] = TkVariable.new("\\n ¤è¤¦¤³¤½¡ª\\nRuby/Tk\\n¤Î\\nÀ¤³¦¤Ø")
- @S['pause'] = TkVariable.new
- @S['details'] = TkVariable.new(true)
-
- @S['mode'] = TkVariable.new(:MSTART, :symbol)
- # :MSTART, :MGO, :MPAUSE, :MSSTEP, :MBSTEP, :MDONE, :MDEBUG
-
- # 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
- @speed = [1, 10, 20, 50, 80, 100, 150, 200, 300, 400, 500]
-
- # colors
- @C = {}
- @C['fg'] = 'black'
- # @C['bg'] = 'gray75'
- @C['bg'] = 'cornflowerblue'
-
- @C['0'] = 'white'; @C['1a'] = 'darkgreen'; @C['1b'] = 'yellow'
- @C['2'] = 'red'; @C['3a'] = 'green'; @C['3b'] = 'darkblue'
- @C['4'] = @C['fg']; @C['5a'] = 'brown'; @C['5b'] = 'white'
- @C['6'] = 'magenta'; @C['7'] = 'green'; @C['8'] = @C['fg']
- @C['9'] = 'blue4'; @C['10a'] = 'white'; @C['10b'] = 'cyan'
- @C['11a'] = 'yellow'; @C['11b'] = 'mediumblue'; @C['12'] = 'tan2'
- @C['13a'] = 'yellow'; @C['13b'] = 'red'; @C['14'] = 'white'
- @C['15a'] = 'green'; @C['15b'] = 'yellow'; @C['16'] = 'gray65'
- @C['17'] = '#A65353'; @C['18'] = @C['fg']; @C['19'] = 'gray50'
- @C['20'] = 'cyan'; @C['21'] = 'gray65'; @C['22'] = @C['20']
- @C['23a'] = 'blue'; @C['23b'] = 'red'; @C['23c'] = 'yellow'
- @C['24a'] = 'red'; @C['24b'] = 'white';
-
- @STEP = TkVariable.new_hash
- @STEP.default_value_type = :numeric
-
- @XY = {}
-
- @XY6 = {
- '-1'=>[366, 207], '-2'=>[349, 204], '-3'=>[359, 193], '-4'=>[375, 192],
- '-5'=>[340, 190], '-6'=>[349, 177], '-7'=>[366, 177], '-8'=>[380, 176],
- '-9'=>[332, 172], '-10'=>[342, 161], '-11'=>[357, 164],
- '-12'=>[372, 163], '-13'=>[381, 149], '-14'=>[364, 151],
- '-15'=>[349, 146], '-16'=>[333, 148], '0'=>[357, 219],
- '1'=>[359, 261], '2'=>[359, 291], '3'=>[359, 318], '4'=>[361, 324],
- '5'=>[365, 329], '6'=>[367, 334], '7'=>[367, 340], '8'=>[366, 346],
- '9'=>[364, 350], '10'=>[361, 355], '11'=>[359, 370], '12'=>[359, 391],
- '13,0'=>[360, 456], '13,1'=>[376, 456], '13,2'=>[346, 456],
- '13,3'=>[330, 456], '13,4'=>[353, 444], '13,5'=>[368, 443],
- '13,6'=>[339, 442], '13,7'=>[359, 431], '13,8'=>[380, 437],
- '13,9'=>[345, 428], '13,10'=>[328, 434], '13,11'=>[373, 424],
- '13,12'=>[331, 420], '13,13'=>[360, 417], '13,14'=>[345, 412],
- '13,15'=>[376, 410], '13,16'=>[360, 403]
- }
-
- @timer = TkTimer.new(@speed[@S['speed'].numeric]){|timer|
- timer.set_interval(go)
- }
-
- do_display
- reset
-
- # Start everything going
- @timer.start
- end
-
- def do_display()
- @ctrl = TkFrame.new(@parent, :relief=>:ridge, :bd=>2, :padx=>5, :pady=>5)
- @screen = TkFrame.new(@parent, :bd=>2,
- :relief=>:raised).pack(:side=>:left, :fill=>:both,
- :expand=>true)
-
- @canvas = TkCanvas.new(@parent, :width=>850, :height=>700,
- :bg=>@C['bg'], :highlightthickness=>0){
- scrollregion([0, 0, 1000, 1000]) # Kludge to move everything up
- yview_moveto(0.05)
- }.pack(:in=>@screen, :side=>:top, :fill=>:both, :expand=>true)
-
- @canvas.bind('3'){ @pause.invoke }
- @canvas.bind('Destroy'){ @timer.stop }
-
- do_ctrl_frame
- do_detail_frame
-
- msg = TkLabel.new(@parent, :bg=>@C['bg'], :fg=>'white') {
- font 'Arial 10'
- wraplength 600
- justify 'left'
- text "¤³¤ì¤Ï¡¢¤¢¤Ê¤¿¤¬¼«Ê¬¤Î¥¢¥Ë¥á¡¼¥·¥ç¥ó¤ò¤¤¤«¤ËÆþ¤êÁȤó¤À¤â¤Î¤Ë¤Ç¤­¤ë¤«¤ò¼¨¤¹¤È¤¤¤¦¤À¤±¤Î¤¿¤á¤Î¥Ç¥â¤Ç¤¹¡£¥Ü¡¼¥ë¤ò¥¯¥ê¥Ã¥¯¤¹¤ì¤Ðʪ¤¬Æ°¤­»Ï¤á¤Þ¤¹¡ª\n\"Man will always find a difficult means to perform a simple task\" - Rube Goldberg"
- }
- msg.place(:in=>@canvas, :relx=>0, :rely=>0, :anchor=>:nw)
-
- frame = TkFrame.new(@parent, :bg=>@C['bg'])
-
- TkButton.new(frame, :bg=>@C['bg'], :activebackground=>@C['bg']) {
- text 'ÊĤ¸¤ë'
- command proc{
- tmppath = $goldberg_demo
- $goldberg_demo = nil
- tmppath.destroy
- }
- }.pack('side'=>'left')
-
- TkButton.new(frame, :bg=>@C['bg'], :activebackground=>@C['bg']) {
- text '¥³¡¼¥É»²¾È'
- command proc{showCode 'goldberg'}
- }.pack('side'=>'left', 'padx'=>5)
-
- @show = TkButton.new(frame, :text=>'>>', :command=>proc{show_ctrl},
- :bg=>@C['bg'], :activebackground=>@C['bg'])
- @show.pack('side'=>'left')
- frame.place(:in=>@canvas, :relx=>1, :rely=>0, :anchor=>:ne)
-
- Tk.update
- end
-
- def do_ctrl_frame
- @start = TkButton.new(@parent, :text=>'Start', :bd=>6,
- :command=>proc{do_button(0)})
- @start.font(@start['font'].weight('bold'))
- font = @start['font']
-
- @pause = TkCheckbutton.new(@parent, :text=>'Pause', :font=>font,
- :command=>proc{do_button(1)}, :relief=>:raised,
- :variable=>@S['pause'])
-
- @step = TkButton.new(@parent, :text=>'Single Step', :font=>font,
- :command=>proc{do_button(2)})
- @bstep = TkButton.new(@parent, :text=>'Big Step', :font=>font,
- :command=>proc{do_button(4)})
- @reset = TkButton.new(@parent, :text=>'Reset', :font=>font,
- :command=>proc{do_button(3)})
-
- @details = TkFrame.new(@parent, :bd=>2, :relief=>:ridge)
- @detail = TkCheckbutton.new(@parent, :text=>'Details', :font=>font,
- :relief=>:raised, :variable=>@S['details'])
-
- @msg_entry = TkEntry.new(@parent, :textvariable=>@S['message'],
- :justify=>:center)
- @speed_scale = TkScale.new(@parent, :orient=>:horizontal,
- :from=>1, :to=>10, :font=>font,
- :variable=>@S['speed'], :bd=>2,
- :relief=>:ridge, :showvalue=>false)
- @about = TkButton.new(@parent, :text=>'About',
- :command=>proc{about}, :font=>font)
-
- Tk.grid(@start, :in=>@ctrl, :row=>0, :sticky=>:ew)
- @ctrl.grid_rowconfigure(1, :minsize=>10)
- Tk.grid(@pause, :in=>@ctrl, :row=>2, :sticky=>:ew)
- Tk.grid(@step, :in=>@ctrl, :sticky=>:ew)
- Tk.grid(@bstep, :in=>@ctrl, :sticky=>:ew)
- Tk.grid(@reset, :in=>@ctrl, :sticky=>:ew)
- @ctrl.grid_rowconfigure(10, :minsize=>20)
- Tk.grid(@details, :in=>@ctrl, :row=>11, :sticky=>:ew)
- Tk.grid(@detail, :in=>@details, :row=>0, :sticky=>:ew)
- @ctrl.grid_rowconfigure(50, :weight=>1)
-
- @S['mode'].trace('w', proc{|*args| active_GUI(*args)})
- @S['details'].trace('w', proc{|*args| active_GUI(*args)})
- @S['speed'].trace('w', proc{|*args| active_GUI(*args)})
-
- Tk.grid(@msg_entry, :in=>@ctrl, :row=>98, :sticky=>:ew, :pady=>5)
- Tk.grid(@speed_scale, :in=>@ctrl, :row=>99, :sticky=>:ew)
- Tk.grid(@about, :in=>@ctrl, :row=>100, :sticky=>:ew)
-
- @reset.bind('3'){@S['mode'].value = -1} # Debugging
- end
-
- def do_detail_frame
- @f_details = TkFrame.new(@details)
-
- @label = TkLabel.new(@f_details, :textvariable=>@S['cnt'],
- :bd=>1, :relief=>:solid, :bg=>'white')
- Tk.grid(@label, '-', '-', '-', :sticky=>:ew, :row=>0)
-
- idx = 1
- loop {
- break unless respond_to?("move#{idx}")
- l = TkLabel.new(@f_details, :text=>idx, :anchor=>:e,
- :width=>2, :bd=>1, :relief=>:solid, :bg=>'white')
- @STEP[idx] = 0
- ll = TkLabel.new(@f_details, :textvariable=>@STEP.ref(idx),
- :width=>5, :bd=>1, :relief=>:solid, :bg=>'white')
- row = (idx + 1)/2
- col = ((idx + 1) & 1) * 2
- Tk.grid(l, :sticky=>:ew, :row=>row, :column=>col)
- Tk.grid(ll, :sticky=>:ew, :row=>row, :column=>(col + 1))
- idx += 1
- }
- @f_details.grid_columnconfigure(1, :weight=>1)
- end
-
- def show_ctrl
- if @ctrl.winfo_mapped?
- @ctrl.pack_forget
- @show.text('>>')
- else
- @ctrl.pack(:side=>:right, :fill=>:both, :ipady=>5)
- @show.text('<<')
- end
- end
-
- def draw_all
- reset_step
- @canvas.delete(:all)
- idx = 0
- loop{
- m = "draw#{idx}"
- break unless respond_to?(m)
- send(m)
- idx += 1
- }
- end
-
- def active_GUI(var1, var2, op)
- st = {false=>:disabled, true=>:normal}
-
- m = @S['mode'].to_sym
- @S['pause'].value = (m == :MPAUSE)
- @start.state(st[m != :MGO])
- @pause.state(st[m != :MSTART && m != :MDONE])
- @step.state(st[m != :MGO && m != :MDONE])
- @bstep.state(st[m != :MGO && m != :MDONE])
- @reset.state(st[m != :MSTART])
-
- if @S['details'].bool
- Tk.grid(@f_details, :in=>@details, :row=>2, :sticky=>:ew)
- else
- Tk.grid_forget(@f_details)
- end
- @speed_scale.label("Speed: #{@S['speed'].value}")
- end
-
- def start
- @S['mode'].value = :MGO
- end
-
- def do_button(what)
- case what
- when 0 # Start
- reset if @S['mode'].to_sym == :MDONE
- @S['mode'].value = :MGO
-
- when 1 # Pause
- @S['mode'].value = ((@S['pause'].bool)? :MPAUSE: :MGO)
-
- when 2 # Step
- @S['mode'].value = :MSSTEP
-
- when 3 # Reset
- reset
-
- when 4 # Big step
- @S['mode'].value = :MBSTEP
- end
- end
-
- def go(who = nil)
- now = Tk::Clock.clicks(:miliseconds)
- if who # Start here for debugging
- @S['active'] = [who]
- @S['mode'].value = :MGO
- end
- return if @S['mode'].to_sym == :MDEBUG # Debugging
- # If not paused, do the next move
- n = next_step if @S['mode'].to_sym != :MPAUSE
- @S['mode'].value = :MPAUSE if @S['mode'].to_sym == :MSSTEP # Single step
- @S['mode'].value = :MSSTEP if @S['mode'].to_sym == :MBSTEP && n # big step
- elapsed = Tk::Clock.clicks(:miliseconds) - now
- delay = @speed[@S['speed'].to_i] - elapsed
- delay = 1 if delay <= 0
- return delay
- end
-
- def next_step
- retval = false # Return value
-
- if @S['mode'].to_sym != :MSTART && @S['mode'].to_sym != :MDONE
- @S['cnt'].numeric += 1
- end
- alive = []
- @S['active'].each{|who|
- who = who.to_i
- n = send("move#{who}")
- if (n & 1).nonzero? # This guy still alive
- alive << who
- end
- if (n & 2).nonzero? # Next guy is active
- alive << (who + 1)
- retval = true
- end
- if (n & 4).nonzero? # End of puzzle flag
- @S['mode'].value = :MDONE # Done mode
- @S['active'] = [] # No more animation
- return true
- end
- }
- @S['active'] = alive
- return retval
- end
-
- def about
- msg = "Ruby/Tk Version ::\nby Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)\n\n"
- msg += "Original Version ::\n"
- msg += "#{@S['title']}\nby Keith Vetter, March 2003\n(Reproduced by kind permission of the author)\n\n"
- msg += "Man will always find a difficult means to perform a simple task"
- msg += "\nRube Goldberg"
- Tk.messageBox(:message=>msg, :title=>'About')
- end
-
- ################################################################
- #
- # All the drawing and moving routines
- #
-
- # START HERE! banner
- def draw0
- color = @C['0']
- TkcText.new(@canvas,
- # [579, 119], :text=>'START HERE!',
- [558, 119], :text=>'¤³¤³¤«¤é¥¹¥¿¡¼¥È¡ª',
- :fill=>color, :anchor=>:w,
- :tag=>'I0', :font=>['Times Roman', 12, :italic, :bold])
- TkcLine.new(@canvas, [719, 119, 763, 119], :tag=>'I0', :fill=>color,
- :width=>5, :arrow=>:last, :arrowshape=>[18, 18, 5])
- @canvas.itembind('I0', '1'){ start }
- end
-
- def move0(step = nil)
- step = get_step(0, step)
-
- if @S['mode'].to_sym != :MSTART # Start the ball rolling
- move_abs('I0', [-100, -100]) # Hide the banner
- return 2
- end
-
- pos = [
- [673, 119], [678, 119], [683, 119], [688, 119],
- [693, 119], [688, 119], [683, 119], [678, 119]
- ]
- step = step % pos.length
- move_abs('I0', pos[step])
- return 1
- end
-
- # Dropping ball
- def draw1
- color = @C['1a']
- color2 = @C['1b']
- TkcPolygon.new(@canvas,
- [ 844, 133, 800, 133, 800, 346, 820, 346,
- 820, 168, 844, 168, 844, 133 ],
- :width=>3, :fill=>color, :outline=>'')
- TkcPolygon.new(@canvas,
- [ 771, 133, 685, 133, 685, 168, 751, 168,
- 751, 346, 771, 346, 771, 133 ],
- :width=>3, :fill=>color, :outline=>'')
- TkcOval.new(@canvas, box(812, 122, 9),
- :tag=>'I1', :fill=>color2, :outline=>'')
-
- @canvas.itembind('I1', '1'){ start }
- end
-
- def move1(step = nil)
- step = get_step(1, step)
- pos = [
- [807, 122], [802, 122], [797, 123], [793, 124], [789, 129], [785, 153],
- [785, 203], [785, 278, :x], [785, 367], [810, 392], [816, 438],
- [821, 503], [824, 585, :y], [838, 587], [848, 593], [857, 601],
- [-100, -100]
- ]
- return 0 if step >= pos.length
- where = pos[step]
- move_abs('I1', where)
- move15a if where[2] == :y
- return 3 if where[2] == :x
- return 1
- end
-
- # Lighting the match
- def draw2
- color = @C['2']
-
- # Fulcrum
- TkcPolygon.new(@canvas, [750, 369, 740, 392, 760, 392],
- :fill=>@C['fg'], :outline=>@C['fg'])
-
- # Strike box
- TkcRectangle.new(@canvas, [628, 335, 660, 383],
- :fill=>'', :outline=>@C['fg'])
- (0..2).each{|y|
- yy = 335 + y*16
- TkcBitmap.new(@canvas, [628, yy], :bitmap=>'gray25',
- :anchor=>:nw, :foreground=>@C['fg'])
- TkcBitmap.new(@canvas, [644, yy], :bitmap=>'gray25',
- :anchor=>:nw, :foreground=>@C['fg'])
- }
-
- # Lever
- TkcLine.new(@canvas, [702, 366, 798, 366],
- :fill=>@C['fg'], :width=>6, :tag=>'I2_0')
-
- # R strap
- TkcLine.new(@canvas, [712, 363, 712, 355],
- :fill=>@C['fg'], :width=>3, :tag=>'I2_1')
-
- # L strap
- TkcLine.new(@canvas, [705, 363, 705, 355],
- :fill=>@C['fg'], :width=>3, :tag=>'I2_2')
-
- # Match stick
- TkcLine.new(@canvas, [679, 356, 679, 360, 717, 360, 717, 356, 679, 356],
- :fill=>@C['fg'], :width=>3, :tag=>'I2_3')
-
- # Match head
- TkcPolygon.new(@canvas,
- [ 671, 352, 677.4, 353.9, 680, 358.5, 677.4, 363.1,
- 671, 365, 664.6, 363.1, 662, 358.5, 664.6, 353.9 ],
- :fill=>color, :outline=>color, :tag=>'I2_4')
- end
-
- def move2(step = nil)
- step = get_step(2, step)
-
- stages = [0, 0, 1, 2, 0, 2, 1, 0, 1, 2, 0, 2, 1]
- xy = []
- xy[0] = [
- 686, 333, 692, 323, 682, 316, 674, 309, 671, 295, 668, 307,
- 662, 318, 662, 328, 671, 336
- ]
- xy[1] = [
- 687, 331, 698, 322, 703, 295, 680, 320, 668, 297, 663, 311,
- 661, 327, 671, 335
- ]
- xy[2] = [
- 686, 331, 704, 322, 688, 300, 678, 283, 678, 283, 674, 298,
- 666, 309, 660, 324, 672, 336
- ]
-
- if step >= stages.length
- @canvas.delete('I2')
- return 0
- end
-
- if step == 0 # Rotate the match
- beta = 20
-
- ox, oy = anchor('I2_0', :s) # Where to pivot
-
- i = 0
- until @canvas.find_withtag("I2_#{i}").empty?
- rotate_item("I2_#{i}", ox, oy, beta)
- i += 1
- end
-
- # For the flame
- TkcPolygon.new(@canvas, [], :tag=>'I2', :smooth=>true, :fill=>@C['2'])
-
- return 1
- end
- @canvas.coords('I2', xy[stages[step]])
- return ((step == 7)? 3: 1)
- end
-
- # Weight and pulleys
- def draw3
- color = @C['3a']
- color2 = @C['3b']
-
- xy = [ [602, 296], [577, 174], [518, 174] ]
- xy.each{|x, y| # 3 Pulleys
- TkcOval.new(@canvas, box(x, y, 13),
- :fill=>color, :outline=>@C['fg'], :width=>3)
- TkcOval.new(@canvas, box(x, y, 2), :fill=>@C['fg'], :outline=>@C['fg'])
- }
-
- # Wall to flame
- TkcLine.new(@canvas, [750, 309, 670, 309], :tag=>'I3_s',
- :width=>3, :fill=>@C['fg'], :smooth=>true)
-
- # Flame to pulley 1
- TkcLine.new(@canvas, [670, 309, 650, 309], :tag=>'I3_0',
- :width=>3, :fill=>@C['fg'], :smooth=>true)
- TkcLine.new(@canvas, [650, 309, 600, 309], :tag=>'I3_1',
- :width=>3, :fill=>@C['fg'], :smooth=>true)
-
- # Pulley 1 half way to 2
- TkcLine.new(@canvas, [589, 296, 589, 235], :tag=>'I3_2',
- :width=>3, :fill=>@C['fg'])
-
- # Pulley 1 other half to 2
- TkcLine.new(@canvas, [589, 235, 589, 174], :width=>3, :fill=>@C['fg'])
-
- # Across the top
- TkcLine.new(@canvas, [577, 161, 518, 161], :width=>3, :fill=>@C['fg'])
-
- # Down to weight
- TkcLine.new(@canvas, [505, 174, 505, 205], :tag=>'I3_w',
- :width=>3, :fill=>@C['fg'])
-
- # Draw the weight as 2 circles, two rectangles and 1 rounded rectangle
- x1, y1, x2, y2 = [515, 207, 495, 207]
- TkcOval.new(@canvas, box(x1, y1, 6),
- :tag=>'I3_', :fill=>color2, :outline=>color2)
- TkcOval.new(@canvas, box(x2, y2, 6),
- :tag=>'I3_', :fill=>color2, :outline=>color2)
- TkcRectangle.new(@canvas, x1, y1 - 6, x2, y2 + 6,
- :tag=>'I3_', :fill=>color2, :outline=>color2)
-
- TkcPolygon.new(@canvas, round_rect([492, 220, 518, 263], 15),
- :smooth=>true, :tag=>'I3_', :fill=>color2, :outline=>color2)
-
- TkcLine.new(@canvas, [500, 217, 511, 217],
- :tag=>'I3_', :fill=>color2, :width=>10)
-
- # Bottom weight target
- TkcLine.new(@canvas, [502, 393, 522, 393, 522, 465],
- :tag=>'I3__', :fill=>@C['fg'], :joinstyle=>:miter, :width=>10)
- end
-
- def move3(step = nil)
- step = get_step(3, step)
-
- pos = [ [505, 247], [505, 297], [505, 386.5], [505, 386.5] ]
- rope = []
- rope[0] = [750, 309, 729, 301, 711, 324, 690, 300]
- rope[1] = [750, 309, 737, 292, 736, 335, 717, 315, 712, 320]
- rope[2] = [750, 309, 737, 309, 740, 343, 736, 351, 725, 340]
- rope[3] = [750, 309, 738, 321, 746, 345, 742, 356]
-
- return 0 if step >= pos.length
-
- @canvas.delete("I3_#{step}") # Delete part of the rope
- move_abs('I3_', pos[step]) # Move weight down
- @canvas.coords('I3_s', rope[step]) # Flapping rope end
- @canvas.coords('I3_w', [505, 174].concat(pos[step]))
- if step == 2
- @canvas.move('I3__', 0, 30)
- return 2
- end
- return 1
- end
-
- # Cage and door
- def draw4
- color = @C['4']
- x0, y0, x1, y1 = [527, 356, 611, 464]
-
- # Horizontal bars
- y0.step(y1, 12){|y|
- TkcLine.new(@canvas, [x0, y, x1, y], :fill=>color, :width=>1)
- }
-
- # Vertical bars
- x0.step(x1, 12){|x|
- TkcLine.new(@canvas, [x, y0, x, y1], :fill=>color, :width=>1)
- }
-
- # Swing gate
- TkcLine.new(@canvas, [518, 464, 518, 428],
- :tag=>'I4', :fill=>color, :width=>1)
- end
-
- def move4(step = nil)
- step = get_step(4, step)
-
- angles = [-10, -20, -30, -30]
- return 0 if step >= angles.length
-
- rotate_item('I4', 518, 464, angles[step])
- @canvas.raise('I4')
-
- return((step == 3)? 3: 1)
- end
-
- # Mouse
- def draw5
- color = @C['5a']
- color2 = @C['5b']
-
- xy = [377, 248, 410, 248, 410, 465, 518, 465] # Mouse course
- xy.concat [518, 428, 451, 428, 451, 212, 377, 212]
-
- TkcPolygon.new(@canvas, xy, :fill=>color2, :outline=>@C['fg'], :width=>3)
-
- xy = [
- 534.5, 445.5, 541, 440, 552, 436, 560, 436, 569, 440, 574, 446,
- 575, 452, 574, 454, 566, 456, 554, 456, 545, 456, 537, 454, 530, 452
- ]
- TkcPolygon.new(@canvas, xy, :tag=>['I5', 'I5_0'], :fill=>color)
-
- TkcLine.new(@canvas, [573, 452, 592, 458, 601, 460, 613, 456], # Tail
- :tag=>['I5', 'I5_1'], :fill=>color, :smooth=>true, :width=>3)
-
- xy = box(540, 446, 2) # Eye
- xy = [540, 444, 541, 445, 541, 447, 540, 448, 538, 447, 538, 445]
- TkcPolygon.new(@canvas, xy, :tag=>['I5', 'I5_2'], :fill=>@C['bg'],
- :outline=>'', :smooth=>true)
-
- xy = [538, 454, 535, 461] # Front leg
- TkcLine.new(@canvas, xy, :tag=>['I5', 'I5_3'], :fill=>color, :width=>2)
-
- xy = [566, 455, 569, 462] # Back leg
- TkcLine.new(@canvas, xy, :tag=>['I5', 'I5_4'], :fill=>color, :width=>2)
-
- xy = [544, 455, 545, 460] # 2nd front leg
- TkcLine.new(@canvas, xy, :tag=>['I5', 'I5_5'], :fill=>color, :width=>2)
-
- xy = [560, 455, 558, 460] # 2nd back leg
- TkcLine.new(@canvas, xy, :tag=>['I5', 'I5_6'], :fill=>color, :width=>2)
- end
-
- def move5(step = nil)
- step = get_step(5, step)
-
- pos = [
- [553, 452], [533, 452], [513, 452], [493, 452], [473, 452],
- [463, 442, 30], [445.5, 441.5, 30], [425.5, 434.5, 30], [422, 414],
- [422, 394], [422, 374], [422, 354], [422, 334], [422, 314], [422, 294],
- [422, 274, -30], [422, 260.5, -30, :x], [422.5, 248.5, -28], [425, 237]
- ]
-
- return 0 if step >= pos.length
-
- x, y, beta, nxt = pos[step]
- move_abs('I5', [x, y])
- if beta
- ox, oy = centroid('I5_0')
- (0..6).each{|id| rotate_item("I5_#{id}", ox, oy, beta) }
- end
- return 3 if nxt == :x
- return 1
- end
-
- # Dropping gumballs
- def draw6
- color = @C['6']
- xy = [324, 130, 391, 204] # Ball holder
- xy = round_rect(xy, 10)
- TkcPolygon.new(@canvas, xy, :smooth=>true,
- :outline=>@C['fg'], :width=>3, :fill=>color)
- xy = [339, 204, 376, 253] # Below the ball holder
- TkcRectangle.new(@canvas, xy, :outline=>@C['fg'], :width=>3,
- :fill=>color, :tag=>'I6c')
- xy = box(346, 339, 28)
- TkcOval.new(@canvas, xy, :fill=>color, :outline=>'') # Roter
- TkcArc.new(@canvas, xy, :outline=>@C['fg'], :width=>2, :style=>:arc,
- :start=>80, :extent=>205)
- TkcArc.new(@canvas, xy, :outline=>@C['fg'], :width=>2, :style=>:arc,
- :start=>-41, :extent=>85)
-
- xy = box(346, 339, 15) # Center of rotor
- TkcOval.new(@canvas, xy, :outline=>@C['fg'], :fill=>@C['fg'], :tag=>'I6m')
- xy = [352, 312, 352, 254, 368, 254, 368, 322] # Top drop to rotor
- TkcPolygon.new(@canvas, xy, :fill=>color, :outline=>'')
- TkcLine.new(@canvas, xy, :fill=>@C['fg'], :width=>2)
-
- xy = [353, 240, 367, 300] # Poke bottom hole
- TkcRectangle.new(@canvas, xy, :fill=>color, :outline=>'')
- xy = [341, 190, 375, 210] # Poke another hole
- TkcRectangle.new(@canvas, xy, :fill=>color, :outline=>'')
-
- xy = [
- 368, 356, 368, 403, 389, 403, 389, 464, 320, 464, 320, 403,
- 352, 403, 352, 366
- ]
- TkcPolygon.new(@canvas, xy, :fill=>color, :outline=>'',
- :width=>2) # Below rotor
- TkcLine.new(@canvas, xy, :fill=>@C['fg'], :width=>2)
- xy = box(275, 342, 7) # On/off rotor
- TkcOval.new(@canvas, xy, :outline=>@C['fg'], :fill=>@C['fg'])
- xy = [276, 334, 342, 325] # Fan belt top
- TkcLine.new(@canvas, xy, :fill=>@C['fg'], :width=>3)
- xy = [276, 349, 342, 353] # Fan belt bottom
- TkcLine.new(@canvas, xy, :fill=>@C['fg'], :width=>3)
-
- xy = [337, 212, 337, 247] # What the mouse pushes
- TkcLine.new(@canvas, xy, :fill=>@C['fg'], :width=>3, :tag=>'I6_')
- xy = [392, 212, 392, 247]
- TkcLine.new(@canvas, xy, :fill=>@C['fg'], :width=>3, :tag=>'I6_')
- xy = [337, 230, 392, 230]
- TkcLine.new(@canvas, xy, :fill=>@C['fg'], :width=>7, :tag=>'I6_')
-
- who = -1 # All the balls
- colors = %w(red cyan orange green blue darkblue)
- colors *= 3
-
- (0..16).each{|i|
- loc = -i
- color = colors[i]
- x, y = @XY6["#{loc}"]
- TkcOval.new(@canvas, box(x, y, 5),
- :fill=>color, :outline=>color, :tag=>"I6_b#{i}")
- }
- draw6a(12) # The wheel
- end
-
- def draw6a(beta)
- @canvas.delete('I6_0')
- ox, oy = [346, 339]
- (0..3).each{|i|
- b = beta + i * 45
- x, y = rotate_c(28, 0, 0, 0, b)
- xy = [ox + x, oy + y, ox - x, oy - y]
- TkcLine.new(@canvas, xy, :tag=>'I6_0', :fill=>@C['fg'], :width=>2)
- }
- end
-
- def move6(step = nil)
- step = get_step(6, step)
-
- return 0 if step > 62
-
- if step < 2 # Open gate for balls to drop
- @canvas.move('I6_', -7, 0)
- if step == 1 # Poke a hole
- xy = [348, 226, 365, 240]
- TkcRectangle.new(@canvas, xy, :fill=>@canvas.itemcget('I6c', :fill),
- :outline=>'')
- end
- return 1
- end
-
- s = step - 1 # Do the gumball drop dance
- (0..(((s - 1)/3).to_i)).each{|i|
- tag = "I6_b#{i}"
- break if @canvas.find_withtag(tag).empty?
- loc = s - 3*i
-
- if @XY6["#{loc},#{i}"]
- move_abs(tag, @XY6["#{loc},#{i}"])
- elsif @XY6["#{loc}"]
- move_abs(tag, @XY6["#{loc}"])
- end
- }
- if s % 3 == 1
- first = (s + 2)/3
- i = first
- loop {
- tag = "I6_b#{i}"
- break if @canvas.find_withtag(tag).empty?
- loc = first - i
- move_abs(tag, @XY6["#{loc}"])
- i += 1
- }
- end
- if s >= 3 # Rotate the motor
- idx = s % 3
- draw6a(12 + s * 15)
- end
- return((s == 3)? 3 : 1)
- end
-
- # On/off switch
- def draw7
- color = @C['7']
- xy = [198, 306, 277, 374] # Box
- TkcRectangle.new(@canvas, xy, :outline=>@C['fg'], :width=>2,
- :fill=>color, :tag=>'I7z')
- @canvas.lower('I7z')
- xy = [275, 343, 230, 349]
- TkcLine.new(@canvas, xy, :tag=>'I7', :fill=>@C['fg'], :arrow=>:last,
- :arrowshape=>[23, 23, 8], :width=>6)
- xy = [225, 324] # On button
- x, y = xy
- TkcOval.new(@canvas, box(x, y, 3), :fill=>@C['fg'], :outline=>@C['fg'])
- xy = [218, 323] # On text
- font = ['Times Roman', 8]
- TkcText.new(@canvas, xy, :text=>'on', :anchor=>:e,
- :fill=>@C['fg'], :font=>font)
- xy = [225, 350] # Off button
- x, y = xy
- TkcOval.new(@canvas, box(x, y, 3), :fill=>@C['fg'], :outline=>@C['fg'])
- xy = [218, 349] # Off text
- TkcText.new(@canvas, xy, :text=>'off', :anchor=>:e,
- :fill=>@C['fg'], :font=>font)
- end
-
- def move7(step = nil)
- step = get_step(7, step)
-
- numsteps = 30
- return 0 if step > numsteps
- beta = 30.0 / numsteps
- rotate_item('I7', 275, 343, beta)
-
- return((step == numsteps)? 3: 1)
- end
-
- # Electricity to the fan
- def draw8
- sine([271, 248, 271, 306], 5, 8, :tag=>'I8_s', :fill=>@C['8'], :width=>3)
- end
-
- def move8(step = nil)
- step = get_step(8, step)
-
- return 0 if step > 3
- if step == 0
- sparkle(anchor('I8_s', :s), 'I8')
- return 1
- elsif step == 1
- move_abs('I8', anchor('I8_s', :c))
- elsif step == 2
- move_abs('I8', anchor('I8_s', :n))
- else
- @canvas.delete('I8')
- end
- return((step == 2)? 3: 1)
- end
-
- # Fan
- def draw9
- color = @C['9']
- xy = [266, 194, 310, 220]
- TkcOval.new(@canvas, xy, :outline=>color, :fill=>color)
- xy = [280, 209, 296, 248]
- TkcOval.new(@canvas, xy, :outline=>color, :fill=>color)
- xy = [
- 288, 249, 252, 249, 260, 240, 280, 234,
- 296, 234, 316, 240, 324, 249, 288, 249
- ]
- TkcPolygon.new(@canvas, xy, :fill=>color, :smooth=>true)
-
- xy = [248, 205, 265, 214, 264, 205, 265, 196] # Spinner
- TkcPolygon.new(@canvas, xy, :fill=>color)
-
- xy = [255, 206, 265, 234] # Fan blades
- TkcOval.new(@canvas, xy, :fill=>'', :outline=>@C['fg'],
- :width=>3, :tag=>'I9_0')
- xy = [255, 176, 265, 204]
- TkcOval.new(@canvas, xy, :fill=>'', :outline=>@C['fg'],
- :width=>3, :tag=>'I9_0')
- xy = [255, 206, 265, 220]
- TkcOval.new(@canvas, xy, :fill=>'', :outline=>@C['fg'],
- :width=>1, :tag=>'I9_1')
- xy = [255, 190, 265, 204]
- TkcOval.new(@canvas, xy, :fill=>'', :outline=>@C['fg'],
- :width=>1, :tag=>'I9_1')
- end
-
- def move9(step = nil)
- step = get_step(9, step)
-
- if (step & 1).nonzero?
- @canvas.itemconfigure('I9_0', :width=>4)
- @canvas.itemconfigure('I9_1', :width=>1)
- @canvas.lower('I9_1', 'I9_0')
- else
- @canvas.itemconfigure('I9_0', :width=>1)
- @canvas.itemconfigure('I9_1', :width=>4)
- @canvas.lower('I9_0', 'I9_1')
- end
- return 3 if step == 0
- return 1
- end
-
- # Boat
- def draw10
- color = @C['10a']
- color2 = @C['10b']
- xy = [191, 230, 233, 230, 233, 178, 191, 178] # Sail
- TkcPolygon.new(@canvas, xy, :fill=>color, :width=>3, :outline=>@C['fg'],
- :tag=>'I10')
- xy = box(209, 204, 31) # Front
- TkcArc.new(@canvas, xy, :outline=>'', :fill=>color, :style=>:pie,
- :start=>120, :extent=>120, :tag=>'I10')
- TkcArc.new(@canvas, xy, :outline=>@C['fg'], :width=>3, :style=>:arc,
- :start=>120, :extent=>120, :tag=>'I10')
- xy = box(249, 204, 31) # Back
- TkcArc.new(@canvas, xy, :outline=>'', :fill=>@C['bg'], :width=>3,
- :style=>:pie, :start=>120, :extent=>120, :tag=>'I10')
- TkcArc.new(@canvas, xy, :outline=>@C['fg'], :width=>3, :style=>:arc,
- :start=>120, :extent=>120, :tag=>'I10')
-
- xy = [200, 171, 200, 249] # Mast
- TkcLine.new(@canvas, xy, :fill=>@C['fg'], :width=>3, :tag=>'I10')
- xy = [159, 234, 182, 234] # Bow sprit
- TkcLine.new(@canvas, xy, :fill=>@C['fg'], :width=>3, :tag=>'I10')
- xy = [180, 234, 180, 251, 220, 251] # Hull
- TkcLine.new(@canvas, xy, :fill=>@C['fg'], :width=>6, :tag=>'I10')
-
- xy = [92, 255, 221, 255] # Waves
- sine(xy, 2, 25, :fill=>color2, :width=>1, :tag=>'I10w')
-
- xy = @canvas.coords('I10w')[4..-5] # Water
- xy.concat([222, 266, 222, 277, 99, 277])
- TkcPolygon.new(@canvas, xy, :fill=>color2, :outline=>color2)
- xy = [222, 266, 222, 277, 97, 277, 97, 266] # Water bottom
- TkcLine.new(@canvas, xy, :fill=>@C['fg'], :width=>3)
-
- xy = box(239, 262, 17)
- TkcArc.new(@canvas, xy, :outline=>@C['fg'], :width=>3, :style=>:arc,
- :start=>95, :extent=>103)
- xy = box(76, 266, 21)
- TkcArc.new(@canvas, xy, :outline=>@C['fg'], :width=>3, :style=>:arc,
- :extent=>190)
- end
-
- def move10(step = nil)
- step = get_step(10, step)
-
- pos = [
- [195, 212], [193, 212], [190, 212], [186, 212], [181, 212], [176, 212],
- [171, 212], [166, 212], [161, 212], [156, 212], [151, 212], [147, 212],
- [142, 212], [137, 212], [132, 212, :x], [127, 212], [121, 212],
- [116, 212], [111, 212]
- ]
-
- return 0 if step >= pos.length
-
- where = pos[step]
- move_abs('I10', where)
-
- return 3 if where[2] == :x
- return 1
- end
-
- # 2nd ball drop
- def draw11
- color = @C['11a']
- color2 = @C['11b']
- xy = [23, 264, 55, 591] # Color the down tube
- TkcRectangle.new(@canvas, xy, :fill=>color, :outline=>'')
- xy = box(71, 460, 48) # Color the outer loop
- TkcOval.new(@canvas, xy, :fill=>color, :outline=>'')
-
- xy = [55, 264, 55, 458] # Top right side
- TkcLine.new(@canvas, xy, :fill=>@C['fg'], :width=>3)
- xy = [55, 504, 55, 591] # Bottom right side
- TkcLine.new(@canvas, xy, :fill=>@C['fg'], :width=>3)
- xy = box(71, 460, 48) # Outer loop
- TkcArc.new(@canvas, xy, :outline=>@C['fg'], :width=>3, :style=>:arc,
- :start=>110, :extent=>-290, :tag=>'I11i')
- xy = box(71, 460, 16) # Inner loop
- TkcOval.new(@canvas, xy, :outline=>@C['fg'], :fill=>'',
- :width=>3, :tag=>'I11i')
- TkcOval.new(@canvas, xy, :outline=>@C['fg'], :fill=>@C['bg'], :width=>3)
-
- xy = [23, 264, 23, 591] # Left side
- TkcLine.new(@canvas, xy, :fill=>@C['fg'], :width=>3)
- xy = box(1, 266, 23) # Top left curve
- TkcArc.new(@canvas, xy, :outline=>@C['fg'], :width=>3,
- :style=>:arc, :extent=>90)
-
- xy = box(75, 235, 9) # The ball
- TkcOval.new(@canvas, xy, :fill=>color2, :outline=>'',
- :width=>3, :tag=>'I11')
- end
-
- def move11(step = nil)
- step = get_step(11, step)
-
- pos = [
- [75, 235], [70, 235], [65, 237], [56, 240], [46, 247], [38, 266],
- [38, 296], [38, 333], [38, 399], [38, 475], [74, 496], [105, 472],
- [100, 437], [65, 423], [-100, -100], [38, 505], [38, 527, :x], [38, 591]
- ]
-
- return 0 if step >= pos.length
- where = pos[step]
- move_abs('I11', where)
- return 3 if where[2] == :x
- return 1
- end
-
- # Hand
- def draw12
- xy = [
- 20, 637, 20, 617, 20, 610, 20, 590, 40, 590, 40, 590,
- 60, 590, 60, 610, 60, 610
- ]
- xy.concat([60, 610, 65, 620, 60, 631]) # Thumb
- xy.concat([60, 631, 60, 637, 60, 662, 60, 669, 52, 669,
- 56, 669, 50, 669, 50, 662, 50, 637])
-
- y0 = 637 # Bumps for fingers
- y1 = 645
- 50.step(21, -10){|x|
- x1 = x - 5
- x2 = x - 10
- xy << x << y0 << x1 << y1 << x2 << y0
- }
- TkcPolygon.new(@canvas, xy, :fill=>@C['12'], :outline=>@C['fg'],
- :smooth=>true, :tag=>'I12', :width=>3)
- end
-
- def move12(step = nil)
- step = get_step(12, step)
-
- pos = [[42.5, 641, :x]]
- return 0 if step >= pos.length
- where = pos[step]
- move_abs('I12', where)
- return 3 if where[2] == :x
- return 1
- end
-
- # Fax
- def draw13
- color = @C['13a']
- xy = [86, 663, 149, 663, 149, 704, 50, 704, 50, 681, 64, 681, 86, 671]
- xy2 = [
- 784, 663, 721, 663, 721, 704, 820, 704, 820, 681, 806, 681, 784, 671
- ]
- radii = [2, 9, 9, 8, 5, 5, 2]
-
- round_poly(@canvas, xy, radii, :width=>3,
- :outline=>@C['fg'], :fill=>color)
- round_poly(@canvas, xy2, radii, :width=>3,
- :outline=>@C['fg'], :fill=>color)
-
- xy = [56, 677]
- x, y = xy
- TkcRectangle.new(@canvas, box(x, y, 4), :fill=>'', :outline=>@C['fg'],
- :width=>3, :tag=>'I13')
- xy = [809, 677]
- x, y = xy
- TkcRectangle.new(@canvas, box(x, y, 4), :fill=>'', :outline=>@C['fg'],
- :width=>3, :tag=>'I13R')
-
- xy = [112, 687] # Label
- TkcText.new(@canvas, xy, :text=>'FAX', :fill=>@C['fg'],
- :font=>['Times Roman', 12, :bold])
- xy = [762, 687]
- TkcText.new(@canvas, xy, :text=>'FAX', :fill=>@C['fg'],
- :font=>['Times Roman', 12, :bold])
-
- xy = [138, 663, 148, 636, 178, 636] # Paper guide
- TkcLine.new(@canvas, xy, :smooth=>true, :fill=>@C['fg'], :width=>3)
- xy = [732, 663, 722, 636, 692, 636]
- TkcLine.new(@canvas, xy, :smooth=>true, :fill=>@C['fg'], :width=>3)
-
- sine([149, 688, 720, 688], 5, 15,
- :tag=>'I13_s', :fill=>@C['fg'], :width=>3)
- end
-
- def move13(step = nil)
- step = get_step(13, step)
-
- numsteps = 7
-
- if step == numsteps + 2
- move_abs('I13_star', [-100, -100])
- @canvas.itemconfigure('I13R', :fill=>@C['13b'], :width=>2)
- return 2
- end
- if step == 0 # Button down
- @canvas.delete('I13')
- sparkle([-100, -100], 'I13_star') # Create off screen
- return 1
- end
- x0, y0 = anchor('I13_s', :w)
- x1, y1 = anchor('I13_s', :e)
- x = x0 + (x1 - x0) * (step - 1) / numsteps.to_f
- move_abs('I13_star', [x, y0])
- return 1
- end
-
- # Paper in fax
- def draw14
- color = @C['14']
- xy = [102, 661, 113, 632, 130, 618] # Left paper edge
- TkcLine.new(@canvas, xy, :smooth=>true, :fill=>color,
- :width=>3, :tag=>'I14L_0')
- xy = [148, 629, 125, 640, 124, 662] # Right paper edge
- TkcLine.new(@canvas, xy, :smooth=>true, :fill=>color,
- :width=>3, :tag=>'I14L_1')
- draw14a('L')
-
- xy = [
- 768.0, 662.5, 767.991316225, 662.433786215, 767.926187912, 662.396880171
- ]
- TkcLine.new(@canvas, xy, :smooth=>true, :fill=>color,
- :width=>3, :tag=>'I14R_0')
- @canvas.lower('I14R_0')
- # NB. these numbers are VERY sensitive, you must start with final size
- # and shrink down to get the values
- xy = [
- 745.947897349, 662.428358855, 745.997829056, 662.452239237, 746.0, 662.5
- ]
- TkcLine.new(@canvas, xy, :smooth=>true, :fill=>color,
- :width=>3, :tag=>'I14R_1')
- @canvas.lower('I14R_1')
- end
-
- def draw14a(side)
- color = @C['14']
- xy = @canvas.coords("I14#{side}_0")
- xy2 = @canvas.coords("I14#{side}_1")
- x0, y0, x1, y1, x2, y2 = xy
- x3, y3, x4, y4, x5, y5 = xy2
-
- zz = [
- x0, y0, x0, y0, xy, x2, y2, x2, y2,
- x3, y3, x3, y3, xy2, x5, y5, x5, y5
- ].flatten
- @canvas.delete("I14#{side}")
- TkcPolygon.new(@canvas, zz, :tag=>"I14#{side}", :smooth=>true,
- :fill=>color, :outline=>color, :width=>3)
- @canvas.lower("I14#{side}")
- end
-
- def move14(step = nil)
- step = get_step(14, step)
-
- # Paper going down
- sc = 0.9 - 0.05*step
- if sc < 0.3
- @canvas.delete('I14L')
- return 0
- end
-
- ox, oy = @canvas.coords('I14L_0')
- @canvas.scale('I14L_0', ox, oy, sc, sc)
- ox, oy = @canvas.coords('I14L_1')[-2..-1]
- @canvas.scale('I14L_1', ox, oy, sc, sc)
- draw14a('L')
-
- # Paper going up
- sc = 0.35 + 0.05*step
- sc = 1/sc
-
- ox, oy = @canvas.coords('I14R_0')
- @canvas.scale('I14R_0', ox, oy, sc, sc)
- ox, oy = @canvas.coords('I14R_1')[-2..-1]
- @canvas.scale('I14R_1', ox, oy, sc, sc)
- draw14a('R')
-
- return((step == 10)? 3: 1)
- end
-
- # Light beam
- def draw15
- color = @C['15a']
- xy = [824, 599, 824, 585, 820, 585, 829, 585]
- TkcLine.new(@canvas, xy, :fill=>@C['fg'], :width=>3, :tag=>'I15a')
- xy = [789, 599, 836, 643]
- TkcRectangle.new(@canvas, xy, :fill=>color, :outline=>@C['fg'], :width=>3)
- xy = [778, 610, 788, 632]
- TkcRectangle.new(@canvas, xy, :fill=>color, :outline=>@C['fg'], :width=>3)
- xy = [766, 617, 776, 625]
- TkcRectangle.new(@canvas, xy, :fill=>color, :outline=>@C['fg'], :width=>3)
-
- xy = [633, 600, 681, 640]
- TkcRectangle.new(@canvas, xy, :fill=>color, :outline=>@C['fg'], :width=>3)
- xy = [635, 567, 657, 599]
- TkcRectangle.new(@canvas, xy, :fill=>color, :outline=>@C['fg'], :width=>2)
- xy = [765, 557, 784, 583]
- TkcRectangle.new(@canvas, xy, :fill=>color, :outline=>@C['fg'], :width=>2)
-
- sine([658, 580, 765, 580], 3, 15,
- :tag=>'I15_s', :fill=>@C['fg'], :width=>3)
- end
-
- def move15a
- color = @C['15b']
- @canvas.scale('I15a', 824, 599, 1, 0.3) # Button down
- xy = [765, 621, 681, 621]
- TkcLine.new(@canvas, xy, :dash=>'-', :width=>3, :fill=>color, :tag=>'I15')
- end
-
- def move15(step = nil)
- step = get_step(15, step)
-
- numsteps = 6
-
- if step == numsteps + 2
- move_abs('I15_star', [-100, -100])
- return 2
- end
- if step == 0 # Break the light beam
- sparkle([-100, -100], 'I15_star')
- xy = [765, 621, 745, 621]
- @canvas.coords('I15', xy)
- return 1
- end
- x0, y0 = anchor('I15_s', :w)
- x1, y1 = anchor('I15_s', :e)
- x = x0 + (x1 - x0) * (step - 1) / numsteps.to_f
- move_abs('I15_star', [x, y0])
- return 1
- end
-
- # Bell
- def draw16
- color = @C['16']
- xy = [722, 485, 791, 556]
- TkcRectangle.new(@canvas, xy, :fill=>'', :outline=>@C['fg'], :width=>3)
- xy = box(752, 515, 25) # Bell
- TkcOval.new(@canvas, xy, :fill=>color, :outline=>'black',
- :tag=>'I16b', :width=>2)
- xy = box(752, 515, 5) # Bell button
- TkcOval.new(@canvas, xy, :fill=>'black', :outline=>'black', :tag=>'I16b')
-
- xy = [784, 523, 764, 549] # Clapper
- TkcLine.new(@canvas, xy, :width=>3, :tag=>'I16c', :fill=>@C['fg'])
- xy = box(784, 523, 4)
- TkcOval.new(@canvas, xy, :fill=>@C['fg'], :outline=>@C['fg'], :tag=>'I16d')
- end
-
- def move16(step = nil)
- step = get_step(16, step)
-
- # Note: we never stop
- ox, oy = [760, 553]
- if (step & 1).nonzero?
- beta = 12
- @canvas.move('I16b', 3, 0)
- else
- beta = -12
- @canvas.move('I16b', -3, 0)
- end
- rotate_item('I16c', ox, oy, beta)
- rotate_item('I16d', ox, oy, beta)
-
- return ((step == 1)? 3: 1)
- end
-
- # Cat
- def draw17
- color = @C['17']
-
- xy = [584, 556, 722, 556]
- TkcLine.new(@canvas, xy, :fill=>@C['fg'], :width=>3)
- xy = [584, 485, 722, 485]
- TkcLine.new(@canvas, xy, :fill=>@C['fg'], :width=>3)
-
- xy = [664, 523, 717, 549] # Body
- TkcArc.new(@canvas, xy, :outline=>@C['fg'], :fill=>color, :width=>3,
- :style=>:chord, :start=>128, :extent=>260, :tag=>'I17')
-
- xy = [709, 554, 690, 543] # Paw
- TkcOval.new(@canvas, xy, :outline=>@C['fg'], :fill=>color,
- :width=>3, :tag=>'I17')
- xy = [657, 544, 676, 555]
- TkcOval.new(@canvas, xy, :outline=>@C['fg'], :fill=>color,
- :width=>3, :tag=>'I17')
-
- xy = box(660, 535, 15) # Lower face
- TkcArc.new(@canvas, xy, :outline=>@C['fg'], :width=>3, :style=>:arc,
- :start=>150, :extent=>240, :tag=>'I17_')
- TkcArc.new(@canvas, xy, :outline=>'', :fill=>color, :width=>1,
- :style=>:chord, :start=>150, :extent=>240, :tag=>'I17_')
- xy = [674, 529, 670, 513, 662, 521, 658, 521, 650, 513, 647, 529] # Ears
- TkcLine.new(@canvas, xy, :fill=>@C['fg'], :width=>3, :tag=>'I17_')
- TkcPolygon.new(@canvas, xy, :fill=>color, :outline=>'', :width=>1,
- :tag=>['I17_', 'I17_c'])
- xy = [652, 542, 628, 539] # Whiskers
- TkcLine.new(@canvas, xy, :fill=>@C['fg'], :width=>3, :tag=>'I17_')
- xy = [652, 543, 632, 545]
- TkcLine.new(@canvas, xy, :fill=>@C['fg'], :width=>3, :tag=>'I17_')
- xy = [652, 546, 632, 552]
- TkcLine.new(@canvas, xy, :fill=>@C['fg'], :width=>3, :tag=>'I17_')
-
- xy = [668, 543, 687, 538]
- TkcLine.new(@canvas, xy, :fill=>@C['fg'], :width=>3,
- :tag=>['I17_', 'I17_w'])
- xy = [668, 544, 688, 546]
- TkcLine.new(@canvas, xy, :fill=>@C['fg'], :width=>3,
- :tag=>['I17_', 'I17_w'])
- xy = [668, 547, 688, 553]
- TkcLine.new(@canvas, xy, :fill=>@C['fg'], :width=>3,
- :tag=>['I17_', 'I17_w'])
-
- xy = [649, 530, 654, 538, 659, 530] # Left eye
- TkcLine.new(@canvas, xy, :fill=>@C['fg'], :width=>2,
- :smooth=>true, :tag=>'I17')
- xy = [671, 530, 666, 538, 661, 530] # Right eye
- TkcLine.new(@canvas, xy, :fill=>@C['fg'], :width=>2,
- :smooth=>true, :tag=>'I17')
- xy = [655, 543, 660, 551, 665, 543] # Mouth
- TkcLine.new(@canvas, xy, :fill=>@C['fg'], :width=>2,
- :smooth=>true, :tag=>'I17')
- end
-
- def move17(step = nil)
- step = get_step(17, step)
-
- if step == 0
- @canvas.delete('I17') # Delete most of the cat
- xy = [655, 543, 660, 535, 665, 543] # Mouth
- TkcLine.new(@canvas, xy, :fill=>@C['fg'], :width=>3,
- :smooth=>true, :tag=>'I17_')
- xy = box(654, 530, 4) # Left eye
- TkcOval.new(@canvas, xy, :outline=>@C['fg'], :width=>3, :fill=>'',
- :tag=>'I17_')
- xy = box(666, 530, 4) # Right eye
- TkcOval.new(@canvas, xy, :outline=>@C['fg'], :width=>3, :fill=>'',
- :tag=>'I17_')
-
- @canvas.move('I17_', 0, -20) # Move face up
- xy = [652, 528, 652, 554] # Front leg
- TkcLine.new(@canvas, xy, :fill=>@C['fg'], :width=>3, :tag=>'I17_')
- xy = [670, 528, 670, 554] # 2nd front leg
- TkcLine.new(@canvas, xy, :fill=>@C['fg'], :width=>3, :tag=>'I17_')
-
- xy = [ # Body
- 675, 506, 694, 489, 715, 513, 715, 513, 715, 513, 716, 525,
- 716, 525, 716, 525, 706, 530, 695, 530, 679, 535, 668, 527,
- 668, 527, 668, 527, 675, 522, 676, 517, 677, 512
- ]
- TkcPolygon.new(@canvas, xy, :fill=>@canvas.itemcget('I17_c', :fill),
- :outline=>@C['fg'], :width=>3, :smooth=>true,
- :tag=>'I17_')
- xy = [716, 514, 716, 554] # Back leg
- TkcLine.new(@canvas, xy, :fill=>@C['fg'], :width=>3, :tag=>'I17_')
- xy = [694, 532, 694, 554] # 2nd back leg
- TkcLine.new(@canvas, xy, :fill=>@C['fg'], :width=>3, :tag=>'I17_')
- xy = [715, 514, 718, 506, 719, 495, 716, 488] # Tail
- TkcLine.new(@canvas, xy, :fill=>@C['fg'], :width=>3,
- :smooth=>true, :tag=>'I17_')
-
- @canvas.raise('I17w') # Make whiskers visible
- @canvas.move('I17_', -5, 0) # Move away from the wall a bit
- return 2
- end
- return 0
- end
-
- # Sling shot
- def draw18
- color = @C['18']
- xy = [721, 506, 627, 506] # Sling hold
- TkcLine.new(@canvas, xy, :width=>4, :fill=>@C['fg'], :tag=>'I18')
-
- xy = [607, 500, 628, 513] # Sling rock
- TkcOval.new(@canvas, xy, :fill=>color, :outline=>'', :tag=>'I18a')
-
- xy = [526, 513, 606, 507, 494, 502] # Sling band
- TkcLine.new(@canvas, xy, :fill=>@C['fg'], :width=>4, :tag=>'I18b')
- xy = [485, 490, 510, 540, 510, 575, 510, 540, 535, 491] # Sling
- TkcLine.new(@canvas, xy, :fill=>@C['fg'], :width=>6)
- end
-
- def move18(step = nil)
- step = get_step(18, step)
-
- pos = [
- [587, 506], [537, 506], [466, 506], [376, 506], [266, 506, :x],
- [136, 506], [16, 506], [-100, -100]
- ]
-
- b = []
- b[0] = [490, 502, 719, 507, 524, 512] # Band collapsing
- b[1] = [
- 491, 503, 524, 557, 563, 505, 559, 496, 546, 506, 551, 525,
- 553, 536, 538, 534, 532, 519, 529, 499
- ]
- b[2] = [
- 491, 503, 508, 563, 542, 533, 551, 526, 561, 539, 549, 550, 530, 500
- ]
- b[3] = [
- 491, 503, 508, 563, 530, 554, 541, 562, 525, 568, 519, 544, 530, 501
- ]
-
- return 0 if step >= pos.length
-
- if step == 0
- @canvas.delete('I18')
- @canvas.itemconfigure('I18b', :smooth=>true)
- end
- if b[step]
- @canvas.coords('I18b', b[step])
- end
-
- where = pos[step]
- move_abs('I18a', where)
- return 3 if where[2] == :x
- return 1
- end
-
- # Water pipe
- def draw19
- color = @C['19']
- xx = [[249, 181], [155, 118], [86, 55], [22, 0]]
- xx.each{|x1, x2|
- TkcRectangle.new(@canvas, x1, 453, x2, 467,
- :fill=>color, :outline=>'', :tag=>'I19')
- TkcLine.new(@canvas, x1, 453, x2, 453,
- :fill=>@C['fg'], :width=>1) # Pipe top
- TkcLine.new(@canvas, x1, 467, x2, 467,
- :fill=>@C['fg'], :width=>1) # Pipe bottom
- }
- @canvas.raise('I11i')
-
- xy = box(168, 460, 16) # Bulge by the joint
- TkcOval.new(@canvas, xy, :fill=>color, :outline=>'')
- TkcArc.new(@canvas, xy, :outline=>@C['fg'], :width=>1, :style=>:arc,
- :start=>21, :extent=>136)
- TkcArc.new(@canvas, xy, :outline=>@C['fg'], :width=>1, :style=>:arc,
- :start=>-21, :extent=>-130)
-
- xy = [249, 447, 255, 473] # First joint 26x6
- TkcRectangle.new(@canvas, xy, :fill=>color, :outline=>@C['fg'], :width=>1)
-
- xy = box(257, 433, 34) # Bend up
- TkcArc.new(@canvas, xy, :outline=>'', :fill=>color, :width=>1,
- :style=>:pie, :start=>0, :extent=>-91)
- TkcArc.new(@canvas, xy, :outline=>@C['fg'], :width=>1,
- :style=>:arc, :start=>0, :extent=>-90)
- xy = box(257, 433, 20)
- TkcArc.new(@canvas, xy, :outline=>'', :fill=>@C['bg'], :width=>1,
- :style=>:pie, :start=>0, :extent=>-92)
- TkcArc.new(@canvas, xy, :outline=>@C['fg'], :width=>1,
- :style=>:arc, :start=>0, :extent=>-90)
- xy = box(257, 421, 34) # Bend left
- TkcArc.new(@canvas, xy, :outline=>'', :fill=>color, :width=>1,
- :style=>:pie, :start=>0, :extent=>91)
- TkcArc.new(@canvas, xy, :outline=>@C['fg'], :width=>1,
- :style=>:arc, :start=>0, :extent=>90)
- xy = box(257, 421, 20)
- TkcArc.new(@canvas, xy, :outline=>'', :fill=>@C['bg'], :width=>1,
- :style=>:pie, :start=>0, :extent=>90)
- TkcArc.new(@canvas, xy, :outline=>@C['fg'], :width=>1,
- :style=>:arc, :start=>0, :extent=>90)
- xy = box(243, 421, 34) # Bend down
- TkcArc.new(@canvas, xy, :outline=>'', :fill=>color, :width=>1,
- :style=>:pie, :start=>90, :extent=>90)
- TkcArc.new(@canvas, xy, :outline=>@C['fg'], :width=>1,
- :style=>:arc, :start=>90, :extent=>90)
- xy = box(243, 421, 20)
- TkcArc.new(@canvas, xy, :outline=>'', :fill=>@C['bg'], :width=>1,
- :style=>:pie, :start=>90, :extent=>90)
- TkcArc.new(@canvas, xy, :outline=>@C['fg'], :width=>1,
- :style=>:arc, :start=>90, :extent=>90)
-
- xy = [270, 427, 296, 433] # 2nd joint bottom
- TkcRectangle.new(@canvas, xy, :fill=>color, :outline=>@C['fg'], :width=>1)
- xy = [270, 421, 296, 427] # 2nd joint top
- TkcRectangle.new(@canvas, xy, :fill=>color, :outline=>@C['fg'], :width=>1)
- xy = [249, 382, 255, 408] # Third joint right
- TkcRectangle.new(@canvas, xy, :fill=>color, :outline=>@C['fg'], :width=>1)
- xy = [243, 382, 249, 408] # Third joint left
- TkcRectangle.new(@canvas, xy, :fill=>color, :outline=>@C['fg'], :width=>1)
- xy = [203, 420, 229, 426] # Last joint
- TkcRectangle.new(@canvas, xy, :fill=>color, :outline=>@C['fg'], :width=>1)
-
- xy = box(168, 460, 6) # Handle joint
- TkcOval.new(@canvas, xy, :fill=>@C['fg'], :outline=>'', :tag=>'I19a')
- xy = [168, 460, 168, 512] # Handle bar
- TkcLine.new(@canvas, xy, :fill=>@C['fg'], :width=>5, :tag=>'I19b')
- end
-
- def move19(step = nil)
- step = get_step(19, step)
-
- angles = [30, 30, 30]
- return 2 if step == angles.length
- ox, oy = centroid('I19a')
- rotate_item('I19b', ox, oy, angles[step])
-
- return 1
- end
-
- # Water pouring
- def draw20
- # do nothing
- end
-
- def move20(step = nil)
- step = get_step(20, step)
-
- pos = [451, 462, 473, 484, 496, 504, 513, 523, 532]
- freq = [20, 40, 40, 40, 40, 40, 40, 40, 40]
- pos = [
- [451, 20], [462, 40], [473, 40], [484, 40], [496, 40],
- [504, 40], [513, 40], [523, 40], [532, 40, :x]
- ]
- return 0 if step >= pos.length
-
- @canvas.delete('I20')
- where = pos[step]
- y, f = where
- h20(y, f)
- return 3 if where[2] == :x
- return 1
- end
-
- def h20(y, f)
- color = @C['20']
- @canvas.delete('I20')
-
- sine([208, 428, 208, y], 4, f, :tag=>['I20', 'I20s'],
- :width=>3, :fill=>color, :smooth=>true)
- TkcLine.new(@canvas, @canvas.coords('I20s'), :width=>3,
- :fill=>color, :smooth=>1, :tag=>['I20', 'I20a'])
- TkcLine.new(@canvas, @canvas.coords('I20s'), :width=>3,
- :fill=>color, :smooth=>1, :tag=>['I20', 'I20b'])
- @canvas.move('I20a', 8, 0)
- @canvas.move('I20b', 16, 0)
- end
-
- # Bucket
- def draw21
- color = @C['21']
- xy = [217, 451, 244, 490] # Right handle
- TkcLine.new(@canvas, xy, :fill=>@C['fg'], :width=>2, :tag=>'I21_a')
- xy = [201, 467, 182, 490] # Left handle
- TkcLine.new(@canvas, xy, :fill=>@C['fg'], :width=>2, :tag=>'I21_a')
-
- xy = [245, 490, 237, 535] # Right side
- xy2 = [189, 535, 181, 490] # Left side
- TkcPolygon.new(@canvas, xy + xy2, :fill=>color, :outline=>'',
- :tag=>['I21', 'I21f'])
- TkcLine.new(@canvas, xy, :fill=>@C['fg'], :width=>2, :tag=>'I21')
- TkcLine.new(@canvas, xy2, :fill=>@C['fg'], :width=>2, :tag=>'I21')
-
- xy = [182, 486, 244, 498] # Top
- TkcOval.new(@canvas, xy, :fill=>color, :outline=>'', :width=>2,
- :tag=>['I21', 'I21f'])
- TkcOval.new(@canvas, xy, :fill=>'', :outline=>@C['fg'], :width=>2,
- :tag=>['I21', 'I21t'])
- xy = [189, 532, 237, 540] # Bottom
- TkcOval.new(@canvas, xy, :fill=>color, :outline=>@C['fg'], :width=>2,
- :tag=>['I21', 'I21b'])
- end
-
- def move21(step = nil)
- step = get_step(21, step)
-
- numsteps = 30
- return 0 if step >= numsteps
-
- x1, y1, x2, y2 = @canvas.coords('I21b')
- # lx1, ly1, lx2, ly2 = @canvas.coords('I21t')
- lx1, ly1, lx2, ly2 = [183, 492, 243, 504]
-
- f = step / numsteps.to_f
- y2 = y2 - 3
- xx1 = x1 + (lx1 - x1) * f
- yy1 = y1 + (ly1 - y1) * f
- xx2 = x2 + (lx2 - x2) * f
- yy2 = y2 + (ly2 - y2) * f
-
- @canvas.itemconfigure('I21b', :fill=>@C['20'])
- @canvas.delete('I21w')
- TkcPolygon.new(@canvas, x2, y2, x1, y1, xx1, yy1, xx2, yy1,
- :tag=>['I21', 'I21w'], :outline=>'', :fill=>@C['20'])
- @canvas.lower('I21w', 'I21')
- @canvas.raise('I21b')
- @canvas.lower('I21f')
-
- return((step == numsteps - 1)? 3: 1)
- end
-
- # Bucket drop
- def draw22
- # do nothing
- end
-
- def move22(step = nil)
- step = get_step(22, step)
- pos = [[213, 513], [213, 523], [213, 543, :x], [213, 583], [213, 593]]
-
- @canvas.itemconfigure('I21f', :fill=>@C['22']) if step == 0
- return 0 if step >= pos.length
- where = pos[step]
- move_abs('I21', where)
- h20(where[1], 40)
- @canvas.delete('I21_a') # Delete handles
-
- return 3 if where[2] == :x
- return 1
- end
-
- # Blow dart
- def draw23
- color = @C['23a']
- color2 = @C['23b']
- color3 = @C['23c']
-
- xy = [185, 623, 253, 650] # Block
- TkcRectangle.new(@canvas, xy, :fill=>'black', :outline=>@C['fg'],
- :width=>2, :tag=>'I23a')
- xy = [187, 592, 241, 623] # Balloon
- TkcOval.new(@canvas, xy, :outline=>'', :fill=>color, :tag=>'I23b')
- TkcArc.new(@canvas, xy, :outline=>@C['fg'], :width=>3, :tag=>'I23b',
- :style=>:arc, :start=>12, :extent=>336)
- xy = [239, 604, 258, 589, 258, 625, 239, 610] # Balloon nozzle
- TkcPolygon.new(@canvas, xy, :outline=>'', :fill=>color, :tag=>'I23b')
- TkcLine.new(@canvas, xy, :fill=>@C['fg'], :width=>3, :tag=>'I23b')
-
- xy = [285, 611, 250, 603] # Dart body
- TkcOval.new(@canvas, xy, :fill=>color2, :outline=>@C['fg'],
- :width=>3, :tag=>'I23d')
- xy = [249, 596, 249, 618, 264, 607, 249, 596] # Dart tail
- TkcPolygon.new(@canvas, xy, :fill=>color3, :outline=>@C['fg'],
- :width=>3, :tag=>'I23d')
- xy = [249, 607, 268, 607] # Dart detail
- TkcLine.new(@canvas, xy, :fill=>@C['fg'], :width=>3, :tag=>'I23d')
- xy = [285, 607, 305, 607] # Dart needle
- TkcLine.new(@canvas, xy, :fill=>@C['fg'], :width=>3, :tag=>'I23d')
- end
-
- def move23(step = nil)
- step = get_step(23, step)
-
- pos = [
- [277, 607], [287, 607], [307, 607, :x], [347, 607], [407, 607],
- [487, 607], [587, 607], [687, 607], [787, 607], [-100, -100]
- ]
-
- return 0 if step >= pos.length
- if step <= 1
- ox, oy = anchor('I23a', :n)
- @canvas.scale('I23b', ox, oy, 0.9, 0.5)
- end
- where = pos[step]
- move_abs('I23d', where)
-
- return 3 if where[2] == :x
- return 1
- end
-
- # Balloon
- def draw24
- color = @C['24a']
- xy = [366, 518, 462, 665] # Balloon
- TkcOval.new(@canvas, xy, :fill=>color, :outline=>@C['fg'],
- :width=>3, :tag=>'I24')
- xy = [414, 666, 414, 729] # String
- TkcLine.new(@canvas, xy, :fill=>@C['fg'], :width=>3, :tag=>'I24')
- xy = [410, 666, 404, 673, 422, 673, 418, 666] # Nozzle
- TkcPolygon.new(@canvas, xy, :fill=>color, :outline=>@C['fg'],
- :width=>3, :tag=>'I24')
-
- xy = [387, 567, 390, 549, 404, 542] # Reflections
- TkcLine.new(@canvas, xy, :fill=>@C['fg'], :smooth=>true,
- :width=>2, :tag=>'I24')
- xy = [395, 568, 399, 554, 413, 547]
- TkcLine.new(@canvas, xy, :fill=>@C['fg'], :smooth=>true,
- :width=>2, :tag=>'I24')
- xy = [403, 570, 396, 555, 381, 553]
- TkcLine.new(@canvas, xy, :fill=>@C['fg'], :smooth=>true,
- :width=>2, :tag=>'I24')
- xy = [408, 564, 402, 547, 386, 545]
- TkcLine.new(@canvas, xy, :fill=>@C['fg'], :smooth=>true,
- :width=>2, :tag=>'I24')
- end
-
- def move24(step = nil)
- step = get_step(24, step)
-
- return 0 if step > 4
- return 2 if step == 4
-
- if step == 0
- @canvas.delete('I24') # Exploding balloon
- xy = [
- 347, 465, 361, 557, 271, 503, 272, 503, 342, 574, 259, 594,
- 259, 593, 362, 626, 320, 737, 320, 740, 398, 691, 436, 738,
- 436, 739, 476, 679, 528, 701, 527, 702, 494, 627, 548, 613,
- 548, 613, 480, 574, 577, 473, 577, 473, 474, 538, 445, 508,
- 431, 441, 431, 440, 400, 502, 347, 465, 347, 465
- ]
- TkcPolygon.new(@canvas, xy, :tag=>'I24', :fill=>@C['24b'],
- :outline=>@C['24a'], :width=>10, :smooth=>true)
- msg = Tk.subst(@S['message'].value)
- TkcText.new(@canvas, centroid('I24'), :text=>msg, :tag=>['I24', 'I24t'],
- :justify=>:center, :font=>['Times Roman', 18, :bold])
- return 1
- end
-
- @canvas.itemconfigure('I24t', :font=>['Times Roman', 18 + 6*step, :bold])
- @canvas.move('I24', 0, -60)
- ox, oy = centroid('I24')
- @canvas.scale('I24', ox, oy, 1.25, 1.25)
- return 1
- end
-
- # Displaying the message
- def move25(step = nil)
- step = get_step(25, step)
-
- if step == 0
- @XY['25'] = Tk::Clock.clicks(:miliseconds)
- return 1
- end
- elapsed = Tk::Clock.clicks(:miliseconds) - @XY['25']
- return 1 if elapsed < 5000
- return 2
- end
-
- # Collapsing balloon
- def move26(step = nil)
- step = get_step(26, step)
-
- if step >= 3
- @canvas.delete('I24', 'I26')
- TkcText.new(@canvas, 430, 735, :anchor=>:s, :tag=>'I26',
- #:text=>'click to continue',
- :text=>'¥¯¥ê¥Ã¥¯¤Ç¥ê¥»¥Ã¥È¤·¤Þ¤¹',
- :font=>['Times Roman', 20, :bold])
- @canvas.bind('1', proc{reset})
- return 4
- end
-
- ox, oy = centroid('I24')
- @canvas.scale('I24', ox, oy, 0.8, 0.8)
- @canvas.move('I24', 0, 60)
- @canvas.itemconfigure('I24t', :font=>['Times Roman', 30 - 6*step, :bold])
- return 1
- end
-
- ################################################################
- #
- # Helper functions
- #
- def box(x, y, r)
- [x - r, y - r, x + r, y + r]
- end
-
- def move_abs(item, xy)
- x, y = xy
- ox, oy = centroid(item)
- dx = x - ox
- dy = y - oy
- @canvas.move(item, dx, dy)
- end
-
- def rotate_item(item, ox, oy, beta)
- xy = @canvas.coords(item)
- xy2 = []
- 0.step(xy.length - 1, 2){|idx|
- x, y = xy[idx, 2]
- xy2.concat(rotate_c(x, y, ox, oy, beta))
- }
- @canvas.coords(item, xy2)
- end
-
- def rotate_c(x, y, ox, oy, beta)
- # rotates vector (ox,oy)->(x,y) by beta degrees clockwise
-
- x -= ox # Shift to origin
- y -= oy
-
- beta = beta * Math.atan(1) * 4 / 180.0 # Radians
- xx = x * Math.cos(beta) - y * Math.sin(beta) # Rotate
- yy = x * Math.sin(beta) + y * Math.cos(beta)
-
- xx += ox # Shift back
- yy += oy
-
- [xx, yy]
- end
-
- def reset
- draw_all
- @canvas.bind_remove('1')
- @S['mode'].value = :MSTART
- @S['active'] = [0]
- end
-
- # Each Move## keeps its state info in STEP, this retrieves and increments it
- def get_step(who, step)
- if step
- @STEP[who] = step
- else
- if !@STEP.exist?(who) || @STEP[who] == ""
- @STEP[who] = 0
- else
- @STEP[who] += 1
- end
- end
- @STEP[who]
- end
-
- def reset_step
- @S['cnt'].value = 0
- @STEP.keys.each{|k| @STEP[k] = ''}
- end
-
- def sine(xy0, amp, freq, opts = {})
- x0, y0, x1, y1 = xy0
- step = 2
- xy = []
- if y0 == y1 # Horizontal
- x0.step(x1, step){|x|
- beta = (x - x0) * 2 * Math::PI / freq
- y = y0 + amp * Math.sin(beta)
- xy << x << y
- }
- else
- y0.step(y1, step){|y|
- beta = (y - y0) * 2 * Math::PI / freq
- x = x0 + amp * Math.sin(beta)
- xy << x << y
- }
- end
- TkcLine.new(@canvas, xy, opts)
- end
-
- def round_rect(xy, radius, opts={})
- x0, y0, x3, y3 = xy
- r = @canvas.winfo_pixels(radius)
- d = 2 * r
-
- # Make sure that the radius of the curve is less than 3/8 size of the box!
- maxr = 0.75
- if d > maxr * (x3 - x0)
- d = maxr * (x3 - x0)
- end
- if d > maxr * (y3 - y0)
- d = maxr * (y3 - y0)
- end
-
- x1 = x0 + d
- x2 = x3 - d
- y1 = y0 + d
- y2 = y3 - d
-
- xy = [x0, y0, x1, y0, x2, y0, x3, y0, x3, y1, x3, y2]
- xy.concat([x3, y3, x2, y3, x1, y3, x0, y3, x0, y2, x0, y1])
- return xy
- end
-
- def round_poly(canv, xy, radii, opts)
- lenXY = xy.length
- lenR = radii.length
- if lenXY != 2*lenR
- raise "wrong number of vertices and radii"
- end
-
- knots = []
- x0 = xy[-2]; y0 = xy[-1]
- x1 = xy[0]; y1 = xy[1]
- xy << xy[0] << xy[1]
-
- 0.step(lenXY - 1, 2){|i|
- radius = radii[i/2]
- r = canv.winfo_pixels(radius)
-
- x2 = xy[i+2]; y2 = xy[i+3]
- z = _round_poly2(x0, y0, x1, y1, x2, y2, r)
- knots.concat(z)
-
- x0 = x1; y0 = y1
- x1 = x2; y1 = y2
- }
- TkcPolygon.new(canv, knots, {:smooth=>true}.update(opts))
- end
-
- def _round_poly2(x0, y0, x1, y1, x2, y2, radius)
- d = 2 * radius
- maxr = 0.75
-
- v1x = x0 - x1
- v1y = y0 - y1
- v2x = x2 - x1
- v2y = y2 - y1
-
- vlen1 = Math.sqrt(v1x*v1x + v1y*v1y)
- vlen2 = Math.sqrt(v2x*v2x + v2y*v2y)
-
- if d > maxr * vlen1
- d = maxr * vlen1
- end
- if d > maxr * vlen2
- d = maxr * vlen2
- end
-
- xy = []
- xy << (x1 + d * v1x / vlen1) << (y1 + d * v1y / vlen1)
- xy << x1 << y1
- xy << (x1 + d * v2x / vlen2) << (y1 + d * v2y / vlen2)
-
- return xy
- end
-
- def sparkle(oxy, tag)
- xy = [
- [299, 283], [298, 302], [295, 314], [271, 331],
- [239, 310], [242, 292], [256, 274], [281, 273]
- ]
- xy.each{|x, y|
- TkcLine.new(@canvas, 271, 304, x, y,
- :fill=>'white', :width=>3, :tag=>tag)
- }
- move_abs(tag, oxy)
- end
-
- def centroid(item)
- anchor(item, :c)
- end
-
- def anchor(item, where)
- x1, y1, x2, y2 = @canvas.bbox(item)
- case(where)
- when :n
- y = y1
- when :s
- y = y2
- else
- y = (y1 + y2) / 2.0
- end
- case(where)
- when :w
- x = x1
- when :e
- x = x2
- else
- x = (x1 + x2) / 2.0
- end
- return [x, y]
- end
-end
-
-TkGoldberg_Demo.new($goldberg_demo)
diff --git a/ext/tk/sample/demos-jp/pendulum.rb b/ext/tk/sample/demos-jp/pendulum.rb
deleted file mode 100644
index d703c74d5a..0000000000
--- a/ext/tk/sample/demos-jp/pendulum.rb
+++ /dev/null
@@ -1,224 +0,0 @@
-#
-# This demonstration illustrates how Tcl/Tk can be used to construct
-# simulations of physical systems.
-# (called by 'widget')
-#
-# based on Tcl/Tk8.5a2 widget demos
-
-# destroy toplevel widget for this demo script
-if defined?($pendulum_demo) && $pendulum_demo
- $pendulum_demo.destroy
- $pendulum_demo = nil
-end
-
-# create toplevel widget
-$pendulum_demo = TkToplevel.new {|w|
- title("Pendulum Animation Demonstration")
- iconname("pendulum")
- positionWindow(w)
-}
-
-# create label
-msg = TkLabel.new($pendulum_demo) {
- font $font
- wraplength '4i'
- justify 'left'
- text '¤³¤Î¥Ç¥â¤Ï¡¢ÊªÍý·Ï¤Î¥·¥ß¥å¥ì¡¼¥·¥ç¥ó¤Ë´Ø¤ï¤ë¤è¤¦¤Ê¥¢¥Ë¥á¡¼¥·¥ç¥ó¼Â¹Ô¤¹¤ë¤¿¤á¤Ë Ruby/Tk ¤ò¤É¤Î¤è¤¦¤ËÍѤ¤¤ë¤³¤È¤¬¤Ç¤­¤ë¤«¤ò¼¨¤·¤Æ¤¤¤Þ¤¹¡£º¸Â¦¤Î¥­¥ã¥ó¥Ð¥¹¤Ïñ½ã¤Ê¿¶¤ê»Ò¤Ç¤¢¤ëʪÍý·Ï¼«ÂΤΥ°¥é¥Õ¥£¥«¥ëɽ¸½¤Ç¤¢¤ë¤Î¤ËÂФ·¡¢±¦Â¦¤Î¥­¥ã¥ó¥Ð¥¹¤Ï·Ï¤Î°ÌÁê¶õ´Ö¤Î¥°¥é¥Õ¡Ê³Ñ®Å٤ȳÑÅ٤Ȥò¥×¥í¥Ã¥È¤·¤¿¤â¤Î¡Ë¤Ë¤Ê¤Ã¤Æ¤¤¤Þ¤¹¡£º¸Â¦¤Î¥­¥ã¥ó¥Ð¥¹¾å¤Ç¥¯¥ê¥Ã¥¯¤ª¤è¤Ó¥É¥é¥Ã¥°¤ò¹Ô¤Ã¤Æ¿¶¤ê»Ò¤Î½Å¤ê¤Î°ÌÃÖ¤òÊѤ¨¤Æ¤ß¤Æ¤¯¤À¤µ¤¤¡£'
-}
-msg.pack('side'=>'top')
-
-# create frame
-TkFrame.new($pendulum_demo) {|frame|
- TkButton.new(frame) {
- #text 'λ²ò'
- text 'ÊĤ¸¤ë'
- command proc{
- tmppath = $pendulum_demo
- $pendulum_demo = nil
- tmppath.destroy
- }
- }.pack('side'=>'left', 'expand'=>'yes')
-
- TkButton.new(frame) {
- text '¥³¡¼¥É»²¾È'
- command proc{showCode 'pendulum'}
- }.pack('side'=>'left', 'expand'=>'yes')
-
-}.pack('side'=>'bottom', 'fill'=>'x', 'pady'=>'2m')
-
-# animated wave
-class PendulumAnimationDemo
- def initialize(frame)
- # Create some structural widgets
- pane = TkPanedWindow.new(frame).pack(:fill=>:both, :expand=>true)
- pane.add(@lf1 = TkLabelFrame.new(pane, :text=>'Pendulum Simulation'))
- pane.add(@lf2 = TkLabelFrame.new(pane, :text=>'Phase Space'))
-
- # Create the canvas containing the graphical representation of the
- # simulated system.
- @c = TkCanvas.new(@lf1, :width=>320, :height=>200, :background=>'white',
- :borderwidth=>2, :relief=>:sunken)
- TkcText.new(@c, 5, 5, :anchor=>:nw,
- :text=>'Click to Adjust Bob Start Position')
- # Coordinates of these items don't matter; they will be set properly below
- @plate = TkcLine.new(@c, 0, 25, 320, 25, :width=>2, :fill=>'grey50')
- @rod = TkcLine.new(@c, 1, 1, 1, 1, :width=>3, :fill=>'black')
- @bob = TkcOval.new(@c, 1, 1, 2, 2,
- :width=>3, :fill=>'yellow', :outline=>'black')
- TkcOval.new(@c, 155, 20, 165, 30, :fill=>'grey50', :outline=>'')
-
- # pack
- @c.pack(:fill=>:both, :expand=>true)
-
- # Create the canvas containing the phase space graph; this consists of
- # a line that gets gradually paler as it ages, which is an extremely
- # effective visual trick.
- @k = TkCanvas.new(@lf2, :width=>320, :height=>200, :background=>'white',
- :borderwidth=>2, :relief=>:sunken)
- @y_axis = TkcLine.new(@k, 160, 200, 160, 0, :fill=>'grey75', :arrow=>:last)
- @x_axis = TkcLine.new(@k, 0, 100, 320, 100, :fill=>'grey75', :arrow=>:last)
-
- @graph = {}
- 90.step(0, -10){|i|
- # Coordinates of these items don't matter;
- # they will be set properly below
- @graph[i] = TkcLine.new(@k, 0, 0, 1, 1, :smooth=>true, :fill=>"grey#{i}")
- }
-
- # labels
- @label_theta = TkcText.new(@k, 0, 0, :anchor=>:ne,
- :text=>'q', :font=>'Symbol 8')
- @label_dtheta = TkcText.new(@k, 0, 0, :anchor=>:ne,
- :text=>'dq', :font=>'Symbol 8')
-
- # pack
- @k.pack(:fill=>:both, :expand=>true)
-
- # Initialize some variables
- @points = []
- @theta = 45.0
- @dTheta = 0.0
- @length = 150
-
- # init display
- showPendulum
-
- # animation loop
- @timer = TkTimer.new(15){ repeat }
-
- # binding
- @c.bindtags_unshift(btag = TkBindTag.new)
- btag.bind('Destroy'){ @timer.stop }
- btag.bind('1', proc{|x, y| @timer.stop; showPendulum(x, y)}, '%x %y')
- btag.bind('B1-Motion', proc{|x, y| showPendulum(x, y)}, '%x %y')
- btag.bind('ButtonRelease-1',
- proc{|x, y| showPendulum(x, y); @timer.start }, '%x %y')
-
- btag.bind('Configure', proc{|w| @plate.coords(0, 25, w, 25)}, '%w')
-
- @k.bind('Configure', proc{|h, w|
- @psh = h/2;
- @psw = w/2
- @x_axis.coords(2, @psh, w-2, @psh)
- @y_axis.coords(@psw, h-2, @psw, 2)
- @label_theta.coords(@psw-4, 6)
- @label_dtheta.coords(w-6, @psh+4)
- }, '%h %w')
-
- # animation start
- @timer.start(500)
- end
-
- # This procedure makes the pendulum appear at the correct place on the
- # canvas. If the additional arguments x, y are passed instead of computing
- # the position of the pendulum from the length of the pendulum rod and its
- # angle, the length and angle are computed in reverse from the given
- # location (which is taken to be the centre of the pendulum bob.)
- def showPendulum(x=nil, y=nil)
- if x && y && (x != 160 || y != 25)
- @dTheta = 0.0
- x2 = x - 160
- y2 = y - 25
- @length = Math.hypot(x2, y2)
- @theta = Math.atan2(x2,y2)*180/Math::PI
- else
- angle = @theta*Math::PI/180
- x = 160 + @length*Math.sin(angle)
- y = 25 + @length*Math.cos(angle)
- end
-
- @rod.coords(160, 25, x, y)
- @bob.coords(x-15, y-15, x+15, y+15)
- end
-
- # Update the phase-space graph according to the current angle and the
- # rate at which the angle is changing (the first derivative with
- # respect to time.)
- def showPhase
- @points << @theta + @psw << -20*@dTheta + @psh
- if @points.length > 100
- @points = @points[-100..-1]
- end
- (0...100).step(10){|i|
- first = - i
- last = 11 - i
- last = -1 if last >= 0
- next if first > last
- lst = @points[first..last]
- @graph[i].coords(lst) if lst && lst.length >= 4
- }
- end
-
- # This procedure is the "business" part of the simulation that does
- # simple numerical integration of the formula for a simple rotational
- # pendulum.
- def recomputeAngle
- scaling = 3000.0/@length/@length
-
- # To estimate the integration accurately, we really need to
- # compute the end-point of our time-step. But to do *that*, we
- # need to estimate the integration accurately! So we try this
- # technique, which is inaccurate, but better than doing it in a
- # single step. What we really want is bound up in the
- # differential equation:
- # .. - sin theta
- # theta + theta = -----------
- # length
- # But my math skills are not good enough to solve this!
-
- # first estimate
- firstDDTheta = -Math.sin(@theta * Math::PI/180) * scaling
- midDTheta = @dTheta + firstDDTheta
- midTheta = @theta + (@dTheta + midDTheta)/2
- # second estimate
- midDDTheta = -Math.sin(midTheta * Math::PI/180) * scaling
- midDTheta = @dTheta + (firstDDTheta + midDDTheta)/2
- midTheta = @theta + (@dTheta + midDTheta)/2
- # Now we do a double-estimate approach for getting the final value
- # first estimate
- midDDTheta = -Math.sin(midTheta * Math::PI/180) * scaling
- lastDTheta = midDTheta + midDDTheta
- lastTheta = midTheta + (midDTheta+ lastDTheta)/2
- # second estimate
- lastDDTheta = -Math.sin(lastTheta * Math::PI/180) * scaling
- lastDTheta = midDTheta + (midDDTheta + lastDDTheta)/2
- lastTheta = midTheta + (midDTheta + lastDTheta)/2
- # Now put the values back in our globals
- @dTheta = lastDTheta
- @theta = lastTheta
- end
-
- # This method ties together the simulation engine and the graphical
- # display code that visualizes it.
- def repeat
- # Simulate
- recomputeAngle
-
- # Update the display
- showPendulum
- showPhase
- end
-end
-
-# Start the animation processing
-PendulumAnimationDemo.new($pendulum_demo)
diff --git a/ext/tk/sample/demos-jp/tcolor b/ext/tk/sample/demos-jp/tcolor
index c7f7ec7289..fc697df63e 100644
--- a/ext/tk/sample/demos-jp/tcolor
+++ b/ext/tk/sample/demos-jp/tcolor
@@ -124,14 +124,9 @@ def hsbToRgb(hue,sat,value)
end
-def _null_binding
- Module.new.instance_eval{binding}
-end
-private :_null_binding
-
def doUpdate
newCmd = $command.to_s.gsub("%%","\"#{$color}\"")
- eval(newCmd, _null_binding)
+ eval(newCmd)
end
@@ -216,21 +211,21 @@ def tc_loadNamedColor(name)
else
case name.length
when 4
- fmt = /#(.{1})(.{1})(.{1})/
+ format = /#(.{1})(.{1})(.{1})/
shift = 12
when 7
- fmt = /#(.{2})(.{2})(.{2})/
+ format = /#(.{2})(.{2})(.{2})/
shift = 8
when 10
- fmt = /#(.{3})(.{3})(.{3})/
+ format = /#(.{3})(.{3})(.{3})/
shift = 4
when 13
- fmt = /#(.{4})(.{4})(.{4})/
+ format = /#(.{4})(.{4})(.{4})/
shift = 0
else
raise(eException,"syntax error in color name \"#{name}\"")
end
- name.scan(fmt){|strlist|
+ name.scan(format){|strlist|
if strlist.length != 3
raise(eException,"syntax error in color name \"#{name}\"")
end
diff --git a/ext/tk/sample/demos-jp/widget b/ext/tk/sample/demos-jp/widget
index ec9a07d778..e8196aec8f 100644
--- a/ext/tk/sample/demos-jp/widget
+++ b/ext/tk/sample/demos-jp/widget
@@ -11,7 +11,7 @@ require 'tk'
$demo_dir = File.dirname($0)
# root ¤ÎÀ¸À®
-$root = TkRoot.new{title "Ruby/Tk Widget Demonstration"}
+$root = TkRoot.new{title "Widget Demonstration"}
# tk ¥Ð¡¼¥¸¥ç¥ó¤Î¼èÆÀ
$tk_version = Tk::TK_VERSION
@@ -86,7 +86,7 @@ EOD
end
if $tk_major_ver >= 8
-$image['print'] = TkPhotoImage.new(:height=>19, :format=>'GIF', :data=><<EOD)
+$image['print'] = TkPhotoImage.new(:height=>16, :format=>'GIF', :data=><<EOD)
R0lGODlhGgATAPcAACEQOTEpQjEpUkIpc0IxY0I5c0oxjEo5SlJCY1JCe1JK
UlpChFpCjFpGkFpSc1paa2NKc2NKnGNja2tapWtjc29KnHNanHNjc3NjrXNr
jHNrnHNzc3tjpXtrtXtzhICAgIRzvYSEjIZzqox7tYyEnIyMjJSEtZSEvZSM
@@ -438,18 +438,6 @@ txt.insert('end', "3. ¿§ÁªÂò¥À¥¤¥¢¥í¥°\n", tag_demo, "demo-clrpick")
txt.insert('end', " \n ", tag_demospace)
txt.insert('end', "\n")
-#txt.insert('end', "¥¢¥Ë¥á¡¼¥·¥ç¥ó\n", tag_middle)
-txt.insert('end', "¥¢¥Ë¥á¡¼¥·¥ç¥ó\n", tag_kanji_title)
-txt.insert('end', " \n ", tag_demospace)
-txt.insert('end', "1. ¥¢¥Ë¥á¡¼¥·¥ç¥ó¥é¥Ù¥ë (µ¡Ç½¤ËÂбþ¤·¤¿¥Ð¡¼¥¸¥ç¥ó¤ÎTk¤¬É¬Í×)\n", tag_demo, "demo-anilabel")
-txt.insert('end', " \n ", tag_demospace)
-txt.insert('end', "2. ÇÈ·Á¤Î¥¢¥Ë¥á¡¼¥·¥ç¥ó (µ¡Ç½¤ËÂбþ¤·¤¿¥Ð¡¼¥¸¥ç¥ó¤ÎTk¤¬É¬Í×)\n", tag_demo, "demo-aniwave")
-txt.insert('end', " \n ", tag_demospace)
-txt.insert('end', "3. ¿¶¤ê»Ò¤Î¥·¥ß¥å¥ì¡¼¥·¥ç¥ó (µ¡Ç½¤ËÂбþ¤·¤¿¥Ð¡¼¥¸¥ç¥ó¤ÎTk¤¬É¬Í×)\n", tag_demo, "demo-pendulum")
-txt.insert('end', " \n ", tag_demospace)
-txt.insert('end', "4. A celebration of Rube Goldberg (µ¡Ç½¤ËÂбþ¤·¤¿¥Ð¡¼¥¸¥ç¥ó¤ÎTk¤¬É¬Í×)\n", tag_demo, "demo-goldberg")
-
-txt.insert('end', "\n")
#txt.insert('end', "¤½¤Î¾\n", tag_middle)
txt.insert('end', "¤½¤Î¾\n", tag_kanji_title)
txt.insert('end', " \n ", tag_demospace)
@@ -551,43 +539,22 @@ else # ver >= 8.4
alias showVars showVars2
end
-def _null_binding
- # binding
- Module.new.instance_eval{binding}
-end
-private :_null_binding
-
# ¥Æ¥­¥¹¥È¾å¤Ç¤Î click ¤ËÂФ¹¤ëưºî
-def invoke(txt, idx)
- tag = txt.tag_names(idx).find{|t| t.kind_of?(String) && t =~ /^demo-/}
+def invoke (txt, index)
+ tag = txt.tag_names(index).find{|t| t.kind_of?(String) && t =~ /^demo-/}
return unless tag
-
cursor = txt.cget('cursor')
txt.cursor('watch')
Tk.update
- eval(IO.readlines("#{[$demo_dir, tag[5..-1]].join(File::Separator)}.rb").join, _null_binding)
- Tk.update
- txt.cursor(cursor)
-
- $tag_visited.add("#{idx} linestart +1 chars", "#{idx} lineend +1 chars")
-end
-=begin
-def invoke (txt, idx)
- tag = txt.tag_names(idx).find{|t| t.kind_of?(String) && t =~ /^demo-/}
- return unless tag
- current_cursor = txt.cget('cursor')
- txt.cursor('watch')
- Tk.update
# eval `cat #{tag[5..-1]}.rb`
# eval `cat #{[$demo_dir, tag[5..-1]].join(File::Separator)}.rb`
eval IO.readlines("#{[$demo_dir, tag[5..-1]].join(File::Separator)}.rb").join
Tk.update
# txt.cursor('xterm')
- txt.cursor(current_cursor)
+ txt.cursor(cursor)
- $tag_visited.add("#{idx} linestart +1 chars", "#{idx} lineend +1 chars")
+ $tag_visited.add("#{index} linestart +1 chars", "#{index} lineend +1 chars")
end
-=end
# ¾õÂÖɽ¼¨
def showStatus (txt, index)
@@ -622,7 +589,7 @@ def showCode1(demo)
}.pack('side'=>'left', 'expand'=>'yes', 'pady'=>2)
TkButton.new(f) {
text "ºÆ¼Â¹Ô"
- command proc{eval($code_text.get('1.0','end'), _null_binding)}
+ command proc{eval($code_text.get('1.0','end'))}
}.pack('side'=>'left', 'expand'=>'yes', 'pady'=>2)
# f.pack('side'=>'bottom', 'expand'=>'yes', 'fill'=>'x')
f.pack('side'=>'bottom', 'fill'=>'x')
@@ -715,9 +682,7 @@ def showCode2(demo)
:command=>proc{printCode($code_text, file)},
:image=>$image['print'], :compound=>:left)
b_run = TkButton.new(bf, :text=>'ºÆ¼Â¹Ô',
- :command=>proc{
- eval($code_text.get('1.0','end'), _null_binding)
- },
+ :command=>proc{eval($code_text.get('1.0','end'))},
:image=>$image['refresh'], :compound=>:left)
TkGrid('x', b_run, b_prn, b_dis, :padx=>4, :pady=>[6,4])
@@ -842,7 +807,7 @@ end
#
def aboutBox
Tk.messageBox('icon'=>'info', 'type'=>'ok', 'title'=>'About Widget Demo',
- 'message'=>"Ruby/Tk ¥¦¥£¥¸¥§¥Ã¥È¥Ç¥â Ver.1.5.4-jp\n\n" +
+ 'message'=>"Ruby/Tk ¥¦¥£¥¸¥§¥Ã¥È¥Ç¥â Ver.1.4.3-jp\n\n" +
"based on demos of Tk8.1 -- 8.5 " +
"( Copyright:: " +
"(c) 1996-1997 Sun Microsystems, Inc. / " +
@@ -863,8 +828,7 @@ ARGV.each{|cmd|
if cmd =~ /(.*).rb/
cmd = $1
end
- eval(IO.readlines("#{[$demo_dir, cmd].join(File::Separator)}.rb").join,
- _null_binding)
+ eval IO.readlines("#{[$demo_dir, cmd].join(File::Separator)}.rb").join
}
if no_launcher
$root.withdraw # hide root window
diff --git a/ext/tk/sample/irbtk.rb b/ext/tk/sample/irbtk.rb
deleted file mode 100644
index 53ef10d0d1..0000000000
--- a/ext/tk/sample/irbtk.rb
+++ /dev/null
@@ -1,30 +0,0 @@
-#!/usr/local/bin/ruby
-#
-# irbtk.rb - irb with Ruby/Tk
-#
-# If you want to use 'multi-tk.rb', give option '--multi-tk'.
-# And if you want to use 'remote-tk.rb', give option '--remote-tk'.
-# If you want both, you don't need to give both options, because
-# 'remote-tk.rb' includes 'multi-tk.rb'.
-# ( There is no trouble even if you give both options. )
-#
-require 'remote-tk' if ARGV.delete('--remote-tk')
-require 'multi-tk' if ARGV.delete('--multi-tk')
-
-require "tk"
-module Tk
- MAINLOOP = Thread.new{ mainloop }
-end
-
-require "irb"
-
-if __FILE__ == $0
- IRB.start(__FILE__)
-else
- # check -e option
- if /^-e$/ =~ $0
- IRB.start(__FILE__)
- else
- IRB.setup(__FILE__)
- end
-end
diff --git a/ext/tk/sample/tkextlib/blt/barchart5.rb b/ext/tk/sample/tkextlib/blt/barchart5.rb
deleted file mode 100644
index db181d10ca..0000000000
--- a/ext/tk/sample/tkextlib/blt/barchart5.rb
+++ /dev/null
@@ -1,101 +0,0 @@
-#!/usr/bin/env ruby
-require 'tk'
-require 'tkextlib/blt'
-
-load File.join(File.dirname(File.expand_path(__FILE__)),
- 'scripts', 'stipples.rb')
-
-TkOption.add('*graph.x.Title', 'X Axis Label')
-TkOption.add('*graph.y.Title', 'Y Axis Label')
-TkOption.add('*graph.title', 'A Simple Barchart')
-TkOption.add('*graph.x.Font', 'Times 10')
-TkOption.add('*graph.Element.Relief', :raised)
-
-visual = Tk.root.winfo_screenvisual
-if visual != 'staticgray' && visual != 'grayscale'
- TkOption.add('*graph.LineMarker.color', 'yellow')
- TkOption.add('*graph.Element.Background', 'white')
- TkOption.add('*graph.Legend.activeForeground', 'pink')
- TkOption.add('*print.background', 'yellow')
- TkOption.add('*quit.background', 'red')
- TkOption.add('*graph.background', 'palegreen')
- TkOption.add('*graph.plotBackground', 'lightblue')
-end
-
-htext = Tk::BLT::Htext.new(:widgetname=>'.htext', :text=><<EOD)
- This is an example of the barchart widget. The barchart has
- many components; x and y axis, legend, crosshairs, elements, etc.
- To create a postscript file "bar.ps", press the %%
-
- ruby {
- b = TkButton.new(Tk::BLT::Htext::Htext_Widget.window,
- :widgetname=>'print', :text=>'Print',
- :command=>proc{
- $graph.postsript(:output=>'bar.ps')
- })
- Tk::BLT::Htext::Htext_Widget.window.append(b)
- }
-
-%% button.
-%%
-
- ruby {
- $graph = Tk::BLT::Barchart.new(:widgetname=>'.htext.graph',
- :relief=>:raised, :borderwidth=>2)
- $graph.xaxis_configure(:rotate=>90, :stepsize=>0)
- Tk::BLT::Htext::Htext_Widget.window.append($graph,
- :fill=>:both, :padx=>4)
- }
-
-%%
- Hit the %%
-
- ruby {
- b = TkButton.new(Tk::BLT::Htext::Htext_Widget.window,
- :widgetname=>'quit', :text=>'Quit',
- :command=>proc{ exit })
- Tk::BLT::Htext::Htext_Widget.window.append(b)
- }
-
-%% button when you've seen enough.%%
-
- ruby {
- l = TkLabel.new(Tk::BLT::Htext::Htext_Widget.window, :bitmap=>'BLT')
- Tk::BLT::Htext::Htext_Widget.window.append(l, :padx=>20)
- }
-
-%%
-EOD
-
-names = %w(One Two Three Four Five Six Seven Eight)
-if visual == 'staticgray' || visual == 'grayscale'
- fgcolors = %w(white white white white white white white white)
- bgcolors = %w(black black black black black black black black)
-else
- fgcolors = %w(yellow orange red magenta purple blue cyan green)
- bgcolors = %w(yellow4 orange4 red4 magenta4 purple4 blue4 cyan4 green4)
-end
-
-numColors = names.length
-
-Tk::TCL_PRECISION.value = 15
-
-x = Tk::BLT::Vector.new
-y = Tk::BLT::Vector.new
-x.seq(-5.0, 5.0, 0.2)
-y.expr("sin(#{x})")
-barWidth = 0.19
-
-$graph.element_create('sin', :relief=>:raised, :borderwidth=>1,
- :x=>x, :y=>y, :barwidth=>barWidth)
-
-Tk::BLT::Table.add(Tk.root, htext, :fill=>:both)
-
-Tk.root.minsize(0, 0)
-
-Tk::BLT.zoom_stack($graph)
-Tk::BLT.crosshairs($graph)
-Tk::BLT.active_legend($graph)
-Tk::BLT.closest_point($graph)
-
-Tk.mainloop
diff --git a/ext/tk/sample/tkextlib/blt/calendar.rb b/ext/tk/sample/tkextlib/blt/calendar.rb
deleted file mode 100644
index 4fc6d64d9e..0000000000
--- a/ext/tk/sample/tkextlib/blt/calendar.rb
+++ /dev/null
@@ -1,117 +0,0 @@
-#!/usr/bin/env ruby
-
-require 'tk'
-require 'tkextlib/blt'
-
-require 'date'
-
-dir = File.join(File.dirname(File.expand_path(__FILE__)), 'images')
-file = File.join(dir, 'chalk.gif')
-active = File.join(dir, 'rain.gif')
-
-texture1 = TkPhotoImage.new(:file=>file)
-texture2 = TkPhotoImage.new(:file=>active)
-
-TkOption.add('*Tile', texture1)
-
-TkOption.add('*HighlightThickness', 0)
-TkOption.add('*calendar.weekframe*Tile', texture2)
-TkOption.add('*Calendar.Label.borderWidth', 0)
-TkOption.add('*Calendar.Label.relief', :sunken)
-TkOption.add('*Calendar.Frame.borderWidth', 2)
-TkOption.add('*Calendar.Frame.relief', :raised)
-TkOption.add('*Calendar.Label.font', 'Helvetica 11')
-TkOption.add('*Calendar.Label.foreground', 'navyblue')
-TkOption.add('*button.foreground', 'navyblue')
-TkOption.add('*background', 'grey85')
-TkOption.add('*Label.ipadX', 200)
-
-TkOption.add('*tile', texture2)
-
-class BLT_Calendar_sample
- @@monthInfo = [
- nil, # dummy
- ['January', 31],
- ['February', 28],
- ['March', 31],
- ['April', 30],
- ['May', 31],
- ['June', 30],
- ['July', 31],
- ['August', 31],
- ['Septembar', 30],
- ['October', 31],
- ['November', 30],
- ['December', 31]
- ]
-
- @@abbrDays = [ 'Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat' ]
-
- def initialize()
- today = Date.today
-
- if TkComm.bool(Tk.info(:commands, '.calendar'))
- Tk.destroy('.calendar')
- end
- cal = Tk::BLT::Tile::Frame.new(:widgetname=>'.calendar',
- :classname=>'Calendar',
- :width=>'3i', :height=>'3i')
-
- mon = Tk::BLT::Tile::Label.new(cal, :font=>'Courier 14 bold',
- :text=>"#{@@monthInfo[today.month][0]} " +
- "#{today.year}")
- Tk::BLT::Table.add(cal, mon, [1, 0], :cspan=>7, :pady=>10)
-
- week_f = Tk::BLT::Tile::Frame.new(cal, :widgetname=>'weekframe',
- :relief=>:sunken, :borderwidth=>1)
- Tk::BLT::Table.add(cal, week_f, [2, 0], :columnspan=>7, :fill=>:both)
-
- @@abbrDays.each_with_index{|dayName, idx|
- Tk::BLT::Table.add(cal,
- Tk::BLT::Tile::Label.new(cal, :text=>dayName,
- :font=>'Helvetica 12'),
- [2, idx], :pady=>2, :padx=>2)
- }
-
- Tk::BLT::Table.itemconfigure(cal, 'c*', 'r2', :pad=>4)
-
- numDays = @@monthInfo[today.month][1]
- week = 0
- cnt = 1
-
- wkday = today.wday - ((today.day - 1) % 7)
- wkday += 7 if wkday < 0
-
- while cnt <= numDays
- Tk::BLT::Table.add(cal,
- Tk::BLT::Tile::Label.new(cal, :text=>cnt){
- self.configure(:borderwidth=>1,
- :relief=>:sunken) if cnt == today.day
- },
- [week+3, wkday], :fill=>:both, :ipadx=>10, :ipady=>4)
- cnt += 1
- wkday += 1
- if wkday == 7
- week += 1
- wkday = 0
- end
- end
-
- Tk::BLT::Tile::Frame.new(cal, :borderwidth=>1, :relief=>:sunken){|f|
- Tk::BLT::Table.add(f,
- Tk::BLT::Tile::Button.new(f, :widgetname=>'button',
- :command=>proc{exit},
- :borderwidth=>2,
- :text=>'Quit'),
- :padx=>4, :pady=>4)
- Tk::BLT::Table.add(cal, f, [week+4, 5], :cspan=>2, :pady=>4)
- }
-
- Tk::BLT::Table.add(Tk.root, cal, :fill=>:both)
- Tk::BLT::Table.itemconfigure(cal, 'r0', :resize=>:none)
- end
-end
-
-BLT_Calendar_sample.new
-
-Tk.mainloop
diff --git a/ext/tk/sample/tkextlib/blt/graph6.rb b/ext/tk/sample/tkextlib/blt/graph6.rb
deleted file mode 100644
index f899b44115..0000000000
--- a/ext/tk/sample/tkextlib/blt/graph6.rb
+++ /dev/null
@@ -1,2222 +0,0 @@
-#!/usr/bin/env ruby
-
-require 'tk'
-require 'tkextlib/blt'
-
-Tk::TCL_PRECISION.value = 15
-
-[
- ['*Graph.Width', '10i'],
- ['*Graph.leftMargin', '.75i'],
- ['*Graph.Height', '6i'],
- ['*Graph.plotBackground', 'black'],
- ['*LineMarker.color', 'white'],
- ['*LineMarker.Dashes', 5],
- ['*TextMarker.foreground', 'white'],
- ['*TextMarker.Background', ''],
-
- ['*Graph.x.hide', true],
- ['*Graph.x.title', ''],
- ['*Graph.y.rotate', 90],
- # ['*Graph.y.stepSize', 2.0],
- ['*Graph.title', ''],
- ['*graph.Title', 'Example s27'],
- ['*graph.x.hide', false],
- ['*graph.topMargin', 0],
- ['*graph.bottomMargin', 0],
- ['*x.Title', 'Time'],
- ['*y.Title', 'Signals'],
- ['*Pixels', 1],
-
- ['*Reduce', 0.5],
- ['*bufferElements', false],
-
- ['*Element.color', 'green4'],
- ['*Element.ScaleSymbols', true],
- ['*Element.Color', 'grey70'],
- ['*Element.Symbol', :none],
- ['*Element.LineWidth', 1],
- # ['*Element.Smooth', :natural],
- ['*Element.Smooth', :catrom],
-
- ['*activeLine.LineWidth', 2],
- ['*activeLine.Color', 'white'],
- ['*activeLine.Color', 'green1'],
-
- # ['*Legend.Hide', true],
- ['*Legend.Position', :right],
- ['*Legend.Relief', :flat],
- ['*Legend.activeRelief', :sunken],
- ['*Legend.borderWidth', 2],
- #['*Legend.Font', '-*-helvetica-medium-r-*-*-10-*-*-*-*-*-*-*'],
- ['*Legend.Font', 'Helvetica -10'],
- ['*Grid.hide', false],
- ['*Grid.dashes', [1, 5]],
-
- # ['*foreground', 'white'],
- ['*zoomOutline.outline', 'yellow'],
-].each{|k, v| TkOption.add(k, v)}
-
-##############################
-
-class BLT_Graph_Demo
- def initialize
- @graph = Tk::BLT::Graph.new(:widgetname=>'graph')
-
- @root = Tk.root
- @root.minsize(0, 0)
-
- _set_vectors()
- (1..39).each{|i| @graph.element_create("V#{i}", :x=>@x, :y=>@v[i])}
-
- @top = Tk::BLT::Tile::Toplevel.new
-=begin
- legend = Tk::BLT::Graph.new(@top, :widgetname=>'legend',
- :without_creating=>true)
- @graph.legend_configure(:position=>legend)
-=end
- # legend = @graph.legend_window_create(@top, :widgetname=>'legend')
- legend = @graph.legend_window_create(@top)
- legend.pack(:fill=>:both, :expand=>true)
-
- Tk::BLT::Table.add(@root, @graph, [0,0], :fill=>:both)
-
- @quit_btn = Tk::BLT::Tile::Button.new(:text=>' quit ', :background=>'red',
- :command=>proc{exit})
- Tk::BLT::Table.add(@root, @quit_btn, [1,0], :anchor=>:e, :padx=>10)
-
- @graph.zoom_stack
- @graph.crosshairs
- @graph.closest_point
- @graph.print_key
-
- @graph.legend_bind(:all, 'ButtonRelease-1',
- proc{|w| highlightTrace(w)}, '%W')
- @graph.legend_bind(:all, 'ButtonRelease-3',
- proc{|w|
- w.legend_deactivate('*')
- active = w.element_activate
- w.element_deactivate(*active)
- }, '%W')
- end
-
- private
-
- def _set_vectors
- @x = Tk::BLT::Vector.new(:variable=>'')
- @v = []
- (1..39).each{|i| @v[i] = Tk::BLT::Vector.new(:variable=>'')}
-
- @x.set(<<-'EOD')
- 0 1e-10 2e-10 3e-10 4e-10 5e-10 6e-10 7e-10 8e-10 9e-10
- 1e-09 1.1e-09 1.2e-09 1.3e-09 1.4e-09 1.5e-09 1.6e-09 1.7e-09
- 1.8e-09 1.9e-09 2e-09 2.1e-09 2.2e-09 2.3e-09 2.4e-09 2.5e-09
- 2.6e-09 2.7e-09 2.8e-09 2.9e-09 3e-09 3.1e-09 3.2e-09 3.3e-09
- 3.4e-09 3.5e-09 3.6e-09 3.7e-09 3.8e-09 3.9e-09 4e-09 4.1e-09
- 4.2e-09 4.3e-09 4.4e-09 4.5e-09 4.6e-09 4.7e-09 4.8e-09
- 4.9e-09 5e-09 5.1e-09 5.2e-09 5.3e-09 5.4e-09 5.5e-09 5.6e-09
- 5.7e-09 5.8e-09 5.9e-09 6e-09 6.1e-09 6.2e-09 6.3e-09 6.4e-09
- 6.5e-09 6.6e-09 6.7e-09 6.8e-09 6.9e-09 7e-09 7.1e-09 7.2e-09
- 7.3e-09 7.4e-09 7.5e-09 7.6e-09 7.7e-09 7.8e-09 7.9e-09
- 8e-09 8.1e-09 8.2e-09 8.3e-09 8.4e-09 8.5e-09 8.6e-09 8.7e-09
- 8.8e-09 8.9e-09 9e-09 9.1e-09 9.2e-09 9.3e-09 9.4e-09 9.5e-09
- 9.6e-09 9.7e-09 9.8e-09 9.9e-09 1e-08 1.01e-08 1.02e-08
- 1.03e-08 1.04e-08 1.05e-08 1.06e-08 1.07e-08 1.08e-08 1.09e-08
- 1.1e-08 1.11e-08 1.12e-08 1.13e-08 1.14e-08 1.15e-08 1.16e-08
- 1.17e-08 1.18e-08 1.19e-08 1.2e-08 1.21e-08 1.22e-08 1.23e-08
- 1.24e-08 1.25e-08 1.26e-08 1.27e-08 1.28e-08 1.29e-08 1.3e-08
- 1.31e-08 1.32e-08 1.33e-08 1.34e-08 1.35e-08 1.36e-08 1.37e-08
- 1.38e-08 1.39e-08 1.4e-08 1.41e-08 1.42e-08 1.43e-08 1.44e-08
- 1.45e-08 1.46e-08 1.47e-08 1.48e-08 1.49e-08 1.5e-08 1.51e-08
- 1.52e-08 1.53e-08 1.54e-08 1.55e-08 1.56e-08 1.57e-08 1.58e-08
- 1.59e-08 1.6e-08 1.61e-08 1.62e-08 1.63e-08 1.64e-08 1.65e-08
- 1.66e-08 1.67e-08 1.68e-08 1.69e-08 1.7e-08 1.71e-08 1.72e-08
- 1.73e-08 1.74e-08 1.75e-08 1.76e-08 1.77e-08 1.78e-08 1.79e-08
- 1.8e-08 1.81e-08 1.82e-08 1.83e-08 1.84e-08 1.85e-08 1.86e-08
- 1.87e-08 1.88e-08 1.89e-08 1.9e-08 1.91e-08 1.92e-08 1.93e-08
- 1.94e-08 1.95e-08 1.96e-08 1.97e-08 1.98e-08 1.99e-08 2e-08
- 2.01e-08 2.02e-08 2.03e-08 2.04e-08 2.05e-08 2.06e-08 2.07e-08
- 2.08e-08 2.09e-08 2.1e-08 2.11e-08 2.12e-08 2.13e-08 2.14e-08
- 2.15e-08 2.16e-08 2.17e-08 2.18e-08 2.19e-08 2.2e-08 2.21e-08
- 2.22e-08 2.23e-08 2.24e-08 2.25e-08 2.26e-08 2.27e-08 2.28e-08
- 2.29e-08 2.3e-08 2.31e-08 2.32e-08 2.33e-08 2.34e-08 2.35e-08
- 2.36e-08 2.37e-08 2.38e-08 2.39e-08 2.4e-08 2.41e-08 2.42e-08
- 2.43e-08 2.44e-08 2.45e-08 2.46e-08 2.47e-08 2.48e-08 2.49e-08
- 2.5e-08 2.51e-08 2.52e-08 2.53e-08 2.54e-08 2.55e-08 2.56e-08
- 2.57e-08 2.58e-08 2.59e-08 2.6e-08 2.61e-08 2.62e-08 2.63e-08
- 2.64e-08 2.65e-08 2.66e-08 2.67e-08 2.68e-08 2.69e-08 2.7e-08
- 2.71e-08 2.72e-08 2.73e-08 2.74e-08 2.75e-08 2.76e-08 2.77e-08
- 2.78e-08 2.79e-08 2.8e-08 2.81e-08 2.82e-08 2.83e-08 2.84e-08
- 2.85e-08 2.86e-08 2.87e-08 2.88e-08 2.89e-08 2.9e-08 2.91e-08
- 2.92e-08 2.93e-08 2.94e-08 2.95e-08 2.96e-08 2.97e-08 2.98e-08
- 2.99e-08 3e-08 3.01e-08 3.02e-08 3.03e-08 3.04e-08 3.05e-08
- 3.06e-08 3.07e-08 3.08e-08 3.09e-08 3.1e-08 3.11e-08 3.12e-08
- 3.13e-08 3.14e-08 3.15e-08 3.16e-08 3.17e-08 3.18e-08 3.19e-08
- 3.2e-08 3.21e-08 3.22e-08 3.23e-08 3.24e-08 3.25e-08 3.26e-08
- 3.27e-08 3.28e-08 3.29e-08 3.3e-08 3.31e-08 3.32e-08 3.33e-08
- 3.34e-08 3.35e-08 3.36e-08 3.37e-08 3.38e-08 3.39e-08 3.4e-08
- 3.41e-08 3.42e-08 3.43e-08 3.44e-08 3.45e-08 3.46e-08 3.47e-08
- 3.48e-08 3.49e-08 3.5e-08 3.51e-08 3.52e-08 3.53e-08 3.54e-08
- 3.55e-08 3.56e-08 3.57e-08 3.58e-08 3.59e-08 3.6e-08
- EOD
-
- @v[1].set(<<-'EOD')
- 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5
- 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5
- 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5
- 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5
- 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5
- 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5
- 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5
- 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5
- 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5
- 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5
- 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5
- 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5
- 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5
- EOD
-
- @v[2].set(<<-'EOD')
- 0 1 2 3 4 5 5 5 5 5 5 5 5 5 5 5 4 3 2 1 0 0 0 0 0 0 0 0
- 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
- 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
- 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
- 0 0 0 0 0 0 0 0 0 1 2 3 4 5 5 5 5 5 5 5 5 5 5 5 4 3 2 1
- 5.32907e-15 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
- 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
- 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
- 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 2 3 4 5 5
- 5 5 5 5 5 5 5 5 5 4 3 2 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
- 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
- 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
- 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
- 0 0
- EOD
-
- @v[3].set(<<-'EOD')
- 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 4 3 2 1 8.88178e-16
- 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
- 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
- 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
- 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
- 0 0 0 1 2 3 4 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5
- 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5
- 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5
- 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5
- 5 5 5 5 5 5 5 5 5 5 5 4 3 2 1 2.13718e-14 0 0 0 0 0 0 0
- 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
- 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
- 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
- 0 0 0 0
- EOD
-
- @v[4].set(<<-'EOD')
- 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 2 3 4 5 5 5
- 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5
- 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5
- 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5
- 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5
- 5 4 3 2 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
- 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
- 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
- 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
- 0 0 0 0 0 0 0 0 0 1 2 3 4 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5
- 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5
- 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5
- 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5
- EOD
-
- @v[5].set(<<-'EOD')
- 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 2 3 4 5 5 5
- 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5
- 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5
- 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5
- 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5
- 5 4 3 2 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
- 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
- 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
- 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
- 0 0 0 0 0 0 0 0 0 1 2 3 4 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5
- 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5
- 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5
- 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5
- EOD
-
- @v[6].set(<<-'EOD')
- 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 4 3 2 1 8.88178e-16
- 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
- 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
- 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
- 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
- 0 0 0 1 2 3 4 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5
- 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5
- 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5
- 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5
- 5 5 5 5 5 5 5 5 5 5 5 4 3 2 1 2.13718e-14 0 0 0 0 0 0 0
- 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
- 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
- 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
- 0 0 0 0
- EOD
-
- @v[7].set(<<-'EOD')
- 5 5.16904 4.84159 3.34542 0.317102 0.103304 0.0275721 0.0221534
- 0.017689 0.0142639 0.0113974 0.00918238 0.00742541 0.00616602
- 0.00481195 0.00397049 -0.0659889 -0.025671 0.165495 0.986891
- 3.05229 4.55511 4.91611 4.98192 4.99428 4.99833 4.99095
- 4.97295 4.95493 4.93428 4.90723 4.94799 4.98584 4.99566
- 4.99813 4.99907 4.99947 4.99965 4.99976 4.99984 4.99989
- 4.99992 4.99994 4.99996 4.99998 5.00002 5.00006 5.00002
- 4.99996 4.99994 4.99999 5.00003 5.00002 5 4.99997 4.99997
- 4.99997 4.99997 4.99997 4.99996 4.99997 4.99997 4.99998
- 4.99998 4.99999 5 5 5 5 5 5 5.00001 5.00001 5.00001 5.00001
- 5.00001 5.00001 5.00001 5.00001 5.00001 5.00001 5.00001
- 5.00001 5.00001 5 5 5 5 5 5 5 4.99999 4.99999 4.99999 4.99999
- 4.99999 4.99999 4.99998 4.99998 4.99998 4.99999 4.99999
- 4.99999 4.99999 4.99999 4.99999 4.99999 4.99999 4.99999
- 4.99999 4.99999 4.99999 4.99999 4.99999 5 5 5 5 5 5 5 5.16575
- 4.69986 2.43862 0.0230224 0.035229 -0.0210607 -0.0292766
- -0.0172693 -0.00271479 -0.000912251 -0.000349106 -0.000116866
- -4.24733e-05 -1.39536e-05 -3.01179e-05 -0.0657192 -0.0204835
- 0.183378 1.07181 3.118 4.46472 4.84158 4.94795 4.98173 4.99236
- 4.99762 5.01939 5.0433 5.05332 5.04959 5.03955 5.02851 5.02052
- 5.01422 5.00965 5.00631 5.00405 5.00248 5.00083 5.00012
- 5.00209 5.00387 5.00347 4.99917 4.99213 4.98411 4.97521
- 4.96332 4.94601 4.9304 4.94633 4.97936 4.99264 4.99685 4.99857
- 4.99925 4.99954 4.9997 4.99973 4.9997 4.99973 4.99979 4.99983
- 4.99986 4.99988 4.9999 4.9999 4.99992 4.99993 4.99994 4.99995
- 4.99996 4.99996 4.99997 4.99997 4.99998 4.99998 4.99998
- 4.99999 4.99999 4.99999 4.99999 4.99999 4.99999 4.99999
- 5 5 5 5.00001 5.00001 5.00001 5.00001 5.00002 5.00002 5.00002
- 5.00002 5.00001 5.00001 5.00001 5 5 5 5 5 5 5 5 4.99999
- 4.99999 4.99999 4.99999 4.99999 4.99999 4.99999 4.99999
- 4.99999 4.99999 4.99999 5 5 5.14242 4.76101 3.16003 0.299374
- 0.0645506 -0.000498424 -2.45108e-05 -2.27986e-05 -5.24401e-05
- -4.9884e-05 -4.92491e-05 -2.93354e-05 -3.21402e-05 -2.11851e-05
- -3.37925e-05 -0.0657892 -0.020563 0.182582 1.06058 3.12484
- 4.46552 4.84146 4.95102 4.98556 4.99472 4.99806 4.99909
- 4.99955 4.99976 4.99994 4.99992 5.00029 4.99967 4.99849
- 4.99736 4.99884 5.00099 5.00377 5.00215 4.99994 4.99893
- 4.99788 4.99862 5.00055 5.00134 5.00127 5.00073 5.00039
- 5.00018 5.00006 5.00001 4.99985 5.00026 5.00018 5.00003
- 4.99981 4.99985 4.99987 4.99985 4.99982 4.99982 4.99982
- 4.99983 4.99985 4.99987 4.99989 4.99991 4.99992 4.99994
- 4.99995 4.99995 4.99994 4.99994 4.99996 4.99999 5.00002
- 5.00008 5.00009 5.00006 5.00001 5 4.99999 4.99998 4.99997
- 4.99996 4.99997 4.99997 4.99998 4.99998 4.99999 4.99999
- 4.99999 5 5 5 5 5.00001 5.00001 5.00001 5.00001 5.00001
- 5.00001 5.00001 5.00001 5.00001 5.00001 5.00001 5.00001
- 5 5 5 5 5 4.99999 4.99999 4.99999 4.99999 4.99998 4.99998
- 4.99998
- EOD
-
- @v[8].set(<<-'EOD')
- 5 5.03758 5.04711 4.96911 4.20882 3.96295 4.01117 4.15521
- 4.2967 4.42274 4.5295 4.6176 4.69014 4.74831 4.7966 4.83537
- 4.80526 4.787 4.79295 4.88588 5.08978 5.15615 5.10778 5.07718
- 5.06652 5.08225 4.9744 4.52977 3.77452 2.69426 1.15294 0.245509
- 0.0981544 0.0567527 0.0367487 0.0252578 0.0180599 0.0133837
- 0.0101497 0.0078616 0.00620186 0.00499056 0.0041027 0.00344223
- 0.00295808 0.00260089 0.00229887 0.00200817 0.00176397 0.00160116
- 0.00147381 0.00134645 0.00125029 0.00116043 0.00107371 0.00101981
- 0.000965921 0.000912028 0.000858135 0.000804242 0.000761669
- 0.00072672 0.000691771 0.000656823 0.000621874 0.000588722
- 0.00057041 0.000552098 0.000533785 0.000515473 0.000497162
- 0.00047885 0.000460537 0.000442226 0.000423914 0.000405601
- 0.000388399 0.000378694 0.000368989 0.000359284 0.00034958
- 0.000339875 0.00033017 0.000320465 0.00031076 0.000301055
- 0.00029135 0.000282207 0.000276247 0.000270287 0.000264327
- 0.000258367 0.000252407 0.000246447 0.000240487 0.000234527
- 0.000228567 0.000222607 0.000217086 0.000213696 0.000210307
- 0.000206918 0.000203528 0.000200139 0.00019675 0.00019336
- 0.000189971 0.000186582 0.000183192 0.000179803 0.000176414
- 0.000173025 0.000169635 0.000166246 0.000162857 0.000159467
- 0.000156078 0.000152689 0.000149299 0.00014591 0.00014255
- 0.0316021 0.163272 0.348732 0.603651 0.35745 0.135965 0.0707354
- 0.0314595 0.0201047 0.00994945 0.00389601 0.00138839 0.00060778
- 0.000329648 0.000492396 -0.0732035 -0.0844077 -0.0789062
- -0.0390837 0.0197559 0.0183094 -0.00180099 -0.0189565 -0.0424144
- -0.0735904 -0.0892423 0.285039 1.13702 2.10809 2.95826 3.60164
- 4.0435 4.35771 4.57254 4.71769 4.81329 4.87534 4.91487 4.94264
- 4.97375 5.01526 5.06517 5.10154 5.06259 4.89005 4.5787 4.12226
- 3.46151 2.49023 1.2586 0.32725 0.116753 0.0701865 0.0455509
- 0.0286914 0.0178176 0.0117599 0.00902715 0.00760583 0.00637745
- 0.00543811 0.00439377 0.00352448 0.0030151 0.00285771 0.002465
- 0.00203114 0.00173004 0.0014839 0.00125177 0.00105327 0.000894905
- 0.000766372 0.000658894 0.000569105 0.000492114 0.000427938
- 0.000370217 0.000314758 0.000266569 0.000233726 0.000209048
- 0.000191957 0.000177169 0.000166604 0.000161 0.000157314
- 0.000143828 0.000130342 0.000116857 0.000103371 8.98855e-05
- 7.63998e-05 6.29141e-05 5.76583e-05 5.30027e-05 4.8347e-05
- 4.36913e-05 3.90357e-05 3.438e-05 2.97243e-05 2.72507e-05
- 2.59083e-05 2.45659e-05 2.32235e-05 2.18811e-05 2.05387e-05
- 1.91963e-05 1.78539e-05 1.65115e-05 1.51691e-05 1.38267e-05
- 1.24843e-05 1.11419e-05 9.79954e-06 8.51574e-06 7.69807e-06
- 6.8804e-06 6.06273e-06 5.24506e-06 0.0287318 0.0317111 -0.0320087
- -0.103609 0.0369639 0.0121128 0.00961197 0.00934971 0.00820853
- 0.00699769 0.00607002 0.00535541 0.00476552 0.00427601 0.00376357
- -0.073012 -0.0866964 -0.0809538 -0.038005 0.0277001 0.0188906
- 0.00614597 0.00373629 0.00489787 0.0146573 0.0191052 0.0151708
- 0.0124224 0.0105859 0.00879272 0.00729464 0.0070047 0.00449575
- -0.00626652 -0.0252417 -0.0147287 0.022538 0.0822905 0.0947372
- 0.0657516 0.0445506 0.0316753 0.0220971 0.0158101 0.0140971
- 0.0161498 0.0139876 0.0122447 0.0106994 0.009397 0.00822236
- 0.00686509 0.00797431 0.00751269 0.00671173 0.00595243 0.00524633
- 0.00459528 0.00401688 0.00350109 0.00303954 0.00260569 0.00222792
- 0.00191033 0.00163917 0.00140949 0.00121464 0.0010471 0.000900638
- 0.000768847 0.000645236 0.000524807 0.000460275 0.000442237
- 0.000446775 0.000397026 0.000301585 0.000228994 0.000190894
- 0.000166569 0.000152261 0.000137953 0.000123644 0.000109336
- 9.50281e-05 8.56557e-05 7.78437e-05 7.00318e-05 6.22198e-05
- 5.44079e-05 4.87539e-05 4.57761e-05 4.27982e-05 3.98203e-05
- 3.68425e-05 3.38646e-05 3.08868e-05 2.79089e-05 2.4931e-05
- 2.19532e-05 1.89753e-05 1.75244e-05 1.64095e-05 1.52946e-05
- 1.41797e-05 1.30648e-05 1.19499e-05 1.0835e-05 9.72011e-06
- 8.60521e-06 7.4903e-06 6.5117e-06 6.10334e-06 5.69497e-06
- 5.2866e-06 4.87824e-06 4.46987e-06 4.06151e-06 3.65314e-06
- 3.24477e-06
- EOD
-
- @v[9].set(<<-'EOD')
- 1.86175 1.99708 2.07867 2.01211 2.43309 3.27194 3.63896
- 3.90426 4.11074 4.27932 4.41496 4.52543 4.61491 4.68862
- 4.7479 4.79666 4.72895 4.68886 4.70354 4.81353 5.01568 5.14184
- 5.10482 5.07362 5.05143 5.03638 5.02323 5.01465 5.00853
- 5.00383 4.99985 5.00454 5.00652 5.00546 5.00411 5.003 5.00214
- 5.00151 5.00106 5.00073 5.0005 5.00034 5.00023 5.00015 5.0001
- 5.00005 5 5.00001 5.00005 5.00005 5.00003 5 4.99998 4.99996
- 4.99994 4.99995 4.99997 4.99998 5 5.00001 5.00002 5.00002
- 5.00003 5.00003 5.00003 5.00003 5.00003 5.00003 5.00002
- 5.00002 5.00001 5.00001 5.00001 5 5 5 4.99999 4.99999 4.99999
- 4.99999 4.99999 4.99999 4.99999 4.99999 4.99999 4.99998
- 4.99998 4.99998 4.99999 4.99999 4.99999 4.99999 5 5 5 5
- 5.00001 5.00001 5.00001 5.00001 5.00001 5.00001 5.00001
- 5.00001 5.00001 5.00001 5.00001 5.00001 5.00001 5.00001
- 5.00001 5.00001 5.00001 5.00001 5.00001 5.00001 5.00001
- 5.00001 5.00001 5.00001 5.00001 5.17392 4.94828 3.78491
- 1.52079 0.608874 0.244031 0.127087 0.0552995 0.0361032 0.0169025
- 0.006364 0.00217624 0.000921391 0.000457305 0.000786754
- -0.120016 -0.148054 -0.15898 -0.0801463 0.16463 0.174017
- 0.0799249 0.0318788 0.0129696 0.00483397 0.0025677 0.0042079
- 0.00350003 0.00178404 -8.72902e-05 -0.00128497 -0.00142213
- -0.00130018 -0.00106874 -0.000789207 -0.000824335 -0.00104518
- -0.00136799 -0.004366 -0.0102621 -0.0109254 -0.00649259
- -0.00194842 0.00029793 0.00148673 0.00221085 0.00228291
- 0.00185261 0.00139687 0.00148183 0.00562266 0.00844119 0.00754627
- 0.00657396 0.00591212 0.00539269 0.0049282 0.00448417 0.0040572
- 0.00363719 0.00320392 0.00279607 0.00243938 0.00211505 0.00182302
- 0.00156254 0.0013341 0.00113834 0.000971865 0.00082776 0.000706193
- 0.000602499 0.000515059 0.000441401 0.00037897 0.000325459
- 0.00028083 0.000242096 0.000207274 0.000176444 0.000150372
- 0.000126407 0.000103373 9.05522e-05 8.53555e-05 8.63685e-05
- 9.02593e-05 8.37346e-05 7.72099e-05 7.06852e-05 6.41605e-05
- 5.76358e-05 5.11112e-05 4.45865e-05 4.08176e-05 3.72497e-05
- 3.36818e-05 3.01138e-05 2.65459e-05 2.2978e-05 1.94101e-05
- 1.76154e-05 1.67399e-05 1.58645e-05 1.4989e-05 1.41136e-05
- 1.32381e-05 1.23626e-05 1.14872e-05 1.06117e-05 9.73629e-06
- 8.86083e-06 7.98538e-06 7.10993e-06 6.23447e-06 5.44363e-06
- 5.32578e-06 5.20792e-06 5.09007e-06 4.97222e-06 0.0784323
- 0.0474527 -0.0764232 -0.151146 0.0615785 0.0144489 0.00974161
- 0.00947176 0.00849005 0.00728201 0.00630581 0.00554032 0.00487809
- 0.00441504 0.00384139 -0.118943 -0.149894 -0.161173 -0.0825299
- 0.171686 0.176912 0.0816085 0.0335236 0.013791 0.0056976
- 0.00238833 0.00105348 0.000526199 0.00025969 0.000396026
- 0.000837835 0.00170131 0.00196699 -0.000553314 -0.0061621
- -0.0111895 -0.0142698 -0.0124608 -0.00795847 -0.00467822
- -0.0043058 -0.00874449 -0.0118584 -0.00871386 -0.00377892
- 1.95244e-05 0.00218952 0.00325486 0.00386497 0.00422837
- 0.00446883 0.00447065 0.00486647 0.00547838 0.00565398 0.00559092
- 0.00538752 0.00507015 0.00466305 0.00420756 0.00373465 0.00328404
- 0.00287059 0.00250057 0.00216124 0.00184861 0.00156815 0.00134624
- 0.00117857 0.00103412 0.0008948 0.000761012 0.000619853
- 0.000462614 0.000319965 0.000287666 0.000356415 0.000379946
- 0.000339183 0.00027972 0.000252982 0.000226244 0.000199507
- 0.000172769 0.000146031 0.000130097 0.000117578 0.000105059
- 9.25401e-05 8.00213e-05 7.11204e-05 6.67061e-05 6.22918e-05
- 5.78775e-05 5.34632e-05 4.90489e-05 4.46346e-05 4.02203e-05
- 3.5806e-05 3.13916e-05 2.69773e-05 2.4827e-05 2.31747e-05
- 2.15225e-05 1.98702e-05 1.8218e-05 1.65658e-05 1.49135e-05
- 1.32613e-05 1.1609e-05 9.95678e-06 8.50108e-06 7.86765e-06
- 7.23422e-06 6.60079e-06 5.96736e-06 5.33393e-06 4.7005e-06
- 4.06707e-06 3.43363e-06
- EOD
-
- @v[10].set(<<-'EOD')
- 1.86175 1.99308 2.16619 2.46661 3.09359 3.76864 4.31299
- 4.65564 4.83425 4.92153 4.96157 4.98063 4.98649 4.99039
- 4.9945 4.9972 4.96206 4.89882 4.83865 4.83202 4.91016 5.04479
- 5.06078 5.04827 5.03474 5.0246 5.01639 5.00996 5.00569 5.00239
- 5.00043 5.00296 5.00437 5.00382 5.00287 5.00208 5.00148
- 5.00104 5.00073 5.0005 5.00034 5.00023 5.00016 5.00011 5.00008
- 5.00007 5.00007 5.00004 5 4.99998 4.99998 4.99997 4.99998
- 4.99999 5 5 5.00001 5.00001 5.00001 5.00002 5.00002 5.00001
- 5.00001 5.00001 5.00001 5 5 5 5 5 5 4.99999 4.99999 4.99999
- 4.99999 4.99999 4.99999 4.99999 4.99999 4.99999 4.99999
- 4.99999 4.99999 5 5 5 5 5 5 5 5 5 5.00001 5.00001 5.00001
- 5.00001 5.00001 5.00001 5.00001 5.00001 5.00001 5.00001
- 5.00001 5.00001 5.00001 5.00001 5.00001 5.00001 5.00001
- 5.00001 5.00001 5.00001 5.00001 5 5 5 5 5 5 5 5 5.10081
- 5.10949 4.98359 5.00733 5.15145 4.37298 2.36126 0.470759
- 0.0577238 0.0115884 0.00262611 0.000671499 0.000389038 0.000291291
- 0.000317347 -0.0167823 -0.0158344 -0.0140559 0.0104849 0.0865874
- 0.107813 0.0524688 0.0214369 0.00876443 0.00341595 0.00170778
- 0.00259042 0.0022241 0.00118519 1.10217e-06 -0.000784506
- -0.000948169 -0.000856256 -0.000696719 -0.000485987 -0.000724787
- -0.000981491 -0.001454 -0.00552498 -0.0114992 -0.0105266
- -0.00543527 -0.000982798 0.00127356 0.00224212 0.00275439
- 0.00281098 0.0025471 0.00230368 0.00222576 0.00485522 0.00729453
- 0.00691796 0.0062615 0.00573987 0.0052688 0.00481185 0.00436934
- 0.00394326 0.00352712 0.00309978 0.00270038 0.00235335 0.00203742
- 0.00175256 0.00150067 0.00128126 0.00109323 0.000933619
- 0.000795113 0.000678182 0.00057843 0.000494345 0.000423609
- 0.000363821 0.000312766 0.000269856 0.000232389 0.000198382
- 0.000168126 0.00014267 0.000119293 9.69034e-05 8.5669e-05
- 8.26828e-05 8.64066e-05 9.26665e-05 8.5454e-05 7.82416e-05
- 7.10291e-05 6.38167e-05 5.66043e-05 4.93918e-05 4.21794e-05
- 3.86073e-05 3.53007e-05 3.19941e-05 2.86876e-05 2.5381e-05
- 2.20744e-05 1.87678e-05 1.70933e-05 1.62648e-05 1.54363e-05
- 1.46079e-05 1.37794e-05 1.2951e-05 1.21225e-05 1.12941e-05
- 1.04656e-05 9.63716e-06 8.80871e-06 7.98026e-06 7.1518e-06
- 6.32335e-06 5.5374e-06 5.08959e-06 4.64178e-06 4.19397e-06
- 3.74616e-06 0.0438026 0.0242078 -0.0602019 -0.0840866 0.00148461
- -0.00292489 0.000442098 0.00219489 0.00281478 0.00290756
- 0.00277945 0.00263896 0.00240099 0.00223283 0.001947 -0.0153629
- -0.0148815 -0.0128673 0.0126017 0.0905161 0.11051 0.0538958
- 0.022562 0.00935726 0.00397422 0.00172534 0.000790207 0.000416322
- 0.000191632 0.000469721 0.0009779 0.00192566 0.00200688
- -0.0016502 -0.00733932 -0.0128113 -0.0147608 -0.0115456
- -0.00668995 -0.00401368 -0.00463908 -0.0101197 -0.0118993
- -0.0076276 -0.00262656 0.000813059 0.00264455 0.00350796
- 0.00399494 0.0043049 0.00451658 0.00444739 0.00503842 0.00559516
- 0.00568213 0.00556459 0.0053176 0.00496654 0.00454337 0.00408592
- 0.00362171 0.00317793 0.00277001 0.00240394 0.00207009 0.00176575
- 0.00149725 0.00129045 0.00114257 0.00101135 0.000871672
- 0.000723764 0.000580438 0.000427507 0.000296956 0.000281834
- 0.000376628 0.000412266 0.000367547 0.000295305 0.000264513
- 0.000233721 0.000202929 0.000172137 0.000141345 0.000124721
- 0.000112577 0.000100433 8.82893e-05 7.61453e-05 6.75517e-05
- 6.33609e-05 5.91701e-05 5.49792e-05 5.07884e-05 4.65976e-05
- 4.24067e-05 3.82159e-05 3.40251e-05 2.98342e-05 2.56434e-05
- 2.36401e-05 2.21181e-05 2.05961e-05 1.90741e-05 1.75521e-05
- 1.60301e-05 1.45081e-05 1.29861e-05 1.14641e-05 9.94208e-06
- 8.59252e-06 7.96439e-06 7.33626e-06 6.70813e-06 6.07999e-06
- 5.45186e-06 4.82373e-06 4.1956e-06 3.56747e-06
- EOD
-
- @v[11].set(<<-'EOD')
- 1.86175 1.73419 1.42874 1.04055 0.943004 0.268275 0.0826455
- 0.0388346 0.0214104 0.0135431 0.00961322 0.00712846 0.00588262
- 0.00432397 0.00377774 0.00270134 -0.00393731 -0.00542187
- -0.00126596 0.0113777 0.0134522 0.00477056 -0.00211067 -0.00229253
- -0.00173355 -0.00122404 -0.00113426 -0.000744931 -0.000520112
- -0.000410048 -0.000220439 0.000508104 5.15856e-05 -0.000112593
- -0.000118917 -9.57394e-05 -7.15727e-05 -5.11847e-05 -3.58275e-05
- -2.47166e-05 -1.68866e-05 -1.14082e-05 -7.66646e-06 -5.12139e-06
- -3.63426e-06 -3.01815e-06 -2.64862e-06 -1.4947e-06 -1.91403e-07
- -2.5763e-08 -7.73699e-07 -1.52164e-06 -1.07268e-06 -3.81696e-07
- 2.6727e-07 4.75489e-07 6.83708e-07 8.91926e-07 1.10014e-06
- 1.30836e-06 1.2482e-06 1.00726e-06 7.66311e-07 5.25364e-07
- 2.84417e-07 6.27857e-08 7.43904e-10 -6.12979e-08 -1.2334e-07
- -1.85382e-07 -2.47423e-07 -3.09465e-07 -3.71507e-07 -4.33549e-07
- -4.95591e-07 -5.57633e-07 -6.04571e-07 -5.4944e-07 -4.9431e-07
- -4.3918e-07 -3.84049e-07 -3.28919e-07 -2.73789e-07 -2.18659e-07
- -1.63528e-07 -1.08398e-07 -5.32678e-08 1.062e-09 5.08502e-08
- 1.00638e-07 1.50427e-07 2.00215e-07 2.50003e-07 2.99791e-07
- 3.4958e-07 3.99368e-07 4.49156e-07 4.98944e-07 5.34512e-07
- 5.01032e-07 4.67553e-07 4.34073e-07 4.00593e-07 3.67113e-07
- 3.33633e-07 3.00153e-07 2.66674e-07 2.33194e-07 1.99714e-07
- 1.66234e-07 1.32754e-07 9.92744e-08 6.57945e-08 3.23147e-08
- -1.16513e-09 -3.4645e-08 -6.81248e-08 -1.01605e-07 -1.35084e-07
- -1.68564e-07 -2.18729e-07 0.0114926 -0.0245378 -0.111828
- 0.0964775 1.61491 3.22668 4.22041 4.54492 4.82845 4.94868
- 4.98588 4.99609 4.9981 4.99908 4.99788 4.98395 4.99294 4.99724
- 5.01939 5.0471 5.00902 4.98194 4.98496 4.99188 4.99623 4.99862
- 5.00025 4.99974 4.99953 4.99946 4.99958 5.00012 4.99997
- 4.99992 4.99988 4.99985 4.9998 4.9997 4.9988 4.99806 4.99982
- 5.00143 5.00159 5.00098 5.00053 5.00028 5.00007 4.99977
- 4.99992 5.00005 5.00133 5.0009 4.99993 4.99972 4.99975 4.9998
- 4.99982 4.99983 4.99983 4.99983 4.99983 4.99984 4.99986
- 4.99987 4.99989 4.9999 4.99991 4.99992 4.99994 4.99995 4.99995
- 4.99996 4.99997 4.99997 4.99998 4.99998 4.99998 4.99998
- 4.99999 4.99999 4.99999 4.99999 4.99999 4.99999 4.99999
- 5 5 5 5.00001 5.00001 5.00001 5.00002 5.00002 5.00002 5.00002
- 5.00002 5.00001 5.00001 5.00001 5 5 5 5 5 5 5 5 4.99999
- 4.99999 4.99999 4.99999 4.99999 4.99999 4.99999 4.99999
- 4.99999 4.99999 4.99999 5 5 5.01457 4.99482 4.96561 4.99326
- 5.03452 5.00424 5.00101 5.00045 5.00004 4.99965 4.99997
- 4.99994 4.99958 4.99999 4.99936 4.9839 4.99248 4.99717 5.01976
- 5.04869 5.0087 4.98143 4.98488 4.99199 4.99622 4.9983 4.99928
- 4.99971 4.99986 5.00031 5.00022 5.00035 5.0001 4.99884 4.99811
- 4.99803 4.99887 5.00078 5.00151 5.00116 5.00007 4.99843
- 4.99915 5.00107 5.00168 5.00141 5.00092 5.00055 5.0003 5.00016
- 5.0001 5.00001 5.00016 5.0002 5.00009 4.99993 4.99975 4.99984
- 4.99991 4.99991 4.99982 4.99974 4.99974 4.99985 4.99995
- 4.99999 4.99998 5.00004 5.00013 5.00015 5.00007 4.99988
- 4.99982 4.99985 4.99995 5.00006 5.0002 5.00025 5.0002 5.00009
- 5.00006 5.00004 5.00002 5 4.99998 4.99997 4.99998 4.99998
- 4.99999 4.99999 4.99999 5 5 5 5 5 5.00001 5.00001 5.00001
- 5.00001 5.00001 5.00001 5.00001 5.00001 5.00001 5.00001
- 5.00001 5.00001 5 5 5 5 5 4.99999 4.99999 4.99999 4.99999
- 4.99998 4.99998 4.99998
- EOD
-
- @v[12].set(<<-'EOD')
- 5 5.16975 4.78685 2.94241 0.126698 0.0487004 -0.00422591
- -0.00130689 -0.000486756 -0.000195875 -0.000108988 -6.66736e-05
- -7.26005e-05 -5.63608e-05 -3.81859e-05 -2.123e-05 -0.0646846
- -0.0184474 0.182248 1.06731 3.10988 4.46133 4.84133 4.95113
- 4.98364 4.99455 4.99694 4.99727 4.9994 4.99975 5.0001 5.00132
- 5.00089 5.00039 5.00019 5.00011 5.00006 5.00005 5.00004
- 5.00001 4.99992 4.99992 5.00002 5.00013 5.00017 5.00009
- 4.99992 4.99991 4.99994 4.99996 4.99998 4.99999 5.00001
- 5.00004 5.00006 5.00005 5.00004 5.00003 5.00002 5.00001
- 5 4.99999 4.99999 4.99998 4.99998 4.99997 4.99997 4.99998
- 4.99998 4.99998 4.99998 4.99999 4.99999 4.99999 4.99999
- 5 5 5 5 5 5 5.00001 5.00001 5.00001 5.00001 5.00001 5.00001
- 5.00002 5.00001 5.00001 5.00001 5.00001 5.00001 5.00001
- 5.00001 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 4.99999 4.99999
- 4.99999 4.99999 4.99999 4.99999 4.99999 5 5.14699 4.78074
- 3.19424 0.305663 0.0611255 -0.00179951 -0.0012032 0.000405978
- 0.000989399 0.000445194 0.000191447 8.30476e-05 3.96236e-05
- 1.91866e-05 1.70665e-05 -0.0655239 -0.0210234 0.1827 1.06848
- 3.11554 4.46518 4.84212 4.94853 4.98244 4.99434 4.9997 5.00081
- 5.00009 4.99972 4.99985 4.99974 4.9995 4.99949 4.99958 4.99973
- 4.99948 4.99914 4.99874 4.99946 5.00309 5.0091 5.01576 5.01835
- 5.01852 5.0176 5.01625 5.01479 5.01345 5.01264 5.011 5.01092
- 5.01344 5.01363 5.01289 5.01184 5.01071 5.00956 5.00848
- 5.00751 5.00663 5.00577 5.00497 5.00427 5.00365 5.0031 5.00264
- 5.00224 5.00191 5.00163 5.00138 5.00117 5.00099 5.00083
- 5.00071 5.00061 5.00053 5.00045 5.00037 5.00029 5.00022
- 5.00019 5.0002 5.00023 5.00024 5.00023 5.00023 5.00022 5.0002
- 5.00018 5.00016 5.00014 5.00011 5.00009 5.00007 5.00006
- 5.00005 5.00005 5.00004 5.00003 5.00002 5.00001 5.00001
- 5.00001 5.00001 5.00001 5.00001 5.00001 5.00001 5.00001
- 5.00002 5.00002 5.00002 5.00002 5.00002 5.00002 5.00002
- 5.00002 5.00001 5.00001 5.00001 5.14298 4.79809 3.32704
- 0.498385 0.105773 0.0160646 0.0319912 0.0299434 0.0240102
- 0.0185844 0.0130411 0.0106532 0.00864871 0.00744519 0.00660887
- -0.0612913 -0.0203719 0.174998 0.991787 3.06292 4.60005
- 4.93058 4.98917 5.00033 4.9999 4.99909 4.9966 4.9955 4.99488
- 4.99374 4.9943 5.00131 5.00506 4.99311 4.96288 4.93567 4.92439
- 4.94236 4.9732 4.98864 4.99458 5.00031 5.00694 5.01525 5.01945
- 5.01998 5.01953 5.01874 5.01766 5.0164 5.01509 5.01326 5.01423
- 5.01455 5.01361 5.01245 5.01122 5.01002 5.00888 5.00783
- 5.00687 5.00596 5.00514 5.00442 5.00379 5.00325 5.00279
- 5.0024 5.00208 5.0018 5.00153 5.00126 5.00107 5.00094 5.00085
- 5.00078 5.00072 5.00063 5.00053 5.00042 5.00038 5.00034
- 5.0003 5.00027 5.00023 5.00021 5.00019 5.00017 5.00015 5.00013
- 5.00012 5.00011 5.0001 5.0001 5.00009 5.00008 5.00007 5.00007
- 5.00006 5.00005 5.00005 5.00004 5.00004 5.00003 5.00003
- 5.00002 5.00002 5.00002 5.00001 5.00001 5 5 5 5.00001 5.00001
- 5.00001 5.00002 5.00002 5.00002 5.00002
- EOD
-
- @v[13].set(<<-'EOD')
- 9.73784e-10 0.0189926 0.0926769 0.206309 0.111533 0.0953491
- 0.0426966 0.0214177 0.0117943 0.00741442 0.00528816 0.00398417
- 0.0032967 0.00266499 0.00206647 0.00158788 -0.0371391 -0.0439528
- -0.0408653 -0.0188706 0.0150241 0.0126852 0.00209817 -0.000239206
- -5.31488e-05 0.000876324 -0.00451221 -0.0165223 -0.0284127
- -0.0427584 -0.0502453 -0.0257366 -0.00903938 -0.00376456
- -0.00233385 -0.00169922 -0.00130397 -0.00102542 -0.000811435
- -0.000648115 -0.000529266 -0.00043795 -0.00036574 -0.00030716
- -0.00026221 -0.000229662 -0.000205112 -0.000181038 -0.000162045
- -0.000148988 -0.000137633 -0.000126278 -0.000115562 -0.000104976
- -9.49324e-05 -9.0585e-05 -8.62375e-05 -8.18901e-05 -7.75426e-05
- -7.31952e-05 -6.93752e-05 -6.59106e-05 -6.24461e-05 -5.89815e-05
- -5.55169e-05 -5.22412e-05 -5.05263e-05 -4.88114e-05 -4.70966e-05
- -4.53817e-05 -4.36668e-05 -4.19519e-05 -4.0237e-05 -3.85222e-05
- -3.68073e-05 -3.50924e-05 -3.34782e-05 -3.25442e-05 -3.16102e-05
- -3.06763e-05 -2.97423e-05 -2.88083e-05 -2.78744e-05 -2.69404e-05
- -2.60064e-05 -2.50725e-05 -2.41385e-05 -2.32635e-05 -2.27232e-05
- -2.21829e-05 -2.16426e-05 -2.11023e-05 -2.0562e-05 -2.00217e-05
- -1.94814e-05 -1.89411e-05 -1.84007e-05 -1.78604e-05 -1.73647e-05
- -1.70853e-05 -1.68059e-05 -1.65265e-05 -1.62471e-05 -1.59677e-05
- -1.56883e-05 -1.54089e-05 -1.51295e-05 -1.48501e-05 -1.45707e-05
- -1.42913e-05 -1.40119e-05 -1.37325e-05 -1.34531e-05 -1.31737e-05
- -1.28943e-05 -1.26149e-05 -1.23355e-05 -1.20561e-05 -1.17767e-05
- -1.14973e-05 -1.10954e-05 0.0152675 0.0228237 -0.00460678
- -0.0341525 0.0232109 -0.0138039 -0.0416538 -0.0458764 -0.0201967
- -0.00878316 -0.00379173 -0.00164621 -0.000785131 -0.00037575
- -0.000352375 -0.0545586 -0.0746881 -0.0771865 -0.05386 -0.0022199
- 0.0136703 0.00633526 0.00138826 -0.00108934 0.0038886 0.0298077
- 0.0475776 0.0481003 0.0464167 0.047818 0.042789 0.035207
- 0.0264423 0.0193959 0.0151614 0.00624257 -0.00913057 -0.0310696
- -0.0430238 0.016426 0.189762 0.49025 0.820116 1.13919 1.43549
- 1.70658 1.95183 2.17414 2.38506 2.5657 2.73958 2.97905 3.21403
- 3.43025 3.62645 3.8028 3.96002 4.09996 4.22443 4.33427 4.42886
- 4.51097 4.5817 4.64326 4.6957 4.74132 4.7797 4.81298 4.84102
- 4.86512 4.88523 4.90224 4.91649 4.92846 4.93868 4.94755
- 4.95483 4.96114 4.96682 4.97161 4.97502 4.9776 4.97944 4.98141
- 4.98319 4.98467 4.98585 4.9869 4.98796 4.98902 4.99008 4.99114
- 4.9922 4.99326 4.9938 4.99429 4.99479 4.99528 4.99578 4.99628
- 4.99677 4.99704 4.99718 4.99733 4.99747 4.99762 4.99777
- 4.99791 4.99806 4.9982 4.99835 4.9985 4.99864 4.99879 4.99893
- 4.99907 4.99916 4.99925 4.99934 4.99943 5.01473 4.92293
- 4.61974 4.0316 3.7835 3.74195 3.78344 3.87272 3.97386 4.07319
- 4.16686 4.25256 4.33126 4.40264 4.46697 4.49249 4.51807
- 4.55803 4.64055 4.78574 4.86074 4.88334 4.8999 4.91455 4.92814
- 4.93926 4.94761 4.95433 4.95907 4.9654 4.98317 5.0208 5.05134
- 4.85852 4.16041 3.00077 1.68376 0.672707 0.240838 0.0794725
- -0.0106347 -0.00879443 0.107196 0.368163 0.701424 1.03581
- 1.3601 1.6678 1.95731 2.22701 2.47544 2.69099 2.92327 3.16648
- 3.3877 3.59067 3.77344 3.93584 4.08066 4.20863 4.32065 4.41791
- 4.50211 4.57423 4.63614 4.68888 4.73377 4.7721 4.80519 4.83338
- 4.85732 4.87815 4.89514 4.90927 4.92108 4.93122 4.94014
- 4.94845 4.95601 4.96251 4.96576 4.969 4.97225 4.9755 4.97874
- 4.98087 4.98265 4.98442 4.9862 4.98797 4.98924 4.9899 4.99055
- 4.9912 4.99186 4.99251 4.99316 4.99381 4.99447 4.99512 4.99577
- 4.99609 4.99634 4.99659 4.99683 4.99708 4.99732 4.99757
- 4.99782 4.99806 4.99831 4.99853 4.99863 4.99873 4.99883
- 4.99893 4.99903 4.99913 4.99923 4.99933
- EOD
-
- @v[14].set(<<-'EOD')
- 1.86175 2.00147 1.85141 1.0654 0.275481 0.205547 0.0712627
- 0.0313387 0.0151431 0.00864531 0.00593861 0.00438111 0.0037479
- 0.00305857 0.00221221 0.0017081 -0.0896128 -0.109079 -0.121356
- -0.0542001 0.175821 0.177442 0.0814591 0.0333042 0.0134909
- 0.00625777 0.00100092 -0.00552776 -0.00411139 -0.00150395
- -0.000564784 3.48169e-05 -0.000287014 -0.000538515 -0.000456537
- -0.000325677 -0.000275468 -0.000166452 -8.27481e-05 -8.28704e-05
- -7.47644e-05 -4.60552e-05 -2.61481e-06 2.26359e-05 2.53852e-05
- -1.39853e-06 -4.23456e-05 -4.0907e-05 -2.8501e-05 -1.5945e-05
- -9.01122e-06 -2.07747e-06 1.49328e-06 4.38398e-06 6.84248e-06
- 4.76711e-06 2.69173e-06 6.16362e-07 -1.45901e-06 -3.53438e-06
- -4.14256e-06 -3.76238e-06 -3.3822e-06 -3.00202e-06 -2.62184e-06
- -2.24878e-06 -1.93456e-06 -1.62033e-06 -1.3061e-06 -9.91867e-07
- -6.77638e-07 -3.63409e-07 -4.91792e-08 2.6505e-07 5.7928e-07
- 8.93509e-07 1.16076e-06 1.11055e-06 1.06034e-06 1.01014e-06
- 9.59927e-07 9.09719e-07 8.59511e-07 8.09302e-07 7.59094e-07
- 7.08886e-07 6.58678e-07 5.99251e-07 4.87523e-07 3.75795e-07
- 2.64068e-07 1.5234e-07 4.06119e-08 -7.1116e-08 -1.82844e-07
- -2.94572e-07 -4.063e-07 -5.18027e-07 -6.08517e-07 -5.95879e-07
- -5.83241e-07 -5.70604e-07 -5.57966e-07 -5.45328e-07 -5.3269e-07
- -5.20053e-07 -5.07415e-07 -4.94777e-07 -4.8214e-07 -4.69502e-07
- -4.56864e-07 -4.44226e-07 -4.31589e-07 -4.18951e-07 -4.06313e-07
- -3.93676e-07 -3.81038e-07 -3.684e-07 -3.55762e-07 -3.43125e-07
- 1.06736e-05 0.0797407 0.0437947 -0.0645098 -0.0877312 0.0653203
- -0.00621184 -0.0353188 -0.0491378 -0.0251957 -0.0110996
- -0.00481123 -0.0020941 -0.000998038 -0.000478747 -0.000445332
- -0.102046 -0.135753 -0.154351 -0.0827509 0.163348 0.174012
- 0.0794822 0.0310624 0.0112213 0.00249061 0.00130764 0.00181315
- 0.00163875 0.00101454 0.000497435 0.000195258 5.31901e-05
- 2.4607e-05 6.62736e-05 7.90718e-05 4.0372e-05 -0.000141184
- -0.000280623 5.5608e-05 0.000799565 0.000920189 0.000931616
- 0.000494527 0.000162303 -8.24884e-05 -0.000183938 -0.000203899
- -0.000144788 -9.87063e-05 -0.000227929 2.93932e-05 0.000208563
- 1.88958e-06 -7.6335e-05 -0.000172472 -0.000165656 -0.000145889
- -0.000177311 -0.000191058 -0.000168287 -0.00015755 -0.00013142
- -8.10488e-05 -6.36115e-05 -7.8699e-05 -8.11282e-05 -7.98625e-05
- -5.98807e-05 -3.40879e-05 -1.95464e-05 -1.79247e-05 -4.45514e-05
- -7.47995e-05 -8.7682e-05 -7.50806e-05 -3.25561e-05 -4.34114e-05
- -7.69099e-05 -0.000141101 -0.00018743 -0.000148471 -5.06546e-05
- 0.000120195 0.000177635 0.000177052 0.000146344 9.75126e-05
- 8.31233e-05 6.8734e-05 5.43447e-05 3.99554e-05 2.55661e-05
- 1.11768e-05 -3.21253e-06 -3.88937e-06 -3.56628e-06 -3.24318e-06
- -2.92008e-06 -2.59699e-06 -2.27389e-06 -1.9508e-06 -1.73227e-06
- -1.56796e-06 -1.40365e-06 -1.23934e-06 -1.07503e-06 -9.10722e-07
- -7.46412e-07 -5.82101e-07 -4.1779e-07 -2.5348e-07 -8.91694e-08
- 7.51412e-08 2.39452e-07 4.03762e-07 5.95733e-07 1.00771e-06
- 1.41969e-06 1.83167e-06 2.24365e-06 0.0828257 0.231038 0.465438
- 1.54516 2.8461 3.19221 3.40395 3.6382 3.80758 3.93848 4.04882
- 4.15428 4.247 4.32917 4.40235 4.36941 4.397 4.48862 4.64552
- 4.86595 5.03475 5.0348 5.02627 5.01967 5.01542 5.00925 4.98613
- 4.9519 4.91581 4.87357 4.82302 4.80403 4.82565 4.86102 4.89483
- 4.92253 4.94428 4.96257 4.97608 4.98373 4.98823 4.99182
- 4.99437 4.99635 4.99745 4.99802 4.99843 4.99873 4.99895
- 4.99912 4.99925 4.99931 4.99962 4.99973 4.99972 4.99971
- 4.9997 4.99969 4.9997 4.99971 4.99973 4.99974 4.99976 4.99978
- 4.9998 4.99982 4.99985 4.99987 4.99989 4.9999 4.99991 4.99991
- 4.99993 4.99994 4.99997 5.00001 5.00006 5.00008 5.00006
- 5.00002 5 4.99999 4.99998 4.99997 4.99995 4.99995 4.99995
- 4.99995 4.99995 4.99995 4.99995 4.99996 4.99997 4.99997
- 4.99998 4.99999 5 5 5.00001 5.00002 5.00002 5.00002 5.00002
- 5.00002 5.00002 5.00002 5.00002 5.00002 5.00002 5.00001
- 5.00001 5.00001 5.00001 5.00001 5 5 5 4.99999 4.99999 4.99999
- EOD
-
- @v[15].set(<<-'EOD')
- 1.86175 2.00199 2.08919 1.84314 1.08254 0.214737 0.0377351
- 0.00952455 0.00232763 0.000563614 0.000263477 0.000148642
- 0.000285086 0.000242592 7.34699e-05 -1.53467e-05 -0.0161874
- -0.0157876 -0.0141194 0.0132576 0.0903272 0.109938 0.0535295
- 0.0224216 0.00940945 0.00466825 -0.000649972 -0.00654752
- -0.00333248 -0.00103671 -0.000508276 -5.8896e-05 -0.00043938
- -0.000544704 -0.00044444 -0.000307093 -0.00024517 -0.000154538
- -8.78602e-05 -7.10461e-05 -6.06485e-05 -3.91039e-05 -8.45988e-06
- 9.43442e-06 1.28351e-05 -2.16734e-06 -2.6142e-05 -2.54768e-05
- -1.88997e-05 -1.17906e-05 -7.3808e-06 -2.97101e-06 1.19146e-07
- 2.94246e-06 5.38942e-06 3.88851e-06 2.38761e-06 8.86704e-07
- -6.14201e-07 -2.11511e-06 -2.59565e-06 -2.38885e-06 -2.18205e-06
- -1.97525e-06 -1.76845e-06 -1.56241e-06 -1.36258e-06 -1.16276e-06
- -9.62939e-07 -7.63116e-07 -5.63293e-07 -3.6347e-07 -1.63647e-07
- 3.61756e-08 2.35999e-07 4.35822e-07 6.07653e-07 5.90323e-07
- 5.72994e-07 5.55665e-07 5.38336e-07 5.21007e-07 5.03678e-07
- 4.86349e-07 4.6902e-07 4.51691e-07 4.34361e-07 4.11899e-07
- 3.60315e-07 3.08731e-07 2.57146e-07 2.05562e-07 1.53977e-07
- 1.02393e-07 5.08082e-08 -7.76222e-10 -5.23607e-08 -1.03945e-07
- -1.47815e-07 -1.54225e-07 -1.60635e-07 -1.67045e-07 -1.73455e-07
- -1.79864e-07 -1.86274e-07 -1.92684e-07 -1.99094e-07 -2.05504e-07
- -2.11914e-07 -2.18324e-07 -2.24734e-07 -2.31144e-07 -2.37554e-07
- -2.43964e-07 -2.50373e-07 -2.56783e-07 -2.63193e-07 -2.69603e-07
- -2.76013e-07 -2.82423e-07 2.92534e-06 0.0446777 0.024278
- -0.0518987 -0.0636547 0.00983929 -0.000518204 -0.000265194
- 0.000154772 0.000299538 3.12715e-05 -3.18225e-05 -2.48268e-05
- -1.16701e-05 -6.05117e-06 7.61116e-06 -0.0163668 -0.0158244
- -0.0141177 0.0100085 0.0857144 0.107784 0.051862 0.0204448
- 0.00629858 0.000967736 0.00121674 0.00190276 0.00154009
- 0.000860922 0.000410386 0.000164585 3.99493e-05 1.93797e-05
- 5.67594e-05 0.000110126 2.49925e-05 -7.17815e-05 -0.000142299
- -1.63109e-05 0.000439529 0.000562489 0.000594599 0.000326164
- 0.000126423 -4.26063e-05 -0.000122927 -0.000114152 -6.72706e-05
- -6.41242e-05 -0.000135588 2.61507e-05 0.000134036 6.43734e-06
- -4.6223e-05 -0.000112047 -0.000101388 -8.67847e-05 -0.000117664
- -0.000133957 -0.000116558 -0.000100873 -7.65448e-05 -4.44964e-05
- -3.6677e-05 -5.26632e-05 -5.45172e-05 -5.13545e-05 -3.73869e-05
- -1.99732e-05 -1.0907e-05 -1.10081e-05 -3.02609e-05 -5.18517e-05
- -6.13597e-05 -5.30706e-05 -2.39572e-05 -3.24146e-05 -5.70062e-05
- -0.000103448 -0.000135376 -0.0001024 -2.39007e-05 0.000110929
- 0.000151226 0.000142044 0.000105922 5.62834e-05 4.78476e-05
- 3.94117e-05 3.09759e-05 2.25401e-05 1.41042e-05 5.66837e-06
- -2.76747e-06 -3.08639e-06 -2.81341e-06 -2.54043e-06 -2.26745e-06
- -1.99447e-06 -1.72149e-06 -1.44851e-06 -1.26226e-06 -1.12096e-06
- -9.79661e-07 -8.38363e-07 -6.97065e-07 -5.55768e-07 -4.1447e-07
- -2.73173e-07 -1.31875e-07 9.42259e-09 1.5072e-07 2.92018e-07
- 4.33315e-07 5.74613e-07 7.10363e-07 8.01984e-07 8.93604e-07
- 9.85225e-07 1.07685e-06 0.04474 0.0928765 0.141327 0.0176048
- -0.071675 -0.0124613 0.989022 2.28104 3.40619 4.21417 4.67173
- 4.87438 4.96044 4.98996 4.99858 4.96672 4.89502 4.79391
- 4.76433 4.8387 4.98612 5.0161 5.01722 5.01437 5.01256 4.99827
- 4.95807 4.9209 4.88217 4.83006 4.78461 4.80759 4.85548 4.89604
- 4.9254 4.94617 4.96126 4.97374 4.98255 4.98792 4.99126 4.99361
- 4.99554 4.99699 4.99792 4.99846 4.99881 4.99905 4.99924
- 4.99938 4.99949 4.99955 4.9997 4.9998 4.99982 4.99982 4.99982
- 4.99982 4.99982 4.99983 4.99984 4.99985 4.99986 4.99987
- 4.99988 4.99989 4.9999 4.99992 4.99993 4.99994 4.99995 4.99995
- 4.99996 4.99996 4.99998 4.99999 5.00001 5.00002 5.00002
- 5.00001 5.00001 5 4.99999 4.99999 4.99998 4.99998 4.99998
- 4.99998 4.99998 4.99998 4.99998 4.99998 4.99998 4.99998
- 4.99999 4.99999 4.99999 4.99999 5 5 5 5 5 5 5.00001 5.00001
- 5.00001 5.00001 5.00001 5.00001 5.00001 5.00001 5.00001
- 5.00001 5.00001 5.00001 5.00001 5.00001 5.00001 5.00001
- EOD
-
- @v[16].set(<<-'EOD')
- 1.86175 1.73073 1.50572 1.89001 3.39004 4.36034 4.79012
- 4.93798 4.98305 4.99539 4.9979 4.99904 4.99772 4.9983 4.99935
- 4.99975 4.98837 4.99456 4.99728 5.01838 5.04568 5.00759
- 4.98112 4.98479 4.99197 4.99641 4.99747 4.99775 5.00043
- 5.0007 5.00035 5.00023 4.99976 5.00002 5.00007 5.0002 4.99993
- 5.00003 5.00021 5.00006 4.99993 4.99992 5.00002 5.00013
- 5.00017 5.00009 4.99992 4.99991 4.99993 4.99996 4.99998
- 4.99999 5.00001 5.00003 5.00005 5.00004 5.00004 5.00003
- 5.00002 5.00001 5 4.99999 4.99999 4.99998 4.99998 4.99997
- 4.99997 4.99998 4.99998 4.99998 4.99998 4.99999 4.99999
- 4.99999 4.99999 5 5 5 5 5 5 5.00001 5.00001 5.00001 5.00001
- 5.00001 5.00001 5.00002 5.00001 5.00001 5.00001 5.00001
- 5.00001 5.00001 5.00001 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5
- 5 4.99999 4.99999 4.99999 4.99999 4.99999 4.99999 4.99999
- 4.99999 5 5.01498 4.99342 4.96899 5.00301 5.02627 4.9977
- 4.99548 4.99757 5.00277 5.00245 5.0014 5.00069 5.00032 5.00014
- 5.00009 4.9867 4.99262 4.99607 5.01805 5.04713 5.00927 4.98184
- 4.98483 4.9914 4.99616 4.99902 4.9999 4.99987 4.99979 4.99981
- 4.99989 4.99994 4.99998 5.0002 5.00001 5.00008 5.00008 5.0001
- 5.00021 5.00032 5.00025 5.00019 5.00006 5.00007 4.99994
- 4.99997 4.99999 5.00023 5.00008 4.99993 4.99998 4.99986
- 4.99982 5.00003 4.99985 4.99996 5.00014 5 4.99984 4.99979
- 4.99982 4.99993 5.00008 5.00011 5.00002 4.99996 4.9999 4.99994
- 5.00001 5.00007 5.00009 4.99995 4.99978 4.99971 4.99976
- 4.99997 4.99996 4.99989 4.99972 4.99955 4.99953 4.99959
- 4.99976 4.9999 5.00005 5.00023 5.00039 5.00034 5.00029 5.00024
- 5.00019 5.00014 5.00009 5.00004 5.00003 5.00002 5.00001
- 5 5 4.99999 4.99998 4.99998 4.99998 4.99998 4.99998 4.99999
- 4.99999 4.99999 4.99999 4.99999 4.99999 4.99999 5 5 5 5
- 5.00001 5.00002 5.00003 5.00004 5.01564 5.03395 5.04932
- 5.11868 3.92502 1.31888 0.163888 0.0946876 0.0789578 0.0565084
- 0.0260333 0.0156986 0.00907667 0.00613629 0.00468417 -0.00174008
- -0.0021422 0.000586962 0.0124937 0.0147977 0.00838454 0.00039383
- -0.000522021 -0.000426598 -0.000290214 -0.00173713 -0.00384132
- -0.00382945 -0.00429219 -0.00580193 -0.00393246 0.0017543
- 0.00423045 0.00408931 0.0031976 0.00245457 0.00187293 0.00159068
- 0.00105697 0.000609902 0.000358825 0.000334125 0.000212708
- 0.000168116 8.97349e-05 5.21578e-05 3.84527e-05 2.93033e-05
- 2.10067e-05 1.59954e-05 1.13917e-05 5.49738e-06 2.77217e-05
- 6.51259e-06 -6.65468e-06 2.09837e-06 -6.617e-06 -4.80187e-06
- 1.55031e-06 4.26536e-06 7.69457e-07 -1.46213e-06 -7.25202e-07
- 3.26501e-06 6.55807e-06 7.524e-06 6.07209e-06 6.00701e-06
- 5.41166e-06 3.86573e-06 1.10651e-06 -2.74603e-06 -2.18566e-06
- 2.3658e-06 8.59956e-06 8.35046e-06 2.90621e-06 -8.75982e-07
- -1.87189e-06 -2.1528e-06 -1.94875e-06 -1.74471e-06 -1.54067e-06
- -1.33662e-06 -1.13258e-06 -8.40567e-07 -5.20743e-07 -2.00918e-07
- 1.18906e-07 4.38731e-07 6.11382e-07 6.01529e-07 5.91675e-07
- 5.81822e-07 5.71968e-07 5.62115e-07 5.52261e-07 5.42407e-07
- 5.32554e-07 5.227e-07 5.12847e-07 4.72812e-07 4.26137e-07
- 3.79462e-07 3.32786e-07 2.86111e-07 2.39436e-07 1.92761e-07
- 1.46086e-07 9.94107e-08 5.27356e-08 -2.77779e-10 -7.98079e-08
- -1.59338e-07 -2.38868e-07 -3.18398e-07 -3.97928e-07 -4.77458e-07
- -5.56988e-07 -6.36519e-07
- EOD
-
- @v[17].set(<<-'EOD')
- 5 5.16963 4.84136 3.33754 0.316206 0.103113 0.0273341 0.0221102
- 0.0177008 0.0143758 0.0115203 0.00929231 0.00752716 0.00625439
- 0.00489872 0.00403656 -0.0657317 -0.0256467 0.165394 0.985963
- 3.05067 4.55799 4.89728 4.92464 4.8882 4.90592 4.97315 4.99241
- 4.99694 4.99845 4.99905 4.99939 4.99959 4.99971 4.9998 4.99986
- 4.9999 4.99993 4.99995 4.99996 4.99997 4.99998 4.99998 4.99999
- 4.99999 4.99999 4.99999 4.99999 5 5.00001 5.00003 5.00005
- 5.00004 5.00002 5 4.99999 4.99999 4.99998 4.99998 4.99997
- 4.99997 4.99998 4.99998 4.99999 4.99999 5 5 5 5 5 5.00001
- 5.00001 5.00001 5.00001 5.00001 5.00001 5.00002 5.00001
- 5.00001 5.00001 5.00001 5.00001 5.00001 5.00001 5 5 5 5
- 5 5 5 4.99999 4.99999 4.99999 4.99999 4.99999 4.99999 4.99998
- 4.99998 4.99998 4.99999 4.99999 4.99999 4.99999 4.99999
- 4.99999 4.99999 4.99999 4.99999 4.99999 4.99999 4.99999
- 4.99999 4.99999 5 5 5 5 5 5 5.00025 5.1657 4.69981 2.43895
- 0.0229743 0.0351406 -0.0211974 -0.0312063 -0.0160331 -0.0021718
- -0.000766597 -0.000251052 -5.49363e-05 -3.36364e-06 -2.01983e-06
- -9.70575e-06 -0.0657007 -0.0205247 0.183332 1.07163 3.11839
- 4.46213 4.84163 4.95195 4.99159 5.02084 5.04029 5.04138
- 5.0271 5.00445 4.97957 4.95702 4.95231 4.97819 4.99191 4.9963
- 4.99822 4.99878 4.99903 4.99925 4.99942 4.9995 4.99954 4.99957
- 4.99961 4.99966 4.9997 4.99974 4.99977 4.99981 4.99983 4.99986
- 4.99988 4.9999 4.99991 4.99992 4.99994 4.99995 4.99995 4.99996
- 4.99997 4.99997 4.99998 4.99998 4.99998 4.99999 4.99999
- 4.99999 4.99999 4.99999 4.99999 4.99999 5 5 5 5 5 5 5 5
- 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5.00001 5.00001 5.00001
- 5.00002 5.00002 5.00002 5.00002 5.00002 5.00002 5.00002
- 5.00002 5.00001 5.00001 5.00001 5.00001 5.00001 5.00001
- 5.00001 5 5 5 4.99999 4.99998 4.99997 4.99996 5.14239 4.76219
- 3.16574 0.299969 0.0631609 -0.00118611 -0.00026052 -5.96333e-05
- -1.44904e-05 -4.3859e-06 -2.99454e-06 1.10547e-06 4.84662e-06
- 1.30971e-05 2.23082e-05 -0.0655844 -0.0204818 0.182507 1.05954
- 3.12277 4.46735 4.83915 4.94512 4.97679 4.98654 4.9966 5.00833
- 5.00776 5.00432 5.00199 5.00086 5.00033 5.00008 5 5.00001
- 5 5.00005 5.00002 4.99981 4.99991 4.99998 4.99979 4.99979
- 4.99984 4.9998 4.9998 5.00006 5.00002 5.00001 5 5 4.99992
- 4.99998 4.99999 5.00002 5.00014 4.99999 4.99987 4.99993
- 5.00003 5.00011 5.00005 4.99996 4.99987 4.99985 4.99994
- 5.00009 5.0001 5 4.99993 4.99997 5.00008 5.00015 5.00021
- 5.00021 5.00007 4.99978 4.99965 4.99973 4.9999 4.99992 4.99995
- 4.99997 4.99999 5.00001 5.00002 5.00001 5.00001 5.00001
- 5 5 5 5 5 4.99999 4.99999 4.99999 4.99999 4.99999 4.99999
- 4.99998 4.99998 4.99999 4.99999 4.99999 4.99999 4.99999
- 4.99999 4.99999 5 5 5 5 5 5.00001 5.00001 5.00001 5.00002
- 5.00002 5.00002
- EOD
-
- @v[18].set(<<-'EOD')
- 5 5.0333 5.02472 4.92559 4.18383 3.93923 3.9961 4.14293
- 4.28591 4.41336 4.52157 4.61101 4.68472 4.7439 4.79294 4.83239
- 4.80697 4.78808 4.79322 4.8838 5.08529 5.21863 4.88852 3.90198
- 2.14586 0.383977 0.101103 0.0525711 0.0318287 0.020895 0.0146908
- 0.010831 0.00830272 0.00656377 0.00532066 0.00440078 0.00369956
- 0.00315713 0.00272614 0.00237965 0.00209659 0.00186339 0.00167014
- 0.0015081 0.00137172 0.00125607 0.00115393 0.00106076 0.000980166
- 0.000918015 0.000862837 0.00080766 0.000763488 0.000721541
- 0.000680825 0.000653026 0.000625226 0.000597426 0.000569627
- 0.000541827 0.000519087 0.000499756 0.000480424 0.000461093
- 0.000441761 0.000423291 0.000411941 0.00040059 0.00038924
- 0.000377889 0.000366539 0.000355188 0.000343838 0.000332487
- 0.000321137 0.000309786 0.000299055 0.000292509 0.000285963
- 0.000279417 0.000272871 0.000266325 0.000259779 0.000253233
- 0.000246686 0.00024014 0.000233594 0.000227387 0.0002231
- 0.000218813 0.000214526 0.00021024 0.000205953 0.000201666
- 0.000197379 0.000193092 0.000188805 0.000184519 0.000180526
- 0.000177963 0.0001754 0.000172837 0.000170274 0.000167711
- 0.000165148 0.000162585 0.000160022 0.000157459 0.000154895
- 0.000152332 0.000149769 0.000147206 0.000144643 0.00014208
- 0.000139517 0.000136954 0.000134391 0.000131828 0.000129265
- 0.000126702 0.000132838 0.0311184 0.163151 0.34986 0.604501
- 0.357125 0.136137 0.0711304 0.0346959 0.0212674 0.00872193
- 0.00252206 0.000455269 7.59332e-05 2.91532e-05 0.000320562
- -0.0720911 -0.0840491 -0.0791345 -0.0404143 0.0182035 -0.0235871
- -0.0426072 -0.0597501 0.00824773 0.481404 1.32496 2.11949
- 2.57317 2.58202 2.15054 1.33786 0.45702 0.153772 0.0913584
- 0.0604989 0.0421591 0.0271456 0.0170021 0.0115815 0.00907886
- 0.00742466 0.00626096 0.00531127 0.00450501 0.00381927 0.00323718
- 0.00274374 0.00232494 0.00196885 0.00166686 0.00141134 0.00119437
- 0.0010109 0.000855534 0.000723378 0.000611408 0.000516704
- 0.000436769 0.000369523 0.000313026 0.00026526 0.000223976
- 0.000188972 0.000159042 0.000134148 0.000112688 9.49738e-05
- 7.97877e-05 6.721e-05 5.65115e-05 4.77194e-05 4.03591e-05
- 3.42848e-05 2.92627e-05 2.50435e-05 2.1412e-05 1.84532e-05
- 1.58624e-05 1.34673e-05 1.14461e-05 1.00935e-05 9.12375e-06
- 8.50202e-06 7.81431e-06 7.20729e-06 6.73936e-06 6.3702e-06
- 5.90049e-06 5.43077e-06 4.96105e-06 4.49133e-06 4.02162e-06
- 3.5519e-06 3.08218e-06 2.79099e-06 2.51281e-06 2.23463e-06
- 1.95645e-06 1.67827e-06 1.40009e-06 1.12191e-06 1.01376e-06
- 9.9375e-07 9.73741e-07 9.53733e-07 9.33724e-07 9.13715e-07
- 8.93707e-07 8.73698e-07 8.5369e-07 8.33681e-07 8.13673e-07
- 7.93664e-07 7.73655e-07 7.53647e-07 7.21781e-07 5.956e-07
- 4.69419e-07 3.43239e-07 2.17058e-07 0.0284032 0.0374438
- -0.0157543 -0.0680497 0.0504768 0.0100294 0.00222261 0.000528697
- 0.000132929 3.99489e-05 2.46066e-05 4.56327e-06 -6.54853e-06
- 1.33783e-05 -3.68221e-05 -0.0724498 -0.0843663 -0.0792935
- -0.0406426 0.0200019 0.0426259 0.0220753 0.00668555 -0.000968483
- 0.024662 0.0383437 0.0911513 0.087848 0.0602076 0.0390559
- 0.0260573 0.0180444 0.012974 0.00985409 0.00788132 0.0064228
- 0.005545 0.00453571 0.00364245 0.00310278 0.00270523 0.00236439
- 0.0020945 0.00186808 0.00167493 0.00151731 0.00138594 0.00126945
- 0.00116695 0.0010762 0.000996366 0.000928387 0.000864414
- 0.000808258 0.000759574 0.000713865 0.000666712 0.000632716
- 0.000601262 0.000572163 0.000543986 0.000515253 0.0004897
- 0.000468112 0.000449313 0.000432981 0.000417911 0.000401307
- 0.000382712 0.000366678 0.000355736 0.000349171 0.000335727
- 0.000317091 0.000296086 0.000283543 0.000277366 0.000272233
- 0.000267001 0.000263147 0.000256699 0.000250251 0.000243803
- 0.000237355 0.000230907 0.000225424 0.000220247 0.000215069
- 0.000209892 0.000204714 0.000200213 0.000196548 0.000192884
- 0.00018922 0.000185556 0.000181892 0.000178228 0.000174564
- 0.0001709 0.000167236 0.000163572 0.000160824 0.000158279
- 0.000155733 0.000153187 0.000150641 0.000148095 0.000145549
- 0.000143003 0.000140457 0.000137911 0.000135457 0.000133386
- 0.000131315 0.000129245 0.000127174 0.000125103 0.000123032
- 0.000120961 0.000118891
- EOD
-
- @v[19].set(<<-'EOD')
- 1.86175 1.99994 2.0833 2.01627 2.42503 3.25769 3.62134 3.88827
- 4.09688 4.26773 4.40529 4.51734 4.60827 4.68313 4.74346
- 4.79302 4.72815 4.68959 4.70421 4.81316 5.01375 5.14493
- 5.10305 5.0699 5.04484 5.03751 5.03348 5.02504 5.01799 5.01271
- 5.00895 5.00628 5.0044 5.00309 5.00216 5.00151 5.00105 5.00073
- 5.00051 5.00034 5.00023 5.00015 5.0001 5.00007 5.00003 4.99998
- 4.99993 4.99993 4.99995 4.99999 5.00001 5.00003 5.00002
- 5.00001 5 5 5 5 4.99999 4.99999 4.99999 5 5 5 5 5 5 5 5
- 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5
- 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5.00017 5.17398
- 4.94779 3.78508 1.52302 0.608808 0.244311 0.126053 0.0597175
- 0.038422 0.0158174 0.00481338 0.00107847 0.000301256 0.000114861
- 0.00059489 -0.118904 -0.147478 -0.158986 -0.080544 0.165361
- 0.171378 0.0776087 0.0435738 0.0428235 0.0423755 0.0347695
- 0.0225061 0.0155539 0.0121357 0.0107997 0.0103976 0.0124406
- 0.016814 0.0167556 0.0149852 0.01459 0.0141182 0.0131934
- 0.0120286 0.0108692 0.0097184 0.00855881 0.00744912 0.00643877
- 0.00554044 0.00475165 0.00406535 0.00347158 0.00295981 0.00251995
- 0.00214318 0.00182101 0.00154613 0.00131196 0.0011119 0.000941587
- 0.000796999 0.000674582 0.000571283 0.000484276 0.000410649
- 0.000347005 0.000292984 0.000246715 0.000208143 0.00017489
- 0.000147412 0.000123854 0.000104332 8.77229e-05 7.40686e-05
- 6.2637e-05 5.32e-05 4.53946e-05 3.88343e-05 3.31864e-05
- 2.85905e-05 2.45725e-05 2.08671e-05 1.77301e-05 1.55911e-05
- 1.40153e-05 1.29421e-05 1.18693e-05 1.09815e-05 1.03484e-05
- 9.87664e-06 9.14446e-06 8.41228e-06 7.68011e-06 6.94793e-06
- 6.21575e-06 5.48357e-06 4.7514e-06 4.38454e-06 4.04432e-06
- 3.7041e-06 3.36388e-06 3.02366e-06 2.68344e-06 2.34322e-06
- 2.15196e-06 2.03791e-06 1.92386e-06 1.80982e-06 1.69577e-06
- 1.58173e-06 1.46768e-06 1.35363e-06 1.23959e-06 1.12554e-06
- 1.0115e-06 8.9745e-07 7.83404e-07 6.69358e-07 4.76113e-07
- -3.47071e-07 -1.17025e-06 -1.99344e-06 -2.81662e-06 0.0783754
- 0.0500262 -0.0659563 -0.120914 0.0815957 0.0154255 0.00347177
- 0.000840357 0.000214582 6.54655e-05 3.91709e-05 8.07396e-06
- -4.44265e-07 1.74384e-05 -4.52725e-05 -0.119379 -0.147984
- -0.159247 -0.0824604 0.169014 0.177628 0.0758742 0.010558
- -0.0346506 -0.0710288 -0.0838952 -0.0599521 -0.034568 -0.0181615
- -0.00968034 -0.00547115 -0.00333511 -0.00232468 -0.00181159
- -0.00143841 -0.00116601 -0.000839755 -0.000569764 -0.000578683
- -0.000490551 -0.000411712 -0.000437859 -0.000408185 -0.000356644
- -0.000311332 -0.000269006 -0.000221396 -0.000210054 -0.0001923
- -0.000175122 -0.000161039 -0.0001428 -0.000126123 -0.000127893
- -8.14516e-05 -0.000120166 -0.000154909 -0.000112733 -8.40377e-05
- -7.11342e-05 -8.09538e-05 -9.77789e-05 -9.82402e-05 -7.73531e-05
- -5.28255e-05 -3.1096e-05 -1.87967e-05 -1.96552e-05 -4.16655e-05
- -5.77185e-05 -5.24142e-05 -2.83153e-05 -1.90012e-05 -1.54415e-05
- -2.52569e-05 -6.23747e-05 -0.000130543 -0.000149394 -0.000110886
- -4.35517e-05 -4.17084e-05 -3.98651e-05 -3.80218e-05 -3.61785e-05
- -3.43352e-05 -3.36249e-05 -3.32729e-05 -3.29208e-05 -3.25687e-05
- -3.22166e-05 -3.17143e-05 -3.10258e-05 -3.03372e-05 -2.96486e-05
- -2.89601e-05 -2.82715e-05 -2.75829e-05 -2.68944e-05 -2.62058e-05
- -2.55173e-05 -2.48287e-05 -2.43043e-05 -2.38159e-05 -2.33276e-05
- -2.28393e-05 -2.2351e-05 -2.18626e-05 -2.13743e-05 -2.0886e-05
- -2.03977e-05 -1.99093e-05 -1.945e-05 -1.91122e-05 -1.87744e-05
- -1.84366e-05 -1.80987e-05 -1.77609e-05 -1.74231e-05 -1.70853e-05
- -1.67474e-05
- EOD
-
- @v[20].set(<<-'EOD')
- 1.86175 1.99724 2.17266 2.48439 3.15933 3.85231 4.38091
- 4.69033 4.85034 4.92851 4.96453 4.98188 4.98736 4.991 4.99482
- 4.9973 4.96422 4.89989 4.83907 4.83151 4.90868 5.04854 5.06104
- 5.04571 5.03219 5.03025 5.02273 5.01707 5.0123 5.0087 5.00611
- 5.00429 5.00301 5.00211 5.00148 5.00103 5.00072 5.0005 5.00035
- 5.00024 5.00016 5.00011 5.00007 5.00005 5.00003 5.00001
- 4.99999 4.99998 4.99998 4.99998 4.99998 4.99998 4.99999
- 5 5 5.00001 5.00001 5.00002 5.00002 5.00002 5.00002 5.00002
- 5.00002 5.00001 5.00001 5 5 5 5 5 5 4.99999 4.99999 4.99999
- 4.99999 4.99999 4.99999 4.99999 4.99999 4.99999 4.99999
- 4.99999 4.99999 4.99999 5 5 5 5 5 5 5 5 5.00001 5.00001
- 5.00001 5.00001 5.00001 5.00001 5.00001 5.00001 5.00001
- 5.00001 5.00001 5.00001 5.00001 5.00001 5.00001 5.00001
- 5.00001 5.00001 5.00001 5.00001 5.00001 5.00001 5 5 5 5
- 5 5 4.99981 5.10081 5.10903 4.98404 5.00999 5.14946 4.36501
- 2.23938 0.325144 0.00660272 -0.0102186 -0.0082401 -0.00556785
- -0.00374178 -0.00264763 -0.00202823 -0.0182241 -0.0169551
- -0.0150395 0.0103736 0.0877592 0.104382 0.0515938 0.0373818
- 0.0411547 0.0397009 0.0308946 0.0205793 0.0154037 0.0129191
- 0.0119327 0.011527 0.0124295 0.0161152 0.0161076 0.0145391
- 0.0144541 0.0139287 0.0129215 0.0117239 0.0105795 0.00942983
- 0.00827423 0.00718354 0.00619954 0.00532868 0.00456631 0.00390448
- 0.00333254 0.00284003 0.00241714 0.00205524 0.0017458 0.00148202
- 0.00125739 0.0010655 0.000902213 0.000763611 0.000646279
- 0.000547291 0.000463934 0.000393401 0.000332424 0.000280655
- 0.000236328 0.000199386 0.000167536 0.000141218 0.000118654
- 9.99559e-05 8.40479e-05 7.09694e-05 6.00188e-05 5.09786e-05
- 4.3502e-05 3.72191e-05 3.18114e-05 2.74071e-05 2.35539e-05
- 1.99967e-05 1.69871e-05 1.49449e-05 1.3451e-05 1.24492e-05
- 1.14256e-05 1.05669e-05 9.94487e-06 9.47514e-06 8.77318e-06
- 8.07123e-06 7.36927e-06 6.66731e-06 5.96536e-06 5.2634e-06
- 4.56144e-06 4.23044e-06 3.92649e-06 3.62254e-06 3.31858e-06
- 3.01463e-06 2.71068e-06 2.40673e-06 2.23063e-06 2.12082e-06
- 2.01102e-06 1.90121e-06 1.7914e-06 1.68159e-06 1.57178e-06
- 1.46197e-06 1.35216e-06 1.24235e-06 1.13255e-06 1.02274e-06
- 9.12929e-07 8.0312e-07 6.33171e-07 -1.51288e-08 -6.63428e-07
- -1.31173e-06 -1.96003e-06 0.0437517 0.0265689 -0.0515377
- -0.0658688 0.010727 -0.000511921 -8.36924e-05 2.13278e-05
- 1.45207e-05 4.54862e-06 -6.14726e-06 2.0062e-06 1.02709e-06
- 1.4152e-05 -3.08225e-05 -0.0166501 -0.0157139 -0.013957
- 0.0107537 0.0873717 0.111302 0.0454129 -0.00530142 -0.0468336
- -0.0790063 -0.0826944 -0.0534753 -0.0288705 -0.0149009 -0.00801592
- -0.0046342 -0.00291835 -0.00213019 -0.00170055 -0.001352
- -0.00110593 -0.000742655 -0.000532042 -0.000544742 -0.000479206
- -0.000407307 -0.000403575 -0.000366209 -0.000324161 -0.000286183
- -0.000247579 -0.000214281 -0.000203435 -0.000186896 -0.000171033
- -0.00015779 -0.000145259 -0.000128069 -0.000122647 -9.89398e-05
- -0.000114926 -0.000132195 -0.000107872 -8.91015e-05 -7.87996e-05
- -8.14061e-05 -8.9098e-05 -8.83368e-05 -7.6122e-05 -6.14668e-05
- -4.75402e-05 -3.81855e-05 -3.69696e-05 -4.78656e-05 -5.61346e-05
- -5.35007e-05 -4.1459e-05 -3.35411e-05 -2.52374e-05 -2.37479e-05
- -4.6406e-05 -9.41884e-05 -0.000109222 -8.52676e-05 -4.25166e-05
- -4.10125e-05 -3.95085e-05 -3.80045e-05 -3.65004e-05 -3.49964e-05
- -3.41627e-05 -3.3541e-05 -3.29193e-05 -3.22976e-05 -3.16758e-05
- -3.10334e-05 -3.03653e-05 -2.96971e-05 -2.9029e-05 -2.83609e-05
- -2.76928e-05 -2.70246e-05 -2.63565e-05 -2.56884e-05 -2.50203e-05
- -2.43521e-05 -2.38716e-05 -2.34324e-05 -2.29932e-05 -2.25539e-05
- -2.21147e-05 -2.16755e-05 -2.12362e-05 -2.0797e-05 -2.03578e-05
- -1.99186e-05 -1.95079e-05 -1.9217e-05 -1.8926e-05 -1.8635e-05
- -1.8344e-05 -1.8053e-05 -1.7762e-05 -1.74711e-05 -1.71801e-05
- EOD
-
- @v[21].set(<<-'EOD')
- 1.86175 1.73273 1.42016 1.02483 0.944013 0.274107 0.0823742
- 0.0379366 0.020816 0.0132952 0.00955525 0.00717008 0.00592286
- 0.00437379 0.00383557 0.00273694 -0.0037467 -0.0054191 -0.00131454
- 0.0112179 0.0133918 0.00519747 -0.00260113 -0.00252847 -0.00181292
- 0.000183398 -0.000667607 -0.000750747 -0.000594314 -0.000433904
- -0.000308985 -0.000217858 -0.000152926 -0.000107454 -7.54076e-05
- -5.2675e-05 -3.66299e-05 -2.54341e-05 -1.75095e-05 -1.18848e-05
- -7.97289e-06 -5.30239e-06 -3.53615e-06 -2.38504e-06 -2.40158e-06
- -3.84485e-06 -5.29435e-06 -2.57099e-06 1.95189e-06 3.55083e-06
- 2.06179e-06 5.72753e-07 3.30469e-07 3.40296e-07 3.60221e-07
- 4.86081e-07 6.1194e-07 7.37799e-07 8.63659e-07 9.89518e-07
- 9.21274e-07 7.22275e-07 5.23276e-07 3.24277e-07 1.25278e-07
- -5.59467e-08 -9.03265e-08 -1.24706e-07 -1.59086e-07 -1.93466e-07
- -2.27846e-07 -2.62226e-07 -2.96605e-07 -3.30985e-07 -3.65365e-07
- -3.99745e-07 -4.24266e-07 -3.82163e-07 -3.40061e-07 -2.97959e-07
- -2.55857e-07 -2.13755e-07 -1.71652e-07 -1.2955e-07 -8.7448e-08
- -4.53457e-08 -3.24353e-09 3.76901e-08 7.19937e-08 1.06297e-07
- 1.40601e-07 1.74904e-07 2.09208e-07 2.43512e-07 2.77815e-07
- 3.12119e-07 3.46422e-07 3.80726e-07 4.04507e-07 3.77191e-07
- 3.49876e-07 3.22561e-07 2.95246e-07 2.67931e-07 2.40616e-07
- 2.13301e-07 1.85986e-07 1.58671e-07 1.31356e-07 1.04041e-07
- 7.67256e-08 4.94105e-08 2.20955e-08 -5.21962e-09 -3.25347e-08
- -5.98498e-08 -8.71649e-08 -1.1448e-07 -1.41795e-07 -1.6911e-07
- 7.87893e-06 0.0114592 -0.0245712 -0.111637 0.0961324 1.61168
- 3.22343 4.20442 4.53535 4.83834 4.95464 4.98874 4.99746
- 4.99883 4.99948 4.99815 4.98431 4.99298 4.99718 5.01948
- 5.04749 5.008 4.98243 4.98985 4.99781 4.99887 4.99679 4.99616
- 4.99743 4.99859 4.99936 4.99972 5.00058 5.00123 5.0002 4.99945
- 4.99983 4.9998 4.99966 4.99958 4.99956 4.99956 4.99956 4.99958
- 4.99961 4.99965 4.99969 4.99973 4.99977 4.9998 4.99983 4.99985
- 4.99987 4.99989 4.99991 4.99992 4.99993 4.99994 4.99995
- 4.99996 4.99997 4.99997 4.99998 4.99998 4.99998 4.99999
- 4.99999 4.99999 4.99999 4.99999 4.99999 4.99999 5 5 5 5
- 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5.00001 5.00001
- 5.00001 5.00002 5.00002 5.00002 5.00002 5.00002 5.00002
- 5.00002 5.00002 5.00001 5.00001 5.00001 5.00001 5.00001
- 5.00001 5.00001 5 5 5 4.99999 4.99998 4.99997 4.99996 5.01454
- 4.99566 4.96796 4.99819 5.03232 5.00034 4.99867 4.99937
- 4.99977 4.99992 4.99997 4.99999 5.00001 5.00021 4.99974
- 4.98462 4.99301 4.99723 5.01936 5.04807 5.00929 4.9789 4.97876
- 4.98244 4.9863 4.99575 5.0069 5.00863 5.00624 5.00357 5.0019
- 5.00098 5.00048 5.00025 5.00016 5.00011 5.00013 5.00009
- 4.99982 4.99994 5.00005 4.99994 4.99988 4.99989 4.99997
- 5.00003 5.00005 5.00002 5.00001 5.00001 5.00001 4.99993
- 4.99999 5 5.00021 4.99997 4.99981 5 5.00009 5.0001 5.00001
- 4.99991 4.9999 5 5.00011 5.00017 5.00018 5.00018 5.00014
- 5.00007 4.99999 4.9999 4.9999 5.00001 5.00016 5.00014 4.99999
- 4.99993 4.99999 5.00009 5.00007 5.00006 5.00004 5.00003
- 5.00001 5.00001 5 4.99999 4.99998 4.99997 4.99997 4.99997
- 4.99998 4.99998 4.99998 4.99998 4.99999 4.99999 4.99999
- 5 5 5 5 5 5 5.00001 5.00001 5.00001 5.00001 5.00001 5.00002
- 5.00002 5.00001 5.00001 5.00001 5.00001 5.00001 5.00001
- 5 5
- EOD
-
- @v[22].set(<<-'EOD')
- 7.10441e-10 0.00107105 0.000637109 -0.00236346 -0.018079
- -0.0120077 -0.00217059 0.00266679 0.00403383 0.00403836
- 0.00356705 0.00303303 0.00244716 0.00198586 0.0016855 0.00136497
- -3.96022e-05 -0.000367409 -3.77079e-05 0.00194085 0.00506964
- -0.0400214 -0.0402572 0.0524434 0.286234 0.803011 1.44795
- 2.02473 2.54768 3.02748 3.4415 3.78287 4.09667 4.35152 4.53987
- 4.67614 4.77407 4.84319 4.89227 4.92702 4.95119 4.96764
- 4.97846 4.98557 4.98982 4.99209 4.99371 4.99569 4.99727
- 4.99802 4.99834 4.99867 4.99892 4.99915 4.99936 4.99939
- 4.99943 4.99946 4.9995 4.99953 4.99957 4.9996 4.99963 4.99967
- 4.9997 4.99973 4.99974 4.99975 4.99976 4.99977 4.99978 4.9998
- 4.99981 4.99982 4.99983 4.99984 4.99985 4.99986 4.99986
- 4.99986 4.99987 4.99987 4.99988 4.99988 4.99989 4.99989
- 4.9999 4.9999 4.9999 4.9999 4.99991 4.99991 4.99991 4.99991
- 4.99992 4.99992 4.99992 4.99992 4.99993 4.99993 4.99993
- 4.99993 4.99993 4.99993 4.99993 4.99993 4.99994 4.99994
- 4.99994 4.99994 4.99994 4.99994 4.99994 4.99994 4.99995
- 4.99995 4.99995 4.99995 4.99995 4.99995 4.99995 5.00145
- 5.00659 5.01209 5.01931 5.00279 4.99273 4.99217 4.99295
- 4.99471 4.99594 4.99696 4.9978 4.99844 4.99891 4.99924 4.99635
- 4.99699 4.99813 5.00068 5.00307 5.0588 4.96365 4.54012 3.6307
- 2.35176 1.0322 0.354379 0.115986 0.0435668 0.0245112 0.020786
- 0.0164656 0.0118409 0.00849698 0.00597078 0.0040105 0.0026076
- 0.0016597 0.00118185 0.00121067 0.00153587 0.00174836 0.00136519
- -0.000189116 -0.00315555 -0.00646603 -0.00898042 -0.010203
- -0.0110896 -0.0123764 -0.00953841 -0.00225795 0.000818314
- 0.00152252 0.00150269 0.00119025 0.000767068 0.000308852
- -3.79272e-05 -0.00019691 -0.000186642 -9.73653e-05 -8.49784e-06
- 2.04147e-05 -9.91086e-06 -1.55959e-05 -1.80499e-05 -1.77097e-05
- -1.51548e-05 -1.1978e-05 -9.84916e-06 -1.29728e-05 -1.67235e-05
- -1.74153e-05 -1.39958e-05 -5.92272e-06 -8.08216e-06 -1.53077e-05
- -2.92531e-05 -3.91049e-05 -2.98935e-05 -7.32122e-06 3.18534e-05
- 4.39134e-05 4.18753e-05 3.22759e-05 1.86766e-05 1.58432e-05
- 1.30098e-05 1.01765e-05 7.34312e-06 4.50975e-06 1.67639e-06
- -1.15697e-06 -1.23877e-06 -1.11991e-06 -1.00106e-06 -8.82208e-07
- -7.63355e-07 -6.44502e-07 -5.2565e-07 -4.29318e-07 -3.44661e-07
- -2.60004e-07 -1.75347e-07 -9.06904e-08 -6.03349e-09 7.86234e-08
- 1.6328e-07 2.47937e-07 3.32594e-07 4.17251e-07 5.01908e-07
- 5.86565e-07 6.71222e-07 7.36123e-07 6.43886e-07 5.5165e-07
- 4.59414e-07 3.67178e-07 0.000334759 -4.60833e-05 -0.00106139
- -0.00166624 0.000859563 0.00102606 0.00410037 0.00419931
- 0.00518997 0.00459791 0.00503125 0.00523877 0.00452158 0.00339924
- 0.00233399 0.000876915 0.000546439 0.000444299 0.000983968
- 0.00119304 -0.0429422 -0.0403983 0.0534896 0.288013 0.807345
- 1.44247 2.03448 2.57021 3.05049 3.47332 3.8131 4.1009 4.34677
- 4.53512 4.67127 4.76531 4.82526 4.86593 4.89586 4.91904
- 4.93806 4.95348 4.96597 4.97629 4.9843 4.98983 4.99335 4.9957
- 4.99741 4.99864 4.99946 4.99994 5.00047 5.00073 5.00086
- 5.00092 5.00094 5.00091 5.00087 5.00081 5.00074 5.00067
- 5.00059 5.00052 5.00046 5.0004 5.00034 5.0003 5.00026 5.00022
- 5.00019 5.00016 5.00014 5.00012 5.0001 5.00009 5.00007 5.00006
- 5.00006 5.00005 5.00004 5.00004 5.00004 5.00003 5.00003
- 5.00003 5.00002 5.00002 5.00002 5.00002 5.00001 5.00001
- 5.00001 5.00001 5.00001 5 5 5 5 4.99999 4.99999 4.99999
- 4.99999 4.99999 4.99999 5 5 5 5 5 5 5 5 5 5.00001 5.00001
- 5.00001 5.00001 5.00002 5.00002
- EOD
-
- @v[23].set(<<-'EOD')
- 5 5.00284 5.01266 5.01895 4.98936 4.99575 4.99217 4.99545
- 4.99775 4.99894 4.99946 4.99968 4.99975 4.99977 4.99986
- 4.9999 4.99528 4.99808 5.00039 5.00392 5.00512 4.99985 4.99863
- 4.99942 4.99992 5.00017 4.99897 4.99803 4.99784 4.99739
- 4.99883 5.00365 5.00298 5.00133 5.00048 5.00019 5.00008
- 5.00005 5.00004 5.00003 5.00002 5.00002 5.00001 5.00001
- 5.00001 5.00001 5.00001 5 5 4.99999 4.99997 4.99995 4.99996
- 4.99998 5 5.00001 5.00001 5.00002 5.00002 5.00003 5.00003
- 5.00002 5.00002 5.00001 5.00001 5 5 5 5 5 4.99999 4.99999
- 4.99999 4.99999 4.99999 4.99999 4.99998 4.99999 4.99999
- 4.99999 4.99999 4.99999 4.99999 4.99999 5 5 5 5 5 5 5 5.00001
- 5.00001 5.00001 5.00001 5.00001 5.00001 5.00001 5.00002
- 5.00002 5.00001 5.00001 5.00001 5.00001 5.00001 5.00001
- 5.00001 5.00001 5.00001 5.00001 5.00001 5.00001 5.00001
- 5.00001 5 5 5 5 5 5 5 5.00217 5.00108 4.99547 4.99658 5.00667
- 4.99641 4.99532 4.99938 5.00328 5.00222 5.00114 5.00052
- 5.00024 5.00011 5.00009 4.99285 4.99591 4.99897 5.00403
- 5.00786 5.00318 4.99942 4.9992 4.99949 5.001 5.00408 5.00319
- 5.00063 4.99995 5.00014 4.99982 4.99832 4.99838 4.99865
- 4.99912 4.99836 4.99735 4.99606 4.99814 5.00958 5.02973
- 5.05293 5.06103 4.99342 4.80726 4.50744 4.07509 3.41358
- 2.37924 1.03194 0.261552 0.142392 0.0904482 0.0555071 0.0322869
- 0.018289 0.0113802 0.00875182 0.00757055 0.00629906 0.00523
- 0.00403349 0.0031953 0.00280864 0.00286119 0.00250389 0.00202815
- 0.001723 0.00147312 0.0012411 0.00104401 0.000886204 0.000758277
- 0.000651915 0.00056348 0.000487966 0.000424048 0.000365613
- 0.000308178 0.000258725 0.000228061 0.000207976 0.000198491
- 0.00018518 0.000172716 0.000163197 0.000155007 0.000141734
- 0.000128461 0.000115188 0.000101915 8.86417e-05 7.53686e-05
- 6.20956e-05 5.69164e-05 5.23275e-05 4.77385e-05 4.31495e-05
- 3.85605e-05 3.39716e-05 2.93826e-05 2.69449e-05 2.56224e-05
- 2.42999e-05 2.29774e-05 2.16549e-05 2.03324e-05 1.90099e-05
- 1.76873e-05 1.63648e-05 1.50423e-05 1.37198e-05 1.23973e-05
- 1.10748e-05 9.75232e-06 8.48447e-06 7.65129e-06 6.81811e-06
- 5.98494e-06 5.15176e-06 0.00056893 -0.00787906 -0.0217381
- -0.0370066 -0.00770505 0.00659312 0.00975477 0.00949456
- 0.00777552 0.00655645 0.00568776 0.00508782 0.00458121 0.00410187
- 0.00365665 0.0015121 0.00160863 0.00263181 0.00638941 0.00772607
- 0.00225583 0.0010843 0.000882939 0.000801563 0.00075632
- 0.000554992 0.000435131 0.0003474 0.000217667 0.000491602
- 0.0012267 0.00250446 0.000212058 -0.0174972 -0.0527527 -0.0479071
- 0.194908 1.45838 3.40677 4.49242 4.86894 4.97215 5.01218
- 5.04342 5.06228 5.03069 4.87169 4.57056 4.11523 3.38264
- 2.19691 0.715839 0.172818 0.102162 0.0627162 0.0363388 0.020289
- 0.0119414 0.00826608 0.0066417 0.00549092 0.00492505 0.00439443
- 0.0037156 0.00306471 0.00247451 0.00195965 0.0014822 0.0010815
- 0.000904464 0.0010514 0.00152308 0.00120752 0.000228447
- -0.00102833 -0.00116644 -0.00042067 4.78758e-05 5.09599e-05
- -4.45756e-05 -3.22966e-06 3.81163e-05 7.94622e-05 0.000120808
- 0.000162154 0.000161895 0.000148481 0.000135068 0.000121654
- 0.000108241 9.81453e-05 9.2164e-05 8.61827e-05 8.02014e-05
- 7.42201e-05 6.82388e-05 6.22576e-05 5.62763e-05 5.0295e-05
- 4.43137e-05 3.83324e-05 3.54323e-05 3.321e-05 3.09877e-05
- 2.87654e-05 2.65431e-05 2.43209e-05 2.20986e-05 1.98763e-05
- 1.7654e-05 1.54317e-05 1.34612e-05 1.25441e-05 1.1627e-05
- 1.07099e-05 9.79276e-06 8.87564e-06 7.95851e-06 7.04139e-06
- 6.12427e-06
- EOD
-
- @v[24].set(<<-'EOD')
- 5 5.01099 5.00866 4.97845 4.92369 4.9273 4.97413 4.9929
- 4.99826 4.99958 4.99978 5.00005 4.99968 4.99959 5.00014
- 4.99979 4.99914 4.99982 5.00023 5.00295 5.00664 4.99854
- 4.99647 5.00438 5.01722 5.03681 5.04766 5.04799 5.04867
- 5.04873 5.04685 5.04413 5.0367 5.02505 5.01726 5.01183 5.00806
- 5.00549 5.00371 5.00246 5.00162 5.00105 5.00069 5.00045
- 5.00031 5.00024 5.00019 5.00012 5.00007 5.00004 5.00001
- 4.99998 4.99999 4.99999 5 5.00001 5.00001 5.00002 5.00002
- 5.00003 5.00003 5.00003 5.00002 5.00002 5.00001 5.00001
- 5.00001 5 5 5 5 5 4.99999 4.99999 4.99999 4.99999 4.99999
- 4.99999 4.99999 4.99999 4.99999 4.99999 4.99999 4.99999
- 5 5 5 5 5 5 5 5.00001 5.00001 5.00001 5.00001 5.00001 5.00001
- 5.00001 5.00002 5.00001 5.00001 5.00001 5.00001 5.00001
- 5.00001 5.00001 5.00001 5.00001 5.00001 5.00001 5.00001
- 5.00001 5.00001 5.00001 5 5 5 5 5 5 5 5.00418 4.99953 4.99152
- 4.99807 5.00497 5.00112 5.00055 5.00038 5.00018 5.00006
- 5.00006 5.00007 5.00006 5.00004 5.00004 4.99853 4.99945
- 4.99998 5.00304 5.00935 5.00742 4.99181 4.97421 4.93603
- 4.8853 4.8927 4.93984 4.97458 4.99039 4.99614 4.99801 4.99851
- 4.99869 4.99924 5.00108 5.00181 5.00119 5.00059 5.00031
- 5.00022 5.00018 5.00011 5.00001 5.00006 4.99981 4.99977
- 4.99982 5.00012 4.99993 5.00008 5.00043 5.00048 5.00024
- 5.00008 4.99984 4.99993 5.00011 4.99996 4.9998 4.99977 4.9998
- 4.99993 5.00008 5.00011 5.00002 4.99995 4.99989 4.99993
- 5 5.00007 5.00009 4.99994 4.99977 4.9997 4.99975 4.99996
- 4.99996 4.99988 4.9997 4.99952 4.9995 4.99956 4.99973 4.99988
- 5.00005 5.00025 5.00042 5.00036 5.00031 5.00025 5.0002 5.00014
- 5.00009 5.00003 5.00002 5.00001 5.00001 5 4.99999 4.99998
- 4.99998 4.99997 4.99998 4.99998 4.99998 4.99998 4.99998
- 4.99998 4.99998 4.99999 4.99999 4.99999 4.99999 4.99999
- 4.99999 4.99999 4.99999 4.99999 4.99999 4.99999 5.00284
- 5.00442 5.00381 4.98997 4.99092 5.00733 5.07791 4.98237
- 4.86434 4.76835 4.74067 4.79278 4.85094 4.90068 4.93603
- 4.95698 4.96984 4.97856 4.98869 4.99904 5.0005 4.99524 5.00181
- 5.01878 5.05177 5.07986 4.98917 4.56217 3.68 2.3539 1.18541
- 0.505772 0.221044 0.115287 0.0760938 0.0589194 0.0476784
- 0.0457213 0.0412911 0.033889 0.0259741 0.0191452 0.0139018
- 0.0100235 0.00711788 0.00497657 0.00349368 0.00250021 0.00176179
- 0.00121843 0.000838368 0.000582711 0.000423458 0.000294608
- 0.000201251 0.000133748 8.6227e-05 5.44252e-05 3.30514e-05
- 1.93926e-05 1.09814e-05 5.29857e-06 1.92247e-06 3.08708e-07
- -3.74311e-07 -6.11121e-07 -7.27807e-07 -4.87604e-07 -4.80493e-07
- -9.15925e-07 -2.03774e-06 -4.01128e-06 -2.46644e-06 2.10626e-06
- 8.22422e-06 1.04922e-05 9.83047e-06 7.27106e-06 3.29654e-06
- -2.06736e-06 -2.18019e-06 -2.29303e-06 -2.40586e-06 -2.51869e-06
- -2.63153e-06 -2.24615e-06 -1.70325e-06 -1.16036e-06 -6.17468e-07
- -7.45754e-08 2.45198e-07 2.88285e-07 3.31373e-07 3.7446e-07
- 4.17548e-07 4.60635e-07 5.03723e-07 5.4681e-07 5.89898e-07
- 6.32985e-07 6.76073e-07 6.19054e-07 5.4001e-07 4.60967e-07
- 3.81923e-07 3.02879e-07 2.23836e-07 1.44792e-07 6.57488e-08
- -1.32948e-08 -9.23383e-08 -1.6698e-07 -2.23206e-07 -2.79432e-07
- -3.35658e-07 -3.91884e-07 -4.48109e-07 -5.04335e-07 -5.60561e-07
- -6.16787e-07
- EOD
-
- @v[25].set(<<-'EOD')
- 1.34824 1.35838 1.36465 1.34675 1.29167 1.23161 1.2201 1.2185
- 1.2181 1.21798 1.21793 1.21788 1.21785 1.21782 1.21779 1.21776
- 1.21655 1.21656 1.21669 1.21871 1.22421 1.22247 1.21858
- 1.2228 1.23803 1.27737 1.10647 0.395248 0.0600669 0.027687
- 0.0192374 0.015425 0.0130881 0.00977445 0.00696598 0.00491122
- 0.00341952 0.00237078 0.00162339 0.00109178 0.000726647
- 0.000478886 0.00031568 0.000207902 0.000143494 0.000109768
- 8.62987e-05 5.69775e-05 3.36547e-05 2.30356e-05 1.86108e-05
- 1.41861e-05 1.08293e-05 7.68835e-06 4.79593e-06 4.51019e-06
- 4.22444e-06 3.9387e-06 3.65295e-06 3.36721e-06 3.04559e-06
- 2.69981e-06 2.35403e-06 2.00825e-06 1.66247e-06 1.34508e-06
- 1.26225e-06 1.17941e-06 1.09657e-06 1.01373e-06 9.30893e-07
- 8.48054e-07 7.65216e-07 6.82378e-07 5.9954e-07 5.16702e-07
- 4.37489e-07 3.82774e-07 3.2806e-07 2.73346e-07 2.18632e-07
- 1.63917e-07 1.09203e-07 5.4489e-08 -2.2523e-10 -5.49395e-08
- -1.09654e-07 -1.52862e-07 -1.3079e-07 -1.08718e-07 -8.6646e-08
- -6.45739e-08 -4.25019e-08 -2.04298e-08 1.64229e-09 2.37144e-08
- 4.57864e-08 6.78585e-08 8.71693e-08 9.30725e-08 9.89758e-08
- 1.04879e-07 1.10782e-07 1.16685e-07 1.22589e-07 1.28492e-07
- 1.34395e-07 1.40298e-07 1.46201e-07 1.52105e-07 1.58008e-07
- 1.63911e-07 1.69814e-07 1.75718e-07 1.81621e-07 1.87524e-07
- 1.93427e-07 1.9933e-07 2.05234e-07 2.11137e-07 2.19788e-07
- 0.000393944 -0.000218983 -0.00105784 0.00172403 -0.00027134
- -0.000204147 8.79968e-06 5.93762e-05 5.83554e-05 4.13815e-05
- 3.71369e-05 3.03372e-05 2.25336e-05 1.5986e-05 1.07284e-05
- -7.5239e-05 5.60593e-05 6.97571e-05 0.000667617 0.000960856
- 0.00131749 -0.00759564 -0.0217897 -0.0450321 -0.076646 -0.128569
- -0.186391 -0.202175 -0.206953 -0.2082 -0.208416 -0.208669
- -0.208934 -0.209111 -0.209234 -0.209329 -0.209389 -0.209416
- -0.2094 -0.209329 -0.20926 -0.209204 -0.209208 -0.209285
- -0.209454 -0.209641 -0.20977 -0.209811 -0.209833 -0.209887
- -0.209653 -0.209127 -0.208893 -0.208811 -0.208777 -0.208758
- -0.208747 -0.20874 -0.208726 -0.208697 -0.208657 -0.208611
- -0.208565 -0.208524 -0.208488 -0.208451 -0.208412 -0.208373
- -0.208333 -0.208294 -0.208256 -0.208219 -0.208183 -0.208145
- -0.208107 -0.208066 -0.208029 -0.207993 -0.207959 -0.207923
- -0.207883 -0.207838 -0.207789 -0.207747 -0.20771 -0.207675
- -0.207642 -0.207605 -0.207568 -0.207531 -0.207494 -0.207457
- -0.20742 -0.207383 -0.207346 -0.207308 -0.207271 -0.207233
- -0.207196 -0.207158 -0.207121 -0.207084 -0.207046 -0.207009
- -0.206972 -0.206935 -0.206898 -0.206861 -0.206823 -0.206786
- -0.206749 -0.206712 -0.206675 -0.206638 -0.2066 -0.206563
- -0.206526 -0.206489 -0.206452 -0.206415 -0.203384 -0.20015
- -0.196872 -0.205024 -0.210727 -0.206779 -0.0685263 0.586138
- 1.4665 2.22945 2.77554 3.076 3.24926 3.34515 3.40164 3.43006
- 3.43713 3.43075 3.42886 3.4384 3.46567 3.49025 3.51287 3.53821
- 3.57841 3.39846 2.80753 2.22947 1.7549 1.30429 0.707786
- 0.303206 0.131352 0.0671706 0.0429955 0.032461 0.0257161
- 0.0239521 0.0217397 0.0179705 0.0138745 0.0102813 0.00749643
- 0.0054328 0.00386817 0.0027004 0.00189442 0.00135552 0.000954715
- 0.000659981 0.000453435 0.000313993 0.000231347 0.000159665
- 0.000108122 7.10528e-05 4.50233e-05 2.77892e-05 1.62765e-05
- 8.9893e-06 4.5471e-06 1.54614e-06 -1.6542e-07 -8.68508e-07
- -1.04369e-06 -9.63086e-07 -8.44294e-07 -6.57339e-07 -7.35885e-07
- -9.80056e-07 -1.39772e-06 -2.10199e-06 -1.37474e-06 6.13269e-07
- 3.3028e-06 4.60941e-06 4.91053e-06 4.14186e-06 2.45258e-06
- -8.7388e-09 -3.59647e-07 -7.10554e-07 -1.06146e-06 -1.41237e-06
- -1.76328e-06 -1.63073e-06 -1.34534e-06 -1.05995e-06 -7.74561e-07
- -4.8917e-07 -2.95733e-07 -2.16326e-07 -1.3692e-07 -5.75135e-08
- 2.18929e-08 1.01299e-07 1.80706e-07 2.60112e-07 3.39519e-07
- 4.18925e-07 4.98332e-07 4.83984e-07 4.4901e-07 4.14035e-07
- 3.79061e-07 3.44087e-07 3.09112e-07 2.74138e-07 2.39163e-07
- 2.04189e-07 1.69215e-07 1.26002e-07 4.83213e-08 -2.9359e-08
- -1.07039e-07 -1.8472e-07 -2.624e-07 -3.4008e-07 -4.1776e-07
- -4.95441e-07
- EOD
-
- @v[26].set(<<-'EOD')
- 7.10441e-10 0.000309731 -0.000308186 -0.001694 -0.00360784
- 8.40909e-05 0.00203175 0.0012896 0.000596548 0.000277191
- 0.000161134 0.000120439 8.4915e-05 9.49929e-05 6.18812e-05
- 1.65433e-05 1.89682e-05 3.97578e-05 4.95446e-05 0.000225325
- 0.000214579 -0.00230134 -0.000451102 0.00997237 0.0341443
- 0.0449314 0.0424411 0.0341996 0.0315315 0.0308892 0.0291614
- 0.024365 0.0190282 0.0188976 0.017238 0.0138526 0.0105645
- 0.00778548 0.00561753 0.0039871 0.00279554 0.00194075 0.0013468
- 0.000934775 0.000664723 0.000498911 0.000377384 0.000254183
- 0.000163421 0.000120773 9.65058e-05 7.22384e-05 5.60316e-05
- 4.14549e-05 2.79516e-05 2.57096e-05 2.34677e-05 2.12257e-05
- 1.89837e-05 1.67417e-05 1.46737e-05 1.27228e-05 1.07719e-05
- 8.82099e-06 6.87009e-06 5.0896e-06 4.71705e-06 4.34451e-06
- 3.97196e-06 3.59941e-06 3.22686e-06 2.85431e-06 2.48176e-06
- 2.10921e-06 1.73666e-06 1.36411e-06 1.02855e-06 9.42931e-07
- 8.57316e-07 7.71701e-07 6.86086e-07 6.00471e-07 5.14856e-07
- 4.29241e-07 3.43626e-07 2.58011e-07 1.72396e-07 9.85409e-08
- 9.14091e-08 8.42773e-08 7.71456e-08 7.00138e-08 6.2882e-08
- 5.57503e-08 4.86185e-08 4.14867e-08 3.4355e-08 2.72232e-08
- 2.05821e-08 1.63235e-08 1.2065e-08 7.80643e-09 3.54786e-09
- -7.10696e-10 -4.96926e-09 -9.22782e-09 -1.34864e-08 -1.77449e-08
- -2.20035e-08 -2.62621e-08 -3.05206e-08 -3.47792e-08 -3.90378e-08
- -4.32963e-08 -4.75549e-08 -5.18134e-08 -5.6072e-08 -6.03306e-08
- -6.45891e-08 -6.88477e-08 -8.76373e-06 0.000131607 -0.00021685
- -0.000433027 0.00047234 0.000211593 -0.000189601 3.2492e-05
- 0.000575955 7.72235e-05 -0.000285172 -0.000242061 -0.000135112
- -3.50117e-05 -2.75868e-05 5.48974e-05 1.80604e-07 5.48911e-05
- 3.97478e-05 0.000192909 0.000297932 0.00402253 -0.0122366
- -0.047853 -0.0963082 -0.108071 -0.0567275 -0.0239271 -0.0178628
- -0.0233027 -0.031853 -0.0400843 -0.0482725 -0.0576154 -0.0627218
- -0.0511236 -0.0279524 -0.0150986 -0.00931091 -0.00652876
- -0.00479286 -0.00344346 -0.00249578 -0.0019532 -0.00157977
- -0.00131848 -0.00111251 -0.000939229 -0.000797445 -0.000708384
- -0.000630452 -0.000539722 -0.000508862 -0.000480596 -0.000439484
- -0.000407217 -0.000363866 -0.000329506 -0.000318642 -0.000307362
- -0.000286511 -0.000266253 -0.000242943 -0.000218107 -0.000204661
- -0.00020241 -0.000194435 -0.000185062 -0.000173042 -0.000160549
- -0.000151407 -0.000145626 -0.000145976 -0.000147342 -0.000145288
- -0.000137979 -0.000124481 -0.000123218 -0.000127453 -0.000139006
- -0.000145486 -0.000129764 -9.82749e-05 -4.72596e-05 -3.08671e-05
- -3.28834e-05 -4.52254e-05 -6.25389e-05 -6.32516e-05 -6.39643e-05
- -6.4677e-05 -6.53897e-05 -6.61023e-05 -6.6815e-05 -6.75277e-05
- -6.61005e-05 -6.45173e-05 -6.29341e-05 -6.13509e-05 -5.97676e-05
- -5.81844e-05 -5.66012e-05 -5.54231e-05 -5.4455e-05 -5.3487e-05
- -5.25189e-05 -5.15508e-05 -5.05828e-05 -4.96147e-05 -4.86466e-05
- -4.76785e-05 -4.67105e-05 -4.57424e-05 -4.47743e-05 -4.38063e-05
- -4.28382e-05 -4.18821e-05 -4.10211e-05 -4.016e-05 -3.9299e-05
- -3.8438e-05 4.29885e-05 5.14113e-05 -0.000127986 -0.000611463
- -0.000149428 0.000882394 0.00297059 -0.00405825 -0.00591067
- -0.00546997 -0.00158744 0.00190677 0.00298403 0.00268595
- 0.00196161 0.00130289 0.000783347 0.000520683 0.000565306
- 0.00053419 -0.00224696 -0.000920818 0.0132755 0.0322504
- 0.0442808 0.0638615 0.0701007 0.0539356 0.0247771 0.056244
- 0.294266 0.831368 1.45424 2.02898 2.54559 2.9937 3.35333
- 3.72609 4.06363 4.32789 4.52413 4.66504 4.7652 4.83637 4.88631
- 4.92109 4.94464 4.96046 4.97218 4.98079 4.98679 4.99076
- 4.99361 4.99555 4.99686 4.99783 4.99853 4.99902 4.99936
- 4.99959 4.99973 4.99983 4.9999 4.99993 4.99996 4.99998 5
- 5.00001 5 4.99999 4.99997 4.99994 4.99993 4.99994 4.99996
- 4.99999 5.00004 5.00006 5.00005 5.00003 5.00002 5.00001
- 5 4.99999 4.99999 4.99999 4.99999 4.99999 4.99999 4.99999
- 5 5 5 5 5 5 5.00001 5.00001 5.00001 5.00001 5.00001 5.00001
- 5.00001 5.00001 5.00001 5.00001 5.00001 5.00001 5.00001
- 5 5 5 5 5 4.99999 4.99999 4.99999 4.99999 4.99999 4.99998
- EOD
-
- @v[27].set(<<-'EOD')
- 5 4.99984 4.99796 4.99478 4.9889 4.98738 4.98896 4.99087
- 4.99262 4.99419 4.99552 4.99659 4.99743 4.99807 4.99855
- 4.9989 4.99894 4.99908 4.99935 5.00001 5.0007 5.00132 5.00032
- 4.99976 5.00134 5.00339 5.00315 5.00157 5.00091 5.00058
- 5.00012 4.99944 4.99886 4.9994 4.99934 4.99899 4.99876 4.99868
- 4.99872 4.99883 4.99898 4.99914 4.9993 4.99944 4.99956 4.99967
- 4.99976 4.99982 4.99986 4.9999 4.99993 4.99997 4.99997 4.99998
- 4.99998 4.99998 4.99998 4.99998 4.99998 4.99998 4.99998
- 4.99999 4.99999 4.99999 4.99999 5 5 5 5 5 5 5 5 5 5 5 5
- 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5
- 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5.00009 5.00028 5.00015 4.99983
- 5.00036 4.99996 4.99834 4.99783 5.00383 5.00734 5.00387
- 5.00058 4.99893 4.99836 4.99832 4.99854 4.99873 4.99905
- 4.99927 4.99952 4.99969 4.99834 4.99536 4.99163 4.99073
- 5.0053 5.03631 5.03103 4.9008 4.62503 4.21887 3.70902 3.09967
- 2.35791 1.41912 0.519675 0.210458 0.131362 0.0980819 0.0708209
- 0.0471701 0.0323272 0.0253535 0.0199144 0.0152615 0.0117228
- 0.00917696 0.00738117 0.00609292 0.00512664 0.00436184 0.0037961
- 0.00331639 0.00289006 0.0025477 0.00226529 0.00202925 0.00182793
- 0.00165474 0.00150531 0.00137529 0.00125983 0.00115603 0.00106455
- 0.000982977 0.000911255 0.000846819 0.000790092 0.000738698
- 0.000692816 0.00065107 0.000613595 0.000579642 0.000548935
- 0.00052106 0.000495598 0.000472174 0.000450849 0.000431118
- 0.000412667 0.000395868 0.000381319 0.000368487 0.000357327
- 0.000344212 0.000330334 0.00031622 0.000303298 0.000295809
- 0.00028832 0.000280831 0.000273342 0.000265853 0.000258364
- 0.000250875 0.000245118 0.000239488 0.000233857 0.000228227
- 0.000222596 0.000216966 0.000211336 0.000207047 0.000203455
- 0.000199863 0.00019627 0.000192678 0.000189085 0.000185493
- 0.0001819 0.000178308 0.000174716 0.000171123 0.000167531
- 0.000163938 0.000160346 0.000156835 0.000153973 0.00015111
- 0.000148248 0.000145385 0.000296579 -3.96718e-05 -0.000449085
- 0.000323433 0.000750086 0.000268264 0.000149028 -0.000100249
- 7.00956e-05 0.00012605 0.00022592 0.000193036 0.000120453
- 8.07865e-05 7.65771e-05 -3.27828e-05 0.000116759 0.000169498
- 0.000409804 0.000414965 0.00092323 -0.00590633 -0.0175477
- -0.032433 -0.0559842 -0.0820373 0.0688484 0.626629 1.32929
- 2.01657 2.60925 3.12329 3.38952 3.14128 2.38463 1.23802
- 0.316019 0.107832 0.0694707 0.051837 0.035247 0.0209999
- 0.0116618 0.00967674 0.00789182 0.00574566 0.00386872 0.00258612
- 0.00167126 0.00104169 0.000641093 0.000401246 0.000277928
- 0.000171775 0.000102266 5.89376e-05 3.29258e-05 1.80463e-05
- 1.0057e-05 6.4571e-06 5.10093e-06 4.06791e-06 3.62716e-06
- 3.63321e-06 3.99625e-06 4.64368e-06 5.20886e-06 4.77728e-06
- 3.23919e-06 1.14113e-06 -1.29416e-06 -4.15607e-06 -1.88532e-06
- 5.24411e-06 1.38678e-05 1.28823e-05 3.6758e-06 -2.52285e-06
- -3.97133e-06 -4.03071e-06 -3.37154e-06 -2.71238e-06 -2.05321e-06
- -1.39404e-06 -7.34872e-07 -3.73325e-07 -1.05873e-07 1.61578e-07
- 4.2903e-07 6.96482e-07 8.18468e-07 7.60065e-07 7.01662e-07
- 6.43258e-07 5.84855e-07 5.26452e-07 4.68049e-07 4.09646e-07
- 3.51243e-07 2.9284e-07 2.34437e-07 1.71213e-07 1.06928e-07
- 4.2644e-08 -2.16403e-08 -8.59247e-08 -1.50209e-07 -2.14493e-07
- -2.78778e-07 -3.43062e-07 -4.07346e-07 -4.55065e-07 -4.3348e-07
- -4.11896e-07 -3.90311e-07 -3.68726e-07 -3.47141e-07 -3.25556e-07
- -3.03971e-07 -2.82386e-07
- EOD
-
- @v[28].set(<<-'EOD')
- 0.368163 0.361756 0.327463 0.269513 0.149476 0.0805716 0.0501146
- 0.03403 0.0230886 0.0160474 0.0116071 0.00870013 0.00679614
- 0.00542384 0.00432512 0.00340653 -0.00129719 -0.00399429
- -0.00318719 0.00443085 0.0150156 0.0334147 0.0132288 -0.0189751
- -0.0508377 -0.0252174 -0.0142489 -0.00675908 -0.0038653
- -0.00243423 -0.00168891 -0.00120901 -0.000900426 -0.000685575
- -0.000557595 -0.000457268 -0.000377427 -0.000315269 -0.000266613
- -0.000228397 -0.000198283 -0.000174248 -0.000154886 -0.00013892
- -0.000125864 -0.000115189 -0.000105841 -9.66611e-05 -8.84262e-05
- -8.23872e-05 -7.74668e-05 -7.25463e-05 -6.79992e-05 -6.35276e-05
- -5.92413e-05 -5.68994e-05 -5.45574e-05 -5.22154e-05 -4.98735e-05
- -4.75315e-05 -4.54981e-05 -4.36726e-05 -4.18471e-05 -4.00216e-05
- -3.81961e-05 -3.64559e-05 -3.54209e-05 -3.43858e-05 -3.33508e-05
- -3.23157e-05 -3.12807e-05 -3.02456e-05 -2.92105e-05 -2.81755e-05
- -2.71404e-05 -2.61054e-05 -2.51232e-05 -2.44984e-05 -2.38736e-05
- -2.32487e-05 -2.26239e-05 -2.19991e-05 -2.13742e-05 -2.07494e-05
- -2.01246e-05 -1.94998e-05 -1.88749e-05 -1.82865e-05 -1.79044e-05
- -1.75224e-05 -1.71403e-05 -1.67582e-05 -1.63762e-05 -1.59941e-05
- -1.56121e-05 -1.523e-05 -1.4848e-05 -1.44659e-05 -1.41138e-05
- -1.39075e-05 -1.37011e-05 -1.34947e-05 -1.32883e-05 -1.30819e-05
- -1.28755e-05 -1.26691e-05 -1.24627e-05 -1.22563e-05 -1.205e-05
- -1.18436e-05 -1.16372e-05 -1.14308e-05 -1.12244e-05 -1.1018e-05
- -1.08116e-05 -1.06052e-05 -1.03988e-05 -1.01924e-05 -9.98605e-06
- -9.77966e-06 -2.85319e-05 0.00281092 0.00180106 -0.000981083
- 0.00551926 -0.00119763 -0.0295069 -0.0367677 0.064749 0.119022
- 0.0882007 0.0552062 0.03418 0.0223243 0.015545 0.011949
- 0.00757134 0.00667655 0.00583243 0.00644443 0.00650959 -0.0302575
- -0.0437806 -0.0355466 0.0381776 0.282109 0.674178 1.07582
- 1.45189 1.789 2.08649 2.34663 2.57245 2.81211 3.04778 3.2523
- 3.45877 3.65593 3.83396 3.9923 4.13368 4.25864 4.36719 4.46064
- 4.54086 4.60962 4.66835 4.71838 4.76094 4.79716 4.82796
- 4.85413 4.87634 4.89518 4.91116 4.92476 4.93631 4.94608
- 4.95434 4.9613 4.96715 4.97211 4.97638 4.98001 4.98312 4.98571
- 4.98795 4.98979 4.99138 4.99269 4.99381 4.99474 4.99551
- 4.99615 4.99668 4.99713 4.99752 4.99783 4.99811 4.99836
- 4.99858 4.99873 4.99884 4.99892 4.999 4.99907 4.99912 4.99916
- 4.99921 4.99926 4.99932 4.99937 4.99942 4.99948 4.99953
- 4.99956 4.99958 4.99961 4.99963 4.99966 4.99968 4.99971
- 4.99972 4.99973 4.99974 4.99975 4.99976 4.99977 4.99978
- 4.99979 4.9998 4.9998 4.99981 4.99982 4.99983 4.99984 4.99985
- 4.99986 4.99986 4.99987 4.99987 5.00498 5.00354 4.99359
- 4.98981 5.00498 5.00099 5.00041 5.00022 5.00015 5.00012
- 5.0001 5.00008 5.00005 5.00003 5 4.99431 4.99459 4.99591
- 5.00087 5.01029 5.03935 4.92784 4.51643 3.78356 2.68745
- 1.43417 0.583128 0.205094 0.0777337 0.0391566 0.02723 0.023883
- 0.018808 0.010165 0.00254623 -0.00377463 -0.0038097 0.00144145
- 0.00267231 0.00193045 0.00144538 0.00121758 0.00112893 0.00109424
- 0.0010226 0.000948072 0.000882573 0.000826996 0.000776391
- 0.000729719 0.000686499 0.000647333 0.000610108 0.000575631
- 0.000545069 0.000515485 0.000488514 0.000465316 0.000443215
- 0.000422454 0.00040292 0.00038488 0.000368472 0.000353628
- 0.000339643 0.000326197 0.000313483 0.000302884 0.000294038
- 0.000284003 0.000270941 0.000254925 0.000246511 0.000244089
- 0.000245538 0.000242099 0.000235728 0.000227482 0.000218001
- 0.000207257 0.000202127 0.000196997 0.000191868 0.000186738
- 0.000181608 0.00017758 0.000173899 0.000170219 0.000166538
- 0.000162857 0.000159576 0.00015679 0.000154005 0.000151219
- 0.000148433 0.000145647 0.000142861 0.000140076 0.00013729
- 0.000134504 0.000131718 0.000129603 0.000127635 0.000125668
- 0.0001237 0.000121732 0.000119765 0.000117797 0.000115829
- 0.000113862 0.000111894 0.000109993 0.000108372 0.000106751
- 0.00010513 0.000103509 0.000101887 0.000100266 9.86449e-05
- 9.70237e-05
- EOD
-
- @v[29].set(<<-'EOD')
- 5 4.99899 4.99654 4.99327 4.9863 4.98954 4.99212 4.99378
- 4.9951 4.99624 4.99715 4.99786 4.99839 4.99879 4.99909 4.99931
- 4.99922 4.99933 4.99971 5.00064 5.00084 5.00123 4.99865
- 4.99853 4.99983 5.00457 5.00242 5.00105 5.00062 5.00042
- 4.99971 4.9994 4.9992 4.9996 4.99955 4.99932 4.99918 4.99915
- 4.99919 4.99927 4.99937 4.99948 4.99957 4.99966 4.99974
- 4.9998 4.99985 4.99989 4.99992 4.99993 4.99994 4.99994 4.99996
- 4.99998 5 5 5.00001 5.00001 5.00001 5.00002 5.00002 5.00001
- 5.00001 5.00001 5 5 5 5 4.99999 4.99999 4.99999 4.99999
- 4.99999 4.99999 4.99999 4.99998 4.99998 4.99999 4.99999
- 4.99999 4.99999 4.99999 4.99999 4.99999 4.99999 5 5 5 5
- 5 5 5.00001 5.00001 5.00001 5.00001 5.00001 5.00001 5.00001
- 5.00002 5.00002 5.00001 5.00001 5.00001 5.00001 5.00001
- 5.00001 5.00001 5.00001 5.00001 5.00001 5.00001 5.00001
- 5.00001 5.00001 5 5 5 5 5 5 4.9997 4.99998 4.99954 4.99963
- 5.00059 4.99945 4.99732 4.99957 5.00919 5.00558 5.00033
- 4.99851 4.9983 4.99854 4.99871 4.99928 4.99914 4.99939 4.99952
- 4.9998 4.99976 4.99744 4.99598 4.99478 4.99806 5.01911 5.04602
- 5.05469 5.01317 4.89484 4.69655 4.42036 4.06069 3.60793
- 3.12531 2.72975 2.45187 2.25081 2.09841 1.98509 1.90211
- 1.84084 1.79411 1.7574 1.72763 1.70283 1.68188 1.66389 1.64823
- 1.63438 1.62201 1.61088 1.60081 1.59163 1.58323 1.57549
- 1.56835 1.56173 1.55558 1.54985 1.54451 1.53951 1.53479
- 1.53035 1.52615 1.5222 1.51845 1.5149 1.51153 1.50834 1.50529
- 1.5024 1.49964 1.497 1.49449 1.49208 1.48977 1.48755 1.48542
- 1.48336 1.48138 1.47948 1.47765 1.4759 1.47419 1.47255 1.47096
- 1.46949 1.46823 1.46696 1.4657 1.46444 1.46317 1.46191 1.46065
- 1.45956 1.4585 1.45743 1.45636 1.45529 1.45422 1.45315 1.45226
- 1.45145 1.45064 1.44983 1.44902 1.44821 1.4474 1.44659 1.44579
- 1.44498 1.44417 1.44336 1.44255 1.44174 1.44094 1.44019
- 1.43944 1.43868 1.43793 1.43765 1.43679 1.43515 1.43405
- 1.43478 1.43387 1.43345 1.43184 1.43086 1.43021 1.43003
- 1.42988 1.42944 1.42883 1.42818 1.42702 1.42642 1.42595
- 1.42586 1.42616 1.42783 1.41733 1.38106 1.30738 1.3877 2.09819
- 3.05285 3.58059 3.77601 3.87609 4.02557 4.24887 4.4608 4.60411
- 4.72109 4.8255 4.90465 4.97379 5.01253 5.01532 5.01239 5.0092
- 5.00665 5.00474 5.00333 5.00232 5.00163 5.00117 5.00082
- 5.00057 5.00039 5.00027 5.00019 5.00013 5.00009 5.00006
- 5.00004 5.00003 5.00002 5.00001 5.00001 5 5 5 4.99998 4.99995
- 4.99992 4.99996 5.00005 5.00012 5.00008 4.99996 4.9999 4.99985
- 4.99986 4.99997 5.00021 5.0003 5.00024 5.00009 5.00007 5.00005
- 5.00003 5.00001 4.99998 4.99998 4.99998 4.99999 4.99999
- 5 5 5 5 5 5.00001 5.00001 5.00001 5.00001 5.00001 5.00001
- 5.00002 5.00002 5.00001 5.00001 5.00001 5.00001 5.00001
- 5.00001 5 5 5 5 5 4.99999 4.99999 4.99999 4.99999 4.99998
- 4.99998 4.99998
- EOD
-
- @v[30].set(<<-'EOD')
- 7.10441e-10 5.70385e-05 0.000226143 0.000131916 -0.000887764
- -8.01837e-05 -3.49653e-05 9.40039e-05 0.000118663 0.000108025
- 8.6059e-05 6.33268e-05 4.99295e-05 3.16843e-05 3.60692e-05
- 2.07572e-05 -8.6375e-05 3.44583e-05 8.07397e-05 0.000196296
- 0.000115615 -7.12768e-05 -0.000129812 -4.18679e-05 7.94364e-05
- 0.000182034 -5.41226e-05 -0.000451819 -0.000713937 -0.00129863
- -0.00262186 -0.00213417 -0.00133767 0.000775698 0.000969902
- 0.000549281 0.000280946 0.000140321 8.6919e-05 7.22446e-05
- 6.5631e-05 6.45263e-05 6.63087e-05 7.17391e-05 7.59042e-05
- 7.59172e-05 7.03353e-05 6.33558e-05 5.31136e-05 4.64278e-05
- 4.40594e-05 4.16909e-05 4.05674e-05 3.96957e-05 3.87875e-05
- 3.74977e-05 3.62079e-05 3.49181e-05 3.36283e-05 3.23385e-05
- 3.12427e-05 3.02775e-05 2.93124e-05 2.83472e-05 2.7382e-05
- 2.64613e-05 2.59077e-05 2.5354e-05 2.48004e-05 2.42468e-05
- 2.36931e-05 2.31395e-05 2.25859e-05 2.20322e-05 2.14786e-05
- 2.0925e-05 2.03916e-05 1.9995e-05 1.95984e-05 1.92019e-05
- 1.88053e-05 1.84087e-05 1.80122e-05 1.76156e-05 1.7219e-05
- 1.68225e-05 1.64259e-05 1.6051e-05 1.57991e-05 1.55471e-05
- 1.52952e-05 1.50433e-05 1.47913e-05 1.45394e-05 1.42875e-05
- 1.40356e-05 1.37836e-05 1.35317e-05 1.32978e-05 1.31513e-05
- 1.30048e-05 1.28583e-05 1.27118e-05 1.25653e-05 1.24188e-05
- 1.22724e-05 1.21259e-05 1.19794e-05 1.18329e-05 1.16864e-05
- 1.15399e-05 1.13934e-05 1.12469e-05 1.11005e-05 1.0954e-05
- 1.08075e-05 1.0661e-05 1.05145e-05 1.0368e-05 1.02215e-05
- 1.76447e-05 7.21516e-05 -3.59786e-05 -0.000159618 0.000156236
- 0.000135106 -0.000336402 -0.000302283 0.000699323 0.000473866
- -0.000156146 -0.000225625 -0.000123592 -3.78116e-05 8.47472e-06
- 2.43387e-06 -7.44762e-05 7.80111e-05 9.43608e-05 0.000170159
- 8.83919e-05 -0.00018802 -0.000373512 -0.000390597 0.000156875
- 0.0032343 0.00776304 -0.000566905 -0.00760695 -0.0159226
- -0.0245989 -0.0331402 -0.0100902 0.067837 0.266702 0.910818
- 1.82282 2.69714 3.43247 3.98325 4.32893 4.51529 4.67087
- 4.79288 4.87574 4.92797 4.95902 4.97655 4.98622 4.99195
- 4.99526 4.99735 4.9991 4.99974 4.99982 4.99974 4.99961 4.9995
- 4.99943 4.9994 4.9994 4.99942 4.99944 4.99948 4.99952 4.99956
- 4.99961 4.99965 4.9997 4.99974 4.99977 4.99981 4.99983 4.99986
- 4.99988 4.9999 4.99991 4.99992 4.99993 4.99994 4.99995 4.99995
- 4.99996 4.99997 4.99997 4.99998 4.99998 4.99999 4.99999
- 4.99999 5 5 5 5.00001 5.00001 5.00001 5.00001 5.00001 5
- 5 5 5 5 5 5 4.99999 4.99999 4.99999 4.99999 4.99999 4.99999
- 4.99999 4.99999 4.99999 4.99999 4.99999 4.99999 4.99999
- 4.99999 4.99999 5 5.00019 4.99888 4.99663 4.99457 4.99902
- 5.00229 5.00323 5.00302 5.0023 5.0015 5.00085 5.00041 5.00013
- 4.99993 4.99979 4.99948 4.99954 4.99983 5.00055 5.00109
- 5.00009 4.9987 4.998 4.99755 4.99676 4.99618 5.01091 5.05272
- 5.04156 4.80112 4.27692 3.42343 2.23953 0.967179 0.429813
- 0.540757 1.32991 2.32147 3.14903 3.78143 4.22325 4.47978
- 4.59448 4.69875 4.79798 4.87419 4.92339 4.95249 4.97174
- 4.98408 4.99124 4.99478 4.99729 4.99868 4.9992 4.99941 4.99947
- 4.99946 4.99943 4.9994 4.99939 4.9994 4.99942 4.99946 4.99951
- 4.99956 4.99961 4.99967 4.99973 4.99977 4.9998 4.99981 4.99983
- 4.99984 4.99987 4.99992 5.00001 5.00005 5.00001 4.99994
- 4.99995 4.99995 4.99996 4.99996 4.99996 4.99997 4.99997
- 4.99997 4.99998 4.99998 4.99998 4.99998 4.99999 4.99999
- 4.99999 4.99999 5 5 5 5.00001 5.00001 5.00001 5.00001 5.00001
- 5.00001 5 5 5 5 5 5 5 5 4.99999 4.99999 4.99999 4.99999
- 4.99998 4.99998 4.99998
- EOD
-
- @v[31].set(<<-'EOD')
- 1.8179e-09 -5.28841e-06 -1.44913e-05 -3.62932e-05 -9.75719e-05
- 0.000141781 3.73396e-05 -1.65603e-05 -1.5271e-05 -6.73884e-06
- 4.40157e-06 -4.85345e-06 -1.02964e-05 2.03126e-05 -1.89457e-05
- -8.75564e-06 7.67422e-06 4.71103e-06 1.29798e-05 6.13469e-06
- -1.14363e-05 -0.0394563 -0.0477298 -0.0622012 -0.0519225
- 0.262499 0.943611 1.67052 2.31017 2.84028 3.28467 3.61582
- 3.85887 4.13011 4.36511 4.54063 4.67013 4.76408 4.83263
- 4.8825 4.91837 4.94373 4.96117 4.97318 4.98093 4.98562 4.98906
- 4.99267 4.99539 4.99666 4.99731 4.99797 4.99844 4.99887
- 4.99927 4.99933 4.99938 4.99944 4.99949 4.99955 4.9996 4.99965
- 4.9997 4.99975 4.9998 4.99985 4.99986 4.99987 4.99989 4.9999
- 4.99991 4.99992 4.99993 4.99995 4.99996 4.99997 4.99998
- 4.99998 4.99999 4.99999 4.99999 4.99999 5 5 5 5 5.00001
- 5.00001 5.00001 5 5 5 5 5 5 4.99999 4.99999 4.99999 4.99999
- 4.99999 4.99999 4.99999 4.99999 4.99999 4.99999 4.99999
- 4.99999 4.99999 4.99999 4.99999 4.99999 4.99999 4.99999
- 4.99999 4.99999 4.99999 4.99999 4.99999 4.99999 4.99999
- 4.99999 4.99997 5.00002 5.00004 5.0001 5.0001 4.99987 5.00009
- 5.00021 5.00002 5.00004 4.99988 5.00013 4.99993 5.00026
- 4.99973 5 5.00006 5.00009 5.00004 5.00004 5.04854 4.82711
- 4.04208 2.64155 0.838902 0.19014 0.0982549 0.0723197 0.0576863
- 0.0427644 0.0301979 0.020146 0.0135728 0.00980358 0.00774482
- 0.00586604 0.0036687 0.00211511 0.00121906 0.000647581 0.000828436
- 0.00190938 0.00224254 0.00199956 0.00165488 0.00135612 0.00113715
- 0.000984181 0.000877175 0.000789973 0.000741139 0.000689338
- 0.000625676 0.000586082 0.000550152 0.000529573 0.000505606
- 0.000482117 0.000460574 0.000441649 0.000424674 0.000408398
- 0.000391914 0.000376272 0.000361487 0.000348181 0.000336045
- 0.000324466 0.000313545 0.000303046 0.000293056 0.00028356
- 0.000274586 0.000266155 0.000258279 0.000250938 0.000243789
- 0.000236912 0.000230244 0.000224186 0.000219291 0.000215346
- 0.000212468 0.000207291 0.000200862 0.00019368 0.000186767
- 0.000183515 0.000180263 0.00017701 0.000173758 0.000170506
- 0.000167253 0.000164001 0.000161164 0.000158357 0.00015555
- 0.000152743 0.000149936 0.000147129 0.000144322 0.000142066
- 0.000140096 0.000138127 0.000136157 0.000134187 0.000132218
- 0.000130248 0.000128278 0.000126308 0.000124339 0.000122369
- 0.000120399 0.000118429 0.00011646 0.000114527 0.000112892
- 0.000111258 0.000109623 0.000107988 0.000103598 6.86052e-05
- 3.337e-05 7.00783e-05 0.000218764 0.000221318 0.000118593
- -0.000113962 5.78552e-05 9.42068e-05 0.000237037 0.000171302
- 0.0001033 6.16066e-05 5.52908e-05 6.30233e-05 7.01897e-05
- 8.48573e-05 0.000106859 8.37213e-05 -0.0391541 -0.047722
- -0.0618454 -0.0169804 0.345725 1.03426 1.74825 2.37152 2.88737
- 3.32173 3.66761 3.9707 4.17762 3.98832 3.30483 2.09737 0.710892
- 0.148159 0.0707463 0.0555808 0.045618 0.0319116 0.0199589
- 0.0133357 0.00898528 0.00586075 0.00375478 0.00245443 0.00156038
- 0.000962344 0.000590953 0.000375107 0.000250243 0.00015882
- 0.000100203 6.18122e-05 3.7372e-05 2.23009e-05 1.32569e-05
- 8.29437e-06 5.72457e-06 3.96832e-06 2.98935e-06 2.59699e-06
- 2.75024e-06 3.38689e-06 4.0453e-06 3.50095e-06 1.64988e-06
- -3.84371e-07 -2.03828e-06 -3.46401e-06 -1.24301e-06 4.63458e-06
- 1.14104e-05 1.02619e-05 2.15487e-06 -2.98487e-06 -3.67221e-06
- -2.94279e-06 -2.58649e-06 -2.23019e-06 -1.87389e-06 -1.5176e-06
- -1.1613e-06 -7.92127e-07 -4.18889e-07 -4.56502e-08 3.27588e-07
- 7.00827e-07 8.79539e-07 8.17025e-07 7.5451e-07 6.91996e-07
- 6.29481e-07 5.66966e-07 5.04452e-07 4.41937e-07 3.79422e-07
- 3.16908e-07 2.54393e-07 1.90078e-07 1.25366e-07 6.0654e-08
- -4.05776e-09 -6.87696e-08 -1.33481e-07 -1.98193e-07 -2.62905e-07
- -3.27617e-07 -3.92329e-07 -4.40392e-07 -4.18802e-07 -3.97213e-07
- -3.75624e-07 -3.54035e-07 -3.32446e-07 -3.10856e-07 -2.89267e-07
- -2.67678e-07
- EOD
-
- @v[32].set(<<-'EOD')
- 1.10294 1.10297 1.10291 1.10277 1.10259 1.10294 1.10313
- 1.10306 1.10299 1.10296 1.10295 1.10295 1.10294 1.10294
- 1.10294 1.10294 1.10294 1.10294 1.10294 1.10296 1.10296
- 1.00547 0.998599 1.5201 2.49297 3.31258 3.73162 3.84757
- 3.92505 4.02965 4.16599 4.30294 4.41541 4.52886 4.64414
- 4.73865 4.81065 4.86391 4.90315 4.93188 4.95258 4.96726
- 4.97738 4.98436 4.98888 4.99162 4.99363 4.99573 4.99731
- 4.99804 4.99843 4.99881 4.99909 4.99934 4.99957 4.9996 4.99964
- 4.99967 4.9997 4.99973 4.99977 4.9998 4.99983 4.99986 4.99988
- 4.99991 4.99992 4.99992 4.99993 4.99994 4.99994 4.99995
- 4.99996 4.99996 4.99997 4.99997 4.99998 4.99998 4.99999
- 4.99999 4.99999 4.99999 5 5 5 5.00001 5.00001 5.00001 5.00001
- 5.00001 5.00001 5.00001 5.00001 5.00001 5.00001 5.00001
- 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 4.99999 4.99999 4.99999
- 4.99999 4.99999 4.99999 4.99999 5.00028 4.99988 4.99968
- 5.00019 4.99987 5.00021 4.99973 4.99977 4.99996 4.99997
- 5.0002 4.99957 5.00026 4.99947 5.00074 5.00003 4.99987 4.99979
- 5.00008 4.99997 5.08794 5.05993 4.76875 3.99197 3.10174
- 2.5197 2.21771 2.04 1.92235 1.83874 1.77592 1.72665 1.686
- 1.65276 1.6286 1.61299 1.60039 1.58934 1.57954 1.57083 1.56306
- 1.55604 1.54963 1.54375 1.53832 1.53331 1.52865 1.52432
- 1.52026 1.51645 1.51287 1.50949 1.50629 1.50327 1.50039
- 1.49766 1.49505 1.49257 1.49019 1.48792 1.48574 1.48365
- 1.48164 1.47971 1.47784 1.47604 1.47431 1.47264 1.47102
- 1.46945 1.46794 1.46647 1.46505 1.46367 1.46233 1.46103
- 1.45976 1.45853 1.45733 1.45616 1.45502 1.45392 1.45284
- 1.45179 1.45076 1.44975 1.4488 1.44795 1.44711 1.44626 1.44541
- 1.44457 1.44372 1.44287 1.44212 1.44138 1.44063 1.43989
- 1.43914 1.4384 1.43766 1.43701 1.43641 1.43581 1.43522 1.43462
- 1.43402 1.43342 1.43282 1.43223 1.43163 1.43103 1.43043
- 1.42984 1.42924 1.42865 1.42808 1.42752 1.42695 1.42639
- 1.42584 1.42529 1.42472 1.42412 1.42365 1.42326 1.42304
- 1.42162 1.42082 1.42032 1.42029 1.42026 1.41995 1.41947
- 1.41894 1.41841 1.4179 1.41742 1.41699 1.41656 1.32097 1.30963
- 1.78765 2.64656 3.35764 3.747 3.86589 3.94217 4.04185 4.18453
- 4.3561 4.53439 4.68621 4.74905 4.77848 4.84629 4.91261 4.97541
- 5.01284 5.01548 5.01248 5.00924 5.00666 5.00475 5.00334
- 5.00234 5.00164 5.00118 5.00083 5.00058 5.0004 5.00028 5.00019
- 5.00013 5.00009 5.00007 5.00004 5.00003 5.00002 5.00001
- 5.00001 5.00001 5 5 4.99999 4.99995 4.99992 4.99996 5.00006
- 5.00012 5.00009 4.99997 4.9999 4.99985 4.99986 4.99997 5.00021
- 5.00031 5.00024 5.0001 5.00007 5.00005 5.00003 5.00001 4.99998
- 4.99998 4.99999 4.99999 4.99999 5 5 5 5 5 5.00001 5.00001
- 5.00001 5.00001 5.00001 5.00001 5.00002 5.00002 5.00001
- 5.00001 5.00001 5.00001 5.00001 5.00001 5.00001 5 5 5 5
- 5 4.99999 4.99999 4.99999 4.99998 4.99998 4.99998
- EOD
-
- @v[33].set(<<-'EOD')
- 5 5.00012 5.00023 5.0003 4.99972 4.99988 4.99984 4.99991
- 4.99996 4.99999 5.00008 5.00009 4.99986 5.00003 5.00007
- 4.99995 4.9999 4.99997 5.00013 5.00014 5.00013 4.99701 4.99763
- 4.99742 4.99998 5.02836 5.07262 4.96856 4.57267 3.85637
- 2.79544 1.45942 0.408016 0.084885 0.0271375 0.0119294 0.00707546
- 0.0051087 0.00373035 0.00264737 0.00186477 0.00130379 0.000915857
- 0.000653121 0.000483893 0.000380852 0.000302362 0.000219498
- 0.000154435 0.000121928 0.000104026 8.61242e-05 7.48526e-05
- 6.49216e-05 5.56238e-05 5.29689e-05 5.03139e-05 4.7659e-05
- 4.5004e-05 4.23491e-05 4.00356e-05 3.79522e-05 3.58687e-05
- 3.37852e-05 3.17018e-05 2.97592e-05 2.89804e-05 2.82016e-05
- 2.74228e-05 2.66441e-05 2.58653e-05 2.50865e-05 2.43077e-05
- 2.35289e-05 2.27501e-05 2.19714e-05 2.12346e-05 2.07821e-05
- 2.03295e-05 1.98769e-05 1.94244e-05 1.89718e-05 1.85192e-05
- 1.80667e-05 1.76141e-05 1.71615e-05 1.6709e-05 1.62828e-05
- 1.60061e-05 1.57294e-05 1.54527e-05 1.5176e-05 1.48993e-05
- 1.46226e-05 1.43459e-05 1.40692e-05 1.37925e-05 1.35158e-05
- 1.3262e-05 1.31191e-05 1.29761e-05 1.28332e-05 1.26903e-05
- 1.25474e-05 1.24045e-05 1.22615e-05 1.21186e-05 1.19757e-05
- 1.18328e-05 1.16898e-05 1.15469e-05 1.1404e-05 1.12611e-05
- 1.11182e-05 1.09752e-05 1.08323e-05 1.06894e-05 1.05465e-05
- 1.04036e-05 1.02606e-05 1.00185e-05 3.8343e-05 -3.06781e-05
- -0.000111758 0.000111673 0.000130815 -0.000210491 -0.000231304
- 0.000310226 0.000265303 3.0878e-05 -4.48405e-05 -1.2852e-05
- -7.84469e-06 3.29986e-05 -1.23286e-05 -6.07871e-05 5.35082e-05
- 7.69194e-05 0.000126221 6.57178e-05 0.00223349 -0.0148854
- -0.0476636 -0.0491447 0.220125 1.11174 2.03988 2.90209 3.61069
- 4.13554 4.50679 4.71501 4.83916 4.91027 4.95284 4.98086
- 4.99151 4.98651 4.97113 4.95075 4.93102 4.93683 4.95457
- 4.97071 4.98212 4.98948 4.99386 4.99636 4.99785 4.9987 4.99927
- 4.99989 5.00014 5.00007 4.99988 4.99982 4.99976 4.99973
- 4.99972 4.99972 4.99973 4.99974 4.99975 4.99977 4.99979
- 4.99981 4.99984 4.99986 4.99988 4.99989 4.99991 4.99992
- 4.99993 4.99994 4.99995 4.99996 4.99996 4.99997 4.99997
- 4.99998 4.99998 4.99998 4.99998 4.99999 4.99999 4.99999
- 4.99999 5 5 5 5.00001 5.00001 5.00001 5.00002 5.00001 5.00001
- 5.00001 5.00001 5.00001 5 5 5 5 5 5 5 5 4.99999 4.99999
- 4.99999 4.99999 4.99999 4.99999 4.99999 4.99999 4.99999
- 4.99999 4.99999 4.99999 5 5.00012 4.99946 4.99839 4.99733
- 4.99948 5.00114 5.00158 5.00147 5.00113 5.00073 5.00043
- 5.0002 5.00006 4.99995 4.99986 4.99973 4.99976 4.9999 5.00029
- 5.00055 4.99704 4.99734 4.9972 5.00278 5.03354 5.07184 4.94057
- 4.51936 3.75638 2.60982 1.23803 0.315016 0.0796102 0.0252894
- 0.0165723 0.0827785 0.491298 1.40686 2.33436 3.1251 3.7691
- 4.22201 4.49976 4.68115 4.80513 4.88509 4.93208 4.95861
- 4.97579 4.98655 4.99268 4.99571 4.99771 4.99881 4.99929
- 4.99954 4.99965 4.9997 4.99971 4.99971 4.99971 4.99971 4.99972
- 4.99974 4.99976 4.99978 4.99981 4.99984 4.99987 4.99989
- 4.99991 4.99991 4.99992 4.99992 4.99993 4.99997 5.00003
- 5.00006 5.00004 5.00001 5 4.99999 4.99998 4.99998 4.99997
- 4.99997 4.99997 4.99998 4.99998 4.99998 4.99999 4.99999
- 4.99999 4.99999 5 5 5 5 5.00001 5.00001 5.00001 5.00001
- 5.00001 5.00001 5.00001 5.00001 5.00001 5 5 5 5 5 5 5 4.99999
- 4.99999 4.99999 4.99999 4.99998 4.99998
- EOD
-
- @v[34].set(<<-'EOD')
- 5 5.00207 5.00813 5.01486 5.00156 5.0018 4.99861 4.99844
- 4.99888 4.9993 4.99956 4.99971 4.99979 4.99983 4.99987 4.99989
- 4.99671 4.9974 4.99864 5.00131 5.00377 5.0021 5.00039 4.99993
- 5.00004 5.0009 5.00109 4.99636 4.98617 4.96778 4.92047 4.89528
- 4.91112 4.9559 4.98286 4.99369 4.99812 4.99951 4.99994 5.00014
- 5.00008 4.99994 4.99984 4.99989 4.99998 5.00004 5.00004
- 5.00006 5.00005 5.00001 4.99997 4.99992 4.99993 4.99994
- 4.99996 4.99996 4.99996 4.99996 4.99996 4.99996 4.99996
- 4.99996 4.99996 4.99996 4.99996 4.99996 4.99996 4.99996
- 4.99997 4.99997 4.99997 4.99997 4.99997 4.99997 4.99997
- 4.99997 4.99997 4.99997 4.99997 4.99997 4.99997 4.99997
- 4.99997 4.99997 4.99997 4.99997 4.99997 4.99997 4.99997
- 4.99998 4.99998 4.99998 4.99998 4.99998 4.99998 4.99998
- 4.99998 4.99998 4.99998 4.99998 4.99998 4.99998 4.99998
- 4.99998 4.99998 4.99998 4.99998 4.99998 4.99998 4.99998
- 4.99998 4.99998 4.99998 4.99998 4.99998 4.99998 4.99998
- 4.99998 4.99998 4.99998 4.99998 5.00131 5.00072 4.9977 4.99811
- 5.00325 4.99647 4.98948 4.99459 5.00262 5.00276 5.00156
- 5.00072 5.0003 5.00013 4.99995 4.99668 4.99775 4.99917 5.00173
- 5.00386 5.00188 4.99888 4.99757 4.99951 5.01712 5.0557 5.07088
- 5.07704 5.07758 5.06958 5.04223 5.03331 5.0279 5.03408 5.07611
- 5.01911 4.68594 3.99152 2.92195 1.69878 0.809 0.344091 0.154663
- 0.0788717 0.0467212 0.0336168 0.0280514 0.0254947 0.024173
- 0.0223567 0.0220555 0.0271514 0.0295872 0.0296052 0.0283971
- 0.0264726 0.0241813 0.0218244 0.0195349 0.017368 0.0152495
- 0.013295 0.0115444 0.00996982 0.00857091 0.00733891 0.00627261
- 0.0053494 0.00456316 0.00388373 0.00331073 0.00282181 0.00240991
- 0.00206389 0.00177187 0.00152283 0.00131167 0.00112558 0.000954373
- 0.000805726 0.00069326 0.000600991 0.000525743 0.00047355
- 0.00044359 0.000434815 0.000436053 0.000402511 0.000368969
- 0.000335427 0.000301886 0.000268344 0.000234802 0.00020126
- 0.000184967 0.000169932 0.000154896 0.000139861 0.000124825
- 0.00010979 9.47546e-05 8.67896e-05 8.24901e-05 7.81906e-05
- 7.38911e-05 6.95915e-05 6.5292e-05 6.09925e-05 5.66929e-05
- 5.23934e-05 4.80939e-05 4.37943e-05 3.94948e-05 3.51953e-05
- 3.08957e-05 2.67968e-05 2.42936e-05 2.17904e-05 1.92872e-05
- 1.6784e-05 0.00125927 -0.00794344 -0.0305499 -0.0621697
- -0.0463796 -0.0224608 -0.00538381 0.00546086 0.0108675 0.012883
- 0.0131787 0.0127271 0.0119702 0.0110398 0.0100635 0.00649617
- 0.00489388 0.00545863 0.0098351 0.0167428 0.0126563 0.00697542
- 0.00427027 0.00330002 0.00390774 0.00408999 -0.00259143
- -0.0160578 -0.0451849 -0.0409651 0.1301 0.597429 1.3848
- 2.63426 3.81272 4.51373 4.8412 4.98731 4.88165 4.37165 3.40034
- 2.17681 1.12217 0.505129 0.219703 0.104992 0.0622333 0.0448317
- 0.0355782 0.0311867 0.0293529 0.0274615 0.0288739 0.0307845
- 0.0304909 0.029245 0.0273602 0.0251006 0.022697 0.0202765
- 0.0179357 0.0157106 0.0136562 0.0117951 0.0101273 0.00865784
- 0.00739394 0.00634364 0.00551356 0.00480538 0.00415747 0.00356084
- 0.00297585 0.00236711 0.00181853 0.00160713 0.00169822 0.00166542
- 0.00145504 0.00120252 0.00109259 0.000982658 0.00087273
- 0.000762802 0.000652874 0.000584068 0.000528263 0.000472458
- 0.000416653 0.000360848 0.000321155 0.000301442 0.000281729
- 0.000262016 0.000242303 0.00022259 0.000202877 0.000183164
- 0.000163451 0.000143738 0.000124025 0.000114582 0.000107399
- 0.000100216 9.30332e-05 8.58502e-05 7.86672e-05 7.14841e-05
- 6.43011e-05 5.7118e-05 4.9935e-05 4.35378e-05 4.04281e-05
- 3.73184e-05 3.42088e-05 3.10991e-05 2.79894e-05 2.48798e-05
- 2.17701e-05 1.86604e-05
- EOD
-
- @v[35].set(<<-'EOD')
- 7.24585e-12 2.21843e-05 3.20014e-05 1.25076e-05 -2.44947e-05
- 1.8425e-05 5.50546e-06 3.53025e-05 -1.07551e-05 -3.94383e-06
- -2.27848e-06 -9.04789e-05 7.44215e-05 -2.7662e-05 0.000200038
- -2.11998e-05 -2.09011e-05 2.37098e-05 2.18751e-05 -2.28422e-05
- -6.23659e-05 3.58241e-05 1.76386e-05 -4.28311e-05 0.000355626
- 0.00156903 0.00100999 -0.0085304 -0.02067 -0.0389485 -0.0651568
- -0.128475 -0.314362 -0.406837 -0.421558 -0.421277 -0.418176
- -0.414481 -0.410845 -0.407348 -0.403971 -0.400716 -0.397582
- -0.394563 -0.391658 -0.388866 -0.386178 -0.383585 -0.381094
- -0.378789 -0.376569 -0.37435 -0.372256 -0.370188 -0.36815
- -0.366422 -0.364694 -0.362967 -0.361239 -0.359511 -0.357888
- -0.356334 -0.354781 -0.353227 -0.351674 -0.350152 -0.348888
- -0.347625 -0.346361 -0.345098 -0.343834 -0.342571 -0.341307
- -0.340044 -0.33878 -0.337517 -0.336279 -0.335215 -0.334152
- -0.333088 -0.332024 -0.330961 -0.329897 -0.328833 -0.32777
- -0.326706 -0.325642 -0.324601 -0.323683 -0.322766 -0.321849
- -0.320932 -0.320014 -0.319097 -0.31818 -0.317263 -0.316345
- -0.315428 -0.314545 -0.313825 -0.313106 -0.312387 -0.311667
- -0.310948 -0.310228 -0.309509 -0.308789 -0.30807 -0.307351
- -0.306631 -0.305912 -0.305192 -0.304473 -0.303754 -0.303034
- -0.302315 -0.301595 -0.300876 -0.300157 -0.299437 -0.298716
- -0.29798 -0.297329 -0.296691 -0.295837 -0.29516 -0.294725
- -0.294044 -0.292917 -0.292351 -0.291965 -0.291365 -0.290687
- -0.290027 -0.289376 -0.288772 -0.288193 -0.287505 -0.286892
- -0.28626 -0.285714 -0.284545 -0.289246 -0.298717 -0.298492
- -0.214163 0.181451 0.0749974 0.0454707 0.0292987 0.0196837
- 0.0124119 0.00884715 0.00527181 0.00585821 0.0296361 0.169856
- 0.361207 0.538856 0.67469 0.685933 0.392802 0.17772 0.0813085
- 0.0424601 0.0246654 0.0175258 0.0144256 0.0129859 0.012205
- 0.0112846 0.010933 0.0134813 0.0147254 0.0147981 0.0142156
- 0.0132732 0.0121355 0.0109587 0.00981238 0.00872731 0.00767007
- 0.00669346 0.00581341 0.00502167 0.00431819 0.00369842 0.00316168
- 0.00269663 0.00230035 0.00195801 0.00166928 0.00142286 0.00121522
- 0.00104072 0.000893384 0.000767675 0.000661268 0.000567659
- 0.000481766 0.000407101 0.000350044 0.000302721 0.000263424
- 0.000236813 0.00022199 0.000218182 0.000219548 0.0002027
- 0.000185853 0.000169006 0.000152158 0.000135311 0.000118463
- 0.000101616 9.33782e-05 8.57685e-05 7.81588e-05 7.0549e-05
- 6.29393e-05 5.53296e-05 4.77199e-05 4.36954e-05 4.15296e-05
- 3.93637e-05 3.71978e-05 3.50319e-05 3.28661e-05 3.07002e-05
- 2.85343e-05 2.63685e-05 2.42026e-05 2.20367e-05 1.98709e-05
- 1.7705e-05 1.55391e-05 1.34772e-05 1.22416e-05 1.10061e-05
- 9.77055e-06 8.535e-06 0.000631271 -0.00362586 -0.0146235
- -0.0308486 -0.0237466 -0.0117522 -0.00304171 0.00251033
- 0.00531986 0.0063897 0.00657351 0.00636494 0.00599705 0.00553442
- 0.00505994 0.00330925 0.00246671 0.0027006 0.00473161 0.00830333
- 0.00649147 0.00356815 0.00217448 0.00187579 0.00270447 0.00219543
- -0.00546118 -0.0179576 -0.0445306 -0.0649309 0.0197935 0.473629
- 0.87268 0.269542 0.0086094 0.0844602 0.606456 1.04929 0.906014
- 0.916205 0.919425 0.872867 0.556244 0.262457 0.11838 0.0571226
- 0.0333451 0.0237133 0.0185096 0.0159617 0.0148663 0.0138683
- 0.0144081 0.0153797 0.0152551 0.0146487 0.0137192 0.0125973
- 0.0113996 0.0101903 0.00901851 0.00790495 0.00687502 0.00593994
- 0.00510092 0.00436111 0.00372439 0.0031945 0.00277537 0.00241888
- 0.002095 0.00179943 0.00150419 0.00119264 0.00090934 0.000802394
- 0.000852816 0.000838368 0.000730842 0.000601028 0.000546616
- 0.000492205 0.000437793 0.000383381 0.000328969 0.00029454
- 0.000266428 0.000238317 0.000210205 0.000182093 0.000162091
- 0.000152145 0.000142198 0.000132252 0.000122306 0.000112359
- 0.000102413 9.24665e-05 8.25201e-05 7.25738e-05 6.26274e-05
- 5.78553e-05 5.42216e-05 5.05878e-05 4.69541e-05 4.33204e-05
- 3.96867e-05 3.60529e-05 3.24192e-05 2.87855e-05 2.51518e-05
- 2.19153e-05 2.03406e-05 1.8766e-05 1.71913e-05 1.56167e-05
- 1.4042e-05 1.24674e-05 1.08927e-05 9.31806e-06
- EOD
-
- @v[36].set(<<-'EOD')
- 5 5.01426 5.02852 5.01923 4.77685 4.56471 4.52338 4.56813
- 4.63122 4.693 4.74776 4.79385 4.83258 4.86358 4.88918 4.91021
- 4.90553 4.89733 4.89554 4.91953 5.00757 5.07101 5.06318
- 5.05241 5.05535 5.08042 5.07251 4.90973 4.56136 3.98637
- 3.237 2.67216 2.33678 2.13529 2.00544 1.91429 1.84638 1.79461
- 1.75338 1.71958 1.69175 1.6686 1.64918 1.63258 1.61836 1.60607
- 1.59506 1.58483 1.57575 1.56847 1.56193 1.55538 1.54968
- 1.54416 1.5388 1.53523 1.53165 1.52807 1.52449 1.52091 1.51771
- 1.51477 1.51182 1.50888 1.50593 1.50309 1.50113 1.49917
- 1.4972 1.49524 1.49328 1.49132 1.48935 1.48739 1.48543 1.48346
- 1.48157 1.48012 1.47868 1.47724 1.47579 1.47435 1.47291
- 1.47146 1.47002 1.46857 1.46713 1.46574 1.46462 1.4635 1.46238
- 1.46126 1.46014 1.45902 1.4579 1.45678 1.45567 1.45455 1.45349
- 1.45275 1.45201 1.45127 1.45053 1.44979 1.44905 1.44831
- 1.44757 1.44683 1.44609 1.44535 1.44461 1.44387 1.44313
- 1.44239 1.44165 1.44091 1.44017 1.43943 1.43869 1.43795
- 1.43721 1.43874 1.43976 1.43619 1.43182 1.43726 1.43084
- 1.42587 1.42383 1.42642 1.42728 1.42736 1.4271 1.42669 1.42621
- 1.42569 1.41703 1.41244 1.41019 1.41199 1.41833 1.42502
- 1.41504 1.37535 1.28381 1.44779 2.33713 3.25835 3.67554
- 3.84975 4.01125 4.2253 4.45433 4.62215 4.74478 4.82998 4.8868
- 4.92396 4.94768 4.96498 4.98537 5.0128 5.04467 5.06722 5.06535
- 5.01475 4.91956 4.80647 4.7242 4.7059 4.73552 4.76379 4.81684
- 4.87376 4.92276 4.96112 4.9884 5.0045 5.00999 5.00933 5.00619
- 5.00384 5.00342 5.00373 5.00362 5.00309 5.00272 5.00239
- 5.00204 5.00172 5.00146 5.00124 5.00105 5.00089 5.00076
- 5.00065 5.00057 5.00048 5.00041 5.00034 5.00028 5.00023
- 5.00019 5.00015 5.00015 5.00016 5.0002 5.00023 5.00021 5.00019
- 5.00017 5.00015 5.00012 5.0001 5.00008 5.00007 5.00006 5.00005
- 5.00004 5.00003 5.00002 5.00001 5.00001 5.00001 5.00001
- 5.00001 5.00001 5.00001 5.00002 5.00002 5.00002 5.00002
- 5.00002 5.00002 5.00002 5.00002 5.00002 5.00002 5.00001
- 5.00001 5.00001 5.00062 4.99506 4.9835 4.96726 4.9728 4.97877
- 4.98675 4.9966 5.00406 5.00679 5.00629 5.00561 5.00487 5.00429
- 5.00384 5.002 5.00164 5.00229 5.00484 5.00769 5.00019 5.00242
- 5.01319 5.0335 5.07265 5.10129 5.11485 5.12551 5.13953 5.16048
- 5.18862 5.22811 5.25656 5.25627 5.19975 4.9139 4.24745 3.43732
- 2.8202 2.43224 2.17409 2.01333 1.93951 1.94622 1.98861 2.02217
- 2.05383 2.08376 2.11184 2.13793 2.16191 2.18267 2.20502
- 2.22837 2.24958 2.26901 2.28648 2.302 2.31582 2.32802 2.33869
- 2.34795 2.35596 2.36282 2.3687 2.37371 2.37797 2.38161 2.38476
- 2.38743 2.3897 2.39168 2.39329 2.39463 2.39575 2.39671 2.39756
- 2.39835 2.39907 2.39968 2.39999 2.4003 2.40061 2.40091 2.40122
- 2.40142 2.40159 2.40176 2.40193 2.4021 2.40222 2.40228 2.40234
- 2.4024 2.40247 2.40253 2.40259 2.40265 2.40271 2.40277 2.40284
- 2.40287 2.40289 2.40291 2.40294 2.40296 2.40298 2.40301
- 2.40303 2.40305 2.40308 2.4031 2.40311 2.40312 2.40313 2.40314
- 2.40315 2.40316 2.40317 2.40318
- EOD
-
- @v[37].set(<<-'EOD')
- 5 5.01732 5.03181 5.05944 5.12686 5.20725 5.28103 5.31254
- 5.32901 5.33709 5.3408 5.34257 5.34311 5.34347 5.34386 5.34411
- 5.3406 5.33484 5.32942 5.32904 5.33644 5.34869 5.35001 5.34882
- 5.34758 5.34672 5.34599 5.34496 5.34364 5.34165 5.33712
- 5.33502 5.3366 5.34067 5.34306 5.34398 5.34434 5.34442 5.34443
- 5.34443 5.34441 5.34439 5.34437 5.34437 5.34438 5.34438
- 5.34438 5.34438 5.34438 5.34437 5.34437 5.34436 5.34436
- 5.34437 5.34437 5.34437 5.34437 5.34437 5.34437 5.34437
- 5.34437 5.34437 5.34437 5.34437 5.34437 5.34437 5.34437
- 5.34437 5.34437 5.34437 5.34437 5.34437 5.34437 5.34437
- 5.34437 5.34437 5.34437 5.34437 5.34437 5.34437 5.34437
- 5.34437 5.34437 5.34437 5.34437 5.34437 5.34437 5.34437
- 5.34437 5.34437 5.34437 5.34437 5.34437 5.34437 5.34437
- 5.34437 5.34437 5.34437 5.34437 5.34437 5.34437 5.34437
- 5.34437 5.34437 5.34437 5.34437 5.34437 5.34437 5.34437
- 5.34437 5.34437 5.34437 5.34437 5.34437 5.34437 5.34437
- 5.34437 5.34437 5.34437 5.34437 5.34437 5.35377 5.35451
- 5.34265 5.34488 5.35861 5.28622 4.90033 4.75027 4.89731
- 4.97098 4.99293 4.99832 4.99909 4.99956 4.99858 4.99829
- 4.9998 5.00035 5.0038 5.00989 5.00251 4.99438 4.9953 4.99761
- 4.99985 5.00152 5.0011 5.00046 4.99996 4.99925 4.99862 4.99919
- 4.99961 5.00048 5.00234 4.99654 4.98235 4.95936 4.83738
- 4.53021 4.21004 4.00593 3.91207 3.88059 3.87822 3.89117
- 3.91278 3.94044 3.97376 4.01152 4.05052 4.10679 4.17908
- 4.25673 4.33414 4.40875 4.47879 4.54342 4.60258 4.65595
- 4.70291 4.74414 4.78018 4.81185 4.83915 4.86291 4.88301
- 4.90048 4.91528 4.92802 4.9387 4.94777 4.95539 4.9618 4.96725
- 4.97195 4.97588 4.97932 4.98247 4.98512 4.98697 4.98831
- 4.98919 4.99015 4.99101 4.99169 4.99222 4.99282 4.99341
- 4.994 4.9946 4.99519 4.99578 4.99638 4.99667 4.99693 4.9972
- 4.99747 4.99773 4.998 4.99827 4.99841 4.99849 4.99856 4.99864
- 4.99872 4.9988 4.99888 4.99896 4.99904 4.99911 4.99919 4.99927
- 4.99935 4.99943 4.9995 4.99955 4.9996 4.99965 4.9997 5.00736
- 4.98252 4.87516 4.66727 4.49142 4.43103 4.4301 4.4571 4.49729
- 4.5407 4.5835 4.62363 4.66114 4.69577 4.72738 4.74632 4.75971
- 4.77576 4.80671 4.87073 4.91665 4.93252 4.94418 4.95331
- 4.96094 4.96727 4.97148 4.97471 4.97612 4.98276 5.00247
- 5.04086 5.08628 5.10673 5.08887 5.0564 5.02767 5.01336 4.99685
- 4.97422 4.90866 4.67035 4.33117 4.07888 3.94432 3.89105
- 3.88174 3.89292 3.91442 3.94564 3.98708 4.0355 4.09134 4.16315
- 4.24088 4.31918 4.39527 4.46693 4.53337 4.59405 4.6486 4.69693
- 4.73938 4.77617 4.80809 4.83551 4.85895 4.87894 4.89596
- 4.91081 4.92417 4.93651 4.94552 4.95198 4.9565 4.96096 4.96523
- 4.96972 4.97428 4.97868 4.98064 4.9826 4.98455 4.98651 4.98847
- 4.98967 4.99064 4.9916 4.99257 4.99353 4.99422 4.99457 4.99493
- 4.99528 4.99563 4.99598 4.99633 4.99668 4.99703 4.99738
- 4.99773 4.9979 4.99804 4.99817 4.9983 4.99843 4.99856 4.99869
- 4.99883 4.99896 4.99909 4.99921 4.99926 4.99931 4.99937
- 4.99942 4.99948 4.99953 4.99959 4.99964
- EOD
-
- @v[38].set(<<-'EOD')
- 4.49849 4.53282 4.58329 4.66625 4.83345 4.97823 5.0207 5.01816
- 5.01116 5.00595 5.00296 5.00148 5.00073 5.00062 5.00033
- 5.0003 4.99864 4.99661 4.99652 4.99928 5.00361 5.12573 5.17251
- 5.22612 5.33479 5.44503 5.44432 5.44379 5.44334 5.443 5.44276
- 5.44258 5.44246 5.44238 5.44232 5.44228 5.44225 5.44223
- 5.44221 5.4422 5.44219 5.44219 5.44218 5.44218 5.44218 5.44218
- 5.44217 5.44217 5.44217 5.44217 5.44217 5.44217 5.44217
- 5.44217 5.44217 5.44217 5.44217 5.44217 5.44217 5.44217
- 5.44217 5.44217 5.44217 5.44217 5.44217 5.44217 5.44216
- 5.44216 5.44216 5.44216 5.44216 5.44216 5.44216 5.44216
- 5.44216 5.44216 5.44216 5.44216 5.44216 5.44216 5.44216
- 5.44216 5.44216 5.44216 5.44216 5.44215 5.44215 5.44215
- 5.44215 5.44215 5.44215 5.44215 5.44215 5.44215 5.44215
- 5.44215 5.44215 5.44215 5.44215 5.44215 5.44215 5.44215
- 5.44215 5.44215 5.44215 5.44215 5.44215 5.44215 5.44215
- 5.44214 5.44214 5.44214 5.44214 5.44214 5.44214 5.44214
- 5.44214 5.44214 5.44214 5.44214 5.44212 5.45159 5.45236
- 5.44064 5.44307 5.45616 5.38122 4.77163 3.53297 2.74466
- 2.34448 2.11802 1.9783 1.88656 1.82001 1.77389 1.72955 1.69632
- 1.66971 1.6526 1.65236 1.56034 1.53764 1.97139 2.75096 3.39212
- 3.74042 3.82345 3.85696 3.88547 3.91862 3.9585 4.00467 4.05903
- 4.1254 4.19533 4.26791 4.34517 4.42112 4.49238 4.55807 4.6179
- 4.6713 4.71815 4.75889 4.79418 4.82456 4.85062 4.87291 4.89196
- 4.90823 4.92209 4.93388 4.9439 4.95242 4.95968 4.96585 4.97108
- 4.9755 4.97923 4.98237 4.98503 4.98732 4.98927 4.99094 4.99233
- 4.99353 4.99452 4.99538 4.99608 4.99668 4.99718 4.9976 4.99794
- 4.99822 4.99847 4.99867 4.99884 4.99899 4.99913 4.99924
- 4.99932 4.99938 4.99943 4.99947 4.99951 4.99953 4.99955
- 4.99958 4.99961 4.99964 4.99967 4.99969 4.99972 4.99975
- 4.99977 4.99978 4.99979 4.99981 4.99982 4.99983 4.99985
- 4.99986 4.99986 4.99987 4.99987 4.99988 4.99988 4.99988
- 4.99989 4.99989 4.9999 4.9999 4.99991 4.99991 4.99992 4.99992
- 4.99993 4.99993 4.99993 4.99994 5.00381 5.00064 4.99246
- 4.99823 5.00349 5.00076 5.00033 5.00015 5.00009 5.00007
- 5.00005 5.00004 5.00003 5.00002 4.99988 4.99732 4.99728
- 4.9978 5.00187 5.00927 5.08712 5.07654 4.92855 4.4863 3.76162
- 3.00049 2.49834 2.20883 2.03492 1.92384 1.84676 1.79021
- 1.74716 1.7132 1.68576 1.66309 1.64406 1.62785 1.61383 1.60162
- 1.59081 1.58117 1.57253 1.56473 1.55765 1.55117 1.54527
- 1.53988 1.53485 1.53012 1.5257 1.5216 1.51773 1.51411 1.51071
- 1.50746 1.50438 1.50146 1.49868 1.49603 1.4935 1.49109 1.48878
- 1.48657 1.48445 1.48242 1.48046 1.47858 1.47677 1.47502
- 1.47333 1.4717 1.47012 1.46859 1.46711 1.46568 1.46428 1.46292
- 1.4616 1.46034 1.45923 1.45812 1.45701 1.4559 1.45479 1.45378
- 1.45279 1.45181 1.45082 1.44983 1.44893 1.44813 1.44732
- 1.44652 1.44571 1.44491 1.4441 1.4433 1.44249 1.44169 1.44089
- 1.44019 1.43951 1.43883 1.43815 1.43747 1.4368 1.43612 1.43544
- 1.43476 1.43408 1.43342 1.43283 1.43223 1.43163 1.43104
- 1.43044 1.42984 1.42924 1.42865
- EOD
-
- @v[39].set(<<-'EOD')
- 5 5.01048 5.01221 4.98887 4.76261 4.54943 4.51564 4.56249
- 4.62621 4.68843 4.74374 4.79044 4.82972 4.86127 4.88724
- 4.90862 4.90791 4.89858 4.89589 4.91767 5.00405 5.16956
- 5.12391 4.7557 3.87953 3.01124 2.48482 2.20424 2.03812 1.92679
- 1.84956 1.79256 1.74907 1.71487 1.68724 1.6644 1.64513 1.6287
- 1.61446 1.60197 1.59095 1.58117 1.57245 1.5646 1.55752 1.55109
- 1.54516 1.53958 1.53444 1.53008 1.52606 1.52205 1.51843
- 1.5149 1.51146 1.50893 1.50639 1.50387 1.50133 1.4988 1.49651
- 1.49436 1.49222 1.49007 1.48793 1.48585 1.48433 1.4828 1.48128
- 1.47975 1.47823 1.4767 1.47518 1.47365 1.47213 1.4706 1.46912
- 1.46795 1.46678 1.46561 1.46444 1.46327 1.4621 1.46093 1.45976
- 1.45859 1.45741 1.45628 1.45534 1.45441 1.45347 1.45254
- 1.4516 1.45067 1.44973 1.4488 1.44786 1.44693 1.44604 1.44539
- 1.44475 1.4441 1.44345 1.44281 1.44216 1.44151 1.44086 1.44022
- 1.43957 1.43892 1.43828 1.43763 1.43698 1.43633 1.43569
- 1.43504 1.43439 1.43375 1.4331 1.43245 1.4318 1.43157 1.43089
- 1.43001 1.43042 1.42899 1.42439 1.42216 1.43447 1.44048
- 1.43705 1.43314 1.43039 1.42861 1.42739 1.42651 1.42548
- 1.42488 1.4243 1.42392 1.4235 1.32443 1.31149 1.78169 2.64844
- 3.43211 3.95252 4.20231 4.3746 4.49948 4.58929 4.65742 4.71183
- 4.77057 4.83196 4.88354 4.92894 4.96625 4.99235 5.00651
- 5.00941 5.00813 5.00689 5.00588 5.00504 5.00431 5.00368
- 5.00314 5.00268 5.00228 5.00194 5.00165 5.0014 5.00118 5.001
- 5.00085 5.00072 5.00061 5.00052 5.00044 5.00037 5.00031
- 5.00027 5.00022 5.00019 5.00016 5.00013 5.00011 5.00009
- 5.00008 5.00007 5.00006 5.00005 5.00004 5.00003 5.00003
- 5.00003 5.00002 5.00002 5.00002 5.00001 5.00001 5.00001
- 5.00001 5.00001 5.00001 5.00001 5.00001 5.00001 5.00001
- 5.00001 5.00001 5 5 5 5 5 4.99999 4.99999 4.99999 4.99998
- 4.99998 4.99998 4.99998 4.99998 4.99998 4.99998 4.99999
- 4.99999 4.99999 4.99999 4.99999 4.99999 5 5 5 5 5.00001
- 5.00002 5.00003 5.00004 5.00022 4.99974 4.99942 4.99997
- 5.00063 5.00002 5.00003 4.99994 4.99998 4.99999 5 5 5 5
- 5 4.99981 4.99998 5.00004 5.00036 5.00049 5.12012 5.16315
- 5.19712 5.21835 4.87874 4.10151 3.31555 2.74207 2.38075
- 2.15872 2.01614 1.91886 1.84852 1.79401 1.75052 1.71508
- 1.68672 1.66467 1.64602 1.62985 1.61576 1.60343 1.59256
- 1.58287 1.57418 1.56632 1.55922 1.55282 1.54687 1.54132
- 1.53618 1.53143 1.52698 1.52282 1.51895 1.51527 1.5118 1.50851
- 1.5054 1.50244 1.49963 1.49695 1.4944 1.49196 1.48963 1.4874
- 1.48527 1.48322 1.48124 1.47934 1.47751 1.47574 1.47403
- 1.47239 1.4708 1.46926 1.46777 1.46632 1.46491 1.46355 1.46237
- 1.4612 1.46002 1.45884 1.45766 1.45659 1.45555 1.45451 1.45346
- 1.45242 1.45147 1.45062 1.44978 1.44894 1.44809 1.44725
- 1.4464 1.44556 1.44472 1.44387 1.44303 1.4423 1.44159 1.44088
- 1.44017 1.43947 1.43876 1.43805 1.43734 1.43664 1.43593
- 1.43524 1.43462 1.434 1.43338 1.43276 1.43213 1.43151 1.43089
- 1.43027
- EOD
- end
-
- def highlightTrace(graph)
- entry = graph.legend_get(:current)
- active_list = graph.legend_activate
- if active_list.include?(entry)
- graph.legend_deactivate(entry)
- graph.element_deactivate(entry)
- else
- graph.legend_activate(entry)
- graph.element_activate(entry)
- end
- end
-
-end
-
-BLT_Graph_Demo.new
-
-Tk.mainloop
diff --git a/ext/tk/sample/tkextlib/blt/graph7.rb b/ext/tk/sample/tkextlib/blt/graph7.rb
deleted file mode 100644
index 27fbe53d97..0000000000
--- a/ext/tk/sample/tkextlib/blt/graph7.rb
+++ /dev/null
@@ -1,40 +0,0 @@
-#!/usr/bin/env ruby
-require 'tk'
-require 'tkextlib/blt'
-
-length = 250000
-graph = Tk::BLT::Graph.new(:title=>"Scatter Plot\n#{length} points")
-graph.xaxis_configure(:loose=>false, :title=>'X Axis Label')
-graph.yaxis_configure(:title=>'Y Axis Label')
-graph.legend_configure(:activerelief=>:sunken, :background=>'')
-
-Tk::BLT::Table.add(Tk.root, graph, [0,0], :fill=>:both)
-
-v_x = Tk::BLT::Vector.new(length)
-v_y = Tk::BLT::Vector.new(length)
-v_x.expr("random(#{v_x})")
-v_y.expr("random(#{v_y})")
-v_x.sort(v_y)
-
-plot = Tk::BLT::PlotComponent::Element.new(graph, :symbol=>:square,
- :color=>'green4', :fill=>'green2',
- :linewidth=>0, :outlinewidth=>1,
- :pixels=>4, :label=>'plot',
- :xdata=>v_x, :ydata=>v_y)
-
-Tk.root.minsize(0, 0)
-
-#graph.zoom_stack
-#graph.crosshairs
-#graph.active_legend
-#graph.closest_point
-Tk::BLT.zoom_stack(graph)
-Tk::BLT.crosshairs(graph)
-Tk::BLT.active_legend(graph)
-Tk::BLT.closest_point(graph)
-
-Tk::BLT::Busy.hold(graph)
-Tk.update
-Tk::BLT::Busy.release(graph)
-
-Tk.mainloop
diff --git a/ext/tk/sample/tkextlib/blt/graph7a.rb b/ext/tk/sample/tkextlib/blt/graph7a.rb
deleted file mode 100644
index a014f72fc7..0000000000
--- a/ext/tk/sample/tkextlib/blt/graph7a.rb
+++ /dev/null
@@ -1,63 +0,0 @@
-#!/usr/bin/env ruby
-require 'tk'
-require 'tkextlib/blt'
-
-file = File.join(File.dirname(File.expand_path(__FILE__)),
- 'images', 'buckskin.gif')
-bgTexture = TkPhotoImage.new(:file=>file)
-
-TkOption.add('*Graph.Tile', bgTexture)
-TkOption.add('*Label.Tile', bgTexture)
-TkOption.add('*Frame.Tile', bgTexture)
-TkOption.add('*Htext.Tile', bgTexture)
-TkOption.add('*TileOffset', 0)
-TkOption.add('*HighlightThickness', 0)
-TkOption.add('*Element.ScaleSybols', false)
-TkOption.add('*Element.Smooth', :linear)
-TkOption.add('*activeLine.Color', 'yellow4')
-TkOption.add('*activeLine.Fill', 'yellow')
-TkOption.add('*activeLine.LineWidth', 0)
-TkOption.add('*Element.Pixels', 3)
-TkOption.add('*Graph.halo', '7i')
-
-if Tk.root.winfo_screenvisual != 'staticgray'
- TkOption.add('*print.background', 'yellow')
- TkOption.add('*quit.background', 'red')
-end
-
-length = 250000
-graph = Tk::BLT::Graph.new(:title=>"Scatter Plot\n#{length} points")
-graph.xaxis_configure(:loose=>false, :title=>'X Axis Label')
-graph.yaxis_configure(:title=>'Y Axis Label')
-graph.legend_configure(:activerelief=>:sunken, :background=>'')
-
-Tk::BLT::Table.add(Tk.root, graph, [0,0], :fill=>:both)
-
-v_x = Tk::BLT::Vector.new(length)
-v_y = Tk::BLT::Vector.new(length)
-v_x.expr("random(#{v_x})")
-v_y.expr("random(#{v_y})")
-v_x.sort(v_y)
-
-plot = Tk::BLT::PlotComponent::Element.new(graph, :symbol=>:square,
- :color=>'green4', :fill=>'green2',
- :linewidth=>0, :outlinewidth=>1,
- :pixels=>4, :label=>'plot',
- :xdata=>v_x, :ydata=>v_y)
-
-Tk.root.minsize(0, 0)
-
-#graph.zoom_stack
-#graph.crosshairs
-#graph.active_legend
-#graph.closest_point
-Tk::BLT.zoom_stack(graph)
-Tk::BLT.crosshairs(graph)
-Tk::BLT.active_legend(graph)
-Tk::BLT.closest_point(graph)
-
-Tk::BLT::Busy.hold(graph)
-Tk.update
-Tk::BLT::Busy.release(graph)
-
-Tk.mainloop
diff --git a/ext/tk/sample/tkextlib/blt/graph7b.rb b/ext/tk/sample/tkextlib/blt/graph7b.rb
deleted file mode 100644
index c589f18d86..0000000000
--- a/ext/tk/sample/tkextlib/blt/graph7b.rb
+++ /dev/null
@@ -1,41 +0,0 @@
-#!/usr/bin/env ruby
-require 'tk'
-require 'tkextlib/blt'
-
-length = 250000
-graph = Tk::BLT::Graph.new(:title=>"Scatter Plot\n#{length} points")
-graph.xaxis_configure(:loose=>false, :title=>'X Axis Label')
-graph.yaxis_configure(:title=>'Y Axis Label')
-graph.legend_configure(:activerelief=>:sunken, :background=>'')
-
-Tk::BLT::Table.add(Tk.root, graph, [0,0], :fill=>:both)
-
-x = Array.new(length)
-y = Array.new(length)
-(0...length).each{|i|
- x[i] = rand
- y[i] = rand
-}
-
-plot = Tk::BLT::PlotComponent::Element.new(graph, :symbol=>:square,
- :color=>'green4', :fill=>'green2',
- :linewidth=>0, :outlinewidth=>1,
- :pixels=>4, :label=>'plot',
- :xdata=>x, :ydata=>y)
-
-Tk.root.minsize(0, 0)
-
-#graph.zoom_stack
-#graph.crosshairs
-#graph.active_legend
-#graph.closest_point
-Tk::BLT.zoom_stack(graph)
-Tk::BLT.crosshairs(graph)
-Tk::BLT.active_legend(graph)
-Tk::BLT.closest_point(graph)
-
-Tk::BLT::Busy.hold(graph)
-Tk.update
-Tk::BLT::Busy.release(graph)
-
-Tk.mainloop
diff --git a/ext/tk/sample/tkextlib/blt/graph7c.rb b/ext/tk/sample/tkextlib/blt/graph7c.rb
deleted file mode 100644
index 495b66f4af..0000000000
--- a/ext/tk/sample/tkextlib/blt/graph7c.rb
+++ /dev/null
@@ -1,45 +0,0 @@
-#!/usr/bin/env ruby
-require 'tk'
-require 'tkextlib/blt'
-
-length = 250000
-graph = Tk::BLT::Graph.new(:title=>"Scatter Plot\n#{length} points")
-graph.xaxis_configure(:loose=>false, :title=>'X Axis Label')
-graph.yaxis_configure(:title=>'Y Axis Label')
-graph.legend_configure(:activerelief=>:sunken, :background=>'')
-
-Tk::BLT::Table.add(Tk.root, graph, [0,0], :fill=>:both)
-
-v_x = Tk::BLT::Vector.new(length)
-v_y = Tk::BLT::Vector.new(length)
-x = Array.new(length)
-y = Array.new(length)
-(0...length).each{|i|
- x[i] = rand
- y[i] = rand
-}
-v_x.set(x)
-v_y.set(y)
-
-plot = Tk::BLT::PlotComponent::Element.new(graph, :symbol=>:square,
- :color=>'green4', :fill=>'green2',
- :linewidth=>0, :outlinewidth=>1,
- :pixels=>4, :label=>'plot',
- :xdata=>v_x, :ydata=>v_y)
-
-Tk.root.minsize(0, 0)
-
-#graph.zoom_stack
-#graph.crosshairs
-#graph.active_legend
-#graph.closest_point
-Tk::BLT.zoom_stack(graph)
-Tk::BLT.crosshairs(graph)
-Tk::BLT.active_legend(graph)
-Tk::BLT.closest_point(graph)
-
-Tk::BLT::Busy.hold(graph)
-Tk.update
-Tk::BLT::Busy.release(graph)
-
-Tk.mainloop
diff --git a/ext/tk/sample/tkextlib/blt/images/buckskin.gif b/ext/tk/sample/tkextlib/blt/images/buckskin.gif
deleted file mode 100644
index e2d7be9d62..0000000000
--- a/ext/tk/sample/tkextlib/blt/images/buckskin.gif
+++ /dev/null
Binary files differ
diff --git a/ext/tk/sample/tkextlib/blt/images/chalk.gif b/ext/tk/sample/tkextlib/blt/images/chalk.gif
deleted file mode 100644
index 30d29a7221..0000000000
--- a/ext/tk/sample/tkextlib/blt/images/chalk.gif
+++ /dev/null
Binary files differ
diff --git a/ext/tk/sample/tkextlib/blt/images/qv100.t.gif b/ext/tk/sample/tkextlib/blt/images/qv100.t.gif
deleted file mode 100644
index 1e738ee86b..0000000000
--- a/ext/tk/sample/tkextlib/blt/images/qv100.t.gif
+++ /dev/null
Binary files differ
diff --git a/ext/tk/sample/tkextlib/blt/images/rain.gif b/ext/tk/sample/tkextlib/blt/images/rain.gif
deleted file mode 100644
index d7bb417939..0000000000
--- a/ext/tk/sample/tkextlib/blt/images/rain.gif
+++ /dev/null
Binary files differ
diff --git a/ext/tk/sample/tkextlib/blt/images/sample.gif b/ext/tk/sample/tkextlib/blt/images/sample.gif
deleted file mode 100644
index 1d8a4010c3..0000000000
--- a/ext/tk/sample/tkextlib/blt/images/sample.gif
+++ /dev/null
Binary files differ
diff --git a/ext/tk/sample/tkextlib/blt/pareto.rb b/ext/tk/sample/tkextlib/blt/pareto.rb
deleted file mode 100644
index 94d5f3f97f..0000000000
--- a/ext/tk/sample/tkextlib/blt/pareto.rb
+++ /dev/null
@@ -1,90 +0,0 @@
-#!/usr/bin/env ruby
-
-require 'tk'
-require 'tkextlib/blt'
-
-# Example of a pareto chart.
-#
-# The pareto chart mixes line and bar elements in the same graph.
-# Each processing operating is represented by a bar element. The
-# total accumulated defects is displayed with a single line element.
-b = Tk::BLT::Barchart.new(:title=>'Defects Found During Inspection',
- :font=>'Helvetica 12', :plotpady=>[12, 4],
- :width=>'6i', :height=>'5i')
-Tk::BLT::Table.add(Tk.root, b, :fill=>:both)
-
-data = [
- ["Spot Weld", 82, 'yellow'],
- ["Lathe", 49, 'orange'],
- ["Gear Cut", 38, 'green'],
- ["Drill", 24, 'blue'],
- ["Grind", 17, 'red'],
- ["Lapping", 12, 'brown'],
- ["Press", 8, 'purple'],
- ["De-burr", 4, 'pink'],
- ["Packaging", 3, 'cyan'],
- ["Other", 12, 'magenta']
-]
-
-# Create an X-Y graph line element to trace the accumulated defects.
-b.line_create('accum', :label=>'', :symbol=>:none, :color=>'red')
-
-# Define a bitmap to be used to stipple the background of each bar.
-pattern1 = Tk::BLT::Bitmap.define([ [4, 4], [1, 2, 4, 8] ])
-
-# For each process, create a bar element to display the magnitude.
-count = 0
-sum = 0
-ydata = [0]
-xdata = [0]
-labels = []
-
-data.each{|label, value, color|
- count += 1
- b.element_create(label, :xdata=>count, :ydata=>value, :foreground=>color,
- :relief=>:solid, :borderwidth=>1, :stipple=>pattern1,
- :background=>'lightblue')
- labels[count] = label
- # Get the total number of defects.
- sum += value
- ydata << sum
- xdata << count
-}
-
-# Configure the coordinates of the accumulated defects,
-# now that we know what they are.
-b.element_configure('accum', :xdata=>xdata, :ydata=>ydata)
-
-# Add text markers to label the percentage of total at each point.
-xdata.zip(ydata){|x, y|
- percent = (y * 100.0) / sum
- if x == 0
- text = ' 0%'
- else
- text = '%.1f' % percent
- end
- b.marker_create(:text, :coords=>[x, y], :text=>text, :font=>'Helvetica 10',
- :foreground=>'red4', :anchor=>:center, :yoffset=>-5)
-}
-
-# Display an auxillary y-axis for percentages.
-b.axis_configure('y2', :hide=>false, :min=>0.0, :max=>100.0,
- :title=>'Percentage')
-
-# Title the y-axis
-b.axis_configure('y', :title=>'Defects')
-
-# Configure the x-axis to display the process names, instead of numbers.
-b.axis_configure('x', :title=>'Process', :rotate=>90, :subdivisions=>0,
- :command=>proc{|w, val|
- val = val.round
- labels[val]? labels[val]: val
- })
-
-# No legend needed.
-b.legend_configure(:hide=>true)
-
-# Configure the grid lines.
-b.gridline_configure(:mapx=>:x, :color=>'lightblue')
-
-Tk.mainloop
diff --git a/ext/tk/sample/tkextlib/blt/plot1.rb b/ext/tk/sample/tkextlib/blt/plot1.rb
deleted file mode 100644
index 07dff48292..0000000000
--- a/ext/tk/sample/tkextlib/blt/plot1.rb
+++ /dev/null
@@ -1,9 +0,0 @@
-#!/usr/bin/env ruby
-require 'tk'
-require 'tkextlib/blt'
-
-graph = Tk::BLT::Graph.new.pack
-plot = Tk::BLT::PlotComponent::Element.new(graph, :linewidth=>0, :label=>'foo')
-plot.data([[1.0, 3.4], [1.1, 2.8], [1.2, 3.1], [1.4, 2.9]].flatten)
-
-Tk.mainloop
diff --git a/ext/tk/sample/tkextlib/blt/plot1b.rb b/ext/tk/sample/tkextlib/blt/plot1b.rb
deleted file mode 100644
index eb41e361f9..0000000000
--- a/ext/tk/sample/tkextlib/blt/plot1b.rb
+++ /dev/null
@@ -1,10 +0,0 @@
-#!/usr/bin/env ruby
-require 'tk'
-require 'tkextlib/blt'
-
-graph = Tk::BLT::Graph.new.pack
-plot = graph.element_create
-plot.configure(:linewidth=>0, :label=>'foo',
- :data=>[[1.0, 3.4], [1.1, 2.8], [1.2, 3.1], [1.4, 2.9]].flatten)
-
-Tk.mainloop
diff --git a/ext/tk/sample/tkextlib/blt/readme.txt b/ext/tk/sample/tkextlib/blt/readme.txt
deleted file mode 100644
index fe12dd88a3..0000000000
--- a/ext/tk/sample/tkextlib/blt/readme.txt
+++ /dev/null
@@ -1,2 +0,0 @@
-The scripts and image files in this directory are based on demo files
-of Tcl/Tk's BLT extention.
diff --git a/ext/tk/sample/tkextlib/blt/scripts/stipples.rb b/ext/tk/sample/tkextlib/blt/scripts/stipples.rb
deleted file mode 100644
index 47f3c4d063..0000000000
--- a/ext/tk/sample/tkextlib/blt/scripts/stipples.rb
+++ /dev/null
@@ -1,156 +0,0 @@
-$stipples = {} unless $stipples
-
-$stipples['bdiagonal1'] = Tk::BLT::Bitmap.new(<<EOD)
-#define bdiagonal1_width 8
-#define bdiagonal1_height 8
-static unsigned char bdiagonal1_bits[] = {
- 0x88, 0x44, 0x22, 0x11, 0x88, 0x44, 0x22, 0x11};
-EOD
-
-$stipples['bdiagonal2'] = Tk::BLT::Bitmap.new(<<EOD)
-#define bdiagonal2_width 8
-#define bdiagonal2_height 8
-static unsigned char bdiagonal2_bits[] = {
- 0x08, 0x04, 0x02, 0x01, 0x80, 0x40, 0x20, 0x10};
-EOD
-
-$stipples['checker2'] = Tk::BLT::Bitmap.new(<<EOD)
-#define checker2_width 8
-#define checker2_height 8
-static unsigned char checker2_bits[] = {
- 0x33, 0x33, 0xcc, 0xcc, 0x33, 0x33, 0xcc, 0xcc};
-EOD
-
-
-$stipples['checker3'] = Tk::BLT::Bitmap.new(<<EOD)
-#define checker3_width 8
-#define checker3_height 8
-static unsigned char checker3_bits[] = {
- 0x0f, 0x0f, 0x0f, 0x0f, 0xf0, 0xf0, 0xf0, 0xf0};
-EOD
-
-$stipples['cross1'] = Tk::BLT::Bitmap.new(<<EOD)
-#define cross1_width 8
-#define cross1_height 8
-static unsigned char cross_bits[] = {
- 0xff, 0xaa, 0xff, 0xaa, 0xff, 0xaa, 0xff, 0xaa};
-EOD
-
-$stipples['cross2'] = Tk::BLT::Bitmap.new(<<EOD)
-#define cross2_width 8
-#define cross2_height 8
-static unsigned char cross2_bits[] = {
- 0xff, 0x88, 0x88, 0x88, 0xff, 0x88, 0x88, 0x88};
-EOD
-
-$stipples['cross3'] = Tk::BLT::Bitmap.new(<<EOD)
-#define cross3_width 8
-#define cross3_height 8
-static unsigned char cross3_bits[] = {
- 0xff, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01};
-EOD
-
-$stipples['crossdiag'] = Tk::BLT::Bitmap.new(<<EOD)
-#define crossdiag_width 8
-#define crossdiag_height 8
-static unsigned char crossdiag2_bits[] = {
- 0x18, 0x24, 0x42, 0x81, 0x81, 0x42, 0x24, 0x18};
-EOD
-
-$stipples['dot1'] = Tk::BLT::Bitmap.new(<<EOD)
-#define dot1_width 8
-#define dot1_height 8
-static unsigned char dot1_bits[] = {
- 0x55, 0xaa, 0x55, 0xaa, 0x55, 0xaa, 0x55, 0xaa};
-EOD
-
-$stipples['dot2'] = Tk::BLT::Bitmap.new(<<EOD)
-#define dot2_width 8
-#define dot2_height 8
-static unsigned char dot2_bits[] = {
- 0x55, 0x00, 0x55, 0x00, 0x55, 0x00, 0x55, 0x00};
-EOD
-
-$stipples['dot3'] = Tk::BLT::Bitmap.new(<<EOD)
-#define dot3_width 8
-#define dot3_height 8
-static unsigned char dot3_bits[] = {
- 0x11, 0x00, 0x00, 0x00, 0x11, 0x00, 0x00, 0x00};
-EOD
-
-$stipples['dot4'] = Tk::BLT::Bitmap.new(<<EOD)
-#define dot4_width 8
-#define dot4_height 8
-static unsigned char dot4_bits[] = {
- 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
-EOD
-
-$stipples['fdiagonal1'] = Tk::BLT::Bitmap.new(<<EOD)
-#define fdiagonal1_width 8
-#define fdiagonal1_height 8
-static unsigned char fdiagonal1_bits[] = {
- 0x11, 0x22, 0x44, 0x88, 0x11, 0x22, 0x44, 0x88};
-EOD
-
-$stipples['fdiagonal2'] = Tk::BLT::Bitmap.new(<<EOD)
-#define fdiagonal2_width 8
-#define fdiagonal2_height 8
-static unsigned char fdiagonal2_bits[] = {
- 0x10, 0x20, 0x40, 0x80, 0x01, 0x02, 0x04, 0x08};
-EOD
-
-$stipples['hline1'] = Tk::BLT::Bitmap.new(<<EOD)
-#define hline1_width 8
-#define hline1_height 8
-static unsigned char hline1_bits[] = {
- 0xff, 0x00, 0xff, 0x00, 0xff, 0x00, 0xff, 0x00};
-EOD
-
-$stipples['hline2'] = Tk::BLT::Bitmap.new(<<EOD)
-#define hline2_width 8
-#define hline2_height 8
-static unsigned char hline2_bits[] = {
- 0xff, 0xff, 0x00, 0x00, 0xff, 0xff, 0x00, 0x00};
-EOD
-
-$stipples['lbottom'] = Tk::BLT::Bitmap.new(<<EOD)
-#define lbottom_width 8
-#define lbottom_height 8
-static unsigned char lbottom_bits[] = {
- 0x00, 0x11, 0x11, 0x77, 0x00, 0x11, 0x11, 0x77};
-EOD
-
-$stipples['ltop'] = Tk::BLT::Bitmap.new(<<EOD)
-#define ltop_width 8
-#define ltop_height 8
-static unsigned char ltop_bits[] = {
- 0xee, 0x88, 0x88, 0x00, 0xee, 0x88, 0x88, 0x00};
-EOD
-
-$stipples['rbottom'] = Tk::BLT::Bitmap.new(<<EOD)
-#define rbottom_width 8
-#define rbottom_height 8
-static unsigned char rbottom_bits[] = {
- 0x00, 0x88, 0x88, 0xee, 0x00, 0x88, 0x88, 0xee};
-EOD
-
-$stipples['rtop'] = Tk::BLT::Bitmap.new(<<EOD)
-#define rtop_width 8
-#define rtop_height 8
-static unsigned char rtop_bits[] = {
- 0x77, 0x11, 0x11, 0x00, 0x77, 0x11, 0x11, 0x00};
-EOD
-
-$stipples['vline1'] = Tk::BLT::Bitmap.new(<<EOD)
-#define vline1_width 8
-#define vline1_height 8
-static unsigned char vline1_bits[] = {
- 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55};
-EOD
-
-$stipples['vline2'] = Tk::BLT::Bitmap.new(<<EOD)
-#define vline2_width 8
-#define vline2_height 8
-static unsigned char vline2_bits[] = {
- 0x33, 0x33, 0x33, 0x33, 0x33, 0x33, 0x33, 0x33};
-EOD
diff --git a/ext/tk/sample/tkextlib/blt/winop1.rb b/ext/tk/sample/tkextlib/blt/winop1.rb
deleted file mode 100644
index e94138cd94..0000000000
--- a/ext/tk/sample/tkextlib/blt/winop1.rb
+++ /dev/null
@@ -1,40 +0,0 @@
-#!/usr/bin/env ruby
-require 'tk'
-require 'tkextlib/blt'
-
-file = File.join(File.dirname(File.expand_path(__FILE__)),
- 'images', 'sample.gif')
-if File.exist?(file)
- src = TkPhotoImage.new(:file=>file)
-else
- fail RuntimeError, 'no image file'
-end
-
-width = src.width
-height = src.height
-
-TkOption.add('*Label.font', '*helvetica*10*')
-TkOption.add('*Label.background', 'white')
-
-l_img0 = TkLabel.new(:image=>src)
-l_hdr0 = TkLabel.new(:text=>"#{width} x #{height}")
-l_ftr0 = TkLabel.new(:text=>'100%')
-Tk.root.background('white')
-
-(2..10).each{|i|
- iw = width/i
- ih = height/i
- r = '%6g'%(100.0/i)
- dst = TkPhotoImage.new(:width=>iw, :height=>ih)
- Tk::BLT::Winop.image_resample(src, dst, :sinc)
- l_hdr = TkLabel.new(:text=>"#{iw} x #{ih}")
- l_ftr = TkLabel.new(:text=>"#{r}%")
- l_img = TkLabel.new(:image=>dst)
- Tk::BLT::Table.add(Tk.root,
- [0,i], l_hdr,
- [1,i], l_img,
- [2,i], l_ftr)
- Tk.update
-}
-
-Tk.mainloop
diff --git a/ext/tk/sample/tkextlib/blt/winop2.rb b/ext/tk/sample/tkextlib/blt/winop2.rb
deleted file mode 100644
index 1f674ee893..0000000000
--- a/ext/tk/sample/tkextlib/blt/winop2.rb
+++ /dev/null
@@ -1,28 +0,0 @@
-#!/usr/bin/env ruby
-require 'tk'
-require 'tkextlib/blt'
-
-file = File.join(File.dirname(File.expand_path(__FILE__)),
- 'images', 'qv100.t.gif')
-if File.exist?(file)
- src = TkPhotoImage.new(:file=>file)
-else
- fail RuntimeError, 'no image file'
-end
-
-width = src.width
-height = src.height
-
-TkOption.add('*Label.font', '*helvetica*10*')
-TkOption.add('*Label.background', 'white')
-
-[0, 90, 180, 270, 360, 45].each_with_index{|r, i|
- dest = TkPhotoImage.new
- Tk::BLT::Winop.image_rotate(src, dest, r)
- l_txt = TkLabel.new(:text=>"#{r} degrees")
- l_img = TkLabel.new(:image=>dest)
- Tk::BLT::Table.add(Tk.root, [0,i], l_img, [1,i], l_txt)
- Tk.update
-}
-
-Tk.mainloop
diff --git a/ext/tk/sample/tkextlib/bwidget/tree.rb b/ext/tk/sample/tkextlib/bwidget/tree.rb
index e1fcaa774f..2b33962fa6 100644
--- a/ext/tk/sample/tkextlib/bwidget/tree.rb
+++ b/ext/tk/sample/tkextlib/bwidget/tree.rb
@@ -119,7 +119,7 @@ module DemoTree
Tk.root.bind_remove('Unmap')
Tk.root.bind_remove('Map')
Tk.root.bind_remove('Configure')
- true
+ return true
})
end
diff --git a/ext/tk/sample/tkextlib/iwidgets/sample/hierarchy.rb b/ext/tk/sample/tkextlib/iwidgets/sample/hierarchy.rb
index ddb08d8b78..c83ae37248 100644
--- a/ext/tk/sample/tkextlib/iwidgets/sample/hierarchy.rb
+++ b/ext/tk/sample/tkextlib/iwidgets/sample/hierarchy.rb
@@ -3,11 +3,11 @@ require 'tk'
require 'tkextlib/iwidgets'
def get_files(file)
- dir = (file.empty?)? ENV['HOME'] : TkComm._fromUTF8(file)
+ dir = (file.empty?)? ENV['HOME'] : file
Dir.chdir(dir) rescue return ''
- Dir['*'].sort.collect{|f|
- [TkComm._toUTF8(File.join(dir, f)), TkComm._toUTF8(f)]
- }
+ rlist = []
+ Dir['*'].sort.each{|f| rlist << File.join(dir, f) }
+ rlist
end
Tk::Iwidgets::Hierarchy.new(:querycommand=>proc{|arg| get_files(arg.node)},
diff --git a/ext/tk/sample/tkextlib/tile/Orig_LICENSE.txt b/ext/tk/sample/tkextlib/tile/Orig_LICENSE.txt
deleted file mode 100644
index 2326ef21fa..0000000000
--- a/ext/tk/sample/tkextlib/tile/Orig_LICENSE.txt
+++ /dev/null
@@ -1,30 +0,0 @@
-
- ######################################################################
- ### The following text is the original 'license.terms' of tile ###
- ### extension. ###
- ######################################################################
-
-
-LICENSE ("MIT-style")
-
-This software is Copyright (C) 2003 Joe English and other parties.
-
-The following terms apply to all files associated with this software
-unless explicitly disclaimed in individual files.
-
-The author(s) hereby grant permission to use, copy, modify, distribute,
-and license this software and its documentation for any purpose, provided
-that existing copyright notices are retained in all copies and that this
-notice is included in any distributions. No written agreement,
-license, or royalty fee is required for any of the authorized uses.
-Modifications to this software may be copyrighted by their authors
-and need not follow the licensing terms described here, provided that
-the new terms are clearly indicated on the first page of each file where
-they apply.
-
-This program is distributed in the hope that it will be useful,
-but WITHOUT ANY WARRANTY; without even the implied warranty of
-MERCHANTABILITY or FITNESS for a PARTICULAR PURPOSE. IN NO EVENT
-shall the AUTHORS of THIS SOFTWARE be LIABLE to ANY PARTY for
-DIRECT, INDIRECT, SPECIAL, INCIDENTAL, or CONSEQUENTIAL DAMAGES
-arising out of the USE of THIS SOFTWARE and its DOCUMENTATION.
diff --git a/ext/tk/sample/tkextlib/tile/demo.rb b/ext/tk/sample/tkextlib/tile/demo.rb
deleted file mode 100644
index 39592b88ec..0000000000
--- a/ext/tk/sample/tkextlib/tile/demo.rb
+++ /dev/null
@@ -1,951 +0,0 @@
-#!/usr/bin/env ruby
-#
-# Demo for 'tile' package.
-#
-require 'tk'
-
-demodir = File.dirname($0)
-Tk::AUTO_PATH.lappend('.', demodir, File.join(demodir, 'themes'))
-
-require 'tkextlib/tile'
-
-def version?(ver)
- TkPackage.vcompare(Tk::Tile.package_version, ver) >= 0
-end
-
-Tk.load_tclscript(File.join(demodir, 'toolbutton.tcl'))
-Tk.load_tclscript(File.join(demodir, 'repeater.tcl'))
-
-# This forces an update of the available packages list. It's required
-# for package names to find the themes in demos/themes/*.tcl
-## Tk.tk_call(TkPackage.unknown_proc, 'Tcl', TkPackage.provide('Tcl'))
-## --> This doesn't work.
-## Because, unknown_proc may be "command + some arguments".
-Tk.ip_eval("#{TkPackage.unknown_proc} Tcl #{TkPackage.provide('Tcl')}")
-
-TkRoot.new{
- title 'Tile demo'
- iconname 'Tile demo'
-}
-
-# The descriptive names of the builtin themes.
-$THEMELIST = [
- ['default', 'Classic'],
- ['alt', 'Revitalized'],
- ['winnative', 'Windows native'],
- ['xpnative', 'XP Native'],
- ['aqua', 'Aqua'],
-]
-
-$V = TkVariable.new_hash(:THEME => 'default',
- :COMPOUND => 'top',
- :CONSOLE => false,
- :MENURADIO1 => 'One',
- :MENUCHECK1 => true,
- :PBMODE => 'determinate',
- :SELECTED => true,
- :CHOICE => 2)
-
-# Add in any available loadable themes.
-TkPackage.names.find_all{|n| n =~ /^tile::theme::/}.each{|pkg|
- name = pkg.split('::')[-1]
- unless $THEMELIST.assoc(name)
- $THEMELIST << [name, Tk.tk_call('string', 'totitle', name)]
- end
-}
-
-# Add theme definition written by ruby
-$RUBY_THEMELIST = []
-begin
- load(File.join(demodir, 'themes', 'kroc.rb'), true)
-rescue
- $RUBY_THEMELIST << ['kroc-rb', 'Kroc (by Ruby)', false]
-else
- $RUBY_THEMELIST << ['kroc-rb', 'Kroc (by Ruby)', true]
-end
-
-def makeThemeControl(parent)
- c = Tk::Tile::Labelframe.new(parent, :text=>'Theme')
- $THEMELIST.each{|theme, name|
- b = Tk::Tile::Radiobutton.new(c, :text=>name, :value=>theme,
- :variable=>$V.ref(:THEME),
- :command=>proc{setTheme(theme)})
- b.grid(:sticky=>:ew)
- unless (TkPackage.names.find{|n| n == "tile::theme::#{theme}"})
- b.state(:disabled)
- end
- }
- $RUBY_THEMELIST.each{|theme, name, available|
- b = Tk::Tile::Radiobutton.new(c, :text=>name, :value=>theme,
- :variable=>$V.ref(:THEME),
- :command=>proc{setTheme(theme)})
- b.grid(:sticky=>:ew)
- b.state(:disabled) unless available
- }
- c
-end
-
-def makeThemeMenu(parent)
- m = TkMenu.new(parent)
- $THEMELIST.each{|theme, name|
- m.add(:radiobutton, :label=>name, :variable=>$V.ref(:THEME),
- :value=>theme, :command=>proc{setTheme(theme)})
- unless (TkPackage.names.find{|n| n == "tile::theme::#{theme}"})
- m.entryconfigure(:end, :state=>:disabled)
- end
- }
- $RUBY_THEMELIST.each{|theme, name, available|
- m.add(:radiobutton, :label=>name, :variable=>$V.ref(:THEME),
- :value=>theme, :command=>proc{setTheme(theme)})
- m.entryconfigure(:end, :state=>:disabled) unless available
- }
- m
-end
-
-def setTheme(theme)
- if (TkPackage.names.find{|n| n == "tile::theme::#{theme}"})
- TkPackage.require("tile::theme::#{theme}")
- end
- Tk::Tile::Style.theme_use(theme)
-end
-
-#
-# Load icons...
-#
-$BUTTONS = ['open', 'new', 'save']
-$CHECKBOXES = ['bold', 'italic']
-$ICON = {}
-
-def loadIcons(file)
- Tk.load_tclscript(file)
- img_data = TkVarAccess.new('ImgData')
- img_data.keys.each{|icon|
- $ICON[icon] = TkPhotoImage.new(:data=>img_data[icon])
- }
-end
-
-loadIcons(File.join(demodir, 'iconlib.tcl'))
-
-#
-# Utilities:
-#
-def foreachWidget(wins, cmd)
- wins.each{|w|
- cmd.call(w)
- foreachWidget(w.winfo_children, cmd)
- }
-end
-
-# sbstub
-# Used as the :command option for a scrollbar,
-# updates the scrollbar's position.
-#
-def sbstub(sb, cmd, num, units = 'units')
- num = TkComm.number(num)
- case cmd.to_s
- when 'moveto'
- sb.set(num, num+0.5)
-
- when 'scroll'
- if units.to_s == 'pages'
- delta = 0.2
- else
- delta = 0.05
- end
- current = sb.get
- sb.set(current[0] + delta * num, current[1] + delta * num)
- end
-end
-
-# ... for debugging:
-TkBindTag::ALL.bind('ButtonPress-3', proc{|w| $W = w}, '%W')
-TkBindTag::ALL.bind('Control-ButtonPress-3', proc{|w| w.set_focus}, '%W')
-
-def showHelp()
- Tk.messageBox(:message=>'No help yet...')
-end
-
-#
-# See toolbutton.tcl.
-TkOption.add('*Toolbar.relief', :groove)
-TkOption.add('*Toolbar.borderWidth', 2)
-
-TkOption.add('*Toolbar.Button.Pad', 2)
-
-$ROOT = Tk.root
-$BASE = $ROOT
-Tk.destroy(*($ROOT.winfo_children))
-
-$TOOLBARS = []
-
-#
-# Toolbar button standard vs. tile comparison:
-#
-def makeToolbars
- #
- # Tile toolbar:
- #
- tb = Tk::Tile::Frame.new($BASE, :class=>'Toolbar')
- $TOOLBARS << tb
- i = 0
- $BUTTONS.each{|icon|
- i += 1
- Tk::Tile::Button.new(tb, :text=>icon, :image=>$ICON[icon],
- :compound=>$V[:COMPOUND],
- :style=>:Toolbutton).grid(:row=>0, :column=>i,
- :sticky=>:news)
- }
- $CHECKBOXES.each{|icon|
- i += 1
- Tk::Tile::Checkbutton.new(tb, :text=>icon, :image=>$ICON[icon],
- :variable=>$V.ref(icon),
- :compound=>$V[:COMPOUND],
- :style=>:Toolbutton).grid(:row=>0, :column=>i,
- :sticky=>:news)
- }
-
- mb = Tk::Tile::Menubutton.new(tb, :text=>'toolbar', :image=>$ICON['file'],
- :compound=>$V[:COMPOUND])
- mb.configure(:menu=>makeCompoundMenu(mb))
- i += 1
- mb.grid(:row=>0, :column=>i, :sticky=>:news)
-
- i += 1
- tb.grid_columnconfigure(i, :weight=>1)
-
- #
- # Standard toolbar:
- #
- tb = TkFrame.new($BASE, :class=>'Toolbar')
- $TOOLBARS << tb
- i = 0
- $BUTTONS.each{|icon|
- i += 1
- TkButton.new(tb, :text=>icon, :image=>$ICON[icon],
- :compound=>$V[:COMPOUND], :relief=>:flat,
- :overrelief=>:raised).grid(:row=>0, :column=>i,
- :sticky=>:news)
- }
- $CHECKBOXES.each{|icon|
- i += 1
- TkCheckbutton.new(tb, :text=>icon, :image=>$ICON[icon],
- :variable=>$V.ref(icon), :compound=>$V[:COMPOUND],
- :indicatoron=>false, :selectcolor=>'', :relief=>:flat,
- :overrelief=>:raised).grid(:row=>0, :column=>i,
- :sticky=>:news)
- }
-
- mb = TkMenubutton.new(tb, :text=>'toolbar', :image=>$ICON['file'],
- :compound=>$V[:COMPOUND])
- mb.configure(:menu=>makeCompoundMenu(mb))
- i += 1
- mb.grid(:row=>0, :column=>i, :sticky=>:news)
-
- i += 1
- tb.grid_columnconfigure(i, :weight=>1)
-end
-
-#
-# Toolbar :compound control:
-#
-def makeCompoundMenu(mb)
- menu = TkMenu.new(mb)
- %w(text image none top bottom left right center).each{|str|
- menu.add(:radiobutton, :label=>Tk.tk_call('string', 'totitle', str),
- :variable=>$V.ref(:COMPOUND), :value=>str,
- :command=>proc{ changeToolbars() })
- }
- menu
-end
-
-makeToolbars()
-
-## CONTROLS
-control = Tk::Tile::Frame.new($BASE)
-
-#
-# Overall theme control:
-#
-makeThemeControl(control).grid(:sticky=>:news, :padx=>6, :ipadx=>6)
-control.grid_rowconfigure(99, :weight=>1)
-
-def changeToolbars
- foreachWidget($TOOLBARS,
- proc{|w|
- begin
- w.compound($V[:COMPOUND])
- rescue
- end
- })
-end
-
-def scrolledWidget(parent, klass, themed, *args)
- if themed
- f = Tk::Tile::Frame.new(parent)
- t = klass.new(f, *args)
- vs = Tk::Tile::Scrollbar.new(f)
- hs = Tk::Tile::Scrollbar.new(f)
- else
- f = TkFrame.new(parent)
- t = klass.new(f, *args)
- vs = TkScrollbar.new(f)
- hs = TkScrollbar.new(f)
- end
- t.yscrollbar(vs)
- t.xscrollbar(hs)
-
- TkGrid.configure(t, vs, :sticky=>:news)
- TkGrid.configure(hs, 'x', :sticky=>:news)
- TkGrid.rowconfigure(f, 0, :weight=>1)
- TkGrid.columnconfigure(f, 0, :weight=>1)
-
- [f, t]
-end
-
-#
-# Notebook demonstration:
-#
-def makeNotebook
- nb = Tk::Tile::Notebook.new($BASE, :padding=>6)
- nb.enable_traversal
- client = Tk::Tile::Frame.new(nb)
- nb.add(client, :text=>'Demo', :underline=>0)
- nb.select(client)
-
- scales = Tk::Tile::Frame.new(nb)
- nb.add(scales, :text=>'Scales')
- combo = Tk::Tile::Frame.new(nb)
- nb.add(combo, :text=>'Combobox', :underline=>7)
- tree = Tk::Tile::Frame.new(nb)
- nb.add(tree, :text=>'Tree')
- others = Tk::Tile::Frame.new(nb)
- nb.add(others, :text=>'Others', :underline=>4)
-
- [nb, client, scales, combo, tree, others]
-end
-
-nb, client, scales, combo, tree, others = makeNotebook()
-
-#
-# Side-by side check, radio, and menu button comparison:
-#
-def fillMenu(menu)
- %w(above below left right flush).each{|dir|
- menu.add(:command, :label=>Tk.tk_call('string', 'totitle', dir),
- :command=>proc{ menu.winfo_parent.direction(dir) })
- }
- menu.add(:cascade, :label=>'Submenu', :menu=>(submenu = TkMenu.new(menu)))
- submenu.add(:command, :label=>'Subcommand 1')
- submenu.add(:command, :label=>'Subcommand 2')
- submenu.add(:command, :label=>'Subcommand 3')
-
- menu.add(:separator)
- menu.add(:command, :label=>'Quit', :command=>proc{Tk.root.destroy})
-end
-
-l = Tk::Tile::Labelframe.new(client, :text=>'Themed', :padding=>6)
-r = TkLabelframe.new(client, :text=>'Standard', :padx=>6, :pady=>6)
-
-## Styled frame
-cb = Tk::Tile::Checkbutton.new(l, :text=>'Checkbutton',
- :variable=>$V.ref(:SELECTED), :underline=>2)
-rb1 = Tk::Tile::Radiobutton.new(l, :text=>'One', :variable=>$V.ref(:CHOICE),
- :value=>1, :underline=>0)
-rb2 = Tk::Tile::Radiobutton.new(l, :text=>'Two', :variable=>$V.ref(:CHOICE),
- :value=>2)
-rb3 = Tk::Tile::Radiobutton.new(l, :text=>'Three',
- :variable=>$V.ref(:CHOICE),
- :value=>3, :underline=>0)
-btn = Tk::Tile::Button.new(l, :text=>'Button', :underline=>0)
-
-mb = Tk::Tile::Menubutton.new(l, :text=>'Menubutton', :underline=>2)
-#m = TkMenu.new(mb)
-#mb.menu(m)
-#fillMenu(m)
-
-$entryText = TkVariable.new('Entry widget')
-e = Tk::Tile::Entry.new(l, :textvariable=>$entryText)
-e.selection_range(6, :end)
-
-ltext_f, ltext = scrolledWidget(l, TkText, true,
- :width=>12, :height=>5, :wrap=>:none)
-# NOTE TO MAINTAINERS:
-# The checkbuttons are -sticky ew / -expand x on purpose:
-# it demonstrates one of the differences between TCheckbuttons
-# and standard checkbuttons.
-#
-Tk.grid(cb, :sticky=>:ew)
-Tk.grid(rb1, :sticky=>:ew)
-Tk.grid(rb2, :sticky=>:ew)
-Tk.grid(rb3, :sticky=>:ew)
-Tk.grid(btn, :sticky=>:ew, :padx=>2, :pady=>2)
-Tk.grid(mb, :sticky=>:ew, :padx=>2, :pady=>2)
-Tk.grid(e, :sticky=>:ew, :padx=>2, :pady=>2)
-Tk.grid(ltext_f, :sticky=>:news)
-
-TkGrid.columnconfigure(l, 0, :weight=>1)
-TkGrid.rowconfigure(l, 7, :weight=>1) # text widget (grid is a PITA)
-
-## Orig frame
-cb = TkCheckbutton.new(r, :text=>'Checkbutton', :variable=>$V.ref(:SELECTED))
-rb1 = TkRadiobutton.new(r, :text=>'One',
- :variable=>$V.ref(:CHOICE), :value=>1)
-rb2 = TkRadiobutton.new(r, :text=>'Two', :variable=>$V.ref(:CHOICE),
- :value=>2, :underline=>1)
-rb3 = TkRadiobutton.new(r, :text=>'Three',
- :variable=>$V.ref(:CHOICE), :value=>3)
-btn = TkButton.new(r, :text=>'Button')
-
-mb = TkMenubutton.new(r, :text=>'Menubutton', :underline=>3, :takefocus=>true)
-m = TkMenu.new(mb)
-mb.menu(m)
-$V[:rmbIndicatoron] = mb.indicatoron
-m.add(:checkbutton, :label=>'Indicator?', #'
- :variable=>$V.ref(:rmbIndicatoron),
- :command=>proc{mb.indicatoron($V[:rmbIndicatoron])})
-m.add(:separator)
-fillMenu(m)
-
-e = TkEntry.new(r, :textvariable=>$entryText)
-
-rtext_f, rtext = scrolledWidget(r, TkText, false,
- :width=>12, :height=>5, :wrap=>:none)
-
-Tk.grid(cb, :sticky=>:ew)
-Tk.grid(rb1, :sticky=>:ew)
-Tk.grid(rb2, :sticky=>:ew)
-Tk.grid(rb3, :sticky=>:ew)
-Tk.grid(btn, :sticky=>:ew, :padx=>2, :pady=>2)
-Tk.grid(mb, :sticky=>:ew, :padx=>2, :pady=>2)
-Tk.grid(e, :sticky=>:ew, :padx=>2, :pady=>2)
-Tk.grid(rtext_f, :sticky=>:news)
-
-TkGrid.columnconfigure(l, 0, :weight=>1)
-TkGrid.rowconfigure(l, 7, :weight=>1) # text widget (grid is a PITA)
-
-Tk.grid(l, r, :sticky=>:news, :padx=>6, :pady=>6)
-TkGrid.rowconfigure(client, 0, :weight=>1)
-TkGrid.columnconfigure(client, [0, 1], :weight=>1)
-
-#
-# Add some text to the text boxes:
-#
-msgs = [
-"The cat crept into the crypt, crapped and crept out again",
-"Peter Piper picked a peck of pickled peppers",
-"How much wood would a woodchuck chuck if a woodchuck could chuck wood",
-"He thrusts his fists against the posts and still insists he sees the ghosts",
-"Who put the bomb in the bom-b-bom-b-bom,",
-"Is this your sister's sixth zither, sir?",
-"Who put the ram in the ramalamadingdong?",
-"I am not the pheasant plucker, I'm the pheasant plucker's mate."
-]
-
-nmsgs = msgs.size
-(0...50).each{|n|
- msg = msgs[n % nmsgs]
- ltext.insert(:end, "#{n}: #{msg}\n")
- rtext.insert(:end, "#{n}: #{msg}\n")
-}
-#
-# Scales and sliders pane:
-#
-l = Tk::Tile::Labelframe.new(scales, :text=>'Themed', :padding=>6)
-r = TkLabelframe.new(scales, :text=>'Standard', :padx=>6, :pady=>6)
-
-if version?('0.6')
-
- # thremed frame
- scale = Tk::Tile::Scale.new(l, :orient=>:horizontal, :from=>0, :to=>100,
- :variable=>$V.ref(:SCALE))
- vscale = Tk::Tile::Scale.new(l, :orient=>:vertical, :from=>0, :to=>100,
- :variable=>$V.ref(:VSCALE))
- progress = Tk::Tile::Progressbar.new(l, :orient=>:horizontal, :maximum=>100)
- vprogress = Tk::Tile::Progressbar.new(l, :orient=>:vertical, :maximum=>100)
-
- if true
- def progress.inverted(w, value)
- w.value(w.maximum - value)
- end
- scale.command {|value| progress.value(value)}
- vscale.command {|value| progress.inverted(vprogress, value) }
- else
- # This would also work, but the Tk scale widgets
- # in the right hand pane cause some interference when
- # in autoincrement/indeterminate mode.
- #
- progress.variable $V.ref(:SCALE)
- vprogress.variable $V.ref(:VSCALE)
- end
-
- scale.set(50)
- vscale.set(50)
-
- lmode = Tk::Tile::Label.new(l, :text=>'Progress bar mode')
- pbmode0 = Tk::Tile::Radiobutton.new(l, :variable=>$V.ref(:PBMODE),
- :text=>'determinate', :value=>'determinate',
- :command=>proc{pbMode(progress, vprogress)})
- pbmode1 = Tk::Tile::Radiobutton.new(l, :variable=>$V.ref(:PBMODE),
- :text=>'indeterminate', :value=>'indeterminate',
- :command=>proc{pbMode(progress, vprogress)})
- def pbMode(progress, vprogress)
- progress.mode $V[:PBMODE]
- vprogress.mode $V[:PBMODE]
- end
-
- start = Tk::Tile::Button.new(l, :text=>"Start",
- :command=>proc{pbStart(progress, vprogress)})
- def pbStart(progress, vprogress)
- $V[:PBMODE] = 'indeterminate'; pbMode(progress, vprogress)
- progress.start 10
- vprogress.start
- end
-
- stop = Tk::Tile::Button.new(l, :text=>'Stop',
- :command=>proc{pbStop(progress, vprogress)})
- def pbStop(progress, vprogress)
- progress.stop
- vprogress.stop
- end
-
- Tk.grid(scale, :columnspan=>2, :sticky=>'ew')
- Tk.grid(progress, :columnspan=>2, :sticky=>'ew')
- Tk.grid(vscale, vprogress, :sticky=>'nws')
-
- Tk.grid(lmode, :sticky=>'we', :columnspan=>2)
- Tk.grid(pbmode0, :sticky=>'we', :columnspan=>2)
- Tk.grid(pbmode1, :sticky=>'we', :columnspan=>2)
- Tk.grid(start, :sticky=>'we', :columnspan=>2)
- Tk.grid(stop, :sticky=>'we', :columnspan=>2)
-
- l.grid_columnconfigure(0, :weight=>1)
- l.grid_columnconfigure(1, :weight=>1)
- l.grid_rowconfigure(99, :weight=>1)
-
- # standard frame
- TkScale.new(r, :orient=>:horizontal, :from=>0, :to=>100,
- :variable=>$V.ref(:SCALE)).grid(:sticky=>'news')
- TkScale.new(r, :orient=>:vertical, :from=>0, :to=>100,
- :variable=>$V.ref(:VSCALE)).grid(:sticky=>'nws')
-
- r.grid_columnconfigure(0, :weight=>1)
- r.grid_columnconfigure(1, :weight=>1)
- r.grid_rowconfigure(99, :weight=>1)
-
-else # tile 0.5 or earlier
-
- # themed frame
- scale = Tk::Tile::Scale.new(l, :variable=>$V.ref(:SCALE),
- :orient=>:horizontal, :from=>0, :to=>100)
- vscale = Tk::Tile::Scale.new(l, :variable=>$V.ref(:VSCALE),
- :orient=>:vertical, :from=>-25, :to=>25)
-
- progress = Tk::Tile::Progress.new(l,
- :orient=>:horizontal, :from=>0, :to=>100)
- vprogress = Tk::Tile::Progress.new(l,
- :orient=>:vertical, :from=>-25, :to=>25)
-
- if true
- scale.command{|value| progress.set(value)}
- vscale.command{|value| vprogress.set(value)}
- else # this would also work. (via TkVariable#trace)
- v1 = scale.variable
- v2 = vscale.variable
- v1.trace('w', proc{ progress.set(v1.value) })
- v2.trace('w', proc{ vprogress.set(v2.value) })
- end
-
- Tk.grid(scale, :columnspan=>2, :sticky=>:ew)
- Tk.grid(progress, :columnspan=>2, :sticky=>:ew)
- Tk.grid(vscale, vprogress, :sticky=>:nws)
- TkGrid.columnconfigure(l, 0, :weight=>1)
- TkGrid.columnconfigure(l, 1, :weight=>1)
-
- # standard frame
- TkScale.new(r, :variable=>$V.ref(:SCALE),
- :orient=>:horizontal, :from=>0, :to=>100).grid(:sticky=>'news')
- TkScale.new(r, :variable=>$V.ref(:VSCALE),
- :orient=>:vertical, :from=>-25, :to=>25).grid(:sticky=>'nws')
-
- TkGrid.columnconfigure(r, 0, :weight=>1)
- TkGrid.columnconfigure(r, 1, :weight=>1)
-end
-
-# layout frames
-Tk.grid(l, r, :sticky=>'nwes', :padx=>6, :pady=>6)
-scales.grid_columnconfigure(0, :weight=>1)
-scales.grid_columnconfigure(1, :weight=>1)
-scales.grid_rowconfigure(0, :weight=>1)
-
-#
-# Command box:
-#
-cmd = Tk::Tile::Frame.new($BASE)
-b_close = Tk::Tile::Button.new(cmd, :text=>'Close',
- :underline=>0, :default=>:normal,
- :command=>proc{Tk.root.destroy})
-b_help = Tk::Tile::Button.new(cmd, :text=>'Help', :underline=>0,
- :default=>:normal, :command=>proc{showHelp()})
-Tk.grid('x', b_close, b_help, :pady=>[6, 4], :padx=>4)
-TkGrid.columnconfigure(cmd, 0, :weight=>1)
-
-#
-# Set up accelerators:
-#
-$ROOT.bind('KeyPress-Escape', proc{Tk.event_generate(b_close, '<Invoke>')})
-$ROOT.bind('<Help>', proc{Tk.event_generate(b_help, '<Invoke>')})
-Tk::Tile::KeyNav.enableMnemonics($ROOT)
-Tk::Tile::KeyNav.defaultButton(b_help)
-
-Tk.grid($TOOLBARS[0], '-', :sticky=>:ew)
-Tk.grid($TOOLBARS[1], '-', :sticky=>:ew)
-Tk.grid(control, nb, :sticky=>:news)
-Tk.grid(cmd, '-', :sticky=>:ew)
-TkGrid.columnconfigure($ROOT, 1, :weight=>1)
-TkGrid.rowconfigure($ROOT, 2, :weight=>1)
-
-#
-# Add a menu
-#
-menu = TkMenu.new($BASE)
-$ROOT.menu(menu)
-m_file = TkMenu.new(menu, :tearoff=>0)
-menu.add(:cascade, :label=>'File', :underline=>0, :menu=>m_file)
-m_file.add(:command, :label=>'Open', :underline=>0,
- :compound=>:left, :image=>$ICON['open'])
-m_file.add(:command, :label=>'Save', :underline=>0,
- :compound=>:left, :image=>$ICON['save'])
-m_file.add(:separator)
-m_f_test = TkMenu.new(menu, :tearoff=>0)
-m_file.add(:cascade, :label=>'Test submenu', :underline=>0, :menu=>m_f_test)
-m_file.add(:checkbutton, :label=>'Text check', :underline=>5,
- :variable=>$V.ref(:MENUCHECK1))
-m_file.insert(:end, :separator)
-
-if Tk.windowingsystem != 'x11'
- TkConsole.create
- m_file.insert(:end, :checkbutton, :label=>'Console', :underline=>5,
- :variable=>$V.ref(:CONSOLE), :command=>proc{toggle_console()})
- def toggle_console
- if TkComm.bool($V[:CONSOLE])
- TkConsole.show
- else
- TkConsole.hide
- end
- end
-end
-
-m_file.add(:command, :label=>'Exit', :underline=>1,
- :command=>proc{Tk.event_generate(b_close, '<Invoke>')})
-
-%w(One Two Three Four).each{|lbl|
- m_f_test.add(:radiobutton, :label=>lbl, :variable=>$V.ref(:MENURADIO1))
-}
-
-# Add Theme menu.
-#
-menu.add(:cascade, :label=>'Theme', :underline=>3,
- :menu=>makeThemeMenu(menu))
-
-setTheme($V[:THEME])
-
-#
-# Combobox demo pane:
-#
-values = %w(list abc def ghi jkl mno pqr stu vwx yz)
-2.times {|i|
- cb = Tk::Tile::Combobox.new(
- combo, :values=>values, :textvariable=>$V.ref(:COMBO))
- cb.pack(:side=>:top, :padx=>2, :pady=>2, :expand=>false, :fill=>:x)
- if i == 1
- cb.state :readonly
- begin
- cb.current = 3 # ignore if unsupported (tile0.4)
- rescue
- end
- end
-}
-
-#
-# Treeview widget demo pane:
-#
-if version?('0.5')
-
- treeview = nil # avoid 'undefined' error
- scrollbar = Tk::Tile::Scrollbar.new(tree,
- :command=>proc{|*args| treeview.yview(*args)})
- treeview = Tk::Tile::Treeview.new(tree, :columns=>%w(Class), :padding=>4,
- :yscrollcommand=>proc{|*args| scrollbar.set(*args)})
-
- Tk.grid(treeview, scrollbar, :sticky=>'news')
- tree.grid_columnconfigure(0, :weight=>1)
- tree.grid_rowconfigure(0, :weight=>1)
- tree.grid_propagate(0)
-
- # Add initial tree node:
- # Later nodes will be added in <<TreeviewOpen>> binding.
- treeview.insert('', 0, :id=>'.', :text=>'Main Window', :open=>false,
- :values=>[TkWinfo.classname('.')])
- treeview.headingconfigure('#0', :text=>'Widget')
- treeview.headingconfigure('Class', :text=>'Class')
- treeview.bind('<TreeviewOpen>', proc{fillTree(treeview)})
-
- def fillTree(treeview)
- id = treeview.focus_item
- unless TkWinfo.exist?(id)
- treeview.delete(id)
- end
- # Replace tree item children with current list of child windows.
- treeview.delete(treeview.children(id))
- for child in TkWinfo.children(id)
- treeview.insert(id, :end, :id=>child, :text=>TkWinfo.appname(child),
- :open=>false, :values=>[TkWinfo.classname(child)])
- unless TkWinfo.children(child).empty?
- # insert dummy child to show [+] indicator
- treeview.insert(child, :end)
- end
- end
- end
-
-else
- Tk::Tile::Label.new(tree,
- :text=>'Treeview is supported on tile 0.5 or later...').pack
-end
-
-#
-# Other demos:
-#
-$Timers = {:StateMonitor=>nil, :FocusMonitor=>nil}
-
-msg = TkMessage.new(others, :aspect=>200)
-
-$Desc = {}
-
-showDescription = TkBindTag.new
-showDescription.bind('Enter', proc{|w| msg.text($Desc[w.path])}, '%W')
-showDescription.bind('Leave', proc{|w| msg.text('')}, '%W')
-
-[
- [ :trackStates, "Widget states...",
- "Display/modify widget state bits" ],
-
- [ :scrollbarResizeDemo, "Scrollbar resize behavior...",
- "Shows how Tile and standard scrollbars differ when they're sized too large" ],
-
- [ :trackFocus, "Track keyboard focus..." ,
- "Display the name of the widget that currently has focus" ],
-
- [ :repeatDemo, "Repeating buttons...",
- "Demonstrates custom classes (see demos/repeater.tcl)" ]
-
-].each{|demo_cmd, label, description|
- b = Tk::Tile::Button.new(others, :text=>label,
- :command=>proc{ self.__send__(demo_cmd) })
- $Desc[b.path] = description
- b.bindtags <<= showDescription
-
- b.pack(:side=>:top, :expand=>false, :fill=>:x, :padx=>6, :pady=>6)
-}
-
-msg.pack(:side=>:bottom, :expand=>true, :fill=>:both)
-
-
-#
-# Scrollbar resize demo:
-#
-$scrollbars = nil
-
-def scrollbarResizeDemo
- if $scrollbars
- begin
- $scrollbars.destroy
- rescue
- end
- end
- $scrollbars = TkToplevel.new(:title=>'Scrollbars', :geometry=>'200x200')
- f = TkFrame.new($scrollbars, :height=>200)
- tsb = Tk::Tile::Scrollbar.new(f, :command=>proc{|*args| sbstub(tsb, *args)})
- sb = TkScrollbar.new(f, :command=>proc{|*args| sbstub(sb, *args)})
- Tk.grid(tsb, sb, :sticky=>:news)
-
- sb.set(0, 0.5) # prevent backwards-compatibility mode for old SB
-
- f.grid_columnconfigure(0, :weight=>1)
- f.grid_columnconfigure(1, :weight=>1)
- f.grid_rowconfigure(0, :weight=>1)
-
- f.pack(:expand=>true, :fill=>:both)
-end
-
-#
-# Track focus demo:
-#
-$FocusInf = TkVariable.new_hash
-$focus = nil
-
-def trackFocus
- if $focus
- begin
- $focus.destroy
- rescue
- end
- end
- $focus = TkToplevel.new(:title=>'Keyboard focus')
- i = 0
- [
- ["Focus widget:", :Widget],
- ["Class:", :WidgetClass],
- ["Next:", :WidgetNext],
- ["Grab:", :Grab],
- ["Status:", :GrabStatus]
- ].each{|label, var_index|
- Tk.grid(Tk::Tile::Label.new($focus, :text=>label, :anchor=>:e),
- Tk::Tile::Label.new($focus,
- :textvariable=>$FocusInf.ref(var_index),
- :width=>40, :anchor=>:w, :relief=>:groove),
- :sticky=>:ew)
- i += 1
- }
- $focus.grid_columnconfigure(1, :weight=>1)
- $focus.grid_rowconfigure(i, :weight=>1)
-
- $focus.bind('Destroy', proc{Tk.after_cancel($Timers[:FocusMonitor])})
- focusMonitor
-end
-
-def focusMonitor
- $FocusInf[:Widget] = focus_win = Tk.focus
- if focus_win
- $FocusInf[:WidgetClass] = focus_win.winfo_classname
- $FocusInf[:WidgetNext] = Tk.focus_next(focus_win)
- else
- $FocusInf[:WidgetClass] = $FocusInf[:WidgetNext] = ''
- end
-
- $FocusInf[:Grab] = grab_wins = Tk.current_grabs
- unless grab_wins.empty?
- $FocusInf[:GrabStatus] = grab_wins[0].grab_status
- else
- $FocusInf[:GrabStatus] = ''
- end
-
- $Timers[:FocusMonitor] = Tk.after(200, proc{ focusMonitor() })
-end
-
-#
-# Widget state demo:
-#
-$Widget = TkVariable.new
-
-TkBindTag::ALL.bind('Control-Shift-ButtonPress-1',
- proc{|w|
- $Widget.value = w
- updateStates()
- Tk.callback_break
- }, '%W')
-$states_list = %w(active disabled focus pressed selected
- background indeterminate invalid default)
-$states_btns = {}
-$states = nil
-
-$State = TkVariable.new_hash
-
-def trackStates
- if $states
- begin
- $state.destroy
- rescue
- end
- end
- $states = TkToplevel.new(:title=>'Widget states')
-
- l_inf = Tk::Tile::Label.new($states, :text=>"Press Control-Shift-Button-1 on any widget")
-
- l_lw = Tk::Tile::Label.new($states, :text=>'Widget:',
- :anchor=>:e, :relief=>:groove)
- l_w = Tk::Tile::Label.new($states, :textvariable=>$Widget,
- :anchor=>:w, :relief=>:groove)
-
- Tk.grid(l_inf, '-', :sticky=>:ew, :padx=>6, :pady=>6)
- Tk.grid(l_lw, l_w, :sticky=>:ew)
-
- $states_list.each{|st|
- cb = Tk::Tile::Checkbutton.new($states, :text=>st,
- :variable=>$State.ref(st),
- :command=>proc{ changeState(st) })
- $states_btns[st] = cb
- Tk.grid('x', cb, :sticky=>:nsew)
- }
-
- $states.grid_columnconfigure(1, :weight=>1)
-
- f_cmd = Tk::Tile::Frame.new($states)
- Tk.grid('x', f_cmd, :sticky=>:nse)
-
- b_close = Tk::Tile::Button.new(f_cmd, :text=>'Close',
- :command=>proc{ $states.destroy })
- Tk.grid('x', b_close, :padx=>4, :pady=>[6,4])
- f_cmd.grid_columnconfigure(0, :weight=>1)
-
- $states.bind('KeyPress-Escape', proc{Tk.event_generate(b_close, '<Invoke>')})
-
- $states.bind('Destroy', proc{Tk.after_cancel($Timers[:StateMonitor])})
- stateMonitor()
-end
-
-def stateMonitor
- updateStates() if $Widget.value != ''
- $Timers[:StateMonitor] = Tk.after(200, proc{ stateMonitor() })
-end
-
-def updateStates
- $states_list.each{|st|
- begin
- $State[st] = $Widget.window.instate(st)
- rescue
- $states_btns[st].state('disabled')
- else
- $states_btns[st].state('!disabled')
- end
- }
-end
-
-def changeState(st)
- if $Widget.value != ''
- if $State.bool_element(st)
- $Widget.window.state(st)
- else
- $Widget.window.state("!#{st}")
- end
- end
-end
-
-#
-# Repeating buttons demo:
-#
-def repeatDemo
- if defined?($repeatDemo) && $repeatDemo.exist?
- $repeatDemo.deiconify; return
- end
- $repeatDemo = TkToplevel.new(:title=>'Repeating button')
-
- f = Tk::Tile::Frame.new($repeatDemo)
- b = Tk::Tile::Button.new(f, :class=>'Repeater', :text=>'Press and hold')
- if version?('0.6')
- p = Tk::Tile::Progressbar.new(f, :orient=>:horizontal, :maximum=>10)
- else # progressbar is not supported
- p = Tk::Tile::Progress.new(f, :orient=>:horizontal, :from=>0, :to=>10)
- def p.step
- i = self.get + 1
- i = self.from if i > self.to
- self.set(i)
- end
- end
- b.command {p.step}
-
- b.pack(:side=>:left, :expand=>false, :fill=>:none, :padx=>6, :pady=>6)
- p.pack(:side=>:right, :expand=>true, :fill=>:x, :padx=>6, :pady=>6)
- f.pack(:expand=>true, :fill=>:both)
-end
-
-Tk.mainloop
diff --git a/ext/tk/sample/tkextlib/tile/iconlib.tcl b/ext/tk/sample/tkextlib/tile/iconlib.tcl
deleted file mode 100644
index 9a93ece504..0000000000
--- a/ext/tk/sample/tkextlib/tile/iconlib.tcl
+++ /dev/null
@@ -1,110 +0,0 @@
-array set ImgData {
-bold {R0lGODlhEAAQAJEAANnZ2QAAAP///////yH5BAEAAAAALAAAAAAQABAAAAI6hI+py60U3wj+
-RYQFJYRvEWFBCeFbRFhQQvhG8YPgX0RYUEL4FhEWlBC+RYQFJYQPFN8IPqYut/8hBQA7}
-copy {R0lGODlhEAAQAJEAANnZ2QAAAP///wAAhCH5BAEAAAAALAAAAAAQABAAAAJUhI8JFJ/gY4iI
-UEL4FyIiFIXgW0iEUDgfACBI9pzMAAGRiIghWSMDECR7JEKGtkFIRFBG+TIQKDQxtgzcDcmX
-IfgwQrFlCD4MyZch+EDzj+Bj6mYBADs=}
-cut {R0lGODlhEAAQAJEAANnZ2QAAAAAAhP///yH5BAEAAAAALAAAAAAQABAAAAJFhI+pcUHwEeIi
-E0gACIKPEAFBIXy0gMg8EhM+YmQiKSL4eAIiJMI/EQEhQGYGYiQIQAg+iAkIATIzECMBIgT/
-RBARERlSADs=}
-dragfile {R0lGODlhGAAYAKIAANnZ2TMzM////wAAAJmZmf///////////yH5BAEAAAAALAAAAAAYABgA
-AAPACBi63IqgC4GiyxwogaAbKLrMgSKBoBoousyBogEACIGiyxwoKgGAECI4uiyCExMTOACB
-osuNpDoAGCI4uiyCIkREOACBosutSDoAgSI4usyCIjQAGCi63Iw0ACEoOLrMgiI0ABgoutyM
-NAAhKDi6zIIiNAAYKLrcjDQAISg4usyCIjQAGCi63Iw0AIGiiqPLIyhCA4CBosvNSAMQKKo4
-ujyCIjQAGCi63Iw0AIGiy81IAxCBpMu9GAMAgKPL3QgJADs=}
-dragicon {R0lGODlhGAAYALMAANnZ2TMzM/////8zM8zMzGYAAAAAAJmZmQCZMwAzZgCZzGZmZv//////
-/////////yH5BAEAAAAALAAAAAAYABgAAAT/EMAgJ60SAjlBgEJOSoMIEMgZoJCT0iADBFIG
-KOSkNMwAAABhwiHnIEKIIIQQAQIZhBBwyDmKEMIEE0yABoAghIBDzlGEENDIaQAIQgg45BwF
-CinPOccAECYcUiKEEBFCiHPgMQAEIcQYYyABBUGIQCHlMQCEScZAAhKEEApCECGOARAEIQQp
-BRGIpAyCJCGOASBAISdEcqJAVBLiGABggELOAJGUKyiVhDgGABigkJMEhNAKSqkEhTgGgCCl
-FCQEGIJSSiUhjgEgQCEnJVBJmYQ4BoAAhZyTQCVnEuIYAAIUckoCk5xSiGMACFDISSs9BoBg
-rRXQMQAEKOSklR4DEUAI8MhJ6wwGAACgkZNWCkAEADs=}
-error {R0lGODlhIAAgAKIAANnZ2YQAAP8AAISEhP///////////////yH5BAEAAAAALAAAAAAgACAA
-AAP/CLoMGLqKoMvtGIqiqxEYCLrcioGiyxwIusyBgaLLLRiBoMsQKLrcjYGgu4Giy+2CAkFX
-A0WX2wXFIOgGii7trkCEohsDCACBoktEKLpKhISiGwAIECiqSKooukiqKKoxgACBooukKiIo
-SKooujGDECi6iqQqsopEV2MQAkV3kXQZRXdjEAJFl5F0FUWXY3ACRZcFSRdFlyVwJlB0WZB0
-UXRZAmcCRZeRdBVFl2NwAkV3kXQZRXdjcAJFV5FURVaR6GoMDgSKLpKqiKAgqaLoxgwOBIoq
-kiqKLpIqimrM4ECg6BIRiq4SIaHoxgyCBoou7a5AhKIbMzgAAIGiy+2CTWJmBhAAAkWX2wXF
-zCDoBooud2PMDIKuRqDocgtGzMwg6O4Eii5z4Kgi6DIMhqLoagQGjiqCLvPgYOgqji6CLrfi
-6DIj6HI7jq4i6DIkADs=}
-file {R0lGODlhCwANAJEAANnZ2QAAAP///////yH5BAEAAAAALAAAAAALAA0AAAIyhI9G8Q0AguSH
-AMQdxQgxEyEFQfItICQokYgEBMm3gBCKLRIQJN8CQii2SECQfAug+FgAOw==}
-folder {R0lGODlhEAANAKIAANnZ2YSEhMbGxv//AP///wAAAP///////yH5BAEAAAAALAAAAAAQAA0A
-AANjCIqhiqDLITgyEgi6GoIjIyMYugCBpMsaWBA0giMjIzgyUYBBMjIoIyODEgVBODIygiMj
-E1gQJIMyMjIoI1GAQSMjODIyghMFQSgjI4MyMhJYEDSCIyMjODJRgKHLXAiApcucADs=}
-hourglass {R0lGODlhIAAgAKIAANnZ2YAAAAAAAP8AAP///8DAwICAgP///yH5BAEAAAAALAAAAAAgACAA
-AAPZCLrc/jDKSau9OGcUuqyCoMvNGENVhaMrCLrcjaLLgqDL7WhFVIVVZoKgy+1oRUSFVWaC
-oMvtaEVEhVVmgqDL7WhFRIVVZoKgy+1oVVaCJWaCoMvtgKxISrBMEHS5fZEVSRkKgi63NzIq
-EwRdbndkVCYIutzeyIqqDAVBl9sXWRFJYZkg6HI7ICsiKqwyEwRdbkcrIhKsMhMEXW5HKyIp
-lDITBF1uRysyEiwxEwRdbkcrIyuUEhMEXW5H0WVB0OVujKGqwtEVBF1uRtHlRdDl9odRTlrt
-xRmjBAA7}
-info {R0lGODlhIAAgAKIAANnZ2YSEhMbGxv///wAA/wAAAP///////yH5BAEAAAAALAAAAAAgACAA
-AAP/CLoMGLqKoMvtGCo4uhKBgaDLDRghOLqsghEIuryBgqPLPSiBoMsQOLojhEQkOLpTCLob
-OLqKpIujq4WgC4Gju0i6OLpbCKohOLorhEQkOLorhaAQOLrc3qgCIARHl9sbSQUEji4j6RKO
-Lk9hQODosiKp4ujyFIbi6LIiqeLo8hSG4uiyIqni6PIUhuLosiKp4ujyFIYKji4PkiqOLkth
-BASOLg+SKo4uV2AEhODoMpIqju5KYShA4Ogqku7i6E4FRgAAYOHocvugiohAUC0cXe7GiohA
-0IUSHF3uQamICATdrULB0WUVrIqIQNBlCCwVHF2pwsJQRdDlDYyoKsHRPMLQDQRdbsDQqBmc
-wlBF0OV2jJqZwggEXW5vVDMVgaDL7Y5qKgJBl9sfVUUg6HL7AxSKoMvtr1AEgi5DAgA7}
-italic {R0lGODlhEAAQAJEAANnZ2QAAAP///////yH5BAEAAAAALAAAAAAQABAAAAIrhI+py+1A4hN8
-hIjINBITPlpEZBqJCR8tIjKNxISPFhGZQOITfExdbv9FCgA7}
-new {R0lGODlhEAAQAJEAANnZ2QAAAP///////yH5BAEAAAAALAAAAAAQABAAAAJFhI95FN8IvgXJ
-jyD4ECQ/JAh+kPyICIIdJP+CYAfJvyDYQfIvCHaQ/AuCHST/gmAHyb8g2EHyLwh2kPwLgk3x
-MQg+pu4WADs=}
-open {R0lGODlhEAAQAKIAANnZ2QAAAP//AP///4SEAP///////////yH5BAEAAAAALAAAAAAQABAA
-AANZCLrczigUQZc1EDQgEHSZAwMgIhB0NQIDQkYwdANBNUZwZGQEJxBUQwZlZGRQAkE1RnAE
-Q5dVcCSQdDcAYySQdDcAISSQdDcAASKQdDcAAQBDlwNBl9sfApQAOw==}
-openfold {R0lGODlhEAANAKIAANnZ2YSEhP///8bGxv//AAAAAP///////yH5BAEAAAAALAAAAAAQAA0A
-AANgCIqhiqDLgaIaCLoagkNDIxi6AIFCQ0M4KKpRgCFDQzg0NIQThaHLSxgVKLochRMVMkhD
-Q4M0VBFYEDKEQ0NDOFFRgCE0NEhDQ4MVBRAoNDSEQ0NRWAAYuqyFBQBYurwJADs=}
-overstrike {R0lGODlhEAAQAJEAANnZ2QAAAP///////yH5BAEAAAAALAAAAAAQABAAAAI3hI+py80Uh+Aj
-RFhQCP8iMILgWwRGEHyLwAiCbxEYQfCB4iPBhwiMIPgXYREEHyEiguBj6nI7FQA7}
-palette {R0lGODlhEAAQAKIAANnZ2QAAAP//AP////8A/4QAhP8AAAD//yH5BAEAAAAALAAAAAAQABAA
-AANtCLrcjqGBoMsRKCMTgaALMSgDAYMSCKoxgAFBITgSAIAQEhUIARCAEgAQOBAwghMQEwga
-MoIjIxAIEgCAEBEyKBAgg4GgGxAIYTGCgaALcRgQIIGgCwEYICODgaALITgyEoGguxiqCLrc
-/lChBAA7}
-passwd {R0lGODlhIAAgAMQAANnZ2QAAAICAgICAAP///7CwsMDAwMjIAPjIAOjo6Pj4AODg4HBwcMj4
-ANjY2JiYANDQ0MjIyPj4yKCgoMiYAMjImDAwAMjIMJiYmJCQkP//////////////////////
-/yH5BAEAAAAALAAAAAAgACAAAAX/ICCOIhiIIgiII1maZSCMQnCeJyAIQiAIAiAMwxCcJwkk
-EAQRCIUwGMSBDEEAAuJIlgKRJEEgGAMRBIGiDENQlqNAJAsYCEwgEEEgBAHSIEMAAuJIAgKR
-LEsgGEMgCEJgBMqhHENQlgJILMsSCMRABEFgGAESHMcRgIA4kgKxOIsTBAOhKAITKEGDHMhD
-kqIAEqAjisJAgIooBkpwNMcTgIA4jgLhOBAkEAOhKIoSKEGDIMcTkKQICgQEQQIxEIqiBEpw
-IMdxPAEIiCMJCEQUMUQ0EIqiHIfSIM3xBGUpCiABCUQyEMqhHMiBHMjxBCAgjuQoEAKxRANB
-HMqhHM1x/zxDUJajQIACsUTDQBAEIR3IcQRDAALiSIoCYQiEE03gII7HQR3BEICAOJICYRSC
-QDjRNE1CAAzVQR3WE5AkAAqEUQiFQEARBAUAAAzHQR3BEICAOI4CUQhFIBAREwXjUFUHdQRD
-QJJAABbCFAhEJBgBAADAMAwXdQRDAALiCAhEIRQCYRiCEZDjUFFHMAQkIBAFOAmTQBiFUAQg
-II7AUFXUEQwBCQjEJExBkBRCEZCjMIBD9RxDAALiGEzCFBBYIRTBOI7AQB1DMIoCMQkYGAjL
-JEwBCIgjOVDDEJCAQGACJiTTJEwBSY5BEJAiSCCwTAiCZBKmAATEkSzNQBCCYCDBJgELTNMk
-g0AMEgwTAhAQR7I0zYARgvM8TyAIznMMAQA7}
-paste {R0lGODlhEAAQAKIAANnZ2QAAAP//AISEAISEhP///wAAhP///yH5BAEAAAAALAAAAAAQABAA
-AANwCLrcjqGBoKsYqiKrCDSGBkMiJJCGAgCDKBB0gwYDIKYwdJUIAyBokIaGBmloAhBiaAgH
-TdcCEIKGBsmwVM0AIYaGcAxL1coQgoYGySoisMzMAoeGxrB01QJpaMiwMHTLAEPVsHTVEHTR
-dBlBlxswAQA7}
-print {R0lGODlhEAAQAKIAANnZ2QAAAP///4SEhP//AP///////////yH5BAEAAAAALAAAAAAQABAA
-AANZCLrcjqG7CLqBoquBoBuCoSqBoBsouhoIuiEYqrKBoIGiqwEYEIChyxAIEYGgywEYgKHL
-DAgRCLozgwABARgIukSEABEBGLq8gAEQCLobgAEAgKHLgaDLzZgAOw==}
-question {R0lGODlhIAAgAKIAANnZ2YSEhMbGxv///wAAAAAA/////////yH5BAEAAAAALAAAAAAgACAA
-AAP/CLoMGLqKoMvtGCo4uhKBgaDLDRghOLqsghEIuryBgqPLPSiBoMsQOLrcjYSgu4GjO4Kl
-Kzi6Qwi6EDi6I4UyU1VYgqM7hKAagqM7VTg6VYWFoztCCAqBo6tVWDVThVU4ukqBACE4ulqF
-VSNVWIWjq0IYEDi6K4UlU1VYOLpMgRA4uryCpTi6PIShOLq8hVU4uqyEoTi6vIUlOLqshKE4
-uryFhaPLSxgqOLrc3kgoAgJHl0ewSnB0eQhDIQRHl6uwCkeXhTAUIHB0uQqrcHSZAiMAAJBw
-dFcKS3B0lwIjAkGVcHS5GykiAkEXSHB0uQeFIiIQdJcIBUeXVZAoIgJBT5chkFRwdIUICUMV
-QZc3MIKIBEcJQzcQdLkBQ4NmcAhDFUGX2zFoZggjEHS5vRHNUASCLrc7oqEIBF1uf0QUgaDL
-7Q9QKIIut79CEQi6DAkAOw==}
-redo {R0lGODlhEAAQAJEAANnZ2QAAhP///////yH5BAEAAAAALAAAAAAQABAAAAIvhI+py+1vSByC
-jxAYQXDMwsyAggQAQBB8iwgMgg8REQgUwqbYBDsIPqYutz+MgBQAOw==}
-save {R0lGODlhEAAQAJEAANnZ2QAAAISEAP///yH5BAEAAAAALAAAAAAQABAAAAJWhI9pFB8RIIRC
-+BYQFqQQvkWEBSmEbyFhQQrhW0hYkEL4FhIWpBC+hYQFSYxvIgFAoXy0AAiSGP8kAIIkxgcI
-CSBEQvEBQgIIkVB8gJAAAhgfj+BjWgEAOw==}
-underline {R0lGODlhEAAQAJEAANnZ2QAAAP///////yH5BAEAAAAALAAAAAAQABAAAAI3hI+py60UBy4I
-vkVcBMG/iIsg+BdxEQT/Ii6C4F/ERRD8i7gIgn8RF0HwkWITfExFin8EH1OXCwA7}
-undo {R0lGODlhEAAQAJEAANnZ2QAAhP///////yH5BAEAAAAALAAAAAAQABAAAAIuhI+py+2vSByC
-HxdxQCHsCIg7oAAAEUHwLTAiKIQPgRSbYMfd3VEIH1OX2x8mUgA7}
-warning {R0lGODlhIAAgAKIAANnZ2YSEAP//AMbGxgAAAISEhP///////yH5BAEAAAAALAAAAAAgACAA
-AAP/CLq8gREIutz+KESGEHS5vVGIiAxSIehy+6JAUaUqBF1uBxQoukOFhaDL7RgoukKFhaDL
-3RgoujqEVQi63IyBortUWAi63IuBostDWIWgy60YIjKERCMiSFUIutyAISKCpCoiOFSFoMsd
-KCpIqiKCQlUIusyBooqkKiIoQ1UIuryBooqkiqJKVQi6rIGii6SKojpUWAi6DIGiG0RIgaJL
-VQi6HCi6MoREg6I7VFgIuhsoukqEhKKrVFgIuhoouhuEgaKrQ1iFoAuBortDOCi6S4WFoBso
-uiyEostDWIWgGii63K6IqgAAIVB0WQaJBkV3h7AKAAJFl4WQiFB0mQoLRyBQdFkJiQhFl4ew
-CgJFl3WQaFB0WQirIFB0ud0RVVWg6HJ7o6GqAgwUXW5fNFRVhQCBpMvti0oVABCwdLndEehi
-6XI7I4AEADs=}
-}
diff --git a/ext/tk/sample/tkextlib/tile/readme.txt b/ext/tk/sample/tkextlib/tile/readme.txt
deleted file mode 100644
index f5d613a7b4..0000000000
--- a/ext/tk/sample/tkextlib/tile/readme.txt
+++ /dev/null
@@ -1,3 +0,0 @@
-All of *.tcl, themes/kroc.tcl and images (themes/kroc/*) are
-quoted from Tcl/Tk's Tile extension.
-Please read Orig_LICENSE.txt.
diff --git a/ext/tk/sample/tkextlib/tile/repeater.tcl b/ext/tk/sample/tkextlib/tile/repeater.tcl
deleted file mode 100644
index 652ba8ab17..0000000000
--- a/ext/tk/sample/tkextlib/tile/repeater.tcl
+++ /dev/null
@@ -1,117 +0,0 @@
-#
-# $Id$
-#
-# Demonstration of custom classes.
-#
-# The Tile button doesn't have built-in support for autorepeat.
-# Instead of adding -repeatdelay and -repeatinterval options,
-# and all the extra binding scripts required to deal with them,
-# we create a custom widget class for autorepeating buttons.
-#
-# Usage:
-# ttk::button .b -class Repeater [... other options ...]
-#
-# TODO:
-# Use system settings for repeat interval and initial delay.
-#
-# Notes:
-# Repeater buttons work more like scrollbar arrows than
-# Tk repeating buttons: they fire once immediately when
-# first pressed, and $State(delay) specifies the initial
-# interval before the button starts autorepeating.
-#
-
-namespace eval tile::Repeater {
- variable State
- set State(timer) {} ;# [after] id of repeat script
- set State(interval) 100 ;# interval between repetitions
- set State(delay) 300 ;# delay after initial invocation
-}
-
-### Class bindings.
-#
-
-bind Repeater <Enter> { %W state active }
-bind Repeater <Leave> { %W state !active }
-
-bind Repeater <Key-space> { tile::Repeater::Activate %W }
-bind Repeater <<Invoke>> { tile::Repeater::Activate %W }
-
-bind Repeater <ButtonPress-1> { tile::Repeater::Press %W }
-bind Repeater <ButtonRelease-1> { tile::Repeater::Release %W }
-bind Repeater <B1-Leave> { tile::Repeater::Pause %W }
-bind Repeater <B1-Enter> { tile::Repeater::Resume %W } ;# @@@ see below
-
-# @@@ Workaround for metacity-induced bug:
-bind Repeater <B1-Enter> \
- { if {"%d" ne "NotifyUngrab"} { tile::Repeater::Resume %W } }
-
-### Binding procedures.
-#
-
-## Activate -- Keyboard activation binding.
-# Simulate clicking the button, and invoke the command once.
-#
-proc tile::Repeater::Activate {w} {
- $w instate disabled { return }
- set oldState [$w state pressed]
- update idletasks; after 100
- $w state $oldState
- after idle [list $w invoke]
-}
-
-## Press -- ButtonPress-1 binding.
-# Invoke the command once and start autorepeating after
-# $State(delay) milliseconds.
-#
-proc tile::Repeater::Press {w} {
- variable State
- $w instate disabled { return }
- $w state pressed
- $w invoke
- after cancel $State(timer)
- set State(timer) [after $State(delay) [list tile::Repeater::Repeat $w]]
-}
-
-## Release -- ButtonRelease binding.
-# Stop repeating.
-#
-proc tile::Repeater::Release {w} {
- variable State
- $w state !pressed
- after cancel $State(timer)
-}
-
-## Pause -- B1-Leave binding
-# Temporarily suspend autorepeat.
-#
-proc tile::Repeater::Pause {w} {
- variable State
- $w state !pressed
- after cancel $State(timer)
-}
-
-## Resume -- B1-Enter binding
-# Resume autorepeat.
-#
-proc tile::Repeater::Resume {w} {
- variable State
- $w instate disabled { return }
- $w state pressed
- $w invoke
- after cancel $State(timer)
- set State(timer) [after $State(interval) [list tile::Repeater::Repeat $w]]
-}
-
-## Repeat -- Timer script
-# Invoke the command and reschedule another repetition
-# after $State(interval) milliseconds.
-#
-proc tile::Repeater::Repeat {w} {
- variable State
- $w instate disabled { return }
- $w invoke
- set State(timer) [after $State(interval) [list tile::Repeater::Repeat $w]]
-}
-
-#*EOF*
diff --git a/ext/tk/sample/tkextlib/tile/themes/kroc.rb b/ext/tk/sample/tkextlib/tile/themes/kroc.rb
deleted file mode 100644
index ab782b8c36..0000000000
--- a/ext/tk/sample/tkextlib/tile/themes/kroc.rb
+++ /dev/null
@@ -1,197 +0,0 @@
-#
-# kroc.rb
-#
-# based on:
-# >> kroc.tcl - Copyright (C) 2004 David Zolli <kroc@kroc.tk>
-#
-
-imgdir = File.join(File.dirname(__FILE__), 'kroc')
-$images = Tk::Tile.load_images(imgdir, '*.gif')
-
-if TkPackage.vcompare(Tk::Tile.package_version, '0.5') >= 0
- $TNotebook_Tab = Tk::Tile::TNotebook.style('Tab')
-else
- $TNotebook_Tab = 'Tab.TNotebook'
-end
-
-def kroc_rb_settings
- # Tk::Tile::Style.default(TkRoot, :background=>'#FCB64F',
- # :troughcolor=>'#F8C278', :borderwidth=>1)
- # or
- # Tk::Tile::Style.default(Tk.root, :background=>'#FCB64F',
- # :troughcolor=>'#F8C278', :borderwidth=>1)
- # or
- # Tk::Tile::Style.default('.', :background=>'#FCB64F',
- # :troughcolor=>'#F8C278', :borderwidth=>1)
- # or
- # Tk::Tile::Style.default(nil, :background=>'#FCB64F',
- # :troughcolor=>'#F8C278', :borderwidth=>1)
- # or
- Tk::Tile::Style.default(:background=>'#FCB64F', :troughcolor=>'#F8C278',
- :borderwidth=>1)
- # Tk::Tile::Style.default(TkRoot, :font=>Tk::Tile::Font::Default,
- # :borderwidth=>1)
- # or
- # Tk::Tile::Style.default(Tk.root, :font=>Tk::Tile::Font::Default,
- # :borderwidth=>1)
- # or
- # Tk::Tile::Style.default('.', :font=>Tk::Tile::Font::Default,
- # :borderwidth=>1)
- # or
- # Tk::Tile::Style.default(nil, :font=>Tk::Tile::Font::Default,
- # :borderwidth=>1)
- # or
- Tk::Tile::Style.default(:font=>Tk::Tile::Font::Default, :borderwidth=>1)
-
- # Tk::Tile::Style.map(TkRoot, :background=>[:active, '#694418'])
- # or
- # Tk::Tile::Style.map(Tk.root, :background=>[:active, '#694418'])
- # or
- # Tk::Tile::Style.map('.', :background=>[:active, '#694418'])
- # or
- # Tk::Tile::Style.map(nil, :background=>[:active, '#694418'])
- # or
- Tk::Tile::Style.map(:background=>[:active, '#694418'])
- Tk::Tile::Style.map(:foreground=>[:disabled, '#B2B2B2', :active, '#FFE7CB'])
-
- # Tk::Tile::Style.default('TButton', :padding=>[10,4])
- Tk::Tile::Style.default(Tk::Tile::TButton, :padding=>[10,4])
-
- # Tk::Tile::Style.default('TNotebook.Tab',
- Tk::Tile::Style.default($TNotebook_Tab,
- :padding=>[10, 3], :font=>Tk::Tile::Font::Default)
- # Tk::Tile::Style.map('TNotebook.Tab',
- Tk::Tile::Style.map($TNotebook_Tab,
- :background=>[:selected, '#FCB64F', '', '#FFE6BA'],
- :foreground=>['', 'black'],
- :padding=>[:selected, [10, 6, 10, 3]])
-
- # Tk::Tile::Style.map('TScrollbar',
- Tk::Tile::Style.map(Tk::Tile::TScrollbar,
- :background=>[:pressed, '#694418'],
- :arrowcolor=>[:pressed, '#FEF7CB'],
- :relief=>[:pressed, :sunken])
-
- # Tk::Tile::Style.layout('Vertical.TScrollbar',
- Tk::Tile::Style.layout(Tk::Tile.style('Vertical', Tk::Tile::TScrollbar),
- ['Scrollbar.trough', {:children=>[
- 'Scrollbar.uparrow', {:side=>:top},
- 'Scrollbar.downarrow', {:side=>:bottom},
- 'Scrollbar.uparrow', {:side=>:bottom},
- 'Scrollbar.thumb', {:side=>:top, :expand=>true}
- ]}
- ])
-
- # Tk::Tile::Style.layout('Horizontal.TScrollbar',
- Tk::Tile::Style.layout(Tk::Tile.style('Horizontal', Tk::Tile::TScrollbar),
- ['Scrollbar.trough', {:children=>[
- 'Scrollbar.leftarrow', {:side=>:left},
- 'Scrollbar.rightarrow', {:side=>:right},
- 'Scrollbar.leftarrow', {:side=>:right},
- 'Scrollbar.thumb', {:side=>:left, :expand=>true}
- ]}
- ])
-
- #
- # Elements:
- #
- if TkPackage.vcompare(Tk::Tile.package_version, '0.5') >= 0
-
- Tk::Tile::Style.element_create('Button.button', :image, $images['button-n'],
- :map=>[
- :pressed, $images['button-p'],
- :active, $images['button-h'],
- ], :border=>3, :sticky=>:ew)
-
- Tk::Tile::Style.element_create('Checkbutton.indicator', :image, $images['check-nu'],
- :map=>[
- [:pressed, :selected], $images['check-nc'],
- :pressed, $images['check-nu'],
- [:active, :selected], $images['check-hc'],
- :active, $images['check-hu'],
- :selected, $images['check-nc'],
- ], :sticky=>:w)
-
- Tk::Tile::Style.element_create('Radiobutton.indicator', :image, $images['radio-nu'],
- :map=>[
- [:pressed, :selected], $images['radio-nc'],
- :pressed, $images['radio-nu'],
- [:active, :selected], $images['radio-hc'],
- :active, $images['radio-hu'],
- :selected, $images['radio-nc'],
- ], :sticky=>:w)
-
- else # tile 0.4 or earlier
-
- Tk::Tile::Style.element_create('Button.button', :pixmap,
- :images=>[
- :pressed, $images['button-p'],
- :active, $images['button-h'],
- '', $images['button-n']
- ], :border=>3, :tiling=>:tile)
-
- Tk::Tile::Style.element_create('Checkbutton.indicator', :pixmap,
- :images=>[
- [:pressed, :selected], $images['check-nc'],
- :pressed, $images['check-nu'],
- [:active, :selected], $images['check-hc'],
- :active, $images['check-hu'],
- :selected, $images['check-nc'],
- '', $images['check-nu'],
- ], :tiling=>:fixed)
-
- Tk::Tile::Style.element_create('Radiobutton.indicator', :pixmap,
- :images=>[
- [:pressed, :selected], $images['radio-nc'],
- :pressed, $images['radio-nu'],
- [:active, :selected], $images['radio-hc'],
- :active, $images['radio-hu'],
- :selected, $images['radio-nc'],
- '', $images['radio-nu'],
- ], :tiling=>:fixed)
-
- end
-
- #
- # Settings:
- #
- # Tk::Tile::Style.layout(Tk::Tile::TButton,
- Tk::Tile::Style.layout('TButton', [
- 'Button.button', {:children=>[
- 'Button.focus', {:children=>[
- 'Button.padding', {:children=>[
- 'Button.label', {:expand=>true, :sticky=>''}
- ]}
- ]}
- ]}
- ])
-
- # Tk::Tile::Style.layout(Tk::Tile::TCheckbutton,
- Tk::Tile::Style.layout('TCheckbutton', [
- 'Checkbutton.background', # this is not needed in tile 0.5 or later
- 'Checkbutton.border', {:children=>[
- 'Checkbutton.padding', {:children=>[
- 'Checkbutton.indicator', {:side=>:left},
- 'Checkbutton.focus', {:side=>:left, :children=>[
- 'Checkbutton.label'
- ]}
- ]}
- ]}
- ])
-
- # Tk::Tile::Style.layout(Tk::Tile::TRadiobutton,
- Tk::Tile::Style.layout('TRadiobutton', [
- 'Radiobutton.background', # this is not needed in tile 0.5 or later
- 'Radiobutton.border', {:children=>[
- 'Radiobutton.padding', {:children=>[
- 'Radiobutton.indicator', {:side=>:left},
- 'Radiobutton.focus', {:expand=>true, :sticky=>:w, :children=>[
- 'Radiobutton.label', {:side=>:right, :expand=>true}
- ]}
- ]}
- ]}
- ])
-end
-
-Tk::Tile::Style.theme_create('kroc-rb', :parent=>'alt',
- :settings=>proc{ kroc_rb_settings() })
diff --git a/ext/tk/sample/tkextlib/tile/themes/kroc.tcl b/ext/tk/sample/tkextlib/tile/themes/kroc.tcl
deleted file mode 100644
index 73548acef2..0000000000
--- a/ext/tk/sample/tkextlib/tile/themes/kroc.tcl
+++ /dev/null
@@ -1,163 +0,0 @@
-# kroc.tcl - Copyright (C) 2004 David Zolli <kroc@kroc.tk>
-#
-# A sample pixmap theme for the tile package.
-
-#package require tile::pixmap
-
-namespace eval tile {
- namespace eval kroc {
- variable version 0.0.1
- }
-}
-
-namespace eval tile::kroc {
-
- set imgdir [file join [file dirname [info script]] kroc]
- array set Images [tile::LoadImages $imgdir *.gif]
-
- if {[package vsatisfies [package provide tile] 0.5]} {
- set TNoteBook_Tab TNotebook.Tab
- } else {
- set TNoteBook_Tab Tab.TNotebook
- }
-
- style theme create kroc -parent alt -settings {
-
- style default . -background #FCB64F -troughcolor #F8C278 -borderwidth 1
- style default . -font TkDefaultFont -borderwidth 1
- style map . -background [list active #694418]
- style map . -foreground [list disabled #B2B2B2 active #FFE7CB]
-
- style default TButton -padding "10 4"
-
- style default $TNoteBook_Tab -padding {10 3} -font TkDefaultFont
- style map $TNoteBook_Tab \
- -background [list selected #FCB64F {} #FFE6BA] \
- -foreground [list {} black] \
- -padding [list selected {10 6 10 3}]
-
- style map TScrollbar \
- -background { pressed #694418} \
- -arrowcolor { pressed #FFE7CB } \
- -relief { pressed sunken } \
- ;
-
- style layout Vertical.TScrollbar {
- Scrollbar.trough -children {
- Scrollbar.uparrow -side top
- Scrollbar.downarrow -side bottom
- Scrollbar.uparrow -side bottom
- Scrollbar.thumb -side top -expand true
- }
- }
-
- style layout Horizontal.TScrollbar {
- Scrollbar.trough -children {
- Scrollbar.leftarrow -side left
- Scrollbar.rightarrow -side right
- Scrollbar.leftarrow -side right
- Scrollbar.thumb -side left -expand true
- }
- }
-
- #
- # Elements:
- #
- if {[package vsatisfies [package provide tile] 0.5]} {
-
- style element create Button.button image $Images(button-n) \
- -map [list \
- pressed $Images(button-p) \
- active $Images(button-h) \
- ] -border 3 -sticky ew
-
- style element create Checkbutton.indicator image $Images(check-nu) \
- -map [list \
- {pressed selected} $Images(check-nc) \
- pressed $Images(check-nu) \
- {active selected} $Images(check-hc) \
- active $Images(check-hu) \
- selected $Images(check-nc) \
- ] -sticky w
-
- style element create Radiobutton.indicator image $Images(radio-nu) \
- -map [list \
- {pressed selected} $Images(radio-nc) \
- pressed $Images(radio-nu) \
- {active selected} $Images(radio-hc) \
- active $Images(radio-hu) \
- selected $Images(radio-nc) \
- ] -sticky w
-
- } else {
-
- style element create Button.button pixmap -images [list \
- pressed $Images(button-p) \
- active $Images(button-h) \
- {} $Images(button-n) \
- ] -border 3 -tiling tile
-
- style element create Checkbutton.indicator pixmap -images [list \
- {pressed selected} $Images(check-nc) \
- pressed $Images(check-nu) \
- {active selected} $Images(check-hc) \
- active $Images(check-hu) \
- selected $Images(check-nc) \
- {} $Images(check-nu) \
- ] -tiling fixed
-
- style element create Radiobutton.indicator pixmap -images [list \
- {pressed selected} $Images(radio-nc) \
- pressed $Images(radio-nu) \
- {active selected} $Images(radio-hc) \
- active $Images(radio-hu) \
- selected $Images(radio-nc) \
- {} $Images(radio-nu) \
- ] -tiling fixed
-
- }
-
- #
- # Settings: (*button.background is not needed in tile 0.5 or above)
- #
- style layout TButton {
- Button.button -children {
- Button.focus -children {
- Button.padding -children {
- Button.label -expand true -sticky {}
- }
- }
- }
- }
-
- style layout TCheckbutton {
- Checkbutton.border -children {
- Checkbutton.background
- Checkbutton.padding -children {
- Checkbutton.indicator -side left
- Checkbutton.focus -side left -children {
- Checkbutton.label
- }
- }
- }
- }
-
- style layout TRadiobutton {
- Radiobutton.border -children {
- Radiobutton.background
- Radiobutton.padding -children {
- Radiobutton.indicator -side left
- Radiobutton.focus -expand true -sticky w -children {
- Radiobutton.label -side right -expand true
- }
- }
- }
- }
-
- } }
-
-# -------------------------------------------------------------------------
-
-package provide tile::theme::kroc $::tile::kroc::version
-
-# -------------------------------------------------------------------------
diff --git a/ext/tk/sample/tkextlib/tile/themes/kroc/button-h.gif b/ext/tk/sample/tkextlib/tile/themes/kroc/button-h.gif
deleted file mode 100644
index e7a140dede..0000000000
--- a/ext/tk/sample/tkextlib/tile/themes/kroc/button-h.gif
+++ /dev/null
Binary files differ
diff --git a/ext/tk/sample/tkextlib/tile/themes/kroc/button-n.gif b/ext/tk/sample/tkextlib/tile/themes/kroc/button-n.gif
deleted file mode 100644
index 78b506ddeb..0000000000
--- a/ext/tk/sample/tkextlib/tile/themes/kroc/button-n.gif
+++ /dev/null
Binary files differ
diff --git a/ext/tk/sample/tkextlib/tile/themes/kroc/button-p.gif b/ext/tk/sample/tkextlib/tile/themes/kroc/button-p.gif
deleted file mode 100644
index a5a4e90be1..0000000000
--- a/ext/tk/sample/tkextlib/tile/themes/kroc/button-p.gif
+++ /dev/null
Binary files differ
diff --git a/ext/tk/sample/tkextlib/tile/themes/kroc/check-hc.gif b/ext/tk/sample/tkextlib/tile/themes/kroc/check-hc.gif
deleted file mode 100644
index 41503c5ebd..0000000000
--- a/ext/tk/sample/tkextlib/tile/themes/kroc/check-hc.gif
+++ /dev/null
Binary files differ
diff --git a/ext/tk/sample/tkextlib/tile/themes/kroc/check-hu.gif b/ext/tk/sample/tkextlib/tile/themes/kroc/check-hu.gif
deleted file mode 100644
index b3e512ca67..0000000000
--- a/ext/tk/sample/tkextlib/tile/themes/kroc/check-hu.gif
+++ /dev/null
Binary files differ
diff --git a/ext/tk/sample/tkextlib/tile/themes/kroc/check-nc.gif b/ext/tk/sample/tkextlib/tile/themes/kroc/check-nc.gif
deleted file mode 100644
index a28c288fce..0000000000
--- a/ext/tk/sample/tkextlib/tile/themes/kroc/check-nc.gif
+++ /dev/null
Binary files differ
diff --git a/ext/tk/sample/tkextlib/tile/themes/kroc/check-nu.gif b/ext/tk/sample/tkextlib/tile/themes/kroc/check-nu.gif
deleted file mode 100644
index 5c23931bbc..0000000000
--- a/ext/tk/sample/tkextlib/tile/themes/kroc/check-nu.gif
+++ /dev/null
Binary files differ
diff --git a/ext/tk/sample/tkextlib/tile/themes/kroc/radio-hc.gif b/ext/tk/sample/tkextlib/tile/themes/kroc/radio-hc.gif
deleted file mode 100644
index 359fe1cc8b..0000000000
--- a/ext/tk/sample/tkextlib/tile/themes/kroc/radio-hc.gif
+++ /dev/null
Binary files differ
diff --git a/ext/tk/sample/tkextlib/tile/themes/kroc/radio-hu.gif b/ext/tk/sample/tkextlib/tile/themes/kroc/radio-hu.gif
deleted file mode 100644
index 9f46b37926..0000000000
--- a/ext/tk/sample/tkextlib/tile/themes/kroc/radio-hu.gif
+++ /dev/null
Binary files differ
diff --git a/ext/tk/sample/tkextlib/tile/themes/kroc/radio-nc.gif b/ext/tk/sample/tkextlib/tile/themes/kroc/radio-nc.gif
deleted file mode 100644
index 6437f33a7a..0000000000
--- a/ext/tk/sample/tkextlib/tile/themes/kroc/radio-nc.gif
+++ /dev/null
Binary files differ
diff --git a/ext/tk/sample/tkextlib/tile/themes/kroc/radio-nu.gif b/ext/tk/sample/tkextlib/tile/themes/kroc/radio-nu.gif
deleted file mode 100644
index 2d2aac8597..0000000000
--- a/ext/tk/sample/tkextlib/tile/themes/kroc/radio-nu.gif
+++ /dev/null
Binary files differ
diff --git a/ext/tk/sample/tkextlib/tile/themes/pkgIndex.tcl b/ext/tk/sample/tkextlib/tile/themes/pkgIndex.tcl
deleted file mode 100644
index 179077917c..0000000000
--- a/ext/tk/sample/tkextlib/tile/themes/pkgIndex.tcl
+++ /dev/null
@@ -1,15 +0,0 @@
-# pkgIndex.tcl for additional tile pixmap themes.
-#
-# We don't provide the package is the image subdirectory isn't present,
-# or we don't have the right version of Tcl/Tk
-#
-# To use this automatically within tile, the tile-using application should
-# use tile::availableThemes and tile::setTheme
-#
-# $Id$
-
-if {![file isdirectory [file join $dir kroc]]} { return }
-if {![package vsatisfies [package provide Tcl] 8.4]} { return }
-
-package ifneeded tile::theme::kroc 0.0.1 \
- [list source [file join $dir kroc.tcl]]
diff --git a/ext/tk/sample/tkextlib/tile/toolbutton.tcl b/ext/tk/sample/tkextlib/tile/toolbutton.tcl
deleted file mode 100644
index 4e08034e31..0000000000
--- a/ext/tk/sample/tkextlib/tile/toolbutton.tcl
+++ /dev/null
@@ -1,152 +0,0 @@
-#
-# $Id$
-#
-# Demonstration of custom widget styles.
-#
-
-#
-# ~ BACKGROUND
-#
-# Checkbuttons in toolbars have a very different appearance
-# than regular checkbuttons: there's no indicator, they
-# "pop up" when the mouse is over them, and they appear sunken
-# when selected.
-#
-# Tk added partial support for toolbar-style buttons in 8.4
-# with the "-overrelief" option, and TIP #82 added further
-# support with the "-offrelief" option. So to get a toolbar-style
-# checkbutton, you can configure it with:
-#
-# checkbutton .cb \
-# -indicatoron false -selectcolor {} -relief flat -overrelief raised
-#
-# Behind the scenes, Tk has a lot of rather complicated logic
-# to implement this checkbutton style; see library/button.tcl,
-# generic/tkButton.c, and the platform-specific files unix/tkUnixButton.c
-# et al. for the full details.
-#
-# The tile widget set has a better way: custom styles.
-# Since the appearance is completely controlled by the theme engine,
-# we can define a new "Toolbutton" style and just use:
-#
-# checkbutton .cb -style Toolbutton
-#
-#
-# ~ DEMONSTRATION
-#
-# The tile built-in themes (default, "alt", windows, and XP)
-# already include Toolbutton styles. This script will add
-# them to the "step" and "blue" themes as a demonstration.
-#
-# (Note: Pushbuttons and radiobuttons can also use the "Toolbutton"
-# style; see demo.tcl.)
-#
-
-style theme settings "step" {
-
-#
-# First, we use [style layout] to define what elements to
-# use and how they're arranged. Toolbuttons are pretty
-# simple, consisting of a border, some internal padding,
-# and a label. (See also the TScrollbar layout definition
-# in demos/blue.tcl for a more complicated layout spec.)
-#
- style layout Toolbutton {
- Toolbutton.background
- Toolbutton.border -children {
- Toolbutton.padding -children {
- Toolbutton.label
- }
- }
- }
-
-# (Actually the above isn't strictly necessary, since the same layout
-# is defined in the default theme; we could have inherited it
-# instead.)
-#
-# Next, specify default values for element options.
-# For many options (like -background), the defaults
-# inherited from the parent style are sufficient.
-#
- style default Toolbutton -width 0 -padding 1 -relief flat -borderwidth 2
-
-#
-# Finally, use [style map] to specify state-specific
-# resource values. We want a flat relief if the widget is
-# disabled, sunken if it's selected (on) or pressed,
-# and raised when it's active (the mouse pointer is
-# over the widget). Each state-value pair is checked
-# in order, and the first matching state takes precedence.
-#
- style map Toolbutton -relief {
- disabled flat
- selected sunken
- pressed sunken
- active raised
- }
-}
-
-#
-# Now for the "blue" theme. (Since the purpose of this
-# theme is to show what *can* be done, not necessarily what
-# *should* be done, the following makes some questionable
-# design decisions from an aesthetic standpoint.)
-#
-if {![catch {package require tile::theme::blue}]} {
-style theme settings "blue" {
-
- #
- # Default values:
- #
- style default Toolbutton \
- -width 0 -relief flat -borderwidth 2 \
- -background #6699CC -foreground #000000 ;
-
- #
- # Configure state-specific values for -relief, as before:
- #
- style map Toolbutton -relief {
- disabled flat
- selected sunken
- pressed sunken
- active raised
- }
-
- #
- # Adjust the -padding at the same time, to enhance
- # the raised/sunken illusion:
- #
- style default Toolbutton -padding 4
- style map Toolbutton -padding {
- disabled {4}
- selected {6 6 2 2}
- pressed {6 6 2 2}
- active {2 2 6 6}
- }
-
- #
- # ... and change the foreground and background colors
- # when the mouse cursor is over the widget:
- #
- style map Toolbutton -background {
- active #008800
- } -foreground {
- active #FFFFFF
- }
-}
-
-}
-
-#
-# ~ A final note:
-#
-# TIP #82 also says: "When -indicatoron is off and the button itself
-# is on, the relief continues to be hard-coded to sunken. For symmetry,
-# we might consider adding another -onrelief option to cover this
-# case. But it is difficult to imagine ever wanting to change the
-# value of -onrelief so it has been omitted from this TIP.
-# If there as strong desire to have -onrelief, it can be added later."
-# ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
-#
-# The Tile project aims to make sure that this never needs to happen.
-#
diff --git a/ext/tk/sample/tkextlib/tkHTML/hv.rb b/ext/tk/sample/tkextlib/tkHTML/hv.rb
index a4d78ea5b1..d9f3ea7d7c 100644
--- a/ext/tk/sample/tkextlib/tkHTML/hv.rb
+++ b/ext/tk/sample/tkextlib/tkHTML/hv.rb
@@ -78,43 +78,38 @@ big_imgs = {}
hotkey = {}
move_big_image = proc{|b|
- if big_imgs.key?(b)
- b.copy(big_imgs[b])
- big_imgs[b].delete
- big_imgs.delete(b)
- Tk.update
- end
+ return unless big_imgs.key?(b)
+ b.copy(big_imgs[b])
+ big_imgs[b].delete
+ big_imgs.delete(b)
+ Tk.update
}
image_cmd = proc{|*args|
- if show_img.bool
- smgray
- else
- fn = args[0]
+ return smgray unless show_img.bool
+ fn = args[0]
+ if old_imgs.key?(fn)
+ images[fn] = old_imgs[fn]
+ old_imgs.delete(fn)
+ return images[fn]
+ end
- if old_imgs.key?(fn)
- images[fn] = old_imgs[fn]
- old_imgs.delete(fn)
- images[fn]
+ begin
+ img = TkPhotoImage.new(:file=>fn)
+ rescue
+ return smgray
+ end
- else
- begin
- img = TkPhotoImage.new(:file=>fn)
- rescue
- smgray
- else
- if img.width * img.height > 20000
- b = TkPhotoImage.new(:width=>img.width, :height=>img.height)
- big_imgs[b] = img
- img = b
- Tk.after_idle(proc{ move_big_image.call(b) })
- end
-
- images[fn] = img
- img
- end
- end
+ if img.width * img.height > 20000
+ b = TkPhotoImage.new(:width=>img.width, :height=>img.height)
+ big_imgs[b] = img
+ img = b
+ Tk.after_idle(proc{ move_big_image.call(b) })
end
+
+ images[fn] = img
+
+ img
}
#
@@ -188,13 +183,12 @@ clear_screen = proc{
# Load a file into the HTML widget
#
load_file = proc{|name|
- if (doc = read_file.call(name))
- clear_screen.call
- last_file = name
- html.configure(:base=>name)
- html.parse(doc)
- old_imgs.clear
- end
+ return unless (doc = read_file.call(name))
+ clear_screen.call
+ last_file = name
+ html.configure(:base=>name)
+ html.parse(doc)
+ old_imgs.clear
}
href_binding = proc{|x, y|
@@ -202,16 +196,15 @@ href_binding = proc{|x, y|
html.selection_clear
priv['mark'] = "@#{x},#{y}"
lst = html.href(x, y)
+ return if lst.size.zero?
- unless lst.size.zero?
- lnk, target = lst
+ lnk, target = lst
- if lnk != ""
- if lnk =~ /^#{last_file}#(.*)$/
- html.yview($1)
- else
- load_file.call(lnk)
- end
+ if lnk != ""
+ if lnk =~ /^#{last_file}#(.*)$/
+ html.yview($1)
+ else
+ load_file.call(lnk)
end
end
}
diff --git a/ext/tk/sample/tkextlib/tkHTML/ss.rb b/ext/tk/sample/tkextlib/tkHTML/ss.rb
index 1c13d7ac34..179bdc13cd 100644
--- a/ext/tk/sample/tkextlib/tkHTML/ss.rb
+++ b/ext/tk/sample/tkextlib/tkHTML/ss.rb
@@ -6,431 +6,399 @@
require 'tk'
require 'tkextlib/tkHTML'
+root = TkRoot.new(:title=>'HTML File Viewer', :iconname=>'HV')
+fswin = nil
+
+html = nil
+html_fs = nil
+
+hotkey = {}
+
file = ARGV[0]
-class TkHTML_File_Viewer
- include TkComm
# These are images to use with the actual image specified in a
# "<img>" markup can't be found.
#
-@@biggray = TkPhotoImage.new(:data=><<'EOD')
+biggray = TkPhotoImage.new(:data=><<'EOD')
R0lGODdhPAA+APAAALi4uAAAACwAAAAAPAA+AAACQISPqcvtD6OctNqLs968+w+G4kiW5omm
6sq27gvH8kzX9o3n+s73/g8MCofEovGITCqXzKbzCY1Kp9Sq9YrNFgsAO///
EOD
-@@smgray = TkPhotoImage.new(:data=><<'EOD')
+smgray = TkPhotoImage.new(:data=><<'EOD')
R0lGODdhOAAYAPAAALi4uAAAACwAAAAAOAAYAAACI4SPqcvtD6OctNqLs968+w+G4kiW5omm
6sq27gvH8kzX9m0VADv/
EOD
- def initialize(file = nil)
- @root = TkRoot.new(:title=>'HTML File Viewer', :iconname=>'HV')
- @fswin = nil
-
- @html = nil
- @html_fs = nil
-
- @hotkey = {}
-
- @applet_arg = TkVarAccess.new_hash('AppletArg')
-
- @images = {}
- @old_imgs = {}
- @big_imgs = {}
-
- @last_dir = Dir.pwd
-
- @last_file = ''
-
- @key_block = false
-
- Tk::HTML_Widget::ClippingWindow.bind('1',
- proc{|w, ksym| key_press(w, ksym)},
- '%W Down')
- Tk::HTML_Widget::ClippingWindow.bind('3',
- proc{|w, ksym| key_press(w, ksym)},
- '%W Up')
- Tk::HTML_Widget::ClippingWindow.bind('2',
- proc{|w, ksym| key_press(w, ksym)},
- '%W Down')
-
- Tk::HTML_Widget::ClippingWindow.bind('KeyPress',
- proc{|w, ksym| key_press(w, ksym)},
- '%W %K')
-
- ############################################
- #
- # Build the half-size view of the page
- #
- menu_spec = [
- [['File', 0],
- ['Open', proc{sel_load()}, 0],
- ['Full Screen', proc{fullscreen()}, 0],
- ['Refresh', proc{refresh()}, 0],
- '---',
- ['Exit', proc{exit}, 1]]
- ]
-
- mbar = @root.add_menubar(menu_spec)
-
- @html = Tk::HTML_Widget.new(:width=>512, :height=>384,
- :padx=>5, :pady=>9,
- :formcommand=>proc{|*args| form_cmd(*args)},
- :imagecommand=>proc{|*args|
- image_cmd(1, *args)
- },
- :scriptcommand=>proc{|*args|
- script_cmd(*args)
- },
- :appletcommand=>proc{|*args|
- applet_cmd(*args)
- },
- :hyperlinkcommand=>proc{|*args|
- hyper_cmd(*args)
- },
- :fontcommand=>proc{|*args|
- pick_font(*args)
- },
- :appletcommand=>proc{|*args|
- run_applet('small', *args)
- },
- :bg=>'white', :tablerelief=>:raised)
- @html.token_handler('meta', proc{|*args| meta(@html, *args)})
+#
+# A font chooser routine.
+#
+# html[:fontcommand] = pick_font
+pick_font = proc{|size, attrs|
+ # puts "FontCmd: #{size} #{attrs}"
+ [ ((attrs =~ /fixed/)? 'courier': 'charter'),
+ (12 * (1.2**(size.to_f - 4.0))).to_i,
+ ((attrs =~ /italic/)? 'italic': 'roman'),
+ ((attrs =~ /bold/)? 'bold': 'normal') ].join(' ')
+}
+
+# This routine is called to pick fonts for the fullscreen view.
+#
+baseFontSize = 24
+pick_font_fs = proc{|size, attrs|
+ # puts "FontCmd: #{size} #{attrs}"
+ [ ((attrs =~ /fixed/)? 'courier': 'charter'),
+ (baseFontSize * (1.2**(size.to_f - 4.0))).to_i,
+ ((attrs =~ /italic/)? 'italic': 'roman'),
+ ((attrs =~ /bold/)? 'bold': 'normal') ].join(' ')
+}
- vscr = @html.yscrollbar(TkScrollbar.new)
- hscr = @html.xscrollbar(TkScrollbar.new)
+#
+#
+hyper_cmd = proc{|*args|
+ puts "HyperlinkCommand: #{args.inspect}"
+}
- Tk.grid(@html, vscr, :sticky=>:news)
- Tk.grid(hscr, :sticky=>:ew)
- @root.grid_columnconfigure(0, :weight=>1)
- @root.grid_columnconfigure(1, :weight=>0)
- @root.grid_rowconfigure(0, :weight=>1)
- @root.grid_rowconfigure(1, :weight=>0)
+# This routine is called to run an applet
+#
+applet_arg = TkVarAccess.new_hash('AppletArg')
+run_applet = proc{|size, w, arglist|
+ applet_arg.value = Hash[*simplelist(arglist)]
- ############################################
+ return unless applet_arg.key?('src')
- @html.clipwin.focus
+ src = html.remove(applet_arg['src'])
- # If an arguent was specified, read it into the HTML widget.
- #
- Tk.update
- if file && file != ""
- load_file(file)
- end
- end
+ applet_arg['window'] = w
+ applet_arg['fontsize'] = size
- #
- # A font chooser routine.
- #
- # html[:fontcommand] = pick_font
- def pick_font(size, attrs)
- # puts "FontCmd: #{size} #{attrs}"
- [ ((attrs =~ /fixed/)? 'courier': 'charter'),
- (12 * (1.2**(size.to_f - 4.0))).to_i,
- ((attrs =~ /italic/)? 'italic': 'roman'),
- ((attrs =~ /bold/)? 'bold': 'normal') ].join(' ')
+ begin
+ Tk.load_tclscript(src)
+ rescue => e
+ puts "Applet error: #{e.message}"
end
+}
- # This routine is called to pick fonts for the fullscreen view.
- #
- def pick_font_fs(size, attrs)
- baseFontSize = 24
+#
+#
+form_cmd = proc{|n, cmd, *args|
+}
- # puts "FontCmd: #{size} #{attrs}"
- [ ((attrs =~ /fixed/)? 'courier': 'charter'),
- (baseFontSize * (1.2**(size.to_f - 4.0))).to_i,
- ((attrs =~ /italic/)? 'italic': 'roman'),
- ((attrs =~ /bold/)? 'bold': 'normal') ].join(' ')
- end
+#
+#
+images = {}
+old_imgs = {}
+big_imgs = {}
- #
- #
- def hyper_cmd(*args)
- puts "HyperlinkCommand: #{args.inspect}"
+#
+#
+move_big_image = proc{|b|
+ return unless big_imgs.key?(b)
+ b.copy(big_imgs[b])
+ big_imgs[b].delete
+ big_imgs.delete(b)
+}
+
+image_cmd = proc{|hs, *args|
+ fn = args[0]
+
+ if old_imgs.key?(fn)
+ return (images[fn] = old_imgs.delete(fn))
end
- # This routine is called to run an applet
- #
- def run_applet(size, w, arglist)
- applet_arg.value = Hash[*simplelist(arglist)]
-
- return unless @applet_arg.key?('src')
-
- src = @html.remove(@applet_arg['src'])
-
- @applet_arg['window'] = w
- @applet_arg['fontsize'] = size
-
- begin
- Tk.load_tclscript(src)
- rescue => e
- puts "Applet error: #{e.message}"
- end
+ begin
+ img = TkPhotoImage.new(:file=>fn)
+ rescue
+ return ((hs)? smallgray: biggray)
end
- #
- #
- def form_cmd(n, cmd, *args)
- # p [n, cmd, *args]
+ if hs
+ img2 = TkPhotoImage.new
+ img2.copy(img, :subsample=>[2,2])
+ img.delete
+ img = img2
end
- #
- #
- def move_big_image(b)
- return unless @big_imgs.key?(b)
- b.copy(@big_imgs[b])
- @big_imgs[b].delete
- @big_imgs.delete(b)
+ if img.width * img.height > 20000
+ b = TkPhotoImage.new(:width=>img.width, :height=>img.height)
+ big_imgs[b] = img
+ img = b
+ Tk.after_idle(proc{ move_big_image.call(b) })
end
- def image_cmd(hs, *args)
- fn = args[0]
+ images[fn] = img
- if @old_imgs.key?(fn)
- return (@images[fn] = @old_imgs.delete(fn))
- end
+ img
+}
- begin
- img = TkPhotoImage.new(:file=>fn)
- rescue
- return ((hs)? @@smallgray: @@biggray)
- end
- if hs
- img2 = TkPhotoImage.new
- img2.copy(img, :subsample=>[2,2])
- img.delete
- img = img2
- end
-
- if img.width * img.height > 20000
- b = TkPhotoImage.new(:width=>img.width, :height=>img.height)
- @big_imgs[b] = img
- img = b
- Tk.after_idle(proc{ move_big_image(b) })
- end
+#
+# This routine is called for every <SCRIPT> markup
+#
+script_cmd = proc{|*args|
+ # puts "ScriptCmd: #{args.inspect}"
+}
- @images[fn] = img
+# This routine is called for every <APPLET> markup
+#
+applet_cmd = proc{|w, arglist|
+ # puts "AppletCmd: w=#{w} arglist=#{arglist}"
+ #TkLabel.new(w, :text=>"The Applet #{w}", :bd=>2, :relief=>raised)
+}
- img
+# This binding fires when there is a click on a hyperlink
+#
+href_binding = proc{|w, x, y|
+ lst = w.href(x, y)
+ unless lst.empty?
+ process_url.call(lst)
end
+}
- #
- # This routine is called for every <SCRIPT> markup
- #
- def script_cmd(*args)
- # puts "ScriptCmd: #{args.inspect}"
+#
+#
+last_dir = Dir.pwd
+sel_load = proc{
+ filetypes = [
+ ['Html Files', ['.html', '.htm']],
+ ['All Files', '*']
+ ]
+
+ f = Tk.getOpenFile(:initialdir=>last_dir, :filetypes=>filetypes)
+ if f != ''
+ load_file.call(f)
+ last_dir = File.dirname(f)
end
+}
- # This routine is called for every <APPLET> markup
- #
- def applet_cmd(w, arglist)
- # puts "AppletCmd: w=#{w} arglist=#{arglist}"
- #TkLabel.new(w, :text=>"The Applet #{w}", :bd=>2, :relief=>raised)
+# Clear the screen.
+#
+clear_screen = proc{
+ if html_fs && html_fs.exist?
+ w = html_fs
+ else
+ w = html
end
-
- # This binding fires when there is a click on a hyperlink
- #
- def href_binding(w, x, y)
- lst = w.href(x, y)
- unless lst.empty?
- process_url(lst)
- end
+ w.clear
+ old_imgs.clear
+ big_imgs.clear
+ hotkey.clear
+ images.each{|k, v| old_imgs[k] = v }
+ images.clear
+}
+
+# Read a file
+#
+read_file = proc{|name|
+ begin
+ fp = open(name, 'r')
+ ret = fp.read(File.size(name))
+ rescue
+ ret = nil
+ fp = nil
+ Tk.messageBox(:icon=>'error', :message=>"fail to open '#{name}'",
+ :type=>:ok)
+ ensure
+ fp.close if fp
end
+ ret
+}
- #
- #
- def sel_load
- filetypes = [
- ['Html Files', ['.html', '.htm']],
- ['All Files', '*']
- ]
-
- f = Tk.getOpenFile(:initialdir=>@last_dir, :filetypes=>filetypes)
- if f != ''
- load_file(f)
- @last_dir = File.dirname(f)
- end
+# Process the given URL
+#
+process_url = proc{|url|
+ case url[0]
+ when /^file:/
+ load_file.call(url[0][5..-1])
+ when /^exec:/
+ Tk.ip_eval(url[0][5..-1].tr('\\', ' '))
+ else
+ load_file.call(url[0])
end
+}
- # Clear the screen.
- #
- def clear_screen
- if @html_fs && @html_fs.exist?
- w = @html_fs
- else
- w = @html
- end
- w.clear
- @old_imgs.clear
- @big_imgs.clear
- @hotkey.clear
- @images.each{|k, v| @old_imgs[k] = v }
- @images.clear
+# Load a file into the HTML widget
+#
+last_file = ''
+
+load_file = proc{|name|
+ return unless (doc = read_file.call(name))
+ clear_screen.call
+ last_file = name
+ if html_fs && html_fs.exist?
+ w = html_fs
+ else
+ w = html
end
+ w.configure(:base=>name)
+ w.parse(doc)
+ w.configure(:cursor=>'top_left_arrow')
+ old_imgs.clear
+}
- # Read a file
- #
- def read_file(name)
- begin
- fp = open(name, 'r')
- ret = fp.read(File.size(name))
- rescue
- ret = nil
- fp = nil
- Tk.messageBox(:icon=>'error', :message=>"fail to open '#{name}'",
- :type=>:ok)
- ensure
- fp.close if fp
- end
- ret
+# Refresh the current file.
+#
+refresh = proc{|*args|
+ load_file.call(last_file) if last_file
+}
+
+# This routine is called whenever a "<meta>" markup is seen.
+#
+meta = proc{|w, tag, alist|
+ v = Hash[*simplelist(alist)]
+
+ if v.kye?('key') && v.key?('href')
+ hotkey[v['key']] = w.resolve(v['href'])
end
- # Process the given URL
- #
- def process_url(url)
- case url[0]
- when /^file:/
- load_file(url[0][5..-1])
- when /^exec:/
- Tk.ip_eval(url[0][5..-1].tr('\\', ' '))
- else
- load_file(url[0])
- end
+ if v.kye?('next')
+ hotkey['Down'] =v['next']
end
- # Load a file into the HTML widget
- #
- def load_file(name)
- return unless (doc = read_file(name))
- clear_screen()
- @last_file = name
- if @html_fs && @html_fs.exist?
- w = @html_fs
- else
- w = @html
- end
- w.configure(:base=>name)
- w.parse(doc)
- w.configure(:cursor=>'top_left_arrow')
- @old_imgs.clear
+ if v.kye?('prev')
+ hotkey['Up'] =v['prev']
end
- # Refresh the current file.
- #
- def refresh(*args)
- load_file(@last_file) if @last_file
+ if v.kye?('other')
+ hotkey['o'] =v['other']
end
+}
- # This routine is called whenever a "<meta>" markup is seen.
- #
- def meta(w, tag, alist)
- v = Hash[*simplelist(alist)]
+# Go from full-screen mode back to window mode.
+#
+fullscreen_off = proc{
+ fswin.destroy
+ root.deiconify
+ Tk.update
+ root.raise
+ html.clipwin.focus
+ clear_screen.call
+ old_imgs.clear
+ refresh.call
+}
+
+# Go from window mode to full-screen mode.
+#
+fullscreen = proc{
+ if fswin && fswin.exist?
+ fswin.deiconify
+ Tk.update
+ fswin.raise
+ return
+ end
- if v.key?('key') && v.key?('href')
- @hotkey[v['key']] = w.resolve(v['href'])
- end
+ width = root.winfo_screenwidth
+ height = root.winfo_screenheight
+ fswin = TkToplevel.new(:overrideredirect=>true,
+ :geometry=>"#{width}x#{height}+0+0")
+
+ html_fs = Tk::HTML_Widget.new(fswin, :padx=>5, :pady=>9,
+ :formcommand=>form_cmd,
+ :imagecommand=>proc{image_cmd.call(0)},
+ :scriptcommand=>script_cmd,
+ :appletcommand=>applet_cmd,
+ :hyperlinkcommand=>hyper_cmd,
+ :bg=>'white', :tablerelief=>:raised,
+ :appletcommand=>proc{|*args|
+ run_applet('big', *args)
+ },
+ :fontcommand=>pick_font_fs,
+ :cursor=>:tcross) {
+ pack(:fill=>:both, :expand=>true)
+ token_handler('meta', proc{|*args| meta.call(self, *args)})
+ }
+
+ clear_screen.call
+ old_imgs.clear
+ refresh.call
+ Tk.update
+ html_fs.clipwin.focus
+}
- if v.key?('next')
- @hotkey['Down'] =v['next']
- end
+#
+#
+key_block = false
- if v.key?('prev')
- @hotkey['Up'] =v['prev']
- end
+key_press = proc{|w, keysym|
+ return if key_block
+ key_block = true
+ Tk.after(250, proc{key_block = false})
- if v.key?('other')
- @hotkey['o'] =v['other']
+ if hotkey.key?(keysym)
+ process_url.call(hotkey[keysym])
+ end
+ case keysym
+ when 'Escape'
+ if fswin && fswin.exist?
+ fullscreen_off.call
+ else
+ fullscreen.call
end
end
+}
- # Go from full-screen mode back to window mode.
- #
- def fullscreen_off
- @fswin.destroy
- @root.deiconify
- Tk.update
- @root.raise
- @html.clipwin.focus
- clear_screen()
- @old_imgs.clear
- refresh()
- end
+Tk::HTML_Widget::ClippingWindow.bind('1', key_press, '%W Down')
+Tk::HTML_Widget::ClippingWindow.bind('3', key_press, '%W Up')
+Tk::HTML_Widget::ClippingWindow.bind('2', key_press, '%w Down')
- # Go from window mode to full-screen mode.
- #
- def fullscreen
- if @fswin && @fswin.exist?
- @fswin.deiconify
- Tk.update
- @fswin.raise
- return
- end
+Tk::HTML_Widget::ClippingWindow.bind('KeyPress', key_press, '%W %K')
- width = @root.winfo_screenwidth
- height = @root.winfo_screenheight
- @fswin = TkToplevel.new(:overrideredirect=>true,
- :geometry=>"#{width}x#{height}+0+0")
-
- @html_fs = Tk::HTML_Widget.new(@fswin, :padx=>5, :pady=>9,
- :formcommand=>proc{|*args|
- form_cmd(*args)
- },
- :imagecommand=>proc{|*args|
- image_cmd(0, *args)
- },
- :scriptcommand=>proc{|*args|
- script_cmd(*args)
- },
- :appletcommand=>proc{|*args|
- applet_cmd(*args)
- },
- :hyperlinkcommand=>proc{|*args|
- hyper_cmd(*args)
- },
- :appletcommand=>proc{|*args|
- run_applet('big', *args)
- },
- :fontcommand=>proc{|*args|
- pick_font_fs(*args)
- },
- :bg=>'white', :tablerelief=>:raised,
- :cursor=>:tcross) {
- pack(:fill=>:both, :expand=>true)
- token_handler('meta', proc{|*args| meta(self, *args)})
- }
-
- clear_screen()
- @old_imgs.clear
- refresh()
- Tk.update
- @html_fs.clipwin.focus
- end
- #
- #
- def key_press(w, keysym)
- return if @key_block
- @key_block = true
- Tk.after(250, proc{@key_block = false})
+############################################
+#
+# Build the half-size view of the page
+#
+menu_spec = [
+ [['File', 0],
+ ['Open', sel_load, 0],
+ ['Full Screen', fullscreen, 0],
+ ['Refresh', refresh, 0],
+ '---',
+ ['Exit', proc{exit}, 1]]
+]
+
+mbar = root.add_menubar(menu_spec)
+
+html = Tk::HTML_Widget.new(:width=>512, :height=>384,
+ :padx=>5, :pady=>9,
+ :formcommand=>form_cmd,
+ :imagecommand=>proc{|*args|
+ image_cmd.call(1, *args)
+ },
+ :scriptcommand=>script_cmd,
+ :appletcommand=>applet_cmd,
+ :hyperlinkcommand=>hyper_cmd,
+ :fontcommand=>pick_font,
+ :appletcommand=>proc{|*args|
+ run_applet.call('small', *args)
+ },
+ :bg=>'white', :tablerelief=>:raised)
+
+html.token_handler('meta', proc{|*args| meta.call(html, *args)})
+
+vscr = html.yscrollbar(TkScrollbar.new)
+hscr = html.xscrollbar(TkScrollbar.new)
+
+Tk.grid(html, vscr, :sticky=>:news)
+Tk.grid(hscr, :sticky=>:ew)
+Tk.root.grid_columnconfigure(0, :weight=>1)
+Tk.root.grid_columnconfigure(1, :weight=>0)
+Tk.root.grid_rowconfigure(0, :weight=>1)
+Tk.root.grid_rowconfigure(1, :weight=>0)
+
- if @hotkey.key?(keysym)
- process_url(@hotkey[keysym])
- end
- case keysym
- when 'Escape'
- if @fswin && @fswin.exist?
- fullscreen_off()
- else
- fullscreen()
- end
- end
- end
-end
############################################
-TkHTML_File_Viewer.new(file)
+html.clipwin.focus
+
+# If an arguent was specified, read it into the HTML widget.
+#
+Tk.update
+if file && file != ""
+ load_file.call(file)
+end
+
+############################################
Tk.mainloop
diff --git a/ext/tk/sample/tkextlib/tkimg/demo.rb b/ext/tk/sample/tkextlib/tkimg/demo.rb
deleted file mode 100644
index a0c4d1b64f..0000000000
--- a/ext/tk/sample/tkextlib/tkimg/demo.rb
+++ /dev/null
@@ -1,1478 +0,0 @@
-#!/usr/bin/env ruby
-#
-# Tk::Img demo
-#
-# -- This script is based on demo.tcl of Tcl/Tk's 'Img' extention.
-# Image data in this script is those of demo.tcl.
-# Please read 'license_terms_of_Img_extension' file.
-#
-require 'tk'
-require 'tkextlib/tkimg'
-
-#
-# Make the Image format available.
-#
-class TkImg_demo
- def initialize
- img_version = Tk::Img.package_version
-
- @typeFrame = Hash.new
- @imgPriv = Hash.new
-
- root = TkRoot.new(:title=>'Tests for available image formats')
-
- root.winfo_children.each{|w| w.destroy}
- TkImage.names{|img| img.delete}
-
- f = TkFrame.new
- TkButton.new(f, :text=>'Dismiss', :command=>proc{exit}).pack(:side=>:left)
- f.pack(:side=>:top, :expand=>:y, :fill=>:both)
-
- TkMessage.new(:aspect=>900, :text=>format('This page shows the available image formats of the Img extension (Img version %s, using Tcl/Tk %s)', img_version, Tk::TK_PATCHLEVEL)).pack(:side=>:top, :expand=>:y, :fill=>:both)
- end
-
-##############################
-
- def update_animated_gif(w, method, num)
- return unless @imgPriv[w]
-
- if @imgPriv[w][:args]
- im = TkPhotoImage.new
- im.copy(@imgPriv[w][num])
- num += 1
- begin
- im.configure(@imgPriv[w][:args].merge(:format=>[:gif, {:index=>num}]))
- im.configure(:data=>'', :file=>'') #free storage
- @imgPriv[w][num] = im
- rescue
- @imgPriv[w].delete(:args)
- if num > 1
- num = 0
- im = @imgPriv[w][num]
- else
- # this is not an animated GIF; just stop
- @imgPriv[w].delete(0)
- return
- end
- end
- else
- num += 1
- num = 0 unless @imgPriv[w][num]
- im = @imgPriv[w][num]
- end
- begin
- w.__send__(method, im)
- Tk.update_idletasks
- Tk.after(20, proc{update_animated_gif(w, method, num)})
- rescue
- @imgPriv[w].delete(:args)
- @imgPriv[w].each{|im|
- @im.delete
- @imgPriv.delete(im)
- }
- end
- end
-
- def show_animated_gif(keys)
- w = TkLabel.new
- begin
- im = TkPhotoImage.new(keys.merge(:format=>[:gif, {:index=>0}]))
- im.configure(:data=>'', :file=>'', :format=>'') #free storage
- w.image(im)
- @imgPriv[w] ||= Hash.new
- @imgPriv[w][0] = im
- @imgPriv[w][:args] = keys
- Tk.update_idletasks
- Tk.after(20, proc{update_animated_gif(w, :image, 0)})
- rescue => e
- w.configure(:text=>"error displaying animated gif:\n#{e.message}",
- :image=>'', :relief=>:ridge)
- end
- w.pack
- end
-
- def show_image(fmt, type, data)
- fmt = fmt.to_s.capitalize
- unless @typeFrame[fmt]
- @typeFrame[fmt] = TkFrame.new.pack(:side=>:top, :expand=>true, :fill=>:x)
- TkLabel.new(@typeFrame[fmt], :text=>"#{fmt} : ").pack(:side=>:left)
- end
- begin
- f = TkFrame.new(@typeFrame[fmt],
- :borderwidth=>2, :relief=>:ridge).pack(:side=>:left)
- im = TkPhotoImage.new(:data=>data)
- im['data'] = ''
- TkLabel.new(f, :image=>im).pack
- TkLabel.new(f, :text=>type, :borderwidth=>0, :pady=>0, :padx=>2,
- :font=>'Helvetica 8').pack
- rescue => e
- TkMessage.new(f, :text=>"error displaying #{type} image: #{e.message}",
- :aspect=>250).pack
- end
- Tk.update
- end
-
-end
-
-##############
-
-demo = TkImg_demo.new
-
-##############
-
-demo.show_animated_gif(:data=><<'ENDofIMG')
-R0lGODlhYgIEAIIAAQAAACQAJEkASW0AbZIAkrYAttsA2/8A/yH/C05FVFNDQVBFMi4wAwEA
-AAAh+QQABgD/ACwAAAAAYgIEAAIDuUg63CMwwiCCvQAHwLv/YCiOZGmeaKqubOu+pZXNV03d
-kuAwysLoucjNlpFtYMikcslsOp+ijbRow1EiD12jtyA4INnJZGg8HmfQtHrNbrPP6KqlEgRq
-B17vzi6ukKVmHXBuhIWGh4RTcXJ0QQ8OeVx6XzlWVTRoiJqbnJ0tGmUXdDhgd1uTP2FCo5dT
-g56wsbKaoYBzVlimPJJ7QX9EirPCw8RttTZ1ul29Er81mMXR0tMvxzXJO1wAACH5BAAGAP8A
-LAAAAABiAgQAAgPdCLrc/jDKSau9OOuNAwjgB46kEJjnKazr0A5wTBDDbBc4buz74f/AoHBI
-LBqPSCGPh7M5abQYTOBysVYprAlFCo0+YI9CzCmbz+i0es1uu9/wOFrsqYtE3S73yq9SpTBP
-BDk5PEmHiImKRQYHTISDNjWTMX9UfFuZIFwkY3RhcqGio6SlpqeoqRt2dXmuWyqZV1Z/UjM1
-ToQFS46Lvr/AQUu6BYK4gJe0V7Eprl+sXqrS09TV1tfYbKxhziqxmFOAgYKDOrs9wenqSY07
-uznklFKXmCzN3aB22fv81AAAIfkEAAYA/wAspgAAABgBBAACA+YIEQrNS61Jg1hX6C2GHiBI
-DERpFkShFkZrHHAsz3Rt06/Lrqk5jqFQ58PheI5B0s+HWrFch9dtSp26dDyULwnqeIoay+Qi
-rkAcZ4YDrVY/IOaxGGz0IkPLknN3rfr/MToGTilaJSRcR3RgikF5JyuDfYCUVFeDKj0mSkle
-Q4sYcXFvaA1rDxIScKIZYUVfiUA+PU6Tlbc4US07PJs/nYqLQ4kieZkqki24yzJXe5qziEHD
-dHNloqqpbqfcbquiGK2MH0mzkJG2zLfOhObSQsHC1OVKTLVQUurrWL1biZ9grIFLs2YbNwAh
-+QQABgD/ACyHAAAAVwEEAAID/ggQy94uyCloFTgPsYf/AyGOYmGaRnoYR+u+cCzPcZqeJyl6
-xMdhm4zwUgkUJ8iFkqFgKptQCQRJMRqJwqAPtCMVCDhDwcaimc9mslhs0vXeoJ9caL1Q748n
-tMl89PFURURXQx4cH11eYChjKmiPkC5kOGCVIyCYWkN2VoB8fXtOS34RgJybGkCZbosnZJGw
-aCw3bF9tXSFxhqhXnb5JSUt6CsKlxneDqHIdqyEjOI0qZbHUMGq1bs6Yh3NDdb93U1Ki41Hi
-poSEqYZcuYphr9XykjbQrLnbHbwYEkd4xQ2GERvoZxQ6LIUOrWLlKtq8h5Ps6ci0SxknQOVE
-Ddy4HvGPQVMIC1Hk4QZavIfUZq3J8YUEPl0WL3qaIIwjMQAh+QQABgD/ACxlAAAAmwEEAAID
-/ggRCr1qSSlWDVXorYfwQxgSxECSBVGsheEaB3zMdG3feF7DbsumJ5JJJPpwjhnLZMloPp4M
-h3RKrVqv2KxW2nRGmBQlBnP0dD7EYfDne8l08DjcbfgFhaW0cX8ciy9LD05RUREOhQ2GYEoa
-ZGQbIGlDJmsqPy9ymZo0PD11Kyp3anogfX5igamGh1utrq+uhFBQYBm2j5CSIncnLHWYm8Fx
-bj52QZOSSBeNp2BfEIVeU4PUi0mOSJFoaXcpvnTC4TnExiejRdrK2IsSgrKIsPHyr4OJ7GHL
-thxmkSN4vZdauIghriCnF2yAmBOCzoiZPkkAOav3JEs0d+z0ZdPFMgvFJWAGCxL7pPBYHiJ8
-TElcNGuey5cwW97Dp6yDpBK82LgJaXAki47IGqq7xm4WPCoAACH5BAAGAP8ALEYAAADZAQQA
-AgP+GKC7yiHKGYSo1Wo9xPgfMYhEWRZoYaiGcbxwLM90Tbf4ihKFSYqgjnBDjFwuGMoD0Fgy
-n9CodEqtWq/YrHa7hTgaTSXySCZ6PMFQyJdC5Vy2uFz+VqV8pFH6czYfM0pKYF4MYE0OD4ET
-Y4BEfHt6eDt2OAdwc5iZLzhtO3iQIBYdGhgWpYoTYUxOXK2ur7CxrV5fqBR/GWZDaT9sPG4s
-l5rDNi4tdpOfQGlno6SmSEkUiISDT4mJtYpkubq7Qb0mbSuVwsTnmzltPJ96oY9+uNGKiLWy
-9/j5+l3YqrZl3UT12YPnxLg36BLCULdOmbt38bjNC3TISSEqSyRQE1M8yo8QXiMk/XJTSaFC
-hg19gIp4auI0Vhf3yZxJUx8EbP/K6EIDLqSvgy1MJlSno0cPlcsg+gEkTZBGVlMAACH5BAAG
-AP8ALCYAAAAXAgQAAgP+CAHaHQtKKGioV+itRx/gQIBESRTnWRRGexhHLM90bd9127Jrao7A
-kMfDKVommMnisYwwHM+odEqtWq/YrHbL7Xq/YIaTCVEoj5YiZ8gmiX6l1UrnguHu+DvdIEeh
-4EJsAkRqGBoXZxJmEU2NYo9mYoyJFRwZG22Bbz99LHR5oKEydDxyPiUimiCDrIeViK9ni4wP
-kGG3uLm6u7y9tmO1iRKuGZeYmUDJJn18OqLPoKQ9fyZuga2Er4fCioqRTVFlZWTcxJVFQx9u
-yioqPM7Q8TbSptRBI0KthRvF3OLitnwJHEiwoMErk5jMOmMIVqFMIdjFmeMJhh15GF/o6HRK
-qhq+VayyWYLlr5GTcVjAlTS0DyIJOBPlfMqI0WKzeoA+htCnph+3SFAOCh1KtGivk/+EnWs5
-KJDEFMzg0ZS3BydMVSL5aStJ6woAIfkEAAYA/wAsBwAAAFUCBAACA/4ICqEd8MUJRQ0i65GH
-F55HEMM4FkShFgZrHHAsz3Rt10aer6s5lqEQqKPRYI6WI+XBYDYYi+diSq1ar9isdsvter/g
-sHhMLkebUEhziUkai8ROMOQ78Vy6m37Pf+1aPXUlJEJCcG9ubGpOaWlPUowSSxYZbW1FHCBz
-g3V3eC98oaIwfi07KCkmQIQfH4eUsBdLa4tnUma4ubq7vL2+v1mPUGiKE7GVh4V0Pz53pjmj
-0X06LD2oqqxBG4dKiRS0TrdTkcURlBWwmJqaIqsmqDw6oNL0NPKeddnaHJlwl0qKGgkTB6yg
-wYMIEyq8Qm5RsXOW4PCbGIREp3jy5tXbWE4KUCBsm4aI5HYuSUBJDoZZgQTu4aVkm5ZdVCFv
-o01SB/589AFkzshXAE8KXEi0qNGjSMlEajnpJcxN+exUy3OTIzUeUXvue4WsXC0mWAAAIfkE
-AAYA/wAsAAAAAGICBAACA/4YotIuA8JBKxkk60KKN6BxiEdpnmiqrmhoeF6naVXdRI/DBAq/
-8MAAQDgsEgHIpHLJbDqf0Kh0Sq1ar9isdsvterdEIW8IJAfPv0XOEalZZjJYwcWq2++i0Fwu
-m2HcbWs5PWoMgm01F4obci90d5CRJS5yHBw0GX8UEpw6D4RnY0FGYUVfp6ipqqusra6vXKVk
-pqFBhYM5gYkYcJWOIZLBdnovMH2YbjcSOLc+hA2GyoB/cBmWe8DC2ivExpdw05vMn4W1o2Wi
-sOrr7O3u7/BVoujz5mrQhxNuF7zWHTCPtgmcNALEHmPg+NnohOvHs3yILPRjBBAYiYHaXBRD
-6CtnmiBP5mqZGhmvpMmTKFOqbBJGTEgg+D5GlFjt2pyAGIVR4lNNU7JxnhwCACH5BAAGAP8A
-LAAAAABiAgQAAgPtWLZ7/jDKSaU5rOhCuu9DKA5CKJRnGgjB6rJt3AIxDdzBbet87//AoHBI
-LBqPyKRyyWw6n9CodOrL8ay5rFa2YsG8qRNJXAoRRB8CZ6NgYCrweJxhUNjd8rz+QWevPwMg
-ImUoYWEtX1wzNFg2jVSQkZKTlJWWl5iZTo+OW4qIMYZhJKQjgWlqbHQXe61wFwt2bQ2utROw
-sX6oZqYoY4YvLp81WY47msjJysvMzc7PxjPEw2DVKWOmvKceaxurtuB8GLl1Dazhtn0bqGdn
-vb/AXsPE0dD29/j5+vvLVtHzJ7qIKpSNXSpVtNCly1AAACH5BAAGAP8ALAAAAABiAgQAAgPV
-eLq8diYWUwqxJJOx9/iDEIpCaZpBmQZs6wYAC8QwPd94ru987//AoHBILBqPyKRyyWw6n9Ao
-Elaj0l4tlYC1PZVCoHBnnLFUJpF0Y81uOyCTc0Wj4YRBJO9qu8LKqjaAUoOEhYaHiImKi4yN
-TzUxN1STflxZXiZgInccdGZyaQ9uo24PoXFmdHacJCOYKXx8lZRXM5COuLm6u7y9vr+KtJSz
-e1perpwZnRqfaGqk0GunZxd0yh54mq8qxFaRwODh4uPk5eaEVVbdxpibm3fWZXLOotEAADs=
-ENDofIMG
-
-demo.show_image('bmp', '1-bit', <<'ENDofIMG')
-Qk3OAQAAAAAAAD4AAAAoAAAAIgAAADIAAAABAAEAAAAAAJABAABtCwAAbQsAAAIAAAACAAAA
-MzPMAMwzMwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
-AAAAAAAAAAAAAAZmTKAAAAAABIRIwAAAAAAEZAigAAAAAAQECIAAAAAAAAAAgAAAAAAAAEAA
-AAAAAAABQAAAAAAAAAPAAAAAAAAAB+AAAAAAAAAC4AAAAAAAAALgAAAAAAAAAsAAAAAAAAAC
-wAAAAAAAAALgAAAAAAAABuAAAAAAAAAG4AAAAAAAAAbgAAAAAAAABuAAAAAAAAAG4AAAAAAA
-AAfgAAAAAAAAA+AAAAAAAAADcAAAAAAAAAPwAAAAAAAAA/AAAAAAAAAD+AAAAAAAAAP4AAAA
-AAAAA/gAAAAAAAAD4AAAAAAAAAHgAAAAAAAAAfAAAAAAAAAA+AAAAAAAAAB8AAAAAAAAADgA
-AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
-AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
-ENDofIMG
-
-demo.show_image('bmp', '4-bit', <<'ENDofIMG')
-Qk1aBAAAAAAAAHIAAAAoAAAAIgAAADIAAAABAAQAAAAAAOgDAABtCwAAbQsAAA8AAAAPAAAA
-////AAD//wDMzP8AmZn/AGaZ/wAzM8wAmZnMAGaZzAAzZswAzMyZAJmZmQDMZjMAZjNmADMz
-ZgBmMzMABWMgAAAAAAAAAAAAAAAAAAAAAAAFVVVVVVVVVVVVVVVVVVVVUAAAAAVVVVVVVVVV
-VVVVVVVVVVVQAAAABVVVVVVVVVVVVVVVVVVVVVAAAAAFVVVVVVVVVVVVVVVVVVVVUAAAAAVV
-VVVVVVVVVVVVVVVVVVWAAAAABVVVVVVVVVVVVVVVVVVVVVAAAAAFVVBVU3VSVVNVB1UFBVVV
-UAAAAAVVUFU1VVNVVVUFVQBVVVVgAAAABVVQVVUFU1VVVQVVBVVVVTAAAAAIVVBVVVVTVXVV
-BVUFVVVVMAAAAAVVVVVVVVFVFVVVVQVVVVUgAAAABVVVVVVVVVUFVVVVVVVVVSAAAAAHVVVV
-VVVVW5tVVVVVVVVVAAAAAAZVVVVVVVW8u2VVVVVVVVUAAAAAA1VVVVVVW7W7tVVVVVVVVQAA
-AAADVVVVVVWCtbuzVVVVVVVVAAAAAANVVVVVVVW1vrJVVVVVVVUAAAAAAlVVVVVVWLW7UFVV
-VVVVVQAAAAACVVVVVVVatbtVVVVVVVVVAAAAAABVVVVVVVq3u8NVVVVVVVUAAAAAAFVVVVVV
-XrS74VVVVVVVVQAAAAAAVVVVVVWLtbuyVVVVVVVVAAAAAABVVVVVVUu1u7BVVVVVVVUAAAAA
-AFVVVVVVO7W7sFVVVVVVVQAAAAAAVVVVVVUbtbu6VVVVVVVVAAAAAABVVVVVVSu9u1VVVVVV
-VVUAAAAAAFVVVVVVJb67tVVVVVVVVQAAAAAAVVVVVVVVu6u7VVVVVVVVAAAAAABVVVVVVVW7
-u7slVVVVVVUAAAAAAFVVVVVVVbu7u1VVVVVVVQAAAAACVVVVVVVVu7u7wlRVVVVVAAAAAAJV
-VVVVVVW7u7uwV1VVVVUAAAAAA1VVVVVVVbu7u7BVhVVVVSAAAAADVVVVVYVVu7vFAFUVVVVV
-MAAAAAZVVVVVhVUbu7VVVRVXVVVgAAAAB1VVVVVVVVu7u1VVFVFVVVAAAAAFVVVVVVhVVLu7
-xVVVVVVVgAAAAAVVVVVVUVVVK7u1VVVVVVVQAAAACFVVVVhRVVVQq7VVVVVVVVAAAAAFVVVV
-VFV1VVUgBVVVVVVVUAAAAAVVVVVUVRVVVVVVVVVVVVVQAAAABVVVVViFUVVVVVVVVVVVVVAA
-AAAFVVVVVRVUFVVVVVVVVVVVUAAAAAVVVVVVVVVVVVVVVVVVVVVQAAAABVVVVVVVVVVVVVVV
-VVVVVVIAAAAFVVVVVVVVVVVVVVVVVVVVUQAAAAVVVVVVVVVVVVVVVTdVVVVWAAAAAAAhNnWF
-VVVVVVcAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA==}
-ENDofIMG
-
-if false
-demo.show_image('bmp', '4-bit-RLE', <<'ENDofIMG')
-Qk1sAwAAAAAAAHYAAAAoAAAAIgAAADIAAAABAAQAAgAAAPYCAAAAAAAAAAAAABAAAAAQAAAA
-////AMzM/wAA//8AmZn/AJmZzABmmcwAMzPMADNmzABmmf8AmZmZAMxmMwBmM2YAZjMzADMz
-ZgDMzJkAAAAAAAAGBkMQABwAAAACBh5mAmAAAAIGHmYCYAAAAgYeZgJgAAACBh5mAmAAAAIG
-HmYCcAAAAgYeZgJgAAAAIgZmYGZjVmFmY2YFZgYGZmZgAAAAACIGZmBmNmZjZmZmBmYAZmZm
-QAAAAAAiBmZgZmYGY2ZmZgZmBmZmZjAAAAAAIgdmYGZmZmNmVmYGZgZmZmYwAAAAAgYKZgAW
-YmYmZmZmBmZmZhAAAAACBg5mAgYOZgIQAAACBQxmAARq6g5mAgAAAAIEDGYABquqRgAMZgIA
-AAACAwpmAAhqpqqmDGYCAAAAAgMKZgAIcaaqowxmAgAAAAIDDGYABqasoQAMZgIAAAACAQpm
-AAhnpqpgDGYCAAAAAgEKZgAGaaaqAA5mAgAAAAIACmYACGmlqrMMZgIAAAACAApmAAhsqKrC
-DGYCAAAAAgAKZgAIeqaqoQxmAgAAAAIACmYACIqmqqAMZgIAAAACAApmAAg6pqqgDGYCAAAA
-AgAKZgAIKqaqqQxmAgAAAAIACmYABhqtqgAOZgIAAAACAApmAAgWrKqmDGYCAAAAAgAMZgAG
-qpqqAAxmAgAAAAIADGYACKqqqhYKZgIAAAACAAxmAAaqqqoADGYCAAAAAgEMZgAKqqqqsWgA
-CGYCAAAAAgEMZgAKqqqqoGUACGYCAAAAAgMMZgAUqqqqoGZ2ZmZmEAAAAgMIZgAYdmaqqrYA
-ZiZmZmYwAAACBAhmABh2ZiqqpmZmJmVmZkAAAAIFDGYAFGqqqmZmJmJmZmAAAAIGCGYADGdm
-aKqqtgpmAnAAAAIGCGYADGJmZhqqpgpmAmAAAAAWB2ZmZmdiZmZgmqYACmYCYAAAABYGZmZm
-aGZWZmYQBgAKZgJgAAAADgZmZmZoZiYAEmYCYAAAAA4GZmZmZ3ZiABJmAmAAAAIGCGYABiZo
-JgAQZgJgAAACBh5mAmAAAAIGHmYCYQAAAgYeZgJiAAACBhZmAAo1ZmZmZAAAAAAMAAASNFZ2
-CGYCZQwAAAAiAAAB
-ENDofIMG
-end
-
-demo.show_image('bmp', '8-bit', <<'ENDofIMG')
-Qk0CCAAAAAAAAPoAAAAoAAAAIgAAADIAAAABAAgAAAAAAAgHAABtCwAAbQsAADEAAAAxAAAA
-////AMz//wAA//8AzMz/AJnM/wAAzP8AmZn/AGaZ/wAAmf8AZmb/ADNm/wAzM/8A/8zMAMzM
-zACZmcwAZpnMAACZzABmZswAM2bMAABmzAAzM8wAADPMAAAAzAD/zJkAzMyZAMyZmQCZmZkA
-ZmaZAGYzmQAzM5kAzJlmAJlmZgBmZmYAZjNmADMzZgDMmTMAmWYzAJkzMwBmMzMAmWYAAJkz
-AAAAAN0A7u7uAN3d3QC7u7sAqqqqAIiIiAB3d3cAVVVVAAARDgYDKgAAAAAAAAAAAAAAAAAA
-AAAAAAAAAAAAAAAAAAAAAAAVFRUVFRUVFRUVFBQUFBQUFRUVFRUVFRUVFRUVFRUVFQAAAAAV
-FRUVFRUVFRUVFRUVFRUVFRUVFRUVFRUVFRUVFRUVFQAAAAAVFRUVFRUVFRUVFRUVFRUVFRUV
-FRUVFRUVFRUVFRUVFAAAAAAVFRUVFRUVFRUVFRUVFRUVFRUVFRUVFRUVFRUVFRUVFAAAAAAV
-FRUVFRUVFRUVFRUVFRUVFRUVFRUVFRUVFRUVFRUVEgAAAAAVFRUVFhUVFRYVFRUWFRUVERUV
-FhUVFRYVFhUVFRUVEQAAAAAUFRUWABEVFQYPFhUDERUWBhUVKg8VFAAUABQVFRUVEQAAAAAU
-FRUWABYVBhQWFRUGFBUWERUWABYVFgAAFRUVFRUVDgAAAAAUFRUVABUVFBEAFhUGFBUUFRUV
-ABUVFgARFRUVFRUVBgAAAAASFRUWABUVFRUVFRUGFBUPFhUWABYVFgAVFBUVFRUVBgAAAAAR
-FRUVFhUVFRUVFRUEFBUEFhUVFhUVFQAWFRUVFRUVAwAAAAARFRUVFRUVFRUVFRUVFRUrHRUV
-FRUVFRUVFRUVFRUVAwAAAAAPFRUVFRUVFRUVFRUVFCQYKBUVFRUVFRUVFRUVFRUVKgAAAAAO
-FRUVFRUVFRUVFRUUJyEeKA4VFRUVFRUVFRUVFRUVAAAAAAAGFRUVFRUVFRUVFRYeKB0kKCQU
-FRUVFRUVFRUVFRUVAAAAAAAGFRUVFRUVFRUVFRIDKBQnKCgGFRUVFRUVFRUVFRUVAAAAAAAG
-FRUVFRUVFRUVFRUVJxEnJigDFRUVFRUVFRUVFRUVAAAAAAADFRUVFRUVFRUVFRUSKBEnKAkq
-FRUVFRUVFRUVFRUVAAAAAAADFRUVFRUVFRUVFRUuJxEoKBEWFRUVFRUVFRUVFRUVAAAAAAAr
-FRUVFRUVFRUVFRYvKA8oKCEGFRUVFRUVFRUVFRUVAAAAAAAqFRUVFRUVFRUVFRQmKAcoKCYE
-FRUVFRUVFRUVFRUVAAAAAAAAFRUVFRUVFRUVFRIoJwkoKCgDFRUVFRUVFRUVFRUVAAAAAAAA
-FRUVFRUVFRUVFQcoJxEnKCgBFRUVFRUVFRUVFRUUAAAAAAAAFRUVFRUVFRUVFQYoKBQnKCgq
-FhUVFRUVFRUVFRUUAAAAAAAAFRUVFRUVFRUVFQQoKBQkKCgsFhUVFRUVFRUVFRUUAAAAAAAA
-FRUVFRUVFRUVFQMkKCIjKB0RFRUVFRUVFRUVFRUUAAAAAAAAFRUVFRUVFRUVFQMUKCYeKCgV
-FRUVFRUVFRUVFRUVAAAAAAAAFRUVFRUVFRUVFRUVKCgaKCgnFRUVFRUVFRUVFRUVAAAAAAAA
-FRUVFRUVFRUVFRUUKCgkKCgoAxYVFRUVFRUVFRUVAAAAAAArFRUVFRUVFRUVFRURKCgoKCgo
-ERQVFRUVFRUVFRUVAAAAAAADFRUVFRUVFRUVFRURKCgoKCgoIQMWCBUVFRUVFRUVAAAAAAAD
-FRUVFRUVFRUVFRURKCgoKCgoKAAWEBYVFRUVFRUVKgAAAAAGFRUVFRUVFRUVFRUUJygoKCgo
-KAAWFRMVFRUVFRUVAwAAAAAGFRUVFRUVFRUTFhUWHigoKCEUKgAWFgIVFRUVFRUVBgAAAAAO
-FRUVFRUVFRUTFRUVBCgoKCgUFRYVFgIWFRAWFRUVDgAAAAAPFRUVFRUVFRUVFRUVFR4oKCgo
-FRUVFQIVFQUVFRUVEQAAAAARFRUVFRUVFRUVExUVFQckKCgoIRUVFRYVFRUVFRUVEgAAAAAR
-FRUVFRUVFRUWAhYVFRYDJygoKB0VFRUVFRUVFRUVFAAAAAASFRUVFRUVFRMVBRUVFRUWKhko
-KBQVFRUVFRUVFRUVFQAAAAAUFRUVFRUVFQgWFRAVFRUVFgMAKxYVFRUVFRUVFRUVFQAAAAAU
-FRUVFRUVFQgWFQIWFRUVFRUWFhUVFRUVFRUVFRUVFQAAAAAUFRUVFRUVFRMTFRUFFhUVFRUV
-FRUVFRUVFRUVFRUVFQAAAAAVFRUVFRUVFRYFFhUIAhYVFRUVFRUVFRUVFRUVFRUVFQAAAAAV
-FRUVFRUVFRUVFRUVFhUVFRUVFRUVFRUVFRUVFRUVFQAAAAAVFRUVFRUVFRUVFRUVFRUVFRUV
-FRUVFRUVFRUVFRUVFQMAAAAVFRUVFRUVFRUVFRUVFRUVFRUVFRUVFRUVFRUVFRUVFQQAAAAV
-FRUVFRUVFRUVFRUVFRUVFRUVFRUVFAYPEREUFBQVFQ4AAAAAACoDBAYODxESFBQVFRUVFRUV
-FQ8AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA==
-ENDofIMG
-
-if false
-demo.show_image('bmp', '8-bit-RLE', <<'ENDofIMG')
-Qk22CAAAAAAAADYEAAAoAAAAIgAAADIAAAABAAgAAQAAAIAEAAAAAAAAAAAAAAABAAAAAQAA
-////AO7u7gDMzP8Amcz/AJmZ/wCZmcwAZpnMAGZmzAAzZswAMzPMAAAzzAAAAMwAAMz/AACZ
-/wAA//8AAGbMAACZzADd3d0AzJmZAJkzAACZZgAAMzOZAGaZ/wCZZjMAZjNmAMyZZgCZmZkA
-ZjMzADMzZgDMmTMAu7u7AMz//wBmZv8Ad3d3AIiIiADMzJkAAAAAAAAAAAAAAAAAAAAAAAAA
-AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
-AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
-AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
-AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
-AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
-AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
-AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
-AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
-AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
-AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
-AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
-AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
-AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
-AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
-AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
-AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAG
-AAcFBAIBHAAAAAEACgoGCRAKAQAAAAEAIAoBAAAAAQAfCgEJAQAAAAEAHwoBCQEAAAABAB8K
-AQgBAAAAAQAECgAWCwoKCgsKCgoLCgoKBwoKCwoKCgsKCwUKAQcBAAAAABwACQoKCwAHCgoE
-BgsKAgcKCwQKCgEGCgkACQAJBAoBBwEAAAAAGgAJCgoLAAsKBAkLCgoECQoLBwoLAAsKCwAA
-BgoBBQEAAAAAGgAJCgoKAAoKCQcACwoECQoJCgoKAAoKCwAHBgoBBAEAAAAABgAICgoLAAcK
-AA4ECQoGCwoLAAsKCwAKCQUKAQQBAAAAAAYABwoKCgsHCgANAwkKAwsKCgsKCgoACwAGCgEC
-AQAAAAEAAQcOCgERARUOCgECAQAAAAEAAQYMCgAECRcjEw4KAQEBAAAAAQABBQsKAAYJFBgZ
-EwUNCgEAAQAAAAEAAQQKCgAICxkTFRcTFwkMCgEAAQAAAAEAAQQKCgAICAITCRQTEwQMCgEA
-AQAAAAEAAQQMCgAGFAcUGxMCDAoBAAEAAAABAAECCwoABwgTBxQTIAEADAoBAAEAAAABAAEC
-CwoAByIUBxMTBwsADAoBAAEAAAABAAERCgoACAshEwYTExgEDAoBAAEAAAABAAEBCgoACAkb
-ExYTExsDDAoBAAEAAAABAAEACgoACAgTFCATExMCDAoBAAEAAAABAAEACgoACBYTFAcUExMf
-CwoAAwkAAAAAAAEAAQAKCgAJBBMTCRQTEwELAAoKAAMJAAAAAAABAAEACgoACQMTEwkXExMe
-CwAKCgADCQAAAAAAAQABAAoKAAgCFxMcHRMVBwsKAAMJAAAAAAABAAEACgoABwIJExsZExMA
-DQoBAAEAAAABAAEADAoABhMTGhMTFAwKAQABAAAAAQABAAsKAAkJExMXExMTAgsACgoBAAEA
-AAABAAERCwoBBwYTAQcBCQoKAQABAAAAAQABAgsKAQcGEwAEGAILDQgKAQABAAAAAQABAgsK
-AQcHEwAEAAsQCwcKAQEBAAAAAQABBAsKAQkBFAYTAAQACwoPBwoBAgEAAAABAAEECAoADw8L
-CgsZExMTGAkBAAsLDgAHCgEEAQAAAAEAAQUICgAFDwoKCgMABBMADwkKCwoLDgsKEAsKCgoF
-AAAAAAEAAQYNCgEZBBMECgAEDgoKDAQKAQcBAAAAAQABBwkKAA4PCgoKFhcTExMYCgoKCwcK
-AQgBAAAAAQABBwgKAAwLDgsKCgsCFBMTExUKCgEJAQAAAAEAAQgHCgADDwoMAAQKAAYLARIT
-EwkLCgEAAAABAAEJBwoABA0LChAECgAFCwIAEQsACwoBAAAAAQABCQcKAAUNCwoOCwAFCgEL
-AQsMCgEAAAABAAEJBwoABg8PCgoMCxIKAQAAAAEACAoABwsMCwoNDgsAEQoBAAAAAQANCgEL
-EgoBAAAAAQAgCgECAAABACAKAQMAAAEAFgoACwkEBgcHCQkJCgoFAAAAAA0AAAABAgMEBQYH
-CAkJAAgKAQYMAAAAIgAAAQ==
-ENDofIMG
-end
-
-demo.show_image('bmp', '32-bit', <<'ENDofIMG')
-Qk2GFAAAAAAAADYAAAAoAAAAIgAAADIAAAABABgAAAAAAFAUAABtCwAAbQsAAAAAAAAAAAAA
-////ZmbMmZnMmZn/zMz/7u7u////////////////////////////////////////////////
-////////////////////////////////////////////////////////////////AAD///8A
-M8wAM8wAM8wAM8wAM8wAM8wAM8wAM8wAM8wAM8wzM8wzM8wzM8wzM8wzM8wzM8wAM8wAM8wA
-M8wAM8wAM8wAM8wAM8wAM8wAM8wAM8wAM8wAM8wAM8wAM8wAM8wAM8z///8AAP///wAzzAAz
-zAAzzAAzzAAzzAAzzAAzzAAzzAAzzAAzzAAzzAAzzAAzzAAzzAAzzAAzzAAzzAAzzAAzzAAz
-zAAzzAAzzAAzzAAzzAAzzAAzzAAzzAAzzAAzzAAzzAAzzAAzzP///wAA////ADPMADPMADPM
-ADPMADPMADPMADPMADPMADPMADPMADPMADPMADPMADPMADPMADPMADPMADPMADPMADPMADPM
-ADPMADPMADPMADPMADPMADPMADPMADPMADPMADPMMzPM////AAD///8AM8wAM8wAM8wAM8wA
-M8wAM8wAM8wAM8wAM8wAM8wAM8wAM8wAM8wAM8wAM8wAM8wAM8wAM8wAM8wAM8wAM8wAM8wA
-M8wAM8wAM8wAM8wAM8wAM8wAM8wAM8wAM8wzM8z///8AAP///wAzzAAzzAAzzAAzzAAzzAAz
-zAAzzAAzzAAzzAAzzAAzzAAzzAAzzAAzzAAzzAAzzAAzzAAzzAAzzAAzzAAzzAAzzAAzzAAz
-zAAzzAAzzAAzzAAzzAAzzAAzzAAzzDNmzP///wAA////ADPMADPMADPMADPMAADMADPMADPM
-ADPMAADMADPMADPMADPMAADMADPMADPMADPMZmbMADPMADPMAADMADPMADPMADPMAADMADPM
-AADMADPMADPMADPMADPMADPMZmbM////AAD///8zM8wAM8wAM8wAAMz///9mZswAM8wAM8yZ
-mf9mmcwAAMwAM8zMzP9mZswAM8wAAMyZmf8AM8wAM8zu7u5mmcwAM8wzM8z///8zM8z///8z
-M8wAM8wAM8wAM8wAM8xmZsz///8AAP///zMzzAAzzAAzzAAAzP///wAAzAAzzJmZ/zMzzAAA
-zAAzzAAzzJmZ/zMzzAAzzAAAzGZmzAAzzAAAzP///wAAzAAzzAAAzP///////wAzzAAzzAAz
-zAAzzAAzzAAzzJmZzP///wAA////MzPMADPMADPMADPM////ADPMADPMMzPMZmbM////AADM
-ADPMmZn/MzPMADPMMzPMADPMADPMADPM////ADPMADPMAADM////ZmbMADPMADPMADPMADPM
-ADPMADPMmZn/////AAD///8zZswAM8wAM8wAAMz///8AM8wAM8wAM8wAM8wAM8wAM8wAM8yZ
-mf8zM8wAM8xmmcwAAMwAM8wAAMz///8AAMwAM8wAAMz///8AM8wzM8wAM8wAM8wAM8wAM8wA
-M8yZmf////8AAP///2ZmzAAzzAAzzAAzzAAAzAAzzAAzzAAzzAAzzAAzzAAzzAAzzJnM/zMz
-zAAzzJnM/wAAzAAzzAAzzAAAzAAzzAAzzAAzzP///wAAzAAzzAAzzAAzzAAzzAAzzAAzzMzM
-/////wAA////ZmbMADPMADPMADPMADPMADPMADPMADPMADPMADPMADPMADPMADPMADPMADPM
-3d3dMzOZADPMADPMADPMADPMADPMADPMADPMADPMADPMADPMADPMADPMADPMADPMzMz/////
-AAD///9mmcwAM8wAM8wAM8wAM8wAM8wAM8wAM8wAM8wAM8wAM8wAM8wAM8wzM8yZZjPMzJmZ
-MwAAM8wAM8wAM8wAM8wAM8wAM8wAM8wAM8wAM8wAM8wAM8wAM8wAM8wAM8zu7u7///8AAP//
-/5mZzAAzzAAzzAAzzAAzzAAzzAAzzAAzzAAzzAAzzAAzzAAzzDMzzJlmAGYzZsyZZpkzAJmZ
-zAAzzAAzzAAzzAAzzAAzzAAzzAAzzAAzzAAzzAAzzAAzzAAzzAAzzP///////wAA////mZn/
-ADPMADPMADPMADPMADPMADPMADPMADPMADPMADPMAADMzJlmmTMAMzOZmWYzmTMAmWYzMzPM
-ADPMADPMADPMADPMADPMADPMADPMADPMADPMADPMADPMADPM////////AAD///+Zmf8AM8wA
-M8wAM8wAM8wAM8wAM8wAM8wAM8wAM8wAM8wzZszMzP+ZMwAzM8yZZgCZMwCZMwCZmf8AM8wA
-M8wAM8wAM8wAM8wAM8wAM8wAM8wAM8wAM8wAM8wAM8z///////8AAP///5mZ/wAzzAAzzAAz
-zAAzzAAzzAAzzAAzzAAzzAAzzAAzzAAzzAAzzJlmAGZmzJlmAGYzM5kzAMzM/wAzzAAzzAAz
-zAAzzAAzzAAzzAAzzAAzzAAzzAAzzAAzzAAzzP///////wAA////zMz/ADPMADPMADPMADPM
-ADPMADPMADPMADPMADPMADPMADPMM2bMmTMAZmbMmWYAmTMAZmb/7u7uADPMADPMADPMADPM
-ADPMADPMADPMADPMADPMADPMADPMADPM////////AAD////MzP8AM8wAM8wAM8wAM8wAM8wA
-M8wAM8wAM8wAM8wAM8wAM8yIiIiZZgBmZsyZMwCZMwBmZswAAMwAM8wAM8wAM8wAM8wAM8wA
-M8wAM8wAM8wAM8wAM8wAM8wAM8z///////8AAP///93d3QAzzAAzzAAzzAAzzAAzzAAzzAAz
-zAAzzAAzzAAzzAAAzHd3d5kzAGaZzJkzAJkzAGYzZpmZ/wAzzAAzzAAzzAAzzAAzzAAzzAAz
-zAAzzAAzzAAzzAAzzAAzzP///////wAA////7u7uADPMADPMADPMADPMADPMADPMADPMADPM
-ADPMADPMMzPMZjMzmTMAZpn/mTMAmTMAZjMzmcz/ADPMADPMADPMADPMADPMADPMADPMADPM
-ADPMADPMADPMADPM////////AAD///////8AM8wAM8wAM8wAM8wAM8wAM8wAM8wAM8wAM8wA
-M8wzZsyZMwCZZgBmZv+ZMwCZMwCZMwDMzP8AM8wAM8wAM8wAM8wAM8wAM8wAM8wAM8wAM8wA
-M8wAM8wAM8z///////8AAP///////wAzzAAzzAAzzAAzzAAzzAAzzAAzzAAzzAAzzAAzzGaZ
-/5kzAJlmAGZmzJlmAJkzAJkzAMz//wAzzAAzzAAzzAAzzAAzzAAzzAAzzAAzzAAzzAAzzAAz
-zDMzzP///////wAA////////ADPMADPMADPMADPMADPMADPMADPMADPMADPMADPMmZn/mTMA
-mTMAMzPMmWYAmTMAmTMA7u7uAADMADPMADPMADPMADPMADPMADPMADPMADPMADPMADPMMzPM
-////////AAD///////8AM8wAM8wAM8wAM8wAM8wAM8wAM8wAM8wAM8wAM8yZzP+ZMwCZMwAz
-M8yZZjOZMwCZMwC7u7sAAMwAM8wAM8wAM8wAM8wAM8wAM8wAM8wAM8wAM8wAM8wzM8z/////
-//8AAP///////wAzzAAzzAAzzAAzzAAzzAAzzAAzzAAzzAAzzAAzzMzM/5lmM5kzADMzZsyZ
-M5kzADMzmWZmzAAzzAAzzAAzzAAzzAAzzAAzzAAzzAAzzAAzzAAzzAAzzDMzzP///////wAA
-////////ADPMADPMADPMADPMADPMADPMADPMADPMADPMADPMzMz/MzPMmTMAZjMzzJlmmTMA
-mTMAADPMADPMADPMADPMADPMADPMADPMADPMADPMADPMADPMADPMADPM////////AAD/////
-//8AM8wAM8wAM8wAM8wAM8wAM8wAM8wAM8wAM8wAM8wAM8wAM8yZMwCZMwCZmZmZMwCZMwCZ
-ZgAAM8wAM8wAM8wAM8wAM8wAM8wAM8wAM8wAM8wAM8wAM8wAM8z///////8AAP///////wAz
-zAAzzAAzzAAzzAAzzAAzzAAzzAAzzAAzzAAzzAAzzDMzzJkzAJkzAJlmM5kzAJkzAJkzAMzM
-/wAAzAAzzAAzzAAzzAAzzAAzzAAzzAAzzAAzzAAzzAAzzP///////wAA////3d3dADPMADPM
-ADPMADPMADPMADPMADPMADPMADPMADPMADPMZmbMmTMAmTMAmTMAmTMAmTMAmTMAZmbMMzPM
-ADPMADPMADPMADPMADPMADPMADPMADPMADPMADPM////////AAD////MzP8AM8wAM8wAM8wA
-M8wAM8wAM8wAM8wAM8wAM8wAM8wAM8xmZsyZMwCZMwCZMwCZMwCZMwCZMwBmM2bMzP8AAMwA
-mf8AM8wAM8wAM8wAM8wAM8wAM8wAM8wAM8z///////8AAP///8zM/wAzzAAzzAAzzAAzzAAz
-zAAzzAAzzAAzzAAzzAAzzAAzzGZmzJkzAJkzAJkzAJkzAJkzAJkzAJkzAP///wAAzACZzAAA
-zAAzzAAzzAAzzAAzzAAzzAAzzAAzzO7u7v///wAA////mZn/ADPMADPMADPMADPMADPMADPM
-ADPMADPMADPMADPMADPMMzPMmWYAmTMAmTMAmTMAmTMAmTMAmTMA////AADMADPMAGbMADPM
-ADPMADPMADPMADPMADPMADPMzMz/////AAD///+Zmf8AM8wAM8wAM8wAM8wAM8wAM8wAM8wA
-M8wAZswAAMwAM8wAAMzMmWaZMwCZMwCZMwBmM2YzM8zu7u7///8AAMwAAMwA//8AM8wAM8wA
-M8wAM8wAM8wAM8wAM8yZmf////8AAP///5mZzAAzzAAzzAAzzAAzzAAzzAAzzAAzzAAzzABm
-zAAzzAAzzAAzzJnM/5kzAJkzAJkzAJkzADMzzAAzzAAAzAAzzAAAzAD//wAAzAAzzACZzAAA
-zAAzzAAzzAAzzJmZzP///wAA////ZpnMADPMADPMADPMADPMADPMADPMADPMADPMADPMADPM
-ADPMADPMADPMzJlmmTMAmTMAmTMAmTMAADPMADPMADPMADPMAP//ADPMADPMAMz/ADPMADPM
-ADPMADPMZmbM////AAD///9mZswAM8wAM8wAM8wAM8wAM8wAM8wAM8wAM8wAM8wAZswAM8wA
-M8wAM8xmmf+ZZjOZMwCZMwCZMwBmM2YAM8wAM8wAM8wAAMwAM8wAM8wAM8wAM8wAM8wAM8wA
-M8wzZsz///8AAP///2ZmzAAzzAAzzAAzzAAzzAAzzAAzzAAzzAAzzAAAzAD//wAAzAAzzAAz
-zAAAzMzM/5lmAJkzAJkzAJkzADMzmQAzzAAzzAAzzAAzzAAzzAAzzAAzzAAzzAAzzAAzzDMz
-zP///wAA////M2bMADPMADPMADPMADPMADPMADPMADPMAGbMADPMAMz/ADPMADPMADPMADPM
-AADM7u7uzJmZmTMAmTMAMzPMADPMADPMADPMADPMADPMADPMADPMADPMADPMADPMADPM////
-AAD///8zM8wAM8wAM8wAM8wAM8wAM8wAM8wAM8wAmf8AAMwAM8wAmcwAM8wAM8wAM8wAM8wA
-AMzMzP/////d3d0AAMwAM8wAM8wAM8wAM8wAM8wAM8wAM8wAM8wAM8wAM8wAM8z///8AAP//
-/zMzzAAzzAAzzAAzzAAzzAAzzAAzzAAzzACZ/wAAzAAzzAD//wAAzAAzzAAzzAAzzAAzzAAz
-zAAAzAAAzAAzzAAzzAAzzAAzzAAzzAAzzAAzzAAzzAAzzAAzzAAzzAAzzP///wAA////MzPM
-ADPMADPMADPMADPMADPMADPMADPMAGbMAGbMADPMADPMAMz/AADMADPMADPMADPMADPMADPM
-ADPMADPMADPMADPMADPMADPMADPMADPMADPMADPMADPMADPMADPM////AAD///8AM8wAM8wA
-M8wAM8wAM8wAM8wAM8wAM8wAAMwAzP8AAMwAM8wAmf8A//8AAMwAM8wAM8wAM8wAM8wAM8wA
-M8wAM8wAM8wAM8wAM8wAM8wAM8wAM8wAM8wAM8wAM8wAM8z///8AAP///wAzzAAzzAAzzAAz
-zAAzzAAzzAAzzAAzzAAzzAAzzAAzzAAzzAAzzAAAzAAzzAAzzAAzzAAzzAAzzAAzzAAzzAAz
-zAAzzAAzzAAzzAAzzAAzzAAzzAAzzAAzzAAzzAAzzP///wAA////ADPMADPMADPMADPMADPM
-ADPMADPMADPMADPMADPMADPMADPMADPMADPMADPMADPMADPMADPMADPMADPMADPMADPMADPM
-ADPMADPMADPMADPMADPMADPMADPMADPMADPMzMz/AAD///8AM8wAM8wAM8wAM8wAM8wAM8wA
-M8wAM8wAM8wAM8wAM8wAM8wAM8wAM8wAM8wAM8wAM8wAM8wAM8wAM8wAM8wAM8wAM8wAM8wA
-M8wAM8wAM8wAM8wAM8wAM8wAM8wAM8yZzP8AAP///wAzzAAzzAAzzAAzzAAzzAAzzAAzzAAz
-zAAzzAAzzAAzzAAzzAAzzAAzzAAzzAAzzAAzzAAzzAAzzAAzzAAzzAAzzDMzzJmZ/2aZzGZm
-zGZmzDMzzDMzzDMzzAAzzAAzzJmZzAAA////////////7u7uzMz/mcz/mZn/mZnMZpnMZmbM
-M2bMMzPMMzPMADPMADPMADPMADPMADPMADPMADPMADPMZpnM////////////////////////
-////////////////////////AAD/////////////////////////////////////////////
-////////////////////////////////////////////////////////////////////////
-//////////////////8AAA==
-ENDofIMG
-
-demo.show_image('gif', 'gif87a', <<'ENDofIMG')
-R0lGODdhQAAoAPcAAAAAADgoOHBgYJiIkIB4iJCAiIB4gGBIUGhggKiYmLCYoLiooHBocMCA
-eJBocLCYmMCooKiQkKCAgGBASIiAiGhYeLiQiIhoaJhwcJh4gMCYkMCgoMCoqKiQiEBAWEg4
-QMiwoMioqMComLCIiFhAWIBgaJhweHBgcLiQkIiAgDg4UIhwgHhgYJh4cMiooFBQcGBYeJiA
-iIBwgIh4iKCAiKB4eHhYYGhIWKiIiEhAWFBIYEhAaEhIaHBYcHBgeFBQeHBogHBQYHBQWGBA
-UFhQaGBYaFhYeKCIkLCQmHhYaGBIWLCYiFBAYEhAYFhQYFBIaFhYcKCIiKCQkKiIkLCIgHBQ
-aIhwcJiAeIBgcJBwcLCQiKiAeKB4gHhwgNCwqMiwqIBoeHBYaJh4eMCYmJBweGhYYNC4qEg4
-UEA4WGBQWEBAYFBQaHBoeFhQcGhgeGhYcMiwsJB4cGBIYNjIwEAwSMCgmHhocFBAWNDAuNDI
-uIBweGBYcHhoeDgwQGhgaKCIgNjQuKiAgNjIuKiIgKCAeKCQiEhIWFBIUGBQaNC4sGBQcGBY
-YMi4sGhYWFhIYFhIaFhQWHhoaLCQkDg4SHBgaJB4gJB4eLiYmLiomGhYaEhIYFhYaIh4gHho
-gGhgcIBoaGBIaHhgcNDAsFBAUGhQYLigoLioqJiIgGhQaFA4SFhIWHhweFBIWJiAgIh4eFhI
-UHBYYIhweEg4WLiYkDg4WGBQYEA4SEA4UMCwqIhocHhgaJB4iJCAgFhASEBAUEhAUIBocFhA
-UKCQmHhgeEgwSNjQwEg4SLCgmDgwUGhQWLCgoEAwUFBASLigmEAwQGhIUFg4SIhoeEgwQKiY
-kFA4UDgwSJiIiIBwcKiQmLCooLCYkDgoQP//////////////////////////////////////
-////////////////////////////////////////////////////////////////////////
-/////////////////////////////////ywAAAAAQAAoAAAI/gABCBxIsKDBggEEDBhAoICB
-AwcjSpxIMSKCBAoWIGDQoIGDBxAURJBAoKLJkwcnUKgQoYEFlxcwdOyYoYGGDRw6eEDJc+IH
-CSBCiHg5YiaJEjM7mjgBAkUKAip6Sh24YqYGmUkbYGDRwoWGlxocvIABI4aMGVN70qiRNSkL
-Gzda4BhhIoeOHTx6+PjxwwcCIGlPouiI4WUDFkFYCLlhYwiLBkU73iBShAgRAkaMHCGAIDBF
-JBpmXkiiZMiQCagzLEFRgi0GDUyaONHx5MkLKFFCSOns+eCUBlRKVIErxIYVG1ewsMiixYSW
-LVxQkIDRpDqRJF1gVPDyhQDg3gSB/mQAwyKMmBJjpoAhU6bKCjMgMGxZAuIMmjRq0KhpsmbN
-EjZtuHEEAgQ4Ad5ACLxRQhkZwBHHGHKMAcccdFxhBgpU1FGDHUzc0QESduDhxRx56DEHHnvs
-4R0ffRzYhREwYOHHH4BUEQgZYYlgoSBfjCHIBh0MAoEdAxBSiCGHIJLIHHCYwEEFQHRhx4Ew
-LLCHIm4sIggjc9RhgQhzgEAIIGSEAAIgjShhwhwN4MGEI4/sAIkjSEQiCRJYuAHEJL0RwMge
-ejzBBiV6VGKJFpcMskUcFyQygoiEbAABJn9kogkaa+RgwCZEMEEEBlNw4gMbiPQ2QyeefAKK
-GpT0cAIk/jjEgQIKggAiiAMgUAFZIkiEIkokozyigyakLFLBGzb8IcUDPXjSGxArlGJKKKcg
-sQAqdojAlQMaCDLGHIlk8EkqiFhQBxJL5BAGE0yo4gQaTBTAQAYc2NGDZ4UAYcoOhfBxwiql
-nFGGDQ3UwMIFGsyBAgs19MBKDg0IQUoroqCRgweO5OCKJjo4osEYBXjySmAE/JBCDHBMUUkT
-T6AxiktgvXTDDbDEUoEsF8ySQxl8LJEGLTugUUQtllBQyyqW8DFyWggY8UYoHPBxxh1O0PDA
-GA0g1ZEQQphQwhus2GJDEGh4cAstbjSBBhF7aEJEEzwYQUQnaQSWHQ+o4BIG/i5gPFIKHl8k
-ZYENGOSiixysqHHGLYbE4IQTt1TQhA6o8KDJGjy8YJkiJPOlCAw7OPKEB7LccYsQoUFWxwSq
-2EFJETo8ogoaThSRwy2y4KEGBaDwUIQfu1DiwyOBNc3DGrzI0cYdnNyRQx+vuCRIAyD0wokS
-aehgSw60+GIILbSoYMstpvwywxM88PAEETwQQTIMCOwBBjAdfMFIFBcEQ4IIDdTaAjAJgMQd
-UnGGJJTtdpMI3yRUAAEP4AUIT9DECRxhN2EoIAZ7IAUkAhECDgwDDLYgxgREgQk8FMNWcxAF
-BwjRhztEQRWtoIQdbHGGHOCBFmqAgRr2kIm6pWUC/p3wwRFAMYM/6IIUR0gAE+Rwh2DIwRgo
-wEMe5jAHQQhCFHFoBAAycYxXxMER27MBMtTACtkU4QyeUYACStGEO8QADA/wRAAEIoMsiOEK
-NxACCEAgiDwIAg+l+EQyAnCKDljAFLbghTHKp4Yi9IBznlEGBxLhiGUsgQOM+EQWAPABKkBC
-DBEIRC/iIApbCQICgxhCMERAiBZYwRLMmIAxFgAK7r3gCb1hAwXwYIUogKIMQSBEHprhDCVc
-4BNVnAMgABEm+hTgGYcoAzQWIAIsTOABaSBEFNIAiSfIAjwIYEQIZIGFMIAhDW/IAy6igYNE
-fEEUiWDEJcRgjBsEgRTM/pDDH5jRAUbgwhQJcIUkaAAEWvziQAjgQCnukIBW6KEWVsDDLFhA
-hQuEwAUjAMEsZnGBPwhBAtI4AAMaEYEOfAIAyjjGNOKgByLM8UADUAYnEmCJLwQBB3jAhRYG
-gTAN4CALWajDEWBxAV1MIBIMcIItjCEQSEShEqoYBTUOJBBbFACAqWjGBl5BhS+gQAs4mEYH
-COHPXmCBEBMYxjQC0IhbVEMglEgDKX5xBgpSVSAEqAAnTtGMB4CBEApAAS6yMIhmlMISlmjG
-IKxxjFnc4AgCsIMqXMEJXujhF7eABFPvKhAEsMENqliAFHpBCRvUAQKm4IAVxBCFBSijFA8Y
-2MQAjDENUrjCClaohB2KAAlWcJYgCLjGABKAjVYsIBsJuEQEmoGJbJjiuNpIQDY4UYAC8EEP
-kegEA9zwBk38tiAIMEB0swGBbGDjGM2QhDIeMItsONe9MrWGMKxhXU8Q4aDfLcgkCpCCCCRA
-G0hQQAKU4d4FGDgbyiBuBAZQAArIAAZ7yEF+IwIER8wAGxherwKOcQllTGMaSJBCBGLAi1Os
-gBJ2nbBEoFCAAUQhCtiIQASEIeMB0IAG1rAsH5ywDRWbJACdmEFDdlGAGMyAxF1gAwzuQNWA
-AAA7
-ENDofIMG
-
-demo.show_image('gif', 'gif89a', <<'ENDofIMG')
-R0lGODlhQAAoAPcAAMnJyTgoOHBgYJiIkIB4iJCAiIB4gGBIUGhggKiYmLCYoLiooHBocMCA
-eJBocLCYmMCooKiQkKCAgGBASIiAiGhYeLiQiIhoaJhwcJh4gMCYkMCgoMCoqKiQiEBAWEg4
-QMiwoMioqMComLCIiFhAWIBgaJhweHBgcLiQkIiAgDg4UIhwgHhgYJh4cMiooFBQcGBYeJiA
-iIBwgIh4iKCAiKB4eHhYYGhIWKiIiEhAWFBIYEhAaEhIaHBYcHBgeFBQeHBogHBQYHBQWGBA
-UFhQaGBYaFhYeKCIkLCQmHhYaGBIWLCYiFBAYEhAYFhQYFBIaFhYcKCIiKCQkKiIkLCIgHBQ
-aIhwcJiAeIBgcJBwcLCQiKiAeKB4gHhwgNCwqMiwqIBoeHBYaJh4eMCYmJBweGhYYNC4qEg4
-UEA4WGBQWEBAYFBQaHBoeFhQcGhgeGhYcMiwsJB4cGBIYNjIwEAwSMCgmHhocFBAWNDAuNDI
-uIBweGBYcHhoeDgwQGhgaKCIgNjQuKiAgNjIuKiIgKCAeKCQiEhIWFBIUGBQaNC4sGBQcGBY
-YMi4sGhYWFhIYFhIaFhQWHhoaLCQkDg4SHBgaJB4gJB4eLiYmLiomGhYaEhIYFhYaIh4gHho
-gGhgcIBoaGBIaHhgcNDAsFBAUGhQYLigoLioqJiIgGhQaFA4SFhIWHhweFBIWJiAgIh4eFhI
-UHBYYIhweEg4WLiYkDg4WGBQYEA4SEA4UMCwqIhocHhgaJB4iJCAgFhASEBAUEhAUIBocFhA
-UKCQmHhgeEgwSNjQwEg4SLCgmDgwUGhQWLCgoEAwUFBASLigmEAwQGhIUFg4SIhoeEgwQKiY
-kFA4UDgwSJiIiIBwcKiQmLCooLCYkDgoQP//////////////////////////////////////
-////////////////////////////////////////////////////////////////////////
-/////////////////////////////////yH5BAEAAAAALAAAAABAACgAAAj+AAEIHEiwoMGC
-AQQMGECggIEDByNKnEgxIoIEChYgYNCggYMHEBREkECgosmTBydQqBChgQWXFzB07JihgYYN
-HDp4QMlz4gcJIEKIeDliJokSMzuaOAECRQoCKnpKHbhipgaZSRtgYNHChYaXGhy8gAEjhowZ
-U3vSqJE1KQsbN1rgGGEih44dPHr4+PHDBwIgaU+i6IjhZQMWQVgIuWFjCIsGRTveIFKECBEC
-RowcIYAgMEUkGmZeSKJkyJAJqDMsQVGCLQYNTJo40fHkyQsoUUJI6ez54JQGVEpUgSvEhhUb
-V7CwyKLFhJYtXFCQgNGkOpEkXWBU8PKFAODeBIH+ZADDIoyYEmOmgCFTpsoKMyAwbFkC4gya
-NGrQqGmyZs0SNm24cQQCBDgB3kAIvFFCGRnAEccYcowBxxx0XGEGClTUUYMdTNzRARJ24OHF
-HHnoMQcee+zhHR99HNiFETBg4ccfgFQRCBlhiWChIF+MIcgGHQwCgR0DEFKIIYcgksgccJjA
-QQVAdGHHgTAssIcibiwiCCNz1GGBCHOAQAggZIQAAiCNKGHCHA3gwYQjj+wAiSNIRCIJEli4
-AcQkvRHAyB56PMEGJXpUYokWlwyyRRwXJDKCiIRsAAEmf2SiCRpr5GDAJkQwQQQGU3DiAxuI
-9DZDJ558AooalPRwAiT+OMSBAgqCACKIAyBQAVkiSIQiSiSjPKKDJqQsUsEbNvwhxQM9eNIb
-ECuUYkoopyCxACp2iMCVAxoIMsYciWTwSSqIWFAHEkvkEAYTTKjiBBpMFMBABhzY0YNnhQBh
-yg6F8HHCKqWcUYYNDdTAwgUazIECCzX0wEoODQhBSiuioJGDB47k4IomOjiiwRgFePJKYAT8
-kEIMcExRSRNPoDGKS2C9dMMNsMRSgSwXzJJDGXwskQYtO6BRRC2WUFDLKpbwMXJaCBjxRigc
-8HHGHU7Q8MAYDSDVkRBCmFDCG6zYYkMQaHhwCy1uNIEGEXtoQkQTPBhBRCdpBJYdD6jgEgb+
-LmA8UgoeXyRlgQ0Y5KKLHKyoccYthsTghBO3VNCEDqjwoMkaPLxgmSIk86UIDDs48oQHstxx
-ixChQVbHBKrYQUkROjyiChpOFJHDLbLgoQYFoPBQhB+7UOLDI4E1zcMavMjRxh2c3JFDH6+4
-JEgDIPTCiRJp6GBLDrT4YggttKhgyy2m/DLDEzzw8AQRPBBBMgwI7AEGMB18wUgUFwRDgggN
-1NoCMAmAxB1ScYYklO12kwjfJFQAAQ/gBQhP0MQJHGE3YSggBnsgBSQCEQIODAMMtiDGBESB
-CTwUw1ZzEAUHCNGHO0RBFa2ghB1scYYc4IEWaoCBGvaQibqlZQL+nfDBEUAxgz/oghRHSAAT
-5HCHYMjBGCjAQx7mMAdBCEIUcWgEADJxjFfEwRHbswEy1MAK2RThDJ5RgAJK0YQ7xAAMD/BE
-AAQigyyI4Qo3EAIIQCCIPAgCD6X4RDICcIoOWMAUtuCFMcqnhiL0gHOeUQYHEuGIZSyBA4z4
-RBYA8AEqQEIMEQhEL+IgClsJAgKDGEIwRECIFljBEsyYgDEWAAruveAJvWEDBfBghSiAogxB
-IEQemuEMJVzgE1WcAyAAESb6FOAZhygDNBYgAixM4AFpIEQU0gCJJ8gCPAhgRAhkgYUwgCEN
-b8gDLqKBg0R8QRSJYMQlxGCMGwSBFMz+kMMfmNEBRuDCFAlwhSRoAARa/OJACOBAKe6QgFbo
-oRZWwMMsWECFC4TABSMAwSxmcYE/CEEC0jgAAxoRgQ58AgDKOMY04qAHIszxQANQBicSYIkv
-BAEHeMCFFgaBMA3gIAtZqMMRYHEBXUwgEgxwgi2MIRBIRKESqhgFNQ4kEFsUAICpaMYGXkGF
-L6BACziYRgcI4c9eYIEQExjGNALQiFtUQyCUSAMpfnEGClJVIASoACdO0YwHgIEQCkABLrIw
-iGaUwhKWaMYgrHGMWdzgCAKwgypcwQle6OEXt4AEU+8qEASwwQ2qWIAUekEJG9QBAqbggBXE
-EIUFKKMUDxjYxACMMQ1SuMIKVqiEHYoACVZwliAIuMYAEoCNViwgGwm4RASagYlsmOK42khA
-NjhRgALwQQ+R6AQD3PAGTfy2IAgwQHSzAYFsYOMYzZCEMh4wi2w4170ytYYwrGFdTxDhoN8t
-yCQKkIIIJEAbSFBAApTh3gUYOBvKIG4EBlAACsgABnvIQX4jAgRHzAAbGF6vAo5xCWVMYxpI
-kEIEYsCLU6yAEnadsESgUIABRCEK2IhABIQh4wHQgAbWsCwfnLANFZskAJ2YQUN2UYAYzIDE
-XWADDO5A1YAAADs=
-ENDofIMG
-
-teapot = <<'ENDofIMG'
-",
-".. c #998074",
-"#. c #84aadc",
-"a. c #c47e55",
-"b. c #4c6ea0",
-"c. c #d48a64",
-"d. c #ecccbc",
-"e. c #8c6252",
-"f. c #b1a094",
-"g. c #714628",
-"h. c #af8a76",
-"i. c #2c5284",
-"j. c #98745f",
-"k. c #8f5124",
-"l. c #844614",
-"m. c #5074a6",
-"n. c #aeb2b9",
-"o. c #3e291c",
-"p. c #44689b",
-"q. c #4c2705",
-"r. c #1b2b43",
-"s. c #e1c8bb",
-"t. c #dd782d",
-"u. c #9c5824",
-"v. c #547aac",
-"w. c #906e5a",
-"x. c #545253",
-"y. c #e07e33",
-"z. c #bcaeac",
-"A. c #aeb6bc",
-"B. c #6f737b",
-"C. c #7e5942",
-"D. c #b55e1a",
-"E. c #7c5134",
-"F. c #8c7a70",
-"G. c #62524d",
-"H. c #bc8a6c",
-"I. c #936754",
-"J. c #6e6d75",
-"K. c #8cb0e2",
-"L. c #d4beb4",
-"M. c #2a201a",
-"N. c #c48664",
-"O. c #412105",
-"P. c #a95a19",
-"Q. c #747a7c",
-"R. c #2a2e33",
-"S. c #484c53",
-"T. c #8690a1",
-"U. c #6c524c",
-"V. c #505967",
-"W. c #040204",
-"X. c #8cb6e4",
-"Y. c #8f4912",
-"Z. c #846e5c",
-"0. c #244a7c",
-"1. c #dcc2b6",
-"2. c #33261b",
-"3. c #81736c",
-"4. c #3c3b46",
-"5. c #735f53",
-"6. c #545e69",
-"7. c #bc7c58",
-"8. c #4c2f1d",
-"9. c #a4806b",
-".# c #604c4c",
-"## c #d4916b",
-"a# c #5c80b2",
-"b# c #e3d3cd",
-"c# c #c8ad9a",
-"d# c #bf6c2e",
-"e# c #08121c",
-"f# c #9c5e34",
-"g# c #9298a1",
-"h# c #8b7f7c",
-"i# c #835f44",
-"j# c #a46e54",
-"k# c #474649",
-"l# c #a65d26",
-"m# c #be6420",
-"n# c #7c9ed2",
-"o# c #ac622c",
-"p# c #726e6c",
-"q# c #e1a684",
-"r# c #a48676",
-"s# c #54464c",
-"t# c #a0a4ac",
-"u# c #b37b5a",
-"v# c #947a70",
-"w# c #543d31",
-"x# c #743e12",
-"y# c #98bcee",
-"z# c #d49e7c",
-"A# c #64320c",
-"B# c #d4cac6",
-"C# c #2c3642",
-"D# c #6e686b",
-"E# c #5c463e",
-"F# c #7f7575",
-"G# c #bcb2b0",
-"H# c #979dac",
-"I# c #a47a61",
-"J# c #8c9094",
-"K# c #1c262c",
-"L# c #d3c3bc",
-"M# c #9cc2f4",
-"N# c #af7455",
-"O# c #fcad5f",
-"P# c #6486b8",
-"Q# c #d4742d",
-"R# c #6d4e3d",
-"S# c #242224",
-"T# c #3b444c",
-"U# c #181515",
-"V# c #6e4024",
-"W# c #749bcc",
-"X# c #afabac",
-"Y# c #7e6a64",
-"Z# c #343634",
-"0# c #e8ac8a",
-"1# c #343a44",
-"2# c #b18f7a",
-"3# c #dda07f",
-"4# c #6f380d",
-"5# c #2f5684",
-"6# c #a08d86",
-"7# c #5f6068",
-"8# c #625751",
-"9# c #16253b",
-".a c #94b6e9",
-"#a c #dfcec8",
-"aa c #3c6194",
-"ba c #ecdad3",
-"ca c #948a89",
-"da c #a4c8fa",
-"ea c #bcb6b8",
-"fa c #604432",
-"ga c #cc6d29",
-"ha c #949ea4",
-"ia c #413024",
-"ja c #a48a7a",
-"ka c #9a867d",
-"la c #1c1a1c",
-"ma c #342116",
-"na c #bc8364",
-"oa c #9c8674",
-"pa c #844e25",
-"qa c #3c4a5c",
-"ra c #582c0d",
-"sa c #c7835a",
-"ta c #613c24",
-"ua c #614b41",
-"va c #adaeb5",
-"wa c #805c4c",
-"xa c #0a0b0f",
-"ya c #c4b2ac",
-"za c #648abc",
-"Aa c #af846a",
-"Ba c #c68a69",
-"Ca c #483c39",
-"Da c #7f400d",
-"Ea c #646e74",
-"Fa c #a85515",
-"Ga c #042244",
-"Ha c #816759",
-"Ia c #95817c",
-"Ja c #9c9aa1",
-"Ka c #9c6b54",
-"La c #7e4924",
-"Ma c #0c1a2c",
-"Na c #5f595f",
-"Oa c #6f615e",
-"Pa c #474149",
-"Qa c #8c9aac",
-"Ra c #cbbeb8",
-"Sa c #806e68",
-"Ta c #82624e",
-"Ua c #949294",
-"Va c #b4652c",
-"Wa c #9c9ea4",
-"Xa c #72574c",
-"Ya c #2a303e",
-"Za c #bc9175",
-"0a c #9c7a64",
-"1a c #261a13",
-"2a c #aca6ac",
-"3a c #341a04",
-"4a c #593520",
-"5a c #d49878",
-"6a c #26282c",
-"7a c #475261",
-"8a c #3f3535",
-"9a c #63676f",
-".b c #a47255",
-"#b c #bc967c",
-"ab c #52433a",
-"bb c #80a4d6",
-"cb c #544c4c",
-"db c #bc723c",
-"eb c #645e54",
-"fb c #a4abb4",
-"gb c #c89070",
-"hb c #8c7469",
-"ib c #c7b8b3",
-" ",
-" ",
-" ",
-" wawae.e.wa ",
-" .#j#N#7.a.db.# ",
-" 8.g.x#C.o. ",
-" N#DaA#raY.Xa4aV#4aPas#q.W.W.6a ",
-" i#O.l.4.4.4.4.4.s#wa7.N#wawaXawawawaA#q.C. ",
-" 3a3a4#wawawae.e.e.I.j#m#d#VaN#KaI.e.e.e.e.waDaO..#j#j#N#N#j#fa ",
-" O.A#wae.e.I.e.I.I.Kal#m#m#D.u.KaKaKaKaI.e.I.e.Da3aXaE#C#W.o.C. ",
-" w#e.k.I.I.Kaf#KaKaKaKal#m#m#D.l#j#Kaj#KaKaKaKaKaFai#u. GaDaI. ",
-" .#waKaI.KaKaj#j#j#j#j#VaD.m#FaVaj#j#j#j#j#j#j#KaKae.U. 9#o.Ka ",
-" .#Xae.Kaj#j#N#N#N#N#N#j#N#j#N#N#N#N#N#dbdbN#N#N#I.waU. e#M.taPa ",
-" .#U.Xawae.Kaj#N#7.dbj#a.a.a.a.a.a.a.j#7.sa##naj#I.e.waXaU.Yama.# ",
-" .#U.Xawae.I.Ka.bna3#0#3###sasaa.sac.##Ba7.u#N#Kaf#f#waXaU.4.s#Pa ",
-" j#N#5aW.Y.u#j#R# 8a.#XaXae.e.I.KaN#naz#0#q#gb7.7.N#N#N#u#nau#N#N#Kaf#f#e.waU.LaU. ",
-" 4.Hahb.bI.j#KaY. s#U.XaXawae.KaKaN#na3#0#3#gbna7.N#u#u#N#7.u#N#.bj#KaI.e.waXa.# ",
-" G.2#e.KaI.E# .#U.Xawae.P.Kaj#N#H.z#q#3#gb7.7.7.7.N#N#u#u#N#.bj#KaI.e.TaXaU.0. ",
-" Ca.#e.j#Va 5#aa0.MaU.Xawak.d#I.j#I#N.5a3#5aBa7.dbN#N#dbN#N#u#I#j#KaKaI.e.waXaU.0.i.p. ",
-" abU.I.KapaaaaaxaGaU.C.wau.VaKaj#I#na5a5agbN.u#N#7.N#N#N#N#N#.bj#KaKaI.e.waXa.#R#m.m.m.p. ",
-" zaW#0.0.s#waKam#0.0.e#GaU.C.k.l#I.KaKa.bnagbgbBa7.u#7.N#N#N#N#N#.bj#j#KaKaI.e.waXa.#.#b.m.m.i.i.0. ",
-" 5#aaW#W#n#aaaa0.U..#e.Kau.ta4aLak.k.u.o#e.KaKa.bu#H.H.nau#N#N#N#N#N#N#j#N#j#KaKaI.I.e.waXa.#fab.m.i.i.i.i.i.0. ",
-"p.p.p.aan#W#0.0.0.0.p.uaU.KaKal#o#d#gal#o#o#e.I.Kaj#N#Aau#u#N#N#N#.bN#N#j#.bj#j#KaKaI.I.e.waXa.#E#m.m.v.m.i.i.m.n#bbn# ",
-"p.p.n#n#n#p.0.0.0.0.0.xa.#waKaKagaQ#t.y.d#dbi#e.I.Ka.bN#I#N#N#N#N#.bN#N#j#N#j#KaKaI.f#e.waXaU.U.w#5#m.m.i.i.i.m.bbbbbbbbaa ",
-"n#n#n#n#n#n#0.aaaap.aaaas#s#waKaj#na##O#dbl#wae.I.I.j.j#j#j#j#j#j#j#.bj#j#j#KaKaKaI.e.e.waXaE.Hai.m.m.i.i.i.i.p.p.bbb.b.p.p.aa ",
-"p.bbn#bbp.p.p.p.p.p.aaaaaaua..#be.Kaj#j#u.XawaTae.I.KaKaKaKaj#j#j#j#j#KaKaKaKaKaI.I.i#waXawaR#uav.m.m.v.v.i.b.bbbbbbbbp.p.b.p.p.",
-"bbp.p.p.p.p.p.n#p.0.0.0.0.p.8#Oa2#ZaZaZak.XaXawae.e.e.I.KaKaKaj#KaKaKaKaI.w.I.I.I.e.waXa0aXa5.5#i.m.m.v.v.p.p.#.#.#.#.#.#.b.bb#.",
-"bbW#p.p.p.n#bbbbp.0.0.0.0.0.0.0.x.D#3.3.w.waU.wawae.e.e.e.f#I.I.I.I.I.I.I.f#e.e.wawaXae.w.ua4.5#5#i.7ai.b.b.b.p.b.#.#.#.p.b.b.#.",
-"p.bbp.bbbbp.p.p.p.0.0.6.p.p.p.0.0.0.0.9#R#wae.9.j.wawae.Tae.e.e.e.I.e.Tai#e.wawaw.Aaw.hbOa6aC#5#m.v.v.#.p.p.b.b.p.#.#.b.b.p.p.b.",
-"0.0.0.p.p.p.p.aa0.0.p.p.p.p.p.p.0.0.p.qaT#s#Z.0a..h.I#I#ZaZaI#gbI#.bH..b.bH.h.j.r#HaU.PaV.V.Na1#v.m.K.K.K.#.b.#.#.#.#.K.p.b.m.p.",
-"0.0.0.0.p.0.0.0.0.0.0.p.p.p.p.0.0.p.p.qaqaqa2.iaR#HaY#ja2#2#I#Za2#0a2#2#h.jaoaF.8#V.6aC#C#C#CaNab.bbbbK.#.b.b.b.#.K.K.#.#.#.X.#.",
-"b.b.p.p.p.0.i.0.0.0.0.p.0.0.0.i.0.0.qaqak#6aR.6a3aiawaY#OaOaOaD#Iah#D#OaF#cbPa6a6aW.V.6.1#C#7ap#b.b.b.b.b.b.b.b.b.K.K.#.b.b.b.b.",
-"bb#.#.#.#.b.b.i.0.p.p.p.0.b.b.0.0.0.qar.YaYaYaR.K#Z#E.xa1a2.S#.#x.x.S.R.laU#1#W.W.9a6.J#J#T.7av#K.K.K.K.b.b.m.m.b.m.K.b.p.m.b.b.",
-"#.#.#.#.#.#.K.#.#.#.#.#.#.b.b.b.#.p.qaqaYaR.YaR.Pa6ak#S#lalaW.W.xaW.W.W.W.U#U#ebT.hag#g#haT.7ac#K.K.K.K.K.K.b.b.#.K.K.K.K.m.b.b.",
-"#.#.#.b.b.b.b.#.#.bb#.#.#.b.K.bbK.#.T.T.J#R.YaS.S.x.ebebR.2.S#S#S#T#S#S#S.9a7aEaEafbhag#6.7aV.m.K.K.K.K.X.K.m.X.K.K..a.aX.K.b.m.",
-"b.b.p.b.p.b.p.K.K.K.b.b.b.b.#.#.#.#.T.T.J#UaJ#J#g#g#haWaWa7#9a2at#fbA.t#9a6.9aJ.EaEafbV.6.V.Nam.b.m..a.am.b.m.m.m.K.X.K..a.a.am.",
-" p.b.p.p.b.p.K.b.b.p.b.b.b.b.K.#.K.7a7aV.9aWat#X#WahaH#ha6.t#n.n.n.n.fbfb9a9an.t#t#fbfb7aV.7#m.m.m..am.m.m.m.m.m.m..a.a.am.m.m.",
-" b.p.b.#.#.#.#.#.b.b.b.b.b.b.K.Pax.V.7aNa7#7#t#vafbB.B.B.B.B.n.A.A.A.fbfb9aA.t#t#fbfbQaH#7#D#m.X..a.a.aX.v.v.v.v.m.m..am.v.m.m.",
-" #.K.K.K.K.K.#.b.b.b.b.K.K.K.T.S.V.9aB.ebNaV.p#9a9aB.D#9a9aB.A.A.A.9aB.B.Eafbn.t#g#hat#X#m..ay#y#y#y#.ay#v.v.v..aX.y#.av.v.v.",
-" #.K.K.#.K.K.K.K.K.K.K.K.K.QaT.V.7#Ea9af.f.2at#OaD#F#Q.J.9aEaB.Ea9a6.Ea9aEaV.H#H#t#2aD#J.v.m.y#y#y#y#X..ay#y#y#y#y#y#.ay#.av.",
-" K.K.K.K.b.b.b.b.K.K.K.K.g#g#t#D#fbWag#c#X#2a2aeb7#D#Q.vaA.2at#p#9a6.V.7#7#9avaSaSaSav.m.v.v.y#.ay#X.v.v.v.v.y#y#y#y#y#y#y#",
-" K.K.b.m.b.b.b.b.K.K.K.K.Ja7#7#6.2az.#ac#z.G#eaG#p#2a2a2at#t#t#t#7#9aD#J.SaL#RaRaF#v.v.v.v.v.v.y#m.v.v.a#a#v.v.M#M#M#y#y# ",
-" b.b.m.b.m.b.b.b.K.X.7#7#7#7#D#3.1.z.yac#yaibh#caB#L#eaz.z.z.z.z.F#h##ab##aL#ibibv.a#m.m.v.y#M#y#a#v.v.v.a#a#a#a#M# ",
-" p.b.m.b.b.m.b.b.m.b.7#9a9aSahb..m..ayayahbhbF.h#Ias.RaRaibibL.L#kab#bab#1.L.L.y#y#a#v.v.M#y#y#M#y#v.a#a#a#v.a#a# ",
-" b.m.b.b.X.K..aK.b.7#D#F#hbv#m.b.m.m.F.F.F.v#v#F.v#L.L.L.L#..ka6#h.s.1.L#1.y#M#y#daM#M#day#y#M#M#M#a#a#a#a# ",
-" p.b.X.X.X.X.X.X.X.9aD#6#..m..aX.y#m.m.F.v#v#v#....1.Ia....kakar#r#r#1.s.M#M#y#a#a#a#M#M#y#y#daM#dadada ",
-" .a.aX..aX..aX..aD#SaF..ay#y#.aX..am.m.........s.s.9.9.r#r#r#r#kakar#M#M#a#a#a#a#a#a#M#M#M#M#dadada ",
-" K.X..a.a.a.a.aH#vab#1.y#X.X.y#y#y#y#v.v...s.d.d.d.s.r#r#h.jajajar#a#M#v.a#a#a#a#a#a#P#dadadaM# "};
-ENDofIMG
-
-demo.show_image('xpm', 'color', "/* XPM */
-static char * teapot[] = {
-\"64 48 204 2\",
-\" c #145ec4#{teapot}")
-
-demo.show_image('xpm', 'transparent', "/* XPM */
-static char * teapot[] = {
-\"64 48 204 2\",
-\" s None c None#{teapot}")
-
-demo.show_image('xbm', 'bitmap', <<'ENDofIMG')
-#define flagup_width 48
-#define flagup_height 48
-static char flagup_bits[] = {
- 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xe0, 0x7f, 0x00,
- 0x00, 0x00, 0x00, 0xe0, 0x7f, 0x00, 0x00, 0x00, 0x00, 0xef, 0x6a, 0x00,
- 0x00, 0x00, 0xc0, 0x7b, 0x75, 0x00, 0x00, 0x00, 0xe0, 0xe0, 0x6a, 0x00,
- 0x00, 0x00, 0x30, 0x60, 0x75, 0x00, 0x00, 0x00, 0x18, 0xe0, 0x7f, 0x00,
- 0x00, 0x00, 0x0c, 0xe0, 0x7f, 0x00, 0x00, 0x00, 0x06, 0xe0, 0x04, 0x00,
- 0x00, 0x00, 0x03, 0xe0, 0x04, 0x00, 0x00, 0x80, 0x01, 0xe0, 0x06, 0x00,
- 0x00, 0xc0, 0x1f, 0xe0, 0x07, 0x00, 0x00, 0xe0, 0x7f, 0xe0, 0x07, 0x00,
- 0x00, 0x70, 0xe0, 0xe0, 0x05, 0x00, 0x00, 0x38, 0x80, 0xe1, 0x04, 0x00,
- 0x00, 0x18, 0x80, 0xf1, 0x04, 0x00, 0x00, 0x0c, 0x00, 0xfb, 0x04, 0x00,
- 0x00, 0x0c, 0x00, 0xff, 0x04, 0x00, 0x00, 0x86, 0x1f, 0xee, 0x04, 0x00,
- 0x00, 0x06, 0x06, 0xe6, 0x04, 0x00, 0x00, 0x06, 0x00, 0xe6, 0x04, 0x00,
- 0x00, 0x06, 0x00, 0xe6, 0x04, 0x00, 0x00, 0x06, 0x00, 0x66, 0x04, 0x00,
- 0x7f, 0x56, 0x52, 0x06, 0xe4, 0xff, 0x00, 0x76, 0x55, 0x06, 0x04, 0x00,
- 0x00, 0x56, 0x57, 0x06, 0x04, 0x00, 0x00, 0x56, 0x55, 0x06, 0x06, 0x00,
- 0x00, 0x56, 0xd5, 0x06, 0x03, 0x00, 0x00, 0x06, 0x00, 0x86, 0x01, 0x00,
- 0x54, 0x06, 0x00, 0xc6, 0x54, 0x55, 0xaa, 0x06, 0x00, 0x66, 0xaa, 0x2a,
- 0x54, 0x06, 0x00, 0x36, 0x55, 0x55, 0xaa, 0x06, 0x00, 0xbe, 0xaa, 0x2a,
- 0x54, 0xfe, 0xff, 0x6f, 0x55, 0x55, 0xaa, 0xfc, 0xff, 0xa7, 0xaa, 0x2a,
- 0x54, 0x01, 0x88, 0x60, 0x55, 0x55, 0xaa, 0xaa, 0x8a, 0xa0, 0xaa, 0x2a,
- 0x54, 0x55, 0x8d, 0x60, 0x55, 0x55, 0xaa, 0xaa, 0x8a, 0xa0, 0xaa, 0x2a,
- 0x54, 0x55, 0x8d, 0x60, 0x55, 0x55, 0xaa, 0xaa, 0x8a, 0xa0, 0xaa, 0x2a,
- 0x54, 0x55, 0x8d, 0x50, 0x55, 0x55, 0xaa, 0xaa, 0x8a, 0xa8, 0xaa, 0x2a,
- 0x54, 0x55, 0x95, 0x54, 0x55, 0x55, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0x2a,
- 0x54, 0x55, 0x55, 0x55, 0x55, 0x15, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
-ENDofIMG
-
-demo.show_image('png', 'color', <<'ENDofIMG')
-iVBORw0KGgoAAAANSUhEUgAAAC4AAAAjCAIAAAETQp8oAAAIVklEQVR4nNVXPYgbSRb+xm7B
-K5CgC07QtaCDOvBCDeyAFAxIwQYdbKCBDeTgQBMqtOGCcTYOvXDBODjwHBzsBHcwExzMBAtW
-4GN7YQ1ScKAOBNPBLFcLHugGC7pgBf0WeuGC1vz6h7XZ4O5DIJp69dX3qr969Rp4A3erv69H
-YQn8aasDxh0Aw66JTtPU5ZIIhLsAvIZXw9rLJItfvd74vVzNepPx3Rh2DQAPwPFO3zqenaaO
-GcAdAAdRkuf50TQxyv8Q0gqh0ZWYNQDD0GRpHrbVJHFRYvtGE9H9nr7/dAwg8OkugLldmFaz
-1fDLtXKj1eytt76fv9JKKkkmaE5/yFbMD0IzDA2A3UEbQFsHH6bs7rsGvt0dnC9yu1heRTwZ
-dKPkHMDhTj9OXp0tXpelCBp0F8DXo/DLjp5ni+3uxou5fXT/c5Tl/HwxPcvO3dIDkOXFxGYA
-0tz+5/neNJooRSqVqi1DE3iXqyhJp2n+1dODooBjVpKKAm2t7gAIpCACgHUlD6IkXFfj2HaN
-YnBs3Ur2oK0BHO/030zqDgBmVpIAVPv924AI7cDvt3X16L0/usKzUcjAo4MIwKjftjb1SRAR
-g6/UVjje6T8bhXvDlZ/3Rt3Di/QOJ6fa9wEMu6arJJFwXGSOT6b2NsvEppPTNMnSZ6Owa4I0
-5Ulsn+8OAIABIh34WvuCKIotAN/Hg377293BDRZFBCDNmQABxNbN0vwwig93BrHNJnHS1TLL
-nE/U7xqfJBhp6m5rAdDTSkkaz6xWUitSvhCCRk9Pjnf6StHR1BYFGGwUSYLRgZKUZO4Gi1Ey
-shYAEQE4iJJwPSgKMLD1dEwQAI6myf2n469O4rZWSorxzD48iFAdxcsXEZ1aJfyJtbF1/bYO
-TaCV/ACD+PRrI//3MOzeOC+/yrvX4RM96Lcz50ah8Wm1EXfePwdAaIKvR/1RaKrHve0wSTMA
-RYHMrU7A26vTs2HY39Tj2AJAWdYEDqOkBPaGYbJ4XTKWS14syyRdnF33S1v7Twbdb3cHO/02
-gJP4FMVFCpKIiIFh15Agm7rM5Qykeb5a5pJlFJrT1B1ESdjWD/pmkmRK0ZNRtxpNUzfsmszl
-He0nNo2SbBzbyrWhCa4yapuWcywEqFZblmXLl2se/JpQ0h/HPypJZ855pbeh1d++m5vA37yn
-7in55+3eX17EZXmhRQkBIM/ZprkkAlAwj2d2Z9ADUDBCo9e1ZObK0NUsAno6uMpIXnhX+jSz
-WeZYK+kTJok9ffZA+qKtVV5wASYSBBARAbHNK8YVi80LBjsUbSUlyCcIwDEe7o/jxFa+cK5w
-edEzgZJUERWMauiCJXMdHez2e0+jxLq8ykJJGvXbjw8nWx2tCFGSHU+tUTItWCuSAiDW/jUt
-xxNLwMOjKCDSSkpJWVEUBZjZOpfmeWWvqc2Ysd0zVU49rR4eRVcsjpkgKmICigJ7J7GSlOYM
-4NHR1KZ5Fbm9P54kqSTR0XLromhcnSMGtCQGADqaxv22BiG68FXljgpPx/Etr1+dI1+AiHyi
-/SgGsN0zkogvRg+iBL8Gxzv9qlP4eFye8f8/mOBG87b2rrjfHMc7/cTlKKClJEJi87ZRW1+d
-XAZ8cNV9P9o6eDzojGN73RfPdwdpxvvjWeBLZrbSFQU62mfm63N/GymBTx2tQqOVpP1xEiUr
-u/fbOuxom7loZisjEVFeMDPGcWayj5XSb+vtnk7zQiv55GSyagcBAFW7l2SpL3Wlwye639OD
-rnHMB9GMIHySjlcbQQQi2NT5hIub6EJKtbG54ywviJAzJ9Z1dNA1KrZpynwysePYjmM7Co0v
-5eNBL0rS/atzTbkrtPI7WgEYdo0QSHN2jnPmwgFUZAygmNjs5mu5wg3b+oRHg24BuEoqMwP9
-ts6ZT2ZWCwJB+X7qeNDWmXM508ODVYnqmkAAu6P7+4djx4VPomeCtlbMvPVG79PVwVZXE4TR
-FCf545Mpbl3QXKL/WWtdSbtY4sJULSkWeWE+qb9IUikEL1n9rv7P6Q+b91SNsB1+/v08WXLZ
-8LyG8DbX1XfJebEsG1RrNuvlz7UFMzNMS36mpJLStOQ9JQXVXi+WX2xq55YP//GyWv12r/Dl
-5qcN8uz5AkAJnKZ506/XBVyBl/GP1bfd5sYn38/Ts9R58DqfNj/f3PhjGB6+mJIg5zhc18uC
-Pc9rCmop0fLrLxNb92oM1D14WP0AqIZYlgBwdqtBvY604CRnm7MAfCGUL2c26xrdM0oH0qVF
-1fjHNus9OuA8VUgPdwZEAFj7xMwMntnMpnnmOPBldR0QkZQkJVXI8sIE/uVX6u1dMcpvNRtl
-WTYEbbb8L3t/yF6X4/mZzYqax3WvweBwo5XY5e/qxMuyLPngu6Srm8uyXFcytouWlH+fzL1f
-vB/yZVPWWlK2pHDlUklyy7LRIM/zxFq5VoNjbjUbZVl7MbdvkcI/8eanzWWJhVvOX7lv/n02
-P89Vs9HAWp0aUlKNUfcECSzc8l7L9+u1+bn7JrZfbLSIoJpkAvnXf83P3dItueF5Rknlk1cT
-S8bPv/BPZck/lbJBql43SjouyxKVlLcU/mejkFEcRtYEghlEJASKAlIgL+CYcy62jE7ZEcgx
-XxZWE/ijsFP1G9cJCXgy7PpCAOACKedaSkEAsL1/Ffm2ElfAKGkCJyWBwcWqDhDRUbQqJI/6
-nTRxDEQzezkvydzjk2hvO7xeuAAw8Oho+paFbuItUqQkgACkqVOSSICIolliL+hHoUkd5znW
-FVl3o2Ax4+FB5BMB7yhkHyQFgGPurfs2ZRCc42tVFcPQnNr8/V2Qe1dBfS9ue2Vv2CUhiGia
-2Oczm7mPIf04/BfyDD1tMD0WfgAAAABJRU5ErkJggg==
-ENDofIMG
-
-demo.show_image('png', 'grayscale', <<'ENDofIMG')
-iVBORw0KGgoAAAANSUhEUgAAAC4AAAAjCAAAAAG5S1ejAAAEJElEQVR4nKWTXUwcZRiFH2YG
-ZpiBLsx2wW6ZpU1YC+3axWClf7ZKY5NVozHRxIYaL0xq1YuGeOFVRW40TXthk4aLxsT/xJjG
-+tdiGkUl1nQV6rYokuy2IFugy8/irp3dHXYGvFiwBdQ08Vx9+d73Oznfe84LAIjQNv+ELdBy
-aVqTRBSh/8p6aGMZWpDomBwwETg7020sL0NjG0XsTTT9GmlSdreji1xZ555bvzmyVvcNAI/s
-pRX/8lfi4uHoREIEnrnEKwNjcxUibdt+39PX6gwNTEkkB0l+3VPtdgclQI8fs0zd8gvoMkZX
-MBywY3B0Ox0FKoGcTvtKhQuQa5tBuvXmkHOCx4Y1xS7o6Qg29vFi6DvMe79paRjP5sIgAL/1
-jxwKJC4ewS72+kp7WfX4UQRgFUlBjA1/2R7t25DQdpbZiQJPU5V1xVMuqW+9ykc+X37WKJLC
-AmD8gkJX0HIOS3S3f+B3h48jAVNI0Viztbub4wCdC+rUf/3J7eEBOgr6l0Dbr4TUpffBl0Jw
-cARr5qYvL2wPM1d8bv65a3kzPTKKBHU7AuFT53eAS3FaSsdyynQcRGiNxXaVff9wfa+Of/rB
-T66OpgkmRNiYkkssj6CuDusJ6s4YDTUHTjsCuEiNauQu7MNqXJ8LekGoRwAVXNGkV+1/33Wn
-mVdERYx5EWDCttbJqpQ5NqCRSgV0UbE0BBjzP/XpBDn90Te3ll3q8aXXqGIVAvSInau8rrSV
-m5iaY9DaU6TUdyKAKVUhWh/qSU6Owmv9mv9wIQ+OxynqbpZ6IQ6cAgrzURXtc/ZoDnQtGWFH
-6z/OW/t/dhkARbfR2DGer5avbnyZZWleCv/+C13AkYmP3bkxqy73X+y6v9F9NgLNW8Sf7DJs
-yzI+X8ne3DK99r0YoDNSEUHbdb95RiozLWR5TM2ABP79fyRlc8gfiKZ7wuFQ5dOR01CU8vpp
-kZMp05St+UFrga4IQN3npMg7W2/8UCm5k9uT2TcgID7/rqkF/LnDANTvkNYNvlMIZn6L73re
-YfWMEdEynm8bSkIXs3Lppki21G3fsGpr3bU1yvS21InFHO8sjTMfryzNXIxbmyPXhPrm0Bkl
-fXdGKr/DfVl2ZEEQqJhl9O91SF+fFMtWR+8KeKdsogdSxe3ynCdnR0dn3IqmuFyKkqwxFtmN
-alutu2/qx3FRsZuGXFm7a8OsL+r5ikSFx53Vb5RJomBWO30L7WaDNTN8fthTrLrmZHnGVz58
-4Z4ST81nU3/Khl6SnbWy5ZVGxu5btOmQfa7GUmRLzZhmU0oyu8B4SOwEEJ/VsFJVCq/ftCm/
-xnDZOVC+gCd/dnqB+NsH1QzgnLzFxoX2CoGELiu9kxBKpo1JAOv4ygwvhsDcNC6lTgF7h25u
-g7mivaD9QKlyOZxcUVyJvwDv65E2xA9RYAAAAABJRU5ErkJggg==
-ENDofIMG
-
-demo.show_image('png', 'transparent color', <<'ENDofIMG')
-iVBORw0KGgoAAAANSUhEUgAAAC4AAAAjCAYAAAGcIAh/AAAIl0lEQVR4nOWYIXDjyNLHf7p6
-oMU0TIIDtcxhNhT0Mi9LoD+2y7JsF+6xhG3YBSYsYWt2gg6zWcS+gSM2w9RsPiDbiS/Z/e7u
-3b33ql5Xqcoujbp7unv+/+6B70i2//HLskn3G8f8xLJaO34COJ3WqX30+BgwIiCML7oYiKps
-Xcw+362pjDyp+Z6t/19Op3UC+AfA3fk8uahsHj1RFdgZv247QgjcPnRZXRV/3txBmtqmvecZ
-wGlTp94HmknFuou0nWNeW0SEdzPLu8tVBlAWkg4hnE9smtkSFyMAE1tx0z5y1rxh6zzDALcP
-3WE975s6nTbjlj8tJmn8qPwnAvh75NdPi9TUo5Wfnr/4spgeTN+cz5MtJF2u1kDO1JbpH/CU
-4AfnuTht0sfbNrNVxWJW03aOresz2KWwDwNr1wPgg+N/v12kh3ZNVQmVN1QTk5q6HBfvpTLC
-ow/8fHnNMEBUpTLCMIwh/QmgNDmyq7k3leG67bLmTcVq67JpXaEoWxefdryY2ARjVX0vMj8B
-6M4ccEjz3yoipElZpPnOQ+A4IL9Hvi6bpMDH6zYDWM4nyTlPITkigqKHtUdJvzufp6/LJl2c
-Ph3ci+U03TyL0836EVuMB+10WqdpZRDJiTrQR+X+wWWvKl87z/rR0/Wer8smTesyea+st45v
-nxajAR1jYMsiWVuQi9BuHQBFAe/nk/Trbu2R8mqXfx8UAXJg6yIbH7hpt9ycL9LW9ay3HVNr
-6PtIIcJ8WlOIAQXv4+thAZjZisoIq43DVgZbCVWRk+fC8vKeu/M5VSXcPrhsGEBR6kowArUt
-qYzQ9fGl8roytG7coux2MRZwyaiI7O3lKhNyYASNd5er7Of7bTaxFZXJWW0cH3bJPqrRr8sm
-tY+OKi9YO8fWxWw+sampS2xl/nxNF8LfjEz/qXI6fYkdf/iE/lYKkfR+PqGPkWVTp2IPZ7xS
-ij+Spi7TL8t5Wu6YBODirKHzI/AOA/Tx6fj/MPtfT5tEzqG0bCGpObHctB0K2cVpk1wMhKCo
-KlFBBFbbEQIOnk9skb4spunXT4t0Ph+57X77CMOzEBjZgRPZ6bROkgvOR/oYUMCHcFB8pHzZ
-1Dz6yHXb0Uws7+d1Wnc9VSV8WT6xmPeR02md+hg4sQWd87Rdn622Luv6mO3DB88S6nce5jm4
-PiIiLKY1nQ8Uec6ymaTrdpuZWpKPgQLBB8VFzeqySLYyByfPrlbHnlf5eKRDUJzfdVXAoMpq
-4zhfzHb/oaktb6xBVWnq8qAYQICZLY+Vm6cKwhTCxvX0UbGVoRBYd47Hr++TKXImtiIMyoAi
-kiOMWCTA1gX2xg7KXRhQlMjApDIYhEJG2I0KH65WbDvHvo5jHIhhYFaPSLg3MCiHNU/K+8iJ
-Lfk0n3HZdrgYDmGojLCcT/h8s+btiaUSaLs+u3tw1JXBD4qtBJMDotjiN57frR0CfLhtKUWw
-lcEYoR+GEW5VcTFmPoQDSz64PlOFs1kNjGU6sxUfbtvjOo+qmZAfrArjibu431KZsTIAPt4+
-ZM6HQ37OrlbZuvMYyTmxhrfPYPkIWxSwRnaeCbcP22w+sQnhwJPAgWn2crnavnrSj7ClyMek
-FCJcteMHZ7MaszuV+3XXbffHSePufJ72be1fKoXIfycT1WXxYuP/NBH9lXJ3Pk9dDDCANQYR
-6FxgUle8/fn+aO2/zPGJLdPnxQmrrXtRyN8+LZLvlavVhrIYsdaZyDDAiS1Q1Rf6/lbHy0LS
-ia1oaktlhKtVR9u5oyGzObG4PtJu3GEIEhHCoKjCattT93+h4/OJTWcziw8DtjJ8uV+zdfEo
-kvuZqes9hbEHpwuR9G5mWUxroirX7QYhpxBD1NHhcQPj43ykEFJUXgLiPpUhKn0YEIGgSudG
-/pjWFVvn8arcrx2rrctWWzc2WMbweTGj7Xy6OgJHIcQBWxWc2AoYp5w8H2eLGJWgyhABGRgD
-Ow62qj9up168LIT0cTFlAOK+KdNxOptPLEGV+43D5uNtS1UU+KgsJpY+RoIKH66fqGJalykH
-Pi3fcXWzIupAITmzumRiK1T1iFqey9SW6e3UIuTUVth2gc/3D8f8tpeoZAKc7JsQfRopVZUY
-BuZvSjY+oAq+j1SFcLnaIiKYAu4+LVNZjNgdd7yoGoiMTA8j3blecVFpapvmE5sWE5v2v+cT
-m0yRs+l6alsQox6cftVxANl1XTw7zY8+4MKA5BAH6H3k28axcYHC5Pg4cN12PLpAZeDq4xl3
-X86Tj0pQuG87Fic1tjTjEKdgCqjLAhiQ3WaKMZGHB8bgBB3P1Q8d34sflC4oLig5UOQ5VWHY
-uJ5pbZnVFbY0RD8cRv2t65l9vM40eCo8N+eLHVoothBUFUXZuB7nA31UysIc+gERwZjxkd3/
-PgzUZcHza7dXHd+3OnU1Lp7XJeeLE3SAm3WH6weiBoTxbqK2hkrM2BnqOHecXa6yR9fjY+Rs
-9gYfFB+VtfP4fmDrw+GurXlTYQzYaozx3mGT7xr5GMeLpOKph37V8XbjUFVyGSPUdj2fb9fc
-PDwiuWCLEbqMEQyC98pkRxS1LZjWI4L8z3WbqSoi0JyU2FLoo2YPrs9cH7POBQZVqkKoqwoQ
-8nxEsxAUEcEWBVNb4eMxln8XcsZboIGb1lGXOapjJPJ8bEpNDmF3pRZ04G1t8RoRZIfNT+xY
-l0VaNif7zvmFTYH05XRKsTtbOoDXgDWGfFfoZ1fH332fgIbxVqQuI8aMJaDD065FhNv2CbM/
-zk+S7yK6y9hz6fqYfb5v08VZ84JIYLxd+Xj78F1XXpPvOm7M07n2Po6Tzq6pbjcdLurB+LKp
-R/QI8KaSo3cH55Tsw3W7a3FfUvgflR9SflRl9qbAeQUZCenqN2PDaVOnRxd+9wQQ9eWm/oy8
-quTidJokH280HzrHt42jfyWK/075P4AQnUfVTZNLAAAAAElFTkSuQmCC
-ENDofIMG
-
-demo.show_image('png', 'transparent grayscale', <<'ENDofIMG')
-iVBORw0KGgoAAAANSUhEUgAAAC4AAAAjCAQAAAE2KcD0AAAFPElEQVR4nMXWXYicZxUH8N+z
-M3HezCy76axJzJrtR8jWVVc29IMtTTG6hUqqqL1QWlrxQmirXpTihRdSY4pUSws1IIEWBesH
-CAZFapNaSISgpUurJra2i7u2IWs+dpNMnbWzndfM9Hixs5tNmrYJCv7vHvi///ec85z/OQ/L
-kODeeMZ1fq+LsTjolIqixAejx3jqj5EFknfEWFBke5zwkga62O01+9LAO38INsW9QeKmmHG1
-vzrgapkttiWqkWA0hsziSr/1CX+T25fAp+Km4PZg8F2CfCseipGga+HwxYBvxur4hWQoigtp
-T7grHk3rbXHAVKJIzQRq9sZ+a/XpixHFBZGqaQ/LNVTlBnVRVcKAPWnEeBrWMrXw7+uD7WfF
-3EVTFdvSxaaiFJfFaGAxlLfinmj7fuIzcUhFpmUZfXvUND2a+Gr0uT+x1+cxFhsc1zDvQOrE
-CC97wWH3xHDM+JMHg5YV+uNSKz2PHrfEQ2eK24OaLgVTDnnKtpj0Rx8wo+IG3VpmLFNnSNW4
-futUZb7tW9b6Xcq1rFe2QdU/ztAHvIgMe9KIXDvdl4rYl7aln6VBfcbtSEupnkTRpKk0Grkt
-9mHHUsV3nl378kV31f8SH1/qkbe91UVU4hanbI0ylhXybIzE12JrwN0OI/caOqPgDL4SK+xI
-rI5rPK2d7opZdU3zSsYXC7kxNhs2blf6g82gV6adxmKlo5oyp0yf6Zmtpu1xrc/Gi9a6O2DG
-WJyy0SsOpvE0nRiJjvq/UHJUZovDun0ynkyVOKak5kQaiH7c7IFF9V7UHVFB07NuQ26TKzSN
-RH+nJkOL9HIn3kk1/cpe8NPodaWG0zIFmYIp/Yv0WS25y5WUFc172EsqqKsbVlWQyVUW6UcN
-utWvzVow9Kf9wHW6HUz7XWrOOmUFaxbp+xXs1KNfrzm5ptl00puYSLkbJZkhO1OH3khFa1CQ
-+7mqGh5LR8AD6QUVg+5Ly3qmbbW2ZF8ajaLnwXTnpnctu/lOz5RlKp5I3KiinWDP2w+k7XH7
-hVuk8v9008DSz9/VTBeG7XHMaWuVvOJDvv7fiA/GHZ5dKvODMeuX+jQdlduoucS7yMVQjUGb
-9Nndmd6jca2C57R0oyWXG/BEuoDIR2PMKe/3E1MdehWHrXIgUYmP+piGJxV1a8hRUnJUOebP
-NONg3OGfakoaXjVo2KQ5+42ncVvjEl9wIH6VFhKt6zeIsSipqWtoKMmFCfk5dVg6luM2bXWc
-1nad1z3jEkV9aq5X84bvJRiOgi/7sYaKYYOaHcssYCg2K7rchMfTslk6nwqu6EjTVHeVQ3Iz
-qnbJ9PhuVIM65v1bjrbjTtoUo3F9bIrRGI1eL9tgzuPL9ymsxGkwbVbJvBnjpqxSs9srqr7h
-kaiZt9cN+mVaeqwXCtrKCgoKOG7ewlPgnC0w57gTCrq916SPGNbvpBYm3ZnqVtim5E2rNbVM
-OuI1fTIVmV69Mpma9RYedcvEj2DAgKvcqmmvY15X1LJBr4qW1XF/+rtTblRTM2HWIbMY0WMd
-Mpmyklnz+s4Vf05TpumgH9ons1q3XiUzNmq6wjAeSU3vcY33qaWJdDS96g1Vl0lKGuoyawyp
-ndstcE+0PG29XKYkVzavoeFqdUWNjicH4maFZW+DQnxJBbm6NTJ853wmOm2dAb1aHQtnfpPg
-c/Fn7c4oZjr9KO5eMgrt9Jjz4yzxVbowo6ok87wTCbZGzZyBzgnytOOCBu859m/4sGOK6ktL
-4qZ49byboHEBU2kZ5c5YKfMX42oX/849L/4D4jD0vGNZ6YMAAAAASUVORK5CYII=
-ENDofIMG
-
-demo.show_image('jpeg', 'color', <<'ENDofIMG')
-/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAgGBgcGBQgHBwcJCQgKDBQNDAsLDBkSEw8UHRof
-Hh0aHBwgJC4nICIsIxwcKDcpLDAxNDQ0Hyc5PTgyPC4zNDL/2wBDAQkJCQwLDBgNDRgyIRwh
-MjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjL/wAAR
-CAAmADkDASIAAhEBAxEB/8QAHwAAAQUBAQEBAQEAAAAAAAAAAAECAwQFBgcICQoL/8QAtRAA
-AgEDAwIEAwUFBAQAAAF9AQIDAAQRBRIhMUEGE1FhByJxFDKBkaEII0KxwRVS0fAkM2JyggkK
-FhcYGRolJicoKSo0NTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqDhIWG
-h4iJipKTlJWWl5iZmqKjpKWmp6ipqrKztLW2t7i5usLDxMXGx8jJytLT1NXW19jZ2uHi4+Tl
-5ufo6erx8vP09fb3+Pn6/8QAHwEAAwEBAQEBAQEBAQAAAAAAAAECAwQFBgcICQoL/8QAtREA
-AgECBAQDBAcFBAQAAQJ3AAECAxEEBSExBhJBUQdhcRMiMoEIFEKRobHBCSMzUvAVYnLRChYk
-NOEl8RcYGRomJygpKjU2Nzg5OkNERUZHSElKU1RVVldYWVpjZGVmZ2hpanN0dXZ3eHl6goOE
-hYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3uLm6wsPExcbHyMnK0tPU1dbX2Nna4uPk
-5ebn6Onq8vP09fb3+Pn6/9oADAMBAAIRAxEAPwDzLyJSuV5FIsUm4DAzW1Ywpb3sbPhoQ4LA
-jPGea6jWdH0W6EdxYLJA78gICUb169KIq8JTutDWnSnUmqcFds4y2e5jkzGrOVGTt7Ct2aae
-ZFzGSR6cmni1t4RiFWCseRknJHf+f51MsZG4JHwP4hXmVaqctEfVYDLqsKbTla+43S7NZLkr
-dHamMEgg9R6isDVtDu7KdjFGZoOodOcD3rowWIVRkbDuUHI3DFbWnOs1n9pIIMZwwIzyBxwe
-v/16ujWs9iK+VQqfFN3W3Yo6Pp/n6LbXFx9rWeCNifLbjac9T6YxXN+a/wDzy/SvedC13S5/
-DtnZ3ckZmMQSVVTK8cYJ6HI96tfZvC3/AD42/wD35NdfM5dT5Pdtp3PBtEji1CVTtyR1U9vc
-11WpXOnRW9rYwWxB6O+/n2OOgrm40EZyg2n2rTm8M6xp+lrrk1q76bIu4hcMwB74zkD3/TFV
-KcXRcFHXudWGm6deM+axUmCQytGjrIi8Kyg81NFKrxqogVsMWk5OH78j8/YfnQ1hKlrbXU8F
-xCk43ws67d4/L3H5j1rLurqVLhhno2RXlKErn2f1qEIKV7xL77QN21VxwMdqdLdvBpbpDveS
-5cJGiHBzyMj8/wBB61i3OoySJjhR3C0+71FYYfIjncSgbSUOMj0J/mBW1OlJSuzz8fmsY0nG
-kvQ6qO4ubaLyt8fnR/Idh3AEdfyNQeVrH/QQuf8Avv8A+tWd4fu0j0dePnEjIM+vU/zqz/aq
-f8/J/wC/h/xotNSaifEO6bsVo1yy8DmvetkF3HbaW0INuYFMiYwpXA4wKKK7Y7HWtzSvNPs7
-ywezurdJLYrjyyOgx29D6EcivGviF4EtfDlnFqVpeSvFLMsPkSKCVJVjncO3y9MfjRRRUirX
-NKdWcfdi9DhbW3YRS3a7cW+GOepycDA+vWsaS3AcqScjvRRUU9zOcnLVlqx8+Elll43qoH1r
-K2L70UVaerMluf/Z
-ENDofIMG
-
-demo.show_image('jpeg', 'grayscale', <<'ENDofIMG')
-/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAgGBgcGBQgHBwcJCQgKDBQNDAsLDBkSEw8UHRof
-Hh0aHBwgJC4nICIsIxwcKDcpLDAxNDQ0Hyc5PTgyPC4zNDL/wAALCAAmADkBAREA/8QAHwAA
-AQUBAQEBAQEAAAAAAAAAAAECAwQFBgcICQoL/8QAtRAAAgEDAwIEAwUFBAQAAAF9AQIDAAQR
-BRIhMUEGE1FhByJxFDKBkaEII0KxwRVS0fAkM2JyggkKFhcYGRolJicoKSo0NTY3ODk6Q0RF
-RkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqDhIWGh4iJipKTlJWWl5iZmqKjpKWmp6ip
-qrKztLW2t7i5usLDxMXGx8jJytLT1NXW19jZ2uHi4+Tl5ufo6erx8vP09fb3+Pn6/9oACAEB
-AAA/APMvIlK5XkUixSbgMDNX7Z7mOTMas5UZO3sK3Zpp5kXMZJHpyan0uzWS5K3R2pjBIIPU
-eorA1bQ7uynYxRmaDqHTnA966/R9P8/Rba4uPtazwRsT5bcbTnqfTGK5vzX/AOeX6VFYwpb3
-sbPhoQ4LAjPGea6jWdH0W6EdxYLJA78gICUb169KzBa28IxCrBWPIyTkjv8Az/OpljI3BI+B
-/EKcCxCqMjYdyg5G4Yra051ms/tJBBjOGBGeQOOD1/8Ar16PoWu6XP4ds7O7kjMxiCSqqZXj
-jBPQ5HvVr7N4W/58bf8A78mvBtEji1CVTtyR1U9vc11WpXOnRW9rYwWxB6O+/n2OOgrDmCQy
-tGjrIi8Kyg81NFKrxqogVsMWk5OH78j8/YfnUT7QN21VxwMdqdLdvBpbpDveS5cJGiHBzyMj
-8/0HrWnHcXNtF5W+Pzo/kOw7gCOv5GoPK1j/AKCFz/33/wDWrIjQRnKDafatObwzrGn6WuuT
-Wrvpsi7iFwzAHvjOQPf9MVE1hKlrbXU8FxCk43ws67d4/L3H5j1rLurqVLhhno2RVa51GSRM
-cKO4Wn3eorDD5Ec7iUDaShxkehP8wK0vD92kejrx84kZBn16n+dWf7VT/n5P/fw/41WjXLLw
-Oa962QXcdtpbQg25gUyJjClcDjArSvNPs7ywezurdJLYrjyyOgx29D6EcivGviF4EtfDlnFq
-VpeSvFLMsPkSKCVJVjncO3y9MfjXC2tuwilu124t8Mc9Tk4GB9etY0luA5Uk5HerVj58JLLL
-xvVQPrWVsX3r/9k=
-ENDofIMG
-
-demo.show_image('jpeg', 'progressive color', <<'ENDofIMG')
-/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAgGBgcGBQgHBwcJCQgKDBQNDAsLDBkSEw8UHRof
-Hh0aHBwgJC4nICIsIxwcKDcpLDAxNDQ0Hyc5PTgyPC4zNDL/2wBDAQkJCQwLDBgNDRgyIRwh
-MjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjL/wgAR
-CAAmADkDASIAAhEBAxEB/8QAGgAAAgMBAQAAAAAAAAAAAAAAAAQDBQYBAv/EABkBAAIDAQAA
-AAAAAAAAAAAAAAECAAMFBP/aAAwDAQACEAMQAAABzA7aRqV/vvl1eIWLrCCt3stuTgrWtaNs
-PsV5dljqXX57XwtLMSLehdazjQjUSQBZVQK//8QAHhAAAgIDAQEBAQAAAAAAAAAAAQIAAwQR
-EiEQBRP/2gAIAQEAAQUC0ZoxegSSZUm2toZDTXuncQcvdTS05UTXyv1KL6jj84spAsNjVhT4
-QfIW1UGZRq6DyHGurq4PLMemsJjWaGO2qf6wTxg9aOn6GCuOir4VibHz/8QAHxEAAgEEAgMA
-AAAAAAAAAAAAAQIAAwQQERIxEyFB/9oACAEDAQE/AVUseIlC3YL3HtQ3ZxTPFwdzygDfyV7o
-BdLlWI9CE7x//8QAGxEAAwEBAAMAAAAAAAAAAAAAAAECESEQEjH/2gAIAQIBAT8BXxsqukWb
-o2vTMMZMvTu8EUifH//EACgQAAEDAwIDCQAAAAAAAAAAAAIAAREQITESUQMiMhMjM0FScYGR
-of/aAAgBAQAGPwKllhcys0shItUs3ksJtkxBLKyxTVsgAnaYuugfqggwqMrHvS2SwotLLxCp
-27j3boSdiacVhnuvldX7QeFHLF1oIZHZNxBN4d4h05emmaf/xAAgEAEAAwACAgIDAAAAAAAA
-AAABABEhMUFRcWGBEJHx/9oACAEBAAE/IcshZFgLXiHkBRkjX2ZMMXcupaDQ7fZRlXxwzq2m
-HKvtNw8afMR+4nAyQDPwUhn1PcOblWCA4SAgq7fyjXNBFYupQJoHCzZ/Qg6ZDC0rzWJF3bSr
-hl7gHj1CvvTIIebEpAaSnHFp1UQioh8wNbjHv6jUa7TSpzzsEon/2gAMAwEAAgADAAAAEIb7
-MuvRaP43Yv/EABoRAQADAQEBAAAAAAAAAAAAAAEAETEhUXH/2gAIAQMBAT8QGjax8NL2bzZn
-k1Ubj8VKe1w5H5Gxahs6xyN0w2f/xAAaEQEBAQEBAQEAAAAAAAAAAAABABEhMUFR/9oACAEC
-AQE/EBu05G8Fg+WvqUj1+xtC02FE8QZt6h63/8QAJBABAAICAgIBBAMAAAAAAAAAAQARITFB
-UWGRcaGx0fCB4fH/2gAIAQEAAT8QvtkSkKLl8RFvQllJTrLEKYaUR2dkTm2mejzMlLHRa9vV
-VP3kopAoS8XmEZJwK929QBQEyWtpz9/cQpiOEFAWXobKVLxEVQS8hjDv+46IjecMUumzzP8A
-cRqyTa48sXGOt/w1ogxTIDmGiosjXPJ78HuVGgwVxK9tt03ks9/Q7nZ8b0E36Z+z/EFWbeJY
-AwKAPNXYefpUHWepPryezuBl6sSs4HJFYsll1Z0v3CYYxDfe37zz/b8yzAZldCmppUMURDFp
-Y0Vx09JklKrxFSl046V/MBjlFe22ij53AGls5lpwah8z5p//2Q==
-ENDofIMG
-
-demo.show_image('jpeg', 'progressive grayscale', <<'ENDofIMG')
-/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAgGBgcGBQgHBwcJCQgKDBQNDAsLDBkSEw8UHRof
-Hh0aHBwgJC4nICIsIxwcKDcpLDAxNDQ0Hyc5PTgyPC4zNDL/wgALCAAmADkBAREA/8QAGgAA
-AgMBAQAAAAAAAAAAAAAAAgQDBQYBAP/aAAgBAQAAAAHMenfNC3rRtFT67pJcFaomPWQTaBWP
-rMsW9ZxtElKr/8QAHhAAAgIDAQEBAQAAAAAAAAAAAQIAAwQREiEQBRP/2gAIAQEAAQUC0Zox
-egSSZUm2toZDTXuncQcvdTS05UTXyv1KL6jj84spAsNjVhT4QfIW1UGZRq6DyHGurq4PLMem
-sJjWaGO2qf6wTxg9aOn6GCuOir4VibHz/8QAKBAAAQMDAgMJAAAAAAAAAAAAAgABERAhMRJR
-AyIyEyMzQVJxgZGh/9oACAEBAAY/AqWWFzKzSyEi1SzeSwm2TEEsrLFNWyACdpi66B+qCDCo
-yse9LZLCi0svEKnbuPduhJ2JpxWGe6+V1ftB4UcsXWghkdk3EE3h3iHTl6aZp//EACAQAQAD
-AAICAgMAAAAAAAAAAAEAESExQVFxYYEQkfH/2gAIAQEAAT8hyyFkWAteIeQFGSNfZkwxdy6l
-oNDt9lGVfHDOraYcq+03Dxp8xH7icDJAM/BSGfU9w5uVYIDhICCrt/KNc0EVi6lAmgcLNn9C
-DpkMLSvNYkXdtKuGXuAePUK+9Mgh5sSkBpKccWnVRCKiHzA1uMe/qNRrtNKnPOwSif/aAAgB
-AQAAABCrPPK25v/EACQQAQACAgICAQQDAAAAAAAAAAEAESExQVFhkXGhsdHwgeHx/9oACAEB
-AAE/EL7ZEpCi5fERb0JZSU6yxCmGlEdnZE5tpno8zJSx0Wvb1VT95KKQKEvF5hGScCvdvUAU
-BMlrac/f3EKYjhBQFl6GylS8RFUEvIYw7/uOiI3nDFLps8z/AHEask2uPLFxjrf8NaIMUyA5
-hoqLI1zye/B7lRoMFcSvbbdN5LPf0O52fG9BN+mfs/xBVm3iWAMCgDzV2Hn6VB1nqT68ns7g
-ZerErOByRWLJZdWdL9wmGMQ33t+88/2/MswGZXQpqaVDFEQxaWNFcdPSZJSq8RUpdOOlfzAY
-5RXttoo+dwBpbOZacGofM+af/9k=
-ENDofIMG
-
-demo.show_image('tiff', 'uncompressed', <<'ENDofIMG')
-TU0AKgAAHggAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
-AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
-AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
-AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
-AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
-AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
-AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
-AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
-AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
-AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
-AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
-AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
-AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
-AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
-AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
-AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
-AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
-AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
-AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
-AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
-AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
-AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
-AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
-AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
-AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
-AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
-AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
-AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
-AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
-AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
-AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
-AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
-AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
-AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
-AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
-AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
-AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
-AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
-AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
-AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
-AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
-AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
-AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
-AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
-AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
-AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
-AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
-AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
-AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
-AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
-AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
-AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
-AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
-AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
-AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
-AAAAAAAAAAAAAAAAAAAAAAAAAADb///bttu2tv+Sttu2ttvb2/8AJEkAAAAAAAAAAAAAAAAA
-AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
-AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
-AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD////b//+229u2
-29vb2/+2ttttttu2ttu22//b//8AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
-AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
-AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
-AAAAAAAAAAAAAAAAAAAAAAAAJAC229skbZLb//+2tv8AJEkkbZJtkrbb///b//9tktvb//8A
-AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
-AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
-AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACSttu2
-29u2ttvb2/8AAAC229skbZIAACSSttu229uSttsAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
-AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
-AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
-AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACQAAAAAAAAAAAAAJCQAJCSSttsAAACS
-ttvb//8AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
-AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
-AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
-AAAAAAAAAAAAAAAASUkAAABJbZIAACQkAACStrYASQDb2/8AAAAAAAAAAAAAAAAAAAAAAAAA
-AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
-AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
-AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
-AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
-AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
-AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
-AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
-AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
-AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
-AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
-AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
-AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
-AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
-AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
-AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
-AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
-AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
-AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
-AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
-AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
-AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
-AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
-AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
-AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
-AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
-AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
-AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
-AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
-AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
-AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
-AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
-AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
-AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
-AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
-AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
-AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
-AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
-AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
-AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
-AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
-AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
-AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
-AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
-AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD/////29v//9v/29v///8AAAAAAAAAAAAAAAAA
-AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
-AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
-AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
-AABtJACSbSS2bUnbkm22km3btm22kkn/25L//9ttJAAkAAAAAAAAAAAAAAAAAAAAAAAAAAAA
-AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
-AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
-AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACSSSSSSSTbkm2SSSSSSSSSJACSSSS2
-bUm2bUm2bUn/27b//9v/////////////27b/tm3btm3//9v/27b//////////////9skAAAA
-AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
-AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
-AAAAAAAAAAAkAABJAAAAAACSSSRJAABtJABtJACSbSSSSSTbtm22km3btm3btm3btm22km3/
-km22bUn/25L/27b/25Lbtm3btpLbkm3/27bbtpLbtm22km3/25L/27b//7b/27b//////9v/
-/////9v/////tpL/km1tJAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
-AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABtAABJAABJAABJAACSJCRJ
-AABtJABtAACSSSRtJACSbSSSSSTbkm222222km22bUm2kknbtpLb25K2km22kknbtpLbtm3b
-tpLbtm22km3btpK2km3btpLb25L//9v/25L/25Lb29v//7b/27b//7b/27b/25Lb29v/27bb
-tpL//9v//////7b///////////////+2bUkAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
-AAAAAAAAAAAAAAAAAABJAABJAABJAABJAABJJACSSSSSJABtSQCSSSSSSSSSSSSSJCSSSSS2
-bUmSSSSSJABtJABtAACSSSS2kkm2bUnbkkm2kkn/25K2kknbtm22km3bkm22km3/tm3btm3b
-tm3btpLbkm22km22kkm2kknbtm3bkpL/25L/27b//7b/27b//7b/////tm3btpL/27b/tm3b
-tpLbtm3//7b/25L//9v/////////////////////2/8AAAAAAAAAAAAAAACSSSQkAABtJABJ
-AABtJABJAABJAABJAACSSSRtSQBtJABtSSS2kkmSJCSSJCSSSSSSSSSSSSSSSSSSSSSSSSRt
-JACSSSSSSSS2bUm2km3//9u2bUm2bUm2bUm2SSS2bUm2bUm2km2SSSSSSSTbtm3btpL/25K2
-km3btkm2km3btm22km3bkm3btpL/25K2tm3bkm22km3btm22bUm2bUm2bUm2kkm2bUnbtm22
-tm3bkm3b25L//9v///////////8ADgEAAAMAAAABAEAAAAEBAAMAAAABACgAAAECAAMAAAAD
-AAAetgEDAAMAAAABAAEAAAEGAAMAAAABAAIAAAERAAQAAAABAAAACAESAAMAAAABAAEAAAEV
-AAMAAAABAAMAAAEWAAMAAAABACgAAAEXAAQAAAABAAAeAAEaAAUAAAABAAAevAEbAAUAAAAB
-AAAexAEcAAMAAAABAAEAAAEoAAMAAAABAAIAAAAAAAAACAAIAAgSwAAAAAQAABLAAAAABAAA
-ENDofIMG
-
-demo.show_image('tiff', 'packbits compressed', <<'ENDofIMG')
-TU0AKgAABAqBAMEAgQDBAIEAwQCBAMEAgQDBAIEAwQCBAMEAgQDBAIEAwQCBAMEAgQDBAIEA
-wQCBAMEAgQDBAIEAwQCbAAvb///bttu2tv+Sttv/tv7bA/8AJEm8AKEA/v8G2///ttvbtv3b
-Df+2ttttttu2ttu22//b//+/AKMACCQAttvbJG2S2////7YR/wAkSSRtkm2Sttv//9v//22S
-/9v//8IAoQADkrbbtv/b/7b+2wD//gARttvbJG2SAAAkkrbbttvbkrbbwgCcAAAk9wD/JAUA
-JCSSttv+AAGStv/b///CAJcA/0n+AAJJbZL/AP8k/wAIkra2AEkA29v/wgCBAMEAgQDBAIEA
-wQCBAMEAgQDBAIEAwQCBAMEAgQDBAIEAwQCBAMEAgQDBAIEAwQD9///b//8B2///2/7/gQDQ
-AB5tJACSbSS2bUnbkm22km3btm22kkn/25L//9ttJAAkgQDgACOSSSSSSSTbkm2SSSSSSSSS
-JACSSSS2bUm2bUm2bUn/27b//9v3/w3btv+2bdu2bf//2//btvb/AdskigADJAAASfwAU5JJ
-JEkAAG0kAG0kAJJtJJJJJNu2bbaSbdu2bdu2bdu2bbaSbf+SbbZtSf/bkv/btv/bktu2bdu2
-ktuSbf/bttu2ktu2bbaSbf/bkv/btv//tv/btvz/ANv8/wDb/f8GtpL/km1tJLUAYm0AAEkA
-AEkAAEkAAJIkJEkAAG0kAG0AAJJJJG0kAJJtJJJJJNuSbbbbbbaSbbZtSbaSSdu2ktvbkraS
-bbaSSdu2ktu2bdu2ktu2bbaSbdu2kraSbdu2ktvbkv//2//bkv/bkv7b//8Mtv/btv//tv/b
-tv/bkv7bCP/bttu2kv//2/z/ALb1/wK2bUnXAH9JAABJAABJAABJAABJJACSSSSSJABtSQCS
-SSSSSSSSSSSSJCSSSSS2bUmSSSSSJABtJABtAACSSSS2kkm2bUnbkkm2kkn/25K2kknbtm22
-km3bkm22km3/tm3btm3btm3btpLbkm22km22kkm2kknbtm3bkpL/25L/27b//7b/2wO2//+2
-/f8Ztm3btpL/27b/tm3btpLbtm3//7b/25L//9vx/wHb//UAAZJJ/yT/AH9tJABJAABtJABJ
-AABJAABJAACSSSRtSQBtJABtSSS2kkmSJCSSJCSSSSSSSSSSSSSSSSSSSSSSSSRtJACSSSSS
-SSS2bUm2km3//9u2bUm2bUm2bUm2SSS2bUm2bUm2km2SSSSSSSTbtm3btpL/25K2km3btkm2
-km3btm22km3bkjBt27aS/9uStrZt25JttpJt27Zttm1Jtm1Jtm1JtpJJtm1J27ZttrZt25Jt
-29uS///b+P8ADgEAAAMAAAABAEAAAAEBAAMAAAABACgAAAECAAMAAAADAAAEuAEDAAMAAAAB
-gAUAAAEGAAMAAAABAAIAAAERAAQAAAABAAAACAESAAMAAAABAAEAAAEVAAMAAAABAAMAAAEW
-AAMAAAABACgAAAEXAAQAAAABAAAEAgEaAAUAAAABAAAEvgEbAAUAAAABAAAExgEcAAMAAAAB
-AAEAAAEoAAMAAAABAAIAAAAAAAAACAAIAAgSwAAAAAQAABLAAAAABAAA
-ENDofIMG
-
-if false
-demo.show_image('tiff', 'pixarlog compressed', <<'ENDofIMG')
-TU0AKgAAA3Z4nO2aIWzbUBCGz7HjYyVTNDAp0CgKDRorCauiSGFjRmWRxs0rlQ2FlUWKrLKQ
-sIDK1BoyjFRUjZSF7f13eYnjpZOmdeuU3Wc1se+dn17uf/ee5SuRYRiGYRiGYRiGYRiGYRiG
-YRg/YxVt3EG04IpLJkqocJ8VD6S1746ELsOP8UNMxO1J9MbDPQs2EvOKcV66uOsZoo34lwxb
-JraMfEsif+S06Lrj74/5XNi2iG6jdbCKruMRz3gdfKUbF/OFi/c0vHbzfNvqBDl1giENKHdt
-492dI/7sdIElMRV+i0l0G62igcx3ZMBhnUFc0ebV4fZzeBfDfx2ofyGr1DycOt+3/RXnALIB
-63rTqnYo9SVYBxptVS11+WDz//WZh/MQ8Z5E8/AiwjdmPnTg9qfg1sV+Hn7gabiK3gWbSDPl
-rcdsGIZhGIZhGIZhGIZhnCebXc1IKxeJ2LSGkbija+8G/zAXEd4LDqkTbFuo091T312l8iYd
-79JhK7ngGY+dNSfoklKP38eX4VOMt73NN77Gr4B3tP4NOeLbCWY84qfYt18x4ntPUCd133XG
-zv+RSOp5RD57DlRSiSo5Y59RY1HQV2fH1KRyunbDy/D/0VRjr3HVirQqMuJJxO2UvDY+R4hm
-DKUe3RXywudIHbVrdBe8lNzJJfK08y2kQr5k7RfXS0ZeZaJNIfYl+35S8dF7j1fI8dHV8fmC
-P7P23OO7+Dl8/idVvZCYz7hpz6VyNHKz/6ACxj8kqLNk5MWxIrkoktKhP0Re49uX+qtWxUtn
-1cjP2Nvhi8/h7vyg7FDUXLKe+7o6tEKs/bgrGUEiFfdTeqji6qN1evSaiLYH34X4/piVaOnx
-Qzx1Gr72f03MX9xdEdlcVh5dhZaMLBkS1XJCuZJxo1XXKOwWsOld6nPQbiC9asT70l+5+93Q
-cMFY//rSk1eBaj7IgaoxW3wGlXu710X7QetwpxnRqTxSEHlEupJZk+x3v2xnIRk1VMvk3oJp
-32tz7a2Du7svVNl0tUFdmtt+NiNWOuf1vE6+m/8aUR/5bSuTqBYu06/2UTjeLU7h8+h+r6nf
-ZfAMMKYbUaTH3+Lj+1Tf+n4E/6K2c+kKqS26Py0k7xDTmcz+tPZ04VUmyTLvX4p/wdR4Gsm4
-uV54beCT1Z5edCVNpc/TSn0HoOsh4gAOAQAAAwAAAAEAQAAAAQEAAwAAAAEAKAAAAQIAAwAA
-AAMAAAQkAQMAAwAAAAGAjQAAAQYAAwAAAAEAAgAAAREABAAAAAEAAAAIARIAAwAAAAEAAQAA
-ARUAAwAAAAEAAwAAARYAAwAAAAEAKAAAARcABAAAAAEAAANuARoABQAAAAEAAAQqARsABQAA
-AAEAAAQyARwAAwAAAAEAAQAAASgAAwAAAAEAAgAAAAAAAAAIAAgACBLAAAAABAAAEsAAAAAE
-AAA=
-ENDofIMG
-end
-
-if false
-demo.show_image('tiff', 'logluv compressed', <<'ENDofIMG')
-TU0AKgAAAAgADgEAAAMAAAABAEAAAAEBAAMAAAABACgAAAECAAMAAAADAAAAtgEDAAMAAAAB
-h3QAAAEGAAMAAAABAAIAAAERAAQAAAABAAAAAAESAAMAAAABAAEAAAEVAAMAAAABAAMAAAEW
-AAMAAAABACgAAAEXAAQAAAABAAAAAAEaAAUAAAABAAAAvAEbAAUAAAABAAAAxAEcAAMAAAAB
-AAEAAAEoAAMAAAABAAIAAAAAAAAAEAAQABASwAAAAAQAABLAAAAABAAA
-ENDofIMG
-end
-
-demo.show_image('tiff', 'jpeg compressed', <<'ENDofIMG')
-TU0AKgAABID/2P/AABEIACgAQAMAEQABEQACEQD/2gAMAwAAAQACAAA/APn+vn+vn+iiiiii
-iiiiiiiiiiiiiiiiiiiiiiiiiiitK28O63e28VxaaNqE8ExIilitXZXIODtIGDyCOPStO18O
-a5e28VxaaNqNxBLny5IrV3V8Eg4IGDyCPqDWtZ+FvEOo2kd3Y6Dql1bS/wCrmgs5HR+SOCBg
-8gj6g1m1mkEEgggjqDWUysjFWUqwOCCMEGikpKKKKKKKKKKKKKKUHBB449RRXdXHxU16+nt5
-Ll1j8li5MDOTIxdWJYOzKSMMF3KwG4jHTHo83xl8QXs8U92Y1aJWASAMAxZkO472ZSQA4G5W
-A3YwRjb6mfjj4guZ4pblYYhEr/u7VWHmMzIcszuwyAHC5Vgu7G054x/GPiGDxNqtvqEcLRz/
-AGcR3LFAvmSB3wwwTxsKcEnbjaCQorA8e+J7bxbrdvqcEDRzfZViunaNU82QM3zgAnjaUGCT
-jG0HAFcx8QfFlt4z1221aK18i4+yrFdt5ap50iu+HwCTymzgkkY25IUE87XLVydFFFFFFFFF
-FFFFFFFFFFFFFFFFFFe2vceH9WtktdR8KaRGsEu53hjW2Z8ZH3o1jP8AeG32B6/d7l/E9hqU
-ENvqHhjSkWKUNKUt47Z2IJHDRiM+oK5xx7Db0t34mjvrWK3u9F0vEcoeUxWkdvI2MjAaJUOO
-eV6d/TFlfhp4BvnlmZtYtCHG6G3uUKJk9F3Izce7ZP542IfDXgG5trm4uv7YtJlOfJhnURAs
-TiNMxuxwM43NkgZ61p2lh4Lube5muodVhmDMdlvdII0JJwqgxuxA46tkj8cT23wi+HtwIsat
-raF/veZcQx4PoN0QJ+vA4zV+x8C/Dm6it92rauJJOH33McIVs8gb4cnjvwDjOfS5p+geAZoo
-BcXuqmWRQGYXEcKo2eRhoiTgc54HB554zofgFayMfM8XeSp+ZC2nggr0/wCeo7+38jitB8H9
-OLAXfi9bVXXfG72PyuucZB8z1BH4fXEUHw70/wDdte+IzaxyLvjZrLO5ckZA3jnIx6Z79cNm
-+AEUkFwNO8YQXF3EuRFLYtGh/wB5w7bRjnODS3HwYtJYpF0fxfbXlzHgvHNZvEqg9CWVnwMc
-5x0/HEt18NNPc+VpPimG7uVAaRJ7NokQHHJZWf37c44zms4fs++JyCf7Y8P/AC5zi5lOB68R
-9ODVdfgZr7KP+J54fDEkbBcysw9yBGePft3qOH4S6lLGr/2/oCgnH/HxK2PQnbGeD69B3xkZ
-w7z4N+MrW8lgjs7O5RGwJor+FUf3AdlbGeOQOlYM/wAL/E0V08McdhOik7ZV1CGNZAP4gJGV
-sfUDofSsV/Aeti9kt4jYShSdsxvookcDuPNZTjnuAfbg1n6h8MPGumiMy+HbybzM4+x7brGM
-Z3eUW29e+M846GoL34aeMrHZu8P3dxuyM2O26C4x97yi23qOuM0tz8PPFlvs2aLNeb8/8g90
-vNuMfe8ktt68ZxnnHQ1//9kAAA8BAAADAAAAAQBAAAABAQADAAAAAQAoAAABAgADAAAAAwAA
-BToBAwADAAAAAQAHAAABBgADAAAAAQACAAABEQAEAAAAAQAAAAgBEgADAAAAAQABAAABFQAD
-AAAAAQADAAABFgADAAAAAQAoAAABFwAEAAAAAQAABHcBGgAFAAAAAQAABUABGwAFAAAAAQAA
-BUgBHAADAAAAAQABAAABKAADAAAAAQACAAABWwAHAAABIQAABVAAAAAAAAgACAAIEsAAAAAE
-AAASwAAAAAQAAP/Y/9sAQwAIBgYHBgUIBwcHCQkICgwUDQwLCwwZEhMPFB0aHx4dGhwcICQu
-JyAiLCMcHCg3KSwwMTQ0NB8nOT04MjwuMzQy/8QAHwAAAQUBAQEBAQEAAAAAAAAAAAECAwQF
-BgcICQoL/8QAtRAAAgEDAwIEAwUFBAQAAAF9AQIDAAQRBRIhMUEGE1FhByJxFDKBkaEII0Kx
-wRVS0fAkM2JyggkKFhcYGRolJicoKSo0NTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlq
-c3R1dnd4eXqDhIWGh4iJipKTlJWWl5iZmqKjpKWmp6ipqrKztLW2t7i5usLDxMXGx8jJytLT
-1NXW19jZ2uHi4+Tl5ufo6erx8vP09fb3+Pn6/9k=
-ENDofIMG
-
-demo.show_image('tiff', 'deflate compressed', <<'ENDofIMG')
-TU0AKgAAAah4nO2Y643EMAiEXQzNUIyboRiaoRh2ADuP+7N70knZkxhZlmNH2fkMRPGO0Wq1
-Wq1Wq9Vqtb5L5m5qqi7Rm5kP4qdNfSSHc3dYDtfmMD8TQS3mn3b3TjRgm6YEgsaeYzwRg4TC
-9PcjRMLYzpmxcABW8+ifNviJ6DIktLKN/vv3/xRHwXJuPoV5HTwqKK1Wq9VqtVqtz+VxwMjv
-8ej/39fUpCGTdLLJVJmm6NlNQIQlev+AhyVMaDBfA6GYAU41nFrzqLSFSw3GjJf6ZeEpUvwu
-bxDOcFREAkpXRKph7IjRzOjAvEnOC9jzcC7rnlp13YB29ip4wvxT1Jn+qwlthMQ5QWDbwlsE
-RTis4uQX+cZl+zCPQfWWGZgsEkfHhaML3KyQN901lIjwL/6a4GvL5EEK4QErneKSKqPW0qaD
-+awarnpJlkTIOnI9Aic1o1LsuEHuMdIyHTgrPyVTVKsM/YfuRzY4odxz3v2KBfaf021aDQqi
-E2q3SYs0QxN1cdSOHnW0i8uWyYoR79dFIK95nedr5HhObRRmctXuUC9uNR31AAAOAQAAAwAA
-AAEAQAAAAQEAAwAAAAEAKAAAAQIAAwAAAAMAAAJWAQMAAwAAAAGAsgAAAQYAAwAAAAEAAgAA
-AREABAAAAAEAAAAIARIAAwAAAAEAAQAAARUAAwAAAAEAAwAAARYAAwAAAAEAKAAAARcABAAA
-AAEAAAGfARoABQAAAAEAAAJcARsABQAAAAEAAAJkARwAAwAAAAEAAQAAASgAAwAAAAEAAgAA
-AAAAAAAIAAgACBLAAAAABAAAEsAAAAAEAAA=
-ENDofIMG
-
-if Tk::PLATFORM['platform'] != 'windows'
-demo.show_image('other', 'postscript', <<'ENDofIMG')
-%!PS-Adobe-3
-%%Title: postscript.ps
-%%BoundingBox: 66 648 146 720
-%%Pages: 1
-%%DocumentProcSets: Adobe_distill 0.96
-%%EndComments
-%%BeginProcSet: Adobe_distill 0.96
-/PROLOGUE 30 40 add dict def
- % 30 procedure entries + room for 40 cached font dictionaries
- PROLOGUE begin
- /clip { } def % causes problems. remove if "clip" is needed
- /bdef { bind def } bind def /ldef { load def } bdef
- /T { moveto show } bdef /A { moveto ashow } bdef
- /W { moveto widthshow } bdef /AW { moveto awidthshow } bdef
- /f /fill ldef /R { { rlineto } repeat } bdef
- /r /rlineto ldef /L { { lineto } repeat } bdef
- /m /moveto ldef /l { moveto lineto stroke } bdef
- /x { 0 rlineto } bdef /y { 0 exch rlineto } bdef
- /c /curveto ldef /cp /closepath ldef
- /s /stroke ldef /w /setlinewidth ldef
- /g /setgray ldef /j /setlinejoin ldef
- /d /setdash ldef /F /setfont ldef
- /C /setcmykcolor where { /setcmykcolor get }{ %ifelse
- { %def
- 1 sub 3 { 3 index add neg dup 0 lt { pop 0 } if 3 1 roll } repeat
- setrgbcolor
- } bind
- } ifelse def
- /selectfont where { pop }{ %ifelse
- /selectfont { exch findfont exch scalefont setfont } bdef
- } ifelse
- /MF { exch findfont exch makefont setfont } bdef
- /FF /selectfont ldef
- /DF { selectfont currentfont def } bdef
- /BEGINPAGE { pop /pagesave save def } bdef
- /ENDPAGE { pop pagesave restore showpage } def
- /REMAP { %def
- FontDirectory 2 index known { pop pop pop } { %ifelse
- findfont dup length dict begin
- { 1 index /FID ne {def}{pop pop} ifelse } forall
- exch dup length 0 gt { /Encoding exch def }{ pop } ifelse
- currentdict end definefont pop
- } ifelse
- } bdef
- /RECODE { %def
- 3 -1 roll 1 index findfont /Encoding get 256 array copy exch
- 0 exch { %forall
- dup type/nametype eq
- { 3 {2 index} repeat put pop 1 add }{ exch pop }ifelse
- } forall pop 3 1 roll REMAP
- } bdef
- end %PROLOGUE
-%%EndProcSet: Adobe_distill 0.96
-%%EndProlog
-%%BeginSetup
-PROLOGUE begin
-%%EndSetup
-%%Page: 1 1
-1 BEGINPAGE
-1 g
-2 setlinecap
-144 53 m
-390 x
--19 y
--390 x
-eofill
-0 g
-1.268 w
-0 setlinecap
-4 setmiterlimit
-[] 0 d
-109.698 714.182 m
-111.525 713.672 112.472 713.234 113.624 712.431 c
--22.3128 -25.8381 r
-97.4019 682.652 103.794 672.84 100.329 664.844 c
-102.034 675.687 90.7436 683.82 84.1099 684.842 c
-25.588 29.3407 r
-f
-1.0361 w
-f
-f
-91.8805 654.468 m
-96.0255 654.285 100.155 654.188 104.481 654.188 c
-113.804 654.188 122.752 654.636 131.141 655.44 c
-134.222 655.737 136.724 658.133 137.108 661.279 c
-137.79 666.855 138.107 672.696 138.107 678.705 c
-138.107 684.714 137.79 690.555 137.108 696.131 c
-136.724 699.277 134.222 701.674 131.141 701.97 c
-127.476 702.321 123.704 702.604 119.84 702.813 c
-119.84 702.813 103.842 668.373 102.231 664.827 c
-99.8549 659.595 96.601 655.765 91.8805 654.468 c
-f
-0.7851 w
-77.8202 655.44 m
-74.7171 655.948 72.2887 657.716 71.8525 661.279 c
-71.1725 666.855 70.8549 672.696 70.8549 678.705 c
-70.8549 684.714 71.1725 690.555 71.8525 696.131 c
-72.2381 699.277 74.7417 701.674 77.8202 701.97 c
-82.1335 702.383 86.5932 702.702 91.1764 702.916 c
-8.16241 9.07727 r
-99.2863 711.98 101.266 712.345 102.996 711.921 c
--28.4564 -32.9334 r
-80.6983 681.906 98.7446 677.354 98.7446 666.708 c
-98.7446 655.332 86.3243 654.054 77.8202 655.44 c
-f
-0.0843 w
-139.67 644.154 m
-140.194 644.154 140.619 644.576 140.619 645.098 c
-140.619 645.619 140.194 646.042 139.67 646.042 c
-139.146 646.042 138.721 645.619 138.721 645.098 c
-138.721 644.576 139.146 644.154 139.67 644.154 c
-1 ENDPAGE
-%%Trailer
-end %PROLOGUE
-%%Pages: 1
-%%EOF
-ENDofIMG
-end
-
-if false
-demo.show_image('other', 'pdf', <<'ENDofIMG')
-JVBERi0xLjIKJcfsj6IKNCAwIG9iago8PC9MZW5ndGggNSAwIFIvRmlsdGVyIC9GbGF0ZURl
-Y29kZT4+CnN0cmVhbQp4nF1TSY7cQAy7+xX1AkFbaXlG3jBAgAAzh/z/Esp2uyeDPhhUayEp
-FZMsnt/9/fg6/h6y/hzCHdS1UlyodH0dIrJJNyIWlLpE1OcLrGQOjLg6MOIm6+NoMULWiopN
-bevz6HRiaUQ0aKMHW1L7itQitGA2UvwdDuhoIaw8zSN3UOVqTnILNLAiXQVy3NNvCvQs+M57
-Zv4Gj6LivWK7UxS0dDCknBGl2jNY6MKoKmBkljwYfQUD2d8ZqjkKgINASEyEfCq208nc0Fon
-YSdZIiFy7IldQmbACe4FraKUfVYkzEAgarhgIBJyvIGi+IYrCWqm4I6UJ4mvV4PmfTW4J3TI
-tZCHQzdmDqeLY7Jgpf6IAG7KKVAsLAMBxWIEqrEvuAAc8xXp2Rtgkdhp038B7PfcCyQZ5WDV
-oXIuWGdCI387SO/GjezVgcZyuRaAP1b3gXVmopb1ZfXXkSM/z6Imx+4xpHAsseGHgD2abFzu
-2+qEzjwjl9fJN4vb6zd+ef1Ebq+fDrfZz4zH7GFhc0O32cPSJR+zXzIes0vnMPZlNk73ejWT
-gFNDYs/IOM3tkTXmGUbMsaPF9cAwq8KuyNwxFMc4gJY+d47S0Td/68nSNxkiUNpz159H8Twg
-g1LkcKyGBe6TkQYL3jhwTDwreSJ7gw9eZeBY3GZpPBU/FjY7/HX8A9+h3WJlbmRzdHJlYW0K
-ZW5kb2JqCjUgMCBvYmoKNTE2CmVuZG9iagozIDAgb2JqCjw8Ci9UeXBlIC9QYWdlCi9NZWRp
-YUJveCBbMCAwIDYxMiA3OTJdCi9QYXJlbnQgMiAwIFIKL1Jlc291cmNlcyA8PCAvUHJvY1Nl
-dCBbL1BERl0KPj4KL0NvbnRlbnRzIDQgMCBSCj4+CmVuZG9iagoyIDAgb2JqCjw8IC9UeXBl
-IC9QYWdlcyAvS2lkcyBbCjMgMCBSCl0gL0NvdW50IDEKPj4KZW5kb2JqCjEgMCBvYmoKPDwg
-L1R5cGUgL0NhdGFsb2cgL1BhZ2VzIDIgMCBSCj4+CmVuZG9iago2IDAgb2JqCjw8IC9DcmVh
-dGlvbkRhdGUgKEQ6MTk5NzEyMDUyMjU2MzcpCi9Qcm9kdWNlciAoQWxhZGRpbiBHaG9zdHNj
-cmlwdCA1LjEwKQo+PgplbmRvYmoKeHJlZgowIDcKMDAwMDAwMDAwMCA2NTUzNSBmIAowMDAw
-MDAwNzk5IDAwMDAwIG4gCjAwMDAwMDA3NDAgMDAwMDAgbiAKMDAwMDAwMDYyMCAwMDAwMCBu
-IAowMDAwMDAwMDE1IDAwMDAwIG4gCjAwMDAwMDA2MDEgMDAwMDAgbiAKMDAwMDAwMDg0OCAw
-MDAwMCBuIAp0cmFpbGVyCjw8IC9TaXplIDcgL1Jvb3QgMSAwIFIgL0luZm8gNiAwIFIKPj4K
-c3RhcnR4cmVmCjkzOQolJUVPRgo=
-ENDofIMG
-end
-
-#######################
-
-Tk.mainloop
diff --git a/ext/tk/sample/tkextlib/tkimg/license_terms_of_Img_extension b/ext/tk/sample/tkextlib/tkimg/license_terms_of_Img_extension
deleted file mode 100644
index 7f515feee8..0000000000
--- a/ext/tk/sample/tkextlib/tkimg/license_terms_of_Img_extension
+++ /dev/null
@@ -1,41 +0,0 @@
-This software is copyrighted by Jan Nijtmans (the maintainer)
-and a lot of other people who contributed code (most notably
-Andreas Kupries, Thomas G. Lane, Ioi K. Lam, Mario Weilguni
-and Roger E Critchlow Jr).
-The following terms apply to all files associated with the
-software unless explicitly disclaimed in individual files.
-
-The authors hereby grant permission to use, copy, modify, distribute,
-and license this software and its documentation for any purpose, provided
-that existing copyright notices are retained in all copies and that this
-notice is included verbatim in any distributions. No written agreement,
-license, or royalty fee is required for any of the authorized uses.
-Modifications to this software may be copyrighted by their authors
-and need not follow the licensing terms described here, provided that
-the new terms are clearly indicated on the first page of each file where
-they apply.
-
-IN NO EVENT SHALL THE AUTHORS OR DISTRIBUTORS BE LIABLE TO ANY PARTY
-FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES
-ARISING OUT OF THE USE OF THIS SOFTWARE, ITS DOCUMENTATION, OR ANY
-DERIVATIVES THEREOF, EVEN IF THE AUTHORS HAVE BEEN ADVISED OF THE
-POSSIBILITY OF SUCH DAMAGE.
-
-THE AUTHORS AND DISTRIBUTORS SPECIFICALLY DISCLAIM ANY WARRANTIES,
-INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY,
-FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT. THIS SOFTWARE
-IS PROVIDED ON AN "AS IS" BASIS, AND THE AUTHORS AND DISTRIBUTORS HAVE
-NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR
-MODIFICATIONS.
-
-GOVERNMENT USE: If you are acquiring this software on behalf of the
-U.S. government, the Government shall have only "Restricted Rights"
-in the software and related documentation as defined in the Federal
-Acquisition Regulations (FARs) in Clause 52.227.19 (c) (2). If you
-are acquiring the software on behalf of the Department of Defense, the
-software shall be classified as "Commercial Computer Software" and the
-Government shall have only "Restricted Rights" as defined in Clause
-252.227-7013 (c) (1) of DFARs. Notwithstanding the foregoing, the
-authors grant the U.S. Government and others acting in its behalf
-permission to use and distribute the software in accordance with the
-terms specified in this license.
diff --git a/ext/tk/sample/tkextlib/tkimg/readme.txt b/ext/tk/sample/tkextlib/tkimg/readme.txt
deleted file mode 100644
index 4d9774492c..0000000000
--- a/ext/tk/sample/tkextlib/tkimg/readme.txt
+++ /dev/null
@@ -1,3 +0,0 @@
-The script 'demo.rb' is based on 'demo.tcl' of Tcl/Tk's 'Img' extention.
-Image data in 'demo.rb' is those of 'demo.tcl'.
-Please read 'license_terms_of_Img_extension' file.
diff --git a/ext/tk/sample/tkextlib/tktable/basic.rb b/ext/tk/sample/tkextlib/tktable/basic.rb
index 0d2d48893a..ece46b318e 100644
--- a/ext/tk/sample/tkextlib/tktable/basic.rb
+++ b/ext/tk/sample/tkextlib/tktable/basic.rb
@@ -29,11 +29,11 @@ table = Tk::TkTable.new(:rows=>rows, :cols=>cols, :variable=>ary,
:rowstretchmode=>:last, :colstretchmode=>:last,
:rowtagcommand=>proc{|row|
row = Integer(row)
- (row>0 && row%2 == 1)? 'OddRow': ''
+ return 'OddRow' if row>0 && row%2 == 1
},
:coltagcommand=>proc{|col|
col = Integer(col)
- (col>0 && col%2 == 1)? 'OddCol': ''
+ return 'OddCol' if col>0 && col%2 == 1
},
:selectmode=>:extended, :sparsearray=>false)
diff --git a/ext/tk/sample/tkextlib/tktable/command.rb b/ext/tk/sample/tkextlib/tktable/command.rb
index bf36159ccc..eb9ddffb78 100644
--- a/ext/tk/sample/tkextlib/tktable/command.rb
+++ b/ext/tk/sample/tkextlib/tktable/command.rb
@@ -45,11 +45,11 @@ table = Tk::TkTable.new(:rows=>rows, :cols=>cols,
:rowstretchmode=>:last, :colstretchmode=>:last,
:rowtagcommand=>proc{|row|
row = Integer(row)
- (row>0 && row%2 == 1)? 'OddRow': ''
+ return 'OddRow' if row>0 && row%2 == 1
},
:coltagcommand=>proc{|col|
col = Integer(col)
- (col>0 && col%2 == 1)? 'OddCol': ''
+ return 'OddCol' if col>0 && col%2 == 1
},
:selectmode=>:extended, :flashmode=>true,
:rowstretch=>:unset, :colstretch=>:unset,
diff --git a/ext/tk/sample/tkextlib/tktable/debug.rb b/ext/tk/sample/tkextlib/tktable/debug.rb
index d5cd5e49ba..3200c1c77a 100644
--- a/ext/tk/sample/tkextlib/tktable/debug.rb
+++ b/ext/tk/sample/tkextlib/tktable/debug.rb
@@ -29,7 +29,7 @@ table = Tk::TkTable.new(:rows=>rows, :cols=>cols, :variable=>ary,
:roworigin=>-5, :colorigin=>-2,
:coltagcommand=>proc{|col|
col = Integer(col)
- (col>0 && col%2 == 1)? 'OddCol': ''
+ return 'OddCol' if col>0 && col%2 == 1
},
:selectmode=>:extended, :flashmode=>true,
:rowstretch=>:unset, :colstretch=>:unset,
diff --git a/ext/tk/sample/tkextlib/tktable/maxsize.rb b/ext/tk/sample/tkextlib/tktable/maxsize.rb
index aff68ff377..c9ca745ee5 100644
--- a/ext/tk/sample/tkextlib/tktable/maxsize.rb
+++ b/ext/tk/sample/tkextlib/tktable/maxsize.rb
@@ -28,7 +28,7 @@ table = Tk::TkTable.new(:rows=>rows, :cols=>cols, :variable=>ary,
:titlerows=>1, :titlecols=>1,
:coltagcommand=>proc{|col|
col = Integer(col)
- (col>0 && col%2 == 1)? 'OddCol': ''
+ return 'OddCol' if col>0 && col%2 == 1
},
:selectmode=>:extended,
:colstretch=>:unset, :rowstretch=>:unset,
diff --git a/ext/tk/sample/tkextlib/treectrl/bitmaps.rb b/ext/tk/sample/tkextlib/treectrl/bitmaps.rb
deleted file mode 100644
index 745e6a2e5b..0000000000
--- a/ext/tk/sample/tkextlib/treectrl/bitmaps.rb
+++ /dev/null
@@ -1,76 +0,0 @@
-#
-# Demo: Bitmaps
-#
-def demoBitmaps(t)
- #if $Version_1_1_OrLater
- if @has_bgimg
- t.configure(:showroot=>false, :showbuttons=>false, :showlines=>false,
- :selectmode=>:browse, :orient=>:horizontal, :wrap=>'5 items',
- :showheader=>false, :backgroundimage=>@images['sky'])
- else
- t.configure(:showroot=>false, :showbuttons=>false, :showlines=>false,
- :selectmode=>:browse, :orient=>:horizontal, :wrap=>'5 items',
- :showheader=>false)
- end
-
- if $HasColumnCreate
- t.column_create(:itembackground=>['gray90', []])
- else
- t.column_configure(0, :itembackground=>['gray90', []])
- end
-
- t.element_create('elemTxt', :text,
- :fill=>[@SystemHighlightText, ['selected', 'focus']])
- t.element_create('elemSelTxt', :rect, :showfocus=>true,
- :fill=>[@SystemHighlight, ['selected', 'focus']])
- t.element_create('elemSelBmp', :rect, :outlinewidth=>4,
- :outline=>[@SystemHighlight, ['selected', 'focus']])
- t.element_create('elemBmp', :bitmap,
- :foreground=>[@SystemHighlight, ['selected', 'focus']],
- :background=>'linen',
- :bitmap=>['question' ['selected']])
-
- s = t.style_create('STYLE', :orient=>:vertical)
- t.style_elements(s, ['elemSelBmp', 'elemBmp', 'elemSelTxt', 'elemTxt'])
- t.style_layout(s, 'elemSelBmp', :union=>'elemBmp', :ipadx=>6, :ipady=>6)
- t.style_layout(s, 'elemBmp', :pady=>[0, 6], :expand=>:we)
- t.style_layout(s, 'elemSelTxt', :union=>'elemTxt', :ipadx=>2)
- t.style_layout(s, 'elemTxt', :expand=>:we)
-
- # Set default item style
- if $Version_1_1_OrLater
- t.defaultstyle = [s]
- end
-
- bitmap_names = %w(error gray75 gray50 gray25 gray12
- hourglass info questhead question warning)
-
- bitmap_names.each{|name|
- i = t.item_create
- unless $Version_1_1_OrLater
- t.item_style_set(i, 0, s)
- end
- t.item_text(i, 0, name)
- t.item_element_configure(i, 0, 'elemBmp', :bitmap=>name)
- t.item_lastchild(:root, i)
- }
-
- bitmap_names.each{|name|
- i = t.item_create
- t.item_style_set(i, 0, s)
- t.item_text(i, 0, name)
- if true
- t.item_element_configure(i, 0, 'elemBmp', :bitmap=>name,
- :foreground=>['brown', ''],
- :background=>['', ''])
- else
- t.item_element_configure(i, 0, 'elemBmp', :bitmap=>name,
- :foreground=>[
- @SystemHighlight, ['selected', 'focus'],
- 'brown', []
- ],
- :background=>['', []])
- end
- t.item_lastchild(:root, i)
- }
-end
diff --git a/ext/tk/sample/tkextlib/treectrl/demo.rb b/ext/tk/sample/tkextlib/treectrl/demo.rb
deleted file mode 100644
index e3d0180584..0000000000
--- a/ext/tk/sample/tkextlib/treectrl/demo.rb
+++ /dev/null
@@ -1,1307 +0,0 @@
-#!/usr/bin/env ruby
-
-require 'tk'
-require 'tkextlib/treectrl'
-
-$ScriptDir = File.dirname(File.expand_path(__FILE__))
-
-$HasColumnCreate = Tk::TreeCtrl::HasColumnCreateCommand
-
-$Version_1_1_OrLater = (TkPackage.vcompare(Tk::TreeCtrl.package_version, '1.1') >= 0)
-
-if Hash.instance_methods.include?('key')
- # probably ruby 1.9.x --> use Hash#key
- # Because Hash#index show warning "Hash#index is deprecated; use Hash#key".
-else
- # probably ruby 1.8.x --> use Hash#index
- class Hash
- alias key index
- end
-end
-
-class TkTreeCtrl_demo
- def initialize(dir)
- @ScriptDir = dir || '.'
-
- @thisPlatform = Tk::PLATFORM['platform']
- if @thisPlatform == 'unix' && Tk.windowingsystem == 'aqua'
- @thisPlatform = 'macosx'
- end
-
- @RandomN = [500]
-
- @images = Hash.new
- @sel_images = Hash.new
-
- @popup = Hash.new
- @mTree = Hash.new
- @mHeader = Hash.new
-
- @non_clear_list = []
-
- @demoCmd = Hash.new
- @demoFile = Hash.new
-
- # Get default colors
- w = TkListbox.new
- @SystemButtonFace = w[:highlightbackground]
- @SystemHighlight = w[:selectbackground]
- @SystemHighlightText = w[:selectforeground]
- w.destroy
-
- ####################
-
- make_source_window()
- make_menubar()
- make_main_window()
-
- if $Version_1_1_OrLater
- begin
- @tree2[:backgroundimage]
- @has_bgimg = true
- rescue
- @has_bgimg = false
- end
- else
- @has_bgimg = false
- end
-
- ####################
-
- make_list_popup()
- make_header_popup()
-
- init_pics('sky')
-
- ####################
-
- @tree2.bind('ButtonPress-3',
- proc{|w, x, y, rootx, rooty|
- show_list_popup(w, x, y, rootx, rooty)
- }, '%W %x %y %X %Y')
-
- # Allow "scan" bindings
- if @thisPlatform == 'windows'
- @tree2.bind_remove('Control-ButtonPress-3')
- end
-
- ####################
-
- init_demo_scripts_module()
- load_demo_scripts()
- init_demo_list()
-
- ####################
-
- @tree1.notify_bind(@tree1, 'Selection',
- proc{|c, t|
- if c == 1
- item = t.selection_get[0]
- demo_set(@demoCmd[item], @demoFile[item])
- end
- }, '%c %T')
-
- # When one item is selected in the demo list, display the styles in
- # that item.
- # See DemoClear for why the tag "DontDelete" is used
- @tree2.notify_bind('DontDelete', 'Selection',
- proc{|c, t|
- display_styles_in_item(t.selection_get[0]) if c == 1
- }, '%c %T')
- end
-
- ##########################
-
- def init_pics(*args)
- args.each{|pat|
- unless TkImage.names.find{|img| (name = @images.key(img)) && File.fnmatch(pat, name)}
- Dir.glob(File.join(@ScriptDir, 'pics', "#{pat}.gif")).each{|file|
- name = File.basename(file, '.gif')
- img = TkPhotoImage.new(:file=>file)
- @images[name] = img
- @sel_images[name] = TkPhotoImage.new
- @sel_images[name].copy(img)
- Tk::TreeCtrl.image_tint(@sel_images[name], @SystemHighlight, 128)
- }
- end
- }
- end
-
- ##########################
-
- private
-
- def make_menubar
- menuspec = [
- [['File']]
- ]
- if Tk::PLATFORM['platform'] != 'unix'
- TkConsole.create
- TkConsole.eval('.console conf -height 8')
- menuspec[0] << ['Console', proc{
- if TkComm.bool(TkConsole.eval('winfo ismapped .'))
- TkConsole.hide
- else
- TkConsole.show
- end
- }]
- end
- menuspec[0] << ['View Source', proc{toggle_source_window()}]
- menuspec[0] << ['Quit', proc{exit}]
- Tk.root.add_menubar(menuspec)
- end
-
- def make_source_window
- @src_top = TkToplevel.new
- f = TkFrame.new(@src_top, :borderwidth=>0)
- case @thisPlatform
- when 'macintosh', 'macos'
- font = TkFont.new(['Geneva', 9])
- when 'unix'
- font = TkFont.new(['Courier', -12])
- else
- font = TkFont.new(['Courier', 9])
- end
-
- @src_txt = TkText.new(f, :font=>font, :tabs=>font.measure('1234'),
- :wrap=>:none)
- xscr = @src_txt.xscrollbar(TkScrollbar.new(f))
- yscr = @src_txt.yscrollbar(TkScrollbar.new(f))
-
- f.pack(:expand=>true, :fill=>:both)
- f.grid_columnconfigure(0, :weight=>1)
- f.grid_rowconfigure(0, :weight=>1)
- @src_txt.grid(:row=>0, :column=>0, :sticky=>:news)
- xscr.grid(:row=>1, :column=>0, :sticky=>:we)
- yscr.grid(:row=>0, :column=>1, :sticky=>:ns)
-
- @src_top.protocol('WM_DELETE_WINDOW', proc{@src_top.withdraw})
- @src_top.geometry('-0+0')
- @src_top.withdraw
- end
-
- def show_source(file)
- @src_top.title("Demo Source: #{file}")
- @src_txt.value = IO.read(File.join(@ScriptDir, file))
- @src_txt.set_insert('1.0')
- end
-
- def toggle_source_window
- if @src_top.winfo_mapped?
- @src_top.withdraw
- else
- @src_top.deiconify
- end
- end
-
- def tree_plus_scrollbars_in_a_frame(parent, h, v)
- f = TkFrame.new(parent, :borderwidth=>1, :relief=>:sunken)
- case @thisPlatform
- when 'macintosh'
- font = TkFont.new(['Geneva', 9])
- when 'macos'
- font = TkFont.new(['Lucida Grande', 11])
- when 'unix'
- font = TkFont.new(['Helvetica', -12])
- else
- # There is a bug on my Win98 box with Tk_MeasureChars() and
- # MS Sans Serif 8.
- font = TkFont.new(['MS Sans', 8])
- end
-
- tree = Tk::TreeCtrl.new(f, :highlightthickness=>0,
- :borderwidth=>0, :font=>font)
- tree[:xscrollincrement] = 20
- tree.debug_configure(:enable=>false, :display=>false)
-
- if h
- h_scr = TkScrollbar.new(f, :orient=>:horizontal,
- :command=>proc{|*args| tree.xview(*args)})
- tree.notify_bind(h_scr, 'Scroll-x',
- proc{|w, l, u| w.set(l, u)}, '%W %l %u')
- h_scr.bind('ButtonPress-1', proc{tree.set_focus})
- end
-
- if v
- v_scr = TkScrollbar.new(f, :orient=>:vertical,
- :command=>proc{|*args| tree.yview(*args)})
- tree.notify_bind(v_scr, 'Scroll-y',
- proc{|w, l, u| w.set(l, u)}, '%W %l %u')
- v_scr.bind('ButtonPress-1', proc{tree.set_focus})
- end
-
- f.grid_columnconfigure(0, :weight=>1)
- f.grid_rowconfigure(0, :weight=>1)
- tree.grid(:row=>0, :column=>0, :sticky=>:news)
- h_scr.grid(:row=>1, :column=>0, :sticky=>:we) if h
- v_scr.grid(:row=>0, :column=>1, :sticky=>:ns) if v
-
- [f, tree]
- end
-
- def make_main_window
- Tk.root.title('Tk::TreeCtrl Demo')
-
- case @thisPlatform
- when 'macintosh', 'macosx'
- Tk.root.geometry('+40+40')
- else
- Tk.root.geometry('+0+30')
- end
-
- pane1 = TkPanedWindow.new(:orient=>:vertical, :borderwidth=>0)
- pane2 = TkPanedWindow.new(:orient=>:horizontal, :borderwidth=>0)
-
- # Tree + scrollbar: demos
- f1, @tree1 = tree_plus_scrollbars_in_a_frame(nil, false, true)
- @tree1.configure(:showbuttons=>false, :showlines=>:false,
- :showroot=>false, :height=>100)
- if $HasColumnCreate
- @tree1.column_create(:text=>'List of Demos',
- :expand=>true, :button=>false)
- else
- @tree1.column_configure(0, :text=>'List of Demos',
- :expand=>true, :button=>false)
- end
-
- # Tree + scrollbar: styles + elements in list
- f4, @tree4 = tree_plus_scrollbars_in_a_frame(nil, false, true)
- @tree4.configure(:showroot=>false, :height=>140)
- if $HasColumnCreate
- @tree4.column_create(:text=>'Elements and Styles',
- :expand=>true, :button=>false)
- else
- @tree4.column_configure(0, :text=>'Elements and Styles',
- :expand=>true, :button=>false)
- end
-
- # Tree + scrollbar: styles + elements in selected item
- f3, @tree3 = tree_plus_scrollbars_in_a_frame(nil, false, true)
- @tree3.configure(:showroot=>false)
- if $HasColumnCreate
- @tree3.column_create(:text=>'Styles in Item',
- :expand=>true, :button=>false)
- else
- @tree3.column_configure(0, :text=>'Styles in Item',
- :expand=>true, :button=>false)
- end
-
- pane1.add(f1, f4, f3, :height=>150)
- pane1.pack(:expand=>true, :fill=>:both)
-
- # Frame on right
- f2_base = TkFrame.new
-
- # Tree + scrollbars
- f2, @tree2 = tree_plus_scrollbars_in_a_frame(f2_base, true, true)
- @tree2.configure(:indent=>19)
- @tree2.debug_configure(:enable=>false, :display=>true,
- :erasecolor=>'pink', :displaydelay=>30)
-
- # Give it a big border to debug drawing
- @tree2.configure(:borderwidth=>6, :relief=>:ridge, :highlightthickness=>3)
-
- f2_base.grid_columnconfigure(0, :weight=>1)
- f2_base.grid_rowconfigure(0, :weight=>1)
- f2.grid(:row=>0, :column=>0, :sticky=>:news, :pady=>0)
-
- pane2.add(pane1, :width=>200)
- pane2.add(f2_base, :width=>450)
-
- pane2.pack(:expand=>true, :fill=>:both)
-
- ###
- # A treectrl widget can generate the following built-in events:
- # <ActiveItem> called when the active item changes
- # <Collapse-before> called before an item is closed
- # <Collapse-after> called after an item is closed
- # <Expand-before> called before an item is opened
- # <Expand-after> called after an item is opened
- # <Selection> called when items are added to or removed from the selection
- # <Scroll-x> called when horizontal scroll position changes
- # <Scroll-y> called when vertical scroll position changes
- #
- # The application programmer can define custom events to be
- # generated by the "T notify generate" command. The following events
- # are generated by the example bindings.
-
- @tree2.notify_install_event('Header')
- @tree2.notify_install_detail('Header', 'invoke')
-
- @tree2.notify_install_event('Drag')
- @tree2.notify_install_detail('Drag', 'begin')
- @tree2.notify_install_detail('Drag', 'end')
- @tree2.notify_install_detail('Drag', 'receive')
-
- @tree2.notify_install_event('Edit')
- @tree2.notify_install_detail('Edit', 'accept')
- end
-
- def make_list_popup
- @popup[:bgimg] = TkVariable.new
- @popup[:bgmode] = TkVariable.new
- @popup[:debug] = Hash.new{|h, k| h[k] = TkVariable.new}
- @popup[:doublebuffer] = TkVariable.new
- @popup[:linestyle] = TkVariable.new
- @popup[:orient] = TkVariable.new
- @popup[:selectmode] = TkVariable.new
- @popup[:show] = Hash.new{|h, k| h[k] = TkVariable.new}
-
- menuspec = [
- [ 'Collapse', [], nil, '', {:menu_config=>{:tearoff=>false}} ],
-
- [ 'Expand', [], nil, '', {:menu_config=>{:tearoff=>false}} ]
- ]
-
- # if $Version_1_1_OrLater
- if @has_bgimg
- menuspec << \
- [ 'Background Image',
- [
- [ 'none', [@popup[:bgimg], 'none'], nil, '',
- {:command=>proc{@tree2.backgroundimage = ''}} ],
- [ 'sky', [@popup[:bgimg], 'sky'], nil, '',
- {:command=>proc{
- @tree2.backgroundimage = @images[@popup[:bgimg].value]}} ]
- ],
- nil, '', {:menu_config=>{:tearoff=>false}}
- ]
- end
-
- menuspec.concat([
- [ 'Background Mode',
- %w(column index row visindex).collect{|val|
- [ val, [@popup[:bgmode], val] , nil, '',
- {:command=>proc{@tree2.backgroundmode = @popup[:bgmode].value}} ]
- },
- nil, '', {:menu_config=>{:tearoff=>false}}
- ],
-
- [ 'Debug',
- [
- [ 'Data', @popup[:debug][:data], nil, '',
- {:command=>proc{
- @tree2.debug_configure(:data=>@popup[:debug][:data].value)
- }
- } ],
- [ 'Display', @popup[:debug][:display], nil, '',
- {:command=>proc{
- @tree2.debug_configure(:display=>@popup[:debug][:display].value)
- }
- } ],
- [ 'Enable', @popup[:debug][:enable], nil, '',
- {:command=>proc{
- @tree2.debug_configure(:enable=>@popup[:debug][:enable].value)
- }
- } ]
- ],
- nil, '', {:menu_config=>{:tearoff=>false}}
- ],
-
- [ 'Buffering',
- [
- [ 'none', [@popup[:doublebuffer], 'none'], nil, '',
- {:command=>proc{
- @tree2.doublebuffer = @popup[:doublebuffer].value
- }
- } ],
- [ 'item', [@popup[:doublebuffer], 'item'], nil, '',
- {:command=>proc{
- @tree2.doublebuffer = @popup[:doublebuffer].value
- }
- } ],
- [ 'window', [@popup[:doublebuffer], 'window'], nil, '',
- {:command=>proc{
- @tree2.doublebuffer = @popup[:doublebuffer].value
- }
- } ]
- ],
- nil, '', {:menu_config=>{:tearoff=>false}}
- ],
-
- [ 'Line style',
- [
- [ 'dot', [@popup[:linestyle], 'dot'], nil, '',
- {:command=>proc{@tree2.linestyle = @popup[:linestyle].value}} ],
- [ 'solid', [@popup[:linestyle], 'solid'], nil, '',
- {:command=>proc{@tree2.linestyle = @popup[:linestyle].value}} ]
- ],
- nil, '', {:menu_config=>{:tearoff=>false}}
- ],
-
- [ 'Orient',
- [
- [ 'Horizontal', [@popup[:orient], 'horizontal'], nil, '',
- {:command=>proc{@tree2.orient = @popup[:orient].value}} ],
- [ 'Vertical', [@popup[:orient], 'vertical'], nil, '',
- {:command=>proc{@tree2.orient = @popup[:orient].value}} ]
- ],
- nil, '', {:menu_config=>{:tearoff=>false}}
- ],
-
- [ 'Selectmode',
- %w(list browse extended multiple single).collect{|val|
- [ val, [@popup[:selectmode], val] , nil, '',
- {:command=>proc{@tree2.selectmode = @popup[:selectmode].value}} ]
- },
- nil, '', {:menu_config=>{:tearoff=>false}}
- ],
-
- [ 'Show',
- [
- [ 'Buttons', @popup[:show][:buttons], nil, '',
- {:command=>proc{
- @tree2.showbuttons = @popup[:show][:buttons].value
- }
- } ],
- [ 'Header', @popup[:show][:header], nil, '',
- {:command=>proc{
- @tree2.showheader = @popup[:show][:header].value
- }
- } ],
- [ 'Lines', @popup[:show][:lines], nil, '',
- {:command=>proc{
- @tree2.showlines = @popup[:show][:lines].value
- }
- } ],
- [ 'Root', @popup[:show][:root], nil, '',
- {:command=>proc{
- @tree2.showroot = @popup[:show][:root].value
- }
- } ],
- [ 'Root Button', @popup[:show][:rootbutton], nil, '',
- {:command=>proc{
- @tree2.showrootbutton = @popup[:show][:rootbutton].value
- }
- } ]
- ],
- nil, '', {:menu_config=>{:tearoff=>false}}
- ],
-
- [ 'Visible', [], nil, '', {:menu_config=>{:tearoff=>false}} ]
- ])
-
- m = TkMenu.new_menuspec(menuspec, @tree2, false)
- @non_clear_list << m
- @mTree[@tree2] = m
- end
-
- def show_list_popup(w, x, y, rootx, rooty)
- id = w.identify(x, y)
- unless id.empty?
- if id[0] == 'header'
- col = id[1]
- @popup[:column].value = col
- @popup[:arrow].value = w.column_cget(col, :arrow)
- @popup[:arrowside].value = w.column_cget(col, :arrowside)
- @popup[:arrowgravity].value = w.column_cget(col, :arrowgravity)
- @popup[:expand].value = w.column_cget(col, :expand)
- @popup[:squeeze].value = w.column_cget(col, :squeeze)
- @popup[:justify].value = w.column_cget(col, :justify)
- @mHeader[w].popup(rootx, rooty)
- return
- end
- end
-
- m = @mTree[w].entrycget('Collapse', :menu)
- m.delete(0, :end)
- if $Version_1_1_OrLater
- m.add_command(:label=>'All', :command=>proc{w.item_collapse(:all)})
- else
- m.add_command(:label=>'All', :command=>proc{w.collapse(:all)})
- end
- unless id.empty?
- if id[0] == 'item'
- item = id[1]
- if $Version_1_1_OrLater
- m.add_command(:label=>"Item #{item}",
- :command=>proc{w.item_collapse(item)})
- m.add_command(:label=>"Item #{item} (recurse)",
- :command=>proc{w.item_collapse_recurse(item)})
- else
- m.add_command(:label=>"Item #{item}",
- :command=>proc{w.collapse(item)})
- m.add_command(:label=>"Item #{item} (recurse)",
- :command=>proc{w.collapse_recurse(item)})
- end
- end
- end
-
- m = @mTree[w].entrycget('Expand', :menu)
- m.delete(0, :end)
- if $Version_1_1_OrLater
- m.add_command(:label=>'All', :command=>proc{w.item_expand(:all)})
- else
- m.add_command(:label=>'All', :command=>proc{w.expand(:all)})
- end
- unless id.empty?
- if id[0] == 'item'
- item = id[1]
- if $Version_1_1_OrLater
- m.add_command(:label=>"Item #{item}",
- :command=>proc{w.item_expand(item)})
- m.add_command(:label=>"Item #{item} (recurse)",
- :command=>proc{w.item_expand_recurse(item)})
- else
- m.add_command(:label=>"Item #{item}",
- :command=>proc{w.expand(item)})
- m.add_command(:label=>"Item #{item} (recurse)",
- :command=>proc{w.expand_recurse(item)})
- end
- end
- end
-
- [:data, :display, :enable].each{|k|
- @popup[:debug][k].value = w.debug_cget(k)
- }
- # if $Version_1_1_OrLater
- if @has_bgimg
- @popup[:bgimg].value = @images.key(w[:backgroundimage])
- end
- @popup[:bgmode].value = w[:backgroundmode]
- @popup[:doublebuffer].value = w[:doublebuffer]
- @popup[:linestyle].value = w[:linestyle]
- @popup[:orient].value = w[:orient]
- @popup[:selectmode].value = w[:selectmode]
- @popup[:show][:buttons].value = w[:showbuttons]
- @popup[:show][:header].value = w[:showheader]
- @popup[:show][:lines].value = w[:showlines]
- @popup[:show][:root].value = w[:showroot]
- @popup[:show][:rootbutton].value = w[:showrootbutton]
-
- m = @mTree[w].entrycget('Visible', :menu)
- m.delete(0, :end)
- @popup[:visible] = []
- (0...(w.numcolumns)).each{|i|
- @popup[:visible][i] = TkVariable.new(w.column_cget(i, :visible))
- txt = w.column_cget(i, :text)
- img_name = w.column_cget(i, :image)
- img_name = @images.key(img_name) if img_name.kind_of?(TkImage)
- m.add_checkbutton(:variable=>@popup[:visible][i],
- :label=>"Column #{i} \"#{txt}\" [#{img_name}]",
- :command=>proc{w.column_configure(i, :visible=>@popup[:visible][i].value)})
- }
-
- @mTree[w].popup(rootx, rooty)
- end
-
- def make_header_popup
- @popup[:column] = TkVariable.new unless @popup[:column]
- @popup[:arrow] = TkVariable.new
- @popup[:arrowside] = TkVariable.new
- @popup[:arrowgravity] = TkVariable.new
- @popup[:expand] = TkVariable.new
- @popup[:squeeze] = TkVariable.new
- @popup[:justify] = TkVariable.new
-
- menuspec = [
- [ 'Arrow',
- [
- [ 'None', [@popup[:arrow], 'none'], nil, '',
- {:command=>proc{
- @tree2.column_configure(@popup[:column].value, :arrow=>:none)
- }
- } ],
- [ 'Up', [@popup[:arrow], 'up'], nil, '',
- {:command=>proc{
- @tree2.column_configure(@popup[:column].value, :arrow=>:up)
- }
- } ],
- [ 'Down', [@popup[:arrow], 'down'], nil, '',
- {:command=>proc{
- @tree2.column_configure(@popup[:column].value, :arrow=>:down)
- }
- } ],
-
- '---',
-
- [ 'Side Left', [@popup[:arrowside], 'left'], nil, '',
- {:command=>proc{
- @tree2.column_configure(@popup[:column].value,
- :arrowside=>:left)
- }
- } ],
- [ 'Side Right', [@popup[:arrowside], 'right'], nil, '',
- {:command=>proc{
- @tree2.column_configure(@popup[:column].value,
- :arrowside=>:right)
- }
- } ],
-
- '---',
-
- [ 'Gravity Left', [@popup[:arrowgravity], 'left'], nil, '',
- {:command=>proc{
- @tree2.column_configure(@popup[:column].value,
- :arrowgravity=>:left)
- }
- } ],
- [ 'Gravity Right', [@popup[:arrowgravity], 'right'], nil, '',
- {:command=>proc{
- @tree2.column_configure(@popup[:column].value,
- :arrowgravity=>:right)
- }
- } ],
- ],
- nil, '', {:menu_config=>{:tearoff=>false}} ],
-
- [ 'Expand', @popup[:expand], nil, '',
- {:command=>proc{
- @tree2.column_configure(@popup[:column].value,
- :expand=>@popup[:expand].value)
- }
- } ],
-
- [ 'Squeeze', @popup[:squeeze], nil, '',
- {:command=>proc{
- @tree2.column_configure(@popup[:column].value,
- :squeeze=>@popup[:squeeze].value)
- }
- } ],
-
- [ 'Justify',
- [
- [ 'Left', [@popup[:justify], 'left'], nil, '',
- {:command=>proc{
- @tree2.column_configure(@popup[:column].value, :justify=>:left)
- }
- } ],
- [ 'Center', [@popup[:justify], 'center'], nil, '',
- {:command=>proc{
- @tree2.column_configure(@popup[:column].value,
- :justify=>:center)
- }
- } ],
- [ 'Right', [@popup[:justify], 'right'], nil, '',
- {:command=>proc{
- @tree2.column_configure(@popup[:column].value,
- :justify=>:right)
- }
- } ]
- ],
- nil, '', {:menu_config=>{:tearoff=>false}} ]
- ]
-
- m = TkMenu.new_menuspec(menuspec, @tree2, false)
- @non_clear_list << m
- @mHeader[@tree2] = m
- end
-
- ###########################
-
- def init_demo_scripts_module
- @demo_scripts = Module.new
-
- master = self
-
- has_bgimg = @has_bgimg
-
- scriptDir = @ScriptDir
-
- thisPlatform = @thisPlatform
-
- randomN = @RandomN
-
- images = @images
- sel_images = @sel_images
-
- systemButtonFace = @SystemButtonFace
- systemHighlight = @SystemHighlight
- systemHighlightText = @SystemHighlightText
-
- proc_disp_styles_in_item = proc{|item|
- master.instance_eval{ display_styles_in_item(item) }
- }
-
- @demo_scripts.instance_eval{
- @master = master
-
- @has_bgimg = has_bgimg
-
- @display_styles_in_item = proc_disp_styles_in_item
-
- @Priv = TkVarAccess.new('::TreeCtrl::Priv')
-
- @ScriptDir = scriptDir
-
- @thisPlatform = thisPlatform
-
- @RandomN = randomN
-
- @images = images
- @sel_images = sel_images
-
- @SystemButtonFace = systemButtonFace
- @SystemHighlight = systemHighlight
- @SystemHighlightText = systemHighlightText
- }
-
- class << @demo_scripts
- def _get_binding
- binding
- end
- private :_get_binding
-
- def load_demo(file)
- puts "load \"#{file}\"" if $DEBUG
- begin
- eval(IO.readlines(file).join, _get_binding())
- rescue Exception => e
- bt = e.backtrace
-
- if bt[0] =~ /^([^:]+):(\d+):/
- errline = $2.to_i
- else
- raise e
- end
-
- if bt[1] =~ /^([^:]+):(\d+):/
- bt.unshift("#{file}:#{errline - $2.to_i + 1}")
- raise e
- else
- raise e
- end
- end
- end
-
- def init_pics(*args)
- @master.init_pics(*args)
- end
- end
- end
-
- def load_demo_scripts
- # demo sources
- [
- 'bitmaps',
- 'explorer',
- 'help',
- 'imovie',
- 'layout',
- 'mailwasher',
- 'outlook-folders',
- 'outlook-newgroup',
- 'random',
- 'www-options'
- ].each{|f|
- @demo_scripts.load_demo(File.join(@ScriptDir, "#{f}.rb"))
- }
- end
-
- ###########################
-
- def init_demo_list
- @tree1.element_create('e1', :text,
- :fill=>[@SystemHighlightText, ['selected', 'focus']])
- @tree1.element_create('e2', :rect, :showfocus=>true,
- :fill=>[
- @SystemHighlight, ['selected', 'focus'],
- 'gray', ['selected', '!focus'],
- ])
- @tree1.style_create('s1')
- @tree1.style_elements('s1', ['e2', 'e1'])
-
- # Tk listbox has linespace + 1 height
- @tree1.style_layout('s1', 'e2', :union=>['e1'],
- :ipadx=>2, :ipady=>[0, 1], :iexpand=>:e)
-
- if $Version_1_1_OrLater
- @tree1.defaultstyle = 's1'
- end
-
- ###
- [
- ["Random #{@RandomN[0]} Items", :demoRandom, 'random.rb'],
- ["Random #{@RandomN[0]} Items, Button Images", :demoRandom2, 'random.rb'],
- ["Outlook Express (Folders)", :demoOutlookFolders, 'outlook-folders.rb'],
- ["Outlook Express (Newsgroup)", :demoOutlookNewsgroup, 'outlook-newgroup.rb'],
- ["Explorer (Details)", :demoExplorerDetails, 'explorer.rb'],
- ["Explorer (List)", :demoExplorerList, 'explorer.rb'],
- ["Explorer (Large icons)", :demoExplorerLargeIcons, 'explorer.rb'],
- ["Explorer (Small icons)", :demoExplorerSmallIcons, 'explorer.rb'],
- ["Internet Options", :demoInternetOptions, 'www-options.rb'],
- ["Help Contents", :demoHelpContents, 'help.rb'],
- ["Layout", :demoLayout, 'layout.rb'],
- ["MailWasher", :demoMailWasher, 'mailwasher.rb'],
- ["Bitmaps", :demoBitmaps, 'bitmaps.rb'],
- ["iMovie", :demoIMovie, 'imovie.rb']
- ].each{|label, cmd, file|
- item = @tree1.item_create
- @tree1.item_lastchild(:root, item)
- unless $Version_1_1_OrLater
- @tree1.item_style_set(item, 0, 's1')
- end
- @tree1.item_text(item, 0, label)
- @demoCmd[item] = cmd
- @demoFile[item] = file
- }
-
- @tree1.yview_moveto(0.0)
- end
-
- def demo_set(cmd, file)
- demo_clear()
- clicks = Tk::Clock.clicks
- @demo_scripts.__send__(cmd, @tree2)
- clicks = Tk::Clock.clicks - clicks
- puts "set list in #{'%.2g'%(clicks/1000000.0)} seconds (#{clicks} clicks)"
- @tree2.xview_moveto(0)
- @tree2.yview_moveto(0)
- Tk.update
- display_styles_in_list()
- show_source(file)
- end
-
- def display_styles_in_list
- # Create elements and styles the first time this is called
- if @tree4.style_names.empty?
- @tree4.element_create('e1', :text,
- :fill=>[@SystemHighlightText,['selected','focus']])
- @tree4.element_create('e2', :text,
- :fill=>[
- @SystemHighlightText, ['selected','focus'],
- '', ['selected','!focus'],
- 'blue', []
- ])
- @tree4.element_create('e3', :rect, :showfocus=>true,
- :fill=>[
- @SystemHighlight, ['selected','focus'],
- 'gray', ['selected', '!focus']
- ])
-
- @tree4.style_create('s1')
- @tree4.style_elements('s1', ['e3', 'e1'])
- @tree4.style_layout('s1', 'e3', :union=>['e1'], :ipadx=>1, :ipady=>[0,1])
-
- @tree4.style_create('s2')
- @tree4.style_elements('s2', ['e3', 'e1', 'e2'])
- @tree4.style_layout('s2', 'e1', :padx=>[0,4])
- @tree4.style_layout('s2', 'e3', :union=>['e1', 'e2'],
- :ipadx=>1, :ipady=>[0,1])
- end
-
- # Clear the list
- @tree4.item_delete(:all)
-
- # One item for each element in the demo list
- @tree2.element_names.sort.each{|elem|
- if $Version_1_1_OrLater
- item = @tree4.item_create(:button=>true)
- @tree4.item_collapse(item)
- else
- item = @tree4.item_create
- @tree4.item_hasbutton(item, true)
- @tree4.collapse(item)
- end
- @tree4.item_style_set(item, 0, 's1')
- @tree4.item_text(item, 0,
- "Element #{elem} (#{@tree2.element_type(elem)})")
-
- # One item for each configuration option for this element
- @tree2.element_configinfo(elem).each{|name, x, y, default, current|
- item2 = @tree4.item_create
-
- if default == current
- @tree4.item_style_set(item2, 0, 's1')
- @tree4.item_complex(item2, [
- ['e1', {:text=>"#{name} #{current.inspect}"}]
- ])
- else
- @tree4.item_style_set(item2, 0, 's2')
- @tree4.item_complex(item2, [
- ['e1', {:text=>name}],
- ['e2', {:text=>current.inspect}]
- ])
- end
-
- @tree4.item_lastchild(item, item2)
- }
-
- @tree4.item_lastchild(:root, item)
- }
-
- # One item for each style in the demo list
- @tree2.style_names.sort.each{|sty|
- if $Version_1_1_OrLater
- item = @tree4.item_create(:button=>true)
- @tree4.item_collapse(item)
- else
- item = @tree4.item_create
- @tree4.item_hasbutton(item, true)
- @tree4.collapse(item)
- end
- @tree4.item_style_set(item, 0, 's1')
- @tree4.item_text(item, 0, "Style #{sty}")
-
- # One item for each element in the style
- @tree2.style_elements(sty).each{|elem|
- if $Version_1_1_OrLater
- item2 = @tree4.item_create(:button=>true)
- @tree4.item_collapse(item2)
- else
- item2 = @tree4.item_create
- @tree4.item_hasbutton(item2, true)
- @tree4.collapse(item2)
- end
- @tree4.item_style_set(item2, 0, 's1')
- @tree4.item_text(item2, 0,
- "Element #{elem} (#{@tree2.element_type(elem)})")
-
- # One item for each layout option for this element in this style
- @tree2.style_layout(sty, elem).each{|k, v|
- item3 = @tree4.item_create
- unless $Version_1_1_OrLater
- @tree4.item_hasbutton(item3, false)
- end
- @tree4.item_style_set(item3, 0, 's1')
- @tree4.item_text(item3, 0, "#{k} #{v.inspect}")
- @tree4.item_lastchild(item2, item3)
- }
-
- @tree4.item_lastchild(item, item2)
- }
-
- @tree4.item_lastchild(:root, item)
- }
-
- @tree4.xview_moveto(0)
- @tree4.yview_moveto(0)
- end
-
- def display_styles_in_item(item)
- @tree3.column_configure(0, :text=>"Styles in item #{@tree2.index(item)}")
-
- # Create elements and styles the first time this is called
- if @tree3.style_names.empty?
- @tree3.element_create('e1', :text,
- :fill=>[@SystemHighlightText,['selected','focus']])
- @tree3.element_create('e2', :text,
- :fill=>[
- @SystemHighlightText, ['selected','focus'],
- '', ['selected','!focus'],
- 'blue', []
- ])
- @tree3.element_create('e3', :rect, :showfocus=>true,
- :fill=>[
- @SystemHighlight, ['selected','focus'],
- 'gray', ['selected', '!focus']
- ])
-
- @tree3.style_create('s1')
- @tree3.style_elements('s1', ['e3', 'e1'])
- @tree3.style_layout('s1', 'e3', :union=>['e1'], :ipadx=>1, :ipady=>[0,1])
-
- @tree3.style_create('s2')
- @tree3.style_elements('s2', ['e3', 'e1', 'e2'])
- @tree3.style_layout('s2', 'e1', :padx=>[0,4])
- @tree3.style_layout('s2', 'e3', :union=>['e1', 'e2'],
- :ipadx=>1, :ipady=>[0,1])
- end
- # Clear the list
- @tree3.item_delete(:all)
-
- # One item for each item-column
- column = 0
- @tree2.item_style_set(item).each{|sty|
- item2 = @tree3.item_create
- if $Version_1_1_OrLater
- @tree3.item_collapse(item2)
- else
- @tree3.collapse(item2)
- end
- @tree3.item_style_set(item2, 0, 's1')
- @tree3.item_element_configure(item2, 0, 'e1',
- :text=>"Column #{column}: Style #{sty}")
-
- button = false
-
- # One item for each element in this style
- unless sty.to_s.empty?
- @tree2.item_style_elements(item, column).each{|elem|
- button = true
- if $Version_1_1_OrLater
- item3 = @tree3.item_create(:button=>true)
- else
- item3 = @tree3.item_create
- @tree3.item_hasbutton(item3, true)
- end
- if $Version_1_1_OrLater
- @tree3.item_collapse(item3)
- else
- @tree3.collapse(item3)
- end
- @tree3.item_style_set(item3, 0, 's1')
- @tree3.item_element_configure(item3, 0, 'e1',
- :text=>"Element #{elem} (#{@tree2.element_type(elem)})")
-
- # One item for each configuration option in this element
- @tree2.item_element_configinfo(item, column, elem) \
- .each{|name, x, y, default, current|
- item4 = @tree3.item_create
- masterDefault = @tree2.element_cget(elem, name)
- sameAsMaster = (masterDefault == current)
- if !sameAsMaster && current == ''
- sameAsMaster = true
- current = masterDefault
- end
-
- if sameAsMaster
- @tree3.item_style_set(item4, 0, 's1')
- @tree3.item_complex(item4, [
- ['e1',
- {:text=>"#{name} #{current.inspect}"}]
- ])
- else
- @tree3.item_style_set(item4, 0, 's2')
- @tree3.item_complex(item4, [
- ['e1', {:text=>name}],
- ['e2', {:text=>current.inspect}]
- ])
- end
- @tree3.item_lastchild(item3, item4)
- }
- @tree3.item_lastchild(item2, item3)
- }
- if $Version_1_1_OrLater
- @tree3.item_configure(item2, :button=>true) if button
- else
- @tree3.item_hasbutton(item2, true) if button
- end
- end
- @tree3.item_lastchild(:root, item2)
- column += 1
- }
-
- @tree3.xview_moveto(0)
- @tree3.yview_moveto(0)
- end
-
- def demo_clear
- # Clear the demo list
- @tree2.item_delete(:all)
-
- # Clear all bindings on the demo list added by the previous demo.
- # This is why DontDelete is used for the <Selection> binding.
- @tree2.notify_bindinfo(@tree2).each{|ev|
- @tree2.notify_bind_remove(@tree2, ev)
- }
-
- # Clear all run-time states
- @tree2.state_names.each{|st| @tree2.state_undefine(st) }
-
- # Clear the styles-in-item list
- @tree3.item_delete(:all)
-
- # Delete columns in demo list
- while (@tree2.numcolumns > 0)
- @tree2.column_delete(0)
- end
-
- # Delete all styles in demo list
- @tree2.style_delete(*(@tree2.style_names))
-
- # Delete all elements in demo list
- @tree2.element_delete(*(@tree2.element_names))
-
- if $Version_1_1_OrLater
- @tree2.item_configure(:root, :button=>false)
- @tree2.item_expand(:root)
- else
- @tree2.item_hasbutton(:root, false)
- @tree2.expand(:root)
- end
-
- # Restore some happy defaults to the demo list
- # if $Version_1_1_OrLater
- if @has_bgimg
- @tree2.configure(:orient=>:vertical, :wrap=>'',
- :xscrollincrement=>0, :yscrollincrement=>0,
- :itemheight=>0, :showheader=>true,
- :background=>'white', :scrollmargin=>0,
- :xscrolldelay=>50, :yscrolldelay=>50,
- :openbuttonimage=>'', :closedbuttonimage=>'',
- :backgroundmode=>:row, :treecolumn=>0, :indent=>19,
- :defaultstyle=>'', :backgroundimage=>'')
- else
- @tree2.configure(:orient=>:vertical, :wrap=>'',
- :xscrollincrement=>0, :yscrollincrement=>0,
- :itemheight=>0, :showheader=>true,
- :background=>'white', :scrollmargin=>0,
- :xscrolldelay=>50, :yscrolldelay=>50,
- :openbuttonimage=>'', :closedbuttonimage=>'',
- :backgroundmode=>:row, :treecolumn=>0, :indent=>19)
- end
-
- # Restore default bindings to the demo list
- @tree2.bindtags = [ @tree2, Tk::TreeCtrl, @tree2.winfo_toplevel, :all ]
-
- @tree2.winfo_children.each{|w|
- w.destroy unless @non_clear_list.include?(w)
- }
- end
-end
-
-TkTreeCtrl_demo.new($ScriptDir)
-
-##############################################
-
-def cursor_window(top = nil)
- top.destroy if top.kind_of?(TkWindow) && top.winfo_exist?
- top = TkToplevel.new(:title=>'Cursor Window')
-
- c = TkCanvas.new(top, :background=>'white',
- :width=>50*10, :highlightthickness=>0,
- :borderwidth=>0).pack(:expand=>true, :fill=>:both)
- cursors = %w(
- X_cursor
- arrow
- based_arrow_down
- based_arrow_up
- boat
- bogosity
- bottom_left_corner
- bottom_right_corner
- bottom_side
- bottom_tee
- box_spiral
- center_ptr
- circle
- clock
- coffee_mug
- cross
- cross_reverse
- crosshair
- diamond_cross
- dot
- dotbox
- double_arrow
- draft_large
- draft_small
- draped_box
- exchange
- fleur
- gobbler
- gumby
- hand1
- hand2
- heart
- icon
- iron_cross
- left_ptr
- left_side
- left_tee
- leftbutton
- ll_angle
- lr_angle
- man
- middlebutton
- mouse
- pencil
- pirate
- plus
- question_arrow
- right_ptr
- right_side
- right_tee
- rightbutton
- rtl_logo
- sailboat
- sb_down_arrow
- sb_h_double_arrow
- sb_left_arrow
- sb_right_arrow
- sb_up_arrow
- sb_v_double_arrow
- shuttle
- sizing
- spider
- spraycan
- star
- target
- tcross
- top_left_arrow
- top_left_corner
- top_right_corner
- top_side
- top_tee
- trek
- ul_angle
- umbrella
- ur_angle
- watch
- xterm
- )
-
- orig_cursor = c.cursor
- col = 0
- row = 0
-
- cursors.each{|cur|
- x = col * 50
- y = row * 40
-
- begin
- c.cursor = cur
-
- r = TkcRectangle.new(c, x, y, x+50, y+40,
- :fill=>'gray90', :outline=>'black', :width=>2)
- t = TkcText.new(c, x+50/2, y+4, :text=>cur, :anchor=>:n, :width=>42)
-
- col += 1
- if col >= 10
- col = 0
- row += 1
- end
-
- r.bind('Enter', proc{c.cursor = cur; r.fill = 'linen'})
- r.bind('Leave', proc{c.cursor = ''; r.fill = 'gray90'})
-
- t.bind('Enter', proc{c.cursor = cur})
- t.bind('Leave', proc{c.cursor = ''})
- rescue
- c.cursor = orig_cursor
- end
- }
-
- c.cursor = orig_cursor
- c.height = (row + 1) * 40
-end
-
-cursor_window()
-
-##############################################
-
-# A little screen magnifier for X11
-if Tk::PLATFORM['platform'] == 'unix' && Tk.windowingsystem != 'aqua'
- def show_loupe(setting=nil)
- loupe = (setting.kind_of?(Hash))? setting: {}
- loupe[:zoom] = 3 unless loupe[:zoom]
- loupe[:x] = 0 unless loupe[:x]
- loupe[:y] = 0 unless loupe[:y]
- loupe[:auto] = true unless loupe[:auto]
- loupe[:delay] = 500 unless loupe[:delay]
- loupe[:image] =
- TkPhotoImage.new(:width=>150, :height=>150) unless loupe[:image]
-
- top = TkToplevel.new(:geometry=>'-0+30',
- :title=>'A little screen magnifier for X11')
- TkLabel.new(top, :image=>loupe[:image]).pack
-
- TkTimer.new(proc{loupe[:delay]}, -1, proc{
- x, y = TkWinfo.pointerxy(Tk.root)
- if loupe[:auto] || loupe[:x] != x || loupe[:y] != y
- w = loupe[:image].width
- h = loupe[:image].height
- Tk::TreeCtrl.loupe(loupe[:image], x, y, w, h, loupe[:zoom])
- loupe[:x] = x
- loupe[:y] = y
- end
- }).start
- end
-
- show_loupe()
-end
-
-##############################################
-
-Tk.mainloop
diff --git a/ext/tk/sample/tkextlib/treectrl/explorer.rb b/ext/tk/sample/tkextlib/treectrl/explorer.rb
deleted file mode 100644
index 242777cbce..0000000000
--- a/ext/tk/sample/tkextlib/treectrl/explorer.rb
+++ /dev/null
@@ -1,430 +0,0 @@
-
-def demoExplorerAux(t, dir_proc, file_proc)
- base_dir = File.dirname(File.dirname(@ScriptDir))
-
- clicks = Tk::Clock.clicks
- globDirs = Dir.glob(File.join(base_dir, '*')).find_all{|file|
- FileTest.directory?(file)
- }
- clickGlobDirs = Tk::Clock.clicks - clicks
-
- clicks = Tk::Clock.clicks
- list = globDirs.sort
- clickSortDirs = Tk::Clock.clicks - clicks
-
- clicks = Tk::Clock.clicks
- list.each{|file| dir_proc.call(file)}
- clickAddDirs = Tk::Clock.clicks - clicks
-
- clicks = Tk::Clock.clicks
- globFiles = Dir.glob(File.join(base_dir, '*')).find_all{|file|
- FileTest.file?(file)
- }
- clickGlobFiles = Tk::Clock.clicks - clicks
-
- clicks = Tk::Clock.clicks
- list = globFiles.sort
- clickSortFiles = Tk::Clock.clicks - clicks
-
- clicks = Tk::Clock.clicks
- list.each{|file| file_proc.call(file)}
- clickAddFiles = Tk::Clock.clicks - clicks
-
- gd = '%.2g' % (clickGlobDirs / 1000000.0)
- sd = '%.2g' % (clickSortDirs / 1000000.0)
- ad = '%.2g' % (clickAddDirs / 1000000.0)
- gf = '%.2g' % (clickGlobFiles / 1000000.0)
- sf = '%.2g' % (clickSortFiles / 1000000.0)
- af = '%.2g' % (clickAddFiles / 1000000.0)
-
- puts "dirs(#{globDirs.length}) glob/sort/add #{gd}/#{sd}/#{ad} files(#{globFiles.length}) glob/sort/add #{gf}/#{sf}/#{af}"
-
- @Priv[:DirCnt, t] = globDirs.length
-end
-
-#
-# Demo: explorer files
-#
-def demoExplorerDetails(t)
- height = t.font.metrics(:linespace)
- height = 18 if height < 18
-
- t.configure(:showroot=>false, :showbuttons=>false, :showlines=>false,
- :itemheight=>height, :selectmode=>:extended,
- :xscrollincrement=>20, :scrollmargin=>16,
- :xscrolldelay=>[500, 50], :yscrolldelay=>[500, 50])
-
- init_pics('small-*')
-
- if $HasColumnCreate
- t.column_create(:text=>'Name', :tag=>'name',
- :width=>200, :arrow=>:up, :arrowpad=>6)
- t.column_create(:text=>'Size', :tag=>'size', :justify=>:right,
- :width=>60, :arrowside=>:left, :arrowgravity=>:right)
- t.column_create(:text=>'Type', :tag=>'type', :width=>120)
- t.column_create(:text=>'Modified', :tag=>'modified', :width=>130)
- else
- t.column_configure(0, :text=>'Name', :tag=>'name',
- :width=>200, :arrow=>:up, :arrowpad=>6)
- t.column_configure(1, :text=>'Size', :tag=>'size', :justify=>:right,
- :width=>60, :arrowside=>:left, :arrowgravity=>:right)
- t.column_configure(2, :text=>'Type', :tag=>'type', :width=>120)
- t.column_configure(3, :text=>'Modified', :tag=>'modified', :width=>130)
- end
-
- t.element_create('e1', :image,
- :image=>[
- @sel_images['small-folder'], ['selected'],
- @images['small-folder'], []
- ])
- t.element_create('e2', :text, :lines=>1,
- :fill=>[@SystemHighlightText, ['selected', 'focus']])
- t.element_create('txtType', :text, :lines=>1)
- t.element_create('txtSize', :text, :lines=>1,
- :datatype=>:integer, :format=>'%dKB')
- t.element_create('txtDate', :text, :lines=>1,
- :datatype=>:time, :format=>'%d/%m/%y %I:%M %p')
- t.element_create('e4', :rect, :showfocus=>true,
- :fill=>[
- @SystemHighlight, ['selected', 'focus'],
- 'gray', ['selected', '!focus']
- ])
-
- # image + text
- s = t.style_create('styName', :orient=>:horizontal)
- t.style_elements(s, ['e4', 'e1', 'e2'])
- t.style_layout(s, 'e1', :expand=>:ns)
- t.style_layout(s, 'e2', :padx=>[2,0], :squeeze=>:x, :expand=>:ns)
- t.style_layout(s, 'e4', :union=>['e2'], :iexpand=>:ns, :ipadx=>2)
-
- # column 1: text
- s = t.style_create('stySize')
- t.style_elements(s, ['txtSize'])
- t.style_layout(s, 'txtSize', :padx=>6, :squeeze=>:x, :expand=>:ns)
-
- # column 2: text
- s = t.style_create('styType')
- t.style_elements(s, ['txtType'])
- t.style_layout(s, 'txtType', :padx=>6, :squeeze=>:x, :expand=>:ns)
-
- # column 3: text
- s = t.style_create('styDate')
- t.style_elements(s, ['txtDate'])
- t.style_layout(s, 'txtDate', :padx=>6, :squeeze=>:x, :expand=>:ns)
-
- @Priv[:edit, t] = ['e2']
- @Priv[:sensitive, t] = [ ['name', 'styName', 'e1', 'e2'] ]
- @Priv[:dragimage, t] = [ ['name', 'styName', 'e1', 'e2'] ]
-
- t.notify_bind(t, 'Edit-accept',
- proc{|w, i, tt| w.item_text(i, 0, tt)}, '%T %I %t')
-
- dir_proc = proc{|file|
- item = t.item_create
- t.item_style_set(item, 0, 'styName', 2, 'styType', 3, 'styDate')
- t.item_complex(item,
- [['e2', {:text=>File.basename(file)}]],
- [],
- [['txtType', {:text=>'Folder'}]],
- [['txtDate', {:data=>File.mtime(file).tv_sec}]])
- t.item_lastchild(:root, item)
- }
-
- file_proc = proc{|file|
- item = t.item_create
- t.item_style_set(item, 0, 'styName', 1, 'stySize',
- 2, 'styType', 3, 'styDate')
-
- ext = File.extname(file)
- case ext
- when '.dll'
- img = 'small-dll'
- when '.exe'
- img = 'small-exe'
- when '.txt'
- img = 'small-txt'
- else
- img = 'small-file'
- end
-
- type = ext.upcase
- type = type[1..-1] << ' ' unless type.empty?
- type << 'File'
-
- t.item_complex(item,
- [
- ['e1', {:image=>[@sel_images[img], ['selected'],
- @images[img], []]}],
- ['e2', {:text=>File.basename(file)}]
- ],
- [ ['txtSize', {:data=>File.size(file)/1024 + 1}] ],
- [ ['txtType', {:text=>type}] ],
- [ ['txtDate', {:data=>File.mtime(file).tv_sec}] ]
- )
- t.item_lastchild(:root, item)
- }
-
- demoExplorerAux(t, dir_proc, file_proc)
-
- @SortColumn = 0
- t.notify_bind(t, 'Header-invoke',
- proc{|w, c| explorerHeaderInvoke(t, w, c)}, '%T %C')
-
- t.bindtags = [ t, 'TreeCtrlFileList', Tk::TreeCtrl, t.winfo_toplevel, :all ]
-end
-
-def explorerHeaderInvoke(t, w, c)
- if (c == @SortColumn)
- if t.column_cget(@SortColumn, :arrow) == 'down'
- order = :increasing
- arrow = :up
- else
- order = :decreasing
- arrow = :down
- end
- else
- if t.column_cget(@SortColumn, :arrow) == 'down'
- order = :decreasing
- arrow = :down
- else
- order = :increasing
- arrow = :up
- end
- t.column_configure(@SortColumn, :arrow=>:none)
- @SortColumn = c
- end
-
- t.column_configure(c, :arrow=>arrow)
- dirCount = TkComm.number(@Priv[:DirCnt, t])
- lastDir = dirCount - 1
- case t.column_cget(c, :tag)
- when 'name'
- if dirCount > 0
- t.item_sort(:root, order, {:last=>"root child #{lastDir}"},
- {:column=>c, :dictionary=>true})
- end
- if dirCount < t.numitems - 1
- t.item_sort(:root, order, {:first=>"root child #{dirCount}"},
- {:column=>c, :dictionary=>true})
- end
-
- when 'size'
- if dirCount < t.numitems - 1
- t.item_sort(:root, order, {:first=>"root child #{dirCount}"},
- {:column=>c, :integer=>true},
- {:column=>'name', :dictionary=>true})
- end
-
- when 'type'
- if dirCount < t.numitems - 1
- t.item_sort(:root, order, {:first=>"root child #{dirCount}"},
- {:column=>c, :dictionary=>true},
- {:column=>'name', :dictionary=>true})
- end
-
- when 'modified'
- if dirCount > 0
- t.item_sort(:root, order, {:last=>"root child #{lastDir}"},
- {:column=>c, :integer=>true},
- {:column=>'name', :dictionary=>true})
- end
- if dirCount < t.numitems - 1
- t.item_sort(:root, order, {:first=>"root child #{dirCount}"},
- {:column=>c, :integer=>true},
- {:column=>'name', :dictionary=>true})
- end
-
- end
-end
-
-def demoExplorerLargeIcons(t)
- # Item height is 32 for icon, 4 padding, 3 lines of text
- itemHeight = 32 + 4 + t.font.metrics(:linespace) * 3
-
- t.configure(:showroot=>false, :showbuttons=>false, :showlines=>false,
- :selectmode=>:extended, :wrap=>:window, :orient=>:horizontal,
- :itemheight=>itemHeight, :showheader=>false, :scrollmargin=>16,
- :xscrolldelay=>[500, 50], :yscrolldelay=>[500, 50])
-
- init_pics('big-*')
-
- if $HasColumnCreate
- t.column_create(:width=>75)
- else
- t.column_configure(0, :width=>75)
- end
-
- t.element_create('elemImg', :image,
- :image=>[
- @sel_images['big-folder'], ['selected'],
- @images['big-folder'], []
- ])
- t.element_create('elemTxt', :text, :justify=>:center,
- :lines=>1, :width=>71, :wrap=>:word,
- :fill=>[@SystemHighlightText, ['selected', 'focus']])
- t.element_create('elemSel', :rect, :showfocus=>true,
- :fill=>[
- @SystemHighlight, ['selected', 'focus'],
- 'gray', ['selected']
- ])
-
- # image + text
- s = t.style_create('STYLE', :orient=>:vertical)
- t.style_elements(s, ['elemSel', 'elemImg', 'elemTxt'])
- t.style_layout(s, 'elemImg', :expand=>:we)
- t.style_layout(s, 'elemTxt',
- :pady=>[4,0], :padx=>2, :squeeze=>:x, :expand=>:we)
- t.style_layout(s, 'elemSel', :union=>['elemTxt'])
-
- @Priv[:edit, t] = ['elemTxt']
- @Priv[:sensitive, t] = [ [0, 'STYLE', 'elemImg', 'elemTxt'] ]
- @Priv[:dragimage, t] = [ [0, 'STYLE', 'elemImg', 'elemTxt'] ]
-
- t.notify_bind(t, 'Edit-accept',
- proc{|w, i, tt| w.item_text(i, 0, tt)}, '%T %I %t')
-
- dir_proc = proc{|file|
- item = t.item_create
- t.item_style_set(item, 0, 'STYLE')
- t.item_text(item, 0, File.basename(file))
- t.item_lastchild(:root, item)
- }
-
- file_proc = proc{|file|
- item = t.item_create
- t.item_style_set(item, 0, 'STYLE')
-
- ext = File.extname(file)
- case ext
- when '.dll'
- img = 'big-dll'
- when '.exe'
- img = 'big-exe'
- when '.txt'
- img = 'big-txt'
- else
- img = 'big-file'
- end
-
- type = ext.upcase
- type = type[1..-1] << ' ' unless type.empty?
- type << 'File'
-
- t.item_complex(item,
- [
- ['elemImg', {:image=>[@sel_images[img], ['selected'],
- @images[img], []]}],
- ['elemTxt', {:text=>File.basename(file)}]
- ])
- t.item_lastchild(:root, item)
- }
-
- demoExplorerAux(t, dir_proc, file_proc)
-
- t.activate(t.index('root firstchild'))
-
- t.notify_bind(t, 'ActiveItem',
- proc{|w, a, c|
- w.item_element_configure(a, 0, 'elemTxt', :lines=>'')
- w.item_element_configure(c, 0, 'elemTxt', :lines=>3)
- }, '%T %p %c')
-
- t.bindtags = [ t, 'TreeCtrlFileList', Tk::TreeCtrl, t.winfo_toplevel, :all ]
-end
-
-# Tree is horizontal, wrapping occurs at right edge of window, each item
-# is as wide as the smallest needed multiple of 110 pixels
-def demoExplorerSmallIcons(t)
- demoExplorerList(t)
- t.configure(:orient=>:horizontal, :xscrollincrement=>0)
- t.column_configure(0, :width=>'', :stepwidth=>110, :widthhack=>false)
-end
-
-# Tree is vertical, wrapping occurs at bottom of window, each range has the
-# same width (as wide as the longest item), xscrollincrement is by range
-def demoExplorerList(t)
- height = t.font.metrics(:linespace) + 2
- height = 18 if height < 18
-
- t.configure(:showroot=>false, :showbuttons=>false, :showlines=>false,
- :itemheight=>height, :selectmode=>:extended, :wrap=>:window,
- :showheader=>false, :scrollmargin=>16,
- :xscrolldelay=>[500, 50], :yscrolldelay=>[500, 50])
-
- init_pics('small-*')
-
- if $HasColumnCreate
- t.column_create(:widthhack=>true)
- else
- t.column_configure(0, :widthhack=>true)
- end
-
- t.element_create('elemImg', :image,
- :image=>[
- @sel_images['small-folder'], ['selected'],
- @images['small-folder'], []
- ])
- t.element_create('elemTxt', :text, :lines=>1,
- :fill=>[@SystemHighlightText, ['selected', 'focus']])
- t.element_create('elemSel', :rect, :showfocus=>true,
- :fill=>[
- @SystemHighlight, ['selected', 'focus'],
- 'gray', ['selected', '!focus']
- ])
-
- # image + text
- s = t.style_create('STYLE')
- t.style_elements(s, ['elemSel', 'elemImg', 'elemTxt'])
- t.style_layout(s, 'elemImg', :expand=>:ns)
- t.style_layout(s, 'elemTxt', :squeeze=>:x, :expand=>:ns, :padx=>[2,0])
- t.style_layout(s, 'elemSel', :union=>['elemTxt'], :iexpand=>:ns, :ipadx=>2)
-
- @Priv[:edit, t] = ['elemTxt']
- @Priv[:sensitive, t] = [ [0, 'STYLE', 'elemImg', 'elemTxt'] ]
- @Priv[:dragimage, t] = [ [0, 'STYLE', 'elemImg', 'elemTxt'] ]
-
- t.notify_bind(t, 'Edit-accept',
- proc{|w, i, tt| w.item_text(i, 0, tt)}, '%T %I %t')
-
- dir_proc = proc{|file|
- item = t.item_create
- t.item_style_set(item, 0, 'STYLE')
- t.item_text(item, 0, File.basename(file))
- t.item_lastchild(:root, item)
- }
-
- file_proc = proc{|file|
- item = t.item_create
- t.item_style_set(item, 0, 'STYLE')
-
- ext = File.extname(file)
- case ext
- when '.dll'
- img = 'small-dll'
- when '.exe'
- img = 'small-exe'
- when '.txt'
- img = 'small-txt'
- else
- img = 'small-file'
- end
-
- type = ext.upcase
- type = type[1..-1] << ' ' unless type.empty?
- type << 'File'
-
- t.item_complex(item,
- [
- ['elemImg', {:image=>[@sel_images[img], ['selected'],
- @images[img], []]}],
- ['elemTxt', {:text=>File.basename(file)}]
- ])
- t.item_lastchild(:root, item)
- }
-
- demoExplorerAux(t, dir_proc, file_proc)
-
- t.activate(t.item_firstchild(:root))
-
- t.bindtags = [ t, 'TreeCtrlFileList', Tk::TreeCtrl, t.winfo_toplevel, :all ]
-end
diff --git a/ext/tk/sample/tkextlib/treectrl/help.rb b/ext/tk/sample/tkextlib/treectrl/help.rb
deleted file mode 100644
index af026fc006..0000000000
--- a/ext/tk/sample/tkextlib/treectrl/help.rb
+++ /dev/null
@@ -1,404 +0,0 @@
-#
-# Demo: Help contents
-#
-def demoHelpContents(t)
- height = t.font.metrics(:linespace)
- height = 18 if height < 18
- t.configure(:showroot=>false, :showbuttons=>false, :showlines=>false,
- :itemheight=>height, :selectmode=>:browse)
-
- init_pics('help-*')
-
- if $Version_1_1_OrLater
- t.column_create(:text=>'Help Contents')
- else # TreeCtrl 1.0
- t.column_configure(0, :text=>'Help Contents')
- end
-
- # Define a new item state
- t.state_define('mouseover')
-
- t.element_create('e1', :image, :image=>@images['help-page'])
- t.element_create('e2', :image, :image=>[
- @images['help-book-open'], ['open'],
- @images['help-book-closed'], [],
- ])
- t.element_create('e3', :text,
- :font=>[t.font.dup.underline(true), ['mouseover']],
- :fill=>[
- @SystemHighlightText, ['selected', 'focus'],
- 'blue', ['mouseover']
- ])
- t.element_create('e4', :rect, :showfocus=>true,
- :fill=>[@SystemHighlight, ['selected', 'focus']])
-
- # book
- s = t.style_create('s1')
- t.style_elements(s, ['e4', 'e1', 'e3'])
- t.style_layout(s, 'e1', :padx=>[0,4], :expand=>:ns)
- t.style_layout(s, 'e3', :expand=>:ns)
- t.style_layout(s, 'e4', :union=>['e3'], :iexpand=>:ns, :ipadx=>2)
-
- # page
- s = t.style_create('s2')
- t.style_elements(s, ['e4', 'e2', 'e3'])
- t.style_layout(s, 'e2', :padx=>[0,4], :expand=>:ns)
- t.style_layout(s, 'e3', :expand=>:ns)
- t.style_layout(s, 'e4', :union=>['e3'], :iexpand=>:ns, :ipadx=>2)
-
- parentList = [:root, '', '', '', '', '', '']
- parent = :root
- [
- [0, 's1', "Welcome to Help"],
- [0, 's2', "Introducing Windows 98"],
- [1, 's2', "How to Use Help"],
- [2, 's1', "Find a topic"],
- [2, 's1', "Get more out of help"],
- [1, 's2', "Register Your Software"],
- [2, 's1', "Registering Windows 98 online"],
- [1, 's2', "What's New in Windows 98"],
- [2, 's1', "Innovative, easy-to-use features"],
- [2, 's1', "Improved reliability"],
- [2, 's1', "A faster operating system"],
- [2, 's1', "True Web integration"],
- [2, 's1', "More entertaining and fun"],
- [1, 's2', "If You're New to Windows 98"],
- [2, 's2', "Tips for Macintosh Users"],
- [3, 's1', "Why does the mouse have two buttons?"]
- ].each{|depth, style, text|
- item = t.item_create
- t.item_style_set(item, 0, style)
- t.item_element_configure(item, 0, 'e3', :text=>text)
- if $Version_1_1_OrLater
- t.item_collapse(item)
- else # TreeCtrl 1.0
- t.collapse(item)
- end
- t.item_lastchild(parentList[depth], item)
- depth += 1
- parentList[depth] = item
- }
-
- treeCtrlHelp = TkBindTag.new
-
- treeCtrlHelp.bind('Double-ButtonPress-1',
- proc{|w, x, y|
- if w.identify(x, y)[0] == 'header'
- Tk::TreeCtrl::BindCallback.doubleButton1(w, x, y)
- else
- helpButton1(w, x, y)
- end
- Tk.callback_break
- }, '%W %x %y')
-
- treeCtrlHelp.bind('ButtonPress-1',
- proc{|w, x, y|
- helpButton1(w, x, y)
- Tk.callback_break
- }, '%W %x %y')
-
- treeCtrlHelp.bind('Button1-Motion',
- proc{|w, x, y|
- helpMotion1(w, x, y)
- Tk.callback_break
- }, '%W %x %y')
-
- treeCtrlHelp.bind('Button1-Leave',
- proc{|w, x, y|
- helpLeave1(w, x, y)
- Tk.callback_break
- }, '%W %x %y')
-
- treeCtrlHelp.bind('ButtonRelease-1',
- proc{|w, x, y|
- helpRelease1(w, x, y)
- Tk.callback_break
- }, '%W %x %y')
-
- treeCtrlHelp.bind('Motion', proc{|w, x, y| helpMotion(w, x, y) }, '%W %x %y')
-
- treeCtrlHelp.bind('Leave', proc{|w, x, y| helpMotion(w, x, y) }, '%W %x %y')
-
- treeCtrlHelp.bind('KeyPress-Return',
- proc{|w, x, y|
- if w.selection_get.length == 1
- if $Version_1_1_OrLater
- w.item_toggle(w.selection_get[0])
- else # TreeCtrl 1.0
- w.toggle(w.selection_get[0])
- end
- end
- Tk.callback_break
- }, '%W %x %y')
-
- @Priv[:help, :prev] = ''
-
- t.bindtags = [ t, treeCtrlHelp, Tk::TreeCtrl, t.winfo_toplevel, :all ]
-end
-
-# This is an alternate implementation that does not define a new item state
-# to change the appearance of the item under the cursor.
-def demoHelpContents2(t)
- height = t.font.metrics(:linespace)
- height = 18 if height < 18
- t.configure(:showroot=>false, :showbuttons=>false, :showlines=>false,
- :itemheight=>height, :selectmode=>:browse)
-
- init_pics('help-*')
-
- if $Version_1_1_OrLater
- t.column_create(:text=>'Help Contents')
- else # TreeCtrl 1.0
- t.column_configure(0, :text=>'Help Contents')
- end
-
- t.element_create('e1', :image, :image=>@images['help-page'])
- t.element_create('e2', :image, :image=>[
- @images['help-book-open'], ['open'],
- @images['help-book-closed'], [],
- ])
- t.element_create('e3', :text,
- :fill=>[
- @SystemHighlightText, ['selected', 'focus'],
- 'blue', []
- ])
- t.element_create('e4', :rect, :showfocus=>true,
- :fill=>[@SystemHighligh, ['selected', 'focus']])
- t.element_create('e5', :text, :font=>t.font.dup.underline(true),
- :fill=>[
- @SystemHighlightText, ['selected', 'focus'],
- 'blue', []
- ])
-
- # book
- s = t.style_create('s1')
- t.style_elements(s, ['e4', 'e1', 'e3'])
- t.style_layout(s, 'e1', :padx=>[0,4], :expand=>:ns)
- t.style_layout(s, 'e3', :expand=>:ns)
- t.style_layout(s, 'e4', :union=>['e3'], :iexpand=>:ns, :ipadx=>2)
-
- # page
- s = t.style_create('s2')
- t.style_elements(s, ['e4', 'e2', 'e3'])
- t.style_layout(s, 'e2', :padx=>[0,4], :expand=>:ns)
- t.style_layout(s, 'e3', :expand=>:ns)
- t.style_layout(s, 'e4', :union=>['e3'], :iexpand=>:ns, :ipadx=>2)
-
- # book (focus)
- s = t.style_create('s1.f')
- t.style_elements(s, ['e4', 'e1', 'e5'])
- t.style_layout(s, 'e1', :padx=>[0,4], :expand=>:ns)
- t.style_layout(s, 'e5', :expand=>:ns)
- t.style_layout(s, 'e4', :union=>['e5'], :iexpand=>:ns, :ipadx=>2)
-
- # page (focus)
- s = t.style_create('s2')
- t.style_elements(s, ['e4', 'e2', 'e5'])
- t.style_layout(s, 'e2', :padx=>[0,4], :expand=>:ns)
- t.style_layout(s, 'e5', :expand=>:ns)
- t.style_layout(s, 'e4', :union=>['e5'], :iexpand=>:ns, :ipadx=>2)
-
- parentList = [:root, '', '', '', '', '', '']
- parent = :root
- [
- [0, 's1', "Welcome to Help"],
- [0, 's2', "Introducing Windows 98"],
- [1, 's2', "How to Use Help"],
- [2, 's1' "Find a topic"],
- [2, 's1', "Get more out of help"],
- [1, 's2', "Register Your Software"],
- [2, 's1', "Registering Windows 98 online"],
- [1, 's2', "What's New in Windows 98"],
- [2, 's1', "Innovative, easy-to-use features"],
- [2, 's1', "Improved reliability"],
- [2, 's1', "A faster operating system"],
- [2, 's1', "True Web integration"],
- [2, 's1', "More entertaining and fun"],
- [1, 's2', "If You're New to Windows 98"],
- [2, 's2', "Tips for Macintosh Users"],
- [3, 's1', "Why does the mouse have two buttons?"]
- ].each{|depth, style, text|
- item = t.item_create
- t.item_style_set(item, 0, style)
- t.item_element_configure(item, 0, 'e3', :text=>text)
- if $Version_1_1_OrLater
- t.item_collapse(item)
- else # TreeCtrl 1.0
- t.collapse(item)
- end
- t.item_lastchild(parentList[depth], item)
- depth += 1
- parentList[depth] = item
- }
-
- treeCtrlHelp = TkBindTag.new
-
- treeCtrlHelp.bind('Double-ButtonPress-1',
- proc{|w, x, y|
- if w.identify(x, y)[0] == 'header'
- Tk::TreeCtrl::BindCallback.doubleButton1(w, x, y)
- else
- helpButton1(w, x, y)
- end
- Tk.callback_break
- }, '%W %x %y')
-
- treeCtrlHelp.bind('ButtonPress-1',
- proc{|w, x, y|
- helpButton1(w, x, y)
- Tk.callback_break
- }, '%W %x %y')
-
- treeCtrlHelp.bind('Button1-Motion',
- proc{|w, x, y|
- helpMotion1(w, x, y)
- Tk.callback_break
- }, '%W %x %y')
-
- treeCtrlHelp.bind('Button1-Leave',
- proc{|w, x, y|
- helpLeave1(w, x, y)
- Tk.callback_break
- }, '%W %x %y')
-
- treeCtrlHelp.bind('ButtonRelease-1',
- proc{|w, x, y|
- helpRelease1(w, x, y)
- Tk.callback_break
- }, '%W %x %y')
-
- treeCtrlHelp.bind('Motion', proc{|w, x, y| helpMotion(w, x, y) }, '%W %x %y')
-
- treeCtrlHelp.bind('Leave', proc{|w, x, y| helpMotion(w, x, y) }, '%W %x %y')
-
- treeCtrlHelp.bind('KeyPress-Return',
- proc{|w, x, y|
- if w.selection_get.length == 1
- w.item_toggle(w.selection_get[0])
- end
- Tk.callback_break
- }, '%W %x %y')
-
- @Priv[:help, :prev] = ''
-
- t.bindtags = [ t, treeCtrlHelp, Tk::TreeCtrl, t.winfo_toplevel, :all ]
-end
-
-def helpButton1(w, x, y)
- w.set_focus
- id = w.identify(x, y)
- @Priv['buttonMode'] = ''
- if id[0] == 'header'
- Tk::TreeCtrl::BindCallback.buttonPress1(w, x, y)
- elsif id[0] == 'item'
- item = id[1]
- # didn't click an element
- return if id.length != 6
- if w.selection_includes(item)
- w.toggle(item)
- return
- end
- if w.selection_get.length > 0
- item2 = w.selection_get[0]
- if $Version_1_1_OrLater
- w.item_collapse(item2)
- else # TreeCtrl 1.0
- w.collapse(item2)
- end
- w.item_ancestors(item2).each{|i|
- if $Version_1_1_OrLater
- w.item_collapse(i) if w.compare(item, '!=', i)
- else # TreeCtrl 1.0
- w.collapse(i) if w.compare(item, '!=', i)
- end
- }
- end
- w.activate(item)
- if $Version_1_1_OrLater
- w.item_ancestors(item).each{|i|
- w.item_expand(i)
- }
- w.item_toggle(item)
- else # TreeCtrl 1.0
- w.expand(*(w.item_ancestors(item)))
- w.toggle(item)
- end
- w.selection_modify(item, :all)
- end
-end
-
-def helpMotion1(w, x, y)
- case @Priv['buttonMode']
- when 'resize', 'header'
- Tk::TreeCtrl::BindCallback.motion1(w, x, y)
- end
-end
-
-def helpLeave1(w, x, y)
- # This is called when I do ButtonPress-1 on Unix for some reason,
- # and buttonMode is undefined.
- return unless @Priv.exist?('buttonMode')
- case @Priv['buttonMode']
- when 'header'
- w.column_configure(@Priv['column'], :sunken=>false)
- end
-end
-
-def helpRelease1(w, x, y)
- case @Priv['buttonMode']
- when 'resize', 'header'
- Tk::TreeCtrl::BindCallback.release1(w, x, y)
- end
- @Priv['buttonMode'] = ''
-end
-
-def helpMotion(w, x, y)
- id = w.identify(x, y)
- if id.empty?
- elsif id[0] == 'header'
- elsif id[0] == 'item'
- item = id[1]
- if id.length == 6
- if @Priv[:help, :prev] != TkComm._get_eval_string(item)
- if @Priv[:help, :prev] != ''
- w.item_state_set(@Priv[:help, :prev], '!mouseover')
- end
- w.item_state_set(item, 'mouseover')
- @Priv[:help, :prev] = item
- end
- return
- end
- end
- if @Priv[:help, :prev] != ''
- w.item_state_set(@Priv[:help, :prev], '!mouseover')
- @Priv[:help, :prev] = ''
- end
-end
-
-# Alternate implementation doesn't rely on mouseover state
-def helpMotion2(w, x, y)
- id = w.identify(x, y)
- if id[0] == 'header'
- elsif !id.empty?
- item = id[1]
- if id.kength == 6
- if @Priv[:help, :prev] != TkComm._get_eval_string(item)
- if @Priv[:help, :prev] != ''
- style = w.item_style_set(@Priv[:help, :prev], 0)
- style.sub!(/\.f$/, '')
- w.item_style_map(@Priv[:help, :prev], 0, style, ['e5', 'e3'])
- end
- style = w.item_style_set(item, 0)
- w.item_style_map(item, 0, style + '.f', ['e3', 'e5'])
- @Priv[:help, :prev] = item
- end
- return
- end
- end
- if @Priv[:help, :prev] != ''
- style = w.item_style_set(@Priv[:help, :prev], 0)
- style.sub!(/\.f$/, '')
- w.item_style_map(@Priv[:help, :prev], 0, style, ['e5', 'e3'])
- @Priv[:help, :prev] = ''
- end
-end
diff --git a/ext/tk/sample/tkextlib/treectrl/imovie.rb b/ext/tk/sample/tkextlib/treectrl/imovie.rb
deleted file mode 100644
index d61bf9a7c3..0000000000
--- a/ext/tk/sample/tkextlib/treectrl/imovie.rb
+++ /dev/null
@@ -1,130 +0,0 @@
-#
-# Demo: iMovie
-#
-def demoIMovie(t)
- t.configure(:showroot=>false, :showbuttons=>false, :showlines=>false,
- :selectmode=>:browse, :orient=>:horizontal, :wrap=>:window,
- :showheader=>false, :background=>'#dcdcdc')
-
- if $HasColumnCreate
- t.column_create
- end
-
- init_pics('imovie-*')
-
- case @thisPlatform
- when 'macintosh', 'macosx'
- font1 = TkFont.new(['Geneva', 9])
- font2 = TkFont.new(['Geneva', 10])
- when 'unix'
- font1 = TkFont.new(['Helvetica', -12])
- font2 = TkFont.new(['Helvetica', -14])
- else
- font1 = TkFont.new(['Helvetica', 8])
- font2 = TkFont.new(['Helvetica', 10])
- end
-
- t.element_create('elemTime', :text, :font=>font1)
- t.element_create('elemName', :text, :font=>font2, :lines=>1, :width=>80)
- t.element_create('elemRect', :rect, :outline=>'#827878', :outlinewidth=>1,
- :fill=>['#ffdc5a', ['selected'], 'white', []])
- t.element_create('elemImg', :image)
- t.element_create('elemShadow', :rect, :outline=>'gray', :outlinewidth=>1,
- :open=>:wn)
-
- s = t.style_create('STYLE', :orient=>:vertical)
- t.style_elements(s, [
- 'elemShadow', 'elemRect', 'elemTime',
- 'elemImg', 'elemName'
- ])
- t.style_layout(s, 'elemShadow', :detach=>true,
- :padx=>[1,2], :pady=>[1,2], :iexpand=>:es)
- t.style_layout(s, 'elemTime', :padx=>[2,0])
- t.style_layout(s, 'elemImg', :pady=>[0,1])
- t.style_layout(s, 'elemName', :expand=>:we, :ipady=>[0,2], :padx=>[0,3],
- :squeeze=>:x)
- t.style_layout(s, 'elemRect', :union=>['elemTime', 'elemImg', 'elemName'],
- :ipadx=>6, :padx=>[0,3], :pady=>[0,3])
-
- # Set default item style
- if $Version_1_1_OrLater
- t.defaultstyle([s])
- end
-
- (0..4).each{|i|
- [
- ['15:20', 'Clip 1', @images['imovie-01']],
- ['19:18', 'Clip 2', @images['imovie-02']],
- ['07:20', 'Clip 3', @images['imovie-03']],
- ['07:20', 'Clip 4', @images['imovie-04']],
- ['07:20', 'Clip 5', @images['imovie-05']],
- ['07:20', 'Clip 6', @images['imovie-06']],
- ['07:20', 'Clip 7', @images['imovie-07']]
- ].each{|time, name, image|
- item = t.item_create
- unless $Version_1_1_OrLater
- t.item_style_set(item, 0, s)
- end
- t.item_element_configure(item, 0, 'elemTime', :text=>time)
- t.item_element_configure(item, 0, 'elemName', :text=>name)
- t.item_element_configure(item, 0, 'elemImg', :image=>image)
- t.item_lastchild(:root, item)
- }
- }
-
- t.notify_bind(t, 'Edit-accept', proc{|w, i, c, e, tt|
- w.item_element_configure(i, c, e, :text=>tt)
- }, '%T %I %C %E %t')
-
- iMovie = TkBindTag.new
- iMovie.bind('ButtonPress-1', proc{|w, x, y|
- iMovieButton1(w, x, y)
- }, '%W %x %y')
-
- t.bindtags = [t, iMovie, Tk::TreeCtrl, t.winfo_toplevel, TkBindTag::ALL]
-end
-
-def iMovieButton1(w, x, y)
- w.set_focus
- id = w.identify(x,y)
-
- if id.empty?
- # Click outside any item
-
- elsif id[0] == 'header'
- # Click in header
- Tk::TreeCtrl::BindCallback.buttonPress1(w, x, y)
-
- elsif id[0] == 'item'
- # Click in item
- Tk::TreeCtrl::BindCallback.buttonPress1(w, x, y)
- Tk.update
- where, item, arg1, arg2, arg3, arg4 = id
- case arg1
- when 'column'
- i = id[1]
- if id.length == 6
- e = id[-1]
- if e == 'elemName'
- exists = TkWinfo.exist?(w.path + '.entry')
- Tk::TreeCtrl::BindCallback.entryOpen(w, i, 0, e)
- ent = TkComm.window(w.path + '.entry')
- unless exists
- ent.configure(:borderwidth=>0, :justify=>:center,
- :background=>'#ffdc5a')
- x1, y1, x2, y2 = w.item_bbox(i, 0, e)
- ent.place(:y=>y1 - 1)
- end
- ent.selection_clear
- x1, y1, x2, y2 = w.item_bbox(i)
- ent.place(:x=>x1 + 1, :width=>x2 - x1 - 5)
- puts "@#{x - (x1 + 1)}"
- # ent.icursor = ent.index("@#{x - (x1 + 1)}")
- ent.icursor = ent.index(TkComm._at(x - (x1 + 1)))
- end
- end
- end
- end
-
- Tk.callback_break
-end
diff --git a/ext/tk/sample/tkextlib/treectrl/layout.rb b/ext/tk/sample/tkextlib/treectrl/layout.rb
deleted file mode 100644
index 745ac86f36..0000000000
--- a/ext/tk/sample/tkextlib/treectrl/layout.rb
+++ /dev/null
@@ -1,159 +0,0 @@
-#
-# Demo: Layout
-#
-def demoLayout(t)
- t.configure(:showroot=>false, :showrootbutton=>true, :showbuttons=>true,
- :showlines=>true, :itemheight=>0, :selectmode=>:browse)
-
- if $HasColumnCreate
- t.column_create(:text=>'Layout')
- else
- t.column_configure(0, :text=>'Layout')
- end
-
- t.element_create('e1', :rect, :width=>30, :height=>30, :fill=>'gray20')
- t.element_create('e2', :rect, :width=>30, :height=>30, :fill=>'gray40',
- :outline=>'blue', :outlinewidth=>3)
- t.element_create('e3', :rect, :fill=>'gray60')
- t.element_create('e4', :rect, :showfocus=>true,
- :fill=>[
- @SystemHighlight, ['selected', 'focus'], 'gray80', []
- ])
- t.element_create('e5', :rect, :fill=>'{sky blue}', :width=>20, :height=>20)
- t.element_create('e6', :rect, :fill=>'{sea green}', :width=>30, :height=>16)
- t.element_create('e7', :rect, :fill=>'{sky blue}', :width=>30, :height=>16)
- t.element_create('e8', :rect, :fill=>'gray70', :height=>1)
-
- s = t.style_create('s1')
- t.style_elements(s, ['e4', 'e3', 'e1', 'e2', 'e5', 'e6', 'e7'])
- t.style_layout(s, 'e1', :padx=>[28, 4], :pady=>4)
- t.style_layout(s, 'e2', :expand=>:es, :padx=>[0, 38])
- t.style_layout(s, 'e3', :union=>['e1', 'e2'], :ipadx=>4, :ipady=>4, :pady=>2)
- t.style_layout(s, 'e4', :detach=>true, :iexpand=>:es)
- t.style_layout(s, 'e5', :detach=>true, :padx=>[2,0], :pady=>2, :iexpand=>:s)
- t.style_layout(s, 'e6', :detach=>true, :expand=>:ws,
- :padx=>[0,2], :pady=>[2,0])
- t.style_layout(s, 'e7', :detach=>true, :expand=>:wn,
- :padx=>[0,2], :pady=>[0,2])
-
- if $Version_1_1_OrLater
- i = t.item_create(:button=>true)
- else
- i = t.item_create
- t.item_hasbutton(i, true)
- end
- t.item_style_set(i, 0, s)
- t.item_lastchild(:root, i)
- parent = i
-
- i = t.item_create()
- unless $Version_1_1_OrLater
- t.item_hasbutton(i, false)
- end
- t.item_style_set(i, 0, s)
- t.item_lastchild(parent, i)
-
- ###
-
- s = t.style_create('s2')
- t.style_elements(s, ['e4', 'e3', 'e1'])
- t.style_layout(s, 'e1', :padx=>8, :pady=>8, :iexpand=>:e)
- t.style_layout(s, 'e3', :union=>['e1'], :ipadx=>[20,4], :ipady=>[4,12])
- t.style_layout(s, 'e4', :detach=>true, :iexpand=>:es)
-
- if $Version_1_1_OrLater
- i = t.item_create(:button=>true)
- else
- i = t.item_create
- t.item_hasbutton(i, true)
- end
- t.item_style_set(i, 0, s)
- t.item_lastchild(:root, i)
-
- i2 = t.item_create()
- unless $Version_1_1_OrLater
- t.item_hasbutton(i2, false)
- end
- t.item_style_set(i2, 0, s)
- t.item_lastchild(i, i2)
-
- ###
-
- s = t.style_create('s3')
- t.style_elements(s, ['e4', 'e3', 'e1', 'e5', 'e6'])
- t.style_layout(s, 'e4', :union=>['e1', 'e6'], :ipadx=>8, :ipady=>[8,0])
- t.style_layout(s, 'e3', :union=>['e1', 'e5'], :ipadx=>4, :ipady=>4)
- t.style_layout(s, 'e5', :ipady=>[0,20])
-
- if $Version_1_1_OrLater
- i = t.item_create(:button=>true)
- else
- i = t.item_create
- t.item_hasbutton(i, true)
- end
- t.item_style_set(i, 0, s)
- t.item_lastchild(:root, i)
-
- i2 = t.item_create()
- unless $Version_1_1_OrLater
- t.item_hasbutton(i2, false)
- end
- t.item_style_set(i2, 0, s)
- t.item_lastchild(i, i2)
-
- ###
-
- t.element_create('eb', :border, :background=>@SystemButtonFace,
- :relief=>[:sunken, ['selected'], :raised, []],
- :thickness=>2, :filled=>true)
- t.element_create('et', :text)
-
- text = "Here is a text element surrounded by a border element.\nResize the column to watch me wrap."
-
- s = t.style_create('e4')
- t.style_elements(s, ['eb', 'et'])
- t.style_layout(s, 'eb', :union=>['et'], :ipadx=>2, :ipady=>2)
- t.style_layout(s, 'et', :squeeze=>:x)
-
- if $Version_1_1_OrLater
- i = t.item_create(:button=>true)
- else
- i = t.item_create
- t.item_hasbutton(i, true)
- end
- t.item_style_set(i, 0, s)
- t.item_text(i, 0, text)
- t.item_lastchild(:root, i)
- parent = i
-
- i = t.item_create()
- unless $Version_1_1_OrLater
- t.item_hasbutton(i, false)
- end
- t.item_style_set(i, 0, s)
- t.item_text(i, 0, text)
- t.item_lastchild(parent, i)
-
- ###
-
- styleNum = 5
- [
- [:horizontal, [:s, :ns, :n]],
- [:vertical, [:e, :we, :w]]
- ].each{|orient, expandList|
- expandList.each{|expand|
- s = t.style_create("s#{styleNum}", :orient=>orient)
- t.style_elements(s, ['e4', 'e8', 'e2', 'e5', 'e6'])
- t.style_layout(s, 'e4', :detach=>true, :iexpand=>:es)
- t.style_layout(s, 'e8', :detach=>true, :expand=>:n, :iexpand=>:e)
- t.style_layout(s, 'e2', :expand=>expand)
- t.style_layout(s, 'e5', :expand=>expand)
- t.style_layout(s, 'e6', :expand=>expand)
- styleNum += 1
-
- i = t.item_create()
- t.item_style_set(i, 0, s)
- t.item_lastchild(:root, i)
- }
- }
-end
diff --git a/ext/tk/sample/tkextlib/treectrl/mailwasher.rb b/ext/tk/sample/tkextlib/treectrl/mailwasher.rb
deleted file mode 100644
index 836e1e87de..0000000000
--- a/ext/tk/sample/tkextlib/treectrl/mailwasher.rb
+++ /dev/null
@@ -1,269 +0,0 @@
-#
-# Demo: MailWasher
-#
-def demoMailWasher(t)
- init_pics('*checked')
-
- height = t.font.metrics(:linespace) + 2
- height = 18 if height < 18
-
- t.configure(:showroot=>false, :showrootbutton=>false, :showbuttons=>false,
- :showlines=>false, :itemheight=>height, :selectmode=>:browse,
- :xscrollincrement=>1)
-
- pad = 4
-
- if $Version_1_1_OrLater
- t.column_create(:text=>'Delete', :textpadx=>pad, :tag=>'delete')
- t.column_create(:text=>'Bounce', :textpadx=>pad, :tag=>'bounce')
- t.column_create(:text=>'Status', :width=>80, :textpadx=>pad,
- :tag=>'status')
- t.column_create(:text=>'Size', :width=>40, :textpadx=>pad,
- :justify=>:right, :tag=>'size')
- t.column_create(:text=>'From', :width=>140, :textpadx=>pad, :tag=>'from')
- t.column_create(:text=>'Subject', :width=>240, :textpadx=>pad,
- :tag=>'subject')
- t.column_create(:text=>'Received', :textpadx=>pad, :arrow=>:up,
- :arrowpad=>[4,0], :tag=>'received')
- t.column_create(:text=>'Attachments', :textpadx=>pad, :tag=>'attachments')
-
- t.state_define('CHECK')
-
- t.element_create('imgCheck', :image, :image=>[
- @images['checked'], ['CHECK'], @images['unchecked'], []
- ])
-
- else # TreeCtrl 1.0
- t.column_configure(0, :text=>'Delete', :textpadx=>pad, :tag=>'delete')
- t.column_configure(1, :text=>'Bounce', :textpadx=>pad, :tag=>'bounce')
- t.column_configure(2, :text=>'Status', :width=>80, :textpadx=>pad,
- :tag=>'status')
- t.column_configure(3, :text=>'Size', :width=>40, :textpadx=>pad,
- :justify=>:right, :tag=>'size')
- t.column_configure(4, :text=>'From', :width=>140, :textpadx=>pad,
- :tag=>'from')
- t.column_configure(5, :text=>'Subject', :width=>240, :textpadx=>pad,
- :tag=>'subject')
- t.column_configure(6, :text=>'Received', :textpadx=>pad, :arrow=>:up,
- :arrowpad=>[4,0], :tag=>'received')
- t.column_configure(7, :text=>'Attachments', :textpadx=>pad,
- :tag=>'attachments')
-
- t.element_create('imgOff', :image, :image=>@images['unchecked'])
- t.element_create('imgOn', :image, :image=>@images['checked'])
- end
-
- t.element_create('border', :rect, :open=>:nw, :outline=>'gray',
- :outlinewidth=>1, :fill=>[@SystemHighlight, ['selected']])
- t.element_create('txtAny', :text, :lines=>1,
- :fill=>[@SystemHighlightText, ['selected']])
- t.element_create('txtNone', :text, :text=>'none', :lines=>1,
- :fill=>[@SystemHighlightText, ['selected']])
- t.element_create('txtYes', :text, :text=>'yes', :lines=>1,
- :fill=>[@SystemHighlightText, ['selected']])
- t.element_create('txtNormal', :text, :text=>'Normal', :lines=>1,
- :fill=>[@SystemHighlightText, ['selected'], '#006800', []])
- t.element_create('txtPossSpam', :text, :text=>'Possible Spam', :lines=>1,
- :fill=>[@SystemHighlightText, ['selected'], '#787800', []])
- t.element_create('txtProbSpam', :text, :text=>'Probably Spam', :lines=>1,
- :fill=>[@SystemHighlightText, ['selected'], '#FF9000', []])
- t.element_create('txtBlacklist', :text, :text=>'Blacklisted', :lines=>1,
- :fill=>[@SystemHighlightText, ['selected'], '#FF5800', []])
-
- if $Version_1_1_OrLater
- s = t.style_create('styCheck')
- t.style_elements(s, ['border', 'imgCheck'])
- t.style_layout(s, 'border', :detach=>true, :iexpand=>:es)
- t.style_layout(s, 'imgCheck', :expand=>:news)
- else
- ['Off', 'On'].each{|name|
- s = t.style_create('sty' << name)
- i = 'img' << name
- t.style_elements(s, ['border', i])
- t.style_layout(s, 'border', :detach=>true, :iexpand=>:es)
- t.style_layout(s, i, :expand=>:news)
- }
- end
-
- pad = 4
-
- %w(Any None Yes Normal PossSpam ProbSpam Blacklist).each{|name|
- s = t.style_create('sty' << name)
- e = 'txt' << name
- t.style_elements(s, ['border', e])
- t.style_layout(s, 'border', :detach=>true, :iexpand=>:es)
- t.style_layout(s, e, :padx=>pad, :squeeze=>:x, :expand=>:ns)
- }
-
- [
- ['baldy@spammer.com', "Your hair is thinning"],
- ['flat@spammer.com', "Your breasts are too small"],
- ['tiny@spammer.com', "Your penis is too small"],
- ['dumbass@spammer.com', "You are not very smart"],
- ['bankrobber@spammer.com', "You need more money"],
- ['loser@spammer.com', "You need better friends"],
- ['gossip@spammer.com', "Find out what your coworkers think about you"],
- ['whoami@spammer.com', "Find out what you think about yourself"],
- ['downsized@spammer.com', "You need a better job"],
- ['poorhouse@spammer.com', "Your mortgage is a joke"],
- ['spam4ever@spammer.com', "You need more spam"]
- ].each{|frm, subj|
- item = t.item_create
- status = ['styNormal','styPossSpam','styProbSpam','styBlacklist'][rand(4)]
- attachments = ['styNone','styYes'][rand(2)]
-
- if $Version_1_1_OrLater
- delete = [false, true][rand(2)]
- bounce = [false, true][rand(2)]
- t.item_style_set(item,
- 0, 'styCheck', 1, 'styCheck', 2, status, 3, 'styAny',
- 4, 'styAny', 5, 'styAny', 6, 'styAny', 7, attachments)
- t.item_state_forcolumn(item, 'delete', 'CHECK') if delete
- t.item_state_forcolumn(item, 'bounce', 'CHECK') if bounce
-
- else # TreeCtrl 1.0
- delete = ['styOn', 'styOff'][rand(2)]
- bounce = ['styOn', 'styOff'][rand(2)]
- t.item_style_set(item,
- 0, delete, 1, bounce, 2, status, 3, 'styAny',
- 4, 'styAny', 5, 'styAny', 6, 'styAny', 7, attachments)
- end
-
- bytes = 512 + rand(1024 * 12)
- size = "#{bytes / 1024 + 1}KB"
- seconds = Tk::Clock.seconds - rand(100000)
- received = Tk::Clock.format(seconds, '%d/%m/%y %I:%M %p')
- t.item_text(item, 3, size, 4, frm, 5, subj, 6, received)
- t.item_lastchild(:root, item)
- }
-
- sortColumn = 6
- t.notify_bind(t, 'Header-invoke',
- proc{|c, w|
- if c == sortColumn
- if w.column_cget(sortColumn, :arrow) == 'down'
- order = :increasing
- arrow = :up
- else
- order = :decreasing
- arrow = :down
- end
- else
- if w.column_cget(sortColumn, :arrow) == 'down'
- order = :decreasing
- arrow = :down
- else
- order = :increasing
- arrow = :up
- end
- w.column_configure(sortColumn, :arrow=>:none)
- sortColumn = c
- end
- w.column_configure(c, :arrow=>arrow)
- case w.column_cget(c, :tag)
- when 'bounce', 'delete'
- w.item_sort(:root, order,
- {
- :column=>c,
- :command=>proc{|item1, item2|
- compareOnOff(w, c, item1, item2)
- }
- },
- { :column=>'subject', :dictionary=>true })
- when 'status'
- w.item_sort(:root, order,
- { :column=>c, :dictionary=>true })
- when 'from'
- w.item_sort(:root, order,
- { :column=>c, :dictionary=>true },
- { :column=>'subject', :dictionary=>true })
- when 'subject'
- w.item_sort(:root, order,
- { :column=>c, :dictionary=>true })
- when 'size'
- w.item_sort(:root, order,
- { :column=>c, :dictionary=>true },
- { :column=>'subject', :dictionary=>true })
- when 'received'
- w.item_sort(:root, order,
- { :column=>c, :dictionary=>true },
- { :column=>'subject', :dictionary=>true })
- when 'attachments'
- w.item_sort(:root, order,
- { :column=>c, :dictionary=>true },
- { :column=>'subject', :dictionary=>true })
- end
- }, '%C %T')
-
- mailWasher = TkBindTag.new
-
- if $Version_1_1_OrLater
- mailWasher.bind('ButtonPress-1',
- proc{|w, x, y|
- id = w.identify(x, y)
- if id.empty?
- elsif id[0] == 'header'
- else
- what, item, where, arg1, arg2, arg3 = id
- if where == 'column'
- tag = w.column_cget(arg1, :tag)
- if tag == 'delete' || tag == 'bounce'
- w.item_state_forcolumn(item, arg1, '~CHECK')
- end
- end
- end
- }, '%W %x %y')
- else # TreeCtrl 1.0
- mailWasher.bind('ButtonPress-1',
- proc{|w, x, y|
- id = w.identify(x, y)
- if id.empty?
- elsif id[0] == 'header'
- else
- what, item, where, arg1, arg2, arg3 = id
- if where == 'column'
- tag = w.column_cget(arg1, :tag)
- if tag == 'delete' || tag == 'bounce'
- style = w.item_style_set(item, arg1)
- if style == 'styOn'
- style = 'styOff'
- else
- style = 'styOn'
- end
- w.item_style_set(item, arg1, style)
- @display_styles_in_item.call(item)
- end
- end
- end
- }, '%W %x %y')
- end
-
- t.bindtags = [t, mailWasher, Tk::TreeCtrl, t.winfo_toplevel, TkBindTag::ALL]
-end
-
-if $Version_1_1_OrLater
- def compareOnOff(w, c, item1, item2)
- s1 = w.item_state_forcolumn(item1, c)
- s2 = w.item_state_forcolumn(item2, c)
- if (s1 == s2)
- 0
- elsif (s1 == 'CHECK')
- -1
- else
- 1
- end
- end
-
-else # TreeCtrl 1.0
- def compareOnOff(w, c, item1, item2)
- s1 = w.item_style_set(item1, c)
- s2 = w.item_style_set(item2, c)
- if (s1 == s2)
- 0
- elsif (s1 == 'styOff')
- -1
- else
- 1
- end
- end
-end
diff --git a/ext/tk/sample/tkextlib/treectrl/outlook-folders.rb b/ext/tk/sample/tkextlib/treectrl/outlook-folders.rb
deleted file mode 100644
index c3af86868e..0000000000
--- a/ext/tk/sample/tkextlib/treectrl/outlook-folders.rb
+++ /dev/null
@@ -1,124 +0,0 @@
-#
-# Demo: Outlook Express folder list
-#
-def demoOutlookFolders(t)
- init_pics('outlook-*')
-
- height = t.font.metrics(:linespace) + 2
- height = 18 if height < 18
-
- t.configure(:itemheight=>height, :selectmode=>:browse, :showlines=>true,
- :showroot=>true, :showrootbutton=>false, :showbuttons=>true)
-
- if $HasColumnCreate
- t.column_create(:text=>'Folders')
- else
- t.column_configure(0, :text=>'Folders')
- end
-
- t.element_create('e1', :image)
- t.element_create('e2', :text, :lines=>1,
- :fill=>[@SystemHighlightText, ['selected', 'focus']])
- t.element_create('e3', :text, :lines=>1, :font=>t.font.dup.weight(:bold),
- :fill=>[@SystemHighlightText, ['selected', 'focus']])
- t.element_create('e4', :text, :fill=>'blue')
- t.element_create('e5', :image, :image=>@images['outlook-folder'])
- t.element_create('e6', :rect, :showfocus=>true,
- :fill=>[
- @SystemHighlight, ['selected', 'focus'],
- 'gray', ['selected', '!focus']
- ])
-
- # image + text
- s = t.style_create('s1')
- t.style_elements(s, ['e6', 'e1', 'e2'])
- t.style_layout(s, 'e1', :expand=>:ns)
- t.style_layout(s, 'e2', :padx=>[4,0], :expand=>:ns, :squeeze=>:x)
- t.style_layout(s, 'e6', :union=>['e2'], :iexpand=>:ns, :ipadx=>2)
-
- # image + text + text
- s = t.style_create('s2')
- t.style_elements(s, ['e6', 'e1', 'e3', 'e4'])
- t.style_layout(s, 'e1', :expand=>:ns)
- t.style_layout(s, 'e3', :padx=>4, :expand=>:ns, :squeeze=>:x)
- t.style_layout(s, 'e4', :expand=>:ns)
- t.style_layout(s, 'e6', :union=>['e3'], :iexpand=>:ns, :ipadx=>2)
-
- # folder + text
- s = t.style_create('s3')
- t.style_elements(s, ['e6', 'e5', 'e2'])
- t.style_layout(s, 'e5', :expand=>:ns)
- t.style_layout(s, 'e2', :padx=>[4,0], :expand=>:ns, :squeeze=>:x)
- t.style_layout(s, 'e6', :union=>['e2'], :iexpand=>:ns, :ipadx=>2)
-
- # folder + text + text
- s = t.style_create('s4')
- t.style_elements(s, ['e6', 'e5', 'e3', 'e4'])
- t.style_layout(s, 'e5', :expand=>:ns)
- t.style_layout(s, 'e3', :padx=>4, :expand=>:ns, :squeeze=>:x)
- t.style_layout(s, 'e4', :expand=>:ns)
- t.style_layout(s, 'e6', :union=>['e3'], :iexpand=>:ns, :ipadx=>2)
-
- t.item_style_set(:root, 0, 's1')
- t.item_complex(:root,
- [
- ['e1', {:image=>@images['outlook-main']}],
- ['e2', {:text=>'Outlook Express'}]
- ])
-
- parentList = [:root, '', '', '', '', '', '']
- parent = :root
- [
- [0, :local, "Local Folders", true, 0],
- [1, :inbox, 'Inbox', false, 5],
- [1, :outbox, 'Outbox', false, 0],
- [1, :sent, "Sent Items", false, 0],
- [1, :deleted, "Deleted Items", false, 50],
- [1, :draft, 'Drafts', false, 0],
- [1, :folder, "Messages to Dad", false, 0],
- [1, :folder, "Messages to Sis", false, 0],
- [1, :folder, "Messages to Me", false, 0],
- [2, :folder, "2001", false, 0],
- [2, :folder, "2000", false, 0],
- [2, :folder, "1999", false, 0],
- [0, :server, "news.gmane.org", true, 0],
- [1, :group, "gmane.comp.lang.lua.general", false, 498]
- ].each{|depth, img, text, button, unread|
- if $Version_1_1_OrLater
- item = t.item_create(:button=>button)
- else
- item = t.item_create
- t.item_hasbutton(item, button)
- end
- if img == :folder
- if unread != 0
- t.item_style_set(item, 0, 's4')
- t.item_complex(item,
- [['e3', {:text=>text}], ['e4', {:text=>"(#{unread})"}]])
- else
- t.item_style_set(item, 0, 's3')
- t.item_complex(item, [['e2', {:text=>text}]])
- end
- else
- if unread != 0
- t.item_style_set(item, 0, 's2')
- t.item_complex(item,
- [
- ['e1', {:image=>@images["outlook-#{img}"]}],
- ['e3', {:text=>text}],
- ['e4', {:text=>"(#{unread})"}]
- ])
- else
- t.item_style_set(item, 0, 's1')
- t.item_complex(item,
- [
- ['e1', {:image=>@images["outlook-#{img}"]}],
- ['e2', {:text=>text}]
- ])
- end
- end
- t.item_lastchild(parentList[depth], item)
- depth += 1
- parentList[depth] = item
- }
-end
diff --git a/ext/tk/sample/tkextlib/treectrl/outlook-newgroup.rb b/ext/tk/sample/tkextlib/treectrl/outlook-newgroup.rb
deleted file mode 100644
index d7e7f7e004..0000000000
--- a/ext/tk/sample/tkextlib/treectrl/outlook-newgroup.rb
+++ /dev/null
@@ -1,448 +0,0 @@
-#
-# Demo: Outlook Express newsgroup messages
-#
-def demoOutlookNewsgroup(t)
- init_pics('outlook-*')
-
- height = t.font.metrics(:linespace)
- height = 18 if height < 18
- t.configure(:itemheight=>height, :selectmode=>:browse, :showlines=>false,
- :showroot=>false, :showrootbutton=>false, :showbuttons=>true)
-
- if $Version_1_1_OrLater
- t.column_create(:image=>@images['outlook-clip'], :tag=>'clip')
- t.column_create(:image=>@images['outlook-arrow'], :tag=>'arrow')
- t.column_create(:image=>@images['outlook-watch'], :tag=>'watch')
- t.column_create(:text=>'Subject', :width=>250, :tag=>'subject')
- t.column_create(:text=>'From', :width=>150, :tag=>'from')
- t.column_create(:text=>'Sent', :width=>150, :tag=>'sent')
- t.column_create(:text=>'Size', :width=>60, :justify=>:right, :tag=>'size')
- else # TreeCtrl 1.0
- t.column_configure(0, :image=>@images['outlook-clip'], :tag=>'clip')
- t.column_configure(1, :image=>@images['outlook-arrow'], :tag=>'arrow')
- t.column_configure(2, :image=>@images['outlook-watch'], :tag=>'watch')
- t.column_configure(3, :text=>'Subject', :width=>250, :tag=>'subject')
- t.column_configure(4, :text=>'From', :width=>150, :tag=>'from')
- t.column_configure(5, :text=>'Sent', :width=>150, :tag=>'sent')
- t.column_configure(6, :text=>'Size', :width=>60, :justify=>:right,
- :tag=>'size')
- end
-
- # Would be nice if I could specify a column -tag too
- t.treecolumn = 3
-
- # State for a read message
- t.state_define('read')
-
- # State for a message with unread descendants
- t.state_define('unread')
-
- t.element_create('elemImg', :image,
- :image=>[
- @sel_images['outlook-read-2'],
- ['selected', 'read', 'unread', '!open'],
- @images['outlook-read-2'], ['read', 'unread', '!open'],
- @sel_images['outlook-read'], ['selected', 'read'],
- @images['outlook-read'], ['read'],
- @sel_images['outlook-unread'], ['selected'],
- @images['outlook-unread'], []
- ])
- t.element_create('elemTxt', :text, :lines=>1,
- :fill=>[@SystemHighlightText, ['selected', 'focus']],
- :font=>[
- t.font.dup.weight(:bold), ['read', 'unread', '!open'],
- t.font.dup.weight(:bold), ['!read']
- ])
- t.element_create('sel.e', :rect, :open=>:e, :showfocus=>true,
- :fill=>[
- @SystemHighlight, ['selected', 'focus'],
- 'gray', ['selected', '!focus']
- ])
- t.element_create('sel.w', :rect, :open=>:w, :showfocus=>true,
- :fill=>[
- @SystemHighlight, ['selected', 'focus'],
- 'gray', ['selected', '!focus']
- ])
- t.element_create('sel.we', :rect, :open=>:we, :showfocus=>true,
- :fill=>[
- @SystemHighlight, ['selected', 'focus'],
- 'gray', ['selected', '!focus']
- ])
-
- # Image + text
- s = t.style_create('s1')
- t.style_elements(s, ['sel.e', 'elemImg', 'elemTxt'])
- t.style_layout(s, 'elemImg', :expand=>:ns)
- t.style_layout(s, 'elemTxt', :padx=>[2,6], :squeeze=>:x, :expand=>:ns)
- t.style_layout(s, 'sel.e', :union=>['elemTxt'],
- :iexpand=>:nes, :ipadx=>[2,0])
-
- # Text
- s = t.style_create('s2.we')
- t.style_elements(s, ['sel.we', 'elemTxt'])
- t.style_layout(s, 'elemTxt', :padx=>6, :squeeze=>:x, :expand=>:ns)
- t.style_layout(s, 'sel.we', :detach=>true, :iexpand=>:es)
-
- # Text
- s = t.style_create('s2.w')
- t.style_elements(s, ['sel.w', 'elemTxt'])
- t.style_layout(s, 'elemTxt', :padx=>6, :squeeze=>:x, :expand=>:ns)
- t.style_layout(s, 'sel.w', :detach=>true, :iexpand=>:es)
-
- # Set default item style
- if $Version_1_1_OrLater
- t.defaultstyle = ['', '', '', 's1', 's2.we', 's2.we', 's2.w']
- end
-
- msgCnt = 100
- thread = 0
-
- @Message = Hash.new{|k, v| k[v] = Hash.new}
- @Message[:count][0] = 0
-
- items = [t.index(:root)]
-
- (1...(msgCnt)).each{|i|
- item_i = t.item_create
- item_j = nil
- j = nil
- loop {
- j = rand(i)
- item_j = items[j]
- break if j == 0
- next if t.depth(item_j) == 5
- next if @Message[:count][@Message[:thread][item_j]] == 15
- break
- }
- t.item_lastchild(item_j, item_i)
-
- @Message[:read][item_i] = (rand(2) == 0)
- if j == 0
- thread += 1
- @Message[:thread][item_i] = thread
- @Message[:seconds][item_i] = (Tk::Clock.seconds - rand(500000))
- @Message[:seconds2][item_i] = @Message[:seconds][item_i]
- @Message[:count][thread] = 1
- else
- @Message[:thread][item_i] = @Message[:thread][item_j]
- @Message[:seconds][item_i] = (@Message[:seconds2][item_j] + rand(10000))
- @Message[:seconds2][item_i] = @Message[:seconds][item_i]
- @Message[:seconds2][item_j] = @Message[:seconds][item_i]
- @Message[:count][@Message[:thread][item_j]] += 1
- end
- items << item_i
- }
-
- (1...(msgCnt)).each{|i|
- item_i = items[i]
- subject = "This is thread number #{@Message[:thread][item_i]}"
- from = 'somebody@somewhere.net'
- sent = Tk::Clock.format(@Message[:seconds][item_i], "%d/%m/%y %I:%M %p")
- size = "#{1 + rand(10)}KB"
-
- # This message has been read
- t.item_state_set(item_i, 'read') if @Message[:read][item_i]
-
- # This message has unread descendants
- t.item_state_set(item_i, 'unread') if anyUnreadDescendants(t, item_i)
-
- if t.item_numchildren(item_i) > 0
- if $Version_1_1_OrLater
- t.item_configure(item_i, :button=>true)
- else # TreeCtrl 1.0
- t.item_hasbutton(item_i, true)
- end
-
- # Collapse some messages
- if $Version_1_1_OrLater
- t.item_collapse(item_i) if rand(2) == 0
- else # TreeCtrl 1.0
- t.collapse(item_i) if rand(2) == 0
- end
- end
-
- unless $Version_1_1_OrLater
- t.item_style_set(item_i, 3, 's1', 4, 's2.we', 5, 's2.we', 6, 's2.w')
- end
- t.item_text(item_i, 3, subject, 4, from, 5, sent, 6, size)
- }
-
- # Do something when the selection changes
- t.notify_bind(t, 'Selection',
- proc{|w|
- if w.selection_count == 1
- # One item is selected
- if @Message[:afterId][:id]
- Tk.after_cancel(@Message[:afterId][:id])
- end
- @Message[:afterId][:item] = w.selection_get[0]
- @Message[:afterId][:id] = Tk.after(500, proc{
- messageReadDelayed(w)
- })
- end
- }, '%T')
-end
-
-def messageReadDelayed(t)
- @Message[:afterId].delete(:id)
- i = @Message[:afterId][:item]
- return unless t.selection_includes(i)
-
- # This message is not read
- unless @Message[:read][i]
- # Read the message
- t.item_state_set(i, 'read')
- @Message[:read][i] = true
-
- # Check ancestors (except root)
- t.item_ancestors(i)[0..-2].each{|i2|
- # This ancestor has no more unread descendants
- t.item_state_set(i2, '!unread') unless anyUnreadDescendants(t, i2)
- }
- end
-end
-
-# Alternate implementation which does not rely on run-time states
-def demoOutlookNewsgroup2(t)
- init_pics('outlook-*')
-
- height = t.font.metrics(:linespace)
- height = 18 if height < 18
- t.configure(:itemheight=>height, :selectmode=>:browse, :showlines=>false,
- :showroot=>false, :showrootbutton=>false, :showbuttons=>true)
-
- if $Version_1_1_OrLater
- t.column_create(:image=>@images['outlook-clip'], :tag=>'clip')
- t.column_create(:image=>@images['outlook-arrow'], :tag=>'arrow')
- t.column_create(:image=>@images['outlook-watch'], :tag=>'watch')
- t.column_create(:text=>'Subject', :width=>250, :tag=>'subject')
- t.column_create(:text=>'From', :width=>150, :tag=>'from')
- t.column_create(:text=>'Sent', :width=>150, :tag=>'sent')
- t.column_create(:text=>'Size', :width=>60, :justify=>:right, :tag=>'size')
- else # TreeCtrl 1.0
- t.column_configure(0, :image=>@images['outlook-clip'], :tag=>'clip')
- t.column_configure(1, :image=>@images['outlook-arrow'], :tag=>'arrow')
- t.column_configure(2, :image=>@images['outlook-watch'], :tag=>'watch')
- t.column_configure(3, :text=>'Subject', :width=>250, :tag=>'subject')
- t.column_configure(4, :text=>'From', :width=>150, :tag=>'from')
- t.column_configure(5, :text=>'Sent', :width=>150, :tag=>'sent')
- t.column_configure(6, :text=>'Size', :width=>60, :justify=>:right,
- :tag=>'size')
- end
-
- t.treecolumn = 3
-
- t.element_create('image.unread', :image, :image=>@images['outlook-unread'])
- t.element_create('image.read', :image, :image=>@images['outlook-read'])
- t.element_create('image.read2', :image, :image=>@images['outlook-read-2'])
- t.element_create('text.read', :text, :lines=>1,
- :fill=>[@SystemHighlightText, ['selected', 'focus']])
- t.element_create('text.unread', :text, :lines=>1,
- :fill=>[@SystemHighlightText, ['selected', 'focus']],
- :font=>t.font.dup.weight(:bold))
- t.element_create('sel.e', :rect, :open=>:e, :showfocus=>true,
- :fill=>[
- @SystemHighlight, ['selected', 'focus'],
- 'gray', ['selected', '!focus']
- ])
- t.element_create('sel.w', :rect, :open=>:w, :showfocus=>true,
- :fill=>[
- @SystemHighlight, ['selected', 'focus'],
- 'gray', ['selected', '!focus']
- ])
- t.element_create('sel.we', :rect, :open=>:we, :showfocus=>true,
- :fill=>[
- @SystemHighlight, ['selected', 'focus'],
- 'gray', ['selected', '!focus']
- ])
-
- # Image + text
- s = t.style_create('unread')
- t.style_elements(s, ['sel.e', 'image.unread', 'text.unread'])
- t.style_layout(s, 'image.unread', :expand=>:ns)
- t.style_layout(s, 'text.unread', :padx=>[2,6], :squeeze=>:x, :expand=>:ns)
- t.style_layout(s, 'sel.e', :union=>['text.unread'],
- :iexpand=>:nes, :ipadx=>[2,0])
-
- # Image + text
- s = t.style_create('read')
- t.style_elements(s, ['sel.e', 'image.read', 'text.read'])
- t.style_layout(s, 'image.read', :expand=>:ns)
- t.style_layout(s, 'text.read', :padx=>[2,6], :squeeze=>:x, :expand=>:ns)
- t.style_layout(s, 'sel.e', :union=>['text.read'],
- :iexpand=>:nes, :ipadx=>[2,0])
-
- # Image + text
- s = t.style_create('read2')
- t.style_elements(s, ['sel.e', 'image.read2', 'text.unread'])
- t.style_layout(s, 'image.read2', :expand=>:ns)
- t.style_layout(s, 'text.unread', :padx=>[2,6], :squeeze=>:x, :expand=>:ns)
- t.style_layout(s, 'sel.e', :union=>['text.unread'],
- :iexpand=>:nes, :ipadx=>[2,0])
-
- # Text
- s = t.style_create('unread.we')
- t.style_elements(s, ['sel.we', 'text.unread'])
- t.style_layout(s, 'text.unread', :padx=>6, :squeeze=>:x, :expand=>:ns)
- t.style_layout(s, 'sel.we', :detach=>true, :iexpand=>:es)
-
- # Text
- s = t.style_create('read.we')
- t.style_elements(s, ['sel.we', 'text.read'])
- t.style_layout(s, 'text.read', :padx=>6, :squeeze=>:x, :expand=>:ns)
- t.style_layout(s, 'sel.we', :detach=>true, :iexpand=>:es)
-
- # Text
- s = t.style_create('unread.w')
- t.style_elements(s, ['sel.w', 'text.unread'])
- t.style_layout(s, 'text.unread', :padx=>6, :squeeze=>:x, :expand=>:ns)
- t.style_layout(s, 'sel.w', :detach=>true, :iexpand=>:es)
-
- # Text
- s = t.style_create('read.w')
- t.style_elements(s, ['sel.w', 'text.read'])
- t.style_layout(s, 'text.read', :padx=>6, :squeeze=>:x, :expand=>:ns)
- t.style_layout(s, 'sel.w', :detach=>true, :iexpand=>:es)
-
- msgCnt = 100
- thread = 0
-
- @Message = Hash.new{|k, v| k[v] = Hash.new}
- @Message[:count][0] = 0
-
- (1...(msgCnt)).each{|i|
- t.item_create
- j = nil
- loop {
- j = rand(i)
- break if j == 0
- next if t.depth(j) == 5
- next if @Message[:count][@Message[:thread][j]] == 15
- break
- }
- t.item_lastchild(j, i)
-
- @Message[:read][i] = (rand(2) == 0)
- if j == 0
- thread += 1
- @Message[:thread][i] = thread
- @Message[:seconds][i] = (Tk::Clock.seconds - rand(500000))
- @Message[:seconds2][i] = @Message[:seconds][i]
- @Message[:count][thread] = 1
- else
- @Message[:thread][i] = @Message[:thread][j]
- @Message[:seconds][i] = (@Message[:seconds2][j] + rand(10000))
- @Message[:seconds2][i] = @Message[:seconds][i]
- @Message[:seconds2][j] = @Message[:seconds][i]
- @Message[:count][@Message[:thread][j]] += 1
- end
- }
-
- (1...(msgCnt)).each{|i|
- subject = "This is thread number #{@Message[:thread][i]}"
- from = 'somebody@somewhere.net'
- sent = Tk::Clock.format(@Message[:seconds][i], "%d/%m/%y %I:%M %p")
- size = "#{1 + rand(10)}KB"
- if @Message[:read][i]
- style = 'read'
- style2 = 'read2'
- else
- style = 'unread'
- style2 = 'unread2'
- end
- t.item_style_set(i, 3, style, 4, "#{style2}.we", 5, "#{style2}.we",
- 6, "#{style2}.w")
- t.item_text(i, 3, subject, 4, from, 5, sent, 6, size)
- if t.item_numchildren(i) > 0
- t.item_configure(item_i, :button=>true)
- end
- }
-
- # Do something when the selection changes
- t.notify_bind(t, 'Selection',
- proc{|w|
- if w.selection_count == 1
- i = t.selection_get[0]
- unless @Message[:read][i]
- if t.item_isopen(i) || !anyUnreadDescendants(t, i)
- # unread -> read
- t.item_style_map(i, 'subject', 'read',
- ['text.unread', 'text.read'])
- t.item_style_map(i, 'from', 'read.we',
- ['text.unread', 'text.read'])
- t.item_style_map(i, 'sent', 'read.we',
- ['text.unread', 'text.read'])
- t.item_style_map(i, 'size', 'read.w',
- ['text.unread', 'text.read'])
- else
- # unread -> read2
- t.item_style_map(i, 'subject', 'read2',
- ['text.unread', 'text.unread'])
- end
-
- @Message[:read][i] = true
- @display_styles_in_item.call(i)
- end
- end
- }, '%T')
-
- t.notify_bind(t, 'Expand-after',
- proc{|w, i|
- if @Messge[:read][i] && anyUnreadDescendants(t, i)
- # read2 -> read
- t.item_style_map(i, 'subject', 'read',
- ['text.unread', 'text.read'])
- # unread -> read
- t.item_style_map(i, 'from', 'read.we',
- ['text.unread', 'text.read'])
- t.item_style_map(i, 'sent', 'read.we',
- ['text.unread', 'text.read'])
- t.item_style_map(i, 'size', 'read.w',
- ['text.unread', 'text.read'])
- end
- }, '%T %I')
-
- t.notify_bind(t, 'Collapse-after',
- proc{|w, i|
- if @Messge[:read][i] && anyUnreadDescendants(t, i)
- # read -> read2
- t.item_style_map(i, 'subject', 'read2',
- ['text.read', 'text.unread'])
- # read -> unread
- t.item_style_map(i, 'from', 'unread.we',
- ['text.read', 'text.unread'])
- t.item_style_map(i, 'sent', 'unread.we',
- ['text.read', 'text.unread'])
- t.item_style_map(i, 'size', 'unread.w',
- ['text.read', 'text.unread'])
- end
- }, '%T %I')
-
- (1...(msgCnt)).each{|i|
- if rand(2) == 0
- if t.item_numchildren(i) > 0
- if $Version_1_1_OrLater
- t.item_collapse(i)
- else # TreeCtrl 1.0
- t.collapse(i)
- end
- end
- end
- }
-end
-
-def anyUnreadDescendants(t, i)
- itemList = []
- item = t.item_firstchild(i)
- itemList.push(item) if item != ''
-
- while item = itemList.pop
- return true unless @Message[:read][item]
-
- item2 = t.item_nextsibling(item)
- itemList.push(item2) if item2 != ''
- item2 = t.item_firstchild(item)
- itemList.push(item2) if item2 != ''
- end
- false
-end
diff --git a/ext/tk/sample/tkextlib/treectrl/pics/big-dll.gif b/ext/tk/sample/tkextlib/treectrl/pics/big-dll.gif
deleted file mode 100644
index 09170c0e26..0000000000
--- a/ext/tk/sample/tkextlib/treectrl/pics/big-dll.gif
+++ /dev/null
Binary files differ
diff --git a/ext/tk/sample/tkextlib/treectrl/pics/big-exe.gif b/ext/tk/sample/tkextlib/treectrl/pics/big-exe.gif
deleted file mode 100644
index e19aac1a2d..0000000000
--- a/ext/tk/sample/tkextlib/treectrl/pics/big-exe.gif
+++ /dev/null
Binary files differ
diff --git a/ext/tk/sample/tkextlib/treectrl/pics/big-file.gif b/ext/tk/sample/tkextlib/treectrl/pics/big-file.gif
deleted file mode 100644
index 6c752312a3..0000000000
--- a/ext/tk/sample/tkextlib/treectrl/pics/big-file.gif
+++ /dev/null
Binary files differ
diff --git a/ext/tk/sample/tkextlib/treectrl/pics/big-folder.gif b/ext/tk/sample/tkextlib/treectrl/pics/big-folder.gif
deleted file mode 100644
index 186c9749fd..0000000000
--- a/ext/tk/sample/tkextlib/treectrl/pics/big-folder.gif
+++ /dev/null
Binary files differ
diff --git a/ext/tk/sample/tkextlib/treectrl/pics/big-txt.gif b/ext/tk/sample/tkextlib/treectrl/pics/big-txt.gif
deleted file mode 100644
index a93492586e..0000000000
--- a/ext/tk/sample/tkextlib/treectrl/pics/big-txt.gif
+++ /dev/null
Binary files differ
diff --git a/ext/tk/sample/tkextlib/treectrl/pics/checked.gif b/ext/tk/sample/tkextlib/treectrl/pics/checked.gif
deleted file mode 100644
index 3b9b176ab3..0000000000
--- a/ext/tk/sample/tkextlib/treectrl/pics/checked.gif
+++ /dev/null
Binary files differ
diff --git a/ext/tk/sample/tkextlib/treectrl/pics/file.gif b/ext/tk/sample/tkextlib/treectrl/pics/file.gif
deleted file mode 100644
index a64c2a06bd..0000000000
--- a/ext/tk/sample/tkextlib/treectrl/pics/file.gif
+++ /dev/null
Binary files differ
diff --git a/ext/tk/sample/tkextlib/treectrl/pics/folder-closed.gif b/ext/tk/sample/tkextlib/treectrl/pics/folder-closed.gif
deleted file mode 100644
index 0a064376c9..0000000000
--- a/ext/tk/sample/tkextlib/treectrl/pics/folder-closed.gif
+++ /dev/null
Binary files differ
diff --git a/ext/tk/sample/tkextlib/treectrl/pics/folder-open.gif b/ext/tk/sample/tkextlib/treectrl/pics/folder-open.gif
deleted file mode 100644
index 3fac27ffd9..0000000000
--- a/ext/tk/sample/tkextlib/treectrl/pics/folder-open.gif
+++ /dev/null
Binary files differ
diff --git a/ext/tk/sample/tkextlib/treectrl/pics/help-book-closed.gif b/ext/tk/sample/tkextlib/treectrl/pics/help-book-closed.gif
deleted file mode 100644
index 0a0497bfa3..0000000000
--- a/ext/tk/sample/tkextlib/treectrl/pics/help-book-closed.gif
+++ /dev/null
Binary files differ
diff --git a/ext/tk/sample/tkextlib/treectrl/pics/help-book-open.gif b/ext/tk/sample/tkextlib/treectrl/pics/help-book-open.gif
deleted file mode 100644
index 40656c5194..0000000000
--- a/ext/tk/sample/tkextlib/treectrl/pics/help-book-open.gif
+++ /dev/null
Binary files differ
diff --git a/ext/tk/sample/tkextlib/treectrl/pics/help-page.gif b/ext/tk/sample/tkextlib/treectrl/pics/help-page.gif
deleted file mode 100644
index e1ce1d72f5..0000000000
--- a/ext/tk/sample/tkextlib/treectrl/pics/help-page.gif
+++ /dev/null
Binary files differ
diff --git a/ext/tk/sample/tkextlib/treectrl/pics/imovie-01.gif b/ext/tk/sample/tkextlib/treectrl/pics/imovie-01.gif
deleted file mode 100644
index 5fd9215551..0000000000
--- a/ext/tk/sample/tkextlib/treectrl/pics/imovie-01.gif
+++ /dev/null
Binary files differ
diff --git a/ext/tk/sample/tkextlib/treectrl/pics/imovie-02.gif b/ext/tk/sample/tkextlib/treectrl/pics/imovie-02.gif
deleted file mode 100644
index 3d2d1c17c2..0000000000
--- a/ext/tk/sample/tkextlib/treectrl/pics/imovie-02.gif
+++ /dev/null
Binary files differ
diff --git a/ext/tk/sample/tkextlib/treectrl/pics/imovie-03.gif b/ext/tk/sample/tkextlib/treectrl/pics/imovie-03.gif
deleted file mode 100644
index 9fccf12b51..0000000000
--- a/ext/tk/sample/tkextlib/treectrl/pics/imovie-03.gif
+++ /dev/null
Binary files differ
diff --git a/ext/tk/sample/tkextlib/treectrl/pics/imovie-04.gif b/ext/tk/sample/tkextlib/treectrl/pics/imovie-04.gif
deleted file mode 100644
index eff851c9bb..0000000000
--- a/ext/tk/sample/tkextlib/treectrl/pics/imovie-04.gif
+++ /dev/null
Binary files differ
diff --git a/ext/tk/sample/tkextlib/treectrl/pics/imovie-05.gif b/ext/tk/sample/tkextlib/treectrl/pics/imovie-05.gif
deleted file mode 100644
index ad00c827f6..0000000000
--- a/ext/tk/sample/tkextlib/treectrl/pics/imovie-05.gif
+++ /dev/null
Binary files differ
diff --git a/ext/tk/sample/tkextlib/treectrl/pics/imovie-06.gif b/ext/tk/sample/tkextlib/treectrl/pics/imovie-06.gif
deleted file mode 100644
index 238bf162ac..0000000000
--- a/ext/tk/sample/tkextlib/treectrl/pics/imovie-06.gif
+++ /dev/null
Binary files differ
diff --git a/ext/tk/sample/tkextlib/treectrl/pics/imovie-07.gif b/ext/tk/sample/tkextlib/treectrl/pics/imovie-07.gif
deleted file mode 100644
index a9287e1b1c..0000000000
--- a/ext/tk/sample/tkextlib/treectrl/pics/imovie-07.gif
+++ /dev/null
Binary files differ
diff --git a/ext/tk/sample/tkextlib/treectrl/pics/internet-check-off.gif b/ext/tk/sample/tkextlib/treectrl/pics/internet-check-off.gif
deleted file mode 100644
index e64866a394..0000000000
--- a/ext/tk/sample/tkextlib/treectrl/pics/internet-check-off.gif
+++ /dev/null
Binary files differ
diff --git a/ext/tk/sample/tkextlib/treectrl/pics/internet-check-on.gif b/ext/tk/sample/tkextlib/treectrl/pics/internet-check-on.gif
deleted file mode 100644
index cf652beff2..0000000000
--- a/ext/tk/sample/tkextlib/treectrl/pics/internet-check-on.gif
+++ /dev/null
Binary files differ
diff --git a/ext/tk/sample/tkextlib/treectrl/pics/internet-print.gif b/ext/tk/sample/tkextlib/treectrl/pics/internet-print.gif
deleted file mode 100644
index 7ac25b10e9..0000000000
--- a/ext/tk/sample/tkextlib/treectrl/pics/internet-print.gif
+++ /dev/null
Binary files differ
diff --git a/ext/tk/sample/tkextlib/treectrl/pics/internet-radio-off.gif b/ext/tk/sample/tkextlib/treectrl/pics/internet-radio-off.gif
deleted file mode 100644
index 90ef62971f..0000000000
--- a/ext/tk/sample/tkextlib/treectrl/pics/internet-radio-off.gif
+++ /dev/null
Binary files differ
diff --git a/ext/tk/sample/tkextlib/treectrl/pics/internet-radio-on.gif b/ext/tk/sample/tkextlib/treectrl/pics/internet-radio-on.gif
deleted file mode 100644
index 9de742c198..0000000000
--- a/ext/tk/sample/tkextlib/treectrl/pics/internet-radio-on.gif
+++ /dev/null
Binary files differ
diff --git a/ext/tk/sample/tkextlib/treectrl/pics/internet-search.gif b/ext/tk/sample/tkextlib/treectrl/pics/internet-search.gif
deleted file mode 100644
index 1f9a047701..0000000000
--- a/ext/tk/sample/tkextlib/treectrl/pics/internet-search.gif
+++ /dev/null
Binary files differ
diff --git a/ext/tk/sample/tkextlib/treectrl/pics/internet-security.gif b/ext/tk/sample/tkextlib/treectrl/pics/internet-security.gif
deleted file mode 100644
index 86d3943786..0000000000
--- a/ext/tk/sample/tkextlib/treectrl/pics/internet-security.gif
+++ /dev/null
Binary files differ
diff --git a/ext/tk/sample/tkextlib/treectrl/pics/mac-collapse.gif b/ext/tk/sample/tkextlib/treectrl/pics/mac-collapse.gif
deleted file mode 100644
index 81302c80c1..0000000000
--- a/ext/tk/sample/tkextlib/treectrl/pics/mac-collapse.gif
+++ /dev/null
Binary files differ
diff --git a/ext/tk/sample/tkextlib/treectrl/pics/mac-expand.gif b/ext/tk/sample/tkextlib/treectrl/pics/mac-expand.gif
deleted file mode 100644
index 0a2cd80040..0000000000
--- a/ext/tk/sample/tkextlib/treectrl/pics/mac-expand.gif
+++ /dev/null
Binary files differ
diff --git a/ext/tk/sample/tkextlib/treectrl/pics/outlook-arrow.gif b/ext/tk/sample/tkextlib/treectrl/pics/outlook-arrow.gif
deleted file mode 100644
index b1c2afd426..0000000000
--- a/ext/tk/sample/tkextlib/treectrl/pics/outlook-arrow.gif
+++ /dev/null
Binary files differ
diff --git a/ext/tk/sample/tkextlib/treectrl/pics/outlook-clip.gif b/ext/tk/sample/tkextlib/treectrl/pics/outlook-clip.gif
deleted file mode 100644
index 8578132702..0000000000
--- a/ext/tk/sample/tkextlib/treectrl/pics/outlook-clip.gif
+++ /dev/null
Binary files differ
diff --git a/ext/tk/sample/tkextlib/treectrl/pics/outlook-deleted.gif b/ext/tk/sample/tkextlib/treectrl/pics/outlook-deleted.gif
deleted file mode 100644
index 7cc8369b4b..0000000000
--- a/ext/tk/sample/tkextlib/treectrl/pics/outlook-deleted.gif
+++ /dev/null
Binary files differ
diff --git a/ext/tk/sample/tkextlib/treectrl/pics/outlook-draft.gif b/ext/tk/sample/tkextlib/treectrl/pics/outlook-draft.gif
deleted file mode 100644
index f19585050f..0000000000
--- a/ext/tk/sample/tkextlib/treectrl/pics/outlook-draft.gif
+++ /dev/null
Binary files differ
diff --git a/ext/tk/sample/tkextlib/treectrl/pics/outlook-folder.gif b/ext/tk/sample/tkextlib/treectrl/pics/outlook-folder.gif
deleted file mode 100644
index b3f733563b..0000000000
--- a/ext/tk/sample/tkextlib/treectrl/pics/outlook-folder.gif
+++ /dev/null
Binary files differ
diff --git a/ext/tk/sample/tkextlib/treectrl/pics/outlook-group.gif b/ext/tk/sample/tkextlib/treectrl/pics/outlook-group.gif
deleted file mode 100644
index 29ad9b466e..0000000000
--- a/ext/tk/sample/tkextlib/treectrl/pics/outlook-group.gif
+++ /dev/null
Binary files differ
diff --git a/ext/tk/sample/tkextlib/treectrl/pics/outlook-inbox.gif b/ext/tk/sample/tkextlib/treectrl/pics/outlook-inbox.gif
deleted file mode 100644
index f41d804444..0000000000
--- a/ext/tk/sample/tkextlib/treectrl/pics/outlook-inbox.gif
+++ /dev/null
Binary files differ
diff --git a/ext/tk/sample/tkextlib/treectrl/pics/outlook-local.gif b/ext/tk/sample/tkextlib/treectrl/pics/outlook-local.gif
deleted file mode 100644
index 0c74970d32..0000000000
--- a/ext/tk/sample/tkextlib/treectrl/pics/outlook-local.gif
+++ /dev/null
Binary files differ
diff --git a/ext/tk/sample/tkextlib/treectrl/pics/outlook-main.gif b/ext/tk/sample/tkextlib/treectrl/pics/outlook-main.gif
deleted file mode 100644
index 92325fa85f..0000000000
--- a/ext/tk/sample/tkextlib/treectrl/pics/outlook-main.gif
+++ /dev/null
Binary files differ
diff --git a/ext/tk/sample/tkextlib/treectrl/pics/outlook-outbox.gif b/ext/tk/sample/tkextlib/treectrl/pics/outlook-outbox.gif
deleted file mode 100644
index c7e80527a0..0000000000
--- a/ext/tk/sample/tkextlib/treectrl/pics/outlook-outbox.gif
+++ /dev/null
Binary files differ
diff --git a/ext/tk/sample/tkextlib/treectrl/pics/outlook-read-2.gif b/ext/tk/sample/tkextlib/treectrl/pics/outlook-read-2.gif
deleted file mode 100644
index 2f15a3af05..0000000000
--- a/ext/tk/sample/tkextlib/treectrl/pics/outlook-read-2.gif
+++ /dev/null
Binary files differ
diff --git a/ext/tk/sample/tkextlib/treectrl/pics/outlook-read.gif b/ext/tk/sample/tkextlib/treectrl/pics/outlook-read.gif
deleted file mode 100644
index a6f956207a..0000000000
--- a/ext/tk/sample/tkextlib/treectrl/pics/outlook-read.gif
+++ /dev/null
Binary files differ
diff --git a/ext/tk/sample/tkextlib/treectrl/pics/outlook-sent.gif b/ext/tk/sample/tkextlib/treectrl/pics/outlook-sent.gif
deleted file mode 100644
index 963b56c4c9..0000000000
--- a/ext/tk/sample/tkextlib/treectrl/pics/outlook-sent.gif
+++ /dev/null
Binary files differ
diff --git a/ext/tk/sample/tkextlib/treectrl/pics/outlook-server.gif b/ext/tk/sample/tkextlib/treectrl/pics/outlook-server.gif
deleted file mode 100644
index c950845d62..0000000000
--- a/ext/tk/sample/tkextlib/treectrl/pics/outlook-server.gif
+++ /dev/null
Binary files differ
diff --git a/ext/tk/sample/tkextlib/treectrl/pics/outlook-unread.gif b/ext/tk/sample/tkextlib/treectrl/pics/outlook-unread.gif
deleted file mode 100644
index 3df4b99439..0000000000
--- a/ext/tk/sample/tkextlib/treectrl/pics/outlook-unread.gif
+++ /dev/null
Binary files differ
diff --git a/ext/tk/sample/tkextlib/treectrl/pics/outlook-watch.gif b/ext/tk/sample/tkextlib/treectrl/pics/outlook-watch.gif
deleted file mode 100644
index 87ec861312..0000000000
--- a/ext/tk/sample/tkextlib/treectrl/pics/outlook-watch.gif
+++ /dev/null
Binary files differ
diff --git a/ext/tk/sample/tkextlib/treectrl/pics/sky.gif b/ext/tk/sample/tkextlib/treectrl/pics/sky.gif
deleted file mode 100644
index b7fbf14a0a..0000000000
--- a/ext/tk/sample/tkextlib/treectrl/pics/sky.gif
+++ /dev/null
Binary files differ
diff --git a/ext/tk/sample/tkextlib/treectrl/pics/small-dll.gif b/ext/tk/sample/tkextlib/treectrl/pics/small-dll.gif
deleted file mode 100644
index d8875ec23f..0000000000
--- a/ext/tk/sample/tkextlib/treectrl/pics/small-dll.gif
+++ /dev/null
Binary files differ
diff --git a/ext/tk/sample/tkextlib/treectrl/pics/small-exe.gif b/ext/tk/sample/tkextlib/treectrl/pics/small-exe.gif
deleted file mode 100644
index 69d30beacd..0000000000
--- a/ext/tk/sample/tkextlib/treectrl/pics/small-exe.gif
+++ /dev/null
Binary files differ
diff --git a/ext/tk/sample/tkextlib/treectrl/pics/small-file.gif b/ext/tk/sample/tkextlib/treectrl/pics/small-file.gif
deleted file mode 100644
index f340662879..0000000000
--- a/ext/tk/sample/tkextlib/treectrl/pics/small-file.gif
+++ /dev/null
Binary files differ
diff --git a/ext/tk/sample/tkextlib/treectrl/pics/small-folder.gif b/ext/tk/sample/tkextlib/treectrl/pics/small-folder.gif
deleted file mode 100644
index ad1b24da84..0000000000
--- a/ext/tk/sample/tkextlib/treectrl/pics/small-folder.gif
+++ /dev/null
Binary files differ
diff --git a/ext/tk/sample/tkextlib/treectrl/pics/small-txt.gif b/ext/tk/sample/tkextlib/treectrl/pics/small-txt.gif
deleted file mode 100644
index cdc7cbfe99..0000000000
--- a/ext/tk/sample/tkextlib/treectrl/pics/small-txt.gif
+++ /dev/null
Binary files differ
diff --git a/ext/tk/sample/tkextlib/treectrl/pics/unchecked.gif b/ext/tk/sample/tkextlib/treectrl/pics/unchecked.gif
deleted file mode 100644
index 833e48268b..0000000000
--- a/ext/tk/sample/tkextlib/treectrl/pics/unchecked.gif
+++ /dev/null
Binary files differ
diff --git a/ext/tk/sample/tkextlib/treectrl/random.rb b/ext/tk/sample/tkextlib/treectrl/random.rb
deleted file mode 100644
index 2c9e614aa5..0000000000
--- a/ext/tk/sample/tkextlib/treectrl/random.rb
+++ /dev/null
@@ -1,508 +0,0 @@
-#
-def random_N
- @RandomN[0] || 500
-end
-
-#
-# Demo: random N items
-#
-def demoRandom(t)
- init_pics('folder-*', 'small-*')
-
- height = t.font.metrics(:linespace)
- height = 18 if height < 18
- t.configure(:itemheight=>height, :selectmode=>:extended,
- :showroot=>true, :showrootbutton=>true, :showbuttons=>true,
- :showlines=>true, :scrollmargin=>16,
- :xscrolldelay=>[500, 50], :yscrolldelay=>[500, 50])
-
- if $Version_1_1_OrLater
- t.column_create(:expand=>true, :text=>'Item',
- :itembackground=>['#e0e8f0', []], :tag=>'item')
- t.column_create(:text=>'Parent', :justify=>:center,
- :itembackground=>['gray90', []], :tag=>'parent')
- t.column_create(:text=>'Depth', :justify=>:center,
- :itembackground=>['linen', []], :tag=>'depth')
- else # TreeCtrl 1.0
- t.column_configure(0, :expand=>true, :text=>'Item',
- :itembackground=>['#e0e8f0', []], :tag=>'item')
- t.column_configure(1, :text=>'Parent', :justify=>:center,
- :itembackground=>['gray90', []], :tag=>'parent')
- t.column_configure(2, :text=>'Depth', :justify=>:center,
- :itembackground=>['linen', []], :tag=>'depth')
- end
-
- t.element_create('e1', :image, :image=>[
- @images['folder-open'], ['open'],
- @images['folder-closed'], []
- ])
- t.element_create('e2', :image, :image=>@images['small-file'])
- t.element_create('e3', :text,
- :fill=>[@SystemHighlightText, ['selected', 'focus']])
- t.element_create('e4', :text, :fill=>'blue')
- t.element_create('e6', :text)
- t.element_create('e5', :rect, :showfocus=>true,
- :fill=>[
- @SystemHighlight, ['selected', 'focus'],
- 'gray', ['selected', '!focus']
- ])
-
- s = t.style_create('s1')
- t.style_elements(s, ['e5', 'e1', 'e3', 'e4'])
- t.style_layout(s, 'e1', :padx=>[0,4], :expand=>:ns)
- t.style_layout(s, 'e3', :padx=>[0,4], :expand=>:ns)
- t.style_layout(s, 'e4', :padx=>[0,6], :expand=>:ns)
- t.style_layout(s, 'e5', :union=>['e3'], :iexpand=>:ns, :ipadx=>2)
-
- s = t.style_create('s2')
- t.style_elements(s, ['e5', 'e2', 'e3'])
- t.style_layout(s, 'e2', :padx=>[0,4], :expand=>:ns)
- t.style_layout(s, 'e3', :padx=>[0,4], :expand=>:ns)
- t.style_layout(s, 'e5', :union=>['e3'], :iexpand=>:ns, :ipadx=>2)
-
- s = t.style_create('s3')
- t.style_elements(s, ['e6'])
- t.style_layout(s, 'e6', :padx=>6, :expand=>:ns)
-
- @Priv[:sensitive, t] = [
- [:item, 's1', 'e5', 'e1', 'e3'],
- [:item, 's2', 'e5', 'e2', 'e3']
- ]
- @Priv[:dragimage, t] = [
- [:item, 's1', 'e1', 'e3'],
- [:item, 's2', 'e2', 'e3']
- ]
-
- clicks = Tk::Clock.clicks
- items = [ t.index(:root) ]
- (1...(random_N())).each{|i|
- item_i = t.item_create
- item_j = nil
- loop {
- j = rand(i)
- item_j = items[j]
- break if t.depth(item_j) < 5
- }
- if $Version_1_1_OrLater
- t.item_collapse(item_i) if rand(2) == 0
- else # TreeCtrl 1.0
- t.collapse(item_i) if rand(2) == 0
- end
- if rand(2) == 0
- t.item_lastchild(item_j, item_i)
- else
- t.item_firstchild(item_j, item_i)
- end
- items << item_i
- }
- puts "created #{random_N() - 1} items in #{Tk::Clock.clicks - clicks} clicks"
-
- clicks = Tk::Clock.clicks
- (0...(random_N())).each{|i|
- item_i = items[i]
- numChildren = t.item_numchildren(item_i)
- if numChildren > 0
- if $Version_1_1_OrLater
- t.item_configure(item_i, :button=>true)
- else # TreeCtrl 1.0
- t.item_hasbutton(item_i, true)
- end
- t.item_style_set(item_i, 0, 's1', 1, 's3', 2, 's3')
- t.item_complex(item_i,
- [ ['e3', {:text=>"Item #{i}"}],
- ['e4', {:text=>"(#{numChildren})"}] ],
- [ ['e6', {:text=>"#{t.item_parent(item_i)}"}] ],
- [ ['e6', {:text=>"#{t.depth(item_i)}"}] ])
- else
- t.item_style_set(item_i, 1, 's3', 2, 's3', 0, 's2')
- t.item_complex(item_i,
- [ ['e3', {:text=>"Item #{i}"}] ],
- [ ['e6', {:text=>"#{t.item_parent(item_i)}"}] ],
- [ ['e6', {:text=>"#{t.depth(item_i)}"}] ])
- end
- }
- puts "configured #{random_N()} items in #{Tk::Clock.clicks - clicks} clicks"
-
- treeCtrlRandom = TkBindTag.new
-
- treeCtrlRandom.bind('Double-ButtonPress-1',
- proc{|w, x, y|
- Tk::TreeCtrl::BindCallback.doubleButton1(w, x, y)
- Tk.callback_break
- }, '%W %x %y')
-
- treeCtrlRandom.bind('Control-ButtonPress-1',
- proc{|w, x, y|
- @Priv['selectMode'] = :toggle
- randomButton1(w, x, y)
- Tk.callback_break
- }, '%W %x %y')
-
- treeCtrlRandom.bind('Shift-ButtonPress-1',
- proc{|w, x, y|
- @Priv['selectMode'] = :add
- randomButton1(w, x, y)
- Tk.callback_break
- }, '%W %x %y')
-
- treeCtrlRandom.bind('ButtonPress-1',
- proc{|w, x, y|
- @Priv['selectMode'] = :set
- randomButton1(w, x, y)
- Tk.callback_break
- }, '%W %x %y')
-
- treeCtrlRandom.bind('Button1-Motion',
- proc{|w, x, y|
- randomMotion1(w, x, y)
- Tk.callback_break
- }, '%W %x %y')
-
- treeCtrlRandom.bind('Button1-Leave',
- proc{|w, x, y|
- randomLeave1(w, x, y)
- Tk.callback_break
- }, '%W %x %y')
-
- treeCtrlRandom.bind('ButtonRelease-1',
- proc{|w, x, y|
- randomRelease1(w, x, y)
- Tk.callback_break
- }, '%W %x %y')
-
- t.bindtags = [ t, treeCtrlRandom, Tk::TreeCtrl, t.winfo_toplevel, :all ]
-end
-
-def randomButton1(t, x, y)
- t.set_focus
- id = t.identify(x, y)
- puts id.inspect
- @Priv['buttonMode'] = ''
-
- # Click outside any item
- if id.empty?
- t.selection_clear
-
- # Click in header
- elsif id[0] == 'header'
- Tk::TreeCtrl::BindCallback.buttonPress1(t, x, y)
-
- # Click in item
- else
- where, item, arg1, arg2, arg3, arg4 = id
- case arg1
- when 'button'
- if $Version_1_1_OrLater
- t.item_toggle(item)
- else # TreeCtrl 1.0
- t.toggle(item)
- end
-
- when 'line'
- if $Version_1_1_OrLater
- t.item_toggle(arg2)
- else # TreeCtrl 1.0
- t.toggle(arg2)
- end
-
- when 'column'
- ok = false
- # Clicked an element
- if id.length == 6
- column = id[3]
- e = id[5]
- @Priv.list_element(:sensitive, t).each{|lst|
- c, s, *eList = TkComm.simplelist(lst)
- next if column != t.column_index(c)
- next if t.item_style_set(item, c) != s
- next if eList.find{|le| le == e} == nil
- ok = true
- break
- }
- end
- unless ok
- t.selection_clear
- return
- end
-
- @Priv[:drag, :motion] = 0
- @Priv[:drag, :x] = t.canvasx(x)
- @Priv[:drag, :y] = t.canvasy(y)
- @Priv[:drop] = ''
-
- if @Priv['selectMode'] == 'add'
- Tk::TreeCtrl::BindCallback.beginExtend(t, item)
- elsif @Priv['selectMode'] == 'toggle'
- Tk::TreeCtrl::BindCallback.beginToggle(t, item)
- elsif ! t.selection_includes(item)
- Tk::TreeCtrl::BindCallback.beginSelect(t, item)
- end
- t.activate(item)
-
- if t.selection_includes(item)
- @Priv['buttonMode'] = 'drag'
- end
- end
- end
-end
-
-def randomMotion1(t, x, y)
- case @Priv['buttonMode']
- when 'resize', 'header'
- Tk::TreeCtrl::BindCallback.motion1(t, x, y)
- when 'drag'
- randomAutoScanCheck(t, x, y)
- randomMotion(t, x, y)
- end
-end
-
-def randomMotion(t, x, y)
- case @Priv['buttonMode']
- when 'resize', 'header'
- Tk::TreeCtrl::BindCallback.motion1(t, x, y)
-
- when 'drag'
- # Detect initial mouse movement
- unless @Priv.bool_element(:drag, :motion)
- @Priv[:selection] = t.selection_get
- @Priv[:drop] = ''
- t.dragimage_clear
- # For each selected item, add 2nd and 3rd elements of
- # column "item" to the dragimage
- @Priv.list_element(:selection).each{|i|
- @Priv.list_element(:dragimage,t).each{|lst|
- c, s, *eList = TkComm.simplelist(lst)
- if t.item_style_set(i, c) == s
- t.dragimage_add(i, c, *eList)
- end
- }
- }
- @Priv[:drag,:motion] = true
- end
-
- # Find the item under the cursor
- cursor = 'X_cursor'
- drop = ''
- id = t.identify(x, y)
- ok = false
- if !id.empty? && id[0] == 'item' && id.length == 6
- item = id[1]
- column = id[3]
- e = id[5]
- @Priv.list_element(:sensitive,t).each{|lst|
- c, s, *eList = TkComm.simplelist(lst)
- next if column != t.column_index(c)
- next if t.item_style_set(item, c) != s
- next unless eList.find{|val| val.to_s == e.to_s}
- ok = true
- break
- }
- ok = true if @Priv.list_element(:sensitive,t).find{|val| TkComm.simplelist(val).index(e)}
- end
-
- if ok
- # If the item is not in the pre-drag selection
- # (i.e. not being dragged) see if we can drop on it
- unless @Priv.list_element(:selection).find{|val| val.to_s == item.to_s}
- drop = item
- # We can drop if dragged item isn't an ancestor
- @Priv.list_element(:selection).each{|item2|
- if t.item_isancestor(item2, item)
- drop = ''
- break
- end
- }
- if drop != ''
- x1, y1, x2, y2 = t.item_bbox(drop)
- if y < y1 + 3
- cursor = 'top_side'
- @Priv[:drop,:pos] = 'prevsibling'
- elsif y >= y2 - 3
- cursor = 'bottom_side'
- @Priv[:drop,:pos] = 'nextsibling'
- else
- cursor = ''
- @Priv[:drop,:pos] = 'lastchild'
- end
- end
- end
- end
-
- t[:cursor] = cursor if t[:cursor] != cursor
-
- # Select the item under the cursor (if any) and deselect
- # the previous drop-item (if any)
- t.selection_modify(drop, @Priv[:drop])
- @Priv[:drop] = drop
-
- # Show the dragimage in its new position
- x = t.canvasx(x) - @Priv.numeric_element(:drag,:x)
- y = t.canvasx(y) - @Priv.numeric_element(:drag,:y)
- t.dragimage_offset(x, y)
- t.dragimage_configure(:visible=>true)
- end
-end
-
-def randomLeave1(t, x, y)
- # This is called when I do ButtonPress-1 on Unix for some reason,
- # and buttonMode is undefined.
- return unless @Priv.exist?('buttonMode')
- case @Priv['buttonMode']
- when 'header'
- Tk::TreeCtrl::BindCallback.leave1(t, x, y)
- end
-end
-
-def randomRelease1(t, x, y)
- case @Priv['buttonMode']
- when 'resize', 'header'
- Tk::TreeCtrl::BindCallback.release1(t, x, y)
- when 'drag'
- Tk::TreeCtrl::BindCallback.autoScanCancel(t)
- t.dragimage_configure(:visible=>false)
- t.selection_modify('', @Priv[:drop])
- t[:cursor] = ''
- if @Priv[:drop] != ''
- randomDrop(t, @Priv[:drop], @Priv.list_element(:selection),
- @Priv[:drop, :pos])
- end
- end
- @Priv['buttonMode'] = ''
-end
-
-def randomDrop(t, target, src, pos)
- parentList = []
- case pos
- when 'lastchild'
- parent = target
- when 'prevsibling'
- parent = t.item_parent(target)
- when 'nextsibling'
- parent = t.item_parent(target)
- end
- src.each{|item|
- # Ignore any item whose ancestor is also selected
- ignore = false
- t.item_ancestors(item).each{|ancestor|
- if src.find{|val| val.to_s == ancestor.to_s}
- ignore = true
- break
- end
- }
- next if ignore
-
- # Update the old parent of this moved item later
- unless parentList.find{|val| val.to_s == item.to_s}
- parentList << t.item_parent(item)
- end
-
- # Add to target
- t.__send__("item_#{pos}", target, item)
-
- # Update text: parent
- t.item_element_configure(item, 'parent', 'e6', :text=>parent)
-
- # Update text: depth
- t.item_element_configure(item, 'depth', 'e6', :text=>t.depth(item))
-
- # Recursively update text: depth
- itemList = []
- item = t.item_firstchild(item)
- itemList << item if item != ''
-
- while item = itemList.pop
- t.item_element_configure(item, 'depth', 'e6', :text=>t.depth(item))
-
- item2 = t.item_nextsibling(item)
- itemList << item2 if item2 != ''
-
- item2 = t.item_firstchild(item)
- itemList << item2 if item2 != ''
- end
- }
-
- # Update items that lost some children
- parentList.each{|item|
- numChildren = t.item_numchildren(item)
- if numChildren == 0
- if $Version_1_1_OrLater
- t.item_configure(item, :button=>false)
- else # TreeCtrl 1.0
- t.item_hasbutton(item, false)
- end
- t.item_style_map(item, 'item', 's2', ['e3', 'e3'])
- else
- t.item_element_configure(item, 'item', 'e4', :text=>"(#{numChildren})")
- end
- }
-
- # Update the target that gained some children
- if t.item_style_set(parent, 0) != 's1'
- if $Version_1_1_OrLater
- t.item_configure(parent, :button=>true)
- else # TreeCtrl 1.0
- t.item_hasbutton(parent, true)
- end
- t.item_style_map(parent, 'item', 's1', ['e3', 'e3'])
- end
- numChildren = t.item_numchildren(parent)
- t.item_element_configure(parent, 'item', 'e4', :text=>"(#{numChildren})")
-end
-
-# Same as TreeCtrl::AutoScanCheck, but calls RandomMotion and
-# RandomAutoScanCheckAux
-def randomAutoScanCheck(t, x, y)
- x1, y1, x2, y2 = t.contentbox
- margin = t.winfo_pixels(t.scrollmargin)
- if x < x1 + margin || x >= x2 - margin || y < y1 + margin || y >= y2 - margin
- if ! @Priv.exist?(:autoscan, :afterId, t)
- if y >= y2 - margin
- t.yview(:scroll, 1, :units)
- delay = t.yscrolldelay
- elsif y < y1 + margin
- t.yview(:scroll, -1, :units)
- delay = t.yscrolldelay
- elsif x >= x2 - margin
- t.xview(:scroll, 1, :units)
- delay = t.xscrolldelay
- elsif x < x1 + margin
- t.xview(:scroll, -1, :units)
- delay = t.xscrolldelay
- end
- if @Priv.exist?(:autoscan, :scanning, t)
- delay = delay[1] if delay.kind_of?(Array)
- else
- delay = delay[0] if delay.kind_of?(Array)
- @Priv[:autoscan, :scanning, t] = true
- end
- case @Priv['buttonMode']
- when 'drag', 'marquee'
- randomMotion(t, x, y)
- end
- @Priv[:autoscan, :afterId, t] =
- Tk.after(delay, proc{ randomAutoScanCheckAux(t) })
- end
- return
- end
- Tk::TreeCtrl::BindCallback.autoScanCancel(t)
-end
-
-def randomAutoScanCheckAux(t)
- @Priv.unset(:autoscan, :afterId, t)
- x = t.winfo_pointerx - t.winfo_rootx
- y = t.winfo_pointery - t.winfo_rooty
- randomAutoScanCheck(t, x, y)
-end
-
-#
-# Demo: random N items, button images
-#
-def demoRandom2(t)
- demoRandom(t)
-
- init_pics('mac-*')
-
- t.configure(:openbuttonimage=>@images['mac-collapse'],
- :closedbuttonimage=>@images['mac-expand'],
- :showlines=>false)
-end
diff --git a/ext/tk/sample/tkextlib/treectrl/readme.txt b/ext/tk/sample/tkextlib/treectrl/readme.txt
deleted file mode 100644
index 9f26ac069c..0000000000
--- a/ext/tk/sample/tkextlib/treectrl/readme.txt
+++ /dev/null
@@ -1,2 +0,0 @@
-The scripts and image files in this directory are based on demo files
-of Tcl/Tk's TreeCtrl extention.
diff --git a/ext/tk/sample/tkextlib/treectrl/www-options.rb b/ext/tk/sample/tkextlib/treectrl/www-options.rb
deleted file mode 100644
index efa55ca06c..0000000000
--- a/ext/tk/sample/tkextlib/treectrl/www-options.rb
+++ /dev/null
@@ -1,303 +0,0 @@
-def demoInternetOptions (t)
- @Option = TkVarAccess.new_hash('::Option')
-
- height = t.font.metrics(:linespace) + 2
- height = 18 if height < 18
- t.configure(:showroot=>false, :showbuttons=>false, :showlines=>false,
- :itemheight=>height, :selectmode=>:browse)
-
- init_pics('internet-*')
-
- if $HasColumnCreate
- t.column_create(:text=>'Internet Options')
- else
- t.column_configure(0, :text=>'Internet Options')
- end
-
- t.state_define('check')
- t.state_define('radio')
- t.state_define('on')
-
- t.element_create('e1', :image, :image=>[
- @images['internet-check-on'], ['check', 'on'],
- @images['internet-check-off'], ['check'],
- @images['internet-radio-on'], ['radio', 'on'],
- @images['internet-radio-off'], ['radio']
- ])
- t.element_create('e2', :text,
- :fill=>[@SystemHighlightText, ['selected', 'focus']])
- t.element_create('e3', :rect, :showfocus=>true,
- :fill=>[@SystemHighlight, ['selected', 'focus']])
-
- s = t.style_create('s1')
- t.style_elements(s, ['e3', 'e1', 'e2'])
- t.style_layout(s, 'e1', :padx=>[0,4], :expand=>:ns)
- t.style_layout(s, 'e2', :expand=>:ns)
- t.style_layout(s, 'e3', :union=>['e2'], :iexpand=>:ns, :ipadx=>2)
-
- parentList = [:root, '', '', '', '', '', '']
- parent = :root
- [
- [0, :print, "Printing", "", ""],
- [1, :off, "Print background colors and images", "o1", ""],
- [0, :search, "Search from Address bar", "", ""],
- [1, :search, "When searching", "", ""],
- [2, :off, "Display results, and go to the most likely sites",
- "o2", "r1"],
- [2, :off, "Do not search from the Address bar", "o3", "r1"],
- [2, :off, "Just display the results in the main window",
- "o4", "r1"],
- [2, :on, "Just go to the most likely site", "o5", "r1"],
- [0, :security, "Security", "", ""],
- [1, :on, "Check for publisher's certificate revocation", "o5", ""],
- [1, :off, "Check for server certificate revocation (requires restart)",
- "o6", ""]
- ].each{|depth, setting, text, option, group|
- item = t.item_create()
- t.item_style_set(item, 0, 's1')
- t.item_element_configure(item, 0, 'e2', :text=>text)
- @Option[:option, item] = option
- @Option[:group, item] = group
- if setting == :on || setting == :off
- @Option[:setting, item] = setting
- if group == ''
- t.item_state_set(item, 'check')
- if setting == :on
- t.item_state_set(item, 'on')
- end
- else
- if setting == :on
- @Option[:current, group] = item
- t.item_state_set(item, 'on')
- end
- t.item_state_set(item, 'radio')
- end
- else
- t.item_element_configure(item, 0, 'e1',
- :image=>@images["internet-#{setting}"])
- end
- t.item_lastchild(parentList[depth], item)
- depth += 1
- parentList[depth] = item
- }
-
- treeCtrlOption = TkBindTag.new
- treeCtrlOption.bind('Double-ButtonPress-1', proc{|w, x, y|
- Tk::TreeCtrl::BindCallback.doubleButton1(w, x, y)
- }, '%W %x %y')
- treeCtrlOption.bind('ButtonPress-1', proc{|w, x, y|
- optionButton1(w, x, y)
- Tk.callback_break
- }, '%W %x %y')
- treeCtrlOption.bind('Button1-Motion', proc{|w, x, y|
- optionMotion1(w, x, y)
- Tk.callback_break
- }, '%W %x %y')
- treeCtrlOption.bind('Button1-Leave', proc{|w, x, y|
- optionLeave1(w, x, y)
- Tk.callback_break
- }, '%W %x %y')
- treeCtrlOption.bind('ButtonRelease-1', proc{|w, x, y|
- optionRelease1(w, x, y)
- Tk.callback_break
- }, '%W %x %y')
-
- t.bindtags = [
- t, treeCtrlOption, Tk::TreeCtrl, t.winfo_toplevel, TkBindTag::ALL
- ]
-end
-
-def optionButton1(w, x, y)
- w.set_focus
- id = w.identify(x, y)
- if id[0] == 'header'
- Tk::TreeCtrl::BindCallback.buttonPress1(w, x, y)
- elsif id.empty?
- @Priv['buttonMode'] = ''
- else
- @Priv['buttonMode'] = ''
- item = id[1]
- w.selection_modify(item, :all)
- w.activate(item)
- return if @Option[:option, item] == ''
- group = @Option[:group, item]
- if group == ''
- # a checkbutton
- w.item_state_set(item, '~on')
- if @Option[:setting, item] == 'on'
- setting = :off
- else
- setting = :on
- end
- @Option[:setting, item] = setting
- else
- # a radiobutton
- current = @Option[:current, group]
- return if current == item.to_s
- w.item_state_set(current, '!on')
- w.item_state_set(item, 'on')
- @Option[:setting, item] = :on
- @Option[:current, group] = item
- end
- end
-end
-
-# Alternate implementation that doesn't rely on run-time styles
-def demoInternetOptions_2(t)
- height = t.font.metrics(:linespace) + 2
- height = 18 if height < 18
- t.configure(:showroot=>false, :showbuttons=>false, :showlines=>false,
- :itemheight=>height, :selectmode=>:browse)
-
- init_pics('internet-*')
-
- t.column_configure(0, :text=>'Internet Options')
-
- t.element_create('e1', :image)
- t.element_create('e2', :text,
- :fill=>[@SystemHighlightText, ['selected', 'focus']])
- t.element_create('e3', :rect, :showfocus=>true,
- :fill=>[@SystemHighlight, ['selected', 'focus']])
-
- s = t.style_create('s1')
- t.style_elements('s1', ['e3', 'e1', 'e2'])
- t.style_layout(s, 'e1', :padx=>[0,4], :expand=>:ns)
- t.style_layout(s, 'e2', :expand=>:ns)
- t.style_layout(s, 'e3', :union=>['e2'], :iexpand=>:ns, :ipadx=>2)
-
- parentList = [:root, '', '', '', '', '', '']
- parent = :root
- [
- [0, :print, "Printing", "", ""],
- [1, :off, "Print background colors and images", "o1", ""],
- [0, :search, "Search from Address bar", "", ""],
- [1, :search, "When searching", "", ""],
- [2, :off, "Display results, and go to the most likely sites",
- "o2", "r1"],
- [2, :off, "Do not search from the Address bar", "o3", "r1"],
- [2, :off, "Just display the results in the main window",
- "o4", "r1"],
- [2, :on, "Just go to the most likely site", "o5", "r1"],
- [0, :security, "Security", "", ""],
- [1, :on, "Check for publisher's certificate revocation", "o5", ""],
- [1, :off, "Check for server certificate revocation (requires restart)",
- "o6", ""]
- ].each{|depth, setting, text, option, group|
- item = t.item_create()
- t.item_style_set(item, 0, 's1')
- t.item_element_configure(item, 0, 'e2', :text=>text)
- @Option[:option, item] = option
- @Option[:group, item] = group
- if setting == :on || setting == :off
- @Option[:setting, item] = setting
- if group == ''
- img = @images["internet-check-#{setting}"]
- t.item_element_configure(item, 0, 'e1', :image=>img)
- else
- if setting == :on
- @Option[:current, group] = item
- end
- img = @images["internet-radio-#{setting}"]
- t.item_element_configure(item, 0, 'e1', :image=>img)
- end
- else
- t.item_element_configure(item, 0, 'e1',
- :image=>@images["internet-#{setting}"])
- end
- t.item_lastchild(parentList[depth], item)
- depth += 1
- parentList[depth] = item
- }
-
- treeCtrlOption = TkBindTag.new
- treeCtrlOption.bind('Double-ButtonPress-1', proc{|w, x, y|
- Tk::TreeCtrl::BindCallback.doubleButton1(w, x, y)
- }, '%W %x %y')
- treeCtrlOption.bind('ButtonPress-1', proc{|w, x, y|
- optionButton1(w, x, y)
- Tk.callback_break
- }, '%W %x %y')
- treeCtrlOption.bind('Button1-Motion', proc{|w, x, y|
- optionMotion1(w, x, y)
- Tk.callback_break
- }, '%W %x %y')
- treeCtrlOption.bind('Button1-Leave', proc{|w, x, y|
- optionLeave1(w, x, y)
- Tk.callback_break
- }, '%W %x %y')
- treeCtrlOption.bind('ButtonRelease-1', proc{|w, x, y|
- optionRelease1(w, x, y)
- Tk.callback_break
- }, '%W %x %y')
-
- t.bindtags = [
- t, treeCtrlOption, Tk::TreeCtrl, t.winfo_toplevel, TkBindTag::ALL
- ]
-end
-
-def optionButton1_2(w, x, y)
- w.set_focus
- id = w.identify(x, y)
- if id[0] == 'header'
- Tk::TreeCtrl::BindCallback.buttonPress1(w, x, y)
- elsif id.empty?
- @Priv['buttonMode'] = ''
- else
- @Priv['buttonMode'] = ''
- item = id[1]
- w.selection_modify(item, :all)
- w.activate(item)
- return if @Option[:option, item] == ''
- group = @Option[:group, item]
- if group == ''
- # a checkbutton
- if @Option[:setting, item] == 'on'
- setting = :off
- else
- setting = :on
- end
- w.item_element_configure(item, 0, 'e1',
- :image=>@images["internet-check-#{setting}"])
- @Option[:setting, item] = setting
- else
- # a radiobutton
- current = @Option[:current, group]
- return if current == item.to_s
- w.item_element_configure(current, 0, 'e1',
- :image=>@images["internet-radio-off"])
- w.item_element_configure(item, 0, 'e1',
- :image=>@images["internet-radio-on"])
- @Option[:setting, item] = :on
- @Option[:current, group] = item
- end
- end
-end
-
-def optionMotion1(w, x, y)
- case @Priv['buttonMode']
- when 'resize', 'header'
- Tk::TreeCtrl::BindCallback.motion1(w, x, y)
- end
-end
-
-def optionLeave1(w, x, y)
- # This is called when I do ButtonPress-1 on Unix for some reason,
- # and buttonMode is undefined.
- begin
- mode = @Priv['buttonMode']
- rescue
- else
- case mode
- when 'header'
- t.column_configure(@Priv['column'], :sunken=>false)
- end
- end
-end
-
-def optionRelease1(w, x, y)
- case @Priv['buttonMode']
- when 'resize', 'header'
- Tk::TreeCtrl::BindCallback.release1(w, x, y)
- end
- @Priv['buttonMode'] = ''
-end
diff --git a/ext/tk/sample/tkextlib/vu/dial_demo.rb b/ext/tk/sample/tkextlib/vu/dial.rb
index 09bd3e9186..09bd3e9186 100644
--- a/ext/tk/sample/tkextlib/vu/dial_demo.rb
+++ b/ext/tk/sample/tkextlib/vu/dial.rb
diff --git a/ext/tk/sample/tkextlib/vu/vu_demo.rb b/ext/tk/sample/tkextlib/vu/vu.rb
index d078ae16f2..d078ae16f2 100644
--- a/ext/tk/sample/tkextlib/vu/vu_demo.rb
+++ b/ext/tk/sample/tkextlib/vu/vu.rb
diff --git a/ext/tk/sample/tkrttimer.rb b/ext/tk/sample/tkrttimer.rb
deleted file mode 100644
index 531f4a8d5a..0000000000
--- a/ext/tk/sample/tkrttimer.rb
+++ /dev/null
@@ -1,68 +0,0 @@
-#!/usr/bin/env ruby
-# This script is a re-implementation of tktimer.rb with TkTimer(TkAfter) class.
-
-require "tk"
-
-root = TkRoot.new(:title=>'realtime timer sample')
-
-f1 = TkFrame.new(:borderwidth=>2, :relief=>:ridge)
-f1.pack(:side=>:bottom, :fill=>:both)
-TkLabel.new(f1, :text=>'use TkTimer (TkAfter) class').pack(:anchor=>:center)
-label1 = TkLabel.new(:parent=>f1, :relief=>:raised,
- :width=>10).pack(:fill=>:both)
-
-f2 = TkFrame.new(:borderwidth=>2, :relief=>:ridge)
-f2.pack(:side=>:bottom, :fill=>:both)
-TkLabel.new(f2, :text=>'use TkRTTimer class').pack
-label2 = TkLabel.new(:parent=>f2, :relief=>:raised,
- :width=>10).pack(:fill=>:both)
-
-TkLabel.new(:text=>'Interval setting of each timer is 10 ms.',
- :padx=>10, :pady=>5).pack
-
-# define the procedure repeated by the TkTimer object
-tick = proc{|aobj| #<== TkTimer object
- cnt = aobj.return_value + 1 # return_value keeps a result of the last proc
- label = aobj.current_args[0]
- label.text format("%d.%02d", *(cnt.divmod(100)))
- cnt #==> return value is kept by TkTimer object
- # (so, can be send to the next repeat-proc)
-}
-
-timer1 = TkTimer.new(10, -1, [tick, label1]) # 10 ms interval
-timer2 = TkRTTimer.new(10, -1, [tick, label2]) # 10 ms interval
-
-timer1.start(0, proc{ label1.text('0.00'); 0 })
-timer2.start(0, proc{ label2.text('0.00'); 0 })
-
-b_start = TkButton.new(:text=>'Start', :state=>:disabled) {
- pack(:side=>:left, :fill=>:both, :expand=>true)
-}
-
-b_stop = TkButton.new(:text=>'Stop', :state=>:normal) {
- pack('side'=>'left', 'fill'=>'both', 'expand'=>'yes')
-}
-
-b_start.command {
- timer1.continue
- timer2.continue
- b_stop.state(:normal)
- b_start.state(:disabled)
-}
-
-b_stop.command {
- timer1.stop
- timer2.stop
- b_start.state(:normal)
- b_stop.state(:disabled)
-}
-
-TkButton.new(:text=>'Reset', :state=>:normal) {
- command { timer1.reset; timer2.reset }
- pack(:side=>:right, :fill=>:both, :expand=>:yes)
-}
-
-ev_quit = TkVirtualEvent.new('Control-c', 'Control-q')
-Tk.root.bind(ev_quit, proc{Tk.exit}).focus
-
-Tk.mainloop
diff --git a/ext/tk/sample/tktextio.rb b/ext/tk/sample/tktextio.rb
deleted file mode 100644
index cb59c2d9d6..0000000000
--- a/ext/tk/sample/tktextio.rb
+++ /dev/null
@@ -1,603 +0,0 @@
-#!/usr/bin/env ruby
-#
-# sample class of handling I/O stream on a TkText widget
-# by Hidetoshi NAGAI
-#
-# NOTE: TkTextIO supports 'character' (not 'byte') access only.
-# So, for example, TkTextIO#getc returns a character, TkTextIO#pos
-# means the character position, TkTextIO#read(size) counts by
-# characters, and so on.
-# Of course, it is available to make TkTextIO class to suuport
-# 'byte' access. However, it may break multi-byte characters.
-# and then, displayed string on the text widget may be garbled.
-# I think that it is not good on the supposed situation of using
-# TkTextIO.
-#
-require 'tk'
-
-class TkTextIO < TkText
- def create_self(keys)
- mode = nil
- ovwt = false
- text = nil
- wrap = 'char'
- show = :pos
-
- if keys.kind_of?(Hash)
- mode = keys.delete('mode')
- ovwt = keys.delete('overwrite')
- text = keys.delete('text')
- show = keys.delete('show') if keys.has_key?('show')
- wrap = keys.delete('wrap') || 'char'
- end
-
- super(keys)
-
- self['wrap'] = wrap
- insert('1.0', text)
-
- @txtpos = TkTextMark.new(self, '1.0')
- @txtpos.gravity = :left
-
- self.show_mode = show
-
- @sync = true
- @overwrite = (ovwt)? true: false
-
- @lineno = 0
- @line_offset = 0
- @count_var = TkVariable.new
-
- @open = {:r => true, :w => true} # default is 'r+'
-
- case mode
- when 'r'
- @open[:r] = true; @open[:w] = nil
-
- when 'r+'
- @open[:r] = true; @open[:w] = true
-
- when 'w'
- @open[:r] = nil; @open[:w] = true
- self.value=''
-
- when 'w+'
- @open[:r] = true; @open[:w] = true
- self.value=''
-
- when 'a'
- @open[:r] = nil; @open[:w] = true
- @txtpos = TkTextMark.new(self, 'end - 1 char')
- @txtpos.gravity = :right
-
- when 'a+'
- @open[:r] = true; @open[:w] = true
- @txtpos = TkTextMark.new(self, 'end - 1 char')
- @txtpos.gravity = :right
- end
- end
-
- def <<(obj)
- _write(obj)
- self
- end
-
- def binmode
- self
- end
-
- def clone
- fail NotImplementedError, 'cannot clone TkTextIO'
- end
- def dup
- fail NotImplementedError, 'cannot duplicate TkTextIO'
- end
-
- def close
- close_read
- close_write
- nil
- end
- def close_read
- @open[:r] = false if @open[:r]
- nil
- end
- def close_write
- @open[:w] = false if @opne[:w]
- nil
- end
-
- def closed?
- close_read? && close_write?
- end
- def closed_read?
- !@open[:r]
- end
- def closed_write?
- !@open[:w]
- end
-
- def _check_readable
- fail IOError, "not opened for reading" if @open[:r].nil?
- fail IOError, "closed stream" if !@open[:r]
- end
- def _check_writable
- fail IOError, "not opened for writing" if @open[:w].nil?
- fail IOError, "closed stream" if !@open[:w]
- end
- private :_check_readable, :_check_writable
-
- def each_line(rs = $/)
- _check_readable
- while(s = gets)
- yield(s)
- end
- self
- end
- alias each each_line
-
- def each_char
- _check_readable
- while(c = getc)
- yield(c)
- end
- self
- end
- alias each_byte each_char
-
- def eof?
- compare(@txtpos, '==', 'end - 1 char')
- end
- alias eof eof?
-
- def fcntl(*args)
- fail NotImplementedError, 'fcntl is not implemented on TkTextIO'
- end
-
- def fsync
- 0
- end
-
- def fileno
- nil
- end
-
- def flush
- Tk.update if @open[:w] && @sync
- self
- end
-
- def getc
- _check_readable
- return nil if eof?
- c = get(@txtpos)
- @txtpos.set(@txtpos + '1 char')
- _see_pos
- c
- end
-
- def gets(rs = $/)
- _check_readable
- return nil if eof?
- _readline(rs)
- end
-
- def ioctrl(*args)
- fail NotImplementedError, 'iocntl is not implemented on TkTextIO'
- end
-
- def isatty
- false
- end
- def tty?
- false
- end
-
- def lineno
- @lineno + @line_offset
- end
-
- def lineno=(num)
- @line_offset = num - @lineno
- num
- end
-
- def overwrite?
- @overwrite
- end
-
- def overwrite=(ovwt)
- @overwrite = (ovwt)? true: false
- end
-
- def pid
- nil
- end
-
- def index_pos
- index(@txtpos)
- end
- alias tell_index index_pos
-
- def index_pos=(idx)
- @txtpos.set(idx)
- @txtpos.set('end - 1 char') if compare(@txtpos, '>=', :end)
- _see_pos
- idx
- end
-
- def pos
- s = get('1.0', @txtpos)
- number(tk_call('string', 'length', s))
- end
- alias tell pos
-
- def pos=(idx)
- # @txtpos.set((idx.kind_of?(Numeric))? "1.0 + #{idx} char": idx)
- seek(idx, IO::SEEK_SET)
- idx
- end
-
- def pos_gravity
- @txtpos.gravity
- end
-
- def pos_gravity=(side)
- @txtpos.gravity = side
- side
- end
-
- def print(arg=$_, *args)
- _check_writable
- args.unshift(arg)
- args.map!{|val| (val == nil)? 'nil': val.to_s }
- str = args.join($,)
- str << $\ if $\
- _write(str)
- nil
- end
- def printf(*args)
- _check_writable
- _write(sprintf(*args))
- nil
- end
-
- def putc(c)
- _check_writable
- c = c.chr if c.kind_of?(Fixnum)
- _write(c)
- c
- end
-
- def puts(*args)
- _check_writable
- if args.empty?
- _write("\n")
- return nil
- end
- args.each{|arg|
- if arg == nil
- _write("nil\n")
- elsif arg.kind_of?(Array)
- puts(*arg)
- elsif arg.kind_of?(String)
- _write(arg.chomp)
- _write("\n")
- else
- begin
- arg = arg.to_ary
- puts(*arg)
- rescue
- puts(arg.to_s)
- end
- end
- }
- nil
- end
-
- def _read(len)
- epos = @txtpos + "#{len} char"
- s = get(@txtpos, epos)
- @txtpos.set(epos)
- @txtpos.set('end - 1 char') if compare(@txtpos, '>=', :end)
- _see_pos
- s
- end
- private :_read
-
- def read(len=nil, buf=nil)
- _check_readable
- if len
- return "" if len == 0
- return nil if eof?
- s = _read(len)
- else
- s = get(@txtpos, 'end - 1 char')
- @txtpos.set('end - 1 char')
- _see_pos
- end
- buf.replace(s) if buf.kind_of?(String)
- s
- end
-
- def readchar
- _check_readable
- fail EOFError if eof?
- c = get(@txtpos)
- @txtpos.set(@txtpos + '1 char')
- _see_pos
- c
- end
-
- def _readline(rs = $/)
- if rs == nil
- s = get(@txtpos, 'end - 1 char')
- @txtpos.set('end - 1 char')
- elsif rs == ''
- idx = tksearch_with_count([:regexp], @count_var,
- "\n(\n)+", @txtpos, 'end - 1 char')
- if idx
- s = get(@txtpos, idx) << "\n"
- @txtpos.set("#{idx} + #{@count_var.value} char")
- @txtpos.set('end - 1 char') if compare(@txtpos, '>=', :end)
- else
- s = get(@txtpos, 'end - 1 char')
- @txtpos.set('end - 1 char')
- end
- else
- idx = tksearch_with_count(@count_var, rs, @txtpos, 'end - 1 char')
- if idx
- s = get(@txtpos, "#{idx} + #{@count_var.value} char")
- @txtpos.set("#{idx} + #{@count_var.value} char")
- @txtpos.set('end - 1 char') if compare(@txtpos, '>=', :end)
- else
- s = get(@txtpos, 'end - 1 char')
- @txtpos.set('end - 1 char')
- end
- end
-
- _see_pos
- @lineno += 1
- $_ = s
- end
- private :_readline
-
- def readline(rs = $/)
- _check_readable
- fail EOFError if eof?
- _readline(rs)
- end
-
- def readlines(rs = $/)
- _check_readable
- lines = []
- until(eof?)
- lines << _readline(rs)
- end
- $_ = nil
- lines
- end
-
- def readpartial(maxlen, buf=nil)
- _check_readable
- s = _read(maxlen)
- buf.replace(s) if buf.kind_of?(String)
- s
- end
-
- def reopen(*args)
- fail NotImplementedError, 'reopen is not implemented on TkTextIO'
- end
-
- def rewind
- @txtpos.set('1.0')
- _see_pos
- @lineno = 0
- @line_offset = 0
- self
- end
-
- def seek(offset, whence=IO::SEEK_SET)
- case whence
- when IO::SEEK_SET
- offset = "1.0 + #{offset} char" if offset.kind_of?(Numeric)
- @txtpos.set(offset)
-
- when IO::SEEK_CUR
- offset = "#{offset} char" if offset.kind_of?(Numeric)
- @txtpos.set(@txtpos + offset)
-
- when IO::SEEK_END
- offset = "#{offset} char" if offset.kind_of?(Numeric)
- @txtpos.set("end - 1 char + #{offset}")
-
- else
- fail Errno::EINVAL, 'invalid whence argument'
- end
-
- @txtpos.set('end - 1 char') if compare(@txtpos, '>=', :end)
- _see_pos
-
- 0
- end
- alias sysseek seek
-
- def _see_pos
- see(@show) if @show
- end
- private :_see_pos
-
- def show_mode
- (@show == @txtpos)? :pos : @show
- end
-
- def show_mode=(mode)
- # define show mode when file position is changed.
- # mode == :pos or "pos" or true :: see current file position.
- # mode == :insert or "insert" :: see insert cursor position.
- # mode == nil or false :: do nothing
- # else see 'mode' position ('mode' should be text index or mark)
- case mode
- when :pos, 'pos', true
- @show = @txtpos
- when :insert, 'insert'
- @show = :insert
- when nil, false
- @show = false
- else
- begin
- index(mode)
- rescue
- fail ArgumentError, 'invalid show-position'
- end
- @show = mode
- end
-
- _see_pos
-
- mode
- end
-
- def stat
- fail NotImplementedError, 'stat is not implemented on TkTextIO'
- end
-
- def sync
- @sync
- end
-
- def sync=(mode)
- @sync = mode
- end
-
- def sysread(len, buf=nil)
- _check_readable
- fail EOFError if eof?
- s = _read(len)
- buf.replace(s) if buf.kind_of?(String)
- s
- end
-
- def syswrite(obj)
- _write(obj)
- end
-
- def to_io
- self
- end
-
- def trancate(len)
- delete("1.0 + #{len} char", :end)
- 0
- end
-
- def ungetc(c)
- _check_readable
- c = c.chr if c.kind_of?(Fixnum)
- if compare(@txtpos, '>', '1.0')
- @txtpos.set(@txtpos - '1 char')
- delete(@txtpos)
- insert(@txtpos, tk_call('string', 'range', c, 0, 1))
- @txtpos.set(@txtpos - '1 char') if @txtpos.gravity == 'right'
- _see_pos
- else
- fail IOError, 'cannot ungetc at head of stream'
- end
- nil
- end
-
- def _write(obj)
- s = _get_eval_string(obj)
- n = number(tk_call('string', 'length', s))
- delete(@txtpos, @txtpos + "#{n} char") if @overwrite
- self.insert(@txtpos, s)
- @txtpos.set(@txtpos + "#{n} char")
- @txtpos.set('end - 1 char') if compare(@txtpos, '>=', :end)
- _see_pos
- Tk.update if @sync
- n
- end
- private :_write
-
- def write(obj)
- _check_writable
- _write(obj)
- end
-end
-
-####################
-# TEST
-####################
-if __FILE__ == $0
- f = TkFrame.new.pack
- tio = TkTextIO.new(f, :show=>:pos,
- :text=>">>> This is an initial text line. <<<\n\n"){
- yscrollbar(TkScrollbar.new(f).pack(:side=>:right, :fill=>:y))
- pack(:side=>:left, :fill=>:both, :expand=>true)
- }
-
- $stdin = tio
- $stdout = tio
- $stderr = tio
-
- STDOUT.print("\n========= TkTextIO#gets for inital text ========\n\n")
-
- while(s = gets)
- STDOUT.print(s)
- end
-
- STDOUT.print("\n============ put strings to TkTextIO ===========\n\n")
-
- puts "On this sample, a text widget works as if it is a I/O stream."
- puts "Please see the code."
- puts
- printf("printf message: %d %X\n", 123456, 255)
- puts
- printf("(output by 'p' method) This TkTextIO object is ...\n")
- p tio
- print(" [ Current wrap mode of this object is 'char'. ]\n")
- puts
- warn("This is a warning message generated by 'warn' method.")
- puts
- puts "current show_mode is #{tio.show_mode}."
- if tio.show_mode == :pos
- puts "So, you can see the current file position on this text widget."
- else
- puts "So, you can see the position '#{tio.show_mode}' on this text widget."
- end
- print("Please scroll up this text widget to see the head of lines.\n")
- print("---------------------------------------------------------\n")
-
- STDOUT.print("\n=============== TkTextIO#readlines =============\n\n")
-
- tio.seek(0)
- lines = readlines
- STDOUT.puts(lines.inspect)
-
- STDOUT.print("\n================== TkTextIO#each ===============\n\n")
-
- tio.rewind
- tio.each{|line| STDOUT.printf("%2d: %s\n", tio.lineno, line.chomp)}
-
- STDOUT.print("\n================================================\n\n")
-
- STDOUT.print("\n========= reverse order (seek by lines) ========\n\n")
-
- tio.seek(-1, IO::SEEK_END)
- begin
- begin
- tio.seek(:linestart, IO::SEEK_CUR)
- rescue
- # maybe use old version of tk/textmark.rb
- tio.seek('0 char linestart', IO::SEEK_CUR)
- end
- STDOUT.print(gets)
- tio.seek('-1 char linestart -1 char', IO::SEEK_CUR)
- end while(tio.pos > 0)
-
- STDOUT.print("\n================================================\n\n")
-
- tio.seek(0, IO::SEEK_END)
-
- Tk.mainloop
-end
diff --git a/ext/tk/sample/tktree.rb b/ext/tk/sample/tktree.rb
index 56b7211c88..d16d3344bd 100644
--- a/ext/tk/sample/tktree.rb
+++ b/ext/tk/sample/tktree.rb
@@ -25,7 +25,7 @@ class TkTree < TkCanvas
end
begin
tk_call('::tktree::treecreate', *args)
- rescue NameError, RuntimeError
+ rescue NameError
Tk.load_tclscript(TkTree::TCL_SCRIPT_PATH)
tk_call('::tktree::treecreate', *args)
end
diff --git a/ext/tk/tkutil.c b/ext/tk/tkutil.c
index f191eb1627..04d276cca2 100644
--- a/ext/tk/tkutil.c
+++ b/ext/tk/tkutil.c
@@ -8,8 +8,6 @@
************************************************/
-#define TKUTIL_RELEASE_DATE "2005-07-28"
-
#include "ruby.h"
#include "rubysig.h"
#include "st.h"
@@ -31,15 +29,12 @@ static ID ID_toUTF8;
static ID ID_fromUTF8;
static ID ID_path;
static ID ID_at_path;
-static ID ID_at_enc;
static ID ID_to_eval;
static ID ID_to_s;
static ID ID_source;
static ID ID_downcase;
static ID ID_install_cmd;
static ID ID_merge_tklist;
-static ID ID_encoding;
-static ID ID_encoding_system;
static ID ID_call;
static ID ID_SUBST_INFO;
@@ -202,12 +197,24 @@ fromUTF8_toDefaultEnc(str, self)
return tk_fromUTF8(1, argv, self);
}
+
+static void
+hash_check(err)
+ int err;
+{
+ if (err) {
+ rb_raise(rb_eRuntimeError, "hash modified");
+ }
+}
+
static int
-to_strkey(key, value, hash)
+to_strkey(key, value, hash, err)
VALUE key;
VALUE value;
VALUE hash;
+ int err;
{
+ hash_check(err);
if (key == Qundef) return ST_CONTINUE;
rb_hash_aset(hash, rb_funcall(key, ID_to_s, 0, 0), value);
return ST_CHECK;
@@ -227,40 +234,19 @@ tk_symbolkey2str(self, keys)
}
static VALUE get_eval_string_core _((VALUE, VALUE, VALUE));
-static VALUE ary2list _((VALUE, VALUE, VALUE));
-static VALUE ary2list2 _((VALUE, VALUE, VALUE));
+static VALUE ary2list _((VALUE, VALUE));
+static VALUE ary2list2 _((VALUE, VALUE));
static VALUE hash2list _((VALUE, VALUE));
-static VALUE hash2list_enc _((VALUE, VALUE));
static VALUE hash2kv _((VALUE, VALUE, VALUE));
-static VALUE hash2kv_enc _((VALUE, VALUE, VALUE));
static VALUE
-ary2list(ary, enc_flag, self)
+ary2list(ary, self)
VALUE ary;
- VALUE enc_flag;
VALUE self;
{
- int idx, idx2, size, size2, req_chk_flag;
- volatile VALUE val, val2, str_val;
+ int idx, idx2, size, size2;
+ volatile VALUE val, val2;
volatile VALUE dst;
- volatile VALUE sys_enc, dst_enc, str_enc;
-
- sys_enc = rb_funcall(cTclTkLib, ID_encoding, 0, 0);
- if (NIL_P(sys_enc)) {
- sys_enc = rb_funcall(cTclTkLib, ID_encoding_system, 0, 0);
- sys_enc = rb_funcall(sys_enc, ID_to_s, 0, 0);
- }
-
- if NIL_P(enc_flag) {
- dst_enc = sys_enc;
- req_chk_flag = 1;
- } else if (TYPE(enc_flag) == T_TRUE || TYPE(enc_flag) == T_FALSE) {
- dst_enc = enc_flag;
- req_chk_flag = 0;
- } else {
- dst_enc = rb_funcall(enc_flag, ID_to_s, 0, 0);
- req_chk_flag = 0;
- }
/* size = RARRAY(ary)->len; */
size = 0;
@@ -276,69 +262,31 @@ ary2list(ary, enc_flag, self)
RARRAY(dst)->len = 0;
for(idx = 0; idx < RARRAY(ary)->len; idx++) {
val = RARRAY(ary)->ptr[idx];
- str_val = Qnil;
switch(TYPE(val)) {
case T_ARRAY:
- str_val = ary2list(val, enc_flag, self);
- RARRAY(dst)->ptr[RARRAY(dst)->len++] = str_val;
-
- if (req_chk_flag) {
- str_enc = rb_ivar_get(str_val, ID_at_enc);
- if (!NIL_P(str_enc)) {
- str_enc = rb_funcall(str_enc, ID_to_s, 0, 0);
- } else {
- str_enc = sys_enc;
- }
- if (!rb_str_cmp(str_enc, dst_enc)) {
- dst_enc = Qtrue;
- req_chk_flag = 0;
- }
- }
-
+ RARRAY(dst)->ptr[RARRAY(dst)->len++] = ary2list(val, self);
break;
case T_HASH:
/* RARRAY(dst)->ptr[RARRAY(dst)->len++] = hash2list(val, self); */
- if (RTEST(enc_flag)) {
- val = hash2kv_enc(val, Qnil, self);
- } else {
- val = hash2kv(val, Qnil, self);
- }
+ val = hash2kv(val, Qnil, self);
size2 = RARRAY(val)->len;
for(idx2 = 0; idx2 < size2; idx2++) {
val2 = RARRAY(val)->ptr[idx2];
switch(TYPE(val2)) {
case T_ARRAY:
- str_val = ary2list(val2, enc_flag, self);
- RARRAY(dst)->ptr[RARRAY(dst)->len++] = str_val;
+ RARRAY(dst)->ptr[RARRAY(dst)->len++]
+ = ary2list(val2, self);
break;
case T_HASH:
- if (RTEST(enc_flag)) {
- str_val = hash2list_enc(val2, self);
- } else {
- str_val = hash2list(val2, self);
- }
- RARRAY(dst)->ptr[RARRAY(dst)->len++] = str_val;
- break;
+ RARRAY(dst)->ptr[RARRAY(dst)->len++]
+ = hash2list(val2, self);
default:
if (val2 != TK_None) {
- str_val = get_eval_string_core(val2, enc_flag, self);
- RARRAY(dst)->ptr[RARRAY(dst)->len++] = str_val;
- }
- }
-
- if (req_chk_flag) {
- str_enc = rb_ivar_get(str_val, ID_at_enc);
- if (!NIL_P(str_enc)) {
- str_enc = rb_funcall(str_enc, ID_to_s, 0, 0);
- } else {
- str_enc = sys_enc;
- }
- if (!rb_str_cmp(str_enc, dst_enc)) {
- dst_enc = Qtrue;
- req_chk_flag = 0;
+ RARRAY(dst)->ptr[RARRAY(dst)->len++]
+ = get_eval_string_core(val2, Qnil, self);
}
}
}
@@ -346,140 +294,45 @@ ary2list(ary, enc_flag, self)
default:
if (val != TK_None) {
- str_val = get_eval_string_core(val, enc_flag, self);
- RARRAY(dst)->ptr[RARRAY(dst)->len++] = str_val;
-
- if (req_chk_flag) {
- str_enc = rb_ivar_get(str_val, ID_at_enc);
- if (!NIL_P(str_enc)) {
- str_enc = rb_funcall(str_enc, ID_to_s, 0, 0);
- } else {
- str_enc = sys_enc;
- }
- if (!rb_str_cmp(str_enc, dst_enc)) {
- dst_enc = Qtrue;
- req_chk_flag = 0;
- }
- }
+ RARRAY(dst)->ptr[RARRAY(dst)->len++]
+ = get_eval_string_core(val, Qnil, self);
}
}
}
-
- if (RTEST(dst_enc) && !NIL_P(sys_enc)) {
- for(idx = 0; idx < RARRAY(dst)->len; idx++) {
- str_val = RARRAY(dst)->ptr[idx];
- if (rb_respond_to(self, ID_toUTF8)) {
- str_val = rb_funcall(self, ID_toUTF8, 1, str_val);
- } else {
- str_val = rb_funcall(cTclTkLib, ID_toUTF8, 1, str_val);
- }
- RARRAY(dst)->ptr[idx] = str_val;
- }
- val = rb_apply(cTclTkLib, ID_merge_tklist, dst);
- if (TYPE(dst_enc) == T_STRING) {
- val = rb_funcall(cTclTkLib, ID_fromUTF8, 2, val, dst_enc);
- rb_ivar_set(val, ID_at_enc, dst_enc);
- } else {
- rb_ivar_set(val, ID_at_enc, rb_str_new2("utf-8"));
- }
- return val;
- } else {
- return rb_apply(cTclTkLib, ID_merge_tklist, dst);
- }
+ return rb_apply(cTclTkLib, ID_merge_tklist, dst);
}
static VALUE
-ary2list2(ary, enc_flag, self)
+ary2list2(ary, self)
VALUE ary;
- VALUE enc_flag;
VALUE self;
{
- int idx, size, req_chk_flag;
- volatile VALUE val, str_val;
+ int idx, size;
+ volatile VALUE val;
volatile VALUE dst;
- volatile VALUE sys_enc, dst_enc, str_enc;
-
- sys_enc = rb_funcall(cTclTkLib, ID_encoding, 0, 0);
- if NIL_P(sys_enc) {
- sys_enc = rb_funcall(cTclTkLib, ID_encoding_system, 0, 0);
- sys_enc = rb_funcall(sys_enc, ID_to_s, 0, 0);
- }
-
- if NIL_P(enc_flag) {
- dst_enc = sys_enc;
- req_chk_flag = 1;
- } else if (TYPE(enc_flag) == T_TRUE || TYPE(enc_flag) == T_FALSE) {
- dst_enc = enc_flag;
- req_chk_flag = 0;
- } else {
- dst_enc = rb_funcall(enc_flag, ID_to_s, 0, 0);
- req_chk_flag = 0;
- }
size = RARRAY(ary)->len;
dst = rb_ary_new2(size);
RARRAY(dst)->len = 0;
for(idx = 0; idx < RARRAY(ary)->len; idx++) {
val = RARRAY(ary)->ptr[idx];
- str_val = Qnil;
switch(TYPE(val)) {
case T_ARRAY:
- str_val = ary2list(val, enc_flag, self);
+ RARRAY(dst)->ptr[RARRAY(dst)->len++] = ary2list(val, self);
break;
case T_HASH:
- if (RTEST(enc_flag)) {
- str_val = hash2list(val, self);
- } else {
- str_val = hash2list_enc(val, self);
- }
+ RARRAY(dst)->ptr[RARRAY(dst)->len++] = hash2list(val, self);
break;
default:
if (val != TK_None) {
- str_val = get_eval_string_core(val, enc_flag, self);
- }
- }
-
- if (!NIL_P(str_val)) {
- RARRAY(dst)->ptr[RARRAY(dst)->len++] = str_val;
-
- if (req_chk_flag) {
- str_enc = rb_ivar_get(str_val, ID_at_enc);
- if (!NIL_P(str_enc)) {
- str_enc = rb_funcall(str_enc, ID_to_s, 0, 0);
- } else {
- str_enc = sys_enc;
- }
- if (!rb_str_cmp(str_enc, dst_enc)) {
- dst_enc = Qtrue;
- req_chk_flag = 0;
- }
+ RARRAY(dst)->ptr[RARRAY(dst)->len++]
+ = get_eval_string_core(val, Qnil, self);
}
}
}
-
- if (RTEST(dst_enc) && !NIL_P(sys_enc)) {
- for(idx = 0; idx < RARRAY(dst)->len; idx++) {
- str_val = RARRAY(dst)->ptr[idx];
- if (rb_respond_to(self, ID_toUTF8)) {
- str_val = rb_funcall(self, ID_toUTF8, 1, str_val);
- } else {
- str_val = rb_funcall(cTclTkLib, ID_toUTF8, 1, str_val);
- }
- RARRAY(dst)->ptr[idx] = str_val;
- }
- val = rb_apply(cTclTkLib, ID_merge_tklist, dst);
- if (TYPE(dst_enc) == T_STRING) {
- val = rb_funcall(cTclTkLib, ID_fromUTF8, 2, val, dst_enc);
- rb_ivar_set(val, ID_at_enc, dst_enc);
- } else {
- rb_ivar_set(val, ID_at_enc, rb_str_new2("utf-8"));
- }
- return val;
- } else {
- return rb_apply(cTclTkLib, ID_merge_tklist, dst);
- }
+ return rb_apply(cTclTkLib, ID_merge_tklist, dst);
}
static VALUE
@@ -594,13 +447,15 @@ assoc2kv_enc(assoc, ary, self)
}
static int
-push_kv(key, val, args)
+push_kv(key, val, args, err)
VALUE key;
VALUE val;
VALUE args;
+ int err;
{
volatile VALUE ary;
+ hash_check(err);
ary = RARRAY(args)->ptr[0];
if (key == Qundef) return ST_CONTINUE;
@@ -642,13 +497,15 @@ hash2kv(hash, ary, self)
}
static int
-push_kv_enc(key, val, args)
+push_kv_enc(key, val, args, err)
VALUE key;
VALUE val;
VALUE args;
+ int err;
{
volatile VALUE ary;
+ hash_check(err);
ary = RARRAY(args)->ptr[0];
if (key == Qundef) return ST_CONTINUE;
@@ -697,7 +554,7 @@ hash2list(hash, self)
VALUE hash;
VALUE self;
{
- return ary2list2(hash2kv(hash, Qnil, self), Qfalse, self);
+ return ary2list2(hash2kv(hash, Qnil, self), self);
}
@@ -706,7 +563,7 @@ hash2list_enc(hash, self)
VALUE hash;
VALUE self;
{
- return ary2list2(hash2kv_enc(hash, Qnil, self), Qfalse, self);
+ return ary2list2(hash2kv_enc(hash, Qnil, self), self);
}
static VALUE
@@ -810,7 +667,11 @@ get_eval_string_core(obj, enc_flag, self)
}
case T_ARRAY:
- return ary2list(obj, enc_flag, self);
+ if (RTEST(enc_flag)) {
+ return fromDefaultEnc_toUTF8(ary2list(obj, self), self);
+ } else {
+ return ary2list(obj, self);
+ }
case T_FALSE:
return rb_str_new2("0");
@@ -892,7 +753,7 @@ tk_get_eval_enc_str(self, obj)
static VALUE
tk_conv_args(argc, argv, self)
int argc;
- VALUE *argv; /* [0]:base_array, [1]:enc_mode, [2]..[n]:args */
+ VALUE *argv;
VALUE self;
{
int idx, size;
@@ -900,14 +761,14 @@ tk_conv_args(argc, argv, self)
int thr_crit_bup;
VALUE old_gc;
- if (argc < 2) {
- rb_raise(rb_eArgError, "too few arguments");
- }
-
thr_crit_bup = rb_thread_critical;
rb_thread_critical = Qtrue;
+
old_gc = rb_gc_disable();
+ if (argc < 2) {
+ rb_raise(rb_eArgError, "too few arguments");
+ }
for(size = 0, idx = 2; idx < argc; idx++) {
if (TYPE(argv[idx]) == T_HASH) {
size += 2 * RHASH(argv[idx])->tbl->num_entries;
@@ -961,8 +822,6 @@ tcl2rb_bool(self, value)
value = rb_funcall(value, ID_downcase, 0);
- if (RSTRING(value)->ptr == (char*)NULL) return Qnil;
-
if (RSTRING(value)->ptr[0] == '\0'
|| strcmp(RSTRING(value)->ptr, "0") == 0
|| strcmp(RSTRING(value)->ptr, "no") == 0
@@ -1019,8 +878,6 @@ tkstr_to_number(value)
{
rb_check_type(value, T_STRING);
- if (RSTRING(value)->ptr == (char*)NULL) return INT2FIX(0);
-
return rb_rescue2(tkstr_to_int, value,
tkstr_rescue_float, value,
rb_eArgError, 0);
@@ -1057,8 +914,6 @@ tcl2rb_string(self, value)
{
rb_check_type(value, T_STRING);
- if (RSTRING(value)->ptr == (char*)NULL) return rb_tainted_str_new2("");
-
return tkstr_to_str(value);
}
@@ -1069,8 +924,6 @@ tcl2rb_num_or_str(self, value)
{
rb_check_type(value, T_STRING);
- if (RSTRING(value)->ptr == (char*)NULL) return rb_tainted_str_new2("");
-
return rb_rescue2(tkstr_to_number, value,
tkstr_to_str, value,
rb_eArgError, 0);
@@ -1085,7 +938,6 @@ struct cbsubst_info {
char *type;
ID *ivar;
VALUE proc;
- VALUE aliases;
};
static void
@@ -1093,7 +945,6 @@ subst_mark(ptr)
struct cbsubst_info *ptr;
{
rb_gc_mark(ptr->proc);
- rb_gc_mark(ptr->aliases);
}
static void
@@ -1113,7 +964,7 @@ cbsubst_init()
{
struct cbsubst_info *inf;
ID *ivar;
- volatile VALUE proc, aliases;
+ volatile VALUE proc;
inf = ALLOC(struct cbsubst_info);
@@ -1131,9 +982,6 @@ cbsubst_init()
proc = rb_hash_new();
inf->proc = proc;
- aliases = rb_hash_new();
- inf->aliases = aliases;
-
rb_const_set(cCB_SUBST, ID_SUBST_INFO,
Data_Wrap_Struct(cSUBST_INFO, subst_mark, subst_free, inf));
}
@@ -1167,122 +1015,6 @@ cbsubst_ret_val(self, val)
return val;
}
-static int
-each_attr_def(key, value, klass)
- VALUE key, value, klass;
-{
- ID key_id, value_id;
-
- if (key == Qundef) return ST_CONTINUE;
-
- switch(TYPE(key)) {
- case T_STRING:
- key_id = rb_intern(RSTRING(key)->ptr);
- break;
- case T_SYMBOL:
- key_id = SYM2ID(key);
- break;
- default:
- rb_raise(rb_eArgError,
- "includes invalid key(s). expected a String or a Symbol");
- }
-
- switch(TYPE(value)) {
- case T_STRING:
- value_id = rb_intern(RSTRING(value)->ptr);
- break;
- case T_SYMBOL:
- value_id = SYM2ID(value);
- break;
- default:
- rb_raise(rb_eArgError,
- "includes invalid value(s). expected a String or a Symbol");
- }
-
- rb_alias(klass, key_id, value_id);
-
- return ST_CONTINUE;
-}
-
-static VALUE
-cbsubst_def_attr_aliases(self, tbl)
- VALUE self;
- VALUE tbl;
-{
- struct cbsubst_info *inf;
-
- if (TYPE(tbl) != T_HASH) {
- rb_raise(rb_eArgError, "expected a Hash");
- }
-
- Data_Get_Struct(rb_const_get(self, ID_SUBST_INFO),
- struct cbsubst_info, inf);
-
- rb_hash_foreach(tbl, each_attr_def, self);
-
- return rb_funcall(inf->aliases, rb_intern("update"), 1, tbl);
-}
-
-static VALUE
-cbsubst_get_subst_arg(argc, argv, self)
- int argc;
- VALUE *argv;
- VALUE self;
-{
- struct cbsubst_info *inf;
- char *str, *buf, *ptr;
- int i, j, len;
- ID id;
- volatile VALUE arg_sym, ret;
-
- Data_Get_Struct(rb_const_get(self, ID_SUBST_INFO),
- struct cbsubst_info, inf);
-
- buf = ALLOC_N(char, 3*argc + 1);
- ptr = buf;
- len = strlen(inf->key);
-
- for(i = 0; i < argc; i++) {
- switch(TYPE(argv[i])) {
- case T_STRING:
- str = RSTRING(argv[i])->ptr;
- arg_sym = ID2SYM(rb_intern(str));
- break;
- case T_SYMBOL:
- arg_sym = argv[i];
- str = rb_id2name(SYM2ID(arg_sym));
- break;
- default:
- rb_raise(rb_eArgError, "arg #%d is not a String or a Symbol", i);
- }
-
- if (!NIL_P(ret = rb_hash_aref(inf->aliases, arg_sym))) {
- str = rb_id2name(SYM2ID(ret));
- }
-
- id = rb_intern(RSTRING(rb_str_cat2(rb_str_new2("@"), str))->ptr);
-
- for(j = 0; j < len; j++) {
- if (inf->ivar[j] == id) break;
- }
-
- if (j >= len) {
- rb_raise(rb_eArgError, "cannot find attribute :%s", str);
- }
-
- *(ptr++) = '%';
- *(ptr++) = *(inf->key + j);
- *(ptr++) = ' ';
- }
-
- *ptr = '\0';
-
- ret = rb_str_new2(buf);
-
- free(buf);
-
- return ret;
-}
static VALUE
cbsubst_get_subst_key(self, str)
@@ -1357,7 +1089,6 @@ cbsubst_table_setup(self, key_inf, proc_inf)
char *type = ALLOC_N(char, len + 1);
ID *ivar = ALLOC_N(ID, len + 1);
volatile VALUE proc = rb_hash_new();
- volatile VALUE aliases = rb_hash_new();
volatile VALUE inf;
/* init */
@@ -1367,7 +1098,6 @@ cbsubst_table_setup(self, key_inf, proc_inf)
subst_inf->type = type;
subst_inf->ivar = ivar;
subst_inf->proc = proc;
- subst_inf->aliases = aliases;
/*
* keys : array of [subst, type, ivar]
@@ -1509,8 +1239,6 @@ tkobj_path(self)
}
/*************************************/
-/* release date */
-const char tkutil_release_date[] = TKUTIL_RELEASE_DATE;
void
Init_tkutil()
@@ -1521,25 +1249,17 @@ Init_tkutil()
VALUE mTK = rb_define_module("TkUtil");
/* --------------------- */
-
- rb_define_const(mTK, "RELEASE_DATE",
- rb_obj_freeze(rb_str_new2(tkutil_release_date)));
-
- /* --------------------- */
rb_global_variable(&cMethod);
cMethod = rb_const_get(rb_cObject, rb_intern("Method"));
ID_path = rb_intern("path");
ID_at_path = rb_intern("@path");
- ID_at_enc = rb_intern("@encoding");
ID_to_eval = rb_intern("to_eval");
ID_to_s = rb_intern("to_s");
ID_source = rb_intern("source");
ID_downcase = rb_intern("downcase");
ID_install_cmd = rb_intern("install_cmd");
ID_merge_tklist = rb_intern("_merge_tklist");
- ID_encoding = rb_intern("encoding");
- ID_encoding_system = rb_intern("encoding_system");
ID_call = rb_intern("call");
/* --------------------- */
@@ -1552,8 +1272,6 @@ Init_tkutil()
ID_SUBST_INFO = rb_intern("SUBST_INFO");
rb_define_singleton_method(cCB_SUBST, "ret_val", cbsubst_ret_val, 1);
rb_define_singleton_method(cCB_SUBST, "scan_args", cbsubst_scan_args, 2);
- rb_define_singleton_method(cCB_SUBST, "subst_arg",
- cbsubst_get_subst_arg, -1);
rb_define_singleton_method(cCB_SUBST, "_get_subst_key",
cbsubst_get_subst_key, 1);
rb_define_singleton_method(cCB_SUBST, "_get_all_subst_keys",
@@ -1562,8 +1280,6 @@ Init_tkutil()
cbsubst_table_setup, 2);
rb_define_singleton_method(cCB_SUBST, "_get_extra_args_tbl",
cbsubst_get_extra_args_tbl, 0);
- rb_define_singleton_method(cCB_SUBST, "_define_attribute_aliases",
- cbsubst_def_attr_aliases, 1);
rb_define_method(cCB_SUBST, "initialize", cbsubst_initialize, -1);
@@ -1613,7 +1329,6 @@ Init_tkutil()
tk_get_eval_string, -1);
rb_define_singleton_method(mTK, "_get_eval_enc_str",
tk_get_eval_enc_str, 1);
- rb_define_singleton_method(mTK, "_conv_args", tk_conv_args, -1);
rb_define_singleton_method(mTK, "bool", tcl2rb_bool, 1);
rb_define_singleton_method(mTK, "number", tcl2rb_number, 1);
diff --git a/ext/win32ole/extconf.rb b/ext/win32ole/extconf.rb
index cee922554a..c989267733 100644
--- a/ext/win32ole/extconf.rb
+++ b/ext/win32ole/extconf.rb
@@ -6,17 +6,6 @@
require 'mkmf'
dir_config("win32")
-
-SRCFILES=<<SRC
-win32ole.c
-SRC
-
-def create_docfile(src)
- open(File.expand_path($srcdir) + "/.document", "w") {|ofs|
- ofs.print src
- }
-end
-
def create_win32ole_makefile
if have_library("ole32") and
have_library("oleaut32") and
@@ -26,9 +15,6 @@ def create_win32ole_makefile
have_library("advapi32") and
have_header("windows.h")
create_makefile("win32ole")
- create_docfile(SRCFILES)
- else
- create_docfile("")
end
end
diff --git a/ext/win32ole/tests/testNIL2VTEMPTY.rb b/ext/win32ole/tests/testNIL2VTEMPTY.rb
deleted file mode 100644
index 555d35fbf3..0000000000
--- a/ext/win32ole/tests/testNIL2VTEMPTY.rb
+++ /dev/null
@@ -1,28 +0,0 @@
-# This is test script to check that WIN32OLE should convert nil to VT_EMPTY in second try.
-# [ruby-talk:137054]
-
-require 'win32ole'
-require 'test/unit'
-
-class TestNIL2VT_EMPTY < Test::Unit::TestCase
- def setup
- fs = WIN32OLE.new('Scripting.FileSystemObject')
- @path = fs.GetFolder(".").path
- end
- def test_openSchema
- con = nil
- begin
- con = WIN32OLE.new('ADODB.Connection')
- con.connectionString = "Provider=MSDASQL;Extended Properties="
- con.connectionString +="\"DRIVER={Microsoft Text Driver (*.txt; *.csv)};DBQ=#{@path}\""
- con.open
- rescue
- con = nil
- end
- if con
- rs = con.openSchema(4, [nil,nil,"DUMMY", "TABLE"])
- assert(rs)
- end
- end
-end
-
diff --git a/ext/win32ole/tests/testOLEEVENT.rb b/ext/win32ole/tests/testOLEEVENT.rb
index 0901158642..15b7ca8413 100644
--- a/ext/win32ole/tests/testOLEEVENT.rb
+++ b/ext/win32ole/tests/testOLEEVENT.rb
@@ -5,8 +5,6 @@ class TestWIN32OLE_EVENT < RUNIT::TestCase
def setup
@excel = WIN32OLE.new("Excel.Application")
@excel.visible = true
- @event = ""
- @event2 = ""
end
def test_on_event
book = @excel.workbooks.Add
@@ -26,62 +24,6 @@ class TestWIN32OLE_EVENT < RUNIT::TestCase
end
assert_equal("OK", value)
end
-
- def handler1
- @event += "handler1"
- end
- def handler2
- @event += "handler2"
- end
-
- def handler3
- @event += "handler3"
- end
-
- def test_on_event2
- book = @excel.workbooks.Add
- begin
- ev = WIN32OLE_EVENT.new(book, 'WorkbookEvents')
- ev.on_event('SheetChange'){|arg1, arg2|
- handler1
- }
- ev.on_event('SheetChange'){|arg1, arg2|
- handler2
- }
- book.Worksheets(1).Range("A1").value = "OK"
- ensure
- book.saved = true
- end
- assert_equal("handler2", @event)
- end
-
- def test_on_event3
- book = @excel.workbooks.Add
- begin
- ev = WIN32OLE_EVENT.new(book, 'WorkbookEvents')
- ev.on_event{ handler1 }
- ev.on_event{ handler2 }
- book.Worksheets(1).Range("A1").value = "OK"
- ensure
- book.saved = true
- end
- assert_equal("handler2", @event)
- end
-
- def test_on_event4
- book = @excel.workbooks.Add
- begin
- ev = WIN32OLE_EVENT.new(book, 'WorkbookEvents')
- ev.on_event{ handler1 }
- ev.on_event{ handler2 }
- ev.on_event('SheetChange'){|arg1, arg2| handler3 }
- book.Worksheets(1).Range("A1").value = "OK"
- ensure
- book.saved = true
- end
- assert_equal("handler3", @event)
- end
-
def teardown
@excel.quit
@excel = nil
diff --git a/ext/win32ole/tests/testOLEMETHOD.rb b/ext/win32ole/tests/testOLEMETHOD.rb
index 390c9999f8..b52052e669 100644
--- a/ext/win32ole/tests/testOLEMETHOD.rb
+++ b/ext/win32ole/tests/testOLEMETHOD.rb
@@ -84,9 +84,4 @@ class TestOLEMETHOD < RUNIT::TestCase
m = WIN32OLE_METHOD.new(@excel_app, 'QueryInterface')
assert_equal(0, m.offset_vtbl)
end
- def test_dispid
- tobj = WIN32OLE_TYPE.new('Microsoft Shell Controls And Automation', 'FolderItem2')
- method = WIN32OLE_METHOD.new(tobj, 'InvokeVerb')
- assert_equal(1610743824, method.dispid)
- end
end
diff --git a/ext/win32ole/tests/testOLEPARAM.rb b/ext/win32ole/tests/testOLEPARAM.rb
index 4014fadbfc..685b548aa5 100644
--- a/ext/win32ole/tests/testOLEPARAM.rb
+++ b/ext/win32ole/tests/testOLEPARAM.rb
@@ -62,4 +62,13 @@ class TestOLEPARAM < RUNIT::TestCase
f = methods.find {|m| m.name == 'SaveAs'}
assert(f.params[0].optional?)
end
+ def test_ole_type_detail
+ classes = WIN32OLE_TYPE.ole_classes(MS_EXCEL_TYPELIB)
+ methods = classes.find {|c| c.name == 'Worksheet'}.ole_methods
+ f = methods.find {|m| m.name == 'SaveAs'}
+ assert_equal(nil, f.params[0].default)
+ methods = classes.find {|c| c.name == 'Workbook'}.ole_methods
+ f = methods.find {|m| m.name == 'SaveAs'}
+ assert_equal(1, f.params[6].default)
+ end
end
diff --git a/ext/win32ole/tests/testWIN32OLE.rb b/ext/win32ole/tests/testWIN32OLE.rb
index 988fbb9101..d8c3b6e6ba 100644
--- a/ext/win32ole/tests/testWIN32OLE.rb
+++ b/ext/win32ole/tests/testWIN32OLE.rb
@@ -40,7 +40,7 @@ class TestWin32OLE < RUNIT::TestCase
exc = assert_exception(WIN32OLERuntimeError) {
WIN32OLE.new("{000}")
}
- assert_match(/unknown OLE server: `\{000\}'/, exc.message)
+ assert_match(/Unknown OLE server: `\{000\}'/, exc.message)
end
def test_s_connect
excel2 = WIN32OLE.connect('Excel.Application')
@@ -57,60 +57,6 @@ class TestWin32OLE < RUNIT::TestCase
assert_equal(-4160, CONST1::XlTop)
end
- def test_s_codepage
- assert_equal(WIN32OLE::CP_ACP, WIN32OLE.codepage)
- end
-
- def test_s_codepage_set
- WIN32OLE.codepage = WIN32OLE::CP_UTF8
- assert_equal(WIN32OLE::CP_UTF8, WIN32OLE.codepage)
- WIN32OLE.codepage = WIN32OLE::CP_ACP
- end
-
- def test_const_CP_ACP
- assert_equal(0, WIN32OLE::CP_ACP)
- end
-
- def test_const_CP_OEMCP
- assert_equal(1, WIN32OLE::CP_OEMCP)
- end
-
- def test_const_CP_MACCP
- assert_equal(2, WIN32OLE::CP_MACCP)
- end
-
- def test_const_CP_THREAD_ACP
- assert_equal(3, WIN32OLE::CP_THREAD_ACP)
- end
-
- def test_const_CP_SYMBOL
- assert_equal(42, WIN32OLE::CP_SYMBOL)
- end
-
- def test_const_CP_UTF7
- assert_equal(65000, WIN32OLE::CP_UTF7)
- end
-
- def test_const_CP_UTF8
- assert_equal(65001, WIN32OLE::CP_UTF8)
- end
-
- def test_s_codepage_changed
- book = @excel.workbooks.add
- sheet = book.worksheets(1)
- begin
- WIN32OLE.codepage = WIN32OLE::CP_UTF8
- sheet.range("A1").value = [0x3042].pack("U*")
- val = sheet.range("A1").value
- assert_equal("\343\201\202", val)
- WIN32OLE.codepage = WIN32OLE::CP_ACP
- val = sheet.range("A1").value
- assert_equal("\202\240", val)
- ensure
- book.saved = true
- end
- end
-
def test_get_win32ole_object
workbooks = @excel.Workbooks;
assert_instance_of(WIN32OLE, workbooks)
@@ -303,11 +249,6 @@ class TestWin32OLE_WITH_MSI < RUNIT::TestCase
@record[ "StringData", 1 ] = 'ffff'
assert_equal('ffff', @record.StringData(1))
end
-
- def test__invoke
- shell=WIN32OLE.new('Shell.Application')
- assert_equal(shell.NameSpace(0).title, shell._invoke(0x60020002, [0], [WIN32OLE::VARIANT::VT_VARIANT]).title)
- end
end
# ---------------------
diff --git a/ext/win32ole/tests/testall.rb b/ext/win32ole/tests/testall.rb
index 4835bac748..17bae2c810 100644
--- a/ext/win32ole/tests/testall.rb
+++ b/ext/win32ole/tests/testall.rb
@@ -8,5 +8,4 @@ require "testOLEPARAM"
require "testOLEMETHOD"
require "testOLEVARIABLE"
require "testVARIANT"
-require "testNIL2VTEMPTY"
# require "testOLEEVENT"
diff --git a/ext/win32ole/win32ole.c b/ext/win32ole/win32ole.c
index 875ac578a8..7a800986b5 100644
--- a/ext/win32ole/win32ole.c
+++ b/ext/win32ole/win32ole.c
@@ -72,13 +72,13 @@
#define OLEData_Get_Struct(obj, pole) {\
Data_Get_Struct(obj, struct oledata, pole);\
if(!pole->pDispatch) {\
- rb_raise(rb_eRuntimeError, "failed to get Dispatch Interface");\
+ rb_raise(rb_eRuntimeError, "Failed to get Dispatch Interface");\
}\
}
#define WC2VSTR(x) ole_wc2vstr((x), TRUE)
-#define WIN32OLE_VERSION "0.6.5"
+#define WIN32OLE_VERSION "0.5.9"
typedef HRESULT (STDAPICALLTYPE FNCOCREATEINSTANCEEX)
(REFCLSID, IUnknown*, DWORD, COSERVERINFO*, DWORD, MULTI_QI*);
@@ -134,7 +134,6 @@ typedef struct tagIEVENTSINKOBJ {
DWORD m_dwCookie;
IConnectionPoint *pConnectionPoint;
ITypeInfo *pTypeInfo;
- int *ptr_freed;
}IEVENTSINKOBJ, *PIEVENTSINKOBJ;
VALUE cWIN32OLE;
@@ -154,8 +153,6 @@ static HINSTANCE gole32 = NULL;
static FNCOCREATEINSTANCEEX *gCoCreateInstanceEx = NULL;
static VALUE com_hash;
static IDispatchVtbl com_vtbl;
-static UINT cWIN32OLE_cp = CP_ACP;
-static VARTYPE g_nil_to = VT_ERROR;
struct oledata {
IDispatch *pDispatch;
@@ -184,7 +181,6 @@ struct oleparamdata {
struct oleeventdata {
IEVENTSINKOBJ *pEvent;
- int freed;
};
struct oleparam {
@@ -474,10 +470,10 @@ ole_wc2mb(pw)
{
int size;
LPSTR pm;
- size = WideCharToMultiByte(cWIN32OLE_cp, 0, pw, -1, NULL, 0, NULL, NULL);
+ size = WideCharToMultiByte(CP_ACP, 0, pw, -1, NULL, 0, NULL, NULL);
if (size) {
pm = ALLOC_N(char, size);
- WideCharToMultiByte(cWIN32OLE_cp, 0, pw, -1, pm, size, NULL, NULL);
+ WideCharToMultiByte(CP_ACP, 0, pw, -1, pm, size, NULL, NULL);
}
else {
pm = ALLOC_N(char, 1);
@@ -607,7 +603,7 @@ ole_initialize()
if(gOLEInitialized == Qfalse) {
hr = OleInitialize(NULL);
if(FAILED(hr)) {
- ole_raise(hr, rb_eRuntimeError, "fail: OLE initialize");
+ ole_raise(hr, rb_eRuntimeError, "Fail: OLE initialize");
}
gOLEInitialized = Qtrue;
/*
@@ -671,9 +667,9 @@ ole_mb2wc(pm, len)
{
int size;
LPWSTR pw;
- size = MultiByteToWideChar(cWIN32OLE_cp, 0, pm, len, NULL, 0);
+ size = MultiByteToWideChar(CP_ACP, 0, pm, len, NULL, 0);
pw = SysAllocStringLen(NULL, size - 1);
- MultiByteToWideChar(cWIN32OLE_cp, 0, pm, len, pw, size);
+ MultiByteToWideChar(CP_ACP, 0, pm, len, pw, size);
return pw;
}
@@ -835,12 +831,8 @@ ole_val2variant(val, var)
V_BOOL(var) = VARIANT_FALSE;
break;
case T_NIL:
- if (g_nil_to == VT_ERROR) {
- V_VT(var) = VT_ERROR;
- V_ERROR(var) = DISP_E_PARAMNOTFOUND;
- }else {
- V_VT(var) = VT_EMPTY;
- }
+ V_VT(var) = VT_ERROR;
+ V_ERROR(var) = DISP_E_PARAMNOTFOUND;
break;
default:
V_VT(var) = VT_DISPATCH;
@@ -849,16 +841,6 @@ ole_val2variant(val, var)
}
}
-static void
-ole_val2variant2(val, var)
- VALUE val;
- VARIANT *var;
-{
- g_nil_to = VT_EMPTY;
- ole_val2variant(val, var);
- g_nil_to = VT_ERROR;
-}
-
static VALUE
ole_set_member(self, dispatch)
VALUE self;
@@ -1105,7 +1087,6 @@ ole_variant2val(pvar)
return obj;
}
-
static LONG reg_open_key(hkey, name, phkey)
HKEY hkey;
const char *name;
@@ -1383,12 +1364,12 @@ ole_create_dcom(argc, argv, self)
if (!gole32)
gole32 = LoadLibrary("OLE32");
if (!gole32)
- rb_raise(rb_eRuntimeError, "failed to load OLE32");
+ rb_raise(rb_eRuntimeError, "Failed to load OLE32");
if (!gCoCreateInstanceEx)
gCoCreateInstanceEx = (FNCOCREATEINSTANCEEX*)
GetProcAddress(gole32, "CoCreateInstanceEx");
if (!gCoCreateInstanceEx)
- rb_raise(rb_eRuntimeError, "CoCreateInstanceEx is not supported in this environment");
+ rb_raise(rb_eRuntimeError, "CoCreateInstanceEx is not supported in this environment.");
rb_scan_args(argc, argv, "2*", &ole, &host, &others);
pbuf = ole_mb2wc(StringValuePtr(ole), -1);
@@ -1400,7 +1381,7 @@ ole_create_dcom(argc, argv, self)
SysFreeString(pbuf);
if (FAILED(hr))
ole_raise(hr, eWIN32OLE_RUNTIME_ERROR,
- "unknown OLE server: `%s'",
+ "Unknown OLE server: `%s'",
StringValuePtr(ole));
memset(&serverinfo, 0, sizeof(COSERVERINFO));
serverinfo.pwszName = ole_mb2wc(StringValuePtr(host), -1);
@@ -1410,7 +1391,7 @@ ole_create_dcom(argc, argv, self)
SysFreeString(serverinfo.pwszName);
if (FAILED(hr))
ole_raise(hr, eWIN32OLE_RUNTIME_ERROR,
- "failed to create DCOM server `%s' in `%s'",
+ "Failed to create DCOM server `%s' in `%s'",
StringValuePtr(ole),
StringValuePtr(host));
@@ -1437,7 +1418,7 @@ ole_bind_obj(moniker, argc, argv, self)
hr = CreateBindCtx(0, &pBindCtx);
if(FAILED(hr)) {
ole_raise(hr, eWIN32OLE_RUNTIME_ERROR,
- "failed to create bind context");
+ "Failed to create bind context");
}
pbuf = ole_mb2wc(StringValuePtr(moniker), -1);
@@ -1446,7 +1427,7 @@ ole_bind_obj(moniker, argc, argv, self)
if(FAILED(hr)) {
OLE_RELEASE(pBindCtx);
ole_raise(hr, eWIN32OLE_RUNTIME_ERROR,
- "failed to parse display name of moniker `%s'",
+ "Failed to parse display name of moniker `%s'",
StringValuePtr(moniker));
}
hr = pMoniker->lpVtbl->BindToObject(pMoniker, pBindCtx, NULL,
@@ -1457,20 +1438,17 @@ ole_bind_obj(moniker, argc, argv, self)
if(FAILED(hr)) {
ole_raise(hr, eWIN32OLE_RUNTIME_ERROR,
- "failed to bind moniker `%s'",
+ "Failed to bind moniker `%s'",
StringValuePtr(moniker));
}
return create_win32ole_object(self, pDispatch, argc, argv);
}
/*
- * call-seq:
- * WIN32OLE.connect( ole ) --> aWIN32OLE
- *
- * Returns running OLE Automation object or WIN32OLE object from moniker.
- * 1st argument should be OLE program id or class id or moniker.
- *
- * WIN32OLE.connect('Excel.Application') # => WIN32OLE object which represents running Excel.
+ * WIN32OLE.connect( ole ) --> aWIN32OLE
+ * ----
+ * Returns running OLE Automation object or WIN32OLE object from moniker.
+ * 1st argument should be OLE program id or class id or moniker.
*/
static VALUE
fole_s_connect(argc, argv, self)
@@ -1517,7 +1495,7 @@ fole_s_connect(argc, argv, self)
if(FAILED(hr)) {
OLE_RELEASE(pUnknown);
ole_raise(hr, eWIN32OLE_RUNTIME_ERROR,
- "failed to create WIN32OLE server `%s'",
+ "Failed to create WIN32OLE server `%s'",
StringValuePtr(svr_name));
}
@@ -1527,33 +1505,10 @@ fole_s_connect(argc, argv, self)
}
/*
- * call-seq:
- * WIN32OLE.const_load( ole, mod = WIN32OLE)
- *
- * Defines the constants of OLE Automation server as mod's constants.
- * The first argument is WIN32OLE object or type library name.
- * If 2nd argument is omitted, the default is WIN32OLE.
- * The first letter of Ruby's constant variable name is upper case,
- * so constant variable name of WIN32OLE object is capitalized.
- * For example, the 'xlTop' constant of Excel is changed to 'XlTop'
- * in WIN32OLE.
- * If the first letter of constant variabl is not [A-Z], then
- * the constant is defined as CONSTANTS hash element.
- *
- * module EXCEL_CONST
- * end
- * excel = WIN32OLE.new('Excel.Application')
- * WIN32OLE.const_load(excel, EXCEL_CONST)
- * puts EXCEL_CONST::XlTop # => -4160
- * puts EXCEL_CONST::CONSTANTS['_xlDialogChartSourceData'] # => 541
- *
- * WIN32OLE.const_load(excel)
- * puts WIN32OLE::XlTop # => -4160
- *
- * module MSO
- * end
- * WIN32OLE.const_load('Microsoft Office 9.0 Object Library', MSO)
- * puts MSO::MsoLineSingle # => 1
+ * WIN32OLE.const_load( ole, mod = WIN32OLE)
+ * ----
+ * Defines the constants of OLE Automation server as mod's constants.
+ * If 2nd argument is omitted, the default is WIN32OLE.
*/
static VALUE
fole_s_const_load(argc, argv, self)
@@ -1577,19 +1532,19 @@ fole_s_const_load(argc, argv, self)
if (TYPE(klass) != T_CLASS &&
TYPE(klass) != T_MODULE &&
TYPE(klass) != T_NIL) {
- rb_raise(rb_eTypeError, "2nd parameter must be Class or Module");
+ rb_raise(rb_eTypeError, "2nd paramator must be Class or Module.");
}
if (rb_obj_is_kind_of(ole, cWIN32OLE)) {
OLEData_Get_Struct(ole, pole);
hr = pole->pDispatch->lpVtbl->GetTypeInfo(pole->pDispatch,
0, lcid, &pTypeInfo);
if(FAILED(hr)) {
- ole_raise(hr, rb_eRuntimeError, "failed to GetTypeInfo");
+ ole_raise(hr, rb_eRuntimeError, "Failed to GetTypeInfo");
}
hr = pTypeInfo->lpVtbl->GetContainingTypeLib(pTypeInfo, &pTypeLib, &index);
if(FAILED(hr)) {
OLE_RELEASE(pTypeInfo);
- ole_raise(hr, rb_eRuntimeError, "failed to GetContainingTypeLib");
+ ole_raise(hr, rb_eRuntimeError, "Failed to GetContainingTypeLib");
}
OLE_RELEASE(pTypeInfo);
if(TYPE(klass) != T_NIL) {
@@ -1609,7 +1564,7 @@ fole_s_const_load(argc, argv, self)
hr = LoadTypeLibEx(pBuf, REGKIND_NONE, &pTypeLib);
SysFreeString(pBuf);
if (FAILED(hr))
- ole_raise(hr, eWIN32OLE_RUNTIME_ERROR, "failed to LoadTypeLibEx");
+ ole_raise(hr, eWIN32OLE_RUNTIME_ERROR, "Failed to LoadTypeLibEx");
if(TYPE(klass) != T_NIL) {
ole_const_load(pTypeLib, klass, self);
}
@@ -1619,7 +1574,7 @@ fole_s_const_load(argc, argv, self)
OLE_RELEASE(pTypeLib);
}
else {
- rb_raise(rb_eTypeError, "1st parameter must be WIN32OLE instance");
+ rb_raise(rb_eTypeError, "1st paramator must be WIN32OLE instance");
}
return Qnil;
}
@@ -1671,12 +1626,11 @@ reference_count(pole)
}
/*
- * call-seq:
- * WIN32OLE.ole_reference_count(aWIN32OLE) --> number
- *
- * Returns reference counter of Dispatch interface of WIN32OLE object.
- * You should not use this method because this method
- * exists only for debugging WIN32OLE.
+ * WIN32OLE.ole_reference_count(aWIN32OLE) --> number
+ * ----
+ * Returns reference counter of Dispatch interface of WIN32OLE object.
+ * You should not use this method because this method
+ * exists only for debugging WIN32OLE.
*/
static VALUE
fole_s_reference_count(self, obj)
@@ -1689,13 +1643,12 @@ fole_s_reference_count(self, obj)
}
/*
- * call-seq:
- * WIN32OLE.ole_free(aWIN32OLE) --> number
- *
- * Invokes Release method of Dispatch interface of WIN32OLE object.
- * You should not use this method because this method
- * exists only for debugging WIN32OLE.
- * The return value is reference counter of OLE object.
+ * WIN32OLE.ole_free(aWIN32OLE) --> number
+ * ----
+ * Invokes Release method of Dispatch interface of WIN32OLE object.
+ * You should not use this method because this method
+ * exists only for debugging WIN32OLE.
+ * The return value is reference counter of OLE object.
*/
static VALUE
fole_s_free(self, obj)
@@ -1737,15 +1690,10 @@ ole_show_help(helpfile, helpcontext)
}
/*
- * call-seq:
- * WIN32OLE.ole_show_help(obj [,helpcontext])
- *
- * Displays helpfile. The 1st argument specifies WIN32OLE_TYPE
- * object or WIN32OLE_METHOD object or helpfile.
- *
- * excel = WIN32OLE.new('Excel.Application')
- * typeobj = excel.ole_type
- * WIN32OLE.ole_show_help(typeobj)
+ * WIN32OLE.ole_show_help(obj [,helpcontext])
+ * ----
+ * Displays helpfile. The 1st argument specifies WIN32OLE_TYPE
+ * object or WIN32OLE_METHOD object or helpfile.
*/
static VALUE
fole_s_show_help(argc, argv, self)
@@ -1772,84 +1720,16 @@ fole_s_show_help(argc, argv, self)
helpfile = target;
}
if (TYPE(helpfile) != T_STRING) {
- rb_raise(rb_eTypeError, "1st parameter must be (String|WIN32OLE_TYPE|WIN32OLE_METHOD)");
+ rb_raise(rb_eTypeError, "1st parameter must be (String|WIN32OLE_TYPE|WIN32OLE_METHOD).");
}
hwnd = ole_show_help(helpfile, helpcontext);
if(hwnd == 0) {
- rb_raise(rb_eRuntimeError, "failed to open help file `%s'",
+ rb_raise(rb_eRuntimeError, "Failed to open help file `%s'",
StringValuePtr(helpfile));
}
return Qnil;
}
-/*
- * call-seq:
- * WIN32OLE.codepage
- *
- * Returns current codepage.
- * WIN32OLE.codepage # => WIN32OLE::CP_ACP
- */
-static VALUE
-fole_s_get_code_page(self)
- VALUE self;
-{
- return INT2FIX(cWIN32OLE_cp);
-}
-
-/*
- * call-seq:
- * WIN32OLE.codepage = CP
- *
- * Sets current codepage.
- * WIN32OLE.codepage = WIN32OLE::CP_UTF8
- */
-static VALUE
-fole_s_set_code_page(self, vcp)
- VALUE self;
- VALUE vcp;
-{
- UINT cp = FIX2INT(vcp);
-
- switch(cp) {
- case CP_ACP:
- case CP_OEMCP:
- case CP_MACCP:
- case CP_THREAD_ACP:
- case CP_SYMBOL:
- case CP_UTF7:
- case CP_UTF8:
- cWIN32OLE_cp = cp;
- break;
- default:
- rb_raise(eWIN32OLE_RUNTIME_ERROR, "codepage should be WIN32OLE::CP_ACP, WIN32OLE::CP_OEMCP, WIN32OLE::CP_MACCP, WIN32OLE::CP_THREAD_ACP, WIN32OLE::CP_SYMBOL, WIN32OLE::CP_UTF7, WIN32OLE::CP_UTF8");
- break;
- }
-
- /*
- * Should this method return old codepage?
- */
- return Qnil;
-}
-
-/*
- * Document-class: WIN32OLE
- *
- * <code>WIN32OLE</code> objects represent OLE Automation object in Ruby.
- */
-
-/*
- * call-seq:
- * WIN32OLE.new(server, [host]) -> WIN32OLE object
- *
- * Returns a new WIN32OLE object(OLE Automation object).
- * The first argument server specifies OLE Automation server.
- * The first argument should be CLSID or PROGID.
- * If second argument host specified, then returns OLE Automation
- * object on host.
- *
- * WIN32OLE.new('Excel.Application') # => Excel OLE Automation WIN32OLE object.
- * WIN32OLE.new('{00024500-0000-0000-C000-000000000046}') # => Excel OLE Automation WIN32OLE object.
- */
static VALUE
fole_initialize(argc, argv, self)
int argc;
@@ -1889,7 +1769,7 @@ fole_initialize(argc, argv, self)
SysFreeString(pBuf);
if(FAILED(hr)) {
ole_raise(hr, eWIN32OLE_RUNTIME_ERROR,
- "unknown OLE server: `%s'",
+ "Unknown OLE server: `%s'",
StringValuePtr(svr_name));
}
@@ -1898,7 +1778,7 @@ fole_initialize(argc, argv, self)
&IID_IDispatch, (void**)&pDispatch);
if(FAILED(hr)) {
ole_raise(hr, eWIN32OLE_RUNTIME_ERROR,
- "failed to create WIN32OLE object from `%s'",
+ "Failed to create WIN32OLE object from `%s'",
StringValuePtr(svr_name));
}
@@ -1999,7 +1879,7 @@ ole_invoke(argc, argv, self, wFlags)
rb_scan_args(argc, argv, "1*", &cmd, &paramS);
OLEData_Get_Struct(self, pole);
if(!pole->pDispatch) {
- rb_raise(rb_eRuntimeError, "failed to get dispatch interface");
+ rb_raise(rb_eRuntimeError, "Failed to get dispatch interface");
}
wcmdname = ole_mb2wc(StringValuePtr(cmd), -1);
hr = pole->pDispatch->lpVtbl->GetIDsOfNames( pole->pDispatch, &IID_NULL,
@@ -2007,7 +1887,7 @@ ole_invoke(argc, argv, self, wFlags)
SysFreeString(wcmdname);
if(FAILED(hr)) {
ole_raise(hr, eWIN32OLE_RUNTIME_ERROR,
- "unknown property or method `%s'",
+ "Unknown property or method `%s'",
StringValuePtr(cmd));
}
@@ -2044,7 +1924,7 @@ ole_invoke(argc, argv, self, wFlags)
VariantClear(&op.dp.rgvarg[i]);
}
ole_raise(hr, eWIN32OLE_RUNTIME_ERROR,
- "failed to get named argument info: `%s'",
+ "Failed to get named argument info: `%s'",
StringValuePtr(cmd));
}
op.dp.rgdispidNamedArgs = &(pDispID[1]);
@@ -2106,27 +1986,6 @@ ole_invoke(argc, argv, self, wFlags)
VariantClear(&op.dp.rgvarg[n]);
}
}
- if (FAILED(hr)) {
- /* retry after converting nil to VT_EMPTY */
- if (op.dp.cArgs > cNamedArgs) {
- for(i = cNamedArgs; i < op.dp.cArgs; i++) {
- n = op.dp.cArgs - i + cNamedArgs - 1;
- param = rb_ary_entry(paramS, i-cNamedArgs);
- ole_val2variant2(param, &op.dp.rgvarg[n]);
- }
- memset(&excepinfo, 0, sizeof(EXCEPINFO));
- VariantInit(&result);
- hr = pole->pDispatch->lpVtbl->Invoke(pole->pDispatch, DispID,
- &IID_NULL, lcid, wFlags,
- &op.dp, &result,
- &excepinfo, &argErr);
- for(i = cNamedArgs; i < op.dp.cArgs; i++) {
- n = op.dp.cArgs - i + cNamedArgs - 1;
- VariantClear(&op.dp.rgvarg[n]);
- }
- }
- }
-
/* mega kludge. if a method in WORD is called and we ask
* for a result when one is not returned then
* hResult == DISP_E_EXCEPTION. this only happens on
@@ -2161,19 +2020,6 @@ ole_invoke(argc, argv, self, wFlags)
return obj;
}
-/*
- * call-seq:
- * WIN32OLE#invoke(method, [arg1,...]) => return value of method.
- *
- * Runs OLE method.
- * The first argument specifies the method name of OLE Automation object.
- * The others specify argument of the <i>method</i>.
- * If you can not execute <i>method</i> directly, then use this method instead.
- *
- * excel = WIN32OLE.new('Excel.Application')
- * excel.invoke('Quit') # => same as excel.Quit
- *
- */
static VALUE
fole_invoke(argc, argv, self)
int argc;
@@ -2355,7 +2201,7 @@ ole_invoke2(self, dispid, args, types, dispkind)
dispParams.rgdispidNamedArgs[0] = DISPID_PROPERTYPUT;
}
- hr = pole->pDispatch->lpVtbl->Invoke(pole->pDispatch, NUM2INT(dispid),
+ hr = pole->pDispatch->lpVtbl->Invoke(pole->pDispatch, FIX2INT(dispid),
&IID_NULL, LOCALE_SYSTEM_DEFAULT,
dispkind,
&dispParams, &result,
@@ -2378,16 +2224,12 @@ ole_invoke2(self, dispid, args, types, dispkind)
}
/*
- * call-seq:
- * WIN32OLE#_invoke(dispid, args, types)
- *
- * Runs the early binding method.
- * The 1st argument specifies dispatch ID,
- * the 2nd argument specifies the array of arguments,
- * the 3rd argument specifies the array of the type of arguments.
- *
- * excel = WIN32OLE.new('Excel.Application')
- * excel._invoke(302, [], []) # same effect as excel.Quit
+ * WIN32OLE#_invoke(dispid, args, types)
+ * ----
+ * Runs the early binding method.
+ * The 1st argument specifies dispatch ID,
+ * the 2nd argument specifies the array of arguments,
+ * the 3rd argument specifies the array of the type of arguments.
*/
static VALUE
fole_invoke2(self, dispid, args, types)
@@ -2400,16 +2242,12 @@ fole_invoke2(self, dispid, args, types)
}
/*
- * call-seq:
- * WIN32OLE#_getproperty(dispid, args, types)
- *
- * Runs the early binding method to get property.
- * The 1st argument specifies dispatch ID,
- * the 2nd argument specifies the array of arguments,
- * the 3rd argument specifies the array of the type of arguments.
- *
- * excel = WIN32OLE.new('Excel.Application')
- * puts excel._getproperty(558, [], []) # same effect as puts excel.visible
+ * WIN32OLE#_getproperty(dispid, args, types)
+ * ----
+ * Runs the early binding method to get property.
+ * The 1st argument specifies dispatch ID,
+ * the 2nd argument specifies the array of arguments,
+ * the 3rd argument specifies the array of the type of arguments.
*/
static VALUE
fole_getproperty2(self, dispid, args, types)
@@ -2422,16 +2260,12 @@ fole_getproperty2(self, dispid, args, types)
}
/*
- * call-seq:
- * WIN32OLE#_setproperty(dispid, args, types)
- *
- * Runs the early binding method to set property.
- * The 1st argument specifies dispatch ID,
- * the 2nd argument specifies the array of arguments,
- * the 3rd argument specifies the array of the type of arguments.
- *
- * excel = WIN32OLE.new('Excel.Application')
- * excel._setproperty(558, [true], [WIN32OLE::VARIANT::VT_BOOL]) # same effect as excel.visible = true
+ * WIN32OLE#_setproperty(dispid, args, types)
+ * ----
+ * Runs the early binding method to set property.
+ * The 1st argument specifies dispatch ID,
+ * the 2nd argument specifies the array of arguments,
+ * the 3rd argument specifies the array of the type of arguments.
*/
static VALUE
fole_setproperty2(self, dispid, args, types)
@@ -2444,18 +2278,12 @@ fole_setproperty2(self, dispid, args, types)
}
/*
- * call-seq:
- * WIN32OLE['property']=val
- * WIN32OLE.setproperty('property', [arg1, arg2,...] val)
- *
- * Sets property of OLE object.
- * When you want to set property with argument, you can use this method.
+ * WIN32OLE['property']=val
*
- * excel = WIN32OLE.new('Excel.Application')
- * excel['Visible'] = true
- * book = excel.workbooks.add
- * sheet = book.worksheets(1)
- * sheet.setproperty('Cells', 1, 2, 10) # => The B1 cell value is 10.
+ * WIN32OLE.setproperty('property', [arg1, arg2,] val)
+ * -----
+ * Sets property of OLE object.
+ * When you want to set property with argument, you can use setproperty method.
*/
static VALUE
fole_setproperty(argc, argv, self)
@@ -2467,13 +2295,9 @@ fole_setproperty(argc, argv, self)
}
/*
- * call-seq:
- * WIN32OLE['property']
- *
- * Returns property of OLE object.
- *
- * excel = WIN32OLE.new('Excel.Application')
- * puts excel['Visible'] # => false
+ * WIN32OLE['property']
+ * -----
+ * Returns property of OLE object.
*/
static VALUE
fole_getproperty(self, property)
@@ -2519,7 +2343,7 @@ ole_propertyput(self, property, value)
if(FAILED(hr)) {
ole_raise(hr, eWIN32OLE_RUNTIME_ERROR,
- "unknown property or method: `%s'",
+ "Unknown property or method: `%s'",
StringValuePtr(property));
}
/* set property value */
@@ -2538,15 +2362,6 @@ ole_propertyput(self, property, value)
return Qnil;
}
-/*
- * call-seq:
- * WIN32OLE#ole_free
- *
- * invokes Release method of Dispatch interface of WIN32OLE object.
- * Usually, you do not need to call this method because Release method
- * called automatically when WIN32OLE object garbaged.
- *
- */
static VALUE
fole_free(self)
VALUE self;
@@ -2586,18 +2401,9 @@ ole_ienum_free(pEnumV)
}
/*
- * call-seq:
- * WIN32OLE#each {|i|...}
- *
- * Iterates over each item of OLE collection which has IEnumVARIANT interface.
- *
- * excel = WIN32OLE.new('Excel.Application')
- * book = excel.workbooks.add
- * sheets = book.worksheets(1)
- * cells = sheets.cells("A1:A5")
- * cells.each do |cell|
- * cell.value = 10
- * end
+ * WIN32OLE#each {|i|...}
+ * -----
+ * Iterates over each item of OLE collection which has IEnumVARIANT interface.
*/
static VALUE
fole_each(self)
@@ -2630,7 +2436,7 @@ fole_each(self)
if (FAILED(hr)) {
VariantClear(&result);
- ole_raise(hr, eWIN32OLE_RUNTIME_ERROR, "failed to get IEnum Interface");
+ ole_raise(hr, eWIN32OLE_RUNTIME_ERROR, "Failed to get IEnum Interface");
}
if (V_VT(&result) == VT_UNKNOWN)
@@ -2643,7 +2449,7 @@ fole_each(self)
(void**)&pEnum);
if (FAILED(hr) || !pEnum) {
VariantClear(&result);
- ole_raise(hr, rb_eRuntimeError, "failed to get IEnum Interface");
+ ole_raise(hr, rb_eRuntimeError, "Failed to get IEnum Interface");
}
VariantClear(&result);
@@ -2652,10 +2458,9 @@ fole_each(self)
}
/*
- * call-seq:
- * WIN32OLE#method_missing(id [,arg1, arg2, ...])
- *
- * Calls WIN32OLE#invoke method.
+ * WIN32OLE#method_missing(id [,arg1, arg2, ...])
+ * ----
+ * Calls WIN32OLE#invoke method.
*/
static VALUE
fole_missing(argc, argv, self)
@@ -2669,7 +2474,7 @@ fole_missing(argc, argv, self)
id = rb_to_id(argv[0]);
mname = rb_id2name(id);
if(!mname) {
- rb_raise(rb_eRuntimeError, "fail: unknown method or property");
+ rb_raise(rb_eRuntimeError, "Fail: unknown method or property");
}
n = strlen(mname);
if(mname[n-1] == '=') {
@@ -2699,7 +2504,7 @@ ole_method_sub(self, pOwnerTypeInfo, pTypeInfo, name)
VALUE method = Qnil;
hr = OLE_GET_TYPEATTR(pTypeInfo, &pTypeAttr);
if (FAILED(hr)) {
- ole_raise(hr, eWIN32OLE_RUNTIME_ERROR, "failed to GetTypeAttr");
+ ole_raise(hr, eWIN32OLE_RUNTIME_ERROR, "Failed to GetTypeAttr");
}
for(i = 0; i < pTypeAttr->cFuncs && method == Qnil; i++) {
hr = pTypeInfo->lpVtbl->GetFuncDesc(pTypeInfo, i, &pFuncDesc);
@@ -2738,7 +2543,7 @@ olemethod_from_typeinfo(self, pTypeInfo, name)
VALUE method = Qnil;
hr = OLE_GET_TYPEATTR(pTypeInfo, &pTypeAttr);
if (FAILED(hr)) {
- ole_raise(hr, eWIN32OLE_RUNTIME_ERROR, "failed to GetTypeAttr");
+ ole_raise(hr, eWIN32OLE_RUNTIME_ERROR, "Failed to GetTypeAttr");
}
method = ole_method_sub(self, 0, pTypeInfo, name);
if (method != Qnil) {
@@ -2774,7 +2579,7 @@ ole_methods_sub(pOwnerTypeInfo, pTypeInfo, methods, mask)
WORD i;
hr = OLE_GET_TYPEATTR(pTypeInfo, &pTypeAttr);
if (FAILED(hr)) {
- ole_raise(hr, eWIN32OLE_RUNTIME_ERROR, "failed to GetTypeAttr");
+ ole_raise(hr, eWIN32OLE_RUNTIME_ERROR, "Failed to GetTypeAttr");
}
for(i = 0; i < pTypeAttr->cFuncs; i++) {
pstr = NULL;
@@ -2815,7 +2620,7 @@ ole_methods_from_typeinfo(pTypeInfo, mask)
VALUE methods = rb_ary_new();
hr = OLE_GET_TYPEATTR(pTypeInfo, &pTypeAttr);
if (FAILED(hr)) {
- ole_raise(hr, eWIN32OLE_RUNTIME_ERROR, "failed to GetTypeAttr");
+ ole_raise(hr, eWIN32OLE_RUNTIME_ERROR, "Failed to GetTypeAttr");
}
ole_methods_sub(0, pTypeInfo, methods, mask);
@@ -2848,7 +2653,7 @@ typeinfo_from_ole(pole, ppti)
HRESULT hr = pole->pDispatch->lpVtbl->GetTypeInfo(pole->pDispatch,
0, lcid, &pTypeInfo);
if(FAILED(hr)) {
- ole_raise(hr, rb_eRuntimeError, "failed to GetTypeInfo");
+ ole_raise(hr, rb_eRuntimeError, "Failed to GetTypeInfo");
}
hr = pTypeInfo->lpVtbl->GetDocumentation(pTypeInfo,
-1,
@@ -2858,7 +2663,7 @@ typeinfo_from_ole(pole, ppti)
hr = pTypeInfo->lpVtbl->GetContainingTypeLib(pTypeInfo, &pTypeLib, &i);
OLE_RELEASE(pTypeInfo);
if (FAILED(hr)) {
- ole_raise(hr, rb_eRuntimeError, "failed to GetContainingTypeLib");
+ ole_raise(hr, rb_eRuntimeError, "Failed to GetContainingTypeLib");
}
count = pTypeLib->lpVtbl->GetTypeInfoCount(pTypeLib);
for (i = 0; i < count; i++) {
@@ -2898,15 +2703,9 @@ ole_methods(self,mask)
}
/*
- * call-seq:
- * WIN32OLE#ole_methods
- *
- * Returns the array of WIN32OLE_METHOD object.
- * The element is OLE method of WIN32OLE object.
- *
- * excel = WIN32OLE.new('Excel.Application')
- * methods = excel.ole_methods
- *
+ * WIN32OLE#ole_methods
+ * ----
+ * Returns OLE methods
*/
static VALUE
fole_methods( self )
@@ -2916,14 +2715,9 @@ fole_methods( self )
}
/*
- * call-seq:
- * WIN32OLE#ole_get_methods
- *
- * Returns the array of WIN32OLE_METHOD object .
- * The element of the array is property (gettable) of WIN32OLE object.
- *
- * excel = WIN32OLE.new('Excel.Application')
- * properties = excel.ole_get_methods
+ * WIN32OLE#ole_get_methods
+ * ----
+ * Returns get properties.
*/
static VALUE
fole_get_methods( self )
@@ -2933,14 +2727,9 @@ fole_get_methods( self )
}
/*
- * call-seq:
- * WIN32OLE#ole_put_methods
- *
- * Returns the array of WIN32OLE_METHOD object .
- * The element of the array is property (settable) of WIN32OLE object.
- *
- * excel = WIN32OLE.new('Excel.Application')
- * properties = excel.ole_put_methods
+ * WIN32OLE#ole_put_methods
+ * ----
+ * Returns put properties.
*/
static VALUE
fole_put_methods( self )
@@ -2950,15 +2739,9 @@ fole_put_methods( self )
}
/*
- * call-seq:
- * WIN32OLE#ole_func_methods
- *
- * Returns the array of WIN32OLE_METHOD object .
- * The element of the array is functional method of WIN32OLE object.
- *
- * excel = WIN32OLE.new('Excel.Application')
- * properties = excel.ole_func_methods
- *
+ * WIN32OLE#ole_func_methods
+ * ---
+ * Returns OLE func methods.
*/
static VALUE
fole_func_methods( self )
@@ -2968,13 +2751,9 @@ fole_func_methods( self )
}
/*
- * call-seq:
- * WIN32OLE#ole_obj_help
- *
- * Returns WIN32OLE_TYPE object.
- *
- * excel = WIN32OLE.new('Excel.Application')
- * tobj = excel.ole_obj_help
+ * WIN32OLE#ole_obj_help
+ * ----
+ * Returns WIN32OLE_TYPE object.
*/
static VALUE
fole_obj_help( self )
@@ -2993,12 +2772,12 @@ fole_obj_help( self )
hr = pole->pDispatch->lpVtbl->GetTypeInfo( pole->pDispatch, 0, lcid, &pTypeInfo );
if(FAILED(hr)) {
- ole_raise(hr, rb_eRuntimeError, "failed to GetTypeInfo");
+ ole_raise(hr, rb_eRuntimeError, "Failed to GetTypeInfo");
}
hr = pTypeInfo->lpVtbl->GetContainingTypeLib( pTypeInfo, &pTypeLib, &index );
if(FAILED(hr)) {
OLE_RELEASE(pTypeInfo);
- ole_raise(hr, rb_eRuntimeError, "failed to GetContainingTypeLib");
+ ole_raise(hr, rb_eRuntimeError, "Failed to GetContainingTypeLib");
}
hr = pTypeLib->lpVtbl->GetDocumentation( pTypeLib, index,
&bstr, NULL, NULL, NULL);
@@ -3211,15 +2990,10 @@ ole_typedesc2val(pTypeInfo, pTypeDesc, typedetails)
}
/*
- * call-seq:
- * WIN32OLE#ole_method_help(method)
- *
- * Returns WIN32OLE_METHOD object corresponding with method
- * specified by 1st argument.
- *
- * excel = WIN32OLE.new('Excel.Application')
- * method = excel.ole_method_help('Quit')
- *
+ * WIN32OLE#ole_method_help(method)
+ * -----
+ * Returns WIN32OLE_METHOD object corresponding with method
+ * specified by 1st argument.
*/
static VALUE
fole_method_help( self, cmdname )
@@ -3236,21 +3010,20 @@ fole_method_help( self, cmdname )
OLEData_Get_Struct(self, pole);
hr = typeinfo_from_ole(pole, &pTypeInfo);
if(FAILED(hr))
- ole_raise(hr, rb_eRuntimeError, "failed to get ITypeInfo");
+ ole_raise(hr, rb_eRuntimeError, "Failed to get ITypeInfo");
method = folemethod_s_allocate(cWIN32OLE_METHOD);
obj = olemethod_from_typeinfo(method, pTypeInfo, cmdname);
OLE_RELEASE(pTypeInfo);
if (obj == Qnil)
- rb_raise(eWIN32OLE_RUNTIME_ERROR, "not found %s",
+ rb_raise(eWIN32OLE_RUNTIME_ERROR, "Not found %s",
StringValuePtr(cmdname));
return obj;
}
/*
- * call-seq:
- * WIN32OLE_TYPE.ole_classes(typelib)
- *
- * Returns array of WIN32OLE_TYPE objects defined by the <i>typelib</i> type library.
+ * WIN32OLE.ole_classes(typelibrary)
+ * ----
+ * Returns array of WIN32OLE_TYPE objects defined by type library.
*/
static VALUE
foletype_s_ole_classes(self, typelib)
@@ -3272,7 +3045,7 @@ foletype_s_ole_classes(self, typelib)
pbuf = ole_mb2wc(StringValuePtr(file), -1);
hr = LoadTypeLibEx(pbuf, REGKIND_NONE, &pTypeLib);
if (FAILED(hr))
- ole_raise(hr, eWIN32OLE_RUNTIME_ERROR, "failed to LoadTypeLibEx");
+ ole_raise(hr, eWIN32OLE_RUNTIME_ERROR, "Failed to LoadTypeLibEx");
SysFreeString(pbuf);
ole_classes_from_typelib(pTypeLib, classes);
OLE_RELEASE(pTypeLib);
@@ -3283,11 +3056,9 @@ foletype_s_ole_classes(self, typelib)
}
/*
- * call-seq:
- * WIN32OLE_TYPE.typelibs
- *
- * Returns array of type libraries.
- *
+ * WIN32OLE_TYPE.typelibs
+ * ----
+ * Returns array of type libraries.
*/
static VALUE
foletype_s_typelibs(self)
@@ -3332,10 +3103,9 @@ foletype_s_typelibs(self)
}
/*
- * call-seq:
- * WIN32OLE_TYPE.progids
- *
- * Returns array of ProgID.
+ * WIN32OLE_TYPE.progids
+ * ---
+ * Returns array of ProgID.
*/
static VALUE
foletype_s_progids(self)
@@ -3430,23 +3200,6 @@ oleclass_from_typelib(self, pTypeLib, oleclass)
return found;
}
-/*
- * Document-class: WIN32OLE_TYPE
- *
- * <code>WIN32OLE_TYPE</code> objects represent OLE type libarary information.
- */
-
-/*
- * call-seq:
- * WIN32OLE_TYPE.new(typelib, ole_class) -> WIN32OLE_TYPE object
- *
- * Returns a new WIN32OLE_TYPE object.
- * The first argument <i>typelib</i> specifies OLE type library name.
- * The second argument specifies OLE class name.
- *
- * WIN32OLE_TYPE.new('Microsoft Excel 9.0 Object Library', 'Application')
- * # => WIN32OLE_TYPE object of Application class of Excel.
- */
static VALUE
foletype_initialize(self, typelib, oleclass)
VALUE self;
@@ -3467,11 +3220,11 @@ foletype_initialize(self, typelib, oleclass)
pbuf = ole_mb2wc(StringValuePtr(file), -1);
hr = LoadTypeLibEx(pbuf, REGKIND_NONE, &pTypeLib);
if (FAILED(hr))
- ole_raise(hr, eWIN32OLE_RUNTIME_ERROR, "failed to LoadTypeLibEx");
+ ole_raise(hr, eWIN32OLE_RUNTIME_ERROR, "Failed to LoadTypeLibEx");
SysFreeString(pbuf);
if (oleclass_from_typelib(self, pTypeLib, oleclass) == Qfalse) {
OLE_RELEASE(pTypeLib);
- rb_raise(eWIN32OLE_RUNTIME_ERROR, "not found `%s` in `%s`",
+ rb_raise(eWIN32OLE_RUNTIME_ERROR, "Not found `%s` in `%s`",
StringValuePtr(oleclass), StringValuePtr(typelib));
}
OLE_RELEASE(pTypeLib);
@@ -3479,12 +3232,9 @@ foletype_initialize(self, typelib, oleclass)
}
/*
- * call-seq:
- * WIN32OLE_TYPE#name #=> OLE type name
- *
- * Returns OLE type name.
- * tobj = WIN32OLE_TYPE.new('Microsoft Excel 9.0 Object Library', 'Application')
- * puts tobj.name # => Application
+ * WIN32OLE_TYPE#name
+ * ---
+ * Returns name.
*/
static VALUE
foletype_name(self)
@@ -3541,12 +3291,9 @@ ole_ole_type(pTypeInfo)
}
/*
- * call-seq:
- * WIN32OLE_TYPE#ole_type #=> OLE type string.
- *
- * returns type of OLE class.
- * tobj = WIN32OLE_TYPE.new('Microsoft Excel 9.0 Object Library', 'Application')
- * puts tobj.ole_type # => Class
+ * WIN32OLE_TYPE#ole_type
+ * ----
+ * returns type of class.
*/
static VALUE
foletype_ole_type(self)
@@ -3578,12 +3325,9 @@ ole_type_guid(pTypeInfo)
}
/*
- * call-seq:
- * WIN32OLE_TYPE#guid #=> GUID
- *
- * Returns GUID.
- * tobj = WIN32OLE_TYPE.new('Microsoft Excel 9.0 Object Library', 'Application')
- * puts tobj.guid # => {00024500-0000-0000-C000-000000000046}
+ * WIN32OLE_TYPE#guid
+ * ----
+ * Returns GUID.
*/
static VALUE
foletype_guid(self)
@@ -3613,12 +3357,9 @@ ole_type_progid(pTypeInfo)
}
/*
- * call-seq:
- * WIN32OLE_TYPE#progid #=> ProgID
- *
+ * WIN32OLE_TYPE#progid
+ * ----
* Returns ProgID if it exists. If not found, then returns nil.
- * tobj = WIN32OLE_TYPE.new('Microsoft Excel 9.0 Object Library', 'Application')
- * puts tobj.progid # => Excel.Application.9
*/
static VALUE
foletype_progid(self)
@@ -3650,12 +3391,9 @@ ole_type_visible(pTypeInfo)
}
/*
- * call-seq:
- * WIN32OLE_TYPE#visible #=> true or false
- *
- * Returns true if the OLE class is public.
- * tobj = WIN32OLE_TYPE.new('Microsoft Excel 9.0 Object Library', 'Application')
- * puts tobj.visible # => true
+ * WIN32OLE_TYPE#visible
+ * ----
+ * returns true if the OLE class is public.
*/
static VALUE
foletype_visible(self)
@@ -3675,19 +3413,16 @@ ole_type_major_version(pTypeInfo)
HRESULT hr;
hr = OLE_GET_TYPEATTR(pTypeInfo, &pTypeAttr);
if (FAILED(hr))
- ole_raise(hr, eWIN32OLE_RUNTIME_ERROR, "failed to GetTypeAttr");
+ ole_raise(hr, eWIN32OLE_RUNTIME_ERROR, "Failed to GetTypeAttr");
ver = INT2FIX(pTypeAttr->wMajorVerNum);
OLE_RELEASE_TYPEATTR(pTypeInfo, pTypeAttr);
return ver;
}
/*
- * call-seq:
- * WIN32OLE_TYPE#major_version
- *
- * Returns major version.
- * tobj = WIN32OLE_TYPE.new('Microsoft Word 10.0 Object Library', 'Documents')
- * puts tobj.major_version # => 8
+ * WIN32OLE_TYPE#major_version
+ * ----
+ * Returns major version.
*/
static VALUE
foletype_major_version(self)
@@ -3707,19 +3442,16 @@ ole_type_minor_version(pTypeInfo)
HRESULT hr;
hr = OLE_GET_TYPEATTR(pTypeInfo, &pTypeAttr);
if (FAILED(hr))
- ole_raise(hr, eWIN32OLE_RUNTIME_ERROR, "failed to GetTypeAttr");
+ ole_raise(hr, eWIN32OLE_RUNTIME_ERROR, "Failed to GetTypeAttr");
ver = INT2FIX(pTypeAttr->wMinorVerNum);
OLE_RELEASE_TYPEATTR(pTypeInfo, pTypeAttr);
return ver;
}
/*
- * call-seq:
- * WIN32OLE_TYPE#minor_version #=> OLE minor version
- *
- * Returns minor version.
- * tobj = WIN32OLE_TYPE.new('Microsoft Word 10.0 Object Library', 'Documents')
- * puts tobj.minor_version # => 2
+ * WIN32OLE_TYPE#minor_version
+ * ----
+ * Returns minor version.
*/
static VALUE
foletype_minor_version(self)
@@ -3739,20 +3471,16 @@ ole_type_typekind(pTypeInfo)
HRESULT hr;
hr = OLE_GET_TYPEATTR(pTypeInfo, &pTypeAttr);
if (FAILED(hr))
- ole_raise(hr, eWIN32OLE_RUNTIME_ERROR, "failed to GetTypeAttr");
+ ole_raise(hr, eWIN32OLE_RUNTIME_ERROR, "Failed to GetTypeAttr");
typekind = INT2FIX(pTypeAttr->typekind);
OLE_RELEASE_TYPEATTR(pTypeInfo, pTypeAttr);
return typekind;
}
/*
- * call-seq:
- * WIN32OLE_TYPE#typekind #=> number of type.
- *
- * Returns number which represents type.
- * tobj = WIN32OLE_TYPE.new('Microsoft Word 10.0 Object Library', 'Documents')
- * puts tobj.typekind # => 4
- *
+ * WIN32OLE_TYPE#typekind
+ * ----
+ * Returns number which represents type.
*/
static VALUE
foletype_typekind(self)
@@ -3777,12 +3505,9 @@ ole_type_helpstring(pTypeInfo)
}
/*
- * call-seq:
- * WIN32OLE_TYPE#helpstring #=> help string.
- *
- * Returns help string.
- * tobj = WIN32OLE_TYPE.new('Microsoft Internet Controls', 'IWebBrowser')
- * puts tobj.helpstring # => Web Browser interface
+ * WIN32OLE_TYPE#helpstring
+ * ---
+ * Returns help string.
*/
static VALUE
foletype_helpstring(self)
@@ -3813,13 +3538,9 @@ ole_type_src_type(pTypeInfo)
}
/*
- * call-seq:
- * WIN32OLE_TYPE#src_type #=> OLE source class
- *
- * Returns source class when the OLE class is 'Alias'.
- * tobj = WIN32OLE_TYPE.new('Microsoft Office 9.0 Object Library', 'MsoRGBType')
- * puts tobj.src_type # => I4
- *
+ * WIN32OLE_TYPE#src_type
+ * ----
+ * Returns source class when the OLE class is 'Alias'.
*/
static VALUE
foletype_src_type(self)
@@ -3844,13 +3565,9 @@ ole_type_helpfile(pTypeInfo)
}
/*
- * call-seq:
- * WIN32OLE_TYPE#helpfile
- *
- * Returns helpfile path. If helpfile is not found, then returns nil.
- * tobj = WIN32OLE_TYPE.new('Microsoft Excel 9.0 Object Library', 'Worksheet')
- * puts tobj.helpfile # => C:\...\VBAXL9.CHM
- *
+ * WIN32OLE_TYPE#helpfile
+ * ----
+ * Returns helpfile
*/
static VALUE
foletype_helpfile(self)
@@ -3875,12 +3592,9 @@ ole_type_helpcontext(pTypeInfo)
}
/*
- * call-seq:
- * WIN32OLE_TYPE#helpcontext
- *
- * Returns helpcontext. If helpcontext is not found, then returns nil.
- * tobj = WIN32OLE_TYPE.new('Microsoft Excel 9.0 Object Library', 'Worksheet')
- * puts tobj.helpfile # => 131185
+ * WIN32OLE_TYPE#helpcontext
+ * ---
+ * Returns helpcontext.
*/
static VALUE
foletype_helpcontext(self)
@@ -3907,7 +3621,7 @@ ole_variables(pTypeInfo)
VALUE variables = rb_ary_new();
hr = OLE_GET_TYPEATTR(pTypeInfo, &pTypeAttr);
if (FAILED(hr)) {
- ole_raise(hr, eWIN32OLE_RUNTIME_ERROR, "failed to GetTypeAttr");
+ ole_raise(hr, eWIN32OLE_RUNTIME_ERROR, "Failed to GetTypeAttr");
}
for(i = 0; i < pTypeAttr->cVars; i++) {
@@ -3937,24 +3651,9 @@ ole_variables(pTypeInfo)
}
/*
- * call-seq:
- * WIN32OLE_TYPE#variables
- *
- * Returns array of WIN32OLE_VARIABLE objects which represent variables
- * defined in OLE class.
- * tobj = WIN32OLE_TYPE.new('Microsoft Excel 9.0 Object Library', 'XlSheetType')
- * vars = tobj.variables
- * vars.each do |v|
- * puts "#{v.name} = #{v.value}"
- * end
- *
- * The result of above sample script is follows:
- * xlChart = -4109
- * xlDialogSheet = -4116
- * xlExcel4IntlMacroSheet = 4
- * xlExcel4MacroSheet = 3
- * xlWorksheet = -4167
- *
+ * WIN32OLE_TYPE#variables
+ * ----
+ * Returns array of variables defined in OLE class.
*/
static VALUE
foletype_variables(self)
@@ -3966,16 +3665,9 @@ foletype_variables(self)
}
/*
- * call-seq:
- * WIN32OLE_TYPE#ole_methods # the array of WIN32OLE_METHOD objects.
- *
- * Returns array of WIN32OLE_METHOD objects which represent OLE method defined in
- * OLE type library.
- * tobj = WIN32OLE_TYPE.new('Microsoft Excel 9.0 Object Library', 'Worksheet')
- * methods = tobj.ole_methods.collect{|m|
- * m.name
- * }
- * # => ['Activate', 'Copy', 'Delete',....]
+ * WIN32OLE_TYPE#ole_methods
+ * ----
+ * Returns array of WIN32OLE_METHOD objects.
*/
static VALUE
foletype_methods(argc, argv, self)
@@ -3989,30 +3681,9 @@ foletype_methods(argc, argv, self)
}
/*
- * Document-class: WIN32OLE_VARIABLE
- *
- * <code>WIN32OLE_VARIABLE</code> objects represent OLE variable information.
- */
-
-/*
- * call-seq:
- * WIN32OLE_VARIABLE#name
- *
- * Returns the name of variable.
- *
- * tobj = WIN32OLE_TYPE.new('Microsoft Excel 9.0 Object Library', 'XlSheetType')
- * variables = tobj.variables
- * variables.each do |variable|
- * puts "#{variable.name}"
- * end
- *
- * The result of above script is following:
- * xlChart
- * xlDialogSheet
- * xlExcel4IntlMacroSheet
- * xlExcel4MacroSheet
- * xlWorksheet
- *
+ * WIN32OLE_VARIABLE#name
+ * ---
+ * Returns the name.
*/
static VALUE
folevariable_name(self)
@@ -4030,31 +3701,16 @@ static ole_variable_ole_type(pTypeInfo, var_index)
VALUE type;
hr = pTypeInfo->lpVtbl->GetVarDesc(pTypeInfo, var_index, &pVarDesc);
if (FAILED(hr))
- ole_raise(hr, eWIN32OLE_RUNTIME_ERROR, "failed to GetVarDesc");
+ ole_raise(hr, eWIN32OLE_RUNTIME_ERROR, "Failed to GetVarDesc");
type = ole_typedesc2val(pTypeInfo, &(pVarDesc->elemdescVar.tdesc), Qnil);
pTypeInfo->lpVtbl->ReleaseVarDesc(pTypeInfo, pVarDesc);
return type;
}
/*
- * call-seq:
- * WIN32OLE_VARIABLE#ole_type
- *
- * Returns OLE type string.
- *
- * tobj = WIN32OLE_TYPE.new('Microsoft Excel 9.0 Object Library', 'XlSheetType')
- * variables = tobj.variables
- * variables.each do |variable|
- * puts "#{variable.ole_type} #{variable.name}"
- * end
- *
- * The result of above script is following:
- * INT xlChart
- * INT xlDialogSheet
- * INT xlExcel4IntlMacroSheet
- * INT xlExcel4MacroSheet
- * INT xlWorksheet
- *
+ * WIN32OLE_VARIABLE#ole_type
+ * ----
+ * Returns type.
*/
static VALUE
folevariable_ole_type(self)
@@ -4074,23 +3730,16 @@ static ole_variable_ole_type_detail(pTypeInfo, var_index)
VALUE type = rb_ary_new();
hr = pTypeInfo->lpVtbl->GetVarDesc(pTypeInfo, var_index, &pVarDesc);
if (FAILED(hr))
- ole_raise(hr, eWIN32OLE_RUNTIME_ERROR, "failed to GetVarDesc");
+ ole_raise(hr, eWIN32OLE_RUNTIME_ERROR, "Failed to GetVarDesc");
ole_typedesc2val(pTypeInfo, &(pVarDesc->elemdescVar.tdesc), type);
pTypeInfo->lpVtbl->ReleaseVarDesc(pTypeInfo, pVarDesc);
return type;
}
/*
- * call-seq:
- * WIN32OLE_VARIABLE#ole_type_detail
- *
- * Returns detail information of type. The information is array of type.
- *
- * tobj = WIN32OLE_TYPE.new('DirectX 7 for Visual Basic Type Library', 'D3DCLIPSTATUS')
- * variable = tobj.variables.find {|variable| variable.name == 'lFlags'}
- * tdetail = variable.ole_type_detail
- * p tdetail # => ["USERDEFINED", "CONST_D3DCLIPSTATUSFLAGS"]
- *
+ * WIN32OLE_VARIABLE#ole_type_detail
+ * ---
+ * Returns detail information of type. The information is array of type.
*/
static VALUE
folevariable_ole_type_detail(self)
@@ -4118,25 +3767,10 @@ static ole_variable_value(pTypeInfo, var_index)
}
/*
- * call-seq:
- * WIN32OLE_VARIABLE#value
- *
- * Returns value if value is exists. If the value does not exist,
- * this method returns nil.
- *
- * tobj = WIN32OLE_TYPE.new('Microsoft Excel 9.0 Object Library', 'XlSheetType')
- * variables = tobj.variables
- * variables.each do |variable|
- * puts "#{variable.name} = #{variable.value}"
- * end
- *
- * The result of above script is following:
- * xlChart = -4109
- * xlDialogSheet = -4116
- * xlExcel4IntlMacroSheet = 4
- * xlExcel4MacroSheet = 3
- * xlWorksheet = -4167
- *
+ * WIN32OLE_VARIABLE#value
+ * ----
+ * Returns value if value is exists. If the value does not exist,
+ * this method returns nil.
*/
static VALUE
folevariable_value(self)
@@ -4167,24 +3801,9 @@ static ole_variable_visible(pTypeInfo, var_index)
}
/*
- * call-seq:
- * WIN32OLE_VARIABLE#visible?
- *
- * Returns true if the variable is public.
- *
- * tobj = WIN32OLE_TYPE.new('Microsoft Excel 9.0 Object Library', 'XlSheetType')
- * variables = tobj.variables
- * variables.each do |variable|
- * puts "#{variable.name} #{variable.visible?}"
- * end
- *
- * The result of above script is following:
- * xlChart true
- * xlDialogSheet true
- * xlExcel4IntlMacroSheet true
- * xlExcel4MacroSheet true
- * xlWorksheet true
- *
+ * WIN32OLE_VARIABLE#visible?
+ * ----
+ * Returns true if the variable is public.
*/
static VALUE
folevariable_visible(self)
@@ -4227,23 +3846,9 @@ ole_variable_kind(pTypeInfo, var_index)
}
/*
- * call-seq:
- * WIN32OLE_VARIABLE#variable_kind
- *
+ * WIN32OLE_VARIABLE#variable_kind
+ * ----
* Returns variable kind string.
- *
- * tobj = WIN32OLE_TYPE.new('Microsoft Excel 9.0 Object Library', 'XlSheetType')
- * variables = tobj.variables
- * variables.each do |variable|
- * puts "#{variable.name} #{variable.variable_kind}"
- * end
- *
- * The result of above script is following:
- * xlChart CONSTANT
- * xlDialogSheet CONSTANT
- * xlExcel4IntlMacroSheet CONSTANT
- * xlExcel4MacroSheet CONSTANT
- * xlWorksheet CONSTANT
*/
static VALUE
folevariable_variable_kind(self)
@@ -4271,22 +3876,9 @@ ole_variable_varkind(pTypeInfo, var_index)
}
/*
- * call-seq:
- * WIN32OLE_VARIABLE#varkind
- *
- * Returns the number which represents variable kind.
- * tobj = WIN32OLE_TYPE.new('Microsoft Excel 9.0 Object Library', 'XlSheetType')
- * variables = tobj.variables
- * variables.each do |variable|
- * puts "#{variable.name} #{variable.varkind}"
- * end
- *
- * The result of above script is following:
- * xlChart 2
- * xlDialogSheet 2
- * xlExcel4IntlMacroSheet 2
- * xlExcel4MacroSheet 2
- * xlWorksheet 2
+ * WIN32OLE_VARIABLE#varkind
+ * ----
+ * Returns the number which represents variable kind.
*/
static VALUE
folevariable_varkind(self)
@@ -4297,12 +3889,6 @@ folevariable_varkind(self)
return ole_variable_varkind(pvar->pTypeInfo, pvar->index);
}
-/*
- * Document-class: WIN32OLE_METHOD
- *
- * <code>WIN32OLE_METHOD</code> objects represent OLE method information.
- */
-
static VALUE
olemethod_set_member(self, pTypeInfo, pOwnerTypeInfo, index, name)
VALUE self;
@@ -4337,19 +3923,6 @@ folemethod_s_allocate(klass)
return obj;
}
-/*
- * call-seq:
- * WIN32OLE_METHOD.new(ole_type, method) -> WIN32OLE_METHOD object
- *
- * Returns a new WIN32OLE_METHOD object which represents the information
- * about OLE method.
- * The first argument <i>ole_type</i> specifies WIN32OLE_TYPE object.
- * The second argument <i>method</i> specifies OLE method name defined OLE class
- * which represents WIN32OLE_TYPE object.
- *
- * tobj = WIN32OLE_TYPE.new('Microsoft Excel 9.0 Object Library', 'Workbook')
- * method = WIN32OLE_METHOD.new(tobj, 'SaveAs')
- */
static VALUE
folemethod_initialize(self, oletype, method)
VALUE self;
@@ -4363,26 +3936,20 @@ folemethod_initialize(self, oletype, method)
Data_Get_Struct(oletype, struct oletypedata, ptype);
obj = olemethod_from_typeinfo(self, ptype->pTypeInfo, method);
if (obj == Qnil) {
- rb_raise(eWIN32OLE_RUNTIME_ERROR, "not found %s",
+ rb_raise(eWIN32OLE_RUNTIME_ERROR, "Not found %s",
StringValuePtr(method));
}
}
else {
- rb_raise(rb_eTypeError, "1st argument should be WIN32OLE_TYPE object");
+ rb_raise(rb_eTypeError, "1st argument should be WIN32OLE_TYPE object.");
}
return obj;
}
/*
- * call-seq
- * WIN32OLE_METHOD#name
- *
- * Returns the name of the method.
- *
- * tobj = WIN32OLE_TYPE.new('Microsoft Excel 9.0 Object Library', 'Workbook')
- * method = WIN32OLE_METHOD.new(tobj, 'SaveAs')
- * puts method.name # => SaveAs
- *
+ * WIN32OLE_METHOD#name
+ * ----
+ * Returns the name of the method.
*/
static VALUE
folemethod_name(self)
@@ -4402,7 +3969,7 @@ ole_method_return_type(pTypeInfo, method_index)
hr = pTypeInfo->lpVtbl->GetFuncDesc(pTypeInfo, method_index, &pFuncDesc);
if (FAILED(hr))
- ole_raise(hr, eWIN32OLE_RUNTIME_ERROR, "failed to GetFuncDesc");
+ ole_raise(hr, eWIN32OLE_RUNTIME_ERROR, "Failed to GetFuncDesc");
type = ole_typedesc2val(pTypeInfo, &(pFuncDesc->elemdescFunc.tdesc), Qnil);
pTypeInfo->lpVtbl->ReleaseFuncDesc(pTypeInfo, pFuncDesc);
@@ -4410,14 +3977,9 @@ ole_method_return_type(pTypeInfo, method_index)
}
/*
- * call-seq:
- * WIN32OLE_METHOD#return_type
- *
- * Returns string of return value type of method.
- * tobj = WIN32OLE_TYPE.new('Microsoft Excel 9.0 Object Library', 'Workbooks')
- * method = WIN32OLE_METHOD.new(tobj, 'Add')
- * puts method.return_type # => Workbook
- *
+ * WIN32OLE_METHOD#return_type
+ * ----
+ * Returns string of return value type of method.
*/
static VALUE
folemethod_return_type(self)
@@ -4439,7 +4001,7 @@ ole_method_return_vtype(pTypeInfo, method_index)
hr = pTypeInfo->lpVtbl->GetFuncDesc(pTypeInfo, method_index, &pFuncDesc);
if (FAILED(hr))
- ole_raise(hr, eWIN32OLE_RUNTIME_ERROR, "failed to GetFuncDesc");
+ ole_raise(hr, eWIN32OLE_RUNTIME_ERROR, "Failed to GetFuncDesc");
vt = INT2FIX(pFuncDesc->elemdescFunc.tdesc.vt);
pTypeInfo->lpVtbl->ReleaseFuncDesc(pTypeInfo, pFuncDesc);
@@ -4447,14 +4009,9 @@ ole_method_return_vtype(pTypeInfo, method_index)
}
/*
- * call-seq:
- * WIN32OLE_METHOD#return_vtype
- *
- * Returns number of return value type of method.
- * tobj = WIN32OLE_TYPE.new('Microsoft Excel 9.0 Object Library', 'Workbooks')
- * method = WIN32OLE_METHOD.new(tobj, 'Add')
- * puts method.return_vtype # => 26
- *
+ * WIN32OLE_METHOD#return_vtype
+ * ----
+ * Returns number of return value type of method.
*/
static VALUE
folemethod_return_vtype(self)
@@ -4484,14 +4041,10 @@ ole_method_return_type_detail(pTypeInfo, method_index)
}
/*
- * call-seq:
- * WIN32OLE_METHOD#return_type_detail
- *
- * Returns detail information of return value type of method.
- * The information is array.
- * tobj = WIN32OLE_TYPE.new('Microsoft Excel 9.0 Object Library', 'Workbooks')
- * method = WIN32OLE_METHOD.new(tobj, 'Add')
- * p method.return_type_detail # => ["PTR", "USERDEFINED", "Workbook"]
+ * WIN32OLE_METHOD#return_type_detail
+ * -----
+ * Returns detail information of return value type of method.
+ * The information is array.
*/
static VALUE
folemethod_return_type_detail(self)
@@ -4512,7 +4065,7 @@ ole_method_invkind(pTypeInfo, method_index)
VALUE invkind;
hr = pTypeInfo->lpVtbl->GetFuncDesc(pTypeInfo, method_index, &pFuncDesc);
if(FAILED(hr))
- ole_raise(hr, eWIN32OLE_RUNTIME_ERROR, "failed to GetFuncDesc");
+ ole_raise(hr, eWIN32OLE_RUNTIME_ERROR, "Failed to GetFuncDesc");
invkind = INT2FIX(pFuncDesc->invkind);
pTypeInfo->lpVtbl->ReleaseFuncDesc(pTypeInfo, pFuncDesc);
return invkind;
@@ -4541,14 +4094,9 @@ ole_method_invoke_kind(pTypeInfo, method_index)
}
/*
- * call-seq:
- * WIN32OLE_MTHOD#invkind
- *
- * Returns the method invoke kind.
- * tobj = WIN32OLE_TYPE.new('Microsoft Excel 9.0 Object Library', 'Workbooks')
- * method = WIN32OLE_METHOD.new(tobj, 'Add')
- * puts method.invkind # => 1
- *
+ * WIN32OLE_MTHOD#invkind
+ * ----
+ * Returns invkind.
*/
static VALUE
folemethod_invkind(self)
@@ -4560,15 +4108,9 @@ folemethod_invkind(self)
}
/*
- * call-seq:
- * WIN32OLE_METHOD#invoke_kind
- *
- * Returns the method kind string. The string is "UNKNOWN" or "PROPERTY"
- * or "PROPERTY" or "PROPERTYGET" or "PROPERTYPUT" or "PROPERTYPPUTREF"
- * or "FUNC".
- * tobj = WIN32OLE_TYPE.new('Microsoft Excel 9.0 Object Library', 'Workbooks')
- * method = WIN32OLE_METHOD.new(tobj, 'Add')
- * puts method.invoke_kind # => "FUNC"
+ * WIN32OLE_METHOD#invoke_kind
+ * ----
+ * Returns invoke kind string.
*/
static VALUE
folemethod_invoke_kind(self)
@@ -4602,13 +4144,9 @@ ole_method_visible(pTypeInfo, method_index)
}
/*
- * call-seq:
- * WIN32OLE_METHOD#visible?
- *
- * Returns true if the method is public.
- * tobj = WIN32OLE_TYPE.new('Microsoft Excel 9.0 Object Library', 'Workbooks')
- * method = WIN32OLE_METHOD.new(tobj, 'Add')
- * puts method.visible? # => true
+ * WIN32OLE_METHOD#visible?
+ * ----
+ * Returns true if the method is public.
*/
static VALUE
folemethod_visible(self)
@@ -4686,14 +4224,9 @@ static ole_method_event(pTypeInfo, method_index, method_name)
}
/*
- * call-seq:
- * WIN32OLE_METHOD#event?
- *
- * Returns true if the method is event.
- * tobj = WIN32OLE_TYPE.new('Microsoft Excel 9.0 Object Library', 'Workbook')
- * method = WIN32OLE_METHOD.new(tobj, 'SheetActivate')
- * puts method.event? # => true
- *
+ * WIN32OLE_METHOD#event?
+ * ----
+ * Returns true if the method is event.
*/
static VALUE
folemethod_event(self)
@@ -4708,15 +4241,6 @@ folemethod_event(self)
rb_ivar_get(self, rb_intern("name")));
}
-/*
- * call-seq:
- * WIN32OLE_METHOD#event_interface
- *
- * Returns event interface name if the method is event.
- * tobj = WIN32OLE_TYPE.new('Microsoft Excel 9.0 Object Library', 'Workbook')
- * method = WIN32OLE_METHOD.new(tobj, 'SheetActivate')
- * puts method.event_interface # => WorkbookEvents
- */
static VALUE
folemethod_event_interface(self)
VALUE self;
@@ -4769,17 +4293,6 @@ ole_method_helpstring(pTypeInfo, method_index)
return WC2VSTR(bhelpstring);
}
-/*
- * call-seq:
- * WIN32OLE_METHOD#helpstring
- *
- * Returns help string of OLE method. If the help string is not found,
- * then the method returns nil.
- * tobj = WIN32OLE_TYPE.new('Microsoft Internet Controls', 'IWebBrowser')
- * method = WIN32OLE_METHOD.new(tobj, 'Navigate')
- * puts method.helpstring # => Navigates to a URL or file.
- *
- */
static VALUE
folemethod_helpstring(self)
VALUE self;
@@ -4804,14 +4317,9 @@ ole_method_helpfile(pTypeInfo, method_index)
}
/*
- * call-seq:
- * WIN32OLE_METHOD#helpfile
- *
- * Returns help file. If help file is not found, then
- * the method returns nil.
- * tobj = WIN32OLE_TYPE.new('Microsoft Excel 9.0 Object Library', 'Workbooks')
- * method = WIN32OLE_METHOD.new(tobj, 'Add')
- * puts method.helpfile # => C:\...\VBAXL9.CHM
+ * WIN32OLE_METHOD#helpfile
+ * ---
+ * Returns help file.
*/
static VALUE
folemethod_helpfile(self)
@@ -4838,13 +4346,9 @@ ole_method_helpcontext(pTypeInfo, method_index)
}
/*
- * call-seq:
- * WIN32OLE_METHOD#helpcontext
- *
- * Returns help context.
- * tobj = WIN32OLE_TYPE.new('Microsoft Excel 9.0 Object Library', 'Workbooks')
- * method = WIN32OLE_METHOD.new(tobj, 'Add')
- * puts method.helpcontext # => 65717
+ * WIN32OLE_METHOD#helpcontext
+ * -----
+ * Returns help context.
*/
static VALUE
folemethod_helpcontext(self)
@@ -4866,19 +4370,15 @@ ole_method_dispid(pTypeInfo, method_index)
hr = pTypeInfo->lpVtbl->GetFuncDesc(pTypeInfo, method_index, &pFuncDesc);
if (FAILED(hr))
return dispid;
- dispid = INT2NUM(pFuncDesc->memid);
+ dispid = INT2FIX(pFuncDesc->memid);
pTypeInfo->lpVtbl->ReleaseFuncDesc(pTypeInfo, pFuncDesc);
return dispid;
}
/*
- * call-seq:
- * WIN32OLE_METHOD#dispid
- *
- * Returns dispatch ID.
- * tobj = WIN32OLE_TYPE.new('Microsoft Excel 9.0 Object Library', 'Workbooks')
- * method = WIN32OLE_METHOD.new(tobj, 'Add')
- * puts method.dispid # => 181
+ * WIN32OLE_METHOD#dispid
+ * ----
+ * Returns dispatch ID.
*/
static VALUE
folemethod_dispid(self)
@@ -4906,13 +4406,9 @@ ole_method_offset_vtbl(pTypeInfo, method_index)
}
/*
- * call-seq:
- * WIN32OLE_METHOD#offset_vtbl
- *
- * Returns the offset ov VTBL.
- * tobj = WIN32OLE_TYPE.new('Microsoft Excel 9.0 Object Library', 'Workbooks')
- * method = WIN32OLE_METHOD.new(tobj, 'Add')
- * puts method.offset_vtbl # => 40
+ * WIN32OLE_METHOD#offset_vtbl
+ * ----
+ * Returns the offset ov VTBL.
*/
static VALUE
folemethod_offset_vtbl(self)
@@ -4940,14 +4436,9 @@ ole_method_size_params(pTypeInfo, method_index)
}
/*
- * call-seq:
- * WIN32OLE_METHOD#size_params
- *
- * Returns the size of arguments of the method.
- * tobj = WIN32OLE_TYPE.new('Microsoft Excel 9.0 Object Library', 'Workbook')
- * method = WIN32OLE_METHOD.new(tobj, 'SaveAs')
- * puts method.size_params # => 11
- *
+ * WIN32OLE_METHOD#size_params
+ * ----
+ * Returns the size of arguments.
*/
static VALUE
folemethod_size_params(self)
@@ -4958,6 +4449,11 @@ folemethod_size_params(self)
return ole_method_size_params(pmethod->pTypeInfo, pmethod->index);
}
+/*
+ * WIN32OLE_METHOD#size_opt_params
+ * ----
+ * Returns the size of optional parameters.
+ */
static VALUE
ole_method_size_opt_params(pTypeInfo, method_index)
ITypeInfo *pTypeInfo;
@@ -4974,15 +4470,6 @@ ole_method_size_opt_params(pTypeInfo, method_index)
return size_opt_params;
}
-/*
- * call-seq:
- * WIN32OLE_METHOD#size_opt_params
- *
- * Returns the size of optional parameters.
- * tobj = WIN32OLE_TYPE.new('Microsoft Excel 9.0 Object Library', 'Workbook')
- * method = WIN32OLE_METHOD.new(tobj, 'SaveAs')
- * puts method.size_opt_params # => 4
- */
static VALUE
folemethod_size_opt_params(self)
VALUE self;
@@ -5035,16 +4522,9 @@ ole_method_params(pTypeInfo, method_index)
}
/*
- * call-seq:
- * WIN32OLE_METHOD#params
- *
- * returns array of WIN32OLE_PARAM object corresponding with method parameters.
- * tobj = WIN32OLE_TYPE.new('Microsoft Excel 9.0 Object Library', 'Workbook')
- * method = WIN32OLE_METHOD.new(tobj, 'SaveAs')
- * p method.params # => [Filename, FileFormat, Password, WriteResPassword,
- * ReadOnlyRecommended, CreateBackup, AccessMode,
- * ConflictResolution, AddToMru, TextCodepage,
- * TextVisualLayout]
+ * WIN32OLE_METHOD#params
+ * ----
+ * returns array of WIN32OLE_PARAM object corresponding with method parameters.
*/
static VALUE
folemethod_params(self)
@@ -5056,21 +4536,9 @@ folemethod_params(self)
}
/*
- * Document-class: WIN32OLE_PARAM
- *
- * <code>WIN32OLE_PARAM</code> objects represent param information of
- * the OLE method.
- */
-
-/*
- * call-seq:
- * WIN32OLE_PARAM#name
- *
- * Returns name.
- * tobj = WIN32OLE_TYPE.new('Microsoft Excel 9.0 Object Library', 'Workbook')
- * method = WIN32OLE_METHOD.new(tobj, 'SaveAs')
- * param1 = method.params[0]
- * puts param1.name # => Filename
+ * WIN32OLE_PARAM#name
+ * ----
+ * Returns name.
*/
static VALUE
foleparam_name(self)
@@ -5097,16 +4565,6 @@ ole_param_ole_type(pTypeInfo, method_index, index)
return type;
}
-/*
- * call-seq:
- * WIN32OLE_PARAM#ole_type
- *
- * Returns OLE type of WIN32OLE_PARAM object(parameter of OLE method).
- * tobj = WIN32OLE_TYPE.new('Microsoft Excel 9.0 Object Library', 'Workbook')
- * method = WIN32OLE_METHOD.new(tobj, 'SaveAs')
- * param1 = method.params[0]
- * puts param1.ole_type # => VARIANT
- */
static VALUE
foleparam_ole_type(self)
VALUE self;
@@ -5135,16 +4593,6 @@ ole_param_ole_type_detail(pTypeInfo, method_index, index)
return typedetail;
}
-/*
- * call-seq:
- * WIN32OLE_PARAM#ole_type_detail
- *
- * Returns detail information of type of argument.
- * tobj = WIN32OLE_TYPE.new('Microsoft Excel 9.0 Object Library', 'IWorksheetFunction')
- * method = WIN32OLE_METHOD.new(tobj, 'SumIf')
- * param1 = method.params[0]
- * p param1.ole_type_detail # => ["PTR", "USERDEFINED", "Range"]
- */
static VALUE
foleparam_ole_type_detail(self)
VALUE self;
@@ -5175,14 +4623,9 @@ ole_param_flag_mask(pTypeInfo, method_index, index, mask)
}
/*
- * call-seq:
- * WIN32OLE_PARAM#input?
- *
- * Returns true if the parameter is input.
- * tobj = WIN32OLE_TYPE.new('Microsoft Excel 9.0 Object Library', 'Workbook')
- * method = WIN32OLE_METHOD.new(tobj, 'SaveAs')
- * param1 = method.params[0]
- * puts param1.input? # => true
+ * WIN32OLE_PARAM#input?
+ * ----
+ * Returns true if the parameter is input.
*/
static VALUE foleparam_input(self)
VALUE self;
@@ -5194,23 +4637,9 @@ static VALUE foleparam_input(self)
}
/*
- * call-seq:
- * WIN32OLE#output?
- *
- * Returns true if argument is output.
- * tobj = WIN32OLE_TYPE.new('Microsoft Internet Controls', 'DWebBrowserEvents')
- * method = WIN32OLE_METHOD.new(tobj, 'NewWindow')
- * method.params.each do |param|
- * puts "#{param.name} #{param.output?}"
- * end
- *
- * The result of above script is following:
- * URL false
- * Flags false
- * TargetFrameName false
- * PostData false
- * Headers false
- * Processed true
+ * WIN32OLE#output?
+ * ----
+ * Returns true if argument is output.
*/
static VALUE foleparam_output(self)
VALUE self;
@@ -5222,14 +4651,9 @@ static VALUE foleparam_output(self)
}
/*
- * call-seq:
- * WIN32OLE_PARAM#optional?
- *
- * Returns true if argument is optional.
- * tobj = WIN32OLE_TYPE.new('Microsoft Excel 9.0 Object Library', 'Workbook')
- * method = WIN32OLE_METHOD.new(tobj, 'SaveAs')
- * param1 = method.params[0]
- * puts "#{param1.name} #{param1.optional?}" # => Filename true
+ * WIN32OLE_PARAM#optional?
+ * -----
+ * Returns true if argument is output.
*/
static VALUE foleparam_optional(self)
VALUE self;
@@ -5240,17 +4664,6 @@ static VALUE foleparam_optional(self)
pparam->index, PARAMFLAG_FOPT);
}
-/*
- * call-seq:
- * WIN32OLE_PARAM#retval?
- *
- * Returns true if argument is return value.
- * tobj = WIN32OLE_TYPE.new('DirectX 7 for Visual Basic Type Library',
- * 'DirectPlayLobbyConnection')
- * method = WIN32OLE_METHOD.new(tobj, 'GetPlayerShortName')
- * param = method.params[0]
- * puts "#{param.name} #{param.retval?}" # => name true
- */
static VALUE foleparam_retval(self)
VALUE self;
{
@@ -5287,33 +4700,10 @@ ole_param_default(pTypeInfo, method_index, index)
}
/*
- * call-seq:
- * WIN32OLE_PARAM#default
- *
- * Returns default value. If the default value does not exist,
- * this method returns nil.
- * tobj = WIN32OLE_TYPE.new('Microsoft Excel 9.0 Object Library', 'Workbook')
- * method = WIN32OLE_METHOD.new(tobj, 'SaveAs')
- * method.params.each do |param|
- * if param.default
- * puts "#{param.name} (= #{param.default})"
- * else
- * puts "#{param}"
- * end
- * end
- *
- * The above script result is following:
- * Filename
- * FileFormat
- * Password
- * WriteResPassword
- * ReadOnlyRecommended
- * CreateBackup
- * AccessMode (= 1)
- * ConflictResolution
- * AddToMru
- * TextCodepage
- * TextVisualLayout
+ * WIN32OLE_PARAM#default
+ * ----
+ * Returns default value. If the default value does not exist,
+ * this method returns nil.
*/
static VALUE foleparam_default(self)
VALUE self;
@@ -5324,13 +4714,6 @@ static VALUE foleparam_default(self)
pparam->index);
}
-
-/*
- * Document-class: WIN32OLE_EVENT
- *
- * <code>WIN32OLE_EVENT</code> objects controls OLE event.
- */
-
static IEventSinkVtbl vtEventSink;
static BOOL g_IsEventSinkVtblInitialized = FALSE;
@@ -5403,35 +4786,6 @@ STDMETHODIMP EVENTSINK_GetIDsOfNames(
return DISP_E_UNKNOWNNAME;
}
-static long
-ole_search_event_at(ary, ev)
- VALUE ary;
- VALUE ev;
-{
- VALUE event;
- VALUE def_event;
- VALUE event_name;
- long i, len;
- long ret = -1;
- def_event = Qnil;
- len = RARRAY(ary)->len;
- for(i = 0; i < len; i++) {
- event = rb_ary_entry(ary, i);
- event_name = rb_ary_entry(event, 1);
- if(NIL_P(event_name) && NIL_P(ev)) {
- ret = i;
- break;
- }
- else if (TYPE(ev) == T_STRING &&
- TYPE(event_name) == T_STRING &&
- rb_str_cmp(ev, event_name) == 0) {
- ret = i;
- break;
- }
- }
- return ret;
-}
-
static VALUE
ole_search_event(ary, ev, is_default)
VALUE ary;
@@ -5441,7 +4795,7 @@ ole_search_event(ary, ev, is_default)
VALUE event;
VALUE def_event;
VALUE event_name;
- long i, len;
+ int i, len;
*is_default = FALSE;
def_event = Qnil;
len = RARRAY(ary)->len;
@@ -5639,7 +4993,6 @@ EVENTSINK_Constructor() {
pEv->m_dwCookie = 0;
pEv->pConnectionPoint = NULL;
pEv->pTypeInfo = NULL;
- pEv->ptr_freed = NULL;
return pEv;
}
@@ -5647,7 +5000,6 @@ void EVENTSINK_Destructor(
PIEVENTSINKOBJ pEVObj
) {
if(pEVObj != NULL) {
- *(pEVObj->ptr_freed) = 1;
free(pEVObj);
}
}
@@ -5869,9 +5221,6 @@ ole_event_free(poleev)
ITypeInfo *pti = NULL;
IConnectionPoint *pcp = NULL;
- if (poleev->freed == 1) {
- return;
- }
if(poleev->pEvent) {
pti = poleev->pEvent->pTypeInfo;
if(pti) OLE_RELEASE(pti);
@@ -5895,16 +5244,6 @@ fev_s_allocate(klass)
return obj;
}
-/*
- * call-seq:
- * WIN32OLE_EVENT.new(ole, event) #=> WIN32OLE_EVENT object.
- *
- * Returns OLE event object.
- * The first argument specifies WIN32OLE object.
- * The second argument specifies OLE event name.
- * ie = WIN32OLE.new('InternetExplorer.Application')
- * ev = WIN32OLE_EVENT.new(ie, 'DWebBrowserEvents')
- */
static VALUE
fev_initialize(argc, argv, self)
int argc;
@@ -5921,14 +5260,14 @@ fev_initialize(argc, argv, self)
IConnectionPointContainer *pContainer;
IConnectionPoint *pConnectionPoint;
IEVENTSINKOBJ *pIEV;
- DWORD dwCookie = 0;
+ DWORD dwCookie;
struct oleeventdata *poleev;
rb_secure(4);
rb_scan_args(argc, argv, "11", &ole, &itf);
if (!rb_obj_is_kind_of(ole, cWIN32OLE)) {
- rb_raise(rb_eTypeError, "1st parameter must be WIN32OLE object");
+ rb_raise(rb_eTypeError, "1st parameter must be WIN32OLE object.");
}
if(TYPE(itf) != T_NIL) {
@@ -5955,7 +5294,7 @@ fev_initialize(argc, argv, self)
if (FAILED(hr)) {
OLE_RELEASE(pTypeInfo);
ole_raise(hr, rb_eRuntimeError,
- "failed to query IConnectionPointContainer");
+ "Failed to query IConnectionPointContainer");
}
hr = pContainer->lpVtbl->FindConnectionPoint(pContainer,
@@ -5964,7 +5303,7 @@ fev_initialize(argc, argv, self)
OLE_RELEASE(pContainer);
if (FAILED(hr)) {
OLE_RELEASE(pTypeInfo);
- ole_raise(hr, rb_eRuntimeError, "failed to query IConnectionPoint");
+ ole_raise(hr, rb_eRuntimeError, "Failed to query IConnectionPoint");
}
pIEV = EVENTSINK_Constructor();
pIEV->m_iid = iid;
@@ -5982,17 +5321,15 @@ fev_initialize(argc, argv, self)
poleev->pEvent->pConnectionPoint = pConnectionPoint;
poleev->pEvent->pTypeInfo = pTypeInfo;
poleev->pEvent->m_dwCookie = dwCookie;
- poleev->freed = 0;
- poleev->pEvent->ptr_freed = &(poleev->freed);
+
rb_ary_push(ary_ole_event, self);
return self;
}
/*
- * call-seq:
- * WIN32OLE_EVENT.message_loop
- *
- * Translates and dispatches Windows message.
+ * WIN32OLE_EVENT.message_loop
+ * ---
+ * Translates and dispatches Windows message.
*/
static VALUE
fev_s_msg_loop(klass)
@@ -6004,22 +5341,16 @@ fev_s_msg_loop(klass)
static void
-add_event_call_back(obj, event, data)
+add_event_call_back(obj, data)
VALUE obj;
- VALUE event;
VALUE data;
{
- long at;
- VALUE events = rb_ivar_get(obj, id_events);
- if (NIL_P(events) || TYPE(events) != T_ARRAY) {
- events = rb_ary_new();
- rb_ivar_set(obj, id_events, events);
- }
- at = ole_search_event_at(events, event);
- if (at > -1) {
- rb_ary_delete_at(events, at);
+ VALUE ary = rb_ivar_get(obj, id_events);
+ if (NIL_P(ary) || TYPE(ary) != T_ARRAY) {
+ ary = rb_ary_new();
+ rb_ivar_set(obj, id_events, ary);
}
- rb_ary_push(events, data);
+ rb_ary_push(ary, data);
}
static VALUE
@@ -6035,19 +5366,15 @@ ev_on_event(argc, argv, self, is_ary_arg)
Check_SafeStr(event);
}
data = rb_ary_new3(4, rb_block_proc(), event, args, is_ary_arg);
- add_event_call_back(self, event, data);
+ add_event_call_back(self, data);
return Qnil;
}
/*
- * call-seq:
- * WIN32OLE_EVENT#on_event([event]){...}
- *
- * Defines the callback event.
- * If argument is omitted, this method defines the callback of all events.
- * ie = WIN32OLE.new('InternetExplorer.Application')
- * ev = WIN32OLE_EVENT.new(ie, 'DWebBrowserEvents')
- * ev.on_event("NavigateComplete") {|url| puts url}
+ * WIN32OLE_EVENT#on_event([event]){...}
+ * ----
+ * defines the callback event.
+ * If argument is omitted, this method defines the callback of all events.
*/
static VALUE
fev_on_event(argc, argv, self)
@@ -6059,12 +5386,11 @@ fev_on_event(argc, argv, self)
}
/*
- * call-seq:
- * WIN32OLE_EVENT#on_event_with_outargs([event]){...}
- *
- * Defines the callback of event.
- * If you want modify argument in callback,
- * you should use this method instead of WIN32OLE_EVENT#on_event.
+ * WIN32OLE_EVENT#on_event_with_outargs([event]){...}
+ * ----
+ * defines the callback of event.
+ * If you want modify argument in callback,
+ * you should use this method instead of WIN32OLE_EVENT#on_event.
*/
static VALUE
fev_on_event_with_outargs(argc, argv, self)
@@ -6105,8 +5431,6 @@ Init_win32ole()
rb_define_singleton_method(cWIN32OLE, "ole_free", fole_s_free, 1);
rb_define_singleton_method(cWIN32OLE, "ole_reference_count", fole_s_reference_count, 1);
rb_define_singleton_method(cWIN32OLE, "ole_show_help", fole_s_show_help, -1);
- rb_define_singleton_method(cWIN32OLE, "codepage", fole_s_get_code_page, 0);
- rb_define_singleton_method(cWIN32OLE, "codepage=", fole_s_set_code_page, 1);
rb_define_method(cWIN32OLE, "invoke", fole_invoke, -1);
@@ -6137,13 +5461,6 @@ Init_win32ole()
rb_define_const(cWIN32OLE, "VERSION", rb_str_new2(WIN32OLE_VERSION));
rb_define_const(cWIN32OLE, "ARGV", rb_ary_new());
- rb_define_const(cWIN32OLE, "CP_ACP" ,INT2FIX(CP_ACP));
- rb_define_const(cWIN32OLE, "CP_OEMCP" ,INT2FIX(CP_OEMCP));
- rb_define_const(cWIN32OLE, "CP_MACCP" ,INT2FIX(CP_MACCP));
- rb_define_const(cWIN32OLE, "CP_THREAD_ACP",INT2FIX(CP_THREAD_ACP));
- rb_define_const(cWIN32OLE, "CP_SYMBOL" ,INT2FIX(CP_SYMBOL));
- rb_define_const(cWIN32OLE, "CP_UTF7" ,INT2FIX(CP_UTF7));
- rb_define_const(cWIN32OLE, "CP_UTF8" ,INT2FIX(CP_UTF8));
mWIN32OLE_VARIANT = rb_define_module_under(cWIN32OLE, "VARIANT");
rb_define_const(mWIN32OLE_VARIANT, "VT_I2", INT2FIX(VT_I2));
diff --git a/ext/zlib/zlib.c b/ext/zlib/zlib.c
index c8c4407d08..6dfb4cb4b6 100644
--- a/ext/zlib/zlib.c
+++ b/ext/zlib/zlib.c
@@ -55,7 +55,7 @@ static void zstream_reset_input _((struct zstream*));
static void zstream_passthrough_input _((struct zstream*));
static VALUE zstream_detach_input _((struct zstream*));
static void zstream_reset _((struct zstream*));
-static VALUE zstream_end _((struct zstream*));
+static void zstream_end _((struct zstream*));
static void zstream_run _((struct zstream*, Bytef*, uInt, int));
static VALUE zstream_sync _((struct zstream*, Bytef*, uInt));
static void zstream_mark _((struct zstream*));
@@ -80,8 +80,7 @@ static VALUE rb_zstream_closed_p _((VALUE));
static VALUE rb_deflate_s_allocate _((VALUE));
static VALUE rb_deflate_initialize _((int, VALUE*, VALUE));
-static VALUE rb_deflate_init_copy _((VALUE, VALUE));
-static VALUE deflate_run _((VALUE));
+static VALUE rb_deflate_clone _((VALUE));
static VALUE rb_deflate_s_deflate _((int, VALUE*, VALUE));
static void do_deflate _((struct zstream*, VALUE, int));
static VALUE rb_deflate_deflate _((int, VALUE*, VALUE));
@@ -90,7 +89,6 @@ static VALUE rb_deflate_flush _((int, VALUE*, VALUE));
static VALUE rb_deflate_params _((VALUE, VALUE, VALUE));
static VALUE rb_deflate_set_dictionary _((VALUE, VALUE));
-static VALUE inflate_run _((VALUE));
static VALUE rb_inflate_s_allocate _((VALUE));
static VALUE rb_inflate_initialize _((int, VALUE*, VALUE));
static VALUE rb_inflate_s_inflate _((VALUE, VALUE));
@@ -669,7 +667,7 @@ zstream_reset(z)
zstream_reset_input(z);
}
-static VALUE
+static void
zstream_end(z)
struct zstream *z;
{
@@ -679,7 +677,7 @@ zstream_end(z)
if (RTEST(ruby_debug)) {
rb_warning("attempt to close uninitialized zstream; ignored.");
}
- return Qnil;
+ return;
}
if (z->flags & ZSTREAM_FLAG_IN_STREAM) {
if (RTEST(ruby_debug)) {
@@ -694,7 +692,6 @@ zstream_end(z)
raise_zlib_error(err, z->stream.msg);
}
z->flags = 0;
- return Qnil;
}
static void
@@ -706,7 +703,6 @@ zstream_run(z, src, len, flush)
{
uInt n;
int err;
- volatile VALUE guard;
if (NIL_P(z->input) && len == 0) {
z->stream.next_in = "";
@@ -716,10 +712,6 @@ zstream_run(z, src, len, flush)
zstream_append_input(z, src, len);
z->stream.next_in = RSTRING(z->input)->ptr;
z->stream.avail_in = RSTRING(z->input)->len;
- /* keep reference to `z->input' so as not to be garbage collected
- after zstream_reset_input() and prevent `z->stream.next_in'
- from dangling. */
- guard = z->input;
}
if (z->stream.avail_out == 0) {
@@ -1160,31 +1152,26 @@ rb_deflate_initialize(argc, argv, obj)
* Duplicates the deflate stream.
*/
static VALUE
-rb_deflate_init_copy(self, orig)
- VALUE self, orig;
+rb_deflate_clone(obj)
+ VALUE obj;
{
- struct zstream *z1 = get_zstream(self);
- struct zstream *z2 = get_zstream(orig);
+ struct zstream *z = get_zstream(obj);
+ struct zstream *z2;
+ VALUE clone;
int err;
- err = deflateCopy(&z1->stream, &z2->stream);
+ clone = zstream_deflate_new(rb_class_of(obj));
+ Data_Get_Struct(clone, struct zstream, z2);
+
+ err = deflateCopy(&z2->stream, &z->stream);
if (err != Z_OK) {
raise_zlib_error(err, 0);
}
- z1->flags = z2->flags;
-
- return self;
-}
-
-static VALUE
-deflate_run(args)
- VALUE args;
-{
- struct zstream *z = (struct zstream *)((VALUE *)args)[0];
- VALUE src = ((VALUE *)args)[1];
- zstream_run(z, RSTRING(src)->ptr, RSTRING(src)->len, Z_FINISH);
- return zstream_detach_buffer(z);
+ z2->flags = z->flags;
+ CLONESETUP(clone, obj);
+ OBJ_INFECT(clone, obj);
+ return clone;
}
/*
@@ -1214,23 +1201,22 @@ rb_deflate_s_deflate(argc, argv, klass)
VALUE klass;
{
struct zstream z;
- VALUE src, level, dst, args[2];
- int err, lev;
+ VALUE src, level, dst;
+ int err;
rb_scan_args(argc, argv, "11", &src, &level);
- lev = ARG_LEVEL(level);
- StringValue(src);
zstream_init_deflate(&z);
- err = deflateInit(&z.stream, lev);
+ err = deflateInit(&z.stream, ARG_LEVEL(level));
if (err != Z_OK) {
raise_zlib_error(err, z.stream.msg);
}
ZSTREAM_READY(&z);
- args[0] = (VALUE)&z;
- args[1] = src;
- dst = rb_ensure(deflate_run, (VALUE)args, zstream_end, (VALUE)&z);
+ StringValue(src);
+ zstream_run(&z, RSTRING(src)->ptr, RSTRING(src)->len, Z_FINISH);
+ dst = zstream_detach_buffer(&z);
+ zstream_end(&z);
OBJ_INFECT(dst, src);
return dst;
@@ -1443,18 +1429,6 @@ rb_inflate_initialize(argc, argv, obj)
return obj;
}
-static VALUE
-inflate_run(args)
- VALUE args;
-{
- struct zstream *z = (struct zstream *)((VALUE *)args)[0];
- VALUE src = ((VALUE *)args)[1];
-
- zstream_run(z, RSTRING(src)->ptr, RSTRING(src)->len, Z_SYNC_FLUSH);
- zstream_run(z, "", 0, Z_FINISH); /* for checking errors */
- return zstream_detach_buffer(z);
-}
-
/*
* call-seq: Zlib::Inflate.inflate(string)
*
@@ -1477,10 +1451,9 @@ rb_inflate_s_inflate(obj, src)
VALUE obj, src;
{
struct zstream z;
- VALUE dst, args[2];
+ VALUE dst;
int err;
- StringValue(src);
zstream_init_inflate(&z);
err = inflateInit(&z.stream);
if (err != Z_OK) {
@@ -1488,9 +1461,11 @@ rb_inflate_s_inflate(obj, src)
}
ZSTREAM_READY(&z);
- args[0] = (VALUE)&z;
- args[1] = src;
- dst = rb_ensure(inflate_run, (VALUE)args, zstream_end, (VALUE)&z);
+ StringValue(src);
+ zstream_run(&z, RSTRING(src)->ptr, RSTRING(src)->len, Z_SYNC_FLUSH);
+ zstream_run(&z, "", 0, Z_FINISH); /* for checking errors */
+ dst = zstream_detach_buffer(&z);
+ zstream_end(&z);
OBJ_INFECT(dst, src);
return dst;
@@ -3000,7 +2975,7 @@ rb_gzreader_readchar(obj)
VALUE dst;
dst = rb_gzreader_getc(obj);
if (NIL_P(dst)) {
- rb_raise(rb_eEOFError, "end of file reached");
+ rb_raise(rb_eEOFError, "End of file reached");
}
return dst;
}
@@ -3182,7 +3157,7 @@ rb_gzreader_readline(argc, argv, obj)
VALUE dst;
dst = rb_gzreader_gets(argc, argv, obj);
if (NIL_P(dst)) {
- rb_raise(rb_eEOFError, "end of file reached");
+ rb_raise(rb_eEOFError, "End of file reached");
}
return dst;
}
@@ -3357,7 +3332,7 @@ void Init_zlib()
rb_define_singleton_method(cDeflate, "deflate", rb_deflate_s_deflate, -1);
rb_define_alloc_func(cDeflate, rb_deflate_s_allocate);
rb_define_method(cDeflate, "initialize", rb_deflate_initialize, -1);
- rb_define_method(cDeflate, "initialize_copy", rb_deflate_init_copy, 0);
+ rb_define_method(cDeflate, "clone", rb_deflate_clone, 0);
rb_define_method(cDeflate, "deflate", rb_deflate_deflate, -1);
rb_define_method(cDeflate, "<<", rb_deflate_addstr, 1);
rb_define_method(cDeflate, "flush", rb_deflate_flush, -1);
diff --git a/file.c b/file.c
index 2e465e2d89..066745ca6a 100644
--- a/file.c
+++ b/file.c
@@ -64,8 +64,8 @@ char *strrchr _((const char*,const char));
#include <sys/mkdev.h>
#endif
-#if !defined HAVE_LSTAT && !defined lstat
-#define lstat stat
+#ifndef HAVE_LSTAT
+#define lstat(path,st) stat(path,st)
#endif
#if !HAVE_FSEEKO && !defined(fseeko)
# define fseeko fseek
@@ -75,10 +75,9 @@ VALUE rb_cFile;
VALUE rb_mFileTest;
static VALUE rb_cStat;
-static long apply2files _((void (*)(const char *, void *), VALUE, void *));
static long
apply2files(func, vargs, arg)
- void (*func)_((const char *, void *));
+ void (*func)();
VALUE vargs;
void *arg;
{
@@ -97,7 +96,7 @@ apply2files(func, vargs, arg)
/*
* call-seq:
- * file.path -> filename
+ * file.path -> file_ame
*
* Returns the pathname used to create <i>file</i> as a string. Does
* not normalize the name.
@@ -180,20 +179,6 @@ rb_stat_cmp(self, other)
return Qnil;
}
-static VALUE rb_stat_dev _((VALUE));
-static VALUE rb_stat_ino _((VALUE));
-static VALUE rb_stat_mode _((VALUE));
-static VALUE rb_stat_nlink _((VALUE));
-static VALUE rb_stat_uid _((VALUE));
-static VALUE rb_stat_gid _((VALUE));
-static VALUE rb_stat_rdev _((VALUE));
-static VALUE rb_stat_size _((VALUE));
-static VALUE rb_stat_blksize _((VALUE));
-static VALUE rb_stat_blocks _((VALUE));
-static VALUE rb_stat_atime _((VALUE));
-static VALUE rb_stat_mtime _((VALUE));
-static VALUE rb_stat_ctime _((VALUE));
-
/*
* call-seq:
* stat.dev => fixnum
@@ -562,23 +547,23 @@ rb_stat_inspect(self)
{
VALUE str;
int i;
- static const struct {
- const char *name;
- VALUE (*func)_((VALUE));
+ static struct {
+ char *name;
+ VALUE (*func)();
} member[] = {
- {"dev", rb_stat_dev},
- {"ino", rb_stat_ino},
- {"mode", rb_stat_mode},
- {"nlink", rb_stat_nlink},
- {"uid", rb_stat_uid},
- {"gid", rb_stat_gid},
- {"rdev", rb_stat_rdev},
- {"size", rb_stat_size},
- {"blksize", rb_stat_blksize},
- {"blocks", rb_stat_blocks},
- {"atime", rb_stat_atime},
- {"mtime", rb_stat_mtime},
- {"ctime", rb_stat_ctime},
+ {"dev", rb_stat_dev},
+ {"ino", rb_stat_ino},
+ {"mode", rb_stat_mode},
+ {"nlink", rb_stat_nlink},
+ {"uid", rb_stat_uid},
+ {"gid", rb_stat_gid},
+ {"rdev", rb_stat_rdev},
+ {"size", rb_stat_size},
+ {"blksize", rb_stat_blksize},
+ {"blocks", rb_stat_blocks},
+ {"atime", rb_stat_atime},
+ {"mtime", rb_stat_mtime},
+ {"ctime", rb_stat_ctime},
};
str = rb_str_buf_new2("#<");
@@ -1560,13 +1545,12 @@ rb_file_ctime(obj)
return rb_time_new(st.st_ctime, 0);
}
-static void chmod_internal _((const char *, void *));
static void
chmod_internal(path, mode)
const char *path;
- void *mode;
+ int mode;
{
- if (chmod(path, (int)mode) < 0)
+ if (chmod(path, mode) < 0)
rb_sys_fail(path);
}
@@ -1638,13 +1622,12 @@ rb_file_chmod(obj, vmode)
}
#if defined(HAVE_LCHMOD)
-static void lchmod_internal _((const char *, void *));
static void
lchmod_internal(path, mode)
const char *path;
- void *mode;
+ int mode;
{
- if (lchmod(path, (int)mode) < 0)
+ if (lchmod(path, mode) < 0)
rb_sys_fail(path);
}
@@ -1689,13 +1672,11 @@ struct chown_args {
int owner, group;
};
-static void chown_internal _((const char *, void *));
static void
-chown_internal(path, argp)
+chown_internal(path, args)
const char *path;
- void *argp;
+ struct chown_args *args;
{
- struct chown_args *args = (struct chown_args *)argp;
if (chown(path, args->owner, args->group) < 0)
rb_sys_fail(path);
}
@@ -1763,18 +1744,15 @@ rb_file_chown(obj, owner, group)
VALUE obj, owner, group;
{
OpenFile *fptr;
- int o, g;
rb_secure(2);
- o = NIL_P(owner) ? -1 : NUM2INT(owner);
- g = NIL_P(group) ? -1 : NUM2INT(group);
GetOpenFile(obj, fptr);
#if defined(DJGPP) || defined(__CYGWIN32__) || defined(_WIN32) || defined(__EMX__)
if (!fptr->path) return Qnil;
- if (chown(fptr->path, o, g) == -1)
+ if (chown(fptr->path, NUM2INT(owner), NUM2INT(group)) == -1)
rb_sys_fail(fptr->path);
#else
- if (fchown(fileno(fptr->f), o, g) == -1)
+ if (fchown(fileno(fptr->f), NUM2INT(owner), NUM2INT(group)) == -1)
rb_sys_fail(fptr->path);
#endif
@@ -1782,13 +1760,11 @@ rb_file_chown(obj, owner, group)
}
#if defined(HAVE_LCHOWN) && !defined(__CHECKER__)
-static void lchown_internal _((const char *, void *));
static void
-lchown_internal(path, argp)
+lchown_internal(path, args)
const char *path;
- void *argp;
+ struct chown_args *args;
{
- struct chown_args *args = (struct chown_args *)argp;
if (lchown(path, args->owner, args->group) < 0)
rb_sys_fail(path);
}
@@ -1844,16 +1820,13 @@ rb_file_s_lchown(argc, argv)
struct timeval rb_time_timeval();
-static void utime_internal _((const char *, void *));
-
#if defined(HAVE_UTIMES) && !defined(__CHECKER__)
static void
-utime_internal(path, arg)
- const char *path;
- void *arg;
+utime_internal(path, tvp)
+ char *path;
+ struct timeval tvp[];
{
- struct timeval *tvp = arg;
if (utimes(path, tvp) < 0)
rb_sys_fail(path);
}
@@ -1895,11 +1868,10 @@ struct utimbuf {
#endif
static void
-utime_internal(path, arg)
+utime_internal(path, utp)
const char *path;
- void *arg;
+ struct utimbuf *utp;
{
- struct utimbuf *utp = arg;
if (utime(path, utp) < 0)
rb_sys_fail(path);
}
@@ -2037,11 +2009,9 @@ rb_file_s_readlink(klass, path)
#endif
}
-static void unlink_internal _((const char *, void *));
static void
-unlink_internal(path, arg)
+unlink_internal(path)
const char *path;
- void *arg;
{
if (unlink(path) < 0)
rb_sys_fail(path);
@@ -2652,8 +2622,8 @@ rb_file_s_dirname(klass, fname)
name = StringValueCStr(fname);
root = skiproot(name);
#ifdef DOSISH_UNC
- if (root > name + 1 && isdirsep(*name))
- root = skipprefix(name = root - 2);
+ if (root > name + 2 && isdirsep(*name))
+ name = root - 2;
#else
if (root > name + 1)
name = root - 1;
@@ -2702,7 +2672,7 @@ rb_file_s_extname(klass, fname)
p++;
e = strrchr(p, '.'); /* get the last dot of the last component */
- if (!e || e == p || !e[1]) /* no dot, or the only dot is first or end? */
+ if (!e || e == p) /* no dot, or the only dot is first? */
return rb_str_new2("");
extname = rb_str_new(e, chompdirsep(e) - e); /* keep the dot, too! */
OBJ_INFECT(extname, fname);
@@ -2747,7 +2717,7 @@ rb_file_join(ary, sep)
long len, i;
int taint = 0;
VALUE result, tmp;
- char *name, *tail;
+ char *name;
if (RARRAY(ary)->len == 0) return rb_str_new(0, 0);
if (OBJ_TAINTED(ary)) taint = 1;
@@ -2784,18 +2754,11 @@ rb_file_join(ary, sep)
}
break;
default:
- StringValueCStr(tmp);
+ tmp = rb_obj_as_string(tmp);
}
name = StringValueCStr(result);
- if (i > 0 && !NIL_P(sep)) {
- tail = chompdirsep(name);
- if (RSTRING(tmp)->ptr && isdirsep(RSTRING(tmp)->ptr[0])) {
- RSTRING(result)->len = tail - name;
- }
- else if (!*tail) {
- rb_str_buf_append(result, sep);
- }
- }
+ if (i > 0 && !NIL_P(sep) && !*chompdirsep(name))
+ rb_str_buf_append(result, sep);
rb_str_buf_append(result, tmp);
if (OBJ_TAINTED(tmp)) taint = 1;
}
@@ -2841,14 +2804,11 @@ static VALUE
rb_file_s_truncate(klass, path, len)
VALUE klass, path, len;
{
- off_t pos;
-
rb_secure(2);
- pos = NUM2OFFT(len);
SafeStringValue(path);
#ifdef HAVE_TRUNCATE
- if (truncate(StringValueCStr(path), pos) < 0)
+ if (truncate(StringValueCStr(path), NUM2OFFT(len)) < 0)
rb_sys_fail(RSTRING(path)->ptr);
#else
# ifdef HAVE_CHSIZE
@@ -2864,7 +2824,7 @@ rb_file_s_truncate(klass, path, len)
rb_sys_fail(RSTRING(path)->ptr);
}
# endif
- if (chsize(tmpfd, pos) < 0) {
+ if (chsize(tmpfd, NUM2OFFT(len)) < 0) {
close(tmpfd);
rb_sys_fail(RSTRING(path)->ptr);
}
@@ -2897,10 +2857,8 @@ rb_file_truncate(obj, len)
{
OpenFile *fptr;
FILE *f;
- off_t pos;
rb_secure(2);
- pos = NUM2OFFT(len);
GetOpenFile(obj, fptr);
if (!(fptr->mode & FMODE_WRITABLE)) {
rb_raise(rb_eIOError, "not opened for writing");
@@ -2909,11 +2867,11 @@ rb_file_truncate(obj, len)
fflush(f);
fseeko(f, (off_t)0, SEEK_CUR);
#ifdef HAVE_TRUNCATE
- if (ftruncate(fileno(f), pos) < 0)
+ if (ftruncate(fileno(f), NUM2OFFT(len)) < 0)
rb_sys_fail(fptr->path);
#else
# ifdef HAVE_CHSIZE
- if (chsize(fileno(f), pos) < 0)
+ if (chsize(fileno(f), NUM2OFFT(len)) < 0)
rb_sys_fail(fptr->path);
# else
rb_notimplement();
@@ -2935,30 +2893,26 @@ rb_file_truncate(obj, len)
# define LOCK_UN 8
# endif
-#if 1
+#if 0
static int
rb_thread_flock(fd, op, fptr)
int fd, op;
OpenFile *fptr;
{
if (rb_thread_alone() || (op & LOCK_NB)) {
- int ret;
- TRAP_BEG;
- ret = flock(fd, op);
- TRAP_END;
- return ret;
+ return flock(fd, op);
}
op |= LOCK_NB;
while (flock(fd, op) < 0) {
switch (errno) {
- case EAGAIN:
- case EACCES:
+ case EAGAIN:
+ case EACCES:
#if defined(EWOULDBLOCK) && EWOULDBLOCK != EAGAIN
case EWOULDBLOCK:
#endif
rb_thread_polling(); /* busy wait */
rb_io_check_closed(fptr);
- continue;
+ continue;
default:
return -1;
}
@@ -3004,30 +2958,28 @@ rb_file_flock(obj, operation)
{
#ifndef __CHECKER__
OpenFile *fptr;
- int op;
rb_secure(2);
- op = NUM2INT(operation);
GetOpenFile(obj, fptr);
if (fptr->mode & FMODE_WRITABLE) {
fflush(GetWriteFile(fptr));
}
retry:
- if (flock(fileno(fptr->f), op) < 0) {
- switch (errno) {
- case EAGAIN:
- case EACCES:
+ if (flock(fileno(fptr->f), NUM2INT(operation)) < 0) {
+ switch (errno) {
+ case EAGAIN:
+ case EACCES:
#if defined(EWOULDBLOCK) && EWOULDBLOCK != EAGAIN
- case EWOULDBLOCK:
+ case EWOULDBLOCK:
#endif
- return Qfalse;
+ return Qfalse;
case EINTR:
#if defined(ERESTART)
case ERESTART:
#endif
goto retry;
- }
+ }
rb_sys_fail(fptr->path);
}
#endif
@@ -3076,14 +3028,14 @@ test_check(n, argc, argv)
* ?d | boolean | True if file1 exists and is a directory
* ?e | boolean | True if file1 exists
* ?f | boolean | True if file1 exists and is a regular file
- * ?g | boolean | True if file1 has the \CF{setgid} bit
+ * ?g | boolean | True if files has the \CF{setgid} bit
* | | set (false under NT)
* ?G | boolean | True if file1 exists and has a group
* | | ownership equal to the caller's group
* ?k | boolean | True if file1 exists and has the sticky bit set
- * ?l | boolean | True if file1 exists and is a symbolic link
+ * ?l | boolean | True if files exists and is a symbolic link
* ?M | Time | Last modification time for file1
- * ?o | boolean | True if file1 exists and is owned by
+ * ?o | boolean | True if files exists and is owned by
* | | the caller's effective uid
* ?O | boolean | True if file1 exists and is owned by
* | | the caller's real uid
@@ -3092,7 +3044,7 @@ test_check(n, argc, argv)
* | | uid/gid of the caller
* ?R | boolean | True if file is readable by the real
* | | uid/gid of the caller
- * ?s | int/nil | If file1 has nonzero size, return the size,
+ * ?s | int/nil | If files has nonzero size, return the size,
* | | otherwise return nil
* ?S | boolean | True if file1 exists and is a socket
* ?u | boolean | True if file1 has the setuid bit set
@@ -3233,7 +3185,7 @@ rb_f_test(argc, argv)
case '-':
if (st1.st_dev == st2.st_dev && st1.st_ino == st2.st_ino)
return Qtrue;
- return Qfalse;
+ return Qfalse;
case '=':
if (st1.st_mtime == st2.st_mtime) return Qtrue;
@@ -3246,7 +3198,7 @@ rb_f_test(argc, argv)
case '<':
if (st1.st_mtime < st2.st_mtime) return Qtrue;
return Qfalse;
- }
+ }
}
/* unknown command */
rb_raise(rb_eArgError, "unknown command ?%c", cmd);
@@ -3308,7 +3260,6 @@ rb_stat_init(obj, fname)
return Qnil;
}
-/* :nodoc: */
static VALUE
rb_stat_init_copy(copy, orig)
VALUE copy, orig;
@@ -3878,12 +3829,11 @@ is_absolute_path(path)
#ifndef DOSISH
static int
-path_check_0(fpath, loadpath)
- VALUE fpath;
- int loadpath;
+path_check_1(path)
+ VALUE path;
{
struct stat st;
- char *p0 = StringValueCStr(fpath);
+ char *p0 = StringValueCStr(path);
char *p = 0, *s;
if (!is_absolute_path(p0)) {
@@ -3895,7 +3845,7 @@ path_check_0(fpath, loadpath)
rb_str_cat2(newpath, "/");
rb_str_cat2(newpath, p0);
- return path_check_0(newpath, loadpath);
+ return path_check_1(newpath);
}
for (;;) {
#ifndef S_IWOTH
@@ -3903,7 +3853,7 @@ path_check_0(fpath, loadpath)
#endif
if (stat(p0, &st) == 0 && S_ISDIR(st.st_mode) && (st.st_mode & S_IWOTH)
#ifdef S_ISVTX
- && (loadpath || !(st.st_mode & S_ISVTX))
+ && !(st.st_mode & S_ISVTX)
#endif
) {
rb_warn("Insecure world writable dir %s, mode 0%o", p0, st.st_mode);
@@ -3919,17 +3869,6 @@ path_check_0(fpath, loadpath)
}
#endif
-static int
-fpath_check(path)
- char *path;
-{
-#ifndef DOSISH
- return path_check_0(rb_str_new2(path), Qfalse);
-#else
- return 1;
-#endif
-}
-
int
rb_path_check(path)
char *path;
@@ -3946,7 +3885,7 @@ rb_path_check(path)
if (!p) p = pend;
for (;;) {
- if (!path_check_0(rb_str_new(p0, p - p0), Qtrue)) {
+ if (!path_check_1(rb_str_new(p0, p - p0))) {
return 0; /* not safe */
}
p0 = p + 1;
@@ -4058,7 +3997,7 @@ rb_find_file(path)
#if defined(__MACOS__) || defined(riscos)
if (is_macos_native_path(f)) {
- if (rb_safe_level() >= 1 && !fpath_check(f)) {
+ if (rb_safe_level() >= 1 && !rb_path_check(f)) {
rb_raise(rb_eSecurityError, "loading from unsafe file %s", f);
}
if (file_load_ok(f)) return path;
@@ -4066,7 +4005,7 @@ rb_find_file(path)
#endif
if (is_absolute_path(f)) {
- if (rb_safe_level() >= 1 && !fpath_check(f)) {
+ if (rb_safe_level() >= 1 && !rb_path_check(f)) {
rb_raise(rb_eSecurityError, "loading from unsafe file %s", f);
}
if (file_load_ok(f)) return path;
@@ -4107,7 +4046,7 @@ rb_find_file(path)
return 0; /* no path, no load */
}
f = dln_find_file(f, lpath);
- if (rb_safe_level() >= 1 && !fpath_check(f)) {
+ if (rb_safe_level() >= 1 && !rb_path_check(f)) {
rb_raise(rb_eSecurityError, "loading from unsafe file %s", f);
}
if (file_load_ok(f)) {
diff --git a/gc.c b/gc.c
index d076898fd7..b00c170927 100644
--- a/gc.c
+++ b/gc.c
@@ -185,14 +185,14 @@ static st_table *finalizer_table = 0;
/*
* call-seq:
* GC.enable => true or false
- *
+ *
* Enables garbage collection, returning <code>true</code> if garbage
* collection was previously disabled.
- *
+ *
* GC.disable #=> false
* GC.enable #=> true
* GC.enable #=> false
- *
+ *
*/
VALUE
@@ -207,13 +207,13 @@ rb_gc_enable()
/*
* call-seq:
* GC.disable => true or false
- *
+ *
* Disables garbage collection, returning <code>true</code> if garbage
* collection was already disabled.
- *
+ *
* GC.disable #=> false
* GC.disable #=> true
- *
+ *
*/
VALUE
@@ -296,7 +296,7 @@ typedef struct RVALUE {
struct RFile file;
struct RNode node;
struct RMatch match;
- struct RVarmap varmap;
+ struct RVarmap varmap;
struct SCOPE scope;
} as;
#ifdef GC_DEBUG
@@ -398,7 +398,7 @@ rb_data_object_alloc(klass, datap, dmark, dfree)
RUBY_DATA_FUNC dfree;
{
NEWOBJ(data, struct RData);
- if (klass) Check_Type(klass, T_CLASS);
+ Check_Type(klass, T_CLASS);
OBJSETUP(data, klass, T_DATA);
data->data = datap;
data->dfree = dfree;
@@ -432,15 +432,7 @@ static unsigned int STACK_LEVEL_MAX = 655300;
# define STACK_END (&stack_end)
#else
# if defined(__GNUC__) && defined(USE_BUILTIN_FRAME_ADDRESS) && !defined(__ia64__)
-# if ( __GNUC__ == 3 && __GNUC_MINOR__ > 0 ) || __GNUC__ > 3
-__attribute__ ((noinline))
-# endif
-static VALUE *
-stack_end_address(void)
-{
- return (VALUE *)__builtin_frame_address(0);
-}
-# define SET_STACK_END VALUE *stack_end = stack_end_address()
+# define SET_STACK_END VALUE *stack_end = __builtin_frame_address(0)
# else
# define SET_STACK_END VALUE *stack_end = alloca(1)
# endif
@@ -619,11 +611,9 @@ mark_locations_array(x, n)
register VALUE *x;
register long n;
{
- VALUE v;
while (n--) {
- v = *x;
- if (is_pointer_to_heap((void *)v)) {
- gc_mark(v, 0);
+ if (is_pointer_to_heap((void *)*x)) {
+ gc_mark(*x, 0);
}
x++;
}
@@ -649,7 +639,7 @@ mark_entry(key, value, lev)
return ST_CONTINUE;
}
-static void
+void
mark_tbl(tbl, lev)
st_table *tbl;
int lev;
@@ -676,7 +666,7 @@ mark_keyvalue(key, value, lev)
return ST_CONTINUE;
}
-static void
+void
mark_hash(tbl, lev)
st_table *tbl;
int lev;
@@ -703,7 +693,7 @@ rb_gc_mark_maybe(obj)
#define GC_LEVEL_MAX 250
-static void
+void
gc_mark(ptr, lev)
VALUE ptr;
int lev;
@@ -713,7 +703,7 @@ gc_mark(ptr, lev)
obj = RANY(ptr);
if (rb_special_const_p(ptr)) return; /* special const not marked */
if (obj->as.basic.flags == 0) return; /* free cell */
- if (obj->as.basic.flags & FL_MARK) return; /* already marked */
+ if (obj->as.basic.flags & FL_MARK) return; /* already marked */
obj->as.basic.flags |= FL_MARK;
if (lev > GC_LEVEL_MAX || (lev == 0 && ruby_stack_check())) {
@@ -751,7 +741,7 @@ gc_mark_children(ptr, lev)
obj = RANY(ptr);
if (rb_special_const_p(ptr)) return; /* special const not marked */
if (obj->as.basic.flags == 0) return; /* free cell */
- if (obj->as.basic.flags & FL_MARK) return; /* already marked */
+ if (obj->as.basic.flags & FL_MARK) return; /* already marked */
obj->as.basic.flags |= FL_MARK;
marking:
@@ -880,11 +870,13 @@ gc_mark_children(ptr, lev)
case NODE_BLOCK_ARG:
case NODE_POSTEXE:
break;
+#ifdef C_ALLOCA
case NODE_ALLOCA:
mark_locations_array((VALUE*)obj->as.node.u1.value,
obj->as.node.u3.cnt);
ptr = (VALUE)obj->as.node.u2.node;
goto again;
+#endif
default: /* unlisted NODE */
if (is_pointer_to_heap(obj->as.node.u1.node)) {
@@ -1228,9 +1220,11 @@ obj_free(obj)
RUBY_CRITICAL(free(RANY(obj)->as.node.u1.tbl));
}
break;
+#ifdef C_ALLOCA
case NODE_ALLOCA:
RUBY_CRITICAL(free(RANY(obj)->as.node.u1.node));
break;
+#endif
}
return; /* no need to free iv_tbl */
@@ -1252,8 +1246,8 @@ obj_free(obj)
break;
default:
- rb_bug("gc_sweep(): unknown data type 0x%lx(0x%lx)",
- RANY(obj)->as.basic.flags & T_MASK, obj);
+ rb_bug("gc_sweep(): unknown data type 0x%lx(%ld)", obj,
+ RANY(obj)->as.basic.flags & T_MASK);
}
}
@@ -1326,10 +1320,10 @@ garbage_collect()
during_gc++;
init_mark_stack();
-
+
/* mark frame stack */
for (frame = ruby_frame; frame; frame = frame->prev) {
- rb_gc_mark_frame(frame);
+ rb_gc_mark_frame(frame);
if (frame->tmp) {
struct FRAME *tmp = frame->tmp;
while (tmp) {
@@ -1396,7 +1390,7 @@ garbage_collect()
rb_mark_generic_ivar_tbl();
rb_gc_mark_parser();
-
+
/* gc_mark objects whose marking are not completed*/
while (!MARK_STACK_EMPTY){
if (mark_stack_overflow){
@@ -1423,7 +1417,7 @@ rb_gc()
* ObjectSpace.garbage_collect => nil
*
* Initiates garbage collection, unless manually disabled.
- *
+ *
*/
VALUE
@@ -1479,6 +1473,14 @@ Init_stack(addr)
STACK_LEVEL_MAX = (rlim.rlim_cur - space) / sizeof(VALUE);
}
}
+#if defined(__ia64__) && (!defined(__GNUC__) || __GNUC__ < 2 || defined(__OPTIMIZE__))
+ /* ruby crashes on IA64 if compiled with optimizer on */
+ /* when if STACK_LEVEL_MAX is greater than this magic number */
+ /* I know this is a kludge. I suspect optimizer bug */
+#define IA64_MAGIC_STACK_LIMIT 49152
+ if (STACK_LEVEL_MAX > IA64_MAGIC_STACK_LIMIT)
+ STACK_LEVEL_MAX = IA64_MAGIC_STACK_LIMIT;
+#endif
#endif
}
@@ -1489,29 +1491,29 @@ Init_stack(addr)
* The <code>ObjectSpace</code> module contains a number of routines
* that interact with the garbage collection facility and allow you to
* traverse all living objects with an iterator.
- *
+ *
* <code>ObjectSpace</code> also provides support for object
* finalizers, procs that will be called when a specific object is
* about to be destroyed by garbage collection.
- *
+ *
* include ObjectSpace
- *
- *
+ *
+ *
* a = "A"
* b = "B"
* c = "C"
- *
- *
+ *
+ *
* define_finalizer(a, proc {|id| puts "Finalizer one on #{id}" })
* define_finalizer(a, proc {|id| puts "Finalizer two on #{id}" })
* define_finalizer(b, proc {|id| puts "Finalizer three on #{id}" })
- *
+ *
* <em>produces:</em>
- *
+ *
* Finalizer three on 537763470
* Finalizer one on 537763480
* Finalizer two on 537763480
- *
+ *
*/
void
@@ -1593,7 +1595,7 @@ os_obj_of(of)
/*
* call-seq:
* ObjectSpace.each_object([module]) {|obj| ... } => fixnum
- *
+ *
* Calls the block once for each living, nonimmediate object in this
* Ruby process. If <i>module</i> is specified, calls the block
* for only those classes or modules that match (or are a subclass of)
@@ -1603,15 +1605,15 @@ os_obj_of(of)
* never returned. In the example below, <code>each_object</code>
* returns both the numbers we defined and several constants defined in
* the <code>Math</code> module.
- *
+ *
* a = 102.7
* b = 95 # Won't be returned
* c = 12345678987654321
* count = ObjectSpace.each_object(Numeric) {|x| p x }
* puts "Total count: #{count}"
- *
+ *
* <em>produces:</em>
- *
+ *
* 12345678987654321
* 102.7
* 2.71828182845905
@@ -1620,7 +1622,7 @@ os_obj_of(of)
* 1.7976931348623157e+308
* 2.2250738585072e-308
* Total count: 7
- *
+ *
*/
static VALUE
@@ -1696,9 +1698,9 @@ call_final(os, obj)
/*
* call-seq:
* ObjectSpace.undefine_finalizer(obj)
- *
+ *
* Removes all finalizers for <i>obj</i>.
- *
+ *
*/
static VALUE
@@ -1714,10 +1716,10 @@ undefine_final(os, obj)
/*
* call-seq:
* ObjectSpace.define_finalizer(obj, aProc=proc())
- *
- * Adds <i>aProc</i> as a finalizer, to be called after <i>obj</i>
- * was destroyed.
- *
+ *
+ * Adds <i>aProc</i> as a finalizer, to be called when <i>obj</i>
+ * is about to be destroyed.
+ *
*/
static VALUE
@@ -1781,22 +1783,19 @@ run_final(obj)
{
long i;
int status, critical_save = rb_thread_critical;
- VALUE args[3], table, objid;
+ VALUE args[3], table;
- objid = rb_obj_id(obj); /* make obj into id */
rb_thread_critical = Qtrue;
- args[1] = 0;
+ args[1] = rb_ary_new3(1, rb_obj_id(obj)); /* make obj into id */
args[2] = (VALUE)ruby_safe_level;
for (i=0; i<RARRAY(finalizers)->len; i++) {
args[0] = RARRAY(finalizers)->ptr[i];
- if (!args[1]) args[1] = rb_ary_new3(1, objid);
rb_protect((VALUE(*)_((VALUE)))run_single_final, (VALUE)args, &status);
}
if (finalizer_table && st_delete(finalizer_table, (st_data_t*)&obj, &table)) {
for (i=0; i<RARRAY(table)->len; i++) {
VALUE final = RARRAY(table)->ptr[i];
args[0] = RARRAY(final)->ptr[1];
- if (!args[1]) args[1] = rb_ary_new3(1, objid);
args[2] = FIX2INT(RARRAY(final)->ptr[0]);
rb_protect((VALUE(*)_((VALUE)))run_single_final, (VALUE)args, &status);
}
@@ -1824,9 +1823,7 @@ rb_gc_call_finalizer_at_exit()
/* run finalizers */
if (need_call_final) {
- p = deferred_final_list;
- deferred_final_list = 0;
- finalize_list(p);
+ finalize_list(deferred_final_list);
for (i = 0; i < heaps_used; i++) {
p = heaps[i].slot; pend = p + heaps[i].limit;
while (p < pend) {
@@ -1865,14 +1862,14 @@ rb_gc_call_finalizer_at_exit()
/*
* call-seq:
* ObjectSpace._id2ref(object_id) -> an_object
- *
+ *
* Converts an object id to a reference to the object. May not be
* called on an object id passed as a parameter to a finalizer.
- *
+ *
* s = "I am a string" #=> "I am a string"
* r = ObjectSpace._id2ref(s.object_id) #=> "I am a string"
* r == s #=> true
- *
+ *
*/
static VALUE
diff --git a/hash.c b/hash.c
index 09d866b133..fbf8d5d20d 100644
--- a/hash.c
+++ b/hash.c
@@ -121,14 +121,17 @@ struct foreach_safe_arg {
};
static int
-foreach_safe_i(key, value, arg)
+foreach_safe_i(key, value, arg, err)
st_data_t key, value;
struct foreach_safe_arg *arg;
{
int status;
+ if (err) {
+ rb_raise(rb_eRuntimeError, "hash modified during iteration");
+ }
if (key == Qundef) return ST_CONTINUE;
- status = (*arg->func)(key, value, arg->arg);
+ status = (*arg->func)(key, value, arg->arg, err);
if (status == ST_CONTINUE) {
return ST_CHECK;
}
@@ -146,9 +149,7 @@ st_foreach_safe(table, func, a)
arg.tbl = table;
arg.func = func;
arg.arg = a;
- if (st_foreach(table, foreach_safe_i, (st_data_t)&arg)) {
- rb_raise(rb_eRuntimeError, "hash modified during iteration");
- }
+ st_foreach(table, foreach_safe_i, (st_data_t)&arg);
}
struct hash_foreach_arg {
@@ -158,13 +159,17 @@ struct hash_foreach_arg {
};
static int
-hash_foreach_iter(key, value, arg)
+hash_foreach_iter(key, value, arg, err)
VALUE key, value;
struct hash_foreach_arg *arg;
+ int err;
{
int status;
st_table *tbl;
+ if (err) {
+ rb_raise(rb_eRuntimeError, "hash modified during iteration");
+ }
tbl = RHASH(arg->hash)->tbl;
if (key == Qundef) return ST_CONTINUE;
status = (*arg->func)(key, value, arg->arg);
@@ -202,9 +207,7 @@ static VALUE
hash_foreach_call(arg)
struct hash_foreach_arg *arg;
{
- if (st_foreach(RHASH(arg->hash)->tbl, hash_foreach_iter, (st_data_t)arg)) {
- rb_raise(rb_eRuntimeError, "hash modified during iteration");
- }
+ st_foreach(RHASH(arg->hash)->tbl, hash_foreach_iter, (st_data_t)arg);
return Qnil;
}
@@ -880,6 +883,8 @@ static VALUE
rb_hash_clear(hash)
VALUE hash;
{
+ void *tmp;
+
rb_hash_modify(hash);
if (RHASH(hash)->tbl->num_entries > 0) {
rb_hash_foreach(hash, clear_i, 0);
@@ -1498,6 +1503,22 @@ rb_hash_equal(hash1, hash2)
return hash_equal(hash1, hash2, Qfalse);
}
+/*
+ * call-seq:
+ * hsh.eql?(other_hash) => true or false
+ *
+ * Returns true if two hashes are equal, i.e they have same key-value set,
+ * and same default values.
+ *
+ */
+
+static VALUE
+rb_hash_eql(hash1, hash2)
+ VALUE hash1, hash2;
+{
+ return hash_equal(hash1, hash2, Qtrue);
+}
+
static int
rb_hash_invert_i(key, value, hash)
VALUE key, value;
@@ -1555,10 +1576,8 @@ rb_hash_update_block_i(key, value, hash)
/*
* call-seq:
- * hsh.merge!(other_hash) => hsh
- * hsh.update(other_hash) => hsh
- * hsh.merge!(other_hash){|key, oldval, newval| block} => hsh
- * hsh.update(other_hash){|key, oldval, newval| block} => hsh
+ * hsh.merge!(other_hash) => hsh
+ * hsh.update(other_hash) => hsh
*
* Adds the contents of <i>other_hash</i> to <i>hsh</i>, overwriting
* entries with duplicate keys with those from <i>other_hash</i>.
@@ -1584,8 +1603,7 @@ rb_hash_update(hash1, hash2)
/*
* call-seq:
- * hsh.merge(other_hash) -> a_hash
- * hsh.merge(other_hash){|key, oldval, newval| block} -> a_hash
+ * hsh.merge(other_hash) -> a_hash
*
* Returns a new hash containing the contents of <i>other_hash</i> and
* the contents of <i>hsh</i>, overwriting entries in <i>hsh</i> with
@@ -1820,7 +1838,7 @@ ruby_setenv(name, value)
else
unsetenv(name);
#else /* WIN32 */
- size_t len;
+
int i=envix(name); /* where does it go? */
if (environ == origenviron) { /* need we copy environment? */
@@ -1835,28 +1853,30 @@ ruby_setenv(name, value)
tmpenv[max] = 0;
environ = tmpenv; /* tell exec where it is now */
}
- if (environ[i]) {
- char **envp = origenviron;
- while (*envp && *envp != environ[i]) envp++;
- if (!*envp)
- free(environ[i]);
- if (!value) {
- while (environ[i]) {
- environ[i] = environ[i+1];
- i++;
- }
- return;
+ if (!value) {
+ if (environ != origenviron) {
+ char **envp = origenviron;
+ while (*envp && *envp != environ[i]) envp++;
+ if (!*envp)
+ free(environ[i]);
+ }
+ while (environ[i]) {
+ environ[i] = environ[i+1];
+ i++;
}
+ return;
}
- else { /* does not exist yet */
- if (!value) return;
+ if (!environ[i]) { /* does not exist yet */
REALLOC_N(environ, char*, i+2); /* just expand it a bit */
environ[i+1] = 0; /* make sure it's null terminated */
}
- len = strlen(name) + strlen(value) + 2;
- environ[i] = ALLOC_N(char, len);
+ else {
+ if (environ[i] != origenviron[i])
+ free(environ[i]);
+ }
+ environ[i] = ALLOC_N(char, strlen(name) + strlen(value) + 2);
#ifndef MSDOS
- snprintf(environ[i],len,"%s=%s",name,value); /* all that work just for this */
+ sprintf(environ[i],"%s=%s",name,value); /* all that work just for this */
#else
/* MS-DOS requires environment variable names to be in uppercase */
/* [Tom Dinger, 27 August 1990: Well, it doesn't _require_ it, but
@@ -1884,7 +1904,7 @@ env_aset(obj, nm, val)
char *name, *value;
if (rb_safe_level() >= 4) {
- rb_raise(rb_eSecurityError, "can't change environment variable");
+ rb_raise(rb_eSecurityError, "cannot change environment variable");
}
if (NIL_P(val)) {
@@ -2430,6 +2450,7 @@ Init_Hash()
rb_define_method(rb_cHash,"inspect", rb_hash_inspect, 0);
rb_define_method(rb_cHash,"==", rb_hash_equal, 1);
+ rb_define_method(rb_cHash,"eql?", rb_hash_eql, 1);
rb_define_method(rb_cHash,"[]", rb_hash_aref, 1);
rb_define_method(rb_cHash,"fetch", rb_hash_fetch, -1);
rb_define_method(rb_cHash,"[]=", rb_hash_aset, 2);
diff --git a/instruby.rb b/instruby.rb
index be011d46ab..a9d66c7670 100644
--- a/instruby.rb
+++ b/instruby.rb
@@ -3,36 +3,30 @@
load "./rbconfig.rb"
include Config
-srcdir = File.dirname(__FILE__)
-$:.unshift File.expand_path("lib", srcdir)
+$:.unshift File.join(CONFIG["srcdir"], "lib")
require 'fileutils'
require 'shellwords'
-require 'optparse'
-require 'optparse/shellwords'
+require 'getopts'
require 'tempfile'
-STDOUT.sync = true
File.umask(0)
def parse_args()
- $mantype = 'doc'
- $destdir = nil
- $make = 'make'
- $mflags = []
- $install = []
- opt = OptionParser.new
- opt.on('-n') {$dryrun = true}
- opt.on('--dest-dir=DIR') {|dir| $destdir = dir}
- opt.on('--make=COMMAND') {|make| $make = make}
- opt.on('--mantype=MAN') {|man| $mantype = man}
- opt.on('--make-flags=FLAGS', '--mflags', Shellwords) do |v|
- if arg = v.first
- arg.insert(0, '-') if /\A[^-][^=]*\Z/ =~ arg
- end
- $mflags.concat(v)
+ getopts('n', 'dest-dir:',
+ 'make:', 'make-flags:', 'mflags:',
+ 'mantype:doc')
+
+ $dryrun = $OPT['n']
+ $destdir = $OPT['dest-dir'] || ''
+ $make = $OPT['make'] || $make || 'make'
+ $mantype = $OPT['mantype']
+ mflags = ($OPT['make-flags'] || '').strip
+ mflags = ($OPT['mflags'] || '').strip if mflags.empty?
+
+ $mflags = Shellwords.shellwords(mflags)
+ if arg = $mflags.first
+ arg.insert(0, '-') if /\A[^-][^=]*\Z/ =~ arg
end
- opt.on('--install=TYPE', [:bin, :lib, :man]) {|ins| $install << ins}
- opt.parse! rescue abort [$!.message, opt].join("\n")
$make, *rest = Shellwords.shellwords($make)
$mflags.unshift(*rest) unless rest.empty?
@@ -60,10 +54,6 @@ include FileUtils::NoWrite if $dryrun
@fileutils_output = STDOUT
@fileutils_label = ''
-def install?(type)
- yield if $install.empty? or $install.include?(type)
-end
-
def install(src, dest, options = {})
options[:preserve] = true
super
@@ -82,7 +72,7 @@ def makedirs(dirs)
end
def with_destdir(dir)
- return dir if !$destdir or $destdir.empty?
+ return dir if $destdir.empty?
dir = dir.sub(/\A\w:/, '') if File::PATH_SEPARATOR == ';'
$destdir + dir
end
@@ -108,7 +98,6 @@ arc = CONFIG["LIBRUBY_A"]
makedirs [bindir, libdir, rubylibdir, archlibdir, sitelibdir, sitearchlibdir]
-install?(:bin) do
ruby_bin = File.join(bindir, ruby_install_name)
install ruby_install_name+exeext, ruby_bin+exeext, :mode => 0755
@@ -131,11 +120,9 @@ if dll == lib and dll != arc
ln_sf(dll, File.join(libdir, link))
end
end
-end
-Dir.chdir srcdir
+Dir.chdir CONFIG["srcdir"]
-install?(:lib) do
ruby_shebang = File.join(CONFIG["bindir"], ruby_install_name)
if File::ALT_SEPARATOR
ruby_bin_dosish = ruby_shebang.tr(File::SEPARATOR, File::ALT_SEPARATOR)
@@ -188,9 +175,7 @@ for f in Dir["lib/**/*{.rb,help-message}"]
makedirs dir
install f, dir, :mode => 0644
end
-end
-install?(:bin) do
for f in Dir["*.h"]
install f, archlibdir, :mode => 0644
end
@@ -199,9 +184,7 @@ if RUBY_PLATFORM =~ /mswin32|mingw|bccwin32/
makedirs File.join(archlibdir, "win32")
install "win32/win32.h", File.join(archlibdir, "win32"), :mode => 0644
end
-end
-install?(:man) do
for mdoc in Dir["*.[1-9]"]
next unless File.file?(mdoc) and open(mdoc){|fh| fh.read(1) == '.'}
@@ -228,6 +211,5 @@ for mdoc in Dir["*.[1-9]"]
install w.path, destfile, :mode => 0644
end
end
-end
# vi:set sw=2:
diff --git a/intern.h b/intern.h
index 818fcf891a..f97afade46 100644
--- a/intern.h
+++ b/intern.h
@@ -164,7 +164,6 @@ void rb_dvar_asgn _((ID, VALUE));
void rb_dvar_push _((ID, VALUE));
VALUE *rb_svar _((int));
VALUE rb_eval_cmd _((VALUE, VALUE, int));
-int rb_obj_respond_to _((VALUE, ID, int));
int rb_respond_to _((VALUE, ID));
void rb_interrupt _((void));
VALUE rb_apply _((VALUE, ID, VALUE));
@@ -211,7 +210,6 @@ VALUE rb_thread_create _((VALUE (*)(ANYARGS), void*));
void rb_thread_interrupt _((void));
void rb_thread_trap_eval _((VALUE, int, int));
void rb_thread_signal_raise _((char*));
-void rb_thread_signal_exit _((void));
int rb_thread_select _((int, fd_set *, fd_set *, fd_set *, struct timeval *));
void rb_thread_wait_for _((struct timeval));
VALUE rb_thread_current _((void));
@@ -219,7 +217,6 @@ VALUE rb_thread_main _((void));
VALUE rb_thread_local_aref _((VALUE, ID));
VALUE rb_thread_local_aset _((VALUE, ID, VALUE));
void rb_thread_atfork _((void));
-VALUE rb_funcall_rescue __((VALUE, ID, int, ...));
/* file.c */
int eaccess _((const char*, int));
VALUE rb_file_s_expand_path _((int, VALUE *));
@@ -249,8 +246,8 @@ VALUE rb_gc_enable _((void));
VALUE rb_gc_disable _((void));
VALUE rb_gc_start _((void));
/* hash.c */
-void st_foreach_safe _((struct st_table *, int (*)(ANYARGS), unsigned long));
-void rb_hash_foreach _((VALUE, int (*)(ANYARGS), VALUE));
+void st_foreach _((struct st_table *, int (*)(), unsigned long));
+void rb_hash_foreach _((VALUE, int (*)(), VALUE));
VALUE rb_hash _((VALUE));
VALUE rb_hash_new _((void));
VALUE rb_hash_freeze _((VALUE));
@@ -335,7 +332,6 @@ int rb_is_instance_id _((ID));
int rb_is_class_id _((ID));
int rb_is_local_id _((ID));
int rb_is_junk_id _((ID));
-int rb_symname_p _((const char*));
VALUE rb_backref_get _((void));
void rb_backref_set _((VALUE));
VALUE rb_lastline_get _((void));
@@ -451,7 +447,7 @@ VALUE rb_path2class _((const char*));
void rb_name_class _((VALUE, ID));
VALUE rb_class_name _((VALUE));
void rb_autoload _((VALUE, ID, const char*));
-VALUE rb_autoload_load _((VALUE, ID));
+void rb_autoload_load _((VALUE, ID));
VALUE rb_autoload_p _((VALUE, ID));
void rb_gc_mark_global_tbl _((void));
VALUE rb_f_trace_var _((int, VALUE*));
diff --git a/io.c b/io.c
index 8bd760336e..195392e565 100644
--- a/io.c
+++ b/io.c
@@ -32,7 +32,7 @@
# define NO_LONG_FNAME
#endif
-#if defined(__FreeBSD__) || defined(__NetBSD__) || defined(__OpenBSD__) || defined(__DragonFly__) || defined(sun) || defined(_nec_ews)
+#if defined(__FreeBSD__) || defined(__NetBSD__) || defined(__OpenBSD__) || defined(sun) || defined(_nec_ews)
# define USE_SETVBUF
#endif
@@ -41,7 +41,7 @@
#endif
#include <sys/types.h>
-#if defined(HAVE_SYS_IOCTL_H) && !defined(DJGPP) && !defined(_WIN32) && !defined(__human68k__)
+#if !defined(DJGPP) && !defined(_WIN32) && !defined(__human68k__)
#include <sys/ioctl.h>
#endif
#if defined(HAVE_FCNTL_H) || defined(_WIN32)
@@ -72,12 +72,6 @@
#endif
#ifdef HAVE_UNISTD_H
-#ifdef HAVE_SYSCALL_H
-#include <syscall.h>
-#elif defined HAVE_SYS_SYSCALL_H
-#include <sys/syscall.h>
-#endif
-
#include <unistd.h>
#endif
@@ -92,22 +86,10 @@ extern void Init_File _((void));
#include "util.h"
-#ifndef O_ACCMODE
-#define O_ACCMODE (O_RDONLY | O_WRONLY | O_RDWR)
-#endif
-
#if SIZEOF_OFF_T > SIZEOF_LONG && !defined(HAVE_LONG_LONG)
# error off_t is bigger than long, but you have no long long...
#endif
-#ifndef PIPE_BUF
-# ifdef _POSIX_PIPE_BUF
-# define PIPE_BUF _POSIX_PIPE_BUF
-# else
-# define PIPE_BUF 512 /* is this ok? */
-# endif
-#endif
-
VALUE rb_cIO;
VALUE rb_eEOFError;
VALUE rb_eIOError;
@@ -187,7 +169,7 @@ extern int ReadDataPending();
void
rb_eof_error()
{
- rb_raise(rb_eEOFError, "end of file reached");
+ rb_raise(rb_eEOFError, "End of file reached");
}
VALUE
@@ -269,9 +251,11 @@ rb_io_check_writable(fptr)
if (!(fptr->mode & FMODE_WRITABLE)) {
rb_raise(rb_eIOError, "not opened for writing");
}
+#if NEED_IO_SEEK_BETWEEN_RW
if ((fptr->mode & FMODE_RBUF) && !feof(fptr->f) && !fptr->f2) {
io_seek(fptr, 0, SEEK_CUR);
}
+#endif
if (!fptr->f2) {
fptr->mode &= ~FMODE_RBUF;
}
@@ -336,9 +320,7 @@ io_fflush(f, fptr)
rb_io_check_closed(fptr);
}
for (;;) {
- TRAP_BEG;
n = fflush(f);
- TRAP_END;
if (n != EOF) break;
if (!rb_io_wait_writable(fileno(f)))
rb_sys_fail(fptr->path);
@@ -402,80 +384,25 @@ rb_io_wait_writable(f)
}
}
-#ifndef S_ISREG
-# define S_ISREG(m) ((m & S_IFMT) == S_IFREG)
-#endif
-
-static int
-wsplit_p(OpenFile *fptr)
-{
- FILE *f = GetWriteFile(fptr);
- int r;
- if (!(fptr->mode & FMODE_WSPLIT_INITIALIZED)) {
- struct stat buf;
- if (fstat(fileno(f), &buf) == 0 &&
- !S_ISREG(buf.st_mode)
-#if defined(HAVE_FCNTL) && defined(F_GETFL) && defined(O_NONBLOCK)
- && (r = fcntl(fileno(f), F_GETFL)) != -1 &&
- !(r & O_NONBLOCK)
-#endif
- ) {
- fptr->mode |= FMODE_WSPLIT;
- }
- fptr->mode |= FMODE_WSPLIT_INITIALIZED;
- }
- return fptr->mode & FMODE_WSPLIT;
-}
-
/* writing functions */
-static long
-io_fwrite(str, fptr)
- VALUE str;
- OpenFile *fptr;
+long
+rb_io_fwrite(ptr, len, f)
+ const char *ptr;
+ long len;
+ FILE *f;
{
- long len, n, r, l, offset = 0;
- FILE *f = GetWriteFile(fptr);
+ long n, r;
- len = RSTRING(str)->len;
if ((n = len) <= 0) return n;
- if (fptr->mode & FMODE_SYNC) {
- io_fflush(f, fptr);
- if (!rb_thread_fd_writable(fileno(f))) {
- rb_io_check_closed(fptr);
- }
- retry:
- l = n;
- if (PIPE_BUF < l &&
- !rb_thread_critical &&
- !rb_thread_alone() &&
- wsplit_p(fptr)) {
- l = PIPE_BUF;
- }
- TRAP_BEG;
- r = write(fileno(f), RSTRING(str)->ptr+offset, l);
- TRAP_END;
- if (r == n) return len;
- if (0 <= r) {
- offset += r;
- n -= r;
- errno = EAGAIN;
- }
- if (rb_io_wait_writable(fileno(f))) {
- rb_io_check_closed(fptr);
- if (offset < RSTRING(str)->len)
- goto retry;
- }
- return -1L;
- }
#if defined(__human68k__) || defined(__vms)
do {
- if (fputc(RSTRING(str)->ptr[offset++], f) == EOF) {
+ if (fputc(*ptr++, f) == EOF) {
if (ferror(f)) return -1L;
break;
}
} while (--n > 0);
#else
- while (errno = 0, offset += (r = fwrite(RSTRING(str)->ptr+offset, 1, n, f)), (n -= r) > 0) {
+ while (errno = 0, ptr += (r = fwrite(ptr, 1, n, f)), (n -= r) > 0) {
if (ferror(f)
#if defined __BORLANDC__
|| errno
@@ -483,20 +410,10 @@ io_fwrite(str, fptr)
) {
#ifdef __hpux
if (!errno) errno = EAGAIN;
-#elif defined(_WIN32) && !defined(__BORLANDC__)
- /* workaround for MSVCRT's bug */
- if (!errno) {
- if (GetLastError() == ERROR_NO_DATA)
- errno = EPIPE;
- else
- errno = EBADF;
- }
#endif
if (rb_io_wait_writable(fileno(f))) {
- rb_io_check_closed(fptr);
clearerr(f);
- if (offset < RSTRING(str)->len)
- continue;
+ continue;
}
return -1L;
}
@@ -505,21 +422,6 @@ io_fwrite(str, fptr)
return len - n;
}
-long
-rb_io_fwrite(ptr, len, f)
- const char *ptr;
- long len;
- FILE *f;
-{
- OpenFile of;
-
- of.f = f;
- of.f2 = NULL;
- of.mode = FMODE_WRITABLE;
- of.path = NULL;
- return io_fwrite(rb_str_new(ptr, len), &of);
-}
-
/*
* call-seq:
* ios.write(string) => integer
@@ -543,6 +445,7 @@ io_write(io, str)
VALUE io, str;
{
OpenFile *fptr;
+ FILE *f;
long n;
rb_secure(4);
@@ -557,10 +460,16 @@ io_write(io, str)
GetOpenFile(io, fptr);
rb_io_check_writable(fptr);
+ f = GetWriteFile(fptr);
- n = io_fwrite(str, fptr);
+ rb_str_locktmp(str);
+ n = rb_io_fwrite(RSTRING(str)->ptr, RSTRING(str)->len, f);
+ rb_str_unlocktmp(str);
if (n == -1L) rb_sys_fail(fptr->path);
- if (!(fptr->mode & FMODE_SYNC)) {
+ if (fptr->mode & FMODE_SYNC) {
+ io_fflush(f, fptr);
+ }
+ else {
fptr->mode |= FMODE_WBUF;
}
@@ -663,9 +572,8 @@ rb_io_seek(io, offset, whence)
OpenFile *fptr;
off_t pos;
- pos = NUM2OFFT(offset);
GetOpenFile(io, fptr);
- pos = io_seek(fptr, pos, whence);
+ pos = io_seek(fptr, NUM2OFFT(offset), whence);
if (pos < 0) rb_sys_fail(fptr->path);
clearerr(fptr->f);
@@ -711,7 +619,7 @@ rb_io_seek_m(argc, argv, io)
/*
* call-seq:
- * ios.pos = integer => integer
+ * ios.pos = integer => 0
*
* Seeks to the given position (in bytes) in <em>ios</em>.
*
@@ -727,9 +635,8 @@ rb_io_set_pos(io, offset)
OpenFile *fptr;
off_t pos;
- pos = NUM2OFFT(offset);
GetOpenFile(io, fptr);
- pos = io_seek(fptr, pos, SEEK_SET);
+ pos = io_seek(fptr, NUM2OFFT(offset), SEEK_SET);
if (pos != 0) rb_sys_fail(fptr->path);
clearerr(fptr->f);
@@ -771,32 +678,13 @@ rb_io_rewind(io)
* call-seq:
* ios.eof => true or false
* ios.eof? => true or false
- *
- * Returns true if <em>ios</em> is at end of file that means
- * there are no more data to read.
- * The stream must be opened for reading or an <code>IOError</code> will be
- * raised.
- *
+ *
+ * Returns true if <em>ios</em> is at end of file. The stream must be
+ * opened for reading or an <code>IOError</code> will be raised.
+ *
* f = File.new("testfile")
* dummy = f.readlines
* f.eof #=> true
- *
- * If <em>ios</em> is a stream such as pipe or socket, <code>IO#eof?</code>
- * blocks until the other end sends some data or closes it.
- *
- * r, w = IO.pipe
- * Thread.new { sleep 1; w.close }
- * r.eof? #=> true after 1 second blocking
- *
- * r, w = IO.pipe
- * Thread.new { sleep 1; w.puts "a" }
- * r.eof? #=> false after 1 second blocking
- *
- * r, w = IO.pipe
- * r.eof? # blocks forever
- *
- * Note that <code>IO#eof?</code> reads data to a input buffer.
- * So <code>IO#sysread</code> doesn't work with <code>IO#eof?</code>.
*/
VALUE
@@ -812,7 +700,6 @@ rb_io_eof(io)
if (feof(fptr->f)) return Qtrue;
if (READ_DATA_PENDING(fptr->f)) return Qfalse;
READ_CHECK(fptr->f);
- clearerr(fptr->f);
TRAP_BEG;
ch = getc(fptr->f);
TRAP_END;
@@ -821,7 +708,6 @@ rb_io_eof(io)
ungetc(ch, fptr->f);
return Qfalse;
}
- rb_io_check_closed(fptr);
clearerr(fptr->f);
return Qtrue;
}
@@ -993,7 +879,7 @@ rb_io_inspect(obj)
len += 9;
}
buf = ALLOCA_N(char, len);
- snprintf(buf, len, "#<%s:%s%s>", cname, fptr->path, st);
+ sprintf(buf, "#<%s:%s%s>", cname, fptr->path, st);
return rb_str_new2(buf);
}
@@ -1012,75 +898,63 @@ rb_io_to_io(io)
}
/* reading functions */
-static long
-read_buffered_data(ptr, len, f)
- char *ptr;
- long len;
- FILE *f;
-{
- long n;
-
-#ifdef READ_DATA_PENDING_COUNT
- n = READ_DATA_PENDING_COUNT(f);
- if (n <= 0) return 0;
- if (n > len) n = len;
- return fread(ptr, 1, n, f);
-#else
- int c;
-
- for (n = 0; n < len && READ_DATA_PENDING(f) && (c = getc(f)) != EOF; ++n) {
- *ptr++ = c;
- }
- return n;
-#endif
-}
-
long
-io_fread(ptr, len, fptr)
+rb_io_fread(ptr, len, f)
char *ptr;
long len;
- OpenFile *fptr;
+ FILE *f;
{
long n = len;
int c;
- int saved_errno;
while (n > 0) {
- c = read_buffered_data(ptr, n, fptr->f);
- if (c < 0) goto eof;
- if (c > 0) {
- ptr += c;
- if ((n -= c) <= 0) break;
- }
- rb_thread_wait_fd(fileno(fptr->f));
- rb_io_check_closed(fptr);
- clearerr(fptr->f);
+#ifdef READ_DATA_PENDING_COUNT
+ long i = READ_DATA_PENDING_COUNT(f);
+ if (i <= 0) {
+ rb_thread_wait_fd(fileno(f));
+ i = READ_DATA_PENDING_COUNT(f);
+ }
+ if (i > 0) {
+ if (i > n) i = n;
+ TRAP_BEG;
+ c = fread(ptr, 1, i, f);
+ TRAP_END;
+ if (c < 0) goto eof;
+ ptr += c;
+ n -= c;
+ if (c < i) goto eof;
+ continue;
+ }
+#else
+ if (!READ_DATA_PENDING(f)) {
+ rb_thread_wait_fd(fileno(f));
+ }
+#endif
TRAP_BEG;
- c = getc(fptr->f);
+ c = getc(f);
TRAP_END;
if (c == EOF) {
eof:
- if (ferror(fptr->f)) {
+ if (ferror(f)) {
switch (errno) {
case EINTR:
#if defined(ERESTART)
case ERESTART:
#endif
- clearerr(fptr->f);
+ clearerr(f);
continue;
case EAGAIN:
#if defined(EWOULDBLOCK) && EWOULDBLOCK != EAGAIN
case EWOULDBLOCK:
#endif
if (len > n) {
- clearerr(fptr->f);
+ clearerr(f);
}
- saved_errno = errno;
- rb_warning("nonblocking IO#read is obsolete; use IO#readpartial or IO#sysread");
- errno = saved_errno;
+ rb_thread_wait_fd(fileno(f));
}
if (len == n) return 0;
}
+ *ptr = '\0';
break;
}
*ptr++ = c;
@@ -1089,18 +963,9 @@ io_fread(ptr, len, fptr)
return len - n;
}
-long
-rb_io_fread(ptr, len, f)
- char *ptr;
- long len;
- FILE *f;
-{
- OpenFile of;
-
- of.f = f;
- of.f2 = NULL;
- return io_fread(ptr, len, &of);
-}
+#ifndef S_ISREG
+# define S_ISREG(m) ((m & S_IFMT) == S_IFREG)
+#endif
#define SMALLBUF 100
@@ -1141,17 +1006,19 @@ read_all(fptr, siz, str)
if (siz == 0) siz = BUFSIZ;
if (NIL_P(str)) {
- str = rb_str_new(0, siz);
+ str = rb_tainted_str_new(0, siz);
}
else {
+ StringValue(str);
rb_str_resize(str, siz);
}
for (;;) {
rb_str_locktmp(str);
READ_CHECK(fptr->f);
- n = io_fread(RSTRING(str)->ptr+bytes, siz-bytes, fptr);
+ n = rb_io_fread(RSTRING(str)->ptr+bytes, siz-bytes, fptr->f);
rb_str_unlocktmp(str);
if (n == 0 && bytes == 0) {
+ rb_str_resize(str,0);
if (!fptr->f) break;
if (feof(fptr->f)) break;
if (!ferror(fptr->f)) break;
@@ -1163,147 +1030,20 @@ read_all(fptr, siz, str)
rb_str_resize(str, siz);
}
if (bytes != siz) rb_str_resize(str, bytes);
- OBJ_TAINT(str);
return str;
}
-static VALUE
-io_getpartial(int argc, VALUE *argv, VALUE io)
-{
- OpenFile *fptr;
- VALUE length, str;
- long n, len;
-
- rb_scan_args(argc, argv, "11", &length, &str);
-
- if ((len = NUM2LONG(length)) < 0) {
- rb_raise(rb_eArgError, "negative length %ld given", len);
- }
-
- if (NIL_P(str)) {
- str = rb_str_new(0, len);
- }
- else {
- StringValue(str);
- rb_str_modify(str);
- rb_str_resize(str, len);
- }
- OBJ_TAINT(str);
-
- GetOpenFile(io, fptr);
- rb_io_check_readable(fptr);
-
- if (len == 0)
- return str;
-
- READ_CHECK(fptr->f);
- if (RSTRING(str)->len != len) {
- modified:
- rb_raise(rb_eRuntimeError, "buffer string modified");
- }
- n = read_buffered_data(RSTRING(str)->ptr, len, fptr->f);
- if (n <= 0) {
- again:
- if (RSTRING(str)->len != len) goto modified;
- TRAP_BEG;
- n = read(fileno(fptr->f), RSTRING(str)->ptr, len);
- TRAP_END;
- if (n < 0) {
- if (rb_io_wait_readable(fileno(fptr->f)))
- goto again;
- rb_sys_fail(fptr->path);
- }
- }
- rb_str_resize(str, n);
-
- if (n == 0)
- return Qnil;
- else
- return str;
-}
-
-/*
- * call-seq:
- * ios.readpartial(maxlen[, outbuf]) => string, outbuf
- *
- * Reads at most <i>maxlen</i> bytes from the I/O stream but
- * it blocks only if <em>ios</em> has no data immediately available.
- * If the optional <i>outbuf</i> argument is present,
- * it must reference a String, which will receive the data.
- * It raises <code>EOFError</code> on end of file.
- *
- * readpartial is designed for streams such as pipe, socket, tty, etc.
- * It blocks only when no data immediately available.
- * This means that it blocks only when following all conditions hold.
- * * the buffer in the IO object is empty.
- * * the content of the stream is empty.
- * * the stream is not reached to EOF.
- *
- * When readpartial blocks, it waits data or EOF on the stream.
- * If some data is reached, readpartial returns with the data.
- * If EOF is reached, readpartial raises EOFError.
- *
- * When readpartial doesn't blocks, it returns or raises immediately.
- * If the buffer is not empty, it returns the data in the buffer.
- * Otherwise if the stream has some content,
- * it returns the data in the stream.
- * Otherwise if the stream is reached to EOF, it raises EOFError.
- *
- * r, w = IO.pipe # buffer pipe content
- * w << "abc" # "" "abc".
- * r.readpartial(4096) #=> "abc" "" ""
- * r.readpartial(4096) # blocks because buffer and pipe is empty.
- *
- * r, w = IO.pipe # buffer pipe content
- * w << "abc" # "" "abc"
- * w.close # "" "abc" EOF
- * r.readpartial(4096) #=> "abc" "" EOF
- * r.readpartial(4096) # raises EOFError
- *
- * r, w = IO.pipe # buffer pipe content
- * w << "abc\ndef\n" # "" "abc\ndef\n"
- * r.gets #=> "abc\n" "def\n" ""
- * w << "ghi\n" # "def\n" "ghi\n"
- * r.readpartial(4096) #=> "def\n" "" "ghi\n"
- * r.readpartial(4096) #=> "ghi\n" "" ""
- *
- * Note that readpartial is nonblocking-flag insensitive.
- * It blocks even if the nonblocking-flag is set.
- *
- * Also note that readpartial behaves similar to sysread in blocking mode.
- * The behavior is identical when the buffer is empty.
- *
- */
-
-static VALUE
-io_readpartial(int argc, VALUE *argv, VALUE io)
-{
- VALUE ret;
-
- ret = io_getpartial(argc, argv, io);
- if (NIL_P(ret))
- rb_eof_error();
- else
- return ret;
-}
-
/*
* call-seq:
- * ios.read([length [, buffer]]) => string, buffer, or nil
- *
- * Reads at most <i>length</i> bytes from the I/O stream, or to the
- * end of file if <i>length</i> is omitted or is <code>nil</code>.
- * <i>length</i> must be a non-negative integer or nil.
+ * ios.read([integer [, buffer]]) => string, buffer, or nil
+ *
+ * Reads at most <i>integer</i> bytes from the I/O stream, or to the
+ * end of file if <i>integer</i> is omitted or is <code>nil</code>.
* If the optional <i>buffer</i> argument is present, it must reference
- * a String, which will receive the data.
- *
- * At end of file, it returns <code>nil</code> or <code>""</code>
- * depend on <i>length</i>.
- * <code><i>ios</i>.read()</code> and
- * <code><i>ios</i>.read(nil)</code> returns <code>""</code>.
- * <code><i>ios</i>.read(<i>positive-integer</i>)</code> returns nil.
- *
+ * a String, which will receive the data. Returns <code>nil</code>
+ * if called at end of file.
+ *
* f = File.new("testfile")
* f.read(16) #=> "This is line one"
*/
@@ -1320,47 +1060,38 @@ io_read(argc, argv, io)
rb_scan_args(argc, argv, "02", &length, &str);
+ GetOpenFile(io, fptr);
+ rb_io_check_readable(fptr);
if (NIL_P(length)) {
- if (!NIL_P(str)) StringValue(str);
- GetOpenFile(io, fptr);
- rb_io_check_readable(fptr);
return read_all(fptr, remain_size(fptr), str);
}
+
len = NUM2LONG(length);
if (len < 0) {
rb_raise(rb_eArgError, "negative length %ld given", len);
}
+ if (feof(fptr->f)) return Qnil;
if (NIL_P(str)) {
- str = rb_tainted_str_new(0, len);
+ str = rb_str_new(0, len);
}
else {
StringValue(str);
rb_str_modify(str);
rb_str_resize(str,len);
}
-
- GetOpenFile(io, fptr);
- rb_io_check_readable(fptr);
- if (feof(fptr->f)) return Qnil;
if (len == 0) return str;
rb_str_locktmp(str);
READ_CHECK(fptr->f);
- if (RSTRING(str)->len != len) {
- rb_raise(rb_eRuntimeError, "buffer string modified");
- }
- n = io_fread(RSTRING(str)->ptr, len, fptr);
+ n = rb_io_fread(RSTRING(str)->ptr, len, fptr->f);
rb_str_unlocktmp(str);
if (n == 0) {
+ rb_str_resize(str,0);
if (!fptr->f) return Qnil;
- if (feof(fptr->f)) {
- rb_str_resize(str, 0);
- return Qnil;
- }
+ if (feof(fptr->f)) return Qnil;
if (len > 0) rb_sys_fail(fptr->path);
}
- rb_str_resize(str, n);
RSTRING(str)->len = n;
RSTRING(str)->ptr[n] = '\0';
OBJ_TAINT(str);
@@ -1422,7 +1153,6 @@ appendline(fptr, delim, strp)
#else
READ_CHECK(f);
#endif
- clearerr(f);
TRAP_BEG;
c = getc(f);
TRAP_END;
@@ -1500,7 +1230,6 @@ swallow(fptr, term)
#else
READ_CHECK(f);
#endif
- clearerr(f);
TRAP_BEG;
c = getc(f);
TRAP_END;
@@ -1542,16 +1271,13 @@ rscheck(rsptr, rslen, rs)
return 1;
}
-static VALUE rb_io_getline(VALUE rs, VALUE io);
-
static VALUE
-rb_io_getline(rs, io)
- VALUE rs, io;
+rb_io_getline(rs, fptr)
+ VALUE rs;
+ OpenFile *fptr;
{
VALUE str = Qnil;
- OpenFile *fptr;
- GetOpenFile(io, fptr);
rb_io_check_readable(fptr);
if (NIL_P(rs)) {
str = read_all(fptr, 0, Qnil);
@@ -1566,6 +1292,7 @@ rb_io_getline(rs, io)
long rslen;
int rspara = 0;
+ StringValue(rs);
rslen = RSTRING(rs)->len;
if (rslen == 0) {
rsptr = "\n\n";
@@ -1637,15 +1364,16 @@ rb_io_gets_m(argc, argv, io)
VALUE io;
{
VALUE rs, str;
+ OpenFile *fptr;
if (argc == 0) {
rs = rb_rs;
}
else {
rb_scan_args(argc, argv, "1", &rs);
- if (!NIL_P(rs)) StringValue(rs);
}
- str = rb_io_getline(rs, io);
+ GetOpenFile(io, fptr);
+ str = rb_io_getline(rs, fptr);
rb_lastline_set(str);
return str;
@@ -1763,7 +1491,7 @@ rb_io_readline(argc, argv, io)
*
* Reads all of the lines in <em>ios</em>, and returns them in
* <i>anArray</i>. Lines are separated by the optional
- * <i>sep_string</i>. If <i>sep_string</i> is <code>nil</code>, the
+ * <i>sep_string</i>. If <i>set_string</i> is <code>nil</code>, the
* rest of the stream is returned as a single record.
* The stream must be opened for reading or an
* <code>IOError</code> will be raised.
@@ -1780,16 +1508,17 @@ rb_io_readlines(argc, argv, io)
{
VALUE line, ary;
VALUE rs;
+ OpenFile *fptr;
if (argc == 0) {
rs = rb_rs;
}
else {
rb_scan_args(argc, argv, "1", &rs);
- if (!NIL_P(rs)) StringValue(rs);
}
+ GetOpenFile(io, fptr);
ary = rb_ary_new();
- while (!NIL_P(line = rb_io_getline(rs, io))) {
+ while (!NIL_P(line = rb_io_getline(rs, fptr))) {
rb_ary_push(ary, line);
}
return ary;
@@ -1822,6 +1551,7 @@ rb_io_each_line(argc, argv, io)
VALUE io;
{
VALUE str;
+ OpenFile *fptr;
VALUE rs;
if (argc == 0) {
@@ -1829,9 +1559,9 @@ rb_io_each_line(argc, argv, io)
}
else {
rb_scan_args(argc, argv, "1", &rs);
- if (!NIL_P(rs)) StringValue(rs);
}
- while (!NIL_P(str = rb_io_getline(rs, io))) {
+ GetOpenFile(io, fptr);
+ while (!NIL_P(str = rb_io_getline(rs, fptr))) {
rb_yield(str);
}
return io;
@@ -1865,7 +1595,6 @@ rb_io_each_byte(io)
rb_io_check_readable(fptr);
f = fptr->f;
READ_CHECK(f);
- clearerr(f);
TRAP_BEG;
c = getc(f);
TRAP_END;
@@ -1910,7 +1639,6 @@ rb_io_getc(io)
retry:
READ_CHECK(f);
- clearerr(f);
TRAP_BEG;
c = getc(f);
TRAP_END;
@@ -1936,7 +1664,6 @@ rb_getc(f)
if (!READ_DATA_PENDING(f)) {
rb_thread_wait_fd(fileno(f));
}
- clearerr(f);
TRAP_BEG;
c = getc(f);
TRAP_END;
@@ -2031,29 +1758,22 @@ fptr_finalize(fptr, noraise)
if (fptr->f2) {
f2 = fileno(fptr->f2);
- while (n2 = 0, fflush(fptr->f2) < 0) {
+ while (n2 = 0, fclose(fptr->f2) < 0) {
n2 = errno;
if (!rb_io_wait_writable(f2)) {
break;
}
if (!fptr->f2) break;
}
- if (fclose(fptr->f2) < 0 && n2 == 0) {
- n2 = errno;
- }
fptr->f2 = 0;
}
if (fptr->f) {
f1 = fileno(fptr->f);
- if ((f2 == -1) && (fptr->mode & FMODE_WBUF)) {
- while (n1 = 0, fflush(fptr->f) < 0) {
- n1 = errno;
- if (!rb_io_wait_writable(f1)) break;
- if (!fptr->f) break;
- }
- }
- if (fclose(fptr->f) < 0 && n1 == 0) {
+ while (n1 = 0, fclose(fptr->f) < 0) {
n1 = errno;
+ if (f2 != -1 || !(fptr->mode & FMODE_WBUF)) break;
+ if (!rb_io_wait_writable(f1)) break;
+ if (!fptr->f) break;
}
fptr->f = 0;
if (n1 == EBADF && f1 == f2) {
@@ -2150,10 +1870,6 @@ static VALUE
io_close(io)
VALUE io;
{
- if (TYPE(io) == T_FILE) {
- rb_io_close(io);
- return Qnil;
- }
return rb_funcall(io, rb_intern("close"), 0, 0);
}
@@ -2301,7 +2017,7 @@ rb_io_sysseek(argc, argv, io)
if (rb_scan_args(argc, argv, "11", &offset, &ptrname) == 2) {
whence = NUM2INT(ptrname);
}
- pos = NUM2OFFT(offset);
+
GetOpenFile(io, fptr);
if ((fptr->mode & FMODE_READABLE) && READ_DATA_BUFFERED(fptr->f)) {
rb_raise(rb_eIOError, "sysseek for buffered IO");
@@ -2309,7 +2025,7 @@ rb_io_sysseek(argc, argv, io)
if ((fptr->mode & FMODE_WRITABLE) && (fptr->mode & FMODE_WBUF)) {
rb_warn("sysseek for buffered IO");
}
- pos = lseek(fileno(fptr->f), pos, whence);
+ pos = lseek(fileno(fptr->f), NUM2OFFT(offset), whence);
if (pos == -1) rb_sys_fail(fptr->path);
clearerr(fptr->f);
@@ -2318,7 +2034,7 @@ rb_io_sysseek(argc, argv, io)
/*
* call-seq:
- * ios.syswrite(string) => integer
+ * ios.syswrite(string ) => integer
*
* Writes the given string to <em>ios</em> using a low-level write.
* Returns the number of bytes written. Do not mix with other methods
@@ -2351,9 +2067,7 @@ rb_io_syswrite(io, str)
if (!rb_thread_fd_writable(fileno(f))) {
rb_io_check_closed(fptr);
}
- TRAP_BEG;
n = write(fileno(f), RSTRING(str)->ptr, RSTRING(str)->len);
- TRAP_END;
if (n == -1) rb_sys_fail(fptr->path);
@@ -2386,7 +2100,12 @@ rb_io_sysread(argc, argv, io)
rb_scan_args(argc, argv, "11", &len, &str);
ilen = NUM2LONG(len);
+ GetOpenFile(io, fptr);
+ rb_io_check_readable(fptr);
+ if (READ_DATA_BUFFERED(fptr->f)) {
+ rb_raise(rb_eIOError, "sysread for buffered IO");
+ }
if (NIL_P(str)) {
str = rb_str_new(0, ilen);
}
@@ -2397,32 +2116,21 @@ rb_io_sysread(argc, argv, io)
}
if (ilen == 0) return str;
- GetOpenFile(io, fptr);
- rb_io_check_readable(fptr);
-
- if (READ_DATA_BUFFERED(fptr->f)) {
- rb_raise(rb_eIOError, "sysread for buffered IO");
- }
- rb_str_locktmp(str);
-
n = fileno(fptr->f);
rb_thread_wait_fd(fileno(fptr->f));
- rb_io_check_closed(fptr);
- if (RSTRING(str)->len != ilen) {
- rb_raise(rb_eRuntimeError, "buffer string modified");
- }
TRAP_BEG;
- n = read(fileno(fptr->f), RSTRING(str)->ptr, ilen);
+ n = read(fileno(fptr->f), RSTRING(str)->ptr, RSTRING(str)->len);
TRAP_END;
- rb_str_unlocktmp(str);
if (n == -1) {
+ rb_str_resize(str, 0);
rb_sys_fail(fptr->path);
}
- rb_str_resize(str, n);
if (n == 0 && ilen > 0) {
+ rb_str_resize(str, 0);
rb_eof_error();
}
+
RSTRING(str)->len = n;
RSTRING(str)->ptr[n] = '\0';
OBJ_TAINT(str);
@@ -2490,7 +2198,7 @@ rb_io_flags_mode(flags)
}
return MODE_BINMODE("r+", "rb+");
}
- rb_raise(rb_eArgError, "illegal access modenum %o", flags);
+ rb_raise(rb_eArgError, "illegal access mode %o", flags);
return NULL; /* not reached */
}
@@ -2532,7 +2240,7 @@ rb_io_mode_flags(mode)
return flags;
}
-int
+static int
rb_io_modenum_flags(mode)
int mode;
{
@@ -2595,7 +2303,7 @@ rb_io_mode_modenum(mode)
#endif
break;
case '+':
- flags = (flags & ~O_ACCMODE) | O_RDWR;
+ flags |= O_RDWR;
break;
default:
goto error;
@@ -3209,7 +2917,7 @@ rb_io_s_sysopen(argc, argv)
/*
* call-seq:
* open(path [, mode [, perm]] ) => io or nil
- * open(path [, mode [, perm]] ) {|io| block } => obj
+ * open(path [, mode [. perm]] ) {|io| block } => nil
*
* Creates an <code>IO</code> object connected to the given stream,
* file, or subprocess.
@@ -3222,8 +2930,8 @@ rb_io_s_sysopen(argc, argv)
*
* If a block is specified, it will be invoked with the
* <code>File</code> object as a parameter, and the file will be
- * automatically closed when the block terminates. The call
- * returns the value of the block.
+ * automatically closed when the block terminates. The call always
+ * returns <code>nil</code> in this case.
*
* If <i>path</i> starts with a pipe character, a subprocess is
* created, connected to the caller by a pair of pipes. The returned
@@ -3397,22 +3105,10 @@ io_reopen(io, nfile)
rb_sys_fail(orig->path);
}
else {
- FILE *f2 = fptr->f2;
- int m = fptr->mode;
fclose(fptr->f);
- fptr->f = f2;
- fptr->f2 = NULL;
- fptr->mode &= (m & FMODE_READABLE) ? ~FMODE_READABLE : ~FMODE_WRITABLE;
if (dup2(fd2, fd) < 0)
rb_sys_fail(orig->path);
- if (f2) {
- fptr->f = rb_fdopen(fd, "r");
- fptr->f2 = f2;
- }
- else {
- fptr->f = rb_fdopen(fd, mode);
- }
- fptr->mode = m;
+ fptr->f = rb_fdopen(fd, mode);
}
rb_thread_fd_close(fd);
if ((orig->mode & FMODE_READABLE) && pos >= 0) {
@@ -3524,7 +3220,6 @@ rb_io_reopen(argc, argv, file)
return file;
}
-/* :nodoc: */
static VALUE
rb_io_init_copy(dest, io)
VALUE dest, io;
@@ -3641,7 +3336,7 @@ rb_f_printf(argc, argv)
* ios.print(obj, ...) => nil
*
* Writes the given object(s) to <em>ios</em>. The stream must be
- * opened for writing. If the output record separator (<code>$\\</code>)
+ * opened for writing. If the output record separator (<code>$\</code>)
* is not <code>nil</code>, it will be appended to the output. If no
* arguments are given, prints <code>$_</code>. Objects that aren't
* strings will be converted by calling their <code>to_s</code> method.
@@ -3697,7 +3392,7 @@ rb_io_print(argc, argv, out)
* Prints each object in turn to <code>$stdout</code>. If the output
* field separator (<code>$,</code>) is not +nil+, its
* contents will appear between each field. If the output record
- * separator (<code>$\\</code>) is not +nil+, it will be
+ * separator (<code>$\</code>) is not +nil+, it will be
* appended to the output. If no arguments are given, prints
* <code>$_</code>. Objects that aren't strings will be converted by
* calling their <code>to_s</code> method.
@@ -3869,7 +3564,8 @@ rb_p(obj) /* for debug print within C code */
*
* For each object, directly writes
* _obj_.+inspect+ followed by the current output
- * record separator to the program's standard output.
+ * record separator to the program's standard output. +p+
+ * bypasses the Ruby I/O libraries.
*
* S = Struct.new(:name, :state)
* s = S['dave', 'TX']
@@ -4078,7 +3774,7 @@ rb_io_initialize(argc, argv, io)
}
MakeOpenFile(io, fp);
fp->mode = rb_io_modenum_flags(flags);
- fp->f = rb_fdopen(fd, rb_io_modenum_mode(flags));
+ fp->f = rb_fdopen(fd, rb_io_modenum_mode(flags));
return io;
}
@@ -4111,7 +3807,9 @@ rb_file_initialize(argc, argv, io)
VALUE io;
{
if (RFILE(io)->fptr) {
- rb_raise(rb_eRuntimeError, "reinitializing File");
+ rb_io_close_m(io);
+ free(RFILE(io)->fptr);
+ RFILE(io)->fptr = 0;
}
if (0 < argc && argc < 3) {
VALUE fd = rb_check_convert_type(argv[0], T_FIXNUM, "Fixnum", "to_int");
@@ -4337,15 +4035,16 @@ argf_getline(argc, argv)
}
else {
VALUE rs;
+ OpenFile *fptr;
if (argc == 0) {
rs = rb_rs;
}
else {
rb_scan_args(argc, argv, "1", &rs);
- if (!NIL_P(rs)) StringValue(rs);
}
- line = rb_io_getline(rs, current_file);
+ GetOpenFile(current_file, fptr);
+ line = rb_io_getline(rs, fptr);
}
if (NIL_P(line) && next_p != -1) {
argf_close(current_file);
@@ -4434,7 +4133,7 @@ rb_gets()
/*
* call-seq:
- * readline(separator=$/) => string
+ * readline(separator=$/ => string
*
* Equivalent to <code>Kernel::gets</code>, except
* +readline+ raises +EOFError+ at end of file.
@@ -4476,7 +4175,7 @@ rb_f_getc()
* readlines(separator=$/) => array
*
* Returns an array containing the lines returned by calling
- * <code>Kernel.gets(<i>separator</i>)</code> until the end of file.
+ * <code>Kernel.gets(<i>aString</i>)</code> until the end of file.
*/
static VALUE
@@ -4643,7 +4342,7 @@ rb_f_select(argc, argv, obj)
GetOpenFile(rb_io_get_io(RARRAY(read)->ptr[i]), fptr);
if (FD_ISSET(fileno(fptr->f), rp)
|| FD_ISSET(fileno(fptr->f), &pset)) {
- rb_ary_push(list, rb_ary_entry(read, i));
+ rb_ary_push(list, RARRAY(read)->ptr[i]);
}
}
}
@@ -4653,10 +4352,10 @@ rb_f_select(argc, argv, obj)
for (i=0; i< RARRAY(write)->len; i++) {
GetOpenFile(rb_io_get_io(RARRAY(write)->ptr[i]), fptr);
if (FD_ISSET(fileno(fptr->f), wp)) {
- rb_ary_push(list, rb_ary_entry(write, i));
+ rb_ary_push(list, RARRAY(write)->ptr[i]);
}
else if (fptr->f2 && FD_ISSET(fileno(fptr->f2), wp)) {
- rb_ary_push(list, rb_ary_entry(write, i));
+ rb_ary_push(list, RARRAY(write)->ptr[i]);
}
}
}
@@ -4666,10 +4365,10 @@ rb_f_select(argc, argv, obj)
for (i=0; i< RARRAY(except)->len; i++) {
GetOpenFile(rb_io_get_io(RARRAY(except)->ptr[i]), fptr);
if (FD_ISSET(fileno(fptr->f), ep)) {
- rb_ary_push(list, rb_ary_entry(except, i));
+ rb_ary_push(list, RARRAY(except)->ptr[i]);
}
else if (fptr->f2 && FD_ISSET(fileno(fptr->f2), ep)) {
- rb_ary_push(list, rb_ary_entry(except, i));
+ rb_ary_push(list, RARRAY(except)->ptr[i]);
}
}
}
@@ -4719,6 +4418,7 @@ rb_io_ctl(io, req, arg, io_p)
int retval;
rb_secure(2);
+ GetOpenFile(io, fptr);
if (NIL_P(arg) || arg == Qfalse) {
narg = 0;
@@ -4759,7 +4459,6 @@ rb_io_ctl(io, req, arg, io_p)
narg = (long)RSTRING(arg)->ptr;
}
}
- GetOpenFile(io, fptr);
retval = io_cntl(fileno(fptr->f), cmd, narg, io_p);
if (retval < 0) rb_sys_fail(fptr->path);
if (TYPE(arg) == T_STRING && RSTRING(arg)->ptr[len] != 17) {
@@ -4771,16 +4470,6 @@ rb_io_ctl(io, req, arg, io_p)
io_cntl(fileno(fptr->f2), cmd, narg, io_p);
}
- if (!io_p && cmd == F_SETFL) {
- if (narg & O_NONBLOCK) {
- fptr->mode |= FMODE_WSPLIT_INITIALIZED;
- fptr->mode &= ~FMODE_WSPLIT;
- }
- else {
- fptr->mode &= ~(FMODE_WSPLIT_INITIALIZED|FMODE_WSPLIT);
- }
- }
-
return INT2NUM(retval);
#else
rb_notimplement();
@@ -5051,6 +4740,7 @@ struct foreach_arg {
int argc;
VALUE sep;
VALUE io;
+ OpenFile *fptr;
};
static VALUE
@@ -5059,7 +4749,7 @@ io_s_foreach(arg)
{
VALUE str;
- while (!NIL_P(str = rb_io_getline(arg->sep, arg->io))) {
+ while (!NIL_P(str = rb_io_getline(arg->sep, arg->fptr))) {
rb_yield(str);
}
return Qnil;
@@ -5087,7 +4777,8 @@ rb_io_s_foreach(argc, argv)
int argc;
VALUE *argv;
{
- VALUE fname;
+ VALUE fname, io;
+ OpenFile *fptr;
struct foreach_arg arg;
rb_scan_args(argc, argv, "11", &fname, &arg.sep);
@@ -5096,13 +4787,12 @@ rb_io_s_foreach(argc, argv)
if (argc == 1) {
arg.sep = rb_default_rs;
}
- else if (!NIL_P(arg.sep)) {
- StringValue(arg.sep);
- }
- arg.io = rb_io_open(RSTRING(fname)->ptr, "r");
- if (NIL_P(arg.io)) return Qnil;
+ io = rb_io_open(RSTRING(fname)->ptr, "r");
+ if (NIL_P(io)) return Qnil;
+ GetOpenFile(io, fptr);
+ arg.fptr = fptr;
- return rb_ensure(io_s_foreach, (VALUE)&arg, rb_io_close, arg.io);
+ return rb_ensure(io_s_foreach, (VALUE)&arg, rb_io_close, io);
}
static VALUE
@@ -5152,7 +4842,7 @@ io_s_read(arg)
/*
* call-seq:
- * IO.read(name, [length [, offset]] ) => string
+ * IO.read(rane, [length [, offset]] ) => string
*
* Opens the file, optionally seeks to the given offset, then returns
* <i>length</i> bytes (defaulting to the rest of the file).
@@ -5632,7 +5322,6 @@ Init_IO()
rb_define_method(rb_cIO, "readlines", rb_io_readlines, -1);
- rb_define_method(rb_cIO, "readpartial", io_readpartial, -1);
rb_define_method(rb_cIO, "read", io_read, -1);
rb_define_method(rb_cIO, "write", io_write, 1);
rb_define_method(rb_cIO, "gets", rb_io_gets_m, -1);
diff --git a/lib/.document b/lib/.document
index 8029750178..e93b0e63e2 100644
--- a/lib/.document
+++ b/lib/.document
@@ -13,20 +13,15 @@ cgi.rb
cgi
complex.rb
date.rb
-delegate.rb
-erb.rb
English.rb
fileutils.rb
find.rb
-forwardable.rb
generator.rb
logger.rb
matrix.rb
observer.rb
optionparser.rb
pathname.rb
-pstore.rb
-rational.rb
set.rb
shellwords.rb
singleton.rb
@@ -35,5 +30,4 @@ test/unit.rb
thread.rb
thwait.rb
time.rb
-uri
yaml.rb
diff --git a/lib/cgi-lib.rb b/lib/cgi-lib.rb
index d6b60d66cc..bc780ffc4e 100644
--- a/lib/cgi-lib.rb
+++ b/lib/cgi-lib.rb
@@ -1,5 +1,3 @@
-warn "Warning:#{caller[0].sub(/:in `.*'\z/, '')}: cgi-lib is deprecated after Ruby 1.8.1; use cgi instead"
-
=begin
= simple CGI support library
diff --git a/lib/cgi.rb b/lib/cgi.rb
index 2d75ac2488..0fd0bc7cd4 100644
--- a/lib/cgi.rb
+++ b/lib/cgi.rb
@@ -770,7 +770,7 @@ class CGI
# cookie1.domain = 'domain'
# cookie1.expires = Time.now + 30
# cookie1.secure = true
- class Cookie < DelegateClass(Array)
+ class Cookie < SimpleDelegator
# Create a new CGI::Cookie object.
#
@@ -870,16 +870,15 @@ class CGI
cookies = Hash.new([])
return cookies unless raw_cookie
- raw_cookie.split(/[;,]\s?/).each do |pairs|
+ raw_cookie.split(/; /).each do |pairs|
name, values = pairs.split('=',2)
next unless name and values
name = CGI::unescape(name)
values ||= ""
values = values.split('&').collect{|v| CGI::unescape(v) }
- if cookies.has_key?(name)
- values = cookies[name].value + values
+ unless cookies.has_key?(name)
+ cookies[name] = Cookie::new({ "name" => name, "value" => values })
end
- cookies[name] = Cookie::new({ "name" => name, "value" => values })
end
cookies
diff --git a/lib/cgi/session.rb b/lib/cgi/session.rb
index 562e571cd5..9a49fdedc9 100644
--- a/lib/cgi/session.rb
+++ b/lib/cgi/session.rb
@@ -155,14 +155,11 @@ class CGI
#
class Session
- class NoSession < RuntimeError #:nodoc:
- end
-
# The id of this session.
- attr_reader :session_id, :new_session
+ attr_reader :session_id
def Session::callback(dbman) #:nodoc:
- Proc.new{
+ lambda{
dbman[0].close unless dbman.empty?
}
end
@@ -173,7 +170,7 @@ class CGI
# a random number, and a constant string. This routine
# is used internally for automatically generated
# session ids.
- def create_new_id
+ def Session::create_new_id
require 'digest/md5'
md5 = Digest::MD5::new
now = Time::now
@@ -182,10 +179,8 @@ class CGI
md5.update(String(rand(0)))
md5.update(String($$))
md5.update('foobar')
- @new_session = true
- md5.hexdigest
+ md5.hexdigest[0,16]
end
- private :create_new_id
# Create a new CGI::Session object for +request+.
#
@@ -244,45 +239,36 @@ class CGI
# end
#
def initialize(request, option={})
- @new_session = false
session_key = option['session_key'] || '_session_id'
- session_id = option['session_id']
- unless session_id
+ id = option['session_id']
+ unless id
if option['new_session']
- session_id = create_new_id
+ id = Session::create_new_id
end
end
- unless session_id
+ unless id
if request.key?(session_key)
- session_id = request[session_key]
- session_id = session_id.read if session_id.respond_to?(:read)
+ id = request[session_key]
+ id = id.read if id.respond_to?(:read)
end
- unless session_id
- session_id, = request.cookies[session_key]
+ unless id
+ id, = request.cookies[session_key]
end
- unless session_id
- unless option.fetch('new_session', true)
+ unless id
+ if option.key?('new_session') and not option['new_session']
raise ArgumentError, "session_key `%s' should be supplied"%session_key
end
- session_id = create_new_id
+ id = Session::create_new_id
end
end
- @session_id = session_id
+ @session_id = id
dbman = option['database_manager'] || FileStore
- begin
- @dbman = dbman::new(self, option)
- rescue NoSession
- unless option.fetch('new_session', true)
- raise ArgumentError, "invalid session_id `%s'"%session_id
- end
- session_id = @session_id = create_new_id
- retry
- end
+ @dbman = dbman::new(self, option)
request.instance_eval do
- @output_hidden = {session_key => session_id} unless option['no_hidden']
+ @output_hidden = {session_key => id}
@output_cookies = [
Cookie::new("name" => session_key,
- "value" => session_id,
+ "value" => id,
"expires" => option['session_expires'],
"domain" => option['session_domain'],
"secure" => option['session_secure'],
@@ -293,7 +279,7 @@ class CGI
else
""
end)
- ] unless option['no_cookies']
+ ]
end
@dbprot = [@dbman]
ObjectSpace::define_finalizer(self, Session::callback(@dbprot))
@@ -366,24 +352,17 @@ class CGI
# prefix:: the prefix to add to the session id when generating
# the filename for this session's FileStore file.
# Defaults to the empty string.
- # suffix:: the prefix to add to the session id when generating
- # the filename for this session's FileStore file.
- # Defaults to the empty string.
#
# This session's FileStore file will be created if it does
# not exist, or opened if it does.
def initialize(session, option={})
dir = option['tmpdir'] || Dir::tmpdir
- prefix = option['prefix'] || ''
- suffix = option['suffix'] || ''
+ prefix = option['prefix'] || ''
id = session.session_id
require 'digest/md5'
md5 = Digest::MD5.hexdigest(id)[0,16]
- @path = dir+"/"+prefix+md5+suffix
+ @path = dir+"/"+prefix+md5
unless File::exist? @path
- unless session.new_session
- raise CGI::Session::NoSession, "uninitialized session"
- end
@hash = {}
end
end
@@ -450,12 +429,7 @@ class CGI
# currently recognised.
def initialize(session, option=nil)
@session_id = session.session_id
- unless GLOBAL_HASH_TABLE.key?(@session_id)
- unless session.new_session
- raise CGI::Session::NoSession, "uninitialized session"
- end
- GLOBAL_HASH_TABLE[@session_id] = {}
- end
+ GLOBAL_HASH_TABLE[@session_id] ||= {}
end
# Restore session state.
diff --git a/lib/cgi/session/pstore.rb b/lib/cgi/session/pstore.rb
index 696f6f2d3b..10f3e8f75f 100644
--- a/lib/cgi/session/pstore.rb
+++ b/lib/cgi/session/pstore.rb
@@ -61,10 +61,7 @@ class CGI
md5 = Digest::MD5.hexdigest(id)[0,16]
path = dir+"/"+prefix+md5
path.untaint
- unless File::exist?(path)
- unless session.new_session
- raise CGI::Session::NoSession, "uninitialized session"
- end
+ unless File::exist? path
@hash = {}
end
@p = ::PStore.new(path)
diff --git a/lib/date.rb b/lib/date.rb
index c2070760ad..79a2df1135 100644
--- a/lib/date.rb
+++ b/lib/date.rb
@@ -1,12 +1,12 @@
#
# date.rb - date and time library
#
-# Author: Tadayoshi Funaba 1998-2005
+# Author: Tadayoshi Funaba 1998-2004
#
# Documentation: William Webber <william@williamwebber.com>
#
#--
-# $Id: date.rb,v 2.15 2005-02-06 11:09:53+09 tadf Exp $
+# $Id: date.rb,v 2.12 2004-03-20 08:05:13+09 tadf Exp $
#++
#
# == Overview
@@ -647,7 +647,7 @@ class Date
elem ||= {}
y, m, d = elem.values_at(:year, :mon, :mday)
if [y, m, d].include? nil
- raise ArgumentError, '3 elements of civil date are necessary'
+ raise ArgumentError, 'invalid date'
else
civil(y, m, d, sg)
end
@@ -1211,7 +1211,7 @@ class DateTime < Date
fr ||= 0
of ||= 0
if [y, m, d].include? nil
- raise ArgumentError, '3 elements of civil date are necessary'
+ raise ArgumentError, 'invalid date'
else
civil(y, m, d, h, min, s, of.to_r/86400, sg) + (fr/86400)
end
@@ -1258,7 +1258,7 @@ class DateTime < Date
new_with_hash(elem, sg)
end
- class << self; undef_method :today end rescue nil
+ class << self; undef_method :today end
# Create a new DateTime object representing the current time.
#
diff --git a/lib/date/format.rb b/lib/date/format.rb
index babcffbfc5..e8e54e7894 100644
--- a/lib/date/format.rb
+++ b/lib/date/format.rb
@@ -1,5 +1,5 @@
-# format.rb: Written by Tadayoshi Funaba 1999-2005
-# $Id: format.rb,v 2.15 2005-02-06 13:28:48+09 tadf Exp $
+# format.rb: Written by Tadayoshi Funaba 1999-2004
+# $Id: format.rb,v 2.13 2004-03-20 08:05:13+09 tadf Exp $
require 'rational'
@@ -116,12 +116,6 @@ class Date
val = $1.to_i
return unless (1..12) === val
elem[:mon] = val
-=begin
- when '%N'
- return unless str.sub!(/\A(\d+)/o, '')
- val = $1.to_i.to_r / (10**9)
- elem[:sec_fraction] = val
-=end
when '%n'
return unless __strptime(str, ' ', elem)
when '%p', '%P'
@@ -197,21 +191,12 @@ class Date
elem[:sec_fraction] = val
=end
when '%1'
- if $VERBOSE
- warn("warning: %1 is deprecated; forget this")
- end
return unless str.sub!(/\A(\d+)/o, '')
val = $1.to_i
elem[:jd] = val
when '%2'
- if $VERBOSE
- warn("warning: %2 is deprecated; use '%Y-%j'")
- end
return unless __strptime(str, '%Y-%j', elem)
when '%3'
- if $VERBOSE
- warn("warning: %3 is deprecated; use '%F'")
- end
return unless __strptime(str, '%F', elem)
else
return unless str.sub!(Regexp.new('\\A' + Regexp.quote(c)), '')
@@ -291,9 +276,7 @@ class Date
end
end
- if $6
- zone = $6
- end
+ zone = $6
end
# eu
@@ -440,9 +423,7 @@ class Date
if $4
sec_fraction = $4.to_i.to_r / (10**$4.size)
end
- if $5
- zone = $5
- end
+ zone = $5
end
if str.sub!(/\b(bc\b|bce\b|b\.c\.|b\.c\.e\.)/ino, ' ')
@@ -513,10 +494,6 @@ class Date
when '%l'; o << '%2d' % ((hour % 12).nonzero? or 12) # AR,TZ,GL
when '%M'; o << '%02d' % min
when '%m'; o << '%02d' % mon
-=begin
- when '%N' # GNU date
- o << '%09d' % (sec_fraction / (1.to_r/86400/(10**9)))
-=end
when '%n'; o << "\n" # P2,ID
when '%P'; o << if hour < 12 then 'am' else 'pm' end # GL
when '%p'; o << if hour < 12 then 'AM' else 'PM' end
@@ -556,21 +533,9 @@ class Date
when '%.'
o << '%06d' % (sec_fraction / (1.to_r/86400/(10**6)))
=end
- when '%1'
- if $VERBOSE
- warn("warning: %1 is deprecated; forget this")
- end
- o << '%d' % jd
- when '%2'
- if $VERBOSE
- warn("warning: %2 is deprecated; use '%Y-%j'")
- end
- o << strftime('%Y-%j')
- when '%3'
- if $VERBOSE
- warn("warning: %3 is deprecated; use '%F'")
- end
- o << strftime('%F')
+ when '%1'; o << '%d' % jd
+ when '%2'; o << strftime('%Y-%j')
+ when '%3'; o << strftime('%Y-%m-%d')
else; o << c
end
end
diff --git a/lib/debug.rb b/lib/debug.rb
index d22982b5a9..1b12188a76 100644
--- a/lib/debug.rb
+++ b/lib/debug.rb
@@ -324,7 +324,7 @@ class Context
when /^\s*wat(?:ch)?\s+(.+)$/
exp = $1
break_points.push [true, 1, exp]
- stdout.printf "Set watchpoint %d:%s\n", break_points.size, exp
+ stdout.printf "Set watchpoint %d\n", break_points.size, exp
when /^\s*b(?:reak)?$/
if break_points.find{|b| b[1] == 0}
diff --git a/lib/delegate.rb b/lib/delegate.rb
index 93c9803a18..20e6b53c2e 100644
--- a/lib/delegate.rb
+++ b/lib/delegate.rb
@@ -1,125 +1,23 @@
-# = delegate -- Support for the Delegation Pattern
+# Delegation class that delegates even methods defined in super class,
+# which can not be covered with normal method_missing hack.
+#
+# Delegator is the abstract delegation class. Need to redefine
+# `__getobj__' method in the subclass. SimpleDelegator is the
+# concrete subclass for simple delegation.
#
-# Documentation by James Edward Gray II and Gavin Sinclair
+# Usage:
+# foo = Object.new
+# foo2 = SimpleDelegator.new(foo)
+# foo.hash == foo2.hash # => false
#
-# == Introduction
+# Foo = DelegateClass(Array)
#
-# This library provides three different ways to delegate method calls to an
-# object. The easiest to use is SimpleDelegator. Pass an object to the
-# constructor and all methods supported by the object will be delegated. This
-# object can be changed later.
-#
-# Going a step further, the top level DelegateClass method allows you to easily
-# setup delegation through class inheritance. This is considerably more
-# flexible and thus probably the most common use for this library.
-#
-# Finally, if you need full control over the delegation scheme, you can inherit
-# from the abstract class Delegator and customize as needed. (If you find
-# yourself needing this control, have a look at _forwardable_, also in the
-# standard library. It may suit your needs better.)
-#
-# == Notes
-#
-# Be advised, RDoc will not detect delegated methods.
-#
-# <b>delegate.rb provides full-class delegation via the
-# DelegateClass() method. For single-method delegation via
-# def_delegator(), see forwardable.rb.</b>
-#
-# == Examples
-#
-# === SimpleDelegator
-#
-# Here's a simple example that takes advantage of the fact that
-# SimpleDelegator's delegation object can be changed at any time.
-#
-# class Stats
-# def initialize
-# @source = SimpleDelegator.new([])
-# end
-#
-# def stats( records )
-# @source.__setobj__(records)
-#
-# "Elements: #{@source.size}\n" +
-# " Non-Nil: #{@source.compact.size}\n" +
-# " Unique: #{@source.uniq.size}\n"
-# end
-# end
-#
-# s = Stats.new
-# puts s.stats(%w{James Edward Gray II})
-# puts
-# puts s.stats([1, 2, 3, nil, 4, 5, 1, 2])
-#
-# <i>Prints:</i>
-#
-# Elements: 4
-# Non-Nil: 4
-# Unique: 4
-#
-# Elements: 8
-# Non-Nil: 7
-# Unique: 6
-#
-# === DelegateClass()
-#
-# Here's a sample of use from <i>tempfile.rb</i>.
-#
-# A _Tempfile_ object is really just a _File_ object with a few special rules
-# about storage location and/or when the File should be deleted. That makes for
-# an almost textbook perfect example of how to use delegation.
-#
-# class Tempfile < DelegateClass(File)
-# # constant and class member data initialization...
-#
-# def initialize(basename, tmpdir=Dir::tmpdir)
-# # build up file path/name in var tmpname...
-#
-# @tmpfile = File.open(tmpname, File::RDWR|File::CREAT|File::EXCL, 0600)
-#
-# # ...
-#
-# super(@tmpfile)
-#
-# # below this point, all methods of File are supported...
-# end
-#
-# # ...
-# end
-#
-# === Delegator
-#
-# SimpleDelegator's implementation serves as a nice example here.
-#
-# class SimpleDelegator < Delegator
-# def initialize(obj)
-# super # pass obj to Delegator constructor, required
-# @_sd_obj = obj # store obj for future use
-# end
-#
-# def __getobj__
-# @_sd_obj # return object we are delegating to, required
-# end
-#
-# def __setobj__(obj)
-# @_sd_obj = obj # change delegation object, a feature we're providing
-# end
-#
-# # ...
-# end
+# class ExtArray<DelegateClass(Array)
+# ...
+# end
-#
-# Delegator is an abstract class used to build delegator pattern objects from
-# subclasses. Subclasses should redefine \_\_getobj\_\_. For a concrete
-# implementation, see SimpleDelegator.
-#
class Delegator
- #
- # Pass in the _obj_ to delegate method calls to. All methods supported by
- # _obj_ will be delegated to.
- #
def initialize(obj)
preserved = ::Kernel.public_instance_methods(false)
preserved -= ["to_s","to_a","inspect","==","=~","==="]
@@ -151,141 +49,76 @@ class Delegator
end
alias initialize_methods initialize
- # Handles the magic of delegation through \_\_getobj\_\_.
- def method_missing(m, *args)
- target = self.__getobj__
- unless target.respond_to?(m)
- super(m, *args)
- end
- target.__send__(m, *args)
- end
-
- #
- # Checks for a method provided by this the delegate object by fowarding the
- # call through \_\_getobj\_\_.
- #
- def respond_to?(m)
- return true if super
- return self.__getobj__.respond_to?(m)
- end
-
- #
- # This method must be overridden by subclasses and should return the object
- # method calls are being delegated to.
- #
def __getobj__
raise NotImplementedError, "need to define `__getobj__'"
end
- # Serialization support for the object returned by \_\_getobj\_\_.
def marshal_dump
__getobj__
end
- # Reinitializes delegation from a serialized object.
def marshal_load(obj)
initialize_methods(obj)
end
end
-#
-# A concrete implementation of Delegator, this class provides the means to
-# delegate all supported method calls to the object passed into the constructor
-# and even to change the object being delegated to at a later time with
-# \_\_setobj\_\_ .
-#
class SimpleDelegator<Delegator
- # Pass in the _obj_ you would like to delegate method calls to.
def initialize(obj)
super
@_sd_obj = obj
end
- # Returns the current object method calls are being delegated to.
def __getobj__
@_sd_obj
end
- #
- # Changes the delegate object to _obj_.
- #
- # It's important to note that this does *not* cause SimpleDelegator's methods
- # to change. Because of this, you probably only want to change delegation
- # to objects of the same type as the original delegate.
- #
- # Here's an example of changing the delegation object.
- #
- # names = SimpleDelegator.new(%w{James Edward Gray II})
- # puts names[1] # => Edward
- # names.__setobj__(%w{Gavin Sinclair})
- # puts names[1] # => Sinclair
- #
def __setobj__(obj)
- raise ArgumentError, "cannot delegate to self" if self.equal?(obj)
@_sd_obj = obj
end
- # Clone support for the object returned by \_\_getobj\_\_.
- def clone
+ def clone(obj)
super
- __setobj__(__getobj__.clone)
+ __setobj__(obj.__getobj__.clone)
end
- # Duplication support for the object returned by \_\_getobj\_\_.
def dup(obj)
super
- __setobj__(__getobj__.dup)
+ __setobj__(obj.__getobj__.dup)
end
end
-# :stopdoc:
# backward compatibility ^_^;;;
Delegater = Delegator
SimpleDelegater = SimpleDelegator
-# :startdoc:
#
-# The primary interface to this library. Use to setup delegation when defining
-# your class.
-#
-# class MyClass < DelegateClass( ClassToDelegateTo ) # Step 1
-# def initiaize
-# super(obj_of_ClassToDelegateTo) # Step 2
-# end
-# end
-#
def DelegateClass(superclass)
klass = Class.new
methods = superclass.public_instance_methods(true)
methods -= ::Kernel.public_instance_methods(false)
methods |= ["to_s","to_a","inspect","==","=~","==="]
klass.module_eval {
- def initialize(obj) # :nodoc:
+ def initialize(obj)
@_dc_obj = obj
end
- def method_missing(m, *args) # :nodoc:
+ def method_missing(m, *args)
unless @_dc_obj.respond_to?(m)
super(m, *args)
end
@_dc_obj.__send__(m, *args)
end
- def respond_to?(m) # :nodoc:
- return true if super
- return @_dc_obj.respond_to?(m)
- end
- def __getobj__ # :nodoc:
+ def __getobj__
@_dc_obj
end
- def __setobj__(obj) # :nodoc:
- raise ArgumentError, "cannot delegate to self" if self.equal?(obj)
+ def __setobj__(obj)
@_dc_obj = obj
end
- def clone # :nodoc:
+ def clone(obj)
super
- __setobj__(__getobj__.clone)
+ __setobj__(obj.__getobj__.clone)
end
- def dup # :nodoc:
+ def dup(obj)
super
- __setobj__(__getobj__.dup)
+ __setobj__(obj.__getobj__.dup)
end
}
for method in methods
@@ -307,8 +140,6 @@ def DelegateClass(superclass)
return klass
end
-# :enddoc:
-
if __FILE__ == $0
class ExtArray<DelegateClass(Array)
def initialize()
diff --git a/lib/drb/drb.rb b/lib/drb/drb.rb
index 2177af871b..c90259f87e 100644
--- a/lib/drb/drb.rb
+++ b/lib/drb/drb.rb
@@ -430,15 +430,6 @@ module DRb
end
end
- class DRbRemoteError < DRbError
- def initialize(error)
- @reason = error.class.to_s
- super("#{error.message} (#{error.class})")
- set_backtrace(error.backtrace)
- end
- attr_reader :reason
- end
-
# Class wrapping a marshalled object whose type is unknown locally.
#
# If an object is returned by a method invoked over drb, but the
@@ -461,7 +452,7 @@ module DRb
# when the unmarshalling failed. It is used to determine the
# name of the unmarshalled object.
def initialize(err, buf)
- case err.to_s
+ case err
when /uninitialized constant (\S+)/
@name = $1
when /undefined class\/module (\S+)/
@@ -548,12 +539,12 @@ module DRb
@argc_limit = config[:argc_limit]
end
- def dump(obj, error=false) # :nodoc:
- obj = make_proxy(obj, error) if obj.kind_of? DRbUndumped
+ def dump(obj) # :nodoc:
+ obj = DRbObject.new(obj) if obj.kind_of? DRbUndumped
begin
str = Marshal::dump(obj)
rescue
- str = Marshal::dump(make_proxy(obj, error))
+ str = Marshal::dump(DRbObject.new(obj))
end
[str.size].pack('N') + str
end
@@ -573,21 +564,12 @@ module DRb
rescue
raise(DRbConnError, $!.message, $!.backtrace)
end
- raise(DRbConnError, 'connection closed') if str.nil?
+ raise(DRbConnError, 'connection closed') if sz.nil?
raise(DRbConnError, 'premature marshal format(can\'t read)') if str.size < sz
- Thread.exclusive do
- begin
- save = Thread.current[:drb_untaint]
- Thread.current[:drb_untaint] = []
- Marshal::load(str)
- rescue NameError, ArgumentError
- DRbUnknown.new($!, str)
- ensure
- Thread.current[:drb_untaint].each do |x|
- x.untaint
- end
- Thread.current[:drb_untaint] = save
- end
+ begin
+ Marshal::load(str)
+ rescue NameError, ArgumentError
+ DRbUnknown.new($!, str)
end
end
@@ -620,7 +602,7 @@ module DRb
end
def send_reply(stream, succ, result) # :nodoc:
- stream.write(dump(succ) + dump(result, !succ))
+ stream.write(dump(succ) + dump(result))
rescue
raise(DRbConnError, $!.message, $!.backtrace)
end
@@ -630,15 +612,6 @@ module DRb
result = load(stream)
[succ, result]
end
-
- private
- def make_proxy(obj, error=false)
- if error
- DRbRemoteError.new(obj)
- else
- DRbObject.new(obj)
- end
- end
end
# Module managing the underlying network protocol(s) used by drb.
@@ -824,40 +797,14 @@ module DRb
self.new(uri, soc, config)
end
- def self.getservername
- host = Socket::gethostname
- begin
- Socket::gethostbyname(host)[0]
- rescue
- host
- end
- end
-
- def self.open_server_inaddr_any(host, port)
- infos = Socket::getaddrinfo(host, nil,
- Socket::AF_UNSPEC,
- Socket::SOCK_STREAM,
- 0,
- Socket::AI_PASSIVE)
- family = infos.collect { |af, *_| af }.uniq
- case family
- when ['AF_INET']
- return TCPServer.open('0.0.0.0', port)
- when ['AF_INET6']
- return TCPServer.open('::', port)
- else
- return TCPServer.open(port)
- end
- end
-
# Open a server listening for connections at +uri+ using
# configuration +config+.
def self.open_server(uri, config)
uri = 'druby://:0' unless uri
host, port, opt = parse_uri(uri)
if host.size == 0
- host = getservername
- soc = open_server_inaddr_any(host, port)
+ soc = TCPServer.open(port)
+ host = Socket.gethostname
else
soc = TCPServer.open(host, port)
end
@@ -997,22 +944,12 @@ module DRb
# created to act as a stub for the remote referenced object.
def self._load(s)
uri, ref = Marshal.load(s)
-
if DRb.here?(uri)
- obj = DRb.to_obj(ref)
- if ((! obj.tainted?) && Thread.current[:drb_untaint])
- Thread.current[:drb_untaint].push(obj)
- end
- return obj
+ return DRb.to_obj(ref)
end
- self.new_with(uri, ref)
- end
-
- def self.new_with(uri, ref)
- it = self.allocate
- it.instance_variable_set('@uri', uri)
- it.instance_variable_set('@ref', ref)
+ it = self.new(nil)
+ it.reinit(uri, ref)
it
end
@@ -1046,6 +983,12 @@ module DRb
end
end
+ # Reinitialise this object with the given +uri+ and +ref+
+ def reinit(uri, ref)
+ @uri = uri
+ @ref = ref
+ end
+
# Get the URI of the remote object.
def __drburi
@uri
@@ -1058,17 +1001,7 @@ module DRb
undef :to_s
undef :to_a if respond_to?(:to_a)
-
- def respond_to?(msg_id, priv=false)
- case msg_id
- when :_dump
- true
- when :marshal_dump
- false
- else
- method_missing(:respond_to?, msg_id, priv)
- end
- end
+ undef :respond_to?
# Routes method calls to the referenced object.
def method_missing(msg_id, *a, &b)
@@ -1078,46 +1011,25 @@ module DRb
return obj.__send__(msg_id, *a, &b)
end
- succ, result = self.class.with_friend(@uri) do
- DRbConn.open(@uri) do |conn|
- conn.send_message(self, msg_id, a, b)
- end
+ succ, result = DRbConn.open(@uri) do |conn|
+ conn.send_message(self, msg_id, a, b)
end
-
- if succ
- return result
- elsif DRbUnknown === result
- raise result
+ return result if succ
+ unless DRbUnknown === result
+ prefix = "(#{@uri}) "
+ bt = []
+ result.backtrace.each do |x|
+ break if /`__send__'$/ =~ x
+ if /^\(druby:\/\// =~ x
+ bt.push(x)
+ else
+ bt.push(prefix + x)
+ end
+ end
+ raise result, result.message, bt + caller
else
- bt = self.class.prepare_backtrace(@uri, result)
- result.set_backtrace(bt + caller)
- raise result
- end
- end
-
- def self.with_friend(uri)
- friend = DRb.fetch_server(uri)
- return yield() unless friend
-
- save = Thread.current['DRb']
- Thread.current['DRb'] = { 'server' => friend }
- return yield
- ensure
- Thread.current['DRb'] = save if friend
- end
-
- def self.prepare_backtrace(uri, result)
- prefix = "(#{uri}) "
- bt = []
- result.backtrace.each do |x|
- break if /`__send__'$/ =~ x
- if /^\(druby:\/\// =~ x
- bt.push(x)
- else
- bt.push(prefix + x)
- end
+ raise result
end
- bt
end
def pretty_print(q) # :nodoc:
@@ -1220,7 +1132,6 @@ module DRb
@@argc_limit = 256
@@load_limit = 256 * 102400
@@verbose = false
- @@safe_level = 0
# Set the default value for the :argc_limit option.
#
@@ -1250,10 +1161,6 @@ module DRb
@@idconv = idconv
end
- def self.default_safe_level(level)
- @@safe_level = level
- end
-
# Set the default value of the :verbose option.
#
# See #new(). The initial default value is false.
@@ -1272,8 +1179,7 @@ module DRb
:verbose => @@verbose,
:tcp_acl => @@acl,
:load_limit => @@load_limit,
- :argc_limit => @@argc_limit,
- :safe_level => @@safe_level
+ :argc_limit => @@argc_limit
}
default_config.update(hash)
end
@@ -1338,12 +1244,13 @@ module DRb
@front = front
@idconv = @config[:idconv]
- @safe_level = @config[:safe_level]
@grp = ThreadGroup.new
@thread = run
- DRb.regist_server(self)
+ Thread.exclusive do
+ DRb.primary_server = self unless DRb.primary_server
+ end
end
# The URI of this DRbServer.
@@ -1365,8 +1272,6 @@ module DRb
# The configuration of this DRbServer
attr_reader :config
- attr_reader :safe_level
-
# Set whether to operate in verbose mode.
#
# In verbose mode, failed calls are logged to stdout.
@@ -1384,12 +1289,7 @@ module DRb
# Stop this server.
def stop_service
- DRb.remove_server(self)
- if Thread.current['DRb'] && Thread.current['DRb']['server'] == self
- Thread.current['DRb']['stop_service'] = true
- else
- @thread.kill
- end
+ @thread.kill
end
# Convert a dRuby reference to the local object it refers to.
@@ -1448,9 +1348,7 @@ module DRb
# Coerce an object to a string, providing our own representation if
# to_s is not defined for the object.
def any_to_s(obj)
- obj.to_s + ":#{obj.class}"
- rescue
- sprintf("#<%s:0x%lx>", obj.class, obj.__id__)
+ obj.to_s rescue sprintf("#<%s:0x%lx>", obj.class, obj.__id__)
end
# Check that a method is callable via dRuby.
@@ -1465,23 +1363,25 @@ module DRb
return true if Proc === obj && msg_id == :__drb_yield
raise(ArgumentError, "#{any_to_s(msg_id)} is not a symbol") unless Symbol == msg_id.class
raise(SecurityError, "insecure method `#{msg_id}'") if insecure_method?(msg_id)
-
- if obj.private_methods.include?(msg_id.to_s)
+ unless obj.respond_to?(msg_id)
desc = any_to_s(obj)
- raise NoMethodError, "private method `#{msg_id}' called for #{desc}"
- elsif obj.protected_methods.include?(msg_id.to_s)
- desc = any_to_s(obj)
- raise NoMethodError, "protected method `#{msg_id}' called for #{desc}"
- else
- true
+ if desc.nil? || desc[0] == '#'
+ desc << ":#{obj.class}"
+ end
+
+ if obj.private_methods.include?(msg_id.to_s)
+ raise NameError, "private method `#{msg_id}' called for #{desc}"
+ else
+ raise NameError, "undefined method `#{msg_id}' called for #{desc}"
+ end
end
+ true
end
public :check_insecure_method
-
+
class InvokeMethod # :nodoc:
def initialize(drb_server, client)
@drb_server = drb_server
- @safe_level = drb_server.safe_level
@client = client
end
@@ -1489,28 +1389,10 @@ module DRb
@result = nil
@succ = false
setup_message
-
- if $SAFE < @safe_level
- info = Thread.current['DRb']
- if @block
- @result = Thread.new {
- Thread.current['DRb'] = info
- $SAFE = @safe_level
- perform_with_block
- }.value
- else
- @result = Thread.new {
- Thread.current['DRb'] = info
- $SAFE = @safe_level
- perform_without_block
- }.value
- end
+ if @block
+ @result = perform_with_block
else
- if @block
- @result = perform_with_block
- else
- @result = perform_without_block
- end
+ @result = perform_without_block
end
@succ = true
if @msg_id == :to_ary && @result.class == Array
@@ -1592,11 +1474,10 @@ module DRb
end
client.send_reply(succ, result) rescue nil
ensure
- client.close unless succ
- if Thread.current['DRb']['stop_service']
- Thread.new { stop_service }
- end
- break unless succ
+ unless succ
+ client.close
+ break
+ end
end
end
end
@@ -1734,25 +1615,6 @@ module DRb
DRbServer.default_acl(acl)
end
module_function :install_acl
-
- @server = {}
- def regist_server(server)
- @server[server.uri] = server
- Thread.exclusive do
- @primary_server = server unless @primary_server
- end
- end
- module_function :regist_server
-
- def remove_server(server)
- @server.delete(server.uri)
- end
- module_function :remove_server
-
- def fetch_server(uri)
- @server[uri]
- end
- module_function :fetch_server
end
DRbObject = DRb::DRbObject
diff --git a/lib/drb/extserv.rb b/lib/drb/extserv.rb
index 7da8130c2b..4ed2913051 100644
--- a/lib/drb/extserv.rb
+++ b/lib/drb/extserv.rb
@@ -25,7 +25,10 @@ module DRb
@invoker.unregist(@name)
server = @server
@server = nil
- server.stop_service
+ Thread.new do
+ sleep 1
+ server.stop_service
+ end
true
end
diff --git a/lib/drb/extservm.rb b/lib/drb/extservm.rb
index b649c9c006..50009dbae2 100644
--- a/lib/drb/extservm.rb
+++ b/lib/drb/extservm.rb
@@ -25,9 +25,8 @@ module DRb
@waiting = []
@queue = Queue.new
@thread = invoke_thread
- @uri = nil
end
- attr_accessor :uri
+ attr_reader :server
def service(name)
while true
@@ -85,11 +84,10 @@ module DRb
return if @servers.include?(name)
@servers[name] = false
end
- uri = @uri || DRb.uri
if RUBY_PLATFORM =~ /mswin32/
- system("cmd /c start /b #{command} #{uri} #{name}")
+ system("cmd /c start /b #{command} #{DRb.uri} #{name}")
else
- system("#{command} #{uri} #{name} &")
+ system("#{command} #{DRb.uri} #{name} &")
end
end
end
diff --git a/lib/drb/gw.rb b/lib/drb/gw.rb
index b7a5f5383f..012a2b0a11 100644
--- a/lib/drb/gw.rb
+++ b/lib/drb/gw.rb
@@ -5,7 +5,9 @@ module DRb
class GWIdConv < DRbIdConv
def to_obj(ref)
if Array === ref && ref[0] == :DRbObject
- return DRbObject.new_with(ref[1], ref[2])
+ it = DRbObject.new(nil)
+ it.reinit(ref[1], ref[2])
+ return it
end
super(ref)
end
@@ -38,7 +40,9 @@ module DRb
return ref ? DRb.to_obj(ref) : DRb.front
end
- self.new_with(DRb.uri, [:DRbObject, uri, ref])
+ it = self.new(nil)
+ it.reinit(DRb.uri, [:DRbObject, uri, ref])
+ it
end
def _dump(lv)
@@ -54,69 +58,3 @@ module DRb
end
end
end
-
-=begin
-DRb.install_id_conv(DRb::GWIdConv.new)
-
-front = DRb::GW.new
-
-s1 = DRb::DRbServer.new('drbunix:/tmp/gw_b_a', front)
-s2 = DRb::DRbServer.new('drbunix:/tmp/gw_b_c', front)
-
-s1.thread.join
-s2.thread.join
-=end
-
-=begin
-# foo.rb
-
-require 'drb/drb'
-
-class Foo
- include DRbUndumped
- def initialize(name, peer=nil)
- @name = name
- @peer = peer
- end
-
- def ping(obj)
- puts "#{@name}: ping: #{obj.inspect}"
- @peer.ping(self) if @peer
- end
-end
-=end
-
-=begin
-# gw_a.rb
-require 'drb/unix'
-require 'foo'
-
-obj = Foo.new('a')
-DRb.start_service("drbunix:/tmp/gw_a", obj)
-
-robj = DRbObject.new_with_uri('drbunix:/tmp/gw_b_a')
-robj[:a] = obj
-
-DRb.thread.join
-=end
-
-=begin
-# gw_c.rb
-require 'drb/unix'
-require 'foo'
-
-foo = Foo.new('c', nil)
-
-DRb.start_service("drbunix:/tmp/gw_c", nil)
-
-robj = DRbObject.new_with_uri("drbunix:/tmp/gw_b_c")
-
-puts "c->b"
-a = robj[:a]
-sleep 2
-
-a.ping(foo)
-
-DRb.thread.join
-=end
-
diff --git a/lib/drb/ssl.rb b/lib/drb/ssl.rb
index a35be03dd8..1a454a59cc 100644
--- a/lib/drb/ssl.rb
+++ b/lib/drb/ssl.rb
@@ -136,8 +136,8 @@ module DRb
uri = 'drbssl://:0' unless uri
host, port, opt = parse_uri(uri)
if host.size == 0
- host = getservername
- soc = open_server_inaddr_any(host, port)
+ soc = TCPServer.open(port)
+ host = Socket.gethostname
else
soc = TCPServer.open(host, port)
end
@@ -171,7 +171,6 @@ module DRb
end
def accept
- begin
while true
soc = @socket.accept
break if (@acl ? @acl.allow_socket?(soc) : true)
@@ -179,10 +178,6 @@ module DRb
end
ssl = @config.accept(soc)
self.class.new(uri, ssl, @config, true)
- rescue OpenSSL::SSL::SSLError
- warn("#{__FILE__}:#{__LINE__}: warning: #{$!.message} (#{$!.class})") if verbose
- retry
- end
end
end
diff --git a/lib/drb/unix.rb b/lib/drb/unix.rb
index 989ec57eed..cdc771da1f 100644
--- a/lib/drb/unix.rb
+++ b/lib/drb/unix.rb
@@ -29,7 +29,6 @@ module DRb
filename, option = parse_uri(uri)
if filename.size == 0
soc = temp_server
- filename = soc.path
uri = 'drbunix:' + soc.path
else
soc = UNIXServer.open(filename)
diff --git a/lib/erb.rb b/lib/erb.rb
index 6b1cdaed20..44529bf325 100644
--- a/lib/erb.rb
+++ b/lib/erb.rb
@@ -1,254 +1,19 @@
-# = ERB -- Ruby Templating
-#
-# Author:: Masatoshi SEKI
-# Documentation:: James Edward Gray II and Gavin Sinclair
-#
-# See ERB for primary documentation and ERB::Util for a couple of utility
-# routines.
-#
-# Copyright (c) 1999-2000,2002,2003 Masatoshi SEKI
-#
+# Tiny eRuby --- ERB2
+# Copyright (c) 1999-2000,2002,2003 Masatoshi SEKI
# You can redistribute it and/or modify it under the same terms as Ruby.
-#
-# = ERB -- Ruby Templating
-#
-# == Introduction
-#
-# ERB provides an easy to use but powerful templating system for Ruby. Using
-# ERB, actual Ruby code can be added to any plain text document for the
-# purposes of generating document information details and/or flow control.
-#
-# A very simple example is this:
-#
-# require 'erb'
-#
-# x = 42
-# template = ERB.new <<-EOF
-# The value of x is: <%= x %>
-# EOF
-# puts template.result(binding)
-#
-# <em>Prints:</em> The value of x is: 42
-#
-# More complex examples are given below.
-#
-#
-# == Recognized Tags
-#
-# ERB recognizes certain tags in the provided template and converts them based
-# on the rules below:
-#
-# <% Ruby code -- inline with output %>
-# <%= Ruby expression -- replace with result %>
-# <%# comment -- ignored -- useful in testing %>
-# % a line of Ruby code -- treated as <% line %> (optional -- see ERB.new)
-# %% replaced with % if first thing on a line and % processing is used
-# <%% or %%> -- replace with <% or %> respectively
-#
-# All other text is passed through ERB filtering unchanged.
-#
-#
-# == Options
-#
-# There are several settings you can change when you use ERB:
-# * the nature of the tags that are recognized;
-# * the value of <tt>$SAFE</tt> under which the template is run;
-# * the binding used to resolve local variables in the template.
-#
-# See the ERB.new and ERB#result methods for more detail.
-#
-#
-# == Examples
-#
-# === Plain Text
-#
-# ERB is useful for any generic templating situation. Note that in this example, we use the
-# convenient "% at start of line" tag, and we quote the template literally with
-# <tt>%q{...}</tt> to avoid trouble with the backslash.
-#
-# require "erb"
-#
-# # Create template.
-# template = %q{
-# From: James Edward Gray II <james@grayproductions.net>
-# To: <%= to %>
-# Subject: Addressing Needs
-#
-# <%= to[/\w+/] %>:
-#
-# Just wanted to send a quick note assuring that your needs are being
-# addressed.
-#
-# I want you to know that my team will keep working on the issues,
-# especially:
-#
-# <%# ignore numerous minor requests -- focus on priorities %>
-# % priorities.each do |priority|
-# * <%= priority %>
-# % end
-#
-# Thanks for your patience.
-#
-# James Edward Gray II
-# }.gsub(/^ /, '')
-#
-# message = ERB.new(template, 0, "%<>")
-#
-# # Set up template data.
-# to = "Community Spokesman <spokesman@ruby_community.org>"
-# priorities = [ "Run Ruby Quiz",
-# "Document Modules",
-# "Answer Questions on Ruby Talk" ]
-#
-# # Produce result.
-# email = message.result
-# puts email
-#
-# <i>Generates:</i>
-#
-# From: James Edward Gray II <james@grayproductions.net>
-# To: Community Spokesman <spokesman@ruby_community.org>
-# Subject: Addressing Needs
-#
-# Community:
-#
-# Just wanted to send a quick note assuring that your needs are being addressed.
-#
-# I want you to know that my team will keep working on the issues, especially:
-#
-# * Run Ruby Quiz
-# * Document Modules
-# * Answer Questions on Ruby Talk
-#
-# Thanks for your patience.
-#
-# James Edward Gray II
-#
-# === Ruby in HTML
-#
-# ERB is often used in <tt>.rhtml</tt> files (HTML with embedded Ruby). Notice the need in
-# this example to provide a special binding when the template is run, so that the instance
-# variables in the Product object can be resolved.
-#
-# require "erb"
-#
-# # Build template data class.
-# class Product
-# def initialize( code, name, desc, cost )
-# @code = code
-# @name = name
-# @desc = desc
-# @cost = cost
-#
-# @features = [ ]
-# end
-#
-# def add_feature( feature )
-# @features << feature
-# end
-#
-# # Support templating of member data.
-# def get_binding
-# binding
-# end
-#
-# # ...
-# end
-#
-# # Create template.
-# template = %{
-# <html>
-# <head><title>Ruby Toys -- <%= @name %></title></head>
-# <body>
-#
-# <h1><%= @name %> (<%= @code %>)</h1>
-# <p><%= @desc %></p>
-#
-# <ul>
-# <% @features.each do |f| %>
-# <li><b><%= f %></b></li>
-# <% end %>
-# </ul>
-#
-# <p>
-# <% if @cost < 10 %>
-# <b>Only <%= @cost %>!!!</b>
-# <% else %>
-# Call for a price, today!
-# <% end %>
-# </p>
-#
-# </body>
-# </html>
-# }.gsub(/^ /, '')
-#
-# rhtml = ERB.new(template)
-#
-# # Set up template data.
-# toy = Product.new( "TZ-1002",
-# "Rubysapien",
-# "Geek's Best Friend! Responds to Ruby commands...",
-# 999.95 )
-# toy.add_feature("Listens for verbal commands in the Ruby language!")
-# toy.add_feature("Ignores Perl, Java, and all C variants.")
-# toy.add_feature("Karate-Chop Action!!!")
-# toy.add_feature("Matz signature on left leg.")
-# toy.add_feature("Gem studded eyes... Rubies, of course!")
-#
-# # Produce result.
-# rhtml.run(toy.get_binding)
-#
-# <i>Generates (some blank lines removed):</i>
-#
-# <html>
-# <head><title>Ruby Toys -- Rubysapien</title></head>
-# <body>
-#
-# <h1>Rubysapien (TZ-1002)</h1>
-# <p>Geek's Best Friend! Responds to Ruby commands...</p>
-#
-# <ul>
-# <li><b>Listens for verbal commands in the Ruby language!</b></li>
-# <li><b>Ignores Perl, Java, and all C variants.</b></li>
-# <li><b>Karate-Chop Action!!!</b></li>
-# <li><b>Matz signature on left leg.</b></li>
-# <li><b>Gem studded eyes... Rubies, of course!</b></li>
-# </ul>
-#
-# <p>
-# Call for a price, today!
-# </p>
-#
-# </body>
-# </html>
-#
-#
-# == Notes
-#
-# There are a variety of templating solutions available in various Ruby projects:
-# * ERB's big brother, eRuby, works the same but is written in C for speed;
-# * Amrita (smart at producing HTML/XML);
-# * cs/Template (written in C for speed);
-# * RDoc, distributed with Ruby, uses its own template engine, which can be reused elsewhere;
-# * and others; search the RAA.
-#
-# Rails, the web application framework, uses ERB to create views.
-#
class ERB
Revision = '$Date$' #'
- # Returns revision information for the erb.rb module.
def self.version
"erb.rb [2.0.4 #{ERB::Revision.split[1]}]"
end
end
-#--
# ERB::Compiler
class ERB
- class Compiler # :nodoc:
- class PercentLine # :nodoc:
+ class Compiler
+ class PercentLine
def initialize(str)
@value = str
end
@@ -256,7 +21,7 @@ class ERB
alias :to_s :value
end
- class Scanner # :nodoc:
+ class Scanner
SplitRegexp = /(<%%)|(%%>)|(<%=)|(<%#)|(<%)|(%>)|(\n)/
@scanner_map = {}
@@ -282,7 +47,7 @@ class ERB
def scan; end
end
- class TrimScanner < Scanner # :nodoc:
+ class TrimScanner < Scanner
TrimSplitRegexp = /(<%%)|(%%>)|(<%=)|(<%#)|(<%)|(%>\n)|(%>)|(\n)/
def initialize(src, trim_mode, percent)
@@ -390,7 +155,7 @@ class ERB
Scanner.default_scanner = TrimScanner
- class SimpleScanner < Scanner # :nodoc:
+ class SimpleScanner < Scanner
def scan
@src.each do |line|
line.split(SplitRegexp).each do |token|
@@ -405,7 +170,7 @@ class ERB
begin
require 'strscan'
- class SimpleScanner2 < Scanner # :nodoc:
+ class SimpleScanner2 < Scanner
def scan
stag_reg = /(.*?)(<%%|<%=|<%#|<%|\n|\z)/
etag_reg = /(.*?)(%%>|%>|\n|\z)/
@@ -421,7 +186,7 @@ class ERB
end
Scanner.regist_scanner(SimpleScanner2, nil, false)
- class PercentScanner < Scanner # :nodoc:
+ class PercentScanner < Scanner
def scan
new_line = true
stag_reg = /(.*?)(<%%|<%=|<%#|<%|\n|\z)/
@@ -449,7 +214,7 @@ class ERB
end
Scanner.regist_scanner(PercentScanner, nil, true)
- class ExplicitScanner < Scanner # :nodoc:
+ class ExplicitScanner < Scanner
def scan
new_line = true
stag_reg = /(.*?)(<%%|<%=|<%#|<%-|<%|\n|\z)/
@@ -485,7 +250,7 @@ class ERB
rescue LoadError
end
- class Buffer # :nodoc:
+ class Buffer
def initialize(compiler)
@compiler = compiler
@line = []
@@ -615,74 +380,8 @@ class ERB
end
end
-#--
# ERB
class ERB
- #
- # Constructs a new ERB object with the template specified in _str_.
- #
- # An ERB object works by building a chunk of Ruby code that will output
- # the completed template when run. If _safe_level_ is set to a non-nil value,
- # ERB code will be run in a separate thread with <b>$SAFE</b> set to the
- # provided level.
- #
- # If _trim_mode_ is passed a String containing one or more of the following
- # modifiers, ERB will adjust its code generation as listed:
- #
- # % enables Ruby code processing for lines beginning with %
- # <> omit newline for lines starting with <% and ending in %>
- # > omit newline for lines ending in %>
- #
- # _eoutvar_ can be used to set the name of the variable ERB will build up
- # its output in. This is useful when you need to run multiple ERB
- # templates through the same binding and/or when you want to control where
- # output ends up. Pass the name of the variable to be used inside a String.
- #
- # === Example
- #
- # require "erb"
- #
- # # build data class
- # class Listings
- # PRODUCT = { :name => "Chicken Fried Steak",
- # :desc => "A well messages pattie, breaded and fried.",
- # :cost => 9.95 }
- #
- # attr_reader :product, :price
- #
- # def initialize( product = "", price = "" )
- # @product = product
- # @price = price
- # end
- #
- # def build
- # b = binding
- # # create and run templates, filling member data variebles
- # ERB.new(<<-'END_PRODUCT'.gsub(/^\s+/, ""), 0, "", "@product").result b
- # <%= PRODUCT[:name] %>
- # <%= PRODUCT[:desc] %>
- # END_PRODUCT
- # ERB.new(<<-'END_PRICE'.gsub(/^\s+/, ""), 0, "", "@price").result b
- # <%= PRODUCT[:name] %> -- <%= PRODUCT[:cost] %>
- # <%= PRODUCT[:desc] %>
- # END_PRICE
- # end
- # end
- #
- # # setup template data
- # listings = Listings.new
- # listings.build
- #
- # puts listings.product + "\n" + listings.price
- #
- # _Generates_
- #
- # Chicken Fried Steak
- # A well messages pattie, breaded and fried.
- #
- # Chicken Fried Steak -- 9.95
- # A well messages pattie, breaded and fried.
- #
def initialize(str, safe_level=nil, trim_mode=nil, eoutvar='_erbout')
@safe_level = safe_level
compiler = ERB::Compiler.new(trim_mode)
@@ -690,19 +389,9 @@ class ERB
@src = compiler.compile(str)
@filename = nil
end
-
- # The Ruby code generated by ERB
attr_reader :src
-
- # The optional _filename_ argument passed to Kernel#eval when the ERB code
- # is run
attr_accessor :filename
- #
- # Can be used to set _eoutvar_ as described in ERB#new. It's probably easier
- # to just use the constructor though, since calling this method requires the
- # setup of an ERB _compiler_ object.
- #
def set_eoutvar(compiler, eoutvar = '_erbout')
compiler.put_cmd = "#{eoutvar}.concat"
@@ -717,19 +406,10 @@ class ERB
compiler.post_cmd = cmd
end
- # Generate results and print them. (see ERB#result)
def run(b=TOPLEVEL_BINDING)
print self.result(b)
end
- #
- # Executes the generated ERB code to produce a completed template, returning
- # the results of that code. (See ERB#new for details on how this process can
- # be affected by _safe_level_.)
- #
- # _b_ accepts a Binding or Proc object which is used to set the context of
- # code evaluation.
- #
def result(b=TOPLEVEL_BINDING)
if @safe_level
th = Thread.start {
@@ -742,73 +422,42 @@ class ERB
end
end
- def def_method(mod, methodname, fname='(ERB)') # :nodoc:
+ def def_method(mod, methodname, fname='(ERB)')
mod.module_eval("def #{methodname}\n" + self.src + "\nend\n", fname, 0)
end
- def def_module(methodname='erb') # :nodoc:
+ def def_module(methodname='erb')
mod = Module.new
def_method(mod, methodname)
mod
end
- def def_class(superklass=Object, methodname='result') # :nodoc:
+ def def_class(superklass=Object, methodname='result')
cls = Class.new(superklass)
def_method(cls, methodname)
cls
end
end
-#--
# ERB::Util
class ERB
- # A utility module for conversion routines, often handy in HTML generation.
module Util
public
- #
- # A utility method for escaping HTML tag characters in _s_.
- #
- # require "erb"
- # include ERB::Util
- #
- # puts html_escape("is a > 0 & a < 10?")
- #
- # _Generates_
- #
- # is a &gt; 0 &amp; a &lt; 10?
- #
def html_escape(s)
s.to_s.gsub(/&/, "&amp;").gsub(/\"/, "&quot;").gsub(/>/, "&gt;").gsub(/</, "&lt;")
end
alias h html_escape
- module_function :h
- module_function :html_escape
- #
- # A utility method for encoding the String _s_ as a URL.
- #
- # require "erb"
- # include ERB::Util
- #
- # puts url_encode("Programming Ruby: The Pragmatic Programmer's Guide")
- #
- # _Generates_
- #
- # Programming%20Ruby%3A%20%20The%20Pragmatic%20Programmer%27s%20Guide
- #
def url_encode(s)
s.to_s.gsub(/[^a-zA-Z0-9_\-.]/n){ sprintf("%%%02X", $&.unpack("C")[0]) }
end
alias u url_encode
- module_function :u
- module_function :url_encode
end
end
-#--
# ERB::DefMethod
class ERB
- module DefMethod # :nodoc:
+ module DefMethod
public
def def_erb_method(methodname, erb)
if erb.kind_of? String
@@ -822,5 +471,3 @@ class ERB
module_function :def_erb_method
end
end
-
-
diff --git a/lib/fileutils.rb b/lib/fileutils.rb
index af36bbc738..d92e4c3c94 100644
--- a/lib/fileutils.rb
+++ b/lib/fileutils.rb
@@ -1,7 +1,7 @@
#
# = fileutils.rb
#
-# Copyright (c) 2000-2005 Minero Aoki <aamine@loveruby.net>
+# Copyright (c) 2000-2004 Minero Aoki <aamine@loveruby.net>
#
# This program is free software.
# You can distribute/modify this program under the same terms of ruby.
@@ -16,11 +16,8 @@
# cd(dir, options) {|dir| .... }
# pwd()
# mkdir(dir, options)
-# mkdir(list, options)
# mkdir_p(dir, options)
-# mkdir_p(list, options)
# rmdir(dir, options)
-# rmdir(list, options)
# ln(old, new, options)
# ln(list, destdir, options)
# ln_s(old, new, options)
@@ -37,9 +34,6 @@
# rm_rf(list, options)
# install(src, dest, mode = <src's>, options)
# chmod(mode, list, options)
-# chmod_R(mode, list, options)
-# chown(user, group, list, options)
-# chown_R(user, group, list, options)
# touch(list, options)
#
# The <tt>options</tt> parameter is a hash of options, taken from the list
@@ -51,17 +45,14 @@
# either one file or a list of files in that argument. See the method
# documentation for examples.
#
-# There are some `low level' methods, which do not accept any option:
+# There are some `low level' methods, which does not accept any option:
#
+# uptodate?(file, cmp_list)
# copy_entry(src, dest, preserve = false, dereference = false)
# copy_file(src, dest, preserve = false, dereference = true)
# copy_stream(srcstream, deststream)
-# remove_entry(path, force = false)
-# remove_entry_secure(path, force = false)
-# remove_file(path, force = false)
# compare_file(path_a, path_b)
# compare_stream(stream_a, stream_b)
-# uptodate?(file, cmp_list)
#
# == module FileUtils::Verbose
#
@@ -82,15 +73,10 @@
# <tt>:verbose</tt> flags to methods in FileUtils.
#
-module FileUtils
- def self.private_module_function(name) #:nodoc:
- module_function name
- private_class_method name
- end
+module FileUtils
- # This hash table holds command options.
- OPT_TABLE = {} #:nodoc: internal use only
+ # All methods are module_function.
#
# Options: (none)
@@ -100,13 +86,11 @@ module FileUtils
def pwd
Dir.pwd
end
- module_function :pwd
alias getwd pwd
- module_function :getwd
#
- # Options: verbose
+ # Options: noop verbose
#
# Changes the current directory to the directory +dir+.
#
@@ -116,18 +100,14 @@ module FileUtils
# FileUtils.cd('/', :verbose => true) # chdir and report it
#
def cd(dir, options = {}, &block) # :yield: dir
- fu_check_options options, :verbose
+ fu_check_options options, :noop, :verbose
fu_output_message "cd #{dir}" if options[:verbose]
- Dir.chdir(dir, &block)
+ Dir.chdir(dir, &block) unless options[:noop]
fu_output_message 'cd -' if options[:verbose] and block
end
- module_function :cd
alias chdir cd
- module_function :chdir
- OPT_TABLE['cd'] =
- OPT_TABLE['chdir'] = %w( verbose )
#
# Options: (none)
@@ -150,7 +130,7 @@ module FileUtils
end
true
end
- module_function :uptodate?
+
#
# Options: mode noop verbose
@@ -168,13 +148,11 @@ module FileUtils
fu_output_message "mkdir #{options[:mode] ? ('-m %03o ' % options[:mode]) : ''}#{list.join ' '}" if options[:verbose]
return if options[:noop]
+ mode = options[:mode] || (0777 & ~File.umask)
list.each do |dir|
- fu_mkdir dir, options[:mode]
+ Dir.mkdir dir.sub(%r</\z>, ''), mode
end
end
- module_function :mkdir
-
- OPT_TABLE['mkdir'] = %w( noop verbose mode )
#
# Options: mode noop verbose
@@ -198,10 +176,11 @@ module FileUtils
fu_output_message "mkdir -p #{options[:mode] ? ('-m %03o ' % options[:mode]) : ''}#{list.join ' '}" if options[:verbose]
return *list if options[:noop]
+ mode = options[:mode] || (0777 & ~File.umask)
list.map {|path| path.sub(%r</\z>, '') }.each do |path|
# optimize for the most common case
begin
- fu_mkdir path, options[:mode]
+ Dir.mkdir path, mode
next
rescue SystemCallError
next if File.directory?(path)
@@ -214,7 +193,7 @@ module FileUtils
end
stack.reverse_each do |path|
begin
- fu_mkdir path, options[:mode]
+ Dir.mkdir path, mode
rescue SystemCallError => err
raise unless File.directory?(path)
end
@@ -223,27 +202,10 @@ module FileUtils
return *list
end
- module_function :mkdir_p
alias mkpath mkdir_p
alias makedirs mkdir_p
- module_function :mkpath
- module_function :makedirs
-
- OPT_TABLE['mkdir_p'] =
- OPT_TABLE['mkpath'] =
- OPT_TABLE['makedirs'] = %w( noop verbose )
-
- def fu_mkdir(path, mode) #:nodoc:
- path = path.sub(%r</\z>, '')
- if mode
- Dir.mkdir path, mode
- File.chmod mode, path
- else
- Dir.mkdir path
- end
- end
- private_module_function :fu_mkdir
+
#
# Options: noop, verbose
@@ -260,18 +222,17 @@ module FileUtils
list = fu_list(list)
fu_output_message "rmdir #{list.join ' '}" if options[:verbose]
return if options[:noop]
+
list.each do |dir|
Dir.rmdir dir.sub(%r</\z>, '')
end
end
- module_function :rmdir
- OPT_TABLE['rmdir'] = %w( noop verbose )
#
# Options: force noop verbose
#
- # <b><tt>ln(old, new, options = {})</tt></b>
+ # <b><tt>ln( old, new, options = {} )</tt></b>
#
# Creates a hard link +new+ which points to +old+.
# If +new+ already exists and it is a directory, creates a symbolic link +new/old+.
@@ -281,36 +242,32 @@ module FileUtils
# FileUtils.ln 'gcc', 'cc', :verbose => true
# FileUtils.ln '/usr/bin/emacs21', '/usr/bin/emacs'
#
- # <b><tt>ln(list, destdir, options = {})</tt></b>
+ # <b><tt>ln( list, destdir, options = {} )</tt></b>
#
# Creates several hard links in a directory, with each one pointing to the
# item in +list+. If +destdir+ is not a directory, raises Errno::ENOTDIR.
#
# include FileUtils
- # cd '/sbin'
- # FileUtils.ln %w(cp mv mkdir), '/bin' # Now /sbin/cp and /bin/cp are linked.
+ # cd '/bin'
+ # ln %w(cp mv mkdir), '/usr/bin' # Now /usr/bin/cp and /bin/cp are linked.
#
def ln(src, dest, options = {})
fu_check_options options, :force, :noop, :verbose
fu_output_message "ln#{options[:force] ? ' -f' : ''} #{[src,dest].flatten.join ' '}" if options[:verbose]
return if options[:noop]
+
fu_each_src_dest0(src, dest) do |s,d|
remove_file d, true if options[:force]
File.link s, d
end
end
- module_function :ln
alias link ln
- module_function :link
-
- OPT_TABLE['ln'] =
- OPT_TABLE['link'] = %w( noop verbose force )
#
# Options: force noop verbose
#
- # <b><tt>ln_s(old, new, options = {})</tt></b>
+ # <b><tt>ln_s( old, new, options = {} )</tt></b>
#
# Creates a symbolic link +new+ which points to +old+. If +new+ already
# exists and it is a directory, creates a symbolic link +new/old+. If +new+
@@ -320,7 +277,7 @@ module FileUtils
# FileUtils.ln_s '/usr/bin/ruby', '/usr/local/bin/ruby'
# FileUtils.ln_s 'verylongsourcefilename.c', 'c', :force => true
#
- # <b><tt>ln_s(list, destdir, options = {})</tt></b>
+ # <b><tt>ln_s( list, destdir, options = {} )</tt></b>
#
# Creates several symbolic links in a directory, with each one pointing to the
# item in +list+. If +destdir+ is not a directory, raises Errno::ENOTDIR.
@@ -333,18 +290,14 @@ module FileUtils
fu_check_options options, :force, :noop, :verbose
fu_output_message "ln -s#{options[:force] ? 'f' : ''} #{[src,dest].flatten.join ' '}" if options[:verbose]
return if options[:noop]
+
fu_each_src_dest0(src, dest) do |s,d|
remove_file d, true if options[:force]
File.symlink s, d
end
end
- module_function :ln_s
alias symlink ln_s
- module_function :symlink
-
- OPT_TABLE['ln_s'] =
- OPT_TABLE['symlink'] = %w( noop verbose force )
#
# Options: noop verbose
@@ -358,41 +311,34 @@ module FileUtils
options[:force] = true
ln_s src, dest, options
end
- module_function :ln_sf
- OPT_TABLE['ln_sf'] = %w( noop verbose )
#
# Options: preserve noop verbose
#
- # Copies a file content +src+ to +dest+. If +dest+ is a directory,
- # copies +src+ to +dest/src+.
+ # Copies a file +src+ to +dest+. If +dest+ is a directory, copies
+ # +src+ to +dest/src+.
#
# If +src+ is a list of files, then +dest+ must be a directory.
#
# FileUtils.cp 'eval.c', 'eval.c.org'
# FileUtils.cp %w(cgi.rb complex.rb date.rb), '/usr/lib/ruby/1.6'
# FileUtils.cp %w(cgi.rb complex.rb date.rb), '/usr/lib/ruby/1.6', :verbose => true
- # FileUtils.cp 'symlink', 'dest' # copy content, "dest" is not a symlink
#
def cp(src, dest, options = {})
fu_check_options options, :preserve, :noop, :verbose
fu_output_message "cp#{options[:preserve] ? ' -p' : ''} #{[src,dest].flatten.join ' '}" if options[:verbose]
return if options[:noop]
- fu_each_src_dest(src, dest) do |s, d|
+
+ fu_each_src_dest(src, dest) do |s,d|
copy_file s, d, options[:preserve]
end
end
- module_function :cp
alias copy cp
- module_function :copy
-
- OPT_TABLE['cp'] =
- OPT_TABLE['copy'] = %w( noop verbose preserve )
#
- # Options: preserve noop verbose dereference_root
+ # Options: preserve noop verbose
#
# Copies +src+ to +dest+. If +src+ is a directory, this method copies
# all its contents recursively. If +dest+ is a directory, copies
@@ -406,7 +352,7 @@ module FileUtils
#
# # Examples of copying several files to target directory.
# FileUtils.cp_r %w(mail.rb field.rb debug/), site_ruby + '/tmail'
- # FileUtils.cp_r Dir.glob('*.rb'), '/home/aamine/lib/ruby', :noop => true, :verbose => true
+ # FileUtils.cp_r Dir.glob('*.rb'), '/home/aamine/lib/ruby', :noop, :verbose
#
# # If you want to copy all contents of a directory instead of the
# # directory itself, c.f. src/x -> dest/x, src/y -> dest/y,
@@ -415,61 +361,188 @@ module FileUtils
# # but this doesn't.
#
def cp_r(src, dest, options = {})
- fu_check_options options, :preserve, :noop, :verbose, :dereference_root
+ fu_check_options options, :preserve, :noop, :verbose
fu_output_message "cp -r#{options[:preserve] ? 'p' : ''} #{[src,dest].flatten.join ' '}" if options[:verbose]
return if options[:noop]
- options[:dereference_root] = true unless options.key?(:dereference_root)
- fu_each_src_dest(src, dest) do |s, d|
- copy_entry s, d, options[:preserve], options[:dereference_root]
+
+ fu_each_src_dest(src, dest) do |s,d|
+ if File.directory?(s)
+ fu_traverse(s) {|rel, deref, st|
+ ctx = CopyContext_.new(options[:preserve], deref, st)
+ ctx.copy_entry "#{s}/#{rel}", "#{d}/#{rel}"
+ }
+ else
+ copy_file s, d, options[:preserve]
+ end
end
end
- module_function :cp_r
- OPT_TABLE['cp_r'] = %w( noop verbose preserve dereference_root )
+ def fu_traverse(prefix, dereference_root = true) #:nodoc:
+ stack = ['.']
+ deref = dereference_root
+ while rel = stack.pop
+ st = File.lstat("#{prefix}/#{rel}")
+ if st.directory? and (deref or not st.symlink?)
+ stack.concat Dir.entries("#{prefix}/#{rel}")\
+ .reject {|ent| ent == '.' or ent == '..' }\
+ .map {|ent| "#{rel}/#{ent}" }.reverse
+ end
+ yield rel, deref, st
+ deref = false
+ end
+ end
+ private :fu_traverse
#
# Copies a file system entry +src+ to +dest+.
- # If +src+ is a directory, this method copies its contents recursively.
- # This method preserves file types, c.f. symlink, directory...
- # (FIFO, device files and etc. are not supported yet)
+ # This method preserves file types, c.f. FIFO, device files, directory....
#
# Both of +src+ and +dest+ must be a path name.
# +src+ must exist, +dest+ must not exist.
#
- # If +preserve+ is true, this method preserves owner, group, permissions
- # and modified time.
+ # If +preserve+ is true, this method preserves owner, group and permissions.
+ # If +dereference+ is true, this method copies a target of symbolic link
+ # instead of a symbolic link itself.
#
- # If +dereference_root+ is true, this method dereference tree root.
- #
- def copy_entry(src, dest, preserve = false, dereference_root = false)
- Entry_.new(src, nil, dereference_root).traverse do |ent|
- destent = Entry_.new(dest, ent.rel, false)
- ent.copy destent.path
- ent.copy_metadata destent.path if preserve
- end
+ def copy_entry(src, dest, preserve = false, dereference = false)
+ CopyContext_.new(preserve, dereference).copy_entry src, dest
end
- module_function :copy_entry
#
# Copies file contents of +src+ to +dest+.
# Both of +src+ and +dest+ must be a path name.
#
def copy_file(src, dest, preserve = false, dereference = true)
- ent = Entry_.new(src, nil, dereference)
- ent.copy_file dest
- ent.copy_metadata dest if preserve
+ CopyContext_.new(preserve, dereference).copy_content src, dest
end
- module_function :copy_file
#
# Copies stream +src+ to +dest+.
- # +src+ must respond to #read(n) and
- # +dest+ must respond to #write(str).
+ # Both of +src+ and +dest+ must be a IO.
#
def copy_stream(src, dest)
fu_copy_stream0 src, dest, fu_stream_blksize(src, dest)
end
- module_function :copy_stream
+
+ def fu_copy_stream0(src, dest, blksize) #:nodoc:
+ begin
+ while true
+ dest.syswrite src.sysread(blksize)
+ end
+ rescue EOFError
+ end
+ end
+ private :fu_copy_stream0
+
+ class CopyContext_
+ include ::FileUtils
+
+ def initialize(preserve = false, dereference = false, stat = nil)
+ @preserve = preserve
+ @dereference = dereference
+ @stat = stat
+ end
+
+ def copy_entry(src, dest)
+ preserve(src, dest) {
+ _copy_entry src, dest
+ }
+ end
+
+ def copy_content(src, dest)
+ preserve(src, dest) {
+ _copy_content src, dest
+ }
+ end
+
+ private
+
+ def _copy_entry(src, dest)
+ st = stat(src)
+ case
+ when st.file?
+ _copy_content src, dest
+ when st.directory?
+ begin
+ Dir.mkdir File.expand_path(dest)
+ rescue => err
+ raise unless File.directory?(dest)
+ end
+ when st.symlink?
+ File.symlink File.readlink(src), dest
+ when st.chardev?
+ raise "cannot handle device file" unless File.respond_to?(:mknod)
+ mknod dest, ?c, 0666, st.rdev
+ when st.blockdev?
+ raise "cannot handle device file" unless File.respond_to?(:mknod)
+ mknod dest, ?b, 0666, st.rdev
+ when st.socket?
+ raise "cannot handle socket" unless File.respond_to?(:mknod)
+ mknod dest, nil, st.mode, 0
+ when st.pipe?
+ raise "cannot handle FIFO" unless File.respond_to?(:mkfifo)
+ mkfifo dest, 0666
+ when (st.mode & 0xF000) == (_S_IF_DOOR = 0xD000) # door
+ raise "cannot handle door: #{src}"
+ else
+ raise "unknown file type: #{src}"
+ end
+ end
+
+ def _copy_content(src, dest)
+ st = stat(src)
+ File.open(src, 'rb') {|r|
+ File.open(dest, 'wb', st.mode) {|w|
+ fu_copy_stream0 r, w, (fu_blksize(st) || fu_default_blksize())
+ }
+ }
+ end
+
+ def preserve(src, dest)
+ return yield unless @preserve
+ st = stat(src)
+ yield
+ File.utime st.atime, st.mtime, dest
+ begin
+ chown st.uid, st.gid, dest
+ rescue Errno::EPERM
+ # clear setuid/setgid
+ chmod st.mode & 01777, dest
+ else
+ chmod st.mode, dest
+ end
+ end
+
+ def stat(path)
+ @stat ||= ::File.stat(path)
+ end
+
+ def chmod(mode, path)
+ if @dereference
+ ::File.chmod mode, path
+ else
+ begin
+ ::File.lchmod mode, path
+ rescue NotImplementedError
+ # just ignore this because chmod(symlink) changes attributes of
+ # symlink target, which is not our intent.
+ end
+ end
+ end
+
+ def chown(uid, gid, path)
+ if @dereference
+ ::File.chown uid, gid, path
+ else
+ begin
+ ::File.lchown uid, gid, path
+ rescue NotImplementedError
+ # just ignore this because chown(symlink) changes attributes of
+ # symlink target, which is not our intent.
+ end
+ end
+ end
+ end
#
# Options: force noop verbose
@@ -487,38 +560,35 @@ module FileUtils
fu_check_options options, :force, :noop, :verbose
fu_output_message "mv#{options[:force] ? ' -f' : ''} #{[src,dest].flatten.join ' '}" if options[:verbose]
return if options[:noop]
- fu_each_src_dest(src, dest) do |s, d|
- destent = Entry_.new(d, nil, true)
- begin
- if destent.exist?
- if destent.directory?
- raise Errno::EEXIST, dest
- else
- destent.remove_file if rename_cannot_overwrite_file?
- end
+
+ fu_each_src_dest(src, dest) do |s,d|
+ if rename_cannot_overwrite_file? and File.file?(d)
+ begin
+ File.unlink d
+ rescue SystemCallError
+ raise unless options[:force]
end
+ end
+ begin
+ File.rename s, d
+ rescue SystemCallError
begin
- File.rename s, d
- rescue Errno::EXDEV
copy_entry s, d, true
+ File.unlink s
+ rescue SystemCallError
+ raise unless options[:force]
end
- rescue SystemCallError
- raise unless options[:force]
end
end
end
- module_function :mv
alias move mv
- module_function :move
-
- OPT_TABLE['mv'] =
- OPT_TABLE['move'] = %w( noop verbose force )
def rename_cannot_overwrite_file? #:nodoc:
- /djgpp|cygwin|mswin|mingw|bccwin|wince|emx/ =~ RUBY_PLATFORM
+ /djgpp|cygwin|mswin|mingw|bccwin|wince|emx/ !~ RUBY_PLATFORM
end
- private_module_function :rename_cannot_overwrite_file?
+ private :rename_cannot_overwrite_file?
+
#
# Options: force noop verbose
@@ -536,24 +606,18 @@ module FileUtils
fu_output_message "rm#{options[:force] ? ' -f' : ''} #{list.join ' '}" if options[:verbose]
return if options[:noop]
- list.each do |path|
- remove_file path, options[:force]
+ list.each do |fname|
+ remove_file fname, options[:force]
end
end
- module_function :rm
alias remove rm
- module_function :remove
-
- OPT_TABLE['rm'] =
- OPT_TABLE['remove'] = %w( noop verbose force )
#
# Options: noop verbose
#
- # Equivalent to
- #
- # #rm(list, :force => true)
+ # Same as
+ # #rm(list, :force)
#
def rm_f(list, options = {})
fu_check_options options, :noop, :verbose
@@ -561,16 +625,11 @@ module FileUtils
options[:force] = true
rm list, options
end
- module_function :rm_f
alias safe_unlink rm_f
- module_function :safe_unlink
-
- OPT_TABLE['rm_f'] =
- OPT_TABLE['safe_unlink'] = %w( noop verbose )
#
- # Options: force noop verbose secure
+ # Options: force noop verbose
#
# remove files +list+[0] +list+[1]... If +list+[n] is a directory,
# removes its all contents recursively. This method ignores
@@ -578,200 +637,78 @@ module FileUtils
#
# FileUtils.rm_r Dir.glob('/tmp/*')
# FileUtils.rm_r '/', :force => true # :-)
- #
- # WARNING: This method causes local vulnerability
- # if one of parent directories or removing directory tree are world
- # writable (including /tmp, whose permission is 1777), and the current
- # process has strong privilege such as Unix super user (root), and the
- # system has symbolic link. For secure removing, read the documentation
- # of #remove_entry_secure carefully, and set :secure option to true.
- # Default is :secure=>false.
- #
- # NOTE: This method calls #remove_entry_secure if :secure option is set.
- # See also #remove_entry_secure.
#
def rm_r(list, options = {})
- fu_check_options options, :force, :noop, :verbose, :secure
- # options[:secure] = true unless options.key?(:secure)
+ fu_check_options options, :force, :noop, :verbose
list = fu_list(list)
fu_output_message "rm -r#{options[:force] ? 'f' : ''} #{list.join ' '}" if options[:verbose]
return if options[:noop]
- list.each do |path|
- if options[:secure]
- remove_entry_secure path, options[:force]
- else
- remove_entry path, options[:force]
+
+ list.each do |fname|
+ begin
+ st = File.lstat(fname)
+ rescue
+ next if options[:force]
+ raise
+ end
+ if st.symlink? then remove_file fname, options[:force]
+ elsif st.directory? then remove_dir fname, options[:force]
+ else remove_file fname, options[:force]
end
end
end
- module_function :rm_r
-
- OPT_TABLE['rm_r'] = %w( noop verbose force secure )
#
- # Options: noop verbose secure
+ # Options: noop verbose
#
- # Equivalent to
- #
+ # Same as
# #rm_r(list, :force => true)
- #
- # WARNING: This method causes local vulnerability.
- # Read the documentation of #rm_r first.
#
def rm_rf(list, options = {})
- fu_check_options options, :noop, :verbose, :secure
+ fu_check_options options, :noop, :verbose
options = options.dup
options[:force] = true
rm_r list, options
end
- module_function :rm_rf
alias rmtree rm_rf
- module_function :rmtree
-
- OPT_TABLE['rm_rf'] =
- OPT_TABLE['rmtree'] = %w( noop verbose secure )
- #
- # This method removes a file system entry +path+. +path+ shall be a
- # regular file, a directory, or something. If +path+ is a directory,
- # remove it recursively. This method is required to avoid TOCTTOU
- # (time-of-check-to-time-of-use) local security vulnerability of #rm_r.
- # #rm_r causes security hole when:
- #
- # * Parent directory is world writable (including /tmp).
- # * Removing directory tree includes world writable directory.
- # * The system has symbolic link.
- #
- # To avoid this security hole, this method applies special preprocess.
- # If +path+ is a directory, this method chown(2) and chmod(2) all
- # removing directories. This requires the current process is the
- # owner of the removing whole directory tree, or is the super user (root).
- #
- # WARNING: You must ensure that *ALL* parent directories are not
- # world writable. Otherwise this method does not work.
- # Only exception is temporary directory like /tmp and /var/tmp,
- # whose permission is 1777.
- #
- # WARNING: Only the owner of the removing directory tree, or Unix super
- # user (root) should invoke this method. Otherwise this method does not
- # work.
- #
- # For details of this security vulnerability, see Perl's case:
- #
- # http://www.cve.mitre.org/cgi-bin/cvename.cgi?name=CAN-2005-0448
- # http://www.cve.mitre.org/cgi-bin/cvename.cgi?name=CAN-2004-0452
- #
- # For fileutils.rb, this vulnerability is reported in [ruby-dev:26100].
- #
- def remove_entry_secure(path, force = false)
- unless fu_have_symlink?
- remove_entry path, force
- return
- end
- fullpath = File.expand_path(path)
- st = File.lstat(fullpath)
- unless st.directory?
- File.unlink fullpath
- return
- end
- # is a directory.
- parent_st = File.stat(File.dirname(fullpath))
- unless fu_world_writable?(parent_st)
- remove_entry path, force
- return
- end
- unless parent_st.sticky?
- raise ArgumentError, "parent directory is world writable, FileUtils#remove_entry_secure does not work; abort: #{path.inspect} (parent directory mode #{'%o' % parent_st.mode})"
- end
- # freeze tree root
- euid = Process.euid
- File.open(fullpath + '/.') {|f|
- unless fu_stat_identical_entry?(st, f.stat)
- # symlink (TOC-to-TOU attack?)
- File.unlink fullpath
- return
- end
- f.chown euid, -1
- f.chmod 0700
- }
- # ---- tree root is frozen ----
- root = Entry_.new(path)
- root.preorder_traverse do |ent|
- if ent.directory?
- ent.chown euid, -1
- ent.chmod 0700
- end
- end
- root.postorder_traverse do |ent|
- begin
- ent.remove
- rescue
- raise unless force
+ def remove_file(fname, force = false) #:nodoc:
+ first_time_p = true
+ begin
+ File.unlink fname
+ rescue Errno::ENOENT
+ raise unless force
+ rescue
+ if first_time_p
+ # try once more for Windows
+ first_time_p = false
+ File.chmod 0777, fname
+ retry
+ end
+ raise
+ end
+ end
+
+ def remove_dir(dir, force = false) #:nodoc:
+ Dir.foreach(dir) do |file|
+ next if /\A\.\.?\z/ === file
+ path = "#{dir}/#{file}"
+ if File.symlink?(path)
+ remove_file path, force
+ elsif File.directory?(path)
+ remove_dir path, force
+ else
+ remove_file path, force
end
end
- rescue
- raise unless force
- end
- module_function :remove_entry_secure
-
- def fu_world_writable?(st)
- (st.mode & 0002) != 0
- end
-
- def fu_have_symlink? #:nodoc
- File.symlink nil, nil
- rescue NotImplementedError
- return false
- rescue
- return true
- end
- private_module_function :fu_have_symlink?
-
- def fu_stat_identical_entry?(a, b) #:nodoc:
- a.dev == b.dev and a.ino == b.ino
- end
- private_module_function :fu_stat_identical_entry?
-
- #
- # This method removes a file system entry +path+.
- # +path+ might be a regular file, a directory, or something.
- # If +path+ is a directory, remove it recursively.
- #
- # See also #remove_entry_secure.
- #
- def remove_entry(path, force = false)
- Entry_.new(path).postorder_traverse do |ent|
- begin
- ent.remove
- rescue
- raise unless force
- end
+ begin
+ Dir.rmdir dir.sub(%r</\z>, '')
+ rescue Errno::ENOENT
+ raise unless force
end
- rescue
- raise unless force
end
- module_function :remove_entry
- #
- # Removes a file +path+.
- # This method ignores StandardError if +force+ is true.
- #
- def remove_file(path, force = false)
- Entry_.new(path).remove_file
- rescue
- raise unless force
- end
- module_function :remove_file
-
- #
- # Removes a directory +dir+ and its contents recursively.
- # This method ignores StandardError if +force+ is true.
- #
- def remove_dir(path, force = false)
- remove_entry path, force # FIXME?? check if it is a directory
- end
- module_function :remove_dir
#
# Returns true if the contents of a file A and a file B are identical.
@@ -787,12 +724,9 @@ module FileUtils
}
}
end
- module_function :compare_file
alias identical? compare_file
alias cmp compare_file
- module_function :identical?
- module_function :cmp
#
# Returns true if the contents of a stream +a+ and +b+ are identical.
@@ -811,7 +745,7 @@ module FileUtils
end
false
end
- module_function :compare_stream
+
#
# Options: mode noop verbose
@@ -826,8 +760,9 @@ module FileUtils
fu_check_options options, :mode, :preserve, :noop, :verbose
fu_output_message "install -c#{options[:preserve] && ' -p'}#{options[:mode] ? (' -m 0%o' % options[:mode]) : ''} #{[src,dest].flatten.join ' '}" if options[:verbose]
return if options[:noop]
- fu_each_src_dest(src, dest) do |s, d|
- unless File.exist?(d) and compare_file(s, d)
+
+ fu_each_src_dest(src, dest) do |s,d|
+ unless File.exist?(d) and compare_file(s,d)
remove_file d, true
st = File.stat(s) if options[:preserve]
copy_file s, d
@@ -836,9 +771,7 @@ module FileUtils
end
end
end
- module_function :install
- OPT_TABLE['install'] = %w( noop verbose preserve mode )
#
# Options: noop verbose
@@ -855,144 +788,9 @@ module FileUtils
list = fu_list(list)
fu_output_message sprintf('chmod %o %s', mode, list.join(' ')) if options[:verbose]
return if options[:noop]
- list.each do |path|
- Entry_.new(path).chmod mode
- end
- end
- module_function :chmod
-
- OPT_TABLE['chmod'] = %w( noop verbose )
-
- #
- # Options: noop verbose force
- #
- # Changes permission bits on the named files (in +list+)
- # to the bit pattern represented by +mode+.
- #
- # FileUtils.chmod_R 0700, "/tmp/app.#{$$}"
- #
- def chmod_R(mode, list, options = {})
- fu_check_options options, :noop, :verbose, :force
- list = fu_list(list)
- fu_output_message sprintf('chmod -R%s %o %s',
- (options[:force] ? 'f' : ''),
- mode, list.join(' ')) if options[:verbose]
- return if options[:noop]
- list.each do |root|
- Entry_.new(root).traverse do |ent|
- begin
- ent.chmod mode
- rescue
- raise unless options[:force]
- end
- end
- end
+ File.chmod mode, *list
end
- module_function :chmod_R
- OPT_TABLE['chmod_R'] = %w( noop verbose )
-
- #
- # Options: noop verbose
- #
- # Changes owner and group on the named files (in +list+)
- # to the user +user+ and the group +group+. +user+ and +group+
- # may be an ID (Integer/String) or a name (String).
- # If +user+ or +group+ is nil, this method does not change
- # the attribute.
- #
- # FileUtils.chown 'root', 'staff', '/usr/local/bin/ruby'
- # FileUtils.chown nil, 'bin', Dir.glob('/usr/bin/*'), :verbose => true
- #
- def chown(user, group, list, options = {})
- fu_check_options options, :noop, :verbose
- list = fu_list(list)
- fu_output_message sprintf('chown %s%s',
- [user,group].compact.join(':') + ' ',
- list.join(' ')) if options[:verbose]
- return if options[:noop]
- uid = fu_get_uid(user)
- gid = fu_get_gid(group)
- list.each do |path|
- Entry_.new(path).chown uid, gid
- end
- end
- module_function :chown
-
- OPT_TABLE['chown'] = %w( noop verbose )
-
- #
- # Options: noop verbose force
- #
- # Changes owner and group on the named files (in +list+)
- # to the user +user+ and the group +group+ recursively.
- # +user+ and +group+ may be an ID (Integer/String) or
- # a name (String). If +user+ or +group+ is nil, this
- # method does not change the attribute.
- #
- # FileUtils.chown_R 'www', 'www', '/var/www/htdocs'
- # FileUtils.chown_R 'cvs', 'cvs', '/var/cvs', :verbose => true
- #
- def chown_R(user, group, list, options = {})
- fu_check_options options, :noop, :verbose, :force
- list = fu_list(list)
- fu_output_message sprintf('chown -R%s %s%s',
- (options[:force] ? 'f' : ''),
- [user,group].compact.join(':') + ' ',
- list.join(' ')) if options[:verbose]
- return if options[:noop]
- uid = fu_get_uid(user)
- gid = fu_get_gid(group)
- return unless uid or gid
- list.each do |root|
- Entry_.new(root).traverse do |ent|
- begin
- ent.chown uid, gid
- rescue
- raise unless options[:force]
- end
- end
- end
- end
- module_function :chown_R
-
- OPT_TABLE['chown_R'] = %w( noop verbose )
-
- begin
- require 'etc'
-
- def fu_get_uid(user) #:nodoc:
- return nil unless user
- user = user.to_s
- if /\A\d+\z/ =~ user
- then user.to_i
- else Etc.getpwnam(user).uid
- end
- end
- private_module_function :fu_get_uid
-
- def fu_get_gid(group) #:nodoc:
- return nil unless group
- if /\A\d+\z/ =~ group
- then group.to_i
- else Etc.getgrnam(group).gid
- end
- end
- private_module_function :fu_get_gid
-
- rescue LoadError
- # need Win32 support???
-
- def fu_get_uid(user) #:nodoc:
- user # FIXME
- end
- private_module_function :fu_get_uid
-
- def fu_get_gid(group) #:nodoc:
- group # FIXME
- end
- private_module_function :fu_get_gid
- end
#
# Options: noop verbose
@@ -1008,396 +806,56 @@ module FileUtils
list = fu_list(list)
fu_output_message "touch #{list.join ' '}" if options[:verbose]
return if options[:noop]
+
t = Time.now
- list.each do |path|
+ list.each do |fname|
begin
- File.utime(t, t, path)
+ File.utime(t, t, fname)
rescue Errno::ENOENT
- File.open(path, 'a') {
+ File.open(fname, 'a') {
;
}
end
end
end
- module_function :touch
-
- OPT_TABLE['touch'] = %w( noop verbose )
private
- module StreamUtils_
- private
-
- def fu_windows?
- /mswin|mingw|bccwin|wince|emx/ =~ RUBY_PLATFORM
- end
-
- def fu_copy_stream0(src, dest, blksize) #:nodoc:
- # FIXME: readpartial?
- while s = src.read(blksize)
- dest.write s
- end
- end
-
- def fu_stream_blksize(*streams)
- streams.each do |s|
- next unless s.respond_to?(:stat)
- size = fu_blksize(s.stat)
- return size if size
- end
- fu_default_blksize()
- end
-
- def fu_blksize(st)
- s = st.blksize
- return nil unless s
- return nil if s == 0
- s
- end
-
- def fu_default_blksize
- 1024
+ def fu_check_options(options, *optdecl)
+ h = options.dup
+ optdecl.each do |name|
+ h.delete name
end
+ raise ArgumentError, "no such option: #{h.keys.join(' ')}" unless h.empty?
end
- include StreamUtils_
- extend StreamUtils_
-
- class Entry_ #:nodoc: internal use only
- include StreamUtils_
-
- def initialize(a, b = nil, deref = false)
- @prefix = @rel = @path = nil
- if b
- @prefix = a
- @rel = b
- else
- @path = a
- end
- @deref = deref
- @stat = nil
- @lstat = nil
- end
-
- def inspect
- "\#<#{self.class} #{path()}>"
- end
-
- def path
- if @path
- @path.to_str
- else
- join(@prefix, @rel)
- end
- end
-
- def prefix
- @prefix || @path
- end
-
- def rel
- @rel
- end
-
- def dereference?
- @deref
- end
-
- def exist?
- lstat! ? true : false
- end
-
- def file?
- s = lstat!
- s and s.file?
- end
-
- def directory?
- s = lstat!
- s and s.directory?
- end
-
- def symlink?
- s = lstat!
- s and s.symlink?
- end
-
- def chardev?
- s = lstat!
- s and s.chardev?
- end
-
- def blockdev?
- s = lstat!
- s and s.blockdev?
- end
-
- def socket?
- s = lstat!
- s and s.socket?
- end
-
- def pipe?
- s = lstat!
- s and s.pipe?
- end
-
- S_IF_DOOR = 0xD000
-
- def door?
- s = lstat!
- s and (s.mode & 0xF000 == S_IF_DOOR)
- end
-
- def entries
- Dir.entries(path())\
- .reject {|n| n == '.' or n == '..' }\
- .map {|n| Entry_.new(prefix(), join(rel(), n.untaint)) }
- end
-
- def stat
- return @stat if @stat
- if lstat() and lstat().symlink?
- @stat = File.stat(path())
- else
- @stat = lstat()
- end
- @stat
- end
-
- def stat!
- return @stat if @stat
- if lstat! and lstat!.symlink?
- @stat = File.stat(path())
- else
- @stat = lstat!
- end
- @stat
- rescue SystemCallError
- nil
- end
-
- def lstat
- if dereference?
- @lstat ||= File.stat(path())
- else
- @lstat ||= File.lstat(path())
- end
- end
-
- def lstat!
- lstat()
- rescue SystemCallError
- nil
- end
-
- def chmod(mode)
- if symlink?
- File.lchmod mode, path() if have_lchmod?
- else
- File.chmod mode, path()
- end
- end
-
- def chown(uid, gid)
- if symlink?
- File.lchown uid, gid, path() if have_lchown?
- else
- File.chown uid, gid, path()
- end
- end
-
- def copy(dest)
- case
- when file?
- copy_file dest
- when directory?
- begin
- Dir.mkdir dest
- rescue
- raise unless File.directory?(dest)
- end
- when symlink?
- File.symlink File.readlink(path()), dest
- when chardev?
- raise "cannot handle device file" unless File.respond_to?(:mknod)
- mknod dest, ?c, 0666, lstat().rdev
- when blockdev?
- raise "cannot handle device file" unless File.respond_to?(:mknod)
- mknod dest, ?b, 0666, lstat().rdev
- when socket?
- raise "cannot handle socket" unless File.respond_to?(:mknod)
- mknod dest, nil, lstat().mode, 0
- when pipe?
- raise "cannot handle FIFO" unless File.respond_to?(:mkfifo)
- mkfifo dest, 0666
- when door?
- raise "cannot handle door: #{path()}"
- else
- raise "unknown file type: #{path()}"
- end
- end
-
- def copy_file(dest)
- st = stat()
- File.open(path(), 'rb') {|r|
- File.open(dest, 'wb', st.mode) {|w|
- fu_copy_stream0 r, w, (fu_blksize(st) || fu_default_blksize())
- }
- }
- end
-
- def copy_metadata(path)
- st = lstat()
- File.utime st.atime, st.mtime, path
- begin
- File.chown st.uid, st.gid, path
- rescue Errno::EPERM
- # clear setuid/setgid
- File.chmod st.mode & 01777, path
- else
- File.chmod st.mode, path
- end
- end
-
- def remove
- if directory?
- remove_dir1
- else
- remove_file
- end
- end
-
- def remove_dir1
- platform_support {
- Dir.rmdir path().sub(%r</\z>, '')
- }
- end
-
- def remove_file
- platform_support {
- File.unlink path
- }
- end
-
- def platform_support
- return yield unless fu_windows?
- first_time_p = true
- begin
- yield
- rescue Errno::ENOENT
- raise
- rescue => err
- if first_time_p
- first_time_p = false
- begin
- File.chmod 0700, path() # Windows does not have symlink
- retry
- rescue SystemCallError
- end
- end
- raise err
- end
- end
-
- def preorder_traverse
- stack = [self]
- while ent = stack.pop
- yield ent
- stack.concat ent.entries.reverse if ent.directory?
- end
- end
-
- alias traverse preorder_traverse
-
- def postorder_traverse
- if directory?
- entries().each do |ent|
- ent.postorder_traverse do |e|
- yield e
- end
- end
- end
- yield self
- end
-
- private
-
- $fileutils_rb_have_lchmod = nil
-
- def have_lchmod?
- # This is not MT-safe, but it does not matter.
- if $fileutils_rb_have_lchmod == nil
- $fileutils_rb_have_lchmod = check_have_lchmod?
- end
- $fileutils_rb_have_lchmod
- end
-
- def check_have_lchmod?
- return false unless File.respond_to?(:lchmod)
- File.lchmod 0
- return true
- rescue NotImplementedError
- return false
- end
-
- $fileutils_rb_have_lchown = nil
-
- def have_lchown?
- # This is not MT-safe, but it does not matter.
- if $fileutils_rb_have_lchown == nil
- $fileutils_rb_have_lchown = check_have_lchown?
- end
- $fileutils_rb_have_lchown
- end
-
- def check_have_lchown?
- return false unless File.respond_to?(:lchown)
- File.lchown nil, nil
- return true
- rescue NotImplementedError
- return false
- end
-
- def join(dir, base)
- return dir.to_str if not base or base == '.'
- return base.to_str if not dir or dir == '.'
- File.join(dir, base)
- end
- end # class Entry_
-
- def fu_list(arg) #:nodoc:
+ def fu_list(arg)
[arg].flatten.map {|path| path.to_str }
end
- private_module_function :fu_list
- def fu_each_src_dest(src, dest) #:nodoc:
+ def fu_each_src_dest(src, dest)
fu_each_src_dest0(src, dest) do |s, d|
raise ArgumentError, "same file: #{s} and #{d}" if fu_same?(s, d)
yield s, d
end
end
- private_module_function :fu_each_src_dest
- def fu_each_src_dest0(src, dest) #:nodoc:
+ def fu_each_src_dest0(src, dest)
if src.is_a?(Array)
src.each do |s|
- s = s.to_str
- yield s, File.join(dest, File.basename(s))
+ yield s.to_str, File.join(dest, File.basename(s))
end
else
- src = src.to_str
if File.directory?(dest)
- yield src, File.join(dest, File.basename(src))
+ yield src.to_str, File.join(dest, File.basename(src))
else
- yield src, dest.to_str
+ yield src.to_str, dest.to_str
end
end
end
- private_module_function :fu_each_src_dest0
- def fu_same?(a, b) #:nodoc:
- if fu_have_st_ino?
+ def fu_same?(a, b)
+ if have_st_ino?
st1 = File.stat(a)
st2 = File.stat(b)
st1.dev == st2.dev and st1.ino == st2.ino
@@ -1407,91 +865,83 @@ module FileUtils
rescue Errno::ENOENT
return false
end
- private_module_function :fu_same?
- def fu_have_st_ino? #:nodoc:
- not fu_windows?
+ def have_st_ino?
+ /mswin|mingw|bccwin|wince|emx/ !~ RUBY_PLATFORM
end
- private_module_function :fu_have_st_ino?
- def fu_check_options(options, *optdecl) #:nodoc:
- h = options.dup
- optdecl.each do |name|
- h.delete name
+ def fu_stream_blksize(*streams)
+ streams.each do |s|
+ next unless s.respond_to?(:stat)
+ size = fu_blksize(s.stat)
+ return size if size
end
- raise ArgumentError, "no such option: #{h.keys.join(' ')}" unless h.empty?
+ fu_default_blksize()
end
- private_module_function :fu_check_options
- def fu_update_option(args, new) #:nodoc:
- if args.last.is_a?(Hash)
- args[-1] = args.last.dup.update(new)
- else
- args.push new
- end
- args
+ def fu_blksize(st)
+ s = st.blksize
+ return nil unless s
+ return nil if s == 0
+ s
+ end
+
+ def fu_default_blksize
+ 1024
end
- private_module_function :fu_update_option
@fileutils_output = $stderr
@fileutils_label = ''
- def fu_output_message(msg) #:nodoc:
+ def fu_output_message(msg)
@fileutils_output ||= $stderr
@fileutils_label ||= ''
@fileutils_output.puts @fileutils_label + msg
end
- private_module_function :fu_output_message
-
- METHODS = singleton_methods() - ['private_module_function']
-
- #
- # Returns an Array of method names which have any options.
- #
- # p FileUtils.commands #=> ["chmod", "cp", "cp_r", "install", ...]
- #
- def FileUtils.commands
- OPT_TABLE.keys
- end
- #
- # Returns an Array of option names.
- #
- # p FileUtils.options #=> ["noop", "force", "verbose", "preserve", "mode"]
- #
- def FileUtils.options
- OPT_TABLE.values.flatten.uniq
+ def fu_update_option(args, new)
+ if args.last.is_a?(Hash)
+ args.last.update new
+ else
+ args.push new
+ end
+ args
end
- #
- # Returns true if the method +mid+ have an option +opt+.
- #
- # p FileUtils.have_option?(:cp, :noop) #=> true
- # p FileUtils.have_option?(:rm, :force) #=> true
- # p FileUtils.have_option?(:rm, :perserve) #=> false
- #
- def FileUtils.have_option?(mid, opt)
- li = OPT_TABLE[mid.to_s] or raise ArgumentError, "no such method: #{mid}"
- li.include?(opt.to_s)
- end
- #
- # Returns an Array of option names of the method +mid+.
- #
- # p FileUtils.options(:rm) #=> ["noop", "verbose", "force"]
- #
- def FileUtils.options_of(mid)
- OPT_TABLE[mid.to_s]
- end
+ extend self
+
+
+ OPT_TABLE = {
+ 'cd' => %w( noop verbose ),
+ 'chdir' => %w( noop verbose ),
+ 'chmod' => %w( noop verbose ),
+ 'copy' => %w( noop verbose preserve ),
+ 'cp' => %w( noop verbose preserve ),
+ 'cp_r' => %w( noop verbose preserve ),
+ 'install' => %w( noop verbose preserve mode ),
+ 'link' => %w( noop verbose force ),
+ 'ln' => %w( noop verbose force ),
+ 'ln_s' => %w( noop verbose force ),
+ 'ln_sf' => %w( noop verbose ),
+ 'makedirs' => %w( noop verbose ),
+ 'mkdir' => %w( noop verbose mode ),
+ 'mkdir_p' => %w( noop verbose mode ),
+ 'mkpath' => %w( noop verbose ),
+ 'move' => %w( noop verbose force ),
+ 'mv' => %w( noop verbose force ),
+ 'remove' => %w( noop verbose force ),
+ 'rm' => %w( noop verbose force ),
+ 'rm_f' => %w( noop verbose ),
+ 'rm_r' => %w( noop verbose force ),
+ 'rm_rf' => %w( noop verbose ),
+ 'rmtree' => %w( noop verbose ),
+ 'rmdir' => %w( noop verbose ),
+ 'safe_unlink' => %w( noop verbose ),
+ 'symlink' => %w( noop verbose force ),
+ 'touch' => %w( noop verbose )
+ }
- #
- # Returns an Array of method names which have the option +opt+.
- #
- # p FileUtils.collect_method(:preserve) #=> ["cp", "cp_r", "copy", "install"]
- #
- def FileUtils.collect_method(opt)
- OPT_TABLE.keys.select {|m| OPT_TABLE[m].include?(opt.to_s) }
- end
#
# This module has all methods of FileUtils module, but it outputs messages
@@ -1502,20 +952,15 @@ module FileUtils
include FileUtils
@fileutils_output = $stderr
@fileutils_label = ''
- ::FileUtils.collect_method('verbose').each do |name|
+ FileUtils::OPT_TABLE.each do |name, opts|
+ next unless opts.include?('verbose')
module_eval(<<-EOS, __FILE__, __LINE__ + 1)
def #{name}(*args)
super(*fu_update_option(args, :verbose => true))
end
- private :#{name}
EOS
end
extend self
- class << self
- ::FileUtils::METHODS.each do |m|
- public m
- end
- end
end
#
@@ -1527,20 +972,15 @@ module FileUtils
include FileUtils
@fileutils_output = $stderr
@fileutils_label = ''
- ::FileUtils.collect_method('noop').each do |name|
+ FileUtils::OPT_TABLE.each do |name, opts|
+ next unless opts.include?('noop')
module_eval(<<-EOS, __FILE__, __LINE__ + 1)
def #{name}(*args)
super(*fu_update_option(args, :noop => true))
end
- private :#{name}
EOS
end
extend self
- class << self
- ::FileUtils::METHODS.each do |m|
- public m
- end
- end
end
#
@@ -1553,20 +993,15 @@ module FileUtils
include FileUtils
@fileutils_output = $stderr
@fileutils_label = ''
- ::FileUtils.collect_method('noop').each do |name|
+ FileUtils::OPT_TABLE.each do |name, opts|
+ next unless opts.include?('noop')
module_eval(<<-EOS, __FILE__, __LINE__ + 1)
def #{name}(*args)
super(*fu_update_option(args, :noop => true, :verbose => true))
end
- private :#{name}
EOS
end
extend self
- class << self
- ::FileUtils::METHODS.each do |m|
- public m
- end
- end
end
end
diff --git a/lib/forwardable.rb b/lib/forwardable.rb
index 79004ccd20..b845f76ec4 100644
--- a/lib/forwardable.rb
+++ b/lib/forwardable.rb
@@ -1,145 +1,45 @@
-# = forwardable - Support for the Delegation Pattern
#
-# $Release Version: 1.1$
-# $Revision$
-# $Date$
-# by Keiju ISHITSUKA(keiju@ishitsuka.com)
+# forwardable.rb -
+# $Release Version: 1.1$
+# $Revision$
+# $Date$
+# by Keiju ISHITSUKA(keiju@ishitsuka.com)
+# original definition by delegator.rb
+# --
+# Usage:
#
-# Documentation by James Edward Gray II and Gavin Sinclair
-#
-# == Introduction
-#
-# This library allows you delegate method calls to an object, on a method by
-# method basis. You can use Forwardable to setup this delegation at the class
-# level, or SingleForwardable to handle it at the object level.
-#
-# == Notes
-#
-# Be advised, RDoc will not detect delegated methods.
-#
-# <b>forwardable.rb provides single-method delegation via the
-# def_delegator() and def_delegators() methods. For full-class
-# delegation via DelegateClass(), see delegate.rb.</b>
-#
-# == Examples
-#
-# === Forwardable
-#
-# Forwardable makes building a new class based on existing work, with a proper
-# interface, almost trivial. We want to rely on what has come before obviously,
-# but with delegation we can take just the methods we need and even rename them
-# as appropriate. In many cases this is preferable to inheritance, which gives
-# us the entire old interface, even if much of it isn't needed.
-#
-# class Queue
+# class Foo
# extend Forwardable
-#
-# def initialize
-# @q = [ ] # prepare delegate object
-# end
-#
-# # setup prefered interface, enq() and deq()...
-# def_delegator :@q, :push, :enq
-# def_delegator :@q, :shift, :deq
-#
-# # support some general Array methods that fit Queues well
-# def_delegators :@q, :clear, :first, :push, :shift, :size
-# end
-#
-# q = Queue.new
-# q.enq 1, 2, 3, 4, 5
-# q.push 6
-#
-# q.shift # => 1
-# while q.size > 0
-# puts q.deq
-# end
-#
-# q.enq "Ruby", "Perl", "Python"
-# puts q.first
-# q.clear
-# puts q.first
-#
-# <i>Prints:</i>
-#
-# 2
-# 3
-# 4
-# 5
-# 6
-# Ruby
-# nil
-#
-# === SingleForwardable
-#
-# printer = String.new
-# printer.extend SingleForwardable # prepare object for delegation
-# printer.def_delegator "STDOUT", "puts" # add delegation for STDOUT.puts()
-# printer.puts "Howdy!"
#
-# <i>Prints:</i>
-#
-# Howdy!
-
-#
-# The Forwardable module provides delegation of specified
-# methods to a designated object, using the methods #def_delegator
-# and #def_delegators.
-#
-# For example, say you have a class RecordCollection which
-# contains an array <tt>@records</tt>. You could provide the lookup method
-# #record_number(), which simply calls #[] on the <tt>@records</tt>
-# array, like this:
-#
-# class RecordCollection
-# extends Forwardable
-# def_delegator :@records, :[], :record_number
+# def_delegators("@out", "printf", "print")
+# def_delegators(:@in, :gets)
+# def_delegator(:@contents, :[], "content_at")
# end
+# f = Foo.new
+# f.printf ...
+# f.gets
+# f.content_at(1)
#
-# Further, if you wish to provide the methods #size, #<<, and #map,
-# all of which delegate to @records, this is how you can do it:
-#
-# class RecordCollection
-# # extends Forwardable, but we did that above
-# def_delegators :@records, :size, :<<, :map
-# end
+# g = Goo.new
+# g.extend SingleForwardable
+# g.def_delegator("@out", :puts)
+# g.puts ...
#
-# Also see the example at forwardable.rb.
#
+
module Forwardable
@debug = nil
class<<self
- # force Forwardable to show up in stack backtraces of delegated methods
attr_accessor :debug
end
- #
- # Shortcut for defining multiple delegator methods, but with no
- # provision for using a different name. The following two code
- # samples have the same effect:
- #
- # def_delegators :@records, :size, :<<, :map
- #
- # def_delegator :@records, :size
- # def_delegator :@records, :<<
- # def_delegator :@records, :map
- #
- # See the examples at Forwardable and forwardable.rb.
- #
def def_instance_delegators(accessor, *methods)
for method in methods
def_instance_delegator(accessor, method)
end
end
- #
- # Defines a method _method_ which delegates to _obj_ (i.e. it calls
- # the method of the same name in _obj_). If _new_name_ is
- # provided, it is used as the name for the delegate method.
- #
- # See the examples at Forwardable and forwardable.rb.
- #
def def_instance_delegator(accessor, method, ali = method)
accessor = accessor.id2name if accessor.kind_of?(Integer)
method = method.id2name if method.kind_of?(Integer)
@@ -161,41 +61,13 @@ module Forwardable
alias def_delegator def_instance_delegator
end
-#
-# The SingleForwardable module provides delegation of specified
-# methods to a designated object, using the methods #def_delegator
-# and #def_delegators. This module is similar to Forwardable, but it works on
-# objects themselves, instead of their defining classes.
-#
-# Also see the example at forwardable.rb.
-#
module SingleForwardable
- #
- # Shortcut for defining multiple delegator methods, but with no
- # provision for using a different name. The following two code
- # samples have the same effect:
- #
- # single_forwardable.def_delegators :@records, :size, :<<, :map
- #
- # single_forwardable.def_delegator :@records, :size
- # single_forwardable.def_delegator :@records, :<<
- # single_forwardable.def_delegator :@records, :map
- #
- # See the example at forwardable.rb.
- #
def def_singleton_delegators(accessor, *methods)
for method in methods
def_singleton_delegator(accessor, method)
end
end
- #
- # Defines a method _method_ which delegates to _obj_ (i.e. it calls
- # the method of the same name in _obj_). If _new_name_ is
- # provided, it is used as the name for the delegate method.
- #
- # See the example at forwardable.rb.
- #
def def_singleton_delegator(accessor, method, ali = method)
accessor = accessor.id2name if accessor.kind_of?(Integer)
method = method.id2name if method.kind_of?(Integer)
@@ -216,3 +88,7 @@ module SingleForwardable
alias def_delegators def_singleton_delegators
alias def_delegator def_singleton_delegator
end
+
+
+
+
diff --git a/lib/ftools.rb b/lib/ftools.rb
index a99c7e713f..0441020b05 100644
--- a/lib/ftools.rb
+++ b/lib/ftools.rb
@@ -1,7 +1,7 @@
#
# = ftools.rb: Extra tools for the File class
#
-# Author:: WATANABE, Hirofumi
+# Author:: WANTANABE, Hirofumi
# Documentation:: Zachary Landau
#
# This library can be distributed under the terms of the Ruby license.
@@ -45,8 +45,8 @@ class << File
# in +to+.
#
def catname(from, to)
- if directory? to
- join to.sub(%r([/\\]$), ''), basename(from)
+ if FileTest.directory? to
+ File.join to.sub(%r([/\\]$), ''), basename(from)
else
to
end
@@ -88,7 +88,7 @@ class << File
# is printed.
#
def copy(from, to, verbose = false)
- $stderr.print from, " -> ", catname(from, to), "\n" if verbose
+ $deferr.print from, " -> ", catname(from, to), "\n" if verbose
syscopy from, to
end
@@ -101,9 +101,9 @@ class << File
#
def move(from, to, verbose = false)
to = catname(from, to)
- $stderr.print from, " -> ", to, "\n" if verbose
+ $deferr.print from, " -> ", to, "\n" if verbose
- if RUBY_PLATFORM =~ /djgpp|(cyg|ms|bcc)win|mingw/ and file? to
+ if RUBY_PLATFORM =~ /djgpp|(cyg|ms|bcc)win|mingw/ and FileTest.file? to
unlink to
end
fstat = stat(from)
@@ -111,7 +111,7 @@ class << File
rename from, to
rescue
begin
- symlink readlink(from), to and unlink from
+ symlink File.readlink(from), to and unlink from
rescue
from_stat = stat(from)
syscopy from, to and unlink from
@@ -131,7 +131,7 @@ class << File
# identical. If +verbose+ is +true+, <tt>from <=> to</tt> is printed.
#
def compare(from, to, verbose = false)
- $stderr.print from, " <=> ", to, "\n" if verbose
+ $deferr.print from, " <=> ", to, "\n" if verbose
return false if stat(from).size != stat(to).size
@@ -170,22 +170,12 @@ class << File
#
def safe_unlink(*files)
verbose = if files[-1].is_a? String then false else files.pop end
- files.each do |file|
- begin
- unlink file
- $stderr.print "removing ", file, "\n" if verbose
- rescue Errno::EACCES # for Windows
- continue if symlink? file
- begin
- mode = stat(file).mode
- o_chmod mode | 0200, file
- unlink file
- $stderr.print "removing ", file, "\n" if verbose
- rescue
- o_chmod mode, file rescue nil
- end
- rescue
- end
+ begin
+ $deferr.print files.join(" "), "\n" if verbose
+ chmod 0777, *files
+ unlink(*files)
+ rescue
+# $deferr.print "warning: Couldn't unlink #{files.join ' '}\n"
end
end
@@ -207,17 +197,18 @@ class << File
#
def makedirs(*dirs)
verbose = if dirs[-1].is_a? String then false else dirs.pop end
+# mode = if dirs[-1].is_a? Fixnum then dirs.pop else 0755 end
mode = 0755
for dir in dirs
parent = dirname(dir)
- next if parent == dir or directory? dir
- makedirs parent unless directory? parent
- $stderr.print "mkdir ", dir, "\n" if verbose
+ next if parent == dir or FileTest.directory? dir
+ makedirs parent unless FileTest.directory? parent
+ $deferr.print "mkdir ", dir, "\n" if verbose
if basename(dir) != ""
begin
Dir.mkdir dir, mode
rescue SystemCallError
- raise unless directory? dir
+ raise unless File.directory? dir
end
end
end
@@ -239,7 +230,7 @@ class << File
#
def chmod(mode, *files)
verbose = if files[-1].is_a? String then false else files.pop end
- $stderr.printf "chmod %04o %s\n", mode, files.join(" ") if verbose
+ $deferr.printf "chmod %04o %s\n", mode, files.join(" ") if verbose
o_chmod mode, *files
end
$VERBOSE = vsave
@@ -252,8 +243,8 @@ class << File
#
def install(from, to, mode = nil, verbose = false)
to = catname(from, to)
- unless exist? to and cmp from, to
- safe_unlink to if exist? to
+ unless FileTest.exist? to and cmp from, to
+ safe_unlink to if FileTest.exist? to
cp from, to, verbose
chmod mode, to, verbose if mode
end
diff --git a/lib/getopts.rb b/lib/getopts.rb
index ddb0639db1..34fb0d6442 100644
--- a/lib/getopts.rb
+++ b/lib/getopts.rb
@@ -15,8 +15,6 @@
# rewritten by Akinori MUSHA <knu@ruby-lang.org>
#
-warn "Warning:#{caller[0].sub(/:in `.*'\z/, '')}: getopts is deprecated after Ruby 1.8.1; use optparse instead" if caller[0] and $VERBOSE
-
$RCS_ID=%q$Header$
diff --git a/lib/importenv.rb b/lib/importenv.rb
index 8e1ba33b1d..435d6f972a 100644
--- a/lib/importenv.rb
+++ b/lib/importenv.rb
@@ -7,8 +7,6 @@
# $USER = "matz"
# p ENV["USER"]
-warn "Warning:#{caller[0].sub(/:in `.*'\z/, '')}: importenv is deprecated after Ruby 1.8.1 (no replacement)"
-
for k,v in ENV
next unless /^[a-zA-Z][_a-zA-Z0-9]*/ =~ k
eval <<EOS
diff --git a/lib/ipaddr.rb b/lib/ipaddr.rb
index ea26b374ec..24543ce093 100644
--- a/lib/ipaddr.rb
+++ b/lib/ipaddr.rb
@@ -207,7 +207,6 @@ class IPAddr
break if str.sub!(/\b0:0\b/, ':')
break
end
- str.sub!(/:{3,}/, '::')
if /\A::(ffff:)?([\da-f]{1,4}):([\da-f]{1,4})\Z/i =~ str
str = sprintf('::%s%d.%d.%d.%d', $1, $2.hex / 256, $2.hex % 256, $3.hex / 256, $3.hex % 256)
@@ -675,10 +674,6 @@ class TC_IPAddr < Test::Unit::TestCase
}
end
- def test_to_s
- assert_equal("3ffe:0505:0002:0000:0000:0000:0000:0001", IPAddr.new("3ffe:505:2::1").to_string)
- assert_equal("3ffe:505:2::1", IPAddr.new("3ffe:505:2::1").to_s)
- end
end
class TC_Operator < Test::Unit::TestCase
diff --git a/lib/irb.rb b/lib/irb.rb
index 1fb4397e68..1e59d6f669 100644
--- a/lib/irb.rb
+++ b/lib/irb.rb
@@ -1,9 +1,9 @@
#
# irb.rb - irb main module
-# $Release Version: 0.9.5 $
+# $Release Version: 0.9 $
# $Revision$
# $Date$
-# by Keiju ISHITSUKA(keiju@ruby-lang.org)
+# by Keiju ISHITSUKA(keiju@ishitsuka.com)
#
# --
#
@@ -88,8 +88,8 @@ module IRB
# irb interpriter main routine
#
class Irb
- def initialize(workspace = nil, input_method = nil, output_method = nil)
- @context = Context.new(self, workspace, input_method, output_method)
+ def initialize(workspace = nil, input_method = nil)
+ @context = Context.new(self, workspace, input_method)
@context.main.extend ExtendCommandBundle
@signal_status = :IN_IRB
@@ -106,8 +106,6 @@ module IRB
f = @context.prompt_s
elsif continue
f = @context.prompt_c
- elsif indent > 0
- f = @context.prompt_n
else @context.prompt_i
f = @context.prompt_i
end
@@ -119,7 +117,7 @@ module IRB
end
if @context.auto_indent_mode
unless ltype
- ind = prompt(@context.prompt_i, ltype, indent, line_no)[/.*\z/].size +
+ ind = prompt(@context.prompt_i, ltype, indent, line_no).size +
indent * 2 - p.size
ind += 2 if continue
@context.io.prompt = p + " " * ind if ind > 0
diff --git a/lib/irb/cmd/chws.rb b/lib/irb/cmd/chws.rb
index 88585b778b..84f06014ba 100644
--- a/lib/irb/cmd/chws.rb
+++ b/lib/irb/cmd/chws.rb
@@ -1,9 +1,9 @@
#
# change-ws.rb -
-# $Release Version: 0.9.5$
+# $Release Version: 0.9$
# $Revision$
# $Date$
-# by Keiju ISHITSUKA(keiju@ruby-lang.org)
+# by Keiju ISHITSUKA(Nihon Rational Software Co.,Ltd)
#
# --
#
diff --git a/lib/irb/cmd/fork.rb b/lib/irb/cmd/fork.rb
index 2866b1373b..30024dc5e0 100644
--- a/lib/irb/cmd/fork.rb
+++ b/lib/irb/cmd/fork.rb
@@ -1,23 +1,9 @@
-#
-# fork.rb -
-# $Release Version: 0.9.5 $
-# $Revision$
-# $Date$
-# by Keiju ISHITSUKA(keiju@ruby-lang.org)
-#
-# --
-#
-#
-#
-
-@RCS_ID='-$Id$-'
-
module IRB
module ExtendCommand
class Fork<Nop
def execute(&block)
- pid = send ExtendCommand.irb_original_method_name("fork")
+ pid = send(ExtendCommand.irb_original_method_name("fork"))
unless pid
class<<self
alias_method :exit, ExtendCommand.irb_original_method_name('exit')
diff --git a/lib/irb/cmd/help.rb b/lib/irb/cmd/help.rb
deleted file mode 100644
index 3e8d1388e0..0000000000
--- a/lib/irb/cmd/help.rb
+++ /dev/null
@@ -1,34 +0,0 @@
-#
-# help.rb - helper using ri
-# $Release Version: 0.9.5$
-# $Revision$
-# $Date$
-#
-# --
-#
-#
-#
-
-require 'rdoc/ri/ri_driver'
-
-module IRB
- module ExtendCommand
- module Help
- begin
- @ri = RiDriver.new
- rescue SystemExit
- else
- def self.execute(context, *names)
- names.each do |name|
- begin
- @ri.get_info_for(name.to_s)
- rescue RiError
- puts $!.message
- end
- end
- nil
- end
- end
- end
- end
-end
diff --git a/lib/irb/cmd/load.rb b/lib/irb/cmd/load.rb
index cbc5d91d03..99d20f500c 100644
--- a/lib/irb/cmd/load.rb
+++ b/lib/irb/cmd/load.rb
@@ -1,9 +1,9 @@
#
# load.rb -
-# $Release Version: 0.9.5$
+# $Release Version: 0.9$
# $Revision$
# $Date$
-# by Keiju ISHITSUKA(keiju@ruby-lang.org)
+# by Keiju ISHITSUKA(Nihon Rational Software Co.,Ltd)
#
# --
#
diff --git a/lib/irb/cmd/nop.rb b/lib/irb/cmd/nop.rb
index aa553c959e..73c52b1aa3 100644
--- a/lib/irb/cmd/nop.rb
+++ b/lib/irb/cmd/nop.rb
@@ -1,9 +1,9 @@
#
# nop.rb -
-# $Release Version: 0.9.5$
+# $Release Version: 0.9$
# $Revision$
# $Date$
-# by Keiju ISHITSUKA(keiju@ruby-lang.org)
+# by Keiju ISHITSUKA(Nihon Rational Software Co.,Ltd)
#
# --
#
diff --git a/lib/irb/cmd/pushws.rb b/lib/irb/cmd/pushws.rb
index eddaeae631..0d8130d5c6 100644
--- a/lib/irb/cmd/pushws.rb
+++ b/lib/irb/cmd/pushws.rb
@@ -1,9 +1,9 @@
#
# change-ws.rb -
-# $Release Version: 0.9.5$
+# $Release Version: 0.9$
# $Revision$
# $Date$
-# by Keiju ISHITSUKA(keiju@ruby-lang.org)
+# by Keiju ISHITSUKA(Nihon Rational Software Co.,Ltd)
#
# --
#
diff --git a/lib/irb/cmd/subirb.rb b/lib/irb/cmd/subirb.rb
index 79d654b172..7899f1bb43 100644
--- a/lib/irb/cmd/subirb.rb
+++ b/lib/irb/cmd/subirb.rb
@@ -1,10 +1,10 @@
#!/usr/local/bin/ruby
#
# multi.rb -
-# $Release Version: 0.9.5$
+# $Release Version: 0.9$
# $Revision$
# $Date$
-# by Keiju ISHITSUKA(keiju@ruby-lang.org)
+# by Keiju ISHITSUKA(Nihon Rational Software Co.,Ltd)
#
# --
#
diff --git a/lib/irb/context.rb b/lib/irb/context.rb
index d01bd4aefa..9421608f85 100644
--- a/lib/irb/context.rb
+++ b/lib/irb/context.rb
@@ -1,9 +1,9 @@
#
# irb/context.rb - irb context
-# $Release Version: 0.9.5$
+# $Release Version: 0.9$
# $Revision$
# $Date$
-# by Keiju ISHITSUKA(keiju@ruby-lang.org)
+# by Keiju ISHITSUKA(keiju@ishitsuka.com)
#
# --
#
@@ -19,7 +19,7 @@ module IRB
# String -- File
# other -- using this as InputMethod
#
- def initialize(irb, workspace = nil, input_method = nil, output_method = nil)
+ def initialize(irb, workspace = nil, input_method = nil)
@irb = irb
if workspace
@workspace = workspace
@@ -38,7 +38,7 @@ module IRB
@inspect_mode = IRB.conf[:INSPECT_MODE]
self.math_mode = IRB.conf[:MATH_MODE] if IRB.conf[:MATH_MODE]
- self.use_tracer = IRB.conf[:USE_TRACER] if IRB.conf[:USE_TRACER]
+ self.use_tracer = IRB.conf[:USE_TRACER] if IRB.conf[:USE_TRASER]
self.use_loader = IRB.conf[:USE_LOADER] if IRB.conf[:USE_LOADER]
self.eval_history = IRB.conf[:EVAL_HISTORY] if IRB.conf[:EVAL_HISTORY]
@@ -58,24 +58,12 @@ module IRB
case input_method
when nil
- case use_readline?
- when nil
- if (defined?(ReadlineInputMethod) && STDIN.tty? &&
- IRB.conf[:PROMPT_MODE] != :INF_RUBY)
- @io = ReadlineInputMethod.new
- else
- @io = StdioInputMethod.new
- end
- when false
+ if (defined?(ReadlineInputMethod) &&
+ (use_readline? || IRB.conf[:PROMPT_MODE] != :INF_RUBY && STDIN.tty?))
+ @io = ReadlineInputMethod.new
+ else
@io = StdioInputMethod.new
- when true
- if defined?(ReadlineInputMethod)
- @io = ReadlineInputMethod.new
- else
- @io = StdioInputMethod.new
- end
end
-
when String
@io = FileInputMethod.new(input_method)
@irb_name = File.basename(input_method)
@@ -83,13 +71,6 @@ module IRB
else
@io = input_method
end
- self.save_history = IRB.conf[:SAVE_HISTORY] if IRB.conf[:SAVE_HISTORY]
-
- if output_method
- @output_method = output_method
- else
- @output_method = StdioOutputMethod.new
- end
@verbose = IRB.conf[:VERBOSE]
@echo = IRB.conf[:ECHO]
@@ -115,14 +96,13 @@ module IRB
attr_accessor :irb_name
attr_accessor :irb_path
- attr_reader :use_readline
+ attr_accessor :use_readline
attr_reader :inspect_mode
attr_reader :prompt_mode
attr_accessor :prompt_i
attr_accessor :prompt_s
attr_accessor :prompt_c
- attr_accessor :prompt_n
attr_accessor :auto_indent_mode
attr_accessor :return_format
@@ -161,7 +141,6 @@ module IRB
def set_last_value(value)
@last_value = value
- @workspace.evaluate self, "_ = IRB.CurrentContext.last_value"
end
attr_reader :irb_name
@@ -172,7 +151,6 @@ module IRB
@prompt_i = pconf[:PROMPT_I]
@prompt_s = pconf[:PROMPT_S]
@prompt_c = pconf[:PROMPT_C]
- @prompt_n = pconf[:PROMPT_N]
@return_format = pconf[:RETURN]
if ai = pconf.include?(:AUTO_INDENT)
@auto_indent_mode = ai
@@ -199,6 +177,7 @@ module IRB
@inspect_mode
end
+ undef use_readline=
def use_readline=(opt)
@use_readline = opt
print "use readline module\n" if @use_readline
diff --git a/lib/irb/ext/change-ws.rb b/lib/irb/ext/change-ws.rb
index fff8f58fe5..f15391e202 100644
--- a/lib/irb/ext/change-ws.rb
+++ b/lib/irb/ext/change-ws.rb
@@ -1,9 +1,9 @@
#
# irb/ext/cb.rb -
-# $Release Version: 0.9.5$
+# $Release Version: 0.9$
# $Revision$
# $Date$
-# by Keiju ISHITSUKA(keiju@ruby-lang.org)
+# by Keiju ISHITSUKA(Nihon Rational Software Co.,Ltd)
#
# --
#
diff --git a/lib/irb/ext/history.rb b/lib/irb/ext/history.rb
index 40f8692e8b..d40a62e959 100644
--- a/lib/irb/ext/history.rb
+++ b/lib/irb/ext/history.rb
@@ -1,9 +1,9 @@
#
# history.rb -
-# $Release Version: 0.9.5$
+# $Release Version: 0.9$
# $Revision$
# $Date$
-# by Keiju ISHITSUKA(keiju@ruby-lang.org)
+# by Keiju ISHITSUKA(Nihon Rational Software Co.,Ltd)
#
# --
#
@@ -21,7 +21,7 @@ module IRB
def set_last_value(value)
_set_last_value(value)
-# @workspace.evaluate self, "_ = IRB.CurrentContext.last_value"
+ @workspace.evaluate self, "_ = IRB.CurrentContext.last_value"
if @eval_history #and !@eval_history_values.equal?(llv)
@eval_history_values.push @line_no, @last_value
@workspace.evaluate self, "__ = IRB.CurrentContext.instance_eval{@eval_history_values}"
@@ -33,7 +33,7 @@ module IRB
attr_reader :eval_history
def eval_history=(no)
if no
- if defined?(@eval_history) && @eval_history
+ if @eval_history
@eval_history_values.size(no)
else
@eval_history_values = History.new(no)
diff --git a/lib/irb/ext/loader.rb b/lib/irb/ext/loader.rb
index 837e2553ac..26e36e1209 100644
--- a/lib/irb/ext/loader.rb
+++ b/lib/irb/ext/loader.rb
@@ -1,22 +1,8 @@
-#
-# loader.rb -
-# $Release Version: 0.9.5$
-# $Revision$
-# $Date$
-# by Keiju ISHITSUKA(keiju@ruby-lang.org)
-#
-# --
-#
-#
-#
-
-
module IRB
class LoadAbort < Exception;end
module IrbLoader
@RCS_ID='-$Id$-'
-
alias ruby_load load
alias ruby_require require
diff --git a/lib/irb/ext/math-mode.rb b/lib/irb/ext/math-mode.rb
index bd443b96ed..5e268bb3e5 100644
--- a/lib/irb/ext/math-mode.rb
+++ b/lib/irb/ext/math-mode.rb
@@ -1,9 +1,9 @@
#
# math-mode.rb -
-# $Release Version: 0.9.5$
+# $Release Version: 0.9$
# $Revision$
# $Date$
-# by Keiju ISHITSUKA(keiju@ruby-lang.org)
+# by Keiju ISHITSUKA(Nihon Rational Software Co.,Ltd)
#
# --
#
diff --git a/lib/irb/ext/multi-irb.rb b/lib/irb/ext/multi-irb.rb
index 4589b1d554..e815889383 100644
--- a/lib/irb/ext/multi-irb.rb
+++ b/lib/irb/ext/multi-irb.rb
@@ -1,9 +1,9 @@
#
# irb/multi-irb.rb - multiple irb module
-# $Release Version: 0.9.5$
+# $Release Version: 0.9$
# $Revision$
# $Date$
-# by Keiju ISHITSUKA(keiju@ruby-lang.org)
+# by Keiju ISHITSUKA(keiju@ishitsuka.com)
#
# --
#
diff --git a/lib/irb/ext/save-history.rb b/lib/irb/ext/save-history.rb
deleted file mode 100644
index 5260bfcdd8..0000000000
--- a/lib/irb/ext/save-history.rb
+++ /dev/null
@@ -1,85 +0,0 @@
-#!/usr/local/bin/ruby
-#
-# save-history.rb -
-# $Release Version: 0.9.5$
-# $Revision$
-# $Date$
-# by Keiju ISHITSUKAkeiju@ruby-lang.org)
-#
-# --
-#
-#
-#
-
-require "readline"
-
-module IRB
- module HistorySavingAbility
- @RCS_ID='-$Id$-'
- end
-
- class Context
- def init_save_history
- unless (class<<@io;self;end).include?(HistorySavingAbility)
- @io.extend(HistorySavingAbility)
- end
- end
-
- def save_history
- IRB.conf[:SAVE_HISTORY]
- end
-
- def save_history=(val)
- IRB.conf[:SAVE_HISTORY] = val
- if val
- main_context = IRB.conf[:MAIN_CONTEXT]
- main_context = self unless main_context
- main_context.init_save_history
- end
- end
-
- def history_file
- IRB.conf[:HISTORY_FILE]
- end
-
- def history_file=(hist)
- IRB.conf[:HISTORY_FILE] = hist
- end
- end
-
- module HistorySavingAbility
- include Readline
-
- def HistorySavingAbility.create_finalizer
- proc do
- if num = IRB.conf[:SAVE_HISTORY] and (num = num.to_i) > 0
- if hf = IRB.conf[:HISTORY_FILE]
- file = File.expand_path(hf)
- end
- file = IRB.rc_file("_history") unless file
- open(file, 'w' ) do |f|
- hist = HISTORY.to_a
- f.puts(hist[-num..-1] || hist)
- end
- end
- end
- end
-
- def HistorySavingAbility.extended(obj)
- ObjectSpace.define_finalizer(obj, HistorySavingAbility.create_finalizer)
- obj.load_history
- obj
- end
-
- def load_history
- hist = IRB.conf[:HISTORY_FILE]
- hist = IRB.rc_file("_history") unless hist
- if File.exist?(hist)
- open(hist) do |f|
- f.each {|l| HISTORY << l.chomp}
- end
- end
- end
- end
-end
-
diff --git a/lib/irb/ext/tracer.rb b/lib/irb/ext/tracer.rb
index 805f630a4d..b2528f74b2 100644
--- a/lib/irb/ext/tracer.rb
+++ b/lib/irb/ext/tracer.rb
@@ -1,9 +1,9 @@
#
# irb/lib/tracer.rb -
-# $Release Version: 0.9.5$
+# $Release Version: 0.9$
# $Revision$
# $Date$
-# by Keiju ISHITSUKA(keiju@ruby-lang.org)
+# by Keiju ISHITSUKA(Nihon Rational Software Co.,Ltd)
#
# --
#
diff --git a/lib/irb/ext/use-loader.rb b/lib/irb/ext/use-loader.rb
index 1b4d480fcd..a81b3aca7b 100644
--- a/lib/irb/ext/use-loader.rb
+++ b/lib/irb/ext/use-loader.rb
@@ -1,9 +1,9 @@
#
# use-loader.rb -
-# $Release Version: 0.9.5$
+# $Release Version: 0.9$
# $Revision$
# $Date$
-# by Keiju ISHITSUKA(keiju@ruby-lang.org)
+# by Keiju ISHITSUKA(Nihon Rational Software Co.,Ltd)
#
# --
#
diff --git a/lib/irb/ext/workspaces.rb b/lib/irb/ext/workspaces.rb
index 79098570dc..2fe8f8a87b 100644
--- a/lib/irb/ext/workspaces.rb
+++ b/lib/irb/ext/workspaces.rb
@@ -1,9 +1,9 @@
#
# push-ws.rb -
-# $Release Version: 0.9.5$
+# $Release Version: 0.9$
# $Revision$
# $Date$
-# by Keiju ISHITSUKA(keiju@ruby-lang.org)
+# by Keiju ISHITSUKA(Nihon Rational Software Co.,Ltd)
#
# --
#
diff --git a/lib/irb/extend-command.rb b/lib/irb/extend-command.rb
index c330d1bd3b..cfb2c7c4be 100644
--- a/lib/irb/extend-command.rb
+++ b/lib/irb/extend-command.rb
@@ -1,9 +1,9 @@
#
-# irb/extend-command.rb - irb extend command
-# $Release Version: 0.9.5$
+# irb/extend-command.rb - irb command extend
+# $Release Version: 0.9$
# $Revision$
# $Date$
-# by Keiju ISHITSUKA(keiju@ruby-lang.org)
+# by Keiju ISHITSUKA(keiju@ishitsuka.com)
#
# --
#
@@ -100,10 +100,6 @@ module IRB
[:fg, NO_OVERRIDE]],
[:irb_kill, :Kill, "irb/cmd/subirb",
[:kill, OVERRIDE_PRIVATE_ONLY]],
-
- [:irb_help, :Help, "irb/cmd/help",
- [:help, NO_OVERRIDE]],
-
]
def EXCB.install_extend_commands
@@ -193,7 +189,6 @@ module IRB
[:use_tracer=, "irb/ext/tracer.rb"],
[:math_mode=, "irb/ext/math-mode.rb"],
[:use_loader=, "irb/ext/use-loader.rb"],
- [:save_history=, "irb/ext/save-history.rb"],
]
def CE.install_extend_commands
@@ -205,7 +200,6 @@ module IRB
def CE.def_extend_command(cmd_name, load_file, *aliases)
Context.module_eval %[
def #{cmd_name}(*opts, &b)
- Context.module_eval {remove_method(:#{cmd_name})}
require "#{load_file}"
send :#{cmd_name}, *opts, &b
end
@@ -217,48 +211,5 @@ module IRB
CE.install_extend_commands
end
-
- module MethodExtender
- def def_pre_proc(base_method, extend_method)
- base_method = base_method.to_s
- extend_method = extend_method.to_s
-
- alias_name = new_alias_name(base_method)
- module_eval %[
- alias_method alias_name, base_method
- def #{base_method}(*opts)
- send :#{extend_method}, *opts
- send :#{alias_name}, *opts
- end
- ]
- end
-
- def def_post_proc(base_method, extend_method)
- base_method = base_method.to_s
- extend_method = extend_method.to_s
-
- alias_name = new_alias_name(base_method)
- module_eval %[
- alias_method alias_name, base_method
- def #{base_method}(*opts)
- send :#{alias_name}, *opts
- send :#{extend_method}, *opts
- end
- ]
- end
-
- # return #{prefix}#{name}#{postfix}<num>
- def new_alias_name(name, prefix = "__alias_of__", postfix = "__")
- base_name = "#{prefix}#{name}#{postfix}"
- all_methods = instance_methods(true) + private_instance_methods(true)
- same_methods = all_methods.grep(/^#{Regexp.quote(base_name)}[0-9]*$/)
- return base_name if same_methods.empty?
- no = same_methods.size
- while !same_methods.include?(alias_name = base_name + no)
- no += 1
- end
- alias_name
- end
- end
end
diff --git a/lib/irb/help.rb b/lib/irb/help.rb
index f091999bd1..eb876a6dbe 100644
--- a/lib/irb/help.rb
+++ b/lib/irb/help.rb
@@ -1,6 +1,6 @@
#
# irb/help.rb - print usase module
-# $Release Version: 0.9.5$
+# $Release Version: 0.9$
# $Revision$
# $Date$
# by Keiju ISHITSUKA(keiju@ishitsuka.com)
diff --git a/lib/irb/init.rb b/lib/irb/init.rb
index 842eb1221e..37cdb313e6 100644
--- a/lib/irb/init.rb
+++ b/lib/irb/init.rb
@@ -1,9 +1,9 @@
#
# irb/init.rb - irb initialize module
-# $Release Version: 0.9.5$
+# $Release Version: 0.9$
# $Revision$
# $Date$
-# by Keiju ISHITSUKA(keiju@ruby-lang.org)
+# by Keiju ISHITSUKA(keiju@ishitsuka.com)
#
# --
#
@@ -54,43 +54,36 @@ module IRB
@CONF[:VERBOSE] = nil
@CONF[:EVAL_HISTORY] = nil
- @CONF[:SAVE_HISTORY] = nil
@CONF[:BACK_TRACE_LIMIT] = 16
@CONF[:PROMPT] = {
:NULL => {
:PROMPT_I => nil,
- :PROMPT_N => nil,
:PROMPT_S => nil,
:PROMPT_C => nil,
:RETURN => "%s\n"
},
:DEFAULT => {
:PROMPT_I => "%N(%m):%03n:%i> ",
- :PROMPT_N => "%N(%m):%03n:%i> ",
:PROMPT_S => "%N(%m):%03n:%i%l ",
:PROMPT_C => "%N(%m):%03n:%i* ",
:RETURN => "=> %s\n"
},
:CLASSIC => {
:PROMPT_I => "%N(%m):%03n:%i> ",
- :PROMPT_N => "%N(%m):%03n:%i> ",
:PROMPT_S => "%N(%m):%03n:%i%l ",
:PROMPT_C => "%N(%m):%03n:%i* ",
:RETURN => "%s\n"
},
:SIMPLE => {
:PROMPT_I => ">> ",
- :PROMPT_N => ">> ",
:PROMPT_S => nil,
:PROMPT_C => "?> ",
:RETURN => "=> %s\n"
},
:INF_RUBY => {
:PROMPT_I => "%N(%m):%03n:%i> ",
-# :PROMPT_N => "%N(%m):%03n:%i> ",
- :PROMPT_N => nil,
:PROMPT_S => nil,
:PROMPT_C => nil,
:RETURN => "%s\n",
@@ -98,14 +91,13 @@ module IRB
},
:XMP => {
:PROMPT_I => nil,
- :PROMPT_N => nil,
:PROMPT_S => nil,
:PROMPT_C => nil,
:RETURN => " ==>%s\n"
}
}
- @CONF[:PROMPT_MODE] = (STDIN.tty? ? :DEFAULT : :NULL)
+ @CONF[:PROMPT_MODE] = :DEFAULT
@CONF[:AUTO_INDENT] = false
@CONF[:CONTEXT_MODE] = 3 # use binding in function on TOPLEVEL_BINDING
@@ -121,11 +113,8 @@ module IRB
@CONF[:LC_MESSAGES].load("irb/error.rb")
end
- FEATURE_IOPT_CHANGE_VERSION = "1.9.0"
-
# option analyzing
def IRB.parse_opts
- load_path = []
while opt = ARGV.shift
case opt
when "-f"
@@ -134,12 +123,12 @@ module IRB
@CONF[:MATH_MODE] = true
when "-d"
$DEBUG = true
- when /^-r(.+)?/
- opt = $1 || ARGV.shift
+ when "-r"
+ opt = ARGV.shift
@CONF[:LOAD_MODULES].push opt if opt
- when /^-I(.+)?/
- opt = $1 || ARGV.shift
- load_path.concat(opt.split(File::PATH_SEPARATOR)) if opt
+ when "-I"
+ opt = ARGV.shift
+ $LOAD_PATH.push opt if opt
when /^-K(.)/
$KCODE = $1
when "--inspect"
@@ -192,57 +181,34 @@ module IRB
break
end
end
- if RUBY_VERSION >= FEATURE_IOPT_CHANGE_VERSION
- load_path.collect! do |path|
- /\A\.\// =~ path ? path : File.expand_path(path)
- end
- end
- $LOAD_PATH.unshift(*load_path)
end
# running config
def IRB.run_config
if @CONF[:RC]
- begin
- load rc_file
- rescue LoadError, Errno::ENOENT
- rescue
- print "load error: #{rc_file}\n"
- print $!.class, ": ", $!, "\n"
- for err in $@[0, $@.size - 2]
- print "\t", err, "\n"
- end
- end
- end
- end
-
- IRBRC_EXT = "rc"
- def IRB.rc_file(ext = IRBRC_EXT)
- if !@CONF[:RC_NAME_GENERATOR]
- rc_file_generators do |rcgen|
- @CONF[:RC_NAME_GENERATOR] ||= rcgen
- if File.exist?(rcgen.call(IRBRC_EXT))
- @CONF[:RC_NAME_GENERATOR] = rcgen
- break
+ rcs = []
+ rcs.push File.expand_path("~/.irbrc") if ENV.key?("HOME")
+ rcs.push ".irbrc"
+ rcs.push "irb.rc"
+ rcs.push "_irbrc"
+ rcs.push "$irbrc"
+ catch(:EXIT) do
+ for rc in rcs
+ begin
+ load rc
+ throw :EXIT
+ rescue LoadError, Errno::ENOENT
+ rescue
+ print "load error: #{rc}\n"
+ print $!.class, ": ", $!, "\n"
+ for err in $@[0, $@.size - 2]
+ print "\t", err, "\n"
+ end
+ throw :EXIT
+ end
end
end
end
- @CONF[:RC_NAME_GENERATOR].call ext
- end
-
- # enumerate possible rc-file base name generators
- def IRB.rc_file_generators
- if irbrc = ENV["IRBRC"]
- yield proc{|rc| irbrc}
- end
- if home = ENV["HOME"]
- yield proc{|rc| home+"/.irb#{rc}"}
- end
- home = Dir.pwd
- yield proc{|rc| home+"/.irb#{rc}"}
- yield proc{|rc| home+"/irb#{rc.sub(/\A_?/, '.')}"}
- yield proc{|rc| home+"/_irb#{rc}"}
- yield proc{|rc| home+"/$irb#{rc}"}
end
# loading modules
diff --git a/lib/irb/input-method.rb b/lib/irb/input-method.rb
index bfb90fa59a..ec834b17bc 100644
--- a/lib/irb/input-method.rb
+++ b/lib/irb/input-method.rb
@@ -1,9 +1,9 @@
#
-# irb/input-method.rb - input methods used irb
-# $Release Version: 0.9.5$
+# irb/input-method.rb - input methods using irb
+# $Release Version: 0.9$
# $Revision$
# $Date$
-# by Keiju ISHITSUKA(keiju@ruby-lang.org)
+# by Keiju ISHITSUKA(keiju@ishitsuka.com)
#
# --
#
@@ -94,8 +94,8 @@ module IRB
end
def gets
- if l = readline(@prompt, false)
- HISTORY.push(l) if !l.empty?
+ if l = readline(@prompt, true)
+ HISTORY.pop if l.empty?
@line[@line_no += 1] = l + "\n"
else
@eof = true
diff --git a/lib/irb/lc/error.rb b/lib/irb/lc/error.rb
index 247596b7fe..68a488a48a 100644
--- a/lib/irb/lc/error.rb
+++ b/lib/irb/lc/error.rb
@@ -1,9 +1,9 @@
#
# irb/lc/error.rb -
-# $Release Version: 0.9.5$
+# $Release Version: 0.9$
# $Revision$
# $Date$
-# by Keiju ISHITSUKA(keiju@ruby-lang.org)
+# by Keiju ISHITSUKA(keiju@ishitsuka.com)
#
# --
#
diff --git a/lib/irb/lc/help-message b/lib/irb/lc/help-message
index 32087d113c..efc00bf148 100644
--- a/lib/irb/lc/help-message
+++ b/lib/irb/lc/help-message
@@ -1,9 +1,9 @@
#
# irb/lc/help-message.rb -
-# $Release Version: 0.9.5$
+# $Release Version: 0.9$
# $Revision$
# $Date$
-# by Keiju ISHITSUKA(keiju@ruby-lang.org)
+# by Keiju ISHITSUKA(keiju@ishitsuka.com)
#
# --
#
diff --git a/lib/irb/lc/ja/error.rb b/lib/irb/lc/ja/error.rb
index 4c2fb3b839..e1afaf5d71 100644
--- a/lib/irb/lc/ja/error.rb
+++ b/lib/irb/lc/ja/error.rb
@@ -1,9 +1,9 @@
#
# irb/lc/ja/error.rb -
-# $Release Version: 0.9.5$
+# $Release Version: 0.9$
# $Revision$
# $Date$
-# by Keiju ISHITSUKA(keiju@ruby-lang.org)
+# by Keiju ISHITSUKA(keiju@ishitsuka.com)
#
# --
#
@@ -25,3 +25,5 @@ module IRB
def_exception :CantChangeBinding, '$B%P%$%s%G%#%s%0(B(%s)$B$KJQ99$G$-$^$;$s(B.'
def_exception :UndefinedPromptMode, '$B%W%m%s%W%H%b!<%I(B(%s)$B$ODj5A$5$l$F$$$^$;$s(B.'
end
+
+
diff --git a/lib/irb/lc/ja/help-message b/lib/irb/lc/ja/help-message
index debbfe9355..4b710c7788 100644
--- a/lib/irb/lc/ja/help-message
+++ b/lib/irb/lc/ja/help-message
@@ -1,9 +1,9 @@
#
# irb/lc/ja/help-message.rb -
-# $Release Version: 0.9.5$
+# $Release Version: 0.9$
# $Revision$
# $Date$
-# by Keiju ISHITSUKA(keiju@ruby-lang.org)
+# by Keiju ISHITSUKA(keiju@ishitsuka.com)
#
# --
#
diff --git a/lib/irb/locale.rb b/lib/irb/locale.rb
index 4b6aba2bb9..b2c90e38e2 100644
--- a/lib/irb/locale.rb
+++ b/lib/irb/locale.rb
@@ -1,15 +1,16 @@
#
# irb/locale.rb - internationalization module
-# $Release Version: 0.9.5$
+# $Release Version: 0.9$
# $Revision$
# $Date$
-# by Keiju ISHITSUKA(keiju@ruby-lang.org)
+# by Keiju ISHITSUKA(keiju@ishitsuka.com)
#
# --
#
#
#
+autoload :Tempfile, "tempfile"
autoload :Kconv, "kconv"
module IRB
@@ -31,8 +32,6 @@ module IRB
Kconv::EUC
when "ja_JP.sjis", "ja_JP.SJIS"
Kconv::SJIS
- when /ja_JP.utf-?8/i
- Kconv::UTF8
end
end
private :lc2kconv
@@ -127,12 +126,15 @@ module IRB
end
def real_load(path, priv)
- src = self.String(File.read(path))
- if priv
- eval("self", TOPLEVEL_BINDING).extend(Module.new {eval(src, nil, path)})
- else
- eval(src, TOPLEVEL_BINDING, path)
+ tmp_base = path.tr("./:", "___")
+ lc_file = Tempfile.new(tmp_base)
+ File.foreach(path) do |line|
+ line = self.String(line)
+ lc_file.print(line)
end
+ lc_file.close
+ toplevel_load lc_file.path, priv
+ lc_file.close(true)
end
private :real_load
diff --git a/lib/irb/notifier.rb b/lib/irb/notifier.rb
deleted file mode 100644
index c8e66fa859..0000000000
--- a/lib/irb/notifier.rb
+++ /dev/null
@@ -1,145 +0,0 @@
-#
-# notifier.rb - optput methods used by irb
-# $Release Version: 0.9.5$
-# $Revision$
-# $Date$
-# by Keiju ISHITSUKA(keiju@ruby-lang.org)
-#
-# --
-#
-#
-#
-
-require "e2mmap"
-require "irb/output-method"
-
-module IRB
- module Notifier
- extend Exception2MessageMapper
- def_exception :ErrUndefinedNotifier,
- "undefined notifier level: %d is specified"
- def_exception :ErrUnrecognizedLevel,
- "unrecognized notifier level: %s is specified"
-
- def def_notifier(prefix = "", output_method = StdioOutputMethod.new)
- CompositeNotifier.new(prefix, output_method)
- end
- module_function :def_notifier
-
- class AbstructNotifier
- def initialize(prefix, base_notifier)
- @prefix = prefix
- @base_notifier = base_notifier
- end
-
- attr_reader :prefix
-
- def notify?
- true
- end
-
- def print(*opts)
- @base_notifier.print prefix, *opts if notify?
- end
-
- def printn(*opts)
- @base_notifier.printn prefix, *opts if notify?
- end
-
- def printf(format, *opts)
- @base_notifier.printf(prefix + format, *opts) if notify?
- end
-
- def puts(*objs)
- if notify?
- @base_notifier.puts(*objs.collect{|obj| prefix + obj.to_s})
- end
- end
-
- def pp(*objs)
- if notify?
- @base_notifier.ppx @prefix, *objs
- end
- end
-
- def ppx(prefix, *objs)
- if notify?
- @base_notifier.ppx @prefix+prefix, *objs
- end
- end
-
- def exec_if
- yield(@base_notifier) if notify?
- end
- end
-
- class CompositeNotifier<AbstructNotifier
- def initialize(prefix, base_notifier)
- super
-
- @notifiers = [D_NOMSG]
- @level_notifier = D_NOMSG
- end
-
- attr_reader :notifiers
-
- def def_notifier(level, prefix = "")
- notifier = LeveledNotifier.new(self, level, prefix)
- @notifiers[level] = notifier
- notifier
- end
-
- attr_reader :level_notifier
- alias level level_notifier
-
- def level_notifier=(value)
- case value
- when AbstructNotifier
- @level_notifier = value
- when Integer
- l = @notifiers[value]
- Notifier.Raise ErrUndefinedNotifer, value unless l
- @level_notifier = l
- else
- Notifier.Raise ErrUnrecognizedLevel, value unless l
- end
- end
-
- alias level= level_notifier=
- end
-
- class LeveledNotifier<AbstructNotifier
- include Comparable
-
- def initialize(base, level, prefix)
- super(prefix, base)
-
- @level = level
- end
-
- attr_reader :level
-
- def <=>(other)
- @level <=> other.level
- end
-
- def notify?
- @base_notifier.level >= self
- end
- end
-
- class NoMsgNotifier<LeveledNotifier
- def initialize
- @base_notifier = nil
- @level = 0
- @prefix = ""
- end
-
- def notify?
- false
- end
- end
-
- D_NOMSG = NoMsgNotifier.new
- end
-end
diff --git a/lib/irb/output-method.rb b/lib/irb/output-method.rb
deleted file mode 100644
index b9a3a8851e..0000000000
--- a/lib/irb/output-method.rb
+++ /dev/null
@@ -1,85 +0,0 @@
-#
-# output-method.rb - optput methods used by irb
-# $Release Version: 0.9.5$
-# $Revision$
-# $Date$
-# by Keiju ISHITSUKA(keiju@ruby-lang.org)
-#
-# --
-#
-#
-#
-
-require "e2mmap"
-
-module IRB
- # OutputMethod
- # StdioOutputMethod
-
- class OutputMethod
- @RCS_ID='-$Id$-'
-
- def print(*opts)
- IRB.fail NotImplementError, "print"
- end
-
- def printn(*opts)
- print opts.join(" "), "\n"
- end
-
- # extend printf
- def printf(format, *opts)
- if /(%*)%I/ =~ format
- format, opts = parse_printf_format(format, opts)
- end
- print sprintf(format, *opts)
- end
-
- # %
- # <¥Õ¥é¥°> [#0- +]
- # <ºÇ¾®¥Õ¥£¡¼¥ë¥ÉÉý> (\*|\*[1-9][0-9]*\$|[1-9][0-9]*)
- # <ÀºÅÙ>.(\*|\*[1-9][0-9]*\$|[1-9][0-9]*|)?
- # #<Ťµ½¤ÀµÊ¸»ú>(hh|h|l|ll|L|q|j|z|t)
- # <ÊÑ´¹½¤ÀµÊ¸»ú>[diouxXeEfgGcsb%]
- def parse_printf_format(format, opts)
- return format, opts if $1.size % 2 == 1
- end
-
- def foo(format)
- pos = 0
- inspects = []
- format.scan(/%[#0\-+ ]?(\*(?=[^0-9])|\*[1-9][0-9]*\$|[1-9][0-9]*(?=[^0-9]))?(\.(\*(?=[^0-9])|\*[1-9][0-9]*\$|[1-9][0-9]*(?=[^0-9])))?(([1-9][0-9]*\$)*)([diouxXeEfgGcsb%])/) {|f, p, pp, pos, new_pos, c|
- puts [f, p, pp, pos, new_pos, c].join("!")
- pos = new_pos if new_pos
- if c == "I"
- inspects.push pos.to_i
- (f||"")+(p||"")+(pp||"")+(pos||"")+"s"
- else
- $&
- end
- }
- end
-
- def puts(*objs)
- for obj in objs
- print(*obj)
- print "\n"
- end
- end
-
- def pp(*objs)
- puts(*objs.collect{|obj| obj.inspect})
- end
-
- def ppx(prefix, *objs)
- puts(*objs.collect{|obj| prefix+obj.inspect})
- end
-
- end
-
- class StdioOutputMethod<OutputMethod
- def print(*opts)
- STDOUT.print(*opts)
- end
- end
-end
diff --git a/lib/irb/ruby-lex.rb b/lib/irb/ruby-lex.rb
index 4bfa5f2001..e25af30546 100644
--- a/lib/irb/ruby-lex.rb
+++ b/lib/irb/ruby-lex.rb
@@ -1,9 +1,9 @@
#
# irb/ruby-lex.rb - ruby lexcal analizer
-# $Release Version: 0.9.5$
+# $Release Version: 0.9$
# $Revision$
# $Date$
-# by Keiju ISHITSUKA(keiju@ruby-lang.org)
+# by Keiju ISHITSUKA(keiju@ishitsuka.com)
#
# --
#
@@ -51,18 +51,13 @@ class RubyLex
@indent = 0
@indent_stack = []
- @lex_state = EXPR_BEG
- @space_seen = false
- @here_header = false
-
- @continue = false
- @line = ""
@skip_space = false
@readed_auto_clean_up = false
@exception_on_syntax_error = true
-
@prompt = nil
+ @here_header = nil
+ @lex_state = nil
end
attr_accessor :skip_space
@@ -100,8 +95,7 @@ class RubyLex
def getc
while @rests.empty?
-# return nil unless buf_input
- @rests.push nil unless buf_input
+ return nil unless buf_input
end
c = @rests.shift
if @here_header
@@ -122,10 +116,9 @@ class RubyLex
def gets
l = ""
while c = getc
- l.concat(c)
+ l.concat c
break if c == "\n"
end
- return nil if l == "" and c.nil?
l
end
@@ -193,7 +186,7 @@ class RubyLex
end
private :buf_input
- def set_prompt(p = nil, &block)
+ def set_prompt(p=nil, &block)
p = block if block_given?
if p.respond_to?(:call)
@prompt = p
@@ -287,7 +280,7 @@ class RubyLex
tk = @OP.match(self)
@space_seen = tk.kind_of?(TkSPACE)
rescue SyntaxError
- raise if @exception_on_syntax_error
+ abort if @exception_on_syntax_error
tk = TkError.new(@seek, @line_no, @char_no)
end
end while @skip_space and tk.kind_of?(TkSPACE)
@@ -337,7 +330,7 @@ class RubyLex
}
def lex_init()
- @OP = IRB::SLex.new
+ @OP = SLex.new
@OP.def_rules("\0", "\004", "\032") do
Token(TkEND_OF_SCRIPT)
end
@@ -436,7 +429,6 @@ class RubyLex
@OP.def_rules("`") do
|op, io|
if @lex_state == EXPR_FNAME
- @lex_state = EXPR_END
Token(op)
else
identify_string(op)
@@ -480,13 +472,11 @@ class RubyLex
@OP.def_rule("+@", proc{@lex_state == EXPR_FNAME}) do
|op, io|
- @lex_state = EXPR_ARG
Token(op)
end
@OP.def_rule("-@", proc{@lex_state == EXPR_FNAME}) do
|op, io|
- @lex_state = EXPR_ARG
Token(op)
end
@@ -626,12 +616,10 @@ class RubyLex
end
@OP.def_rule("[]", proc{@lex_state == EXPR_FNAME}) do
- @lex_state = EXPR_ARG
Token("[]")
end
@OP.def_rule("[]=", proc{@lex_state == EXPR_FNAME}) do
- @lex_state = EXPR_ARG
Token("[]=")
end
@@ -802,13 +790,14 @@ class RubyLex
else
if @lex_state != EXPR_FNAME
if ENINDENT_CLAUSE.include?(token)
- # check for ``class = val'' etc.
+ # check for ``class = val''.
valid = true
case token
when "class"
valid = false unless peek_match?(/^\s*(<<|\w|::)/)
when "def"
valid = false if peek_match?(/^\s*(([+-\/*&\|^]|<<|>>|\|\||\&\&)=|\&\&|\|\|)/)
+# valid = false if peek_match?(/^\s*(([+-\/*&\|^]|<<|>>|\|\||\&\&)?=|\&\&|\|\|)/)
when "do"
valid = false if peek_match?(/^\s*([+-\/*]?=|\*|<|>|\&)/)
when *ENINDENT_CLAUSE
@@ -896,11 +885,7 @@ class RubyLex
end
@here_header = false
- while l = gets
- l = l.sub(/(:?\r)?\n\z/, '')
- if (indent ? l.strip : l) == quoted
- break
- end
+ while (l = gets.chomp) && (indent ? l.strip : l) != quoted
end
@here_header = true
@@ -935,50 +920,19 @@ class RubyLex
def identify_number
@lex_state = EXPR_END
- if peek(0) == "0" && peek(1) !~ /[.eE]/
- case peek(0)
- when /[xX]/
+ if ch = getc
+ if /[xX]/ =~ peek(0)
ch = getc
match = /[0-9a-fA-F_]/
- when /[bB]/
+ elsif /[bB]/ =~ peek(0)
ch = getc
match = /[01_]/
- when /[oO]/
- ch = getc
- match = /[0-7_]/
- when /[dD]/
- ch = getc
- match = /[0-9_]/
- when /[0-7]/
+ else
match = /[0-7_]/
- when /[89]/
- RubyLex.fail SyntaxError, "Illegal octal digit"
- else
- return Token(TkINTEGER)
end
-
- len0 = true
- non_digit = false
while ch = getc
- if match =~ ch
- if ch == "_"
- if non_digit
- RubyLex.fail SyntaxError, "trailing `#{ch}' in number"
- else
- non_digit = ch
- end
- else
- non_digit = false
- len0 = false
- end
- else
+ if ch !~ match
ungetc
- if len0
- RubyLex.fail SyntaxError, "numeric literal without digits"
- end
- if non_digit
- RubyLex.fail SyntaxError, "trailing `#{non_digit}' in number"
- end
break
end
end
@@ -988,39 +942,24 @@ class RubyLex
type = TkINTEGER
allow_point = true
allow_e = true
- non_digit = false
while ch = getc
case ch
- when /[0-9]/
- non_digit = false
- when "_"
- non_digit = ch
+ when /[0-9_]/
when allow_point && "."
- if non_digit
- RubyLex.fail SyntaxError, "trailing `#{non_digit}' in number"
- end
type = TkFLOAT
if peek(0) !~ /[0-9]/
- type = TkINTEGER
ungetc
break
end
allow_point = false
when allow_e && "e", allow_e && "E"
- if non_digit
- RubyLex.fail SyntaxError, "trailing `#{non_digit}' in number"
- end
type = TkFLOAT
if peek(0) =~ /[+-]/
getc
end
allow_e = false
allow_point = false
- non_digit = ch
else
- if non_digit
- RubyLex.fail SyntaxError, "trailing `#{non_digit}' in number"
- end
ungetc
break
end
diff --git a/lib/irb/ruby-token.rb b/lib/irb/ruby-token.rb
index 525d4df14c..49b97e9c54 100644
--- a/lib/irb/ruby-token.rb
+++ b/lib/irb/ruby-token.rb
@@ -1,9 +1,9 @@
#
# irb/ruby-token.rb - ruby tokens
-# $Release Version: 0.9.5$
+# $Release Version: 0.9$
# $Revision$
# $Date$
-# by Keiju ISHITSUKA(keiju@ruby-lang.org)
+# by Keiju ISHITSUKA(keiju@ishitsuka.com)
#
# --
#
@@ -64,7 +64,7 @@ module RubyToken
class TkOPASGN < TkOp
def initialize(seek, line_no, char_no, op)
super(seek, line_no, char_no)
- op = TkReading2Token[op][0] unless op.kind_of?(Symbol)
+ op = TkReading2Token[op] unless op.kind_of?(Symbol)
@op = op
end
attr :op
diff --git a/lib/irb/slex.rb b/lib/irb/slex.rb
index a6ea6fb473..c0943f6e33 100644
--- a/lib/irb/slex.rb
+++ b/lib/irb/slex.rb
@@ -1,9 +1,9 @@
#
# irb/slex.rb - symple lex analizer
-# $Release Version: 0.9.5$
+# $Release Version: 0.9$
# $Revision$
# $Date$
-# by Keiju ISHITSUKA(keiju@ruby-lang.org)
+# by Keiju ISHITSUKA(keiju@ishituska.com)
#
# --
#
@@ -11,242 +11,236 @@
#
require "e2mmap"
-require "irb/notifier"
-module IRB
- class SLex
- @RCS_ID='-$Id$-'
+class SLex
+ @RCS_ID='-$Id$-'
- extend Exception2MessageMapper
- def_exception :ErrNodeNothing, "node nothing"
- def_exception :ErrNodeAlreadyExists, "node already exists"
+ extend Exception2MessageMapper
+ def_exception :ErrNodeNothing, "node nothing"
+ def_exception :ErrNodeAlreadyExists, "node already exists"
- DOUT = Notifier::def_notifier("SLex::")
- D_WARN = DOUT::def_notifier(1, "Warn: ")
- D_DEBUG = DOUT::def_notifier(2, "Debug: ")
- D_DETAIL = DOUT::def_notifier(4, "Detail: ")
-
- DOUT.level = Notifier::D_NOMSG
-
- def initialize
- @head = Node.new("")
+ class << self
+ attr_accessor :debug_level
+ def debug?
+ debug_level > 0
end
-
- def def_rule(token, preproc = nil, postproc = nil, &block)
- D_DETAIL.pp token
+ end
+ @debug_level = 0
- postproc = block if block_given?
- node = create(token, preproc, postproc)
- end
-
- def def_rules(*tokens, &block)
- if block_given?
- p = block
- end
- for token in tokens
- def_rule(token, nil, p)
- end
+ def initialize
+ @head = Node.new("")
+ end
+
+ def def_rule(token, preproc = nil, postproc = nil, &block)
+ # print node.inspect, "\n" if SLex.debug?
+ postproc = block if block_given?
+ node = create(token, preproc, postproc)
+ end
+
+ def def_rules(*tokens, &block)
+ if block_given?
+ p = block
end
-
- def preproc(token, proc)
- node = search(token)
- node.preproc=proc
+ for token in tokens
+ def_rule(token, nil, p)
end
-
- #$BMW%A%'%C%/(B?
- def postproc(token)
- node = search(token, proc)
- node.postproc=proc
- end
-
- def search(token)
- @head.search(token.split(//))
+ end
+
+ def preproc(token, proc)
+ node = search(token)
+ node.preproc=proc
+ end
+
+ def postproc(token)
+ node = search(token, proc)
+ node.postproc=proc
+ end
+
+ def search(token)
+ @head.search(token.split(//))
+ end
+
+ def create(token, preproc = nil, postproc = nil)
+ @head.create_subnode(token.split(//), preproc, postproc)
+ end
+
+ def match(token)
+ case token
+ when Array
+ when String
+ return match(token.split(//))
+ else
+ return @head.match_io(token)
end
+ ret = @head.match(token)
+ printf "match end: %s:%s", ret, token.inspect if SLex.debug?
+ ret
+ end
+
+ def inspect
+ format("<SLex: @head = %s>", @head.inspect)
+ end
- def create(token, preproc = nil, postproc = nil)
- @head.create_subnode(token.split(//), preproc, postproc)
+ #----------------------------------------------------------------------
+ #
+ # class Node -
+ #
+ #----------------------------------------------------------------------
+ class Node
+ # if postproc is nil, this node is an abstract node.
+ # if postproc is non-nil, this node is a real node.
+ def initialize(preproc = nil, postproc = nil)
+ @Tree = {}
+ @preproc = preproc
+ @postproc = postproc
end
+
+ attr_accessor :preproc
+ attr_accessor :postproc
- def match(token)
- case token
- when Array
- when String
- return match(token.split(//))
+ def search(chrs, opt = nil)
+ return self if chrs.empty?
+ ch = chrs.shift
+ if node = @Tree[ch]
+ node.search(chrs, opt)
else
- return @head.match_io(token)
+ if opt
+ chrs.unshift ch
+ self.create_subnode(chrs)
+ else
+ SLex.fail ErrNodeNothing
+ end
end
- ret = @head.match(token)
- D_DETAIL.exec_if{D_DEATIL.printf "match end: %s:%s\n", ret, token.inspect}
- ret
end
- def inspect
- format("<SLex: @head = %s>", @head.inspect)
- end
-
- #----------------------------------------------------------------------
- #
- # class Node -
- #
- #----------------------------------------------------------------------
- class Node
- # if postproc is nil, this node is an abstract node.
- # if postproc is non-nil, this node is a real node.
- def initialize(preproc = nil, postproc = nil)
- @Tree = {}
- @preproc = preproc
- @postproc = postproc
- end
-
- attr_accessor :preproc
- attr_accessor :postproc
-
- def search(chrs, opt = nil)
- return self if chrs.empty?
- ch = chrs.shift
- if node = @Tree[ch]
- node.search(chrs, opt)
+ def create_subnode(chrs, preproc = nil, postproc = nil)
+ if chrs.empty?
+ if @postproc
+ p node
+ SLex.fail ErrNodeAlreadyExists
else
- if opt
- chrs.unshift ch
- self.create_subnode(chrs)
- else
- SLex.fail ErrNodeNothing
- end
+ print "Warn: change abstract node to real node\n" if SLex.debug?
+ @preproc = preproc
+ @postproc = postproc
end
+ return self
end
- def create_subnode(chrs, preproc = nil, postproc = nil)
+ ch = chrs.shift
+ if node = @Tree[ch]
if chrs.empty?
- if @postproc
- D_DETAIL.pp node
+ if node.postproc
+ p node
+ p self
+ p ch
+ p chrs
SLex.fail ErrNodeAlreadyExists
else
- D_DEBUG.puts "change abstract node to real node."
- @preproc = preproc
- @postproc = postproc
+ print "Warn: change abstract node to real node\n" if SLex.debug?
+ node.preproc = preproc
+ node.postproc = postproc
end
- return self
+ else
+ node.create_subnode(chrs, preproc, postproc)
end
-
- ch = chrs.shift
- if node = @Tree[ch]
- if chrs.empty?
- if node.postproc
- DebugLogger.pp node
- DebugLogger.pp self
- DebugLogger.pp ch
- DebugLogger.pp chrs
- SLex.fail ErrNodeAlreadyExists
- else
- D_WARN.puts "change abstract node to real node"
- node.preproc = preproc
- node.postproc = postproc
- end
- else
- node.create_subnode(chrs, preproc, postproc)
- end
+ else
+ if chrs.empty?
+ node = Node.new(preproc, postproc)
else
- if chrs.empty?
- node = Node.new(preproc, postproc)
- else
- node = Node.new
- node.create_subnode(chrs, preproc, postproc)
- end
- @Tree[ch] = node
+ node = Node.new
+ node.create_subnode(chrs, preproc, postproc)
end
- node
+ @Tree[ch] = node
end
+ node
+ end
- #
- # chrs: String
- # character array
- # io must have getc()/ungetc(); and ungetc() must be
- # able to be called arbitrary number of times.
- #
- def match(chrs, op = "")
- D_DETAIL.print "match>: ", chrs, "op:", op, "\n"
- if chrs.empty?
- if @preproc.nil? || @preproc.call(op, chrs)
- DOUT.printf(D_DETAIL, "op1: %s\n", op)
- @postproc.call(op, chrs)
- else
- nil
- end
+ #
+ # chrs: String
+ # character array
+ # io must have getc()/ungetc(); and ungetc() must be
+ # able to be called arbitrary number of times.
+ #
+ def match(chrs, op = "")
+ print "match>: ", chrs, "op:", op, "\n" if SLex.debug?
+ if chrs.empty?
+ if @preproc.nil? || @preproc.call(op, chrs)
+ printf "op1: %s\n", op if SLex.debug?
+ @postproc.call(op, chrs)
else
- ch = chrs.shift
- if node = @Tree[ch]
- if ret = node.match(chrs, op+ch)
- return ret
- else
- chrs.unshift ch
- if @postproc and @preproc.nil? || @preproc.call(op, chrs)
- DOUT.printf(D_DETAIL, "op2: %s\n", op.inspect)
- ret = @postproc.call(op, chrs)
- return ret
- else
- return nil
- end
- end
+ nil
+ end
+ else
+ ch = chrs.shift
+ if node = @Tree[ch]
+ if ret = node.match(chrs, op+ch)
+ return ret
else
chrs.unshift ch
if @postproc and @preproc.nil? || @preproc.call(op, chrs)
- DOUT.printf(D_DETAIL, "op3: %s\n", op)
- @postproc.call(op, chrs)
- return ""
+ printf "op2: %s\n", op.inspect if SLex.debug?
+ ret = @postproc.call(op, chrs)
+ return ret
else
return nil
end
end
+ else
+ chrs.unshift ch
+ if @postproc and @preproc.nil? || @preproc.call(op, chrs)
+ printf "op3: %s\n", op if SLex.debug?
+ @postproc.call(op, chrs)
+ return ""
+ else
+ return nil
+ end
end
end
+ end
- def match_io(io, op = "")
- if op == ""
- ch = io.getc
- if ch == nil
- return nil
- end
- else
- ch = io.getc_of_rests
+ def match_io(io, op = "")
+ if op == ""
+ ch = io.getc
+ if ch == nil
+ return nil
end
- if ch.nil?
- if @preproc.nil? || @preproc.call(op, io)
- D_DETAIL.printf("op1: %s\n", op)
- @postproc.call(op, io)
- else
- nil
- end
+ else
+ ch = io.getc_of_rests
+ end
+ if ch.nil?
+ if @preproc.nil? || @preproc.call(op, io)
+ printf "op1: %s\n", op if SLex.debug?
+ @postproc.call(op, io)
else
- if node = @Tree[ch]
- if ret = node.match_io(io, op+ch)
- ret
- else
- io.ungetc ch
- if @postproc and @preproc.nil? || @preproc.call(op, io)
- DOUT.exec_if{D_DETAIL.printf "op2: %s\n", op.inspect}
- @postproc.call(op, io)
- else
- nil
- end
- end
+ nil
+ end
+ else
+ if node = @Tree[ch]
+ if ret = node.match_io(io, op+ch)
+ ret
else
io.ungetc ch
if @postproc and @preproc.nil? || @preproc.call(op, io)
- D_DETAIL.printf("op3: %s\n", op)
+ printf "op2: %s\n", op.inspect if SLex.debug?
@postproc.call(op, io)
else
nil
end
end
+ else
+ io.ungetc ch
+ if @postproc and @preproc.nil? || @preproc.call(op, io)
+ printf "op3: %s\n", op if SLex.debug?
+ @postproc.call(op, io)
+ else
+ nil
+ end
end
end
end
end
end
-SLex=IRB::SLex
-
if $0 == __FILE__
# Tracer.on
case $1
@@ -282,4 +276,3 @@ if $0 == __FILE__
end
exit
end
-
diff --git a/lib/irb/version.rb b/lib/irb/version.rb
index 28b079740a..a9e37f7e7b 100644
--- a/lib/irb/version.rb
+++ b/lib/irb/version.rb
@@ -1,6 +1,6 @@
#
# irb/version.rb - irb version definition file
-# $Release Version: 0.9.5$
+# $Release Version: 0.9$
# $Revision$
# $Date$
# by Keiju ISHITSUKA(keiju@ishitsuka.com)
@@ -11,6 +11,6 @@
#
module IRB
- @RELEASE_VERSION = "0.9.5"
- @LAST_UPDATE_DATE = "05/04/13"
+ @RELEASE_VERSION = "0.9"
+ @LAST_UPDATE_DATE = "02/07/03"
end
diff --git a/lib/irb/workspace.rb b/lib/irb/workspace.rb
index 7d1794cd7b..3b099b1baa 100644
--- a/lib/irb/workspace.rb
+++ b/lib/irb/workspace.rb
@@ -1,9 +1,9 @@
#
# irb/workspace-binding.rb -
-# $Release Version: 0.9.5$
+# $Release Version: 0.9$
# $Revision$
# $Date$
-# by Keiju ISHITSUKA(keiju@ruby-lang.org)
+# by Keiju ISHITSUKA(keiju@ishitsuka.com)
#
# --
#
diff --git a/lib/irb/ws-for-case-2.rb b/lib/irb/ws-for-case-2.rb
index afd49d23e1..1c58fb7dda 100644
--- a/lib/irb/ws-for-case-2.rb
+++ b/lib/irb/ws-for-case-2.rb
@@ -1,9 +1,9 @@
#
# irb/ws-for-case-2.rb -
-# $Release Version: 0.9.5$
+# $Release Version: 0.9$
# $Revision$
# $Date$
-# by Keiju ISHITSUKA(keiju@ruby-lang.org)
+# by Keiju ISHITSUKA(keiju@ishitsuka.com)
#
# --
#
diff --git a/lib/jcode.rb b/lib/jcode.rb
index 691d22dafe..8cd770be26 100644
--- a/lib/jcode.rb
+++ b/lib/jcode.rb
@@ -90,8 +90,7 @@ class String
end
def succ
- str = self.dup
- str.succ! or str
+ (str = self.dup).succ! or str
end
private
diff --git a/lib/logger.rb b/lib/logger.rb
index 9a2b51d6db..363e9774b4 100644
--- a/lib/logger.rb
+++ b/lib/logger.rb
@@ -1,7 +1,4 @@
-# logger.rb - saimple logging utility
-# Copyright (C) 2000-2003, 2005 NAKAMURA, Hiroshi <nakahiro@sarion.co.jp>.
-
-
+#
# = logger.rb
#
# Simple logging utility.
@@ -22,6 +19,7 @@
#
# The Logger class provides a simple but sophisticated logging utility that
# anyone can use because it's included in the Ruby 1.8.x standard library.
+# For more advanced logging, see the "Log4r" package on the RAA.
#
# The HOWTOs below give a code-based overview of Logger's usage, but the basic
# concept is as follows. You create a Logger object (output to a file or
@@ -78,6 +76,10 @@
# specifying a program name in conjunction with the message. The next section
# shows you how to achieve these things.
#
+# See http://raa.ruby-lang.org/list.rhtml?name=log4r for Log4r, which contains
+# many advanced features like file-based configuration, a wide range of
+# logging targets, simultaneous logging, and hierarchical logging.
+#
#
# == HOWTOs
#
@@ -144,7 +146,7 @@
#
# 1. Original interface.
#
-# logger.sev_threshold = Logger::WARN
+# logger.level = Logger::WARN
#
# 2. Log4r (somewhat) compatible interface.
#
@@ -172,13 +174,7 @@
# There is currently no supported way to change the overall format, but you may
# have some luck hacking the Format constant.
#
-
-
-require 'monitor'
-
-
class Logger
- VERSION = "1.2.6"
/: (\S+),v (\S+)/ =~ %q$Id$
ProgName = "#{$1}/#{$2}"
@@ -203,20 +199,7 @@ class Logger
attr_accessor :progname
# Logging date-time format (string passed to +strftime+).
- def datetime_format=(datetime_format)
- @default_formatter.datetime_format = datetime_format
- end
-
- def datetime_format
- @default_formatter.datetime_format
- end
-
- # Logging formatter. formatter#call is invoked with 4 arguments; severity,
- # time, progname and msg for each log. Bear in mind that time is a Time and
- # msg is an Object that user passed and it could not be a String. It is
- # expected to return a logdev#write-able Object. Default formatter is used
- # when no formatter is set.
- attr_accessor :formatter
+ attr_accessor :datetime_format
alias sev_threshold level
alias sev_threshold= level=
@@ -260,17 +243,17 @@ class Logger
#
# === Description
#
- # Create an instance.
+ # Create an instance. See Logger::LogDevice.new for more information if
+ # required.
#
def initialize(logdev, shift_age = 0, shift_size = 1048576)
+ @logdev = nil
@progname = nil
@level = DEBUG
- @default_formatter = Formatter.new
- @formatter = nil
+ @datetime_format = nil
@logdev = nil
if logdev
- @logdev = LogDevice.new(logdev, :shift_age => shift_age,
- :shift_size => shift_size)
+ @logdev = LogDevice.new(logdev, :shift_age => shift_age, :shift_size => shift_size)
end
end
@@ -333,7 +316,13 @@ class Logger
end
end
@logdev.write(
- format_message(format_severity(severity), Time.now, progname, message))
+ format_message(
+ format_severity(severity),
+ format_datetime(Time.now),
+ msg2str(message),
+ progname
+ )
+ )
true
end
alias log add
@@ -436,60 +425,72 @@ private
SEV_LABEL[severity] || 'ANY'
end
- def format_message(severity, datetime, progname, msg)
- (@formatter || @default_formatter).call(severity, datetime, progname, msg)
- end
-
-
- class Formatter
- Format = "%s, [%s#%d] %5s -- %s: %s\n"
-
- attr_accessor :datetime_format
-
- def initialize
- @datetime_format = nil
- end
-
- def call(severity, time, progname, msg)
- Format % [severity[0..0], format_datetime(time), $$, severity, progname,
- msg2str(msg)]
+ def format_datetime(datetime)
+ if @datetime_format.nil?
+ datetime.strftime("%Y-%m-%dT%H:%M:%S.") << "%06d " % datetime.usec
+ else
+ datetime.strftime(@datetime_format)
end
+ end
- private
-
- def format_datetime(time)
- if @datetime_format.nil?
- time.strftime("%Y-%m-%dT%H:%M:%S.") << "%06d " % time.usec
- else
- time.strftime(@datetime_format)
- end
- end
+ Format = "%s, [%s#%d] %5s -- %s: %s\n"
+ def format_message(severity, timestamp, msg, progname)
+ Format % [severity[0..0], timestamp, $$, severity, progname, msg]
+ end
- def msg2str(msg)
- case msg
- when ::String
- msg
- when ::Exception
- "#{ msg.message } (#{ msg.class })\n" <<
- (msg.backtrace || []).join("\n")
- else
- msg.inspect
- end
+ def msg2str(msg)
+ case msg
+ when ::String
+ msg
+ when ::Exception
+ "#{ msg.message } (#{ msg.class })\n" << (msg.backtrace || []).join("\n")
+ else
+ msg.inspect
end
end
+ #
+ # LogDevice -- Logging device.
+ #
class LogDevice
attr_reader :dev
attr_reader :filename
- class LogDeviceMutex
- include MonitorMixin
- end
-
+ #
+ # == Synopsis
+ #
+ # Logger::LogDev.new(name, :shift_age => 'daily|weekly|monthly')
+ # Logger::LogDev.new(name, :shift_age => 10, :shift_size => 1024*1024)
+ #
+ # == Args
+ #
+ # +name+::
+ # A String (representing a filename) or an IO object (actually, anything
+ # that responds to +write+ and +close+). If a filename is given, then
+ # that file is opened for writing (and appending if it already exists),
+ # with +sync+ set to +true+.
+ # +opts+::
+ # Contains optional arguments for rolling ("shifting") the log file.
+ # <tt>:shift_age</tt> is either a description (e.g. 'daily'), or an
+ # integer number of log files to keep. <tt>shift_size</tt> is the maximum
+ # size of the log file, and is only significant is a number is given for
+ # <tt>shift_age</tt>.
+ #
+ # These arguments are only relevant if a filename is provided for the
+ # first argument.
+ #
+ # == Description
+ #
+ # Creates a LogDevice object, which is the target for log messages. Rolling
+ # of log files is supported (only if a filename is given; you can't roll an
+ # IO object). The beginning of each file created by this class is tagged
+ # with a header message.
+ #
+ # This class is unlikely to be used directly; it is a backend for Logger.
+ #
def initialize(log = nil, opt = {})
@dev = @filename = @shift_age = @shift_size = nil
- @mutex = LogDeviceMutex.new
if log.respond_to?(:write) and log.respond_to?(:close)
@dev = log
else
@@ -501,23 +502,29 @@ private
end
end
+ #
+ # Log a message. If needed, the log file is rolled and the new file is
+ # prepared. Log device is not locked. Append open does not need to lock
+ # file but on an OS which supports multi I/O, records could possibly be
+ # mixed.
+ #
def write(message)
- @mutex.synchronize do
- if @shift_age and @dev.respond_to?(:stat)
- begin
- check_shift_log
- rescue
- raise Logger::ShiftingError.new("Shifting failed. #{$!}")
- end
- end
- @dev.write(message)
+ if shift_log?
+ begin
+ shift_log
+ rescue
+ raise Logger::ShiftingError.new("Shifting failed. #{$!}")
+ end
end
+
+ @dev.write(message)
end
+ #
+ # Close the logging device.
+ #
def close
- @mutex.synchronize do
- @dev.close
- end
+ @dev.close
end
private
@@ -545,57 +552,66 @@ private
SiD = 24 * 60 * 60
- def check_shift_log
- if @shift_age.is_a?(Integer)
- # Note: always returns false if '0'.
- if @filename && (@shift_age > 0) && (@dev.stat.size > @shift_size)
- shift_log_age
- end
+ def shift_log?
+ if !@shift_age or !@dev.respond_to?(:stat)
+ return false
+ end
+ if (@shift_age.is_a?(Integer))
+ # Note: always returns false if '0'.
+ return (@filename && (@shift_age > 0) && (@dev.stat.size > @shift_size))
else
- now = Time.now
- if @dev.stat.mtime <= previous_period_end(now)
- shift_log_period(now)
- end
+ now = Time.now
+ limit_time = case @shift_age
+ when /^daily$/
+ eod(now - 1 * SiD)
+ when /^weekly$/
+ eod(now - ((now.wday + 1) * SiD))
+ when /^monthly$/
+ eod(now - now.mday * SiD)
+ else
+ now
+ end
+ return (@dev.stat.mtime <= limit_time)
end
end
- def shift_log_age
- (@shift_age-3).downto(0) do |i|
- if FileTest.exist?("#{@filename}.#{i}")
- File.rename("#{@filename}.#{i}", "#{@filename}.#{i+1}")
- end
+ def shift_log
+ # At first, close the device if opened.
+ if @dev
+ @dev.close
+ @dev = nil
end
- @dev.close
- File.rename("#{@filename}", "#{@filename}.0")
- @dev = create_logfile(@filename)
- return true
- end
-
- def shift_log_period(now)
- postfix = previous_period_end(now).strftime("%Y%m%d") # YYYYMMDD
- age_file = "#{@filename}.#{postfix}"
- if FileTest.exist?(age_file)
- raise RuntimeError.new("'#{ age_file }' already exists.")
+ if (@shift_age.is_a?(Integer))
+ (@shift_age-3).downto(0) do |i|
+ if (FileTest.exist?("#{@filename}.#{i}"))
+ File.rename("#{@filename}.#{i}", "#{@filename}.#{i+1}")
+ end
+ end
+ File.rename("#{@filename}", "#{@filename}.0")
+ else
+ now = Time.now
+ postfix_time = case @shift_age
+ when /^daily$/
+ eod(now - 1 * SiD)
+ when /^weekly$/
+ eod(now - ((now.wday + 1) * SiD))
+ when /^monthly$/
+ eod(now - now.mday * SiD)
+ else
+ now
+ end
+ postfix = postfix_time.strftime("%Y%m%d") # YYYYMMDD
+ age_file = "#{@filename}.#{postfix}"
+ if (FileTest.exist?(age_file))
+ raise RuntimeError.new("'#{ age_file }' already exists.")
+ end
+ File.rename("#{@filename}", age_file)
end
- @dev.close
- File.rename("#{@filename}", age_file)
+
@dev = create_logfile(@filename)
return true
end
- def previous_period_end(now)
- case @shift_age
- when /^daily$/
- eod(now - 1 * SiD)
- when /^weekly$/
- eod(now - ((now.wday + 1) * SiD))
- when /^monthly$/
- eod(now - now.mday * SiD)
- else
- now
- end
- end
-
def eod(t)
Time.mktime(t.year, t.month, t.mday, 23, 59, 59)
end
@@ -675,8 +691,8 @@ private
end
#
- # Sets the log device for this application. See the class Logger for an
- # explanation of the arguments.
+ # Sets the log device for this application. See the classes Logger and
+ # Logger::LogDevice for an explanation of the arguments.
#
def set_log(logdev, shift_age = 0, shift_size = 1024000)
@log = Logger.new(logdev, shift_age, shift_size)
diff --git a/lib/mathn.rb b/lib/mathn.rb
index 14e2e9272c..2257a4074a 100644
--- a/lib/mathn.rb
+++ b/lib/mathn.rb
@@ -124,7 +124,6 @@ class Rational
def ** (other)
if other.kind_of?(Rational)
- other2 = other
if self < 0
return Complex.new!(self, 0) ** other
elsif other == 0
@@ -145,7 +144,7 @@ class Rational
for elm in npd
elm[1] = elm[1] * other
if !elm[1].kind_of?(Integer) and elm[1].denominator != 1
- return Float(self) ** other2
+ return Float(self) ** other
end
elm[1] = elm[1].to_i
end
@@ -153,7 +152,7 @@ class Rational
for elm in dpd
elm[1] = elm[1] * other
if !elm[1].kind_of?(Integer) and elm[1].denominator != 1
- return Float(self) ** other2
+ return Float(self) ** other
end
elm[1] = elm[1].to_i
end
diff --git a/lib/mkmf.rb b/lib/mkmf.rb
index 6150b59c9a..494838e63b 100644
--- a/lib/mkmf.rb
+++ b/lib/mkmf.rb
@@ -8,11 +8,7 @@ require 'shellwords'
CONFIG = Config::MAKEFILE_CONFIG
ORIG_LIBPATH = ENV['LIB']
-CXX_EXT = %w[cc cxx cpp]
-if /mswin|bccwin|mingw|msdosdjgpp|human|os2/ !~ CONFIG['build_os']
- CXX_EXT.concat(%w[C])
-end
-SRC_EXT = %w[c m] << CXX_EXT
+SRC_EXT = ["c", "cc", "m", "cxx", "cpp", "C"]
$static = $config_h = nil
unless defined? $configure_args
@@ -44,6 +40,7 @@ unless defined? $configure_args
end
end
+$srcdir = CONFIG["srcdir"]
$libdir = CONFIG["libdir"]
$rubylibdir = CONFIG["rubylibdir"]
$archdir = CONFIG["archdir"]
@@ -58,8 +55,6 @@ $cygwin = /cygwin/ =~ RUBY_PLATFORM
$human = /human/ =~ RUBY_PLATFORM
$netbsd = /netbsd/ =~ RUBY_PLATFORM
$os2 = /os2/ =~ RUBY_PLATFORM
-$beos = /beos/ =~ RUBY_PLATFORM
-$solaris = /solaris/ =~ RUBY_PLATFORM
def config_string(key, config = CONFIG)
s = config[key] and !s.empty? and block_given? ? yield(s) : s
@@ -78,45 +73,18 @@ INSTALL_DIRS = [
[dir_re('sitearchdir'), "$(RUBYARCHDIR)"]
]
-def install_dirs(target_prefix = nil)
- if $extout
- dirs = [
- ['RUBYCOMMONDIR', '$(extout)'],
- ['RUBYLIBDIR', '$(extout)$(target_prefix)'],
- ['RUBYARCHDIR', '$(extout)/$(arch)$(target_prefix)'],
- ['extout', "#$extout"],
- ['extout_prefix', "#$extout_prefix"],
- ]
- elsif $extmk
- dirs = [
- ['RUBYCOMMONDIR', '$(rubylibdir)'],
- ['RUBYLIBDIR', '$(rubylibdir)$(target_prefix)'],
- ['RUBYARCHDIR', '$(archdir)$(target_prefix)'],
- ]
- else
- dirs = [
- ['RUBYCOMMONDIR', '$(sitedir)$(target_prefix)'],
- ['RUBYLIBDIR', '$(sitelibdir)$(target_prefix)'],
- ['RUBYARCHDIR', '$(sitearchdir)$(target_prefix)'],
- ]
- end
- dirs << ['target_prefix', (target_prefix ? "/#{target_prefix}" : "")]
- dirs
-end
-
def map_dir(dir, map = nil)
map ||= INSTALL_DIRS
map.inject(dir) {|dir, (orig, new)| dir.gsub(orig, new)}
end
-topdir = File.dirname(libdir = File.dirname(__FILE__))
-extdir = File.expand_path("ext", topdir)
-$extmk = File.expand_path($0)[0, extdir.size+1] == extdir+"/"
-if not $extmk and File.exist?(Config::CONFIG["archdir"] + "/ruby.h")
+libdir = File.dirname(__FILE__)
+$extmk = libdir != Config::CONFIG["rubylibdir"]
+if not $extmk and File.exist? Config::CONFIG["archdir"] + "/ruby.h"
$hdrdir = $topdir = Config::CONFIG["archdir"]
-elsif File.exist?(($top_srcdir ||= topdir) + "/ruby.h") and
- File.exist?(($topdir ||= Config::CONFIG["topdir"]) + "/config.h")
- $hdrdir = $top_srcdir
+elsif File.exist? $srcdir + "/ruby.h"
+ $topdir = Config::CONFIG["compile_dir"]
+ $hdrdir = $srcdir
else
abort "can't find header files for ruby."
end
@@ -168,7 +136,6 @@ module Logging
@logfile = 'mkmf.log'
@orgerr = $stderr.dup
@orgout = $stdout.dup
- @postpone = 0
def self::open
@log ||= File::open(@logfile, 'w')
@@ -197,7 +164,7 @@ module Logging
end
def self::postpone
- tmplog = "mkmftmp#{@postpone += 1}.log"
+ tmplog = "mkmftmp.log"
open do
log, *save = @log, @logfile, @orgout, @orgerr
@log, @logfile, @orgout, @orgerr = nil, tmplog, log, log
@@ -207,7 +174,6 @@ module Logging
File::open(tmplog) {|t| FileUtils.copy_stream(t, log)}
ensure
@log, @logfile, @orgout, @orgerr = log, *save
- @postpone -= 1
rm_f tmplog
end
end
@@ -215,6 +181,7 @@ module Logging
end
def xsystem command
+ Config.expand(command)
Logging::open do
puts command.quote
system(command)
@@ -222,6 +189,7 @@ def xsystem command
end
def xpopen command, *mode, &block
+ Config.expand(command)
Logging::open do
case mode[0]
when nil, /^r/
@@ -260,33 +228,31 @@ end
def link_command(ldflags, opt="", libpath=$LIBPATH)
Config::expand(TRY_LINK.dup,
- CONFIG.merge('hdrdir' => $hdrdir.quote,
- 'src' => CONFTEST_C,
- 'INCFLAGS' => $INCFLAGS,
- 'CPPFLAGS' => $CPPFLAGS,
- 'CFLAGS' => "#$CFLAGS",
- 'ARCH_FLAG' => "#$ARCH_FLAG",
- 'LDFLAGS' => "#$LDFLAGS #{ldflags}",
- 'LIBPATH' => libpathflag(libpath),
- 'LOCAL_LIBS' => "#$LOCAL_LIBS #$libs",
- 'LIBS' => "#$LIBRUBYARG_STATIC #{opt} #$LIBS"))
+ 'hdrdir' => $hdrdir,
+ 'src' => CONFTEST_C,
+ 'INCFLAGS' => $INCFLAGS,
+ 'CPPFLAGS' => $CPPFLAGS,
+ 'CFLAGS' => "#$CFLAGS",
+ 'ARCH_FLAG' => "#$ARCH_FLAG",
+ 'LDFLAGS' => "#$LDFLAGS #{ldflags}",
+ 'LIBPATH' => libpathflag(libpath),
+ 'LOCAL_LIBS' => "#$LOCAL_LIBS #$libs",
+ 'LIBS' => "#$LIBRUBYARG_STATIC #{opt} #$LIBS")
end
def cc_command(opt="")
- Config::expand("$(CC) -c #$INCFLAGS -I$(hdrdir) " \
- "#$CPPFLAGS #$CFLAGS #$ARCH_FLAG #{opt} #{CONFTEST_C}",
- CONFIG.merge('hdrdir' => $hdrdir.quote))
+ "$(CC) -c #$INCFLAGS -I#{$hdrdir} " \
+ "#$CPPFLAGS #$CFLAGS #$ARCH_FLAG #{opt} #{CONFTEST_C}"
end
def cpp_command(outfile, opt="")
- Config::expand("$(CPP) #$INCFLAGS -I$(hdrdir) " \
- "#$CPPFLAGS #$CFLAGS #{opt} #{CONFTEST_C} #{outfile}",
- CONFIG.merge('hdrdir' => $hdrdir.quote))
+ "$(CPP) #$INCFLAGS -I#{$hdrdir} " \
+ "#$CPPFLAGS #$CFLAGS #{opt} #{CONFTEST_C} #{outfile}"
end
def libpathflag(libpath=$LIBPATH)
libpath.map{|x|
- (x == "$(topdir)" ? LIBPATHFLAG : LIBPATHFLAG+RPATHFLAG) % x.quote
+ (x == "$(topdir)" ? LIBPATHFLAG : LIBPATHFLAG+RPATHFLAG) % x
}.join
end
@@ -321,82 +287,54 @@ def cpp_include(header)
end
end
-def with_cppflags(flags)
- cppflags = $CPPFLAGS
- $CPPFLAGS = flags
- ret = yield
-ensure
- $CPPFLAGS = cppflags unless ret
-end
-
-def with_cflags(flags)
- cflags = $CFLAGS
- $CFLAGS = flags
- ret = yield
-ensure
- $CFLAGS = cflags unless ret
-end
-
-def with_ldflags(flags)
- ldflags = $LDFLAGS
- $LDFLAGS = flags
- ret = yield
-ensure
- $LDFLAGS = ldflags unless ret
-end
-
def try_static_assert(expr, headers = nil, opt = "", &b)
headers = cpp_include(headers)
try_compile(<<SRC, opt, &b)
#{COMMON_HEADERS}
#{headers}
/*top*/
-int conftest_const[(#{expr}) ? 1 : -1];
+int tmp[(#{expr}) ? 1 : -1];
SRC
end
def try_constant(const, headers = nil, opt = "", &b)
- includes = cpp_include(headers)
+ headers = cpp_include(headers)
if CROSS_COMPILING
- if try_static_assert("#{const} > 0", headers, opt)
- # positive constant
- elsif try_static_assert("#{const} < 0", headers, opt)
+ unless try_compile(<<"SRC", opt, &b)
+#{COMMON_HEADERS}
+#{headers}
+/*top*/
+int tmp = #{const};
+SRC
+ return nil
+ end
+ if try_static_assert("#{const} < 0", headers, opt)
neg = true
const = "-(#{const})"
elsif try_static_assert("#{const} == 0", headers, opt)
return 0
- else
- # not a constant
- return nil
end
upper = 1
- until try_static_assert("#{const} <= #{upper}", headers, opt)
+ until try_static_assert("#{const} < #{upper}", headers, opt)
lower = upper
upper <<= 1
end
return nil unless lower
- while upper > lower + 1
- mid = (upper + lower) / 2
- if try_static_assert("#{const} > #{mid}", headers, opt)
- lower = mid
+ until try_static_assert("#{const} == #{upper}", headers, opt)
+ if try_static_assert("#{const} > #{(upper+lower)/2}", headers, opt)
+ lower = (upper+lower)/2
else
- upper = mid
- end
- end
- unless upper == lower
- if try_static_assert("#{const} == #{lower}", headers, opt)
- upper = lower
+ upper = (upper+lower)/2
end
end
upper = -upper if neg
return upper
else
src = %{#{COMMON_HEADERS}
-#{includes}
+#{headers}
#include <stdio.h>
/*top*/
-int conftest_const = (int)(#{const});
-int main() {printf("%d\\n", conftest_const); return 0;}
+int main() {printf("%d\\n", (int)(#{const})); return 0;}
}
if try_link0(src, opt, &b)
xpopen("./conftest") do |f|
@@ -423,17 +361,6 @@ int t() { void ((*volatile p)()); p = (void ((*)()))#{func}; return 0; }
SRC
end
-def try_var(var, headers = nil, &b)
- headers = cpp_include(headers)
- try_compile(<<"SRC", &b)
-#{COMMON_HEADERS}
-#{headers}
-/*top*/
-int main() { return 0; }
-int t() { void *volatile p; p = (void *)&#{var}; return 0; }
-SRC
-end
-
def egrep_cpp(pat, src, opt = "", &b)
src = create_tmpsrc(src, &b)
xpopen(cpp_command('', opt)) do |f|
@@ -462,11 +389,10 @@ end
def macro_defined?(macro, src, opt = "", &b)
src = src.sub(/[^\n]\z/, "\\&\n")
- try_compile(src + <<"SRC", opt, &b)
+ try_cpp(src + <<"SRC", opt, &b)
/*top*/
#ifndef #{macro}
# error
->>>>>> #{macro} undefined <<<<<<
#endif
SRC
end
@@ -490,7 +416,7 @@ def install_files(mfile, ifiles, map = nil, srcprefix = nil)
ifiles.each do |files, dir, prefix|
dir = map_dir(dir, map)
prefix = %r|\A#{Regexp.quote(prefix)}/?| if prefix
- if /\A\.\// =~ files
+ if( files[0,2] == "./" )
# install files which are in current working directory.
files = files[2..-1]
len = nil
@@ -533,14 +459,14 @@ def message(*s)
end
end
-def checking_for(m, fmt = nil)
+def checking_for(m)
f = caller[0][/in `(.*)'$/, 1] and f << ": " #` for vim
m = "checking for #{m}... "
message "%s", m
a = r = nil
Logging::postpone do
r = yield
- a = (fmt ? fmt % r : r ? "yes" : "no") << "\n"
+ a = r ? "yes\n" : "no\n"
"#{f}#{m}-------------------- #{a}\n"
end
message(a)
@@ -548,14 +474,6 @@ def checking_for(m, fmt = nil)
r
end
-def have_macro(macro, headers = nil, opt = "", &b)
- m = "#{macro}"
- m << " in #{headers.inspect}" if headers
- checking_for m do
- macro_defined?(macro, cpp_include(headers), opt, &b)
- end
-end
-
def have_library(lib, func = nil, header=nil, &b)
func = "main" if !func or func.empty?
lib = with_config(lib+'lib', lib)
@@ -577,7 +495,6 @@ end
def find_library(lib, func, *paths, &b)
func = "main" if !func or func.empty?
lib = with_config(lib+'lib', lib)
- paths = paths.collect {|path| path.split(File::PATH_SEPARATOR)}.flatten
checking_for "#{func}() in #{LIBARG%lib}" do
libpath = $LIBPATH
libs = append_library($libs, lib)
@@ -607,17 +524,6 @@ def have_func(func, headers = nil, &b)
end
end
-def have_var(var, headers = nil, &b)
- checking_for "#{var}" do
- if try_var(var, headers, &b)
- $defs.push(format("-DHAVE_%s", var.upcase))
- true
- else
- false
- end
- end
-end
-
def have_header(header, &b)
checking_for header do
if try_cpp(cpp_include(header), &b)
@@ -629,25 +535,6 @@ def have_header(header, &b)
end
end
-def find_header(header, *paths)
- checking_for header do
- if try_cpp(cpp_include(header))
- true
- else
- found = false
- paths.each do |dir|
- opt = "-I#{dir}".quote
- if try_cpp(cpp_include(header), opt)
- $INCFLAGS << " " << opt
- found = true
- break
- end
- end
- found
- end
- end
-end
-
def have_struct_member(type, member, header = nil, &b)
checking_for "#{type}.#{member}" do
if try_compile(<<"SRC", &b)
@@ -691,88 +578,18 @@ def check_sizeof(type, header = nil, &b)
expr = "sizeof(#{type})"
m = "checking size of #{type}... "
message "%s", m
- a = size = nil
- Logging::postpone do
- if size = try_constant(expr, header, &b)
- $defs.push(format("-DSIZEOF_%s=%d", type.upcase.tr_s("^A-Z0-9_", "_"), size))
- a = "#{size}\n"
- else
- a = "failed\n"
- end
- "check_sizeof: #{m}-------------------- #{a}\n"
+ Logging::message "check_sizeof: %s--------------------\n", m
+ if size = try_constant(expr, header, &b)
+ $defs.push(format("-DSIZEOF_%s=%d", type.upcase.tr_s("^A-Z0-9_", "_"), size))
end
- message(a)
- Logging::message "--------------------\n\n"
+ message(a = size ? "#{size}\n" : "failed\n")
+ Logging::message "-------------------- %s\n", a
size
end
-def scalar_ptr_type?(type, member = nil, headers = nil, &b)
- try_compile(<<"SRC", &b) # pointer
-#{COMMON_HEADERS}
-#{cpp_include(headers)}
-/*top*/
-volatile #{type} conftestval;
-int main() { return 0; }
-int t() {return (int)(1-*(conftestval#{member ? ".#{member}" : ""}));}
-SRC
-end
-
-def scalar_type?(type, member = nil, headers = nil, &b)
- try_compile(<<"SRC", &b) # pointer
-#{COMMON_HEADERS}
-#{cpp_include(headers)}
-/*top*/
-volatile #{type} conftestval;
-int main() { return 0; }
-int t() {return (int)(1-(conftestval#{member ? ".#{member}" : ""}));}
-SRC
-end
-
-def what_type?(type, member = nil, headers = nil, &b)
- m = "#{type}"
- name = type
- if member
- m << "." << member
- name = "(((#{type} *)0)->#{member})"
- end
- m << " in #{headers.inspect}" if headers
- fmt = "seems %s"
- def fmt.%(x)
- x ? super : "unknown"
- end
- checking_for m, fmt do
- if scalar_ptr_type?(type, member, headers, &b)
- if try_static_assert("sizeof(*#{name}) == 1", headers)
- "string"
- end
- elsif scalar_type?(type, member, headers, &b)
- if try_static_assert("sizeof(#{name}) > sizeof(long)", headers)
- "long long"
- elsif try_static_assert("sizeof(#{name}) > sizeof(int)", headers)
- "long"
- elsif try_static_assert("sizeof(#{name}) > sizeof(short)", headers)
- "int"
- elsif try_static_assert("sizeof(#{name}) > 1", headers)
- "short"
- else
- "char"
- end
- end
- end
-end
-
def find_executable0(bin, path = nil)
+ path = (path || ENV['PATH']).split(File::PATH_SEPARATOR)
ext = config_string('EXEEXT')
- if File.expand_path(bin) == bin
- return bin if File.executable?(bin)
- return file if ext and File.executable?(file = bin + ext)
- return nil
- end
- if path ||= ENV['PATH']
- path = path.split(File::PATH_SEPARATOR)
- else
- path = %w[/usr/local/bin /usr/ucb /usr/bin /bin]
- end
file = nil
path.each do |dir|
return file if File.executable?(file = File.join(dir, bin))
@@ -787,42 +604,24 @@ def find_executable(bin, path = nil)
end
end
-def arg_config(config, *defaults, &block)
- $arg_config << [config, *defaults]
- defaults << nil if !block and defaults.empty?
- $configure_args.fetch(config.tr('_', '-'), *defaults, &block)
+def arg_config(config, default=nil)
+ $configure_args.fetch(config.tr('_', '-'), default)
end
-def with_config(config, *defaults)
- config = config.sub(/^--with[-_]/, '')
- val = arg_config("--with-"+config) do
- if arg_config("--without-"+config)
- false
- elsif block_given?
- yield(config, *defaults)
- else
- break *defaults
- end
- end
- case val
- when "yes"
- true
- when "no"
- false
- else
- val
+def with_config(config, default=nil)
+ unless /^--with[-_]/ =~ config
+ config = '--with-' + config
end
+ arg_config(config, default)
end
-def enable_config(config, *defaults)
+def enable_config(config, default=nil)
if arg_config("--enable-"+config)
true
elsif arg_config("--disable-"+config)
false
- elsif block_given?
- yield(config, *defaults)
else
- return *defaults
+ default
end
end
@@ -847,16 +646,15 @@ end
def dir_config(target, idefault=nil, ldefault=nil)
if dir = with_config(target + "-dir", (idefault unless ldefault))
- defaults = Array === dir ? dir : dir.split(File::PATH_SEPARATOR)
+ defaults = dir.split(File::PATH_SEPARATOR)
idefault = ldefault = nil
end
idir = with_config(target + "-include", idefault)
- $arg_config.last[1] ||= "${#{target}-dir}/include"
ldir = with_config(target + "-lib", ldefault)
- $arg_config.last[1] ||= "${#{target}-dir}/lib"
- idirs = idir ? Array === idir ? idir : idir.split(File::PATH_SEPARATOR) : []
+# idirs = idir ? idir.split(File::PATH_SEPARATOR) : []
+ idirs = idir.split(File::PATH_SEPARATOR) rescue []
if defaults
idirs.concat(defaults.collect {|dir| dir + "/include"})
idir = ([idir] + idirs).compact.join(File::PATH_SEPARATOR)
@@ -869,7 +667,7 @@ def dir_config(target, idefault=nil, ldefault=nil)
end
end
- ldirs = ldir ? Array === ldir ? ldir : ldir.split(File::PATH_SEPARATOR) : []
+ ldirs = ldir ? ldir.split(File::PATH_SEPARATOR) : []
if defaults
ldirs.concat(defaults.collect {|dir| dir + "/lib"})
ldir = ([ldir] + ldirs).compact.join(File::PATH_SEPARATOR)
@@ -911,26 +709,15 @@ end
def configuration(srcdir)
mk = []
- vpath = %w[$(srcdir) $(topdir) $(hdrdir)]
- if !CROSS_COMPILING
- case CONFIG['build_os']
- when 'cygwin'
- if CONFIG['target_os'] != 'cygwin'
- vpath.each {|p| p.sub!(/.*/, '$(shell cygpath -u \&)')}
- end
- when 'msdosdjgpp', 'mingw32'
- CONFIG['PATH_SEPARATOR'] = ';'
- end
- end
mk << %{
SHELL = /bin/sh
#### Start of system configuration section. ####
-srcdir = #{srcdir.gsub(/\$\((srcdir)\)|\$\{(srcdir)\}/) {CONFIG[$1||$2]}.quote}
-topdir = #{($extmk ? CONFIG["topdir"] : $topdir).quote}
-hdrdir = #{$extmk ? CONFIG["hdrdir"].quote : '$(topdir)'}
-VPATH = #{vpath.join(CONFIG['PATH_SEPARATOR'])}
+srcdir = #{srcdir}
+topdir = #{$topdir}
+hdrdir = #{$extmk ? $hdrdir : '$(topdir)'}
+VPATH = #{$mingw && CONFIG['build_os'] == 'cygwin' ? '$(shell cygpath -u $(srcdir))' : '$(srcdir)'}
}
drive = File::PATH_SEPARATOR == ';' ? /\A\w:/ : /\A/
if destdir = CONFIG["prefix"].scan(drive)[0] and !destdir.empty?
@@ -942,15 +729,9 @@ VPATH = #{vpath.join(CONFIG['PATH_SEPARATOR'])}
end
CONFIG.each do |key, var|
next if /^abs_/ =~ key
- next unless /^(?:src|top|hdr|(.*))dir$/ =~ key and $1
+ next unless /^(?:src|top|(.*))dir$/ =~ key and $1
mk << "#{key} = #{with_destdir(var.sub(drive, ''))}\n"
end
- if !$extmk and !$configure_args.has_key?('--ruby') and
- sep = config_string('BUILD_FILE_SEPARATOR')
- sep = ":/=#{sep}"
- else
- sep = ""
- end
mk << %{
CC = #{CONFIG['CC']}
LIBRUBY = #{CONFIG['LIBRUBY']}
@@ -972,17 +753,14 @@ arch = #{CONFIG['arch']}
sitearch = #{CONFIG['sitearch']}
ruby_version = #{Config::CONFIG['ruby_version']}
ruby = #{$ruby}
-RUBY = $(ruby#{sep})
-RM = #{config_string('RM') || '$(RUBY) -run -e rm -- -f'}
-MAKEDIRS = #{config_string('MAKEDIRS') || '@$(RUBY) -run -e mkdir -- -p'}
-INSTALL = #{config_string('INSTALL') || '@$(RUBY) -run -e install -- -vp'}
-INSTALL_PROG = #{config_string('INSTALL_PROG') || '$(INSTALL) -m 0755'}
-INSTALL_DATA = #{config_string('INSTALL_DATA') || '$(INSTALL) -m 0644'}
-COPY = #{config_string('CP') || '@$(RUBY) -run -e cp -- -v'}
+RUBY = #{($nmake && !$extmk && !$configure_args.has_key?('--ruby')) ? '$(ruby:/=\)' : '$(ruby)'}
+RM = $(RUBY) -run -e rm -- -f
+MAKEDIRS = $(RUBY) -run -e mkdir -- -p
+INSTALL_PROG = $(RUBY) -run -e install -- -vpm 0755
+INSTALL_DATA = $(RUBY) -run -e install -- -vpm 0644
#### End of system configuration section. ####
-preload = #{$preload.join(" ") if $preload}
}
if $nmake == ?b
mk.each do |x|
@@ -997,13 +775,7 @@ preload = #{$preload.join(" ") if $preload}
end
def dummy_makefile(srcdir)
- configuration(srcdir) << <<RULES << CLEANINGS
-CLEANFILES = #{$cleanfiles.join(' ')}
-DISTCLEANFILES = #{$distcleanfiles.join(' ')}
-
-all install static install-so install-rb: Makefile
-
-RULES
+ configuration(srcdir) << "all install: Makefile\n" << CLEANINGS
end
def create_makefile(target, srcprefix = nil)
@@ -1028,18 +800,15 @@ def create_makefile(target, srcprefix = nil)
srcprefix ||= '$(srcdir)'
Config::expand(srcdir = srcprefix.dup)
- if not $objs
+ unless $objs then
$objs = []
- srcs = Dir[File.join(srcdir, "*.{#{SRC_EXT.join(%q{,})}}")]
- for f in srcs
- obj = File.basename(f, ".*") << ".o"
- $objs.push(obj) unless $objs.index(obj)
+ for f in Dir[File.join(srcdir, "*.{#{SRC_EXT.join(%q{,})}}")]
+ $objs.push(File.basename(f, ".*") << "." << $OBJEXT)
+ end
+ else
+ for i in $objs
+ i.sub!(/\.o\z/, ".#{$OBJEXT}")
end
- elsif !(srcs = $srcs)
- srcs = $objs.collect {|obj| obj.sub(/\.o\z/, '.c')}
- end
- for i in $objs
- i.sub!(/\.o\z/, ".#{$OBJEXT}")
end
$objs = $objs.join(" ")
@@ -1066,106 +835,80 @@ def create_makefile(target, srcprefix = nil)
dllib = target ? "$(TARGET).#{CONFIG['DLEXT']}" : ""
staticlib = target ? "$(TARGET).#$LIBEXT" : ""
mfile = open("Makefile", "wb")
- mfile.print configuration(srcprefix)
+ mfile.print configuration(srcdir)
mfile.print %{
-libpath = #{$LIBPATH.join(" ")}
LIBPATH = #{libpath}
DEFFILE = #{deffile}
CLEANFILES = #{$cleanfiles.join(' ')}
DISTCLEANFILES = #{$distcleanfiles.join(' ')}
-extout = #{$extout}
-extout_prefix = #{$extout_prefix}
target_prefix = #{target_prefix}
LOCAL_LIBS = #{$LOCAL_LIBS}
LIBS = #{$LIBRUBYARG} #{$libs} #{$LIBS}
-SRCS = #{srcs.collect(&File.method(:basename)).join(' ')}
OBJS = #{$objs}
TARGET = #{target}
DLLIB = #{dllib}
-STATIC_LIB = #{staticlib unless $static.nil?}
-
+STATIC_LIB = #{staticlib}
}
- install_dirs.each {|d| mfile.print("%-14s= %s\n" % d) if /^[[:upper:]]/ =~ d[0]}
- n = ($extout ? '$(RUBYARCHDIR)/' : '') + '$(TARGET).'
+ if $extmk
+ mfile.print %{
+RUBYCOMMONDIR = $(rubylibdir)
+RUBYLIBDIR = $(rubylibdir)$(target_prefix)
+RUBYARCHDIR = $(archdir)$(target_prefix)
+}
+ else
+ mfile.print %{
+RUBYCOMMONDIR = $(sitedir)$(target_prefix)
+RUBYLIBDIR = $(sitelibdir)$(target_prefix)
+RUBYARCHDIR = $(sitearchdir)$(target_prefix)
+}
+ end
mfile.print %{
-TARGET_SO = #{($extout ? '$(RUBYARCHDIR)/' : '')}$(DLLIB)
-CLEANLIBS = #{n}#{CONFIG['DLEXT']} #{n}il? #{n}tds #{n}map
-CLEANOBJS = *.#{$OBJEXT} *.#{$LIBEXT} *.s[ol] *.pdb *.exp *.bak
+CLEANLIBS = "$(TARGET).{lib,exp,il?,tds,map}" $(DLLIB)
+CLEANOBJS = "*.{#{$OBJEXT},#{$LIBEXT},s[ol],pdb,bak}"
-all: #{target ? $extout ? "install" : "$(DLLIB)" : "Makefile"}
-static: $(STATIC_LIB)#{$extout ? " install-rb" : ""}
+all: #{target ? "$(DLLIB)" : "Makefile"}
+static: $(STATIC_LIB)
}
mfile.print CLEANINGS
dirs = []
- mfile.print "install: install-so install-rb\n\n"
- sodir = dir = "$(RUBYARCHDIR)"
- mfile.print("install-so: #{dir}\n")
- if target
+ if not $static and target
+ dirs << (dir = "$(RUBYARCHDIR)")
+ mfile.print("install: #{dir}\n")
f = "$(DLLIB)"
dest = "#{dir}/#{f}"
- mfile.print "install-so: #{dest}\n"
- unless $extout
- mfile.print "#{dest}: #{f}\n"
- if (sep = config_string('BUILD_FILE_SEPARATOR'))
- f.gsub!("/", sep)
- dir.gsub!("/", sep)
- sep = ":/="+sep
- f.gsub!(/(\$\(\w+)(\))/) {$1+sep+$2}
- f.gsub!(/(\$\{\w+)(\})/) {$1+sep+$2}
- dir.gsub!(/(\$\(\w+)(\))/) {$1+sep+$2}
- dir.gsub!(/(\$\{\w+)(\})/) {$1+sep+$2}
- end
- mfile.print "\t$(INSTALL_PROG) #{f} #{dir}\n"
- end
+ mfile.print "install: #{dest}\n"
+ mfile.print "#{dest}: #{f} #{dir}\n\t@$(INSTALL_PROG) #{f} #{dir}\n"
end
- mfile.print("install-rb: pre-install-rb install-rb-default\n")
- mfile.print("install-rb-default: pre-install-rb-default\n")
- mfile.print("pre-install-rb: Makefile\n")
- mfile.print("pre-install-rb-default: Makefile\n")
- for sfx, i in [["-default", [["lib/**/*.rb", "$(RUBYLIBDIR)", "lib"]]], ["", $INSTALLFILES]]
+ for i in [[["lib/**/*.rb", "$(RUBYLIBDIR)", "lib"]], $INSTALLFILES]
files = install_files(mfile, i, nil, srcprefix) or next
for dir, *files in files
unless dirs.include?(dir)
dirs << dir
- mfile.print "pre-install-rb#{sfx}: #{dir}\n"
+ mfile.print("install: #{dir}\n")
end
files.each do |f|
dest = "#{dir}/#{File.basename(f)}"
- mfile.print("install-rb#{sfx}: #{dest}\n")
- mfile.print("#{dest}: #{f}\n\t$(#{$extout ? 'COPY' : 'INSTALL_DATA'}) ")
- sep = config_string('BUILD_FILE_SEPARATOR')
- if sep
- f = f.gsub("/", sep)
- sep = ":/="+sep
- f = f.gsub(/(\$\(\w+)(\))/) {$1+sep+$2}
- f = f.gsub(/(\$\{\w+)(\})/) {$1+sep+$2}
- else
- sep = ""
- end
- mfile.print("#{f} $(@D#{sep})\n")
+ mfile.print("install: #{dest}\n")
+ mfile.print("#{dest}: #{f} #{dir}\n\t@$(INSTALL_DATA) #{f} #{dir}\n")
end
end
end
- dirs.unshift(sodir) if target and !dirs.include?(sodir)
- dirs.each {|dir| mfile.print "#{dir}:\n\t$(MAKEDIRS) $@\n"}
-
- mfile.print <<-SITEINSTALL
-
-site-install: site-install-so site-install-rb
-site-install-so: install-so
-site-install-rb: install-rb
+ if dirs.empty?
+ mfile.print("install:\n")
+ else
+ dirs.each {|dir| mfile.print "#{dir}:\n\t@$(MAKEDIRS) #{dir}\n"}
+ end
- SITEINSTALL
+ mfile.print "\nsite-install: install\n\n"
return unless target
- mfile.puts SRC_EXT.collect {|ext| ".path.#{ext} = $(VPATH)"} if $nmake == ?b
mfile.print ".SUFFIXES: .#{SRC_EXT.join(' .')} .#{$OBJEXT}\n"
mfile.print "\n"
- CXX_EXT.each do |ext|
+ %w[cc cpp cxx C].each do |ext|
COMPILE_RULES.each do |rule|
mfile.printf(rule, ext, $OBJEXT)
mfile.printf("\n\t%s\n\n", COMPILE_CXX)
@@ -1178,17 +921,18 @@ site-install-rb: install-rb
end
end
- mfile.print "$(RUBYARCHDIR)/" if $extout
- mfile.print "$(DLLIB): ", (makedef ? "$(DEFFILE) " : ""), "$(OBJS)\n\t"
+ if makedef
+ mfile.print "$(DLLIB): $(OBJS) $(DEFFILE)\n\t"
+ else
+ mfile.print "$(DLLIB): $(OBJS)\n\t"
+ end
mfile.print "@-$(RM) $@\n\t"
- mfile.print "@-$(MAKEDIRS) $(@D)\n\t" if $extout
+ mfile.print "@-$(RM) $(TARGET).lib\n\t" if $mswin
mfile.print LINK_SO, "\n\n"
- unless $static.nil?
- mfile.print "$(STATIC_LIB): $(OBJS)\n\t"
- mfile.print "$(AR) #{config_string('ARFLAGS') || 'cru '}$@ $(OBJS)"
- config_string('RANLIB') do |ranlib|
- mfile.print "\n\t@-#{ranlib} $(DLLIB) 2> /dev/null || true"
- end
+ mfile.print "$(STATIC_LIB): $(OBJS)\n\t"
+ mfile.print "$(AR) #{config_string('ARFLAGS') || 'cru '}$@ $(OBJS)"
+ if ranlib = config_string('RANLIB')
+ mfile.print "\n\t@-#{ranlib} $(DLLIB) 2> /dev/null || true"
end
mfile.print "\n\n"
if makedef
@@ -1198,72 +942,21 @@ site-install-rb: install-rb
depend = File.join(srcdir, "depend")
if File.exist?(depend)
- suffixes = []
- depout = []
open(depend, "r") do |dfile|
mfile.printf "###\n"
- cont = implicit = nil
- impconv = proc do
- COMPILE_RULES.each {|rule| depout << (rule % implicit[0]) << implicit[1]}
- implicit = nil
- end
- ruleconv = proc do |line|
- if implicit
- if /\A\t/ =~ line
- implicit[1] << line
- next
- else
- impconv[]
- end
- end
- if m = /\A\.(\w+)\.(\w+)(?:\s*:)/.match(line)
- suffixes << m[1] << m[2]
- implicit = [[m[1], m[2]], [m.post_match]]
- next
- elsif RULE_SUBST and /\A[$\w][^#]*:/ =~ line
- line.gsub!(%r"(\s)(?!\.)([^$(){}+=:\s\/\\,]+)(?=\s|\z)") {$1 + RULE_SUBST % $2}
- end
- depout << line
- end
while line = dfile.gets()
line.gsub!(/\.o\b/, ".#{$OBJEXT}")
+ line.gsub!(/(\s)([^\s\/]+\.[ch])/, '\1{$(srcdir)}\2') if $nmake
line.gsub!(/\$\(hdrdir\)\/config.h/, $config_h) if $config_h
- if /(?:^|[^\\])(?:\\\\)*\\$/ =~ line
- (cont ||= []) << line
- next
- elsif cont
- line = (cont << line).join
- cont = nil
- end
- ruleconv.call(line)
- end
- if cont
- ruleconv.call(cont.join)
- elsif implicit
- impconv.call
+ mfile.print line
end
end
- unless suffixes.empty?
- mfile.print ".SUFFIXES: .", suffixes.uniq.join(" ."), "\n\n"
- end
- mfile.print depout
- else
- headers = %w[ruby.h defines.h]
- if RULE_SUBST
- headers.each {|h| h.sub!(/.*/) {|*m| RULE_SUBST % m}}
- end
- headers << $config_h if $config_h
- mfile.print "$(OBJS): ", headers.join(' '), "\n"
end
-
- $makefile_created = true
ensure
mfile.close if mfile
end
def init_mkmf(config = CONFIG)
- $makefile_created = false
- $arg_config = []
$enable_shared = config['ENABLE_SHARED'] == 'yes'
$defs = []
$CFLAGS = with_config("cflags", arg_config("CFLAGS", config["CFLAGS"])).dup
@@ -1282,7 +975,6 @@ def init_mkmf(config = CONFIG)
$INSTALLFILES = nil
$objs = nil
- $srcs = nil
$libs = ""
if $enable_shared or Config.expand(config["LIBRUBY"].dup) != Config.expand(config["LIBRUBY_A"].dup)
$LIBRUBYARG = config['LIBRUBYARG']
@@ -1290,31 +982,12 @@ def init_mkmf(config = CONFIG)
$LOCAL_LIBS = ""
- $cleanfiles = config_string('CLEANFILES') {|s| Shellwords.shellwords(s)} || []
- $distcleanfiles = config_string('DISTCLEANFILES') {|s| Shellwords.shellwords(s)} || []
-
- $extout ||= nil
- $extout_prefix ||= nil
+ $cleanfiles = []
+ $distcleanfiles = []
- $arg_config.clear
dir_config("opt")
end
-FailedMessage = <<MESSAGE
-Could not create Makefile due to some reason, probably lack of
-necessary libraries and/or headers. Check the mkmf.log file for more
-details. You may need configuration options.
-
-Provided configuration options:
-MESSAGE
-
-def mkmf_failed(path)
- unless $makefile_created or File.exist?("Makefile")
- opts = $arg_config.collect {|t, n| "\t#{t}#{"=#{n}" if n}\n"}
- abort "*** #{path} failed ***\n" + FailedMessage + opts.join
- end
-end
-
init_mkmf
$make = with_config("make-prog", ENV["MAKE"] || "make")
@@ -1330,15 +1003,8 @@ end
Config::CONFIG["srcdir"] = CONFIG["srcdir"] =
$srcdir = arg_config("--srcdir", File.dirname($0))
$configure_args["--topsrcdir"] ||= $srcdir
-if $curdir = arg_config("--curdir")
- Config.expand(curdir = $curdir.dup)
-else
- curdir = $curdir = "."
-end
-unless File.expand_path(Config::CONFIG["topdir"]) == File.expand_path(curdir)
- CONFIG["topdir"] = $curdir
- Config::CONFIG["topdir"] = curdir
-end
+Config::CONFIG["topdir"] = CONFIG["topdir"] =
+ $curdir = arg_config("--curdir", Dir.pwd)
$configure_args["--topdir"] ||= $curdir
$ruby = arg_config("--ruby", File.join(Config::CONFIG["bindir"], CONFIG["ruby_install_name"]))
@@ -1360,7 +1026,6 @@ COMMON_HEADERS = (hdr.join("\n") unless hdr.empty?)
COMMON_LIBS = config_string('COMMON_LIBS', &split) || []
COMPILE_RULES = config_string('COMPILE_RULES', &split) || %w[.%s.%s:]
-RULE_SUBST = config_string('RULE_SUBST')
COMPILE_C = config_string('COMPILE_C') || '$(CC) $(CFLAGS) $(CPPFLAGS) -c $<'
COMPILE_CXX = config_string('COMPILE_CXX') || '$(CXX) $(CXXFLAGS) $(CPPFLAGS) -c $<'
TRY_LINK = config_string('TRY_LINK') ||
@@ -1368,27 +1033,22 @@ TRY_LINK = config_string('TRY_LINK') ||
"$(CFLAGS) $(src) $(LIBPATH) $(LDFLAGS) $(ARCH_FLAG) $(LOCAL_LIBS) $(LIBS)"
LINK_SO = config_string('LINK_SO') ||
if CONFIG["DLEXT"] == $OBJEXT
- "ld $(DLDFLAGS) -r -o $@ $(OBJS)\n"
+ "ld $(DLDFLAGS) -r -o $(DLLIB) $(OBJS)\n"
else
- "$(LDSHARED) $(DLDFLAGS) $(LIBPATH) #{OUTFLAG}$@ " \
+ "$(LDSHARED) $(DLDFLAGS) $(LIBPATH) #{OUTFLAG}$(DLLIB) " \
"$(OBJS) $(LOCAL_LIBS) $(LIBS)"
end
LIBPATHFLAG = config_string('LIBPATHFLAG') || ' -L"%s"'
RPATHFLAG = config_string('RPATHFLAG') || ''
LIBARG = config_string('LIBARG') || '-l%s'
-sep = File::ALT_SEPARATOR ? ":/=#{File::ALT_SEPARATOR}" : ''
CLEANINGS = "
clean:
- @-$(RM) $(CLEANLIBS#{sep}) $(CLEANOBJS#{sep}) $(CLEANFILES#{sep})
+ @$(RM) $(CLEANLIBS) $(CLEANOBJS) $(CLEANFILES)
distclean: clean
- @-$(RM) Makefile extconf.h conftest.* mkmf.log
- @-$(RM) core ruby$(EXEEXT) *~ $(DISTCLEANFILES#{sep})
+ @$(RM) Makefile extconf.h conftest.* mkmf.log
+ @$(RM) core ruby$(EXEEXT) *~ $(DISTCLEANFILES)
realclean: distclean
"
-
-if not $extmk and /\A(extconf|makefile).rb\z/ =~ File.basename($0)
- END {mkmf_failed($0)}
-end
diff --git a/lib/monitor.rb b/lib/monitor.rb
index 6bd14d0789..a573af2bae 100644
--- a/lib/monitor.rb
+++ b/lib/monitor.rb
@@ -87,11 +87,11 @@ module MonitorMixin
class Timeout < Exception; end
def wait(timeout = nil)
- @monitor.instance_eval {mon_check_owner()}
+ @monitor.__send__(:mon_check_owner)
timer = create_timer(timeout)
Thread.critical = true
- count = @monitor.instance_eval {mon_exit_for_cond()}
+ count = @monitor.__send__(:mon_exit_for_cond)
@waiters.push(Thread.current)
begin
@@ -107,7 +107,7 @@ module MonitorMixin
if @waiters.include?(Thread.current) # interrupted?
@waiters.delete(Thread.current)
end
- @monitor.instance_eval {mon_enter_for_cond(count)}
+ @monitor.__send__(:mon_enter_for_cond, count)
Thread.critical = false
end
end
@@ -125,7 +125,7 @@ module MonitorMixin
end
def signal
- @monitor.instance_eval {mon_check_owner()}
+ @monitor.__send__(:mon_check_owner)
Thread.critical = true
t = @waiters.shift
t.wakeup if t
@@ -134,7 +134,7 @@ module MonitorMixin
end
def broadcast
- @monitor.instance_eval {mon_check_owner()}
+ @monitor.__send__(:mon_check_owner)
Thread.critical = true
for t in @waiters
t.wakeup
@@ -172,7 +172,7 @@ module MonitorMixin
def self.extend_object(obj)
super(obj)
- obj.instance_eval {mon_initialize()}
+ obj.__send__(:mon_initialize)
end
#
diff --git a/lib/net/http.rb b/lib/net/http.rb
index 98e16c9294..39c58dd521 100644
--- a/lib/net/http.rb
+++ b/lib/net/http.rb
@@ -1,12 +1,10 @@
#
# = net/http.rb
#
-# Copyright (c) 1999-2005 Yukihiro Matsumoto
-# Copyright (c) 1999-2005 Minero Aoki
-# Copyright (c) 2001 GOTOU Yuuzou
+# Copyright (c) 1999-2003 Yukihiro Matsumoto
+# Copyright (c) 1999-2003 Minero Aoki
#
-# Written and maintained by Minero Aoki <aamine@loveruby.net>.
-# HTTPS support added by GOTOU Yuuzou <gotoyuzo@notwork.org>.
+# Written & maintained by Minero Aoki <aamine@loveruby.net>.
#
# This file is derived from "http-access.rb".
#
@@ -28,7 +26,8 @@
require 'net/protocol'
require 'uri'
-module Net #:nodoc:
+
+module Net # :nodoc:
# :stopdoc:
class HTTPBadResponse < StandardError; end
@@ -46,66 +45,31 @@ module Net #:nodoc:
#
# === Getting Document From WWW Server
#
- # Example #1: Simple GET+print
+ # (formal version)
#
# require 'net/http'
- # Net::HTTP.get_print 'www.example.com', '/index.html'
+ # Net::HTTP.start('www.example.com', 80) { |http|
+ # response = http.get('/index.html')
+ # puts response.body
+ # }
#
- # Example #2: Simple GET+print by URL
+ # (shorter version)
#
# require 'net/http'
- # require 'uri'
- # Net::HTTP.get_print URI.parse('http://www.example.com/index.html')
+ # Net::HTTP.get_print 'www.example.com', '/index.html'
#
- # Example #3: More generic GET+print
+ # or
#
# require 'net/http'
# require 'uri'
- #
- # url = URI.parse('http://www.example.com/index.html')
- # res = Net::HTTP.start(url.host, url.port) {|http|
- # http.get('/index.html')
- # }
- # puts res.body
- #
- # Example #4: More generic GET+print
- #
- # require 'net/http'
- #
- # url = URI.parse('http://www.example.com/index.html')
- # req = Net::HTTP::Get.new(url.path)
- # res = Net::HTTP.start(url.host, url.port) {|http|
- # http.request(req)
- # }
- # puts res.body
+ # Net::HTTP.get_print URI.parse('http://www.example.com/index.html')
#
# === Posting Form Data
#
# require 'net/http'
- # require 'uri'
- #
- # #1: Simple POST
- # res = Net::HTTP.post_form(URI.parse('http://www.example.com/search.cgi'),
- # {'q'=>'ruby', 'max'=>'50'})
- # puts res.body
- #
- # #2: POST with basic authentication
- # res = Net::HTTP.post_form(URI.parse('http://jack:pass@www.example.com/todo.cgi'),
- # {'from'=>'2005-01-01', 'to'=>'2005-03-31'})
- # puts res.body
- #
- # #3: Detailed control
- # url = URI.parse('http://www.example.com/todo.cgi')
- # req = Net::HTTP::Post.new(url.path)
- # req.basic_auth 'jack', 'pass'
- # req.set_form_data({'from'=>'2005-01-01', 'to'=>'2005-03-31'}, ';')
- # res = Net::HTTP.new(url.host, url.port).start { http.request(req) }
- # case res
- # when Net::HTTPSuccess, Net::HTTPRedirection
- # # OK
- # else
- # res.error!
- # end
+ # Net::HTTP.start('some.www.server', 80) { |http|
+ # response = http.post('/cgi-bin/search.rb', 'query=ruby')
+ # }
#
# === Accessing via Proxy
#
@@ -119,7 +83,7 @@ module Net #:nodoc:
# proxy_port = 8080
# :
# Net::HTTP::Proxy(proxy_addr, proxy_port).start('www.example.com') {|http|
- # # always connect to your.proxy.addr:8080
+ # # always connect to your.proxy.addr:8080
# :
# }
#
@@ -154,7 +118,7 @@ module Net #:nodoc:
# require 'net/http'
# require 'uri'
#
- # def fetch(uri_str, limit = 10)
+ # def fetch( uri_str, limit = 10 )
# # You should choose better exception.
# raise ArgumentError, 'HTTP redirect too deep' if limit == 0
#
@@ -185,78 +149,9 @@ module Net #:nodoc:
# print response.body
# }
#
- # === HTTP Request Classes
- #
- # Here is HTTP request class hierarchy.
- #
- # Net::HTTPRequest
- # Net::HTTP::Get
- # Net::HTTP::Head
- # Net::HTTP::Post
- # Net::HTTP::Put
- # Net::HTTP::Proppatch
- # Net::HTTP::Lock
- # Net::HTTP::Unlock
- # Net::HTTP::Options
- # Net::HTTP::Propfind
- # Net::HTTP::Delete
- # Net::HTTP::Move
- # Net::HTTP::Copy
- # Net::HTTP::Mkcol
- # Net::HTTP::Trace
- #
# === HTTP Response Classes
#
- # Here is HTTP response class hierarchy.
- # All classes are defined in Net module.
- #
- # HTTPResponse
- # HTTPUnknownResponse
- # HTTPInformation # 1xx
- # HTTPContinue # 100
- # HTTPSwitchProtocl # 101
- # HTTPSuccess # 2xx
- # HTTPOK # 200
- # HTTPCreated # 201
- # HTTPAccepted # 202
- # HTTPNonAuthoritativeInformation # 203
- # HTTPNoContent # 204
- # HTTPResetContent # 205
- # HTTPPartialContent # 206
- # HTTPRedirection # 3xx
- # HTTPMultipleChoice # 300
- # HTTPMovedPermanently # 301
- # HTTPFound # 302
- # HTTPSeeOther # 303
- # HTTPNotModified # 304
- # HTTPUseProxy # 305
- # HTTPTemporaryRedirect # 307
- # HTTPClientError # 4xx
- # HTTPBadRequest # 400
- # HTTPUnauthorized # 401
- # HTTPPaymentRequired # 402
- # HTTPForbidden # 403
- # HTTPNotFound # 404
- # HTTPMethodNotAllowed # 405
- # HTTPNotAcceptable # 406
- # HTTPProxyAuthenticationRequired # 407
- # HTTPRequestTimeOut # 408
- # HTTPConflict # 409
- # HTTPGone # 410
- # HTTPLengthRequired # 411
- # HTTPPreconditionFailed # 412
- # HTTPRequestEntityTooLarge # 413
- # HTTPRequestURITooLong # 414
- # HTTPUnsupportedMediaType # 415
- # HTTPRequestedRangeNotSatisfiable # 416
- # HTTPExpectationFailed # 417
- # HTTPServerError # 5xx
- # HTTPInternalServerError # 500
- # HTTPNotImplemented # 501
- # HTTPBadGateway # 502
- # HTTPServiceUnavailable # 503
- # HTTPGatewayTimeOut # 504
- # HTTPVersionNotSupported # 505
+ # TODO: write me.
#
# == Switching Net::HTTP versions
#
@@ -265,13 +160,13 @@ module Net #:nodoc:
# allows you to use 1.2 features again.
#
# # example
- # Net::HTTP.start {|http1| ...(http1 has 1.2 features)... }
+ # Net::HTTP.start { |http1| ...(http1 has 1.2 features)... }
#
# Net::HTTP.version_1_1
- # Net::HTTP.start {|http2| ...(http2 has 1.1 features)... }
+ # Net::HTTP.start { |http2| ...(http2 has 1.1 features)... }
#
# Net::HTTP.version_1_2
- # Net::HTTP.start {|http3| ...(http3 has 1.2 features)... }
+ # Net::HTTP.start { |http3| ...(http3 has 1.2 features)... }
#
# This function is NOT thread-safe.
#
@@ -280,7 +175,7 @@ module Net #:nodoc:
# :stopdoc:
Revision = %q$Revision$.split[1]
HTTPVersion = '1.1'
- @newimpl = true # for backward compatability
+ @@newimpl = true # for backward compatability
# :startdoc:
# Turns on net/http 1.2 (ruby 1.8) features.
@@ -292,25 +187,25 @@ module Net #:nodoc:
# Net::HTTP.version_1_2
#
def HTTP.version_1_2
- @newimpl = true
+ @@newimpl = true
end
# Turns on net/http 1.1 (ruby 1.6) features.
# Defaults to OFF in ruby 1.8.
def HTTP.version_1_1
- @newimpl = false
+ @@newimpl = false
end
# true if net/http is in version 1.2 mode.
# Defaults to true.
def HTTP.version_1_2?
- @newimpl
+ @@newimpl
end
# true if net/http is in version 1.1 compatible mode.
# Defaults to true.
def HTTP.version_1_1?
- not @newimpl
+ not @@newimpl
end
class << HTTP
@@ -318,6 +213,12 @@ module Net #:nodoc:
alias is_version_1_2? version_1_2? #:nodoc:
end
+ def HTTP.setimplversion(obj) #:nodoc:
+ f = @@newimpl
+ obj.instance_eval { @newimpl = f }
+ end
+ private_class_method :setimplversion
+
#
# short cut methods
#
@@ -331,13 +232,19 @@ module Net #:nodoc:
#
# or:
#
- # Net::HTTP.get_print 'www.example.com', '/index.html'
+ # Net::HTTP.get_print('www.example.com', '/index.html')
#
- def HTTP.get_print(uri_or_host, path = nil, port = nil)
- get_response(uri_or_host, path, port) {|res|
- res.read_body do |chunk|
- $stdout.print chunk
- end
+ def HTTP.get_print(arg1, arg2 = nil, port = nil)
+ if arg2
+ addr, path = arg1, arg2
+ else
+ uri = arg1
+ addr = uri.host
+ path = uri.request_uri
+ port = uri.port
+ end
+ new(addr, port || HTTP.default_port).start {|http|
+ http.get path, nil, $stdout
}
nil
end
@@ -352,8 +259,8 @@ module Net #:nodoc:
#
# print Net::HTTP.get('www.example.com', '/index.html')
#
- def HTTP.get(uri_or_host, path = nil, port = nil)
- get_response(uri_or_host, path, port).body
+ def HTTP.get(arg1, arg2 = nil, arg3 = nil)
+ get_response(arg1,arg2,arg3).body
end
# Send a GET request to the target and return the response
@@ -368,43 +275,29 @@ module Net #:nodoc:
# res = Net::HTTP.get_response('www.example.com', '/index.html')
# print res.body
#
- def HTTP.get_response(uri_or_host, path = nil, port = nil, &block)
- if path
- host = uri_or_host
- new(host, port || HTTP.default_port).start {|http|
- return http.request_get(path, &block)
- }
+ def HTTP.get_response(arg1, arg2 = nil, arg3 = nil)
+ if arg2
+ get_by_path(arg1, arg2, arg3)
else
- uri = uri_or_host
- new(uri.host, uri.port).start {|http|
- return http.request_get(uri.request_uri, &block)
- }
+ get_by_uri(arg1)
end
end
- # Posts HTML form data to the +URL+.
- # Form data must be represented as a Hash of String to String, e.g:
- #
- # { "cmd" => "search", "q" => "ruby", "max" => "50" }
- #
- # This method also does Basic Authentication iff +URL+.user exists.
- #
- # Example:
- #
- # require 'net/http'
- # require 'uri'
- #
- # HTTP.post_form URI.parse('http://www.example.com/search.cgi'),
- # { "q" => "ruby", "max" => "50" }
- #
- def HTTP.post_form(url, params)
- req = Post.new(url.path)
- req.form_data = params
- req.basic_auth url.user, url.password if url.user
- new(url.host, url.port).start {|http|
- http.request(req)
+ def HTTP.get_by_path(addr, path, port = nil) #:nodoc:
+ new(addr, port || HTTP.default_port).start {|http|
+ return http.request(Get.new(path))
}
end
+ private_class_method :get_by_path
+
+ def HTTP.get_by_uri(uri) #:nodoc:
+ # Should we allow this?
+ # uri = URI.parse(uri) unless uri.respond_to?(:host)
+ new(uri.host, uri.port).start {|http|
+ return http.request(Get.new(uri.request_uri))
+ }
+ end
+ private_class_method :get_by_uri
#
# HTTP session management
@@ -412,47 +305,35 @@ module Net #:nodoc:
# The default port to use for HTTP requests; defaults to 80.
def HTTP.default_port
- http_default_port()
- end
-
- # The default port to use for HTTP requests; defaults to 80.
- def HTTP.http_default_port
80
end
- # The default port to use for HTTPS requests; defaults to 443.
- def HTTP.https_default_port
- 443
- end
-
def HTTP.socket_type #:nodoc: obsolete
- BufferedIO
- end
-
- # creates a new Net::HTTP object and opens its TCP connection and
- # HTTP session. If the optional block is given, the newly
- # created Net::HTTP object is passed to it and closed when the
- # block finishes. In this case, the return value of this method
- # is the return value of the block. If no block is given, the
- # return value of this method is the newly created Net::HTTP object
- # itself, and the caller is responsible for closing it upon completion.
- def HTTP.start(address, port = nil, p_addr = nil, p_port = nil, p_user = nil, p_pass = nil, &block) # :yield: +http+
- new(address, port, p_addr, p_port, p_user, p_pass).start(&block)
+ InternetMessageIO
end
class << HTTP
+ # creates a new Net::HTTP object and opens its TCP connection and
+ # HTTP session. If the optional block is given, the newly
+ # created Net::HTTP object is passed to it and closed when the
+ # block finishes. In this case, the return value of this method
+ # is the return value of the block. If no block is given, the
+ # return value of this method is the newly created Net::HTTP object
+ # itself, and the caller is responsible for closing it upon completion.
+ def start(address, port = nil, p_addr = nil, p_port = nil, p_user = nil, p_pass = nil, &block) # :yield: +http+
+ new(address, port, p_addr, p_port, p_user, p_pass).start(&block)
+ end
+
alias newobj new
- end
- # Creates a new Net::HTTP object.
- # If +proxy_addr+ is given, creates an Net::HTTP object with proxy support.
- # This method does not open the TCP connection.
- def HTTP.new(address, port = nil, p_addr = nil, p_port = nil, p_user = nil, p_pass = nil)
- h = Proxy(p_addr, p_port, p_user, p_pass).newobj(address, port)
- h.instance_eval {
- @newimpl = ::Net::HTTP.version_1_2?
- }
- h
+ # Creates a new Net::HTTP object.
+ # If +proxy_addr+ is given, creates an Net::HTTP object with proxy support.
+ # This method does not open the TCP connection.
+ def new(address, port = nil, p_addr = nil, p_port = nil, p_user = nil, p_pass = nil)
+ obj = Proxy(p_addr, p_port, p_user, p_pass).newobj(address, port)
+ setimplversion obj
+ obj
+ end
end
# Creates a new Net::HTTP object for the specified +address+.
@@ -460,16 +341,17 @@ module Net #:nodoc:
def initialize(address, port = nil)
@address = address
@port = (port || HTTP.default_port)
+
@curr_http_version = HTTPVersion
@seems_1_0_server = false
@close_on_empty_response = false
@socket = nil
@started = false
- @open_timeout = nil
+
+ @open_timeout = 30
@read_timeout = 60
+
@debug_output = nil
- @use_ssl = false
- @ssl_context = nil
end
def inspect
@@ -521,13 +403,6 @@ module Net #:nodoc:
attr_accessor :close_on_empty_response
- # returns true if use SSL/TLS with HTTP.
- def use_ssl?
- @use_ssl
- end
-
- alias use_ssl use_ssl? #:nodoc: obsolete
-
# Opens TCP connection and HTTP session.
#
# When this method is called with block, gives a HTTP object
@@ -552,45 +427,14 @@ module Net #:nodoc:
end
def do_start
- connect
+ @socket = self.class.socket_type.open(conn_address(), conn_port(),
+ @open_timeout, @read_timeout,
+ @debug_output)
+ on_connect
@started = true
end
private :do_start
- def connect
- D "opening connection to #{conn_address()}..."
- s = timeout(@open_timeout) { TCPSocket.open(conn_address(), conn_port()) }
- D "opened"
- if use_ssl?
- unless @ssl_context.verify_mode
- warn "warning: peer certificate won't be verified in this SSL session"
- @ssl_context.verify_mode = OpenSSL::SSL::VERIFY_NONE
- end
- s = OpenSSL::SSL::SSLSocket.new(s, @ssl_context)
- s.sync_close = true
- end
- @socket = BufferedIO.new(s)
- @socket.read_timeout = @read_timeout
- @socket.debug_output = @debug_output
- if use_ssl?
- if proxy?
- @socket.writeline sprintf('CONNECT %s:%s HTTP/%s',
- @address, @port, HTTPVersion)
- @socket.writeline "Host: #{@address}:#{@port}"
- if proxy_user
- credential = ["#{proxy_user}:#{proxy_pass}"].pack('m')
- credential.delete!("\r\n")
- @socket.writeline "Proxy-Authorization: Basic #{credential}"
- end
- @socket.writeline ''
- HTTPResponse.read_new(@socket).value
- end
- s.connect
- end
- on_connect
- end
- private :connect
-
def on_connect
end
private :on_connect
@@ -665,7 +509,7 @@ module Net #:nodoc:
attr_reader :proxy_pass
end
- # True if self is a HTTP proxy class.
+ # True if self is a HTTP proxy class
def proxy?
self.class.proxy_class?
end
@@ -698,11 +542,11 @@ module Net #:nodoc:
# without proxy
def conn_address
- address()
+ address
end
def conn_port
- port()
+ port
end
def edit_path(path)
@@ -721,7 +565,7 @@ module Net #:nodoc:
end
def edit_path(path)
- use_ssl? ? path : "http://#{addr_port()}#{path}"
+ 'http://' + addr_port() + path
end
end
@@ -814,8 +658,14 @@ module Net #:nodoc:
# the socket. Note that in this case, the returned response
# object will *not* contain a (meaningful) body.
#
- # +dest+ argument is obsolete.
- # It still works but you must not use it.
+ # +dest+ is an alternative method of collecting the body. It
+ # must be an object responding to the "<<" operator (such as
+ # a String or an Array). Each fragment of the entity body
+ # will be "<<"-ed in turn onto +dest+ if provided, and it will
+ # also become the body of the returned response object.
+ #
+ # You must *not* provide both +dest+ and a block; doing so
+ # will result in an ArgumentError.
#
# In version 1.1, this method might raise an exception for
# 3xx (redirect). In this case you can get an HTTPResponse object
@@ -855,66 +705,6 @@ module Net #:nodoc:
res
end
- # Sends a PROPPATCH request to the +path+ and gets a response,
- # as an HTTPResponse object.
- def proppatch(path, body, initheader = nil)
- request(Proppatch.new(path, initheader), body)
- end
-
- # Sends a LOCK request to the +path+ and gets a response,
- # as an HTTPResponse object.
- def lock(path, body, initheader = nil)
- request(Lock.new(path, initheader), body)
- end
-
- # Sends a UNLOCK request to the +path+ and gets a response,
- # as an HTTPResponse object.
- def unlock(path, body, initheader = nil)
- request(Unlock.new(path, initheader), body)
- end
-
- # Sends a OPTIONS request to the +path+ and gets a response,
- # as an HTTPResponse object.
- def options(path, initheader = nil)
- request(Options.new(path, initheader))
- end
-
- # Sends a PROPFIND request to the +path+ and gets a response,
- # as an HTTPResponse object.
- def propfind(path, body = nil, initheader = {'Depth' => '0'})
- request(Propfind.new(path, initheader), body)
- end
-
- # Sends a DELETE request to the +path+ and gets a response,
- # as an HTTPResponse object.
- def delete(path, initheader = {'Depth' => 'Infinity'})
- request(Delete.new(path, initheader))
- end
-
- # Sends a MOVE request to the +path+ and gets a response,
- # as an HTTPResponse object.
- def move(path, initheader = nil)
- request(Move.new(path, initheader))
- end
-
- # Sends a COPY request to the +path+ and gets a response,
- # as an HTTPResponse object.
- def copy(path, initheader = nil)
- request(Copy.new(path, initheader))
- end
-
- # Sends a MKCOL request to the +path+ and gets a response,
- # as an HTTPResponse object.
- def mkcol(path, body = nil, initheader = nil)
- request(Mkcol.new(path, initheader), body)
- end
-
- # Sends a TRACE request to the +path+ and gets a response,
- # as an HTTPResponse object.
- def trace(path, initheader = nil)
- request(Trace.new(path, initheader))
- end
-
# Sends a GET request to the +path+ and gets a response,
# as an HTTPResponse object.
#
@@ -1034,17 +824,14 @@ module Net #:nodoc:
}
end
if proxy_user()
- unless use_ssl?
- req.proxy_basic_auth proxy_user(), proxy_pass()
- end
+ req.proxy_basic_auth proxy_user(), proxy_pass()
end
- req.set_body_internal body
begin_transport req
- req.exec @socket, @curr_http_version, edit_path(req.path)
+ req.exec @socket, @curr_http_version, edit_path(req.path), body
begin
res = HTTPResponse.read_new(@socket)
- end while res.kind_of?(HTTPContinue)
+ end while HTTPContinue === res
res.reading_body(@socket, req.response_body_permitted?) {
yield res if block_given?
}
@@ -1057,7 +844,8 @@ module Net #:nodoc:
def begin_transport(req)
if @socket.closed?
- connect
+ @socket.reopen @open_timeout
+ on_connect
end
if @seems_1_0_server
req['connection'] ||= 'close'
@@ -1102,11 +890,7 @@ module Net #:nodoc:
private
def addr_port
- if use_ssl?
- address() + (port == HTTP.https_default_port ? '' : ":#{port()}")
- else
- address() + (port == HTTP.http_default_port ? '' : ":#{port()}")
- end
+ address + (port == HTTP.default_port ? '' : ":#{port}")
end
def D(msg)
@@ -1119,7 +903,6 @@ module Net #:nodoc:
HTTPSession = HTTP
-
#
# Header module.
#
@@ -1130,15 +913,6 @@ module Net #:nodoc:
#
module HTTPHeader
- def initialize_http_header(initheader)
- @header = {}
- return unless initheader
- initheader.each do |key, value|
- warn "net/http: warning: duplicated HTTP header: #{key}" if key?(key) and $VERBOSE
- @header[key.downcase] = [value.strip]
- end
- end
-
def size #:nodoc: obsolete
@header.size
end
@@ -1148,94 +922,36 @@ module Net #:nodoc:
# Returns the header field corresponding to the case-insensitive key.
# For example, a key of "Content-Type" might return "text/html"
def [](key)
- a = @header[key.downcase] or return nil
- a.join(', ')
+ @header[key.downcase]
end
# Sets the header field corresponding to the case-insensitive key.
def []=(key, val)
- unless val
- @header.delete key.downcase
- return val
- end
- @header[key.downcase] = Array(val).map {|s| s.to_str }
- end
-
- # [Ruby 1.8.3]
- # Adds header field instead of replace.
- # Second argument +val+ must be a String.
- # See also #[]=, #[] and #get_fields.
- #
- # request.add_field 'X-My-Header', 'a'
- # p request['X-My-Header'] #=> "a"
- # p request.get_fields('X-My-Header') #=> ["a"]
- # request.add_field 'X-My-Header', 'b'
- # p request['X-My-Header'] #=> "a, b"
- # p request.get_fields('X-My-Header') #=> ["a", "b"]
- # request.add_field 'X-My-Header', 'c'
- # p request['X-My-Header'] #=> "a, b, c"
- # p request.get_fields('X-My-Header') #=> ["a", "b", "c"]
- #
- def add_field(key, val)
- if @header.key?(key.downcase)
- @header[key.downcase].concat Array(val)
- else
- @header[key.downcase] = Array(val).dup
- end
- end
-
- # [Ruby 1.8.3]
- # Returns an array of header field strings corresponding to the
- # case-insensitive +key+. This method allows you to get duplicated
- # header fields without any processing. See also #[].
- #
- # p response.get_fields('Set-Cookie')
- # #=> ["session=al98axx; expires=Fri, 31-Dec-1999 23:58:23",
- # "query=rubyscript; expires=Fri, 31-Dec-1999 23:58:23"]
- # p response['Set-Cookie']
- # #=> "session=al98axx; expires=Fri, 31-Dec-1999 23:58:23, query=rubyscript; expires=Fri, 31-Dec-1999 23:58:23"
- #
- def get_fields(key)
- return nil unless @header[key.downcase]
- @header[key.downcase].dup
+ @header[key.downcase] = val
end
# Returns the header field corresponding to the case-insensitive key.
# Returns the default value +args+, or the result of the block, or nil,
# if there's no header field named key. See Hash#fetch
def fetch(key, *args, &block) #:yield: +key+
- a = @header.fetch(key.downcase, *args, &block)
- a.join(', ')
+ @header.fetch(key.downcase, *args, &block)
end
# Iterates for each header names and values.
- def each_header #:yield: +key+, +value+
- @header.each do |k,va|
- yield k, va.join(', ')
- end
+ def each_header(&block) #:yield: +key+, +value+
+ @header.each(&block)
end
alias each each_header
# Iterates for each header names.
- def each_name(&block) #:yield: +key+
+ def each_key(&block) #:yield: +key+
@header.each_key(&block)
end
- alias each_key each_name
-
- # Iterates for each capitalized header names.
- def each_capitalized_name(&block) #:yield: +key+
- @header.each_key do |k|
- yield capitalize(k)
- end
- end
-
# Iterates for each header values.
- def each_value #:yield: +value+
- @header.each_value do |va|
- yield va.join(', ')
- end
+ def each_value(&block) #:yield: +value+
+ @header.each_value(&block)
end
# Removes a header field.
@@ -1254,24 +970,22 @@ module Net #:nodoc:
end
# As for #each_header, except the keys are provided in capitalized form.
- def each_capitalized
+ def canonical_each
@header.each do |k,v|
- yield capitalize(k), v.join(', ')
+ yield canonical(k), v
end
end
- alias canonical_each each_capitalized
-
- def capitalize(name)
- name.split(/-/).map {|s| s.capitalize }.join('-')
+ def canonical( k )
+ k.split(/-/).map {|i| i.capitalize }.join('-')
end
- private :capitalize
+ private :canonical
- # Returns an Array of Range objects which represents Range: header field,
+ # Returns a Range object which represents Range: header field,
# or +nil+ if there is no such header.
def range
- return nil unless @header['range']
- self['Range'].split(/,/).map {|spec|
+ s = @header['range'] or return nil
+ s.split(/,/).map {|spec|
m = /bytes\s*=\s*(\d+)?\s*-\s*(\d+)?/i.match(spec) or
raise HTTPHeaderSyntaxError, "wrong Range: #{spec}"
d1 = m[1].to_i
@@ -1286,57 +1000,44 @@ module Net #:nodoc:
end
# Set Range: header from Range (arg r) or beginning index and
- # length from it (arg idx&len).
- #
- # req.range = (0..1023)
- # req.set_range 0, 1023
- #
- def set_range(r, e = nil)
- unless r
- @header.delete 'range'
- return r
- end
- r = (r...r+e) if e
+ # length from it (arg i&len).
+ def range=(r, fin = nil)
+ r = (r ... r + fin) if fin
case r
when Numeric
- n = r.to_i
- rangestr = (n > 0 ? "0-#{n-1}" : "-#{-n}")
+ s = r > 0 ? "0-#{r - 1}" : "-#{-r}"
when Range
first = r.first
last = r.last
- last -= 1 if r.exclude_end?
+ if r.exclude_end?
+ last -= 1
+ end
+
if last == -1
- rangestr = (first > 0 ? "#{first}-" : "-#{-first}")
+ s = first > 0 ? "#{first}-" : "-#{-first}"
else
- raise HTTPHeaderSyntaxError, 'range.first is negative' if first < 0
- raise HTTPHeaderSyntaxError, 'range.last is negative' if last < 0
- raise HTTPHeaderSyntaxError, 'must be .first < .last' if first > last
- rangestr = "#{first}-#{last}"
+ first >= 0 or raise HTTPHeaderSyntaxError, 'range.first is negative'
+ last > 0 or raise HTTPHeaderSyntaxError, 'range.last is negative'
+ first < last or raise HTTPHeaderSyntaxError, 'must be .first < .last'
+ s = "#{first}-#{last}"
end
else
raise TypeError, 'Range/Integer is required'
end
- @header['range'] = ["bytes=#{rangestr}"]
+
+ @header['range'] = "bytes=#{s}"
r
end
- alias range= set_range
+ alias set_range range=
# Returns an Integer object which represents the Content-Length: header field
# or +nil+ if that field is not provided.
def content_length
- return nil unless key?('Content-Length')
- len = self['Content-Length'].slice(/\d+/) or
- raise HTTPHeaderSyntaxError, 'wrong Content-Length format'
- len.to_i
- end
-
- def content_length=(len)
- unless len
- @header.delete 'content-length'
- return nil
- end
- @header['content-length'] = [len.to_i.to_s]
+ s = @header['content-length'] or return nil
+ m = /\d+/.match(s) or
+ raise HTTPHeaderSyntaxError, 'wrong Content-Length format'
+ m[0].to_i
end
# Returns "true" if the "transfer-encoding" header is present and
@@ -1344,86 +1045,43 @@ module Net #:nodoc:
# the content to be sent in "chunks" without at the outset
# stating the entire content length.
def chunked?
- return false unless @header['transfer-encoding']
- field = self['Transfer-Encoding']
- (/(?:\A|[^\-\w])chunked(?![\-\w])/i =~ field) ? true : false
+ s = @header['transfer-encoding']
+ (s and /(?:\A|[^\-\w])chunked(?:[^\-\w]|\z)/i === s) ? true : false
end
# Returns a Range object which represents Content-Range: header field.
# This indicates, for a partial entity body, where this fragment
# fits inside the full entity body, as range of byte offsets.
def content_range
- return nil unless @header['content-range']
- m = %r<bytes\s+(\d+)-(\d+)/(\d+|\*)>i.match(self['Content-Range']) or
- raise HTTPHeaderSyntaxError, 'wrong Content-Range format'
+ s = @header['content-range'] or return nil
+ m = %r<bytes\s+(\d+)-(\d+)/(?:\d+|\*)>i.match(s) or
+ raise HTTPHeaderSyntaxError, 'wrong Content-Range format'
m[1].to_i .. m[2].to_i + 1
end
- # The length of the range represented in Content-Range: header.
+ # The length of the range represented in Range: header.
def range_length
- r = content_range() or return nil
- r.end - r.begin
- end
-
- def content_type
- "#{main_type()}/#{sub_type()}"
+ r = self.content_range
+ r and (r.end - r.begin)
end
- def main_type
- return nil unless @header['content-type']
- self['Content-Type'].split(';').first.to_s.split('/')[0].to_s.strip
- end
-
- def sub_type
- return nil unless @header['content-type']
- self['Content-Type'].split(';').first.to_s.split('/')[1].to_s.strip
- end
-
- def type_params
- result = {}
- self['Content-Type'].to_s.split(';')[1..-1].each do |param|
- k, v = *param.split('=', 2)
- result[k.strip] = v.strip
- end
- result
- end
-
- def set_content_type(type, params = {})
- @header['content-type'] = [type + params.map{|k,v|"; #{k}=#{v}"}.join('')]
- end
-
- alias content_type= set_content_type
-
- def set_form_data(params, sep = '&')
- self.body = params.map {|k,v| "#{urlencode(k.to_s)}=#{urlencode(v.to_s)}" }.join(sep)
- self.content_type = 'application/x-www-form-urlencoded'
- end
-
- alias form_data= set_form_data
-
- def urlencode(str)
- str.gsub(/[^a-zA-Z0-9_\.\-]/n) {|s| sprintf('%%%02x', s[0]) }
- end
- private :urlencode
-
# Set the Authorization: header for "Basic" authorization.
def basic_auth(account, password)
- @header['authorization'] = [basic_encode(account, password)]
+ @header['authorization'] = basic_encode(account, password)
end
# Set Proxy-Authorization: header for "Basic" authorization.
def proxy_basic_auth(account, password)
- @header['proxy-authorization'] = [basic_encode(account, password)]
+ @header['proxy-authorization'] = basic_encode(account, password)
end
def basic_encode(account, password)
- 'Basic ' + ["#{account}:#{password}"].pack('m').delete("\r\n")
+ 'Basic ' + ["#{account}:#{password}"].pack('m').strip
end
private :basic_encode
end
-
#
# Parent of HTTPRequest class. Do not use this directly; use
# a subclass of HTTPRequest.
@@ -1438,12 +1096,16 @@ module Net #:nodoc:
@method = m
@request_has_body = reqbody
@response_has_body = resbody
- raise ArgumentError, "HTTP request path is empty" if path.empty?
@path = path
- initialize_http_header initheader
- self['Accept'] ||= '*/*'
- @body = nil
- @body_stream = nil
+
+ @header = {}
+ return unless initheader
+ initheader.each do |k,v|
+ key = k.downcase
+ $stderr.puts "net/http: warning: duplicated HTTP header: #{k}" if @header.key?(key) and $VERBOSE
+ @header[key] = v.strip
+ end
+ @header['accept'] ||= '*/*'
end
attr_reader :method
@@ -1461,82 +1123,45 @@ module Net #:nodoc:
@response_has_body
end
- def body_exist?
- warn "Net::HTTPRequest#body_exist? is obsolete; use response_body_permitted?" if $VERBOSE
- response_body_permitted?
- end
-
- attr_reader :body
-
- def body=(str)
- @body = str
- @body_stream = nil
- str
- end
-
- attr_reader :body_stream
-
- def body_stream=(input)
- @body = nil
- @body_stream = input
- input
- end
-
- def set_body_internal(str) #:nodoc: internal use only
- raise ArgumentError, "both of body argument and HTTPRequest#body set" if str and (@body or @body_stream)
- self.body = str if str
- end
+ alias body_exist? response_body_permitted?
#
# write
#
- def exec(sock, ver, path) #:nodoc: internal use only
- if @body
- send_request_with_body sock, ver, path, @body
- elsif @body_stream
- send_request_with_body_stream sock, ver, path, @body_stream
+ def exec(sock, ver, path, body) #:nodoc: internal use only
+ if body
+ check_body_permitted
+ send_request_with_body sock, ver, path, body
else
- write_header sock, ver, path
+ request sock, ver, path
end
end
private
- def send_request_with_body(sock, ver, path, body)
- self.content_length = body.length
- delete 'Transfer-Encoding'
- unless content_type()
- warn 'net/http: warning: Content-Type did not set; using application/x-www-form-urlencoded' if $VERBOSE
- set_content_type 'application/x-www-form-urlencoded'
- end
- write_header sock, ver, path
- sock.write body
+ def check_body_permitted
+ request_body_permitted? or
+ raise ArgumentError, 'HTTP request body is not permitted'
end
- def send_request_with_body_stream(sock, ver, path, f)
- raise ArgumentError, "Content-Length not given and Transfer-Encoding is not `chunked'" unless content_length() or chunked?
- unless content_type()
- warn 'net/http: warning: Content-Type did not set; using application/x-www-form-urlencoded' if $VERBOSE
- set_content_type 'application/x-www-form-urlencoded'
- end
- write_header sock, ver, path
- if chunked?
- while s = f.read(1024)
- sock.write(sprintf("%x\r\n", s.length) << s << "\r\n")
- end
- sock.write "0\r\n\r\n"
- else
- while s = f.read(1024)
- sock.write s
- end
+ def send_request_with_body( sock, ver, path, body )
+ @header['content-length'] = body.length.to_s
+ @header.delete 'transfer-encoding'
+
+ unless @header['content-type']
+ $stderr.puts 'net/http: warning: Content-Type did not set; using application/x-www-form-urlencoded' if $VERBOSE
+ @header['content-type'] = 'application/x-www-form-urlencoded'
end
+
+ request sock, ver, path
+ sock.write body
end
- def write_header(sock, ver, path)
+ def request(sock, ver, path)
buf = "#{@method} #{path} HTTP/#{ver}\r\n"
- each_capitalized do |k,v|
- buf << "#{k}: #{v}\r\n"
+ canonical_each do |k,v|
+ buf << k + ': ' + v + "\r\n"
end
buf << "\r\n"
sock.write buf
@@ -1561,10 +1186,7 @@ module Net #:nodoc:
end
- class HTTP # reopen
- #
- # HTTP 1.1 methods --- RFC2616
- #
+ class HTTP
class Get < HTTPRequest
METHOD = 'GET'
@@ -1590,69 +1212,6 @@ module Net #:nodoc:
RESPONSE_HAS_BODY = true
end
- class Delete < HTTPRequest
- METHOD = 'DELETE'
- REQUEST_HAS_BODY = false
- RESPONSE_HAS_BODY = true
- end
-
- class Options < HTTPRequest
- METHOD = 'OPTIONS'
- REQUEST_HAS_BODY = false
- RESPONSE_HAS_BODY = false
- end
-
- class Trace < HTTPRequest
- METHOD = 'TRACE'
- REQUEST_HAS_BODY = false
- RESPONSE_HAS_BODY = true
- end
-
- #
- # WebDAV methods --- RFC2518
- #
-
- class Propfind < HTTPRequest
- METHOD = 'PROPFIND'
- REQUEST_HAS_BODY = true
- RESPONSE_HAS_BODY = true
- end
-
- class Proppatch < HTTPRequest
- METHOD = 'PROPPATCH'
- REQUEST_HAS_BODY = true
- RESPONSE_HAS_BODY = true
- end
-
- class Mkcol < HTTPRequest
- METHOD = 'MKCOL'
- REQUEST_HAS_BODY = true
- RESPONSE_HAS_BODY = true
- end
-
- class Copy < HTTPRequest
- METHOD = 'COPY'
- REQUEST_HAS_BODY = false
- RESPONSE_HAS_BODY = true
- end
-
- class Move < HTTPRequest
- METHOD = 'MOVE'
- REQUEST_HAS_BODY = false
- RESPONSE_HAS_BODY = true
- end
-
- class Lock < HTTPRequest
- METHOD = 'LOCK'
- REQUEST_HAS_BODY = true
- RESPONSE_HAS_BODY = true
- end
-
- class Unlock < HTTPRequest
- METHOD = 'UNLOCK'
- REQUEST_HAS_BODY = true
- RESPONSE_HAS_BODY = true
- end
end
@@ -1756,7 +1315,7 @@ module Net #:nodoc:
def HTTPResponse.exception_type # :nodoc: internal use only
self::EXCEPTION_TYPE
end
- end # reopened after
+ end # redefined after
# :stopdoc:
@@ -1916,7 +1475,7 @@ module Net #:nodoc:
# :startdoc:
- class HTTPResponse # reopen
+ class HTTPResponse # redefine
CODE_CLASS_TO_OBJ = {
'1' => HTTPInformation,
@@ -1972,13 +1531,20 @@ module Net #:nodoc:
'505' => HTTPVersionNotSupported
}
- class << HTTPResponse
+
+ class << self
+
def read_new(sock) #:nodoc: internal use only
httpv, code, msg = read_status_line(sock)
res = response_class(code).new(httpv, code, msg)
each_response_header(sock) do |k,v|
- res.add_field k, v
+ if res.key?(k)
+ res[k] << ', ' << v
+ else
+ res[k] = v
+ end
end
+
res
end
@@ -1987,8 +1553,8 @@ module Net #:nodoc:
def read_status_line(sock)
str = sock.readline
m = /\AHTTP(?:\/(\d+\.\d+))?\s+(\d\d\d)\s*(.*)\z/in.match(str) or
- raise HTTPBadResponse, "wrong status line: #{str.dump}"
- m.captures
+ raise HTTPBadResponse, "wrong status line: #{str.dump}"
+ m.to_a[1,3]
end
def response_class(code)
@@ -2006,6 +1572,7 @@ module Net #:nodoc:
yield m[1], m.post_match
end
end
+
end
# next is to fix bug in RDoc, where the private inside class << self
@@ -2018,7 +1585,8 @@ module Net #:nodoc:
@http_version = httpv
@code = code
@message = msg
- initialize_http_header nil
+
+ @header = {}
@body = nil
@read = false
end
@@ -2036,7 +1604,7 @@ module Net #:nodoc:
alias msg message # :nodoc: obsolete
def inspect
- "#<#{self.class} #{@code} #{@message} readbody=#{@read}>"
+ "#<#{self.class} #{@code} readbody=#{@read}>"
end
# For backward compatibility.
@@ -2046,11 +1614,7 @@ module Net #:nodoc:
#
def to_ary
warn "net/http.rb: warning: Net::HTTP v1.1 style assignment found at #{caller(1)[0]}; use `response = http.get(...)' instead." if $VERBOSE
- res = self.dup
- class << res
- undef to_ary
- end
- [res, res.body]
+ [self, body()]
end
#
@@ -2071,7 +1635,7 @@ module Net #:nodoc:
# Raises HTTP error if the response is not 2xx.
def value
- error! unless self.kind_of?(HTTPSuccess)
+ error! unless HTTPSuccess === self
end
#
@@ -2079,19 +1643,11 @@ module Net #:nodoc:
#
def response #:nodoc:
- warn "#{caller(1)[0]}: warning: HTTPResponse#response is obsolete" if $VERBOSE
self
end
- def header #:nodoc:
- warn "#{caller(1)[0]}: warning: HTTPResponse#header is obsolete" if $VERBOSE
- self
- end
-
- def read_header #:nodoc:
- warn "#{caller(1)[0]}: warning: HTTPResponse#read_header is obsolete" if $VERBOSE
- self
- end
+ alias header response #:nodoc:
+ alias read_header response #:nodoc:
#
# body
@@ -2173,19 +1729,19 @@ module Net #:nodoc:
def read_body_0(dest)
if chunked?
read_chunked dest
- return
- end
- clen = content_length()
- if clen
- @socket.read clen, dest, true # ignore EOF
- return
- end
- clen = range_length()
- if clen
- @socket.read clen, dest
- return
+ else
+ clen = content_length()
+ if clen
+ @socket.read clen, dest, true # ignore EOF
+ else
+ clen = range_length()
+ if clen
+ @socket.read clen, dest
+ else
+ @socket.read_all dest
+ end
+ end
end
- @socket.read_all dest
end
def read_chunked(dest)
@@ -2224,8 +1780,8 @@ module Net #:nodoc:
# :enddoc:
- #--
# for backward compatibility
+
class HTTP
ProxyMod = ProxyDelta
end
diff --git a/lib/net/https.rb b/lib/net/https.rb
deleted file mode 100644
index 8268c04885..0000000000
--- a/lib/net/https.rb
+++ /dev/null
@@ -1,165 +0,0 @@
-=begin
-
-= $RCSfile$ -- SSL/TLS enhancement for Net::HTTP.
-
-== Info
- 'OpenSSL for Ruby 2' project
- Copyright (C) 2001 GOTOU Yuuzou <gotoyuzo@notwork.org>
- All rights reserved.
-
-== Licence
- This program is licenced under the same licence as Ruby.
- (See the file 'LICENCE'.)
-
-== Requirements
- This program requires Net 1.2.0 or higher version.
- You can get it from RAA or Ruby's CVS repository.
-
-== Version
- $Id$
-
- 2001-11-06: Contiributed to Ruby/OpenSSL project.
- 2004-03-06: Some code is merged in to net/http.
-
-== Example
-
-Here is a simple HTTP client:
-
- require 'net/http'
- require 'uri'
-
- uri = URI.parse(ARGV[0] || 'http://localhost/')
- http = Net::HTTP.new(uri.host, uri.port)
- http.start {
- http.request_get(uri.path) {|res|
- print res.body
- }
- }
-
-It can be replaced by the following code:
-
- require 'net/https'
- require 'uri'
-
- uri = URI.parse(ARGV[0] || 'https://localhost/')
- http = Net::HTTP.new(uri.host, uri.port)
- http.use_ssl = true if uri.scheme == "https" # enable SSL/TLS
- http.start {
- http.request_get(uri.path) {|res|
- print res.body
- }
- }
-
-== class Net::HTTP
-
-=== Instance Methods
-
-: use_ssl?
- returns true if use SSL/TLS with HTTP.
-
-: use_ssl=((|true_or_false|))
- sets use_ssl.
-
-: peer_cert
- return the X.509 certificates the server presented.
-
-: key, key=((|key|))
- Sets an OpenSSL::PKey::RSA or OpenSSL::PKey::DSA object.
- (This method is appeared in Michal Rokos's OpenSSL extention.)
-
-: cert, cert=((|cert|))
- Sets an OpenSSL::X509::Certificate object as client certificate
- (This method is appeared in Michal Rokos's OpenSSL extention).
-
-: ca_file, ca_file=((|path|))
- Sets path of a CA certification file in PEM format.
- The file can contrain several CA certificats.
-
-: ca_path, ca_path=((|path|))
- Sets path of a CA certification directory containing certifications
- in PEM format.
-
-: verify_mode, verify_mode=((|mode|))
- Sets the flags for server the certification verification at
- begining of SSL/TLS session.
- OpenSSL::SSL::VERIFY_NONE or OpenSSL::SSL::VERIFY_PEER is acceptable.
-
-: verify_callback, verify_callback=((|proc|))
- Sets the verify callback for the server certification verification.
-
-: verify_depth, verify_depth=((|num|))
- Sets the maximum depth for the certificate chain verification.
-
-: cert_store, cert_store=((|store|))
- Sets the X509::Store to verify peer certificate.
-
-: ssl_timeout, ssl_timeout=((|sec|))
- Sets the SSL timeout seconds.
-
-=end
-
-require 'net/http'
-require 'openssl'
-
-module Net
-
- class HTTP
- # Turn on/off SSL.
- # This flag must be set before starting session.
- # If you change use_ssl value after session started,
- # a Net::HTTP object raises IOError.
- def use_ssl=(flag)
- flag = (flag ? true : false)
- raise IOError, "use_ssl value changed, but session already started" \
- if started? and @use_ssl != flag
- if flag and not @ssl_context
- @ssl_context = OpenSSL::SSL::SSLContext.new
- end
- @use_ssl = flag
- end
-
- def self.ssl_context_accessor(name)
- module_eval(<<-End, __FILE__, __LINE__ + 1)
- def #{name}
- return nil unless @ssl_context
- @ssl_context.#{name}
- end
-
- def #{name}=(val)
- @ssl_context ||= OpenSSL::SSL::SSLContext.new
- @ssl_context.#{name} = val
- end
- End
- end
-
- ssl_context_accessor :key
- ssl_context_accessor :cert
- ssl_context_accessor :ca_file
- ssl_context_accessor :ca_path
- ssl_context_accessor :verify_mode
- ssl_context_accessor :verify_callback
- ssl_context_accessor :verify_depth
- ssl_context_accessor :cert_store
-
- def ssl_timeout
- return nil unless @ssl_context
- @ssl_context.timeout
- end
-
- def ssl_timeout=(sec)
- raise ArgumentError, 'Net::HTTP#ssl_timeout= called but use_ssl=false' \
- unless use_ssl?
- @ssl_context ||= OpenSSL::SSL::SSLContext.new
- @ssl_context.timeout = sec
- end
-
- # For backward compatibility
- alias timeout= ssl_timeout=
-
- def peer_cert
- return nil if not use_ssl? or not @socket
- @socket.io.peer_cert
- end
- end
-
-end
diff --git a/lib/net/imap.rb b/lib/net/imap.rb
index 29b6359e0e..7886c66fdd 100644
--- a/lib/net/imap.rb
+++ b/lib/net/imap.rb
@@ -885,16 +885,15 @@ module Net
raise "SSL extension not installed"
end
@usessl = true
+ @sock = SSLSocket.new(@sock)
# verify the server.
- context = SSLContext::new()
- context.ca_file = certs if certs && FileTest::file?(certs)
- context.ca_path = certs if certs && FileTest::directory?(certs)
- context.verify_mode = VERIFY_PEER if verify
+ @sock.ca_file = certs if certs && FileTest::file?(certs)
+ @sock.ca_path = certs if certs && FileTest::directory?(certs)
+ @sock.verify_mode = VERIFY_PEER if verify
if defined?(VerifyCallbackProc)
- context.verify_callback = VerifyCallbackProc
+ @sock.verify_callback = VerifyCallbackProc
end
- @sock = SSLSocket.new(@sock, context)
@sock.connect # start ssl session.
else
@usessl = false
@@ -1267,7 +1266,7 @@ module Net
buf.concat(c)
i += 1
elsif (c & 0xe0) == 0xc0 &&
- len >= 2 &&
+ inlen >= 2 &&
(s[i + 1] & 0xc0) == 0x80
if c == 0xc0 || c == 0xc1
raise DataFormatError, format("non-shortest UTF-8 sequence (%02x)", c)
diff --git a/lib/net/pop.rb b/lib/net/pop.rb
index 2ecbcbdf28..a4f50b002c 100644
--- a/lib/net/pop.rb
+++ b/lib/net/pop.rb
@@ -435,7 +435,7 @@ module Net
end
def do_start( account, password )
- @socket = self.class.socket_type.old_open(@address, @port,
+ @socket = self.class.socket_type.open(@address, @port,
@open_timeout, @read_timeout, @debug_output)
on_connect
@command = POP3Command.new(@socket)
diff --git a/lib/net/protocol.rb b/lib/net/protocol.rb
index d722fdcbd4..ac6bce1058 100644
--- a/lib/net/protocol.rb
+++ b/lib/net/protocol.rb
@@ -2,8 +2,8 @@
# = net/protocol.rb
#
#--
-# Copyright (c) 1999-2005 Yukihiro Matsumoto
-# Copyright (c) 1999-2005 Minero Aoki
+# Copyright (c) 1999-2004 Yukihiro Matsumoto
+# Copyright (c) 1999-2004 Minero Aoki
#
# written and maintained by Minero Aoki <aamine@loveruby.net>
#
@@ -25,7 +25,7 @@ module Net # :nodoc:
class Protocol #:nodoc: internal use only
private
- def Protocol.protocol_param(name, val)
+ def Protocol.protocol_param( name, val )
module_eval(<<-End, __FILE__, __LINE__ + 1)
def #{name}
#{val}
@@ -34,7 +34,6 @@ module Net # :nodoc:
end
end
-
class ProtocolError < StandardError; end
class ProtoSyntaxError < ProtocolError; end
class ProtoFatalError < ProtocolError; end
@@ -46,282 +45,335 @@ module Net # :nodoc:
ProtocRetryError = ProtoRetriableError
- class BufferedIO #:nodoc: internal use only
- def initialize(io)
- @io = io
- @read_timeout = 60
- @debug_output = nil
- @rbuf = ''
+ class InternetMessageIO #:nodoc: internal use only
+
+ class << self
+ alias open new
+ end
+
+ def initialize( addr, port,
+ open_timeout = nil, read_timeout = nil,
+ debug_output = nil )
+ @address = addr
+ @port = port
+ @read_timeout = read_timeout
+ @debug_output = debug_output
+ @socket = nil
+ @rbuf = nil # read buffer
+ @wbuf = nil # write buffer
+ connect open_timeout
+ LOG 'opened'
+ end
+
+ attr_reader :address
+ attr_reader :port
+
+ def ip_address
+ return '' unless @socket
+ @socket.addr[3]
end
- attr_reader :io
attr_accessor :read_timeout
- attr_accessor :debug_output
- def inspect
- "#<#{self.class} io=#{@io}>"
+ attr_reader :socket
+
+ def connect( open_timeout )
+ LOG "opening connection to #{@address}..."
+ timeout(open_timeout) {
+ @socket = TCPsocket.new(@address, @port)
+ }
+ @rbuf = ''
+ end
+ private :connect
+
+ def close
+ if @socket
+ @socket.close
+ LOG 'closed'
+ else
+ LOG 'close call for already closed socket'
+ end
+ @socket = nil
+ @rbuf = ''
+ end
+
+ def reopen( open_timeout = nil )
+ LOG 'reopening...'
+ close
+ connect open_timeout
+ LOG 'reopened'
end
def closed?
- @io.closed?
+ not @socket
end
- def close
- @io.close
+ def inspect
+ "#<#{self.class} #{closed?() ? 'closed' : 'opened'}>"
end
- #
- # Read
- #
+ ###
+ ### READ
+ ###
public
- def read(len, dest = '', ignore_eof = false)
+ def read( len, dest = '', ignore_eof = false )
LOG "reading #{len} bytes..."
+ # LOG_off() # experimental: [ruby-list:38800]
read_bytes = 0
begin
while read_bytes + @rbuf.size < len
- dest << (s = rbuf_consume(@rbuf.size))
- read_bytes += s.size
+ read_bytes += rbuf_moveto(dest, @rbuf.size)
rbuf_fill
end
- dest << (s = rbuf_consume(len - read_bytes))
- read_bytes += s.size
+ rbuf_moveto dest, len - read_bytes
rescue EOFError
raise unless ignore_eof
end
+ # LOG_on()
LOG "read #{read_bytes} bytes"
dest
end
- def read_all(dest = '')
+ def read_all( dest = '' )
LOG 'reading all...'
+ # LOG_off() # experimental: [ruby-list:38800]
read_bytes = 0
begin
while true
- dest << (s = rbuf_consume(@rbuf.size))
- read_bytes += s.size
+ read_bytes += rbuf_moveto(dest, @rbuf.size)
rbuf_fill
end
rescue EOFError
;
end
+ # LOG_on()
LOG "read #{read_bytes} bytes"
dest
end
- def readuntil(terminator, ignore_eof = false)
+ def readuntil( terminator, ignore_eof = false )
+ dest = ''
begin
until idx = @rbuf.index(terminator)
rbuf_fill
end
- return rbuf_consume(idx + terminator.size)
+ rbuf_moveto dest, idx + terminator.size
rescue EOFError
raise unless ignore_eof
- return rbuf_consume(@rbuf.size)
+ rbuf_moveto dest, @rbuf.size
end
+ dest
end
def readline
readuntil("\n").chop
end
+ def each_message_chunk
+ LOG 'reading message...'
+ LOG_off()
+ read_bytes = 0
+ while (line = readuntil("\r\n")) != ".\r\n"
+ read_bytes += line.size
+ yield line.sub(/\A\./, '')
+ end
+ LOG_on()
+ LOG "read message (#{read_bytes} bytes)"
+ end
+
+ # *library private* (cannot handle 'break')
+ def each_list_item
+ while (str = readuntil("\r\n")) != ".\r\n"
+ yield str.chop
+ end
+ end
+
private
def rbuf_fill
timeout(@read_timeout) {
- @rbuf << @io.sysread(1024)
+ @rbuf << @socket.sysread(1024)
}
end
- def rbuf_consume(len)
- s = @rbuf.slice!(0, len)
+ def rbuf_moveto( dest, len )
+ dest << (s = @rbuf.slice!(0, len))
@debug_output << %Q[-> #{s.dump}\n] if @debug_output
- s
+ len
end
- #
- # Write
- #
+ ###
+ ### WRITE
+ ###
public
- def write(str)
+ def write( str )
writing {
write0 str
}
end
- def writeline(str)
+ def writeline( str )
writing {
write0 str + "\r\n"
}
end
+ def write_message( src )
+ LOG "writing message from #{src.class}"
+ LOG_off()
+ len = using_each_crlf_line {
+ write_message_0 src
+ }
+ LOG_on()
+ LOG "wrote #{len} bytes"
+ len
+ end
+
+ def write_message_by_block( &block )
+ LOG 'writing message from block'
+ LOG_off()
+ len = using_each_crlf_line {
+ begin
+ block.call(WriteAdapter.new(self, :write_message_0))
+ rescue LocalJumpError
+ # allow `break' from writer block
+ end
+ }
+ LOG_on()
+ LOG "wrote #{len} bytes"
+ len
+ end
+
private
def writing
@written_bytes = 0
@debug_output << '<- ' if @debug_output
yield
+ @socket.flush
@debug_output << "\n" if @debug_output
bytes = @written_bytes
@written_bytes = nil
bytes
end
- def write0(str)
+ def write0( str )
@debug_output << str.dump if @debug_output
- len = @io.write(str)
+ len = @socket.write(str)
@written_bytes += len
len
end
#
- # Logging
+ # Reads string from src calling :each, and write to @socket.
+ # Escapes '.' on the each line head.
#
-
- private
-
- def LOG_off
- @save_debug_out = @debug_output
- @debug_output = nil
- end
-
- def LOG_on
- @debug_output = @save_debug_out
- end
-
- def LOG(msg)
- return unless @debug_output
- @debug_output << msg + "\n"
- end
- end
-
-
- class InternetMessageIO < BufferedIO #:nodoc: internal use only
- def InternetMessageIO.old_open(addr, port,
- open_timeout = nil, read_timeout = nil, debug_output = nil)
- debug_output << "opening connection to #{addr}...\n" if debug_output
- s = timeout(open_timeout) { TCPsocket.new(addr, port) }
- io = new(s)
- io.read_timeout = read_timeout
- io.debug_output = debug_output
- io
- end
-
- def initialize(io)
- super
- @wbuf = nil
- end
-
- #
- # Read
- #
-
- def each_message_chunk
- LOG 'reading message...'
- LOG_off()
- read_bytes = 0
- while (line = readuntil("\r\n")) != ".\r\n"
- read_bytes += line.size
- yield line.sub(/\A\./, '')
- end
- LOG_on()
- LOG "read message (#{read_bytes} bytes)"
- end
-
- # *library private* (cannot handle 'break')
- def each_list_item
- while (str = readuntil("\r\n")) != ".\r\n"
- yield str.chop
- end
- end
-
- def write_message_0(src)
+ def write_message_0( src )
prev = @written_bytes
each_crlf_line(src) do |line|
- write0 line.sub(/\A\./, '..')
+ if line[0] == ?.
+ then write0 '.' + line
+ else write0 line
+ end
end
@written_bytes - prev
end
#
- # Write
+ # setup @wbuf for each_crlf_line.
#
-
- def write_message(src)
- LOG "writing message from #{src.class}"
- LOG_off()
- len = writing {
- using_each_crlf_line {
- write_message_0 src
- }
- }
- LOG_on()
- LOG "wrote #{len} bytes"
- len
- end
-
- def write_message_by_block(&block)
- LOG 'writing message from block'
- LOG_off()
- len = writing {
- using_each_crlf_line {
- begin
- block.call(WriteAdapter.new(self, :write_message_0))
- rescue LocalJumpError
- # allow `break' from writer block
+ def using_each_crlf_line
+ writing {
+ @wbuf = ''
+ yield
+ if not @wbuf.empty? # unterminated last line
+ if @wbuf[-1] == ?\r
+ @wbuf.chop!
+ end
+ @wbuf.concat "\r\n"
+ write0 @wbuf
+ elsif @written_bytes == 0 # empty src
+ write0 "\r\n"
end
- }
+ write0 ".\r\n"
+ @wbuf = nil
}
- LOG_on()
- LOG "wrote #{len} bytes"
- len
- end
-
- private
-
- def using_each_crlf_line
- @wbuf = ''
- yield
- if not @wbuf.empty? # unterminated last line
- write0 @wbuf.chomp + "\r\n"
- elsif @written_bytes == 0 # empty src
- write0 "\r\n"
- end
- write0 ".\r\n"
- @wbuf = nil
end
- def each_crlf_line(src)
- buffer_filling(@wbuf, src) do
- while line = @wbuf.slice!(/\A.*(?:\n|\r\n|\r(?!\z))/n)
- yield line.chomp("\n") + "\r\n"
+ #
+ # extract a CR-LF-terminating-line from @wbuf and yield it.
+ #
+ def each_crlf_line( src )
+ adding(src) do
+ beg = 0
+ buf = @wbuf
+ while buf.index(/\n|\r\n|\r/, beg)
+ m = Regexp.last_match
+ if (m.begin(0) == buf.length - 1) and buf[-1] == ?\r
+ # "...\r" : can follow "\n..."
+ break
+ end
+ str = buf[beg ... m.begin(0)]
+ str.concat "\r\n"
+ yield str
+ beg = m.end(0)
end
+ @wbuf = buf[beg ... buf.length]
end
end
- def buffer_filling(buf, src)
+ #
+ # Reads strings from SRC and add to @wbuf, then yield.
+ #
+ def adding( src )
case src
when String # for speeding up.
- 0.step(src.size - 1, 1024) do |i|
- buf << src[i, 1024]
+ 0.step(src.size - 1, 2048) do |i|
+ @wbuf << src[i,2048]
yield
end
+
when File # for speeding up.
- while s = src.read(1024)
- buf << s
+ while s = src.read(2048)
+ s[0,0] = @wbuf
+ @wbuf = s
yield
end
+
else # generic reader
src.each do |s|
- buf << s
- yield if buf.size > 1024
+ @wbuf << s
+ yield if @wbuf.size > 2048
end
- yield unless buf.empty?
+ yield unless @wbuf.empty?
end
end
+
+ ###
+ ### DEBUG
+ ###
+
+ private
+
+ def LOG_off
+ @save_debug_out = @debug_output
+ @debug_output = nil
+ end
+
+ def LOG_on
+ @debug_output = @save_debug_out
+ end
+
+ def LOG( msg )
+ return unless @debug_output
+ @debug_output << msg
+ @debug_output << "\n"
+ end
+
end
@@ -329,38 +381,41 @@ module Net # :nodoc:
# The writer adapter class
#
class WriteAdapter
- def initialize(socket, method)
- @socket = socket
- @method_id = method
+
+ def initialize( sock, mid )
+ @socket = sock
+ @method_id = mid
end
def inspect
"#<#{self.class} socket=#{@socket.inspect}>"
end
- def write(str)
+ def write( str )
@socket.__send__(@method_id, str)
end
alias print write
- def <<(str)
+ def <<( str )
write str
self
end
- def puts(str = '')
- write str.chomp("\n") + "\n"
+ def puts( str = '' )
+ write str.sub(/\n?/, "\n")
end
- def printf(*args)
+ def printf( *args )
write sprintf(*args)
end
+
end
class ReadAdapter #:nodoc: internal use only
- def initialize(block)
+
+ def initialize( block )
@block = block
end
@@ -368,18 +423,21 @@ module Net # :nodoc:
"#<#{self.class}>"
end
- def <<(str)
+ def <<( str )
call_block(str, &@block) if @block
end
private
+ #
# This method is needed because @block must be called by yield,
# not Proc#call. You can see difference when using `break' in
# the block.
- def call_block(str)
+ #
+ def call_block( str )
yield str
end
+
end
diff --git a/lib/net/smtp.rb b/lib/net/smtp.rb
index dda9dab072..db54b998c9 100644
--- a/lib/net/smtp.rb
+++ b/lib/net/smtp.rb
@@ -390,7 +390,7 @@ module Net
raise IOError, 'SMTP session already started' if @started
check_auth_args user, secret, authtype if user or secret
- @socket = InternetMessageIO.old_open(@address, @port,
+ @socket = InternetMessageIO.open(@address, @port,
@open_timeout, @read_timeout,
@debug_output)
check_response(critical { recv_response() })
diff --git a/lib/net/telnet.rb b/lib/net/telnet.rb
index c5f8b0429a..05691de0f7 100644
--- a/lib/net/telnet.rb
+++ b/lib/net/telnet.rb
@@ -551,7 +551,7 @@ module Net
raise TimeoutError, "timed out while waiting for more data"
end
begin
- c = @sock.readpartial(1024 * 1024)
+ c = @sock.sysread(1024 * 1024)
@dumplog.log_dump('<', c) if @options.has_key?("Dump_log")
if @options["Telnetmode"]
c = rest + c
diff --git a/lib/open-uri.rb b/lib/open-uri.rb
index ce6058935d..8d0353bbc9 100644
--- a/lib/open-uri.rb
+++ b/lib/open-uri.rb
@@ -1,10 +1,10 @@
#= open-uri.rb
#
-#open-uri.rb is easy-to-use wrapper for net/http, net/https and net/ftp.
+#open-uri.rb is easy-to-use wrapper for net/http and net/ftp.
#
#== Example
#
-#It is possible to open http/https/ftp URL as usual a file:
+#It is possible to open http/ftp URL as usual a file:
#
# open("http://www.ruby-lang.org/") {|f|
# f.each_line {|line| p line}
@@ -31,8 +31,8 @@
# ...
# }
#
-#The environment variables such as http_proxy, https_proxy and ftp_proxy
-#are in effect by default. :proxy => nil disables proxy.
+#The environment variables such as http_proxy and ftp_proxy are in effect by
+#default. :proxy => nil disables proxy.
#
# open("http://www.ruby-lang.org/en/raa.html",
# :proxy => nil) {|f|
@@ -72,11 +72,10 @@ module Kernel
#
# Otherwise original open is called.
#
- # Since open-uri.rb provides URI::HTTP#open, URI::HTTPS#open and
- # URI::FTP#open,
+ # Since open-uri.rb provides URI::HTTP#open and URI::FTP#open,
# Kernel[#.]open can accepts such URIs and strings which begins with
- # http://, https:// and ftp://.
- # In these case, the opened file object is extended by OpenURI::Meta.
+ # http:// and ftp://. In this http and ftp case, the opened file object
+ # is extended by OpenURI::Meta.
def open(name, *rest, &block) # :doc:
if name.respond_to?(:open)
name.open(*rest, &block)
@@ -96,9 +95,9 @@ module OpenURI
:proxy => true,
:progress_proc => true,
:content_length_proc => true,
- :http_basic_authentication => true,
}
+
def OpenURI.check_options(options) # :nodoc:
options.each {|k, v|
next unless Symbol === k
@@ -164,7 +163,11 @@ module OpenURI
while true
redirect = catch(:open_uri_redirect) {
buf = Buffer.new
- uri.buffer_open(buf, find_proxy.call(uri), options)
+ if proxy_uri = find_proxy.call(uri)
+ proxy_uri.proxy_open(buf, uri, options)
+ else
+ uri.direct_open(buf, options)
+ end
nil
}
if redirect
@@ -176,11 +179,6 @@ module OpenURI
unless OpenURI.redirectable?(uri, redirect)
raise "redirection forbidden: #{uri} -> #{redirect}"
end
- if options.include? :http_basic_authentication
- # send authentication only for the URI directly specified.
- options = options.dup
- options.delete :http_basic_authentication
- end
uri = redirect
raise "HTTP redirection loop: #{uri}" if uri_set.include? uri.to_s
uri_set[uri.to_s] = true
@@ -201,96 +199,6 @@ module OpenURI
(/\A(?:http|ftp)\z/i =~ uri1.scheme && /\A(?:http|ftp)\z/i =~ uri2.scheme)
end
- def OpenURI.open_http(buf, target, proxy, options) # :nodoc:
- if proxy
- raise "Non-HTTP proxy URI: #{proxy}" if proxy.class != URI::HTTP
- end
-
- if target.userinfo && "1.9.0" <= RUBY_VERSION
- # don't raise for 1.8 because compatibility.
- raise ArgumentError, "userinfo not supported. [RFC3986]"
- end
-
- require 'net/http'
- klass = Net::HTTP
- if URI::HTTP === target
- # HTTP or HTTPS
- if proxy
- klass = Net::HTTP::Proxy(proxy.host, proxy.port)
- end
- target_host = target.host
- target_port = target.port
- request_uri = target.request_uri
- else
- # FTP over HTTP proxy
- target_host = proxy.host
- target_port = proxy.port
- request_uri = target.to_s
- end
-
- http = klass.new(target_host, target_port)
- if target.class == URI::HTTPS
- require 'net/https'
- http.use_ssl = true
- http.verify_mode = OpenSSL::SSL::VERIFY_PEER
- store = OpenSSL::X509::Store.new
- store.set_default_paths
- http.cert_store = store
- end
-
- header = {}
- options.each {|k, v| header[k] = v if String === k }
-
- resp = nil
- http.start {
- if target.class == URI::HTTPS
- # xxx: information hiding violation
- sock = http.instance_variable_get(:@socket)
- if sock.respond_to?(:io)
- sock = sock.io # 1.9
- else
- sock = sock.instance_variable_get(:@socket) # 1.8
- end
- sock.post_connection_check(target_host)
- end
- req = Net::HTTP::Get.new(request_uri, header)
- if options.include? :http_basic_authentication
- user, pass = options[:http_basic_authentication]
- req.basic_auth user, pass
- end
- http.request(req) {|response|
- resp = response
- if options[:content_length_proc] && Net::HTTPSuccess === resp
- if resp.key?('Content-Length')
- options[:content_length_proc].call(resp['Content-Length'].to_i)
- else
- options[:content_length_proc].call(nil)
- end
- end
- resp.read_body {|str|
- buf << str
- if options[:progress_proc] && Net::HTTPSuccess === resp
- options[:progress_proc].call(buf.size)
- end
- }
- }
- }
- io = buf.io
- io.rewind
- io.status = [resp.code, resp.message]
- resp.each {|name,value| buf.io.meta_add_field name, value }
- case resp
- when Net::HTTPSuccess
- when Net::HTTPMovedPermanently, # 301
- Net::HTTPFound, # 302
- Net::HTTPSeeOther, # 303
- Net::HTTPTemporaryRedirect # 307
- throw :open_uri_redirect, URI.parse(resp['location'])
- else
- raise OpenURI::HTTPError.new(io.status.join(' '), io)
- end
- end
-
class HTTPError < StandardError
def initialize(message, io)
super(message)
@@ -314,14 +222,14 @@ module OpenURI
require 'tempfile'
io = Tempfile.new('open-uri')
io.binmode
- Meta.init io, @io if @io.respond_to? :meta
+ Meta.init io, @io if Meta === @io
io << @io.string
@io = io
end
end
def io
- Meta.init @io unless @io.respond_to? :meta
+ Meta.init @io unless Meta === @io
@io
end
end
@@ -369,7 +277,7 @@ module OpenURI
RE_LWS = /[\r\n\t ]+/n
RE_TOKEN = %r{[^\x00- ()<>@,;:\\"/\[\]?={}\x7f]+}n
- RE_QUOTED_STRING = %r{"(?:[\r\n\t !#-\[\]-~\x80-\xff]|\\[\x00-\x7f])*"}n
+ RE_QUOTED_STRING = %r{"(?:[\r\n\t !#-\[\]-~\x80-\xff]|\\[\x00-\x7f])"}n
RE_PARAMETERS = %r{(?:;#{RE_LWS}?#{RE_TOKEN}#{RE_LWS}?=#{RE_LWS}?(?:#{RE_TOKEN}|#{RE_QUOTED_STRING})#{RE_LWS}?)*}n
def content_type_parse # :nodoc:
@@ -454,75 +362,60 @@ module OpenURI
# field for HTTP.
# I.e. it is ignored for FTP without HTTP proxy.
#
- # The hash may include other options which key is a symbol:
+ # The hash may include other option which key is a symbol:
+ #
+ # :proxy => "http://proxy.foo.com:8000/"
+ # :proxy => URI.parse("http://proxy.foo.com:8000/")
+ # :proxy => true
+ # :proxy => false
+ # :proxy => nil
#
- # [:proxy]
- # Synopsis:
- # :proxy => "http://proxy.foo.com:8000/"
- # :proxy => URI.parse("http://proxy.foo.com:8000/")
- # :proxy => true
- # :proxy => false
- # :proxy => nil
- #
- # If :proxy option is specified, the value should be String, URI,
- # boolean or nil.
- # When String or URI is given, it is treated as proxy URI.
- # When true is given or the option itself is not specified,
- # environment variable `scheme_proxy' is examined.
- # `scheme' is replaced by `http', `https' or `ftp'.
- # When false or nil is given, the environment variables are ignored and
- # connection will be made to a server directly.
+ # If :proxy option is specified, the value should be String, URI,
+ # boolean or nil.
+ # When String or URI is given, it is treated as proxy URI.
+ # When true is given or the option itself is not specified,
+ # environment variable `scheme_proxy'(or `SCHEME_PROXY') is examined.
+ # `scheme' is replaced by `http' or `ftp'.
+ # When false or nil is given, the environment variables are ignored and
+ # connection will be made to a server directly.
#
- # [:http_basic_authentication]
- # Synopsis:
- # :http_basic_authentication=>[user, password]
+ # :content_length_proc => lambda {|content_length| ... }
#
- # If :http_basic_authentication is specified,
- # the value should be an array which contains 2 strings:
- # username and password.
- # It is used for HTTP Basic authentication defined by RFC 2617.
+ # If :content_length_proc option is specified, the option value procedure
+ # is called before actual transfer is started.
+ # It takes one argument which is expected content length in bytes.
#
- # [:content_length_proc]
- # Synopsis:
- # :content_length_proc => lambda {|content_length| ... }
- #
- # If :content_length_proc option is specified, the option value procedure
- # is called before actual transfer is started.
- # It takes one argument which is expected content length in bytes.
- #
- # If two or more transfer is done by HTTP redirection, the procedure
- # is called only one for a last transfer.
- #
- # When expected content length is unknown, the procedure is called with
- # nil.
- # It is happen when HTTP response has no Content-Length header.
+ # If two or more transfer is done by HTTP redirection, the procedure
+ # is called only one for a last transfer.
#
- # [:progress_proc]
- # Synopsis:
- # :progress_proc => lambda {|size| ...}
+ # When expected content length is unknown, the procedure is called with
+ # nil.
+ # It is happen when HTTP response has no Content-Length header.
#
- # If :progress_proc option is specified, the proc is called with one
- # argument each time when `open' gets content fragment from network.
- # The argument `size' `size' is a accumulated transfered size in bytes.
+ # :progress_proc => lambda {|size| ...}
#
- # If two or more transfer is done by HTTP redirection, the procedure
- # is called only one for a last transfer.
+ # If :progress_proc option is specified, the proc is called with one
+ # argument each time when `open' gets content fragment from network.
+ # The argument `size' `size' is a accumulated transfered size in bytes.
#
- # :progress_proc and :content_length_proc are intended to be used for
- # progress bar.
- # For example, it can be implemented as follows using Ruby/ProgressBar.
+ # If two or more transfer is done by HTTP redirection, the procedure
+ # is called only one for a last transfer.
#
- # pbar = nil
- # open("http://...",
- # :content_length_proc => lambda {|t|
- # if t && 0 < t
- # pbar = ProgressBar.new("...", t)
- # pbar.file_transfer_mode
- # end
- # },
- # :progress_proc => lambda {|s|
- # pbar.set s if pbar
- # }) {|f| ... }
+ # :progress_proc and :content_length_proc are intended to be used for
+ # progress bar.
+ # For example, it can be implemented as follows using Ruby/ProgressBar.
+ #
+ # pbar = nil
+ # open("http://...",
+ # :content_length_proc => lambda {|t|
+ # if t && 0 < t
+ # pbar = ProgressBar.new("...", t)
+ # pbar.file_transfer_mode
+ # end
+ # },
+ # :progress_proc => lambda {|s|
+ # pbar.set s if pbar
+ # }) {|f| ... }
#
# OpenURI::OpenRead#open returns an IO like object if block is not given.
# Otherwise it yields the IO object and return the value of the block.
@@ -607,6 +500,9 @@ module URI
if proxy_uri
proxy_uri = URI.parse(proxy_uri)
+ unless URI::HTTP === proxy_uri
+ raise "Non-HTTP proxy URI: #{proxy_uri}"
+ end
name = 'no_proxy'
if no_proxy = ENV[name] || ENV[name.upcase]
no_proxy.scan(/([^:,]*)(?::(\d+))?/) {|host, port|
@@ -625,60 +521,83 @@ module URI
end
class HTTP
- def buffer_open(buf, proxy, options) # :nodoc:
- OpenURI.open_http(buf, self, proxy, options)
+ def direct_open(buf, options) # :nodoc:
+ proxy_open(buf, request_uri, options)
end
- include OpenURI::OpenRead
- end
-
- class FTP
- def buffer_open(buf, proxy, options) # :nodoc:
- if proxy
- OpenURI.open_http(buf, self, proxy, options)
- return
+ def proxy_open(buf, uri, options) # :nodoc:
+ header = {}
+ options.each {|k, v| header[k] = v if String === k }
+
+ if uri.respond_to? :host
+ # According to RFC2616 14.23, Host: request-header field should be set
+ # an origin server.
+ # But net/http wrongly set a proxy server if an absolute URI is
+ # specified as a request URI.
+ # So open-uri override it here explicitly.
+ header['host'] = uri.host
+ header['host'] += ":#{uri.port}" if uri.port
end
- require 'net/ftp'
- directories = self.path.split(%r{/}, -1)
- directories.shift if directories[0] == '' # strip a field before leading slash
- directories.each {|d|
- d.gsub!(/%([0-9A-Fa-f][0-9A-Fa-f])/) { [$1].pack("H2") }
- }
- unless filename = directories.pop
- raise ArgumentError, "no filename: #{self.inspect}"
- end
- directories.each {|d|
- if /[\r\n]/ =~ d
- raise ArgumentError, "invalid directory: #{d.inspect}"
- end
+ require 'net/http'
+ resp = nil
+ Net::HTTP.start(self.host, self.port) {|http|
+ http.request_get(uri.to_s, header) {|response|
+ resp = response
+ if options[:content_length_proc] && Net::HTTPSuccess === resp
+ if resp.key?('Content-Length')
+ options[:content_length_proc].call(resp['Content-Length'].to_i)
+ else
+ options[:content_length_proc].call(nil)
+ end
+ end
+ resp.read_body {|str|
+ buf << str
+ if options[:progress_proc] && Net::HTTPSuccess === resp
+ options[:progress_proc].call(buf.size)
+ end
+ }
+ }
}
- if /[\r\n]/ =~ filename
- raise ArgumentError, "invalid filename: #{filename.inspect}"
- end
- typecode = self.typecode
- if typecode && /\A[aid]\z/ !~ typecode
- raise ArgumentError, "invalid typecode: #{typecode.inspect}"
+ io = buf.io
+ io.rewind
+ io.status = [resp.code, resp.message]
+ resp.each {|name,value| buf.io.meta_add_field name, value }
+ case resp
+ when Net::HTTPSuccess
+ when Net::HTTPMovedPermanently, # 301
+ Net::HTTPFound, # 302
+ Net::HTTPSeeOther, # 303
+ Net::HTTPTemporaryRedirect # 307
+ throw :open_uri_redirect, URI.parse(resp['location'])
+ else
+ raise OpenURI::HTTPError.new(io.status.join(' '), io)
end
+ end
- # The access sequence is defined by RFC 1738
- ftp = Net::FTP.open(self.host)
+ include OpenURI::OpenRead
+ end
+
+ class HTTPS
+ def proxy_open(buf, uri, options) # :nodoc:
+ raise ArgumentError, "open-uri doesn't support https."
+ end
+ end
+
+ class FTP
+ def direct_open(buf, options) # :nodoc:
+ require 'net/ftp'
# todo: extract user/passwd from .netrc.
user = 'anonymous'
passwd = nil
user, passwd = self.userinfo.split(/:/) if self.userinfo
+
+ ftp = Net::FTP.open(self.host)
ftp.login(user, passwd)
- directories.each {|cwd|
- ftp.voidcmd("CWD #{cwd}")
- }
- if typecode
- # xxx: typecode D is not handled.
- ftp.voidcmd("TYPE #{typecode.upcase}")
- end
if options[:content_length_proc]
- options[:content_length_proc].call(ftp.size(filename))
+ options[:content_length_proc].call(ftp.size(self.path))
end
- ftp.retrbinary("RETR #{filename}", 4096) { |str|
+ ftp.getbinaryfile(self.path, '/dev/null', Net::FTP::DEFAULT_BLOCKSIZE) {|str|
buf << str
options[:progress_proc].call(buf.size) if options[:progress_proc]
}
diff --git a/lib/open3.rb b/lib/open3.rb
index 59db1a4cc5..407cd7662c 100644
--- a/lib/open3.rb
+++ b/lib/open3.rb
@@ -35,7 +35,7 @@ module Open3
exec(*cmd)
}
- exit!(0)
+ exit!
}
pw[0].close
diff --git a/lib/optparse.rb b/lib/optparse.rb
index 6668f30c8b..63cf1d79f0 100644
--- a/lib/optparse.rb
+++ b/lib/optparse.rb
@@ -207,9 +207,9 @@ class OptionParser
# and resolved against a list of acceptable values.
#
module Completion
- def complete(key, icase = false, pat = nil)
+ def complete(key, pat = nil)
pat ||= Regexp.new('\A' + Regexp.quote(key).gsub(/\w+\b/, '\&\w*'),
- icase)
+ ignore_case?)
canon, sw, k, v, cn = nil
candidates = []
each do |k, *v|
@@ -250,6 +250,10 @@ class OptionParser
def convert(opt = nil, val = nil, *)
val
end
+
+ def ignore_case?
+ false
+ end
end
@@ -259,6 +263,11 @@ class OptionParser
class OptionMap < Hash
include Completion
end
+ class OptionCaseMap < OptionMap
+ def ignore_case?
+ true
+ end
+ end
#
@@ -441,12 +450,12 @@ class OptionParser
#
# Raises an exception if argument is not present.
#
- def parse(arg, argv)
+ def parse(arg, argv, &error)
unless arg
raise MissingArgument if argv.empty?
arg = argv.shift
end
- conv_arg(*parse_arg(arg) {|*exc| raise(*exc)})
+ conv_arg(*parse_arg(arg, &error))
end
end
@@ -467,11 +476,11 @@ class OptionParser
end
#
- # Switch that takes an argument, which does not begin with '-'.
+ # ?
#
class PlacedArgument < self
#
- # Returns nil if argument is not present or begins with '-'.
+ # ?
#
def parse(arg, argv, &error)
if !(val = arg) and (argv.empty? or /\A-/ =~ (val = argv[0]))
@@ -514,7 +523,7 @@ class OptionParser
def initialize
@atype = {}
@short = OptionMap.new
- @long = OptionMap.new
+ @long = OptionCaseMap.new
@list = []
end
@@ -623,15 +632,13 @@ class OptionParser
# searching list.
# : ((|opt|))
# searching key.
- # : ((|icase|))
- # search case insensitive if true.
# : ((|*pat|))
# optional pattern for completion.
# : (({block}))
# yielded with the found value when succeeded.
#
- def complete(id, opt, icase = false, *pat, &block)
- __send__(id).complete(opt, icase, *pat, &block)
+ def complete(id, opt, *pat, &block)
+ __send__(id).complete(opt, *pat, &block)
end
#
@@ -711,38 +718,30 @@ class OptionParser
DefaultList.long[''] = Switch::NoArgument.new {throw :terminate}
#
- # OptionParser::Officious
- # Default options for ARGV, which never appear in option summary.
- #
- Officious = {}
-
+ # Default options, which never appear in option summary.
# --help
# Shows option summary.
- Officious['help'] = proc do |parser|
- Switch::NoArgument.new do
- puts parser.help
- exit
- end
- end
-
# --version
# Shows version string if (({::Version})) is defined.
- Officious['version'] = proc do |parser|
- Switch::OptionalArgument.new do |pkg|
- if pkg
- begin
- require 'optparse/version'
- rescue LoadError
- else
- show_version(*pkg.split(/,/)) or
- abort("#{parser.program_name}: no version found in package #{pkg}")
- exit
- end
+ #
+ DefaultList.long['help'] = Switch::NoArgument.new do
+ puts ARGV.options
+ exit
+ end
+ DefaultList.long['version'] = Switch::OptionalArgument.new do |pkg|
+ if pkg
+ begin
+ require 'optparse/version'
+ rescue LoadError
+ pkg = nil
+ else
+ show_version(*pkg.split(/,/))
end
- v = parser.ver or abort("#{parser.program_name}: version unknown")
- puts v
- exit
end
+ unless pkg
+ v = ARGV.options.ver and puts v
+ end
+ exit
end
# :startdoc:
@@ -810,19 +809,9 @@ class OptionParser
@banner = banner
@summary_width = width
@summary_indent = indent
- @default_argv = ARGV
- add_officious
yield self if block_given?
end
- # :nodoc:
- def add_officious
- list = base()
- Officious.each_pair do |opt, block|
- list.long[opt] ||= block.call(self)
- end
- end
-
=begin
--- OptionParser.terminate([arg])
Terminates option parsing. Optional parameter ((|arg|)) would be
@@ -886,13 +875,9 @@ class OptionParser
--- OptionParser#program_name=(name)
Program name to be emitted in error message and default banner,
defaulted to (({$0})).
---- OptionParser#default_argv
---- OptionParser#default_argv=(argv)
- Strings to be parsed in default.
=end #'#"#`#
attr_writer :banner, :program_name
attr_accessor :summary_width, :summary_indent
- attr_accessor :default_argv
def banner
@banner ||= "Usage: #{program_name} [options]"
@@ -922,7 +907,7 @@ class OptionParser
attr_writer :version, :release
def version
- @version || (defined?(::Version) && ::Version)
+ @version || (defined?(::Version) && ::Version) || (defined?(::VERSION) && ::VERSION)
end
def release
@@ -1265,7 +1250,7 @@ class OptionParser
order!(argv, &block)
end
- def order!(argv = default_argv, &nonopt)
+ def order!(argv = ARGV, &nonopt)
opt, arg, sw, val, rest = nil
nonopt ||= proc {|arg| throw :terminate, arg}
argv.unshift(arg) if arg = catch(:terminate) {
@@ -1275,7 +1260,7 @@ class OptionParser
when /\A--([^=]*)(?:=(.*))?/
opt, rest = $1, $2
begin
- sw, = complete(:long, opt, true)
+ sw, = complete(:long, opt)
rescue ParseError
raise $!.set_option(arg, true)
end
@@ -1345,7 +1330,7 @@ class OptionParser
permute!(argv)
end
- def permute!(argv = default_argv)
+ def permute!(argv = ARGV)
nonopts = []
arg = nil
order!(argv) {|arg| nonopts << arg}
@@ -1371,7 +1356,7 @@ class OptionParser
parse!(argv)
end
- def parse!(argv = default_argv)
+ def parse!(argv = ARGV)
if ENV.include?('POSIXLY_CORRECT')
order!(argv)
else
@@ -1429,19 +1414,17 @@ class OptionParser
searching table.
: ((|opt|))
searching key.
- : ((|icase|))
- search case insensitive if true.
: ((|*pat|))
optional pattern for completion.
: (({block}))
yielded with the found value when succeeded.
=end #'#"#`#
- def complete(typ, opt, icase = false, *pat)
+ def complete(typ, opt, *pat)
if pat.empty?
search(typ, opt) {|sw| return [sw, opt]} # exact match or...
end
raise AmbiguousOption, catch(:ambiguous) {
- visit(:complete, typ, opt, icase, *pat) {|opt, *sw| return sw}
+ visit(:complete, typ, opt, *pat) {|opt, *sw| return sw}
raise InvalidOption, opt
}
end
@@ -1579,21 +1562,6 @@ class OptionParser
s
end
-=begin
-: Regexp
- Regular expression with option.
-=end
- accept(Regexp, %r"\A/((?:\\.|[^\\])*)/([[:alpha:]]+)?\z|.*") do |all, s, o|
- f = 0
- if o
- f |= Regexp::IGNORECASE if /i/ =~ o
- f |= Regexp::MULTILINE if /m/ =~ o
- f |= Regexp::EXTENDED if /x/ =~ o
- k = o.delete("^imx")
- end
- Regexp.new(s || all, f, k)
- end
-
=begin
= Exceptions
@@ -1678,7 +1646,7 @@ argument.
((<OptionParser::ParseError>))
=end #'#"#`#
class NeedlessArgument < ParseError
- const_set(:Reason, 'needless argument'.freeze)
+ const_set(:Reason, 'needles argument'.freeze)
end
=begin
@@ -1765,7 +1733,6 @@ Extends command line arguments array to parse itself.
=end #'#"#`#
def options
@optparse ||= OptionParser.new
- @optparse.default_argv = self
block_given? or return @optparse
begin
yield @optparse
diff --git a/lib/optparse/version.rb b/lib/optparse/version.rb
index 558d9d710b..8e99836878 100644
--- a/lib/optparse/version.rb
+++ b/lib/optparse/version.rb
@@ -3,47 +3,45 @@
class << OptionParser
def show_version(*pkg)
progname = ARGV.options.program_name
- result = false
- show = proc do |klass, cname, version|
+ show = proc do |klass, version|
+ version = version.join(".") if Array === version
str = "#{progname}"
- unless klass == ::Object and cname == :VERSION
- version = version.join(".") if Array === version
- str << ": #{klass}" unless klass == Object
- str << " version #{version}"
- end
- [:Release, :RELEASE].find do |rel|
- if klass.const_defined?(rel)
- str << " (#{klass.const_get(rel)})"
- end
+ str << ": #{klass}" unless klass == Object
+ str << " version #{version}"
+ case
+ when klass.const_defined?(:Release)
+ str << " (#{klass.const_get(:Release)})"
+ when klass.const_defined?(:RELEASE)
+ str << " (#{klass.const_get(:Release)})"
end
puts str
- result = true
end
if pkg.size == 1 and pkg[0] == "all"
self.search_const(::Object, /\AV(?:ERSION|ersion)\z/) do |klass, cname, version|
unless cname[1] == ?e and klass.const_defined?(:Version)
- show.call(klass, cname.intern, version)
+ show.call(klass, version)
end
end
else
pkg.each do |pkg|
+ /\A[A-Z]\w*((::|\/)[A-Z]\w*)*\z/ni =~ pkg or next
begin
- pkg = pkg.split(/::|\//).inject(::Object) {|m, c| m.const_get(c)}
+ pkg = eval(pkg)
v = case
when pkg.const_defined?(:Version)
- pkg.const_get(n = :Version)
+ pkg.const_get(:Version)
when pkg.const_defined?(:VERSION)
- pkg.const_get(n = :VERSION)
+ pkg.const_get(:VERSION)
else
- n = nil
"unknown"
end
- show.call(pkg, n, v)
+ show.call(pkg, v)
rescue NameError
+ puts "#{progname}: #$!"
end
end
end
- result
+ exit
end
def each_const(path, klass = ::Object)
diff --git a/lib/ostruct.rb b/lib/ostruct.rb
index 6af5bbdac0..d92ee503ad 100644
--- a/lib/ostruct.rb
+++ b/lib/ostruct.rb
@@ -47,33 +47,16 @@ class OpenStruct
@table = {}
if hash
for k,v in hash
- @table[k.to_sym] = v
- new_ostruct_member(k)
+ @table[k.to_sym] = v
end
end
end
- # Duplicate an OpenStruct object members.
- def initialize_copy(orig)
- super
- @table = @table.dup
- end
-
- def marshal_dump
- @table
- end
- def marshal_load(x)
- @table = x
- @table.each_key{|key| new_ostruct_member(key)}
- end
-
def new_ostruct_member(name)
- name = name.to_sym
- unless self.respond_to?(name)
- meta = class << self; self; end
- meta.send(:define_method, name) { @table[name] }
- meta.send(:define_method, :"#{name}=") { |x| @table[name] = x }
- end
+ self.instance_eval %{
+ def #{name}; @table[:#{name}]; end
+ def #{name}=(x); @table[:#{name}] = x; end
+ }
end
def method_missing(mid, *args) # :nodoc:
@@ -81,14 +64,14 @@ class OpenStruct
len = args.length
if mname =~ /=$/
if len != 1
- raise ArgumentError, "wrong number of arguments (#{len} for 1)", caller(1)
+ raise ArgumentError, "wrong number of arguments (#{len} for 1)", caller(1)
end
if self.frozen?
- raise TypeError, "can't modify frozen #{self.class}", caller(1)
+ raise TypeError, "can't modify frozen #{self.class}", caller(1)
end
mname.chop!
- self.new_ostruct_member(mname)
@table[mname.intern] = args[0]
+ self.new_ostruct_member(mname)
elsif len == 0
@table[mid]
else
@@ -103,35 +86,16 @@ class OpenStruct
@table.delete name.to_sym
end
- InspectKey = :__inspect_key__ # :nodoc:
-
#
# Returns a string containing a detailed summary of the keys and values.
#
def inspect
- str = "#<#{self.class}"
-
- Thread.current[InspectKey] ||= []
- if Thread.current[InspectKey].include?(self) then
- str << " ..."
- else
- first = true
- for k,v in @table
- str << "," unless first
- first = false
-
- Thread.current[InspectKey] << v
- begin
- str << " #{k}=#{v.inspect}"
- ensure
- Thread.current[InspectKey].pop
- end
- end
+ str = "<#{self.class}"
+ for k,v in @table
+ str << " #{k}=#{v.inspect}"
end
-
str << ">"
end
- alias :to_s :inspect
attr_reader :table # :nodoc:
protected :table
diff --git a/lib/parsearg.rb b/lib/parsearg.rb
index 9c67aca43e..d5f3c9638d 100644
--- a/lib/parsearg.rb
+++ b/lib/parsearg.rb
@@ -10,8 +10,6 @@
#
#
-warn "Warning:#{caller[0].sub(/:in `.*'\z/, '')}: parsearg is deprecated after Ruby 1.8.1; use optparse instead"
-
$RCS_ID=%q$Header$
require "getopts"
diff --git a/lib/pathname.rb b/lib/pathname.rb
index b21abd746b..663afcf5ed 100644
--- a/lib/pathname.rb
+++ b/lib/pathname.rb
@@ -254,7 +254,7 @@ class Pathname
# Clean the path simply by resolving and removing excess "." and ".." entries.
# Nothing more, nothing less.
#
- def cleanpath_aggressive
+ def cleanpath_aggressive # :nodoc:
# cleanpath_aggressive assumes:
# * no symlink
# * all pathname prefix contained in the pathname is existing directory
@@ -280,9 +280,8 @@ class Pathname
path << names.join('/')
Pathname.new(path)
end
- private :cleanpath_aggressive
- def cleanpath_conservative
+ def cleanpath_conservative # :nodoc:
return Pathname.new('') if @path == ''
names = @path.scan(%r{[^/]+})
last_dot = names.last == '.'
@@ -300,7 +299,6 @@ class Pathname
end
Pathname.new(path)
end
- private :cleanpath_conservative
#
# Returns a real (absolute) pathname of +self+ in the actual filesystem.
@@ -413,7 +411,7 @@ class Pathname
#
# Iterates over each component of the path.
#
- # Pathname.new("/usr/bin/ruby").each_filename {|filename| ... }
+ # Pathname.new("/usr/bin/ruby").each_filename
# # yields "usr", "bin", and "ruby".
#
def each_filename # :yield: s
@@ -860,9 +858,9 @@ class Pathname # * mixed *
# Removes a file or directory, using <tt>File.unlink</tt> or
# <tt>Dir.unlink</tt> as necessary.
def unlink()
- begin
+ if FileTest.directory? @path
Dir.unlink @path
- rescue Errno::ENOTDIR
+ else
File.unlink @path
end
end
diff --git a/lib/ping.rb b/lib/ping.rb
index 07b46374b2..7f970f96de 100644
--- a/lib/ping.rb
+++ b/lib/ping.rb
@@ -49,7 +49,7 @@ module Ping
end
rescue Errno::ECONNREFUSED
return true
- rescue Timeout::Error, StandardError
+ rescue Timeout::Error
return false
end
return true
diff --git a/lib/pp.rb b/lib/pp.rb
index 3fd3aeab3a..6ddd4dd2eb 100644
--- a/lib/pp.rb
+++ b/lib/pp.rb
@@ -1,47 +1,150 @@
-# == Pretty-printer for Ruby objects.
-#
-# = Which seems better?
-#
-# non-pretty-printed output by #p is:
-# #<PP:0x81fedf0 @genspace=#<Proc:0x81feda0>, @group_queue=#<PrettyPrint::GroupQueue:0x81fed3c @queue=[[#<PrettyPrint::Group:0x81fed78 @breakables=[], @depth=0, @break=false>], []]>, @buffer=[], @newline="\n", @group_stack=[#<PrettyPrint::Group:0x81fed78 @breakables=[], @depth=0, @break=false>], @buffer_width=0, @indent=0, @maxwidth=79, @output_width=2, @output=#<IO:0x8114ee4>>
-#
-# pretty-printed output by #pp is:
-# #<PP:0x81fedf0
-# @buffer=[],
-# @buffer_width=0,
-# @genspace=#<Proc:0x81feda0>,
-# @group_queue=
-# #<PrettyPrint::GroupQueue:0x81fed3c
-# @queue=
-# [[#<PrettyPrint::Group:0x81fed78 @break=false, @breakables=[], @depth=0>],
-# []]>,
-# @group_stack=
-# [#<PrettyPrint::Group:0x81fed78 @break=false, @breakables=[], @depth=0>],
-# @indent=0,
-# @maxwidth=79,
-# @newline="\n",
-# @output=#<IO:0x8114ee4>,
-# @output_width=2>
-#
-# I like the latter. If you do too, this library is for you.
-#
-# = Usage
-#
-# pp(obj)
-#
-# output +obj+ to +$>+ in pretty printed format.
-#
-# It returns +nil+.
-#
-# = Output Customization
-# To define your customized pretty printing function for your classes,
-# redefine a method #pretty_print(+pp+) in the class.
-# It takes an argument +pp+ which is an instance of the class PP.
-# The method should use PP#text, PP#breakable, PP#nest, PP#group and
-# PP#pp to print the object.
-#
-# = Author
-# Tanaka Akira <akr@m17n.org>
+# $Id$
+
+=begin
+= Pretty-printer for Ruby objects.
+
+== Which seems better?
+
+non-pretty-printed output by (({p})) is:
+ #<PP:0x81fedf0 @genspace=#<Proc:0x81feda0>, @group_queue=#<PrettyPrint::GroupQueue:0x81fed3c @queue=[[#<PrettyPrint::Group:0x81fed78 @breakables=[], @depth=0, @break=false>], []]>, @buffer=[], @newline="\n", @group_stack=[#<PrettyPrint::Group:0x81fed78 @breakables=[], @depth=0, @break=false>], @buffer_width=0, @indent=0, @maxwidth=79, @output_width=2, @output=#<IO:0x8114ee4>>
+
+pretty-printed output by (({pp})) is:
+ #<PP:0x81fedf0
+ @buffer=[],
+ @buffer_width=0,
+ @genspace=#<Proc:0x81feda0>,
+ @group_queue=
+ #<PrettyPrint::GroupQueue:0x81fed3c
+ @queue=
+ [[#<PrettyPrint::Group:0x81fed78 @break=false, @breakables=[], @depth=0>],
+ []]>,
+ @group_stack=
+ [#<PrettyPrint::Group:0x81fed78 @break=false, @breakables=[], @depth=0>],
+ @indent=0,
+ @maxwidth=79,
+ @newline="\n",
+ @output=#<IO:0x8114ee4>,
+ @output_width=2>
+
+I like the latter. If you do too, this library is for you.
+
+== Usage
+
+: pp(obj)
+ output ((|obj|)) to (({$>})) in pretty printed format.
+
+ It returns (({nil})).
+
+== Output Customization
+To define your customized pretty printing function for your classes,
+redefine a method (({pretty_print(((|pp|)))})) in the class.
+It takes an argument ((|pp|)) which is an instance of the class ((<PP>)).
+The method should use PP#text, PP#breakable, PP#nest, PP#group and
+PP#pp to print the object.
+
+= PP
+== super class
+((<PrettyPrint>))
+
+== class methods
+--- PP.pp(obj[, out[, width]])
+ outputs ((|obj|)) to ((|out|)) in pretty printed format of
+ ((|width|)) columns in width.
+
+ If ((|out|)) is omitted, (({$>})) is assumed.
+ If ((|width|)) is omitted, 79 is assumed.
+
+ PP.pp returns ((|out|)).
+
+--- PP.singleline_pp(obj[, out])
+ outputs ((|obj|)) to ((|out|)) like (({PP.pp})) but with no indent and
+ newline.
+
+ PP.singleline_pp returns ((|out|)).
+
+--- PP.sharing_detection
+ returns the sharing detection flag as a boolean value.
+ It is false by default.
+
+--- PP.sharing_detection = boolean_value
+ sets the sharing detection flag.
+
+== methods
+--- pp(obj)
+ adds ((|obj|)) to the pretty printing buffer
+ using Object#pretty_print or Object#pretty_print_cycle.
+
+ Object#pretty_print_cycle is used when ((|obj|)) is already
+ printed, a.k.a the object reference chain has a cycle.
+
+--- object_group(obj) { ... }
+ is a convenience method which is same as follows:
+
+ group(1, '#<' + obj.class.name, '>') { ... }
+
+--- comma_breakable
+ is a convenience method which is same as follows:
+
+ text ','
+ breakable
+
+--- seplist(list[, separator_proc[, iter_method]]) {|elt| ... }
+ adds a separated list.
+ The list is separated by comma with breakable space, by default.
+
+ seplist iterates the ((|list|)) using ((|iter_method|)).
+ It yields each object to the block given for seplist.
+ The procedure ((|separator_proc|)) is called between each yields.
+
+ If the iteration is zero times, ((|separator_proc|)) is not called at all.
+
+ If ((|separator_proc|)) is nil or not given,
+ (({lambda { comma_breakable }})) is used.
+ If ((|iter_method|)) is not given, (({:each})) is used.
+
+ For example, following 3 code fragments has similar effect.
+
+ q.seplist([1,2,3]) {|v| xxx v }
+
+ q.seplist([1,2,3], lambda { comma_breakable }, :each) {|v| xxx v }
+
+ xxx 1
+ q.comma_breakable
+ xxx 2
+ q.comma_breakable
+ xxx 3
+
+= Object
+--- pretty_print(pp)
+ is a default pretty printing method for general objects.
+ It calls (({pretty_print_instance_variables})) to list instance variables.
+
+ If (({self})) has a customized (redefined) (({inspect})) method,
+ the result of (({self.inspect})) is used but it obviously has no
+ line break hints.
+
+ This module provides predefined pretty_print() methods for some of
+ the most commonly used built-in classes for convenience.
+
+--- pretty_print_cycle(pp)
+ is a default pretty printing method for general objects that are
+ detected as part of a cycle.
+
+--- pretty_print_instance_variables
+ returns a sorted array of instance variable names.
+
+ This method should return an array of names of instance variables as symbols or strings as:
+ (({[:@a, :@b]})).
+
+--- pretty_print_inspect
+ is (({inspect})) implementation using (({pretty_print})).
+ If you implement (({pretty_print})), it can be used as follows.
+
+ alias inspect pretty_print_inspect
+
+== AUTHOR
+Tanaka Akira <akr@m17n.org>
+=end
require 'prettyprint'
@@ -57,13 +160,6 @@ module Kernel
end
class PP < PrettyPrint
- # Outputs +obj+ to +out+ in pretty printed format of
- # +width+ columns in width.
- #
- # If +out+ is omitted, +$>+ is assumed.
- # If +width+ is omitted, 79 is assumed.
- #
- # PP.pp returns +out+.
def PP.pp(obj, out=$>, width=79)
q = PP.new(out, width)
q.guard_inspect_key {q.pp obj}
@@ -72,10 +168,6 @@ class PP < PrettyPrint
out << "\n"
end
- # Outputs +obj+ to +out+ like PP.pp but with no indent and
- # newline.
- #
- # PP.singleline_pp returns +out+.
def PP.singleline_pp(obj, out=$>)
q = SingleLine.new(out)
q.guard_inspect_key {q.pp obj}
@@ -85,8 +177,6 @@ class PP < PrettyPrint
@sharing_detection = false
class << self
- # Returns the sharing detection flag as a boolean value.
- # It is false by default.
attr_accessor :sharing_detection
end
@@ -108,11 +198,6 @@ class PP < PrettyPrint
end
end
- # Adds +obj+ to the pretty printing buffer
- # using Object#pretty_print or Object#pretty_print_cycle.
- #
- # Object#pretty_print_cycle is used when +obj+ is already
- # printed, a.k.a the object reference chain has a cycle.
def pp(obj)
id = obj.__id__
@@ -129,53 +214,20 @@ class PP < PrettyPrint
end
end
- # A convenience method which is same as follows:
- #
- # group(1, '#<' + obj.class.name, '>') { ... }
- def object_group(obj, &block) # :yield:
+ def object_group(obj, &block)
group(1, '#<' + obj.class.name, '>', &block)
end
def object_address_group(obj, &block)
- id = "%x" % (obj.__id__ * 2)
- id.sub!(/\Af(?=[[:xdigit:]]{2}+\z)/, '') if id.sub!(/\A\.\./, '')
- group(1, "\#<#{obj.class}:0x#{id}", '>', &block)
+ group(1, "\#<#{obj.class}:#{("0x%x" % (obj.__id__ * 2)).sub(/\.\.f/, '')}", '>', &block)
end
- # A convenience method which is same as follows:
- #
- # text ','
- # breakable
def comma_breakable
text ','
breakable
end
- # Adds a separated list.
- # The list is separated by comma with breakable space, by default.
- #
- # #seplist iterates the +list+ using +iter_method+.
- # It yields each object to the block given for #seplist.
- # The procedure +separator_proc+ is called between each yields.
- #
- # If the iteration is zero times, +separator_proc+ is not called at all.
- #
- # If +separator_proc+ is nil or not given,
- # +lambda { comma_breakable }+ is used.
- # If +iter_method+ is not given, :each is used.
- #
- # For example, following 3 code fragments has similar effect.
- #
- # q.seplist([1,2,3]) {|v| xxx v }
- #
- # q.seplist([1,2,3], lambda { comma_breakable }, :each) {|v| xxx v }
- #
- # xxx 1
- # q.comma_breakable
- # xxx 2
- # q.comma_breakable
- # xxx 3
- def seplist(list, sep=nil, iter_method=:each) # :yield: element
+ def seplist(list, sep=nil, iter_method=:each)
sep ||= lambda { comma_breakable }
first = true
list.__send__(iter_method) {|*v|
@@ -231,15 +283,6 @@ class PP < PrettyPrint
# 3. specific to_s if instance variable is empty
# 4. generic pretty_print
- # A default pretty printing method for general objects.
- # It calls #pretty_print_instance_variables to list instance variables.
- #
- # If +self+ has a customized (redefined) #inspect method,
- # the result of self.inspect is used but it obviously has no
- # line break hints.
- #
- # This module provides predefined #pretty_print methods for some of
- # the most commonly used built-in classes for convenience.
def pretty_print(q)
if /\(Kernel\)#/ !~ method(:inspect).inspect
q.text self.inspect
@@ -250,8 +293,6 @@ class PP < PrettyPrint
end
end
- # A default pretty printing method for general objects that are
- # detected as part of a cycle.
def pretty_print_cycle(q)
q.object_address_group(self) {
q.breakable
@@ -259,21 +300,10 @@ class PP < PrettyPrint
}
end
- # Returns a sorted array of instance variable names.
- #
- # This method should return an array of names of instance variables as symbols or strings as:
- # +[:@a, :@b]+.
def pretty_print_instance_variables
instance_variables.sort
end
- # Is #inspect implementation using #pretty_print.
- # If you implement #pretty_print, it can be used as follows.
- #
- # alias inspect pretty_print_inspect
- #
- # However, doing this requires that every class that #inspect is called on
- # implement #pretty_print, or a RuntimeError will be raised.
def pretty_print_inspect
if /\(PP::ObjectMixin\)#/ =~ method(:pretty_print).inspect
raise "pretty_print is not overridden."
@@ -375,23 +405,19 @@ class File
q.group {
q.text "uid="; q.pp self.uid
begin
- pw = Etc.getpwuid(self.uid)
+ name = Etc.getpwuid(self.uid).name
+ q.breakable; q.text "(#{name})"
rescue ArgumentError
end
- if pw
- q.breakable; q.text "(#{pw.name})"
- end
}
q.comma_breakable
q.group {
q.text "gid="; q.pp self.gid
begin
- gr = Etc.getgrgid(self.gid)
+ name = Etc.getgrgid(self.gid).name
+ q.breakable; q.text "(#{name})"
rescue ArgumentError
end
- if gr
- q.breakable; q.text "(#{gr.name})"
- end
}
q.comma_breakable
q.group {
@@ -456,7 +482,6 @@ end
}
}
-# :enddoc:
if __FILE__ == $0
require 'test/unit'
diff --git a/lib/profiler.rb b/lib/profiler.rb
index 9762fa1181..74e9b96295 100644
--- a/lib/profiler.rb
+++ b/lib/profiler.rb
@@ -1,29 +1,40 @@
module Profiler__
+ Times = if defined? Process.times then Process else Time end
# internal values
@@start = @@stack = @@map = nil
PROFILE_PROC = proc{|event, file, line, id, binding, klass|
case event
when "call", "c-call"
- now = Process.times[0]
- @@stack.push [now, 0.0]
+ now = Float(Times::times[0])
+ @@stack.push [now, 0.0, id]
when "return", "c-return"
- now = Process.times[0]
- key = [klass, id]
- if tick = @@stack.pop
- data = (@@map[key] ||= [0, 0.0, 0.0, key])
- data[0] += 1
- cost = now - tick[0]
- data[1] += cost
- data[2] += cost - tick[1]
- @@stack[-1][1] += cost if @@stack[-1]
+ now = Float(Times::times[0])
+ tick = @@stack.pop
+ name = klass.to_s
+ if name.nil? then name = '' end
+ if klass.kind_of? Class
+ name += "#"
+ else
+ name += "."
end
+ name += id.id2name
+ data = @@map[name]
+ unless data
+ data = [0.0, 0.0, 0.0, name]
+ @@map[name] = data
+ end
+ data[0] += 1
+ cost = now - tick[0]
+ data[1] += cost
+ data[2] += cost - tick[1]
+ @@stack[-1][1] += cost
end
}
module_function
def start_profile
- @@start = Process.times[0]
- @@stack = []
- @@map = {}
+ @@start = Float(Times::times[0])
+ @@stack = [[0, 0, :toplevel], [0, 0, :dummy]]
+ @@map = {"#toplevel" => [1, 0, 0, "#toplevel"]}
set_trace_func PROFILE_PROC
end
def stop_profile
@@ -31,29 +42,18 @@ module_function
end
def print_profile(f)
stop_profile
- total = Process.times[0] - @@start
+ total = Float(Times::times[0]) - @@start
if total == 0 then total = 0.01 end
+ @@map["#toplevel"][1] = total
data = @@map.values
data.sort!{|a,b| b[2] <=> a[2]}
sum = 0
- f.printf " %% cumulative self self total\n"
+ f.printf " %% cumulative self self total\n"
f.printf " time seconds seconds calls ms/call ms/call name\n"
for d in data
sum += d[2]
f.printf "%6.2f %8.2f %8.2f %8d ", d[2]/total*100, sum, d[2], d[0]
- f.printf "%8.2f %8.2f %s\n", d[2]*1000/d[0], d[1]*1000/d[0], get_name(*d[3])
- end
- f.printf "%6.2f %8.2f %8.2f %8d ", 0.0, total, 0.0, 1 # ???
- f.printf "%8.2f %8.2f %s\n", 0.0, total*1000, "#toplevel" # ???
- end
- def get_name(klass, id)
- name = klass.to_s || ""
- if klass.kind_of? Class
- name += "#"
- else
- name += "."
+ f.printf "%8.2f %8.2f %s\n", d[2]*1000/d[0], d[1]*1000/d[0], d[3]
end
- name + id.id2name
end
- private :get_name
end
diff --git a/lib/pstore.rb b/lib/pstore.rb
index a691ce611e..51cef6e134 100644
--- a/lib/pstore.rb
+++ b/lib/pstore.rb
@@ -1,91 +1,24 @@
-# = PStore -- Transactional File Storage for Ruby Objects
#
-# pstore.rb -
-# originally by matz
-# documentation by Kev Jackson and James Edward Gray II
+# How to use:
#
-# See PStore for documentation.
+# db = PStore.new("/tmp/foo")
+# db.transaction do
+# p db.roots
+# ary = db["root"] = [1,2,3,4]
+# ary[0] = [1,1.5]
+# end
+# db.transaction do
+# p db["root"]
+# end
require "fileutils"
require "digest/md5"
-#
-# PStore implements a file based persistance mechanism based on a Hash. User
-# code can store hierarchies of Ruby objects (values) into the data store file
-# by name (keys). An object hierarchy may be just a single object. User code
-# may later read values back from the data store or even update data, as needed.
-#
-# The transactional behavior ensures that any changes succeed or fail together.
-# This can be used to ensure that the data store is not left in a transitory
-# state, where some values were upated but others were not.
-#
-# Behind the scenes, Ruby objects are stored to the data store file with
-# Marshal. That carries the usual limitations. Proc objects cannot be
-# marshalled, for example.
-#
-# == Usage example:
-#
-# require "pstore"
-#
-# # a mock wiki object...
-# class WikiPage
-# def initialize( page_name, author, contents )
-# @page_name = page_name
-# @revisions = Array.new
-#
-# add_revision(author, contents)
-# end
-#
-# attr_reader :page_name
-#
-# def add_revision( author, contents )
-# @revisions << { :created => Time.now,
-# :author => author,
-# :contents => contents }
-# end
-#
-# def wiki_page_references
-# [@page_name] + @revisions.last[:contents].scan(/\b(?:[A-Z]+[a-z]+){2,}/)
-# end
-#
-# # ...
-# end
-#
-# # create a new page...
-# home_page = WikiPage.new( "HomePage", "James Edward Gray II",
-# "A page about the JoysOfDocumentation..." )
-#
-# # then we want to update page data and the index together, or not at all...
-# wiki = PStore.new("wiki_pages.pstore")
-# wiki.transaction do # begin transaction; do all of this or none of it
-# # store page...
-# wiki[home_page.page_name] = home_page
-# # ensure that an index has been created...
-# wiki[:wiki_index] ||= Array.new
-# # update wiki index...
-# wiki[:wiki_index].push(*home_page.wiki_page_references)
-# end # commit changes to wiki data store file
-#
-# ### Some time later... ###
-#
-# # read wiki data...
-# wiki.transaction(true) do # begin read-only transaction, no changes allowed
-# wiki.roots.each do |data_root_name|
-# p data_root_name
-# p wiki[data_root_name]
-# end
-# end
-#
class PStore
- # The error type thrown by all PStore methods.
class Error < StandardError
end
- #
- # To construct a PStore object, pass in the _file_ path where you would like
- # the data to be stored.
- #
def initialize(file)
dir = File::dirname(file)
unless File::directory? dir
@@ -99,41 +32,19 @@ class PStore
@abort = false
end
- # Raises PStore::Error if the calling code is not in a PStore#transaction.
def in_transaction
raise PStore::Error, "not in transaction" unless @transaction
end
- #
- # Raises PStore::Error if the calling code is not in a PStore#transaction or
- # if the code is in a read-only PStore#transaction.
- #
def in_transaction_wr()
in_transaction()
raise PStore::Error, "in read-only transaction" if @rdonly
end
private :in_transaction, :in_transaction_wr
- #
- # Retrieves a value from the PStore file data, by _name_. The hierarchy of
- # Ruby objects stored under that root _name_ will be returned.
- #
- # *WARNING*: This method is only valid in a PStore#transaction. It will
- # raise PStore::Error if called at any other time.
- #
def [](name)
in_transaction
@table[name]
end
- #
- # This method is just like PStore#[], save that you may also provide a
- # _default_ value for the object. In the event the specified _name_ is not
- # found in the data store, your _default_ will be returned instead. If you do
- # not specify a default, PStore::Error will be raised if the object is not
- # found.
- #
- # *WARNING*: This method is only valid in a PStore#transaction. It will
- # raise PStore::Error if called at any other time.
- #
def fetch(name, default=PStore::Error)
unless @table.key? name
if default==PStore::Error
@@ -144,138 +55,39 @@ class PStore
end
self[name]
end
- #
- # Stores an individual Ruby object or a hierarchy of Ruby objects in the data
- # store file under the root _name_. Assigning to a _name_ already in the data
- # store clobbers the old data.
- #
- # == Example:
- #
- # require "pstore"
- #
- # store = PStore.new("data_file.pstore")
- # store.transaction do # begin transaction
- # # load some data into the store...
- # store[:single_object] = "My data..."
- # store[:obj_heirarchy] = { "Kev Jackson" => ["rational.rb", "pstore.rb"],
- # "James Gray" => ["erb.rb", "pstore.rb"] }
- # end # commit changes to data store file
- #
- # *WARNING*: This method is only valid in a PStore#transaction and it cannot
- # be read-only. It will raise PStore::Error if called at any other time.
- #
def []=(name, value)
in_transaction_wr()
@table[name] = value
end
- #
- # Removes an object hierarchy from the data store, by _name_.
- #
- # *WARNING*: This method is only valid in a PStore#transaction and it cannot
- # be read-only. It will raise PStore::Error if called at any other time.
- #
def delete(name)
in_transaction_wr()
@table.delete name
end
- #
- # Returns the names of all object hierarchies currently in the store.
- #
- # *WARNING*: This method is only valid in a PStore#transaction. It will
- # raise PStore::Error if called at any other time.
- #
def roots
in_transaction
@table.keys
end
- #
- # Returns true if the supplied _name_ is currently in the data store.
- #
- # *WARNING*: This method is only valid in a PStore#transaction. It will
- # raise PStore::Error if called at any other time.
- #
def root?(name)
in_transaction
@table.key? name
end
- # Returns the path to the data store file.
def path
@filename
end
- #
- # Ends the current PStore#transaction, committing any changes to the data
- # store immediately.
- #
- # == Example:
- #
- # require "pstore"
- #
- # store = PStore.new("data_file.pstore")
- # store.transaction do # begin transaction
- # # load some data into the store...
- # store[:one] = 1
- # store[:two] = 2
- #
- # store.commit # end transaction here, committing changes
- #
- # store[:three] = 3 # this change is never reached
- # end
- #
- # *WARNING*: This method is only valid in a PStore#transaction. It will
- # raise PStore::Error if called at any other time.
- #
def commit
in_transaction
@abort = false
throw :pstore_abort_transaction
end
- #
- # Ends the current PStore#transaction, discarding any changes to the data
- # store.
- #
- # == Example:
- #
- # require "pstore"
- #
- # store = PStore.new("data_file.pstore")
- # store.transaction do # begin transaction
- # store[:one] = 1 # this change is not applied, see below...
- # store[:two] = 2 # this change is not applied, see below...
- #
- # store.abort # end transaction here, discard all changes
- #
- # store[:three] = 3 # this change is never reached
- # end
- #
- # *WARNING*: This method is only valid in a PStore#transaction. It will
- # raise PStore::Error if called at any other time.
- #
def abort
in_transaction
@abort = true
throw :pstore_abort_transaction
end
- #
- # Opens a new transaction for the data store. Code executed inside a block
- # passed to this method may read and write data to and from the data store
- # file.
- #
- # At the end of the block, changes are committed to the data store
- # automatically. You may exit the transaction early with a call to either
- # PStore#commit or PStore#abort. See those methods for details about how
- # changes are handled. Raising an uncaught Exception in the block is
- # equivalent to calling PStore#abort.
- #
- # If _read_only_ is set to +true+, you will only be allowed to read from the
- # data store during the transaction and any attempts to change the data will
- # raise a PStore::Error.
- #
- # Note that PStore does not support nested transactions.
- #
- def transaction(read_only=false) # :yields: pstore
+ def transaction(read_only=false)
raise PStore::Error, "nested transaction" if @transaction
begin
@rdonly = read_only
@@ -343,23 +155,19 @@ class PStore
value
end
- # This method is just a wrapped around Marshal.dump.
- def dump(table) # :nodoc:
+ def dump(table)
Marshal::dump(table)
end
- # This method is just a wrapped around Marshal.load.
- def load(content) # :nodoc:
+ def load(content)
Marshal::load(content)
end
- # This method is just a wrapped around Marshal.load.
- def load_file(file) # :nodoc:
+ def load_file(file)
Marshal::load(file)
end
private
- # Commits changes to the data store file.
def commit_new(f)
f.truncate(0)
f.rewind
@@ -372,8 +180,6 @@ class PStore
end
end
-# :enddoc:
-
if __FILE__ == $0
db = PStore.new("/tmp/foo")
db.transaction do
diff --git a/lib/rational.rb b/lib/rational.rb
index 3f15cfafa8..2019363ac6 100644
--- a/lib/rational.rb
+++ b/lib/rational.rb
@@ -1,33 +1,41 @@
#
-# rational.rb -
-# $Release Version: 0.5 $
-# $Revision: 1.7 $
-# $Date: 1999/08/24 12:49:28 $
-# by Keiju ISHITSUKA(SHL Japan Inc.)
+# rational.rb -
+# $Release Version: 0.5 $
+# $Revision: 1.7 $
+# $Date: 1999/08/24 12:49:28 $
+# by Keiju ISHITSUKA(SHL Japan Inc.)
#
-# Documentation by Kevin Jackson and Gavin Sinclair.
-#
-# When you <tt>require 'rational'</tt>, all interactions between numbers
-# potentially return a rational result. For example:
+# --
+# Usage:
+# class Rational < Numeric
+# (include Comparable)
#
-# 1.quo(2) # -> 0.5
-# require 'rational'
-# 1.quo(2) # -> Rational(1,2)
-#
-# See Rational for full documentation.
+# Rational(a, b) --> a/b
#
-
-
-#
-# Creates a Rational number (i.e. a fraction). +a+ and +b+ should be Integers:
-#
-# Rational(1,3) # -> 1/3
+# Rational::+
+# Rational::-
+# Rational::*
+# Rational::/
+# Rational::**
+# Rational::%
+# Rational::divmod
+# Rational::abs
+# Rational::<=>
+# Rational::to_i
+# Rational::to_f
+# Rational::to_s
#
-# Note: trying to construct a Rational with floating point or real values
-# produces errors:
+# Integer::gcd
+# Integer::lcm
+# Integer::gcdlcm
+# Integer::to_r
#
-# Rational(1.1, 2.3) # -> NoMethodError
+# Fixnum::**
+# Fixnum::quo
+# Bignum::**
+# Bignum::quo
#
+
def Rational(a, b = 1)
if a.kind_of?(Rational) && b == 1
a
@@ -35,39 +43,10 @@ def Rational(a, b = 1)
Rational.reduce(a, b)
end
end
-
-#
-# Rational implements a rational class for numbers.
-#
-# <em>A rational number is a number that can be expressed as a fraction p/q
-# where p and q are integers and q != 0. A rational number p/q is said to have
-# numerator p and denominator q. Numbers that are not rational are called
-# irrational numbers.</em> (http://mathworld.wolfram.com/RationalNumber.html)
-#
-# To create a Rational Number:
-# Rational(a,b) # -> a/b
-# Rational.new!(a,b) # -> a/b
-#
-# Examples:
-# Rational(5,6) # -> 5/6
-# Rational(5) # -> 5/1
-#
-# Rational numbers are reduced to their lowest terms:
-# Rational(6,10) # -> 3/5
-#
-# But not if you use the unusual method "new!":
-# Rational.new!(6,10) # -> 6/10
-#
-# Division by zero is obviously not allowed:
-# Rational(3,0) # -> ZeroDivisionError
-#
+
class Rational < Numeric
@RCS_ID='-$Id: rational.rb,v 1.7 1999/08/24 12:49:28 keiju Exp keiju $-'
- #
- # Reduces the given numerator and denominator to their lowest terms. Use
- # Rational() instead.
- #
def Rational.reduce(num, den = 1)
raise ZeroDivisionError, "denominator is zero" if den == 0
@@ -84,21 +63,13 @@ class Rational < Numeric
new!(num, den)
end
end
-
- #
- # Implements the constructor. This method does not reduce to lowest terms or
- # check for division by zero. Therefore #Rational() should be preferred in
- # normal use.
- #
+
def Rational.new!(num, den = 1)
new(num, den)
end
private_class_method :new
- #
- # This method is actually private.
- #
def initialize(num, den)
if den < 0
num = -num
@@ -112,15 +83,7 @@ class Rational < Numeric
@denominator = den.to_i
end
end
-
- #
- # Returns the addition of this value and +a+.
- #
- # Examples:
- # r = Rational(3,4) # -> Rational(3,4)
- # r + 1 # -> Rational(7,4)
- # r + 0.5 # -> 1.25
- #
+
def + (a)
if a.kind_of?(Rational)
num = @numerator * a.denominator
@@ -135,16 +98,7 @@ class Rational < Numeric
x + y
end
end
-
- #
- # Returns the difference of this value and +a+.
- # subtracted.
- #
- # Examples:
- # r = Rational(3,4) # -> Rational(3,4)
- # r - 1 # -> Rational(-1,4)
- # r - 0.5 # -> 0.25
- #
+
def - (a)
if a.kind_of?(Rational)
num = @numerator * a.denominator
@@ -159,17 +113,7 @@ class Rational < Numeric
x - y
end
end
-
- #
- # Returns the product of this value and +a+.
- #
- # Examples:
- # r = Rational(3,4) # -> Rational(3,4)
- # r * 2 # -> Rational(3,2)
- # r * 4 # -> Rational(3,1)
- # r * 0.5 # -> 0.375
- # r * Rational(1,2) # -> Rational(3,8)
- #
+
def * (a)
if a.kind_of?(Rational)
num = @numerator * a.numerator
@@ -184,14 +128,7 @@ class Rational < Numeric
x * y
end
end
-
- #
- # Returns the quotient of this value and +a+.
- # r = Rational(3,4) # -> Rational(3,4)
- # r / 2 # -> Rational(3,8)
- # r / 2.0 # -> 0.375
- # r / Rational(1,2) # -> Rational(3,2)
- #
+
def / (a)
if a.kind_of?(Rational)
num = @numerator * a.denominator
@@ -207,16 +144,7 @@ class Rational < Numeric
x / y
end
end
-
- #
- # Returns this value raised to the given power.
- #
- # Examples:
- # r = Rational(3,4) # -> Rational(3,4)
- # r ** 2 # -> Rational(9,16)
- # r ** 2.0 # -> 0.5625
- # r ** Rational(1,2) # -> 0.866025403784439
- #
+
def ** (other)
if other.kind_of?(Rational)
Float(self) ** other
@@ -239,37 +167,17 @@ class Rational < Numeric
x ** y
end
end
-
- #
- # Returns the remainder when this value is divided by +other+.
- #
- # Examples:
- # r = Rational(7,4) # -> Rational(7,4)
- # r % Rational(1,2) # -> Rational(1,4)
- # r % 1 # -> Rational(3,4)
- # r % Rational(1,7) # -> Rational(1,28)
- # r % 0.26 # -> 0.19
- #
+
def % (other)
value = (self / other).to_i
return self - other * value
end
-
- #
- # Returns the quotient _and_ remainder.
- #
- # Examples:
- # r = Rational(7,4) # -> Rational(7,4)
- # r.divmod Rational(1,2) # -> [3, Rational(1,4)]
- #
+
def divmod(other)
value = (self / other).to_i
return value, self - other * value
end
-
- #
- # Returns the absolute value.
- #
+
def abs
if @numerator > 0
Rational.new!(@numerator, @denominator)
@@ -278,15 +186,6 @@ class Rational < Numeric
end
end
- #
- # Returns +true+ iff this value is numerically equal to +other+.
- #
- # But beware:
- # Rational(1,2) == Rational(4,8) # -> true
- # Rational(1,2) == Rational.new!(4,8) # -> false
- #
- # Don't use Rational.new!
- #
def == (other)
if other.kind_of?(Rational)
@numerator == other.numerator and @denominator == other.denominator
@@ -299,9 +198,6 @@ class Rational < Numeric
end
end
- #
- # Standard comparison operator.
- #
def <=> (other)
if other.kind_of?(Rational)
num = @numerator * other.denominator
@@ -336,35 +232,14 @@ class Rational < Numeric
end
end
- #
- # Converts the rational to an Integer. Not the _nearest_ integer, the
- # truncated integer. Study the following example carefully:
- # Rational(+7,4).to_i # -> 1
- # Rational(-7,4).to_i # -> -2
- # (-1.75).to_i # -> -1
- #
- # In other words:
- # Rational(-7,4) == -1.75 # -> true
- # Rational(-7,4).to_i == (-1.75).to_i # false
- #
def to_i
Integer(@numerator.div(@denominator))
end
-
- #
- # Converts the rational to a Float.
- #
+
def to_f
@numerator.to_f/@denominator.to_f
end
-
- #
- # Returns a string representation of the rational number.
- #
- # Example:
- # Rational(3,4).to_s # "3/4"
- # Rational(8).to_s # "8"
- #
+
def to_s
if @denominator == 1
@numerator.to_s
@@ -372,69 +247,38 @@ class Rational < Numeric
@numerator.to_s+"/"+@denominator.to_s
end
end
-
- #
- # Returns +self+.
- #
+
def to_r
self
end
-
- #
- # Returns a reconstructable string representation:
- #
- # Rational(5,8).inspect # -> "Rational(5, 8)"
- #
+
def inspect
sprintf("Rational(%s, %s)", @numerator.inspect, @denominator.inspect)
end
-
- #
- # Returns a hash code for the object.
- #
+
def hash
@numerator.hash ^ @denominator.hash
end
-
+
attr :numerator
attr :denominator
-
+
private :initialize
end
class Integer
- #
- # In an integer, the value _is_ the numerator of its rational equivalent.
- # Therefore, this method returns +self+.
- #
def numerator
self
end
-
- #
- # In an integer, the denominator is 1. Therefore, this method returns 1.
- #
+
def denominator
1
end
-
- #
- # Returns a Rational representation of this integer.
- #
+
def to_r
Rational(self, 1)
end
-
- #
- # Returns the <em>greatest common denominator</em> of the two numbers (+self+
- # and +n+).
- #
- # Examples:
- # 72.gcd 168 # -> 24
- # 19.gcd 36 # -> 1
- #
- # The result is positive, no matter the sign of the arguments.
- #
+
def gcd(n)
m = self.abs
n = n.abs
@@ -454,13 +298,13 @@ class Integer
end
m << b
end
-
+
def gcd2(int)
a = self.abs
b = int.abs
-
+
a, b = b, a if a < b
-
+
while b != 0
void, a = a.divmod(b)
a, b = b, a
@@ -468,49 +312,29 @@ class Integer
return a
end
- #
- # Returns the <em>lowest common multiple</em> (LCM) of the two arguments
- # (+self+ and +other+).
- #
- # Examples:
- # 6.lcm 7 # -> 42
- # 6.lcm 9 # -> 18
- #
- def lcm(other)
- if self.zero? or other.zero?
- 0
- else
- (self.div(self.gcd(other)) * other).abs
- end
+ def lcm(int)
+ a = self.abs
+ b = int.abs
+ gcd = a.gcd(b)
+ (a.div(gcd)) * b
end
-
- #
- # Returns the GCD _and_ the LCM (see #gcd and #lcm) of the two arguments
- # (+self+ and +other+). This is more efficient than calculating them
- # separately.
- #
- # Example:
- # 6.gcdlcm 9 # -> [3, 18]
- #
- def gcdlcm(other)
- gcd = self.gcd(other)
- if self.zero? or other.zero?
- [gcd, 0]
- else
- [gcd, (self.div(gcd) * other).abs]
- end
+
+ def gcdlcm(int)
+ a = self.abs
+ b = int.abs
+ gcd = a.gcd(b)
+ return gcd, (a.div(gcd)) * b
end
+
end
class Fixnum
undef quo
- # If Rational is defined, returns a Rational number instead of a Fixnum.
def quo(other)
Rational.new!(self,1) / other
end
alias rdiv quo
-
- # Returns a Rational number if the result is in fact rational (i.e. +other+ < 0).
+
def rpower (other)
if other >= 0
self.power!(other)
@@ -520,7 +344,7 @@ class Fixnum
end
unless defined? 1.power!
- alias power! **
+ alias power! **
alias ** rpower
end
end
@@ -531,13 +355,11 @@ class Bignum
end
undef quo
- # If Rational is defined, returns a Rational number instead of a Bignum.
def quo(other)
Rational.new!(self,1) / other
end
alias rdiv quo
-
- # Returns a Rational number if the result is in fact rational (i.e. +other+ < 0).
+
def rpower (other)
if other >= 0
self.power!(other)
@@ -545,7 +367,7 @@ class Bignum
Rational.new!(self, 1)**other
end
end
-
+
unless defined? Complex
alias ** rpower
end
diff --git a/lib/rdoc/README b/lib/rdoc/README
index 60650dd88b..5e90d792a2 100644
--- a/lib/rdoc/README
+++ b/lib/rdoc/README
@@ -422,23 +422,6 @@ this margin are formatted verbatim.
12. Comment blocks can contain other directives:
- [<tt>:section: title</tt>]
- Starts a new section in the output. The title following
- <tt>:section:</tt> is used as the section heading, and the
- remainder of the comment containing the section is used as
- introductory text. Subsequent methods, aliases, attributes,
- and classes will be documented in this section. A :section:
- comment block may have one or more lines before the :section:
- directive. These will be removed, and any identical lines at
- the end of the block are also removed. This allows you to add
- visual cues such as
-
- # ----------------------------------------
- # :section: My Section
- # This is the section that I wrote.
- # See it glisten in the noon-day sun.
- # ----------------------------------------
-
[<tt>call-seq:</tt>]
lines up to the next blank line in the comment are treated as
the method's calling sequence, overriding the
diff --git a/lib/rdoc/code_objects.rb b/lib/rdoc/code_objects.rb
index d6c4f1bdb9..bd713ab92b 100644
--- a/lib/rdoc/code_objects.rb
+++ b/lib/rdoc/code_objects.rb
@@ -23,9 +23,6 @@ module RDoc
attr_accessor :done_documenting
- # Which section are we in
-
- attr_accessor :section
# do we document ourselves?
@@ -114,51 +111,7 @@ module RDoc
class Context < CodeObject
attr_reader :name, :method_list, :attributes, :aliases, :constants
attr_reader :requires, :includes, :in_files, :visibility
-
- attr_reader :sections
-
- class Section
- attr_reader :title, :comment, :sequence
-
- @@sequence = "SEC00000"
-
- def initialize(title, comment)
- @title = title
- @@sequence.succ!
- @sequence = @@sequence.dup
- set_comment(comment)
- end
-
- private
-
- # Set the comment for this section from the original comment block
- # If the first line contains :section:, strip it and use the rest. Otherwise
- # remove lines up to the line containing :section:, and look for
- # those lines again at the end and remove them. This lets us write
- #
- # # ---------------------
- # # :SECTION: The title
- # # The body
- # # ---------------------
-
- def set_comment(comment)
- return unless comment
-
- if comment =~ /^.*?:section:.*$/
- start = $`
- rest = $'
- if start.empty?
- @comment = rest
- else
- @comment = rest.sub(/#{start.chomp}\Z/, '')
- end
- else
- @comment = comment
- end
- @comment = nil if @comment.empty?
- end
- end
-
+
def initialize
super()
@@ -170,9 +123,6 @@ module RDoc
@parent = nil
@visibility = :public
- @current_section = Section.new(nil, nil)
- @sections = [ @current_section ]
-
initialize_methods_etc
initialize_classes_and_modules
end
@@ -286,7 +236,6 @@ module RDoc
# collection[name] = cls if @document_self && !@done_documenting
collection[name] = cls if !@done_documenting
cls.parent = self
- cls.section = @current_section
end
cls
end
@@ -294,7 +243,6 @@ module RDoc
def add_to(array, thing)
array << thing if @document_self && !@done_documenting
thing.parent = self
- thing.section = @current_section
end
# If a class's documentation is turned off after we've started
@@ -426,13 +374,6 @@ module RDoc
find_module_named(symbol)
end
- # Handle sections
-
- def set_current_section(title, comment)
- @current_section = Section.new(title, comment)
- @sections << @current_section
- end
-
private
# Find a named method, or return nil
diff --git a/lib/rdoc/generators/html_generator.rb b/lib/rdoc/generators/html_generator.rb
index d263a14784..fbfc596cc3 100644
--- a/lib/rdoc/generators/html_generator.rb
+++ b/lib/rdoc/generators/html_generator.rb
@@ -314,7 +314,7 @@ module Generators
def collect_methods
list = @context.method_list
unless @options.show_all
- list = list.find_all {|m| m.visibility == :public || m.visibility == :protected || m.force_documentation }
+ list = list.find_all {|m| m.visibility == :public || m.force_documentation }
end
@methods = list.collect {|m| HtmlMethod.new(m, self, @options) }
end
@@ -336,10 +336,8 @@ module Generators
# Build a list of aliases for which we couldn't find a
# corresponding method
- def build_alias_summary_list(section)
- values = []
- @context.aliases.each do |al|
- next unless al.section == section
+ def build_alias_summary_list
+ @context.aliases.map do |al|
res = {
'old_name' => al.old_name,
'new_name' => al.new_name,
@@ -347,24 +345,20 @@ module Generators
if al.comment && !al.comment.empty?
res['desc'] = markup(al.comment, true)
end
- values << res
+ res
end
- values
end
# Build a list of constants
- def build_constants_summary_list(section)
- values = []
- @context.constants.each do |co|
- next unless co.section == section
+ def build_constants_summary_list
+ @context.constants.map do |co|
res = {
'name' => co.name,
'value' => CGI.escapeHTML(co.value)
}
res['desc'] = markup(co.comment, true) if co.comment && !co.comment.empty?
- values << res
+ res
end
- values
end
def build_requires_list(context)
@@ -422,7 +416,7 @@ module Generators
# methods, the other for instance methods. The inner arrays contain
# a hash for each method
- def build_method_detail_list(section)
+ def build_method_detail_list
outer = []
methods = @methods.sort
@@ -430,10 +424,7 @@ module Generators
for vis in [ :public, :protected, :private ]
res = []
methods.each do |m|
- if m.section == section and
- m.document_self and
- m.visibility == vis and
- m.singleton == singleton
+ if m.document_self and m.visibility == vis and m.singleton == singleton
row = {}
if m.call_seq
row["callseq"] = m.call_seq.gsub(/->/, '&rarr;')
@@ -487,12 +478,11 @@ module Generators
# Build the structured list of classes and modules contained
# in this context.
- def build_class_list(level, from, section, infile=nil)
+ def build_class_list(level, from, infile=nil)
res = ""
prefix = "&nbsp;&nbsp;::" * level;
from.modules.sort.each do |mod|
- next unless mod.section == section
next if infile && !mod.defined_in?(infile)
if mod.document_self
res <<
@@ -500,12 +490,11 @@ module Generators
"Module " <<
href(url(mod.viewer.path), "link", mod.full_name) <<
"<br />\n" <<
- build_class_list(level + 1, mod, section, infile)
+ build_class_list(level + 1, mod, infile)
end
end
from.classes.sort.each do |cls|
- next unless cls.section == section
next if infile && !cls.defined_in?(infile)
if cls.document_self
res <<
@@ -513,7 +502,7 @@ module Generators
"Class " <<
href(url(cls.viewer.path), "link", cls.full_name) <<
"<br />\n" <<
- build_class_list(level + 1, cls, section, infile)
+ build_class_list(level + 1, cls, infile)
end
end
@@ -552,24 +541,6 @@ module Generators
end
res
end
-
- # create table of contents if we contain sections
-
- def add_table_of_sections
- toc = []
- @context.sections.each do |section|
- if section.title
- toc << {
- 'secname' => section.title,
- 'href' => section.sequence
- }
- end
- end
-
- @values['toc'] = toc unless toc.empty?
- end
-
-
end
#####################################################################
@@ -633,7 +604,6 @@ module Generators
def value_hash
class_attribute_values
- add_table_of_sections
@values["charset"] = @options.charset
@values["style_url"] = style_url(path, @options.css)
@@ -644,50 +614,37 @@ module Generators
ml = build_method_summary_list
@values["methods"] = ml unless ml.empty?
- il = build_include_list(@context)
- @values["includes"] = il unless il.empty?
+ al = build_alias_summary_list
+ @values["aliases"] = al unless al.empty?
- @values["sections"] = @context.sections.map do |section|
+ co = build_constants_summary_list
+ @values["constants"] = co unless co.empty?
- secdata = {
- "sectitle" => section.title,
- "secsequence" => section.sequence,
- "seccomment" => markup(section.comment)
- }
-
- al = build_alias_summary_list(section)
- secdata["aliases"] = al unless al.empty?
-
- co = build_constants_summary_list(section)
- secdata["constants"] = co unless co.empty?
-
- al = build_attribute_list(section)
- secdata["attributes"] = al unless al.empty?
-
- cl = build_class_list(0, @context, section)
- secdata["classlist"] = cl unless cl.empty?
-
- mdl = build_method_detail_list(section)
- secdata["method_list"] = mdl unless mdl.empty?
+ il = build_include_list(@context)
+ @values["includes"] = il unless il.empty?
- secdata
- end
+ al = build_attribute_list
+ @values["attributes"] = al unless al.empty?
+
+ cl = build_class_list(0, @context)
+ @values["classlist"] = cl unless cl.empty?
+ mdl = build_method_detail_list
+ @values["method_list"] = mdl unless mdl.empty?
@values
end
- def build_attribute_list(section)
+ def build_attribute_list
atts = @context.attributes.sort
res = []
atts.each do |att|
- next unless att.section == section
- if att.visibility == :public || att.visibility == :protected || @options.show_all
+ if att.visibility == :public || @options.show_all
entry = {
"name" => CGI.escapeHTML(att.name),
"rw" => att.rw,
"a_desc" => markup(att.comment, true)
}
- unless att.visibility == :public || att.visibility == :protected
+ unless att.visibility == :public
entry["rw"] << "-"
end
res << entry
@@ -744,6 +701,7 @@ module Generators
end
@values['infiles'] = files
+
end
def <=>(other)
@@ -801,7 +759,6 @@ module Generators
def value_hash
file_attribute_values
- add_table_of_sections
@values["charset"] = @options.charset
@values["href"] = path
@@ -821,36 +778,23 @@ module Generators
rl = build_requires_list(@context)
@values["requires"] = rl unless rl.empty?
+ co = build_constants_summary_list
+ @values["constants"] = co unless co.empty?
+
+ al = build_alias_summary_list
+ @values["aliases"] = al unless al.empty?
+
if @options.promiscuous
file_context = nil
else
file_context = @context
end
+ cl = build_class_list(0, @context, file_context)
+ @values["classlist"] = cl unless cl.empty?
- @values["sections"] = @context.sections.map do |section|
-
- secdata = {
- "sectitle" => section.title,
- "secsequence" => section.sequence,
- "seccomment" => markup(section.comment)
- }
-
- cl = build_class_list(0, @context, section, file_context)
- @values["classlist"] = cl unless cl.empty?
-
- mdl = build_method_detail_list(section)
- secdata["method_list"] = mdl unless mdl.empty?
-
- al = build_alias_summary_list(section)
- secdata["aliases"] = al unless al.empty?
-
- co = build_constants_summary_list(section)
- @values["constants"] = co unless co.empty?
-
- secdata
- end
-
+ mdl = build_method_detail_list
+ @values["method_list"] = mdl unless mdl.empty?
@values
end
@@ -941,10 +885,6 @@ module Generators
@context.name
end
- def section
- @context.section
- end
-
def index_name
"#{@context.name} (#{@html_class.name})"
end
diff --git a/lib/rdoc/generators/ri_generator.rb b/lib/rdoc/generators/ri_generator.rb
index c4b4a7e17c..8d94579347 100644
--- a/lib/rdoc/generators/ri_generator.rb
+++ b/lib/rdoc/generators/ri_generator.rb
@@ -172,7 +172,7 @@ module Generators
list = cls.method_list
unless @options.show_all
list = list.find_all do |m|
- m.visibility == :public || m.visibility == :protected || m.force_documentation
+ m.visibility == :public || m.force_documentation
end
end
diff --git a/lib/rdoc/generators/template/html/html.rb b/lib/rdoc/generators/template/html/html.rb
index 6bbde46000..e0a8880004 100644
--- a/lib/rdoc/generators/template/html/html.rb
+++ b/lib/rdoc/generators/template/html/html.rb
@@ -20,22 +20,19 @@
#
module RDoc
- module Page
+ module Page
- FONTS = "Verdana,Arial,Helvetica,sans-serif"
+ FONTS = "Verdana,Arial,Helvetica,sans-serif"
STYLE = %{
body {
- font-family: Verdana,Arial,Helvetica,sans-serif;
- font-size: 90%;
margin: 0;
- margin-left: 40px;
padding: 0;
background: white;
}
h1,h2,h3,h4 { margin: 0; color: #efefef; background: transparent; }
-h1 { font-size: 150%; }
+h1 { font-size: 120%; }
h2,h3,h4 { margin-top: 1em; }
a { background: #eef; color: #039; text-decoration: none; }
@@ -43,75 +40,61 @@ a:hover { background: #039; color: #eef; }
/* Override the base stylesheet's Anchor inside a table cell */
td > a {
- background: transparent;
- color: #039;
- text-decoration: none;
-}
-
-/* and inside a section title */
-.section-title > a {
- background: transparent;
- color: #eee;
- text-decoration: none;
+ background: transparent;
+ color: #039;
+ text-decoration: none;
}
/* === Structural elements =================================== */
div#index {
margin: 0;
- margin-left: -40px;
padding: 0;
- font-size: 90%;
+ font-size: 0.9em;
}
-
div#index a {
margin-left: 0.7em;
}
-div#index .section-bar {
- margin-left: 0px;
- padding-left: 0.7em;
- background: #ccc;
- font-size: small;
-}
-
-
-div#classHeader, div#fileHeader {
+div#classHeader {
width: auto;
+ background: #039;
color: white;
padding: 0.5em 1.5em 0.5em 1.5em;
margin: 0;
- margin-left: -40px;
border-bottom: 3px solid #006;
}
-div#classHeader a, div#fileHeader a {
+div#classHeader a {
background: inherit;
color: white;
}
-div#classHeader td, div#fileHeader td {
+div#classHeader td {
background: inherit;
color: white;
}
-
div#fileHeader {
- background: #057;
+ width: auto;
+ background: #039;
+ color: white;
+ padding: 0.5em 1.5em 0.5em 1.5em;
+ margin: 0;
+ border-bottom: 3px solid #006;
}
-div#classHeader {
- background: #048;
+div#fileHeader a {
+ background: inherit;
+ color: white;
}
-
-.class-name-in-header {
- font-size: 180%;
- font-weight: bold;
+div#fileHeader td {
+ background: inherit;
+ color: white;
}
-
div#bodyContent {
padding: 0 1.5em 0 1.5em;
}
@@ -123,7 +106,7 @@ div#description {
}
div#description h1,h2,h3,h4,h5,h6 {
- color: #125;;
+ color: black;
background: transparent;
}
@@ -154,51 +137,35 @@ table.header-table {
color: #DEDEDE;
}
-.xxsection-bar {
+.section-bar {
background: #eee;
color: #333;
padding: 3px;
-}
-
-.section-bar {
- color: #333;
- border-bottom: 1px solid #999;
- margin-left: -20px;
-}
-
-
-.section-title {
- background: #79a;
- color: #eee;
- padding: 3px;
- margin-top: 2em;
- margin-left: -30px;
border: 1px solid #999;
}
-.top-aligned-row { vertical-align: top }
-.bottom-aligned-row { vertical-align: bottom }
+.top-aligned-row { vertical-align: vertical-align: top }
/* --- Context section classes ----------------------- */
.context-row { }
.context-item-name { font-family: monospace; font-weight: bold; color: black; }
-.context-item-value { font-size: small; color: #448; }
-.context-item-desc { color: #333; padding-left: 2em; }
+.context-item-value { font-size: x-small; color: #448; }
+.context-item-desc { background: #efefef; }
/* --- Method classes -------------------------- */
.method-detail {
- background: #efefef;
+ background: #EFEFEF;
padding: 0;
margin-top: 0.5em;
- margin-bottom: 1em;
- border: 1px dotted #ccc;
+ margin-bottom: 0.5em;
+ border: 1px dotted #DDD;
}
.method-heading {
- color: black;
- background: #ccc;
- border-bottom: 1px solid #666;
- padding: 0.2em 0.5em 0 0.5em;
+ color: black;
+ background: #AAA;
+ border-bottom: 1px solid #666;
+ padding: 0.2em 0.5em 0 0.5em;
}
.method-signature { color: black; background: inherit; }
.method-name { font-weight: bold; }
@@ -211,7 +178,7 @@ a.source-toggle { font-size: 90%; }
div.method-source-code {
background: #262626;
color: #ffdead;
- margin: 1em;
+ margin: 1em;
padding: 0.5em;
border: 1px dashed #999;
overflow: hidden;
@@ -223,20 +190,20 @@ div.method-source-code pre { color: #ffdead; overflow: hidden; }
.standalone-code { background: #221111; color: #ffdead; overflow: hidden; }
-.ruby-constant { color: #7fffd4; background: transparent; }
-.ruby-keyword { color: #00ffff; background: transparent; }
-.ruby-ivar { color: #eedd82; background: transparent; }
-.ruby-operator { color: #00ffee; background: transparent; }
+.ruby-constant { color: #7fffd4; background: transparent; }
+.ruby-keyword { color: #00ffff; background: transparent; }
+.ruby-ivar { color: #eedd82; background: transparent; }
+.ruby-operator { color: #00ffee; background: transparent; }
.ruby-identifier { color: #ffdead; background: transparent; }
-.ruby-node { color: #ffa07a; background: transparent; }
-.ruby-comment { color: #b22222; font-weight: bold; background: transparent; }
-.ruby-regexp { color: #ffa07a; background: transparent; }
-.ruby-value { color: #7fffd4; background: transparent; }
+.ruby-node { color: #ffa07a; background: transparent; }
+.ruby-comment { color: #b22222; font-weight: bold; background: transparent; }
+.ruby-regexp { color: #ffa07a; background: transparent; }
+.ruby-value { color: #7fffd4; background: transparent; }
}
#####################################################################
-### H E A D E R T E M P L A T E
+### H E A D E R T E M P L A T E
#####################################################################
XHTML_PREAMBLE = %{<?xml version="1.0" encoding="%charset%"?>
@@ -248,41 +215,41 @@ XHTML_PREAMBLE = %{<?xml version="1.0" encoding="%charset%"?>
HEADER = XHTML_PREAMBLE + %{
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
- <title>%title%</title>
- <meta http-equiv="Content-Type" content="text/html; charset=%charset%" />
- <meta http-equiv="Content-Script-Type" content="text/javascript" />
- <link rel="stylesheet" href="%style_url%" type="text/css" media="screen" />
- <script type="text/javascript">
- // <![CDATA[
-
- function popupCode( url ) {
- window.open(url, "Code", "resizable=yes,scrollbars=yes,toolbar=no,status=no,height=150,width=400")
- }
-
- function toggleCode( id ) {
- if ( document.getElementById )
- elem = document.getElementById( id );
- else if ( document.all )
- elem = eval( "document.all." + id );
- else
- return false;
-
- elemStyle = elem.style;
-
- if ( elemStyle.display != "block" ) {
- elemStyle.display = "block"
- } else {
- elemStyle.display = "none"
- }
-
- return true;
- }
-
- // Make codeblocks hidden by default
- document.writeln( "<style type=\\"text/css\\">div.method-source-code { display: none }</style>" )
-
- // ]]>
- </script>
+ <title>%title%</title>
+ <meta http-equiv="Content-Type" content="text/html; charset=%charset%" />
+ <meta http-equiv="Content-Script-Type" content="text/javascript" />
+ <link rel="stylesheet" href="%style_url%" type="text/css" media="screen" />
+ <script type="text/javascript">
+ // <![CDATA[
+
+ function popupCode( url ) {
+ window.open(url, "Code", "resizable=yes,scrollbars=yes,toolbar=no,status=no,height=150,width=400")
+ }
+
+ function toggleCode( id ) {
+ if ( document.getElementById )
+ elem = document.getElementById( id );
+ else if ( document.all )
+ elem = eval( "document.all." + id );
+ else
+ return false;
+
+ elemStyle = elem.style;
+
+ if ( elemStyle.display != "block" ) {
+ elemStyle.display = "block"
+ } else {
+ elemStyle.display = "none"
+ }
+
+ return true;
+ }
+
+ // Make codeblocks hidden by default
+ document.writeln( "<style type=\\"text/css\\">div.method-source-code { display: none }</style>" )
+
+ // ]]>
+ </script>
</head>
<body>
@@ -290,15 +257,129 @@ HEADER = XHTML_PREAMBLE + %{
#####################################################################
-### C O N T E X T C O N T E N T T E M P L A T E
+### C O N T E X T C O N T E N T T E M P L A T E
#####################################################################
CONTEXT_CONTENT = %{
+ <div id="contextContent">
+IF:diagram
+ <div id="diagram">
+ %diagram%
+ </div>
+ENDIF:diagram
+
+IF:description
+ <div id="description">
+ %description%
+ </div>
+ENDIF:description
+
+IF:requires
+ <div id="requires-list">
+ <h2 class="section-bar">Required files</h2>
+
+ <div class="name-list">
+START:requires
+ HREF:aref:name:&nbsp;&nbsp;
+END:requires
+ </div>
+ </div>
+ENDIF:requires
+
+IF:methods
+ <div id="method-list">
+ <h2 class="section-bar">Methods</h2>
+
+ <div class="name-list">
+START:methods
+ HREF:aref:name:&nbsp;&nbsp;
+END:methods
+ </div>
+ </div>
+ENDIF:methods
+
+IF:constants
+ <div id="constants-list">
+ <h2 class="section-bar">Constants</h2>
+
+ <div class="name-list">
+ <table summary="Constants">
+START:constants
+ <tr class="top-aligned-row context-row">
+ <td class="context-item-name">%name%</td>
+ <td>=</td>
+ <td class="context-item-value">%value%</td>
+ </tr>
+IF:desc
+ <tr class="top-aligned-row context-row">
+ <td>&nbsp;</td>
+ <td colspan="2" class="context-item-desc">%desc%</td>
+ </tr>
+ENDIF:desc
+END:constants
+ </table>
+ </div>
+ </div>
+ENDIF:constants
+
+IF:aliases
+ <div id="aliases-list">
+ <h2 class="section-bar">External Aliases</h2>
+
+ <div class="name-list">
+ <table summary="aliases">
+START:aliases
+ <tr class="top-aligned-row context-row">
+ <td class="context-item-name">%old_name%</td>
+ <td>-></td>
+ <td class="context-item-value">%new_name%</td>
+ </tr>
+IF:desc
+ <tr class="top-aligned-row context-row">
+ <td>&nbsp;</td>
+ <td colspan="2" class="context-item-desc">%desc%</td>
+ </tr>
+ENDIF:desc
+END:aliases
+ </table>
+ </div>
+ </div>
+ENDIF:aliases
+
+
+IF:attributes
+ <div id="attribute-list">
+ <h2 class="section-bar">Attributes</h2>
+
+ <div class="name-list">
+ <table>
+START:attributes
+ <tr class="top-aligned-row context-row">
+ <td class="context-item-name">%name%</td>
+ <td class="context-item-value">&nbsp;[%rw%]&nbsp;</td>
+ <td class="context-item-desc">%a_desc%</td>
+ </tr>
+END:attributes
+ </table>
+ </div>
+ </div>
+ENDIF:attributes
+
+IF:classlist
+ <div id="class-list">
+ <h2 class="section-bar">Classes and Modules</h2>
+
+ %classlist%
+ </div>
+ENDIF:classlist
+
+ </div>
+
}
#####################################################################
-### F O O T E R T E M P L A T E
+### F O O T E R T E M P L A T E
#####################################################################
FOOTER = %{
<div id="validator-badges">
@@ -311,42 +392,39 @@ FOOTER = %{
#####################################################################
-### F I L E P A G E H E A D E R T E M P L A T E
+### F I L E P A G E H E A D E R T E M P L A T E
#####################################################################
FILE_PAGE = %{
- <div id="fileHeader">
- <h1>%short_name%</h1>
- <table class="header-table">
- <tr class="top-aligned-row">
- <td><strong>Path:</strong></td>
- <td>%full_path%
+ <div id="fileHeader">
+ <h1>%short_name%</h1>
+ <table class="header-table">
+ <tr class="top-aligned-row">
+ <td><strong>Path:</strong></td>
+ <td>%full_path%
IF:cvsurl
- &nbsp;(<a href="%cvsurl%">CVS</a>)
+ &nbsp;(<a href="%cvsurl%">CVS</a>)
ENDIF:cvsurl
- </td>
- </tr>
- <tr class="top-aligned-row">
- <td><strong>Last Update:</strong></td>
- <td>%dtm_modified%</td>
- </tr>
- </table>
- </div>
+ </td>
+ </tr>
+ <tr class="top-aligned-row">
+ <td><strong>Last Update:</strong></td>
+ <td>%dtm_modified%</td>
+ </tr>
+ </table>
+ </div>
}
#####################################################################
-### C L A S S P A G E H E A D E R T E M P L A T E
+### C L A S S P A G E H E A D E R T E M P L A T E
#####################################################################
CLASS_PAGE = %{
<div id="classHeader">
+ <h1>%full_name% <sup class="type-note">(%classmod%)</sup></h1>
<table class="header-table">
<tr class="top-aligned-row">
- <td><strong>%classmod%</strong></td>
- <td class="class-name-in-header">%full_name%</td>
- </tr>
- <tr class="top-aligned-row">
<td><strong>In:</strong></td>
<td>
START:infiles
@@ -358,9 +436,9 @@ IF:full_path_url
</a>
ENDIF:full_path_url
IF:cvsurl
- &nbsp;(<a href="%cvsurl%">CVS</a>)
+ &nbsp;(<a href="%cvsurl%">CVS</a>)
ENDIF:cvsurl
- <br />
+ <br />
END:infiles
</td>
</tr>
@@ -385,263 +463,121 @@ ENDIF:parent
#####################################################################
-### M E T H O D L I S T T E M P L A T E
+### M E T H O D L I S T T E M P L A T E
#####################################################################
METHOD_LIST = %{
- <div id="contextContent">
-IF:diagram
- <div id="diagram">
- %diagram%
- </div>
-ENDIF:diagram
-
-IF:description
- <div id="description">
- %description%
- </div>
-ENDIF:description
-
-IF:requires
- <div id="requires-list">
- <h3 class="section-bar">Required files</h3>
-
- <div class="name-list">
-START:requires
- HREF:aref:name:&nbsp;&nbsp;
-END:requires
- </div>
- </div>
-ENDIF:requires
-
-IF:toc
- <div id="contents-list">
- <h3 class="section-bar">Contents</h3>
- <ul>
-START:toc
- <li><a href="#%href%">%secname%</a></li>
-END:toc
- </ul>
-ENDIF:toc
- </div>
-
-IF:methods
- <div id="method-list">
- <h3 class="section-bar">Methods</h3>
-
- <div class="name-list">
-START:methods
- HREF:aref:name:&nbsp;&nbsp;
-END:methods
- </div>
- </div>
-ENDIF:methods
-
- </div>
-
-
- <!-- if includes -->
+ <!-- if includes -->
IF:includes
- <div id="includes">
- <h3 class="section-bar">Included Modules</h3>
+ <div id="includes">
+ <h2 class="section-bar">Included Modules</h2>
- <div id="includes-list">
+ <div id="includes-list">
START:includes
- <span class="include-name">HREF:aref:name:</span>
+ <span class="include-name">HREF:aref:name:</span>
END:includes
- </div>
- </div>
+ </div>
+ </div>
ENDIF:includes
-START:sections
- <div id="section">
-IF:sectitle
- <h2 class="section-title"><a name="%secsequence%">%sectitle%</a></h2>
-IF:seccomment
- <div class="section-comment">
- %seccomment%
- </div>
-ENDIF:seccomment
-ENDIF:sectitle
-
-IF:classlist
- <div id="class-list">
- <h3 class="section-bar">Classes and Modules</h3>
-
- %classlist%
- </div>
-ENDIF:classlist
-
-IF:constants
- <div id="constants-list">
- <h3 class="section-bar">Constants</h3>
-
- <div class="name-list">
- <table summary="Constants">
-START:constants
- <tr class="top-aligned-row context-row">
- <td class="context-item-name">%name%</td>
- <td>=</td>
- <td class="context-item-value">%value%</td>
-IF:desc
- <td width="3em">&nbsp;</td>
- <td class="context-item-desc">%desc%</td>
-ENDIF:desc
- </tr>
-END:constants
- </table>
- </div>
- </div>
-ENDIF:constants
-
-IF:aliases
- <div id="aliases-list">
- <h3 class="section-bar">External Aliases</h3>
-
- <div class="name-list">
- <table summary="aliases">
-START:aliases
- <tr class="top-aligned-row context-row">
- <td class="context-item-name">%old_name%</td>
- <td>-></td>
- <td class="context-item-value">%new_name%</td>
- </tr>
-IF:desc
- <tr class="top-aligned-row context-row">
- <td>&nbsp;</td>
- <td colspan="2" class="context-item-desc">%desc%</td>
- </tr>
-ENDIF:desc
-END:aliases
- </table>
- </div>
- </div>
-ENDIF:aliases
-
-
-IF:attributes
- <div id="attribute-list">
- <h3 class="section-bar">Attributes</h3>
-
- <div class="name-list">
- <table>
-START:attributes
- <tr class="top-aligned-row context-row">
- <td class="context-item-name">%name%</td>
-IF:rw
- <td class="context-item-value">&nbsp;[%rw%]&nbsp;</td>
-ENDIF:rw
-IFNOT:rw
- <td class="context-item-value">&nbsp;&nbsp;</td>
-ENDIF:rw
- <td class="context-item-desc">%a_desc%</td>
- </tr>
-END:attributes
- </table>
- </div>
- </div>
-ENDIF:attributes
-
-
- <!-- if method_list -->
+ <!-- if method_list -->
IF:method_list
- <div id="methods">
+ <div id="methods">
START:method_list
IF:methods
- <h3 class="section-bar">%type% %category% methods</h3>
+ <h2 class="section-bar">%type% %category% methods</h2>
START:methods
- <div id="method-%aref%" class="method-detail">
- <a name="%aref%"></a>
+ <div id="method-%aref%" class="method-detail">
+ <a name="%aref%"></a>
- <div class="method-heading">
+ <div class="method-heading">
IF:codeurl
- <a href="%codeurl%" target="Code" class="method-signature"
- onclick="popupCode('%codeurl%');return false;">
+ <a href="%codeurl%" target="Code" class="method-signature"
+ onclick="popupCode('%codeurl%');return false;">
ENDIF:codeurl
IF:sourcecode
- <a href="#%aref%" class="method-signature">
+ <a href="#%aref%" class="method-signature">
ENDIF:sourcecode
IF:callseq
- <span class="method-name">%callseq%</span>
+ <span class="method-name">%callseq%</span>
ENDIF:callseq
IFNOT:callseq
- <span class="method-name">%name%</span><span class="method-args">%params%</span>
+ <span class="method-name">%name%</span><span class="method-args">%params%</span>
ENDIF:callseq
IF:codeurl
- </a>
+ </a>
ENDIF:codeurl
IF:sourcecode
- </a>
+ </a>
ENDIF:sourcecode
- </div>
-
- <div class="method-description">
+ </div>
+
+ <div class="method-description">
IF:m_desc
- %m_desc%
+ %m_desc%
ENDIF:m_desc
IF:sourcecode
- <p><a class="source-toggle" href="#"
- onclick="toggleCode('%aref%-source');return false;">[Source]</a></p>
- <div class="method-source-code" id="%aref%-source">
+ <p><a class="source-toggle" href="#"
+ onclick="toggleCode('%aref%-source');return false;">[Source]</a></p>
+ <div class="method-source-code" id="%aref%-source">
<pre>
%sourcecode%
</pre>
- </div>
+ </div>
ENDIF:sourcecode
- </div>
- </div>
+ </div>
+ </div>
END:methods
ENDIF:methods
END:method_list
- </div>
+ </div>
ENDIF:method_list
-END:sections
}
#####################################################################
-### B O D Y T E M P L A T E
+### B O D Y T E M P L A T E
#####################################################################
BODY = HEADER + %{
!INCLUDE! <!-- banner header -->
- <div id="bodyContent">
+ <div id="bodyContent">
-} + METHOD_LIST + %{
+} + CONTEXT_CONTENT + METHOD_LIST + %{
- </div>
+ </div>
} + FOOTER
#####################################################################
-### S O U R C E C O D E T E M P L A T E
+### S O U R C E C O D E T E M P L A T E
#####################################################################
SRC_PAGE = XHTML_PREAMBLE + %{
<html>
<head>
- <title>%title%</title>
- <meta http-equiv="Content-Type" content="text/html; charset=%charset%" />
- <link rel="stylesheet" href="%style_url%" type="text/css" media="screen" />
+ <title>%title%</title>
+ <meta http-equiv="Content-Type" content="text/html; charset=%charset%" />
+ <link rel="stylesheet" href="%style_url%" type="text/css" media="screen" />
</head>
<body class="standalone-code">
- <pre>%code%</pre>
+ <pre>%code%</pre>
</body>
</html>
}
#####################################################################
-### I N D E X F I L E T E M P L A T E S
+### I N D E X F I L E T E M P L A T E S
#####################################################################
FR_INDEX_BODY = %{
@@ -656,19 +592,19 @@ FILE_INDEX = XHTML_PREAMBLE + %{
-->
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
- <title>%list_title%</title>
- <meta http-equiv="Content-Type" content="text/html; charset=%charset%" />
- <link rel="stylesheet" href="%style_url%" type="text/css" />
- <base target="docwin" />
+ <title>%list_title%</title>
+ <meta http-equiv="Content-Type" content="text/html; charset=%charset%" />
+ <link rel="stylesheet" href="%style_url%" type="text/css" />
+ <base target="docwin" />
</head>
<body>
<div id="index">
- <h1 class="section-bar">%list_title%</h1>
- <div id="index-entries">
+ <h1 class="section-bar">%list_title%</h1>
+ <div id="index-entries">
START:entries
- <a href="%href%">%name%</a><br />
+ <a href="%href%">%name%</a><br />
END:entries
- </div>
+ </div>
</div>
</body>
</html>
@@ -689,8 +625,8 @@ INDEX = %{<?xml version="1.0" encoding="%charset%"?>
-->
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
- <title>%title%</title>
- <meta http-equiv="Content-Type" content="text/html; charset=%charset%" />
+ <title>%title%</title>
+ <meta http-equiv="Content-Type" content="text/html; charset=%charset%" />
</head>
<frameset rows="20%, 80%">
<frameset cols="25%,35%,45%">
@@ -705,7 +641,7 @@ INDEX = %{<?xml version="1.0" encoding="%charset%"?>
- end # module Page
+ end # module Page
end # class RDoc
require 'rdoc/generators/template/html/one_page_html'
diff --git a/lib/rdoc/generators/template/html/kilmer.rb b/lib/rdoc/generators/template/html/kilmer.rb
index 9fbef3573a..0d47587f67 100644
--- a/lib/rdoc/generators/template/html/kilmer.rb
+++ b/lib/rdoc/generators/template/html/kilmer.rb
@@ -139,18 +139,6 @@ END:methods
</div>
ENDIF:methods
-
-START:sections
- <div id="section">
-IF:sectitle
- <h2 class="section-title"><a name="%secsequence%">%sectitle%</a></h2>
-IF:seccomment
- <div class="section-comment">
- %seccomment%
- </div>
-ENDIF:seccomment
-ENDIF:sectitle
-
IF:attributes
<table cellpadding=5 width="100%">
<tr><td class="tablesubtitle">Attributes</td></tr>
@@ -180,8 +168,6 @@ ENDIF:classlist
!INCLUDE! <!-- method descriptions -->
-END:sections
-
</body>
</html>
}
diff --git a/lib/rdoc/markup/simple_markup.rb b/lib/rdoc/markup/simple_markup.rb
index 8193ca02d4..21064cb009 100644
--- a/lib/rdoc/markup/simple_markup.rb
+++ b/lib/rdoc/markup/simple_markup.rb
@@ -194,7 +194,8 @@ module SM #:nodoc:
LABEL_LIST_RE = /^(
( \[.*?\] (?# labeled )
|\S.*:: (?# note )
- )(?:\s+|$)
+ )(?=\s|$)
+ \s*
)/x
diff --git a/lib/rdoc/markup/simple_markup/preprocess.rb b/lib/rdoc/markup/simple_markup/preprocess.rb
index bbbae1b77c..dbf4b216ca 100644
--- a/lib/rdoc/markup/simple_markup/preprocess.rb
+++ b/lib/rdoc/markup/simple_markup/preprocess.rb
@@ -19,11 +19,13 @@ module SM
def handle(text)
text.gsub!(/^([ \t#]*):(\w+):\s*(.+)?\n/) do
+
prefix = $1
directive = $2.downcase
param = $3
case directive
+
when "include"
filename = param.split[0]
include_file(filename, prefix)
diff --git a/lib/rdoc/markup/simple_markup/to_flow.rb b/lib/rdoc/markup/simple_markup/to_flow.rb
index 048e71abce..401703a72a 100644
--- a/lib/rdoc/markup/simple_markup/to_flow.rb
+++ b/lib/rdoc/markup/simple_markup/to_flow.rb
@@ -113,7 +113,7 @@ module SM
end
def accept_heading(am, fragment)
- @res << Flow::H.new(fragment.head_level, convert_flow(am.flow(fragment.txt)))
+ @res << Flow::H.new(fragment.head_level, am.flow(fragment.txt))
end
diff --git a/lib/rdoc/options.rb b/lib/rdoc/options.rb
index 53eee992e2..62c6dabff0 100644
--- a/lib/rdoc/options.rb
+++ b/lib/rdoc/options.rb
@@ -391,7 +391,7 @@ class Options
when "--line-numbers" then @include_line_numbers = true
when "--main" then @main_page = arg
when "--merge" then @merge = true
- when "--one-file" then @all_one_file = @inline_source = true
+ when "--one-file" then @all_one_file = true
when "--op" then @op_dir = arg
when "--opname" then @op_name = arg
when "--promiscuous" then @promiscuous = true
diff --git a/lib/rdoc/parsers/parse_c.rb b/lib/rdoc/parsers/parse_c.rb
index e6c18cb0ff..6c9134fc62 100644
--- a/lib/rdoc/parsers/parse_c.rb
+++ b/lib/rdoc/parsers/parse_c.rb
@@ -174,13 +174,12 @@ module RDoc
# prepare to parse a C file
def initialize(top_level, file_name, body, options, stats)
@known_classes = KNOWN_CLASSES.dup
- @body = handle_tab_width(handle_ifdefs_in(body))
+ @body = handle_ifdefs_in(body)
@options = options
@stats = stats
@top_level = top_level
@classes = Hash.new
@file_dir = File.dirname(file_name)
- @progress = $stderr unless options.quiet
end
# Extract the classes/modules and methods from a C file
@@ -188,7 +187,6 @@ module RDoc
def scan
remove_commented_out_lines
do_classes
- do_constants
do_methods
do_includes
do_aliases
@@ -199,19 +197,6 @@ module RDoc
private
#######
- def progress(char)
- unless @options.quiet
- @progress.print(char)
- @progress.flush
- end
- end
-
- def warn(msg)
- $stderr.puts
- $stderr.puts msg
- $stderr.flush
- end
-
# remove lines that are commented out that might otherwise get
# picked up when scanning for classes and methods
@@ -220,28 +205,19 @@ module RDoc
end
def handle_class_module(var_name, class_mod, class_name, parent, in_module)
- progress(class_mod[0, 1])
-
parent_name = @known_classes[parent] || parent
if in_module
enclosure = @classes[in_module]
unless enclosure
- if enclosure = @known_classes[in_module]
- handle_class_module(in_module, (/^rb_m/ =~ in_module ? "module" : "class"),
- enclosure, nil, nil)
- enclosure = @classes[in_module]
- end
- end
- unless enclosure
- warn("Enclosing class/module '#{in_module}' for " +
- "#{class_mod} #{class_name} not known")
+ $stderr.puts("Enclosing class/module '#{in_module}' for " +
+ "#{class_mod} #{class_name} not known")
return
end
else
enclosure = @top_level
end
-
+
if class_mod == "class"
cm = enclosure.add_class(NormalClass, class_name, parent_name)
@stats.num_classes += 1
@@ -264,7 +240,7 @@ module RDoc
if @body =~ %r{((?>/\*.*?\*/\s+))
(static\s+)?void\s+Init_#{class_name}\s*\(\)}xmi
comment = $1
- elsif @body =~ %r{Document-(class|module):\s#{class_name}\s*?\n((?>.*?\*/))}m
+ elsif @body =~ %r{Document-(class|module):\s#{class_name}.*?\n((?>.*?\*/))}m
comment = $2
end
class_meth.comment = mangle_comment(comment) if comment
@@ -273,13 +249,13 @@ module RDoc
############################################################
def do_classes
- @body.scan(/(\w+)\s* = \s*rb_define_module\s*\(\s*"(\w+)"\s*\)/mx) do
+ @body.scan(/(\w+)\s* = \s*rb_define_module\(\s*"(\w+)"\s*\)/mx) do
|var_name, class_name|
handle_class_module(var_name, "module", class_name, nil, nil)
end
# The '.' lets us handle SWIG-generated files
- @body.scan(/([\w\.]+)\s* = \s*rb_define_class\s*
+ @body.scan(/([\w\.]+)\s* = \s*rb_define_class
\(
\s*"(\w+)",
\s*(\w+)\s*
@@ -289,7 +265,7 @@ module RDoc
handle_class_module(var_name, "class", class_name, parent, nil)
end
- @body.scan(/(\w+)\s*=\s*boot_defclass\s*\(\s*"(\w+?)",\s*(\w+?)\s*\)/) do
+ @body.scan(/(\w+)\s*=\s*boot_defclass\(\s*"(\w+?)",\s*(\w+?)\)/) do
|var_name, class_name, parent|
parent = nil if parent == "0"
handle_class_module(var_name, "class", class_name, parent, nil)
@@ -305,40 +281,18 @@ module RDoc
handle_class_module(var_name, "module", class_name, nil, in_module)
end
- @body.scan(/([\w\.]+)\s* = \s*rb_define_class_under\s*
+ @body.scan(/([\w\.]+)\s* = \s*rb_define_class_under
\(
\s*(\w+),
\s*"(\w+)",
\s*(\w+)\s*
- \s*\)/mx) do
+ \)/mx) do
|var_name, in_module, class_name, parent|
handle_class_module(var_name, "class", class_name, parent, in_module)
end
end
-
- ###########################################################
-
- def do_constants
- @body.scan(%r{\Wrb_define_
- (
- variable |
- readonly_variable |
- const |
- global_const |
- )
- \s*\(
- (?:\s*(\w+),)?
- \s*"(\w+)",
- \s*(.*?)\s*\)\s*;
- }xm) do
-
- |type, var_name, const_name, definition|
- var_name = "rb_cObject" if !var_name or var_name == "rb_mKernel"
- handle_constants(type, var_name, const_name, definition)
- end
- end
############################################################
@@ -351,7 +305,7 @@ module RDoc
module_function |
private_method
)
- \s*\(\s*([\w\.]+),
+ \(\s*([\w\.]+),
\s*"([^"]+)",
\s*(?:RUBY_METHOD_FUNC\(|VALUEFUNC\()?(\w+)\)?,
\s*(-?\w+)\s*\)
@@ -371,21 +325,7 @@ module RDoc
meth_body, param_count, source_file)
end
- @body.scan(%r{rb_define_attr\(
- \s*([\w\.]+),
- \s*"([^"]+)",
- \s*(\d+),
- \s*(\d+)\s*\);
- }xm) do #"
- |var_name, attr_name, attr_reader, attr_writer|
-
- #var_name = "rb_cObject" if var_name == "rb_mKernel"
- handle_attr(var_name, attr_name,
- attr_reader.to_i != 0,
- attr_writer.to_i != 0)
- end
-
- @body.scan(%r{rb_define_global_function\s*\(
+ @body.scan(%r{rb_define_global_function\(
\s*"([^"]+)",
\s*(?:RUBY_METHOD_FUNC\(|VALUEFUNC\()?(\w+)\)?,
\s*(-?\w+)\s*\)
@@ -396,7 +336,7 @@ module RDoc
meth_body, param_count, source_file)
end
- @body.scan(/define_filetest_function\s*\(
+ @body.scan(/define_filetest_function\(
\s*"([^"]+)",
\s*(?:RUBY_METHOD_FUNC\(|VALUEFUNC\()?(\w+)\)?,
\s*(-?\w+)\s*\)/xm) do #"
@@ -410,7 +350,7 @@ module RDoc
############################################################
def do_aliases
- @body.scan(%r{rb_define_alias\s*\(\s*(\w+),\s*"([^"]+)",\s*"([^"]+)"\s*\)}m) do
+ @body.scan(%r{rb_define_alias\(\s*(\w+),\s*"([^"]+)",\s*"([^"]+)"\s*\)}m) do
|var_name, new_name, old_name|
@stats.num_methods += 1
class_name = @known_classes[var_name] || var_name
@@ -422,87 +362,8 @@ module RDoc
############################################################
- def handle_constants(type, var_name, const_name, definition)
- #@stats.num_constants += 1
- class_name = @known_classes[var_name]
-
- return unless class_name
-
- class_obj = find_class(var_name, class_name)
-
- unless class_obj
- warn("Enclosing class/module '#{const_name}' for not known")
- return
- end
-
- comment = find_const_comment(type, const_name)
-
- con = Constant.new(const_name, definition, mangle_comment(comment))
- class_obj.add_constant(con)
- end
-
- ###########################################################
-
- def find_const_comment(type, const_name)
- if @body =~ %r{((?>/\*.*?\*/\s+))
- rb_define_#{type}\((?:\s*(\w+),)?\s*"#{const_name}"\s*,.*?\)\s*;}xmi
- $1
- elsif @body =~ %r{Document-(?:const|global|variable):\s#{const_name}\s*?\n((?>.*?\*/))}m
- $1
- else
- ''
- end
- end
-
- ###########################################################
-
- def handle_attr(var_name, attr_name, reader, writer)
- rw = ''
- if reader
- #@stats.num_methods += 1
- rw << 'R'
- end
- if writer
- #@stats.num_methods += 1
- rw << 'W'
- end
-
- class_name = @known_classes[var_name]
-
- return unless class_name
-
- class_obj = find_class(var_name, class_name)
-
- if class_obj
- comment = find_attr_comment(attr_name)
- unless comment.empty?
- comment = mangle_comment(comment)
- end
- att = Attr.new('', attr_name, rw, comment)
- class_obj.add_attribute(att)
- end
-
- end
-
- ###########################################################
-
- def find_attr_comment(attr_name)
- if @body =~ %r{((?>/\*.*?\*/\s+))
- rb_define_attr\((?:\s*(\w+),)?\s*"#{attr_name}"\s*,.*?\)\s*;}xmi
- $1
- elsif @body =~ %r{Document-attr:\s#{attr_name}\s*?\n((?>.*?\*/))}m
- $1
- else
- ''
- end
- end
-
- ###########################################################
-
def handle_method(type, var_name, meth_name,
meth_body, param_count, source_file = nil)
- progress(".")
-
@stats.num_methods += 1
class_name = @known_classes[var_name]
@@ -531,25 +392,24 @@ module RDoc
end
if source_file
- file_name = File.join(@file_dir, source_file)
+ file_name = File.join(@file_dir, source_file)
body = (@@known_bodies[source_file] ||= File.read(file_name))
else
body = @body
end
- if find_body(meth_body, meth_obj, body) and meth_obj.document_self
- class_obj.add_method(meth_obj)
- end
+ find_body(meth_body, meth_obj, body)
+ class_obj.add_method(meth_obj)
end
end
############################################################
# Find the C code corresponding to a Ruby method
- def find_body(meth_name, meth_obj, body, quiet = false)
- case body
- when %r{((?>/\*.*?\*/\s*))(?:static\s+)?VALUE\s+#{meth_name}
- \s*(\(.*?\)).*?^}xm
- comment, params = $1, $2
+ def find_body(meth_name, meth_obj, body)
+ if body =~ %r{((?>/\*.*?\*/\s*))(static\s+)?VALUE\s+#{meth_name}
+ \s*(\(.*?\)).*?^}xm
+
+ comment, params = $1, $3
body_text = $&
# see if we can find the whole body
@@ -569,36 +429,25 @@ module RDoc
override_comment = find_override_comment(meth_obj.name)
comment = override_comment if override_comment
- find_modifiers(comment, meth_obj) if comment
+ find_call_seq(comment, meth_obj) if comment
# meth_obj.params = params
meth_obj.start_collecting_tokens
meth_obj.add_token(RubyToken::Token.new(1,1).set_text(body_text))
meth_obj.comment = mangle_comment(comment)
- when %r{((?>/\*.*?\*/\s*))^\s*\#\s*define\s+#{meth_name}\s+(\w+)}m
- comment = $1
- find_body($2, meth_obj, body, true)
- find_modifiers(comment, meth_obj)
- meth_obj.comment = mangle_comment(comment) + meth_obj.comment
- when %r{^\s*\#\s*define\s+#{meth_name}\s+(\w+)}m
- unless find_body($1, meth_obj, body, true)
- warn "No definition for #{meth_name}" unless quiet
- return false
- end
+
else
# No body, but might still have an override comment
comment = find_override_comment(meth_obj.name)
if comment
- find_modifiers(comment, meth_obj)
+ find_call_seq(comment, meth_obj)
meth_obj.comment = mangle_comment(comment)
else
- warn "No definition for #{meth_name}" unless quiet
- return false
+ $stderr.puts "No definition for #{meth_name}"
end
end
- true
end
@@ -609,13 +458,8 @@ module RDoc
# Array.new
# Array.new(10)
# use it for the parameters
- def find_modifiers(comment, meth_obj)
- if comment.sub!(/:nodoc:\s*^\s*\*?\s*$/m, '') or
- comment.sub!(/\A\/\*\s*:nodoc:\s*\*\/\Z/, '')
- meth_obj.document_self = false
- end
- if comment.sub!(/call-seq:(.*?)^\s*\*?\s*$/m, '') or
- comment.sub!(/\A\/\*\s*call-seq:(.*?)\*\/\Z/, '')
+ def find_call_seq(comment, meth_obj)
+ if comment.sub!(/call-seq:(.*?)^\s*\*?\s*$/m, '')
seq = $1
seq.gsub!(/^\s*\*\s*/, '')
meth_obj.call_seq = seq
@@ -625,10 +469,12 @@ module RDoc
############################################################
def find_override_comment(meth_name)
+ comment = nil
name = Regexp.escape(meth_name)
- if @body =~ %r{Document-method:\s#{name}\s*?\n((?>.*?\*/))}m
- $1
+ if @body =~ %r{Document-method:\s#{name}.*?\n((?>.*?\*/))}m
+ comment = $1
end
+ comment
end
############################################################
@@ -636,9 +482,9 @@ module RDoc
# Look for includes of the form
# rb_include_module(rb_cArray, rb_mEnumerable);
def do_includes
- @body.scan(/rb_include_module\s*\(\s*(\w+?),\s*(\w+?)\s*\)/) do |c,m|
+ @body.scan(/rb_include_module\(\s*(\w+?),\s*(\w+?)\s*\)/) do |c,m|
if cls = @classes[c]
- m = @known_classes[m] || m
+ m = KNOWN_CLASSES[m] || m
cls.add_include(Include.new(m, ""))
end
end
@@ -666,18 +512,6 @@ module RDoc
@classes[raw_name]
end
- def handle_tab_width(body)
- if /\t/ =~ body
- tab_width = Options.instance.tab_width
- body.split(/\n/).map do |line|
- 1 while line.gsub!(/\t+/) { ' ' * (tab_width*$&.length - $`.length % tab_width)} && $~ #`
- line
- end .join("\n")
- else
- body
- end
- end
-
# Remove #ifdefs that would otherwise confuse us
def handle_ifdefs_in(body)
diff --git a/lib/rdoc/parsers/parse_rb.rb b/lib/rdoc/parsers/parse_rb.rb
index fd95b2b7c8..5a98258f7e 100644
--- a/lib/rdoc/parsers/parse_rb.rb
+++ b/lib/rdoc/parsers/parse_rb.rb
@@ -1580,6 +1580,23 @@ module RDoc
non_comment_seen = true unless tk.kind_of?(TkCOMMENT)
+# $stderr.puts "===== #{tk.inspect}"
+# blank_line_seen = true
+# while tk.kind_of?(TkNL)
+# skip_tkspace(false)
+# if peek_tk.kind_of?(TkCOMMENT)
+# if blank_line_seen
+# comment = ''
+# blank_line_seen = false
+# end
+# tk = get_tk
+# comment << tk.text << "\n"
+# else
+# blank_line_seen = true
+# end
+# tk = get_tk
+# end
+
case tk
when TkNL
@@ -1730,7 +1747,7 @@ module RDoc
when TkCONSTANT
name = name_t.name
superclass = "Object"
-
+
if peek_tk.kind_of?(TkLT)
get_tk
skip_tkspace(true)
@@ -1809,7 +1826,6 @@ module RDoc
get_tk
name_t = get_tk
end
- skip_tkspace(false)
return [container, name_t]
end
@@ -1883,7 +1899,6 @@ module RDoc
name_t = get_tk
back_tk = skip_tkspace
meth = nil
- added_container = false
dot = get_tk
if dot.kind_of?(TkDOT) or dot.kind_of?(TkCOLON2)
@@ -1898,21 +1913,8 @@ module RDoc
prev_container = container
container = container.find_module_named(name_t.name)
if !container
- added_container = true
- obj = name_t.name.split("::").inject(Object) do |state, item|
- state.const_get(item)
- end rescue nil
-
- type = obj.class == Class ? NormalClass : NormalModule
- if not [Class, Module].include?(obj.class)
- warn("Couldn't find #{name_t.name}. Assuming it's a module")
- end
-
- if type == NormalClass then
- container = prev_container.add_class(type, name_t.name, obj.superclass.name)
- else
- container = prev_container.add_module(type, name_t.name)
- end
+ warn("Couldn't find #{name_t.name}. Assuming it's a module")
+ container = prev_container.add_module(NormalModule, name_t.name)
end
else
# warn("Unexpected token '#{name_t2.inspect}'")
@@ -1954,9 +1956,7 @@ module RDoc
parse_method_parameters(meth)
if meth.document_self
- container.add_method(meth)
- elsif added_container
- container.document_self = false
+ container.add_method(meth)
end
# Having now read the method parameters and documentation modifiers, we
@@ -2325,10 +2325,6 @@ module RDoc
options.title = param
""
- when "section"
- context.set_current_section(param, comment)
- comment.replace("") # 1.8 doesn't support #clear
- break
else
warn "Unrecognized directive '#{directive}'"
break
@@ -2405,12 +2401,12 @@ module RDoc
case tk
when TkSTRING
name = tk.text
-# when TkCONSTANT, TkIDENTIFIER, TkIVAR, TkGVAR
-# name = tk.name
+ when TkCONSTANT, TkIDENTIFIER, TkIVAR, TkGVAR
+ name = tk.name
when TkDSTRING
warn "Skipping require of dynamic string: #{tk.text}"
- # else
- # warn "'require' used as variable"
+ else
+ warn "'require' used as variable"
end
if name
context.add_require(Require.new(name, comment))
@@ -2551,7 +2547,7 @@ module RDoc
break
when TkCOMMA
else
- warn("unexpected token: '#{tk2.inspect}'") if $DEBBUG
+ warn("unexpected token: '#{tk.inspect}'")
break
end
end
diff --git a/lib/rdoc/parsers/parse_simple.rb b/lib/rdoc/parsers/parse_simple.rb
index 3f1a546964..b01104574e 100644
--- a/lib/rdoc/parsers/parse_simple.rb
+++ b/lib/rdoc/parsers/parse_simple.rb
@@ -30,12 +30,8 @@ module RDoc
def scan
# @body.gsub(/^(\s\n)+/, '')
- @top_level.comment = remove_private_comments(@body)
+ @top_level.comment = @body
@top_level
end
-
- def remove_private_comments(comment)
- comment.gsub(/^--.*?^\+\+/m, '').sub(/^--.*/m, '')
- end
end
end
diff --git a/lib/rdoc/rdoc.rb b/lib/rdoc/rdoc.rb
index 18bf64c8c9..060e9ba826 100644
--- a/lib/rdoc/rdoc.rb
+++ b/lib/rdoc/rdoc.rb
@@ -2,7 +2,14 @@
#
-VERSION_STRING = %{RDoc V1.0.1 - 20041108}
+RDOC_VERSION = "1.0pr1"
+
+rcs = '$Date$ $Revision$'.
+ gsub(/\$/, '').
+ sub(/Date: /, ': ').
+ sub(/ Revision: (\S+)/) { "(#$1)" }
+
+VERSION_STRING = %{RDoc V} + RDOC_VERSION + rcs
require 'rdoc/parsers/parse_rb.rb'
@@ -144,20 +151,19 @@ module RDoc
# Given a list of files and directories, create a list
# of all the Ruby files they contain.
#
- # If +force_doc+ is true, we always add the given files.
+ # If +force_dic+ is true, we always add the given files.
# If false, only add files that we guarantee we can parse
# It is true when looking at files given on the command line,
# false when recursing through subdirectories.
#
# The effect of this is that if you want a file with a non-
# standard extension parsed, you must name it explicity.
- #
- def normalized_file_list(options, relative_files, force_doc = false, exclude_pattern=nil)
+ def normalized_file_list(options, relative_files, force_doc = false)
file_list = []
relative_files.each do |rel_file_name|
- next if exclude_pattern && exclude_pattern =~ rel_file_name
+ next if options.exclude && options.exclude =~ rel_file_name
case type = File.stat(rel_file_name).ftype
when "file"
file_list << rel_file_name.sub(/^\.\//, '') if force_doc || ParserFactory.can_parse(rel_file_name)
@@ -182,7 +188,7 @@ module RDoc
# we may well contain subdirectories which must
# be tested for .document files
def list_files_in_directory(dir, options)
- normalized_file_list(options, Dir.glob(File.join(dir, "*")), false, options.exclude)
+ normalized_file_list(options, Dir.glob(File.join(dir, "*")))
end
diff --git a/lib/rdoc/ri/ri_formatter.rb b/lib/rdoc/ri/ri_formatter.rb
index cf016d7d79..15c964618c 100644
--- a/lib/rdoc/ri/ri_formatter.rb
+++ b/lib/rdoc/ri/ri_formatter.rb
@@ -164,7 +164,7 @@ module RI
display_verbatim_flow_item(item, @indent)
when SM::Flow::H
- display_heading(conv_html(item.text), item.level, @indent)
+ display_heading(conv_html(item.text.join), item.level, @indent)
when SM::Flow::RULE
draw_line
@@ -186,7 +186,6 @@ module RI
######################################################################
def display_heading(text, level, indent)
- text = strip_attributes(text)
case level
when 1
ul = "=" * text.length
@@ -212,30 +211,13 @@ module RI
display_flow_item(f)
end
end
-
- def strip_attributes(txt)
- tokens = txt.split(%r{(</?(?:b|code|em|i|tt)>)})
- text = []
- attributes = 0
- tokens.each do |tok|
- case tok
- when %r{^</(\w+)>$}, %r{^<(\w+)>$}
- ;
- else
- text << tok
- end
- end
- text.join
- end
-
-
end
######################################################################
# Handle text with attributes. We're a base class: there are
# different presentation classes (one, for example, uses overstrikes
- # to handle bold and underlining, while another using ANSI escape
+ # to handle bold and underlinig, while another using ANSI escape
# sequences
class AttributeFormatter < TextFormatter
@@ -265,8 +247,6 @@ module RI
class AttributeString
- attr_reader :txt
-
def initialize
@txt = []
@optr = 0
@@ -365,7 +345,7 @@ module RI
##################################################
# This formatter generates overstrike-style formatting, which
- # works with pagers such as man and less.
+ # works with pages such as man and less.
class OverstrikeFormatter < AttributeFormatter
@@ -428,18 +408,16 @@ module RI
end
HEADINGS = {
- 1 => [ "\033[1;32m", "\033[m" ] ,
- 2 => ["\033[4;32m", "\033[m" ],
- 3 => ["\033[32m", "\033[m" ]
+ 1 => "\033[1;32m%s\033[m",
+ 2 => "\033[4;32m%s\033[m",
+ 3 => "\033[32m%s\033[m"
}
def display_heading(text, level, indent)
level = 3 if level > 3
- heading = HEADINGS[level]
print indent
- print heading[0]
- print strip_attributes(text)
- puts heading[1]
+ printf(HEADINGS[level], text)
+ puts
end
private
@@ -633,7 +611,6 @@ module RI
# Place heading level indicators inline with heading.
def display_heading(text, level, indent)
- text = strip_attributes(text)
case level
when 1
puts "= " + text.upcase
diff --git a/lib/rdoc/ri/ri_options.rb b/lib/rdoc/ri/ri_options.rb
index 5ee9a45588..f59cdeda1c 100644
--- a/lib/rdoc/ri/ri_options.rb
+++ b/lib/rdoc/ri/ri_options.rb
@@ -5,7 +5,8 @@ module RI
require 'rdoc/ri/ri_display'
- VERSION_STRING = "ri v1.0.1 - 20041108"
+ VERSION_STRING = "ri: beta1"
+ CVS_ID = "$Id$";
class Options
@@ -169,7 +170,8 @@ module RI
# Show the version and exit
def show_version
- puts VERSION_STRING
+ cvs_info = CVS_ID.split
+ puts "#{VERSION_STRING} (#{cvs_info[2]} #{cvs_info[3]})"
exit(0)
end
diff --git a/lib/rdoc/usage.rb b/lib/rdoc/usage.rb
index 08393c380b..da6593d89e 100644
--- a/lib/rdoc/usage.rb
+++ b/lib/rdoc/usage.rb
@@ -96,7 +96,7 @@ module RDoc
# Display usage
def RDoc.usage_no_exit(*args)
- main_program_file, = caller[-1].split(/:\d+/, 2)
+ main_program_file, = caller[-1].split(/:/, 2)
comment = File.open(main_program_file) do |file|
find_comment(file)
end
@@ -128,31 +128,24 @@ module RDoc
# Find the first comment in the file (that isn't a shebang line)
# If the file doesn't start with a comment, report the fact
- # and return empty string
+ # and return nil
- def RDoc.gets(file)
- if (line = file.gets) && (line =~ /^#!/) # shebang
- throw :exit, find_comment(file)
- else
- line
+ def RDoc.find_comment(file)
+ # skip leading blank lines and shebangs
+ while line = file.gets
+ break unless line =~ /^(#!|\s*$)/
end
- end
- def RDoc.find_comment(file)
- catch(:exit) do
- # skip leading blank lines
- 0 while (line = gets(file)) && (line =~ /^\s*$/)
-
- comment = []
- while line && line =~ /^\s*#/
- comment << line
- line = gets(file)
- end
+ comment = []
- 0 while line && (line = gets(file))
- return no_comment if comment.empty?
- return comment.join
+ while line && line =~ /^\s*#/
+ comment << line
+ line = file.gets
end
+
+ return no_comment if comment.empty?
+
+ comment.join
end
@@ -174,7 +167,7 @@ module RDoc
if copy_upto_level && item.level >= copy_upto_level
copy_upto_level = nil
else
- if item.text.downcase == name
+ if item.text[0].downcase == name
result << item
copy_upto_level = item.level
end
@@ -198,7 +191,7 @@ module RDoc
# Report the fact that no doc comment count be found
def RDoc.no_comment
$stderr.puts "No usage information available for this program"
- ""
+ nil
end
end
diff --git a/lib/resolv.rb b/lib/resolv.rb
index e55bb72654..069cf5c8f1 100644
--- a/lib/resolv.rb
+++ b/lib/resolv.rb
@@ -7,12 +7,12 @@ I.e. it can resolv many hostnames concurrently.
It is possible to lookup various resources of DNS using DNS module directly.
== example
- p Resolv.getaddress("www.ruby-lang.org")
- p Resolv.getname("210.251.121.214")
+ Resolv.getaddress("www.ruby-lang.org")
+ Resolv.getname("210.251.121.214")
Resolv::DNS.open {|dns|
- p dns.getresources("www.ruby-lang.org", Resolv::DNS::Resource::IN::A).collect {|r| r.address}
- p dns.getresources("ruby-lang.org", Resolv::DNS::Resource::IN::MX).collect {|r| [r.exchange.to_s, r.preference]}
+ dns.getresources("www.ruby-lang.org", Resolv::DNS::Resource::IN::A).collect {|r| r.address}
+ dns.getresources("ruby-lang.org", Resolv::DNS::Resource::IN::MX).collect {|r| [r.exchange.to_s, r.preference]}
}
== Resolv class
@@ -319,7 +319,6 @@ class Resolv
@initialized = true
end
}
- self
end
def getaddress(name)
@@ -398,7 +397,6 @@ class Resolv
@initialized = true
end
}
- self
end
def close
@@ -736,18 +734,9 @@ class Resolv
when 'nameserver'
nameserver += args
when 'domain'
- next if args.empty?
search = [args[0]]
when 'search'
- next if args.empty?
search = args
- when 'options'
- args.each {|arg|
- case arg
- when /\Andots:(\d+)\z/
- ndots = $1.to_i
- end
- }
end
}
}
@@ -823,7 +812,6 @@ class Resolv
@initialized = true
end
}
- self
end
def single?
@@ -879,8 +867,10 @@ class Resolv
rescue NXDomain
end
}
- rescue ResolvError
+ rescue OtherResolvError
+ raise ResolvError.new("DNS error: #{$!.message}")
end
+ raise ResolvError.new("DNS resolv error: #{name}")
end
class NXDomain < ResolvError
@@ -978,38 +968,15 @@ class Resolv
@absolute = absolute
end
- def inspect
- "#<#{self.class}: #{self.to_s}#{@absolute ? '.' : ''}>"
- end
-
def absolute?
return @absolute
end
def ==(other)
- return false unless Name === other
return @labels == other.to_a && @absolute == other.absolute?
end
alias eql? ==
- # tests subdomain-of relation.
- #
- # domain = Resolv::DNS::Name.create("y.z")
- # p Resolv::DNS::Name.create("w.x.y.z").subdomain_of?(domain) #=> true
- # p Resolv::DNS::Name.create("x.y.z").subdomain_of?(domain) #=> true
- # p Resolv::DNS::Name.create("y.z").subdomain_of?(domain) #=> false
- # p Resolv::DNS::Name.create("z").subdomain_of?(domain) #=> false
- # p Resolv::DNS::Name.create("x.y.z.").subdomain_of?(domain) #=> false
- # p Resolv::DNS::Name.create("w.z").subdomain_of?(domain) #=> false
- #
- def subdomain_of?(other)
- raise ArgumentError, "not a domain name: #{other.inspect}" unless Name === other
- return false if @absolute != other.absolute?
- other_len = other.length
- return false if @labels.length <= other_len
- return @labels[-other_len, other_len] == other.to_a
- end
-
def hash
return @labels.hash ^ @absolute.hash
end
@@ -1026,14 +993,6 @@ class Resolv
return @labels[i]
end
- # returns the domain name as a string.
- #
- # The domain name doesn't have a trailing dot even if the name object is
- # absolute.
- #
- # p Resolv::DNS::Name.create("x.y.z.").to_s #=> "x.y.z"
- # p Resolv::DNS::Name.create("x.y.z").to_s #=> "x.y.z"
- #
def to_s
return @labels.join('.')
end
@@ -1185,12 +1144,6 @@ class Resolv
@data << d
end
- def put_string_list(ds)
- ds.each {|d|
- self.put_string(d)
- }
- end
-
def put_name(d)
put_labels(d.to_a)
end
@@ -1303,14 +1256,6 @@ class Resolv
return d
end
- def get_string_list
- strings = []
- while @index < @limit
- strings << self.get_string
- end
- strings
- end
-
def get_name
return Name.new(self.get_labels)
end
@@ -1553,22 +1498,18 @@ class Resolv
class TXT < Resource
TypeValue = 16
- def initialize(first_string, *rest_strings)
- @strings = [first_string, *rest_strings]
- end
- attr_reader :strings
-
- def data
- @strings[0]
+ def initialize(data)
+ @data = data
end
+ attr_reader :data
def encode_rdata(msg)
- msg.put_string_list(@strings)
+ msg.put_string(@data)
end
def self.decode_rdata(msg)
- strings = msg.get_string_list
- return self.new(*strings)
+ data = msg.get_string
+ return self.new(data)
end
end
@@ -1649,64 +1590,6 @@ class Resolv
return self.new(IPv6.new(msg.get_bytes(16)))
end
end
-
- # SRV resource record defined in RFC 2782
- #
- # These records identify the hostname and port that a service is
- # available at.
- #
- # The format is:
- # _Service._Proto.Name TTL Class SRV Priority Weight Port Target
- #
- # The fields specific to SRV are defined in RFC 2782 as meaning:
- # - +priority+ The priority of this target host. A client MUST attempt
- # to contact the target host with the lowest-numbered priority it can
- # reach; target hosts with the same priority SHOULD be tried in an
- # order defined by the weight field. The range is 0-65535. Note that
- # it is not widely implemented and should be set to zero.
- #
- # - +weight+ A server selection mechanism. The weight field specifies
- # a relative weight for entries with the same priority. Larger weights
- # SHOULD be given a proportionately higher probability of being
- # selected. The range of this number is 0-65535. Domain administrators
- # SHOULD use Weight 0 when there isn't any server selection to do, to
- # make the RR easier to read for humans (less noisy). Note that it is
- # not widely implemented and should be set to zero.
- #
- # - +port+ The port on this target host of this service. The range is 0-
- # 65535.
- #
- # - +target+ The domain name of the target host. A target of "." means
- # that the service is decidedly not available at this domain.
- class SRV < Resource
- ClassHash[[TypeValue = 33, ClassValue = ClassValue]] = self
-
- # Create a SRV resource record.
- def initialize(priority, weight, port, target)
- @priority = priority.to_int
- @weight = weight.to_int
- @port = port.to_int
- @target = Name.create(target)
- end
-
- attr_reader :priority, :weight, :port, :target
-
- def encode_rdata(msg)
- msg.put_pack("n", @priority)
- msg.put_pack("n", @weight)
- msg.put_pack("n", @port)
- msg.put_name(@target)
- end
-
- def self.decode_rdata(msg)
- priority, = msg.get_unpack("n")
- weight, = msg.get_unpack("n")
- port, = msg.get_unpack("n")
- target = msg.get_name
- return self.new(priority, weight, port, target)
- end
- end
-
end
end
end
diff --git a/lib/rexml/attribute.rb b/lib/rexml/attribute.rb
index a169148f32..a5a58055b8 100644
--- a/lib/rexml/attribute.rb
+++ b/lib/rexml/attribute.rb
@@ -101,20 +101,20 @@ module REXML
end
@unnormalized = nil
- @normalized = Text::normalize( @value, doctype )
+ @value = @normalized = Text::normalize( @value, doctype )
end
# Returns the UNNORMALIZED value of this attribute. That is, entities
# have been expanded to their values
def value
- return @unnormalized if @unnormalized
+ @unnormalized if @unnormalized
doctype = nil
if @element
doc = @element.document
doctype = doc.doctype if doc
end
@normalized = nil
- @unnormalized = Text::unnormalize( @value, doctype )
+ @value = @unnormalized = Text::unnormalize( @value, doctype )
end
# Returns a copy of this attribute
diff --git a/lib/rexml/document.rb b/lib/rexml/document.rb
index 1a63501905..a7f056ad3f 100644
--- a/lib/rexml/document.rb
+++ b/lib/rexml/document.rb
@@ -93,9 +93,7 @@ module REXML
# @return the root Element of the document, or nil if this document
# has no children.
def root
- elements[1]
- #self
- #@children.find { |item| item.kind_of? Element }
+ @children.find { |item| item.kind_of? Element }
end
# @return the DocType child of the document, if one exists,
diff --git a/lib/rexml/element.rb b/lib/rexml/element.rb
index e7754da2c5..b76c0179c7 100644
--- a/lib/rexml/element.rb
+++ b/lib/rexml/element.rb
@@ -6,14 +6,6 @@ require "rexml/xpath"
require "rexml/parseexception"
module REXML
- # An implementation note about namespaces:
- # As we parse, when we find namespaces we put them in a hash and assign
- # them a unique ID. We then convert the namespace prefix for the node
- # to the unique ID. This makes namespace lookup much faster for the
- # cost of extra memory use. We save the namespace prefix for the
- # context node and convert it back when we write it.
- @@namespaces = {}
-
# Represents a tagged XML element. Elements are characterized by
# having children, attributes, and names, and can themselves be
# children.
@@ -36,6 +28,8 @@ module REXML
# If an Element, the object will be shallowly cloned; name,
# attributes, and namespaces will be copied. Children will +not+ be
# copied.
+ # If a Source, the source will be scanned and parsed for an Element,
+ # and all child elements will be recursively parsed as well.
# parent::
# if supplied, must be a Parent, and will be used as
# the parent of this object.
@@ -97,35 +91,19 @@ module REXML
Element.new self
end
- # Evaluates to the root node of the document that this element
+ # Evaluates to the root element of the document that this element
# belongs to. If this element doesn't belong to a document, but does
# belong to another Element, the parent's root will be returned, until the
# earliest ancestor is found.
- #
- # Note that this is not the same as the document element.
- # In the following example, <a> is the document element, and the root
- # node is the parent node of the document element. You may ask yourself
- # why the root node is useful: consider the doctype and XML declaration,
- # and any processing instructions before the document element... they
- # are children of the root node, or siblings of the document element.
- # The only time this isn't true is when an Element is created that is
- # not part of any Document. In this case, the ancestor that has no
- # parent acts as the root node.
# d = Document.new '<a><b><c/></b></a>'
# a = d[1] ; c = a[1][1]
- # d.root_node == d # TRUE
- # a.root_node # namely, d
- # c.root_node # again, d
- def root_node
- parent.nil? ? self : parent.root_node
+ # d.root # These all evaluate to the same Element,
+ # a.root # namely, <a>
+ # c.root #
+ def root
+ parent.nil? ? self : parent.root
end
- def root
- return elements[1] if self.kind_of? Document
- return self if parent.kind_of? Document or parent.nil?
- return parent.root
- end
-
# Evaluates to the document to which this element belongs, or nil if this
# element doesn't belong to a document.
def document
@@ -292,8 +270,7 @@ module REXML
# el = doc.add_element 'my-tag', {'attr1'=>'val1', 'attr2'=>'val2'}
# el = Element.new 'my-tag'
# doc.add_element el
- def add_element element, attrs=nil
- raise "First argument must be either an element name, or an Element object" if element.nil?
+ def add_element element=nil, attrs=nil
el = @elements.add(element)
if attrs.kind_of? Hash
attrs.each do |key, value|
diff --git a/lib/rexml/encoding.rb b/lib/rexml/encoding.rb
index 739002dc4a..92ae1e8c21 100644
--- a/lib/rexml/encoding.rb
+++ b/lib/rexml/encoding.rb
@@ -1,16 +1,6 @@
-# -*- mode: ruby; ruby-indent-level: 2; indent-tabs-mode: t; tab-width: 2 -*- vim: sw=2 ts=2
module REXML
module Encoding
- @encoding_methods = {}
- def self.register(enc, &block)
- @encoding_methods[enc] = block
- end
- def self.apply(obj, enc)
- @encoding_methods[enc][obj]
- end
- def self.encoding_method(enc)
- @encoding_methods[enc]
- end
+ @@uconv_available = false
# Native, default format is UTF-8, so it is declared here rather than in
# an encodings/ definition.
@@ -28,24 +18,26 @@ module REXML
if enc and enc != UTF_8
@encoding = enc.upcase
begin
- require 'rexml/encodings/ICONV.rb'
- Encoding.apply(self, "ICONV")
+ load 'rexml/encodings/ICONV.rb'
+ instance_eval @@__REXML_encoding_methods
+ Iconv::iconv( UTF_8, @encoding, "" )
rescue LoadError, Exception => err
- raise ArgumentError, "Bad encoding name #@encoding" unless @encoding =~ /^[\w-]+$/
+ raise "Bad encoding name #@encoding" unless @encoding =~ /^[\w-]+$/
@encoding.untaint
enc_file = File.join( "rexml", "encodings", "#@encoding.rb" )
begin
- require enc_file
- Encoding.apply(self, @encoding)
+ load enc_file
+ instance_eval @@__REXML_encoding_methods
rescue LoadError
- puts $!.message
- raise ArgumentError, "No decoder found for encoding #@encoding. Please install iconv."
+ puts $!.message
+ raise Exception.new( "No decoder found for encoding #@encoding. Please install iconv." )
end
end
else
- @encoding = UTF_8
- require 'rexml/encodings/UTF-8.rb'
- Encoding.apply(self, @encoding)
+ enc = UTF_8
+ @encoding = enc.upcase
+ load 'rexml/encodings/UTF-8.rb'
+ instance_eval @@__REXML_encoding_methods
end
ensure
$VERBOSE = old_verbosity
diff --git a/lib/rexml/encodings/EUC-JP.rb b/lib/rexml/encodings/EUC-JP.rb
index 684df0bbd6..a1314d0856 100644
--- a/lib/rexml/encodings/EUC-JP.rb
+++ b/lib/rexml/encodings/EUC-JP.rb
@@ -1,20 +1,37 @@
-require 'uconv'
+begin
+ require 'iconv'
-module REXML
- module Encoding
- def decode_eucjp(str)
- Uconv::euctou8(str)
- end
+ module REXML
+ module Encoding
+ @@__REXML_encoding_methods =<<-EOL
+ def decode(str)
+ return Iconv::iconv("utf-8", "euc-jp", str)[0]
+ end
- def encode_eucjp content
- Uconv::u8toeuc(content)
+ def encode content
+ return Iconv::iconv("euc-jp", "utf-8", content)[0]
+ end
+ EOL
end
+ end
+rescue LoadError
+ begin
+ require 'uconv'
+
+ module REXML
+ module Encoding
+ @@__REXML_encoding_methods =<<-EOL
+ def decode(str)
+ return Uconv::euctou8(str)
+ end
- register("EUC-JP") do |obj|
- class << obj
- alias decode decode_eucjp
- alias encode encode_eucjp
+ def encode content
+ return Uconv::u8toeuc(content)
+ end
+ EOL
end
end
+ rescue LoadError
+ raise "uconv or iconv is required for Japanese encoding support."
end
end
diff --git a/lib/rexml/encodings/ICONV.rb b/lib/rexml/encodings/ICONV.rb
index 172fba7cd1..384758d7b2 100644
--- a/lib/rexml/encodings/ICONV.rb
+++ b/lib/rexml/encodings/ICONV.rb
@@ -3,20 +3,14 @@ raise LoadError unless defined? Iconv
module REXML
module Encoding
- def decode_iconv(str)
- Iconv.conv(UTF_8, @encoding, str)
+ @@__REXML_encoding_methods =<<-EOL
+ def decode( str )
+ return Iconv::iconv("utf-8", @encoding, str)[0]
end
- def encode_iconv(content)
- Iconv.conv(@encoding, UTF_8, content)
- end
-
- register("ICONV") do |obj|
- Iconv.conv(UTF_8, obj.encoding, nil)
- class << obj
- alias decode decode_iconv
- alias encode encode_iconv
- end
+ def encode( content )
+ return Iconv::iconv(@encoding, "utf-8", content)[0]
end
+ EOL
end
end
diff --git a/lib/rexml/encodings/ISO-8859-1.rb b/lib/rexml/encodings/ISO-8859-1.rb
index 2873d13bf0..f4e4527c2d 100644
--- a/lib/rexml/encodings/ISO-8859-1.rb
+++ b/lib/rexml/encodings/ISO-8859-1.rb
@@ -1,7 +1,25 @@
-require 'rexml/encodings/US-ASCII'
-
module REXML
module Encoding
- register("ISO-8859-1", &encoding_method("US-ASCII"))
+ @@__REXML_encoding_methods = %q~
+ # Convert from UTF-8
+ def encode content
+ array_utf8 = content.unpack('U*')
+ array_enc = []
+ array_utf8.each do |num|
+ if num <= 0xFF
+ array_enc << num
+ else
+ # Numeric entity (&#nnnn;); shard by Stefan Scholl
+ array_enc.concat "&\##{num};".unpack('C*')
+ end
+ end
+ array_enc.pack('C*')
+ end
+
+ # Convert to UTF-8
+ def decode(str)
+ str.unpack('C*').pack('U*')
+ end
+ ~
end
end
diff --git a/lib/rexml/encodings/SHIFT-JIS.rb b/lib/rexml/encodings/SHIFT-JIS.rb
index d055d0c761..e7dc6339ae 100644
--- a/lib/rexml/encodings/SHIFT-JIS.rb
+++ b/lib/rexml/encodings/SHIFT-JIS.rb
@@ -1,22 +1,37 @@
-require 'uconv'
+begin
+ require 'iconv'
-module REXML
- module Encoding
- def decode_sjis content
- Uconv::sjistou8(content)
- end
+ module REXML
+ module Encoding
+ @@__REXML_encoding_methods =<<-EOL
+ def decode(str)
+ return Iconv::iconv("utf-8", "shift-jis", str)[0]
+ end
- def encode_sjis(str)
- Uconv::u8tosjis(str)
+ def encode content
+ return Iconv::iconv("shift-jis", "utf-8", content)[0]
+ end
+ EOL
end
+ end
+rescue LoadError
+ begin
+ require 'uconv'
+
+ module REXML
+ module Encoding
+ @@__REXML_encoding_methods =<<-EOL
+ def to_shift_jis content
+ Uconv::u8tosjis(content)
+ end
- b = proc do |obj|
- class << obj
- alias decode decode_sjis
- alias encode encode_sjis
+ def from_shift_jis(str)
+ Uconv::sjistou8(str)
+ end
+ EOL
end
end
- register("SHIFT-JIS", &b)
- register("SHIFT_JIS", &b)
+ rescue LoadError
+ raise "uconv or iconv is required for Japanese encoding support."
end
end
diff --git a/lib/rexml/encodings/SHIFT_JIS.rb b/lib/rexml/encodings/SHIFT_JIS.rb
index 2fc0b28306..6e8f759373 100644
--- a/lib/rexml/encodings/SHIFT_JIS.rb
+++ b/lib/rexml/encodings/SHIFT_JIS.rb
@@ -1 +1 @@
-load 'rexml/encodings/SHIFT-JIS.rb'
+require 'rexml/encodings/Shift-JIS'
diff --git a/lib/rexml/encodings/UNILE.rb b/lib/rexml/encodings/UNILE.rb
index 0560a08361..95141093b5 100644
--- a/lib/rexml/encodings/UNILE.rb
+++ b/lib/rexml/encodings/UNILE.rb
@@ -1,6 +1,7 @@
module REXML
module Encoding
- def encode_unile content
+ @@__REXML_encoding_methods =<<-EOL
+ def encode content
array_utf8 = content.unpack("U*")
array_enc = []
array_utf8.each do |num|
@@ -15,7 +16,7 @@ module REXML
array_enc.pack('C*')
end
- def decode_unile(str)
+ def decode(str)
array_enc=str.unpack('C*')
array_utf8 = []
2.step(array_enc.size-1, 2){|i|
@@ -23,12 +24,6 @@ module REXML
}
array_utf8.pack('U*')
end
-
- register(UNILE) do |obj|
- class << obj
- alias decode decode_unile
- alias encode encode_unile
- end
- end
+ EOL
end
end
diff --git a/lib/rexml/encodings/US-ASCII.rb b/lib/rexml/encodings/US-ASCII.rb
index fb4c217074..fe8f6df303 100644
--- a/lib/rexml/encodings/US-ASCII.rb
+++ b/lib/rexml/encodings/US-ASCII.rb
@@ -1,7 +1,8 @@
module REXML
module Encoding
+ @@__REXML_encoding_methods = %q~
# Convert from UTF-8
- def encode_ascii content
+ def encode content
array_utf8 = content.unpack('U*')
array_enc = []
array_utf8.each do |num|
@@ -16,15 +17,9 @@ module REXML
end
# Convert to UTF-8
- def decode_ascii(str)
+ def decode(str)
str.unpack('C*').pack('U*')
end
-
- register("US-ASCII") do |obj|
- class << obj
- alias decode decode_ascii
- alias encode encode_ascii
- end
- end
+ ~
end
end
diff --git a/lib/rexml/encodings/UTF-16.rb b/lib/rexml/encodings/UTF-16.rb
index 972169755e..bd92fce18d 100644
--- a/lib/rexml/encodings/UTF-16.rb
+++ b/lib/rexml/encodings/UTF-16.rb
@@ -1,6 +1,7 @@
module REXML
module Encoding
- def encode_utf16 content
+ @@__REXML_encoding_methods =<<-EOL
+ def encode content
array_utf8 = content.unpack("U*")
array_enc = []
array_utf8.each do |num|
@@ -15,7 +16,7 @@ module REXML
array_enc.pack('C*')
end
- def decode_utf16(str)
+ def decode(str)
array_enc=str.unpack('C*')
array_utf8 = []
2.step(array_enc.size-1, 2){|i|
@@ -23,12 +24,6 @@ module REXML
}
array_utf8.pack('U*')
end
-
- register(UTF_16) do |obj|
- class << obj
- alias decode decode_utf16
- alias encode encode_utf16
- end
- end
+ EOL
end
end
diff --git a/lib/rexml/encodings/UTF-8.rb b/lib/rexml/encodings/UTF-8.rb
index bb08f44100..33a7e490c4 100644
--- a/lib/rexml/encodings/UTF-8.rb
+++ b/lib/rexml/encodings/UTF-8.rb
@@ -1,18 +1,13 @@
module REXML
module Encoding
- def encode_utf8 content
+ @@__REXML_encoding_methods =<<-EOL
+ def encode content
content
end
- def decode_utf8(str)
+ def decode(str)
str
end
-
- register(UTF_8) do |obj|
- class << obj
- alias decode decode_utf8
- alias encode encode_utf8
- end
- end
+ EOL
end
end
diff --git a/lib/rexml/functions.rb b/lib/rexml/functions.rb
index 0db9b98a53..9cbff99537 100644
--- a/lib/rexml/functions.rb
+++ b/lib/rexml/functions.rb
@@ -7,33 +7,41 @@ module REXML
# Therefore, in XML, "local-name()" is identical (and actually becomes)
# "local_name()"
module Functions
- @@context = nil
- @@namespace_context = {}
+ @@node = nil
+ @@index = nil
+ @@size = nil
@@variables = {}
+ @@namespace_context = {}
- def Functions::namespace_context=(x) ; @@namespace_context=x ; end
- def Functions::variables=(x) ; @@variables=x ; end
- def Functions::namespace_context ; @@namespace_context ; end
- def Functions::variables ; @@variables ; end
-
- def Functions::context=(value); @@context = value; end
+ def Functions::node=(value); @@node = value; end
+ def Functions::index=(value); @@index = value; end
+ def Functions::size=(value); @@size = value; end
+ def Functions::variables=(value); @@variables = value; end
+ def Functions::namespace_context=(value)
+ @@namespace_context = value
+ end
+ def Functions::node; @@node; end
+ def Functions::index; @@index; end
+ def Functions::size; @@size; end
+ def Functions::variables; @@variables; end
+ def Functions::namespace_context; @@namespace_context; end
def Functions::text( )
- if @@context[:node].node_type == :element
- return @@context[:node].find_all{|n| n.node_type == :text}.collect{|n| n.value}
- elsif @@context[:node].node_type == :text
- return @@context[:node].value
+ if @@node.node_type == :element
+ return @@node.text
+ elsif @@node.node_type == :text
+ return @@node.value
else
return false
end
end
def Functions::last( )
- @@context[:size]
+ @@size
end
def Functions::position( )
- @@context[:index]
+ @@index
end
def Functions::count( node_set )
@@ -65,7 +73,7 @@ module REXML
# Helper method.
def Functions::get_namespace( node_set = nil )
if node_set == nil
- yield @@context[:node] if defined? @@context[:node].namespace
+ yield @@node if defined? @@node.namespace
else
if node_set.namespace
yield node_set
@@ -206,7 +214,7 @@ module REXML
# UNTESTED
def Functions::normalize_space( string=nil )
- string = string(@@context[:node]) if string.nil?
+ string = string(@@node) if string.nil?
if string.kind_of? Array
string.collect{|x| string.to_s.strip.gsub(/\s+/um, ' ') if string}
else
@@ -283,7 +291,7 @@ module REXML
# UNTESTED
def Functions::lang( language )
lang = false
- node = @@context[:node]
+ node = @@node
attr = nil
until node.nil?
if node.node_type == :element
@@ -317,16 +325,15 @@ module REXML
# an object of a type other than the four basic types is converted to a
# number in a way that is dependent on that type
def Functions::number( object=nil )
- object = @@context[:node] unless object
- case object
- when true
+ object = @@node unless object
+ if object == true
Float(1)
- when false
+ elsif object == false
Float(0)
- when Array
+ elsif object.kind_of? Array
number(string( object ))
- when Numeric
- object.to_f
+ elsif object.kind_of? Float
+ object
else
str = string( object )
#puts "STRING OF #{object.inspect} = #{str}"
@@ -339,8 +346,6 @@ module REXML
end
def Functions::sum( nodes )
- nodes = [nodes] unless nodes.kind_of? Array
- nodes.inject(0) { |r,n| r += number(string(n)) }
end
def Functions::floor( number )
@@ -359,13 +364,9 @@ module REXML
end
end
- def Functions::processing_instruction( node )
- node.node_type == :processing_instruction
- end
-
def Functions::method_missing( id )
puts "METHOD MISSING #{id.id2name}"
- XPath.match( @@context[:node], id.id2name )
+ XPath.match( @@node, id.id2name )
end
end
end
diff --git a/lib/rexml/instruction.rb b/lib/rexml/instruction.rb
index f24f7786f7..0b770d4b3d 100644
--- a/lib/rexml/instruction.rb
+++ b/lib/rexml/instruction.rb
@@ -58,9 +58,5 @@ module REXML
def node_type
:processing_instruction
end
-
- def inspect
- "<?p-i #{target} ...?>"
- end
end
end
diff --git a/lib/rexml/node.rb b/lib/rexml/node.rb
index e5dec72a9d..5f414c03ef 100644
--- a/lib/rexml/node.rb
+++ b/lib/rexml/node.rb
@@ -36,31 +36,5 @@ module REXML
def parent?
false;
end
-
-
- # Visit all subnodes of +self+ recursively
- def each_recursive(&block) # :yields: node
- self.elements.each {|node|
- block.call(node)
- node.each_recursive(&block)
- }
- end
-
- # Find (and return) first subnode (recursively) for which the block
- # evaluates to true. Returns +nil+ if none was found.
- def find_first_recursive(&block) # :yields: node
- each_recursive {|node|
- return node if block.call(node)
- }
- return nil
- end
-
- # Returns the index that +self+ has in its parent's elements array, so that
- # the following equation holds true:
- #
- # node == node.parent.elements[node.index_in_parent]
- def index_in_parent
- parent.index(self)+1
- end
end
end
diff --git a/lib/rexml/parsers/baseparser.rb b/lib/rexml/parsers/baseparser.rb
index cb33a64908..e95cba8904 100644
--- a/lib/rexml/parsers/baseparser.rb
+++ b/lib/rexml/parsers/baseparser.rb
@@ -2,103 +2,103 @@ require 'rexml/parseexception'
require 'rexml/source'
module REXML
- module Parsers
- # = Using the Pull Parser
- # <em>This API is experimental, and subject to change.</em>
- # parser = PullParser.new( "<a>text<b att='val'/>txet</a>" )
- # while parser.has_next?
- # res = parser.next
- # puts res[1]['att'] if res.start_tag? and res[0] == 'b'
- # end
- # See the PullEvent class for information on the content of the results.
- # The data is identical to the arguments passed for the various events to
- # the StreamListener API.
- #
- # Notice that:
- # parser = PullParser.new( "<a>BAD DOCUMENT" )
- # while parser.has_next?
- # res = parser.next
- # raise res[1] if res.error?
- # end
- #
- # Nat Price gave me some good ideas for the API.
- class BaseParser
- NCNAME_STR= '[\w:][\-\w\d.]*'
- NAME_STR= "(?:#{NCNAME_STR}:)?#{NCNAME_STR}"
+ module Parsers
+ # = Using the Pull Parser
+ # <em>This API is experimental, and subject to change.</em>
+ # parser = PullParser.new( "<a>text<b att='val'/>txet</a>" )
+ # while parser.has_next?
+ # res = parser.next
+ # puts res[1]['att'] if res.start_tag? and res[0] == 'b'
+ # end
+ # See the PullEvent class for information on the content of the results.
+ # The data is identical to the arguments passed for the various events to
+ # the StreamListener API.
+ #
+ # Notice that:
+ # parser = PullParser.new( "<a>BAD DOCUMENT" )
+ # while parser.has_next?
+ # res = parser.next
+ # raise res[1] if res.error?
+ # end
+ #
+ # Nat Price gave me some good ideas for the API.
+ class BaseParser
+ NCNAME_STR= '[\w:][\-\w\d.]*'
+ NAME_STR= "(?:#{NCNAME_STR}:)?#{NCNAME_STR}"
- NAMECHAR = '[\-\w\d\.:]'
- NAME = "([\\w:]#{NAMECHAR}*)"
- NMTOKEN = "(?:#{NAMECHAR})+"
- NMTOKENS = "#{NMTOKEN}(\\s+#{NMTOKEN})*"
- REFERENCE = "(?:&#{NAME};|&#\\d+;|&#x[0-9a-fA-F]+;)"
- REFERENCE_RE = /#{REFERENCE}/
+ NAMECHAR = '[\-\w\d\.:]'
+ NAME = "([\\w:]#{NAMECHAR}*)"
+ NMTOKEN = "(?:#{NAMECHAR})+"
+ NMTOKENS = "#{NMTOKEN}(\\s+#{NMTOKEN})*"
+ REFERENCE = "(?:&#{NAME};|&#\\d+;|&#x[0-9a-fA-F]+;)"
+ REFERENCE_RE = /#{REFERENCE}/
- DOCTYPE_START = /\A\s*<!DOCTYPE\s/um
- DOCTYPE_PATTERN = /\s*<!DOCTYPE\s+(.*?)(\[|>)/um
- ATTRIBUTE_PATTERN = /\s*(#{NAME_STR})\s*=\s*(["'])(.*?)\2/um
- COMMENT_START = /\A<!--/u
- COMMENT_PATTERN = /<!--(.*?)-->/um
- CDATA_START = /\A<!\[CDATA\[/u
- CDATA_END = /^\s*\]\s*>/um
- CDATA_PATTERN = /<!\[CDATA\[(.*?)\]\]>/um
- XMLDECL_START = /\A<\?xml\s/u;
- XMLDECL_PATTERN = /<\?xml\s+(.*?)\?>*/um
- INSTRUCTION_START = /\A<\?/u
- INSTRUCTION_PATTERN = /<\?(.*?)(\s+.*?)?\?>/um
- TAG_MATCH = /^<((?>#{NAME_STR}))\s*((?>\s+#{NAME_STR}\s*=\s*(["']).*?\3)*)\s*(\/)?>/um
- CLOSE_MATCH = /^\s*<\/(#{NAME_STR})\s*>/um
+ DOCTYPE_START = /\A\s*<!DOCTYPE\s/um
+ DOCTYPE_PATTERN = /\s*<!DOCTYPE\s+(.*?)(\[|>)/um
+ ATTRIBUTE_PATTERN = /\s*(#{NAME_STR})\s*=\s*(["'])(.*?)\2/um
+ COMMENT_START = /\A<!--/u
+ COMMENT_PATTERN = /<!--(.*?)-->/um
+ CDATA_START = /\A<!\[CDATA\[/u
+ CDATA_END = /^\s*\]\s*>/um
+ CDATA_PATTERN = /<!\[CDATA\[(.*?)\]\]>/um
+ XMLDECL_START = /\A<\?xml\s/u;
+ XMLDECL_PATTERN = /<\?xml\s+(.*?)\?>*/um
+ INSTRUCTION_START = /\A<\?/u
+ INSTRUCTION_PATTERN = /<\?(.*?)(\s+.*?)?\?>/um
+ TAG_MATCH = /^<((?>#{NAME_STR}))\s*((?>\s+#{NAME_STR}\s*=\s*(["']).*?\3)*)\s*(\/)?>/um
+ CLOSE_MATCH = /^\s*<\/(#{NAME_STR})\s*>/um
- VERSION = /\bversion\s*=\s*["'](.*?)['"]/um
- ENCODING = /\bencoding=["'](.*?)['"]/um
- STANDALONE = /\bstandalone=["'](.*?)['"]/um
+ VERSION = /\bversion\s*=\s*["'](.*?)['"]/um
+ ENCODING = /\bencoding=["'](.*?)['"]/um
+ STANDALONE = /\bstandalone=["'](.*?)['"]/um
- ENTITY_START = /^\s*<!ENTITY/
- IDENTITY = /^([!\*\w\-]+)(\s+#{NCNAME_STR})?(\s+["'].*?['"])?(\s+['"].*?["'])?/u
- ELEMENTDECL_START = /^\s*<!ELEMENT/um
- ELEMENTDECL_PATTERN = /^\s*(<!ELEMENT.*?)>/um
- SYSTEMENTITY = /^\s*(%.*?;)\s*$/um
- ENUMERATION = "\\(\\s*#{NMTOKEN}(?:\\s*\\|\\s*#{NMTOKEN})*\\s*\\)"
- NOTATIONTYPE = "NOTATION\\s+\\(\\s*#{NAME}(?:\\s*\\|\\s*#{NAME})*\\s*\\)"
- ENUMERATEDTYPE = "(?:(?:#{NOTATIONTYPE})|(?:#{ENUMERATION}))"
- ATTTYPE = "(CDATA|ID|IDREF|IDREFS|ENTITY|ENTITIES|NMTOKEN|NMTOKENS|#{ENUMERATEDTYPE})"
- ATTVALUE = "(?:\"((?:[^<&\"]|#{REFERENCE})*)\")|(?:'((?:[^<&']|#{REFERENCE})*)')"
- DEFAULTDECL = "(#REQUIRED|#IMPLIED|(?:(#FIXED\\s+)?#{ATTVALUE}))"
- ATTDEF = "\\s+#{NAME}\\s+#{ATTTYPE}\\s+#{DEFAULTDECL}"
- ATTDEF_RE = /#{ATTDEF}/
- ATTLISTDECL_START = /^\s*<!ATTLIST/um
- ATTLISTDECL_PATTERN = /^\s*<!ATTLIST\s+#{NAME}(?:#{ATTDEF})*\s*>/um
- NOTATIONDECL_START = /^\s*<!NOTATION/um
- PUBLIC = /^\s*<!NOTATION\s+(\w[\-\w]*)\s+(PUBLIC)\s+((["']).*?\4)\s*>/um
- SYSTEM = /^\s*<!NOTATION\s+(\w[\-\w]*)\s+(SYSTEM)\s+((["']).*?\4)\s*>/um
+ ENTITY_START = /^\s*<!ENTITY/
+ IDENTITY = /^([!\*\w\-]+)(\s+#{NCNAME_STR})?(\s+["'].*?['"])?(\s+['"].*?["'])?/u
+ ELEMENTDECL_START = /^\s*<!ELEMENT/um
+ ELEMENTDECL_PATTERN = /^\s*(<!ELEMENT.*?)>/um
+ SYSTEMENTITY = /^\s*(%.*?;)\s*$/um
+ ENUMERATION = "\\(\\s*#{NMTOKEN}(?:\\s*\\|\\s*#{NMTOKEN})*\\s*\\)"
+ NOTATIONTYPE = "NOTATION\\s+\\(\\s*#{NAME}(?:\\s*\\|\\s*#{NAME})*\\s*\\)"
+ ENUMERATEDTYPE = "(?:(?:#{NOTATIONTYPE})|(?:#{ENUMERATION}))"
+ ATTTYPE = "(CDATA|ID|IDREF|IDREFS|ENTITY|ENTITIES|NMTOKEN|NMTOKENS|#{ENUMERATEDTYPE})"
+ ATTVALUE = "(?:\"((?:[^<&\"]|#{REFERENCE})*)\")|(?:'((?:[^<&']|#{REFERENCE})*)')"
+ DEFAULTDECL = "(#REQUIRED|#IMPLIED|(?:(#FIXED\\s+)?#{ATTVALUE}))"
+ ATTDEF = "\\s+#{NAME}\\s+#{ATTTYPE}\\s+#{DEFAULTDECL}"
+ ATTDEF_RE = /#{ATTDEF}/
+ ATTLISTDECL_START = /^\s*<!ATTLIST/um
+ ATTLISTDECL_PATTERN = /^\s*<!ATTLIST\s+#{NAME}(?:#{ATTDEF})*\s*>/um
+ NOTATIONDECL_START = /^\s*<!NOTATION/um
+ PUBLIC = /^\s*<!NOTATION\s+(\w[\-\w]*)\s+(PUBLIC)\s+((["']).*?\4)\s*>/um
+ SYSTEM = /^\s*<!NOTATION\s+(\w[\-\w]*)\s+(SYSTEM)\s+((["']).*?\4)\s*>/um
- TEXT_PATTERN = /\A([^<]*)/um
+ TEXT_PATTERN = /\A([^<]*)/um
- # Entity constants
- PUBIDCHAR = "\x20\x0D\x0Aa-zA-Z0-9\\-()+,./:=?;!*@$_%#"
- SYSTEMLITERAL = %Q{((?:"[^"]*")|(?:'[^']*'))}
- PUBIDLITERAL = %Q{("[#{PUBIDCHAR}']*"|'[#{PUBIDCHAR}]*')}
- EXTERNALID = "(?:(?:(SYSTEM)\\s+#{SYSTEMLITERAL})|(?:(PUBLIC)\\s+#{PUBIDLITERAL}\\s+#{SYSTEMLITERAL}))"
- NDATADECL = "\\s+NDATA\\s+#{NAME}"
- PEREFERENCE = "%#{NAME};"
- ENTITYVALUE = %Q{((?:"(?:[^%&"]|#{PEREFERENCE}|#{REFERENCE})*")|(?:'([^%&']|#{PEREFERENCE}|#{REFERENCE})*'))}
- PEDEF = "(?:#{ENTITYVALUE}|#{EXTERNALID})"
- ENTITYDEF = "(?:#{ENTITYVALUE}|(?:#{EXTERNALID}(#{NDATADECL})?))"
- PEDECL = "<!ENTITY\\s+(%)\\s+#{NAME}\\s+#{PEDEF}\\s*>"
- GEDECL = "<!ENTITY\\s+#{NAME}\\s+#{ENTITYDEF}\\s*>"
- ENTITYDECL = /\s*(?:#{GEDECL})|(?:#{PEDECL})/um
+ # Entity constants
+ PUBIDCHAR = "\x20\x0D\x0Aa-zA-Z0-9\\-()+,./:=?;!*@$_%#"
+ SYSTEMLITERAL = %Q{((?:"[^"]*")|(?:'[^']*'))}
+ PUBIDLITERAL = %Q{("[#{PUBIDCHAR}']*"|'[#{PUBIDCHAR}]*')}
+ EXTERNALID = "(?:(?:(SYSTEM)\\s+#{SYSTEMLITERAL})|(?:(PUBLIC)\\s+#{PUBIDLITERAL}\\s+#{SYSTEMLITERAL}))"
+ NDATADECL = "\\s+NDATA\\s+#{NAME}"
+ PEREFERENCE = "%#{NAME};"
+ ENTITYVALUE = %Q{((?:"(?:[^%&"]|#{PEREFERENCE}|#{REFERENCE})*")|(?:'([^%&']|#{PEREFERENCE}|#{REFERENCE})*'))}
+ PEDEF = "(?:#{ENTITYVALUE}|#{EXTERNALID})"
+ ENTITYDEF = "(?:#{ENTITYVALUE}|(?:#{EXTERNALID}(#{NDATADECL})?))"
+ PEDECL = "<!ENTITY\\s+(%)\\s+#{NAME}\\s+#{PEDEF}\\s*>"
+ GEDECL = "<!ENTITY\\s+#{NAME}\\s+#{ENTITYDEF}\\s*>"
+ ENTITYDECL = /\s*(?:#{GEDECL})|(?:#{PEDECL})/um
- EREFERENCE = /&(?!#{NAME};)/
+ EREFERENCE = /&(?!#{NAME};)/
- DEFAULT_ENTITIES = {
- 'gt' => [/&gt;/, '&gt;', '>', />/],
- 'lt' => [/&lt;/, '&lt;', '<', /</],
- 'quot' => [/&quot;/, '&quot;', '"', /"/],
- "apos" => [/&apos;/, "&apos;", "'", /'/]
- }
+ DEFAULT_ENTITIES = {
+ 'gt' => [/&gt;/, '&gt;', '>', />/],
+ 'lt' => [/&lt;/, '&lt;', '<', /</],
+ 'quot' => [/&quot;/, '&quot;', '"', /"/],
+ "apos" => [/&apos;/, "&apos;", "'", /'/]
+ }
- def initialize( source )
- self.stream = source
- end
+ def initialize( source )
+ self.stream = source
+ end
def add_listener( listener )
if !defined?(@listeners) or !@listeners
@@ -119,315 +119,315 @@ module REXML
attr_reader :source
- def stream=( source )
- if source.kind_of? String
- @source = Source.new(source)
- elsif source.kind_of? IO
- @source = IOSource.new(source)
- elsif source.kind_of? Source
- @source = source
- elsif defined? StringIO and source.kind_of? StringIO
- @source = IOSource.new(source)
- else
- raise "#{source.class} is not a valid input stream. It must be \n"+
- "either a String, IO, StringIO or Source."
- end
- @closed = nil
- @document_status = nil
- @tags = []
- @stack = []
- @entities = []
- end
+ def stream=( source )
+ if source.kind_of? String
+ @source = Source.new(source)
+ elsif source.kind_of? IO
+ @source = IOSource.new(source)
+ elsif source.kind_of? Source
+ @source = source
+ elsif defined? StringIO and source.kind_of? StringIO
+ @source = IOSource.new(source)
+ else
+ raise "#{source.class} is not a valid input stream. It must be \n"+
+ "either a String, IO, StringIO or Source."
+ end
+ @closed = nil
+ @document_status = nil
+ @tags = []
+ @stack = []
+ @entities = []
+ end
- # Returns true if there are no more events
- def empty?
+ # Returns true if there are no more events
+ def empty?
#puts "@source.empty? = #{@source.empty?}"
#puts "@stack.empty? = #{@stack.empty?}"
return (@source.empty? and @stack.empty?)
- end
+ end
- # Returns true if there are more events. Synonymous with !empty?
- def has_next?
+ # Returns true if there are more events. Synonymous with !empty?
+ def has_next?
return !(@source.empty? and @stack.empty?)
- end
+ end
- # Push an event back on the head of the stream. This method
- # has (theoretically) infinite depth.
- def unshift token
- @stack.unshift(token)
- end
+ # Push an event back on the head of the stream. This method
+ # has (theoretically) infinite depth.
+ def unshift token
+ @stack.unshift(token)
+ end
- # Peek at the +depth+ event in the stack. The first element on the stack
- # is at depth 0. If +depth+ is -1, will parse to the end of the input
- # stream and return the last event, which is always :end_document.
- # Be aware that this causes the stream to be parsed up to the +depth+
- # event, so you can effectively pre-parse the entire document (pull the
- # entire thing into memory) using this method.
- def peek depth=0
- raise %Q[Illegal argument "#{depth}"] if depth < -1
- temp = []
- if depth == -1
- temp.push(pull()) until empty?
- else
- while @stack.size+temp.size < depth+1
- temp.push(pull())
- end
- end
- @stack += temp if temp.size > 0
- @stack[depth]
- end
+ # Peek at the +depth+ event in the stack. The first element on the stack
+ # is at depth 0. If +depth+ is -1, will parse to the end of the input
+ # stream and return the last event, which is always :end_document.
+ # Be aware that this causes the stream to be parsed up to the +depth+
+ # event, so you can effectively pre-parse the entire document (pull the
+ # entire thing into memory) using this method.
+ def peek depth=0
+ raise %Q[Illegal argument "#{depth}"] if depth < -1
+ temp = []
+ if depth == -1
+ temp.push(pull()) until empty?
+ else
+ while @stack.size+temp.size < depth+1
+ temp.push(pull())
+ end
+ end
+ @stack += temp if temp.size > 0
+ @stack[depth]
+ end
- # Returns the next event. This is a +PullEvent+ object.
- def pull
- if @closed
- x, @closed = @closed, nil
- return [ :end_element, x ]
- end
- return [ :end_document ] if empty?
- return @stack.shift if @stack.size > 0
- @source.read if @source.buffer.size<2
- if @document_status == nil
- @source.consume( /^\s*/um )
- word = @source.match( /(<[^>]*)>/um )
- word = word[1] unless word.nil?
- case word
- when COMMENT_START
- return [ :comment, @source.match( COMMENT_PATTERN, true )[1] ]
- when XMLDECL_START
- results = @source.match( XMLDECL_PATTERN, true )[1]
- version = VERSION.match( results )
- version = version[1] unless version.nil?
- encoding = ENCODING.match(results)
- encoding = encoding[1] unless encoding.nil?
- @source.encoding = encoding
- standalone = STANDALONE.match(results)
- standalone = standalone[1] unless standalone.nil?
- return [ :xmldecl, version, encoding, standalone]
- when INSTRUCTION_START
- return [ :processing_instruction, *@source.match(INSTRUCTION_PATTERN, true)[1,2] ]
- when DOCTYPE_START
- md = @source.match( DOCTYPE_PATTERN, true )
- identity = md[1]
- close = md[2]
- identity =~ IDENTITY
- name = $1
- raise REXML::ParseException("DOCTYPE is missing a name") if name.nil?
- pub_sys = $2.nil? ? nil : $2.strip
- long_name = $3.nil? ? nil : $3.strip
- uri = $4.nil? ? nil : $4.strip
- args = [ :start_doctype, name, pub_sys, long_name, uri ]
- if close == ">"
- @document_status = :after_doctype
- @source.read if @source.buffer.size<2
- md = @source.match(/^\s*/um, true)
- @stack << [ :end_doctype ]
- else
- @document_status = :in_doctype
- end
- return args
- else
- @document_status = :after_doctype
- @source.read if @source.buffer.size<2
- md = @source.match(/\s*/um, true)
- end
- end
- if @document_status == :in_doctype
- md = @source.match(/\s*(.*?>)/um)
- case md[1]
- when SYSTEMENTITY
- match = @source.match( SYSTEMENTITY, true )[1]
- return [ :externalentity, match ]
+ # Returns the next event. This is a +PullEvent+ object.
+ def pull
+ if @closed
+ x, @closed = @closed, nil
+ return [ :end_element, x ]
+ end
+ return [ :end_document ] if empty?
+ return @stack.shift if @stack.size > 0
+ @source.read if @source.buffer.size<2
+ if @document_status == nil
+ @source.consume( /^\s*/um )
+ word = @source.match( /(<[^>]*)>/um )
+ word = word[1] unless word.nil?
+ case word
+ when COMMENT_START
+ return [ :comment, @source.match( COMMENT_PATTERN, true )[1] ]
+ when XMLDECL_START
+ results = @source.match( XMLDECL_PATTERN, true )[1]
+ version = VERSION.match( results )
+ version = version[1] unless version.nil?
+ encoding = ENCODING.match(results)
+ encoding = encoding[1] unless encoding.nil?
+ @source.encoding = encoding
+ standalone = STANDALONE.match(results)
+ standalone = standalone[1] unless standalone.nil?
+ return [ :xmldecl, version, encoding, standalone]
+ when INSTRUCTION_START
+ return [ :processing_instruction, *@source.match(INSTRUCTION_PATTERN, true)[1,2] ]
+ when DOCTYPE_START
+ md = @source.match( DOCTYPE_PATTERN, true )
+ identity = md[1]
+ close = md[2]
+ identity =~ IDENTITY
+ name = $1
+ raise REXML::ParseException("DOCTYPE is missing a name") if name.nil?
+ pub_sys = $2.nil? ? nil : $2.strip
+ long_name = $3.nil? ? nil : $3.strip
+ uri = $4.nil? ? nil : $4.strip
+ args = [ :start_doctype, name, pub_sys, long_name, uri ]
+ if close == ">"
+ @document_status = :after_doctype
+ @source.read if @source.buffer.size<2
+ md = @source.match(/^\s*/um, true)
+ @stack << [ :end_doctype ]
+ else
+ @document_status = :in_doctype
+ end
+ return args
+ else
+ @document_status = :after_doctype
+ @source.read if @source.buffer.size<2
+ md = @source.match(/\s*/um, true)
+ end
+ end
+ if @document_status == :in_doctype
+ md = @source.match(/\s*(.*?>)/um)
+ case md[1]
+ when SYSTEMENTITY
+ match = @source.match( SYSTEMENTITY, true )[1]
+ return [ :externalentity, match ]
- when ELEMENTDECL_START
- return [ :elementdecl, @source.match( ELEMENTDECL_PATTERN, true )[1] ]
+ when ELEMENTDECL_START
+ return [ :elementdecl, @source.match( ELEMENTDECL_PATTERN, true )[1] ]
- when ENTITY_START
- match = @source.match( ENTITYDECL, true ).to_a.compact
- match[0] = :entitydecl
- ref = false
- if match[1] == '%'
- ref = true
- match.delete_at 1
- end
- # Now we have to sort out what kind of entity reference this is
- if match[2] == 'SYSTEM'
- # External reference
- match[3] = match[3][1..-2] # PUBID
- match.delete_at(4) if match.size > 4 # Chop out NDATA decl
- # match is [ :entity, name, SYSTEM, pubid(, ndata)? ]
- elsif match[2] == 'PUBLIC'
- # External reference
- match[3] = match[3][1..-2] # PUBID
- match[4] = match[4][1..-2] # HREF
- # match is [ :entity, name, PUBLIC, pubid, href ]
- else
- match[2] = match[2][1..-2]
- match.pop if match.size == 4
- # match is [ :entity, name, value ]
- end
- match << '%' if ref
- return match
- when ATTLISTDECL_START
- md = @source.match( ATTLISTDECL_PATTERN, true )
- raise REXML::ParseException.new( "Bad ATTLIST declaration!", @source ) if md.nil?
- element = md[1]
- contents = md[0]
+ when ENTITY_START
+ match = @source.match( ENTITYDECL, true ).to_a.compact
+ match[0] = :entitydecl
+ ref = false
+ if match[1] == '%'
+ ref = true
+ match.delete_at 1
+ end
+ # Now we have to sort out what kind of entity reference this is
+ if match[2] == 'SYSTEM'
+ # External reference
+ match[3] = match[3][1..-2] # PUBID
+ match.delete_at(4) if match.size > 4 # Chop out NDATA decl
+ # match is [ :entity, name, SYSTEM, pubid(, ndata)? ]
+ elsif match[2] == 'PUBLIC'
+ # External reference
+ match[3] = match[3][1..-2] # PUBID
+ match[4] = match[4][1..-2] # HREF
+ # match is [ :entity, name, PUBLIC, pubid, href ]
+ else
+ match[2] = match[2][1..-2]
+ match.pop if match.size == 4
+ # match is [ :entity, name, value ]
+ end
+ match << '%' if ref
+ return match
+ when ATTLISTDECL_START
+ md = @source.match( ATTLISTDECL_PATTERN, true )
+ raise REXML::ParseException.new( "Bad ATTLIST declaration!", @source ) if md.nil?
+ element = md[1]
+ contents = md[0]
- pairs = {}
- values = md[0].scan( ATTDEF_RE )
- values.each do |attdef|
- unless attdef[3] == "#IMPLIED"
- attdef.compact!
- val = attdef[3]
- val = attdef[4] if val == "#FIXED "
- pairs[attdef[0]] = val
- end
- end
- return [ :attlistdecl, element, pairs, contents ]
- when NOTATIONDECL_START
- md = nil
- if @source.match( PUBLIC )
- md = @source.match( PUBLIC, true )
- elsif @source.match( SYSTEM )
- md = @source.match( SYSTEM, true )
- else
- raise REXML::ParseException.new( "error parsing notation: no matching pattern", @source )
- end
- return [ :notationdecl, md[1], md[2], md[3] ]
- when CDATA_END
- @document_status = :after_doctype
- @source.match( CDATA_END, true )
- return [ :end_doctype ]
- end
- end
- begin
- if @source.buffer[0] == ?<
- if @source.buffer[1] == ?/
- last_tag = @tags.pop
- #md = @source.match_to_consume( '>', CLOSE_MATCH)
- md = @source.match( CLOSE_MATCH, true )
- raise REXML::ParseException.new( "Missing end tag for "+
+ pairs = {}
+ values = md[0].scan( ATTDEF_RE )
+ values.each do |attdef|
+ unless attdef[3] == "#IMPLIED"
+ attdef.compact!
+ val = attdef[3]
+ val = attdef[4] if val == "#FIXED "
+ pairs[attdef[0]] = val
+ end
+ end
+ return [ :attlistdecl, element, pairs, contents ]
+ when NOTATIONDECL_START
+ md = nil
+ if @source.match( PUBLIC )
+ md = @source.match( PUBLIC, true )
+ elsif @source.match( SYSTEM )
+ md = @source.match( SYSTEM, true )
+ else
+ raise REXML::ParseException.new( "error parsing notation: no matching pattern", @source )
+ end
+ return [ :notationdecl, md[1], md[2], md[3] ]
+ when CDATA_END
+ @document_status = :after_doctype
+ @source.match( CDATA_END, true )
+ return [ :end_doctype ]
+ end
+ end
+ begin
+ if @source.buffer[0] == ?<
+ if @source.buffer[1] == ?/
+ last_tag = @tags.pop
+ #md = @source.match_to_consume( '>', CLOSE_MATCH)
+ md = @source.match( CLOSE_MATCH, true )
+ raise REXML::ParseException.new( "Missing end tag for "+
"'#{last_tag}' (got \"#{md[1]}\")",
@source) unless last_tag == md[1]
- return [ :end_element, last_tag ]
- elsif @source.buffer[1] == ?!
- md = @source.match(/\A(\s*[^>]*>)/um)
- #puts "SOURCE BUFFER = #{source.buffer}, #{source.buffer.size}"
- raise REXML::ParseException.new("Malformed node", @source) unless md
- if md[0][2] == ?-
- md = @source.match( COMMENT_PATTERN, true )
- return [ :comment, md[1] ] if md
- else
- md = @source.match( CDATA_PATTERN, true )
- return [ :cdata, md[1] ] if md
- end
- raise REXML::ParseException.new( "Declarations can only occur "+
- "in the doctype declaration.", @source)
- elsif @source.buffer[1] == ??
- md = @source.match( INSTRUCTION_PATTERN, true )
- return [ :processing_instruction, md[1], md[2] ] if md
- raise REXML::ParseException.new( "Bad instruction declaration",
- @source)
- else
- # Get the next tag
- md = @source.match(TAG_MATCH, true)
- raise REXML::ParseException.new("malformed XML: missing tag start", @source) unless md
- attrs = []
- if md[2].size > 0
- attrs = md[2].scan( ATTRIBUTE_PATTERN )
- raise REXML::ParseException.new( "error parsing attributes: [#{attrs.join ', '}], excess = \"#$'\"", @source) if $' and $'.strip.size > 0
- end
-
- if md[4]
- @closed = md[1]
- else
- @tags.push( md[1] )
- end
- attributes = {}
- attrs.each { |a,b,c| attributes[a] = c }
- return [ :start_element, md[1], attributes ]
- end
- else
- md = @source.match( TEXT_PATTERN, true )
+ return [ :end_element, last_tag ]
+ elsif @source.buffer[1] == ?!
+ md = @source.match(/\A(\s*[^>]*>)/um)
+ #puts "SOURCE BUFFER = #{source.buffer}, #{source.buffer.size}"
+ raise REXML::ParseException.new("Malformed node", @source) unless md
+ if md[0][2] == ?-
+ md = @source.match( COMMENT_PATTERN, true )
+ return [ :comment, md[1] ] if md
+ else
+ md = @source.match( CDATA_PATTERN, true )
+ return [ :cdata, md[1] ] if md
+ end
+ raise REXML::ParseException.new( "Declarations can only occur "+
+ "in the doctype declaration.", @source)
+ elsif @source.buffer[1] == ??
+ md = @source.match( INSTRUCTION_PATTERN, true )
+ return [ :processing_instruction, md[1], md[2] ] if md
+ raise REXML::ParseException.new( "Bad instruction declaration",
+ @source)
+ else
+ # Get the next tag
+ md = @source.match(TAG_MATCH, true)
+ raise REXML::ParseException.new("malformed XML: missing tag start", @source) unless md
+ attrs = []
+ if md[2].size > 0
+ attrs = md[2].scan( ATTRIBUTE_PATTERN )
+ raise REXML::ParseException.new( "error parsing attributes: [#{attrs.join ', '}], excess = \"#$'\"", @source) if $' and $'.strip.size > 0
+ end
+
+ if md[4]
+ @closed = md[1]
+ else
+ @tags.push( md[1] )
+ end
+ attributes = {}
+ attrs.each { |a,b,c| attributes[a] = c }
+ return [ :start_element, md[1], attributes ]
+ end
+ else
+ md = @source.match( TEXT_PATTERN, true )
if md[0].length == 0
#puts "EMPTY = #{empty?}"
#puts "BUFFER = \"#{@source.buffer}\""
@source.match( /(\s+)/, true )
end
#return [ :text, "" ] if md[0].length == 0
- # unnormalized = Text::unnormalize( md[1], self )
- # return PullEvent.new( :text, md[1], unnormalized )
- return [ :text, md[1] ]
- end
- rescue REXML::ParseException
- raise
- rescue Exception, NameError => error
- raise REXML::ParseException.new( "Exception parsing",
- @source, self, (error ? error : $!) )
- end
- return [ :dummy ]
- end
+ # unnormalized = Text::unnormalize( md[1], self )
+ # return PullEvent.new( :text, md[1], unnormalized )
+ return [ :text, md[1] ]
+ end
+ rescue REXML::ParseException
+ raise
+ rescue Exception, NameError => error
+ raise REXML::ParseException.new( "Exception parsing",
+ @source, self, (error ? error : $!) )
+ end
+ return [ :dummy ]
+ end
- def entity( reference, entities )
- value = nil
- value = entities[ reference ] if entities
- if not value
- value = DEFAULT_ENTITIES[ reference ]
- value = value[2] if value
- end
- unnormalize( value, entities ) if value
- end
+ def entity( reference, entities )
+ value = nil
+ value = entities[ reference ] if entities
+ if not value
+ value = DEFAULT_ENTITIES[ reference ]
+ value = value[2] if value
+ end
+ unnormalize( value, entities ) if value
+ end
- # Escapes all possible entities
- def normalize( input, entities=nil, entity_filter=nil )
- copy = input.clone
- # Doing it like this rather than in a loop improves the speed
- copy.gsub!( EREFERENCE, '&amp;' )
- entities.each do |key, value|
- copy.gsub!( value, "&#{key};" ) unless entity_filter and
- entity_filter.include?(entity)
- end if entities
- copy.gsub!( EREFERENCE, '&amp;' )
- DEFAULT_ENTITIES.each do |key, value|
- copy.gsub!( value[3], value[1] )
- end
- copy
- end
+ # Escapes all possible entities
+ def normalize( input, entities=nil, entity_filter=nil )
+ copy = input.clone
+ # Doing it like this rather than in a loop improves the speed
+ copy.gsub!( EREFERENCE, '&amp;' )
+ entities.each do |key, value|
+ copy.gsub!( value, "&#{key};" ) unless entity_filter and
+ entity_filter.include?(entity)
+ end if entities
+ copy.gsub!( EREFERENCE, '&amp;' )
+ DEFAULT_ENTITIES.each do |key, value|
+ copy.gsub!( value[3], value[1] )
+ end
+ copy
+ end
- # Unescapes all possible entities
- def unnormalize( string, entities=nil, filter=nil )
- rv = string.clone
- rv.gsub!( /\r\n?/, "\n" )
- matches = rv.scan( REFERENCE_RE )
- return rv if matches.size == 0
- rv.gsub!( /&#0*((?:\d+)|(?:x[a-fA-F0-9]+));/ ) {|m|
- m=$1
- m = "0#{m}" if m[0] == ?x
- [Integer(m)].pack('U*')
- }
- matches.collect!{|x|x[0]}.compact!
- if matches.size > 0
- matches.each do |entity_reference|
- unless filter and filter.include?(entity_reference)
- entity_value = entity( entity_reference, entities )
- if entity_value
- re = /&#{entity_reference};/
- rv.gsub!( re, entity_value )
- end
- end
- end
- matches.each do |entity_reference|
- unless filter and filter.include?(entity_reference)
- er = DEFAULT_ENTITIES[entity_reference]
- rv.gsub!( er[0], er[2] ) if er
- end
- end
- rv.gsub!( /&amp;/, '&' )
- end
- rv
- end
- end
- end
+ # Unescapes all possible entities
+ def unnormalize( string, entities=nil, filter=nil )
+ rv = string.clone
+ rv.gsub!( /\r\n?/, "\n" )
+ matches = rv.scan( REFERENCE_RE )
+ return rv if matches.size == 0
+ rv.gsub!( /&#0*((?:\d+)|(?:x[a-fA-F0-9]+));/ ) {|m|
+ m=$1
+ m = "0#{m}" if m[0] == ?x
+ [Integer(m)].pack('U*')
+ }
+ matches.collect!{|x|x[0]}.compact!
+ if matches.size > 0
+ matches.each do |entity_reference|
+ unless filter and filter.include?(entity_reference)
+ entity_value = entity( entity_reference, entities )
+ if entity_value
+ re = /&#{entity_reference};/
+ rv.gsub!( re, entity_value )
+ end
+ end
+ end
+ matches.each do |entity_reference|
+ unless filter and filter.include?(entity_reference)
+ er = DEFAULT_ENTITIES[entity_reference]
+ rv.gsub!( er[0], er[2] ) if er
+ end
+ end
+ rv.gsub!( /&amp;/, '&' )
+ end
+ rv
+ end
+ end
+ end
end
=begin
diff --git a/lib/rexml/parsers/pullparser.rb b/lib/rexml/parsers/pullparser.rb
index 09ac8948f6..fe4d41c959 100644
--- a/lib/rexml/parsers/pullparser.rb
+++ b/lib/rexml/parsers/pullparser.rb
@@ -1,195 +1,149 @@
-require 'forwardable'
-
require 'rexml/parseexception'
require 'rexml/parsers/baseparser'
require 'rexml/xmltokens'
module REXML
- module Parsers
- # = Using the Pull Parser
- # <em>This API is experimental, and subject to change.</em>
- # parser = PullParser.new( "<a>text<b att='val'/>txet</a>" )
- # while parser.has_next?
- # res = parser.next
- # puts res[1]['att'] if res.start_tag? and res[0] == 'b'
- # end
- # See the PullEvent class for information on the content of the results.
- # The data is identical to the arguments passed for the various events to
- # the StreamListener API.
- #
- # Notice that:
- # parser = PullParser.new( "<a>BAD DOCUMENT" )
- # while parser.has_next?
- # res = parser.next
- # raise res[1] if res.error?
- # end
- #
- # Nat Price gave me some good ideas for the API.
- class PullParser
- include XMLTokens
- extend Forwardable
-
- def_delegators( :@parser, :has_next? )
- def_delegators( :@parser, :entity )
- def_delegators( :@parser, :empty? )
-
- def initialize stream
- @entities = {}
+ module Parsers
+ # = Using the Pull Parser
+ # <em>This API is experimental, and subject to change.</em>
+ # parser = PullParser.new( "<a>text<b att='val'/>txet</a>" )
+ # while parser.has_next?
+ # res = parser.next
+ # puts res[1]['att'] if res.start_tag? and res[0] == 'b'
+ # end
+ # See the PullEvent class for information on the content of the results.
+ # The data is identical to the arguments passed for the various events to
+ # the StreamListener API.
+ #
+ # Notice that:
+ # parser = PullParser.new( "<a>BAD DOCUMENT" )
+ # while parser.has_next?
+ # res = parser.next
+ # raise res[1] if res.error?
+ # end
+ #
+ # Nat Price gave me some good ideas for the API.
+ class PullParser < BaseParser
+ include XMLTokens
+
+ def initialize stream
+ super
+ @entities = {}
@listeners = nil
- @parser = BaseParser.new( stream )
- @my_stack = []
- end
+ end
def add_listener( listener )
@listeners = [] unless @listeners
@listeners << listener
end
- def each
- while has_next?
- yield self.pull
- end
- end
-
- def peek depth=0
- if @my_stack.length <= depth
- (depth - @my_stack.length + 1).times {
- e = PullEvent.new(@parser.pull)
- @my_stack.push(e)
- }
- end
- @my_stack[depth]
- end
-
- def pull
- return @my_stack.shift if @my_stack.length > 0
-
- event = @parser.pull
- case event[0]
- when :entitydecl
- @entities[ event[1] ] =
- event[2] unless event[2] =~ /PUBLIC|SYSTEM/
- when :text
- unnormalized = @parser.unnormalize( event[1], @entities )
- event << unnormalized
- end
- PullEvent.new( event )
- end
-
- def unshift token
- @my_stack.unshift token
- end
- end
-
- # A parsing event. The contents of the event are accessed as an +Array?,
- # and the type is given either by the ...? methods, or by accessing the
- # +type+ accessor. The contents of this object vary from event to event,
- # but are identical to the arguments passed to +StreamListener+s for each
- # event.
- class PullEvent
- # The type of this event. Will be one of :tag_start, :tag_end, :text,
- # :processing_instruction, :comment, :doctype, :attlistdecl, :entitydecl,
- # :notationdecl, :entity, :cdata, :xmldecl, or :error.
- def initialize(arg)
- @contents = arg
- end
-
- def []( start, endd=nil)
- if start.kind_of? Range
- @contents.slice( start.begin+1 .. start.end )
- elsif start.kind_of? Numeric
- if endd.nil?
- @contents.slice( start+1 )
- else
- @contents.slice( start+1, endd )
- end
- else
- raise "Illegal argument #{start.inspect} (#{start.class})"
- end
- end
-
- def event_type
- @contents[0]
- end
-
- # Content: [ String tag_name, Hash attributes ]
- def start_element?
- @contents[0] == :start_element
- end
-
- # Content: [ String tag_name ]
- def end_element?
- @contents[0] == :end_element
- end
-
- # Content: [ String raw_text, String unnormalized_text ]
- def text?
- @contents[0] == :text
- end
-
- # Content: [ String text ]
- def instruction?
- @contents[0] == :processing_instruction
- end
-
- # Content: [ String text ]
- def comment?
- @contents[0] == :comment
- end
-
- # Content: [ String name, String pub_sys, String long_name, String uri ]
- def doctype?
- @contents[0] == :start_doctype
- end
-
- # Content: [ String text ]
- def attlistdecl?
- @contents[0] == :attlistdecl
- end
-
- # Content: [ String text ]
- def elementdecl?
- @contents[0] == :elementdecl
- end
-
- # Due to the wonders of DTDs, an entity declaration can be just about
- # anything. There's no way to normalize it; you'll have to interpret the
- # content yourself. However, the following is true:
- #
- # * If the entity declaration is an internal entity:
- # [ String name, String value ]
- # Content: [ String text ]
- def entitydecl?
- @contents[0] == :entitydecl
- end
-
- # Content: [ String text ]
- def notationdecl?
- @contents[0] == :notationdecl
- end
-
- # Content: [ String text ]
- def entity?
- @contents[0] == :entity
- end
-
- # Content: [ String text ]
- def cdata?
- @contents[0] == :cdata
- end
-
- # Content: [ String version, String encoding, String standalone ]
- def xmldecl?
- @contents[0] == :xmldecl
- end
-
- def error?
- @contents[0] == :error
- end
-
- def inspect
- @contents[0].to_s + ": " + @contents[1..-1].inspect
- end
- end
- end
+ def each
+ while has_next?
+ yield self.pull
+ end
+ end
+
+ def peek depth=0
+ PullEvent.new(super)
+ end
+
+ def pull
+ event = super
+ case event[0]
+ when :entitydecl
+ @entities[ event[1] ] =
+ event[2] unless event[2] =~ /PUBLIC|SYSTEM/
+ when :text
+ unnormalized = unnormalize( event[1], @entities )
+ event << unnormalized
+ end
+ PullEvent.new( event )
+ end
+ end
+
+ # A parsing event. The contents of the event are accessed as an +Array?,
+ # and the type is given either by the ...? methods, or by accessing the
+ # +type+ accessor. The contents of this object vary from event to event,
+ # but are identical to the arguments passed to +StreamListener+s for each
+ # event.
+ class PullEvent
+ # The type of this event. Will be one of :tag_start, :tag_end, :text,
+ # :processing_instruction, :comment, :doctype, :attlistdecl, :entitydecl,
+ # :notationdecl, :entity, :cdata, :xmldecl, or :error.
+ def initialize(arg)
+ @contents = arg
+ end
+ def []( index )
+ @contents[index+1]
+ end
+ def event_type
+ @contents[0]
+ end
+ # Content: [ String tag_name, Hash attributes ]
+ def start_element?
+ @contents[0] == :start_element
+ end
+ # Content: [ String tag_name ]
+ def end_element?
+ @contents[0] == :end_element
+ end
+ # Content: [ String raw_text, String unnormalized_text ]
+ def text?
+ @contents[0] == :text
+ end
+ # Content: [ String text ]
+ def instruction?
+ @contents[0] == :processing_instruction
+ end
+ # Content: [ String text ]
+ def comment?
+ @contents[0] == :comment
+ end
+ # Content: [ String name, String pub_sys, String long_name, String uri ]
+ def doctype?
+ @contents[0] == :start_doctype
+ end
+ # Content: [ String text ]
+ def attlistdecl?
+ @contents[0] == :attlistdecl
+ end
+ # Content: [ String text ]
+ def elementdecl?
+ @contents[0] == :elementdecl
+ end
+ # Due to the wonders of DTDs, an entity declaration can be just about
+ # anything. There's no way to normalize it; you'll have to interpret the
+ # content yourself. However, the following is true:
+ #
+ # * If the entity declaration is an internal entity:
+ # [ String name, String value ]
+ # Content: [ String text ]
+ def entitydecl?
+ @contents[0] == :entitydecl
+ end
+ # Content: [ String text ]
+ def notationdecl?
+ @contents[0] == :notationdecl
+ end
+ # Content: [ String text ]
+ def entity?
+ @contents[0] == :entity
+ end
+ # Content: [ String text ]
+ def cdata?
+ @contents[0] == :cdata
+ end
+ # Content: [ String version, String encoding, String standalone ]
+ def xmldecl?
+ @contents[0] == :xmldecl
+ end
+ def error?
+ @contents[0] == :error
+ end
+
+ def inspect
+ @contents[0].to_s + ": " + @contents[1..-1].inspect
+ end
+ end
+ end
end
diff --git a/lib/rexml/parsers/sax2parser.rb b/lib/rexml/parsers/sax2parser.rb
index f1b8246902..96440d17bf 100644
--- a/lib/rexml/parsers/sax2parser.rb
+++ b/lib/rexml/parsers/sax2parser.rb
@@ -1,11 +1,9 @@
require 'rexml/parsers/baseparser'
require 'rexml/parseexception'
require 'rexml/namespace'
-require 'rexml/text'
module REXML
module Parsers
- # SAX2Parser
class SAX2Parser
def initialize source
@parser = BaseParser.new(source)
@@ -14,7 +12,6 @@ module REXML
@namespace_stack = []
@has_listeners = false
@tag_stack = []
- @entities = {}
end
def add_listener( listener )
@@ -38,10 +35,6 @@ module REXML
# :start_prefix_mapping, :end_prefix_mapping, :characters,
# :processing_instruction, :doctype, :attlistdecl, :elementdecl,
# :entitydecl, :notationdecl, :cdata, :xmldecl, :comment
- #
- # There is an additional symbol that can be listened for: :progress.
- # This will be called for every event generated, passing in the current
- # stream position.
#
# Array contains regular expressions or strings which will be matched
# against fully qualified element names.
@@ -150,24 +143,12 @@ module REXML
end
end
when :text
- #normalized = @parser.normalize( event[1] )
- #handle( :characters, normalized )
- copy = event[1].clone
- @entities.each { |key, value| copy = copy.gsub("&#{key};", value) }
- copy.gsub!( Text::NUMERICENTITY ) {|m|
- m=$1
- m = "0#{m}" if m[0] == ?x
- [Integer(m)].pack('U*')
- }
- handle( :characters, copy )
- when :entitydecl
- @entities[ event[1] ] = event[2] if event.size == 3
- handle( *event )
+ normalized = @parser.normalize( event[1] )
+ handle( :characters, normalized )
when :processing_instruction, :comment, :doctype, :attlistdecl,
- :elementdecl, :cdata, :notationdecl, :xmldecl
+ :elementdecl, :entitydecl, :cdata, :notationdecl, :xmldecl
handle( *event )
end
- handle( :progress, @parser.source.position )
end
end
diff --git a/lib/rexml/parsers/streamparser.rb b/lib/rexml/parsers/streamparser.rb
index 996d613e15..357cc186e6 100644
--- a/lib/rexml/parsers/streamparser.rb
+++ b/lib/rexml/parsers/streamparser.rb
@@ -31,8 +31,9 @@ module REXML
@listener.instruction( *event[1,2] )
when :start_doctype
@listener.doctype( *event[1..-1] )
- when :comment, :attlistdecl, :notationdecl, :elementdecl,
- :entitydecl, :cdata, :xmldecl, :attlistdecl
+ when :notationdecl, :entitydecl, :elementdecl
+ @listener.notationdecl( event[1..-1] )
+ when :comment, :attlistdecl, :elementdecl, :cdata, :xmldecl
@listener.send( event[0].to_s, *event[1..-1] )
end
end
diff --git a/lib/rexml/parsers/xpathparser.rb b/lib/rexml/parsers/xpathparser.rb
index 6bac852d6b..41b2b8a5c1 100644
--- a/lib/rexml/parsers/xpathparser.rb
+++ b/lib/rexml/parsers/xpathparser.rb
@@ -20,7 +20,7 @@ module REXML
path.gsub!(/([\(\[])\s+/, '\1') # Strip ignorable spaces
path.gsub!( /\s+([\]\)])/, '\1' )
parsed = []
- path = OrExpr(path, parsed)
+ path = LocationPath(path, parsed)
parsed
end
@@ -302,7 +302,7 @@ module REXML
path = path[1..-1]
end
parsed << :processing_instruction
- parsed << (literal || '')
+ parsed << literal
when NCNAMETEST
#puts "NCNAMETEST"
prefix = $1
@@ -589,10 +589,9 @@ module REXML
when /^(\w[-\w]*)(?:\()/
#puts "PrimaryExpr :: Function >>> #$1 -- '#$''"
fname = $1
- tmp = $'
+ path = $'
#puts "#{fname} =~ #{NT.inspect}"
- return path if fname =~ NT
- path = tmp
+ #return nil if fname =~ NT
parsed << :function
parsed << fname
path = FunctionCall(path, parsed)
diff --git a/lib/rexml/rexml.rb b/lib/rexml/rexml.rb
index 86690b8488..991650e95f 100644
--- a/lib/rexml/rexml.rb
+++ b/lib/rexml/rexml.rb
@@ -10,8 +10,8 @@
#
# Main page:: http://www.germane-software.com/software/rexml
# Author:: Sean Russell <serATgermaneHYPHENsoftwareDOTcom>
-# Version:: 3.1.3
-# Date:: 2005/224
+# Date:: +2004/200
+# Version:: 3.1.2.1
#
# This API documentation can be downloaded from the REXML home page, or can
# be accessed online[http://www.germane-software.com/software/rexml_doc]
@@ -21,6 +21,6 @@
# online[http://www.germane-software.com/software/rexml/docs/tutorial.html]
module REXML
Copyright = "Copyright © 2001, 2002, 2003, 2004 Sean Russell <ser@germane-software.com>"
- Date = "2005/224"
- Version = "3.1.3"
+ Date = "+2004/200"
+ Version = "3.1.2.1"
end
diff --git a/lib/rexml/sax2listener.rb b/lib/rexml/sax2listener.rb
index 339ae64121..40a77ed464 100644
--- a/lib/rexml/sax2listener.rb
+++ b/lib/rexml/sax2listener.rb
@@ -90,7 +90,5 @@ module REXML
# @p comment The content of the comment
def comment comment
end
- def progress position
- end
end
end
diff --git a/lib/rexml/source.rb b/lib/rexml/source.rb
index f599d2276c..7251666160 100644
--- a/lib/rexml/source.rb
+++ b/lib/rexml/source.rb
@@ -98,10 +98,6 @@ module REXML
@buffer == ""
end
- def position
- @orig.index( @buffer )
- end
-
# @return the current line in the source
def current_line
lines = @orig.split
@@ -198,10 +194,6 @@ module REXML
super and ( @source.nil? || @source.eof? )
end
- def position
- @er_source.pos
- end
-
# @return the current line in the source
def current_line
begin
diff --git a/lib/rexml/syncenumerator.rb b/lib/rexml/syncenumerator.rb
deleted file mode 100644
index 955e006cb2..0000000000
--- a/lib/rexml/syncenumerator.rb
+++ /dev/null
@@ -1,33 +0,0 @@
-module REXML
- class SyncEnumerator
- include Enumerable
-
- # Creates a new SyncEnumerator which enumerates rows of given
- # Enumerable objects.
- def initialize(*enums)
- @gens = enums
- @biggest = @gens[0]
- @gens.each {|x| @biggest = x if x.size > @biggest.size }
- end
-
- # Returns the number of enumerated Enumerable objects, i.e. the size
- # of each row.
- def size
- @gens.size
- end
-
- # Returns the number of enumerated Enumerable objects, i.e. the size
- # of each row.
- def length
- @gens.length
- end
-
- # Enumerates rows of the Enumerable objects.
- def each
- @biggest.zip( *@gens ) {|a|
- yield(*a[1..-1])
- }
- self
- end
- end
-end
diff --git a/lib/rexml/text.rb b/lib/rexml/text.rb
index 9a83121af8..3e5fcc23b6 100644
--- a/lib/rexml/text.rb
+++ b/lib/rexml/text.rb
@@ -5,182 +5,180 @@ require 'rexml/doctype'
require 'rexml/parseexception'
module REXML
- # Represents text nodes in an XML document
- class Text < Child
- include Comparable
- # The order in which the substitutions occur
- SPECIALS = [ /&(?!#?[\w-]+;)/u, /</u, />/u, /"/u, /'/u, /\r/u ]
- SUBSTITUTES = ['&amp;', '&lt;', '&gt;', '&quot;', '&apos;', '&#13;']
- # Characters which are substituted in written strings
- SLAICEPS = [ '<', '>', '"', "'", '&' ]
- SETUTITSBUS = [ /&lt;/u, /&gt;/u, /&quot;/u, /&apos;/u, /&amp;/u ]
+ # Represents text nodes in an XML document
+ class Text < Child
+ include Comparable
+ # The order in which the substitutions occur
+ SPECIALS = [ /&(?!#?[\w-]+;)/u, /</u, />/u, /"/u, /'/u, /\r/u ]
+ SUBSTITUTES = ['&amp;', '&lt;', '&gt;', '&quot;', '&apos;', '&#13;']
+ # Characters which are substituted in written strings
+ SLAICEPS = [ '<', '>', '"', "'", '&' ]
+ SETUTITSBUS = [ /&lt;/u, /&gt;/u, /&quot;/u, /&apos;/u, /&amp;/u ]
- # If +raw+ is true, then REXML leaves the value alone
- attr_accessor :raw
+ # If +raw+ is true, then REXML leaves the value alone
+ attr_accessor :raw
- ILLEGAL = /(<|&(?!(#{Entity::NAME})|(#0*((?:\d+)|(?:x[a-fA-F0-9]+)));))/um
- NUMERICENTITY = /&#0*((?:\d+)|(?:x[a-fA-F0-9]+));/
+ ILLEGAL = /(<|&(?!(#{Entity::NAME})|(#0*((?:\d+)|(?:x[a-fA-F0-9]+)));))/um
+ NUMERICENTITY = /&#0*((?:\d+)|(?:x[a-fA-F0-9]+));/
- # Constructor
- # +arg+ if a String, the content is set to the String. If a Text,
- # the object is shallowly cloned.
- #
- # +respect_whitespace+ (boolean, false) if true, whitespace is
- # respected
- #
- # +parent+ (nil) if this is a Parent object, the parent
- # will be set to this.
- #
- # +raw+ (nil) This argument can be given three values.
- # If true, then the value of used to construct this object is expected to
- # contain no unescaped XML markup, and REXML will not change the text. If
- # this value is false, the string may contain any characters, and REXML will
- # escape any and all defined entities whose values are contained in the
- # text. If this value is nil (the default), then the raw value of the
- # parent will be used as the raw value for this node. If there is no raw
- # value for the parent, and no value is supplied, the default is false.
- # Text.new( "<&", false, nil, false ) #-> "&lt;&amp;"
- # Text.new( "<&", false, nil, true ) #-> IllegalArgumentException
- # Text.new( "&lt;&amp;", false, nil, true ) #-> "&lt;&amp;"
- # # Assume that the entity "s" is defined to be "sean"
- # # and that the entity "r" is defined to be "russell"
- # Text.new( "sean russell" ) #-> "&s; &r;"
- # Text.new( "sean russell", false, nil, true ) #-> "sean russell"
- #
- # +entity_filter+ (nil) This can be an array of entities to match in the
- # supplied text. This argument is only useful if +raw+ is set to false.
- # Text.new( "sean russell", false, nil, false, ["s"] ) #-> "&s; russell"
- # Text.new( "sean russell", false, nil, true, ["s"] ) #-> "sean russell"
- # In the last example, the +entity_filter+ argument is ignored.
- #
- # +pattern+ INTERNAL USE ONLY
- def initialize(arg, respect_whitespace=false, parent=nil, raw=nil,
- entity_filter=nil, illegal=ILLEGAL )
+ # Constructor
+ # +arg+ if a String, the content is set to the String. If a Text,
+ # the object is shallowly cloned.
+ #
+ # +respect_whitespace+ (boolean, false) if true, whitespace is
+ # respected
+ #
+ # +parent+ (nil) if this is a Parent object, the parent
+ # will be set to this.
+ #
+ # +raw+ (nil) This argument can be given three values.
+ # If true, then the value of used to construct this object is expected to
+ # contain no unescaped XML markup, and REXML will not change the text. If
+ # this value is false, the string may contain any characters, and REXML will
+ # escape any and all defined entities whose values are contained in the
+ # text. If this value is nil (the default), then the raw value of the
+ # parent will be used as the raw value for this node. If there is no raw
+ # value for the parent, and no value is supplied, the default is false.
+ # Text.new( "<&", false, nil, false ) #-> "&lt;&amp;"
+ # Text.new( "<&", false, nil, true ) #-> IllegalArgumentException
+ # Text.new( "&lt;&amp;", false, nil, true ) #-> "&lt;&amp;"
+ # # Assume that the entity "s" is defined to be "sean"
+ # # and that the entity "r" is defined to be "russell"
+ # Text.new( "sean russell" ) #-> "&s; &r;"
+ # Text.new( "sean russell", false, nil, true ) #-> "sean russell"
+ #
+ # +entity_filter+ (nil) This can be an array of entities to match in the
+ # supplied text. This argument is only useful if +raw+ is set to false.
+ # Text.new( "sean russell", false, nil, false, ["s"] ) #-> "&s; russell"
+ # Text.new( "sean russell", false, nil, true, ["s"] ) #-> "sean russell"
+ # In the last example, the +entity_filter+ argument is ignored.
+ #
+ # +pattern+ INTERNAL USE ONLY
+ def initialize(arg, respect_whitespace=false, parent=nil, raw=nil,
+ entity_filter=nil, illegal=ILLEGAL )
- @raw = false
+ @raw = false
- if parent
- super( parent )
- @raw = parent.raw
- else
- @parent = nil
- end
+ if parent
+ super( parent )
+ @raw = parent.raw
+ else
+ @parent = nil
+ end
- @raw = raw unless raw.nil?
- @entity_filter = entity_filter
- @normalized = @unnormalized = nil
+ @raw = raw unless raw.nil?
+ @entity_filter = entity_filter
+ @normalized = @unnormalized = nil
- if arg.kind_of? String
- @string = arg.clone
- @string.squeeze!(" \n\t") unless respect_whitespace
- elsif arg.kind_of? Text
- @string = arg.to_s
- @raw = arg.raw
- elsif
- raise "Illegal argument of type #{arg.type} for Text constructor (#{arg})"
- end
+ if arg.kind_of? String
+ @string = arg.clone
+ @string.squeeze!(" \n\t") unless respect_whitespace
+ elsif arg.kind_of? Text
+ @string = arg.to_s
+ @raw = arg.raw
+ elsif
+ raise Exception.new( "Illegal argument of type #{arg.type} for Text constructor (#{arg})" )
+ end
- @string.gsub!( /\r\n?/, "\n" )
+ @string.gsub!( /\r\n?/, "\n" )
- # check for illegal characters
- if @raw
- if @string =~ illegal
- raise "Illegal character '#{$1}' in raw string \"#{@string}\""
- end
- end
- end
+ # check for illegal characters
+ if @raw
+ if @string =~ illegal
+ raise Exception.new(
+ "Illegal character '#{$1}' in raw string \"#{@string}\""
+ )
+ end
+ end
+ end
- def node_type
- :text
- end
+ def node_type
+ :text
+ end
- def empty?
- @string.size==0
- end
+ def empty?
+ @string.size==0
+ end
- def clone
- return Text.new(self)
- end
+ def clone
+ return Text.new(self)
+ end
- # Appends text to this text node. The text is appended in the +raw+ mode
- # of this text node.
- def <<( to_append )
- @string << to_append.gsub( /\r\n?/, "\n" )
- end
+ # Appends text to this text node. The text is appended in the +raw+ mode
+ # of this text node.
+ def <<( to_append )
+ @string << to_append.gsub( /\r\n?/, "\n" )
+ end
- # +other+ a String or a Text
- # +returns+ the result of (to_s <=> arg.to_s)
- def <=>( other )
- to_s() <=> other.to_s
- end
+ # +other+ a String or a Text
+ # +returns+ the result of (to_s <=> arg.to_s)
+ def <=>( other )
+ to_s() <=> other.to_s
+ end
- REFERENCE = /#{Entity::REFERENCE}/
- # Returns the string value of this text node. This string is always
- # escaped, meaning that it is a valid XML text node string, and all
- # entities that can be escaped, have been inserted. This method respects
- # the entity filter set in the constructor.
- #
- # # Assume that the entity "s" is defined to be "sean", and that the
- # # entity "r" is defined to be "russell"
- # t = Text.new( "< & sean russell", false, nil, false, ['s'] )
- # t.to_s #-> "&lt; &amp; &s; russell"
- # t = Text.new( "< & &s; russell", false, nil, false )
- # t.to_s #-> "&lt; &amp; &s; russell"
- # u = Text.new( "sean russell", false, nil, true )
- # u.to_s #-> "sean russell"
- def to_s
- return @string if @raw
- return @normalized if @normalized
+ REFERENCE = /#{Entity::REFERENCE}/
+ # Returns the string value of this text node. This string is always
+ # escaped, meaning that it is a valid XML text node string, and all
+ # entities that can be escaped, have been inserted. This method respects
+ # the entity filter set in the constructor.
+ #
+ # # Assume that the entity "s" is defined to be "sean", and that the
+ # # entity "r" is defined to be "russell"
+ # t = Text.new( "< & sean russell", false, nil, false, ['s'] )
+ # t.to_s #-> "&lt; &amp; &s; russell"
+ # t = Text.new( "< & &s; russell", false, nil, false )
+ # t.to_s #-> "&lt; &amp; &s; russell"
+ # u = Text.new( "sean russell", false, nil, true )
+ # u.to_s #-> "sean russell"
+ def to_s
+ return @string if @raw
+ return @normalized if @normalized
- doctype = nil
- if @parent
- doc = @parent.document
- doctype = doc.doctype if doc
- end
+ doctype = nil
+ if @parent
+ doc = @parent.document
+ doctype = doc.doctype if doc
+ end
- @normalized = Text::normalize( @string, doctype, @entity_filter )
- end
+ @normalized = Text::normalize( @string, doctype, @entity_filter )
+ end
- def inspect
- @string.inspect
- end
-
- # Returns the string value of this text. This is the text without
- # entities, as it might be used programmatically, or printed to the
- # console. This ignores the 'raw' attribute setting, and any
- # entity_filter.
- #
- # # Assume that the entity "s" is defined to be "sean", and that the
- # # entity "r" is defined to be "russell"
- # t = Text.new( "< & sean russell", false, nil, false, ['s'] )
- # t.string #-> "< & sean russell"
- # t = Text.new( "< & &s; russell", false, nil, false )
- # t.string #-> "< & sean russell"
- # u = Text.new( "sean russell", false, nil, true )
- # u.string #-> "sean russell"
- def value
- @unnormalized if @unnormalized
- doctype = nil
- if @parent
- doc = @parent.document
- doctype = doc.doctype if doc
- end
- @unnormalized = Text::unnormalize( @string, doctype )
- end
-
- def wrap(string, width, addnewline=false)
- # Recursivly wrap string at width.
- return string if string.length <= width
- place = string.rindex(' ', width) # Position in string with last ' ' before cutoff
- if addnewline then
- return "\n" + string[0,place] + "\n" + wrap(string[place+1..-1], width)
- else
- return string[0,place] + "\n" + wrap(string[place+1..-1], width)
- end
- end
+ # Returns the string value of this text. This is the text without
+ # entities, as it might be used programmatically, or printed to the
+ # console. This ignores the 'raw' attribute setting, and any
+ # entity_filter.
+ #
+ # # Assume that the entity "s" is defined to be "sean", and that the
+ # # entity "r" is defined to be "russell"
+ # t = Text.new( "< & sean russell", false, nil, false, ['s'] )
+ # t.string #-> "< & sean russell"
+ # t = Text.new( "< & &s; russell", false, nil, false )
+ # t.string #-> "< & sean russell"
+ # u = Text.new( "sean russell", false, nil, true )
+ # u.string #-> "sean russell"
+ def value
+ @unnormalized if @unnormalized
+ doctype = nil
+ if @parent
+ doc = @parent.document
+ doctype = doc.doctype if doc
+ end
+ @unnormalized = Text::unnormalize( @string, doctype )
+ end
+
+ def wrap(string, width, addnewline=false)
+ # Recursivly wrap string at width.
+ return string if string.length <= width
+ place = string.rindex(' ', width) # Position in string with last ' ' before cutoff
+ if addnewline then
+ return "\n" + string[0,place] + "\n" + wrap(string[place+1..-1], width)
+ else
+ return string[0,place] + "\n" + wrap(string[place+1..-1], width)
+ end
+ end
# Sets the contents of this text node. This expects the text to be
# unnormalized. It returns self.
@@ -190,26 +188,26 @@ module REXML
# e[0].value = "bar" # <a>bar</a>
# e[0].value = "<a>" # <a>&lt;a&gt;</a>
def value=( val )
- @string = val.gsub( /\r\n?/, "\n" )
+ @string = val.gsub( /\r\n?/, "\n" )
@unnormalized = nil
@normalized = nil
@raw = false
end
- def indent_text(string, level=1, style="\t", indentfirstline=true)
+ def indent_text(string, level=1, style="\t", indentfirstline=true)
return string if level < 0
- new_string = ''
- string.each { |line|
- indent_string = style * level
- new_line = (indent_string + line).sub(/[\s]+$/,'')
- new_string << new_line
- }
- new_string.strip! unless indentfirstline
- return new_string
- end
+ new_string = ''
+ string.each { |line|
+ indent_string = style * level
+ new_line = (indent_string + line).sub(/[\s]+$/,'')
+ new_string << new_line
+ }
+ new_string.strip! unless indentfirstline
+ return new_string
+ end
- def write( writer, indent=-1, transitive=false, ie_hack=false )
- s = to_s()
+ def write( writer, indent=-1, transitive=false, ie_hack=false )
+ s = to_s()
if not (@parent and @parent.whitespace) then
s = wrap(s, 60, false) if @parent and @parent.context[:wordwrap] == :all
if @parent and not @parent.context[:indentstyle].nil? and indent > 0 and s.count("\n") > 0
@@ -218,7 +216,7 @@ module REXML
s.squeeze!(" \n\t") if @parent and !@parent.whitespace
end
writer << s
- end
+ end
# FIXME
# This probably won't work properly
@@ -228,111 +226,111 @@ module REXML
return path
end
- # Writes out text, substituting special characters beforehand.
- # +out+ A String, IO, or any other object supporting <<( String )
- # +input+ the text to substitute and the write out
- #
- # z=utf8.unpack("U*")
- # ascOut=""
- # z.each{|r|
- # if r < 0x100
- # ascOut.concat(r.chr)
- # else
- # ascOut.concat(sprintf("&#x%x;", r))
- # end
- # }
- # puts ascOut
- def write_with_substitution out, input
- copy = input.clone
- # Doing it like this rather than in a loop improves the speed
- copy.gsub!( SPECIALS[0], SUBSTITUTES[0] )
- copy.gsub!( SPECIALS[1], SUBSTITUTES[1] )
- copy.gsub!( SPECIALS[2], SUBSTITUTES[2] )
- copy.gsub!( SPECIALS[3], SUBSTITUTES[3] )
- copy.gsub!( SPECIALS[4], SUBSTITUTES[4] )
- copy.gsub!( SPECIALS[5], SUBSTITUTES[5] )
- out << copy
- end
+ # Writes out text, substituting special characters beforehand.
+ # +out+ A String, IO, or any other object supporting <<( String )
+ # +input+ the text to substitute and the write out
+ #
+ # z=utf8.unpack("U*")
+ # ascOut=""
+ # z.each{|r|
+ # if r < 0x100
+ # ascOut.concat(r.chr)
+ # else
+ # ascOut.concat(sprintf("&#x%x;", r))
+ # end
+ # }
+ # puts ascOut
+ def write_with_substitution out, input
+ copy = input.clone
+ # Doing it like this rather than in a loop improves the speed
+ copy.gsub!( SPECIALS[0], SUBSTITUTES[0] )
+ copy.gsub!( SPECIALS[1], SUBSTITUTES[1] )
+ copy.gsub!( SPECIALS[2], SUBSTITUTES[2] )
+ copy.gsub!( SPECIALS[3], SUBSTITUTES[3] )
+ copy.gsub!( SPECIALS[4], SUBSTITUTES[4] )
+ copy.gsub!( SPECIALS[5], SUBSTITUTES[5] )
+ out << copy
+ end
- # Reads text, substituting entities
- def Text::read_with_substitution( input, illegal=nil )
- copy = input.clone
+ # Reads text, substituting entities
+ def Text::read_with_substitution( input, illegal=nil )
+ copy = input.clone
- if copy =~ illegal
- raise ParseException.new( "malformed text: Illegal character #$& in \"#{copy}\"" )
- end if illegal
-
- copy.gsub!( /\r\n?/, "\n" )
- if copy.include? ?&
- copy.gsub!( SETUTITSBUS[0], SLAICEPS[0] )
- copy.gsub!( SETUTITSBUS[1], SLAICEPS[1] )
- copy.gsub!( SETUTITSBUS[2], SLAICEPS[2] )
- copy.gsub!( SETUTITSBUS[3], SLAICEPS[3] )
- copy.gsub!( SETUTITSBUS[4], SLAICEPS[4] )
- copy.gsub!( /&#0*((?:\d+)|(?:x[a-f0-9]+));/ ) {|m|
- m=$1
- #m='0' if m==''
- m = "0#{m}" if m[0] == ?x
- [Integer(m)].pack('U*')
- }
- end
- copy
- end
+ if copy =~ illegal
+ raise ParseException.new( "malformed text: Illegal character #$& in \"#{copy}\"" )
+ end if illegal
+
+ copy.gsub!( /\r\n?/, "\n" )
+ if copy.include? ?&
+ copy.gsub!( SETUTITSBUS[0], SLAICEPS[0] )
+ copy.gsub!( SETUTITSBUS[1], SLAICEPS[1] )
+ copy.gsub!( SETUTITSBUS[2], SLAICEPS[2] )
+ copy.gsub!( SETUTITSBUS[3], SLAICEPS[3] )
+ copy.gsub!( SETUTITSBUS[4], SLAICEPS[4] )
+ copy.gsub!( /&#0*((?:\d+)|(?:x[a-f0-9]+));/ ) {|m|
+ m=$1
+ #m='0' if m==''
+ m = "0#{m}" if m[0] == ?x
+ [Integer(m)].pack('U*')
+ }
+ end
+ copy
+ end
- EREFERENCE = /&(?!#{Entity::NAME};)/
- # Escapes all possible entities
- def Text::normalize( input, doctype=nil, entity_filter=nil )
- copy = input.clone
- # Doing it like this rather than in a loop improves the speed
- if doctype
- copy = copy.gsub( EREFERENCE, '&amp;' )
- doctype.entities.each_value do |entity|
- copy = copy.gsub( entity.value,
- "&#{entity.name};" ) if entity.value and
- not( entity_filter and entity_filter.include?(entity) )
- end
- else
- copy = copy.gsub( EREFERENCE, '&amp;' )
- DocType::DEFAULT_ENTITIES.each_value do |entity|
- copy = copy.gsub(entity.value, "&#{entity.name};" )
- end
- end
- copy
- end
+ EREFERENCE = /&(?!#{Entity::NAME};)/
+ # Escapes all possible entities
+ def Text::normalize( input, doctype=nil, entity_filter=nil )
+ copy = input.clone
+ # Doing it like this rather than in a loop improves the speed
+ if doctype
+ copy = copy.gsub( EREFERENCE, '&amp;' )
+ doctype.entities.each_value do |entity|
+ copy = copy.gsub( entity.value,
+ "&#{entity.name};" ) if entity.value and
+ not( entity_filter and entity_filter.include?(entity) )
+ end
+ else
+ copy = copy.gsub( EREFERENCE, '&amp;' )
+ DocType::DEFAULT_ENTITIES.each_value do |entity|
+ copy = copy.gsub(entity.value, "&#{entity.name};" )
+ end
+ end
+ copy
+ end
- # Unescapes all possible entities
- def Text::unnormalize( string, doctype=nil, filter=nil, illegal=nil )
- rv = string.clone
- rv.gsub!( /\r\n?/, "\n" )
- matches = rv.scan( REFERENCE )
- return rv if matches.size == 0
- rv.gsub!( NUMERICENTITY ) {|m|
- m=$1
- m = "0#{m}" if m[0] == ?x
- [Integer(m)].pack('U*')
- }
- matches.collect!{|x|x[0]}.compact!
- if matches.size > 0
- if doctype
- matches.each do |entity_reference|
- unless filter and filter.include?(entity_reference)
- entity_value = doctype.entity( entity_reference )
- re = /&#{entity_reference};/
- rv.gsub!( re, entity_value ) if entity_value
- end
- end
- else
- matches.each do |entity_reference|
- unless filter and filter.include?(entity_reference)
- entity_value = DocType::DEFAULT_ENTITIES[ entity_reference ]
- re = /&#{entity_reference};/
- rv.gsub!( re, entity_value.value ) if entity_value
- end
- end
- end
- rv.gsub!( /&amp;/, '&' )
- end
- rv
- end
- end
+ # Unescapes all possible entities
+ def Text::unnormalize( string, doctype=nil, filter=nil, illegal=nil )
+ rv = string.clone
+ rv.gsub!( /\r\n?/, "\n" )
+ matches = rv.scan( REFERENCE )
+ return rv if matches.size == 0
+ rv.gsub!( NUMERICENTITY ) {|m|
+ m=$1
+ m = "0#{m}" if m[0] == ?x
+ [Integer(m)].pack('U*')
+ }
+ matches.collect!{|x|x[0]}.compact!
+ if matches.size > 0
+ if doctype
+ matches.each do |entity_reference|
+ unless filter and filter.include?(entity_reference)
+ entity_value = doctype.entity( entity_reference )
+ re = /&#{entity_reference};/
+ rv.gsub!( re, entity_value ) if entity_value
+ end
+ end
+ else
+ matches.each do |entity_reference|
+ unless filter and filter.include?(entity_reference)
+ entity_value = DocType::DEFAULT_ENTITIES[ entity_reference ]
+ re = /&#{entity_reference};/
+ rv.gsub!( re, entity_value.value ) if entity_value
+ end
+ end
+ end
+ rv.gsub!( /&amp;/, '&' )
+ end
+ rv
+ end
+ end
end
diff --git a/lib/rexml/validation/validation.rb b/lib/rexml/validation/validation.rb
index 160ea96b31..fbee315f0b 100644
--- a/lib/rexml/validation/validation.rb
+++ b/lib/rexml/validation/validation.rb
@@ -82,13 +82,10 @@ module REXML
@event_arg = event_arg
end
+ attr_reader :done?
attr_reader :event_type
attr_accessor :event_arg
- def done?
- @done
- end
-
def single?
return (@event_type != :start_element and @event_type != :start_attribute)
end
diff --git a/lib/rexml/xmldecl.rb b/lib/rexml/xmldecl.rb
index 1b7ef813d1..3f90e0160f 100644
--- a/lib/rexml/xmldecl.rb
+++ b/lib/rexml/xmldecl.rb
@@ -94,10 +94,6 @@ module REXML
@writethis = true
end
- def inspect
- START.sub(/\\/u, '') + " ... " + STOP.sub(/\\/u, '')
- end
-
private
def content(enc)
rv = "version='#@version'"
diff --git a/lib/rexml/xpath.rb b/lib/rexml/xpath.rb
index 1ed440868b..c9c216fe27 100644
--- a/lib/rexml/xpath.rb
+++ b/lib/rexml/xpath.rb
@@ -19,15 +19,13 @@ module REXML
# XPath.first( node )
# XPath.first( doc, "//b"} )
# XPath.first( node, "a/x:b", { "x"=>"http://doofus" } )
- def XPath::first element, path=nil, namespaces={}, variables={}
- raise "The namespaces argument, if supplied, must be a hash object." unless namespaces.kind_of? Hash
- raise "The variables argument, if supplied, must be a hash object." unless variables.kind_of? Hash
+ def XPath::first element, path=nil, namespaces={}, variables={}
parser = XPathParser.new
parser.namespaces = namespaces
parser.variables = variables
path = "*" unless path
element = [element] unless element.kind_of? Array
- parser.parse(path, element).flatten[0]
+ parser.parse(path, element)[0]
end
# Itterates over nodes that match the given path, calling the supplied
@@ -43,8 +41,6 @@ module REXML
# XPath.each( node, '/*[@attr='v']' ) { |el| ... }
# XPath.each( node, 'ancestor::x' ) { |el| ... }
def XPath::each element, path=nil, namespaces={}, variables={}, &block
- raise "The namespaces argument, if supplied, must be a hash object." unless namespaces.kind_of? Hash
- raise "The variables argument, if supplied, must be a hash object." unless variables.kind_of? Hash
parser = XPathParser.new
parser.namespaces = namespaces
parser.variables = variables
diff --git a/lib/rexml/xpath_parser.rb b/lib/rexml/xpath_parser.rb
index 7c0d1dc358..5a976d5e82 100644
--- a/lib/rexml/xpath_parser.rb
+++ b/lib/rexml/xpath_parser.rb
@@ -1,28 +1,7 @@
require 'rexml/namespace'
require 'rexml/xmltokens'
-require 'rexml/attribute'
-require 'rexml/syncenumerator'
require 'rexml/parsers/xpathparser'
-class Object
- def dclone
- clone
- end
-end
-class Symbol
- def dclone
- self
- end
-end
-class Array
- def dclone
- klone = self.clone
- klone.clear
- self.each{|v| klone << v.dclone}
- klone
- end
-end
-
module REXML
# You don't want to use this class. Really. Use XPath, which is a wrapper
# for this class. Believe me. You don't want to poke around in here.
@@ -49,413 +28,259 @@ module REXML
end
def parse path, nodeset
- #puts "#"*40
- path_stack = @parser.parse( path )
- #puts "PARSE: #{path} => #{path_stack.inspect}"
- #puts "PARSE: nodeset = #{nodeset.inspect}"
- match( path_stack, nodeset )
- end
-
- def get_first path, nodeset
- #puts "#"*40
- path_stack = @parser.parse( path )
- #puts "PARSE: #{path} => #{path_stack.inspect}"
- #puts "PARSE: nodeset = #{nodeset.inspect}"
- first( path_stack, nodeset )
+ path_stack = @parser.parse( path )
+ #puts "PARSE: #{path} => #{path_stack.inspect}"
+ #puts "PARSE: nodeset = #{nodeset.collect{|x|x.to_s}.inspect}"
+ match( path_stack, nodeset )
end
def predicate path, nodeset
- path_stack = @parser.parse( path )
- expr( path_stack, nodeset )
+ path_stack = @parser.predicate( path )
+ return Predicate( path_stack, nodeset )
end
def []=( variable_name, value )
@variables[ variable_name ] = value
end
+ def match( path_stack, nodeset )
+ while ( path_stack.size > 0 and nodeset.size > 0 )
+ #puts "PARSE: #{path_stack.inspect} '#{nodeset.collect{|n|n.class}.inspect}'"
+ nodeset = internal_parse( path_stack, nodeset )
+ #puts "NODESET: #{nodeset}"
+ #puts "PATH_STACK: #{path_stack.inspect}"
+ end
+ nodeset
+ end
- # Performs a depth-first (document order) XPath search, and returns the
- # first match. This is the fastest, lightest way to return a single result.
- #
- # FIXME: This method is incomplete!
- def first( path_stack, node )
- #puts "#{depth}) Entering match( #{path.inspect}, #{tree.inspect} )"
- return nil if path.size == 0
+ private
- case path[0]
+ def internal_parse path_stack, nodeset
+ #puts "INTERNAL_PARSE RETURNING WITH NO RESULTS" if nodeset.size == 0 or path_stack.size == 0
+ return nodeset if nodeset.size == 0 or path_stack.size == 0
+ #puts "INTERNAL_PARSE: #{path_stack.inspect}, #{nodeset.collect{|n| n.class}.inspect}"
+ case path_stack.shift
when :document
- # do nothing
- return first( path[1..-1], node )
- when :child
- for c in node.children
- #puts "#{depth}) CHILD checking #{name(c)}"
- r = first( path[1..-1], c )
- #puts "#{depth}) RETURNING #{r.inspect}" if r
- return r if r
- end
+ return [ nodeset[0].root.parent ]
+
when :qname
- name = path[2]
- #puts "#{depth}) QNAME #{name(tree)} == #{name} (path => #{path.size})"
- if node.name == name
- #puts "#{depth}) RETURNING #{tree.inspect}" if path.size == 3
- return node if path.size == 3
- return first( path[3..-1], node )
- else
- return nil
+ prefix = path_stack.shift
+ name = path_stack.shift
+ #puts "QNAME #{prefix}#{prefix.size>0?':':''}#{name}"
+ n = nodeset.clone
+ ns = @namespaces[prefix]
+ ns = ns ? ns : ''
+ n.delete_if do |node|
+ # FIXME: This DOUBLES the time XPath searches take
+ ns = node.namespace( prefix ) if node.node_type == :element and ns == ''
+ #puts "NODE: '#{node.to_s}'; node.has_name?( #{name.inspect}, #{ns.inspect} ): #{ node.has_name?( name, ns )}; node.namespace() = #{node.namespace().inspect}; node.prefix = #{node.prefix().inspect}" if node.node_type == :element
+ !(node.node_type == :element and node.name == name and node.namespace == ns )
end
- when :descendant_or_self
- r = first( path[1..-1], node )
- return r if r
- for c in node.children
- r = first( path, c )
- return r if r
- end
- when :node
- return first( path[1..-1], node )
- when :any
- return first( path[1..-1], node )
- end
- return nil
- end
+ return n
+ when :any
+ n = nodeset.clone
+ n.delete_if { |node| node.node_type != :element }
+ return n
+
+ when :self
+ # THIS SPACE LEFT INTENTIONALLY BLANK
+
+ when :processing_instruction
+ target = path_stack.shift
+ n = nodeset.clone
+ n.delete_if do |node|
+ (node.node_type != :processing_instruction) or
+ ( !target.nil? and ( node.target != target ) )
+ end
+ return n
+
+ when :text
+ #puts ":TEXT"
+ n = nodeset.clone
+ n.delete_if do |node|
+ #puts "#{node} :: #{node.node_type}"
+ node.node_type != :text
+ end
+ return n
- def match( path_stack, nodeset )
- #puts "MATCH: path_stack = #{path_stack.inspect}"
- #puts "MATCH: nodeset = #{nodeset.inspect}"
- r = expr( path_stack, nodeset )
- #puts "MAIN EXPR => #{r.inspect}"
- r
- end
-
- private
-
+ when :comment
+ n = nodeset.clone
+ n.delete_if do |node|
+ node.node_type != :comment
+ end
+ return n
- # Expr takes a stack of path elements and a set of nodes (either a Parent
- # or an Array and returns an Array of matching nodes
- ALL = [ :attribute, :element, :text, :processing_instruction, :comment ]
- ELEMENTS = [ :element ]
- def expr( path_stack, nodeset, context=nil )
- #puts "#"*15
- #puts "In expr with #{path_stack.inspect}"
- #puts "Returning" if path_stack.length == 0 || nodeset.length == 0
- node_types = ELEMENTS
- return nodeset if path_stack.length == 0 || nodeset.length == 0
- while path_stack.length > 0
- #puts "Path stack = #{path_stack.inspect}"
- #puts "Nodeset is #{nodeset.inspect}"
- case (op = path_stack.shift)
- when :document
- nodeset = [ nodeset[0].root_node ]
- #puts ":document, nodeset = #{nodeset.inspect}"
+ when :node
+ return nodeset
+
+ # FIXME: I suspect the following XPath will fail:
+ # /a/*/*[1]
+ when :child
+ #puts "CHILD"
+ new_nodeset = []
+ nt = nil
+ for node in nodeset
+ nt = node.node_type
+ new_nodeset += node.children if nt == :element or nt == :document
+ end
+ #path_stack[0,(path_stack.size-ps_clone.size)] = []
+ return new_nodeset
+ when :literal
+ literal = path_stack.shift
+ if literal =~ /^\d+(\.\d+)?$/
+ return ($1 ? literal.to_f : literal.to_i)
+ end
+ #puts "RETURNING '#{literal}'"
+ return literal
+
+ when :attribute
+ new_nodeset = []
+ case path_stack.shift
when :qname
- #puts "IN QNAME"
prefix = path_stack.shift
name = path_stack.shift
- ns = @namespaces[prefix]
- ns = ns ? ns : ''
- nodeset.delete_if do |node|
- # FIXME: This DOUBLES the time XPath searches take
- ns = node.namespace( prefix ) if node.node_type == :element and ns == ''
- #puts "NS = #{ns.inspect}"
- #puts "node.node_type == :element => #{node.node_type == :element}"
- if node.node_type == :element
- #puts "node.name == #{name} => #{node.name == name}"
- if node.name == name
- #puts "node.namespace == #{ns.inspect} => #{node.namespace == ns}"
- end
+ for element in nodeset
+ if element.node_type == :element
+ #puts element.name
+ #puts "looking for attribute #{name} in '#{@namespaces[prefix]}'"
+ attr = element.attribute( name, @namespaces[prefix] )
+ #puts ":ATTRIBUTE: attr => #{attr}"
+ new_nodeset << attr if attr
end
- !(node.node_type == :element and
- node.name == name and
- node.namespace == ns )
end
- node_types = ELEMENTS
-
when :any
- #puts "ANY 1: nodeset = #{nodeset.inspect}"
- #puts "ANY 1: node_types = #{node_types.inspect}"
- nodeset.delete_if { |node| !node_types.include?(node.node_type) }
- #puts "ANY 2: nodeset = #{nodeset.inspect}"
-
- when :self
- # This space left intentionally blank
-
- when :processing_instruction
- target = path_stack.shift
- nodeset.delete_if do |node|
- (node.node_type != :processing_instruction) or
- ( target!='' and ( node.target != target ) )
- end
-
- when :text
- nodeset.delete_if { |node| node.node_type != :text }
-
- when :comment
- nodeset.delete_if { |node| node.node_type != :comment }
-
- when :node
- # This space left intentionally blank
- node_types = ALL
-
- when :child
- new_nodeset = []
- nt = nil
- for node in nodeset
- nt = node.node_type
- new_nodeset += node.children if nt == :element or nt == :document
- end
- nodeset = new_nodeset
- node_types = ELEMENTS
-
- when :literal
- literal = path_stack.shift
- if literal =~ /^\d+(\.\d+)?$/
- return ($1 ? literal.to_f : literal.to_i)
- end
- return literal
-
- when :attribute
- new_nodeset = []
- case path_stack.shift
- when :qname
- prefix = path_stack.shift
- name = path_stack.shift
- for element in nodeset
- if element.node_type == :element
- #puts element.name
- attr = element.attribute( name, @namespaces[prefix] )
- new_nodeset << attr if attr
- end
- end
- when :any
- #puts "ANY"
- for element in nodeset
- if element.node_type == :element
- new_nodeset += element.attributes.to_a
- end
+ #puts "ANY"
+ for element in nodeset
+ if element.node_type == :element
+ new_nodeset += element.attributes.to_a
end
end
- nodeset = new_nodeset
-
- when :parent
- #puts "PARENT 1: nodeset = #{nodeset}"
- nodeset = nodeset.collect{|n| n.parent}.compact
- #nodeset = expr(path_stack.dclone, nodeset.collect{|n| n.parent}.compact)
- #puts "PARENT 2: nodeset = #{nodeset.inspect}"
- node_types = ELEMENTS
-
- when :ancestor
- new_nodeset = []
- for node in nodeset
- while node.parent
+ end
+ #puts "RETURNING #{new_nodeset.collect{|n|n.to_s}.inspect}"
+ return new_nodeset
+
+ when :parent
+ return internal_parse( path_stack, nodeset.collect{|n| n.parent}.compact )
+
+ when :ancestor
+ #puts "ANCESTOR"
+ new_nodeset = []
+ for node in nodeset
+ while node.parent
+ node = node.parent
+ new_nodeset << node unless new_nodeset.include? node
+ end
+ end
+ #nodeset = new_nodeset.uniq
+ return new_nodeset
+
+ when :ancestor_or_self
+ new_nodeset = []
+ for node in nodeset
+ if node.node_type == :element
+ new_nodeset << node
+ while ( node.parent )
node = node.parent
new_nodeset << node unless new_nodeset.include? node
end
end
- nodeset = new_nodeset
- node_types = ELEMENTS
-
- when :ancestor_or_self
- new_nodeset = []
- for node in nodeset
- if node.node_type == :element
- new_nodeset << node
- while ( node.parent )
- node = node.parent
- new_nodeset << node unless new_nodeset.include? node
- end
- end
- end
- nodeset = new_nodeset
- node_types = ELEMENTS
-
- when :predicate
- new_nodeset = []
- subcontext = { :size => nodeset.size }
- pred = path_stack.shift
- nodeset.each_with_index { |node, index|
- subcontext[ :node ] = node
- #puts "PREDICATE SETTING CONTEXT INDEX TO #{index+1}"
- subcontext[ :index ] = index+1
- pc = pred.dclone
- #puts "#{node.hash}) Recursing with #{pred.inspect} and [#{node.inspect}]"
- result = expr( pc, [node], subcontext )
- result = result[0] if result.kind_of? Array and result.length == 1
- #puts "#{node.hash}) Result = #{result.inspect} (#{result.class.name})"
- if result.kind_of? Numeric
- #puts "Adding node #{node.inspect}" if result == (index+1)
- new_nodeset << node if result == (index+1)
- elsif result.instance_of? Array
- #puts "Adding node #{node.inspect}" if result.size > 0
- new_nodeset << node if result.size > 0
- else
- #puts "Adding node #{node.inspect}" if result
- new_nodeset << node if result
- end
- }
- #puts "New nodeset = #{new_nodeset.inspect}"
- #puts "Path_stack = #{path_stack.inspect}"
- nodeset = new_nodeset
-=begin
- predicate = path_stack.shift
- ns = nodeset.clone
- result = expr( predicate, ns )
- #puts "Result = #{result.inspect} (#{result.class.name})"
- #puts "nodeset = #{nodeset.inspect}"
- if result.kind_of? Array
- nodeset = result.zip(ns).collect{|m,n| n if m}.compact
+ end
+ #nodeset = new_nodeset.uniq
+ return new_nodeset
+
+ when :predicate
+ #puts "@"*80
+ #puts "NODESET = #{nodeset.collect{|n|n.to_s}.inspect}"
+ predicate = path_stack.shift
+ new_nodeset = []
+ Functions::size = nodeset.size
+ nodeset.size.times do |index|
+ node = nodeset[index]
+ Functions::node = node
+ Functions::index = index+1
+ #puts "Node #{node} and index=#{index+1}"
+ result = Predicate( predicate, node )
+ #puts "Predicate returned #{result} (#{result.class}) for #{node.class}"
+ if result.kind_of? Numeric
+ #puts "#{result} == #{index} => #{result == index}"
+ new_nodeset << node if result == (index+1)
+ elsif result.instance_of? Array
+ new_nodeset << node if result.size > 0
else
- nodeset = result ? nodeset : []
- end
- #puts "Outgoing NS = #{nodeset.inspect}"
-=end
-
- when :descendant_or_self
- rv = descendant_or_self( path_stack, nodeset )
- path_stack.clear
- nodeset = rv
- node_types = ELEMENTS
-
- when :descendant
- results = []
- nt = nil
- for node in nodeset
- nt = node.node_type
- results += expr( path_stack.dclone.unshift( :descendant_or_self ),
- node.children ) if nt == :element or nt == :document
+ new_nodeset << node if result
end
- nodeset = results
- node_types = ELEMENTS
-
- when :following_sibling
- #puts "FOLLOWING_SIBLING 1: nodeset = #{nodeset}"
- results = []
- for node in nodeset
- all_siblings = node.parent.children
- current_index = all_siblings.index( node )
- following_siblings = all_siblings[ current_index+1 .. -1 ]
- results += expr( path_stack.dclone, following_siblings )
- end
- #puts "FOLLOWING_SIBLING 2: nodeset = #{nodeset}"
- nodeset = results
-
- when :preceding_sibling
- results = []
- for node in nodeset
- all_siblings = node.parent.children
- current_index = all_siblings.index( node )
- preceding_siblings = all_siblings[ 0 .. current_index-1 ].reverse
- #results += expr( path_stack.dclone, preceding_siblings )
- end
- nodeset = preceding_siblings
- node_types = ELEMENTS
-
- when :preceding
- new_nodeset = []
- for node in nodeset
- new_nodeset += preceding( node )
- end
- #puts "NEW NODESET => #{new_nodeset.inspect}"
- nodeset = new_nodeset
- node_types = ELEMENTS
-
- when :following
- new_nodeset = []
- for node in nodeset
- new_nodeset += following( node )
- end
- nodeset = new_nodeset
- node_types = ELEMENTS
-
- when :namespace
- new_set = []
- for node in nodeset
- new_nodeset << node.namespace if node.node_type == :element or node.node_type == :attribute
- end
- nodeset = new_nodeset
-
- when :variable
- var_name = path_stack.shift
- return @variables[ var_name ]
-
- # :and, :or, :eq, :neq, :lt, :lteq, :gt, :gteq
- when :eq, :neq, :lt, :lteq, :gt, :gteq, :and, :or
- left = expr( path_stack.shift, nodeset, context )
- #puts "LEFT => #{left.inspect} (#{left.class.name})"
- right = expr( path_stack.shift, nodeset, context )
- #puts "RIGHT => #{right.inspect} (#{right.class.name})"
- res = equality_relational_compare( left, op, right )
- #puts "RES => #{res.inspect}"
- return res
+ end
+ #puts "Nodeset after predicate #{predicate.inspect} has #{new_nodeset.size} nodes"
+ #puts "NODESET: #{new_nodeset.collect{|n|n.to_s}.inspect}"
+ return new_nodeset
- when :div
- left = Functions::number(expr(path_stack.shift, nodeset, context)).to_f
- right = Functions::number(expr(path_stack.shift, nodeset, context)).to_f
- return (left / right)
+ when :descendant_or_self
+ rv = descendant_or_self( path_stack, nodeset )
+ path_stack.clear
+ return rv
+
+ when :descendant
+ #puts ":DESCENDANT"
+ results = []
+ nt = nil
+ for node in nodeset
+ nt = node.node_type
+ results += internal_parse( path_stack.clone.unshift( :descendant_or_self ),
+ node.children ) if nt == :element or nt == :document
+ end
+ return results
+
+ when :following_sibling
+ results = []
+ for node in nodeset
+ all_siblings = node.parent.children
+ current_index = all_siblings.index( node )
+ following_siblings = all_siblings[ current_index+1 .. -1 ]
+ results += internal_parse( path_stack.clone, following_siblings )
+ end
+ return results
+
+ when :preceding_sibling
+ results = []
+ for node in nodeset
+ all_siblings = node.parent.children
+ current_index = all_siblings.index( node )
+ preceding_siblings = all_siblings[ 0 .. current_index-1 ]
+ results += internal_parse( path_stack.clone, preceding_siblings )
+ end
+ return results
- when :mod
- left = Functions::number(expr(path_stack.shift, nodeset, context )).to_f
- right = Functions::number(expr(path_stack.shift, nodeset, context )).to_f
- return (left % right)
+ when :preceding
+ new_nodeset = []
+ for node in nodeset
+ new_nodeset += preceding( node )
+ end
+ return new_nodeset
- when :mult
- left = Functions::number(expr(path_stack.shift, nodeset, context )).to_f
- right = Functions::number(expr(path_stack.shift, nodeset, context )).to_f
- return (left * right)
+ when :following
+ new_nodeset = []
+ for node in nodeset
+ new_nodeset += following( node )
+ end
+ return new_nodeset
- when :plus
- left = Functions::number(expr(path_stack.shift, nodeset, context )).to_f
- right = Functions::number(expr(path_stack.shift, nodeset, context )).to_f
- return (left + right)
+ when :namespace
+ new_set = []
+ for node in nodeset
+ new_nodeset << node.namespace if node.node_type == :element or node.node_type == :attribute
+ end
+ return new_nodeset
- when :minus
- left = Functions::number(expr(path_stack.shift, nodeset, context )).to_f
- right = Functions::number(expr(path_stack.shift, nodeset, context )).to_f
- return (left - right)
-
- when :union
- left = expr( path_stack.shift, nodeset, context )
- right = expr( path_stack.shift, nodeset, context )
- return (left | right)
-
- when :neg
- res = expr( path_stack, nodeset, context )
- return -(res.to_f)
-
- when :not
- when :function
- func_name = path_stack.shift.tr('-','_')
- arguments = path_stack.shift
- #puts "FUNCTION 0: #{func_name}(#{arguments.collect{|a|a.inspect}.join(', ')})"
- subcontext = context ? nil : { :size => nodeset.size }
-
- res = []
- cont = context
- nodeset.each_with_index { |n, i|
- if subcontext
- subcontext[:node] = n
- subcontext[:index] = i
- cont = subcontext
- end
- arg_clone = arguments.dclone
- args = arg_clone.collect { |arg|
- #puts "FUNCTION 1: Calling expr( #{arg.inspect}, [#{n.inspect}] )"
- expr( arg, [n], cont )
- }
- #puts "FUNCTION 2: #{func_name}(#{args.collect{|a|a.inspect}.join(', ')})"
- Functions.context = cont
- res << Functions.send( func_name, *args )
- #puts "FUNCTION 3: #{res[-1].inspect}"
- }
- return res
+ when :variable
+ var_name = path_stack.shift
+ return @variables[ var_name ]
- end
- end # while
- #puts "EXPR returning #{nodeset.inspect}"
- return nodeset
+ end
+ nodeset
end
-
##########################################################
# FIXME
# The next two methods are BAD MOJO!
@@ -469,16 +294,13 @@ module REXML
d_o_s( path_stack, nodeset, rs )
#puts "RS = #{rs.collect{|n|n.to_s}.inspect}"
document_order(rs.flatten.compact)
- #rs.flatten.compact
end
def d_o_s( p, ns, r )
- #puts "IN DOS with #{ns.inspect}; ALREADY HAVE #{r.inspect}"
nt = nil
ns.each_index do |i|
n = ns[i]
- #puts "P => #{p.inspect}"
- x = expr( p.dclone, [ n ] )
+ x = match( p.clone, [ n ] )
nt = n.node_type
d_o_s( p, n.children, x ) if nt == :element or nt == :document and n.children.size > 0
r.concat(x) if x.size > 0
@@ -488,12 +310,6 @@ module REXML
# Reorders an array of nodes so that they are in document order
# It tries to do this efficiently.
- #
- # FIXME: I need to get rid of this, but the issue is that most of the XPath
- # interpreter functions as a filter, which means that we lose context going
- # in and out of function calls. If I knew what the index of the nodes was,
- # I wouldn't have to do this. Maybe add a document IDX for each node?
- # Problems with mutable documents. Or, rewrite everything.
def document_order( array_of_nodes )
new_arry = []
array_of_nodes.each { |node|
@@ -503,9 +319,8 @@ module REXML
node_idx << np.parent.index( np )
np = np.parent
end
- new_arry << [ node_idx.reverse, node ]
+ new_arry << [ node_idx.reverse.join, node ]
}
- #puts "new_arry = #{new_arry.inspect}"
new_arry.sort{ |s1, s2| s1[0] <=> s2[0] }.collect{ |s| s[1] }
end
@@ -518,127 +333,124 @@ module REXML
end
+ # Given a predicate, a node, and a context, evaluates to true or false.
+ def Predicate( predicate, node )
+ predicate = predicate.clone
+ #puts "#"*20
+ #puts "Predicate( #{predicate.inspect}, #{node.class} )"
+ results = []
+ case (predicate[0])
+ when :and, :or, :eq, :neq, :lt, :lteq, :gt, :gteq
+ eq = predicate.shift
+ left = Predicate( predicate.shift, node )
+ right = Predicate( predicate.shift, node )
+ #puts "LEFT = #{left.inspect}"
+ #puts "RIGHT = #{right.inspect}"
+ return equality_relational_compare( left, eq, right )
+
+ when :div, :mod, :mult, :plus, :minus
+ op = predicate.shift
+ left = Predicate( predicate.shift, node )
+ right = Predicate( predicate.shift, node )
+ #puts "LEFT = #{left.inspect}"
+ #puts "RIGHT = #{right.inspect}"
+ left = Functions::number( left )
+ right = Functions::number( right )
+ #puts "LEFT = #{left.inspect}"
+ #puts "RIGHT = #{right.inspect}"
+ case op
+ when :div
+ return left.to_f / right.to_f
+ when :mod
+ return left % right
+ when :mult
+ return left * right
+ when :plus
+ return left + right
+ when :minus
+ return left - right
+ end
- # Builds a nodeset of all of the preceding nodes of the supplied node,
- # in reverse document order
- # preceding:: includes every element in the document that precedes this node,
- # except for ancestors
- def preceding( node )
- #puts "IN PRECEDING"
- ancestors = []
- p = node.parent
- while p
- ancestors << p
- p = p.parent
- end
+ when :union
+ predicate.shift
+ left = Predicate( predicate.shift, node )
+ right = Predicate( predicate.shift, node )
+ return (left | right)
+
+ when :neg
+ predicate.shift
+ operand = Functions::number(Predicate( predicate, node ))
+ return -operand
+
+ when :not
+ predicate.shift
+ return !Predicate( predicate.shift, node )
+
+ when :function
+ predicate.shift
+ func_name = predicate.shift.tr('-', '_')
+ arguments = predicate.shift
+ #puts "\nFUNCTION: #{func_name}"
+ #puts "ARGUMENTS: #{arguments.inspect} #{node.to_s}"
+ args = arguments.collect { |arg| Predicate( arg, node ) }
+ #puts "FUNCTION: #{func_name}( #{args.collect{|n|n.to_s}.inspect} )"
+ result = Functions.send( func_name, *args )
+ #puts "RESULTS: #{result.inspect}"
+ return result
- acc = []
- p = preceding_node_of( node )
- #puts "P = #{p.inspect}"
- while p
- if ancestors.include? p
- ancestors.delete(p)
- else
- acc << p
- end
- p = preceding_node_of( p )
- #puts "P = #{p.inspect}"
- end
- acc
- end
+ else
+ return match( predicate, [ node ] )
- def preceding_node_of( node )
- #puts "NODE: #{node.inspect}"
- #puts "PREVIOUS NODE: #{node.previous_sibling_node.inspect}"
- #puts "PARENT NODE: #{node.parent}"
- psn = node.previous_sibling_node
- if psn.nil?
- if node.parent.nil? or node.parent.class == Document
- return nil
- end
- return node.parent
- #psn = preceding_node_of( node.parent )
- end
- while psn and psn.kind_of? Element and psn.children.size > 0
- psn = psn.children[-1]
end
- psn
end
+ # Builds a nodeset of all of the following nodes of the supplied node,
+ # in document order
def following( node )
- #puts "IN PRECEDING"
- acc = []
- p = next_sibling_node( node )
- #puts "P = #{p.inspect}"
- while p
- acc << p
- p = following_node_of( p )
- #puts "P = #{p.inspect}"
- end
- acc
+ all_siblings = node.parent.children
+ current_index = all_siblings.index( node )
+ following_siblings = all_siblings[ current_index+1 .. -1 ]
+ following = []
+ recurse( following_siblings ) { |node| following << node }
+ following.shift
+ #puts "following is returning #{puta following}"
+ following
end
- def following_node_of( node )
- #puts "NODE: #{node.inspect}"
- #puts "PREVIOUS NODE: #{node.previous_sibling_node.inspect}"
- #puts "PARENT NODE: #{node.parent}"
- if node.kind_of? Element and node.children.size > 0
- return node.children[0]
- end
- return next_sibling_node(node)
- end
-
- def next_sibling_node(node)
- psn = node.next_sibling_node
- while psn.nil?
- if node.parent.nil? or node.parent.class == Document
- return nil
- end
- node = node.parent
- psn = node.next_sibling_node
- #puts "psn = #{psn.inspect}"
- end
- return psn
- end
+ # Builds a nodeset of all of the preceding nodes of the supplied node,
+ # in reverse document order
+ def preceding( node )
+ all_siblings = node.parent.children
+ current_index = all_siblings.index( node )
+ preceding_siblings = all_siblings[ 0 .. current_index-1 ]
- def norm b
- case b
- when true, false
- return b
- when 'true', 'false'
- return Functions::boolean( b )
- when /^\d+(\.\d+)?$/
- return Functions::number( b )
- else
- return Functions::string( b )
- end
+ preceding = []
+ recurse( preceding_siblings ) { |node| preceding.unshift( node ) }
+ preceding
end
def equality_relational_compare( set1, op, set2 )
- #puts "EQ_REL_COMP(#{set1.inspect} #{op.inspect} #{set2.inspect})"
+ #puts "#"*80
if set1.kind_of? Array and set2.kind_of? Array
- #puts "#{set1.size} & #{set2.size}"
+ #puts "#{set1.size} & #{set2.size}"
if set1.size == 1 and set2.size == 1
set1 = set1[0]
set2 = set2[0]
elsif set1.size == 0 or set2.size == 0
nd = set1.size==0 ? set2 : set1
- rv = nd.collect { |il| compare( il, op, nil ) }
- #puts "RV = #{rv.inspect}"
- return rv
+ nd.each { |il| return true if compare( il, op, nil ) }
else
- res = []
- enum = SyncEnumerator.new( set1, set2 ).each { |i1, i2|
- #puts "i1 = #{i1.inspect} (#{i1.class.name})"
- #puts "i2 = #{i2.inspect} (#{i2.class.name})"
- i1 = norm( i1 )
- i2 = norm( i2 )
- res << compare( i1, op, i2 )
- }
- return res
+ set1.each do |i1|
+ i1 = i1.to_s
+ set2.each do |i2|
+ i2 = i2.to_s
+ return true if compare( i1, op, i2 )
+ end
+ end
+ return false
end
end
- #puts "EQ_REL_COMP: #{set1.inspect} (#{set1.class.name}), #{op}, #{set2.inspect} (#{set2.class.name})"
+ #puts "EQ_REL_COMP: #{set1.class.name} #{set1.inspect}, #{op}, #{set2.class.name} #{set2.inspect}"
#puts "COMPARING VALUES"
# If one is nodeset and other is number, compare number to each item
# in nodeset s.t. number op number(string(item))
@@ -647,28 +459,40 @@ module REXML
# If one is nodeset and other is boolean, compare boolean to each item
# in nodeset s.t. boolean op boolean(item)
if set1.kind_of? Array or set2.kind_of? Array
- #puts "ISA ARRAY"
+ #puts "ISA ARRAY"
if set1.kind_of? Array
a = set1
- b = set2
+ b = set2.to_s
else
a = set2
- b = set1
+ b = set1.to_s
end
case b
- when true, false
- return a.collect {|v| compare( Functions::boolean(v), op, b ) }
- when Numeric
- return a.collect {|v| compare( Functions::number(v), op, b )}
+ when 'true', 'false'
+ b = Functions::boolean( b )
+ for v in a
+ v = Functions::boolean(v)
+ return true if compare( v, op, b )
+ end
when /^\d+(\.\d+)?$/
b = Functions::number( b )
#puts "B = #{b.inspect}"
- return a.collect {|v| compare( Functions::number(v), op, b )}
+ for v in a
+ #puts "v = #{v.inspect}"
+ v = Functions::number(v)
+ #puts "v = #{v.inspect}"
+ #puts compare(v,op,b)
+ return true if compare( v, op, b )
+ end
else
- #puts "Functions::string( #{b}(#{b.class.name}) ) = #{Functions::string(b)}"
+ #puts "Functions::string( #{b}(#{b.class.name}) ) = #{Functions::string(b)}"
b = Functions::string( b )
- return a.collect { |v| compare( Functions::string(v), op, b ) }
+ for v in a
+ #puts "v = #{v.class.name} #{v.inspect}"
+ v = Functions::string(v)
+ return true if compare( v, op, b )
+ end
end
else
# If neither is nodeset,
@@ -708,7 +532,7 @@ module REXML
end
def compare a, op, b
- #puts "COMPARE #{a.inspect}(#{a.class.name}) #{op} #{b.inspect}(#{b.class.name})"
+ #puts "COMPARE #{a.to_s}(#{a.class.name}) #{op} #{b.to_s}(#{a.class.name})"
case op
when :eq
a == b
diff --git a/lib/rinda/rinda.rb b/lib/rinda/rinda.rb
index 6c59e68654..50fb84696a 100644
--- a/lib/rinda/rinda.rb
+++ b/lib/rinda/rinda.rb
@@ -1,150 +1,96 @@
-require 'drb/drb'
-require 'thread'
-
-##
-# A module to implement the Linda distributed computing paradigm in Ruby.
#
-# Rinda is part of DRb (dRuby).
+# rinda.rb: A Ruby implementation of the Linda distributed computing paradigm.
#
-# == Example(s)
+# <i>Introduction to Linda/rinda?</i>
#
-# See the sample/drb/ directory in the Ruby distribution, from 1.8.2 onwards.
+# <i>Why is this library separate from <tt>drb</tt>?</i>
#
-#--
-# TODO
-# == Introduction to Linda/rinda?
+# <i>Example(s)</i>
+#
+# (See the samples directory in the Ruby distribution, from 1.8.2 onwards.)
#
-# == Why is this library separate from DRb?
-
-module Rinda
- ##
- # Rinda error base class
+require 'drb/drb'
+require 'thread'
+#
+# A module to implement the Linda programming paradigm in Ruby.
+# This is part of +drb+ (dRuby).
+#
+module Rinda
class RindaError < RuntimeError; end
-
- ##
- # Raised when a hash-based tuple has an invalid key.
-
class InvalidHashTupleKey < RindaError; end
-
- ##
- # Raised when trying to use a canceled tuple.
-
class RequestCanceledError < ThreadError; end
-
- ##
- # Raised when trying to use an expired tuple.
-
class RequestExpiredError < ThreadError; end
- ##
+ #
# A tuple is the elementary object in Rinda programming.
# Tuples may be matched against templates if the tuple and
# the template are the same size.
-
+ #
class Tuple
-
- ##
- # Creates a new Tuple from +ary_or_hash+ which must be an Array or Hash.
-
+ # Initialize a tuple with an Array or a Hash.
def initialize(ary_or_hash)
- if hash?(ary_or_hash)
- init_with_hash(ary_or_hash)
+ if Hash === ary_or_hash
+ init_with_hash(ary_or_hash)
else
- init_with_ary(ary_or_hash)
+ init_with_ary(ary_or_hash)
end
end
- ##
# The number of elements in the tuple.
-
def size
@tuple.size
end
- ##
# Accessor method for elements of the tuple.
-
def [](k)
@tuple[k]
end
- ##
- # Fetches item +k+ from the tuple.
-
def fetch(k)
@tuple.fetch(k)
end
- ##
# Iterate through the tuple, yielding the index or key, and the
# value, thus ensuring arrays are iterated similarly to hashes.
-
def each # FIXME
if Hash === @tuple
- @tuple.each { |k, v| yield(k, v) }
+ @tuple.each { |k, v| yield(k, v) }
else
- @tuple.each_with_index { |v, k| yield(k, v) }
+ @tuple.each_with_index { |v, k| yield(k, v) }
end
end
- ##
- # Return the tuple itself
+ # Return the tuple itself -- i.e the Array or hash.
def value
@tuple
end
private
-
- def hash?(ary_or_hash)
- ary_or_hash.respond_to?(:keys)
- end
-
- ##
- # Munges +ary+ into a valid Tuple.
-
def init_with_ary(ary)
@tuple = Array.new(ary.size)
@tuple.size.times do |i|
- @tuple[i] = ary[i]
+ @tuple[i] = ary[i]
end
end
- ##
- # Ensures +hash+ is a valid Tuple.
-
def init_with_hash(hash)
@tuple = Hash.new
hash.each do |k, v|
raise InvalidHashTupleKey unless String === k
- @tuple[k] = v
+ @tuple[k] = v
end
end
-
end
- ##
+ #
# Templates are used to match tuples in Rinda.
-
+ #
class Template < Tuple
-
- ##
- # Matches this template against +tuple+. The +tuple+ must be the same
- # size as the template. An element with a +nil+ value in a template acts
- # as a wildcard, matching any value in the corresponding position in the
- # tuple. Elements of the template match the +tuple+ if the are #== or
- # #===.
- #
- # Template.new([:foo, 5]).match Tuple.new([:foo, 5]) # => true
- # Template.new([:foo, nil]).match Tuple.new([:foo, 5]) # => true
- # Template.new([String]).match Tuple.new(['hello']) # => true
- #
- # Template.new([:foo]).match Tuple.new([:foo, 5]) # => false
- # Template.new([:foo, 6]).match Tuple.new([:foo, 5]) # => false
- # Template.new([:foo, nil]).match Tuple.new([:foo]) # => false
- # Template.new([:foo, 6]).match Tuple.new([:foo]) # => false
-
+ # Perform the matching of a tuple against a template. An
+ # element with a +nil+ value in a template acts as a wildcard,
+ # matching any value in the corresponding position in the tuple.
def match(tuple)
return false unless tuple.respond_to?(:size)
return false unless tuple.respond_to?(:fetch)
@@ -155,129 +101,84 @@ module Rinda
rescue
return false
end
- next if v.nil?
+ next if v.nil?
next if v == it
next if v === it
- return false
+ return false
end
return true
end
- ##
# Alias for #match.
-
def ===(tuple)
match(tuple)
end
-
end
- ##
+ #
# <i>Documentation?</i>
-
+ #
class DRbObjectTemplate
-
- ##
- # Creates a new DRbObjectTemplate that will match against +uri+ and +ref+.
-
def initialize(uri=nil, ref=nil)
@drb_uri = uri
@drb_ref = ref
end
- ##
- # This DRbObjectTemplate matches +ro+ if the remote object's drburi and
- # drbref are the same. +nil+ is used as a wildcard.
-
def ===(ro)
return true if super(ro)
unless @drb_uri.nil?
- return false unless (@drb_uri === ro.__drburi rescue false)
+ return false unless (@drb_uri === ro.__drburi rescue false)
end
unless @drb_ref.nil?
- return false unless (@drb_ref === ro.__drbref rescue false)
+ return false unless (@drb_ref === ro.__drbref rescue false)
end
true
end
-
end
- ##
+ #
# TupleSpaceProxy allows a remote Tuplespace to appear as local.
-
+ #
class TupleSpaceProxy
-
- ##
- # Creates a new TupleSpaceProxy to wrap +ts+.
-
def initialize(ts)
@ts = ts
end
- ##
- # Adds +tuple+ to the proxied TupleSpace. See TupleSpace#write.
-
def write(tuple, sec=nil)
@ts.write(tuple, sec)
end
- ##
- # Takes +tuple+ from the proxied TupleSpace. See TupleSpace#take.
-
def take(tuple, sec=nil, &block)
port = []
@ts.move(DRbObject.new(port), tuple, sec, &block)
port[0]
end
- ##
- # Reads +tuple+ from the proxied TupleSpace. See TupleSpace#read.
-
def read(tuple, sec=nil, &block)
@ts.read(tuple, sec, &block)
end
- ##
- # Reads all tuples matching +tuple+ from the proxied TupleSpace. See
- # TupleSpace#read_all.
-
def read_all(tuple)
@ts.read_all(tuple)
end
- ##
- # Registers for notifications of event +ev+ on the proxied TupleSpace.
- # See TupleSpace#notify
-
def notify(ev, tuple, sec=nil)
@ts.notify(ev, tuple, sec)
end
-
end
- ##
- # An SimpleRenewer allows a TupleSpace to check if a TupleEntry is still
- # alive.
-
+ #
+ # <i>Documentation?</i>
+ #
class SimpleRenewer
-
include DRbUndumped
-
- ##
- # Creates a new SimpleRenewer that keeps an object alive for another +sec+
- # seconds.
-
def initialize(sec=180)
@sec = sec
end
- ##
- # Called by the TupleSpace to check if the object is still alive.
-
def renew
@sec
end
end
-
end
diff --git a/lib/rinda/ring.rb b/lib/rinda/ring.rb
index 5b2d412451..bc952032e9 100644
--- a/lib/rinda/ring.rb
+++ b/lib/rinda/ring.rb
@@ -6,29 +6,10 @@ require 'rinda/rinda'
require 'thread'
module Rinda
-
- ##
- # The default port Ring discovery will use.
-
Ring_PORT = 7647
-
- ##
- # A RingServer allows a Rinda::TupleSpace to be located via UDP broadcasts.
- # Service location uses the following steps:
- #
- # 1. A RingServer begins listening on the broadcast UDP address.
- # 2. A RingFinger sends a UDP packet containing the DRb URI where it will
- # listen for a reply.
- # 3. The RingServer recieves the UDP packet and connects back to the
- # provided DRb URI with the DRb service.
-
class RingServer
-
include DRbUndumped
- ##
- # Advertises +ts+ on the UDP broadcast address at +port+.
-
def initialize(ts, port=Ring_PORT)
@ts = ts
@soc = UDPSocket.open
@@ -37,10 +18,6 @@ module Rinda
@r_service = reply_service
end
- ##
- # Creates a thread that picks up UDP packets and passes them to do_write
- # for decoding.
-
def write_service
Thread.new do
loop do
@@ -50,10 +27,6 @@ module Rinda
end
end
- ##
- # Extracts the response URI from +msg+ and adds it to TupleSpace where it
- # will be picked up by +reply_service+ for notification.
-
def do_write(msg)
Thread.new do
begin
@@ -64,9 +37,6 @@ module Rinda
end
end
- ##
- # Creates a thread that notifies waiting clients from the TupleSpace.
-
def reply_service
Thread.new do
loop do
@@ -75,34 +45,15 @@ module Rinda
end
end
- ##
- # Pulls lookup tuples out of the TupleSpace and sends their DRb object the
- # address of the local TupleSpace.
-
def do_reply
tuple = @ts.take([:lookup_ring, DRbObject])
Thread.new { tuple[1].call(@ts) rescue nil}
rescue
end
-
end
- ##
- # RingFinger is used by RingServer clients to discover the RingServer's
- # TupleSpace. Typically, all a client needs to do is call
- # RingFinger.primary to retrieve the remote TupleSpace, which it can then
- # begin using.
-
class RingFinger
-
- @@broadcast_list = ['<broadcast>', 'localhost']
-
@@finger = nil
-
- ##
- # Creates a singleton RingFinger and looks for a RingServer. Returns the
- # created RingFinger.
-
def self.finger
unless @@finger
@@finger = self.new
@@ -111,56 +62,27 @@ module Rinda
@@finger
end
- ##
- # Returns the first advertised TupleSpace.
-
def self.primary
finger.primary
end
- ##
- # Contains all discoverd TupleSpaces except for the primary.
-
def self.to_a
finger.to_a
end
- ##
- # The list of addresses where RingFinger will send query packets.
-
- attr_accessor :broadcast_list
-
- ##
- # The port that RingFinger will send query packets to.
-
- attr_accessor :port
-
- ##
- # Contain the first advertised TupleSpace after lookup_ring_any is called.
-
- attr_accessor :primary
-
- ##
- # Creates a new RingFinger that will look for RingServers at +port+ on
- # the addresses in +broadcast_list+.
-
+ @@broadcast_list = ['<broadcast>', 'localhost']
def initialize(broadcast_list=@@broadcast_list, port=Ring_PORT)
@broadcast_list = broadcast_list || ['localhost']
@port = port
@primary = nil
@rings = []
end
-
- ##
- # Contains all discovered TupleSpaces except for the primary.
+ attr_accessor :broadcast_list, :port, :primary
def to_a
@rings
end
- ##
- # Iterates over all discovered TupleSpaces starting with the primary.
-
def each
lookup_ring_any unless @primary
return unless @primary
@@ -168,11 +90,6 @@ module Rinda
@rings.each { |x| yield(x) }
end
- ##
- # Looks up RingServers waiting +timeout+ seconds. RingServers will be
- # given +block+ as a callback, which will be called with the remote
- # TupleSpace.
-
def lookup_ring(timeout=5, &block)
return lookup_ring_any(timeout) unless block_given?
@@ -191,10 +108,6 @@ module Rinda
sleep(timeout)
end
- ##
- # Returns the first found remote TupleSpace. Any further recovered
- # TupleSpaces can be found by calling +to_a+.
-
def lookup_ring_any(timeout=5)
queue = Queue.new
@@ -212,38 +125,19 @@ module Rinda
raise('RingNotFound') if @primary.nil?
@primary
end
-
end
- ##
- # RingProvider uses a RingServer advertised TupleSpace as a name service.
- # TupleSpace clients can register themselves with the remote TupleSpace and
- # look up other provided services via the remote TupleSpace.
- #
- # Services are registered with a tuple of the format [:name, klass,
- # DRbObject, description].
-
class RingProvider
-
- ##
- # Creates a RingProvider that will provide a +klass+ service running on
- # +front+, with a +description+. +renewer+ is optional.
-
def initialize(klass, front, desc, renewer = nil)
@tuple = [:name, klass, front, desc]
@renewer = renewer || Rinda::SimpleRenewer.new
end
- ##
- # Advertises this service on the primary remote TupleSpace.
-
def provide
ts = Rinda::RingFinger.primary
ts.write(@tuple, @renewer)
end
-
end
-
end
if __FILE__ == $0
@@ -268,4 +162,3 @@ if __FILE__ == $0
end
end
end
-
diff --git a/lib/rinda/tuplespace.rb b/lib/rinda/tuplespace.rb
index 73e79bb401..6986e49b3e 100644
--- a/lib/rinda/tuplespace.rb
+++ b/lib/rinda/tuplespace.rb
@@ -1,66 +1,47 @@
+#
+# = tuplespace: <i>???</i>
+#
+# <i>Overview of rinda/tuplespace.rb</i>
+#
+# <i>Example(s)</i>
+#
+
require 'monitor'
require 'thread'
require 'drb/drb'
require 'rinda/rinda'
module Rinda
-
- ##
+ #
# A TupleEntry is a Tuple (i.e. a possible entry in some Tuplespace)
# together with expiry and cancellation data.
-
+ #
class TupleEntry
-
include DRbUndumped
- attr_accessor :expires
-
- ##
- # Creates a TupleEntry based on +ary+ with an optional renewer or expiry
- # time +sec+.
- #
- # A renewer must implement the +renew+ method which returns a Numeric,
- # nil, or true to indicate when the tuple has expired.
-
def initialize(ary, sec=nil)
@cancel = false
- @expires = nil
- @tuple = make_tuple(ary)
+ @ary = make_tuple(ary)
@renewer = nil
renew(sec)
end
-
- ##
- # Marks this TupleEntry as canceled.
+ attr_accessor :expires
def cancel
@cancel = true
end
- ##
- # A TupleEntry is dead when it is canceled or expired.
-
def alive?
!canceled? && !expired?
end
- ##
# Return the object which makes up the tuple itself: the Array
# or Hash.
-
- def value; @tuple.value; end
-
- ##
- # Returns the canceled status.
+ def value; @ary.value; end
def canceled?; @cancel; end
- ##
# Has this tuple expired? (true/false).
- #
- # A tuple has expired when its expiry timer based on the +sec+ argument to
- # #initialize runs out.
-
def expired?
return true unless @expires
return false if @expires > Time.now
@@ -70,8 +51,8 @@ module Rinda
return @expires < Time.now
end
- ##
- # Reset the expiry time according to +sec_or_renewer+.
+ # Reset the expiry data according to the supplied argument. If
+ # the argument is:
#
# +nil+:: it is set to expire in the far future.
# +false+:: it has expired.
@@ -79,115 +60,102 @@ module Rinda
#
# Otherwise the argument refers to some kind of renewer object
# which will reset its expiry time.
-
def renew(sec_or_renewer)
sec, @renewer = get_renewer(sec_or_renewer)
@expires = make_expires(sec)
end
-
- ##
- # Returns an expiry Time based on +sec+ which can be one of:
- # Numeric:: +sec+ seconds into the future
- # +true+:: the expiry time is the start of 1970 (i.e. expired)
- # +nil+:: it is Tue Jan 19 03:14:07 GMT Standard Time 2038 (i.e. when
- # UNIX clocks will die)
-
+
+ # Create an expiry time. Called with:
+ #
+ # +true+:: the expiry time is the start of 1970 (i.e. expired).
+ # +nil+:: it is Tue Jan 19 03:14:07 GMT Standard Time 2038 (i.e. when
+ # UNIX clocks will die)
+ #
+ # otherwise it is +sec+ seconds into the
+ # future.
def make_expires(sec=nil)
case sec
when Numeric
- Time.now + sec
+ Time.now + sec
when true
- Time.at(1)
+ Time.at(1)
when nil
- Time.at(2**31-1)
+ Time.at(2**31-1)
end
end
- ##
- # Retrieves +key+ from the tuple.
-
+ # Accessor method for the tuple.
def [](key)
- @tuple[key]
+ @ary[key]
end
- ##
- # Fetches +key+ from the tuple.
-
def fetch(key)
- @tuple.fetch(key)
+ @ary.fetch(key)
end
- ##
# The size of the tuple.
-
def size
- @tuple.size
+ @ary.size
end
-
- ##
- # Creates a Rinda::Tuple for +ary+.
-
+
+ # Create a new tuple from the supplied object (array-like).
def make_tuple(ary)
Rinda::Tuple.new(ary)
end
-
+
private
-
- ##
- # Returns a valid argument to make_expires and the renewer or nil.
- #
- # Given +true+, +nil+, or Numeric, returns that value and +nil+ (no actual
- # renewer). Otherwise it returns an expiry value from calling +it.renew+
- # and the renewer.
-
+ # Given +true+, +nil+, or +Numeric+, returns that (suitable input to
+ # make_expires) and +nil+ (no actual +renewer+), else it return the
+ # time data from the supplied +renewer+.
def get_renewer(it)
case it
when Numeric, true, nil
- return it, nil
+ return it, nil
else
- begin
- return it.renew, it
- rescue Exception
- return it, nil
- end
+ begin
+ return it.renew, it
+ rescue Exception
+ return it, nil
+ end
end
end
-
end
- ##
- # A TemplateEntry is a Template together with expiry and cancellation data.
-
+ #
+ # The same as a TupleEntry but with methods to do matching.
+ #
class TemplateEntry < TupleEntry
- ##
- # Matches this TemplateEntry against +tuple+. See Template#match for
- # details on how a Template matches a Tuple.
+ def initialize(ary, expires=nil)
+ super(ary, expires)
+ @template = Rinda::Template.new(ary)
+ end
def match(tuple)
- @tuple.match(tuple)
+ @template.match(tuple)
end
-
- alias === match
- def make_tuple(ary) # :nodoc:
- Rinda::Template.new(ary)
+ # An alias for #match.
+ def ===(tuple)
+ match(tuple)
end
+ # Create a new Template from the supplied object.
+ def make_tuple(ary)
+ Rinda::Template.new(ary)
+ end
end
- ##
+ #
# <i>Documentation?</i>
-
+ #
class WaitTemplateEntry < TemplateEntry
-
- attr_reader :found
-
def initialize(place, ary, expires=nil)
super(ary, expires)
@place = place
@cond = place.new_cond
@found = nil
end
+ attr_reader :found
def cancel
super
@@ -197,79 +165,42 @@ module Rinda
def wait
@cond.wait
end
-
+
def read(tuple)
@found = tuple
signal
end
-
+
def signal
@place.synchronize do
- @cond.signal
+ @cond.signal
end
end
-
end
- ##
- # A NotifyTemplateEntry is returned by TupleSpace#notify and is notified of
- # TupleSpace changes. You may receive either your subscribed event or the
- # 'close' event when iterating over notifications.
- #
- # See TupleSpace#notify_event for valid notification types.
#
- # == Example
- #
- # ts = Rinda::TupleSpace.new
- # observer = ts.notify 'write', [nil]
- #
- # Thread.start do
- # observer.each { |t| p t }
- # end
- #
- # 3.times { |i| ts.write [i] }
- #
- # Outputs:
+ # <i>Documentation?</i>
#
- # ['write', [0]]
- # ['write', [1]]
- # ['write', [2]]
-
class NotifyTemplateEntry < TemplateEntry
-
- ##
- # Creates a new NotifyTemplateEntry that watches +place+ for +event+s that
- # match +tuple+.
-
def initialize(place, event, tuple, expires=nil)
ary = [event, Rinda::Template.new(tuple)]
super(ary, expires)
@queue = Queue.new
@done = false
end
-
- ##
- # Called by TupleSpace to notify this NotifyTemplateEntry of a new event.
-
+
def notify(ev)
@queue.push(ev)
end
- ##
- # Retrieves a notification. Raises RequestExpiredError when this
- # NotifyTemplateEntry expires.
-
def pop
raise RequestExpiredError if @done
it = @queue.pop
@done = true if it[0] == 'close'
return it
end
-
- ##
- # Yields event/tuple pairs until this NotifyTemplateEntry expires.
-
- def each # :yields: event, tuple
+
+ def each
while !@done
it = pop
yield(it)
@@ -278,117 +209,78 @@ module Rinda
ensure
cancel
end
-
end
- ##
+ #
# TupleBag is an unordered collection of tuples. It is the basis
# of Tuplespace.
-
+ #
class TupleBag
-
- def initialize # :nodoc:
+ def initialize
@hash = {}
end
-
- ##
- # +true+ if the TupleBag to see if it has any expired entries.
-
- def has_expires?
- @hash.each do |k, v|
- v.each do |tuple|
- return true if tuple.expires
- end
- end
- false
- end
-
- ##
- # Add +ary+ to the TupleBag.
-
+
+ # Add the object to the TupleBag.
def push(ary)
size = ary.size
@hash[size] ||= []
@hash[size].push(ary)
end
-
- ##
- # Removes +ary+ from the TupleBag.
-
+
+ # Remove the object from the TupleBag.
def delete(ary)
size = ary.size
@hash.fetch(size, []).delete(ary)
end
- ##
- # Finds all live tuples that match +template+.
-
+ # Finds all tuples that match the template and are alive.
def find_all(template)
@hash.fetch(template.size, []).find_all do |tuple|
- tuple.alive? && template.match(tuple)
+ tuple.alive? && template.match(tuple)
end
end
- ##
- # Finds a live tuple that matches +template+.
-
+ # Finds a template that matches and is alive.
def find(template)
@hash.fetch(template.size, []).find do |tuple|
- tuple.alive? && template.match(tuple)
+ tuple.alive? && template.match(tuple)
end
end
- ##
- # Finds all tuples in the TupleBag which when treated as templates, match
- # +tuple+ and are alive.
-
+ # Finds all tuples in the TupleBag which when treated as
+ # templates, match the supplied tuple and are alive.
def find_all_template(tuple)
@hash.fetch(tuple.size, []).find_all do |template|
- template.alive? && template.match(tuple)
+ template.alive? && template.match(tuple)
end
end
- ##
- # Delete tuples which dead tuples from the TupleBag, returning the deleted
- # tuples.
-
+ # Delete tuples which are not alive from the TupleBag. Returns
+ # the list of tuples so deleted.
def delete_unless_alive
deleted = []
@hash.keys.each do |size|
- ary = []
- @hash[size].each do |tuple|
- if tuple.alive?
- ary.push(tuple)
- else
- deleted.push(tuple)
- end
- end
- @hash[size] = ary
+ ary = []
+ @hash[size].each do |tuple|
+ if tuple.alive?
+ ary.push(tuple)
+ else
+ deleted.push(tuple)
+ end
+ end
+ @hash[size] = ary
end
deleted
end
-
end
- ##
+ #
# The Tuplespace manages access to the tuples it contains,
# ensuring mutual exclusion requirements are met.
#
- # The +sec+ option for the write, take, move, read and notify methods may
- # either be a number of seconds or a Renewer object.
-
class TupleSpace
-
include DRbUndumped
include MonitorMixin
-
- ##
- # Creates a new TupleSpace. +period+ is used to control how often to look
- # for dead tuples after modifications to the TupleSpace.
- #
- # If no dead tuples are found +period+ seconds after the last
- # modification, the TupleSpace will stop looking for dead tuples.
-
def initialize(period=60)
super()
@bag = TupleBag.new
@@ -396,194 +288,141 @@ module Rinda
@take_waiter = TupleBag.new
@notify_waiter = TupleBag.new
@period = period
- @keeper = nil
+ @keeper = keeper
end
- ##
- # Adds +tuple+
-
+ # Put a tuple into the tuplespace.
def write(tuple, sec=nil)
entry = TupleEntry.new(tuple, sec)
- start_keeper
synchronize do
- if entry.expired?
- @read_waiter.find_all_template(entry).each do |template|
- template.read(tuple)
- end
- notify_event('write', entry.value)
- notify_event('delete', entry.value)
- else
- @bag.push(entry)
- @read_waiter.find_all_template(entry).each do |template|
- template.read(tuple)
- end
- @take_waiter.find_all_template(entry).each do |template|
- template.signal
- end
- notify_event('write', entry.value)
- end
+ if entry.expired?
+ @read_waiter.find_all_template(entry).each do |template|
+ template.read(tuple)
+ end
+ notify_event('write', entry.value)
+ notify_event('delete', entry.value)
+ else
+ @bag.push(entry)
+ @read_waiter.find_all_template(entry).each do |template|
+ template.read(tuple)
+ end
+ @take_waiter.find_all_template(entry).each do |template|
+ template.signal
+ end
+ notify_event('write', entry.value)
+ end
end
entry
end
- ##
- # Removes +tuple+
-
+ # Remove an entry from the Tuplespace.
def take(tuple, sec=nil, &block)
move(nil, tuple, sec, &block)
end
- ##
- # Moves +tuple+ to +port+.
-
def move(port, tuple, sec=nil)
template = WaitTemplateEntry.new(self, tuple, sec)
yield(template) if block_given?
- start_keeper
synchronize do
- entry = @bag.find(template)
- if entry
- port.push(entry.value) if port
- @bag.delete(entry)
- notify_event('take', entry.value)
- return entry.value
- end
+ entry = @bag.find(template)
+ if entry
+ port.push(entry.value) if port
+ @bag.delete(entry)
+ notify_event('take', entry.value)
+ return entry.value
+ end
raise RequestExpiredError if template.expired?
- begin
- @take_waiter.push(template)
- while true
- raise RequestCanceledError if template.canceled?
- raise RequestExpiredError if template.expired?
- entry = @bag.find(template)
- if entry
- port.push(entry.value) if port
- @bag.delete(entry)
- notify_event('take', entry.value)
- return entry.value
- end
- template.wait
- end
- ensure
- @take_waiter.delete(template)
- end
+ begin
+ @take_waiter.push(template)
+ while true
+ raise RequestCanceledError if template.canceled?
+ raise RequestExpiredError if template.expired?
+ entry = @bag.find(template)
+ if entry
+ port.push(entry.value) if port
+ @bag.delete(entry)
+ notify_event('take', entry.value)
+ return entry.value
+ end
+ template.wait
+ end
+ ensure
+ @take_waiter.delete(template)
+ end
end
end
- ##
- # Reads +tuple+, but does not remove it.
-
def read(tuple, sec=nil)
template = WaitTemplateEntry.new(self, tuple, sec)
yield(template) if block_given?
- start_keeper
synchronize do
- entry = @bag.find(template)
- return entry.value if entry
+ entry = @bag.find(template)
+ return entry.value if entry
raise RequestExpiredError if template.expired?
- begin
- @read_waiter.push(template)
- template.wait
- raise RequestCanceledError if template.canceled?
- raise RequestExpiredError if template.expired?
- return template.found
- ensure
- @read_waiter.delete(template)
- end
+ begin
+ @read_waiter.push(template)
+ template.wait
+ raise RequestCanceledError if template.canceled?
+ raise RequestExpiredError if template.expired?
+ return template.found
+ ensure
+ @read_waiter.delete(template)
+ end
end
end
- ##
- # Returns all tuples matching +tuple+. Does not remove the found tuples.
-
def read_all(tuple)
template = WaitTemplateEntry.new(self, tuple, nil)
synchronize do
- entry = @bag.find_all(template)
- entry.collect do |e|
- e.value
- end
+ entry = @bag.find_all(template)
+ entry.collect do |e|
+ e.value
+ end
end
end
- ##
- # Registers for notifications of +event+. Returns a NotifyTemplateEntry.
- # See NotifyTemplateEntry for examples of how to listen for notifications.
- #
- # +event+ can be:
- # 'write':: A tuple was added
- # 'take':: A tuple was taken or moved
- # 'delete':: A tuple was lost after being overwritten or expiring
- #
- # The TupleSpace will also notify you of the 'close' event when the
- # NotifyTemplateEntry has expired.
-
def notify(event, tuple, sec=nil)
template = NotifyTemplateEntry.new(self, event, tuple, sec)
synchronize do
- @notify_waiter.push(template)
+ @notify_waiter.push(template)
end
template
end
-
+
private
-
- ##
- # Removes dead tuples.
-
def keep_clean
synchronize do
- @read_waiter.delete_unless_alive.each do |e|
- e.signal
- end
- @take_waiter.delete_unless_alive.each do |e|
- e.signal
- end
- @notify_waiter.delete_unless_alive.each do |e|
- e.notify(['close'])
- end
- @bag.delete_unless_alive.each do |e|
- notify_event('delete', e.value)
- end
+ @read_waiter.delete_unless_alive.each do |e|
+ e.signal
+ end
+ @take_waiter.delete_unless_alive.each do |e|
+ e.signal
+ end
+ @notify_waiter.delete_unless_alive.each do |e|
+ e.notify(['close'])
+ end
+ @bag.delete_unless_alive.each do |e|
+ notify_event('delete', e.value)
+ end
end
end
-
- ##
- # Notifies all registered listeners for +event+ of a status change of
- # +tuple+.
-
+
def notify_event(event, tuple)
ev = [event, tuple]
@notify_waiter.find_all_template(ev).each do |template|
- template.notify(ev)
+ template.notify(ev)
end
end
- ##
- # Creates a thread that scans the tuplespace for expired tuples.
-
- def start_keeper
- return if @keeper && @keeper.alive?
- @keeper = Thread.new do
- while need_keeper?
- keep_clean
- sleep(@period)
- end
+ def keeper
+ Thread.new do
+ loop do
+ sleep(@period)
+ keep_clean
+ end
end
end
-
- ##
- # Checks the tuplespace to see if it needs cleaning.
-
- def need_keeper?
- return true if @bag.has_expires?
- return true if @read_waiter.has_expires?
- return true if @take_waiter.has_expires?
- return true if @notify_waiter.has_expires?
- end
-
end
-
end
-
diff --git a/lib/rss.rb b/lib/rss.rb
deleted file mode 100644
index 495edb1b98..0000000000
--- a/lib/rss.rb
+++ /dev/null
@@ -1,16 +0,0 @@
-# Copyright (c) 2003-2005 Kouhei Sutou. You can redistribute it and/or
-# modify it under the same terms as Ruby.
-#
-# Author:: Kouhei Sutou <kou@cozmixng.org>
-# Tutorial:: http://www.cozmixng.org/~rwiki/?cmd=view;name=RSS+Parser%3A%3ATutorial.en
-
-require 'rss/1.0'
-require 'rss/2.0'
-require 'rss/content'
-require 'rss/dublincore'
-require 'rss/image'
-require 'rss/syndication'
-#require 'rss/taxonomy'
-require 'rss/trackback'
-
-require "rss/maker"
diff --git a/lib/rss/0.9.rb b/lib/rss/0.9.rb
index 3bbf67be05..c772e80870 100644
--- a/lib/rss/0.9.rb
+++ b/lib/rss/0.9.rb
@@ -25,8 +25,8 @@ module RSS
install_model(tag, occurs)
end
- %w(channel).each do |name|
- install_have_child_element(name)
+ %w(channel).each do |x|
+ install_have_child_element(x)
end
attr_accessor :rss_version, :version, :encoding, :standalone
@@ -59,15 +59,18 @@ module RSS
end
end
- def to_s(need_convert=true, indent=calc_indent)
- rv = tag(indent, ns_declarations) do |next_indent|
- [
- channel_element(false, next_indent),
- other_element(false, next_indent),
- ]
- end
- rv = convert(rv) if need_convert
- rv
+ def to_s(convert=true, indent=calc_indent)
+ next_indent = indent + INDENT
+ rv = <<-EOR
+#{xmldecl}
+#{xml_stylesheet_pi}
+#{indent}<rss version="#{@rss_version}"#{ns_declaration(next_indent)}>
+#{channel_element(false, next_indent)}
+#{other_element(false, next_indent)}
+#{indent}</rss>
+EOR
+ rv = @converter.convert(rv) if convert and @converter
+ remove_empty_newline(rv)
end
private
@@ -78,14 +81,12 @@ module RSS
def _tags
[
[nil, 'channel'],
- ].delete_if do |uri, name|
- send(name).nil?
- end
+ ].delete_if {|x| send(x[1]).nil?}
end
def _attrs
[
- ["version", true, "rss_version"],
+ ["version", true],
]
end
@@ -103,79 +104,77 @@ module RSS
["webMaster", "?"],
["rating", "?"],
["docs", "?"],
- ].each do |name, occurs|
- install_text_element(name)
- install_model(name, occurs)
+ ["skipDays", "?"],
+ ["skipHours", "?"],
+ ].each do |x, occurs|
+ install_text_element(x)
+ install_model(x, occurs)
end
[
["pubDate", "?"],
["lastBuildDate", "?"],
- ].each do |name, occurs|
- install_date_element(name, 'rfc822')
- install_model(name, occurs)
+ ].each do |x, occurs|
+ install_date_element(x, 'rfc822')
+ install_model(x, occurs)
end
- alias date pubDate
- alias date= pubDate=
[
- ["skipDays", "?"],
- ["skipHours", "?"],
["image", nil],
["textInput", "?"],
- ].each do |name, occurs|
- install_have_child_element(name)
- install_model(name, occurs)
+ ].each do |x, occurs|
+ install_have_child_element(x)
+ install_model(x, occurs)
end
[
["cloud", "?"]
- ].each do |name, occurs|
- install_have_attribute_element(name)
- install_model(name, occurs)
+ ].each do |x, occurs|
+ install_have_attribute_element(x)
+ install_model(x, occurs)
end
[
["item", "*"]
- ].each do |name, occurs|
- install_have_children_element(name)
- install_model(name, occurs)
+ ].each do |x, occurs|
+ install_have_children_element(x)
+ install_model(x, occurs)
end
def initialize()
super()
end
- def to_s(need_convert=true, indent=calc_indent)
- rv = tag(indent) do |next_indent|
- [
- title_element(false, next_indent),
- link_element(false, next_indent),
- description_element(false, next_indent),
- language_element(false, next_indent),
- copyright_element(false, next_indent),
- managingEditor_element(false, next_indent),
- webMaster_element(false, next_indent),
- rating_element(false, next_indent),
- pubDate_element(false, next_indent),
- lastBuildDate_element(false, next_indent),
- docs_element(false, next_indent),
- cloud_element(false, next_indent),
- skipDays_element(false, next_indent),
- skipHours_element(false, next_indent),
- image_element(false, next_indent),
- item_elements(false, next_indent),
- textInput_element(false, next_indent),
- other_element(false, next_indent),
- ]
- end
- rv = convert(rv) if need_convert
+ def to_s(convert=true, indent=calc_indent)
+ next_indent = indent + INDENT
+ rv = <<-EOT
+#{indent}<channel>
+#{title_element(false, next_indent)}
+#{link_element(false, next_indent)}
+#{description_element(false, next_indent)}
+#{language_element(false, next_indent)}
+#{copyright_element(false, next_indent)}
+#{managingEditor_element(false, next_indent)}
+#{webMaster_element(false, next_indent)}
+#{rating_element(false, next_indent)}
+#{pubDate_element(false, next_indent)}
+#{lastBuildDate_element(false, next_indent)}
+#{docs_element(false, next_indent)}
+#{skipDays_element(false, next_indent)}
+#{skipHours_element(false, next_indent)}
+#{image_element(false, next_indent)}
+#{item_elements(false, next_indent)}
+#{textInput_element(false, next_indent)}
+#{other_element(false, next_indent)}
+#{indent}</channel>
+EOT
+ rv = @converter.convert(rv) if convert and @converter
rv
end
private
def children
- [@skipDays, @skipHours, @image, @textInput, @cloud, *@item]
+ [@image, @textInput, @cloud, *@item]
end
def _tags
@@ -194,8 +193,8 @@ module RSS
"image",
"textInput",
"cloud",
- ].delete_if do |name|
- send(name).nil?
+ ].delete_if do |x|
+ send(x).nil?
end.collect do |elem|
[nil, elem]
end
@@ -207,168 +206,46 @@ module RSS
rv
end
- def maker_target(maker)
- maker.channel
- end
-
- def setup_maker_elements(channel)
- super
- [
- [skipDays, "day"],
- [skipHours, "hour"],
- ].each do |skip, key|
- if skip
- skip.__send__("#{key}s").each do |val|
- target_skips = channel.__send__("skip#{key.capitalize}s")
- new_target = target_skips.__send__("new_#{key}")
- new_target.content = val.content
- end
- end
- end
- end
-
- def not_need_to_call_setup_maker_variables
- %w(image textInput)
- end
-
- class SkipDays < Element
- include RSS09
-
- [
- ["day", "*"]
- ].each do |name, occurs|
- install_have_children_element(name)
- install_model(name, occurs)
- end
-
- def to_s(need_convert=true, indent=calc_indent)
- rv = tag(indent) do |next_indent|
- [
- day_elements(false, next_indent)
- ]
- end
- rv = convert(rv) if need_convert
- rv
- end
-
- private
- def children
- @day
- end
-
- def _tags
- @day.compact.collect do
- [nil, "day"]
- end
- end
-
- class Day < Element
- include RSS09
-
- content_setup
-
- def initialize(content=nil)
- super()
- @content = content
- end
-
- end
-
- end
-
- class SkipHours < Element
- include RSS09
-
- [
- ["hour", "*"]
- ].each do |name, occurs|
- install_have_children_element(name)
- install_model(name, occurs)
- end
-
- def to_s(need_convert=true, indent=calc_indent)
- rv = tag(indent) do |next_indent|
- [
- hour_elements(false, next_indent)
- ]
- end
- rv = convert(rv) if need_convert
- rv
- end
-
- private
- def children
- @hour
- end
-
- def _tags
- @hour.compact.collect do
- [nil, "hour"]
- end
- end
-
- class Hour < Element
- include RSS09
-
- content_setup
-
- def initialize(content=nil)
- super()
- @content = content
- end
-
- remove_method :content=
- def content=(value)
- @content = value.to_i
- end
-
- end
-
- end
-
class Image < Element
include RSS09
- %w(url title link).each do |name|
- install_text_element(name)
- install_model(name, nil)
- end
- %w(width height description).each do |name|
- install_text_element(name)
- install_model(name, "?")
- end
-
- def to_s(need_convert=true, indent=calc_indent)
- rv = tag(indent) do |next_indent|
- [
- url_element(false, next_indent),
- title_element(false, next_indent),
- link_element(false, next_indent),
- width_element(false, next_indent),
- height_element(false, next_indent),
- description_element(false, next_indent),
- other_element(false, next_indent),
- ]
- end
- rv = convert(rv) if need_convert
- rv
+ %w(url title link).each do |x|
+ install_text_element(x)
+ install_model(x, nil)
+ end
+ %w(width height description).each do |x|
+ install_text_element(x)
+ install_model(x, "?")
+ end
+
+ def to_s(convert=true, indent=calc_indent)
+ next_indent = indent + INDENT
+ rv = <<-EOT
+#{indent}<image>
+#{url_element(false, next_indent)}
+#{title_element(false, next_indent)}
+#{link_element(false, next_indent)}
+#{width_element(false, next_indent)}
+#{height_element(false, next_indent)}
+#{description_element(false, next_indent)}
+#{other_element(false, next_indent)}
+#{indent}</image>
+EOT
+ rv = @converter.convert(rv) if convert and @converter
+ rv
end
private
def _tags
- %w(url title link width height description).delete_if do |name|
- send(name).nil?
+ %w(url title link width height description).delete_if do |x|
+ send(x).nil?
end.collect do |elem|
[nil, elem]
end
end
-
- def maker_target(maker)
- maker.image
- end
end
-
+
class Cloud < Element
include RSS09
@@ -392,10 +269,18 @@ module RSS
@protocol = protocol
end
- def to_s(need_convert=true, indent=calc_indent)
- rv = tag(indent)
- rv = convert(rv) if need_convert
- rv
+ def to_s(convert=true, indent=calc_indent)
+ next_indent = indent + INDENT
+ rv = <<-EOT
+#{indent}<cloud
+#{next_indent}domain="#{h @domain}"
+#{next_indent}port="#{h @port}"
+#{next_indent}path="#{h @path}"
+#{next_indent}registerProcedure="#{h @registerProcedure}"
+#{next_indent}protocol="#{h @protocol}"/>
+EOT
+ rv = @converter.convert(rv) if convert and @converter
+ rv
end
private
@@ -411,77 +296,56 @@ module RSS
include RSS09
- %w(title link description).each do |name|
- install_text_element(name)
+ %w(title link description).each do |x|
+ install_text_element(x)
end
- %w(source enclosure).each do |name|
- install_have_child_element(name)
+ %w(category source enclosure).each do |x|
+ install_have_child_element(x)
end
[
- %w(category categories),
- ].each do |name, plural_name|
- install_have_children_element(name, plural_name)
- end
-
- [
["title", '?'],
["link", '?'],
["description", '?'],
- ["category", '*'],
+ ["category", '?'],
["source", '?'],
["enclosure", '?'],
].each do |tag, occurs|
install_model(tag, occurs)
end
- def to_s(need_convert=true, indent=calc_indent)
- rv = tag(indent) do |next_indent|
- [
- title_element(false, next_indent),
- link_element(false, next_indent),
- description_element(false, next_indent),
- category_elements(false, next_indent),
- source_element(false, next_indent),
- enclosure_element(false, next_indent),
- other_element(false, next_indent),
- ]
- end
- rv = convert(rv) if need_convert
- rv
+ def to_s(convert=true, indent=calc_indent)
+ next_indent = indent + INDENT
+ rv = <<-EOT
+#{indent}<item>
+#{title_element(false, next_indent)}
+#{link_element(false, next_indent)}
+#{description_element(false, next_indent)}
+#{category_element(false, next_indent)}
+#{source_element(false, next_indent)}
+#{enclosure_element(false, next_indent)}
+#{other_element(false, next_indent)}
+#{indent}</item>
+EOT
+ rv = @converter.convert(rv) if convert and @converter
+ rv
end
private
def children
- [@source, @enclosure, *@category].compact
+ [@category, @source, @enclosure,].compact
end
def _tags
- rv = %w(title link description author comments
- source enclosure).delete_if do |name|
- send(name).nil?
- end.collect do |name|
- [nil, name]
+ %w(title link description author comments category
+ source enclosure).delete_if do |x|
+ send(x).nil?
+ end.collect do |x|
+ [nil, x]
end
-
- @category.each do
- rv << [nil, "category"]
- end
-
- rv
- end
-
- def maker_target(maker)
- maker.items.new_item
end
- def setup_maker_element(item)
- super
- @enclosure.setup_maker(item) if @enclosure
- @source.setup_maker(item) if @source
- end
-
class Source < Element
include RSS09
@@ -500,6 +364,17 @@ module RSS
@content = content
end
+ def to_s(convert=true, indent=calc_indent)
+ if @url
+ rv = %Q! <source url="#{@url}">!
+ rv << %Q!#{@content}</source>!
+ rv = @converter.convert(rv) if convert and @converter
+ rv
+ else
+ ''
+ end
+ end
+
private
def _tags
[]
@@ -511,15 +386,6 @@ module RSS
]
end
-
- def maker_target(item)
- item.source
- end
-
- def setup_maker_attributes(source)
- source.url = url
- source.content = content
- end
end
class Enclosure < Element
@@ -541,10 +407,15 @@ module RSS
@type = type
end
- def to_s(need_convert=true, indent=calc_indent)
- rv = tag(indent)
- rv = convert(rv) if need_convert
- rv
+ def to_s(convert=true, indent=calc_indent)
+ if @url and @length and @type
+ rv = %Q!<enclosure url="#{h @url}" !
+ rv << %Q!length="#{h @length}" type="#{h @type}"/>!
+ rv = @converter.convert(rv) if convert and @converter
+ rv
+ else
+ ''
+ end
end
private
@@ -556,15 +427,6 @@ module RSS
]
end
- def maker_target(item)
- item.enclosure
- end
-
- def setup_maker_attributes(enclosure)
- enclosure.url = url
- enclosure.length = length
- enclosure.type = type
- end
end
class Category < Element
@@ -572,7 +434,7 @@ module RSS
include RSS09
[
- ["domain", nil, false]
+ ["domain", nil, true]
].each do |name, uri, required|
install_get_attribute(name, uri, required)
end
@@ -585,69 +447,68 @@ module RSS
@content = content
end
+ def to_s(convert=true, indent=calc_indent)
+ if @domain
+ rv = %Q!<category domain="#{h @domain}">!
+ rv << %Q!#{h @content}</category>!
+ rv = @converter.convert(rv) if convert and @converter
+ rv
+ else
+ ''
+ end
+ end
+
private
def _attrs
[
- ["domain", false]
+ ["domain", true]
]
end
- def maker_target(item)
- item.new_category
- end
-
- def setup_maker_attributes(category)
- category.domain = domain
- category.content = content
- end
-
end
end
class TextInput < Element
-
+
include RSS09
- %w(title description name link).each do |name|
- install_text_element(name)
- install_model(name, nil)
+ %w(title description name link).each do |x|
+ install_text_element(x)
+ install_model(x, nil)
end
- def to_s(need_convert=true, indent=calc_indent)
- rv = tag(indent) do |next_indent|
- [
- title_element(false, next_indent),
- description_element(false, next_indent),
- name_element(false, next_indent),
- link_element(false, next_indent),
- other_element(false, next_indent),
- ]
- end
- rv = convert(rv) if need_convert
- rv
+ def to_s(convert=true, indent=calc_indent)
+ next_indent = indent + INDENT
+ rv = <<-EOT
+#{indent}<textInput>
+#{title_element(false, next_indent)}
+#{description_element(false, next_indent)}
+#{name_element(false, next_indent)}
+#{link_element(false, next_indent)}
+#{other_element(false, next_indent)}
+#{indent}</textInput>
+EOT
+ rv = @converter.convert(rv) if convert and @converter
+ rv
end
private
def _tags
- %w(title description name link).each do |name|
- send(name).nil?
+ %w(title description name link).each do |x|
+ send(x).nil?
end.collect do |elem|
[nil, elem]
end
end
-
- def maker_target(maker)
- maker.textinput
- end
end
end
end
- RSS09::ELEMENTS.each do |name|
- BaseListener.install_get_text_element(nil, name, "#{name}=")
+ RSS09::ELEMENTS.each do |x|
+ BaseListener.install_get_text_element(x, nil, "#{x}=")
end
module ListenerMixin
diff --git a/lib/rss/1.0.rb b/lib/rss/1.0.rb
index fb1629944b..563ed66426 100644
--- a/lib/rss/1.0.rb
+++ b/lib/rss/1.0.rb
@@ -18,6 +18,7 @@ module RSS
include RSS10
include RootElementMixin
+ include XMLStyleSheetMixin
class << self
@@ -44,8 +45,8 @@ module RSS
install_model(tag, occurs)
end
- %w(channel image textinput).each do |name|
- install_have_child_element(name)
+ %w(channel image textinput).each do |x|
+ install_have_child_element(x)
end
install_have_children_element("item")
@@ -56,22 +57,21 @@ module RSS
super('1.0', version, encoding, standalone)
end
- def full_name
- tag_name_with_prefix(PREFIX)
- end
-
- def to_s(need_convert=true, indent=calc_indent)
- rv = tag(indent, ns_declarations) do |next_indent|
- [
- channel_element(false, next_indent),
- image_element(false, next_indent),
- item_elements(false, next_indent),
- textinput_element(false, next_indent),
- other_element(false, next_indent),
- ]
- end
- rv = convert(rv) if need_convert
- rv
+ def to_s(convert=true, indent=calc_indent)
+ next_indent = indent + INDENT
+ rv = <<-EORDF
+#{xmldecl}
+#{xml_stylesheet_pi}
+#{indent}<#{PREFIX}:RDF#{ns_declaration(next_indent)}>
+#{channel_element(false, next_indent)}
+#{image_element(false, next_indent)}
+#{item_elements(false, next_indent)}
+#{textinput_element(false, next_indent)}
+#{other_element(false, next_indent)}
+#{indent}</#{PREFIX}:RDF>
+EORDF
+ rv = @converter.convert(rv) if convert and @converter
+ remove_empty_newline(rv)
end
private
@@ -87,8 +87,8 @@ module RSS
rv = [
[::RSS::URI, "channel"],
[::RSS::URI, "image"],
- ].delete_if {|uri, name| send(name).nil?}
- @item.each do |item|
+ ].delete_if {|x| send(x[1]).nil?}
+ @item.each do |x|
rv << [::RSS::URI, "item"]
end
rv << [::RSS::URI, "textinput"] if @textinput
@@ -118,20 +118,17 @@ module RSS
@li = li
end
- def to_s(need_convert=true, indent=calc_indent)
- tag(indent) do |next_indent|
- [
- li_elements(need_convert, next_indent),
- other_element(need_convert, next_indent),
- ]
- end
+ def to_s(convert=true, indent=calc_indent)
+ next_indent = indent + INDENT
+ <<-EOT
+#{indent}<#{PREFIX}:Seq>
+#{li_elements(convert, next_indent)}
+#{other_element(convert, next_indent)}
+#{indent}</#{PREFIX}:Seq>
+EOT
end
- def full_name
- tag_name_with_prefix(PREFIX)
- end
-
- private
+ private
def children
@li
end
@@ -142,7 +139,7 @@ module RSS
def _tags
rv = []
- @li.each do |li|
+ @li.each do |x|
rv << [URI, "li"]
end
rv
@@ -172,15 +169,15 @@ module RSS
super()
@resource = resource
end
-
- def full_name
- tag_name_with_prefix(PREFIX)
- end
- def to_s(need_convert=true, indent=calc_indent)
- rv = tag(indent)
- rv = convert(rv) if need_convert
- rv
+ def to_s(convert=true, indent=calc_indent)
+ if @resource
+ rv = %Q!#{indent}<#{PREFIX}:li resource="#{h @resource}" />\n!
+ rv = @converter.convert(rv) if convert and @converter
+ rv
+ else
+ ''
+ end
end
private
@@ -204,18 +201,18 @@ module RSS
end
- [
+ [
["about", URI, true]
].each do |name, uri, required|
install_get_attribute(name, uri, required)
end
- %w(title link description).each do |name|
- install_text_element(name)
+ %w(title link description).each do |x|
+ install_text_element(x)
end
- %w(image items textinput).each do |name|
- install_have_child_element(name)
+ %w(image items textinput).each do |x|
+ install_have_child_element(x)
end
[
@@ -234,20 +231,23 @@ module RSS
@about = about
end
- def to_s(need_convert=true, indent=calc_indent)
- rv = tag(indent) do |next_indent|
- [
- title_element(false, next_indent),
- link_element(false, next_indent),
- description_element(false, next_indent),
- image_element(false, next_indent),
- items_element(false, next_indent),
- textinput_element(false, next_indent),
- other_element(false, next_indent),
- ]
- end
- rv = convert(rv) if need_convert
- rv
+ def to_s(convert=true, indent=calc_indent)
+ next_indent = indent + INDENT
+ about = ''
+ about << %Q!#{PREFIX}:about="#{h @about}"! if @about
+ rv = <<-EOT
+#{indent}<channel #{about}>
+#{title_element(false, next_indent)}
+#{link_element(false, next_indent)}
+#{description_element(false, next_indent)}
+#{image_element(false, next_indent)}
+#{items_element(false, next_indent)}
+#{textinput_element(false, next_indent)}
+#{other_element(false, next_indent)}
+#{indent}</channel>
+EOT
+ rv = @converter.convert(rv) if convert and @converter
+ rv
end
private
@@ -263,25 +263,17 @@ module RSS
[::RSS::URI, 'image'],
[::RSS::URI, 'items'],
[::RSS::URI, 'textinput'],
- ].delete_if do |uri, name|
- send(name).nil?
+ ].delete_if do |x|
+ send(x[1]).nil?
end
end
def _attrs
[
- ["#{PREFIX}:about", true, "about"]
+ ["about", true]
]
end
- def maker_target(maker)
- maker.channel
- end
-
- def setup_maker_attributes(channel)
- channel.about = about
- end
-
class Image < Element
include RSS10
@@ -305,18 +297,23 @@ module RSS
@resource = resource
end
- def to_s(need_convert=true, indent=calc_indent)
- rv = tag(indent)
- rv = convert(rv) if need_convert
- rv
+ def to_s(convert=true, indent=calc_indent)
+ if @resource
+ rv = %Q!#{indent}<image #{PREFIX}:resource="#{h @resource}" />!
+ rv = @converter.convert(rv) if convert and @converter
+ rv
+ else
+ ''
+ end
end
private
def _attrs
[
- ["#{PREFIX}:resource", true, "resource"]
+ ["resource", true]
]
end
+
end
class Textinput < Element
@@ -342,18 +339,23 @@ module RSS
@resource = resource
end
- def to_s(need_convert=true, indent=calc_indent)
- rv = tag(indent)
- rv = convert(rv) if need_convert
- rv
+ def to_s(convert=true, indent=calc_indent)
+ if @resource
+ rv = %Q|#{indent}<textinput #{PREFIX}:resource="#{h @resource}" />|
+ rv = @converter.convert(rv) if convert and @converter
+ rv
+ else
+ ''
+ end
end
private
def _attrs
[
- ["#{PREFIX}:resource", true, "resource"]
+ ["resource", true],
]
end
+
end
class Items < Element
@@ -384,13 +386,14 @@ module RSS
@Seq = seq
end
- def to_s(need_convert=true, indent=calc_indent)
- rv = tag(indent) do |next_indent|
- [
- Seq_element(need_convert, next_indent),
- other_element(need_convert, next_indent),
- ]
- end
+ def to_s(convert=true, indent=calc_indent)
+ next_indent = indent + INDENT
+ <<-EOT
+#{indent}<items>
+#{Seq_element(convert, next_indent)}
+#{other_element(convert, next_indent)}
+#{indent}</items>
+EOT
end
private
@@ -431,8 +434,8 @@ module RSS
install_get_attribute(name, uri, required)
end
- %w(title url link).each do |name|
- install_text_element(name)
+ %w(title url link).each do |x|
+ install_text_element(x)
end
[
@@ -448,16 +451,19 @@ module RSS
@about = about
end
- def to_s(need_convert=true, indent=calc_indent)
- rv = tag(indent) do |next_indent|
- [
- title_element(false, next_indent),
- url_element(false, next_indent),
- link_element(false, next_indent),
- other_element(false, next_indent),
- ]
- end
- rv = convert(rv) if need_convert
+ def to_s(convert=true, indent=calc_indent)
+ next_indent = indent + INDENT
+ about = ''
+ about << %Q!#{PREFIX}:about="#{h @about}"! if @about
+ rv = <<-EOT
+#{indent}<image #{about}>
+#{title_element(false, next_indent)}
+#{url_element(false, next_indent)}
+#{link_element(false, next_indent)}
+#{other_element(false, next_indent)}
+#{indent}</image>
+EOT
+ rv = @converter.convert(rv) if convert and @converter
rv
end
@@ -467,20 +473,17 @@ module RSS
[::RSS::URI, 'title'],
[::RSS::URI, 'url'],
[::RSS::URI, 'link'],
- ].delete_if do |uri, name|
- send(name).nil?
+ ].delete_if do |x|
+ send(x[1]).nil?
end
end
def _attrs
[
- ["#{PREFIX}:about", true, "about"]
+ ["about", true],
]
end
- def maker_target(maker)
- maker.image
- end
end
class Item < Element
@@ -501,8 +504,8 @@ module RSS
install_get_attribute(name, uri, required)
end
- %w(title link description).each do |name|
- install_text_element(name)
+ %w(title link description).each do |x|
+ install_text_element(x)
end
[
@@ -518,16 +521,19 @@ module RSS
@about = about
end
- def to_s(need_convert=true, indent=calc_indent)
- rv = tag(indent) do |next_indent|
- [
- title_element(false, next_indent),
- link_element(false, next_indent),
- description_element(false, next_indent),
- other_element(false, next_indent),
- ]
- end
- rv = convert(rv) if need_convert
+ def to_s(convert=true, indent=calc_indent)
+ next_indent = indent + INDENT
+ about = ''
+ about << %Q!#{PREFIX}:about="#{h @about}"! if @about
+ rv = <<-EOT
+#{indent}<item #{about}>
+#{title_element(false, next_indent)}
+#{link_element(false, next_indent)}
+#{description_element(false, next_indent)}
+#{other_element(false, next_indent)}
+#{indent}</item>
+EOT
+ rv = @converter.convert(rv) if convert and @converter
rv
end
@@ -537,20 +543,17 @@ module RSS
[::RSS::URI, 'title'],
[::RSS::URI, 'link'],
[::RSS::URI, 'description'],
- ].delete_if do |uri, name|
- send(name).nil?
+ ].delete_if do |x|
+ send(x[1]).nil?
end
end
def _attrs
[
- ["#{PREFIX}:about", true, "about"]
+ ["about", true],
]
end
- def maker_target(maker)
- maker.items.new_item
- end
end
class Textinput < Element
@@ -571,8 +574,8 @@ module RSS
install_get_attribute(name, uri, required)
end
- %w(title description name link).each do |name|
- install_text_element(name)
+ %w(title description name link).each do |x|
+ install_text_element(x)
end
[
@@ -589,17 +592,20 @@ module RSS
@about = about
end
- def to_s(need_convert=true, indent=calc_indent)
- rv = tag(indent) do |next_indent|
- [
- title_element(false, next_indent),
- description_element(false, next_indent),
- name_element(false, next_indent),
- link_element(false, next_indent),
- other_element(false, next_indent),
- ]
- end
- rv = convert(rv) if need_convert
+ def to_s(convert=true, indent=calc_indent)
+ next_indent = indent + INDENT
+ about = ''
+ about << %Q!#{PREFIX}:about="#{h @about}"! if @about
+ rv = <<-EOT
+#{indent}<textinput #{about}>
+#{title_element(false, next_indent)}
+#{description_element(false, next_indent)}
+#{name_element(false, next_indent)}
+#{link_element(false, next_indent)}
+#{other_element(false, next_indent)}
+#{indent}</textinput>
+EOT
+ rv = @converter.convert(rv) if convert and @converter
rv
end
@@ -610,26 +616,23 @@ module RSS
[::RSS::URI, 'description'],
[::RSS::URI, 'name'],
[::RSS::URI, 'link'],
- ].delete_if do |uri, name|
- send(name).nil?
+ ].delete_if do |x|
+ send(x[1]).nil?
end
end
def _attrs
[
- ["#{PREFIX}:about", true, "about"]
+ ["about", true],
]
end
- def maker_target(maker)
- maker.textinput
- end
end
end
- RSS10::ELEMENTS.each do |name|
- BaseListener.install_get_text_element(URI, name, "#{name}=")
+ RSS10::ELEMENTS.each do |x|
+ BaseListener.install_get_text_element(x, URI, "#{x}=")
end
module ListenerMixin
diff --git a/lib/rss/2.0.rb b/lib/rss/2.0.rb
index af6ced9f7c..7fafb23ba9 100644
--- a/lib/rss/2.0.rb
+++ b/lib/rss/2.0.rb
@@ -6,35 +6,28 @@ module RSS
class Channel
- %w(generator ttl).each do |name|
- install_text_element(name)
- install_model(name, '?')
+ %w(generator ttl).each do |x|
+ install_text_element(x)
+ install_model(x, '?')
end
- remove_method :ttl=
- def ttl=(value)
- @ttl = value.to_i
+ %w(category).each do |x|
+ install_have_child_element(x)
+ install_model(x, '?')
end
-
- [
- %w(category categories),
- ].each do |name, plural_name|
- install_have_children_element(name, plural_name)
- install_model(name, '*')
- end
-
+
[
["image", "?"],
["language", "?"],
- ].each do |name, occurs|
- install_model(name, occurs)
+ ].each do |x, occurs|
+ install_model(x, occurs)
end
- def other_element(need_convert, indent)
+ def other_element(convert, indent)
rv = <<-EOT
-#{category_elements(need_convert, indent)}
-#{generator_element(need_convert, indent)}
-#{ttl_element(need_convert, indent)}
+#{category_element(convert, indent)}
+#{generator_element(convert, indent)}
+#{ttl_element(convert, indent)}
EOT
rv << super
end
@@ -42,22 +35,16 @@ EOT
private
alias children09 children
def children
- children09 + @category.compact
+ children09 + [@category].compact
end
alias _tags09 _tags
def _tags
- rv = %w(generator ttl).delete_if do |name|
- send(name).nil?
+ %w(generator ttl category).delete_if do |x|
+ send(x).nil?
end.collect do |elem|
[nil, elem]
end + _tags09
-
- @category.each do
- rv << [nil, "category"]
- end
-
- rv
end
Category = Item::Category
@@ -67,37 +54,33 @@ EOT
[
["comments", "?"],
["author", "?"],
- ].each do |name, occurs|
- install_text_element(name)
- install_model(name, occurs)
+ ].each do |x, occurs|
+ install_text_element(x)
+ install_model(x, occurs)
end
[
["pubDate", '?'],
- ].each do |name, occurs|
- install_date_element(name, 'rfc822')
- install_model(name, occurs)
+ ].each do |x, occurs|
+ install_date_element(x, 'rfc822')
+ install_model(x, occurs)
end
- alias date pubDate
- alias date= pubDate=
[
["guid", '?'],
- ].each do |name, occurs|
- install_have_child_element(name)
- install_model(name, occurs)
+ ].each do |x, occurs|
+ install_have_child_element(x)
+ install_model(x, occurs)
end
- def other_element(need_convert, indent)
- rv = [
- super,
- *%w(author comments pubDate guid).collect do |name|
- __send__("#{name}_element", false, indent)
- end
- ].reject do |value|
- /\A\s*\z/.match(value)
- end
- rv.join("\n")
+ def other_element(convert, indent)
+ rv = <<-EOT
+#{author_element(false, indent)}
+#{comments_element(false, indent)}
+#{pubDate_element(false, indent)}
+#{guid_element(false, indent)}
+EOT
+ rv << super
end
private
@@ -108,19 +91,13 @@ EOT
alias _tags09 _tags
def _tags
- %w(comments author pubDate guid).delete_if do |name|
- send(name).nil?
+ %w(comments author pubDate guid).delete_if do |x|
+ send(x).nil?
end.collect do |elem|
[nil, elem]
end + _tags09
end
- alias _setup_maker_element setup_maker_element
- def setup_maker_element(item)
- _setup_maker_element(item)
- @guid.setup_maker(item) if @guid
- end
-
class Guid < Element
include RSS09
@@ -139,6 +116,18 @@ EOT
@content = content
end
+ def to_s(convert=true, indent=calc_indent)
+ if @content
+ rv = %Q!<guid!
+ rv << %Q! isPermaLink="#{h @isPermaLink}"! if @isPermaLink
+ rv << %Q!>#{h @content}</guid>!
+ rv = @converter.convert(rv) if convert and @converter
+ rv
+ else
+ ''
+ end
+ end
+
private
def _attrs
[
@@ -146,14 +135,6 @@ EOT
]
end
- def maker_target(item)
- item.guid
- end
-
- def setup_maker_attributes(guid)
- guid.isPermaLink = isPermaLink
- guid.content = content
- end
end
end
@@ -162,8 +143,8 @@ EOT
end
- RSS09::ELEMENTS.each do |name|
- BaseListener.install_get_text_element(nil, name, "#{name}=")
+ RSS09::ELEMENTS.each do |x|
+ BaseListener.install_get_text_element(x, nil, "#{x}=")
end
end
diff --git a/lib/rss/content.rb b/lib/rss/content.rb
index a732cec973..280bbb8d6b 100644
--- a/lib/rss/content.rb
+++ b/lib/rss/content.rb
@@ -17,16 +17,16 @@ module RSS
super
klass.module_eval(<<-EOC, *get_file_and_line_from_caller(1))
- %w(encoded).each do |name|
- install_text_element("\#{CONTENT_PREFIX}_\#{name}")
+ %w(encoded).each do |x|
+ install_text_element("\#{CONTENT_PREFIX}_\#{x}")
end
EOC
end
def content_validate(tags)
counter = {}
- ELEMENTS.each do |name|
- counter[name] = 0
+ ELEMENTS.each do |x|
+ counter[x] = 0
end
tags.each do |tag|
@@ -45,9 +45,8 @@ module RSS
prefix_size = CONTENT_PREFIX.size + 1
ContentModel::ELEMENTS.uniq!
- ContentModel::ELEMENTS.each do |full_name|
- name = full_name[prefix_size..-1]
- BaseListener.install_get_text_element(CONTENT_URI, name, "#{full_name}=")
+ ContentModel::ELEMENTS.each do |x|
+ BaseListener.install_get_text_element(x[prefix_size..-1], CONTENT_URI, "#{x}=")
end
end
diff --git a/lib/rss/dublincore.rb b/lib/rss/dublincore.rb
index 5571640bf2..7ea9cf31dd 100644
--- a/lib/rss/dublincore.rb
+++ b/lib/rss/dublincore.rb
@@ -7,135 +7,39 @@ module RSS
RDF.install_ns(DC_PREFIX, DC_URI)
- module BaseDublinCoreModel
- def append_features(klass)
- super
-
- return if klass.instance_of?(Module)
- DublinCoreModel::ELEMENT_NAME_INFOS.each do |name, plural_name|
- plural = plural_name || "#{name}s"
- full_name = "#{DC_PREFIX}_#{name}"
- full_plural_name = "#{DC_PREFIX}_#{plural}"
- klass_name = "DublinCore#{Utils.to_class_name(name)}"
- klass.module_eval(<<-EOC, *get_file_and_line_from_caller(0))
- install_have_children_element(#{full_name.dump},
- #{full_plural_name.dump})
-
- remove_method :#{full_name}
- remove_method :#{full_name}=
- remove_method :set_#{full_name}
-
- def #{full_name}
- @#{full_name}.first and @#{full_name}.first.value
- end
-
- def #{full_name}=(new_value)
- @#{full_name}[0] = Utils.new_with_value_if_need(#{klass_name}, new_value)
- end
- alias set_#{full_name} #{full_name}=
- EOC
- end
- klass.module_eval(<<-EOC, *get_file_and_line_from_caller(0))
- alias date #{DC_PREFIX}_date
- alias date= #{DC_PREFIX}_date=
- EOC
- end
- end
-
module DublinCoreModel
extend BaseModel
- extend BaseDublinCoreModel
-
- TEXT_ELEMENTS = {
- "title" => nil,
- "description" => nil,
- "creator" => nil,
- "subject" => nil,
- "publisher" => nil,
- "contributor" => nil,
- "type" => nil,
- "format" => nil,
- "identifier" => nil,
- "source" => nil,
- "language" => nil,
- "relation" => nil,
- "coverage" => nil,
- "rights" => "rightses" # FIXME
- }
-
- DATE_ELEMENTS = {
- "date" => "w3cdtf",
- }
-
- ELEMENT_NAME_INFOS = DublinCoreModel::TEXT_ELEMENTS.to_a
- DublinCoreModel::DATE_ELEMENTS.each do |name, |
- ELEMENT_NAME_INFOS << [name, nil]
- end
-
- ELEMENTS = TEXT_ELEMENTS.keys + DATE_ELEMENTS.keys
-
- ELEMENTS.each do |name, plural_name|
- module_eval(<<-EOC, *get_file_and_line_from_caller(0))
- class DublinCore#{Utils.to_class_name(name)} < Element
- include RSS10
-
- content_setup
- class << self
- def required_prefix
- DC_PREFIX
- end
-
- def required_uri
- DC_URI
- end
- end
+ ELEMENTS = []
- @tag_name = #{name.dump}
-
- alias_method(:value, :content)
- alias_method(:value=, :content=)
-
- def initialize(content=nil)
- super()
- self.content = content
- end
+ def self.append_features(klass)
+ super
- def full_name
- tag_name_with_prefix(DC_PREFIX)
- end
-
- def maker_target(target)
- target.new_#{name}
- end
-
- def setup_maker_attributes(#{name})
- #{name}.content = content
- end
+ klass.module_eval(<<-EOC, *get_file_and_line_from_caller(1))
+ %w(title description creator subject publisher
+ contributor type format identifier source
+ language relation coverage rights).each do |x|
+ install_text_element("\#{DC_PREFIX}_\#{x}")
end
- EOC
- end
- DATE_ELEMENTS.each do |name, type|
- module_eval(<<-EOC, *get_file_and_line_from_caller(0))
- class DublinCore#{Utils.to_class_name(name)} < Element
- remove_method(:content=)
- remove_method(:value=)
-
- date_writer("content", #{type.dump}, #{name.dump})
-
- alias_method(:value=, :content=)
+ %w(date).each do |x|
+ install_date_element("\#{DC_PREFIX}_\#{x}", 'w3cdtf', x)
end
EOC
end
-
+
def dc_validate(tags)
+ counter = {}
+ ELEMENTS.each do |x|
+ counter[x] = 0
+ end
+
tags.each do |tag|
key = "#{DC_PREFIX}_#{tag}"
- unless DublinCoreModel::ELEMENTS.include?(key)
- raise UnknownTagError.new(tag, DC_URI)
- end
+ raise UnknownTagError.new(tag, DC_URI) unless counter.has_key?(key)
+ counter[key] += 1
+ raise TooMuchTagError.new(tag, tag_name) if counter[key] > 1
end
end
@@ -151,10 +55,10 @@ module RSS
class Textinput; include DublinCoreModel; end
end
- DublinCoreModel::ELEMENTS.each do |name|
- class_name = Utils.to_class_name(name)
- BaseListener.install_class_name(DC_URI, name, "DublinCore#{class_name}")
+ prefix_size = DC_PREFIX.size + 1
+ DublinCoreModel::ELEMENTS.uniq!
+ DublinCoreModel::ELEMENTS.each do |x|
+ BaseListener.install_get_text_element(x[prefix_size..-1], DC_URI, "#{x}=")
end
- DublinCoreModel::ELEMENTS.collect! {|name| "#{DC_PREFIX}_#{name}"}
end
diff --git a/lib/rss/image.rb b/lib/rss/image.rb
deleted file mode 100644
index 4dea91925b..0000000000
--- a/lib/rss/image.rb
+++ /dev/null
@@ -1,216 +0,0 @@
-require 'rss/1.0'
-require 'rss/dublincore'
-
-module RSS
-
- IMAGE_PREFIX = 'image'
- IMAGE_URI = 'http://web.resource.org/rss/1.0/modules/image/'
-
- RDF.install_ns(IMAGE_PREFIX, IMAGE_URI)
-
- module ImageModelUtils
- def validate_one_tag_name(name, tags)
- invalid = tags.find {|tag| tag != name}
- raise UnknownTagError.new(invalid, IMAGE_URI) if invalid
- raise TooMuchTagError.new(name, tag_name) if tags.size > 1
- end
- end
-
- module ImageItemModel
- include ImageModelUtils
- extend BaseModel
-
- def self.append_features(klass)
- super
-
- klass.install_have_child_element("#{IMAGE_PREFIX}_item")
- end
-
- def image_validate(tags)
- validate_one_tag_name("item", tags)
- end
-
- class Item < Element
- include RSS10
- include DublinCoreModel
-
- class << self
- def required_prefix
- IMAGE_PREFIX
- end
-
- def required_uri
- IMAGE_URI
- end
- end
-
- [
- ["about", ::RSS::RDF::URI, true],
- ["resource", ::RSS::RDF::URI, false],
- ].each do |name, uri, required|
- install_get_attribute(name, uri, required)
- end
-
- %w(width height).each do |tag|
- full_name = "#{IMAGE_PREFIX}_#{tag}"
- install_text_element(full_name)
- BaseListener.install_get_text_element(IMAGE_URI, tag, "#{full_name}=")
- end
-
- def initialize(about=nil, resource=nil)
- super()
- @about = about
- @resource = resource
- end
-
- def full_name
- tag_name_with_prefix(IMAGE_PREFIX)
- end
-
- def to_s(need_convert=true, indent=calc_indent)
- rv = tag(indent) do |next_indent|
- [
- other_element(false, next_indent),
- ]
- end
- rv = convert(rv) if need_convert
- rv
- end
-
- alias _image_width= image_width=
- def image_width=(new_value)
- if @do_validate
- self._image_width = Integer(new_value)
- else
- self._image_width = new_value.to_i
- end
- end
-
- alias _image_height= image_height=
- def image_height=(new_value)
- if @do_validate
- self._image_height = Integer(new_value)
- else
- self._image_height = new_value.to_i
- end
- end
-
- alias width= image_width=
- alias width image_width
- alias height= image_height=
- alias height image_height
-
- private
- def _tags
- [
- [IMAGE_URI, 'width'],
- [IMAGE_URI, 'height'],
- ].delete_if do |uri, name|
- send(name).nil?
- end
- end
-
- def _attrs
- [
- ["#{::RSS::RDF::PREFIX}:about", true, "about"],
- ["#{::RSS::RDF::PREFIX}:resource", false, "resource"],
- ]
- end
-
- def maker_target(target)
- target.image_item
- end
-
- def setup_maker_attributes(item)
- item.about = self.about
- item.resource = self.resource
- end
- end
- end
-
- module ImageFaviconModel
- include ImageModelUtils
- extend BaseModel
-
- def self.append_features(klass)
- super
-
- unless klass.class == Module
- klass.install_have_child_element("#{IMAGE_PREFIX}_favicon")
- end
- end
-
- def image_validate(tags)
- validate_one_tag_name("favicon", tags)
- end
-
- class Favicon < Element
- include RSS10
- include DublinCoreModel
-
- class << self
- def required_prefix
- IMAGE_PREFIX
- end
-
- def required_uri
- IMAGE_URI
- end
- end
-
- [
- ["about", ::RSS::RDF::URI, true],
- ["size", IMAGE_URI, true],
- ].each do |name, uri, required|
- install_get_attribute(name, uri, required)
- end
-
- alias image_size= size=
- alias image_size size
-
- def initialize(about=nil, size=nil)
- super()
- @about = about
- @size = size
- end
-
- def full_name
- tag_name_with_prefix(IMAGE_PREFIX)
- end
-
- def to_s(need_convert=true, indent=calc_indent)
- rv = tag(indent) do |next_indent|
- [
- other_element(false, next_indent),
- ]
- end
- rv = convert(rv) if need_convert
- rv
- end
-
- private
- def _attrs
- [
- ["#{::RSS::RDF::PREFIX}:about", true, "about"],
- ["#{IMAGE_PREFIX}:size", true, "size"],
- ]
- end
-
- def maker_target(target)
- target.image_favicon
- end
-
- def setup_maker_attributes(favicon)
- favicon.about = self.about
- favicon.size = self.size
- end
- end
-
- end
-
- class RDF
- class Channel; include ImageFaviconModel; end
- class Item; include ImageItemModel; end
- end
-
-end
diff --git a/lib/rss/maker.rb b/lib/rss/maker.rb
index d248711aa2..c158c726c3 100644
--- a/lib/rss/maker.rb
+++ b/lib/rss/maker.rb
@@ -7,7 +7,12 @@ module RSS
MAKERS = {}
class << self
- def make(version, &block)
+ def make(version, modules=[], &block)
+ prefix = "rss/maker"
+ require "#{prefix}/#{version}"
+ modules.each do |mod|
+ require "#{prefix}/#{mod}"
+ end
maker(version).make(&block)
end
@@ -26,11 +31,3 @@ module RSS
end
end
-
-require "rss/maker/1.0"
-require "rss/maker/2.0"
-require "rss/maker/content"
-require "rss/maker/dublincore"
-require "rss/maker/syndication"
-require "rss/maker/trackback"
-require "rss/maker/image"
diff --git a/lib/rss/maker/0.9.rb b/lib/rss/maker/0.9.rb
index b82585fb96..05578082b0 100644
--- a/lib/rss/maker/0.9.rb
+++ b/lib/rss/maker/0.9.rb
@@ -11,15 +11,23 @@ module RSS
super
end
- private
- def make_rss
- Rss.new(@rss_version, @version, @encoding, @standalone)
- end
-
- def setup_elements(rss)
+ def to_rss
+ rss = Rss.new(@rss_version, @version, @encoding, @standalone)
+ setup_xml_stylesheets(rss)
setup_channel(rss)
+ setup_other_elements(rss)
+ if rss.channel
+ rss
+ else
+ nil
+ end
end
-
+
+ private
+ def setup_channel(rss)
+ @channel.to_rss(rss)
+ end
+
class Channel < ChannelBase
def to_rss(rss)
@@ -36,13 +44,12 @@ module RSS
else
nil
end
- elsif variable_is_set?
- raise NotSetError.new("maker.channel", not_set_required_variables)
end
end
def have_required_values?
- @title and @link and @description and @language
+ @title and @link and @description and @language and
+ @maker.image.have_required_values?
end
private
@@ -62,76 +69,9 @@ module RSS
super + ["pubDate"]
end
- def required_variable_names
- %w(title link description language)
- end
-
- class SkipDays < SkipDaysBase
- def to_rss(rss, channel)
- unless @days.empty?
- skipDays = Rss::Channel::SkipDays.new
- channel.skipDays = skipDays
- @days.each do |day|
- day.to_rss(rss, skipDays.days)
- end
- end
- end
-
- class Day < DayBase
- def to_rss(rss, days)
- day = Rss::Channel::SkipDays::Day.new
- set = setup_values(day)
- if set
- days << day
- setup_other_elements(rss)
- end
- end
-
- def have_required_values?
- @content
- end
- end
- end
-
- class SkipHours < SkipHoursBase
- def to_rss(rss, channel)
- unless @hours.empty?
- skipHours = Rss::Channel::SkipHours.new
- channel.skipHours = skipHours
- @hours.each do |hour|
- hour.to_rss(rss, skipHours.hours)
- end
- end
- end
-
- class Hour < HourBase
- def to_rss(rss, hours)
- hour = Rss::Channel::SkipHours::Hour.new
- set = setup_values(hour)
- if set
- hours << hour
- setup_other_elements(rss)
- end
- end
-
- def have_required_values?
- @content
- end
- end
- end
-
class Cloud < CloudBase
- def to_rss(*args)
- end
end
- class Categories < CategoriesBase
- def to_rss(*args)
- end
-
- class Category < CategoryBase
- end
- end
end
class Image < ImageBase
@@ -190,12 +130,9 @@ module RSS
end
end
- class Categories < CategoriesBase
+ class Category < CategoryBase
def to_rss(*args)
end
-
- class Category < CategoryBase
- end
end
end
@@ -219,6 +156,5 @@ module RSS
end
add_maker(filename_to_version(__FILE__), RSS09)
- add_maker(filename_to_version(__FILE__) + "1", RSS09)
end
end
diff --git a/lib/rss/maker/1.0.rb b/lib/rss/maker/1.0.rb
index 3e6542a007..894bcc0a24 100644
--- a/lib/rss/maker/1.0.rb
+++ b/lib/rss/maker/1.0.rb
@@ -11,27 +11,45 @@ module RSS
super("1.0")
end
- private
- def make_rss
- RDF.new(@version, @encoding, @standalone)
- end
-
- def setup_elements(rss)
+ def to_rss
+ rss = RDF.new(@version, @encoding, @standalone)
+ setup_xml_stylesheets(rss)
setup_channel(rss)
setup_image(rss)
setup_items(rss)
setup_textinput(rss)
+ setup_other_elements(rss)
+ if rss.channel
+ rss
+ else
+ nil
+ end
+ end
+
+ private
+ def setup_channel(rss)
+ @channel.to_rss(rss)
+ end
+
+ def setup_image(rss)
+ @image.to_rss(rss)
+ end
+
+ def setup_items(rss)
+ @items.to_rss(rss)
+ end
+
+ def setup_textinput(rss)
+ @textinput.to_rss(rss)
end
class Channel < ChannelBase
def to_rss(rss)
- set = false
if @about
channel = RDF::Channel.new(@about)
set = setup_values(channel)
if set
- channel.dc_dates.clear
rss.channel = channel
setup_items(rss)
setup_image(rss)
@@ -39,16 +57,12 @@ module RSS
setup_other_elements(rss)
end
end
-
- if (!@about or !set) and variable_is_set?
- raise NotSetError.new("maker.channel", not_set_required_variables)
- end
end
def have_required_values?
@about and @title and @link and @description
end
-
+
private
def setup_items(rss)
items = RDF::Channel::Items.new
@@ -72,37 +86,7 @@ module RSS
end
end
- def required_variable_names
- %w(about title link description)
- end
-
- class SkipDays < SkipDaysBase
- def to_rss(*args)
- end
-
- class Day < DayBase
- end
- end
-
- class SkipHours < SkipHoursBase
- def to_rss(*args)
- end
-
- class Hour < HourBase
- end
- end
-
class Cloud < CloudBase
- def to_rss(*args)
- end
- end
-
- class Categories < CategoriesBase
- def to_rss(*args)
- end
-
- class Category < CategoryBase
- end
end
end
@@ -144,7 +128,6 @@ module RSS
item = RDF::Item.new(@link)
set = setup_values(item)
if set
- item.dc_dates.clear
rss.items << item
setup_other_elements(rss)
end
@@ -170,12 +153,9 @@ module RSS
end
end
- class Categories < CategoriesBase
+ class Category < CategoryBase
def to_rss(*args)
end
-
- class Category < CategoryBase
- end
end
end
end
diff --git a/lib/rss/maker/2.0.rb b/lib/rss/maker/2.0.rb
index a958661614..05fc46480a 100644
--- a/lib/rss/maker/2.0.rb
+++ b/lib/rss/maker/2.0.rb
@@ -13,30 +13,23 @@ module RSS
class Channel < RSS09::Channel
+ add_other_element("cloud")
+
def have_required_values?
@title and @link and @description
end
- def required_variable_names
- %w(title link description)
- end
-
- class SkipDays < RSS09::Channel::SkipDays
- class Day < RSS09::Channel::SkipDays::Day
- end
+ private
+ def setup_cloud(rss, current)
+ @maker.channel.cloud.to_rss(rss)
end
-
- class SkipHours < RSS09::Channel::SkipHours
- class Hour < RSS09::Channel::SkipHours::Hour
- end
- end
-
+
class Cloud < RSS09::Channel::Cloud
- def to_rss(rss, channel)
+ def to_rss(rss)
cloud = Rss::Channel::Cloud.new
set = setup_values(cloud)
if set
- channel.cloud = cloud
+ rss.channel.cloud = cloud
setup_other_elements(rss)
end
end
@@ -46,30 +39,6 @@ module RSS
@registerProcedure and @protocol
end
end
-
- class Categories < RSS09::Channel::Categories
- def to_rss(rss, channel)
- @categories.each do |category|
- category.to_rss(rss, channel)
- end
- end
-
- class Category < RSS09::Channel::Categories::Category
- def to_rss(rss, channel)
- category = Rss::Channel::Category.new
- set = setup_values(category)
- if set
- channel.categories << category
- setup_other_elements(rss)
- end
- end
-
- def have_required_values?
- @content
- end
- end
- end
-
end
class Image < RSS09::Image
@@ -133,26 +102,18 @@ module RSS
end
end
- class Categories < RSS09::Items::Item::Categories
+ class Category < RSS09::Items::Item::Category
def to_rss(rss, item)
- @categories.each do |category|
- category.to_rss(rss, item)
+ category = Rss::Channel::Item::Category.new
+ set = setup_values(category)
+ if set
+ item.category = category
+ setup_other_elements(rss)
end
end
-
- class Category < RSS09::Items::Item::Categories::Category
- def to_rss(rss, item)
- category = Rss::Channel::Item::Category.new
- set = setup_values(category)
- if set
- item.categories << category
- setup_other_elements(rss)
- end
- end
-
- def have_required_values?
- @content
- end
+
+ def have_required_values?
+ @content
end
end
end
diff --git a/lib/rss/maker/base.rb b/lib/rss/maker/base.rb
index dbd8bf9041..21222351f2 100644
--- a/lib/rss/maker/base.rb
+++ b/lib/rss/maker/base.rb
@@ -21,41 +21,30 @@ module RSS
subclass.module_eval(<<-EOEOC, __FILE__, __LINE__)
def self.other_elements
- OTHER_ELEMENTS + super
+ const_get("OTHER_ELEMENTS") + super
end
def self.need_initialize_variables
- NEED_INITIALIZE_VARIABLES + super
+ const_get("NEED_INITIALIZE_VARIABLES") + super
end
EOEOC
end
def self.add_other_element(variable_name)
- OTHER_ELEMENTS << variable_name
+ const_get("OTHER_ELEMENTS") << variable_name
end
def self.other_elements
OTHER_ELEMENTS
end
- def self.add_need_initialize_variable(variable_name, init_value="nil")
- NEED_INITIALIZE_VARIABLES << [variable_name, init_value]
+ def self.add_need_initialize_variable(variable_name)
+ const_get("NEED_INITIALIZE_VARIABLES") << variable_name
end
def self.need_initialize_variables
NEED_INITIALIZE_VARIABLES
end
-
- def self.def_array_element(name)
- include Enumerable
- extend Forwardable
-
- def_delegators("@\#{name}", :<<, :[], :[]=, :first, :last)
- def_delegators("@\#{name}", :push, :pop, :shift, :unshift)
- def_delegators("@\#{name}", :each, :size)
-
- add_need_initialize_variable(name, "[]")
- end
EOC
end
@@ -70,8 +59,8 @@ module RSS
private
def initialize_variables
- self.class.need_initialize_variables.each do |variable_name, init_value|
- instance_eval("@#{variable_name} = #{init_value}", __FILE__, __LINE__)
+ self.class.need_initialize_variables.each do |variable_name|
+ instance_eval("@#{variable_name} = nil", __FILE__, __LINE__)
end
end
@@ -81,10 +70,6 @@ module RSS
end
end
- def current_element(rss)
- rss
- end
-
def setup_values(target)
set = false
if have_required_values?
@@ -103,28 +88,7 @@ module RSS
end
def variables
- self.class.need_initialize_variables.find_all do |name, init|
- "nil" == init
- end.collect do |name, init|
- name
- end
- end
-
- def variable_is_set?
- variables.find {|var| !__send__(var).nil?}
- end
-
- def not_set_required_variables
- required_variable_names.find_all do |var|
- __send__(var).nil?
- end
- end
-
- def required_variables_are_set?
- required_variable_names.each do |var|
- return false if __send__(var).nil?
- end
- true
+ self.class.need_initialize_variables
end
end
@@ -138,22 +102,9 @@ module RSS
end
end
- %w(xml_stylesheets channel image items textinput).each do |element|
- attr_reader element
- add_need_initialize_variable(element, "make_#{element}")
- module_eval(<<-EOC, __FILE__, __LINE__)
- private
- def setup_#{element}(rss)
- @#{element}.to_rss(rss)
- end
-
- def make_#{element}
- self.class::#{Utils.to_class_name(element)}.new(self)
- end
-EOC
- end
+ attr_reader :rss_version, :xml_stylesheets
+ attr_reader :channel, :image, :items, :textinput
- attr_reader :rss_version
attr_accessor :version, :encoding, :standalone
def initialize(rss_version)
@@ -162,41 +113,63 @@ EOC
@version = "1.0"
@encoding = "UTF-8"
@standalone = nil
+ @xml_stylesheets = make_xml_stylesheets
+ @channel = make_channel
+ @image = make_image
+ @items = make_items
+ @textinput = make_textinput
end
- def make
- if block_given?
- yield(self)
- to_rss
- else
- nil
- end
+ def make(&block)
+ block.call(self) if block
+ to_rss
end
- def to_rss
- rss = make_rss
- setup_xml_stylesheets(rss)
- setup_elements(rss)
- setup_other_elements(rss)
- if rss.channel
- rss
- else
- nil
- end
+ def current_element(rss)
+ rss
end
private
- remove_method :make_xml_stylesheets
def make_xml_stylesheets
XMLStyleSheets.new(self)
end
+ def make_channel
+ self.class::Channel.new(self)
+ end
+
+ def make_image
+ self.class::Image.new(self)
+ end
+
+ def make_items
+ self.class::Items.new(self)
+ end
+
+ def make_textinput
+ self.class::Textinput.new(self)
+ end
+
+ def setup_xml_stylesheets(rss)
+ @xml_stylesheets.to_rss(rss)
+ end
+
end
class XMLStyleSheets
include Base
- def_array_element("xml_stylesheets")
+ include Enumerable
+ extend Forwardable
+
+ def_delegators(:@xml_stylesheets, :<<, :[], :[]=, :first, :last)
+ def_delegators(:@xml_stylesheets, :push, :pop, :shift, :unshift)
+ def_delegators(:@xml_stylesheets, :each)
+
+ def initialize(maker)
+ super
+ @xml_stylesheets = []
+ end
def to_rss(rss)
@xml_stylesheets.each do |xss|
@@ -244,25 +217,12 @@ EOC
class ChannelBase
include Base
- %w(cloud categories skipDays skipHours).each do |element|
- attr_reader element
- add_other_element(element)
- add_need_initialize_variable(element, "make_#{element}")
- module_eval(<<-EOC, __FILE__, __LINE__)
- private
- def setup_#{element}(rss, current)
- @#{element}.to_rss(rss, current)
- end
-
- def make_#{element}
- self.class::#{Utils.to_class_name(element)}.new(@maker)
- end
-EOC
- end
+ attr_reader :cloud
%w(about title link description language copyright
- managingEditor webMaster rating docs date
- lastBuildDate generator ttl).each do |element|
+ managingEditor webMaster rating docs skipDays
+ skipHours date lastBuildDate category generator ttl
+ ).each do |element|
attr_accessor element
add_need_initialize_variable(element)
end
@@ -270,68 +230,18 @@ EOC
alias_method(:pubDate, :date)
alias_method(:pubDate=, :date=)
- def current_element(rss)
- rss.channel
+ def initialize(maker)
+ super
+ @cloud = make_cloud
end
- class SkipDaysBase
- include Base
-
- def_array_element("days")
-
- def new_day
- day = self.class::Day.new(@maker)
- @days << day
- day
- end
-
- def current_element(rss)
- rss.channel.skipDays
- end
-
- class DayBase
- include Base
-
- %w(content).each do |element|
- attr_accessor element
- add_need_initialize_variable(element)
- end
-
- def current_element(rss)
- rss.channel.skipDays.last
- end
-
- end
+ def current_element(rss)
+ rss.channel
end
-
- class SkipHoursBase
- include Base
-
- def_array_element("hours")
-
- def new_hour
- hour = self.class::Hour.new(@maker)
- @hours << hour
- hour
- end
-
- def current_element(rss)
- rss.channel.skipHours
- end
-
- class HourBase
- include Base
-
- %w(content).each do |element|
- attr_accessor element
- add_need_initialize_variable(element)
- end
-
- def current_element(rss)
- rss.channel.skipHours.last
- end
- end
+ private
+ def make_cloud
+ self.class::Cloud.new(@maker)
end
class CloudBase
@@ -347,27 +257,6 @@ EOC
end
end
-
- class CategoriesBase
- include Base
-
- def_array_element("categories")
-
- def new_category
- category = self.class::Category.new(@maker)
- @categories << category
- category
- end
-
- class CategoryBase
- include Base
-
- %w(domain content).each do |element|
- attr_accessor element
- add_need_initialize_variable(element)
- end
- end
- end
end
class ImageBase
@@ -390,22 +279,23 @@ EOC
class ItemsBase
include Base
- def_array_element("items")
+ include Enumerable
+ extend Forwardable
+
+ def_delegators(:@items, :<<, :[], :[]=, :first, :last)
+ def_delegators(:@items, :push, :pop, :shift, :unshift)
+ def_delegators(:@items, :each)
- attr_accessor :do_sort, :max_size
+ attr_accessor :do_sort
def initialize(maker)
super
+ @items = []
@do_sort = false
- @max_size = -1
end
def normalize
- if @max_size >= 0
- sort_if_need[0...@max_size]
- else
- sort_if_need[0..@max_size]
- end
+ sort_if_need
end
def current_element(rss)
@@ -436,10 +326,9 @@ EOC
class ItemBase
include Base
- %w(guid enclosure source categories).each do |element|
+ %w(guid enclosure source category).each do |element|
attr_reader element
add_other_element(element)
- add_need_initialize_variable(element, "make_#{element}")
module_eval(<<-EOC, __FILE__, __LINE__)
private
def setup_#{element}(rss, current)
@@ -447,7 +336,7 @@ EOC
end
def make_#{element}
- self.class::#{Utils.to_class_name(element)}.new(@maker)
+ self.class::#{element[0,1].upcase}#{element[1..-1]}.new(@maker)
end
EOC
end
@@ -460,10 +349,18 @@ EOC
alias_method(:pubDate, :date)
alias_method(:pubDate=, :date=)
+ def initialize(maker)
+ super
+ @guid = make_guid
+ @enclosure = make_enclosure
+ @source = make_source
+ @category = make_category
+ end
+
def <=>(other)
- if date and other.date
- date <=> other.date
- elsif date
+ if @date and other.date
+ @date <=> other.date
+ elsif @date
1
elsif other.date
-1
@@ -503,7 +400,14 @@ EOC
end
end
- CategoriesBase = ChannelBase::CategoriesBase
+ class CategoryBase
+ include Base
+
+ %w(domain content).each do |element|
+ attr_accessor element
+ add_need_initialize_variable(element)
+ end
+ end
end
end
diff --git a/lib/rss/maker/content.rb b/lib/rss/maker/content.rb
index 18590d0cf8..96f3ccb6d9 100644
--- a/lib/rss/maker/content.rb
+++ b/lib/rss/maker/content.rb
@@ -10,8 +10,8 @@ module RSS
::RSS::ContentModel::ELEMENTS.each do |element|
klass.add_need_initialize_variable(element)
klass.add_other_element(element)
- klass.module_eval(<<-EOC, __FILE__, __LINE__+1)
- attr_accessor :#{element}
+ klass.__send__(:attr_accessor, element)
+ klass.module_eval(<<-EOC, __FILE__, __LINE__)
def setup_#{element}(rss, current)
if #{element} and current.respond_to?(:#{element}=)
current.#{element} = @#{element} if @#{element}
diff --git a/lib/rss/maker/dublincore.rb b/lib/rss/maker/dublincore.rb
index e038378329..a9b8d58715 100644
--- a/lib/rss/maker/dublincore.rb
+++ b/lib/rss/maker/dublincore.rb
@@ -7,94 +7,16 @@ module RSS
def self.append_features(klass)
super
- ::RSS::DublinCoreModel::ELEMENT_NAME_INFOS.each do |name, plural_name|
- plural_name ||= "#{name}s"
- full_name = "#{RSS::DC_PREFIX}_#{name}"
- full_plural_name = "#{RSS::DC_PREFIX}_#{plural_name}"
- klass_name = Utils.to_class_name(name)
- plural_klass_name = "DublinCore#{Utils.to_class_name(plural_name)}"
- full_plural_klass_name = "self.class::#{plural_klass_name}"
- full_klass_name = "#{full_plural_klass_name}::#{klass_name}"
- klass.add_need_initialize_variable(full_plural_name,
- "make_#{full_plural_name}")
- klass.add_other_element(full_plural_name)
- klass.module_eval(<<-EOC, __FILE__, __LINE__+1)
- attr_accessor :#{full_plural_name}
- def make_#{full_plural_name}
- #{full_plural_klass_name}.new(@maker)
- end
-
- def setup_#{full_plural_name}(rss, current)
- @#{full_plural_name}.to_rss(rss, current)
- end
-
- def #{full_name}
- @#{full_plural_name}[0] and @#{full_plural_name}[0].value
- end
-
- def #{full_name}=(new_value)
- @#{full_plural_name}[0] = #{full_klass_name}.new(self)
- @#{full_plural_name}[0].value = new_value
- end
-EOC
- end
- end
-
- ::RSS::DublinCoreModel::ELEMENT_NAME_INFOS.each do |name, plural_name|
- plural_name ||= "#{name}s"
- klass_name = Utils.to_class_name(name)
- plural_klass_name = "DublinCore#{Utils.to_class_name(plural_name)}"
- module_eval(<<-EOC, __FILE__, __LINE__)
- class #{plural_klass_name}Base
- include Base
-
- def_array_element(#{plural_name.dump})
-
- def new_#{name}
- #{name} = self.class::#{klass_name}.new(self)
- @#{plural_name} << #{name}
- #{name}
- end
-
- def to_rss(rss, current)
- @#{plural_name}.each do |#{name}|
- #{name}.to_rss(rss, current)
- end
- end
-
- class #{klass_name}Base
- include Base
-
- attr_accessor :value
- add_need_initialize_variable("value")
- alias_method(:content, :value)
- alias_method(:content=, :value=)
-
- def have_required_values?
- @value
- end
- end
- end
- EOC
- end
-
- def self.install_dublin_core(klass)
- ::RSS::DublinCoreModel::ELEMENT_NAME_INFOS.each do |name, plural_name|
- plural_name ||= "#{name}s"
- klass_name = Utils.to_class_name(name)
- plural_klass_name = "DublinCore#{Utils.to_class_name(plural_name)}"
- full_klass_name = "DublinCore#{klass_name}"
- klass.module_eval(<<-EOC, *Utils.get_file_and_line_from_caller(1))
- class #{plural_klass_name} < #{plural_klass_name}Base
- class #{klass_name} < #{klass_name}Base
- def to_rss(rss, current)
- if value and current.respond_to?(:dc_#{name})
- new_item = current.class::#{full_klass_name}.new(value)
- current.dc_#{plural_name} << new_item
- end
+ ::RSS::DublinCoreModel::ELEMENTS.each do |element|
+ klass.add_need_initialize_variable(element)
+ klass.add_other_element(element)
+ klass.__send__(:attr_accessor, element)
+ klass.module_eval(<<-EOC, __FILE__, __LINE__)
+ def setup_#{element}(rss, current)
+ if #{element} and current.respond_to?(:#{element}=)
+ current.#{element} = #{element}
end
end
- end
EOC
end
end
@@ -102,11 +24,11 @@ EOC
class ChannelBase
include DublinCoreModel
-
- remove_method(:date)
- remove_method(:date=)
- alias_method(:date, :dc_date)
- alias_method(:date=, :dc_date=)
+
+ undef_method(:dc_date)
+ undef_method(:dc_date=)
+ alias_method(:dc_date, :date)
+ alias_method(:dc_date=, :date=)
end
class ImageBase; include DublinCoreModel; end
@@ -114,52 +36,12 @@ EOC
class ItemBase
include DublinCoreModel
- remove_method(:date)
- remove_method(:date=)
- alias_method(:date, :dc_date)
- alias_method(:date=, :dc_date=)
+ undef_method(:dc_date)
+ undef_method(:dc_date=)
+ alias_method(:dc_date, :date)
+ alias_method(:dc_date=, :date=)
end
end
class TextinputBase; include DublinCoreModel; end
-
- class RSS10
- class Channel
- DublinCoreModel.install_dublin_core(self)
- end
-
- class Image
- DublinCoreModel.install_dublin_core(self)
- end
-
- class Items
- class Item
- DublinCoreModel.install_dublin_core(self)
- end
- end
-
- class Textinput
- DublinCoreModel.install_dublin_core(self)
- end
- end
-
- class RSS09
- class Channel
- DublinCoreModel.install_dublin_core(self)
- end
-
- class Image
- DublinCoreModel.install_dublin_core(self)
- end
-
- class Items
- class Item
- DublinCoreModel.install_dublin_core(self)
- end
- end
-
- class Textinput
- DublinCoreModel.install_dublin_core(self)
- end
- end
end
end
diff --git a/lib/rss/maker/image.rb b/lib/rss/maker/image.rb
deleted file mode 100644
index 85d9d9c95e..0000000000
--- a/lib/rss/maker/image.rb
+++ /dev/null
@@ -1,145 +0,0 @@
-require 'rss/image'
-require 'rss/maker/1.0'
-require 'rss/maker/dublincore'
-
-module RSS
- module Maker
- module ImageItemModel
- def self.append_features(klass)
- super
-
- name = "#{RSS::IMAGE_PREFIX}_item"
- klass.add_need_initialize_variable(name, "make_#{name}")
- klass.add_other_element(name)
- klass.module_eval(<<-EOC, __FILE__, __LINE__+1)
- attr_reader :#{name}
- def setup_#{name}(rss, current)
- if @#{name}
- @#{name}.to_rss(rss, current)
- end
- end
-
- def make_#{name}
- self.class::#{Utils.to_class_name(name)}.new(@maker)
- end
-EOC
- end
-
- class ImageItemBase
- include Base
- include Maker::DublinCoreModel
-
- attr_accessor :about, :resource, :image_width, :image_height
- add_need_initialize_variable("about")
- add_need_initialize_variable("resource")
- add_need_initialize_variable("image_width")
- add_need_initialize_variable("image_height")
- alias width= image_width=
- alias width image_width
- alias height= image_height=
- alias height image_height
-
- def have_required_values?
- @about
- end
- end
- end
-
- module ImageFaviconModel
- def self.append_features(klass)
- super
-
- name = "#{RSS::IMAGE_PREFIX}_favicon"
- klass.add_need_initialize_variable(name, "make_#{name}")
- klass.add_other_element(name)
- klass.module_eval(<<-EOC, __FILE__, __LINE__+1)
- attr_reader :#{name}
- def setup_#{name}(rss, current)
- if @#{name}
- @#{name}.to_rss(rss, current)
- end
- end
-
- def make_#{name}
- self.class::#{Utils.to_class_name(name)}.new(@maker)
- end
-EOC
- end
-
- class ImageFaviconBase
- include Base
- include Maker::DublinCoreModel
-
- attr_accessor :about, :image_size
- add_need_initialize_variable("about")
- add_need_initialize_variable("image_size")
- alias size image_size
- alias size= image_size=
-
- def have_required_values?
- @about and @image_size
- end
- end
- end
-
- class ChannelBase; include Maker::ImageFaviconModel; end
-
- class ItemsBase
- class ItemBase; include Maker::ImageItemModel; end
- end
-
- class RSS10
- class Items
- class Item
- class ImageItem < ImageItemBase
- DublinCoreModel.install_dublin_core(self)
- def to_rss(rss, current)
- if @about
- item = ::RSS::ImageItemModel::Item.new(@about, @resource)
- setup_values(item)
- setup_other_elements(item)
- current.image_item = item
- end
- end
- end
- end
- end
-
- class Channel
- class ImageFavicon < ImageFaviconBase
- DublinCoreModel.install_dublin_core(self)
- def to_rss(rss, current)
- if @about and @image_size
- args = [@about, @image_size]
- favicon = ::RSS::ImageFaviconModel::Favicon.new(*args)
- setup_values(favicon)
- setup_other_elements(favicon)
- current.image_favicon = favicon
- end
- end
- end
- end
- end
-
- class RSS09
- class Items
- class Item
- class ImageItem < ImageItemBase
- DublinCoreModel.install_dublin_core(self)
- def to_rss(*args)
- end
- end
- end
- end
-
- class Channel
- class ImageFavicon < ImageFaviconBase
- DublinCoreModel.install_dublin_core(self)
- def to_rss(*args)
- end
- end
- end
- end
-
- end
-end
diff --git a/lib/rss/maker/syndication.rb b/lib/rss/maker/syndication.rb
index 3717086257..72d00c63ea 100644
--- a/lib/rss/maker/syndication.rb
+++ b/lib/rss/maker/syndication.rb
@@ -10,8 +10,8 @@ module RSS
::RSS::SyndicationModel::ELEMENTS.each do |element|
klass.add_need_initialize_variable(element)
klass.add_other_element(element)
- klass.module_eval(<<-EOC, __FILE__, __LINE__+1)
- attr_accessor :#{element}
+ klass.__send__(:attr_accessor, element)
+ klass.module_eval(<<-EOC, __FILE__, __LINE__)
def setup_#{element}(rss, current)
if #{element} and current.respond_to?(:#{element}=)
current.#{element} = @#{element} if @#{element}
diff --git a/lib/rss/maker/trackback.rb b/lib/rss/maker/trackback.rb
index b334079582..1ec59ab0b0 100644
--- a/lib/rss/maker/trackback.rb
+++ b/lib/rss/maker/trackback.rb
@@ -1,6 +1,5 @@
require 'rss/trackback'
require 'rss/maker/1.0'
-require 'rss/maker/2.0'
module RSS
module Maker
@@ -8,65 +7,18 @@ module RSS
def self.append_features(klass)
super
- name = "#{RSS::TRACKBACK_PREFIX}_ping"
- klass.add_need_initialize_variable(name)
- klass.add_other_element(name)
- klass.module_eval(<<-EOC, __FILE__, __LINE__+1)
- attr_accessor :#{name}
- def setup_#{name}(rss, current)
- if #{name} and current.respond_to?(:#{name}=)
- current.#{name} = #{name}
+ %w(ping about).each do |element|
+ name = "#{RSS::TRACKBACK_PREFIX}_#{element}"
+ klass.add_need_initialize_variable(name)
+ klass.add_other_element(name)
+ klass.__send__(:attr_accessor, name)
+ klass.module_eval(<<-EOC, __FILE__, __LINE__)
+ def setup_#{name}(rss, current)
+ if #{name} and current.respond_to?(:#{name}=)
+ current.#{name} = @#{name} if @#{name}
+ end
end
- end
- EOC
-
- name = "#{RSS::TRACKBACK_PREFIX}_abouts"
- klass.add_need_initialize_variable(name, "make_#{name}")
- klass.add_other_element(name)
- klass.module_eval(<<-EOC, __FILE__, __LINE__+1)
- attr_accessor :#{name}
- def make_#{name}
- self.class::TrackBackAbouts.new(self)
- end
-
- def setup_#{name}(rss, current)
- @#{name}.to_rss(rss, current)
- end
- EOC
- end
-
- class TrackBackAboutsBase
- include Base
-
- def_array_element("abouts")
-
- def new_about
- about = self.class::About.new(@maker)
- @abouts << about
- about
- end
-
- def to_rss(rss, current)
- @abouts.each do |about|
- about.to_rss(rss, current)
- end
- end
-
- class AboutBase
- include Base
-
- attr_accessor :value
- add_need_initialize_variable("value")
-
- alias_method(:resource, :value)
- alias_method(:resource=, :value=)
- alias_method(:content, :value)
- alias_method(:content=, :value=)
-
- def have_required_values?
- @value
- end
-
+ EOC
end
end
end
@@ -74,53 +26,5 @@ module RSS
class ItemsBase
class ItemBase; include TrackBackModel; end
end
-
- class RSS10
- class Items
- class Item
- class TrackBackAbouts < TrackBackAboutsBase
- class About < AboutBase
- def to_rss(rss, current)
- if resource
- about = ::RSS::TrackBackModel10::About.new(resource)
- current.trackback_abouts << about
- end
- end
- end
- end
- end
- end
- end
-
- class RSS09
- class Items
- class Item
- class TrackBackAbouts < TrackBackAboutsBase
- def to_rss(*args)
- end
- class About < AboutBase
- end
- end
- end
- end
- end
-
- class RSS20
- class Items
- class Item
- class TrackBackAbouts < TrackBackAboutsBase
- class About < AboutBase
- def to_rss(rss, current)
- if content
- about = ::RSS::TrackBackModel20::About.new(content)
- current.trackback_abouts << about
- end
- end
- end
- end
- end
- end
- end
-
end
end
diff --git a/lib/rss/parser.rb b/lib/rss/parser.rb
index 6b3fe06419..09b3213372 100644
--- a/lib/rss/parser.rb
+++ b/lib/rss/parser.rb
@@ -1,5 +1,4 @@
require "forwardable"
-require "open-uri"
require "rss/rss"
@@ -78,36 +77,7 @@ module RSS
:do_validate=)
def initialize(rss, parser_class=self.class.default_parser)
- @parser = parser_class.new(normalize_rss(rss))
- end
-
- private
- def normalize_rss(rss)
- return rss if maybe_xml?(rss)
-
- uri = to_uri(rss)
-
- if uri.respond_to?(:read)
- uri.read
- elsif !rss.tainted? and File.readable?(rss)
- File.open(rss) {|f| f.read}
- else
- rss
- end
- end
-
- def maybe_xml?(source)
- source.is_a?(String) and /</ =~ source
- end
-
- def to_uri(rss)
- return rss if rss.is_a?(::URI::Generic)
-
- begin
- URI(rss)
- rescue ::URI::Error
- rss
- end
+ @parser = parser_class.new(rss)
end
end
@@ -153,18 +123,26 @@ module RSS
class << self
- @@setters = {}
+ @@setter = {}
@@registered_uris = {}
- @@class_names = {}
def install_setter(uri, tag_name, setter)
- @@setters[uri] ||= {}
- @@setters[uri][tag_name] = setter
+ @@setter[uri] = {} unless @@setter.has_key?(uri)
+ @@setter[uri][tag_name] = setter
+ end
+
+ def register_uri(name, uri)
+ @@registered_uris[name] = {} unless @@registered_uris.has_key?(name)
+ @@registered_uris[name][uri] = nil
+ end
+
+ def uri_registered?(name, uri)
+ @@registered_uris[name].has_key?(uri)
end
def setter(uri, tag_name)
begin
- @@setters[uri][tag_name]
+ @@setter[uri][tag_name]
rescue NameError
nil
end
@@ -172,35 +150,13 @@ module RSS
def available_tags(uri)
begin
- @@setters[uri].keys
+ @@setter[uri].keys
rescue NameError
[]
end
end
-
- def register_uri(uri, name)
- @@registered_uris[name] ||= {}
- @@registered_uris[name][uri] = nil
- end
-
- def uri_registered?(uri, name)
- @@registered_uris[name].has_key?(uri)
- end
-
- def install_class_name(uri, tag_name, class_name)
- @@class_names[uri] ||= {}
- @@class_names[uri][tag_name] = class_name
- end
-
- def class_name(uri, tag_name)
- begin
- @@class_names[uri][tag_name]
- rescue NameError
- tag_name[0,1].upcase + tag_name[1..-1]
- end
- end
-
- def install_get_text_element(uri, name, setter)
+
+ def install_get_text_element(name, uri, setter)
install_setter(uri, name, setter)
def_get_text_element(uri, name, *get_file_and_line_from_caller(1))
end
@@ -208,12 +164,12 @@ module RSS
private
def def_get_text_element(uri, name, file, line)
- register_uri(uri, name)
+ register_uri(name, uri)
unless private_instance_methods(false).include?("start_#{name}")
module_eval(<<-EOT, file, line)
def start_#{name}(name, prefix, attrs, ns)
uri = ns[prefix]
- if self.class.uri_registered?(uri, #{name.inspect})
+ if self.class.uri_registered?(#{name.inspect}, uri)
if @do_validate
tags = self.class.available_tags(uri)
unless tags.include?(name)
@@ -273,7 +229,7 @@ module RSS
ns = @ns_stack.last.dup
attrs = {}
attributes.each do |n, v|
- if /\Axmlns(?:\z|:)/ =~ n
+ if n =~ /\Axmlns:?/
ns[$POSTMATCH] = v
else
attrs[n] = v
@@ -300,7 +256,6 @@ module RSS
tags = @tag_stack.pop
pr = @proc_stack.pop
pr.call(text, tags) unless pr.nil?
- @ns_stack.pop
end
def text(data)
@@ -319,11 +274,13 @@ module RSS
end
def start_else_element(local, prefix, attrs, ns)
- class_name = self.class.class_name(ns[prefix], local)
+ class_name = local[0,1].upcase << local[1..-1]
current_class = @last_element.class
+# begin
if current_class.constants.include?(class_name)
next_class = current_class.const_get(class_name)
start_have_something_element(local, prefix, attrs, ns, next_class)
+# rescue NameError
else
if @ignore_unknown_element
@proc_stack.push(nil)
@@ -391,13 +348,6 @@ module RSS
end
if @do_validate and required and val.nil?
- unless a_uri.include?(nil)
- for prefix, uri in ns
- if a_uri.include?(uri)
- a_name = "#{prefix}:#{a_name}"
- end
- end
- end
raise MissingAttributeError.new(tag_name, a_name)
end
@@ -407,9 +357,10 @@ module RSS
previous = @last_element
next_element = klass.send(:new, *args)
next_element.do_validate = @do_validate
- prefix = ""
- prefix << "#{klass.required_prefix}_" if klass.required_prefix
- previous.instance_eval {set_next_element(prefix, tag_name, next_element)}
+ setter = ""
+ setter << "#{klass.required_prefix}_" if klass.required_prefix
+ setter << "#{tag_name}="
+ @last_element.send(setter, next_element)
@last_element = next_element
@proc_stack.push Proc.new { |text, tags|
p(@last_element.class) if DEBUG
diff --git a/lib/rss/rexmlparser.rb b/lib/rss/rexmlparser.rb
index 73e352a731..375b7794fb 100644
--- a/lib/rss/rexmlparser.rb
+++ b/lib/rss/rexmlparser.rb
@@ -36,7 +36,7 @@ module RSS
include ListenerMixin
def xmldecl(version, encoding, standalone)
- super(version, encoding, standalone == "yes")
+ super
# Encoding is converted to UTF-8 when REXML parse XML.
@encoding = 'UTF-8'
end
diff --git a/lib/rss/rss.rb b/lib/rss/rss.rb
index 0d3da8b51a..b6afa24b93 100644
--- a/lib/rss/rss.rb
+++ b/lib/rss/rss.rb
@@ -1,3 +1,10 @@
+# Copyright (c) 2003-2004 Kouhei Sutou. You can redistribute it and/or
+# modify it under the same terms as Ruby.
+#
+# Author:: Kouhei Sutou <kou@cozmixng.org>
+# Tutorial:: http://www.cozmixng.org/~rwiki/?cmd=view;name=RSS+Parser%3A%3ATutorial.en
+
+
require "time"
class Time
@@ -44,14 +51,6 @@ module Enumerable
end
end
-class Hash
- unless instance_methods.include?("merge")
- def merge(other)
- dup.update(other)
- end
- end
-end
-
require "English"
require "rss/utils"
require "rss/converter"
@@ -59,7 +58,7 @@ require "rss/xml-stylesheet"
module RSS
- VERSION = "0.1.5"
+ VERSION = "0.1.0"
URI = "http://purl.org/rss/1.0/"
@@ -145,15 +144,6 @@ module RSS
end
end
- class NotSetError < Error
- attr_reader :name, :variables
- def initialize(name, variables)
- @name = name
- @variables = variables
- super("required variables of #{@name} are not set: #{@variables.join(', ')}")
- end
- end
-
module BaseModel
include Utils
@@ -165,7 +155,7 @@ module RSS
install_element(name) do |n, elem_name|
<<-EOC
if @#{n}
- "\#{@#{n}.to_s(need_convert, indent)}"
+ "\#{@#{n}.to_s(convert, indent)}"
else
''
end
@@ -174,20 +164,17 @@ EOC
end
alias_method(:install_have_attribute_element, :install_have_child_element)
- def install_have_children_element(name, plural_name=nil)
- plural_name ||= "#{name}s"
- add_have_children_element(name, plural_name)
- add_plural_form(name, plural_name)
-
- def_children_accessor(name, plural_name)
- install_element(name, "s") do |n, elem_name|
+ def install_have_children_element(name, postfix="s")
+ add_have_children_element(name)
+
+ def_children_accessor(name, postfix)
+ install_element(name, postfix) do |n, elem_name|
<<-EOC
- rv = []
+ rv = ''
@#{n}.each do |x|
- value = "\#{x.to_s(need_convert, indent)}"
- rv << value if /\\A\\s*\\z/ !~ value
+ rv << "\#{x.to_s(convert, indent)}"
end
- rv.join("\n")
+ rv
EOC
end
end
@@ -203,8 +190,8 @@ EOC
if @#{n}
rv = "\#{indent}<#{elem_name}>"
value = html_escape(@#{n})
- if need_convert
- rv << convert(value)
+ if convert and @converter
+ rv << @converter.convert(value)
else
rv << value
end
@@ -223,15 +210,46 @@ EOC
# accessor
convert_attr_reader name
- date_writer(name, type, disp_name)
+ module_eval(<<-EOC, *get_file_and_line_from_caller(2))
+ def #{name}=(new_value)
+ if new_value.kind_of?(Time)
+ @#{name} = new_value
+ else
+ if @do_validate
+ begin
+ @#{name} = Time.send('#{type}', new_value)
+ rescue ArgumentError
+ raise NotAvailableValueError.new('#{disp_name}', new_value)
+ end
+ else
+ @#{name} = nil
+ if /\\A\\s*\\z/ !~ new_value.to_s
+ begin
+ @#{name} = Time.parse(new_value)
+ rescue ArgumentError
+ end
+ end
+ end
+ end
+
+ # Is it need?
+ if @#{name}
+ class << @#{name}
+ undef_method(:to_s)
+ alias_method(:to_s, :#{type})
+ end
+ end
+
+ end
+EOC
install_element(name) do |n, elem_name|
<<-EOC
if @#{n}
rv = "\#{indent}<#{elem_name}>"
value = html_escape(@#{n}.#{type})
- if need_convert
- rv << convert(value)
+ if convert and @converter
+ rv << @converter.convert(value)
else
rv << value
end
@@ -249,7 +267,7 @@ EOC
def install_element(name, postfix="")
elem_name = name.sub('_', ':')
module_eval(<<-EOC, *get_file_and_line_from_caller(2))
- def #{name}_element#{postfix}(need_convert=true, indent='')
+ def #{name}_element#{postfix}(convert=true, indent='')
#{yield(name, elem_name)}
end
private :#{name}_element#{postfix}
@@ -271,44 +289,9 @@ EOC
end
end
- def date_writer(name, type, disp_name=name)
+ def def_children_accessor(accessor_name, postfix="s")
module_eval(<<-EOC, *get_file_and_line_from_caller(2))
- def #{name}=(new_value)
- if new_value.nil? or new_value.kind_of?(Time)
- @#{name} = new_value
- else
- if @do_validate
- begin
- @#{name} = Time.send('#{type}', new_value)
- rescue ArgumentError
- raise NotAvailableValueError.new('#{disp_name}', new_value)
- end
- else
- @#{name} = nil
- if /\\A\\s*\\z/ !~ new_value.to_s
- begin
- @#{name} = Time.parse(new_value)
- rescue ArgumentError
- end
- end
- end
- end
-
- # Is it need?
- if @#{name}
- class << @#{name}
- undef_method(:to_s)
- alias_method(:to_s, :#{type})
- end
- end
-
- end
-EOC
- end
-
- def def_children_accessor(accessor_name, plural_name)
- module_eval(<<-EOC, *get_file_and_line_from_caller(2))
- def #{plural_name}
+ def #{accessor_name}#{postfix}
@#{accessor_name}
end
@@ -319,12 +302,8 @@ EOC
@#{accessor_name}.send("[]", *args)
end
end
-
+
def #{accessor_name}=(*args)
- warn("Warning:\#{caller.first.sub(/:in `.*'\z/, '')}: " \
- "Don't use `#{accessor_name} = XXX'/`set_#{accessor_name}(XXX)'. " \
- "Those APIs are not sense of Ruby. " \
- "Use `#{plural_name} << XXX' instead of them.")
if args.size == 1
@#{accessor_name}.push(args[0])
else
@@ -335,22 +314,6 @@ EOC
EOC
end
- def def_content_only_to_s
- module_eval(<<-EOC, *get_file_and_line_from_caller(2))
- def to_s(need_convert=true, indent=calc_indent)
- if @content
- rv = tag(indent) do |next_indent|
- h(@content)
- end
- rv = convert(rv) if need_convert
- rv
- else
- ""
- end
- end
-EOC
- end
-
end
class Element
@@ -360,112 +323,83 @@ EOC
INDENT = " "
- MUST_CALL_VALIDATORS = {}
- MODEL = []
- GET_ATTRIBUTES = []
- HAVE_CHILDREN_ELEMENTS = []
- NEED_INITIALIZE_VARIABLES = []
- PLURAL_FORMS = {}
-
class << self
- def must_call_validators
- MUST_CALL_VALIDATORS
- end
- def model
- MODEL
- end
- def get_attributes
- GET_ATTRIBUTES
- end
- def have_children_elements
- HAVE_CHILDREN_ELEMENTS
- end
- def need_initialize_variables
- NEED_INITIALIZE_VARIABLES
- end
- def plural_forms
- PLURAL_FORMS
- end
-
-
def inherited(klass)
- klass.const_set("MUST_CALL_VALIDATORS", {})
- klass.const_set("MODEL", [])
- klass.const_set("GET_ATTRIBUTES", [])
- klass.const_set("HAVE_CHILDREN_ELEMENTS", [])
- klass.const_set("NEED_INITIALIZE_VARIABLES", [])
- klass.const_set("PLURAL_FORMS", {})
-
klass.module_eval(<<-EOC)
public
- @tag_name = name.split(/::/).last
- @tag_name[0,1] = @tag_name[0,1].downcase
+ @tag_name = name.split(/::/).last.downcase
@indent_size = name.split(/::/).size - 2
- @have_content = false
+
+ @@must_call_validators = {}
def self.must_call_validators
- super.merge(MUST_CALL_VALIDATORS)
- end
- def self.model
- MODEL + super
- end
- def self.get_attributes
- GET_ATTRIBUTES + super
- end
- def self.have_children_elements
- HAVE_CHILDREN_ELEMENTS + super
- end
- def self.need_initialize_variables
- NEED_INITIALIZE_VARIABLES + super
- end
- def self.plural_forms
- super.merge(PLURAL_FORMS)
+ @@must_call_validators
end
-
def self.install_must_call_validator(prefix, uri)
- MUST_CALL_VALIDATORS[uri] = prefix
+ @@must_call_validators[uri] = prefix
end
+ @@model = []
+
+ def self.model
+ @@model
+ end
+
def self.install_model(tag, occurs=nil)
- if m = MODEL.find {|t, o| t == tag}
+ if m = @@model.find {|t, o| t == tag}
m[1] = occurs
else
- MODEL << [tag, occurs]
+ @@model << [tag, occurs]
end
end
+ @@get_attributes = []
+
+ def self.get_attributes()
+ @@get_attributes
+ end
+
def self.install_get_attribute(name, uri, required=true)
attr_writer name
convert_attr_reader name
- GET_ATTRIBUTES << [name, uri, required]
+ @@get_attributes << [name, uri, required]
end
+ @@have_content = false
+
def self.content_setup
attr_writer :content
convert_attr_reader :content
- def_content_only_to_s
- @have_content = true
+ @@have_content = true
end
def self.have_content?
- @have_content
+ @@have_content
+ end
+
+ @@have_children_elements = []
+
+ def self.have_children_elements
+ @@have_children_elements
end
- def self.add_have_children_element(variable_name, plural_name)
- HAVE_CHILDREN_ELEMENTS << [variable_name, plural_name]
+ def self.add_have_children_element(variable_name)
+ @@have_children_elements << variable_name
end
+ @@need_initialize_variables = []
+
def self.add_need_initialize_variable(variable_name)
- NEED_INITIALIZE_VARIABLES << variable_name
+ @@need_initialize_variables << variable_name
end
- def self.add_plural_form(singular, plural)
- PLURAL_FORMS[singular] = plural
+ def self.need_initialize_variables
+ @@need_initialize_variables
end
-
+
EOC
end
@@ -506,30 +440,10 @@ EOC
self.class.tag_name
end
- def full_name
- tag_name
- end
-
- def indent_size
- self.class.indent_size
- end
-
def converter=(converter)
@converter = converter
- targets = children.dup
- self.class.have_children_elements.each do |variable_name, plural_name|
- targets.concat(__send__(plural_name))
- end
- targets.each do |target|
- target.converter = converter unless target.nil?
- end
- end
-
- def convert(value)
- if @converter
- @converter.convert(value)
- else
- value
+ children.each do |child|
+ child.converter = converter unless child.nil?
end
end
@@ -543,15 +457,6 @@ EOC
__validate(tags, false)
end
- def setup_maker(maker)
- target = maker_target(maker)
- unless target.nil?
- setup_maker_attributes(target)
- setup_maker_element(target)
- setup_maker_elements(target)
- end
- end
-
private
def initialize_variables
self.class.need_initialize_variables.each do |variable_name|
@@ -562,122 +467,11 @@ EOC
end
def initialize_have_children_elements
- self.class.have_children_elements.each do |variable_name, plural_name|
+ self.class.have_children_elements.each do |variable_name|
instance_eval("@#{variable_name} = []")
end
end
- def tag(indent, additional_attrs=[], &block)
- next_indent = indent + INDENT
-
- attrs = collect_attrs
- return "" if attrs.nil?
-
- attrs += additional_attrs
- start_tag = make_start_tag(indent, next_indent, attrs)
-
- if block
- content = block.call(next_indent)
- else
- content = []
- end
-
- if content.is_a?(String)
- content = [content]
- start_tag << ">"
- end_tag = "</#{full_name}>"
- else
- content = content.reject{|x| x.empty?}
- if content.empty?
- end_tag = "/>"
- else
- start_tag << ">\n"
- end_tag = "\n#{indent}</#{full_name}>"
- end
- end
-
- start_tag + content.join("\n") + end_tag
- end
-
- def make_start_tag(indent, next_indent, attrs)
- start_tag = ["#{indent}<#{full_name}"]
- unless attrs.empty?
- start_tag << attrs.collect do |key, value|
- %Q[#{h key}="#{h value}"]
- end.join("\n#{next_indent}")
- end
- start_tag.join(" ")
- end
-
- def collect_attrs
- _attrs.collect do |name, required, alias_name|
- value = __send__(alias_name || name)
- return nil if required and value.nil?
- [name, value]
- end.reject do |name, value|
- value.nil?
- end
- end
-
- def tag_name_with_prefix(prefix)
- "#{prefix}:#{tag_name}"
- end
-
- def calc_indent
- INDENT * (self.class.indent_size)
- end
-
- def maker_target(maker)
- nil
- end
-
- def setup_maker_attributes(target)
- end
-
- def setup_maker_element(target)
- self.class.need_initialize_variables.each do |var|
- value = __send__(var)
- if value.respond_to?("setup_maker") and
- !not_need_to_call_setup_maker_variables.include?(var)
- value.setup_maker(target)
- else
- setter = "#{var}="
- if target.respond_to?(setter)
- target.__send__(setter, value)
- end
- end
- end
- end
-
- def not_need_to_call_setup_maker_variables
- []
- end
-
- def setup_maker_elements(parent)
- self.class.have_children_elements.each do |name, plural_name|
- real_name = name.sub(/^[^_]+_/, '')
- if parent.respond_to?(plural_name)
- target = parent.__send__(plural_name)
- __send__(plural_name).each do |elem|
- elem.setup_maker(target)
- end
- end
- end
- end
-
- def set_next_element(prefix, tag_name, next_element)
- klass = next_element.class
- prefix = ""
- prefix << "#{klass.required_prefix}_" if klass.required_prefix
- key = "#{prefix}#{tag_name}"
- if self.class.plural_forms.has_key?(key)
- ary = __send__("#{self.class.plural_forms[key]}")
- ary << next_element
- else
- __send__("#{prefix}#{tag_name}=", next_element)
- end
- end
-
# not String class children.
def children
[]
@@ -713,23 +507,23 @@ EOC
end
def validate_attribute
- _attrs.each do |a_name, required, alias_name|
- if required and __send__(alias_name || a_name).nil?
- raise MissingAttributeError.new(tag_name, a_name)
+ _attrs.each do |a_name, required|
+ if required and send(a_name).nil?
+ raise MissingAttributeError.new(self.class.tag_name, a_name)
end
end
end
- def other_element(need_convert, indent='')
- rv = []
+ def other_element(convert, indent='')
+ rv = ''
private_methods.each do |meth|
if /\A([^_]+)_[^_]+_elements?\z/ =~ meth and
self.class::NSPOOL.has_key?($1)
- res = __send__(meth, need_convert)
- rv << "#{indent}#{res}" if /\A\s*\z/ !~ res
+ res = send(meth, convert)
+ rv << "#{indent}#{res}\n" if /\A\s*\z/ !~ res
end
end
- rv.join("\n")
+ rv
end
def _validate(tags, model=self.class.model)
@@ -832,12 +626,19 @@ EOC
rv
end
+ private
+ def calc_indent
+ INDENT * (self.class.indent_size)
+ end
+
+ def remove_empty_newline(string)
+ string.gsub(/^\s*$(?:\r?\n?)/, '')
+ end
+
end
module RootElementMixin
- include XMLStyleSheetMixin
-
attr_reader :output_encoding
def initialize(rss_version, version=nil, encoding=nil, standalone=nil)
@@ -854,50 +655,26 @@ EOC
self.converter = Converter.new(@output_encoding, @encoding)
end
- def setup_maker(maker)
- maker.version = version
- maker.encoding = encoding
- maker.standalone = standalone
-
- xml_stylesheets.each do |xss|
- xss.setup_maker(maker)
- end
-
- setup_maker_elements(maker)
- end
-
private
- def tag(indent, attrs, &block)
- rv = xmldecl + xml_stylesheet_pi
- rv << super(indent, attrs, &block)
- rv
- end
-
def xmldecl
rv = %Q[<?xml version="#{@version}"]
if @output_encoding or @encoding
rv << %Q[ encoding="#{@output_encoding or @encoding}"]
end
- rv << %Q[ standalone="yes"] if @standalone
- rv << "?>\n"
+ rv << %Q[ standalone="#{@standalone}"] if @standalone
+ rv << '?>'
rv
end
- def ns_declarations
- self.class::NSPOOL.collect do |prefix, uri|
+ def ns_declaration(indent)
+ rv = ''
+ self.class::NSPOOL.each do |prefix, uri|
prefix = ":#{prefix}" unless prefix.empty?
- ["xmlns#{prefix}", uri]
+ rv << %Q|\n#{indent}xmlns#{prefix}="#{html_escape(uri)}"|
end
+ rv
end
- def setup_maker_elements(maker)
- channel.setup_maker(maker) if channel
- image.setup_maker(maker) if image
- textinput.setup_maker(maker) if textinput
- items.each do |item|
- item.setup_maker(maker)
- end
- end
end
end
diff --git a/lib/rss/syndication.rb b/lib/rss/syndication.rb
index 56976085a1..c274ff8c82 100644
--- a/lib/rss/syndication.rb
+++ b/lib/rss/syndication.rb
@@ -17,12 +17,12 @@ module RSS
super
klass.module_eval(<<-EOC, *get_file_and_line_from_caller(1))
- %w(updatePeriod updateFrequency).each do |name|
- install_text_element("\#{SY_PREFIX}_\#{name}")
+ %w(updatePeriod updateFrequency).each do |x|
+ install_text_element("\#{SY_PREFIX}_\#{x}")
end
- %w(updateBase).each do |name|
- install_date_element("\#{SY_PREFIX}_\#{name}", 'w3cdtf', name)
+ %w(updateBase).each do |x|
+ install_date_element("\#{SY_PREFIX}_\#{x}", 'w3cdtf', x)
end
alias_method(:_sy_updatePeriod=, :sy_updatePeriod=)
@@ -42,8 +42,8 @@ module RSS
def sy_validate(tags)
counter = {}
- ELEMENTS.each do |name|
- counter[name] = 0
+ ELEMENTS.each do |x|
+ counter[x] = 0
end
tags.each do |tag|
@@ -78,9 +78,8 @@ module RSS
prefix_size = SY_PREFIX.size + 1
SyndicationModel::ELEMENTS.uniq!
- SyndicationModel::ELEMENTS.each do |full_name|
- name = full_name[prefix_size..-1]
- BaseListener.install_get_text_element(SY_URI, name, "#{full_name}=")
+ SyndicationModel::ELEMENTS.each do |x|
+ BaseListener.install_get_text_element(x[prefix_size..-1], SY_URI, "#{x}=")
end
end
diff --git a/lib/rss/taxonomy.rb b/lib/rss/taxonomy.rb
index f70d475a11..bec6ea3c17 100644
--- a/lib/rss/taxonomy.rb
+++ b/lib/rss/taxonomy.rb
@@ -11,17 +11,17 @@ module RSS
TAXO_ELEMENTS = []
- %w(link).each do |name|
- full_name = "#{TAXO_PREFIX}_#{name}"
- BaseListener.install_get_text_element(TAXO_NS, name, "#{full_name}=")
- TAXO_ELEMENTS << "#{TAXO_PREFIX}_#{name}"
+ %w(link).each do |x|
+ if const_defined? :Listener
+ Listener.install_get_text_element(x, TAXO_NS, "#{TAXO_PREFIX}_#{x}=")
+ end
+ TAXO_ELEMENTS << "#{TAXO_PREFIX}_#{x}"
end
module TaxonomyModel
attr_writer(*%w(title description creator subject publisher
contributor date format identifier source
- language relation coverage rights
- ).collect{|name| "#{TAXO_PREFIX}_#{name}"})
+ language relation coverage rights).collect{|x| "#{TAXO_PREFIX}_#{x}"})
end
class Channel; extend TaxonomyModel; end
diff --git a/lib/rss/trackback.rb b/lib/rss/trackback.rb
index 6c083504ae..e276305ec1 100644
--- a/lib/rss/trackback.rb
+++ b/lib/rss/trackback.rb
@@ -9,12 +9,11 @@ module RSS
RDF.install_ns(TRACKBACK_PREFIX, TRACKBACK_URI)
Rss.install_ns(TRACKBACK_PREFIX, TRACKBACK_URI)
- module TrackBackUtils
- private
+ module BaseTrackBackModel
def trackback_validate(tags)
counter = {}
- %w(ping about).each do |name|
- counter["#{TRACKBACK_PREFIX}_#{name}"] = 0
+ %w(ping about).each do |x|
+ counter["#{TRACKBACK_PREFIX}_#{x}"] = 0
end
tags.each do |tag|
@@ -32,78 +31,24 @@ module RSS
end
end
end
-
- module BaseTrackBackModel
- def append_features(klass)
- super
- unless klass.class == Module
- klass.module_eval {include TrackBackUtils}
+ module TrackBackModel10
+ extend BaseModel
+ include BaseTrackBackModel
- %w(ping).each do |name|
- var_name = "#{TRACKBACK_PREFIX}_#{name}"
- klass_name = name.capitalize
- klass.install_have_child_element(var_name)
- klass.module_eval(<<-EOC, __FILE__, __LINE__)
- remove_method :#{var_name}
- def #{var_name}
- @#{var_name} and @#{var_name}.value
- end
+ def self.append_features(klass)
+ super
- remove_method :#{var_name}=
- def #{var_name}=(value)
- @#{var_name} = Utils.new_with_value_if_need(#{klass_name}, value)
- end
- EOC
+ unless klass.class == Module
+ %w(ping).each do |x|
+ klass.install_have_child_element("#{TRACKBACK_PREFIX}_#{x}")
end
- [%w(about s)].each do |name, postfix|
- var_name = "#{TRACKBACK_PREFIX}_#{name}"
- klass_name = name.capitalize
- klass.install_have_children_element(var_name)
- klass.module_eval(<<-EOC, __FILE__, __LINE__)
- remove_method :#{var_name}
- def #{var_name}(*args)
- if args.empty?
- @#{var_name}.first and @#{var_name}.first.value
- else
- ret = @#{var_name}.send("[]", *args)
- if ret.is_a?(Array)
- ret.collect {|x| x.value}
- else
- ret.value
- end
- end
- end
-
- remove_method :#{var_name}=
- remove_method :set_#{var_name}
- def #{var_name}=(*args)
- if args.size == 1
- item = Utils.new_with_value_if_need(#{klass_name}, args[0])
- @#{var_name}.push(item)
- else
- new_val = args.last
- if new_val.is_a?(Array)
- new_val = new_value.collect do |val|
- Utils.new_with_value_if_need(#{klass_name}, val)
- end
- else
- new_val = Utils.new_with_value_if_need(#{klass_name}, new_val)
- end
- @#{var_name}.send("[]=", *(args[0..-2] + [new_val]))
- end
- end
- alias set_#{var_name} #{var_name}=
- EOC
+ %w(about).each do |x|
+ klass.install_have_children_element("#{TRACKBACK_PREFIX}_#{x}")
end
end
end
- end
-
- module TrackBackModel10
- extend BaseModel
- extend BaseTrackBackModel
class Ping < Element
include RSS10
@@ -126,28 +71,26 @@ module RSS
install_get_attribute(name, uri, required)
end
- alias_method(:value, :resource)
- alias_method(:value=, :resource=)
-
def initialize(resource=nil)
super()
@resource = resource
end
- def full_name
- tag_name_with_prefix(TRACKBACK_PREFIX)
- end
-
- def to_s(need_convert=true, indent=calc_indent)
- rv = tag(indent)
- rv = convert(rv) if need_convert
- rv
+ def to_s(convert=true, indent=calc_indent)
+ if @resource
+ rv = %Q[#{indent}<#{TRACKBACK_PREFIX}:ping ]
+ rv << %Q[#{::RSS::RDF::PREFIX}:resource="#{h @resource}"/>]
+ rv = @converter.convert(rv) if convert and @converter
+ rv
+ else
+ ''
+ end
end
private
def _attrs
[
- ["#{::RSS::RDF::PREFIX}:resource", true, "resource"],
+ ["resource", true],
]
end
@@ -174,45 +117,118 @@ module RSS
install_get_attribute(name, uri, required)
end
- alias_method(:value, :resource)
- alias_method(:value=, :resource=)
-
def initialize(resource=nil)
super()
@resource = resource
end
- def full_name
- tag_name_with_prefix(TRACKBACK_PREFIX)
- end
-
- def to_s(need_convert=true, indent=calc_indent)
- rv = tag(indent)
- rv = convert(rv) if need_convert
- rv
+ def to_s(convert=true, indent=calc_indent)
+ if @resource
+ rv = %Q[#{indent}<#{TRACKBACK_PREFIX}:about ]
+ rv << %Q[#{::RSS::RDF::PREFIX}:resource="#{h @resource}"/>]
+ rv = @converter.convert(rv) if convert and @converter
+ rv
+ else
+ ''
+ end
end
private
def _attrs
[
- ["#{::RSS::RDF::PREFIX}:resource", true, "resource"],
+ ["resource", true],
]
end
- def maker_target(abouts)
- abouts.new_about
- end
-
- def setup_maker_attributes(about)
- about.resource = self.resource
- end
-
end
end
module TrackBackModel20
+ include BaseTrackBackModel
extend BaseModel
- extend BaseTrackBackModel
+
+ def self.append_features(klass)
+ super
+
+ unless klass.class == Module
+ %w(ping).each do |x|
+ var_name = "#{TRACKBACK_PREFIX}_#{x}"
+ klass.install_have_child_element(var_name)
+ klass.module_eval(<<-EOC)
+ alias _#{var_name} #{var_name}
+ def #{var_name}
+ @#{var_name} and @#{var_name}.content
+ end
+
+ alias _#{var_name}= #{var_name}=
+ def #{var_name}=(content)
+ @#{var_name} = new_with_content_if_need(#{x.capitalize}, content)
+ end
+ EOC
+ end
+
+ [%w(about s)].each do |x, postfix|
+ var_name = "#{TRACKBACK_PREFIX}_#{x}"
+ klass.install_have_children_element(var_name)
+ klass.module_eval(<<-EOC)
+ alias _#{var_name}#{postfix} #{var_name}#{postfix}
+ def #{var_name}#{postfix}
+ @#{var_name}.collect {|x| x.content}
+ end
+
+ alias _#{var_name} #{var_name}
+ def #{var_name}(*args)
+ if args.empty?
+ @#{var_name}.first and @#{var_name}.first.content
+ else
+ ret = @#{var_name}.send("[]", *args)
+ if ret.is_a?(Array)
+ ret.collect {|x| x.content}
+ else
+ ret.content
+ end
+ end
+ end
+
+ alias _#{var_name}= #{var_name}=
+ alias _set_#{var_name} set_#{var_name}
+ def #{var_name}=(*args)
+ if args.size == 1
+ item = new_with_content_if_need(#{x.capitalize}, args[0])
+ @#{var_name}.push(item)
+ else
+ new_val = args.last
+ if new_val.is_a?(Array)
+ new_val = new_value.collect do |val|
+ new_with_content_if_need(#{x.capitalize}, val)
+ end
+ else
+ new_val = new_with_content_if_need(#{x.capitalize}, new_val)
+ end
+ @#{var_name}.send("[]=", *(args[0..-2] + [new_val]))
+ end
+ end
+ alias set_#{var_name} #{var_name}=
+ EOC
+ end
+ end
+ end
+
+ private
+ def new_with_content(klass, content)
+ obj = klass.new
+ obj.content = content
+ obj
+ end
+
+ def new_with_content_if_need(klass, content)
+ if content.is_a?(klass)
+ content
+ else
+ new_with_content(klass, content)
+ end
+ end
+
class Ping < Element
include RSS09
@@ -231,18 +247,18 @@ module RSS
end
- alias_method(:value, :content)
- alias_method(:value=, :content=)
-
- def initialize(content=nil)
- super()
- @content = content
- end
-
- def full_name
- tag_name_with_prefix(TRACKBACK_PREFIX)
+ def to_s(convert=true, indent=calc_indent)
+ if @content
+ rv = %Q[#{indent}<#{TRACKBACK_PREFIX}:ping>]
+ rv << h(@content)
+ rv << %Q[</#{TRACKBACK_PREFIX}:ping>]
+ rv = @converter.convert(rv) if convert and @converter
+ rv
+ else
+ ''
+ end
end
-
+
end
class About < Element
@@ -261,19 +277,19 @@ module RSS
end
end
-
- alias_method(:value, :content)
- alias_method(:value=, :content=)
-
- def initialize(content=nil)
- super()
- @content = content
- end
- def full_name
- tag_name_with_prefix(TRACKBACK_PREFIX)
+ def to_s(convert=true, indent=calc_indent)
+ if @content
+ rv = %Q[#{indent}<#{TRACKBACK_PREFIX}:about>]
+ rv << h(@content)
+ rv << %Q[</#{TRACKBACK_PREFIX}:about>]
+ rv = @converter.convert(rv) if convert and @converter
+ rv
+ else
+ ''
+ end
end
-
+
end
end
diff --git a/lib/rss/utils.rb b/lib/rss/utils.rb
index 0286becf00..1c30ae74bc 100644
--- a/lib/rss/utils.rb
+++ b/lib/rss/utils.rb
@@ -2,13 +2,6 @@ module RSS
module Utils
- module_function
- def to_class_name(name)
- name.split(/_/).collect do |part|
- "#{part[0, 1].upcase}#{part[1..-1]}"
- end.join("")
- end
-
def get_file_and_line_from_caller(i=0)
file, line, = caller[i].split(':')
[file, line.to_i]
@@ -19,13 +12,6 @@ module RSS
end
alias h html_escape
- def new_with_value_if_need(klass, value)
- if value.is_a?(klass)
- value
- else
- klass.new(value)
- end
- end
end
end
diff --git a/lib/rss/xml-stylesheet.rb b/lib/rss/xml-stylesheet.rb
index 05602eee9b..c51c0dc71a 100644
--- a/lib/rss/xml-stylesheet.rb
+++ b/lib/rss/xml-stylesheet.rb
@@ -84,13 +84,6 @@ module RSS
@alternate
end
- def setup_maker(maker)
- xss = maker.xml_stylesheets.new_xml_stylesheet
- ATTRIBUTES.each do |attr|
- xss.__send__("#{attr}=", __send__(attr))
- end
- end
-
private
def guess_type(filename)
/\.([^.]+)$/ =~ filename
diff --git a/lib/rss/xmlscanner.rb b/lib/rss/xmlscanner.rb
index c5a11bad18..472ca93523 100644
--- a/lib/rss/xmlscanner.rb
+++ b/lib/rss/xmlscanner.rb
@@ -45,7 +45,7 @@ module RSS
end
def on_xmldecl_end
- xmldecl(@version, @encoding, @standalone == "yes")
+ xmldecl(@version, @encoding, @standalone)
end
alias_method(:on_pi, :instruction)
diff --git a/lib/set.rb b/lib/set.rb
index 0ad47c842f..23d7b847ef 100644
--- a/lib/set.rb
+++ b/lib/set.rb
@@ -251,7 +251,7 @@ class Set
# Merges the elements of the given enumerable object to the set and
# returns self.
def merge(enum)
- if enum.is_a?(Set)
+ if enum.class == self.class
@hash.update(enum.instance_eval { @hash })
else
enum.is_a?(Enumerable) or raise ArgumentError, "value must be enumerable"
@@ -291,7 +291,7 @@ class Set
def &(enum)
enum.is_a?(Enumerable) or raise ArgumentError, "value must be enumerable"
n = self.class.new
- enum.each { |o| n.add(o) if include?(o) }
+ enum.each { |o| include?(o) and n.add(o) }
n
end
alias intersection & ##
@@ -313,8 +313,7 @@ class Set
set.is_a?(Set) && size == set.size or return false
- hash = @hash.dup
- set.all? { |o| hash.include?(o) }
+ set.all? { |o| include?(o) }
end
def hash # :nodoc:
@@ -322,8 +321,7 @@ class Set
end
def eql?(o) # :nodoc:
- return false unless o.is_a?(Set)
- @hash.eql?(o.instance_eval{@hash})
+ @hash.hash == o.hash
end
# Classifies the set by the return value of the given block and
@@ -440,11 +438,6 @@ class SortedSet < Set
def setup # :nodoc:
@@setup and return
- module_eval {
- # a hack to shut up warning
- alias old_init initialize
- remove_method :old_init
- }
begin
require 'rbtree'
@@ -519,7 +512,6 @@ end
module Enumerable
# Makes a set from the enumerable object with given arguments.
- # Needs to +require "set"+ to use this method.
def to_set(klass = Set, *args, &block)
klass.new(self, *args, &block)
end
@@ -591,9 +583,7 @@ end
# else
# instance_eval %{
# def add(o)
-# if @proc.call(o)
-# @hash[o] = true
-# end
+# @hash[o] = true if @proc.call(o)
# self
# end
# alias << add
@@ -1065,8 +1055,6 @@ class TC_Set < Test::Unit::TestCase
# assert_equal(set2, set1)
assert_equal(set2, set2.clone)
assert_equal(set1.clone, set1)
-
- assert_not_equal(Set[Exception.new,nil], Set[Exception.new,Exception.new], "[ruby-dev:26127]")
end
# def test_hash
diff --git a/lib/shellwords.rb b/lib/shellwords.rb
index e87b9e656b..99c0bf8437 100644
--- a/lib/shellwords.rb
+++ b/lib/shellwords.rb
@@ -41,8 +41,8 @@ module Shellwords
snippet = $1
elsif line =~ /\A'/ then
raise ArgumentError, "Unmatched single quote: #{line}"
- elsif line.sub!(/\A\\(.)?/, '') then
- snippet = $1 || '\\'
+ elsif line.sub!(/\A\\(.)/, '') then
+ snippet = $1
elsif line.sub!(/\A([^\s\\'"]+)/, '') then
snippet = $1
else
diff --git a/lib/singleton.rb b/lib/singleton.rb
index 0ab8517275..18fda0bc58 100644
--- a/lib/singleton.rb
+++ b/lib/singleton.rb
@@ -16,11 +16,11 @@
# * ``The instance'' is created at instantiation time, in other
# words the first call of Klass.instance(), thus
#
-# class OtherKlass
+# class OtherKlass
# include Singleton
# # ...
-# end
-# ObjectSpace.each_object(OtherKlass){} # => 0.
+# end
+# ObjectSpace.each_object(OtherKlass){} # => 0.
#
# * This behavior is preserved under inheritance and cloning.
#
diff --git a/lib/soap/baseData.rb b/lib/soap/baseData.rb
index 0e8b00d450..49c1d2d1f4 100644
--- a/lib/soap/baseData.rb
+++ b/lib/soap/baseData.rb
@@ -1,5 +1,5 @@
# soap/baseData.rb: SOAP4R - Base type library
-# Copyright (C) 2000, 2001, 2003-2005 NAKAMURA, Hiroshi <nahi@ruby-lang.org>.
+# Copyright (C) 2000, 2001, 2003, 2004 NAKAMURA, Hiroshi <nahi@ruby-lang.org>.
# This program is copyrighted free software by NAKAMURA, Hiroshi. You can
# redistribute it and/or modify it under the same terms of Ruby's license;
@@ -44,9 +44,9 @@ module SOAPType
attr_accessor :definedtype
def initialize(*arg)
- super
+ super(*arg)
@encodingstyle = nil
- @elename = XSD::QName::EMPTY
+ @elename = XSD::QName.new
@id = nil
@precedents = []
@root = false
@@ -56,14 +56,6 @@ module SOAPType
@extraattr = {}
end
- def inspect
- if self.is_a?(XSD::NSDBase)
- sprintf("#<%s:0x%x %s %s>", self.class.name, __id__, self.elename, self.type)
- else
- sprintf("#<%s:0x%x %s>", self.class.name, __id__, self.elename)
- end
- end
-
def rootnode
node = self
while node = node.parent
@@ -82,7 +74,7 @@ module SOAPBasetype
include SOAP
def initialize(*arg)
- super
+ super(*arg)
end
end
@@ -95,7 +87,7 @@ module SOAPCompoundtype
include SOAP
def initialize(*arg)
- super
+ super(*arg)
end
end
@@ -114,7 +106,7 @@ public
# Override the definition in SOAPBasetype.
def initialize(obj = nil)
super()
- @type = XSD::QName::EMPTY
+ @type = XSD::QName.new
@refid = nil
@obj = nil
__setobj__(obj) if obj
@@ -178,7 +170,7 @@ class SOAPExternalReference < XSD::NSDBase
def initialize
super()
- @type = XSD::QName::EMPTY
+ @type = XSD::QName.new
end
def referred
@@ -327,16 +319,6 @@ class SOAPInteger < XSD::XSDInteger
extend SOAPModuleUtils
end
-class SOAPNonPositiveInteger < XSD::XSDNonPositiveInteger
- include SOAPBasetype
- extend SOAPModuleUtils
-end
-
-class SOAPNegativeInteger < XSD::XSDNegativeInteger
- include SOAPBasetype
- extend SOAPModuleUtils
-end
-
class SOAPLong < XSD::XSDLong
include SOAPBasetype
extend SOAPModuleUtils
@@ -352,41 +334,6 @@ class SOAPShort < XSD::XSDShort
extend SOAPModuleUtils
end
-class SOAPByte < XSD::XSDByte
- include SOAPBasetype
- extend SOAPModuleUtils
-end
-
-class SOAPNonNegativeInteger < XSD::XSDNonNegativeInteger
- include SOAPBasetype
- extend SOAPModuleUtils
-end
-
-class SOAPUnsignedLong < XSD::XSDUnsignedLong
- include SOAPBasetype
- extend SOAPModuleUtils
-end
-
-class SOAPUnsignedInt < XSD::XSDUnsignedInt
- include SOAPBasetype
- extend SOAPModuleUtils
-end
-
-class SOAPUnsignedShort < XSD::XSDUnsignedShort
- include SOAPBasetype
- extend SOAPModuleUtils
-end
-
-class SOAPUnsignedByte < XSD::XSDUnsignedByte
- include SOAPBasetype
- extend SOAPModuleUtils
-end
-
-class SOAPPositiveInteger < XSD::XSDPositiveInteger
- include SOAPBasetype
- extend SOAPModuleUtils
-end
-
###
## Compound datatypes.
@@ -399,7 +346,7 @@ public
def initialize(type = nil)
super()
- @type = type || XSD::QName::EMPTY
+ @type = type || XSD::QName.new
@array = []
@data = []
end
@@ -407,7 +354,7 @@ public
def to_s()
str = ''
self.each do |key, data|
- str << "#{key}: #{data}\n"
+ str << "#{ key }: #{ data }\n"
end
str
end
@@ -450,30 +397,9 @@ public
@array
end
- def to_obj
- hash = {}
- proptype = {}
- each do |k, v|
- value = v.respond_to?(:to_obj) ? v.to_obj : v.to_s
- case proptype[k]
- when :single
- hash[k] = [hash[k], value]
- proptype[k] = :multi
- when :multi
- hash[k] << value
- else
- hash[k] = value
- proptype[k] = :single
- end
- end
- hash
- end
-
def each
- idx = 0
- while idx < @array.length
- yield(@array[idx], @data[idx])
- idx += 1
+ for i in 0..(@array.length - 1)
+ yield(@array[i], @data[i])
end
end
@@ -531,20 +457,15 @@ class SOAPElement
@position = nil
@extraattr = {}
- @qualified = nil
+ @qualified = false
@array = []
@data = []
@text = text
end
- def inspect
- sprintf("#<%s:0x%x %s>", self.class.name, __id__, self.elename)
- end
-
# Text interface.
attr_accessor :text
- alias data text
# Element interfaces.
def add(value)
@@ -581,29 +502,16 @@ class SOAPElement
@text
else
hash = {}
- proptype = {}
each do |k, v|
- value = v.respond_to?(:to_obj) ? v.to_obj : v.to_s
- case proptype[k]
- when :single
- hash[k] = [hash[k], value]
- proptype[k] = :multi
- when :multi
- hash[k] << value
- else
- hash[k] = value
- proptype[k] = :single
- end
+ hash[k] = v.is_a?(SOAPElement) ? v.to_obj : v.to_s
end
hash
end
end
def each
- idx = 0
- while idx < @array.length
- yield(@array[idx], @data[idx])
- idx += 1
+ for i in 0..(@array.length - 1)
+ yield(@array[i], @data[i])
end
end
@@ -612,41 +520,20 @@ class SOAPElement
o
end
- def self.from_obj(obj, namespace = nil)
+ def self.from_obj(hash_or_string)
o = SOAPElement.new(nil)
- case obj
- when nil
- o.text = nil
- when Hash
- obj.each do |elename, value|
- if value.is_a?(Array)
- value.each do |subvalue|
- child = from_obj(subvalue, namespace)
- child.elename = to_elename(elename, namespace)
- o.add(child)
- end
- else
- child = from_obj(value, namespace)
- child.elename = to_elename(elename, namespace)
- o.add(child)
- end
+ if hash_or_string.is_a?(Hash)
+ hash_or_string.each do |k, v|
+ child = self.from_obj(v)
+ child.elename = k.is_a?(XSD::QName) ? k : XSD::QName.new(nil, k.to_s)
+ o.add(child)
end
else
- o.text = obj.to_s
+ o.text = hash_or_string
end
o
end
- def self.to_elename(obj, namespace = nil)
- if obj.is_a?(XSD::QName)
- obj
- elsif /\A(.+):([^:]+)\z/ =~ obj.to_s
- XSD::QName.new($1, $2)
- else
- XSD::QName.new(namespace, obj.to_s)
- end
- end
-
private
def add_member(name, value)
@@ -657,31 +544,24 @@ private
value
end
- if RUBY_VERSION > "1.7.0"
- def add_accessor(name)
- methodname = name
- if self.respond_to?(methodname)
- methodname = safe_accessor_name(methodname)
- end
- Mapping.define_singleton_method(self, methodname) do
- @data[@array.index(name)]
- end
- Mapping.define_singleton_method(self, methodname + '=') do |value|
- @data[@array.index(name)] = value
- end
+ def add_accessor(name)
+ methodname = name
+ if self.respond_to?(methodname)
+ methodname = safe_accessor_name(methodname)
end
- else
- def add_accessor(name)
- methodname = safe_accessor_name(name)
+ begin
instance_eval <<-EOS
- def #{methodname}
- @data[@array.index(#{name.dump})]
+ def #{ methodname }()
+ @data[@array.index('#{ name }')]
end
- def #{methodname}=(value)
- @data[@array.index(#{name.dump})] = value
+ def #{ methodname }=(value)
+ @data[@array.index('#{ name }')] = value
end
EOS
+ rescue SyntaxError
+ methodname = safe_accessor_name(methodname)
+ retry
end
end
@@ -705,7 +585,7 @@ public
def initialize(type = nil, rank = 1, arytype = nil)
super()
- @type = type || ValueArrayName
+ @type = type || XSD::QName.new
@rank = rank
@data = Array.new
@sparse = false
@@ -727,7 +607,7 @@ public
def [](*idxary)
if idxary.size != @rank
- raise ArgumentError.new("given #{idxary.size} params does not match rank: #{@rank}")
+ raise ArgumentError.new("Given #{ idxary.size } params does not match rank: #{ @rank }")
end
retrieve(idxary)
@@ -737,29 +617,30 @@ public
value = idxary.slice!(-1)
if idxary.size != @rank
- raise ArgumentError.new("given #{idxary.size} params(#{idxary})" +
- " does not match rank: #{@rank}")
+ raise ArgumentError.new("Given #{ idxary.size } params(#{ idxary }) does not match rank: #{ @rank }")
end
- idx = 0
- while idx < idxary.size
- if idxary[idx] + 1 > @size[idx]
- @size[idx] = idxary[idx] + 1
+ for i in 0..(idxary.size - 1)
+ if idxary[i] + 1 > @size[i]
+ @size[i] = idxary[i] + 1
end
- idx += 1
end
data = retrieve(idxary[0, idxary.size - 1])
data[idxary.last] = value
if value.is_a?(SOAPType)
- value.elename = ITEM_NAME
+ value.elename = value.elename.dup_name('item')
+
# Sync type
unless @type.name
@type = XSD::QName.new(value.type.namespace,
SOAPArray.create_arytype(value.type.name, @rank))
end
- value.type ||= @type
+
+ unless value.type
+ value.type = @type
+ end
end
@offset = idxary
@@ -789,7 +670,7 @@ public
deep_map(ele, &block)
else
new_obj = block.call(ele)
- new_obj.elename = ITEM_NAME
+ new_obj.elename = new_obj.elename.dup_name('item')
new_obj
end
end
@@ -817,15 +698,13 @@ public
def soap2array(ary)
traverse_data(@data) do |v, *position|
iteary = ary
- rank = 1
- while rank < position.size
+ for rank in 1..(position.size - 1)
idx = position[rank - 1]
if iteary[idx].nil?
iteary = iteary[idx] = Array.new
else
iteary = iteary[idx]
end
- rank += 1
end
if block_given?
iteary[position.last] = yield(v)
@@ -841,26 +720,21 @@ public
private
- ITEM_NAME = XSD::QName.new(nil, 'item')
-
def retrieve(idxary)
data = @data
- rank = 1
- while rank <= idxary.size
+ for rank in 1..(idxary.size)
idx = idxary[rank - 1]
if data[idx].nil?
data = data[idx] = Array.new
else
data = data[idx]
end
- rank += 1
end
data
end
def traverse_data(data, rank = 1)
- idx = 0
- while idx < ranksize(rank)
+ for idx in 0..(ranksize(rank) - 1)
if rank < @rank
traverse_data(data[idx], rank + 1) do |*v|
v[1, 0] = idx
@@ -869,7 +743,6 @@ private
else
yield(data[idx], idx)
end
- idx += 1
end
end
@@ -924,7 +797,7 @@ public
private
def self.create_arytype(typename, rank)
- "#{typename}[" << ',' * (rank - 1) << ']'
+ "#{ typename }[" << ',' * (rank - 1) << ']'
end
TypeParseRegexp = Regexp.new('^(.+)\[([\d,]*)\]$')
diff --git a/lib/soap/element.rb b/lib/soap/element.rb
index cc58b5d341..1494cd61dd 100644
--- a/lib/soap/element.rb
+++ b/lib/soap/element.rb
@@ -1,5 +1,5 @@
# SOAP4R - SOAP elements library
-# Copyright (C) 2000, 2001, 2003-2005 NAKAMURA, Hiroshi <nahi@ruby-lang.org>.
+# Copyright (C) 2000, 2001, 2003, 2004 NAKAMURA, Hiroshi <nahi@ruby-lang.org>.
# This program is copyrighted free software by NAKAMURA, Hiroshi. You can
# redistribute it and/or modify it under the same terms of Ruby's license;
@@ -83,10 +83,10 @@ public
attrs[ns.name(AttrEncodingStyleName)] = EncodingNamespace
name = ns.name(@elename)
generator.encode_tag(name, attrs)
- yield(self.faultcode)
- yield(self.faultstring)
- yield(self.faultactor)
- yield(self.detail) if self.detail
+ yield(self.faultcode, false)
+ yield(self.faultstring, false)
+ yield(self.faultactor, false)
+ yield(self.detail, false) if self.detail
generator.encode_tag_end(name, true)
end
end
@@ -99,15 +99,7 @@ class SOAPBody < SOAPStruct
super(nil)
@elename = EleBodyName
@encodingstyle = nil
- if data
- if data.respond_to?(:elename)
- add(data.elename.name, data)
- else
- data.to_a.each do |datum|
- add(datum.elename.name, datum)
- end
- end
- end
+ add(data.elename.name, data) if data
@is_fault = is_fault
end
@@ -115,10 +107,10 @@ class SOAPBody < SOAPStruct
name = ns.name(@elename)
generator.encode_tag(name, attrs)
if @is_fault
- yield(@data)
+ yield(@data, true)
else
@data.each do |data|
- yield(data)
+ yield(data, true)
end
end
generator.encode_tag_end(name, true)
@@ -137,7 +129,7 @@ class SOAPBody < SOAPStruct
end
end
- raise Parser::FormatDecodeError.new('no root element')
+ raise SOAPParser::FormatDecodeError.new('No root element.')
end
end
@@ -171,7 +163,7 @@ public
@element.extraattr[ns.name(AttrEncodingStyleName)] = @encodingstyle
end
@element.encodingstyle = @encodingstyle if !@element.encodingstyle
- yield(@element)
+ yield(@element, true)
end
end
@@ -189,7 +181,7 @@ class SOAPHeader < SOAPStruct
name = ns.name(@elename)
generator.encode_tag(name, attrs)
@data.each do |data|
- yield(data)
+ yield(data, true)
end
generator.encode_tag_end(name, true)
end
@@ -239,12 +231,13 @@ class SOAPEnvelope < XSD::NSDBase
end
def encode(generator, ns, attrs = {})
- SOAPGenerator.assign_ns(attrs, ns, elename.namespace, SOAPNamespaceTag)
+ SOAPGenerator.assign_ns(attrs, ns, EnvelopeNamespace,
+ SOAPNamespaceTag)
name = ns.name(@elename)
generator.encode_tag(name, attrs)
- yield(@header) if @header and @header.length > 0
- yield(@body)
+ yield(@header, true) if @header and @header.length > 0
+ yield(@body, true)
generator.encode_tag_end(name, true)
end
diff --git a/lib/soap/encodingstyle/aspDotNetHandler.rb b/lib/soap/encodingstyle/aspDotNetHandler.rb
index fd7e0fa217..e976433a7b 100644
--- a/lib/soap/encodingstyle/aspDotNetHandler.rb
+++ b/lib/soap/encodingstyle/aspDotNetHandler.rb
@@ -1,5 +1,5 @@
# SOAP4R - ASP.NET EncodingStyle handler library
-# Copyright (C) 2001, 2003, 2005 NAKAMURA, Hiroshi <nahi@ruby-lang.org>.
+# Copyright (C) 2001, 2003 NAKAMURA, Hiroshi <nahi@ruby-lang.org>.
# This program is copyrighted free software by NAKAMURA, Hiroshi. You can
# redistribute it and/or modify it under the same terms of Ruby's license;
@@ -27,45 +27,51 @@ class ASPDotNetHandler < Handler
###
## encode interface.
#
- def encode_data(generator, ns, data, parent)
+ def encode_data(generator, ns, qualified, data, parent)
attrs = {}
- # ASPDotNetHandler is intended to be used for accessing an ASP.NET doc/lit
- # service as an rpc/encoded service. in the situation, local elements
- # should be qualified. propagate parent's namespace to children.
- if data.elename.namespace.nil?
- data.elename.namespace = parent.elename.namespace
- end
- name = generator.encode_name(ns, data, attrs)
+ name = if qualified and data.elename.namespace
+ SOAPGenerator.assign_ns(attrs, ns, data.elename.namespace)
+ ns.name(data.elename)
+ else
+ data.elename.name
+ end
+
case data
when SOAPRawString
generator.encode_tag(name, attrs)
generator.encode_rawstring(data.to_s)
when XSD::XSDString
generator.encode_tag(name, attrs)
- generator.encode_string(@charset ?
- XSD::Charset.encoding_to_xml(data.to_s, @charset) : data.to_s)
+ generator.encode_string(@charset ? XSD::Charset.encoding_to_xml(data.to_s, @charset) : data.to_s)
when XSD::XSDAnySimpleType
generator.encode_tag(name, attrs)
generator.encode_string(data.to_s)
when SOAPStruct
generator.encode_tag(name, attrs)
data.each do |key, value|
- generator.encode_child(ns, value, data)
+ if !value.elename.namespace
+ value.elename.namespace = data.elename.namespace
+ end
+ yield(value, true)
end
when SOAPArray
generator.encode_tag(name, attrs)
data.traverse do |child, *rank|
data.position = nil
- generator.encode_child(ns, child, data)
+ yield(child, true)
end
else
- raise EncodingStyleError.new(
- "unknown object:#{data} in this encodingStyle")
+ raise EncodingStyleError.new("Unknown object:#{ data } in this encodingSt
+yle.")
end
end
- def encode_data_end(generator, ns, data, parent)
- name = generator.encode_name_end(ns, data)
+ def encode_data_end(generator, ns, qualified, data, parent)
+ name = if qualified and data.elename.namespace
+ ns.name(data.elename)
+ else
+ data.elename.name
+ end
cr = data.is_a?(SOAPCompoundtype)
generator.encode_tag_end(name, cr)
end
@@ -113,6 +119,7 @@ class ASPDotNetHandler < Handler
end
def decode_tag(ns, elename, attrs, parent)
+ # ToDo: check if @textbuf is empty...
@textbuf = ''
o = SOAPUnknown.new(self, elename)
o.parent = parent
@@ -183,11 +190,11 @@ class ASPDotNetHandler < Handler
end
when SOAPBasetype
- raise EncodingStyleError.new("SOAP base type must not have a child")
+ raise EncodingStyleError.new("SOAP base type must not have a child.")
else
# SOAPUnknown does not have parent.
- # raise EncodingStyleError.new("illegal parent: #{parent}")
+ # raise EncodingStyleError.new("Illegal parent: #{ parent }.")
end
end
diff --git a/lib/soap/encodingstyle/handler.rb b/lib/soap/encodingstyle/handler.rb
index c015417435..7bf65a2fd5 100644
--- a/lib/soap/encodingstyle/handler.rb
+++ b/lib/soap/encodingstyle/handler.rb
@@ -58,12 +58,12 @@ class Handler
## encode interface.
#
# Returns a XML instance as a string.
- def encode_data(generator, ns, data, parent)
- raise NotImplementError
+ def encode_data(generator, ns, qualified, data, parent)
+ raise NotImplementError.new('Method encode_data must be defined in derived class.')
end
- def encode_data_end(generator, ns, data, parent)
- raise NotImplementError
+ def encode_data_end(generator, ns, qualified, data, parent)
+ raise NotImplementError.new('Method encode_data must be defined in derived class.')
end
def encode_prologue
diff --git a/lib/soap/encodingstyle/literalHandler.rb b/lib/soap/encodingstyle/literalHandler.rb
index 59c7205366..72a10b2daa 100644
--- a/lib/soap/encodingstyle/literalHandler.rb
+++ b/lib/soap/encodingstyle/literalHandler.rb
@@ -1,5 +1,5 @@
# SOAP4R - XML Literal EncodingStyle handler library
-# Copyright (C) 2001, 2003-2005 NAKAMURA, Hiroshi <nahi@ruby-lang.org>.
+# Copyright (C) 2001, 2003, 2004 NAKAMURA, Hiroshi <nahi@ruby-lang.org>.
# This program is copyrighted free software by NAKAMURA, Hiroshi. You can
# redistribute it and/or modify it under the same terms of Ruby's license;
@@ -26,21 +26,15 @@ class LiteralHandler < Handler
###
## encode interface.
#
- def encode_data(generator, ns, data, parent)
+ def encode_data(generator, ns, qualified, data, parent)
attrs = {}
- name = generator.encode_name(ns, data, attrs)
- data.extraattr.each do |k, v|
- # ToDo: check generator.attributeformdefault here
- if k.is_a?(XSD::QName)
- if k.namespace
- SOAPGenerator.assign_ns(attrs, ns, k.namespace)
- k = ns.name(k)
- else
- k = k.name
- end
+ name = if qualified and data.elename.namespace
+ SOAPGenerator.assign_ns(attrs, ns, data.elename.namespace)
+ ns.name(data.elename)
+ else
+ data.elename.name
end
- attrs[k] = v
- end
+
case data
when SOAPRawString
generator.encode_tag(name, attrs)
@@ -56,36 +50,35 @@ class LiteralHandler < Handler
when SOAPStruct
generator.encode_tag(name, attrs)
data.each do |key, value|
- generator.encode_child(ns, value, data)
+ if !value.elename.namespace
+ value.elename.namespace = data.elename.namespace
+ end
+ yield(value, true)
end
when SOAPArray
generator.encode_tag(name, attrs)
data.traverse do |child, *rank|
data.position = nil
- generator.encode_child(ns, child, data)
+ yield(child, true)
end
when SOAPElement
- # passes 2 times for simplifying namespace definition
- data.each do |key, value|
- if value.elename.namespace
- SOAPGenerator.assign_ns(attrs, ns, value.elename.namespace)
- end
- end
- generator.encode_tag(name, attrs)
+ generator.encode_tag(name, attrs.update(data.extraattr))
generator.encode_rawstring(data.text) if data.text
data.each do |key, value|
- generator.encode_child(ns, value, data)
+ yield(value, qualified)
end
else
- raise EncodingStyleError.new(
- "unknown object:#{data} in this encodingStyle")
+ raise EncodingStyleError.new("Unknown object:#{ data } in this encodingStyle.")
end
end
- def encode_data_end(generator, ns, data, parent)
- name = generator.encode_name_end(ns, data)
- cr = (data.is_a?(SOAPCompoundtype) or
- (data.is_a?(SOAPElement) and !data.text))
+ def encode_data_end(generator, ns, qualified, data, parent)
+ name = if qualified and data.elename.namespace
+ ns.name(data.elename)
+ else
+ data.elename.name
+ end
+ cr = data.is_a?(SOAPElement) && !data.text
generator.encode_tag_end(name, cr)
end
@@ -135,6 +128,7 @@ class LiteralHandler < Handler
end
def decode_tag(ns, elename, attrs, parent)
+ # ToDo: check if @textbuf is empty...
@textbuf = ''
o = SOAPUnknown.new(self, elename, decode_attrs(ns, attrs))
o.parent = parent
@@ -165,7 +159,7 @@ class LiteralHandler < Handler
def decode_attrs(ns, attrs)
extraattr = {}
attrs.each do |key, value|
- qname = ns.parse_local(key)
+ qname = ns.parse(key)
extraattr[qname] = value
end
extraattr
@@ -178,19 +172,21 @@ class LiteralHandler < Handler
end
def decode_parent(parent, node)
- return unless parent.node
case parent.node
when SOAPUnknown
newparent = parent.node.as_element
node.parent = newparent
parent.replace_node(newparent)
decode_parent(parent, node)
+
when SOAPElement
parent.node.add(node)
node.parent = parent.node
+
when SOAPStruct
parent.node.add(node.elename.name, node)
node.parent = parent.node
+
when SOAPArray
if node.position
parent.node[*(decode_arypos(node.position))] = node
@@ -199,8 +195,13 @@ class LiteralHandler < Handler
parent.node.add(node)
end
node.parent = parent.node
+
+ when SOAPBasetype
+ raise EncodingStyleError.new("SOAP base type must not have a child.")
+
else
- raise EncodingStyleError.new("illegal parent: #{parent.node}")
+ # SOAPUnknown does not have parent.
+ raise EncodingStyleError.new("Illegal parent: #{ parent }.")
end
end
diff --git a/lib/soap/encodingstyle/soapHandler.rb b/lib/soap/encodingstyle/soapHandler.rb
index a522392625..114060bd02 100644
--- a/lib/soap/encodingstyle/soapHandler.rb
+++ b/lib/soap/encodingstyle/soapHandler.rb
@@ -1,5 +1,5 @@
# SOAP4R - SOAP EncodingStyle handler library
-# Copyright (C) 2001, 2003, 2005 NAKAMURA, Hiroshi <nahi@ruby-lang.org>.
+# Copyright (C) 2001, 2003 NAKAMURA, Hiroshi <nahi@ruby-lang.org>.
# This program is copyrighted free software by NAKAMURA, Hiroshi. You can
# redistribute it and/or modify it under the same terms of Ruby's license;
@@ -29,12 +29,21 @@ class SOAPHandler < Handler
###
## encode interface.
#
- def encode_data(generator, ns, data, parent)
+ def encode_data(generator, ns, qualified, data, parent)
attrs = encode_attrs(generator, ns, data, parent)
+
if parent && parent.is_a?(SOAPArray) && parent.position
- attrs[ns.name(AttrPositionName)] = "[#{parent.position.join(',')}]"
+ attrs[ns.name(AttrPositionName)] = "[#{ parent.position.join(',') }]"
+ end
+
+ name = nil
+ if qualified and data.elename.namespace
+ SOAPGenerator.assign_ns(attrs, ns, data.elename.namespace)
+ name = ns.name(data.elename)
+ else
+ name = data.elename.name
end
- name = generator.encode_name(ns, data, attrs)
+
case data
when SOAPReference
attrs['href'] = data.refidstr
@@ -56,22 +65,26 @@ class SOAPHandler < Handler
when SOAPStruct
generator.encode_tag(name, attrs)
data.each do |key, value|
- generator.encode_child(ns, value, data)
+ yield(value, false)
end
when SOAPArray
generator.encode_tag(name, attrs)
data.traverse do |child, *rank|
data.position = data.sparse ? rank : nil
- generator.encode_child(ns, child, data)
+ yield(child, false)
end
else
raise EncodingStyleError.new(
- "unknown object:#{data} in this encodingStyle")
+ "Unknown object:#{ data } in this encodingStyle.")
end
end
- def encode_data_end(generator, ns, data, parent)
- name = generator.encode_name_end(ns, data)
+ def encode_data_end(generator, ns, qualified, data, parent)
+ name = if qualified and data.elename.namespace
+ ns.name(data.elename)
+ else
+ data.elename.name
+ end
cr = data.is_a?(SOAPCompoundtype)
generator.encode_tag_end(name, cr)
end
@@ -143,6 +156,7 @@ class SOAPHandler < Handler
end
def decode_tag(ns, elename, attrs, parent)
+ # ToDo: check if @textbuf is empty...
@textbuf = ''
is_nil, type, arytype, root, offset, position, href, id, extraattr =
decode_attrs(ns, attrs)
@@ -213,7 +227,6 @@ class SOAPHandler < Handler
end
def decode_parent(parent, node)
- return unless parent.node
case parent.node
when SOAPUnknown
newparent = parent.node.as_struct
@@ -234,8 +247,10 @@ class SOAPHandler < Handler
parent.node.add(node)
end
node.parent = parent.node
+ when SOAPBasetype
+ raise EncodingStyleError.new("SOAP base type must not have a child.")
else
- raise EncodingStyleError.new("illegal parent: #{parent.node}")
+ raise EncodingStyleError.new("Illegal parent: #{ parent.node }.")
end
end
@@ -251,12 +266,12 @@ private
def create_arytype(ns, data)
XSD::QName.new(data.arytype.namespace,
- content_typename(data.arytype.name) + "[#{data.size.join(',')}]")
+ content_typename(data.arytype.name) + "[#{ data.size.join(',') }]")
end
def encode_attrs(generator, ns, data, parent)
+ return {} if data.is_a?(SOAPReference)
attrs = {}
- return attrs if data.is_a?(SOAPReference)
if !parent || parent.encodingstyle != EncodingNamespace
if @generate_explicit_type
@@ -368,7 +383,7 @@ private
def decode_definedtype(elename, typename, typedef, arytypestr)
unless typedef
- raise EncodingStyleError.new("unknown type '#{typename}'")
+ raise EncodingStyleError.new("Unknown type '#{ typename }'.")
end
if typedef.is_a?(::WSDL::XMLSchema::SimpleType)
decode_defined_simpletype(elename, typename, typedef, arytypestr)
@@ -389,7 +404,7 @@ private
def decode_defined_complextype(elename, typename, typedef, arytypestr)
case typedef.compoundtype
- when :TYPE_STRUCT, :TYPE_MAP
+ when :TYPE_STRUCT
o = SOAPStruct.decode(elename, typename)
o.definedtype = typedef
return o
@@ -406,13 +421,6 @@ private
end
o.definedtype = typedef
return o
- when :TYPE_EMPTY
- o = SOAPNil.decode(elename)
- o.definedtype = typedef
- return o
- else
- raise RuntimeError.new(
- "Unknown kind of complexType: #{typedef.compoundtype}")
end
nil
end
@@ -498,7 +506,7 @@ private
case qname.name
when XSD::NilLiteral
is_nil = NilLiteralMap[value] or
- raise EncodingStyleError.new("cannot accept attribute value: #{value} as the value of xsi:#{XSD::NilLiteral} (expected 'true', 'false', '1', or '0')")
+ raise EncodingStyleError.new("Cannot accept attribute value: #{ value } as the value of xsi:#{ XSD::NilLiteral } (expected 'true', 'false', '1', or '0').")
next
when XSD::AttrType
type = value
@@ -512,7 +520,7 @@ private
when AttrRoot
root = RootLiteralMap[value] or
raise EncodingStyleError.new(
- "illegal root attribute value: #{value}")
+ "Illegal root attribute value: #{ value }.")
next
when AttrOffset
offset = value
@@ -529,7 +537,6 @@ private
id = value
next
end
- qname = ns.parse_local(key)
extraattr[qname] = decode_attr_value(ns, qname, value)
end
@@ -567,7 +574,7 @@ private
ref.__setobj__(o)
false
else
- raise EncodingStyleError.new("unresolved reference: #{ref.refid}")
+ raise EncodingStyleError.new("Unresolved reference: #{ ref.refid }.")
end
}
count -= 1
diff --git a/lib/soap/generator.rb b/lib/soap/generator.rb
index f179555e1d..edd90492c6 100644
--- a/lib/soap/generator.rb
+++ b/lib/soap/generator.rb
@@ -1,5 +1,5 @@
# SOAP4R - SOAP XML Instance Generator library.
-# Copyright (C) 2001, 2003, 2005 NAKAMURA, Hiroshi <nahi@ruby-lang.org>.
+# Copyright (C) 2001, 2003 NAKAMURA, Hiroshi <nahi@ruby-lang.org>.
# This program is copyrighted free software by NAKAMURA, Hiroshi. You can
# redistribute it and/or modify it under the same terms of Ruby's license;
@@ -28,19 +28,14 @@ public
attr_accessor :charset
attr_accessor :default_encodingstyle
attr_accessor :generate_explicit_type
- attr_accessor :use_numeric_character_reference
def initialize(opt = {})
@reftarget = nil
@handlers = {}
- @charset = opt[:charset] || XSD::Charset.xml_encoding_label
+ @charset = opt[:charset] || XSD::Charset.encoding_label
@default_encodingstyle = opt[:default_encodingstyle] || EncodingNamespace
@generate_explicit_type =
opt.key?(:generate_explicit_type) ? opt[:generate_explicit_type] : true
- @elementformdefault = opt[:elementformdefault]
- @attributeformdefault = opt[:attributeformdefault]
- @use_numeric_character_reference = opt[:use_numeric_character_reference]
- @indentstr = opt[:no_indent] ? '' : ' '
@buf = @indent = @curr = nil
end
@@ -55,7 +50,7 @@ public
ns = XSD::NS.new
@buf << xmldecl
- encode_data(ns, obj, nil)
+ encode_data(ns, true, obj, nil)
@handlers.each do |uri, handler|
handler.encode_epilogue
@@ -65,33 +60,42 @@ public
@buf
end
- def encode_data(ns, obj, parent)
+ def encode_data(ns, qualified, obj, parent)
if obj.is_a?(SOAPEnvelopeElement)
- encode_element(ns, obj, parent)
+ encode_element(ns, qualified, obj, parent)
return
end
+
if @reftarget && !obj.precedents.empty?
add_reftarget(obj.elename.name, obj)
ref = SOAPReference.new(obj)
- ref.elename = ref.elename.dup_name(obj.elename.name)
+ ref.elename.name = obj.elename.name
obj.precedents.clear # Avoid cyclic delay.
obj.encodingstyle = parent.encodingstyle
# SOAPReference is encoded here.
obj = ref
end
+
encodingstyle = obj.encodingstyle
# Children's encodingstyle is derived from its parent.
encodingstyle ||= parent.encodingstyle if parent
obj.encodingstyle = encodingstyle
+
handler = find_handler(encodingstyle || @default_encodingstyle)
unless handler
raise FormatEncodeError.new("Unknown encodingStyle: #{ encodingstyle }.")
end
+
if !obj.elename.name
raise FormatEncodeError.new("Element name not defined: #{ obj }.")
end
- handler.encode_data(self, ns, obj, parent)
- handler.encode_data_end(self, ns, obj, parent)
+
+ handler.encode_data(self, ns, qualified, obj, parent) do |child, nextq|
+ indent_backup, @indent = @indent, @indent + ' '
+ encode_data(ns.clone_ns, nextq, child, obj)
+ @indent = indent_backup
+ end
+ handler.encode_data_end(self, ns, qualified, obj, parent)
end
def add_reftarget(name, node)
@@ -101,19 +105,13 @@ public
@reftarget.add(name, node)
end
- def encode_child(ns, child, parent)
- indent_backup, @indent = @indent, @indent + @indentstr
- encode_data(ns.clone_ns, child, parent)
- @indent = indent_backup
- end
-
- def encode_element(ns, obj, parent)
+ def encode_element(ns, qualified, obj, parent)
attrs = {}
if obj.is_a?(SOAPBody)
@reftarget = obj
- obj.encode(self, ns, attrs) do |child|
- indent_backup, @indent = @indent, @indent + @indentstr
- encode_data(ns.clone_ns, child, obj)
+ obj.encode(self, ns, attrs) do |child, nextq|
+ indent_backup, @indent = @indent, @indent + ' '
+ encode_data(ns.clone_ns, nextq, child, obj)
@indent = indent_backup
end
@reftarget = nil
@@ -126,35 +124,14 @@ public
SOAPGenerator.assign_ns(attrs, ns, XSD::Namespace, XSDNamespaceTag)
end
end
- obj.encode(self, ns, attrs) do |child|
- indent_backup, @indent = @indent, @indent + @indentstr
- encode_data(ns.clone_ns, child, obj)
+ obj.encode(self, ns, attrs) do |child, nextq|
+ indent_backup, @indent = @indent, @indent + ' '
+ encode_data(ns.clone_ns, nextq, child, obj)
@indent = indent_backup
end
end
end
- def encode_name(ns, data, attrs)
- if element_local?(data)
- data.elename.name
- else
- if element_qualified?(data)
- SOAPGenerator.assign_ns(attrs, ns, data.elename.namespace, '')
- else
- SOAPGenerator.assign_ns(attrs, ns, data.elename.namespace)
- end
- ns.name(data.elename)
- end
- end
-
- def encode_name_end(ns, data)
- if element_local?(data)
- data.elename.name
- else
- ns.name(data.elename)
- end
- end
-
def encode_tag(elename, attrs = nil)
if !attrs or attrs.empty?
@buf << "\n#{ @indent }<#{ elename }>"
@@ -165,7 +142,7 @@ public
@buf << "\n#{ @indent }<#{ elename } " <<
attrs.collect { |key, value|
%Q[#{ key }="#{ value }"]
- }.join("\n#{ @indent }#{ @indentstr * 2 }") <<
+ }.join("\n#{ @indent } ") <<
'>'
end
end
@@ -192,48 +169,13 @@ public
}
EncodeCharRegexp = Regexp.new("[#{EncodeMap.keys.join}]")
def encode_string(str)
- if @use_numeric_character_reference and !XSD::Charset.is_us_ascii(str)
- str.gsub!(EncodeCharRegexp) { |c| EncodeMap[c] }
- @buf << str.unpack("U*").collect { |c|
- if c == 0x9 or c == 0xa or c == 0xd or (c >= 0x20 and c <= 0x7f)
- c.chr
- else
- sprintf("&#x%x;", c)
- end
- }.join
- else
- @buf << str.gsub(EncodeCharRegexp) { |c| EncodeMap[c] }
- end
- end
-
- def element_local?(element)
- element.elename.namespace.nil?
- end
-
- def element_qualified?(element)
- if element.respond_to?(:qualified)
- if element.qualified.nil?
- @elementformdefault
- else
- element.qualified
- end
- else
- @elementformdefault
- end
+ @buf << str.gsub(EncodeCharRegexp) { |c| EncodeMap[c] }
end
def self.assign_ns(attrs, ns, namespace, tag = nil)
- if namespace.nil?
- raise FormatEncodeError.new("empty namespace")
- end
- unless ns.assigned?(namespace)
+ if namespace and !ns.assigned?(namespace)
tag = ns.assign(namespace, tag)
- if tag == ''
- attr = 'xmlns'
- else
- attr = "xmlns:#{tag}"
- end
- attrs[attr] = namespace
+ attrs['xmlns:' << tag] = namespace
end
end
diff --git a/lib/soap/header/handlerset.rb b/lib/soap/header/handlerset.rb
index a8eee03023..499d6bb8a1 100644
--- a/lib/soap/header/handlerset.rb
+++ b/lib/soap/header/handlerset.rb
@@ -18,12 +18,6 @@ class HandlerSet
@store = XSD::NamedElements.new
end
- def dup
- obj = HandlerSet.new
- obj.store = @store.dup
- obj
- end
-
def add(handler)
@store << handler
end
@@ -57,12 +51,6 @@ class HandlerSet
end
end
end
-
-protected
-
- def store=(store)
- @store = store
- end
end
diff --git a/lib/soap/header/simplehandler.rb b/lib/soap/header/simplehandler.rb
index 7b206f77db..e7268e04a3 100644
--- a/lib/soap/header/simplehandler.rb
+++ b/lib/soap/header/simplehandler.rb
@@ -1,5 +1,5 @@
# SOAP4R - SOAP Simple header item handler
-# Copyright (C) 2003-2005 NAKAMURA, Hiroshi <nahi@ruby-lang.org>.
+# Copyright (C) 2003, 2004 NAKAMURA, Hiroshi <nahi@ruby-lang.org>.
# This program is copyrighted free software by NAKAMURA, Hiroshi. You can
# redistribute it and/or modify it under the same terms of Ruby's license;
@@ -19,22 +19,22 @@ class SimpleHandler < SOAP::Header::Handler
super(elename)
end
- # Should return a Hash, String or nil.
+ # Should return a Hash or nil.
def on_simple_outbound
nil
end
- # Given header is a Hash, String or nil.
+ # Given header is a Hash or nil.
def on_simple_inbound(header, mustunderstand)
end
def on_outbound
h = on_simple_outbound
- h ? SOAPElement.from_obj(h, elename.namespace) : nil
+ h ? SOAPElement.from_obj(h) : nil
end
def on_inbound(header, mustunderstand)
- h = header.respond_to?(:to_obj) ? header.to_obj : header.data
+ h = header.to_obj
on_simple_inbound(h, mustunderstand)
end
end
diff --git a/lib/soap/httpconfigloader.rb b/lib/soap/httpconfigloader.rb
deleted file mode 100644
index cd7bca8a65..0000000000
--- a/lib/soap/httpconfigloader.rb
+++ /dev/null
@@ -1,119 +0,0 @@
-# SOAP4R - HTTP config loader.
-# Copyright (C) 2005 NAKAMURA, Hiroshi <nahi@ruby-lang.org>.
-
-# This program is copyrighted free software by NAKAMURA, Hiroshi. You can
-# redistribute it and/or modify it under the same terms of Ruby's license;
-# either the dual license version in 2003, or any later version.
-
-
-require 'soap/property'
-
-
-module SOAP
-
-
-module HTTPConfigLoader
-module_function
-
- def set_options(client, options)
- client.proxy = options["proxy"]
- options.add_hook("proxy") do |key, value|
- client.proxy = value
- end
- client.no_proxy = options["no_proxy"]
- options.add_hook("no_proxy") do |key, value|
- client.no_proxy = value
- end
- if client.respond_to?(:protocol_version=)
- client.protocol_version = options["protocol_version"]
- options.add_hook("protocol_version") do |key, value|
- client.protocol_version = value
- end
- end
- ssl_config = options["ssl_config"] ||= ::SOAP::Property.new
- set_ssl_config(client, ssl_config)
- ssl_config.add_hook(true) do |key, value|
- set_ssl_config(client, ssl_config)
- end
- basic_auth = options["basic_auth"] ||= ::SOAP::Property.new
- set_basic_auth(client, basic_auth)
- basic_auth.add_hook do |key, value|
- set_basic_auth(client, basic_auth)
- end
- options.add_hook("connect_timeout") do |key, value|
- client.connect_timeout = value
- end
- options.add_hook("send_timeout") do |key, value|
- client.send_timeout = value
- end
- options.add_hook("receive_timeout") do |key, value|
- client.receive_timeout = value
- end
- end
-
- def set_basic_auth(client, basic_auth)
- basic_auth.values.each do |url, userid, passwd|
- client.set_basic_auth(url, userid, passwd)
- end
- end
-
- def set_ssl_config(client, ssl_config)
- ssl_config.each do |key, value|
- cfg = client.ssl_config
- if cfg.nil?
- raise NotImplementedError.new("SSL not supported")
- end
- case key
- when 'client_cert'
- cfg.client_cert = cert_from_file(value)
- when 'client_key'
- cfg.client_key = key_from_file(value)
- when 'client_ca'
- cfg.client_ca = value
- when 'ca_path'
- cfg.set_trust_ca(value)
- when 'ca_file'
- cfg.set_trust_ca(value)
- when 'crl'
- cfg.set_crl(value)
- when 'verify_mode'
- cfg.verify_mode = ssl_config_int(value)
- when 'verify_depth'
- cfg.verify_depth = ssl_config_int(value)
- when 'options'
- cfg.options = value
- when 'ciphers'
- cfg.ciphers = value
- when 'verify_callback'
- cfg.verify_callback = value
- when 'cert_store'
- cfg.cert_store = value
- else
- raise ArgumentError.new("unknown ssl_config property #{key}")
- end
- end
- end
-
- def ssl_config_int(value)
- if value.nil? or value.to_s.empty?
- nil
- else
- begin
- Integer(value)
- rescue ArgumentError
- ::SOAP::Property::Util.const_from_name(value.to_s)
- end
- end
- end
-
- def cert_from_file(filename)
- OpenSSL::X509::Certificate.new(File.open(filename) { |f| f.read })
- end
-
- def key_from_file(filename)
- OpenSSL::PKey::RSA.new(File.open(filename) { |f| f.read })
- end
-end
-
-
-end
diff --git a/lib/soap/mapping/factory.rb b/lib/soap/mapping/factory.rb
index 978b303b3d..6b9ac1eeaa 100644
--- a/lib/soap/mapping/factory.rb
+++ b/lib/soap/mapping/factory.rb
@@ -27,6 +27,39 @@ class Factory
# return convert_succeeded_or_not, obj
end
+ if Object.respond_to?(:allocate)
+ # ruby/1.7 or later.
+ def create_empty_object(klass)
+ klass.allocate
+ end
+ else
+ MARSHAL_TAG = {
+ String => ['"', 1],
+ Regexp => ['/', 2],
+ Array => ['[', 1],
+ Hash => ['{', 1]
+ }
+ def create_empty_object(klass)
+ if klass <= Struct
+ name = klass.name
+ return ::Marshal.load(sprintf("\004\006S:%c%s\000", name.length + 5, name))
+ end
+ if MARSHAL_TAG.has_key?(klass)
+ tag, terminate = MARSHAL_TAG[klass]
+ return ::Marshal.load(sprintf("\004\006%s%s", tag, "\000" * terminate))
+ end
+ MARSHAL_TAG.each do |k, v|
+ if klass < k
+ name = klass.name
+ tag, terminate = v
+ return ::Marshal.load(sprintf("\004\006C:%c%s%s%s", name.length + 5, name, tag, "\000" * terminate))
+ end
+ end
+ name = klass.name
+ ::Marshal.load(sprintf("\004\006o:%c%s\000", name.length + 5, name))
+ end
+ end
+
def setiv2obj(obj, node, map)
return if node.nil?
if obj.is_a?(Array)
@@ -37,28 +70,24 @@ class Factory
end
def setiv2soap(node, obj, map)
- if obj.class.class_variables.include?('@@schema_element')
- obj.class.class_eval('@@schema_element').each do |name, info|
- type, qname = info
- if qname
- elename = qname.name
- else
- elename = Mapping.name2elename(name)
- end
- node.add(elename,
- Mapping._obj2soap(obj.instance_variable_get('@' + name), map))
- end
- else
- # should we sort instance_variables?
- obj.instance_variables.each do |var|
- name = var.sub(/^@/, '')
- elename = Mapping.name2elename(name)
- node.add(elename,
- Mapping._obj2soap(obj.instance_variable_get(var), map))
- end
+ # should we sort instance_variables?
+ obj.instance_variables.each do |var|
+ name = var.sub(/^@/, '')
+ node.add(Mapping.name2elename(name),
+ Mapping._obj2soap(obj.instance_eval(var), map))
end
end
+ # It breaks Thread.current[:SOAPMarshalDataKey].
+ def mark_marshalled_obj(obj, soap_obj)
+ Thread.current[:SOAPMarshalDataKey][obj.__id__] = soap_obj
+ end
+
+ # It breaks Thread.current[:SOAPMarshalDataKey].
+ def mark_unmarshalled_obj(node, obj)
+ Thread.current[:SOAPMarshalDataKey][node.id] = obj
+ end
+
private
def setiv2ary(obj, node, map)
@@ -72,7 +101,7 @@ private
node.each do |name, value|
vars[Mapping.elename2name(name)] = Mapping._soap2obj(value, map)
end
- Mapping.set_attributes(obj, vars)
+ Mapping.set_instance_vars(obj, vars)
end
end
@@ -87,11 +116,10 @@ class StringFactory_ < Factory
return nil
end
begin
- unless XSD::Charset.is_ces(obj, Thread.current[:SOAPExternalCES])
- return nil
+ unless XSD::Charset.is_ces(obj, $KCODE)
+ return nil
end
- encoded = XSD::Charset.encoding_conv(obj,
- Thread.current[:SOAPExternalCES], XSD::Charset.encoding)
+ encoded = XSD::Charset.encoding_conv(obj, $KCODE, XSD::Charset.encoding)
soap_obj = soap_class.new(encoded)
rescue XSD::ValueSpaceError
return nil
@@ -101,9 +129,8 @@ class StringFactory_ < Factory
end
def soap2obj(obj_class, node, info, map)
- obj = Mapping.create_empty_object(obj_class)
- decoded = XSD::Charset.encoding_conv(node.data, XSD::Charset.encoding,
- Thread.current[:SOAPExternalCES])
+ obj = create_empty_object(obj_class)
+ decoded = XSD::Charset.encoding_conv(node.data, XSD::Charset.encoding, $KCODE)
obj.replace(decoded)
mark_unmarshalled_obj(node, obj)
return true, obj
@@ -162,14 +189,20 @@ class DateTimeFactory_ < Factory
end
def soap2obj(obj_class, node, info, map)
- if node.respond_to?(:to_obj)
- obj = node.to_obj(obj_class)
- return false if obj.nil?
- mark_unmarshalled_obj(node, obj)
- return true, obj
+ obj = nil
+ if obj_class == Time
+ obj = node.to_time
+ if obj.nil?
+ # Is out of range as a Time
+ return false
+ end
+ elsif obj_class == Date
+ obj = node.data
else
return false
end
+ mark_unmarshalled_obj(node, obj)
+ return true, obj
end
end
@@ -220,16 +253,16 @@ class ArrayFactory_ < Factory
else
arytype = XSD::AnyTypeName
end
- soap_obj = SOAPArray.new(ValueArrayName, 1, arytype)
- mark_marshalled_obj(obj, soap_obj)
- obj.each do |item|
- soap_obj.add(Mapping._obj2soap(item, map))
+ param = SOAPArray.new(ValueArrayName, 1, arytype)
+ mark_marshalled_obj(obj, param)
+ obj.each do |var|
+ param.add(Mapping._obj2soap(var, map))
end
- soap_obj
+ param
end
def soap2obj(obj_class, node, info, map)
- obj = Mapping.create_empty_object(obj_class)
+ obj = create_empty_object(obj_class)
mark_unmarshalled_obj(node, obj)
node.soap2array(obj) do |elem|
elem ? Mapping._soap2obj(elem, map) : nil
@@ -249,12 +282,12 @@ class TypedArrayFactory_ < Factory
return nil
end
arytype = info[:type] || info[0]
- soap_obj = SOAPArray.new(ValueArrayName, 1, arytype)
- mark_marshalled_obj(obj, soap_obj)
+ param = SOAPArray.new(ValueArrayName, 1, arytype)
+ mark_marshalled_obj(obj, param)
obj.each do |var|
- soap_obj.add(Mapping._obj2soap(var, map))
+ param.add(Mapping._obj2soap(var, map))
end
- soap_obj
+ param
end
def soap2obj(obj_class, node, info, map)
@@ -265,7 +298,7 @@ class TypedArrayFactory_ < Factory
unless node.arytype == arytype
return false
end
- obj = Mapping.create_empty_object(obj_class)
+ obj = create_empty_object(obj_class)
mark_unmarshalled_obj(node, obj)
node.soap2array(obj) do |elem|
elem ? Mapping._soap2obj(elem, map) : nil
@@ -277,14 +310,14 @@ end
class TypedStructFactory_ < Factory
def obj2soap(soap_class, obj, info, map)
type = info[:type] || info[0]
- soap_obj = soap_class.new(type)
- mark_marshalled_obj(obj, soap_obj)
+ param = soap_class.new(type)
+ mark_marshalled_obj(obj, param)
if obj.class <= SOAP::Marshallable
- setiv2soap(soap_obj, obj, map)
+ setiv2soap(param, obj, map)
else
- setiv2soap(soap_obj, obj, map)
+ setiv2soap(param, obj, map)
end
- soap_obj
+ param
end
def soap2obj(obj_class, node, info, map)
@@ -292,7 +325,7 @@ class TypedStructFactory_ < Factory
unless node.type == type
return false
end
- obj = Mapping.create_empty_object(obj_class)
+ obj = create_empty_object(obj_class)
mark_unmarshalled_obj(node, obj)
setiv2obj(obj, node, map)
return true, obj
@@ -314,16 +347,16 @@ class HashFactory_ < Factory
(obj.respond_to?(:default_proc) and obj.default_proc)
return nil
end
- soap_obj = SOAPStruct.new(MapQName)
- mark_marshalled_obj(obj, soap_obj)
+ param = SOAPStruct.new(MapQName)
+ mark_marshalled_obj(obj, param)
obj.each do |key, value|
elem = SOAPStruct.new
elem.add("key", Mapping._obj2soap(key, map))
elem.add("value", Mapping._obj2soap(value, map))
# ApacheAxis allows only 'item' here.
- soap_obj.add("item", elem)
+ param.add("item", elem)
end
- soap_obj
+ param
end
def soap2obj(obj_class, node, info, map)
@@ -333,7 +366,7 @@ class HashFactory_ < Factory
if node.class == SOAPStruct and node.key?('default')
return false
end
- obj = Mapping.create_empty_object(obj_class)
+ obj = create_empty_object(obj_class)
mark_unmarshalled_obj(node, obj)
if node.class == SOAPStruct
node.each do |key, value|
diff --git a/lib/soap/mapping/mapping.rb b/lib/soap/mapping/mapping.rb
index 65d6bb4d5b..db7ea607fd 100644
--- a/lib/soap/mapping/mapping.rb
+++ b/lib/soap/mapping/mapping.rb
@@ -1,14 +1,11 @@
# SOAP4R - Ruby type mapping utility.
-# Copyright (C) 2000, 2001, 2003-2005 NAKAMURA Hiroshi <nahi@ruby-lang.org>.
+# Copyright (C) 2000, 2001, 2003 NAKAMURA Hiroshi <nahi@ruby-lang.org>.
# This program is copyrighted free software by NAKAMURA, Hiroshi. You can
# redistribute it and/or modify it under the same terms of Ruby's license;
# either the dual license version in 2003, or any later version.
-require 'xsd/codegen/gensupport'
-
-
module SOAP
@@ -20,72 +17,54 @@ module Mapping
ApacheSOAPTypeNamespace = 'http://xml.apache.org/xml-soap'
- # TraverseSupport breaks following thread variables.
- # Thread.current[:SOAPMarshalDataKey]
+ # TraverseSupport breaks Thread.current[:SOAPMarshalDataKey].
module TraverseSupport
def mark_marshalled_obj(obj, soap_obj)
- raise if obj.nil?
Thread.current[:SOAPMarshalDataKey][obj.__id__] = soap_obj
end
def mark_unmarshalled_obj(node, obj)
- return if obj.nil?
# node.id is not Object#id but SOAPReference#id
Thread.current[:SOAPMarshalDataKey][node.id] = obj
end
end
- EMPTY_OPT = {}
- def self.obj2soap(obj, registry = nil, type = nil, opt = EMPTY_OPT)
+ def self.obj2soap(obj, registry = nil, type = nil)
registry ||= Mapping::DefaultRegistry
- soap_obj = nil
- protect_threadvars(:SOAPMarshalDataKey, :SOAPExternalCES, :SOAPMarshalNoReference) do
- Thread.current[:SOAPMarshalDataKey] = {}
- Thread.current[:SOAPExternalCES] = opt[:external_ces] || $KCODE
- Thread.current[:SOAPMarshalNoReference] = opt[:no_reference]
- soap_obj = _obj2soap(obj, registry, type)
- end
+ Thread.current[:SOAPMarshalDataKey] = {}
+ soap_obj = _obj2soap(obj, registry, type)
+ Thread.current[:SOAPMarshalDataKey] = nil
soap_obj
end
- def self.soap2obj(node, registry = nil, klass = nil, opt = EMPTY_OPT)
+ def self.soap2obj(node, registry = nil)
registry ||= Mapping::DefaultRegistry
- obj = nil
- protect_threadvars(:SOAPMarshalDataKey, :SOAPExternalCES, :SOAPMarshalNoReference) do
- Thread.current[:SOAPMarshalDataKey] = {}
- Thread.current[:SOAPExternalCES] = opt[:external_ces] || $KCODE
- Thread.current[:SOAPMarshalNoReference] = opt[:no_reference]
- obj = _soap2obj(node, registry, klass)
- end
+ Thread.current[:SOAPMarshalDataKey] = {}
+ obj = _soap2obj(node, registry)
+ Thread.current[:SOAPMarshalDataKey] = nil
obj
end
- def self.ary2soap(ary, type_ns = XSD::Namespace, typename = XSD::AnyTypeLiteral, registry = nil, opt = EMPTY_OPT)
+ def self.ary2soap(ary, type_ns = XSD::Namespace, typename = XSD::AnyTypeLiteral, registry = nil)
registry ||= Mapping::DefaultRegistry
type = XSD::QName.new(type_ns, typename)
soap_ary = SOAPArray.new(ValueArrayName, 1, type)
- protect_threadvars(:SOAPMarshalDataKey, :SOAPExternalCES, :SOAPMarshalNoReference) do
- Thread.current[:SOAPMarshalDataKey] = {}
- Thread.current[:SOAPExternalCES] = opt[:external_ces] || $KCODE
- Thread.current[:SOAPMarshalNoReference] = opt[:no_reference]
- ary.each do |ele|
- soap_ary.add(_obj2soap(ele, registry, type))
- end
+ Thread.current[:SOAPMarshalDataKey] = {}
+ ary.each do |ele|
+ soap_ary.add(_obj2soap(ele, registry, type))
end
+ Thread.current[:SOAPMarshalDataKey] = nil
soap_ary
end
- def self.ary2md(ary, rank, type_ns = XSD::Namespace, typename = XSD::AnyTypeLiteral, registry = nil, opt = EMPTY_OPT)
+ def self.ary2md(ary, rank, type_ns = XSD::Namespace, typename = XSD::AnyTypeLiteral, registry = nil)
registry ||= Mapping::DefaultRegistry
type = XSD::QName.new(type_ns, typename)
md_ary = SOAPArray.new(ValueArrayName, rank, type)
- protect_threadvars(:SOAPMarshalDataKey, :SOAPExternalCES, :SOAPMarshalNoReference) do
- Thread.current[:SOAPMarshalDataKey] = {}
- Thread.current[:SOAPExternalCES] = opt[:external_ces] || $KCODE
- Thread.current[:SOAPMarshalNoReference] = opt[:no_reference]
- add_md_ary(md_ary, ary, [], registry)
- end
+ Thread.current[:SOAPMarshalDataKey] = {}
+ add_md_ary(md_ary, ary, [], registry)
+ Thread.current[:SOAPMarshalDataKey] = nil
md_ary
end
@@ -120,62 +99,34 @@ module Mapping
end
def self._obj2soap(obj, registry, type = nil)
- if referent = Thread.current[:SOAPMarshalDataKey][obj.__id__] and
- !Thread.current[:SOAPMarshalNoReference]
+ if referent = Thread.current[:SOAPMarshalDataKey][obj.__id__]
SOAPReference.new(referent)
- elsif registry
- registry.obj2soap(obj, type)
else
- raise MappingError.new("no mapping registry given")
+ registry.obj2soap(obj.class, obj, type)
end
end
- def self._soap2obj(node, registry, klass = nil)
- if node.nil?
- return nil
- elsif node.is_a?(SOAPReference)
+ def self._soap2obj(node, registry)
+ if node.is_a?(SOAPReference)
target = node.__getobj__
# target.id is not Object#id but SOAPReference#id
- if referent = Thread.current[:SOAPMarshalDataKey][target.id] and
- !Thread.current[:SOAPMarshalNoReference]
+ if referent = Thread.current[:SOAPMarshalDataKey][target.id]
return referent
else
- return _soap2obj(target, registry, klass)
+ return _soap2obj(target, registry)
end
end
- return registry.soap2obj(node, klass)
+ return registry.soap2obj(node.class, node)
end
- if Object.respond_to?(:allocate)
- # ruby/1.7 or later.
- def self.create_empty_object(klass)
- klass.allocate
- end
- else
- MARSHAL_TAG = {
- String => ['"', 1],
- Regexp => ['/', 2],
- Array => ['[', 1],
- Hash => ['{', 1]
- }
- def self.create_empty_object(klass)
- if klass <= Struct
- name = klass.name
- return ::Marshal.load(sprintf("\004\006S:%c%s\000", name.length + 5, name))
- end
- if MARSHAL_TAG.has_key?(klass)
- tag, terminate = MARSHAL_TAG[klass]
- return ::Marshal.load(sprintf("\004\006%s%s", tag, "\000" * terminate))
- end
- MARSHAL_TAG.each do |k, v|
- if klass < k
- name = klass.name
- tag, terminate = v
- return ::Marshal.load(sprintf("\004\006C:%c%s%s%s", name.length + 5, name, tag, "\000" * terminate))
- end
+ def self.set_instance_vars(obj, values)
+ values.each do |name, value|
+ setter = name + "="
+ if obj.respond_to?(setter)
+ obj.__send__(setter, value)
+ else
+ obj.instance_eval("@#{ name } = value")
end
- name = klass.name
- ::Marshal.load(sprintf("\004\006o:%c%s\000", name.length + 5, name))
end
end
@@ -197,47 +148,32 @@ module Mapping
}
end
- def self.const_from_name(name, lenient = false)
- const = ::Object
- name.sub(/\A::/, '').split('::').each do |const_str|
- if XSD::CodeGen::GenSupport.safeconstname?(const_str)
- if const.const_defined?(const_str)
- const = const.const_get(const_str)
- next
- end
- elsif lenient
- const_str = XSD::CodeGen::GenSupport.safeconstname(const_str)
- if const.const_defined?(const_str)
- const = const.const_get(const_str)
- next
- end
- end
+ def self.class_from_name(name)
+ if /^[A-Z]/ !~ name
return nil
end
- const
- end
-
- def self.class_from_name(name, lenient = false)
- const = const_from_name(name, lenient)
- if const.is_a?(::Class)
- const
- else
- nil
- end
- end
-
- def self.module_from_name(name, lenient = false)
- const = const_from_name(name, lenient)
- if const.is_a?(::Module)
- const
- else
- nil
+ klass = ::Object
+ name.split('::').each do |klass_str|
+ if klass.const_defined?(klass_str)
+ klass = klass.const_get(klass_str)
+ else
+ return nil
+ end
end
+ klass
end
def self.class2qname(klass)
- name = schema_type_definition(klass)
- namespace = schema_ns_definition(klass)
+ name = if klass.class_variables.include?("@@schema_type")
+ klass.class_eval("@@schema_type")
+ else
+ nil
+ end
+ namespace = if klass.class_variables.include?("@@schema_ns")
+ klass.class_eval("@@schema_ns")
+ else
+ nil
+ end
XSD::QName.new(namespace, name)
end
@@ -251,11 +187,11 @@ module Mapping
def self.obj2element(obj)
name = namespace = nil
ivars = obj.instance_variables
- if ivars.include?('@schema_type')
- name = obj.instance_variable_get('@schema_type')
+ if ivars.include?("@schema_type")
+ name = obj.instance_eval("@schema_type")
end
- if ivars.include?('@schema_ns')
- namespace = obj.instance_variable_get('@schema_ns')
+ if ivars.include?("@schema_ns")
+ namespace = obj.instance_eval("@schema_ns")
end
if !name or !namespace
class2qname(obj.class)
@@ -264,107 +200,8 @@ module Mapping
end
end
- def self.define_singleton_method(obj, name, &block)
- sclass = (class << obj; self; end)
- sclass.class_eval {
- define_method(name, &block)
- }
- end
-
- def self.get_attribute(obj, attr_name)
- if obj.is_a?(::Hash)
- obj[attr_name] || obj[attr_name.intern]
- else
- name = XSD::CodeGen::GenSupport.safevarname(attr_name)
- if obj.instance_variables.include?('@' + name)
- obj.instance_variable_get('@' + name)
- elsif ((obj.is_a?(::Struct) or obj.is_a?(Marshallable)) and
- obj.respond_to?(name))
- obj.__send__(name)
- end
- end
- end
-
- def self.set_attributes(obj, values)
- if obj.is_a?(::SOAP::Mapping::Object)
- values.each do |attr_name, value|
- obj.__add_xmlele_value(attr_name, value)
- end
- else
- values.each do |attr_name, value|
- name = XSD::CodeGen::GenSupport.safevarname(attr_name)
- setter = name + "="
- if obj.respond_to?(setter)
- obj.__send__(setter, value)
- else
- obj.instance_variable_set('@' + name, value)
- begin
- define_attr_accessor(obj, name,
- proc { instance_variable_get('@' + name) },
- proc { |value| instance_variable_set('@' + name, value) })
- rescue TypeError
- # singleton class may not exist (e.g. Float)
- end
- end
- end
- end
- end
-
- def self.define_attr_accessor(obj, name, getterproc, setterproc = nil)
- define_singleton_method(obj, name, &getterproc)
- define_singleton_method(obj, name + '=', &setterproc) if setterproc
- end
-
- def self.schema_type_definition(klass)
- class_schema_variable(:schema_type, klass)
- end
-
- def self.schema_ns_definition(klass)
- class_schema_variable(:schema_ns, klass)
- end
-
- def self.schema_element_definition(klass)
- schema_element = class_schema_variable(:schema_element, klass) or return nil
- schema_ns = schema_ns_definition(klass)
- elements = []
- as_array = []
- schema_element.each do |varname, definition|
- class_name, name = definition
- if /\[\]$/ =~ class_name
- class_name = class_name.sub(/\[\]$/, '')
- as_array << (name ? name.name : varname)
- end
- elements << [name || XSD::QName.new(schema_ns, varname), class_name]
- end
- [elements, as_array]
- end
-
- def self.schema_attribute_definition(klass)
- class_schema_variable(:schema_attribute, klass)
- end
-
class << Mapping
private
-
- def class_schema_variable(sym, klass)
- var = "@@#{sym}"
- klass.class_variables.include?(var) ? klass.class_eval(var) : nil
- end
-
- def protect_threadvars(*symbols)
- backup = {}
- begin
- symbols.each do |sym|
- backup[sym] = Thread.current[sym]
- end
- yield
- ensure
- symbols.each do |sym|
- Thread.current[sym] = backup[sym]
- end
- end
- end
-
def add_md_ary(md_ary, ary, indices, registry)
for idx in 0..(ary.size - 1)
if ary[idx].is_a?(Array)
diff --git a/lib/soap/mapping/registry.rb b/lib/soap/mapping/registry.rb
index 823e80666d..1317d40cd6 100644
--- a/lib/soap/mapping/registry.rb
+++ b/lib/soap/mapping/registry.rb
@@ -49,7 +49,8 @@ class SOAPException; include Marshallable
e.set_backtrace(@cause.backtrace)
return e
end
- klass = Mapping.class_from_name(Mapping.elename2name(@excn_type_name.to_s))
+ klass = Mapping.class_from_name(
+ Mapping.elename2name(@excn_type_name.to_s))
if klass.nil? or not klass <= ::Exception
return RuntimeError.new(@cause.inspect)
end
@@ -63,109 +64,79 @@ end
# For anyType object: SOAP::Mapping::Object not ::Object
class Object; include Marshallable
def initialize
- @__xmlele_type = {}
- @__xmlele = []
- @__xmlattr = {}
+ @__members = []
+ @__value_type = {}
end
- def inspect
- sprintf("#<%s:0x%x%s>", self.class.name, __id__,
- @__xmlele.collect { |name, value| " #{name}=#{value.inspect}" }.join)
- end
-
- def __xmlattr
- @__xmlattr
- end
-
- def __xmlele
- @__xmlele
+ def [](name)
+ if @__members.include?(name)
+ self.__send__(name)
+ else
+ self.__send__(Object.safe_name(name))
+ end
end
- def [](qname)
- unless qname.is_a?(XSD::QName)
- qname = XSD::QName.new(nil, qname)
- end
- @__xmlele.each do |k, v|
- return v if k == qname
- end
- # fallback
- @__xmlele.each do |k, v|
- return v if k.name == qname.name
+ def []=(name, value)
+ if @__members.include?(name)
+ self.__send__(name + '=', value)
+ else
+ self.__send__(Object.safe_name(name) + '=', value)
end
- nil
end
- def []=(qname, value)
- unless qname.is_a?(XSD::QName)
- qname = XSD::QName.new(nil, qname)
+ def __set_property(name, value)
+ var_name = name
+ unless @__members.include?(name)
+ var_name = __define_attr_accessor(var_name)
end
- found = false
- @__xmlele.each do |pair|
- if pair[0] == qname
- found = true
- pair[1] = value
- end
- end
- unless found
- __define_attr_accessor(qname)
- @__xmlele << [qname, value]
- end
- @__xmlele_type[qname] = :single
+ __set_property_value(var_name, value)
+ var_name
end
- def __add_xmlele_value(qname, value)
- found = false
- @__xmlele.map! do |k, v|
- if k == qname
- found = true
- [k, __set_xmlele_value(k, v, value)]
- else
- [k, v]
- end
- end
- unless found
- __define_attr_accessor(qname)
- @__xmlele << [qname, value]
- @__xmlele_type[qname] = :single
- end
- value
+ def __members
+ @__members
end
private
- if RUBY_VERSION > "1.7.0"
- def __define_attr_accessor(qname)
- name = XSD::CodeGen::GenSupport.safemethodname(qname.name)
- Mapping.define_attr_accessor(self, name,
- proc { self[qname] },
- proc { |value| self[qname] = value })
+ def __set_property_value(name, value)
+ org = self.__send__(name)
+ case @__value_type[name]
+ when :single
+ self.__send__(name + '=', [org, value])
+ @__value_type[name] = :multi
+ when :multi
+ org << value
+ else
+ self.__send__(name + '=', value)
+ @__value_type[name] = :single
end
- else
- def __define_attr_accessor(qname)
- name = XSD::CodeGen::GenSupport.safemethodname(qname.name)
+ value
+ end
+
+ def __define_attr_accessor(name)
+ var_name = name
+ begin
instance_eval <<-EOS
- def #{name}
- self[#{qname.dump}]
- end
+ def #{ var_name }
+ @#{ var_name }
+ end
- def #{name}=(value)
- self[#{qname.dump}] = value
- end
+ def #{ var_name }=(value)
+ @#{ var_name } = value
+ end
EOS
+ rescue SyntaxError
+ var_name = Object.safe_name(var_name)
+ retry
end
+ @__members << var_name
+ var_name
end
- def __set_xmlele_value(key, org, value)
- case @__xmlele_type[key]
- when :multi
- org << value
- org
- when :single
- @__xmlele_type[key] = :multi
- [org, value]
- else
- raise RuntimeError.new("unknown type")
- end
+ def Object.safe_name(name)
+ require 'md5'
+ "var_" << MD5.new(name).hexdigest
end
end
@@ -176,45 +147,30 @@ class MappingError < Error; end
class Registry
class Map
def initialize(registry)
- @obj2soap = {}
- @soap2obj = {}
+ @map = []
@registry = registry
end
- def obj2soap(obj)
- klass = obj.class
- if map = @obj2soap[klass]
- map.each do |soap_class, factory, info|
+ def obj2soap(klass, obj, type_qname = nil)
+ @map.each do |obj_class, soap_class, factory, info|
+ if klass == obj_class or
+ (info[:derived_class] and klass <= obj_class)
ret = factory.obj2soap(soap_class, obj, info, @registry)
return ret if ret
end
end
- ancestors = klass.ancestors
- ancestors.delete(klass)
- ancestors.delete(::Object)
- ancestors.delete(::Kernel)
- ancestors.each do |klass|
- if map = @obj2soap[klass]
- map.each do |soap_class, factory, info|
- if info[:derived_class]
- ret = factory.obj2soap(soap_class, obj, info, @registry)
- return ret if ret
- end
- end
- end
- end
nil
end
- def soap2obj(node, klass = nil)
- if map = @soap2obj[node.class]
- map.each do |obj_class, factory, info|
- next if klass and obj_class != klass
+ def soap2obj(klass, node)
+ @map.each do |obj_class, soap_class, factory, info|
+ if klass == soap_class or
+ (info[:derived_class] and klass <= soap_class)
conv, obj = factory.soap2obj(obj_class, node, info, @registry)
return true, obj if conv
end
end
- return false, nil
+ return false
end
# Give priority to former entry.
@@ -228,23 +184,29 @@ class Registry
# Give priority to latter entry.
def add(obj_class, soap_class, factory, info)
info ||= {}
- (@obj2soap[obj_class] ||= []).unshift([soap_class, factory, info])
- (@soap2obj[soap_class] ||= []).unshift([obj_class, factory, info])
+ @map.unshift([obj_class, soap_class, factory, info])
end
def clear
- @obj2soap.clear
- @soap2obj.clear
+ @map.clear
end
def find_mapped_soap_class(target_obj_class)
- map = @obj2soap[target_obj_class]
- map.empty? ? nil : map[0][1]
+ @map.each do |obj_class, soap_class, factory, info|
+ if obj_class == target_obj_class
+ return soap_class
+ end
+ end
+ nil
end
def find_mapped_obj_class(target_soap_class)
- map = @soap2obj[target_soap_class]
- map.empty? ? nil : map[0][0]
+ @map.each do |obj_class, soap_class, factory, info|
+ if soap_class == target_soap_class
+ return obj_class
+ end
+ end
+ nil
end
end
@@ -265,6 +227,7 @@ class Registry
[::FalseClass, ::SOAP::SOAPBoolean, BasetypeFactory],
[::String, ::SOAP::SOAPString, StringFactory],
[::DateTime, ::SOAP::SOAPDateTime, DateTimeFactory],
+ [::Date, ::SOAP::SOAPDateTime, DateTimeFactory],
[::Date, ::SOAP::SOAPDate, DateTimeFactory],
[::Time, ::SOAP::SOAPDateTime, DateTimeFactory],
[::Time, ::SOAP::SOAPTime, DateTimeFactory],
@@ -280,24 +243,6 @@ class Registry
{:derived_class => true}],
[::Integer, ::SOAP::SOAPShort, BasetypeFactory,
{:derived_class => true}],
- [::Integer, ::SOAP::SOAPByte, BasetypeFactory,
- {:derived_class => true}],
- [::Integer, ::SOAP::SOAPNonPositiveInteger, BasetypeFactory,
- {:derived_class => true}],
- [::Integer, ::SOAP::SOAPNegativeInteger, BasetypeFactory,
- {:derived_class => true}],
- [::Integer, ::SOAP::SOAPNonNegativeInteger, BasetypeFactory,
- {:derived_class => true}],
- [::Integer, ::SOAP::SOAPPositiveInteger, BasetypeFactory,
- {:derived_class => true}],
- [::Integer, ::SOAP::SOAPUnsignedLong, BasetypeFactory,
- {:derived_class => true}],
- [::Integer, ::SOAP::SOAPUnsignedInt, BasetypeFactory,
- {:derived_class => true}],
- [::Integer, ::SOAP::SOAPUnsignedShort, BasetypeFactory,
- {:derived_class => true}],
- [::Integer, ::SOAP::SOAPUnsignedByte, BasetypeFactory,
- {:derived_class => true}],
[::URI::Generic, ::SOAP::SOAPAnyURI, URIFactory,
{:derived_class => true}],
[::String, ::SOAP::SOAPBase64, Base64Factory],
@@ -328,6 +273,7 @@ class Registry
[::FalseClass, ::SOAP::SOAPBoolean, BasetypeFactory],
[::String, ::SOAP::SOAPString, StringFactory],
[::DateTime, ::SOAP::SOAPDateTime, DateTimeFactory],
+ [::Date, ::SOAP::SOAPDateTime, DateTimeFactory],
[::Date, ::SOAP::SOAPDate, DateTimeFactory],
[::Time, ::SOAP::SOAPDateTime, DateTimeFactory],
[::Time, ::SOAP::SOAPTime, DateTimeFactory],
@@ -343,24 +289,6 @@ class Registry
{:derived_class => true}],
[::Integer, ::SOAP::SOAPShort, BasetypeFactory,
{:derived_class => true}],
- [::Integer, ::SOAP::SOAPByte, BasetypeFactory,
- {:derived_class => true}],
- [::Integer, ::SOAP::SOAPNonPositiveInteger, BasetypeFactory,
- {:derived_class => true}],
- [::Integer, ::SOAP::SOAPNegativeInteger, BasetypeFactory,
- {:derived_class => true}],
- [::Integer, ::SOAP::SOAPNonNegativeInteger, BasetypeFactory,
- {:derived_class => true}],
- [::Integer, ::SOAP::SOAPPositiveInteger, BasetypeFactory,
- {:derived_class => true}],
- [::Integer, ::SOAP::SOAPUnsignedLong, BasetypeFactory,
- {:derived_class => true}],
- [::Integer, ::SOAP::SOAPUnsignedInt, BasetypeFactory,
- {:derived_class => true}],
- [::Integer, ::SOAP::SOAPUnsignedShort, BasetypeFactory,
- {:derived_class => true}],
- [::Integer, ::SOAP::SOAPUnsignedByte, BasetypeFactory,
- {:derived_class => true}],
[::URI::Generic, ::SOAP::SOAPAnyURI, URIFactory,
{:derived_class => true}],
[::String, ::SOAP::SOAPBase64, Base64Factory],
@@ -385,10 +313,6 @@ class Registry
{:type => XSD::QName.new(RubyCustomTypeNamespace, "SOAPException")}],
]
- attr_accessor :default_factory
- attr_accessor :excn_handler_obj2soap
- attr_accessor :excn_handler_soap2obj
-
def initialize(config = {})
@config = config
@map = Map.new(self)
@@ -399,6 +323,7 @@ class Registry
@allow_original_mapping = false
@map.init(SOAPBaseMap)
end
+
@allow_untyped_struct = @config.key?(:allow_untyped_struct) ?
@config[:allow_untyped_struct] : true
@rubytype_factory = RubytypeFactory.new(
@@ -415,17 +340,17 @@ class Registry
end
alias set add
- # general Registry ignores type_qname
- def obj2soap(obj, type_qname = nil)
- soap = _obj2soap(obj)
+ # This mapping registry ignores type hint.
+ def obj2soap(klass, obj, type_qname = nil)
+ soap = _obj2soap(klass, obj, type_qname)
if @allow_original_mapping
addextend2soap(soap, obj)
end
soap
end
- def soap2obj(node, klass = nil)
- obj = _soap2obj(node, klass)
+ def soap2obj(klass, node)
+ obj = _soap2obj(klass, node)
if @allow_original_mapping
addextend2obj(obj, node.extraattr[RubyExtendName])
addiv2obj(obj, node.extraattr[RubyIVarName])
@@ -433,6 +358,18 @@ class Registry
obj
end
+ def default_factory=(factory)
+ @default_factory = factory
+ end
+
+ def excn_handler_obj2soap=(handler)
+ @excn_handler_obj2soap = handler
+ end
+
+ def excn_handler_soap2obj=(handler)
+ @excn_handler_soap2obj = handler
+ end
+
def find_mapped_soap_class(obj_class)
@map.find_mapped_soap_class(obj_class)
end
@@ -443,7 +380,7 @@ class Registry
private
- def _obj2soap(obj)
+ def _obj2soap(klass, obj, type_qname)
ret = nil
if obj.is_a?(SOAPStruct) or obj.is_a?(SOAPArray)
obj.replace do |ele|
@@ -454,31 +391,32 @@ private
return obj
end
begin
- ret = @map.obj2soap(obj) ||
- @default_factory.obj2soap(nil, obj, nil, self)
- return ret if ret
+ ret = @map.obj2soap(klass, obj, type_qname) ||
+ @default_factory.obj2soap(klass, obj, nil, self)
rescue MappingError
end
+ return ret if ret
if @excn_handler_obj2soap
ret = @excn_handler_obj2soap.call(obj) { |yield_obj|
Mapping._obj2soap(yield_obj, self)
}
- return ret if ret
end
- raise MappingError.new("Cannot map #{ obj.class.name } to SOAP/OM.")
+ return ret if ret
+ raise MappingError.new("Cannot map #{ klass.name } to SOAP/OM.")
end
# Might return nil as a mapping result.
- def _soap2obj(node, klass = nil)
+ def _soap2obj(klass, node)
if node.extraattr.key?(RubyTypeName)
- conv, obj = @rubytype_factory.soap2obj(nil, node, nil, self)
+ conv, obj = @rubytype_factory.soap2obj(klass, node, nil, self)
return obj if conv
else
- conv, obj = @map.soap2obj(node, klass)
+ conv, obj = @map.soap2obj(klass, node)
return obj if conv
- conv, obj = @default_factory.soap2obj(nil, node, nil, self)
+ conv, obj = @default_factory.soap2obj(klass, node, nil, self)
return obj if conv
end
+
if @excn_handler_soap2obj
begin
return @excn_handler_soap2obj.call(node) { |yield_node|
@@ -496,14 +434,14 @@ private
attr.__getobj__.each do |name, value|
vars[name] = Mapping._soap2obj(value, self)
end
- Mapping.set_attributes(obj, vars)
+ Mapping.set_instance_vars(obj, vars)
end
if RUBY_VERSION >= '1.8.0'
def addextend2obj(obj, attr)
return unless attr
attr.split(/ /).reverse_each do |mstr|
- obj.extend(Mapping.module_from_name(mstr))
+ obj.extend(Mapping.class_from_name(mstr))
end
end
else
@@ -511,8 +449,8 @@ private
def addextend2obj(obj, attr)
return unless attr
attr.split(/ /).reverse_each do |mstr|
- m = Mapping.module_from_name(mstr)
- obj.extend(m)
+ m = Mapping.class_from_name(mstr)
+ obj.extend(m) if m.class == Module
end
end
end
diff --git a/lib/soap/mapping/rubytypeFactory.rb b/lib/soap/mapping/rubytypeFactory.rb
index 61c21d8b20..a46d93275f 100644
--- a/lib/soap/mapping/rubytypeFactory.rb
+++ b/lib/soap/mapping/rubytypeFactory.rb
@@ -1,5 +1,5 @@
# SOAP4R - Ruby type mapping factory.
-# Copyright (C) 2000-2003, 2005 NAKAMURA, Hiroshi <nahi@ruby-lang.org>.
+# Copyright (C) 2000, 2001, 2002, 2003 NAKAMURA, Hiroshi <nahi@ruby-lang.org>.
# This program is copyrighted free software by NAKAMURA, Hiroshi. You can
# redistribute it and/or modify it under the same terms of Ruby's license;
@@ -168,7 +168,7 @@ class RubytypeFactory < Factory
return nil
end
if obj.to_s[0] == ?#
- raise TypeError.new("can't dump anonymous class #{obj}")
+ raise TypeError.new("can't dump anonymous class #{ obj }")
end
param = SOAPStruct.new(TYPE_CLASS)
mark_marshalled_obj(obj, param)
@@ -179,7 +179,7 @@ class RubytypeFactory < Factory
return nil
end
if obj.to_s[0] == ?#
- raise TypeError.new("can't dump anonymous module #{obj}")
+ raise TypeError.new("can't dump anonymous module #{ obj }")
end
param = SOAPStruct.new(TYPE_MODULE)
mark_marshalled_obj(obj, param)
@@ -222,12 +222,7 @@ class RubytypeFactory < Factory
when ::SOAP::Mapping::Object
param = SOAPStruct.new(XSD::AnyTypeName)
mark_marshalled_obj(obj, param)
- obj.__xmlele.each do |key, value|
- param.add(key.name, Mapping._obj2soap(value, map))
- end
- obj.__xmlattr.each do |key, value|
- param.extraattr[key] = value
- end
+ addiv2soapattr(param, obj, map)
when ::Exception
typestr = Mapping.name2elename(obj.class.to_s)
param = SOAPStruct.new(XSD::QName.new(RubyTypeNamespace, typestr))
@@ -263,12 +258,12 @@ private
def unknownobj2soap(soap_class, obj, info, map)
if obj.class.name.empty?
- raise TypeError.new("can't dump anonymous class #{obj}")
+ raise TypeError.new("can't dump anonymous class #{ obj }")
end
singleton_class = class << obj; self; end
if !singleton_methods_true(obj).empty? or
!singleton_class.instance_variables.empty?
- raise TypeError.new("singleton can't be dumped #{obj}")
+ raise TypeError.new("singleton can't be dumped #{ obj }")
end
if !(singleton_class.ancestors - obj.class.ancestors).empty?
typestr = Mapping.name2elename(obj.class.to_s)
@@ -323,7 +318,7 @@ private
case node.type
when TYPE_HASH
klass = rubytype ? Mapping.class_from_name(rubytype) : Hash
- obj = Mapping.create_empty_object(klass)
+ obj = create_empty_object(klass)
mark_unmarshalled_obj(node, obj)
node.each do |key, value|
next unless key == 'item'
@@ -335,14 +330,14 @@ private
end
when TYPE_REGEXP
klass = rubytype ? Mapping.class_from_name(rubytype) : Regexp
- obj = Mapping.create_empty_object(klass)
+ obj = create_empty_object(klass)
mark_unmarshalled_obj(node, obj)
source = node['source'].string
options = node['options'].data || 0
Regexp.instance_method(:initialize).bind(obj).call(source, options)
when TYPE_RANGE
klass = rubytype ? Mapping.class_from_name(rubytype) : Range
- obj = Mapping.create_empty_object(klass)
+ obj = create_empty_object(klass)
mark_unmarshalled_obj(node, obj)
first = Mapping._soap2obj(node['begin'], map)
last = Mapping._soap2obj(node['end'], map)
@@ -363,7 +358,7 @@ private
unless klass <= ::Struct
return false
end
- obj = Mapping.create_empty_object(klass)
+ obj = create_empty_object(klass)
mark_unmarshalled_obj(node, obj)
node['member'].each do |name, value|
obj[Mapping.elename2name(name)] = Mapping._soap2obj(value, map)
@@ -383,11 +378,7 @@ private
obj = klass.new
mark_unmarshalled_obj(node, obj)
node.each do |name, value|
- obj.__add_xmlele_value(XSD::QName.new(nil, name),
- Mapping._soap2obj(value, map))
- end
- unless node.extraattr.empty?
- obj.instance_variable_set('@__xmlattr', node.extraattr)
+ obj.__set_property(name, Mapping._soap2obj(value, map))
end
return true, obj
else
@@ -396,12 +387,7 @@ private
end
def unknowntype2obj(node, info, map)
- case node
- when SOAPBasetype
- return true, node.data
- when SOAPArray
- return @array_factory.soap2obj(Array, node, info, map)
- when SOAPStruct
+ if node.is_a?(SOAPStruct)
obj = unknownstruct2obj(node, info, map)
return true, obj if obj
if !@allow_untyped_struct
@@ -420,9 +406,6 @@ private
end
typestr = Mapping.elename2name(node.type.name)
klass = Mapping.class_from_name(typestr)
- if klass.nil? and @allow_untyped_struct
- klass = Mapping.class_from_name(typestr, true) # lenient
- end
if klass.nil?
return nil
end
@@ -431,13 +414,7 @@ private
end
klass_type = Mapping.class2qname(klass)
return nil unless node.type.match(klass_type)
- obj = nil
- begin
- obj = Mapping.create_empty_object(klass)
- rescue
- # type name "data" tries Data.new which raises TypeError
- nil
- end
+ obj = create_empty_object(klass)
mark_unmarshalled_obj(node, obj)
setiv2obj(obj, node, map)
obj
@@ -446,7 +423,7 @@ private
def exception2obj(klass, node, map)
message = Mapping._soap2obj(node['message'], map)
backtrace = Mapping._soap2obj(node['backtrace'], map)
- obj = Mapping.create_empty_object(klass)
+ obj = create_empty_object(klass)
obj = obj.exception(message)
mark_unmarshalled_obj(node, obj)
obj.set_backtrace(backtrace)
@@ -456,7 +433,7 @@ private
# Only creates empty array. Do String#replace it with real string.
def array2obj(node, map, rubytype)
klass = rubytype ? Mapping.class_from_name(rubytype) : Array
- obj = Mapping.create_empty_object(klass)
+ obj = create_empty_object(klass)
mark_unmarshalled_obj(node, obj)
obj
end
@@ -464,7 +441,7 @@ private
# Only creates empty string. Do String#replace it with real string.
def string2obj(node, map, rubytype)
klass = rubytype ? Mapping.class_from_name(rubytype) : String
- obj = Mapping.create_empty_object(klass)
+ obj = create_empty_object(klass)
mark_unmarshalled_obj(node, obj)
obj
end
diff --git a/lib/soap/mapping/typeMap.rb b/lib/soap/mapping/typeMap.rb
index 34db19a5b6..93f24b4bd8 100644
--- a/lib/soap/mapping/typeMap.rb
+++ b/lib/soap/mapping/typeMap.rb
@@ -30,18 +30,9 @@ TypeMap = {
XSD::XSDAnyURI::Type => SOAPAnyURI,
XSD::XSDQName::Type => SOAPQName,
XSD::XSDInteger::Type => SOAPInteger,
- XSD::XSDNonPositiveInteger::Type => SOAPNonPositiveInteger,
- XSD::XSDNegativeInteger::Type => SOAPNegativeInteger,
XSD::XSDLong::Type => SOAPLong,
XSD::XSDInt::Type => SOAPInt,
XSD::XSDShort::Type => SOAPShort,
- XSD::XSDByte::Type => SOAPByte,
- XSD::XSDNonNegativeInteger::Type => SOAPNonNegativeInteger,
- XSD::XSDUnsignedLong::Type => SOAPUnsignedLong,
- XSD::XSDUnsignedInt::Type => SOAPUnsignedInt,
- XSD::XSDUnsignedShort::Type => SOAPUnsignedShort,
- XSD::XSDUnsignedByte::Type => SOAPUnsignedByte,
- XSD::XSDPositiveInteger::Type => SOAPPositiveInteger,
SOAP::SOAPBase64::Type => SOAPBase64,
}
diff --git a/lib/soap/mapping/wsdlRegistry.rb b/lib/soap/mapping/wsdlRegistry.rb
new file mode 100644
index 0000000000..64f49f2265
--- /dev/null
+++ b/lib/soap/mapping/wsdlRegistry.rb
@@ -0,0 +1,155 @@
+# SOAP4R - WSDL mapping registry.
+# Copyright (C) 2000, 2001, 2002, 2003 NAKAMURA, Hiroshi <nahi@ruby-lang.org>.
+
+# This program is copyrighted free software by NAKAMURA, Hiroshi. You can
+# redistribute it and/or modify it under the same terms of Ruby's license;
+# either the dual license version in 2003, or any later version.
+
+
+require 'soap/baseData'
+require 'soap/mapping/mapping'
+require 'soap/mapping/typeMap'
+
+
+module SOAP
+module Mapping
+
+
+class WSDLRegistry
+ include TraverseSupport
+
+ attr_reader :definedtypes
+
+ def initialize(definedtypes, config = {})
+ @definedtypes = definedtypes
+ @config = config
+ @excn_handler_obj2soap = nil
+ # For mapping AnyType element.
+ @rubytype_factory = RubytypeFactory.new(
+ :allow_untyped_struct => true,
+ :allow_original_mapping => true
+ )
+ end
+
+ def obj2soap(klass, obj, type_qname)
+ soap_obj = nil
+ if obj.nil?
+ soap_obj = SOAPNil.new
+ elsif obj.is_a?(XSD::NSDBase)
+ soap_obj = soap2soap(obj, type_qname)
+ elsif type = @definedtypes[type_qname]
+ soap_obj = obj2type(obj, type)
+ elsif (type = TypeMap[type_qname])
+ soap_obj = base2soap(obj, type)
+ elsif type_qname == XSD::AnyTypeName
+ soap_obj = @rubytype_factory.obj2soap(nil, obj, nil, nil)
+ end
+ return soap_obj if soap_obj
+ if @excn_handler_obj2soap
+ soap_obj = @excn_handler_obj2soap.call(obj) { |yield_obj|
+ Mapping._obj2soap(yield_obj, self)
+ }
+ end
+ return soap_obj if soap_obj
+ raise MappingError.new("Cannot map #{ klass.name } to SOAP/OM.")
+ end
+
+ def soap2obj(klass, node)
+ raise RuntimeError.new("#{ self } is for obj2soap only.")
+ end
+
+ def excn_handler_obj2soap=(handler)
+ @excn_handler_obj2soap = handler
+ end
+
+private
+
+ def soap2soap(obj, type_qname)
+ if obj.is_a?(SOAPBasetype)
+ obj
+ elsif obj.is_a?(SOAPStruct) && (type = @definedtypes[type_qname])
+ soap_obj = obj
+ mark_marshalled_obj(obj, soap_obj)
+ elements2soap(obj, soap_obj, type.content.elements)
+ soap_obj
+ elsif obj.is_a?(SOAPArray) && (type = @definedtypes[type_qname])
+ soap_obj = obj
+ contenttype = type.child_type
+ mark_marshalled_obj(obj, soap_obj)
+ obj.replace do |ele|
+ Mapping._obj2soap(ele, self, contenttype)
+ end
+ soap_obj
+ else
+ nil
+ end
+ end
+
+ def obj2type(obj, type)
+ if type.is_a?(::WSDL::XMLSchema::SimpleType)
+ simple2soap(obj, type)
+ else
+ complex2soap(obj, type)
+ end
+ end
+
+ def simple2soap(obj, type)
+ o = base2soap(obj, TypeMap[type.base])
+ if type.restriction.enumeration.empty?
+ STDERR.puts("#{type.name}: simpleType which is not enum type not supported.")
+ return o
+ end
+ type.check_lexical_format(obj)
+ o
+ end
+
+ def complex2soap(obj, type)
+ case type.compoundtype
+ when :TYPE_STRUCT
+ struct2soap(obj, type.name, type)
+ when :TYPE_ARRAY
+ array2soap(obj, type.name, type)
+ end
+ end
+
+ def base2soap(obj, type)
+ soap_obj = nil
+ if type <= XSD::XSDString
+ soap_obj = type.new(XSD::Charset.is_ces(obj, $KCODE) ?
+ XSD::Charset.encoding_conv(obj, $KCODE, XSD::Charset.encoding) : obj)
+ mark_marshalled_obj(obj, soap_obj)
+ else
+ soap_obj = type.new(obj)
+ end
+ soap_obj
+ end
+
+ def struct2soap(obj, type_qname, type)
+ soap_obj = SOAPStruct.new(type_qname)
+ mark_marshalled_obj(obj, soap_obj)
+ elements2soap(obj, soap_obj, type.content.elements)
+ soap_obj
+ end
+
+ def array2soap(obj, type_qname, type)
+ contenttype = type.child_type
+ soap_obj = SOAPArray.new(ValueArrayName, 1, contenttype)
+ mark_marshalled_obj(obj, soap_obj)
+ obj.each do |item|
+ soap_obj.add(Mapping._obj2soap(item, self, contenttype))
+ end
+ soap_obj
+ end
+
+ def elements2soap(obj, soap_obj, elements)
+ elements.each do |element|
+ name = element.name.name
+ child_obj = obj.instance_eval("@#{ name }")
+ soap_obj.add(name, Mapping._obj2soap(child_obj, self, element.type))
+ end
+ end
+end
+
+
+end
+end
diff --git a/lib/soap/mapping/wsdlencodedregistry.rb b/lib/soap/mapping/wsdlencodedregistry.rb
deleted file mode 100644
index 4efb60188f..0000000000
--- a/lib/soap/mapping/wsdlencodedregistry.rb
+++ /dev/null
@@ -1,280 +0,0 @@
-# SOAP4R - WSDL encoded mapping registry.
-# Copyright (C) 2000-2003, 2005 NAKAMURA, Hiroshi <nahi@ruby-lang.org>.
-
-# This program is copyrighted free software by NAKAMURA, Hiroshi. You can
-# redistribute it and/or modify it under the same terms of Ruby's license;
-# either the dual license version in 2003, or any later version.
-
-
-require 'xsd/qname'
-require 'xsd/namedelements'
-require 'soap/baseData'
-require 'soap/mapping/mapping'
-require 'soap/mapping/typeMap'
-
-
-module SOAP
-module Mapping
-
-
-class WSDLEncodedRegistry < Registry
- include TraverseSupport
-
- attr_reader :definedelements
- attr_reader :definedtypes
- attr_accessor :excn_handler_obj2soap
- attr_accessor :excn_handler_soap2obj
-
- def initialize(definedtypes = XSD::NamedElements::Empty)
- @definedtypes = definedtypes
- # @definedelements = definedelements needed?
- @excn_handler_obj2soap = nil
- @excn_handler_soap2obj = nil
- # For mapping AnyType element.
- @rubytype_factory = RubytypeFactory.new(
- :allow_untyped_struct => true,
- :allow_original_mapping => true
- )
- @schema_element_cache = {}
- end
-
- def obj2soap(obj, qname = nil)
- soap_obj = nil
- if type = @definedtypes[qname]
- soap_obj = obj2typesoap(obj, type)
- else
- soap_obj = any2soap(obj, qname)
- end
- return soap_obj if soap_obj
- if @excn_handler_obj2soap
- soap_obj = @excn_handler_obj2soap.call(obj) { |yield_obj|
- Mapping._obj2soap(yield_obj, self)
- }
- return soap_obj if soap_obj
- end
- if qname
- raise MappingError.new("cannot map #{obj.class.name} as #{qname}")
- else
- raise MappingError.new("cannot map #{obj.class.name} to SOAP/OM")
- end
- end
-
- # map anything for now: must refer WSDL while mapping. [ToDo]
- def soap2obj(node, obj_class = nil)
- begin
- return any2obj(node, obj_class)
- rescue MappingError
- end
- if @excn_handler_soap2obj
- begin
- return @excn_handler_soap2obj.call(node) { |yield_node|
- Mapping._soap2obj(yield_node, self)
- }
- rescue Exception
- end
- end
- raise MappingError.new("cannot map #{node.type.name} to Ruby object")
- end
-
-private
-
- def any2soap(obj, qname)
- if obj.nil?
- SOAPNil.new
- elsif qname.nil? or qname == XSD::AnyTypeName
- @rubytype_factory.obj2soap(nil, obj, nil, self)
- elsif obj.is_a?(XSD::NSDBase)
- soap2soap(obj, qname)
- elsif (type = TypeMap[qname])
- base2soap(obj, type)
- else
- nil
- end
- end
-
- def soap2soap(obj, type_qname)
- if obj.is_a?(SOAPBasetype)
- obj
- elsif obj.is_a?(SOAPStruct) && (type = @definedtypes[type_qname])
- soap_obj = obj
- mark_marshalled_obj(obj, soap_obj)
- elements2soap(obj, soap_obj, type.content.elements)
- soap_obj
- elsif obj.is_a?(SOAPArray) && (type = @definedtypes[type_qname])
- soap_obj = obj
- contenttype = type.child_type
- mark_marshalled_obj(obj, soap_obj)
- obj.replace do |ele|
- Mapping._obj2soap(ele, self, contenttype)
- end
- soap_obj
- else
- nil
- end
- end
-
- def obj2typesoap(obj, type)
- if type.is_a?(::WSDL::XMLSchema::SimpleType)
- simpleobj2soap(obj, type)
- else
- complexobj2soap(obj, type)
- end
- end
-
- def simpleobj2soap(obj, type)
- type.check_lexical_format(obj)
- return SOAPNil.new if obj.nil? # ToDo: check nillable.
- o = base2soap(obj, TypeMap[type.base])
- o
- end
-
- def complexobj2soap(obj, type)
- case type.compoundtype
- when :TYPE_STRUCT
- struct2soap(obj, type.name, type)
- when :TYPE_ARRAY
- array2soap(obj, type.name, type)
- when :TYPE_MAP
- map2soap(obj, type.name, type)
- when :TYPE_SIMPLE
- simpleobj2soap(obj, type.simplecontent)
- when :TYPE_EMPTY
- raise MappingError.new("should be empty") unless obj.nil?
- SOAPNil.new
- else
- raise MappingError.new("unknown compound type: #{type.compoundtype}")
- end
- end
-
- def base2soap(obj, type)
- soap_obj = nil
- if type <= XSD::XSDString
- str = XSD::Charset.encoding_conv(obj.to_s,
- Thread.current[:SOAPExternalCES], XSD::Charset.encoding)
- soap_obj = type.new(str)
- mark_marshalled_obj(obj, soap_obj)
- else
- soap_obj = type.new(obj)
- end
- soap_obj
- end
-
- def struct2soap(obj, type_qname, type)
- return SOAPNil.new if obj.nil? # ToDo: check nillable.
- soap_obj = SOAPStruct.new(type_qname)
- unless obj.nil?
- mark_marshalled_obj(obj, soap_obj)
- elements2soap(obj, soap_obj, type.content.elements)
- end
- soap_obj
- end
-
- def array2soap(obj, type_qname, type)
- return SOAPNil.new if obj.nil? # ToDo: check nillable.
- arytype = type.child_type
- soap_obj = SOAPArray.new(ValueArrayName, 1, arytype)
- unless obj.nil?
- mark_marshalled_obj(obj, soap_obj)
- obj.each do |item|
- soap_obj.add(Mapping._obj2soap(item, self, arytype))
- end
- end
- soap_obj
- end
-
- MapKeyName = XSD::QName.new(nil, "key")
- MapValueName = XSD::QName.new(nil, "value")
- def map2soap(obj, type_qname, type)
- return SOAPNil.new if obj.nil? # ToDo: check nillable.
- keytype = type.child_type(MapKeyName) || XSD::AnyTypeName
- valuetype = type.child_type(MapValueName) || XSD::AnyTypeName
- soap_obj = SOAPStruct.new(MapQName)
- unless obj.nil?
- mark_marshalled_obj(obj, soap_obj)
- obj.each do |key, value|
- elem = SOAPStruct.new
- elem.add("key", Mapping._obj2soap(key, self, keytype))
- elem.add("value", Mapping._obj2soap(value, self, valuetype))
- # ApacheAxis allows only 'item' here.
- soap_obj.add("item", elem)
- end
- end
- soap_obj
- end
-
- def elements2soap(obj, soap_obj, elements)
- elements.each do |element|
- name = element.name.name
- child_obj = Mapping.get_attribute(obj, name)
- soap_obj.add(name,
- Mapping._obj2soap(child_obj, self, element.type || element.name))
- end
- end
-
- def any2obj(node, obj_class)
- unless obj_class
- typestr = XSD::CodeGen::GenSupport.safeconstname(node.elename.name)
- obj_class = Mapping.class_from_name(typestr)
- end
- if obj_class and obj_class.class_variables.include?('@@schema_element')
- soap2stubobj(node, obj_class)
- else
- Mapping._soap2obj(node, Mapping::DefaultRegistry, obj_class)
- end
- end
-
- def soap2stubobj(node, obj_class)
- obj = Mapping.create_empty_object(obj_class)
- unless node.is_a?(SOAPNil)
- add_elements2stubobj(node, obj)
- end
- obj
- end
-
- def add_elements2stubobj(node, obj)
- elements, as_array = schema_element_definition(obj.class)
- vars = {}
- node.each do |name, value|
- item = elements.find { |k, v| k.name == name }
- if item
- elename, class_name = item
- if klass = Mapping.class_from_name(class_name)
- # klass must be a SOAPBasetype or a class
- if klass.ancestors.include?(::SOAP::SOAPBasetype)
- if value.respond_to?(:data)
- child = klass.new(value.data).data
- else
- child = klass.new(nil).data
- end
- else
- child = Mapping._soap2obj(value, self, klass)
- end
- elsif klass = Mapping.module_from_name(class_name)
- # simpletype
- if value.respond_to?(:data)
- child = value.data
- else
- raise MappingError.new(
- "cannot map to a module value: #{class_name}")
- end
- else
- raise MappingError.new("unknown class: #{class_name}")
- end
- else # untyped element is treated as anyType.
- child = Mapping._soap2obj(value, self)
- end
- vars[name] = child
- end
- Mapping.set_attributes(obj, vars)
- end
-
- # it caches @@schema_element. this means that @@schema_element must not be
- # changed while a lifetime of a WSDLLiteralRegistry.
- def schema_element_definition(klass)
- @schema_element_cache[klass] ||= Mapping.schema_element_definition(klass)
- end
-end
-
-
-end
-end
diff --git a/lib/soap/mapping/wsdlliteralregistry.rb b/lib/soap/mapping/wsdlliteralregistry.rb
deleted file mode 100644
index 7bb8e12203..0000000000
--- a/lib/soap/mapping/wsdlliteralregistry.rb
+++ /dev/null
@@ -1,418 +0,0 @@
-# SOAP4R - WSDL literal mapping registry.
-# Copyright (C) 2004, 2005 NAKAMURA, Hiroshi <nahi@ruby-lang.org>.
-
-# This program is copyrighted free software by NAKAMURA, Hiroshi. You can
-# redistribute it and/or modify it under the same terms of Ruby's license;
-# either the dual license version in 2003, or any later version.
-
-
-require 'soap/baseData'
-require 'soap/mapping/mapping'
-require 'soap/mapping/typeMap'
-require 'xsd/codegen/gensupport'
-require 'xsd/namedelements'
-
-
-module SOAP
-module Mapping
-
-
-class WSDLLiteralRegistry < Registry
- attr_reader :definedelements
- attr_reader :definedtypes
- attr_accessor :excn_handler_obj2soap
- attr_accessor :excn_handler_soap2obj
-
- def initialize(definedtypes = XSD::NamedElements::Empty,
- definedelements = XSD::NamedElements::Empty)
- @definedtypes = definedtypes
- @definedelements = definedelements
- @excn_handler_obj2soap = nil
- @excn_handler_soap2obj = nil
- @schema_element_cache = {}
- @schema_attribute_cache = {}
- end
-
- def obj2soap(obj, qname)
- soap_obj = nil
- if ele = @definedelements[qname]
- soap_obj = obj2elesoap(obj, ele)
- elsif type = @definedtypes[qname]
- soap_obj = obj2typesoap(obj, type, true)
- else
- soap_obj = any2soap(obj, qname)
- end
- return soap_obj if soap_obj
- if @excn_handler_obj2soap
- soap_obj = @excn_handler_obj2soap.call(obj) { |yield_obj|
- Mapping.obj2soap(yield_obj, nil, nil, MAPPING_OPT)
- }
- return soap_obj if soap_obj
- end
- raise MappingError.new("cannot map #{obj.class.name} as #{qname}")
- end
-
- # node should be a SOAPElement
- def soap2obj(node, obj_class = nil)
- # obj_class is given when rpc/literal service. but ignored for now.
- begin
- return any2obj(node)
- rescue MappingError
- end
- if @excn_handler_soap2obj
- begin
- return @excn_handler_soap2obj.call(node) { |yield_node|
- Mapping.soap2obj(yield_node, nil, nil, MAPPING_OPT)
- }
- rescue Exception
- end
- end
- if node.respond_to?(:type)
- raise MappingError.new("cannot map #{node.type.name} to Ruby object")
- else
- raise MappingError.new("cannot map #{node.elename.name} to Ruby object")
- end
- end
-
-private
-
- MAPPING_OPT = { :no_reference => true }
-
- def obj2elesoap(obj, ele)
- o = nil
- qualified = (ele.elementform == 'qualified')
- if ele.type
- if type = @definedtypes[ele.type]
- o = obj2typesoap(obj, type, qualified)
- elsif type = TypeMap[ele.type]
- o = base2soap(obj, type)
- else
- raise MappingError.new("cannot find type #{ele.type}")
- end
- elsif ele.local_complextype
- o = obj2typesoap(obj, ele.local_complextype, qualified)
- add_attributes2soap(obj, o)
- elsif ele.local_simpletype
- o = obj2typesoap(obj, ele.local_simpletype, qualified)
- else
- raise MappingError.new('illegal schema?')
- end
- o.elename = ele.name
- o
- end
-
- def obj2typesoap(obj, type, qualified)
- if type.is_a?(::WSDL::XMLSchema::SimpleType)
- simpleobj2soap(obj, type)
- else
- complexobj2soap(obj, type, qualified)
- end
- end
-
- def simpleobj2soap(obj, type)
- type.check_lexical_format(obj)
- return SOAPNil.new if obj.nil? # ToDo: check nillable.
- o = base2soap(obj, TypeMap[type.base])
- o
- end
-
- def complexobj2soap(obj, type, qualified)
- o = SOAPElement.new(type.name)
- o.qualified = qualified
- type.each_element do |child_ele|
- child = Mapping.get_attribute(obj, child_ele.name.name)
- if child.nil?
- if child_ele.nillable
- # ToDo: test
- # add empty element
- child_soap = obj2elesoap(nil, child_ele)
- o.add(child_soap)
- elsif Integer(child_ele.minoccurs) == 0
- # nothing to do
- else
- raise MappingError.new("nil not allowed: #{child_ele.name.name}")
- end
- elsif child_ele.map_as_array?
- child.each do |item|
- child_soap = obj2elesoap(item, child_ele)
- o.add(child_soap)
- end
- else
- child_soap = obj2elesoap(child, child_ele)
- o.add(child_soap)
- end
- end
- o
- end
-
- def any2soap(obj, qname)
- if obj.is_a?(SOAPElement)
- obj
- elsif obj.class.class_variables.include?('@@schema_element')
- stubobj2soap(obj, qname)
- elsif obj.is_a?(SOAP::Mapping::Object)
- mappingobj2soap(obj, qname)
- elsif obj.is_a?(Hash)
- ele = SOAPElement.from_obj(obj)
- ele.elename = qname
- ele
- else
- # expected to be a basetype or an anyType.
- # SOAPStruct, etc. is used instead of SOAPElement.
- begin
- ele = Mapping.obj2soap(obj, nil, nil, MAPPING_OPT)
- ele.elename = qname
- ele
- rescue MappingError
- ele = SOAPElement.new(qname, obj.to_s)
- end
- if obj.respond_to?(:__xmlattr)
- obj.__xmlattr.each do |key, value|
- ele.extraattr[key] = value
- end
- end
- ele
- end
- end
-
- def stubobj2soap(obj, qname)
- ele = SOAPElement.new(qname)
- ele.qualified =
- (obj.class.class_variables.include?('@@schema_qualified') and
- obj.class.class_eval('@@schema_qualified'))
- add_elements2soap(obj, ele)
- add_attributes2soap(obj, ele)
- ele
- end
-
- def mappingobj2soap(obj, qname)
- ele = SOAPElement.new(qname)
- obj.__xmlele.each do |key, value|
- if value.is_a?(::Array)
- value.each do |item|
- ele.add(obj2soap(item, key))
- end
- else
- ele.add(obj2soap(value, key))
- end
- end
- obj.__xmlattr.each do |key, value|
- ele.extraattr[key] = value
- end
- ele
- end
-
- def add_elements2soap(obj, ele)
- elements, as_array = schema_element_definition(obj.class)
- if elements
- elements.each do |elename, type|
- if child = Mapping.get_attribute(obj, elename.name)
- if as_array.include?(elename.name)
- child.each do |item|
- ele.add(obj2soap(item, elename))
- end
- else
- ele.add(obj2soap(child, elename))
- end
- elsif obj.is_a?(::Array) and as_array.include?(elename.name)
- obj.each do |item|
- ele.add(obj2soap(item, elename))
- end
- end
- end
- end
- end
-
- def add_attributes2soap(obj, ele)
- attributes = schema_attribute_definition(obj.class)
- if attributes
- attributes.each do |qname, param|
- attr = obj.__send__('xmlattr_' +
- XSD::CodeGen::GenSupport.safevarname(qname.name))
- ele.extraattr[qname] = attr
- end
- end
- end
-
- def base2soap(obj, type)
- soap_obj = nil
- if type <= XSD::XSDString
- str = XSD::Charset.encoding_conv(obj.to_s,
- Thread.current[:SOAPExternalCES], XSD::Charset.encoding)
- soap_obj = type.new(str)
- else
- soap_obj = type.new(obj)
- end
- soap_obj
- end
-
- def anytype2obj(node)
- if node.is_a?(::SOAP::SOAPBasetype)
- return node.data
- end
- klass = ::SOAP::Mapping::Object
- obj = klass.new
- obj
- end
-
- def any2obj(node, obj_class = nil)
- unless obj_class
- typestr = XSD::CodeGen::GenSupport.safeconstname(node.elename.name)
- obj_class = Mapping.class_from_name(typestr)
- end
- if obj_class and obj_class.class_variables.include?('@@schema_element')
- soapele2stubobj(node, obj_class)
- elsif node.is_a?(SOAPElement) or node.is_a?(SOAPStruct)
- # SOAPArray for literal?
- soapele2plainobj(node)
- else
- obj = Mapping.soap2obj(node, nil, obj_class, MAPPING_OPT)
- add_attributes2plainobj(node, obj)
- obj
- end
- end
-
- def soapele2stubobj(node, obj_class)
- obj = Mapping.create_empty_object(obj_class)
- add_elements2stubobj(node, obj)
- add_attributes2stubobj(node, obj)
- obj
- end
-
- def soapele2plainobj(node)
- obj = anytype2obj(node)
- add_elements2plainobj(node, obj)
- add_attributes2plainobj(node, obj)
- obj
- end
-
- def add_elements2stubobj(node, obj)
- elements, as_array = schema_element_definition(obj.class)
- vars = {}
- node.each do |name, value|
- item = elements.find { |k, v| k.name == name }
- if item
- elename, class_name = item
- if klass = Mapping.class_from_name(class_name)
- # klass must be a SOAPBasetype or a class
- if klass.ancestors.include?(::SOAP::SOAPBasetype)
- if value.respond_to?(:data)
- child = klass.new(value.data).data
- else
- child = klass.new(nil).data
- end
- else
- child = any2obj(value, klass)
- end
- elsif klass = Mapping.module_from_name(class_name)
- # simpletype
- if value.respond_to?(:data)
- child = value.data
- else
- raise MappingError.new(
- "cannot map to a module value: #{class_name}")
- end
- else
- raise MappingError.new("unknown class/module: #{class_name}")
- end
- else # untyped element is treated as anyType.
- child = any2obj(value)
- end
- if as_array.include?(elename.name)
- (vars[name] ||= []) << child
- else
- vars[name] = child
- end
- end
- Mapping.set_attributes(obj, vars)
- end
-
- def add_attributes2stubobj(node, obj)
- if attributes = schema_attribute_definition(obj.class)
- define_xmlattr(obj)
- attributes.each do |qname, class_name|
- attr = node.extraattr[qname]
- next if attr.nil? or attr.empty?
- klass = Mapping.class_from_name(class_name)
- if klass.ancestors.include?(::SOAP::SOAPBasetype)
- child = klass.new(attr).data
- else
- child = attr
- end
- obj.__xmlattr[qname] = child
- define_xmlattr_accessor(obj, qname)
- end
- end
- end
-
- def add_elements2plainobj(node, obj)
- node.each do |name, value|
- obj.__add_xmlele_value(value.elename, any2obj(value))
- end
- end
-
- def add_attributes2plainobj(node, obj)
- return if node.extraattr.empty?
- define_xmlattr(obj)
- node.extraattr.each do |qname, value|
- obj.__xmlattr[qname] = value
- define_xmlattr_accessor(obj, qname)
- end
- end
-
- if RUBY_VERSION > "1.7.0"
- def define_xmlattr_accessor(obj, qname)
- name = XSD::CodeGen::GenSupport.safemethodname(qname.name)
- Mapping.define_attr_accessor(obj, 'xmlattr_' + name,
- proc { @__xmlattr[qname] },
- proc { |value| @__xmlattr[qname] = value })
- end
- else
- def define_xmlattr_accessor(obj, qname)
- name = XSD::CodeGen::GenSupport.safemethodname(qname.name)
- obj.instance_eval <<-EOS
- def #{name}
- @__xmlattr[#{qname.dump}]
- end
-
- def #{name}=(value)
- @__xmlattr[#{qname.dump}] = value
- end
- EOS
- end
- end
-
- if RUBY_VERSION > "1.7.0"
- def define_xmlattr(obj)
- obj.instance_variable_set('@__xmlattr', {})
- unless obj.respond_to?(:__xmlattr)
- Mapping.define_attr_accessor(obj, :__xmlattr, proc { @__xmlattr })
- end
- end
- else
- def define_xmlattr(obj)
- obj.instance_variable_set('@__xmlattr', {})
- unless obj.respond_to?(:__xmlattr)
- obj.instance_eval <<-EOS
- def __xmlattr
- @__xmlattr
- end
- EOS
- end
- end
- end
-
- # it caches @@schema_element. this means that @@schema_element must not be
- # changed while a lifetime of a WSDLLiteralRegistry.
- def schema_element_definition(klass)
- @schema_element_cache[klass] ||= Mapping.schema_element_definition(klass)
- end
-
- def schema_attribute_definition(klass)
- @schema_attribute_cache[klass] ||= Mapping.schema_attribute_definition(klass)
- end
-end
-
-
-end
-end
diff --git a/lib/soap/marshal.rb b/lib/soap/marshal.rb
index 1c3d5b01db..7202a6aba8 100644
--- a/lib/soap/marshal.rb
+++ b/lib/soap/marshal.rb
@@ -14,9 +14,8 @@ module SOAP
module Marshal
- # Trying xsd:dateTime data to be recovered as aTime.
- MarshalMappingRegistry = Mapping::Registry.new(
- :allow_original_mapping => true)
+ # Trying xsd:dateTime data to be recovered as aTime. aDateTime if it fails.
+ MarshalMappingRegistry = Mapping::Registry.new(:allow_original_mapping => true)
MarshalMappingRegistry.add(
Time,
::SOAP::SOAPDateTime,
diff --git a/lib/soap/mimemessage.rb b/lib/soap/mimemessage.rb
index acb4322e11..1197cebc8c 100644
--- a/lib/soap/mimemessage.rb
+++ b/lib/soap/mimemessage.rb
@@ -112,7 +112,6 @@ class MIMEMessage
@headers = Headers.new
@headers.add("Content-Transfer-Encoding", "8bit")
@body = nil
- @contentid = nil
end
def self.parse(str)
@@ -148,7 +147,6 @@ class MIMEMessage
def initialize
@parts = []
@headers = Headers.new
- @root = nil
end
def self.parse(head, str)
@@ -199,7 +197,7 @@ class MIMEMessage
def add_part(content)
part = Part.new
part.headers.add("Content-Type",
- "text/xml; charset=" + XSD::Charset.xml_encoding_label)
+ "text/xml; charset=" + XSD::Charset.encoding_label)
part.headers.add("Content-ID", Attachment.contentid(part))
part.body = content
@parts.unshift(part)
diff --git a/lib/soap/netHttpClient.rb b/lib/soap/netHttpClient.rb
index 10d68e2a4c..1e9d71c5a3 100644
--- a/lib/soap/netHttpClient.rb
+++ b/lib/soap/netHttpClient.rb
@@ -26,45 +26,35 @@ class NetHttpClient
attr_accessor :debug_dev
attr_accessor :ssl_config # ignored for now.
attr_accessor :protocol_version # ignored for now.
- attr_accessor :connect_timeout
- attr_accessor :send_timeout # ignored for now.
- attr_accessor :receive_timeout
def initialize(proxy = nil, agent = nil)
@proxy = proxy ? URI.parse(proxy) : nil
@agent = agent
@debug_dev = nil
@session_manager = SessionManager.new
- @no_proxy = @ssl_config = @protocol_version = nil
- @connect_timeout = @send_timeout = @receive_timeout = nil
+ @no_proxy = nil
end
def test_loopback_response
raise NotImplementedError.new("not supported for now")
end
- def proxy=(proxy)
- if proxy.nil?
+ def proxy=(proxy_str)
+ if proxy_str.nil?
@proxy = nil
else
- if proxy.is_a?(URI)
- @proxy = proxy
- else
- @proxy = URI.parse(proxy)
- end
+ @proxy = URI.parse(proxy_str)
if @proxy.scheme == nil or @proxy.scheme.downcase != 'http' or
@proxy.host == nil or @proxy.port == nil
- raise ArgumentError.new("unsupported proxy `#{proxy}'")
+ raise ArgumentError.new("unsupported proxy `#{proxy_str}'")
end
+ @proxy
end
- reset_all
- @proxy
end
def set_basic_auth(uri, user_id, passwd)
# net/http does not handle url.
@basic_auth = [user_id, passwd]
- raise NotImplementedError.new("basic_auth is not supported under soap4r + net/http.")
end
def set_cookie_store(filename)
@@ -84,9 +74,7 @@ class NetHttpClient
end
def post(url, req_body, header = {})
- unless url.is_a?(URI)
- url = URI.parse(url)
- end
+ url = URI.parse(url)
extra = header.dup
extra['User-Agent'] = @agent if @agent
res = start(url) { |http|
@@ -96,9 +84,7 @@ class NetHttpClient
end
def get_content(url, header = {})
- unless url.is_a?(URI)
- url = URI.parse(url)
- end
+ url = URI.parse(url)
extra = header.dup
extra['User-Agent'] = @agent if @agent
res = start(url) { |http|
@@ -113,7 +99,7 @@ private
http = create_connection(url)
response = nil
http.start { |worker|
- response = yield(worker)
+ response, = yield(worker)
worker.finish
}
@debug_dev << response.body if @debug_dev
@@ -130,8 +116,6 @@ private
if http.respond_to?(:set_debug_output)
http.set_debug_output(@debug_dev)
end
- http.open_timeout = @connect_timeout if @connect_timeout
- http.read_timeout = @receive_timeout if @receive_timeout
case url
when URI::HTTPS
if SSLEnabled
diff --git a/lib/soap/parser.rb b/lib/soap/parser.rb
index 412fd4855a..14704a6d9b 100644
--- a/lib/soap/parser.rb
+++ b/lib/soap/parser.rb
@@ -60,7 +60,6 @@ private
public
- attr_accessor :envelopenamespace
attr_accessor :default_encodingstyle
attr_accessor :decode_typemap
attr_accessor :allow_unqualified_element
@@ -71,7 +70,6 @@ public
@parsestack = nil
@lastnode = nil
@handlers = {}
- @envelopenamespace = opt[:envelopenamespace] || EnvelopeNamespace
@default_encodingstyle = opt[:default_encodingstyle] || EncodingNamespace
@decode_typemap = opt[:decode_typemap] || nil
@allow_unqualified_element = opt[:allow_unqualified_element] || false
@@ -136,7 +134,10 @@ public
lastframe = @parsestack.last
if lastframe
# Need not to be cloned because character does not have attr.
- decode_text(lastframe.ns, text, lastframe.encodingstyle)
+ ns = lastframe.ns
+ parent = lastframe.node
+ encodingstyle = lastframe.encodingstyle
+ decode_text(ns, text, encodingstyle)
else
# Ignore Text outside of SOAP Envelope.
p text if $DEBUG
@@ -156,7 +157,7 @@ private
def find_encodingstyle(ns, attrs)
attrs.each do |key, value|
- if (ns.compare(@envelopenamespace, AttrEncodingStyle, key))
+ if (ns.compare(EnvelopeNamespace, AttrEncodingStyle, key))
return value
end
end
@@ -167,7 +168,7 @@ private
ele = ns.parse(name)
# Envelope based parsing.
- if ((ele.namespace == @envelopenamespace) ||
+ if ((ele.namespace == EnvelopeNamespace) ||
(@allow_unqualified_element && ele.namespace.nil?))
o = decode_soap_envelope(ns, ele, attrs, parent)
return o if o
diff --git a/lib/soap/property.rb b/lib/soap/property.rb
index 882dcc6e28..113cc64f3c 100644
--- a/lib/soap/property.rb
+++ b/lib/soap/property.rb
@@ -32,8 +32,6 @@ module SOAP
# aaa.hhh = iii
#
class Property
- FrozenError = (RUBY_VERSION >= "1.9.0") ? RuntimeError : TypeError
-
include Enumerable
module Util
@@ -80,7 +78,8 @@ class Property
when LINE_REGEXP
key, value = $1.strip, $2.strip
key = "#{key_prefix}.#{key}" unless key_prefix.empty?
- key, value = loadstr(key), loadstr(value)
+ key = eval("\"#{key}\"")
+ value = eval("\"#{value}\"")
self[key] = value
else
raise TypeError.new(
@@ -191,7 +190,7 @@ protected
def local_referent(key)
check_lock(key)
if propkey?(@store[key]) and @store[key].locked?
- raise FrozenError.new("cannot split any key from locked property")
+ raise TypeError.new("cannot split any key from locked property")
end
@store[key]
end
@@ -200,9 +199,9 @@ protected
check_lock(key)
if @locked
if propkey?(value)
- raise FrozenError.new("cannot add any key to locked property")
+ raise TypeError.new("cannot add any key to locked property")
elsif propkey?(@store[key])
- raise FrozenError.new("cannot override any key in locked property")
+ raise TypeError.new("cannot override any key in locked property")
end
end
@store[key] = value
@@ -266,7 +265,7 @@ private
def check_lock(key)
if @locked and (key.nil? or !@store.key?(key))
- raise FrozenError.new("cannot add any key to locked property")
+ raise TypeError.new("cannot add any key to locked property")
end
end
@@ -309,10 +308,6 @@ private
load(f)
end
end
-
- def loadstr(str)
- str.gsub(/\\./) { |c| eval("\"#{c}\"") }
- end
end
diff --git a/lib/soap/rpc/cgistub.rb b/lib/soap/rpc/cgistub.rb
index 487f05a9bf..55437bac59 100644
--- a/lib/soap/rpc/cgistub.rb
+++ b/lib/soap/rpc/cgistub.rb
@@ -1,5 +1,5 @@
-# SOAP4R - CGI/mod_ruby stub library
-# Copyright (C) 2001, 2003-2005 NAKAMURA, Hiroshi <nahi@ruby-lang.org>.
+# SOAP4R - CGI stub library
+# Copyright (C) 2001, 2003, 2004 NAKAMURA, Hiroshi <nahi@ruby-lang.org>.
# This program is copyrighted free software by NAKAMURA, Hiroshi. You can
# redistribute it and/or modify it under the same terms of Ruby's license;
@@ -10,7 +10,7 @@ require 'soap/streamHandler'
require 'webrick/httpresponse'
require 'webrick/httpstatus'
require 'logger'
-require 'soap/rpc/soaplet'
+require 'soap/rpc/router'
module SOAP
@@ -26,51 +26,57 @@ module RPC
#
class CGIStub < Logger::Application
include SOAP
- include WEBrick
- class SOAPRequest
- attr_reader :body
-
- def [](var); end
-
- def meta_vars; end
- end
+ # There is a client which does not accept the media-type which is defined in
+ # SOAP spec.
+ attr_accessor :mediatype
- class SOAPStdinRequest < SOAPRequest
- attr_reader :body
+ class CGIError < Error; end
- def initialize(stream)
- size = ENV['CONTENT_LENGTH'].to_i || 0
- @body = stream.read(size)
+ class SOAPRequest
+ ALLOWED_LENGTH = 1024 * 1024
+
+ def initialize(stream = $stdin)
+ @method = ENV['REQUEST_METHOD']
+ @size = ENV['CONTENT_LENGTH'].to_i || 0
+ @contenttype = ENV['CONTENT_TYPE']
+ @soapaction = ENV['HTTP_SOAPAction']
+ @source = stream
+ @body = nil
end
- def [](var)
- ENV[var.gsub(/-/, '_').upcase]
+ def init
+ validate
+ @body = @source.read(@size)
+ self
end
- def meta_vars
- {
- 'HTTP_SOAPACTION' => ENV['HTTP_SOAPAction']
- }
+ def dump
+ @body.dup
end
- end
- class SOAPFCGIRequest < SOAPRequest
- attr_reader :body
+ def soapaction
+ @soapaction
+ end
- def initialize(request)
- @request = request
- @body = @request.in.read
+ def contenttype
+ @contenttype
end
- def [](var)
- @request.env[var.gsub(/-/, '_').upcase]
+ def to_s
+ "method: #{ @method }, size: #{ @size }"
end
- def meta_vars
- {
- 'HTTP_SOAPACTION' => @request.env['HTTP_SOAPAction']
- }
+ private
+
+ def validate # raise CGIError
+ if @method != 'POST'
+ raise CGIError.new("Method '#{ @method }' not allowed.")
+ end
+
+ if @size > ALLOWED_LENGTH
+ raise CGIError.new("Content-length too long.")
+ end
end
end
@@ -79,14 +85,33 @@ class CGIStub < Logger::Application
set_log(STDERR)
self.level = ERROR
@default_namespace = default_namespace
+ @router = SOAP::RPC::Router.new(appname)
+ @remote_user = ENV['REMOTE_USER'] || 'anonymous'
@remote_host = ENV['REMOTE_HOST'] || ENV['REMOTE_ADDR'] || 'unknown'
- @router = ::SOAP::RPC::Router.new(self.class.name)
- @soaplet = ::SOAP::RPC::SOAPlet.new(@router)
+ @request = nil
+ @response = nil
+ @mediatype = MediaType
on_init
end
+ def add_rpc_servant(obj, namespace = @default_namespace, soapaction = nil)
+ RPC.defined_methods(obj).each do |name|
+ qname = XSD::QName.new(namespace, name)
+ param_size = obj.method(name).arity.abs
+ params = (1..param_size).collect { |i| "p#{i}" }
+ param_def = SOAP::RPC::SOAPMethod.create_param_def(params)
+ @router.add_method(obj, qname, soapaction, name, param_def)
+ end
+ end
+ alias add_servant add_rpc_servant
+
+ def add_rpc_headerhandler(obj)
+ @router.headerhandler << obj
+ end
+ alias add_headerhandler add_rpc_headerhandler
+
def on_init
- # do extra initialization in a derived class if needed.
+ # Override this method in derived class to call 'add_method' to add methods.
end
def mapping_registry
@@ -97,108 +122,83 @@ class CGIStub < Logger::Application
@router.mapping_registry = value
end
- def generate_explicit_type
- @router.generate_explicit_type
+ def add_method(receiver, name, *param)
+ add_method_with_namespace_as(@default_namespace, receiver,
+ name, name, *param)
end
- def generate_explicit_type=(generate_explicit_type)
- @router.generate_explicit_type = generate_explicit_type
+ def add_method_as(receiver, name, name_as, *param)
+ add_method_with_namespace_as(@default_namespace, receiver,
+ name, name_as, *param)
end
- # servant entry interface
-
- def add_rpc_servant(obj, namespace = @default_namespace)
- @router.add_rpc_servant(obj, namespace)
+ def add_method_with_namespace(namespace, receiver, name, *param)
+ add_method_with_namespace_as(namespace, receiver, name, name, *param)
end
- alias add_servant add_rpc_servant
-
- def add_headerhandler(obj)
- @router.add_headerhandler(obj)
- end
- alias add_rpc_headerhandler add_headerhandler
-
- # method entry interface
- def add_rpc_method(obj, name, *param)
- add_rpc_method_with_namespace_as(@default_namespace, obj, name, name, *param)
- end
- alias add_method add_rpc_method
-
- def add_rpc_method_as(obj, name, name_as, *param)
- add_rpc_method_with_namespace_as(@default_namespace, obj, name, name_as, *param)
- end
- alias add_method_as add_rpc_method_as
-
- def add_rpc_method_with_namespace(namespace, obj, name, *param)
- add_rpc_method_with_namespace_as(namespace, obj, name, name, *param)
- end
- alias add_method_with_namespace add_rpc_method_with_namespace
-
- def add_rpc_method_with_namespace_as(namespace, obj, name, name_as, *param)
+ def add_method_with_namespace_as(namespace, receiver, name, name_as, *param)
+ param_def = if param.size == 1 and param[0].is_a?(Array)
+ param[0]
+ else
+ SOAP::RPC::SOAPMethod.create_param_def(param)
+ end
qname = XSD::QName.new(namespace, name_as)
- soapaction = nil
- param_def = SOAPMethod.derive_rpc_param_def(obj, name, *param)
- @router.add_rpc_operation(obj, qname, soapaction, name, param_def)
+ @router.add_method(receiver, qname, nil, name, param_def)
end
- alias add_method_with_namespace_as add_rpc_method_with_namespace_as
- def add_rpc_operation(receiver, qname, soapaction, name, param_def, opt = {})
- @router.add_rpc_operation(receiver, qname, soapaction, name, param_def, opt)
+ def route(conn_data)
+ @router.route(conn_data)
end
- def add_document_operation(receiver, soapaction, name, param_def, opt = {})
- @router.add_document_operation(receiver, soapaction, name, param_def, opt)
- end
-
- def set_fcgi_request(request)
- @fcgi = request
+ def create_fault_response(e)
+ @router.create_fault_response(e)
end
private
-
- HTTPVersion = WEBrick::HTTPVersion.new('1.0') # dummy; ignored
-
+
def run
- res = WEBrick::HTTPResponse.new({:HTTPVersion => HTTPVersion})
+ prologue
+
+ httpversion = WEBrick::HTTPVersion.new('1.0')
+ @response = WEBrick::HTTPResponse.new({:HTTPVersion => httpversion})
+ conn_data = nil
begin
- @log.info { "received a request from '#{ @remote_host }'" }
- if @fcgi
- req = SOAPFCGIRequest.new(@fcgi)
- else
- req = SOAPStdinRequest.new($stdin)
+ log(INFO) { "Received a request from '#{ @remote_user }@#{ @remote_host }'." }
+ # SOAP request parsing.
+ @request = SOAPRequest.new.init
+ @response['Status'] = 200
+ conn_data = ::SOAP::StreamHandler::ConnectionData.new
+ conn_data.receive_string = @request.dump
+ conn_data.receive_contenttype = @request.contenttype
+ log(DEBUG) { "XML Request: #{conn_data.receive_string}" }
+ conn_data = route(conn_data)
+ log(DEBUG) { "XML Response: #{conn_data.send_string}" }
+ if conn_data.is_fault
+ @response['Status'] = 500
end
- @soaplet.do_POST(req, res)
- rescue HTTPStatus::EOFError, HTTPStatus::RequestTimeout => ex
- res.set_error(ex)
- rescue HTTPStatus::Error => ex
- res.set_error(ex)
- rescue HTTPStatus::Status => ex
- res.status = ex.code
- rescue StandardError, NameError => ex # for Ruby 1.6
- res.set_error(ex, true)
+ @response['Cache-Control'] = 'private'
+ @response.body = conn_data.send_string
+ @response['content-type'] = conn_data.send_contenttype
+ rescue Exception
+ conn_data = create_fault_response($!)
+ @response['Cache-Control'] = 'private'
+ @response['Status'] = 500
+ @response.body = conn_data.send_string
+ @response['content-type'] = conn_data.send_contenttype || @mediatype
ensure
- if defined?(MOD_RUBY)
- r = Apache.request
- r.status = res.status
- r.content_type = res.content_type
- r.send_http_header
- buf = res.body
- else
- buf = ''
- res.send_response(buf)
- buf.sub!(/^[^\r]+\r\n/, '') # Trim status line.
- end
- @log.debug { "SOAP CGI Response:\n#{ buf }" }
- if @fcgi
- @fcgi.out.print buf
- @fcgi.finish
- @fcgi = nil
- else
- print buf
- end
+ buf = ''
+ @response.send_response(buf)
+ buf.sub!(/^[^\r]+\r\n/, '') # Trim status line.
+ log(DEBUG) { "SOAP CGI Response:\n#{ buf }" }
+ print buf
+ epilogue
end
+
0
end
+
+ def prologue; end
+ def epilogue; end
end
diff --git a/lib/soap/rpc/driver.rb b/lib/soap/rpc/driver.rb
index 0fb4e82488..0e59dde9be 100644
--- a/lib/soap/rpc/driver.rb
+++ b/lib/soap/rpc/driver.rb
@@ -1,5 +1,5 @@
# SOAP4R - SOAP RPC driver
-# Copyright (C) 2000, 2001, 2003-2005 NAKAMURA, Hiroshi <nahi@ruby-lang.org>.
+# Copyright (C) 2000, 2001, 2003, 2004 NAKAMURA, Hiroshi <nahi@ruby-lang.org>.
# This program is copyrighted free software by NAKAMURA, Hiroshi. You can
# redistribute it and/or modify it under the same terms of Ruby's license;
@@ -8,7 +8,6 @@
require 'soap/soap'
require 'soap/mapping'
-require 'soap/mapping/wsdlliteralregistry'
require 'soap/rpc/rpc'
require 'soap/rpc/proxy'
require 'soap/rpc/element'
@@ -22,95 +21,70 @@ module RPC
class Driver
+ class EmptyResponseError < Error; end
+
class << self
- if RUBY_VERSION >= "1.7.0"
- def __attr_proxy(symbol, assignable = false)
- name = symbol.to_s
- define_method(name) {
- @proxy.__send__(name)
- }
- if assignable
- aname = name + '='
- define_method(aname) { |rhs|
- @proxy.__send__(aname, rhs)
- }
- end
- end
- else
- def __attr_proxy(symbol, assignable = false)
- name = symbol.to_s
- module_eval <<-EOS
- def #{name}
- @proxy.#{name}
- end
- EOS
- if assignable
- module_eval <<-EOS
- def #{name}=(value)
- @proxy.#{name} = value
- end
- EOS
- end
+ def __attr_proxy(symbol, assignable = false)
+ name = symbol.to_s
+ module_eval <<-EOD
+ def #{name}
+ @servant.#{name}
+ end
+ EOD
+ if assignable
+ module_eval <<-EOD
+ def #{name}=(rhs)
+ @servant.#{name} = rhs
+ end
+ EOD
end
end
end
+ __attr_proxy :options
+ __attr_proxy :headerhandler
+ __attr_proxy :test_loopback_response
__attr_proxy :endpoint_url, true
__attr_proxy :mapping_registry, true
+ __attr_proxy :soapaction, true
__attr_proxy :default_encodingstyle, true
- __attr_proxy :generate_explicit_type, true
- __attr_proxy :allow_unqualified_element, true
- __attr_proxy :headerhandler
- __attr_proxy :streamhandler
- __attr_proxy :test_loopback_response
- __attr_proxy :reset_stream
-
- attr_reader :proxy
- attr_reader :options
- attr_accessor :soapaction
-
- def inspect
- "#<#{self.class}:#{@proxy.inspect}>"
- end
def httpproxy
- options["protocol.http.proxy"]
+ @servant.options["protocol.http.proxy"]
end
def httpproxy=(httpproxy)
- options["protocol.http.proxy"] = httpproxy
+ @servant.options["protocol.http.proxy"] = httpproxy
end
def wiredump_dev
- options["protocol.http.wiredump_dev"]
+ @servant.options["protocol.http.wiredump_dev"]
end
def wiredump_dev=(wiredump_dev)
- options["protocol.http.wiredump_dev"] = wiredump_dev
+ @servant.options["protocol.http.wiredump_dev"] = wiredump_dev
end
def mandatorycharset
- options["protocol.mandatorycharset"]
+ @servant.options["protocol.mandatorycharset"]
end
def mandatorycharset=(mandatorycharset)
- options["protocol.mandatorycharset"] = mandatorycharset
+ @servant.options["protocol.mandatorycharset"] = mandatorycharset
end
def wiredump_file_base
- options["protocol.wiredump_file_base"]
+ @servant.options["protocol.wiredump_file_base"]
end
def wiredump_file_base=(wiredump_file_base)
- options["protocol.wiredump_file_base"] = wiredump_file_base
+ @servant.options["protocol.wiredump_file_base"] = wiredump_file_base
end
- def initialize(endpoint_url, namespace = nil, soapaction = nil)
- @namespace = namespace
- @soapaction = soapaction
- @options = setup_options
- @wiredump_file_base = nil
- @proxy = Proxy.new(endpoint_url, @soapaction, @options)
+ def initialize(endpoint_url, namespace, soapaction = nil)
+ @servant = Servant__.new(self, endpoint_url, namespace)
+ @servant.soapaction = soapaction
+ @proxy = @servant.proxy
end
def loadproperty(propertyname)
@@ -119,132 +93,204 @@ class Driver
end
end
- def add_rpc_method(name, *params)
- add_rpc_method_with_soapaction_as(name, name, @soapaction, *params)
- end
-
- def add_rpc_method_as(name, name_as, *params)
- add_rpc_method_with_soapaction_as(name, name_as, @soapaction, *params)
+ def inspect
+ "#<#{self.class}:#{@servant.streamhandler.inspect}>"
end
- def add_rpc_method_with_soapaction(name, soapaction, *params)
- add_rpc_method_with_soapaction_as(name, name, soapaction, *params)
+ def add_method(name, *params)
+ add_method_with_soapaction_as(name, name, @servant.soapaction, *params)
end
- def add_rpc_method_with_soapaction_as(name, name_as, soapaction, *params)
- param_def = SOAPMethod.create_rpc_param_def(params)
- qname = XSD::QName.new(@namespace, name_as)
- @proxy.add_rpc_method(qname, soapaction, name, param_def)
- add_rpc_method_interface(name, param_def)
+ def add_method_as(name, name_as, *params)
+ add_method_with_soapaction_as(name, name_as, @servant.soapaction, *params)
end
- # add_method is for shortcut of typical rpc/encoded method definition.
- alias add_method add_rpc_method
- alias add_method_as add_rpc_method_as
- alias add_method_with_soapaction add_rpc_method_with_soapaction
- alias add_method_with_soapaction_as add_rpc_method_with_soapaction_as
-
- def add_document_method(name, soapaction, req_qname, res_qname)
- param_def = SOAPMethod.create_doc_param_def(req_qname, res_qname)
- @proxy.add_document_method(soapaction, name, param_def)
- add_document_method_interface(name, param_def)
+ def add_method_with_soapaction(name, soapaction, *params)
+ add_method_with_soapaction_as(name, name, soapaction, *params)
end
- def add_rpc_operation(qname, soapaction, name, param_def, opt = {})
- @proxy.add_rpc_operation(qname, soapaction, name, param_def, opt)
- add_rpc_method_interface(name, param_def)
+ def add_method_with_soapaction_as(name, name_as, soapaction, *params)
+ param_def = if params.size == 1 and params[0].is_a?(Array)
+ params[0]
+ else
+ SOAPMethod.create_param_def(params)
+ end
+ @servant.add_method(name_as, soapaction, name, param_def)
end
- def add_document_operation(soapaction, name, param_def, opt = {})
- @proxy.add_document_operation(soapaction, name, param_def, opt)
- add_document_method_interface(name, param_def)
+ def reset_stream
+ @servant.streamhandler.reset
end
def invoke(headers, body)
- if headers and !headers.is_a?(SOAPHeader)
- headers = create_header(headers)
- end
- set_wiredump_file_base(body.elename.name)
- env = @proxy.invoke(headers, body)
- if env.nil?
- return nil, nil
- else
- return env.header, env.body
- end
+ @servant.invoke(headers, body)
end
def call(name, *params)
- set_wiredump_file_base(name)
- @proxy.call(name, *params)
+ @servant.call(name, *params)
end
private
- def set_wiredump_file_base(name)
- if @wiredump_file_base
- @proxy.set_wiredump_file_base("#{@wiredump_file_base}_#{name}")
- end
+ def add_rpc_method_interface(name, param_def)
+ @servant.add_rpc_method_interface(name, param_def)
end
- def create_header(headers)
- header = SOAPHeader.new()
- headers.each do |content, mustunderstand, encodingstyle|
- header.add(SOAPHeaderItem.new(content, mustunderstand, encodingstyle))
+ class Servant__
+ attr_reader :options
+ attr_reader :streamhandler
+ attr_reader :headerhandler
+ attr_reader :proxy
+
+ def initialize(host, endpoint_url, namespace)
+ @host = host
+ @namespace = namespace
+ @mapping_registry = nil
+ @soapaction = nil
+ @wiredump_file_base = nil
+ @options = setup_options
+ @streamhandler = HTTPPostStreamHandler.new(endpoint_url,
+ @options["protocol.http"] ||= ::SOAP::Property.new)
+ @headerhandler = Header::HandlerSet.new
+ @proxy = Proxy.new(@streamhandler, @soapaction)
+ @proxy.allow_unqualified_element = true
end
- header
- end
- def setup_options
- if opt = Property.loadproperty(::SOAP::PropertyName)
- opt = opt["client"]
+ def endpoint_url
+ @streamhandler.endpoint_url
end
- opt ||= Property.new
- opt.add_hook("protocol.mandatorycharset") do |key, value|
- @proxy.mandatorycharset = value
+
+ def endpoint_url=(endpoint_url)
+ @streamhandler.endpoint_url = endpoint_url
+ @streamhandler.reset
end
- opt.add_hook("protocol.wiredump_file_base") do |key, value|
- @wiredump_file_base = value
+
+ def mapping_registry
+ @mapping_registry
end
- opt["protocol.http.charset"] ||= XSD::Charset.xml_encoding_label
- opt["protocol.http.proxy"] ||= Env::HTTP_PROXY
- opt["protocol.http.no_proxy"] ||= Env::NO_PROXY
- opt
- end
- def add_rpc_method_interface(name, param_def)
- param_count = RPC::SOAPMethod.param_count(param_def,
- RPC::SOAPMethod::IN, RPC::SOAPMethod::INOUT)
- add_method_interface(name, param_count)
- end
+ def mapping_registry=(mapping_registry)
+ @mapping_registry = mapping_registry
+ end
- def add_document_method_interface(name, param_def)
- param_count = RPC::SOAPMethod.param_count(param_def, RPC::SOAPMethod::IN)
- add_method_interface(name, param_count)
- end
+ def soapaction
+ @soapaction
+ end
+
+ def soapaction=(soapaction)
+ @soapaction = soapaction
+ end
- if RUBY_VERSION > "1.7.0"
- def add_method_interface(name, param_count)
- ::SOAP::Mapping.define_singleton_method(self, name) do |*arg|
- unless arg.size == param_count
- raise ArgumentError.new(
- "wrong number of arguments (#{arg.size} for #{param_count})")
- end
- call(name, *arg)
+ def default_encodingstyle
+ @proxy.default_encodingstyle
+ end
+
+ def default_encodingstyle=(encodingstyle)
+ @proxy.default_encodingstyle = encodingstyle
+ end
+
+ def test_loopback_response
+ @streamhandler.test_loopback_response
+ end
+
+ def invoke(headers, body)
+ set_wiredump_file_base(body.elename.name)
+ env = @proxy.invoke(headers, body)
+ if env.nil?
+ return nil, nil
+ else
+ return env.header, env.body
end
- self.method(name)
- end
- else
- def add_method_interface(name, param_count)
- instance_eval <<-EOS
- def #{name}(*arg)
- unless arg.size == #{param_count}
- raise ArgumentError.new(
- "wrong number of arguments (\#{arg.size} for #{param_count})")
- end
- call(#{name.dump}, *arg)
- end
+ end
+
+ def call(name, *params)
+ set_wiredump_file_base(name)
+ # Convert parameters: params array => SOAPArray => members array
+ params = Mapping.obj2soap(params, @mapping_registry).to_a
+ env = @proxy.call(call_headers, name, *params)
+ raise EmptyResponseError.new("Empty response.") unless env
+ receive_headers(env.header)
+ begin
+ @proxy.check_fault(env.body)
+ rescue SOAP::FaultError => e
+ Mapping.fault2exception(e)
+ end
+
+ ret = env.body.response ?
+ Mapping.soap2obj(env.body.response, @mapping_registry) : nil
+ if env.body.outparams
+ outparams = env.body.outparams.collect { |outparam|
+ Mapping.soap2obj(outparam)
+ }
+ return [ret].concat(outparams)
+ else
+ return ret
+ end
+ end
+
+ def add_method(name_as, soapaction, name, param_def)
+ qname = XSD::QName.new(@namespace, name_as)
+ @proxy.add_method(qname, soapaction, name, param_def)
+ add_rpc_method_interface(name, param_def)
+ end
+
+ def add_rpc_method_interface(name, param_def)
+ param_names = []
+ i = 0
+ @proxy.method[name].each_param_name(RPC::SOAPMethod::IN,
+ RPC::SOAPMethod::INOUT) do |param_name|
+ i += 1
+ param_names << "arg#{ i }"
+ end
+ callparam = (param_names.collect { |pname| ", " + pname }).join
+ @host.instance_eval <<-EOS
+ def #{ name }(#{ param_names.join(", ") })
+ @servant.call(#{ name.dump }#{ callparam })
+ end
EOS
- self.method(name)
+ @host.method(name)
+ end
+
+ private
+
+ def call_headers
+ headers = @headerhandler.on_outbound
+ if headers.empty?
+ nil
+ else
+ h = ::SOAP::SOAPHeader.new
+ headers.each do |header|
+ h.add(header.elename.name, header)
+ end
+ h
+ end
+ end
+
+ def receive_headers(headers)
+ @headerhandler.on_inbound(headers) if headers
+ end
+
+ def set_wiredump_file_base(name)
+ if @wiredump_file_base
+ @streamhandler.wiredump_file_base = @wiredump_file_base + "_#{ name }"
+ end
+ end
+
+ def setup_options
+ if opt = Property.loadproperty(::SOAP::PropertyName)
+ opt = opt["client"]
+ end
+ opt ||= Property.new
+ opt.add_hook("protocol.mandatorycharset") do |key, value|
+ @proxy.mandatorycharset = value
+ end
+ opt.add_hook("protocol.wiredump_file_base") do |key, value|
+ @wiredump_file_base = value
+ end
+ opt["protocol.http.charset"] ||= XSD::Charset.encoding_label
+ opt["protocol.http.proxy"] ||= Env::HTTP_PROXY
+ opt["protocol.http.no_proxy"] ||= Env::NO_PROXY
+ opt
end
end
end
diff --git a/lib/soap/rpc/element.rb b/lib/soap/rpc/element.rb
index c224b03d0d..8a2f319293 100644
--- a/lib/soap/rpc/element.rb
+++ b/lib/soap/rpc/element.rb
@@ -1,5 +1,5 @@
# SOAP4R - RPC element definition.
-# Copyright (C) 2000, 2001, 2003, 2005 NAKAMURA, Hiroshi <nahi@ruby-lang.org>.
+# Copyright (C) 2000, 2001, 2003 NAKAMURA, Hiroshi <nahi@ruby-lang.org>.
# This program is copyrighted free software by NAKAMURA, Hiroshi. You can
# redistribute it and/or modify it under the same terms of Ruby's license;
@@ -20,25 +20,21 @@ class SOAPBody < SOAPStruct
end
def response
- root = root_node
if !@is_fault
- if root.nil?
+ if void?
nil
- elsif root.is_a?(SOAPBasetype)
- root
else
# Initial element is [retval].
- root[0]
+ root_node[0]
end
else
- root
+ root_node
end
end
def outparams
- root = root_node
- if !@is_fault and !root.nil? and !root.is_a?(SOAPBasetype)
- op = root[1..-1]
+ if !@is_fault and !void?
+ op = root_node[1..-1]
op = nil if op && op.empty?
op
else
@@ -46,6 +42,10 @@ class SOAPBody < SOAPStruct
end
end
+ def void?
+ root_node.nil?
+ end
+
def fault
if @is_fault
self['fault']
@@ -77,8 +77,6 @@ class SOAPMethod < SOAPStruct
attr_reader :param_def
attr_reader :inparam
attr_reader :outparam
- attr_reader :retval_name
- attr_reader :retval_class_name
def initialize(qname, param_def = nil)
super(nil)
@@ -95,7 +93,6 @@ class SOAPMethod < SOAPStruct
@inparam = {}
@outparam = {}
@retval_name = nil
- @retval_class_name = nil
init_param(@param_def) if @param_def
end
@@ -104,12 +101,12 @@ class SOAPMethod < SOAPStruct
@outparam_names.size > 0
end
- def input_params
- collect_params(IN, INOUT)
- end
-
- def output_params
- collect_params(OUT, INOUT)
+ def each_param_name(*type)
+ @signature.each do |io_type, name, param_type|
+ if type.include?(io_type)
+ yield(name)
+ end
+ end
end
def set_param(params)
@@ -127,30 +124,7 @@ class SOAPMethod < SOAPStruct
end
end
- def SOAPMethod.param_count(param_def, *type)
- count = 0
- param_def.each do |io_type, name, param_type|
- if type.include?(io_type)
- count += 1
- end
- end
- count
- end
-
- def SOAPMethod.derive_rpc_param_def(obj, name, *param)
- if param.size == 1 and param[0].is_a?(Array)
- return param[0]
- end
- if param.empty?
- method = obj.method(name)
- param_names = (1..method.arity.abs).collect { |i| "p#{i}" }
- else
- param_names = param
- end
- create_rpc_param_def(param_names)
- end
-
- def SOAPMethod.create_rpc_param_def(param_names)
+ def SOAPMethod.create_param_def(param_names)
param_def = []
param_names.each do |param_name|
param_def.push([IN, param_name, nil])
@@ -159,29 +133,8 @@ class SOAPMethod < SOAPStruct
param_def
end
- def SOAPMethod.create_doc_param_def(req_qnames, res_qnames)
- req_qnames = [req_qnames] if req_qnames.is_a?(XSD::QName)
- res_qnames = [res_qnames] if res_qnames.is_a?(XSD::QName)
- param_def = []
- req_qnames.each do |qname|
- param_def << [IN, qname.name, [nil, qname.namespace, qname.name]]
- end
- res_qnames.each do |qname|
- param_def << [OUT, qname.name, [nil, qname.namespace, qname.name]]
- end
- param_def
- end
-
private
- def collect_params(*type)
- names = []
- @signature.each do |io_type, name, param_type|
- names << name if type.include?(io_type)
- end
- names
- end
-
def init_param(param_def)
param_def.each do |io_type, name, param_type|
case io_type
@@ -195,20 +148,12 @@ private
@signature.push([INOUT, name, param_type])
@inoutparam_names.push(name)
when RETVAL
- if @retval_name
- raise MethodDefinitionError.new('duplicated retval')
+ if (@retval_name)
+ raise MethodDefinitionError.new('Duplicated retval')
end
@retval_name = name
- @retval_class_name = nil
- if param_type
- if param_type[0].is_a?(String)
- @retval_class_name = Mapping.class_from_name(param_type[0])
- else
- @retval_class_name = param_type[0]
- end
- end
else
- raise MethodDefinitionError.new("unknown type: #{io_type}")
+ raise MethodDefinitionError.new("Unknown type: #{ io_type }")
end
end
end
@@ -223,7 +168,7 @@ class SOAPMethodRequest < SOAPMethod
param_value = []
i = 0
params.each do |param|
- param_name = "p#{i}"
+ param_name = "p#{ i }"
i += 1
param_def << [IN, param_name, nil]
param_value << [param_name, param]
@@ -241,9 +186,9 @@ class SOAPMethodRequest < SOAPMethod
end
def each
- input_params.each do |name|
+ each_param_name(IN, INOUT) do |name|
unless @inparam[name]
- raise ParameterError.new("parameter: #{name} was not given")
+ raise ParameterError.new("Parameter: #{ name } was not given.")
end
yield(name, @inparam[name])
end
@@ -255,10 +200,10 @@ class SOAPMethodRequest < SOAPMethod
req
end
- def create_method_response(response_name = nil)
- response_name ||=
- XSD::QName.new(@elename.namespace, @elename.name + 'Response')
- SOAPMethodResponse.new(response_name, @param_def)
+ def create_method_response
+ SOAPMethodResponse.new(
+ XSD::QName.new(@elename.namespace, @elename.name + 'Response'),
+ @param_def)
end
private
@@ -266,7 +211,7 @@ private
def check_elename(qname)
# NCName & ruby's method name
unless /\A[\w_][\w\d_\-]*\z/ =~ qname.name
- raise MethodDefinitionError.new("element name '#{qname.name}' not allowed")
+ raise MethodDefinitionError.new("Element name '#{qname.name}' not allowed")
end
end
end
@@ -291,11 +236,11 @@ class SOAPMethodResponse < SOAPMethod
yield(@retval_name, @retval)
end
- output_params.each do |name|
- unless @outparam[name]
- raise ParameterError.new("parameter: #{name} was not given")
+ each_param_name(OUT, INOUT) do |param_name|
+ unless @outparam[param_name]
+ raise ParameterError.new("Parameter: #{ param_name } was not given.")
end
- yield(name, @outparam[name])
+ yield(param_name, @outparam[param_name])
end
end
end
diff --git a/lib/soap/rpc/httpserver.rb b/lib/soap/rpc/httpserver.rb
index 6d2a72ebe3..7b1f961d9e 100644
--- a/lib/soap/rpc/httpserver.rb
+++ b/lib/soap/rpc/httpserver.rb
@@ -24,102 +24,78 @@ class HTTPServer < Logger::Application
super(config[:SOAPHTTPServerApplicationName] || self.class.name)
@default_namespace = config[:SOAPDefaultNamespace]
@webrick_config = config.dup
- self.level = Logger::Severity::ERROR # keep silent by default
@webrick_config[:Logger] ||= @log
- @log = @webrick_config[:Logger] # sync logger of App and HTTPServer
- @router = ::SOAP::RPC::Router.new(self.class.name)
- @soaplet = ::SOAP::RPC::SOAPlet.new(@router)
+ @server = nil
+ @soaplet = ::SOAP::RPC::SOAPlet.new
+ self.level = Logger::Severity::INFO
on_init
- @server = WEBrick::HTTPServer.new(@webrick_config)
- @server.mount('/', @soaplet)
end
def on_init
- # do extra initialization in a derived class if needed.
+ # define extra methods in derived class.
end
def status
- @server.status if @server
+ if @server
+ @server.status
+ else
+ nil
+ end
end
def shutdown
@server.shutdown if @server
end
-
+
def mapping_registry
- @router.mapping_registry
+ @soaplet.app_scope_router.mapping_registry
end
def mapping_registry=(mapping_registry)
- @router.mapping_registry = mapping_registry
- end
-
- def generate_explicit_type
- @router.generate_explicit_type
+ @soaplet.app_scope_router.mapping_registry = mapping_registry
end
- def generate_explicit_type=(generate_explicit_type)
- @router.generate_explicit_type = generate_explicit_type
- end
-
- # servant entry interface
-
- def add_rpc_request_servant(factory, namespace = @default_namespace)
- @router.add_rpc_request_servant(factory, namespace)
+ def add_rpc_request_servant(factory, namespace = @default_namespace,
+ mapping_registry = nil)
+ @soaplet.add_rpc_request_servant(factory, namespace, mapping_registry)
end
def add_rpc_servant(obj, namespace = @default_namespace)
- @router.add_rpc_servant(obj, namespace)
+ @soaplet.add_rpc_servant(obj, namespace)
end
- def add_request_headerhandler(factory)
- @router.add_request_headerhandler(factory)
+ def add_rpc_request_headerhandler(factory)
+ @soaplet.add_rpc_request_headerhandler(factory)
end
- def add_headerhandler(obj)
- @router.add_headerhandler(obj)
+ def add_rpc_headerhandler(obj)
+ @soaplet.add_rpc_headerhandler(obj)
end
- alias add_rpc_headerhandler add_headerhandler
- # method entry interface
-
- def add_rpc_method(obj, name, *param)
- add_rpc_method_as(obj, name, name, *param)
+ def add_method(obj, name, *param)
+ add_method_as(obj, name, name, *param)
end
- alias add_method add_rpc_method
- def add_rpc_method_as(obj, name, name_as, *param)
+ def add_method_as(obj, name, name_as, *param)
qname = XSD::QName.new(@default_namespace, name_as)
soapaction = nil
- param_def = SOAPMethod.derive_rpc_param_def(obj, name, *param)
- @router.add_rpc_operation(obj, qname, soapaction, name, param_def)
- end
- alias add_method_as add_rpc_method_as
-
- def add_document_method(obj, soapaction, name, req_qnames, res_qnames)
- param_def = SOAPMethod.create_doc_param_def(req_qnames, res_qnames)
- @router.add_document_operation(obj, soapaction, name, param_def)
- end
-
- def add_rpc_operation(receiver, qname, soapaction, name, param_def, opt = {})
- @router.add_rpc_operation(receiver, qname, soapaction, name, param_def, opt)
- end
-
- def add_rpc_request_operation(factory, qname, soapaction, name, param_def, opt = {})
- @router.add_rpc_request_operation(factory, qname, soapaction, name, param_def, opt)
- end
-
- def add_document_operation(receiver, soapaction, name, param_def, opt = {})
- @router.add_document_operation(receiver, soapaction, name, param_def, opt)
- end
-
- def add_document_request_operation(factory, soapaction, name, param_def, opt = {})
- @router.add_document_request_operation(factory, soapaction, name, param_def, opt)
+ method = obj.method(name)
+ param_def = if param.size == 1 and param[0].is_a?(Array)
+ param[0]
+ elsif param.empty?
+ ::SOAP::RPC::SOAPMethod.create_param_def(
+ (1..method.arity.abs).collect { |i| "p#{ i }" })
+ else
+ SOAP::RPC::SOAPMethod.create_param_def(param)
+ end
+ @soaplet.app_scope_router.add_method(obj, qname, soapaction, name, param_def)
end
private
def run
+ @server = WEBrick::HTTPServer.new(@webrick_config)
+ @server.mount('/', @soaplet)
@server.start
end
end
diff --git a/lib/soap/rpc/proxy.rb b/lib/soap/rpc/proxy.rb
index 7dfda62006..355bf2e81a 100644
--- a/lib/soap/rpc/proxy.rb
+++ b/lib/soap/rpc/proxy.rb
@@ -1,5 +1,5 @@
# SOAP4R - RPC Proxy library.
-# Copyright (C) 2000, 2003-2005 NAKAMURA, Hiroshi <nahi@ruby-lang.org>.
+# Copyright (C) 2000, 2003, 2004 NAKAMURA, Hiroshi <nahi@ruby-lang.org>.
# This program is copyrighted free software by NAKAMURA, Hiroshi. You can
# redistribute it and/or modify it under the same terms of Ruby's license;
@@ -28,136 +28,74 @@ public
attr_accessor :mandatorycharset
attr_accessor :allow_unqualified_element
attr_accessor :default_encodingstyle
- attr_accessor :generate_explicit_type
- attr_reader :headerhandler
- attr_reader :streamhandler
+ attr_reader :method
- attr_accessor :mapping_registry
- attr_accessor :literal_mapping_registry
-
- attr_reader :operation
-
- def initialize(endpoint_url, soapaction, options)
- @endpoint_url = endpoint_url
+ def initialize(streamhandler, soapaction = nil)
+ @streamhandler = streamhandler
@soapaction = soapaction
- @options = options
- @streamhandler = HTTPStreamHandler.new(
- @options["protocol.http"] ||= ::SOAP::Property.new)
- @operation = {}
+ @method = {}
@mandatorycharset = nil
- @allow_unqualified_element = true
+ @allow_unqualified_element = false
@default_encodingstyle = nil
- @generate_explicit_type = true
- @headerhandler = Header::HandlerSet.new
- @mapping_registry = nil
- @literal_mapping_registry = ::SOAP::Mapping::WSDLLiteralRegistry.new
- end
-
- def inspect
- "#<#{self.class}:#{@endpoint_url}>"
end
- def endpoint_url
- @endpoint_url
- end
+ class Request
+ include RPC
- def endpoint_url=(endpoint_url)
- @endpoint_url = endpoint_url
- reset_stream
- end
+ public
- def reset_stream
- @streamhandler.reset(@endpoint_url)
- end
+ attr_reader :method
+ attr_reader :namespace
+ attr_reader :name
- def set_wiredump_file_base(wiredump_file_base)
- @streamhandler.wiredump_file_base = wiredump_file_base
- end
+ def initialize(model, values)
+ @method = model.dup
+ @namespace = @method.elename.namespace
+ @name = @method.elename.name
- def test_loopback_response
- @streamhandler.test_loopback_response
- end
-
- def add_rpc_operation(qname, soapaction, name, param_def, opt = {})
- opt[:request_qname] = qname
- opt[:request_style] ||= :rpc
- opt[:response_style] ||= :rpc
- opt[:request_use] ||= :encoded
- opt[:response_use] ||= :encoded
- @operation[name] = Operation.new(soapaction, param_def, opt)
- end
-
- def add_document_operation(soapaction, name, param_def, opt = {})
- opt[:request_style] ||= :document
- opt[:response_style] ||= :document
- opt[:request_use] ||= :literal
- opt[:response_use] ||= :literal
- # default values of these values are unqualified in XML Schema.
- # set true for backward compatibility.
- unless opt.key?(:elementformdefault)
- opt[:elementformdefault] = true
- end
- unless opt.key?(:attributeformdefault)
- opt[:attributeformdefault] = true
+ params = {}
+
+ if ((values.size == 1) and (values[0].is_a?(Hash)))
+ params = values[0]
+ else
+ i = 0
+ @method.each_param_name(SOAPMethod::IN, SOAPMethod::INOUT) do |name|
+ params[name] = values[i] || SOAPNil.new
+ i += 1
+ end
+ end
+ @method.set_param(params)
end
- @operation[name] = Operation.new(soapaction, param_def, opt)
end
- # add_method is for shortcut of typical rpc/encoded method definition.
- alias add_method add_rpc_operation
- alias add_rpc_method add_rpc_operation
- alias add_document_method add_document_operation
-
- def invoke(req_header, req_body, opt = nil)
- opt ||= create_encoding_opt
- route(req_header, req_body, opt, opt)
+ def add_method(qname, soapaction, name, param_def)
+ @method[name] = SOAPMethodRequest.new(qname, param_def, soapaction)
end
- def call(name, *params)
- unless op_info = @operation[name]
- raise MethodDefinitionError, "method: #{name} not defined"
- end
- mapping_opt = create_mapping_opt
- req_header = create_request_header
- req_body = SOAPBody.new(
- op_info.request_body(params, @mapping_registry,
- @literal_mapping_registry, mapping_opt)
- )
- reqopt = create_encoding_opt(
- :soapaction => op_info.soapaction || @soapaction,
- :envelopenamespace => @options["soap.envelope.requestnamespace"],
- :default_encodingstyle =>
- @default_encodingstyle || op_info.request_default_encodingstyle,
- :elementformdefault => op_info.elementformdefault,
- :attributeformdefault => op_info.attributeformdefault
- )
- resopt = create_encoding_opt(
- :envelopenamespace => @options["soap.envelope.responsenamespace"],
- :default_encodingstyle =>
- @default_encodingstyle || op_info.response_default_encodingstyle,
- :elementformdefault => op_info.elementformdefault,
- :attributeformdefault => op_info.attributeformdefault
- )
- env = route(req_header, req_body, reqopt, resopt)
- raise EmptyResponseError unless env
- receive_headers(env.header)
- begin
- check_fault(env.body)
- rescue ::SOAP::FaultError => e
- op_info.raise_fault(e, @mapping_registry, @literal_mapping_registry)
+ def create_request(name, *values)
+ if (@method.key?(name))
+ method = @method[name]
+ method.encodingstyle = @default_encodingstyle if @default_encodingstyle
+ else
+ raise SOAP::RPC::MethodDefinitionError.new(
+ "Method: #{ name } not defined.")
end
- op_info.response_obj(env.body, @mapping_registry,
- @literal_mapping_registry, mapping_opt)
+ Request.new(method, values)
end
- def route(req_header, req_body, reqopt, resopt)
- req_env = ::SOAP::SOAPEnvelope.new(req_header, req_body)
- unless reqopt[:envelopenamespace].nil?
- set_envelopenamespace(req_env, reqopt[:envelopenamespace])
+ def invoke(req_header, req_body, soapaction = nil)
+ if req_header and !req_header.is_a?(SOAPHeader)
+ req_header = create_header(req_header)
+ end
+ if !req_body.is_a?(SOAPBody)
+ req_body = SOAPBody.new(req_body)
end
- reqopt[:external_content] = nil
- conn_data = marshal(req_env, reqopt)
- if ext = reqopt[:external_content]
+ opt = create_options
+ opt[:external_content] = nil
+ req_env = SOAPEnvelope.new(req_header, req_body)
+ send_string = Processor.marshal(req_env, opt)
+ conn_data = StreamHandler::ConnectionData.new(send_string)
+ if ext = opt[:external_content]
mime = MIMEMessage.new
ext.each do |k, v|
mime.add_attachment(v.data)
@@ -167,12 +105,16 @@ public
conn_data.send_string = mime.content_str
conn_data.send_contenttype = mime.headers['content-type'].str
end
- conn_data = @streamhandler.send(@endpoint_url, conn_data,
- reqopt[:soapaction])
+ conn_data = @streamhandler.send(conn_data, soapaction)
if conn_data.receive_string.empty?
- return nil
+ return nil, nil
end
- unmarshal(conn_data, resopt)
+ unmarshal(conn_data, opt)
+ end
+
+ def call(req_header, name, *values)
+ req = create_request(name, *values)
+ invoke(req_header, req.method, req.method.soapaction || @soapaction)
end
def check_fault(body)
@@ -183,38 +125,6 @@ public
private
- def set_envelopenamespace(env, namespace)
- env.elename = XSD::QName.new(namespace, env.elename.name)
- if env.header
- env.header.elename = XSD::QName.new(namespace, env.header.elename.name)
- end
- if env.body
- env.body.elename = XSD::QName.new(namespace, env.body.elename.name)
- end
- end
-
- def create_request_header
- headers = @headerhandler.on_outbound
- if headers.empty?
- nil
- else
- h = ::SOAP::SOAPHeader.new
- headers.each do |header|
- h.add(header.elename.name, header)
- end
- h
- end
- end
-
- def receive_headers(headers)
- @headerhandler.on_inbound(headers) if headers
- end
-
- def marshal(env, opt)
- send_string = Processor.marshal(env, opt)
- StreamHandler::ConnectionData.new(send_string)
- end
-
def unmarshal(conn_data, opt)
contenttype = conn_data.receive_contenttype
if /#{MIMEMessage::MultipartContentType}/i =~ contenttype
@@ -235,10 +145,6 @@ private
::SOAP::StreamHandler.parse_media_type(contenttype)
env = Processor.unmarshal(conn_data.receive_string, opt)
end
- unless env.is_a?(::SOAP::SOAPEnvelope)
- raise ResponseFormatError.new(
- "response is not a SOAP envelope: #{conn_data.receive_string}")
- end
env
end
@@ -250,245 +156,13 @@ private
header
end
- def create_encoding_opt(hash = nil)
+ def create_options
opt = {}
opt[:default_encodingstyle] = @default_encodingstyle
- opt[:allow_unqualified_element] = @allow_unqualified_element
- opt[:generate_explicit_type] = @generate_explicit_type
- opt[:no_indent] = @options["soap.envelope.no_indent"]
- opt[:use_numeric_character_reference] =
- @options["soap.envelope.use_numeric_character_reference"]
- opt.update(hash) if hash
- opt
- end
-
- def create_mapping_opt(hash = nil)
- opt = {
- :external_ces => @options["soap.mapping.external_ces"]
- }
- opt.update(hash) if hash
- opt
- end
-
- class Operation
- attr_reader :soapaction
- attr_reader :request_style
- attr_reader :response_style
- attr_reader :request_use
- attr_reader :response_use
- attr_reader :elementformdefault
- attr_reader :attributeformdefault
-
- def initialize(soapaction, param_def, opt)
- @soapaction = soapaction
- @request_style = opt[:request_style]
- @response_style = opt[:response_style]
- @request_use = opt[:request_use]
- @response_use = opt[:response_use]
- # set nil(unqualified) by default
- @elementformdefault = opt[:elementformdefault]
- @attributeformdefault = opt[:attributeformdefault]
- check_style(@request_style)
- check_style(@response_style)
- check_use(@request_use)
- check_use(@response_use)
- if @request_style == :rpc
- @rpc_request_qname = opt[:request_qname]
- if @rpc_request_qname.nil?
- raise MethodDefinitionError.new("rpc_request_qname must be given")
- end
- @rpc_method_factory =
- RPC::SOAPMethodRequest.new(@rpc_request_qname, param_def, @soapaction)
- else
- @doc_request_qnames = []
- @doc_request_qualified = []
- @doc_response_qnames = []
- @doc_response_qualified = []
- param_def.each do |inout, paramname, typeinfo, eleinfo|
- klass_not_used, nsdef, namedef = typeinfo
- qualified = eleinfo
- if namedef.nil?
- raise MethodDefinitionError.new("qname must be given")
- end
- case inout
- when SOAPMethod::IN
- @doc_request_qnames << XSD::QName.new(nsdef, namedef)
- @doc_request_qualified << qualified
- when SOAPMethod::OUT
- @doc_response_qnames << XSD::QName.new(nsdef, namedef)
- @doc_response_qualified << qualified
- else
- raise MethodDefinitionError.new(
- "illegal inout definition for document style: #{inout}")
- end
- end
- end
- end
-
- def request_default_encodingstyle
- (@request_use == :encoded) ? EncodingNamespace : LiteralNamespace
- end
-
- def response_default_encodingstyle
- (@response_use == :encoded) ? EncodingNamespace : LiteralNamespace
- end
-
- def request_body(values, mapping_registry, literal_mapping_registry, opt)
- if @request_style == :rpc
- request_rpc(values, mapping_registry, literal_mapping_registry, opt)
- else
- request_doc(values, mapping_registry, literal_mapping_registry, opt)
- end
- end
-
- def response_obj(body, mapping_registry, literal_mapping_registry, opt)
- if @response_style == :rpc
- response_rpc(body, mapping_registry, literal_mapping_registry, opt)
- else
- response_doc(body, mapping_registry, literal_mapping_registry, opt)
- end
- end
-
- def raise_fault(e, mapping_registry, literal_mapping_registry)
- if @response_style == :rpc
- Mapping.fault2exception(e, mapping_registry)
- else
- Mapping.fault2exception(e, literal_mapping_registry)
- end
- end
-
- private
-
- def check_style(style)
- unless [:rpc, :document].include?(style)
- raise MethodDefinitionError.new("unknown style: #{style}")
- end
- end
-
- def check_use(use)
- unless [:encoded, :literal].include?(use)
- raise MethodDefinitionError.new("unknown use: #{use}")
- end
- end
-
- def request_rpc(values, mapping_registry, literal_mapping_registry, opt)
- if @request_use == :encoded
- request_rpc_enc(values, mapping_registry, opt)
- else
- request_rpc_lit(values, literal_mapping_registry, opt)
- end
- end
-
- def request_doc(values, mapping_registry, literal_mapping_registry, opt)
- if @request_use == :encoded
- request_doc_enc(values, mapping_registry, opt)
- else
- request_doc_lit(values, literal_mapping_registry, opt)
- end
- end
-
- def request_rpc_enc(values, mapping_registry, opt)
- method = @rpc_method_factory.dup
- names = method.input_params
- obj = create_request_obj(names, values)
- soap = Mapping.obj2soap(obj, mapping_registry, @rpc_request_qname, opt)
- method.set_param(soap)
- method
- end
-
- def request_rpc_lit(values, mapping_registry, opt)
- method = @rpc_method_factory.dup
- params = {}
- idx = 0
- method.input_params.each do |name|
- params[name] = Mapping.obj2soap(values[idx], mapping_registry,
- XSD::QName.new(nil, name), opt)
- idx += 1
- end
- method.set_param(params)
- method
- end
-
- def request_doc_enc(values, mapping_registry, opt)
- (0...values.size).collect { |idx|
- ele = Mapping.obj2soap(values[idx], mapping_registry, nil, opt)
- ele.elename = @doc_request_qnames[idx]
- ele
- }
- end
-
- def request_doc_lit(values, mapping_registry, opt)
- (0...values.size).collect { |idx|
- ele = Mapping.obj2soap(values[idx], mapping_registry,
- @doc_request_qnames[idx], opt)
- ele.encodingstyle = LiteralNamespace
- if ele.respond_to?(:qualified)
- ele.qualified = @doc_request_qualified[idx]
- end
- ele
- }
- end
-
- def response_rpc(body, mapping_registry, literal_mapping_registry, opt)
- if @response_use == :encoded
- response_rpc_enc(body, mapping_registry, opt)
- else
- response_rpc_lit(body, literal_mapping_registry, opt)
- end
- end
-
- def response_doc(body, mapping_registry, literal_mapping_registry, opt)
- if @response_use == :encoded
- return *response_doc_enc(body, mapping_registry, opt)
- else
- return *response_doc_lit(body, literal_mapping_registry, opt)
- end
- end
-
- def response_rpc_enc(body, mapping_registry, opt)
- ret = nil
- if body.response
- ret = Mapping.soap2obj(body.response, mapping_registry,
- @rpc_method_factory.retval_class_name, opt)
- end
- if body.outparams
- outparams = body.outparams.collect { |outparam|
- Mapping.soap2obj(outparam, mapping_registry, nil, opt)
- }
- [ret].concat(outparams)
- else
- ret
- end
- end
-
- def response_rpc_lit(body, mapping_registry, opt)
- body.root_node.collect { |key, value|
- Mapping.soap2obj(value, mapping_registry,
- @rpc_method_factory.retval_class_name, opt)
- }
- end
-
- def response_doc_enc(body, mapping_registry, opt)
- body.collect { |key, value|
- Mapping.soap2obj(value, mapping_registry, nil, opt)
- }
- end
-
- def response_doc_lit(body, mapping_registry, opt)
- body.collect { |key, value|
- Mapping.soap2obj(value, mapping_registry)
- }
- end
-
- def create_request_obj(names, params)
- o = Object.new
- idx = 0
- while idx < params.length
- o.instance_variable_set('@' + names[idx], params[idx])
- idx += 1
- end
- o
+ if @allow_unqualified_element
+ opt[:allow_unqualified_element] = true
end
+ opt
end
end
diff --git a/lib/soap/rpc/router.rb b/lib/soap/rpc/router.rb
index 71c6eb625b..9d8d1c8da6 100644
--- a/lib/soap/rpc/router.rb
+++ b/lib/soap/rpc/router.rb
@@ -1,5 +1,5 @@
# SOAP4R - RPC Routing library
-# Copyright (C) 2001, 2002, 2004, 2005 NAKAMURA, Hiroshi <nahi@ruby-lang.org>.
+# Copyright (C) 2001, 2002 NAKAMURA, Hiroshi <nahi@ruby-lang.org>.
# This program is copyrighted free software by NAKAMURA, Hiroshi. You can
# redistribute it and/or modify it under the same terms of Ruby's license;
@@ -9,7 +9,6 @@
require 'soap/soap'
require 'soap/processor'
require 'soap/mapping'
-require 'soap/mapping/wsdlliteralregistry'
require 'soap/rpc/rpc'
require 'soap/rpc/element'
require 'soap/streamHandler'
@@ -25,255 +24,117 @@ class Router
include SOAP
attr_reader :actor
+ attr_accessor :allow_unqualified_element
+ attr_accessor :default_encodingstyle
attr_accessor :mapping_registry
- attr_accessor :literal_mapping_registry
- attr_accessor :generate_explicit_type
- attr_accessor :external_ces
+ attr_reader :headerhandler
def initialize(actor)
@actor = actor
+ @receiver = {}
+ @method_name = {}
+ @method = {}
+ @allow_unqualified_element = false
+ @default_encodingstyle = nil
@mapping_registry = nil
@headerhandler = Header::HandlerSet.new
- @literal_mapping_registry = ::SOAP::Mapping::WSDLLiteralRegistry.new
- @generate_explicit_type = true
- @external_ces = nil
- @operation_by_soapaction = {}
- @operation_by_qname = {}
- @headerhandlerfactory = []
end
- ###
- ## header handler interface
- #
- def add_request_headerhandler(factory)
- unless factory.respond_to?(:create)
- raise TypeError.new("factory must respond to 'create'")
- end
- @headerhandlerfactory << factory
- end
-
- def add_headerhandler(handler)
- @headerhandler.add(handler)
- end
-
- ###
- ## servant definition interface
- #
- def add_rpc_request_servant(factory, namespace)
- unless factory.respond_to?(:create)
- raise TypeError.new("factory must respond to 'create'")
- end
- obj = factory.create # a dummy instance for introspection
- ::SOAP::RPC.defined_methods(obj).each do |name|
- begin
- qname = XSD::QName.new(namespace, name)
- param_def = ::SOAP::RPC::SOAPMethod.derive_rpc_param_def(obj, name)
- opt = create_styleuse_option(:rpc, :encoded)
- add_rpc_request_operation(factory, qname, nil, name, param_def, opt)
- rescue SOAP::RPC::MethodDefinitionError => e
- p e if $DEBUG
- end
- end
- end
-
- def add_rpc_servant(obj, namespace)
- ::SOAP::RPC.defined_methods(obj).each do |name|
- begin
- qname = XSD::QName.new(namespace, name)
- param_def = ::SOAP::RPC::SOAPMethod.derive_rpc_param_def(obj, name)
- opt = create_styleuse_option(:rpc, :encoded)
- add_rpc_operation(obj, qname, nil, name, param_def, opt)
- rescue SOAP::RPC::MethodDefinitionError => e
- p e if $DEBUG
- end
- end
- end
- alias add_servant add_rpc_servant
-
- ###
- ## operation definition interface
- #
- def add_rpc_operation(receiver, qname, soapaction, name, param_def, opt = {})
- ensure_styleuse_option(opt, :rpc, :encoded)
- opt[:request_qname] = qname
- op = ApplicationScopeOperation.new(soapaction, receiver, name, param_def,
- opt)
- if opt[:request_style] != :rpc
- raise RPCRoutingError.new("illegal request_style given")
- end
- assign_operation(soapaction, qname, op)
- end
- alias add_method add_rpc_operation
- alias add_rpc_method add_rpc_operation
-
- def add_rpc_request_operation(factory, qname, soapaction, name, param_def, opt = {})
- ensure_styleuse_option(opt, :rpc, :encoded)
- opt[:request_qname] = qname
- op = RequestScopeOperation.new(soapaction, factory, name, param_def, opt)
- if opt[:request_style] != :rpc
- raise RPCRoutingError.new("illegal request_style given")
- end
- assign_operation(soapaction, qname, op)
- end
-
- def add_document_operation(receiver, soapaction, name, param_def, opt = {})
- #
- # adopt workaround for doc/lit wrapper method
- # (you should consider to simply use rpc/lit service)
- #
- #unless soapaction
- # raise RPCRoutingError.new("soapaction is a must for document method")
- #end
- ensure_styleuse_option(opt, :document, :literal)
- op = ApplicationScopeOperation.new(soapaction, receiver, name, param_def,
- opt)
- if opt[:request_style] != :document
- raise RPCRoutingError.new("illegal request_style given")
- end
- assign_operation(soapaction, first_input_part_qname(param_def), op)
- end
- alias add_document_method add_document_operation
-
- def add_document_request_operation(factory, soapaction, name, param_def, opt = {})
- #
- # adopt workaround for doc/lit wrapper method
- # (you should consider to simply use rpc/lit service)
- #
- #unless soapaction
- # raise RPCRoutingError.new("soapaction is a must for document method")
- #end
- ensure_styleuse_option(opt, :document, :literal)
- op = RequestScopeOperation.new(soapaction, receiver, name, param_def, opt)
- if opt[:request_style] != :document
- raise RPCRoutingError.new("illegal request_style given")
- end
- assign_operation(soapaction, first_input_part_qname(param_def), op)
+ def add_method(receiver, qname, soapaction, name, param_def)
+ fqname = fqname(qname)
+ @receiver[fqname] = receiver
+ @method_name[fqname] = name
+ @method[fqname] = RPC::SOAPMethodRequest.new(qname, param_def, soapaction)
end
def route(conn_data)
- # we cannot set request_default_encodingsyle before parsing the content.
- env = unmarshal(conn_data)
- if env.nil?
- raise ArgumentError.new("illegal SOAP marshal format")
- end
- op = lookup_operation(conn_data.soapaction, env.body)
- headerhandler = @headerhandler.dup
- @headerhandlerfactory.each do |f|
- headerhandler.add(f.create)
- end
- receive_headers(headerhandler, env.header)
- soap_response = default_encodingstyle = nil
+ soap_response = nil
begin
- soap_response =
- op.call(env.body, @mapping_registry, @literal_mapping_registry,
- create_mapping_opt)
- default_encodingstyle = op.response_default_encodingstyle
+ env = unmarshal(conn_data)
+ if env.nil?
+ raise ArgumentError.new("Illegal SOAP marshal format.")
+ end
+ receive_headers(env.header)
+ soap_request = env.body.request
+ unless soap_request.is_a?(SOAPStruct)
+ raise RPCRoutingError.new("Not an RPC style.")
+ end
+ soap_response = dispatch(soap_request)
rescue Exception
soap_response = fault($!)
- default_encodingstyle = nil
+ conn_data.is_fault = true
end
- conn_data.is_fault = true if soap_response.is_a?(SOAPFault)
- header = call_headers(headerhandler)
+
+ opt = options
+ opt[:external_content] = nil
+ header = call_headers
body = SOAPBody.new(soap_response)
env = SOAPEnvelope.new(header, body)
- marshal(conn_data, env, default_encodingstyle)
+ response_string = Processor.marshal(env, opt)
+ conn_data.send_string = response_string
+ if ext = opt[:external_content]
+ mime = MIMEMessage.new
+ ext.each do |k, v|
+ mime.add_attachment(v.data)
+ end
+ mime.add_part(conn_data.send_string + "\r\n")
+ mime.close
+ conn_data.send_string = mime.content_str
+ conn_data.send_contenttype = mime.headers['content-type'].str
+ end
+ conn_data
end
# Create fault response string.
- def create_fault_response(e)
- env = SOAPEnvelope.new(SOAPHeader.new, SOAPBody.new(fault(e)))
- opt = {}
+ def create_fault_response(e, charset = nil)
+ header = SOAPHeader.new
+ body = SOAPBody.new(fault(e))
+ env = SOAPEnvelope.new(header, body)
+ opt = options
opt[:external_content] = nil
+ opt[:charset] = charset
response_string = Processor.marshal(env, opt)
conn_data = StreamHandler::ConnectionData.new(response_string)
conn_data.is_fault = true
if ext = opt[:external_content]
- mimeize(conn_data, ext)
+ mime = MIMEMessage.new
+ ext.each do |k, v|
+ mime.add_attachment(v.data)
+ end
+ mime.add_part(conn_data.send_string + "\r\n")
+ mime.close
+ conn_data.send_string = mime.content_str
+ conn_data.send_contenttype = mime.headers['content-type'].str
end
conn_data
end
private
- def first_input_part_qname(param_def)
- param_def.each do |inout, paramname, typeinfo|
- if inout == SOAPMethod::IN
- klass, nsdef, namedef = typeinfo
- return XSD::QName.new(nsdef, namedef)
- end
- end
- nil
- end
-
- def create_styleuse_option(style, use)
- opt = {}
- opt[:request_style] = opt[:response_style] = style
- opt[:request_use] = opt[:response_use] = use
- opt
- end
-
- def ensure_styleuse_option(opt, style, use)
- opt[:request_style] ||= style
- opt[:response_style] ||= style
- opt[:request_use] ||= use
- opt[:response_use] ||= use
- end
-
- def assign_operation(soapaction, qname, op)
- assigned = false
- if soapaction and !soapaction.empty?
- @operation_by_soapaction[soapaction] = op
- assigned = true
- end
- if qname
- @operation_by_qname[qname] = op
- assigned = true
- end
- unless assigned
- raise RPCRoutingError.new("cannot assign operation")
- end
- end
-
- def lookup_operation(soapaction, body)
- if op = @operation_by_soapaction[soapaction]
- return op
- end
- qname = body.root_node.elename
- if op = @operation_by_qname[qname]
- return op
- end
- if soapaction
- raise RPCRoutingError.new(
- "operation: #{soapaction} #{qname} not supported")
- else
- raise RPCRoutingError.new("operation: #{qname} not supported")
- end
- end
-
- def call_headers(headerhandler)
- headers = headerhandler.on_outbound
+ def call_headers
+ headers = @headerhandler.on_outbound
if headers.empty?
nil
else
h = ::SOAP::SOAPHeader.new
headers.each do |header|
- h.add(header.elename.name, header)
- end
- h
+ h.add(header.elename.name, header)
+ end
+ h
end
end
- def receive_headers(headerhandler, headers)
- headerhandler.on_inbound(headers) if headers
+ def receive_headers(headers)
+ @headerhandler.on_inbound(headers) if headers
end
def unmarshal(conn_data)
- opt = {}
+ opt = options
contenttype = conn_data.receive_contenttype
if /#{MIMEMessage::MultipartContentType}/i =~ contenttype
opt[:external_content] = {}
mime = MIMEMessage.parse("Content-Type: " + contenttype,
- conn_data.receive_string)
+ conn_data.receive_string)
mime.parts.each do |part|
value = Attachment.new(part.content)
value.contentid = part.contentid
@@ -292,29 +153,32 @@ private
env
end
- def marshal(conn_data, env, default_encodingstyle = nil)
- opt = {}
- opt[:external_content] = nil
- opt[:default_encodingstyle] = default_encodingstyle
- opt[:generate_explicit_type] = @generate_explicit_type
- response_string = Processor.marshal(env, opt)
- conn_data.send_string = response_string
- if ext = opt[:external_content]
- mimeize(conn_data, ext)
+ # Create new response.
+ def create_response(qname, result)
+ name = fqname(qname)
+ if (@method.key?(name))
+ method = @method[name]
+ else
+ raise RPCRoutingError.new("Method: #{ name } not defined.")
end
- conn_data
- end
- def mimeize(conn_data, ext)
- mime = MIMEMessage.new
- ext.each do |k, v|
- mime.add_attachment(v.data)
+ soap_response = method.create_method_response
+ if soap_response.have_outparam?
+ unless result.is_a?(Array)
+ raise RPCRoutingError.new("Out parameter was not returned.")
+ end
+ outparams = {}
+ i = 1
+ soap_response.each_param_name('out', 'inout') do |outparam|
+ outparams[outparam] = Mapping.obj2soap(result[i], @mapping_registry)
+ i += 1
+ end
+ soap_response.set_outparam(outparams)
+ soap_response.retval = Mapping.obj2soap(result[0], @mapping_registry)
+ else
+ soap_response.retval = Mapping.obj2soap(result, @mapping_registry)
end
- mime.add_part(conn_data.send_string + "\r\n")
- mime.close
- conn_data.send_string = mime.content_str
- conn_data.send_contenttype = mime.headers['content-type'].str
- conn_data
+ soap_response
end
# Create fault response.
@@ -327,265 +191,42 @@ private
Mapping.obj2soap(detail, @mapping_registry))
end
- def create_mapping_opt
- { :external_ces => @external_ces }
- end
-
- class Operation
- attr_reader :name
- attr_reader :soapaction
- attr_reader :request_style
- attr_reader :response_style
- attr_reader :request_use
- attr_reader :response_use
-
- def initialize(soapaction, name, param_def, opt)
- @soapaction = soapaction
- @name = name
- @request_style = opt[:request_style]
- @response_style = opt[:response_style]
- @request_use = opt[:request_use]
- @response_use = opt[:response_use]
- check_style(@request_style)
- check_style(@response_style)
- check_use(@request_use)
- check_use(@response_use)
- if @response_style == :rpc
- request_qname = opt[:request_qname] or raise
- @rpc_method_factory =
- RPC::SOAPMethodRequest.new(request_qname, param_def, @soapaction)
- @rpc_response_qname = opt[:response_qname]
- else
- @doc_request_qnames = []
- @doc_request_qualified = []
- @doc_response_qnames = []
- @doc_response_qualified = []
- param_def.each do |inout, paramname, typeinfo, eleinfo|
- klass, nsdef, namedef = typeinfo
- qualified = eleinfo
- case inout
- when SOAPMethod::IN
- @doc_request_qnames << XSD::QName.new(nsdef, namedef)
- @doc_request_qualified << qualified
- when SOAPMethod::OUT
- @doc_response_qnames << XSD::QName.new(nsdef, namedef)
- @doc_response_qualified << qualified
- else
- raise ArgumentError.new(
- "illegal inout definition for document style: #{inout}")
- end
- end
- end
- end
-
- def request_default_encodingstyle
- (@request_use == :encoded) ? EncodingNamespace : LiteralNamespace
- end
-
- def response_default_encodingstyle
- (@response_use == :encoded) ? EncodingNamespace : LiteralNamespace
- end
-
- def call(body, mapping_registry, literal_mapping_registry, opt)
- if @request_style == :rpc
- values = request_rpc(body, mapping_registry, literal_mapping_registry,
- opt)
- else
- values = request_document(body, mapping_registry,
- literal_mapping_registry, opt)
- end
- result = receiver.method(@name.intern).call(*values)
- return result if result.is_a?(SOAPFault)
- if @response_style == :rpc
- response_rpc(result, mapping_registry, literal_mapping_registry, opt)
- else
- response_doc(result, mapping_registry, literal_mapping_registry, opt)
- end
- end
-
- private
-
- def receiver
- raise NotImplementedError.new('must be defined in derived class')
- end
-
- def request_rpc(body, mapping_registry, literal_mapping_registry, opt)
- request = body.request
- unless request.is_a?(SOAPStruct)
- raise RPCRoutingError.new("not an RPC style")
- end
- if @request_use == :encoded
- request_rpc_enc(request, mapping_registry, opt)
- else
- request_rpc_lit(request, literal_mapping_registry, opt)
- end
- end
-
- def request_document(body, mapping_registry, literal_mapping_registry, opt)
- # ToDo: compare names with @doc_request_qnames
- if @request_use == :encoded
- request_doc_enc(body, mapping_registry, opt)
- else
- request_doc_lit(body, literal_mapping_registry, opt)
- end
- end
-
- def request_rpc_enc(request, mapping_registry, opt)
- param = Mapping.soap2obj(request, mapping_registry, nil, opt)
- request.collect { |key, value|
- param[key]
- }
- end
-
- def request_rpc_lit(request, mapping_registry, opt)
- request.collect { |key, value|
- Mapping.soap2obj(value, mapping_registry, nil, opt)
- }
- end
-
- def request_doc_enc(body, mapping_registry, opt)
- body.collect { |key, value|
- Mapping.soap2obj(value, mapping_registry, nil, opt)
- }
- end
-
- def request_doc_lit(body, mapping_registry, opt)
- body.collect { |key, value|
- Mapping.soap2obj(value, mapping_registry, nil, opt)
- }
- end
-
- def response_rpc(result, mapping_registry, literal_mapping_registry, opt)
- if @response_use == :encoded
- response_rpc_enc(result, mapping_registry, opt)
- else
- response_rpc_lit(result, literal_mapping_registry, opt)
- end
- end
-
- def response_doc(result, mapping_registry, literal_mapping_registry, opt)
- if @doc_response_qnames.size == 1 and !result.is_a?(Array)
- result = [result]
- end
- if result.size != @doc_response_qnames.size
- raise "required #{@doc_response_qnames.size} responses " +
- "but #{result.size} given"
- end
- if @response_use == :encoded
- response_doc_enc(result, mapping_registry, opt)
- else
- response_doc_lit(result, literal_mapping_registry, opt)
- end
- end
-
- def response_rpc_enc(result, mapping_registry, opt)
- soap_response =
- @rpc_method_factory.create_method_response(@rpc_response_qname)
- if soap_response.have_outparam?
- unless result.is_a?(Array)
- raise RPCRoutingError.new("out parameter was not returned")
- end
- outparams = {}
- i = 1
- soap_response.output_params.each do |outparam|
- outparams[outparam] = Mapping.obj2soap(result[i], mapping_registry,
- nil, opt)
- i += 1
- end
- soap_response.set_outparam(outparams)
- soap_response.retval = Mapping.obj2soap(result[0], mapping_registry,
- nil, opt)
- else
- soap_response.retval = Mapping.obj2soap(result, mapping_registry, nil,
- opt)
- end
- soap_response
- end
-
- def response_rpc_lit(result, mapping_registry, opt)
- soap_response =
- @rpc_method_factory.create_method_response(@rpc_response_qname)
- if soap_response.have_outparam?
- unless result.is_a?(Array)
- raise RPCRoutingError.new("out parameter was not returned")
- end
- outparams = {}
- i = 1
- soap_response.output_params.each do |outparam|
- outparams[outparam] = Mapping.obj2soap(result[i], mapping_registry,
- XSD::QName.new(nil, outparam), opt)
- i += 1
- end
- soap_response.set_outparam(outparams)
- soap_response.retval = Mapping.obj2soap(result[0], mapping_registry,
- XSD::QName.new(nil, soap_response.elename), opt)
- else
- soap_response.retval = Mapping.obj2soap(result, mapping_registry,
- XSD::QName.new(nil, soap_response.elename), opt)
- end
- soap_response
- end
-
- def response_doc_enc(result, mapping_registry, opt)
- (0...result.size).collect { |idx|
- ele = Mapping.obj2soap(result[idx], mapping_registry, nil, opt)
- ele.elename = @doc_response_qnames[idx]
- ele
- }
- end
-
- def response_doc_lit(result, mapping_registry, opt)
- (0...result.size).collect { |idx|
- ele = Mapping.obj2soap(result[idx], mapping_registry,
- @doc_response_qnames[idx])
- ele.encodingstyle = LiteralNamespace
- if ele.respond_to?(:qualified)
- ele.qualified = @doc_response_qualified[idx]
- end
- ele
- }
- end
-
- def check_style(style)
- unless [:rpc, :document].include?(style)
- raise ArgumentError.new("unknown style: #{style}")
- end
+ # Dispatch to defined method.
+ def dispatch(soap_method)
+ request_struct = Mapping.soap2obj(soap_method, @mapping_registry)
+ values = soap_method.collect { |key, value| request_struct[key] }
+ method = lookup(soap_method.elename, values)
+ unless method
+ raise RPCRoutingError.new(
+ "Method: #{ soap_method.elename } not supported.")
end
- def check_use(use)
- unless [:encoded, :literal].include?(use)
- raise ArgumentError.new("unknown use: #{use}")
- end
- end
+ result = method.call(*values)
+ create_response(soap_method.elename, result)
end
- class ApplicationScopeOperation < Operation
- def initialize(soapaction, receiver, name, param_def, opt)
- super(soapaction, name, param_def, opt)
- @receiver = receiver
- end
-
- private
-
- def receiver
- @receiver
+ # Method lookup
+ def lookup(qname, values)
+ name = fqname(qname)
+ # It may be necessary to check all part of method signature...
+ if @method.member?(name)
+ @receiver[name].method(@method_name[name].intern)
+ else
+ nil
end
end
- class RequestScopeOperation < Operation
- def initialize(soapaction, receiver_factory, name, param_def, opt)
- super(soapaction, name, param_def, opt)
- unless receiver_factory.respond_to?(:create)
- raise TypeError.new("factory must respond to 'create'")
- end
- @receiver_factory = receiver_factory
- end
-
- private
+ def fqname(qname)
+ "#{ qname.namespace }:#{ qname.name }"
+ end
- def receiver
- @receiver_factory.create
+ def options
+ opt = {}
+ opt[:default_encodingstyle] = @default_encodingstyle
+ if @allow_unqualified_element
+ opt[:allow_unqualified_element] = true
end
+ opt
end
end
diff --git a/lib/soap/rpc/rpc.rb b/lib/soap/rpc/rpc.rb
index a48b525dbb..5f77b4d2e9 100644
--- a/lib/soap/rpc/rpc.rb
+++ b/lib/soap/rpc/rpc.rb
@@ -16,7 +16,7 @@ module RPC
if obj.is_a?(Module)
obj.methods - Module.methods
else
- obj.methods - Object.instance_methods(true)
+ obj.methods - Kernel.instance_methods(true)
end
end
end
diff --git a/lib/soap/rpc/soaplet.rb b/lib/soap/rpc/soaplet.rb
index 7cccdd3e31..0c1427acf5 100644
--- a/lib/soap/rpc/soaplet.rb
+++ b/lib/soap/rpc/soaplet.rb
@@ -1,5 +1,5 @@
# SOAP4R - SOAP handler servlet for WEBrick
-# Copyright (C) 2001-2005 NAKAMURA, Hiroshi <nahi@ruby-lang.org>.
+# Copyright (C) 2001, 2002, 2003, 2004 NAKAMURA, Hiroshi <nahi@ruby-lang.org>.
# This program is copyrighted free software by NAKAMURA, Hiroshi. You can
# redistribute it and/or modify it under the same terms of Ruby's license;
@@ -10,29 +10,6 @@ require 'webrick/httpservlet/abstract'
require 'webrick/httpstatus'
require 'soap/rpc/router'
require 'soap/streamHandler'
-begin
- require 'stringio'
- require 'zlib'
-rescue LoadError
- warn("Loading stringio or zlib failed. No gzipped response supported.") if $DEBUG
-end
-
-
-warn("Overriding WEBrick::Log#debug") if $DEBUG
-require 'webrick/log'
-module WEBrick
- class Log < BasicLog
- alias __debug debug
- def debug(msg = nil)
- if block_given? and msg.nil?
- __debug(yield)
- else
- __debug(msg)
- end
- end
- end
-end
-
module SOAP
module RPC
@@ -40,27 +17,54 @@ module RPC
class SOAPlet < WEBrick::HTTPServlet::AbstractServlet
public
- attr_reader :options
+ attr_reader :app_scope_router
+
+ def initialize
+ @router_map = {}
+ @app_scope_router = ::SOAP::RPC::Router.new(self.class.name)
+ @headerhandlerfactory = []
+ @app_scope_headerhandler = nil
+ end
- def initialize(router = nil)
- @router = router || ::SOAP::RPC::Router.new(self.class.name)
- @options = {}
- @config = {}
+ # Add servant factory whose object has request scope. A servant object is
+ # instanciated for each request.
+ #
+ # Bear in mind that servant factories are distinguished by HTTP SOAPAction
+ # header in request. Client which calls request-scoped servant must have a
+ # SOAPAction header which is a namespace of the servant factory.
+ # I mean, use Driver#add_method_with_soapaction instead of Driver#add_method
+ # at client side.
+ #
+ # A factory must respond to :create.
+ #
+ def add_rpc_request_servant(factory, namespace, mapping_registry = nil)
+ unless factory.respond_to?(:create)
+ raise TypeError.new("factory must respond to 'create'")
+ end
+ router = setup_request_router(namespace)
+ router.factory = factory
+ router.mapping_registry = mapping_registry
end
- # for backward compatibility
- def app_scope_router
- @router
+ # Add servant object which has application scope.
+ def add_rpc_servant(obj, namespace)
+ router = @app_scope_router
+ SOAPlet.add_servant_to_router(router, obj, namespace)
+ add_router(namespace, router)
end
+ alias add_servant add_rpc_servant
- # for backward compatibility
- def add_servant(obj, namespace)
- @router.add_rpc_servant(obj, namespace)
+ def add_rpc_request_headerhandler(factory)
+ unless factory.respond_to?(:create)
+ raise TypeError.new("factory must respond to 'create'")
+ end
+ @headerhandlerfactory << factory
end
- def allow_content_encoding_gzip=(allow)
- @options[:allow_content_encoding_gzip] = allow
+ def add_rpc_headerhandler(obj)
+ @app_scope_headerhandler = obj
end
+ alias add_headerhandler add_rpc_headerhandler
###
## Servlet interfaces for WEBrick.
@@ -76,84 +80,118 @@ public
def do_GET(req, res)
res.header['Allow'] = 'POST'
- raise WEBrick::HTTPStatus::MethodNotAllowed, "GET request not allowed"
+ raise WEBrick::HTTPStatus::MethodNotAllowed, "GET request not allowed."
end
def do_POST(req, res)
- logger.debug { "SOAP request: " + req.body } if logger
- begin
- conn_data = ::SOAP::StreamHandler::ConnectionData.new
- setup_req(conn_data, req)
- @router.external_ces = @options[:external_ces]
- conn_data = @router.route(conn_data)
- setup_res(conn_data, req, res)
- rescue Exception => e
- conn_data = @router.create_fault_response(e)
- res.status = WEBrick::HTTPStatus::RC_INTERNAL_SERVER_ERROR
- res.body = conn_data.send_string
- res['content-type'] = conn_data.send_contenttype || "text/xml"
+ namespace = parse_soapaction(req.meta_vars['HTTP_SOAPACTION'])
+ router = lookup_router(namespace)
+ with_headerhandler(router) do |router|
+ begin
+ conn_data = ::SOAP::StreamHandler::ConnectionData.new
+ conn_data.receive_string = req.body
+ conn_data.receive_contenttype = req['content-type']
+ conn_data = router.route(conn_data)
+ if conn_data.is_fault
+ res.status = WEBrick::HTTPStatus::RC_INTERNAL_SERVER_ERROR
+ end
+ res.body = conn_data.send_string
+ res['content-type'] = conn_data.send_contenttype
+ rescue Exception => e
+ conn_data = router.create_fault_response(e)
+ res.status = WEBrick::HTTPStatus::RC_INTERNAL_SERVER_ERROR
+ res.body = conn_data.send_string
+ res['content-type'] = conn_data.send_contenttype || "text/xml"
+ end
end
+
if res.body.is_a?(IO)
res.chunked = true
- logger.debug { "SOAP response: (chunked response not logged)" } if logger
- else
- logger.debug { "SOAP response: " + res.body } if logger
end
end
private
- def logger
- @config[:Logger]
+ class RequestRouter < ::SOAP::RPC::Router
+ attr_accessor :factory
+
+ def initialize(namespace = nil)
+ super(namespace)
+ @namespace = namespace
+ @factory = nil
+ end
+
+ def route(soap_string)
+ obj = @factory.create
+ namespace = self.actor
+ router = ::SOAP::RPC::Router.new(@namespace)
+ SOAPlet.add_servant_to_router(router, obj, namespace)
+ router.route(soap_string)
+ end
end
- def setup_req(conn_data, req)
- conn_data.receive_string = req.body
- conn_data.receive_contenttype = req['content-type']
- conn_data.soapaction = parse_soapaction(req.meta_vars['HTTP_SOAPACTION'])
+ def setup_request_router(namespace)
+ router = @router_map[namespace] || RequestRouter.new(namespace)
+ add_router(namespace, router)
+ router
end
- def setup_res(conn_data, req, res)
- res['content-type'] = conn_data.send_contenttype
- if conn_data.is_fault
- res.status = WEBrick::HTTPStatus::RC_INTERNAL_SERVER_ERROR
+ def add_router(namespace, router)
+ @router_map[namespace] = router
+ end
+
+ def parse_soapaction(soapaction)
+ if /^"(.*)"$/ =~ soapaction
+ soapaction = $1
end
- if outstring = encode_gzip(req, conn_data.send_string)
- res['content-encoding'] = 'gzip'
- res['content-length'] = outstring.size
- res.body = outstring
- else
- res.body = conn_data.send_string
+ if soapaction.empty?
+ return nil
end
+ soapaction
end
- def parse_soapaction(soapaction)
- if !soapaction.nil? and !soapaction.empty?
- if /^"(.+)"$/ =~ soapaction
- return $1
- end
+ def lookup_router(namespace)
+ if namespace
+ @router_map[namespace] || @app_scope_router
+ else
+ @app_scope_router
end
- nil
end
- def encode_gzip(req, outstring)
- unless encode_gzip?(req)
- return nil
+ def with_headerhandler(router)
+ if @app_scope_headerhandler and
+ !router.headerhandler.include?(@app_scope_headerhandler)
+ router.headerhandler.add(@app_scope_headerhandler)
end
+ handlers = @headerhandlerfactory.collect { |f| f.create }
begin
- ostream = StringIO.new
- gz = Zlib::GzipWriter.new(ostream)
- gz.write(outstring)
- ostream.string
+ handlers.each { |h| router.headerhandler.add(h) }
+ yield(router)
ensure
- gz.close
+ handlers.each { |h| router.headerhandler.delete(h) }
end
end
- def encode_gzip?(req)
- @options[:allow_content_encoding_gzip] and defined?(::Zlib) and
- req['accept-encoding'] and
- req['accept-encoding'].split(/,\s*/).include?('gzip')
+ class << self
+ public
+ def add_servant_to_router(router, obj, namespace)
+ ::SOAP::RPC.defined_methods(obj).each do |name|
+ begin
+ add_servant_method_to_router(router, obj, namespace, name)
+ rescue SOAP::RPC::MethodDefinitionError => e
+ p e if $DEBUG
+ end
+ end
+ end
+
+ def add_servant_method_to_router(router, obj, namespace, name)
+ qname = XSD::QName.new(namespace, name)
+ soapaction = nil
+ method = obj.method(name)
+ param_def = ::SOAP::RPC::SOAPMethod.create_param_def(
+ (1..method.arity.abs).collect { |i| "p#{ i }" })
+ router.add_method(obj, qname, soapaction, name, param_def)
+ end
end
end
diff --git a/lib/soap/soap.rb b/lib/soap/soap.rb
index 12e09eccfe..02b26e4246 100644
--- a/lib/soap/soap.rb
+++ b/lib/soap/soap.rb
@@ -13,7 +13,7 @@ require 'xsd/charset'
module SOAP
-VERSION = Version = '1.5.5'
+Version = '1.5.2'
PropertyName = 'soap/property'
EnvelopeNamespace = 'http://schemas.xmlsoap.org/soap/envelope/'
@@ -40,21 +40,21 @@ AttrOffset = 'offset'
AttrPosition = 'position'
ValueArray = 'Array'
-EleEnvelopeName = XSD::QName.new(EnvelopeNamespace, EleEnvelope).freeze
-EleHeaderName = XSD::QName.new(EnvelopeNamespace, EleHeader).freeze
-EleBodyName = XSD::QName.new(EnvelopeNamespace, EleBody).freeze
-EleFaultName = XSD::QName.new(EnvelopeNamespace, EleFault).freeze
-EleFaultStringName = XSD::QName.new(nil, EleFaultString).freeze
-EleFaultActorName = XSD::QName.new(nil, EleFaultActor).freeze
-EleFaultCodeName = XSD::QName.new(nil, EleFaultCode).freeze
-EleFaultDetailName = XSD::QName.new(nil, EleFaultDetail).freeze
-AttrMustUnderstandName = XSD::QName.new(EnvelopeNamespace, AttrMustUnderstand).freeze
-AttrEncodingStyleName = XSD::QName.new(EnvelopeNamespace, AttrEncodingStyle).freeze
-AttrRootName = XSD::QName.new(EncodingNamespace, AttrRoot).freeze
-AttrArrayTypeName = XSD::QName.new(EncodingNamespace, AttrArrayType).freeze
-AttrOffsetName = XSD::QName.new(EncodingNamespace, AttrOffset).freeze
-AttrPositionName = XSD::QName.new(EncodingNamespace, AttrPosition).freeze
-ValueArrayName = XSD::QName.new(EncodingNamespace, ValueArray).freeze
+EleEnvelopeName = XSD::QName.new(EnvelopeNamespace, EleEnvelope)
+EleHeaderName = XSD::QName.new(EnvelopeNamespace, EleHeader)
+EleBodyName = XSD::QName.new(EnvelopeNamespace, EleBody)
+EleFaultName = XSD::QName.new(EnvelopeNamespace, EleFault)
+EleFaultStringName = XSD::QName.new(nil, EleFaultString)
+EleFaultActorName = XSD::QName.new(nil, EleFaultActor)
+EleFaultCodeName = XSD::QName.new(nil, EleFaultCode)
+EleFaultDetailName = XSD::QName.new(nil, EleFaultDetail)
+AttrMustUnderstandName = XSD::QName.new(EnvelopeNamespace, AttrMustUnderstand)
+AttrEncodingStyleName = XSD::QName.new(EnvelopeNamespace, AttrEncodingStyle)
+AttrRootName = XSD::QName.new(EncodingNamespace, AttrRoot)
+AttrArrayTypeName = XSD::QName.new(EncodingNamespace, AttrArrayType)
+AttrOffsetName = XSD::QName.new(EncodingNamespace, AttrOffset)
+AttrPositionName = XSD::QName.new(EncodingNamespace, AttrPosition)
+ValueArrayName = XSD::QName.new(EncodingNamespace, ValueArray)
Base64Literal = 'base64'
@@ -75,8 +75,6 @@ class ArrayIndexOutOfBoundsError < Error; end
class ArrayStoreError < Error; end
class RPCRoutingError < Error; end
-class EmptyResponseError < Error; end
-class ResponseFormatError < Error; end
class UnhandledMustUnderstandHeaderError < Error; end
@@ -103,7 +101,6 @@ class FaultError < Error
end
end
-
module Env
def self.getenv(name)
ENV[name.downcase] || ENV[name.upcase]
@@ -116,25 +113,3 @@ end
end
-
-
-unless Object.respond_to?(:instance_variable_get)
- class Object
- def instance_variable_get(ivarname)
- instance_eval(ivarname)
- end
-
- def instance_variable_set(ivarname, value)
- instance_eval("#{ivarname} = value")
- end
- end
-end
-
-
-unless Kernel.respond_to?(:warn)
- module Kernel
- def warn(msg)
- STDERR.puts(msg + "\n") unless $VERBOSE.nil?
- end
- end
-end
diff --git a/lib/soap/streamHandler.rb b/lib/soap/streamHandler.rb
index 672396ecce..efadf21e07 100644
--- a/lib/soap/streamHandler.rb
+++ b/lib/soap/streamHandler.rb
@@ -7,19 +7,25 @@
require 'soap/soap'
-require 'soap/httpconfigloader'
-begin
- require 'stringio'
- require 'zlib'
-rescue LoadError
- warn("Loading stringio or zlib failed. No gzipped response support.") if $DEBUG
-end
+require 'soap/property'
module SOAP
class StreamHandler
+ Client = begin
+ require 'http-access2'
+ if HTTPAccess2::VERSION < "2.0"
+ raise LoadError.new("http-access/2.0 or later is required.")
+ end
+ HTTPAccess2::Client
+ rescue LoadError
+ STDERR.puts "Loading http-access2 failed. Net/http is used." if $DEBUG
+ require 'soap/netHttpClient'
+ SOAP::NetHttpClient
+ end
+
RUBY_VERSION_STRING = "ruby #{ RUBY_VERSION } (#{ RUBY_RELEASE_DATE }) [#{ RUBY_PLATFORM }]"
class ConnectionData
@@ -28,7 +34,6 @@ class StreamHandler
attr_accessor :receive_string
attr_accessor :receive_contenttype
attr_accessor :is_fault
- attr_accessor :soapaction
def initialize(send_string = nil)
@send_string = send_string
@@ -36,10 +41,15 @@ class StreamHandler
@receive_string = nil
@receive_contenttype = nil
@is_fault = false
- @soapaction = nil
end
end
+ attr_accessor :endpoint_url
+
+ def initialize(endpoint_url)
+ @endpoint_url = endpoint_url
+ end
+
def self.parse_media_type(str)
if /^#{ MediaType }(?:\s*;\s*charset=([^"]+|"[^"]+"))?$/i !~ str
return nil
@@ -55,33 +65,18 @@ class StreamHandler
end
-class HTTPStreamHandler < StreamHandler
+class HTTPPostStreamHandler < StreamHandler
include SOAP
- begin
- require 'http-access2'
- if HTTPAccess2::VERSION < "2.0"
- raise LoadError.new("http-access/2.0 or later is required.")
- end
- Client = HTTPAccess2::Client
- RETRYABLE = true
- rescue LoadError
- warn("Loading http-access2 failed. Net/http is used.") if $DEBUG
- require 'soap/netHttpClient'
- Client = SOAP::NetHttpClient
- RETRYABLE = false
- end
-
-
public
attr_reader :client
attr_accessor :wiredump_file_base
- MAX_RETRY_COUNT = 10 # [times]
+ NofRetry = 10 # [times]
- def initialize(options)
- super()
+ def initialize(endpoint_url, options)
+ super(endpoint_url)
@client = Client.new(nil, "SOAP4R/#{ Version }")
@wiredump_file_base = nil
@charset = @wiredump_dev = nil
@@ -89,40 +84,47 @@ public
set_options
@client.debug_dev = @wiredump_dev
@cookie_store = nil
- @accept_encoding_gzip = false
end
def test_loopback_response
@client.test_loopback_response
end
- def accept_encoding_gzip=(allow)
- @accept_encoding_gzip = allow
- end
-
def inspect
- "#<#{self.class}>"
+ "#<#{self.class}:#{endpoint_url}>"
end
- def send(endpoint_url, conn_data, soapaction = nil, charset = @charset)
- conn_data.soapaction ||= soapaction # for backward conpatibility
- send_post(endpoint_url, conn_data, charset)
+ def send(conn_data, soapaction = nil, charset = @charset)
+ send_post(conn_data, soapaction, charset)
end
- def reset(endpoint_url = nil)
- if endpoint_url.nil?
- @client.reset_all
- else
- @client.reset(endpoint_url)
- end
+ def reset
+ @client.reset(@endpoint_url)
@client.save_cookie_store if @cookie_store
end
private
def set_options
- HTTPConfigLoader.set_options(@client, @options)
- @charset = @options["charset"] || XSD::Charset.xml_encoding_label
+ @client.proxy = @options["proxy"]
+ @options.add_hook("proxy") do |key, value|
+ @client.proxy = value
+ end
+ @client.no_proxy = @options["no_proxy"]
+ @options.add_hook("no_proxy") do |key, value|
+ @client.no_proxy = value
+ end
+ if @client.respond_to?(:protocol_version=)
+ @client.protocol_version = @options["protocol_version"]
+ @options.add_hook("protocol_version") do |key, value|
+ @client.protocol_version = value
+ end
+ end
+ set_cookie_store_file(@options["cookie_store_file"])
+ @options.add_hook("cookie_store_file") do |key, value|
+ set_cookie_store_file(value)
+ end
+ @charset = @options["charset"] || XSD::Charset.charset_label($KCODE)
@options.add_hook("charset") do |key, value|
@charset = value
end
@@ -131,24 +133,87 @@ private
@wiredump_dev = value
@client.debug_dev = @wiredump_dev
end
- set_cookie_store_file(@options["cookie_store_file"])
- @options.add_hook("cookie_store_file") do |key, value|
- set_cookie_store_file(value)
+ ssl_config = @options["ssl_config"] ||= ::SOAP::Property.new
+ set_ssl_config(ssl_config)
+ ssl_config.add_hook(true) do |key, value|
+ set_ssl_config(ssl_config)
+ end
+ basic_auth = @options["basic_auth"] ||= ::SOAP::Property.new
+ set_basic_auth(basic_auth)
+ basic_auth.add_hook do |key, value|
+ set_basic_auth(basic_auth)
end
- ssl_config = @options["ssl_config"]
- basic_auth = @options["basic_auth"]
@options.lock(true)
ssl_config.unlock
basic_auth.unlock
end
+ def set_basic_auth(basic_auth)
+ basic_auth.values.each do |url, userid, passwd|
+ @client.set_basic_auth(url, userid, passwd)
+ end
+ end
+
def set_cookie_store_file(value)
- value = nil if value and value.empty?
@cookie_store = value
@client.set_cookie_store(@cookie_store) if @cookie_store
end
- def send_post(endpoint_url, conn_data, charset)
+ def set_ssl_config(ssl_config)
+ ssl_config.each do |key, value|
+ cfg = @client.ssl_config
+ case key
+ when 'client_cert'
+ cfg.client_cert = cert_from_file(value)
+ when 'client_key'
+ cfg.client_key = key_from_file(value)
+ when 'client_ca'
+ cfg.client_ca = value
+ when 'ca_path'
+ cfg.set_trust_ca(value)
+ when 'ca_file'
+ cfg.set_trust_ca(value)
+ when 'crl'
+ cfg.set_crl(value)
+ when 'verify_mode'
+ cfg.verify_mode = ssl_config_int(value)
+ when 'verify_depth'
+ cfg.verify_depth = ssl_config_int(value)
+ when 'options'
+ cfg.options = value
+ when 'ciphers'
+ cfg.ciphers = value
+ when 'verify_callback'
+ cfg.verify_callback = value
+ when 'cert_store'
+ cfg.cert_store = value
+ else
+ raise ArgumentError.new("unknown ssl_config property #{key}")
+ end
+ end
+ end
+
+ def ssl_config_int(value)
+ if value.nil? or value.empty?
+ nil
+ else
+ begin
+ Integer(value)
+ rescue ArgumentError
+ ::SOAP::Property::Util.const_from_name(value)
+ end
+ end
+ end
+
+ def cert_from_file(filename)
+ OpenSSL::X509::Certificate.new(File.open(filename) { |f| f.read })
+ end
+
+ def key_from_file(filename)
+ OpenSSL::PKey::RSA.new(File.open(filename) { |f| f.read })
+ end
+
+ def send_post(conn_data, soapaction, charset)
conn_data.send_contenttype ||= StreamHandler.create_media_type(charset)
if @wiredump_file_base
@@ -160,37 +225,27 @@ private
extra = {}
extra['Content-Type'] = conn_data.send_contenttype
- extra['SOAPAction'] = "\"#{ conn_data.soapaction }\""
- extra['Accept-Encoding'] = 'gzip' if send_accept_encoding_gzip?
+ extra['SOAPAction'] = "\"#{ soapaction }\""
send_string = conn_data.send_string
+
@wiredump_dev << "Wire dump:\n\n" if @wiredump_dev
begin
- retry_count = 0
- while true
- res = @client.post(endpoint_url, send_string, extra)
- if RETRYABLE and HTTP::Status.redirect?(res.status)
- retry_count += 1
- if retry_count >= MAX_RETRY_COUNT
- raise HTTPStreamError.new("redirect count exceeded")
- end
- endpoint_url = res.header["location"][0]
- puts "redirected to #{endpoint_url}" if $DEBUG
- else
- break
- end
- end
+ res = @client.post(@endpoint_url, send_string, extra)
rescue
- @client.reset(endpoint_url)
+ @client.reset(@endpoint_url)
raise
end
@wiredump_dev << "\n\n" if @wiredump_dev
+
receive_string = res.content
+
if @wiredump_file_base
filename = @wiredump_file_base + '_response.xml'
f = File.open(filename, "w")
f << receive_string
f.close
end
+
case res.status
when 405
raise PostUnavailableError.new("#{ res.status }: #{ res.reason }")
@@ -199,30 +254,13 @@ private
else
raise HTTPStreamError.new("#{ res.status }: #{ res.reason }")
end
- if res.respond_to?(:header) and !res.header['content-encoding'].empty? and
- res.header['content-encoding'][0].downcase == 'gzip'
- receive_string = decode_gzip(receive_string)
- end
+
conn_data.receive_string = receive_string
conn_data.receive_contenttype = res.contenttype
conn_data
end
- def send_accept_encoding_gzip?
- @accept_encoding_gzip and defined?(::Zlib)
- end
-
- def decode_gzip(instring)
- unless send_accept_encoding_gzip?
- raise HTTPStreamError.new("Gzipped response content.")
- end
- begin
- gz = Zlib::GzipReader.new(StringIO.new(instring))
- gz.read
- ensure
- gz.close
- end
- end
+ CRLF = "\r\n"
end
diff --git a/lib/soap/wsdlDriver.rb b/lib/soap/wsdlDriver.rb
index eba9608df5..af868ea886 100644
--- a/lib/soap/wsdlDriver.rb
+++ b/lib/soap/wsdlDriver.rb
@@ -1,5 +1,5 @@
# SOAP4R - SOAP WSDL driver
-# Copyright (C) 2002, 2003, 2005 NAKAMURA, Hiroshi <nahi@ruby-lang.org>.
+# Copyright (C) 2002, 2003 NAKAMURA, Hiroshi <nahi@ruby-lang.org>.
# This program is copyrighted free software by NAKAMURA, Hiroshi. You can
# redistribute it and/or modify it under the same terms of Ruby's license;
@@ -9,11 +9,17 @@
require 'wsdl/parser'
require 'wsdl/importer'
require 'xsd/qname'
-require 'xsd/codegen/gensupport'
-require 'soap/mapping/wsdlencodedregistry'
-require 'soap/mapping/wsdlliteralregistry'
-require 'soap/rpc/driver'
-require 'wsdl/soap/methodDefCreator'
+require 'soap/element'
+require 'soap/baseData'
+require 'soap/streamHandler'
+require 'soap/mimemessage'
+require 'soap/mapping'
+require 'soap/mapping/wsdlRegistry'
+require 'soap/rpc/rpc'
+require 'soap/rpc/element'
+require 'soap/processor'
+require 'soap/header/handlerset'
+require 'logger'
module SOAP
@@ -24,184 +30,77 @@ class WSDLDriverFactory
attr_reader :wsdl
- def initialize(wsdl)
+ def initialize(wsdl, logdev = nil)
+ @logdev = logdev
@wsdl = import(wsdl)
- @methoddefcreator = WSDL::SOAP::MethodDefCreator.new(@wsdl)
end
def inspect
"#<#{self.class}:#{@wsdl.name}>"
end
- def create_rpc_driver(servicename = nil, portname = nil)
- port = find_port(servicename, portname)
- drv = SOAP::RPC::Driver.new(port.soap_address.location)
- init_driver(drv, port)
- add_operation(drv, port)
- drv
- end
-
- # depricated old interface
def create_driver(servicename = nil, portname = nil)
- warn("WSDLDriverFactory#create_driver is depricated. Use create_rpc_driver instead.")
- port = find_port(servicename, portname)
- WSDLDriver.new(@wsdl, port, nil)
- end
-
- # Backward compatibility.
- alias createDriver create_driver
-
-private
-
- def find_port(servicename = nil, portname = nil)
- service = port = nil
- if servicename
- service = @wsdl.service(
- XSD::QName.new(@wsdl.targetnamespace, servicename))
- else
- service = @wsdl.services[0]
- end
+ service = if servicename
+ @wsdl.service(XSD::QName.new(@wsdl.targetnamespace, servicename))
+ else
+ @wsdl.services[0]
+ end
if service.nil?
- raise FactoryError.new("service #{servicename} not found in WSDL")
+ raise FactoryError.new("Service #{ servicename } not found in WSDL.")
end
- if portname
- port = service.ports[XSD::QName.new(@wsdl.targetnamespace, portname)]
- if port.nil?
- raise FactoryError.new("port #{portname} not found in WSDL")
- end
- else
- port = service.ports.find { |port| !port.soap_address.nil? }
- if port.nil?
- raise FactoryError.new("no ports have soap:address")
+ port = if portname
+ service.ports[XSD::QName.new(@wsdl.targetnamespace, portname)]
+ else
+ service.ports[0]
end
+ if port.nil?
+ raise FactoryError.new("Port #{ portname } not found in WSDL.")
end
if port.soap_address.nil?
- raise FactoryError.new("soap:address element not found in WSDL")
+ raise FactoryError.new("soap:address element not found in WSDL.")
end
- port
+ WSDLDriver.new(@wsdl, port, @logdev)
end
- def init_driver(drv, port)
- wsdl_elements = @wsdl.collect_elements
- wsdl_types = @wsdl.collect_complextypes + @wsdl.collect_simpletypes
- rpc_decode_typemap = wsdl_types +
- @wsdl.soap_rpc_complextypes(port.find_binding)
- drv.proxy.mapping_registry =
- Mapping::WSDLEncodedRegistry.new(rpc_decode_typemap)
- drv.proxy.literal_mapping_registry =
- Mapping::WSDLLiteralRegistry.new(wsdl_types, wsdl_elements)
- end
-
- def add_operation(drv, port)
- port.find_binding.operations.each do |op_bind|
- op_name = op_bind.soapoperation_name
- soapaction = op_bind.soapaction || ''
- orgname = op_name.name
- name = XSD::CodeGen::GenSupport.safemethodname(orgname)
- param_def = create_param_def(op_bind)
- opt = {
- :request_style => op_bind.soapoperation_style,
- :response_style => op_bind.soapoperation_style,
- :request_use => op_bind.input.soapbody_use,
- :response_use => op_bind.output.soapbody_use,
- :elementformdefault => false,
- :attributeformdefault => false
- }
- if op_bind.soapoperation_style == :rpc
- drv.add_rpc_operation(op_name, soapaction, name, param_def, opt)
- else
- drv.add_document_operation(soapaction, name, param_def, opt)
- end
- if orgname != name and orgname.capitalize == name.capitalize
- ::SOAP::Mapping.define_singleton_method(drv, orgname) do |*arg|
- __send__(name, *arg)
- end
- end
- end
- end
+ # Backward compatibility.
+ alias createDriver create_driver
+private
+
def import(location)
WSDL::Importer.import(location)
end
-
- def create_param_def(op_bind)
- op = op_bind.find_operation
- if op_bind.soapoperation_style == :rpc
- param_def = @methoddefcreator.collect_rpcparameter(op)
- else
- param_def = @methoddefcreator.collect_documentparameter(op)
- end
- # the first element of typedef in param_def is a String like
- # "::SOAP::SOAPStruct". turn this String to a class.
- param_def.collect { |io, name, typedef|
- typedef[0] = Mapping.class_from_name(typedef[0])
- [io, name, typedef]
- }
- end
-
- def partqname(part)
- if part.type
- part.type
- else
- part.element
- end
- end
-
- def param_def(type, name, klass, partqname)
- [type, name, [klass, partqname.namespace, partqname.name]]
- end
-
- def filter_parts(partsdef, partssource)
- parts = partsdef.split(/\s+/)
- partssource.find_all { |part| parts.include?(part.name) }
- end
end
class WSDLDriver
class << self
- if RUBY_VERSION >= "1.7.0"
- def __attr_proxy(symbol, assignable = false)
- name = symbol.to_s
- define_method(name) {
- @servant.__send__(name)
- }
- if assignable
- aname = name + '='
- define_method(aname) { |rhs|
- @servant.__send__(aname, rhs)
- }
- end
- end
- else
- def __attr_proxy(symbol, assignable = false)
- name = symbol.to_s
- module_eval <<-EOS
- def #{name}
- @servant.#{name}
- end
- EOS
- if assignable
- module_eval <<-EOS
- def #{name}=(value)
- @servant.#{name} = value
- end
- EOS
- end
+ def __attr_proxy(symbol, assignable = false)
+ name = symbol.to_s
+ module_eval <<-EOD
+ def #{name}
+ @servant.#{name}
+ end
+ EOD
+ if assignable
+ module_eval <<-EOD
+ def #{name}=(rhs)
+ @servant.#{name} = rhs
+ end
+ EOD
end
end
end
__attr_proxy :options
__attr_proxy :headerhandler
- __attr_proxy :streamhandler
__attr_proxy :test_loopback_response
__attr_proxy :endpoint_url, true
__attr_proxy :mapping_registry, true # for RPC unmarshal
__attr_proxy :wsdl_mapping_registry, true # for RPC marshal
__attr_proxy :default_encodingstyle, true
- __attr_proxy :generate_explicit_type, true
__attr_proxy :allow_unqualified_element, true
+ __attr_proxy :generate_explicit_type, true
def httpproxy
@servant.options["protocol.http.proxy"]
@@ -244,110 +143,105 @@ class WSDLDriver
end
def reset_stream
- @servant.reset_stream
+ @servant.streamhandler.reset
end
# Backward compatibility.
alias generateEncodeType= generate_explicit_type=
class Servant__
+ include Logger::Severity
include SOAP
attr_reader :options
+ attr_reader :streamhandler
+ attr_reader :headerhandler
attr_reader :port
- attr_accessor :soapaction
+ attr_accessor :mapping_registry
+ attr_accessor :wsdl_mapping_registry
attr_accessor :default_encodingstyle
attr_accessor :allow_unqualified_element
attr_accessor :generate_explicit_type
- attr_accessor :mapping_registry
- attr_accessor :wsdl_mapping_registry
def initialize(host, wsdl, port, logdev)
@host = host
@wsdl = wsdl
@port = port
@logdev = logdev
- @soapaction = nil
+
@options = setup_options
- @default_encodingstyle = nil
- @allow_unqualified_element = nil
- @generate_explicit_type = false
@mapping_registry = nil # for rpc unmarshal
@wsdl_mapping_registry = nil # for rpc marshal
+ @default_encodingstyle = EncodingNamespace
+ @allow_unqualified_element = true
+ @generate_explicit_type = false
@wiredump_file_base = nil
@mandatorycharset = nil
+
@wsdl_elements = @wsdl.collect_elements
@wsdl_types = @wsdl.collect_complextypes + @wsdl.collect_simpletypes
@rpc_decode_typemap = @wsdl_types +
@wsdl.soap_rpc_complextypes(port.find_binding)
- @wsdl_mapping_registry = Mapping::WSDLEncodedRegistry.new(
- @rpc_decode_typemap)
- @doc_mapper = Mapping::WSDLLiteralRegistry.new(
- @wsdl_types, @wsdl_elements)
+ @wsdl_mapping_registry = Mapping::WSDLRegistry.new(@rpc_decode_typemap)
+ @doc_mapper = Mapper.new(@wsdl_elements, @wsdl_types)
endpoint_url = @port.soap_address.location
+ @streamhandler = HTTPPostStreamHandler.new(endpoint_url,
+ @options["protocol.http"] ||= Property.new)
+ @headerhandler = Header::HandlerSet.new
# Convert a map which key is QName, to a Hash which key is String.
- @operation = {}
+ @operations = {}
@port.inputoperation_map.each do |op_name, op_info|
- orgname = op_name.name
- name = XSD::CodeGen::GenSupport.safemethodname(orgname)
- @operation[name] = @operation[orgname] = op_info
+ @operations[op_name.name] = op_info
add_method_interface(op_info)
end
- @proxy = ::SOAP::RPC::Proxy.new(endpoint_url, @soapaction, @options)
- end
-
- def inspect
- "#<#{self.class}:#{@proxy.inspect}>"
end
def endpoint_url
- @proxy.endpoint_url
+ @streamhandler.endpoint_url
end
def endpoint_url=(endpoint_url)
- @proxy.endpoint_url = endpoint_url
+ @streamhandler.endpoint_url = endpoint_url
+ @streamhandler.reset
end
- def headerhandler
- @proxy.headerhandler
+ def test_loopback_response
+ @streamhandler.test_loopback_response
end
- def streamhandler
- @proxy.streamhandler
- end
+ def rpc_send(method_name, *params)
+ log(INFO) { "call: calling method '#{ method_name }'." }
+ log(DEBUG) { "call: parameters '#{ params.inspect }'." }
- def test_loopback_response
- @proxy.test_loopback_response
- end
+ op_info = @operations[method_name]
+ method = create_method_struct(op_info, params)
+ req_header = call_headers
+ req_body = SOAPBody.new(method)
+ req_env = SOAPEnvelope.new(req_header, req_body)
- def reset_stream
- @proxy.reset_stream
- end
+ if @wiredump_file_base
+ @streamhandler.wiredump_file_base =
+ @wiredump_file_base + '_' << method_name
+ end
- def rpc_call(name, *values)
- set_wiredump_file_base(name)
- unless op_info = @operation[name]
- raise RuntimeError, "method: #{name} not defined"
- end
- req_header = create_request_header
- req_body = create_request_body(op_info, *values)
- reqopt = create_options({
- :soapaction => op_info.soapaction || @soapaction})
- resopt = create_options({
- :decode_typemap => @rpc_decode_typemap})
- env = @proxy.route(req_header, req_body, reqopt, resopt)
- raise EmptyResponseError unless env
- receive_headers(env.header)
begin
- @proxy.check_fault(env.body)
+ opt = create_options
+ opt[:decode_typemap] = @rpc_decode_typemap
+ res_env = invoke(req_env, op_info, opt)
+ receive_headers(res_env.header)
+ if res_env.body.fault
+ raise ::SOAP::FaultError.new(res_env.body.fault)
+ end
rescue ::SOAP::FaultError => e
Mapping.fault2exception(e)
end
- ret = env.body.response ?
- Mapping.soap2obj(env.body.response, @mapping_registry) : nil
- if env.body.outparams
- outparams = env.body.outparams.collect { |outparam|
+
+ ret = res_env.body.response ?
+ Mapping.soap2obj(res_env.body.response, @mapping_registry) : nil
+
+ if res_env.body.outparams
+ outparams = res_env.body.outparams.collect { |outparam|
Mapping.soap2obj(outparam)
}
return [ret].concat(outparams)
@@ -359,48 +253,29 @@ class WSDLDriver
# req_header: [[element, mustunderstand, encodingstyle(QName/String)], ...]
# req_body: SOAPBasetype/SOAPCompoundtype
def document_send(name, header_obj, body_obj)
- set_wiredump_file_base(name)
- unless op_info = @operation[name]
- raise RuntimeError, "method: #{name} not defined"
- end
- req_header = header_obj ? header_from_obj(header_obj, op_info) : nil
+ log(INFO) { "document_send: sending document '#{ name }'." }
+ op_info = @operations[name]
+ req_header = header_from_obj(header_obj, op_info)
req_body = body_from_obj(body_obj, op_info)
- opt = create_options({
- :soapaction => op_info.soapaction || @soapaction,
- :decode_typemap => @wsdl_types})
- env = @proxy.invoke(req_header, req_body, opt)
- raise EmptyResponseError unless env
- if env.body.fault
- raise ::SOAP::FaultError.new(env.body.fault)
- end
- res_body_obj = env.body.response ?
- Mapping.soap2obj(env.body.response, @mapping_registry) : nil
- return env.header, res_body_obj
+ req_env = SOAPEnvelope.new(req_header, req_body)
+ opt = create_options
+ res_env = invoke(req_env, op_info, opt)
+ if res_env.body.fault
+ raise ::SOAP::FaultError.new(res_env.body.fault)
+ end
+ res_body_obj = res_env.body.response ?
+ Mapping.soap2obj(res_env.body.response, @mapping_registry) : nil
+ return res_env.header, res_body_obj
end
private
- def create_options(hash = nil)
- opt = {}
- opt[:default_encodingstyle] = @default_encodingstyle
- opt[:allow_unqualified_element] = @allow_unqualified_element
- opt[:generate_explicit_type] = @generate_explicit_type
- opt.update(hash) if hash
- opt
- end
-
- def set_wiredump_file_base(name)
- if @wiredump_file_base
- @proxy.set_wiredump_file_base(@wiredump_file_base + "_#{name}")
- end
- end
-
- def create_request_header
- headers = @proxy.headerhandler.on_outbound
+ def call_headers
+ headers = @headerhandler.on_outbound
if headers.empty?
nil
else
- h = SOAPHeader.new
+ h = ::SOAP::SOAPHeader.new
headers.each do |header|
h.add(header.elename.name, header)
end
@@ -409,18 +284,13 @@ class WSDLDriver
end
def receive_headers(headers)
- @proxy.headerhandler.on_inbound(headers) if headers
- end
-
- def create_request_body(op_info, *values)
- method = create_method_struct(op_info, *values)
- SOAPBody.new(method)
+ @headerhandler.on_inbound(headers) if headers
end
- def create_method_struct(op_info, *params)
+ def create_method_struct(op_info, params)
parts_names = op_info.bodyparts.collect { |part| part.name }
obj = create_method_obj(parts_names, params)
- method = Mapping.obj2soap(obj, @wsdl_mapping_registry, op_info.op_name)
+ method = Mapping.obj2soap(obj, @wsdl_mapping_registry, op_info.optype_name)
if method.members.size != parts_names.size
new_method = SOAPStruct.new
method.each do |key, value|
@@ -437,14 +307,58 @@ class WSDLDriver
def create_method_obj(names, params)
o = Object.new
- idx = 0
- while idx < params.length
- o.instance_variable_set('@' + names[idx], params[idx])
- idx += 1
+ for idx in 0 ... params.length
+ o.instance_eval("@#{ names[idx] } = params[idx]")
end
o
end
+ def invoke(req_env, op_info, opt)
+ opt[:external_content] = nil
+ send_string = Processor.marshal(req_env, opt)
+ log(DEBUG) { "invoke: sending string #{ send_string }" }
+ conn_data = StreamHandler::ConnectionData.new(send_string)
+ if ext = opt[:external_content]
+ mime = MIMEMessage.new
+ ext.each do |k, v|
+ mime.add_attachment(v.data)
+ end
+ mime.add_part(conn_data.send_string + "\r\n")
+ mime.close
+ conn_data.send_string = mime.content_str
+ conn_data.send_contenttype = mime.headers['content-type'].str
+ end
+ conn_data = @streamhandler.send(conn_data, op_info.soapaction)
+ log(DEBUG) { "invoke: received string #{ conn_data.receive_string }" }
+ if conn_data.receive_string.empty?
+ return nil, nil
+ end
+ unmarshal(conn_data, opt)
+ end
+
+ def unmarshal(conn_data, opt)
+ contenttype = conn_data.receive_contenttype
+ if /#{MIMEMessage::MultipartContentType}/i =~ contenttype
+ opt[:external_content] = {}
+ mime = MIMEMessage.parse("Content-Type: " + contenttype,
+ conn_data.receive_string)
+ mime.parts.each do |part|
+ value = Attachment.new(part.content)
+ value.contentid = part.contentid
+ obj = SOAPAttachment.new(value)
+ opt[:external_content][value.contentid] = obj if value.contentid
+ end
+ opt[:charset] = @mandatorycharset ||
+ StreamHandler.parse_media_type(mime.root.headers['content-type'].str)
+ env = Processor.unmarshal(mime.root.content, opt)
+ else
+ opt[:charset] = @mandatorycharset ||
+ ::SOAP::StreamHandler.parse_media_type(contenttype)
+ env = Processor.unmarshal(conn_data.receive_string, opt)
+ end
+ env
+ end
+
def header_from_obj(obj, op_info)
if obj.is_a?(SOAPHeader)
obj
@@ -452,7 +366,7 @@ class WSDLDriver
if obj.nil?
nil
else
- raise RuntimeError.new("no header definition in schema: #{obj}")
+ raise RuntimeError.new("No header definition in schema.")
end
elsif op_info.headerparts.size == 1
part = op_info.headerparts[0]
@@ -462,7 +376,7 @@ class WSDLDriver
else
header = SOAPHeader.new()
op_info.headerparts.each do |part|
- child = Mapping.get_attribute(obj, part.name)
+ child = Mapper.find_attribute(obj, part.name)
ele = headeritem_from_obj(child, part.element || part.eletype)
header.add(part.name, ele)
end
@@ -476,7 +390,7 @@ class WSDLDriver
elsif obj.is_a?(SOAPHeaderItem)
obj
else
- Mapping.obj2soap(obj, @doc_mapper, name)
+ @doc_mapper.obj2ele(obj, name)
end
end
@@ -487,7 +401,7 @@ class WSDLDriver
if obj.nil?
nil
else
- raise RuntimeError.new("no body found in schema")
+ raise RuntimeError.new("No body found in schema.")
end
elsif op_info.bodyparts.size == 1
part = op_info.bodyparts[0]
@@ -496,7 +410,7 @@ class WSDLDriver
else
body = SOAPBody.new
op_info.bodyparts.each do |part|
- child = Mapping.get_attribute(obj, part.name)
+ child = Mapper.find_attribute(obj, part.name)
ele = bodyitem_from_obj(child, part.element || part.type)
body.add(ele.elename.name, ele)
end
@@ -510,46 +424,51 @@ class WSDLDriver
elsif obj.is_a?(SOAPElement)
obj
else
- Mapping.obj2soap(obj, @doc_mapper, name)
+ @doc_mapper.obj2ele(obj, name)
end
end
def add_method_interface(op_info)
- name = XSD::CodeGen::GenSupport.safemethodname(op_info.op_name.name)
- orgname = op_info.op_name.name
- parts_names = op_info.bodyparts.collect { |part| part.name }
case op_info.style
when :document
- if orgname != name and orgname.capitalize == name.capitalize
- add_document_method_interface(orgname, parts_names)
- end
- add_document_method_interface(name, parts_names)
+ add_document_method_interface(op_info.op_name.name)
when :rpc
- if orgname != name and orgname.capitalize == name.capitalize
- add_rpc_method_interface(orgname, parts_names)
- end
- add_rpc_method_interface(name, parts_names)
+ parts_names = op_info.bodyparts.collect { |part| part.name }
+ add_rpc_method_interface(op_info.op_name.name, parts_names)
else
- raise RuntimeError.new("unknown style: #{op_info.style}")
+ raise RuntimeError.new("Unknown style: #{op_info.style}")
end
end
+ def add_document_method_interface(name)
+ @host.instance_eval <<-EOS
+ def #{ name }(headers, body)
+ @servant.document_send(#{ name.dump }, headers, body)
+ end
+ EOS
+ end
+
def add_rpc_method_interface(name, parts_names)
- ::SOAP::Mapping.define_singleton_method(@host, name) do |*arg|
- unless arg.size == parts_names.size
- raise ArgumentError.new(
- "wrong number of arguments (#{arg.size} for #{parts_names.size})")
- end
- @servant.rpc_call(name, *arg)
- end
- @host.method(name)
+ i = 0
+ param_names = parts_names.collect { |orgname| i += 1; "arg#{ i }" }
+ callparam = (param_names.collect { |pname| ", " + pname }).join
+ @host.instance_eval <<-EOS
+ def #{ name }(#{ param_names.join(", ") })
+ @servant.rpc_send(#{ name.dump }#{ callparam })
+ end
+ EOS
end
- def add_document_method_interface(name, parts_names)
- ::SOAP::Mapping.define_singleton_method(@host, name) do |h, b|
- @servant.document_send(name, h, b)
- end
- @host.method(name)
+ def create_options
+ opt = {}
+ opt[:default_encodingstyle] = @default_encodingstyle
+ opt[:allow_unqualified_element] = @allow_unqualified_element
+ opt[:generate_explicit_type] = @generate_explicit_type
+ opt
+ end
+
+ def log(sev)
+ @logdev.add(sev, nil, self.class) { yield } if @logdev
end
def setup_options
@@ -563,13 +482,117 @@ class WSDLDriver
opt.add_hook("protocol.wiredump_file_base") do |key, value|
@wiredump_file_base = value
end
- opt["protocol.http.charset"] ||= XSD::Charset.xml_encoding_label
+ opt["protocol.http.charset"] ||= XSD::Charset.encoding_label
opt["protocol.http.proxy"] ||= Env::HTTP_PROXY
opt["protocol.http.no_proxy"] ||= Env::NO_PROXY
opt
end
+
+ class MappingError < StandardError; end
+ class Mapper
+ def initialize(elements, types)
+ @elements = elements
+ @types = types
+ end
+
+ def obj2ele(obj, name)
+ if ele = @elements[name]
+ _obj2ele(obj, ele)
+ elsif type = @types[name]
+ obj2type(obj, type)
+ else
+ raise MappingError.new("Cannot find name #{name} in schema.")
+ end
+ end
+
+ def ele2obj(ele, *arg)
+ raise NotImplementedError.new
+ end
+
+ def Mapper.find_attribute(obj, attr_name)
+ if obj.respond_to?(attr_name)
+ obj.__send__(attr_name)
+ elsif obj.is_a?(Hash)
+ obj[attr_name] || obj[attr_name.intern]
+ else
+ obj.instance_eval("@#{ attr_name }")
+ end
+ end
+
+ private
+
+ def _obj2ele(obj, ele)
+ o = nil
+ if ele.type
+ if type = @types[ele.type]
+ o = obj2type(obj, type)
+ elsif type = TypeMap[ele.type]
+ o = base2soap(obj, type)
+ else
+ raise MappingError.new("Cannot find type #{ele.type}.")
+ end
+ o.elename = ele.name
+ elsif ele.local_complextype
+ o = SOAPElement.new(ele.name)
+ ele.local_complextype.each_element do |child_ele|
+ o.add(_obj2ele(Mapper.find_attribute(obj, child_ele.name.name),
+ child_ele))
+ end
+ else
+ raise MappingError.new("Illegal schema?")
+ end
+ o
+ end
+
+ def obj2type(obj, type)
+ if type.is_a?(::WSDL::XMLSchema::SimpleType)
+ simple2soap(obj, type)
+ else
+ complex2soap(obj, type)
+ end
+ end
+
+ def simple2soap(obj, type)
+ o = base2soap(obj, TypeMap[type.base])
+ if type.restriction.enumeration.empty?
+ STDERR.puts("#{type.name}: simpleType which is not enum type not supported.")
+ return o
+ end
+ if type.restriction.enumeration.include?(o)
+ raise MappingError.new("#{o} is not allowed for #{type.name}")
+ end
+ o
+ end
+
+ def complex2soap(obj, type)
+ o = SOAPElement.new(type.name)
+ type.each_element do |child_ele|
+ o.add(_obj2ele(Mapper.find_attribute(obj, child_ele.name.name),
+ child_ele))
+ end
+ o
+ end
+
+ def _ele2obj(ele)
+ raise NotImplementedError.new
+ end
+
+ def base2soap(obj, type)
+ soap_obj = nil
+ if type <= XSD::XSDString
+ soap_obj = type.new(XSD::Charset.is_ces(obj, $KCODE) ?
+ XSD::Charset.encoding_conv(obj, $KCODE, XSD::Charset.encoding) :
+ obj)
+ else
+ soap_obj = type.new(obj)
+ end
+ soap_obj
+ end
+ end
end
end
end
+
+
diff --git a/lib/tempfile.rb b/lib/tempfile.rb
index 0e44e00d0e..cea229132a 100644
--- a/lib/tempfile.rb
+++ b/lib/tempfile.rb
@@ -116,7 +116,7 @@ class Tempfile < DelegateClass(File)
@@cleanlist.delete(@tmpname)
@data = @tmpname = nil
ObjectSpace.undefine_finalizer(self)
- rescue Errno::EACCES
+ rescue Errno::EACCESS
# may not be able to unlink on Windows; just ignore
end
end
diff --git a/lib/test/unit.rb b/lib/test/unit.rb
index 3a1676a330..3c0d265b2c 100644
--- a/lib/test/unit.rb
+++ b/lib/test/unit.rb
@@ -240,35 +240,35 @@ module Test
# class TS_MyTests
# def self.suite
# suite = Test::Unit::TestSuite.new
- # suite << TC_MyFirstTests.suite
- # suite << TC_MoreTestsByMe.suite
- # suite << TS_AnotherSetOfTests.suite
- # return suite
- # end
- # end
- # Test::Unit::UI::Console::TestRunner.run(TS_MyTests)
- #
- # Now, this is a bit cumbersome, so Test::Unit does a little bit more
- # for you, by wrapping these up automatically when you require
- # 'test/unit'. What does this mean? It means you could write the above
- # test case like this instead:
- #
- # require 'test/unit'
- # require 'tc_myfirsttests'
- # require 'tc_moretestsbyme'
- # require 'ts_anothersetoftests'
- #
- # Test::Unit is smart enough to find all the test cases existing in
- # the ObjectSpace and wrap them up into a suite for you. It then runs
- # the dynamic suite using the console TestRunner.
- #
- #
- # == Questions?
- #
- # I'd really like to get feedback from all levels of Ruby
- # practitioners about typos, grammatical errors, unclear statements,
- # missing points, etc., in this document (or any other).
- #
+# suite << TC_MyFirstTests.suite
+# suite << TC_MoreTestsByMe.suite
+# suite << TS_AnotherSetOfTests.suite
+# return suite
+# end
+# end
+# Test::Unit::UI::Console::TestRunner.run(TS_MyTests)
+#
+# Now, this is a bit cumbersome, so Test::Unit does a little bit more
+# for you, by wrapping these up automatically when you require
+# 'test/unit'. What does this mean? It means you could write the above
+# test case like this instead:
+#
+# require 'test/unit'
+# require 'tc_myfirsttests'
+# require 'tc_moretestsbyme'
+# require 'ts_anothersetoftests'
+#
+# Test::Unit is smart enough to find all the test cases existing in
+# the ObjectSpace and wrap them up into a suite for you. It then runs
+# the dynamic suite using the console TestRunner.
+#
+#
+# == Questions?
+#
+# I'd really like to get feedback from all levels of Ruby
+# practitioners about typos, grammatical errors, unclear statements,
+# missing points, etc., in this document (or any other).
+#
module Unit
def self.run=(flag)
@run = flag
@@ -280,8 +280,4 @@ module Test
end
end
-at_exit do
- unless $! || Test::Unit.run?
- exit Test::Unit::AutoRunner.run
- end
-end
+at_exit{exit(Test::Unit::AutoRunner.run($0)) unless($! || Test::Unit.run?)}
diff --git a/lib/test/unit/autorunner.rb b/lib/test/unit/autorunner.rb
index 2831293b7c..4eee7f654b 100644
--- a/lib/test/unit/autorunner.rb
+++ b/lib/test/unit/autorunner.rb
@@ -1,24 +1,17 @@
-require 'test/unit'
require 'test/unit/ui/testrunnerutilities'
require 'optparse'
module Test
module Unit
class AutoRunner
- def self.run(force_standalone=false, default_dir=nil, argv=ARGV, &block)
- r = new(force_standalone || standalone?, &block)
- if((!r.process_args(argv)) && default_dir)
- r.to_run << default_dir
- end
- r.run
- end
-
- def self.standalone?
- return false unless("-e" == $0)
- ObjectSpace.each_object(Class) do |klass|
- return false if(klass < TestCase)
+ def self.run(current_file=nil, default_dir=nil, argv=ARGV, &block)
+ if(!current_file || current_file == $0)
+ r = new(!current_file, &block)
+ if !r.process_args(argv) && default_dir
+ r.to_run << default_dir
+ end
+ r.run
end
- true
end
RUNNERS = {
@@ -62,14 +55,13 @@ module Test
require 'test/unit/collector/dir'
c = Collector::Dir.new
c.filter = r.filters
- c.pattern.concat(r.pattern) if(r.pattern)
- c.exclude.concat(r.exclude) if(r.exclude)
+ c.pattern = r.pattern if(r.pattern)
c.collect(*(r.to_run.empty? ? ['.'] : r.to_run))
end,
}
attr_reader :suite
- attr_accessor :output_level, :filters, :to_run, :pattern, :exclude
+ attr_accessor :output_level, :filters, :to_run, :pattern
attr_writer :runner, :collector
def initialize(standalone)
@@ -116,16 +108,9 @@ module Test
@to_run.concat(a)
end
- @pattern = []
- o.on('-p', '--pattern=PATTERN', Regexp,
+ o.on('-p', '--pattern=PATTERN', String,
"Match files to collect against PATTERN.") do |e|
- @pattern << e
- end
-
- @exclude = []
- o.on('-x', '--exclude=PATTERN', Regexp,
- "Ignore files to collect against PATTERN.") do |e|
- @exclude << e
+ @pattern = Regexp.new(e.sub(%r{\A/(.*)/\Z}m, '\\1'))
end
end
diff --git a/lib/test/unit/collector/dir.rb b/lib/test/unit/collector/dir.rb
index 1395cdf4e5..43fd1be718 100644
--- a/lib/test/unit/collector/dir.rb
+++ b/lib/test/unit/collector/dir.rb
@@ -7,7 +7,7 @@ module Test
class Dir
include Collector
- attr_reader :pattern, :exclude
+ attr_writer :pattern
def initialize(dir=::Dir, file=::File, object_space=::ObjectSpace, req=nil)
super()
@@ -15,8 +15,7 @@ module Test
@file = file
@object_space = object_space
@req = req
- @pattern = [/\btest_.*\.rb\Z/m]
- @exclude = []
+ @pattern = /\Atest_.*\.rb\Z/m
end
def collect(*from)
@@ -52,17 +51,10 @@ module Test
next if(e == '.' || e == '..')
e_name = @file.join(name, e)
if(@file.directory?(e_name))
- next if /\ACVS\z/ =~ e
sub_suite = recursive_collect(e_name, already_gathered)
sub_suites << sub_suite unless(sub_suite.empty?)
else
- next if /~\z/ =~ e_name or /\A\.\#/ =~ e
- if @pattern and !@pattern.empty?
- next unless @pattern.any? {|pat| pat =~ e_name}
- end
- if @exclude and !@exclude.empty?
- next if @exclude.any? {|pat| pat =~ e_name}
- end
+ (next unless(@pattern =~ e)) if(@pattern)
collect_file(e_name, sub_suites, already_gathered)
end
end
@@ -75,16 +67,18 @@ module Test
end
def collect_file(name, suites, already_gathered)
+ loadpath = $:.dup
dir = File.dirname(File.expand_path(name))
- $:.unshift(dir)
+ $:.unshift(dir) unless $:.first == dir
if(@req)
@req.require(name)
else
require(name)
end
find_test_cases(already_gathered).each{|t| add_suite(suites, t.suite)}
+ rescue LoadError, SystemExit
ensure
- $:.delete_at($:.rindex(dir)) if(dir)
+ $:.replace(loadpath)
end
end
end
diff --git a/lib/thread.rb b/lib/thread.rb
index 4c6a651a56..8b27356c48 100644
--- a/lib/thread.rb
+++ b/lib/thread.rb
@@ -23,8 +23,7 @@ end
class Thread
#
- # Wraps a block in Thread.critical, restoring the original value upon exit
- # from the critical section.
+ # FIXME: not documented in Pickaxe or Nutshell.
#
def Thread.exclusive
_old = Thread.critical
@@ -38,7 +37,7 @@ class Thread
end
#
-# Mutex implements a simple semaphore that can be used to coordinate access to
+# +Mutex+ implements a simple semaphore that can be used to coordinate access to
# shared data from multiple concurrent threads.
#
# Example:
@@ -59,9 +58,6 @@ end
# }
#
class Mutex
- #
- # Creates a new Mutex
- #
def initialize
@waiting = []
@locked = false;
@@ -127,7 +123,7 @@ class Mutex
#
# Obtains a lock, runs the block, and releases the lock when the block
- # completes. See the example under Mutex.
+ # completes. See the example under +Mutex+.
#
def synchronize
lock
@@ -139,8 +135,7 @@ class Mutex
end
#
- # If the mutex is locked, unlocks the mutex, wakes one waiting thread, and
- # yields in a critical section.
+ # FIXME: not documented in Pickaxe/Nutshell.
#
def exclusive_unlock
return unless @locked
@@ -159,9 +154,9 @@ class Mutex
end
#
-# ConditionVariable objects augment class Mutex. Using condition variables,
+# +ConditionVariable+ objects augment class +Mutex+. Using condition variables,
# it is possible to suspend while in the middle of a critical section until a
-# resource becomes available.
+# resource becomes available (see the discussion on page 117).
#
# Example:
#
@@ -186,9 +181,6 @@ end
# }
#
class ConditionVariable
- #
- # Creates a new ConditionVariable
- #
def initialize
@waiters = []
end
@@ -238,31 +230,10 @@ class ConditionVariable
end
#
-# This class provides a way to synchronize communication between threads.
-#
-# Example:
+# This class provides a way to communicate data between threads.
#
-# require 'thread'
-#
-# queue = Queue.new
-#
-# producer = Thread.new do
-# 5.times do |i|
-# sleep rand(i) # simulate expense
-# queue << i
-# puts "#{i} produced"
-# end
-# end
-#
-# consumer = Thread.new do
-# 5.times do |i|
-# value = queue.pop
-# sleep rand(i/2) # simulate expense
-# puts "consumed #{value}"
-# end
-# end
-#
-# consumer.join
+# TODO: an example (code or English) would really help here. How do you set up
+# a queue between two threads?
#
class Queue
#
@@ -295,15 +266,7 @@ class Queue
rescue ThreadError
end
end
-
- #
- # Alias of push
- #
alias << push
-
- #
- # Alias of push
- #
alias enq push
#
@@ -321,15 +284,7 @@ class Queue
ensure
Thread.critical = false
end
-
- #
- # Alias of pop
- #
alias shift pop
-
- #
- # Alias of pop
- #
alias deq pop
#
@@ -356,7 +311,9 @@ class Queue
#
# Alias of length.
#
- alias size length
+ def size
+ length
+ end
#
# Returns the number of threads waiting on the queue.
@@ -367,11 +324,9 @@ class Queue
end
#
-# This class represents queues of specified size capacity. The push operation
+# This class represents queues of specified size capacity. The +push+ operation
# may be blocked if the capacity is full.
#
-# See Queue for an example of how a SizedQueue works.
-#
class SizedQueue<Queue
#
# Creates a fixed-length queue with a maximum size of +max+.
@@ -415,10 +370,6 @@ class SizedQueue<Queue
max
end
- #
- # Pushes +obj+ to the queue. If there is no space left in the queue, waits
- # until space becomes available.
- #
def push(obj)
Thread.critical = true
while @que.length >= @max
@@ -428,20 +379,9 @@ class SizedQueue<Queue
end
super
end
-
- #
- # Alias of push
- #
alias << push
-
- #
- # Alias of push
- #
alias enq push
- #
- # Retrieves data from the queue and runs a waiting thread, if any.
- #
def pop(*args)
retval = super
Thread.critical = true
@@ -461,24 +401,20 @@ class SizedQueue<Queue
end
retval
end
-
- #
- # Alias of pop
- #
alias shift pop
-
- #
- # Alias of pop
- #
alias deq pop
- #
- # Returns the number of threads waiting on the queue.
- #
def num_waiting
@waiting.size + @queue_wait.size
end
end
# Documentation comments:
+# - SizedQueue #push and #pop deserve some documentation, as they are different
+# from the Queue implementations.
+# - Some methods are not documented in Pickaxe/Nutshell, and are therefore not
+# documented here. See FIXME notes.
+# - Reference to Pickaxe page numbers should be replaced with either a section
+# name or a summary.
+# - How do you document aliases?
# - How do you make RDoc inherit documentation from superclass?
diff --git a/lib/thwait.rb b/lib/thwait.rb
index 95d294a85d..8549ca0884 100644
--- a/lib/thwait.rb
+++ b/lib/thwait.rb
@@ -117,11 +117,8 @@ class ThreadsWait
@threads.concat threads
for th in threads
Thread.start(th) do |t|
- begin
- t.join
- ensure
- @wait_queue.push t
- end
+ t.join
+ @wait_queue.push t
end
end
end
diff --git a/lib/time.rb b/lib/time.rb
index 3b4ee9e72a..b045203ea1 100644
--- a/lib/time.rb
+++ b/lib/time.rb
@@ -7,7 +7,7 @@
# * date-time defined by RFC 2822
# * HTTP-date defined by RFC 2616
# * dateTime defined by XML Schema Part 2: Datatypes (ISO 8601)
-# * various formats handled by Date._parse (string to time only)
+# * various formats handled by ParseDate (string to time only)
#
# == Design Issues
#
@@ -60,7 +60,7 @@ class Time
'MST' => -7, 'MDT' => -6,
'PST' => -8, 'PDT' => -7,
# Following definition of military zones is original one.
- # See RFC 1123 and RFC 2822 for the error in RFC 822.
+ # See RFC 1123 and RFC 2822 for the error of RFC 822.
'A' => +1, 'B' => +2, 'C' => +3, 'D' => +4, 'E' => +5, 'F' => +6,
'G' => +7, 'H' => +8, 'I' => +9, 'K' => +10, 'L' => +11, 'M' => +12,
'N' => -1, 'O' => -2, 'P' => -3, 'Q' => -4, 'R' => -5, 'S' => -6,
@@ -83,111 +83,8 @@ class Time
off
end
- def zone_utc?(zone)
- # * +0000 means localtime. [RFC 2822]
- # * GMT is a localtime abbreviation in Europe/London, etc.
- if /\A(?:-00:00|-0000|-00|UTC|Z|UT)\z/i =~ zone
- true
- else
- false
- end
- end
- private :zone_utc?
-
- LeapYearMonthDays = [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
- CommonYearMonthDays = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
- def month_days(y, m)
- if ((y % 4 == 0) && (y % 100 != 0)) || (y % 400 == 0)
- LeapYearMonthDays[m-1]
- else
- CommonYearMonthDays[m-1]
- end
- end
- private :month_days
-
- def apply_offset(year, mon, day, hour, min, sec, off)
- if off < 0
- off = -off
- off, o = off.divmod(60)
- if o != 0 then sec += o; o, sec = sec.divmod(60); off += o end
- off, o = off.divmod(60)
- if o != 0 then min += o; o, min = min.divmod(60); off += o end
- off, o = off.divmod(24)
- if o != 0 then hour += o; o, hour = hour.divmod(24); off += o end
- if off != 0
- day += off
- if month_days(year, mon) < day
- mon += 1
- if 12 < mon
- mon = 1
- year += 1
- end
- day = 1
- end
- end
- elsif 0 < off
- off, o = off.divmod(60)
- if o != 0 then sec -= o; o, sec = sec.divmod(60); off -= o end
- off, o = off.divmod(60)
- if o != 0 then min -= o; o, min = min.divmod(60); off -= o end
- off, o = off.divmod(24)
- if o != 0 then hour -= o; o, hour = hour.divmod(24); off -= o end
- if off != 0 then
- day -= off
- if day < 1
- mon -= 1
- if mon < 1
- year -= 1
- mon = 12
- end
- day = month_days(year, mon)
- end
- end
- end
- return year, mon, day, hour, min, sec
- end
- private :apply_offset
-
- def make_time(year, mon, day, hour, min, sec, sec_fraction, zone, now)
- usec = nil
- usec = (sec_fraction * 1000000).to_i if sec_fraction
- if now
- begin
- break if year; year = now.year
- break if mon; mon = now.mon
- break if day; day = now.day
- break if hour; hour = now.hour
- break if min; min = now.min
- break if sec; sec = now.sec
- break if sec_fraction; usec = now.tv_usec
- end until true
- end
-
- year ||= 1970
- mon ||= 1
- day ||= 1
- hour ||= 0
- min ||= 0
- sec ||= 0
- usec ||= 0
-
- off = nil
- off = zone_offset(zone, year) if zone
-
- if off
- year, mon, day, hour, min, sec =
- apply_offset(year, mon, day, hour, min, sec, off)
- t = Time.utc(year, mon, day, hour, min, sec, usec)
- t.localtime if !zone_utc?(zone)
- t
- else
- Time.local(year, mon, day, hour, min, sec, usec)
- end
- end
- private :make_time
-
#
- # Parses +date+ using Date._parse and converts it to a Time object.
+ # Parses +date+ using ParseDate.parsedate and converts it to a Time object.
#
# If a block is given, the year described in +date+ is converted by the
# block. For example:
@@ -225,7 +122,7 @@ class Time
# If the extracted timezone abbreviation does not match any of them,
# it is ignored and the given time is regarded as a local time.
#
- # ArgumentError is raised if Date._parse cannot extract information from
+ # ArgumentError is raised if ParseDate cannot extract information from
# +date+ or Time class cannot represent specified date.
#
# This method can be used as fail-safe for other parsing methods as:
@@ -237,10 +134,37 @@ class Time
# A failure for Time.parse should be checked, though.
#
def parse(date, now=Time.now)
- d = Date._parse(date, false)
- year = d[:year]
+ year, mon, day, hour, min, sec, zone, _ = ParseDate.parsedate(date)
year = yield(year) if year && block_given?
- make_time(year, d[:mon], d[:mday], d[:hour], d[:min], d[:sec], d[:sec_fraction], d[:zone], now)
+
+ if now
+ begin
+ break if year; year = now.year
+ break if mon; mon = now.mon
+ break if day; day = now.day
+ break if hour; hour = now.hour
+ break if min; min = now.min
+ break if sec; sec = now.sec
+ end until true
+ end
+
+ year ||= 1970
+ mon ||= 1
+ day ||= 1
+ hour ||= 0
+ min ||= 0
+ sec ||= 0
+
+ off = nil
+ off = zone_offset(zone, year) if zone
+
+ if off
+ t = Time.utc(year, mon, day, hour, min, sec) - off
+ t.localtime if off != 0
+ t
+ else
+ Time.local(year, mon, day, hour, min, sec)
+ end
end
MonthValue = {
@@ -287,11 +211,10 @@ class Time
year
end
- year, mon, day, hour, min, sec =
- apply_offset(year, mon, day, hour, min, sec, zone_offset(zone))
t = Time.utc(year, mon, day, hour, min, sec)
- t.localtime if !zone_utc?(zone)
- t
+ offset = zone_offset(zone)
+ t = (t - offset).localtime if offset != 0 || zone == '+0000'
+ t
else
raise ArgumentError.new("not RFC 2822 compliant date: #{date.inspect}")
end
@@ -356,22 +279,13 @@ class Time
(\.\d*)?
(Z|[+-]\d\d:\d\d)?
\s*\z/ix =~ date
- year = $1.to_i
- mon = $2.to_i
- day = $3.to_i
- hour = $4.to_i
- min = $5.to_i
- sec = $6.to_i
- usec = 0
- usec = $7.to_f * 1000000 if $7
- if $8
- zone = $8
- year, mon, day, hour, min, sec =
- apply_offset(year, mon, day, hour, min, sec, zone_offset(zone))
- Time.utc(year, mon, day, hour, min, sec, usec)
- else
- Time.local(year, mon, day, hour, min, sec, usec)
- end
+ datetime = [$1.to_i, $2.to_i, $3.to_i, $4.to_i, $5.to_i, $6.to_i]
+ datetime << $7.to_f * 1000000 if $7
+ if $8
+ Time.utc(*datetime) - zone_offset($8)
+ else
+ Time.local(*datetime)
+ end
else
raise ArgumentError.new("invalid date: #{date.inspect}")
end
@@ -597,7 +511,7 @@ if __FILE__ == $0
assert_equal(Time.utc(2000, 1, 12, 12, 13, 14),
Time.xmlschema("2000-01-12T12:13:14Z"))
assert_equal(Time.utc(2001, 4, 17, 19, 23, 17, 300000),
- Time.xmlschema("2001-04-17T19:23:17.3Z"))
+ Time.xmlschema("2001-04-17T19:23:17.3Z"))
end
def test_encode_xmlschema
@@ -698,100 +612,6 @@ if __FILE__ == $0
assert_raise(ArgumentError) { Time.rfc2822("\307\341\314\343\332\311, 30 \344\346\335\343\310\321 2001 10:01:06") }
assert_raise(ArgumentError) { Time.rfc2822("=?iso-8859-1?Q?(=BF=E5),?= 12 =?iso-8859-1?Q?9=B7=EE?= 2001 14:52:41\n+0900 (JST)") }
end
-
- def test_zone_0000
- assert_equal(true, Time.parse("2000-01-01T00:00:00Z").utc?)
- assert_equal(true, Time.parse("2000-01-01T00:00:00-00:00").utc?)
- assert_equal(false, Time.parse("2000-01-01T00:00:00+00:00").utc?)
- assert_equal(false, Time.parse("Sat, 01 Jan 2000 00:00:00 GMT").utc?)
- assert_equal(true, Time.parse("Sat, 01 Jan 2000 00:00:00 -0000").utc?)
- assert_equal(false, Time.parse("Sat, 01 Jan 2000 00:00:00 +0000").utc?)
- assert_equal(false, Time.rfc2822("Sat, 01 Jan 2000 00:00:00 GMT").utc?)
- assert_equal(true, Time.rfc2822("Sat, 01 Jan 2000 00:00:00 -0000").utc?)
- assert_equal(false, Time.rfc2822("Sat, 01 Jan 2000 00:00:00 +0000").utc?)
- assert_equal(true, Time.rfc2822("Sat, 01 Jan 2000 00:00:00 UTC").utc?)
- end
-
- def test_parse_leap_second
- t = Time.utc(1998,12,31,23,59,59)
- assert_equal(t, Time.parse("Thu Dec 31 23:59:59 UTC 1998"))
- assert_equal(t, Time.parse("Fri Dec 31 23:59:59 -0000 1998"));t.localtime
- assert_equal(t, Time.parse("Fri Jan 1 08:59:59 +0900 1999"))
- assert_equal(t, Time.parse("Fri Jan 1 00:59:59 +0100 1999"))
- assert_equal(t, Time.parse("Fri Dec 31 23:59:59 +0000 1998"))
- assert_equal(t, Time.parse("Fri Dec 31 22:59:59 -0100 1998"));t.utc
- t += 1
- assert_equal(t, Time.parse("Thu Dec 31 23:59:60 UTC 1998"))
- assert_equal(t, Time.parse("Fri Dec 31 23:59:60 -0000 1998"));t.localtime
- assert_equal(t, Time.parse("Fri Jan 1 08:59:60 +0900 1999"))
- assert_equal(t, Time.parse("Fri Jan 1 00:59:60 +0100 1999"))
- assert_equal(t, Time.parse("Fri Dec 31 23:59:60 +0000 1998"))
- assert_equal(t, Time.parse("Fri Dec 31 22:59:60 -0100 1998"));t.utc
- t += 1 if t.sec == 60
- assert_equal(t, Time.parse("Thu Jan 1 00:00:00 UTC 1999"))
- assert_equal(t, Time.parse("Fri Jan 1 00:00:00 -0000 1999"));t.localtime
- assert_equal(t, Time.parse("Fri Jan 1 09:00:00 +0900 1999"))
- assert_equal(t, Time.parse("Fri Jan 1 01:00:00 +0100 1999"))
- assert_equal(t, Time.parse("Fri Jan 1 00:00:00 +0000 1999"))
- assert_equal(t, Time.parse("Fri Dec 31 23:00:00 -0100 1998"))
- end
-
- def test_rfc2822_leap_second
- t = Time.utc(1998,12,31,23,59,59)
- assert_equal(t, Time.rfc2822("Thu, 31 Dec 1998 23:59:59 UTC"))
- assert_equal(t, Time.rfc2822("Fri, 31 Dec 1998 23:59:59 -0000"));t.localtime
- assert_equal(t, Time.rfc2822("Fri, 1 Jan 1999 08:59:59 +0900"))
- assert_equal(t, Time.rfc2822("Fri, 1 Jan 1999 00:59:59 +0100"))
- assert_equal(t, Time.rfc2822("Fri, 31 Dec 1998 23:59:59 +0000"))
- assert_equal(t, Time.rfc2822("Fri, 31 Dec 1998 22:59:59 -0100"));t.utc
- t += 1
- assert_equal(t, Time.rfc2822("Thu, 31 Dec 1998 23:59:60 UTC"))
- assert_equal(t, Time.rfc2822("Fri, 31 Dec 1998 23:59:60 -0000"));t.localtime
- assert_equal(t, Time.rfc2822("Fri, 1 Jan 1999 08:59:60 +0900"))
- assert_equal(t, Time.rfc2822("Fri, 1 Jan 1999 00:59:60 +0100"))
- assert_equal(t, Time.rfc2822("Fri, 31 Dec 1998 23:59:60 +0000"))
- assert_equal(t, Time.rfc2822("Fri, 31 Dec 1998 22:59:60 -0100"));t.utc
- t += 1 if t.sec == 60
- assert_equal(t, Time.rfc2822("Thu, 1 Jan 1999 00:00:00 UTC"))
- assert_equal(t, Time.rfc2822("Fri, 1 Jan 1999 00:00:00 -0000"));t.localtime
- assert_equal(t, Time.rfc2822("Fri, 1 Jan 1999 09:00:00 +0900"))
- assert_equal(t, Time.rfc2822("Fri, 1 Jan 1999 01:00:00 +0100"))
- assert_equal(t, Time.rfc2822("Fri, 1 Jan 1999 00:00:00 +0000"))
- assert_equal(t, Time.rfc2822("Fri, 31 Dec 1998 23:00:00 -0100"))
- end
-
- def test_xmlschema_leap_second
- t = Time.utc(1998,12,31,23,59,59)
- assert_equal(t, Time.xmlschema("1998-12-31T23:59:59Z"))
- assert_equal(t, Time.xmlschema("1998-12-31T23:59:59-00:00"));t.localtime
- assert_equal(t, Time.xmlschema("1999-01-01T08:59:59+09:00"))
- assert_equal(t, Time.xmlschema("1999-01-01T00:59:59+01:00"))
- assert_equal(t, Time.xmlschema("1998-12-31T23:59:59+00:00"))
- assert_equal(t, Time.xmlschema("1998-12-31T22:59:59-01:00"));t.utc
- t += 1
- assert_equal(t, Time.xmlschema("1998-12-31T23:59:60Z"))
- assert_equal(t, Time.xmlschema("1998-12-31T23:59:60-00:00"));t.localtime
- assert_equal(t, Time.xmlschema("1999-01-01T08:59:60+09:00"))
- assert_equal(t, Time.xmlschema("1999-01-01T00:59:60+01:00"))
- assert_equal(t, Time.xmlschema("1998-12-31T23:59:60+00:00"))
- assert_equal(t, Time.xmlschema("1998-12-31T22:59:60-01:00"));t.utc
- t += 1 if t.sec == 60
- assert_equal(t, Time.xmlschema("1999-01-01T00:00:00Z"))
- assert_equal(t, Time.xmlschema("1999-01-01T00:00:00-00:00"));t.localtime
- assert_equal(t, Time.xmlschema("1999-01-01T09:00:00+09:00"))
- assert_equal(t, Time.xmlschema("1999-01-01T01:00:00+01:00"))
- assert_equal(t, Time.xmlschema("1999-01-01T00:00:00+00:00"))
- assert_equal(t, Time.xmlschema("1998-12-31T23:00:00-01:00"))
- end
-
- def test_ruby_talk_152866
- t = Time::xmlschema('2005-08-30T22:48:00-07:00')
- assert_equal(31, t.day)
- assert_equal(8, t.mon)
- end
-
- def test_parse_fraction
- assert_equal(500000, Time.parse("2000-01-01T00:00:00.5+00:00").tv_usec)
- end
end
+
end
diff --git a/lib/timeout.rb b/lib/timeout.rb
index 734d87f204..0ba5293d1d 100644
--- a/lib/timeout.rb
+++ b/lib/timeout.rb
@@ -1,39 +1,38 @@
-# = timeout.rb
#
-# execution timeout
+# timeout.rb -- execution timeout
#
-# = Synopsis
+# Copyright (C) 2000 Network Applied Communication Laboratory, Inc.
+# Copyright (C) 2000 Information-technology Promotion Agency, Japan
+#
+#= SYNOPSIS
#
# require 'timeout'
-# status = Timeout::timeout(5) {
-# # Something that should be interrupted if it takes too much time...
+# status = timeout(5) {
+# # something may take time
# }
#
-# = Description
+#= DESCRIPTION
+#
+# timeout executes the block. If the block execution terminates successfully
+# before timeout, it returns true. If not, it terminates the execution and
+# raise TimeoutError exception.
+#
+#== Parameters
+#
+# : timout
#
-# A way of performing a potentially long-running operation in a thread, and terminating
-# it's execution if it hasn't finished by a fixed amount of time.
+# The time in seconds to wait for block termination.
#
-# Previous versions of timeout didn't provide use a module for namespace. This version
-# provides both Timeout.timeout, and a backwards-compatible #timeout.
+# : [exception]
#
-# = Copyright
+# The exception class to be raised on timeout.
#
-# Copyright:: (C) 2000 Network Applied Communication Laboratory, Inc.
-# Copyright:: (C) 2000 Information-technology Promotion Agency, Japan
+#=end
module Timeout
- # Raised by Timeout#timeout when the block times out.
class Error<Interrupt
end
- # Executes the method's block. If the block execution terminates before +sec+
- # seconds has passed, it returns true. If not, it terminates the execution
- # and raises +exception+ (which defaults to Timeout::Error).
- #
- # Note that this is both a method of module Timeout, so you can 'include Timeout'
- # into your classes so they have a #timeout method, as well as a module method,
- # so you can call it directly as Timeout.timeout().
def timeout(sec, exception=Error)
return yield if sec == nil or sec.zero?
begin
@@ -48,22 +47,13 @@ module Timeout
y.kill if y and y.alive?
end
end
-
module_function :timeout
end
-# Identical to:
-#
-# Timeout::timeout(n, e, &block).
-#
-# Defined for backwards compatibility with earlier versions of timeout.rb, see
-# Timeout#timeout.
+# compatible
def timeout(n, e=Timeout::Error, &block)
Timeout::timeout(n, e, &block)
end
-
-# Another name for Timeout::Error, defined for backwards compatibility with
-# earlier versions of timeout.rb.
TimeoutError = Timeout::Error
if __FILE__ == $0
diff --git a/lib/un.rb b/lib/un.rb
index 9bf6c13146..c665f659b1 100644
--- a/lib/un.rb
+++ b/lib/un.rb
@@ -21,19 +21,20 @@
# ruby -run -e touch -- [OPTION] FILE
# ruby -run -e help [COMMAND]
-require "fileutils"
-require "optparse"
+require 'fileutils'
+require 'getopts'
module FileUtils
-# @fileutils_label = ""
+# @fileutils_label = ''
@fileutils_output = $stdout
end
def setup(options = "")
+ options += "v"
ARGV.map! do |x|
case x
when /^-/
- x.delete "^-#{options}v"
+ x.delete "^-#{options}"
when /[*?\[{]/
Dir[x]
else
@@ -41,18 +42,13 @@ def setup(options = "")
end
end
ARGV.flatten!
- ARGV.delete_if{|x| x == "-"}
- opt_hash = {}
- OptionParser.new do |o|
- options.scan(/.:?/) do |s|
- o.on("-" + s.tr(":", " ")) do |val|
- opt_hash[s.delete(":").intern] = val
- end
- end
- o.on("-v") do opt_hash[:verbose] = true end
- o.parse!
- end
- yield ARGV, opt_hash
+ ARGV.delete_if{|x| x == '-'}
+ getopts(options)
+ options = {}
+ options[:verbose] = true if $OPT["v"]
+ options[:force] = true if $OPT["f"]
+ options[:preserve] = true if $OPT["p"]
+ yield ARGV, options, $OPT
end
##
@@ -66,10 +62,9 @@ end
#
def cp
- setup("pr") do |argv, options|
+ setup("pr") do |argv, options, opt|
cmd = "cp"
- cmd += "_r" if options.delete :r
- options[:preserve] = true if options.delete :p
+ cmd += "_r" if opt["r"]
dest = argv.pop
argv = argv[0] if argv.size == 1
FileUtils.send cmd, argv, dest, options
@@ -87,10 +82,9 @@ end
#
def ln
- setup("sf") do |argv, options|
+ setup("sf") do |argv, options, opt|
cmd = "ln"
- cmd += "_s" if options.delete :s
- options[:force] = true if options.delete :f
+ cmd += "_s" if opt["s"]
dest = argv.pop
argv = argv[0] if argv.size == 1
FileUtils.send cmd, argv, dest, options
@@ -124,10 +118,9 @@ end
#
def rm
- setup("fr") do |argv, options|
+ setup("fr") do |argv, options, opt|
cmd = "rm"
- cmd += "_r" if options.delete :r
- options[:force] = true if options.delete :f
+ cmd += "_r" if opt["r"]
FileUtils.send cmd, argv, options
end
end
@@ -142,9 +135,9 @@ end
#
def mkdir
- setup("p") do |argv, options|
+ setup("p") do |argv, options, opt|
cmd = "mkdir"
- cmd += "_p" if options.delete :p
+ cmd += "_p" if options.delete :preserve
FileUtils.send cmd, argv, options
end
end
@@ -175,9 +168,8 @@ end
#
def install
- setup("pm:") do |argv, options|
- options[:mode] = (mode = options.delete :m) ? mode.oct : 0755
- options[:preserve] = true if options.delete :p
+ setup("pm:") do |argv, options, opt|
+ options[:mode] = opt["m"] ? opt["m"].oct : 0755
dest = argv.pop
argv = argv[0] if argv.size == 1
FileUtils.install argv, dest, options
diff --git a/lib/uri/common.rb b/lib/uri/common.rb
index ccf57bd93b..1e59c0fa33 100644
--- a/lib/uri/common.rb
+++ b/lib/uri/common.rb
@@ -88,7 +88,7 @@ module URI
# host = hostname | IPv4address | IPv6reference (RFC 2732)
HOST = "(?:#{HOSTNAME}|#{IPV4ADDR}|#{IPV6REF})"
# port = *digit
- PORT = '\d*'
+ PORT = "\d*"
# hostport = host [ ":" port ]
HOSTPORT = "#{HOST}(?::#{PORT})?"
@@ -270,12 +270,12 @@ module URI
#
# require 'uri'
#
- # enc_uri = URI.escape("http://example.com/?a=\11\15")
+ # enc_uri = URI.escape("http://foobar.com/?a=\11\15")
# p enc_uri
- # # => "http://example.com/?a=%09%0D"
+ # # => "http://foobar.com/?a=%09%0D"
#
# p URI.unescape(enc_uri)
- # # => "http://example.com/?a=\t\r"
+ # # => "http://foobar.com/?a=\t\r"
#
def escape(str, unsafe = UNSAFE)
unless unsafe.kind_of?(Regexp)
@@ -305,12 +305,12 @@ module URI
#
# require 'uri'
#
- # enc_uri = URI.escape("http://example.com/?a=\11\15")
+ # enc_uri = URI.escape("http://foobar.com/?a=\11\15")
# p enc_uri
- # # => "http://example.com/?a=%09%0D"
+ # # => "http://foobar.com/?a=%09%0D"
#
# p URI.unescape(enc_uri)
- # # => "http://example.com/?a=\t\r"
+ # # => "http://foobar.com/?a=\t\r"
#
def unescape(str)
str.gsub(ESCAPED) do
@@ -509,8 +509,8 @@ module URI
#
# require 'uri'
#
- # p URI.join("http://localhost/","main.rbx")
- # # => #<URI::HTTP:0x2022ac02 URL:http://localhost/main.rbx>
+ # p URI.join("http:/localhost/","main.rbx")
+ # # => #<URI::HTTP:0x2022ac02 URL:http:/localhost/main.php>
#
def self.join(*str)
u = self.parse(str[0])
@@ -541,8 +541,8 @@ module URI
#
# require "uri"
#
- # URI.extract("text here http://foo.example.org/bla and here mailto:test@example.com and here also.")
- # # => ["http://foo.example.org/bla", "mailto:test@example.com"]
+ # URI.extract("text here http://foo.bar.org/bla and here mailto:test@ruby.com and here also.")
+ # # => ["http://foo.bar.com/foobar", "mailto:foo@bar.com"]
#
def self.extract(str, schemes = nil, &block)
if block_given?
diff --git a/lib/uri/generic.rb b/lib/uri/generic.rb
index 51c2bf17f6..0dedcf494a 100644
--- a/lib/uri/generic.rb
+++ b/lib/uri/generic.rb
@@ -343,7 +343,14 @@ module URI
def split_userinfo(ui)
return nil, nil unless ui
- user, password = ui.split(/:/, 2)
+ tmp = ui.index(':')
+ if tmp
+ user = ui[0..tmp - 1]
+ password = ui[tmp + 1..-1]
+ else
+ user = ui
+ password = nil
+ end
return user, password
end
@@ -689,10 +696,10 @@ module URI
#
# require 'uri'
#
- # uri = URI.parse("http://my.example.com")
+ # uri = URI.parse("http://my.rubysite.com")
# uri.merge!("/main.rbx?page=1")
# p uri
- # # => #<URI::HTTP:0x2021f3b0 URL:http://my.example.com/main.rbx?page=1>
+ # # => #<URI::HTTP:0x2021f3b0 URL:http://my.rubysite.com/main.rbx?page=1>
#
def merge!(oth)
t = merge(oth)
@@ -718,9 +725,9 @@ module URI
#
# require 'uri'
#
- # uri = URI.parse("http://my.example.com")
+ # uri = URI.parse("http://my.rubysite.com")
# p uri.merge("/main.rbx?page=1")
- # # => #<URI::HTTP:0x2021f3b0 URL:http://my.example.com/main.rbx?page=1>
+ # # => #<URI::HTTP:0x2021f3b0 URL:http://my.rubysite.com/main.rbx?page=1>
#
def merge(oth)
begin
@@ -904,8 +911,8 @@ module URI
#
# require 'uri'
#
- # uri = URI.parse('http://my.example.com/main.rbx?page=1')
- # p uri.route_from('http://my.example.com')
+ # uri = URI.parse('http://my.rubysite.com/main.rbx?page=1')
+ # p uri.route_from('http://my.rubysite.com')
# #=> #<URI::Generic:0x20218858 URL:/main.rbx?page=1>
#
def route_from(oth)
@@ -944,8 +951,8 @@ module URI
#
# require 'uri'
#
- # uri = URI.parse('http://my.example.com')
- # p uri.route_to('http://my.example.com/main.rbx?page=1')
+ # uri = URI.parse('http://my.rubysite.com')
+ # p uri.route_to('http://my.rubysite.com/main.rbx?page=1')
# #=> #<URI::Generic:0x2020c2f6 URL:/main.rbx?page=1>
#
def route_to(oth)
@@ -1085,9 +1092,9 @@ module URI
#
# require 'uri'
#
- # uri = URI.parse('http://myuser:mypass@my.example.com/test.rbx')
+ # uri = URI.parse('http://myuser:mypass@my.rubysite.com/test.rbx')
# p uri.select(:userinfo, :host, :path)
- # # => ["myuser:mypass", "my.example.com", "/test.rbx"]
+ # # => ["myuser:mypass", "my.rubysite.com", "/test.rbx"]
#
def select(*components)
components.collect do |c|
@@ -1101,7 +1108,7 @@ module URI
end
def inspect
- sprintf("#<%s:%#0x URL:%s>", self.class.to_s, self.object_id, self.to_s)
+ sprintf("#<%s:0x%x URL:%s>", self.class.to_s, self.object_id, self.to_s)
end
def coerce(oth)
diff --git a/lib/webrick/accesslog.rb b/lib/webrick/accesslog.rb
index f97769545e..25dcbc1be8 100644
--- a/lib/webrick/accesslog.rb
+++ b/lib/webrick/accesslog.rb
@@ -32,7 +32,6 @@ module WEBrick
params["i"] = req
params["l"] = "-"
params["m"] = req.request_method
- params["n"] = req.attributes
params["o"] = res
params["p"] = req.port
params["q"] = req.query_string
@@ -47,17 +46,15 @@ module WEBrick
end
def format(format_string, params)
- format_string.gsub(/\%(?:\{(.*?)\})?>?([a-zA-Z%])/){
+ format_string.gsub(/\%(?:\{(.*?)\})?>?([a-zA-Z])/){
param, spec = $1, $2
case spec[0]
- when ?e, ?i, ?n, ?o
+ when ?e, ?i, ?o
raise AccessLogError,
"parameter is required for \"#{spec}\"" unless param
params[spec][param] || "-"
when ?t
params[spec].strftime(param || CLF_TIME_FORMAT)
- when ?%
- "%"
else
params[spec]
end
diff --git a/lib/webrick/cgi.rb b/lib/webrick/cgi.rb
index ff5f7a6102..5c38e42fc4 100644
--- a/lib/webrick/cgi.rb
+++ b/lib/webrick/cgi.rb
@@ -16,8 +16,6 @@ module WEBrick
class CGI
CGIError = Class.new(StandardError)
- attr_reader :config, :logger
-
def initialize(*args)
if defined?(MOD_RUBY)
unless ENV.has_key?("GATEWAY_INTERFACE")
@@ -28,7 +26,7 @@ module WEBrick
httpv = $1
end
@config = WEBrick::Config::HTTP.dup.update(
- :ServerSoftware => ENV["SERVER_SOFTWARE"] || "null",
+ :ServerSoftware => ENV["SERVER_SOFTWARE"],
:HTTPVersion => HTTPVersion.new(httpv || "1.0"),
:RunOnCGI => true, # to detect if it runs on CGI.
:NPH => false # set true to run as NPH script.
@@ -41,20 +39,13 @@ module WEBrick
@options = args
end
- def [](key)
- @config[key]
- end
-
def start(env=ENV, stdin=$stdin, stdout=$stdout)
sock = WEBrick::CGI::Socket.new(@config, env, stdin, stdout)
req = HTTPRequest.new(@config)
res = HTTPResponse.new(@config)
unless @config[:NPH] or defined?(MOD_RUBY)
def res.setup_header
- unless @header["status"]
- phrase = HTTPStatus::reason_phrase(@status)
- @header["status"] = "#{@status} #{phrase}"
- end
+ @header["status"] ||= @status
super
end
def res.status_line
@@ -64,9 +55,12 @@ module WEBrick
begin
req.parse(sock)
- req.script_name = (env["SCRIPT_NAME"] || File.expand_path($0)).dup
- req.path_info = (env["PATH_INFO"] || "").dup
- req.query_string = env["QUERY_STRING"]
+ req.script_name = (env["SCRIPT_NAME"] || "").dup
+ if env["PATH_INFO"].nil? || env["PATH_INFO"].empty?
+ req.path_info = nil
+ else
+ req.path_info = env["PATH_INFO"].dup
+ end
req.user = env["REMOTE_USER"]
res.request_method = req.request_method
res.request_uri = req.request_uri
@@ -129,7 +123,6 @@ module WEBrick
@header_part = StringIO.new
@body_part = stdin
@out_port = stdout
- @out_port.binmode
@server_addr = @env["SERVER_ADDR"] || "0.0.0.0"
@server_name = @env["SERVER_NAME"]
@@ -149,20 +142,19 @@ module WEBrick
end
def request_line
- meth = @env["REQUEST_METHOD"] || "GET"
- unless url = @env["REQUEST_URI"]
- url = (@env["SCRIPT_NAME"] || File.expand_path($0)).dup
- url << @env["PATH_INFO"].to_s
- url = WEBrick::HTTPUtils.escape_path(url)
- if query_string = @env["QUERY_STRING"]
- unless query_string.empty?
- url << "?" << query_string
- end
+ meth = @env["REQUEST_METHOD"]
+ url = @env["SCRIPT_NAME"].dup
+ if path_info = @env["PATH_INFO"]
+ url << path_info
+ end
+ if query_string = @env["QUERY_STRING"]
+ unless query_string.empty?
+ url << "?" << query_string
end
end
# we cannot get real HTTP version of client ;)
httpv = @config[:HTTPVersion]
- return "#{meth} #{url} HTTP/#{httpv}"
+ "#{meth} #{url} HTTP/#{httpv}"
end
def setup_header
diff --git a/lib/webrick/config.rb b/lib/webrick/config.rb
index 5897b977d8..f0e262bf3e 100644
--- a/lib/webrick/config.rb
+++ b/lib/webrick/config.rb
@@ -33,6 +33,7 @@ module WEBrick
:StartCallback => nil,
:StopCallback => nil,
:AcceptCallback => nil,
+ :DoNotReverseLookup => nil,
}
# for HTTPServer, HTTPRequest, HTTPResponse ...
@@ -65,13 +66,13 @@ module WEBrick
)
FileHandler = {
- :NondisclosureName => [".ht*", "*~"],
+ :NondisclosureName => ".ht*",
:FancyIndexing => false,
:HandlerTable => {},
:HandlerCallback => nil,
:DirectoryCallback => nil,
:FileCallback => nil,
- :UserDir => nil, # e.g. "public_html"
+ :UserDir => "public_html",
:AcceptableLanguages => [] # ["en", "ja", ... ]
}
diff --git a/lib/webrick/httpauth.rb b/lib/webrick/httpauth.rb
index 147c04021c..3f0b83339d 100644
--- a/lib/webrick/httpauth.rb
+++ b/lib/webrick/httpauth.rb
@@ -8,6 +8,7 @@
#
# $IPR: httpauth.rb,v 1.14 2003/07/22 19:20:42 gotoyuzo Exp $
+require 'base64'
require 'webrick/httpauth/basicauth'
require 'webrick/httpauth/digestauth'
require 'webrick/httpauth/htpasswd'
@@ -22,7 +23,7 @@ module WEBrick
user = pass = nil
if /^Basic\s+(.*)/o =~ req[req_field]
userpass = $1
- user, pass = userpass.unpack("m*")[0].split(":", 2)
+ user, pass = decode64(userpass).split(":", 2)
end
if block.call(user, pass)
req.user = user
diff --git a/lib/webrick/httpauth/basicauth.rb b/lib/webrick/httpauth/basicauth.rb
index e835361dc2..926a6b8289 100644
--- a/lib/webrick/httpauth/basicauth.rb
+++ b/lib/webrick/httpauth/basicauth.rb
@@ -10,6 +10,7 @@
require 'webrick/config'
require 'webrick/httpstatus'
require 'webrick/httpauth/authenticator'
+require 'base64'
module WEBrick
module HTTPAuth
@@ -34,7 +35,7 @@ module WEBrick
unless basic_credentials = check_scheme(req)
challenge(req, res)
end
- userid, password = basic_credentials.unpack("m*")[0].split(":", 2)
+ userid, password = decode64(basic_credentials).split(":", 2)
password ||= ""
if userid.empty?
error("user id was not given.")
diff --git a/lib/webrick/httpauth/digestauth.rb b/lib/webrick/httpauth/digestauth.rb
index 318e0bf17f..05a6f192c3 100644
--- a/lib/webrick/httpauth/digestauth.rb
+++ b/lib/webrick/httpauth/digestauth.rb
@@ -16,6 +16,7 @@ require 'webrick/httpstatus'
require 'webrick/httpauth/authenticator'
require 'digest/md5'
require 'digest/sha1'
+require 'base64'
module WEBrick
module HTTPAuth
@@ -174,11 +175,11 @@ module WEBrick
if auth_req['qop'] == "auth" || auth_req['qop'] == nil
ha2 = hexdigest(req.request_method, auth_req['uri'])
- ha2_res = hexdigest("", auth_req['uri'])
+ ha2_res = digest("", auth_req['uri'])
elsif auth_req['qop'] == "auth-int"
ha2 = hexdigest(req.request_method, auth_req['uri'],
hexdigest(req.body))
- ha2_res = hexdigest("", auth_req['uri'], hexdigest(res.body))
+ ha2_res = digest("", auth_req['uri'], hexdigest(req.body))
end
if auth_req['qop'] == "auth" || auth_req['qop'] == "auth-int"
@@ -253,7 +254,7 @@ module WEBrick
def generate_next_nonce(req)
now = "%012d" % req.request_time.to_i
pk = hexdigest(now, @instance_key)[0,32]
- nonce = [now + ":" + pk].pack("m*").chop # it has 60 length of chars.
+ nonce = Base64.encode64(now + ":" + pk).chop # it has 60 length of chars.
nonce
end
@@ -261,7 +262,7 @@ module WEBrick
username = auth_req['username']
nonce = auth_req['nonce']
- pub_time, pk = nonce.unpack("m*")[0].split(":", 2)
+ pub_time, pk = Base64.decode64(nonce).split(":", 2)
if (!pub_time || !pk)
error("%s: empty nonce is given", username)
return false
@@ -330,6 +331,10 @@ module WEBrick
def hexdigest(*args)
@h.hexdigest(args.join(":"))
end
+
+ def digest(*args)
+ @h.digest(args.join(":"))
+ end
end
class ProxyDigestAuth < DigestAuth
diff --git a/lib/webrick/httpauth/htpasswd.rb b/lib/webrick/httpauth/htpasswd.rb
index 40f9297b05..a4a80647d8 100644
--- a/lib/webrick/httpauth/htpasswd.rb
+++ b/lib/webrick/httpauth/htpasswd.rb
@@ -32,15 +32,7 @@ module WEBrick
open(@path){|io|
while line = io.gets
line.chomp!
- case line
- when %r!\A[^:]+:[a-zA-Z0-9./]{13}\z!
- user, pass = line.split(":")
- when /:\$/, /:\{SHA\}/
- raise NotImplementedError,
- 'MD5, SHA1 .htpasswd file not supported'
- else
- raise StandardError, 'bad .htpasswd file'
- end
+ user, pass = line.split(":")
@passwd[user] = pass
end
}
diff --git a/lib/webrick/httpproxy.rb b/lib/webrick/httpproxy.rb
index 14e3499775..65f830ecbb 100644
--- a/lib/webrick/httpproxy.rb
+++ b/lib/webrick/httpproxy.rb
@@ -15,14 +15,6 @@ require "net/http"
Net::HTTP::version_1_2 if RUBY_VERSION < "1.7"
module WEBrick
- NullReader = Object.new
- class << NullReader
- def read(*args)
- nil
- end
- alias gets read
- end
-
class HTTPProxyServer < HTTPServer
def initialize(config)
super
@@ -118,8 +110,7 @@ module WEBrick
proxy_host = proxy.host
proxy_port = proxy.port
if proxy.userinfo
- credentials = "Basic " + [proxy.userinfo].pack("m*")
- credentials.chomp!
+ credentials = "Basic " + encode64(proxy.userinfo)
header['proxy-authorization'] = credentials
end
end
@@ -179,8 +170,7 @@ module WEBrick
if proxy = proxy_uri(req, res)
proxy_request_line = "CONNECT #{host}:#{port} HTTP/1.0"
if proxy.userinfo
- credentials = "Basic " + [proxy.userinfo].pack("m*")
- credentials.chomp!
+ credentials = "Basic " + encode64(proxy.userinfo)
end
host, port = proxy.host, proxy.port
end
@@ -221,10 +211,6 @@ module WEBrick
end
res.send_response(ua)
access_log(@config, req, res)
-
- # Should clear request-line not to send the sesponse twice.
- # see: HTTPServer#run
- req.parse(NullReader) rescue nil
end
begin
diff --git a/lib/webrick/httprequest.rb b/lib/webrick/httprequest.rb
index 297866f47a..508374adf6 100644
--- a/lib/webrick/httprequest.rb
+++ b/lib/webrick/httprequest.rb
@@ -27,8 +27,8 @@ module WEBrick
attr_reader :request_method, :unparsed_uri, :http_version
# Request-URI
- attr_reader :request_uri, :host, :port, :path
- attr_accessor :script_name, :path_info, :query_string
+ attr_reader :request_uri, :host, :port, :path, :query_string
+ attr_accessor :script_name, :path_info
# Header and entity body
attr_reader :raw_header, :header, :cookies
@@ -306,12 +306,7 @@ module WEBrick
def read_chunked(socket, block)
chunk_size, = read_chunk_size(socket)
while chunk_size > 0
- data = ""
- while data.size < chunk_size
- tmp = read_data(socket, chunk_size-data.size) # read chunk-data
- break unless tmp
- data << tmp
- end
+ data = read_data(socket, chunk_size) # read chunk-data
if data.nil? || data.size != chunk_size
raise BadRequest, "bad chunk data size."
end
diff --git a/lib/webrick/httpserver.rb b/lib/webrick/httpserver.rb
index ccb656299d..ffbae70409 100644
--- a/lib/webrick/httpserver.rb
+++ b/lib/webrick/httpserver.rb
@@ -46,13 +46,6 @@ module WEBrick
req = HTTPRequest.new(@config)
server = self
begin
- timeout = @config[:RequestTimeout]
- while timeout > 0
- break if IO.select([sock], nil, nil, 0.5)
- timeout = 0 if @status != :Running
- timeout -= 0.5
- end
- raise HTTPStatus::EOFError if timeout <= 0 || sock.eof?
req.parse(sock)
res.request_method = req.request_method
res.request_uri = req.request_uri
diff --git a/lib/webrick/httpservlet/filehandler.rb b/lib/webrick/httpservlet/filehandler.rb
index ba9417f3e8..1c48734987 100644
--- a/lib/webrick/httpservlet/filehandler.rb
+++ b/lib/webrick/httpservlet/filehandler.rb
@@ -226,7 +226,7 @@ module WEBrick
path_info.unshift("") # dummy for checking @root dir
while base = path_info.first
- check_filename(req, res, base)
+ check_filename(base)
break if base == "/"
break unless File.directory?(res.filename + base)
shift_path_info(req, res, path_info)
@@ -234,7 +234,7 @@ module WEBrick
end
if base = path_info.first
- check_filename(req, res, base)
+ check_filename(base)
if base == "/"
if file = search_index_file(req, res)
shift_path_info(req, res, path_info, file)
@@ -254,13 +254,11 @@ module WEBrick
return false
end
- def check_filename(req, res, name)
- @options[:NondisclosureName].each{|pattern|
- if File.fnmatch("/#{pattern}", name)
- @logger.warn("the request refers nondisclosure name `#{name}'.")
- raise HTTPStatus::NotFound, "`#{req.path}' not found."
- end
- }
+ def check_filename(name)
+ if File.fnmatch("/#{@options[:NondisclosureName]}", name)
+ @logger.warn("the request refers nondisclosure name `#{name}'.")
+ raise HTTPStatus::NotFound, "`#{req.path}' not found."
+ end
end
def shift_path_info(req, res, path_info, base=nil)
@@ -308,15 +306,6 @@ module WEBrick
end
end
- def nondisclosure_name?(name)
- @options[:NondisclosureName].each{|pattern|
- if File.fnmatch(pattern, name)
- return true
- end
- }
- return false
- end
-
def set_dir_list(req, res)
redirect_to_directory_uri(req, res)
unless @options[:FancyIndexing]
@@ -325,7 +314,7 @@ module WEBrick
local_path = res.filename
list = Dir::entries(local_path).collect{|name|
next if name == "." || name == ".."
- next if nondisclosure_name?(name)
+ next if File::fnmatch(@options[:NondisclosureName], name)
st = (File::stat(local_path + name) rescue nil)
if st.nil?
[ name, nil, -1 ]
diff --git a/lib/webrick/httputils.rb b/lib/webrick/httputils.rb
index c57af2c860..18e3e25887 100644
--- a/lib/webrick/httputils.rb
+++ b/lib/webrick/httputils.rb
@@ -179,14 +179,14 @@ module WEBrick
if value
parts = value.split(/,\s*/)
parts.each {|part|
- if m = %r{^([^\s,]+?)(?:;\s*q=(\d+(?:\.\d+)?))?$}.match(part)
- val = m[1]
+ if m = %r{^([^\s,]+?)(?:;\s*q=([\d]+(?:\.[\d]+)))?$}.match(part)
+ lang = m[1]
q = (m[2] or 1).to_f
- tmp.push([val, q])
+ tmp.push([lang, q])
end
}
- tmp = tmp.sort_by{|val, q| -q}
- tmp.collect!{|val, q| val}
+ tmp = tmp.sort_by{|lang, q| -q}
+ tmp.collect!{|lang, q| lang}
end
return tmp
end
@@ -294,7 +294,6 @@ module WEBrick
query = Hash.new
if str
str.split(/[&;]/).each{|x|
- next if x.empty?
key, val = x.split(/=/,2)
key = unescape_form(key)
val = unescape_form(val.to_s)
@@ -353,18 +352,15 @@ module WEBrick
unwise = '{}|\\^[]`'
nonascii = (0x80..0xff).collect{|c| c.chr }.join
- module_function
-
def _make_regex(str) /([#{Regexp.escape(str)}])/n end
- def _make_regex!(str) /([^#{Regexp.escape(str)}])/n end
def _escape(str, regex) str.gsub(regex){ "%%%02X" % $1[0] } end
def _unescape(str, regex) str.gsub(regex){ $1.hex.chr } end
+ module_function :_make_regex, :_escape, :_unescape
UNESCAPED = _make_regex(control+space+delims+unwise+nonascii)
UNESCAPED_FORM = _make_regex(reserved+control+delims+unwise+nonascii)
NONASCII = _make_regex(nonascii)
ESCAPED = /%([0-9a-fA-F]{2})/
- UNESCAPED_PCHAR = _make_regex!(unreserved+":@&=+$,")
def escape(str)
_escape(str, UNESCAPED)
@@ -384,16 +380,12 @@ module WEBrick
_unescape(str.gsub(/\+/, " "), ESCAPED)
end
- def escape_path(str)
- result = ""
- str.scan(%r{/([^/]*)}).each{|i|
- result << "/" << _escape(i[0], UNESCAPED_PCHAR)
- }
- return result
- end
-
def escape8bit(str)
_escape(str, NONASCII)
end
+
+ module_function :escape, :unescape, :escape_form, :unescape_form,
+ :escape8bit
+
end
end
diff --git a/lib/webrick/server.rb b/lib/webrick/server.rb
index 16dbd46f98..0668e27b05 100644
--- a/lib/webrick/server.rb
+++ b/lib/webrick/server.rb
@@ -31,9 +31,9 @@ module WEBrick
exit!(0) if fork
Dir::chdir("/")
File::umask(0)
- STDIN.reopen("/dev/null")
- STDOUT.reopen("/dev/null", "w")
- STDERR.reopen("/dev/null", "w")
+ [ STDIN, STDOUT, STDERR ].each{|io|
+ io.reopen("/dev/null", "r+")
+ }
yield if block_given?
end
end
@@ -61,9 +61,6 @@ module WEBrick
warn(":Listen option is deprecated; use GenericServer#listen")
end
listen(@config[:BindAddress], @config[:Port])
- if @config[:Port] == 0
- @config[:Port] = @listeners[0].addr[1]
- end
end
end
@@ -91,15 +88,20 @@ module WEBrick
if svrs = IO.select(@listeners, nil, nil, 2.0)
svrs[0].each{|svr|
@tokens.pop # blocks while no token is there.
- if sock = accept_client(svr)
- th = start_thread(sock, &block)
- th[:WEBrickThread] = true
- thgroup.add(th)
- else
- @tokens.push(nil)
+ sock = svr.accept
+ sock.sync = true
+ if @config[:DoNotReverseLookup]
+ sock.do_not_reverse_lookup = true
end
+ Utils::set_close_on_exec(sock)
+ th = start_thread(sock, &block)
+ th[:WEBrickThread] = true
+ thgroup.add(th)
}
end
+ rescue Errno::ECONNRESET, Errno::ECONNABORTED, Errno::EPROTO => ex
+ # TCP connection was established but RST segment was sent
+ # from peer before calling TCPServer#accept.
rescue Errno::EBADF, IOError => ex
# if the listening socket was closed in GenericServer#shutdown,
# IO::select raise it.
@@ -141,34 +143,12 @@ module WEBrick
private
- def accept_client(svr)
- sock = nil
- begin
- sock = svr.accept
- sock.sync = true
- Utils::set_non_blocking(sock)
- Utils::set_close_on_exec(sock)
- rescue Errno::ECONNRESET, Errno::ECONNABORTED, Errno::EPROTO => ex
- # TCP connection was established but RST segment was sent
- # from peer before calling TCPServer#accept.
- rescue Exception => ex
- msg = "#{ex.class}: #{ex.message}\n\t#{ex.backtrace[0]}"
- @logger.error msg
- end
- return sock
- end
-
def start_thread(sock, &block)
Thread.start{
begin
Thread.current[:WEBrickSocket] = sock
- begin
- addr = sock.peeraddr
- @logger.debug "accept: #{addr[3]}:#{addr[1]}"
- rescue SocketError
- @logger.debug "accept: <address unknown>"
- raise
- end
+ addr = sock.peeraddr
+ @logger.debug "accept: #{addr[3]}:#{addr[1]}"
call_callback(:AcceptCallback, sock)
block ? block.call(sock) : run(sock)
rescue Errno::ENOTCONN
@@ -179,7 +159,6 @@ module WEBrick
rescue Exception => ex
@logger.error ex
ensure
- @tokens.push(nil)
Thread.current[:WEBrickSocket] = nil
if addr
@logger.debug "close: #{addr[3]}:#{addr[1]}"
@@ -188,6 +167,7 @@ module WEBrick
end
sock.close
end
+ @tokens.push(nil)
}
end
diff --git a/lib/webrick/ssl.rb b/lib/webrick/ssl.rb
index 03bfdf4aa0..4562ba4948 100644
--- a/lib/webrick/ssl.rb
+++ b/lib/webrick/ssl.rb
@@ -14,7 +14,7 @@ module WEBrick
osslv = ::OpenSSL::OPENSSL_VERSION.split[1]
SSL = {
:ServerSoftware => "#{svrsoft} OpenSSL/#{osslv}",
- :SSLEnable => false,
+ :SSLEnable => true,
:SSLCertificate => nil,
:SSLPrivateKey => nil,
:SSLClientCA => nil,
diff --git a/lib/webrick/utils.rb b/lib/webrick/utils.rb
index cf9da6f2ce..41b54271c7 100644
--- a/lib/webrick/utils.rb
+++ b/lib/webrick/utils.rb
@@ -18,14 +18,6 @@ end
module WEBrick
module Utils
- def set_non_blocking(io)
- flag = File::NONBLOCK
- if defined?(Fcntl::F_GETFL)
- flag |= io.fcntl(Fcntl::F_GETFL)
- end
- io.fcntl(Fcntl::F_SETFL, flag)
- end
- module_function :set_non_blocking
def set_close_on_exec(io)
if defined?(Fcntl::FD_CLOEXEC)
@@ -57,9 +49,6 @@ module WEBrick
module_function :getservername
def create_listeners(address, port, logger=nil)
- unless port
- raise ArgumentError, "must specify port"
- end
res = Socket::getaddrinfo(address, port,
Socket::AF_UNSPEC, # address family
Socket::SOCK_STREAM, # socket type
@@ -69,9 +58,8 @@ module WEBrick
sockets = []
res.each{|ai|
begin
- logger.debug("TCPServer.new(#{ai[3]}, #{port})") if logger
- sock = TCPServer.new(ai[3], port)
- port = sock.addr[1] if port == 0
+ logger.debug("TCPServer.new(#{ai[3]}, #{ai[1]})") if logger
+ sock = TCPServer.new(ai[3], ai[1])
Utils::set_close_on_exec(sock)
sockets << sock
rescue => ex
diff --git a/lib/wsdl/binding.rb b/lib/wsdl/binding.rb
index 58a21d820d..e8c9d5be9d 100644
--- a/lib/wsdl/binding.rb
+++ b/lib/wsdl/binding.rb
@@ -52,7 +52,7 @@ class Binding < Info
def parse_attr(attr, value)
case attr
when NameAttrName
- @name = XSD::QName.new(targetnamespace, value.source)
+ @name = XSD::QName.new(targetnamespace, value)
when TypeAttrName
@type = value
else
diff --git a/lib/wsdl/definitions.rb b/lib/wsdl/definitions.rb
index 5235037cfe..c530220fde 100644
--- a/lib/wsdl/definitions.rb
+++ b/lib/wsdl/definitions.rb
@@ -18,16 +18,19 @@ class Definitions < Info
attr_reader :targetnamespace
attr_reader :imports
- attr_accessor :location
- attr_reader :importedschema
+ # Overrides Info#root
+ def root
+ @root
+ end
+
+ def root=(root)
+ @root = root
+ end
def initialize
super
@name = nil
@targetnamespace = nil
- @location = nil
- @importedschema = {}
-
@types = nil
@imports = []
@messages = XSD::NamedElements.new
@@ -50,19 +53,6 @@ class Definitions < Info
end
end
- def collect_attributes
- result = XSD::NamedElements.new
- if @types
- @types.schemas.each do |schema|
- result.concat(schema.collect_attributes)
- end
- end
- @imports.each do |import|
- result.concat(import.content.collect_attributes)
- end
- result
- end
-
def collect_elements
result = XSD::NamedElements.new
if @types
@@ -226,9 +216,9 @@ class Definitions < Info
def parse_attr(attr, value)
case attr
when NameAttrName
- @name = XSD::QName.new(targetnamespace, value.source)
+ @name = XSD::QName.new(@targetnamespace, value)
when TargetNamespaceAttrName
- self.targetnamespace = value.source
+ self.targetnamespace = value
else
nil
end
diff --git a/lib/wsdl/import.rb b/lib/wsdl/import.rb
index faf60871a5..ab244f6ca6 100644
--- a/lib/wsdl/import.rb
+++ b/lib/wsdl/import.rb
@@ -39,29 +39,19 @@ class Import < Info
def parse_attr(attr, value)
case attr
when NamespaceAttrName
- @namespace = value.source
+ @namespace = value
if @content
@content.targetnamespace = @namespace
end
@namespace
when LocationAttrName
- @location = URI.parse(value.source)
- if @location.relative? and !parent.location.nil? and
- !parent.location.relative?
- @location = parent.location + @location
- end
- if root.importedschema.key?(@location)
- @content = root.importedschema[@location]
- else
- root.importedschema[@location] = nil # placeholder
- @content = import(@location)
- if @content.is_a?(Definitions)
- @content.root = root
- if @namespace
- @content.targetnamespace = @namespace
- end
- end
- root.importedschema[@location] = @content
+ @location = value
+ @content = import(@location)
+ if @content.is_a?(Definitions)
+ @content.root = root
+ if @namespace
+ @content.targetnamespace = @namespace
+ end
end
@location
else
@@ -72,7 +62,7 @@ class Import < Info
private
def import(location)
- Importer.import(location, root)
+ Importer.import(location)
end
end
diff --git a/lib/wsdl/importer.rb b/lib/wsdl/importer.rb
index 481bd81b25..fac02b51a0 100644
--- a/lib/wsdl/importer.rb
+++ b/lib/wsdl/importer.rb
@@ -1,37 +1,72 @@
# WSDL4R - WSDL importer library.
-# Copyright (C) 2003, 2005 NAKAMURA, Hiroshi <nahi@ruby-lang.org>.
+# Copyright (C) 2003 NAKAMURA, Hiroshi <nahi@ruby-lang.org>.
# This program is copyrighted free software by NAKAMURA, Hiroshi. You can
# redistribute it and/or modify it under the same terms of Ruby's license;
# either the dual license version in 2003, or any later version.
-require 'wsdl/xmlSchema/importer'
+require 'wsdl/info'
require 'wsdl/parser'
+require 'soap/soap'
+require 'soap/property'
module WSDL
-class Importer < WSDL::XMLSchema::Importer
- def self.import(location, originalroot = nil)
- new.import(location, originalroot)
+class Importer
+ def self.import(location)
+ new.import(location)
end
-private
+ def initialize
+ @web_client = nil
+ end
- def parse(content, location, originalroot)
- opt = {
- :location => location,
- :originalroot => originalroot
- }
+ def import(location)
+ content = nil
+ if FileTest.exist?(location)
+ content = File.open(location).read
+ else
+ client = web_client.new(nil, "WSDL4R")
+ if opt = ::SOAP::Property.loadproperty(::SOAP::PropertyName)
+ client.proxy = opt["client.protocol.http.proxy"]
+ client.no_proxy = opt["client.protocol.http.no_proxy"]
+ end
+ client.proxy ||= ::SOAP::Env::HTTP_PROXY
+ client.no_proxy ||= ::SOAP::Env::NO_PROXY
+ content = client.get_content(location)
+ end
+ opt = {}
begin
WSDL::Parser.new(opt).parse(content)
- rescue WSDL::Parser::ParseError
- super(content, location, originalroot)
+ rescue WSDL::Parser::ParseError => orgexcn
+ begin
+ require 'wsdl/xmlSchema/parser'
+ WSDL::XMLSchema::Parser.new(opt).parse(content)
+ rescue
+ raise orgexcn
+ end
end
end
+private
+
+ def web_client
+ @web_client ||= begin
+ require 'http-access2'
+ if HTTPAccess2::VERSION < "2.0"
+ raise LoadError.new("http-access/2.0 or later is required.")
+ end
+ HTTPAccess2::Client
+ rescue LoadError
+ STDERR.puts "Loading http-access2 failed. Net/http is used." if $DEBUG
+ require 'soap/netHttpClient'
+ ::SOAP::NetHttpClient
+ end
+ @web_client
+ end
end
diff --git a/lib/wsdl/info.rb b/lib/wsdl/info.rb
index ffd90390a4..657ff5863a 100644
--- a/lib/wsdl/info.rb
+++ b/lib/wsdl/info.rb
@@ -10,22 +10,16 @@ module WSDL
class Info
- attr_accessor :root
attr_accessor :parent
attr_accessor :id
def initialize
- @root = nil
@parent = nil
@id = nil
end
- def inspect
- if self.respond_to?(:name)
- sprintf("#<%s:0x%x %s>", self.class.name, __id__, self.name)
- else
- sprintf("#<%s:0x%x>", self.class.name, __id__)
- end
+ def root
+ @parent.root
end
def parse_element(element); end # abstract
diff --git a/lib/wsdl/message.rb b/lib/wsdl/message.rb
index cecc602da3..a346708cf4 100644
--- a/lib/wsdl/message.rb
+++ b/lib/wsdl/message.rb
@@ -43,7 +43,7 @@ class Message < Info
def parse_attr(attr, value)
case attr
when NameAttrName
- @name = XSD::QName.new(parent.targetnamespace, value.source)
+ @name = XSD::QName.new(parent.targetnamespace, value)
else
nil
end
diff --git a/lib/wsdl/operation.rb b/lib/wsdl/operation.rb
index fb7f4a80f4..be28446d34 100644
--- a/lib/wsdl/operation.rb
+++ b/lib/wsdl/operation.rb
@@ -46,23 +46,21 @@ class Operation < Info
end
def input_info
- typename = input.find_message.name
- NameInfo.new(@name, typename, inputparts)
+ op_name = @name
+ optype_name = XSD::QName.new(targetnamespace, input.name ? input.name.name : @name.name)
+ NameInfo.new(op_name, optype_name, inputparts)
end
def output_info
- typename = output.find_message.name
- NameInfo.new(@name, typename, outputparts)
+ op_name = @name
+ optype_name = XSD::QName.new(targetnamespace, output.name ? output.name.name : @name.name)
+ NameInfo.new(op_name, optype_name, outputparts)
end
def inputparts
sort_parts(input.find_message.parts)
end
- def inputname
- XSD::QName.new(targetnamespace, input.name ? input.name.name : @name.name)
- end
-
def outputparts
sort_parts(output.find_message.parts)
end
@@ -97,11 +95,11 @@ class Operation < Info
def parse_attr(attr, value)
case attr
when NameAttrName
- @name = XSD::QName.new(targetnamespace, value.source)
+ @name = XSD::QName.new(targetnamespace, value)
when TypeAttrName
@type = value
when ParameterOrderAttrName
- @parameter_order = value.source.split(/\s+/)
+ @parameter_order = value.split(/\s+/)
else
nil
end
@@ -120,8 +118,9 @@ private
if result.length == 0
return parts.dup
end
- # result length can be shorter than parts's.
- # return part must not be a part of the parameterOrder.
+ if parts.length != result.length
+ raise RuntimeError.new("Incomplete prarmeterOrder list.")
+ end
result
end
end
diff --git a/lib/wsdl/operationBinding.rb b/lib/wsdl/operationBinding.rb
index c2b8cd6591..4c04a884ea 100644
--- a/lib/wsdl/operationBinding.rb
+++ b/lib/wsdl/operationBinding.rb
@@ -37,35 +37,7 @@ class OperationBinding < Info
end
def find_operation
- porttype.operations[@name] or raise RuntimeError.new("#{@name} not found")
- end
-
- def soapoperation_name
- if @soapoperation
- @soapoperation.input_info.op_name
- else
- find_operation.name
- end
- end
-
- def soapoperation_style
- style = nil
- if @soapoperation
- style = @soapoperation.operation_style
- elsif parent.soapbinding
- style = parent.soapbinding.style
- else
- raise TypeError.new("operation style definition not found")
- end
- style || :document
- end
-
- def soapaction
- if @soapoperation
- @soapoperation.soapaction
- else
- nil
- end
+ porttype.operations[@name]
end
def parse_element(element)
@@ -97,7 +69,7 @@ class OperationBinding < Info
def parse_attr(attr, value)
case attr
when NameAttrName
- @name = XSD::QName.new(targetnamespace, value.source)
+ @name = XSD::QName.new(targetnamespace, value)
else
nil
end
diff --git a/lib/wsdl/param.rb b/lib/wsdl/param.rb
index b6836b7def..06dd3beb7e 100644
--- a/lib/wsdl/param.rb
+++ b/lib/wsdl/param.rb
@@ -33,15 +33,7 @@ class Param < Info
end
def find_message
- root.message(@message) or raise RuntimeError.new("#{@message} not found")
- end
-
- def soapbody_use
- if @soapbody
- @soapbody.use || :literal
- else
- raise RuntimeError.new("soap:body not found")
- end
+ root.message(@message)
end
def parse_element(element)
@@ -69,12 +61,9 @@ class Param < Info
def parse_attr(attr, value)
case attr
when MessageAttrName
- if value.namespace.nil?
- value = XSD::QName.new(targetnamespace, value.source)
- end
@message = value
when NameAttrName
- @name = XSD::QName.new(targetnamespace, value.source)
+ @name = XSD::QName.new(targetnamespace, value)
else
nil
end
diff --git a/lib/wsdl/parser.rb b/lib/wsdl/parser.rb
index f96e96ee2a..6387911f79 100644
--- a/lib/wsdl/parser.rb
+++ b/lib/wsdl/parser.rb
@@ -1,5 +1,5 @@
# WSDL4R - WSDL XML Instance parser library.
-# Copyright (C) 2002, 2003, 2005 NAKAMURA, Hiroshi <nahi@ruby-lang.org>.
+# Copyright (C) 2002, 2003 NAKAMURA, Hiroshi <nahi@ruby-lang.org>.
# This program is copyrighted free software by NAKAMURA, Hiroshi. You can
# redistribute it and/or modify it under the same terms of Ruby's license;
@@ -53,9 +53,6 @@ public
@parser = XSD::XMLParser.create_parser(self, opt)
@parsestack = nil
@lastnode = nil
- @ignored = {}
- @location = opt[:location]
- @originalroot = opt[:originalroot]
end
def parse(string_or_readable)
@@ -99,7 +96,7 @@ public
def end_element(name)
lastframe = @parsestack.pop
unless name == lastframe.name
- raise UnexpectedElementError.new("closing element name '#{name}' does not match with opening element '#{lastframe.name}'")
+ raise UnexpectedElementError.new("Closing element name '#{ name }' does not match with opening element '#{ lastframe.name }'.")
end
decode_tag_end(lastframe.ns, lastframe.node)
@lastnode = lastframe.node
@@ -109,42 +106,42 @@ private
def decode_tag(ns, name, attrs, parent)
o = nil
- elename = ns.parse(name)
+ element = ns.parse(name)
if !parent
- if elename == DefinitionsName
- o = Definitions.parse_element(elename)
- o.location = @location
+ if element == DefinitionsName
+ o = Definitions.parse_element(element)
else
- raise UnknownElementError.new("unknown element: #{elename}")
+ raise UnknownElementError.new("Unknown element #{ element }.")
end
- o.root = @originalroot if @originalroot # o.root = o otherwise
else
- if elename == XMLSchema::AnnotationName
- # only the first annotation element is allowed for each xsd element.
- o = XMLSchema::Annotation.new
- else
- o = parent.parse_element(elename)
- end
+ o = parent.parse_element(element)
unless o
- unless @ignored.key?(elename)
- warn("ignored element: #{elename}")
- @ignored[elename] = elename
- end
+ STDERR.puts("Unknown element #{ element }.")
o = Documentation.new # which accepts any element.
end
# node could be a pseudo element. pseudo element has its own parent.
- o.root = parent.root
o.parent = parent if o.parent.nil?
end
attrs.each do |key, value|
- attr_ele = ns.parse(key, true)
- value_ele = ns.parse(value, true)
- value_ele.source = value # for recovery; value may not be a QName
- unless o.parse_attr(attr_ele, value_ele)
- unless @ignored.key?(attr_ele)
- warn("ignored attr: #{attr_ele}")
- @ignored[attr_ele] = attr_ele
- end
+ attr = unless /:/ =~ key
+ XSD::QName.new(nil, key)
+ else
+ ns.parse(key)
+ end
+ value_ele = if /:/ !~ value
+ value
+ elsif /^http:\/\// =~ value # ToDo: ugly.
+ value
+ else
+ begin
+ ns.parse(value)
+ rescue
+ value
+ end
+ end
+ unless o.parse_attr(attr, value_ele)
+ STDERR.puts("Unknown attr #{ attr }.")
+ # raise UnknownAttributeError.new("Unknown attr #{ attr }.")
end
end
o
diff --git a/lib/wsdl/part.rb b/lib/wsdl/part.rb
index 5dafd4ee73..30f71f15d9 100644
--- a/lib/wsdl/part.rb
+++ b/lib/wsdl/part.rb
@@ -37,7 +37,7 @@ class Part < Info
def parse_attr(attr, value)
case attr
when NameAttrName
- @name = value.source
+ @name = value
when ElementAttrName
@element = value
when TypeAttrName
diff --git a/lib/wsdl/port.rb b/lib/wsdl/port.rb
index 883cc3232d..e6553f1287 100644
--- a/lib/wsdl/port.rb
+++ b/lib/wsdl/port.rb
@@ -33,7 +33,7 @@ class Port < Info
end
def find_binding
- root.binding(@binding) or raise RuntimeError.new("#{@binding} not found")
+ root.binding(@binding)
end
def inputoperation_map
@@ -71,7 +71,7 @@ class Port < Info
def parse_attr(attr, value)
case attr
when NameAttrName
- @name = XSD::QName.new(targetnamespace, value.source)
+ @name = XSD::QName.new(targetnamespace, value)
when BindingAttrName
@binding = value
else
diff --git a/lib/wsdl/portType.rb b/lib/wsdl/portType.rb
index 03e37690a8..e3cf9b51ec 100644
--- a/lib/wsdl/portType.rb
+++ b/lib/wsdl/portType.rb
@@ -28,8 +28,7 @@ class PortType < Info
end
def find_binding
- root.bindings.find { |item| item.type == @name } or
- raise RuntimeError.new("#{@name} not found")
+ root.bindings.find { |item| item.type == @name }
end
def locations
@@ -62,7 +61,7 @@ class PortType < Info
def parse_attr(attr, value)
case attr
when NameAttrName
- @name = XSD::QName.new(targetnamespace, value.source)
+ @name = XSD::QName.new(targetnamespace, value)
else
nil
end
diff --git a/lib/wsdl/service.rb b/lib/wsdl/service.rb
index 652b127331..0e0843a098 100644
--- a/lib/wsdl/service.rb
+++ b/lib/wsdl/service.rb
@@ -50,7 +50,7 @@ class Service < Info
def parse_attr(attr, value)
case attr
when NameAttrName
- @name = XSD::QName.new(targetnamespace, value.source)
+ @name = XSD::QName.new(targetnamespace, value)
else
nil
end
diff --git a/lib/wsdl/soap/address.rb b/lib/wsdl/soap/address.rb
index 0b2b59caf0..e4558e4ff8 100644
--- a/lib/wsdl/soap/address.rb
+++ b/lib/wsdl/soap/address.rb
@@ -28,7 +28,7 @@ class Address < Info
def parse_attr(attr, value)
case attr
when LocationAttrName
- @location = value.source
+ @location = value
else
nil
end
diff --git a/lib/wsdl/soap/binding.rb b/lib/wsdl/soap/binding.rb
index 7e15a99701..1cfe9b9cc4 100644
--- a/lib/wsdl/soap/binding.rb
+++ b/lib/wsdl/soap/binding.rb
@@ -30,14 +30,13 @@ class Binding < Info
def parse_attr(attr, value)
case attr
when StyleAttrName
- if ["document", "rpc"].include?(value.source)
- @style = value.source.intern
+ if ["document", "rpc"].include?(value)
+ @style = value.intern
else
- raise Parser::AttributeConstraintError.new(
- "Unexpected value #{ value }.")
+ raise AttributeConstraintError.new("Unexpected value #{ value }.")
end
when TransportAttrName
- @transport = value.source
+ @transport = value
else
nil
end
diff --git a/lib/wsdl/soap/body.rb b/lib/wsdl/soap/body.rb
index 824f8121a2..47de6b1e1a 100644
--- a/lib/wsdl/soap/body.rb
+++ b/lib/wsdl/soap/body.rb
@@ -34,17 +34,13 @@ class Body < Info
def parse_attr(attr, value)
case attr
when PartsAttrName
- @parts = value.source
+ @parts = value
when UseAttrName
- if ['literal', 'encoded'].include?(value.source)
- @use = value.source.intern
- else
- raise RuntimeError.new("unknown use of soap:body: #{value.source}")
- end
+ @use = value
when EncodingStyleAttrName
- @encodingstyle = value.source
+ @encodingstyle = value
when NamespaceAttrName
- @namespace = value.source
+ @namespace = value
else
nil
end
diff --git a/lib/wsdl/soap/cgiStubCreator.rb b/lib/wsdl/soap/cgiStubCreator.rb
index 2c4dff2f62..e5b64336e7 100644
--- a/lib/wsdl/soap/cgiStubCreator.rb
+++ b/lib/wsdl/soap/cgiStubCreator.rb
@@ -1,5 +1,5 @@
# WSDL4R - Creating CGI stub code from WSDL.
-# Copyright (C) 2002, 2003, 2005 NAKAMURA, Hiroshi <nahi@ruby-lang.org>.
+# Copyright (C) 2002, 2003 NAKAMURA, Hiroshi <nahi@ruby-lang.org>.
# This program is copyrighted free software by NAKAMURA, Hiroshi. You can
# redistribute it and/or modify it under the same terms of Ruby's license;
@@ -26,7 +26,9 @@ class CGIStubCreator
end
def dump(service_name)
- warn("CGI stub can have only 1 port. Creating stub for the first port... Rests are ignored.")
+ STDERR.puts "!!! IMPORTANT !!!"
+ STDERR.puts "- CGI stub can only 1 port. Creating stub for the first port... Rests are ignored."
+ STDERR.puts "!!! IMPORTANT !!!"
port = @definitions.service(service_name).ports[0]
dump_porttype(port.porttype.name)
end
@@ -37,29 +39,24 @@ private
class_name = create_class_name(name)
methoddef, types = MethodDefCreator.new(@definitions).dump(name)
mr_creator = MappingRegistryCreator.new(@definitions)
- c1 = XSD::CodeGen::ClassDef.new(class_name)
+ c1 = ::XSD::CodeGen::ClassDef.new(class_name)
c1.def_require("soap/rpc/cgistub")
c1.def_require("soap/mapping/registry")
c1.def_const("MappingRegistry", "::SOAP::Mapping::Registry.new")
c1.def_code(mr_creator.dump(types))
c1.def_code <<-EOD
Methods = [
-#{methoddef.gsub(/^/, " ")}
+#{ methoddef.gsub(/^/, " ") }
]
EOD
- c2 = XSD::CodeGen::ClassDef.new(class_name + "App",
+ c2 = ::XSD::CodeGen::ClassDef.new(class_name + "App",
"::SOAP::RPC::CGIStub")
c2.def_method("initialize", "*arg") do
<<-EOD
super(*arg)
servant = #{class_name}.new
- #{class_name}::Methods.each do |definitions|
- opt = definitions.last
- if opt[:request_style] == :document
- @router.add_document_operation(servant, *definitions)
- else
- @router.add_rpc_operation(servant, *definitions)
- end
+ #{class_name}::Methods.each do |name_as, name, params, soapaction, ns|
+ add_method_with_namespace_as(ns, servant, name, name_as, params, soapaction)
end
self.mapping_registry = #{class_name}::MappingRegistry
self.level = Logger::Severity::ERROR
diff --git a/lib/wsdl/soap/classDefCreator.rb b/lib/wsdl/soap/classDefCreator.rb
index aeb67c0613..6c7d381932 100644
--- a/lib/wsdl/soap/classDefCreator.rb
+++ b/lib/wsdl/soap/classDefCreator.rb
@@ -1,5 +1,5 @@
# WSDL4R - Creating class definition from WSDL
-# Copyright (C) 2002, 2003, 2004 NAKAMURA, Hiroshi <nahi@ruby-lang.org>.
+# Copyright (C) 2002, 2003 NAKAMURA, Hiroshi <nahi@ruby-lang.org>.
# This program is copyrighted free software by NAKAMURA, Hiroshi. You can
# redistribute it and/or modify it under the same terms of Ruby's license;
@@ -19,292 +19,90 @@ class ClassDefCreator
include ClassDefCreatorSupport
def initialize(definitions)
- @elements = definitions.collect_elements
@simpletypes = definitions.collect_simpletypes
@complextypes = definitions.collect_complextypes
- @faulttypes = nil
- if definitions.respond_to?(:collect_faulttypes)
- @faulttypes = definitions.collect_faulttypes
- end
+ @faulttypes = definitions.collect_faulttypes
end
- def dump(type = nil)
- result = "require 'xsd/qname'\n"
- if type
- result = dump_classdef(type.name, type)
+ def dump(class_name = nil)
+ result = ""
+ if class_name
+ result = dump_classdef(class_name)
else
- str = dump_element
- unless str.empty?
- result << "\n" unless result.empty?
- result << str
- end
- str = dump_complextype
- unless str.empty?
- result << "\n" unless result.empty?
- result << str
- end
- str = dump_simpletype
- unless str.empty?
- result << "\n" unless result.empty?
- result << str
+ @complextypes.each do |type|
+ case type.compoundtype
+ when :TYPE_STRUCT
+ result << dump_classdef(type)
+ when :TYPE_ARRAY
+ result << dump_arraydef(type)
+ else
+ raise RuntimeError.new("Unknown complexContent definition...")
+ end
+ result << "\n"
end
+
+ result << @simpletypes.collect { |type|
+ dump_simpletypedef(type)
+ }.join("\n")
end
result
end
private
- def dump_element
- @elements.collect { |ele|
- if ele.local_complextype
- dump_classdef(ele.name, ele.local_complextype,
- ele.elementform == 'qualified')
- elsif ele.local_simpletype
- dump_simpletypedef(ele.name, ele.local_simpletype)
- else
- nil
- end
- }.compact.join("\n")
- end
-
- def dump_simpletype
- @simpletypes.collect { |type|
- dump_simpletypedef(type.name, type)
- }.compact.join("\n")
- end
-
- def dump_complextype
- @complextypes.collect { |type|
- case type.compoundtype
- when :TYPE_STRUCT, :TYPE_EMPTY
- dump_classdef(type.name, type)
- when :TYPE_ARRAY
- dump_arraydef(type)
- when :TYPE_SIMPLE
- dump_simpleclassdef(type)
- when :TYPE_MAP
- # mapped as a general Hash
- nil
- else
- raise RuntimeError.new(
- "unknown kind of complexContent: #{type.compoundtype}")
- end
- }.compact.join("\n")
- end
-
- def dump_simpletypedef(qname, simpletype)
- if !simpletype.restriction or simpletype.restriction.enumeration.empty?
- return nil
+ def dump_simpletypedef(simpletype)
+ qname = simpletype.name
+ if simpletype.restriction.enumeration.empty?
+ STDERR.puts("#{qname}: simpleType which is not enum type not supported.")
+ return ""
end
c = XSD::CodeGen::ModuleDef.new(create_class_name(qname))
- c.comment = "#{qname}"
- const = {}
+ c.comment = "#{ qname.namespace }"
simpletype.restriction.enumeration.each do |value|
- constname = safeconstname(value)
- const[constname] ||= 0
- if (const[constname] += 1) > 1
- constname += "_#{const[constname]}"
- end
- c.def_const(constname, ndq(value))
+ c.def_const(safeconstname(value), value.dump)
end
c.dump
end
- def dump_simpleclassdef(type_or_element)
- qname = type_or_element.name
- base = create_class_name(type_or_element.simplecontent.base)
- c = XSD::CodeGen::ClassDef.new(create_class_name(qname), base)
- c.comment = "#{qname}"
- c.dump
- end
-
- def dump_classdef(qname, typedef, qualified = false)
- if @faulttypes and @faulttypes.index(qname)
+ def dump_classdef(complextype)
+ qname = complextype.name
+ if @faulttypes.index(qname)
c = XSD::CodeGen::ClassDef.new(create_class_name(qname),
- '::StandardError')
+ "::StandardError")
else
c = XSD::CodeGen::ClassDef.new(create_class_name(qname))
end
- c.comment = "#{qname}"
- c.def_classvar('schema_type', ndq(qname.name))
- c.def_classvar('schema_ns', ndq(qname.namespace))
- c.def_classvar('schema_qualified', dq('true')) if qualified
- schema_element = []
- init_lines = ''
+ c.comment = "#{ qname.namespace }"
+ c.def_classvar("schema_type", qname.name.dump)
+ c.def_classvar("schema_ns", qname.namespace.dump)
+ init_lines = ""
params = []
- typedef.each_element do |element|
- if element.type == XSD::AnyTypeName
- type = nil
- elsif klass = element_basetype(element)
- type = klass.name
- elsif element.type
- type = create_class_name(element.type)
- else
- type = nil # means anyType.
- # do we define a class for local complexType from it's name?
- # type = create_class_name(element.name)
- # <element>
- # <complexType>
- # <seq...>
- # </complexType>
- # </element>
- end
- name = name_element(element).name
- attrname = safemethodname?(name) ? name : safemethodname(name)
+ complextype.each_element do |element|
+ name = element.name.name
varname = safevarname(name)
- c.def_attr(attrname, true, varname)
- init_lines << "@#{varname} = #{varname}\n"
- if element.map_as_array?
- params << "#{varname} = []"
- type << '[]' if type
- else
- params << "#{varname} = nil"
- end
- # nil means @@schema_ns + varname
- eleqname =
- (varname == name && element.name.namespace == qname.namespace) ?
- nil : element.name
- schema_element << [varname, eleqname, type]
+ c.def_attr(name, true, varname)
+ init_lines << "@#{ varname } = #{ varname }\n"
+ params << "#{ varname } = nil"
end
- unless typedef.attributes.empty?
- define_attribute(c, typedef.attributes)
- init_lines << "@__xmlattr = {}\n"
+ complextype.attributes.each do |attribute|
+ name = "attr_" + attribute.name
+ varname = safevarname(name)
+ c.def_attr(name, true, varname)
+ init_lines << "@#{ varname } = #{ varname }\n"
+ params << "#{ varname } = nil"
end
- c.def_classvar('schema_element',
- '[' +
- schema_element.collect { |varname, name, type|
- '[' +
- (
- if name
- varname.dump + ', [' + ndq(type) + ', ' + dqname(name) + ']'
- else
- varname.dump + ', ' + ndq(type)
- end
- ) +
- ']'
- }.join(', ') +
- ']'
- )
- c.def_method('initialize', *params) do
+ c.def_method("initialize", *params) do
init_lines
end
c.dump
end
- def element_basetype(ele)
- if klass = basetype_class(ele.type)
- klass
- elsif ele.local_simpletype
- basetype_class(ele.local_simpletype.base)
- else
- nil
- end
- end
-
- def attribute_basetype(attr)
- if klass = basetype_class(attr.type)
- klass
- elsif attr.local_simpletype
- basetype_class(attr.local_simpletype.base)
- else
- nil
- end
- end
-
- def basetype_class(type)
- return nil if type.nil?
- if simpletype = @simpletypes[type]
- basetype_mapped_class(simpletype.base)
- else
- basetype_mapped_class(type)
- end
- end
-
- def define_attribute(c, attributes)
- schema_attribute = []
- attributes.each do |attribute|
- name = name_attribute(attribute)
- if klass = attribute_basetype(attribute)
- type = klass.name
- else
- type = nil
- end
- methodname = safemethodname('xmlattr_' + name.name)
- c.def_method(methodname) do <<-__EOD__
- (@__xmlattr ||= {})[#{dqname(name)}]
- __EOD__
- end
- c.def_method(methodname + '=', 'value') do <<-__EOD__
- (@__xmlattr ||= {})[#{dqname(name)}] = value
- __EOD__
- end
- schema_attribute << [name, type]
- end
- c.def_classvar('schema_attribute',
- '{' +
- schema_attribute.collect { |name, type|
- dqname(name) + ' => ' + ndq(type)
- }.join(', ') +
- '}'
- )
- end
-
- def name_element(element)
- return element.name if element.name
- return element.ref if element.ref
- raise RuntimeError.new("cannot define name of #{element}")
- end
-
- def name_attribute(attribute)
- return attribute.name if attribute.name
- return attribute.ref if attribute.ref
- raise RuntimeError.new("cannot define name of #{attribute}")
- end
-
- DEFAULT_ITEM_NAME = XSD::QName.new(nil, 'item')
-
def dump_arraydef(complextype)
qname = complextype.name
- c = XSD::CodeGen::ClassDef.new(create_class_name(qname), '::Array')
- c.comment = "#{qname}"
- child_type = complextype.child_type
- c.def_classvar('schema_type', ndq(child_type.name))
- c.def_classvar('schema_ns', ndq(child_type.namespace))
- child_element = complextype.find_aryelement
- schema_element = []
- if child_type == XSD::AnyTypeName
- type = nil
- elsif child_element and (klass = element_basetype(child_element))
- type = klass.name
- elsif child_type
- type = create_class_name(child_type)
- else
- type = nil
- end
- if child_element
- if child_element.map_as_array?
- type << '[]' if type
- end
- child_element_name = child_element.name
- else
- child_element_name = DEFAULT_ITEM_NAME
- end
- schema_element << [child_element_name.name, child_element_name, type]
- c.def_classvar('schema_element',
- '[' +
- schema_element.collect { |varname, name, type|
- '[' +
- (
- if name
- varname.dump + ', [' + ndq(type) + ', ' + dqname(name) + ']'
- else
- varname.dump + ', ' + ndq(type)
- end
- ) +
- ']'
- }.join(', ') +
- ']'
- )
+ c = XSD::CodeGen::ClassDef.new(create_class_name(qname), "::Array")
+ c.comment = "#{ qname.namespace }"
+ c.def_classvar("schema_type", qname.name.dump)
+ c.def_classvar("schema_ns", qname.namespace.dump)
c.dump
end
end
diff --git a/lib/wsdl/soap/classDefCreatorSupport.rb b/lib/wsdl/soap/classDefCreatorSupport.rb
index 8f335653c8..dbcc55f7b9 100644
--- a/lib/wsdl/soap/classDefCreatorSupport.rb
+++ b/lib/wsdl/soap/classDefCreatorSupport.rb
@@ -21,7 +21,7 @@ module ClassDefCreatorSupport
def create_class_name(qname)
if klass = basetype_mapped_class(qname)
- ::SOAP::Mapping::DefaultRegistry.find_mapped_obj_class(klass).name
+ ::SOAP::Mapping::DefaultRegistry.find_mapped_obj_class(klass.name)
else
safeconstname(qname.name)
end
@@ -59,22 +59,6 @@ __EOD__
str
end
- def dq(ele)
- ele.dump
- end
-
- def ndq(ele)
- ele.nil? ? 'nil' : dq(ele)
- end
-
- def sym(ele)
- ':' + ele
- end
-
- def dqname(qname)
- qname.dump
- end
-
private
def dump_inout_type(param)
@@ -82,14 +66,10 @@ private
message = param.find_message
params = ""
message.parts.each do |part|
+ next unless part.type
name = safevarname(part.name)
- if part.type
- typename = safeconstname(part.type.name)
- params << add_at("# #{name}", "#{typename} - #{part.type}\n", 20)
- elsif part.element
- typename = safeconstname(part.element.name)
- params << add_at("# #{name}", "#{typename} - #{part.element}\n", 20)
- end
+ typename = safeconstname(part.type.name)
+ params << add_at("# #{name}", "#{typename} - #{part.type}\n", 20)
end
unless params.empty?
return params
diff --git a/lib/wsdl/soap/clientSkeltonCreator.rb b/lib/wsdl/soap/clientSkeltonCreator.rb
index 916f0d4dc0..9c538dd612 100644
--- a/lib/wsdl/soap/clientSkeltonCreator.rb
+++ b/lib/wsdl/soap/clientSkeltonCreator.rb
@@ -42,8 +42,8 @@ private
endpoint_url = ARGV.shift
obj = #{ drv_name }.new(endpoint_url)
-# run ruby with -d to see SOAP wiredumps.
-obj.wiredump_dev = STDERR if $DEBUG
+# Uncomment the below line to see SOAP wiredumps.
+# obj.wiredump_dev = STDERR
__EOD__
@definitions.porttype(name).operations.each do |operation|
@@ -62,7 +62,7 @@ __EOD__
def dump_input_init(input)
result = input.find_message.parts.collect { |part|
- safevarname(part.name)
+ "#{ uncapitalize(part.name) }"
}.join(" = ")
if result.empty?
""
diff --git a/lib/wsdl/soap/complexType.rb b/lib/wsdl/soap/complexType.rb
index b2e13d0564..34fc18f1a4 100644
--- a/lib/wsdl/soap/complexType.rb
+++ b/lib/wsdl/soap/complexType.rb
@@ -7,7 +7,6 @@
require 'wsdl/xmlSchema/complexType'
-require 'soap/mapping'
module WSDL
@@ -21,28 +20,15 @@ class ComplexType < Info
def check_type
if content
- if attributes.empty? and
- content.elements.size == 1 and content.elements[0].maxoccurs != '1'
- if name == ::SOAP::Mapping::MapQName
- :TYPE_MAP
- else
- :TYPE_ARRAY
- end
+ if content.elements.size == 1 and content.elements[0].maxoccurs != 1
+ :TYPE_ARRAY
else
:TYPE_STRUCT
end
- elsif complexcontent
- if complexcontent.base == ::SOAP::ValueArrayName
- :TYPE_ARRAY
- else
- complexcontent.basetype.check_type
- end
- elsif simplecontent
- :TYPE_SIMPLE
- elsif !attributes.empty?
- :TYPE_STRUCT
- else # empty complexType definition (seen in partner.wsdl of salesforce)
- :TYPE_EMPTY
+ elsif complexcontent and complexcontent.base == ::SOAP::ValueArrayName
+ :TYPE_ARRAY
+ else
+ raise NotImplementedError.new("Unknown kind of complexType.")
end
end
@@ -53,28 +39,18 @@ class ComplexType < Info
ele.type
elsif ele = find_element_by_name(name.name)
ele.type
+ else
+ nil
end
when :TYPE_ARRAY
@contenttype ||= content_arytype
- when :TYPE_MAP
- item_ele = find_element_by_name("item") or
- raise RuntimeError.new("'item' element not found in Map definition.")
- content = item_ele.local_complextype or
- raise RuntimeError.new("No complexType definition for 'item'.")
- if ele = content.find_element(name)
- ele.type
- elsif ele = content.find_element_by_name(name.name)
- ele.type
- end
- else
- raise NotImplementedError.new("Unknown kind of complexType.")
end
end
def child_defined_complextype(name)
ele = nil
case compoundtype
- when :TYPE_STRUCT, :TYPE_MAP
+ when :TYPE_STRUCT
unless ele = find_element(name)
if name.namespace.nil?
ele = find_element_by_name(name.name)
@@ -105,45 +81,15 @@ class ComplexType < Info
return attribute.arytype
end
end
- if check_array_content(complexcontent.content)
- return element_simpletype(complexcontent.content.elements[0])
- end
- elsif check_array_content(content)
- return element_simpletype(content.elements[0])
- end
- raise RuntimeError.new("Assert: Unknown array definition.")
- end
-
- def find_aryelement
- unless compoundtype == :TYPE_ARRAY
- raise RuntimeError.new("Assert: not for array")
- end
- if complexcontent
- if check_array_content(complexcontent.content)
- return complexcontent.content.elements[0]
- end
- elsif check_array_content(content)
- return content.elements[0]
- end
- nil # use default item name
- end
-
-private
-
- def element_simpletype(element)
- if element.type
- element.type
- elsif element.local_simpletype
- element.local_simpletype.base
+ elsif content.elements.size == 1 and content.elements[0].maxoccurs != 1
+ return content.elements[0].type
else
- nil
+ raise RuntimeError.new("Assert: Unknown array definition.")
end
+ nil
end
- def check_array_content(content)
- content and content.elements.size == 1 and
- content.elements[0].maxoccurs != '1'
- end
+private
def content_arytype
if arytype = find_arytype
diff --git a/lib/wsdl/soap/data.rb b/lib/wsdl/soap/data.rb
index 48512d3751..23aaff83b5 100644
--- a/lib/wsdl/soap/data.rb
+++ b/lib/wsdl/soap/data.rb
@@ -11,7 +11,6 @@ require 'wsdl/soap/definitions'
require 'wsdl/soap/binding'
require 'wsdl/soap/operation'
require 'wsdl/soap/body'
-require 'wsdl/soap/element'
require 'wsdl/soap/header'
require 'wsdl/soap/headerfault'
require 'wsdl/soap/fault'
diff --git a/lib/wsdl/soap/definitions.rb b/lib/wsdl/soap/definitions.rb
index b014d5af6b..2f6e7e19f0 100644
--- a/lib/wsdl/soap/definitions.rb
+++ b/lib/wsdl/soap/definitions.rb
@@ -1,5 +1,5 @@
# WSDL4R - WSDL additional definitions for SOAP.
-# Copyright (C) 2002-2005 NAKAMURA, Hiroshi <nahi@ruby-lang.org>.
+# Copyright (C) 2002, 2003 NAKAMURA, Hiroshi <nahi@ruby-lang.org>.
# This program is copyrighted free software by NAKAMURA, Hiroshi. You can
# redistribute it and/or modify it under the same terms of Ruby's license;
@@ -77,13 +77,13 @@ class Definitions < Info
def collect_faulttypes
result = []
- collect_fault_messages.each do |name|
- faultparts = message(name).parts
- if faultparts.size != 1
- raise RuntimeError.new("expecting fault message to have only 1 part")
+ collect_fault_messages.each do |message|
+ parts = message(message).parts
+ if parts.size != 1
+ raise RuntimeError.new("Expecting fault message to have only 1 part.")
end
- if result.index(faultparts[0].type).nil?
- result << faultparts[0].type
+ if result.index(parts[0].type).nil?
+ result << parts[0].type
end
end
result
@@ -111,13 +111,13 @@ private
if op_bind_rpc?(op_bind)
operation = op_bind.find_operation
if op_bind.input
- type = XMLSchema::ComplexType.new(op_bind.soapoperation_name)
+ type = XMLSchema::ComplexType.new(operation_input_name(operation))
message = messages[operation.input.message]
type.sequence_elements = elements_from_message(message)
types << type
end
if op_bind.output
- type = XMLSchema::ComplexType.new(operation.outputname)
+ type = XMLSchema::ComplexType.new(operation_output_name(operation))
message = messages[operation.output.message]
type.sequence_elements = elements_from_message(message)
types << type
@@ -127,20 +127,23 @@ private
types
end
+ def operation_input_name(operation)
+ operation.input.name || operation.name
+ end
+
+ def operation_output_name(operation)
+ operation.output.name ||
+ XSD::QName.new(operation.name.namespace, operation.name.name + "Response")
+ end
+
def op_bind_rpc?(op_bind)
- op_bind.soapoperation_style == :rpc
+ op_bind.soapoperation and op_bind.soapoperation.operation_style == :rpc
end
def elements_from_message(message)
message.parts.collect { |part|
- if part.element
- collect_elements[part.element]
- elsif part.name.nil? or part.type.nil?
- raise RuntimeError.new("part of a message must be an element or typed")
- else
- qname = XSD::QName.new(nil, part.name)
- XMLSchema::Element.new(qname, part.type)
- end
+ qname = XSD::QName.new(nil, part.name)
+ XMLSchema::Element.new(qname, part.type)
}
end
end
diff --git a/lib/wsdl/soap/driverCreator.rb b/lib/wsdl/soap/driverCreator.rb
index eba7c158a2..50be8ed1dc 100644
--- a/lib/wsdl/soap/driverCreator.rb
+++ b/lib/wsdl/soap/driverCreator.rb
@@ -1,5 +1,5 @@
# WSDL4R - Creating driver code from WSDL.
-# Copyright (C) 2002, 2003, 2005 NAKAMURA, Hiroshi <nahi@ruby-lang.org>.
+# Copyright (C) 2002, 2003 NAKAMURA, Hiroshi <nahi@ruby-lang.org>.
# This program is copyrighted free software by NAKAMURA, Hiroshi. You can
# redistribute it and/or modify it under the same terms of Ruby's license;
@@ -46,17 +46,16 @@ private
methoddef, types = MethodDefCreator.new(@definitions).dump(name)
mr_creator = MappingRegistryCreator.new(@definitions)
binding = @definitions.bindings.find { |item| item.type == name }
- return '' unless binding.soapbinding # not a SOAP binding
- address = @definitions.porttype(name).locations[0]
+ addresses = @definitions.porttype(name).locations
- c = XSD::CodeGen::ClassDef.new(class_name, "::SOAP::RPC::Driver")
+ c = ::XSD::CodeGen::ClassDef.new(class_name, "::SOAP::RPC::Driver")
c.def_require("soap/rpc/driver")
c.def_const("MappingRegistry", "::SOAP::Mapping::Registry.new")
- c.def_const("DefaultEndpointUrl", ndq(address))
+ c.def_const("DefaultEndpointUrl", addresses[0].dump)
c.def_code(mr_creator.dump(types))
c.def_code <<-EOD
Methods = [
-#{methoddef.gsub(/^/, " ")}
+#{ methoddef.gsub(/^/, " ") }
]
EOD
c.def_method("initialize", "endpoint_url = nil") do
@@ -69,20 +68,10 @@ Methods = [
end
c.def_privatemethod("init_methods") do
<<-EOD
- Methods.each do |definitions|
- opt = definitions.last
- if opt[:request_style] == :document
- add_document_operation(*definitions)
- else
- add_rpc_operation(*definitions)
- qname = definitions[0]
- name = definitions[2]
- if qname.name != name and qname.name.capitalize == name.capitalize
- ::SOAP::Mapping.define_singleton_method(self, qname.name) do |*arg|
- __send__(name, *arg)
- end
- end
- end
+ Methods.each do |name_as, name, params, soapaction, namespace|
+ qname = ::XSD::QName.new(namespace, name_as)
+ @proxy.add_method(qname, soapaction, name, params)
+ add_rpc_method_interface(name, params)
end
EOD
end
diff --git a/lib/wsdl/soap/element.rb b/lib/wsdl/soap/element.rb
deleted file mode 100644
index 0fa6017c5b..0000000000
--- a/lib/wsdl/soap/element.rb
+++ /dev/null
@@ -1,28 +0,0 @@
-# WSDL4R - XMLSchema element definition for WSDL.
-# Copyright (C) 2004 NAKAMURA, Hiroshi <nahi@ruby-lang.org>.
-
-# This program is copyrighted free software by NAKAMURA, Hiroshi. You can
-# redistribute it and/or modify it under the same terms of Ruby's license;
-# either the dual license version in 2003, or any later version.
-
-
-require 'wsdl/xmlSchema/element'
-
-
-module WSDL
-module XMLSchema
-
-
-class Element < Info
- def map_as_array?
- maxoccurs != '1'
- end
-
- def attributes
- @local_complextype.attributes
- end
-end
-
-
-end
-end
diff --git a/lib/wsdl/soap/fault.rb b/lib/wsdl/soap/fault.rb
index 2862b659ab..abd3cbe3dd 100644
--- a/lib/wsdl/soap/fault.rb
+++ b/lib/wsdl/soap/fault.rb
@@ -27,10 +27,6 @@ class Fault < Info
@namespace = nil
end
- def targetnamespace
- parent.targetnamespace
- end
-
def parse_element(element)
nil
end
@@ -38,13 +34,13 @@ class Fault < Info
def parse_attr(attr, value)
case attr
when NameAttrName
- @name = XSD::QName.new(targetnamespace, value.source)
+ @name = value
when UseAttrName
- @use = value.source
+ @use = value
when EncodingStyleAttrName
- @encodingstyle = value.source
+ @encodingstyle = value
when NamespaceAttrName
- @namespace = value.source
+ @namespace = value
else
nil
end
diff --git a/lib/wsdl/soap/header.rb b/lib/wsdl/soap/header.rb
index 8d7c4e9d70..f1dd69eafb 100644
--- a/lib/wsdl/soap/header.rb
+++ b/lib/wsdl/soap/header.rb
@@ -32,12 +32,8 @@ class Header < Info
@headerfault = nil
end
- def targetnamespace
- parent.targetnamespace
- end
-
def find_message
- root.message(@message) or raise RuntimeError.new("#{@message} not found")
+ root.message(@message)
end
def find_part
@@ -46,7 +42,7 @@ class Header < Info
return part
end
end
- raise RuntimeError.new("#{@part} not found")
+ nil
end
def parse_element(element)
@@ -63,18 +59,15 @@ class Header < Info
def parse_attr(attr, value)
case attr
when MessageAttrName
- if value.namespace.nil?
- value = XSD::QName.new(targetnamespace, value.source)
- end
@message = value
when PartAttrName
- @part = value.source
+ @part = value
when UseAttrName
- @use = value.source
+ @use = value
when EncodingStyleAttrName
- @encodingstyle = value.source
+ @encodingstyle = value
when NamespaceAttrName
- @namespace = value.source
+ @namespace = value
else
nil
end
diff --git a/lib/wsdl/soap/headerfault.rb b/lib/wsdl/soap/headerfault.rb
index d6b14f2646..a6e86661c2 100644
--- a/lib/wsdl/soap/headerfault.rb
+++ b/lib/wsdl/soap/headerfault.rb
@@ -38,13 +38,13 @@ class HeaderFault < Info
when MessageAttrName
@message = value
when PartAttrName
- @part = value.source
+ @part = value
when UseAttrName
- @use = value.source
+ @use = value
when EncodingStyleAttrName
- @encodingstyle = value.source
+ @encodingstyle = value
when NamespaceAttrName
- @namespace = value.source
+ @namespace = value
else
nil
end
diff --git a/lib/wsdl/soap/mappingRegistryCreator.rb b/lib/wsdl/soap/mappingRegistryCreator.rb
index 8669339ce4..d3b28f47e0 100644
--- a/lib/wsdl/soap/mappingRegistryCreator.rb
+++ b/lib/wsdl/soap/mappingRegistryCreator.rb
@@ -1,5 +1,5 @@
# WSDL4R - Creating MappingRegistry code from WSDL.
-# Copyright (C) 2002, 2003, 2005 NAKAMURA, Hiroshi <nahi@ruby-lang.org>.
+# Copyright (C) 2002, 2003 NAKAMURA, Hiroshi <nahi@ruby-lang.org>.
# This program is copyrighted free software by NAKAMURA, Hiroshi. You can
# redistribute it and/or modify it under the same terms of Ruby's license;
@@ -38,7 +38,7 @@ class MappingRegistryCreator
end
end
end
- end
+ end
return map
end
@@ -51,10 +51,8 @@ private
dump_struct_typemap(definedtype)
when :TYPE_ARRAY
dump_array_typemap(definedtype)
- when :TYPE_MAP, :TYPE_EMPTY
- nil
else
- raise NotImplementedError.new("must not reach here")
+ raise NotImplementedError.new("Must not reach here.")
end
end
end
@@ -63,10 +61,10 @@ private
ele = definedtype.name
return <<__EOD__
MappingRegistry.set(
- #{create_class_name(ele)},
+ #{ create_class_name(ele) },
::SOAP::SOAPStruct,
::SOAP::Mapping::Registry::TypedStructFactory,
- { :type => #{dqname(ele)} }
+ { :type => ::XSD::QName.new("#{ ele.namespace }", "#{ ele.name }") }
)
__EOD__
end
@@ -78,10 +76,10 @@ __EOD__
@types << type
return <<__EOD__
MappingRegistry.set(
- #{create_class_name(ele)},
+ #{ create_class_name(ele) },
::SOAP::SOAPArray,
::SOAP::Mapping::Registry::TypedArrayFactory,
- { :type => #{dqname(type)} }
+ { :type => ::XSD::QName.new("#{ type.namespace }", "#{ type.name }") }
)
__EOD__
end
diff --git a/lib/wsdl/soap/methodDefCreator.rb b/lib/wsdl/soap/methodDefCreator.rb
index f3ffadbe69..eded972cdc 100644
--- a/lib/wsdl/soap/methodDefCreator.rb
+++ b/lib/wsdl/soap/methodDefCreator.rb
@@ -1,5 +1,5 @@
# WSDL4R - Creating driver code from WSDL.
-# Copyright (C) 2002, 2003, 2005 NAKAMURA, Hiroshi <nahi@ruby-lang.org>.
+# Copyright (C) 2002, 2003 NAKAMURA, Hiroshi <nahi@ruby-lang.org>.
# This program is copyrighted free software by NAKAMURA, Hiroshi. You can
# redistribute it and/or modify it under the same terms of Ruby's license;
@@ -8,7 +8,6 @@
require 'wsdl/info'
require 'wsdl/soap/classDefCreatorSupport'
-require 'soap/rpc/element'
module WSDL
@@ -25,162 +24,93 @@ class MethodDefCreator
@simpletypes = @definitions.collect_simpletypes
@complextypes = @definitions.collect_complextypes
@elements = @definitions.collect_elements
- @types = []
+ @types = nil
end
def dump(porttype)
- @types.clear
+ @types = []
result = ""
operations = @definitions.porttype(porttype).operations
binding = @definitions.porttype_binding(porttype)
operations.each do |operation|
op_bind = binding.operations[operation.name]
- next unless op_bind # no binding is defined
- next unless op_bind.soapoperation # not a SOAP operation binding
result << ",\n" unless result.empty?
result << dump_method(operation, op_bind).chomp
end
return result, @types
end
- def collect_rpcparameter(operation)
- result = operation.inputparts.collect { |part|
- collect_type(part.type)
- param_set(::SOAP::RPC::SOAPMethod::IN, part.name, rpcdefinedtype(part))
- }
- outparts = operation.outputparts
- if outparts.size > 0
- retval = outparts[0]
- collect_type(retval.type)
- result << param_set(::SOAP::RPC::SOAPMethod::RETVAL, retval.name,
- rpcdefinedtype(retval))
- cdr(outparts).each { |part|
- collect_type(part.type)
- result << param_set(::SOAP::RPC::SOAPMethod::OUT, part.name,
- rpcdefinedtype(part))
- }
- end
- result
- end
-
- def collect_documentparameter(operation)
- param = []
- operation.inputparts.each do |input|
- param << param_set(::SOAP::RPC::SOAPMethod::IN, input.name,
- documentdefinedtype(input), elementqualified(input))
- end
- operation.outputparts.each do |output|
- param << param_set(::SOAP::RPC::SOAPMethod::OUT, output.name,
- documentdefinedtype(output), elementqualified(output))
- end
- param
- end
-
private
def dump_method(operation, binding)
name = safemethodname(operation.name.name)
name_as = operation.name.name
- style = binding.soapoperation_style
- inputuse = binding.input.soapbody_use
- outputuse = binding.output.soapbody_use
+ params = collect_parameter(operation)
+ soapaction = binding.soapoperation.soapaction
namespace = binding.input.soapbody.namespace
- if style == :rpc
- qname = XSD::QName.new(namespace, name_as)
- paramstr = param2str(collect_rpcparameter(operation))
- else
- qname = nil
- paramstr = param2str(collect_documentparameter(operation))
- end
+ paramstr = param2str(params)
if paramstr.empty?
paramstr = '[]'
else
- paramstr = "[ " << paramstr.split(/\r?\n/).join("\n ") << " ]"
+ paramstr = "[\n" << paramstr.gsub(/^/, ' ') << "\n ]"
end
- definitions = <<__EOD__
-#{ndq(binding.soapaction)},
- #{dq(name)},
- #{paramstr},
- { :request_style => #{sym(style.id2name)}, :request_use => #{sym(inputuse.id2name)},
- :response_style => #{sym(style.id2name)}, :response_use => #{sym(outputuse.id2name)} }
-__EOD__
- if style == :rpc
- return <<__EOD__
-[ #{qname.dump},
- #{definitions}]
-__EOD__
- else
- return <<__EOD__
-[ #{definitions}]
+ return <<__EOD__
+[#{ dq(name_as) }, #{ dq(name) },
+ #{ paramstr },
+ #{ soapaction ? dq(soapaction) : "nil" }, #{ dq(namespace) }
+]
__EOD__
+ end
+
+ def collect_parameter(operation)
+ result = operation.inputparts.collect { |part|
+ collect_type(part.type)
+ param_set('in', definedtype(part), part.name)
+ }
+ outparts = operation.outputparts
+ if outparts.size > 0
+ retval = outparts[0]
+ collect_type(retval.type)
+ result << param_set('retval', definedtype(retval), retval.name)
+ cdr(outparts).each { |part|
+ collect_type(part.type)
+ result << param_set('out', definedtype(part), part.name)
+ }
end
+ result
end
- def rpcdefinedtype(part)
+ def definedtype(part)
if mapped = basetype_mapped_class(part.type)
['::' + mapped.name]
+ elsif definedelement = @elements[part.element]
+ raise RuntimeError.new("Part: #{part.name} should be typed for RPC service for now.")
elsif definedtype = @simpletypes[part.type]
['::' + basetype_mapped_class(definedtype.base).name]
- elsif definedtype = @elements[part.element]
- #['::SOAP::SOAPStruct', part.element.namespace, part.element.name]
- ['nil', part.element.namespace, part.element.name]
elsif definedtype = @complextypes[part.type]
case definedtype.compoundtype
- when :TYPE_STRUCT, :TYPE_EMPTY # ToDo: empty should be treated as void.
- type = create_class_name(part.type)
- [type, part.type.namespace, part.type.name]
- when :TYPE_MAP
- [Hash.name, part.type.namespace, part.type.name]
+ when :TYPE_STRUCT
+ ['::SOAP::SOAPStruct', part.type.namespace, part.type.name]
when :TYPE_ARRAY
arytype = definedtype.find_arytype || XSD::AnyTypeName
ns = arytype.namespace
name = arytype.name.sub(/\[(?:,)*\]$/, '')
- type = create_class_name(XSD::QName.new(ns, name))
- [type + '[]', ns, name]
+ ['::SOAP::SOAPArray', ns, name]
else
- raise NotImplementedError.new("must not reach here")
+ raise NotImplementedError.new("Must not reach here.")
end
else
- raise RuntimeError.new("part: #{part.name} cannot be resolved")
- end
- end
-
- def documentdefinedtype(part)
- if mapped = basetype_mapped_class(part.type)
- ['::' + mapped.name, nil, part.name]
- elsif definedtype = @simpletypes[part.type]
- ['::' + basetype_mapped_class(definedtype.base).name, nil, part.name]
- elsif definedtype = @elements[part.element]
- ['::SOAP::SOAPElement', part.element.namespace, part.element.name]
- elsif definedtype = @complextypes[part.type]
- ['::SOAP::SOAPElement', part.type.namespace, part.type.name]
- else
- raise RuntimeError.new("part: #{part.name} cannot be resolved")
- end
- end
-
- def elementqualified(part)
- if mapped = basetype_mapped_class(part.type)
- false
- elsif definedtype = @simpletypes[part.type]
- false
- elsif definedtype = @elements[part.element]
- definedtype.elementform == 'qualified'
- elsif definedtype = @complextypes[part.type]
- false
- else
- raise RuntimeError.new("part: #{part.name} cannot be resolved")
+ raise RuntimeError.new("Part: #{part.name} cannot be resolved.")
end
end
- def param_set(io_type, name, type, ele = nil)
- [io_type, name, type, ele]
+ def param_set(io_type, type, name)
+ [io_type, type, name]
end
def collect_type(type)
# ignore inline type definition.
return if type.nil?
- return if @types.include?(type)
@types << type
return unless @complextypes[type]
@complextypes[type].each_element do |element|
@@ -190,30 +120,20 @@ __EOD__
def param2str(params)
params.collect { |param|
- io, name, type, ele = param
- unless ele.nil?
- "[#{dq(io)}, #{dq(name)}, #{type2str(type)}, #{ele2str(ele)}]"
- else
- "[#{dq(io)}, #{dq(name)}, #{type2str(type)}]"
- end
+ "[#{ dq(param[0]) }, #{ dq(param[2]) }, #{ type2str(param[1]) }]"
}.join(",\n")
end
def type2str(type)
if type.size == 1
- "[#{dq(type[0])}]"
+ "[#{ type[0] }]"
else
- "[#{dq(type[0])}, #{ndq(type[1])}, #{dq(type[2])}]"
+ "[#{ type[0] }, #{ dq(type[1]) }, #{ dq(type[2]) }]"
end
end
- def ele2str(ele)
- qualified = ele
- if qualified
- "true"
- else
- "false"
- end
+ def dq(ele)
+ "\"" << ele << "\""
end
def cdr(ary)
diff --git a/lib/wsdl/soap/operation.rb b/lib/wsdl/soap/operation.rb
index 502d34a07d..bb49f2099c 100644
--- a/lib/wsdl/soap/operation.rb
+++ b/lib/wsdl/soap/operation.rb
@@ -50,14 +50,13 @@ class Operation < Info
def parse_attr(attr, value)
case attr
when StyleAttrName
- if ["document", "rpc"].include?(value.source)
- @style = value.source.intern
+ if ["document", "rpc"].include?(value)
+ @style = value.intern
else
- raise Parser::AttributeConstraintError.new(
- "Unexpected value #{ value }.")
+ raise AttributeConstraintError.new("Unexpected value #{ value }.")
end
when SOAPActionAttrName
- @soapaction = value.source
+ @soapaction = value
else
nil
end
@@ -101,7 +100,8 @@ private
"EncodingStyle '#{ soapbody.encodingstyle }' not supported.")
end
if soapbody.namespace
- op_name = XSD::QName.new(soapbody.namespace, op_name.name)
+ op_name = op_name.dup
+ op_name.namespace = soapbody.namespace
end
if soapbody.parts
target = soapbody.parts.split(/\s+/)
@@ -113,7 +113,8 @@ private
end
faultpart = nil
- OperationInfo.new(operation_style, op_name, optype_name, headerparts, bodyparts, faultpart, parent.soapaction)
+ soapaction = parent.soapoperation.soapaction
+ OperationInfo.new(operation_style, op_name, optype_name, headerparts, bodyparts, faultpart, soapaction)
end
end
diff --git a/lib/wsdl/soap/servantSkeltonCreator.rb b/lib/wsdl/soap/servantSkeltonCreator.rb
index 88294ffed8..bf293949b8 100644
--- a/lib/wsdl/soap/servantSkeltonCreator.rb
+++ b/lib/wsdl/soap/servantSkeltonCreator.rb
@@ -1,5 +1,5 @@
# WSDL4R - Creating servant skelton code from WSDL.
-# Copyright (C) 2002, 2003, 2005 NAKAMURA, Hiroshi <nahi@ruby-lang.org>.
+# Copyright (C) 2002, 2003 NAKAMURA, Hiroshi <nahi@ruby-lang.org>.
# This program is copyrighted free software by NAKAMURA, Hiroshi. You can
# redistribute it and/or modify it under the same terms of Ruby's license;
@@ -17,7 +17,7 @@ module SOAP
class ServantSkeltonCreator
include ClassDefCreatorSupport
- include XSD::CodeGen::GenSupport
+ include ::XSD::CodeGen::GenSupport
attr_reader :definitions
@@ -42,19 +42,17 @@ private
def dump_porttype(name)
class_name = create_class_name(name)
- c = XSD::CodeGen::ClassDef.new(class_name)
+ c = ::XSD::CodeGen::ClassDef.new(class_name)
operations = @definitions.porttype(name).operations
operations.each do |operation|
- name = safemethodname(operation.name.name)
+ name = operation.name.name
input = operation.input
- params = input.find_message.parts.collect { |part|
- safevarname(part.name)
- }
- m = XSD::CodeGen::MethodDef.new(name, params) do <<-EOD
- p [#{params.join(", ")}]
- raise NotImplementedError.new
- EOD
- end
+ m = ::XSD::CodeGen::MethodDef.new(name,
+ input.find_message.parts.collect { |part| safevarname(part.name) }) do
+ <<-EOD
+ raise NotImplementedError.new
+ EOD
+ end
m.comment = dump_method_signature(operation)
c.add_method(m)
end
diff --git a/lib/wsdl/soap/standaloneServerStubCreator.rb b/lib/wsdl/soap/standaloneServerStubCreator.rb
index 0b751b5153..34bcfdbba9 100644
--- a/lib/wsdl/soap/standaloneServerStubCreator.rb
+++ b/lib/wsdl/soap/standaloneServerStubCreator.rb
@@ -1,5 +1,5 @@
# WSDL4R - Creating standalone server stub code from WSDL.
-# Copyright (C) 2002, 2003, 2005 NAKAMURA, Hiroshi <nahi@ruby-lang.org>.
+# Copyright (C) 2002, 2003 NAKAMURA, Hiroshi <nahi@ruby-lang.org>.
# This program is copyrighted free software by NAKAMURA, Hiroshi. You can
# redistribute it and/or modify it under the same terms of Ruby's license;
@@ -26,8 +26,10 @@ class StandaloneServerStubCreator
end
def dump(service_name)
- warn("- Standalone stub can have only 1 port for now. So creating stub for the first port and rests are ignored.")
- warn("- Standalone server stub ignores port location defined in WSDL. Location is http://localhost:10080/ by default. Generated client from WSDL must be configured to point this endpoint manually.")
+ STDERR.puts "!!! IMPORTANT !!!"
+ STDERR.puts "- Standalone stub can have only 1 port for now. So creating stub for the first port and rests are ignored."
+ STDERR.puts "- Standalone server stub ignores port location defined in WSDL. Location is http://localhost:10080/ by default. Generated client from WSDL must be configured to point this endpoint by hand."
+ STDERR.puts "!!! IMPORTANT !!!"
port = @definitions.service(service_name).ports[0]
dump_porttype(port.porttype.name)
end
@@ -39,29 +41,25 @@ private
methoddef, types = MethodDefCreator.new(@definitions).dump(name)
mr_creator = MappingRegistryCreator.new(@definitions)
- c1 = XSD::CodeGen::ClassDef.new(class_name)
+ c1 = ::XSD::CodeGen::ClassDef.new(class_name)
c1.def_require("soap/rpc/standaloneServer")
c1.def_require("soap/mapping/registry")
c1.def_const("MappingRegistry", "::SOAP::Mapping::Registry.new")
c1.def_code(mr_creator.dump(types))
c1.def_code <<-EOD
Methods = [
-#{methoddef.gsub(/^/, " ")}
+#{ methoddef.gsub(/^/, " ") }
]
EOD
- c2 = XSD::CodeGen::ClassDef.new(class_name + "App",
+ c2 = ::XSD::CodeGen::ClassDef.new(class_name + "App",
"::SOAP::RPC::StandaloneServer")
c2.def_method("initialize", "*arg") do
<<-EOD
super(*arg)
servant = #{class_name}.new
- #{class_name}::Methods.each do |definitions|
- opt = definitions.last
- if opt[:request_style] == :document
- @router.add_document_operation(servant, *definitions)
- else
- @router.add_rpc_operation(servant, *definitions)
- end
+ #{class_name}::Methods.each do |name_as, name, params, soapaction, ns|
+ qname = XSD::QName.new(ns, name_as)
+ @soaplet.app_scope_router.add_method(servant, qname, soapaction, name, params)
end
self.mapping_registry = #{class_name}::MappingRegistry
EOD
@@ -70,11 +68,7 @@ Methods = [
if $0 == __FILE__
# Change listen port.
- server = #{class_name}App.new('app', nil, '0.0.0.0', 10080)
- trap(:INT) do
- server.shutdown
- end
- server.start
+ #{class_name}App.new('app', nil, '0.0.0.0', 10080).start
end
EOD
end
diff --git a/lib/wsdl/soap/wsdl2ruby.rb b/lib/wsdl/soap/wsdl2ruby.rb
deleted file mode 100644
index 16b05fb032..0000000000
--- a/lib/wsdl/soap/wsdl2ruby.rb
+++ /dev/null
@@ -1,176 +0,0 @@
-# WSDL4R - WSDL to ruby mapping library.
-# Copyright (C) 2002-2005 NAKAMURA, Hiroshi <nahi@ruby-lang.org>.
-
-# This program is copyrighted free software by NAKAMURA, Hiroshi. You can
-# redistribute it and/or modify it under the same terms of Ruby's license;
-# either the dual license version in 2003, or any later version.
-
-
-require 'logger'
-require 'xsd/qname'
-require 'wsdl/importer'
-require 'wsdl/soap/classDefCreator'
-require 'wsdl/soap/servantSkeltonCreator'
-require 'wsdl/soap/driverCreator'
-require 'wsdl/soap/clientSkeltonCreator'
-require 'wsdl/soap/standaloneServerStubCreator'
-require 'wsdl/soap/cgiStubCreator'
-
-
-module WSDL
-module SOAP
-
-
-class WSDL2Ruby
- attr_accessor :location
- attr_reader :opt
- attr_accessor :logger
- attr_accessor :basedir
-
- def run
- unless @location
- raise RuntimeError, "WSDL location not given"
- end
- @wsdl = import(@location)
- @name = @wsdl.name ? @wsdl.name.name : 'default'
- create_file
- end
-
-private
-
- def initialize
- @location = nil
- @opt = {}
- @logger = Logger.new(STDERR)
- @basedir = nil
- @wsdl = nil
- @name = nil
- end
-
- def create_file
- create_classdef if @opt.key?('classdef')
- create_servant_skelton(@opt['servant_skelton']) if @opt.key?('servant_skelton')
- create_cgi_stub(@opt['cgi_stub']) if @opt.key?('cgi_stub')
- create_standalone_server_stub(@opt['standalone_server_stub']) if @opt.key?('standalone_server_stub')
- create_driver(@opt['driver']) if @opt.key?('driver')
- create_client_skelton(@opt['client_skelton']) if @opt.key?('client_skelton')
- end
-
- def create_classdef
- @logger.info { "Creating class definition." }
- @classdef_filename = @name + '.rb'
- check_file(@classdef_filename) or return
- write_file(@classdef_filename) do |f|
- f << WSDL::SOAP::ClassDefCreator.new(@wsdl).dump
- end
- end
-
- def create_client_skelton(servicename)
- @logger.info { "Creating client skelton." }
- servicename ||= @wsdl.services[0].name.name
- @client_skelton_filename = servicename + 'Client.rb'
- check_file(@client_skelton_filename) or return
- write_file(@client_skelton_filename) do |f|
- f << shbang << "\n"
- f << "require '#{@driver_filename}'\n\n" if @driver_filename
- f << WSDL::SOAP::ClientSkeltonCreator.new(@wsdl).dump(
- create_name(servicename))
- end
- end
-
- def create_servant_skelton(porttypename)
- @logger.info { "Creating servant skelton." }
- @servant_skelton_filename = (porttypename || @name + 'Servant') + '.rb'
- check_file(@servant_skelton_filename) or return
- write_file(@servant_skelton_filename) do |f|
- f << "require '#{@classdef_filename}'\n\n" if @classdef_filename
- f << WSDL::SOAP::ServantSkeltonCreator.new(@wsdl).dump(
- create_name(porttypename))
- end
- end
-
- def create_cgi_stub(servicename)
- @logger.info { "Creating CGI stub." }
- servicename ||= @wsdl.services[0].name.name
- @cgi_stubFilename = servicename + '.cgi'
- check_file(@cgi_stubFilename) or return
- write_file(@cgi_stubFilename) do |f|
- f << shbang << "\n"
- if @servant_skelton_filename
- f << "require '#{@servant_skelton_filename}'\n\n"
- end
- f << WSDL::SOAP::CGIStubCreator.new(@wsdl).dump(create_name(servicename))
- end
- end
-
- def create_standalone_server_stub(servicename)
- @logger.info { "Creating standalone stub." }
- servicename ||= @wsdl.services[0].name.name
- @standalone_server_stub_filename = servicename + '.rb'
- check_file(@standalone_server_stub_filename) or return
- write_file(@standalone_server_stub_filename) do |f|
- f << shbang << "\n"
- f << "require '#{@servant_skelton_filename}'\n\n" if @servant_skelton_filename
- f << WSDL::SOAP::StandaloneServerStubCreator.new(@wsdl).dump(
- create_name(servicename))
- end
- end
-
- def create_driver(porttypename)
- @logger.info { "Creating driver." }
- @driver_filename = (porttypename || @name) + 'Driver.rb'
- check_file(@driver_filename) or return
- write_file(@driver_filename) do |f|
- f << "require '#{@classdef_filename}'\n\n" if @classdef_filename
- f << WSDL::SOAP::DriverCreator.new(@wsdl).dump(
- create_name(porttypename))
- end
- end
-
- def write_file(filename)
- if @basedir
- filename = File.join(basedir, filename)
- end
- File.open(filename, "w") do |f|
- yield f
- end
- end
-
- def check_file(filename)
- if @basedir
- filename = File.join(basedir, filename)
- end
- if FileTest.exist?(filename)
- if @opt.key?('force')
- @logger.warn {
- "File '#{filename}' exists but overrides it."
- }
- true
- else
- @logger.warn {
- "File '#{filename}' exists. #{$0} did not override it."
- }
- false
- end
- else
- @logger.info { "Creates file '#{filename}'." }
- true
- end
- end
-
- def shbang
- "#!/usr/bin/env ruby"
- end
-
- def create_name(name)
- name ? XSD::QName.new(@wsdl.targetnamespace, name) : nil
- end
-
- def import(location)
- WSDL::Importer.import(location)
- end
-end
-
-
-end
-end
diff --git a/lib/wsdl/xmlSchema/all.rb b/lib/wsdl/xmlSchema/all.rb
index bb9566feac..53f7ae82e4 100644
--- a/lib/wsdl/xmlSchema/all.rb
+++ b/lib/wsdl/xmlSchema/all.rb
@@ -20,8 +20,8 @@ class All < Info
def initialize
super()
- @minoccurs = '1'
- @maxoccurs = '1'
+ @minoccurs = 1
+ @maxoccurs = 1
@elements = []
end
@@ -29,10 +29,6 @@ class All < Info
parent.targetnamespace
end
- def elementformdefault
- parent.elementformdefault
- end
-
def <<(element)
@elements << element
end
@@ -55,9 +51,9 @@ class All < Info
def parse_attr(attr, value)
case attr
when MaxOccursAttrName
- @maxoccurs = value.source
+ @maxoccurs = value
when MinOccursAttrName
- @minoccurs = value.source
+ @minoccurs = value
else
nil
end
diff --git a/lib/wsdl/xmlSchema/annotation.rb b/lib/wsdl/xmlSchema/annotation.rb
deleted file mode 100644
index 633bd196f1..0000000000
--- a/lib/wsdl/xmlSchema/annotation.rb
+++ /dev/null
@@ -1,34 +0,0 @@
-# WSDL4R - WSDL SOAP documentation element.
-# Copyright (C) 2003, 2005 NAKAMURA, Hiroshi <nahi@ruby-lang.org>.
-
-# This program is copyrighted free software by NAKAMURA, Hiroshi. You can
-# redistribute it and/or modify it under the same terms of Ruby's license;
-# either the dual license version in 2003, or any later version.
-
-
-require 'wsdl/info'
-
-
-module WSDL
-module XMLSchema
-
-
-class Annotation < Info
- def initialize
- super
- end
-
- def parse_element(element)
- # Accepts any element.
- self
- end
-
- def parse_attr(attr, value)
- # Accepts any attribute.
- true
- end
-end
-
-
-end
-end
diff --git a/lib/wsdl/xmlSchema/any.rb b/lib/wsdl/xmlSchema/any.rb
index 72d25e8dde..3fc3706182 100644
--- a/lib/wsdl/xmlSchema/any.rb
+++ b/lib/wsdl/xmlSchema/any.rb
@@ -21,8 +21,8 @@ class Any < Info
def initialize
super()
- @maxoccurs = '1'
- @minoccurs = '1'
+ @maxoccurs = 1
+ @minoccurs = 1
@namespace = '##any'
@process_contents = 'strict'
end
@@ -38,13 +38,13 @@ class Any < Info
def parse_attr(attr, value)
case attr
when MaxOccursAttrName
- @maxoccurs = value.source
+ @maxoccurs = value
when MinOccursAttrName
- @minoccurs = value.source
+ @minoccurs = value
when NamespaceAttrName
- @namespace = value.source
+ @namespace = value
when ProcessContentsAttrName
- @process_contents = value.source
+ @process_contents = value
else
nil
end
diff --git a/lib/wsdl/xmlSchema/attribute.rb b/lib/wsdl/xmlSchema/attribute.rb
index f9048661a2..e5046dd991 100644
--- a/lib/wsdl/xmlSchema/attribute.rb
+++ b/lib/wsdl/xmlSchema/attribute.rb
@@ -1,5 +1,5 @@
# WSDL4R - XMLSchema attribute definition for WSDL.
-# Copyright (C) 2002, 2003, 2005 NAKAMURA, Hiroshi <nahi@ruby-lang.org>.
+# Copyright (C) 2002, 2003 NAKAMURA, Hiroshi <nahi@ruby-lang.org>.
# This program is copyrighted free software by NAKAMURA, Hiroshi. You can
# redistribute it and/or modify it under the same terms of Ruby's license;
@@ -14,74 +14,31 @@ module XMLSchema
class Attribute < Info
- class << self
- if RUBY_VERSION > "1.7.0"
- def attr_reader_ref(symbol)
- name = symbol.to_s
- define_method(name) {
- instance_variable_get("@#{name}") ||
- (refelement ? refelement.__send__(name) : nil)
- }
- end
- else
- def attr_reader_ref(symbol)
- name = symbol.to_s
- module_eval <<-EOS
- def #{name}
- @#{name} || (refelement ? refelement.#{name} : nil)
- end
- EOS
- end
- end
- end
-
- attr_writer :use
- attr_writer :form
- attr_writer :name
- attr_writer :type
- attr_writer :local_simpletype
- attr_writer :default
- attr_writer :fixed
-
- attr_reader_ref :use
- attr_reader_ref :form
- attr_reader_ref :name
- attr_reader_ref :type
- attr_reader_ref :local_simpletype
- attr_reader_ref :default
- attr_reader_ref :fixed
-
attr_accessor :ref
+ attr_accessor :use
+ attr_accessor :form
+ attr_accessor :name
+ attr_accessor :type
+ attr_accessor :default
+ attr_accessor :fixed
+
attr_accessor :arytype
def initialize
super
+ @ref = nil
@use = nil
@form = nil
@name = nil
@type = nil
- @local_simpletype = nil
@default = nil
@fixed = nil
- @ref = nil
- @refelement = nil
- @arytype = nil
- end
- def refelement
- @refelement ||= root.collect_attributes[@ref]
- end
-
- def targetnamespace
- parent.targetnamespace
+ @arytype = nil
end
def parse_element(element)
- case element
- when SimpleTypeName
- @local_simpletype = SimpleType.new
- @local_simpletype
- end
+ nil
end
def parse_attr(attr, value)
@@ -89,37 +46,27 @@ class Attribute < Info
when RefAttrName
@ref = value
when UseAttrName
- @use = value.source
+ @use = value
when FormAttrName
- @form = value.source
+ @form = value
when NameAttrName
- if directelement?
- @name = XSD::QName.new(targetnamespace, value.source)
- else
- @name = XSD::QName.new(nil, value.source)
- end
+ @name = value
when TypeAttrName
@type = value
when DefaultAttrName
- @default = value.source
+ @default = value
when FixedAttrName
- @fixed = value.source
+ @fixed = value
when ArrayTypeAttrName
- @arytype = if value.namespace.nil?
- XSD::QName.new(XSD::Namespace, value.source)
- else
- value
- end
+ @arytype = if value.is_a?(XSD::QName)
+ value
+ else
+ XSD::QName.new(XSD::Namespace, value)
+ end
else
nil
end
end
-
-private
-
- def directelement?
- parent.is_a?(Schema)
- end
end
diff --git a/lib/wsdl/xmlSchema/choice.rb b/lib/wsdl/xmlSchema/choice.rb
index f6d27fa38c..4cf481ec9e 100644
--- a/lib/wsdl/xmlSchema/choice.rb
+++ b/lib/wsdl/xmlSchema/choice.rb
@@ -20,8 +20,8 @@ class Choice < Info
def initialize
super()
- @minoccurs = '1'
- @maxoccurs = '1'
+ @minoccurs = 1
+ @maxoccurs = 1
@elements = []
end
@@ -29,10 +29,6 @@ class Choice < Info
parent.targetnamespace
end
- def elementformdefault
- parent.elementformdefault
- end
-
def <<(element)
@elements << element
end
@@ -55,9 +51,9 @@ class Choice < Info
def parse_attr(attr, value)
case attr
when MaxOccursAttrName
- @maxoccurs = value.source
+ @maxoccurs = value
when MinOccursAttrName
- @minoccurs = value.source
+ @minoccurs = value
else
nil
end
diff --git a/lib/wsdl/xmlSchema/complexContent.rb b/lib/wsdl/xmlSchema/complexContent.rb
index eddb52f5ef..66ad9e251d 100644
--- a/lib/wsdl/xmlSchema/complexContent.rb
+++ b/lib/wsdl/xmlSchema/complexContent.rb
@@ -26,17 +26,12 @@ class ComplexContent < Info
@derivetype = nil
@content = nil
@attributes = XSD::NamedElements.new
- @basetype = nil
end
def targetnamespace
parent.targetnamespace
end
- def basetype
- @basetype ||= root.collect_complextypes[@base]
- end
-
def parse_element(element)
case element
when RestrictionName, ExtensionName
diff --git a/lib/wsdl/xmlSchema/complexType.rb b/lib/wsdl/xmlSchema/complexType.rb
index dc9ec954fc..056a806dc5 100644
--- a/lib/wsdl/xmlSchema/complexType.rb
+++ b/lib/wsdl/xmlSchema/complexType.rb
@@ -19,8 +19,7 @@ module XMLSchema
class ComplexType < Info
attr_accessor :name
attr_accessor :complexcontent
- attr_accessor :simplecontent
- attr_reader :content
+ attr_accessor :content
attr_accessor :final
attr_accessor :mixed
attr_reader :attributes
@@ -29,7 +28,6 @@ class ComplexType < Info
super()
@name = name
@complexcontent = nil
- @simplecontent = nil
@content = nil
@final = nil
@mixed = false
@@ -37,19 +35,13 @@ class ComplexType < Info
end
def targetnamespace
- # inner elements can be qualified
- # parent.is_a?(WSDL::XMLSchema::Element) ? nil : parent.targetnamespace
parent.targetnamespace
end
-
- def elementformdefault
- parent.elementformdefault
- end
AnyAsElement = Element.new(XSD::QName.new(nil, 'any'), XSD::AnyTypeName)
def each_element
- if content
- content.elements.each do |element|
+ if @content
+ @content.elements.each do |element|
if element.is_a?(Any)
yield(AnyAsElement)
else
@@ -60,8 +52,8 @@ class ComplexType < Info
end
def find_element(name)
- if content
- content.elements.each do |element|
+ if @content
+ @content.elements.each do |element|
if element.is_a?(Any)
return AnyAsElement if name == AnyAsElement.name
else
@@ -73,8 +65,8 @@ class ComplexType < Info
end
def find_element_by_name(name)
- if content
- content.elements.each do |element|
+ if @content
+ @content.elements.each do |element|
if element.is_a?(Any)
return AnyAsElement if name == AnyAsElement.name.name
else
@@ -103,14 +95,16 @@ class ComplexType < Info
case element
when AllName
@content = All.new
+ @content
when SequenceName
@content = Sequence.new
+ @content
when ChoiceName
@content = Choice.new
+ @content
when ComplexContentName
@complexcontent = ComplexContent.new
- when SimpleContentName
- @simplecontent = SimpleContent.new
+ @complexcontent
when AttributeName
o = Attribute.new
@attributes << o
@@ -123,11 +117,11 @@ class ComplexType < Info
def parse_attr(attr, value)
case attr
when FinalAttrName
- @final = value.source
+ @final = value
when MixedAttrName
- @mixed = (value.source == 'true')
+ @mixed = (value == 'true')
when NameAttrName
- @name = XSD::QName.new(targetnamespace, value.source)
+ @name = XSD::QName.new(targetnamespace, value)
else
nil
end
diff --git a/lib/wsdl/xmlSchema/content.rb b/lib/wsdl/xmlSchema/content.rb
index 2f1dfb4b6c..3aa875e3e7 100644
--- a/lib/wsdl/xmlSchema/content.rb
+++ b/lib/wsdl/xmlSchema/content.rb
@@ -67,9 +67,9 @@ class Content < Info
def parse_attr(attr, value)
case attr
when FinalAttrName
- @final = value.source
+ @final = value
when MixedAttrName
- @mixed = (value.source == 'true')
+ @mixed = (value == 'true')
else
nil
end
diff --git a/lib/wsdl/xmlSchema/data.rb b/lib/wsdl/xmlSchema/data.rb
index 23ab1adf0b..1283ac2a1d 100644
--- a/lib/wsdl/xmlSchema/data.rb
+++ b/lib/wsdl/xmlSchema/data.rb
@@ -1,5 +1,5 @@
# WSDL4R - XMLSchema data definitions.
-# Copyright (C) 2002, 2003, 2005 NAKAMURA, Hiroshi <nahi@ruby-lang.org>.
+# Copyright (C) 2002, 2003 NAKAMURA, Hiroshi <nahi@ruby-lang.org>.
# This program is copyrighted free software by NAKAMURA, Hiroshi. You can
# redistribute it and/or modify it under the same terms of Ruby's license;
@@ -7,16 +7,12 @@
require 'xsd/datatypes'
-require 'wsdl/xmlSchema/annotation'
require 'wsdl/xmlSchema/schema'
require 'wsdl/xmlSchema/import'
-require 'wsdl/xmlSchema/include'
require 'wsdl/xmlSchema/simpleType'
require 'wsdl/xmlSchema/simpleRestriction'
-require 'wsdl/xmlSchema/simpleExtension'
require 'wsdl/xmlSchema/complexType'
require 'wsdl/xmlSchema/complexContent'
-require 'wsdl/xmlSchema/simpleContent'
require 'wsdl/xmlSchema/any'
require 'wsdl/xmlSchema/element'
require 'wsdl/xmlSchema/all'
@@ -25,15 +21,12 @@ require 'wsdl/xmlSchema/sequence'
require 'wsdl/xmlSchema/attribute'
require 'wsdl/xmlSchema/unique'
require 'wsdl/xmlSchema/enumeration'
-require 'wsdl/xmlSchema/length'
-require 'wsdl/xmlSchema/pattern'
module WSDL
module XMLSchema
AllName = XSD::QName.new(XSD::Namespace, 'all')
-AnnotationName = XSD::QName.new(XSD::Namespace, 'annotation')
AnyName = XSD::QName.new(XSD::Namespace, 'any')
AttributeName = XSD::QName.new(XSD::Namespace, 'attribute')
ChoiceName = XSD::QName.new(XSD::Namespace, 'choice')
@@ -43,13 +36,9 @@ ElementName = XSD::QName.new(XSD::Namespace, 'element')
EnumerationName = XSD::QName.new(XSD::Namespace, 'enumeration')
ExtensionName = XSD::QName.new(XSD::Namespace, 'extension')
ImportName = XSD::QName.new(XSD::Namespace, 'import')
-IncludeName = XSD::QName.new(XSD::Namespace, 'include')
-LengthName = XSD::QName.new(XSD::Namespace, 'length')
-PatternName = XSD::QName.new(XSD::Namespace, 'pattern')
RestrictionName = XSD::QName.new(XSD::Namespace, 'restriction')
SequenceName = XSD::QName.new(XSD::Namespace, 'sequence')
SchemaName = XSD::QName.new(XSD::Namespace, 'schema')
-SimpleContentName = XSD::QName.new(XSD::Namespace, 'simpleContent')
SimpleTypeName = XSD::QName.new(XSD::Namespace, 'simpleType')
UniqueName = XSD::QName.new(XSD::Namespace, 'unique')
@@ -67,7 +56,6 @@ MixedAttrName = XSD::QName.new(nil, 'mixed')
NameAttrName = XSD::QName.new(nil, 'name')
NamespaceAttrName = XSD::QName.new(nil, 'namespace')
NillableAttrName = XSD::QName.new(nil, 'nillable')
-ProcessContentsAttrName = XSD::QName.new(nil, 'processContents')
RefAttrName = XSD::QName.new(nil, 'ref')
SchemaLocationAttrName = XSD::QName.new(nil, 'schemaLocation')
TargetNamespaceAttrName = XSD::QName.new(nil, 'targetNamespace')
diff --git a/lib/wsdl/xmlSchema/element.rb b/lib/wsdl/xmlSchema/element.rb
index fffb6485d0..90e8c0d5d1 100644
--- a/lib/wsdl/xmlSchema/element.rb
+++ b/lib/wsdl/xmlSchema/element.rb
@@ -1,5 +1,5 @@
# WSDL4R - XMLSchema element definition for WSDL.
-# Copyright (C) 2002, 2003, 2005 NAKAMURA, Hiroshi <nahi@ruby-lang.org>.
+# Copyright (C) 2002, 2003 NAKAMURA, Hiroshi <nahi@ruby-lang.org>.
# This program is copyrighted free software by NAKAMURA, Hiroshi. You can
# redistribute it and/or modify it under the same terms of Ruby's license;
@@ -14,84 +14,31 @@ module XMLSchema
class Element < Info
- class << self
- if RUBY_VERSION > "1.7.0"
- def attr_reader_ref(symbol)
- name = symbol.to_s
- define_method(name) {
- instance_variable_get("@#{name}") ||
- (refelement ? refelement.__send__(name) : nil)
- }
- end
- else
- def attr_reader_ref(symbol)
- name = symbol.to_s
- module_eval <<-EOS
- def #{name}
- @#{name} || (refelement ? refelement.#{name} : nil)
- end
- EOS
- end
- end
- end
-
- attr_writer :name # required
- attr_writer :form
- attr_writer :type
- attr_writer :local_simpletype
- attr_writer :local_complextype
- attr_writer :constraint
- attr_writer :maxoccurs
- attr_writer :minoccurs
- attr_writer :nillable
-
- attr_reader_ref :name
- attr_reader_ref :form
- attr_reader_ref :type
- attr_reader_ref :local_simpletype
- attr_reader_ref :local_complextype
- attr_reader_ref :constraint
- attr_reader_ref :maxoccurs
- attr_reader_ref :minoccurs
- attr_reader_ref :nillable
-
- attr_accessor :ref
-
- def initialize(name = nil, type = nil)
+ attr_accessor :name # required
+ attr_accessor :type
+ attr_accessor :local_complextype
+ attr_accessor :constraint
+ attr_accessor :maxoccurs
+ attr_accessor :minoccurs
+ attr_accessor :nillable
+
+ def initialize(name = nil, type = XSD::AnyTypeName)
super()
@name = name
- @form = nil
@type = type
- @local_simpletype = @local_complextype = nil
+ @local_complextype = nil
@constraint = nil
- @maxoccurs = '1'
- @minoccurs = '1'
+ @maxoccurs = 1
+ @minoccurs = 1
@nillable = nil
- @ref = nil
- @refelement = nil
- end
-
- def refelement
- @refelement ||= (@ref ? root.collect_elements[@ref] : nil)
end
def targetnamespace
parent.targetnamespace
end
- def elementformdefault
- parent.elementformdefault
- end
-
- def elementform
- self.form.nil? ? parent.elementformdefault : self.form
- end
-
def parse_element(element)
case element
- when SimpleTypeName
- @local_simpletype = SimpleType.new
- @local_simpletype
when ComplexTypeName
@type = nil
@local_complextype = ComplexType.new
@@ -107,46 +54,49 @@ class Element < Info
def parse_attr(attr, value)
case attr
when NameAttrName
- # namespace may be nil
- if directelement? or elementform == 'qualified'
- @name = XSD::QName.new(targetnamespace, value.source)
- else
- @name = XSD::QName.new(nil, value.source)
- end
- when FormAttrName
- @form = value.source
+ #@name = XSD::QName.new(nil, value)
+ @name = XSD::QName.new(targetnamespace, value)
when TypeAttrName
- @type = value
- when RefAttrName
- @ref = value
+ @type = if value.is_a?(XSD::QName)
+ value
+ else
+ XSD::QName.new(XSD::Namespace, value)
+ end
when MaxOccursAttrName
- if parent.is_a?(All)
- if value.source != '1'
+ case parent
+ when All
+ if value != '1'
raise Parser::AttrConstraintError.new(
- "cannot parse #{value} for #{attr}")
+ "Cannot parse #{ value } for #{ attr }.")
end
+ @maxoccurs = value
+ when Sequence
+ @maxoccurs = value
+ else
+ raise NotImplementedError.new
end
- @maxoccurs = value.source
+ @maxoccurs
when MinOccursAttrName
- if parent.is_a?(All)
- unless ['0', '1'].include?(value.source)
+ case parent
+ when All
+ if ['0', '1'].include?(value)
+ @minoccurs = value
+ else
raise Parser::AttrConstraintError.new(
- "cannot parse #{value} for #{attr}")
+ "Cannot parse #{ value } for #{ attr }.")
end
+ when Sequence
+ @minoccurs = value
+ else
+ raise NotImplementedError.new
end
- @minoccurs = value.source
+ @minoccurs
when NillableAttrName
- @nillable = (value.source == 'true')
+ @nillable = (value == 'true')
else
nil
end
end
-
-private
-
- def directelement?
- parent.is_a?(Schema)
- end
end
diff --git a/lib/wsdl/xmlSchema/enumeration.rb b/lib/wsdl/xmlSchema/enumeration.rb
index 5a16476032..cd61572d07 100644
--- a/lib/wsdl/xmlSchema/enumeration.rb
+++ b/lib/wsdl/xmlSchema/enumeration.rb
@@ -25,8 +25,8 @@ class Enumeration < Info
def parse_attr(attr, value)
case attr
when ValueAttrName
- parent.enumeration << value.source
- value.source
+ parent.enumeration << value
+ value
end
end
end
diff --git a/lib/wsdl/xmlSchema/import.rb b/lib/wsdl/xmlSchema/import.rb
index d3487af934..2ef3b72ab2 100644
--- a/lib/wsdl/xmlSchema/import.rb
+++ b/lib/wsdl/xmlSchema/import.rb
@@ -1,5 +1,5 @@
# WSDL4R - XMLSchema import definition.
-# Copyright (C) 2002, 2003, 2005 NAKAMURA, Hiroshi <nahi@ruby-lang.org>.
+# Copyright (C) 2002, 2003 NAKAMURA, Hiroshi <nahi@ruby-lang.org>.
# This program is copyrighted free software by NAKAMURA, Hiroshi. You can
# redistribute it and/or modify it under the same terms of Ruby's license;
@@ -7,7 +7,6 @@
require 'wsdl/info'
-require 'wsdl/xmlSchema/importer'
module WSDL
@@ -17,13 +16,11 @@ module XMLSchema
class Import < Info
attr_reader :namespace
attr_reader :schemalocation
- attr_reader :content
def initialize
super
@namespace = nil
@schemalocation = nil
- @content = nil
end
def parse_element(element)
@@ -33,31 +30,13 @@ class Import < Info
def parse_attr(attr, value)
case attr
when NamespaceAttrName
- @namespace = value.source
+ @namespace = value
when SchemaLocationAttrName
- @schemalocation = URI.parse(value.source)
- if @schemalocation.relative? and !parent.location.nil? and
- !parent.location.relative?
- @schemalocation = parent.location + @schemalocation
- end
- if root.importedschema.key?(@schemalocation)
- @content = root.importedschema[@schemalocation]
- else
- root.importedschema[@schemalocation] = nil # placeholder
- @content = import(@schemalocation)
- root.importedschema[@schemalocation] = @content
- end
- @schemalocation
+ @schemalocation = value
else
nil
end
end
-
-private
-
- def import(location)
- Importer.import(location, root)
- end
end
diff --git a/lib/wsdl/xmlSchema/importer.rb b/lib/wsdl/xmlSchema/importer.rb
deleted file mode 100644
index f57bfd972a..0000000000
--- a/lib/wsdl/xmlSchema/importer.rb
+++ /dev/null
@@ -1,87 +0,0 @@
-# WSDL4R - XSD importer library.
-# Copyright (C) 2003, 2005 NAKAMURA, Hiroshi <nahi@ruby-lang.org>.
-
-# This program is copyrighted free software by NAKAMURA, Hiroshi. You can
-# redistribute it and/or modify it under the same terms of Ruby's license;
-# either the dual license version in 2003, or any later version.
-
-
-require 'soap/httpconfigloader'
-require 'wsdl/xmlSchema/parser'
-
-
-module WSDL
-module XMLSchema
-
-
-class Importer
- def self.import(location, originalroot = nil)
- new.import(location, originalroot)
- end
-
- def initialize
- @web_client = nil
- end
-
- def import(location, originalroot = nil)
- unless location.is_a?(URI)
- location = URI.parse(location)
- end
- content = parse(fetch(location), location, originalroot)
- content.location = location
- content
- end
-
-private
-
- def parse(content, location, originalroot)
- opt = {
- :location => location,
- :originalroot => originalroot
- }
- WSDL::XMLSchema::Parser.new(opt).parse(content)
- end
-
- def fetch(location)
- warn("importing: #{location}") if $DEBUG
- content = nil
- if location.scheme == 'file' or
- (location.relative? and FileTest.exist?(location.path))
- content = File.open(location.path).read
- elsif location.scheme and location.scheme.size == 1 and
- FileTest.exist?(location.to_s)
- # ToDo: remove this ugly workaround for a path with drive letter
- # (D://foo/bar)
- content = File.open(location.to_s).read
- else
- client = web_client.new(nil, "WSDL4R")
- client.proxy = ::SOAP::Env::HTTP_PROXY
- client.no_proxy = ::SOAP::Env::NO_PROXY
- if opt = ::SOAP::Property.loadproperty(::SOAP::PropertyName)
- ::SOAP::HTTPConfigLoader.set_options(client,
- opt["client.protocol.http"])
- end
- content = client.get_content(location)
- end
- content
- end
-
- def web_client
- @web_client ||= begin
- require 'http-access2'
- if HTTPAccess2::VERSION < "2.0"
- raise LoadError.new("http-access/2.0 or later is required.")
- end
- HTTPAccess2::Client
- rescue LoadError
- warn("Loading http-access2 failed. Net/http is used.") if $DEBUG
- require 'soap/netHttpClient'
- ::SOAP::NetHttpClient
- end
- @web_client
- end
-end
-
-
-end
-end
diff --git a/lib/wsdl/xmlSchema/include.rb b/lib/wsdl/xmlSchema/include.rb
deleted file mode 100644
index af1ef942bb..0000000000
--- a/lib/wsdl/xmlSchema/include.rb
+++ /dev/null
@@ -1,54 +0,0 @@
-# WSDL4R - XMLSchema include definition.
-# Copyright (C) 2005 NAKAMURA, Hiroshi <nahi@ruby-lang.org>.
-
-# This program is copyrighted free software by NAKAMURA, Hiroshi. You can
-# redistribute it and/or modify it under the same terms of Ruby's license;
-# either the dual license version in 2003, or any later version.
-
-
-require 'wsdl/info'
-require 'wsdl/xmlSchema/importer'
-
-
-module WSDL
-module XMLSchema
-
-
-class Include < Info
- attr_reader :schemalocation
- attr_reader :content
-
- def initialize
- super
- @schemalocation = nil
- @content = nil
- end
-
- def parse_element(element)
- nil
- end
-
- def parse_attr(attr, value)
- case attr
- when SchemaLocationAttrName
- @schemalocation = URI.parse(value.source)
- if @schemalocation.relative?
- @schemalocation = parent.location + @schemalocation
- end
- @content = import(@schemalocation)
- @schemalocation
- else
- nil
- end
- end
-
-private
-
- def import(location)
- Importer.import(location)
- end
-end
-
-
-end
-end
diff --git a/lib/wsdl/xmlSchema/length.rb b/lib/wsdl/xmlSchema/length.rb
deleted file mode 100644
index 7f61602da9..0000000000
--- a/lib/wsdl/xmlSchema/length.rb
+++ /dev/null
@@ -1,35 +0,0 @@
-# WSDL4R - XMLSchema length definition for WSDL.
-# Copyright (C) 2005 NAKAMURA, Hiroshi <nahi@ruby-lang.org>.
-
-# This program is copyrighted free software by NAKAMURA, Hiroshi. You can
-# redistribute it and/or modify it under the same terms of Ruby's license;
-# either the dual license version in 2003, or any later version.
-
-
-require 'wsdl/info'
-
-
-module WSDL
-module XMLSchema
-
-
-class Length < Info
- def initialize
- super
- end
-
- def parse_element(element)
- nil
- end
-
- def parse_attr(attr, value)
- case attr
- when ValueAttrName
- value.source
- end
- end
-end
-
-
-end
-end
diff --git a/lib/wsdl/xmlSchema/parser.rb b/lib/wsdl/xmlSchema/parser.rb
index 057d9d9b70..5401c5f729 100644
--- a/lib/wsdl/xmlSchema/parser.rb
+++ b/lib/wsdl/xmlSchema/parser.rb
@@ -1,5 +1,5 @@
# WSDL4R - WSDL XML Instance parser library.
-# Copyright (C) 2002, 2003, 2005 NAKAMURA, Hiroshi <nahi@ruby-lang.org>.
+# Copyright (C) 2002, 2003 NAKAMURA, Hiroshi <nahi@ruby-lang.org>.
# This program is copyrighted free software by NAKAMURA, Hiroshi. You can
# redistribute it and/or modify it under the same terms of Ruby's license;
@@ -22,7 +22,7 @@ class Parser
include XSD
class ParseError < Error; end
- class FormatDecodeError < ParseError; end
+ class FormatDecodeError < Error; end
class UnknownElementError < FormatDecodeError; end
class UnknownAttributeError < FormatDecodeError; end
class UnexpectedElementError < FormatDecodeError; end
@@ -51,9 +51,6 @@ public
@parser = XSD::XMLParser.create_parser(self, opt)
@parsestack = nil
@lastnode = nil
- @ignored = {}
- @location = opt[:location]
- @originalroot = opt[:originalroot]
end
def parse(string_or_readable)
@@ -97,7 +94,7 @@ public
def end_element(name)
lastframe = @parsestack.pop
unless name == lastframe.name
- raise UnexpectedElementError.new("closing element name '#{name}' does not match with opening element '#{lastframe.name}'")
+ raise UnexpectedElementError.new("Closing element name '#{ name }' does not match with opening element '#{ lastframe.name }'.")
end
decode_tag_end(lastframe.ns, lastframe.node)
@lastnode = lastframe.node
@@ -107,46 +104,45 @@ private
def decode_tag(ns, name, attrs, parent)
o = nil
- elename = ns.parse(name)
+ element = ns.parse(name)
if !parent
- if elename == SchemaName
- o = Schema.parse_element(elename)
- o.location = @location
+ if element == SchemaName
+ o = Schema.parse_element(element)
else
- raise UnknownElementError.new("unknown element: #{elename}")
+ raise UnknownElementError.new("Unknown element #{ element }.")
end
- o.root = @originalroot if @originalroot # o.root = o otherwise
else
- if elename == AnnotationName
- # only the first annotation element is allowed for each element.
- o = Annotation.new
- else
- o = parent.parse_element(elename)
- end
+ o = parent.parse_element(element)
unless o
- unless @ignored.key?(elename)
- warn("ignored element: #{elename} of #{parent.class}")
- @ignored[elename] = elename
- end
- o = Documentation.new # which accepts any element.
+ raise UnknownElementError.new("Unknown element #{ element }.")
end
# node could be a pseudo element. pseudo element has its own parent.
- o.root = parent.root
o.parent = parent if o.parent.nil?
end
attrs.each do |key, value|
- attr_ele = ns.parse(key, true)
- value_ele = ns.parse(value, true)
- value_ele.source = value # for recovery; value may not be a QName
- if attr_ele == IdAttrName
+ attr = unless /:/ =~ key
+ XSD::QName.new(nil, key)
+ else
+ ns.parse(key)
+ end
+ value_ele = if /:/ !~ value
+ value
+ elsif /^http:\/\// =~ value # ToDo: ugly.
+ value
+ else
+ begin
+ ns.parse(value)
+ rescue
+ value
+ end
+ end
+ if attr == IdAttrName
o.id = value_ele
else
- unless o.parse_attr(attr_ele, value_ele)
- unless @ignored.key?(attr_ele)
- warn("ignored attr: #{attr_ele}")
- @ignored[attr_ele] = attr_ele
- end
- end
+ unless o.parse_attr(attr, value_ele)
+ STDERR.puts("Unknown attr #{ attr }.")
+ # raise UnknownAttributeError.new("Unknown attr #{ attr }.")
+ end
end
end
o
diff --git a/lib/wsdl/xmlSchema/pattern.rb b/lib/wsdl/xmlSchema/pattern.rb
deleted file mode 100644
index f826be4578..0000000000
--- a/lib/wsdl/xmlSchema/pattern.rb
+++ /dev/null
@@ -1,36 +0,0 @@
-# WSDL4R - XMLSchema pattern definition for WSDL.
-# Copyright (C) 2005 NAKAMURA, Hiroshi <nahi@ruby-lang.org>.
-
-# This program is copyrighted free software by NAKAMURA, Hiroshi. You can
-# redistribute it and/or modify it under the same terms of Ruby's license;
-# either the dual license version in 2003, or any later version.
-
-
-require 'wsdl/info'
-
-
-module WSDL
-module XMLSchema
-
-
-class Pattern < Info
- def initialize
- super
- end
-
- def parse_element(element)
- nil
- end
-
- def parse_attr(attr, value)
- case attr
- when ValueAttrName
- parent.pattern = /\A#{value.source}\z/n
- value.source
- end
- end
-end
-
-
-end
-end
diff --git a/lib/wsdl/xmlSchema/schema.rb b/lib/wsdl/xmlSchema/schema.rb
index ec97d07aa5..b530a92556 100644
--- a/lib/wsdl/xmlSchema/schema.rb
+++ b/lib/wsdl/xmlSchema/schema.rb
@@ -1,5 +1,5 @@
# WSDL4R - XMLSchema schema definition for WSDL.
-# Copyright (C) 2002, 2003-2005 NAKAMURA, Hiroshi <nahi@ruby-lang.org>.
+# Copyright (C) 2002, 2003 NAKAMURA, Hiroshi <nahi@ruby-lang.org>.
# This program is copyrighted free software by NAKAMURA, Hiroshi. You can
# redistribute it and/or modify it under the same terms of Ruby's license;
@@ -24,8 +24,6 @@ class Schema < Info
attr_accessor :attributeformdefault
attr_accessor :elementformdefault
- attr_reader :importedschema
-
def initialize
super
@targetnamespace = nil
@@ -34,19 +32,7 @@ class Schema < Info
@elements = XSD::NamedElements.new
@attributes = XSD::NamedElements.new
@imports = []
- @attributeformdefault = "unqualified"
- @elementformdefault = "unqualified"
- @importedschema = {}
- @location = nil
- @root = self
- end
-
- def location
- @location || (root.nil? ? nil : root.location)
- end
-
- def location=(location)
- @location = location
+ @elementformdefault = nil
end
def parse_element(element)
@@ -55,10 +41,6 @@ class Schema < Info
o = Import.new
@imports << o
o
- when IncludeName
- o = Include.new
- @imports << o
- o
when ComplexTypeName
o = ComplexType.new
@complextypes << o
@@ -73,7 +55,6 @@ class Schema < Info
o
when AttributeName
o = Attribute.new
- @attributes << o
o
else
nil
@@ -83,49 +64,31 @@ class Schema < Info
def parse_attr(attr, value)
case attr
when TargetNamespaceAttrName
- @targetnamespace = value.source
+ @targetnamespace = value
when AttributeFormDefaultAttrName
- @attributeformdefault = value.source
+ @attributeformdefault = value
when ElementFormDefaultAttrName
- @elementformdefault = value.source
+ @elementformdefault = value
else
nil
end
end
- def collect_attributes
- result = XSD::NamedElements.new
- result.concat(@attributes)
- @imports.each do |import|
- result.concat(import.content.collect_attributes) if import.content
- end
- result
- end
-
def collect_elements
result = XSD::NamedElements.new
result.concat(@elements)
- @imports.each do |import|
- result.concat(import.content.collect_elements) if import.content
- end
result
end
def collect_complextypes
result = XSD::NamedElements.new
result.concat(@complextypes)
- @imports.each do |import|
- result.concat(import.content.collect_complextypes) if import.content
- end
result
end
def collect_simpletypes
result = XSD::NamedElements.new
result.concat(@simpletypes)
- @imports.each do |import|
- result.concat(import.content.collect_simpletypes) if import.content
- end
result
end
diff --git a/lib/wsdl/xmlSchema/sequence.rb b/lib/wsdl/xmlSchema/sequence.rb
index 823fa3b7f9..3810832ab2 100644
--- a/lib/wsdl/xmlSchema/sequence.rb
+++ b/lib/wsdl/xmlSchema/sequence.rb
@@ -20,8 +20,8 @@ class Sequence < Info
def initialize
super()
- @minoccurs = '1'
- @maxoccurs = '1'
+ @minoccurs = 1
+ @maxoccurs = 1
@elements = []
end
@@ -29,10 +29,6 @@ class Sequence < Info
parent.targetnamespace
end
- def elementformdefault
- parent.elementformdefault
- end
-
def <<(element)
@elements << element
end
@@ -55,9 +51,9 @@ class Sequence < Info
def parse_attr(attr, value)
case attr
when MaxOccursAttrName
- @maxoccurs = value.source
+ @maxoccurs = value
when MinOccursAttrName
- @minoccurs = value.source
+ @minoccurs = value
else
nil
end
diff --git a/lib/wsdl/xmlSchema/simpleContent.rb b/lib/wsdl/xmlSchema/simpleContent.rb
deleted file mode 100644
index e1f35c88b8..0000000000
--- a/lib/wsdl/xmlSchema/simpleContent.rb
+++ /dev/null
@@ -1,65 +0,0 @@
-# WSDL4R - XMLSchema simpleContent definition for WSDL.
-# Copyright (C) 2004, 2005 NAKAMURA, Hiroshi <nahi@ruby-lang.org>.
-
-# This program is copyrighted free software by NAKAMURA, Hiroshi. You can
-# redistribute it and/or modify it under the same terms of Ruby's license;
-# either the dual license version in 2003, or any later version.
-
-
-require 'wsdl/info'
-require 'xsd/namedelements'
-
-
-module WSDL
-module XMLSchema
-
-
-class SimpleContent < Info
- attr_reader :restriction
- attr_reader :extension
-
- def check_lexical_format(value)
- check(value)
- end
-
- def initialize
- super
- @restriction = nil
- @extension = nil
- end
-
- def base
- content.base
- end
-
- def targetnamespace
- parent.targetnamespace
- end
-
- def parse_element(element)
- case element
- when RestrictionName
- @restriction = SimpleRestriction.new
- @restriction
- when ExtensionName
- @extension = SimpleExtension.new
- @extension
- end
- end
-
-private
-
- def content
- @restriction || @extension
- end
-
- def check(value)
- unless content.valid?(value)
- raise XSD::ValueSpaceError.new("#{@name}: cannot accept '#{value}'")
- end
- end
-end
-
-
-end
-end
diff --git a/lib/wsdl/xmlSchema/simpleExtension.rb b/lib/wsdl/xmlSchema/simpleExtension.rb
deleted file mode 100644
index 3c53a7328c..0000000000
--- a/lib/wsdl/xmlSchema/simpleExtension.rb
+++ /dev/null
@@ -1,54 +0,0 @@
-# WSDL4R - XMLSchema simpleType extension definition for WSDL.
-# Copyright (C) 2005 NAKAMURA, Hiroshi <nahi@ruby-lang.org>.
-
-# This program is copyrighted free software by NAKAMURA, Hiroshi. You can
-# redistribute it and/or modify it under the same terms of Ruby's license;
-# either the dual license version in 2003, or any later version.
-
-
-require 'wsdl/info'
-require 'xsd/namedelements'
-
-
-module WSDL
-module XMLSchema
-
-
-class SimpleExtension < Info
- attr_reader :base
- attr_reader :attributes
-
- def initialize
- super
- @base = nil
- @attributes = XSD::NamedElements.new
- end
-
- def targetnamespace
- parent.targetnamespace
- end
-
- def valid?(value)
- true
- end
-
- def parse_element(element)
- case element
- when AttributeName
- o = Attribute.new
- @attributes << o
- o
- end
- end
-
- def parse_attr(attr, value)
- case attr
- when BaseAttrName
- @base = value
- end
- end
-end
-
-
-end
-end
diff --git a/lib/wsdl/xmlSchema/simpleRestriction.rb b/lib/wsdl/xmlSchema/simpleRestriction.rb
index e8bf3ebfa5..6986e74423 100644
--- a/lib/wsdl/xmlSchema/simpleRestriction.rb
+++ b/lib/wsdl/xmlSchema/simpleRestriction.rb
@@ -1,4 +1,4 @@
-# WSDL4R - XMLSchema simpleContent restriction definition for WSDL.
+# WSDL4R - XMLSchema simpleType definition for WSDL.
# Copyright (C) 2004 NAKAMURA, Hiroshi <nahi@ruby-lang.org>.
# This program is copyrighted free software by NAKAMURA, Hiroshi. You can
@@ -17,32 +17,21 @@ module XMLSchema
class SimpleRestriction < Info
attr_reader :base
attr_reader :enumeration
- attr_accessor :length
- attr_accessor :pattern
def initialize
super
@base = nil
@enumeration = [] # NamedElements?
- @length = nil
- @pattern = nil
end
def valid?(value)
- return false unless check_restriction(value)
- return false unless check_length(value)
- return false unless check_pattern(value)
- true
+ @enumeration.include?(value)
end
def parse_element(element)
case element
when EnumerationName
Enumeration.new # just a parsing handler
- when LengthName
- Length.new # just a parsing handler
- when PatternName
- Pattern.new # just a parsing handler
end
end
@@ -52,20 +41,6 @@ class SimpleRestriction < Info
@base = value
end
end
-
-private
-
- def check_restriction(value)
- @enumeration.empty? or @enumeration.include?(value)
- end
-
- def check_length(value)
- @length.nil? or value.size == @length
- end
-
- def check_pattern(value)
- @pattern.nil? or @pattern =~ value
- end
end
diff --git a/lib/wsdl/xmlSchema/simpleType.rb b/lib/wsdl/xmlSchema/simpleType.rb
index e808c318c4..830086f99e 100644
--- a/lib/wsdl/xmlSchema/simpleType.rb
+++ b/lib/wsdl/xmlSchema/simpleType.rb
@@ -1,5 +1,5 @@
# WSDL4R - XMLSchema simpleType definition for WSDL.
-# Copyright (C) 2004, 2005 NAKAMURA, Hiroshi <nahi@ruby-lang.org>.
+# Copyright (C) 2004 NAKAMURA, Hiroshi <nahi@ruby-lang.org>.
# This program is copyrighted free software by NAKAMURA, Hiroshi. You can
# redistribute it and/or modify it under the same terms of Ruby's license;
@@ -16,11 +16,15 @@ module XMLSchema
class SimpleType < Info
attr_accessor :name
+ attr_reader :derivetype
attr_reader :restriction
def check_lexical_format(value)
if @restriction
check_restriction(value)
+ elsif @extension
+ raise NotImplementedError
+ # ToDo
else
raise ArgumentError.new("incomplete simpleType")
end
@@ -29,6 +33,8 @@ class SimpleType < Info
def base
if @restriction
@restriction.base
+ elsif @extension
+ @extension.base
else
raise ArgumentError.new("incomplete simpleType")
end
@@ -37,6 +43,7 @@ class SimpleType < Info
def initialize(name = nil)
super()
@name = name
+ @derivetype = nil
@restriction = nil
end
@@ -48,6 +55,7 @@ class SimpleType < Info
case element
when RestrictionName
@restriction = SimpleRestriction.new
+ @derivetype = element.name
@restriction
end
end
@@ -55,7 +63,7 @@ class SimpleType < Info
def parse_attr(attr, value)
case attr
when NameAttrName
- @name = XSD::QName.new(targetnamespace, value.source)
+ @name = XSD::QName.new(targetnamespace, value)
end
end
@@ -63,7 +71,7 @@ private
def check_restriction(value)
unless @restriction.valid?(value)
- raise XSD::ValueSpaceError.new("#{@name}: cannot accept '#{value}'")
+ raise ::XSD::ValueSpaceError.new("#{@name}: cannot accept '#{value}'.")
end
end
end
diff --git a/lib/wsdl/xmlSchema/xsd2ruby.rb b/lib/wsdl/xmlSchema/xsd2ruby.rb
deleted file mode 100644
index afe5fc5ada..0000000000
--- a/lib/wsdl/xmlSchema/xsd2ruby.rb
+++ /dev/null
@@ -1,107 +0,0 @@
-# XSD4R - XSD to ruby mapping library.
-# Copyright (C) 2005 NAKAMURA, Hiroshi <nahi@ruby-lang.org>.
-
-# This program is copyrighted free software by NAKAMURA, Hiroshi. You can
-# redistribute it and/or modify it under the same terms of Ruby's license;
-# either the dual license version in 2003, or any later version.
-
-
-require 'xsd/codegen/gensupport'
-require 'wsdl/xmlSchema/importer'
-require 'wsdl/soap/classDefCreator'
-
-
-module WSDL
-module XMLSchema
-
-
-class XSD2Ruby
- attr_accessor :location
- attr_reader :opt
- attr_accessor :logger
- attr_accessor :basedir
-
- def run
- unless @location
- raise RuntimeError, "XML Schema location not given"
- end
- @xsd = import(@location)
- @name = create_classname(@xsd)
- create_file
- end
-
-private
-
- def initialize
- @location = nil
- @opt = {}
- @logger = Logger.new(STDERR)
- @basedir = nil
- @xsd = nil
- @name = nil
- end
-
- def create_file
- create_classdef
- end
-
- def create_classdef
- @logger.info { "Creating class definition." }
- @classdef_filename = @name + '.rb'
- check_file(@classdef_filename) or return
- write_file(@classdef_filename) do |f|
- f << WSDL::SOAP::ClassDefCreator.new(@xsd).dump
- end
- end
-
- def write_file(filename)
- if @basedir
- filename = File.join(basedir, filename)
- end
- File.open(filename, "w") do |f|
- yield f
- end
- end
-
- def check_file(filename)
- if @basedir
- filename = File.join(basedir, filename)
- end
- if FileTest.exist?(filename)
- if @opt.key?('force')
- @logger.warn {
- "File '#{filename}' exists but overrides it."
- }
- true
- else
- @logger.warn {
- "File '#{filename}' exists. #{$0} did not override it."
- }
- false
- end
- else
- @logger.info { "Creates file '#{filename}'." }
- true
- end
- end
-
- def create_classname(xsd)
- name = nil
- if xsd.targetnamespace
- name = xsd.targetnamespace.scan(/[a-zA-Z0-9]+$/)[0]
- end
- if name.nil?
- 'default'
- else
- XSD::CodeGen::GenSupport.safevarname(name)
- end
- end
-
- def import(location)
- WSDL::XMLSchema::Importer.import(location)
- end
-end
-
-
-end
-end
diff --git a/lib/xmlrpc/.document b/lib/xmlrpc/.document
deleted file mode 100644
index e475c53ed0..0000000000
--- a/lib/xmlrpc/.document
+++ /dev/null
@@ -1 +0,0 @@
-README.rdoc
diff --git a/lib/xmlrpc/client.rb b/lib/xmlrpc/client.rb
index dadd3279f2..18cf4b0cf3 100644
--- a/lib/xmlrpc/client.rb
+++ b/lib/xmlrpc/client.rb
@@ -69,7 +69,6 @@ call on the remote-side and of course the parameters for the remote procedure.
Parameter ((|timeout|)) is the time to wait for a XML-RPC response, defaults to 30.
--- XMLRPC::Client.new2( uri, proxy=nil, timeout=nil)
---- XMLRPC::Client.new_from_uri( uri, proxy=nil, timeout=nil)
: uri
URI specifying protocol (http or https), host, port, path, user and password.
Example: https://user:password@host:port/path
@@ -81,7 +80,6 @@ call on the remote-side and of course the parameters for the remote procedure.
Defaults to 30.
--- XMLRPC::Client.new3( hash={} )
---- XMLRPC::Client.new_from_hash( hash={} )
Parameter ((|hash|)) has following case-insensitive keys:
* host
* path
@@ -137,8 +135,6 @@ call on the remote-side and of course the parameters for the remote procedure.
(({XMLRPC::FaultException})).
Both are explained in ((<call|XMLRPC::Client#call>)).
- Simple to remember: The "2" in "call2" denotes the number of values it returns.
-
--- XMLRPC::Client#multicall( *methods )
You can use this method to execute several methods on a XMLRPC server which supports
the multi-call extension.
@@ -335,9 +331,7 @@ module XMLRPC
end
- class << self
-
- def new2(uri, proxy=nil, timeout=nil)
+ def self.new2(uri, proxy=nil, timeout=nil)
if match = /^([^:]+):\/\/(([^@]+)@)?([^\/]+)(\/.*)?$/.match(uri)
proto = match[1]
user, passwd = (match[3] || "").split(":")
@@ -356,10 +350,9 @@ module XMLRPC
self.new(host, path, port, proxy_host, proxy_port, user, passwd, (proto == "https"), timeout)
end
+
- alias new_from_uri new2
-
- def new3(hash={})
+ def self.new3(hash={})
# convert all keys into lowercase strings
h = {}
@@ -369,10 +362,6 @@ module XMLRPC
h['use_ssl'], h['timeout'])
end
- alias new_from_hash new3
-
- end
-
# Attribute Accessors -------------------------------------------------------------------
@@ -468,19 +457,19 @@ module XMLRPC
# Proxy generating methods ------------------------------------------
- def proxy(prefix=nil, *args)
+ def proxy(prefix, *args)
Proxy.new(self, prefix, args, :call)
end
- def proxy2(prefix=nil, *args)
+ def proxy2(prefix, *args)
Proxy.new(self, prefix, args, :call2)
end
- def proxy_async(prefix=nil, *args)
+ def proxy_async(prefix, *args)
Proxy.new(self, prefix, args, :call_async)
end
- def proxy2_async(prefix=nil, *args)
+ def proxy2_async(prefix, *args)
Proxy.new(self, prefix, args, :call2_async)
end
@@ -500,7 +489,7 @@ module XMLRPC
def do_rpc(request, async=false)
header = {
"User-Agent" => USER_AGENT,
- "Content-Type" => "text/xml; charset=utf-8",
+ "Content-Type" => "text/xml",
"Content-Length" => request.size.to_s,
"Connection" => (async ? "close" : "keep-alive")
}
@@ -597,7 +586,7 @@ module XMLRPC
def initialize(server, prefix, args=[], meth=:call, delim=".")
@server = server
- @prefix = prefix ? prefix + delim : ""
+ @prefix = prefix + delim
@args = args
@meth = meth
end
diff --git a/lib/xmlrpc/create.rb b/lib/xmlrpc/create.rb
index 0bfa4ab551..072e72ab46 100644
--- a/lib/xmlrpc/create.rb
+++ b/lib/xmlrpc/create.rb
@@ -86,18 +86,6 @@ module XMLRPC
end # class XMLParser
- Classes = [Simple, XMLParser]
-
- # yields an instance of each installed XML writer
- def self.each_installed_writer
- XMLRPC::XMLWriter::Classes.each do |klass|
- begin
- yield klass.new
- rescue LoadError
- end
- end
- end
-
end # module XMLWriter
class Create
@@ -260,10 +248,7 @@ module XMLRPC
if Config::ENABLE_MARSHALLING and param.class.included_modules.include? XMLRPC::Marshallable
# convert Ruby object into Hash
ret = {"___class___" => param.class.name}
- param.instance_variables.each {|v|
- name = v[1..-1]
- val = param.instance_variable_get(v)
-
+ param.__get_instance_variables.each {|name, val|
if val.nil?
ret[name] = val if Config::ENABLE_NIL_CREATE
else
diff --git a/lib/xmlrpc/datetime.rb b/lib/xmlrpc/datetime.rb
index 298263fe8a..e3bc6943f0 100644
--- a/lib/xmlrpc/datetime.rb
+++ b/lib/xmlrpc/datetime.rb
@@ -126,10 +126,6 @@ class DateTime
[@year, @month, @day, @hour, @min, @sec]
end
- def ==(o)
- Array(self) == Array(o)
- end
-
end
diff --git a/lib/xmlrpc/parser.rb b/lib/xmlrpc/parser.rb
index d27d7c3827..da214ba1ce 100644
--- a/lib/xmlrpc/parser.rb
+++ b/lib/xmlrpc/parser.rb
@@ -51,11 +51,9 @@ end # module NQXML
module XMLRPC
- class FaultException < StandardError
+ class FaultException < Exception
attr_reader :faultCode, :faultString
- alias message faultString
-
def initialize(faultCode, faultString)
@faultCode = faultCode
@faultString = faultString
@@ -86,32 +84,18 @@ module XMLRPC
end
def self.dateTime(str)
- case str
- when /^(-?\d\d\d\d)-?(\d\d)-?(\d\d)T(\d\d):(\d\d):(\d\d)(?:Z|([+-])(\d\d):?(\d\d))?$/
- a = [$1, $2, $3, $4, $5, $6].collect{|i| i.to_i}
- if $7
- ofs = $8.to_i*3600 + $9.to_i*60
- ofs = -ofs if $7=='+'
- utc = Time.utc(a.reverse) + ofs
- a = [ utc.year, utc.month, utc.day, utc.hour, utc.min, utc.sec ]
- end
- XMLRPC::DateTime.new(*a)
- when /^(-?\d\d)-?(\d\d)-?(\d\d)T(\d\d):(\d\d):(\d\d)(Z|([+-]\d\d):(\d\d))?$/
+ if str =~ /^(-?\d\d\d\d)(\d\d)(\d\d)T(\d\d):(\d\d):(\d\d)$/ then
+ # TODO: Time.gm ??? .local ???
a = [$1, $2, $3, $4, $5, $6].collect{|i| i.to_i}
- if a[0] < 70
- a[0] += 2000
- else
- a[0] += 1900
- end
- if $7
- ofs = $8.to_i*3600 + $9.to_i*60
- ofs = -ofs if $7=='+'
- utc = Time.utc(a.reverse) + ofs
- a = [ utc.year, utc.month, utc.day, utc.hour, utc.min, utc.sec ]
- end
+
XMLRPC::DateTime.new(*a)
+ #if a[0] >= 1970 then
+ # Time.gm(*a)
+ #else
+ # Date.new(*a[0,3])
+ #end
else
- raise "wrong dateTime.iso8601 format " + str
+ raise "wrong dateTime.iso8601 format"
end
end
@@ -128,13 +112,31 @@ module XMLRPC
begin
mod = Module
klass.split("::").each {|const| mod = mod.const_get(const.strip)}
-
- obj = mod.allocate
- hash.delete "___class___"
- hash.each {|key, value|
- obj.instance_variable_set("@#{ key }", value) if key =~ /^([\w_][\w_0-9]*)$/
+ Thread.critical = true
+ # let initialize take 0 parameters
+ mod.module_eval %{
+ begin
+ alias __initialize initialize
+ rescue NameError
+ end
+ def initialize; end
+ }
+
+ obj = mod.new
+
+ # restore old initialize
+ mod.module_eval %{
+ undef initialize
+ begin
+ alias initialize __initialize
+ rescue NameError
+ end
}
+ Thread.critical = false
+
+ hash.delete "___class___"
+ hash.each {|k,v| obj.__set_instance_variable(k, v) }
obj
rescue
hash
@@ -580,9 +582,12 @@ module XMLRPC
class XMLStreamParser < AbstractStreamParser
def initialize
require "xmlparser"
- @parser_class = Class.new(::XMLParser) {
- include StreamParserMixin
+ eval %{
+ class XMLRPCParser < ::XMLParser
+ include StreamParserMixin
+ end
}
+ @parser_class = XMLRPCParser
end
end # class XMLStreamParser
# ---------------------------------------------------------------------------
@@ -796,16 +801,6 @@ module XMLRPC
NQXMLStreamParser, NQXMLTreeParser,
REXMLStreamParser, XMLScanStreamParser]
- # yields an instance of each installed parser
- def self.each_installed_parser
- XMLRPC::XMLParser::Classes.each do |klass|
- begin
- yield klass.new
- rescue LoadError
- end
- end
- end
-
end # module XMLParser
diff --git a/lib/xmlrpc/server.rb b/lib/xmlrpc/server.rb
index 59a5869408..0ef3ca4c93 100644
--- a/lib/xmlrpc/server.rb
+++ b/lib/xmlrpc/server.rb
@@ -1,6 +1,6 @@
=begin
= xmlrpc/server.rb
-Copyright (C) 2001, 2002, 2003, 2005 by Michael Neumann (mneumann@ntecs.de)
+Copyright (C) 2001, 2002, 2003 by Michael Neumann (mneumann@ntecs.de)
Released under the same term of license as Ruby.
@@ -145,6 +145,7 @@ the same class.
require "xmlrpc/parser"
require "xmlrpc/create"
require "xmlrpc/config"
+require "xmlrpc/httpserver"
require "xmlrpc/utils" # ParserWriterChooseMixin
@@ -322,11 +323,11 @@ class BasicServer
def dispatch(methodname, *args)
for name, obj in @handler
if obj.kind_of? Proc
- next unless methodname == name
+ next unless methodname == name
else
- next unless methodname =~ /^#{name}(.+)$/
+ next unless methodname =~ /^#{name}(.+)$/
next unless obj.respond_to? $1
- obj = obj.method($1)
+ obj = obj.method($1)
end
if check_arity(obj, args.size)
@@ -447,7 +448,7 @@ class CGIServer < BasicServer
length = ENV['CONTENT_LENGTH'].to_i
http_error(405, "Method Not Allowed") unless ENV['REQUEST_METHOD'] == "POST"
- http_error(400, "Bad Request") unless parse_content_type(ENV['CONTENT_TYPE']).first == "text/xml"
+ http_error(400, "Bad Request") unless ENV['CONTENT_TYPE'] == "text/xml"
http_error(411, "Length Required") unless length > 0
# TODO: do we need a call to binmode?
@@ -456,7 +457,7 @@ class CGIServer < BasicServer
http_error(400, "Bad Request") if data.nil? or data.size != length
- http_write(process(data), "Content-type" => "text/xml; charset=utf-8")
+ http_write(process(data), "Content-type" => "text/xml")
}
end
@@ -531,7 +532,7 @@ class ModRubyServer < BasicServer
http_error(400, "Bad Request") if data.nil? or data.size != length
- http_write(process(data), 200, "Content-type" => "text/xml; charset=utf-8")
+ http_write(process(data), 200, "Content-type" => "text/xml")
}
end
@@ -572,6 +573,9 @@ class ModRubyServer < BasicServer
end
+
+
+
=begin
= XMLRPC::Server
== Synopsis
@@ -603,7 +607,7 @@ Implements a standalone XML-RPC server. The method (({serve}))) is left if a SIG
program.
== Superclass
-((<XMLRPC::WEBrickServlet>))
+((<XMLRPC::BasicServer>))
== Class Methods
--- XMLRPC::Server.new( port=8080, host="127.0.0.1", maxConnections=4, stdlog=$stdout, audit=true, debug=true, *a )
@@ -611,10 +615,12 @@ program.
port ((|port|)) and accepts requests for the host ((|host|)), which is by default only the localhost.
The server is not started, to start it you have to call ((<serve|XMLRPC::Server#serve>)).
- Parameters ((|audit|)) and ((|debug|)) are obsolete!
+ The parameters ((|maxConnections|)), ((|stdlog|)), ((|audit|)) and ((|debug|)) are passed to the HTTP server and
+ specify it's behaviour more precise.
All additionally given parameters in ((|*a|)) are by-passed to ((<XMLRPC::BasicServer.new>)).
+
== Instance Methods
--- XMLRPC::Server#serve
Call this after you have added all you handlers to the server.
@@ -622,19 +628,23 @@ program.
--- XMLRPC::Server#shutdown
Stops and shuts the server down.
+
+--- XMLRPC::Server#set_valid_ip( *ip_addr )
+ Specifies the valid IP addresses that are allowed to connect to the server.
+ Each IP is either a (({String})) or a (({Regexp})).
+
+--- XMLRPC::Server#get_valid_ip
+ Return the via method ((<set_valid_ip|XMLRPC::Server#set_valid_ip>)) specified
+ valid IP addresses.
=end
-class WEBrickServlet < BasicServer; end # forward declaration
-
-class Server < WEBrickServlet
+class Server < BasicServer
def initialize(port=8080, host="127.0.0.1", maxConnections=4, stdlog=$stdout, audit=true, debug=true, *a)
super(*a)
- require 'webrick'
- @server = WEBrick::HTTPServer.new(:Port => port, :BindAddress => host, :MaxClients => maxConnections,
- :Logger => WEBrick::Log.new(stdlog))
- @server.mount("/", self)
+ @server = ::HttpServer.new(self, port, host, maxConnections, stdlog, audit, debug)
+ @valid_ip = nil
end
def serve
@@ -645,15 +655,87 @@ class Server < WEBrickServlet
end
trap(signal) { @server.shutdown }
- @server.start
+ @server.start.join
end
def shutdown
@server.shutdown
end
-
+
+ def set_valid_ip(*ip_addr)
+ if ip_addr.size == 1 and ip_addr[0].nil?
+ @valid_ip = nil
+ else
+ @valid_ip = ip_addr
+ end
+ end
+
+ def get_valid_ip
+ @valid_ip
+ end
+
+ # methods that get called by HttpServer ------------------------------------------
+
+ def request_handler(request, response)
+ $stderr.puts "in request_handler" if $DEBUG
+
+ if request.method != "POST"
+ # Method not allowed
+ response.status = 405
+ return
+ end
+
+ if parse_content_type(request.header['Content-type']).first != "text/xml"
+ # Bad request
+ response.status = 400
+ return
+ end
+
+ length = request.content_length || 0
+
+ unless length > 0
+ # Length required
+ response.status = 411
+ return
+ end
+
+ data = request.data.read(length)
+
+ if data.nil? or data.size != length
+ # Bad request
+ response.status = 400
+ return
+ end
+
+ resp = process(data)
+ raise if resp.nil? or resp.size <= 0 # => Internal Server Error
+
+ response.status = 200
+ response.header['Content-Length'] = resp.size
+ response.header['Content-Type'] = "text/xml"
+ response.body = resp
+
+ end
+
+ ##
+ # Is called before request_handler and should return true if
+ # the client is allowed to connect to the server.
+ # `io' is a Socket object.
+ def ip_auth_handler(io)
+ if @valid_ip
+ client_ip = io.peeraddr[3]
+ @valid_ip.each { |ip|
+ return true if client_ip =~ ip
+ }
+ false
+ else
+ true
+ end
+ end
+
end
+
=begin
= XMLRPC::WEBrickServlet
== Synopsis
@@ -683,17 +765,6 @@ end
httpserver.mount("/RPC2", s)
trap("HUP") { httpserver.shutdown } # use 1 instead of "HUP" on Windows
httpserver.start
-
-== Instance Methods
-
---- XMLRPC::WEBrickServlet#set_valid_ip( *ip_addr )
- Specifies the valid IP addresses that are allowed to connect to the server.
- Each IP is either a (({String})) or a (({Regexp})).
-
---- XMLRPC::WEBrickServlet#get_valid_ip
- Return the via method ((<set_valid_ip|XMLRPC::Server#set_valid_ip>)) specified
- valid IP addresses.
-
== Description
Implements a servlet for use with WEBrick, a pure Ruby (HTTP-) server framework.
@@ -706,7 +777,6 @@ class WEBrickServlet < BasicServer
def initialize(*a)
super
require "webrick/httpstatus"
- @valid_ip = nil
end
# deprecated from WEBrick/1.2.2.
@@ -720,51 +790,34 @@ class WEBrickServlet < BasicServer
self
end
- def set_valid_ip(*ip_addr)
- if ip_addr.size == 1 and ip_addr[0].nil?
- @valid_ip = nil
- else
- @valid_ip = ip_addr
- end
- end
-
- def get_valid_ip
- @valid_ip
- end
-
def service(request, response)
-
- if @valid_ip
- raise WEBrick::HTTPStatus::Forbidden unless @valid_ip.any? { |ip| request.peeraddr[3] =~ ip }
- end
-
if request.request_method != "POST"
- raise WEBrick::HTTPStatus::MethodNotAllowed,
+ raise HTTPStatus::MethodNotAllowed,
"unsupported method `#{request.request_method}'."
end
if parse_content_type(request['Content-type']).first != "text/xml"
- raise WEBrick::HTTPStatus::BadRequest
+ raise HTTPStatus::BadRequest
end
length = (request['Content-length'] || 0).to_i
- raise WEBrick::HTTPStatus::LengthRequired unless length > 0
+ raise HTTPStatus::LengthRequired unless length > 0
data = request.body
if data.nil? or data.size != length
- raise WEBrick::HTTPStatus::BadRequest
+ raise HTTPStatus::BadRequest
end
resp = process(data)
if resp.nil? or resp.size <= 0
- raise WEBrick::HTTPStatus::InternalServerError
+ raise HTTPStatus::InternalServerError
end
response.status = 200
response['Content-Length'] = resp.size
- response['Content-Type'] = "text/xml; charset=utf-8"
+ response['Content-Type'] = "text/xml"
response.body = resp
end
end
diff --git a/lib/xmlrpc/utils.rb b/lib/xmlrpc/utils.rb
index 85c6bba372..14dd08b21d 100644
--- a/lib/xmlrpc/utils.rb
+++ b/lib/xmlrpc/utils.rb
@@ -17,6 +17,13 @@ module XMLRPC
# key/value pair "___class___" => ClassName
#
module Marshallable
+ def __get_instance_variables
+ instance_variables.collect {|var| [var[1..-1], eval(var)] }
+ end
+
+ def __set_instance_variable(key, value)
+ eval("@#$1 = value") if key =~ /^([\w_][\w_0-9]*)$/
+ end
end
@@ -131,7 +138,7 @@ module XMLRPC
def get_methods(obj, delim=".")
prefix = @prefix + delim
- obj.class.public_instance_methods(false).collect { |name|
+ obj.class.public_instance_methods.collect { |name|
[prefix + name, obj.method(name).to_proc, nil, nil]
}
end
diff --git a/lib/xsd/charset.rb b/lib/xsd/charset.rb
index 15d5500fce..362f13edfc 100644
--- a/lib/xsd/charset.rb
+++ b/lib/xsd/charset.rb
@@ -1,5 +1,5 @@
# XSD4R - Charset handling library.
-# Copyright (C) 2001, 2003, 2005 NAKAMURA, Hiroshi <nahi@ruby-lang.org>.
+# Copyright (C) 2001, 2003 NAKAMURA, Hiroshi <nahi@ruby-lang.org>.
# This program is copyrighted free software by NAKAMURA, Hiroshi. You can
# redistribute it and/or modify it under the same terms of Ruby's license;
@@ -10,7 +10,7 @@ module XSD
module Charset
- @internal_encoding = $KCODE
+ @encoding = $KCODE
class XSDError < StandardError; end
class CharsetError < XSDError; end
@@ -24,40 +24,27 @@ public
#
EncodingConvertMap = {}
def Charset.init
- EncodingConvertMap[['UTF8', 'X_ISO8859_1']] =
- Proc.new { |str| str.unpack('U*').pack('C*') }
- EncodingConvertMap[['X_ISO8859_1', 'UTF8']] =
- Proc.new { |str| str.unpack('C*').pack('U*') }
begin
require 'xsd/iconvcharset'
- @internal_encoding = 'UTF8'
- sjtag = (/(mswin|bccwin|mingw|cygwin|emx)/ =~ RUBY_PLATFORM) ? 'cp932' :
- 'shift_jis'
- EncodingConvertMap[['UTF8', 'EUC' ]] =
- Proc.new { |str| IconvCharset.safe_iconv("euc-jp", "utf-8", str) }
- EncodingConvertMap[['EUC' , 'UTF8']] =
- Proc.new { |str| IconvCharset.safe_iconv("utf-8", "euc-jp", str) }
- EncodingConvertMap[['EUC' , 'SJIS']] =
- Proc.new { |str| IconvCharset.safe_iconv(sjtag, "euc-jp", str) }
- EncodingConvertMap[['UTF8', 'SJIS']] =
- Proc.new { |str| IconvCharset.safe_iconv(sjtag, "utf-8", str) }
- EncodingConvertMap[['SJIS', 'UTF8']] =
- Proc.new { |str| IconvCharset.safe_iconv("utf-8", sjtag, str) }
- EncodingConvertMap[['SJIS', 'EUC' ]] =
- Proc.new { |str| IconvCharset.safe_iconv("euc-jp", sjtag, str) }
+ @encoding = 'UTF8'
+ sjtag = (/(mswin|bccwin|mingw|cygwin|emx)/ =~ RUBY_PLATFORM) ? 'cp932' : 'shift_jis'
+ EncodingConvertMap[['UTF8', 'EUC' ]] = Proc.new { |str| IconvCharset.safe_iconv("euc-jp", "utf-8", str) }
+ EncodingConvertMap[['EUC' , 'UTF8']] = Proc.new { |str| IconvCharset.safe_iconv("utf-8", "euc-jp", str) }
+ EncodingConvertMap[['EUC' , 'SJIS']] = Proc.new { |str| IconvCharset.safe_iconv(sjtag, "euc-jp", str) }
+ EncodingConvertMap[['UTF8', 'SJIS']] = Proc.new { |str| IconvCharset.safe_iconv(sjtag, "utf-8", str) }
+ EncodingConvertMap[['SJIS', 'UTF8']] = Proc.new { |str| IconvCharset.safe_iconv("utf-8", sjtag, str) }
+ EncodingConvertMap[['SJIS', 'EUC' ]] = Proc.new { |str| IconvCharset.safe_iconv("euc-jp", sjtag, str) }
rescue LoadError
begin
require 'nkf'
- EncodingConvertMap[['EUC' , 'SJIS']] =
- Proc.new { |str| NKF.nkf('-sXm0', str) }
- EncodingConvertMap[['SJIS', 'EUC' ]] =
- Proc.new { |str| NKF.nkf('-eXm0', str) }
+ EncodingConvertMap[['EUC' , 'SJIS']] = Proc.new { |str| NKF.nkf('-sXm0', str) }
+ EncodingConvertMap[['SJIS', 'EUC' ]] = Proc.new { |str| NKF.nkf('-eXm0', str) }
rescue LoadError
end
begin
require 'uconv'
- @internal_encoding = 'UTF8'
+ @encoding = 'UTF8'
EncodingConvertMap[['UTF8', 'EUC' ]] = Uconv.method(:u8toeuc)
EncodingConvertMap[['UTF8', 'SJIS']] = Uconv.method(:u8tosjis)
EncodingConvertMap[['EUC' , 'UTF8']] = Uconv.method(:euctou8)
@@ -73,8 +60,6 @@ public
'EUC' => 'euc-jp',
'SJIS' => 'shift_jis',
'UTF8' => 'utf-8',
- 'X_ISO_8859_1' => 'iso-8859-1',
- 'X_UNKNOWN' => nil,
}
@@ -82,24 +67,24 @@ public
## handlers
#
def Charset.encoding
- @internal_encoding
+ @encoding
end
def Charset.encoding=(encoding)
- warn("xsd charset is set to #{encoding}") if $DEBUG
- @internal_encoding = encoding
+ STDERR.puts("xsd charset is set to #{encoding}") if $DEBUG
+ @encoding = encoding
end
- def Charset.xml_encoding_label
- charset_label(@internal_encoding)
+ def Charset.encoding_label
+ charset_label(@encoding)
end
def Charset.encoding_to_xml(str, charset)
- encoding_conv(str, @internal_encoding, charset_str(charset))
+ encoding_conv(str, @encoding, charset_str(charset))
end
def Charset.encoding_from_xml(str, charset)
- encoding_conv(str, charset_str(charset), @internal_encoding)
+ encoding_conv(str, charset_str(charset), @encoding)
end
def Charset.encoding_conv(str, enc_from, enc_to)
@@ -109,7 +94,7 @@ public
converter.call(str)
else
raise CharsetConversionError.new(
- "Converter not found: #{enc_from} -> #{enc_to}")
+ "Converter not found: #{ enc_from } -> #{ enc_to }")
end
end
@@ -118,27 +103,23 @@ public
end
def Charset.charset_str(label)
- if CharsetMap.respond_to?(:key)
- CharsetMap.key(label.downcase) || 'X_UNKNOWN'
- else
- CharsetMap.index(label.downcase) || 'X_UNKNOWN'
- end
+ CharsetMap.index(label.downcase)
end
# us_ascii = '[\x00-\x7F]'
us_ascii = '[\x9\xa\xd\x20-\x7F]' # XML 1.0 restricted.
- USASCIIRegexp = Regexp.new("\\A#{us_ascii}*\\z", nil, "NONE")
+ USASCIIRegexp = Regexp.new("\\A#{ us_ascii }*\\z", nil, "NONE")
twobytes_euc = '(?:[\x8E\xA1-\xFE][\xA1-\xFE])'
threebytes_euc = '(?:\x8F[\xA1-\xFE][\xA1-\xFE])'
- character_euc = "(?:#{us_ascii}|#{twobytes_euc}|#{threebytes_euc})"
- EUCRegexp = Regexp.new("\\A#{character_euc}*\\z", nil, "NONE")
+ character_euc = "(?:#{ us_ascii }|#{ twobytes_euc }|#{ threebytes_euc })"
+ EUCRegexp = Regexp.new("\\A#{ character_euc }*\\z", nil, "NONE")
# onebyte_sjis = '[\x00-\x7F\xA1-\xDF]'
onebyte_sjis = '[\x9\xa\xd\x20-\x7F\xA1-\xDF]' # XML 1.0 restricted.
twobytes_sjis = '(?:[\x81-\x9F\xE0-\xFC][\x40-\x7E\x80-\xFC])'
- character_sjis = "(?:#{onebyte_sjis}|#{twobytes_sjis})"
- SJISRegexp = Regexp.new("\\A#{character_sjis}*\\z", nil, "NONE")
+ character_sjis = "(?:#{ onebyte_sjis }|#{ twobytes_sjis })"
+ SJISRegexp = Regexp.new("\\A#{ character_sjis }*\\z", nil, "NONE")
# 0xxxxxxx
# 110yyyyy 10xxxxxx
@@ -147,9 +128,8 @@ public
threebytes_utf8 = '(?:[\xE0-\xEF][\x80-\xBF][\x80-\xBF])'
# 11110uuu 10uuuzzz 10yyyyyy 10xxxxxx
fourbytes_utf8 = '(?:[\xF0-\xF7][\x80-\xBF][\x80-\xBF][\x80-\xBF])'
- character_utf8 =
- "(?:#{us_ascii}|#{twobytes_utf8}|#{threebytes_utf8}|#{fourbytes_utf8})"
- UTF8Regexp = Regexp.new("\\A#{character_utf8}*\\z", nil, "NONE")
+ character_utf8 = "(?:#{ us_ascii }|#{ twobytes_utf8 }|#{ threebytes_utf8 }|#{ fourbytes_utf8 })"
+ UTF8Regexp = Regexp.new("\\A#{ character_utf8 }*\\z", nil, "NONE")
def Charset.is_us_ascii(str)
USASCIIRegexp =~ str
@@ -178,7 +158,7 @@ public
when 'SJIS'
is_sjis(str)
else
- raise UnknownCharsetError.new("Unknown charset: #{code}")
+ raise UnknownCharsetError.new("Unknown charset: #{ code }")
end
end
end
diff --git a/lib/xsd/codegen/classdef.rb b/lib/xsd/codegen/classdef.rb
index 9eb1ce6607..8f72e95efd 100644
--- a/lib/xsd/codegen/classdef.rb
+++ b/lib/xsd/codegen/classdef.rb
@@ -77,7 +77,7 @@ class ClassDef < ModuleDef
end
buf << dump_class_def_end
buf << dump_package_def_end(package) unless package.empty?
- buf.gsub(/^\s+$/, '')
+ buf
end
private
diff --git a/lib/xsd/codegen/commentdef.rb b/lib/xsd/codegen/commentdef.rb
index c9493a1363..f98fade57d 100644
--- a/lib/xsd/codegen/commentdef.rb
+++ b/lib/xsd/codegen/commentdef.rb
@@ -21,10 +21,10 @@ module CommentDef
private
def dump_comment
- if /\A#/ =~ @comment
+ if /^#/ =~ @comment
format(@comment)
else
- format(@comment).gsub(/^/, '# ')
+ format(@comment).gsub(/^/, "# ")
end
end
end
diff --git a/lib/xsd/codegen/gensupport.rb b/lib/xsd/codegen/gensupport.rb
index 1e85d3668f..df90550fa0 100644
--- a/lib/xsd/codegen/gensupport.rb
+++ b/lib/xsd/codegen/gensupport.rb
@@ -1,5 +1,5 @@
# XSD4R - Code generation support
-# Copyright (C) 2004, 2005 NAKAMURA, Hiroshi <nahi@ruby-lang.org>.
+# Copyright (C) 2004 NAKAMURA, Hiroshi <nahi@ruby-lang.org>.
# This program is copyrighted free software by NAKAMURA, Hiroshi. You can
# redistribute it and/or modify it under the same terms of Ruby's license;
@@ -9,50 +9,6 @@
module XSD
module CodeGen
-# from the file 'keywords' in 1.9.
-KEYWORD = {}
-%w(
-__LINE__
-__FILE__
-BEGIN
-END
-alias
-and
-begin
-break
-case
-class
-def
-defined?
-do
-else
-elsif
-end
-ensure
-false
-for
-if
-in
-module
-next
-nil
-not
-or
-redo
-rescue
-retry
-return
-self
-super
-then
-true
-undef
-unless
-until
-when
-while
-yield
-).each { |k| KEYWORD[k] = nil }
module GenSupport
def capitalize(target)
@@ -69,7 +25,7 @@ module GenSupport
safename = name.scan(/[a-zA-Z0-9_]+/).collect { |ele|
GenSupport.capitalize(ele)
}.join
- if /^[A-Z]/ !~ safename or keyword?(safename)
+ unless /^[A-Z]/ =~ safename
safename = "C_#{safename}"
end
safename
@@ -77,17 +33,12 @@ module GenSupport
module_function :safeconstname
def safeconstname?(name)
- /\A[A-Z][a-zA-Z0-9_]*\z/ =~ name and !keyword?(name)
+ /\A[A-Z][a-zA-Z0-9_]*\z/ =~ name
end
module_function :safeconstname?
def safemethodname(name)
- safename = name.scan(/[a-zA-Z0-9_]+/).join('_')
- safename = uncapitalize(safename)
- if /^[a-z]/ !~ safename
- safename = "m_#{safename}"
- end
- safename
+ safevarname(name)
end
module_function :safemethodname
@@ -97,25 +48,20 @@ module GenSupport
module_function :safemethodname?
def safevarname(name)
- safename = uncapitalize(name.scan(/[a-zA-Z0-9_]+/).join('_'))
- if /^[a-z]/ !~ safename or keyword?(safename)
- "v_#{safename}"
- else
- safename
+ safename = name.scan(/[a-zA-Z0-9_]+/).join('_')
+ safename = uncapitalize(safename)
+ unless /^[a-z]/ =~ safename
+ safename = "m_#{safename}"
end
+ safename
end
module_function :safevarname
def safevarname?(name)
- /\A[a-z_][a-zA-Z0-9_]*\z/ =~ name and !keyword?(name)
+ /\A[a-z_][a-zA-Z0-9_]*\z/ =~ name
end
module_function :safevarname?
- def keyword?(word)
- KEYWORD.key?(word)
- end
- module_function :keyword?
-
def format(str, indent = nil)
str = trim_eol(str)
str = trim_indent(str)
@@ -130,7 +76,7 @@ private
def trim_eol(str)
str.collect { |line|
- line.sub(/\r?\n\z/, "") + "\n"
+ line.sub(/\r?\n$/, "") + "\n"
}.join
end
diff --git a/lib/xsd/codegen/methoddef.rb b/lib/xsd/codegen/methoddef.rb
index 15892fc5bf..797a4f024e 100644
--- a/lib/xsd/codegen/methoddef.rb
+++ b/lib/xsd/codegen/methoddef.rb
@@ -22,7 +22,7 @@ class MethodDef
def initialize(name, *params)
unless safemethodname?(name)
- raise ArgumentError.new("name '#{name}' seems to be unsafe")
+ raise ArgumentError.new("#{name} seems to be unsafe")
end
@name = name
@params = params
@@ -34,7 +34,7 @@ class MethodDef
buf = ""
buf << dump_comment if @comment
buf << dump_method_def
- buf << dump_definition if @definition and !@definition.empty?
+ buf << dump_definition if @definition
buf << dump_method_def_end
buf
end
diff --git a/lib/xsd/codegen/moduledef.rb b/lib/xsd/codegen/moduledef.rb
index 744af2ff97..dc2746b2ee 100644
--- a/lib/xsd/codegen/moduledef.rb
+++ b/lib/xsd/codegen/moduledef.rb
@@ -89,7 +89,7 @@ class ModuleDef
end
buf << dump_module_def_end
buf << dump_package_def_end(package) unless package.empty?
- buf.gsub(/^\s+$/, '')
+ buf
end
private
diff --git a/lib/xsd/datatypes.rb b/lib/xsd/datatypes.rb
index bbe6c8578f..7173f52d65 100644
--- a/lib/xsd/datatypes.rb
+++ b/lib/xsd/datatypes.rb
@@ -46,30 +46,10 @@ AnyURILiteral = 'anyURI'
QNameLiteral = 'QName'
NormalizedStringLiteral = 'normalizedString'
-#3.3.2 token
-#3.3.3 language
-#3.3.4 NMTOKEN
-#3.3.5 NMTOKENS
-#3.3.6 Name
-#3.3.7 NCName
-#3.3.8 ID
-#3.3.9 IDREF
-#3.3.10 IDREFS
-#3.3.11 ENTITY
-#3.3.12 ENTITIES
IntegerLiteral = 'integer'
-NonPositiveIntegerLiteral = 'nonPositiveInteger'
-NegativeIntegerLiteral = 'negativeInteger'
LongLiteral = 'long'
IntLiteral = 'int'
ShortLiteral = 'short'
-ByteLiteral = 'byte'
-NonNegativeIntegerLiteral = 'nonNegativeInteger'
-UnsignedLongLiteral = 'unsignedLong'
-UnsignedIntLiteral = 'unsignedInt'
-UnsignedShortLiteral = 'unsignedShort'
-UnsignedByteLiteral = 'unsignedByte'
-PositiveIntegerLiteral = 'positiveInteger'
AttrTypeName = QName.new(InstanceNamespace, AttrType)
AttrNilName = QName.new(InstanceNamespace, NilLiteral)
@@ -98,10 +78,7 @@ class NSDBase
end
def initialize
- end
-
- def init(type)
- @type = type
+ @type = nil
end
end
@@ -119,7 +96,11 @@ class XSDAnySimpleType < NSDBase
attr_accessor :is_nil
def initialize(value = nil)
- init(Type, value)
+ super()
+ @type = Type
+ @data = nil
+ @is_nil = true
+ set(value) if value
end
# true or raise
@@ -134,7 +115,6 @@ class XSDAnySimpleType < NSDBase
if value.nil?
@is_nil = true
@data = nil
- _set(nil)
else
@is_nil = false
_set(screen_data(value))
@@ -152,11 +132,6 @@ class XSDAnySimpleType < NSDBase
private
- def init(type, value)
- super(type)
- set(value)
- end
-
# raises ValueSpaceError if check failed
def screen_data(value)
value
@@ -176,7 +151,9 @@ class XSDNil < XSDAnySimpleType
Value = 'true'
def initialize(value = nil)
- init(Type, value)
+ super()
+ @type = Type
+ set(value)
end
end
@@ -188,7 +165,9 @@ class XSDString < XSDAnySimpleType
Type = QName.new(Namespace, StringLiteral)
def initialize(value = nil)
- init(Type, value)
+ super()
+ @type = Type
+ set(value) if value
end
private
@@ -205,7 +184,9 @@ class XSDBoolean < XSDAnySimpleType
Type = QName.new(Namespace, BooleanLiteral)
def initialize(value = nil)
- init(Type, value)
+ super()
+ @type = Type
+ set(value)
end
private
@@ -230,7 +211,12 @@ class XSDDecimal < XSDAnySimpleType
Type = QName.new(Namespace, DecimalLiteral)
def initialize(value = nil)
- init(Type, value)
+ super()
+ @type = Type
+ @sign = ''
+ @number = ''
+ @point = 0
+ set(value) if value
end
def nonzero?
@@ -270,12 +256,8 @@ private
[sign, point, number]
end
- def _set(data)
- if data.nil?
- @sign = @point = @number = @data = nil
- return
- end
- @sign, @point, @number = data
+ def _set(pair)
+ @sign, @point, @number = pair
@data = _to_s
@data.freeze
end
@@ -304,7 +286,9 @@ class XSDFloat < XSDAnySimpleType
Type = QName.new(Namespace, FloatLiteral)
def initialize(value = nil)
- init(Type, value)
+ super()
+ @type = Type
+ set(value) if value
end
private
@@ -370,7 +354,9 @@ class XSDDouble < XSDAnySimpleType
Type = QName.new(Namespace, DoubleLiteral)
def initialize(value = nil)
- init(Type, value)
+ super()
+ @type = Type
+ set(value) if value
end
private
@@ -431,7 +417,16 @@ class XSDDuration < XSDAnySimpleType
attr_accessor :sec
def initialize(value = nil)
- init(Type, value)
+ super()
+ @type = Type
+ @sign = nil
+ @year = nil
+ @month = nil
+ @day = nil
+ @hour = nil
+ @min = nil
+ @sec = nil
+ set(value) if value
end
private
@@ -455,12 +450,8 @@ private
[sign, year, month, day, hour, min, sec]
end
- def _set(data)
- if data.nil?
- @sign = @year = @month = @day = @hour = @min = @sec = @data = nil
- return
- end
- @sign, @year, @month, @day, @hour, @min, @sec = data
+ def _set(ary)
+ @sign, @year, @month, @day, @hour, @min, @sec = ary
@data = _to_s
@data.freeze
end
@@ -495,18 +486,6 @@ require 'date'
module XSDDateTimeImpl
SecInDay = 86400 # 24 * 60 * 60
- def to_obj(klass)
- if klass == Time
- to_time
- elsif klass == Date
- to_date
- elsif klass == DateTime
- to_datetime
- else
- nil
- end
- end
-
def to_time
begin
if @data.offset * SecInDay == Time.now.utc_offset
@@ -523,14 +502,6 @@ module XSDDateTimeImpl
end
end
- def to_date
- Date.new0(@data.class.jd_to_ajd(@data.jd, 0, 0), 0, @data.start)
- end
-
- def to_datetime
- data
- end
-
def tz2of(str)
/^(?:Z|(?:([+\-])(\d\d):(\d\d))?)$/ =~ str
sign = $1
@@ -559,21 +530,15 @@ module XSDDateTimeImpl
end
def screen_data(t)
- # convert t to a DateTime as an internal representation.
- if t.respond_to?(:to_datetime) # 1.9 or later
- t.to_datetime
- elsif t.is_a?(DateTime)
- t
- elsif t.is_a?(Date)
- t = screen_data_str(t)
- t <<= 12 if t.year < 0
+ if (t.is_a?(Date))
t
- elsif t.is_a?(Time)
- jd = DateTime.civil_to_jd(t.year, t.mon, t.mday, DateTime::ITALY)
- fr = DateTime.time_to_day_fraction(t.hour, t.min, [t.sec, 59].min) +
- t.usec.to_r / 1000000 / SecInDay
+ elsif (t.is_a?(Time))
+ sec, min, hour, mday, month, year = t.to_a[0..5]
+ diffday = t.usec.to_r / 1000000 / SecInDay
of = t.utc_offset.to_r / SecInDay
- DateTime.new0(DateTime.jd_to_ajd(jd, fr, of), of, DateTime::ITALY)
+ data = DateTime.civil(year, month, mday, hour, min, sec, of)
+ data += diffday
+ data
else
screen_data_str(t)
end
@@ -589,7 +554,10 @@ class XSDDateTime < XSDAnySimpleType
Type = QName.new(Namespace, DateTimeLiteral)
def initialize(value = nil)
- init(Type, value)
+ super()
+ @type = Type
+ @secfrac = nil
+ set(value) if value
end
private
@@ -623,12 +591,8 @@ private
[data, secfrac]
end
- def _set(data)
- if data.nil?
- @data = @secfrac = nil
- return
- end
- @data, @secfrac = data
+ def _set(pair)
+ @data, @secfrac = pair
end
def _to_s
@@ -652,7 +616,10 @@ class XSDTime < XSDAnySimpleType
Type = QName.new(Namespace, TimeLiteral)
def initialize(value = nil)
- init(Type, value)
+ super()
+ @type = Type
+ @secfrac = nil
+ set(value) if value
end
private
@@ -675,12 +642,8 @@ private
[data, secfrac]
end
- def _set(data)
- if data.nil?
- @data = @secfrac = nil
- return
- end
- @data, @secfrac = data
+ def _set(pair)
+ @data, @secfrac = pair
end
def _to_s
@@ -702,7 +665,9 @@ class XSDDate < XSDAnySimpleType
Type = QName.new(Namespace, DateLiteral)
def initialize(value = nil)
- init(Type, value)
+ super()
+ @type = Type
+ set(value) if value
end
private
@@ -734,7 +699,9 @@ class XSDGYearMonth < XSDAnySimpleType
Type = QName.new(Namespace, GYearMonthLiteral)
def initialize(value = nil)
- init(Type, value)
+ super()
+ @type = Type
+ set(value) if value
end
private
@@ -765,7 +732,9 @@ class XSDGYear < XSDAnySimpleType
Type = QName.new(Namespace, GYearLiteral)
def initialize(value = nil)
- init(Type, value)
+ super()
+ @type = Type
+ set(value) if value
end
private
@@ -795,7 +764,9 @@ class XSDGMonthDay < XSDAnySimpleType
Type = QName.new(Namespace, GMonthDayLiteral)
def initialize(value = nil)
- init(Type, value)
+ super()
+ @type = Type
+ set(value) if value
end
private
@@ -822,7 +793,9 @@ class XSDGDay < XSDAnySimpleType
Type = QName.new(Namespace, GDayLiteral)
def initialize(value = nil)
- init(Type, value)
+ super()
+ @type = Type
+ set(value) if value
end
private
@@ -848,7 +821,9 @@ class XSDGMonth < XSDAnySimpleType
Type = QName.new(Namespace, GMonthLiteral)
def initialize(value = nil)
- init(Type, value)
+ super()
+ @type = Type
+ set(value) if value
end
private
@@ -874,7 +849,9 @@ class XSDHexBinary < XSDAnySimpleType
# String in Ruby could be a binary.
def initialize(value = nil)
- init(Type, value)
+ super()
+ @type = Type
+ set(value) if value
end
def set_encoded(value)
@@ -901,7 +878,9 @@ class XSDBase64Binary < XSDAnySimpleType
# String in Ruby could be a binary.
def initialize(value = nil)
- init(Type, value)
+ super()
+ @type = Type
+ set(value) if value
end
def set_encoded(value)
@@ -927,7 +906,9 @@ class XSDAnyURI < XSDAnySimpleType
Type = QName.new(Namespace, AnyURILiteral)
def initialize(value = nil)
- init(Type, value)
+ super()
+ @type = Type
+ set(value) if value
end
private
@@ -945,7 +926,9 @@ class XSDQName < XSDAnySimpleType
Type = QName.new(Namespace, QNameLiteral)
def initialize(value = nil)
- init(Type, value)
+ super()
+ @type = Type
+ set(value) if value
end
private
@@ -960,12 +943,8 @@ private
[prefix, localpart]
end
- def _set(data)
- if data.nil?
- @prefix = @localpart = @data = nil
- return
- end
- @prefix, @localpart = data
+ def _set(pair)
+ @prefix, @localpart = pair
@data = _to_s
@data.freeze
end
@@ -987,7 +966,9 @@ class XSDNormalizedString < XSDString
Type = QName.new(Namespace, NormalizedStringLiteral)
def initialize(value = nil)
- init(Type, value)
+ super()
+ @type = Type
+ set(value) if value
end
private
@@ -1004,7 +985,9 @@ class XSDInteger < XSDDecimal
Type = QName.new(Namespace, IntegerLiteral)
def initialize(value = nil)
- init(Type, value)
+ super()
+ @type = Type
+ set(value) if value
end
private
@@ -1015,9 +998,6 @@ private
rescue ArgumentError
raise ValueSpaceError.new("#{ type }: cannot accept '#{ str }'.")
end
- unless validate(data)
- raise ValueSpaceError.new("#{ type }: cannot accept '#{ str }'.")
- end
data
end
@@ -1028,240 +1008,107 @@ private
def _to_s()
@data.to_s
end
-
- def validate(v)
- max = maxinclusive
- min = mininclusive
- (max.nil? or v <= max) and (min.nil? or v >= min)
- end
-
- def maxinclusive
- nil
- end
-
- def mininclusive
- nil
- end
-
- PositiveMinInclusive = 1
- def positive(v)
- PositiveMinInclusive <= v
- end
-end
-
-class XSDNonPositiveInteger < XSDInteger
- Type = QName.new(Namespace, NonPositiveIntegerLiteral)
-
- def initialize(value = nil)
- init(Type, value)
- end
-
-private
-
- def maxinclusive
- 0
- end
-
- def mininclusive
- nil
- end
-end
-
-class XSDNegativeInteger < XSDNonPositiveInteger
- Type = QName.new(Namespace, NegativeIntegerLiteral)
-
- def initialize(value = nil)
- init(Type, value)
- end
-
-private
-
- def maxinclusive
- -1
- end
-
- def mininclusive
- nil
- end
end
class XSDLong < XSDInteger
Type = QName.new(Namespace, LongLiteral)
def initialize(value = nil)
- init(Type, value)
- end
-
-private
-
- def maxinclusive
- +9223372036854775807
- end
-
- def mininclusive
- -9223372036854775808
- end
-end
-
-class XSDInt < XSDLong
- Type = QName.new(Namespace, IntLiteral)
-
- def initialize(value = nil)
- init(Type, value)
- end
-
-private
-
- def maxinclusive
- +2147483647
- end
-
- def mininclusive
- -2147483648
- end
-end
-
-class XSDShort < XSDInt
- Type = QName.new(Namespace, ShortLiteral)
-
- def initialize(value = nil)
- init(Type, value)
- end
-
-private
-
- def maxinclusive
- +32767
- end
-
- def mininclusive
- -32768
- end
-end
-
-class XSDByte < XSDShort
- Type = QName.new(Namespace, ByteLiteral)
-
- def initialize(value = nil)
- init(Type, value)
- end
-
-private
-
- def maxinclusive
- +127
- end
-
- def mininclusive
- -128
- end
-end
-
-class XSDNonNegativeInteger < XSDInteger
- Type = QName.new(Namespace, NonNegativeIntegerLiteral)
-
- def initialize(value = nil)
- init(Type, value)
+ super()
+ @type = Type
+ set(value) if value
end
private
- def maxinclusive
- nil
- end
-
- def mininclusive
- 0
- end
-end
-
-class XSDUnsignedLong < XSDNonNegativeInteger
- Type = QName.new(Namespace, UnsignedLongLiteral)
-
- def initialize(value = nil)
- init(Type, value)
+ def screen_data_str(str)
+ begin
+ data = Integer(str)
+ rescue ArgumentError
+ raise ValueSpaceError.new("#{ type }: cannot accept '#{ str }'.")
+ end
+ unless validate(data)
+ raise ValueSpaceError.new("#{ type }: cannot accept '#{ str }'.")
+ end
+ data
end
-private
-
- def maxinclusive
- +18446744073709551615
+ def _set(value)
+ @data = value
end
- def mininclusive
- 0
+ MaxInclusive = +9223372036854775807
+ MinInclusive = -9223372036854775808
+ def validate(v)
+ ((MinInclusive <= v) && (v <= MaxInclusive))
end
end
-class XSDUnsignedInt < XSDUnsignedLong
- Type = QName.new(Namespace, UnsignedIntLiteral)
+class XSDInt < XSDLong
+ Type = QName.new(Namespace, IntLiteral)
def initialize(value = nil)
- init(Type, value)
+ super()
+ @type = Type
+ set(value) if value
end
private
- def maxinclusive
- +4294967295
- end
-
- def mininclusive
- 0
- end
-end
-
-class XSDUnsignedShort < XSDUnsignedInt
- Type = QName.new(Namespace, UnsignedShortLiteral)
-
- def initialize(value = nil)
- init(Type, value)
+ def screen_data_str(str)
+ begin
+ data = Integer(str)
+ rescue ArgumentError
+ raise ValueSpaceError.new("#{ type }: cannot accept '#{ str }'.")
+ end
+ unless validate(data)
+ raise ValueSpaceError.new("#{ type }: cannot accept '#{ str }'.")
+ end
+ data
end
-private
-
- def maxinclusive
- +65535
+ def _set(value)
+ @data = value
end
- def mininclusive
- 0
+ MaxInclusive = +2147483647
+ MinInclusive = -2147483648
+ def validate(v)
+ ((MinInclusive <= v) && (v <= MaxInclusive))
end
end
-class XSDUnsignedByte < XSDUnsignedShort
- Type = QName.new(Namespace, UnsignedByteLiteral)
+class XSDShort < XSDInt
+ Type = QName.new(Namespace, ShortLiteral)
def initialize(value = nil)
- init(Type, value)
+ super()
+ @type = Type
+ set(value) if value
end
private
- def maxinclusive
- +255
- end
-
- def mininclusive
- 0
- end
-end
-
-class XSDPositiveInteger < XSDNonNegativeInteger
- Type = QName.new(Namespace, PositiveIntegerLiteral)
-
- def initialize(value = nil)
- init(Type, value)
+ def screen_data_str(str)
+ begin
+ data = Integer(str)
+ rescue ArgumentError
+ raise ValueSpaceError.new("#{ type }: cannot accept '#{ str }'.")
+ end
+ unless validate(data)
+ raise ValueSpaceError.new("#{ type }: cannot accept '#{ str }'.")
+ end
+ data
end
-private
-
- def maxinclusive
- nil
+ def _set(value)
+ @data = value
end
- def mininclusive
- 1
+ MaxInclusive = +32767
+ MinInclusive = -32768
+ def validate(v)
+ ((MinInclusive <= v) && (v <= MaxInclusive))
end
end
diff --git a/lib/xsd/iconvcharset.rb b/lib/xsd/iconvcharset.rb
index 7e629d569b..cac66515e2 100644
--- a/lib/xsd/iconvcharset.rb
+++ b/lib/xsd/iconvcharset.rb
@@ -22,7 +22,7 @@ class IconvCharset
out << e.success
ch, str = e.failed.split(//, 2)
out << '?'
- warn("Failed to convert #{ch}")
+ STDERR.puts("Failed to convert #{ch}")
retry
end
return out
diff --git a/lib/xsd/mapping.rb b/lib/xsd/mapping.rb
deleted file mode 100644
index 06d30d4cbf..0000000000
--- a/lib/xsd/mapping.rb
+++ /dev/null
@@ -1,42 +0,0 @@
-# XSD4R - XML Mapping for Ruby
-# Copyright (C) 2005 NAKAMURA, Hiroshi <nahi@ruby-lang.org>.
-
-# This program is copyrighted free software by NAKAMURA, Hiroshi. You can
-# redistribute it and/or modify it under the same terms of Ruby's license;
-# either the dual license version in 2003, or any later version.
-
-
-require "soap/parser"
-require 'soap/encodingstyle/literalHandler'
-require "soap/generator"
-require "soap/mapping"
-require "soap/mapping/wsdlliteralregistry"
-
-
-module XSD
-
-
-module Mapping
- MappingRegistry = SOAP::Mapping::WSDLLiteralRegistry.new
- MappingOpt = {:default_encodingstyle => SOAP::LiteralNamespace}
-
- def self.obj2xml(obj, elename = nil, io = nil)
- if !elename.nil? and !elename.is_a?(XSD::QName)
- elename = XSD::QName.new(nil, elename)
- end
- elename ||= XSD::QName.new(nil, SOAP::Mapping.name2elename(obj.class.to_s))
- soap = SOAP::Mapping.obj2soap(obj, MappingRegistry)
- soap.elename = elename
- generator = SOAP::SOAPGenerator.new(MappingOpt)
- generator.generate(soap, io)
- end
-
- def self.xml2obj(stream)
- parser = SOAP::Parser.new(MappingOpt)
- soap = parser.parse(stream)
- SOAP::Mapping.soap2obj(soap, MappingRegistry)
- end
-end
-
-
-end
diff --git a/lib/xsd/namedelements.rb b/lib/xsd/namedelements.rb
index a13396bb71..b6f909c1dc 100644
--- a/lib/xsd/namedelements.rb
+++ b/lib/xsd/namedelements.rb
@@ -1,5 +1,5 @@
# XSD4R - WSDL named element collection.
-# Copyright (C) 2002, 2003, 2005 NAKAMURA, Hiroshi <nahi@ruby-lang.org>.
+# Copyright (C) 2002, 2003 NAKAMURA, Hiroshi <nahi@ruby-lang.org>.
# This program is copyrighted free software by NAKAMURA, Hiroshi. You can
# redistribute it and/or modify it under the same terms of Ruby's license;
@@ -23,16 +23,6 @@ class NamedElements
o
end
- def freeze
- super
- @elements.freeze
- self
- end
-
- def empty?
- size == 0
- end
-
def size
@elements.size
end
@@ -49,10 +39,6 @@ class NamedElements
@elements.find { |item| item.name.name == name }
end
- def keys
- collect { |element| element.name }
- end
-
def each
@elements.each do |element|
yield(element)
@@ -79,8 +65,6 @@ class NamedElements
self
end
- Empty = NamedElements.new.freeze
-
protected
def elements=(rhs)
diff --git a/lib/xsd/ns.rb b/lib/xsd/ns.rb
index 53eeae7130..224db6c058 100644
--- a/lib/xsd/ns.rb
+++ b/lib/xsd/ns.rb
@@ -1,5 +1,5 @@
# XSD4R - XML Schema Namespace library
-# Copyright (C) 2000-2003, 2005 NAKAMURA, Hiroshi <nahi@ruby-lang.org>.
+# Copyright (C) 2000, 2001, 2002, 2003 NAKAMURA, Hiroshi <nahi@ruby-lang.org>.
# This program is copyrighted free software by NAKAMURA, Hiroshi. You can
# redistribute it and/or modify it under the same terms of Ruby's license;
@@ -20,7 +20,7 @@ class NS
def assign(ns)
@count += 1
- "n#{@count}"
+ "n#{ @count }"
end
end
@@ -54,7 +54,7 @@ public
end
def assigned?(ns)
- @default_namespace == ns or @ns2tag.key?(ns)
+ @ns2tag.key?(ns)
end
def assigned_tag?(tag)
@@ -72,9 +72,9 @@ public
if (name.namespace == @default_namespace)
name.name
elsif @ns2tag.key?(name.namespace)
- "#{@ns2tag[name.namespace]}:#{name.name}"
+ @ns2tag[name.namespace] + ':' << name.name
else
- raise FormatError.new("namespace: #{name.namespace} not defined yet")
+ raise FormatError.new('Namespace: ' << name.namespace << ' not defined yet.')
end
end
@@ -83,7 +83,7 @@ public
return true if (name == rhs)
end
@tag2ns.each do |assigned_tag, assigned_ns|
- if assigned_ns == ns && "#{assigned_tag}:#{name}" == rhs
+ if assigned_ns == ns && "#{ assigned_tag }:#{ name }" == rhs
return true
end
end
@@ -93,32 +93,22 @@ public
# $1 and $2 are necessary.
ParseRegexp = Regexp.new('^([^:]+)(?::(.+))?$')
- def parse(str, local = false)
- if ParseRegexp =~ str
- if (name = $2) and (ns = @tag2ns[$1])
- return XSD::QName.new(ns, name)
- end
- end
- XSD::QName.new(local ? nil : @default_namespace, str)
- end
-
- # For local attribute key parsing
- # <foo xmlns="urn:a" xmlns:n1="urn:a" bar="1" n1:baz="2" />
- # =>
- # {}bar, {urn:a}baz
- def parse_local(elem)
+ def parse(elem)
+ ns = nil
+ name = nil
ParseRegexp =~ elem
if $2
ns = @tag2ns[$1]
name = $2
if !ns
- raise FormatError.new("unknown namespace qualifier: #{$1}")
+ raise FormatError.new('Unknown namespace qualifier: ' << $1)
end
elsif $1
- ns = nil
+ ns = @default_namespace
name = $1
- else
- raise FormatError.new("illegal element format: #{elem}")
+ end
+ if !name
+ raise FormatError.new("Illegal element format: #{ elem }")
end
XSD::QName.new(ns, name)
end
diff --git a/lib/xsd/qname.rb b/lib/xsd/qname.rb
index bb9763a69a..7185fedf2d 100644
--- a/lib/xsd/qname.rb
+++ b/lib/xsd/qname.rb
@@ -12,25 +12,20 @@ module XSD
class QName
attr_accessor :namespace
attr_accessor :name
- attr_accessor :source
def initialize(namespace = nil, name = nil)
@namespace = namespace
@name = name
- @source = nil
end
def dup_name(name)
- XSD::QName.new(@namespace, name)
- end
-
- def dump
- ns = @namespace.nil? ? 'nil' : @namespace.dump
- name = @name.nil? ? 'nil' : @name.dump
- "XSD::QName.new(#{ns}, #{name})"
+ ::XSD::QName.new(@namespace, name)
end
def match(rhs)
+ unless self.class === rhs
+ return false
+ end
if rhs.namespace and (rhs.namespace != @namespace)
return false
end
@@ -41,7 +36,7 @@ class QName
end
def ==(rhs)
- !rhs.nil? and @namespace == rhs.namespace and @name == rhs.name
+ (self.class === rhs && @namespace == rhs.namespace && @name == rhs.name)
end
def ===(rhs)
@@ -70,8 +65,6 @@ class QName
NormalizedNameRegexp =~ str
self.new($1, $2)
end
-
- EMPTY = QName.new.freeze
end
diff --git a/lib/xsd/xmlparser.rb b/lib/xsd/xmlparser.rb
index e79e36c58c..1f87ae2e4d 100644
--- a/lib/xsd/xmlparser.rb
+++ b/lib/xsd/xmlparser.rb
@@ -45,8 +45,8 @@ end
# Try to load XML processor.
loaded = false
[
- 'xsd/xmlparser/xmlparser',
'xsd/xmlparser/xmlscanner',
+ 'xsd/xmlparser/xmlparser',
'xsd/xmlparser/rexmlparser',
].each do |lib|
begin
diff --git a/lib/xsd/xmlparser/xmlscanner.rb b/lib/xsd/xmlparser/xmlscanner.rb
index c80dc23910..c2ad51be52 100644
--- a/lib/xsd/xmlparser/xmlscanner.rb
+++ b/lib/xsd/xmlparser/xmlscanner.rb
@@ -1,5 +1,5 @@
# XSD4R - XMLScan XML parser library.
-# Copyright (C) 2002, 2003, 2005 NAKAMURA, Hiroshi <nahi@ruby-lang.org>.
+# Copyright (C) 2002, 2003 NAKAMURA, Hiroshi <nahi@ruby-lang.org>.
# This program is copyrighted free software by NAKAMURA, Hiroshi. You can
# redistribute it and/or modify it under the same terms of Ruby's license;
@@ -21,12 +21,12 @@ class XMLScanner < XSD::XMLParser::Parser
@attrs = {}
@curattr = nil
@scanner = XMLScan::XMLScanner.new(self)
- @scanner.kcode = XSD::Charset.charset_str(charset) if charset
+ @scanner.kcode = ::XSD::Charset.charset_str(charset) if charset
@scanner.parse(string_or_readable)
end
def scanner_kcode=(charset)
- @scanner.kcode = XSD::Charset.charset_str(charset) if charset
+ @scanner.kcode = ::XSD::Charset.charset_str(charset) if charset
self.xmldecl_encoding = charset
end
diff --git a/lib/yaml.rb b/lib/yaml.rb
index cdce7f7635..38463404bd 100644
--- a/lib/yaml.rb
+++ b/lib/yaml.rb
@@ -6,12 +6,9 @@
# Author:: why the lucky stiff
#
-require 'stringio'
-require 'yaml/error'
require 'yaml/syck'
-require 'yaml/tag'
+require 'yaml/loader'
require 'yaml/stream'
-require 'yaml/constants'
# == YAML
#
@@ -76,7 +73,7 @@ require 'yaml/constants'
# ruby_obj == test_obj
# # => true
#
-# To register your custom types with the global resolver, use +add_domain_type+.
+# To register your custom types with the global loader, use +add_domain_type+.
#
# YAML::add_domain_type( "your-site.com,2004", "widget" ) do |type, val|
# Widget.new( val )
@@ -84,21 +81,9 @@ require 'yaml/constants'
#
module YAML
- Resolver = YAML::Syck::Resolver
- DefaultResolver = YAML::Syck::DefaultResolver
- DefaultResolver.use_types_at( @@tagged_classes )
- GenericResolver = YAML::Syck::GenericResolver
- Parser = YAML::Syck::Parser
- Emitter = YAML::Syck::Emitter
-
- # Returns a new default parser
- def YAML.parser; Parser.new.set_resolver( YAML.resolver ); end
- # Returns a new generic parser
- def YAML.generic_parser; Parser.new.set_resolver( GenericResolver ); end
- # Returns the default resolver
- def YAML.resolver; DefaultResolver; end
- # Returns a new default emitter
- def YAML.emitter; Emitter.new.set_resolver( YAML.resolver ); end
+ @@parser = YAML::Syck::Parser
+ @@loader = YAML::Syck::DefaultLoader
+ @@emitter = YAML::Syck::Emitter
#
# Converts _obj_ to YAML and writes the YAML result to _io_.
@@ -114,8 +99,9 @@ module YAML
# #=> "--- :locked"
#
def YAML.dump( obj, io = nil )
- obj.to_yaml( io || io2 = StringIO.new )
- io || ( io2.rewind; io2.read )
+ io ||= ""
+ io << obj.to_yaml
+ io
end
#
@@ -130,7 +116,7 @@ module YAML
# #=> :locked
#
def YAML.load( io )
- yp = parser.load( io )
+ yp = @@parser.new.load( io )
end
#
@@ -167,13 +153,13 @@ module YAML
#
# Can also load from a string.
#
- # YAML.parse( "--- :locked" )
+ # YAML.load( "--- :locked" )
# #=> #<YAML::Syck::Node:0x82edddc
# @type_id="tag:ruby.yaml.org,2002:sym",
# @value=":locked", @kind=:scalar>
#
def YAML.parse( io )
- yp = generic_parser.load( io )
+ yp = @@parser.new( :Model => :Generic ).load( io )
end
#
@@ -214,7 +200,7 @@ module YAML
# end
#
def YAML.each_document( io, &block )
- yp = parser.load_documents( io, &block )
+ yp = @@parser.new.load_documents( io, &block )
end
#
@@ -244,7 +230,7 @@ module YAML
# end
#
def YAML.each_node( io, &doc_proc )
- yp = generic_parser.load_documents( io, &doc_proc )
+ yp = @@parser.new( :Model => :Generic ).load_documents( io, &doc_proc )
end
#
@@ -268,11 +254,12 @@ module YAML
# loaded documents.
#
def YAML.load_stream( io )
+ yp = @@parser.new
d = nil
- parser.load_documents( io ) do |doc|
- d = YAML::Stream.new if not d
+ yp.load_documents( io ) { |doc|
+ d = YAML::Stream.new( yp.options ) if not d
d.add( doc )
- end
+ }
return d
end
@@ -296,50 +283,43 @@ module YAML
#
# Add a global handler for a YAML domain type.
#
- def YAML.add_domain_type( domain, type_tag, &transfer_proc )
- resolver.add_type( "tag:#{ domain }:#{ type_tag }", transfer_proc )
+ def YAML.add_domain_type( domain, type_re, &transfer_proc )
+ @@loader.add_domain_type( domain, type_re, &transfer_proc )
end
#
# Add a transfer method for a builtin type
#
- def YAML.add_builtin_type( type_tag, &transfer_proc )
- resolver.add_type( "tag:yaml.org,2002:#{ type_tag }", transfer_proc )
+ def YAML.add_builtin_type( type_re, &transfer_proc )
+ @@loader.add_builtin_type( type_re, &transfer_proc )
end
#
# Add a transfer method for a builtin type
#
def YAML.add_ruby_type( type, &transfer_proc )
- resolver.add_type( "tag:ruby.yaml.org,2002:#{ type_tag }", transfer_proc )
+ @@loader.add_ruby_type( type, &transfer_proc )
end
#
# Add a private document type
#
def YAML.add_private_type( type_re, &transfer_proc )
- resolver.add_type( "x-private:" + type_re, transfer_proc )
+ @@loader.add_private_type( type_re, &transfer_proc )
end
#
# Detect typing of a string
#
def YAML.detect_implicit( val )
- resolver.detect_implicit( val )
- end
-
- #
- # Convert a type_id to a taguri
- #
- def YAML.tagurize( val )
- resolver.tagurize( val )
+ @@loader.detect_implicit( val )
end
#
# Apply a transfer method to a Ruby object
#
def YAML.transfer( type_id, obj )
- resolver.transfer( YAML.tagurize( type_id ), obj )
+ @@loader.transfer( type_id, obj )
end
#
@@ -378,13 +358,24 @@ module YAML
# Allocate an Emitter if needed
#
def YAML.quick_emit( oid, opts = {}, &e )
- out =
- if opts.is_a? YAML::Emitter
- opts
- else
- emitter.reset( opts )
- end
- out.emit( oid, &e )
+ old_opt = nil
+ if opts[:Emitter].is_a? @@emitter
+ out = opts.delete( :Emitter )
+ old_opt = out.options.dup
+ out.options.update( opts )
+ else
+ out = @@emitter.new( opts )
+ end
+ aidx = out.start_object( oid )
+ if aidx
+ out.simple( "*#{ aidx }" )
+ else
+ e.call( out )
+ end
+ if old_opt.is_a? Hash
+ out.options = old_opt
+ end
+ out.end_object
end
end
@@ -392,7 +383,7 @@ end
require 'yaml/rubytypes'
require 'yaml/types'
-module Kernel # :nodoc:
+module Kernel
#
# ryan:: You know how Kernel.p is a really convenient way to dump ruby
# structures? The only downside is that it's not as legible as
@@ -409,25 +400,11 @@ module Kernel # :nodoc:
# ryan:: Either way, I certainly will have a pony parade.
#
- # Prints any supplied _objects_ out in YAML. Intended as
- # a variation on +Kernel::p+.
- #
- # S = Struct.new(:name, :state)
- # s = S['dave', 'TX']
- # y s
- #
- # _produces:_
- #
- # --- !ruby/struct:S
- # name: dave
- # state: TX
- #
- def y( object, *objects )
- objects.unshift object
- puts( if objects.length == 1
- YAML::dump( *objects )
+ def y( *x )
+ puts( if x.length == 1
+ YAML::dump( *x )
else
- YAML::dump_stream( *objects )
+ YAML::dump_stream( *x )
end )
end
private :y
diff --git a/lib/yaml/basenode.rb b/lib/yaml/basenode.rb
index d24f6172e9..e88a76f3d2 100644
--- a/lib/yaml/basenode.rb
+++ b/lib/yaml/basenode.rb
@@ -25,7 +25,7 @@ module YAML
matches.each { |m|
result.push m.last
}
- YAML.transfer( 'seq', result )
+ self.class.new( 'seq', result )
end
end
@@ -67,8 +67,8 @@ module YAML
end
def at( seg )
- if Hash === @value
- self[seg]
+ if Hash === @value and @value.has_key?( seg )
+ @value[seg][1]
elsif Array === @value and seg =~ /\A\d+\Z/ and @value[seg.to_i]
@value[seg.to_i]
end
@@ -99,8 +99,8 @@ module YAML
@value.collect { |v|
idx += 1
if Hash === @value
- match_init = [v[0].transform, v[1]]
- match_deep = v[1].match_segment( ypath, depth )
+ match_init = [v[0], v[1][1]]
+ match_deep = v[1][1].match_segment( ypath, depth )
else
match_init = [idx, v]
match_deep = v.match_segment( ypath, depth )
@@ -127,7 +127,7 @@ module YAML
@value.collect { |h|
idx += 1
if Hash === @value
- [h[0].transform, h[1]]
+ [h[0], h[1][1]]
else
[idx, h]
end
@@ -148,7 +148,7 @@ module YAML
if pred
case pred
when /^\.=/
- pred = $' # '
+ pred = $'
match_nodes.reject! { |n|
n.last.value != pred
}
@@ -182,12 +182,12 @@ module YAML
# We want the node to act like as Hash
# if it is.
#
- def []( *key )
+ def []( *k )
if Hash === @value
- v = @value.detect { |k,v| k.transform == key.first }
+ v = @value.[]( *k )
v[1] if v
elsif Array === @value
- @value.[]( *key )
+ @value.[]( *k )
end
end
diff --git a/lib/yaml/emitter.rb b/lib/yaml/emitter.rb
new file mode 100644
index 0000000000..a6be4a6733
--- /dev/null
+++ b/lib/yaml/emitter.rb
@@ -0,0 +1,107 @@
+#
+# Output classes and methods
+#
+
+require 'yaml/baseemitter'
+require 'yaml/encoding'
+
+module YAML
+
+ #
+ # Emit a set of values
+ #
+
+ class Emitter
+
+ include BaseEmitter
+
+ attr_accessor :options
+
+ def initialize( opts )
+ opts = {} if opts.class != Hash
+ @options = YAML::DEFAULTS.dup.update( opts )
+ @headless = 0
+ @seq_map = false
+ @anchors = {}
+ @anchor_extras = {}
+ @active_anchors = []
+ @level = -1
+ self.clear
+ end
+
+ def clear
+ @buffer = []
+ end
+
+ def level
+ @level
+ end
+
+ #
+ # Version string
+ #
+ def version_s
+ " %YAML:#{@options[:Version]}" if @options[:UseVersion]
+ end
+
+ #
+ # Header
+ #
+ def header
+ if @headless.nonzero?
+ ""
+ else
+ "---#{version_s} "
+ end
+ end
+
+ #
+ # Concatenate to the buffer
+ #
+ def <<( str )
+ #p [ self.id, @level, str ]
+ @buffer.last << str
+ end
+
+ #
+ # Monitor objects and allow references
+ #
+ def start_object( oid )
+ @level += 1
+ @buffer.push( "" )
+ #p [ self.id, @level, :OPEN ]
+ idx = nil
+ if oid
+ if @anchors.has_key?( oid )
+ idx = @active_anchors.index( oid )
+ unless idx
+ idx = @active_anchors.length
+ af_str = "&#{@options[:AnchorFormat]} " % [ idx + 1 ]
+ af_str += @anchor_extras[ @anchors[ oid ] ].to_s
+ @buffer[ @anchors[ oid ] ][0,0] = af_str
+ @headless = 0 if @anchors[ oid ].zero?
+ end
+ idx += 1
+ @active_anchors.push( oid )
+ else
+ @anchors[ oid ] = @buffer.length - 1
+ end
+ end
+ return idx
+ end
+
+ #
+ # Output method
+ #
+ def end_object
+ @level -= 1
+ @buffer.push( "" )
+ #p [ self.id, @level, :END ]
+ if @level < 0
+ header + @buffer.to_s[@headless..-1].to_s
+ end
+ end
+ end
+
+end
+
diff --git a/lib/yaml/error.rb b/lib/yaml/error.rb
index 15865a9aa9..a9df22749b 100644
--- a/lib/yaml/error.rb
+++ b/lib/yaml/error.rb
@@ -29,6 +29,5 @@ module YAML
class Error < StandardError; end
class ParseError < Error; end
- class TypeError < StandardError; end
end
diff --git a/lib/yaml/rubytypes.rb b/lib/yaml/rubytypes.rb
index 10516d7557..2a0c31d990 100644
--- a/lib/yaml/rubytypes.rb
+++ b/lib/yaml/rubytypes.rb
@@ -1,5 +1,8 @@
# -*- mode: ruby; ruby-indent-level: 4; tab-width: 4 -*- vim: sw=4 ts=4
require 'date'
+#
+# Type conversions
+#
class Class
def to_yaml( opts = {} )
@@ -8,398 +11,615 @@ class Class
end
class Object
- yaml_as "tag:ruby.yaml.org,2002:object"
- def to_yaml_style; end
- def to_yaml_properties; instance_variables.sort; end
+ def is_complex_yaml?
+ true
+ end
+ def to_yaml_type
+ "!ruby/object:#{self.class}"
+ end
+ def to_yaml_properties
+ instance_variables.sort
+ end
def to_yaml( opts = {} )
- YAML::quick_emit( object_id, opts ) do |out|
- out.map( taguri, to_yaml_style ) do |map|
- to_yaml_properties.each do |m|
+ YAML::quick_emit( self.object_id, opts ) { |out|
+ out.map( self.to_yaml_type ) { |map|
+ to_yaml_properties.each { |m|
map.add( m[1..-1], instance_variable_get( m ) )
- end
- end
- end
+ }
+ }
+ }
end
end
+YAML.add_ruby_type( /^object/ ) { |type, val|
+ type, obj_class = YAML.read_type_class( type, Object )
+ YAML.object_maker( obj_class, val )
+}
+
+#
+# Maps: Hash#to_yaml
+#
class Hash
- yaml_as "tag:ruby.yaml.org,2002:hash"
- yaml_as "tag:yaml.org,2002:map"
- def yaml_initialize( tag, val )
- if Array === val
- update Hash.[]( *val ) # Convert the map to a sequence
- elsif Hash === val
- update val
+ def is_complex_yaml?
+ true
+ end
+ def to_yaml_type
+ if self.class == Hash or self.class == YAML::SpecialHash
+ "!map"
else
- raise YAML::TypeError, "Invalid map explicitly tagged #{ tag }: " + val.inspect
+ "!ruby/hash:#{self.class}"
end
end
def to_yaml( opts = {} )
- YAML::quick_emit( object_id, opts ) do |out|
- out.map( taguri, to_yaml_style ) do |map|
- each do |k, v|
- map.add( k, v )
- end
+ opts[:DocType] = self.class if Hash === opts
+ YAML::quick_emit( self.object_id, opts ) { |out|
+ hash_type = to_yaml_type
+ if not out.options(:ExplicitTypes) and hash_type == "!map"
+ hash_type = ""
end
- end
+ out.map( hash_type ) { |map|
+ #
+ # Sort the hash
+ #
+ if out.options(:SortKeys)
+ map.concat( self.sort )
+ else
+ map.concat( self.to_a )
+ end
+ }
+ }
end
end
-class Struct
- yaml_as "tag:ruby.yaml.org,2002:struct"
- def self.yaml_tag_class_name; self.name.gsub( "Struct::", "" ); end
- def self.yaml_tag_read_class( name ); "Struct::#{ name }"; end
- def self.yaml_new( klass, tag, val )
- if Hash === val
- struct_type = nil
-
- #
- # Use existing Struct if it exists
- #
- props = {}
- val.delete_if { |k,v| props[k] = v if k =~ /^@/ }
- begin
- struct_name, struct_type = YAML.read_type_class( tag, Struct )
- rescue NameError
- end
- if not struct_type
- struct_def = [ tag.split( ':', 4 ).last ]
- struct_type = Struct.new( *struct_def.concat( val.keys.collect { |k| k.intern } ) )
- end
+hash_proc = Proc.new { |type, val|
+ if Array === val
+ val = Hash.[]( *val ) # Convert the map to a sequence
+ elsif Hash === val
+ type, obj_class = YAML.read_type_class( type, Hash )
+ if obj_class != Hash
+ o = obj_class.new
+ o.update( val )
+ val = o
+ end
+ else
+ raise YAML::Error, "Invalid map explicitly tagged !map: " + val.inspect
+ end
+ val
+}
+YAML.add_ruby_type( /^hash/, &hash_proc )
- #
- # Set the Struct properties
- #
- st = YAML::object_maker( struct_type, {} )
- st.members.each do |m|
- st.send( "#{m}=", val[m] )
- end
- props.each do |k,v|
- st.instance_variable_set(k, v)
+module YAML
+
+ #
+ # Ruby-specific collection: !ruby/flexhash
+ #
+ class FlexHash < Array
+ def []( k )
+ self.assoc( k ).to_a[1]
+ end
+ def []=( k, *rest )
+ val, set = rest.reverse
+ if ( tmp = self.assoc( k ) ) and not set
+ tmp[1] = val
+ else
+ self << [ k, val ]
end
- st
+ val
+ end
+ def has_key?( k )
+ self.assoc( k ) ? true : false
+ end
+ def is_complex_yaml?
+ true
+ end
+ def to_yaml( opts = {} )
+ YAML::quick_emit( self.object_id, opts ) { |out|
+ out.seq( "!ruby/flexhash" ) { |seq|
+ self.each { |v|
+ if v[1]
+ seq.add( Hash.[]( *v ) )
+ else
+ seq.add( v[0] )
+ end
+ }
+ }
+ }
+ end
+ end
+
+ YAML.add_ruby_type( 'flexhash' ) { |type, val|
+ if Array === val
+ p = FlexHash.new
+ val.each { |v|
+ if Hash === v
+ p.concat( v.to_a ) # Convert the map to a sequence
+ else
+ p << [ v, nil ]
+ end
+ }
+ p
else
- raise YAML::TypeError, "Invalid Ruby Struct: " + val.inspect
+ raise YAML::Error, "Invalid !ruby/flexhash: " + val.inspect
end
+ }
+end
+
+#
+# Structs: export as a !map
+#
+class Struct
+ def is_complex_yaml?
+ true
end
def to_yaml( opts = {} )
- YAML::quick_emit( object_id, opts ) do |out|
+ YAML::quick_emit( self.object_id, opts ) { |out|
#
# Basic struct is passed as a YAML map
#
- out.map( taguri, to_yaml_style ) do |map|
- self.members.each do |m|
+ struct_name = self.class.name.gsub( "Struct::", "" )
+ out.map( "!ruby/struct:#{struct_name}" ) { |map|
+ self.members.each { |m|
map.add( m, self[m] )
- end
- self.to_yaml_properties.each do |m|
+ }
+ self.to_yaml_properties.each { |m|
map.add( m, instance_variable_get( m ) )
- end
- end
- end
+ }
+ }
+ }
end
end
+YAML.add_ruby_type( /^struct/ ) { |type, val|
+ if Hash === val
+ struct_type = nil
+
+ #
+ # Use existing Struct if it exists
+ #
+ props = {}
+ val.delete_if { |k,v| props[k] = v if k =~ /^@/ }
+ begin
+ struct_name, struct_type = YAML.read_type_class( type, Struct )
+ rescue NameError
+ end
+ if not struct_type
+ struct_def = [ type.split( ':', 4 ).last ]
+ struct_type = Struct.new( *struct_def.concat( val.keys.collect { |k| k.intern } ) )
+ end
+
+ #
+ # Set the Struct properties
+ #
+ st = YAML::object_maker( struct_type, {} )
+ st.members.each { |m|
+ st.send( "#{m}=", val[m] )
+ }
+ props.each { |k,v|
+ st.instance_variable_set(k, v)
+ }
+ st
+ else
+ raise YAML::Error, "Invalid Ruby Struct: " + val.inspect
+ end
+}
+
+#
+# Sequences: Array#to_yaml
+#
class Array
- yaml_as "tag:ruby.yaml.org,2002:array"
- yaml_as "tag:yaml.org,2002:seq"
- def yaml_initialize( tag, val ); concat( val.to_a ); end
+ def is_complex_yaml?
+ true
+ end
+ def to_yaml_type
+ if self.class == Array
+ "!seq"
+ else
+ "!ruby/array:#{self.class}"
+ end
+ end
def to_yaml( opts = {} )
- YAML::quick_emit( object_id, opts ) do |out|
- out.seq( taguri, to_yaml_style ) do |seq|
- each do |x|
- seq.add( x )
- end
+ opts[:DocType] = self.class if Hash === opts
+ YAML::quick_emit( self.object_id, opts ) { |out|
+ array_type = to_yaml_type
+ if not out.options(:ExplicitTypes) and array_type == "!seq"
+ array_type = ""
end
- end
+
+ out.seq( array_type ) { |seq|
+ seq.concat( self )
+ }
+ }
end
end
-class Exception
- yaml_as "tag:ruby.yaml.org,2002:exception"
- def Exception.yaml_new( klass, tag, val )
- o = YAML.object_maker( klass, { 'mesg' => val.delete( 'message' ) } )
- val.each_pair do |k,v|
- o.instance_variable_set("@#{k}", v)
+array_proc = Proc.new { |type, val|
+ if Array === val
+ type, obj_class = YAML.read_type_class( type, Array )
+ if obj_class != Array
+ o = obj_class.new
+ o.concat( val )
+ val = o
end
- o
+ val
+ else
+ val.to_a
+ end
+}
+YAML.add_ruby_type( /^array/, &array_proc )
+
+#
+# Exception#to_yaml
+#
+class Exception
+ def is_complex_yaml?
+ true
+ end
+ def to_yaml_type
+ "!ruby/exception:#{self.class}"
end
def to_yaml( opts = {} )
- YAML::quick_emit( object_id, opts ) do |out|
- out.map( taguri, to_yaml_style ) do |map|
- map.add( 'message', message )
- to_yaml_properties.each do |m|
+ YAML::quick_emit( self.object_id, opts ) { |out|
+ out.map( self.to_yaml_type ) { |map|
+ map.add( 'message', self.message )
+ to_yaml_properties.each { |m|
map.add( m[1..-1], instance_variable_get( m ) )
- end
- end
- end
+ }
+ }
+ }
end
end
+YAML.add_ruby_type( /^exception/ ) { |type, val|
+ type, obj_class = YAML.read_type_class( type, Exception )
+ o = YAML.object_maker( obj_class, { 'mesg' => val.delete( 'message' ) } )
+ val.each_pair { |k,v|
+ o.instance_variable_set("@#{k}", v)
+ }
+ o
+}
+
+
+#
+# String#to_yaml
+#
class String
- yaml_as "tag:ruby.yaml.org,2002:string"
- yaml_as "tag:yaml.org,2002:binary"
- yaml_as "tag:yaml.org,2002:str"
def is_complex_yaml?
- to_yaml_style or not to_yaml_properties.empty? or self =~ /\n.+/
+ to_yaml_fold or not to_yaml_properties.empty? or self =~ /\n.+/
end
def is_binary_data?
- ( self.count( "^ -~", "^\r\n" ) / self.size > 0.3 || self.count( "\x00" ) > 0 ) unless empty?
+ ( self.count( "^ -~", "^\r\n" ) / self.size > 0.3 || self.count( "\x00" ) > 0 )
end
- def String.yaml_new( klass, tag, val )
- val = val.unpack("m")[0] if tag == "tag:yaml.org,2002:binary"
- val = { 'str' => val } if String === val
- if Hash === val
- s = klass.allocate
- # Thank you, NaHi
- String.instance_method(:initialize).
- bind(s).
- call( val.delete( 'str' ) )
- val.each { |k,v| s.instance_variable_set( k, v ) }
- s
- else
- raise YAML::TypeError, "Invalid String: " + val.inspect
- end
+ def to_yaml_type
+ "!ruby/string#{ ":#{ self.class }" if self.class != ::String }"
+ end
+ def to_yaml_fold
+ nil
end
def to_yaml( opts = {} )
- YAML::quick_emit( is_complex_yaml? ? object_id : nil, opts ) do |out|
- if is_binary_data?
- out.scalar( "tag:yaml.org,2002:binary", [self].pack("m"), :literal )
- elsif to_yaml_properties.empty?
- out.scalar( taguri, self, self =~ /^:/ ? :quote2 : to_yaml_style )
- else
- out.map( taguri, to_yaml_style ) do |map|
- map.add( 'str', "#{self}" )
- to_yaml_properties.each do |m|
- map.add( m, instance_variable_get( m ) )
- end
- end
+ complex = false
+ if self.is_complex_yaml?
+ complex = true
+ elsif opts[:BestWidth].to_i > 0
+ if self.length > opts[:BestWidth] and opts[:UseFold]
+ complex = true
end
end
+ YAML::quick_emit( complex ? self.object_id : nil, opts ) { |out|
+ if complex
+ if not to_yaml_properties.empty?
+ out.map( self.to_yaml_type ) { |map|
+ map.add( 'str', "#{self}" )
+ to_yaml_properties.each { |m|
+ map.add( m, instance_variable_get( m ) )
+ }
+ }
+ elsif self.is_binary_data?
+ out.binary_base64( self )
+ elsif self =~ /#{YAML::ESCAPE_CHAR}/
+ out.node_text( self, '"' )
+ else
+ out.node_text( self, to_yaml_fold )
+ end
+ else
+ ostr = if out.options(:KeepValue)
+ self
+ elsif empty?
+ "''"
+ elsif self =~ /^[^#{YAML::WORD_CHAR}\/]| \#|#{YAML::ESCAPE_CHAR}|[#{YAML::SPACE_INDICATORS}]( |$)| $|\n|\'/
+ out.node_text( self, '"' ); nil
+ elsif YAML.detect_implicit( self ) != 'str'
+ out.node_text( self, '"' ); nil
+ else
+ self
+ end
+ out.simple( ostr ) unless ostr.nil?
+ end
+ }
end
end
+YAML.add_ruby_type( /^string/ ) { |type, val|
+ type, obj_class = YAML.read_type_class( type, ::String )
+ if Hash === val
+ s = YAML::object_maker( obj_class, {} )
+ # Thank you, NaHi
+ String.instance_method(:initialize).
+ bind(s).
+ call( val.delete( 'str' ) )
+ val.each { |k,v| s.instance_variable_set( k, v ) }
+ s
+ else
+ raise YAML::Error, "Invalid String: " + val.inspect
+ end
+}
+
+#
+# Symbol#to_yaml
+#
class Symbol
- yaml_as "tag:ruby.yaml.org,2002:symbol"
- yaml_as "tag:ruby.yaml.org,2002:sym"
- def Symbol.yaml_new( klass, tag, val )
- if String === val
- val.intern
- else
- raise YAML::TypeError, "Invalid Symbol: " + val.inspect
- end
+ def is_complex_yaml?
+ false
end
def to_yaml( opts = {} )
- YAML::quick_emit( nil, opts ) do |out|
- out.scalar( "tag:yaml.org,2002:str", self.inspect, :plain )
- end
+ YAML::quick_emit( nil, opts ) { |out|
+ out << ":"
+ self.id2name.to_yaml( :Emitter => out )
+ }
end
end
+symbol_proc = Proc.new { |type, val|
+ if String === val
+ val = YAML::load( "--- #{val}") if val =~ /^["'].*['"]$/
+ val.intern
+ else
+ raise YAML::Error, "Invalid Symbol: " + val.inspect
+ end
+}
+YAML.add_ruby_type( 'symbol', &symbol_proc )
+YAML.add_ruby_type( 'sym', &symbol_proc )
+
+#
+# Range#to_yaml
+#
class Range
- yaml_as "tag:ruby.yaml.org,2002:range"
- def Range.yaml_new( klass, tag, val )
- inr = %r'(\w+|[+-]?\d+(?:\.\d+)?(?:e[+-]\d+)?|"(?:[^\\"]|\\.)*")'
- opts = {}
- if String === val and val =~ /^#{inr}(\.{2,3})#{inr}$/o
- r1, rdots, r2 = $1, $2, $3
- opts = {
- 'begin' => YAML.load( "--- #{r1}" ),
- 'end' => YAML.load( "--- #{r2}" ),
- 'excl' => rdots.length == 3
- }
- val = {}
- elsif Hash === val
- opts['begin'] = val.delete('begin')
- opts['end'] = val.delete('end')
- opts['excl'] = val.delete('excl')
- end
- if Hash === opts
- r = YAML::object_maker( klass, {} )
- # Thank you, NaHi
- Range.instance_method(:initialize).
- bind(r).
- call( opts['begin'], opts['end'], opts['excl'] )
- val.each { |k,v| r.instance_variable_set( k, v ) }
- r
- else
- raise YAML::TypeError, "Invalid Range: " + val.inspect
- end
+ def is_complex_yaml?
+ true
+ end
+ def to_yaml_type
+ "!ruby/range#{ if self.class != ::Range; ":#{ self.class }"; end }"
end
def to_yaml( opts = {} )
- YAML::quick_emit( object_id, opts ) do |out|
- # if self.begin.is_complex_yaml? or self.begin.respond_to? :to_str or
- # self.end.is_complex_yaml? or self.end.respond_to? :to_str or
- # not to_yaml_properties.empty?
- out.map( taguri, to_yaml_style ) do |map|
+ YAML::quick_emit( self.object_id, opts ) { |out|
+ if self.begin.is_complex_yaml? or self.begin.respond_to? :to_str or
+ self.end.is_complex_yaml? or self.end.respond_to? :to_str or
+ not to_yaml_properties.empty?
+ out.map( to_yaml_type ) { |map|
map.add( 'begin', self.begin )
map.add( 'end', self.end )
map.add( 'excl', self.exclude_end? )
- to_yaml_properties.each do |m|
+ to_yaml_properties.each { |m|
map.add( m, instance_variable_get( m ) )
- end
- end
- # else
- # out.scalar( taguri ) do |sc|
- # sc.embed( self.begin )
- # sc.concat( self.exclude_end? ? "..." : ".." )
- # sc.embed( self.end )
- # end
- # end
- end
+ }
+ }
+ else
+ out << "#{ to_yaml_type } '"
+ self.begin.to_yaml(:Emitter => out)
+ out << ( self.exclude_end? ? "..." : ".." )
+ self.end.to_yaml(:Emitter => out)
+ out << "'"
+ end
+ }
end
end
+YAML.add_ruby_type( /^range/ ) { |type, val|
+ type, obj_class = YAML.read_type_class( type, ::Range )
+ inr = %r'(\w+|[+-]?\d+(?:\.\d+)?(?:e[+-]\d+)?|"(?:[^\\"]|\\.)*")'
+ opts = {}
+ if String === val and val =~ /^#{inr}(\.{2,3})#{inr}$/o
+ r1, rdots, r2 = $1, $2, $3
+ opts = {
+ 'begin' => YAML.load( "--- #{r1}" ),
+ 'end' => YAML.load( "--- #{r2}" ),
+ 'excl' => rdots.length == 3
+ }
+ val = {}
+ elsif Hash === val
+ opts['begin'] = val.delete('begin')
+ opts['end'] = val.delete('end')
+ opts['excl'] = val.delete('excl')
+ end
+ if Hash === opts
+ r = YAML::object_maker( obj_class, {} )
+ # Thank you, NaHi
+ Range.instance_method(:initialize).
+ bind(r).
+ call( opts['begin'], opts['end'], opts['excl'] )
+ val.each { |k,v| r.instance_variable_set( k, v ) }
+ r
+ else
+ raise YAML::Error, "Invalid Range: " + val.inspect
+ end
+}
+
+#
+# Make an Regexp
+#
class Regexp
- yaml_as "tag:ruby.yaml.org,2002:regexp"
- def Regexp.yaml_new( klass, tag, val )
- if String === val and val =~ /^\/(.*)\/([mix]*)$/
- val = { 'regexp' => $1, 'mods' => $2 }
- end
- if Hash === val
- mods = nil
- unless val['mods'].to_s.empty?
- mods = 0x00
- mods |= Regexp::EXTENDED if val['mods'].include?( 'x' )
- mods |= Regexp::IGNORECASE if val['mods'].include?( 'i' )
- mods |= Regexp::MULTILINE if val['mods'].include?( 'm' )
- end
- val.delete( 'mods' )
- r = YAML::object_maker( klass, {} )
- Regexp.instance_method(:initialize).
- bind(r).
- call( val.delete( 'regexp' ), mods )
- val.each { |k,v| r.instance_variable_set( k, v ) }
- r
- else
- raise YAML::TypeError, "Invalid Regular expression: " + val.inspect
- end
+ def is_complex_yaml?
+ self.class != Regexp or not to_yaml_properties.empty?
+ end
+ def to_yaml_type
+ "!ruby/regexp#{ if self.class != ::Regexp; ":#{ self.class }"; end }"
end
def to_yaml( opts = {} )
- YAML::quick_emit( nil, opts ) do |out|
- if to_yaml_properties.empty?
- out.scalar( taguri, self.inspect, :plain )
- else
- out.map( taguri, to_yaml_style ) do |map|
+ YAML::quick_emit( nil, opts ) { |out|
+ if self.is_complex_yaml?
+ out.map( self.to_yaml_type ) { |map|
src = self.inspect
if src =~ /\A\/(.*)\/([a-z]*)\Z/
map.add( 'regexp', $1 )
map.add( 'mods', $2 )
else
- raise YAML::TypeError, "Invalid Regular expression: " + src
+ raise YAML::Error, "Invalid Regular expression: " + src
end
- to_yaml_properties.each do |m|
+ to_yaml_properties.each { |m|
map.add( m, instance_variable_get( m ) )
- end
- end
+ }
+ }
+ else
+ out << "#{ to_yaml_type } "
+ self.inspect.to_yaml( :Emitter => out )
end
- end
+ }
end
end
+regexp_proc = Proc.new { |type, val|
+ type, obj_class = YAML.read_type_class( type, ::Regexp )
+ if String === val and val =~ /^\/(.*)\/([mix]*)$/
+ val = { 'regexp' => $1, 'mods' => $2 }
+ end
+ if Hash === val
+ mods = nil
+ unless val['mods'].to_s.empty?
+ mods = 0x00
+ mods |= Regexp::EXTENDED if val['mods'].include?( 'x' )
+ mods |= Regexp::IGNORECASE if val['mods'].include?( 'i' )
+ mods |= Regexp::MULTILINE if val['mods'].include?( 'm' )
+ end
+ val.delete( 'mods' )
+ r = YAML::object_maker( obj_class, {} )
+ Regexp.instance_method(:initialize).
+ bind(r).
+ call( val.delete( 'regexp' ), mods )
+ val.each { |k,v| r.instance_variable_set( k, v ) }
+ r
+ else
+ raise YAML::Error, "Invalid Regular expression: " + val.inspect
+ end
+}
+YAML.add_domain_type( "perl.yaml.org,2002", /^regexp/, &regexp_proc )
+YAML.add_ruby_type( /^regexp/, &regexp_proc )
+
+#
+# Emit a Time object as an ISO 8601 timestamp
+#
class Time
- yaml_as "tag:ruby.yaml.org,2002:time"
- yaml_as "tag:yaml.org,2002:timestamp"
- def Time.yaml_new( klass, tag, val )
- if Hash === val
- t = val.delete( 'at' )
- val.each { |k,v| t.instance_variable_set( k, v ) }
- t
- else
- raise YAML::TypeError, "Invalid Time: " + val.inspect
- end
+ def is_complex_yaml?
+ self.class != Time or not to_yaml_properties.empty?
+ end
+ def to_yaml_type
+ "!ruby/time#{ if self.class != ::Time; ":#{ self.class }"; end }"
end
def to_yaml( opts = {} )
- YAML::quick_emit( object_id, opts ) do |out|
- tz = "Z"
- # from the tidy Tobias Peters <t-peters@gmx.de> Thanks!
- unless self.utc?
- utc_same_instant = self.dup.utc
- utc_same_writing = Time.utc(year,month,day,hour,min,sec,usec)
- difference_to_utc = utc_same_writing - utc_same_instant
- if (difference_to_utc < 0)
- difference_sign = '-'
- absolute_difference = -difference_to_utc
- else
- difference_sign = '+'
- absolute_difference = difference_to_utc
- end
- difference_minutes = (absolute_difference/60).round
- tz = "%s%02d:%02d" % [ difference_sign, difference_minutes / 60, difference_minutes % 60]
- end
- standard = self.strftime( "%Y-%m-%d %H:%M:%S" )
- standard += ".%06d" % [usec] if usec.nonzero?
- standard += " %s" % [tz]
- if to_yaml_properties.empty?
- out.scalar( taguri, standard, :plain )
- else
- out.map( taguri, to_yaml_style ) do |map|
- map.add( 'at', standard )
- to_yaml_properties.each do |m|
+ YAML::quick_emit( nil, opts ) { |out|
+ if self.is_complex_yaml?
+ out.map( self.to_yaml_type ) { |map|
+ map.add( 'at', ::Time.at( self ) )
+ to_yaml_properties.each { |m|
map.add( m, instance_variable_get( m ) )
+ }
+ }
+ else
+ tz = "Z"
+ # from the tidy Tobias Peters <t-peters@gmx.de> Thanks!
+ unless self.utc?
+ utc_same_instant = self.dup.utc
+ utc_same_writing = Time.utc(year,month,day,hour,min,sec,usec)
+ difference_to_utc = utc_same_writing - utc_same_instant
+ if (difference_to_utc < 0)
+ difference_sign = '-'
+ absolute_difference = -difference_to_utc
+ else
+ difference_sign = '+'
+ absolute_difference = difference_to_utc
end
+ difference_minutes = (absolute_difference/60).round
+ tz = "%s%02d:%02d" % [ difference_sign, difference_minutes / 60, difference_minutes % 60]
end
+ standard = self.strftime( "%Y-%m-%d %H:%M:%S" )
+ standard += ".%06d" % [usec] if usec.nonzero?
+ standard += " %s" % [tz]
+ standard.to_yaml( :Emitter => out, :KeepValue => true )
end
- end
+ }
end
end
+YAML.add_ruby_type( /^time/ ) { |type, val|
+ type, obj_class = YAML.read_type_class( type, ::Time )
+ if Hash === val
+ t = obj_class.at( val.delete( 'at' ) )
+ val.each { |k,v| t.instance_variable_set( k, v ) }
+ t
+ else
+ raise YAML::Error, "Invalid Time: " + val.inspect
+ end
+}
+
+#
+# Emit a Date object as a simple implicit
+#
class Date
- yaml_as "tag:yaml.org,2002:timestamp#ymd"
+ def is_complex_yaml?
+ false
+ end
def to_yaml( opts = {} )
- YAML::quick_emit( object_id, opts ) do |out|
- out.scalar( "tag:yaml.org,2002:timestamp", self.to_s, :plain )
- end
+ opts[:KeepValue] = true
+ self.to_s.to_yaml( opts )
end
end
+#
+# Send Integer, Booleans, NilClass to String
+#
class Numeric
+ def is_complex_yaml?
+ false
+ end
def to_yaml( opts = {} )
- YAML::quick_emit( nil, opts ) do |out|
- str = self.to_s
- if str == "Infinity"
- str = ".Inf"
- elsif str == "-Infinity"
- str = "-.Inf"
- elsif str == "NaN"
- str = ".NaN"
- end
- out.scalar( taguri, str, :plain )
- end
+ str = self.to_s
+ if str == "Infinity"
+ str = ".Inf"
+ elsif str == "-Infinity"
+ str = "-.Inf"
+ elsif str == "NaN"
+ str = ".NaN"
+ end
+ opts[:KeepValue] = true
+ str.to_yaml( opts )
end
end
-class Fixnum
- yaml_as "tag:yaml.org,2002:int"
-end
-
-class Float
- yaml_as "tag:yaml.org,2002:float"
-end
-
class TrueClass
- yaml_as "tag:yaml.org,2002:bool#yes"
+ def is_complex_yaml?
+ false
+ end
def to_yaml( opts = {} )
- YAML::quick_emit( nil, opts ) do |out|
- out.scalar( taguri, "true", :plain )
- end
+ opts[:KeepValue] = true
+ "true".to_yaml( opts )
end
end
class FalseClass
- yaml_as "tag:yaml.org,2002:bool#no"
+ def is_complex_yaml?
+ false
+ end
def to_yaml( opts = {} )
- YAML::quick_emit( nil, opts ) do |out|
- out.scalar( taguri, "false", :plain )
- end
+ opts[:KeepValue] = true
+ "false".to_yaml( opts )
end
end
class NilClass
- yaml_as "tag:yaml.org,2002:null"
+ def is_complex_yaml?
+ false
+ end
def to_yaml( opts = {} )
- YAML::quick_emit( nil, opts ) do |out|
- out.scalar( taguri, "", :plain )
- end
+ opts[:KeepValue] = true
+ "".to_yaml( opts )
end
end
diff --git a/lib/yaml/stream.rb b/lib/yaml/stream.rb
index 060fbc4200..943c51526b 100644
--- a/lib/yaml/stream.rb
+++ b/lib/yaml/stream.rb
@@ -24,15 +24,19 @@ module YAML
@documents[ doc_num ] = doc
end
- def emit( io = nil )
- # opts = @options.dup
- # opts[:UseHeader] = true if @documents.length > 1
- out = YAML.emitter
- out.reset( io || io2 = StringIO.new )
+ def emit
+ opts = @options.dup
+ opts[:UseHeader] = true if @documents.length > 1
+ ct = 0
+ out = YAML::Syck::Emitter.new( opts )
@documents.each { |v|
- v.to_yaml( out )
+ if ct > 0
+ out << "\n--- "
+ end
+ v.to_yaml( :Emitter => out )
+ ct += 1
}
- io || ( io2.rewind; io2.read )
+ out.end_object
end
end
diff --git a/lib/yaml/syck.rb b/lib/yaml/syck.rb
index faf57e8036..267067feb5 100644
--- a/lib/yaml/syck.rb
+++ b/lib/yaml/syck.rb
@@ -4,6 +4,7 @@
#
require 'syck'
require 'yaml/basenode'
+require 'yaml/baseemitter'
module YAML
module Syck
@@ -15,5 +16,12 @@ module YAML
include YAML::BaseNode
end
+ #
+ # Mixin BaseEmitter functionality
+ #
+ class Emitter
+ include YAML::BaseEmitter
+ end
+
end
end
diff --git a/lib/yaml/tag.rb b/lib/yaml/tag.rb
deleted file mode 100644
index e51677230f..0000000000
--- a/lib/yaml/tag.rb
+++ /dev/null
@@ -1,89 +0,0 @@
-# -*- mode: ruby; ruby-indent-level: 4; tab-width: 4 -*- vim: sw=4 ts=4
-# $Id$
-#
-# = yaml/tag.rb: methods for associating a taguri to a class.
-#
-# Author:: why the lucky stiff
-#
-module YAML
- # A dictionary of taguris which map to
- # Ruby classes.
- @@tagged_classes = {}
-
- #
- # Associates a taguri _tag_ with a Ruby class _cls_. The taguri is used to give types
- # to classes when loading YAML. Taguris are of the form:
- #
- # tag:authorityName,date:specific
- #
- # The +authorityName+ is a domain name or email address. The +date+ is the date the type
- # was issued in YYYY or YYYY-MM or YYYY-MM-DD format. The +specific+ is a name for
- # the type being added.
- #
- # For example, built-in YAML types have 'yaml.org' as the +authorityName+ and '2002' as the
- # +date+. The +specific+ is simply the name of the type:
- #
- # tag:yaml.org,2002:int
- # tag:yaml.org,2002:float
- # tag:yaml.org,2002:timestamp
- #
- # The domain must be owned by you on the +date+ declared. If you don't own any domains on the
- # date you declare the type, you can simply use an e-mail address.
- #
- # tag:why@ruby-lang.org,2004:notes/personal
- #
- def YAML.tag_class( tag, cls )
- if @@tagged_classes.has_key? tag
- warn "class #{ @@tagged_classes[tag] } held ownership of the #{ tag } tag"
- end
- @@tagged_classes[tag] = cls
- end
-
- # Returns the complete dictionary of taguris, paired with classes. The key for
- # the dictionary is the full taguri. The value for each key is the class constant
- # associated to that taguri.
- #
- # YAML.tagged_classes["tag:yaml.org,2002:int"] => Integer
- #
- def YAML.tagged_classes
- @@tagged_classes
- end
-end
-
-class Module # :nodoc: all
- # Adds a taguri _tag_ to a class, used when dumping or loading the class
- # in YAML. See YAML::tag_class for detailed information on typing and
- # taguris.
- def yaml_as( tag, sc = true )
- verbose, $VERBOSE = $VERBOSE, nil
- class_eval <<-"end;", __FILE__, __LINE__+1
- attr_writer :taguri
- def taguri
- if respond_to? :to_yaml_type
- YAML::tagurize( to_yaml_type[1..-1] )
- else
- return @taguri if defined?(@taguri) and @taguri
- tag = #{ tag.dump }
- if self.class.yaml_tag_subclasses? and self.class != YAML::tagged_classes[tag]
- tag = "\#{ tag }:\#{ self.class.yaml_tag_class_name }"
- end
- tag
- end
- end
- def self.yaml_tag_subclasses?; #{ sc ? 'true' : 'false' }; end
- end;
- YAML::tag_class tag, self
- ensure
- $VERBOSE = verbose
- end
- # Transforms the subclass name into a name suitable for display
- # in a subclassed tag.
- def yaml_tag_class_name
- self.name
- end
- # Transforms the subclass name found in the tag into a Ruby
- # constant name.
- def yaml_tag_read_class( name )
- name
- end
-end
diff --git a/lib/yaml/types.rb b/lib/yaml/types.rb
index 05113f216d..f7772cb3a0 100644
--- a/lib/yaml/types.rb
+++ b/lib/yaml/types.rb
@@ -1,109 +1,80 @@
-# -*- mode: ruby; ruby-indent-level: 4 -*- vim: sw=4
#
# Classes required by the full core typeset
#
module YAML
- #
- # Default private type
- #
- class PrivateType
- def self.tag_subclasses?; false; end
- attr_accessor :type_id, :value
- verbose, $VERBOSE = $VERBOSE, nil
- def initialize( type, val )
- @type_id = type; @value = val
- @value.taguri = "x-private:#{ @type_id }"
- end
- def to_yaml( opts = {} )
- @value.to_yaml( opts )
- end
- ensure
- $VERBOSE = verbose
- end
+ #
+ # Default private type
+ #
+ class PrivateType
+ attr_accessor :type_id, :value
+ def initialize( type, val )
+ @type_id = type; @value = val
+ end
+ def to_yaml( opts = {} )
+ YAML::quick_emit( self.object_id, opts ) { |out|
+ out << " !!#{@type_id}"
+ value.to_yaml( :Emitter => out )
+ }
+ end
+ end
#
# Default domain type
#
class DomainType
- def self.tag_subclasses?; false; end
- attr_accessor :domain, :type_id, :value
- verbose, $VERBOSE = $VERBOSE, nil
- def initialize( domain, type, val )
- @domain = domain; @type_id = type; @value = val
- @value.taguri = "tag:#{ @domain }:#{ @type_id }"
- end
- def to_yaml( opts = {} )
- @value.to_yaml( opts )
- end
- ensure
- $VERBOSE = verbose
- end
-
- #
- # Unresolved objects
- #
- class Object
- def self.tag_subclasses?; false; end
- def to_yaml( opts = {} )
- YAML::quick_emit( object_id, opts ) do |out|
- out.map( "tag:ruby.yaml.org,2002:object:#{ @class }", to_yaml_style ) do |map|
- @ivars.each do |k,v|
- map.add( k, v )
- end
- end
+ attr_accessor :domain, :type_id, :value
+ def initialize( domain, type, val )
+ @domain = domain; @type_id = type; @value = val
+ end
+ def to_yaml_type
+ dom = @domain.dup
+ if dom =~ /\.yaml\.org,2002$/
+ dom = $`
end
- end
- end
+ "#{dom}/#{@type_id}"
+ end
+ def to_yaml( opts = {} )
+ YAML::quick_emit( self.object_id, opts ) { |out|
+ out << " !#{to_yaml_type} "
+ value.to_yaml( :Emitter => out )
+ }
+ end
+ end
- #
- # YAML Hash class to support comments and defaults
- #
- class SpecialHash < ::Hash
- attr_accessor :default
+ #
+ # YAML Hash class to support comments and defaults
+ #
+ class SpecialHash < Object::Hash
+ attr_accessor :default
def inspect
self.default.to_s
end
- def to_s
- self.default.to_s
- end
- def update( h )
- if YAML::SpecialHash === h
- @default = h.default if h.default
- end
- super( h )
- end
+ def to_s
+ self.default.to_s
+ end
+ def update( h )
+ if YAML::SpecialHash === h
+ @default = h.default if h.default
+ end
+ super( h )
+ end
def to_yaml( opts = {} )
opts[:DefaultKey] = self.default
super( opts )
end
- end
+ end
#
# Builtin collection: !omap
#
- class Omap < ::Array
- yaml_as "tag:yaml.org,2002:omap"
- def yaml_initialize( tag, val )
- if Array === val
- val.each do |v|
- if Hash === v
- concat( v.to_a ) # Convert the map to a sequence
- else
- raise YAML::Error, "Invalid !omap entry: " + val.inspect
- end
- end
- else
- raise YAML::Error, "Invalid !omap: " + val.inspect
- end
- self
- end
+ class Omap < Array
def self.[]( *vals )
o = Omap.new
- 0.step( vals.length - 1, 2 ) do |i|
+ 0.step( vals.length - 1, 2 ) { |i|
o[vals[i]] = vals[i+1]
- end
+ }
o
end
def []( k )
@@ -125,35 +96,36 @@ module YAML
true
end
def to_yaml( opts = {} )
- YAML::quick_emit( self.object_id, opts ) do |out|
- out.seq( taguri, to_yaml_style ) do |seq|
- self.each do |v|
+ YAML::quick_emit( self.object_id, opts ) { |out|
+ out.seq( "!omap" ) { |seq|
+ self.each { |v|
seq.add( Hash[ *v ] )
- end
- end
- end
+ }
+ }
+ }
end
end
+ YAML.add_builtin_type( "omap" ) { |type, val|
+ if Array === val
+ p = Omap.new
+ val.each { |v|
+ if Hash === v
+ p.concat( v.to_a ) # Convert the map to a sequence
+ else
+ raise YAML::Error, "Invalid !omap entry: " + val.inspect
+ end
+ }
+ else
+ raise YAML::Error, "Invalid !omap: " + val.inspect
+ end
+ p
+ }
+
#
# Builtin collection: !pairs
#
- class Pairs < ::Array
- yaml_as "tag:yaml.org,2002:pairs"
- def yaml_initialize( tag, val )
- if Array === val
- val.each do |v|
- if Hash === v
- concat( v.to_a ) # Convert the map to a sequence
- else
- raise YAML::Error, "Invalid !pairs entry: " + val.inspect
- end
- end
- else
- raise YAML::Error, "Invalid !pairs: " + val.inspect
- end
- self
- end
+ class Pairs < Array
def self.[]( *vals )
p = Pairs.new
0.step( vals.length - 1, 2 ) { |i|
@@ -175,20 +147,50 @@ module YAML
true
end
def to_yaml( opts = {} )
- YAML::quick_emit( self.object_id, opts ) do |out|
- out.seq( taguri, to_yaml_style ) do |seq|
- self.each do |v|
+ YAML::quick_emit( self.object_id, opts ) { |out|
+ out.seq( "!pairs" ) { |seq|
+ self.each { |v|
seq.add( Hash[ *v ] )
- end
- end
- end
+ }
+ }
+ }
end
end
+ YAML.add_builtin_type( "pairs" ) { |type, val|
+ if Array === val
+ p = Pairs.new
+ val.each { |v|
+ if Hash === v
+ p.concat( v.to_a ) # Convert the map to a sequence
+ else
+ raise YAML::Error, "Invalid !pairs entry: " + val.inspect
+ end
+ }
+ else
+ raise YAML::Error, "Invalid !pairs: " + val.inspect
+ end
+ p
+ }
+
#
# Builtin collection: !set
#
- class Set < ::Hash
- yaml_as "tag:yaml.org,2002:set"
+ class Set < Hash
+ def to_yaml_type
+ "!set"
+ end
end
+
+ YAML.add_builtin_type( 'set' ) { |type, val|
+ if Array === val
+ val = Set[ *val ]
+ elsif Hash === val
+ Set[ val ]
+ else
+ raise YAML::Error, "Invalid map explicitly tagged !map: " + val.inspect
+ end
+ val
+ }
+
end
diff --git a/marshal.c b/marshal.c
index 3791c4c79a..5323fdde25 100644
--- a/marshal.c
+++ b/marshal.c
@@ -111,7 +111,7 @@ class2path(klass)
n);
}
if (rb_path2class(n) != rb_class_real(klass)) {
- rb_raise(rb_eTypeError, "%s can't be referred", n);
+ rb_raise(rb_eTypeError, "%s cannot be referred", n);
}
return path;
}
@@ -615,7 +615,7 @@ w_object(obj, arg, limit)
}
else if (FL_TEST(obj, FL_USER2)) {
/* FL_USER2 means HASH_PROC_DEFAULT (see hash.c) */
- rb_raise(rb_eTypeError, "can't dump hash with default proc");
+ rb_raise(rb_eTypeError, "cannot dump hash with default proc");
}
else {
w_byte(TYPE_HASH_DEF, arg);
diff --git a/misc/ruby-electric.el b/misc/ruby-electric.el
deleted file mode 100644
index c361089938..0000000000
--- a/misc/ruby-electric.el
+++ /dev/null
@@ -1,200 +0,0 @@
-;; -*-Emacs-Lisp-*-
-;;
-;; ruby-electric.el --- electric editing commands for ruby files
-;;
-;; Copyright (C) 2005 by Dee Zsombor <dee dot zsombor at gmail dot com>.
-;; Released under same license terms as Ruby.
-;;
-;; Due credit: this work was inspired by a code snippet posted by
-;; Frederick Ros at http://rubygarden.org/ruby?EmacsExtensions.
-;;
-;; Following improvements where added:
-;;
-;; - handling of strings of type 'here document'
-;; - more keywords, with special handling for 'do'
-;; - packaged into a minor mode
-;;
-;; Usage:
-;;
-;; 0) copy ruby-electric.el into directory where emacs can find it.
-;;
-;; 1) modify your startup file (.emacs or whatever) by adding
-;; following line:
-;;
-;; (require 'ruby-electric)
-;;
-;; note that you need to have font lock enabled beforehand.
-;;
-;; 2) toggle Ruby Electric Mode on/off with ruby-electric-mode.
-;;
-;; Changelog:
-;;
-;; 2005/Jan/14: inserts matching pair delimiters like {, [, (, ', ",
-;; ' and | .
-;;
-;; 2005/Jan/14: added basic Custom support for configuring keywords
-;; with electric closing.
-;;
-;; 2005/Jan/18: more Custom support for configuring characters for
-;; which matching expansion should occur.
-;;
-;; 2005/Jan/18: no longer uses 'looking-back' or regexp character
-;; classes like [:space:] since they are not implemented on XEmacs.
-;;
-;; 2005/Feb/01: explicitly provide default argument of 1 to
-;; 'backward-word' as it requires it on Emacs 21.3
-;;
-;; 2005/Mar/06: now stored inside ruby CVS; customize pages now have
-;; ruby as parent; cosmetic fixes.
-
-
-(require 'ruby-mode)
-
-(defgroup ruby-electric nil
- "Minor mode providing electric editing commands for ruby files"
- :group 'ruby)
-
-(defconst ruby-electric-expandable-do-re
- "do\\s-$")
-
-(defconst ruby-electric-expandable-bar
- "\\s-\\(do\\|{\\)\\s-+|")
-
-(defvar ruby-electric-matching-delimeter-alist
- '((?\[ . ?\])
- (?\( . ?\))
- (?\' . ?\')
- (?\` . ?\`)
- (?\" . ?\")))
-
-(defcustom ruby-electric-simple-keywords-re
- "\\(def\\|if\\|class\\|module\\|unless\\|case\\|while\\|do\\|until\\|for\\|begin\\)"
- "*Regular expresion matching keywords for which closing 'end'
-is to be inserted."
- :type 'regexp :group 'ruby-electric)
-
-(defcustom ruby-electric-expand-delimiters-list '(all)
- "*List of contexts where matching delimiter should be
-inserted. The word 'all' will do all insertions."
- :type '(set :extra-offset 8
- (const :tag "Everything" all )
- (const :tag "Curly brace" ?\{ )
- (const :tag "Square brace" ?\[ )
- (const :tag "Round brace" ?\( )
- (const :tag "Quote" ?\' )
- (const :tag "Double quote" ?\" )
- (const :tag "Back quote" ?\` )
- (const :tag "Vertical bar" ?\| ))
- :group 'ruby-electric)
-
-(defcustom ruby-electric-newline-before-closing-bracket nil
- "*Controls whether a newline should be inserted before the
-closing bracket or not."
- :type 'boolean :group 'ruby-electric)
-
-(define-minor-mode ruby-electric-mode
- "Toggle Ruby Electric minor mode.
-With no argument, this command toggles the mode. Non-null prefix
-argument turns on the mode. Null prefix argument turns off the
-mode.
-
-When Ruby Electric mode is enabled, an indented 'end' is
-heuristicaly inserted whenever typing a word like 'module',
-'class', 'def', 'if', 'unless', 'case', 'until', 'for', 'begin',
-'do'. Simple, double and back quotes as well as braces are paired
-auto-magically. Expansion does not occur inside comments and
-strings. Note that you must have Font Lock enabled."
- ;; initial value.
- nil
- ;;indicator for the mode line.
- " REl"
- ;;keymap
- ruby-mode-map
- (ruby-electric-setup-keymap))
-
-(defun ruby-electric-setup-keymap()
- (define-key ruby-mode-map " " 'ruby-electric-space)
- (define-key ruby-mode-map "{" 'ruby-electric-curlies)
- (define-key ruby-mode-map "(" 'ruby-electric-matching-char)
- (define-key ruby-mode-map "[" 'ruby-electric-matching-char)
- (define-key ruby-mode-map "\"" 'ruby-electric-matching-char)
- (define-key ruby-mode-map "\'" 'ruby-electric-matching-char)
- (define-key ruby-mode-map "|" 'ruby-electric-bar))
-
-(defun ruby-electric-space (arg)
- (interactive "P")
- (self-insert-command (prefix-numeric-value arg))
- (if (ruby-electric-space-can-be-expanded-p)
- (save-excursion
- (ruby-indent-line t)
- (newline)
- (ruby-insert-end))))
-
-(defun ruby-electric-code-at-point-p()
- (and ruby-electric-mode
- (let* ((properties (text-properties-at (point))))
- (and (null (memq 'font-lock-string-face properties))
- (null (memq 'font-lock-comment-face properties))))))
-
-(defun ruby-electric-string-at-point-p()
- (and ruby-electric-mode
- (consp (memq 'font-lock-string-face (text-properties-at (point))))))
-
-(defun ruby-electric-is-last-command-char-expandable-punct-p()
- (or (memq 'all ruby-electric-expand-delimiters-list)
- (memq last-command-char ruby-electric-expand-delimiters-list)))
-
-(defun ruby-electric-space-can-be-expanded-p()
- (if (ruby-electric-code-at-point-p)
- (let* ((ruby-electric-keywords-re
- (concat ruby-electric-simple-keywords-re "\\s-$"))
- (ruby-electric-single-keyword-in-line-re
- (concat "\\s-*" ruby-electric-keywords-re)))
- (save-excursion
- (backward-word 1)
- (or (looking-at ruby-electric-expandable-do-re)
- (and (looking-at ruby-electric-keywords-re)
- (not (string= "do" (match-string 1)))
- (progn
- (beginning-of-line)
- (looking-at ruby-electric-single-keyword-in-line-re))))))))
-
-
-(defun ruby-electric-curlies(arg)
- (interactive "P")
- (self-insert-command (prefix-numeric-value arg))
- (if (ruby-electric-is-last-command-char-expandable-punct-p)
- (cond ((ruby-electric-code-at-point-p)
- (insert " ")
- (save-excursion
- (if ruby-electric-newline-before-closing-bracket
- (newline))
- (insert "}")))
- ((ruby-electric-string-at-point-p)
- (save-excursion
- (backward-char 1)
- (when (char-equal ?\# (preceding-char))
- (forward-char 1)
- (insert "}")))))))
-
-(defun ruby-electric-matching-char(arg)
- (interactive "P")
- (self-insert-command (prefix-numeric-value arg))
- (and (ruby-electric-is-last-command-char-expandable-punct-p)
- (ruby-electric-code-at-point-p)
- (save-excursion
- (insert (cdr (assoc last-command-char
- ruby-electric-matching-delimeter-alist))))))
-
-(defun ruby-electric-bar(arg)
- (interactive "P")
- (self-insert-command (prefix-numeric-value arg))
- (and (ruby-electric-is-last-command-char-expandable-punct-p)
- (ruby-electric-code-at-point-p)
- (and (save-excursion (re-search-backward ruby-electric-expandable-bar nil t))
- (= (point) (match-end 0))) ;looking-back is missing on XEmacs
- (save-excursion
- (insert "|"))))
-
-
-(provide 'ruby-electric)
diff --git a/misc/ruby-mode.el b/misc/ruby-mode.el
index 294424434e..041ddc66ff 100644
--- a/misc/ruby-mode.el
+++ b/misc/ruby-mode.el
@@ -152,7 +152,7 @@
Also ignores spaces after parenthesis when 'space."
:group 'ruby)
-(defcustom ruby-deep-indent-paren '(?\( ?\[ ?\] t)
+(defcustom ruby-deep-indent-paren '(?\( t)
"*Deep indent lists in parenthesis when non-nil. t means continuous line.
Also ignores spaces after parenthesis when 'space."
:group 'ruby)
@@ -293,17 +293,15 @@ The variable ruby-indent-level controls the amount of indentation.
(move-to-column (+ x shift))))))
(defun ruby-special-char-p (&optional pnt)
- (setq pnt (or pnt (point)))
- (let ((c (char-before pnt)) (b (and (< (point-min) pnt) (char-before (1- pnt)))))
+ (let ((c (char-before (or pnt (point)))))
(cond ((or (eq c ??) (eq c ?$)))
- ((and (eq c ?:) (or (not b) (eq (char-syntax b) ? ))))
- ((eq c ?\\) (eq b ??)))))
+ ((eq c ?\\)
+ (eq (char-before (1- (or pnt (point)))) ??)))))
(defun ruby-expr-beg (&optional option)
(save-excursion
(store-match-data nil)
- (let ((space (skip-chars-backward " \t"))
- (start (point)))
+ (let ((space (skip-chars-backward " \t")))
(cond
((bolp) t)
((progn
@@ -312,10 +310,11 @@ The variable ruby-indent-level controls the amount of indentation.
(or (eq (char-syntax (char-before (point))) ?w)
(ruby-special-char-p))))
nil)
- ((and (eq option 'heredoc) (< space 0)) t)
((or (looking-at ruby-operator-re)
(looking-at "[\\[({,;]")
- (and (looking-at "[!?]")
+ (and (or (not (eq option 'heredoc))
+ (< space 0))
+ (looking-at "[!?]")
(or (not (eq option 'modifier))
(bolp)
(save-excursion (forward-char -1) (looking-at "\\Sw"))))
@@ -326,7 +325,7 @@ The variable ruby-indent-level controls the amount of indentation.
"|" ruby-block-op-re
"|" ruby-block-mid-re "\\)\\>")))
(goto-char (match-end 0))
- (not (looking-at "\\s_")))
+ (not (looking-at "\\s_")))
((eq option 'expr-qstr)
(looking-at "[a-zA-Z][a-zA-z0-9_]* +%[^ \t]"))
((eq option 'expr-re)
@@ -397,7 +396,7 @@ The variable ruby-indent-level controls the amount of indentation.
((and (not (eobp))
(ruby-expr-beg 'expr-qstr)
(not (looking-at "%="))
- (looking-at "%[QqrxWw]?\\([^a-zA-Z0-9 \t\n]\\)"))
+ (looking-at "%[QqrxWw]?\\(.\\)"))
(goto-char (match-beginning 1))
(setq expand (not (memq (char-before) '(?q ?w))))
(setq w (match-string 1))
@@ -504,11 +503,7 @@ The variable ruby-indent-level controls the amount of indentation.
(setq nest (cons (cons nil pnt) nest))
(setq depth (1+ depth)))
(goto-char pnt))
- ((looking-at ":\\(['\"]\\)\\(\\\\.\\|[^\\\\]\\)*\\1")
- (goto-char (match-end 0)))
- ((looking-at ":\\([-,.+*/%&|^~<>]=?\\|===?\\|<=>\\)")
- (goto-char (match-end 0)))
- ((looking-at ":\\([a-zA-Z_][a-zA-Z_0-9]*[!?=]?\\)?")
+ ((looking-at ":\\([a-zA-Z_][a-zA-Z_0-9]*\\)?")
(goto-char (match-end 0)))
((or (looking-at "\\.\\.\\.?")
(looking-at "\\.[0-9]+")
@@ -617,11 +612,7 @@ The variable ruby-indent-level controls the amount of indentation.
(t (setq indent (ruby-indent-size (1- indent) 1))))))
(if (nth 3 state) (goto-char (nth 3 state))
(goto-char parse-start) (back-to-indentation))
- (setq indent (ruby-indent-size (current-column) (nth 2 state))))
- (and (eq (car (nth 1 state)) paren)
- (ruby-deep-indent-paren-p (matching-paren paren))
- (search-backward (char-to-string paren))
- (setq indent (current-column)))))
+ (setq indent (ruby-indent-size (current-column) (nth 2 state))))))
((and (nth 2 state) (> (nth 2 state) 0)) ; in nest
(if (null (cdr (nth 1 state)))
(error "invalid nest"))
@@ -730,7 +721,6 @@ The variable ruby-indent-level controls the amount of indentation.
(goto-char (or begin parse-start))
(skip-syntax-forward " ")
(current-column)))
- ((car (nth 1 state)) indent)
(t
(+ indent ruby-indent-level))))))))
indent)))
@@ -1003,7 +993,7 @@ balanced expression is found."
("\\(#\\)[{$@]" 1 (1 . nil))
;; the last $', $", $` in the respective string is not variable
;; the last ?', ?", ?` in the respective string is not ascii code
- ("\\(^\\|[\[ \t\n<+\(,=]\\)\\(['\"`]\\)\\(\\\\.\\|\\2\\|[^'\"`\n\\\\]\\)*?\\\\?[?$]\\(\\2\\)"
+ ("\\(^\\|[\[ \t\n<+\(,=]\\)\\(['\"`]\\)\\(\\\\.\\|\\2\\|[^'\"`\n\\\\]\\)*\\\\?[?$]\\(\\2\\)"
(2 (7 . nil))
(4 (7 . nil)))
;; $' $" $` .... are variables
diff --git a/missing.h b/missing.h
index a4616950e3..ac499bd7d7 100644
--- a/missing.h
+++ b/missing.h
@@ -21,9 +21,6 @@ struct timeval {
time_t tv_usec; /* microseconds */
};
#endif
-#if defined(HAVE_SYS_TYPES_H)
-# include <sys/types.h>
-#endif
#ifndef HAVE_ACOSH
extern double acosh _((double));
@@ -84,6 +81,10 @@ extern int memcmp _((char *, char *, int));
extern void *memmove _((void *, void *, int));
#endif
+#ifndef HAVE_MKDIR
+extern int mkdir _((char *, int));
+#endif
+
/*
#ifndef HAVE_MODF
extern double modf _((double, double *));
diff --git a/missing/crypt.c b/missing/crypt.c
index 486df5050b..9f9b562c36 100644
--- a/missing/crypt.c
+++ b/missing/crypt.c
@@ -1,970 +1,276 @@
-/*
- * Copyright (c) 1989, 1993
- * The Regents of the University of California. All rights reserved.
- *
- * This code is derived from software contributed to Berkeley by
- * Tom Truscott.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * 3. Neither the name of the University nor the names of its contributors
- * may be used to endorse or promote products derived from this software
- * without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
- * SUCH DAMAGE.
- */
-
-#if defined(LIBC_SCCS) && !defined(lint)
-static char sccsid[] = "@(#)crypt.c 8.1 (Berkeley) 6/4/93";
-#endif /* LIBC_SCCS and not lint */
-
-#ifdef HAVE_UNISTD_H
-#include <unistd.h>
-#endif
-#include <limits.h>
-#ifdef HAVE_PWD_H
-#include <pwd.h>
-#endif
-#include <stdio.h>
-#ifndef _PASSWORD_EFMT1
-#define _PASSWORD_EFMT1 '_'
-#endif
-
-/*
- * UNIX password, and DES, encryption.
- * By Tom Truscott, trt@rti.rti.org,
- * from algorithms by Robert W. Baldwin and James Gillogly.
- *
- * References:
- * "Mathematical Cryptology for Computer Scientists and Mathematicians,"
- * by Wayne Patterson, 1987, ISBN 0-8476-7438-X.
- *
- * "Password Security: A Case History," R. Morris and Ken Thompson,
- * Communications of the ACM, vol. 22, pp. 594-597, Nov. 1979.
- *
- * "DES will be Totally Insecure within Ten Years," M.E. Hellman,
- * IEEE Spectrum, vol. 16, pp. 32-39, July 1979.
- */
-
-/* ===== Configuration ==================== */
-
-/*
- * define "MUST_ALIGN" if your compiler cannot load/store
- * long integers at arbitrary (e.g. odd) memory locations.
- * (Either that or never pass unaligned addresses to des_cipher!)
- */
-#if !defined(vax)
-#define MUST_ALIGN
-#endif
-
-#ifdef CHAR_BITS
-#if CHAR_BITS != 8
- #error C_block structure assumes 8 bit characters
-#endif
-#endif
-
-/*
- * define "LONG_IS_32_BITS" only if sizeof(long)==4.
- * This avoids use of bit fields (your compiler may be sloppy with them).
- */
-#if !defined(cray)
-#define LONG_IS_32_BITS
-#endif
-
-/*
- * define "B64" to be the declaration for a 64 bit integer.
- * XXX this feature is currently unused, see "endian" comment below.
- */
-#if defined(cray)
-#define B64 long
-#endif
-#if defined(convex)
-#define B64 long long
-#endif
-
-/*
- * define "LARGEDATA" to get faster permutations, by using about 72 kilobytes
- * of lookup tables. This speeds up des_setkey() and des_cipher(), but has
- * little effect on crypt().
- */
-#if defined(notdef)
-#define LARGEDATA
-#endif
-
-/* compile with "-DSTATIC=int" when profiling */
-#ifndef STATIC
-#define STATIC static
-#endif
-STATIC init_des(), init_perm(), permute();
-#ifdef DEBUG
-STATIC prtab();
-#endif
-
-/* ==================================== */
-
-/*
- * Cipher-block representation (Bob Baldwin):
- *
- * DES operates on groups of 64 bits, numbered 1..64 (sigh). One
- * representation is to store one bit per byte in an array of bytes. Bit N of
- * the NBS spec is stored as the LSB of the Nth byte (index N-1) in the array.
- * Another representation stores the 64 bits in 8 bytes, with bits 1..8 in the
- * first byte, 9..16 in the second, and so on. The DES spec apparently has
- * bit 1 in the MSB of the first byte, but that is particularly noxious so we
- * bit-reverse each byte so that bit 1 is the LSB of the first byte, bit 8 is
- * the MSB of the first byte. Specifically, the 64-bit input data and key are
- * converted to LSB format, and the output 64-bit block is converted back into
- * MSB format.
- *
- * DES operates internally on groups of 32 bits which are expanded to 48 bits
- * by permutation E and shrunk back to 32 bits by the S boxes. To speed up
- * the computation, the expansion is applied only once, the expanded
- * representation is maintained during the encryption, and a compression
- * permutation is applied only at the end. To speed up the S-box lookups,
- * the 48 bits are maintained as eight 6 bit groups, one per byte, which
- * directly feed the eight S-boxes. Within each byte, the 6 bits are the
- * most significant ones. The low two bits of each byte are zero. (Thus,
- * bit 1 of the 48 bit E expansion is stored as the "4"-valued bit of the
- * first byte in the eight byte representation, bit 2 of the 48 bit value is
- * the "8"-valued bit, and so on.) In fact, a combined "SPE"-box lookup is
- * used, in which the output is the 64 bit result of an S-box lookup which
- * has been permuted by P and expanded by E, and is ready for use in the next
- * iteration. Two 32-bit wide tables, SPE[0] and SPE[1], are used for this
- * lookup. Since each byte in the 48 bit path is a multiple of four, indexed
- * lookup of SPE[0] and SPE[1] is simple and fast. The key schedule and
- * "salt" are also converted to this 8*(6+2) format. The SPE table size is
- * 8*64*8 = 4K bytes.
- *
- * To speed up bit-parallel operations (such as XOR), the 8 byte
- * representation is "union"ed with 32 bit values "i0" and "i1", and, on
- * machines which support it, a 64 bit value "b64". This data structure,
- * "C_block", has two problems. First, alignment restrictions must be
- * honored. Second, the byte-order (e.g. little-endian or big-endian) of
- * the architecture becomes visible.
- *
- * The byte-order problem is unfortunate, since on the one hand it is good
- * to have a machine-independent C_block representation (bits 1..8 in the
- * first byte, etc.), and on the other hand it is good for the LSB of the
- * first byte to be the LSB of i0. We cannot have both these things, so we
- * currently use the "little-endian" representation and avoid any multi-byte
- * operations that depend on byte order. This largely precludes use of the
- * 64-bit datatype since the relative order of i0 and i1 are unknown. It
- * also inhibits grouping the SPE table to look up 12 bits at a time. (The
- * 12 bits can be stored in a 16-bit field with 3 low-order zeroes and 1
- * high-order zero, providing fast indexing into a 64-bit wide SPE.) On the
- * other hand, 64-bit datatypes are currently rare, and a 12-bit SPE lookup
- * requires a 128 kilobyte table, so perhaps this is not a big loss.
- *
- * Permutation representation (Jim Gillogly):
- *
- * A transformation is defined by its effect on each of the 8 bytes of the
- * 64-bit input. For each byte we give a 64-bit output that has the bits in
- * the input distributed appropriately. The transformation is then the OR
- * of the 8 sets of 64-bits. This uses 8*256*8 = 16K bytes of storage for
- * each transformation. Unless LARGEDATA is defined, however, a more compact
- * table is used which looks up 16 4-bit "chunks" rather than 8 8-bit chunks.
- * The smaller table uses 16*16*8 = 2K bytes for each transformation. This
- * is slower but tolerable, particularly for password encryption in which
- * the SPE transformation is iterated many times. The small tables total 9K
- * bytes, the large tables total 72K bytes.
- *
- * The transformations used are:
- * IE3264: MSB->LSB conversion, initial permutation, and expansion.
- * This is done by collecting the 32 even-numbered bits and applying
- * a 32->64 bit transformation, and then collecting the 32 odd-numbered
- * bits and applying the same transformation. Since there are only
- * 32 input bits, the IE3264 transformation table is half the size of
- * the usual table.
- * CF6464: Compression, final permutation, and LSB->MSB conversion.
- * This is done by two trivial 48->32 bit compressions to obtain
- * a 64-bit block (the bit numbering is given in the "CIFP" table)
- * followed by a 64->64 bit "cleanup" transformation. (It would
- * be possible to group the bits in the 64-bit block so that 2
- * identical 32->32 bit transformations could be used instead,
- * saving a factor of 4 in space and possibly 2 in time, but
- * byte-ordering and other complications rear their ugly head.
- * Similar opportunities/problems arise in the key schedule
- * transforms.)
- * PC1ROT: MSB->LSB, PC1 permutation, rotate, and PC2 permutation.
- * This admittedly baroque 64->64 bit transformation is used to
- * produce the first code (in 8*(6+2) format) of the key schedule.
- * PC2ROT[0]: Inverse PC2 permutation, rotate, and PC2 permutation.
- * It would be possible to define 15 more transformations, each
- * with a different rotation, to generate the entire key schedule.
- * To save space, however, we instead permute each code into the
- * next by using a transformation that "undoes" the PC2 permutation,
- * rotates the code, and then applies PC2. Unfortunately, PC2
- * transforms 56 bits into 48 bits, dropping 8 bits, so PC2 is not
- * invertible. We get around that problem by using a modified PC2
- * which retains the 8 otherwise-lost bits in the unused low-order
- * bits of each byte. The low-order bits are cleared when the
- * codes are stored into the key schedule.
- * PC2ROT[1]: Same as PC2ROT[0], but with two rotations.
- * This is faster than applying PC2ROT[0] twice,
- *
- * The Bell Labs "salt" (Bob Baldwin):
- *
- * The salting is a simple permutation applied to the 48-bit result of E.
- * Specifically, if bit i (1 <= i <= 24) of the salt is set then bits i and
- * i+24 of the result are swapped. The salt is thus a 24 bit number, with
- * 16777216 possible values. (The original salt was 12 bits and could not
- * swap bits 13..24 with 36..48.)
- *
- * It is possible, but ugly, to warp the SPE table to account for the salt
- * permutation. Fortunately, the conditional bit swapping requires only
- * about four machine instructions and can be done on-the-fly with about an
- * 8% performance penalty.
- */
-
-typedef union {
- unsigned char b[8];
- struct {
-#if defined(LONG_IS_32_BITS)
- /* long is often faster than a 32-bit bit field */
- long i0;
- long i1;
-#else
- long i0: 32;
- long i1: 32;
-#endif
- } b32;
-#if defined(B64)
- B64 b64;
-#endif
-} C_block;
-
-/*
- * Convert twenty-four-bit long in host-order
- * to six bits (and 2 low-order zeroes) per char little-endian format.
- */
-#define TO_SIX_BIT(rslt, src) { \
- C_block cvt; \
- cvt.b[0] = src; src >>= 6; \
- cvt.b[1] = src; src >>= 6; \
- cvt.b[2] = src; src >>= 6; \
- cvt.b[3] = src; \
- rslt = (cvt.b32.i0 & 0x3f3f3f3fL) << 2; \
- }
-
-/*
- * These macros may someday permit efficient use of 64-bit integers.
- */
-#define ZERO(d,d0,d1) d0 = 0, d1 = 0
-#define LOAD(d,d0,d1,bl) d0 = (bl).b32.i0, d1 = (bl).b32.i1
-#define LOADREG(d,d0,d1,s,s0,s1) d0 = s0, d1 = s1
-#define OR(d,d0,d1,bl) d0 |= (bl).b32.i0, d1 |= (bl).b32.i1
-#define STORE(s,s0,s1,bl) (bl).b32.i0 = s0, (bl).b32.i1 = s1
-#define DCL_BLOCK(d,d0,d1) long d0, d1
-
-#if defined(LARGEDATA)
- /* Waste memory like crazy. Also, do permutations in line */
-#define LGCHUNKBITS 3
-#define CHUNKBITS (1<<LGCHUNKBITS)
-#define PERM6464(d,d0,d1,cpp,p) \
- LOAD(d,d0,d1,(p)[(0<<CHUNKBITS)+(cpp)[0]]); \
- OR (d,d0,d1,(p)[(1<<CHUNKBITS)+(cpp)[1]]); \
- OR (d,d0,d1,(p)[(2<<CHUNKBITS)+(cpp)[2]]); \
- OR (d,d0,d1,(p)[(3<<CHUNKBITS)+(cpp)[3]]); \
- OR (d,d0,d1,(p)[(4<<CHUNKBITS)+(cpp)[4]]); \
- OR (d,d0,d1,(p)[(5<<CHUNKBITS)+(cpp)[5]]); \
- OR (d,d0,d1,(p)[(6<<CHUNKBITS)+(cpp)[6]]); \
- OR (d,d0,d1,(p)[(7<<CHUNKBITS)+(cpp)[7]]);
-#define PERM3264(d,d0,d1,cpp,p) \
- LOAD(d,d0,d1,(p)[(0<<CHUNKBITS)+(cpp)[0]]); \
- OR (d,d0,d1,(p)[(1<<CHUNKBITS)+(cpp)[1]]); \
- OR (d,d0,d1,(p)[(2<<CHUNKBITS)+(cpp)[2]]); \
- OR (d,d0,d1,(p)[(3<<CHUNKBITS)+(cpp)[3]]);
-#else
- /* "small data" */
-#define LGCHUNKBITS 2
-#define CHUNKBITS (1<<LGCHUNKBITS)
-#define PERM6464(d,d0,d1,cpp,p) \
- { C_block tblk; permute(cpp,&tblk,p,8); LOAD (d,d0,d1,tblk); }
-#define PERM3264(d,d0,d1,cpp,p) \
- { C_block tblk; permute(cpp,&tblk,p,4); LOAD (d,d0,d1,tblk); }
-
-STATIC
-permute(cp, out, p, chars_in)
- unsigned char *cp;
- C_block *out;
- register C_block *p;
- int chars_in;
-{
- register DCL_BLOCK(D,D0,D1);
- register C_block *tp;
- register int t;
-
- ZERO(D,D0,D1);
- do {
- t = *cp++;
- tp = &p[t&0xf]; OR(D,D0,D1,*tp); p += (1<<CHUNKBITS);
- tp = &p[t>>4]; OR(D,D0,D1,*tp); p += (1<<CHUNKBITS);
- } while (--chars_in > 0);
- STORE(D,D0,D1,*out);
-}
-#endif /* LARGEDATA */
-
-
-/* ===== (mostly) Standard DES Tables ==================== */
+/* From Andy Tanenbaum's book "Computer Networks",
+ rewritten in C
+*/
-static unsigned char IP[] = { /* initial permutation */
- 58, 50, 42, 34, 26, 18, 10, 2,
- 60, 52, 44, 36, 28, 20, 12, 4,
- 62, 54, 46, 38, 30, 22, 14, 6,
- 64, 56, 48, 40, 32, 24, 16, 8,
- 57, 49, 41, 33, 25, 17, 9, 1,
- 59, 51, 43, 35, 27, 19, 11, 3,
- 61, 53, 45, 37, 29, 21, 13, 5,
- 63, 55, 47, 39, 31, 23, 15, 7,
+struct block {
+ unsigned char b_data[64];
};
-/* The final permutation is the inverse of IP - no table is necessary */
-
-static unsigned char ExpandTr[] = { /* expansion operation */
- 32, 1, 2, 3, 4, 5,
- 4, 5, 6, 7, 8, 9,
- 8, 9, 10, 11, 12, 13,
- 12, 13, 14, 15, 16, 17,
- 16, 17, 18, 19, 20, 21,
- 20, 21, 22, 23, 24, 25,
- 24, 25, 26, 27, 28, 29,
- 28, 29, 30, 31, 32, 1,
+struct ordering {
+ unsigned char o_data[64];
};
-static unsigned char PC1[] = { /* permuted choice table 1 */
- 57, 49, 41, 33, 25, 17, 9,
- 1, 58, 50, 42, 34, 26, 18,
- 10, 2, 59, 51, 43, 35, 27,
- 19, 11, 3, 60, 52, 44, 36,
+static struct block key;
- 63, 55, 47, 39, 31, 23, 15,
- 7, 62, 54, 46, 38, 30, 22,
- 14, 6, 61, 53, 45, 37, 29,
- 21, 13, 5, 28, 20, 12, 4,
+static struct ordering InitialTr = {
+ 58,50,42,34,26,18,10, 2,60,52,44,36,28,20,12, 4,
+ 62,54,46,38,30,22,14, 6,64,56,48,40,32,24,16, 8,
+ 57,49,41,33,25,17, 9, 1,59,51,43,35,27,19,11, 3,
+ 61,53,45,37,29,21,13, 5,63,55,47,39,31,23,15, 7,
};
-static unsigned char Rotates[] = { /* PC1 rotation schedule */
- 1, 1, 2, 2, 2, 2, 2, 2, 1, 2, 2, 2, 2, 2, 2, 1,
+static struct ordering FinalTr = {
+ 40, 8,48,16,56,24,64,32,39, 7,47,15,55,23,63,31,
+ 38, 6,46,14,54,22,62,30,37, 5,45,13,53,21,61,29,
+ 36, 4,44,12,52,20,60,28,35, 3,43,11,51,19,59,27,
+ 34, 2,42,10,50,18,58,26,33, 1,41, 9,49,17,57,25,
};
-/* note: each "row" of PC2 is left-padded with bits that make it invertible */
-static unsigned char PC2[] = { /* permuted choice table 2 */
- 9, 18, 14, 17, 11, 24, 1, 5,
- 22, 25, 3, 28, 15, 6, 21, 10,
- 35, 38, 23, 19, 12, 4, 26, 8,
- 43, 54, 16, 7, 27, 20, 13, 2,
-
- 0, 0, 41, 52, 31, 37, 47, 55,
- 0, 0, 30, 40, 51, 45, 33, 48,
- 0, 0, 44, 49, 39, 56, 34, 53,
- 0, 0, 46, 42, 50, 36, 29, 32,
+static struct ordering swap = {
+ 33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,
+ 49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,
+ 1, 2, 3, 4, 5, 6, 7, 8, 9,10,11,12,13,14,15,16,
+ 17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,
};
-static unsigned char S[8][64] = { /* 48->32 bit substitution tables */
- /* S[1] */
- 14, 4, 13, 1, 2, 15, 11, 8, 3, 10, 6, 12, 5, 9, 0, 7,
- 0, 15, 7, 4, 14, 2, 13, 1, 10, 6, 12, 11, 9, 5, 3, 8,
- 4, 1, 14, 8, 13, 6, 2, 11, 15, 12, 9, 7, 3, 10, 5, 0,
- 15, 12, 8, 2, 4, 9, 1, 7, 5, 11, 3, 14, 10, 0, 6, 13,
- /* S[2] */
- 15, 1, 8, 14, 6, 11, 3, 4, 9, 7, 2, 13, 12, 0, 5, 10,
- 3, 13, 4, 7, 15, 2, 8, 14, 12, 0, 1, 10, 6, 9, 11, 5,
- 0, 14, 7, 11, 10, 4, 13, 1, 5, 8, 12, 6, 9, 3, 2, 15,
- 13, 8, 10, 1, 3, 15, 4, 2, 11, 6, 7, 12, 0, 5, 14, 9,
- /* S[3] */
- 10, 0, 9, 14, 6, 3, 15, 5, 1, 13, 12, 7, 11, 4, 2, 8,
- 13, 7, 0, 9, 3, 4, 6, 10, 2, 8, 5, 14, 12, 11, 15, 1,
- 13, 6, 4, 9, 8, 15, 3, 0, 11, 1, 2, 12, 5, 10, 14, 7,
- 1, 10, 13, 0, 6, 9, 8, 7, 4, 15, 14, 3, 11, 5, 2, 12,
- /* S[4] */
- 7, 13, 14, 3, 0, 6, 9, 10, 1, 2, 8, 5, 11, 12, 4, 15,
- 13, 8, 11, 5, 6, 15, 0, 3, 4, 7, 2, 12, 1, 10, 14, 9,
- 10, 6, 9, 0, 12, 11, 7, 13, 15, 1, 3, 14, 5, 2, 8, 4,
- 3, 15, 0, 6, 10, 1, 13, 8, 9, 4, 5, 11, 12, 7, 2, 14,
- /* S[5] */
- 2, 12, 4, 1, 7, 10, 11, 6, 8, 5, 3, 15, 13, 0, 14, 9,
- 14, 11, 2, 12, 4, 7, 13, 1, 5, 0, 15, 10, 3, 9, 8, 6,
- 4, 2, 1, 11, 10, 13, 7, 8, 15, 9, 12, 5, 6, 3, 0, 14,
- 11, 8, 12, 7, 1, 14, 2, 13, 6, 15, 0, 9, 10, 4, 5, 3,
- /* S[6] */
- 12, 1, 10, 15, 9, 2, 6, 8, 0, 13, 3, 4, 14, 7, 5, 11,
- 10, 15, 4, 2, 7, 12, 9, 5, 6, 1, 13, 14, 0, 11, 3, 8,
- 9, 14, 15, 5, 2, 8, 12, 3, 7, 0, 4, 10, 1, 13, 11, 6,
- 4, 3, 2, 12, 9, 5, 15, 10, 11, 14, 1, 7, 6, 0, 8, 13,
- /* S[7] */
- 4, 11, 2, 14, 15, 0, 8, 13, 3, 12, 9, 7, 5, 10, 6, 1,
- 13, 0, 11, 7, 4, 9, 1, 10, 14, 3, 5, 12, 2, 15, 8, 6,
- 1, 4, 11, 13, 12, 3, 7, 14, 10, 15, 6, 8, 0, 5, 9, 2,
- 6, 11, 13, 8, 1, 4, 10, 7, 9, 5, 0, 15, 14, 2, 3, 12,
- /* S[8] */
- 13, 2, 8, 4, 6, 15, 11, 1, 10, 9, 3, 14, 5, 0, 12, 7,
- 1, 15, 13, 8, 10, 3, 7, 4, 12, 5, 6, 11, 0, 14, 9, 2,
- 7, 11, 4, 1, 9, 12, 14, 2, 0, 6, 10, 13, 15, 3, 5, 8,
- 2, 1, 14, 7, 4, 10, 8, 13, 15, 12, 9, 0, 3, 5, 6, 11,
+static struct ordering KeyTr1 = {
+ 57,49,41,33,25,17, 9, 1,58,50,42,34,26,18,
+ 10, 2,59,51,43,35,27,19,11, 3,60,52,44,36,
+ 63,55,47,39,31,23,15, 7,62,54,46,38,30,22,
+ 14, 6,61,53,45,37,29,21,13, 5,28,20,12, 4,
};
-static unsigned char P32Tr[] = { /* 32-bit permutation function */
- 16, 7, 20, 21,
- 29, 12, 28, 17,
- 1, 15, 23, 26,
- 5, 18, 31, 10,
- 2, 8, 24, 14,
- 32, 27, 3, 9,
- 19, 13, 30, 6,
- 22, 11, 4, 25,
+static struct ordering KeyTr2 = {
+ 14,17,11,24, 1, 5, 3,28,15, 6,21,10,
+ 23,19,12, 4,26, 8,16, 7,27,20,13, 2,
+ 41,52,31,37,47,55,30,40,51,45,33,48,
+ 44,49,39,56,34,53,46,42,50,36,29,32,
};
-static unsigned char CIFP[] = { /* compressed/interleaved permutation */
- 1, 2, 3, 4, 17, 18, 19, 20,
- 5, 6, 7, 8, 21, 22, 23, 24,
- 9, 10, 11, 12, 25, 26, 27, 28,
- 13, 14, 15, 16, 29, 30, 31, 32,
-
- 33, 34, 35, 36, 49, 50, 51, 52,
- 37, 38, 39, 40, 53, 54, 55, 56,
- 41, 42, 43, 44, 57, 58, 59, 60,
- 45, 46, 47, 48, 61, 62, 63, 64,
+static struct ordering etr = {
+ 32, 1, 2, 3, 4, 5, 4, 5, 6, 7, 8, 9,
+ 8, 9,10,11,12,13,12,13,14,15,16,17,
+ 16,17,18,19,20,21,20,21,22,23,24,25,
+ 24,25,26,27,28,29,28,29,30,31,32, 1,
};
-static unsigned char itoa64[] = /* 0..63 => ascii-64 */
- "./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
-
-
-/* ===== Tables that are initialized at run time ==================== */
-
-
-static unsigned char a64toi[128]; /* ascii-64 => 0..63 */
-
-/* Initial key schedule permutation */
-static C_block PC1ROT[64/CHUNKBITS][1<<CHUNKBITS];
-
-/* Subsequent key schedule rotation permutations */
-static C_block PC2ROT[2][64/CHUNKBITS][1<<CHUNKBITS];
-
-/* Initial permutation/expansion table */
-static C_block IE3264[32/CHUNKBITS][1<<CHUNKBITS];
-
-/* Table that combines the S, P, and E operations. */
-static long SPE[2][8][64];
-
-/* compressed/interleaved => final permutation table */
-static C_block CF6464[64/CHUNKBITS][1<<CHUNKBITS];
-
-
-/* ==================================== */
+static struct ordering ptr = {
+ 16, 7,20,21,29,12,28,17, 1,15,23,26, 5,18,31,10,
+ 2, 8,24,14,32,27, 3, 9,19,13,30, 6,22,11, 4,25,
+};
+static unsigned char s_boxes[8][64] = {
+{ 14, 4,13, 1, 2,15,11, 8, 3,10, 6,12, 5, 9, 0, 7,
+ 0,15, 7, 4,14, 2,13, 1,10, 6,12,11, 9, 5, 3, 8,
+ 4, 1,14, 8,13, 6, 2,11,15,12, 9, 7, 3,10, 5, 0,
+ 15,12, 8, 2, 4, 9, 1, 7, 5,11, 3,14,10, 0, 6,13,
+},
+
+{ 15, 1, 8,14, 6,11, 3, 4, 9, 7, 2,13,12, 0, 5,10,
+ 3,13, 4, 7,15, 2, 8,14,12, 0, 1,10, 6, 9,11, 5,
+ 0,14, 7,11,10, 4,13, 1, 5, 8,12, 6, 9, 3, 2,15,
+ 13, 8,10, 1, 3,15, 4, 2,11, 6, 7,12, 0, 5,14, 9,
+},
+
+{ 10, 0, 9,14, 6, 3,15, 5, 1,13,12, 7,11, 4, 2, 8,
+ 13, 7, 0, 9, 3, 4, 6,10, 2, 8, 5,14,12,11,15, 1,
+ 13, 6, 4, 9, 8,15, 3, 0,11, 1, 2,12, 5,10,14, 7,
+ 1,10,13, 0, 6, 9, 8, 7, 4,15,14, 3,11, 5, 2,12,
+},
+
+{ 7,13,14, 3, 0, 6, 9,10, 1, 2, 8, 5,11,12, 4,15,
+ 13, 8,11, 5, 6,15, 0, 3, 4, 7, 2,12, 1,10,14, 9,
+ 10, 6, 9, 0,12,11, 7,13,15, 1, 3,14, 5, 2, 8, 4,
+ 3,15, 0, 6,10, 1,13, 8, 9, 4, 5,11,12, 7, 2,14,
+},
+
+{ 2,12, 4, 1, 7,10,11, 6, 8, 5, 3,15,13, 0,14, 9,
+ 14,11, 2,12, 4, 7,13, 1, 5, 0,15,10, 3, 9, 8, 6,
+ 4, 2, 1,11,10,13, 7, 8,15, 9,12, 5, 6, 3, 0,14,
+ 11, 8,12, 7, 1,14, 2,13, 6,15, 0, 9,10, 4, 5, 3,
+},
+
+{ 12, 1,10,15, 9, 2, 6, 8, 0,13, 3, 4,14, 7, 5,11,
+ 10,15, 4, 2, 7,12, 9, 5, 6, 1,13,14, 0,11, 3, 8,
+ 9,14,15, 5, 2, 8,12, 3, 7, 0, 4,10, 1,13,11, 6,
+ 4, 3, 2,12, 9, 5,15,10,11,14, 1, 7, 6, 0, 8,13,
+},
+
+{ 4,11, 2,14,15, 0, 8,13, 3,12, 9, 7, 5,10, 6, 1,
+ 13, 0,11, 7, 4, 9, 1,10,14, 3, 5,12, 2,15, 8, 6,
+ 1, 4,11,13,12, 3, 7,14,10,15, 6, 8, 0, 5, 9, 2,
+ 6,11,13, 8, 1, 4,10, 7, 9, 5, 0,15,14, 2, 3,12,
+},
+
+{ 13, 2, 8, 4, 6,15,11, 1,10, 9, 3,14, 5, 0,12, 7,
+ 1,15,13, 8,10, 3, 7, 4,12, 5, 6,11, 0,14, 9, 2,
+ 7,11, 4, 1, 9,12,14, 2, 0, 6,10,13,15, 3, 5, 8,
+ 2, 1,14, 7, 4,10, 8,13,15,12, 9, 0, 3, 5, 6,11,
+},
+};
-static C_block constdatablock; /* encryption constant */
-static char cryptresult[1+4+4+11+1]; /* encrypted result */
+static int rots[] = {
+ 1,1,2,2,2,2,2,2,1,2,2,2,2,2,2,1,
+};
-/*
- * Return a pointer to static data consisting of the "setting"
- * followed by an encryption produced by the "key" and "setting".
- */
-char *
-crypt(key, setting)
- register const char *key;
- register const char *setting;
+static void transpose(struct block *data, struct ordering *t, int n)
{
- register char *encp;
- register long i;
- register int t;
- long salt;
- int num_iter, salt_size;
- C_block keyblock, rsltblock;
-
- for (i = 0; i < 8; i++) {
- if ((t = 2*(unsigned char)(*key)) != 0)
- key++;
- keyblock.b[i] = t;
- }
- if (des_setkey((char *)keyblock.b)) /* also initializes "a64toi" */
- return (NULL);
-
- encp = &cryptresult[0];
- switch (*setting) {
- case _PASSWORD_EFMT1:
- /*
- * Involve the rest of the password 8 characters at a time.
- */
- while (*key) {
- if (des_cipher((char *)&keyblock,
- (char *)&keyblock, 0L, 1))
- return (NULL);
- for (i = 0; i < 8; i++) {
- if ((t = 2*(unsigned char)(*key)) != 0)
- key++;
- keyblock.b[i] ^= t;
- }
- if (des_setkey((char *)keyblock.b))
- return (NULL);
- }
-
- *encp++ = *setting++;
-
- /* get iteration count */
- num_iter = 0;
- for (i = 4; --i >= 0; ) {
- if ((t = (unsigned char)setting[i]) == '\0')
- t = '.';
- encp[i] = t;
- num_iter = (num_iter<<6) | a64toi[t];
- }
- setting += 4;
- encp += 4;
- salt_size = 4;
- break;
- default:
- num_iter = 25;
- salt_size = 2;
- }
-
- salt = 0;
- for (i = salt_size; --i >= 0; ) {
- if ((t = (unsigned char)setting[i]) == '\0')
- t = '.';
- encp[i] = t;
- salt = (salt<<6) | a64toi[t];
- }
- encp += salt_size;
- if (des_cipher((char *)&constdatablock, (char *)&rsltblock,
- salt, num_iter))
- return (NULL);
-
- /*
- * Encode the 64 cipher bits as 11 ascii characters.
- */
- i = ((long)((rsltblock.b[0]<<8) | rsltblock.b[1])<<8) | rsltblock.b[2];
- encp[3] = itoa64[i&0x3f]; i >>= 6;
- encp[2] = itoa64[i&0x3f]; i >>= 6;
- encp[1] = itoa64[i&0x3f]; i >>= 6;
- encp[0] = itoa64[i]; encp += 4;
- i = ((long)((rsltblock.b[3]<<8) | rsltblock.b[4])<<8) | rsltblock.b[5];
- encp[3] = itoa64[i&0x3f]; i >>= 6;
- encp[2] = itoa64[i&0x3f]; i >>= 6;
- encp[1] = itoa64[i&0x3f]; i >>= 6;
- encp[0] = itoa64[i]; encp += 4;
- i = ((long)((rsltblock.b[6])<<8) | rsltblock.b[7])<<2;
- encp[2] = itoa64[i&0x3f]; i >>= 6;
- encp[1] = itoa64[i&0x3f]; i >>= 6;
- encp[0] = itoa64[i];
-
- encp[3] = 0;
-
- return (cryptresult);
-}
+ struct block x;
+ x = *data;
-/*
- * The Key Schedule, filled in by des_setkey() or setkey().
- */
-#define KS_SIZE 16
-static C_block KS[KS_SIZE];
-
-/*
- * Set up the key schedule from the key.
- */
-des_setkey(key)
- register const char *key;
-{
- register DCL_BLOCK(K, K0, K1);
- register C_block *ptabp;
- register int i;
- static int des_ready = 0;
-
- if (!des_ready) {
- init_des();
- des_ready = 1;
- }
-
- PERM6464(K,K0,K1,(unsigned char *)key,(C_block *)PC1ROT);
- key = (char *)&KS[0];
- STORE(K&~0x03030303L, K0&~0x03030303L, K1, *(C_block *)key);
- for (i = 1; i < 16; i++) {
- key += sizeof(C_block);
- STORE(K,K0,K1,*(C_block *)key);
- ptabp = (C_block *)PC2ROT[Rotates[i]-1];
- PERM6464(K,K0,K1,(unsigned char *)key,ptabp);
- STORE(K&~0x03030303L, K0&~0x03030303L, K1, *(C_block *)key);
- }
- return (0);
+ while (n-- > 0) {
+ data->b_data[n] = x.b_data[t->o_data[n] - 1];
+ }
}
-/*
- * Encrypt (or decrypt if num_iter < 0) the 8 chars at "in" with abs(num_iter)
- * iterations of DES, using the the given 24-bit salt and the pre-computed key
- * schedule, and store the resulting 8 chars at "out" (in == out is permitted).
- *
- * NOTE: the performance of this routine is critically dependent on your
- * compiler and machine architecture.
- */
-des_cipher(in, out, salt, num_iter)
- const char *in;
- char *out;
- long salt;
- int num_iter;
+static void rotate(struct block *key)
{
- /* variables that we want in registers, most important first */
-#if defined(pdp11)
- register int j;
-#endif
- register long L0, L1, R0, R1, k;
- register C_block *kp;
- register int ks_inc, loop_count;
- C_block B;
-
- L0 = salt;
- TO_SIX_BIT(salt, L0); /* convert to 4*(6+2) format */
-
-#if defined(vax) || defined(pdp11)
- salt = ~salt; /* "x &~ y" is faster than "x & y". */
-#define SALT (~salt)
-#else
-#define SALT salt
-#endif
-
-#if defined(MUST_ALIGN)
- B.b[0] = in[0]; B.b[1] = in[1]; B.b[2] = in[2]; B.b[3] = in[3];
- B.b[4] = in[4]; B.b[5] = in[5]; B.b[6] = in[6]; B.b[7] = in[7];
- LOAD(L,L0,L1,B);
-#else
- LOAD(L,L0,L1,*(C_block *)in);
-#endif
- LOADREG(R,R0,R1,L,L0,L1);
- L0 &= 0x55555555L;
- L1 &= 0x55555555L;
- L0 = (L0 << 1) | L1; /* L0 is the even-numbered input bits */
- R0 &= 0xaaaaaaaaL;
- R1 = (R1 >> 1) & 0x55555555L;
- L1 = R0 | R1; /* L1 is the odd-numbered input bits */
- STORE(L,L0,L1,B);
- PERM3264(L,L0,L1,B.b, (C_block *)IE3264); /* even bits */
- PERM3264(R,R0,R1,B.b+4,(C_block *)IE3264); /* odd bits */
-
- if (num_iter >= 0)
- { /* encryption */
- kp = &KS[0];
- ks_inc = sizeof(*kp);
- }
- else
- { /* decryption */
- num_iter = -num_iter;
- kp = &KS[KS_SIZE-1];
- ks_inc = -sizeof(*kp);
- }
-
- while (--num_iter >= 0) {
- loop_count = 8;
- do {
-
-#define SPTAB(t, i) (*(long *)((unsigned char *)t + i*(sizeof(long)/4)))
-#if defined(gould)
- /* use this if B.b[i] is evaluated just once ... */
-#define DOXOR(x,y,i) x^=SPTAB(SPE[0][i],B.b[i]); y^=SPTAB(SPE[1][i],B.b[i]);
-#else
-#if defined(pdp11)
- /* use this if your "long" int indexing is slow */
-#define DOXOR(x,y,i) j=B.b[i]; x^=SPTAB(SPE[0][i],j); y^=SPTAB(SPE[1][i],j);
-#else
- /* use this if "k" is allocated to a register ... */
-#define DOXOR(x,y,i) k=B.b[i]; x^=SPTAB(SPE[0][i],k); y^=SPTAB(SPE[1][i],k);
-#endif
-#endif
-
-#define CRUNCH(p0, p1, q0, q1) \
- k = (q0 ^ q1) & SALT; \
- B.b32.i0 = k ^ q0 ^ kp->b32.i0; \
- B.b32.i1 = k ^ q1 ^ kp->b32.i1; \
- kp = (C_block *)((char *)kp+ks_inc); \
- \
- DOXOR(p0, p1, 0); \
- DOXOR(p0, p1, 1); \
- DOXOR(p0, p1, 2); \
- DOXOR(p0, p1, 3); \
- DOXOR(p0, p1, 4); \
- DOXOR(p0, p1, 5); \
- DOXOR(p0, p1, 6); \
- DOXOR(p0, p1, 7);
-
- CRUNCH(L0, L1, R0, R1);
- CRUNCH(R0, R1, L0, L1);
- } while (--loop_count != 0);
- kp = (C_block *)((char *)kp-(ks_inc*KS_SIZE));
-
-
- /* swap L and R */
- L0 ^= R0; L1 ^= R1;
- R0 ^= L0; R1 ^= L1;
- L0 ^= R0; L1 ^= R1;
- }
-
- /* store the encrypted (or decrypted) result */
- L0 = ((L0 >> 3) & 0x0f0f0f0fL) | ((L1 << 1) & 0xf0f0f0f0L);
- L1 = ((R0 >> 3) & 0x0f0f0f0fL) | ((R1 << 1) & 0xf0f0f0f0L);
- STORE(L,L0,L1,B);
- PERM6464(L,L0,L1,B.b, (C_block *)CF6464);
-#if defined(MUST_ALIGN)
- STORE(L,L0,L1,B);
- out[0] = B.b[0]; out[1] = B.b[1]; out[2] = B.b[2]; out[3] = B.b[3];
- out[4] = B.b[4]; out[5] = B.b[5]; out[6] = B.b[6]; out[7] = B.b[7];
-#else
- STORE(L,L0,L1,*(C_block *)out);
-#endif
- return (0);
+ register unsigned char *p = key->b_data;
+ register unsigned char *ep = &(key->b_data[55]);
+ int data0 = key->b_data[0], data28 = key->b_data[28];
+
+ while (p++ < ep) *(p-1) = *p;
+ key->b_data[27] = (char) data0;
+ key->b_data[55] = (char) data28;
}
+static struct ordering *EP = &etr;
-/*
- * Initialize various tables. This need only be done once. It could even be
- * done at compile time, if the compiler were capable of that sort of thing.
- */
-STATIC
-init_des()
+static void f(int i, struct block *key, struct block *a, struct block *x)
{
- register int i, j;
- register long k;
- register int tableno;
- static unsigned char perm[64], tmp32[32]; /* "static" for speed */
-
- /*
- * table that converts chars "./0-9A-Za-z"to integers 0-63.
- */
- for (i = 0; i < 64; i++)
- a64toi[itoa64[i]] = i;
-
- /*
- * PC1ROT - bit reverse, then PC1, then Rotate, then PC2.
- */
- for (i = 0; i < 64; i++)
- perm[i] = 0;
- for (i = 0; i < 64; i++) {
- if ((k = PC2[i]) == 0)
- continue;
- k += Rotates[0]-1;
- if ((k%28) < Rotates[0]) k -= 28;
- k = PC1[k];
- if (k > 0) {
- k--;
- k = (k|07) - (k&07);
- k++;
- }
- perm[i] = k;
- }
-#ifdef DEBUG
- prtab("pc1tab", perm, 8);
-#endif
- init_perm(PC1ROT, perm, 8, 8);
-
- /*
- * PC2ROT - PC2 inverse, then Rotate (once or twice), then PC2.
- */
- for (j = 0; j < 2; j++) {
- unsigned char pc2inv[64];
- for (i = 0; i < 64; i++)
- perm[i] = pc2inv[i] = 0;
- for (i = 0; i < 64; i++) {
- if ((k = PC2[i]) == 0)
- continue;
- pc2inv[k-1] = i+1;
- }
- for (i = 0; i < 64; i++) {
- if ((k = PC2[i]) == 0)
- continue;
- k += j;
- if ((k%28) <= j) k -= 28;
- perm[i] = pc2inv[k];
- }
-#ifdef DEBUG
- prtab("pc2tab", perm, 8);
-#endif
- init_perm(PC2ROT[j], perm, 8, 8);
- }
-
- /*
- * Bit reverse, then initial permutation, then expansion.
- */
- for (i = 0; i < 8; i++) {
- for (j = 0; j < 8; j++) {
- k = (j < 2)? 0: IP[ExpandTr[i*6+j-2]-1];
- if (k > 32)
- k -= 32;
- else if (k > 0)
- k--;
- if (k > 0) {
- k--;
- k = (k|07) - (k&07);
- k++;
- }
- perm[i*8+j] = k;
- }
- }
-#ifdef DEBUG
- prtab("ietab", perm, 8);
-#endif
- init_perm(IE3264, perm, 4, 8);
-
- /*
- * Compression, then final permutation, then bit reverse.
- */
- for (i = 0; i < 64; i++) {
- k = IP[CIFP[i]-1];
- if (k > 0) {
- k--;
- k = (k|07) - (k&07);
- k++;
- }
- perm[k-1] = i+1;
- }
-#ifdef DEBUG
- prtab("cftab", perm, 8);
-#endif
- init_perm(CF6464, perm, 8, 8);
-
- /*
- * SPE table
- */
- for (i = 0; i < 48; i++)
- perm[i] = P32Tr[ExpandTr[i]-1];
- for (tableno = 0; tableno < 8; tableno++) {
- for (j = 0; j < 64; j++) {
- k = (((j >> 0) &01) << 5)|
- (((j >> 1) &01) << 3)|
- (((j >> 2) &01) << 2)|
- (((j >> 3) &01) << 1)|
- (((j >> 4) &01) << 0)|
- (((j >> 5) &01) << 4);
- k = S[tableno][k];
- k = (((k >> 3)&01) << 0)|
- (((k >> 2)&01) << 1)|
- (((k >> 1)&01) << 2)|
- (((k >> 0)&01) << 3);
- for (i = 0; i < 32; i++)
- tmp32[i] = 0;
- for (i = 0; i < 4; i++)
- tmp32[4 * tableno + i] = (k >> i) & 01;
- k = 0;
- for (i = 24; --i >= 0; )
- k = (k<<1) | tmp32[perm[i]-1];
- TO_SIX_BIT(SPE[0][tableno][j], k);
- k = 0;
- for (i = 24; --i >= 0; )
- k = (k<<1) | tmp32[perm[i+24]-1];
- TO_SIX_BIT(SPE[1][tableno][j], k);
- }
- }
+ struct block e, ikey, y;
+ int k;
+ register unsigned char *p, *q, *r;
+
+ e = *a;
+ transpose(&e, EP, 48);
+ for (k = rots[i]; k; k--) rotate(key);
+ ikey = *key;
+ transpose(&ikey, &KeyTr2, 48);
+ p = &(y.b_data[48]);
+ q = &(e.b_data[48]);
+ r = &(ikey.b_data[48]);
+ while (p > y.b_data) {
+ *--p = *--q ^ *--r;
+ }
+ q = x->b_data;
+ for (k = 0; k < 8; k++) {
+ register int xb, r;
+
+ r = *p++ << 5;
+ r += *p++ << 3;
+ r += *p++ << 2;
+ r += *p++ << 1;
+ r += *p++;
+ r += *p++ << 4;
+
+ xb = s_boxes[k][r];
+
+ *q++ = (char) (xb >> 3) & 1;
+ *q++ = (char) (xb>>2) & 1;
+ *q++ = (char) (xb>>1) & 1;
+ *q++ = (char) (xb & 1);
+ }
+ transpose(x, &ptr, 32);
}
-/*
- * Initialize "perm" to represent transformation "p", which rearranges
- * (perhaps with expansion and/or contraction) one packed array of bits
- * (of size "chars_in" characters) into another array (of size "chars_out"
- * characters).
- *
- * "perm" must be all-zeroes on entry to this routine.
- */
-STATIC
-init_perm(perm, p, chars_in, chars_out)
- C_block perm[64/CHUNKBITS][1<<CHUNKBITS];
- unsigned char p[64];
- int chars_in, chars_out;
+void definekey(char *k)
{
- register int i, j, k, l;
-
- for (k = 0; k < chars_out*8; k++) { /* each output bit position */
- l = p[k] - 1; /* where this bit comes from */
- if (l < 0)
- continue; /* output bit is always 0 */
- i = l>>LGCHUNKBITS; /* which chunk this bit comes from */
- l = 1<<(l&(CHUNKBITS-1)); /* mask for this bit */
- for (j = 0; j < (1<<CHUNKBITS); j++) { /* each chunk value */
- if ((j & l) != 0)
- perm[i][j].b[k>>3] |= 1<<(k&07);
- }
- }
-}
-/*
- * "setkey" routine (for backwards compatibility)
- */
-setkey(key)
- register const char *key;
-{
- register int i, j, k;
- C_block keyblock;
-
- for (i = 0; i < 8; i++) {
- k = 0;
- for (j = 0; j < 8; j++) {
- k <<= 1;
- k |= (unsigned char)*key++;
- }
- keyblock.b[i] = k;
- }
- return (des_setkey((char *)keyblock.b));
+ key = *((struct block *) k);
+ transpose(&key, &KeyTr1, 56);
}
-/*
- * "encrypt" routine (for backwards compatibility)
- */
-encrypt(block, flag)
- register char *block;
- int flag;
+void encrypt(char *blck, int edflag)
{
- register int i, j, k;
- C_block cblock;
-
- for (i = 0; i < 8; i++) {
- k = 0;
- for (j = 0; j < 8; j++) {
- k <<= 1;
- k |= (unsigned char)*block++;
- }
- cblock.b[i] = k;
- }
- if (des_cipher((char *)&cblock, (char *)&cblock, 0L, (flag ? -1: 1)))
- return (1);
- for (i = 7; i >= 0; i--) {
- k = cblock.b[i];
- for (j = 7; j >= 0; j--) {
- *--block = k&01;
- k >>= 1;
- }
- }
- return (0);
+ register struct block *p = (struct block *) blck;
+ register int i;
+
+ transpose(p, &InitialTr, 64);
+ for (i = 15; i>= 0; i--) {
+ int j = edflag ? i : 15 - i;
+ register int k;
+ struct block b, x;
+
+ b = *p;
+ for (k = 31; k >= 0; k--) {
+ p->b_data[k] = b.b_data[k + 32];
+ }
+ f(j, &key, p, &x);
+ for (k = 31; k >= 0; k--) {
+ p->b_data[k+32] = b.b_data[k] ^ x.b_data[k];
+ }
+ }
+ transpose(p, &swap, 64);
+ transpose(p, &FinalTr, 64);
}
-#ifdef DEBUG
-STATIC
-prtab(s, t, num_rows)
- char *s;
- unsigned char *t;
- int num_rows;
+char *crypt(char *pw, char *salt)
{
- register int i, j;
-
- (void)printf("%s:\n", s);
- for (i = 0; i < num_rows; i++) {
- for (j = 0; j < 8; j++) {
- (void)printf("%3d", t[i*8+j]);
- }
- (void)printf("\n");
- }
- (void)printf("\n");
+
+ char pwb[66];
+ static char result[16];
+ register char *p = pwb;
+ struct ordering new_etr;
+ register int i;
+
+ while (*pw && p < &pwb[64]) {
+ register int j = 7;
+
+ while (j--) {
+ *p++ = (*pw >> j) & 01;
+ }
+ pw++;
+ *p++ = 0;
+ }
+ while (p < &pwb[64]) *p++ = 0;
+
+ definekey(p = pwb);
+
+ while (p < &pwb[66]) *p++ = 0;
+
+ new_etr = etr;
+ EP = &new_etr;
+ for (i = 0; i < 2; i++) {
+ register char c = *salt++;
+ register int j;
+
+ result[i] = c;
+ if ( c > 'Z') c -= 6 + 7 + '.'; /* c was a lower case letter */
+ else if ( c > '9') c -= 7 + '.';/* c was upper case letter */
+ else c -= '.'; /* c was digit, '.' or '/'. */
+ /* now, 0 <= c <= 63 */
+ for (j = 0; j < 6; j++) {
+ if ((c >> j) & 01) {
+ int t = 6*i + j;
+ int temp = new_etr.o_data[t];
+ new_etr.o_data[t] = new_etr.o_data[t+24];
+ new_etr.o_data[t+24] = (char) temp;
+ }
+ }
+ }
+
+ if (result[1] == 0) result[1] = result[0];
+
+ for (i = 0; i < 25; i++) encrypt(pwb,0);
+ EP = &etr;
+
+ p = pwb;
+ pw = result+2;
+ while (p < &pwb[66]) {
+ register int c = 0;
+ register int j = 6;
+
+ while (j--) {
+ c <<= 1;
+ c |= *p++;
+ }
+ c += '.'; /* becomes >= '.' */
+ if (c > '9') c += 7; /* not in [./0-9], becomes upper */
+ if (c > 'Z') c += 6; /* not in [A-Z], becomes lower */
+ *pw++ = (char) c;
+ }
+ *pw = 0;
+ return result;
}
-#endif
diff --git a/missing/erf.c b/missing/erf.c
index d9e7469024..e30a90051e 100644
--- a/missing/erf.c
+++ b/missing/erf.c
@@ -1,5 +1,4 @@
-/* erf.c - public domain implementation of error function erf(3m)
-
+/* erf.c
reference - Haruhiko Okumura: C-gengo niyoru saishin algorithm jiten
(New Algorithm handbook in C language) (Gijyutsu hyouron
sha, Tokyo, 1991) p.227 [in Japanese] */
diff --git a/missing/isinf.c b/missing/isinf.c
index e44ef6c3c1..8829b72935 100644
--- a/missing/isinf.c
+++ b/missing/isinf.c
@@ -23,7 +23,6 @@ isinf(n)
#if defined(HAVE_FINITE) && defined(HAVE_ISNAN)
-#include <math.h>
#ifdef HAVE_IEEEFP_H
#include <ieeefp.h>
#endif
diff --git a/missing/mkdir.c b/missing/mkdir.c
new file mode 100644
index 0000000000..ed1476db9a
--- /dev/null
+++ b/missing/mkdir.c
@@ -0,0 +1,104 @@
+/*
+ * Written by Robert Rother, Mariah Corporation, August 1985.
+ *
+ * If you want it, it's yours. All I ask in return is that if you
+ * figure out how to do this in a Bourne Shell script you send me
+ * a copy.
+ * sdcsvax!rmr or rmr@uscd
+ *
+ * Severely hacked over by John Gilmore to make a 4.2BSD compatible
+ * subroutine. 11Mar86; hoptoad!gnu
+ *
+ * Modified by rmtodd@uokmax 6-28-87 -- when making an already existing dir,
+ * subroutine didn't return EEXIST. It does now.
+ */
+
+#include <sys/stat.h>
+#include <errno.h>
+/*
+ * Make a directory.
+ */
+int
+mkdir (dpath, dmode)
+ char *dpath;
+ int dmode;
+{
+ int cpid, status;
+ struct stat statbuf;
+
+ if (stat (dpath, &statbuf) == 0)
+ {
+ errno = EEXIST; /* Stat worked, so it already exists */
+ return -1;
+ }
+
+ /* If stat fails for a reason other than non-existence, return error */
+ if (errno != ENOENT)
+ return -1;
+
+ switch (cpid = fork ())
+ {
+
+ case -1: /* Error in fork() */
+ return (-1); /* Errno is set already */
+
+ case 0: /* Child process */
+ /*
+ * Cheap hack to set mode of new directory. Since this
+ * child process is going away anyway, we zap its umask.
+ * FIXME, this won't suffice to set SUID, SGID, etc. on this
+ * directory. Does anybody care?
+ */
+ status = umask (0); /* Get current umask */
+ status = umask (status | (0777 & ~dmode)); /* Set for mkdir */
+ execl ("/bin/mkdir", "mkdir", dpath, (char *) 0);
+ _exit (-1); /* Can't exec /bin/mkdir */
+
+ default: /* Parent process */
+ while (cpid != wait (&status)); /* Wait for kid to finish */
+ }
+
+ if (WIFSIGNALED (status) || WEXITSTATUS (status) != 0)
+ {
+ errno = EIO; /* We don't know why, but */
+ return -1; /* /bin/mkdir failed */
+ }
+
+ return 0;
+}
+
+int
+rmdir (dpath)
+ char *dpath;
+{
+ int cpid, status;
+ struct stat statbuf;
+
+ if (stat (dpath, &statbuf) != 0)
+ {
+ /* Stat just set errno. We don't have to */
+ return -1;
+ }
+
+ switch (cpid = fork ())
+ {
+
+ case -1: /* Error in fork() */
+ return (-1); /* Errno is set already */
+
+ case 0: /* Child process */
+ execl ("/bin/rmdir", "rmdir", dpath, (char *) 0);
+ _exit (-1); /* Can't exec /bin/mkdir */
+
+ default: /* Parent process */
+ while (cpid != wait (&status)); /* Wait for kid to finish */
+ }
+
+ if (WIFSIGNALED (status) || WEXITSTATUS (status) != 0)
+ {
+ errno = EIO; /* We don't know why, but */
+ return -1; /* /bin/rmdir failed */
+ }
+
+ return 0;
+}
diff --git a/missing/strchr.c b/missing/strchr.c
index 886d70ede6..82f3cc96b0 100644
--- a/missing/strchr.c
+++ b/missing/strchr.c
@@ -19,10 +19,8 @@ strrchr(s, c)
char *s;
int c;
{
- char *save;
+ char *save = 0;
- if (c == 0) return s + strlen(s);
- save = 0;
while (*s) {
if (*s == c)
save = s;
diff --git a/missing/vsnprintf.c b/missing/vsnprintf.c
index 6afdfa189f..266290a139 100644
--- a/missing/vsnprintf.c
+++ b/missing/vsnprintf.c
@@ -13,7 +13,11 @@
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
- * 3. Neither the name of the University nor the names of its contributors
+ * 3. All advertising materials mentioning features or use of this software
+ * must display the following acknowledgement:
+ * This product includes software developed by the University of
+ * California, Berkeley and its contributors.
+ * 4. Neither the name of the University nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
@@ -95,7 +99,7 @@
# endif
#endif
-#if defined(__hpux) && !defined(__GNUC__) && !defined(__STDC__)
+#if defined(__hpux) && !defined(__GNUC__)
#define const
#endif
@@ -781,19 +785,14 @@ fp_begin: _double = va_arg(ap, double);
* defined manner.''
* -- ANSI X3J11
*/
-#ifdef _HAVE_LLP64_
- uqval = (u_long)va_arg(ap, void *);
- flags = (flags) | QUADINT | HEXPREFIX;
-#else
ulval = (u_long)va_arg(ap, void *);
+ base = 16;
+ xdigs = "0123456789abcdef";
#ifdef _HAVE_SANE_QUAD_
flags = (flags & ~QUADINT) | HEXPREFIX;
#else /* _HAVE_SANE_QUAD_ */
flags = (flags) | HEXPREFIX;
#endif /* _HAVE_SANE_QUAD_ */
-#endif
- base = 16;
- xdigs = "0123456789abcdef";
ch = 'x';
goto nosign;
case 's':
diff --git a/mkconfig.rb b/mkconfig.rb
index b4897e6aaa..b0abee35ad 100644
--- a/mkconfig.rb
+++ b/mkconfig.rb
@@ -1,19 +1,16 @@
#!./miniruby -s
# avoid warnings with -d.
+$srcdir ||= nil
$install_name ||= nil
$so_name ||= nil
-srcdir = File.dirname(__FILE__)
-$:.replace [srcdir+"/lib", "."]
-
-require "fileutils"
+require File.dirname($0)+"/lib/ftools"
mkconfig = File.basename($0)
rbconfig_rb = ARGV[0] || 'rbconfig.rb'
-unless File.directory?(dir = File.dirname(rbconfig_rb))
- FileUtils.makedirs(dir, :verbose => true)
-end
+srcdir = $srcdir || '.'
+File.makedirs(File.dirname(rbconfig_rb), true)
version = RUBY_VERSION
rbconfig_rb_tmp = rbconfig_rb + '.tmp'
@@ -44,10 +41,7 @@ File.foreach "config.status" do |line|
elsif /^s[%,]@(\w+)@[%,](.*)[%,]/ =~ line
name = $1
val = $2 || ""
- next if /^(?:ac_.*|DEFS|configure_input)$/ =~ name
- next if /^\$\(ac_\w+\)$/ =~ val
- next if /^\$\{ac_\w+\}$/ =~ val
- next if /^\$ac_\w+$/ =~ val
+ next if /^(INSTALL|DEFS|configure_input|srcdir|top_srcdir)$/ =~ name
next if $install_name and /^RUBY_INSTALL_NAME$/ =~ name
next if $so_name and /^RUBY_SO_NAME$/ =~ name
v = " CONFIG[\"" + name + "\"] = " +
@@ -58,12 +52,17 @@ File.foreach "config.status" do |line|
v_others << v
end
has_version = true if name == "MAJOR"
- elsif /^(?:ac_given_)?INSTALL=(.*)/ =~ line
+ elsif /^(?:ac_given_)?srcdir=(.*)/ =~ line
+ srcdir = $1.strip
+ elsif /^ac_given_INSTALL=(.*)/ =~ line
v_fast << " CONFIG[\"INSTALL\"] = " + $1 + "\n"
end
# break if /^CEOF/
end
+srcdir = File.expand_path(srcdir)
+v_fast.unshift(" CONFIG[\"srcdir\"] = \"" + srcdir + "\"\n")
+
v_fast.collect! do |x|
if /"prefix"/ === x
x.sub(/= (.*)/, '= (TOPDIR || DESTDIR + \1)')
@@ -74,8 +73,8 @@ end
drive = File::PATH_SEPARATOR == ';'
-prefix = '/lib/ruby/' + RUBY_VERSION.sub(/\.\d+$/, '') + '/' + RUBY_PLATFORM
-print " TOPDIR = File.dirname(__FILE__).chomp!(#{prefix.dump})\n"
+prefix = Regexp.quote('/lib/ruby/' + RUBY_VERSION.sub(/\.\d+$/, '') + '/' + RUBY_PLATFORM)
+print " TOPDIR = File.dirname(__FILE__).sub!(%r'#{prefix}\\Z', '')\n"
print " DESTDIR = ", (drive ? "TOPDIR && TOPDIR[/\\A[a-z]:/i] || " : ""), "'' unless defined? DESTDIR\n"
print " CONFIG = {}\n"
print " CONFIG[\"DESTDIR\"] = DESTDIR\n"
@@ -112,7 +111,7 @@ print <<EOS
CONFIG["archdir"] = "$(rubylibdir)/$(arch)"
CONFIG["sitelibdir"] = "$(sitedir)/$(ruby_version)"
CONFIG["sitearchdir"] = "$(sitelibdir)/$(sitearch)"
- CONFIG["topdir"] = File.dirname(__FILE__)
+ CONFIG["compile_dir"] = "#{Dir.pwd}"
MAKEFILE_CONFIG = {}
CONFIG.each{|k,v| MAKEFILE_CONFIG[k] = v.dup}
def Config::expand(val, config = CONFIG)
@@ -121,7 +120,7 @@ print <<EOS
'$'
elsif key = config[v]
config[v] = false
- Config::expand(key, config)
+ Config::expand(key, config)
config[v] = key
else
var
@@ -138,17 +137,6 @@ EOS
$stdout.flush
$stdout.reopen($orgout)
config.close
-if $timestamp and
- File.exist?(rbconfig_rb) and
- FileUtils.compare_file(rbconfig_rb, rbconfig_rb_tmp)
- puts "#{rbconfig_rb} unchanged"
- File.unlink(rbconfig_rb_tmp)
-else
- puts "#{rbconfig_rb} updated"
- File.rename(rbconfig_rb_tmp, rbconfig_rb)
-end
-if String === $timestamp
- FileUtils.touch($timestamp)
-end
+File.rename(rbconfig_rb_tmp, rbconfig_rb)
# vi:set sw=2:
diff --git a/node.h b/node.h
index fe5b5f56f5..3f2416e4d9 100644
--- a/node.h
+++ b/node.h
@@ -115,7 +115,9 @@ enum node_type {
NODE_DEFINED,
NODE_NEWLINE,
NODE_POSTEXE,
+#ifdef C_ALLOCA
NODE_ALLOCA,
+#endif
NODE_DMETHOD,
NODE_BMETHOD,
NODE_MEMO,
@@ -357,23 +359,6 @@ VALUE rb_gvar_get _((struct global_entry *));
VALUE rb_gvar_set _((struct global_entry *, VALUE));
VALUE rb_gvar_defined _((struct global_entry *));
-typedef unsigned int rb_event_t;
-
-#define RUBY_EVENT_NONE 0x00
-#define RUBY_EVENT_LINE 0x01
-#define RUBY_EVENT_CLASS 0x02
-#define RUBY_EVENT_END 0x04
-#define RUBY_EVENT_CALL 0x08
-#define RUBY_EVENT_RETURN 0x10
-#define RUBY_EVENT_C_CALL 0x20
-#define RUBY_EVENT_C_RETURN 0x40
-#define RUBY_EVENT_RAISE 0x80
-#define RUBY_EVENT_ALL 0xff
-
-typedef void (*rb_event_hook_func_t) _((rb_event_t,NODE*,VALUE,ID,VALUE));
-void rb_add_event_hook _((rb_event_hook_func_t,rb_event_t));
-int rb_remove_event_hook _((rb_event_hook_func_t));
-
#if defined(__cplusplus)
} /* extern "C" { */
#endif
diff --git a/numeric.c b/numeric.c
index ca61ebdb41..bbb279b7d5 100644
--- a/numeric.c
+++ b/numeric.c
@@ -198,7 +198,6 @@ num_sadded(x, name)
return Qnil; /* not reached */
}
-/* :nodoc: */
static VALUE
num_init_copy(x, y)
VALUE x, y;
@@ -593,7 +592,7 @@ flo_minus(x, y)
* call-seq:
* float * other => float
*
- * Returns a new float which is the product of <code>float</code>
+ * Returns a new float with is the product of <code>float</code>
* and <code>other</code>.
*/
@@ -716,7 +715,6 @@ flo_divmod(x, y)
VALUE x, y;
{
double fy, div, mod;
- volatile VALUE a, b;
switch (TYPE(y)) {
case T_FIXNUM:
@@ -732,9 +730,7 @@ flo_divmod(x, y)
return rb_num_coerce_bin(x, y);
}
flodivmod(RFLOAT(x)->value, fy, &div, &mod);
- a = rb_float_new(div);
- b = rb_float_new(mod);
- return rb_assoc_new(a, b);
+ return rb_assoc_new(rb_float_new(div), rb_float_new(mod));
}
/*
@@ -833,13 +829,12 @@ flo_eq(x, y)
break;
case T_FLOAT:
b = RFLOAT(y)->value;
- if (isnan(b)) return Qfalse;
break;
default:
return num_equal(x, y);
}
a = RFLOAT(x)->value;
- if (isnan(a)) return Qfalse;
+ if (isnan(a) || isnan(b)) return Qfalse;
return (a == b)?Qtrue:Qfalse;
}
@@ -939,13 +934,12 @@ flo_gt(x, y)
case T_FLOAT:
b = RFLOAT(y)->value;
- if (isnan(b)) return Qfalse;
break;
default:
return rb_num_coerce_relop(x, y);
}
- if (isnan(a)) return Qfalse;
+ if (isnan(a) || isnan(b)) return Qfalse;
return (a > b)?Qtrue:Qfalse;
}
@@ -975,13 +969,12 @@ flo_ge(x, y)
case T_FLOAT:
b = RFLOAT(y)->value;
- if (isnan(b)) return Qfalse;
break;
default:
return rb_num_coerce_relop(x, y);
}
- if (isnan(a)) return Qfalse;
+ if (isnan(a) || isnan(b)) return Qfalse;
return (a >= b)?Qtrue:Qfalse;
}
@@ -1010,13 +1003,12 @@ flo_lt(x, y)
case T_FLOAT:
b = RFLOAT(y)->value;
- if (isnan(b)) return Qfalse;
break;
default:
return rb_num_coerce_relop(x, y);
}
- if (isnan(a)) return Qfalse;
+ if (isnan(a) || isnan(b)) return Qfalse;
return (a < b)?Qtrue:Qfalse;
}
@@ -1046,13 +1038,12 @@ flo_le(x, y)
case T_FLOAT:
b = RFLOAT(y)->value;
- if (isnan(b)) return Qfalse;
break;
default:
return rb_num_coerce_relop(x, y);
}
- if (isnan(a)) return Qfalse;
+ if (isnan(a) || isnan(b)) return Qfalse;
return (a <= b)?Qtrue:Qfalse;
}
@@ -1443,7 +1434,7 @@ num_step(argc, argv, from)
rb_raise(rb_eArgError, "wrong number of arguments");
}
if (rb_equal(step, INT2FIX(0))) {
- rb_raise(rb_eArgError, "step can't be 0");
+ rb_raise(rb_eArgError, "step cannot be 0");
}
}
@@ -2202,9 +2193,6 @@ fix_pow(x, y)
return rb_big_pow(rb_int2big(a), y);
}
return rb_float_new(pow((double)a, (double)b));
- } else if (TYPE(y) == T_FLOAT) {
- long a = FIX2LONG(x);
- return rb_float_new(pow((double)a, RFLOAT(y)->value));
}
return rb_num_coerce_bin(x, y);
}
@@ -2776,9 +2764,6 @@ Init_Numeric()
#elif defined(_UNICOSMP)
/* Turn off floating point exceptions for divide by zero, etc. */
_set_Creg(0, 0);
-#elif defined(__BORLANDC__)
- /* Turn off floating point exceptions for overflow, etc. */
- _control87(MCW_EM, MCW_EM);
#endif
id_coerce = rb_intern("coerce");
id_to_i = rb_intern("to_i");
diff --git a/object.c b/object.c
index 837e74cb90..5fd722b338 100644
--- a/object.c
+++ b/object.c
@@ -149,7 +149,7 @@ VALUE
rb_obj_id_obsolete(obj)
VALUE obj;
{
- rb_warn("Object#id will be deprecated; use Object#object_id");
+ rb_warning("Object#id will be deprecated; use Object#object_id");
return rb_obj_id(obj);
}
@@ -303,7 +303,6 @@ rb_obj_dup(obj)
return dup;
}
-/* :nodoc: */
VALUE
rb_obj_init_copy(obj, orig)
VALUE obj, orig;
@@ -355,12 +354,10 @@ rb_any_to_s(obj)
VALUE obj;
{
char *cname = rb_obj_classname(obj);
- size_t len;
VALUE str;
- len = strlen(cname)+6+16;
- str = rb_str_new(0, len); /* 6:tags 16:addr */
- snprintf(RSTRING(str)->ptr, len+1, "#<%s:0x%lx>", cname, obj);
+ str = rb_str_new(0, strlen(cname)+6+16+1); /* 6:tags 16:addr 1:nul */
+ sprintf(RSTRING(str)->ptr, "#<%s:0x%lx>", cname, obj);
RSTRING(str)->len = strlen(RSTRING(str)->ptr);
if (OBJ_TAINTED(obj)) OBJ_TAINT(str);
@@ -436,20 +433,17 @@ rb_obj_inspect(obj)
&& ROBJECT(obj)->iv_tbl
&& ROBJECT(obj)->iv_tbl->num_entries > 0) {
VALUE str;
- size_t len;
char *c;
c = rb_obj_classname(obj);
if (rb_inspecting_p(obj)) {
- len = strlen(c)+10+16+1;
- str = rb_str_new(0, len); /* 10:tags 16:addr 1:nul */
- snprintf(RSTRING(str)->ptr, len, "#<%s:0x%lx ...>", c, obj);
+ str = rb_str_new(0, strlen(c)+10+16+1); /* 10:tags 16:addr 1:nul */
+ sprintf(RSTRING(str)->ptr, "#<%s:0x%lx ...>", c, obj);
RSTRING(str)->len = strlen(RSTRING(str)->ptr);
return str;
}
- len = strlen(c)+6+16+1;
- str = rb_str_new(0, len); /* 6:tags 16:addr 1:nul */
- snprintf(RSTRING(str)->ptr, len, "-<%s:0x%lx", c, obj);
+ str = rb_str_new(0, strlen(c)+6+16+1); /* 6:tags 16:addr 1:nul */
+ sprintf(RSTRING(str)->ptr, "-<%s:0x%lx", c, obj);
RSTRING(str)->len = strlen(RSTRING(str)->ptr);
return rb_protect_inspect(inspect_obj, obj, str);
}
@@ -1174,7 +1168,7 @@ sym_inspect(sym)
str = rb_str_new(0, strlen(name)+1);
RSTRING(str)->ptr[0] = ':';
strcpy(RSTRING(str)->ptr+1, name);
- if (!rb_symname_p(name)) {
+ if (rb_is_junk_id(id)) {
str = rb_str_dump(str);
strncpy(RSTRING(str)->ptr, ":\"", 2);
}
@@ -1630,9 +1624,6 @@ rb_class_superclass(klass)
if (!super) {
rb_raise(rb_eTypeError, "uninitialized class");
}
- if (FL_TEST(klass, FL_SINGLETON)) {
- super = RBASIC(klass)->klass;
- }
while (TYPE(super) == T_ICLASS) {
super = RCLASS(super)->super;
}
@@ -1649,9 +1640,6 @@ str_to_id(str)
if (!RSTRING(str)->ptr || RSTRING(str)->len == 0) {
rb_raise(rb_eArgError, "empty symbol string");
}
- if (RSTRING(str)->len != strlen(RSTRING(str)->ptr)) {
- rb_warn("Symbols should not contain NUL (\\0)");
- }
return rb_intern(RSTRING(str)->ptr);
}
@@ -2018,8 +2006,7 @@ rb_obj_ivar_get(obj, iv)
*
* Sets the instance variable names by <i>symbol</i> to
* <i>object</i>, thereby frustrating the efforts of the class's
- * author to attempt to provide proper encapsulation. The variable
- * did not have to exist prior to this call.
+ * author to attempt to provide proper encapsulation.
*
* class Fred
* def initialize(p1, p2)
@@ -2028,8 +2015,7 @@ rb_obj_ivar_get(obj, iv)
* end
* fred = Fred.new('cat', 99)
* fred.instance_variable_set(:@a, 'dog') #=> "dog"
- * fred.instance_variable_set(:@c, 'cat') #=> "cat"
- * fred.inspect #=> "#<Fred:0x401b3da8 @a=\"dog\", @b=99, @c=\"cat\">"
+ * fred.inspect #=> "#<Fred:0x401b3da8 @a=\"dog\", @b=99>"
*/
static VALUE
@@ -2044,70 +2030,6 @@ rb_obj_ivar_set(obj, iv, val)
return rb_ivar_set(obj, id, val);
}
-/*
- * call-seq:
- * mod.class_variable_get(symbol) => obj
- *
- * Returns the value of the given class variable (or throws a
- * <code>NameError</code> exception). The <code>@@</code> part of the
- * variable name should be included for regular class variables
- *
- * class Fred
- * @@foo = 99
- * end
- *
- * def Fred.foo
- * class_variable_get(:@@foo) #=> 99
- * end
- */
-
-static VALUE
-rb_mod_cvar_get(obj, iv)
- VALUE obj, iv;
-{
- ID id = rb_to_id(iv);
-
- if (!rb_is_class_id(id)) {
- rb_name_error(id, "`%s' is not allowed as an class variable name", rb_id2name(id));
- }
- return rb_cvar_get(obj, id);
-}
-
-
-/*
- * call-seq:
- * obj.class_variable_set(symbol, obj) => obj
- *
- * Sets the class variable names by <i>symbol</i> to
- * <i>object</i>.
- *
- * class Fred
- * @@foo = 99
- * def foo
- * @@foo
- * end
- * end
- *
- * def Fred.foo
- * class_variable_set(:@@foo, 101) #=> 101
- * end
- * Fred.foo
- * Fred.new.foo #=> 101
- */
-
-static VALUE
-rb_mod_cvar_set(obj, iv, val)
- VALUE obj, iv, val;
-{
- ID id = rb_to_id(iv);
-
- if (!rb_is_class_id(id)) {
- rb_name_error(id, "`%s' is not allowed as an class variable name", rb_id2name(id));
- }
- rb_cvar_set(obj, id, val, Qfalse);
- return val;
-}
-
static VALUE
convert_type(val, tname, method, raise)
VALUE val;
@@ -2119,7 +2041,7 @@ convert_type(val, tname, method, raise)
m = rb_intern(method);
if (!rb_respond_to(val, m)) {
if (raise) {
- rb_raise(rb_eTypeError, "can't convert %s into %s",
+ rb_raise(rb_eTypeError, "cannot convert %s into %s",
NIL_P(val) ? "nil" :
val == Qtrue ? "true" :
val == Qfalse ? "false" :
@@ -2173,7 +2095,7 @@ rb_check_convert_type(val, type, tname, method)
static VALUE
rb_to_integer(val, method)
VALUE val;
- const char *method;
+ char *method;
{
VALUE v = convert_type(val, "Integer", method, Qtrue);
if (!rb_obj_is_kind_of(v, rb_cInteger)) {
@@ -2194,8 +2116,6 @@ VALUE
rb_Integer(val)
VALUE val;
{
- VALUE tmp;
-
switch (TYPE(val)) {
case T_FLOAT:
if (RFLOAT(val)->value <= (double)FIXNUM_MAX
@@ -2214,11 +2134,10 @@ rb_Integer(val)
default:
break;
}
- tmp = convert_type(val, "Integer", "to_int", Qfalse);
- if (NIL_P(tmp)) {
- return rb_to_integer(val, "to_i");
+ if (rb_respond_to(val, rb_intern("to_int"))) {
+ return rb_to_integer(val, "to_int");
}
- return tmp;
+ return rb_to_integer(val, "to_i");
}
/*
@@ -2358,7 +2277,7 @@ rb_Float(val)
return rb_float_new(rb_str_to_dbl(val, Qtrue));
case T_NIL:
- rb_raise(rb_eTypeError, "can't convert nil into Float");
+ rb_raise(rb_eTypeError, "cannot convert nil into Float");
break;
default:
@@ -2460,10 +2379,18 @@ rb_Array(val)
VALUE val;
{
VALUE tmp = rb_check_array_type(val);
+ ID to_a;
if (NIL_P(tmp)) {
- tmp = rb_check_convert_type(val, T_ARRAY, "Array", "to_a");
- if (NIL_P(tmp)) {
+ to_a = rb_intern("to_a");
+ if (rb_respond_to(val, to_a)) {
+ val = rb_funcall(val, to_a, 0);
+ if (TYPE(val) != T_ARRAY) {
+ rb_raise(rb_eTypeError, "`to_a' did not return Array");
+ }
+ return val;
+ }
+ else {
return rb_ary_new3(1, val);
}
}
@@ -2541,7 +2468,7 @@ VALUE ruby_top_self;
* Creating a new Name
*
* Classes, modules, and objects are interrelated. In the diagram
- * that follows, the vertical arrows represent inheritance, and the
+ * that follows, the arrows represent inheritance, and the
* parentheses meta-classes. All metaclasses are instances
* of the class `Class'.
*
@@ -2702,7 +2629,7 @@ Init_Object()
rb_define_method(rb_cModule, "<=", rb_class_inherited_p, 1);
rb_define_method(rb_cModule, ">", rb_mod_gt, 1);
rb_define_method(rb_cModule, ">=", rb_mod_ge, 1);
- rb_define_method(rb_cModule, "initialize_copy", rb_mod_init_copy, 1); /* in class.c */
+ rb_define_method(rb_cModule, "initialize_copy", rb_mod_init_copy, 1);
rb_define_method(rb_cModule, "to_s", rb_mod_to_s, 0);
rb_define_method(rb_cModule, "included_modules",
rb_mod_included_modules, 0); /* in class.c */
@@ -2738,13 +2665,11 @@ Init_Object()
rb_mod_class_variables, 0); /* in variable.c */
rb_define_private_method(rb_cModule, "remove_class_variable",
rb_mod_remove_cvar, 1); /* in variable.c */
- rb_define_private_method(rb_cModule, "class_variable_get", rb_mod_cvar_get, 1);
- rb_define_private_method(rb_cModule, "class_variable_set", rb_mod_cvar_set, 2);
rb_define_method(rb_cClass, "allocate", rb_obj_alloc, 0);
rb_define_method(rb_cClass, "new", rb_class_new_instance, -1);
rb_define_method(rb_cClass, "initialize", rb_class_initialize, -1);
- rb_define_method(rb_cClass, "initialize_copy", rb_class_init_copy, 1); /* in class.c */
+ rb_define_method(rb_cClass, "initialize_copy", rb_class_init_copy, 1);
rb_define_method(rb_cClass, "superclass", rb_class_superclass, 0);
rb_define_alloc_func(rb_cClass, rb_class_s_alloc);
rb_undef_method(rb_cClass, "extend_object");
diff --git a/pack.c b/pack.c
index 05e112e79d..498c3553fa 100644
--- a/pack.c
+++ b/pack.c
@@ -24,6 +24,8 @@
#ifdef NATINT_PACK
# define OFF16B(p) ((char*)(p) + (natint?0:(sizeof(short) - SIZE16)))
# define OFF32B(p) ((char*)(p) + (natint?0:(sizeof(long) - SIZE32)))
+# define NATINT_I32(x) (natint?NUM2LONG(x):(NUM2I32(x)))
+# define NATINT_U32(x) (natint?NUM2ULONG(x):(NUM2U32(x)))
# define NATINT_LEN(type,len) (natint?sizeof(type):(len))
# ifdef WORDS_BIGENDIAN
# define OFF16(p) OFF16B(p)
@@ -34,6 +36,8 @@
# define NATINT_HTONS(x) (natint?htons(x):hton16(x))
# define NATINT_HTONL(x) (natint?htonl(x):hton32(x))
#else
+# define NATINT_I32(x) NUM2I32(x)
+# define NATINT_U32(x) NUM2U32(x)
# define NATINT_LEN(type,len) sizeof(type)
# define NATINT_HTOVS(x) htovs(x)
# define NATINT_HTOVL(x) htovl(x)
@@ -175,7 +179,7 @@ define_swapx(d, double)
#endif /* #if SIZEOF_LONG == 8 */
#else /* SIZEOF_DOUBLE != 8 */
define_swapx(d, double)
-#endif /* #if SIZEOF_DOUBLE == 8 */
+#endif /* #if SIZEOF_DPOUBLE == 8 */
#undef define_swapx
@@ -248,16 +252,16 @@ endian()
#define hton32(x) (x)
# endif
#else /* LITTLE ENDIAN */
-#ifdef ntohs
+#ifndef ntohs
#undef ntohs
#undef ntohl
#undef htons
#undef htonl
-#endif
#define ntohs(x) swaps(x)
#define ntohl(x) swapl(x)
#define htons(x) swaps(x)
#define htonl(x) swapl(x)
+#endif
#define ntohf(x) swapf(x)
#define ntohd(x) swapd(x)
#define htonf(x) swapf(x)
@@ -331,32 +335,63 @@ endian()
#define VTOHD(x,y) vtohd(x)
#endif
-unsigned long rb_big2ulong_pack _((VALUE x));
+#if SIZEOF_LONG == SIZE32
+typedef long I32;
+typedef unsigned long U32;
+#define NUM2I32(x) NUM2LONG(x)
+#define NUM2U32(x) NUM2ULONG(x)
+#else
+typedef int I32;
+typedef unsigned int U32;
+# if SIZEOF_INT == SIZE32
+# define NUM2I32(x) NUM2INT(x)
+# define NUM2U32(x) NUM2UINT(x)
+# else
+
+#define I32_MAX 2147483647
+#define I32_MIN (-I32_MAX-1)
-static unsigned long
+static I32
num2i32(x)
VALUE x;
{
- x = rb_to_int(x); /* is nil OK? (should not) */
+ long num = NUM2LONG(x);
+
+ if (num < I32_MIN || I32_MAX < num) {
+ rb_raise(rb_eRangeError, "integer %ld too big to convert to `I32'", num);
+ }
+ return (I32)num;
+}
+
+#define U32_MAX 4294967295
+
+static U32
+num2u32(x)
+ VALUE x;
+{
+ unsigned long num = NUM2ULONG(x);
- if (FIXNUM_P(x)) return FIX2LONG(x);
- if (TYPE(x) == T_BIGNUM) {
- return rb_big2ulong_pack(x);
+ if (U32_MAX < num) {
+ rb_raise(rb_eRangeError, "integer %ld too big to convert to `U32'", num);
}
- rb_raise(rb_eTypeError, "can't convert %s to `integer'", rb_obj_classname(x));
- return 0; /* not reached */
+ return (U32)num;
}
+# define NUM2I32(x) num2i32(x)
+# define NUM2U32(x) num2u32(x)
+# endif
+#endif
+
#if SIZEOF_LONG == SIZE32 || SIZEOF_INT == SIZE32
# define EXTEND32(x)
#else
/* invariant in modulo 1<<31 */
-# define EXTEND32(x) do {if (!natint) {(x) = (I32)(((1<<31)-1-(x))^~(~0<<31));}} while(0)
+# define EXTEND32(x) do {if (!natint) {(x) = (I32)(((1<<31)-1-(x))^~(~0<<31))}} while(0)
#endif
#if SIZEOF_SHORT == SIZE16
# define EXTEND16(x)
#else
-# define EXTEND16(x) do { if (!natint) {(x) = (short)(((1<<15)-1-(x))^~(~0<<15));}} while(0)
+# define EXTEND16(x) do { if (!natint) {(x) = (short)(((1<<15)-1-(x))^~(~0<<15))}} while(0)
#endif
#ifdef HAVE_LONG_LONG
@@ -480,7 +515,7 @@ pack_pack(ary, fmt)
continue;
}
if (*p == '_' || *p == '!') {
- const char *natstr = "sSiIlL";
+ char *natstr = "sSiIlL";
if (strchr(natstr, type)) {
#ifdef NATINT_PACK
@@ -673,7 +708,10 @@ pack_pack(ary, fmt)
char c;
from = NEXTFROM;
- c = num2i32(from);
+ if (NIL_P(from)) c = 0;
+ else {
+ c = NUM2INT(from);
+ }
rb_str_buf_cat(res, &c, sizeof(char));
}
break;
@@ -684,7 +722,10 @@ pack_pack(ary, fmt)
short s;
from = NEXTFROM;
- s = num2i32(from);
+ if (NIL_P(from)) s = 0;
+ else {
+ s = NUM2INT(from);
+ }
rb_str_buf_cat(res, OFF16(&s), NATINT_LEN(short,2));
}
break;
@@ -695,7 +736,13 @@ pack_pack(ary, fmt)
long i;
from = NEXTFROM;
- i = num2i32(from);
+ if (NIL_P(from)) i = 0;
+ else if (type == 'i') {
+ i = NATINT_I32(from);
+ }
+ else {
+ i = NATINT_U32(from);
+ }
rb_str_buf_cat(res, OFF32(&i), NATINT_LEN(int,4));
}
break;
@@ -706,7 +753,13 @@ pack_pack(ary, fmt)
long l;
from = NEXTFROM;
- l = num2i32(from);
+ if (NIL_P(from)) l = 0;
+ else if (type == 'l') {
+ l = NATINT_I32(from);
+ }
+ else {
+ l = NATINT_U32(from);
+ }
rb_str_buf_cat(res, OFF32(&l), NATINT_LEN(long,4));
}
break;
@@ -717,6 +770,7 @@ pack_pack(ary, fmt)
char tmp[QUAD_SIZE];
from = NEXTFROM;
+ if (NIL_P(from)) from = INT2FIX(0);
rb_quad_pack(tmp, from);
rb_str_buf_cat(res, (char*)&tmp, QUAD_SIZE);
}
@@ -727,7 +781,10 @@ pack_pack(ary, fmt)
unsigned short s;
from = NEXTFROM;
- s = num2i32(from);
+ if (NIL_P(from)) s = 0;
+ else {
+ s = NUM2INT(from);
+ }
s = NATINT_HTONS(s);
rb_str_buf_cat(res, OFF16(&s), NATINT_LEN(short,2));
}
@@ -738,7 +795,10 @@ pack_pack(ary, fmt)
unsigned long l;
from = NEXTFROM;
- l = num2i32(from);
+ if (NIL_P(from)) l = 0;
+ else {
+ l = NATINT_U32(from);
+ }
l = NATINT_HTONL(l);
rb_str_buf_cat(res, OFF32(&l), NATINT_LEN(long,4));
}
@@ -749,7 +809,10 @@ pack_pack(ary, fmt)
unsigned short s;
from = NEXTFROM;
- s = num2i32(from);
+ if (NIL_P(from)) s = 0;
+ else {
+ s = NUM2INT(from);
+ }
s = NATINT_HTOVS(s);
rb_str_buf_cat(res, OFF16(&s), NATINT_LEN(short,2));
}
@@ -760,7 +823,10 @@ pack_pack(ary, fmt)
unsigned long l;
from = NEXTFROM;
- l = num2i32(from);
+ if (NIL_P(from)) l = 0;
+ else {
+ l = NATINT_U32(from);
+ }
l = NATINT_HTOVL(l);
rb_str_buf_cat(res, OFF32(&l), NATINT_LEN(long,4));
}
@@ -872,10 +938,9 @@ pack_pack(ary, fmt)
int le;
from = NEXTFROM;
- from = rb_to_int(from);
- l = NUM2INT(from);
- if (l < 0) {
- rb_raise(rb_eRangeError, "pack(U): value out of range");
+ if (NIL_P(from)) l = 0;
+ else {
+ l = NUM2UINT(from);
}
le = uv_to_utf8(buf, l);
rb_str_buf_cat(res, (char*)buf, le);
@@ -959,10 +1024,11 @@ pack_pack(ary, fmt)
}
}
- {
+ if (NIL_P(from)) ul = 0;
+ else {
long l = NUM2LONG(from);
if (l < 0) {
- rb_raise(rb_eArgError, "can't compress negative numbers");
+ rb_raise(rb_eArgError, "cannot compress negative numbers");
}
ul = l;
}
@@ -2033,10 +2099,10 @@ uv_to_utf8(buf, uv)
buf[5] = (uv&0x3f)|0x80;
return 6;
}
- rb_raise(rb_eRangeError, "pack(U): value out of range");
+ rb_raise(rb_eArgError, "pack(U): value out of range");
}
-static const unsigned long utf8_limits[] = {
+static const long utf8_limits[] = {
0x0, /* 1 */
0x80, /* 2 */
0x800, /* 3 */
diff --git a/parse.y b/parse.y
index 36683d6686..c4179fdc8b 100644
--- a/parse.y
+++ b/parse.y
@@ -13,10 +13,6 @@
%{
#define YYDEBUG 1
-#define YYERROR_VERBOSE 1
-#ifndef YYSTACK_USE_ALLOCA
-#define YYSTACK_USE_ALLOCA 0
-#endif
#include "ruby.h"
#include "env.h"
@@ -27,19 +23,6 @@
#include <errno.h>
#include <ctype.h>
-#define YYMALLOC rb_parser_malloc
-#define YYREALLOC rb_parser_realloc
-#define YYCALLOC rb_parser_calloc
-#define YYFREE rb_parser_free
-#define malloc YYMALLOC
-#define realloc YYREALLOC
-#define calloc YYCALLOC
-#define free YYFREE
-static void *rb_parser_malloc _((size_t));
-static void *rb_parser_realloc _((void *, size_t));
-static void *rb_parser_calloc _((size_t, size_t));
-static void rb_parser_free _((void *));
-
#define yyparse ruby_yyparse
#define yylex ruby_yylex
#define yyerror ruby_yyerror
@@ -1074,27 +1057,13 @@ arg : lhs '=' arg
{
value_expr($1);
value_expr($3);
- if (nd_type($1) == NODE_LIT && FIXNUM_P($1->nd_lit) &&
- nd_type($3) == NODE_LIT && FIXNUM_P($3->nd_lit)) {
- $1->nd_lit = rb_range_new($1->nd_lit, $3->nd_lit, Qfalse);
- $$ = $1;
- }
- else {
- $$ = NEW_DOT2($1, $3);
- }
+ $$ = NEW_DOT2($1, $3);
}
| arg tDOT3 arg
{
value_expr($1);
value_expr($3);
- if (nd_type($1) == NODE_LIT && FIXNUM_P($1->nd_lit) &&
- nd_type($3) == NODE_LIT && FIXNUM_P($3->nd_lit)) {
- $1->nd_lit = rb_range_new($1->nd_lit, $3->nd_lit, Qtrue);
- $$ = $1;
- }
- else {
- $$ = NEW_DOT3($1, $3);
- }
+ $$ = NEW_DOT3($1, $3);
}
| arg '+' arg
{
@@ -1585,7 +1554,7 @@ primary : literal
nd_set_type($$, NODE_UNTIL);
}
}
- | kUNTIL {COND_PUSH(1);} expr_value do {COND_POP();}
+ | kUNTIL {COND_PUSH(1);} expr_value do {COND_POP();}
compstmt
kEND
{
@@ -1682,7 +1651,6 @@ primary : literal
bodystmt
kEND
{
- if (!$5) $5 = NEW_NIL();
$$ = NEW_DEFN($2, $4, $5, NOEX_PRIVATE);
fixpos($$, $4);
local_pop();
@@ -2467,10 +2435,6 @@ terms : term
none : /* none */ {$$ = 0;}
;
%%
-#ifdef yystacksize
-#undef YYMALLOC
-#endif
-
#include "regex.h"
#include "util.h"
@@ -2549,9 +2513,6 @@ int ruby_in_compile = 0;
int ruby__end__seen;
static VALUE ruby_debug_lines;
-#ifdef YYMALLOC
-static NODE *parser_heap;
-#endif
static NODE*
yycompile(f, line)
@@ -2597,7 +2558,7 @@ yycompile(f, line)
ruby_in_compile = 0;
cond_stack = 0;
cmdarg_stack = 0;
- command_start = 1;
+ command_start = 1;
class_nest = 0;
in_single = 0;
in_def = 0;
@@ -3016,7 +2977,7 @@ static void
dispose_string(str)
VALUE str;
{
- xfree(RSTRING(str)->ptr);
+ free(RSTRING(str)->ptr);
rb_gc_force_recycle(str);
}
@@ -3344,7 +3305,6 @@ yylex()
register int c;
int space_seen = 0;
int cmd_state;
- enum lex_state last_state;
if (lex_strterm) {
int token;
@@ -3497,7 +3457,7 @@ yylex()
if (c == '<' &&
lex_state != EXPR_END &&
lex_state != EXPR_DOT &&
- lex_state != EXPR_ENDARG &&
+ lex_state != EXPR_ENDARG &&
lex_state != EXPR_CLASS &&
(!IS_ARG() || space_seen)) {
int token = heredoc_identifier();
@@ -4232,7 +4192,6 @@ yylex()
return '%';
case '$':
- last_state = lex_state;
lex_state = EXPR_END;
newtok();
c = nextc();
@@ -4275,13 +4234,7 @@ yylex()
tokadd('$');
tokadd(c);
c = nextc();
- if (is_identchar(c)) {
- tokadd(c);
- }
- else {
- pushback(c);
- }
- gvar:
+ tokadd(c);
tokfix();
yylval.id = rb_intern(tok());
/* xxx shouldn't check if valid option variable */
@@ -4291,11 +4244,6 @@ yylex()
case '`': /* $`: string before last match */
case '\'': /* $': string after last match */
case '+': /* $+: string matches last paren. */
- if (last_state == EXPR_FNAME) {
- tokadd('$');
- tokadd(c);
- goto gvar;
- }
yylval.node = NEW_BACK_REF(c);
return tBACK_REF;
@@ -4308,7 +4256,6 @@ yylex()
c = nextc();
} while (ISDIGIT(c));
pushback(c);
- if (last_state == EXPR_FNAME) goto gvar;
tokfix();
yylval.node = NEW_NTH_REF(atoi(tok()+1));
return tNTH_REF;
@@ -4387,7 +4334,6 @@ yylex()
{
int result = 0;
- last_state = lex_state;
switch (tok()[0]) {
case '$':
lex_state = EXPR_END;
@@ -4472,7 +4418,6 @@ yylex()
}
yylval.id = rb_intern(tok());
if (is_local_id(yylval.id) &&
- last_state != EXPR_DOT &&
((dyna_in_block() && rb_dvar_defined(yylval.id)) || local_id(yylval.id))) {
lex_state = EXPR_END;
}
@@ -5601,11 +5546,11 @@ local_pop()
struct local_vars *local = lvtbl->prev;
if (lvtbl->tbl) {
- if (!lvtbl->nofree) xfree(lvtbl->tbl);
+ if (!lvtbl->nofree) free(lvtbl->tbl);
else lvtbl->tbl[0] = lvtbl->cnt;
}
ruby_dyna_vars = lvtbl->dyna_vars;
- xfree(lvtbl);
+ free(lvtbl);
lvtbl = local;
}
@@ -5713,7 +5658,7 @@ top_local_setup()
rb_mem_clear(ruby_scope->local_vars+i, len-i);
}
if (ruby_scope->local_tbl && ruby_scope->local_vars[-1] == 0) {
- xfree(ruby_scope->local_tbl);
+ free(ruby_scope->local_tbl);
}
ruby_scope->local_vars[-1] = 0;
ruby_scope->local_tbl = local_tbl();
@@ -5764,7 +5709,7 @@ dyna_init(node, pre)
int
ruby_parser_stack_on_heap()
{
-#if defined(YYMALLOC)
+#if defined(YYBISON) && !defined(C_ALLOCA)
return Qfalse;
#else
return Qtrue;
@@ -5774,12 +5719,6 @@ ruby_parser_stack_on_heap()
void
rb_gc_mark_parser()
{
-#if defined YYMALLOC
- rb_gc_mark((VALUE)parser_heap);
-#elif defined yystacksize
- if (yyvsp) rb_gc_mark_locations((VALUE *)yyvs, (VALUE *)yyvsp);
-#endif
-
if (!ruby_in_compile) return;
rb_gc_mark_maybe((VALUE)yylval.node);
@@ -5881,99 +5820,6 @@ internal_id()
return ID_INTERNAL | (++last_id << ID_SCOPE_SHIFT);
}
-static int
-is_special_global_name(m)
- const char *m;
-{
- switch (*m) {
- case '~': case '*': case '$': case '?': case '!': case '@':
- case '/': case '\\': case ';': case ',': case '.': case '=':
- case ':': case '<': case '>': case '\"':
- case '&': case '`': case '\'': case '+':
- case '0':
- ++m;
- break;
- case '-':
- ++m;
- if (is_identchar(*m)) m += mbclen(*m);
- break;
- default:
- if (!ISDIGIT(*m)) return 0;
- do ++m; while (ISDIGIT(*m));
- }
- return !*m;
-}
-
-int
-rb_symname_p(name)
- const char *name;
-{
- const char *m = name;
- int localid = Qfalse;
-
- if (!m) return Qfalse;
- switch (*m) {
- case '\0':
- return Qfalse;
-
- case '$':
- if (is_special_global_name(++m)) return Qtrue;
- goto id;
-
- case '@':
- if (*++m == '@') ++m;
- goto id;
-
- case '<':
- switch (*++m) {
- case '<': ++m; break;
- case '=': if (*++m == '>') ++m; break;
- default: break;
- }
- break;
-
- case '>':
- if (*++m == '>') ++m;
- break;
-
- case '=':
- switch (*++m) {
- case '~': ++m; break;
- case '=': if (*++m == '=') ++m; break;
- default: return Qfalse;
- }
- break;
-
- case '*':
- if (*++m == '*') ++m;
- break;
-
- case '+': case '-':
- if (*++m == '@') ++m;
- break;
-
- case '|': case '^': case '&': case '/': case '%': case '~': case '`':
- break;
-
- case '[':
- if (*++m == ']' && *++m == '=') ++m;
- break;
-
- default:
- localid = !ISUPPER(*m);
- id:
- if (*m != '_' && !ISALPHA(*m) && !ismbchar(*m)) return Qfalse;
- while (is_identchar(*m)) m += mbclen(*m);
- if (localid) {
- switch (*m) {
- case '!': case '?': case '=': ++m;
- }
- }
- break;
- }
- return *m ? Qfalse : Qtrue;
-}
-
ID
rb_intern(name)
const char *name;
@@ -5990,7 +5836,8 @@ rb_intern(name)
switch (*name) {
case '$':
id |= ID_GLOBAL;
- if (is_special_global_name(++m)) goto new_id;
+ m++;
+ if (!is_identchar(*m)) m++;
break;
case '@':
if (name[1] == '@') {
@@ -6003,7 +5850,7 @@ rb_intern(name)
m++;
break;
default:
- if (name[0] != '_' && ISASCII(name[0]) && !ISALNUM(name[0])) {
+ if (name[0] != '_' && !ISALPHA(name[0]) && !ismbchar(name[0])) {
/* operators */
int i;
@@ -6037,13 +5884,10 @@ rb_intern(name)
}
break;
}
- if (!ISDIGIT(*m)) {
- while (m <= name + last && is_identchar(*m)) {
- m += mbclen(*m);
- }
+ while (m <= name + last && is_identchar(*m)) {
+ m += mbclen(*m);
}
if (*m) id = ID_JUNK;
- new_id:
id |= ++last_id << ID_SCOPE_SHIFT;
id_regist:
name = strdup(name);
@@ -6224,65 +6068,3 @@ rb_lastline_set(val)
special_local_set('_', val);
}
}
-
-#ifdef YYMALLOC
-#define HEAPCNT(n, size) ((n) * (size) / sizeof(YYSTYPE))
-#define NEWHEAP(cnt) rb_node_newnode(NODE_ALLOCA, 0, (VALUE)parser_heap, cnt)
-#define ADD2HEAP(n, ptr) ((parser_heap = (n))->u1.node = (ptr))
-
-static void *
-rb_parser_malloc(size)
- size_t size;
-{
- NODE *n = NEWHEAP(HEAPCNT(1, size));
-
- return ADD2HEAP(n, xmalloc(size));
-}
-
-static void *
-rb_parser_calloc(nelem, size)
- size_t nelem, size;
-{
- NODE *n = NEWHEAP(HEAPCNT(nelem, size));
-
- return ADD2HEAP(n, xcalloc(nelem, size));
-}
-
-static void *
-rb_parser_realloc(ptr, size)
- void *ptr;
- size_t size;
-{
- NODE *n;
- size_t cnt = HEAPCNT(1, size);
-
- if (ptr && (n = parser_heap) != NULL) {
- do {
- if (n->u1.node == ptr) {
- n->u1.node = ptr = xrealloc(ptr, size);
- if (n->u3.cnt) n->u3.cnt = cnt;
- return ptr;
- }
- } while ((n = n->u2.node) != NULL);
- }
- n = NEWHEAP(cnt);
- return ADD2HEAP(n, xrealloc(ptr, size));
-}
-
-static void
-rb_parser_free(ptr)
- void *ptr;
-{
- NODE **prev = &parser_heap, *n;
-
- while (n = *prev) {
- if (n->u1.node == ptr) {
- *prev = n->u2.node;
- rb_gc_force_recycle((VALUE)n);
- break;
- }
- prev = &n->u2.node;
- }
- xfree(ptr);
-}
-#endif
diff --git a/process.c b/process.c
index 8a01eee3f1..5fa1b9510b 100644
--- a/process.c
+++ b/process.c
@@ -91,8 +91,8 @@ static VALUE S_Tms;
#define HAVE_44BSD_SETGID 1
#endif
-#ifdef __NetBSD__
-#undef HAVE_SETRUID
+#ifdef __NetBSD__
+#undef HAVE_SETRUID
#undef HAVE_SETRGID
#endif
@@ -114,17 +114,16 @@ static VALUE S_Tms;
/*
* call-seq:
* Process.pid => fixnum
- *
+ *
* Returns the process id of this process. Not available on all
* platforms.
- *
+ *
* Process.pid #=> 27415
*/
static VALUE
get_pid()
{
- rb_secure(2);
return INT2FIX(getpid());
}
@@ -132,15 +131,15 @@ get_pid()
/*
* call-seq:
* Process.ppid => fixnum
- *
+ *
* Returns the process id of the parent of this process. Always
* returns 0 on NT. Not available on all platforms.
- *
+ *
* puts "I am #{Process.pid}"
* Process.fork { puts "Dad is #{Process.ppid}" }
- *
+ *
* <em>produces:</em>
- *
+ *
* I am 27417
* Dad is 27417
*/
@@ -148,7 +147,6 @@ get_pid()
static VALUE
get_ppid()
{
- rb_secure(2);
#ifdef _WIN32
return INT2FIX(0);
#else
@@ -165,7 +163,7 @@ get_ppid()
* status of a running or terminated system process. The built-in
* variable <code>$?</code> is either +nil+ or a
* <code>Process::Status</code> object.
- *
+ *
* fork { exit 99 } #=> 26557
* Process.wait #=> 26557
* $?.class #=> Process::Status
@@ -174,7 +172,7 @@ get_ppid()
* $?.stopped? #=> false
* $?.exited? #=> true
* $?.exitstatus #=> 99
- *
+ *
* Posix systems record information on processes using a 16-bit
* integer. The lower bits record the process status (stopped,
* exited, signaled) and the upper bits possibly contain additional
@@ -204,10 +202,10 @@ last_status_set(status, pid)
* call-seq:
* stat.to_i => fixnum
* stat.to_int => fixnum
- *
+ *
* Returns the bits in _stat_ as a <code>Fixnum</code>. Poking
* around in these bits is platform dependent.
- *
+ *
* fork { exit 0xab } #=> 26566
* Process.wait #=> 26566
* sprintf('%04x', $?.to_i) #=> "ab00"
@@ -224,7 +222,7 @@ pst_to_i(st)
/*
* call-seq:
* stat.to_s => string
- *
+ *
* Equivalent to _stat_<code>.to_i.to_s</code>.
*/
@@ -239,9 +237,9 @@ pst_to_s(st)
/*
* call-seq:
* stat.pid => fixnum
- *
+ *
* Returns the process ID that this status object represents.
- *
+ *
* fork { exit } #=> 26569
* Process.wait #=> 26569
* $?.pid #=> 26569
@@ -258,7 +256,7 @@ pst_pid(st)
/*
* call-seq:
* stat.inspect => string
- *
+ *
* Override the inspection method.
*/
@@ -315,7 +313,7 @@ pst_inspect(st)
/*
* call-seq:
* stat == other => true or false
- *
+ *
* Returns +true+ if the integer value of _stat_
* equals <em>other</em>.
*/
@@ -332,9 +330,9 @@ pst_equal(st1, st2)
/*
* call-seq:
* stat & num => fixnum
- *
+ *
* Logical AND of the bits in _stat_ with <em>num</em>.
- *
+ *
* fork { exit 0x37 }
* Process.wait
* sprintf('%04x', $?.to_i) #=> "3700"
@@ -354,9 +352,9 @@ pst_bitand(st1, st2)
/*
* call-seq:
* stat >> num => fixnum
- *
+ *
* Shift the bits in _stat_ right <em>num</em> places.
- *
+ *
* fork { exit 99 } #=> 26563
* Process.wait #=> 26563
* $?.to_i #=> 25344
@@ -376,7 +374,7 @@ pst_rshift(st1, st2)
/*
* call-seq:
* stat.stopped? => true or false
- *
+ *
* Returns +true+ if this process is stopped. This is only
* returned if the corresponding <code>wait</code> call had the
* <code>WUNTRACED</code> flag set.
@@ -398,7 +396,7 @@ pst_wifstopped(st)
/*
* call-seq:
* stat.stopsig => fixnum or nil
- *
+ *
* Returns the number of the signal that caused _stat_ to stop
* (or +nil+ if self is not stopped).
*/
@@ -418,7 +416,7 @@ pst_wstopsig(st)
/*
* call-seq:
* stat.signaled? => true or false
- *
+ *
* Returns +true+ if _stat_ terminated because of
* an uncaught signal.
*/
@@ -439,7 +437,7 @@ pst_wifsignaled(st)
/*
* call-seq:
* stat.termsig => fixnum or nil
- *
+ *
* Returns the number of the signal that caused _stat_ to
* terminate (or +nil+ if self was not terminated by an
* uncaught signal).
@@ -460,7 +458,7 @@ pst_wtermsig(st)
/*
* call-seq:
* stat.exited? => true or false
- *
+ *
* Returns +true+ if _stat_ exited normally (for
* example using an <code>exit()</code> call or finishing the
* program).
@@ -482,16 +480,16 @@ pst_wifexited(st)
/*
* call-seq:
* stat.exitstatus => fixnum or nil
- *
+ *
* Returns the least significant eight bits of the return code of
* _stat_. Only available if <code>exited?</code> is
* +true+.
- *
+ *
* fork { } #=> 26572
* Process.wait #=> 26572
* $?.exited? #=> true
* $?.exitstatus #=> 0
- *
+ *
* fork { exit 99 } #=> 26573
* Process.wait #=> 26573
* $?.exited? #=> true
@@ -513,7 +511,7 @@ pst_wexitstatus(st)
/*
* call-seq:
* stat.success? => true, false or nil
- *
+ *
* Returns +true+ if _stat_ is successful, +false+ if not.
* Returns +nil+ if <code>exited?</code> is not +true+.
*/
@@ -533,7 +531,7 @@ pst_success_p(st)
/*
* call-seq:
* stat.coredump? => true or false
- *
+ *
* Returns +true+ if _stat_ generated a coredump
* when it terminated. Not available on all platforms.
*/
@@ -679,20 +677,20 @@ waitall_each(pid, status, ary)
* Process.wait() => fixnum
* Process.wait(pid=-1, flags=0) => fixnum
* Process.waitpid(pid=-1, flags=0) => fixnum
- *
+ *
* Waits for a child process to exit, returns its process id, and
* sets <code>$?</code> to a <code>Process::Status</code> object
* containing information on that process. Which child it waits on
* depends on the value of _pid_:
- *
+ *
* > 0:: Waits for the child whose process ID equals _pid_.
- *
+ *
* 0:: Waits for any child whose process group ID equals that of the
* calling process.
*
* -1:: Waits for any child process (the default if no _pid_ is
* given).
- *
+ *
* < -1:: Waits for any child whose process group ID equals the absolute
* value of _pid_.
*
@@ -701,10 +699,10 @@ waitall_each(pid, status, ary)
* or <code>Process::WUNTRACED</code> (return stopped children that
* haven't been reported). Not all flags are available on all
* platforms, but a flag value of zero will work on all platforms.
- *
+ *
* Calling this method raises a <code>SystemError</code> if there are
* no child processes. Not available on all platforms.
- *
+ *
* include Process
* fork { exit 99 } #=> 27429
* wait #=> 27429
@@ -726,7 +724,6 @@ proc_wait(argc, argv)
VALUE vpid, vflags;
int pid, flags, status;
- rb_secure(2);
flags = 0;
rb_scan_args(argc, argv, "02", &vpid, &vflags);
if (argc == 0) {
@@ -751,13 +748,13 @@ proc_wait(argc, argv)
* call-seq:
* Process.wait2(pid=-1, flags=0) => [pid, status]
* Process.waitpid2(pid=-1, flags=0) => [pid, status]
- *
+ *
* Waits for a child process to exit (see Process::waitpid for exact
* semantics) and returns an array containing the process id and the
* exit status (a <code>Process::Status</code> object) of that
* child. Raises a <code>SystemError</code> if there are no child
* processes.
- *
+ *
* Process.fork { exit 99 } #=> 27437
* pid, status = Process.wait2
* pid #=> 27437
@@ -778,11 +775,11 @@ proc_wait2(argc, argv)
/*
* call-seq:
* Process.waitall => [ [pid1,status1], ...]
- *
+ *
* Waits for all children, returning an array of
* _pid_/_status_ pairs (where _status_ is a
* <code>Process::Status</code> object).
- *
+ *
* fork { sleep 0.2; exit 2 } #=> 27432
* fork { sleep 0.1; exit 1 } #=> 27433
* fork { exit 0 } #=> 27434
@@ -801,7 +798,6 @@ proc_waitall()
VALUE result;
int pid, status;
- rb_secure(2);
result = rb_ary_new();
#ifdef NO_WAITPID
if (pid_tbl) {
@@ -813,7 +809,7 @@ proc_waitall()
if (pid == -1) {
if (errno == ECHILD)
break;
- if (errno == EINTR) {
+ if (errno == EINTR) {
rb_thread_schedule();
continue;
}
@@ -838,14 +834,14 @@ proc_waitall()
}
static VALUE
-detach_process_watcher(pid_p)
+detach_process_watcer(pid_p)
int *pid_p;
{
int cpid, status;
for (;;) {
cpid = rb_waitpid(*pid_p, &status, WNOHANG);
- if (cpid != 0) return Qnil;
+ if (cpid == -1) return Qnil;
rb_thread_sleep(1);
}
}
@@ -854,14 +850,14 @@ VALUE
rb_detach_process(pid)
int pid;
{
- return rb_thread_create(detach_process_watcher, (void*)&pid);
+ return rb_thread_create(detach_process_watcer, (void*)&pid);
}
/*
* call-seq:
* Process.detach(pid) => thread
- *
+ *
* Some operating systems retain the status of terminated child
* processes until the parent collects that status (normally using
* some variant of <code>wait()</code>. If the parent never collects
@@ -872,37 +868,37 @@ rb_detach_process(pid)
* only when you do not intent to explicitly wait for the child to
* terminate. <code>detach</code> only checks the status
* periodically (currently once each second).
- *
+ *
* In this first example, we don't reap the first child process, so
* it appears as a zombie in the process status display.
- *
+ *
* p1 = fork { sleep 0.1 }
* p2 = fork { sleep 0.2 }
* Process.waitpid(p2)
* sleep 2
* system("ps -ho pid,state -p #{p1}")
- *
+ *
* <em>produces:</em>
- *
+ *
* 27389 Z
- *
+ *
* In the next example, <code>Process::detach</code> is used to reap
* the child automatically.
- *
+ *
* p1 = fork { sleep 0.1 }
* p2 = fork { sleep 0.2 }
* Process.detach(p1)
* Process.waitpid(p2)
* sleep 2
* system("ps -ho pid,state -p #{p1}")
- *
+ *
* <em>(produces no output)</em>
*/
static VALUE
-proc_detach(VALUE obj, VALUE pid)
+proc_detach(obj, pid)
+ VALUE pid;
{
- rb_secure(2);
return rb_detach_process(NUM2INT(pid));
}
@@ -1183,7 +1179,7 @@ proc_spawn(sv)
/*
* call-seq:
* exec(command [, arg, ...])
- *
+ *
* Replaces the current process by running the given external _command_.
* If +exec+ is given a single argument, that argument is
* taken as a line that is subject to shell expansion before being
@@ -1196,11 +1192,11 @@ proc_spawn(sv)
* subshell; otherwise, one of the <code>exec(2)</code> system calls is
* used, so the running command may inherit some of the environment of
* the original program (including open file descriptors).
- *
+ *
* exec "echo *" # echoes list of files in current directory
* # never get here
- *
- *
+ *
+ *
* exec "echo", "*" # echoes an asterisk
* # never get here
*/
@@ -1251,8 +1247,8 @@ rb_f_exec(argc, argv)
* the parent, returning the process ID of the child, and once in
* the child, returning _nil_. The child process can exit using
* <code>Kernel.exit!</code> to avoid running any
- * <code>at_exit</code> functions. The parent process should
- * use <code>Process.wait</code> to collect the termination statuses
+ * <code>at_exit</code> functions. The parent process should
+ * use <code>Process.wait</code> to collect the termination statuses
* of its children or use <code>Process.detach</code> to register
* disinterest in their status; otherwise, the operating system
* may accumulate zombie processes.
@@ -1302,11 +1298,11 @@ rb_f_fork(obj)
/*
* call-seq:
* Process.exit!(fixnum=-1)
- *
+ *
* Exits the process immediately. No exit handlers are
* run. <em>fixnum</em> is returned to the underlying system as the
* exit status.
- *
+ *
* Process.exit!(0)
*/
@@ -1350,13 +1346,7 @@ rb_syswait(pid)
int pid;
{
static int overriding;
-#ifdef SIGHUP
- RETSIGTYPE (*hfunc)_((int));
-#endif
-#ifdef SIGQUIT
- RETSIGTYPE (*qfunc)_((int));
-#endif
- RETSIGTYPE (*ifunc)_((int));
+ RETSIGTYPE (*hfunc)_((int)), (*qfunc)_((int)), (*ifunc)_((int));
int status;
int i, hooked = Qfalse;
@@ -1391,18 +1381,18 @@ rb_syswait(pid)
/*
* call-seq:
* system(cmd [, arg, ...]) => true or false
- *
+ *
* Executes _cmd_ in a subshell, returning +true+ if
* the command was found and ran successfully, +false+
* otherwise. An error status is available in <code>$?</code>. The
* arguments are processed in the same way as for
* <code>Kernel::exec</code>.
- *
+ *
* system("echo *")
* system("echo", "*")
- *
+ *
* <em>produces:</em>
- *
+ *
* config.h main.rb
* *
*/
@@ -1544,15 +1534,15 @@ rb_f_system(argc, argv)
/*
* call-seq:
- * sleep([duration]) => fixnum
- *
+ * sleep(duration=0) => fixnum
+ *
* Suspends the current thread for _duration_ seconds (which may be
* any number, including a +Float+ with fractional seconds). Returns the actual
* number of seconds slept (rounded), which may be less than that asked
* for if the thread was interrupted by a +SIGALRM+, or if
- * another thread calls <code>Thread#run</code>. Zero arguments
+ * another thread calls <code>Thread#run</code>. An argument of zero
* causes +sleep+ to sleep forever.
- *
+ *
* Time.new #=> Wed Apr 09 08:56:32 CDT 2003
* sleep 1.2 #=> 1
* Time.new #=> Wed Apr 09 08:56:33 CDT 2003
@@ -1587,10 +1577,10 @@ rb_f_sleep(argc, argv)
/*
* call-seq:
* Process.getpgrp => integer
- *
+ *
* Returns the process group ID for this process. Not available on
* all platforms.
- *
+ *
* Process.getpgid(0) #=> 25527
* Process.getpgrp #=> 25527
*/
@@ -1600,7 +1590,6 @@ proc_getpgrp()
{
int pgrp;
- rb_secure(2);
#if defined(HAVE_GETPGRP) && defined(GETPGRP_VOID)
pgrp = getpgrp();
if (pgrp < 0) rb_sys_fail(0);
@@ -1620,7 +1609,7 @@ proc_getpgrp()
/*
* call-seq:
* Process.setpgrp => 0
- *
+ *
* Equivalent to <code>setpgid(0,0)</code>. Not available on all
* platforms.
*/
@@ -1628,13 +1617,12 @@ proc_getpgrp()
static VALUE
proc_setpgrp()
{
- rb_secure(2);
/* check for posix setpgid() first; this matches the posix */
/* getpgrp() above. It appears that configure will set SETPGRP_VOID */
/* even though setpgrp(0,0) would be prefered. The posix call avoids */
/* this confusion. */
#ifdef HAVE_SETPGID
- if (setpgid(0,0) < 0) rb_sys_fail(0);
+ if (setpgid(0,0) < 0) rb_sys_fail(0);
#elif defined(HAVE_SETPGRP) && defined(SETPGRP_VOID)
if (setpgrp() < 0) rb_sys_fail(0);
#else
@@ -1647,10 +1635,10 @@ proc_setpgrp()
/*
* call-seq:
* Process.getpgid(pid) => integer
- *
+ *
* Returns the process group ID for the given process id. Not
* available on all platforms.
- *
+ *
* Process.getpgid(Process.ppid()) #=> 25527
*/
@@ -1659,10 +1647,8 @@ proc_getpgid(obj, pid)
VALUE obj, pid;
{
#if defined(HAVE_GETPGID) && !defined(__CHECKER__)
- int i;
+ int i = getpgid(NUM2INT(pid));
- rb_secure(2);
- i = getpgid(NUM2INT(pid));
if (i < 0) rb_sys_fail(0);
return INT2NUM(i);
#else
@@ -1674,7 +1660,7 @@ proc_getpgid(obj, pid)
/*
* call-seq:
* Process.setpgid(pid, integer) => 0
- *
+ *
* Sets the process group ID of _pid_ (0 indicates this
* process) to <em>integer</em>. Not available on all platforms.
*/
@@ -1701,11 +1687,11 @@ proc_setpgid(obj, pid, pgrp)
/*
* call-seq:
* Process.setsid => fixnum
- *
+ *
* Establishes this process as a new session and process group
* leader, with no controlling tty. Returns the session id. Not
* available on all platforms.
- *
+ *
* Process.setsid #=> 27422
*/
@@ -1720,7 +1706,7 @@ proc_setsid()
if (pid < 0) rb_sys_fail(0);
return INT2FIX(pid);
#elif defined(HAVE_SETPGRP) && defined(TIOCNOTTY)
- rb_pid_t pid;
+ pid_t pid;
int ret;
rb_secure(2);
@@ -1749,7 +1735,7 @@ proc_setsid()
/*
* call-seq:
* Process.getpriority(kind, integer) => fixnum
- *
+ *
* Gets the scheduling priority for specified process, process group,
* or user. <em>kind</em> indicates the kind of entity to find: one
* of <code>Process::PRIO_PGRP</code>,
@@ -1758,7 +1744,7 @@ proc_setsid()
* indicating the particular process, process group, or user (an id
* of 0 means _current_). Lower priorities are more favorable
* for scheduling. Not available on all platforms.
- *
+ *
* Process.getpriority(Process::PRIO_USER, 0) #=> 19
* Process.getpriority(Process::PRIO_PROCESS, 0) #=> 19
*/
@@ -1770,7 +1756,6 @@ proc_getpriority(obj, which, who)
#ifdef HAVE_GETPRIORITY
int prio, iwhich, iwho;
- rb_secure(2);
iwhich = NUM2INT(which);
iwho = NUM2INT(who);
@@ -1787,9 +1772,9 @@ proc_getpriority(obj, which, who)
/*
* call-seq:
* Process.setpriority(kind, integer, priority) => 0
- *
+ *
* See <code>Process#getpriority</code>.
- *
+ *
* Process.setpriority(Process::PRIO_USER, 0, 19) #=> 0
* Process.setpriority(Process::PRIO_PROCESS, 0, 19) #=> 0
* Process.getpriority(Process::PRIO_USER, 0) #=> 19
@@ -1822,7 +1807,7 @@ check_uid_switch()
{
rb_secure(2);
if (under_uid_switch) {
- rb_raise(rb_eRuntimeError, "can't handle UID while evaluating block given to Process::UID.switch method");
+ rb_raise(rb_eRuntimeError, "can't handle UID during evaluating the block given to the Process::UID.switch method");
}
}
@@ -1832,7 +1817,7 @@ check_gid_switch()
{
rb_secure(2);
if (under_gid_switch) {
- rb_raise(rb_eRuntimeError, "can't handle GID while evaluating block given to Process::UID.switch method");
+ rb_raise(rb_eRuntimeError, "can't handle GID during evaluating the block given to the Process::UID.switch method");
}
}
@@ -1851,10 +1836,10 @@ check_gid_switch()
/*
* call-seq:
* Process::Sys.setuid(integer) => nil
- *
+ *
* Set the user ID of the current process to _integer_. Not
* available on all platforms.
- *
+ *
*/
static VALUE
@@ -1875,10 +1860,10 @@ p_sys_setuid(obj, id)
/*
* call-seq:
* Process::Sys.setruid(integer) => nil
- *
+ *
* Set the real user ID of the calling process to _integer_.
* Not available on all platforms.
- *
+ *
*/
static VALUE
@@ -1898,10 +1883,10 @@ p_sys_setruid(obj, id)
/*
* call-seq:
* Process::Sys.seteuid(integer) => nil
- *
+ *
* Set the effective user ID of the calling process to
* _integer_. Not available on all platforms.
- *
+ *
*/
static VALUE
@@ -1921,7 +1906,7 @@ p_sys_seteuid(obj, id)
/*
* call-seq:
* Process::Sys.setreuid(rid, eid) => nil
- *
+ *
* Sets the (integer) real and/or effective user IDs of the current
* process to _rid_ and _eid_, respectively. A value of
* <code>-1</code> for either means to leave that ID unchanged. Not
@@ -1946,9 +1931,9 @@ p_sys_setreuid(obj, rid, eid)
/*
* call-seq:
* Process::Sys.setresuid(rid, eid, sid) => nil
- *
+ *
* Sets the (integer) real, effective, and saved user IDs of the
- * current process to _rid_, _eid_, and _sid_ respectively. A
+ * current process to _rid_, _eid_, and _sid_ respectively. A
* value of <code>-1</code> for any value means to
* leave that ID unchanged. Not available on all platforms.
*
@@ -1973,9 +1958,9 @@ p_sys_setresuid(obj, rid, eid, sid)
* Process.uid => fixnum
* Process::UID.rid => fixnum
* Process::Sys.getuid => fixnum
- *
+ *
* Returns the (real) user ID of this process.
- *
+ *
* Process.uid #=> 501
*/
@@ -1991,7 +1976,7 @@ proc_getuid(obj)
/*
* call-seq:
* Process.uid= integer => numeric
- *
+ *
* Sets the (integer) user ID for this process. Not available on all
* platforms.
*/
@@ -2026,7 +2011,7 @@ proc_setuid(obj, id)
/********************************************************************
- *
+ *
* Document-class: Process::UID
*
* The <code>Process::UID</code> module contains a collection of
@@ -2041,11 +2026,11 @@ static int SAVED_USER_ID;
/*
* call-seq:
* Process::UID.change_privilege(integer) => fixnum
- *
+ *
* Change the current process's real and effective user ID to that
* specified by _integer_. Returns the new user ID. Not
* available on all platforms.
- *
+ *
* [Process.uid, Process.euid] #=> [0, 0]
* Process::UID.change_privilege(31) #=> 31
* [Process.uid, Process.euid] #=> [31, 31]
@@ -2055,6 +2040,7 @@ static VALUE
p_uid_change_privilege(obj, id)
VALUE obj, id;
{
+ extern int errno;
int uid;
check_uid_switch();
@@ -2117,13 +2103,13 @@ p_uid_change_privilege(obj, id)
#endif
} else { /* unprivileged user */
#if defined(HAVE_SETRESUID)
- if (setresuid((getuid() == uid)? -1: uid,
- (geteuid() == uid)? -1: uid,
+ if (setresuid((getuid() == uid)? -1: uid,
+ (geteuid() == uid)? -1: uid,
(SAVED_USER_ID == uid)? -1: uid) < 0) rb_sys_fail(0);
SAVED_USER_ID = uid;
#elif defined(HAVE_SETREUID) && !defined(OBSOLETE_SETREUID)
if (SAVED_USER_ID == uid) {
- if (setreuid((getuid() == uid)? -1: uid,
+ if (setreuid((getuid() == uid)? -1: uid,
(geteuid() == uid)? -1: uid) < 0) rb_sys_fail(0);
} else if (getuid() != uid) {
if (setreuid(uid, (geteuid() == uid)? -1: uid) < 0) rb_sys_fail(0);
@@ -2195,10 +2181,10 @@ p_uid_change_privilege(obj, id)
/*
* call-seq:
* Process::Sys.setgid(integer) => nil
- *
+ *
* Set the group ID of the current process to _integer_. Not
* available on all platforms.
- *
+ *
*/
static VALUE
@@ -2218,10 +2204,10 @@ p_sys_setgid(obj, id)
/*
* call-seq:
* Process::Sys.setrgid(integer) => nil
- *
+ *
* Set the real group ID of the calling process to _integer_.
* Not available on all platforms.
- *
+ *
*/
static VALUE
@@ -2242,10 +2228,10 @@ p_sys_setrgid(obj, id)
/*
* call-seq:
* Process::Sys.setegid(integer) => nil
- *
+ *
* Set the effective group ID of the calling process to
* _integer_. Not available on all platforms.
- *
+ *
*/
static VALUE
@@ -2265,7 +2251,7 @@ p_sys_setegid(obj, id)
/*
* call-seq:
* Process::Sys.setregid(rid, eid) => nil
- *
+ *
* Sets the (integer) real and/or effective group IDs of the current
* process to <em>rid</em> and <em>eid</em>, respectively. A value of
* <code>-1</code> for either means to leave that ID unchanged. Not
@@ -2289,7 +2275,7 @@ p_sys_setregid(obj, rid, eid)
/*
* call-seq:
* Process::Sys.setresgid(rid, eid, sid) => nil
- *
+ *
* Sets the (integer) real, effective, and saved user IDs of the
* current process to <em>rid</em>, <em>eid</em>, and <em>sid</em>
* respectively. A value of <code>-1</code> for any value means to
@@ -2314,7 +2300,7 @@ p_sys_setresgid(obj, rid, eid, sid)
/*
* call-seq:
* Process::Sys.issetugid => true or false
- *
+ *
* Returns +true+ if the process was created as a result
* of an execve(2) system call which had either of the setuid or
* setgid bits set (and extra privileges were given as a result) or
@@ -2328,7 +2314,6 @@ p_sys_issetugid(obj)
VALUE obj;
{
#if defined HAVE_ISSETUGID
- rb_secure(2);
if (issetugid()) {
return Qtrue;
} else {
@@ -2346,9 +2331,9 @@ p_sys_issetugid(obj)
* Process.gid => fixnum
* Process::GID.rid => fixnum
* Process::Sys.getgid => fixnum
- *
+ *
* Returns the (real) group ID for this process.
- *
+ *
* Process.gid #=> 500
*/
@@ -2364,7 +2349,7 @@ proc_getgid(obj)
/*
* call-seq:
* Process.gid= fixnum => fixnum
- *
+ *
* Sets the group ID for this process.
*/
@@ -2403,7 +2388,7 @@ static size_t maxgroups = 32;
/*
* call-seq:
* Process.groups => array
- *
+ *
* Get an <code>Array</code> of the gids of groups in the
* supplemental group access list for this process.
*
@@ -2417,18 +2402,18 @@ proc_getgroups(VALUE obj)
#ifdef HAVE_GETGROUPS
VALUE ary;
size_t ngroups;
- rb_gid_t *groups;
+ gid_t *groups;
int i;
- groups = ALLOCA_N(rb_gid_t, maxgroups);
+ groups = ALLOCA_N(gid_t, maxgroups);
ngroups = getgroups(maxgroups, groups);
if (ngroups == -1)
- rb_sys_fail(0);
+ rb_sys_fail(0);
ary = rb_ary_new();
for (i = 0; i < ngroups; i++)
- rb_ary_push(ary, INT2NUM(groups[i]));
+ rb_ary_push(ary, INT2NUM(groups[i]));
return ary;
#else
@@ -2441,7 +2426,7 @@ proc_getgroups(VALUE obj)
/*
* call-seq:
* Process.groups= array => array
- *
+ *
* Set the supplemental group access list to the given
* <code>Array</code> of group IDs.
*
@@ -2456,7 +2441,7 @@ proc_setgroups(VALUE obj, VALUE ary)
{
#ifdef HAVE_SETGROUPS
size_t ngroups;
- rb_gid_t *groups;
+ gid_t *groups;
int i;
struct group *gr;
@@ -2464,15 +2449,15 @@ proc_setgroups(VALUE obj, VALUE ary)
ngroups = RARRAY(ary)->len;
if (ngroups > maxgroups)
- rb_raise(rb_eArgError, "too many groups, %d max", maxgroups);
+ rb_raise(rb_eArgError, "too many groups, %d max", maxgroups);
- groups = ALLOCA_N(rb_gid_t, ngroups);
+ groups = ALLOCA_N(gid_t, ngroups);
- for (i = 0; i < ngroups && i < RARRAY(ary)->len; i++) {
- VALUE g = RARRAY(ary)->ptr[i];
+ for (i = 0; i < ngroups; i++) {
+ VALUE g = RARRAY(ary)->ptr[i];
if (FIXNUM_P(g)) {
- groups[i] = FIX2INT(g);
+ groups[i] = FIX2INT(g);
}
else {
VALUE tmp = rb_check_string_type(g);
@@ -2481,10 +2466,10 @@ proc_setgroups(VALUE obj, VALUE ary)
groups[i] = NUM2INT(g);
}
else {
- gr = getgrnam(RSTRING(tmp)->ptr);
+ gr = getgrnam(RSTRING(g)->ptr);
if (gr == NULL)
- rb_raise(rb_eArgError,
- "can't find group for %s", RSTRING(tmp)->ptr);
+ rb_raise(rb_eArgError,
+ "can't find group for %s", RSTRING(g)->ptr);
groups[i] = gr->gr_gid;
}
}
@@ -2492,7 +2477,7 @@ proc_setgroups(VALUE obj, VALUE ary)
i = setgroups(ngroups, groups);
if (i == -1)
- rb_sys_fail(0);
+ rb_sys_fail(0);
return proc_getgroups(obj);
#else
@@ -2505,7 +2490,7 @@ proc_setgroups(VALUE obj, VALUE ary)
/*
* call-seq:
* Process.initgroups(username, gid) => array
- *
+ *
* Initializes the supplemental group access list by reading the
* system group database and using all groups of which the given user
* is a member. The group with the specified <em>gid</em> is also
@@ -2524,7 +2509,7 @@ proc_initgroups(obj, uname, base_grp)
VALUE obj, uname, base_grp;
{
#ifdef HAVE_INITGROUPS
- if (initgroups(StringValuePtr(uname), (rb_gid_t)NUM2INT(base_grp)) != 0) {
+ if (initgroups(StringValuePtr(uname), (gid_t)NUM2INT(base_grp)) != 0) {
rb_sys_fail(0);
}
return proc_getgroups(obj);
@@ -2538,10 +2523,10 @@ proc_initgroups(obj, uname, base_grp)
/*
* call-seq:
* Process.maxgroups => fixnum
- *
+ *
* Returns the maximum number of gids allowed in the supplemental
* group access list.
- *
+ *
* Process.maxgroups #=> 32
*/
@@ -2556,13 +2541,14 @@ proc_getmaxgroups(obj)
/*
* call-seq:
* Process.maxgroups= fixnum => fixnum
- *
+ *
* Sets the maximum number of gids allowed in the supplemental group
* access list.
*/
static VALUE
-proc_setmaxgroups(VALUE obj, VALUE val)
+proc_setmaxgroups(obj, val)
+ VALUE obj;
{
size_t ngroups = FIX2INT(val);
@@ -2576,7 +2562,7 @@ proc_setmaxgroups(VALUE obj, VALUE val)
/********************************************************************
- *
+ *
* Document-class: Process::GID
*
* The <code>Process::GID</code> module contains a collection of
@@ -2591,7 +2577,7 @@ static int SAVED_GROUP_ID;
/*
* call-seq:
* Process::GID.change_privilege(integer) => fixnum
- *
+ *
* Change the current process's real and effective group ID to that
* specified by _integer_. Returns the new group ID. Not
* available on all platforms.
@@ -2605,6 +2591,7 @@ static VALUE
p_gid_change_privilege(obj, id)
VALUE obj, id;
{
+ extern int errno;
int gid;
check_gid_switch();
@@ -2668,13 +2655,13 @@ p_gid_change_privilege(obj, id)
#endif
} else { /* unprivileged user */
#if defined(HAVE_SETRESGID)
- if (setresgid((getgid() == gid)? -1: gid,
- (getegid() == gid)? -1: gid,
+ if (setresgid((getgid() == gid)? -1: gid,
+ (getegid() == gid)? -1: gid,
(SAVED_GROUP_ID == gid)? -1: gid) < 0) rb_sys_fail(0);
SAVED_GROUP_ID = gid;
#elif defined(HAVE_SETREGID) && !defined(OBSOLETE_SETREGID)
if (SAVED_GROUP_ID == gid) {
- if (setregid((getgid() == gid)? -1: gid,
+ if (setregid((getgid() == gid)? -1: gid,
(getegid() == gid)? -1: gid) < 0) rb_sys_fail(0);
} else if (getgid() != gid) {
if (setregid(gid, (getegid() == gid)? -1: gid) < 0) rb_sys_fail(0);
@@ -2747,9 +2734,9 @@ p_gid_change_privilege(obj, id)
* Process.euid => fixnum
* Process::UID.eid => fixnum
* Process::Sys.geteuid => fixnum
- *
+ *
* Returns the effective user ID for this process.
- *
+ *
* Process.euid #=> 501
*/
@@ -2765,7 +2752,7 @@ proc_geteuid(obj)
/*
* call-seq:
* Process.euid= integer
- *
+ *
* Sets the effective user ID for this process. Not available on all
* platforms.
*/
@@ -2835,11 +2822,11 @@ rb_seteuid_core(euid)
* call-seq:
* Process::UID.grant_privilege(integer) => fixnum
* Process::UID.eid= integer => fixnum
- *
+ *
* Set the effective user ID, and if possible, the saved user ID of
* the process to the given _integer_. Returns the new
* effective user ID. Not available on all platforms.
- *
+ *
* [Process.uid, Process.euid] #=> [0, 0]
* Process::UID.grant_privilege(31) #=> 31
* [Process.uid, Process.euid] #=> [0, 31]
@@ -2858,10 +2845,10 @@ p_uid_grant_privilege(obj, id)
* Process.egid => fixnum
* Process::GID.eid => fixnum
* Process::Sys.geteid => fixnum
- *
+ *
* Returns the effective group ID for this process. Not available on
* all platforms.
- *
+ *
* Process.egid #=> 500
*/
@@ -2878,7 +2865,7 @@ proc_getegid(obj)
/*
* call-seq:
* Process.egid = fixnum => fixnum
- *
+ *
* Sets the effective group ID for this process. Not available on all
* platforms.
*/
@@ -2949,11 +2936,11 @@ rb_setegid_core(egid)
* call-seq:
* Process::GID.grant_privilege(integer) => fixnum
* Process::GID.eid = integer => fixnum
- *
+ *
* Set the effective group ID, and if possible, the saved group ID of
* the process to the given _integer_. Returns the new
* effective group ID. Not available on all platforms.
- *
+ *
* [Process.gid, Process.egid] #=> [0, 0]
* Process::GID.grant_privilege(31) #=> 33
* [Process.gid, Process.egid] #=> [0, 33]
@@ -2970,10 +2957,10 @@ p_gid_grant_privilege(obj, id)
/*
* call-seq:
* Process::UID.re_exchangeable? => true or false
- *
+ *
* Returns +true+ if the real and effective user IDs of a
* process may be exchanged on the current platform.
- *
+ *
*/
static VALUE
@@ -2992,10 +2979,10 @@ p_uid_exchangeable()
/*
* call-seq:
* Process::UID.re_exchange => fixnum
- *
+ *
* Exchange real and effective user IDs and return the new effective
* user ID. Not available on all platforms.
- *
+ *
* [Process.uid, Process.euid] #=> [0, 31]
* Process::UID.re_exchange #=> 0
* [Process.uid, Process.euid] #=> [31, 0]
@@ -3028,10 +3015,10 @@ p_uid_exchange(obj)
/*
* call-seq:
* Process::GID.re_exchangeable? => true or false
- *
+ *
* Returns +true+ if the real and effective group IDs of a
* process may be exchanged on the current platform.
- *
+ *
*/
static VALUE
@@ -3050,10 +3037,10 @@ p_gid_exchangeable()
/*
* call-seq:
* Process::GID.re_exchange => fixnum
- *
+ *
* Exchange real and effective group IDs and return the new effective
* group ID. Not available on all platforms.
- *
+ *
* [Process.gid, Process.egid] #=> [0, 33]
* Process::GID.re_exchange #=> 0
* [Process.gid, Process.egid] #=> [33, 0]
@@ -3087,10 +3074,10 @@ p_gid_exchange(obj)
/*
* call-seq:
* Process::UID.sid_available? => true or false
- *
+ *
* Returns +true+ if the current platform has saved user
* ID functionality.
- *
+ *
*/
static VALUE
@@ -3118,19 +3105,20 @@ p_uid_sw_ensure(id)
* call-seq:
* Process::UID.switch => fixnum
* Process::UID.switch {|| block} => object
- *
+ *
* Switch the effective and real user IDs of the current process. If
* a <em>block</em> is given, the user IDs will be switched back
* after the block is executed. Returns the new effective user ID if
* called without a block, and the return value of the block if one
* is given.
- *
+ *
*/
static VALUE
p_uid_switch(obj)
VALUE obj;
{
+ extern int errno;
int uid, euid;
check_uid_switch();
@@ -3172,6 +3160,7 @@ static VALUE
p_uid_switch(obj)
VALUE obj;
{
+ extern int errno;
int uid, euid;
check_uid_switch();
@@ -3199,10 +3188,10 @@ p_uid_switch(obj)
/*
* call-seq:
* Process::GID.sid_available? => true or false
- *
+ *
* Returns +true+ if the current platform has saved group
* ID functionality.
- *
+ *
*/
static VALUE
@@ -3229,19 +3218,20 @@ p_gid_sw_ensure(id)
* call-seq:
* Process::GID.switch => fixnum
* Process::GID.switch {|| block} => object
- *
+ *
* Switch the effective and real group IDs of the current process. If
* a <em>block</em> is given, the group IDs will be switched back
* after the block is executed. Returns the new effective group ID if
* called without a block, and the return value of the block if one
* is given.
- *
+ *
*/
static VALUE
p_gid_switch(obj)
VALUE obj;
{
+ extern int errno;
int gid, egid;
check_gid_switch();
@@ -3282,6 +3272,7 @@ static VALUE
p_gid_switch(obj)
VALUE obj;
{
+ extern int errno;
int gid, egid;
check_gid_switch();
@@ -3307,11 +3298,11 @@ p_gid_switch(obj)
/*
* call-seq:
* Process.times => aStructTms
- *
+ *
* Returns a <code>Tms</code> structure (see <code>Struct::Tms</code>
* on page 388) that contains user and system CPU times for this
* process.
- *
+ *
* t = Process.times
* [ t.utime, t.stime ] #=> [0.0, 0.02]
*/
@@ -3463,18 +3454,26 @@ Init_process()
rb_define_module_function(rb_mProcGID, "rid", proc_getgid, 0);
rb_define_module_function(rb_mProcUID, "eid", proc_geteuid, 0);
rb_define_module_function(rb_mProcGID, "eid", proc_getegid, 0);
- rb_define_module_function(rb_mProcUID, "change_privilege", p_uid_change_privilege, 1);
- rb_define_module_function(rb_mProcGID, "change_privilege", p_gid_change_privilege, 1);
- rb_define_module_function(rb_mProcUID, "grant_privilege", p_uid_grant_privilege, 1);
- rb_define_module_function(rb_mProcGID, "grant_privilege", p_gid_grant_privilege, 1);
+ rb_define_module_function(rb_mProcUID, "change_privilege",
+ p_uid_change_privilege, 1);
+ rb_define_module_function(rb_mProcGID, "change_privilege",
+ p_gid_change_privilege, 1);
+ rb_define_module_function(rb_mProcUID, "grant_privilege",
+ p_uid_grant_privilege, 1);
+ rb_define_module_function(rb_mProcGID, "grant_privilege",
+ p_gid_grant_privilege, 1);
rb_define_alias(rb_mProcUID, "eid=", "grant_privilege");
rb_define_alias(rb_mProcGID, "eid=", "grant_privilege");
rb_define_module_function(rb_mProcUID, "re_exchange", p_uid_exchange, 0);
rb_define_module_function(rb_mProcGID, "re_exchange", p_gid_exchange, 0);
- rb_define_module_function(rb_mProcUID, "re_exchangeable?", p_uid_exchangeable, 0);
- rb_define_module_function(rb_mProcGID, "re_exchangeable?", p_gid_exchangeable, 0);
- rb_define_module_function(rb_mProcUID, "sid_available?", p_uid_have_saved_id, 0);
- rb_define_module_function(rb_mProcGID, "sid_available?", p_gid_have_saved_id, 0);
+ rb_define_module_function(rb_mProcUID, "re_exchangeable?",
+ p_uid_exchangeable, 0);
+ rb_define_module_function(rb_mProcGID, "re_exchangeable?",
+ p_gid_exchangeable, 0);
+ rb_define_module_function(rb_mProcUID, "sid_available?",
+ p_uid_have_saved_id, 0);
+ rb_define_module_function(rb_mProcGID, "sid_available?",
+ p_gid_have_saved_id, 0);
rb_define_module_function(rb_mProcUID, "switch", p_uid_switch, 0);
rb_define_module_function(rb_mProcGID, "switch", p_gid_switch, 0);
@@ -3494,10 +3493,15 @@ Init_process()
rb_define_module_function(rb_mProcID_Syscall, "seteuid", p_sys_seteuid, 1);
rb_define_module_function(rb_mProcID_Syscall, "setegid", p_sys_setegid, 1);
- rb_define_module_function(rb_mProcID_Syscall, "setreuid", p_sys_setreuid, 2);
- rb_define_module_function(rb_mProcID_Syscall, "setregid", p_sys_setregid, 2);
-
- rb_define_module_function(rb_mProcID_Syscall, "setresuid", p_sys_setresuid, 3);
- rb_define_module_function(rb_mProcID_Syscall, "setresgid", p_sys_setresgid, 3);
- rb_define_module_function(rb_mProcID_Syscall, "issetugid", p_sys_issetugid, 0);
+ rb_define_module_function(rb_mProcID_Syscall, "setreuid",
+ p_sys_setreuid, 2);
+ rb_define_module_function(rb_mProcID_Syscall, "setregid",
+ p_sys_setregid, 2);
+
+ rb_define_module_function(rb_mProcID_Syscall, "setresuid",
+ p_sys_setresuid, 3);
+ rb_define_module_function(rb_mProcID_Syscall, "setresgid",
+ p_sys_setresgid, 3);
+ rb_define_module_function(rb_mProcID_Syscall, "issetugid",
+ p_sys_issetugid, 0);
}
diff --git a/random.c b/random.c
index 618a3a8fa3..a317aa5cc1 100644
--- a/random.c
+++ b/random.c
@@ -92,37 +92,6 @@ init_genrand(s)
left = 1; initf = 1;
}
-/* initialize by an array with array-length */
-/* init_key is the array for initializing keys */
-/* key_length is its length */
-/* slight change for C++, 2004/2/26 */
-static void
-init_by_array(unsigned long init_key[], int key_length)
-{
- int i, j, k;
- init_genrand(19650218UL);
- i=1; j=0;
- k = (N>key_length ? N : key_length);
- for (; k; k--) {
- state[i] = (state[i] ^ ((state[i-1] ^ (state[i-1] >> 30)) * 1664525UL))
- + init_key[j] + j; /* non linear */
- state[i] &= 0xffffffffUL; /* for WORDSIZE > 32 machines */
- i++; j++;
- if (i>=N) { state[0] = state[N-1]; i=1; }
- if (j>=key_length) j=0;
- }
- for (k=N-1; k; k--) {
- state[i] = (state[i] ^ ((state[i-1] ^ (state[i-1] >> 30)) * 1566083941UL))
- - i; /* non linear */
- state[i] &= 0xffffffffUL; /* for WORDSIZE > 32 machines */
- i++;
- if (i>=N) { state[0] = state[N-1]; i=1; }
- }
-
- state[0] = 0x80000000UL; /* MSB is 1; assuring non-zero initial array */
- left = 1; initf = 1;
-}
-
static void
next_state()
{
@@ -145,9 +114,9 @@ next_state()
*p = p[M-N] ^ TWIST(p[0], state[0]);
}
-/* generates a random number on [0,0xffffffff]-interval */
-static unsigned long
-genrand_int32(void)
+/* generates a random number on [0,1)-real-interval */
+static double
+genrand_real()
{
unsigned long y;
@@ -160,18 +129,10 @@ genrand_int32(void)
y ^= (y << 15) & 0xefc60000UL;
y ^= (y >> 18);
- return y;
+ return (double)y * (1.0/4294967296.0);
+ /* divided by 2^32 */
}
-/* generates a random number on [0,1) with 53-bit resolution*/
-static double
-genrand_real(void)
-{
- unsigned long a=genrand_int32()>>5, b=genrand_int32()>>6;
- return(a*67108864.0+b)*(1.0/9007199254740992.0);
-}
-/* These real versions are due to Isaku Wada, 2002/01/09 added */
-
#undef N
#undef M
@@ -183,126 +144,32 @@ genrand_real(void)
#include <unistd.h>
#endif
#include <time.h>
-#include <sys/types.h>
-#include <sys/stat.h>
-#ifdef HAVE_FCNTL_H
-#include <fcntl.h>
-#endif
static int first = 1;
-static VALUE saved_seed = INT2FIX(0);
-static VALUE
-rand_init(vseed)
- VALUE vseed;
+static int
+rand_init(seed)
+ unsigned long seed;
{
- volatile VALUE seed;
- VALUE old;
- long len;
- unsigned long *buf;
+ static unsigned long saved_seed;
+ unsigned long old;
- seed = rb_to_int(vseed);
- switch (TYPE(seed)) {
- case T_FIXNUM:
- len = sizeof(VALUE);
- break;
- case T_BIGNUM:
- len = RBIGNUM(seed)->len * SIZEOF_BDIGITS;
- if (len == 0)
- len = 4;
- break;
- default:
- rb_raise(rb_eTypeError, "failed to convert %s into Integer",
- rb_obj_classname(vseed));
- }
- len = (len + 3) / 4; /* number of 32bit words */
- buf = ALLOC_N(unsigned long, len); /* allocate longs for init_by_array */
- memset(buf, 0, len * sizeof(long));
- if (FIXNUM_P(seed)) {
- buf[0] = FIX2ULONG(seed) & 0xffffffff;
-#if SIZEOF_LONG > 4
- buf[1] = FIX2ULONG(seed) >> 32;
-#endif
- }
- else {
- int i, j;
- for (i = RBIGNUM(seed)->len-1; 0 <= i; i--) {
- j = i * SIZEOF_BDIGITS / 4;
-#if SIZEOF_BDIGITS < 4
- buf[j] <<= SIZEOF_BDIGITS * 8;
-#endif
- buf[j] |= ((BDIGIT *)RBIGNUM(seed)->digits)[i];
- }
- }
- while (1 < len && buf[len-1] == 0) {
- len--;
- }
- if (len <= 1) {
- init_genrand(buf[0]);
- }
- else {
- if (buf[len-1] == 1) /* remove leading-zero-guard */
- len--;
- init_by_array(buf, len);
- }
first = 0;
+ init_genrand(seed);
old = saved_seed;
saved_seed = seed;
- free(buf);
+
return old;
}
-static VALUE
+static unsigned long
random_seed()
{
static int n = 0;
struct timeval tv;
- int fd;
- struct stat statbuf;
-
- int seed_len;
- BDIGIT *digits;
- unsigned long *seed;
- NEWOBJ(big, struct RBignum);
- OBJSETUP(big, rb_cBignum, T_BIGNUM);
-
- seed_len = 4 * sizeof(long);
- big->sign = 1;
- big->len = seed_len / SIZEOF_BDIGITS + 1;
- digits = big->digits = ALLOC_N(BDIGIT, big->len);
- seed = (unsigned long *)big->digits;
-
- memset(digits, 0, big->len * SIZEOF_BDIGITS);
-
-#ifdef S_ISCHR
- if ((fd = open("/dev/urandom", O_RDONLY
-#ifdef O_NONBLOCK
- |O_NONBLOCK
-#endif
-#ifdef O_NOCTTY
- |O_NOCTTY
-#endif
-#ifdef O_NOFOLLOW
- |O_NOFOLLOW
-#endif
- )) >= 0) {
- if (fstat(fd, &statbuf) == 0 && S_ISCHR(statbuf.st_mode)) {
- read(fd, seed, seed_len);
- }
- close(fd);
- }
-#endif
gettimeofday(&tv, 0);
- seed[0] ^= tv.tv_usec;
- seed[1] ^= tv.tv_sec;
- seed[2] ^= getpid() ^ (n++ << 16);
- seed[3] ^= (unsigned long)&seed;
-
- /* set leading-zero-guard if need. */
- digits[big->len-1] = digits[big->len-2] <= 1 ? 1 : 0;
-
- return rb_big_norm((VALUE)big);
+ return tv.tv_sec ^ tv.tv_usec ^ getpid() ^ n++;
}
/*
@@ -325,94 +192,19 @@ rb_f_srand(argc, argv, obj)
VALUE *argv;
VALUE obj;
{
- VALUE seed, old;
+ VALUE sd;
+ unsigned long seed, old;
rb_secure(4);
- if (rb_scan_args(argc, argv, "01", &seed) == 0) {
+ if (rb_scan_args(argc, argv, "01", &sd) == 0) {
seed = random_seed();
}
- old = rand_init(seed);
-
- return old;
-}
-
-static unsigned long
-make_mask(unsigned long x)
-{
- x = x | x >> 1;
- x = x | x >> 2;
- x = x | x >> 4;
- x = x | x >> 8;
- x = x | x >> 16;
-#if 4 < SIZEOF_LONG
- x = x | x >> 32;
-#endif
- return x;
-}
-
-static unsigned long
-limited_rand(unsigned long limit)
-{
- unsigned long mask = make_mask(limit);
- int i;
- unsigned long val;
-
- retry:
- val = 0;
- for (i = SIZEOF_LONG/4-1; 0 <= i; i--) {
- if (mask >> (i * 32)) {
- val |= genrand_int32() << (i * 32);
- val &= mask;
- if (limit < val)
- goto retry;
- }
+ else {
+ seed = NUM2ULONG(sd);
}
- return val;
-}
+ old = rand_init(seed);
-static VALUE
-limited_big_rand(struct RBignum *limit)
-{
- unsigned long mask, lim, rnd;
- struct RBignum *val;
- int i, len, boundary;
-
- len = (limit->len * SIZEOF_BDIGITS + 3) / 4;
- val = (struct RBignum *)rb_big_clone((VALUE)limit);
- val->sign = 1;
-#if SIZEOF_BDIGITS == 2
-# define BIG_GET32(big,i) (((BDIGIT *)(big)->digits)[(i)*2] | \
- ((i)*2+1 < (big)->len ? (((BDIGIT *)(big)->digits)[(i)*2+1] << 16) \
- : 0))
-# define BIG_SET32(big,i,d) ((((BDIGIT *)(big)->digits)[(i)*2] = (d) & 0xffff), \
- ((i)*2+1 < (big)->len ? (((BDIGIT *)(big)->digits)[(i)*2+1] = (d) >> 16) \
- : 0))
-#else
- /* SIZEOF_BDIGITS == 4 */
-# define BIG_GET32(big,i) (((BDIGIT *)(big)->digits)[i])
-# define BIG_SET32(big,i,d) (((BDIGIT *)(big)->digits)[i] = (d))
-#endif
- retry:
- mask = 0;
- boundary = 1;
- for (i = len-1; 0 <= i; i--) {
- lim = BIG_GET32(limit, i);
- mask = mask ? 0xffffffff : make_mask(lim);
- if (mask) {
- rnd = genrand_int32() & mask;
- if (boundary) {
- if (lim < rnd)
- goto retry;
- if (rnd < lim)
- boundary = 0;
- }
- }
- else {
- rnd = 0;
- }
- BIG_SET32(val, i, rnd);
- }
- return rb_big_norm((VALUE)val);
+ return ULONG2NUM(old);
}
/*
@@ -454,26 +246,18 @@ rb_f_rand(argc, argv, obj)
max = (long)RFLOAT(vmax)->value;
break;
}
- if (RFLOAT(vmax)->value < 0)
- vmax = rb_dbl2big(-RFLOAT(vmax)->value);
- else
- vmax = rb_dbl2big(RFLOAT(vmax)->value);
+ vmax = rb_dbl2big(RFLOAT(vmax)->value);
/* fall through */
case T_BIGNUM:
bignum:
{
- struct RBignum *limit = (struct RBignum *)vmax;
- if (!limit->sign) {
- limit = (struct RBignum *)rb_big_clone(vmax);
- limit->sign = 1;
- }
- limit = (struct RBignum *)rb_big_minus((VALUE)limit, INT2FIX(1));
- if (FIXNUM_P((VALUE)limit)) {
- if (FIX2LONG((VALUE)limit) == -1)
- return rb_float_new(genrand_real());
- return LONG2NUM(limited_rand(FIX2LONG((VALUE)limit)));
- }
- return limited_big_rand(limit);
+ long len = RBIGNUM(vmax)->len;
+ double *buf = ALLOCA_N(double, len);
+
+ while (len--) {
+ buf[len] = genrand_real();
+ }
+ return rb_big_rand(vmax, buf);
}
case T_NIL:
max = 0;
@@ -490,7 +274,8 @@ rb_f_rand(argc, argv, obj)
return rb_float_new(genrand_real());
}
if (max < 0) max = -max;
- val = limited_rand(max-1);
+ val = max*genrand_real();
+
return LONG2NUM(val);
}
@@ -499,5 +284,4 @@ Init_Random()
{
rb_define_global_function("srand", rb_f_srand, -1);
rb_define_global_function("rand", rb_f_rand, -1);
- rb_global_variable(&saved_seed);
}
diff --git a/range.c b/range.c
index 3f575de91b..6783eff782 100644
--- a/range.c
+++ b/range.c
@@ -29,7 +29,11 @@ static VALUE
range_check(args)
VALUE *args;
{
- return rb_funcall(args[0], id_cmp, 1, args[1]);
+ VALUE v;
+
+ v = rb_funcall(args[0], id_cmp, 1, args[1]);
+ if (NIL_P(v)) range_failed();
+ return Qnil;
}
static void
@@ -43,10 +47,7 @@ range_init(range, beg, end, exclude_end)
args[1] = end;
if (!FIXNUM_P(beg) || !FIXNUM_P(end)) {
- VALUE v;
-
- v = rb_rescue(range_check, (VALUE)args, range_failed, 0);
- if (NIL_P(v)) range_failed();
+ rb_rescue(range_check, (VALUE)args, range_failed, 0);
}
SET_EXCL(range, exclude_end);
@@ -351,7 +352,7 @@ range_step(argc, argv, range)
if (unit == 0) rb_raise(rb_eArgError, "step can't be 0");
if (!rb_respond_to(b, id_succ)) {
- rb_raise(rb_eTypeError, "can't iterate from %s",
+ rb_raise(rb_eTypeError, "cannot iterate from %s",
rb_obj_classname(b));
}
@@ -399,7 +400,7 @@ range_each(range)
end = rb_ivar_get(range, id_end);
if (!rb_respond_to(beg, id_succ)) {
- rb_raise(rb_eTypeError, "can't iterate from %s",
+ rb_raise(rb_eTypeError, "cannot iterate from %s",
rb_obj_classname(beg));
}
if (FIXNUM_P(beg) && FIXNUM_P(end)) { /* fixnums are special */
diff --git a/re.c b/re.c
index ab60aba1c1..f676b203d7 100644
--- a/re.c
+++ b/re.c
@@ -641,9 +641,7 @@ make_regexp(s, len, flags)
err = re_compile_pattern(s, len, rp);
if (err != NULL) {
- re_free_pattern(rp);
rb_reg_raise(s, len, err, 0);
- return 0;
}
return rp;
}
@@ -680,7 +678,6 @@ match_alloc(klass)
return (VALUE)match;
}
-/* :nodoc: */
static VALUE
match_init_copy(obj, orig)
VALUE obj, orig;
@@ -1526,8 +1523,8 @@ rb_reg_match(re, str)
*
* a = "HELLO"
* case a
- * when /^[a-z]*$/; print "Lower case\n"
- * when /^[A-Z]*$/; print "Upper case\n"
+ * when /^a-z*$/; print "Lower case\n"
+ * when /^A-Z*$/; print "Upper case\n"
* else; print "Mixed case\n"
* end
*
@@ -1630,7 +1627,7 @@ rb_reg_match_m(re, str)
* options are propagated, and new options may not be specified (a change as of
* Ruby 1.8). If <i>options</i> is a <code>Fixnum</code>, it should be one or
* more of the constants <code>Regexp::EXTENDED</code>,
- * <code>Regexp::IGNORECASE</code>, and <code>Regexp::MULTILINE</code>,
+ * <code>Regexp::IGNORECASE</code>, and <code>Regexp::POSIXLINE</code>,
* <em>or</em>-ed together. Otherwise, if <i>options</i> is not
* <code>nil</code>, the regexp will be case insensitive. The <i>lang</i>
* parameter enables multibyte support for the regexp: `n', `N' = none, `e',
@@ -1712,7 +1709,7 @@ rb_reg_initialize_m(argc, argv, self)
s = StringValuePtr(argv[0]);
len = RSTRING(argv[0])->len;
}
- rb_reg_initialize(self, s, len, flags);
+ rb_reg_initialize(self, s, len, flags, Qtrue);
return self;
}
@@ -1804,12 +1801,11 @@ rb_reg_quote(str)
/*
* call-seq:
- * Regexp.escape(str) => a_str
- * Regexp.quote(str) => a_str
+ * Regexp.escape(str) => new_str
+ * Regexp.quote(str) => new_str
*
* Escapes any characters that would have special meaning in a regular
- * expression. Returns a new escaped string, or self if no characters are
- * escaped. For any string,
+ * expression. For any string,
* <code>Regexp.escape(<i>str</i>)=~<i>str</i></code> will be true.
*
* Regexp.escape('\\*?{}.') #=> \\\\\*\?\{\}\.
@@ -1975,7 +1971,6 @@ rb_reg_s_union(argc, argv)
}
}
-/* :nodoc: */
static VALUE
rb_reg_init_copy(copy, re)
VALUE copy, re;
@@ -1988,7 +1983,7 @@ rb_reg_init_copy(copy, re)
}
rb_reg_check(re);
rb_reg_initialize(copy, RREGEXP(re)->str, RREGEXP(re)->len,
- rb_reg_options(re));
+ rb_reg_options(re), Qfalse);
return copy;
}
diff --git a/regex.c b/regex.c
index 7717835c92..eb6c9efa54 100644
--- a/regex.c
+++ b/regex.c
@@ -185,7 +185,7 @@ static int current_mbctype = MBCTYPE_ASCII;
#ifdef RUBY
#include "util.h"
-void rb_warn _((const char*, ...));
+void rb_warn _((char*));
# define re_warning(x) rb_warn(x)
#endif
@@ -1011,8 +1011,8 @@ calculate_must_string(start, end)
{
int mcnt;
int max = 0;
- unsigned char *p = start;
- unsigned char *pend = end;
+ char *p = start;
+ char *pend = end;
char *must = 0;
if (start == NULL) return 0;
@@ -1162,7 +1162,7 @@ read_special(p, pend, pp)
PATFETCH_RAW(c);
*pp = p;
if (c == '\\') {
- return read_special(--p, pend, pp) | 0x80;
+ return read_special(p, pend, pp) | 0x80;
}
else if (c == -1) return ~0;
else {
@@ -1176,13 +1176,12 @@ read_special(p, pend, pp)
PATFETCH_RAW(c);
*pp = p;
if (c == '\\') {
- c = read_special(--p, pend, pp);
+ c = read_special(p, pend, pp);
}
else if (c == '?') return 0177;
else if (c == -1) return ~0;
return c & 0x9f;
default:
- *pp = p + 1;
return read_backslash(c);
}
@@ -1578,7 +1577,7 @@ re_compile_pattern(pattern, size, bufp)
case 'C':
case 'c':
{
- const char *pp;
+ char *pp;
--p;
c = read_special(p, pend, &pp);
@@ -1725,7 +1724,6 @@ re_compile_pattern(pattern, size, bufp)
memmove(&b[(unsigned char)b[-1]], &b[(1 << BYTEWIDTH) / BYTEWIDTH],
2 + EXTRACT_UNSIGNED(&b[(1 << BYTEWIDTH) / BYTEWIDTH])*8);
b += b[-1] + 2 + EXTRACT_UNSIGNED(&b[(unsigned char)b[-1]])*8;
- had_num_literal = 0;
break;
case '(':
@@ -2625,9 +2623,9 @@ insert_op_2(op, there, current_end, num_1, num_2)
#define trans_eq(c1, c2, translate) (translate?(translate[c1]==translate[c2]):((c1)==(c2)))
static int
slow_match(little, lend, big, bend, translate)
- const unsigned char *little, *lend;
- const unsigned char *big, *bend;
- const unsigned char *translate;
+ unsigned char *little, *lend;
+ unsigned char *big, *bend;
+ unsigned char *translate;
{
int c;
diff --git a/ruby.c b/ruby.c
index 8862f51b7d..f41196093c 100644
--- a/ruby.c
+++ b/ruby.c
@@ -192,7 +192,7 @@ ruby_incpush(path)
p = path;
while (*p) {
while (*p == sep) p++;
- if ((s = strchr(p, sep)) != 0) {
+ if (s = strchr(p, sep)) {
rb_ary_push(ary, rubylib_mangled_path(p, (int)(s-p)));
p = s + 1;
}
@@ -350,11 +350,8 @@ require_libraries()
ruby_set_current_source();
req_list_last = 0;
while (list) {
- int state;
-
ruby_current_node = 0;
- rb_protect((VALUE (*)(VALUE))rb_require, (VALUE)list->name, &state);
- if (state) rb_jump_tag(state);
+ rb_require(list->name);
tmp = list->next;
free(list->name);
free(list);
@@ -382,43 +379,20 @@ process_sflag()
VALUE v = *args++;
char *s = StringValuePtr(v);
char *p;
- int hyphen = Qfalse;
if (s[0] != '-') break;
n--;
if (s[1] == '-' && s[2] == '\0') break;
- v = Qtrue;
- /* check if valid name before replacing - with _ */
- for (p = s + 1; *p; p++) {
- if (*p == '=') {
- *p++ = '\0';
- v = rb_str_new2(p);
- break;
- }
- if (*p == '-') {
- hyphen = Qtrue;
- }
- else if (*p != '_' && !ISALNUM(*p)) {
- VALUE name_error[2];
- name_error[0] = rb_str_new2("invalid name for global variable - ");
- if (!(p = strchr(p, '='))) {
- rb_str_cat2(name_error[0], s);
- }
- else {
- rb_str_cat(name_error[0], s, p - s);
- }
- name_error[1] = args[-1];
- rb_exc_raise(rb_class_new_instance(2, name_error, rb_eNameError));
- }
- }
s[0] = '$';
- if (hyphen) {
- for (p = s + 1; *p; ++p) {
- if (*p == '-') *p = '_';
- }
+ if (p = strchr(s, '=')) {
+ *p++ = '\0';
+ rb_gv_set(s, rb_str_new2(p));
+ }
+ else {
+ rb_gv_set(s, Qtrue);
}
- rb_gv_set(s, v);
+ s[0] = '-';
}
n = RARRAY(rb_argv)->len - n;
while (n--) {
@@ -704,20 +678,9 @@ proc_options(argc, argv)
}
break;
- case '\r':
- if (!s[1]) break;
-
default:
- {
- const char *format;
- if (ISPRINT(*s)) {
- format = "%s: invalid option -%c (-h will show valid options)\n";
- }
- else {
- format = "%s: invalid option -\\%03o (-h will show valid options)\n";
- }
- fprintf(stderr, format, origargv[0], (int)(unsigned char)*s);
- }
+ fprintf(stderr, "%s: invalid option -%c (-h will show valid options)\n",
+ origargv[0], *s);
exit(2);
case 0:
@@ -730,11 +693,11 @@ proc_options(argc, argv)
if (rb_safe_level() == 0 && (s = getenv("RUBYOPT"))) {
while (ISSPACE(*s)) s++;
- if (*s == 'T' || (*s == '-' && *(s+1) == 'T')) {
+ if (*s == '-' && *(s+1) == 'T') {
int numlen;
int v = 1;
- if (*s != 'T') ++s;
+ s += 2;
if (*++s) {
v = scan_oct(s, 2, &numlen);
if (numlen == 0) v = 1;
@@ -752,7 +715,7 @@ proc_options(argc, argv)
}
if (!*s) break;
if (!strchr("IdvwrK", *s))
- rb_raise(rb_eRuntimeError, "illegal switch in RUBYOPT: -%c", *s);
+ rb_raise(rb_eRuntimeError, "Illegal switch in RUBYOPT: -%c", *s);
s = moreswitches(s);
}
}
@@ -874,12 +837,12 @@ load_file(fname, script)
if (RSTRING(line)->len > 2
&& RSTRING(line)->ptr[0] == '#'
&& RSTRING(line)->ptr[1] == '!') {
- if ((p = strstr(RSTRING(line)->ptr, "ruby")) != 0) {
+ if (p = strstr(RSTRING(line)->ptr, "ruby")) {
goto start_read;
}
}
}
- rb_raise(rb_eLoadError, "no Ruby script found in input");
+ rb_raise(rb_eLoadError, "No Ruby script found in input");
}
c = rb_io_getc(f);
@@ -926,7 +889,7 @@ load_file(fname, script)
RSTRING(line)->ptr[RSTRING(line)->len-1] = '\0';
if (RSTRING(line)->ptr[RSTRING(line)->len-2] == '\r')
RSTRING(line)->ptr[RSTRING(line)->len-2] = '\0';
- if ((p = strstr(p, " -")) != 0) {
+ if (p = strstr(p, " -")) {
p++; /* skip space before `-' */
while (*p == '-') {
p = moreswitches(p+1);
@@ -971,33 +934,6 @@ VALUE rb_progname;
VALUE rb_argv;
VALUE rb_argv0;
-#if !defined(PSTAT_SETCMD) && !defined(HAVE_SETPROCTITLE) && !defined(DOSISH)
-static struct {
- char *begin, *end;
-} envspace;
-extern char **environ;
-
-static void
-set_arg0space()
-{
- char *s;
- int i;
-
- if (!environ || (s = environ[0]) == NULL) return;
- envspace.begin = s;
- s += strlen(s);
- for (i = 1; environ[i]; i++) {
- if (environ[i] == s + 1) {
- s++;
- s += strlen(s); /* this one is ok too */
- }
- }
- envspace.end = s;
-}
-#else
-#define set_arg0space() ((void)0)
-#endif
-
static void
set_arg0(val, id)
VALUE val;
@@ -1005,27 +941,25 @@ set_arg0(val, id)
{
char *s;
long i;
-#if !defined(PSTAT_SETCMD) && !defined(HAVE_SETPROCTITLE)
static int len;
-#endif
if (origargv == 0) rb_raise(rb_eRuntimeError, "$0 not initialized");
StringValue(val);
s = RSTRING(val)->ptr;
i = RSTRING(val)->len;
-#if defined(PSTAT_SETCMD)
+#ifdef __hpux
if (i >= PST_CLEN) {
- union pstun j;
- j.pst_command = s;
- i = PST_CLEN;
- RSTRING(val)->len = i;
- *(s + i) = '\0';
- pstat(PSTAT_SETCMD, j, PST_CLEN, 0, 0);
+ union pstun j;
+ j.pst_command = s;
+ i = PST_CLEN;
+ RSTRING(val)->len = i;
+ *(s + i) = '\0';
+ pstat(PSTAT_SETCMD, j, PST_CLEN, 0, 0);
}
else {
- union pstun j;
- j.pst_command = s;
- pstat(PSTAT_SETCMD, j, i, 0, 0);
+ union pstun j;
+ j.pst_command = s;
+ pstat(PSTAT_SETCMD, j, i, 0, 0);
}
rb_progname = rb_tainted_str_new(s, i);
#elif defined(HAVE_SETPROCTITLE)
@@ -1047,12 +981,6 @@ set_arg0(val, id)
break;
}
}
-#ifndef DOSISH
- if (s + 1 == envspace.begin) {
- s = envspace.end;
- ruby_setenv("", NULL); /* duplicate environ vars */
- }
-#endif
len = s - origargv[0];
}
@@ -1107,11 +1035,11 @@ forbid_setid(s)
const char *s;
{
if (euid != uid)
- rb_raise(rb_eSecurityError, "no %s allowed while running setuid", s);
+ rb_raise(rb_eSecurityError, "No %s allowed while running setuid", s);
if (egid != gid)
- rb_raise(rb_eSecurityError, "no %s allowed while running setgid", s);
+ rb_raise(rb_eSecurityError, "No %s allowed while running setgid", s);
if (rb_safe_level() > 0)
- rb_raise(rb_eSecurityError, "no %s allowed in tainted mode", s);
+ rb_raise(rb_eSecurityError, "No %s allowed in tainted mode", s);
}
static void
@@ -1188,7 +1116,6 @@ ruby_process_options(argc, argv)
#if defined(USE_DLN_A_OUT)
dln_argv0 = argv[0];
#endif
- set_arg0space();
proc_options(argc, argv);
if (do_check && ruby_nerrs == 0) {
diff --git a/ruby.h b/ruby.h
index 37e84b601a..db3280b905 100644
--- a/ruby.h
+++ b/ruby.h
@@ -16,9 +16,6 @@
#if defined(__cplusplus)
extern "C" {
-#if 0
-} /* satisfy cc-mode */
-#endif
#endif
#include "config.h"
@@ -75,10 +72,9 @@ extern "C" {
#if SIZEOF_LONG != SIZEOF_VOIDP
# error ---->> ruby requires sizeof(void*) == sizeof(long) to be compiled. <<----
-#else
+#endif
typedef unsigned long VALUE;
typedef unsigned long ID;
-#endif
#ifdef __STDC__
# include <limits.h>
@@ -170,10 +166,10 @@ VALUE rb_ull2inum _((unsigned LONG_LONG));
#define SYM2ID(x) RSHIFT((long)x,8)
/* special contants - i.e. non-zero and non-fixnum constants */
-#define Qfalse ((VALUE)0)
-#define Qtrue ((VALUE)2)
-#define Qnil ((VALUE)4)
-#define Qundef ((VALUE)6) /* undefined value for placeholder */
+#define Qfalse 0
+#define Qtrue 2
+#define Qnil 4
+#define Qundef 6 /* undefined value for placeholder */
#define RTEST(v) (((VALUE)(v) & ~Qnil) != 0)
#define NIL_P(v) ((VALUE)(v) == Qnil)
@@ -486,8 +482,6 @@ void rb_extend_object _((VALUE,VALUE));
void rb_define_variable _((const char*,VALUE*));
void rb_define_virtual_variable _((const char*,VALUE(*)(ANYARGS),void(*)(ANYARGS)));
void rb_define_hooked_variable _((const char*,VALUE*,VALUE(*)(ANYARGS),void(*)(ANYARGS)));
-int ruby_glob _((const char*,int,int(*)(const char*,VALUE),VALUE));
-int ruby_globi _((const char*,int,int(*)(const char*,VALUE),VALUE));
void rb_define_readonly_variable _((const char*,VALUE*));
void rb_define_const _((VALUE,const char*,VALUE));
void rb_define_global_const _((const char*,VALUE));
@@ -549,7 +543,6 @@ VALUE rb_yield _((VALUE));
VALUE rb_yield_values __((int n, ...));
VALUE rb_yield_splat _((VALUE));
int rb_block_given_p _((void));
-void rb_need_block _((void));
VALUE rb_iterate _((VALUE(*)(VALUE),VALUE,VALUE(*)(ANYARGS),VALUE));
VALUE rb_rescue _((VALUE(*)(ANYARGS),VALUE,VALUE(*)(ANYARGS),VALUE));
VALUE rb_rescue2 __((VALUE(*)(ANYARGS),VALUE,VALUE(*)(ANYARGS),VALUE,...));
@@ -703,9 +696,6 @@ RUBY_EXTERN int is_ruby_native_thread();
#endif
#if defined(__cplusplus)
-#if 0
-{ /* satisfy cc-mode */
-#endif
} /* extern "C" { */
#endif
diff --git a/rubyio.h b/rubyio.h
index 6039158d55..44f679494e 100644
--- a/rubyio.h
+++ b/rubyio.h
@@ -16,10 +16,6 @@
#include <stdio.h>
#include <errno.h>
-#if defined(HAVE_STDIO_EXT_H)
-#include <stdio_ext.h>
-#endif
-
typedef struct OpenFile {
FILE *f; /* stdio ptr for read/write */
FILE *f2; /* additional ptr for rw pipes */
@@ -39,8 +35,6 @@ typedef struct OpenFile {
#define FMODE_SYNC 8
#define FMODE_WBUF 16
#define FMODE_RBUF 32
-#define FMODE_WSPLIT 0x200
-#define FMODE_WSPLIT_INITIALIZED 0x400
#define GetOpenFile(obj,fp) rb_io_check_closed((fp) = RFILE(rb_io_taint_check(obj))->fptr)
@@ -69,7 +63,6 @@ int rb_getc _((FILE*));
long rb_io_fread _((char *, long, FILE *));
long rb_io_fwrite _((const char *, long, FILE *));
int rb_io_mode_flags _((const char*));
-int rb_io_modenum_flags _((int));
void rb_io_check_writable _((OpenFile*));
void rb_io_check_readable _((OpenFile*));
void rb_io_fptr_finalize _((OpenFile*));
@@ -80,7 +73,7 @@ int rb_io_wait_readable _((int));
int rb_io_wait_writable _((int));
VALUE rb_io_taint_check _((VALUE));
-NORETURN(void rb_eof_error _((void)));
+void rb_eof_error _((void));
void rb_read_check _((FILE*));
int rb_read_pending _((FILE*));
diff --git a/rubysig.h b/rubysig.h
index f716824877..8871e3aa03 100644
--- a/rubysig.h
+++ b/rubysig.h
@@ -46,13 +46,10 @@ typedef int rb_atomic_t;
# define ATOMIC_DEC(var) (--(var))
# define TRAP_BEG do {\
- int saved_errno = 0;\
int trap_immediate = rb_trap_immediate;\
rb_trap_immediate = 1
# define TRAP_END rb_trap_immediate = trap_immediate;\
- saved_errno = errno;\
- CHECK_INTS;\
- errno = saved_errno;\
+ CHECK_INTS;\
} while (0)
# define RUBY_CRITICAL(statements) do {\
@@ -79,12 +76,13 @@ void rb_trap_restore_mask _((void));
RUBY_EXTERN int rb_thread_critical;
void rb_thread_schedule _((void));
-#if defined(HAVE_SETITIMER) || defined(_THREAD_SAFE)
+#if defined(HAVE_SETITIMER)
RUBY_EXTERN int rb_thread_pending;
# define CHECK_INTS do {\
- if (!(rb_prohibit_interrupt || rb_thread_critical)) {\
- if (rb_thread_pending) rb_thread_schedule();\
+ if (!rb_prohibit_interrupt) {\
if (rb_trap_pending) rb_trap_exec();\
+ if (rb_thread_pending && !rb_thread_critical)\
+ rb_thread_schedule();\
}\
} while (0)
#else
@@ -92,13 +90,15 @@ RUBY_EXTERN int rb_thread_pending;
RUBY_EXTERN int rb_thread_tick;
#define THREAD_TICK 500
#define CHECK_INTS do {\
- if (!(rb_prohibit_interrupt || rb_thread_critical)) {\
- if (rb_thread_tick-- <= 0) {\
- rb_thread_tick = THREAD_TICK;\
- rb_thread_schedule();\
+ if (!rb_prohibit_interrupt) {\
+ if (rb_trap_pending) rb_trap_exec();\
+ if (!rb_thread_critical) {\
+ if (rb_thread_tick-- <= 0) {\
+ rb_thread_tick = THREAD_TICK;\
+ rb_thread_schedule();\
+ }\
}\
}\
- if (rb_trap_pending) rb_trap_exec();\
} while (0)
#endif
diff --git a/rubytest.rb b/rubytest.rb
index 8ae637c00e..6f717a2b60 100644
--- a/rubytest.rb
+++ b/rubytest.rb
@@ -1,14 +1,12 @@
#! ./miniruby
-exit if defined?(CROSS_COMPILING)
load './rbconfig.rb'
include Config
-ruby = "./#{CONFIG['ruby_install_name']}#{CONFIG['EXEEXT']}"
-unless File.exist? ruby
- print "#{ruby} is not found.\n"
+unless File.exist? "./#{CONFIG['ruby_install_name']}#{CONFIG['EXEEXT']}"
+ print "./#{CONFIG['ruby_install_name']} is not found.\n"
print "Try `make' first, then `make test', please.\n"
- exit false
+ exit 1
end
if File.exist? CONFIG['LIBRUBY_SO']
@@ -36,8 +34,7 @@ end
$stderr.reopen($stdout)
error = ''
-srcdir = File.dirname(__FILE__)
-`#{ruby} -I#{srcdir}/lib #{srcdir}/sample/test.rb`.each do |line|
+`./#{CONFIG["ruby_install_name"]}#{CONFIG["EXEEXT"]} -I#{CONFIG["srcdir"]}/lib #{CONFIG["srcdir"]}/sample/test.rb`.each do |line|
if line =~ /^end of test/
print "test succeeded\n"
exit 0
diff --git a/runruby.rb b/runruby.rb
deleted file mode 100755
index e749441553..0000000000
--- a/runruby.rb
+++ /dev/null
@@ -1,59 +0,0 @@
-#!./miniruby
-
-while arg = ARGV[0]
- break ARGV.shift if arg == '--'
- /\A--([-\w]+)(?:=(.*))?\z/ =~ arg or break
- arg, value = $1, $2
- re = Regexp.new('\A'+arg.gsub(/\w+\b/, '\&\\w*')+'\z', "i")
- case
- when re =~ "srcdir"
- srcdir = value
- when re =~ "archdir"
- archdir = value
- when re =~ "extout"
- extout = value
- else
- break
- end
- ARGV.shift
-end
-
-srcdir ||= File.dirname(__FILE__)
-archdir ||= '.'
-
-abs_archdir = File.expand_path(archdir)
-$:.unshift(abs_archdir)
-
-require 'rbconfig'
-config = Config::CONFIG
-
-ruby = File.join(archdir, config["RUBY_INSTALL_NAME"]+config['EXEEXT'])
-unless File.exist?(ruby)
- abort "#{ruby} is not found.\nTry `make' first, then `make test', please.\n"
-end
-
-libs = [abs_archdir, File.expand_path("lib", srcdir)]
-if extout
- abs_extout = File.expand_path(extout)
- libs << abs_extout << File.expand_path(RUBY_PLATFORM, abs_extout)
-end
-config["bindir"] = abs_archdir
-ENV["RUBY"] = File.expand_path(ruby)
-ENV["PATH"] = [abs_archdir, ENV["PATH"]].compact.join(File::PATH_SEPARATOR)
-
-if e = ENV["RUBYLIB"]
- libs |= e.split(File::PATH_SEPARATOR)
-end
-ENV["RUBYLIB"] = $:.replace(libs).join(File::PATH_SEPARATOR)
-
-libruby_so = File.join(abs_archdir, config['LIBRUBY_SO'])
-if File.file?(libruby_so)
- if e = config['LIBPATHENV'] and !e.empty?
- ENV[e] = [abs_archdir, ENV[e]].compact.join(File::PATH_SEPARATOR)
- end
- if /linux/ =~ RUBY_PLATFORM
- ENV["LD_PRELOAD"] = [libruby_so, ENV["LD_PRELOAD"]].compact.join(' ')
- end
-end
-
-exec ruby, *ARGV
diff --git a/sample/optparse/subcommand.rb b/sample/optparse/subcommand.rb
deleted file mode 100755
index 21c42dd60a..0000000000
--- a/sample/optparse/subcommand.rb
+++ /dev/null
@@ -1,19 +0,0 @@
-#! /usr/bin/ruby
-# contributed by Minero Aoki.
-
-require 'optparse'
-
-parser = OptionParser.new
-parser.on('-i') { puts "-i" }
-parser.on('-o') { puts '-o' }
-
-subparsers = Hash.new {|h,k|
- $stderr.puts "no such subcommand: #{k}"
- exit 1
-}
-subparsers['add'] = OptionParser.new.on('-i') { puts "add -i" }
-subparsers['del'] = OptionParser.new.on('-i') { puts "del -i" }
-subparsers['list'] = OptionParser.new.on('-i') { puts "list -i" }
-
-parser.order!(ARGV)
-subparsers[ARGV.shift].parse!(ARGV) unless ARGV.empty?
diff --git a/sample/rss/blend.rb b/sample/rss/blend.rb
deleted file mode 100755
index e578f26a86..0000000000
--- a/sample/rss/blend.rb
+++ /dev/null
@@ -1,73 +0,0 @@
-#!/usr/bin/env ruby
-
-require "rss"
-
-feeds = []
-verbose = false
-encoding = "UTF-8"
-
-def error(exception)
- mark = "=" * 20
- mark = "#{mark} error #{mark}"
- STDERR.puts mark
- STDERR.puts exception.class
- STDERR.puts exception.message
- STDERR.puts exception.backtrace
- STDERR.puts mark
-end
-
-before_time = Time.now
-ARGV.each do |fname|
- if fname == '-v'
- verbose = true
- next
- end
- rss = nil
- f = File.new(fname).read
- begin
- ## do validate parse
- rss = RSS::Parser.parse(f)
- rescue RSS::InvalidRSSError
- error($!) if verbose
- ## do non validate parse for invalid RSS 1.0
- begin
- rss = RSS::Parser.parse(f, false)
- rescue RSS::Error
- ## invalid RSS.
- error($!) if verbose
- end
- rescue RSS::Error
- error($!) if verbose
- end
- if rss.nil?
- STDERR.puts "#{fname} does not include RSS 1.0 or 0.9x/2.0"
- else
- begin
- rss.output_encoding = encoding
- rescue RSS::UnknownConversionMethodError
- error($!) if verbose
- end
- feeds << rss
- end
-end
-processing_time = Time.now - before_time
-
-rss = RSS::Maker.make("1.0") do |maker|
- maker.encoding = encoding
- maker.channel.about = "http://example.com/blend.rdf"
- maker.channel.title = "blended feeds"
- maker.channel.link = "http://example.com/"
- maker.channel.description = "blended feeds generated by RSS Parser"
-
- feeds.each do |feed|
- feed.items.each do |item|
- item.setup_maker(maker)
- end
- end
- maker.items.do_sort = true
- maker.items.max_size = 15
-end
-puts rss
-
-STDERR.puts "Used XML parser: #{RSS::Parser.default_parser}"
-STDERR.puts "Processing time: #{processing_time}s"
diff --git a/sample/rss/list_description.rb b/sample/rss/list_description.rb
index bb1f9636e2..e0b59ea659 100644
--- a/sample/rss/list_description.rb
+++ b/sample/rss/list_description.rb
@@ -2,80 +2,82 @@
require "nkf"
class String
- # From tdiary.rb
- def shorten( len = 120 )
- lines = NKF::nkf( "-e -m0 -f#{len}", self.gsub( /\n/, ' ' ) ).split( /\n/ )
- lines[0].concat( '...' ) if lines[0] and lines[1]
- lines[0]
- end
+ # From tdiary.rb
+ def shorten( len = 120 )
+ lines = NKF::nkf( "-e -m0 -f#{len}", self.gsub( /\n/, ' ' ) ).split( /\n/ )
+ lines[0].concat( '...' ) if lines[0] and lines[1]
+ lines[0]
+ end
end
-require "rss"
+require "rss/1.0"
+require "rss/2.0"
+require "rss/dublincore"
channels = {}
verbose = false
def error(exception)
- mark = "=" * 20
- mark = "#{mark} error #{mark}"
- puts mark
- puts exception.class
- puts exception.message
- puts exception.backtrace
- puts mark
+ mark = "=" * 20
+ mark = "#{mark} error #{mark}"
+ puts mark
+ puts exception.class
+ puts exception.message
+ puts exception.backtrace
+ puts mark
end
before_time = Time.now
ARGV.each do |fname|
- if fname == '-v'
- verbose = true
- next
- end
- rss = nil
- f = File.new(fname).read
- begin
- ## do validate parse
- rss = RSS::Parser.parse(f)
- rescue RSS::InvalidRSSError
- error($!) if verbose
- ## do non validate parse for invalid RSS 1.0
- begin
- rss = RSS::Parser.parse(f, false)
- rescue RSS::Error
- ## invalid RSS.
- error($!) if verbose
- end
- rescue RSS::Error
- error($!) if verbose
- end
- if rss.nil?
- puts "#{fname} does not include RSS 1.0 or 0.9x/2.0"
- else
- begin
- rss.output_encoding = "euc-jp"
- rescue RSS::UnknownConversionMethodError
- error($!) if verbose
- end
- rss.channel.title ||= "Unknown"
- rss.items.each do |item|
- item.title ||= "Unknown"
- channels[rss.channel.title] ||= []
- channels[rss.channel.title] << item if item.description
- end
- end
+ if fname == '-v'
+ verbose = true
+ next
+ end
+ rss = nil
+ f = File.new(fname).read
+ begin
+ ## do validate parse
+ rss = RSS::Parser.parse(f)
+ rescue RSS::InvalidRSSError
+ error($!) if verbose
+ ## do non validate parse for invalid RSS 1.0
+ begin
+ rss = RSS::Parser.parse(f, false)
+ rescue RSS::Error
+ ## invalid RSS.
+ error($!) if verbose
+ end
+ rescue RSS::Error
+ error($!) if verbose
+ end
+ if rss.nil?
+ puts "#{fname} does not include RSS 1.0 or 0.9x/2.0"
+ else
+ begin
+ rss.output_encoding = "euc-jp"
+ rescue RSS::UnknownConversionMethodError
+ error($!) if verbose
+ end
+ rss.channel.title ||= "Unknown"
+ rss.items.each do |item|
+ item.title ||= "Unknown"
+ channels[rss.channel.title] ||= []
+ channels[rss.channel.title] << item if item.description
+ end
+ end
end
processing_time = Time.now - before_time
channels.sort do |x, y|
- x[0] <=> y[0]
+ x[0] <=> y[0]
end[0..20].each do |title, items|
- puts "Channel: #{title}" unless items.empty?
- items.sort do |x, y|
- x.title <=> y.title
- end[0..10].each do |item|
- puts " Item: #{item.title.shorten(50)}"
- puts " Description: #{item.description.shorten(50)}"
- end
+ puts "Channel: #{title}" unless items.empty?
+ items.sort do |x, y|
+ x.title <=> y.title
+ end[0..10].each do |item|
+ puts " Item: #{item.title.shorten(50)}"
+ puts " Description: #{item.description.shorten(50)}"
+ end
end
puts "Used XML parser: #{RSS::Parser.default_parser}"
diff --git a/sample/rss/re_read.rb b/sample/rss/re_read.rb
deleted file mode 100755
index c19a5099bb..0000000000
--- a/sample/rss/re_read.rb
+++ /dev/null
@@ -1,64 +0,0 @@
-#!/usr/bin/env ruby
-
-require "rss"
-
-def error(exception)
- mark = "=" * 20
- mark = "#{mark} error #{mark}"
- puts mark
- puts exception.class
- puts exception.message
- puts exception.backtrace
- puts mark
-end
-
-verbose = false
-before_time = Time.now
-
-ARGV.each do |fname|
- if fname == '-v'
- verbose = true
- next
- end
- source = nil
- File.open(fname) do |f|
- source = f.read
- end
-
- rss = nil
- read = false
- begin
- rss = RSS::Parser.parse(source)
- puts "Re-read valid RSS: #{fname}"
- RSS::Parser.parse(rss.to_s)
- read = true
- rescue RSS::InvalidRSSError
- error($!) if verbose
- ## do non validate parse for invalid RSS 1.0
- begin
- rss = RSS::Parser.parse(source, false)
- rescue RSS::Error
- ## invalid RSS.
- error($!) if verbose
- end
- rescue RSS::Error
- error($!) if verbose
- end
-
- if rss.nil?
- puts "Invalid RSS: #{fname}"
- elsif !read
- puts "Re-read invalid RSS: #{fname}"
- begin
- RSS::Parser.parse(rss.to_s)
- rescue RSS::Error
- puts " Error occurred: #{fname}"
- error($!) if verbose
- end
- end
-end
-
-processing_time = Time.now - before_time
-
-puts "Used XML parser: #{RSS::Parser.default_parser}"
-puts "Processing time: #{processing_time}s"
diff --git a/sample/rss/rss_recent.rb b/sample/rss/rss_recent.rb
index 7821df5c7b..8e40151e1c 100644
--- a/sample/rss/rss_recent.rb
+++ b/sample/rss/rss_recent.rb
@@ -2,79 +2,81 @@
require "nkf"
class String
- # From tdiary.rb
- def shorten( len = 120 )
- lines = NKF::nkf( "-e -m0 -f#{len}", self.gsub( /\n/, ' ' ) ).split( /\n/ )
- lines[0].concat( '...' ) if lines[0] and lines[1]
- lines[0]
- end
+ # From tdiary.rb
+ def shorten( len = 120 )
+ lines = NKF::nkf( "-e -m0 -f#{len}", self.gsub( /\n/, ' ' ) ).split( /\n/ )
+ lines[0].concat( '...' ) if lines[0] and lines[1]
+ lines[0]
+ end
end
-require "rss"
+require "rss/1.0"
+require "rss/2.0"
+require "rss/dublincore"
items = []
verbose = false
def error(exception)
- mark = "=" * 20
- mark = "#{mark} error #{mark}"
- puts mark
- puts exception.class
- puts exception.message
- puts exception.backtrace
- puts mark
+ mark = "=" * 20
+ mark = "#{mark} error #{mark}"
+ puts mark
+ puts exception.class
+ puts exception.message
+ puts exception.backtrace
+ puts mark
end
before_time = Time.now
ARGV.each do |fname|
- if fname == '-v'
- verbose = true
- next
- end
- rss = nil
- f = File.new(fname).read
- begin
- ## do validate parse
- rss = RSS::Parser.parse(f)
- rescue RSS::InvalidRSSError
- error($!) if verbose
- ## do non validate parse for invalid RSS 1.0
- begin
- rss = RSS::Parser.parse(f, false)
- rescue RSS::Error
- ## invalid RSS.
- error($!) if verbose
- end
- rescue RSS::Error
- error($!) if verbose
- end
- if rss.nil?
- puts "#{fname} does not include RSS 1.0 or 0.9x/2.0"
- else
- begin
- rss.output_encoding = "euc-jp"
- rescue RSS::UnknownConversionMethodError
- error($!) if verbose
- end
- rss.items.each do |item|
- if item.respond_to?(:pubDate) and item.pubDate
- class << item
- alias_method(:dc_date, :pubDate)
- end
- end
- if item.respond_to?(:dc_date) and item.dc_date
- items << [rss.channel, item]
- end
- end
- end
+ if fname == '-v'
+ verbose = true
+ next
+ end
+ rss = nil
+ f = File.new(fname).read
+ begin
+ ## do validate parse
+ rss = RSS::Parser.parse(f)
+ rescue RSS::InvalidRSSError
+ error($!) if verbose
+ ## do non validate parse for invalid RSS 1.0
+ begin
+ rss = RSS::Parser.parse(f, false)
+ rescue RSS::Error
+ ## invalid RSS.
+ error($!) if verbose
+ end
+ rescue RSS::Error
+ error($!) if verbose
+ end
+ if rss.nil?
+ puts "#{fname} does not include RSS 1.0 or 0.9x/2.0"
+ else
+ begin
+ rss.output_encoding = "euc-jp"
+ rescue RSS::UnknownConversionMethodError
+ error($!) if verbose
+ end
+ rss.items.each do |item|
+ if item.respond_to?(:pubDate) and item.pubDate
+ class << item
+ alias_method(:dc_date, :pubDate)
+ end
+ end
+ if item.respond_to?(:dc_date) and item.dc_date
+ items << [rss.channel, item]
+ end
+ end
+ end
end
processing_time = Time.now - before_time
items.sort do |x, y|
- y[1].dc_date <=> x[1].dc_date
+ y[1].dc_date <=> x[1].dc_date
end[0..20].each do |channel, item|
- puts "#{item.dc_date.localtime.iso8601}: " <<
- "#{channel.title}: #{item.title}"
- puts " Description: #{item.description.shorten(50)}" if item.description
+ puts "#{item.dc_date.localtime.iso8601}: " <<
+ "#{channel.title}: #{item.title}"
+ puts " Description: #{item.description.shorten(50)}" if item.description
end
puts "Used XML parser: #{RSS::Parser.default_parser}"
diff --git a/sample/rss/tdiary_plugin/rss-recent.rb b/sample/rss/tdiary_plugin/rss-recent.rb
new file mode 100644
index 0000000000..090a779092
--- /dev/null
+++ b/sample/rss/tdiary_plugin/rss-recent.rb
@@ -0,0 +1,213 @@
+# rss-recent.rb: RSS recent plugin
+#
+# rss_recnet: show recnet list from RSS
+# parameters (default):
+# url: URL of RSS
+# max: max of list itmes(5)
+# cache_time: cache time(second) of RSS(60*60)
+#
+#
+# Copyright (c) 2003-2004 Kouhei Sutou <kou@cozmixng.org>
+# Distributed under the GPL
+#
+
+require "rss/rss"
+
+RSS_RECENT_FIELD_SEPARATOR = "\0"
+RSS_RECENT_ENTRY_SEPARATOR = "\1"
+RSS_RECENT_VERSION = "0.0.5"
+RSS_RECENT_HTTP_HEADER = {
+ "User-Agent" => "tDiary RSS recent plugin version #{RSS_RECENT_VERSION}. " <<
+ "Using RSS parser version is #{::RSS::VERSION}.",
+}
+
+def rss_recent(url, max=5, cache_time=3600)
+ url.untaint
+
+ cache_file = "#{@cache_path}/rss-recent.#{CGI.escape(url)}"
+
+ rss_recent_cache_rss(url, cache_file, cache_time.to_i)
+
+ return '' unless test(?r, cache_file)
+
+ rv = "<ul>\n"
+
+ i = 0
+ rss_recent_read_from_cache(cache_file).each do |title, url, time|
+ break if i >= max
+ next if title.nil?
+ rv << '<li>'
+ rv << %Q[<span class="#{rss_recent_modified_class(time)}">]
+ unless url.nil?
+ rv << %Q[<a href="#{CGI.escapeHTML(url)}" title="#{CGI.escapeHTML(title)}]
+ rv << %Q[ (#{CGI.escapeHTML(time.localtime.to_s)})] unless time.nil?
+ rv << %Q[">]
+ end
+ rv << CGI::escapeHTML(title)
+ rv << '</a>' unless url.nil?
+ rv << "(#{rss_recent_modified(time)})"
+ rv << %Q[</span>]
+ rv << "</li>\n"
+ i += 1
+ end
+
+ rv << "</ul>\n"
+
+ rv
+end
+
+class InvalidResourceError < StandardError; end
+
+def rss_recent_cache_rss(url, cache_file, cache_time)
+
+ cached_time = nil
+ cached_time = File.mtime(cache_file) if File.exist?(cache_file)
+
+ if cached_time.nil? or Time.now > cached_time + cache_time
+ require 'time'
+ require 'open-uri'
+ require 'net/http'
+ require 'uri/generic'
+ require 'rss/parser'
+ require 'rss/1.0'
+ require 'rss/2.0'
+ require 'rss/dublincore'
+
+ begin
+ uri = URI.parse(url)
+
+ raise URI::InvalidURIError if uri.scheme != "http"
+
+ rss_source = rss_recent_fetch_rss(uri, cached_time)
+
+ raise InvalidResourceError if rss_source.nil?
+
+ # parse RSS
+ rss = ::RSS::Parser.parse(rss_source, false)
+ raise ::RSS::Error if rss.nil?
+
+ # pre processing
+ begin
+ rss.output_encoding = @conf.charset || charset
+ rescue ::RSS::UnknownConversionMethodError
+ end
+
+ rss_infos = rss.items.collect do |item|
+ rss_recent_pubDate_to_dc_date(item)
+ [item.title, item.link, item.dc_date]
+ end
+ rss_recent_write_to_cache(cache_file, rss_infos)
+
+ rescue URI::InvalidURIError
+ rss_recent_write_to_cache(cache_file, [['Invalid URI', url]])
+ rescue InvalidResourceError, ::RSS::Error
+ rss_recent_write_to_cache(cache_file, [['Invalid Resource', url]])
+ end
+ end
+
+end
+
+def rss_recent_fetch_rss(uri, cache_time)
+ rss = nil
+ begin
+ uri.open(rss_recent_http_header(cache_time)) do |f|
+ case f.status.first
+ when "200"
+ rss = f.read
+ # STDERR.puts "Got RSS of #{uri}"
+ when "304"
+ # not modified
+ # STDERR.puts "#{uri} does not modified"
+ else
+ raise InvalidResourceError
+ end
+ end
+ rescue TimeoutError, SocketError, StandardError,
+ SecurityError # occured in redirect
+ raise InvalidResourceError
+ end
+ rss
+end
+
+def rss_recent_http_header(cache_time)
+ header = RSS_RECENT_HTTP_HEADER.dup
+ if cache_time.respond_to?(:rfc2822)
+ header["If-Modified-Since"] = cache_time.rfc2822
+ end
+ header
+end
+
+def rss_recent_write_to_cache(cache_file, rss_infos)
+ File.open(cache_file, 'w') do |f|
+ f.flock(File::LOCK_EX)
+ rss_infos.each do |info|
+ f << info.join(RSS_RECENT_FIELD_SEPARATOR)
+ f << RSS_RECENT_ENTRY_SEPARATOR
+ end
+ f.flock(File::LOCK_UN)
+ end
+end
+
+def rss_recent_read_from_cache(cache_file)
+ require 'time'
+ infos = []
+ File.open(cache_file) do |f|
+ while info = f.gets(RSS_RECENT_ENTRY_SEPARATOR)
+ info = info.chomp(RSS_RECENT_ENTRY_SEPARATOR)
+ infos << info.split(RSS_RECENT_FIELD_SEPARATOR)
+ end
+ end
+ infos.collect do |title, url, time|
+ [
+ rss_recent_convert(title),
+ rss_recent_convert(url),
+ rss_recent_convert(time) {|time| Time.parse(time)},
+ ]
+ end
+end
+
+def rss_recent_convert(str)
+ if str.nil? or str.empty?
+ nil
+ else
+ if block_given?
+ yield str
+ else
+ str
+ end
+ end
+end
+
+# from RWiki
+def rss_recent_modified(t)
+ return '-' unless t
+ dif = (Time.now - t).to_i
+ dif = dif / 60
+ return "#{dif}m" if dif <= 60
+ dif = dif / 60
+ return "#{dif}h" if dif <= 24
+ dif = dif / 24
+ return "#{dif}d"
+end
+
+# from RWiki
+def rss_recent_modified_class(t)
+ return 'dangling' unless t
+ dif = (Time.now - t).to_i
+ dif = dif / 60
+ return "modified-hour" if dif <= 60
+ dif = dif / 60
+ return "modified-today" if dif <= 24
+ dif = dif / 24
+ return "modified-month" if dif <= 30
+ return "modified-year" if dif <= 365
+ return "modified-old"
+end
+
+def rss_recent_pubDate_to_dc_date(target)
+ if target.respond_to?(:pubDate)
+ class << target
+ alias_method(:dc_date, :pubDate)
+ end
+ end
+end
diff --git a/sample/soap/authheader/authmgr.rb b/sample/soap/authheader/authmgr.rb
new file mode 100644
index 0000000000..a4d3b66c0d
--- /dev/null
+++ b/sample/soap/authheader/authmgr.rb
@@ -0,0 +1,41 @@
+class Authmgr
+ def initialize
+ @users = {
+ 'NaHi' => 'passwd',
+ 'HiNa' => 'wspass'
+ }
+ @sessions = {}
+ end
+
+ def login(userid, passwd)
+ userid and passwd and @users[userid] == passwd
+ end
+
+ # returns userid
+ def auth(sessionid)
+ @sessions[sessionid]
+ end
+
+ def create_session(userid)
+ while true
+ key = create_sessionkey
+ break unless @sessions[key]
+ end
+ @sessions[key] = userid
+ key
+ end
+
+ def get_session(userid)
+ @sessions.index(userid)
+ end
+
+ def destroy_session(sessionkey)
+ @sessions.delete(sessionkey)
+ end
+
+private
+
+ def create_sessionkey
+ Time.now.usec.to_s
+ end
+end
diff --git a/sample/soap/authheader/client.rb b/sample/soap/authheader/client.rb
new file mode 100644
index 0000000000..4055fe63fe
--- /dev/null
+++ b/sample/soap/authheader/client.rb
@@ -0,0 +1,40 @@
+require 'soap/rpc/driver'
+require 'soap/header/simplehandler'
+
+server = ARGV.shift || 'http://localhost:7000/'
+
+class ClientAuthHeaderHandler < SOAP::Header::SimpleHandler
+ MyHeaderName = XSD::QName.new("http://tempuri.org/authHeader", "auth")
+
+ def initialize(userid, passwd)
+ super(MyHeaderName)
+ @sessionid = nil
+ @userid = userid
+ @passwd = passwd
+ @mustunderstand = true
+ end
+
+ def on_simple_outbound
+ if @sessionid
+ { "sessionid" => @sessionid }
+ else
+ { "userid" => @userid, "passwd" => @passwd }
+ end
+ end
+
+ def on_simple_inbound(my_header, mustunderstand)
+ @sessionid = my_header["sessionid"]
+ end
+end
+
+ns = 'http://tempuri.org/authHeaderPort'
+serv = SOAP::RPC::Driver.new(server, ns)
+serv.add_method('deposit', 'amt')
+serv.add_method('withdrawal', 'amt')
+
+serv.headerhandler << ClientAuthHeaderHandler.new('NaHi', 'passwd')
+
+serv.wiredump_dev = STDOUT
+
+p serv.deposit(150)
+p serv.withdrawal(120)
diff --git a/sample/soap/authheader/client2.rb b/sample/soap/authheader/client2.rb
new file mode 100644
index 0000000000..58a7da45ae
--- /dev/null
+++ b/sample/soap/authheader/client2.rb
@@ -0,0 +1,39 @@
+require 'soap/rpc/driver'
+require 'soap/header/simplehandler'
+
+server = ARGV.shift || 'http://localhost:7000/'
+
+class ClientAuthHeaderHandler < SOAP::Header::SimpleHandler
+ MyHeaderName = XSD::QName.new("http://tempuri.org/authHeader", "auth")
+
+ def initialize(userid, passwd)
+ super(MyHeaderName)
+ @sessionid = nil
+ @userid = userid
+ @passwd = passwd
+ end
+
+ def on_simple_outbound
+ if @sessionid
+ { "sessionid" => @sessionid }
+ else
+ { "userid" => @userid, "passwd" => @passwd }
+ end
+ end
+
+ def on_simple_inbound(my_header, mustunderstand)
+ @sessionid = my_header["sessionid"]
+ end
+end
+
+ns = 'http://tempuri.org/authHeaderPort'
+serv = SOAP::RPC::Driver.new(server, ns)
+serv.add_method('deposit', 'amt')
+serv.add_method('withdrawal', 'amt')
+
+serv.headerhandler << ClientAuthHeaderHandler.new('NaHi', 'passwd')
+
+serv.wiredump_dev = STDOUT
+
+p serv.deposit(150)
+p serv.withdrawal(120)
diff --git a/sample/soap/authheader/server.rb b/sample/soap/authheader/server.rb
new file mode 100644
index 0000000000..6b562d02f3
--- /dev/null
+++ b/sample/soap/authheader/server.rb
@@ -0,0 +1,72 @@
+#!/usr/bin/env ruby
+
+require 'soap/rpc/standaloneServer'
+require 'soap/header/simplehandler'
+require 'authmgr'
+
+class AuthHeaderPortServer < SOAP::RPC::StandaloneServer
+ class AuthHeaderService
+ def self.create
+ new
+ end
+
+ def deposit(amt)
+ "deposit #{amt} OK"
+ end
+
+ def withdrawal(amt)
+ "withdrawal #{amt} OK"
+ end
+ end
+
+ Name = 'http://tempuri.org/authHeaderPort'
+ def initialize(*arg)
+ super
+ add_rpc_servant(AuthHeaderService.new, Name)
+ add_rpc_request_headerhandler(ServerAuthHeaderHandler)
+ end
+
+ class ServerAuthHeaderHandler < SOAP::Header::SimpleHandler
+ MyHeaderName = XSD::QName.new("http://tempuri.org/authHeader", "auth")
+
+ @authmgr = Authmgr.new
+ def self.create
+ new(@authmgr)
+ end
+
+ def initialize(authmgr)
+ super(MyHeaderName)
+ @authmgr = authmgr
+ @userid = @sessionid = nil
+ end
+
+ def on_simple_outbound
+ { "sessionid" => @sessionid }
+ end
+
+ def on_simple_inbound(my_header, mu)
+ auth = false
+ userid = my_header["userid"]
+ passwd = my_header["passwd"]
+ if @authmgr.login(userid, passwd)
+ auth = true
+ elsif sessionid = my_header["sessionid"]
+ if userid = @authmgr.auth(sessionid)
+ @authmgr.destroy_session(sessionid)
+ auth = true
+ end
+ end
+ raise RuntimeError.new("authentication failed") unless auth
+ @userid = userid
+ @sessionid = @authmgr.create_session(userid)
+ end
+ end
+end
+
+if $0 == __FILE__
+ svr = AuthHeaderPortServer.new('AuthHeaderPortServer', nil, '0.0.0.0', 7000)
+ trap(:INT) do
+ svr.shutdown
+ end
+ status = svr.start
+end
diff --git a/sample/soap/authheader/server2.rb b/sample/soap/authheader/server2.rb
new file mode 100644
index 0000000000..b0065e3140
--- /dev/null
+++ b/sample/soap/authheader/server2.rb
@@ -0,0 +1,77 @@
+#!/usr/bin/env ruby
+
+require 'soap/rpc/standaloneServer'
+require 'soap/header/simplehandler'
+require 'authmgr'
+
+class AuthHeaderPortServer < SOAP::RPC::StandaloneServer
+ class AuthHeaderService
+ def self.create
+ new
+ end
+
+ def initialize(authmgr)
+ @authmgr = authmgr
+ end
+
+ def login(userid, passwd)
+ if @authmgr.login(userid, passwd)
+ @authmgr.create_session(userid)
+ else
+ raise RuntimeError.new("authentication failed")
+ end
+ end
+
+ def deposit(amt)
+ "deposit #{amt} OK"
+ end
+
+ def withdrawal(amt)
+ "withdrawal #{amt} OK"
+ end
+ end
+
+ Name = 'http://tempuri.org/authHeaderPort'
+ def initialize(*arg)
+ super
+ add_rpc_servant(AuthHeaderService.new, Name)
+ ServerAuthHeaderHandler.init
+ add_rpc_request_headerhandler(ServerAuthHeaderHandler)
+ end
+
+ class ServerAuthHeaderHandler < SOAP::Header::SimpleHandler
+ MyHeaderName = XSD::QName.new("http://tempuri.org/authHeader", "auth")
+
+ def self.create
+ new(@authmgr)
+ end
+
+ def initialize(authmgr)
+ super(MyHeaderName)
+ @authmgr = authmgr
+ @sessionid = nil
+ end
+
+ def on_simple_outbound
+ if @sessionid
+ { "sessionid" => @sessionid }
+ end
+ end
+
+ def on_simple_inbound(my_header, mu)
+ auth = false
+ if sessionid = my_header["sessionid"]
+ if userid = @authmgr.auth(sessionid)
+ @authmgr.destroy_session(sessionid)
+ @session_id = @authmgr.create_session(userid)
+ auth = true
+ end
+ end
+ raise RuntimeError.new("authentication failed") unless auth
+ end
+ end
+end
+
+if $0 == __FILE__
+ status = AuthHeaderPortServer.new('AuthHeaderPortServer', nil, '0.0.0.0', 7000).start
+end
diff --git a/sample/soap/babelfish.rb b/sample/soap/babelfish.rb
new file mode 100644
index 0000000000..eb2421449a
--- /dev/null
+++ b/sample/soap/babelfish.rb
@@ -0,0 +1,16 @@
+#!/usr/bin/env ruby
+
+text = ARGV.shift || 'Hello world.'
+lang = ARGV.shift || 'en_fr'
+
+require 'soap/rpc/driver'
+
+server = 'http://services.xmethods.net/perl/soaplite.cgi'
+InterfaceNS = 'urn:xmethodsBabelFish'
+wireDumpDev = nil # STDERR
+
+drv = SOAP::RPC::Driver.new(server, InterfaceNS)
+drv.wiredump_dev = wireDumpDev
+drv.add_method_with_soapaction('BabelFish', InterfaceNS + "#BabelFish", 'translationmode', 'sourcedata')
+
+p drv.BabelFish(lang, text)
diff --git a/sample/soap/calc/calc.rb b/sample/soap/calc/calc.rb
new file mode 100644
index 0000000000..6bc78803b3
--- /dev/null
+++ b/sample/soap/calc/calc.rb
@@ -0,0 +1,17 @@
+module CalcService
+ def self.add(lhs, rhs)
+ lhs + rhs
+ end
+
+ def self.sub(lhs, rhs)
+ lhs - rhs
+ end
+
+ def self.multi(lhs, rhs)
+ lhs * rhs
+ end
+
+ def self.div(lhs, rhs)
+ lhs / rhs
+ end
+end
diff --git a/sample/soap/calc/calc2.rb b/sample/soap/calc/calc2.rb
new file mode 100644
index 0000000000..e9cf6bbca7
--- /dev/null
+++ b/sample/soap/calc/calc2.rb
@@ -0,0 +1,29 @@
+class CalcService2
+ def initialize(value = 0)
+ @value = value
+ end
+
+ def set(value)
+ @value = value
+ end
+
+ def get
+ @value
+ end
+
+ def +(rhs)
+ @value + rhs
+ end
+
+ def -(rhs)
+ @value - rhs
+ end
+
+ def *(rhs)
+ @value * rhs
+ end
+
+ def /(rhs)
+ @value / rhs
+ end
+end
diff --git a/sample/soap/calc/client.rb b/sample/soap/calc/client.rb
new file mode 100644
index 0000000000..57a4c0ba5b
--- /dev/null
+++ b/sample/soap/calc/client.rb
@@ -0,0 +1,26 @@
+require 'soap/rpc/driver'
+
+server = ARGV.shift || 'http://localhost:7000/'
+# server = 'http://localhost:8808/server.cgi'
+
+calc = SOAP::RPC::Driver.new(server, 'http://tempuri.org/calcService')
+#calc.wiredump_dev = STDERR
+calc.add_method('add', 'lhs', 'rhs')
+calc.add_method('sub', 'lhs', 'rhs')
+calc.add_method('multi', 'lhs', 'rhs')
+calc.add_method('div', 'lhs', 'rhs')
+
+puts 'add: 1 + 2 # => 3'
+puts calc.add(1, 2)
+puts 'sub: 1.1 - 2.2 # => -1.1'
+puts calc.sub(1.1, 2.2)
+puts 'multi: 1.1 * 2.2 # => 2.42'
+puts calc.multi(1.1, 2.2)
+puts 'div: 5 / 2 # => 2'
+puts calc.div(5, 2)
+puts 'div: 5.0 / 2 # => 2.5'
+puts calc.div(5.0, 2)
+puts 'div: 1.1 / 0 # => Infinity'
+puts calc.div(1.1, 0)
+puts 'div: 1 / 0 # => ZeroDivisionError'
+puts calc.div(1, 0)
diff --git a/sample/soap/calc/client2.rb b/sample/soap/calc/client2.rb
new file mode 100644
index 0000000000..2c53f09d42
--- /dev/null
+++ b/sample/soap/calc/client2.rb
@@ -0,0 +1,29 @@
+require 'soap/rpc/driver'
+
+server = ARGV.shift || 'http://localhost:7000/'
+# server = 'http://localhost:8808/server2.cgi'
+
+var = SOAP::RPC::Driver.new( server, 'http://tempuri.org/calcService' )
+var.add_method( 'set', 'newValue' )
+var.add_method( 'get' )
+var.add_method_as( '+', 'add', 'rhs' )
+var.add_method_as( '-', 'sub', 'rhs' )
+var.add_method_as( '*', 'multi', 'rhs' )
+var.add_method_as( '/', 'div', 'rhs' )
+
+puts 'var.set( 1 )'
+puts '# Bare in mind that another client set another value to this service.'
+puts '# This is only a sample for proof of concept.'
+var.set( 1 )
+puts 'var + 2 # => 1 + 2 = 3'
+puts var + 2
+puts 'var - 2.2 # => 1 - 2.2 = -1.2'
+puts var - 2.2
+puts 'var * 2.2 # => 1 * 2.2 = 2.2'
+puts var * 2.2
+puts 'var / 2 # => 1 / 2 = 0'
+puts var / 2
+puts 'var / 2.0 # => 1 / 2.0 = 0.5'
+puts var / 2.0
+puts 'var / 0 # => 1 / 0 => ZeroDivisionError'
+puts var / 0
diff --git a/sample/soap/calc/httpd.rb b/sample/soap/calc/httpd.rb
new file mode 100644
index 0000000000..bebcff96c6
--- /dev/null
+++ b/sample/soap/calc/httpd.rb
@@ -0,0 +1,20 @@
+#!/usr/bin/env ruby
+
+require 'webrick'
+require 'soap/property'
+
+docroot = "."
+port = 8808
+if opt = SOAP::Property.loadproperty("samplehttpd.conf")
+ docroot = opt["docroot"]
+ port = Integer(opt["port"])
+end
+
+s = WEBrick::HTTPServer.new(
+ :BindAddress => "0.0.0.0",
+ :Port => port,
+ :DocumentRoot => docroot,
+ :CGIPathEnv => ENV['PATH']
+)
+trap(:INT){ s.shutdown }
+s.start
diff --git a/sample/soap/calc/samplehttpd.conf b/sample/soap/calc/samplehttpd.conf
new file mode 100644
index 0000000000..85e9995021
--- /dev/null
+++ b/sample/soap/calc/samplehttpd.conf
@@ -0,0 +1,2 @@
+docroot = .
+port = 8808
diff --git a/sample/soap/calc/server.cgi b/sample/soap/calc/server.cgi
new file mode 100644
index 0000000000..c4fa687550
--- /dev/null
+++ b/sample/soap/calc/server.cgi
@@ -0,0 +1,15 @@
+#!/usr/bin/env ruby
+
+require 'soap/rpc/cgistub'
+
+class CalcServer < SOAP::RPC::CGIStub
+ def initialize(*arg)
+ super
+
+ require 'calc'
+ servant = CalcService
+ add_servant(servant, 'http://tempuri.org/calcService')
+ end
+end
+
+status = CalcServer.new('CalcServer', nil).start
diff --git a/sample/soap/calc/server.rb b/sample/soap/calc/server.rb
new file mode 100644
index 0000000000..12a3968b5a
--- /dev/null
+++ b/sample/soap/calc/server.rb
@@ -0,0 +1,17 @@
+#!/usr/bin/env ruby
+
+require 'soap/rpc/standaloneServer'
+require 'calc'
+
+class CalcServer < SOAP::RPC::StandaloneServer
+ def initialize(*arg)
+ super
+
+ servant = CalcService
+ add_servant(servant, 'http://tempuri.org/calcService')
+ end
+end
+
+if $0 == __FILE__
+ status = CalcServer.new('CalcServer', nil, '0.0.0.0', 7000).start
+end
diff --git a/sample/soap/calc/server2.rb b/sample/soap/calc/server2.rb
new file mode 100644
index 0000000000..735721de64
--- /dev/null
+++ b/sample/soap/calc/server2.rb
@@ -0,0 +1,20 @@
+#!/usr/bin/env ruby
+
+require 'soap/rpc/standaloneServer'
+require 'calc2'
+
+class CalcServer2 < SOAP::RPC::StandaloneServer
+ def on_init
+ servant = CalcService2.new
+ add_method(servant, 'set', 'newValue')
+ add_method(servant, 'get')
+ add_method_as(servant, '+', 'add', 'lhs')
+ add_method_as(servant, '-', 'sub', 'lhs')
+ add_method_as(servant, '*', 'multi', 'lhs')
+ add_method_as(servant, '/', 'div', 'lhs')
+ end
+end
+
+if $0 == __FILE__
+ status = CalcServer2.new('CalcServer', 'http://tempuri.org/calcService', '0.0.0.0', 7000).start
+end
diff --git a/sample/soap/digraph.rb b/sample/soap/digraph.rb
new file mode 100644
index 0000000000..54ff302592
--- /dev/null
+++ b/sample/soap/digraph.rb
@@ -0,0 +1,43 @@
+require 'soap/marshal'
+
+class Node; include SOAP::Marshallable
+ attr_reader :first, :second, :str
+
+ def initialize(*init_next)
+ @first = init_next[0]
+ @second = init_next[1]
+ end
+end
+
+n9 = Node.new
+n81 = Node.new(n9)
+n82 = Node.new(n9)
+n7 = Node.new(n81, n82)
+n61 = Node.new(n7)
+n62 = Node.new(n7)
+n5 = Node.new(n61, n62)
+n41 = Node.new(n5)
+n42 = Node.new(n5)
+n3 = Node.new(n41, n42)
+n21 = Node.new(n3)
+n22 = Node.new(n3)
+n1 = Node.new(n21, n22)
+
+File.open("digraph_marshalled_string.soap", "wb") do |f|
+ SOAP::Marshal.dump(n1, f)
+end
+
+marshalledString = File.open("digraph_marshalled_string.soap") { |f| f.read }
+
+puts marshalledString
+
+newnode = SOAP::Marshal.unmarshal(marshalledString)
+
+puts newnode.inspect
+
+p newnode.first.first.__id__
+p newnode.second.first.__id__
+p newnode.first.first.first.first.__id__
+p newnode.second.first.second.first.__id__
+
+File.unlink("digraph_marshalled_string.soap")
diff --git a/sample/soap/exchange/client.rb b/sample/soap/exchange/client.rb
new file mode 100644
index 0000000000..2aa277afef
--- /dev/null
+++ b/sample/soap/exchange/client.rb
@@ -0,0 +1,19 @@
+#!/usr/bin/env ruby
+
+require "soap/rpc/driver"
+
+ExchangeServiceNamespace = 'http://tempuri.org/exchangeService'
+
+server = ARGV.shift || "http://localhost:7000/"
+# server = "http://localhost:8808/server.cgi"
+
+logger = nil
+wiredump_dev = nil
+# logger = Logger.new(STDERR)
+# wiredump_dev = STDERR
+
+drv = SOAP::RPC::Driver.new(server, ExchangeServiceNamespace)
+drv.wiredump_dev = wiredump_dev
+drv.add_method("rate", "country1", "country2")
+
+p drv.rate("USA", "Japan")
diff --git a/sample/soap/exchange/exchange.rb b/sample/soap/exchange/exchange.rb
new file mode 100644
index 0000000000..00f930deb8
--- /dev/null
+++ b/sample/soap/exchange/exchange.rb
@@ -0,0 +1,17 @@
+require 'soap/rpc/driver'
+
+ExchangeServiceNamespace = 'http://tempuri.org/exchangeService'
+
+class Exchange
+ ForeignServer = "http://services.xmethods.net/soap"
+ Namespace = "urn:xmethods-CurrencyExchange"
+
+ def initialize
+ @drv = SOAP::RPC::Driver.new(ForeignServer, Namespace)
+ @drv.add_method("getRate", "country1", "country2")
+ end
+
+ def rate(country1, country2)
+ return @drv.getRate(country1, country2)
+ end
+end
diff --git a/sample/soap/exchange/httpd.rb b/sample/soap/exchange/httpd.rb
new file mode 100644
index 0000000000..bebcff96c6
--- /dev/null
+++ b/sample/soap/exchange/httpd.rb
@@ -0,0 +1,20 @@
+#!/usr/bin/env ruby
+
+require 'webrick'
+require 'soap/property'
+
+docroot = "."
+port = 8808
+if opt = SOAP::Property.loadproperty("samplehttpd.conf")
+ docroot = opt["docroot"]
+ port = Integer(opt["port"])
+end
+
+s = WEBrick::HTTPServer.new(
+ :BindAddress => "0.0.0.0",
+ :Port => port,
+ :DocumentRoot => docroot,
+ :CGIPathEnv => ENV['PATH']
+)
+trap(:INT){ s.shutdown }
+s.start
diff --git a/sample/soap/exchange/samplehttpd.conf b/sample/soap/exchange/samplehttpd.conf
new file mode 100644
index 0000000000..85e9995021
--- /dev/null
+++ b/sample/soap/exchange/samplehttpd.conf
@@ -0,0 +1,2 @@
+docroot = .
+port = 8808
diff --git a/sample/soap/exchange/server.cgi b/sample/soap/exchange/server.cgi
new file mode 100644
index 0000000000..16bc85a042
--- /dev/null
+++ b/sample/soap/exchange/server.cgi
@@ -0,0 +1,14 @@
+#!/usr/local/bin/ruby
+
+require 'soap/rpc/cgistub'
+require 'exchange'
+
+class ExchangeServer < SOAP::RPC::CGIStub
+ def initialize(*arg)
+ super
+ servant = Exchange.new
+ add_servant(servant)
+ end
+end
+
+status = ExchangeServer.new('SampleStructServer', ExchangeServiceNamespace).start
diff --git a/sample/soap/exchange/server.rb b/sample/soap/exchange/server.rb
new file mode 100644
index 0000000000..d510d54a76
--- /dev/null
+++ b/sample/soap/exchange/server.rb
@@ -0,0 +1,16 @@
+#!/usr/bin/env ruby
+
+require 'soap/rpc/standaloneServer'
+require 'exchange'
+
+class ExchangeServer < SOAP::RPC::StandaloneServer
+ def initialize(*arg)
+ super
+ servant = Exchange.new
+ add_servant(servant)
+ end
+end
+
+if $0 == __FILE__
+ status = ExchangeServer.new('SampleStructServer', ExchangeServiceNamespace, '0.0.0.0', 7000).start
+end
diff --git a/sample/soap/helloworld/hw_c.rb b/sample/soap/helloworld/hw_c.rb
new file mode 100644
index 0000000000..253d0a409b
--- /dev/null
+++ b/sample/soap/helloworld/hw_c.rb
@@ -0,0 +1,6 @@
+require 'soap/rpc/driver'
+
+s = SOAP::RPC::Driver.new('http://localhost:2000/', 'urn:hws')
+s.add_method("hello_world", "from")
+
+p s.hello_world(self.to_s)
diff --git a/sample/soap/helloworld/hw_s.rb b/sample/soap/helloworld/hw_s.rb
new file mode 100644
index 0000000000..b917f72fc0
--- /dev/null
+++ b/sample/soap/helloworld/hw_s.rb
@@ -0,0 +1,17 @@
+require 'soap/rpc/standaloneServer'
+
+class HelloWorldServer < SOAP::RPC::StandaloneServer
+ def on_init
+ @log.level = Logger::Severity::DEBUG
+ add_method(self, 'hello_world', 'from')
+ end
+
+ def hello_world(from)
+ "Hello World, from #{ from }"
+ end
+end
+
+if $0 == __FILE__
+ server = HelloWorldServer.new('hws', 'urn:hws', '0.0.0.0', 2000)
+ server.start
+end
diff --git a/sample/soap/icd/IICD.rb b/sample/soap/icd/IICD.rb
new file mode 100644
index 0000000000..3b1fa9b32c
--- /dev/null
+++ b/sample/soap/icd/IICD.rb
@@ -0,0 +1,17 @@
+module IICD
+ # All methods in a single namespace?!
+ InterfaceNS = 'http://www.iwebmethod.net'
+
+ Methods = [
+ ['SearchWord', 'query', 'partial'],
+ ['GetItemById', 'id'],
+ ['EnumWords'],
+ ['FullTextSearch', 'query'],
+ ]
+
+ def IICD.add_method(drv)
+ Methods.each do |method, *param|
+ drv.add_method_with_soapaction(method, InterfaceNS + "/#{ method }", *param )
+ end
+ end
+end
diff --git a/sample/soap/icd/icd.rb b/sample/soap/icd/icd.rb
new file mode 100644
index 0000000000..6e1e51c996
--- /dev/null
+++ b/sample/soap/icd/icd.rb
@@ -0,0 +1,46 @@
+#!/usr/bin/env ruby
+
+$KCODE = 'SJIS'
+
+require 'soap/rpc/driver'
+require 'IICD'; include IICD
+
+server = 'http://www.iwebmethod.net/icd1.0/icd.asmx'
+wiredump_dev = nil # STDERR
+
+icd = SOAP::RPC::Driver.new(server, IICD::InterfaceNS)
+icd.wiredump_dev = wiredump_dev
+icd.default_encodingstyle = SOAP::EncodingStyle::ASPDotNetHandler::Namespace
+IICD::add_method(icd)
+
+puts "ƒL[ƒ[ƒh: 'microsoft'‚ÅŒ©o‚µŒŸõ"
+result = icd.SearchWord('microsoft', true)
+
+id = nil
+result.WORD.each do |word|
+ puts "Title: " << word.title
+ puts "Id: " << word.id
+ puts "English: " << word.english
+ puts "Japanese: " << word.japanese
+ puts "----"
+ id = word.id
+end
+
+item = icd.GetItemById(id)
+puts
+puts
+puts "Title: " << item.word.title
+puts "ˆÓ–¡: " << item.meaning
+
+#p icd.EnumWords
+
+puts
+puts
+puts "ƒL[ƒ[ƒh: 'IBM'‚Å‘S•¶ŒŸõ"
+icd.FullTextSearch("IBM").WORD.each do |word|
+ puts "Title: " << word.title
+ puts "Id: " << word.id
+ puts "English: " << word.english
+ puts "Japanese: " << word.japanese
+ puts "----"
+end
diff --git a/sample/soap/raa/iRAA.rb b/sample/soap/raa/iRAA.rb
new file mode 100644
index 0000000000..2b188fb887
--- /dev/null
+++ b/sample/soap/raa/iRAA.rb
@@ -0,0 +1,154 @@
+require 'soap/mapping'
+
+
+module RAA; extend SOAP
+
+
+InterfaceNS = "http://www.ruby-lang.org/xmlns/soap/interface/RAA/0.0.2/"
+MappingRegistry = SOAP::Mapping::Registry.new
+
+Methods = [
+ ['getAllListings', ['retval', 'return']],
+ ['getProductTree', ['retval', 'return']],
+ ['getInfoFromCategory', ['in', 'category'], [ 'retval', 'return']],
+ ['getModifiedInfoSince', ['in', 'time'], [ 'retval', 'return']],
+ ['getInfoFromName', ['in', 'name'], ['retval', 'return']],
+]
+
+
+class Category
+ include SOAP::Marshallable
+
+ @@schema_type = 'Category'
+ @@schema_ns = InterfaceNS
+
+ attr_reader :major, :minor
+
+ def initialize(major, minor = nil)
+ @major = major
+ @minor = minor
+ end
+
+ def to_s
+ "#{ @major }/#{ @minor }"
+ end
+
+ def ==(rhs)
+ if @major != rhs.major
+ false
+ elsif !@minor or !rhs.minor
+ true
+ else
+ @minor == rhs.minor
+ end
+ end
+end
+
+MappingRegistry.set(
+ ::RAA::Category,
+ ::SOAP::SOAPStruct,
+ ::SOAP::Mapping::Registry::TypedStructFactory,
+ { :type => XSD::QName.new(InterfaceNS, "Category") }
+)
+
+class Product
+ include SOAP::Marshallable
+
+ @@schema_type = 'Product'
+ @@schema_ns = InterfaceNS
+
+ attr_reader :id, :name
+ attr_accessor :short_description, :version, :status, :homepage, :download, :license, :description
+
+ def initialize(name, short_description = nil, version = nil, status = nil, homepage = nil, download = nil, license = nil, description = nil)
+ @name = name
+ @short_description = short_description
+ @version = version
+ @status = status
+ @homepage = homepage
+ @download = download
+ @license = license
+ @description = description
+ end
+end
+
+MappingRegistry.set(
+ ::RAA::Product,
+ ::SOAP::SOAPStruct,
+ ::SOAP::Mapping::Registry::TypedStructFactory,
+ { :type => XSD::QName.new(InterfaceNS, "Product") }
+)
+
+class Owner
+ include SOAP::Marshallable
+
+ @@schema_type = 'Owner'
+ @@schema_ns = InterfaceNS
+
+ attr_reader :id
+ attr_accessor :email, :name
+
+ def initialize(email, name)
+ @email = email
+ @name = name
+ @id = "#{ @email }-#{ @name }"
+ end
+end
+
+MappingRegistry.set(
+ ::RAA::Owner,
+ ::SOAP::SOAPStruct,
+ ::SOAP::Mapping::Registry::TypedStructFactory,
+ { :type => XSD::QName.new(InterfaceNS, "Owner") }
+)
+
+class Info
+ include SOAP::Marshallable
+
+ @@schema_type = 'Info'
+ @@schema_ns = InterfaceNS
+
+ attr_accessor :category, :product, :owner, :updated, :created
+
+ def initialize(category = nil, product = nil, owner = nil, updated = nil, created = nil)
+ @category = category
+ @product = product
+ @owner = owner
+ @updated = updated
+ @created = created
+ end
+
+ def <=>(rhs)
+ @updated <=> rhs.updated
+ end
+
+ def eql?(rhs)
+ @product.name == rhs.product.name
+ end
+end
+
+MappingRegistry.set(
+ ::RAA::Info,
+ ::SOAP::SOAPStruct,
+ ::SOAP::Mapping::Registry::TypedStructFactory,
+ { :type => XSD::QName.new(InterfaceNS, "Info") }
+)
+
+class StringArray < Array; end
+MappingRegistry.set(
+ ::RAA::StringArray,
+ ::SOAP::SOAPArray,
+ ::SOAP::Mapping::Registry::TypedArrayFactory,
+ { :type => XSD::XSDString::Type }
+)
+
+class InfoArray < Array; end
+MappingRegistry.set(
+ ::RAA::InfoArray,
+ ::SOAP::SOAPArray,
+ ::SOAP::Mapping::Registry::TypedArrayFactory,
+ { :type => XSD::QName.new(InterfaceNS, 'Info') }
+)
+
+
+end
diff --git a/sample/soap/raa/soap4r.rb b/sample/soap/raa/soap4r.rb
new file mode 100644
index 0000000000..b93d1e7dbe
--- /dev/null
+++ b/sample/soap/raa/soap4r.rb
@@ -0,0 +1,30 @@
+#!/usr/bin/env ruby
+
+require 'iRAA'
+require 'soap/rpc/driver'
+
+
+server = ARGV.shift || 'http://raa.ruby-lang.org/soap/1.0.2/'
+
+raa = SOAP::RPC::Driver.new(server, RAA::InterfaceNS)
+raa.mapping_registry = RAA::MappingRegistry
+RAA::Methods.each do |name, *params|
+ raa.add_method(name, params)
+end
+# raa.wiredump_dev = STDOUT
+
+p raa.getAllListings().sort
+
+p raa.getProductTree()
+
+p raa.getInfoFromCategory(RAA::Category.new("Library", "XML"))
+
+t = Time.at(Time.now.to_i - 24 * 3600)
+p raa.getModifiedInfoSince(t)
+
+p raa.getModifiedInfoSince(DateTime.new(t.year, t.mon, t.mday, t.hour, t.min, t.sec))
+
+o = raa.getInfoFromName("SOAP4R")
+p o.class
+p o.owner.name
+p o
diff --git a/sample/soap/raa2.4/raa.rb b/sample/soap/raa2.4/raa.rb
new file mode 100644
index 0000000000..9b4c4e41aa
--- /dev/null
+++ b/sample/soap/raa2.4/raa.rb
@@ -0,0 +1,332 @@
+# http://www.ruby-lang.org/xmlns/soap/type/RAA/0.0.3/
+class Gem
+ @@schema_type = "Gem"
+ @@schema_ns = "http://www.ruby-lang.org/xmlns/soap/type/RAA/0.0.3/"
+
+ def id
+ @id
+ end
+
+ def id=(value)
+ @id = value
+ end
+
+ def category
+ @category
+ end
+
+ def category=(value)
+ @category = value
+ end
+
+ def owner
+ @owner
+ end
+
+ def owner=(value)
+ @owner = value
+ end
+
+ def project
+ @project
+ end
+
+ def project=(value)
+ @project = value
+ end
+
+ def updated
+ @updated
+ end
+
+ def updated=(value)
+ @updated = value
+ end
+
+ def created
+ @created
+ end
+
+ def created=(value)
+ @created = value
+ end
+
+ def initialize(id = nil,
+ category = nil,
+ owner = nil,
+ project = nil,
+ updated = nil,
+ created = nil)
+ @id = id
+ @category = category
+ @owner = owner
+ @project = project
+ @updated = updated
+ @created = created
+ end
+end
+
+# http://www.ruby-lang.org/xmlns/soap/type/RAA/0.0.3/
+class Category
+ @@schema_type = "Category"
+ @@schema_ns = "http://www.ruby-lang.org/xmlns/soap/type/RAA/0.0.3/"
+
+ def major
+ @major
+ end
+
+ def major=(value)
+ @major = value
+ end
+
+ def minor
+ @minor
+ end
+
+ def minor=(value)
+ @minor = value
+ end
+
+ def initialize(major = nil,
+ minor = nil)
+ @major = major
+ @minor = minor
+ end
+end
+
+# http://www.ruby-lang.org/xmlns/soap/type/RAA/0.0.3/
+class Owner
+ @@schema_type = "Owner"
+ @@schema_ns = "http://www.ruby-lang.org/xmlns/soap/type/RAA/0.0.3/"
+
+ def id
+ @id
+ end
+
+ def id=(value)
+ @id = value
+ end
+
+ def email
+ @email
+ end
+
+ def email=(value)
+ @email = value
+ end
+
+ def name
+ @name
+ end
+
+ def name=(value)
+ @name = value
+ end
+
+ def initialize(id = nil,
+ email = nil,
+ name = nil)
+ @id = id
+ @email = email
+ @name = name
+ end
+end
+
+# http://www.ruby-lang.org/xmlns/soap/type/RAA/0.0.3/
+class Project
+ @@schema_type = "Project"
+ @@schema_ns = "http://www.ruby-lang.org/xmlns/soap/type/RAA/0.0.3/"
+
+ def name
+ @name
+ end
+
+ def name=(value)
+ @name = value
+ end
+
+ def short_description
+ @short_description
+ end
+
+ def short_description=(value)
+ @short_description = value
+ end
+
+ def version
+ @version
+ end
+
+ def version=(value)
+ @version = value
+ end
+
+ def status
+ @status
+ end
+
+ def status=(value)
+ @status = value
+ end
+
+ def url
+ @url
+ end
+
+ def url=(value)
+ @url = value
+ end
+
+ def download
+ @download
+ end
+
+ def download=(value)
+ @download = value
+ end
+
+ def license
+ @license
+ end
+
+ def license=(value)
+ @license = value
+ end
+
+ def description
+ @description
+ end
+
+ def description=(value)
+ @description = value
+ end
+
+ def updated
+ @updated
+ end
+
+ def updated=(value)
+ @updated = value
+ end
+
+ def history
+ @history
+ end
+
+ def history=(value)
+ @history = value
+ end
+
+ def dependency
+ @dependency
+ end
+
+ def dependency=(value)
+ @dependency = value
+ end
+
+ def initialize(name = nil,
+ short_description = nil,
+ version = nil,
+ status = nil,
+ url = nil,
+ download = nil,
+ license = nil,
+ description = nil,
+ updated = nil,
+ history = nil,
+ dependency = nil)
+ @name = name
+ @short_description = short_description
+ @version = version
+ @status = status
+ @url = url
+ @download = download
+ @license = license
+ @description = description
+ @updated = updated
+ @history = history
+ @dependency = dependency
+ end
+end
+
+# http://www.ruby-lang.org/xmlns/soap/type/RAA/0.0.3/
+class ProjectDependency
+ @@schema_type = "ProjectDependency"
+ @@schema_ns = "http://www.ruby-lang.org/xmlns/soap/type/RAA/0.0.3/"
+
+ def project
+ @project
+ end
+
+ def project=(value)
+ @project = value
+ end
+
+ def version
+ @version
+ end
+
+ def version=(value)
+ @version = value
+ end
+
+ def description
+ @description
+ end
+
+ def description=(value)
+ @description = value
+ end
+
+ def initialize(project = nil,
+ version = nil,
+ description = nil)
+ @project = project
+ @version = version
+ @description = description
+ end
+end
+
+# http://www.ruby-lang.org/xmlns/soap/type/RAA/0.0.3/
+class GemArray < Array
+ # Contents type should be dumped here...
+ @@schema_type = "GemArray"
+ @@schema_ns = "http://www.ruby-lang.org/xmlns/soap/type/RAA/0.0.3/"
+end
+
+# http://www.ruby-lang.org/xmlns/soap/type/RAA/0.0.3/
+class OwnerArray < Array
+ # Contents type should be dumped here...
+ @@schema_type = "OwnerArray"
+ @@schema_ns = "http://www.ruby-lang.org/xmlns/soap/type/RAA/0.0.3/"
+end
+
+# http://www.ruby-lang.org/xmlns/soap/type/RAA/0.0.3/
+class ProjectArray < Array
+ # Contents type should be dumped here...
+ @@schema_type = "ProjectArray"
+ @@schema_ns = "http://www.ruby-lang.org/xmlns/soap/type/RAA/0.0.3/"
+end
+
+# http://www.ruby-lang.org/xmlns/soap/type/RAA/0.0.3/
+class ProjectDependencyArray < Array
+ # Contents type should be dumped here...
+ @@schema_type = "ProjectDependencyArray"
+ @@schema_ns = "http://www.ruby-lang.org/xmlns/soap/type/RAA/0.0.3/"
+end
+
+# http://www.ruby-lang.org/xmlns/soap/type/RAA/0.0.3/
+class StringArray < Array
+ # Contents type should be dumped here...
+ @@schema_type = "StringArray"
+ @@schema_ns = "http://www.ruby-lang.org/xmlns/soap/type/RAA/0.0.3/"
+end
+
+# http://xml.apache.org/xml-soap
+class Map < Array
+ # Contents type should be dumped here...
+ @@schema_type = "Map"
+ @@schema_ns = "http://xml.apache.org/xml-soap"
+end
+
diff --git a/sample/soap/raa2.4/raaDriver.rb b/sample/soap/raa2.4/raaDriver.rb
new file mode 100644
index 0000000000..10d0ba257e
--- /dev/null
+++ b/sample/soap/raa2.4/raaDriver.rb
@@ -0,0 +1,255 @@
+require 'raa.rb'
+
+require 'soap/rpc/driver'
+
+class RaaServicePortType < SOAP::RPC::Driver
+ TargetNamespace = "http://www.ruby-lang.org/xmlns/soap/interface/RAA/0.0.4/"
+ MappingRegistry = ::SOAP::Mapping::Registry.new
+
+ MappingRegistry.set(
+ Gem,
+ ::SOAP::SOAPStruct,
+ ::SOAP::Mapping::Registry::TypedStructFactory,
+ { :type => XSD::QName.new("http://www.ruby-lang.org/xmlns/soap/type/RAA/0.0.3/", "Gem") }
+ )
+ MappingRegistry.set(
+ Category,
+ ::SOAP::SOAPStruct,
+ ::SOAP::Mapping::Registry::TypedStructFactory,
+ { :type => XSD::QName.new("http://www.ruby-lang.org/xmlns/soap/type/RAA/0.0.3/", "Category") }
+ )
+ MappingRegistry.set(
+ Owner,
+ ::SOAP::SOAPStruct,
+ ::SOAP::Mapping::Registry::TypedStructFactory,
+ { :type => XSD::QName.new("http://www.ruby-lang.org/xmlns/soap/type/RAA/0.0.3/", "Owner") }
+ )
+ MappingRegistry.set(
+ Project,
+ ::SOAP::SOAPStruct,
+ ::SOAP::Mapping::Registry::TypedStructFactory,
+ { :type => XSD::QName.new("http://www.ruby-lang.org/xmlns/soap/type/RAA/0.0.3/", "Project") }
+ )
+ MappingRegistry.set(
+ ProjectArray,
+ ::SOAP::SOAPArray,
+ ::SOAP::Mapping::Registry::TypedArrayFactory,
+ { :type => XSD::QName.new("http://www.ruby-lang.org/xmlns/soap/type/RAA/0.0.3/", "Project") }
+ )
+ MappingRegistry.set(
+ ProjectDependencyArray,
+ ::SOAP::SOAPArray,
+ ::SOAP::Mapping::Registry::TypedArrayFactory,
+ { :type => XSD::QName.new("http://www.ruby-lang.org/xmlns/soap/type/RAA/0.0.3/", "ProjectDependency") }
+ )
+ MappingRegistry.set(
+ StringArray,
+ ::SOAP::SOAPArray,
+ ::SOAP::Mapping::Registry::TypedArrayFactory,
+ { :type => XSD::QName.new("http://www.w3.org/2001/XMLSchema", "string") }
+ )
+ MappingRegistry.set(
+ Map,
+ ::SOAP::SOAPArray,
+ ::SOAP::Mapping::Registry::TypedArrayFactory,
+ { :type => XSD::QName.new("http://www.w3.org/2001/XMLSchema", "anyType") }
+ )
+ MappingRegistry.set(
+ OwnerArray,
+ ::SOAP::SOAPArray,
+ ::SOAP::Mapping::Registry::TypedArrayFactory,
+ { :type => XSD::QName.new("http://www.ruby-lang.org/xmlns/soap/type/RAA/0.0.3/", "Owner") }
+ )
+ MappingRegistry.set(
+ ProjectDependency,
+ ::SOAP::SOAPStruct,
+ ::SOAP::Mapping::Registry::TypedStructFactory,
+ { :type => XSD::QName.new("http://www.ruby-lang.org/xmlns/soap/type/RAA/0.0.3/", "ProjectDependency") }
+ )
+ Methods = [
+ ["gem", "gem",
+ [
+ ["in", "name", [SOAP::SOAPString]],
+ ["retval", "return", [::SOAP::SOAPStruct, "http://www.ruby-lang.org/xmlns/soap/type/RAA/0.0.3/", "Gem"]]
+ ],
+ "", "http://www.ruby-lang.org/xmlns/soap/interface/RAA/0.0.4/"
+ ],
+ ["dependents", "dependents",
+ [
+ ["in", "name", [SOAP::SOAPString]],
+ ["in", "version", [SOAP::SOAPString]],
+ ["retval", "return", [::SOAP::SOAPArray, "http://www.ruby-lang.org/xmlns/soap/type/RAA/0.0.3/", "ProjectDependency"]]
+ ],
+ "", "http://www.ruby-lang.org/xmlns/soap/interface/RAA/0.0.4/"
+ ],
+ ["names", "names",
+ [
+ ["retval", "return", [::SOAP::SOAPArray, "http://www.w3.org/2001/XMLSchema", "string"]]
+ ],
+ "", "http://www.ruby-lang.org/xmlns/soap/interface/RAA/0.0.4/"
+ ],
+ ["size", "size",
+ [
+ ["retval", "return", [SOAP::SOAPInt]]
+ ],
+ "", "http://www.ruby-lang.org/xmlns/soap/interface/RAA/0.0.4/"
+ ],
+ ["list_by_category", "list_by_category",
+ [
+ ["in", "major", [SOAP::SOAPString]],
+ ["in", "minor", [SOAP::SOAPString]],
+ ["retval", "return", [::SOAP::SOAPArray, "http://www.w3.org/2001/XMLSchema", "string"]]
+ ],
+ "", "http://www.ruby-lang.org/xmlns/soap/interface/RAA/0.0.4/"
+ ],
+ ["tree_by_category", "tree_by_category",
+ [
+ ["retval", "return", [::SOAP::SOAPArray, "http://www.w3.org/2001/XMLSchema", "anyType"]]
+ ],
+ "", "http://www.ruby-lang.org/xmlns/soap/interface/RAA/0.0.4/"
+ ],
+ ["list_recent_updated", "list_recent_updated",
+ [
+ ["in", "idx", [SOAP::SOAPInt]],
+ ["retval", "return", [::SOAP::SOAPArray, "http://www.w3.org/2001/XMLSchema", "string"]]
+ ],
+ "", "http://www.ruby-lang.org/xmlns/soap/interface/RAA/0.0.4/"
+ ],
+ ["list_recent_created", "list_recent_created",
+ [
+ ["in", "idx", [SOAP::SOAPInt]],
+ ["retval", "return", [::SOAP::SOAPArray, "http://www.w3.org/2001/XMLSchema", "string"]]
+ ],
+ "", "http://www.ruby-lang.org/xmlns/soap/interface/RAA/0.0.4/"
+ ],
+ ["list_updated_since", "list_updated_since",
+ [
+ ["in", "date", [SOAP::SOAPDateTime]],
+ ["in", "idx", [SOAP::SOAPInt]],
+ ["retval", "return", [::SOAP::SOAPArray, "http://www.w3.org/2001/XMLSchema", "string"]]
+ ],
+ "", "http://www.ruby-lang.org/xmlns/soap/interface/RAA/0.0.4/"
+ ],
+ ["list_created_since", "list_created_since",
+ [
+ ["in", "date", [SOAP::SOAPDateTime]],
+ ["in", "idx", [SOAP::SOAPInt]],
+ ["retval", "return", [::SOAP::SOAPArray, "http://www.w3.org/2001/XMLSchema", "string"]]
+ ],
+ "", "http://www.ruby-lang.org/xmlns/soap/interface/RAA/0.0.4/"
+ ],
+ ["list_by_owner", "list_by_owner",
+ [
+ ["in", "owner_id", [SOAP::SOAPInt]],
+ ["retval", "return", [::SOAP::SOAPArray, "http://www.w3.org/2001/XMLSchema", "string"]]
+ ],
+ "", "http://www.ruby-lang.org/xmlns/soap/interface/RAA/0.0.4/"
+ ],
+ ["search_name", "search_name",
+ [
+ ["in", "substring", [SOAP::SOAPString]],
+ ["in", "idx", [SOAP::SOAPInt]],
+ ["retval", "return", [::SOAP::SOAPArray, "http://www.w3.org/2001/XMLSchema", "string"]]
+ ],
+ "", "http://www.ruby-lang.org/xmlns/soap/interface/RAA/0.0.4/"
+ ],
+ ["search_short_description", "search_short_description",
+ [
+ ["in", "substring", [SOAP::SOAPString]],
+ ["in", "idx", [SOAP::SOAPInt]],
+ ["retval", "return", [::SOAP::SOAPArray, "http://www.w3.org/2001/XMLSchema", "string"]]
+ ],
+ "", "http://www.ruby-lang.org/xmlns/soap/interface/RAA/0.0.4/"
+ ],
+ ["search_owner", "search_owner",
+ [
+ ["in", "substring", [SOAP::SOAPString]],
+ ["in", "idx", [SOAP::SOAPInt]],
+ ["retval", "return", [::SOAP::SOAPArray, "http://www.w3.org/2001/XMLSchema", "string"]]
+ ],
+ "", "http://www.ruby-lang.org/xmlns/soap/interface/RAA/0.0.4/"
+ ],
+ ["search_version", "search_version",
+ [
+ ["in", "substring", [SOAP::SOAPString]],
+ ["in", "idx", [SOAP::SOAPInt]],
+ ["retval", "return", [::SOAP::SOAPArray, "http://www.w3.org/2001/XMLSchema", "string"]]
+ ],
+ "", "http://www.ruby-lang.org/xmlns/soap/interface/RAA/0.0.4/"
+ ],
+ ["search_status", "search_status",
+ [
+ ["in", "substring", [SOAP::SOAPString]],
+ ["in", "idx", [SOAP::SOAPInt]],
+ ["retval", "return", [::SOAP::SOAPArray, "http://www.w3.org/2001/XMLSchema", "string"]]
+ ],
+ "", "http://www.ruby-lang.org/xmlns/soap/interface/RAA/0.0.4/"
+ ],
+ ["search_description", "search_description",
+ [
+ ["in", "substring", [SOAP::SOAPString]],
+ ["in", "idx", [SOAP::SOAPInt]],
+ ["retval", "return", [::SOAP::SOAPArray, "http://www.w3.org/2001/XMLSchema", "string"]]
+ ],
+ "", "http://www.ruby-lang.org/xmlns/soap/interface/RAA/0.0.4/"
+ ],
+ ["search", "search",
+ [
+ ["in", "substring", [SOAP::SOAPString]],
+ ["retval", "return", [::SOAP::SOAPArray, "http://www.w3.org/2001/XMLSchema", "anyType"]]
+ ],
+ "", "http://www.ruby-lang.org/xmlns/soap/interface/RAA/0.0.4/"
+ ],
+ ["owner", "owner",
+ [
+ ["in", "owner_id", [SOAP::SOAPInt]],
+ ["retval", "return", [::SOAP::SOAPStruct, "http://www.ruby-lang.org/xmlns/soap/type/RAA/0.0.3/", "Owner"]]
+ ],
+ "", "http://www.ruby-lang.org/xmlns/soap/interface/RAA/0.0.4/"
+ ],
+ ["list_owner", "list_owner",
+ [
+ ["in", "idx", [SOAP::SOAPInt]],
+ ["retval", "return", [::SOAP::SOAPArray, "http://www.ruby-lang.org/xmlns/soap/type/RAA/0.0.3/", "Owner"]]
+ ],
+ "", "http://www.ruby-lang.org/xmlns/soap/interface/RAA/0.0.4/"
+ ],
+ ["update", "update",
+ [
+ ["in", "name", [SOAP::SOAPString]],
+ ["in", "pass", [SOAP::SOAPString]],
+ ["in", "gem", [::SOAP::SOAPStruct, "http://www.ruby-lang.org/xmlns/soap/type/RAA/0.0.3/", "Gem"]],
+ ["retval", "return", [::SOAP::SOAPStruct, "http://www.ruby-lang.org/xmlns/soap/type/RAA/0.0.3/", "Gem"]]
+ ],
+ "", "http://www.ruby-lang.org/xmlns/soap/interface/RAA/0.0.4/"
+ ],
+ ["update_pass", "update_pass",
+ [
+ ["in", "name", [SOAP::SOAPString]],
+ ["in", "oldpass", [SOAP::SOAPString]],
+ ["in", "newpass", [SOAP::SOAPString]]
+ ],
+ "", "http://www.ruby-lang.org/xmlns/soap/interface/RAA/0.0.4/"
+ ]
+ ]
+
+ DefaultEndpointUrl = "http://raa.ruby-lang.org/soapsrv"
+
+ def initialize(endpoint_url = nil)
+ endpoint_url ||= DefaultEndpointUrl
+ super(endpoint_url, nil)
+ self.mapping_registry = MappingRegistry
+ init_methods
+ end
+
+private
+
+ def init_methods
+ Methods.each do |name_as, name, params, soapaction, namespace|
+ qname = XSD::QName.new(namespace, name_as)
+ @proxy.add_method(qname, soapaction, name, params)
+ add_rpc_method_interface(name, params)
+ end
+ end
+end
+
diff --git a/sample/soap/raa2.4/raaServiceClient.rb b/sample/soap/raa2.4/raaServiceClient.rb
new file mode 100644
index 0000000000..a59815ba72
--- /dev/null
+++ b/sample/soap/raa2.4/raaServiceClient.rb
@@ -0,0 +1,354 @@
+#!/usr/bin/env ruby
+require 'raaDriver.rb'
+
+endpoint_url = ARGV.shift
+obj = RaaServicePortType.new(endpoint_url)
+
+# Uncomment the below line to see SOAP wiredumps.
+# obj.wiredump_dev = STDERR
+
+# SYNOPSIS
+# gem(name)
+#
+# ARGS
+# name - {http://www.w3.org/2001/XMLSchema}string
+#
+# RETURNS
+# return Gem - {http://www.ruby-lang.org/xmlns/soap/type/RAA/0.0.3/}Gem
+#
+# RAISES
+# (undefined)
+#
+name = nil
+puts obj.gem(name)
+
+# SYNOPSIS
+# dependents(name, version)
+#
+# ARGS
+# name - {http://www.w3.org/2001/XMLSchema}string
+# version - {http://www.w3.org/2001/XMLSchema}string
+#
+# RETURNS
+# return ProjectDependencyArray - {http://www.ruby-lang.org/xmlns/soap/type/RAA/0.0.3/}ProjectDependencyArray
+#
+# RAISES
+# (undefined)
+#
+name = version = nil
+puts obj.dependents(name, version)
+
+# SYNOPSIS
+# names
+#
+# ARGS
+# N/A
+#
+# RETURNS
+# return StringArray - {http://www.ruby-lang.org/xmlns/soap/type/RAA/0.0.3/}StringArray
+#
+# RAISES
+# (undefined)
+#
+
+puts obj.names
+
+# SYNOPSIS
+# size
+#
+# ARGS
+# N/A
+#
+# RETURNS
+# return - {http://www.w3.org/2001/XMLSchema}int
+#
+# RAISES
+# (undefined)
+#
+
+puts obj.size
+
+# SYNOPSIS
+# list_by_category(major, minor)
+#
+# ARGS
+# major - {http://www.w3.org/2001/XMLSchema}string
+# minor - {http://www.w3.org/2001/XMLSchema}string
+#
+# RETURNS
+# return StringArray - {http://www.ruby-lang.org/xmlns/soap/type/RAA/0.0.3/}StringArray
+#
+# RAISES
+# (undefined)
+#
+major = minor = nil
+puts obj.list_by_category(major, minor)
+
+# SYNOPSIS
+# tree_by_category
+#
+# ARGS
+# N/A
+#
+# RETURNS
+# return Map - {http://xml.apache.org/xml-soap}Map
+#
+# RAISES
+# (undefined)
+#
+
+puts obj.tree_by_category
+
+# SYNOPSIS
+# list_recent_updated(idx)
+#
+# ARGS
+# idx - {http://www.w3.org/2001/XMLSchema}int
+#
+# RETURNS
+# return StringArray - {http://www.ruby-lang.org/xmlns/soap/type/RAA/0.0.3/}StringArray
+#
+# RAISES
+# (undefined)
+#
+idx = nil
+puts obj.list_recent_updated(idx)
+
+# SYNOPSIS
+# list_recent_created(idx)
+#
+# ARGS
+# idx - {http://www.w3.org/2001/XMLSchema}int
+#
+# RETURNS
+# return StringArray - {http://www.ruby-lang.org/xmlns/soap/type/RAA/0.0.3/}StringArray
+#
+# RAISES
+# (undefined)
+#
+idx = nil
+puts obj.list_recent_created(idx)
+
+# SYNOPSIS
+# list_updated_since(date, idx)
+#
+# ARGS
+# date - {http://www.w3.org/2001/XMLSchema}dateTime
+# idx - {http://www.w3.org/2001/XMLSchema}int
+#
+# RETURNS
+# return StringArray - {http://www.ruby-lang.org/xmlns/soap/type/RAA/0.0.3/}StringArray
+#
+# RAISES
+# (undefined)
+#
+date = idx = nil
+puts obj.list_updated_since(date, idx)
+
+# SYNOPSIS
+# list_created_since(date, idx)
+#
+# ARGS
+# date - {http://www.w3.org/2001/XMLSchema}dateTime
+# idx - {http://www.w3.org/2001/XMLSchema}int
+#
+# RETURNS
+# return StringArray - {http://www.ruby-lang.org/xmlns/soap/type/RAA/0.0.3/}StringArray
+#
+# RAISES
+# (undefined)
+#
+date = idx = nil
+puts obj.list_created_since(date, idx)
+
+# SYNOPSIS
+# list_by_owner(owner_id)
+#
+# ARGS
+# owner_id - {http://www.w3.org/2001/XMLSchema}int
+#
+# RETURNS
+# return StringArray - {http://www.ruby-lang.org/xmlns/soap/type/RAA/0.0.3/}StringArray
+#
+# RAISES
+# (undefined)
+#
+owner_id = nil
+puts obj.list_by_owner(owner_id)
+
+# SYNOPSIS
+# search_name(substring, idx)
+#
+# ARGS
+# substring - {http://www.w3.org/2001/XMLSchema}string
+# idx - {http://www.w3.org/2001/XMLSchema}int
+#
+# RETURNS
+# return StringArray - {http://www.ruby-lang.org/xmlns/soap/type/RAA/0.0.3/}StringArray
+#
+# RAISES
+# (undefined)
+#
+substring = idx = nil
+puts obj.search_name(substring, idx)
+
+# SYNOPSIS
+# search_short_description(substring, idx)
+#
+# ARGS
+# substring - {http://www.w3.org/2001/XMLSchema}string
+# idx - {http://www.w3.org/2001/XMLSchema}int
+#
+# RETURNS
+# return StringArray - {http://www.ruby-lang.org/xmlns/soap/type/RAA/0.0.3/}StringArray
+#
+# RAISES
+# (undefined)
+#
+substring = idx = nil
+puts obj.search_short_description(substring, idx)
+
+# SYNOPSIS
+# search_owner(substring, idx)
+#
+# ARGS
+# substring - {http://www.w3.org/2001/XMLSchema}string
+# idx - {http://www.w3.org/2001/XMLSchema}int
+#
+# RETURNS
+# return StringArray - {http://www.ruby-lang.org/xmlns/soap/type/RAA/0.0.3/}StringArray
+#
+# RAISES
+# (undefined)
+#
+substring = idx = nil
+puts obj.search_owner(substring, idx)
+
+# SYNOPSIS
+# search_version(substring, idx)
+#
+# ARGS
+# substring - {http://www.w3.org/2001/XMLSchema}string
+# idx - {http://www.w3.org/2001/XMLSchema}int
+#
+# RETURNS
+# return StringArray - {http://www.ruby-lang.org/xmlns/soap/type/RAA/0.0.3/}StringArray
+#
+# RAISES
+# (undefined)
+#
+substring = idx = nil
+puts obj.search_version(substring, idx)
+
+# SYNOPSIS
+# search_status(substring, idx)
+#
+# ARGS
+# substring - {http://www.w3.org/2001/XMLSchema}string
+# idx - {http://www.w3.org/2001/XMLSchema}int
+#
+# RETURNS
+# return StringArray - {http://www.ruby-lang.org/xmlns/soap/type/RAA/0.0.3/}StringArray
+#
+# RAISES
+# (undefined)
+#
+substring = idx = nil
+puts obj.search_status(substring, idx)
+
+# SYNOPSIS
+# search_description(substring, idx)
+#
+# ARGS
+# substring - {http://www.w3.org/2001/XMLSchema}string
+# idx - {http://www.w3.org/2001/XMLSchema}int
+#
+# RETURNS
+# return StringArray - {http://www.ruby-lang.org/xmlns/soap/type/RAA/0.0.3/}StringArray
+#
+# RAISES
+# (undefined)
+#
+substring = idx = nil
+puts obj.search_description(substring, idx)
+
+# SYNOPSIS
+# search(substring)
+#
+# ARGS
+# substring - {http://www.w3.org/2001/XMLSchema}string
+#
+# RETURNS
+# return Map - {http://xml.apache.org/xml-soap}Map
+#
+# RAISES
+# (undefined)
+#
+substring = nil
+puts obj.search(substring)
+
+# SYNOPSIS
+# owner(owner_id)
+#
+# ARGS
+# owner_id - {http://www.w3.org/2001/XMLSchema}int
+#
+# RETURNS
+# return Owner - {http://www.ruby-lang.org/xmlns/soap/type/RAA/0.0.3/}Owner
+#
+# RAISES
+# (undefined)
+#
+owner_id = nil
+puts obj.owner(owner_id)
+
+# SYNOPSIS
+# list_owner(idx)
+#
+# ARGS
+# idx - {http://www.w3.org/2001/XMLSchema}int
+#
+# RETURNS
+# return OwnerArray - {http://www.ruby-lang.org/xmlns/soap/type/RAA/0.0.3/}OwnerArray
+#
+# RAISES
+# (undefined)
+#
+idx = nil
+puts obj.list_owner(idx)
+
+# SYNOPSIS
+# update(name, pass, gem)
+#
+# ARGS
+# name - {http://www.w3.org/2001/XMLSchema}string
+# pass - {http://www.w3.org/2001/XMLSchema}string
+# gem Gem - {http://www.ruby-lang.org/xmlns/soap/type/RAA/0.0.3/}Gem
+#
+# RETURNS
+# return Gem - {http://www.ruby-lang.org/xmlns/soap/type/RAA/0.0.3/}Gem
+#
+# RAISES
+# (undefined)
+#
+name = pass = gem = nil
+puts obj.update(name, pass, gem)
+
+# SYNOPSIS
+# update_pass(name, oldpass, newpass)
+#
+# ARGS
+# name - {http://www.w3.org/2001/XMLSchema}string
+# oldpass - {http://www.w3.org/2001/XMLSchema}string
+# newpass - {http://www.w3.org/2001/XMLSchema}string
+#
+# RETURNS
+# N/A
+#
+# RAISES
+# (undefined)
+#
+name = oldpass = newpass = nil
+puts obj.update_pass(name, oldpass, newpass)
+
+
diff --git a/sample/soap/raa2.4/sample.rb b/sample/soap/raa2.4/sample.rb
new file mode 100644
index 0000000000..e157f8361f
--- /dev/null
+++ b/sample/soap/raa2.4/sample.rb
@@ -0,0 +1,115 @@
+#!/usr/bin/env ruby
+
+# This is a sample client based on raaServiceClient.rb.
+# You can generate raaServiceClient.rb and related files with
+# wsdl2ruby.rb --wsdl http://www.ruby-lang.org/xmlns/soap/interface/RAA/0.0.4/ --type client
+
+require 'pp'
+require 'raaDriver.rb'
+
+raa = RaaServicePortType.new
+# raa.wiredump_dev = STDERR
+
+def sec(msg)
+ puts
+ puts "--------"
+ puts "-- " + msg
+ puts
+end
+
+def subsec(msg)
+ puts "-- " + msg
+end
+
+sec("retrieve a gem (RAA Information) which has specified name")
+name = 'soap4r'
+pp raa.gem(name)
+
+sec("retrieve dependents of the project")
+name = 'http-access2'; version = nil
+pp raa.dependents(name, version)
+
+sec("number of registered gems")
+puts raa.size
+
+sec("retrieve all registered gem names")
+p raa.names
+
+sec("retrieve gems of specified category")
+major = 'Library'; minor = 'XML'
+p raa.list_by_category(major, minor)
+
+sec("retrieve category tree")
+pp raa.tree_by_category
+
+sec("retrieve gems which is updated recently")
+idx = 0
+p raa.list_recent_updated(idx)
+subsec("next 10 gems")
+idx += 1
+p raa.list_recent_updated(idx)
+subsec("next 10 gems")
+idx += 1
+p raa.list_recent_updated(idx)
+
+sec("retrieve gems which is created recently")
+p raa.list_recent_created(idx)
+
+sec("retrieve gems which is updated in 7 days")
+date = Time.now - 7 * 24 * 60 * 60; idx = 0
+p raa.list_updated_since(date, idx)
+
+sec("retrieve gems which is created in 7 days")
+p raa.list_created_since(date, idx)
+
+sec("retrieve gems of specified owner")
+owner_id = 8 # NaHi
+p raa.list_by_owner(owner_id)
+
+sec("search gems with keyword")
+substring = 'soap'
+pp raa.search(substring)
+
+# There are several search interface to search a field explicitly.
+# puts raa.search_name(substring, idx)
+# puts raa.search_short_description(substring, idx)
+# puts raa.search_owner(substring, idx)
+# puts raa.search_version(substring, idx)
+# puts raa.search_status(substring, idx)
+# puts raa.search_description(substring, idx)
+
+sec("retrieve owner info")
+owner_id = 8
+pp raa.owner(owner_id)
+
+sec("retrieve owners")
+idx = 0
+p raa.list_owner(idx)
+
+sec("update 'sampleproject'")
+name = 'sampleproject'
+pass = 'sampleproject'
+gem = raa.gem(name)
+p gem.project.version
+gem.project.version.succ!
+gem.updated = Time.now
+raa.update(name, pass, gem)
+p raa.gem(name).project.version
+
+sec("update pass phrase")
+raa.update_pass(name, 'sampleproject', 'foo')
+subsec("update check")
+gem = raa.gem(name)
+gem.project.description = 'Current pass phrase is "foo"'
+gem.updated = Time.now
+raa.update(name, 'foo', gem)
+#
+subsec("recover pass phrase")
+raa.update_pass(name, 'foo', 'sampleproject')
+subsec("update check")
+gem = raa.gem(name)
+gem.project.description = 'Current pass phrase is "sampleproject"'
+gem.updated = Time.now
+raa.update(name, 'sampleproject', gem)
+
+sec("done")
diff --git a/sample/soap/sampleStruct/client.rb b/sample/soap/sampleStruct/client.rb
new file mode 100644
index 0000000000..b55c7fdfc5
--- /dev/null
+++ b/sample/soap/sampleStruct/client.rb
@@ -0,0 +1,16 @@
+require 'soap/rpc/driver'
+
+require 'iSampleStruct'
+
+server = ARGV.shift || 'http://localhost:7000/'
+# server = 'http://localhost:8808/server.cgi'
+
+drv = SOAP::RPC::Driver.new(server, SampleStructServiceNamespace)
+drv.wiredump_dev = STDERR
+drv.add_method('hi', 'sampleStruct')
+
+o1 = SampleStruct.new
+puts "Sending struct: #{ o1.inspect }"
+puts
+o2 = drv.hi(o1)
+puts "Received (wrapped): #{ o2.inspect }"
diff --git a/sample/soap/sampleStruct/httpd.rb b/sample/soap/sampleStruct/httpd.rb
new file mode 100644
index 0000000000..bebcff96c6
--- /dev/null
+++ b/sample/soap/sampleStruct/httpd.rb
@@ -0,0 +1,20 @@
+#!/usr/bin/env ruby
+
+require 'webrick'
+require 'soap/property'
+
+docroot = "."
+port = 8808
+if opt = SOAP::Property.loadproperty("samplehttpd.conf")
+ docroot = opt["docroot"]
+ port = Integer(opt["port"])
+end
+
+s = WEBrick::HTTPServer.new(
+ :BindAddress => "0.0.0.0",
+ :Port => port,
+ :DocumentRoot => docroot,
+ :CGIPathEnv => ENV['PATH']
+)
+trap(:INT){ s.shutdown }
+s.start
diff --git a/sample/soap/sampleStruct/iSampleStruct.rb b/sample/soap/sampleStruct/iSampleStruct.rb
new file mode 100644
index 0000000000..399ea52eb8
--- /dev/null
+++ b/sample/soap/sampleStruct/iSampleStruct.rb
@@ -0,0 +1,22 @@
+require 'soap/mapping'
+
+SampleStructServiceNamespace = 'http://tempuri.org/sampleStructService'
+
+class SampleStruct; include SOAP::Marshallable
+ attr_accessor :sampleArray
+ attr_accessor :date
+
+ def initialize
+ @sampleArray = SampleArray[ "cyclic", self ]
+ @date = DateTime.now
+ end
+
+ def wrap( rhs )
+ @sampleArray = SampleArray[ "wrap", rhs.dup ]
+ @date = DateTime.now
+ self
+ end
+end
+
+class SampleArray < Array; include SOAP::Marshallable
+end
diff --git a/sample/soap/sampleStruct/sampleStruct.rb b/sample/soap/sampleStruct/sampleStruct.rb
new file mode 100644
index 0000000000..394c1bff09
--- /dev/null
+++ b/sample/soap/sampleStruct/sampleStruct.rb
@@ -0,0 +1,13 @@
+require 'iSampleStruct'
+
+class SampleStructService
+ def hi(struct)
+ ack = SampleStruct.new
+ ack.wrap(struct)
+ ack
+ end
+end
+
+if __FILE__ == $0
+ p SampleStructService.new.hi(SampleStruct.new)
+end
diff --git a/sample/soap/sampleStruct/samplehttpd.conf b/sample/soap/sampleStruct/samplehttpd.conf
new file mode 100644
index 0000000000..85e9995021
--- /dev/null
+++ b/sample/soap/sampleStruct/samplehttpd.conf
@@ -0,0 +1,2 @@
+docroot = .
+port = 8808
diff --git a/sample/soap/sampleStruct/server.cgi b/sample/soap/sampleStruct/server.cgi
new file mode 100644
index 0000000000..42751386a0
--- /dev/null
+++ b/sample/soap/sampleStruct/server.cgi
@@ -0,0 +1,14 @@
+#!/usr/local/bin/ruby
+
+require 'soap/rpc/cgistub'
+require 'sampleStruct'
+
+class SampleStructServer < SOAP::RPC::CGIStub
+ def initialize(*arg)
+ super
+ servant = SampleStructService.new
+ add_servant(servant)
+ end
+end
+
+status = SampleStructServer.new('SampleStructServer', SampleStructServiceNamespace).start
diff --git a/sample/soap/sampleStruct/server.rb b/sample/soap/sampleStruct/server.rb
new file mode 100644
index 0000000000..ea1a2ef1d4
--- /dev/null
+++ b/sample/soap/sampleStruct/server.rb
@@ -0,0 +1,20 @@
+#!/usr/bin/env ruby
+
+require 'soap/rpc/standaloneServer'
+require 'sampleStruct'
+
+class SampleStructServer < SOAP::RPC::StandaloneServer
+ def initialize(*arg)
+ super
+ servant = SampleStructService.new
+ add_servant(servant)
+ end
+end
+
+if $0 == __FILE__
+ server = SampleStructServer.new('SampleStructServer', SampleStructServiceNamespace, '0.0.0.0', 7000)
+ trap(:INT) do
+ server.shutdown
+ end
+ server.start
+end
diff --git a/sample/soap/ssl/files/README b/sample/soap/ssl/files/README
new file mode 100644
index 0000000000..98ebcf7c23
--- /dev/null
+++ b/sample/soap/ssl/files/README
@@ -0,0 +1 @@
+* certificates and keys in this directory is copied from http-access2 test.
diff --git a/sample/soap/ssl/files/ca.cert b/sample/soap/ssl/files/ca.cert
new file mode 100644
index 0000000000..bcabbee4ad
--- /dev/null
+++ b/sample/soap/ssl/files/ca.cert
@@ -0,0 +1,23 @@
+-----BEGIN CERTIFICATE-----
+MIID0DCCArigAwIBAgIBADANBgkqhkiG9w0BAQUFADA8MQswCQYDVQQGDAJKUDES
+MBAGA1UECgwJSklOLkdSLkpQMQwwCgYDVQQLDANSUlIxCzAJBgNVBAMMAkNBMB4X
+DTA0MDEzMDAwNDIzMloXDTM2MDEyMjAwNDIzMlowPDELMAkGA1UEBgwCSlAxEjAQ
+BgNVBAoMCUpJTi5HUi5KUDEMMAoGA1UECwwDUlJSMQswCQYDVQQDDAJDQTCCASIw
+DQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBANbv0x42BTKFEQOE+KJ2XmiSdZpR
+wjzQLAkPLRnLB98tlzs4xo+y4RyY/rd5TT9UzBJTIhP8CJi5GbS1oXEerQXB3P0d
+L5oSSMwGGyuIzgZe5+vZ1kgzQxMEKMMKlzA73rbMd4Jx3u5+jdbP0EDrPYfXSvLY
+bS04n2aX7zrN3x5KdDrNBfwBio2/qeaaj4+9OxnwRvYP3WOvqdW0h329eMfHw0pi
+JI0drIVdsEqClUV4pebT/F+CPUPkEh/weySgo9wANockkYu5ujw2GbLFcO5LXxxm
+dEfcVr3r6t6zOA4bJwL0W/e6LBcrwiG/qPDFErhwtgTLYf6Er67SzLyA66UCAwEA
+AaOB3DCB2TAPBgNVHRMBAf8EBTADAQH/MDEGCWCGSAGG+EIBDQQkFiJSdWJ5L09w
+ZW5TU0wgR2VuZXJhdGVkIENlcnRpZmljYXRlMB0GA1UdDgQWBBRJ7Xd380KzBV7f
+USKIQ+O/vKbhDzAOBgNVHQ8BAf8EBAMCAQYwZAYDVR0jBF0wW4AUSe13d/NCswVe
+31EiiEPjv7ym4Q+hQKQ+MDwxCzAJBgNVBAYMAkpQMRIwEAYDVQQKDAlKSU4uR1Iu
+SlAxDDAKBgNVBAsMA1JSUjELMAkGA1UEAwwCQ0GCAQAwDQYJKoZIhvcNAQEFBQAD
+ggEBAIu/mfiez5XN5tn2jScgShPgHEFJBR0BTJBZF6xCk0jyqNx/g9HMj2ELCuK+
+r/Y7KFW5c5M3AQ+xWW0ZSc4kvzyTcV7yTVIwj2jZ9ddYMN3nupZFgBK1GB4Y05GY
+MJJFRkSu6d/Ph5ypzBVw2YMT/nsOo5VwMUGLgS7YVjU+u/HNWz80J3oO17mNZllj
+PvORJcnjwlroDnS58KoJ7GDgejv3ESWADvX1OHLE4cRkiQGeLoEU4pxdCxXRqX0U
+PbwIkZN9mXVcrmPHq8MWi4eC/V7hnbZETMHuWhUoiNdOEfsAXr3iP4KjyyRdwc7a
+d/xgcK06UVQRL/HbEYGiQL056mc=
+-----END CERTIFICATE-----
diff --git a/sample/soap/ssl/files/client.cert b/sample/soap/ssl/files/client.cert
new file mode 100644
index 0000000000..ad13c4b735
--- /dev/null
+++ b/sample/soap/ssl/files/client.cert
@@ -0,0 +1,19 @@
+-----BEGIN CERTIFICATE-----
+MIIDKDCCAhCgAwIBAgIBAjANBgkqhkiG9w0BAQUFADA8MQswCQYDVQQGDAJKUDES
+MBAGA1UECgwJSklOLkdSLkpQMQwwCgYDVQQLDANSUlIxCzAJBgNVBAMMAkNBMB4X
+DTA0MDEzMTAzMTQ1OFoXDTM1MDEyMzAzMTQ1OFowZTELMAkGA1UEBgwCSlAxEjAQ
+BgNVBAoMCUpJTi5HUi5KUDEMMAoGA1UECwwDUlJSMRAwDgYDVQQDDAdleGFtcGxl
+MSIwIAYJKoZIhvcNAQkBDBNleGFtcGxlQGV4YW1wbGUub3JnMIGfMA0GCSqGSIb3
+DQEBAQUAA4GNADCBiQKBgQDRWssrK8Gyr+500hpLjCGR3+AHL8/hEJM5zKi/MgLW
+jTkvsgOwbYwXOiNtAbR9y4/ucDq7EY+cMUMHES4uFaPTcOaAV0aZRmk8AgslN1tQ
+gNS6ew7/Luq3DcVeWkX8PYgR9VG0mD1MPfJ6+IFA5d3vKpdBkBgN4l46jjO0/2Xf
+ewIDAQABo4GPMIGMMAwGA1UdEwEB/wQCMAAwMQYJYIZIAYb4QgENBCQWIlJ1Ynkv
+T3BlblNTTCBHZW5lcmF0ZWQgQ2VydGlmaWNhdGUwHQYDVR0OBBYEFOFvay0H7lr2
+xUx6waYEV2bVDYQhMAsGA1UdDwQEAwIF4DAdBgNVHSUEFjAUBggrBgEFBQcDAgYI
+KwYBBQUHAwQwDQYJKoZIhvcNAQEFBQADggEBABd2dYWqbDIWf5sWFvslezxJv8gI
+w64KCJBuyJAiDuf+oazr3016kMzAlt97KecLZDusGNagPrq02UX7YMoQFsWJBans
+cDtHrkM0al5r6/WGexNMgtYbNTYzt/IwodISGBgZ6dsOuhznwms+IBsTNDAvWeLP
+lt2tOqD8kEmjwMgn0GDRuKjs4EoboA3kMULb1p9akDV9ZESU3eOtpS5/G5J5msLI
+9WXbYBjcjvkLuJH9VsJhb+R58Vl0ViemvAHhPilSl1SPWVunGhv6FcIkdBEi1k9F
+e8BNMmsEjFiANiIRvpdLRbiGBt0KrKTndVfsmoKCvY48oCOvnzxtahFxfs8=
+-----END CERTIFICATE-----
diff --git a/sample/soap/ssl/files/client.key b/sample/soap/ssl/files/client.key
new file mode 100644
index 0000000000..37bc62f259
--- /dev/null
+++ b/sample/soap/ssl/files/client.key
@@ -0,0 +1,15 @@
+-----BEGIN RSA PRIVATE KEY-----
+MIICWwIBAAKBgQDRWssrK8Gyr+500hpLjCGR3+AHL8/hEJM5zKi/MgLWjTkvsgOw
+bYwXOiNtAbR9y4/ucDq7EY+cMUMHES4uFaPTcOaAV0aZRmk8AgslN1tQgNS6ew7/
+Luq3DcVeWkX8PYgR9VG0mD1MPfJ6+IFA5d3vKpdBkBgN4l46jjO0/2XfewIDAQAB
+AoGAZcz8llWErtsV3QB9gNb3S/PNADGjqBFjReva8n3jG2k4sZSibpwWTwUaTNtT
+ZQgjSRKRvH1hk9XwffNAvXAQZNNkuj/16gO2oO45nyLj4dO365ujLptWnVIWDHOE
+uN0GeiZO+VzcCisT0WCq4tvtLeH8svrxzA8cbXIEyOK7NiECQQDwo2zPFyKAZ/Cu
+lDJ6zKT+RjfWwW7DgWzirAlTrt4ViMaW+IaDH29TmQpb4V4NuR3Xi+2Xl4oicu6S
+36TW9+/FAkEA3rgfOQJuLlWSnw1RTGwvnC816a/W7iYYY7B+0U4cDbfWl7IoXT4y
+M8nV/HESooviZLqBwzAYSoj3fFKYBKpGPwJAUO8GN5iWWA2dW3ooiDiv/X1sZmRk
+dojfMFWgRW747tEzya8Ivq0h6kH8w+5GjeMG8Gn1nRiwsulo6Ckj7dEx6QJACyui
+7UIQ8qP6GZ4aYMHgVW4Mvy7Bkeo5OO7GPYs0Xv/EdJFL8vlGnVBXOjUVoS9w6Gpu
+TbLg1QQvnX2rADjmEwJANxZO2GUkaWGsEif8aGW0x5g/IdaMGG27pTWk5zqix7P3
+1UDrdo/JOXhptovhRi06EppIxAxYmbh9vd9VN8Itlw==
+-----END RSA PRIVATE KEY-----
diff --git a/sample/soap/ssl/files/server.cert b/sample/soap/ssl/files/server.cert
new file mode 100644
index 0000000000..998ccc5892
--- /dev/null
+++ b/sample/soap/ssl/files/server.cert
@@ -0,0 +1,19 @@
+-----BEGIN CERTIFICATE-----
+MIIC/zCCAeegAwIBAgIBATANBgkqhkiG9w0BAQUFADA/MQswCQYDVQQGDAJKUDES
+MBAGA1UECgwJSklOLkdSLkpQMQwwCgYDVQQLDANSUlIxDjAMBgNVBAMMBVN1YkNB
+MB4XDTA0MDEzMTAzMTMxNloXDTMzMDEyMzAzMTMxNlowQzELMAkGA1UEBgwCSlAx
+EjAQBgNVBAoMCUpJTi5HUi5KUDEMMAoGA1UECwwDUlJSMRIwEAYDVQQDDAlsb2Nh
+bGhvc3QwgZ8wDQYJKoZIhvcNAQEBBQADgY0AMIGJAoGBANFJTxWqup3nV9dsJAku
+p+WaXnPNIzcpAA3qMGZDJTJsfa8Du7ZxTP0XJK5mETttBrn711cJxAuP3KjqnW9S
+vtZ9lY2sXJ6Zj62sN5LwG3VVe25dI28yR1EsbHjJ5Zjf9tmggMC6am52dxuHbt5/
+vHo4ngJuKE/U+eeGRivMn6gFAgMBAAGjgYUwgYIwDAYDVR0TAQH/BAIwADAxBglg
+hkgBhvhCAQ0EJBYiUnVieS9PcGVuU1NMIEdlbmVyYXRlZCBDZXJ0aWZpY2F0ZTAd
+BgNVHQ4EFgQUpZIyygD9JxFYHHOTEuWOLbCKfckwCwYDVR0PBAQDAgWgMBMGA1Ud
+JQQMMAoGCCsGAQUFBwMBMA0GCSqGSIb3DQEBBQUAA4IBAQBwAIj5SaBHaA5X31IP
+CFCJiep96awfp7RANO0cuUj+ZpGoFn9d6FXY0g+Eg5wAkCNIzZU5NHN9xsdOpnUo
+zIBbyTfQEPrge1CMWMvL6uGaoEXytq84VTitF/xBTky4KtTn6+es4/e7jrrzeUXQ
+RC46gkHObmDT91RkOEGjHLyld2328jo3DIN/VTHIryDeVHDWjY5dENwpwdkhhm60
+DR9IrNBbXWEe9emtguNXeN0iu1ux0lG1Hc6pWGQxMlRKNvGh0yZB9u5EVe38tOV0
+jQaoNyL7qzcQoXD3Dmbi1p0iRmg/+HngISsz8K7k7MBNVsSclztwgCzTZOBiVtkM
+rRlQ
+-----END CERTIFICATE-----
diff --git a/sample/soap/ssl/files/server.key b/sample/soap/ssl/files/server.key
new file mode 100644
index 0000000000..9ba2218a03
--- /dev/null
+++ b/sample/soap/ssl/files/server.key
@@ -0,0 +1,15 @@
+-----BEGIN RSA PRIVATE KEY-----
+MIICXQIBAAKBgQDRSU8Vqrqd51fXbCQJLqflml5zzSM3KQAN6jBmQyUybH2vA7u2
+cUz9FySuZhE7bQa5+9dXCcQLj9yo6p1vUr7WfZWNrFyemY+trDeS8Bt1VXtuXSNv
+MkdRLGx4yeWY3/bZoIDAumpudncbh27ef7x6OJ4CbihP1PnnhkYrzJ+oBQIDAQAB
+AoGBAIf4CstW2ltQO7+XYGoex7Hh8s9lTSW/G2vu5Hbr1LTHy3fzAvdq8MvVR12O
+rk9fa+lU9vhzPc0NMB0GIDZ9GcHuhW5hD1Wg9OSCbTOkZDoH3CAFqonjh4Qfwv5W
+IPAFn9KHukdqGXkwEMdErsUaPTy9A1V/aROVEaAY+HJgq/eZAkEA/BP1QMV04WEZ
+Oynzz7/lLizJGGxp2AOvEVtqMoycA/Qk+zdKP8ufE0wbmCE3Qd6GoynavsHb6aGK
+gQobb8zDZwJBANSK6MrXlrZTtEaeZuyOB4mAmRzGzOUVkUyULUjEx2GDT93ujAma
+qm/2d3E+wXAkNSeRpjUmlQXy/2oSqnGvYbMCQQDRM+cYyEcGPUVpWpnj0shrF/QU
+9vSot/X1G775EMTyaw6+BtbyNxVgOIu2J+rqGbn3c+b85XqTXOPL0A2RLYkFAkAm
+syhSDtE9X55aoWsCNZY/vi+i4rvaFoQ/WleogVQAeGVpdo7/DK9t9YWoFBIqth0L
+mGSYFu9ZhvZkvQNV8eYrAkBJ+rOIaLDsmbrgkeDruH+B/9yrm4McDtQ/rgnOGYnH
+LjLpLLOrgUxqpzLWe++EwSLwK2//dHO+SPsQJ4xsyQJy
+-----END RSA PRIVATE KEY-----
diff --git a/sample/soap/ssl/files/sslclient.properties b/sample/soap/ssl/files/sslclient.properties
new file mode 100644
index 0000000000..547ac7b3fb
--- /dev/null
+++ b/sample/soap/ssl/files/sslclient.properties
@@ -0,0 +1,5 @@
+# verify server's certificate
+protocol.http.ssl_config.verify_mode = OpenSSL::SSL::VERIFY_PEER
+# certificates for verification
+protocol.http.ssl_config.ca_file = files/ca.cert
+protocol.http.ssl_config.ca_file = files/subca.cert
diff --git a/sample/soap/ssl/files/sslclient_require_noserverauth.properties b/sample/soap/ssl/files/sslclient_require_noserverauth.properties
new file mode 100644
index 0000000000..5ce5337fbf
--- /dev/null
+++ b/sample/soap/ssl/files/sslclient_require_noserverauth.properties
@@ -0,0 +1,2 @@
+# no verify server's certificate
+protocol.http.ssl_config.verify_mode =
diff --git a/sample/soap/ssl/files/sslclient_with_clientauth.properties b/sample/soap/ssl/files/sslclient_with_clientauth.properties
new file mode 100644
index 0000000000..f1c81ebf46
--- /dev/null
+++ b/sample/soap/ssl/files/sslclient_with_clientauth.properties
@@ -0,0 +1,9 @@
+# verify server's certificate
+protocol.http.ssl_config.verify_mode = OpenSSL::SSL::VERIFY_PEER
+# certificates for verification
+protocol.http.ssl_config.ca_file = files/ca.cert
+protocol.http.ssl_config.ca_file = files/subca.cert
+
+# key and certificate for client identity
+protocol.http.ssl_config.client_cert = files/client.cert
+protocol.http.ssl_config.client_key = files/client.key
diff --git a/sample/soap/ssl/files/subca.cert b/sample/soap/ssl/files/subca.cert
new file mode 100644
index 0000000000..1e471851b8
--- /dev/null
+++ b/sample/soap/ssl/files/subca.cert
@@ -0,0 +1,21 @@
+-----BEGIN CERTIFICATE-----
+MIIDaDCCAlCgAwIBAgIBATANBgkqhkiG9w0BAQUFADA8MQswCQYDVQQGDAJKUDES
+MBAGA1UECgwJSklOLkdSLkpQMQwwCgYDVQQLDANSUlIxCzAJBgNVBAMMAkNBMB4X
+DTA0MDEzMDAwNDMyN1oXDTM1MDEyMjAwNDMyN1owPzELMAkGA1UEBgwCSlAxEjAQ
+BgNVBAoMCUpJTi5HUi5KUDEMMAoGA1UECwwDUlJSMQ4wDAYDVQQDDAVTdWJDQTCC
+ASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAJ0Ou7AyRcRXnB/kVHv/6kwe
+ANzgg/DyJfsAUqW90m7Lu1nqyug8gK0RBd77yU0w5HOAMHTVSdpjZK0g2sgx4Mb1
+d/213eL9TTl5MRVEChTvQr8q5DVG/8fxPPE7fMI8eOAzd98/NOAChk+80r4Sx7fC
+kGVEE1bKwY1MrUsUNjOY2d6t3M4HHV3HX1V8ShuKfsHxgCmLzdI8U+5CnQedFgkm
+3e+8tr8IX5RR1wA1Ifw9VadF7OdI/bGMzog/Q8XCLf+WPFjnK7Gcx6JFtzF6Gi4x
+4dp1Xl45JYiVvi9zQ132wu8A1pDHhiNgQviyzbP+UjcB/tsOpzBQF8abYzgEkWEC
+AwEAAaNyMHAwDwYDVR0TAQH/BAUwAwEB/zAxBglghkgBhvhCAQ0EJBYiUnVieS9P
+cGVuU1NMIEdlbmVyYXRlZCBDZXJ0aWZpY2F0ZTAdBgNVHQ4EFgQUlCjXWLsReYzH
+LzsxwVnCXmKoB/owCwYDVR0PBAQDAgEGMA0GCSqGSIb3DQEBBQUAA4IBAQCJ/OyN
+rT8Cq2Y+G2yA/L1EMRvvxwFBqxavqaqHl/6rwsIBFlB3zbqGA/0oec6MAVnYynq4
+c4AcHTjx3bQ/S4r2sNTZq0DH4SYbQzIobx/YW8PjQUJt8KQdKMcwwi7arHP7A/Ha
+LKu8eIC2nsUBnP4NhkYSGhbmpJK+PFD0FVtD0ZIRlY/wsnaZNjWWcnWF1/FNuQ4H
+ySjIblqVQkPuzebv3Ror6ZnVDukn96Mg7kP4u6zgxOeqlJGRe1M949SS9Vudjl8X
+SF4aZUUB9pQGhsqQJVqaz2OlhGOp9D0q54xko/rekjAIcuDjl1mdX4F2WRrzpUmZ
+uY/bPeOBYiVsOYVe
+-----END CERTIFICATE-----
diff --git a/sample/soap/ssl/sslclient.rb b/sample/soap/ssl/sslclient.rb
new file mode 100644
index 0000000000..a055247a4c
--- /dev/null
+++ b/sample/soap/ssl/sslclient.rb
@@ -0,0 +1,12 @@
+require 'http-access2'
+require 'soap/rpc/driver'
+
+# setup driver
+url = "https://localhost:17443/"
+client = SOAP::RPC::Driver.new(url, 'urn:sslhelloworld')
+client.add_method("hello_world", "from")
+# load SSL properties
+client.loadproperty('files/sslclient.properties')
+
+# SOAP over SSL
+p client.hello_world(__FILE__)
diff --git a/sample/soap/ssl/sslclient_require_noserverauth.rb b/sample/soap/ssl/sslclient_require_noserverauth.rb
new file mode 100644
index 0000000000..af121e9a41
--- /dev/null
+++ b/sample/soap/ssl/sslclient_require_noserverauth.rb
@@ -0,0 +1,12 @@
+require 'http-access2'
+require 'soap/rpc/driver'
+
+# setup driver
+url = "https://localhost:17443/"
+client = SOAP::RPC::Driver.new(url, 'urn:sslhelloworld')
+client.add_method("hello_world", "from")
+# load SSL properties
+client.loadproperty('files/sslclient_require_noserverauth.properties')
+
+# SOAP over SSL
+p client.hello_world(__FILE__)
diff --git a/sample/soap/ssl/sslclient_with_clientauth.rb b/sample/soap/ssl/sslclient_with_clientauth.rb
new file mode 100644
index 0000000000..7753d7b807
--- /dev/null
+++ b/sample/soap/ssl/sslclient_with_clientauth.rb
@@ -0,0 +1,12 @@
+require 'http-access2'
+require 'soap/rpc/driver'
+
+# setup driver
+url = "https://localhost:17443/"
+client = SOAP::RPC::Driver.new(url, 'urn:sslhelloworld')
+client.add_method("hello_world", "from")
+# load SSL properties
+client.loadproperty('files/sslclient_with_clientauth.properties')
+
+# SOAP over SSL
+p client.hello_world(__FILE__)
diff --git a/sample/soap/ssl/sslserver.rb b/sample/soap/ssl/sslserver.rb
new file mode 100644
index 0000000000..e65cbacc7f
--- /dev/null
+++ b/sample/soap/ssl/sslserver.rb
@@ -0,0 +1,49 @@
+require 'soap/rpc/httpserver'
+require 'webrick/https'
+require 'logger'
+
+class HelloWorldServer < SOAP::RPC::HTTPServer
+private
+
+ def on_init
+ @default_namespace = 'urn:sslhelloworld'
+ add_method(self, 'hello_world', 'from')
+ end
+
+ def hello_world(from)
+ "Hello World, from #{ from }"
+ end
+end
+
+
+if $0 == __FILE__
+ DIR = File.dirname(File.expand_path(__FILE__))
+
+ def cert(filename)
+ OpenSSL::X509::Certificate.new(File.open(File.join(DIR, filename)) { |f|
+ f.read
+ })
+ end
+
+ def key(filename)
+ OpenSSL::PKey::RSA.new(File.open(File.join(DIR, filename)) { |f|
+ f.read
+ })
+ end
+
+ $server = HelloWorldServer.new(
+ :BindAddress => "0.0.0.0",
+ :Port => 17443,
+ :AccessLog => [],
+ :SSLEnable => true,
+ :SSLCACertificateFile => File.join(DIR, 'files/ca.cert'),
+ :SSLCertificate => cert('files/server.cert'),
+ :SSLPrivateKey => key('files/server.key'),
+ :SSLVerifyClient => nil,
+ :SSLCertName => nil
+ )
+ trap(:INT) do
+ $server.shutdown
+ end
+ $server.start
+end
diff --git a/sample/soap/ssl/sslserver_noauth.rb b/sample/soap/ssl/sslserver_noauth.rb
new file mode 100644
index 0000000000..48f5a68ad0
--- /dev/null
+++ b/sample/soap/ssl/sslserver_noauth.rb
@@ -0,0 +1,45 @@
+require 'soap/rpc/httpserver'
+require 'webrick/https'
+require 'logger'
+
+class HelloWorldServer < SOAP::RPC::HTTPServer
+private
+
+ def on_init
+ @default_namespace = 'urn:sslhelloworld'
+ add_method(self, 'hello_world', 'from')
+ end
+
+ def hello_world(from)
+ "Hello World, from #{ from }"
+ end
+end
+
+
+if $0 == __FILE__
+ DIR = File.dirname(File.expand_path(__FILE__))
+
+ def cert(filename)
+ OpenSSL::X509::Certificate.new(File.open(File.join(DIR, filename)) { |f|
+ f.read
+ })
+ end
+
+ def key(filename)
+ OpenSSL::PKey::RSA.new(File.open(File.join(DIR, filename)) { |f|
+ f.read
+ })
+ end
+
+ $server = HelloWorldServer.new(
+ :BindAddress => "0.0.0.0",
+ :Port => 17443,
+ :AccessLog => [],
+ :SSLEnable => true,
+ :SSLCertName => [['OU', 'example'], ['CN', 'localhost']] # creates dummy certificate
+ )
+ trap(:INT) do
+ $server.shutdown
+ end
+ $server.start
+end
diff --git a/sample/soap/ssl/sslserver_require_clientauth.rb b/sample/soap/ssl/sslserver_require_clientauth.rb
new file mode 100644
index 0000000000..63caf69caf
--- /dev/null
+++ b/sample/soap/ssl/sslserver_require_clientauth.rb
@@ -0,0 +1,50 @@
+require 'soap/rpc/httpserver'
+require 'webrick/https'
+require 'logger'
+
+class HelloWorldServer < SOAP::RPC::HTTPServer
+private
+
+ def on_init
+ @default_namespace = 'urn:sslhelloworld'
+ add_method(self, 'hello_world', 'from')
+ end
+
+ def hello_world(from)
+ "Hello World, from #{ from }"
+ end
+end
+
+
+if $0 == __FILE__
+ DIR = File.dirname(File.expand_path(__FILE__))
+
+ def cert(filename)
+ OpenSSL::X509::Certificate.new(File.open(File.join(DIR, filename)) { |f|
+ f.read
+ })
+ end
+
+ def key(filename)
+ OpenSSL::PKey::RSA.new(File.open(File.join(DIR, filename)) { |f|
+ f.read
+ })
+ end
+
+ $server = HelloWorldServer.new(
+ :BindAddress => "0.0.0.0",
+ :Port => 17443,
+ :AccessLog => [],
+ :SSLEnable => true,
+ :SSLCACertificateFile => File.join(DIR, 'files/ca.cert'),
+ :SSLCertificate => cert('files/server.cert'),
+ :SSLPrivateKey => key('files/server.key'),
+ :SSLVerifyClient =>
+ OpenSSL::SSL::VERIFY_FAIL_IF_NO_PEER_CERT|OpenSSL::SSL::VERIFY_PEER,
+ :SSLClientCA => cert('files/ca.cert')
+ )
+ trap(:INT) do
+ $server.shutdown
+ end
+ $server.start
+end
diff --git a/sample/soap/swa/client.rb b/sample/soap/swa/client.rb
new file mode 100644
index 0000000000..01c59a3845
--- /dev/null
+++ b/sample/soap/swa/client.rb
@@ -0,0 +1,13 @@
+require 'soap/rpc/driver'
+require 'soap/attachment'
+
+server = 'http://localhost:7000/'
+driver = SOAP::RPC::Driver.new(server, 'http://www.acmetron.com/soap')
+driver.wiredump_dev = STDERR
+driver.add_method('get_file')
+driver.add_method('put_file', 'name', 'file')
+
+p driver.get_file
+file = File.open($0)
+attach = SOAP::Attachment.new(file)
+p driver.put_file($0, attach)
diff --git a/sample/soap/swa/server.rb b/sample/soap/swa/server.rb
new file mode 100644
index 0000000000..0a82fe58bf
--- /dev/null
+++ b/sample/soap/swa/server.rb
@@ -0,0 +1,23 @@
+require 'soap/rpc/standaloneServer'
+require 'soap/attachment'
+
+class SwAService
+ def get_file
+ return {
+ 'name' => $0,
+ 'file' => SOAP::Attachment.new(File.open($0))
+ }
+ end
+
+ def put_file(name, file)
+ "File '#{name}' was received ok."
+ end
+end
+
+server = SOAP::RPC::StandaloneServer.new('SwAServer',
+ 'http://www.acmetron.com/soap', '0.0.0.0', 7000)
+server.add_servant(SwAService.new)
+trap(:INT) do
+ server.shutdown
+end
+server.start
diff --git a/sample/soap/whois.rb b/sample/soap/whois.rb
new file mode 100644
index 0000000000..2737e8085e
--- /dev/null
+++ b/sample/soap/whois.rb
@@ -0,0 +1,14 @@
+#!/usr/bin/env ruby
+
+key = ARGV.shift
+
+require 'soap/rpc/driver'
+
+server = 'http://www.SoapClient.com/xml/SQLDataSoap.WSDL'
+interface = 'http://www.SoapClient.com/xml/SQLDataSoap.xsd'
+
+whois = SOAP::RPC::Driver.new(server, interface)
+whois.wiredump_dev = STDERR
+whois.add_method('ProcessSRL', 'SRLFile', 'RequestName', 'key')
+
+p whois.ProcessSRL('WHOIS.SRI', 'whois', key)
diff --git a/sample/svr.rb b/sample/svr.rb
index 11cfc5fbfe..6169861abc 100644
--- a/sample/svr.rb
+++ b/sample/svr.rb
@@ -1,9 +1,6 @@
# socket example - server side
# usage: ruby svr.rb
-# this server might be blocked by an ill-behaved client.
-# see tsvr.rb which is safe from client blocking.
-
require "socket"
gs = TCPserver.open(0)
@@ -25,9 +22,10 @@ loop do
print(s, " is gone\n")
s.close
socks.delete(s)
- # single thread gets may block whole service
- elsif str = s.gets
+ else
+ if str = s.gets
s.write(str)
+ end
end
end
end
diff --git a/sample/test.rb b/sample/test.rb
index e7f2d251b7..65cfcad475 100644
--- a/sample/test.rb
+++ b/sample/test.rb
@@ -787,10 +787,10 @@ test_ok($x.has_value?(4))
test_ok($x.values_at(2,3) == [4,6])
test_ok($x == {1=>2, 2=>4, 3=>6})
-$z = $y.keys.sort.join(":")
+$z = $y.keys.join(":")
test_ok($z == "1:2:3")
-$z = $y.values.sort.join(":")
+$z = $y.values.join(":")
test_ok($z == "2:4:6")
test_ok($x == $y)
diff --git a/sample/webrick/httpproxy.rb b/sample/webrick/httpproxy.rb
deleted file mode 100644
index bca0cc4626..0000000000
--- a/sample/webrick/httpproxy.rb
+++ /dev/null
@@ -1,26 +0,0 @@
-require "webrick"
-require "webrick/httpproxy"
-
-# :ProxyContentHandler will be invoked before sending
-# response to User-Agenge. You can inspect the pair of
-# request and response messages (or can edit the response
-# message if necessary).
-
-pch = Proc.new{|req, res|
- p [ req.request_line, res.status_line ]
-}
-
-def upstream_proxy
- if prx = ENV["http_proxy"]
- return URI.parse(prx)
- end
- return nil
-end
-
-httpd = WEBrick::HTTPProxyServer.new(
- :Port => 10080,
- :ProxyContentHandler => pch,
- :ProxyURI => upstream_proxy
-)
-Signal.trap(:INT){ httpd.shutdown }
-httpd.start
diff --git a/sample/webrick/httpsd.rb b/sample/webrick/httpsd.rb
index a120782c3c..9d82ef36cf 100644
--- a/sample/webrick/httpsd.rb
+++ b/sample/webrick/httpsd.rb
@@ -11,8 +11,8 @@ httpd = WEBrick::HTTPServer.new(
:SSLEnable => true,
# Specify key pair and server certificate.
- # :SSLPrivateKey => OpenSSL::PKey::RSA.new(File.read("server.key")),
- # :SSLCertificate => OpenSSL::X509::Certificate.new(File.read("server.crt")),
+ # :SSLPrivateKey => OpenSSL::PKey::RSA.new("server.key"),
+ # :SSLCertificate => OpenSSL::X509::Certificate.new("server.crt"),
# specify the following SSL options if you want to use auto
# generated self-signed certificate.
diff --git a/sample/wsdl/amazon/AmazonSearch.rb b/sample/wsdl/amazon/AmazonSearch.rb
new file mode 100644
index 0000000000..373c7da29d
--- /dev/null
+++ b/sample/wsdl/amazon/AmazonSearch.rb
@@ -0,0 +1,3057 @@
+# http://soap.amazon.com
+class ProductLineArray < Array
+ @@schema_type = "ProductLineArray"
+ @@schema_ns = "http://soap.amazon.com"
+end
+
+# http://soap.amazon.com
+class ProductLine
+ @@schema_type = "ProductLine"
+ @@schema_ns = "http://soap.amazon.com"
+
+ def Mode
+ @mode
+ end
+
+ def Mode=(value)
+ @mode = value
+ end
+
+ def RelevanceRank
+ @relevanceRank
+ end
+
+ def RelevanceRank=(value)
+ @relevanceRank = value
+ end
+
+ def ProductInfo
+ @productInfo
+ end
+
+ def ProductInfo=(value)
+ @productInfo = value
+ end
+
+ def initialize(mode = nil, relevanceRank = nil, productInfo = nil)
+ @mode = mode
+ @relevanceRank = relevanceRank
+ @productInfo = productInfo
+ end
+end
+
+# http://soap.amazon.com
+class ProductInfo
+ @@schema_type = "ProductInfo"
+ @@schema_ns = "http://soap.amazon.com"
+
+ def TotalResults
+ @totalResults
+ end
+
+ def TotalResults=(value)
+ @totalResults = value
+ end
+
+ def TotalPages
+ @totalPages
+ end
+
+ def TotalPages=(value)
+ @totalPages = value
+ end
+
+ def ListName
+ @listName
+ end
+
+ def ListName=(value)
+ @listName = value
+ end
+
+ def Details
+ @details
+ end
+
+ def Details=(value)
+ @details = value
+ end
+
+ def initialize(totalResults = nil, totalPages = nil, listName = nil, details = nil)
+ @totalResults = totalResults
+ @totalPages = totalPages
+ @listName = listName
+ @details = details
+ end
+end
+
+# http://soap.amazon.com
+class DetailsArray < Array
+ @@schema_type = "DetailsArray"
+ @@schema_ns = "http://soap.amazon.com"
+end
+
+# http://soap.amazon.com
+class Details
+ @@schema_type = "Details"
+ @@schema_ns = "http://soap.amazon.com"
+
+ def Url
+ @url
+ end
+
+ def Url=(value)
+ @url = value
+ end
+
+ def Asin
+ @asin
+ end
+
+ def Asin=(value)
+ @asin = value
+ end
+
+ def ProductName
+ @productName
+ end
+
+ def ProductName=(value)
+ @productName = value
+ end
+
+ def Catalog
+ @catalog
+ end
+
+ def Catalog=(value)
+ @catalog = value
+ end
+
+ def KeyPhrases
+ @keyPhrases
+ end
+
+ def KeyPhrases=(value)
+ @keyPhrases = value
+ end
+
+ def Artists
+ @artists
+ end
+
+ def Artists=(value)
+ @artists = value
+ end
+
+ def Authors
+ @authors
+ end
+
+ def Authors=(value)
+ @authors = value
+ end
+
+ def Mpn
+ @mpn
+ end
+
+ def Mpn=(value)
+ @mpn = value
+ end
+
+ def Starring
+ @starring
+ end
+
+ def Starring=(value)
+ @starring = value
+ end
+
+ def Directors
+ @directors
+ end
+
+ def Directors=(value)
+ @directors = value
+ end
+
+ def TheatricalReleaseDate
+ @theatricalReleaseDate
+ end
+
+ def TheatricalReleaseDate=(value)
+ @theatricalReleaseDate = value
+ end
+
+ def ReleaseDate
+ @releaseDate
+ end
+
+ def ReleaseDate=(value)
+ @releaseDate = value
+ end
+
+ def Manufacturer
+ @manufacturer
+ end
+
+ def Manufacturer=(value)
+ @manufacturer = value
+ end
+
+ def Distributor
+ @distributor
+ end
+
+ def Distributor=(value)
+ @distributor = value
+ end
+
+ def ImageUrlSmall
+ @imageUrlSmall
+ end
+
+ def ImageUrlSmall=(value)
+ @imageUrlSmall = value
+ end
+
+ def ImageUrlMedium
+ @imageUrlMedium
+ end
+
+ def ImageUrlMedium=(value)
+ @imageUrlMedium = value
+ end
+
+ def ImageUrlLarge
+ @imageUrlLarge
+ end
+
+ def ImageUrlLarge=(value)
+ @imageUrlLarge = value
+ end
+
+ def MerchantId
+ @merchantId
+ end
+
+ def MerchantId=(value)
+ @merchantId = value
+ end
+
+ def MinPrice
+ @minPrice
+ end
+
+ def MinPrice=(value)
+ @minPrice = value
+ end
+
+ def MaxPrice
+ @maxPrice
+ end
+
+ def MaxPrice=(value)
+ @maxPrice = value
+ end
+
+ def MinSalePrice
+ @minSalePrice
+ end
+
+ def MinSalePrice=(value)
+ @minSalePrice = value
+ end
+
+ def MaxSalePrice
+ @maxSalePrice
+ end
+
+ def MaxSalePrice=(value)
+ @maxSalePrice = value
+ end
+
+ def MultiMerchant
+ @multiMerchant
+ end
+
+ def MultiMerchant=(value)
+ @multiMerchant = value
+ end
+
+ def MerchantSku
+ @merchantSku
+ end
+
+ def MerchantSku=(value)
+ @merchantSku = value
+ end
+
+ def ListPrice
+ @listPrice
+ end
+
+ def ListPrice=(value)
+ @listPrice = value
+ end
+
+ def OurPrice
+ @ourPrice
+ end
+
+ def OurPrice=(value)
+ @ourPrice = value
+ end
+
+ def UsedPrice
+ @usedPrice
+ end
+
+ def UsedPrice=(value)
+ @usedPrice = value
+ end
+
+ def RefurbishedPrice
+ @refurbishedPrice
+ end
+
+ def RefurbishedPrice=(value)
+ @refurbishedPrice = value
+ end
+
+ def CollectiblePrice
+ @collectiblePrice
+ end
+
+ def CollectiblePrice=(value)
+ @collectiblePrice = value
+ end
+
+ def ThirdPartyNewPrice
+ @thirdPartyNewPrice
+ end
+
+ def ThirdPartyNewPrice=(value)
+ @thirdPartyNewPrice = value
+ end
+
+ def NumberOfOfferings
+ @numberOfOfferings
+ end
+
+ def NumberOfOfferings=(value)
+ @numberOfOfferings = value
+ end
+
+ def ThirdPartyNewCount
+ @thirdPartyNewCount
+ end
+
+ def ThirdPartyNewCount=(value)
+ @thirdPartyNewCount = value
+ end
+
+ def UsedCount
+ @usedCount
+ end
+
+ def UsedCount=(value)
+ @usedCount = value
+ end
+
+ def CollectibleCount
+ @collectibleCount
+ end
+
+ def CollectibleCount=(value)
+ @collectibleCount = value
+ end
+
+ def RefurbishedCount
+ @refurbishedCount
+ end
+
+ def RefurbishedCount=(value)
+ @refurbishedCount = value
+ end
+
+ def ThirdPartyProductInfo
+ @thirdPartyProductInfo
+ end
+
+ def ThirdPartyProductInfo=(value)
+ @thirdPartyProductInfo = value
+ end
+
+ def SalesRank
+ @salesRank
+ end
+
+ def SalesRank=(value)
+ @salesRank = value
+ end
+
+ def BrowseList
+ @browseList
+ end
+
+ def BrowseList=(value)
+ @browseList = value
+ end
+
+ def Media
+ @media
+ end
+
+ def Media=(value)
+ @media = value
+ end
+
+ def ReadingLevel
+ @readingLevel
+ end
+
+ def ReadingLevel=(value)
+ @readingLevel = value
+ end
+
+ def NumberOfPages
+ @numberOfPages
+ end
+
+ def NumberOfPages=(value)
+ @numberOfPages = value
+ end
+
+ def NumberOfIssues
+ @numberOfIssues
+ end
+
+ def NumberOfIssues=(value)
+ @numberOfIssues = value
+ end
+
+ def IssuesPerYear
+ @issuesPerYear
+ end
+
+ def IssuesPerYear=(value)
+ @issuesPerYear = value
+ end
+
+ def SubscriptionLength
+ @subscriptionLength
+ end
+
+ def SubscriptionLength=(value)
+ @subscriptionLength = value
+ end
+
+ def DeweyNumber
+ @deweyNumber
+ end
+
+ def DeweyNumber=(value)
+ @deweyNumber = value
+ end
+
+ def RunningTime
+ @runningTime
+ end
+
+ def RunningTime=(value)
+ @runningTime = value
+ end
+
+ def Publisher
+ @publisher
+ end
+
+ def Publisher=(value)
+ @publisher = value
+ end
+
+ def NumMedia
+ @numMedia
+ end
+
+ def NumMedia=(value)
+ @numMedia = value
+ end
+
+ def Isbn
+ @isbn
+ end
+
+ def Isbn=(value)
+ @isbn = value
+ end
+
+ def Features
+ @features
+ end
+
+ def Features=(value)
+ @features = value
+ end
+
+ def MpaaRating
+ @mpaaRating
+ end
+
+ def MpaaRating=(value)
+ @mpaaRating = value
+ end
+
+ def EsrbRating
+ @esrbRating
+ end
+
+ def EsrbRating=(value)
+ @esrbRating = value
+ end
+
+ def AgeGroup
+ @ageGroup
+ end
+
+ def AgeGroup=(value)
+ @ageGroup = value
+ end
+
+ def Availability
+ @availability
+ end
+
+ def Availability=(value)
+ @availability = value
+ end
+
+ def Upc
+ @upc
+ end
+
+ def Upc=(value)
+ @upc = value
+ end
+
+ def Tracks
+ @tracks
+ end
+
+ def Tracks=(value)
+ @tracks = value
+ end
+
+ def Accessories
+ @accessories
+ end
+
+ def Accessories=(value)
+ @accessories = value
+ end
+
+ def Platforms
+ @platforms
+ end
+
+ def Platforms=(value)
+ @platforms = value
+ end
+
+ def Encoding
+ @encoding
+ end
+
+ def Encoding=(value)
+ @encoding = value
+ end
+
+ def ProductDescription
+ @productDescription
+ end
+
+ def ProductDescription=(value)
+ @productDescription = value
+ end
+
+ def Reviews
+ @reviews
+ end
+
+ def Reviews=(value)
+ @reviews = value
+ end
+
+ def SimilarProducts
+ @similarProducts
+ end
+
+ def SimilarProducts=(value)
+ @similarProducts = value
+ end
+
+ def FeaturedProducts
+ @featuredProducts
+ end
+
+ def FeaturedProducts=(value)
+ @featuredProducts = value
+ end
+
+ def Lists
+ @lists
+ end
+
+ def Lists=(value)
+ @lists = value
+ end
+
+ def Status
+ @status
+ end
+
+ def Status=(value)
+ @status = value
+ end
+
+ def Variations
+ @variations
+ end
+
+ def Variations=(value)
+ @variations = value
+ end
+
+ def initialize(url = nil, asin = nil, productName = nil, catalog = nil, keyPhrases = nil, artists = nil, authors = nil, mpn = nil, starring = nil, directors = nil, theatricalReleaseDate = nil, releaseDate = nil, manufacturer = nil, distributor = nil, imageUrlSmall = nil, imageUrlMedium = nil, imageUrlLarge = nil, merchantId = nil, minPrice = nil, maxPrice = nil, minSalePrice = nil, maxSalePrice = nil, multiMerchant = nil, merchantSku = nil, listPrice = nil, ourPrice = nil, usedPrice = nil, refurbishedPrice = nil, collectiblePrice = nil, thirdPartyNewPrice = nil, numberOfOfferings = nil, thirdPartyNewCount = nil, usedCount = nil, collectibleCount = nil, refurbishedCount = nil, thirdPartyProductInfo = nil, salesRank = nil, browseList = nil, media = nil, readingLevel = nil, numberOfPages = nil, numberOfIssues = nil, issuesPerYear = nil, subscriptionLength = nil, deweyNumber = nil, runningTime = nil, publisher = nil, numMedia = nil, isbn = nil, features = nil, mpaaRating = nil, esrbRating = nil, ageGroup = nil, availability = nil, upc = nil, tracks = nil, accessories = nil, platforms = nil, encoding = nil, productDescription = nil, reviews = nil, similarProducts = nil, featuredProducts = nil, lists = nil, status = nil, variations = nil)
+ @url = url
+ @asin = asin
+ @productName = productName
+ @catalog = catalog
+ @keyPhrases = keyPhrases
+ @artists = artists
+ @authors = authors
+ @mpn = mpn
+ @starring = starring
+ @directors = directors
+ @theatricalReleaseDate = theatricalReleaseDate
+ @releaseDate = releaseDate
+ @manufacturer = manufacturer
+ @distributor = distributor
+ @imageUrlSmall = imageUrlSmall
+ @imageUrlMedium = imageUrlMedium
+ @imageUrlLarge = imageUrlLarge
+ @merchantId = merchantId
+ @minPrice = minPrice
+ @maxPrice = maxPrice
+ @minSalePrice = minSalePrice
+ @maxSalePrice = maxSalePrice
+ @multiMerchant = multiMerchant
+ @merchantSku = merchantSku
+ @listPrice = listPrice
+ @ourPrice = ourPrice
+ @usedPrice = usedPrice
+ @refurbishedPrice = refurbishedPrice
+ @collectiblePrice = collectiblePrice
+ @thirdPartyNewPrice = thirdPartyNewPrice
+ @numberOfOfferings = numberOfOfferings
+ @thirdPartyNewCount = thirdPartyNewCount
+ @usedCount = usedCount
+ @collectibleCount = collectibleCount
+ @refurbishedCount = refurbishedCount
+ @thirdPartyProductInfo = thirdPartyProductInfo
+ @salesRank = salesRank
+ @browseList = browseList
+ @media = media
+ @readingLevel = readingLevel
+ @numberOfPages = numberOfPages
+ @numberOfIssues = numberOfIssues
+ @issuesPerYear = issuesPerYear
+ @subscriptionLength = subscriptionLength
+ @deweyNumber = deweyNumber
+ @runningTime = runningTime
+ @publisher = publisher
+ @numMedia = numMedia
+ @isbn = isbn
+ @features = features
+ @mpaaRating = mpaaRating
+ @esrbRating = esrbRating
+ @ageGroup = ageGroup
+ @availability = availability
+ @upc = upc
+ @tracks = tracks
+ @accessories = accessories
+ @platforms = platforms
+ @encoding = encoding
+ @productDescription = productDescription
+ @reviews = reviews
+ @similarProducts = similarProducts
+ @featuredProducts = featuredProducts
+ @lists = lists
+ @status = status
+ @variations = variations
+ end
+end
+
+# http://soap.amazon.com
+class KeyPhraseArray < Array
+ @@schema_type = "KeyPhraseArray"
+ @@schema_ns = "http://soap.amazon.com"
+end
+
+# http://soap.amazon.com
+class KeyPhrase
+ @@schema_type = "KeyPhrase"
+ @@schema_ns = "http://soap.amazon.com"
+
+ def KeyPhrase
+ @keyPhrase
+ end
+
+ def KeyPhrase=(value)
+ @keyPhrase = value
+ end
+
+ def Type
+ @type
+ end
+
+ def Type=(value)
+ @type = value
+ end
+
+ def initialize(keyPhrase = nil, type = nil)
+ @keyPhrase = keyPhrase
+ @type = type
+ end
+end
+
+# http://soap.amazon.com
+class ArtistArray < Array
+ @@schema_type = "ArtistArray"
+ @@schema_ns = "http://soap.amazon.com"
+end
+
+# http://soap.amazon.com
+class AuthorArray < Array
+ @@schema_type = "AuthorArray"
+ @@schema_ns = "http://soap.amazon.com"
+end
+
+# http://soap.amazon.com
+class StarringArray < Array
+ @@schema_type = "StarringArray"
+ @@schema_ns = "http://soap.amazon.com"
+end
+
+# http://soap.amazon.com
+class DirectorArray < Array
+ @@schema_type = "DirectorArray"
+ @@schema_ns = "http://soap.amazon.com"
+end
+
+# http://soap.amazon.com
+class BrowseNodeArray < Array
+ @@schema_type = "BrowseNodeArray"
+ @@schema_ns = "http://soap.amazon.com"
+end
+
+# http://soap.amazon.com
+class BrowseNode
+ @@schema_type = "BrowseNode"
+ @@schema_ns = "http://soap.amazon.com"
+
+ def BrowseId
+ @browseId
+ end
+
+ def BrowseId=(value)
+ @browseId = value
+ end
+
+ def BrowseName
+ @browseName
+ end
+
+ def BrowseName=(value)
+ @browseName = value
+ end
+
+ def initialize(browseId = nil, browseName = nil)
+ @browseId = browseId
+ @browseName = browseName
+ end
+end
+
+# http://soap.amazon.com
+class FeaturesArray < Array
+ @@schema_type = "FeaturesArray"
+ @@schema_ns = "http://soap.amazon.com"
+end
+
+# http://soap.amazon.com
+class TrackArray < Array
+ @@schema_type = "TrackArray"
+ @@schema_ns = "http://soap.amazon.com"
+end
+
+# http://soap.amazon.com
+class Track
+ @@schema_type = "Track"
+ @@schema_ns = "http://soap.amazon.com"
+
+ def TrackName
+ @trackName
+ end
+
+ def TrackName=(value)
+ @trackName = value
+ end
+
+ def ByArtist
+ @byArtist
+ end
+
+ def ByArtist=(value)
+ @byArtist = value
+ end
+
+ def initialize(trackName = nil, byArtist = nil)
+ @trackName = trackName
+ @byArtist = byArtist
+ end
+end
+
+# http://soap.amazon.com
+class AccessoryArray < Array
+ @@schema_type = "AccessoryArray"
+ @@schema_ns = "http://soap.amazon.com"
+end
+
+# http://soap.amazon.com
+class PlatformArray < Array
+ @@schema_type = "PlatformArray"
+ @@schema_ns = "http://soap.amazon.com"
+end
+
+# http://soap.amazon.com
+class Reviews
+ @@schema_type = "Reviews"
+ @@schema_ns = "http://soap.amazon.com"
+
+ def AvgCustomerRating
+ @avgCustomerRating
+ end
+
+ def AvgCustomerRating=(value)
+ @avgCustomerRating = value
+ end
+
+ def TotalCustomerReviews
+ @totalCustomerReviews
+ end
+
+ def TotalCustomerReviews=(value)
+ @totalCustomerReviews = value
+ end
+
+ def CustomerReviews
+ @customerReviews
+ end
+
+ def CustomerReviews=(value)
+ @customerReviews = value
+ end
+
+ def initialize(avgCustomerRating = nil, totalCustomerReviews = nil, customerReviews = nil)
+ @avgCustomerRating = avgCustomerRating
+ @totalCustomerReviews = totalCustomerReviews
+ @customerReviews = customerReviews
+ end
+end
+
+# http://soap.amazon.com
+class CustomerReviewArray < Array
+ @@schema_type = "CustomerReviewArray"
+ @@schema_ns = "http://soap.amazon.com"
+end
+
+# http://soap.amazon.com
+class CustomerReview
+ @@schema_type = "CustomerReview"
+ @@schema_ns = "http://soap.amazon.com"
+
+ def Rating
+ @rating
+ end
+
+ def Rating=(value)
+ @rating = value
+ end
+
+ def Date
+ @date
+ end
+
+ def Date=(value)
+ @date = value
+ end
+
+ def Summary
+ @summary
+ end
+
+ def Summary=(value)
+ @summary = value
+ end
+
+ def Comment
+ @comment
+ end
+
+ def Comment=(value)
+ @comment = value
+ end
+
+ def initialize(rating = nil, date = nil, summary = nil, comment = nil)
+ @rating = rating
+ @date = date
+ @summary = summary
+ @comment = comment
+ end
+end
+
+# http://soap.amazon.com
+class SimilarProductsArray < Array
+ @@schema_type = "SimilarProductsArray"
+ @@schema_ns = "http://soap.amazon.com"
+end
+
+# http://soap.amazon.com
+class FeaturedProductsArray < Array
+ @@schema_type = "FeaturedProductsArray"
+ @@schema_ns = "http://soap.amazon.com"
+end
+
+# http://soap.amazon.com
+class FeaturedProduct
+ @@schema_type = "FeaturedProduct"
+ @@schema_ns = "http://soap.amazon.com"
+
+ def Asin
+ @asin
+ end
+
+ def Asin=(value)
+ @asin = value
+ end
+
+ def Comment
+ @comment
+ end
+
+ def Comment=(value)
+ @comment = value
+ end
+
+ def initialize(asin = nil, comment = nil)
+ @asin = asin
+ @comment = comment
+ end
+end
+
+# http://soap.amazon.com
+class ListArray < Array
+ @@schema_type = "ListArray"
+ @@schema_ns = "http://soap.amazon.com"
+end
+
+# http://soap.amazon.com
+class VariationArray < Array
+ @@schema_type = "VariationArray"
+ @@schema_ns = "http://soap.amazon.com"
+end
+
+# http://soap.amazon.com
+class Variation
+ @@schema_type = "Variation"
+ @@schema_ns = "http://soap.amazon.com"
+
+ def Asin
+ @asin
+ end
+
+ def Asin=(value)
+ @asin = value
+ end
+
+ def ClothingSize
+ @clothingSize
+ end
+
+ def ClothingSize=(value)
+ @clothingSize = value
+ end
+
+ def ClothingColor
+ @clothingColor
+ end
+
+ def ClothingColor=(value)
+ @clothingColor = value
+ end
+
+ def Price
+ @price
+ end
+
+ def Price=(value)
+ @price = value
+ end
+
+ def SalePrice
+ @salePrice
+ end
+
+ def SalePrice=(value)
+ @salePrice = value
+ end
+
+ def Availability
+ @availability
+ end
+
+ def Availability=(value)
+ @availability = value
+ end
+
+ def MultiMerchant
+ @multiMerchant
+ end
+
+ def MultiMerchant=(value)
+ @multiMerchant = value
+ end
+
+ def MerchantSku
+ @merchantSku
+ end
+
+ def MerchantSku=(value)
+ @merchantSku = value
+ end
+
+ def initialize(asin = nil, clothingSize = nil, clothingColor = nil, price = nil, salePrice = nil, availability = nil, multiMerchant = nil, merchantSku = nil)
+ @asin = asin
+ @clothingSize = clothingSize
+ @clothingColor = clothingColor
+ @price = price
+ @salePrice = salePrice
+ @availability = availability
+ @multiMerchant = multiMerchant
+ @merchantSku = merchantSku
+ end
+end
+
+# http://soap.amazon.com
+class MarketplaceSearch
+ @@schema_type = "MarketplaceSearch"
+ @@schema_ns = "http://soap.amazon.com"
+
+ def MarketplaceSearchDetails
+ @marketplaceSearchDetails
+ end
+
+ def MarketplaceSearchDetails=(value)
+ @marketplaceSearchDetails = value
+ end
+
+ def initialize(marketplaceSearchDetails = nil)
+ @marketplaceSearchDetails = marketplaceSearchDetails
+ end
+end
+
+# http://soap.amazon.com
+class SellerProfile
+ @@schema_type = "SellerProfile"
+ @@schema_ns = "http://soap.amazon.com"
+
+ def SellerProfileDetails
+ @sellerProfileDetails
+ end
+
+ def SellerProfileDetails=(value)
+ @sellerProfileDetails = value
+ end
+
+ def initialize(sellerProfileDetails = nil)
+ @sellerProfileDetails = sellerProfileDetails
+ end
+end
+
+# http://soap.amazon.com
+class SellerSearch
+ @@schema_type = "SellerSearch"
+ @@schema_ns = "http://soap.amazon.com"
+
+ def SellerSearchDetails
+ @sellerSearchDetails
+ end
+
+ def SellerSearchDetails=(value)
+ @sellerSearchDetails = value
+ end
+
+ def initialize(sellerSearchDetails = nil)
+ @sellerSearchDetails = sellerSearchDetails
+ end
+end
+
+# http://soap.amazon.com
+class MarketplaceSearchDetails
+ @@schema_type = "MarketplaceSearchDetails"
+ @@schema_ns = "http://soap.amazon.com"
+
+ def NumberOfOpenListings
+ @numberOfOpenListings
+ end
+
+ def NumberOfOpenListings=(value)
+ @numberOfOpenListings = value
+ end
+
+ def ListingProductInfo
+ @listingProductInfo
+ end
+
+ def ListingProductInfo=(value)
+ @listingProductInfo = value
+ end
+
+ def initialize(numberOfOpenListings = nil, listingProductInfo = nil)
+ @numberOfOpenListings = numberOfOpenListings
+ @listingProductInfo = listingProductInfo
+ end
+end
+
+# http://soap.amazon.com
+class MarketplaceSearchDetailsArray < Array
+ @@schema_type = "MarketplaceSearchDetailsArray"
+ @@schema_ns = "http://soap.amazon.com"
+end
+
+# http://soap.amazon.com
+class SellerProfileDetails
+ @@schema_type = "SellerProfileDetails"
+ @@schema_ns = "http://soap.amazon.com"
+
+ def SellerNickname
+ @sellerNickname
+ end
+
+ def SellerNickname=(value)
+ @sellerNickname = value
+ end
+
+ def OverallFeedbackRating
+ @overallFeedbackRating
+ end
+
+ def OverallFeedbackRating=(value)
+ @overallFeedbackRating = value
+ end
+
+ def NumberOfFeedback
+ @numberOfFeedback
+ end
+
+ def NumberOfFeedback=(value)
+ @numberOfFeedback = value
+ end
+
+ def NumberOfCanceledBids
+ @numberOfCanceledBids
+ end
+
+ def NumberOfCanceledBids=(value)
+ @numberOfCanceledBids = value
+ end
+
+ def NumberOfCanceledAuctions
+ @numberOfCanceledAuctions
+ end
+
+ def NumberOfCanceledAuctions=(value)
+ @numberOfCanceledAuctions = value
+ end
+
+ def StoreId
+ @storeId
+ end
+
+ def StoreId=(value)
+ @storeId = value
+ end
+
+ def StoreName
+ @storeName
+ end
+
+ def StoreName=(value)
+ @storeName = value
+ end
+
+ def SellerFeedback
+ @sellerFeedback
+ end
+
+ def SellerFeedback=(value)
+ @sellerFeedback = value
+ end
+
+ def initialize(sellerNickname = nil, overallFeedbackRating = nil, numberOfFeedback = nil, numberOfCanceledBids = nil, numberOfCanceledAuctions = nil, storeId = nil, storeName = nil, sellerFeedback = nil)
+ @sellerNickname = sellerNickname
+ @overallFeedbackRating = overallFeedbackRating
+ @numberOfFeedback = numberOfFeedback
+ @numberOfCanceledBids = numberOfCanceledBids
+ @numberOfCanceledAuctions = numberOfCanceledAuctions
+ @storeId = storeId
+ @storeName = storeName
+ @sellerFeedback = sellerFeedback
+ end
+end
+
+# http://soap.amazon.com
+class SellerProfileDetailsArray < Array
+ @@schema_type = "SellerProfileDetailsArray"
+ @@schema_ns = "http://soap.amazon.com"
+end
+
+# http://soap.amazon.com
+class SellerSearchDetails
+ @@schema_type = "SellerSearchDetails"
+ @@schema_ns = "http://soap.amazon.com"
+
+ def SellerNickname
+ @sellerNickname
+ end
+
+ def SellerNickname=(value)
+ @sellerNickname = value
+ end
+
+ def StoreId
+ @storeId
+ end
+
+ def StoreId=(value)
+ @storeId = value
+ end
+
+ def StoreName
+ @storeName
+ end
+
+ def StoreName=(value)
+ @storeName = value
+ end
+
+ def NumberOfOpenListings
+ @numberOfOpenListings
+ end
+
+ def NumberOfOpenListings=(value)
+ @numberOfOpenListings = value
+ end
+
+ def ListingProductInfo
+ @listingProductInfo
+ end
+
+ def ListingProductInfo=(value)
+ @listingProductInfo = value
+ end
+
+ def initialize(sellerNickname = nil, storeId = nil, storeName = nil, numberOfOpenListings = nil, listingProductInfo = nil)
+ @sellerNickname = sellerNickname
+ @storeId = storeId
+ @storeName = storeName
+ @numberOfOpenListings = numberOfOpenListings
+ @listingProductInfo = listingProductInfo
+ end
+end
+
+# http://soap.amazon.com
+class SellerSearchDetailsArray < Array
+ @@schema_type = "SellerSearchDetailsArray"
+ @@schema_ns = "http://soap.amazon.com"
+end
+
+# http://soap.amazon.com
+class ListingProductInfo
+ @@schema_type = "ListingProductInfo"
+ @@schema_ns = "http://soap.amazon.com"
+
+ def ListingProductDetails
+ @listingProductDetails
+ end
+
+ def ListingProductDetails=(value)
+ @listingProductDetails = value
+ end
+
+ def initialize(listingProductDetails = nil)
+ @listingProductDetails = listingProductDetails
+ end
+end
+
+# http://soap.amazon.com
+class ListingProductDetailsArray < Array
+ @@schema_type = "ListingProductDetailsArray"
+ @@schema_ns = "http://soap.amazon.com"
+end
+
+# http://soap.amazon.com
+class ListingProductDetails
+ @@schema_type = "ListingProductDetails"
+ @@schema_ns = "http://soap.amazon.com"
+
+ def ExchangeId
+ @exchangeId
+ end
+
+ def ExchangeId=(value)
+ @exchangeId = value
+ end
+
+ def ListingId
+ @listingId
+ end
+
+ def ListingId=(value)
+ @listingId = value
+ end
+
+ def ExchangeTitle
+ @exchangeTitle
+ end
+
+ def ExchangeTitle=(value)
+ @exchangeTitle = value
+ end
+
+ def ExchangeDescription
+ @exchangeDescription
+ end
+
+ def ExchangeDescription=(value)
+ @exchangeDescription = value
+ end
+
+ def ExchangePrice
+ @exchangePrice
+ end
+
+ def ExchangePrice=(value)
+ @exchangePrice = value
+ end
+
+ def ExchangeAsin
+ @exchangeAsin
+ end
+
+ def ExchangeAsin=(value)
+ @exchangeAsin = value
+ end
+
+ def ExchangeEndDate
+ @exchangeEndDate
+ end
+
+ def ExchangeEndDate=(value)
+ @exchangeEndDate = value
+ end
+
+ def ExchangeTinyImage
+ @exchangeTinyImage
+ end
+
+ def ExchangeTinyImage=(value)
+ @exchangeTinyImage = value
+ end
+
+ def ExchangeSellerId
+ @exchangeSellerId
+ end
+
+ def ExchangeSellerId=(value)
+ @exchangeSellerId = value
+ end
+
+ def ExchangeSellerNickname
+ @exchangeSellerNickname
+ end
+
+ def ExchangeSellerNickname=(value)
+ @exchangeSellerNickname = value
+ end
+
+ def ExchangeStartDate
+ @exchangeStartDate
+ end
+
+ def ExchangeStartDate=(value)
+ @exchangeStartDate = value
+ end
+
+ def ExchangeStatus
+ @exchangeStatus
+ end
+
+ def ExchangeStatus=(value)
+ @exchangeStatus = value
+ end
+
+ def ExchangeQuantity
+ @exchangeQuantity
+ end
+
+ def ExchangeQuantity=(value)
+ @exchangeQuantity = value
+ end
+
+ def ExchangeQuantityAllocated
+ @exchangeQuantityAllocated
+ end
+
+ def ExchangeQuantityAllocated=(value)
+ @exchangeQuantityAllocated = value
+ end
+
+ def ExchangeFeaturedCategory
+ @exchangeFeaturedCategory
+ end
+
+ def ExchangeFeaturedCategory=(value)
+ @exchangeFeaturedCategory = value
+ end
+
+ def ExchangeCondition
+ @exchangeCondition
+ end
+
+ def ExchangeCondition=(value)
+ @exchangeCondition = value
+ end
+
+ def ExchangeConditionType
+ @exchangeConditionType
+ end
+
+ def ExchangeConditionType=(value)
+ @exchangeConditionType = value
+ end
+
+ def ExchangeAvailability
+ @exchangeAvailability
+ end
+
+ def ExchangeAvailability=(value)
+ @exchangeAvailability = value
+ end
+
+ def ExchangeOfferingType
+ @exchangeOfferingType
+ end
+
+ def ExchangeOfferingType=(value)
+ @exchangeOfferingType = value
+ end
+
+ def ExchangeSellerState
+ @exchangeSellerState
+ end
+
+ def ExchangeSellerState=(value)
+ @exchangeSellerState = value
+ end
+
+ def ExchangeSellerCountry
+ @exchangeSellerCountry
+ end
+
+ def ExchangeSellerCountry=(value)
+ @exchangeSellerCountry = value
+ end
+
+ def ExchangeSellerRating
+ @exchangeSellerRating
+ end
+
+ def ExchangeSellerRating=(value)
+ @exchangeSellerRating = value
+ end
+
+ def initialize(exchangeId = nil, listingId = nil, exchangeTitle = nil, exchangeDescription = nil, exchangePrice = nil, exchangeAsin = nil, exchangeEndDate = nil, exchangeTinyImage = nil, exchangeSellerId = nil, exchangeSellerNickname = nil, exchangeStartDate = nil, exchangeStatus = nil, exchangeQuantity = nil, exchangeQuantityAllocated = nil, exchangeFeaturedCategory = nil, exchangeCondition = nil, exchangeConditionType = nil, exchangeAvailability = nil, exchangeOfferingType = nil, exchangeSellerState = nil, exchangeSellerCountry = nil, exchangeSellerRating = nil)
+ @exchangeId = exchangeId
+ @listingId = listingId
+ @exchangeTitle = exchangeTitle
+ @exchangeDescription = exchangeDescription
+ @exchangePrice = exchangePrice
+ @exchangeAsin = exchangeAsin
+ @exchangeEndDate = exchangeEndDate
+ @exchangeTinyImage = exchangeTinyImage
+ @exchangeSellerId = exchangeSellerId
+ @exchangeSellerNickname = exchangeSellerNickname
+ @exchangeStartDate = exchangeStartDate
+ @exchangeStatus = exchangeStatus
+ @exchangeQuantity = exchangeQuantity
+ @exchangeQuantityAllocated = exchangeQuantityAllocated
+ @exchangeFeaturedCategory = exchangeFeaturedCategory
+ @exchangeCondition = exchangeCondition
+ @exchangeConditionType = exchangeConditionType
+ @exchangeAvailability = exchangeAvailability
+ @exchangeOfferingType = exchangeOfferingType
+ @exchangeSellerState = exchangeSellerState
+ @exchangeSellerCountry = exchangeSellerCountry
+ @exchangeSellerRating = exchangeSellerRating
+ end
+end
+
+# http://soap.amazon.com
+class SellerFeedback
+ @@schema_type = "SellerFeedback"
+ @@schema_ns = "http://soap.amazon.com"
+
+ def Feedback
+ @feedback
+ end
+
+ def Feedback=(value)
+ @feedback = value
+ end
+
+ def initialize(feedback = nil)
+ @feedback = feedback
+ end
+end
+
+# http://soap.amazon.com
+class FeedbackArray < Array
+ @@schema_type = "FeedbackArray"
+ @@schema_ns = "http://soap.amazon.com"
+end
+
+# http://soap.amazon.com
+class Feedback
+ @@schema_type = "Feedback"
+ @@schema_ns = "http://soap.amazon.com"
+
+ def FeedbackRating
+ @feedbackRating
+ end
+
+ def FeedbackRating=(value)
+ @feedbackRating = value
+ end
+
+ def FeedbackComments
+ @feedbackComments
+ end
+
+ def FeedbackComments=(value)
+ @feedbackComments = value
+ end
+
+ def FeedbackDate
+ @feedbackDate
+ end
+
+ def FeedbackDate=(value)
+ @feedbackDate = value
+ end
+
+ def FeedbackRater
+ @feedbackRater
+ end
+
+ def FeedbackRater=(value)
+ @feedbackRater = value
+ end
+
+ def initialize(feedbackRating = nil, feedbackComments = nil, feedbackDate = nil, feedbackRater = nil)
+ @feedbackRating = feedbackRating
+ @feedbackComments = feedbackComments
+ @feedbackDate = feedbackDate
+ @feedbackRater = feedbackRater
+ end
+end
+
+# http://soap.amazon.com
+class ThirdPartyProductInfo
+ @@schema_type = "ThirdPartyProductInfo"
+ @@schema_ns = "http://soap.amazon.com"
+
+ def ThirdPartyProductDetails
+ @thirdPartyProductDetails
+ end
+
+ def ThirdPartyProductDetails=(value)
+ @thirdPartyProductDetails = value
+ end
+
+ def initialize(thirdPartyProductDetails = nil)
+ @thirdPartyProductDetails = thirdPartyProductDetails
+ end
+end
+
+# http://soap.amazon.com
+class ThirdPartyProductDetailsArray < Array
+ @@schema_type = "ThirdPartyProductDetailsArray"
+ @@schema_ns = "http://soap.amazon.com"
+end
+
+# http://soap.amazon.com
+class ThirdPartyProductDetails
+ @@schema_type = "ThirdPartyProductDetails"
+ @@schema_ns = "http://soap.amazon.com"
+
+ def OfferingType
+ @offeringType
+ end
+
+ def OfferingType=(value)
+ @offeringType = value
+ end
+
+ def SellerId
+ @sellerId
+ end
+
+ def SellerId=(value)
+ @sellerId = value
+ end
+
+ def SellerNickname
+ @sellerNickname
+ end
+
+ def SellerNickname=(value)
+ @sellerNickname = value
+ end
+
+ def ExchangeId
+ @exchangeId
+ end
+
+ def ExchangeId=(value)
+ @exchangeId = value
+ end
+
+ def OfferingPrice
+ @offeringPrice
+ end
+
+ def OfferingPrice=(value)
+ @offeringPrice = value
+ end
+
+ def Condition
+ @condition
+ end
+
+ def Condition=(value)
+ @condition = value
+ end
+
+ def ConditionType
+ @conditionType
+ end
+
+ def ConditionType=(value)
+ @conditionType = value
+ end
+
+ def ExchangeAvailability
+ @exchangeAvailability
+ end
+
+ def ExchangeAvailability=(value)
+ @exchangeAvailability = value
+ end
+
+ def SellerCountry
+ @sellerCountry
+ end
+
+ def SellerCountry=(value)
+ @sellerCountry = value
+ end
+
+ def SellerState
+ @sellerState
+ end
+
+ def SellerState=(value)
+ @sellerState = value
+ end
+
+ def ShipComments
+ @shipComments
+ end
+
+ def ShipComments=(value)
+ @shipComments = value
+ end
+
+ def SellerRating
+ @sellerRating
+ end
+
+ def SellerRating=(value)
+ @sellerRating = value
+ end
+
+ def initialize(offeringType = nil, sellerId = nil, sellerNickname = nil, exchangeId = nil, offeringPrice = nil, condition = nil, conditionType = nil, exchangeAvailability = nil, sellerCountry = nil, sellerState = nil, shipComments = nil, sellerRating = nil)
+ @offeringType = offeringType
+ @sellerId = sellerId
+ @sellerNickname = sellerNickname
+ @exchangeId = exchangeId
+ @offeringPrice = offeringPrice
+ @condition = condition
+ @conditionType = conditionType
+ @exchangeAvailability = exchangeAvailability
+ @sellerCountry = sellerCountry
+ @sellerState = sellerState
+ @shipComments = shipComments
+ @sellerRating = sellerRating
+ end
+end
+
+# http://soap.amazon.com
+class KeywordRequest
+ @@schema_type = "KeywordRequest"
+ @@schema_ns = "http://soap.amazon.com"
+
+ attr_accessor :keyword
+ attr_accessor :page
+ attr_accessor :mode
+ attr_accessor :tag
+ attr_accessor :type
+ attr_accessor :devtag
+ attr_accessor :sort
+ attr_accessor :locale
+ attr_accessor :price
+
+ def initialize(keyword = nil, page = nil, mode = nil, tag = nil, type = nil, devtag = nil, sort = nil, locale = nil, price = nil)
+ @keyword = keyword
+ @page = page
+ @mode = mode
+ @tag = tag
+ @type = type
+ @devtag = devtag
+ @sort = sort
+ @locale = locale
+ @price = price
+ end
+end
+
+# http://soap.amazon.com
+class TextStreamRequest
+ @@schema_type = "TextStreamRequest"
+ @@schema_ns = "http://soap.amazon.com"
+
+ attr_accessor :textStream
+ attr_accessor :page
+ attr_accessor :mode
+ attr_accessor :tag
+ attr_accessor :type
+ attr_accessor :devtag
+ attr_accessor :sort
+ attr_accessor :locale
+ attr_accessor :price
+
+ def initialize(textStream = nil, page = nil, mode = nil, tag = nil, type = nil, devtag = nil, sort = nil, locale = nil, price = nil)
+ @textStream = textStream
+ @page = page
+ @mode = mode
+ @tag = tag
+ @type = type
+ @devtag = devtag
+ @sort = sort
+ @locale = locale
+ @price = price
+ end
+end
+
+# http://soap.amazon.com
+class PowerRequest
+ @@schema_type = "PowerRequest"
+ @@schema_ns = "http://soap.amazon.com"
+
+ attr_accessor :power
+ attr_accessor :page
+ attr_accessor :mode
+ attr_accessor :tag
+ attr_accessor :type
+ attr_accessor :devtag
+ attr_accessor :sort
+ attr_accessor :locale
+
+ def initialize(power = nil, page = nil, mode = nil, tag = nil, type = nil, devtag = nil, sort = nil, locale = nil)
+ @power = power
+ @page = page
+ @mode = mode
+ @tag = tag
+ @type = type
+ @devtag = devtag
+ @sort = sort
+ @locale = locale
+ end
+end
+
+# http://soap.amazon.com
+class BrowseNodeRequest
+ @@schema_type = "BrowseNodeRequest"
+ @@schema_ns = "http://soap.amazon.com"
+
+ attr_accessor :browse_node
+ attr_accessor :page
+ attr_accessor :mode
+ attr_accessor :tag
+ attr_accessor :type
+ attr_accessor :devtag
+ attr_accessor :sort
+ attr_accessor :locale
+ attr_accessor :keywords
+ attr_accessor :price
+
+ def initialize(browse_node = nil, page = nil, mode = nil, tag = nil, type = nil, devtag = nil, sort = nil, locale = nil, keywords = nil, price = nil)
+ @browse_node = browse_node
+ @page = page
+ @mode = mode
+ @tag = tag
+ @type = type
+ @devtag = devtag
+ @sort = sort
+ @locale = locale
+ @keywords = keywords
+ @price = price
+ end
+end
+
+# http://soap.amazon.com
+class AsinRequest
+ @@schema_type = "AsinRequest"
+ @@schema_ns = "http://soap.amazon.com"
+
+ attr_accessor :asin
+ attr_accessor :tag
+ attr_accessor :type
+ attr_accessor :devtag
+ attr_accessor :offer
+ attr_accessor :offerpage
+ attr_accessor :locale
+ attr_accessor :mode
+
+ def initialize(asin = nil, tag = nil, type = nil, devtag = nil, offer = nil, offerpage = nil, locale = nil, mode = nil)
+ @asin = asin
+ @tag = tag
+ @type = type
+ @devtag = devtag
+ @offer = offer
+ @offerpage = offerpage
+ @locale = locale
+ @mode = mode
+ end
+end
+
+# http://soap.amazon.com
+class BlendedRequest
+ @@schema_type = "BlendedRequest"
+ @@schema_ns = "http://soap.amazon.com"
+
+ attr_accessor :blended
+ attr_accessor :tag
+ attr_accessor :type
+ attr_accessor :devtag
+ attr_accessor :locale
+
+ def initialize(blended = nil, tag = nil, type = nil, devtag = nil, locale = nil)
+ @blended = blended
+ @tag = tag
+ @type = type
+ @devtag = devtag
+ @locale = locale
+ end
+end
+
+# http://soap.amazon.com
+class UpcRequest
+ @@schema_type = "UpcRequest"
+ @@schema_ns = "http://soap.amazon.com"
+
+ attr_accessor :upc
+ attr_accessor :mode
+ attr_accessor :tag
+ attr_accessor :type
+ attr_accessor :devtag
+ attr_accessor :sort
+ attr_accessor :locale
+
+ def initialize(upc = nil, mode = nil, tag = nil, type = nil, devtag = nil, sort = nil, locale = nil)
+ @upc = upc
+ @mode = mode
+ @tag = tag
+ @type = type
+ @devtag = devtag
+ @sort = sort
+ @locale = locale
+ end
+end
+
+# http://soap.amazon.com
+class SkuRequest
+ @@schema_type = "SkuRequest"
+ @@schema_ns = "http://soap.amazon.com"
+
+ attr_accessor :sku
+ attr_accessor :mode
+ attr_accessor :tag
+ attr_accessor :type
+ attr_accessor :devtag
+ attr_accessor :merchant_id
+ attr_accessor :keywords
+ attr_accessor :sort
+ attr_accessor :locale
+
+ def initialize(sku = nil, mode = nil, tag = nil, type = nil, devtag = nil, merchant_id = nil, keywords = nil, sort = nil, locale = nil)
+ @sku = sku
+ @mode = mode
+ @tag = tag
+ @type = type
+ @devtag = devtag
+ @merchant_id = merchant_id
+ @keywords = keywords
+ @sort = sort
+ @locale = locale
+ end
+end
+
+# http://soap.amazon.com
+class ArtistRequest
+ @@schema_type = "ArtistRequest"
+ @@schema_ns = "http://soap.amazon.com"
+
+ attr_accessor :artist
+ attr_accessor :page
+ attr_accessor :mode
+ attr_accessor :tag
+ attr_accessor :type
+ attr_accessor :devtag
+ attr_accessor :sort
+ attr_accessor :locale
+ attr_accessor :keywords
+ attr_accessor :price
+
+ def initialize(artist = nil, page = nil, mode = nil, tag = nil, type = nil, devtag = nil, sort = nil, locale = nil, keywords = nil, price = nil)
+ @artist = artist
+ @page = page
+ @mode = mode
+ @tag = tag
+ @type = type
+ @devtag = devtag
+ @sort = sort
+ @locale = locale
+ @keywords = keywords
+ @price = price
+ end
+end
+
+# http://soap.amazon.com
+class AuthorRequest
+ @@schema_type = "AuthorRequest"
+ @@schema_ns = "http://soap.amazon.com"
+
+ attr_accessor :author
+ attr_accessor :page
+ attr_accessor :mode
+ attr_accessor :tag
+ attr_accessor :type
+ attr_accessor :devtag
+ attr_accessor :sort
+ attr_accessor :locale
+ attr_accessor :keywords
+ attr_accessor :price
+
+ def initialize(author = nil, page = nil, mode = nil, tag = nil, type = nil, devtag = nil, sort = nil, locale = nil, keywords = nil, price = nil)
+ @author = author
+ @page = page
+ @mode = mode
+ @tag = tag
+ @type = type
+ @devtag = devtag
+ @sort = sort
+ @locale = locale
+ @keywords = keywords
+ @price = price
+ end
+end
+
+# http://soap.amazon.com
+class ActorRequest
+ @@schema_type = "ActorRequest"
+ @@schema_ns = "http://soap.amazon.com"
+
+ attr_accessor :actor
+ attr_accessor :page
+ attr_accessor :mode
+ attr_accessor :tag
+ attr_accessor :type
+ attr_accessor :devtag
+ attr_accessor :sort
+ attr_accessor :locale
+ attr_accessor :keywords
+ attr_accessor :price
+
+ def initialize(actor = nil, page = nil, mode = nil, tag = nil, type = nil, devtag = nil, sort = nil, locale = nil, keywords = nil, price = nil)
+ @actor = actor
+ @page = page
+ @mode = mode
+ @tag = tag
+ @type = type
+ @devtag = devtag
+ @sort = sort
+ @locale = locale
+ @keywords = keywords
+ @price = price
+ end
+end
+
+# http://soap.amazon.com
+class DirectorRequest
+ @@schema_type = "DirectorRequest"
+ @@schema_ns = "http://soap.amazon.com"
+
+ attr_accessor :director
+ attr_accessor :page
+ attr_accessor :mode
+ attr_accessor :tag
+ attr_accessor :type
+ attr_accessor :devtag
+ attr_accessor :sort
+ attr_accessor :locale
+ attr_accessor :keywords
+ attr_accessor :price
+
+ def initialize(director = nil, page = nil, mode = nil, tag = nil, type = nil, devtag = nil, sort = nil, locale = nil, keywords = nil, price = nil)
+ @director = director
+ @page = page
+ @mode = mode
+ @tag = tag
+ @type = type
+ @devtag = devtag
+ @sort = sort
+ @locale = locale
+ @keywords = keywords
+ @price = price
+ end
+end
+
+# http://soap.amazon.com
+class ExchangeRequest
+ @@schema_type = "ExchangeRequest"
+ @@schema_ns = "http://soap.amazon.com"
+
+ attr_accessor :exchange_id
+ attr_accessor :tag
+ attr_accessor :type
+ attr_accessor :devtag
+ attr_accessor :locale
+
+ def initialize(exchange_id = nil, tag = nil, type = nil, devtag = nil, locale = nil)
+ @exchange_id = exchange_id
+ @tag = tag
+ @type = type
+ @devtag = devtag
+ @locale = locale
+ end
+end
+
+# http://soap.amazon.com
+class ManufacturerRequest
+ @@schema_type = "ManufacturerRequest"
+ @@schema_ns = "http://soap.amazon.com"
+
+ attr_accessor :manufacturer
+ attr_accessor :page
+ attr_accessor :mode
+ attr_accessor :tag
+ attr_accessor :type
+ attr_accessor :devtag
+ attr_accessor :sort
+ attr_accessor :locale
+ attr_accessor :keywords
+ attr_accessor :price
+
+ def initialize(manufacturer = nil, page = nil, mode = nil, tag = nil, type = nil, devtag = nil, sort = nil, locale = nil, keywords = nil, price = nil)
+ @manufacturer = manufacturer
+ @page = page
+ @mode = mode
+ @tag = tag
+ @type = type
+ @devtag = devtag
+ @sort = sort
+ @locale = locale
+ @keywords = keywords
+ @price = price
+ end
+end
+
+# http://soap.amazon.com
+class ListManiaRequest
+ @@schema_type = "ListManiaRequest"
+ @@schema_ns = "http://soap.amazon.com"
+
+ attr_accessor :lm_id
+ attr_accessor :page
+ attr_accessor :tag
+ attr_accessor :type
+ attr_accessor :devtag
+ attr_accessor :locale
+
+ def initialize(lm_id = nil, page = nil, tag = nil, type = nil, devtag = nil, locale = nil)
+ @lm_id = lm_id
+ @page = page
+ @tag = tag
+ @type = type
+ @devtag = devtag
+ @locale = locale
+ end
+end
+
+# http://soap.amazon.com
+class WishlistRequest
+ @@schema_type = "WishlistRequest"
+ @@schema_ns = "http://soap.amazon.com"
+
+ attr_accessor :wishlist_id
+ attr_accessor :page
+ attr_accessor :tag
+ attr_accessor :type
+ attr_accessor :devtag
+ attr_accessor :locale
+
+ def initialize(wishlist_id = nil, page = nil, tag = nil, type = nil, devtag = nil, locale = nil)
+ @wishlist_id = wishlist_id
+ @page = page
+ @tag = tag
+ @type = type
+ @devtag = devtag
+ @locale = locale
+ end
+end
+
+# http://soap.amazon.com
+class MarketplaceRequest
+ @@schema_type = "MarketplaceRequest"
+ @@schema_ns = "http://soap.amazon.com"
+
+ attr_accessor :marketplace_search
+ attr_accessor :tag
+ attr_accessor :type
+ attr_accessor :devtag
+ attr_accessor :page
+ attr_accessor :keyword
+ attr_accessor :keyword_search
+ attr_accessor :browse_id
+ attr_accessor :zipcode
+ attr_accessor :area_id
+ attr_accessor :geo
+ attr_accessor :sort
+ attr_accessor :listing_id
+ attr_accessor :desc
+ attr_accessor :locale
+ attr_accessor :index
+
+ def initialize(marketplace_search = nil, tag = nil, type = nil, devtag = nil, page = nil, keyword = nil, keyword_search = nil, browse_id = nil, zipcode = nil, area_id = nil, geo = nil, sort = nil, listing_id = nil, desc = nil, locale = nil, index = nil)
+ @marketplace_search = marketplace_search
+ @tag = tag
+ @type = type
+ @devtag = devtag
+ @page = page
+ @keyword = keyword
+ @keyword_search = keyword_search
+ @browse_id = browse_id
+ @zipcode = zipcode
+ @area_id = area_id
+ @geo = geo
+ @sort = sort
+ @listing_id = listing_id
+ @desc = desc
+ @locale = locale
+ @index = index
+ end
+end
+
+# http://soap.amazon.com
+class SellerProfileRequest
+ @@schema_type = "SellerProfileRequest"
+ @@schema_ns = "http://soap.amazon.com"
+
+ attr_accessor :seller_id
+ attr_accessor :tag
+ attr_accessor :type
+ attr_accessor :devtag
+ attr_accessor :page
+ attr_accessor :desc
+ attr_accessor :locale
+
+ def initialize(seller_id = nil, tag = nil, type = nil, devtag = nil, page = nil, desc = nil, locale = nil)
+ @seller_id = seller_id
+ @tag = tag
+ @type = type
+ @devtag = devtag
+ @page = page
+ @desc = desc
+ @locale = locale
+ end
+end
+
+# http://soap.amazon.com
+class SellerRequest
+ @@schema_type = "SellerRequest"
+ @@schema_ns = "http://soap.amazon.com"
+
+ attr_accessor :seller_id
+ attr_accessor :tag
+ attr_accessor :type
+ attr_accessor :devtag
+ attr_accessor :offerstatus
+ attr_accessor :page
+ attr_accessor :seller_browse_id
+ attr_accessor :keyword
+ attr_accessor :desc
+ attr_accessor :locale
+ attr_accessor :index
+
+ def initialize(seller_id = nil, tag = nil, type = nil, devtag = nil, offerstatus = nil, page = nil, seller_browse_id = nil, keyword = nil, desc = nil, locale = nil, index = nil)
+ @seller_id = seller_id
+ @tag = tag
+ @type = type
+ @devtag = devtag
+ @offerstatus = offerstatus
+ @page = page
+ @seller_browse_id = seller_browse_id
+ @keyword = keyword
+ @desc = desc
+ @locale = locale
+ @index = index
+ end
+end
+
+# http://soap.amazon.com
+class SimilarityRequest
+ @@schema_type = "SimilarityRequest"
+ @@schema_ns = "http://soap.amazon.com"
+
+ attr_accessor :asin
+ attr_accessor :tag
+ attr_accessor :type
+ attr_accessor :devtag
+ attr_accessor :locale
+
+ def initialize(asin = nil, tag = nil, type = nil, devtag = nil, locale = nil)
+ @asin = asin
+ @tag = tag
+ @type = type
+ @devtag = devtag
+ @locale = locale
+ end
+end
+
+# http://soap.amazon.com
+class ItemIdArray < Array
+ @@schema_type = "ItemIdArray"
+ @@schema_ns = "http://soap.amazon.com"
+end
+
+# http://soap.amazon.com
+class ItemArray < Array
+ @@schema_type = "ItemArray"
+ @@schema_ns = "http://soap.amazon.com"
+end
+
+# http://soap.amazon.com
+class Item
+ @@schema_type = "Item"
+ @@schema_ns = "http://soap.amazon.com"
+
+ def ItemId
+ @itemId
+ end
+
+ def ItemId=(value)
+ @itemId = value
+ end
+
+ def ProductName
+ @productName
+ end
+
+ def ProductName=(value)
+ @productName = value
+ end
+
+ def Catalog
+ @catalog
+ end
+
+ def Catalog=(value)
+ @catalog = value
+ end
+
+ def Asin
+ @asin
+ end
+
+ def Asin=(value)
+ @asin = value
+ end
+
+ def ExchangeId
+ @exchangeId
+ end
+
+ def ExchangeId=(value)
+ @exchangeId = value
+ end
+
+ def Quantity
+ @quantity
+ end
+
+ def Quantity=(value)
+ @quantity = value
+ end
+
+ def ListPrice
+ @listPrice
+ end
+
+ def ListPrice=(value)
+ @listPrice = value
+ end
+
+ def OurPrice
+ @ourPrice
+ end
+
+ def OurPrice=(value)
+ @ourPrice = value
+ end
+
+ def MerchantSku
+ @merchantSku
+ end
+
+ def MerchantSku=(value)
+ @merchantSku = value
+ end
+
+ def initialize(itemId = nil, productName = nil, catalog = nil, asin = nil, exchangeId = nil, quantity = nil, listPrice = nil, ourPrice = nil, merchantSku = nil)
+ @itemId = itemId
+ @productName = productName
+ @catalog = catalog
+ @asin = asin
+ @exchangeId = exchangeId
+ @quantity = quantity
+ @listPrice = listPrice
+ @ourPrice = ourPrice
+ @merchantSku = merchantSku
+ end
+end
+
+# http://soap.amazon.com
+class ItemQuantityArray < Array
+ @@schema_type = "ItemQuantityArray"
+ @@schema_ns = "http://soap.amazon.com"
+end
+
+# http://soap.amazon.com
+class ItemQuantity
+ @@schema_type = "ItemQuantity"
+ @@schema_ns = "http://soap.amazon.com"
+
+ def ItemId
+ @itemId
+ end
+
+ def ItemId=(value)
+ @itemId = value
+ end
+
+ def Quantity
+ @quantity
+ end
+
+ def Quantity=(value)
+ @quantity = value
+ end
+
+ def initialize(itemId = nil, quantity = nil)
+ @itemId = itemId
+ @quantity = quantity
+ end
+end
+
+# http://soap.amazon.com
+class AddItemArray < Array
+ @@schema_type = "AddItemArray"
+ @@schema_ns = "http://soap.amazon.com"
+end
+
+# http://soap.amazon.com
+class AddItem
+ @@schema_type = "AddItem"
+ @@schema_ns = "http://soap.amazon.com"
+
+ def ParentAsin
+ @parentAsin
+ end
+
+ def ParentAsin=(value)
+ @parentAsin = value
+ end
+
+ def Asin
+ @asin
+ end
+
+ def Asin=(value)
+ @asin = value
+ end
+
+ def MerchantId
+ @merchantId
+ end
+
+ def MerchantId=(value)
+ @merchantId = value
+ end
+
+ def ExchangeId
+ @exchangeId
+ end
+
+ def ExchangeId=(value)
+ @exchangeId = value
+ end
+
+ def Quantity
+ @quantity
+ end
+
+ def Quantity=(value)
+ @quantity = value
+ end
+
+ def initialize(parentAsin = nil, asin = nil, merchantId = nil, exchangeId = nil, quantity = nil)
+ @parentAsin = parentAsin
+ @asin = asin
+ @merchantId = merchantId
+ @exchangeId = exchangeId
+ @quantity = quantity
+ end
+end
+
+# http://soap.amazon.com
+class ShoppingCart
+ @@schema_type = "ShoppingCart"
+ @@schema_ns = "http://soap.amazon.com"
+
+ def CartId
+ @cartId
+ end
+
+ def CartId=(value)
+ @cartId = value
+ end
+
+ def HMAC
+ @hMAC
+ end
+
+ def HMAC=(value)
+ @hMAC = value
+ end
+
+ def PurchaseUrl
+ @purchaseUrl
+ end
+
+ def PurchaseUrl=(value)
+ @purchaseUrl = value
+ end
+
+ def Items
+ @items
+ end
+
+ def Items=(value)
+ @items = value
+ end
+
+ def SimilarProducts
+ @similarProducts
+ end
+
+ def SimilarProducts=(value)
+ @similarProducts = value
+ end
+
+ def initialize(cartId = nil, hMAC = nil, purchaseUrl = nil, items = nil, similarProducts = nil)
+ @cartId = cartId
+ @hMAC = hMAC
+ @purchaseUrl = purchaseUrl
+ @items = items
+ @similarProducts = similarProducts
+ end
+end
+
+# http://soap.amazon.com
+class GetShoppingCartRequest
+ @@schema_type = "GetShoppingCartRequest"
+ @@schema_ns = "http://soap.amazon.com"
+
+ attr_accessor :tag
+ attr_accessor :devtag
+ attr_accessor :locale
+ attr_accessor :sims
+
+ def CartId
+ @cartId
+ end
+
+ def CartId=(value)
+ @cartId = value
+ end
+
+ def HMAC
+ @hMAC
+ end
+
+ def HMAC=(value)
+ @hMAC = value
+ end
+
+ def initialize(tag = nil, devtag = nil, cartId = nil, hMAC = nil, locale = nil, sims = nil)
+ @tag = tag
+ @devtag = devtag
+ @cartId = cartId
+ @hMAC = hMAC
+ @locale = locale
+ @sims = sims
+ end
+end
+
+# http://soap.amazon.com
+class ClearShoppingCartRequest
+ @@schema_type = "ClearShoppingCartRequest"
+ @@schema_ns = "http://soap.amazon.com"
+
+ attr_accessor :tag
+ attr_accessor :devtag
+ attr_accessor :locale
+
+ def CartId
+ @cartId
+ end
+
+ def CartId=(value)
+ @cartId = value
+ end
+
+ def HMAC
+ @hMAC
+ end
+
+ def HMAC=(value)
+ @hMAC = value
+ end
+
+ def initialize(tag = nil, devtag = nil, cartId = nil, hMAC = nil, locale = nil)
+ @tag = tag
+ @devtag = devtag
+ @cartId = cartId
+ @hMAC = hMAC
+ @locale = locale
+ end
+end
+
+# http://soap.amazon.com
+class AddShoppingCartItemsRequest
+ @@schema_type = "AddShoppingCartItemsRequest"
+ @@schema_ns = "http://soap.amazon.com"
+
+ attr_accessor :tag
+ attr_accessor :devtag
+ attr_accessor :locale
+ attr_accessor :sims
+
+ def CartId
+ @cartId
+ end
+
+ def CartId=(value)
+ @cartId = value
+ end
+
+ def HMAC
+ @hMAC
+ end
+
+ def HMAC=(value)
+ @hMAC = value
+ end
+
+ def Items
+ @items
+ end
+
+ def Items=(value)
+ @items = value
+ end
+
+ def initialize(tag = nil, devtag = nil, cartId = nil, hMAC = nil, items = nil, locale = nil, sims = nil)
+ @tag = tag
+ @devtag = devtag
+ @cartId = cartId
+ @hMAC = hMAC
+ @items = items
+ @locale = locale
+ @sims = sims
+ end
+end
+
+# http://soap.amazon.com
+class RemoveShoppingCartItemsRequest
+ @@schema_type = "RemoveShoppingCartItemsRequest"
+ @@schema_ns = "http://soap.amazon.com"
+
+ attr_accessor :tag
+ attr_accessor :devtag
+ attr_accessor :locale
+ attr_accessor :sims
+
+ def CartId
+ @cartId
+ end
+
+ def CartId=(value)
+ @cartId = value
+ end
+
+ def HMAC
+ @hMAC
+ end
+
+ def HMAC=(value)
+ @hMAC = value
+ end
+
+ def Items
+ @items
+ end
+
+ def Items=(value)
+ @items = value
+ end
+
+ def initialize(tag = nil, devtag = nil, cartId = nil, hMAC = nil, items = nil, locale = nil, sims = nil)
+ @tag = tag
+ @devtag = devtag
+ @cartId = cartId
+ @hMAC = hMAC
+ @items = items
+ @locale = locale
+ @sims = sims
+ end
+end
+
+# http://soap.amazon.com
+class ModifyShoppingCartItemsRequest
+ @@schema_type = "ModifyShoppingCartItemsRequest"
+ @@schema_ns = "http://soap.amazon.com"
+
+ attr_accessor :tag
+ attr_accessor :devtag
+ attr_accessor :locale
+ attr_accessor :sims
+
+ def CartId
+ @cartId
+ end
+
+ def CartId=(value)
+ @cartId = value
+ end
+
+ def HMAC
+ @hMAC
+ end
+
+ def HMAC=(value)
+ @hMAC = value
+ end
+
+ def Items
+ @items
+ end
+
+ def Items=(value)
+ @items = value
+ end
+
+ def initialize(tag = nil, devtag = nil, cartId = nil, hMAC = nil, items = nil, locale = nil, sims = nil)
+ @tag = tag
+ @devtag = devtag
+ @cartId = cartId
+ @hMAC = hMAC
+ @items = items
+ @locale = locale
+ @sims = sims
+ end
+end
+
+# http://soap.amazon.com
+class OrderIdArray < Array
+ @@schema_type = "OrderIdArray"
+ @@schema_ns = "http://soap.amazon.com"
+end
+
+# http://soap.amazon.com
+class Price
+ @@schema_type = "Price"
+ @@schema_ns = "http://soap.amazon.com"
+
+ def Amount
+ @amount
+ end
+
+ def Amount=(value)
+ @amount = value
+ end
+
+ def CurrencyCode
+ @currencyCode
+ end
+
+ def CurrencyCode=(value)
+ @currencyCode = value
+ end
+
+ def initialize(amount = nil, currencyCode = nil)
+ @amount = amount
+ @currencyCode = currencyCode
+ end
+end
+
+# http://soap.amazon.com
+class Package
+ @@schema_type = "Package"
+ @@schema_ns = "http://soap.amazon.com"
+
+ def TrackingNumber
+ @trackingNumber
+ end
+
+ def TrackingNumber=(value)
+ @trackingNumber = value
+ end
+
+ def CarrierName
+ @carrierName
+ end
+
+ def CarrierName=(value)
+ @carrierName = value
+ end
+
+ def initialize(trackingNumber = nil, carrierName = nil)
+ @trackingNumber = trackingNumber
+ @carrierName = carrierName
+ end
+end
+
+# http://soap.amazon.com
+class PackageArray < Array
+ @@schema_type = "PackageArray"
+ @@schema_ns = "http://soap.amazon.com"
+end
+
+# http://soap.amazon.com
+class OrderItem
+ @@schema_type = "OrderItem"
+ @@schema_ns = "http://soap.amazon.com"
+
+ def ItemNumber
+ @itemNumber
+ end
+
+ def ItemNumber=(value)
+ @itemNumber = value
+ end
+
+ def ASIN
+ @aSIN
+ end
+
+ def ASIN=(value)
+ @aSIN = value
+ end
+
+ def ExchangeId
+ @exchangeId
+ end
+
+ def ExchangeId=(value)
+ @exchangeId = value
+ end
+
+ def Quantity
+ @quantity
+ end
+
+ def Quantity=(value)
+ @quantity = value
+ end
+
+ def UnitPrice
+ @unitPrice
+ end
+
+ def UnitPrice=(value)
+ @unitPrice = value
+ end
+
+ def TotalPrice
+ @totalPrice
+ end
+
+ def TotalPrice=(value)
+ @totalPrice = value
+ end
+
+ def initialize(itemNumber = nil, aSIN = nil, exchangeId = nil, quantity = nil, unitPrice = nil, totalPrice = nil)
+ @itemNumber = itemNumber
+ @aSIN = aSIN
+ @exchangeId = exchangeId
+ @quantity = quantity
+ @unitPrice = unitPrice
+ @totalPrice = totalPrice
+ end
+end
+
+# http://soap.amazon.com
+class OrderItemArray < Array
+ @@schema_type = "OrderItemArray"
+ @@schema_ns = "http://soap.amazon.com"
+end
+
+# http://soap.amazon.com
+class ShortSummary
+ @@schema_type = "ShortSummary"
+ @@schema_ns = "http://soap.amazon.com"
+
+ def OrderId
+ @orderId
+ end
+
+ def OrderId=(value)
+ @orderId = value
+ end
+
+ def SellerId
+ @sellerId
+ end
+
+ def SellerId=(value)
+ @sellerId = value
+ end
+
+ def Condition
+ @condition
+ end
+
+ def Condition=(value)
+ @condition = value
+ end
+
+ def TransactionDate
+ @transactionDate
+ end
+
+ def TransactionDate=(value)
+ @transactionDate = value
+ end
+
+ def TransactionDateEpoch
+ @transactionDateEpoch
+ end
+
+ def TransactionDateEpoch=(value)
+ @transactionDateEpoch = value
+ end
+
+ def Total
+ @total
+ end
+
+ def Total=(value)
+ @total = value
+ end
+
+ def Subtotal
+ @subtotal
+ end
+
+ def Subtotal=(value)
+ @subtotal = value
+ end
+
+ def Shipping
+ @shipping
+ end
+
+ def Shipping=(value)
+ @shipping = value
+ end
+
+ def Tax
+ @tax
+ end
+
+ def Tax=(value)
+ @tax = value
+ end
+
+ def Promotion
+ @promotion
+ end
+
+ def Promotion=(value)
+ @promotion = value
+ end
+
+ def StoreName
+ @storeName
+ end
+
+ def StoreName=(value)
+ @storeName = value
+ end
+
+ def Packages
+ @packages
+ end
+
+ def Packages=(value)
+ @packages = value
+ end
+
+ def OrderItems
+ @orderItems
+ end
+
+ def OrderItems=(value)
+ @orderItems = value
+ end
+
+ def ErrorCode
+ @errorCode
+ end
+
+ def ErrorCode=(value)
+ @errorCode = value
+ end
+
+ def ErrorString
+ @errorString
+ end
+
+ def ErrorString=(value)
+ @errorString = value
+ end
+
+ def initialize(orderId = nil, sellerId = nil, condition = nil, transactionDate = nil, transactionDateEpoch = nil, total = nil, subtotal = nil, shipping = nil, tax = nil, promotion = nil, storeName = nil, packages = nil, orderItems = nil, errorCode = nil, errorString = nil)
+ @orderId = orderId
+ @sellerId = sellerId
+ @condition = condition
+ @transactionDate = transactionDate
+ @transactionDateEpoch = transactionDateEpoch
+ @total = total
+ @subtotal = subtotal
+ @shipping = shipping
+ @tax = tax
+ @promotion = promotion
+ @storeName = storeName
+ @packages = packages
+ @orderItems = orderItems
+ @errorCode = errorCode
+ @errorString = errorString
+ end
+end
+
+# http://soap.amazon.com
+class ShortSummaryArray < Array
+ @@schema_type = "ShortSummaryArray"
+ @@schema_ns = "http://soap.amazon.com"
+end
+
+# http://soap.amazon.com
+class GetTransactionDetailsRequest
+ @@schema_type = "GetTransactionDetailsRequest"
+ @@schema_ns = "http://soap.amazon.com"
+
+ attr_accessor :tag
+ attr_accessor :devtag
+ attr_accessor :key
+ attr_accessor :locale
+
+ def OrderIds
+ @orderIds
+ end
+
+ def OrderIds=(value)
+ @orderIds = value
+ end
+
+ def initialize(tag = nil, devtag = nil, key = nil, orderIds = nil, locale = nil)
+ @tag = tag
+ @devtag = devtag
+ @key = key
+ @orderIds = orderIds
+ @locale = locale
+ end
+end
+
+# http://soap.amazon.com
+class GetTransactionDetailsResponse
+ @@schema_type = "GetTransactionDetailsResponse"
+ @@schema_ns = "http://soap.amazon.com"
+
+ def ShortSummaries
+ @shortSummaries
+ end
+
+ def ShortSummaries=(value)
+ @shortSummaries = value
+ end
+
+ def initialize(shortSummaries = nil)
+ @shortSummaries = shortSummaries
+ end
+end
+
diff --git a/sample/wsdl/amazon/AmazonSearchDriver.rb b/sample/wsdl/amazon/AmazonSearchDriver.rb
new file mode 100644
index 0000000000..60af68887c
--- /dev/null
+++ b/sample/wsdl/amazon/AmazonSearchDriver.rb
@@ -0,0 +1,536 @@
+require 'AmazonSearch.rb'
+
+require 'soap/rpc/driver'
+
+class AmazonSearchPort < ::SOAP::RPC::Driver
+ DefaultEndpointUrl = "http://soap.amazon.com/onca/soap3"
+ MappingRegistry = ::SOAP::Mapping::Registry.new
+
+ MappingRegistry.set(
+ KeywordRequest,
+ ::SOAP::SOAPStruct,
+ ::SOAP::Mapping::Registry::TypedStructFactory,
+ { :type => XSD::QName.new("http://soap.amazon.com", "KeywordRequest") }
+ )
+ MappingRegistry.set(
+ ProductInfo,
+ ::SOAP::SOAPStruct,
+ ::SOAP::Mapping::Registry::TypedStructFactory,
+ { :type => XSD::QName.new("http://soap.amazon.com", "ProductInfo") }
+ )
+ MappingRegistry.set(
+ DetailsArray,
+ ::SOAP::SOAPArray,
+ ::SOAP::Mapping::Registry::TypedArrayFactory,
+ { :type => XSD::QName.new("http://soap.amazon.com", "Details") }
+ )
+ MappingRegistry.set(
+ TextStreamRequest,
+ ::SOAP::SOAPStruct,
+ ::SOAP::Mapping::Registry::TypedStructFactory,
+ { :type => XSD::QName.new("http://soap.amazon.com", "TextStreamRequest") }
+ )
+ MappingRegistry.set(
+ PowerRequest,
+ ::SOAP::SOAPStruct,
+ ::SOAP::Mapping::Registry::TypedStructFactory,
+ { :type => XSD::QName.new("http://soap.amazon.com", "PowerRequest") }
+ )
+ MappingRegistry.set(
+ BrowseNodeRequest,
+ ::SOAP::SOAPStruct,
+ ::SOAP::Mapping::Registry::TypedStructFactory,
+ { :type => XSD::QName.new("http://soap.amazon.com", "BrowseNodeRequest") }
+ )
+ MappingRegistry.set(
+ AsinRequest,
+ ::SOAP::SOAPStruct,
+ ::SOAP::Mapping::Registry::TypedStructFactory,
+ { :type => XSD::QName.new("http://soap.amazon.com", "AsinRequest") }
+ )
+ MappingRegistry.set(
+ BlendedRequest,
+ ::SOAP::SOAPStruct,
+ ::SOAP::Mapping::Registry::TypedStructFactory,
+ { :type => XSD::QName.new("http://soap.amazon.com", "BlendedRequest") }
+ )
+ MappingRegistry.set(
+ ProductLineArray,
+ ::SOAP::SOAPArray,
+ ::SOAP::Mapping::Registry::TypedArrayFactory,
+ { :type => XSD::QName.new("http://soap.amazon.com", "ProductLine") }
+ )
+ MappingRegistry.set(
+ UpcRequest,
+ ::SOAP::SOAPStruct,
+ ::SOAP::Mapping::Registry::TypedStructFactory,
+ { :type => XSD::QName.new("http://soap.amazon.com", "UpcRequest") }
+ )
+ MappingRegistry.set(
+ SkuRequest,
+ ::SOAP::SOAPStruct,
+ ::SOAP::Mapping::Registry::TypedStructFactory,
+ { :type => XSD::QName.new("http://soap.amazon.com", "SkuRequest") }
+ )
+ MappingRegistry.set(
+ AuthorRequest,
+ ::SOAP::SOAPStruct,
+ ::SOAP::Mapping::Registry::TypedStructFactory,
+ { :type => XSD::QName.new("http://soap.amazon.com", "AuthorRequest") }
+ )
+ MappingRegistry.set(
+ ArtistRequest,
+ ::SOAP::SOAPStruct,
+ ::SOAP::Mapping::Registry::TypedStructFactory,
+ { :type => XSD::QName.new("http://soap.amazon.com", "ArtistRequest") }
+ )
+ MappingRegistry.set(
+ ActorRequest,
+ ::SOAP::SOAPStruct,
+ ::SOAP::Mapping::Registry::TypedStructFactory,
+ { :type => XSD::QName.new("http://soap.amazon.com", "ActorRequest") }
+ )
+ MappingRegistry.set(
+ ManufacturerRequest,
+ ::SOAP::SOAPStruct,
+ ::SOAP::Mapping::Registry::TypedStructFactory,
+ { :type => XSD::QName.new("http://soap.amazon.com", "ManufacturerRequest") }
+ )
+ MappingRegistry.set(
+ DirectorRequest,
+ ::SOAP::SOAPStruct,
+ ::SOAP::Mapping::Registry::TypedStructFactory,
+ { :type => XSD::QName.new("http://soap.amazon.com", "DirectorRequest") }
+ )
+ MappingRegistry.set(
+ ListManiaRequest,
+ ::SOAP::SOAPStruct,
+ ::SOAP::Mapping::Registry::TypedStructFactory,
+ { :type => XSD::QName.new("http://soap.amazon.com", "ListManiaRequest") }
+ )
+ MappingRegistry.set(
+ WishlistRequest,
+ ::SOAP::SOAPStruct,
+ ::SOAP::Mapping::Registry::TypedStructFactory,
+ { :type => XSD::QName.new("http://soap.amazon.com", "WishlistRequest") }
+ )
+ MappingRegistry.set(
+ ExchangeRequest,
+ ::SOAP::SOAPStruct,
+ ::SOAP::Mapping::Registry::TypedStructFactory,
+ { :type => XSD::QName.new("http://soap.amazon.com", "ExchangeRequest") }
+ )
+ MappingRegistry.set(
+ ListingProductDetails,
+ ::SOAP::SOAPStruct,
+ ::SOAP::Mapping::Registry::TypedStructFactory,
+ { :type => XSD::QName.new("http://soap.amazon.com", "ListingProductDetails") }
+ )
+ MappingRegistry.set(
+ MarketplaceRequest,
+ ::SOAP::SOAPStruct,
+ ::SOAP::Mapping::Registry::TypedStructFactory,
+ { :type => XSD::QName.new("http://soap.amazon.com", "MarketplaceRequest") }
+ )
+ MappingRegistry.set(
+ MarketplaceSearch,
+ ::SOAP::SOAPStruct,
+ ::SOAP::Mapping::Registry::TypedStructFactory,
+ { :type => XSD::QName.new("http://soap.amazon.com", "MarketplaceSearch") }
+ )
+ MappingRegistry.set(
+ MarketplaceSearchDetailsArray,
+ ::SOAP::SOAPArray,
+ ::SOAP::Mapping::Registry::TypedArrayFactory,
+ { :type => XSD::QName.new("http://soap.amazon.com", "MarketplaceSearchDetails") }
+ )
+ MappingRegistry.set(
+ SellerProfileRequest,
+ ::SOAP::SOAPStruct,
+ ::SOAP::Mapping::Registry::TypedStructFactory,
+ { :type => XSD::QName.new("http://soap.amazon.com", "SellerProfileRequest") }
+ )
+ MappingRegistry.set(
+ SellerProfile,
+ ::SOAP::SOAPStruct,
+ ::SOAP::Mapping::Registry::TypedStructFactory,
+ { :type => XSD::QName.new("http://soap.amazon.com", "SellerProfile") }
+ )
+ MappingRegistry.set(
+ SellerProfileDetailsArray,
+ ::SOAP::SOAPArray,
+ ::SOAP::Mapping::Registry::TypedArrayFactory,
+ { :type => XSD::QName.new("http://soap.amazon.com", "SellerProfileDetails") }
+ )
+ MappingRegistry.set(
+ SellerRequest,
+ ::SOAP::SOAPStruct,
+ ::SOAP::Mapping::Registry::TypedStructFactory,
+ { :type => XSD::QName.new("http://soap.amazon.com", "SellerRequest") }
+ )
+ MappingRegistry.set(
+ SellerSearch,
+ ::SOAP::SOAPStruct,
+ ::SOAP::Mapping::Registry::TypedStructFactory,
+ { :type => XSD::QName.new("http://soap.amazon.com", "SellerSearch") }
+ )
+ MappingRegistry.set(
+ SellerSearchDetailsArray,
+ ::SOAP::SOAPArray,
+ ::SOAP::Mapping::Registry::TypedArrayFactory,
+ { :type => XSD::QName.new("http://soap.amazon.com", "SellerSearchDetails") }
+ )
+ MappingRegistry.set(
+ SimilarityRequest,
+ ::SOAP::SOAPStruct,
+ ::SOAP::Mapping::Registry::TypedStructFactory,
+ { :type => XSD::QName.new("http://soap.amazon.com", "SimilarityRequest") }
+ )
+ MappingRegistry.set(
+ GetShoppingCartRequest,
+ ::SOAP::SOAPStruct,
+ ::SOAP::Mapping::Registry::TypedStructFactory,
+ { :type => XSD::QName.new("http://soap.amazon.com", "GetShoppingCartRequest") }
+ )
+ MappingRegistry.set(
+ ShoppingCart,
+ ::SOAP::SOAPStruct,
+ ::SOAP::Mapping::Registry::TypedStructFactory,
+ { :type => XSD::QName.new("http://soap.amazon.com", "ShoppingCart") }
+ )
+ MappingRegistry.set(
+ ItemArray,
+ ::SOAP::SOAPArray,
+ ::SOAP::Mapping::Registry::TypedArrayFactory,
+ { :type => XSD::QName.new("http://soap.amazon.com", "Item") }
+ )
+ MappingRegistry.set(
+ SimilarProductsArray,
+ ::SOAP::SOAPArray,
+ ::SOAP::Mapping::Registry::TypedArrayFactory,
+ { :type => XSD::QName.new("http://www.w3.org/2001/XMLSchema", "string") }
+ )
+ MappingRegistry.set(
+ ClearShoppingCartRequest,
+ ::SOAP::SOAPStruct,
+ ::SOAP::Mapping::Registry::TypedStructFactory,
+ { :type => XSD::QName.new("http://soap.amazon.com", "ClearShoppingCartRequest") }
+ )
+ MappingRegistry.set(
+ AddShoppingCartItemsRequest,
+ ::SOAP::SOAPStruct,
+ ::SOAP::Mapping::Registry::TypedStructFactory,
+ { :type => XSD::QName.new("http://soap.amazon.com", "AddShoppingCartItemsRequest") }
+ )
+ MappingRegistry.set(
+ AddItemArray,
+ ::SOAP::SOAPArray,
+ ::SOAP::Mapping::Registry::TypedArrayFactory,
+ { :type => XSD::QName.new("http://soap.amazon.com", "AddItem") }
+ )
+ MappingRegistry.set(
+ RemoveShoppingCartItemsRequest,
+ ::SOAP::SOAPStruct,
+ ::SOAP::Mapping::Registry::TypedStructFactory,
+ { :type => XSD::QName.new("http://soap.amazon.com", "RemoveShoppingCartItemsRequest") }
+ )
+ MappingRegistry.set(
+ ItemIdArray,
+ ::SOAP::SOAPArray,
+ ::SOAP::Mapping::Registry::TypedArrayFactory,
+ { :type => XSD::QName.new("http://www.w3.org/2001/XMLSchema", "string") }
+ )
+ MappingRegistry.set(
+ ModifyShoppingCartItemsRequest,
+ ::SOAP::SOAPStruct,
+ ::SOAP::Mapping::Registry::TypedStructFactory,
+ { :type => XSD::QName.new("http://soap.amazon.com", "ModifyShoppingCartItemsRequest") }
+ )
+ MappingRegistry.set(
+ ItemQuantityArray,
+ ::SOAP::SOAPArray,
+ ::SOAP::Mapping::Registry::TypedArrayFactory,
+ { :type => XSD::QName.new("http://soap.amazon.com", "ItemQuantity") }
+ )
+ MappingRegistry.set(
+ GetTransactionDetailsRequest,
+ ::SOAP::SOAPStruct,
+ ::SOAP::Mapping::Registry::TypedStructFactory,
+ { :type => XSD::QName.new("http://soap.amazon.com", "GetTransactionDetailsRequest") }
+ )
+ MappingRegistry.set(
+ OrderIdArray,
+ ::SOAP::SOAPArray,
+ ::SOAP::Mapping::Registry::TypedArrayFactory,
+ { :type => XSD::QName.new("http://www.w3.org/2001/XMLSchema", "string") }
+ )
+ MappingRegistry.set(
+ GetTransactionDetailsResponse,
+ ::SOAP::SOAPStruct,
+ ::SOAP::Mapping::Registry::TypedStructFactory,
+ { :type => XSD::QName.new("http://soap.amazon.com", "GetTransactionDetailsResponse") }
+ )
+ MappingRegistry.set(
+ ShortSummaryArray,
+ ::SOAP::SOAPArray,
+ ::SOAP::Mapping::Registry::TypedArrayFactory,
+ { :type => XSD::QName.new("http://soap.amazon.com", "ShortSummary") }
+ )
+ MappingRegistry.set(
+ Details,
+ ::SOAP::SOAPStruct,
+ ::SOAP::Mapping::Registry::TypedStructFactory,
+ { :type => XSD::QName.new("http://soap.amazon.com", "Details") }
+ )
+ MappingRegistry.set(
+ ProductLine,
+ ::SOAP::SOAPStruct,
+ ::SOAP::Mapping::Registry::TypedStructFactory,
+ { :type => XSD::QName.new("http://soap.amazon.com", "ProductLine") }
+ )
+ MappingRegistry.set(
+ MarketplaceSearchDetails,
+ ::SOAP::SOAPStruct,
+ ::SOAP::Mapping::Registry::TypedStructFactory,
+ { :type => XSD::QName.new("http://soap.amazon.com", "MarketplaceSearchDetails") }
+ )
+ MappingRegistry.set(
+ SellerProfileDetails,
+ ::SOAP::SOAPStruct,
+ ::SOAP::Mapping::Registry::TypedStructFactory,
+ { :type => XSD::QName.new("http://soap.amazon.com", "SellerProfileDetails") }
+ )
+ MappingRegistry.set(
+ SellerSearchDetails,
+ ::SOAP::SOAPStruct,
+ ::SOAP::Mapping::Registry::TypedStructFactory,
+ { :type => XSD::QName.new("http://soap.amazon.com", "SellerSearchDetails") }
+ )
+ MappingRegistry.set(
+ Item,
+ ::SOAP::SOAPStruct,
+ ::SOAP::Mapping::Registry::TypedStructFactory,
+ { :type => XSD::QName.new("http://soap.amazon.com", "Item") }
+ )
+ MappingRegistry.set(
+ AddItem,
+ ::SOAP::SOAPStruct,
+ ::SOAP::Mapping::Registry::TypedStructFactory,
+ { :type => XSD::QName.new("http://soap.amazon.com", "AddItem") }
+ )
+ MappingRegistry.set(
+ ItemQuantity,
+ ::SOAP::SOAPStruct,
+ ::SOAP::Mapping::Registry::TypedStructFactory,
+ { :type => XSD::QName.new("http://soap.amazon.com", "ItemQuantity") }
+ )
+ MappingRegistry.set(
+ ShortSummary,
+ ::SOAP::SOAPStruct,
+ ::SOAP::Mapping::Registry::TypedStructFactory,
+ { :type => XSD::QName.new("http://soap.amazon.com", "ShortSummary") }
+ )
+
+ Methods = [
+ ["KeywordSearchRequest", "keywordSearchRequest",
+ [
+ ["in", "KeywordSearchRequest", [::SOAP::SOAPStruct, "http://soap.amazon.com", "KeywordRequest"]],
+ ["retval", "return", [::SOAP::SOAPStruct, "http://soap.amazon.com", "ProductInfo"]]
+ ],
+ "http://soap.amazon.com", "http://soap.amazon.com"
+ ],
+ ["TextStreamSearchRequest", "textStreamSearchRequest",
+ [
+ ["in", "TextStreamSearchRequest", [::SOAP::SOAPStruct, "http://soap.amazon.com", "TextStreamRequest"]],
+ ["retval", "return", [::SOAP::SOAPStruct, "http://soap.amazon.com", "ProductInfo"]]
+ ],
+ "http://soap.amazon.com", "http://soap.amazon.com"
+ ],
+ ["PowerSearchRequest", "powerSearchRequest",
+ [
+ ["in", "PowerSearchRequest", [::SOAP::SOAPStruct, "http://soap.amazon.com", "PowerRequest"]],
+ ["retval", "return", [::SOAP::SOAPStruct, "http://soap.amazon.com", "ProductInfo"]]
+ ],
+ "http://soap.amazon.com", "http://soap.amazon.com"
+ ],
+ ["BrowseNodeSearchRequest", "browseNodeSearchRequest",
+ [
+ ["in", "BrowseNodeSearchRequest", [::SOAP::SOAPStruct, "http://soap.amazon.com", "BrowseNodeRequest"]],
+ ["retval", "return", [::SOAP::SOAPStruct, "http://soap.amazon.com", "ProductInfo"]]
+ ],
+ "http://soap.amazon.com", "http://soap.amazon.com"
+ ],
+ ["AsinSearchRequest", "asinSearchRequest",
+ [
+ ["in", "AsinSearchRequest", [::SOAP::SOAPStruct, "http://soap.amazon.com", "AsinRequest"]],
+ ["retval", "return", [::SOAP::SOAPStruct, "http://soap.amazon.com", "ProductInfo"]]
+ ],
+ "http://soap.amazon.com", "http://soap.amazon.com"
+ ],
+ ["BlendedSearchRequest", "blendedSearchRequest",
+ [
+ ["in", "BlendedSearchRequest", [::SOAP::SOAPStruct, "http://soap.amazon.com", "BlendedRequest"]],
+ ["retval", "return", [::SOAP::SOAPArray, "http://soap.amazon.com", "ProductLine"]]
+ ],
+ "http://soap.amazon.com", "http://soap.amazon.com"
+ ],
+ ["UpcSearchRequest", "upcSearchRequest",
+ [
+ ["in", "UpcSearchRequest", [::SOAP::SOAPStruct, "http://soap.amazon.com", "UpcRequest"]],
+ ["retval", "return", [::SOAP::SOAPStruct, "http://soap.amazon.com", "ProductInfo"]]
+ ],
+ "http://soap.amazon.com", "http://soap.amazon.com"
+ ],
+ ["SkuSearchRequest", "skuSearchRequest",
+ [
+ ["in", "SkuSearchRequest", [::SOAP::SOAPStruct, "http://soap.amazon.com", "SkuRequest"]],
+ ["retval", "return", [::SOAP::SOAPStruct, "http://soap.amazon.com", "ProductInfo"]]
+ ],
+ "http://soap.amazon.com", "http://soap.amazon.com"
+ ],
+ ["AuthorSearchRequest", "authorSearchRequest",
+ [
+ ["in", "AuthorSearchRequest", [::SOAP::SOAPStruct, "http://soap.amazon.com", "AuthorRequest"]],
+ ["retval", "return", [::SOAP::SOAPStruct, "http://soap.amazon.com", "ProductInfo"]]
+ ],
+ "http://soap.amazon.com", "http://soap.amazon.com"
+ ],
+ ["ArtistSearchRequest", "artistSearchRequest",
+ [
+ ["in", "ArtistSearchRequest", [::SOAP::SOAPStruct, "http://soap.amazon.com", "ArtistRequest"]],
+ ["retval", "return", [::SOAP::SOAPStruct, "http://soap.amazon.com", "ProductInfo"]]
+ ],
+ "http://soap.amazon.com", "http://soap.amazon.com"
+ ],
+ ["ActorSearchRequest", "actorSearchRequest",
+ [
+ ["in", "ActorSearchRequest", [::SOAP::SOAPStruct, "http://soap.amazon.com", "ActorRequest"]],
+ ["retval", "return", [::SOAP::SOAPStruct, "http://soap.amazon.com", "ProductInfo"]]
+ ],
+ "http://soap.amazon.com", "http://soap.amazon.com"
+ ],
+ ["ManufacturerSearchRequest", "manufacturerSearchRequest",
+ [
+ ["in", "ManufacturerSearchRequest", [::SOAP::SOAPStruct, "http://soap.amazon.com", "ManufacturerRequest"]],
+ ["retval", "return", [::SOAP::SOAPStruct, "http://soap.amazon.com", "ProductInfo"]]
+ ],
+ "http://soap.amazon.com", "http://soap.amazon.com"
+ ],
+ ["DirectorSearchRequest", "directorSearchRequest",
+ [
+ ["in", "DirectorSearchRequest", [::SOAP::SOAPStruct, "http://soap.amazon.com", "DirectorRequest"]],
+ ["retval", "return", [::SOAP::SOAPStruct, "http://soap.amazon.com", "ProductInfo"]]
+ ],
+ "http://soap.amazon.com", "http://soap.amazon.com"
+ ],
+ ["ListManiaSearchRequest", "listManiaSearchRequest",
+ [
+ ["in", "ListManiaSearchRequest", [::SOAP::SOAPStruct, "http://soap.amazon.com", "ListManiaRequest"]],
+ ["retval", "return", [::SOAP::SOAPStruct, "http://soap.amazon.com", "ProductInfo"]]
+ ],
+ "http://soap.amazon.com", "http://soap.amazon.com"
+ ],
+ ["WishlistSearchRequest", "wishlistSearchRequest",
+ [
+ ["in", "WishlistSearchRequest", [::SOAP::SOAPStruct, "http://soap.amazon.com", "WishlistRequest"]],
+ ["retval", "return", [::SOAP::SOAPStruct, "http://soap.amazon.com", "ProductInfo"]]
+ ],
+ "http://soap.amazon.com", "http://soap.amazon.com"
+ ],
+ ["ExchangeSearchRequest", "exchangeSearchRequest",
+ [
+ ["in", "ExchangeSearchRequest", [::SOAP::SOAPStruct, "http://soap.amazon.com", "ExchangeRequest"]],
+ ["retval", "return", [::SOAP::SOAPStruct, "http://soap.amazon.com", "ListingProductDetails"]]
+ ],
+ "http://soap.amazon.com", "http://soap.amazon.com"
+ ],
+ ["MarketplaceSearchRequest", "marketplaceSearchRequest",
+ [
+ ["in", "MarketplaceSearchRequest", [::SOAP::SOAPStruct, "http://soap.amazon.com", "MarketplaceRequest"]],
+ ["retval", "return", [::SOAP::SOAPStruct, "http://soap.amazon.com", "MarketplaceSearch"]]
+ ],
+ "http://soap.amazon.com", "http://soap.amazon.com"
+ ],
+ ["SellerProfileSearchRequest", "sellerProfileSearchRequest",
+ [
+ ["in", "SellerProfileSearchRequest", [::SOAP::SOAPStruct, "http://soap.amazon.com", "SellerProfileRequest"]],
+ ["retval", "return", [::SOAP::SOAPStruct, "http://soap.amazon.com", "SellerProfile"]]
+ ],
+ "http://soap.amazon.com", "http://soap.amazon.com"
+ ],
+ ["SellerSearchRequest", "sellerSearchRequest",
+ [
+ ["in", "SellerSearchRequest", [::SOAP::SOAPStruct, "http://soap.amazon.com", "SellerRequest"]],
+ ["retval", "return", [::SOAP::SOAPStruct, "http://soap.amazon.com", "SellerSearch"]]
+ ],
+ "http://soap.amazon.com", "http://soap.amazon.com"
+ ],
+ ["SimilaritySearchRequest", "similaritySearchRequest",
+ [
+ ["in", "SimilaritySearchRequest", [::SOAP::SOAPStruct, "http://soap.amazon.com", "SimilarityRequest"]],
+ ["retval", "return", [::SOAP::SOAPStruct, "http://soap.amazon.com", "ProductInfo"]]
+ ],
+ "http://soap.amazon.com", "http://soap.amazon.com"
+ ],
+ ["GetShoppingCartRequest", "getShoppingCartRequest",
+ [
+ ["in", "GetShoppingCartRequest", [::SOAP::SOAPStruct, "http://soap.amazon.com", "GetShoppingCartRequest"]],
+ ["retval", "ShoppingCart", [::SOAP::SOAPStruct, "http://soap.amazon.com", "ShoppingCart"]]
+ ],
+ "http://soap.amazon.com", "http://soap.amazon.com"
+ ],
+ ["ClearShoppingCartRequest", "clearShoppingCartRequest",
+ [
+ ["in", "ClearShoppingCartRequest", [::SOAP::SOAPStruct, "http://soap.amazon.com", "ClearShoppingCartRequest"]],
+ ["retval", "ShoppingCart", [::SOAP::SOAPStruct, "http://soap.amazon.com", "ShoppingCart"]]
+ ],
+ "http://soap.amazon.com", "http://soap.amazon.com"
+ ],
+ ["AddShoppingCartItemsRequest", "addShoppingCartItemsRequest",
+ [
+ ["in", "AddShoppingCartItemsRequest", [::SOAP::SOAPStruct, "http://soap.amazon.com", "AddShoppingCartItemsRequest"]],
+ ["retval", "ShoppingCart", [::SOAP::SOAPStruct, "http://soap.amazon.com", "ShoppingCart"]]
+ ],
+ "http://soap.amazon.com", "http://soap.amazon.com"
+ ],
+ ["RemoveShoppingCartItemsRequest", "removeShoppingCartItemsRequest",
+ [
+ ["in", "RemoveShoppingCartItemsRequest", [::SOAP::SOAPStruct, "http://soap.amazon.com", "RemoveShoppingCartItemsRequest"]],
+ ["retval", "ShoppingCart", [::SOAP::SOAPStruct, "http://soap.amazon.com", "ShoppingCart"]]
+ ],
+ "http://soap.amazon.com", "http://soap.amazon.com"
+ ],
+ ["ModifyShoppingCartItemsRequest", "modifyShoppingCartItemsRequest",
+ [
+ ["in", "ModifyShoppingCartItemsRequest", [::SOAP::SOAPStruct, "http://soap.amazon.com", "ModifyShoppingCartItemsRequest"]],
+ ["retval", "ShoppingCart", [::SOAP::SOAPStruct, "http://soap.amazon.com", "ShoppingCart"]]
+ ],
+ "http://soap.amazon.com", "http://soap.amazon.com"
+ ],
+ ["GetTransactionDetailsRequest", "getTransactionDetailsRequest",
+ [
+ ["in", "GetTransactionDetailsRequest", [::SOAP::SOAPStruct, "http://soap.amazon.com", "GetTransactionDetailsRequest"]],
+ ["retval", "GetTransactionDetailsResponse", [::SOAP::SOAPStruct, "http://soap.amazon.com", "GetTransactionDetailsResponse"]]
+ ],
+ "http://soap.amazon.com", "http://soap.amazon.com"
+ ]
+ ]
+
+ def initialize(endpoint_url = nil)
+ endpoint_url ||= DefaultEndpointUrl
+ super(endpoint_url, nil)
+ self.mapping_registry = MappingRegistry
+ init_methods
+ end
+
+private
+
+ def init_methods
+ Methods.each do |name_as, name, params, soapaction, namespace|
+ qname = XSD::QName.new(namespace, name_as)
+ @proxy.add_method(qname, soapaction, name, params)
+ add_rpc_method_interface(name, params)
+ end
+ end
+end
+
diff --git a/sample/wsdl/amazon/sampleClient.rb b/sample/wsdl/amazon/sampleClient.rb
new file mode 100644
index 0000000000..3caad84e04
--- /dev/null
+++ b/sample/wsdl/amazon/sampleClient.rb
@@ -0,0 +1,37 @@
+#!/usr/bin/env ruby
+
+# This file is a sample based on AmazonSearchServiceClient.rb, which can be
+# generated by WSDL file and wsdl2ruby.rb.
+#
+# $ wsdl2ruby.rb --type client --force \
+# --wsdl http://soap.amazon.com/schemas3/AmazonWebServices.wsdl
+#
+# See wsdlDriver.rb to use WSDL file directly (slow).
+require 'AmazonSearchDriver.rb'
+
+endpoint_url = ARGV.shift
+obj = AmazonSearchPort.new(endpoint_url)
+
+# Uncomment the below line to see SOAP wiredumps.
+# obj.wiredump_dev = STDERR
+
+# SYNOPSIS
+# KeywordSearchRequest(keywordSearchRequest)
+#
+# ARGS
+# keywordSearchRequest KeywordRequest - {urn:PI/DevCentral/SoapService}KeywordRequest
+#
+# RETURNS
+# return ProductInfo - {urn:PI/DevCentral/SoapService}ProductInfo
+#
+# RAISES
+# N/A
+#
+keywordSearchRequest = KeywordRequest.new("Ruby Object", "1", "books", "webservices-20", "lite", "", "+salesrank")
+obj.keywordSearchRequest(keywordSearchRequest).Details.each do |detail|
+ puts "== #{detail.ProductName}"
+ puts "Author: #{detail.Authors.join(", ")}"
+ puts "Release date: #{detail.ReleaseDate}"
+ puts "List price: #{detail.ListPrice}, our price: #{detail.OurPrice}"
+ puts
+end
diff --git a/sample/wsdl/amazon/wsdlDriver.rb b/sample/wsdl/amazon/wsdlDriver.rb
new file mode 100644
index 0000000000..e62a9a65b3
--- /dev/null
+++ b/sample/wsdl/amazon/wsdlDriver.rb
@@ -0,0 +1,52 @@
+require 'soap/wsdlDriver'
+
+book = ARGV.shift || "Ruby"
+
+# AmazonSearch.rb is generated from WSDL.
+# Run "wsdl2ruby.rb --wsdl http://soap.amazon.com/schemas3/AmazonWebServices.wsdl --classdef --force"
+# http://soap.amazon.com/schemas3/AmazonWebServices.wsdl
+require 'AmazonSearch.rb'
+
+=begin
+Or, define the class by yourself like this.
+
+class KeywordRequest
+ def initialize(keyword = nil,
+ page = nil,
+ mode = nil,
+ tag = nil,
+ type = nil,
+ devtag = nil,
+ sort = nil)
+ @keyword = keyword
+ @page = page
+ @mode = mode
+ @tag = tag
+ @type = type
+ @devtag = devtag
+ @sort = sort
+ end
+end
+=end
+
+# You must get 'developer's token" from http://associates.amazon.com/exec/panama/associates/ntg/browse/-/1067662 to use Amazon Web Services 2.0.
+#devtag = File.open(File.expand_path("~/.amazon_key")) { |f| f.read }.chomp
+devtag = nil
+
+# v2: AMAZON_WSDL = 'http://soap.amazon.com/schemas2/AmazonWebServices.wsdl'
+AMAZON_WSDL = 'http://soap.amazon.com/schemas3/AmazonWebServices.wsdl'
+amazon = SOAP::WSDLDriverFactory.new(AMAZON_WSDL).create_driver
+p "WSDL loaded"
+amazon.generate_explicit_type = true
+amazon.mandatorycharset = 'utf-8' # AWS should fix this bug.
+#amazon.wiredump_dev = STDERR
+
+# Show sales rank.
+req = KeywordRequest.new(book, "1", "books", "webservices-20", "lite", devtag, "+salesrank")
+amazon.KeywordSearchRequest(req).Details.each do |detail|
+ puts "== #{detail.ProductName}"
+ puts "Author: #{detail.Authors.join(", ")}"
+ puts "Release date: #{detail.ReleaseDate}"
+ puts "List price: #{detail.ListPrice}, our price: #{detail.OurPrice}"
+ puts
+end
diff --git a/sample/wsdl/googleSearch/GoogleSearch.rb b/sample/wsdl/googleSearch/GoogleSearch.rb
new file mode 100644
index 0000000000..e124208b91
--- /dev/null
+++ b/sample/wsdl/googleSearch/GoogleSearch.rb
@@ -0,0 +1,258 @@
+# urn:GoogleSearch
+class GoogleSearchResult
+ @@schema_type = "GoogleSearchResult"
+ @@schema_ns = "urn:GoogleSearch"
+
+ def documentFiltering
+ @documentFiltering
+ end
+
+ def documentFiltering=(value)
+ @documentFiltering = value
+ end
+
+ def searchComments
+ @searchComments
+ end
+
+ def searchComments=(value)
+ @searchComments = value
+ end
+
+ def estimatedTotalResultsCount
+ @estimatedTotalResultsCount
+ end
+
+ def estimatedTotalResultsCount=(value)
+ @estimatedTotalResultsCount = value
+ end
+
+ def estimateIsExact
+ @estimateIsExact
+ end
+
+ def estimateIsExact=(value)
+ @estimateIsExact = value
+ end
+
+ def resultElements
+ @resultElements
+ end
+
+ def resultElements=(value)
+ @resultElements = value
+ end
+
+ def searchQuery
+ @searchQuery
+ end
+
+ def searchQuery=(value)
+ @searchQuery = value
+ end
+
+ def startIndex
+ @startIndex
+ end
+
+ def startIndex=(value)
+ @startIndex = value
+ end
+
+ def endIndex
+ @endIndex
+ end
+
+ def endIndex=(value)
+ @endIndex = value
+ end
+
+ def searchTips
+ @searchTips
+ end
+
+ def searchTips=(value)
+ @searchTips = value
+ end
+
+ def directoryCategories
+ @directoryCategories
+ end
+
+ def directoryCategories=(value)
+ @directoryCategories = value
+ end
+
+ def searchTime
+ @searchTime
+ end
+
+ def searchTime=(value)
+ @searchTime = value
+ end
+
+ def initialize(documentFiltering = nil,
+ searchComments = nil,
+ estimatedTotalResultsCount = nil,
+ estimateIsExact = nil,
+ resultElements = nil,
+ searchQuery = nil,
+ startIndex = nil,
+ endIndex = nil,
+ searchTips = nil,
+ directoryCategories = nil,
+ searchTime = nil)
+ @documentFiltering = documentFiltering
+ @searchComments = searchComments
+ @estimatedTotalResultsCount = estimatedTotalResultsCount
+ @estimateIsExact = estimateIsExact
+ @resultElements = resultElements
+ @searchQuery = searchQuery
+ @startIndex = startIndex
+ @endIndex = endIndex
+ @searchTips = searchTips
+ @directoryCategories = directoryCategories
+ @searchTime = searchTime
+ end
+end
+
+# urn:GoogleSearch
+class ResultElement
+ @@schema_type = "ResultElement"
+ @@schema_ns = "urn:GoogleSearch"
+
+ def summary
+ @summary
+ end
+
+ def summary=(value)
+ @summary = value
+ end
+
+ def URL
+ @uRL
+ end
+
+ def URL=(value)
+ @uRL = value
+ end
+
+ def snippet
+ @snippet
+ end
+
+ def snippet=(value)
+ @snippet = value
+ end
+
+ def title
+ @title
+ end
+
+ def title=(value)
+ @title = value
+ end
+
+ def cachedSize
+ @cachedSize
+ end
+
+ def cachedSize=(value)
+ @cachedSize = value
+ end
+
+ def relatedInformationPresent
+ @relatedInformationPresent
+ end
+
+ def relatedInformationPresent=(value)
+ @relatedInformationPresent = value
+ end
+
+ def hostName
+ @hostName
+ end
+
+ def hostName=(value)
+ @hostName = value
+ end
+
+ def directoryCategory
+ @directoryCategory
+ end
+
+ def directoryCategory=(value)
+ @directoryCategory = value
+ end
+
+ def directoryTitle
+ @directoryTitle
+ end
+
+ def directoryTitle=(value)
+ @directoryTitle = value
+ end
+
+ def initialize(summary = nil,
+ uRL = nil,
+ snippet = nil,
+ title = nil,
+ cachedSize = nil,
+ relatedInformationPresent = nil,
+ hostName = nil,
+ directoryCategory = nil,
+ directoryTitle = nil)
+ @summary = summary
+ @uRL = uRL
+ @snippet = snippet
+ @title = title
+ @cachedSize = cachedSize
+ @relatedInformationPresent = relatedInformationPresent
+ @hostName = hostName
+ @directoryCategory = directoryCategory
+ @directoryTitle = directoryTitle
+ end
+end
+
+# urn:GoogleSearch
+class ResultElementArray < Array
+ # Contents type should be dumped here...
+ @@schema_type = "ResultElementArray"
+ @@schema_ns = "urn:GoogleSearch"
+end
+
+# urn:GoogleSearch
+class DirectoryCategoryArray < Array
+ # Contents type should be dumped here...
+ @@schema_type = "DirectoryCategoryArray"
+ @@schema_ns = "urn:GoogleSearch"
+end
+
+# urn:GoogleSearch
+class DirectoryCategory
+ @@schema_type = "DirectoryCategory"
+ @@schema_ns = "urn:GoogleSearch"
+
+ def fullViewableName
+ @fullViewableName
+ end
+
+ def fullViewableName=(value)
+ @fullViewableName = value
+ end
+
+ def specialEncoding
+ @specialEncoding
+ end
+
+ def specialEncoding=(value)
+ @specialEncoding = value
+ end
+
+ def initialize(fullViewableName = nil,
+ specialEncoding = nil)
+ @fullViewableName = fullViewableName
+ @specialEncoding = specialEncoding
+ end
+end
+
diff --git a/sample/wsdl/googleSearch/GoogleSearchDriver.rb b/sample/wsdl/googleSearch/GoogleSearchDriver.rb
new file mode 100644
index 0000000000..9901b89071
--- /dev/null
+++ b/sample/wsdl/googleSearch/GoogleSearchDriver.rb
@@ -0,0 +1,101 @@
+require 'GoogleSearch.rb'
+
+require 'soap/rpc/driver'
+
+class GoogleSearchPort < SOAP::RPC::Driver
+ MappingRegistry = ::SOAP::Mapping::Registry.new
+
+ MappingRegistry.set(
+ GoogleSearchResult,
+ ::SOAP::SOAPStruct,
+ ::SOAP::Mapping::Registry::TypedStructFactory,
+ { :type => XSD::QName.new("urn:GoogleSearch", "GoogleSearchResult") }
+ )
+ MappingRegistry.set(
+ ResultElementArray,
+ ::SOAP::SOAPArray,
+ ::SOAP::Mapping::Registry::TypedArrayFactory,
+ { :type => XSD::QName.new("urn:GoogleSearch", "ResultElement") }
+ )
+ MappingRegistry.set(
+ DirectoryCategoryArray,
+ ::SOAP::SOAPArray,
+ ::SOAP::Mapping::Registry::TypedArrayFactory,
+ { :type => XSD::QName.new("urn:GoogleSearch", "DirectoryCategory") }
+ )
+ MappingRegistry.set(
+ ResultElement,
+ ::SOAP::SOAPStruct,
+ ::SOAP::Mapping::Registry::TypedStructFactory,
+ { :type => XSD::QName.new("urn:GoogleSearch", "ResultElement") }
+ )
+ MappingRegistry.set(
+ DirectoryCategory,
+ ::SOAP::SOAPStruct,
+ ::SOAP::Mapping::Registry::TypedStructFactory,
+ { :type => XSD::QName.new("urn:GoogleSearch", "DirectoryCategory") }
+ )
+
+ Methods = [
+ ["doGetCachedPage", "doGetCachedPage", [
+ ["in", "key",
+ [SOAP::SOAPString]],
+ ["in", "url",
+ [SOAP::SOAPString]],
+ ["retval", "return",
+ [SOAP::SOAPBase64]]],
+ "urn:GoogleSearchAction", "urn:GoogleSearch"],
+ ["doSpellingSuggestion", "doSpellingSuggestion", [
+ ["in", "key",
+ [SOAP::SOAPString]],
+ ["in", "phrase",
+ [SOAP::SOAPString]],
+ ["retval", "return",
+ [SOAP::SOAPString]]],
+ "urn:GoogleSearchAction", "urn:GoogleSearch"],
+ ["doGoogleSearch", "doGoogleSearch", [
+ ["in", "key",
+ [SOAP::SOAPString]],
+ ["in", "q",
+ [SOAP::SOAPString]],
+ ["in", "start",
+ [SOAP::SOAPInt]],
+ ["in", "maxResults",
+ [SOAP::SOAPInt]],
+ ["in", "filter",
+ [SOAP::SOAPBoolean]],
+ ["in", "restrict",
+ [SOAP::SOAPString]],
+ ["in", "safeSearch",
+ [SOAP::SOAPBoolean]],
+ ["in", "lr",
+ [SOAP::SOAPString]],
+ ["in", "ie",
+ [SOAP::SOAPString]],
+ ["in", "oe",
+ [SOAP::SOAPString]],
+ ["retval", "return",
+ [::SOAP::SOAPStruct, "urn:GoogleSearch", "GoogleSearchResult"]]],
+ "urn:GoogleSearchAction", "urn:GoogleSearch"]
+ ]
+
+ DefaultEndpointUrl = "http://api.google.com/search/beta2"
+
+ def initialize(endpoint_url = nil)
+ endpoint_url ||= DefaultEndpointUrl
+ super(endpoint_url, nil)
+ self.mapping_registry = MappingRegistry
+ init_methods
+ end
+
+private
+
+ def init_methods
+ Methods.each do |name_as, name, params, soapaction, namespace|
+ qname = XSD::QName.new(namespace, name_as)
+ @proxy.add_method(qname, soapaction, name, params)
+ add_rpc_method_interface(name, params)
+ end
+ end
+end
+
diff --git a/sample/wsdl/googleSearch/README b/sample/wsdl/googleSearch/README
new file mode 100644
index 0000000000..461a5634dc
--- /dev/null
+++ b/sample/wsdl/googleSearch/README
@@ -0,0 +1,6 @@
+wsdlDriver.rb: Do google search using WSDL.
+
+Whole files except wsdl.rb in this directory is created by wsdl2ruby.rb from
+GoogleSearch.wsdl with options;
+
+% wsdl2ruby.rb --wsdl http://api.google.com/GoogleSearch.wsdl --classdef --client_skelton --servant_skelton --cgi_stub --standalone_server_stub --driver --force
diff --git a/sample/wsdl/googleSearch/httpd.rb b/sample/wsdl/googleSearch/httpd.rb
new file mode 100644
index 0000000000..bebcff96c6
--- /dev/null
+++ b/sample/wsdl/googleSearch/httpd.rb
@@ -0,0 +1,20 @@
+#!/usr/bin/env ruby
+
+require 'webrick'
+require 'soap/property'
+
+docroot = "."
+port = 8808
+if opt = SOAP::Property.loadproperty("samplehttpd.conf")
+ docroot = opt["docroot"]
+ port = Integer(opt["port"])
+end
+
+s = WEBrick::HTTPServer.new(
+ :BindAddress => "0.0.0.0",
+ :Port => port,
+ :DocumentRoot => docroot,
+ :CGIPathEnv => ENV['PATH']
+)
+trap(:INT){ s.shutdown }
+s.start
diff --git a/sample/wsdl/googleSearch/sampleClient.rb b/sample/wsdl/googleSearch/sampleClient.rb
new file mode 100644
index 0000000000..b05d57be54
--- /dev/null
+++ b/sample/wsdl/googleSearch/sampleClient.rb
@@ -0,0 +1,56 @@
+#!/usr/bin/env ruby
+
+# This file is a sample based on GoogleSearchClient.rb, which can be
+# generated by WSDL file and wsdl2ruby.rb.
+#
+# $ wsdl2ruby.rb --type client --force \
+# --wsdl http://api.google.com/GoogleSearch.wsdl
+#
+# See wsdlDriver.rb to use WSDL file directly (slow).
+require 'GoogleSearchDriver.rb'
+
+endpoint_url = ARGV.shift
+obj = GoogleSearchPort.new(endpoint_url)
+
+# Uncomment the below line to see SOAP wiredumps.
+# obj.wiredump_dev = STDERR
+
+# SYNOPSIS
+# doGoogleSearch(key, q, start, maxResults, filter, restrict, safeSearch, lr, ie, oe)
+#
+# ARGS
+# key - {http://www.w3.org/2001/XMLSchema}string
+# q - {http://www.w3.org/2001/XMLSchema}string
+# start - {http://www.w3.org/2001/XMLSchema}int
+# maxResults - {http://www.w3.org/2001/XMLSchema}int
+# filter - {http://www.w3.org/2001/XMLSchema}boolean
+# restrict - {http://www.w3.org/2001/XMLSchema}string
+# safeSearch - {http://www.w3.org/2001/XMLSchema}boolean
+# lr - {http://www.w3.org/2001/XMLSchema}string
+# ie - {http://www.w3.org/2001/XMLSchema}string
+# oe - {http://www.w3.org/2001/XMLSchema}string
+#
+# RETURNS
+# return GoogleSearchResult - {urn:GoogleSearch}GoogleSearchResult
+#
+# RAISES
+# N/A
+#
+key = q = start = maxResults = filter = restrict = safeSearch = lr = ie = oe = nil
+key = File.open(File.expand_path("~/.google_key")) { |f| f.read }.chomp
+q = "Ruby"
+start = 0
+maxResults = 10
+filter = false
+restrict = ""
+safeSearch = false
+lr = ""
+ie = "utf-8"
+oe = "utf-8"
+result = obj.doGoogleSearch(key, q, start, maxResults, filter, restrict, safeSearch, lr, ie, oe)
+
+result.resultElements.each do |ele|
+ puts "== #{ele.title}: #{ele.URL}"
+ puts ele.snippet
+ puts
+end
diff --git a/sample/wsdl/googleSearch/samplehttpd.conf b/sample/wsdl/googleSearch/samplehttpd.conf
new file mode 100644
index 0000000000..85e9995021
--- /dev/null
+++ b/sample/wsdl/googleSearch/samplehttpd.conf
@@ -0,0 +1,2 @@
+docroot = .
+port = 8808
diff --git a/sample/wsdl/googleSearch/sjissearch.sh b/sample/wsdl/googleSearch/sjissearch.sh
new file mode 100644
index 0000000000..b8efb20647
--- /dev/null
+++ b/sample/wsdl/googleSearch/sjissearch.sh
@@ -0,0 +1,3 @@
+#!/bin/sh -
+
+ruby -Ks wsdlDriver.rb 'Ruby ‚È‚Ð'
diff --git a/sample/wsdl/googleSearch/wsdlDriver.rb b/sample/wsdl/googleSearch/wsdlDriver.rb
new file mode 100644
index 0000000000..9059aed2df
--- /dev/null
+++ b/sample/wsdl/googleSearch/wsdlDriver.rb
@@ -0,0 +1,23 @@
+#require 'uconv'
+require 'soap/wsdlDriver'
+
+word = ARGV.shift
+# You must get key from http://www.google.com/apis/ to use Google Web APIs.
+key = File.open(File.expand_path("~/.google_key")) { |f| f.read }.chomp
+
+GOOGLE_WSDL = 'http://api.google.com/GoogleSearch.wsdl'
+# GOOGLE_WSDL = 'GoogleSearch.wsdl'
+
+def html2rd(str)
+ str.gsub(%r(<b>(.*?)</b>), '((*\\1*))').strip
+end
+
+
+google = SOAP::WSDLDriverFactory.new(GOOGLE_WSDL).create_driver
+#google.wiredump_dev = STDERR
+result = google.doGoogleSearch( key, word, 0, 10, false, "", false, "", 'utf-8', 'utf-8' )
+result.resultElements.each do |ele|
+ puts "== #{html2rd(ele.title)}: #{ele.URL}"
+ puts html2rd(ele.snippet)
+ puts
+end
diff --git a/sample/wsdl/raa/raa.wsdl b/sample/wsdl/raa/raa.wsdl
new file mode 100644
index 0000000000..78376893dd
--- /dev/null
+++ b/sample/wsdl/raa/raa.wsdl
@@ -0,0 +1,264 @@
+<?xml version="1.0"?>
+<definitions
+ name="RAA"
+ targetNamespace="http://www.ruby-lang.org/xmlns/soap/interface/RAA/0.0.2/"
+ xmlns:tns="http://www.ruby-lang.org/xmlns/soap/interface/RAA/0.0.2/"
+ xmlns:txd="http://www.ruby-lang.org/xmlns/soap/interface/RAA/0.0.2/"
+ xmlns="http://schemas.xmlsoap.org/wsdl/"
+ xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/"
+ xmlns:xsd="http://www.w3.org/2001/XMLSchema"
+ xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/"
+ xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/"
+ xmlns:apachesoap="http://xml.apache.org/xml-soap">
+
+ <types>
+ <schema
+ xmlns="http://www.w3.org/2001/XMLSchema"
+ targetNamespace="http://www.ruby-lang.org/xmlns/soap/interface/RAA/0.0.2/">
+
+ <complexType name="Category">
+ <all>
+ <element name="major" type="string"/>
+ <element name="minor" type="string"/>
+ </all>
+ </complexType>
+
+ <complexType name="Product">
+ <all>
+ <element name="id" type="int"/>
+ <element name="name" type="string"/>
+ <element name="short_description" type="string"/>
+ <element name="version" type="string"/>
+ <element name="status" type="string"/>
+ <element name="homepage" type="anyURI"/>
+ <element name="download" type="anyURI"/>
+ <element name="license" type="string"/>
+ <element name="description" type="string"/>
+ </all>
+ </complexType>
+
+ <complexType name="Owner">
+ <all>
+ <element name="id" type="int"/>
+ <element name="email" type="anyURI"/>
+ <element name="name" type="string"/>
+ </all>
+ </complexType>
+
+ <complexType name="Info">
+ <all>
+ <element name="category" type="txd:Category"/>
+ <element name="product" type="txd:Product"/>
+ <element name="owner" type="txd:Owner"/>
+ <element name="created" type="xsd:dateTime"/>
+ <element name="updated" type="xsd:dateTime"/>
+ </all>
+ </complexType>
+
+ <import namespace="http://schemas.xmlsoap.org/soap/encoding/"/>
+ <complexType name="InfoArray">
+ <complexContent>
+ <restriction base="soapenc:Array">
+ <attribute ref="soapenc:arrayType" wsdl:arrayType="txd:Info[]"/>
+ </restriction>
+ </complexContent>
+ </complexType>
+
+ <complexType name="StringArray">
+ <complexContent>
+ <restriction base="soapenc:Array">
+ <attribute ref="soapenc:arrayType" wsdl:arrayType="xsd:string[]"/>
+ </restriction>
+ </complexContent>
+ </complexType>
+ </schema>
+
+ <!-- type definition for ApacheSOAP's Map -->
+ <schema
+ xmlns="http://www.w3.org/2001/XMLSchema"
+ targetNamespace="http://xml.apache.org/xml-soap">
+ <complexType name="Map">
+ <sequence>
+ <element name="item" minOccurs="0" maxOccurs="unbounded">
+ <complexType>
+ <sequence>
+ <element name="key" type="anyType" />
+ <element name="value" type="anyType" />
+ </sequence>
+ </complexType>
+ </element>
+ </sequence>
+ </complexType>
+ </schema>
+ </types>
+
+ <message name="getAllListingsRequest"/>
+ <message name="getAllListingsResponse">
+ <part name="return" type="txd:StringArray"/>
+ </message>
+
+ <message name="getProductTreeRequest"/>
+ <message name="getProductTreeResponse">
+ <part name="return" type="apachesoap:Map"/>
+ </message>
+
+ <message name="getInfoFromCategoryRequest">
+ <part name="category" type="txd:Category"/>
+ </message>
+ <message name="getInfoFromCategoryResponse">
+ <part name="return" type="txd:InfoArray"/>
+ </message>
+
+ <message name="getModifiedInfoSinceRequest">
+ <part name="timeInstant" type="xsd:dateTime"/>
+ </message>
+ <message name="getModifiedInfoSinceResponse">
+ <part name="return" type="txd:InfoArray"/>
+ </message>
+
+ <message name="getInfoFromNameRequest">
+ <part name="productName" type="xsd:string"/>
+ </message>
+ <message name="getInfoFromNameResponse">
+ <part name="return" type="txd:Info"/>
+ </message>
+
+ <message name="getInfoFromOwnerIdRequest">
+ <part name="ownerId" type="xsd:int"/>
+ </message>
+ <message name="getInfoFromOwnerIdResponse">
+ <part name="return" type="txd:InfoArray"/>
+ </message>
+
+ <portType name="RAABaseServicePortType">
+ <operation name="getAllListings"
+ parameterOrder="">
+ <input message="tns:getAllListingsRequest"/>
+ <output message="tns:getAllListingsResponse"/>
+ </operation>
+
+ <operation name="getProductTree"
+ parameterOrder="">
+ <input message="tns:getProductTreeRequest"/>
+ <output message="tns:getProductTreeResponse"/>
+ </operation>
+
+ <operation name="getInfoFromCategory"
+ parameterOrder="category">
+ <input message="tns:getInfoFromCategoryRequest"/>
+ <output message="tns:getInfoFromCategoryResponse"/>
+ </operation>
+
+ <operation name="getModifiedInfoSince"
+ parameterOrder="timeInstant">
+ <input message="tns:getModifiedInfoSinceRequest"/>
+ <output message="tns:getModifiedInfoSinceResponse"/>
+ </operation>
+
+ <operation name="getInfoFromName"
+ parameterOrder="productName">
+ <input message="tns:getInfoFromNameRequest"/>
+ <output message="tns:getInfoFromNameResponse"/>
+ </operation>
+
+ <operation name="getInfoFromOwnerId"
+ parameterOrder="ownerId">
+ <input message="tns:getInfoFromOwnerIdRequest"/>
+ <output message="tns:getInfoFromOwnerIdResponse"/>
+ </operation>
+ </portType>
+
+ <binding name="RAABaseServicePortBinding" type="tns:RAABaseServicePortType">
+ <soap:binding style="rpc" transport="http://schemas.xmlsoap.org/soap/http"/>
+
+ <operation name="getAllListings">
+ <soap:operation soapAction=""/>
+ <input>
+ <soap:body use="encoded"
+ encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"
+ namespace="http://www.ruby-lang.org/xmlns/soap/interface/RAA/0.0.2/"/>
+ </input>
+ <output>
+ <soap:body use="encoded"
+ encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"
+ namespace="http://www.ruby-lang.org/xmlns/soap/interface/RAA/0.0.2/"/>
+ </output>
+ </operation>
+
+ <operation name="getProductTree">
+ <soap:operation soapAction=""/>
+ <input>
+ <soap:body use="encoded"
+ encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"
+ namespace="http://www.ruby-lang.org/xmlns/soap/interface/RAA/0.0.2/"/>
+ </input>
+ <output>
+ <soap:body use="encoded"
+ encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"
+ namespace="http://www.ruby-lang.org/xmlns/soap/interface/RAA/0.0.2/"/>
+ </output>
+ </operation>
+
+ <operation name="getInfoFromCategory">
+ <soap:operation soapAction=""/>
+ <input>
+ <soap:body use="encoded"
+ encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"
+ namespace="http://www.ruby-lang.org/xmlns/soap/interface/RAA/0.0.2/"/>
+ </input>
+ <output>
+ <soap:body use="encoded"
+ encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"
+ namespace="http://www.ruby-lang.org/xmlns/soap/interface/RAA/0.0.2/"/>
+ </output>
+ </operation>
+
+ <operation name="getModifiedInfoSince">
+ <soap:operation soapAction=""/>
+ <input>
+ <soap:body use="encoded"
+ encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"
+ namespace="http://www.ruby-lang.org/xmlns/soap/interface/RAA/0.0.2/"/>
+ </input>
+ <output>
+ <soap:body use="encoded"
+ encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"
+ namespace="http://www.ruby-lang.org/xmlns/soap/interface/RAA/0.0.2/"/>
+ </output>
+ </operation>
+
+ <operation name="getInfoFromName">
+ <soap:operation soapAction=""/>
+ <input>
+ <soap:body use="encoded"
+ encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"
+ namespace="http://www.ruby-lang.org/xmlns/soap/interface/RAA/0.0.2/"/>
+ </input>
+ <output>
+ <soap:body use="encoded"
+ encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"
+ namespace="http://www.ruby-lang.org/xmlns/soap/interface/RAA/0.0.2/"/>
+ </output>
+ </operation>
+
+ <operation name="getInfoFromOwnerId">
+ <soap:operation soapAction=""/>
+ <input>
+ <soap:body use="encoded"
+ encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"
+ namespace="http://www.ruby-lang.org/xmlns/soap/interface/RAA/0.0.2/"/>
+ </input>
+ <output>
+ <soap:body use="encoded"
+ encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"
+ namespace="http://www.ruby-lang.org/xmlns/soap/interface/RAA/0.0.2/"/>
+ </output>
+ </operation>
+ </binding>
+
+ <service name="RAAService">
+ <port name="RAABaseServicePort" binding="tns:RAABaseServicePortBinding">
+ <soap:address location="http://raa.ruby-lang.org/soap/1.0.2/"/>
+ </port>
+ </service>
+</definitions>
diff --git a/sample/wsdl/raa/soap4r.rb b/sample/wsdl/raa/soap4r.rb
new file mode 100644
index 0000000000..a70b3b5b21
--- /dev/null
+++ b/sample/wsdl/raa/soap4r.rb
@@ -0,0 +1,31 @@
+#!/usr/bin/env ruby
+
+require 'soap/wsdlDriver'
+wsdl = 'http://www.ruby-lang.org/xmlns/soap/interface/RAA/0.0.2/'
+raa = SOAP::WSDLDriverFactory.new(wsdl).create_driver
+raa.generate_explicit_type = true
+p "WSDL loaded."
+
+class Category
+ def initialize(major, minor)
+ @major = major
+ @minor = minor
+ end
+end
+
+p raa.getAllListings().sort
+
+p raa.getProductTree()
+
+p raa.getInfoFromCategory(Category.new("Library", "XML"))
+
+t = Time.at(Time.now.to_i - 24 * 3600)
+p raa.getModifiedInfoSince(t)
+
+p raa.getModifiedInfoSince(DateTime.new(t.year, t.mon, t.mday, t.hour, t.min, t.sec))
+
+o = raa.getInfoFromName("SOAP4R")
+p o.type
+p o.owner.name
+p o
+
diff --git a/sample/wsdl/raa2.4/raa.rb b/sample/wsdl/raa2.4/raa.rb
new file mode 100644
index 0000000000..9b4c4e41aa
--- /dev/null
+++ b/sample/wsdl/raa2.4/raa.rb
@@ -0,0 +1,332 @@
+# http://www.ruby-lang.org/xmlns/soap/type/RAA/0.0.3/
+class Gem
+ @@schema_type = "Gem"
+ @@schema_ns = "http://www.ruby-lang.org/xmlns/soap/type/RAA/0.0.3/"
+
+ def id
+ @id
+ end
+
+ def id=(value)
+ @id = value
+ end
+
+ def category
+ @category
+ end
+
+ def category=(value)
+ @category = value
+ end
+
+ def owner
+ @owner
+ end
+
+ def owner=(value)
+ @owner = value
+ end
+
+ def project
+ @project
+ end
+
+ def project=(value)
+ @project = value
+ end
+
+ def updated
+ @updated
+ end
+
+ def updated=(value)
+ @updated = value
+ end
+
+ def created
+ @created
+ end
+
+ def created=(value)
+ @created = value
+ end
+
+ def initialize(id = nil,
+ category = nil,
+ owner = nil,
+ project = nil,
+ updated = nil,
+ created = nil)
+ @id = id
+ @category = category
+ @owner = owner
+ @project = project
+ @updated = updated
+ @created = created
+ end
+end
+
+# http://www.ruby-lang.org/xmlns/soap/type/RAA/0.0.3/
+class Category
+ @@schema_type = "Category"
+ @@schema_ns = "http://www.ruby-lang.org/xmlns/soap/type/RAA/0.0.3/"
+
+ def major
+ @major
+ end
+
+ def major=(value)
+ @major = value
+ end
+
+ def minor
+ @minor
+ end
+
+ def minor=(value)
+ @minor = value
+ end
+
+ def initialize(major = nil,
+ minor = nil)
+ @major = major
+ @minor = minor
+ end
+end
+
+# http://www.ruby-lang.org/xmlns/soap/type/RAA/0.0.3/
+class Owner
+ @@schema_type = "Owner"
+ @@schema_ns = "http://www.ruby-lang.org/xmlns/soap/type/RAA/0.0.3/"
+
+ def id
+ @id
+ end
+
+ def id=(value)
+ @id = value
+ end
+
+ def email
+ @email
+ end
+
+ def email=(value)
+ @email = value
+ end
+
+ def name
+ @name
+ end
+
+ def name=(value)
+ @name = value
+ end
+
+ def initialize(id = nil,
+ email = nil,
+ name = nil)
+ @id = id
+ @email = email
+ @name = name
+ end
+end
+
+# http://www.ruby-lang.org/xmlns/soap/type/RAA/0.0.3/
+class Project
+ @@schema_type = "Project"
+ @@schema_ns = "http://www.ruby-lang.org/xmlns/soap/type/RAA/0.0.3/"
+
+ def name
+ @name
+ end
+
+ def name=(value)
+ @name = value
+ end
+
+ def short_description
+ @short_description
+ end
+
+ def short_description=(value)
+ @short_description = value
+ end
+
+ def version
+ @version
+ end
+
+ def version=(value)
+ @version = value
+ end
+
+ def status
+ @status
+ end
+
+ def status=(value)
+ @status = value
+ end
+
+ def url
+ @url
+ end
+
+ def url=(value)
+ @url = value
+ end
+
+ def download
+ @download
+ end
+
+ def download=(value)
+ @download = value
+ end
+
+ def license
+ @license
+ end
+
+ def license=(value)
+ @license = value
+ end
+
+ def description
+ @description
+ end
+
+ def description=(value)
+ @description = value
+ end
+
+ def updated
+ @updated
+ end
+
+ def updated=(value)
+ @updated = value
+ end
+
+ def history
+ @history
+ end
+
+ def history=(value)
+ @history = value
+ end
+
+ def dependency
+ @dependency
+ end
+
+ def dependency=(value)
+ @dependency = value
+ end
+
+ def initialize(name = nil,
+ short_description = nil,
+ version = nil,
+ status = nil,
+ url = nil,
+ download = nil,
+ license = nil,
+ description = nil,
+ updated = nil,
+ history = nil,
+ dependency = nil)
+ @name = name
+ @short_description = short_description
+ @version = version
+ @status = status
+ @url = url
+ @download = download
+ @license = license
+ @description = description
+ @updated = updated
+ @history = history
+ @dependency = dependency
+ end
+end
+
+# http://www.ruby-lang.org/xmlns/soap/type/RAA/0.0.3/
+class ProjectDependency
+ @@schema_type = "ProjectDependency"
+ @@schema_ns = "http://www.ruby-lang.org/xmlns/soap/type/RAA/0.0.3/"
+
+ def project
+ @project
+ end
+
+ def project=(value)
+ @project = value
+ end
+
+ def version
+ @version
+ end
+
+ def version=(value)
+ @version = value
+ end
+
+ def description
+ @description
+ end
+
+ def description=(value)
+ @description = value
+ end
+
+ def initialize(project = nil,
+ version = nil,
+ description = nil)
+ @project = project
+ @version = version
+ @description = description
+ end
+end
+
+# http://www.ruby-lang.org/xmlns/soap/type/RAA/0.0.3/
+class GemArray < Array
+ # Contents type should be dumped here...
+ @@schema_type = "GemArray"
+ @@schema_ns = "http://www.ruby-lang.org/xmlns/soap/type/RAA/0.0.3/"
+end
+
+# http://www.ruby-lang.org/xmlns/soap/type/RAA/0.0.3/
+class OwnerArray < Array
+ # Contents type should be dumped here...
+ @@schema_type = "OwnerArray"
+ @@schema_ns = "http://www.ruby-lang.org/xmlns/soap/type/RAA/0.0.3/"
+end
+
+# http://www.ruby-lang.org/xmlns/soap/type/RAA/0.0.3/
+class ProjectArray < Array
+ # Contents type should be dumped here...
+ @@schema_type = "ProjectArray"
+ @@schema_ns = "http://www.ruby-lang.org/xmlns/soap/type/RAA/0.0.3/"
+end
+
+# http://www.ruby-lang.org/xmlns/soap/type/RAA/0.0.3/
+class ProjectDependencyArray < Array
+ # Contents type should be dumped here...
+ @@schema_type = "ProjectDependencyArray"
+ @@schema_ns = "http://www.ruby-lang.org/xmlns/soap/type/RAA/0.0.3/"
+end
+
+# http://www.ruby-lang.org/xmlns/soap/type/RAA/0.0.3/
+class StringArray < Array
+ # Contents type should be dumped here...
+ @@schema_type = "StringArray"
+ @@schema_ns = "http://www.ruby-lang.org/xmlns/soap/type/RAA/0.0.3/"
+end
+
+# http://xml.apache.org/xml-soap
+class Map < Array
+ # Contents type should be dumped here...
+ @@schema_type = "Map"
+ @@schema_ns = "http://xml.apache.org/xml-soap"
+end
+
diff --git a/sample/wsdl/raa2.4/wsdlDriver.rb b/sample/wsdl/raa2.4/wsdlDriver.rb
new file mode 100644
index 0000000000..bc5fb19982
--- /dev/null
+++ b/sample/wsdl/raa2.4/wsdlDriver.rb
@@ -0,0 +1,117 @@
+#!/usr/bin/env ruby
+
+# You can generate raa.rb required here with the command;
+# wsdl2ruby.rb --wsdl http://www.ruby-lang.org/xmlns/soap/interface/RAA/0.0.4/ --classdef
+require 'raa'
+require 'soap/wsdlDriver'
+require 'pp'
+
+RAA_WSDL = 'http://www.ruby-lang.org/xmlns/soap/interface/RAA/0.0.4/'
+
+raa = SOAP::WSDLDriverFactory.new(RAA_WSDL).create_driver
+raa.generate_explicit_type = true
+# raa.wiredump_dev = STDERR
+
+def sec(msg)
+ puts
+ puts "--------"
+ puts "-- " + msg
+ puts
+end
+
+def subsec(msg)
+ puts "-- " + msg
+end
+
+sec("retrieve a gem (RAA Information) which has specified name")
+name = 'soap4r'
+pp raa.gem(name)
+
+sec("retrieve dependents of the project")
+name = 'http-access2'; version = nil
+pp raa.dependents(name, version)
+
+sec("number of registered gems")
+puts raa.size
+
+sec("retrieve all registered gem names")
+p raa.names
+
+sec("retrieve gems of specified category")
+major = 'Library'; minor = 'XML'
+p raa.list_by_category(major, minor)
+
+sec("retrieve category tree")
+pp raa.tree_by_category
+
+sec("retrieve gems which is updated recently")
+idx = 0
+p raa.list_recent_updated(idx)
+subsec("next 10 gems")
+idx += 1
+p raa.list_recent_updated(idx)
+subsec("next 10 gems")
+idx += 1
+p raa.list_recent_updated(idx)
+
+sec("retrieve gems which is created recently")
+p raa.list_recent_created(idx)
+
+sec("retrieve gems which is updated in 7 days")
+date = Time.now - 7 * 24 * 60 * 60; idx = 0
+p raa.list_updated_since(date, idx)
+
+sec("retrieve gems which is created in 7 days")
+p raa.list_created_since(date, idx)
+
+sec("retrieve gems of specified owner")
+owner_id = 8 # NaHi
+p raa.list_by_owner(owner_id)
+
+sec("search gems with keyword")
+substring = 'soap'
+pp raa.search(substring)
+
+# There are several search interface to search a field explicitly.
+# puts raa.search_name(substring, idx)
+# puts raa.search_short_description(substring, idx)
+# puts raa.search_owner(substring, idx)
+# puts raa.search_version(substring, idx)
+# puts raa.search_status(substring, idx)
+# puts raa.search_description(substring, idx)
+
+sec("retrieve owner info")
+owner_id = 8
+pp raa.owner(owner_id)
+
+sec("retrieve owners")
+idx = 0
+p raa.list_owner(idx)
+
+sec("update 'sampleproject'")
+name = 'sampleproject'
+pass = 'sampleproject'
+gem = raa.gem(name)
+p gem.project.version
+gem.project.version.succ!
+gem.updated = Time.now
+raa.update(name, pass, gem)
+p raa.gem(name).project.version
+
+sec("update pass phrase")
+raa.update_pass(name, 'sampleproject', 'foo')
+subsec("update check")
+gem = raa.gem(name)
+gem.project.description = 'Current pass phrase is "foo"'
+gem.updated = Time.now
+raa.update(name, 'foo', gem)
+#
+subsec("recover pass phrase")
+raa.update_pass(name, 'foo', 'sampleproject')
+subsec("update check")
+gem = raa.gem(name)
+gem.project.description = 'Current pass phrase is "sampleproject"'
+gem.updated = Time.now
+raa.update(name, 'sampleproject', gem)
+
+sec("done")
diff --git a/signal.c b/signal.c
index 3003ceabf9..c45d3c95f4 100644
--- a/signal.c
+++ b/signal.c
@@ -33,7 +33,6 @@ static struct signals {
char *signm;
int signo;
} siglist [] = {
- {"EXIT", 0},
#ifdef SIGHUP
{"HUP", SIGHUP},
#endif
@@ -509,7 +508,7 @@ static RETSIGTYPE
sigexit(sig)
int sig;
{
- rb_thread_signal_exit();
+ rb_exit(0);
}
static VALUE
@@ -583,7 +582,7 @@ trap(arg)
}
#if defined(HAVE_SETITIMER)
if (sig == SIGVTALRM) {
- rb_raise(rb_eArgError, "SIGVTALRM reserved for Thread; can't set handler");
+ rb_raise(rb_eArgError, "SIGVTALRM reserved for Thread; cannot set handler");
}
#endif
if (func == SIG_DFL) {
diff --git a/sprintf.c b/sprintf.c
index dabdc93e7e..38283919e6 100644
--- a/sprintf.c
+++ b/sprintf.c
@@ -107,7 +107,7 @@ sign_bits(base, p)
(posarg = -1, GETNTHARG(n))))
#define GETNTHARG(nth) \
- ((nth >= argc) ? (rb_raise(rb_eArgError, "too few arguments"), 0) : argv[nth])
+ ((nth >= argc) ? (rb_raise(rb_eArgError, "too few arguments."), 0) : argv[nth])
#define GETASTER(val) do { \
t = p++; \
@@ -146,7 +146,7 @@ sign_bits(base, p)
*
* Flag | Applies to | Meaning
* ---------+--------------+-----------------------------------------
- * space | bdeEfgGiouxX | Leave a space at the start of
+ * space | bdeEfgGioxXu | Leave a space at the start of
* | | positive numbers.
* ---------+--------------+-----------------------------------------
* (digit)$ | all | Specifies the absolute argument number
@@ -162,11 +162,11 @@ sign_bits(base, p)
* | | point to be added, even if no digits follow.
* | | For `g' and 'G', do not remove trailing zeros.
* ---------+--------------+-----------------------------------------
- * + | bdeEfgGiouxX | Add a leading plus sign to positive numbers.
+ * + | bdeEfgGioxXu | Add a leading plus sign to positive numbers.
* ---------+--------------+-----------------------------------------
* - | all | Left-justify the result of this conversion.
* ---------+--------------+-----------------------------------------
- * 0 (zero) | bdeEfgGiouxX | Pad with zeros, not spaces.
+ * 0 (zero) | all | Pad with zeros, not spaces.
* ---------+--------------+-----------------------------------------
* * | all | Use the next argument as the field width.
* | | If negative, left-justify the result. If the
@@ -249,7 +249,6 @@ rb_f_sprintf(argc, argv)
fmt = GETNTHARG(0);
if (OBJ_TAINTED(fmt)) tainted = 1;
StringValue(fmt);
- fmt = rb_str_new4(fmt);
p = RSTRING(fmt)->ptr;
end = p + RSTRING(fmt)->len;
blen = 0;
@@ -771,12 +770,11 @@ rb_f_sprintf(argc, argv)
}
sprint_exit:
- /* XXX - We cannot validiate the number of arguments if (digit)$ style used.
+ /* XXX - We cannot validiate the number of arguments because
+ * the format string may contain `n$'-style argument selector.
*/
- if (posarg >= 0 && nextarg < argc) {
- const char *mesg = "too many arguments for format string";
- if (RTEST(ruby_debug)) rb_raise(rb_eArgError, mesg);
- if (RTEST(ruby_verbose)) rb_warn(mesg);
+ if (RTEST(ruby_verbose) && posarg >= 0 && nextarg < argc) {
+ rb_raise(rb_eArgError, "too many arguments for format string");
}
rb_str_resize(result, blen);
diff --git a/st.c b/st.c
index f83b2b70e5..12ed401145 100644
--- a/st.c
+++ b/st.c
@@ -5,12 +5,14 @@
#include "config.h"
#include "defines.h"
#include <stdio.h>
-#ifdef HAVE_STDLIB_H
#include <stdlib.h>
-#endif
#include <string.h>
#include "st.h"
+#ifdef _WIN32
+#include <malloc.h>
+#endif
+
typedef struct st_table_entry st_table_entry;
struct st_table_entry {
@@ -216,12 +218,12 @@ st_free_table(table)
ptr = table->bins[i];
while (ptr != 0) {
next = ptr->next;
- xfree(ptr);
+ free(ptr);
ptr = next;
}
}
- xfree(table->bins);
- xfree(table);
+ free(table->bins);
+ free(table);
}
#define PTR_NOT_EQUAL(table, ptr, hash_val, key) \
@@ -340,7 +342,7 @@ rehash(table)
ptr = next;
}
}
- xfree(table->bins);
+ free(table->bins);
table->num_bins = new_num_bins;
table->bins = new_bins;
}
@@ -363,7 +365,7 @@ st_copy(old_table)
Calloc((unsigned)num_bins, sizeof(st_table_entry*));
if (new_table->bins == 0) {
- xfree(new_table);
+ free(new_table);
return 0;
}
@@ -373,8 +375,8 @@ st_copy(old_table)
while (ptr != 0) {
entry = alloc(st_table_entry);
if (entry == 0) {
- xfree(new_table->bins);
- xfree(new_table);
+ free(new_table->bins);
+ free(new_table);
return 0;
}
*entry = *ptr;
@@ -409,7 +411,7 @@ st_delete(table, key, value)
table->num_entries--;
if (value != 0) *value = ptr->record;
*key = ptr->key;
- xfree(ptr);
+ free(ptr);
return 1;
}
@@ -420,7 +422,7 @@ st_delete(table, key, value)
table->num_entries--;
if (value != 0) *value = tmp->record;
*key = tmp->key;
- xfree(tmp);
+ free(tmp);
return 1;
}
}
@@ -478,7 +480,7 @@ st_cleanup_safe(table, never)
table->num_entries = num_entries;
}
-int
+void
st_foreach(table, func, arg)
st_table *table;
int (*func)();
@@ -491,7 +493,7 @@ st_foreach(table, func, arg)
for(i = 0; i < table->num_bins; i++) {
last = 0;
for(ptr = table->bins[i]; ptr != 0;) {
- retval = (*func)(ptr->key, ptr->record, arg);
+ retval = (*func)(ptr->key, ptr->record, arg, 0);
switch (retval) {
case ST_CHECK: /* check if hash is modified during iteration */
tmp = 0;
@@ -502,7 +504,8 @@ st_foreach(table, func, arg)
}
if (!tmp) {
/* call func with error notice */
- return 1;
+ retval = (*func)(0, 0, arg, 1);
+ return;
}
/* fall through */
case ST_CONTINUE:
@@ -510,7 +513,7 @@ st_foreach(table, func, arg)
ptr = ptr->next;
break;
case ST_STOP:
- return 0;
+ return;
case ST_DELETE:
tmp = ptr;
if (last == 0) {
@@ -520,12 +523,11 @@ st_foreach(table, func, arg)
last->next = ptr->next;
}
ptr = ptr->next;
- xfree(tmp);
+ free(tmp);
table->num_entries--;
}
}
}
- return 0;
}
static int
diff --git a/st.h b/st.h
index 5901bd4f80..cdf8a1220b 100644
--- a/st.h
+++ b/st.h
@@ -27,32 +27,21 @@ struct st_table {
enum st_retval {ST_CONTINUE, ST_STOP, ST_DELETE, ST_CHECK};
-#ifndef _
-# define _(args) args
-#endif
-#ifndef ANYARGS
-# ifdef __cplusplus
-# define ANYARGS ...
-# else
-# define ANYARGS
-# endif
-#endif
-
-st_table *st_init_table _((struct st_hash_type *));
-st_table *st_init_table_with_size _((struct st_hash_type *, int));
-st_table *st_init_numtable _((void));
-st_table *st_init_numtable_with_size _((int));
-st_table *st_init_strtable _((void));
-st_table *st_init_strtable_with_size _((int));
-int st_delete _((st_table *, st_data_t *, st_data_t *));
-int st_delete_safe _((st_table *, st_data_t *, st_data_t *, st_data_t));
-int st_insert _((st_table *, st_data_t, st_data_t));
-int st_lookup _((st_table *, st_data_t, st_data_t *));
-int st_foreach _((st_table *, int (*)(ANYARGS), st_data_t));
-void st_add_direct _((st_table *, st_data_t, st_data_t));
-void st_free_table _((st_table *));
-void st_cleanup_safe _((st_table *, st_data_t));
-st_table *st_copy _((st_table *));
+st_table *st_init_table(struct st_hash_type *);
+st_table *st_init_table_with_size(struct st_hash_type *, int);
+st_table *st_init_numtable(void);
+st_table *st_init_numtable_with_size(int);
+st_table *st_init_strtable(void);
+st_table *st_init_strtable_with_size(int);
+int st_delete(st_table *, st_data_t *, st_data_t *);
+int st_delete_safe(st_table *, st_data_t *, st_data_t *, st_data_t);
+int st_insert(st_table *, st_data_t, st_data_t);
+int st_lookup(st_table *, st_data_t, st_data_t *);
+void st_foreach(st_table *, int (*)(), st_data_t);
+void st_add_direct(st_table *, st_data_t, st_data_t);
+void st_free_table(st_table *);
+void st_cleanup_safe(st_table *, st_data_t);
+st_table *st_copy(st_table *);
#define ST_NUMCMP ((int (*)()) 0)
#define ST_NUMHASH ((int (*)()) -2)
diff --git a/string.c b/string.c
index c428ea7d76..12f0474495 100644
--- a/string.c
+++ b/string.c
@@ -50,15 +50,6 @@ str_mod_check(s, p, len)
}
}
-static inline void
-str_frozen_check(s)
- VALUE s;
-{
- if (OBJ_FROZEN(s)) {
- rb_raise(rb_eRuntimeError, "string frozen");
- }
-}
-
static VALUE str_alloc _((VALUE));
static VALUE
str_alloc(klass)
@@ -201,7 +192,6 @@ rb_str_new4(orig)
else {
str = str_new4(klass, orig);
}
- OBJ_INFECT(str, orig);
OBJ_FREEZE(str);
return str;
}
@@ -416,16 +406,17 @@ rb_str_times(str, times)
long i, len;
len = NUM2LONG(times);
+ if (len == 0) return rb_str_new5(str,0,0);
if (len < 0) {
rb_raise(rb_eArgError, "negative argument");
}
- if (len && LONG_MAX/len < RSTRING(str)->len) {
+ if (LONG_MAX/len < RSTRING(str)->len) {
rb_raise(rb_eArgError, "argument too big");
}
- str2 = rb_str_new5(str,0, len *= RSTRING(str)->len);
- for (i = 0; i < len; i += RSTRING(str)->len) {
- memcpy(RSTRING(str2)->ptr + i,
+ str2 = rb_str_new5(str,0, RSTRING(str)->len*len);
+ for (i=0; i<len; i++) {
+ memcpy(RSTRING(str2)->ptr+(i*RSTRING(str)->len),
RSTRING(str)->ptr, RSTRING(str)->len);
}
RSTRING(str2)->ptr[RSTRING(str2)->len] = '\0';
@@ -605,10 +596,9 @@ rb_str_substr(str, beg, len)
if (len < 0) {
len = 0;
}
- if (len == 0) {
- str2 = rb_str_new5(str,0,0);
- }
- else if (len > sizeof(struct RString)/2 &&
+ if (len == 0) return rb_str_new5(str,0,0);
+
+ if (len > sizeof(struct RString)/2 &&
beg + len == RSTRING(str)->len && !FL_TEST(str, STR_ASSOC)) {
str2 = rb_str_new3(rb_str_new4(str));
RSTRING(str2)->ptr += RSTRING(str2)->len - len;
@@ -677,8 +667,8 @@ rb_str_resize(str, len)
rb_raise(rb_eArgError, "negative string size (or size too big)");
}
- rb_str_modify(str);
if (len != RSTRING(str)->len) {
+ rb_str_modify(str);
if (RSTRING(str)->len < len || RSTRING(str)->len - len > 1024) {
REALLOC_N(RSTRING(str)->ptr, char, len+1);
if (!FL_TEST(str, STR_NOCAPA)) {
@@ -796,8 +786,8 @@ VALUE
rb_str_append(str, str2)
VALUE str, str2;
{
- StringValue(str2);
rb_str_modify(str);
+ StringValue(str2);
if (RSTRING(str2)->len > 0) {
if (FL_TEST(str, STR_ASSOC)) {
long len = RSTRING(str)->len+RSTRING(str2)->len;
@@ -947,8 +937,6 @@ rb_str_equal(str1, str2)
return Qfalse;
}
-#define IS_EVSTR(p,e) ((p) < (e) && (*(p) == '$' || *(p) == '@' || *(p) == '{'))
-
/*
* call-seq:
* str.eql?(other) => true or false
@@ -1003,7 +991,7 @@ rb_str_cmp_m(str1, str2)
if (TYPE(str2) != T_STRING) {
if (!rb_respond_to(str2, rb_intern("to_str"))) {
- return Qnil;
+ return Qfalse;
}
else if (!rb_respond_to(str2, rb_intern("<=>"))) {
return Qnil;
@@ -1389,7 +1377,7 @@ rb_str_succ(orig)
int c = -1;
long n = 0;
- str = rb_str_new5(orig, RSTRING(orig)->ptr, RSTRING(orig)->len);
+ str = rb_str_new5(orig,RSTRING(orig)->ptr, RSTRING(orig)->len);
OBJ_INFECT(str, orig);
if (RSTRING(str)->len == 0) return str;
@@ -1540,17 +1528,13 @@ rb_str_aref(str, indx)
/* check if indx is Range */
{
long beg, len;
- VALUE tmp;
-
switch (rb_range_beg_len(indx, &beg, &len, RSTRING(str)->len, 0)) {
case Qfalse:
break;
case Qnil:
return Qnil;
default:
- tmp = rb_str_substr(str, beg, len);
- OBJ_INFECT(tmp, indx);
- return tmp;
+ return rb_str_substr(str, beg, len);
}
}
idx = NUM2LONG(indx);
@@ -1632,10 +1616,6 @@ rb_str_splice(str, beg, len, val)
VALUE val;
{
if (len < 0) rb_raise(rb_eIndexError, "negative length %ld", len);
-
- StringValue(val);
- rb_str_modify(str);
-
if (RSTRING(str)->len < beg) {
out_of_range:
rb_raise(rb_eIndexError, "index %ld out of string", beg);
@@ -1650,6 +1630,7 @@ rb_str_splice(str, beg, len, val)
len = RSTRING(str)->len - beg;
}
+ StringValue(val);
if (len < RSTRING(val)->len) {
/* expand string */
RESIZE_CAPA(str, RSTRING(str)->len + RSTRING(val)->len - len + 1);
@@ -1679,6 +1660,7 @@ rb_str_update(str, beg, len, val)
long beg, len;
VALUE val;
{
+ rb_str_modify(str);
rb_str_splice(str, beg, len, val);
}
@@ -1712,6 +1694,7 @@ rb_str_subpat_set(str, re, nth, val)
}
end = RMATCH(match)->END(nth);
len = end - start;
+ rb_str_modify(str);
rb_str_splice(str, start, len, val);
}
@@ -1736,7 +1719,6 @@ rb_str_aset(str, indx, val)
idx += RSTRING(str)->len;
}
if (FIXNUM_P(val)) {
- rb_str_modify(str);
if (RSTRING(str)->len == idx) {
RSTRING(str)->len += 1;
RESIZE_CAPA(str, RSTRING(str)->len);
@@ -1805,6 +1787,7 @@ rb_str_aset_m(argc, argv, str)
VALUE *argv;
VALUE str;
{
+ rb_str_modify(str);
if (argc == 3) {
if (TYPE(argv[0]) == T_REGEXP) {
rb_str_subpat_set(str, argv[0], NUM2INT(argv[1]), argv[2]);
@@ -1843,6 +1826,7 @@ rb_str_insert(str, idx, str2)
{
long pos = NUM2LONG(idx);
+ rb_str_modify(str);
if (pos == -1) {
pos = RSTRING(str)->len;
}
@@ -1974,8 +1958,9 @@ rb_str_sub_bang(argc, argv, str)
rb_match_busy(match);
repl = rb_obj_as_string(rb_yield(rb_reg_nth_match(0, match)));
- str_mod_check(str, p, len);
- str_frozen_check(str);
+ if (RSTRING(str)->ptr != p || RSTRING(str)->len != len) {
+ rb_raise(rb_eRuntimeError, "string modified");
+ }
rb_backref_set(match);
}
else {
@@ -2080,7 +2065,7 @@ str_gsub(argc, argv, str, bang)
}
blen = RSTRING(str)->len + 30; /* len + margin */
- dest = str_new(0, 0, blen);
+ dest = rb_str_new5(str, 0, blen);
buf = RSTRING(dest)->ptr;
bp = buf;
sp = cp = RSTRING(str)->ptr;
@@ -2095,10 +2080,6 @@ str_gsub(argc, argv, str, bang)
rb_match_busy(match);
val = rb_obj_as_string(rb_yield(rb_reg_nth_match(0, match)));
str_mod_check(str, sp, slen);
- if (bang) str_frozen_check(str);
- if (val == dest) { /* paranoid chack [ruby-dev:24827] */
- rb_raise(rb_eRuntimeError, "block should not cheat");
- }
rb_backref_set(match);
}
else {
@@ -2160,7 +2141,6 @@ str_gsub(argc, argv, str, bang)
RSTRING(dest)->len = 0;
}
else {
- RBASIC(dest)->klass = rb_obj_class(str);
OBJ_INFECT(dest, str);
str = dest;
}
@@ -2547,6 +2527,7 @@ rb_str_to_s(str)
return str;
}
+VALUE
/*
* call-seq:
* str.inspect => string
@@ -2559,7 +2540,6 @@ rb_str_to_s(str)
* str.inspect #=> "hel\010o"
*/
-VALUE
rb_str_inspect(str)
VALUE str;
{
@@ -2575,7 +2555,7 @@ rb_str_inspect(str)
rb_str_buf_cat(result, p - 1, len);
p += len - 1;
}
- else if (c == '"'|| c == '\\' || (c == '#' && IS_EVSTR(p, pend))) {
+ else if (c == '"'|| c == '\\') {
s[0] = '\\'; s[1] = c;
rb_str_buf_cat(result, s, 2);
}
@@ -2647,15 +2627,11 @@ rb_str_dump(str)
switch (c) {
case '"': case '\\':
case '\n': case '\r':
- case '\t': case '\f':
+ case '\t': case '\f': case '#':
case '\013': case '\007': case '\033':
len += 2;
break;
- case '#':
- len += IS_EVSTR(p, pend) ? 2 : 1;
- break;
-
default:
if (ISPRINT(c)) {
len++;
@@ -2680,7 +2656,7 @@ rb_str_dump(str)
*q++ = c;
}
else if (c == '#') {
- if (IS_EVSTR(p, pend)) *q++ = '\\';
+ *q++ = '\\';
*q++ = '#';
}
else if (ISPRINT(c)) {
@@ -3879,8 +3855,8 @@ rb_str_chomp_bang(argc, argv, str)
rs = rb_rs;
if (rs == rb_default_rs) {
smart_chomp:
- rb_str_modify(str);
if (RSTRING(str)->ptr[len-1] == '\n') {
+ rb_str_modify(str);
RSTRING(str)->len--;
if (RSTRING(str)->len > 0 &&
RSTRING(str)->ptr[RSTRING(str)->len-1] == '\r') {
@@ -3888,6 +3864,7 @@ rb_str_chomp_bang(argc, argv, str)
}
}
else if (RSTRING(str)->ptr[len-1] == '\r') {
+ rb_str_modify(str);
RSTRING(str)->len--;
}
else {
@@ -4189,7 +4166,7 @@ scan_once(str, pat, start)
/*
* Always consume at least one character of the input string
*/
- if (RSTRING(str)->len > END(0))
+ if (RSTRING(str)->len < END(0))
*start = END(0)+mbclen2(RSTRING(str)->ptr[END(0)],pat);
else
*start = END(0)+1;
@@ -4479,16 +4456,15 @@ rb_str_justify(argc, argv, str, jflag)
rb_scan_args(argc, argv, "11", &w, &pad);
width = NUM2LONG(w);
- if (argc == 2) {
+ if (width < 0 || RSTRING(str)->len >= width) return rb_str_dup(str);
+ res = rb_str_new5(str, 0, width);
+ if (argc == 0) {
StringValue(pad);
- f = RSTRING(pad)->ptr;
- flen = RSTRING(pad)->len;
- if (flen == 0) {
- rb_raise(rb_eArgError, "zero width padding");
+ if (RSTRING(pad)->len > 0) {
+ f = RSTRING(pad)->ptr;
+ flen = RSTRING(pad)->len;
}
}
- if (width < 0 || RSTRING(str)->len >= width) return rb_str_dup(str);
- res = rb_str_new5(str, 0, width);
p = RSTRING(res)->ptr;
if (jflag != 'l') {
n = width - RSTRING(str)->len;
@@ -4535,15 +4511,14 @@ rb_str_justify(argc, argv, str, jflag)
/*
* call-seq:
- * str.ljust(integer, padstr=' ') => new_str
+ * str.ljust(integer) => new_str
*
* If <i>integer</i> is greater than the length of <i>str</i>, returns a new
* <code>String</code> of length <i>integer</i> with <i>str</i> left justified
- * and padded with <i>padstr</i>; otherwise, returns <i>str</i>.
+ * and space padded; otherwise, returns <i>str</i>.
*
- * "hello".ljust(4) #=> "hello"
- * "hello".ljust(20) #=> "hello "
- * "hello".ljust(20, '1234') #=> "hello123412341234123"
+ * "hello".ljust(4) #=> "hello"
+ * "hello".ljust(20) #=> "hello "
*/
static VALUE
@@ -4558,15 +4533,14 @@ rb_str_ljust(argc, argv, str)
/*
* call-seq:
- * str.rjust(integer, padstr=' ') => new_str
+ * str.rjust(integer) => new_str
*
* If <i>integer</i> is greater than the length of <i>str</i>, returns a new
* <code>String</code> of length <i>integer</i> with <i>str</i> right justified
- * and padded with <i>padstr</i>; otherwise, returns <i>str</i>.
+ * and space padded; otherwise, returns <i>str</i>.
*
- * "hello".rjust(4) #=> "hello"
- * "hello".rjust(20) #=> " hello"
- * "hello".rjust(20, '1234') #=> "123412341234123hello"
+ * "hello".rjust(4) #=> "hello"
+ * "hello".rjust(20) #=> " hello"
*/
static VALUE
@@ -4581,15 +4555,14 @@ rb_str_rjust(argc, argv, str)
/*
* call-seq:
- * str.center(integer, padstr) => new_str
+ * str.center(integer) => new_str
*
* If <i>integer</i> is greater than the length of <i>str</i>, returns a new
- * <code>String</code> of length <i>integer</i> with <i>str</i> centered and
- * padded with <i>padstr</i>; otherwise, returns <i>str</i>.
+ * <code>String</code> of length <i>integer</i> with <i>str</i> centered
+ * between spaces; otherwise, returns <i>str</i>.
*
- * "hello".center(4) #=> "hello"
- * "hello".center(20) #=> " hello "
- * "hello".center(20, '123') #=> "1231231hello12312312"
+ * "hello".center(4) #=> "hello"
+ * "hello".center(20) #=> " hello "
*/
static VALUE
diff --git a/struct.c b/struct.c
index 15546b981d..a82799de4d 100644
--- a/struct.c
+++ b/struct.c
@@ -11,7 +11,6 @@
**********************************************************************/
#include "ruby.h"
-#include "env.h"
VALUE rb_cStruct;
@@ -119,7 +118,7 @@ static VALUE
rb_struct_ref(obj)
VALUE obj;
{
- return rb_struct_getmember(obj, ruby_frame->orig_func);
+ return rb_struct_getmember(obj, rb_frame_last_func());
}
static VALUE rb_struct_ref0(obj) VALUE obj; {return RSTRUCT(obj)->ptr[0];}
@@ -160,20 +159,18 @@ rb_struct_set(obj, val)
VALUE obj, val;
{
VALUE members, slot;
- ID id;
long i;
members = rb_struct_members(obj);
rb_struct_modify(obj);
- id = ruby_frame->orig_func;
for (i=0; i<RARRAY(members)->len; i++) {
slot = RARRAY(members)->ptr[i];
- if (rb_id_attrset(SYM2ID(slot)) == id) {
+ if (rb_id_attrset(SYM2ID(slot)) == rb_frame_last_func()) {
return RSTRUCT(obj)->ptr[i] = val;
}
}
- rb_name_error(ruby_frame->last_func, "`%s' is not a struct member",
- rb_id2name(id));
+ rb_name_error(rb_frame_last_func(), "`%s' is not a struct member",
+ rb_id2name(rb_frame_last_func()));
return Qnil; /* not reached */
}
@@ -201,7 +198,7 @@ make_struct(name, members, klass)
rb_warn("redefining constant Struct::%s", cname);
rb_mod_remove_const(klass, ID2SYM(id));
}
- nstr = rb_define_class_under(klass, rb_id2name(id), klass);
+ nstr = rb_define_class_under(klass, cname, klass);
}
rb_iv_set(nstr, "__size__", LONG2NUM(RARRAY(members)->len));
rb_iv_set(nstr, "__members__", members);
@@ -212,15 +209,13 @@ make_struct(name, members, klass)
rb_define_singleton_method(nstr, "members", rb_struct_s_members_m, 0);
for (i=0; i< RARRAY(members)->len; i++) {
ID id = SYM2ID(RARRAY(members)->ptr[i]);
- if (rb_is_local_id(id) || rb_is_const_id(id)) {
- if (i<10) {
- rb_define_method_id(nstr, id, ref_func[i], 0);
- }
- else {
- rb_define_method_id(nstr, id, rb_struct_ref, 0);
- }
- rb_define_method_id(nstr, rb_id_attrset(id), rb_struct_set, 1);
+ if (i<10) {
+ rb_define_method_id(nstr, id, ref_func[i], 0);
+ }
+ else {
+ rb_define_method_id(nstr, id, rb_struct_ref, 0);
}
+ rb_define_method_id(nstr, rb_id_attrset(id), rb_struct_set, 1);
}
return nstr;
@@ -479,24 +474,18 @@ inspect_struct(s)
rb_str_cat2(str, cname);
rb_str_cat2(str, " ");
for (i=0; i<RSTRUCT(s)->len; i++) {
- VALUE slot;
- ID id;
+ VALUE str2, slot;
char *p;
if (i > 0) {
rb_str_cat2(str, ", ");
}
slot = RARRAY(members)->ptr[i];
- id = SYM2ID(slot);
- if (rb_is_local_id(id) || rb_is_const_id(id)) {
- p = rb_id2name(id);
- rb_str_cat2(str, p);
- }
- else {
- rb_str_append(str, rb_inspect(slot));
- }
+ p = rb_id2name(SYM2ID(slot));
+ rb_str_cat2(str, p);
rb_str_cat2(str, "=");
- rb_str_append(str, rb_inspect(RSTRUCT(s)->ptr[i]));
+ str2 = rb_inspect(RSTRUCT(s)->ptr[i]);
+ rb_str_append(str, str2);
}
rb_str_cat2(str, ">");
OBJ_INFECT(str, s);
@@ -518,10 +507,9 @@ rb_struct_inspect(s)
{
if (rb_inspecting_p(s)) {
char *cname = rb_class2name(rb_obj_class(s));
- size_t len = strlen(cname) + 14;
- VALUE str = rb_str_new(0, len);
+ VALUE str = rb_str_new(0, strlen(cname) + 15);
- snprintf(RSTRING(str)->ptr, len+1, "#<struct %s:...>", cname);
+ sprintf(RSTRING(str)->ptr, "#<struct %s:...>", cname);
RSTRING(str)->len = strlen(RSTRING(str)->ptr);
return str;
}
diff --git a/test/dbm/test_dbm.rb b/test/dbm/test_dbm.rb
index d4d488f577..2de73d1d5e 100644
--- a/test/dbm/test_dbm.rb
+++ b/test/dbm/test_dbm.rb
@@ -1,4 +1,5 @@
-require 'test/unit'
+require 'test/unit/testsuite'
+require 'test/unit/testcase'
begin
require 'dbm'
@@ -10,498 +11,6 @@ if defined? DBM
require 'fileutils'
class TestDBM < Test::Unit::TestCase
- def TestDBM.uname_s
- require 'rbconfig'
- case Config::CONFIG['host_os']
- when 'cygwin'
- require 'Win32API'
- uname = Win32API.new('cygwin1', 'uname', 'P', 'I')
- utsname = ' ' * 100
- raise 'cannot get system name' if uname.call(utsname) == -1
-
- utsname.unpack('A20' * 5)[0]
- else
- Config::CONFIG['host_os']
- end
- end
- SYSTEM = uname_s
-
- def setup
- @path = "tmptest_dbm_"
- assert_instance_of(DBM, @dbm = DBM.new(@path))
-
- # prepare to make readonly DBM file
- DBM.open("tmptest_dbm_rdonly") {|dbm|
- dbm['foo'] = 'FOO'
- }
-
- File.chmod(0400, *Dir.glob("tmptest_dbm_rdonly.*"))
-
- assert_instance_of(DBM, @dbm_rdonly = DBM.new("tmptest_dbm_rdonly", nil))
- end
- def teardown
- assert_nil(@dbm.close)
- assert_nil(@dbm_rdonly.close)
- ObjectSpace.each_object(DBM) do |obj|
- obj.close unless obj.closed?
- end
- File.delete *Dir.glob("tmptest_dbm*").to_a
- p Dir.glob("tmptest_dbm*") if $DEBUG
- end
-
- def check_size(expect, dbm=@dbm)
- assert_equal(expect, dbm.size)
- n = 0
- dbm.each { n+=1 }
- assert_equal(expect, n)
- if expect == 0
- assert_equal(true, dbm.empty?)
- else
- assert_equal(false, dbm.empty?)
- end
- end
-
- def have_fork?
- begin
- fork{}
- true
- rescue NotImplementedError
- false
- end
- end
-
- def test_s_new_has_no_block
- # DBM.new ignore the block
- foo = true
- assert_instance_of(DBM, dbm = DBM.new("tmptest_dbm") { foo = false })
- assert_equal(foo, true)
- assert_nil(dbm.close)
- end
- def test_s_open_no_create
- assert_nil(dbm = DBM.open("tmptest_dbm", nil))
- ensure
- dbm.close if dbm
- end
- def test_s_open_with_block
- assert_equal(DBM.open("tmptest_dbm") { :foo }, :foo)
- end
-
- def test_close
- assert_instance_of(DBM, dbm = DBM.open("tmptest_dbm"))
- assert_nil(dbm.close)
-
- # closed DBM file
- assert_raise(DBMError) { dbm.close }
- end
-
- def test_aref
- assert_equal('bar', @dbm['foo'] = 'bar')
- assert_equal('bar', @dbm['foo'])
-
- assert_nil(@dbm['bar'])
- end
-
- def test_fetch
- assert_equal('bar', @dbm['foo']='bar')
- assert_equal('bar', @dbm.fetch('foo'))
-
- # key not found
- assert_raise(IndexError) {
- @dbm.fetch('bar')
- }
-
- # test for `ifnone' arg
- assert_equal('baz', @dbm.fetch('bar', 'baz'))
-
- # test for `ifnone' block
- assert_equal('foobar', @dbm.fetch('bar') {|key| 'foo' + key })
- end
-
- def test_aset
- num = 0
- 2.times {|i|
- assert_equal('foo', @dbm['foo'] = 'foo')
- assert_equal('foo', @dbm['foo'])
- assert_equal('bar', @dbm['foo'] = 'bar')
- assert_equal('bar', @dbm['foo'])
-
- num += 1 if i == 0
- assert_equal(num, @dbm.size)
-
- # assign nil
- assert_equal('', @dbm['bar'] = '')
- assert_equal('', @dbm['bar'])
-
- num += 1 if i == 0
- assert_equal(num, @dbm.size)
-
- # empty string
- assert_equal('', @dbm[''] = '')
- assert_equal('', @dbm[''])
-
- num += 1 if i == 0
- assert_equal(num, @dbm.size)
-
- # Fixnum
- assert_equal('200', @dbm['100'] = '200')
- assert_equal('200', @dbm['100'])
-
- num += 1 if i == 0
- assert_equal(num, @dbm.size)
-
- # Big key and value
- assert_equal('y' * 100, @dbm['x' * 100] = 'y' * 100)
- assert_equal('y' * 100, @dbm['x' * 100])
-
- num += 1 if i == 0
- assert_equal(num, @dbm.size)
- }
- end
-
- def test_index
- assert_equal('bar', @dbm['foo'] = 'bar')
- assert_equal('foo', @dbm.index('bar'))
- assert_nil(@dbm['bar'])
- end
-
- def test_indexes
- keys = %w(foo bar baz)
- values = %w(FOO BAR BAZ)
- @dbm[keys[0]], @dbm[keys[1]], @dbm[keys[2]] = values
- assert_equal(values.reverse, @dbm.indexes(*keys.reverse))
- end
-
- def test_values_at
- keys = %w(foo bar baz)
- values = %w(FOO BAR BAZ)
- @dbm[keys[0]], @dbm[keys[1]], @dbm[keys[2]] = values
- assert_equal(values.reverse, @dbm.values_at(*keys.reverse))
- end
-
- def test_select_with_block
- keys = %w(foo bar baz)
- values = %w(FOO BAR BAZ)
- @dbm[keys[0]], @dbm[keys[1]], @dbm[keys[2]] = values
- ret = @dbm.select {|k,v|
- assert_equal(k.upcase, v)
- k != "bar"
- }
- assert_equal([['baz', 'BAZ'], ['foo', 'FOO']],
- ret.sort)
- end
-
- def test_length
- num = 10
- assert_equal(0, @dbm.size)
- num.times {|i|
- i = i.to_s
- @dbm[i] = i
- }
- assert_equal(num, @dbm.size)
-
- @dbm.shift
-
- assert_equal(num - 1, @dbm.size)
- end
-
- def test_empty?
- assert_equal(true, @dbm.empty?)
- @dbm['foo'] = 'FOO'
- assert_equal(false, @dbm.empty?)
- end
-
- def test_each_pair
- n = 0
- @dbm.each_pair { n += 1 }
- assert_equal(0, n)
-
- keys = %w(foo bar baz)
- values = %w(FOO BAR BAZ)
-
- @dbm[keys[0]], @dbm[keys[1]], @dbm[keys[2]] = values
-
- n = 0
- ret = @dbm.each_pair {|key, val|
- assert_not_nil(i = keys.index(key))
- assert_equal(val, values[i])
-
- n += 1
- }
- assert_equal(keys.size, n)
- assert_equal(@dbm, ret)
- end
-
- def test_each_value
- n = 0
- @dbm.each_value { n += 1 }
- assert_equal(0, n)
-
- keys = %w(foo bar baz)
- values = %w(FOO BAR BAZ)
-
- @dbm[keys[0]], @dbm[keys[1]], @dbm[keys[2]] = values
-
- n = 0
- ret = @dbm.each_value {|val|
- assert_not_nil(key = @dbm.index(val))
- assert_not_nil(i = keys.index(key))
- assert_equal(val, values[i])
-
- n += 1
- }
- assert_equal(keys.size, n)
- assert_equal(@dbm, ret)
- end
-
- def test_each_key
- n = 0
- @dbm.each_key { n += 1 }
- assert_equal(0, n)
-
- keys = %w(foo bar baz)
- values = %w(FOO BAR BAZ)
-
- @dbm[keys[0]], @dbm[keys[1]], @dbm[keys[2]] = values
-
- n = 0
- ret = @dbm.each_key {|key|
- assert_not_nil(i = keys.index(key))
- assert_equal(@dbm[key], values[i])
-
- n += 1
- }
- assert_equal(keys.size, n)
- assert_equal(@dbm, ret)
- end
-
- def test_keys
- assert_equal([], @dbm.keys)
-
- keys = %w(foo bar baz)
- values = %w(FOO BAR BAZ)
-
- @dbm[keys[0]], @dbm[keys[1]], @dbm[keys[2]] = values
-
- assert_equal(keys.sort, @dbm.keys.sort)
- assert_equal(values.sort, @dbm.values.sort)
- end
-
- def test_values
- test_keys
- end
-
- def test_shift
- assert_nil(@dbm.shift)
- assert_equal(0, @dbm.size)
-
- keys = %w(foo bar baz)
- values = %w(FOO BAR BAZ)
-
- @dbm[keys[0]], @dbm[keys[1]], @dbm[keys[2]] = values
-
- ret_keys = []
- ret_values = []
- while ret = @dbm.shift
- ret_keys.push ret[0]
- ret_values.push ret[1]
-
- assert_equal(keys.size - ret_keys.size, @dbm.size)
- end
-
- assert_equal(keys.sort, ret_keys.sort)
- assert_equal(values.sort, ret_values.sort)
- end
-
- def test_delete
- keys = %w(foo bar baz)
- values = %w(FOO BAR BAZ)
- key = keys[1]
-
- assert_nil(@dbm.delete(key))
- assert_equal(0, @dbm.size)
-
- @dbm[keys[0]], @dbm[keys[1]], @dbm[keys[2]] = values
-
- assert_equal('BAR', @dbm.delete(key))
- assert_nil(@dbm[key])
- assert_equal(2, @dbm.size)
-
- assert_nil(@dbm.delete(key))
-
- if /^CYGWIN_9/ !~ SYSTEM
- assert_raise(DBMError) {
- @dbm_rdonly.delete("foo")
- }
-
- assert_nil(@dbm_rdonly.delete("bar"))
- end
- end
- def test_delete_with_block
- key = 'no called block'
- @dbm[key] = 'foo'
- assert_equal('foo', @dbm.delete(key) {|k| k.replace 'called block'})
- assert_equal('no called block', key)
- assert_equal(0, @dbm.size)
-
- key = 'no called block'
- assert_equal(:blockval,
- @dbm.delete(key) {|k| k.replace 'called block'; :blockval})
- assert_equal('called block', key)
- assert_equal(0, @dbm.size)
- end
-
- def test_delete_if
- v = "0"
- 100.times {@dbm[v] = v; v = v.next}
-
- ret = @dbm.delete_if {|key, val| key.to_i < 50}
- assert_equal(@dbm, ret)
- check_size(50, @dbm)
-
- ret = @dbm.delete_if {|key, val| key.to_i >= 50}
- assert_equal(@dbm, ret)
- check_size(0, @dbm)
-
- # break
- v = "0"
- 100.times {@dbm[v] = v; v = v.next}
- check_size(100, @dbm)
- n = 0;
- @dbm.delete_if {|key, val|
- break if n > 50
- n+=1
- true
- }
- assert_equal(51, n)
- check_size(49, @dbm)
-
- @dbm.clear
-
- # raise
- v = "0"
- 100.times {@dbm[v] = v; v = v.next}
- check_size(100, @dbm)
- n = 0;
- begin
- @dbm.delete_if {|key, val|
- raise "runtime error" if n > 50
- n+=1
- true
- }
- rescue
- end
- assert_equal(51, n)
- check_size(49, @dbm)
- end
-
- def test_reject
- v = "0"
- 100.times {@dbm[v] = v; v = v.next}
-
- hash = @dbm.reject {|key, val| key.to_i < 50}
- assert_instance_of(Hash, hash)
- assert_equal(100, @dbm.size)
-
- assert_equal(50, hash.size)
- hash.each_pair {|key,val|
- assert_equal(false, key.to_i < 50)
- assert_equal(key, val)
- }
-
- hash = @dbm.reject {|key, val| key.to_i < 100}
- assert_instance_of(Hash, hash)
- assert_equal(true, hash.empty?)
- end
-
- def test_clear
- v = "1"
- 100.times {v = v.next; @dbm[v] = v}
-
- assert_equal(@dbm, @dbm.clear)
-
- # validate DBM#size
- i = 0
- @dbm.each { i += 1 }
- assert_equal(@dbm.size, i)
- assert_equal(0, i)
- end
-
- def test_invert
- v = "0"
- 100.times {@dbm[v] = v; v = v.next}
-
- hash = @dbm.invert
- assert_instance_of(Hash, hash)
- assert_equal(100, hash.size)
- hash.each_pair {|key, val|
- assert_equal(key.to_i, val.to_i)
- }
- end
-
- def test_update
- hash = {}
- v = "0"
- 100.times {v = v.next; hash[v] = v}
-
- @dbm["101"] = "101"
- @dbm.update hash
- assert_equal(101, @dbm.size)
- @dbm.each_pair {|key, val|
- assert_equal(key.to_i, val.to_i)
- }
- end
-
- def test_replace
- hash = {}
- v = "0"
- 100.times {v = v.next; hash[v] = v}
-
- @dbm["101"] = "101"
- @dbm.replace hash
- assert_equal(100, @dbm.size)
- @dbm.each_pair {|key, val|
- assert_equal(key.to_i, val.to_i)
- }
- end
-
- def test_haskey?
- assert_equal('bar', @dbm['foo']='bar')
- assert_equal(true, @dbm.has_key?('foo'))
- assert_equal(false, @dbm.has_key?('bar'))
- end
-
- def test_has_value?
- assert_equal('bar', @dbm['foo']='bar')
- assert_equal(true, @dbm.has_value?('bar'))
- assert_equal(false, @dbm.has_value?('foo'))
- end
-
- def test_to_a
- v = "0"
- 100.times {v = v.next; @dbm[v] = v}
-
- ary = @dbm.to_a
- assert_instance_of(Array, ary)
- assert_equal(100, ary.size)
- ary.each {|key,val|
- assert_equal(key.to_i, val.to_i)
- }
- end
-
- def test_to_hash
- v = "0"
- 100.times {v = v.next; @dbm[v] = v}
-
- hash = @dbm.to_hash
- assert_instance_of(Hash, hash)
- assert_equal(100, hash.size)
- hash.each {|key,val|
- assert_equal(key.to_i, val.to_i)
- }
- end
- end
-
- class TestDBM2 < Test::Unit::TestCase
TMPROOT = "#{Dir.tmpdir}/ruby-dbm.#{$$}"
def setup
diff --git a/test/digest/test_digest.rb b/test/digest/test_digest.rb
index 62f0aa2cd7..7cdc639340 100644
--- a/test/digest/test_digest.rb
+++ b/test/digest/test_digest.rb
@@ -5,28 +5,55 @@
require 'test/unit'
-require 'digest'
-%w[digest/md5 digest/rmd160 digest/sha1 digest/sha2].each do |lib|
- begin
- require lib
- rescue LoadError
- end
-end
+require 'digest/md5'
+require 'digest/rmd160'
+require 'digest/sha1'
+require 'digest/sha2'
include Digest
-module TestDigest
- Data1 = "abc"
- Data2 = "abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq"
+class TestDigest < Test::Unit::TestCase
+ ALGOS = [
+ MD5,
+ SHA1,
+ SHA256,
+ SHA384,
+ SHA512,
+ RMD160
+ ]
+
+ DATA = {
+ "abc" => {
+ MD5 => "900150983cd24fb0d6963f7d28e17f72",
+ SHA1 => "a9993e364706816aba3e25717850c26c9cd0d89d",
+ SHA256 => "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad",
+ SHA384 => "cb00753f45a35e8bb5a03d699ac65007272c32ab0eded1631a8b605a43ff5bed8086072ba1e7cc2358baeca134c825a7",
+ SHA512 => "ddaf35a193617abacc417349ae20413112e6fa4e89a97ea20a9eeee64b55d39a2192992a274fc1a836ba3c23a3feebbd454d4423643ce80e2a9ac94fa54ca49f",
+ RMD160 => "8eb208f7e05d987a9b044a8e98c6b087f15a0bfc"
+ },
+
+ "abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq" => {
+ MD5 => "8215ef0796a20bcaaae116d3876c664a",
+ SHA1 => "84983e441c3bd26ebaae4aa1f95129e5e54670f1",
+ SHA256 => "248d6a61d20638b8e5c026930c3e6039a33ce45964ff2167f6ecedd419db06c1",
+ SHA384 => "3391fdddfc8dc7393707a65b1b4709397cf8b1d162af05abfe8f450de5f36bc6b0455a8520bc4e6f5fe95b1fe3c8452b",
+ SHA512 => "204a8fc6dda82f0a0ced7beb8e08a41657c16ef468b228a8279be331a703c33596fd15c13b1b07f9aa1d3bea57789ca031ad85c7a71dd70354ec631238ca3445",
+ RMD160 => "12a053384a9c0c88e405a06c27dcf49ada62eb2b"
+ }
+ }
def test_s_hexdigest
- self.class::DATA.each do |str, digest|
- assert_equal(digest, self.class::ALGO.hexdigest(str))
+ ALGOS.each do |algo|
+ DATA.each do |str, table|
+ assert_equal(table[algo], algo.hexdigest(str))
+ end
end
end
def test_s_digest
- self.class::DATA.each do |str, digest|
- assert_equal([digest].pack("H*"), self.class::ALGO.digest(str))
+ ALGOS.each do |algo|
+ DATA.each do |str, table|
+ assert_equal([table[algo]].pack("H*"), algo.digest(str))
+ end
end
end
@@ -35,86 +62,36 @@ module TestDigest
str = "ABC"
- md = self.class::ALGO.new
- md.update str
- assert_equal(self.class::ALGO.hexdigest(str), md.hexdigest)
- assert_equal(self.class::ALGO.digest(str), md.digest)
+ ALGOS.each do |algo|
+ md = algo.new
+ md.update str
+ assert_equal(algo.hexdigest(str), md.hexdigest)
+ assert_equal(algo.digest(str), md.digest)
+ end
end
def test_eq
# This test is also for clone()
- md1 = self.class::ALGO.new("ABC")
+ ALGOS.each do |algo|
+ md1 = algo.new("ABC")
- assert_equal(md1, md1.clone, self.class::ALGO)
+ assert_equal(md1, md1.clone, algo)
- md2 = self.class::ALGO.new
- md2 << "A"
+ md2 = algo.new
+ md2 << "A"
- assert(md1 != md2, self.class::ALGO)
+ assert(md1 != md2, algo)
- md2 << "BC"
+ md2 << "BC"
- assert_equal(md1, md2, self.class::ALGO)
+ assert_equal(md1, md2, algo)
+ end
end
- def test_instance_eval
+ def test_instance_eval # [ruby-dev:24202]
assert_nothing_raised {
- self.class::ALGO.new.instance_eval { update "a" }
+ Digest::SHA1.new.instance_eval { update "a" }
}
end
-
- class TestMD5 < Test::Unit::TestCase
- include TestDigest
- ALGO = MD5
- DATA = {
- Data1 => "900150983cd24fb0d6963f7d28e17f72",
- Data2 => "8215ef0796a20bcaaae116d3876c664a",
- }
- end if defined?(MD5)
-
- class TestSHA1 < Test::Unit::TestCase
- include TestDigest
- ALGO = SHA1
- DATA = {
- Data1 => "a9993e364706816aba3e25717850c26c9cd0d89d",
- Data2 => "84983e441c3bd26ebaae4aa1f95129e5e54670f1",
- }
- end if defined?(SHA1)
-
- class TestSHA256 < Test::Unit::TestCase
- include TestDigest
- ALGO = SHA256
- DATA = {
- Data1 => "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad",
- Data2 => "248d6a61d20638b8e5c026930c3e6039a33ce45964ff2167f6ecedd419db06c1",
- }
- end if defined?(SHA256)
-
- class TestSHA384 < Test::Unit::TestCase
- include TestDigest
- ALGO = SHA384
- DATA = {
- Data1 => "cb00753f45a35e8bb5a03d699ac65007272c32ab0eded1631a8b605a43ff5bed8086072ba1e7cc2358baeca134c825a7",
- Data2 => "3391fdddfc8dc7393707a65b1b4709397cf8b1d162af05abfe8f450de5f36bc6b0455a8520bc4e6f5fe95b1fe3c8452b",
- }
- end if defined?(SHA384)
-
- class TestSHA512 < Test::Unit::TestCase
- include TestDigest
- ALGO = SHA512
- DATA = {
- Data1 => "ddaf35a193617abacc417349ae20413112e6fa4e89a97ea20a9eeee64b55d39a2192992a274fc1a836ba3c23a3feebbd454d4423643ce80e2a9ac94fa54ca49f",
- Data2 => "204a8fc6dda82f0a0ced7beb8e08a41657c16ef468b228a8279be331a703c33596fd15c13b1b07f9aa1d3bea57789ca031ad85c7a71dd70354ec631238ca3445",
- }
- end if defined?(SHA512)
-
- class TestRMD160 < Test::Unit::TestCase
- include TestDigest
- ALGO = RMD160
- DATA = {
- Data1 => "8eb208f7e05d987a9b044a8e98c6b087f15a0bfc",
- Data2 => "12a053384a9c0c88e405a06c27dcf49ada62eb2b",
- }
- end if defined?(RMD160)
end
diff --git a/test/drb/drbtest.rb b/test/drb/drbtest.rb
index 410a33c7e1..792cdcb7c7 100644
--- a/test/drb/drbtest.rb
+++ b/test/drb/drbtest.rb
@@ -2,39 +2,27 @@ require 'test/unit'
require 'drb/drb'
require 'drb/extservm'
require 'timeout'
-begin
- loadpath = $:.dup
- $:.replace($: | [File.expand_path("../ruby", File.dirname(__FILE__))])
- require 'envutil'
-ensure
- $:.replace(loadpath)
-end
+require 'rbconfig'
class DRbService
@@manager = DRb::ExtServManager.new
- @@ruby = EnvUtil.rubybin
+ @@ruby = File.join(
+ Config::CONFIG["bindir"],
+ Config::CONFIG["ruby_install_name"] + Config::CONFIG["EXEEXT"]
+ )
@@ruby += " -d" if $DEBUG
- def self.add_service_command(nm)
- dir = File.dirname(File.expand_path(__FILE__))
- DRb::ExtServManager.command[nm] = "#{@@ruby} #{dir}/#{nm}"
- end
+ @@dir = File.dirname(File.expand_path(__FILE__))
%w(ut_drb.rb ut_array.rb ut_port.rb ut_large.rb ut_safe1.rb ut_eval.rb).each do |nm|
- add_service_command(nm)
+ DRb::ExtServManager.command[nm] = "#{@@ruby} #{@@dir}/#{nm}"
end
@server = @@server = DRb::DRbServer.new(nil, @@manager, {})
- @@manager.uri = @@server.uri
def self.manager
@@manager
end
def self.server
@server || @@server
end
- def self.ext_service(name)
- timeout(10, RuntimeError) do
- manager.service(name)
- end
- end
end
class Onecky
@@ -70,12 +58,12 @@ end
module DRbCore
def setup
- @ext = DRbService.ext_service('ut_drb.rb')
+ @ext = DRbService.manager.service('ut_drb.rb')
@there = @ext.front
end
def teardown
- @ext.stop_service if @ext
+ @ext.stop_service
end
def test_00_DRbObject
@@ -98,11 +86,6 @@ module DRbCore
assert_equal(6, @there.sample(onecky, 1, 2))
ary = @there.to_a
assert_kind_of(DRb::DRbObject, ary)
-
- assert(@there.respond_to?(:to_a, true))
- assert(@there.respond_to?(:eval, true))
- assert(! @there.respond_to?(:eval, false))
- assert(! @there.respond_to?(:eval))
end
def test_01_02_loop
@@ -176,42 +159,24 @@ module DRbCore
end
end
- def test_07_public_private_protected_missing
+ def test_07_public_private
assert_nothing_raised() {
begin
@there.method_missing(:eval)
- rescue NoMethodError
+ rescue NameError
assert_match(/^private method \`eval\'/, $!.message)
end
}
assert_nothing_raised() {
begin
- @there.call_private_method
- rescue NoMethodError
- assert_equal(NoMethodError, $!.class)
- assert_match(/^private method \`call_private_method\'/, $!.message)
- end
- }
- assert_nothing_raised() {
- begin
- @there.call_protected_method
- rescue NoMethodError
- assert_equal(NoMethodError, $!.class)
- assert_match(/^protected method \`call_protected_method\'/, $!.message)
- end
- }
- assert_nothing_raised() {
- begin
@there.method_missing(:undefined_method_test)
- rescue NoMethodError
- assert_equal(NoMethodError, $!.class)
+ rescue NameError
assert_match(/^undefined method \`undefined_method_test\'/, $!.message)
end
}
assert_raises(SecurityError) do
@there.method_missing(:__send__, :to_s)
end
- assert_equal(true, @there.missing)
end
def test_08_here
@@ -259,29 +224,16 @@ module DRbCore
assert_kind_of(DRbObject, v)
end
end
-
- def test_11_remote_no_method_error
- assert_raises(DRb::DRbRemoteError) do
- @there.remote_no_method_error
- end
- begin
- @there.remote_no_method_error
- rescue
- error = $!
- assert_match(/^undefined method .*\(NoMethodError\)/, error.message)
- assert_equal('NoMethodError', error.reason)
- end
- end
end
module DRbAry
def setup
- @ext = DRbService.ext_service('ut_array.rb')
+ @ext = DRbService.manager.service('ut_array.rb')
@there = @ext.front
end
def teardown
- @ext.stop_service if @ext
+ @ext.stop_service
end
def test_01
diff --git a/test/drb/ignore_test_drb.rb b/test/drb/ignore_test_drb.rb
deleted file mode 100644
index d0bb1f49b0..0000000000
--- a/test/drb/ignore_test_drb.rb
+++ /dev/null
@@ -1,24 +0,0 @@
-require 'drbtest'
-
-class TestDRbReusePort < Test::Unit::TestCase
- include DRbAry
-
- def setup
- @ext = DRbService.ext_service('ut_port.rb')
- @there = @ext.front
- end
-
- def teardown
- return unless @ext
- @ext.stop_service
- while true
- sleep 0.1
- begin
- @ext.alive?
- rescue DRb::DRbConnError
- break
- end
- end
- end
-end
-
diff --git a/test/drb/test_drb.rb b/test/drb/test_drb.rb
index 5719f60b80..5a4a98e1cc 100644
--- a/test/drb/test_drb.rb
+++ b/test/drb/test_drb.rb
@@ -6,12 +6,12 @@ end
class TestDRbYield < Test::Unit::TestCase
def setup
- @ext = DRbService.ext_service('ut_drb.rb')
+ @ext = DRbService.manager.service('ut_drb.rb')
@there = @ext.front
end
def teardown
- @ext.stop_service if @ext
+ @ext.stop_service
end
def test_01_one
@@ -102,15 +102,6 @@ class TestDRbYield < Test::Unit::TestCase
@there.xarray_each {|x| assert_kind_of(XArray, x)}
@there.xarray_each {|*x| assert_kind_of(XArray, x[0])}
end
-
- def test_06_taint
- x = proc {}
- assert(! x.tainted?)
- @there.echo_yield(x) {|o|
- assert_equal(x, o)
- assert(! x.tainted?)
- }
- end
end
class TestRubyYield < TestDRbYield
@@ -181,7 +172,7 @@ end
class TestDRbMServer < Test::Unit::TestCase
def setup
- @ext = DRbService.ext_service('ut_drb.rb')
+ @ext = DRbService.manager.service('ut_drb.rb')
@there = @ext.front
@server = (1..3).collect do |n|
DRb::DRbServer.new(nil, Onecky.new(n.to_s))
@@ -192,7 +183,7 @@ class TestDRbMServer < Test::Unit::TestCase
@server.each do |s|
s.stop_service
end
- @ext.stop_service if @ext
+ @ext.stop_service
end
def test_01
@@ -200,9 +191,18 @@ class TestDRbMServer < Test::Unit::TestCase
end
end
+class TestDRbReusePort < TestDRbAry
+ def setup
+ sleep 1
+ @ext = DRbService.manager.service('ut_port.rb')
+ @there = @ext.front
+ end
+end
+
class TestDRbSafe1 < TestDRbAry
def setup
- @ext = DRbService.ext_service('ut_safe1.rb')
+ sleep 1
+ @ext = DRbService.manager.service('ut_safe1.rb')
@there = @ext.front
end
end
@@ -210,15 +210,16 @@ end
class TestDRbEval < Test::Unit::TestCase
def setup
super
- @ext = DRbService.ext_service('ut_eval.rb')
+ sleep 1
+ @ext = DRbService.manager.service('ut_eval.rb')
@there = @ext.front
end
def teardown
- @ext.stop_service if @ext
+ @ext.stop_service
end
- def test_01_safe1_safe4_eval
+ def test_01_safe1_eval
assert_raises(SecurityError) do
@there.method_missing(:instance_eval, 'ENV.inspect')
end
@@ -236,34 +237,18 @@ class TestDRbEval < Test::Unit::TestCase
assert_raises(SecurityError) do
remote_class.module_eval('ENV.inspect')
end
-
- four = @there.four
- assert_equal(1, four.method_missing(:send, :eval, '1'))
-
- remote_class = four.remote_class
-
- assert_equal(1, remote_class.class_eval('1'))
-
- assert_equal(1, remote_class.module_eval('1'))
-
- assert_raises(SecurityError) do
- remote_class.class_eval('ENV = {}')
- end
-
- assert_raises(SecurityError) do
- remote_class.module_eval('ENV = {}')
- end
end
end
class TestDRbLarge < Test::Unit::TestCase
def setup
- @ext = DRbService.ext_service('ut_large.rb')
+ sleep 1
+ @ext = DRbService.manager.service('ut_large.rb')
@there = @ext.front
end
def teardown
- @ext.stop_service if @ext
+ @ext.stop_service
end
def test_01_large_ary
diff --git a/test/drb/test_drbssl.rb b/test/drb/test_drbssl.rb
index cfb3bc36a4..b5dd68f6a7 100644
--- a/test/drb/test_drbssl.rb
+++ b/test/drb/test_drbssl.rb
@@ -10,7 +10,7 @@ if Object.const_defined?("OpenSSL")
class DRbSSLService < DRbService
%w(ut_drb_drbssl.rb ut_array_drbssl.rb).each do |nm|
- add_service_command(nm)
+ DRb::ExtServManager.command[nm] = "#{@@ruby} #{@@dir}/#{nm}"
end
config = Hash.new
@@ -30,13 +30,13 @@ class DRbSSLService < DRbService
end
uri = ARGV.shift if $0 == __FILE__
- @server = DRb::DRbServer.new(uri || 'drbssl://:0', self.manager, config)
+ @server = DRb::DRbServer.new(uri || 'drbssl://:0', @@manager, config)
end
class TestDRbSSLCore < Test::Unit::TestCase
include DRbCore
def setup
- @ext = DRbSSLService.ext_service('ut_drb_drbssl.rb')
+ @ext = DRbSSLService.manager.service('ut_drb_drbssl.rb')
@there = @ext.front
end
@@ -48,12 +48,24 @@ class TestDRbSSLCore < Test::Unit::TestCase
def test_05_eq
end
+
+ def test_06_timeout
+ ten = Onecky.new(3)
+ assert_raises(TimeoutError) do
+ @there.do_timeout(ten)
+ end
+ assert_raises(TimeoutError) do
+ @there.do_timeout(ten)
+ end
+ sleep 3
+ end
+
end
class TestDRbSSLAry < Test::Unit::TestCase
include DRbAry
def setup
- @ext = DRbSSLService.ext_service('ut_array_drbssl.rb')
+ @ext = DRbSSLService.manager.service('ut_array_drbssl.rb')
@there = @ext.front
end
end
diff --git a/test/drb/test_drbunix.rb b/test/drb/test_drbunix.rb
index e1a17edd3d..e35a7bd580 100644
--- a/test/drb/test_drbunix.rb
+++ b/test/drb/test_drbunix.rb
@@ -10,17 +10,17 @@ if Object.const_defined?("UNIXServer")
class DRbUNIXService < DRbService
%w(ut_drb_drbunix.rb ut_array_drbunix.rb).each do |nm|
- add_service_command(nm)
+ DRb::ExtServManager.command[nm] = "#{@@ruby} #{@@dir}/#{nm}"
end
uri = ARGV.shift if $0 == __FILE__
- @server = DRb::DRbServer.new(uri || 'drbunix:', self.manager, {})
+ @server = DRb::DRbServer.new(uri || 'drbunix:', @@manager, {})
end
class TestDRbUNIXCore < Test::Unit::TestCase
include DRbCore
def setup
- @ext = DRbUNIXService.ext_service('ut_drb_drbunix.rb')
+ @ext = DRbUNIXService.manager.service('ut_drb_drbunix.rb')
@there = @ext.front
end
@@ -32,12 +32,23 @@ class TestDRbUNIXCore < Test::Unit::TestCase
def test_05_eq
end
+
+ def test_06_timeout
+ ten = Onecky.new(3)
+ assert_raises(TimeoutError) do
+ @there.do_timeout(ten)
+ end
+ assert_raises(TimeoutError) do
+ @there.do_timeout(ten)
+ end
+ sleep 3
+ end
end
class TestDRbUNIXAry < Test::Unit::TestCase
include DRbAry
def setup
- @ext = DRbUNIXService.ext_service('ut_array_drbunix.rb')
+ @ext = DRbUNIXService.manager.service('ut_array_drbunix.rb')
@there = @ext.front
end
end
diff --git a/test/drb/ut_drb.rb b/test/drb/ut_drb.rb
index f5720cfca2..e7eedf8864 100644
--- a/test/drb/ut_drb.rb
+++ b/test/drb/ut_drb.rb
@@ -49,7 +49,7 @@ class DRbEx
end
def do_timeout(n)
- timeout(0.1) do
+ timeout(1) do
n.sleep(2)
end
end
@@ -66,10 +66,6 @@ class DRbEx
raise UError
end
- def remote_no_method_error
- invoke_no_method(self)
- end
-
def test_yield
yield
yield([])
@@ -126,23 +122,10 @@ class DRbEx
[self]
end
- def method_missing(msg, *a, &b)
- if msg == :missing
- return true
- else
- super(msg, *a, &b)
- end
- end
-
private
def call_private_method
true
end
-
- protected
- def call_protected_method
- true
- end
end
if __FILE__ == $0
diff --git a/test/drb/ut_eval.rb b/test/drb/ut_eval.rb
index 4df963e7cd..6a81e17d05 100644
--- a/test/drb/ut_eval.rb
+++ b/test/drb/ut_eval.rb
@@ -2,14 +2,6 @@ require 'drb/drb'
require 'drb/extserv'
class EvalAttack
- def initialize
- @four = DRb::DRbServer.new('druby://localhost:0', self, {:safe_level => 4})
- end
-
- def four
- DRbObject.new_with_uri(@four.uri)
- end
-
def remote_class
DRbObject.new(self.class)
end
@@ -25,7 +17,7 @@ if __FILE__ == $0
$SAFE = 1
- DRb.start_service('druby://localhost:0', EvalAttack.new, {:safe_level => 2})
+ DRb.start_service('druby://localhost:0', EvalAttack.new)
es = DRb::ExtServ.new(ARGV.shift, ARGV.shift)
DRb.thread.join
end
diff --git a/test/drb/ut_safe1.rb b/test/drb/ut_safe1.rb
index 4df8e1e5a1..761bdff4b1 100644
--- a/test/drb/ut_safe1.rb
+++ b/test/drb/ut_safe1.rb
@@ -8,8 +8,9 @@ if __FILE__ == $0
it
end
- DRb.start_service('druby://localhost:0', [1, 2, 'III', 4, "five", 6],
- {:safe_level => 1})
+ $SAFE = 1
+
+ DRb.start_service('druby://localhost:0', [1, 2, 'III', 4, "five", 6])
es = DRb::ExtServ.new(ARGV.shift, ARGV.shift)
DRb.thread.join
end
diff --git a/test/fileutils/fileasserts.rb b/test/fileutils/fileasserts.rb
index c2e9244a96..2a96351bc2 100644
--- a/test/fileutils/fileasserts.rb
+++ b/test/fileutils/fileasserts.rb
@@ -1,10 +1,12 @@
-# $Id$
+#
+# test/fileutils/fileasserts.rb
+#
module Test
module Unit
module Assertions # redefine
- def assert_same_file(from, to)
+ def assert_same_file( from, to )
_wrap_assertion {
assert_block("file #{from} != #{to}") {
File.read(from) == File.read(to)
@@ -12,17 +14,7 @@ module Test
}
end
- def assert_same_entry(from, to)
- a = File.stat(from)
- b = File.stat(to)
- assert_equal a.mode, b.mode, "mode #{a.mode} != #{b.mode}"
- #assert_equal a.atime, b.atime
- assert_equal a.mtime, b.mtime, "mtime #{a.mtime} != #{b.mtime}"
- assert_equal a.uid, b.uid, "uid #{a.uid} != #{b.uid}"
- assert_equal a.gid, b.gid, "gid #{a.gid} != #{b.gid}"
- end
-
- def assert_file_exist(path)
+ def assert_file_exist( path )
_wrap_assertion {
assert_block("file not exist: #{path}") {
File.exist?(path)
@@ -30,7 +22,7 @@ module Test
}
end
- def assert_file_not_exist(path)
+ def assert_file_not_exist( path )
_wrap_assertion {
assert_block("file not exist: #{path}") {
not File.exist?(path)
@@ -38,7 +30,7 @@ module Test
}
end
- def assert_directory(path)
+ def assert_directory( path )
_wrap_assertion {
assert_block("is not directory: #{path}") {
File.directory?(path)
@@ -46,22 +38,14 @@ module Test
}
end
- def assert_symlink(path)
+ def assert_symlink( path )
_wrap_assertion {
- assert_block("is not a symlink: #{path}") {
+ assert_block("is no symlink: #{path}") {
File.symlink?(path)
}
}
end
- def assert_not_symlink(path)
- _wrap_assertion {
- assert_block("is a symlink: #{path}") {
- not File.symlink?(path)
- }
- }
- end
-
end
end
end
diff --git a/test/fileutils/test_dryrun.rb b/test/fileutils/test_dryrun.rb
deleted file mode 100644
index 2fdd65d2f6..0000000000
--- a/test/fileutils/test_dryrun.rb
+++ /dev/null
@@ -1,25 +0,0 @@
-# $Id$
-
-require 'test/unit'
-require 'fileutils'
-
-class TestFileUtilsDryRun < Test::Unit::TestCase
-
- include FileUtils::DryRun
-
- def test_visibility
- FileUtils::METHODS.each do |m|
- assert_equal true, FileUtils::DryRun.respond_to?(m, true),
- "FileUtils::DryRun.#{m} not defined"
- assert_equal true, FileUtils::DryRun.respond_to?(m, false),
- "FileUtils::DryRun.#{m} not public"
- end
- FileUtils::METHODS.each do |m|
- assert_equal true, respond_to?(m, true)
- "FileUtils::DryRun\##{m} is not defined"
- assert_equal true, FileUtils::DryRun.private_method_defined?(m),
- "FileUtils::DryRun\##{m} is not private"
- end
- end
-
-end
diff --git a/test/fileutils/test_fileutils.rb b/test/fileutils/test_fileutils.rb
index cab51c9e8c..8c06f875b2 100644
--- a/test/fileutils/test_fileutils.rb
+++ b/test/fileutils/test_fileutils.rb
@@ -1,4 +1,8 @@
-# $Id$
+#
+# test/fileutils/test_fileutils.rb
+#
+
+$:.unshift File.dirname(__FILE__)
require 'fileutils'
require 'fileasserts'
@@ -16,57 +20,37 @@ Dir.mkdir tmproot unless File.directory?(tmproot)
Dir.chdir tmproot
def have_drive_letter?
- /djgpp|mswin(?!ce)|mingw|bcc|emx/ =~ RUBY_PLATFORM
+ /djgpp|mswin(?!ce)|mingw|bcc|emx/ === RUBY_PLATFORM
end
def have_file_perm?
/djgpp|mswin|mingw|bcc|wince|emx/ !~ RUBY_PLATFORM
end
-$fileutils_rb_have_symlink = nil
-
-def have_symlink?
- if $fileutils_rb_have_symlink == nil
- $fileutils_rb_have_symlink = check_have_symlink?
- end
- $fileutils_rb_have_symlink
-end
-
-def check_have_symlink?
- File.symlink nil, nil
+begin
+ File.symlink 'not_exist', 'symlink_test'
+ HAVE_SYMLINK = true
rescue NotImplementedError
- return false
-rescue
- return true
-end
-
-$fileutils_rb_have_hardlink = nil
-
-def have_hardlink?
- if $fileutils_rb_have_hardlink == nil
- $fileutils_rb_have_hardlink = check_have_hardlink?
- end
- $fileutils_rb_have_hardlink
+ HAVE_SYMLINK = false
+ensure
+ File.unlink 'symlink_test' if File.symlink?('symlink_test')
end
-
-def check_have_hardlink?
- File.link nil, nil
-rescue NotImplementedError
- return false
-rescue
- return true
+def have_symlink?
+ HAVE_SYMLINK
end
begin
- Dir.mkdir("\n")
- Dir.rmdir("\n")
- def lf_in_path_allowed?
- true
- end
-rescue
- def lf_in_path_allowed?
- false
- end
+ File.open('linktmp', 'w') {|f| f.puts 'dummy' }
+ File.link 'linktmp', 'linktest'
+ HAVE_HARDLINK = true
+rescue NotImplementedError, SystemCallError
+ HAVE_HARDLINK = false
+ensure
+ File.unlink 'linktest' if File.exist?('linktest')
+ File.unlink 'linktmp' if File.exist?('linktmp')
+end
+def have_hardlink?
+ HAVE_HARDLINK
end
Dir.chdir prevdir
@@ -76,11 +60,7 @@ class TestFileUtils
include FileUtils
- def check_singleton(name)
- assert_equal true, ::FileUtils.public_methods.include?(name.to_s)
- end
-
- def my_rm_rf(path)
+ def my_rm_rf( path )
if File.exist?('/bin/rm')
system %Q[/bin/rm -rf "#{path}"]
else
@@ -88,19 +68,15 @@ class TestFileUtils
end
end
- def mymkdir(path)
- Dir.mkdir path
- File.chown nil, Process.gid, path if have_file_perm?
- end
-
def setup
@prevdir = Dir.pwd
- tmproot = TMPROOT
- mymkdir tmproot unless File.directory?(tmproot)
+ tmproot = "#{Dir.tmpdir}/fileutils.rb.#{$$}"
+ Dir.mkdir tmproot unless File.directory?(tmproot)
Dir.chdir tmproot
- my_rm_rf 'data'; mymkdir 'data'
- my_rm_rf 'tmp'; mymkdir 'tmp'
+ my_rm_rf 'data'; Dir.mkdir 'data'
+ my_rm_rf 'tmp'; Dir.mkdir 'tmp'
prepare_data_file
+ prepare_time_data
end
def teardown
@@ -110,12 +86,13 @@ class TestFileUtils
end
- TARGETS = %w( data/a data/all data/random data/zero )
+ TARGETS = %w( data/same data/all data/random data/zero )
def prepare_data_file
- File.open('data/a', 'w') {|f|
+ same_chars = 'a' * 50
+ File.open('data/same', 'w') {|f|
32.times do
- f.puts 'a' * 50
+ f.puts same_chars
end
}
@@ -157,19 +134,7 @@ class TestFileUtils
File.utime t-4, t-4, 'data/newer'
end
- def each_srcdest
- TARGETS.each do |path|
- yield path, "tmp/#{File.basename(path)}"
- end
- end
-
- #
- # Test Cases
- #
-
def test_pwd
- check_singleton :pwd
-
assert_equal Dir.pwd, pwd()
cwd = Dir.pwd
@@ -187,8 +152,6 @@ end
end
def test_cmp
- check_singleton :cmp
-
TARGETS.each do |fname|
assert cmp(fname, fname), 'not same?'
end
@@ -206,21 +169,24 @@ end
end
def test_cp
- check_singleton :cp
-
- each_srcdest do |srcpath, destpath|
- cp srcpath, destpath
- assert_same_file srcpath, destpath
+ TARGETS.each do |fname|
+ cp fname, 'tmp/cp'
+ assert_same_file fname, 'tmp/cp'
- cp srcpath, File.dirname(destpath)
- assert_same_file srcpath, destpath
+ cp fname, 'tmp'
+ assert_same_file fname, 'tmp/' + File.basename(fname)
- cp srcpath, File.dirname(destpath) + '/'
- assert_same_file srcpath, destpath
+ cp fname, 'tmp/'
+ assert_same_file fname, 'tmp/' + File.basename(fname)
- cp srcpath, destpath, :preserve => true
- assert_same_file srcpath, destpath
- assert_same_entry srcpath, destpath
+ cp fname, 'tmp/preserve', :preserve => true
+ assert_same_file fname, 'tmp/preserve'
+ a = File.stat(fname)
+ b = File.stat('tmp/preserve')
+ assert_equal a.mode, b.mode
+ assert_equal a.mtime, b.mtime
+ assert_equal a.uid, b.uid
+ assert_equal a.gid, b.gid
end
# src==dest (1) same path
@@ -255,55 +221,11 @@ end
end
def test_cp_r
- check_singleton :cp_r
-
cp_r 'data', 'tmp'
TARGETS.each do |fname|
assert_same_file fname, "tmp/#{fname}"
end
- cp_r 'data', 'tmp2', :preserve => true
- TARGETS.each do |fname|
- assert_same_entry fname, "tmp2/#{File.basename(fname)}"
- assert_same_file fname, "tmp2/#{File.basename(fname)}"
- end
-
- # a/* -> b/*
- mkdir 'tmp/cpr_src'
- mkdir 'tmp/cpr_dest'
- File.open('tmp/cpr_src/a', 'w') {|f| f.puts 'a' }
- File.open('tmp/cpr_src/b', 'w') {|f| f.puts 'b' }
- File.open('tmp/cpr_src/c', 'w') {|f| f.puts 'c' }
- mkdir 'tmp/cpr_src/d'
- cp_r 'tmp/cpr_src/.', 'tmp/cpr_dest'
- assert_same_file 'tmp/cpr_src/a', 'tmp/cpr_dest/a'
- assert_same_file 'tmp/cpr_src/b', 'tmp/cpr_dest/b'
- assert_same_file 'tmp/cpr_src/c', 'tmp/cpr_dest/c'
- assert_directory 'tmp/cpr_dest/d'
- my_rm_rf 'tmp/cpr_src'
- my_rm_rf 'tmp/cpr_dest'
-
-if have_symlink?
- # symlink in a directory
- mkdir 'tmp/cpr_src'
- ln_s 'SLdest', 'tmp/cpr_src/symlink'
- cp_r 'tmp/cpr_src', 'tmp/cpr_dest'
- assert_symlink 'tmp/cpr_dest/symlink'
- assert_equal 'SLdest', File.readlink('tmp/cpr_dest/symlink')
-
- # root is a symlink
- ln_s 'cpr_src', 'tmp/cpr_src2'
- cp_r 'tmp/cpr_src2', 'tmp/cpr_dest2'
- assert_directory 'tmp/cpr_dest2'
- #assert_not_symlink 'tmp/cpr_dest2'
- # * 2005-05-26: feature change on trunk
- #assert_symlink 'tmp/cpr_dest2'
- # * 2005-09-19: revert for 1.8 (:dereference_root => true by default)
- assert_not_symlink 'tmp/cpr_dest2'
- assert_symlink 'tmp/cpr_dest2/symlink'
- assert_equal 'SLdest', File.readlink('tmp/cpr_dest2/symlink')
-end
-
# pathname
touch 'tmp/cprtmp'
assert_nothing_raised {
@@ -314,8 +236,6 @@ end
end
def test_mv
- check_singleton :mv
-
mkdir 'tmp/dest'
TARGETS.each do |fname|
cp fname, 'tmp/mvsrc'
@@ -329,17 +249,6 @@ end
assert_same_file fname, 'tmp/mvdest'
end
- # [ruby-talk:124368]
- mkdir 'tmp/tmpdir'
- mkdir_p 'tmp/dest2/tmpdir'
- assert_raises(Errno::EEXIST) {
- mv 'tmp/tmpdir', 'tmp/dest2'
- }
- mkdir 'tmp/dest2/tmpdir/junk'
- assert_raises(Errno::EEXIST) {
- mv 'tmp/tmpdir', 'tmp/dest2'
- }
-
# src==dest (1) same path
touch 'tmp/cptmp'
assert_raises(ArgumentError) {
@@ -373,8 +282,6 @@ end
end
def test_rm
- check_singleton :rm
-
TARGETS.each do |fname|
cp fname, 'tmp/rmsrc'
rm 'tmp/rmsrc'
@@ -395,8 +302,6 @@ end
end
def test_rm_f
- check_singleton :rm_f
-
TARGETS.each do |fname|
cp fname, 'tmp/rmsrc'
rm_f 'tmp/rmsrc'
@@ -418,14 +323,6 @@ end
# rm_f 'tmpdatadir'
Dir.rmdir 'tmpdatadir'
- Dir.mkdir 'tmp/tmpdir'
- File.open('tmp/tmpdir/a', 'w') {|f| f.puts 'dummy' }
- File.open('tmp/tmpdir/c', 'w') {|f| f.puts 'dummy' }
- rm_f ['tmp/tmpdir/a', 'tmp/tmpdir/b', 'tmp/tmpdir/c']
- assert_file_not_exist 'tmp/tmpdir/a'
- assert_file_not_exist 'tmp/tmpdir/c'
- Dir.rmdir 'tmp/tmpdir'
-
# pathname
touch 'tmp/rmtmp1'
touch 'tmp/rmtmp2'
@@ -442,8 +339,6 @@ end
end
def test_rm_r
- check_singleton :rm_r
-
my_rm_rf 'tmpdatadir'
Dir.mkdir 'tmpdatadir'
@@ -472,23 +367,6 @@ end
assert_file_not_exist 'tmp/tmpdir'
assert_file_exist 'tmp'
- Dir.mkdir 'tmp/tmpdir'
- File.open('tmp/tmpdir/a', 'w') {|f| f.puts 'dummy' }
- File.open('tmp/tmpdir/c', 'w') {|f| f.puts 'dummy' }
- rm_r ['tmp/tmpdir/a', 'tmp/tmpdir/b', 'tmp/tmpdir/c'], :force => true
- assert_file_not_exist 'tmp/tmpdir/a'
- assert_file_not_exist 'tmp/tmpdir/c'
- Dir.rmdir 'tmp/tmpdir'
-
-if have_symlink?
- # [ruby-talk:94635] a symlink to the directory
- Dir.mkdir 'tmp/tmpdir'
- File.symlink '..', 'tmp/tmpdir/symlink_to_dir'
- rm_r 'tmp/tmpdir'
- assert_file_not_exist 'tmp/tmpdir'
- assert_file_exist 'tmp'
-end
-
# pathname
Dir.mkdir 'tmp/tmpdir1'; touch 'tmp/tmpdir1/tmp'
Dir.mkdir 'tmp/tmpdir2'; touch 'tmp/tmpdir2/tmp'
@@ -502,64 +380,6 @@ end
assert_file_not_exist 'tmp/tmpdir3'
end
- def test_remove_entry_secure
- check_singleton :remove_entry_secure
-
- my_rm_rf 'tmpdatadir'
-
- Dir.mkdir 'tmpdatadir'
- remove_entry_secure 'tmpdatadir'
- assert_file_not_exist 'tmpdatadir'
-
- Dir.mkdir 'tmpdatadir'
- remove_entry_secure 'tmpdatadir/'
- assert_file_not_exist 'tmpdatadir'
-
- Dir.mkdir 'tmp/tmpdir'
- remove_entry_secure 'tmp/tmpdir/'
- assert_file_not_exist 'tmp/tmpdir'
- assert_file_exist 'tmp'
-
- Dir.mkdir 'tmp/tmpdir'
- remove_entry_secure 'tmp/tmpdir'
- assert_file_not_exist 'tmp/tmpdir'
- assert_file_exist 'tmp'
-
- Dir.mkdir 'tmp/tmpdir'
- File.open('tmp/tmpdir/a', 'w') {|f| f.puts 'dummy' }
- File.open('tmp/tmpdir/b', 'w') {|f| f.puts 'dummy' }
- File.open('tmp/tmpdir/c', 'w') {|f| f.puts 'dummy' }
- remove_entry_secure 'tmp/tmpdir'
- assert_file_not_exist 'tmp/tmpdir'
- assert_file_exist 'tmp'
-
- Dir.mkdir 'tmp/tmpdir'
- File.open('tmp/tmpdir/a', 'w') {|f| f.puts 'dummy' }
- File.open('tmp/tmpdir/c', 'w') {|f| f.puts 'dummy' }
- remove_entry_secure 'tmp/tmpdir/a', true
- remove_entry_secure 'tmp/tmpdir/b', true
- remove_entry_secure 'tmp/tmpdir/c', true
- assert_file_not_exist 'tmp/tmpdir/a'
- assert_file_not_exist 'tmp/tmpdir/c'
- Dir.rmdir 'tmp/tmpdir'
-
-if have_symlink?
- # [ruby-talk:94635] a symlink to the directory
- Dir.mkdir 'tmp/tmpdir'
- File.symlink '..', 'tmp/tmpdir/symlink_to_dir'
- remove_entry_secure 'tmp/tmpdir'
- assert_file_not_exist 'tmp/tmpdir'
- assert_file_exist 'tmp'
-end
-
- # pathname
- Dir.mkdir 'tmp/tmpdir1'; touch 'tmp/tmpdir1/tmp'
- assert_nothing_raised {
- remove_entry_secure Pathname.new('tmp/tmpdir1')
- }
- assert_file_not_exist 'tmp/tmpdir1'
- end
-
def test_with_big_file
prepare_big_file
@@ -626,8 +446,6 @@ end
if have_symlink?
def test_ln_s
- check_singleton :ln_s
-
TARGETS.each do |fname|
ln_s fname, 'tmp/lnsdest'
assert FileTest.symlink?('tmp/lnsdest'), 'not symlink'
@@ -651,8 +469,6 @@ end
if have_symlink?
def test_ln_sf
- check_singleton :ln_sf
-
TARGETS.each do |fname|
ln_sf fname, 'tmp/lnsdest'
assert FileTest.symlink?('tmp/lnsdest'), 'not symlink'
@@ -675,8 +491,6 @@ if have_symlink?
end
def test_mkdir
- check_singleton :mkdir
-
my_rm_rf 'tmpdatadir'
mkdir 'tmpdatadir'
assert_directory 'tmpdatadir'
@@ -695,19 +509,6 @@ end
assert_equal 0700, (File.stat('tmp/tmp').mode & 0777) if have_file_perm?
Dir.rmdir 'tmp/tmp'
-if have_file_perm?
- mkdir 'tmp/tmp', :mode => 07777
- assert_directory 'tmp/tmp'
- assert_equal 07777, (File.stat('tmp/tmp').mode & 07777)
- Dir.rmdir 'tmp/tmp'
-end
-
-if lf_in_path_allowed?
- mkdir "tmp-first-line\ntmp-second-line"
- assert_directory "tmp-first-line\ntmp-second-line"
- Dir.rmdir "tmp-first-line\ntmp-second-line"
-end
-
# pathname
assert_nothing_raised {
mkdir Pathname.new('tmp/tmpdirtmp')
@@ -716,8 +517,6 @@ end
end
def test_mkdir_p
- check_singleton :mkdir_p
-
dirs = %w(
tmpdir/dir/
tmpdir/dir/./
@@ -731,14 +530,14 @@ end
tmpdir/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a
tmpdir/a/a
)
- my_rm_rf 'tmpdir'
+ rm_rf 'tmpdir'
dirs.each do |d|
mkdir_p d
assert_directory d
assert_file_not_exist "#{d}/a"
assert_file_not_exist "#{d}/b"
assert_file_not_exist "#{d}/c"
- my_rm_rf 'tmpdir'
+ rm_rf 'tmpdir'
end
dirs.each do |d|
mkdir_p d
@@ -758,31 +557,32 @@ end
assert_equal 0700, (File.stat('tmp/tmp/tmp').mode & 0777) if have_file_perm?
rm_rf 'tmp/tmp'
- mkdir_p 'tmp/tmp', :mode => 0
- assert_directory 'tmp/tmp'
- assert_equal 0, (File.stat('tmp/tmp').mode & 0777) if have_file_perm?
- # DO NOT USE rm_rf here.
- # (rm(1) try to chdir to parent directory, it fails to remove directory.)
- Dir.rmdir 'tmp/tmp'
- Dir.rmdir 'tmp'
+ # pathname
+ assert_nothing_raised {
+ mkdir_p Pathname.new('tmp/tmp/tmp')
+ }
+ end
-if have_file_perm?
- mkdir_p 'tmp/tmp/tmp', :mode => 07777
- assert_directory 'tmp/tmp/tmp'
- assert_equal 07777, (File.stat('tmp/tmp/tmp').mode & 07777)
- Dir.rmdir 'tmp/tmp/tmp'
- Dir.rmdir 'tmp/tmp'
-end
+ def test_uptodate?
+ Dir.chdir('data') {
+ assert( uptodate?('newest', %w(old newer notexist)) )
+ assert( ! uptodate?('newer', %w(old newest notexist)) )
+ assert( ! uptodate?('notexist', %w(old newest newer)) )
+ }
# pathname
+ touch 'tmp/a'
+ touch 'tmp/b'
+ touch 'tmp/c'
assert_nothing_raised {
- mkdir_p Pathname.new('tmp/tmp/tmp')
+ uptodate? Pathname.new('tmp/a'), ['tmp/b', 'tmp/c']
+ uptodate? 'tmp/a', [Pathname.new('tmp/b'), 'tmp/c']
+ uptodate? 'tmp/a', ['tmp/b', Pathname.new('tmp/c')]
+ uptodate? Pathname.new('tmp/a'), [Pathname.new('tmp/b'), Pathname.new('tmp/c')]
}
end
def test_install
- check_singleton :install
-
File.open('tmp/aaa', 'w') {|f| f.puts 'aaa' }
File.open('tmp/bbb', 'w') {|f| f.puts 'bbb' }
install 'tmp/aaa', 'tmp/bbb', :mode => 0600
@@ -833,253 +633,10 @@ end
touch 'tmp/b'
mkdir 'tmp/dest'
install [Pathname.new('tmp/a'), Pathname.new('tmp/b')], 'tmp/dest'
- my_rm_rf 'tmp/dest'
+ rm_rf 'tmp/dest'
mkdir 'tmp/dest'
install [Pathname.new('tmp/a'), Pathname.new('tmp/b')], Pathname.new('tmp/dest')
}
end
-if have_file_perm?
- def test_chmod
- check_singleton :chmod
-
- touch 'tmp/a'
- chmod 0700, 'tmp/a'
- assert_equal 0700, File.stat('tmp/a').mode & 0777
- chmod 0500, 'tmp/a'
- assert_equal 0500, File.stat('tmp/a').mode & 0777
- end
-
- def test_chmod_R
- check_singleton :chmod_R
-
- mkdir_p 'tmp/dir/dir'
- touch %w( tmp/dir/file tmp/dir/dir/file )
- chmod_R 0700, 'tmp/dir'
- assert_equal 0700, File.stat('tmp/dir').mode & 0777
- assert_equal 0700, File.stat('tmp/dir/file').mode & 0777
- assert_equal 0700, File.stat('tmp/dir/dir').mode & 0777
- assert_equal 0700, File.stat('tmp/dir/dir/file').mode & 0777
- chmod_R 0500, 'tmp/dir'
- assert_equal 0500, File.stat('tmp/dir').mode & 0777
- assert_equal 0500, File.stat('tmp/dir/file').mode & 0777
- assert_equal 0500, File.stat('tmp/dir/dir').mode & 0777
- assert_equal 0500, File.stat('tmp/dir/dir/file').mode & 0777
- chmod_R 0700, 'tmp/dir' # to remove
- end
-
- # FIXME: How can I test this method?
- def test_chown
- check_singleton :chown
- end
-
- # FIXME: How can I test this method?
- def test_chown_R
- check_singleton :chown_R
- end
-end
-
- def test_copy_entry
- check_singleton :copy_entry
-
- each_srcdest do |srcpath, destpath|
- copy_entry srcpath, destpath
- assert_same_file srcpath, destpath
- assert_equal File.stat(srcpath).ftype, File.stat(destpath).ftype
- end
-if have_symlink?
- # root is a symlink
- File.symlink 'somewhere', 'tmp/symsrc'
- copy_entry 'tmp/symsrc', 'tmp/symdest'
- assert_symlink 'tmp/symdest'
- assert_equal 'somewhere', File.readlink('tmp/symdest')
-
- # content is a symlink
- mkdir 'tmp/dir'
- File.symlink 'somewhere', 'tmp/dir/sym'
- copy_entry 'tmp/dir', 'tmp/dirdest'
- assert_directory 'tmp/dirdest'
- assert_not_symlink 'tmp/dirdest'
- assert_symlink 'tmp/dirdest/sym'
- assert_equal 'somewhere', File.readlink('tmp/dirdest/sym')
-end
- end
-
- def test_copy_file
- check_singleton :copy_file
-
- each_srcdest do |srcpath, destpath|
- copy_file srcpath, destpath
- assert_same_file srcpath, destpath
- end
- end
-
- def test_copy_stream
- check_singleton :copy_stream
- # IO
- each_srcdest do |srcpath, destpath|
- File.open(srcpath) {|src|
- File.open(destpath, 'w') {|dest|
- copy_stream src, dest
- }
- }
- assert_same_file srcpath, destpath
- end
-
- # duck typing test [ruby-dev:25369]
- my_rm_rf 'tmp'
- Dir.mkdir 'tmp'
- each_srcdest do |srcpath, destpath|
- File.open(srcpath) {|src|
- File.open(destpath, 'w') {|dest|
- copy_stream Stream.new(src), Stream.new(dest)
- }
- }
- assert_same_file srcpath, destpath
- end
- end
-
- def test_remove_file
- check_singleton :remove_file
- File.open('data/tmp', 'w') {|f| f.puts 'dummy' }
- remove_file 'data/tmp'
- assert_file_not_exist 'data/tmp'
-if have_file_perm?
- File.open('data/tmp', 'w') {|f| f.puts 'dummy' }
- File.chmod 0, 'data/tmp'
- remove_file 'data/tmp'
- assert_file_not_exist 'data/tmp'
-end
- end
-
- def test_remove_dir
- check_singleton :remove_dir
- Dir.mkdir 'data/tmpdir'
- File.open('data/tmpdir/a', 'w') {|f| f.puts 'dummy' }
- remove_dir 'data/tmpdir'
- assert_file_not_exist 'data/tmpdir'
-if have_file_perm?
- Dir.mkdir 'data/tmpdir'
- File.chmod 0555, 'data/tmpdir'
- remove_dir 'data/tmpdir'
- assert_file_not_exist 'data/tmpdir'
-end
- end
-
- def test_compare_file
- check_singleton :compare_file
- # FIXME
- end
-
- def test_compare_stream
- check_singleton :compare_stream
- # FIXME
- end
-
- class Stream
- def initialize(f)
- @f = f
- end
-
- def read(n)
- @f.read(n)
- end
-
- def write(str)
- @f.write str
- end
- end
-
- def test_uptodate?
- check_singleton :uptodate?
- prepare_time_data
- Dir.chdir('data') {
- assert( uptodate?('newest', %w(old newer notexist)) )
- assert( ! uptodate?('newer', %w(old newest notexist)) )
- assert( ! uptodate?('notexist', %w(old newest newer)) )
- }
-
- # pathname
- touch 'tmp/a'
- touch 'tmp/b'
- touch 'tmp/c'
- assert_nothing_raised {
- uptodate? Pathname.new('tmp/a'), ['tmp/b', 'tmp/c']
- uptodate? 'tmp/a', [Pathname.new('tmp/b'), 'tmp/c']
- uptodate? 'tmp/a', ['tmp/b', Pathname.new('tmp/c')]
- uptodate? Pathname.new('tmp/a'), [Pathname.new('tmp/b'), Pathname.new('tmp/c')]
- }
- end
-
- def test_cd
- check_singleton :cd
- end
-
- def test_chdir
- check_singleton :chdir
- end
-
- def test_getwd
- check_singleton :getwd
- end
-
- def test_identical?
- check_singleton :identical?
- end
-
- def test_link
- check_singleton :link
- end
-
- def test_makedirs
- check_singleton :makedirs
- end
-
- def test_mkpath
- check_singleton :mkpath
- end
-
- def test_move
- check_singleton :move
- end
-
- def test_rm_rf
- check_singleton :rm_rf
- end
-
- def test_rmdir
- check_singleton :rmdir
- end
-
- def test_rmtree
- check_singleton :rmtree
- end
-
- def test_safe_unlink
- check_singleton :safe_unlink
- end
-
- def test_symlink
- check_singleton :symlink
- end
-
- def test_touch
- check_singleton :touch
- end
-
- def test_collect_methods
- end
-
- def test_commands
- end
-
- def test_have_option?
- end
-
- def test_options
- end
-
- def test_options_of
- end
-
end
diff --git a/test/fileutils/test_nowrite.rb b/test/fileutils/test_nowrite.rb
index 369f8ca608..18c00b8e08 100644
--- a/test/fileutils/test_nowrite.rb
+++ b/test/fileutils/test_nowrite.rb
@@ -1,30 +1,20 @@
-# $Id$
+#
+# test/fileutils/test_nowrite.rb
+#
+
+$:.unshift File.dirname(__FILE__)
require 'fileutils'
require 'fileasserts'
require 'tmpdir'
require 'test/unit'
-class TestFileUtilsNoWrite < Test::Unit::TestCase
- include FileUtils::NoWrite
+class TestNoWrite < Test::Unit::TestCase
- def test_visibility
- FileUtils::METHODS.each do |m|
- assert_equal true, FileUtils::NoWrite.respond_to?(m, true),
- "FileUtils::NoWrite.#{m} is not defined"
- assert_equal true, FileUtils::NoWrite.respond_to?(m, false),
- "FileUtils::NoWrite.#{m} is not public"
- end
- FileUtils::METHODS.each do |m|
- assert_equal true, respond_to?(m, true),
- "FileUtils::NoWrite\##{m} is not defined"
- assert_equal true, FileUtils::NoWrite.private_method_defined?(m),
- "FileUtils::NoWrite\##{m} is not private"
- end
- end
+ include FileUtils::NoWrite
- def my_rm_rf(path)
+ def my_rm_rf( path )
if File.exist?('/bin/rm')
system %Q[/bin/rm -rf "#{path}"]
else
@@ -62,7 +52,7 @@ class TestFileUtilsNoWrite < Test::Unit::TestCase
check 'tmp/mv'
end
- def check(dest)
+ def check( dest )
assert_file_not_exist dest
assert_file_exist SRC
assert_same_file SRC, COPY
diff --git a/test/fileutils/test_verbose.rb b/test/fileutils/test_verbose.rb
deleted file mode 100644
index e60e85ea4e..0000000000
--- a/test/fileutils/test_verbose.rb
+++ /dev/null
@@ -1,25 +0,0 @@
-# $Id$
-
-require 'test/unit'
-require 'fileutils'
-
-class TestFileUtilsVerbose < Test::Unit::TestCase
-
- include FileUtils::Verbose
-
- def test_visibility
- FileUtils::METHODS.each do |m|
- assert_equal true, FileUtils::Verbose.respond_to?(m, true),
- "FileUtils::Verbose.#{m} is not defined"
- assert_equal true, FileUtils::Verbose.respond_to?(m, false),
- "FileUtils::Verbose.#{m} is not public"
- end
- FileUtils::METHODS.each do |m|
- assert_equal true, respond_to?(m, true),
- "FileUtils::Verbose.#{m} is not defined"
- assert_equal true, FileUtils::Verbose.private_method_defined?(m),
- "FileUtils::Verbose.#{m} is not private"
- end
- end
-
-end
diff --git a/test/gdbm/test_gdbm.rb b/test/gdbm/test_gdbm.rb
index f4a6bfb197..c90f4a6074 100644
--- a/test/gdbm/test_gdbm.rb
+++ b/test/gdbm/test_gdbm.rb
@@ -1,4 +1,5 @@
-require 'test/unit'
+require 'test/unit/testsuite'
+require 'test/unit/testcase'
begin
require 'gdbm'
@@ -10,646 +11,6 @@ if defined? GDBM
require 'fileutils'
class TestGDBM < Test::Unit::TestCase
- def TestGDBM.uname_s
- require 'rbconfig'
- case Config::CONFIG['host_os']
- when 'cygwin'
- require 'Win32API'
- uname = Win32API.new('cygwin1', 'uname', 'P', 'I')
- utsname = ' ' * 100
- raise 'cannot get system name' if uname.call(utsname) == -1
-
- utsname.unpack('A20' * 5)[0]
- else
- Config::CONFIG['host_os']
- end
- end
- SYSTEM = uname_s
-
- def setup
- @path = "tmptest_gdbm_"
- assert_instance_of(GDBM, @gdbm = GDBM.new(@path))
-
- # prepare to make readonly GDBM file
- GDBM.open("tmptest_gdbm_rdonly", 0400) {|gdbm|
- gdbm['foo'] = 'FOO'
- }
- assert_instance_of(GDBM, @gdbm_rdonly = GDBM.new("tmptest_gdbm_rdonly", nil))
- end
- def teardown
- assert_nil(@gdbm.close)
- assert_nil(@gdbm_rdonly.close)
- ObjectSpace.each_object(GDBM) do |obj|
- obj.close unless obj.closed?
- end
- File.delete *Dir.glob("*tmptest_gdbm*").to_a
- p Dir.glob("*tmptest_gdbm*") if $DEBUG
- end
-
- def check_size(expect, gdbm=@gdbm)
- assert_equal(expect, gdbm.size)
- n = 0
- gdbm.each { n+=1 }
- assert_equal(expect, n)
- if expect == 0
- assert_equal(true, gdbm.empty?)
- else
- assert_equal(false, gdbm.empty?)
- end
- end
-
- def have_fork?
- begin
- fork{}
- true
- rescue NotImplementedError
- false
- end
- end
-
- def test_s_new_has_no_block
- # GDBM.new ignore the block
- foo = true
- assert_instance_of(GDBM, gdbm = GDBM.new("tmptest_gdbm") { foo = false })
- assert_equal(foo, true)
- assert_nil(gdbm.close)
- end
- def test_s_open_create_new
- return if /^CYGWIN_9/ =~ SYSTEM
-
- save_mask = File.umask(0)
- begin
- assert_instance_of(GDBM, gdbm = GDBM.open("tmptest_gdbm"))
- gdbm.close
- assert_equal(File.stat("tmptest_gdbm").mode & 0777, 0666)
- assert_instance_of(GDBM, gdbm = GDBM.open("tmptest_gdbm2", 0644))
- gdbm.close
- assert_equal(File.stat("tmptest_gdbm2").mode & 0777, 0644)
- ensure
- File.umask save_mask
- end
- end
- def test_s_open_no_create
- # this test is failed on libgdbm 1.8.0
- assert_nil(gdbm = GDBM.open("tmptest_gdbm", nil))
- ensure
- gdbm.close if gdbm
- end
- def test_s_open_3rd_arg
- assert_instance_of(GDBM, gdbm = GDBM.open("tmptest_gdbm", 0644,
- GDBM::FAST))
- gdbm.close
-
- # gdbm 1.8.0 specific
- if defined? GDBM::SYNC
- assert_instance_of(GDBM, gdbm = GDBM.open("tmptest_gdbm", 0644,
- GDBM::SYNC))
- gdbm.close
- end
- # gdbm 1.8.0 specific
- if defined? GDBM::NOLOCK
- assert_instance_of(GDBM, gdbm = GDBM.open("tmptest_gdbm", 0644,
- GDBM::NOLOCK))
- gdbm.close
- end
- end
- def test_s_open_with_block
- assert_equal(GDBM.open("tmptest_gdbm") { :foo }, :foo)
- end
- def test_s_open_lock
- return unless have_fork? # snip this test
- fork() {
- assert_instance_of(GDBM, gdbm = GDBM.open("tmptest_gdbm", 0644))
- sleep 2
- }
- begin
- sleep 1
- assert_raise(Errno::EWOULDBLOCK) {
- begin
- assert_instance_of(GDBM, gdbm2 = GDBM.open("tmptest_gdbm", 0644))
- rescue Errno::EAGAIN, Errno::EACCES
- raise Errno::EWOULDBLOCK
- end
- }
- ensure
- Process.wait
- end
- end
-
-=begin
- # Is it guaranteed on many OS?
- def test_s_open_lock_one_process
- # locking on one process
- assert_instance_of(GDBM, gdbm = GDBM.open("tmptest_gdbm", 0644))
- assert_raise(Errno::EWOULDBLOCK) {
- begin
- GDBM.open("tmptest_gdbm", 0644)
- rescue Errno::EAGAIN
- raise Errno::EWOULDBLOCK
- end
- }
- end
-=end
-
- def test_s_open_nolock
- # gdbm 1.8.0 specific
- if not defined? GDBM::NOLOCK
- return
- end
- return unless have_fork? # snip this test
-
- fork() {
- assert_instance_of(GDBM, gdbm = GDBM.open("tmptest_gdbm", 0644,
- GDBM::NOLOCK))
- sleep 2
- }
- sleep 1
- begin
- gdbm2 = nil
- assert_nothing_raised(Errno::EWOULDBLOCK, Errno::EAGAIN, Errno::EACCES) {
- assert_instance_of(GDBM, gdbm2 = GDBM.open("tmptest_gdbm", 0644))
- }
- ensure
- Process.wait
- gdbm2.close if gdbm2
- end
-
- p Dir.glob("tmptest_gdbm*") if $DEBUG
-
- fork() {
- assert_instance_of(GDBM, gdbm = GDBM.open("tmptest_gdbm", 0644))
- sleep 2
- }
- begin
- sleep 1
- gdbm2 = nil
- assert_nothing_raised(Errno::EWOULDBLOCK, Errno::EAGAIN, Errno::EACCES) {
- # this test is failed on Cygwin98 (???)
- assert_instance_of(GDBM, gdbm2 = GDBM.open("tmptest_gdbm", 0644,
- GDBM::NOLOCK))
- }
- ensure
- Process.wait
- gdbm2.close if gdbm2
- end
- end
-
- def test_s_open_error
- assert_instance_of(GDBM, gdbm = GDBM.open("tmptest_gdbm", 0))
- assert_raise(Errno::EACCES) {
- GDBM.open("tmptest_gdbm", 0)
- }
- gdbm.close
- end
-
- def test_close
- assert_instance_of(GDBM, gdbm = GDBM.open("tmptest_gdbm"))
- assert_nil(gdbm.close)
-
- # closed GDBM file
- assert_raise(RuntimeError) { gdbm.close }
- end
-
- def test_aref
- assert_equal('bar', @gdbm['foo'] = 'bar')
- assert_equal('bar', @gdbm['foo'])
-
- assert_nil(@gdbm['bar'])
- end
-
- def test_fetch
- assert_equal('bar', @gdbm['foo']='bar')
- assert_equal('bar', @gdbm.fetch('foo'))
-
- # key not found
- assert_raise(IndexError) {
- @gdbm.fetch('bar')
- }
-
- # test for `ifnone' arg
- assert_equal('baz', @gdbm.fetch('bar', 'baz'))
-
- # test for `ifnone' block
- assert_equal('foobar', @gdbm.fetch('bar') {|key| 'foo' + key })
- end
-
- def test_aset
- num = 0
- 2.times {|i|
- assert_equal('foo', @gdbm['foo'] = 'foo')
- assert_equal('foo', @gdbm['foo'])
- assert_equal('bar', @gdbm['foo'] = 'bar')
- assert_equal('bar', @gdbm['foo'])
-
- num += 1 if i == 0
- assert_equal(num, @gdbm.size)
-
- # assign nil
- assert_equal('', @gdbm['bar'] = '')
- assert_equal('', @gdbm['bar'])
-
- num += 1 if i == 0
- assert_equal(num, @gdbm.size)
-
- # empty string
- assert_equal('', @gdbm[''] = '')
- assert_equal('', @gdbm[''])
-
- num += 1 if i == 0
- assert_equal(num, @gdbm.size)
-
- # Fixnum
- assert_equal('200', @gdbm['100'] = '200')
- assert_equal('200', @gdbm['100'])
-
- num += 1 if i == 0
- assert_equal(num, @gdbm.size)
-
- # Big key and value
- assert_equal('y' * 100, @gdbm['x' * 100] = 'y' * 100)
- assert_equal('y' * 100, @gdbm['x' * 100])
-
- num += 1 if i == 0
- assert_equal(num, @gdbm.size)
- }
- end
-
- def test_index
- assert_equal('bar', @gdbm['foo'] = 'bar')
- assert_equal('foo', @gdbm.index('bar'))
- assert_nil(@gdbm['bar'])
- end
-
- def test_values_at
- keys = %w(foo bar baz)
- values = %w(FOO BAR BAZ)
- @gdbm[keys[0]], @gdbm[keys[1]], @gdbm[keys[2]] = values
- assert_equal(values.reverse, @gdbm.values_at(*keys.reverse))
- end
-
- def test_select_with_block
- keys = %w(foo bar baz)
- values = %w(FOO BAR BAZ)
- @gdbm[keys[0]], @gdbm[keys[1]], @gdbm[keys[2]] = values
- ret = @gdbm.select {|k,v|
- assert_equal(k.upcase, v)
- k != "bar"
- }
- assert_equal([['baz', 'BAZ'], ['foo', 'FOO']],
- ret.sort)
- end
-
- def test_length
- num = 10
- assert_equal(0, @gdbm.size)
- num.times {|i|
- i = i.to_s
- @gdbm[i] = i
- }
- assert_equal(num, @gdbm.size)
-
- @gdbm.shift
-
- assert_equal(num - 1, @gdbm.size)
- end
-
- def test_empty?
- assert_equal(true, @gdbm.empty?)
- @gdbm['foo'] = 'FOO'
- assert_equal(false, @gdbm.empty?)
- end
-
- def test_each_pair
- n = 0
- @gdbm.each_pair { n += 1 }
- assert_equal(0, n)
-
- keys = %w(foo bar baz)
- values = %w(FOO BAR BAZ)
-
- @gdbm[keys[0]], @gdbm[keys[1]], @gdbm[keys[2]] = values
-
- n = 0
- ret = @gdbm.each_pair {|key, val|
- assert_not_nil(i = keys.index(key))
- assert_equal(val, values[i])
-
- n += 1
- }
- assert_equal(keys.size, n)
- assert_equal(@gdbm, ret)
- end
-
- def test_each_value
- n = 0
- @gdbm.each_value { n += 1 }
- assert_equal(0, n)
-
- keys = %w(foo bar baz)
- values = %w(FOO BAR BAZ)
-
- @gdbm[keys[0]], @gdbm[keys[1]], @gdbm[keys[2]] = values
-
- n = 0
- ret = @gdbm.each_value {|val|
- assert_not_nil(key = @gdbm.index(val))
- assert_not_nil(i = keys.index(key))
- assert_equal(val, values[i])
-
- n += 1
- }
- assert_equal(keys.size, n)
- assert_equal(@gdbm, ret)
- end
-
- def test_each_key
- n = 0
- @gdbm.each_key { n += 1 }
- assert_equal(0, n)
-
- keys = %w(foo bar baz)
- values = %w(FOO BAR BAZ)
-
- @gdbm[keys[0]], @gdbm[keys[1]], @gdbm[keys[2]] = values
-
- n = 0
- ret = @gdbm.each_key {|key|
- assert_not_nil(i = keys.index(key))
- assert_equal(@gdbm[key], values[i])
-
- n += 1
- }
- assert_equal(keys.size, n)
- assert_equal(@gdbm, ret)
- end
-
- def test_keys
- assert_equal([], @gdbm.keys)
-
- keys = %w(foo bar baz)
- values = %w(FOO BAR BAZ)
-
- @gdbm[keys[0]], @gdbm[keys[1]], @gdbm[keys[2]] = values
-
- assert_equal(keys.sort, @gdbm.keys.sort)
- assert_equal(values.sort, @gdbm.values.sort)
- end
-
- def test_values
- test_keys
- end
-
- def test_shift
- assert_nil(@gdbm.shift)
- assert_equal(0, @gdbm.size)
-
- keys = %w(foo bar baz)
- values = %w(FOO BAR BAZ)
-
- @gdbm[keys[0]], @gdbm[keys[1]], @gdbm[keys[2]] = values
-
- ret_keys = []
- ret_values = []
- while ret = @gdbm.shift
- ret_keys.push ret[0]
- ret_values.push ret[1]
-
- assert_equal(keys.size - ret_keys.size, @gdbm.size)
- end
-
- assert_equal(keys.sort, ret_keys.sort)
- assert_equal(values.sort, ret_values.sort)
- end
-
- def test_delete
- keys = %w(foo bar baz)
- values = %w(FOO BAR BAZ)
- key = keys[1]
-
- assert_nil(@gdbm.delete(key))
- assert_equal(0, @gdbm.size)
-
- @gdbm[keys[0]], @gdbm[keys[1]], @gdbm[keys[2]] = values
-
- assert_equal('BAR', @gdbm.delete(key))
- assert_nil(@gdbm[key])
- assert_equal(2, @gdbm.size)
-
- assert_nil(@gdbm.delete(key))
-
- if /^CYGWIN_9/ !~ SYSTEM
- assert_raise(GDBMError) {
- @gdbm_rdonly.delete("foo")
- }
-
- assert_nil(@gdbm_rdonly.delete("bar"))
- end
- end
- def test_delete_with_block
- key = 'no called block'
- @gdbm[key] = 'foo'
- assert_equal('foo', @gdbm.delete(key) {|k| k.replace 'called block'})
- assert_equal('no called block', key)
- assert_equal(0, @gdbm.size)
-
- key = 'no called block'
- assert_equal(:blockval,
- @gdbm.delete(key) {|k| k.replace 'called block'; :blockval})
- assert_equal('called block', key)
- assert_equal(0, @gdbm.size)
- end
-
- def test_delete_if
- v = "0"
- 100.times {@gdbm[v] = v; v = v.next}
-
- ret = @gdbm.delete_if {|key, val| key.to_i < 50}
- assert_equal(@gdbm, ret)
- check_size(50, @gdbm)
-
- ret = @gdbm.delete_if {|key, val| key.to_i >= 50}
- assert_equal(@gdbm, ret)
- check_size(0, @gdbm)
-
- # break
- v = "0"
- 100.times {@gdbm[v] = v; v = v.next}
- check_size(100, @gdbm)
- n = 0;
- @gdbm.delete_if {|key, val|
- break if n > 50
- n+=1
- true
- }
- assert_equal(51, n)
- check_size(49, @gdbm)
-
- @gdbm.clear
-
- # raise
- v = "0"
- 100.times {@gdbm[v] = v; v = v.next}
- check_size(100, @gdbm)
- n = 0;
- begin
- @gdbm.delete_if {|key, val|
- raise "runtime error" if n > 50
- n+=1
- true
- }
- rescue
- end
- assert_equal(51, n)
- check_size(49, @gdbm)
- end
-
- def test_reject
- v = "0"
- 100.times {@gdbm[v] = v; v = v.next}
-
- hash = @gdbm.reject {|key, val| key.to_i < 50}
- assert_instance_of(Hash, hash)
- assert_equal(100, @gdbm.size)
-
- assert_equal(50, hash.size)
- hash.each_pair {|key,val|
- assert_equal(false, key.to_i < 50)
- assert_equal(key, val)
- }
-
- hash = @gdbm.reject {|key, val| key.to_i < 100}
- assert_instance_of(Hash, hash)
- assert_equal(true, hash.empty?)
- end
-
- def test_clear
- v = "1"
- 100.times {v = v.next; @gdbm[v] = v}
-
- assert_equal(@gdbm, @gdbm.clear)
-
- # validate GDBM#size
- i = 0
- @gdbm.each { i += 1 }
- assert_equal(@gdbm.size, i)
- assert_equal(0, i)
- end
-
- def test_invert
- v = "0"
- 100.times {@gdbm[v] = v; v = v.next}
-
- hash = @gdbm.invert
- assert_instance_of(Hash, hash)
- assert_equal(100, hash.size)
- hash.each_pair {|key, val|
- assert_equal(key.to_i, val.to_i)
- }
- end
-
- def test_update
- hash = {}
- v = "0"
- 100.times {v = v.next; hash[v] = v}
-
- @gdbm["101"] = "101"
- @gdbm.update hash
- assert_equal(101, @gdbm.size)
- @gdbm.each_pair {|key, val|
- assert_equal(key.to_i, val.to_i)
- }
- end
-
- def test_replace
- hash = {}
- v = "0"
- 100.times {v = v.next; hash[v] = v}
-
- @gdbm["101"] = "101"
- @gdbm.replace hash
- assert_equal(100, @gdbm.size)
- @gdbm.each_pair {|key, val|
- assert_equal(key.to_i, val.to_i)
- }
- end
-
- def test_reorganize
- size1 = File.size(@path)
- i = "1"
- 1000.times {i = i.next; @gdbm[i] = i}
- @gdbm.clear
- @gdbm.sync
-
- size2 = File.size(@path)
- @gdbm.reorganize
- size3 = File.size(@path)
-
- # p [size1, size2, size3]
- assert_equal(true, size1 < size2)
- # this test is failed on Cygwin98. `GDBM version 1.8.0, as of May 19, 1999'
- assert_equal(true, size3 < size2)
- assert_equal(size1, size3)
- end
-
- def test_sync
- assert_instance_of(GDBM, gdbm = GDBM.open('tmptest_gdbm', 0666, GDBM::FAST))
- assert_equal(gdbm.sync, gdbm)
- gdbm.close
- assert_instance_of(GDBM, gdbm = GDBM.open('tmptest_gdbm', 0666))
- assert_equal(gdbm.sync, gdbm)
- gdbm.close
- end
-
- def test_cachesize=
- assert_equal(@gdbm.cachesize = 1024, 1024)
- end
-
- def test_fastmode=
- assert_equal(@gdbm.fastmode = true, true)
- end
-
- def test_syncmode=
- assert_equal(@gdbm.syncmode = true, true)
- end
-
- def test_haskey?
- assert_equal('bar', @gdbm['foo']='bar')
- assert_equal(true, @gdbm.has_key?('foo'))
- assert_equal(false, @gdbm.has_key?('bar'))
- end
-
- def test_has_value?
- assert_equal('bar', @gdbm['foo']='bar')
- assert_equal(true, @gdbm.has_value?('bar'))
- assert_equal(false, @gdbm.has_value?('foo'))
- end
-
- def test_to_a
- v = "0"
- 100.times {v = v.next; @gdbm[v] = v}
-
- ary = @gdbm.to_a
- assert_instance_of(Array, ary)
- assert_equal(100, ary.size)
- ary.each {|key,val|
- assert_equal(key.to_i, val.to_i)
- }
- end
-
- def test_to_hash
- v = "0"
- 100.times {v = v.next; @gdbm[v] = v}
-
- hash = @gdbm.to_hash
- assert_instance_of(Hash, hash)
- assert_equal(100, hash.size)
- hash.each {|key,val|
- assert_equal(key.to_i, val.to_i)
- }
- end
- end
-
- class TestGDBM2 < Test::Unit::TestCase
TMPROOT = "#{Dir.tmpdir}/ruby-gdbm.#{$$}"
def setup
diff --git a/test/io/nonblock/test_flush.rb b/test/io/nonblock/test_flush.rb
deleted file mode 100644
index 2afbba300e..0000000000
--- a/test/io/nonblock/test_flush.rb
+++ /dev/null
@@ -1,28 +0,0 @@
-require 'test/unit'
-begin
- require 'io/nonblock'
-rescue LoadError
-end
-
-class TestIONonblock < Test::Unit::TestCase
- def test_flush # [ruby-dev:24985]
- r,w = IO.pipe
- w.nonblock = true
- w.sync = false
- w << "b"
- w.flush
- w << "a" * 4096
- Thread.new {
- Thread.pass
- w.close
- }
- result = ""
- t = Thread.new {
- while (Thread.pass; s = r.read(4096))
- result << s
- end
- }
- assert_raise(IOError) {w.flush}
- assert_nothing_raised {t.join}
- end
-end if IO.method_defined?(:nonblock)
diff --git a/test/logger/test_logger.rb b/test/logger/test_logger.rb
index ab578a1b81..ed1270cf39 100644
--- a/test/logger/test_logger.rb
+++ b/test/logger/test_logger.rb
@@ -36,17 +36,13 @@ class TestLogger < Test::Unit::TestCase
end
def log(logger, msg_id, *arg, &block)
- Log.new(log_raw(logger, msg_id, *arg, &block))
- end
-
- def log_raw(logger, msg_id, *arg, &block)
logdev = Tempfile.new(File.basename(__FILE__) + '.log')
logger.instance_eval { @logdev = Logger::LogDevice.new(logdev) }
logger.__send__(msg_id, *arg, &block)
logdev.open
msg = logdev.read
logdev.close
- msg
+ Log.new(msg)
end
def test_level
@@ -102,32 +98,6 @@ class TestLogger < Test::Unit::TestCase
assert_match(/^$/, log.datetime)
end
- def test_formatter
- dummy = STDERR
- logger = Logger.new(dummy)
- # default
- log = log(logger, :info, "foo")
- assert_equal("foo\n", log.msg)
- # config
- logger.formatter = proc { |severity, timestamp, progname, msg|
- "#{severity}:#{msg}\n\n"
- }
- line = log_raw(logger, :info, "foo")
- assert_equal("INFO:foo\n\n", line)
- # recover
- logger.formatter = nil
- log = log(logger, :info, "foo")
- assert_equal("foo\n", log.msg)
- # again
- o = Object.new
- def o.call(severity, timestamp, progname, msg)
- "<<#{severity}-#{msg}>>\n"
- end
- logger.formatter = o
- line = log_raw(logger, :info, "foo")
- assert_equal("<<INFO-foo>>\n", line)
- end
-
def test_initialize
logger = Logger.new(STDERR)
assert_nil(logger.progname)
@@ -303,74 +273,4 @@ class TestLogDevice < Test::Unit::TestCase
assert(w.closed?)
r.close
end
-
- def test_shifting_size
- logfile = File.basename(__FILE__) + '_1.log'
- logfile0 = logfile + '.0'
- logfile1 = logfile + '.1'
- logfile2 = logfile + '.2'
- logfile3 = logfile + '.3'
- File.unlink(logfile) if File.exist?(logfile)
- File.unlink(logfile0) if File.exist?(logfile0)
- File.unlink(logfile1) if File.exist?(logfile1)
- File.unlink(logfile2) if File.exist?(logfile2)
- logger = Logger.new(logfile, 4, 100)
- logger.error("0" * 15)
- assert(File.exist?(logfile))
- assert(!File.exist?(logfile0))
- logger.error("0" * 15)
- assert(File.exist?(logfile0))
- assert(!File.exist?(logfile1))
- logger.error("0" * 15)
- assert(File.exist?(logfile1))
- assert(!File.exist?(logfile2))
- logger.error("0" * 15)
- assert(File.exist?(logfile2))
- assert(!File.exist?(logfile3))
- logger.error("0" * 15)
- assert(!File.exist?(logfile3))
- logger.error("0" * 15)
- assert(!File.exist?(logfile3))
- logger.close
- File.unlink(logfile)
- File.unlink(logfile0)
- File.unlink(logfile1)
- File.unlink(logfile2)
-
- logfile = File.basename(__FILE__) + '_2.log'
- logfile0 = logfile + '.0'
- logfile1 = logfile + '.1'
- logfile2 = logfile + '.2'
- logfile3 = logfile + '.3'
- logger = Logger.new(logfile, 4, 150)
- logger.error("0" * 15)
- assert(File.exist?(logfile))
- assert(!File.exist?(logfile0))
- logger.error("0" * 15)
- assert(!File.exist?(logfile0))
- logger.error("0" * 15)
- assert(File.exist?(logfile0))
- assert(!File.exist?(logfile1))
- logger.error("0" * 15)
- assert(!File.exist?(logfile1))
- logger.error("0" * 15)
- assert(File.exist?(logfile1))
- assert(!File.exist?(logfile2))
- logger.error("0" * 15)
- assert(!File.exist?(logfile2))
- logger.error("0" * 15)
- assert(File.exist?(logfile2))
- assert(!File.exist?(logfile3))
- logger.error("0" * 15)
- assert(!File.exist?(logfile3))
- logger.error("0" * 15)
- assert(!File.exist?(logfile3))
- logger.error("0" * 15)
- assert(!File.exist?(logfile3))
- logger.close
- File.unlink(logfile)
- File.unlink(logfile0)
- File.unlink(logfile1)
- File.unlink(logfile2)
- end
end
diff --git a/test/net/http/test_httpheader.rb b/test/net/http/test_httpheader.rb
deleted file mode 100644
index 2c64e31f10..0000000000
--- a/test/net/http/test_httpheader.rb
+++ /dev/null
@@ -1,290 +0,0 @@
-require 'net/http'
-require 'test/unit'
-
-class HTTPHeaderTest < Test::Unit::TestCase
-
- class C
- include Net::HTTPHeader
- def initialize
- initialize_http_header({})
- end
- end
-
- def setup
- @c = C.new
- end
-
- def test_size
- assert_equal 0, @c.size
- @c['a'] = 'a'
- assert_equal 1, @c.size
- @c['b'] = 'b'
- assert_equal 2, @c.size
- @c['b'] = 'b'
- assert_equal 2, @c.size
- @c['c'] = 'c'
- assert_equal 3, @c.size
- end
-
- def test_ASET
- @c['My-Header'] = 'test string'
- @c['my-Header'] = 'test string'
- @c['My-header'] = 'test string'
- @c['my-header'] = 'test string'
- @c['MY-HEADER'] = 'test string'
- assert_equal 1, @c.size
-
- @c['AaA'] = 'aaa'
- @c['aaA'] = 'aaa'
- @c['AAa'] = 'aaa'
- assert_equal 2, @c.length
- end
-
- def test_AREF
- @c['My-Header'] = 'test string'
- assert_equal 'test string', @c['my-header']
- assert_equal 'test string', @c['MY-header']
- assert_equal 'test string', @c['my-HEADER']
-
- @c['Next-Header'] = 'next string'
- assert_equal 'next string', @c['next-header']
- end
-
- def test_add_field
- @c.add_field 'My-Header', 'a'
- assert_equal 'a', @c['My-Header']
- assert_equal ['a'], @c.get_fields('My-Header')
- @c.add_field 'My-Header', 'b'
- assert_equal 'a, b', @c['My-Header']
- assert_equal ['a', 'b'], @c.get_fields('My-Header')
- @c.add_field 'My-Header', 'c'
- assert_equal 'a, b, c', @c['My-Header']
- assert_equal ['a', 'b', 'c'], @c.get_fields('My-Header')
- @c.add_field 'My-Header', 'd, d'
- assert_equal 'a, b, c, d, d', @c['My-Header']
- assert_equal ['a', 'b', 'c', 'd, d'], @c.get_fields('My-Header')
- end
-
- def test_get_fields
- @c['My-Header'] = 'test string'
- assert_equal ['test string'], @c.get_fields('my-header')
- assert_equal ['test string'], @c.get_fields('My-header')
- assert_equal ['test string'], @c.get_fields('my-Header')
-
- assert_nil @c.get_fields('not-found')
- assert_nil @c.get_fields('Not-Found')
-
- @c.get_fields('my-header').push 'junk'
- assert_equal ['test string'], @c.get_fields('my-header')
- @c.get_fields('my-header').clear
- assert_equal ['test string'], @c.get_fields('my-header')
- end
-
- def test_delete
- @c['My-Header'] = 'test'
- assert_equal 'test', @c['My-Header']
- assert_nil @c['not-found']
- @c.delete 'My-Header'
- assert_nil @c['My-Header']
- assert_nil @c['not-found']
- @c.delete 'My-Header'
- @c.delete 'My-Header'
- assert_nil @c['My-Header']
- assert_nil @c['not-found']
- end
-
- def test_each
- @c['My-Header'] = 'test'
- @c.each do |k, v|
- assert_equal 'my-header', k
- assert_equal 'test', v
- end
- @c.each do |k, v|
- assert_equal 'my-header', k
- assert_equal 'test', v
- end
- end
-
- def test_each_key
- @c['My-Header'] = 'test'
- @c.each_key do |k|
- assert_equal 'my-header', k
- end
- @c.each_key do |k|
- assert_equal 'my-header', k
- end
- end
-
- def test_each_value
- @c['My-Header'] = 'test'
- @c.each_value do |v|
- assert_equal 'test', v
- end
- @c.each_value do |v|
- assert_equal 'test', v
- end
- end
-
- def test_canonical_each
- @c['my-header'] = ['a', 'b']
- @c.canonical_each do |k,v|
- assert_equal 'My-Header', k
- assert_equal 'a, b', v
- end
- end
-
-=begin
- def test_each_capitalized
- @c['my-header'] = ['a', 'b']
- @c.each_capitalized do |k,v|
- assert_equal 'My-Header', k
- assert_equal 'a, b', v
- end
- end
-=end
-
- def test_key?
- @c['My-Header'] = 'test'
- assert_equal true, @c.key?('My-Header')
- assert_equal true, @c.key?('my-header')
- assert_equal false, @c.key?('Not-Found')
- assert_equal false, @c.key?('not-found')
- assert_equal false, @c.key?('')
- assert_equal false, @c.key?('x' * 1024)
- end
-
- def test_to_hash
- end
-
- def test_range
- try_range(1..5, '1-5')
- try_range(234..567, '234-567')
- try_range(-5..-1, '-5')
- try_range(1..-1, '1-')
- end
-
- def try_range(r, s)
- @c['range'] = "bytes=#{s}"
- assert_equal r, Array(@c.range)[0]
- end
-
- def test_range=
- @c.range = 0..499
- assert_equal 'bytes=0-499', @c['range']
- @c.range = 0...500
- assert_equal 'bytes=0-499', @c['range']
- @c.range = 300
- assert_equal 'bytes=0-299', @c['range']
- @c.range = -400
- assert_equal 'bytes=-400', @c['range']
- @c.set_range 0, 500
- assert_equal 'bytes=0-499', @c['range']
- end
-
- def test_content_range
- end
-
- def test_range_length
- @c['Content-Range'] = "bytes 0-499/1000"
- assert_equal 500, @c.range_length
- @c['Content-Range'] = "bytes 1-500/1000"
- assert_equal 500, @c.range_length
- @c['Content-Range'] = "bytes 1-1/1000"
- assert_equal 1, @c.range_length
- end
-
- def test_chunked?
- try_chunked true, 'chunked'
- try_chunked true, ' chunked '
- try_chunked true, '(OK)chunked'
-
- try_chunked false, 'not-chunked'
- try_chunked false, 'chunked-but-not-chunked'
- end
-
- def try_chunked(bool, str)
- @c['transfer-encoding'] = str
- assert_equal bool, @c.chunked?
- end
-
- def test_content_length
- @c.delete('content-length')
- assert_nil @c['content-length']
-
- try_content_length 500, '500'
- try_content_length 10000_0000_0000, '1000000000000'
- try_content_length 123, ' 123'
- try_content_length 1, '1 23'
- try_content_length 500, '(OK)500'
- assert_raises(Net::HTTPHeaderSyntaxError, 'here is no digit, but') {
- @c['content-length'] = 'no digit'
- @c.content_length
- }
- end
-
- def try_content_length(len, str)
- @c['content-length'] = str
- assert_equal len, @c.content_length
- end
-
-=begin
- def test_content_length=
- @c.content_length = 0
- assert_equal 0, @c.content_length
- @c.content_length = 1
- assert_equal 1, @c.content_length
- @c.content_length = 999
- assert_equal 999, @c.content_length
- @c.content_length = 10000000000000
- assert_equal 10000000000000, @c.content_length
- end
-=end
-
-=begin
- def test_content_type
- @c.content_type = 'text/html'
- assert_equal 'text/html', @c.content_type
- @c.content_type = 'application/pdf'
- assert_equal 'application/pdf', @c.content_type
- @c.set_content_type 'text/html', {'charset' => 'iso-2022-jp'}
- assert_equal 'text/html', @c.content_type
- end
-
- def test_main_type
- @c.content_type = 'text/html'
- assert_equal 'text', @c.main_type
- @c.content_type = 'application/pdf'
- assert_equal 'application', @c.main_type
- @c.set_content_type 'text/html', {'charset' => 'iso-2022-jp'}
- assert_equal 'text', @c.main_type
- end
-
- def test_sub_type
- @c.content_type = 'text/html'
- assert_equal 'html', @c.sub_type
- @c.content_type = 'application/pdf'
- assert_equal 'pdf', @c.sub_type
- @c.set_content_type 'text/html', {'charset' => 'iso-2022-jp'}
- assert_equal 'html', @c.sub_type
- end
-
- def test_type_params
- @c.content_type = 'text/html'
- assert_equal({}, @c.type_params)
- @c.content_type = 'application/pdf'
- assert_equal({}, @c.type_params)
- @c.set_content_type 'text/html', {'charset' => 'iso-2022-jp'}
- assert_equal({'charset' => 'iso-2022-jp'}, @c.type_params)
- end
-
- def test_set_content_type
- end
-=end
-
- def test_basic_auth
- end
-
- def test_proxy_basic_auth
- end
-
-end
diff --git a/test/net/http/test_https_proxy.rb b/test/net/http/test_https_proxy.rb
deleted file mode 100644
index 6332319f26..0000000000
--- a/test/net/http/test_https_proxy.rb
+++ /dev/null
@@ -1,30 +0,0 @@
-begin
- require 'net/https'
-rescue LoadError
-end
-require 'test/unit'
-
-class HTTPSProxyTest < Test::Unit::TestCase
- def test_https_proxy_authentication
- TCPServer.open("127.0.0.1", 0) {|serv|
- _, port, _, _ = serv.addr
- t = Thread.new {
- proxy = Net::HTTP.Proxy("127.0.0.1", port, 'user', 'password')
- http = proxy.new("foo.example.org", 8000)
- http.use_ssl = true
- http.verify_mode = OpenSSL::SSL::VERIFY_NONE
- http.start
- }
- sock = serv.accept
- proxy_request = sock.gets("\r\n\r\n")
- assert_equal(
- "CONNECT foo.example.org:8000 HTTP/1.1\r\n" +
- "Host: foo.example.org:8000\r\n" +
- "Proxy-Authorization: Basic dXNlcjpwYXNzd29yZA==\r\n" +
- "\r\n",
- proxy_request,
- "[ruby-dev:25673]")
- }
- end
-end if defined?(OpenSSL)
-
diff --git a/test/nkf/test_kconv.rb b/test/nkf/test_kconv.rb
deleted file mode 100644
index 2533424705..0000000000
--- a/test/nkf/test_kconv.rb
+++ /dev/null
@@ -1,71 +0,0 @@
-require 'test/unit'
-require 'kconv'
-
-class TestKconv < Test::Unit::TestCase
- EUC_STR = "\
-\xa5\xaa\xa5\xd6\xa5\xb8\xa5\xa7\xa5\xaf\xa5\xc8\xbb\xd8\xb8\xfe\
-\xa5\xd7\xa5\xed\xa5\xb0\xa5\xe9\xa5\xdf\xa5\xf3\xa5\xb0\xb8\xc0\xb8\xec
-\x52\x75\x62\x79"
- UTF8_STR = "\
-\xe3\x82\xaa\xe3\x83\x96\xe3\x82\xb8\xe3\x82\xa7\
-\xe3\x82\xaf\xe3\x83\x88\xe6\x8c\x87\xe5\x90\x91\
-\xe3\x83\x97\xe3\x83\xad\xe3\x82\xb0\xe3\x83\xa9\xe3\x83\x9f\
-\xe3\x83\xb3\xe3\x82\xb0\xe8\xa8\x80\xe8\xaa\x9e
-\x52\x75\x62\x79"
- SJIS_STR = "\
-\x83\x49\x83\x75\x83\x57\x83\x46\x83\x4e\x83\x67\x8e\x77\x8c\xfc\
-\x83\x76\x83\x8d\x83\x4f\x83\x89\x83\x7e\x83\x93\x83\x4f\x8c\xbe\x8c\xea
-\x52\x75\x62\x79"
- JIS_STR = "\
-\x1b\x24\x42\x25\x2a\x25\x56\x25\x38\x25\x27\x25\x2f\x25\x48\x3b\x58\x38\x7e\
-\x25\x57\x25\x6d\x25\x30\x25\x69\x25\x5f\x25\x73\x25\x30\x38\x40\x38\x6c\x1b\x28\x42
-\x52\x75\x62\x79"
-
- def test_eucjp
- assert(EUC_STR.iseuc)
- assert_equal(::Kconv::EUC, Kconv.guess(EUC_STR))
- assert_equal(EUC_STR, EUC_STR.toeuc)
- assert_equal(EUC_STR, SJIS_STR.toeuc)
- assert_equal(EUC_STR, UTF8_STR.toeuc)
- assert_equal(EUC_STR, JIS_STR.toeuc)
- assert_equal(EUC_STR, EUC_STR.kconv(::NKF::EUC))
- assert_equal(EUC_STR, SJIS_STR.kconv(::NKF::EUC))
- assert_equal(EUC_STR, UTF8_STR.kconv(::NKF::EUC))
- assert_equal(EUC_STR, JIS_STR.kconv(::NKF::EUC))
- end
- def test_shiftjis
- assert(SJIS_STR.issjis)
- assert_equal(::Kconv::SJIS, Kconv.guess(SJIS_STR))
- assert_equal(SJIS_STR, EUC_STR.tosjis)
- assert_equal(SJIS_STR, SJIS_STR.tosjis)
- assert_equal(SJIS_STR, UTF8_STR.tosjis)
- assert_equal(SJIS_STR, JIS_STR.tosjis)
- assert_equal(SJIS_STR, EUC_STR.kconv(::NKF::SJIS))
- assert_equal(SJIS_STR, SJIS_STR.kconv(::NKF::SJIS))
- assert_equal(SJIS_STR, UTF8_STR.kconv(::NKF::SJIS))
- assert_equal(SJIS_STR, JIS_STR.kconv(::NKF::SJIS))
- end
- def test_utf8
- assert(UTF8_STR.isutf8)
- assert_equal(::Kconv::UTF8, Kconv.guess(UTF8_STR))
- assert_equal(UTF8_STR, EUC_STR.toutf8)
- assert_equal(UTF8_STR, SJIS_STR.toutf8)
- assert_equal(UTF8_STR, UTF8_STR.toutf8)
- assert_equal(UTF8_STR, JIS_STR.toutf8)
- assert_equal(UTF8_STR, EUC_STR.kconv(::NKF::UTF8))
- assert_equal(UTF8_STR, SJIS_STR.kconv(::NKF::UTF8))
- assert_equal(UTF8_STR, UTF8_STR.kconv(::NKF::UTF8))
- assert_equal(UTF8_STR, JIS_STR.kconv(::NKF::UTF8))
- end
- def test_jis
- assert_equal(::Kconv::JIS, Kconv.guess(JIS_STR))
- assert_equal(JIS_STR, EUC_STR.tojis)
- assert_equal(JIS_STR, SJIS_STR.tojis)
- assert_equal(JIS_STR, UTF8_STR.tojis)
- assert_equal(JIS_STR, JIS_STR.tojis)
- assert_equal(JIS_STR, EUC_STR.kconv(::NKF::JIS))
- assert_equal(JIS_STR, SJIS_STR.kconv(::NKF::JIS))
- assert_equal(JIS_STR, UTF8_STR.kconv(::NKF::JIS))
- assert_equal(JIS_STR, JIS_STR.kconv(::NKF::JIS))
- end
-end
diff --git a/test/nkf/test_nkf.rb b/test/nkf/test_nkf.rb
deleted file mode 100644
index 279ad59e1a..0000000000
--- a/test/nkf/test_nkf.rb
+++ /dev/null
@@ -1,16 +0,0 @@
-require 'test/unit'
-require 'nkf'
-
-class TestNKF < Test::Unit::TestCase
- EUC_STR = "\xa5\xaa\xa5\xd6\xa5\xb8\xa5\xa7\xa5\xaf\xa5\xc8\xbb\xd8\xb8\xfe\
-\xa5\xb9\xa5\xaf\xa5\xea\xa5\xd7\xa5\xc8\xb8\xc0\xb8\xec\
-Ruby"
-
- def test_guess
- str_euc = EUC_STR
- str_jis = NKF.nkf('-j', str_euc)
- assert_equal(::NKF::JIS, NKF.guess(str_jis))
- assert_equal(::NKF::EUC, NKF.guess(str_euc))
- end
-
-end
diff --git a/test/openssl/ssl_server.rb b/test/openssl/ssl_server.rb
index 6e620629c5..699a181256 100644
--- a/test/openssl/ssl_server.rb
+++ b/test/openssl/ssl_server.rb
@@ -46,25 +46,15 @@ ctx.key = ssl_key
ctx.verify_mode = verify_mode
Socket.do_not_reverse_lookup = true
-tcps = nil
-100.times{|i|
- begin
- tcps = TCPServer.new("0.0.0.0", port+i)
- port = port + i
- break
- rescue Errno::EADDRINUSE
- next
- end
-}
+tcps = TCPServer.new("0.0.0.0", port)
ssls = OpenSSL::SSL::SSLServer.new(tcps, ctx)
ssls.start_immediately = start_immediately
$stdout.sync = true
$stdout.puts Process.pid
-$stdout.puts port
loop do
- ssl = ssls.accept rescue next
+ ssl = ssls.accept
Thread.start{
q = Queue.new
th = Thread.start{ ssl.write(q.shift) while true }
diff --git a/test/openssl/test_asn1.rb b/test/openssl/test_asn1.rb
deleted file mode 100644
index f196bc48fb..0000000000
--- a/test/openssl/test_asn1.rb
+++ /dev/null
@@ -1,197 +0,0 @@
-begin
- require "openssl"
- require File.join(File.dirname(__FILE__), "utils.rb")
-rescue LoadError
-end
-require 'test/unit'
-
-class OpenSSL::TestASN1 < Test::Unit::TestCase
- def test_decode
- subj = OpenSSL::X509::Name.parse("/DC=org/DC=ruby-lang/CN=TestCA")
- key = OpenSSL::TestUtils::TEST_KEY_RSA1024
- now = Time.at(Time.now.to_i) # suppress usec
- s = 0xdeadbeafdeadbeafdeadbeafdeadbeaf
- exts = [
- ["basicConstraints","CA:TRUE,pathlen:1",true],
- ["keyUsage","keyCertSign, cRLSign",true],
- ["subjectKeyIdentifier","hash",false],
- ]
- dgst = OpenSSL::Digest::SHA1.new
- cert = OpenSSL::TestUtils.issue_cert(
- subj, key, s, now, now+3600, exts, nil, nil, dgst)
-
-
- asn1 = OpenSSL::ASN1.decode(cert)
- assert_equal(OpenSSL::ASN1::Sequence, asn1.class)
- assert_equal(3, asn1.value.size)
- tbs_cert, sig_alg, sig_val = *asn1.value
-
- assert_equal(OpenSSL::ASN1::Sequence, tbs_cert.class)
- assert_equal(8, tbs_cert.value.size)
-
- version = tbs_cert.value[0]
- assert_equal(:CONTEXT_SPECIFIC, version.tag_class)
- assert_equal(0, version.tag)
- assert_equal(1, version.value.size)
- assert_equal(OpenSSL::ASN1::Integer, version.value[0].class)
- assert_equal(2, version.value[0].value)
-
- serial = tbs_cert.value[1]
- assert_equal(OpenSSL::ASN1::Integer, serial.class)
- assert_equal(0xdeadbeafdeadbeafdeadbeafdeadbeaf, serial.value)
-
- sig = tbs_cert.value[2]
- assert_equal(OpenSSL::ASN1::Sequence, sig.class)
- assert_equal(2, sig.value.size)
- assert_equal(OpenSSL::ASN1::ObjectId, sig.value[0].class)
- assert_equal("1.2.840.113549.1.1.5", sig.value[0].oid)
- assert_equal(OpenSSL::ASN1::Null, sig.value[1].class)
-
- dn = tbs_cert.value[3] # issuer
- assert_equal(subj.hash, OpenSSL::X509::Name.new(dn).hash)
- assert_equal(OpenSSL::ASN1::Sequence, dn.class)
- assert_equal(3, dn.value.size)
- assert_equal(OpenSSL::ASN1::Set, dn.value[0].class)
- assert_equal(OpenSSL::ASN1::Set, dn.value[1].class)
- assert_equal(OpenSSL::ASN1::Set, dn.value[2].class)
- assert_equal(1, dn.value[0].value.size)
- assert_equal(1, dn.value[1].value.size)
- assert_equal(1, dn.value[2].value.size)
- assert_equal(OpenSSL::ASN1::Sequence, dn.value[0].value[0].class)
- assert_equal(OpenSSL::ASN1::Sequence, dn.value[1].value[0].class)
- assert_equal(OpenSSL::ASN1::Sequence, dn.value[2].value[0].class)
- assert_equal(2, dn.value[0].value[0].value.size)
- assert_equal(2, dn.value[1].value[0].value.size)
- assert_equal(2, dn.value[2].value[0].value.size)
- oid, value = *dn.value[0].value[0].value
- assert_equal(OpenSSL::ASN1::ObjectId, oid.class)
- assert_equal("0.9.2342.19200300.100.1.25", oid.oid)
- assert_equal(OpenSSL::ASN1::IA5String, value.class)
- assert_equal("org", value.value)
- oid, value = *dn.value[1].value[0].value
- assert_equal(OpenSSL::ASN1::ObjectId, oid.class)
- assert_equal("0.9.2342.19200300.100.1.25", oid.oid)
- assert_equal(OpenSSL::ASN1::IA5String, value.class)
- assert_equal("ruby-lang", value.value)
- oid, value = *dn.value[2].value[0].value
- assert_equal(OpenSSL::ASN1::ObjectId, oid.class)
- assert_equal("2.5.4.3", oid.oid)
- assert_equal(OpenSSL::ASN1::UTF8String, value.class)
- assert_equal("TestCA", value.value)
-
- validity = tbs_cert.value[4]
- assert_equal(OpenSSL::ASN1::Sequence, validity.class)
- assert_equal(2, validity.value.size)
- assert_equal(OpenSSL::ASN1::UTCTime, validity.value[0].class)
- assert_equal(now, validity.value[0].value)
- assert_equal(OpenSSL::ASN1::UTCTime, validity.value[1].class)
- assert_equal(now+3600, validity.value[1].value)
-
- dn = tbs_cert.value[5] # subject
- assert_equal(subj.hash, OpenSSL::X509::Name.new(dn).hash)
- assert_equal(OpenSSL::ASN1::Sequence, dn.class)
- assert_equal(3, dn.value.size)
- assert_equal(OpenSSL::ASN1::Set, dn.value[0].class)
- assert_equal(OpenSSL::ASN1::Set, dn.value[1].class)
- assert_equal(OpenSSL::ASN1::Set, dn.value[2].class)
- assert_equal(1, dn.value[0].value.size)
- assert_equal(1, dn.value[1].value.size)
- assert_equal(1, dn.value[2].value.size)
- assert_equal(OpenSSL::ASN1::Sequence, dn.value[0].value[0].class)
- assert_equal(OpenSSL::ASN1::Sequence, dn.value[1].value[0].class)
- assert_equal(OpenSSL::ASN1::Sequence, dn.value[2].value[0].class)
- assert_equal(2, dn.value[0].value[0].value.size)
- assert_equal(2, dn.value[1].value[0].value.size)
- assert_equal(2, dn.value[2].value[0].value.size)
- oid, value = *dn.value[0].value[0].value
- assert_equal(OpenSSL::ASN1::ObjectId, oid.class)
- assert_equal("0.9.2342.19200300.100.1.25", oid.oid)
- assert_equal(OpenSSL::ASN1::IA5String, value.class)
- assert_equal("org", value.value)
- oid, value = *dn.value[1].value[0].value
- assert_equal(OpenSSL::ASN1::ObjectId, oid.class)
- assert_equal("0.9.2342.19200300.100.1.25", oid.oid)
- assert_equal(OpenSSL::ASN1::IA5String, value.class)
- assert_equal("ruby-lang", value.value)
- oid, value = *dn.value[2].value[0].value
- assert_equal(OpenSSL::ASN1::ObjectId, oid.class)
- assert_equal("2.5.4.3", oid.oid)
- assert_equal(OpenSSL::ASN1::UTF8String, value.class)
- assert_equal("TestCA", value.value)
-
- pkey = tbs_cert.value[6]
- assert_equal(OpenSSL::ASN1::Sequence, pkey.class)
- assert_equal(2, pkey.value.size)
- assert_equal(OpenSSL::ASN1::Sequence, pkey.value[0].class)
- assert_equal(2, pkey.value[0].value.size)
- assert_equal(OpenSSL::ASN1::ObjectId, pkey.value[0].value[0].class)
- assert_equal("1.2.840.113549.1.1.1", pkey.value[0].value[0].oid)
- assert_equal(OpenSSL::ASN1::BitString, pkey.value[1].class)
- assert_equal(0, pkey.value[1].unused_bits)
- spkey = OpenSSL::ASN1.decode(pkey.value[1].value)
- assert_equal(OpenSSL::ASN1::Sequence, spkey.class)
- assert_equal(2, spkey.value.size)
- assert_equal(OpenSSL::ASN1::Integer, spkey.value[0].class)
- assert_equal(143085709396403084580358323862163416700436550432664688288860593156058579474547937626086626045206357324274536445865308750491138538454154232826011964045825759324933943290377903384882276841880081931690695505836279972214003660451338124170055999155993192881685495391496854691199517389593073052473319331505702779271, spkey.value[0].value)
- assert_equal(OpenSSL::ASN1::Integer, spkey.value[1].class)
- assert_equal(65537, spkey.value[1].value)
-
- extensions = tbs_cert.value[7]
- assert_equal(:CONTEXT_SPECIFIC, extensions.tag_class)
- assert_equal(3, extensions.tag)
- assert_equal(1, extensions.value.size)
- assert_equal(OpenSSL::ASN1::Sequence, extensions.value[0].class)
- assert_equal(3, extensions.value[0].value.size)
-
- ext = extensions.value[0].value[0] # basicConstraints
- assert_equal(OpenSSL::ASN1::Sequence, ext.class)
- assert_equal(3, ext.value.size)
- assert_equal(OpenSSL::ASN1::ObjectId, ext.value[0].class)
- assert_equal("2.5.29.19", ext.value[0].oid)
- assert_equal(OpenSSL::ASN1::Boolean, ext.value[1].class)
- assert_equal(true, ext.value[1].value)
- assert_equal(OpenSSL::ASN1::OctetString, ext.value[2].class)
- extv = OpenSSL::ASN1.decode(ext.value[2].value)
- assert_equal(OpenSSL::ASN1::Sequence, extv.class)
- assert_equal(2, extv.value.size)
- assert_equal(OpenSSL::ASN1::Boolean, extv.value[0].class)
- assert_equal(true, extv.value[0].value)
- assert_equal(OpenSSL::ASN1::Integer, extv.value[1].class)
- assert_equal(1, extv.value[1].value)
-
- ext = extensions.value[0].value[1] # keyUsage
- assert_equal(OpenSSL::ASN1::Sequence, ext.class)
- assert_equal(3, ext.value.size)
- assert_equal(OpenSSL::ASN1::ObjectId, ext.value[0].class)
- assert_equal("2.5.29.15", ext.value[0].oid)
- assert_equal(OpenSSL::ASN1::Boolean, ext.value[1].class)
- assert_equal(true, ext.value[1].value)
- assert_equal(OpenSSL::ASN1::OctetString, ext.value[2].class)
- extv = OpenSSL::ASN1.decode(ext.value[2].value)
- assert_equal(OpenSSL::ASN1::BitString, extv.class)
- str = "\000"; str[0] = 0b00000110
- assert_equal(str, extv.value)
-
- ext = extensions.value[0].value[2] # subjetKeyIdentifier
- assert_equal(OpenSSL::ASN1::Sequence, ext.class)
- assert_equal(2, ext.value.size)
- assert_equal(OpenSSL::ASN1::ObjectId, ext.value[0].class)
- assert_equal("2.5.29.14", ext.value[0].oid)
- assert_equal(OpenSSL::ASN1::OctetString, ext.value[1].class)
- extv = OpenSSL::ASN1.decode(ext.value[1].value)
- assert_equal(OpenSSL::ASN1::OctetString, extv.class)
- sha1 = OpenSSL::Digest::SHA1.new
- sha1.update(pkey.value[1].value)
- assert_equal(sha1.digest, extv.value)
-
- assert_equal(OpenSSL::ASN1::Sequence, sig_alg.class)
- assert_equal(2, sig_alg.value.size)
- assert_equal(OpenSSL::ASN1::ObjectId, pkey.value[0].value[0].class)
- assert_equal("1.2.840.113549.1.1.1", pkey.value[0].value[0].oid)
- assert_equal(OpenSSL::ASN1::Null, pkey.value[0].value[1].class)
-
- assert_equal(OpenSSL::ASN1::BitString, sig_val.class)
- cululated_sig = key.sign(OpenSSL::Digest::SHA1.new, tbs_cert.to_der)
- assert_equal(cululated_sig, sig_val.value)
- end
-end if defined?(OpenSSL)
diff --git a/test/openssl/test_digest.rb b/test/openssl/test_digest.rb
index da5b6e49c5..b169b802a8 100644
--- a/test/openssl/test_digest.rb
+++ b/test/openssl/test_digest.rb
@@ -60,15 +60,6 @@ class OpenSSL::TestDigest < Test::Unit::TestCase
dig2 = @d1.digest
assert_equal(dig1, dig2, "reset")
end
-
- if OpenSSL::OPENSSL_VERSION_NUMBER > 0x00908000
- def test_098_features
- assert_equal("abd37534c7d9a2efb9465de931cd7055ffdb8879563ae98078d6d6d5", OpenSSL::Digest::SHA224.hexdigest("a"))
- assert_equal("ca978112ca1bbdcafac231b39a23dc4da786eff8147c4e72b9807785afee48bb", OpenSSL::Digest::SHA256.hexdigest("a"))
- assert_equal("54a59b9f22b0b80880d8427e548b7c23abd873486e1f035dce9cd697e85175033caa88e6d57bc35efae0b5afd3145f31", OpenSSL::Digest::SHA384.hexdigest("a"))
- assert_equal("1f40fc92da241694750979ee6cf582f2d5d7d28e18335de05abc54d0560e0f5302860c652bf08d560252aa5e74210546f369fbbbce8c12cfc7957b2652fe9a75", OpenSSL::Digest::SHA512.hexdigest("a"))
- end
- end
end
end
diff --git a/test/openssl/test_ns_spki.rb b/test/openssl/test_ns_spki.rb
deleted file mode 100644
index 3937132aa0..0000000000
--- a/test/openssl/test_ns_spki.rb
+++ /dev/null
@@ -1,59 +0,0 @@
-begin
- require "openssl"
- require File.join(File.dirname(__FILE__), "utils.rb")
-rescue LoadError
-end
-require "test/unit"
-
-if defined?(OpenSSL)
-
-
-class OpenSSL::TestNSSPI < Test::Unit::TestCase
- def setup
- # This request data is adopt from the specification of
- # "Netscape Extensions for User Key Generation".
- # -- http://wp.netscape.com/eng/security/comm4-keygen.html
- @b64 = "MIHFMHEwXDANBgkqhkiG9w0BAQEFAANLADBIAkEAnX0TILJrOMUue+PtwBRE6XfV"
- @b64 << "WtKQbsshxk5ZhcUwcwyvcnIq9b82QhJdoACdD34rqfCAIND46fXKQUnb0mvKzQID"
- @b64 << "AQABFhFNb3ppbGxhSXNNeUZyaWVuZDANBgkqhkiG9w0BAQQFAANBAAKv2Eex2n/S"
- @b64 << "r/7iJNroWlSzSMtTiQTEB+ADWHGj9u1xrUrOilq/o2cuQxIfZcNZkYAkWP4DubqW"
- @b64 << "i0//rgBvmco="
- end
-
- def teardown
- end
-
- def test_build_data
- key1 = OpenSSL::TestUtils::TEST_KEY_RSA1024
- key2 = OpenSSL::TestUtils::TEST_KEY_RSA2048
- spki = OpenSSL::Netscape::SPKI.new
- spki.challenge = "RandomString"
- spki.public_key = key1.public_key
- spki.sign(key1, OpenSSL::Digest::SHA1.new)
- assert(spki.verify(spki.public_key))
- assert(spki.verify(key1.public_key))
- assert(!spki.verify(key2.public_key))
-
- der = spki.to_der
- spki = OpenSSL::Netscape::SPKI.new(der)
- assert_equal("RandomString", spki.challenge)
- assert_equal(key1.public_key.to_der, spki.public_key.to_der)
- assert(spki.verify(spki.public_key))
- end
-
- def test_decode_data
- spki = OpenSSL::Netscape::SPKI.new(@b64)
- assert_equal(@b64, spki.to_pem)
- assert_equal(@b64.unpack("m").first, spki.to_der)
- assert_equal("MozillaIsMyFriend", spki.challenge)
- assert_equal(OpenSSL::PKey::RSA, spki.public_key.class)
-
- spki = OpenSSL::Netscape::SPKI.new(@b64.unpack("m").first)
- assert_equal(@b64, spki.to_pem)
- assert_equal(@b64.unpack("m").first, spki.to_der)
- assert_equal("MozillaIsMyFriend", spki.challenge)
- assert_equal(OpenSSL::PKey::RSA, spki.public_key.class)
- end
-end
-
-end
diff --git a/test/openssl/test_pair.rb b/test/openssl/test_pair.rb
deleted file mode 100644
index 7273554362..0000000000
--- a/test/openssl/test_pair.rb
+++ /dev/null
@@ -1,144 +0,0 @@
-begin
- require "openssl"
-rescue LoadError
-end
-require 'test/unit'
-
-if defined?(OpenSSL)
-
-require 'socket'
-dir = File.expand_path(__FILE__)
-2.times {dir = File.dirname(dir)}
-$:.replace([File.join(dir, "ruby")] | $:)
-require 'ut_eof'
-
-module SSLPair
- def server
- host = "127.0.0.1"
- port = 0
- ctx = OpenSSL::SSL::SSLContext.new()
- ctx.ciphers = "ADH"
- tcps = TCPServer.new(host, port)
- ssls = OpenSSL::SSL::SSLServer.new(tcps, ctx)
- return ssls
- end
-
- def client(port)
- host = "127.0.0.1"
- ctx = OpenSSL::SSL::SSLContext.new()
- ctx.ciphers = "ADH"
- s = TCPSocket.new(host, port)
- ssl = OpenSSL::SSL::SSLSocket.new(s, ctx)
- ssl.connect
- ssl.sync_close = true
- ssl
- end
-
- def ssl_pair
- ssls = server
- th = Thread.new {
- ns = ssls.accept
- ssls.close
- ns
- }
- port = ssls.to_io.addr[1]
- c = client(port)
- s = th.value
- if block_given?
- begin
- yield c, s
- ensure
- c.close unless c.closed?
- s.close unless s.closed?
- end
- else
- return c, s
- end
- end
-end
-
-class OpenSSL::TestEOF1 < Test::Unit::TestCase
- include TestEOF
- include SSLPair
-
- def open_file(content)
- s1, s2 = ssl_pair
- Thread.new { s2 << content; s2.close }
- yield s1
- end
-end
-
-class OpenSSL::TestEOF2 < Test::Unit::TestCase
- include TestEOF
- include SSLPair
-
- def open_file(content)
- s1, s2 = ssl_pair
- Thread.new { s1 << content; s1.close }
- yield s2
- end
-end
-
-class OpenSSL::TestPair < Test::Unit::TestCase
- include SSLPair
-
- def test_getc
- ssl_pair {|s1, s2|
- s1 << "a"
- assert_equal(?a, s2.getc)
- }
- end
-
- def test_readpartial
- ssl_pair {|s1, s2|
- s2.write "a\nbcd"
- assert_equal("a\n", s1.gets)
- assert_equal("bcd", s1.readpartial(10))
- s2.write "efg"
- assert_equal("efg", s1.readpartial(10))
- s2.close
- assert_raise(EOFError) { s1.readpartial(10) }
- assert_raise(EOFError) { s1.readpartial(10) }
- assert_equal("", s1.readpartial(0))
- }
- end
-
- def test_readall
- ssl_pair {|s1, s2|
- s2.close
- assert_equal("", s1.read)
- }
- end
-
- def test_readline
- ssl_pair {|s1, s2|
- s2.close
- assert_raise(EOFError) { s1.readline }
- }
- end
-
- def test_puts_meta
- ssl_pair {|s1, s2|
- begin
- old = $/
- $/ = '*'
- s1.puts 'a'
- ensure
- $/ = old
- end
- s1.close
- assert_equal("a\n", s2.read)
- }
- end
-
- def test_puts_empty
- ssl_pair {|s1, s2|
- s1.puts
- s1.close
- assert_equal("\n", s2.read)
- }
- end
-
-end
-
-end
diff --git a/test/openssl/test_pkcs7.rb b/test/openssl/test_pkcs7.rb
deleted file mode 100644
index 9b472c1795..0000000000
--- a/test/openssl/test_pkcs7.rb
+++ /dev/null
@@ -1,154 +0,0 @@
-begin
- require "openssl"
- require File.join(File.dirname(__FILE__), "utils.rb")
-rescue LoadError
-end
-require "test/unit"
-
-if defined?(OpenSSL)
-
-class OpenSSL::TestPKCS7 < Test::Unit::TestCase
- def setup
- @rsa1024 = OpenSSL::TestUtils::TEST_KEY_RSA1024
- @rsa2048 = OpenSSL::TestUtils::TEST_KEY_RSA2048
- ca = OpenSSL::X509::Name.parse("/DC=org/DC=ruby-lang/CN=CA")
- ee1 = OpenSSL::X509::Name.parse("/DC=org/DC=ruby-lang/CN=EE1")
- ee2 = OpenSSL::X509::Name.parse("/DC=org/DC=ruby-lang/CN=EE2")
-
- now = Time.now
- ca_exts = [
- ["basicConstraints","CA:TRUE",true],
- ["keyUsage","keyCertSign, cRLSign",true],
- ["subjectKeyIdentifier","hash",false],
- ["authorityKeyIdentifier","keyid:always",false],
- ]
- @ca_cert = issue_cert(ca, @rsa2048, 1, Time.now, Time.now+3600, ca_exts,
- nil, nil, OpenSSL::Digest::SHA1.new)
- ee_exts = [
- ["keyUsage","Non Repudiation, Digital Signature, Key Encipherment",true],
- ["authorityKeyIdentifier","keyid:always",false],
- ["extendedKeyUsage","clientAuth, emailProtection, codeSigning",false],
- ]
- @ee1_cert = issue_cert(ee1, @rsa1024, 2, Time.now, Time.now+1800, ee_exts,
- @ca_cert, @rsa2048, OpenSSL::Digest::SHA1.new)
- @ee2_cert = issue_cert(ee2, @rsa1024, 3, Time.now, Time.now+1800, ee_exts,
- @ca_cert, @rsa2048, OpenSSL::Digest::SHA1.new)
- end
-
- def issue_cert(*args)
- OpenSSL::TestUtils.issue_cert(*args)
- end
-
- def test_signed
- store = OpenSSL::X509::Store.new
- store.add_cert(@ca_cert)
- ca_certs = [@ca_cert]
-
- data = "aaaaa\r\nbbbbb\r\nccccc\r\n"
- tmp = OpenSSL::PKCS7.sign(@ee1_cert, @rsa1024, data, ca_certs)
- p7 = OpenSSL::PKCS7::PKCS7.new(tmp.to_der)
- certs = p7.certificates
- signers = p7.signers
- assert(p7.verify([], store))
- assert_equal(data, p7.data)
- assert_equal(2, certs.size)
- assert_equal(@ee1_cert.subject.to_s, certs[0].subject.to_s)
- assert_equal(@ca_cert.subject.to_s, certs[1].subject.to_s)
- assert_equal(1, signers.size)
- assert_equal(@ee1_cert.serial, signers[0].serial)
- assert_equal(@ee1_cert.issuer.to_s, signers[0].issuer.to_s)
-
- # Normaly OpenSSL tries to translate the supplied content into canonical
- # MIME format (e.g. a newline character is converted into CR+LF).
- # If the content is a binary, PKCS7::BINARY flag should be used.
-
- data = "aaaaa\nbbbbb\nccccc\n"
- flag = OpenSSL::PKCS7::BINARY
- tmp = OpenSSL::PKCS7.sign(@ee1_cert, @rsa1024, data, ca_certs, flag)
- p7 = OpenSSL::PKCS7::PKCS7.new(tmp.to_der)
- certs = p7.certificates
- signers = p7.signers
- assert(p7.verify([], store))
- assert_equal(data, p7.data)
- assert_equal(2, certs.size)
- assert_equal(@ee1_cert.subject.to_s, certs[0].subject.to_s)
- assert_equal(@ca_cert.subject.to_s, certs[1].subject.to_s)
- assert_equal(1, signers.size)
- assert_equal(@ee1_cert.serial, signers[0].serial)
- assert_equal(@ee1_cert.issuer.to_s, signers[0].issuer.to_s)
-
- # A signed-data which have multiple signatures can be created
- # through the following steps.
- # 1. create two signed-data
- # 2. copy signerInfo and certificate from one to another
-
- tmp1 = OpenSSL::PKCS7.sign(@ee1_cert, @rsa1024, data, [], flag)
- tmp2 = OpenSSL::PKCS7.sign(@ee2_cert, @rsa1024, data, [], flag)
- tmp1.add_signer(tmp2.signers[0])
- tmp1.add_certificate(@ee2_cert)
-
- p7 = OpenSSL::PKCS7::PKCS7.new(tmp1.to_der)
- certs = p7.certificates
- signers = p7.signers
- assert(p7.verify([], store))
- assert_equal(data, p7.data)
- assert_equal(2, certs.size)
- assert_equal(2, signers.size)
- assert_equal(@ee1_cert.serial, signers[0].serial)
- assert_equal(@ee1_cert.issuer.to_s, signers[0].issuer.to_s)
- assert_equal(@ee2_cert.serial, signers[1].serial)
- assert_equal(@ee2_cert.issuer.to_s, signers[1].issuer.to_s)
- end
-
- def test_detached_sign
- store = OpenSSL::X509::Store.new
- store.add_cert(@ca_cert)
- ca_certs = [@ca_cert]
-
- data = "aaaaa\nbbbbb\nccccc\n"
- flag = OpenSSL::PKCS7::BINARY|OpenSSL::PKCS7::DETACHED
- tmp = OpenSSL::PKCS7.sign(@ee1_cert, @rsa1024, data, ca_certs, flag)
- p7 = OpenSSL::PKCS7::PKCS7.new(tmp.to_der)
- a1 = OpenSSL::ASN1.decode(p7)
-
- certs = p7.certificates
- signers = p7.signers
- assert(!p7.verify([], store))
- assert(p7.verify([], store, data))
- assert_equal(data, p7.data)
- assert_equal(2, certs.size)
- assert_equal(@ee1_cert.subject.to_s, certs[0].subject.to_s)
- assert_equal(@ca_cert.subject.to_s, certs[1].subject.to_s)
- assert_equal(1, signers.size)
- assert_equal(@ee1_cert.serial, signers[0].serial)
- assert_equal(@ee1_cert.issuer.to_s, signers[0].issuer.to_s)
- end
-
- def test_enveloped
- if OpenSSL::OPENSSL_VERSION_NUMBER <= 0x0090704f
- # PKCS7_encrypt() of OpenSSL-0.9.7d goes to SEGV.
- # http://www.mail-archive.com/openssl-dev@openssl.org/msg17376.html
- return
- end
-
- certs = [@ee1_cert, @ee2_cert]
- cipher = OpenSSL::Cipher::AES.new("128-CBC")
- data = "aaaaa\nbbbbb\nccccc\n"
-
- tmp = OpenSSL::PKCS7.encrypt(certs, data, cipher, OpenSSL::PKCS7::BINARY)
- p7 = OpenSSL::PKCS7::PKCS7.new(tmp.to_der)
- recip = p7.recipients
- assert_equal(:enveloped, p7.type)
- assert_equal(2, recip.size)
-
- assert_equal(@ca_cert.subject.to_s, recip[0].issuer.to_s)
- assert_equal(2, recip[0].serial)
- assert_equal(data, p7.decrypt(@rsa1024, @ee1_cert))
-
- assert_equal(@ca_cert.subject.to_s, recip[1].issuer.to_s)
- assert_equal(3, recip[1].serial)
- assert_equal(data, p7.decrypt(@rsa1024, @ee2_cert))
- end
-end
-
-end
diff --git a/test/openssl/test_pkey_rsa.rb b/test/openssl/test_pkey_rsa.rb
deleted file mode 100644
index 401cb6c3e0..0000000000
--- a/test/openssl/test_pkey_rsa.rb
+++ /dev/null
@@ -1,49 +0,0 @@
-begin
- require "openssl"
- require File.join(File.dirname(__FILE__), "utils.rb")
-rescue LoadError
-end
-require 'test/unit'
-
-if defined?(OpenSSL)
-
-class OpenSSL::TestPKeyRSA < Test::Unit::TestCase
- def test_padding
- key = OpenSSL::PKey::RSA.new(512, 3)
-
- # Need right size for raw mode
- plain0 = "x" * (512/8)
- cipher = key.private_encrypt(plain0, OpenSSL::PKey::RSA::NO_PADDING)
- plain1 = key.public_decrypt(cipher, OpenSSL::PKey::RSA::NO_PADDING)
- assert_equal(plain0, plain1)
-
- # Need smaller size for pkcs1 mode
- plain0 = "x" * (512/8 - 11)
- cipher1 = key.private_encrypt(plain0, OpenSSL::PKey::RSA::PKCS1_PADDING)
- plain1 = key.public_decrypt(cipher1, OpenSSL::PKey::RSA::PKCS1_PADDING)
- assert_equal(plain0, plain1)
-
- cipherdef = key.private_encrypt(plain0) # PKCS1_PADDING is default
- plain1 = key.public_decrypt(cipherdef)
- assert_equal(plain0, plain1)
- assert_equal(cipher1, cipherdef)
-
- # Failure cases
- assert_raise(ArgumentError){ key.private_encrypt() }
- assert_raise(ArgumentError){ key.private_encrypt("hi", 1, nil) }
- assert_raise(OpenSSL::PKey::RSAError){ key.private_encrypt(plain0, 666) }
- end
-
- def test_private
- key = OpenSSL::PKey::RSA.new(512, 3)
- assert(key.private?)
- key2 = OpenSSL::PKey::RSA.new(key.to_der)
- assert(key2.private?)
- key3 = key.public_key
- assert(!key3.private?)
- key4 = OpenSSL::PKey::RSA.new(key3.to_der)
- assert(!key4.private?)
- end
-end
-
-end
diff --git a/test/openssl/test_ssl.rb b/test/openssl/test_ssl.rb
index e80f32f234..5ca981798c 100644
--- a/test/openssl/test_ssl.rb
+++ b/test/openssl/test_ssl.rb
@@ -54,27 +54,23 @@ class OpenSSL::TestSSL < Test::Unit::TestCase
OpenSSL::TestUtils.issue_crl(*arg)
end
- def start_server(port0, verify_mode, start_immediately, &block)
+ def start_server(port, verify_mode, start_immediately, &block)
server = nil
begin
cmd = [RUBY]
cmd << "-d" if $DEBUG
- cmd << SSL_SERVER << port0.to_s << verify_mode.to_s
+ cmd << SSL_SERVER << port.to_s << verify_mode.to_s
cmd << (start_immediately ? "yes" : "no")
server = IO.popen(cmd.join(" "), "w+")
server.write(@ca_cert.to_pem)
server.write(@svr_cert.to_pem)
server.write(@svr_key.to_pem)
pid = Integer(server.gets)
- if port = server.gets
- if $DEBUG
- $stderr.printf("%s started: pid=%d port=%d\n", SSL_SERVER, pid, port)
- end
- block.call(server, port.to_i)
- end
+ $stderr.printf("%s started: pid=%d\n", SSL_SERVER, pid) if $DEBUG
+ block.call(server)
ensure
if server
- Process.kill(:KILL, pid)
+ Process.kill(:KILL, pid) if pid > 0
server.close
end
end
@@ -90,15 +86,15 @@ class OpenSSL::TestSSL < Test::Unit::TestCase
end
def test_connect_and_close
- start_server(PORT, OpenSSL::SSL::VERIFY_NONE, true){|s, p|
- sock = TCPSocket.new("127.0.0.1", p)
+ start_server(PORT, OpenSSL::SSL::VERIFY_NONE, true){
+ sock = TCPSocket.new("127.0.0.1", PORT)
ssl = OpenSSL::SSL::SSLSocket.new(sock)
assert(ssl.connect)
ssl.close
assert(!sock.closed?)
sock.close
- sock = TCPSocket.new("127.0.0.1", p)
+ sock = TCPSocket.new("127.0.0.1", PORT)
ssl = OpenSSL::SSL::SSLSocket.new(sock)
ssl.sync_close = true # !!
assert(ssl.connect)
@@ -108,8 +104,8 @@ class OpenSSL::TestSSL < Test::Unit::TestCase
end
def test_read_and_write
- start_server(PORT, OpenSSL::SSL::VERIFY_NONE, true){|s, p|
- sock = TCPSocket.new("127.0.0.1", p)
+ start_server(PORT, OpenSSL::SSL::VERIFY_NONE, true){
+ sock = TCPSocket.new("127.0.0.1", PORT)
ssl = OpenSSL::SSL::SSLSocket.new(sock)
ssl.sync_close = true
ssl.connect
@@ -151,46 +147,9 @@ class OpenSSL::TestSSL < Test::Unit::TestCase
}
end
- def test_client_auth
- vflag = OpenSSL::SSL::VERIFY_PEER|OpenSSL::SSL::VERIFY_FAIL_IF_NO_PEER_CERT
- start_server(PORT, vflag, true){|s, p|
- assert_raises(OpenSSL::SSL::SSLError){
- sock = TCPSocket.new("127.0.0.1", p)
- ssl = OpenSSL::SSL::SSLSocket.new(sock)
- ssl.connect
- }
-
- ctx = OpenSSL::SSL::SSLContext.new
- ctx.key = @cli_key
- ctx.cert = @cli_cert
- sock = TCPSocket.new("127.0.0.1", p)
- ssl = OpenSSL::SSL::SSLSocket.new(sock, ctx)
- ssl.sync_close = true
- ssl.connect
- ssl.puts("foo")
- assert_equal("foo\n", ssl.gets)
- ssl.close
-
- called = nil
- ctx = OpenSSL::SSL::SSLContext.new
- ctx.client_cert_cb = Proc.new{|ssl|
- called = true
- [@cli_cert, @cli_key]
- }
- sock = TCPSocket.new("127.0.0.1", p)
- ssl = OpenSSL::SSL::SSLSocket.new(sock, ctx)
- ssl.sync_close = true
- ssl.connect
- assert(called)
- ssl.puts("foo")
- assert_equal("foo\n", ssl.gets)
- ssl.close
- }
- end
-
def test_starttls
- start_server(PORT, OpenSSL::SSL::VERIFY_NONE, false){|s, p|
- sock = TCPSocket.new("127.0.0.1", p)
+ start_server(PORT, OpenSSL::SSL::VERIFY_NONE, false){|s|
+ sock = TCPSocket.new("127.0.0.1", PORT)
ssl = OpenSSL::SSL::SSLSocket.new(sock)
ssl.sync_close = true
str = "x" * 1000 + "\n"
@@ -212,10 +171,10 @@ class OpenSSL::TestSSL < Test::Unit::TestCase
end
def test_parallel
- start_server(PORT, OpenSSL::SSL::VERIFY_NONE, true){|s, p|
+ start_server(PORT, OpenSSL::SSL::VERIFY_NONE, true){
ssls = []
10.times{
- sock = TCPSocket.new("127.0.0.1", p)
+ sock = TCPSocket.new("127.0.0.1", PORT)
ssl = OpenSSL::SSL::SSLSocket.new(sock)
ssl.connect
ssl.sync_close = true
@@ -231,55 +190,6 @@ class OpenSSL::TestSSL < Test::Unit::TestCase
ssls.each{|ssl| ssl.close }
}
end
-
- def test_post_connection_check
- sslerr = OpenSSL::SSL::SSLError
-
- start_server(PORT, OpenSSL::SSL::VERIFY_NONE, true){|s, p|
- sock = TCPSocket.new("127.0.0.1", p)
- ssl = OpenSSL::SSL::SSLSocket.new(sock)
- ssl.connect
- assert_raises(sslerr){ssl.post_connection_check("localhost.localdomain")}
- assert_raises(sslerr){ssl.post_connection_check("127.0.0.1")}
- assert(ssl.post_connection_check("localhost"))
- assert_raises(sslerr){ssl.post_connection_check("foo.example.com")}
- }
-
- now = Time.now
- exts = [
- ["keyUsage","keyEncipherment,digitalSignature",true],
- ["subjectAltName","DNS:localhost.localdomain",false],
- ["subjectAltName","IP:127.0.0.1",false],
- ]
- @svr_cert = issue_cert(@svr, @svr_key, 4, now, now+1800, exts,
- @ca_cert, @ca_key, OpenSSL::Digest::SHA1.new)
- start_server(PORT, OpenSSL::SSL::VERIFY_NONE, true){|s, p|
- sock = TCPSocket.new("127.0.0.1", p)
- ssl = OpenSSL::SSL::SSLSocket.new(sock)
- ssl.connect
- assert(ssl.post_connection_check("localhost.localdomain"))
- assert(ssl.post_connection_check("127.0.0.1"))
- assert_raises(sslerr){ssl.post_connection_check("localhost")}
- assert_raises(sslerr){ssl.post_connection_check("foo.example.com")}
- }
-
- now = Time.now
- exts = [
- ["keyUsage","keyEncipherment,digitalSignature",true],
- ["subjectAltName","DNS:*.localdomain",false],
- ]
- @svr_cert = issue_cert(@svr, @svr_key, 5, now, now+1800, exts,
- @ca_cert, @ca_key, OpenSSL::Digest::SHA1.new)
- start_server(PORT, OpenSSL::SSL::VERIFY_NONE, true){|s, p|
- sock = TCPSocket.new("127.0.0.1", p)
- ssl = OpenSSL::SSL::SSLSocket.new(sock)
- ssl.connect
- assert(ssl.post_connection_check("localhost.localdomain"))
- assert_raises(sslerr){ssl.post_connection_check("127.0.0.1")}
- assert_raises(sslerr){ssl.post_connection_check("localhost")}
- assert_raises(sslerr){ssl.post_connection_check("foo.example.com")}
- }
- end
end
end
diff --git a/test/openssl/test_x509name.rb b/test/openssl/test_x509name.rb
index fb5a1ae4ff..14004a4e20 100644
--- a/test/openssl/test_x509name.rb
+++ b/test/openssl/test_x509name.rb
@@ -7,11 +7,6 @@ require "test/unit"
if defined?(OpenSSL)
class OpenSSL::TestX509Name < Test::Unit::TestCase
- OpenSSL::ASN1::ObjectId.register(
- "1.2.840.113549.1.9.1", "emailAddress", "emailAddress")
- OpenSSL::ASN1::ObjectId.register(
- "2.5.4.5", "serialNumber", "serialNumber")
-
def setup
@obj_type_tmpl = Hash.new(OpenSSL::ASN1::PRINTABLESTRING)
@obj_type_tmpl.update(OpenSSL::X509::Name::OBJECT_TYPE_TEMPLATE)
@@ -81,12 +76,21 @@ class OpenSSL::TestX509Name < Test::Unit::TestCase
]
name = OpenSSL::X509::Name.new(dn)
ary = name.to_a
- assert_equal("/DC=org/DC=ruby-lang/CN=GOTOU Yuuzou/emailAddress=gotoyuzo@ruby-lang.org/serialNumber=123", name.to_s)
+ if OpenSSL::OPENSSL_VERSION_NUMBER < 0x00907000
+ assert_equal("/DC=org/DC=ruby-lang/CN=GOTOU Yuuzou/Email=gotoyuzo@ruby-lang.org/SN=123", name.to_s)
+ else
+ assert_equal("/DC=org/DC=ruby-lang/CN=GOTOU Yuuzou/emailAddress=gotoyuzo@ruby-lang.org/serialNumber=123", name.to_s)
+ end
assert_equal("DC", ary[0][0])
assert_equal("DC", ary[1][0])
assert_equal("CN", ary[2][0])
- assert_equal("emailAddress", ary[3][0])
- assert_equal("serialNumber", ary[4][0])
+ if OpenSSL::OPENSSL_VERSION_NUMBER < 0x00907000
+ assert_equal("Email", ary[3][0])
+ assert_equal("SN", ary[4][0])
+ else
+ assert_equal("emailAddress", ary[3][0])
+ assert_equal("serialNumber", ary[4][0])
+ end
assert_equal("org", ary[0][1])
assert_equal("ruby-lang", ary[1][1])
assert_equal("GOTOU Yuuzou", ary[2][1])
@@ -134,105 +138,6 @@ class OpenSSL::TestX509Name < Test::Unit::TestCase
assert_equal(OpenSSL::ASN1::PRINTABLESTRING, ary[2][2])
end
- def test_s_parse_rfc2253
- scanner = OpenSSL::X509::Name::RFC2253DN.method(:scan)
-
- assert_equal([["C", "JP"]], scanner.call("C=JP"))
- assert_equal([
- ["DC", "org"],
- ["DC", "ruby-lang"],
- ["CN", "GOTOU Yuuzou"],
- ["emailAddress", "gotoyuzo@ruby-lang.org"],
- ],
- scanner.call(
- "emailAddress=gotoyuzo@ruby-lang.org,CN=GOTOU Yuuzou,"+
- "DC=ruby-lang,DC=org")
- )
-
- u8 = OpenSSL::ASN1::UTF8STRING
- assert_equal([
- ["DC", "org"],
- ["DC", "ruby-lang"],
- ["O", ",=+<>#;"],
- ["O", ",=+<>#;"],
- ["OU", ""],
- ["OU", ""],
- ["L", "aaa=\"bbb, ccc\""],
- ["L", "aaa=\"bbb, ccc\""],
- ["CN", "\345\276\214\350\227\244\350\243\225\350\224\265"],
- ["CN", "\345\276\214\350\227\244\350\243\225\350\224\265"],
- ["CN", "\345\276\214\350\227\244\350\243\225\350\224\265"],
- ["CN", "\345\276\214\350\227\244\350\243\225\350\224\265", u8],
- ["2.5.4.3", "GOTOU, Yuuzou"],
- ["2.5.4.3", "GOTOU, Yuuzou"],
- ["2.5.4.3", "GOTOU, Yuuzou"],
- ["2.5.4.3", "GOTOU, Yuuzou"],
- ["CN", "GOTOU \"gotoyuzo\" Yuuzou"],
- ["CN", "GOTOU \"gotoyuzo\" Yuuzou"],
- ["1.2.840.113549.1.9.1", "gotoyuzo@ruby-lang.org"],
- ["emailAddress", "gotoyuzo@ruby-lang.org"],
- ],
- scanner.call(
- "emailAddress=gotoyuzo@ruby-lang.org," +
- "1.2.840.113549.1.9.1=gotoyuzo@ruby-lang.org," +
- 'CN=GOTOU \"gotoyuzo\" Yuuzou,' +
- 'CN="GOTOU \"gotoyuzo\" Yuuzou",' +
- '2.5.4.3=GOTOU\,\20Yuuzou,' +
- '2.5.4.3=GOTOU\, Yuuzou,' +
- '2.5.4.3="GOTOU, Yuuzou",' +
- '2.5.4.3="GOTOU\, Yuuzou",' +
- "CN=#0C0CE5BE8CE897A4E8A395E894B5," +
- 'CN=\E5\BE\8C\E8\97\A4\E8\A3\95\E8\94\B5,' +
- "CN=\"\xE5\xBE\x8C\xE8\x97\xA4\xE8\xA3\x95\xE8\x94\xB5\"," +
- "CN=\xE5\xBE\x8C\xE8\x97\xA4\xE8\xA3\x95\xE8\x94\xB5," +
- 'L=aaa\=\"bbb\, ccc\",' +
- 'L="aaa=\"bbb, ccc\"",' +
- 'OU=,' +
- 'OU="",' +
- 'O=\,\=\+\<\>\#\;,' +
- 'O=",=+<>#;",' +
- "DC=ruby-lang," +
- "DC=org")
- )
-
- [
- "DC=org+DC=jp",
- "DC=org,DC=ruby-lang+DC=rubyist,DC=www"
- ].each{|dn|
- ex = scanner.call(dn) rescue $!
- dn_r = Regexp.escape(dn)
- assert_match(/^multi-valued RDN is not supported: #{dn_r}/, ex.message)
- }
-
- [
- ["DC=org,DC=exapmle,CN", "CN"],
- ["DC=org,DC=example,", ""],
- ["DC=org,DC=exapmle,CN=www.example.org;", "CN=www.example.org;"],
- ["DC=org,DC=exapmle,CN=#www.example.org", "CN=#www.example.org"],
- ["DC=org,DC=exapmle,CN=#777777.example.org", "CN=#777777.example.org"],
- ["DC=org,DC=exapmle,CN=\"www.example\".org", "CN=\"www.example\".org"],
- ["DC=org,DC=exapmle,CN=www.\"example.org\"", "CN=www.\"example.org\""],
- ["DC=org,DC=exapmle,CN=www.\"example\".org", "CN=www.\"example\".org"],
- ].each{|dn, msg|
- ex = scanner.call(dn) rescue $!
- assert_match(/^malformed RDN: .*=>#{Regexp.escape(msg)}/, ex.message)
- }
-
- dn = "CN=www.ruby-lang.org,DC=ruby-lang,DC=org"
- name = OpenSSL::X509::Name.parse_rfc2253(dn)
- assert_equal(dn, name.to_s(OpenSSL::X509::Name::RFC2253))
- ary = name.to_a
- assert_equal("DC", ary[0][0])
- assert_equal("DC", ary[1][0])
- assert_equal("CN", ary[2][0])
- assert_equal("org", ary[0][1])
- assert_equal("ruby-lang", ary[1][1])
- assert_equal("www.ruby-lang.org", ary[2][1])
- assert_equal(OpenSSL::ASN1::IA5STRING, ary[0][2])
- assert_equal(OpenSSL::ASN1::IA5STRING, ary[1][2])
- assert_equal(OpenSSL::ASN1::UTF8STRING, ary[2][2])
- end
-
def test_add_entry
dn = [
["DC", "org"],
@@ -244,12 +149,21 @@ class OpenSSL::TestX509Name < Test::Unit::TestCase
name = OpenSSL::X509::Name.new
dn.each{|attr| name.add_entry(*attr) }
ary = name.to_a
- assert_equal("/DC=org/DC=ruby-lang/CN=GOTOU Yuuzou/emailAddress=gotoyuzo@ruby-lang.org/serialNumber=123", name.to_s)
+ if OpenSSL::OPENSSL_VERSION_NUMBER < 0x00907000
+ assert_equal("/DC=org/DC=ruby-lang/CN=GOTOU Yuuzou/Email=gotoyuzo@ruby-lang.org/SN=123", name.to_s)
+ else
+ assert_equal("/DC=org/DC=ruby-lang/CN=GOTOU Yuuzou/emailAddress=gotoyuzo@ruby-lang.org/serialNumber=123", name.to_s)
+ end
assert_equal("DC", ary[0][0])
assert_equal("DC", ary[1][0])
assert_equal("CN", ary[2][0])
- assert_equal("emailAddress", ary[3][0])
- assert_equal("serialNumber", ary[4][0])
+ if OpenSSL::OPENSSL_VERSION_NUMBER < 0x00907000
+ assert_equal("Email", ary[3][0])
+ assert_equal("SN", ary[4][0])
+ else
+ assert_equal("emailAddress", ary[3][0])
+ assert_equal("serialNumber", ary[4][0])
+ end
assert_equal("org", ary[0][1])
assert_equal("ruby-lang", ary[1][1])
assert_equal("GOTOU Yuuzou", ary[2][1])
diff --git a/test/openssl/test_x509store.rb b/test/openssl/test_x509store.rb
index b0fe597262..113e81fa52 100644
--- a/test/openssl/test_x509store.rb
+++ b/test/openssl/test_x509store.rb
@@ -49,8 +49,6 @@ class OpenSSL::TestX509Store < Test::Unit::TestCase
ca2_cert, @rsa1024, OpenSSL::Digest::SHA1.new)
ee3_cert = issue_cert(@ee2, @dsa512, 30, now-100, now-1, ee_exts,
ca2_cert, @rsa1024, OpenSSL::Digest::SHA1.new)
- ee4_cert = issue_cert(@ee2, @dsa512, 40, now+1000, now+2000, ee_exts,
- ca2_cert, @rsa1024, OpenSSL::Digest::SHA1.new)
revoke_info = []
crl1 = issue_crl(revoke_info, 1, now, now+1800, [],
@@ -61,9 +59,6 @@ class OpenSSL::TestX509Store < Test::Unit::TestCase
revoke_info = [ [20, now, 1], ]
crl2 = issue_crl(revoke_info, 1, now, now+1800, [],
ca2_cert, @rsa1024, OpenSSL::Digest::SHA1.new)
- revoke_info = []
- crl2_2 = issue_crl(revoke_info, 2, now-100, now-1, [],
- ca2_cert, @rsa1024, OpenSSL::Digest::SHA1.new)
assert(true, ca1_cert.verify(ca1_cert.public_key)) # self signed
assert(true, ca2_cert.verify(ca1_cert.public_key)) # issued by ca1
@@ -73,7 +68,6 @@ class OpenSSL::TestX509Store < Test::Unit::TestCase
assert(true, crl1.verify(ca1_cert.public_key)) # issued by ca1
assert(true, crl1_2.verify(ca1_cert.public_key)) # issued by ca1
assert(true, crl2.verify(ca2_cert.public_key)) # issued by ca2
- assert(true, crl2_2.verify(ca2_cert.public_key)) # issued by ca2
store = OpenSSL::X509::Store.new
assert_equal(false, store.verify(ca1_cert))
@@ -111,39 +105,7 @@ class OpenSSL::TestX509Store < Test::Unit::TestCase
assert_equal(@ca2.to_der, chain[1].subject.to_der)
assert_equal(@ca1.to_der, chain[2].subject.to_der)
assert_equal(false, store.verify(ee3_cert))
- assert_equal(OpenSSL::X509::V_ERR_CERT_HAS_EXPIRED, store.error)
assert_match(/expire/i, store.error_string)
- assert_equal(false, store.verify(ee4_cert))
- assert_equal(OpenSSL::X509::V_ERR_CERT_NOT_YET_VALID, store.error)
- assert_match(/not yet valid/i, store.error_string)
-
- store = OpenSSL::X509::Store.new
- store.add_cert(ca1_cert)
- store.add_cert(ca2_cert)
- store.time = now + 1500
- assert_equal(true, store.verify(ca1_cert))
- assert_equal(true, store.verify(ca2_cert))
- assert_equal(true, store.verify(ee4_cert))
- store.time = now + 1900
- assert_equal(true, store.verify(ca1_cert))
- assert_equal(false, store.verify(ca2_cert))
- assert_equal(OpenSSL::X509::V_ERR_CERT_HAS_EXPIRED, store.error)
- assert_equal(false, store.verify(ee4_cert))
- assert_equal(OpenSSL::X509::V_ERR_CERT_HAS_EXPIRED, store.error)
- store.time = now + 4000
- assert_equal(false, store.verify(ee1_cert))
- assert_equal(OpenSSL::X509::V_ERR_CERT_HAS_EXPIRED, store.error)
- assert_equal(false, store.verify(ee4_cert))
- assert_equal(OpenSSL::X509::V_ERR_CERT_HAS_EXPIRED, store.error)
-
- # the underlying X509 struct caches the result of the last
- # verification for signature and not-before. so the following code
- # rebuilds new objects to avoid site effect.
- store.time = Time.now - 4000
- assert_equal(false, store.verify(OpenSSL::X509::Certificate.new(ca2_cert)))
- assert_equal(OpenSSL::X509::V_ERR_CERT_NOT_YET_VALID, store.error)
- assert_equal(false, store.verify(OpenSSL::X509::Certificate.new(ee1_cert)))
- assert_equal(OpenSSL::X509::V_ERR_CERT_NOT_YET_VALID, store.error)
return unless defined?(OpenSSL::X509::V_FLAG_CRL_CHECK)
@@ -166,8 +128,7 @@ class OpenSSL::TestX509Store < Test::Unit::TestCase
store.add_crl(crl2) # revoke ee2_cert
assert_equal(true, store.verify(ca1_cert))
assert_equal(false, store.verify(ca2_cert))
- assert_equal(true, store.verify(ee1_cert, [ca2_cert]),
- "This test is expected to be success with OpenSSL 0.9.7c or later.")
+ assert_equal(true, store.verify(ee1_cert, [ca2_cert]))
assert_equal(false, store.verify(ee2_cert, [ca2_cert]))
store.flags =
@@ -176,42 +137,6 @@ class OpenSSL::TestX509Store < Test::Unit::TestCase
assert_equal(false, store.verify(ca2_cert))
assert_equal(false, store.verify(ee1_cert, [ca2_cert]))
assert_equal(false, store.verify(ee2_cert, [ca2_cert]))
-
- store = OpenSSL::X509::Store.new
- store.purpose = OpenSSL::X509::PURPOSE_ANY
- store.flags =
- OpenSSL::X509::V_FLAG_CRL_CHECK|OpenSSL::X509::V_FLAG_CRL_CHECK_ALL
- store.add_cert(ca1_cert)
- store.add_cert(ca2_cert)
- store.add_crl(crl1)
- store.add_crl(crl2_2) # issued by ca2 but expired.
- assert_equal(true, store.verify(ca1_cert))
- assert_equal(true, store.verify(ca2_cert))
- assert_equal(false, store.verify(ee1_cert))
- assert_equal(OpenSSL::X509::V_ERR_CRL_HAS_EXPIRED, store.error)
- assert_equal(false, store.verify(ee2_cert))
- end
-
- def test_set_errors
- now = Time.now
- ca1_cert = issue_cert(@ca1, @rsa2048, 1, now, now+3600, [],
- nil, nil, OpenSSL::Digest::SHA1.new)
- store = OpenSSL::X509::Store.new
- store.add_cert(ca1_cert)
- assert_raises(OpenSSL::X509::StoreError){
- store.add_cert(ca1_cert) # add same certificate twice
- }
-
- revoke_info = []
- crl1 = issue_crl(revoke_info, 1, now, now+1800, [],
- ca1_cert, @rsa2048, OpenSSL::Digest::SHA1.new)
- revoke_info = [ [2, now, 1], ]
- crl2 = issue_crl(revoke_info, 2, now+1800, now+3600, [],
- ca1_cert, @rsa2048, OpenSSL::Digest::SHA1.new)
- store.add_crl(crl1)
- assert_raises(OpenSSL::X509::StoreError){
- store.add_crl(crl2) # add CRL issued by same CA twice.
- }
end
end
diff --git a/test/optparse/test_noarg.rb b/test/optparse/test_noarg.rb
index 28c469093d..cd57ed5a56 100644
--- a/test/optparse/test_noarg.rb
+++ b/test/optparse/test_noarg.rb
@@ -31,8 +31,8 @@ module TestOptionParser::NoArg
assert_equal(%w"", no_error {@opt.parse!(%w"-o")})
assert_equal(true, @flag)
@flag = nil
- assert_raises(OptionParser::InvalidOption) {@opt.parse!(%w"-O")}
- assert_nil(@flag)
+ no_error {@opt.parse!(%w"-O")}
+ assert_equal(true, @flag)
@flag = nil
assert_equal(%w"foo", no_error {@opt.parse!(%w"-o foo")})
assert_equal(true, @flag)
diff --git a/test/readline/test_readline.rb b/test/readline/test_readline.rb
deleted file mode 100644
index edc3aa09b9..0000000000
--- a/test/readline/test_readline.rb
+++ /dev/null
@@ -1,84 +0,0 @@
-begin
- require "readline"
-rescue LoadError
-end
-
-if defined?(Readline) && !/EditLine/n.match(Readline::VERSION)
-
-require "test/unit"
-require "tempfile"
-
-class TestReadline < Test::Unit::TestCase
- def test_readline
- stdin = Tempfile.new("test_readline_stdin")
- stdout = Tempfile.new("test_readline_stdout")
- begin
- stdin.write("hello\n")
- stdin.close
- stdout.close
- line = replace_stdio(stdin.path, stdout.path) {
- Readline.readline("> ", true)
- }
- assert_equal("hello", line)
- assert_equal(true, line.tainted?)
- stdout.open
- assert_equal("> ", stdout.read(2))
- assert_equal(1, Readline::HISTORY.length)
- assert_equal("hello", Readline::HISTORY[0])
- assert_raises(SecurityError) do
- Thread.start {
- $SAFE = 1
- replace_stdio(stdin.path, stdout.path) do
- Readline.readline("> ".taint)
- end
- }.join
- end
- assert_raises(SecurityError) do
- Thread.start {
- $SAFE = 4
- replace_stdio(stdin.path, stdout.path) { Readline.readline("> ") }
- }.join
- end
- ensure
- stdin.close(true)
- stdout.close(true)
- end
- end
-
- def test_completion_append_character
- begin
- Readline.completion_append_character = "x"
- assert_equal("x", Readline.completion_append_character)
- Readline.completion_append_character = "xyz"
- assert_equal("x", Readline.completion_append_character)
- Readline.completion_append_character = nil
- assert_equal(nil, Readline.completion_append_character)
- Readline.completion_append_character = ""
- assert_equal(nil, Readline.completion_append_character)
- rescue NotImplementedError
- end
- end
-
- private
-
- def replace_stdio(stdin_path, stdout_path)
- open(stdin_path, "r"){|stdin|
- open(stdout_path, "w"){|stdout|
- orig_stdin = STDIN.dup
- orig_stdout = STDOUT.dup
- STDIN.reopen(stdin)
- STDOUT.reopen(stdout)
- begin
- yield
- ensure
- STDIN.reopen(orig_stdin)
- STDOUT.reopen(orig_stdout)
- orig_stdin.close
- orig_stdout.close
- end
- }
- }
- end
-end
-
-end
diff --git a/test/rinda/test_rinda.rb b/test/rinda/test_rinda.rb
index d663e0446d..28e455ef85 100644
--- a/test/rinda/test_rinda.rb
+++ b/test/rinda/test_rinda.rb
@@ -4,118 +4,9 @@ require 'drb/drb'
require 'drb/eq'
require 'rinda/tuplespace'
-require 'singleton'
-
module Rinda
-class MockClock
- include Singleton
-
- class MyTS < Rinda::TupleSpace
- def keeper
- nil
- end
- end
-
- def initialize
- @now = 2
- @reso = 0.1
- @ts = MyTS.new
- @ts.write([2, :now])
- @inf = 2**31 - 1
- end
-
- def now
- @now.to_f
- end
-
- def at(n)
- n
- end
-
- def _forward(n=nil)
- now ,= @ts.take([nil, :now])
- @now = now + n
- n = @reso if n.nil?
- @ts.write([@now, :now])
- end
-
- def forward(n=nil)
- while n > 0
- _forward(@reso)
- n -= @reso
- end
- end
-
- def rewind
- now ,= @ts.take([nil, :now])
- @ts.write([@inf, :now])
- @ts.take([nil, :now])
- @now = 2
- @ts.write([2, :now])
- end
-
- def sleep(n=nil)
- while will_deadlock?
- n -= @reso
- forward
- return 0 if n <= 0
- end
- now ,= @ts.read([nil, :now])
- @ts.read([(now + n)..@inf, :now])
- 0
- end
-
- def will_deadlock?
- sz = Thread.current.group.list.find_all {|x| x.status != 'sleep'}.size
- sz <= 1
- end
-end
-
-module Time
- def sleep(n)
- @m.sleep(n)
- end
- module_function :sleep
-
- def at(n)
- n
- end
- module_function :at
-
- def now
- @m ? @m.now : 2
- end
- module_function :now
-
- def rewind
- @m.rewind
- end
- module_function :rewind
-
- def forward(n)
- @m.forward(n)
- end
- module_function :forward
-
- @m = MockClock.instance
-end
-
-class TupleSpace
- def sleep(n)
- Time.sleep(n)
- end
-end
-
module TupleSpaceTestModule
- def sleep(n)
- if Thread.current == Thread.main
- Time.forward(n)
- else
- Time.sleep(n)
- end
- end
-
def test_00_tuple
tuple = Rinda::TupleEntry.new([1,2,3])
assert(!tuple.canceled?)
@@ -214,19 +105,19 @@ module TupleSpaceTestModule
tmpl = Rinda::DRbObjectTemplate.new(/^druby:\/\/host:/)
assert(tmpl === ro)
- ro = DRbObject.new_with(12345, 1234)
+ ro.reinit(12345, 1234)
assert(!(tmpl === ro))
- ro = DRbObject.new_with("druby://foo:12345", 1234)
+ ro.reinit("druby://foo:12345", 1234)
assert(!(tmpl === ro))
tmpl = Rinda::DRbObjectTemplate.new(/^druby:\/\/(foo|bar):/)
assert(tmpl === ro)
- ro = DRbObject.new_with("druby://bar:12345", 1234)
+ ro.reinit("druby://bar:12345", 1234)
assert(tmpl === ro)
- ro = DRbObject.new_with("druby://baz:12345", 1234)
+ ro.reinit("druby://baz:12345", 1234)
assert(!(tmpl === ro))
end
@@ -262,9 +153,8 @@ module TupleSpaceTestModule
@ts.write([:ans, s])
s
end
-
- sleep(20)
- tuple = @ts.take([:ans, nil])
+
+ tuple = @ts.take([:ans, nil], 20)
assert_equal(10, tuple[1])
assert_equal(10, taker.value)
end
@@ -289,8 +179,7 @@ module TupleSpaceTestModule
@ts.write([:req, 2])
end
- sleep(20)
- tuple = @ts.take([:ans, nil])
+ tuple = @ts.take([:ans, nil], 20)
assert_equal(10, tuple[1])
assert_equal(10, taker.value)
assert_equal([], @ts.read_all([nil, nil]))
@@ -368,8 +257,7 @@ module TupleSpaceTestModule
@ts.take({"message"=>"first", "name"=>"3"})
- sleep(4)
- tuple = @ts.take([:ans, nil])
+ tuple = @ts.take([:ans, nil], 20)
assert_equal(10, tuple[1])
assert_equal(10, taker.value)
assert_equal([], @ts.read_all([nil, nil]))
@@ -411,7 +299,7 @@ module TupleSpaceTestModule
end
end
- sleep(1)
+ sleep 1
assert(template.canceled?)
@ts.write([:take, 1])
@@ -438,8 +326,8 @@ module TupleSpaceTestModule
end
end
end
-
- sleep(1)
+
+ sleep 1
assert(template.canceled?)
@ts.write([:take, 1])
@@ -496,7 +384,6 @@ class TupleSpaceTest < Test::Unit::TestCase
include TupleSpaceTestModule
def setup
- ThreadGroup.new.add(Thread.current)
@ts = Rinda::TupleSpace.new(1)
end
end
@@ -505,19 +392,10 @@ class TupleSpaceProxyTest < Test::Unit::TestCase
include TupleSpaceTestModule
def setup
- ThreadGroup.new.add(Thread.current)
@ts_base = Rinda::TupleSpace.new(1)
@ts = Rinda::TupleSpaceProxy.new(@ts_base)
end
- def test_remote_array_and_hash
- @ts.write(DRbObject.new([1, 2, 3]))
- assert_equal([1, 2, 3], @ts.take([1, 2, 3], 0))
- @ts.write(DRbObject.new({'head' => 1, 'tail' => 2}))
- assert_equal({'head' => 1, 'tail' => 2},
- @ts.take({'head' => 1, 'tail' => 2}, 0))
- end
-
@server = DRb.primary_server || DRb.start_service
end
diff --git a/test/rss/rss-assertions.rb b/test/rss/rss-assertions.rb
index 2636062519..6b83cbe093 100644
--- a/test/rss/rss-assertions.rb
+++ b/test/rss/rss-assertions.rb
@@ -94,44 +94,27 @@ module RSS
end
end
end
-
- def assert_not_set_error(name, variables)
- _wrap_assertion do
- begin
- yield
- flunk("Not raise NotSetError")
- rescue ::RSS::NotSetError => e
- assert_equal(name, e.name)
- assert_equal(variables.sort, e.variables.sort)
- end
- end
- end
-
- def assert_xml_declaration(version, encoding, standalone, rss)
- _wrap_assertion do
- assert_equal(version, rss.version)
- assert_equal(encoding, rss.encoding)
- assert_equal(standalone, rss.standalone)
- end
- end
- def assert_xml_stylesheet_attrs(attrs, xsl)
+ def assert_xml_stylesheet_attrs(xsl, attrs)
_wrap_assertion do
- n_attrs = normalized_attrs(attrs)
+ normalized_attrs = {}
+ attrs.each do |name, value|
+ normalized_attrs[name.to_s] = value
+ end
::RSS::XMLStyleSheet::ATTRIBUTES.each do |name|
- assert_equal(n_attrs[name], xsl.send(name))
+ assert_equal(normalized_attrs[name], xsl.send(name))
end
end
end
- def assert_xml_stylesheet(target, attrs, xsl)
+ def assert_xml_stylesheet(target, xsl, attrs)
_wrap_assertion do
if attrs.has_key?(:href)
if !attrs.has_key?(:type) and attrs.has_key?(:guess_type)
attrs[:type] = attrs[:guess_type]
end
assert_equal("xml-stylesheet", target)
- assert_xml_stylesheet_attrs(attrs, xsl)
+ assert_xml_stylesheet_attrs(xsl, attrs)
else
assert_nil(target)
assert_equal("", xsl.to_s)
@@ -140,323 +123,39 @@ module RSS
end
def assert_xml_stylesheet_pis(attrs_ary)
- _wrap_assertion do
- rdf = ::RSS::RDF.new()
- xss_strs = []
- attrs_ary.each do |attrs|
- xss = ::RSS::XMLStyleSheet.new(*attrs)
- xss_strs.push(xss.to_s)
- rdf.xml_stylesheets.push(xss)
- end
- pi_str = rdf.to_s.gsub(/<\?xml .*\n/, "").gsub(/\s*<rdf:RDF.*\z/m, "")
- assert_equal(xss_strs.join("\n"), pi_str)
- end
- end
-
- def assert_xml_stylesheets(attrs, xss)
- _wrap_assertion do
- xss.each_with_index do |xs, i|
- assert_xml_stylesheet_attrs(attrs[i], xs)
- end
- end
- end
-
-
- def assert_channel10(attrs, channel)
- _wrap_assertion do
- n_attrs = normalized_attrs(attrs)
-
- names = %w(about title link description)
- assert_attributes(attrs, names, channel)
-
- %w(image items textinput).each do |name|
- value = n_attrs[name]
- if value
- target = channel.__send__(name)
- __send__("assert_channel10_#{name}", value, target)
- end
- end
- end
- end
-
- def assert_channel10_image(attrs, image)
- _wrap_assertion do
- assert_attributes(attrs, %w(resource), image)
- end
- end
-
- def assert_channel10_textinput(attrs, textinput)
- _wrap_assertion do
- assert_attributes(attrs, %w(resource), textinput)
- end
- end
-
- def assert_channel10_items(attrs, items)
- _wrap_assertion do
- items.Seq.lis.each_with_index do |li, i|
- assert_attributes(attrs[i], %w(resource), li)
- end
- end
- end
-
- def assert_image10(attrs, image)
- _wrap_assertion do
- names = %w(about title url link)
- assert_attributes(attrs, names, image)
+ rdf = ::RSS::RDF.new()
+ xss_strs = []
+ attrs_ary.each do |attrs|
+ xss = ::RSS::XMLStyleSheet.new(*attrs)
+ xss_strs.push(xss.to_s)
+ rdf.xml_stylesheets.push(xss)
end
+ pi_str = rdf.to_s.gsub(/<\?xml .*\n/, "").gsub(/\s*<rdf:RDF.*\z/m, "")
+ assert_equal(xss_strs.join("\n"), pi_str)
end
- def assert_items10(attrs, items)
- _wrap_assertion do
- names = %w(about title link description)
- items.each_with_index do |item, i|
- assert_attributes(attrs[i], names, item)
- end
- end
- end
-
- def assert_textinput10(attrs, textinput)
- _wrap_assertion do
- names = %w(about title description name link)
- assert_attributes(attrs, names, textinput)
- end
- end
-
-
- def assert_channel09(attrs, channel)
- _wrap_assertion do
- n_attrs = normalized_attrs(attrs)
-
- names = %w(title description link language rating
- copyright pubDate lastBuildDate docs
- managingEditor webMaster)
- assert_attributes(attrs, names, channel)
-
- %w(skipHours skipDays).each do |name|
- value = n_attrs[name]
- if value
- target = channel.__send__(name)
- __send__("assert_channel09_#{name}", value, target)
- end
- end
- end
- end
-
- def assert_channel09_skipDays(contents, skipDays)
- _wrap_assertion do
- days = skipDays.days
- contents.each_with_index do |content, i|
- assert_equal(content, days[i].content)
- end
- end
- end
-
- def assert_channel09_skipHours(contents, skipHours)
- _wrap_assertion do
- hours = skipHours.hours
- contents.each_with_index do |content, i|
- assert_equal(content, hours[i].content)
- end
- end
- end
-
- def assert_image09(attrs, image)
- _wrap_assertion do
- names = %w(url link title description width height)
- assert_attributes(attrs, names, image)
- end
- end
-
- def assert_items09(attrs, items)
- _wrap_assertion do
- names = %w(title link description)
- items.each_with_index do |item, i|
- assert_attributes(attrs[i], names, item)
- end
- end
- end
-
- def assert_textinput09(attrs, textinput)
- _wrap_assertion do
- names = %w(title description name link)
- assert_attributes(attrs, names, textinput)
- end
- end
-
-
- def assert_channel20(attrs, channel)
- _wrap_assertion do
- n_attrs = normalized_attrs(attrs)
-
- names = %w(title link description language copyright
- managingEditor webMaster pubDate
- lastBuildDate generator docs ttl rating)
- assert_attributes(attrs, names, channel)
-
- %w(cloud categories skipHours skipDays).each do |name|
- value = n_attrs[name]
- if value
- target = channel.__send__(name)
- __send__("assert_channel20_#{name}", value, target)
- end
- end
- end
- end
-
- def assert_channel20_skipDays(contents, skipDays)
- assert_channel09_skipDays(contents, skipDays)
- end
-
- def assert_channel20_skipHours(contents, skipHours)
- assert_channel09_skipHours(contents, skipHours)
- end
-
- def assert_channel20_cloud(attrs, cloud)
- _wrap_assertion do
- names = %w(domain port path registerProcedure protocol)
- assert_attributes(attrs, names, cloud)
- end
- end
-
- def assert_channel20_categories(attrs, categories)
- _wrap_assertion do
- names = %w(domain content)
- categories.each_with_index do |category, i|
- assert_attributes(attrs[i], names, category)
- end
- end
- end
-
- def assert_image20(attrs, image)
- _wrap_assertion do
- names = %w(url link title description width height)
- assert_attributes(attrs, names, image)
- end
- end
-
- def assert_items20(attrs, items)
- _wrap_assertion do
- names = %w(about title link description)
- items.each_with_index do |item, i|
- assert_attributes(attrs[i], names, item)
-
- n_attrs = normalized_attrs(attrs[i])
-
- %w(source enclosure categories guid).each do |name|
- value = n_attrs[name]
- if value
- target = item.__send__(name)
- __send__("assert_items20_#{name}", value, target)
- end
- end
- end
- end
- end
-
- def assert_items20_source(attrs, source)
- _wrap_assertion do
- assert_attributes(attrs, %w(url content), source)
- end
- end
-
- def assert_items20_enclosure(attrs, enclosure)
- _wrap_assertion do
- names = %w(url length type)
- assert_attributes(attrs, names, enclosure)
- end
- end
-
- def assert_items20_categories(attrs, categories)
- _wrap_assertion do
- assert_channel20_categories(attrs, categories)
- end
- end
-
- def assert_items20_guid(attrs, guid)
- _wrap_assertion do
- assert_attributes(attrs, %w(isPermaLink content), guid)
- end
- end
-
- def assert_textinput20(attrs, textinput)
- _wrap_assertion do
- names = %w(title description name link)
- assert_attributes(attrs, names, textinput)
- end
- end
-
-
def assert_dublin_core(elems, target)
- _wrap_assertion do
- elems.each do |name, value|
- assert_equal(value, target.__send__("dc_#{name}"))
- end
- end
- end
-
- def assert_multiple_dublin_core(elems, target)
- _wrap_assertion do
- elems.each do |name, values, plural|
- plural ||= "#{name}s"
- actual = target.__send__("dc_#{plural}").collect{|x| x.value}
- assert_equal(values, actual)
- end
+ elems.each do |name, value|
+ assert_equal(value, target.__send__("dc_#{name}"))
end
end
def assert_syndication(elems, target)
- _wrap_assertion do
- elems.each do |name, value|
- assert_equal(value, target.__send__("sy_#{name}"))
- end
+ elems.each do |name, value|
+ assert_equal(value, target.__send__("sy_#{name}"))
end
end
def assert_content(elems, target)
- _wrap_assertion do
- elems.each do |name, value|
- assert_equal(value, target.__send__("content_#{name}"))
- end
- end
- end
-
- def assert_trackback(attrs, target)
- _wrap_assertion do
- n_attrs = normalized_attrs(attrs)
- if n_attrs["ping"]
- assert_equal(n_attrs["ping"], target.trackback_ping)
- end
- if n_attrs["abouts"]
- n_attrs["abouts"].each_with_index do |about, i|
- assert_equal(about, target.trackback_abouts[i].value)
- end
- end
- end
- end
-
-
- def assert_attributes(attrs, names, target)
- _wrap_assertion do
- n_attrs = normalized_attrs(attrs)
- names.each do |name|
- value = n_attrs[name]
- if value.is_a?(Time)
- actual = target.__send__(name)
- assert_instance_of(Time, actual)
- assert_equal(value.to_i, actual.to_i)
- elsif value
- assert_equal(value, target.__send__(name))
- end
- end
+ elems.each do |name, value|
+ assert_equal(value, target.__send__("content_#{name}"))
end
end
- def normalized_attrs(attrs)
- n_attrs = {}
- attrs.each do |name, value|
- n_attrs[name.to_s] = value
+ def assert_trackback(elems, target)
+ elems.each do |name, value|
+ assert_equal(value, target.__send__("trackback_#{name}"))
end
- n_attrs
end
end
diff --git a/test/rss/rss-testcase.rb b/test/rss/rss-testcase.rb
index f3a2760fd2..27b4eba5d6 100644
--- a/test/rss/rss-testcase.rb
+++ b/test/rss/rss-testcase.rb
@@ -1,11 +1,10 @@
-require "erb"
+# -*- tab-width: 2 -*- vim: ts=2
require "test/unit"
require 'rss-assertions'
module RSS
class TestCase < Test::Unit::TestCase
- include ERB::Util
include RSS
include Assertions
@@ -190,17 +189,6 @@ EOI
EOC
end
- def make_element(elem_name, attrs, contents)
- attrs_str = attrs.collect do |name, value|
- "#{h name}='#{h value}'"
- end.join(" ")
- contents_str = contents.collect do |name, value|
- "#{Element::INDENT}<#{h name}>#{h value}</#{h name}>"
- end.join("\n")
-
- "<#{h elem_name} #{attrs_str}>\n#{contents_str}\n</#{h elem_name}>"
- end
-
private
def setup_dummy_channel(maker)
about = "http://hoge.com"
diff --git a/test/rss/test_1.0.rb b/test/rss/test_1.0.rb
index c37bd84616..e6a81af2bd 100644
--- a/test/rss/test_1.0.rb
+++ b/test/rss/test_1.0.rb
@@ -19,7 +19,7 @@ module RSS
version = "1.0"
encoding = "UTF-8"
- standalone = false
+ standalone = "no"
rdf = RDF.new(version, encoding, standalone)
@@ -27,10 +27,9 @@ module RSS
xmldecl = doc.xml_decl
- %w(version encoding).each do |x|
+ %w(version encoding standalone).each do |x|
assert_equal(instance_eval(x), xmldecl.send(x))
end
- assert_equal(standalone, !xmldecl.standalone.nil?)
assert_equal(@rdf_uri, doc.root.namespace)
diff --git a/test/rss/test_dublincore.rb b/test/rss/test_dublincore.rb
index 5ad9311fb5..d95d31f24e 100644
--- a/test/rss/test_dublincore.rb
+++ b/test/rss/test_dublincore.rb
@@ -54,35 +54,26 @@ EOR
end
def test_parser
+
assert_nothing_raised do
Parser.parse(@rss_source)
end
@elems.each do |tag, value|
- rss = nil
- assert_nothing_raised do
- rss = Parser.parse(make_RDF(<<-EOR, {@prefix => @uri}))
+ assert_too_much_tag(tag.to_s, "channel") do
+ Parser.parse(make_RDF(<<-EOR, {@prefix => @uri}))
#{make_channel(("<" + @prefix + ":" + tag.to_s + ">" +
value.to_s +
"</" + @prefix + ":" + tag.to_s + ">") * 2)}
#{make_item}
EOR
end
- plural_reader = "dc_#{tag}" + (tag == :rights ? "es" : "s")
- values = rss.channel.__send__(plural_reader).collect do |x|
- val = x.value
- if val.kind_of?(String)
- CGI.escapeHTML(val)
- else
- val
- end
- end
- assert_equal([value, value], values)
end
end
-
- def test_singular_accessor
+
+ def test_accessor
+
new_value = "hoge"
@elems.each do |name, value|
@@ -99,69 +90,21 @@ EOR
end
@rss.send(parent).send("dc_#{name}=", t.iso8601)
assert_equal(t, @rss.send(parent).send("dc_#{name}"))
- assert_equal(t, @rss.send(parent).date)
-
- @rss.send(parent).date = value
- assert_equal(value, @rss.send(parent).date)
- assert_equal(value, @rss.send(parent).send("dc_#{name}"))
else
@rss.send(parent).send("dc_#{name}=", new_value)
assert_equal(new_value, @rss.send(parent).send("dc_#{name}"))
end
end
end
- end
- def test_plural_accessor
- new_value = "hoge"
-
- @elems.each do |name, value|
- @parents.each do |parent|
- parsed_value = @rss.send(parent).send("dc_#{name}")
- if parsed_value.kind_of?(String)
- parsed_value = CGI.escapeHTML(parsed_value)
- end
- assert_equal(value, parsed_value)
-
- plural_reader = "dc_#{name}" + (name == :rights ? "es" : "s")
- klass_name = "DublinCore#{Utils.to_class_name(name.to_s)}"
- klass = DublinCoreModel.const_get(klass_name)
- if name == :date
- t = Time.iso8601("2003-01-01T02:30:23+09:00")
- class << t
- alias_method(:to_s, :iso8601)
- end
- elems = @rss.send(parent).send(plural_reader)
- elems << klass.new(t.iso8601)
- values = @rss.send(parent).send(plural_reader).collect{|x| x.value}
- assert_equal([@rss.send(parent).send("dc_#{name}"), t],
- values)
- else
- elems = @rss.send(parent).send(plural_reader)
- elems << klass.new(new_value)
- values = @rss.send(parent).send(plural_reader).collect{|x| x.value}
- assert_equal([@rss.send(parent).send("dc_#{name}"), new_value],
- values)
- end
- end
- end
end
def test_to_s
+
@elems.each do |name, value|
excepted = "<#{@prefix}:#{name}>#{value}</#{@prefix}:#{name}>"
@parents.each do |parent|
- assert_equal(excepted, @rss.send(parent).send("dc_#{name}_elements"))
- end
-
- excepted = Array.new(2, excepted).join("\n")
- @parents.each do |parent|
- reader = "dc_#{name}" + (name == :rights ? "es" : "s")
- elems = @rss.send(parent).send(reader)
- klass_name = "DublinCore#{Utils.to_class_name(name.to_s)}"
- klass = DublinCoreModel.const_get(klass_name)
- elems << klass.new(@rss.send(parent).send("dc_#{name}"))
- assert_equal(excepted, @rss.send(parent).send("dc_#{name}_elements"))
+ assert_equal(excepted, @rss.send(parent).send("dc_#{name}_element"))
end
end
@@ -169,12 +112,12 @@ EOR
if @parents.include?(parent.name)
parent.each_element do |elem|
if elem.namespace == @uri
- assert_equal(CGI.escapeHTML(elem.text),
- @elems[elem.name.intern].to_s)
+ assert_equal(CGI.escapeHTML(elem.text), @elems[elem.name.intern].to_s)
end
end
end
end
+
end
end
diff --git a/test/rss/test_image.rb b/test/rss/test_image.rb
deleted file mode 100644
index 8e62085b43..0000000000
--- a/test/rss/test_image.rb
+++ /dev/null
@@ -1,165 +0,0 @@
-require "cgi"
-require "rexml/document"
-
-require "rss-testcase"
-
-require "rss/1.0"
-require "rss/image"
-
-module RSS
- class TestImage < TestCase
-
- def setup
- @prefix = "image"
- @uri = "http://web.resource.org/rss/1.0/modules/image/"
-
- @favicon_attrs = {
- "rdf:about" => "http://www.kuro5hin.org/favicon.ico",
- "#{@prefix}:size" => "small",
- }
- @favicon_contents = {"dc:title" => "Kuro5hin",}
- @items = [
- [
- {
- "rdf:about" => "http://www.example.org/item.png",
- "rdf:resource" => "http://www.example.org/item",
- },
- {
- "dc:title" => "Example Image",
- "#{@prefix}:width" => 100,
- "#{@prefix}:height" => 65,
- },
- ],
- [
- {
- "rdf:about" => "http://www.kuro5hin.org/images/topics/culture.jpg",
- },
- {
- "dc:title" => "Culture",
- "#{@prefix}:width" => 80,
- "#{@prefix}:height" => 50,
- },
- ]
- ]
-
-
- @channel_nodes = make_element("#{@prefix}:favicon",
- @favicon_attrs,
- @favicon_contents)
- items = ""
- @items.each do |attrs, contents|
- image_item = make_element("#{@prefix}:item", attrs, contents)
- items << make_item(image_item)
- end
-
- ns = {
- @prefix => @uri,
- DC_PREFIX => DC_URI,
- }
- @rss_source = make_RDF(<<-EOR, ns)
-#{make_channel(@channel_nodes)}
-#{make_image}
-#{items}
-#{make_textinput}
-EOR
-
- @rss = Parser.parse(@rss_source)
- end
-
- def test_parser
- assert_nothing_raised do
- Parser.parse(@rss_source)
- end
-
- assert_too_much_tag("favicon", "channel") do
- Parser.parse(make_RDF(<<-EOR, {@prefix => @uri}))
-#{make_channel(@channel_nodes * 2)}
-#{make_item}
-EOR
- end
- end
-
- def test_favicon_accessor
- favicon = @rss.channel.image_favicon
- [
- %w(about rdf:about http://example.com/favicon.ico),
- %w(size image:size large),
- %w(image_size image:size medium),
- ].each do |name, full_name, new_value|
- assert_equal(@favicon_attrs[full_name], favicon.send(name))
- favicon.send("#{name}=", new_value)
- assert_equal(new_value, favicon.send(name))
- favicon.send("#{name}=", @favicon_attrs[full_name])
- assert_equal(@favicon_attrs[full_name], favicon.send(name))
- end
-
- [
- %w(dc_title dc:title sample-favicon),
- ].each do |name, full_name, new_value|
- assert_equal(@favicon_contents[full_name], favicon.send(name))
- favicon.send("#{name}=", new_value)
- assert_equal(new_value, favicon.send(name))
- favicon.send("#{name}=", @favicon_contents[full_name])
- assert_equal(@favicon_contents[full_name], favicon.send(name))
- end
- end
-
- def test_item_accessor
- @rss.items.each_with_index do |item, i|
- image_item = item.image_item
- attrs, contents = @items[i]
- [
- %w(about rdf:about http://example.com/image.png),
- %w(resource rdf:resource http://example.com/),
- ].each do |name, full_name, new_value|
- assert_equal(attrs[full_name], image_item.send(name))
- image_item.send("#{name}=", new_value)
- assert_equal(new_value, image_item.send(name))
- image_item.send("#{name}=", attrs[full_name])
- assert_equal(attrs[full_name], image_item.send(name))
- end
-
- [
- ["width", "image:width", 111],
- ["image_width", "image:width", 44],
- ["height", "image:height", 222],
- ["image_height", "image:height", 88],
- ["dc_title", "dc:title", "sample-image"],
- ].each do |name, full_name, new_value|
- assert_equal(contents[full_name], image_item.send(name))
- image_item.send("#{name}=", new_value)
- assert_equal(new_value, image_item.send(name))
- image_item.send("#{name}=", contents[full_name])
- assert_equal(contents[full_name], image_item.send(name))
- end
- end
- end
-
- def test_favicon_to_s
- favicon = @rss.channel.image_favicon
- expected = REXML::Document.new(make_element("#{@prefix}:favicon",
- @favicon_attrs,
- @favicon_contents))
- actual = REXML::Document.new(favicon.to_s(false, ""))
- assert_equal(expected.to_s, actual.to_s)
- end
-
- def test_item_to_s
- @rss.items.each_with_index do |item, i|
- attrs, contents = @items[i]
- expected_s = make_element("#{@prefix}:item", attrs, contents)
- expected = REXML::Document.new(expected_s)
- actual = REXML::Document.new(item.image_item.to_s(false, ""))
-
- assert_equal(expected[0].attributes, actual[0].attributes)
-
- %w(image:height image:width dc:title).each do |name|
- actual_target = actual.elements["//#{name}"]
- expected_target = expected.elements["//#{name}"]
- assert_equal(expected_target.to_s, actual_target.to_s)
- end
- end
- end
-
- end
-end
diff --git a/test/rss/test_inherit.rb b/test/rss/test_inherit.rb
deleted file mode 100644
index fc4bbbe76a..0000000000
--- a/test/rss/test_inherit.rb
+++ /dev/null
@@ -1,41 +0,0 @@
-require "rss-testcase"
-
-require "rss/1.0"
-
-module RSS
- class TestInherit < TestCase
-
- class InheritedImage < RSS::RDF::Image
- def self.indent_size; 1; end
- def self.tag_name; 'image'; end
- end
-
- def setup
- @rss = make_RDF(<<-EOR)
-#{make_channel}
-#{make_image}
-#{make_item}
-#{make_textinput}
-EOR
- end
-
- def test_inherit
- rss = RSS::Parser.parse(@rss)
- orig_image = rss.image
- prefix = "[INHERIT]"
- image = InheritedImage.new("#{prefix} #{orig_image.about}")
- image.title = "#{prefix} #{orig_image.title}"
- image.url = "#{prefix} #{orig_image.url}"
- image.link = "#{prefix} #{orig_image.link}"
- rss.image = image
-
- new_rss = RSS::Parser.parse(rss.to_s)
- new_image = new_rss.image
- assert_equal("#{prefix} #{orig_image.about}", new_image.about)
- assert_equal("#{prefix} #{orig_image.title}", new_image.title)
- assert_equal("#{prefix} #{orig_image.url}", new_image.url)
- assert_equal("#{prefix} #{orig_image.link}", new_image.link)
- end
-
- end
-end
diff --git a/test/rss/test_maker_0.9.rb b/test/rss/test_maker_0.9.rb
index 8fdd5f2d68..df8cd5fe11 100644
--- a/test/rss/test_maker_0.9.rb
+++ b/test/rss/test_maker_0.9.rb
@@ -6,38 +6,36 @@ module RSS
class TestMaker09 < TestCase
def test_rss
- rss = RSS::Maker.make("0.91")
+ rss = RSS::Maker.make("0.9")
assert_nil(rss)
rss = RSS::Maker.make("0.9") do |maker|
setup_dummy_channel(maker)
+ setup_dummy_image(maker)
end
assert_equal("0.91", rss.rss_version)
- rss = RSS::Maker.make("0.91") do |maker|
- setup_dummy_channel(maker)
- end
- assert_equal("0.91", rss.rss_version)
-
-
- rss = RSS::Maker.make("0.91") do |maker|
+ rss = RSS::Maker.make("0.9") do |maker|
setup_dummy_channel(maker)
+ setup_dummy_image(maker)
maker.encoding = "EUC-JP"
end
assert_equal("0.91", rss.rss_version)
assert_equal("EUC-JP", rss.encoding)
- rss = RSS::Maker.make("0.91") do |maker|
+ rss = RSS::Maker.make("0.9") do |maker|
setup_dummy_channel(maker)
+ setup_dummy_image(maker)
maker.standalone = "yes"
end
assert_equal("0.91", rss.rss_version)
assert_equal("yes", rss.standalone)
- rss = RSS::Maker.make("0.91") do |maker|
+ rss = RSS::Maker.make("0.9") do |maker|
setup_dummy_channel(maker)
+ setup_dummy_image(maker)
maker.encoding = "EUC-JP"
maker.standalone = "yes"
@@ -57,18 +55,12 @@ module RSS
webMaster = "web master"
rating = "6"
docs = "http://foo.com/doc"
- skipDays = [
- "Sunday",
- "Monday",
- ]
- skipHours = [
- 0,
- 13,
- ]
+ skipDays = "Sunday"
+ skipHours = "13"
pubDate = Time.now
lastBuildDate = Time.now
- rss = RSS::Maker.make("0.91") do |maker|
+ rss = RSS::Maker.make("0.9") do |maker|
maker.channel.title = title
maker.channel.link = link
maker.channel.description = description
@@ -78,17 +70,12 @@ module RSS
maker.channel.webMaster = webMaster
maker.channel.rating = rating
maker.channel.docs = docs
+ maker.channel.skipDays = skipDays
+ maker.channel.skipHours = skipHours
maker.channel.pubDate = pubDate
maker.channel.lastBuildDate = lastBuildDate
- skipDays.each do |day|
- new_day = maker.channel.skipDays.new_day
- new_day.content = day
- end
- skipHours.each do |hour|
- new_hour = maker.channel.skipHours.new_hour
- new_hour.content = hour
- end
+ setup_dummy_image(maker)
end
channel = rss.channel
@@ -101,19 +88,13 @@ module RSS
assert_equal(webMaster, channel.webMaster)
assert_equal(rating, channel.rating)
assert_equal(docs, channel.docs)
+ assert_equal(skipDays, channel.skipDays)
+ assert_equal(skipHours, channel.skipHours)
assert_equal(pubDate, channel.pubDate)
- assert_equal(pubDate, channel.date)
assert_equal(lastBuildDate, channel.lastBuildDate)
- skipDays.each_with_index do |day, i|
- assert_equal(day, channel.skipDays.days[i].content)
- end
- skipHours.each_with_index do |hour, i|
- assert_equal(hour, channel.skipHours.hours[i].content)
- end
-
assert(channel.items.empty?)
- assert_nil(channel.image)
+ assert_not_nil(channel.image)
assert_nil(channel.textInput)
end
@@ -122,43 +103,57 @@ module RSS
link = "http://hoge.com"
description = "fugafugafugafuga"
language = "ja"
+
+ rss = RSS::Maker.make("0.9") do |maker|
+ # setup_dummy_image(maker)
+
+ maker.channel.title = title
+ maker.channel.link = link
+ maker.channel.description = description
+ maker.channel.language = language
+ end
+ assert_nil(rss)
- assert_not_set_error("maker.channel", %w(title)) do
- RSS::Maker.make("0.91") do |maker|
- # maker.channel.title = title
- maker.channel.link = link
- maker.channel.description = description
- maker.channel.language = language
- end
+ rss = RSS::Maker.make("0.9") do |maker|
+ setup_dummy_image(maker)
+
+ # maker.channel.title = title
+ maker.channel.link = link
+ maker.channel.description = description
+ maker.channel.language = language
end
+ assert_nil(rss)
- assert_not_set_error("maker.channel", %w(link)) do
- RSS::Maker.make("0.91") do |maker|
- maker.channel.title = title
- # maker.channel.link = link
- maker.channel.link = nil
- maker.channel.description = description
- maker.channel.language = language
- end
+ rss = RSS::Maker.make("0.9") do |maker|
+ setup_dummy_image(maker)
+
+ maker.channel.title = title
+ # maker.channel.link = link
+ maker.channel.link = nil
+ maker.channel.description = description
+ maker.channel.language = language
end
+ assert_nil(rss)
- assert_not_set_error("maker.channel", %w(description)) do
- RSS::Maker.make("0.91") do |maker|
- maker.channel.title = title
- maker.channel.link = link
- # maker.channel.description = description
- maker.channel.language = language
- end
+ rss = RSS::Maker.make("0.9") do |maker|
+ setup_dummy_image(maker)
+
+ maker.channel.title = title
+ maker.channel.link = link
+ # maker.channel.description = description
+ maker.channel.language = language
end
+ assert_nil(rss)
- assert_not_set_error("maker.channel", %w(language)) do
- RSS::Maker.make("0.91") do |maker|
- maker.channel.title = title
- maker.channel.link = link
- maker.channel.description = description
- # maker.channel.language = language
- end
+ rss = RSS::Maker.make("0.9") do |maker|
+ setup_dummy_image(maker)
+
+ maker.channel.title = title
+ maker.channel.link = link
+ maker.channel.description = description
+ # maker.channel.language = language
end
+ assert_nil(rss)
end
def test_image
@@ -169,7 +164,7 @@ module RSS
height = 400
description = "an image"
- rss = RSS::Maker.make("0.91") do |maker|
+ rss = RSS::Maker.make("0.9") do |maker|
setup_dummy_channel(maker)
maker.channel.link = link
@@ -187,18 +182,17 @@ module RSS
assert_equal(height, image.height)
assert_equal(description, image.description)
- assert_not_set_error("maker.channel", %w(description title language)) do
- RSS::Maker.make("0.91") do |maker|
- # setup_dummy_channel(maker)
- maker.channel.link = link
+ rss = RSS::Maker.make("0.9") do |maker|
+ # setup_dummy_channel(maker)
+ maker.channel.link = link
- maker.image.title = title
- maker.image.url = url
- maker.image.width = width
- maker.image.height = height
- maker.image.description = description
- end
+ maker.image.title = title
+ maker.image.url = url
+ maker.image.width = width
+ maker.image.height = height
+ maker.image.description = description
end
+ assert_nil(rss)
end
def test_not_valid_image
@@ -209,7 +203,7 @@ module RSS
height = 400
description = "an image"
- rss = RSS::Maker.make("0.91") do |maker|
+ rss = RSS::Maker.make("0.9") do |maker|
setup_dummy_channel(maker)
maker.channel.link = link
@@ -219,23 +213,22 @@ module RSS
maker.image.height = height
maker.image.description = description
end
- assert_nil(rss.channel.image)
+ assert_nil(rss)
- assert_not_set_error("maker.channel", %w(link)) do
- RSS::Maker.make("0.91") do |maker|
- setup_dummy_channel(maker)
- # maker.channel.link = link
- maker.channel.link = nil
+ rss = RSS::Maker.make("0.9") do |maker|
+ setup_dummy_channel(maker)
+ # maker.channel.link = link
+ maker.channel.link = nil
- maker.image.title = title
- maker.image.url = url
- maker.image.width = width
- maker.image.height = height
- maker.image.description = description
- end
+ maker.image.title = title
+ maker.image.url = url
+ maker.image.width = width
+ maker.image.height = height
+ maker.image.description = description
end
+ assert_nil(rss)
- rss = RSS::Maker.make("0.91") do |maker|
+ rss = RSS::Maker.make("0.9") do |maker|
setup_dummy_channel(maker)
maker.channel.link = link
@@ -245,7 +238,7 @@ module RSS
maker.image.height = height
maker.image.description = description
end
- assert_nil(rss.channel.image)
+ assert_nil(rss)
end
def test_items
@@ -253,13 +246,15 @@ module RSS
link = "http://hoge.com/"
description = "text hoge fuga"
- rss = RSS::Maker.make("0.91") do |maker|
+ rss = RSS::Maker.make("0.9") do |maker|
setup_dummy_channel(maker)
+ setup_dummy_image(maker)
end
assert(rss.channel.items.empty?)
- rss = RSS::Maker.make("0.91") do |maker|
+ rss = RSS::Maker.make("0.9") do |maker|
setup_dummy_channel(maker)
+ setup_dummy_image(maker)
item = maker.items.new_item
item.title = title
@@ -274,8 +269,9 @@ module RSS
item_size = 5
- rss = RSS::Maker.make("0.91") do |maker|
+ rss = RSS::Maker.make("0.9") do |maker|
setup_dummy_channel(maker)
+ setup_dummy_image(maker)
item_size.times do |i|
item = maker.items.new_item
@@ -292,8 +288,9 @@ module RSS
assert_equal("#{description}#{i}", item.description)
end
- rss = RSS::Maker.make("0.91") do |maker|
+ rss = RSS::Maker.make("0.9") do |maker|
setup_dummy_channel(maker)
+ setup_dummy_image(maker)
item_size.times do |i|
item = maker.items.new_item
@@ -319,8 +316,9 @@ module RSS
name = "hoge"
link = "http://hoge.com"
- rss = RSS::Maker.make("0.91") do |maker|
+ rss = RSS::Maker.make("0.9") do |maker|
setup_dummy_channel(maker)
+ setup_dummy_image(maker)
maker.textinput.title = title
maker.textinput.description = description
@@ -333,8 +331,9 @@ module RSS
assert_equal(name, textInput.name)
assert_equal(link, textInput.link)
- rss = RSS::Maker.make("0.91") do |maker|
+ rss = RSS::Maker.make("0.9") do |maker|
# setup_dummy_channel(maker)
+ setup_dummy_image(maker)
maker.textinput.title = title
maker.textinput.description = description
@@ -350,8 +349,9 @@ module RSS
name = "hoge"
link = "http://hoge.com"
- rss = RSS::Maker.make("0.91") do |maker|
+ rss = RSS::Maker.make("0.9") do |maker|
setup_dummy_channel(maker)
+ setup_dummy_image(maker)
# maker.textinput.title = title
maker.textinput.description = description
@@ -360,8 +360,9 @@ module RSS
end
assert_nil(rss.channel.textInput)
- rss = RSS::Maker.make("0.91") do |maker|
+ rss = RSS::Maker.make("0.9") do |maker|
setup_dummy_channel(maker)
+ setup_dummy_image(maker)
maker.textinput.title = title
# maker.textinput.description = description
@@ -370,8 +371,9 @@ module RSS
end
assert_nil(rss.channel.textInput)
- rss = RSS::Maker.make("0.91") do |maker|
+ rss = RSS::Maker.make("0.9") do |maker|
setup_dummy_channel(maker)
+ setup_dummy_image(maker)
maker.textinput.title = title
maker.textinput.description = description
@@ -380,8 +382,9 @@ module RSS
end
assert_nil(rss.channel.textInput)
- rss = RSS::Maker.make("0.91") do |maker|
+ rss = RSS::Maker.make("0.9") do |maker|
setup_dummy_channel(maker)
+ setup_dummy_image(maker)
maker.textinput.title = title
maker.textinput.description = description
diff --git a/test/rss/test_maker_1.0.rb b/test/rss/test_maker_1.0.rb
index dca50f7e69..8f80f6e2fe 100644
--- a/test/rss/test_maker_1.0.rb
+++ b/test/rss/test_maker_1.0.rb
@@ -85,41 +85,37 @@ module RSS
link = "http://hoge.com"
description = "fugafugafugafuga"
- assert_not_set_error("maker.channel", %w(about)) do
- RSS::Maker.make("1.0") do |maker|
- # maker.channel.about = about
- maker.channel.title = title
- maker.channel.link = link
- maker.channel.description = description
- end
+ rss = RSS::Maker.make("1.0") do |maker|
+ # maker.channel.about = about
+ maker.channel.title = title
+ maker.channel.link = link
+ maker.channel.description = description
end
+ assert_nil(rss)
- assert_not_set_error("maker.channel", %w(title)) do
- RSS::Maker.make("1.0") do |maker|
- maker.channel.about = about
- # maker.channel.title = title
- maker.channel.link = link
- maker.channel.description = description
- end
+ rss = RSS::Maker.make("1.0") do |maker|
+ maker.channel.about = about
+ # maker.channel.title = title
+ maker.channel.link = link
+ maker.channel.description = description
end
+ assert_nil(rss)
- assert_not_set_error("maker.channel", %w(link)) do
- RSS::Maker.make("1.0") do |maker|
- maker.channel.about = about
- maker.channel.title = title
- # maker.channel.link = link
- maker.channel.description = description
- end
+ rss = RSS::Maker.make("1.0") do |maker|
+ maker.channel.about = about
+ maker.channel.title = title
+ # maker.channel.link = link
+ maker.channel.description = description
end
+ assert_nil(rss)
- assert_not_set_error("maker.channel", %w(description)) do
- RSS::Maker.make("1.0") do |maker|
- maker.channel.about = about
- maker.channel.title = title
- maker.channel.link = link
- # maker.channel.description = description
- end
+ rss = RSS::Maker.make("1.0") do |maker|
+ maker.channel.about = about
+ maker.channel.title = title
+ maker.channel.link = link
+ # maker.channel.description = description
end
+ assert_nil(rss)
end
@@ -142,15 +138,14 @@ module RSS
assert_equal(link, image.link)
assert_equal(url, image.url)
- assert_not_set_error("maker.channel", %w(about title description)) do
- RSS::Maker.make("1.0") do |maker|
- # setup_dummy_channel(maker)
- maker.channel.link = link
-
- maker.image.title = title
- maker.image.url = url
- end
+ rss = RSS::Maker.make("1.0") do |maker|
+ # setup_dummy_channel(maker)
+ maker.channel.link = link
+
+ maker.image.title = title
+ maker.image.url = url
end
+ assert_nil(rss)
end
def test_not_valid_image
@@ -178,16 +173,15 @@ module RSS
assert_nil(rss.channel.image)
assert_nil(rss.image)
- assert_not_set_error("maker.channel", %w(link)) do
- RSS::Maker.make("1.0") do |maker|
- setup_dummy_channel(maker)
- # maker.channel.link = link
- maker.channel.link = nil
-
- maker.image.url = url
- maker.image.title = title
- end
+ rss = RSS::Maker.make("1.0") do |maker|
+ setup_dummy_channel(maker)
+ # maker.channel.link = link
+ maker.channel.link = nil
+
+ maker.image.url = url
+ maker.image.title = title
end
+ assert_nil(rss)
end
def test_items
@@ -256,60 +250,6 @@ module RSS
assert_equal("#{link}#{i}", item.link)
assert_equal("#{description}#{i}", item.description)
end
-
- max_size = item_size / 2
- rss = RSS::Maker.make("1.0") do |maker|
- setup_dummy_channel(maker)
-
- item_size.times do |i|
- item = maker.items.new_item
- item.title = "#{title}#{i}"
- item.link = "#{link}#{i}"
- item.description = "#{description}#{i}"
- end
- maker.items.max_size = max_size
- end
- assert_equal(max_size, rss.items.size)
- rss.items.each_with_index do |item, i|
- assert_equal("#{link}#{i}", item.about)
- assert_equal("#{title}#{i}", item.title)
- assert_equal("#{link}#{i}", item.link)
- assert_equal("#{description}#{i}", item.description)
- end
-
- max_size = 0
- rss = RSS::Maker.make("1.0") do |maker|
- setup_dummy_channel(maker)
-
- item_size.times do |i|
- item = maker.items.new_item
- item.title = "#{title}#{i}"
- item.link = "#{link}#{i}"
- item.description = "#{description}#{i}"
- end
- maker.items.max_size = max_size
- end
- assert_equal(max_size, rss.items.size)
-
- max_size = -2
- rss = RSS::Maker.make("1.0") do |maker|
- setup_dummy_channel(maker)
-
- item_size.times do |i|
- item = maker.items.new_item
- item.title = "#{title}#{i}"
- item.link = "#{link}#{i}"
- item.description = "#{description}#{i}"
- end
- maker.items.max_size = max_size
- end
- assert_equal(item_size + max_size + 1, rss.items.size)
- rss.items.each_with_index do |item, i|
- assert_equal("#{link}#{i}", item.about)
- assert_equal("#{title}#{i}", item.title)
- assert_equal("#{link}#{i}", item.link)
- assert_equal("#{description}#{i}", item.description)
- end
end
def test_not_valid_items
diff --git a/test/rss/test_maker_2.0.rb b/test/rss/test_maker_2.0.rb
index b4d402a83e..b0752f985f 100644
--- a/test/rss/test_maker_2.0.rb
+++ b/test/rss/test_maker_2.0.rb
@@ -51,20 +51,11 @@ module RSS
webMaster = "web master"
rating = "6"
docs = "http://foo.com/doc"
- skipDays = [
- "Sunday",
- "Monday",
- ]
- skipHours = [
- 0,
- 13,
- ]
+ skipDays = "Sunday"
+ skipHours = "13"
pubDate = Time.now
lastBuildDate = Time.now
- categories = [
- "Nespapers",
- "misc",
- ]
+ category = "Nespapers"
generator = "RSS Maker"
ttl = 60
@@ -78,23 +69,11 @@ module RSS
maker.channel.webMaster = webMaster
maker.channel.rating = rating
maker.channel.docs = docs
+ maker.channel.skipDays = skipDays
+ maker.channel.skipHours = skipHours
maker.channel.pubDate = pubDate
maker.channel.lastBuildDate = lastBuildDate
-
- skipDays.each do |day|
- new_day = maker.channel.skipDays.new_day
- new_day.content = day
- end
- skipHours.each do |hour|
- new_hour = maker.channel.skipHours.new_hour
- new_hour.content = hour
- end
-
- categories.each do |category|
- new_category = maker.channel.categories.new_category
- new_category.content = category
- end
-
+ maker.channel.category = category
maker.channel.generator = generator
maker.channel.ttl = ttl
end
@@ -109,21 +88,11 @@ module RSS
assert_equal(webMaster, channel.webMaster)
assert_equal(rating, channel.rating)
assert_equal(docs, channel.docs)
+ assert_equal(skipDays, channel.skipDays)
+ assert_equal(skipHours, channel.skipHours)
assert_equal(pubDate, channel.pubDate)
- assert_equal(pubDate, channel.date)
assert_equal(lastBuildDate, channel.lastBuildDate)
-
- skipDays.each_with_index do |day, i|
- assert_equal(day, channel.skipDays.days[i].content)
- end
- skipHours.each_with_index do |hour, i|
- assert_equal(hour, channel.skipHours.hours[i].content)
- end
-
- channel.categories.each_with_index do |category, i|
- assert_equal(categories[i], category.content)
- end
-
+ assert_equal(category, channel.category)
assert_equal(generator, channel.generator)
assert_equal(ttl, channel.ttl)
@@ -138,32 +107,29 @@ module RSS
description = "fugafugafugafuga"
language = "ja"
- assert_not_set_error("maker.channel", %w(title)) do
- RSS::Maker.make("2.0") do |maker|
- # maker.channel.title = title
- maker.channel.link = link
- maker.channel.description = description
- maker.channel.language = language
- end
+ rss = RSS::Maker.make("2.0") do |maker|
+ # maker.channel.title = title
+ maker.channel.link = link
+ maker.channel.description = description
+ maker.channel.language = language
end
+ assert_nil(rss)
- assert_not_set_error("maker.channel", %w(link)) do
- RSS::Maker.make("2.0") do |maker|
- maker.channel.title = title
- # maker.channel.link = link
- maker.channel.description = description
- maker.channel.language = language
- end
+ rss = RSS::Maker.make("2.0") do |maker|
+ maker.channel.title = title
+ # maker.channel.link = link
+ maker.channel.description = description
+ maker.channel.language = language
end
+ assert_nil(rss)
- assert_not_set_error("maker.channel", %w(description)) do
- RSS::Maker.make("2.0") do |maker|
- maker.channel.title = title
- maker.channel.link = link
- # maker.channel.description = description
- maker.channel.language = language
- end
+ rss = RSS::Maker.make("2.0") do |maker|
+ maker.channel.title = title
+ maker.channel.link = link
+ # maker.channel.description = description
+ maker.channel.language = language
end
+ assert_nil(rss)
rss = RSS::Maker.make("2.0") do |maker|
maker.channel.title = title
@@ -289,18 +255,17 @@ module RSS
assert_equal(height, image.height)
assert_equal(description, image.description)
- assert_not_set_error("maker.channel", %w(title description)) do
- RSS::Maker.make("2.0") do |maker|
- # setup_dummy_channel(maker)
- maker.channel.link = link
+ rss = RSS::Maker.make("2.0") do |maker|
+ # setup_dummy_channel(maker)
+ maker.channel.link = link
- maker.image.title = title
- maker.image.url = url
- maker.image.width = width
- maker.image.height = height
- maker.image.description = description
- end
+ maker.image.title = title
+ maker.image.url = url
+ maker.image.width = width
+ maker.image.height = height
+ maker.image.description = description
end
+ assert_nil(rss)
end
def test_not_valid_image
@@ -323,19 +288,18 @@ module RSS
end
assert_nil(rss.image)
- assert_not_set_error("maker.channel", %w(link)) do
- RSS::Maker.make("2.0") do |maker|
- setup_dummy_channel(maker)
- # maker.channel.link = link
- maker.channel.link = nil
+ rss = RSS::Maker.make("2.0") do |maker|
+ setup_dummy_channel(maker)
+ # maker.channel.link = link
+ maker.channel.link = nil
- maker.image.title = title
- maker.image.url = url
- maker.image.width = width
- maker.image.height = height
- maker.image.description = description
- end
+ maker.image.title = title
+ maker.image.url = url
+ maker.image.width = width
+ maker.image.height = height
+ maker.image.description = description
end
+ assert_nil(rss)
rss = RSS::Maker.make("2.0") do |maker|
setup_dummy_channel(maker)
@@ -386,7 +350,6 @@ module RSS
assert_equal("#{author}#{i}", item.author)
assert_equal("#{comments}#{i}", item.comments)
assert_equal(pubDate, item.pubDate)
- assert_equal(pubDate, item.date)
end
rss = RSS::Maker.make("2.0") do |maker|
@@ -413,7 +376,6 @@ module RSS
assert_equal("#{author}#{i}", item.author)
assert_equal("#{comments}#{i}", item.comments)
assert_equal(pubDate, item.pubDate)
- assert_equal(pubDate, item.date)
end
end
@@ -557,11 +519,11 @@ module RSS
setup_dummy_channel(maker)
setup_dummy_item(maker)
- category = maker.items.last.categories.new_category
+ category = maker.items.last.category
category.domain = domain
category.content = content
end
- category = rss.channel.items.last.categories.last
+ category = rss.channel.items.last.category
assert_equal(domain, category.domain)
assert_equal(content, category.content)
end
@@ -573,10 +535,10 @@ module RSS
setup_dummy_channel(maker)
setup_dummy_item(maker)
- category = maker.items.last.categories.new_category
+ category = maker.items.last.category
# category.content = content
end
- assert(rss.channel.items.last.categories.empty?)
+ assert_nil(rss.channel.items.last.category)
end
def test_textInput
diff --git a/test/rss/test_maker_content.rb b/test/rss/test_maker_content.rb
index c29d75a649..faadd87131 100644
--- a/test/rss/test_maker_content.rb
+++ b/test/rss/test_maker_content.rb
@@ -14,7 +14,7 @@ module RSS
end
def test_rss10
- rss = RSS::Maker.make("1.0") do |maker|
+ rss = RSS::Maker.make("1.0", ["content"]) do |maker|
setup_dummy_channel(maker)
setup_dummy_item(maker)
diff --git a/test/rss/test_maker_dc.rb b/test/rss/test_maker_dc.rb
index 9f568ed441..512622d29f 100644
--- a/test/rss/test_maker_dc.rb
+++ b/test/rss/test_maker_dc.rb
@@ -34,7 +34,7 @@ module RSS
end
def test_rss10
- rss = RSS::Maker.make("1.0") do |maker|
+ rss = RSS::Maker.make("1.0", ["dublincore"]) do |maker|
setup_dummy_channel(maker)
set_elements(maker.channel)
@@ -56,86 +56,16 @@ module RSS
assert_dublin_core(@elements, rss.textinput)
end
- def test_rss10_multiple
- elems = []
- @elements.each do |name, value|
- plural = name.to_s + (name == :rights ? "es" : "s")
- values = [value]
- if name == :date
- values << value + 60
- else
- values << value * 2
- end
- elems << [name, values, plural]
- end
-
- rss = RSS::Maker.make("1.0") do |maker|
- setup_dummy_channel(maker)
- set_multiple_elements(maker.channel, elems)
-
- setup_dummy_image(maker)
- set_multiple_elements(maker.image, elems)
-
- setup_dummy_item(maker)
- item = maker.items.last
- elems.each do |name, values, plural|
- dc_elems = item.__send__("dc_#{plural}")
- values.each do |value|
- elem = dc_elems.__send__("new_#{name}")
- elem.value = value
- end
- end
-
- setup_dummy_textinput(maker)
- set_multiple_elements(maker.textinput, elems)
- end
- assert_multiple_dublin_core(elems, rss.channel)
- assert_multiple_dublin_core(elems, rss.image)
- assert_multiple_dublin_core(elems, rss.items.last)
- assert_multiple_dublin_core(elems, rss.textinput)
- end
-
- def test_date
- t1 = Time.iso8601("2000-01-01T12:00:05+00:00")
- t2 = Time.iso8601("2005-01-01T12:00:05+00:00")
-
- rss = RSS::Maker.make("1.0") do |maker|
- setup_dummy_channel(maker)
- maker.channel.date = t1
- date = maker.channel.dc_dates.new_date
- date.value = t2
-
- setup_dummy_item(maker)
- item = maker.items.last
- item.date = t2
- date = item.dc_dates.new_date
- date.value = t1
- end
- assert_equal([t1, t2], rss.channel.dc_dates.collect{|x| x.value})
- assert_equal([t2, t1], rss.items.last.dc_dates.collect{|x| x.value})
- end
-
private
def accessor_name(name)
"dc_#{name}"
end
- def set_elements(target, elems=@elements)
- elems.each do |name, value|
+ def set_elements(target)
+ @elements.each do |name, value|
target.__send__("#{accessor_name(name)}=", value)
end
end
- def set_multiple_elements(target, elems)
- elems.each do |name, values, plural|
- plural ||= "#{name}s"
- dc_elems = target.__send__("dc_#{plural}")
- values.each do |value|
- new_dc_elem = dc_elems.__send__("new_#{name}")
- new_dc_elem.value = value
- end
- end
- end
-
end
end
diff --git a/test/rss/test_maker_image.rb b/test/rss/test_maker_image.rb
deleted file mode 100644
index 1c161b2593..0000000000
--- a/test/rss/test_maker_image.rb
+++ /dev/null
@@ -1,62 +0,0 @@
-require "rss-testcase"
-
-require "rss/maker"
-
-module RSS
- class TestMakerImage < TestCase
-
- def setup
- @uri = "http://web.resource.org/rss/1.0/modules/image/"
-
- @favicon_infos = {
- "about" => "http://www.kuro5hin.org/favicon.ico",
- "image_size" => "small",
- "dc_title" => "example",
- }
- @item_infos = {
- "about" => "http://www.example.org/item.png",
- "resource" => "http://www.example.org/item",
- "dc_title" => "Example Image",
- "image_width" => 100,
- "image_height" => 65,
- }
- end
-
- def test_rss10
- rss = RSS::Maker.make("1.0") do |maker|
- setup_dummy_channel(maker)
- @favicon_infos.each do |name, value|
- maker.channel.image_favicon.__send__("#{name}=", value)
- end
-
- setup_dummy_image(maker)
-
- setup_dummy_item(maker)
- item = maker.items.last
- @item_infos.each do |name, value|
- item.image_item.__send__("#{name}=", value)
- end
-
- setup_dummy_textinput(maker)
- end
-
- setup_rss = RSS::Maker.make("1.0") do |maker|
- rss.setup_maker(maker)
- end
-
- [rss, setup_rss].each_with_index do |target, i|
- favicon = target.channel.image_favicon
- assert_equal(@favicon_infos["about"], favicon.about)
- assert_equal(@favicon_infos["image_size"], favicon.image_size)
- assert_equal(@favicon_infos["dc_title"], favicon.dc_title)
-
- item = target.items.last.image_item
- assert_equal(@item_infos["about"], item.about)
- assert_equal(@item_infos["resource"], item.resource)
- assert_equal(@item_infos["image_width"], item.image_width)
- assert_equal(@item_infos["image_height"], item.image_height)
- assert_equal(@item_infos["dc_title"], item.dc_title)
- end
- end
- end
-end
diff --git a/test/rss/test_maker_sy.rb b/test/rss/test_maker_sy.rb
index 58e95d917a..c41ec1d310 100644
--- a/test/rss/test_maker_sy.rb
+++ b/test/rss/test_maker_sy.rb
@@ -21,7 +21,7 @@ module RSS
end
def test_rss10
- rss = RSS::Maker.make("1.0") do |maker|
+ rss = RSS::Maker.make("1.0", ["syndication"]) do |maker|
setup_dummy_channel(maker)
set_elements(maker.channel)
end
diff --git a/test/rss/test_maker_trackback.rb b/test/rss/test_maker_trackback.rb
index e90bb600a3..bffa60e963 100644
--- a/test/rss/test_maker_trackback.rb
+++ b/test/rss/test_maker_trackback.rb
@@ -10,23 +10,18 @@ module RSS
@elements = {
:ping => "http://bar.com/tb.cgi?tb_id=rssplustrackback",
- :abouts => [
- "http://foo.com/trackback/tb.cgi?tb_id=20020923",
- "http://bar.com/trackback/tb.cgi?tb_id=20041114",
- ],
+ :about => "http://foo.com/trackback/tb.cgi?tb_id=20020923",
}
end
def test_rss10
- rss = RSS::Maker.make("1.0") do |maker|
+ rss = RSS::Maker.make("1.0", ["trackback"]) do |maker|
setup_dummy_channel(maker)
setup_dummy_item(maker)
item = maker.items.last
- item.trackback_ping = @elements[:ping]
- @elements[:abouts].each do |about|
- new_about = item.trackback_abouts.new_about
- new_about.value = about
+ @elements.each do |name, value|
+ item.__send__("#{accessor_name(name)}=", value)
end
end
assert_trackback(@elements, rss.items.last)
diff --git a/test/rss/test_parser.rb b/test/rss/test_parser.rb
index adf0864d19..de4894997f 100644
--- a/test/rss/test_parser.rb
+++ b/test/rss/test_parser.rb
@@ -1,5 +1,3 @@
-require "fileutils"
-
require "rss-testcase"
require "rss/1.0"
@@ -11,19 +9,10 @@ module RSS
def setup
@_default_parser = Parser.default_parser
- @rss10 = make_RDF(<<-EOR)
-#{make_channel}
-#{make_item}
-#{make_textinput}
-#{make_image}
-EOR
- @rss_file = "rss10.rdf"
- File.open(@rss_file, "w") {|f| f.print(@rss10)}
end
def teardown
Parser.default_parser = @_default_parser
- FileUtils.rm_f(@rss_file)
end
def test_RDF
@@ -127,7 +116,7 @@ EOR
def test_channel
- assert_parse(make_RDF(<<-EOR), :missing_attribute, "channel", "rdf:about")
+ assert_parse(make_RDF(<<-EOR), :missing_attribute, "channel", "about")
<channel />
EOR
@@ -156,7 +145,7 @@ EOR
</channel>
EOR
- assert_parse(make_RDF(<<-EOR), :missing_attribute, "image", "rdf:resource")
+ assert_parse(make_RDF(<<-EOR), :missing_attribute, "image", "resource")
<channel rdf:about="http://example.com/">
<title>hoge</title>
<link>http://example.com/</link>
@@ -205,7 +194,7 @@ EOR
</channel>
EOR
- assert_parse(make_RDF(<<-EOR), :missing_attribute, "textinput", "rdf:resource")
+ assert_parse(make_RDF(<<-EOR), :missing_attribute, "textinput", "resource")
<channel rdf:about="http://example.com/">
<title>hoge</title>
<link>http://example.com/</link>
@@ -268,7 +257,7 @@ EOR
def test_image
- assert_parse(make_RDF(<<-EOR), :missing_attribute, "image", "rdf:about")
+ assert_parse(make_RDF(<<-EOR), :missing_attribute, "image", "about")
#{make_channel}
<image>
</image>
@@ -325,7 +314,7 @@ EOR
def test_item
- assert_parse(make_RDF(<<-EOR), :missing_attribute, "item", "rdf:about")
+ assert_parse(make_RDF(<<-EOR), :missing_attribute, "item", "about")
#{make_channel}
#{make_image}
<item>
@@ -382,7 +371,7 @@ EOR
def test_textinput
- assert_parse(make_RDF(<<-EOR), :missing_attribute, "textinput", "rdf:about")
+ assert_parse(make_RDF(<<-EOR), :missing_attribute, "textinput", "about")
#{make_channel}
#{make_image}
#{make_item}
@@ -555,28 +544,40 @@ EOR
end
def test_category20
- values = [nil, CATEGORY_DOMAIN]
+
+ attrs = [
+ ["domain", CATEGORY_DOMAIN],
+ ]
- values.each do |value|
- domain = ""
- domain << %Q[domain="#{value}"] if value
+ (attrs.size + 1).times do |i|
+ missing_attr = attrs[i]
+ if missing_attr
+ meth = :missing_attribute
+ args = ["category", missing_attr[0]]
+ else
+ meth = :nothing_raised
+ args = []
+ end
+
+ category_attrs = []
+ attrs.each_with_index do |attr, j|
+ unless i == j
+ category_attrs << %Q[#{attr[0]}="#{attr[1]}"]
+ end
+ end
["", "Example Text"].each do |text|
- rss_src = make_rss20(<<-EOR)
+ assert_parse(make_rss20(<<-EOR), meth, *args)
#{make_channel20(%Q[
#{make_item20(%Q[
-<category #{domain}>#{text}</category>
+<category
+ #{category_attrs.join("\n")}>#{text}</category>
])}
])}
EOR
- assert_parse(rss_src, :nothing_raised)
-
- rss = RSS::Parser.parse(rss_src)
- category = rss.items.last.categories.first
- assert_equal(value, category.domain)
- assert_equal(text, category.content)
end
end
+
end
def test_ignore
@@ -596,7 +597,7 @@ EOR
end
def test_default_parser
- assert_nothing_raised do
+ assert_nothing_raised() do
Parser.default_parser = RSS::AVAILABLE_PARSERS.first
end
@@ -605,19 +606,6 @@ EOR
end
end
- def test_parse
- assert_not_nil(RSS::Parser.parse(@rss_file))
-
- garbage_rss_file = @rss_file + "-garbage"
- if RSS::Parser.default_parser.name == "RSS::XMLParserParser"
- assert_raise(RSS::NotWellFormedError) do
- RSS::Parser.parse(garbage_rss_file)
- end
- else
- assert_nil(RSS::Parser.parse(garbage_rss_file))
- end
- end
-
end
end
diff --git a/test/rss/test_setup_maker_0.9.rb b/test/rss/test_setup_maker_0.9.rb
deleted file mode 100644
index e0f26d5593..0000000000
--- a/test/rss/test_setup_maker_0.9.rb
+++ /dev/null
@@ -1,221 +0,0 @@
-require "rss-testcase"
-
-require "rss/maker"
-
-module RSS
- class TestSetupMaker09 < TestCase
-
- def test_setup_maker_channel
- title = "fugafuga"
- link = "http://hoge.com"
- description = "fugafugafugafuga"
- language = "ja"
- copyright = "foo"
- managingEditor = "bar"
- webMaster = "web master"
- rating = "6"
- docs = "http://foo.com/doc"
- skipDays = [
- "Sunday",
- "Monday",
- ]
- skipHours = [
- 0,
- 13,
- ]
- pubDate = Time.now
- lastBuildDate = Time.now
-
- rss = RSS::Maker.make("0.91") do |maker|
- maker.channel.title = title
- maker.channel.link = link
- maker.channel.description = description
- maker.channel.language = language
- maker.channel.copyright = copyright
- maker.channel.managingEditor = managingEditor
- maker.channel.webMaster = webMaster
- maker.channel.rating = rating
- maker.channel.docs = docs
- maker.channel.pubDate = pubDate
- maker.channel.lastBuildDate = lastBuildDate
-
- skipDays.each do |day|
- new_day = maker.channel.skipDays.new_day
- new_day.content = day
- end
- skipHours.each do |hour|
- new_hour = maker.channel.skipHours.new_hour
- new_hour.content = hour
- end
- end
-
- new_rss = RSS::Maker.make("0.91") do |maker|
- rss.channel.setup_maker(maker)
- end
- channel = new_rss.channel
-
- assert_equal(title, channel.title)
- assert_equal(link, channel.link)
- assert_equal(description, channel.description)
- assert_equal(language, channel.language)
- assert_equal(copyright, channel.copyright)
- assert_equal(managingEditor, channel.managingEditor)
- assert_equal(webMaster, channel.webMaster)
- assert_equal(rating, channel.rating)
- assert_equal(docs, channel.docs)
- assert_equal(pubDate, channel.pubDate)
- assert_equal(lastBuildDate, channel.lastBuildDate)
-
- skipDays.each_with_index do |day, i|
- assert_equal(day, channel.skipDays.days[i].content)
- end
- skipHours.each_with_index do |hour, i|
- assert_equal(hour, channel.skipHours.hours[i].content)
- end
-
- assert(channel.items.empty?)
- assert_nil(channel.image)
- assert_nil(channel.textInput)
- end
-
- def test_setup_maker_image
- title = "fugafuga"
- link = "http://hoge.com"
- url = "http://hoge.com/hoge.png"
- width = 144
- height = 400
- description = "an image"
-
- rss = RSS::Maker.make("0.91") do |maker|
- setup_dummy_channel(maker)
- maker.channel.link = link
-
- maker.image.title = title
- maker.image.url = url
- maker.image.width = width
- maker.image.height = height
- maker.image.description = description
- end
-
- new_rss = RSS::Maker.make("0.91") do |maker|
- rss.channel.setup_maker(maker)
- rss.image.setup_maker(maker)
- end
-
- image = new_rss.image
- assert_equal(title, image.title)
- assert_equal(link, image.link)
- assert_equal(url, image.url)
- assert_equal(width, image.width)
- assert_equal(height, image.height)
- assert_equal(description, image.description)
- end
-
- def test_setup_maker_textinput
- title = "fugafuga"
- description = "text hoge fuga"
- name = "hoge"
- link = "http://hoge.com"
-
- rss = RSS::Maker.make("0.91") do |maker|
- setup_dummy_channel(maker)
-
- maker.textinput.title = title
- maker.textinput.description = description
- maker.textinput.name = name
- maker.textinput.link = link
- end
-
- new_rss = RSS::Maker.make("0.91") do |maker|
- rss.channel.setup_maker(maker)
- rss.textinput.setup_maker(maker)
- end
-
- textInput = new_rss.channel.textInput
- assert_equal(title, textInput.title)
- assert_equal(description, textInput.description)
- assert_equal(name, textInput.name)
- assert_equal(link, textInput.link)
- end
-
- def test_setup_maker_items
- title = "TITLE"
- link = "http://hoge.com/"
- description = "text hoge fuga"
-
- item_size = 5
-
- rss = RSS::Maker.make("0.91") do |maker|
- setup_dummy_channel(maker)
-
- item_size.times do |i|
- item = maker.items.new_item
- item.title = "#{title}#{i}"
- item.link = "#{link}#{i}"
- item.description = "#{description}#{i}"
- end
- end
-
- new_rss = RSS::Maker.make("0.91") do |maker|
- rss.channel.setup_maker(maker)
-
- rss.items.each do |item|
- item.setup_maker(maker)
- end
- end
-
- assert_equal(item_size, new_rss.items.size)
- new_rss.items.each_with_index do |item, i|
- assert_equal("#{title}#{i}", item.title)
- assert_equal("#{link}#{i}", item.link)
- assert_equal("#{description}#{i}", item.description)
- end
-
- end
-
- def test_setup_maker
- encoding = "EUC-JP"
- standalone = true
-
- href = 'a.xsl'
- type = 'text/xsl'
- title = 'sample'
- media = 'printer'
- charset = 'UTF-8'
- alternate = 'yes'
-
- rss = RSS::Maker.make("0.91") do |maker|
- maker.encoding = encoding
- maker.standalone = standalone
-
- xss = maker.xml_stylesheets.new_xml_stylesheet
- xss.href = href
- xss.type = type
- xss.title = title
- xss.media = media
- xss.charset = charset
- xss.alternate = alternate
-
- setup_dummy_channel(maker)
- end
-
- new_rss = RSS::Maker.make("0.91") do |maker|
- rss.setup_maker(maker)
- end
-
- assert_equal("0.91", new_rss.rss_version)
- assert_equal(encoding, new_rss.encoding)
- assert_equal(standalone, new_rss.standalone)
-
- xss = rss.xml_stylesheets.first
- assert_equal(1, rss.xml_stylesheets.size)
- assert_equal(href, xss.href)
- assert_equal(type, xss.type)
- assert_equal(title, xss.title)
- assert_equal(media, xss.media)
- assert_equal(charset, xss.charset)
- assert_equal(alternate, xss.alternate)
- end
-
- end
-end
diff --git a/test/rss/test_setup_maker_1.0.rb b/test/rss/test_setup_maker_1.0.rb
deleted file mode 100644
index 244eee6114..0000000000
--- a/test/rss/test_setup_maker_1.0.rb
+++ /dev/null
@@ -1,326 +0,0 @@
-require "rss-testcase"
-
-require "rss/maker"
-
-module RSS
- class TestSetupMaker10 < TestCase
-
- def setup
- t = Time.iso8601("2000-01-01T12:00:05+00:00")
- class << t
- alias_method(:to_s, :iso8601)
- end
-
- @dc_elems = {
- :title => "hoge",
- :description =>
- " XML is placing increasingly heavy loads on
- the existing technical infrastructure of the Internet.",
- :creator => "Rael Dornfest (mailto:rael@oreilly.com)",
- :subject => "XML",
- :publisher => "The O'Reilly Network",
- :contributor => "hogehoge",
- :type => "fugafuga",
- :format => "hohoho",
- :identifier => "fufufu",
- :source => "barbar",
- :language => "ja",
- :relation => "cococo",
- :rights => "Copyright (c) 2000 O'Reilly &amp; Associates, Inc.",
- :date => t,
- }
-
- @sy_elems = {
- :updatePeriod => "hourly",
- :updateFrequency => 2,
- :updateBase => t,
- }
-
- @content_elems = {
- :encoded => "<em>ATTENTION</em>",
- }
-
- @trackback_elems = {
- :ping => "http://bar.com/tb.cgi?tb_id=rssplustrackback",
- :about => [
- "http://foo.com/trackback/tb.cgi?tb_id=20020923",
- "http://foo.com/trackback/tb.cgi?tb_id=20021010",
- ],
- }
- end
-
- def test_setup_maker_channel
- about = "http://hoge.com"
- title = "fugafuga"
- link = "http://hoge.com"
- description = "fugafugafugafuga"
-
- rss = RSS::Maker.make("1.0") do |maker|
- maker.channel.about = about
- maker.channel.title = title
- maker.channel.link = link
- maker.channel.description = description
-
- @dc_elems.each do |var, value|
- maker.channel.__send__("dc_#{var}=", value)
- end
-
- @sy_elems.each do |var, value|
- maker.channel.__send__("sy_#{var}=", value)
- end
- end
-
- new_rss = RSS::Maker.make("1.0") do |maker|
- rss.channel.setup_maker(maker)
- end
- channel = new_rss.channel
-
- assert_equal(about, channel.about)
- assert_equal(title, channel.title)
- assert_equal(link, channel.link)
- assert_equal(description, channel.description)
- assert_equal(true, channel.items.Seq.lis.empty?)
- assert_nil(channel.image)
- assert_nil(channel.textinput)
-
- @dc_elems.each do |var, value|
- assert_equal(value, channel.__send__("dc_#{var}"))
- end
-
- @sy_elems.each do |var, value|
- assert_equal(value, channel.__send__("sy_#{var}"))
- end
-
- end
-
- def test_setup_maker_image
- title = "fugafuga"
- link = "http://hoge.com"
- url = "http://hoge.com/hoge.png"
-
- rss = RSS::Maker.make("1.0") do |maker|
- setup_dummy_channel(maker)
- maker.channel.link = link
-
- maker.image.title = title
- maker.image.url = url
-
- @dc_elems.each do |var, value|
- maker.image.__send__("dc_#{var}=", value)
- end
- end
-
- new_rss = RSS::Maker.make("1.0") do |maker|
- rss.channel.setup_maker(maker)
- rss.image.setup_maker(maker)
- end
-
- image = new_rss.image
- assert_equal(url, image.about)
- assert_equal(url, new_rss.channel.image.resource)
- assert_equal(title, image.title)
- assert_equal(link, image.link)
- assert_equal(url, image.url)
-
- @dc_elems.each do |var, value|
- assert_equal(image.__send__("dc_#{var}"), value)
- end
- end
-
- def test_setup_maker_textinput
- title = "fugafuga"
- description = "text hoge fuga"
- name = "hoge"
- link = "http://hoge.com"
-
- rss = RSS::Maker.make("1.0") do |maker|
- setup_dummy_channel(maker)
-
- maker.textinput.link = link
- maker.textinput.title = title
- maker.textinput.description = description
- maker.textinput.name = name
-
- @dc_elems.each do |var, value|
- maker.textinput.__send__("dc_#{var}=", value)
- end
- end
-
- new_rss = RSS::Maker.make("1.0") do |maker|
- rss.channel.setup_maker(maker)
- rss.textinput.setup_maker(maker)
- end
-
- textinput = new_rss.textinput
- assert_equal(link, textinput.about)
- assert_equal(link, new_rss.channel.textinput.resource)
- assert_equal(title, textinput.title)
- assert_equal(name, textinput.name)
- assert_equal(description, textinput.description)
- assert_equal(link, textinput.link)
-
- @dc_elems.each do |var, value|
- assert_equal(textinput.__send__("dc_#{var}"), value)
- end
- end
-
- def test_setup_maker_items
- title = "TITLE"
- link = "http://hoge.com/"
- description = "text hoge fuga"
-
- item_size = 5
-
- rss = RSS::Maker.make("1.0") do |maker|
- setup_dummy_channel(maker)
-
- item_size.times do |i|
- item = maker.items.new_item
- item.title = "#{title}#{i}"
- item.link = "#{link}#{i}"
- item.description = "#{description}#{i}"
-
- @dc_elems.each do |var, value|
- item.__send__("dc_#{var}=", value)
- end
-
- @content_elems.each do |var, value|
- item.__send__("content_#{var}=", value)
- end
-
- item.trackback_ping = @trackback_elems[:ping]
- @trackback_elems[:about].each do |value|
- new_about = item.trackback_abouts.new_about
- new_about.value = value
- end
- end
- end
-
- new_rss = RSS::Maker.make("1.0") do |maker|
- rss.channel.setup_maker(maker)
-
- rss.items.each do |item|
- item.setup_maker(maker)
- end
- end
-
- assert_equal(item_size, new_rss.items.size)
- new_rss.items.each_with_index do |item, i|
- assert_equal("#{link}#{i}", item.about)
- assert_equal("#{title}#{i}", item.title)
- assert_equal("#{link}#{i}", item.link)
- assert_equal("#{description}#{i}", item.description)
-
- @dc_elems.each do |var, value|
- assert_equal(item.__send__("dc_#{var}"), value)
- end
-
- @content_elems.each do |var, value|
- assert_equal(item.__send__("content_#{var}"), value)
- end
-
- assert_equal(@trackback_elems[:ping], item.trackback_ping)
- assert_equal(@trackback_elems[:about].size, item.trackback_abouts.size)
- item.trackback_abouts.each_with_index do |about, i|
- assert_equal(@trackback_elems[:about][i], about.value)
- end
- end
- end
-
- def test_setup_maker_items_sort
- title = "TITLE"
- link = "http://hoge.com/"
- description = "text hoge fuga"
- item_size = 5
-
-
- rss = RSS::Maker.make("1.0") do |maker|
- setup_dummy_channel(maker)
-
- item_size.times do |i|
- item = RSS::RDF::Item.new("#{link}#{i}")
- item.title = "#{title}#{i}"
- item.link = "#{link}#{i}"
- item.description = "#{description}#{i}"
- item.dc_date = Time.now + i * 60
- item.setup_maker(maker)
- end
- maker.items.do_sort = false
- end
- assert_equal(item_size, rss.items.size)
- rss.items.each_with_index do |item, i|
- assert_equal("#{link}#{i}", item.about)
- assert_equal("#{title}#{i}", item.title)
- assert_equal("#{link}#{i}", item.link)
- assert_equal("#{description}#{i}", item.description)
- end
-
-
- rss = RSS::Maker.make("1.0") do |maker|
- setup_dummy_channel(maker)
-
- item_size.times do |i|
- item = RSS::RDF::Item.new("#{link}#{i}")
- item.title = "#{title}#{i}"
- item.link = "#{link}#{i}"
- item.description = "#{description}#{i}"
- item.dc_date = Time.now + i * 60
- item.setup_maker(maker)
- end
- maker.items.do_sort = true
- end
- assert_equal(item_size, rss.items.size)
- rss.items.reverse.each_with_index do |item, i|
- assert_equal("#{link}#{i}", item.about)
- assert_equal("#{title}#{i}", item.title)
- assert_equal("#{link}#{i}", item.link)
- assert_equal("#{description}#{i}", item.description)
- end
- end
-
- def test_setup_maker
- encoding = "EUC-JP"
- standalone = true
-
- href = 'a.xsl'
- type = 'text/xsl'
- title = 'sample'
- media = 'printer'
- charset = 'UTF-8'
- alternate = 'yes'
-
- rss = RSS::Maker.make("1.0") do |maker|
- maker.encoding = encoding
- maker.standalone = standalone
-
- xss = maker.xml_stylesheets.new_xml_stylesheet
- xss.href = href
- xss.type = type
- xss.title = title
- xss.media = media
- xss.charset = charset
- xss.alternate = alternate
-
- setup_dummy_channel(maker)
- end
-
- new_rss = RSS::Maker.make("1.0") do |maker|
- rss.setup_maker(maker)
- end
-
- assert_equal("1.0", new_rss.rss_version)
- assert_equal(encoding, new_rss.encoding)
- assert_equal(standalone, new_rss.standalone)
-
- xss = rss.xml_stylesheets.first
- assert_equal(1, rss.xml_stylesheets.size)
- assert_equal(href, xss.href)
- assert_equal(type, xss.type)
- assert_equal(title, xss.title)
- assert_equal(media, xss.media)
- assert_equal(charset, xss.charset)
- assert_equal(alternate, xss.alternate)
- end
-
- end
-end
diff --git a/test/rss/test_setup_maker_2.0.rb b/test/rss/test_setup_maker_2.0.rb
deleted file mode 100644
index f28f837e43..0000000000
--- a/test/rss/test_setup_maker_2.0.rb
+++ /dev/null
@@ -1,295 +0,0 @@
-require "rss-testcase"
-
-require "rss/maker"
-
-module RSS
- class TestSetupMaker20 < TestCase
-
- def test_setup_maker_channel
- title = "fugafuga"
- link = "http://hoge.com"
- description = "fugafugafugafuga"
- language = "ja"
- copyright = "foo"
- managingEditor = "bar"
- webMaster = "web master"
- rating = "6"
- docs = "http://foo.com/doc"
- skipDays = [
- "Sunday",
- "Monday",
- ]
- skipHours = [
- 0,
- 13,
- ]
- pubDate = Time.now
- lastBuildDate = Time.now
- categories = [
- "Nespapers",
- "misc",
- ]
- generator = "RSS Maker"
- ttl = 60
-
- rss = RSS::Maker.make("2.0") do |maker|
- maker.channel.title = title
- maker.channel.link = link
- maker.channel.description = description
- maker.channel.language = language
- maker.channel.copyright = copyright
- maker.channel.managingEditor = managingEditor
- maker.channel.webMaster = webMaster
- maker.channel.rating = rating
- maker.channel.docs = docs
- maker.channel.pubDate = pubDate
- maker.channel.lastBuildDate = lastBuildDate
-
- skipDays.each do |day|
- new_day = maker.channel.skipDays.new_day
- new_day.content = day
- end
- skipHours.each do |hour|
- new_hour = maker.channel.skipHours.new_hour
- new_hour.content = hour
- end
-
-
- categories.each do |category|
- new_category = maker.channel.categories.new_category
- new_category.content = category
- end
-
- maker.channel.generator = generator
- maker.channel.ttl = ttl
- end
-
- new_rss = RSS::Maker.make("2.0") do |maker|
- rss.channel.setup_maker(maker)
- end
- channel = new_rss.channel
-
- assert_equal(title, channel.title)
- assert_equal(link, channel.link)
- assert_equal(description, channel.description)
- assert_equal(language, channel.language)
- assert_equal(copyright, channel.copyright)
- assert_equal(managingEditor, channel.managingEditor)
- assert_equal(webMaster, channel.webMaster)
- assert_equal(rating, channel.rating)
- assert_equal(docs, channel.docs)
- assert_equal(pubDate, channel.pubDate)
- assert_equal(lastBuildDate, channel.lastBuildDate)
-
- skipDays.each_with_index do |day, i|
- assert_equal(day, channel.skipDays.days[i].content)
- end
- skipHours.each_with_index do |hour, i|
- assert_equal(hour, channel.skipHours.hours[i].content)
- end
-
-
- channel.categories.each_with_index do |category, i|
- assert_equal(categories[i], category.content)
- end
-
- assert_equal(generator, channel.generator)
- assert_equal(ttl, channel.ttl)
-
-
- assert(channel.items.empty?)
- assert_nil(channel.image)
- assert_nil(channel.textInput)
- end
-
- def test_setup_maker_image
- title = "fugafuga"
- link = "http://hoge.com"
- url = "http://hoge.com/hoge.png"
- width = 144
- height = 400
- description = "an image"
-
- rss = RSS::Maker.make("2.0") do |maker|
- setup_dummy_channel(maker)
- maker.channel.link = link
-
- maker.image.title = title
- maker.image.url = url
- maker.image.width = width
- maker.image.height = height
- maker.image.description = description
- end
-
- new_rss = RSS::Maker.make("2.0") do |maker|
- rss.channel.setup_maker(maker)
- rss.image.setup_maker(maker)
- end
-
- image = new_rss.image
- assert_equal(title, image.title)
- assert_equal(link, image.link)
- assert_equal(url, image.url)
- assert_equal(width, image.width)
- assert_equal(height, image.height)
- assert_equal(description, image.description)
- end
-
- def test_setup_maker_textinput
- title = "fugafuga"
- description = "text hoge fuga"
- name = "hoge"
- link = "http://hoge.com"
-
- rss = RSS::Maker.make("2.0") do |maker|
- setup_dummy_channel(maker)
-
- maker.textinput.title = title
- maker.textinput.description = description
- maker.textinput.name = name
- maker.textinput.link = link
- end
-
- new_rss = RSS::Maker.make("2.0") do |maker|
- rss.channel.setup_maker(maker)
- rss.textinput.setup_maker(maker)
- end
-
- textInput = new_rss.channel.textInput
- assert_equal(title, textInput.title)
- assert_equal(description, textInput.description)
- assert_equal(name, textInput.name)
- assert_equal(link, textInput.link)
- end
-
- def test_setup_maker_items
- title = "TITLE"
- link = "http://hoge.com/"
- description = "text hoge fuga"
- author = "oprah@oxygen.net"
- comments = "http://www.myblog.org/cgi-local/mt/mt-comments.cgi?entry_id=290"
- pubDate = Time.now
-
- guid_isPermaLink = true
- guid_content = "http://inessential.com/2002/09/01.php#a2"
-
- enclosure_url = "http://www.scripting.com/mp3s/weatherReportSuite.mp3"
- enclosure_length = "12216320"
- enclosure_type = "audio/mpeg"
-
- source_url = "http://static.userland.com/tomalak/links2.xml"
- source_content = "Tomalak's Realm"
-
- category_domain = "http://www.fool.com/cusips"
- category_content = "MSFT"
-
- item_size = 5
-
- rss = RSS::Maker.make("2.0") do |maker|
- setup_dummy_channel(maker)
-
- item_size.times do |i|
- item = maker.items.new_item
- item.title = "#{title}#{i}"
- item.link = "#{link}#{i}"
- item.description = "#{description}#{i}"
- item.author = "#{author}#{i}"
- item.comments = "#{comments}#{i}"
- item.date = pubDate
-
- item.guid.isPermaLink = guid_isPermaLink
- item.guid.content = guid_content
-
- item.enclosure.url = enclosure_url
- item.enclosure.length = enclosure_length
- item.enclosure.type = enclosure_type
-
- item.source.url = source_url
- item.source.content = source_content
-
- category = item.categories.new_category
- category.domain = category_domain
- category.content = category_content
- end
- end
-
- new_rss = RSS::Maker.make("2.0") do |maker|
- rss.channel.setup_maker(maker)
-
- rss.items.each do |item|
- item.setup_maker(maker)
- end
- end
-
- assert_equal(item_size, new_rss.items.size)
- new_rss.items.each_with_index do |item, i|
- assert_equal("#{title}#{i}", item.title)
- assert_equal("#{link}#{i}", item.link)
- assert_equal("#{description}#{i}", item.description)
- assert_equal("#{author}#{i}", item.author)
- assert_equal("#{comments}#{i}", item.comments)
- assert_equal(pubDate, item.pubDate)
-
- assert_equal(guid_isPermaLink, item.guid.isPermaLink)
- assert_equal(guid_content, item.guid.content)
-
- assert_equal(enclosure_url, item.enclosure.url)
- assert_equal(enclosure_length, item.enclosure.length)
- assert_equal(enclosure_type, item.enclosure.type)
-
- assert_equal(source_url, item.source.url)
- assert_equal(source_content, item.source.content)
-
- assert_equal(1, item.categories.size)
- assert_equal(category_domain, item.category.domain)
- assert_equal(category_content, item.category.content)
- end
-
- end
-
- def test_setup_maker
- encoding = "EUC-JP"
- standalone = true
-
- href = 'a.xsl'
- type = 'text/xsl'
- title = 'sample'
- media = 'printer'
- charset = 'UTF-8'
- alternate = 'yes'
-
- rss = RSS::Maker.make("2.0") do |maker|
- maker.encoding = encoding
- maker.standalone = standalone
-
- xss = maker.xml_stylesheets.new_xml_stylesheet
- xss.href = href
- xss.type = type
- xss.title = title
- xss.media = media
- xss.charset = charset
- xss.alternate = alternate
-
- setup_dummy_channel(maker)
- end
-
- new_rss = RSS::Maker.make("2.0") do |maker|
- rss.setup_maker(maker)
- end
-
- assert_equal("2.0", new_rss.rss_version)
- assert_equal(encoding, new_rss.encoding)
- assert_equal(standalone, new_rss.standalone)
-
- xss = rss.xml_stylesheets.first
- assert_equal(1, rss.xml_stylesheets.size)
- assert_equal(href, xss.href)
- assert_equal(type, xss.type)
- assert_equal(title, xss.title)
- assert_equal(media, xss.media)
- assert_equal(charset, xss.charset)
- assert_equal(alternate, xss.alternate)
- end
-
- end
-end
diff --git a/test/rss/test_to_s.rb b/test/rss/test_to_s.rb
deleted file mode 100644
index d6c761e7ef..0000000000
--- a/test/rss/test_to_s.rb
+++ /dev/null
@@ -1,440 +0,0 @@
-require "rexml/document"
-
-require "rss-testcase"
-
-require "rss/maker"
-require "rss/1.0"
-require "rss/2.0"
-require "rss/content"
-require "rss/dublincore"
-require "rss/syndication"
-require "rss/trackback"
-
-module RSS
- class TestToS < TestCase
-
- def setup
- @image_url = "http://example.com/foo.png"
- @textinput_link = "http://example.com/search.cgi"
- @item_links = [
- "http://example.com/1",
- "http://example.com/2",
- ]
-
- setup_xml_declaration_info
- setup_xml_stylesheet_infos
- setup_channel_info
- setup_item_infos
- setup_image_info
- setup_textinput_info
-
- setup_dublin_core_info
- setup_syndication_info
- setup_content_info
- setup_trackback_info
- end
-
- def test_to_s_10
- rss = RSS::Maker.make("1.0") do |maker|
- setup_full(maker)
- end
-
- assert_xml_declaration(@version, @encoding, @standalone, rss)
- assert_xml_stylesheets(@xs_infos, rss.xml_stylesheets)
- assert_channel10(@channel_info, rss.channel)
- assert_items10(@item_infos, rss.items)
- rss.items.each do |item|
- assert_trackback(@trackback_info, item)
- end
- assert_image10(@image_info, rss.image)
- assert_textinput10(@textinput_info, rss.textinput)
-
- rss = RSS::Parser.parse(rss.to_s)
-
- assert_xml_declaration(@version, @encoding, @standalone, rss)
- assert_xml_stylesheets(@xs_infos, rss.xml_stylesheets)
- assert_channel10(@channel_info, rss.channel)
- assert_items10(@item_infos, rss.items)
- assert_image10(@image_info, rss.image)
- assert_textinput10(@textinput_info, rss.textinput)
- end
-
- def test_to_s_09
- rss = RSS::Maker.make("0.91") do |maker|
- setup_full(maker)
- end
-
- assert_xml_declaration(@version, @encoding, @standalone, rss)
- assert_xml_stylesheets(@xs_infos, rss.xml_stylesheets)
- assert_channel09(@channel_info, rss.channel)
- assert_items09(@item_infos, rss.items)
- assert_image09(@image_info, rss.image)
- assert_textinput09(@textinput_info, rss.textinput)
-
- rss = RSS::Parser.parse(rss.to_s)
-
- assert_xml_declaration(@version, @encoding, @standalone, rss)
- assert_xml_stylesheets(@xs_infos, rss.xml_stylesheets)
- assert_channel09(@channel_info, rss.channel)
- assert_items09(@item_infos, rss.items)
- assert_image09(@image_info, rss.image)
- assert_textinput09(@textinput_info, rss.textinput)
- end
-
- def test_to_s_20
- rss = RSS::Maker.make("2.0") do |maker|
- setup_full(maker)
- end
-
- assert_xml_declaration(@version, @encoding, @standalone, rss)
- assert_xml_stylesheets(@xs_infos, rss.xml_stylesheets)
- assert_channel20(@channel_info, rss.channel)
- assert_items20(@item_infos, rss.items)
- assert_image20(@image_info, rss.image)
- assert_textinput20(@textinput_info, rss.textinput)
-
- rss = RSS::Parser.parse(rss.to_s)
-
- assert_xml_declaration(@version, @encoding, @standalone, rss)
- assert_xml_stylesheets(@xs_infos, rss.xml_stylesheets)
- assert_channel20(@channel_info, rss.channel)
- assert_items20(@item_infos, rss.items)
- assert_image20(@image_info, rss.image)
- assert_textinput20(@textinput_info, rss.textinput)
- end
-
- private
- def setup_xml_declaration_info
- @version = "1.0"
- @encoding = "UTF-8"
- @standalone = false
- end
-
- def setup_xml_stylesheet_infos
- @xs_infos = [
- {
- "href" => "XXX.xsl",
- "type" => "text/xsl",
- "title" => "XXX",
- "media" => "print",
- "alternate" => "no",
- },
- {
- "href" => "YYY.css",
- "type" => "text/css",
- "title" => "YYY",
- "media" => "all",
- "alternate" => "no",
- },
- ]
- end
-
- def setup_channel_info
- @channel_info = {
- "about" => "http://example.com/index.rdf",
- "title" => "Sample RSS",
- "link" => "http://example.com/",
- "description" => "Sample\n\n\n\n\nSite",
- "language" => "en",
- "copyright" => "FDL",
- "managingEditor" => "foo@example.com",
- "webMaster" => "webmaster@example.com",
- "rating" => '(PICS-1.1 "http://www.rsac.org/ratingsv01.html" l gen true comment "RSACi North America Server" for "http://www.rsac.org" on "1996.04.16T08:15-0500" r (n 0 s 0 v 0 l 0))',
- "docs" => "http://backend.userland.com/rss091",
- "skipDays" => [
- "Monday",
- "Friday",
- ],
- "skipHours" => [
- 12,
- 23,
- ],
- "date" => Time.now,
- "lastBuildDate" => Time.now - 3600,
- "generator" => "RSS Maker",
- "ttl" => 60,
- "cloud" => {
- "domain" => "rpc.sys.com",
- "port" => "80",
- "path" => "/RPC2",
- "registerProcedure" => "myCloud.rssPleaseNotify",
- "protocol" => "xml-rpc",
- },
- "category" => {
- "domain" => "http://example.com/misc/",
- "content" => "misc",
- },
-
- "image" => {
- "resource" => @image_url,
- },
-
- "textinput" => {
- "resource" => @textinput_link,
- },
-
- "items" => @item_links.collect{|link| {"resource" => link}},
- }
- end
-
- def setup_item_infos
- @item_infos = [
- {
- "title" => "Sample item1",
- "link" => @item_links[0],
- "description" => "Sample description1",
- "date" => Time.now - 3600,
- "author" => "foo@example.com",
- "comments" => "http://example.com/1/comments",
- "guid" => {
- "isPermaLink" => "ture",
- "content" => "http://example.com/1",
- },
- "enclosure" => {
- "url" => "http://example.com/1.mp3",
- "length" => "100",
- "type" => "audio/mpeg",
- },
- "source" => {
- "url" => "http:/example.com/",
- "content" => "Sample site",
- },
- "category" => {
- "domain" => "http://example.com/misc/",
- "content" => "misc",
- },
- },
-
- {
- "title" => "Sample item2",
- "link" => @item_links[1],
- "description" => "Sample description2",
- "date" => Time.now - 7200,
- "author" => "foo@example.com",
- "comments" => "http://example.com/2/comments",
- "guid" => {
- "isPermaLink" => "false",
- "content" => "http://example.com/2",
- },
- "enclosure" => {
- "url" => "http://example.com/2.mp3",
- "length" => "200",
- "type" => "audio/mpeg",
- },
- "source" => {
- "url" => "http:/example.com/",
- "content" => "Sample site",
- },
- "category" => {
- "domain" => "http://example.com/misc/",
- "content" => "misc",
- },
- },
- ]
- end
-
- def setup_image_info
- @image_info = {
- "title" => "Sample image",
- "url" => @image_url,
- "width" => "88",
- "height" => "31",
- "description" => "Sample",
- }
- end
-
- def setup_textinput_info
- @textinput_info = {
- "title" => "Sample textinput",
- "description" => "Search",
- "name" => "key",
- "link" => @textinput_link,
- }
- end
-
- def setup_dublin_core_info
- @dc_info = {
- "title" => "DC title",
- "description" => "DC desc",
- "creator" => "DC creator",
- "subject" => "DC subject",
- "publisher" => "DC publisher",
- "contributor" => "DC contributor",
- "type" => "DC type",
- "format" => "DC format",
- "identifier" => "DC identifier",
- "source" => "DC source",
- "language" => "ja",
- "relation" => "DC relation",
- "coverage" => "DC coverage",
- "rights" => "DC rights",
- "date" => Time.now - 60,
- }
- end
-
- def setup_syndication_info
- @sy_info = {
- "updatePeriod" => "hourly",
- "updateFrequency" => 2,
- "updateBase" => Time.now - 3600,
- }
- end
-
- def setup_content_info
- @content_info = {
- "encoded" => "<p>p</p>",
- }
- end
-
- def setup_trackback_info
- @trackback_info = {
- "ping" => "http://example.com/tb.cgi?tb_id=XXX",
- "abouts" => [
- "http://example.net/tb.cgi?tb_id=YYY",
- "http://example.org/tb.cgi?tb_id=ZZZ",
- ]
- }
- end
-
-
- def setup_full(maker)
- setup_xml_declaration(maker)
- setup_xml_stylesheets(maker)
- setup_channel(maker)
- setup_image(maker)
- setup_items(maker)
- setup_textinput(maker)
- end
-
- def setup_xml_declaration(maker)
- %w(version encoding standalone).each do |name|
- maker.__send__("#{name}=", instance_eval("@#{name}"))
- end
- end
-
- def setup_xml_stylesheets(maker)
- @xs_infos.each do |info|
- xs = maker.xml_stylesheets.new_xml_stylesheet
- info.each do |name, value|
- xs.__send__("#{name}=", value)
- end
- end
- end
-
- def setup_channel(maker)
- channel = maker.channel
- info = @channel_info
-
- %w(about title link description language copyright
- managingEditor webMaster rating docs date
- lastBuildDate generator ttl).each do |name|
- channel.__send__("#{name}=", info[name])
- end
-
- skipDays = channel.skipDays
- info["skipDays"].each do |day|
- new_day = skipDays.new_day
- new_day.content = day
- end
-
- skipHours = channel.skipHours
- info["skipHours"].each do |hour|
- new_hour = skipHours.new_hour
- new_hour.content = hour
- end
-
- cloud = channel.cloud
- %w(domain port path registerProcedure protocol).each do |name|
- cloud.__send__("#{name}=", info["cloud"][name])
- end
-
- category = channel.categories.new_category
- %w(domain content).each do |name|
- category.__send__("#{name}=", info["category"][name])
- end
- end
-
- def setup_image(maker)
- image = maker.image
- info = @image_info
-
- %w(title url width height description).each do |name|
- image.__send__("#{name}=", info[name])
- end
- end
-
- def setup_items(maker)
- items = maker.items
-
- @item_infos.each do |info|
- item = items.new_item
- %w(title link description date author comments).each do |name|
- item.__send__("#{name}=", info[name])
- end
-
- guid = item.guid
- %w(isPermaLink content).each do |name|
- guid.__send__("#{name}=", info["guid"][name])
- end
-
- enclosure = item.enclosure
- %w(url length type).each do |name|
- enclosure.__send__("#{name}=", info["enclosure"][name])
- end
-
- source = item.source
- %w(url content).each do |name|
- source.__send__("#{name}=", info["source"][name])
- end
-
- category = item.categories.new_category
- %w(domain content).each do |name|
- category.__send__("#{name}=", info["category"][name])
- end
-
- setup_trackback(item)
- end
- end
-
- def setup_textinput(maker)
- textinput = maker.textinput
- info = @textinput_info
-
- %w(title description name link).each do |name|
- textinput.__send__("#{name}=", info[name])
- end
- end
-
- def setup_content(target)
- prefix = "content"
- %w(encoded).each do |name|
- target.__send__("#{prefix}_#{name}=", @content_info[name])
- end
- end
-
- def setup_dublin_core(target)
- prefix = "dc"
- %w(title description creator subject publisher
- contributor type format identifier source language
- relation coverage rights).each do |name|
- target.__send__("#{prefix}_#{name}=", @dc_info[name])
- end
- end
-
- def setup_syndicate(target)
- prefix = "sy"
- %w(updatePeriod updateFrequency updateBase).each do |name|
- target.__send__("#{prefix}_#{name}=", @sy_info[name])
- end
- end
-
- def setup_trackback(target)
- target.trackback_ping = @trackback_info["ping"]
- @trackback_info["abouts"].each do |about|
- new_about = target.trackback_abouts.new_about
- new_about.value = about
- end
- end
-
- end
-end
diff --git a/test/rss/test_trackback.rb b/test/rss/test_trackback.rb
index a3f023e887..bfe39d005b 100644
--- a/test/rss/test_trackback.rb
+++ b/test/rss/test_trackback.rb
@@ -88,19 +88,19 @@ EOR
@elems.each do |name, value|
@parents.each do |parent|
accessor = "#{RSS::TRACKBACK_PREFIX}_#{name}"
- target = @rss.send(parent)
+ target_accessor = "resource"
+ target = @rss.send(parent).send(accessor)
target20 = @rss20.channel.send(parent, -1)
- assert_equal(value, target.send(accessor))
+ assert_equal(value, target.send(target_accessor))
assert_equal(value, target20.send(accessor))
+ target.send("#{target_accessor}=", new_value[name].to_s)
if name == :about
# abount is zero or more
- target.send("#{accessor}=", 0, new_value[name].to_s)
target20.send("#{accessor}=", 0, new_value[name].to_s)
else
- target.send("#{accessor}=", new_value[name].to_s)
target20.send("#{accessor}=", new_value[name].to_s)
end
- assert_equal(new_value[name], target.send(accessor))
+ assert_equal(new_value[name], target.send(target_accessor))
assert_equal(new_value[name], target20.send(accessor))
end
end
diff --git a/test/rss/test_version.rb b/test/rss/test_version.rb
deleted file mode 100644
index dbed60b4d8..0000000000
--- a/test/rss/test_version.rb
+++ /dev/null
@@ -1,9 +0,0 @@
-require "rss-testcase"
-
-module RSS
- class TestVersion < TestCase
- def test_version
- assert_equal("0.1.5", ::RSS::VERSION)
- end
- end
-end
diff --git a/test/rss/test_xml-stylesheet.rb b/test/rss/test_xml-stylesheet.rb
index c88a858f56..ab16d6e2ff 100644
--- a/test/rss/test_xml-stylesheet.rb
+++ b/test/rss/test_xml-stylesheet.rb
@@ -14,7 +14,7 @@ module RSS
{:media => "print", :title => "FOO"},
{:charset => "UTF-8", :alternate => "yes"},
].each do |attrs|
- assert_xml_stylesheet_attrs(attrs, XMLStyleSheet.new(*attrs))
+ assert_xml_stylesheet_attrs(XMLStyleSheet.new(*attrs), attrs)
end
end
@@ -36,7 +36,7 @@ module RSS
:alternate => "yes"},
].each do |attrs|
target, contents = parse_pi(XMLStyleSheet.new(*attrs).to_s)
- assert_xml_stylesheet(target, attrs, XMLStyleSheet.new(*contents))
+ assert_xml_stylesheet(target, XMLStyleSheet.new(*contents), attrs)
end
end
@@ -88,7 +88,7 @@ module RSS
assert_equal(have_href_xsss.size, rss.xml_stylesheets.size)
rss.xml_stylesheets.each_with_index do |stylesheet, i|
target, = parse_pi(stylesheet.to_s)
- assert_xml_stylesheet(target, have_href_xsss[i], stylesheet)
+ assert_xml_stylesheet(target, stylesheet, have_href_xsss[i])
end
end
end
diff --git a/test/ruby/beginmainend.rb b/test/ruby/beginmainend.rb
index 646140dd22..f096b96fbc 100644
--- a/test/ruby/beginmainend.rb
+++ b/test/ruby/beginmainend.rb
@@ -28,6 +28,11 @@ END {
puts local_for_end2 # e2
}
+END {
+ raise
+ puts "should not be dumped"
+}
+
eval <<EOE
BEGIN {
puts "b3"
diff --git a/test/ruby/envutil.rb b/test/ruby/envutil.rb
index 09c8e3f7f4..4bae3d9e3b 100644
--- a/test/ruby/envutil.rb
+++ b/test/ruby/envutil.rb
@@ -1,8 +1,5 @@
module EnvUtil
def rubybin
- if ruby = ENV["RUBY"]
- return ruby
- end
miniruby = "miniruby"
3.times do
if File.exist? miniruby or File.exist? miniruby+".exe"
diff --git a/test/ruby/test_array.rb b/test/ruby/test_array.rb
index 95cc5a5a58..3e63dd2f54 100644
--- a/test/ruby/test_array.rb
+++ b/test/ruby/test_array.rb
@@ -98,14 +98,4 @@ class TestArray < Test::Unit::TestCase
x.concat(x)
assert_equal([1,2,3,1,2,3], x)
end
-
- def test_find_all
- assert_respond_to([], :find_all)
- assert_respond_to([], :select) # Alias
- assert_equal([], [].find_all{ |obj| obj == "foo"})
-
- x = ["foo", "bar", "baz", "baz", 1, 2, 3, 3, 4]
- assert_equal(["baz","baz"], x.find_all{ |obj| obj == "baz" })
- assert_equal([3,3], x.find_all{ |obj| obj == 3 })
- end
end
diff --git a/test/ruby/test_env.rb b/test/ruby/test_env.rb
index 3a65f91fa4..edc7dcaf61 100644
--- a/test/ruby/test_env.rb
+++ b/test/ruby/test_env.rb
@@ -4,13 +4,15 @@ class TestEnv < Test::Unit::TestCase
IGNORE_CASE = /djgpp|bccwin|mswin|mingw/ =~ RUBY_PLATFORM
def setup
- @backup = ENV.delete('test')
- @BACKUP = ENV.delete('TEST')
+ @backup = ENV['test']
+ @BACKUP = ENV['TEST']
+ ENV['test'] = nil
+ ENV['TEST'] = nil
end
def teardown
- ENV['test'] = @backup if @backup
- ENV['TEST'] = @BACKUP if @BACKUP
+ ENV['test'] = @backup
+ ENV['TEST'] = @BACKUP
end
def test_bracket
diff --git a/test/ruby/test_file.rb b/test/ruby/test_file.rb
index 2458dde347..4c30373bcf 100644
--- a/test/ruby/test_file.rb
+++ b/test/ruby/test_file.rb
@@ -50,11 +50,11 @@ class TestFile < Test::Unit::TestCase
def test_truncate_wbuf # [ruby-dev:24191]
f = Tempfile.new("test-truncate")
- f.print "abc"
+ f.puts "abc"
f.truncate(0)
- f.print "def"
+ f.puts "def"
f.close
- assert_equal("\0\0\0def", File.read(f.path))
+ assert_equal("\0\0\0\0def\n", File.read(f.path))
end
def test_truncate_rbuf # [ruby-dev:24197]
@@ -67,42 +67,4 @@ class TestFile < Test::Unit::TestCase
f.truncate(3)
assert_equal(nil, f.gets)
end
-
- def test_read_all_extended_file
- f = Tempfile.new("test-extended-file")
- assert_nil(f.getc)
- open(f.path, "w") {|g| g.print "a" }
- assert_equal("a", f.read)
- end
-
- def test_gets_extended_file
- f = Tempfile.new("test-extended-file")
- assert_nil(f.getc)
- open(f.path, "w") {|g| g.print "a" }
- assert_equal("a", f.gets("a"))
- end
-
- def test_gets_para_extended_file
- f = Tempfile.new("test-extended-file")
- assert_nil(f.getc)
- open(f.path, "w") {|g| g.print "\na" }
- assert_equal("a", f.gets(""))
- end
-
- def test_each_byte_extended_file
- f = Tempfile.new("test-extended-file")
- assert_nil(f.getc)
- open(f.path, "w") {|g| g.print "a" }
- result = []
- f.each_byte {|b| result << b }
- assert_equal([?a], result)
- end
-
- def test_getc_extended_file
- f = Tempfile.new("test-extended-file")
- assert_nil(f.getc)
- open(f.path, "w") {|g| g.print "a" }
- assert_equal(?a, f.getc)
- end
-
end
diff --git a/test/ruby/test_iterator.rb b/test/ruby/test_iterator.rb
index 638916309e..f3c2201e0a 100644
--- a/test/ruby/test_iterator.rb
+++ b/test/ruby/test_iterator.rb
@@ -189,20 +189,6 @@ class TestIterator < Test::Unit::TestCase
assert(!m2())
end
- def m3(var, &block)
- m(yield(var), &block)
- end
-
- def m4(&block)
- m(m1(), &block)
- end
-
- def test_block_passing
- assert(!m4())
- assert(!m4 {})
- assert_equal(100, m3(10) {|x|x*x})
- end
-
class C
include Enumerable
def initialize
diff --git a/test/ruby/test_method.rb b/test/ruby/test_method.rb
deleted file mode 100644
index c30705cb15..0000000000
--- a/test/ruby/test_method.rb
+++ /dev/null
@@ -1,42 +0,0 @@
-require 'test/unit'
-
-class TestMethod < Test::Unit::TestCase
- def m0() end
- def m1(a) end
- def m2(a, b) end
- def mo1(a = nil, &b) end
- def mo2(a, b = nil) end
- def mo3(*a) end
- def mo4(a, *b, &c) end
-
- class Base
- def foo() :base end
- end
- class Derived < Base
- def foo() :derived end
- end
-
- def test_arity
- assert_equal(0, method(:m0).arity)
- assert_equal(1, method(:m1).arity)
- assert_equal(2, method(:m2).arity)
- assert_equal(-1, method(:mo1).arity)
- assert_equal(-2, method(:mo2).arity)
- assert_equal(-1, method(:mo3).arity)
- assert_equal(-2, method(:mo4).arity)
- end
-
- def test_unbind
- assert_equal(:derived, Derived.new.foo)
- um = Derived.new.method(:foo).unbind
- assert_instance_of(UnboundMethod, um)
- Derived.class_eval do
- def foo() :changed end
- end
- assert_equal(:changed, Derived.new.foo)
- assert_equal(:derived, um.bind(Derived.new).call)
- assert_raise(TypeError) do
- um.bind(Base.new)
- end
- end
-end
diff --git a/test/ruby/test_pack.rb b/test/ruby/test_pack.rb
index a9f15599e4..083111aace 100644
--- a/test/ruby/test_pack.rb
+++ b/test/ruby/test_pack.rb
@@ -16,42 +16,4 @@ class TestPack < Test::Unit::TestCase
$x = [-1073741825]
assert_equal($x, $x.pack("q").unpack("q"))
end
-
- def test_pack_N
- assert_equal "\000\000\000\000", [0].pack('N')
- assert_equal "\000\000\000\001", [1].pack('N')
- assert_equal "\000\000\000\002", [2].pack('N')
- assert_equal "\000\000\000\003", [3].pack('N')
- assert_equal "\377\377\377\376", [4294967294].pack('N')
- assert_equal "\377\377\377\377", [4294967295].pack('N')
-
- assert_equal "\200\000\000\000", [2**31].pack('N')
- assert_equal "\177\377\377\377", [-2**31-1].pack('N')
- assert_equal "\377\377\377\377", [-1].pack('N')
-
- assert_equal "\000\000\000\001\000\000\000\001", [1,1].pack('N*')
- assert_equal "\000\000\000\001\000\000\000\001\000\000\000\001", [1,1,1].pack('N*')
- end
-
- def test_unpack_N
- assert_equal 1, "\000\000\000\001".unpack('N')[0]
- assert_equal 2, "\000\000\000\002".unpack('N')[0]
- assert_equal 3, "\000\000\000\003".unpack('N')[0]
- assert_equal 3, "\000\000\000\003".unpack('N')[0]
- assert_equal 4294967295, "\377\377\377\377".unpack('N')[0]
- assert_equal [1,1], "\000\000\000\001\000\000\000\001".unpack('N*')
- assert_equal [1,1,1], "\000\000\000\001\000\000\000\001\000\000\000\001".unpack('N*')
- end
-
- def test_pack_U
- assert_raises(RangeError) { [-0x40000001].pack("U") }
- assert_raises(RangeError) { [-0x40000000].pack("U") }
- assert_raises(RangeError) { [-1].pack("U") }
- assert_equal "\000", [0].pack("U")
- assert_equal "\374\277\277\277\277\277", [0x3fffffff].pack("U")
- assert_equal "\375\200\200\200\200\200", [0x40000000].pack("U")
- assert_equal "\375\277\277\277\277\277", [0x7fffffff].pack("U")
- assert_raises(RangeError) { [0x80000000].pack("U") }
- assert_raises(RangeError) { [0x100000000].pack("U") }
- end
end
diff --git a/test/ruby/test_rand.rb b/test/ruby/test_rand.rb
deleted file mode 100644
index e2fd127f9c..0000000000
--- a/test/ruby/test_rand.rb
+++ /dev/null
@@ -1,131 +0,0 @@
-require 'test/unit'
-
-class TestRand < Test::Unit::TestCase
- def test_mt
- srand(0x00000456_00000345_00000234_00000123)
- %w(1067595299 955945823 477289528 4107218783 4228976476).each {|w|
- assert_equal(w.to_i, rand(0x100000000))
- }
- end
-
- def test_0x3fffffff
- srand(0)
- %w(209652396 398764591 924231285 404868288 441365315).each {|w|
- assert_equal(w.to_i, rand(0x3fffffff))
- }
- end
-
- def test_0x40000000
- srand(0)
- %w(209652396 398764591 924231285 404868288 441365315).each {|w|
- assert_equal(w.to_i, rand(0x40000000))
- }
- end
-
- def test_0x40000001
- srand(0)
- %w(209652396 398764591 924231285 441365315 192771779).each {|w|
- assert_equal(w.to_i, rand(0x40000001))
- }
- end
-
- def test_0xffffffff
- srand(0)
- %w(2357136044 2546248239 3071714933 3626093760 2588848963).each {|w|
- assert_equal(w.to_i, rand(0xffffffff))
- }
- end
-
- def test_0x100000000
- srand(0)
- %w(2357136044 2546248239 3071714933 3626093760 2588848963).each {|w|
- assert_equal(w.to_i, rand(0x100000000))
- }
- end
-
- def test_0x100000001
- srand(0)
- %w(2546248239 1277901399 243580376 1171049868 2051556033).each {|w|
- assert_equal(w.to_i, rand(0x100000001))
- }
- end
-
- def test_rand_0x100000000
- srand(311702798)
- %w(4119812344 3870378946 80324654 4294967296 410016213).each {|w|
- assert_equal(w.to_i, rand(0x100000001))
- }
- end
-
- def test_0x1000000000000
- srand(0)
- %w(11736396900911
- 183025067478208
- 197104029029115
- 130583529618791
- 180361239846611).each {|w|
- assert_equal(w.to_i, rand(0x1000000000000))
- }
- end
-
- def test_0x1000000000001
- srand(0)
- %w(187121911899765
- 197104029029115
- 180361239846611
- 236336749852452
- 208739549485656).each {|w|
- assert_equal(w.to_i, rand(0x1000000000001))
- }
- end
-
- def test_0x3fffffffffffffff
- srand(0)
- %w(900450186894289455
- 3969543146641149120
- 1895649597198586619
- 827948490035658087
- 3203365596207111891).each {|w|
- assert_equal(w.to_i, rand(0x3fffffffffffffff))
- }
- end
-
- def test_0x4000000000000000
- srand(0)
- %w(900450186894289455
- 3969543146641149120
- 1895649597198586619
- 827948490035658087
- 3203365596207111891).each {|w|
- assert_equal(w.to_i, rand(0x4000000000000000))
- }
- end
-
- def test_0x4000000000000001
- srand(0)
- %w(900450186894289455
- 3969543146641149120
- 1895649597198586619
- 827948490035658087
- 2279347887019741461).each {|w|
- assert_equal(w.to_i, rand(0x4000000000000001))
- }
- end
-
- def test_neg_0x10000000000
- ws = %w(455570294424 1073054410371 790795084744 2445173525 1088503892627)
- srand(3)
- ws.each {|w| assert_equal(w.to_i, rand(0x10000000000)) }
- srand(3)
- ws.each {|w| assert_equal(w.to_i, rand(-0x10000000000)) }
- end
-
- def test_neg_0x10000
- ws = %w(2732 43567 42613 52416 45891)
- srand(0)
- ws.each {|w| assert_equal(w.to_i, rand(0x10000)) }
- srand(0)
- ws.each {|w| assert_equal(w.to_i, rand(-0x10000)) }
- end
-
-end
diff --git a/test/ruby/test_range.rb b/test/ruby/test_range.rb
index 455175087d..66ed555887 100644
--- a/test/ruby/test_range.rb
+++ b/test/ruby/test_range.rb
@@ -8,10 +8,4 @@ class TestRange < Test::Unit::TestCase
assert_equal(["a"], ("a" ... "b").to_a)
assert_equal(["a", "b"], ("a" .. "b").to_a)
end
-
- def test_evaluation_order
- arr = [1,2]
- r = (arr.shift)..(arr.shift)
- assert_equal(1..2, r, "[ruby-dev:26383]")
- end
end
diff --git a/test/ruby/test_readpartial.rb b/test/ruby/test_readpartial.rb
deleted file mode 100644
index 3877e21f85..0000000000
--- a/test/ruby/test_readpartial.rb
+++ /dev/null
@@ -1,74 +0,0 @@
-require 'test/unit'
-require 'timeout'
-require 'fcntl'
-
-class TestReadPartial < Test::Unit::TestCase
- def make_pipe
- r, w = IO.pipe
- begin
- yield r, w
- ensure
- r.close unless r.closed?
- w.close unless w.closed?
- end
- end
-
- def pipe
- make_pipe {|r, w|
- yield r, w
- }
- return unless defined?(Fcntl::F_SETFL)
- return unless defined?(Fcntl::F_GETFL)
- return unless defined?(Fcntl::O_NONBLOCK)
- make_pipe {|r, w|
- r.fcntl(Fcntl::F_SETFL, r.fcntl(Fcntl::F_GETFL) | Fcntl::O_NONBLOCK)
- yield r, w
- }
- end
-
- def test_length_zero
- pipe {|r, w|
- assert_equal('', r.readpartial(0))
- }
- end
-
- def test_closed_pipe
- pipe {|r, w|
- w << 'abc'
- w.close
- assert_equal('ab', r.readpartial(2))
- assert_equal('c', r.readpartial(2))
- assert_raises(EOFError) { r.readpartial(2) }
- assert_raises(EOFError) { r.readpartial(2) }
- }
- end
-
- if !File::ALT_SEPARATOR # read on pipe cannot timeout on Windows.
- def test_open_pipe
- pipe {|r, w|
- w << 'abc'
- assert_equal('ab', r.readpartial(2))
- assert_equal('c', r.readpartial(2))
- assert_raises(TimeoutError) {
- timeout(0.1) { r.readpartial(2) }
- }
- }
- end
-
- def test_with_stdio
- pipe {|r, w|
- w << "abc\ndef\n"
- assert_equal("abc\n", r.gets)
- w << "ghi\n"
- assert_equal("de", r.readpartial(2))
- assert_equal("f\n", r.readpartial(4096))
- assert_equal("ghi\n", r.readpartial(4096))
- assert_raises(TimeoutError) {
- timeout(0.1) { r.readpartial(2) }
- }
- }
- end
- end
-
-end
-
diff --git a/test/ruby/test_settracefunc.rb b/test/ruby/test_settracefunc.rb
deleted file mode 100644
index 39e1b035d8..0000000000
--- a/test/ruby/test_settracefunc.rb
+++ /dev/null
@@ -1,138 +0,0 @@
-require 'test/unit'
-
-class TestSetTraceFunc < Test::Unit::TestCase
- def foo; end;
-
- def bar
- events = []
- set_trace_func(Proc.new { |event, file, lineno, mid, bidning, klass|
- events << [event, lineno, mid, klass]
- })
- return events
- end
-
- def test_event
- events = []
- set_trace_func(Proc.new { |event, file, lineno, mid, bidning, klass|
- events << [event, lineno, mid, klass]
- })
- a = 1
- foo
- a
- b = 1 + 2
- if b == 3
- case b
- when 2
- c = "b == 2"
- when 3
- c = "b == 3"
- end
- end
- begin
- raise "error"
- rescue
- end
- eval("class Foo; end")
- set_trace_func nil
-
- assert_equal(["line", 19, :test_event, TestSetTraceFunc],
- events.shift) # a = 1
- assert_equal(["line", 20, :test_event, TestSetTraceFunc],
- events.shift) # foo
- assert_equal(["call", 4, :foo, TestSetTraceFunc],
- events.shift) # foo
- assert_equal(["return", 4, :foo, TestSetTraceFunc],
- events.shift) # foo
- assert_equal(["line", 21, :test_event, TestSetTraceFunc],
- events.shift) # a
- assert_equal(["line", 22, :test_event, TestSetTraceFunc],
- events.shift) # b = 1 + 2
- assert_equal(["c-call", 22, :+, Fixnum],
- events.shift) # 1 + 2
- assert_equal(["c-return", 22, :+, Fixnum],
- events.shift) # 1 + 2
- assert_equal(["line", 23, :test_event, TestSetTraceFunc],
- events.shift) # if b == 3
- assert_equal(["line", 23, :test_event, TestSetTraceFunc],
- events.shift) # if b == 3
- assert_equal(["c-call", 23, :==, Fixnum],
- events.shift) # b == 3
- assert_equal(["c-return", 23, :==, Fixnum],
- events.shift) # b == 3
- assert_equal(["line", 24, :test_event, TestSetTraceFunc],
- events.shift) # case b
- assert_equal(["line", 25, :test_event, TestSetTraceFunc],
- events.shift) # when 2
- assert_equal(["c-call", 25, :===, Kernel],
- events.shift) # when 2
- assert_equal(["c-call", 25, :==, Fixnum],
- events.shift) # when 2
- assert_equal(["c-return", 25, :==, Fixnum],
- events.shift) # when 2
- assert_equal(["c-return", 25, :===, Kernel],
- events.shift) # when 2
- assert_equal(["line", 27, :test_event, TestSetTraceFunc],
- events.shift) # when 3
- assert_equal(["c-call", 27, :===, Kernel],
- events.shift) # when 3
- assert_equal(["c-return", 27, :===, Kernel],
- events.shift) # when 3
- assert_equal(["line", 28, :test_event, TestSetTraceFunc],
- events.shift) # c = "b == 3"
- assert_equal(["line", 31, :test_event, TestSetTraceFunc],
- events.shift) # begin
- assert_equal(["line", 32, :test_event, TestSetTraceFunc],
- events.shift) # raise "error"
- assert_equal(["c-call", 32, :raise, Kernel],
- events.shift) # raise "error"
- assert_equal(["c-call", 32, :new, Class],
- events.shift) # raise "error"
- assert_equal(["c-call", 32, :initialize, Exception],
- events.shift) # raise "error"
- assert_equal(["c-return", 32, :initialize, Exception],
- events.shift) # raise "error"
- assert_equal(["c-return", 32, :new, Class],
- events.shift) # raise "error"
- assert_equal(["c-call", 32, :backtrace, Exception],
- events.shift) # raise "error"
- assert_equal(["c-return", 32, :backtrace, Exception],
- events.shift) # raise "error"
- assert_equal(["c-call", 32, :set_backtrace, Exception],
- events.shift) # raise "error"
- assert_equal(["c-return", 32, :set_backtrace, Exception],
- events.shift) # raise "error"
- assert_equal(["raise", 32, :test_event, TestSetTraceFunc],
- events.shift) # raise "error"
- assert_equal(["c-return", 32, :raise, Kernel],
- events.shift) # raise "error"
- assert_equal(["line", 35, :test_event, TestSetTraceFunc],
- events.shift) # eval(<<EOF)
- assert_equal(["c-call", 35, :eval, Kernel],
- events.shift) # eval(<<EOF)
- assert_equal(["line", 1, :test_event, TestSetTraceFunc],
- events.shift) # class Foo
- assert_equal(["c-call", 1, :inherited, Class],
- events.shift) # class Foo
- assert_equal(["c-return", 1, :inherited, Class],
- events.shift) # class Foo
- assert_equal(["class", 1, :test_event, TestSetTraceFunc],
- events.shift) # class Foo
- assert_equal(["end", 1, :test_event, TestSetTraceFunc],
- events.shift) # class Foo
- assert_equal(["c-return", 35, :eval, Kernel],
- events.shift) # eval(<<EOF)
- assert_equal(["line", 36, :test_event, TestSetTraceFunc],
- events.shift) # set_trace_func nil
- assert_equal(["c-call", 36, :set_trace_func, Kernel],
- events.shift) # set_trace_func nil
- assert_equal([], events)
-
- events = bar
- set_trace_func(nil)
- assert_equal(["line", 11, :bar, TestSetTraceFunc], events.shift)
- assert_equal(["return", 7, :bar, TestSetTraceFunc], events.shift)
- assert_equal(["line", 131, :test_event, TestSetTraceFunc], events.shift)
- assert_equal(["c-call", 131, :set_trace_func, Kernel], events.shift)
- assert_equal([], events)
- end
-end
diff --git a/test/ruby/test_signal.rb b/test/ruby/test_signal.rb
index 8daa1cfa21..d212f9fcc3 100644
--- a/test/ruby/test_signal.rb
+++ b/test/ruby/test_signal.rb
@@ -1,16 +1,6 @@
require 'test/unit'
-require 'timeout'
class TestSignal < Test::Unit::TestCase
- def have_fork?
- begin
- fork{}
- true
- rescue NotImplementedError
- false
- end
- end
-
def test_signal
defined?(Process.kill) or return
begin
@@ -32,37 +22,4 @@ class TestSignal < Test::Unit::TestCase
trap "SIGINT", oldtrap
end
end
-
- def test_exit_action
- return unless have_fork? # snip this test
- begin
- r, w = IO.pipe
- r0, w0 = IO.pipe
- pid = fork {
- trap(:USR1, "EXIT")
- w0.close
- w.syswrite("a")
- Thread.start { Thread.pass }
- r0.sysread(4096)
- }
- r.sysread(1)
- sleep 0.1
- assert_nothing_raised("[ruby-dev:26128]") {
- Process.kill(:USR1, pid)
- begin
- Timeout.timeout(1) {
- Process.waitpid pid
- }
- rescue Timeout::Error
- Process.kill(:TERM, pid)
- raise
- end
- }
- ensure
- r.close
- w.close
- r0.close
- w0.close
- end
- end
end
diff --git a/test/ruby/test_stringchar.rb b/test/ruby/test_stringchar.rb
index 34934e87bd..943b656510 100644
--- a/test/ruby/test_stringchar.rb
+++ b/test/ruby/test_stringchar.rb
@@ -113,54 +113,4 @@ EOS
}
assert_equal(0, a.size)
end
-
- def test_bang
- s = "aBc"
- s.upcase
- assert_equal("aBc", s)
- s.upcase!
- assert_equal("ABC", s)
-
- s = "aBc"
- s.downcase
- assert_equal("aBc", s)
- s.downcase!
- assert_equal("abc", s)
-
- s = "aBc"
- s.swapcase
- assert_equal("aBc", s)
- s.swapcase!
- assert_equal("AbC", s)
-
- s = "aBc"
- s.capitalize
- assert_equal("aBc", s)
- s.capitalize!
- assert_equal("Abc", s)
-
- s = "aBc"
- s.tr("a-z", "A-Z")
- assert_equal("aBc", s)
- s.tr!("a-z", "A-Z")
- assert_equal("ABC", s)
-
- s = "aaBBcc"
- s.tr_s("a-z", "A-Z")
- assert_equal("aaBBcc", s)
- s.tr_s!("a-z", "A-Z")
- assert_equal("ABBC", s)
-
- s = "aaBBcc"
- s.squeeze("a-z")
- assert_equal("aaBBcc", s)
- s.squeeze!("a-z")
- assert_equal("aBBc", s)
-
- s = "aaBBcc"
- s.delete("a-z")
- assert_equal("aaBBcc", s)
- s.delete!("a-z")
- assert_equal("BB", s)
- end
end
diff --git a/test/ruby/test_super.rb b/test/ruby/test_super.rb
deleted file mode 100644
index cf2e241fdd..0000000000
--- a/test/ruby/test_super.rb
+++ /dev/null
@@ -1,117 +0,0 @@
-require 'test/unit'
-
-class TestSuper < Test::Unit::TestCase
- class Base
- def single(a) a end
- def double(a, b) [a,b] end
- def array(*a) a end
- def optional(a = 0) a end
- end
- class Single1 < Base
- def single(*) super end
- end
- class Single2 < Base
- def single(a,*) super end
- end
- class Double1 < Base
- def double(*) super end
- end
- class Double2 < Base
- def double(a,*) super end
- end
- class Double3 < Base
- def double(a,b,*) super end
- end
- class Array1 < Base
- def array(*) super end
- end
- class Array2 < Base
- def array(a,*) super end
- end
- class Array3 < Base
- def array(a,b,*) super end
- end
- class Array4 < Base
- def array(a,b,c,*) super end
- end
- class Optional1 < Base
- def optional(a = 1) super end
- end
- class Optional2 < Base
- def optional(a, b = 1) super end
- end
- class Optional3 < Base
- def single(a = 1) super end
- end
-
- def test_single1
- assert_equal(1, Single1.new.single(1))
- end
- def test_single2
- assert_equal(1, Single2.new.single(1))
- end
- def test_double1
- assert_equal([1, 2], Double1.new.double(1, 2))
- end
- def test_double2
- assert_equal([1, 2], Double2.new.double(1, 2))
- end
- def test_double3
- assert_equal([1, 2], Double3.new.double(1, 2))
- end
- def test_array1
- assert_equal([], Array1.new.array())
- assert_equal([1], Array1.new.array(1))
- end
- def test_array2
- assert_equal([1], Array2.new.array(1))
- assert_equal([1,2], Array2.new.array(1, 2))
- end
- def test_array3
- assert_equal([1,2], Array3.new.array(1, 2))
- assert_equal([1,2,3], Array3.new.array(1, 2, 3))
- end
- def test_array4
- assert_equal([1,2,3], Array4.new.array(1, 2, 3))
- assert_equal([1,2,3,4], Array4.new.array(1, 2, 3, 4))
- end
- def test_optional1
- assert_equal(9, Optional1.new.optional(9))
- assert_equal(1, Optional1.new.optional)
- end
- def test_optional2
- assert_raise(ArgumentError) do
- # call Base#optional with 2 arguments; the 2nd arg is supplied
- assert_equal(9, Optional2.new.optional(9))
- end
- assert_raise(ArgumentError) do
- # call Base#optional with 2 arguments
- assert_equal(9, Optional2.new.optional(9, 2))
- end
- end
- def test_optional3
- assert_equal(9, Optional3.new.single(9))
- # call Base#single with 1 argument; the arg is supplied
- assert_equal(1, Optional3.new.single)
- end
-
- class A
- def tt(aa)
- "A#tt"
- end
-
- def uu(a)
- class << self
- define_method(:tt) do |sym|
- super
- end
- end
- end
- end
-
- def test_define_method # [ruby-core:03856]
- a = A.new
- a.uu(12)
- assert_equal("A#tt", a.tt(12))
- end
-end
diff --git a/test/ruby/test_symbol.rb b/test/ruby/test_symbol.rb
deleted file mode 100644
index b6dd203596..0000000000
--- a/test/ruby/test_symbol.rb
+++ /dev/null
@@ -1,50 +0,0 @@
-require 'test/unit'
-
-class TestSymbol < Test::Unit::TestCase
- # [ruby-core:3573]
-
- def assert_eval_inspected(sym)
- n = sym.inspect
- assert_nothing_raised(SyntaxError) {assert_equal(sym, eval(n))}
- end
-
- def test_inspect_invalid
- # 2) Symbol#inspect sometimes returns invalid symbol representations:
- assert_eval_inspected(:"!")
- assert_eval_inspected(:"=")
- assert_eval_inspected(:"0")
- assert_eval_inspected(:"$1")
- assert_eval_inspected(:"@1")
- assert_eval_inspected(:"@@1")
- assert_eval_inspected(:"@")
- assert_eval_inspected(:"@@")
- end
-
- def assert_inspect_evaled(n)
- assert_nothing_raised(SyntaxError) {assert_equal(n, eval(n).inspect)}
- end
-
- def test_inspect_suboptimal
- # 3) Symbol#inspect sometimes returns suboptimal symbol representations:
- assert_inspect_evaled(':foo')
- assert_inspect_evaled(':foo!')
- assert_inspect_evaled(':bar?')
- end
-
- def test_inspect_dollar
- # 4) :$- always treats next character literally:
- sym = "$-".intern
- assert_nothing_raised(SyntaxError) {assert_equal(sym, eval(':$-'))}
- assert_nothing_raised(SyntaxError) {assert_equal(sym, eval(":$-\n"))}
- assert_nothing_raised(SyntaxError) {assert_equal(sym, eval(":$- "))}
- assert_nothing_raised(SyntaxError) {assert_equal(sym, eval(":$-#"))}
- assert_raise(SyntaxError) {eval ':$-('}
- end
-
- def test_inspect_number
- # 5) Inconsistency between :$0 and :$1? The first one is valid, but the
- # latter isn't.
- assert_inspect_evaled(':$0')
- assert_inspect_evaled(':$1')
- end
-end
diff --git a/test/ruby/ut_eof.rb b/test/ruby/ut_eof.rb
index e6f6eddd6f..eff0bddc0b 100644
--- a/test/ruby/ut_eof.rb
+++ b/test/ruby/ut_eof.rb
@@ -83,19 +83,6 @@ module TestEOF
}
end
- def test_eof_2
- open_file("") {|f|
- assert_equal("", f.read)
- assert(f.eof?)
- }
- end
-
- def test_eof_3
- open_file("") {|f|
- assert(f.eof?)
- }
- end
-
module Seek
def open_file_seek(content, pos)
open_file(content) do |f|
diff --git a/test/runner.rb b/test/runner.rb
index d274bc8929..4ecc35aecc 100644
--- a/test/runner.rb
+++ b/test/runner.rb
@@ -4,4 +4,4 @@ rcsid = %w$Id$
Version = rcsid[2].scan(/\d+/).collect!(&method(:Integer)).freeze
Release = rcsid[3].freeze
-exit Test::Unit::AutoRunner.run(true, File.dirname($0))
+exit Test::Unit::AutoRunner.run(false, File.dirname($0))
diff --git a/test/soap/asp.net/hello.wsdl b/test/soap/asp.net/hello.wsdl
deleted file mode 100644
index b94129c152..0000000000
--- a/test/soap/asp.net/hello.wsdl
+++ /dev/null
@@ -1,96 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<wsdl:definitions xmlns:http="http://schemas.xmlsoap.org/wsdl/http/"
-xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/"
-xmlns:s="http://www.w3.org/2001/XMLSchema"
-xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/"
-xmlns:tns="http://localhost/WebService/"
-xmlns:tm="http://microsoft.com/wsdl/mime/textMatching/"
-xmlns:mime="http://schemas.xmlsoap.org/wsdl/mime/"
-targetNamespace="http://localhost/WebService/"
-xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/">
- <wsdl:types>
- <s:schema elementFormDefault="qualified"
-targetNamespace="http://localhost/WebService/">
- <s:element name="HelloWorld">
- <s:complexType />
- </s:element>
- <s:element name="HelloWorldResponse">
- <s:complexType>
- <s:sequence>
- <s:element minOccurs="0" maxOccurs="1"
-name="HelloWorldResult" type="s:string" />
- </s:sequence>
- </s:complexType>
- </s:element>
- <s:element name="SayHello">
- <s:complexType>
- <s:sequence>
- <s:element minOccurs="0" maxOccurs="1" name="name"
-type="s:string" />
- </s:sequence>
- </s:complexType>
- </s:element>
- <s:element name="SayHelloResponse">
- <s:complexType>
- <s:sequence>
- <s:element minOccurs="0" maxOccurs="1"
-name="SayHelloResult" type="s:string" />
- </s:sequence>
- </s:complexType>
- </s:element>
- </s:schema>
- </wsdl:types>
- <wsdl:message name="HelloWorldSoapIn">
- <wsdl:part name="parameters" element="tns:HelloWorld" />
- </wsdl:message>
- <wsdl:message name="HelloWorldSoapOut">
- <wsdl:part name="parameters" element="tns:HelloWorldResponse" />
- </wsdl:message>
- <wsdl:message name="SayHelloSoapIn">
- <wsdl:part name="parameters" element="tns:SayHello" />
- </wsdl:message>
- <wsdl:message name="SayHelloSoapOut">
- <wsdl:part name="parameters" element="tns:SayHelloResponse" />
- </wsdl:message>
- <wsdl:portType name="Service1Soap">
- <wsdl:operation name="HelloWorld">
- <wsdl:input message="tns:HelloWorldSoapIn" />
- <wsdl:output message="tns:HelloWorldSoapOut" />
- </wsdl:operation>
- <wsdl:operation name="SayHello">
- <wsdl:input message="tns:SayHelloSoapIn" />
- <wsdl:output message="tns:SayHelloSoapOut" />
- </wsdl:operation>
- </wsdl:portType>
- <wsdl:binding name="Service1Soap" type="tns:Service1Soap">
- <soap:binding transport="http://schemas.xmlsoap.org/soap/http"
-style="document" />
- <wsdl:operation name="HelloWorld">
- <soap:operation
-soapAction="http://localhost/WebService/HelloWorld" style="document" />
- <wsdl:input>
- <soap:body use="literal" />
- </wsdl:input>
- <wsdl:output>
- <soap:body use="literal" />
- </wsdl:output>
- </wsdl:operation>
- <wsdl:operation name="SayHello">
- <soap:operation soapAction="http://localhost/WebService/SayHello"
-style="document" />
- <wsdl:input>
- <soap:body use="literal" />
- </wsdl:input>
- <wsdl:output>
- <soap:body use="literal" />
- </wsdl:output>
- </wsdl:operation>
- </wsdl:binding>
- <wsdl:service name="Service1">
- <documentation xmlns="http://schemas.xmlsoap.org/wsdl/" />
- <wsdl:port name="Service1Soap" binding="tns:Service1Soap">
- <soap:address
-location="http://localhost/WebService/Service1.asmx" />
- </wsdl:port>
- </wsdl:service>
-</wsdl:definitions>
diff --git a/test/soap/asp.net/test_aspdotnet.rb b/test/soap/asp.net/test_aspdotnet.rb
deleted file mode 100644
index 7d5f3fd288..0000000000
--- a/test/soap/asp.net/test_aspdotnet.rb
+++ /dev/null
@@ -1,111 +0,0 @@
-require 'test/unit'
-require 'soap/rpc/standaloneServer'
-require 'soap/rpc/driver'
-
-
-module SOAP; module ASPDotNet
-
-
-class TestASPDotNet < Test::Unit::TestCase
- class Server < ::SOAP::RPC::StandaloneServer
- Namespace = "http://localhost/WebService/"
-
- def on_init
- add_document_method(
- self,
- Namespace + 'SayHello',
- 'sayHello',
- XSD::QName.new(Namespace, 'SayHello'),
- XSD::QName.new(Namespace, 'SayHelloResponse')
- )
- end
-
- def sayHello(arg)
- name = arg['name']
- "Hello #{name}"
- end
- end
-
- Port = 17171
- Endpoint = "http://localhost:#{Port}/"
-
- def setup
- setup_server
- @client = nil
- end
-
- def teardown
- teardown_server
- @client.reset_stream if @client
- end
-
- def setup_server
- @server = Server.new('Test', Server::Namespace, '0.0.0.0', Port)
- @server.level = Logger::Severity::ERROR
- @server_thread = start_server_thread(@server)
- end
-
- def teardown_server
- @server.shutdown
- @server_thread.kill
- @server_thread.join
- end
-
- def start_server_thread(server)
- t = Thread.new {
- Thread.current.abort_on_exception = true
- server.start
- }
- t
- end
-
- def test_document_method
- @client = SOAP::RPC::Driver.new(Endpoint, Server::Namespace)
- @client.wiredump_dev = STDOUT if $DEBUG
- @client.add_document_method('sayHello', Server::Namespace + 'SayHello',
- XSD::QName.new(Server::Namespace, 'SayHello'),
- XSD::QName.new(Server::Namespace, 'SayHelloResponse'))
- assert_equal("Hello Mike", @client.sayHello(:name => "Mike"))
- end
-
- def test_aspdotnethandler
- @client = SOAP::RPC::Driver.new(Endpoint, Server::Namespace)
- @client.wiredump_dev = STDOUT if $DEBUG
- @client.add_method_with_soapaction('sayHello', Server::Namespace + 'SayHello', 'name')
- @client.default_encodingstyle = SOAP::EncodingStyle::ASPDotNetHandler::Namespace
- assert_equal("Hello Mike", @client.sayHello("Mike"))
- end
-
- if defined?(HTTPAccess2)
-
- # qualified!
- REQUEST_ASPDOTNETHANDLER =
-%q[<?xml version="1.0" encoding="utf-8" ?>
-<env:Envelope xmlns:xsd="http://www.w3.org/2001/XMLSchema"
- xmlns:env="http://schemas.xmlsoap.org/soap/envelope/"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
- <env:Body>
- <n1:sayHello xmlns:n1="http://localhost/WebService/">
- <n1:name>Mike</n1:name>
- </n1:sayHello>
- </env:Body>
-</env:Envelope>]
-
- def test_aspdotnethandler_envelope
- @client = SOAP::RPC::Driver.new(Endpoint, Server::Namespace)
- @client.wiredump_dev = str = ''
- @client.add_method_with_soapaction('sayHello', Server::Namespace + 'SayHello', 'name')
- @client.default_encodingstyle = SOAP::EncodingStyle::ASPDotNetHandler::Namespace
- assert_equal("Hello Mike", @client.sayHello("Mike"))
- assert_equal(REQUEST_ASPDOTNETHANDLER, parse_requestxml(str))
- end
-
- def parse_requestxml(str)
- str.split(/\r?\n\r?\n/)[3]
- end
-
- end
-end
-
-
-end; end
diff --git a/test/soap/calc/calc2.rb b/test/soap/calc/calc2.rb
index 69495730e7..e9cf6bbca7 100644
--- a/test/soap/calc/calc2.rb
+++ b/test/soap/calc/calc2.rb
@@ -3,11 +3,11 @@ class CalcService2
@value = value
end
- def set_value(value)
+ def set(value)
@value = value
end
- def get_value
+ def get
@value
end
diff --git a/test/soap/calc/server2.rb b/test/soap/calc/server2.rb
index 01c6d75289..1c9eec68e8 100644
--- a/test/soap/calc/server2.rb
+++ b/test/soap/calc/server2.rb
@@ -6,8 +6,8 @@ require 'calc2'
class CalcServer2 < SOAP::RPC::StandaloneServer
def on_init
servant = CalcService2.new
- add_method(servant, 'set_value', 'newValue')
- add_method(servant, 'get_value')
+ add_method(servant, 'set', 'newValue')
+ add_method(servant, 'get')
add_method_as(servant, '+', 'add', 'lhs')
add_method_as(servant, '-', 'sub', 'lhs')
add_method_as(servant, '*', 'multi', 'lhs')
diff --git a/test/soap/calc/test_calc.rb b/test/soap/calc/test_calc.rb
index 88738716a6..4210c65772 100644
--- a/test/soap/calc/test_calc.rb
+++ b/test/soap/calc/test_calc.rb
@@ -16,6 +16,13 @@ class TestCalc < Test::Unit::TestCase
@t = Thread.new {
@server.start
}
+ while @server.status != :Running
+ sleep 0.1
+ unless @t.alive?
+ @t.join
+ raise
+ end
+ end
@endpoint = "http://localhost:#{Port}/"
@calc = SOAP::RPC::Driver.new(@endpoint, 'http://tempuri.org/calcService')
@calc.add_method('add', 'lhs', 'rhs')
diff --git a/test/soap/calc/test_calc2.rb b/test/soap/calc/test_calc2.rb
index f334b29bdb..d15cfe9600 100644
--- a/test/soap/calc/test_calc2.rb
+++ b/test/soap/calc/test_calc2.rb
@@ -17,11 +17,18 @@ class TestCalc2 < Test::Unit::TestCase
Thread.current.abort_on_exception = true
@server.start
}
+ while @server.status != :Running
+ sleep 0.1
+ unless @t.alive?
+ @t.join
+ raise
+ end
+ end
@endpoint = "http://localhost:#{Port}/"
@var = SOAP::RPC::Driver.new(@endpoint, 'http://tempuri.org/calcService')
@var.wiredump_dev = STDERR if $DEBUG
- @var.add_method('set_value', 'newValue')
- @var.add_method('get_value')
+ @var.add_method('set', 'newValue')
+ @var.add_method('get')
@var.add_method_as('+', 'add', 'rhs')
@var.add_method_as('-', 'sub', 'rhs')
@var.add_method_as('*', 'multi', 'rhs')
@@ -36,7 +43,7 @@ class TestCalc2 < Test::Unit::TestCase
end
def test_calc2
- assert_equal(1, @var.set_value(1))
+ assert_equal(1, @var.set(1))
assert_equal(3, @var + 2)
assert_equal(-1.2, @var - 2.2)
assert_equal(2.2, @var * 2.2)
diff --git a/test/soap/calc/test_calc_cgi.rb b/test/soap/calc/test_calc_cgi.rb
index d28830629f..d1655b0b01 100644
--- a/test/soap/calc/test_calc_cgi.rb
+++ b/test/soap/calc/test_calc_cgi.rb
@@ -35,6 +35,13 @@ class TestCalcCGI < Test::Unit::TestCase
Thread.current.abort_on_exception = true
@server.start
}
+ while @server.status != :Running
+ sleep 0.1
+ unless @t.alive?
+ @t.join
+ raise
+ end
+ end
@endpoint = "http://localhost:#{Port}/server.cgi"
@calc = SOAP::RPC::Driver.new(@endpoint, 'http://tempuri.org/calcService')
@calc.wiredump_dev = STDERR if $DEBUG
diff --git a/test/soap/fault/test_customfault.rb b/test/soap/fault/test_customfault.rb
deleted file mode 100644
index 2f7bc2be6e..0000000000
--- a/test/soap/fault/test_customfault.rb
+++ /dev/null
@@ -1,58 +0,0 @@
-require 'test/unit'
-require 'soap/rpc/driver'
-require 'soap/rpc/standaloneServer'
-
-
-module SOAP
-module Fault
-
-
-class TestCustomFault < Test::Unit::TestCase
- Port = 17171
-
- class CustomFaultServer < SOAP::RPC::StandaloneServer
- def on_init
- add_method(self, 'fault', 'msg')
- end
-
- def fault(msg)
- SOAPFault.new(SOAPString.new("mycustom"),
- SOAPString.new("error: #{msg}"),
- SOAPString.new(self.class.name))
- end
- end
-
- def setup
- @server = CustomFaultServer.new('customfault', 'urn:customfault', '0.0.0.0', Port)
- @server.level = Logger::Severity::ERROR
- @t = Thread.new {
- Thread.current.abort_on_exception = true
- @server.start
- }
- @endpoint = "http://localhost:#{Port}/"
- @client = SOAP::RPC::Driver.new(@endpoint, 'urn:customfault')
- @client.wiredump_dev = STDERR if $DEBUG
- @client.add_method("fault", "msg")
- end
-
- def teardown
- @server.shutdown
- @t.kill
- @t.join
- @client.reset_stream
- end
-
- def test_custom_fault
- begin
- @client.fault("message")
- assert(false, 'exception not raised')
- rescue SOAP::FaultError => e
- assert(true, 'exception raised')
- assert_equal('error: message', e.message)
- end
- end
-end
-
-
-end
-end
diff --git a/test/soap/header/server.cgi b/test/soap/header/server.cgi
index 2a188538d9..f9739d0d15 100644
--- a/test/soap/header/server.cgi
+++ b/test/soap/header/server.cgi
@@ -85,18 +85,18 @@ class AuthHeaderPortServer < SOAP::RPC::CGIStub
end
def on_simple_inbound(my_header, mu)
- succeeded = false
+ auth = false
userid = my_header["userid"]
passwd = my_header["passwd"]
if login(userid, passwd)
- succeeded = true
+ auth = true
elsif sessionid = my_header["sessionid"]
if userid = auth(sessionid)
destroy_session(sessionid)
- succeeded = true
+ auth = true
end
end
- raise RuntimeError.new("authentication failed") unless succeeded
+ raise RuntimeError.new("authentication failed") unless auth
@userid = userid
@sessionid = create_session(userid)
end
diff --git a/test/soap/header/test_authheader.rb b/test/soap/header/test_authheader.rb
index 47e1e76b82..2c04769dd6 100644
--- a/test/soap/header/test_authheader.rb
+++ b/test/soap/header/test_authheader.rb
@@ -33,7 +33,7 @@ class TestAuthHeader < Test::Unit::TestCase
super
add_rpc_servant(AuthHeaderService.new, PortName)
ServerAuthHeaderHandler.init
- add_request_headerhandler(ServerAuthHeaderHandler)
+ add_rpc_request_headerhandler(ServerAuthHeaderHandler)
end
class ServerAuthHeaderHandler < SOAP::Header::SimpleHandler
@@ -162,6 +162,13 @@ class TestAuthHeader < Test::Unit::TestCase
@t = Thread.new {
@server.start
}
+ while @server.status != :Running
+ sleep 0.1
+ unless @t.alive?
+ @t.join
+ raise
+ end
+ end
end
def setup_client
diff --git a/test/soap/header/test_authheader_cgi.rb b/test/soap/header/test_authheader_cgi.rb
index d70b022ad8..03bd1bb965 100644
--- a/test/soap/header/test_authheader_cgi.rb
+++ b/test/soap/header/test_authheader_cgi.rb
@@ -72,6 +72,13 @@ class TestAuthHeaderCGI < Test::Unit::TestCase
Thread.current.abort_on_exception = true
@server.start
}
+ while @server.status != :Running
+ sleep 0.1
+ unless @t.alive?
+ @t.join
+ raise
+ end
+ end
end
def setup_client
diff --git a/test/soap/header/test_simplehandler.rb b/test/soap/header/test_simplehandler.rb
deleted file mode 100644
index 75dbd4a550..0000000000
--- a/test/soap/header/test_simplehandler.rb
+++ /dev/null
@@ -1,116 +0,0 @@
-require 'test/unit'
-require 'soap/rpc/driver'
-require 'soap/rpc/standaloneServer'
-require 'soap/header/simplehandler'
-
-
-module SOAP
-module Header
-
-
-class TestSimpleHandler < Test::Unit::TestCase
- Port = 17171
- PortName = 'http://tempuri.org/authHeaderPort'
-
- class PingPortServer < SOAP::RPC::StandaloneServer
- class PingService
- def self.create
- new
- end
-
- def ping
- Thread.current[:pingheader]
- end
- end
-
- def initialize(*arg)
- super
- add_rpc_servant(PingService.new, PortName)
- add_request_headerhandler(PingServerHeaderHandler)
- end
-
- class PingServerHeaderHandler < SOAP::Header::SimpleHandler
- MyHeaderName = XSD::QName.new("http://xmlsoap.org/Ping", "PingHeader")
-
- def self.create
- new
- end
-
- def initialize()
- super(MyHeaderName)
- end
-
- def on_simple_outbound
- "dummy"
- end
-
- def on_simple_inbound(my_header, mu)
- Thread.current[:pingheader] = my_header
- end
- end
- end
-
- class PingClientHeaderHandler < SOAP::Header::SimpleHandler
- MyHeaderName = XSD::QName.new("http://xmlsoap.org/Ping", "PingHeader")
-
- def initialize(pingHeader)
- super(MyHeaderName)
- @pingHeader = pingHeader
- @mustunderstand = false
- end
-
- def on_simple_outbound
- @pingHeader # --- note, not a Hash
- end
-
- def on_simple_inbound(my_header, mustunderstand)
- Thread.current[:pingheader] = my_header
- end
- end
-
- def setup
- @endpoint = "http://localhost:#{Port}/"
- setup_server
- setup_client
- end
-
- def setup_server
- @server = PingPortServer.new(self.class.name, nil, '0.0.0.0', Port)
- @server.level = Logger::Severity::ERROR
- @t = Thread.new {
- @server.start
- }
- end
-
- def setup_client
- @client = SOAP::RPC::Driver.new(@endpoint, PortName)
- @client.wiredump_dev = STDERR if $DEBUG
- @client.add_method('ping')
- end
-
- def teardown
- teardown_server
- teardown_client
- end
-
- def teardown_server
- @server.shutdown
- @t.kill
- @t.join
- end
-
- def teardown_client
- @client.reset_stream
- end
-
- def test_string
- h = PingClientHeaderHandler.new('pingheader')
- @client.headerhandler << h
- assert_equal("pingheader", @client.ping)
- assert_equal("dummy", Thread.current[:pingheader])
- end
-end
-
-
-end
-end
diff --git a/test/soap/helloworld/test_helloworld.rb b/test/soap/helloworld/test_helloworld.rb
index 40c35b57fb..cd78d9fa0b 100644
--- a/test/soap/helloworld/test_helloworld.rb
+++ b/test/soap/helloworld/test_helloworld.rb
@@ -17,6 +17,13 @@ class TestHelloWorld < Test::Unit::TestCase
Thread.current.abort_on_exception = true
@server.start
}
+ while @server.status != :Running
+ sleep 0.1
+ unless @t.alive?
+ @t.join
+ raise
+ end
+ end
@endpoint = "http://localhost:#{Port}/"
@client = SOAP::RPC::Driver.new(@endpoint, 'urn:hws')
@client.add_method("hello_world", "from")
diff --git a/test/soap/ssl/sslsvr.rb b/test/soap/ssl/sslsvr.rb
index 4f67eb9485..281c1a1a51 100644
--- a/test/soap/ssl/sslsvr.rb
+++ b/test/soap/ssl/sslsvr.rb
@@ -47,11 +47,10 @@ if $0 == __FILE__
:SSLClientCA => cert('ca.cert'),
:SSLCertName => nil
)
- t = Thread.new {
- Thread.current.abort_on_exception = true
- $server.start
- }
+ trap(:INT) do
+ $server.shutdown if $server
+ end
STDOUT.sync = true
- puts $$
- t.join
+ STDOUT.puts $$
+ $server.start
end
diff --git a/test/soap/ssl/test_ssl.rb b/test/soap/ssl/test_ssl.rb
index f0a1e18971..6678c775ac 100644
--- a/test/soap/ssl/test_ssl.rb
+++ b/test/soap/ssl/test_ssl.rb
@@ -5,7 +5,7 @@ rescue LoadError
end
require 'soap/rpc/driver'
-if defined?(HTTPAccess2) and defined?(OpenSSL)
+if defined?(HTTPAccess2)
module SOAP; module SSL
@@ -33,8 +33,12 @@ class TestSSL < Test::Unit::TestCase
teardown_server
end
+ def streamhandler
+ @client.instance_eval("@servant").instance_eval("@streamhandler").client
+ end
+
def test_options
- cfg = @client.streamhandler.client.ssl_config
+ cfg = streamhandler.ssl_config
assert_nil(cfg.client_cert)
assert_nil(cfg.client_key)
assert_nil(cfg.client_ca)
@@ -53,23 +57,35 @@ class TestSSL < Test::Unit::TestCase
def test_verification
cfg = @client.options
cfg["protocol.http.ssl_config.verify_callback"] = method(:verify_callback).to_proc
- @verify_callback_called = false
- ssle = assert_raise(OpenSSL::SSL::SSLError) {@client.hello_world("ssl client")}
- assert_equal("certificate verify failed", ssle.message)
- assert(@verify_callback_called)
+ begin
+ @verify_callback_called = false
+ @client.hello_world("ssl client")
+ assert(false)
+ rescue OpenSSL::SSL::SSLError => ssle
+ assert_equal("certificate verify failed", ssle.message)
+ assert(@verify_callback_called)
+ end
#
cfg["protocol.http.ssl_config.client_cert"] = File.join(DIR, "client.cert")
cfg["protocol.http.ssl_config.client_key"] = File.join(DIR, "client.key")
@verify_callback_called = false
- ssle = assert_raise(OpenSSL::SSL::SSLError) {@client.hello_world("ssl client")}
- assert_equal("certificate verify failed", ssle.message)
- assert(@verify_callback_called)
+ begin
+ @client.hello_world("ssl client")
+ assert(false)
+ rescue OpenSSL::SSL::SSLError => ssle
+ assert_equal("certificate verify failed", ssle.message)
+ assert(@verify_callback_called)
+ end
#
cfg["protocol.http.ssl_config.ca_file"] = File.join(DIR, "ca.cert")
@verify_callback_called = false
- ssle = assert_raise(OpenSSL::SSL::SSLError) {@client.hello_world("ssl client")}
- assert_equal("certificate verify failed", ssle.message)
- assert(@verify_callback_called)
+ begin
+ @client.hello_world("ssl client")
+ assert(false)
+ rescue OpenSSL::SSL::SSLError => ssle
+ assert_equal("certificate verify failed", ssle.message)
+ assert(@verify_callback_called)
+ end
#
cfg["protocol.http.ssl_config.ca_file"] = File.join(DIR, "subca.cert")
@verify_callback_called = false
@@ -78,15 +94,23 @@ class TestSSL < Test::Unit::TestCase
#
cfg["protocol.http.ssl_config.verify_depth"] = "1"
@verify_callback_called = false
- ssle = assert_raise(OpenSSL::SSL::SSLError) {@client.hello_world("ssl client")}
- assert_equal("certificate verify failed", ssle.message)
- assert(@verify_callback_called)
+ begin
+ @client.hello_world("ssl client")
+ assert(false)
+ rescue OpenSSL::SSL::SSLError => ssle
+ assert_equal("certificate verify failed", ssle.message)
+ assert(@verify_callback_called)
+ end
#
cfg["protocol.http.ssl_config.verify_depth"] = ""
cfg["protocol.http.ssl_config.cert_store"] = OpenSSL::X509::Store.new
cfg["protocol.http.ssl_config.verify_mode"] = OpenSSL::SSL::VERIFY_PEER.to_s
- ssle = assert_raise(OpenSSL::SSL::SSLError) {@client.hello_world("ssl client")}
- assert_equal("certificate verify failed", ssle.message)
+ begin
+ @client.hello_world("ssl client")
+ assert(false)
+ rescue OpenSSL::SSL::SSLError => ssle
+ assert_equal("certificate verify failed", ssle.message)
+ end
#
cfg["protocol.http.ssl_config.verify_mode"] = ""
assert_equal("Hello World, from ssl client", @client.hello_world("ssl client"))
@@ -110,35 +134,18 @@ __EOP__
@client.loadproperty(testpropertyname)
@client.options["protocol.http.ssl_config.verify_callback"] = method(:verify_callback).to_proc
@verify_callback_called = false
- # NG with String
- ssle = assert_raise(OpenSSL::SSL::SSLError) {@client.hello_world("ssl client")}
- assert_equal("certificate verify failed", ssle.message)
- assert(@verify_callback_called)
- # NG with Integer
- @client.options["protocol.http.ssl_config.verify_depth"] = 0
- ssle = assert_raise(OpenSSL::SSL::SSLError) {@client.hello_world("ssl client")}
- assert_equal("certificate verify failed", ssle.message)
- assert(@verify_callback_called)
- # OK with empty
+ begin
+ @client.hello_world("ssl client")
+ assert(false)
+ rescue OpenSSL::SSL::SSLError => ssle
+ assert_equal("certificate verify failed", ssle.message)
+ assert(@verify_callback_called)
+ end
+ #
@client.options["protocol.http.ssl_config.verify_depth"] = ""
@verify_callback_called = false
assert_equal("Hello World, from ssl client", @client.hello_world("ssl client"))
assert(@verify_callback_called)
- # OK with nil
- @client.options["protocol.http.ssl_config.verify_depth"] = nil
- @verify_callback_called = false
- assert_equal("Hello World, from ssl client", @client.hello_world("ssl client"))
- assert(@verify_callback_called)
- # OK with String
- @client.options["protocol.http.ssl_config.verify_depth"] = "3"
- @verify_callback_called = false
- assert_equal("Hello World, from ssl client", @client.hello_world("ssl client"))
- assert(@verify_callback_called)
- # OK with Integer
- @client.options["protocol.http.ssl_config.verify_depth"] = 3
- @verify_callback_called = false
- assert_equal("Hello World, from ssl client", @client.hello_world("ssl client"))
- assert(@verify_callback_called)
ensure
File.unlink(testpropertyname)
end
@@ -151,11 +158,15 @@ __EOP__
cfg["protocol.http.ssl_config.ca_file"] = File.join(DIR, "ca.cert")
cfg["protocol.http.ssl_config.ca_file"] = File.join(DIR, "subca.cert")
#cfg.timeout = 123
- cfg["protocol.http.ssl_config.ciphers"] = "!ALL"
+ assert_equal("Hello World, from ssl client", @client.hello_world("ssl client"))
#
- ssle = assert_raise(OpenSSL::SSL::SSLError) {@client.hello_world("ssl client")}
- # depends on OpenSSL version. (?:0.9.8|0.9.7)
- assert_match(/\A(?:SSL_CTX_set_cipher_list:: no cipher match|no ciphers available)\z/, ssle.message)
+ cfg["protocol.http.ssl_config.ciphers"] = "!ALL"
+ begin
+ @client.hello_world("ssl client")
+ assert(false)
+ rescue OpenSSL::SSL::SSLError => ssle
+ assert_equal("no ciphers available", ssle.message)
+ end
#
cfg["protocol.http.ssl_config.ciphers"] = "ALL"
assert_equal("Hello World, from ssl client", @client.hello_world("ssl client"))
@@ -169,7 +180,7 @@ private
def setup_server
svrcmd = "#{q(RUBY)} "
- #svrcmd << "-d " if $DEBUG
+ svrcmd << "-d " if $DEBUG
svrcmd << File.join(DIR, "sslsvr.rb")
svrout = IO.popen(svrcmd)
@serverpid = Integer(svrout.gets.chomp)
@@ -181,14 +192,11 @@ private
end
def teardown_server
- if @serverpid
- Process.kill('KILL', @serverpid)
- Process.waitpid(@serverpid)
- end
+ Process.kill('INT', @serverpid)
end
def teardown_client
- @client.reset_stream if @client
+ @client.reset_stream
end
def verify_callback(ok, cert)
diff --git a/test/soap/struct/test_struct.rb b/test/soap/struct/test_struct.rb
index d92f4bc18a..71ada31676 100644
--- a/test/soap/struct/test_struct.rb
+++ b/test/soap/struct/test_struct.rb
@@ -30,7 +30,6 @@ class TestStruct < Test::Unit::TestCase
def setup_server
@server = Server.new(
:Port => Port,
- :BindAddress => "0.0.0.0",
:AccessLog => [],
:SOAPDefaultNamespace => Namespace
)
@@ -64,6 +63,13 @@ class TestStruct < Test::Unit::TestCase
Thread.current.abort_on_exception = true
server.start
}
+ while server.status != :Running
+ sleep 0.1
+ unless t.alive?
+ t.join
+ raise
+ end
+ end
t
end
diff --git a/test/soap/swa/test_file.rb b/test/soap/swa/test_file.rb
index 1ec7aa92a7..29bdf88a3b 100644
--- a/test/soap/swa/test_file.rb
+++ b/test/soap/swa/test_file.rb
@@ -33,6 +33,13 @@ class TestFile < Test::Unit::TestCase
@t = Thread.new {
@server.start
}
+ while @server.status != :Running
+ sleep 0.1
+ unless @t.alive?
+ @t.join
+ raise
+ end
+ end
@endpoint = "http://localhost:#{Port}/"
@client = SOAP::RPC::Driver.new(@endpoint, 'http://www.acmetron.com/soap')
@client.add_method('get_file')
@@ -47,14 +54,11 @@ class TestFile < Test::Unit::TestCase
@client.reset_stream
end
- def test_get_file
+ def test_file
assert_equal(
File.open(THIS_FILE) { |f| f.read },
@client.get_file['file'].content
)
- end
-
- def test_put_file
assert_equal(
"File 'foo' was received ok.",
@client.put_file('foo',
diff --git a/test/soap/test_basetype.rb b/test/soap/test_basetype.rb
index 3785873560..afd550f996 100644
--- a/test/soap/test_basetype.rb
+++ b/test/soap/test_basetype.rb
@@ -382,9 +382,6 @@ class TestSOAP < Test::Unit::TestCase
]
targets.each do |data, expected|
assert_equal(expected, SOAP::SOAPDateTime.new(data).to_s)
- d = DateTime.parse(data)
- d >>= 12 if d.year < 0 # XSDDateTime.year(-1) == DateTime.year(0)
- assert_equal(expected, SOAP::SOAPDateTime.new(d).to_s)
end
targets = [
@@ -484,9 +481,6 @@ class TestSOAP < Test::Unit::TestCase
]
targets.each do |data, expected|
assert_equal(expected, SOAP::SOAPDate.new(data).to_s)
- d = Date.parse(data)
- d >>= 12 if d.year < 0 # XSDDate.year(-1) == Date.year(0)
- assert_equal(expected, SOAP::SOAPDate.new(d).to_s)
end
end
diff --git a/test/soap/test_envelopenamespace.rb b/test/soap/test_envelopenamespace.rb
deleted file mode 100644
index 5b7d281341..0000000000
--- a/test/soap/test_envelopenamespace.rb
+++ /dev/null
@@ -1,92 +0,0 @@
-require 'test/unit'
-require 'soap/rpc/driver'
-require 'webrick'
-require 'logger'
-
-
-module SOAP
-
-
-class TestEnvelopeNamespace < Test::Unit::TestCase
- Port = 17171
- TemporaryNamespace = 'urn:foo'
-
- def setup
- @logger = Logger.new(STDERR)
- @logger.level = Logger::Severity::ERROR
- @url = "http://localhost:#{Port}/"
- @server = @client = nil
- @server_thread = nil
- setup_server
- setup_client
- end
-
- def teardown
- teardown_client
- teardown_server
- end
-
- def setup_server
- @server = WEBrick::HTTPServer.new(
- :BindAddress => "0.0.0.0",
- :Logger => @logger,
- :Port => Port,
- :AccessLog => [],
- :DocumentRoot => File.dirname(File.expand_path(__FILE__))
- )
- @server.mount(
- '/',
- WEBrick::HTTPServlet::ProcHandler.new(method(:do_server_proc).to_proc)
- )
- @server_thread = start_server_thread(@server)
- end
-
- def setup_client
- @client = SOAP::RPC::Driver.new(@url, '')
- @client.add_method("do_server_proc")
- end
-
- def teardown_server
- @server.shutdown
- @server_thread.kill
- @server_thread.join
- end
-
- def teardown_client
- @client.reset_stream
- end
-
- def start_server_thread(server)
- t = Thread.new {
- Thread.current.abort_on_exception = true
- server.start
- }
- t
- end
-
- def do_server_proc(req, res)
- res['content-type'] = 'text/xml'
- res.body = <<__EOX__
-<?xml version="1.0" encoding="utf-8" ?>
-<env:Envelope xmlns:env="#{TemporaryNamespace}">
- <env:Body>
- <n1:do_server_proc xmlns:n1="urn:foo" env:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
- <return>hello world</return>
- </n1:do_server_proc>
- </env:Body>
-</env:Envelope>
-__EOX__
- end
-
- def test_normal
- assert_raise(SOAP::ResponseFormatError) do
- @client.do_server_proc
- end
- @client.options["soap.envelope.requestnamespace"] = TemporaryNamespace
- @client.options["soap.envelope.responsenamespace"] = TemporaryNamespace
- assert_equal('hello world', @client.do_server_proc)
- end
-end
-
-
-end
diff --git a/test/soap/test_httpconfigloader.rb b/test/soap/test_httpconfigloader.rb
deleted file mode 100644
index b06243f661..0000000000
--- a/test/soap/test_httpconfigloader.rb
+++ /dev/null
@@ -1,39 +0,0 @@
-require 'test/unit'
-require 'soap/httpconfigloader'
-require 'soap/rpc/driver'
-
-if defined?(HTTPAccess2)
-
-module SOAP
-
-
-class TestHTTPConfigLoader < Test::Unit::TestCase
- DIR = File.dirname(File.expand_path(__FILE__))
-
- def setup
- @client = SOAP::RPC::Driver.new(nil, nil)
- end
-
- def test_property
- testpropertyname = File.join(DIR, 'soapclient.properties')
- File.open(testpropertyname, "w") do |f|
- f <<<<__EOP__
-protocol.http.ssl_config.verify_mode = OpenSSL::SSL::VERIFY_PEER
-# depth: 1 causes an error (intentional)
-protocol.http.ssl_config.verify_depth = 1
-protocol.http.ssl_config.ciphers = ALL
-__EOP__
- end
- begin
- @client.loadproperty(testpropertyname)
- assert_equal('ALL', @client.options['protocol.http.ssl_config.ciphers'])
- ensure
- File.unlink(testpropertyname)
- end
- end
-end
-
-
-end
-
-end
diff --git a/test/soap/test_mapping.rb b/test/soap/test_mapping.rb
deleted file mode 100644
index 26222e6719..0000000000
--- a/test/soap/test_mapping.rb
+++ /dev/null
@@ -1,59 +0,0 @@
-require 'test/unit'
-require 'soap/mapping'
-
-
-module SOAP
-
-
-class TestMapping < Test::Unit::TestCase
- def test_date
- targets = [
- ["2002-12-31",
- "2002-12-31Z"],
- ["2002-12-31+00:00",
- "2002-12-31Z"],
- ["2002-12-31-00:00",
- "2002-12-31Z"],
- ["-2002-12-31",
- "-2002-12-31Z"],
- ["-2002-12-31+00:00",
- "-2002-12-31Z"],
- ["-2002-12-31-00:00",
- "-2002-12-31Z"],
- ]
- targets.each do |str, expectec|
- d = Date.parse(str)
- assert_equal(d.class, convert(d).class)
- assert_equal(d, convert(d))
- end
- end
-
- def test_datetime
- targets = [
- ["2002-12-31T23:59:59.00",
- "2002-12-31T23:59:59Z"],
- ["2002-12-31T23:59:59+00:00",
- "2002-12-31T23:59:59Z"],
- ["2002-12-31T23:59:59-00:00",
- "2002-12-31T23:59:59Z"],
- ["-2002-12-31T23:59:59.00",
- "-2002-12-31T23:59:59Z"],
- ["-2002-12-31T23:59:59+00:00",
- "-2002-12-31T23:59:59Z"],
- ["-2002-12-31T23:59:59-00:00",
- "-2002-12-31T23:59:59Z"],
- ]
- targets.each do |str, expectec|
- d = DateTime.parse(str)
- assert_equal(d.class, convert(d).class)
- assert_equal(d, convert(d))
- end
- end
-
- def convert(obj)
- SOAP::Mapping.soap2obj(SOAP::Mapping.obj2soap(obj))
- end
-end
-
-
-end
diff --git a/test/soap/test_no_indent.rb b/test/soap/test_no_indent.rb
deleted file mode 100644
index f49fb7389f..0000000000
--- a/test/soap/test_no_indent.rb
+++ /dev/null
@@ -1,86 +0,0 @@
-require 'test/unit'
-require 'soap/rpc/standaloneServer'
-require 'soap/rpc/driver'
-
-if defined?(HTTPAccess2)
-
-module SOAP
-
-
-class TestNoIndent < Test::Unit::TestCase
- Port = 17171
-
- class NopServer < SOAP::RPC::StandaloneServer
- def initialize(*arg)
- super
- add_rpc_method(self, 'nop')
- end
-
- def nop
- SOAP::RPC::SOAPVoid.new
- end
- end
-
- def setup
- @server = NopServer.new(self.class.name, nil, '0.0.0.0', Port)
- @server.level = Logger::Severity::ERROR
- @t = Thread.new {
- @server.start
- }
- @endpoint = "http://localhost:#{Port}/"
- @client = SOAP::RPC::Driver.new(@endpoint)
- @client.add_rpc_method('nop')
- end
-
- def teardown
- @server.shutdown
- @t.kill
- @t.join
- @client.reset_stream
- end
-
- INDENT_XML =
-%q[<?xml version="1.0" encoding="utf-8" ?>
-<env:Envelope xmlns:xsd="http://www.w3.org/2001/XMLSchema"
- xmlns:env="http://schemas.xmlsoap.org/soap/envelope/"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
- <env:Body>
- <nop env:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
- </nop>
- </env:Body>
-</env:Envelope>]
-
- NO_INDENT_XML =
-%q[<?xml version="1.0" encoding="utf-8" ?>
-<env:Envelope xmlns:xsd="http://www.w3.org/2001/XMLSchema"
-xmlns:env="http://schemas.xmlsoap.org/soap/envelope/"
-xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
-<env:Body>
-<nop env:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
-</nop>
-</env:Body>
-</env:Envelope>]
-
- def test_indent
- @client.wiredump_dev = str = ''
- @client.options["soap.envelope.no_indent"] = false
- @client.nop
- assert_equal(INDENT_XML, parse_requestxml(str))
- end
-
- def test_no_indent
- @client.wiredump_dev = str = ''
- @client.options["soap.envelope.no_indent"] = true
- @client.nop
- assert_equal(NO_INDENT_XML, parse_requestxml(str))
- end
-
- def parse_requestxml(str)
- str.split(/\r?\n\r?\n/)[3]
- end
-end
-
-
-end
-
-end
diff --git a/test/soap/test_property.rb b/test/soap/test_property.rb
index 7acd2c8437..1cc826695f 100644
--- a/test/soap/test_property.rb
+++ b/test/soap/test_property.rb
@@ -6,8 +6,6 @@ module SOAP
class TestProperty < Test::Unit::TestCase
- FrozenError = (RUBY_VERSION >= "1.9.0") ? RuntimeError : TypeError
-
def setup
@prop = ::SOAP::Property.new
end
@@ -69,7 +67,7 @@ __EOP__
prop["foo.bar"].lock
prop.load("foo.bar.baz = 123")
assert(hooked)
- assert_raises(FrozenError) do
+ assert_raises(TypeError) do
prop.load("foo.bar.qux = 123")
end
prop.load("foo.baz = 456")
@@ -132,7 +130,7 @@ __EOP__
tag = Object.new
tested = false
@prop.add_hook("foo.bar") do |key, value|
- assert_raise(FrozenError) do
+ assert_raise(TypeError) do
key << "baz"
end
tested = true
@@ -268,37 +266,37 @@ __EOP__
@prop.lock
assert(@prop.locked?)
assert_instance_of(::SOAP::Property, @prop["a"])
- assert_raises(FrozenError) do
+ assert_raises(TypeError) do
@prop["b"]
end
#
@prop["a"].lock
- assert_raises(FrozenError) do
+ assert_raises(TypeError) do
@prop["a"]
end
assert_instance_of(::SOAP::Property, @prop["a.b"])
#
@prop["a.b"].lock
- assert_raises(FrozenError) do
+ assert_raises(TypeError) do
@prop["a.b"]
end
- assert_raises(FrozenError) do
+ assert_raises(TypeError) do
@prop["a"]
end
#
@prop["a.b.c.d"].lock
assert_instance_of(::SOAP::Property, @prop["a.b.c"])
- assert_raises(FrozenError) do
+ assert_raises(TypeError) do
@prop["a.b.c.d"]
end
assert_instance_of(::SOAP::Property, @prop["a.b.d"])
#
branch["e"].lock
assert_instance_of(::SOAP::Property, @prop["a.b.d"])
- assert_raises(FrozenError) do
+ assert_raises(TypeError) do
@prop["a.b.d.e"]
end
- assert_raises(FrozenError) do
+ assert_raises(TypeError) do
branch["e"]
end
end
@@ -312,26 +310,26 @@ __EOP__
assert_equal(nil, @prop["a.a"])
assert_equal(1, @prop["a.b.c"])
assert_equal(false, @prop["b"])
- assert_raises(FrozenError) do
+ assert_raises(TypeError) do
@prop["c"]
end
- assert_raises(FrozenError) do
+ assert_raises(TypeError) do
@prop["c"] = 2
end
- assert_raises(FrozenError) do
+ assert_raises(TypeError) do
@prop["a.b.R"]
end
- assert_raises(FrozenError) do
+ assert_raises(TypeError) do
@prop.add_hook do
assert(false)
end
end
- assert_raises(FrozenError) do
+ assert_raises(TypeError) do
@prop.add_hook("c") do
assert(false)
end
end
- assert_raises(FrozenError) do
+ assert_raises(TypeError) do
@prop.add_hook("a.c") do
assert(false)
end
@@ -366,7 +364,7 @@ __EOP__
@prop["a.b.c"] = 5
assert(tested)
assert_equal(5, @prop["a.b.c"])
- assert_raises(FrozenError) do
+ assert_raises(TypeError) do
@prop["a.b.d"] = 5
end
end
@@ -385,28 +383,28 @@ __EOP__
assert_equal(branch, @prop[:a][:b][:d])
@prop.lock(true)
# split error 1
- assert_raises(FrozenError) do
+ assert_raises(TypeError) do
@prop["a.b"]
end
# split error 2
- assert_raises(FrozenError) do
+ assert_raises(TypeError) do
@prop["a"]
end
@prop["a.b.c"] = 2
assert_equal(2, @prop["a.b.c"])
# replace error
- assert_raises(FrozenError) do
+ assert_raises(TypeError) do
@prop["a.b.c"] = ::SOAP::Property.new
end
# override error
- assert_raises(FrozenError) do
+ assert_raises(TypeError) do
@prop["a.b"] = 1
end
#
- assert_raises(FrozenError) do
+ assert_raises(TypeError) do
@prop["a.b.d"] << 1
end
- assert_raises(FrozenError) do
+ assert_raises(TypeError) do
branch << 1
end
branch.unlock(true)
diff --git a/test/soap/test_soapelement.rb b/test/soap/test_soapelement.rb
index 66e2a836a4..99c1f29b98 100644
--- a/test/soap/test_soapelement.rb
+++ b/test/soap/test_soapelement.rb
@@ -1,6 +1,5 @@
require 'test/unit'
require 'soap/baseData'
-require 'soap/mapping'
module SOAP
@@ -37,7 +36,7 @@ class TestSOAPElement < Test::Unit::TestCase
assert_equal(LiteralNamespace, obj.encodingstyle)
assert_equal({}, obj.extraattr)
assert_equal([], obj.precedents)
- assert_equal(nil, obj.qualified)
+ assert_equal(false, obj.qualified)
assert_equal(nil, obj.text)
assert(obj.members.empty?)
@@ -60,7 +59,7 @@ class TestSOAPElement < Test::Unit::TestCase
assert_equal(child, obj.var_foo)
child = d("_?a?b_")
obj.add(child)
- assert_equal(child, obj.__send__('_?a?b_'))
+ assert_equal(child, obj.var__ab_)
end
def test_member
diff --git a/test/soap/test_streamhandler.rb b/test/soap/test_streamhandler.rb
index c31254513f..e5b578d7a6 100644
--- a/test/soap/test_streamhandler.rb
+++ b/test/soap/test_streamhandler.rb
@@ -80,6 +80,13 @@ class TestStreamHandler < Test::Unit::TestCase
Thread.current.abort_on_exception = true
server.start
}
+ while server.status != :Running
+ sleep 0.1
+ unless t.alive?
+ t.join
+ raise
+ end
+ end
t
end
@@ -98,7 +105,7 @@ __EOX__
end
def parse_req_header(str)
- if ::SOAP::HTTPStreamHandler::Client.to_s == 'SOAP::NetHttpClient'
+ if ::SOAP::StreamHandler::Client.to_s == 'SOAP::NetHttpClient'
str = eval(str.split(/\r?\n/)[4][3..-1])
end
parse_req_header_http_access2(str)
@@ -134,24 +141,9 @@ __EOX__
assert(/^text\/xml;/ =~ h["content-type"])
end
- def test_uri
- # initialize client with URI object
- @client = SOAP::RPC::Driver.new(URI.parse(@url), '')
- @client.add_method("do_server_proc")
- # same as test_normal
- str = ""
- @client.wiredump_dev = str
- assert_nil(@client.do_server_proc)
- r, h = parse_req_header(str)
- assert_match(%r"POST / HTTP/1.", r)
- assert(/^text\/xml;/ =~ h["content-type"])
- end
-
def test_basic_auth
unless Object.const_defined?('HTTPAccess2')
- # soap4r + net/http + basic_auth is not supported.
- # use http-access2 instead.
- assert(true)
+ STDERR.puts("basic_auth is not supported under soap4r + net/http for now.")
return
end
str = ""
@@ -177,10 +169,6 @@ __EOX__
assert_nil(@client.do_server_proc)
r, h = parse_req_header(str)
assert_match(%r"POST http://localhost:17171/ HTTP/1.", r)
- # illegal proxy uri
- assert_raise(ArgumentError) do
- @client.options["protocol.http.proxy"] = 'ftp://foo:8080'
- end
ensure
if Object.const_defined?('HTTPAccess2')
HTTPAccess2::Client::NO_PROXY_HOSTS.replace(backup)
diff --git a/test/soap/test_styleuse.rb b/test/soap/test_styleuse.rb
deleted file mode 100644
index 4ea321848d..0000000000
--- a/test/soap/test_styleuse.rb
+++ /dev/null
@@ -1,333 +0,0 @@
-require 'test/unit'
-require 'soap/rpc/httpserver'
-require 'soap/rpc/driver'
-
-
-module SOAP
-
-
-class TestStyleUse < Test::Unit::TestCase
- # rpc driver: obj in(Hash allowed for literal), obj out
- #
- # style: not visible from user
- # rpc: wrapped element
- # document: unwrappted element
- #
- # use:
- # encoding: a graph (SOAP Data Model)
- # literal: not a graph (SOAPElement)
- #
- # rpc stub: obj in, obj out(Hash is allowed for literal)
- #
- # style: not visible from user
- # rpc: wrapped element
- # document: unwrappted element
- #
- # use:
- # encoding: a graph (SOAP Data Model)
- # literal: not a graph (SOAPElement)
- #
- # document driver: SOAPElement in, SOAPElement out? [not implemented]
- #
- # style: ditto
- # use: ditto
- #
- #
- # document stub: SOAPElement in, SOAPElement out? [not implemented]
- #
- # style: ditto
- # use: ditto
- #
- class GenericServant
- # method name style: requeststyle_requestuse_responsestyle_responseuse
-
- # 2 params -> array
- def rpc_enc_rpc_enc(obj1, obj2)
- [obj1, [obj1, obj2]]
- end
-
- # 2 objs -> array
- def rpc_lit_rpc_enc(obj1, obj2)
- [obj2, obj1]
- end
-
- # 2 params -> 2 params
- def rpc_enc_rpc_lit(obj1, obj2)
- klass = [obj1.class.name, obj2.class.name]
- [obj2, obj1]
- end
-
- # 2 objs -> 2 objs
- def rpc_lit_rpc_lit(obj1, obj2)
- [obj1, obj2]
- end
-
- # 2 params -> array
- def doc_enc_doc_enc(obj1, obj2)
- [obj1, [obj1, obj2]]
- end
-
- # 2 objs -> array
- def doc_lit_doc_enc(obj1, obj2)
- [obj2, obj1]
- end
-
- # 2 params -> 2 hashes
- def doc_enc_doc_lit(obj1, obj2)
- klass = [obj1.class.name, obj2.class.name]
- return {'obj1' => {'klass' => klass}, 'misc' => 'hash does not have an order'},
- {'obj2' => {'klass' => klass}}
- end
-
- # 2 objs -> 2 objs
- def doc_lit_doc_lit(obj1, obj2)
- return obj1, obj2
- end
- end
-
- Namespace = "urn:styleuse"
-
- module Op
- def self.opt(request_style, request_use, response_style, response_use)
- {
- :request_style => request_style,
- :request_use => request_use,
- :response_style => response_style,
- :response_use => response_use
- }
- end
-
- Op_rpc_enc_rpc_enc = [
- XSD::QName.new(Namespace, 'rpc_enc_rpc_enc'),
- nil,
- 'rpc_enc_rpc_enc', [
- ['in', 'obj1', nil],
- ['in', 'obj2', nil],
- ['retval', 'return', nil]],
- opt(:rpc, :encoded, :rpc, :encoded)
- ]
-
- Op_rpc_lit_rpc_enc = [
- XSD::QName.new(Namespace, 'rpc_lit_rpc_enc'),
- nil,
- 'rpc_lit_rpc_enc', [
- ['in', 'obj1', nil],
- ['in', 'obj2', nil],
- ['retval', 'return', nil]],
- opt(:rpc, :literal, :rpc, :encoded)
- ]
-
- Op_rpc_enc_rpc_lit = [
- XSD::QName.new(Namespace, 'rpc_enc_rpc_lit'),
- nil,
- 'rpc_enc_rpc_lit', [
- ['in', 'obj1', nil],
- ['in', 'obj2', nil],
- ['retval', 'ret1', nil],
- ['out', 'ret2', nil]],
- opt(:rpc, :encoded, :rpc, :literal)
- ]
-
- Op_rpc_lit_rpc_lit = [
- XSD::QName.new(Namespace, 'rpc_lit_rpc_lit'),
- nil,
- 'rpc_lit_rpc_lit', [
- ['in', 'obj1', nil],
- ['in', 'obj2', nil],
- ['retval', 'ret1', nil],
- ['out', 'ret2', nil]],
- opt(:rpc, :literal, :rpc, :literal)
- ]
-
- Op_doc_enc_doc_enc = [
- Namespace + 'doc_enc_doc_enc',
- 'doc_enc_doc_enc', [
- ['in', 'obj1', [nil, Namespace, 'obj1']],
- ['in', 'obj2', [nil, Namespace, 'obj2']],
- ['out', 'ret1', [nil, Namespace, 'ret1']],
- ['out', 'ret2', [nil, Namespace, 'ret2']]],
- opt(:document, :encoded, :document, :encoded)
- ]
-
- Op_doc_lit_doc_enc = [
- Namespace + 'doc_lit_doc_enc',
- 'doc_lit_doc_enc', [
- ['in', 'obj1', [nil, Namespace, 'obj1']],
- ['in', 'obj2', [nil, Namespace, 'obj2']],
- ['out', 'ret1', [nil, Namespace, 'ret1']],
- ['out', 'ret2', [nil, Namespace, 'ret2']]],
- opt(:document, :literal, :document, :encoded)
- ]
-
- Op_doc_enc_doc_lit = [
- Namespace + 'doc_enc_doc_lit',
- 'doc_enc_doc_lit', [
- ['in', 'obj1', [nil, Namespace, 'obj1']],
- ['in', 'obj2', [nil, Namespace, 'obj2']],
- ['out', 'ret1', [nil, Namespace, 'ret1']],
- ['out', 'ret2', [nil, Namespace, 'ret2']]],
- opt(:document, :encoded, :document, :literal)
- ]
-
- Op_doc_lit_doc_lit = [
- Namespace + 'doc_lit_doc_lit',
- 'doc_lit_doc_lit', [
- ['in', 'obj1', [nil, Namespace, 'obj1']],
- ['in', 'obj2', [nil, Namespace, 'obj2']],
- ['out', 'ret1', [nil, Namespace, 'ret1']],
- ['out', 'ret2', [nil, Namespace, 'ret2']]],
- opt(:document, :literal, :document, :literal)
- ]
- end
-
- include Op
-
- class Server < ::SOAP::RPC::HTTPServer
- include Op
-
- def on_init
- @servant = GenericServant.new
- add_rpc_operation(@servant, *Op_rpc_enc_rpc_enc)
- add_rpc_operation(@servant, *Op_rpc_lit_rpc_enc)
- add_rpc_operation(@servant, *Op_rpc_enc_rpc_lit)
- add_rpc_operation(@servant, *Op_rpc_lit_rpc_lit)
- add_document_operation(@servant, *Op_doc_enc_doc_enc)
- add_document_operation(@servant, *Op_doc_lit_doc_enc)
- add_document_operation(@servant, *Op_doc_enc_doc_lit)
- add_document_operation(@servant, *Op_doc_lit_doc_lit)
- end
- end
-
- Port = 17171
-
- def setup
- setup_server
- setup_client
- end
-
- def setup_server
- @server = Server.new(
- :BindAddress => "0.0.0.0",
- :Port => Port,
- :AccessLog => [],
- :SOAPDefaultNamespace => Namespace
- )
- @server.level = Logger::Severity::ERROR
- @server_thread = start_server_thread(@server)
- end
-
- def setup_client
- @client = ::SOAP::RPC::Driver.new("http://localhost:#{Port}/", Namespace)
- @client.wiredump_dev = STDERR if $DEBUG
- @client.add_rpc_operation(*Op_rpc_enc_rpc_enc)
- @client.add_rpc_operation(*Op_rpc_lit_rpc_enc)
- @client.add_rpc_operation(*Op_rpc_enc_rpc_lit)
- @client.add_rpc_operation(*Op_rpc_lit_rpc_lit)
- @client.add_document_operation(*Op_doc_enc_doc_enc)
- @client.add_document_operation(*Op_doc_lit_doc_enc)
- @client.add_document_operation(*Op_doc_enc_doc_lit)
- @client.add_document_operation(*Op_doc_lit_doc_lit)
- end
-
- def teardown
- teardown_server
- teardown_client
- end
-
- def teardown_server
- @server.shutdown
- @server_thread.kill
- @server_thread.join
- end
-
- def teardown_client
- @client.reset_stream
- end
-
- def start_server_thread(server)
- t = Thread.new {
- Thread.current.abort_on_exception = true
- server.start
- }
- t
- end
-
- def test_rpc_enc_rpc_enc
- o = "hello"
- obj1 = o
- obj2 = [1]
- ret = @client.rpc_enc_rpc_enc(obj1, obj2)
- # server returns [obj1, [obj1, obj2]]
- assert_equal([obj1, [obj1, obj2]], ret)
- assert_same(ret[0], ret[1][0])
- end
-
- S1 = ::Struct.new(:a)
- S2 = ::Struct.new(:c)
- def test_rpc_lit_rpc_enc
- ret1, ret2 = @client.rpc_lit_rpc_enc(S1.new('b'), S2.new('d'))
- assert_equal('d', ret1.c)
- assert_equal('b', ret2.a)
- # Hash is allowed for literal
- ret1, ret2 = @client.rpc_lit_rpc_enc({'a' => 'b'}, {'c' => 'd'})
- assert_equal('d', ret1.c)
- assert_equal('b', ret2.a)
- # simple value
- assert_equal(
- ['1', 'a'],
- @client.rpc_lit_rpc_enc('a', 1)
- )
- end
-
- def test_rpc_enc_rpc_lit
- assert_equal(
- ['1', 'a'],
- @client.rpc_enc_rpc_lit('a', '1')
- )
- end
-
- def test_rpc_lit_rpc_lit
- ret1, ret2 = @client.rpc_lit_rpc_lit({'a' => 'b'}, {'c' => 'd'})
- assert_equal('b', ret1["a"])
- assert_equal('d', ret2["c"])
- end
-
- def test_doc_enc_doc_enc
- o = "hello"
- obj1 = o
- obj2 = [1]
- ret = @client.rpc_enc_rpc_enc(obj1, obj2)
- # server returns [obj1, [obj1, obj2]]
- assert_equal([obj1, [obj1, obj2]], ret)
- assert_same(ret[0], ret[1][0])
- end
-
- def test_doc_lit_doc_enc
- ret1, ret2 = @client.doc_lit_doc_enc({'a' => 'b'}, {'c' => 'd'})
- assert_equal('d', ret1.c)
- assert_equal('b', ret2.a)
- assert_equal(
- ['a', '1'],
- @client.doc_lit_doc_enc(1, 'a')
- )
- end
-
- def test_doc_enc_doc_lit
- ret1, ret2 = @client.doc_enc_doc_lit('a', 1)
- # literal Array
- assert_equal(['String', 'Fixnum'], ret1['obj1']['klass'])
- # same value
- assert_equal(ret1['obj1']['klass'], ret2['obj2']['klass'])
- # not the same object (not encoded)
- assert_not_same(ret1['obj1']['klass'], ret2['obj2']['klass'])
- end
-
- def test_doc_lit_doc_lit
- ret1, ret2 = @client.doc_lit_doc_lit({'a' => 'b'}, {'c' => 'd'})
- assert_equal('b', ret1["a"])
- assert_equal('d', ret2["c"])
- end
-end
-
-
-end
diff --git a/test/soap/wsdlDriver/calc.wsdl b/test/soap/wsdlDriver/calc.wsdl
deleted file mode 100644
index 694a01e87e..0000000000
--- a/test/soap/wsdlDriver/calc.wsdl
+++ /dev/null
@@ -1,126 +0,0 @@
-<?xml version='1.0' encoding='UTF-8'?>
-<!--generated by GLUE Standard 4.0.1 on Wed Mar 09 10:20:07 GMT-08:00
-2005-->
-<wsdl:definitions name='Calculator'
-targetNamespace='http://www.themindelectric.com/wsdl/Calculator/'
- xmlns:tns='http://www.themindelectric.com/wsdl/Calculator/'
- xmlns:soap='http://schemas.xmlsoap.org/wsdl/soap/'
- xmlns:http='http://schemas.xmlsoap.org/wsdl/http/'
- xmlns:mime='http://schemas.xmlsoap.org/wsdl/mime/'
- xmlns:xsd='http://www.w3.org/2001/XMLSchema'
- xmlns:soapenc='http://schemas.xmlsoap.org/soap/encoding/'
- xmlns:wsdl='http://schemas.xmlsoap.org/wsdl/'
- xmlns:tme='http://www.themindelectric.com/'>
- <wsdl:message name='add0In'>
- <wsdl:part name='x' type='xsd:float'/>
- <wsdl:part name='y' type='xsd:float'/>
- </wsdl:message>
- <wsdl:message name='add0Out'>
- <wsdl:part name='Result' type='xsd:float'/>
- </wsdl:message>
- <wsdl:message name='divide1In'>
- <wsdl:part name='numerator' type='xsd:float'/>
- <wsdl:part name='denominator' type='xsd:float'/>
- </wsdl:message>
- <wsdl:message name='divide1Out'>
- <wsdl:part name='Result' type='xsd:float'/>
- </wsdl:message>
- <wsdl:message name='multiply2In'>
- <wsdl:part name='x' type='xsd:float'/>
- <wsdl:part name='y' type='xsd:float'/>
- </wsdl:message>
- <wsdl:message name='multiply2Out'>
- <wsdl:part name='Result' type='xsd:float'/>
- </wsdl:message>
- <wsdl:message name='subtract3In'>
- <wsdl:part name='x' type='xsd:float'/>
- <wsdl:part name='y' type='xsd:float'/>
- </wsdl:message>
- <wsdl:message name='subtract3Out'>
- <wsdl:part name='Result' type='xsd:float'/>
- </wsdl:message>
- <wsdl:portType name='ICalculator'>
- <wsdl:operation name='add' parameterOrder='x y'>
- <wsdl:input name='add0In' message='tns:add0In'/>
- <wsdl:output name='add0Out' message='tns:add0Out'/>
- </wsdl:operation>
- <wsdl:operation name='divide' parameterOrder='numerator
-denominator'>
- <wsdl:input name='divide1In' message='tns:divide1In'/>
- <wsdl:output name='divide1Out' message='tns:divide1Out'/>
- </wsdl:operation>
- <wsdl:operation name='multiply' parameterOrder='x y'>
- <wsdl:input name='multiply2In' message='tns:multiply2In'/>
- <wsdl:output name='multiply2Out'
-message='tns:multiply2Out'/>
- </wsdl:operation>
- <wsdl:operation name='subtract' parameterOrder='x y'>
- <wsdl:input name='subtract3In' message='tns:subtract3In'/>
- <wsdl:output name='subtract3Out'
-message='tns:subtract3Out'/>
- </wsdl:operation>
- </wsdl:portType>
- <wsdl:binding name='ICalculator' type='tns:ICalculator'>
- <soap:binding style='rpc'
-transport='http://schemas.xmlsoap.org/soap/http'/>
- <wsdl:operation name='add'>
- <soap:operation soapAction='add' style='rpc'/>
- <wsdl:input name='add0In'>
- <soap:body use='encoded'
-namespace='http://www.fred.com'
-encodingStyle='http://schemas.xmlsoap.org/soap/encoding/'/>
- </wsdl:input>
- <wsdl:output name='add0Out'>
- <soap:body use='encoded'
-namespace='http://www.fred.com'
-encodingStyle='http://schemas.xmlsoap.org/soap/encoding/'/>
- </wsdl:output>
- </wsdl:operation>
- <wsdl:operation name='divide'>
- <soap:operation soapAction='divide' style='rpc'/>
- <wsdl:input name='divide1In'>
- <soap:body use='encoded'
-namespace='http://www.fred.com'
-encodingStyle='http://schemas.xmlsoap.org/soap/encoding/'/>
- </wsdl:input>
- <wsdl:output name='divide1Out'>
- <soap:body use='encoded'
-namespace='http://www.fred.com'
-encodingStyle='http://schemas.xmlsoap.org/soap/encoding/'/>
- </wsdl:output>
- </wsdl:operation>
- <wsdl:operation name='multiply'>
- <soap:operation soapAction='multiply' style='rpc'/>
- <wsdl:input name='multiply2In'>
- <soap:body use='encoded'
-namespace='http://www.fred.com'
-encodingStyle='http://schemas.xmlsoap.org/soap/encoding/'/>
- </wsdl:input>
- <wsdl:output name='multiply2Out'>
- <soap:body use='encoded'
-namespace='http://www.fred.com'
-encodingStyle='http://schemas.xmlsoap.org/soap/encoding/'/>
- </wsdl:output>
- </wsdl:operation>
- <wsdl:operation name='subtract'>
- <soap:operation soapAction='subtract' style='rpc'/>
- <wsdl:input name='subtract3In'>
- <soap:body use='encoded'
-namespace='http://www.fred.com'
-encodingStyle='http://schemas.xmlsoap.org/soap/encoding/'/>
- </wsdl:input>
- <wsdl:output name='subtract3Out'>
- <soap:body use='encoded'
-namespace='http://www.fred.com'
-encodingStyle='http://schemas.xmlsoap.org/soap/encoding/'/>
- </wsdl:output>
- </wsdl:operation>
- </wsdl:binding>
- <wsdl:service name='Calculator'>
- <wsdl:documentation>calculator service</wsdl:documentation>
- <wsdl:port name='ICalculator' binding='tns:ICalculator'>
- <soap:address
-location='http://ukulele:8080/calcapp/services/calculator'/>
- </wsdl:port>
- </wsdl:service>
-</wsdl:definitions>
diff --git a/test/soap/wsdlDriver/document.wsdl b/test/soap/wsdlDriver/document.wsdl
deleted file mode 100644
index 5e9e74b9df..0000000000
--- a/test/soap/wsdlDriver/document.wsdl
+++ /dev/null
@@ -1,54 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<definitions name="submit_service"
- xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/"
- xmlns:xsd="http://www.w3.org/2001/XMLSchema"
- xmlns:tns="urn:example.com:document"
- targetNamespace="urn:example.com:document"
- xmlns="http://schemas.xmlsoap.org/wsdl/">
- <types>
- <xsd:schema targetNamespace="urn:example.com:document">
- <xsd:element name="ruby">
- <xsd:complexType>
- <xsd:sequence>
- <xsd:element minOccurs="1" maxOccurs="1" name="myversion" type="tns:myversion"/>
- <xsd:element minOccurs="0" maxOccurs="1" name="date" type="xsd:dateTime"/>
- </xsd:sequence>
- </xsd:complexType>
- </xsd:element>
-
- <xsd:simpleType name="myversion">
- <xsd:restriction base="xsd:string">
- <xsd:enumeration value="1.6"/>
- <xsd:enumeration value="1.8"/>
- <xsd:enumeration value="1.9"/>
- </xsd:restriction>
- </xsd:simpleType>
- </xsd:schema>
- </types>
-
- <message name="submit_msg">
- <part name="parameters" element="tns:ruby"/>
- </message>
-
- <portType name="submit_port_type">
- <operation name="submit">
- <input message="tns:submit_msg"/>
- <output message="tns:submit_msg"/>
- </operation>
- </portType>
-
- <binding name="submit_binding" type="tns:submit_port_type">
- <soap:binding transport="http://schemas.xmlsoap.org/soap/http" style="document"/>
- <operation name="submit">
- <soap:operation soapAction="urn:example.com:document#submit" style="document"/>
- <input><soap:body use="literal"/></input>
- <output><soap:body use="literal"/></output>
- </operation>
- </binding>
-
- <service name="submit_service">
- <port name="submit_port" binding="tns:submit_binding">
- <soap:address location="http://localhost:10080"/>
- </port>
- </service>
-</definitions>
diff --git a/test/soap/wsdlDriver/simpletype.wsdl b/test/soap/wsdlDriver/simpletype.wsdl
index 6781dda552..7c211a6b2c 100644
--- a/test/soap/wsdlDriver/simpletype.wsdl
+++ b/test/soap/wsdlDriver/simpletype.wsdl
@@ -10,12 +10,12 @@
<xsd:schema targetNamespace="urn:example.com:simpletype-rpc-type">
<xsd:complexType name="version_struct">
<xsd:all>
- <xsd:element name="myversion" type="txd:myversions" />
+ <xsd:element name="version" type="txd:versions" />
<xsd:element name="msg" type="xsd:string" />
</xsd:all>
</xsd:complexType>
- <xsd:simpleType name="myversions">
+ <xsd:simpleType name="versions">
<xsd:restriction base="xsd:string">
<xsd:enumeration value="1.6"/>
<xsd:enumeration value="1.8"/>
@@ -26,7 +26,7 @@
</types>
<message name="msg_version">
- <part name="myversion" type="txd:myversions"/>
+ <part name="version" type="txd:versions"/>
</message>
<message name="msg_version_struct">
diff --git a/test/soap/wsdlDriver/test_calc.rb b/test/soap/wsdlDriver/test_calc.rb
deleted file mode 100644
index d031f663a3..0000000000
--- a/test/soap/wsdlDriver/test_calc.rb
+++ /dev/null
@@ -1,100 +0,0 @@
-require 'test/unit'
-require 'soap/rpc/httpserver'
-require 'soap/wsdlDriver'
-
-
-module SOAP
-
-
-class TestCalc < Test::Unit::TestCase
- class Server < ::SOAP::RPC::HTTPServer
- def on_init
- add_method(self, 'add', 'x', 'y')
- end
-
- def add(x, y)
- x.to_f + y.to_f
- end
- end
-
- DIR = File.dirname(File.expand_path(__FILE__))
- Port = 17171
-
- def setup
- setup_server
- setup_client
- end
-
- def setup_server
- @server = Server.new(
- :BindAddress => "0.0.0.0",
- :Port => Port,
- :AccessLog => [],
- :SOAPDefaultNamespace => 'http://www.fred.com'
- )
- @server.level = Logger::Severity::ERROR
- @server_thread = start_server_thread(@server)
- end
-
- def setup_client
- @wsdl = File.join(DIR, 'calc.wsdl')
- end
-
- def teardown
- teardown_server
- teardown_client
- end
-
- def teardown_server
- @server.shutdown
- @server_thread.kill
- @server_thread.join
- end
-
- def teardown_client
- @client.reset_stream if @client
- end
-
- def start_server_thread(server)
- t = Thread.new {
- Thread.current.abort_on_exception = true
- server.start
- }
- t
- end
-
- def test_rpc_driver
- @client = ::SOAP::WSDLDriverFactory.new(@wsdl).create_rpc_driver
- @client.wiredump_dev = STDOUT if $DEBUG
- @client.endpoint_url = "http://localhost:#{Port}/"
- @client.generate_explicit_type = true
- assert_equal(0.3, @client.add(0.1, 0.2))
- @client.generate_explicit_type = false
- assert_equal(0.3, @client.add(0.1, 0.2))
- end
-
- def test_old_driver
- silent do
- @client = ::SOAP::WSDLDriverFactory.new(@wsdl).create_driver
- end
- @client.wiredump_dev = STDOUT if $DEBUG
- @client.endpoint_url = "http://localhost:#{Port}/"
- @client.generate_explicit_type = true
- assert_equal(0.3, @client.add(0.1, 0.2))
- @client.generate_explicit_type = false
- assert_equal(0.3, @client.add(0.1, 0.2))
- end
-
- def silent
- back = $VERBOSE
- $VERBOSE = nil
- begin
- yield
- ensure
- $VERBOSE = back
- end
- end
-end
-
-
-end
diff --git a/test/soap/wsdlDriver/test_document.rb b/test/soap/wsdlDriver/test_document.rb
deleted file mode 100644
index 634b827aae..0000000000
--- a/test/soap/wsdlDriver/test_document.rb
+++ /dev/null
@@ -1,78 +0,0 @@
-require 'test/unit'
-require 'soap/rpc/standaloneServer'
-require 'soap/wsdlDriver'
-
-
-module SOAP
-
-
-class TestDocument < Test::Unit::TestCase
- Namespace = 'urn:example.com:document'
-
- class Server < ::SOAP::RPC::StandaloneServer
- def on_init
- add_document_method(self, 'urn:example.com:document#submit', 'submit', XSD::QName.new(Namespace, 'ruby'), XSD::QName.new(Namespace, 'ruby'))
- end
-
- def submit(ruby)
- ruby
- end
- end
-
- DIR = File.dirname(File.expand_path(__FILE__))
-
- Port = 17171
-
- def setup
- setup_server
- setup_client
- end
-
- def setup_server
- @server = Server.new('Test', Namespace, '0.0.0.0', Port)
- @server.level = Logger::Severity::ERROR
- @server_thread = start_server_thread(@server)
- end
-
- def setup_client
- wsdl = File.join(DIR, 'document.wsdl')
- @client = ::SOAP::WSDLDriverFactory.new(wsdl).create_rpc_driver
- @client.endpoint_url = "http://localhost:#{Port}/"
- @client.wiredump_dev = STDOUT if $DEBUG
- end
-
- def teardown
- teardown_server
- teardown_client
- end
-
- def teardown_server
- @server.shutdown
- @server_thread.kill
- @server_thread.join
- end
-
- def teardown_client
- @client.reset_stream
- end
-
- def start_server_thread(server)
- t = Thread.new {
- Thread.current.abort_on_exception = true
- server.start
- }
- t
- end
-
- def test_document
- msg = {'myversion' => "1.9", 'date' => "2004-01-01T00:00:00Z"}
- reply_msg = @client.submit(msg)
- assert_equal('1.9', reply_msg.myversion)
- assert_equal('1.9', reply_msg['myversion'])
- assert_equal('2004-01-01T00:00:00Z', reply_msg.date)
- assert_equal('2004-01-01T00:00:00Z', reply_msg['date'])
- end
-end
-
-
-end
diff --git a/test/soap/wsdlDriver/test_simpletype.rb b/test/soap/wsdlDriver/test_simpletype.rb
index 76b3a32df7..ed628927cd 100644
--- a/test/soap/wsdlDriver/test_simpletype.rb
+++ b/test/soap/wsdlDriver/test_simpletype.rb
@@ -30,7 +30,6 @@ class TestSimpleType < Test::Unit::TestCase
def setup_server
@server = Server.new(
- :BindAddress => "0.0.0.0",
:Port => Port,
:AccessLog => [],
:SOAPDefaultNamespace => "urn:example.com:simpletype-rpc"
@@ -41,8 +40,7 @@ class TestSimpleType < Test::Unit::TestCase
def setup_client
wsdl = File.join(DIR, 'simpletype.wsdl')
- @client = ::SOAP::WSDLDriverFactory.new(wsdl).create_rpc_driver
- @client.wiredump_dev = STDOUT if $DEBUG
+ @client = ::SOAP::WSDLDriverFactory.new(wsdl).create_driver
@client.endpoint_url = "http://localhost:#{Port}/"
@client.generate_explicit_type = false
end
@@ -67,6 +65,13 @@ class TestSimpleType < Test::Unit::TestCase
Thread.current.abort_on_exception = true
server.start
}
+ while server.status != :Running
+ sleep 0.1
+ unless t.alive?
+ t.join
+ raise
+ end
+ end
t
end
@@ -74,10 +79,10 @@ class TestSimpleType < Test::Unit::TestCase
result = @client.echo_version("1.9")
assert_equal("1.9", result.version)
assert_equal("checked", result.msg)
- assert_raise(XSD::ValueSpaceError) do
+ assert_raise(::XSD::ValueSpaceError) do
@client.echo_version("2.0")
end
- assert_raise(XSD::ValueSpaceError) do
+ assert_raise(::XSD::ValueSpaceError) do
@client.echo_version(nil) # nil => "2.0" => out of range
end
end
diff --git a/test/stringio/test_stringio.rb b/test/stringio/test_stringio.rb
index de15ab5508..fee305e856 100644
--- a/test/stringio/test_stringio.rb
+++ b/test/stringio/test_stringio.rb
@@ -30,14 +30,4 @@ class TestStringIO < Test::Unit::TestCase
io.print "last"
assert_equal("\0" * n + "last", io.string)
end
-
- def test_overwrite # [ruby-core:03836]
- stringio = StringIO.new
- responses = ['', 'just another ruby', 'hacker']
- responses.each do |resp|
- stringio.puts(resp)
- stringio.rewind
- end
- assert_equal("hacker\nother ruby\n", stringio.string)
- end
end
diff --git a/test/testunit/collector/test_dir.rb b/test/testunit/collector/test_dir.rb
index e7ae414264..e9b42d7966 100644
--- a/test/testunit/collector/test_dir.rb
+++ b/test/testunit/collector/test_dir.rb
@@ -164,11 +164,11 @@ module Test
def test_dir
inner_dir = nil
- dirs = FileSystem::Directory.new('/', nil) do
+ dir = FileSystem::Directory.new('/', nil) do
file 'a', nil
inner_dir = dir 'b'
end
- assert_equal(inner_dir, dirs['b'])
+ assert_equal(inner_dir, dir['b'])
end
def test_fs
@@ -365,7 +365,7 @@ module Test
def test_nil_pattern
expected = TestSuite.new('d2')
expected << @t5.suite
- @c.pattern.clear
+ @c.pattern = nil
assert_equal(expected, @c.collect('d2'))
end
@@ -380,7 +380,7 @@ module Test
expected = TestSuite.new('[d1, d2]')
expected << (TestSuite.new('d1') << @t3.suite)
expected << (TestSuite.new('d2') << @t5.suite)
- @c.pattern.replace([/\btest_/])
+ @c.pattern = /^test_/
assert_equal(expected, @c.collect('d1', 'd2'))
end
end
diff --git a/test/uri/test_generic.rb b/test/uri/test_generic.rb
index 8a7feb4982..8740574e4e 100644
--- a/test/uri/test_generic.rb
+++ b/test/uri/test_generic.rb
@@ -117,26 +117,11 @@ class TestGeneric < Test::Unit::TestCase
assert_raises(URI::InvalidURIError) { URI.parse('http://a_b/') }
# 8
- # reported by m_seki
+ # reporte by m_seki
uri = URI.parse('file:///foo/bar.txt')
assert_kind_of(URI::Generic, url)
uri = URI.parse('file:/foo/bar.txt')
assert_kind_of(URI::Generic, url)
-
- # 9
- # [ruby-dev:25667]
- url = URI.parse('ftp://:pass@localhost/')
- assert_equal('', url.user)
- assert_equal('pass', url.password)
- assert_equal(':pass', url.userinfo)
- url = URI.parse('ftp://user@localhost/')
- assert_equal('user', url.user)
- assert_equal(nil, url.password)
- assert_equal('user', url.userinfo)
- url = URI.parse('ftp://localhost/')
- assert_equal(nil, url.user)
- assert_equal(nil, url.password)
- assert_equal(nil, url.userinfo)
end
def test_merge
diff --git a/test/webrick/test_cgi.rb b/test/webrick/test_cgi.rb
deleted file mode 100644
index b3e13ba2c5..0000000000
--- a/test/webrick/test_cgi.rb
+++ /dev/null
@@ -1,56 +0,0 @@
-require "webrick"
-require File.join(File.dirname(__FILE__), "utils.rb")
-require "test/unit"
-begin
- loadpath = $:.dup
- $:.replace($: | [File.expand_path("../ruby", File.dirname(__FILE__))])
- require 'envutil'
-ensure
- $:.replace(loadpath)
-end
-
-class TestWEBrickCGI < Test::Unit::TestCase
- def test_cgi
- accepted = started = stopped = 0
- requested0 = requested1 = 0
- config = {
- :CGIInterpreter => EnvUtil.rubybin,
- :DocumentRoot => File.dirname(__FILE__),
- :DirectoryIndex => ["webrick.cgi"],
- }
- if RUBY_PLATFORM =~ /mswin32|mingw|cygwin|bccwin32/
- config[:CGIPathEnv] = ENV['PATH'] # runtime dll may not be in system dir.
- end
- TestWEBrick.start_httpserver(config){|server, addr, port|
- http = Net::HTTP.new(addr, port)
- req = Net::HTTP::Get.new("/webrick.cgi")
- http.request(req){|res| assert_equal("/webrick.cgi", res.body)}
- req = Net::HTTP::Get.new("/webrick.cgi/path/info")
- http.request(req){|res| assert_equal("/path/info", res.body)}
- req = Net::HTTP::Get.new("/webrick.cgi/%3F%3F%3F?foo=bar")
- http.request(req){|res| assert_equal("/???", res.body)}
- req = Net::HTTP::Get.new("/webrick.cgi/%A4%DB%A4%B2/%A4%DB%A4%B2")
- http.request(req){|res|
- assert_equal("/\xA4\xDB\xA4\xB2/\xA4\xDB\xA4\xB2", res.body)}
- req = Net::HTTP::Get.new("/webrick.cgi?a=1;a=2;b=x")
- http.request(req){|res| assert_equal("a=1, a=2, b=x", res.body)}
- req = Net::HTTP::Get.new("/webrick.cgi?a=1&a=2&b=x")
- http.request(req){|res| assert_equal("a=1, a=2, b=x", res.body)}
-
- req = Net::HTTP::Post.new("/webrick.cgi?a=x;a=y;b=1")
- req["Content-Type"] = "application/x-www-form-urlencoded"
- http.request(req, "a=1;a=2;b=x"){|res|
- assert_equal("a=1, a=2, b=x", res.body)}
- req = Net::HTTP::Post.new("/webrick.cgi?a=x&a=y&b=1")
- req["Content-Type"] = "application/x-www-form-urlencoded"
- http.request(req, "a=1&a=2&b=x"){|res|
- assert_equal("a=1, a=2, b=x", res.body)}
- req = Net::HTTP::Get.new("/")
- http.request(req){|res|
- ary = res.body.to_a
- assert_match(%r{/$}, ary[0])
- assert_match(%r{/webrick.cgi$}, ary[1])
- }
- }
- end
-end
diff --git a/test/webrick/test_cookie.rb b/test/webrick/test_cookie.rb
deleted file mode 100644
index 8826d0b81f..0000000000
--- a/test/webrick/test_cookie.rb
+++ /dev/null
@@ -1,56 +0,0 @@
-require "test/unit"
-require "webrick/cookie"
-
-class TestWEBrickCookie < Test::Unit::TestCase
- def test_new
- cookie = WEBrick::Cookie.new("foo","bar")
- assert_equal("foo", cookie.name)
- assert_equal("bar", cookie.value)
- assert_equal("foo=bar", cookie.to_s)
- end
-
- def test_time
- cookie = WEBrick::Cookie.new("foo","bar")
- t = 1000000000
- cookie.max_age = t
- assert_match(t.to_s, cookie.to_s)
-
- cookie = WEBrick::Cookie.new("foo","bar")
- t = Time.at(1000000000)
- cookie.expires = t
- assert_equal(Time, cookie.expires.class)
- assert_equal(t, cookie.expires)
- ts = t.httpdate
- cookie.expires = ts
- assert_equal(Time, cookie.expires.class)
- assert_equal(t, cookie.expires)
- assert_match(ts, cookie.to_s)
- end
-
- def test_parse
- data = ""
- data << '$Version="1"; '
- data << 'Customer="WILE_E_COYOTE"; $Path="/acme"; '
- data << 'Part_Number="Rocket_Launcher_0001"; $Path="/acme"; '
- data << 'Shipping="FedEx"; $Path="/acme"'
- cookies = WEBrick::Cookie.parse(data)
- assert_equal(1, cookies[0].version)
- assert_equal("Customer", cookies[0].name)
- assert_equal("WILE_E_COYOTE", cookies[0].value)
- assert_equal("/acme", cookies[0].path)
- assert_equal(1, cookies[1].version)
- assert_equal("Part_Number", cookies[1].name)
- assert_equal("Rocket_Launcher_0001", cookies[1].value)
- assert_equal(1, cookies[2].version)
- assert_equal("Shipping", cookies[2].name)
- assert_equal("FedEx", cookies[2].value)
-
- data = "hoge=moge; __div__session=9865ecfd514be7f7"
- cookies = WEBrick::Cookie.parse(data)
- assert_equal(0, cookies[0].version)
- assert_equal("hoge", cookies[0].name)
- assert_equal("moge", cookies[0].value)
- assert_equal("__div__session", cookies[1].name)
- assert_equal("9865ecfd514be7f7", cookies[1].value)
- end
-end
diff --git a/test/webrick/test_filehandler.rb b/test/webrick/test_filehandler.rb
deleted file mode 100644
index 703fde4d9a..0000000000
--- a/test/webrick/test_filehandler.rb
+++ /dev/null
@@ -1,65 +0,0 @@
-require "test/unit"
-require "webrick"
-require "stringio"
-
-class WEBrick::TestFileHandler < Test::Unit::TestCase
- def default_file_handler(filename)
- klass = WEBrick::HTTPServlet::DefaultFileHandler
- klass.new(WEBrick::Config::HTTP, filename)
- end
-
- def get_res_body(res)
- return res.body.read rescue res.body
- end
-
- def make_range_request(range_spec)
- msg = <<-_end_of_request_
- GET / HTTP/1.0
- Range: #{range_spec}
-
- _end_of_request_
- return StringIO.new(msg.gsub(/^ {6}/, ""))
- end
-
- def make_range_response(file, range_spec)
- req = WEBrick::HTTPRequest.new(WEBrick::Config::HTTP)
- req.parse(make_range_request(range_spec))
- res = WEBrick::HTTPResponse.new(WEBrick::Config::HTTP)
- size = File.size(file)
- handler = default_file_handler(file)
- handler.make_partial_content(req, res, file, size)
- return res
- end
-
- def test_make_partial_content
- filename = __FILE__
- filesize = File.size(filename)
-
- res = make_range_response(filename, "bytes=#{filesize-100}-")
- assert_match(%r{^text/plain}, res["content-type"])
- assert_equal(get_res_body(res).size, 100)
-
- res = make_range_response(filename, "bytes=-100")
- assert_match(%r{^text/plain}, res["content-type"])
- assert_equal(get_res_body(res).size, 100)
-
- res = make_range_response(filename, "bytes=0-99")
- assert_match(%r{^text/plain}, res["content-type"])
- assert_equal(get_res_body(res).size, 100)
-
- res = make_range_response(filename, "bytes=100-199")
- assert_match(%r{^text/plain}, res["content-type"])
- assert_equal(get_res_body(res).size, 100)
-
- res = make_range_response(filename, "bytes=0-0")
- assert_match(%r{^text/plain}, res["content-type"])
- assert_equal(get_res_body(res).size, 1)
-
- res = make_range_response(filename, "bytes=-1")
- assert_match(%r{^text/plain}, res["content-type"])
- assert_equal(get_res_body(res).size, 1)
-
- res = make_range_response(filename, "bytes=0-0, -2")
- assert_match(%r{^multipart/byteranges}, res["content-type"])
- end
-end
diff --git a/test/webrick/test_httpauth.rb b/test/webrick/test_httpauth.rb
deleted file mode 100644
index 75926b1624..0000000000
--- a/test/webrick/test_httpauth.rb
+++ /dev/null
@@ -1,82 +0,0 @@
-require "test/unit"
-require "net/http"
-require "tempfile"
-require "webrick"
-require "webrick/httpauth/basicauth"
-require File.join(File.dirname(__FILE__), "utils.rb")
-
-class TestWEBrickHTTPAuth < Test::Unit::TestCase
- def test_basic_auth
- TestWEBrick.start_httpserver{|server, addr, port|
- realm = "WEBrick's realm"
- path = "/basic_auth"
-
- server.mount_proc(path){|req, res|
- WEBrick::HTTPAuth.basic_auth(req, res, realm){|user, pass|
- user == "webrick" && pass == "supersecretpassword"
- }
- res.body = "hoge"
- }
- http = Net::HTTP.new(addr, port)
- g = Net::HTTP::Get.new(path)
- g.basic_auth("webrick", "supersecretpassword")
- http.request(g){|res| assert_equal("hoge", res.body)}
- g.basic_auth("webrick", "not super")
- http.request(g){|res| assert_not_equal("hoge", res.body)}
- }
- end
-
- def test_basic_auth2
- TestWEBrick.start_httpserver{|server, addr, port|
- realm = "WEBrick's realm"
- path = "/basic_auth2"
-
- tmpfile = Tempfile.new("test_webrick_auth")
- tmpfile.close
- tmp_pass = WEBrick::HTTPAuth::Htpasswd.new(tmpfile.path)
- tmp_pass.set_passwd(realm, "webrick", "supersecretpassword")
- tmp_pass.set_passwd(realm, "foo", "supersecretpassword")
- tmp_pass.flush
-
- htpasswd = WEBrick::HTTPAuth::Htpasswd.new(tmpfile.path)
- users = []
- htpasswd.each{|user, pass| users << user }
- assert_equal(2, users.size)
- assert(users.member?("webrick"))
- assert(users.member?("foo"))
-
- server.mount_proc(path){|req, res|
- auth = WEBrick::HTTPAuth::BasicAuth.new(
- :Realm => realm, :UserDB => htpasswd,
- :Logger => server.logger
- )
- auth.authenticate(req, res)
- res.body = "hoge"
- }
- http = Net::HTTP.new(addr, port)
- g = Net::HTTP::Get.new(path)
- g.basic_auth("webrick", "supersecretpassword")
- http.request(g){|res| assert_equal("hoge", res.body)}
- g.basic_auth("webrick", "not super")
- http.request(g){|res| assert_not_equal("hoge", res.body)}
- }
- end
-
- def test_basic_auth3
- tmpfile = Tempfile.new("test_webrick_auth")
- tmpfile.puts("webrick:{SHA}GJYFRpBbdchp595jlh3Bhfmgp8k=")
- tmpfile.flush
- assert_raises(NotImplementedError){
- WEBrick::HTTPAuth::Htpasswd.new(tmpfile.path)
- }
- tmpfile.close(true)
-
- tmpfile = Tempfile.new("test_webrick_auth")
- tmpfile.puts("webrick:$apr1$IOVMD/..$rmnOSPXr0.wwrLPZHBQZy0")
- tmpfile.flush
- assert_raises(NotImplementedError){
- WEBrick::HTTPAuth::Htpasswd.new(tmpfile.path)
- }
- tmpfile.close(true)
- end
-end
diff --git a/test/webrick/test_httprequest.rb b/test/webrick/test_httprequest.rb
deleted file mode 100644
index 777a199441..0000000000
--- a/test/webrick/test_httprequest.rb
+++ /dev/null
@@ -1,214 +0,0 @@
-require "webrick"
-require "stringio"
-require "test/unit"
-
-class TestWEBrickHTTPRequest < Test::Unit::TestCase
- def test_parse_09
- msg = <<-_end_of_message_
- GET /
- foobar # HTTP/0.9 request don't have header nor entity body.
- _end_of_message_
- req = WEBrick::HTTPRequest.new(WEBrick::Config::HTTP)
- req.parse(StringIO.new(msg.gsub(/^ {6}/, "")))
- assert_equal("GET", req.request_method)
- assert_equal("/", req.unparsed_uri)
- assert_equal(WEBrick::HTTPVersion.new("0.9"), req.http_version)
- assert_equal(WEBrick::Config::HTTP[:ServerName], req.host)
- assert_equal(80, req.port)
- assert_equal(false, req.keep_alive?)
- assert_equal(nil, req.body)
- assert(req.query.empty?)
- end
-
- def test_parse_10
- msg = <<-_end_of_message_
- GET / HTTP/1.0
-
- _end_of_message_
- req = WEBrick::HTTPRequest.new(WEBrick::Config::HTTP)
- req.parse(StringIO.new(msg.gsub(/^ {6}/, "")))
- assert_equal("GET", req.request_method)
- assert_equal("/", req.unparsed_uri)
- assert_equal(WEBrick::HTTPVersion.new("1.0"), req.http_version)
- assert_equal(WEBrick::Config::HTTP[:ServerName], req.host)
- assert_equal(80, req.port)
- assert_equal(false, req.keep_alive?)
- assert_equal(nil, req.body)
- assert(req.query.empty?)
- end
-
- def test_parse_11
- msg = <<-_end_of_message_
- GET /path HTTP/1.1
-
- _end_of_message_
- req = WEBrick::HTTPRequest.new(WEBrick::Config::HTTP)
- req.parse(StringIO.new(msg.gsub(/^ {6}/, "")))
- assert_equal("GET", req.request_method)
- assert_equal("/path", req.unparsed_uri)
- assert_equal("", req.script_name)
- assert_equal("/path", req.path_info)
- assert_equal(WEBrick::HTTPVersion.new("1.1"), req.http_version)
- assert_equal(WEBrick::Config::HTTP[:ServerName], req.host)
- assert_equal(80, req.port)
- assert_equal(true, req.keep_alive?)
- assert_equal(nil, req.body)
- assert(req.query.empty?)
- end
-
- def test_parse_headers
- msg = <<-_end_of_message_
- GET /path HTTP/1.1
- Host: test.ruby-lang.org:8080
- Connection: close
- Accept: text/*;q=0.3, text/html;q=0.7, text/html;level=1,
- text/html;level=2;q=0.4, */*;q=0.5
- Accept-Encoding: compress;q=0.5
- Accept-Encoding: gzip;q=1.0, identity; q=0.4, *;q=0
- Accept-Language: en;q=0.5, *; q=0
- Accept-Language: ja
- Content-Type: text/plain
- Content-Length: 7
-
- foobar
- _end_of_message_
- req = WEBrick::HTTPRequest.new(WEBrick::Config::HTTP)
- req.parse(StringIO.new(msg.gsub(/^ {6}/, "")))
- assert_equal(
- URI.parse("http://test.ruby-lang.org:8080/path"), req.request_uri)
- assert_equal("test.ruby-lang.org", req.host)
- assert_equal(8080, req.port)
- assert_equal(false, req.keep_alive?)
- assert_equal(
- %w(text/html;level=1 text/html */* text/html;level=2 text/*),
- req.accept)
- assert_equal(%w(gzip compress identity *), req.accept_encoding)
- assert_equal(%w(ja en *), req.accept_language)
- assert_equal(7, req.content_length)
- assert_equal("text/plain", req.content_type)
- assert_equal("foobar\n", req.body)
- assert(req.query.empty?)
- end
-
- def test_parse_header2()
- msg = <<-_end_of_message_
- POST /foo/bar/../baz?q=a HTTP/1.0
- Content-Length: 9
- User-Agent:
- FOO BAR
- BAZ
-
- hogehoge
- _end_of_message_
- req = WEBrick::HTTPRequest.new(WEBrick::Config::HTTP)
- req.parse(StringIO.new(msg.gsub(/^ {6}/, "")))
- assert_equal("POST", req.request_method)
- assert_equal("/foo/baz", req.path)
- assert_equal("", req.script_name)
- assert_equal("/foo/baz", req.path_info)
- assert_equal("9", req['content-length'])
- assert_equal("FOO BAR BAZ", req['user-agent'])
- assert_equal("hogehoge\n", req.body)
- end
-
-
- def test_parse_get_params
- param = "foo=1;foo=2;foo=3;bar=x"
- msg = <<-_end_of_message_
- GET /path?#{param} HTTP/1.1
- Host: test.ruby-lang.org:8080
-
- _end_of_message_
- req = WEBrick::HTTPRequest.new(WEBrick::Config::HTTP)
- req.parse(StringIO.new(msg.gsub(/^ {6}/, "")))
- query = req.query
- assert_equal("1", query["foo"])
- assert_equal(["1", "2", "3"], query["foo"].to_ary)
- assert_equal(["1", "2", "3"], query["foo"].list)
- assert_equal("x", query["bar"])
- assert_equal(["x"], query["bar"].list)
- end
-
- def test_parse_post_params
- param = "foo=1;foo=2;foo=3;bar=x"
- msg = <<-_end_of_message_
- POST /path?foo=x;foo=y;foo=z;bar=1 HTTP/1.1
- Host: test.ruby-lang.org:8080
- Content-Length: #{param.size}
- Content-Type: application/x-www-form-urlencoded
-
- #{param}
- _end_of_message_
- req = WEBrick::HTTPRequest.new(WEBrick::Config::HTTP)
- req.parse(StringIO.new(msg.gsub(/^ {6}/, "")))
- query = req.query
- assert_equal("1", query["foo"])
- assert_equal(["1", "2", "3"], query["foo"].to_ary)
- assert_equal(["1", "2", "3"], query["foo"].list)
- assert_equal("x", query["bar"])
- assert_equal(["x"], query["bar"].list)
- end
-
- def test_chunked
- crlf = "\x0d\x0a"
- msg = <<-_end_of_message_
- POST /path HTTP/1.1
- Host: test.ruby-lang.org:8080
- Transfer-Encoding: chunked
-
- _end_of_message_
- msg.gsub!(/^ {6}/, "")
- open(__FILE__){|io|
- while chunk = io.read(100)
- msg << chunk.size.to_s(16) << crlf
- msg << chunk << crlf
- end
- }
- msg << "0" << crlf
- req = WEBrick::HTTPRequest.new(WEBrick::Config::HTTP)
- req.parse(StringIO.new(msg))
- assert_equal(File.read(__FILE__), req.body)
- end
-
- def test_bad_messages
- param = "foo=1;foo=2;foo=3;bar=x"
- msg = <<-_end_of_message_
- POST /path?foo=x;foo=y;foo=z;bar=1 HTTP/1.1
- Host: test.ruby-lang.org:8080
- Content-Type: application/x-www-form-urlencoded
-
- #{param}
- _end_of_message_
- assert_raises(WEBrick::HTTPStatus::LengthRequired){
- req = WEBrick::HTTPRequest.new(WEBrick::Config::HTTP)
- req.parse(StringIO.new(msg.gsub(/^ {6}/, "")))
- req.body
- }
-
- msg = <<-_end_of_message_
- POST /path?foo=x;foo=y;foo=z;bar=1 HTTP/1.1
- Host: test.ruby-lang.org:8080
- Content-Length: 100000
-
- body is too short.
- _end_of_message_
- assert_raises(WEBrick::HTTPStatus::BadRequest){
- req = WEBrick::HTTPRequest.new(WEBrick::Config::HTTP)
- req.parse(StringIO.new(msg.gsub(/^ {6}/, "")))
- req.body
- }
-
- msg = <<-_end_of_message_
- POST /path?foo=x;foo=y;foo=z;bar=1 HTTP/1.1
- Host: test.ruby-lang.org:8080
- Transfer-Encoding: foobar
-
- body is too short.
- _end_of_message_
- assert_raises(WEBrick::HTTPStatus::NotImplemented){
- req = WEBrick::HTTPRequest.new(WEBrick::Config::HTTP)
- req.parse(StringIO.new(msg.gsub(/^ {6}/, "")))
- req.body
- }
- end
-end
diff --git a/test/webrick/test_httpserver.rb b/test/webrick/test_httpserver.rb
deleted file mode 100644
index eb685f916d..0000000000
--- a/test/webrick/test_httpserver.rb
+++ /dev/null
@@ -1,260 +0,0 @@
-require "test/unit"
-require "net/http"
-require "webrick"
-require File.join(File.dirname(__FILE__), "utils.rb")
-
-class TestWEBrickHTTPServer < Test::Unit::TestCase
- def test_mount
- httpd = WEBrick::HTTPServer.new(
- :Logger => WEBrick::Log.new(TestWEBrick::NullWriter),
- :DoNotListen=>true
- )
- httpd.mount("/", :Root)
- httpd.mount("/foo", :Foo)
- httpd.mount("/foo/bar", :Bar, :bar1)
- httpd.mount("/foo/bar/baz", :Baz, :baz1, :baz2)
-
- serv, opts, script_name, path_info = httpd.search_servlet("/")
- assert_equal(:Root, serv)
- assert_equal([], opts)
- assert_equal(script_name, "")
- assert_equal(path_info, "/")
-
- serv, opts, script_name, path_info = httpd.search_servlet("/sub")
- assert_equal(:Root, serv)
- assert_equal([], opts)
- assert_equal(script_name, "")
- assert_equal(path_info, "/sub")
-
- serv, opts, script_name, path_info = httpd.search_servlet("/sub/")
- assert_equal(:Root, serv)
- assert_equal([], opts)
- assert_equal(script_name, "")
- assert_equal(path_info, "/sub/")
-
- serv, opts, script_name, path_info = httpd.search_servlet("/foo")
- assert_equal(:Foo, serv)
- assert_equal([], opts)
- assert_equal(script_name, "/foo")
- assert_equal(path_info, "")
-
- serv, opts, script_name, path_info = httpd.search_servlet("/foo/")
- assert_equal(:Foo, serv)
- assert_equal([], opts)
- assert_equal(script_name, "/foo")
- assert_equal(path_info, "/")
-
- serv, opts, script_name, path_info = httpd.search_servlet("/foo/sub")
- assert_equal(:Foo, serv)
- assert_equal([], opts)
- assert_equal(script_name, "/foo")
- assert_equal(path_info, "/sub")
-
- serv, opts, script_name, path_info = httpd.search_servlet("/foo/bar")
- assert_equal(:Bar, serv)
- assert_equal([:bar1], opts)
- assert_equal(script_name, "/foo/bar")
- assert_equal(path_info, "")
-
- serv, opts, script_name, path_info = httpd.search_servlet("/foo/bar/baz")
- assert_equal(:Baz, serv)
- assert_equal([:baz1, :baz2], opts)
- assert_equal(script_name, "/foo/bar/baz")
- assert_equal(path_info, "")
- end
-
- class Req
- attr_reader :port, :host
- def initialize(addr, port, host)
- @addr, @port, @host = addr, port, host
- end
- def addr
- [0,0,0,@addr]
- end
- end
-
- def httpd(addr, port, host, ali)
- config ={
- :Logger => WEBrick::Log.new(TestWEBrick::NullWriter),
- :DoNotListen => true,
- :BindAddress => addr,
- :Port => port,
- :ServerName => host,
- :ServerAlias => ali,
- }
- return WEBrick::HTTPServer.new(config)
- end
-
- def assert_eql?(v1, v2)
- assert_equal(v1.object_id, v2.object_id)
- end
-
- def test_lookup_server
- addr1 = "192.168.100.1"
- addr2 = "192.168.100.2"
- addrz = "192.168.100.254"
- local = "127.0.0.1"
- port1 = 80
- port2 = 8080
- port3 = 10080
- portz = 32767
- name1 = "www.example.com"
- name2 = "www2.example.com"
- name3 = "www3.example.com"
- namea = "www.example.co.jp"
- nameb = "www.example.jp"
- namec = "www2.example.co.jp"
- named = "www2.example.jp"
- namez = "foobar.example.com"
- alias1 = [namea, nameb]
- alias2 = [namec, named]
-
- host1 = httpd(nil, port1, name1, nil)
- hosts = [
- host2 = httpd(addr1, port1, name1, nil),
- host3 = httpd(addr1, port1, name2, alias1),
- host4 = httpd(addr1, port2, name1, nil),
- host5 = httpd(addr1, port2, name2, alias1),
- host6 = httpd(addr1, port2, name3, alias2),
- host7 = httpd(addr2, nil, name1, nil),
- host8 = httpd(addr2, nil, name2, alias1),
- host9 = httpd(addr2, nil, name3, alias2),
- host10 = httpd(local, nil, nil, nil),
- host11 = httpd(nil, port3, nil, nil),
- ].sort_by{ rand }
- hosts.each{|h| host1.virtual_host(h) }
-
- # connect to addr1
- assert_eql?(host2, host1.lookup_server(Req.new(addr1, port1, name1)))
- assert_eql?(host3, host1.lookup_server(Req.new(addr1, port1, name2)))
- assert_eql?(host3, host1.lookup_server(Req.new(addr1, port1, namea)))
- assert_eql?(host3, host1.lookup_server(Req.new(addr1, port1, nameb)))
- assert_eql?(nil, host1.lookup_server(Req.new(addr1, port1, namez)))
- assert_eql?(host4, host1.lookup_server(Req.new(addr1, port2, name1)))
- assert_eql?(host5, host1.lookup_server(Req.new(addr1, port2, name2)))
- assert_eql?(host5, host1.lookup_server(Req.new(addr1, port2, namea)))
- assert_eql?(host5, host1.lookup_server(Req.new(addr1, port2, nameb)))
- assert_eql?(nil, host1.lookup_server(Req.new(addr1, port2, namez)))
- assert_eql?(host11, host1.lookup_server(Req.new(addr1, port3, name1)))
- assert_eql?(host11, host1.lookup_server(Req.new(addr1, port3, name2)))
- assert_eql?(host11, host1.lookup_server(Req.new(addr1, port3, namea)))
- assert_eql?(host11, host1.lookup_server(Req.new(addr1, port3, nameb)))
- assert_eql?(host11, host1.lookup_server(Req.new(addr1, port3, namez)))
- assert_eql?(nil, host1.lookup_server(Req.new(addr1, portz, name1)))
- assert_eql?(nil, host1.lookup_server(Req.new(addr1, portz, name2)))
- assert_eql?(nil, host1.lookup_server(Req.new(addr1, portz, namea)))
- assert_eql?(nil, host1.lookup_server(Req.new(addr1, portz, nameb)))
- assert_eql?(nil, host1.lookup_server(Req.new(addr1, portz, namez)))
-
- # connect to addr2
- assert_eql?(host7, host1.lookup_server(Req.new(addr2, port1, name1)))
- assert_eql?(host8, host1.lookup_server(Req.new(addr2, port1, name2)))
- assert_eql?(host8, host1.lookup_server(Req.new(addr2, port1, namea)))
- assert_eql?(host8, host1.lookup_server(Req.new(addr2, port1, nameb)))
- assert_eql?(nil, host1.lookup_server(Req.new(addr2, port1, namez)))
- assert_eql?(host7, host1.lookup_server(Req.new(addr2, port2, name1)))
- assert_eql?(host8, host1.lookup_server(Req.new(addr2, port2, name2)))
- assert_eql?(host8, host1.lookup_server(Req.new(addr2, port2, namea)))
- assert_eql?(host8, host1.lookup_server(Req.new(addr2, port2, nameb)))
- assert_eql?(nil, host1.lookup_server(Req.new(addr2, port2, namez)))
- assert_eql?(host7, host1.lookup_server(Req.new(addr2, port3, name1)))
- assert_eql?(host8, host1.lookup_server(Req.new(addr2, port3, name2)))
- assert_eql?(host8, host1.lookup_server(Req.new(addr2, port3, namea)))
- assert_eql?(host8, host1.lookup_server(Req.new(addr2, port3, nameb)))
- assert_eql?(host11, host1.lookup_server(Req.new(addr2, port3, namez)))
- assert_eql?(host7, host1.lookup_server(Req.new(addr2, portz, name1)))
- assert_eql?(host8, host1.lookup_server(Req.new(addr2, portz, name2)))
- assert_eql?(host8, host1.lookup_server(Req.new(addr2, portz, namea)))
- assert_eql?(host8, host1.lookup_server(Req.new(addr2, portz, nameb)))
- assert_eql?(nil, host1.lookup_server(Req.new(addr2, portz, namez)))
-
- # connect to addrz
- assert_eql?(nil, host1.lookup_server(Req.new(addrz, port1, name1)))
- assert_eql?(nil, host1.lookup_server(Req.new(addrz, port1, name2)))
- assert_eql?(nil, host1.lookup_server(Req.new(addrz, port1, namea)))
- assert_eql?(nil, host1.lookup_server(Req.new(addrz, port1, nameb)))
- assert_eql?(nil, host1.lookup_server(Req.new(addrz, port1, namez)))
- assert_eql?(nil, host1.lookup_server(Req.new(addrz, port2, name1)))
- assert_eql?(nil, host1.lookup_server(Req.new(addrz, port2, name2)))
- assert_eql?(nil, host1.lookup_server(Req.new(addrz, port2, namea)))
- assert_eql?(nil, host1.lookup_server(Req.new(addrz, port2, nameb)))
- assert_eql?(nil, host1.lookup_server(Req.new(addrz, port2, namez)))
- assert_eql?(host11, host1.lookup_server(Req.new(addrz, port3, name1)))
- assert_eql?(host11, host1.lookup_server(Req.new(addrz, port3, name2)))
- assert_eql?(host11, host1.lookup_server(Req.new(addrz, port3, namea)))
- assert_eql?(host11, host1.lookup_server(Req.new(addrz, port3, nameb)))
- assert_eql?(host11, host1.lookup_server(Req.new(addrz, port3, namez)))
- assert_eql?(nil, host1.lookup_server(Req.new(addrz, portz, name1)))
- assert_eql?(nil, host1.lookup_server(Req.new(addrz, portz, name2)))
- assert_eql?(nil, host1.lookup_server(Req.new(addrz, portz, namea)))
- assert_eql?(nil, host1.lookup_server(Req.new(addrz, portz, nameb)))
- assert_eql?(nil, host1.lookup_server(Req.new(addrz, portz, namez)))
-
- # connect to localhost
- assert_eql?(host10, host1.lookup_server(Req.new(local, port1, name1)))
- assert_eql?(host10, host1.lookup_server(Req.new(local, port1, name2)))
- assert_eql?(host10, host1.lookup_server(Req.new(local, port1, namea)))
- assert_eql?(host10, host1.lookup_server(Req.new(local, port1, nameb)))
- assert_eql?(host10, host1.lookup_server(Req.new(local, port1, namez)))
- assert_eql?(host10, host1.lookup_server(Req.new(local, port2, name1)))
- assert_eql?(host10, host1.lookup_server(Req.new(local, port2, name2)))
- assert_eql?(host10, host1.lookup_server(Req.new(local, port2, namea)))
- assert_eql?(host10, host1.lookup_server(Req.new(local, port2, nameb)))
- assert_eql?(host10, host1.lookup_server(Req.new(local, port2, namez)))
- assert_eql?(host10, host1.lookup_server(Req.new(local, port3, name1)))
- assert_eql?(host10, host1.lookup_server(Req.new(local, port3, name2)))
- assert_eql?(host10, host1.lookup_server(Req.new(local, port3, namea)))
- assert_eql?(host10, host1.lookup_server(Req.new(local, port3, nameb)))
- assert_eql?(host10, host1.lookup_server(Req.new(local, port3, namez)))
- assert_eql?(host10, host1.lookup_server(Req.new(local, portz, name1)))
- assert_eql?(host10, host1.lookup_server(Req.new(local, portz, name2)))
- assert_eql?(host10, host1.lookup_server(Req.new(local, portz, namea)))
- assert_eql?(host10, host1.lookup_server(Req.new(local, portz, nameb)))
- assert_eql?(host10, host1.lookup_server(Req.new(local, portz, namez)))
- end
-
- def test_callbacks
- accepted = started = stopped = 0
- requested0 = requested1 = 0
- config = {
- :ServerName => "localhost",
- :AcceptCallback => Proc.new{ accepted += 1 },
- :StartCallback => Proc.new{ started += 1 },
- :StopCallback => Proc.new{ stopped += 1 },
- :RequestCallback => Proc.new{|req, res| requested0 += 1 },
- }
- TestWEBrick.start_httpserver(config){|server, addr, port|
- vhost_config = {
- :ServerName => "myhostname",
- :BindAddress => addr,
- :Port => port,
- :DoNotListen => true,
- :Logger => WEBrick::Log.new(TestWEBrick::NullWriter),
- :AccessLog => [],
- :RequestCallback => Proc.new{|req, res| requested1 += 1 },
- }
- server.virtual_host(WEBrick::HTTPServer.new(vhost_config))
-
- true while server.status != :Running
- assert_equal(started, 1)
- assert_equal(stopped, 0)
- assert_equal(accepted, 0)
-
- http = Net::HTTP.new(addr, port)
- req = Net::HTTP::Get.new("/")
- req["Host"] = "myhostname:#{port}"
- http.request(req){|res| assert_equal("404", res.code)}
- http.request(req){|res| assert_equal("404", res.code)}
- http.request(req){|res| assert_equal("404", res.code)}
- req["Host"] = "localhost:#{port}"
- http.request(req){|res| assert_equal("404", res.code)}
- http.request(req){|res| assert_equal("404", res.code)}
- http.request(req){|res| assert_equal("404", res.code)}
- assert_equal(6, accepted)
- assert_equal(3, requested0)
- assert_equal(3, requested1)
- }
- assert_equal(started, 1)
- assert_equal(stopped, 1)
- end
-end
diff --git a/test/webrick/test_httputils.rb b/test/webrick/test_httputils.rb
deleted file mode 100644
index 9d39ff53ab..0000000000
--- a/test/webrick/test_httputils.rb
+++ /dev/null
@@ -1,96 +0,0 @@
-require "test/unit"
-require "webrick/httputils"
-
-class TestWEBrickHTTPUtils < Test::Unit::TestCase
- include WEBrick::HTTPUtils
-
- def test_normilize_path
- assert_equal("/foo", normalize_path("/foo"))
- assert_equal("/foo/bar/", normalize_path("/foo/bar/"))
-
- assert_equal("/", normalize_path("/foo/../"))
- assert_equal("/", normalize_path("/foo/.."))
- assert_equal("/", normalize_path("/foo/bar/../../"))
- assert_equal("/", normalize_path("/foo/bar/../.."))
- assert_equal("/", normalize_path("/foo/bar/../.."))
- assert_equal("/baz", normalize_path("/foo/bar/../../baz"))
- assert_equal("/baz", normalize_path("/foo/../bar/../baz"))
- assert_equal("/baz/", normalize_path("/foo/../bar/../baz/"))
- assert_equal("/...", normalize_path("/bar/../..."))
- assert_equal("/.../", normalize_path("/bar/../.../"))
-
- assert_equal("/foo/", normalize_path("/foo/./"))
- assert_equal("/foo/", normalize_path("/foo/."))
- assert_equal("/foo/", normalize_path("/foo/././"))
- assert_equal("/foo/", normalize_path("/foo/./."))
- assert_equal("/foo/bar", normalize_path("/foo/./bar"))
- assert_equal("/foo/bar/", normalize_path("/foo/./bar/."))
- assert_equal("/foo/bar/", normalize_path("/./././foo/./bar/."))
-
- assert_equal("/foo/bar/", normalize_path("//foo///.//bar/.///.//"))
- assert_equal("/", normalize_path("//foo///..///bar/.///..//.//"))
-
- assert_raises(RuntimeError){ normalize_path("foo/bar") }
- assert_raises(RuntimeError){ normalize_path("..") }
- assert_raises(RuntimeError){ normalize_path("/..") }
- assert_raises(RuntimeError){ normalize_path("/./..") }
- assert_raises(RuntimeError){ normalize_path("/./../") }
- assert_raises(RuntimeError){ normalize_path("/./../..") }
- assert_raises(RuntimeError){ normalize_path("/./../../") }
- assert_raises(RuntimeError){ normalize_path("/./../") }
- assert_raises(RuntimeError){ normalize_path("/../..") }
- assert_raises(RuntimeError){ normalize_path("/../../") }
- assert_raises(RuntimeError){ normalize_path("/../../..") }
- assert_raises(RuntimeError){ normalize_path("/../../../") }
- assert_raises(RuntimeError){ normalize_path("/../foo/../") }
- assert_raises(RuntimeError){ normalize_path("/../foo/../../") }
- assert_raises(RuntimeError){ normalize_path("/foo/bar/../../../../") }
- assert_raises(RuntimeError){ normalize_path("/foo/../bar/../../") }
- assert_raises(RuntimeError){ normalize_path("/./../bar/") }
- assert_raises(RuntimeError){ normalize_path("/./../") }
- end
-
- def test_split_header_value
- assert_equal(['foo', 'bar'], split_header_value('foo, bar'))
- assert_equal(['"foo"', 'bar'], split_header_value('"foo", bar'))
- assert_equal(['foo', '"bar"'], split_header_value('foo, "bar"'))
- assert_equal(['*'], split_header_value('*'))
- assert_equal(['W/"xyzzy"', 'W/"r2d2xxxx"', 'W/"c3piozzzz"'],
- split_header_value('W/"xyzzy", W/"r2d2xxxx", W/"c3piozzzz"'))
- end
-
- def test_escape
- assert_equal("/foo/bar", escape("/foo/bar"))
- assert_equal("/~foo/bar", escape("/~foo/bar"))
- assert_equal("/~foo%20bar", escape("/~foo bar"))
- assert_equal("/~foo%20bar", escape("/~foo bar"))
- assert_equal("/~foo%09bar", escape("/~foo\tbar"))
- assert_equal("/~foo+bar", escape("/~foo+bar"))
- end
-
- def test_escape_form
- assert_equal("%2Ffoo%2Fbar", escape_form("/foo/bar"))
- assert_equal("%2F~foo%2Fbar", escape_form("/~foo/bar"))
- assert_equal("%2F~foo+bar", escape_form("/~foo bar"))
- assert_equal("%2F~foo+%2B+bar", escape_form("/~foo + bar"))
- end
-
- def test_unescape
- assert_equal("/foo/bar", unescape("%2ffoo%2fbar"))
- assert_equal("/~foo/bar", unescape("/%7efoo/bar"))
- assert_equal("/~foo/bar", unescape("%2f%7efoo%2fbar"))
- assert_equal("/~foo+bar", unescape("/%7efoo+bar"))
- end
-
- def test_unescape_form
- assert_equal("//foo/bar", unescape_form("/%2Ffoo/bar"))
- assert_equal("//foo/bar baz", unescape_form("/%2Ffoo/bar+baz"))
- assert_equal("/~foo/bar baz", unescape_form("/%7Efoo/bar+baz"))
- end
-
- def test_escape_path
- assert_equal("/foo/bar", escape_path("/foo/bar"))
- assert_equal("/foo/bar/", escape_path("/foo/bar/"))
- assert_equal("/%25foo/bar/", escape_path("/%foo/bar/"))
- end
-end
diff --git a/test/webrick/test_httpversion.rb b/test/webrick/test_httpversion.rb
deleted file mode 100644
index 81a871a226..0000000000
--- a/test/webrick/test_httpversion.rb
+++ /dev/null
@@ -1,40 +0,0 @@
-require "test/unit"
-require "webrick/httpversion"
-
-class TestWEBrickHTTPVersion < Test::Unit::TestCase
- def setup
- @v09 = WEBrick::HTTPVersion.new("0.9")
- @v10 = WEBrick::HTTPVersion.new("1.0")
- @v11 = WEBrick::HTTPVersion.new("1.001")
- end
-
- def test_to_s()
- assert_equal("0.9", @v09.to_s)
- assert_equal("1.0", @v10.to_s)
- assert_equal("1.1", @v11.to_s)
- end
-
- def test_major()
- assert_equal(0, @v09.major)
- assert_equal(1, @v10.major)
- assert_equal(1, @v11.major)
- end
-
- def test_minor()
- assert_equal(9, @v09.minor)
- assert_equal(0, @v10.minor)
- assert_equal(1, @v11.minor)
- end
-
- def test_compar()
- assert_equal(0, @v09 <=> "0.9")
- assert_equal(0, @v09 <=> "0.09")
-
- assert_equal(-1, @v09 <=> @v10)
- assert_equal(-1, @v09 <=> "1.00")
-
- assert_equal(1, @v11 <=> @v09)
- assert_equal(1, @v11 <=> "1.0")
- assert_equal(1, @v11 <=> "0.9")
- end
-end
diff --git a/test/webrick/test_server.rb b/test/webrick/test_server.rb
deleted file mode 100644
index ce5ee85c6c..0000000000
--- a/test/webrick/test_server.rb
+++ /dev/null
@@ -1,64 +0,0 @@
-require "test/unit"
-require "tempfile"
-require "webrick"
-require File.join(File.dirname(__FILE__), "utils.rb")
-
-class TestWEBrickServer < Test::Unit::TestCase
- class Echo < WEBrick::GenericServer
- def run(sock)
- while line = sock.gets
- sock << line
- end
- end
- end
-
- def test_server
- TestWEBrick.start_server(Echo){|server, addr, port|
- TCPSocket.open(addr, port){|sock|
- sock.puts("foo"); assert_equal("foo\n", sock.gets)
- sock.puts("bar"); assert_equal("bar\n", sock.gets)
- sock.puts("baz"); assert_equal("baz\n", sock.gets)
- sock.puts("qux"); assert_equal("qux\n", sock.gets)
- }
- }
- end
-
- def test_callbacks
- accepted = started = stopped = 0
- config = {
- :AcceptCallback => Proc.new{ accepted += 1 },
- :StartCallback => Proc.new{ started += 1 },
- :StopCallback => Proc.new{ stopped += 1 },
- }
- TestWEBrick.start_server(Echo, config){|server, addr, port|
- true while server.status != :Running
- assert_equal(started, 1)
- assert_equal(stopped, 0)
- assert_equal(accepted, 0)
- TCPSocket.open(addr, port){|sock| (sock << "foo\n").gets }
- TCPSocket.open(addr, port){|sock| (sock << "foo\n").gets }
- TCPSocket.open(addr, port){|sock| (sock << "foo\n").gets }
- assert_equal(accepted, 3)
- }
- assert_equal(started, 1)
- assert_equal(stopped, 1)
- end
-
- def test_daemon
- begin
- r, w = IO.pipe
- Process.fork{
- r.close
- WEBrick::Daemon.start
- w.puts(Process.pid)
- sleep
- }
- assert(Process.kill(:KILL, r.gets.to_i))
- rescue NotImplementedError
- # snip this test
- ensure
- r.close
- w.close
- end
- end
-end
diff --git a/test/webrick/utils.rb b/test/webrick/utils.rb
deleted file mode 100644
index f1e6e4b027..0000000000
--- a/test/webrick/utils.rb
+++ /dev/null
@@ -1,40 +0,0 @@
-require "webrick"
-begin
- require "webrick/https"
-rescue LoadError
-end
-require "webrick/httpproxy"
-
-module TestWEBrick
- NullWriter = Object.new
- def NullWriter.<<(msg)
- puts msg if $DEBUG
- return self
- end
-
- module_function
-
- def start_server(klass, config={}, &block)
- server = klass.new({
- :BindAddress => "127.0.0.1", :Port => 0,
- :Logger => WEBrick::Log.new(NullWriter),
- :AccessLog => [[NullWriter, ""]]
- }.update(config))
- begin
- thread = Thread.start{ server.start }
- addr = server.listeners[0].addr
- block.call([server, addr[3], addr[1]])
- ensure
- server.stop
- thread.join
- end
- end
-
- def start_httpserver(config={}, &block)
- start_server(WEBrick::HTTPServer, config, &block)
- end
-
- def start_httpproxy(config={}, &block)
- start_server(WEBrick::HTTPProxyServer, config, &block)
- end
-end
diff --git a/test/webrick/webrick.cgi b/test/webrick/webrick.cgi
deleted file mode 100644
index 9edbb13847..0000000000
--- a/test/webrick/webrick.cgi
+++ /dev/null
@@ -1,30 +0,0 @@
-#!ruby -d
-require "webrick/cgi"
-
-class TestApp < WEBrick::CGI
- def do_GET(req, res)
- res["content-type"] = "text/plain"
- if (p = req.path_info) && p.length > 0
- res.body = p
- elsif (q = req.query).size > 0
- res.body = q.keys.sort.collect{|key|
- q[key].list.sort.collect{|v|
- "#{key}=#{v}"
- }.join(", ")
- }.join(", ")
- elsif %r{/$} =~ req.request_uri.to_s
- res.body = ""
- res.body << req.request_uri.to_s << "\n"
- res.body << req.script_name
- else
- res.body = req.script_name
- end
- end
-
- def do_POST(req, res)
- do_GET(req, res)
- end
-end
-
-cgi = TestApp.new
-cgi.start
diff --git a/test/wsdl/any/any.wsdl b/test/wsdl/any/any.wsdl
deleted file mode 100644
index 4d1f73a8cd..0000000000
--- a/test/wsdl/any/any.wsdl
+++ /dev/null
@@ -1,50 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<definitions name="echo"
- xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/"
- xmlns:xsd="http://www.w3.org/2001/XMLSchema"
- xmlns:tns="urn:example.com:echo"
- xmlns:txd="urn:example.com:echo-type"
- targetNamespace="urn:example.com:echo"
- xmlns="http://schemas.xmlsoap.org/wsdl/">
- <types>
- <xsd:schema targetNamespace="urn:example.com:echo-type">
- <xsd:complexType name="foo.bar">
- <xsd:sequence>
- <xsd:any />
- </xsd:sequence>
- </xsd:complexType>
- </xsd:schema>
- </types>
-
- <message name="msg_echoitem">
- <part name="echoitem" type="txd:foo.bar"/>
- </message>
-
- <portType name="echo_port_type">
- <operation name="echo">
- <input message="tns:msg_echoitem"/>
- <output message="tns:msg_echoitem"/>
- </operation>
- </portType>
-
- <binding name="echo_binding" type="tns:echo_port_type">
- <soap:binding transport="http://schemas.xmlsoap.org/soap/http" style="rpc"/>
- <operation name="echo">
- <soap:operation soapAction="urn:example.com:echo"/>
- <input>
- <soap:body use="encoded" namespace="urn:example.com:echo"
- encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"/>
- </input>
- <output>
- <soap:body use="encoded" namespace="urn:example.com:echo"
- encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"/>
- </output>
- </operation>
- </binding>
-
- <service name="echo_service">
- <port name="echo_port" binding="tns:echo_binding">
- <soap:address location="http://localhost:10080"/>
- </port>
- </service>
-</definitions>
diff --git a/test/wsdl/any/expectedDriver.rb b/test/wsdl/any/expectedDriver.rb
deleted file mode 100644
index 6d1827fb94..0000000000
--- a/test/wsdl/any/expectedDriver.rb
+++ /dev/null
@@ -1,54 +0,0 @@
-require 'echo.rb'
-
-require 'soap/rpc/driver'
-
-class Echo_port_type < ::SOAP::RPC::Driver
- DefaultEndpointUrl = "http://localhost:10080"
- MappingRegistry = ::SOAP::Mapping::Registry.new
-
- MappingRegistry.set(
- FooBar,
- ::SOAP::SOAPStruct,
- ::SOAP::Mapping::Registry::TypedStructFactory,
- { :type => XSD::QName.new("urn:example.com:echo-type", "foo.bar") }
- )
-
- Methods = [
- [ XSD::QName.new("urn:example.com:echo", "echo"),
- "urn:example.com:echo",
- "echo",
- [ ["in", "echoitem", ["FooBar", "urn:example.com:echo-type", "foo.bar"]],
- ["retval", "echoitem", ["FooBar", "urn:example.com:echo-type", "foo.bar"]] ],
- { :request_style => :rpc, :request_use => :encoded,
- :response_style => :rpc, :response_use => :encoded }
- ]
- ]
-
- def initialize(endpoint_url = nil)
- endpoint_url ||= DefaultEndpointUrl
- super(endpoint_url, nil)
- self.mapping_registry = MappingRegistry
- init_methods
- end
-
-private
-
- def init_methods
- Methods.each do |definitions|
- opt = definitions.last
- if opt[:request_style] == :document
- add_document_operation(*definitions)
- else
- add_rpc_operation(*definitions)
- qname = definitions[0]
- name = definitions[2]
- if qname.name != name and qname.name.capitalize == name.capitalize
- ::SOAP::Mapping.define_singleton_method(self, qname.name) do |*arg|
- __send__(name, *arg)
- end
- end
- end
- end
- end
-end
-
diff --git a/test/wsdl/any/expectedEcho.rb b/test/wsdl/any/expectedEcho.rb
deleted file mode 100644
index 456950dfef..0000000000
--- a/test/wsdl/any/expectedEcho.rb
+++ /dev/null
@@ -1,14 +0,0 @@
-require 'xsd/qname'
-
-# {urn:example.com:echo-type}foo.bar
-class FooBar
- @@schema_type = "foo.bar"
- @@schema_ns = "urn:example.com:echo-type"
- @@schema_element = [["any", [nil, XSD::QName.new(nil, "any")]]]
-
- attr_accessor :any
-
- def initialize(any = nil)
- @any = any
- end
-end
diff --git a/test/wsdl/any/expectedService.rb b/test/wsdl/any/expectedService.rb
deleted file mode 100644
index e3885e7c6c..0000000000
--- a/test/wsdl/any/expectedService.rb
+++ /dev/null
@@ -1,52 +0,0 @@
-#!/usr/bin/env ruby
-require 'echoServant.rb'
-
-require 'soap/rpc/standaloneServer'
-require 'soap/mapping/registry'
-
-class Echo_port_type
- MappingRegistry = ::SOAP::Mapping::Registry.new
-
- MappingRegistry.set(
- FooBar,
- ::SOAP::SOAPStruct,
- ::SOAP::Mapping::Registry::TypedStructFactory,
- { :type => XSD::QName.new("urn:example.com:echo-type", "foo.bar") }
- )
-
- Methods = [
- [ XSD::QName.new("urn:example.com:echo", "echo"),
- "urn:example.com:echo",
- "echo",
- [ ["in", "echoitem", ["FooBar", "urn:example.com:echo-type", "foo.bar"]],
- ["retval", "echoitem", ["FooBar", "urn:example.com:echo-type", "foo.bar"]] ],
- { :request_style => :rpc, :request_use => :encoded,
- :response_style => :rpc, :response_use => :encoded }
- ]
- ]
-end
-
-class Echo_port_typeApp < ::SOAP::RPC::StandaloneServer
- def initialize(*arg)
- super(*arg)
- servant = Echo_port_type.new
- Echo_port_type::Methods.each do |definitions|
- opt = definitions.last
- if opt[:request_style] == :document
- @router.add_document_operation(servant, *definitions)
- else
- @router.add_rpc_operation(servant, *definitions)
- end
- end
- self.mapping_registry = Echo_port_type::MappingRegistry
- end
-end
-
-if $0 == __FILE__
- # Change listen port.
- server = Echo_port_typeApp.new('app', nil, '0.0.0.0', 10080)
- trap(:INT) do
- server.shutdown
- end
- server.start
-end
diff --git a/test/wsdl/any/test_any.rb b/test/wsdl/any/test_any.rb
deleted file mode 100644
index aab5eb631f..0000000000
--- a/test/wsdl/any/test_any.rb
+++ /dev/null
@@ -1,58 +0,0 @@
-require 'test/unit'
-require 'wsdl/parser'
-require 'wsdl/soap/wsdl2ruby'
-module WSDL; module Any
-
-
-class TestAny < Test::Unit::TestCase
- DIR = File.dirname(File.expand_path(__FILE__))
- def pathname(filename)
- File.join(DIR, filename)
- end
-
- def test_any
- gen = WSDL::SOAP::WSDL2Ruby.new
- gen.location = pathname("any.wsdl")
- gen.basedir = DIR
- gen.logger.level = Logger::FATAL
- gen.opt['classdef'] = nil
- gen.opt['driver'] = nil
- gen.opt['client_skelton'] = nil
- gen.opt['servant_skelton'] = nil
- gen.opt['standalone_server_stub'] = nil
- gen.opt['force'] = true
- suppress_warning do
- gen.run
- end
- compare("expectedDriver.rb", "echoDriver.rb")
- compare("expectedEcho.rb", "echo.rb")
- compare("expectedService.rb", "echo_service.rb")
-
- File.unlink(pathname("echo_service.rb"))
- File.unlink(pathname("echo.rb"))
- File.unlink(pathname("echo_serviceClient.rb"))
- File.unlink(pathname("echoDriver.rb"))
- File.unlink(pathname("echoServant.rb"))
- end
-
- def compare(expected, actual)
- assert_equal(loadfile(expected), loadfile(actual), actual)
- end
-
- def loadfile(file)
- File.open(pathname(file)) { |f| f.read }
- end
-
- def suppress_warning
- back = $VERBOSE
- $VERBOSE = nil
- begin
- yield
- ensure
- $VERBOSE = back
- end
- end
-end
-
-
-end; end
diff --git a/test/wsdl/datetime/DatetimeService.rb b/test/wsdl/datetime/DatetimeService.rb
index 800e06d66f..91c006005d 100644
--- a/test/wsdl/datetime/DatetimeService.rb
+++ b/test/wsdl/datetime/DatetimeService.rb
@@ -2,43 +2,37 @@
require 'datetimeServant.rb'
require 'soap/rpc/standaloneServer'
-require 'soap/mapping/registry'
class DatetimePortType
- MappingRegistry = ::SOAP::Mapping::Registry.new
+ MappingRegistry = SOAP::Mapping::Registry.new
+
+ # No mapping definition
Methods = [
- ["now", "now",
- [
- ["in", "now", [::SOAP::SOAPDateTime]],
- ["retval", "now", [::SOAP::SOAPDateTime]]
- ],
- "", "urn:jp.gr.jin.rrr.example.datetime", :rpc
- ]
+ ["now", "now", [
+ ["in", "now",
+ [SOAP::SOAPDateTime]],
+ ["retval", "now",
+ [SOAP::SOAPDateTime]]], "", "urn:jp.gr.jin.rrr.example.datetime"]
]
end
-class DatetimePortTypeApp < ::SOAP::RPC::StandaloneServer
+class DatetimePortTypeApp < SOAP::RPC::StandaloneServer
def initialize(*arg)
- super(*arg)
+ super
+
servant = DatetimePortType.new
- DatetimePortType::Methods.each do |name_as, name, param_def, soapaction, namespace, style|
- if style == :document
- @router.add_document_operation(servant, soapaction, name, param_def)
- else
- qname = XSD::QName.new(namespace, name_as)
- @router.add_rpc_operation(servant, qname, soapaction, name, param_def)
- end
+ DatetimePortType::Methods.each do |name_as, name, params, soapaction, namespace|
+ qname = XSD::QName.new(namespace, name_as)
+ @soaplet.app_scope_router.add_method(servant, qname, soapaction,
+ name, params)
end
+
self.mapping_registry = DatetimePortType::MappingRegistry
end
end
+# Change listen port.
if $0 == __FILE__
- # Change listen port.
- server = DatetimePortTypeApp.new('app', nil, '0.0.0.0', 10080)
- trap(:INT) do
- server.shutdown
- end
- server.start
+ DatetimePortTypeApp.new('app', nil, '0.0.0.0', 10080).start
end
diff --git a/test/wsdl/datetime/test_datetime.rb b/test/wsdl/datetime/test_datetime.rb
index 7652318205..0f531ff18c 100644
--- a/test/wsdl/datetime/test_datetime.rb
+++ b/test/wsdl/datetime/test_datetime.rb
@@ -24,14 +24,20 @@ class TestDatetime < Test::Unit::TestCase
Thread.current.abort_on_exception = true
@server.start
}
+ while @server.status != :Running
+ sleep 0.1
+ unless @t.alive?
+ @t.join
+ raise
+ end
+ end
end
def setup_client
wsdl = File.join(DIR, 'datetime.wsdl')
- @client = ::SOAP::WSDLDriverFactory.new(wsdl).create_rpc_driver
+ @client = ::SOAP::WSDLDriverFactory.new(wsdl).create_driver
@client.endpoint_url = "http://localhost:#{Port}/"
@client.generate_explicit_type = true
- @client.wiredump_dev = STDOUT if $DEBUG
end
def teardown
diff --git a/test/wsdl/document/document.wsdl b/test/wsdl/document/document.wsdl
deleted file mode 100644
index fbf03fae8b..0000000000
--- a/test/wsdl/document/document.wsdl
+++ /dev/null
@@ -1,74 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<definitions
- name="echo"
- targetNamespace="urn:docrpc"
- xmlns:tns="urn:docrpc"
- xmlns:xsd="http://www.w3.org/2001/XMLSchema"
- xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/"
- xmlns="http://schemas.xmlsoap.org/wsdl/">
- <types>
- <xsd:schema elementFormDefault="unqualified" targetNamespace="urn:docrpc">
- <xsd:complexType name="echo_struct">
- <xsd:sequence>
- <xsd:element minOccurs="0" maxOccurs="1" name="m_string" type="xsd:string" />
- <xsd:element minOccurs="0" maxOccurs="1" name="m_datetime" type="xsd:dateTime" />
- </xsd:sequence>
- <xsd:attribute name="m_attr" type="xsd:string" />
- </xsd:complexType>
-
- <xsd:element name="echoele">
- <xsd:complexType>
- <xsd:sequence>
- <xsd:element minOccurs="0" maxOccurs="1" name="struct1" type="tns:echo_struct" />
- <xsd:element minOccurs="0" maxOccurs="1" name="struct-2" type="tns:echo_struct" />
- </xsd:sequence>
- <xsd:attribute name="attr_string" type="xsd:string" />
- <xsd:attribute name="attr-int" type="xsd:int" />
- </xsd:complexType>
- </xsd:element>
- <xsd:element name="echo_response">
- <xsd:complexType>
- <xsd:sequence>
- <xsd:element minOccurs="0" maxOccurs="1" name="struct1" type="tns:echo_struct" />
- <xsd:element minOccurs="0" maxOccurs="1" name="struct-2" type="tns:echo_struct" />
- </xsd:sequence>
- <xsd:attribute name="attr_string" type="xsd:string" />
- <xsd:attribute name="attr-int" type="xsd:int" />
- </xsd:complexType>
- </xsd:element>
- </xsd:schema>
- </types>
-
- <message name="echo_in">
- <part name="parameters" element="tns:echoele" />
- </message>
- <message name="echo_out">
- <part name="parameters" element="tns:echo_response" />
- </message>
-
- <portType name="docrpc_porttype">
- <operation name="echo">
- <input message="tns:echo_in" />
- <output message="tns:echo_out" />
- </operation>
- </portType>
-
- <binding name="docrpc_binding" type="tns:docrpc_porttype">
- <soap:binding transport="http://schemas.xmlsoap.org/soap/http" style="document" />
- <operation name="echo">
- <soap:operation soapAction="urn:docrpc:echo" style="document" />
- <input>
- <soap:body use="literal" />
- </input>
- <output>
- <soap:body use="literal" />
- </output>
- </operation>
- </binding>
-
- <service name="docrpc_service">
- <port name="docprc_service_port" binding="tns:docrpc_binding">
- <soap:address location="http://localhost:17171/" />
- </port>
- </service>
-</definitions>
diff --git a/test/wsdl/document/echo.rb b/test/wsdl/document/echo.rb
deleted file mode 100644
index c6df75aca0..0000000000
--- a/test/wsdl/document/echo.rb
+++ /dev/null
@@ -1,92 +0,0 @@
-require 'xsd/qname'
-
-# {urn:docrpc}echoele
-class Echoele
- @@schema_type = "echoele"
- @@schema_ns = "urn:docrpc"
- @@schema_attribute = {XSD::QName.new(nil, "attr_string") => "SOAP::SOAPString", XSD::QName.new(nil, "attr-int") => "SOAP::SOAPInt"}
- @@schema_element = [["struct1", ["Echo_struct", XSD::QName.new(nil, "struct1")]], ["struct_2", ["Echo_struct", XSD::QName.new(nil, "struct-2")]]]
-
- attr_accessor :struct1
- attr_accessor :struct_2
-
- def xmlattr_attr_string
- (@__xmlattr ||= {})[XSD::QName.new(nil, "attr_string")]
- end
-
- def xmlattr_attr_string=(value)
- (@__xmlattr ||= {})[XSD::QName.new(nil, "attr_string")] = value
- end
-
- def xmlattr_attr_int
- (@__xmlattr ||= {})[XSD::QName.new(nil, "attr-int")]
- end
-
- def xmlattr_attr_int=(value)
- (@__xmlattr ||= {})[XSD::QName.new(nil, "attr-int")] = value
- end
-
- def initialize(struct1 = nil, struct_2 = nil)
- @struct1 = struct1
- @struct_2 = struct_2
- @__xmlattr = {}
- end
-end
-
-# {urn:docrpc}echo_response
-class Echo_response
- @@schema_type = "echo_response"
- @@schema_ns = "urn:docrpc"
- @@schema_attribute = {XSD::QName.new(nil, "attr_string") => "SOAP::SOAPString", XSD::QName.new(nil, "attr-int") => "SOAP::SOAPInt"}
- @@schema_element = [["struct1", ["Echo_struct", XSD::QName.new(nil, "struct1")]], ["struct_2", ["Echo_struct", XSD::QName.new(nil, "struct-2")]]]
-
- attr_accessor :struct1
- attr_accessor :struct_2
-
- def xmlattr_attr_string
- (@__xmlattr ||= {})[XSD::QName.new(nil, "attr_string")]
- end
-
- def xmlattr_attr_string=(value)
- (@__xmlattr ||= {})[XSD::QName.new(nil, "attr_string")] = value
- end
-
- def xmlattr_attr_int
- (@__xmlattr ||= {})[XSD::QName.new(nil, "attr-int")]
- end
-
- def xmlattr_attr_int=(value)
- (@__xmlattr ||= {})[XSD::QName.new(nil, "attr-int")] = value
- end
-
- def initialize(struct1 = nil, struct_2 = nil)
- @struct1 = struct1
- @struct_2 = struct_2
- @__xmlattr = {}
- end
-end
-
-# {urn:docrpc}echo_struct
-class Echo_struct
- @@schema_type = "echo_struct"
- @@schema_ns = "urn:docrpc"
- @@schema_attribute = {XSD::QName.new(nil, "m_attr") => "SOAP::SOAPString"}
- @@schema_element = [["m_string", ["SOAP::SOAPString", XSD::QName.new(nil, "m_string")]], ["m_datetime", ["SOAP::SOAPDateTime", XSD::QName.new(nil, "m_datetime")]]]
-
- attr_accessor :m_string
- attr_accessor :m_datetime
-
- def xmlattr_m_attr
- (@__xmlattr ||= {})[XSD::QName.new(nil, "m_attr")]
- end
-
- def xmlattr_m_attr=(value)
- (@__xmlattr ||= {})[XSD::QName.new(nil, "m_attr")] = value
- end
-
- def initialize(m_string = nil, m_datetime = nil)
- @m_string = m_string
- @m_datetime = m_datetime
- @__xmlattr = {}
- end
-end
diff --git a/test/wsdl/document/number.wsdl b/test/wsdl/document/number.wsdl
deleted file mode 100644
index cc3dd8e9f0..0000000000
--- a/test/wsdl/document/number.wsdl
+++ /dev/null
@@ -1,54 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<definitions
- name="foo"
- targetNamespace="urn:foo"
- xmlns:tns="urn:foo"
- xmlns:xsd="http://www.w3.org/2001/XMLSchema"
- xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/"
- xmlns="http://schemas.xmlsoap.org/wsdl/">
- <types>
- <xsd:schema elementFormDefault="unqualified" targetNamespace="urn:foo">
- <xsd:element name="get_foo">
- <xsd:complexType>
- <xsd:sequence>
- <xsd:element minOccurs="0" maxOccurs="1" name="number" type="xsd:string" />
- </xsd:sequence>
- </xsd:complexType>
- </xsd:element>
- </xsd:schema>
- </types>
-
- <message name="get_foo_in">
- <part name="parameters" element="tns:get_foo" />
- </message>
- <message name="get_foo_out">
- <part name="parameters" type="xsd:string" />
- </message>
-
- <portType name="foo_porttype">
- <operation name="get_foo">
- <input message="tns:get_foo_in" />
- <output message="tns:get_foo_out" />
- </operation>
- </portType>
-
- <binding name="foo_binding" type="tns:foo_porttype">
- <soap:binding transport="http://schemas.xmlsoap.org/soap/http"
- style="document" />
- <operation name="get_foo">
- <soap:operation soapAction="urn:foo:get_foo" style="document" />
- <input>
- <soap:body use="literal" />
- </input>
- <output>
- <soap:body use="literal" />
- </output>
- </operation>
- </binding>
-
- <service name="foo_service">
- <port name="foo_service_port" binding="tns:foo_binding">
- <soap:address location="http://localhost:17171/" />
- </port>
- </service>
-</definitions>
diff --git a/test/wsdl/document/ping_nosoapaction.wsdl b/test/wsdl/document/ping_nosoapaction.wsdl
deleted file mode 100644
index ab9529e456..0000000000
--- a/test/wsdl/document/ping_nosoapaction.wsdl
+++ /dev/null
@@ -1,66 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<definitions xmlns:tns="http://xmlsoap.org/Ping"
-xmlns="http://schemas.xmlsoap.org/wsdl/"
-xmlns:xsd="http://www.w3.org/2001/XMLSchema"
-xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/"
-targetNamespace="http://xmlsoap.org/Ping" name="Ping">
- <types>
- <schema targetNamespace="http://xmlsoap.org/Ping"
- xmlns="http://www.w3.org/2001/XMLSchema"
- elementFormDefault="qualified">
- <complexType name="ping">
- <sequence>
- <element name="scenario" type="xsd:string"
- nillable="true"/>
- <element name="origin" type="xsd:string"
- nillable="true"/>
- <element name="text" type="xsd:string"
- nillable="true"/>
- </sequence>
- </complexType>
- <complexType name="pingResponse">
- <sequence>
- <element name="scenario" type="xsd:string"
- nillable="true"/>
- <element name="origin" type="xsd:string"
- nillable="true"/>
- <element name="text" type="xsd:string"
- nillable="true"/>
- </sequence>
- </complexType>
- <element name="Ping" type="tns:ping"/>
- <element name="PingResponse" type="tns:pingResponse"/>
- </schema>
- </types>
- <message name="PingRequest">
- <part name="ping" element="tns:Ping"/>
- </message>
- <message name="PingResponse">
- <part name="pingResponse" element="tns:PingResponse"/>
- </message>
- <portType name="PingPort">
- <operation name="Ping">
- <input message="tns:PingRequest"/>
- <output message="tns:PingResponse"/>
- </operation>
- </portType>
- <binding name="PingBinding" type="tns:PingPort">
- <soap:binding style="document"
- transport="http://schemas.xmlsoap.org/soap/http"/>
- <operation name="Ping">
- <soap:operation/>
- <input>
- <soap:body use="literal"/>
- </input>
- <output>
- <soap:body use="literal"/>
- </output>
- </operation>
- </binding>
- <service name="PingService">
- <port name="PingPort" binding="tns:PingBinding">
- <soap:address
- location="http://127.0.0.1:8080/axis/services/PingPort"/>
- </port>
- </service>
-</definitions>
diff --git a/test/wsdl/document/test_nosoapaction.rb b/test/wsdl/document/test_nosoapaction.rb
deleted file mode 100644
index 77f642fe1b..0000000000
--- a/test/wsdl/document/test_nosoapaction.rb
+++ /dev/null
@@ -1,109 +0,0 @@
-require 'test/unit'
-require 'wsdl/parser'
-require 'wsdl/soap/wsdl2ruby'
-require 'soap/rpc/standaloneServer'
-require 'soap/wsdlDriver'
-require 'soap/rpc/driver'
-
-
-module WSDL; module Document
-
-
-class TestNoSOAPAction < Test::Unit::TestCase
- class Server < ::SOAP::RPC::StandaloneServer
- Namespace = 'http://xmlsoap.org/Ping'
-
- def on_init
- add_document_method(
- self,
- Namespace + '/ping',
- 'ping_with_soapaction',
- XSD::QName.new(Namespace, 'Ping'),
- XSD::QName.new(Namespace, 'PingResponse')
- )
-
- add_document_method(
- self,
- nil,
- 'ping',
- XSD::QName.new(Namespace, 'Ping'),
- XSD::QName.new(Namespace, 'PingResponse')
- )
-
- # When no SOAPAction given, latter method(ping) is called.
- end
-
- def ping(arg)
- arg.text = 'ping'
- arg
- end
-
- def ping_with_soapaction(arg)
- arg.text = 'ping_with_soapaction'
- arg
- end
- end
-
- DIR = File.dirname(File.expand_path(__FILE__))
-
- Port = 17171
-
- def setup
- setup_server
- @client = nil
- end
-
- def teardown
- teardown_server
- @client.reset_stream if @client
- end
-
- def setup_server
- @server = Server.new('Test', Server::Namespace, '0.0.0.0', Port)
- @server.level = Logger::Severity::ERROR
- @server_thread = start_server_thread(@server)
- end
-
- def teardown_server
- @server.shutdown
- @server_thread.kill
- @server_thread.join
- end
-
- def start_server_thread(server)
- t = Thread.new {
- Thread.current.abort_on_exception = true
- server.start
- }
- t
- end
-
- def test_with_soapaction
- wsdl = File.join(DIR, 'ping_nosoapaction.wsdl')
- @client = ::SOAP::WSDLDriverFactory.new(wsdl).create_rpc_driver
- @client.endpoint_url = "http://localhost:#{Port}/"
- @client.wiredump_dev = STDOUT if $DEBUG
- rv = @client.ping(:scenario => 'scenario', :origin => 'origin',
- :text => 'text')
- assert_equal('scenario', rv.scenario)
- assert_equal('origin', rv.origin)
- assert_equal('ping', rv.text)
- end
-
- def test_without_soapaction
- @client = ::SOAP::RPC::Driver.new("http://localhost:#{Port}/",
- Server::Namespace)
- @client.add_document_method('ping', Server::Namespace + '/ping',
- XSD::QName.new(Server::Namespace, 'Ping'),
- XSD::QName.new(Server::Namespace, 'PingResponse'))
- @client.wiredump_dev = STDOUT if $DEBUG
- rv = @client.ping(:scenario => 'scenario', :origin => 'origin',
- :text => 'text')
- assert_equal('scenario', rv.scenario)
- assert_equal('origin', rv.origin)
- assert_equal('ping_with_soapaction', rv.text)
- end
-end
-
-
-end; end
diff --git a/test/wsdl/document/test_number.rb b/test/wsdl/document/test_number.rb
deleted file mode 100644
index a640ef2a25..0000000000
--- a/test/wsdl/document/test_number.rb
+++ /dev/null
@@ -1,99 +0,0 @@
-require 'test/unit'
-require 'wsdl/parser'
-require 'wsdl/soap/wsdl2ruby'
-require 'soap/rpc/standaloneServer'
-require 'soap/wsdlDriver'
-
-
-module WSDL; module Document
-
-
-class TestNumber < Test::Unit::TestCase
- class Server < ::SOAP::RPC::StandaloneServer
- Namespace = 'urn:foo'
-
- def on_init
- add_document_method(
- self,
- Namespace + ':get_foo',
- 'get_foo',
- XSD::QName.new(Namespace, 'get_foo'),
- XSD::QName.new(Namespace, 'get_foo_response')
- )
- end
-
- def get_foo(arg)
- arg.number
- end
- end
-
- DIR = File.dirname(File.expand_path(__FILE__))
- Port = 17171
-
- def setup
- setup_server
- setup_classdef
- @client = nil
- end
-
- def teardown
- teardown_server
- File.unlink(pathname('foo.rb'))
- @client.reset_stream if @client
- end
-
- def setup_server
- @server = Server.new('Test', "urn:rpc", '0.0.0.0', Port)
- @server.level = Logger::Severity::ERROR
- @server_thread = start_server_thread(@server)
- end
-
- def setup_classdef
- gen = WSDL::SOAP::WSDL2Ruby.new
- gen.location = pathname("number.wsdl")
- gen.basedir = DIR
- gen.logger.level = Logger::FATAL
- gen.opt['classdef'] = nil
- gen.opt['force'] = true
- gen.run
- require pathname('foo')
- end
-
- def teardown_server
- @server.shutdown
- @server_thread.kill
- @server_thread.join
- end
-
- def start_server_thread(server)
- t = Thread.new {
- Thread.current.abort_on_exception = true
- server.start
- }
- t
- end
-
- def pathname(filename)
- File.join(DIR, filename)
- end
-
- def test_wsdl
- wsdl = File.join(DIR, 'number.wsdl')
- @client = ::SOAP::WSDLDriverFactory.new(wsdl).create_rpc_driver
- @client.endpoint_url = "http://localhost:#{Port}/"
- @client.wiredump_dev = STDOUT if $DEBUG
-
- # with the Struct defined in foo.rb, which is generated from WSDL
- assert_equal("12345", @client.get_foo(Get_foo.new("12345")))
-
- # with Hash
- assert_equal("12345", @client.get_foo({:number => "12345"}))
-
- # with Original struct
- get_foo_struct = Struct.new(:number)
- assert_equal("12345", @client.get_foo(get_foo_struct.new("12345")))
- end
-end
-
-
-end; end
diff --git a/test/wsdl/document/test_rpc.rb b/test/wsdl/document/test_rpc.rb
deleted file mode 100644
index 56cd0677ad..0000000000
--- a/test/wsdl/document/test_rpc.rb
+++ /dev/null
@@ -1,177 +0,0 @@
-require 'test/unit'
-require 'wsdl/parser'
-require 'wsdl/soap/wsdl2ruby'
-require 'soap/rpc/standaloneServer'
-require 'soap/wsdlDriver'
-
-
-module WSDL; module Document
-
-
-class TestRPC < Test::Unit::TestCase
- class Server < ::SOAP::RPC::StandaloneServer
- Namespace = 'urn:docrpc'
-
- def on_init
- add_document_method(
- self,
- Namespace + ':echo',
- 'echo',
- XSD::QName.new(Namespace, 'echo'),
- XSD::QName.new(Namespace, 'echo_response')
- )
- end
-
- def echo(arg)
- if arg.is_a?(Echoele)
- # swap args
- tmp = arg.struct1
- arg.struct1 = arg.struct_2
- arg.struct_2 = tmp
- arg
- else
- # swap args
- tmp = arg["struct1"]
- arg["struct1"] = arg["struct-2"]
- arg["struct-2"] = tmp
- arg
- end
- end
- end
-
- DIR = File.dirname(File.expand_path(__FILE__))
-
- Port = 17171
-
- def setup
- setup_server
- setup_classdef
- @client = nil
- end
-
- def teardown
- teardown_server
- #File.unlink(pathname('echo.rb'))
- @client.reset_stream if @client
- end
-
- def setup_server
- @server = Server.new('Test', "urn:rpc", '0.0.0.0', Port)
- @server.level = Logger::Severity::ERROR
- @server_thread = start_server_thread(@server)
- end
-
- def setup_classdef
- gen = WSDL::SOAP::WSDL2Ruby.new
- gen.location = pathname("document.wsdl")
- gen.basedir = DIR
- gen.logger.level = Logger::FATAL
- gen.opt['classdef'] = nil
- gen.opt['force'] = true
- gen.run
- require pathname('echo')
- end
-
- def teardown_server
- @server.shutdown
- @server_thread.kill
- @server_thread.join
- end
-
- def start_server_thread(server)
- t = Thread.new {
- Thread.current.abort_on_exception = true
- server.start
- }
- t
- end
-
- def pathname(filename)
- File.join(DIR, filename)
- end
-
- def test_wsdl
- wsdl = File.join(DIR, 'document.wsdl')
- @client = ::SOAP::WSDLDriverFactory.new(wsdl).create_rpc_driver
- @client.endpoint_url = "http://localhost:#{Port}/"
- @client.wiredump_dev = STDOUT if $DEBUG
-
- struct1 = Echo_struct.new("mystring1", now1 = Time.now)
- struct1.xmlattr_m_attr = 'myattr1'
- struct2 = Echo_struct.new("mystring2", now2 = Time.now)
- struct2.xmlattr_m_attr = 'myattr2'
- echo = Echoele.new(struct1, struct2)
- echo.xmlattr_attr_string = 'attr_string'
- echo.xmlattr_attr_int = 5
- ret = @client.echo(echo)
-
- # struct#m_datetime in a response is a DateTime even though
- # struct#m_datetime in a request is a Time.
- timeformat = "%Y-%m-%dT%H:%M:%S"
- assert_equal("mystring2", ret.struct1.m_string)
- assert_equal(now2.strftime(timeformat),
- date2time(ret.struct1.m_datetime).strftime(timeformat))
- assert_equal("mystring1", ret.struct_2.m_string)
- assert_equal(now1.strftime(timeformat),
- date2time(ret.struct_2.m_datetime).strftime(timeformat))
- assert_equal("attr_string", ret.xmlattr_attr_string)
- assert_equal(5, ret.xmlattr_attr_int)
- end
-
- def date2time(date)
- if date.respond_to?(:to_time)
- date.to_time
- else
- d = date.new_offset(0)
- d.instance_eval {
- Time.utc(year, mon, mday, hour, min, sec,
- (sec_fraction * 86400000000).to_i)
- }.getlocal
- end
- end
-
- include ::SOAP
- def test_naive
- @client = ::SOAP::RPC::Driver.new("http://localhost:#{Port}/")
- @client.add_document_method('echo', 'urn:docrpc:echo',
- XSD::QName.new('urn:docrpc', 'echoele'),
- XSD::QName.new('urn:docrpc', 'echo_response'))
- @client.wiredump_dev = STDOUT if $DEBUG
-
- echo = SOAPElement.new('foo')
- echo.extraattr['attr_string'] = 'attr_string'
- echo.extraattr['attr-int'] = 5
- echo.add(struct1 = SOAPElement.new('struct1'))
- struct1.add(SOAPElement.new('m_string', 'mystring1'))
- struct1.add(SOAPElement.new('m_datetime', '2005-03-17T19:47:31+01:00'))
- struct1.extraattr['m_attr'] = 'myattr1'
- echo.add(struct2 = SOAPElement.new('struct-2'))
- struct2.add(SOAPElement.new('m_string', 'mystring2'))
- struct2.add(SOAPElement.new('m_datetime', '2005-03-17T19:47:32+02:00'))
- struct2.extraattr['m_attr'] = 'myattr2'
- ret = @client.echo(echo)
- timeformat = "%Y-%m-%dT%H:%M:%S"
- assert_equal('mystring2', ret.struct1.m_string)
- assert_equal('2005-03-17T19:47:32',
- ret.struct1.m_datetime.strftime(timeformat))
- assert_equal("mystring1", ret.struct_2.m_string)
- assert_equal('2005-03-17T19:47:31',
- ret.struct_2.m_datetime.strftime(timeformat))
- assert_equal('attr_string', ret.xmlattr_attr_string)
- assert_equal(5, ret.xmlattr_attr_int)
-
- echo = {'struct1' => {'m_string' => 'mystring1', 'm_datetime' => '2005-03-17T19:47:31+01:00'},
- 'struct-2' => {'m_string' => 'mystring2', 'm_datetime' => '2005-03-17T19:47:32+02:00'}}
- ret = @client.echo(echo)
- timeformat = "%Y-%m-%dT%H:%M:%S"
- assert_equal('mystring2', ret.struct1.m_string)
- assert_equal('2005-03-17T19:47:32',
- ret.struct1.m_datetime.strftime(timeformat))
- assert_equal("mystring1", ret.struct_2.m_string)
- assert_equal('2005-03-17T19:47:31',
- ret.struct_2.m_datetime.strftime(timeformat))
- end
-end
-
-
-end; end
diff --git a/test/wsdl/map/map.wsdl b/test/wsdl/map/map.wsdl
index e418a4cbbd..7b1a140827 100644
--- a/test/wsdl/map/map.wsdl
+++ b/test/wsdl/map/map.wsdl
@@ -1,9 +1,9 @@
<?xml version="1.0"?>
<definitions
- name="map"
- targetNamespace="urn:map"
- xmlns:tns="urn:map"
- xmlns:txd="urn:map"
+ name="RAA"
+ targetNamespace="http://www.ruby-lang.org/xmlns/soap/interface/RAA/0.0.2/"
+ xmlns:tns="http://www.ruby-lang.org/xmlns/soap/interface/RAA/0.0.2/"
+ xmlns:txd="http://www.ruby-lang.org/xmlns/soap/interface/RAA/0.0.2/"
xmlns="http://schemas.xmlsoap.org/wsdl/"
xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
@@ -19,8 +19,8 @@
<element name="item" minOccurs="0" maxOccurs="unbounded">
<complexType>
<sequence>
- <element name="key" type="xsd:anyType" />
- <element name="value" type="xsd:anyType" />
+ <element name="key" type="anyType" />
+ <element name="value" type="anyType" />
</sequence>
</complexType>
</element>
@@ -34,58 +34,32 @@
<part name="return" type="apachesoap:Map"/>
</message>
- <message name="map2Request">
- <part name="arg" type="apachesoap:Map"/>
- </message>
- <message name="map2Response">
- <part name="return" type="apachesoap:Map"/>
- </message>
-
- <portType name="MapServicePortType">
+ <portType name="RAABaseServicePortType">
<operation name="map" parameterOrder="">
<input message="tns:mapRequest"/>
<output message="tns:mapResponse"/>
</operation>
-
- <operation name="map2" parameterOrder="">
- <input message="tns:map2Request"/>
- <output message="tns:map2Response"/>
- </operation>
</portType>
- <binding name="MapServicePortBinding" type="tns:MapServicePortType">
+ <binding name="RAABaseServicePortBinding" type="tns:RAABaseServicePortType">
<soap:binding style="rpc" transport="http://schemas.xmlsoap.org/soap/http"/>
<operation name="map">
<soap:operation soapAction=""/>
<input>
<soap:body use="encoded"
encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"
- namespace="urn:map"/>
- </input>
- <output>
- <soap:body use="encoded"
- encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"
- namespace="urn:map"/>
- </output>
- </operation>
-
- <operation name="map2">
- <soap:operation soapAction=""/>
- <input>
- <soap:body use="encoded"
- encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"
- namespace="urn:map"/>
+ namespace="http://www.ruby-lang.org/xmlns/soap/interface/RAA/0.0.2/"/>
</input>
<output>
<soap:body use="encoded"
encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"
- namespace="urn:map"/>
+ namespace="http://www.ruby-lang.org/xmlns/soap/interface/RAA/0.0.2/"/>
</output>
</operation>
</binding>
- <service name="MapService">
- <port name="MapServicePort" binding="tns:MapServicePortBinding">
+ <service name="RAAService">
+ <port name="RAABaseServicePort" binding="tns:RAABaseServicePortBinding">
<soap:address location="http://raa.ruby-lang.org/soap/1.0.2/"/>
</port>
</service>
diff --git a/test/wsdl/map/test_map.rb b/test/wsdl/map/test_map.rb
index 68f7d76e05..b0f2fb5a53 100644
--- a/test/wsdl/map/test_map.rb
+++ b/test/wsdl/map/test_map.rb
@@ -1,70 +1,15 @@
require 'test/unit'
-require 'soap/rpc/httpserver'
-require 'soap/wsdlDriver'
+require 'soap/processor'
+require 'soap/mapping'
+require 'soap/rpc/element'
+require 'wsdl/importer'
module WSDL
class TestMap < Test::Unit::TestCase
- Port = 17171
- DIR = File.dirname(File.expand_path(__FILE__))
-
- class Server < ::SOAP::RPC::HTTPServer
- def on_init
- add_method(self, 'map')
- add_method(self, 'map2', 'arg')
- end
-
- def map
- {1 => "a", 2 => "b"}
- end
-
- def map2(arg)
- arg
- end
- end
-
def setup
- setup_server
- setup_client
- end
-
- def setup_server
- @server = Server.new(
- :BindAddress => "0.0.0.0",
- :Port => Port,
- :AccessLog => [],
- :SOAPDefaultNamespace => "urn:map"
- )
- @server.level = Logger::Severity::ERROR
- @t = Thread.new {
- Thread.current.abort_on_exception = true
- @server.start
- }
- end
-
- def setup_client
- wsdl = File.join(DIR, 'map.wsdl')
- @client = ::SOAP::WSDLDriverFactory.new(wsdl).create_rpc_driver
- @client.endpoint_url = "http://localhost:#{Port}/"
- @client.generate_explicit_type = true
- @client.wiredump_dev = STDOUT if $DEBUG
- end
-
- def teardown
- teardown_server
- teardown_client
- end
-
- def teardown_server
- @server.shutdown
- @t.kill
- @t.join
- end
-
- def teardown_client
- @client.reset_stream
end
def test_by_wsdl
@@ -86,13 +31,6 @@ class TestMap < Test::Unit::TestCase
assert_equal(["b1"], map["b"]["b1"])
assert_equal(["b2"], map["b"]["b2"])
end
-
- def test_wsdldriver
- assert_equal({1 => "a", 2 => "b"}, @client.map)
- assert_equal({1 => 2}, @client.map2({1 => 2}))
- assert_equal({1 => {2 => 3}}, @client.map2({1 => {2 => 3}}))
- assert_equal({["a", 2] => {2 => 3}}, @client.map2({["a", 2] => {2 => 3}}))
- end
end
diff --git a/test/wsdl/marshal/person.wsdl b/test/wsdl/marshal/person.wsdl
deleted file mode 100644
index 6ea8a04825..0000000000
--- a/test/wsdl/marshal/person.wsdl
+++ /dev/null
@@ -1,21 +0,0 @@
-<?xml version="1.0"?>
-<definitions name="Person"
- targetNamespace="http://www.jin.gr.jp/~nahi/xmlns/sample/Person"
- xmlns:tns="http://www.jin.gr.jp/~nahi/xmlns/sample/Person"
- xmlns:xsd="http://www.w3.org/2001/XMLSchema"
- xmlns="http://schemas.xmlsoap.org/wsdl/">
- <types>
- <xsd:schema xmlns="http://www.w3.org/2001/XMLSchema"
- targetNamespace="http://www.jin.gr.jp/~nahi/xmlns/sample/Person">
- <complexType name="Person">
- <all>
- <element name="familyname" type="xsd:string"/>
- <element name="givenname" type="xsd:string"/>
- <element name="var1" type="xsd:int"/>
- <element name="var2" type="xsd:double"/>
- <element name="var3" type="xsd:string"/>
- </all>
- </complexType>
- </xsd:schema>
- </types>
-</definitions>
diff --git a/test/wsdl/marshal/person_org.rb b/test/wsdl/marshal/person_org.rb
deleted file mode 100644
index f8c0e0db76..0000000000
--- a/test/wsdl/marshal/person_org.rb
+++ /dev/null
@@ -1,22 +0,0 @@
-require 'xsd/qname'
-
-# {http://www.jin.gr.jp/~nahi/xmlns/sample/Person}Person
-class Person
- @@schema_type = "Person"
- @@schema_ns = "http://www.jin.gr.jp/~nahi/xmlns/sample/Person"
- @@schema_element = [["familyname", ["SOAP::SOAPString", XSD::QName.new(nil, "familyname")]], ["givenname", ["SOAP::SOAPString", XSD::QName.new(nil, "givenname")]], ["var1", ["SOAP::SOAPInt", XSD::QName.new(nil, "var1")]], ["var2", ["SOAP::SOAPDouble", XSD::QName.new(nil, "var2")]], ["var3", ["SOAP::SOAPString", XSD::QName.new(nil, "var3")]]]
-
- attr_accessor :familyname
- attr_accessor :givenname
- attr_accessor :var1
- attr_accessor :var2
- attr_accessor :var3
-
- def initialize(familyname = nil, givenname = nil, var1 = nil, var2 = nil, var3 = nil)
- @familyname = familyname
- @givenname = givenname
- @var1 = var1
- @var2 = var2
- @var3 = var3
- end
-end
diff --git a/test/wsdl/marshal/test_wsdlmarshal.rb b/test/wsdl/marshal/test_wsdlmarshal.rb
deleted file mode 100644
index cd2bdb198a..0000000000
--- a/test/wsdl/marshal/test_wsdlmarshal.rb
+++ /dev/null
@@ -1,80 +0,0 @@
-require 'test/unit'
-require 'wsdl/parser'
-require 'soap/mapping/wsdlencodedregistry'
-require 'soap/marshal'
-require 'wsdl/soap/wsdl2ruby'
-
-class WSDLMarshaller
- include SOAP
-
- def initialize(wsdlfile)
- wsdl = WSDL::Parser.new.parse(File.open(wsdlfile) { |f| f.read })
- types = wsdl.collect_complextypes
- @opt = {
- :decode_typemap => types,
- :generate_explicit_type => false,
- :pretty => true
- }
- @mapping_registry = Mapping::WSDLEncodedRegistry.new(types)
- end
-
- def dump(obj, io = nil)
- type = Mapping.class2element(obj.class)
- ele = Mapping.obj2soap(obj, @mapping_registry, type)
- ele.elename = ele.type
- Processor.marshal(SOAPEnvelope.new(nil, SOAPBody.new(ele)), @opt, io)
- end
-
- def load(io)