GtkTable to GtkGrid

GtkTable は GTK+3.2 で廃止になっていた。
当面は使えるみたい、だけどいつ無くなるか解らないって怖い。

seemex は GTK+3.0 の時に作ったし公開終了したからからセフセフ。
GtkVBox や GtkHBox という非推奨も使っていたりするがもうシラネ。

しかし GtkGrid を代替で使えということだけど全然引数が違っている。

まず GtkTable は左上が頂点で絶対値にて四角形を指定だった。
GtkGrid は幅と高さを指定、これでは全置換できないので全書き換えになる。

それより attach(…) の引数から Fill や padding を指定することができない。
それらしき関数も見当たらない、ヘルプもチト解りにくい。
どうやらそれらは GtkWidget 側のプロパティで指定するようだ。
こんなプロパティがあったことすら知らなかったが。

GtkWidget.html#GtkWidget–expand

リサイズ時に引き伸ばすなら expand Property を True にする。
padding Property は無いけど margin Property でイケそうだ。

Gtk+ はコンテナ側にこの指定があるのが少し不便だった。
どう考えても子ウイジェット側にあったほうがウイジェットの入れ替えやパレントの変更がスムース、実際 Windows の WPF はそうなっている。
やはり代えたいのだろうと憶測。
GtkBox なんかも今後そうなっていくかもしれない。
reparent した後に set_child_packing 必須って意味わかんなかったし。

さて、これが解ったところで。

いつものように画像検索から面白そうなことをやっていそうな人を探す。
日本人には最初から期待していない、おかげでリンク先が海外ばかりなこのブログ。
しかし今回はイマイチなものしか見当たらない、
教科書的というか、実用的な解説をしている人が見当たらないというか。

しかたがないので自力でやって確認してみる。
seemex の編集部分に使っていた GtkTable を抜いて GtkGrid に書き換えてみた。
非推奨関数とテキトーだったところは書き換え、外国人が解るようにヘタクソな英語で。

#!/usr/bin/env python
#-*- coding:utf-8 -*-

from gi.repository import Gtk

EDITOR_LABELS = ("Name", "Key", "URL", "Query")
EDITOR_CHECK = "Is POST"
ENTER_BUTTON = "_Edit"

class TableWin(Gtk.Window):
    def __init__(self):
        """
            GtkTable has been deprecated. Use GtkGrid instead.
            table.attach (  child,
                            left_attach,
                            right_attach,
                            top_attach,
                            bottom_attach,
                            xoptions=Gtk.AttachOptions.EXPAND,
                            yoptions=Gtk.AttachOptions.EXPAND,
                            xpadding=0,
                            ypadding=0 )
        """
        Gtk.Window.__init__(self)
        self.set_title("Table")
        self.connect("delete-event", Gtk.main_quit)
        # GtkTable
        table = Gtk.Table(5, 3)
        # Edit Widget
        self.edit_name = Gtk.Entry()
        table.attach(self.edit_name, 1, 2, 0, 1)
        self.edit_key = Gtk.Entry()
        table.attach(self.edit_key, 3, 4, 0, 1, Gtk.AttachOptions.FILL)
        self.edit_url = Gtk.Entry()
        table.attach(self.edit_url, 1, 5, 1, 2)
        self.edit_query = Gtk.Entry()
        table.attach(self.edit_query, 1, 4, 2, 3)
        self.check_post = Gtk.CheckButton.new_with_label(EDITOR_CHECK)
        table.attach(self.check_post, 4, 5, 2, 3, Gtk.AttachOptions.FILL)
        # Label
        labels = []
        for label in EDITOR_LABELS:
            labels.append(Gtk.Label(label))
        table.attach(labels[0], 0, 1, 0, 1, Gtk.AttachOptions.FILL)
        table.attach(labels[1], 2, 3, 0, 1, Gtk.AttachOptions.FILL, xpadding=10)
        table.attach(labels[2], 0, 1, 1, 2, Gtk.AttachOptions.FILL)
        table.attach(labels[3], 0, 1, 2, 3, Gtk.AttachOptions.FILL)
        # Button
        self.button = Gtk.Button.new_with_mnemonic(ENTER_BUTTON)
        table.attach(self.button, 4, 5, 0, 1, Gtk.AttachOptions.FILL)
        #
        self.add(table)
        self.show_all()

