| 1 |
|
| 2 |
|
| 3 |
module Gtk |
| 4 |
class ContextMenu |
| 5 |
extend Gem::Deprecate |
| 6 |
def initialize(*context) |
| 7 |
reset(context) end |
| 8 |
|
| 9 |
def reset(context) |
| 10 |
@contextmenu = context |
| 11 |
end |
| 12 |
|
| 13 |
def register(label, condition=:itself, &callback) |
| 14 |
@contextmenu = @contextmenu.push([label, condition.to_proc, callback]) |
| 15 |
end |
| 16 |
alias :registmenu :register |
| 17 |
deprecate :registmenu, "register", 2018, 04 |
| 18 |
|
| 19 |
def line(&proc) |
| 20 |
register(nil, proc || :itself) |
| 21 |
end |
| 22 |
alias :registline :line |
| 23 |
deprecate :registline, "line", 2018, 04 |
| 24 |
|
| 25 |
|
| 26 |
身を自動的に破棄する Gtk::Menu を作成して返す |
| 27 |
def temporary_menu |
| 28 |
menu = Gtk::Menu.new |
| 29 |
menu.ssc(:selection_done) do |
| 30 |
menu.destroy |
| 31 |
false end |
| 32 |
menu.ssc(:cancel) do |
| 33 |
menu.destroy |
| 34 |
false end |
| 35 |
menu end |
| 36 |
|
| 37 |
def build!(widget, optional, menu = temporary_menu) |
| 38 |
@contextmenu.each do |param| |
| 39 |
label, cond, proc, icon = param |
| 40 |
if cond.call(*[optional, widget][0, (cond.arity < 0 ? 1 : cond.arity)]) |
| 41 |
if label |
| 42 |
item = gen_menu_item(label_text(label, optional, widget), icon, optional, widget) |
| 43 |
if proc |
| 44 |
item.ssc(:activate) do |w| |
| 45 |
proc.call(*[optional, widget][0...proc.arity]) |
| 46 |
false |
| 47 |
end |
| 48 |
end |
| 49 |
menu.append(item) |
| 50 |
else |
| 51 |
menu.append(Gtk::MenuItem.new) |
| 52 |
end |
| 53 |
end |
| 54 |
end |
| 55 |
menu |
| 56 |
end |
| 57 |
|
| 58 |
def popup(widget, optional) |
| 59 |
menu = build!(widget, optional) |
| 60 |
|
| 61 |
if not menu.children.empty? |
| 62 |
menu.show_all.popup(nil, nil, 0, 0) |
| 63 |
end |
| 64 |
end |
| 65 |
|
| 66 |
private |
| 67 |
|
| 68 |
def label_text(label, optional, widget) |
| 69 |
if defined?(label.call) |
| 70 |
label.call(*[optional, widget][0, (label.arity == -1 ? 1 : label.arity)]) |
| 71 |
else |
| 72 |
label |
| 73 |
end |
| 74 |
end |
| 75 |
|
| 76 |
def gen_menu_item(label_text, icon, optional, widget) |
| 77 |
if icon.is_a?(Proc) |
| 78 |
icon = icon.call(*[optional, widget][0, (icon.arity == -1 ? 1 : icon.arity)]) |
| 79 |
end |
| 80 |
if icon |
| 81 |
Gtk::ImageMenuItem.new(label: label_text, use_underline: false).tap do |item| |
| 82 |
item.set_image(Gtk::WebIcon.new(icon, 16, 16)) |
| 83 |
item.always_show_image = true |
| 84 |
end |
| 85 |
else |
| 86 |
Gtk::MenuItem.new(label: label_text, use_underline: false) |
| 87 |
end |
| 88 |
end |
| 89 |
end |
| 90 |
end |