TableWin()
Gtk.main()
#!/usr/bin/env python
#-*- coding:utf-8 -*-

from gi.repository import Gtk

EDITOR_LABELS = ("Name", "Key", "URL", "Query")
EDITOR_CHECK = "Is POST"
ENTER_BUTTON = "_Edit"

class GridWin(Gtk.Window):
    def __init__(self):
        """
            GtkGrid
            grid.attach(child, left, top, width, height)
            or
            grid.attach_next_to(child, sibling, GtkPositionType, width, height)
            
            GtkAttachOptions to GtkWidget 'expand' Property
            Padding to GtkWidget 'margin' Property
        """
        Gtk.Window.__init__(self)
        self.set_title("Grid")
        self.connect("delete-event", Gtk.main_quit)
        # GtkGrid
        grid = Gtk.Grid.new()
        # Edit Widget
        self.edit_name = Gtk.Entry()
        # Substitute Gtk.AttachOptions.EXPAND
        self.edit_name.props.expand = True
        grid.attach(self.edit_name, 1, 0, 1, 1)
        self.edit_key = Gtk.Entry()
        grid.attach(self.edit_key, 3, 0, 1, 1)
        self.edit_url = Gtk.Entry()
        self.edit_url.props.expand = True
        grid.attach(self.edit_url, 1, 1, 5, 1)
        self.edit_query = Gtk.Entry()
        self.edit_query.props.expand = True
        grid.attach(self.edit_query, 1, 2, 3, 1)
        self.check_post = Gtk.CheckButton.new_with_label(EDITOR_CHECK)
        grid.attach(self.check_post, 4, 2, 1, 1)
        # Label
        labels = []
        for label in EDITOR_LABELS:
            labels.append(Gtk.Label(label))
        grid.attach(labels[0], 0, 0, 1, 1)
        grid.attach(labels[1], 2, 0, 1, 1)
        grid.attach(labels[2], 0, 1, 1, 1)
        grid.attach(labels[3], 0, 2, 1, 1)
        # Substitute xpadding
        labels[1].props.margin_left = 10
        labels[1].props.margin_right = 10
        # Button
        self.button = Gtk.Button.new_with_mnemonic(ENTER_BUTTON)
        grid.attach(self.button, 4, 0, 1, 1)
        self.add(grid)
        self.show_all()

GridWin()
Gtk.main()

gtkgrid

よしリサイズでの引き伸ばされかたも完全に同じだ。
GtkGrid はデフォルトが Fill なので引き伸ばしたい Widget の expand を True にすればいいということなのね。

つか、やっぱりコードは似ているようで全然違うわw
子ウイジェット側で引き延ばし指定を行うほうがやはり理解しやすいなと思う。
たとえ記述量が多くなっても理解しやすいほうがいいなと。

GtkButtonBox

GtkButtonBox って何に使うか解らなかった。
検索したら面白そうなのを見つけた。

PHP-GTK по-русски: Группирование кнопок

ドメインは jp だけど思いっきりロシア語なのは何故だろう。
モチロン読めないけど PHP-GTK コードはアルファベットなので解る。
PHP-GTK って使っている人がいるんだな…

Standard Enumerations

GTK_BUTTONBOX_DEFAULT_STYLE って定義は無いんだけど。
デフォルトを調べたら EDGE だった、EDGE とたしかに見た目は同じだね。

edge

つかこのコードだと hbox_main っていらなくね?
それと GtkHButtonBox も GtkHBox 同様に非推奨なのね。
Gtk.ButtonBox.new(Gtk.Orientation.HORIZONTAL) でいいみたい。

その辺りを考慮して PyGI で書き換えるとこんな感じか。

#!/usr/bin/env python
#-*- coding:utf-8 -*-

from gi.repository import Gtk

window = Gtk.Window()
window.set_position(Gtk.WindowPosition.CENTER)
window.set_size_request(450, -1)
window.connect('destroy', Gtk.main_quit)
 
vbox = Gtk.Box.new(Gtk.Orientation.VERTICAL, 0)
 
dic = {
    'Spread': Gtk.ButtonBoxStyle.SPREAD,
    'Edge(Default)': Gtk.ButtonBoxStyle.EDGE,
    'Start': Gtk.ButtonBoxStyle.START,
    'End': Gtk.ButtonBoxStyle.END,
    'Center': Gtk.ButtonBoxStyle.CENTER }
 
for key, value in dic.iteritems():
    box = Gtk.ButtonBox.new(Gtk.Orientation.HORIZONTAL)
    box.set_layout(value)
    box.add(Gtk.Button.new_from_stock(Gtk.STOCK_YES))
    box.add(Gtk.Button.new_from_stock(Gtk.STOCK_CANCEL))
    box.add(Gtk.Button.new_from_stock(Gtk.STOCK_NO))
    frame = Gtk.Frame.new(key)
    frame.set_shadow_type(Gtk.ShadowType.IN)
    frame.add(box)
    vbox.pack_start(frame, False, False, 5)
 
window.add(vbox)
window.show_all()
Gtk.main()

gtk_button_box

右寄せとか完全等間隔とか色々指定できるんだね。
なるほど、使い道は微妙だけどこんなコンテナもあるということで。

DynamicXamlReader

もう一つ IronPython ネタ。

ユーザーインターフェース付きのスクリプトをXAML×IronPythonを使って作る(2): 品質向上と効率改善の組み木パズル

え。。。。。

dynamic.xaml

<Window
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="DynamicXamlReader" Height="200" Width="300" Loaded="on_loaded">
    <DockPanel>
		<Menu DockPanel.Dock="Top">
		    <MenuItem Header="_File">
		        <MenuItem Header="_Open" Click="on_open" InputGestureText="Ctrl+O" />
		        <Separator />
		        <MenuItem Header="_Close" Click="on_close" InputGestureText="Ctrl+Q" />
		    </MenuItem>
		</Menu>
		<TextBox Name="textbox" />
	</DockPanel>
</Window>

dynamic.py

# -*- coding: UTF-8 -*-

import wpf

from System import *
from System.IO import *
from System.Windows import *
from Microsoft.Win32 import OpenFileDialog

class DynamicXamlReaderTest(Window):
    def __init__(self):
        # DynamicXamlReader Set
        wpf.LoadComponent(self, "dynamic.xaml")

    def on_loaded(self, sender, e):
        self.textbox.Focus()

    def on_open(self, sender, e):
        dlg = OpenFileDialog()
        if dlg.ShowDialog():
            # C# using(var sw = new StreamReader(dlg.FileName)){}
            with StreamReader(dlg.FileName) as sw:
                self.textbox.Text = sw.ReadToEnd()

    def on_close(self, sender, e):
        self.Close()

if __name__ == "__main__":
    Application().Run(DynamicXamlReaderTest())

dynamic

動的に XAML を合体できるんだ、知らなかったよ。
exe を作って一つにまとめるわけじゃないけどコレは便利。

と思ったけど…
LoadComponent は第一引数のオブジェクトと XAML を合体するので私の大好きなメニューだけ XAML みたいな方法が使えないよ。
ヒアドキュメントにもできないみたいだし、少し残念。
大半の人はそんなこと気にしないんだろうけど。

Microsoft.Scripting.Runtime.DynamicXamlReader
というのを使っているらしい。
IronPython ディレクトリにある Microsoft.Dynamic.dll リファレンスにあるようだ。

C# からも使えるかもと思って少し四苦八苦してみたけど無駄だった。
そりゃどう考えてもコンパイルで弾かれるわ。
「textbox は定義されていません」みたいな感じで。
動的割り当てなスクリプト言語だから可能な技だろうね。

MSBuild による WPF プログラムのビルド – WPF 入門
C# は素直にコレやるか VisualStudio を使えだろうね。

ApplicationCommands for IronPython

久々に .NET ネタ。
なかなか面白いことをしている人を見つけたので。
C# + WPF + XAML コマンドのバインドとメニューバー – Symfoware
static の意味をイマイチ解っていないようだけど…
いやコレでも動くんだが。

とにかくおかげで解ったこと。
下記を利用すればあらかじめ用意されたメニューを勝手に入れてくれるようだ。
ApplicationCommands クラス (System.Windows.Input)

Windows にも全自動で国際化メニューにしてくれる便利なものがあったのね。
WPF のみみたいだけど。
GTK+ みたくリソースであるほうが理解しやすいんだけど。

で、リンク先は多々無駄があるのでもう少し単純なサンプルを書いてみる。

ただ IronPython で、コンパイル面倒クセェ!
一応 C# 屋が見てもなんとなく解るように。

# -*- coding: UTF-8 -*-

"""
    WPF Simple TextEditor
    Read and Write encoding is UTF-8 Non BOM Text
"""

import clr

clr.AddReferenceByPartialName("PresentationCore")
clr.AddReferenceByPartialName("PresentationFramework")
clr.AddReferenceByPartialName("WindowsBase")

from System import *
from System.IO import *
from System.Windows import *
from System.Windows.Controls import *
from System.Windows.Input import *

from System.Windows.Markup import XamlReader
from Microsoft.Win32 import OpenFileDialog, SaveFileDialog

menu_str = """<Menu DockPanel.Dock="Top"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <MenuItem Header="_File">
        <MenuItem Command="New" />
        <Separator />
        <MenuItem Command="Open" />
        <MenuItem Command="Save" />
        <MenuItem Command="SaveAs" />
        <Separator />
        <MenuItem Command="Close" />
    </MenuItem>
    <MenuItem Header="_Edit">
        <MenuItem Command="Undo" />
        <MenuItem Command="Redo" />
        <Separator />
        <MenuItem Command="Cut" />
        <MenuItem Command="Copy" />
        <MenuItem Command="Paste" />
        <Separator />
        <MenuItem Command="SelectAll" />
    </MenuItem>
</Menu>"""

class TextEditor(Window):
    """
        Auto Internationalization menu Sample
        no mnemonic...
    """
    def __init__(self):
        # Menu
        menu = XamlReader.Parse(menu_str)
        # MenuItem Binding
        cb = CommandBinding(ApplicationCommands.New, self.on_new)
        self.CommandBindings.Add(cb)
        cb = CommandBinding(ApplicationCommands.Open, self.on_open)
        self.CommandBindings.Add(cb)
        cb = CommandBinding(ApplicationCommands.Save, self.on_save, self.on_can_execute)
        self.CommandBindings.Add(cb)
        cb = CommandBinding(ApplicationCommands.SaveAs, self.on_save_as, self.on_can_execute)
        self.CommandBindings.Add(cb)
        cb = CommandBinding(ApplicationCommands.Close, self.on_close)
        self.CommandBindings.Add(cb)
        # TextBox
        self.textbox = TextBox()
        self.textbox.TextWrapping = TextWrapping.NoWrap
        self.textbox.AcceptsReturn = True
        self.textbox.AcceptsTab = True
        self.textbox.VerticalScrollBarVisibility = ScrollBarVisibility.Auto
        self.textbox.HorizontalScrollBarVisibility = ScrollBarVisibility.Auto
        # Add
        docpanel = DockPanel()
        docpanel.Children.Add(menu)
        docpanel.Children.Add(self.textbox)
        self.Content = docpanel
        self.Width = 300
        self.Height = 300
        self.textbox.Focus()

    def on_new(self, sender, e):
        self.textbox.Text = ""
        self.Title = ""

    def on_open(self, sender, e):
        dlg = OpenFileDialog()
        if dlg.ShowDialog():
            sw = StreamReader(dlg.FileName) 
            try:
                self.textbox.Text = sw.ReadToEnd()
                self.Title = dlg.FileName
            except Exception, ex:
                MessageBox.Show(ex.Message)
            finally:
                sw.Close()

    def on_save(self, sender, e):
        if self.Title == "":
            self.on_save_as(sender, e)
        else:
            self.save_file(self.Title)

    def on_save_as(self, sender, e):
        dlg = SaveFileDialog()
        if dlg.ShowDialog():
            self.save_file(dlg.FileName)

    def on_close(self, sender, e):
        self.Close()

    def on_can_execute(self, sender, e):
        e.CanExecute = self.textbox.Text != ""

    def save_file(self, filename):
        sw = StreamWriter(filename) 
        try:
            sw.Write(self.textbox.Text)
            self.Title = filename
        except Exception, ex:
            MessageBox.Show(ex.Message)
        finally:
            sw.Close()

if __name__ == "__main__":
    w = TextEditor()
    Application().Run(w)

menu_win

何故メニューだけ XAML なんだ?と言わない。
Python with GTK+ ではコレが普通。
メニューとツールバー – L’Isola di Niente

とりあえずこのバインディングでやったことの解説を少し。

XAML は見ての通り ApplicationCommands を指定するだけ。
そしてコードで CommandBinding オブジェクトを作る。

CommandBinding クラス (System.Windows.Input)

第一引数に利用する ApplicationCommands
第二引数に結びつけたいイベントハンドラ名
第三引数は必要なら任意でメニューの有効無効を決めるハンドラ名

ハンドラってつまり既に有るオブジェクトですので別途で作成する必要は無い。
それを Window に CommandBindings.Add() すればいい。

ついでに TextBox のバッファが空だと保存できないように。
CommandBinding 第三引数でアッサリと実現できるんですね。

Ctrl+C でコピー等は TextBox が提供している機能なので別にメニューに入れなくても使えるんですけどね。

後今頃知ったけど StreamReader.ReadToEnd ってバイナリを読み込めるのね。
せっかく例外処理を入れたけど意味なかった。

var と new と中括弧とセミコロン追加で C# コードにもなるはずw

で、自動的に日本語メニューにはなったけどニーモニックが無いんですけど。
Alt+F, Alt+S みたいなことができないって少し困る。

以下駄文。

久々に IronPython を使ったけど面白い、DLR の初期化さえ早くなれば…
Microsoft は .NET がネイティブ、かつ local が UTF-8 の新規 OS を出してくれ。
ネイティブなら DLR 初期化なんて一瞬のはず、内部は UTF-16 ではなく UCS-4 なら更に嬉しい。
今更 Windows の local 変更なんて無理なのは解っているから新規で。

Cairo for Python

Cairo Tutorial for Python Programmers

のサンプルコードで値が異様に小さい理由が解らなかった。
単純にコピペすると 1px にしか描写しない、なので DrawingArea サイズ得て計算する方法を覚書ページに書いた。

なんてことない、cairo_scale() で cairo のほうをサイズ指定すればよかったのね。

#!/usr/bin/env python
#-*- coding:utf-8 -*-

from gi.repository import Gtk
import cairo

class DrawTest(Gtk.Window):
    def __init__(self):
        Gtk.Window.__init__(self)
        da = Gtk.DrawingArea()
        da.connect("draw", self.on_draw)
        #da.set_double_buffered(False)
        self.add(da)
        self.connect("delete-event", Gtk.main_quit)
        self.resize(300, 300)
        self.show_all()

    def on_draw(self, widget, cr):
        # Get DrawingArea Size
        width = widget.get_allocated_width()
        height = widget.get_allocated_height()
        # cairo Change Size
        cr.scale(width, height)
        #
        cr.set_source_rgb(0, 0, 0)
        cr.move_to(0, 0)
        cr.line_to(1, 1)
        cr.move_to(1, 0)
        cr.line_to(0, 1)
        cr.set_line_width(0.2)
        cr.stroke()

        cr.rectangle(0, 0, 0.5, 0.5)
        cr.set_source_rgba(1, 0, 0, 0.80)
        cr.fill()

        cr.rectangle(0, 0.5, 0.5, 0.5)
        cr.set_source_rgba(0, 1, 0, 0.60)
        cr.fill()

        cr.rectangle(0.5, 0, 0.5, 0.5)
        cr.set_source_rgba(0, 0, 1, 0.40)
        cr.fill()

if __name__ == '__main__':
    w = DrawTest()
    Gtk.main()

cairo_python

cr.scale(width, height)
だけでサンプルコードがそのまんまコピペできた。
とにかく覚書ページの書き換えか、あーあ。

Boxes 仮想マシンの Lubuntu 上でも問題なく動いた。
しかしこのサンプルは一旦領域を塗りつぶす処理が入っていないのでダブルバッファを無効ににしてリサイズすると悲惨だ。

clutter – A toolkit for creating fast, portable, compelling dynamic UIs

このサンプルを見て気がついた、Clutter での 2D 表示も cairo なのね。
しかし Ubuntu には Clutter がデフォルトで入らないので困る。
海外で GTK+ 等のコードを検索すると皆 Ubuntu ばかり使っていて正直驚く。

ということで PyGI で DrawingArea に表示に作り替えてみた。

#!/usr/bin/env python
#-*- coding:utf-8 -*-

from gi.repository import Gtk, GLib
import cairo, math

class DrawTest(Gtk.Window):
    def __init__(self):
        Gtk.Window.__init__(self)
        da = Gtk.DrawingArea()
        da.connect("draw", self.on_draw)
        self.add(da)
        self.connect("delete-event", Gtk.main_quit)
        self.resize(150, 300)
        self.show_all()
        GLib.timeout_add(1000, self.on_timer, da)

    def on_timer(self, da):
        da.queue_draw()
        return True

    def on_draw(self, widget, cr):
        # get the current time and compute the angles
        now = GLib.DateTime.new_now_local()
        seconds = GLib.DateTime.get_second(now) * GLib.PI / 30
        minutes = GLib.DateTime.get_minute(now) * GLib.PI / 30
        hours = GLib.DateTime.get_hour(now) * GLib.PI / 6
        # scale the modelview to the size of the surface
        width = widget.get_allocated_width()
        height = widget.get_allocated_height()
        cr.scale(width, height)
        cr.set_line_cap(cairo.LINE_CAP_ROUND)
        cr.set_line_width(0.1)
        # the black rail that holds the seconds indicator
        cr.set_source_rgb(0, 0, 0)
        cr.translate(0.5, 0.5)
        cr.arc(0, 0, 0.4, 0, GLib.PI * 2)
        cr.stroke()
        # the seconds hand
        cr.set_source_rgb(1, 1, 1)
        cr.move_to(0, 0)
        cr.arc(math.sin(seconds) * 0.4, - math.cos(seconds) * 0.4, 0.05, 0, GLib.PI * 2)
        cr.stroke()
        # the minutes hand
        cr.set_source_rgb(1, 1, 0)
        cr.move_to(0, 0)
        cr.line_to(math.sin(minutes) * 0.4, - math.cos(minutes) * 0.4)
        cr.stroke()
        # the hours hand
        cr.set_source_rgb(1, 0, 0)
        cr.move_to(0, 0)
        cr.line_to(math.sin(hours) * 0.2, - math.cos(hours) * 0.2)
        cr.stroke()

if __name__ == '__main__':
    w = DrawTest()
    Gtk.main()

cairo_timer

GLib に sinf 関数くらい有りそうなのに見つからなかったので math を利用。
GLib.Math.sinf ? glib-2.0
Vala なら有るんだが、C 言語に sinf 関数があるから不要ということか。
それから色はテキトーです。

うん、基本的に cairo で使う数値は 0.0〜1.0 でいいみたい。
スマートフォンのような拡縮を考えるとそういう方向になるわけで。
作り手としては画面サイズ計算をする必要が無いというのも嬉しいですね。