repo stringlengths 5 92 | file_url stringlengths 80 287 | file_path stringlengths 5 197 | content stringlengths 0 32.8k | language stringclasses 1 value | license stringclasses 7 values | commit_sha stringlengths 40 40 | retrieved_at stringdate 2026-01-04 15:37:27 2026-01-04 17:58:21 | truncated bool 2 classes |
|---|---|---|---|---|---|---|---|---|
AndyObtiva/glimmer-dsl-swt | https://github.com/AndyObtiva/glimmer-dsl-swt/blob/449cf07ada1ec965ae2ac91715ccdf22488df4ca/lib/glimmer/dsl/swt/timer_exec_expression.rb | lib/glimmer/dsl/swt/timer_exec_expression.rb | # Copyright (c) 2007-2025 Andy Maleh
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
require 'glimmer/dsl/static_expression'
require 'glimmer/dsl/swt/exec_expression'
module Glimmer
module DSL
module SWT
# Asynchronously executes code block against the SWT Event Loop
# after a certain time elapsed
class TimerExecExpression < StaticExpression
include ExecExpression
end
end
end
end
| ruby | MIT | 449cf07ada1ec965ae2ac91715ccdf22488df4ca | 2026-01-04T17:52:38.125591Z | false |
AndyObtiva/glimmer-dsl-swt | https://github.com/AndyObtiva/glimmer-dsl-swt/blob/449cf07ada1ec965ae2ac91715ccdf22488df4ca/lib/glimmer/dsl/swt/tab_item_expression.rb | lib/glimmer/dsl/swt/tab_item_expression.rb | # Copyright (c) 2007-2025 Andy Maleh
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
require 'glimmer'
require 'glimmer/dsl/static_expression'
require 'glimmer/dsl/parent_expression'
require 'glimmer/swt/widget_proxy'
require 'glimmer/swt/tab_item_proxy'
module Glimmer
module DSL
module SWT
class TabItemExpression < StaticExpression
include ParentExpression
include_package 'org.eclipse.swt.widgets'
def can_interpret?(parent, keyword, *args, &block)
initial_condition = (keyword == 'tab_item') and parent.respond_to?(:swt_widget)
if initial_condition
if parent.swt_widget.is_a?(TabFolder)
return true
else
Glimmer::Config.logger.error {"tab_item widget may only be used directly under a tab_folder widget!"}
end
end
false
end
def interpret(parent, keyword, *args, &block)
Glimmer::SWT::TabItemProxy.new(parent, args)
end
end
end
end
end
| ruby | MIT | 449cf07ada1ec965ae2ac91715ccdf22488df4ca | 2026-01-04T17:52:38.125591Z | false |
AndyObtiva/glimmer-dsl-swt | https://github.com/AndyObtiva/glimmer-dsl-swt/blob/449cf07ada1ec965ae2ac91715ccdf22488df4ca/lib/glimmer/dsl/swt/sync_call_expression.rb | lib/glimmer/dsl/swt/sync_call_expression.rb | # Copyright (c) 2007-2025 Andy Maleh
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
require 'glimmer/dsl/static_expression'
require 'glimmer/dsl/swt/exec_expression'
module Glimmer
module DSL
module SWT
# Synchronously executes code block against the SWT Event Loop
# to manipulate SWT UI objects on the UI thread safely with
# immediate priority when needed.
#
# Returns the value produced by evaluating the expression.
class SyncCallExpression < StaticExpression
include ExecExpression
end
end
end
end
| ruby | MIT | 449cf07ada1ec965ae2ac91715ccdf22488df4ca | 2026-01-04T17:52:38.125591Z | false |
AndyObtiva/glimmer-dsl-swt | https://github.com/AndyObtiva/glimmer-dsl-swt/blob/449cf07ada1ec965ae2ac91715ccdf22488df4ca/lib/glimmer/dsl/swt/menu_bar_expression.rb | lib/glimmer/dsl/swt/menu_bar_expression.rb | # Copyright (c) 2007-2025 Andy Maleh
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
require 'glimmer'
require 'glimmer/dsl/static_expression'
require 'glimmer/dsl/parent_expression'
require 'glimmer/swt/menu_proxy'
module Glimmer
module DSL
module SWT
class MenuBarExpression < StaticExpression
include ParentExpression
include_package 'org.eclipse.swt.widgets'
def can_interpret?(parent, keyword, *args, &block)
initial_condition = (keyword == 'menu_bar')
if initial_condition
if parent.swt_widget.is_a?(Shell)
return true
else
raise Glimmer::Error, "menu_bar may only be nested under a shell!"
end
end
false
end
def interpret(parent, keyword, *args, &block)
args = args.unshift(:bar)
Glimmer::SWT::MenuProxy.new(parent, args)
end
end
end
end
end
| ruby | MIT | 449cf07ada1ec965ae2ac91715ccdf22488df4ca | 2026-01-04T17:52:38.125591Z | false |
AndyObtiva/glimmer-dsl-swt | https://github.com/AndyObtiva/glimmer-dsl-swt/blob/449cf07ada1ec965ae2ac91715ccdf22488df4ca/lib/glimmer/dsl/swt/tree_items_data_binding_expression.rb | lib/glimmer/dsl/swt/tree_items_data_binding_expression.rb | # Copyright (c) 2007-2025 Andy Maleh
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
require 'glimmer/dsl/expression'
require 'glimmer/data_binding/model_binding'
require 'glimmer/data_binding/tree_items_binding'
module Glimmer
module DSL
module SWT
class TreeItemsDataBindingExpression < Expression
include_package 'org.eclipse.swt.widgets'
def can_interpret?(parent, keyword, *args, &block)
keyword == 'items' and
block.nil? and
parent.respond_to?(:swt_widget) and
parent.swt_widget.is_a?(Tree) and
args.size.between?(1, 2)
# TODO delete these checks if they are too granular
# return false unless initial_condition
# raise Glimmer::Error, 'Tree items args must be 1 or 2' unless args.size.between?(1, 2)
# raise Glimmer::Error, 'Tree items first arg must be a bind expression' unless args[0].is_a?(DataBinding::ModelBinding)
# raise Glimmer::Error, 'Tree items data-binding initial value must not be an array yet a single item representing tree root' unless !args[0].evaluate_property.is_a?(Array)
# raise Glimmer::Error, 'Tree items second arg must be an array' unless args[1].is_a?(Array)
# raise Glimmer::Error, 'Tree items second arg must not be empty' unless !args[1].empty?
# raise Glimmer::Error, 'Tree items second arg array elements must be of type hash' unless args[1].first.is_a?(Hash)
# true
end
def interpret(parent, keyword, *args, &block)
model_binding = args[0]
tree_properties = args[1]
DataBinding::TreeItemsBinding.new(parent, model_binding, tree_properties)
end
end
end
end
end
| ruby | MIT | 449cf07ada1ec965ae2ac91715ccdf22488df4ca | 2026-01-04T17:52:38.125591Z | false |
AndyObtiva/glimmer-dsl-swt | https://github.com/AndyObtiva/glimmer-dsl-swt/blob/449cf07ada1ec965ae2ac91715ccdf22488df4ca/lib/glimmer/dsl/swt/rgb_expression.rb | lib/glimmer/dsl/swt/rgb_expression.rb | # Copyright (c) 2007-2025 Andy Maleh
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
require 'glimmer/dsl/swt/color_expression'
require 'glimmer/swt/color_proxy'
require 'glimmer/swt/display_proxy'
module Glimmer
module DSL
module SWT
class RgbExpression < ColorExpression
end
end
end
end
| ruby | MIT | 449cf07ada1ec965ae2ac91715ccdf22488df4ca | 2026-01-04T17:52:38.125591Z | false |
AndyObtiva/glimmer-dsl-swt | https://github.com/AndyObtiva/glimmer-dsl-swt/blob/449cf07ada1ec965ae2ac91715ccdf22488df4ca/lib/glimmer/swt/table_proxy.rb | lib/glimmer/swt/table_proxy.rb | # Copyright (c) 2007-2025 Andy Maleh
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
require 'glimmer/swt/widget_proxy'
module Glimmer
module SWT
class TableProxy < Glimmer::SWT::WidgetProxy
include Glimmer
module TableListenerEvent
def table_item
table_item_and_column_index[:table_item]
end
def column_index
table_item_and_column_index[:column_index]
end
private
def table_item_and_column_index
@table_item_and_column_index ||= find_table_item_and_column_index
end
def find_table_item_and_column_index
{}.tap do |result|
if respond_to?(:x) && respond_to?(:y)
result[:table_item] = widget.items.detect do |ti|
result[:column_index] = widget.column_count.times.to_a.detect do |ci|
ti.getBounds(ci).contains(x, y)
end
end
end
end
end
end
class << self
def editors
@editors ||= {
# ensure editor can work with string keys not just symbols (leave one string in for testing)
'text' => {
widget_value_property: :text,
editor_gui: lambda do |args, model, property, table_proxy|
table_proxy.table_editor.minimumHeight = 20
table_editor_widget_proxy = text(*args) {
text model.send(property)
focus true
on_focus_lost {
table_proxy.finish_edit!
}
on_key_pressed { |key_event|
if key_event.keyCode == swt(:cr)
table_proxy.finish_edit!
elsif key_event.keyCode == swt(:esc)
table_proxy.cancel_edit!
end
}
}
table_editor_widget_proxy.swt_widget.selectAll
table_editor_widget_proxy
end,
},
combo: {
widget_value_property: :text,
editor_gui: lambda do |args, model, property, table_proxy|
first_time = true
table_proxy.table_editor.minimumHeight = 25
table_editor_widget_proxy = combo(*args) {
items model.send("#{property}_options")
text model.send(property)
focus true
on_focus_lost {
table_proxy.finish_edit!
}
on_key_pressed { |key_event|
if key_event.keyCode == swt(:cr)
table_proxy.finish_edit!
elsif key_event.keyCode == swt(:esc)
table_proxy.cancel_edit!
end
}
on_widget_selected {
if !OS.windows? || !first_time || first_time && model.send(property) != table_editor_widget_proxy.swt_widget.text
table_proxy.finish_edit!
end
}
}
table_editor_widget_proxy
end,
},
checkbox: {
widget_value_property: :selection,
editor_gui: lambda do |args, model, property, table_proxy|
first_time = true
table_proxy.table_editor.minimumHeight = 25
checkbox(*args) {
selection model.send(property)
focus true
on_widget_selected {
table_proxy.finish_edit!
}
on_focus_lost {
table_proxy.finish_edit!
}
on_key_pressed { |key_event|
if key_event.keyCode == swt(:cr)
table_proxy.finish_edit!
elsif key_event.keyCode == swt(:esc)
table_proxy.cancel_edit!
end
}
}
end,
},
date: {
widget_value_property: :date_time,
editor_gui: lambda do |args, model, property, table_proxy|
first_time = true
table_proxy.table_editor.minimumHeight = 25
date(*args) {
date_time model.send(property)
focus true
on_focus_lost {
table_proxy.finish_edit!
}
on_key_pressed { |key_event|
if key_event.keyCode == swt(:cr)
table_proxy.finish_edit!
elsif key_event.keyCode == swt(:esc)
table_proxy.cancel_edit!
end
}
}
end,
},
date_drop_down: {
widget_value_property: :date_time,
editor_gui: lambda do |args, model, property, table_proxy|
first_time = true
table_proxy.table_editor.minimumHeight = 25
date_drop_down(*args) {
date_time model.send(property)
focus true
on_focus_lost {
table_proxy.finish_edit!
}
on_key_pressed { |key_event|
if key_event.keyCode == swt(:cr)
table_proxy.finish_edit!
elsif key_event.keyCode == swt(:esc)
table_proxy.cancel_edit!
end
}
}
end,
},
time: {
widget_value_property: :date_time,
editor_gui: lambda do |args, model, property, table_proxy|
first_time = true
table_proxy.table_editor.minimumHeight = 25
time(*args) {
date_time model.send(property)
focus true
on_focus_lost {
table_proxy.finish_edit!
}
on_key_pressed { |key_event|
if key_event.keyCode == swt(:cr)
table_proxy.finish_edit!
elsif key_event.keyCode == swt(:esc)
table_proxy.cancel_edit!
end
}
}
end,
},
radio: {
widget_value_property: :selection,
editor_gui: lambda do |args, model, property, table_proxy|
first_time = true
table_proxy.table_editor.minimumHeight = 25
radio(*args) {
selection model.send(property)
focus true
on_widget_selected {
table_proxy.finish_edit!
}
on_focus_lost {
table_proxy.finish_edit!
}
on_key_pressed { |key_event|
if key_event.keyCode == swt(:cr)
table_proxy.finish_edit!
elsif key_event.keyCode == swt(:esc)
table_proxy.cancel_edit!
end
}
}
end,
},
spinner: {
widget_value_property: :selection,
editor_gui: lambda do |args, model, property, table_proxy|
first_time = true
table_proxy.table_editor.minimumHeight = 25
table_editor_widget_proxy = spinner(*args) {
selection model.send(property)
focus true
on_focus_lost {
table_proxy.finish_edit!
}
on_key_pressed { |key_event|
if key_event.keyCode == swt(:cr)
table_proxy.finish_edit!
elsif key_event.keyCode == swt(:esc)
table_proxy.cancel_edit!
end
}
}
table_editor_widget_proxy
end,
},
}
end
end
attr_reader :table_editor, :table_editor_widget_proxy, :sort_property, :sort_direction, :sort_block, :sort_type, :sort_by_block, :additional_sort_properties, :editor, :editable
attr_writer :column_properties
attr_accessor :table_items_binding, :sort_strategy
alias column_attributes= column_properties=
alias editable? editable
def initialize(underscored_widget_name, parent, args)
editable_style = args.delete(:editable)
super
@table_editor = TableEditor.new(swt_widget)
@table_editor.horizontalAlignment = SWTProxy[:left]
@table_editor.grabHorizontal = true
@table_editor.minimumHeight = 20
self.editable = editable_style
end
def column_properties
if @column_properties.nil?
swt_widget.columns.to_a.map(&:text).map(&:underscore)
elsif @column_properties.is_a?(Hash)
@column_properties = swt_widget.columns.to_a.map(&:text).map do |column_name|
@column_properties[column_name] || column_name.underscore
end
else
@column_properties
end
end
alias column_attributes column_properties
def items
auto_exec do
swt_widget.get_items
end
end
def model_binding
auto_exec do
swt_widget.data
end
end
def table_items_binding
auto_exec do
swt_widget.get_data('table_items_binding')
end
end
def editable=(value)
@editable = value
if @editable
content {
@editable_on_mouse_up = on_mouse_up { |event|
edit_table_item(event.table_item, event.column_index)
}
}
else
@editable_on_mouse_up.deregister if @editable_on_mouse_up
end
end
def sort_block=(comparator)
@sort_block = comparator
end
def sort_by_block=(property_picker)
@sort_by_block = property_picker
end
def sort_property=(new_sort_property)
@sort_property = [new_sort_property].flatten.compact
end
def detect_sort_type
@sort_type = sort_property.size.times.map { String }
array = model_binding.evaluate_property
sort_property.each_with_index do |a_sort_property, i|
values = array.map { |object| object.send(a_sort_property) }
value_classes = values.map(&:class).uniq
if value_classes.size == 1
@sort_type[i] = value_classes.first
elsif value_classes.include?(Integer)
@sort_type[i] = Integer
elsif value_classes.include?(Float)
@sort_type[i] = Float
end
end
end
def column_sort_properties
column_properties.zip(table_column_proxies.map(&:sort_property)).map do |pair|
[pair.compact.last].flatten.compact
end
end
# Sorts by specified TableColumnProxy object. If nil, it uses the table default sort instead.
def sort_by_column!(table_column_proxy=nil)
index = nil
auto_exec do
index = swt_widget.columns.to_a.index(table_column_proxy.swt_widget) unless table_column_proxy.nil?
end
new_sort_property = table_column_proxy.nil? ? @sort_property : table_column_proxy.sort_property || [column_properties[index]]
return if table_column_proxy.nil? && new_sort_property.nil? && @sort_block.nil? && @sort_by_block.nil?
if new_sort_property && table_column_proxy.nil? && new_sort_property.size == 1 && (index = column_sort_properties.index(new_sort_property))
table_column_proxy = table_column_proxies[index]
end
if new_sort_property && new_sort_property.size == 1 && !additional_sort_properties.to_a.empty?
selected_additional_sort_properties = additional_sort_properties.clone
if selected_additional_sort_properties.include?(new_sort_property.first)
selected_additional_sort_properties.delete(new_sort_property.first)
new_sort_property += selected_additional_sort_properties
else
new_sort_property += additional_sort_properties
end
end
@sort_direction = @sort_direction.nil? || @sort_property.first != new_sort_property.first || @sort_direction == :descending ? :ascending : :descending
auto_exec do
swt_widget.sort_direction = @sort_direction == :ascending ? SWTProxy[:up] : SWTProxy[:down]
end
@sort_property = [new_sort_property].flatten.compact
table_column_index = column_properties.index(new_sort_property.to_s.to_sym)
table_column_proxy ||= table_column_proxies[table_column_index] if table_column_index
auto_exec do
swt_widget.sort_column = table_column_proxy.swt_widget if table_column_proxy
end
if table_column_proxy
@sort_by_block = nil
@sort_block = nil
end
@sort_type = nil
if table_column_proxy&.sort_by_block
@sort_by_block = table_column_proxy.sort_by_block
elsif table_column_proxy&.sort_block
@sort_block = table_column_proxy.sort_block
else
detect_sort_type
end
sort!
end
def initial_sort!
sort_by_column!
end
def additional_sort_properties=(args)
@additional_sort_properties = args unless args.empty?
end
def sort!(internal_sort: false)
return unless sort_property && (sort_type || sort_block || sort_by_block)
if sort_strategy
sort_strategy.call
else
original_array = array = model_binding.evaluate_property
array = array.sort_by(&:hash) # this ensures consistent subsequent sorting in case there are equivalent sorts to avoid an infinite loop
# Converting value to_s first to handle nil cases. Should work with numeric, boolean, and date fields
if sort_block
sorted_array = array.sort(&sort_block)
elsif sort_by_block
sorted_array = array.sort_by(&sort_by_block)
else
sorted_array = array.sort_by do |object|
sort_property.each_with_index.map do |a_sort_property, i|
value = object.send(a_sort_property)
# handle nil and difficult to compare types gracefully
if sort_type[i] == Integer
value = value.to_i
elsif sort_type[i] == Float
value = value.to_f
elsif sort_type[i] == String
value = value.to_s.downcase
end
value
end
end
end
sorted_array = sorted_array.reverse if sort_direction == :descending
if model_binding.binding_options.symbolize_keys[:read_only_sort]
table_items_binding.call(sorted_array, internal_sort: true) unless internal_sort
else
model_binding.call(sorted_array)
end
sorted_array
end
end
def no_sort=(value)
table_column_proxies.each do |table_column_proxy|
table_column_proxy.no_sort = value
end
end
def editor=(args)
@editor = args
end
def cells_for(model, table_item_property: :text)
if table_item_property.to_s == 'text'
column_properties.map {|column_property| model.send(column_property)}
else
column_properties.map do |column_property|
model.send("#{column_property}_#{table_item_property}") if model.respond_to?("#{column_property}_#{table_item_property}")
end
end
end
def cells
column_count = @table.column_properties.size
auto_exec do
swt_widget.items.map {|item| column_count.times.map {|i| item.get_text(i)} }
end
end
# Performs a search for table items matching block condition
# If no condition block is passed, returns all table items
# Returns a Java TableItem array to easily set as selection on org.eclipse.swt.Table if needed
def search(&condition)
auto_exec do
swt_widget.getItems.select {|item| condition.nil? || condition.call(item)}.to_java(TableItem)
end
end
# Returns all table items including descendants
def all_table_items
search
end
def post_initialize_child(table_column_proxy)
table_column_proxies << table_column_proxy
end
def post_add_content
return if @initially_sorted
initial_sort!
@initially_sorted = true
end
def table_column_proxies
@table_column_proxies ||= []
end
# Indicates if table is in edit mode, thus displaying a text widget for a table item cell
def edit_mode?
!!@edit_mode
end
def cancel_edit!
@cancel_edit&.call if @edit_mode
end
def finish_edit!
@finish_edit&.call if @edit_mode
end
# Indicates if table is editing a table item because the user hit ENTER or focused out after making a change in edit mode to a table item cell.
# It is set to false once change is saved to model
def edit_in_progress?
!!@edit_in_progress
end
def edit_selected_table_item(column_index, before_write: nil, after_write: nil, after_cancel: nil)
auto_exec do
edit_table_item(swt_widget.getSelection.first, column_index, before_write: before_write, after_write: after_write, after_cancel: after_cancel)
end
end
def edit_table_item(table_item, column_index, before_write: nil, after_write: nil, after_cancel: nil, write_on_cancel: false)
return if table_item.nil?
model = table_item.data
property = column_properties[column_index]
cancel_edit!
return unless table_column_proxies[column_index].editable?
action_taken = false
@edit_mode = true
editor_config = table_column_proxies[column_index].editor || editor
editor_config = editor_config.to_a
editor_widget_options = editor_config.last.is_a?(Hash) ? editor_config.last : {}
editor_widget_arg_last_index = editor_config.last.is_a?(Hash) ? -2 : -1
editor_widget = (editor_config[0] || :text).to_sym
editor_widget_args = editor_config[1..editor_widget_arg_last_index]
model_editing_property = editor_widget_options[:property] || property
widget_value_property = TableProxy::editors.symbolize_keys[editor_widget][:widget_value_property]
@cancel_edit = lambda do |event=nil|
if write_on_cancel
@finish_edit.call(event)
else
@cancel_in_progress = true
@table_editor_widget_proxy&.swt_widget&.dispose
@table_editor_widget_proxy = nil
if after_cancel&.arity == 0
after_cancel&.call
else
after_cancel&.call(table_item)
end
@edit_in_progress = false
@cancel_in_progress = false
@cancel_edit = nil
@edit_mode = false
end
end
@finish_edit = lambda do |event=nil|
new_value = @table_editor_widget_proxy&.send(widget_value_property)
if table_item.isDisposed
@cancel_edit.call unless write_on_cancel
elsif !new_value.nil? && !action_taken && !@edit_in_progress && !@cancel_in_progress
action_taken = true
@edit_in_progress = true
if new_value == model.send(model_editing_property)
@cancel_edit.call unless write_on_cancel
else
if before_write&.arity == 0
before_write&.call
else
before_write&.call(edited_table_item)
end
model.send("#{model_editing_property}=", new_value) # makes table update itself, so must search for selected table item again
# Table refresh happens here because of model update triggering observers, so must retrieve table item again
edited_table_item = search { |ti| ti.getData == model }.first
auto_exec do
swt_widget.showItem(edited_table_item)
end
@table_editor_widget_proxy&.swt_widget&.dispose
@table_editor_widget_proxy = nil
if after_write&.arity == 0
after_write&.call
else
after_write&.call(edited_table_item)
end
@edit_in_progress = false
end
end
end
content {
@table_editor_widget_proxy = TableProxy::editors.symbolize_keys[editor_widget][:editor_gui].call(editor_widget_args, model, model_editing_property, self)
}
@table_editor.setEditor(@table_editor_widget_proxy.swt_widget, table_item, column_index)
rescue => e
Glimmer::Config.logger.error {e.full_message}
raise e
end
def add_listener(underscored_listener_name, &block)
enhanced_block = lambda do |event|
event.extend(TableListenerEvent)
block.call(event)
end
super(underscored_listener_name, &enhanced_block)
end
private
def property_type_converters
super.merge({
selection: lambda do |value|
if value.is_a?(Array)
search {|ti| value.include?(ti.getData) }
else
search {|ti| ti.getData == value}
end
end,
})
end
end
end
end
| ruby | MIT | 449cf07ada1ec965ae2ac91715ccdf22488df4ca | 2026-01-04T17:52:38.125591Z | false |
AndyObtiva/glimmer-dsl-swt | https://github.com/AndyObtiva/glimmer-dsl-swt/blob/449cf07ada1ec965ae2ac91715ccdf22488df4ca/lib/glimmer/swt/menu_proxy.rb | lib/glimmer/swt/menu_proxy.rb | # Copyright (c) 2007-2025 Andy Maleh
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
require 'glimmer/swt/widget_proxy'
module Glimmer
module SWT
# Proxy for org.eclipse.swt.widgets.Menu
#
# Functions differently from other widget proxies.
#
# Glimmer automatically detects if this is a drop down menu
# or pop up menu from its parent if no SWT style is passed in.
#
# There are 3 possibilities:
# - SWT :bar style is passed in: Menu Bar
# - Parent is ShellProxy: Pop Up Menu (having style :pop_up)
# - Parent is another Menu: Drop Down Menu (having style :drop_down)
#
# In order to get the SWT Menu object, one must call `#swt_widget`.
#
# In the case of a Drop Down menu, this automatically creates an
# SWT MenuItem object with style :cascade
#
# In order to retrieve the menu item widget proxy, one must call `#menu_item_proxy`
#
# Follows the Proxy Design Pattern
class MenuProxy < WidgetProxy
include_package 'org.eclipse.swt.widgets'
attr_reader :menu_item_proxy, :swt_menu_item, :menu_parent
def initialize(parent, args)
index = args.delete(args.last) if args.last.is_a?(Numeric)
styles = args.map(&:to_sym)
if !styles.include?(:bar) && !parent.swt_widget.is_a?(Menu)
styles = styles.unshift(:pop_up)
end
swt_widget_class = self.class.swt_widget_class_for('menu')
if parent.swt_widget.is_a?(Menu)
# TODO support CustomWidget children_owner
@menu_item_proxy = SWT::WidgetProxy.new('menu_item', parent, [:cascade] + [index].compact)
@swt_menu_item = @menu_item_proxy.swt_widget
@swt_widget = swt_widget_class.new(@menu_item_proxy.swt_widget)
@swt_menu_item.setMenu(swt_widget)
elsif parent.swt_widget.is_a?(Shell)
@swt_widget = swt_widget_class.new(parent.swt_widget, style('menu', styles))
elsif parent.swt_widget.is_a?(TrayItem)
# TODO support CustomWidget children_owner
@swt_widget = swt_widget_class.new(parent.shell_proxy.swt_widget, style('menu', styles))
parent.menu_proxy = self
else
@swt_widget = swt_widget_class.new(parent.swt_widget)
end
if styles.include?(:bar)
DisplayProxy.instance.auto_exec { parent.swt_widget.setMenuBar(swt_widget) }
elsif styles.include?(:pop_up)
if parent.swt_widget.is_a?(TrayItem)
parent.on_menu_detected {
self.visible = true
}
else
DisplayProxy.instance.auto_exec {
parent.swt_widget.setMenu(swt_widget) unless parent.swt_widget.is_a?(TrayItem)
}
end
end
end
def has_attribute?(attribute_name, *args)
if ['text', 'enabled'].include?(attribute_name.to_s)
true
else
super(attribute_name, *args)
end
end
def set_attribute(attribute_name, *args)
if normalized_attribute(attribute_name) == 'text'
text_value = args[0]
@swt_menu_item.setText text_value
elsif normalized_attribute(attribute_name) == 'enabled'
value = args[0]
@swt_menu_item.setEnabled value
else
super(attribute_name, *args)
end
end
def get_attribute(attribute_name)
if normalized_attribute(attribute_name) == 'text'
@swt_menu_item.getText
elsif normalized_attribute(attribute_name) == 'enabled'
@swt_menu_item.getEnabled
else
super(attribute_name)
end
end
def can_handle_observation_request?(observation_request, super_only: false)
observation_request = observation_request.to_s
super_result = super(observation_request)
if observation_request.start_with?('on_') && !super_result && !super_only
return menu_item_proxy.can_handle_observation_request?(observation_request)
else
super_result
end
end
def handle_observation_request(observation_request, &block)
if can_handle_observation_request?(observation_request, super_only: true)
super
else
menu_item_proxy.handle_observation_request(observation_request, &block)
end
end
end
end
end
| ruby | MIT | 449cf07ada1ec965ae2ac91715ccdf22488df4ca | 2026-01-04T17:52:38.125591Z | false |
AndyObtiva/glimmer-dsl-swt | https://github.com/AndyObtiva/glimmer-dsl-swt/blob/449cf07ada1ec965ae2ac91715ccdf22488df4ca/lib/glimmer/swt/sash_form_proxy.rb | lib/glimmer/swt/sash_form_proxy.rb | # Copyright (c) 2007-2025 Andy Maleh
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
require 'glimmer/swt/widget_proxy'
require 'glimmer/swt/color_proxy'
module Glimmer
module SWT
# Proxy for org.eclipse.swt.custom.SashForm
#
# Follows the Proxy Design Pattern
class SashFormProxy < WidgetProxy
def initialize(*args, &block)
super
self.background = ColorProxy.new(230, 230, 230).swt_color
end
def post_add_content
self.weights = @weights unless @weights.nil?
end
def set_attribute(attribute_name, *args)
if attribute_name.to_s == 'weights'
@weights = args
@weights = @weights.first if @weights.first.is_a?(Array)
else
super(attribute_name, *args)
end
end
def get_attribute(attribute_name)
if attribute_name.to_s == "weights"
swt_widget.getWeights.to_a
else
super(attribute_name)
end
end
end
end
end
| ruby | MIT | 449cf07ada1ec965ae2ac91715ccdf22488df4ca | 2026-01-04T17:52:38.125591Z | false |
AndyObtiva/glimmer-dsl-swt | https://github.com/AndyObtiva/glimmer-dsl-swt/blob/449cf07ada1ec965ae2ac91715ccdf22488df4ca/lib/glimmer/swt/tab_item_proxy.rb | lib/glimmer/swt/tab_item_proxy.rb | # Copyright (c) 2007-2025 Andy Maleh
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
require 'glimmer/swt/widget_proxy'
module Glimmer
module SWT
# Proxy for org.eclipse.swt.widgets.TabItem
#
# Functions differently from other widget proxies.
#
# Glimmer instantiates an SWT Composite alongside the SWT TabItem
# and returns it for `#swt_widget` to allow adding widgets into it.
#
# In order to get the SWT TabItem object, one must call `#swt_tab_item`.
#
# Behind the scenes, this creates a tab item widget proxy separately from a composite that
# is set as the control of the tab item and `#swt_widget`.
#
# In order to retrieve the tab item widget proxy, one must call `#widget_proxy`
#
# Follows the Proxy Design Pattern
class TabItemProxy < WidgetProxy
ATTRIBUTES = %w[text image tool_tip_text]
include_package 'org.eclipse.swt.widgets'
attr_reader :widget_proxy, :swt_tab_item
def initialize(parent, style, &contents)
super("composite", parent, style, &contents)
keyword = self.class.name.split('::').last.underscore.sub('_proxy', '')
@widget_proxy = SWT::WidgetProxy.new(keyword, parent, style)
@swt_tab_item = @widget_proxy.swt_widget
@swt_tab_item.control = swt_widget
end
def attributes
ATTRIBUTES
end
def has_attribute?(attribute_name, *args)
attributes.include?(attribute_name.to_s) || super(attribute_name, *args)
end
def set_attribute(attribute_name, *args)
attribute_name = attribute_name.to_s
if attributes.include?(attribute_name)
widget_proxy.set_attribute(attribute_name, *args)
else
super(attribute_name, *args)
end
end
def get_attribute(attribute_name)
attribute_name = attribute_name.to_s
if attributes.include?(attribute_name)
widget_proxy.get_attribute(attribute_name)
else
super(attribute_name)
end
end
ATTRIBUTES.each do |attribute|
define_method(attribute) do
auto_exec do
widget_proxy.send(attribute)
end
end
define_method("#{attribute}=") do |value|
value.tap do
auto_exec do
widget_proxy.send("#{attribute}=", value)
shell_proxy.pack_same_size
end
end
end
end
def dispose
auto_exec do
swt_tab_item.setControl(nil)
swt_widget.dispose
swt_tab_item.dispose
end
end
end
end
end
| ruby | MIT | 449cf07ada1ec965ae2ac91715ccdf22488df4ca | 2026-01-04T17:52:38.125591Z | false |
AndyObtiva/glimmer-dsl-swt | https://github.com/AndyObtiva/glimmer-dsl-swt/blob/449cf07ada1ec965ae2ac91715ccdf22488df4ca/lib/glimmer/swt/image_proxy.rb | lib/glimmer/swt/image_proxy.rb | # Copyright (c) 2007-2025 Andy Maleh
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
require 'glimmer/swt/custom/drawable'
require 'glimmer/swt/properties'
module Glimmer
module SWT
# Proxy for org.eclipse.swt.graphics.Image
#
# Invoking `#swt_image` returns the SWT Image object wrapped by this proxy
#
# Follows the Proxy Design Pattern
class ImageProxy
include Custom::Drawable
include Properties
class << self
include_package 'org.eclipse.swt.graphics'
def create(*args, &content)
if args.size == 1 && args.first.is_a?(ImageProxy)
args.first
else
new(*args, &content)
end
end
def create_pixel_by_pixel(*args, &each_pixel_color)
image_proxy = create(*args)
options = args.last.is_a?(Hash) ? args.pop : {}
height = args[-1]
width = args[-2]
image_proxy.paint_pixel_by_pixel(width, height, &each_pixel_color)
image_proxy
end
end
include_package 'org.eclipse.swt.widgets'
include_package 'org.eclipse.swt.graphics'
attr_reader :file_path, :jar_file_path, :image_data, :swt_image, :parent_proxy, :parent
# Initializes a proxy for an SWT Image object
#
# Takes the same args as the SWT Image class
# Alternatively, takes a file path string or a uri:classloader file path string (generated by JRuby when invoking `File.expand_path` inside a JAR file)
# and returns an image object.
# Last but not least, it could serve as a parent for nesting shapes underneath to build an image with the Canvas Shape DSL
def initialize(*args, &content)
@args = args
@parent_proxy = nil
if @args.first.is_a?(WidgetProxy)
@parent_proxy = @args.shift
@parent = @parent_proxy.swt_widget
end
options = @args.last.is_a?(Hash) ? @args.delete_at(-1) : {}
options[:swt_image] = @args.first if @args.size == 1 && @args.first.is_a?(Image)
@args = @args.first if @args.size == 1 && @args.first.is_a?(Array)
@file_path = @args.first if @args.first.is_a?(String)
if options&.keys&.include?(:swt_image)
@swt_image = options[:swt_image]
@original_image_data = @image_data = @swt_image.image_data
elsif args.size == 1 && args.first.is_a?(ImageProxy)
@swt_image = @args.first.swt_image
@original_image_data = @image_data = @swt_image.image_data
elsif @file_path
@original_image_data = @image_data = ImageData.new(input_stream || @file_path)
@swt_image = Image.new(DisplayProxy.instance.swt_display, @image_data)
width = options[:width]
height = options[:height]
height = (@image_data.height.to_f / @image_data.width.to_f)*width.to_f if !width.nil? && height.nil?
width = (@image_data.width.to_f / @image_data.height.to_f)*height.to_f if !height.nil? && width.nil?
scale_to(width, height) unless width.nil? || height.nil?
elsif !@args.first.is_a?(ImageProxy) && !@args.first.is_a?(Image)
@args.prepend(DisplayProxy.instance.swt_display) unless @args.first.is_a?(Display)
@swt_image = Image.new(*@args)
@original_image_data = @image_data = @swt_image.image_data
end
proxy = self
# TODO consider adding a get_data/set_data method to conform with other SWT widgets
@swt_image.class.__persistent__ = true
@swt_image.singleton_class.define_method(:dispose) do
proxy.clear_shapes
super()
end
post_add_content if content.nil?
end
def post_add_content
if shapes.any?
setup_shape_painting
end
if @parent.respond_to?('image=') && !@parent.is_disposed
@parent&.image = swt_image
end
end
def shape(parent_proxy = nil, args = nil)
parent_proxy ||= @parent_proxy
args ||= [self] # TODO consider passing args if available
@shape ||= Glimmer::SWT::Custom::Shape.new(parent_proxy, 'image', *args)
end
def input_stream
if @file_path.start_with?('uri:classloader')
@jar_file_path = @file_path
file_path = @jar_file_path.sub(/^uri\:classloader\:/, '').sub(/^\/+/, '')
require 'jruby'
jcl = JRuby.runtime.jruby_class_loader
resource = jcl.get_resource_as_stream(file_path)
file_input_stream = resource.to_io.to_input_stream
else
file_input_stream = java.io.FileInputStream.new(@file_path)
end
java.io.BufferedInputStream.new(file_input_stream) if file_input_stream
end
def scale_to(width, height)
return self if (width == 0) || (height == 0) || (@image_data.width == width && @image_data.height == height)
scaled_image_data = @original_image_data.scaledTo(width, height)
device = swt_image.device
swt_image.dispose
@swt_image = Image.new(device, scaled_image_data)
@image_data = @swt_image.image_data
self
end
def size
org.eclipse.swt.graphics.Point.new(bounds.width, bounds.height)
end
def gc
@gc ||= reset_gc
end
def reset_gc
@gc = org.eclipse.swt.graphics.GC.new(swt_image)
end
def disposed?
@swt_image.isDisposed
end
def has_attribute?(attribute_name, *args)
@swt_image.respond_to?(attribute_setter(attribute_name), args) || respond_to?(ruby_attribute_setter(attribute_name), args)
end
def set_attribute(attribute_name, *args)
# TODO consider refactoring/unifying this code with WidgetProxy and elsewhere
if args.count == 1
if args.first.is_a?(Symbol) || args.first.is_a?(String)
args[0] = ColorProxy.new(args.first).swt_color
end
if args.first.is_a?(ColorProxy)
args[0] = args.first.swt_color
end
end
if @swt_image.respond_to?(attribute_setter(attribute_name))
@swt_image.send(attribute_setter(attribute_name), *args) unless @swt_image.send(attribute_getter(attribute_name)) == args.first
elsif @swt_image.respond_to?(ruby_attribute_setter(attribute_name))
@swt_image.send(ruby_attribute_setter(attribute_name), args)
else
send(ruby_attribute_setter(attribute_name), args)
end
end
def get_attribute(attribute_name)
if @swt_image.respond_to?(attribute_getter(attribute_name))
@swt_image.send(attribute_getter(attribute_name))
elsif @swt_image.respond_to?(ruby_attribute_getter(attribute_name))
@swt_image.send(ruby_attribute_getter(attribute_name))
elsif @swt_image.respond_to?(attribute_name)
@swt_image.send(attribute_name)
elsif respond_to?(ruby_attribute_getter(attribute_name))
send(ruby_attribute_getter(attribute_name))
else
send(attribute_name)
end
end
def method_missing(method_name, *args, &block)
swt_image.send(method_name, *args, &block)
rescue => e
Glimmer::Config.logger.debug {"Neither ImageProxy nor #{swt_image.class.name} can handle the method ##{method_name}"}
super
end
def respond_to?(method_name, *args, &block)
super || swt_image.respond_to?(method_name, *args, &block)
end
end
end
end
| ruby | MIT | 449cf07ada1ec965ae2ac91715ccdf22488df4ca | 2026-01-04T17:52:38.125591Z | false |
AndyObtiva/glimmer-dsl-swt | https://github.com/AndyObtiva/glimmer-dsl-swt/blob/449cf07ada1ec965ae2ac91715ccdf22488df4ca/lib/glimmer/swt/tray_proxy.rb | lib/glimmer/swt/tray_proxy.rb | # Copyright (c) 2007-2025 Andy Maleh
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
require 'glimmer/swt/display_proxy'
module Glimmer
module SWT
# Proxy for org.eclipse.swt.widgets.Tray
#
# Invoking `#swt_widget` returns the SWT Tray object wrapped by this proxy
#
# Follows the Proxy Design Pattern and Flyweight Design Pattern (caching memoization)
class TrayProxy
class << self
def instance
@instance ||= new(Glimmer::SWT::DisplayProxy.instance)
end
end
attr_reader :swt_widget
def initialize(display_proxy)
@swt_widget = display_proxy.getSystemTray
end
def method_missing(method_name, *args, &block)
@swt_widget.send(method_name, *args, &block)
end
def respond_to?(method_name, *args, &block)
super || @swt_widget.respond_to?(method_name, *args, &block)
end
def post_initialize_child(child)
# No Op
end
# Subclasses may override to perform post add_content work.
# Make sure its logic detects if it ran before since it could run multiple times
# when adding content multiple times post creation.
def post_add_content
# No Op
end
end
end
end
| ruby | MIT | 449cf07ada1ec965ae2ac91715ccdf22488df4ca | 2026-01-04T17:52:38.125591Z | false |
AndyObtiva/glimmer-dsl-swt | https://github.com/AndyObtiva/glimmer-dsl-swt/blob/449cf07ada1ec965ae2ac91715ccdf22488df4ca/lib/glimmer/swt/tree_proxy.rb | lib/glimmer/swt/tree_proxy.rb | # Copyright (c) 2007-2025 Andy Maleh
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
require 'glimmer/swt/widget_proxy'
module Glimmer
module SWT
class TreeProxy < Glimmer::SWT::WidgetProxy
include Glimmer
attr_reader :tree_editor, :tree_editor_text_proxy
attr_accessor :tree_properties
def initialize(underscored_widget_name, parent, args)
super
@tree_editor = TreeEditor.new(swt_widget)
@tree_editor.horizontalAlignment = SWTProxy[:left]
@tree_editor.grabHorizontal = true
@tree_editor.minimumHeight = 20
end
# Performs depth first search for tree items matching block condition
# If no condition block is passed, returns all tree items
# Returns a Java TreeItem array to easily set as selection on org.eclipse.swt.Tree if needed
def depth_first_search(&condition)
found = []
first_item = DisplayProxy.instance.auto_exec { swt_widget.getItems.first }
recursive_depth_first_search(first_item, found, &condition)
found.to_java(TreeItem)
end
# Returns all tree items including descendants
def all_tree_items
depth_first_search
end
def edit_in_progress?
!!@edit_in_progress
end
def edit_selected_tree_item(before_write: nil, after_write: nil, after_cancel: nil)
edit_tree_item(swt_widget.getSelection.first, before_write: before_write, after_write: after_write, after_cancel: after_cancel)
end
def edit_tree_item(tree_item, before_write: nil, after_write: nil, after_cancel: nil)
return if tree_item.nil?
content {
@tree_editor_text_proxy = text {
focus true
text tree_item.getText
action_taken = false
cancel = lambda {
@tree_editor_text_proxy.swt_widget.dispose
@tree_editor_text_proxy = nil
after_cancel&.call
@edit_in_progress = false
}
action = lambda { |event|
begin
if !action_taken && !@edit_in_progress
action_taken = true
@edit_in_progress = true
new_text = @tree_editor_text_proxy.swt_widget.getText
if new_text == tree_item.getText
cancel.call
else
before_write&.call
tree_item.setText(new_text)
model = tree_item.getData
model.send("#{tree_properties[:text]}=", new_text) # makes tree update itself, so must search for selected tree item again
edited_tree_item = depth_first_search { |ti| ti.getData == model }.first
swt_widget.showItem(edited_tree_item)
@tree_editor_text_proxy.swt_widget.dispose
@tree_editor_text_proxy = nil
after_write&.call(edited_tree_item)
@edit_in_progress = false
end
end
rescue => e
Glimmer::Config.logger.error {"Error encountered while editing tree item!\n#{e.full_message}"}
end
}
on_focus_lost(&action)
on_key_pressed { |key_event|
if key_event.keyCode == swt(:cr)
action.call(key_event)
elsif key_event.keyCode == swt(:esc)
cancel.call
end
}
}
@tree_editor_text_proxy.swt_widget.selectAll
}
@tree_editor.setEditor(@tree_editor_text_proxy.swt_widget, tree_item)
end
private
def recursive_depth_first_search(tree_item, found, &condition)
return if tree_item.nil?
found << tree_item if condition.nil? || DisplayProxy.instance.auto_exec {condition.call(tree_item)}
# return if found.any? && !has_style?(:multi) # TODO inspect if this is a good optimization when needed
tree_items = DisplayProxy.instance.auto_exec {tree_item.getItems}
tree_items.each do |child_tree_item|
recursive_depth_first_search(child_tree_item, found, &condition)
end
end
def property_type_converters
super.merge({
selection: lambda do |value|
if value.is_a?(Array)
depth_first_search {|ti| value.include?(ti.getData) }
else
depth_first_search {|ti| ti.getData == value}
end
end,
})
end
end
end
end
| ruby | MIT | 449cf07ada1ec965ae2ac91715ccdf22488df4ca | 2026-01-04T17:52:38.125591Z | false |
AndyObtiva/glimmer-dsl-swt | https://github.com/AndyObtiva/glimmer-dsl-swt/blob/449cf07ada1ec965ae2ac91715ccdf22488df4ca/lib/glimmer/swt/table_column_proxy.rb | lib/glimmer/swt/table_column_proxy.rb | # Copyright (c) 2007-2025 Andy Maleh
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
require 'glimmer/swt/widget_proxy'
require 'glimmer/swt/swt_proxy'
module Glimmer
module SWT
# A proxy object representing SWT TableColumn
# Accepts a :no_sort custom style to disable sorting on this column
class TableColumnProxy < Glimmer::SWT::WidgetProxy
attr_reader :sort_property, :editor
attr_accessor :no_sort, :sort_block, :sort_by_block
alias no_sort? no_sort
def initialize(underscored_widget_name, parent, args)
@no_sort = args.delete(:no_sort)
super
on_widget_selected do |event|
parent.sort_by_column!(self) unless no_sort?
end unless no_sort?
end
def sort_property=(args)
@sort_property = args unless args.empty?
end
# Sets editor (e.g. combo)
def editor=(args)
@editor = args
end
def editable?
!@editor&.include?(:none)
end
end
end
end
| ruby | MIT | 449cf07ada1ec965ae2ac91715ccdf22488df4ca | 2026-01-04T17:52:38.125591Z | false |
AndyObtiva/glimmer-dsl-swt | https://github.com/AndyObtiva/glimmer-dsl-swt/blob/449cf07ada1ec965ae2ac91715ccdf22488df4ca/lib/glimmer/swt/widget_proxy.rb | lib/glimmer/swt/widget_proxy.rb | # Copyright (c) 2007-2025 Andy Maleh
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
require 'glimmer/swt/widget_listener_proxy'
require 'glimmer/swt/color_proxy'
require 'glimmer/swt/font_proxy'
require 'glimmer/swt/swt_proxy'
require 'glimmer/swt/display_proxy'
require 'glimmer/swt/dnd_proxy'
require 'glimmer/swt/image_proxy'
require 'glimmer/swt/proxy_properties'
require 'glimmer/swt/custom/drawable'
# TODO refactor to make file smaller and extract sub-widget-proxies out of this
module Glimmer
module SWT
# Proxy for SWT Widget objects
#
# Sets default SWT styles to widgets upon inititalizing as
# per DEFAULT_STYLES
#
# Also, auto-initializes widgets as per initializer blocks
# in DEFAULT_INITIALIZERS (e.g. setting Composite default layout)
#
# Follows the Proxy Design Pattern
class WidgetProxy
include Packages
include ProxyProperties
include Custom::Drawable
DEFAULT_STYLES = {
'arrow' => [:arrow, :down],
'browser' => ([:edge] if OS.windows?),
'button' => [:push],
'canvas' => ([:double_buffered] unless OS.mac?),
'ccombo' => [:border],
'checkbox' => [:check],
'check' => [:check],
'drag_source' => [:drop_copy],
'drop_target' => [:drop_copy],
'expand_bar' => [:v_scroll],
'list' => [:border, :v_scroll],
'menu_item' => [:push],
'radio' => [:radio],
'scrolled_composite' => [:border, :h_scroll, :v_scroll],
'spinner' => [:border],
'styled_text' => [:border, :multi, :v_scroll, :h_scroll],
'table' => [:virtual, :border, :full_selection],
'text' => [:border],
'toggle' => [:toggle],
'tool_bar' => [:push],
'tool_item' => [:push],
'tree' => [:virtual, :border, :h_scroll, :v_scroll],
'date_drop_down' => [:date, :drop_down],
'time' => [:time],
'calendar' => [:calendar],
}
DEFAULT_INITIALIZERS = {
composite: lambda do |composite|
composite.layout = GridLayout.new if composite.get_layout.nil?
end,
canvas: lambda do |canvas|
canvas.layout = nil if canvas.respond_to?('layout=') && !canvas.get_layout.nil?
end,
scrolled_composite: lambda do |scrolled_composite|
scrolled_composite.expand_horizontal = true
scrolled_composite.expand_vertical = true
end,
table: lambda do |table|
table.setHeaderVisible(true)
table.setLinesVisible(true)
end,
table_column: lambda do |table_column|
table_column.setWidth(80)
end,
group: lambda do |group|
group.layout = GridLayout.new if group.get_layout.nil?
end,
}
KEYWORD_ALIASES = {
'arrow' => 'button',
'checkbox' => 'button',
'check' => 'button',
'radio' => 'button',
'toggle' => 'button',
'date' => 'date_time',
'date_drop_down' => 'date_time',
'time' => 'date_time',
'calendar' => 'date_time',
}
class << self
# Instantiates the right WidgetProxy subclass for passed in keyword
# Args are: keyword, parent, swt_widget_args (including styles)
def create(*init_args, swt_widget: nil)
DisplayProxy.instance.auto_exec do
return swt_widget.get_data('proxy') if swt_widget&.get_data('proxy')
keyword, parent, args = init_args
selected_widget_proxy_class = widget_proxy_class(keyword || underscored_widget_name(swt_widget))
if init_args.empty?
selected_widget_proxy_class.new(swt_widget: swt_widget)
else
selected_widget_proxy_class.new(*init_args)
end
end
end
def widget_proxy_class(keyword)
begin
keyword = KEYWORD_ALIASES[keyword] if KEYWORD_ALIASES[keyword]
class_name = "#{keyword.camelcase(:upper)}Proxy".to_sym
Glimmer::SWT.const_get(class_name)
rescue
Glimmer::SWT::WidgetProxy
end
end
def underscored_widget_name(swt_widget)
swt_widget.class.name.split(/::|\./).last.underscore
end
end
attr_reader :parent_proxy, :swt_widget, :drag_source_proxy, :drop_target_proxy, :drag_source_style, :drag_source_transfer, :drop_target_transfer, :finished_add_content
alias finished_add_content? finished_add_content
# Initializes a new SWT Widget
#
# It is preferred to use `::create` method instead since it instantiates the
# right subclass per widget keyword
#
# keyword, parent, swt_widget_args (including styles)
#
# Styles is a comma separate list of symbols representing SWT styles in lower case
def initialize(*init_args, swt_widget: nil)
auto_exec do
@image_double_buffered = !!(init_args&.last&.include?(:image_double_buffered) && init_args&.last&.delete(:image_double_buffered))
if swt_widget.nil?
underscored_widget_name, parent, args = init_args
@parent_proxy = parent
styles, extra_options = extract_args(underscored_widget_name, args)
swt_widget_class = self.class.swt_widget_class_for(underscored_widget_name)
@swt_widget = swt_widget_class.new(@parent_proxy.swt_widget, style(underscored_widget_name, styles), *extra_options)
else
@swt_widget = swt_widget
underscored_widget_name = self.class.underscored_widget_name(@swt_widget)
parent_proxy_class = self.class.widget_proxy_class(self.class.underscored_widget_name(@swt_widget.parent))
parent = swt_widget.parent
@parent_proxy = parent&.get_data('proxy') || parent_proxy_class.new(swt_widget: parent)
end
shell_proxy # populates @shell_proxy attribute
if @swt_widget&.get_data('proxy').nil?
@swt_widget.set_data('proxy', self)
DEFAULT_INITIALIZERS[underscored_widget_name.to_s.to_sym]&.call(@swt_widget)
@parent_proxy.post_initialize_child(self)
end
@keyword = underscored_widget_name.to_s
if respond_to?(:on_widget_disposed)
on_widget_disposed {
unless shell_proxy.last_shell_closing?
clear_shapes
deregister_shape_painting
end
}
end
end
end
# Subclasses may override to perform post initialization work on an added child
def post_initialize_child(child)
# No Op by default
end
# Subclasses may override to perform post add_content work.
# Make sure its logic detects if it ran before since it could run multiple times
# when adding content multiple times post creation.
def post_add_content
# No Op by default
end
def finish_add_content!
@finished_add_content = true
end
def shell_proxy
if @swt_widget.respond_to?(:shell) && !@swt_widget.is_disposed
@shell_proxy = @swt_widget.shell.get_data('proxy')
elsif @parent_proxy&.shell_proxy
@shell_proxy = @parent_proxy&.shell_proxy
else
@shell_proxy
end
end
def extract_args(underscored_widget_name, args)
@arg_extractor_mapping ||= {
'menu_item' => lambda do |args|
index = args.delete(args.last) if args.last.is_a?(Numeric)
extra_options = [index].compact
styles = args
[styles, extra_options]
end,
}
if @arg_extractor_mapping[underscored_widget_name]
@arg_extractor_mapping[underscored_widget_name].call(args)
else
extra_options = []
style_args = args.select {|arg| arg.is_a?(Symbol) || arg.is_a?(String)}
if style_args.any?
style_arg_start_index = args.index(style_args.first)
style_arg_last_index = args.index(style_args.last)
extra_options = args[style_arg_last_index+1..-1]
args = args[style_arg_start_index..style_arg_last_index]
elsif args.first.is_a?(Integer)
extra_options = args[1..-1]
args = args[0..0]
end
[args, extra_options]
end
end
def proxy_source_object
@swt_widget
end
def has_attribute?(attribute_name, *args)
# TODO test that attribute getter responds too
widget_custom_attribute = widget_custom_attribute_mapping[attribute_name.to_s]
property_type_converter = property_type_converters[attribute_name.to_s.to_sym]
auto_exec do
if widget_custom_attribute
@swt_widget.respond_to?(widget_custom_attribute[:setter][:name])
elsif property_type_converter
true
else
super
end
end
end
def set_attribute(attribute_name, *args)
# TODO Think about widget subclasses overriding set_attribute to add more attributes vs adding as Ruby attributes directly
widget_custom_attribute = widget_custom_attribute_mapping[attribute_name.to_s]
auto_exec do
apply_property_type_converters(normalized_attribute(attribute_name), args)
end
swt_widget_operation = false
result = nil
auto_exec do
result = if widget_custom_attribute
swt_widget_operation = true
widget_custom_attribute[:setter][:invoker].call(@swt_widget, args)
end
end
result = super unless swt_widget_operation
result
end
def get_attribute(attribute_name)
widget_custom_attribute = widget_custom_attribute_mapping[attribute_name.to_s]
swt_widget_operation = false
result = nil
auto_exec do
result = if widget_custom_attribute
swt_widget_operation = true
if widget_custom_attribute[:getter][:invoker]
widget_custom_attribute[:getter][:invoker].call(@swt_widget, [])
else
@swt_widget.send(widget_custom_attribute[:getter][:name])
end
end
end
result = super unless swt_widget_operation
result
end
def pack_same_size
auto_exec do
bounds = @swt_widget.getBounds
listener = on_control_resized {
@swt_widget.setSize(bounds.width, bounds.height)
@swt_widget.setLocation(bounds.x, bounds.y)
}
if @swt_widget.is_a?(Composite)
@swt_widget.layout(true, true)
else
@swt_widget.pack(true)
end
@swt_widget.removeControlListener(listener.swt_listener)
end
end
def x
bounds.x
end
def y
bounds.y
end
def width
bounds.width
end
def height
bounds.height
end
# these work in tandem with the property_type_converters
# sometimes, they are specified in subclasses instead
def widget_property_listener_installers
@swt_widget_property_listener_installers ||= {
Java::OrgEclipseSwtWidgets::Control => {
:focus => lambda do |observer|
on_focus_gained { |focus_event|
observer.call(true)
}
on_focus_lost { |focus_event|
observer.call(false)
}
end,
:selection => lambda do |observer|
on_widget_selected { |selection_event|
observer.call(@swt_widget.getSelection)
} if can_handle_observation_request?(:on_widget_selected)
end,
:text => lambda do |observer|
on_modify_text { |modify_event|
observer.call(@swt_widget.getText)
} if can_handle_observation_request?(:on_modify_text)
end,
},
Java::OrgEclipseSwtWidgets::Combo => {
:text => lambda do |observer|
on_modify_text { |modify_event|
observer.call(@swt_widget.getText)
}
end,
},
Java::OrgEclipseSwtCustom::CCombo => {
:text => lambda do |observer|
on_modify_text { |modify_event|
observer.call(@swt_widget.getText)
}
end,
},
Java::OrgEclipseSwtWidgets::Table => {
:selection => lambda do |observer|
on_widget_selected { |selection_event|
if has_style?(:multi)
observer.call(@swt_widget.getSelection.map(&:get_data))
else
observer.call(@swt_widget.getSelection.first&.get_data)
end
}
end,
},
Java::OrgEclipseSwtWidgets::Tree => {
:selection => lambda do |observer|
on_widget_selected { |selection_event|
if has_style?(:multi)
observer.call(@swt_widget.getSelection.map(&:get_data))
else
observer.call(@swt_widget.getSelection.first&.get_data)
end
}
end,
},
Java::OrgEclipseSwtWidgets::Text => {
:text => lambda do |observer|
on_modify_text { |modify_event|
observer.call(@swt_widget.getText)
}
end,
:caret_position => lambda do |observer|
on_swt_keydown { |event|
observer.call(@swt_widget.getCaretPosition)
}
on_swt_keyup { |event|
observer.call(@swt_widget.getCaretPosition)
}
on_swt_mousedown { |event|
observer.call(@swt_widget.getCaretPosition)
}
on_swt_mouseup { |event|
observer.call(@swt_widget.getCaretPosition)
}
end,
:selection => lambda do |observer|
on_swt_keydown { |event|
observer.call(@swt_widget.getSelection)
}
on_swt_keyup { |event|
observer.call(@swt_widget.getSelection)
}
on_swt_mousedown { |event|
observer.call(@swt_widget.getSelection)
}
on_swt_mouseup { |event|
observer.call(@swt_widget.getSelection)
}
end,
:selection_count => lambda do |observer|
on_swt_keydown { |event|
observer.call(@swt_widget.getSelectionCount)
}
on_swt_keyup { |event|
observer.call(@swt_widget.getSelectionCount)
}
on_swt_mousedown { |event|
observer.call(@swt_widget.getSelectionCount)
}
on_swt_mouseup { |event|
observer.call(@swt_widget.getSelectionCount)
}
end,
:top_index => lambda do |observer|
@last_top_index = @swt_widget.getTopIndex
on_paint_control { |event|
if @swt_widget.getTopIndex != @last_top_index
@last_top_index = @swt_widget.getTopIndex
observer.call(@last_top_index)
end
}
end,
},
Java::OrgEclipseSwtCustom::StyledText => {
:text => lambda do |observer|
on_modify_text { |modify_event|
observer.call(@swt_widget.getText)
}
end,
:caret_position => lambda do |observer|
on_caret_moved { |event|
observer.call(@swt_widget.getSelection.x) unless @swt_widget.getCaretOffset == 0 && @last_modify_text != text
}
on_swt_keyup { |event|
observer.call(@swt_widget.getSelection.x) unless @swt_widget.getCaretOffset == 0 && @last_modify_text != text
}
on_swt_mouseup { |event|
observer.call(@swt_widget.getSelection.x) unless @swt_widget.getCaretOffset == 0 && @last_modify_text != text
}
end,
:caret_offset => lambda do |observer|
on_caret_moved { |event|
observer.call(@swt_widget.getCaretOffset) unless @swt_widget.getCaretOffset == 0 && @last_modify_text != text
}
end,
:selection => lambda do |observer|
on_widget_selected { |event|
observer.call(@swt_widget.getSelection) unless @swt_widget.getCaretOffset == 0 && @last_modify_text != text
}
on_swt_keyup { |event|
observer.call(@swt_widget.getSelection) unless @swt_widget.getCaretOffset == 0 && @last_modify_text != text
}
on_swt_mouseup { |event|
observer.call(@swt_widget.getSelection) unless @swt_widget.getCaretOffset == 0 && @last_modify_text != text
}
end,
:selection_count => lambda do |observer|
on_widget_selected { |event|
observer.call(@swt_widget.getSelectionCount) unless @swt_widget.getCaretOffset == 0 && @last_modify_text != text
}
on_swt_keyup { |event|
observer.call(@swt_widget.getSelectionCount) unless @swt_widget.getCaretOffset == 0 && @last_modify_text != text
}
on_swt_mouseup { |event|
observer.call(@swt_widget.getSelectionCount) unless @swt_widget.getCaretOffset == 0 && @last_modify_text != text
}
end,
:selection_range => lambda do |observer|
on_widget_selected { |event|
observer.call(@swt_widget.getSelectionRange) unless @swt_widget.getCaretOffset == 0 && @last_modify_text != text
}
on_swt_keyup { |event|
observer.call(@swt_widget.getSelectionRange) unless @swt_widget.getCaretOffset == 0 && @last_modify_text != text
}
on_swt_mouseup { |event|
observer.call(@swt_widget.getSelectionRange) unless @swt_widget.getCaretOffset == 0 && @last_modify_text != text
}
end,
:top_index => lambda do |observer|
@last_top_index = @swt_widget.getTopIndex
on_paint_control { |event|
if @swt_widget.getTopIndex != @last_top_index
@last_top_index = @swt_widget.getTopIndex
observer.call(@last_top_index)
end
}
end,
:top_pixel => lambda do |observer|
@last_top_pixel = @swt_widget.getTopPixel
on_paint_control { |event|
if @swt_widget.getTopPixel != @last_top_pixel
@last_top_pixel = @swt_widget.getTopPixel
observer.call(@last_top_pixel)
end
}
end,
},
Java::OrgEclipseSwtWidgets::Button => {
:selection => lambda do |observer|
on_widget_selected { |selection_event|
observer.call(@swt_widget.getSelection)
}
end
},
Java::OrgEclipseSwtWidgets::MenuItem => {
:selection => lambda do |observer|
on_widget_selected { |selection_event|
observer.call(@swt_widget.getSelection)
}
end
},
Java::OrgEclipseSwtWidgets::Spinner => {
:selection => lambda do |observer|
on_widget_selected { |selection_event|
observer.call(@swt_widget.getSelection)
}
end
},
Java::OrgEclipseSwtWidgets::DateTime =>
[:year, :month, :day, :hours, :minutes, :seconds, :date_time, :date, :time].reduce({}) do |hash, attribute|
hash.merge(
attribute => lambda do |observer|
on_widget_selected { |selection_event|
observer.call(get_attribute(attribute))
}
end
)
end,
}
end
def self.widget_exists?(underscored_widget_name)
!!swt_widget_class_for(underscored_widget_name)
end
# Manual entries of SWT widget classes that conflict with Ruby classes
def self.swt_widget_class_manual_entries
{
'date_time' => Java::OrgEclipseSwtWidgets::DateTime
}
end
# This supports widgets in and out of basic SWT
def self.swt_widget_class_for(underscored_widget_name)
# TODO clear memoization for a keyword if a custom widget was defined with that keyword
unless flyweight_swt_widget_classes.keys.include?(underscored_widget_name)
begin
underscored_widget_name = KEYWORD_ALIASES[underscored_widget_name] if KEYWORD_ALIASES[underscored_widget_name]
swt_widget_name = underscored_widget_name.camelcase(:upper)
swt_widget_class = eval(swt_widget_name)
# TODO fix issue with not detecting DateTime because it's conflicting with the Ruby DateTime
unless swt_widget_class.ancestors.include?(org.eclipse.swt.widgets.Widget)
swt_widget_class = swt_widget_class_manual_entries[underscored_widget_name]
if swt_widget_class.nil?
Glimmer::Config.logger.debug {"Class #{swt_widget_class} matching #{underscored_widget_name} is not a subclass of org.eclipse.swt.widgets.Widget"}
return nil
end
end
flyweight_swt_widget_classes[underscored_widget_name] = swt_widget_class
rescue SyntaxError, NameError => e
Glimmer::Config.logger.debug {e.full_message}
nil
rescue => e
Glimmer::Config.logger.debug {e.full_message}
nil
end
end
flyweight_swt_widget_classes[underscored_widget_name]
end
# Flyweight Design Pattern memoization cache. Can be cleared if memory is needed.
def self.flyweight_swt_widget_classes
@flyweight_swt_widget_classes ||= {}
end
# delegates to DisplayProxy
def async_exec(&block)
DisplayProxy.instance.async_exec(&block)
end
# delegates to DisplayProxy
def sync_exec(&block)
DisplayProxy.instance.sync_exec(&block)
end
# delegates to DisplayProxy
def timer_exec(delay_in_millis, &block)
DisplayProxy.instance.timer_exec(delay_in_millis, &block)
end
# delegates to DisplayProxy
def auto_exec(override_sync_exec: nil, override_async_exec: nil, &block)
DisplayProxy.instance.auto_exec(override_sync_exec: override_sync_exec, override_async_exec: override_async_exec, &block)
end
def has_style?(style)
comparison = interpret_style(style)
auto_exec do
(@swt_widget.style & comparison) == comparison
end
end
def print(gc=nil, job_name: nil)
if gc.is_a?(org.eclipse.swt.graphics.GC)
@swt_widget.print(gc)
else
image = Image.new(DisplayProxy.instance.swt_display, bounds)
gc = org.eclipse.swt.graphics.GC.new(image)
success = print(gc)
if success
printer_data = DialogProxy.new('print_dialog', shell.get_data('proxy')).open
if printer_data
printer = Printer.new(printer_data)
job_name ||= 'Glimmer'
if printer.start_job(job_name)
printer_gc = org.eclipse.swt.graphics.GC.new(printer)
if printer.start_page
printer_gc.drawImage(image, 0, 0)
printer.end_page
else
success = false
end
printer_gc.dispose
printer.end_job
else
success = false
end
printer.dispose
gc.dispose
image.dispose
end
end
success
end
end
def dispose
auto_exec do
@swt_widget.dispose
end
end
def disposed?
@swt_widget.isDisposed
end
# TODO Consider renaming these methods as they are mainly used for data-binding
def can_add_observer?(property_name)
auto_exec do
@swt_widget.class.ancestors.map {|ancestor| widget_property_listener_installers[ancestor]}.compact.map(&:keys).flatten.map(&:to_s).include?(property_name.to_s)
end
end
# Used for data-binding only. Consider renaming or improving to avoid the confusion it causes
def add_observer(observer, property_name)
if !observer.respond_to?(:binding_options) || !observer.binding_options[:read_only]
auto_exec do
property_listener_installers = @swt_widget.class.ancestors.map {|ancestor| widget_property_listener_installers[ancestor]}.compact
widget_listener_installers = property_listener_installers.map{|installer| installer[property_name.to_s.to_sym]}.compact if !property_listener_installers.empty?
widget_listener_installers.to_a.first&.call(observer)
end
end
end
def remove_observer(observer, property_name)
# TODO consider implementing if remove_observer is needed (consumers can remove listener via SWT API)
end
def ensure_drag_source_proxy(style=[])
@drag_source_proxy ||= self.class.new('drag_source', self, style).tap do |proxy|
proxy.set_attribute(:transfer, :text)
end
end
def ensure_drop_target_proxy(style=[])
@drop_target_proxy ||= WidgetProxy.new('drop_target', self, style).tap do |proxy|
proxy.set_attribute(:transfer, :text)
proxy.on_drag_enter { |event|
event.detail = DNDProxy[:drop_copy]
}
end
end
# TODO eliminate duplication in the following methods perhaps by relying on exceptions
def can_handle_observation_request?(observation_request)
observation_request = normalize_observation_request(observation_request)
if observation_request.start_with?('on_swt_')
constant_name = observation_request.sub(/^on_swt_/, '')
SWTProxy.has_constant?(constant_name)
elsif observation_request.start_with?('on_')
event = observation_request.sub(/^on_/, '')
can_add_listener?(event) || can_handle_drag_observation_request?(observation_request) || can_handle_drop_observation_request?(observation_request)
end
end
def can_handle_drag_observation_request?(observation_request)
auto_exec do
return false unless swt_widget.is_a?(Control)
potential_drag_source = @drag_source_proxy.nil?
ensure_drag_source_proxy
@drag_source_proxy.can_handle_observation_request?(observation_request).tap do |result|
if potential_drag_source && !result
@drag_source_proxy.swt_widget.dispose
@drag_source_proxy = nil
end
end
end
rescue => e
Glimmer::Config.logger.debug {e.full_message}
false
end
def can_handle_drop_observation_request?(observation_request)
auto_exec do
return false unless swt_widget.is_a?(Control)
potential_drop_target = @drop_target_proxy.nil?
ensure_drop_target_proxy
@drop_target_proxy.can_handle_observation_request?(observation_request).tap do |result|
if potential_drop_target && !result
@drop_target_proxy.swt_widget.dispose
@drop_target_proxy = nil
end
end
end
end
def handle_observation_request(observation_request, &block)
observation_request = normalize_observation_request(observation_request)
if observation_request.start_with?('on_drag_enter')
original_block = block
block = Proc.new do |event|
event.detail = DNDProxy[:drop_copy]
original_block.call(event)
end
end
if observation_request.start_with?('on_swt_')
constant_name = observation_request.sub(/^on_swt_/, '')
add_swt_event_listener(constant_name, &block)
elsif observation_request.start_with?('on_')
event = observation_request.sub(/^on_/, '')
if can_add_listener?(event)
event = observation_request.sub(/^on_/, '')
add_listener(event, &block)
elsif can_handle_drag_observation_request?(observation_request)
@drag_source_proxy&.handle_observation_request(observation_request, &block)
elsif can_handle_drop_observation_request?(observation_request)
@drop_target_proxy&.handle_observation_request(observation_request, &block)
end
end
end
def widget_bindings
@widget_bindings ||= []
end
def content(&block)
auto_exec do
Glimmer::DSL::Engine.add_content(self, Glimmer::DSL::SWT::WidgetExpression.new, @keyword, &block)
end
end
def method_missing(method_name, *args, &block)
# TODO push most of this logic down to Properties (and perhaps create Listeners module as well)
if block && can_handle_observation_request?(method_name)
handle_observation_request(method_name, &block)
else
super
end
end
def respond_to?(method_name, *args, &block)
result = super
return true if result
auto_exec do
can_handle_observation_request?(method_name)
end
end
private
def style(underscored_widget_name, styles)
styles = [styles].flatten.compact
styles = default_style(underscored_widget_name) if styles.empty?
interpret_style(*styles)
end
def interpret_style(*styles)
SWTProxy[*styles] rescue DNDProxy[*styles]
end
def default_style(underscored_widget_name)
DEFAULT_STYLES[underscored_widget_name] || [:none]
end
# TODO refactor following methods to eliminate duplication
# perhaps consider relying on raising an exception to avoid checking first
# unless that gives obscure SWT errors
# Otherwise, consider caching results from can_add_lsitener and using them in
# add_listener knowing it will be called for sure afterwards
def can_add_listener?(underscored_listener_name)
auto_exec do
@swt_widget && !self.class.find_listener(@swt_widget.getClass, underscored_listener_name).empty?
end
end
def add_listener(underscored_listener_name, &block)
auto_exec do
widget_add_listener_method, listener_class, listener_method = self.class.find_listener(@swt_widget.getClass, underscored_listener_name)
| ruby | MIT | 449cf07ada1ec965ae2ac91715ccdf22488df4ca | 2026-01-04T17:52:38.125591Z | true |
AndyObtiva/glimmer-dsl-swt | https://github.com/AndyObtiva/glimmer-dsl-swt/blob/449cf07ada1ec965ae2ac91715ccdf22488df4ca/lib/glimmer/swt/tool_bar_proxy.rb | lib/glimmer/swt/tool_bar_proxy.rb | # Copyright (c) 2007-2025 Andy Maleh
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
require 'glimmer/swt/widget_proxy'
module Glimmer
module SWT
# Proxy for org.eclipse.swt.widgets.ToolBarProxy
#
# Follows the Proxy Design Pattern
class ToolBarProxy < WidgetProxy
attr_accessor :cool_item_proxy, :swt_cool_item
def initialize(*init_args, &block)
super
self.cool_item_proxy = WidgetProxy.new("cool_item", parent_proxy, []) if parent_proxy.swt_widget.is_a?(CoolBar)
self.swt_cool_item = cool_item_proxy&.swt_widget
end
def post_add_content
apply_preferred_size if cool_item_proxy
end
def apply_preferred_size
swt_widget.pack
size = swt_widget.size
cool_item_proxy.control = swt_widget
preferred = swt_cool_item.computeSize(size.x, size.y)
swt_cool_item.setPreferredSize(preferred)
end
end
end
end
| ruby | MIT | 449cf07ada1ec965ae2ac91715ccdf22488df4ca | 2026-01-04T17:52:38.125591Z | false |
AndyObtiva/glimmer-dsl-swt | https://github.com/AndyObtiva/glimmer-dsl-swt/blob/449cf07ada1ec965ae2ac91715ccdf22488df4ca/lib/glimmer/swt/dnd_proxy.rb | lib/glimmer/swt/dnd_proxy.rb | # Copyright (c) 2007-2025 Andy Maleh
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
require 'glimmer/swt/style_constantizable'
module Glimmer
module SWT
# Proxy for org.eclipse.swt.dnd.DND
#
# Follows the Proxy Design Pattern
class DNDProxy
include StyleConstantizable
class << self
JAVA_IMPORT = 'org.eclipse.swt.dnd.DND'
java_import JAVA_IMPORT
def constant_java_import
JAVA_IMPORT
end
def constant_source_class
DND
end
def constant_value_none
DND::DROP_NONE
end
end
end
end
end
| ruby | MIT | 449cf07ada1ec965ae2ac91715ccdf22488df4ca | 2026-01-04T17:52:38.125591Z | false |
AndyObtiva/glimmer-dsl-swt | https://github.com/AndyObtiva/glimmer-dsl-swt/blob/449cf07ada1ec965ae2ac91715ccdf22488df4ca/lib/glimmer/swt/expand_item_proxy.rb | lib/glimmer/swt/expand_item_proxy.rb | # Copyright (c) 2007-2025 Andy Maleh
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
require 'glimmer/swt/widget_proxy'
require 'glimmer/swt/swt_proxy'
module Glimmer
module SWT
# Proxy for org.eclipse.swt.widgets.ExpandItem
#
# Functions differently from other widget proxies.
#
# Glimmer instantiates an SWT Composite alongside the SWT ExpandItem
# and returns it for `#swt_widget` to allow adding widgets into it.
#
# In order to get the SWT ExpandItem object, one must call `#swt_expand_item`.
#
# Behind the scenes, this creates a tab item widget proxy separately from a composite that
# is set as the control of the tab item and `#swt_widget`.
#
# In order to retrieve the tab item widget proxy, one must call `#widget_proxy`
#
# Follows the Proxy Design Pattern
class ExpandItemProxy < WidgetProxy
ATTRIBUTES = ['text', 'height', 'expanded']
include_package 'org.eclipse.swt.widgets'
attr_reader :widget_proxy, :swt_expand_item
def initialize(parent, style, &contents)
super("composite", parent, style, &contents)
layout = FillLayout.new(SWTProxy[:vertical])
layout.marginWidth = 0
layout.marginHeight = 0
layout.spacing = 0
swt_widget.layout = layout
auto_exec do
@widget_proxy = SWT::WidgetProxy.new('expand_item', parent, style)
@swt_expand_item = @widget_proxy.swt_widget
@swt_expand_item.control = swt_widget
@swt_expand_item.expanded = true
end
end
def post_add_content
auto_exec do
@swt_expand_item.setHeight(swt_widget.computeSize(SWTProxy[:default], SWTProxy[:default]).y) unless @swt_expand_item.getHeight > 0
end
end
def has_attribute?(attribute_name, *args)
if ATTRIBUTES.include?(attribute_name.to_s)
true
else
super(attribute_name, *args)
end
end
def set_attribute(attribute_name, *args)
if ATTRIBUTES.include?(attribute_name.to_s)
@widget_proxy.set_attribute(attribute_name, *args)
else
super(attribute_name, *args)
end
end
def get_attribute(attribute_name)
if ATTRIBUTES.include?(attribute_name.to_s)
@widget_proxy.get_attribute(attribute_name)
else
super(attribute_name)
end
end
def dispose
auto_exec do
swt_expand_item.setControl(nil)
swt_widget.dispose
swt_expand_item.dispose
end
end
end
end
end
| ruby | MIT | 449cf07ada1ec965ae2ac91715ccdf22488df4ca | 2026-01-04T17:52:38.125591Z | false |
AndyObtiva/glimmer-dsl-swt | https://github.com/AndyObtiva/glimmer-dsl-swt/blob/449cf07ada1ec965ae2ac91715ccdf22488df4ca/lib/glimmer/swt/scrolled_composite_proxy.rb | lib/glimmer/swt/scrolled_composite_proxy.rb | # Copyright (c) 2007-2025 Andy Maleh
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
require 'glimmer/swt/widget_proxy'
require 'glimmer/swt/swt_proxy'
module Glimmer
module SWT
class ScrolledCompositeProxy < Glimmer::SWT::WidgetProxy
def post_initialize_child(child)
auto_exec do
swt_widget.content = child.swt_widget
end
# TODO consider triggering this method in the future upon resizing of content with a listener (on_control_resized)
# child.on_control_resized do
# swt_widget.set_min_size(swt_widget.computeSize(child.bounds.width, child.bounds.height))
# end
end
def post_add_content
calculate_min_size
end
def calculate_min_size
auto_exec do
swt_widget.set_min_size(swt_widget.computeSize(SWTProxy[:default], SWTProxy[:default]))
end
end
alias recalculate_min_size calculate_min_size
end
end
end
| ruby | MIT | 449cf07ada1ec965ae2ac91715ccdf22488df4ca | 2026-01-04T17:52:38.125591Z | false |
AndyObtiva/glimmer-dsl-swt | https://github.com/AndyObtiva/glimmer-dsl-swt/blob/449cf07ada1ec965ae2ac91715ccdf22488df4ca/lib/glimmer/swt/dialog_proxy.rb | lib/glimmer/swt/dialog_proxy.rb | # Copyright (c) 2007-2025 Andy Maleh
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
require 'glimmer/swt/swt_proxy'
require 'glimmer/swt/widget_proxy'
require 'glimmer/swt/display_proxy'
require 'glimmer/swt/proxy_properties'
module Glimmer
module SWT
# Proxy for org.eclipse.swt.widgets.Dialog superclass
# of dialogs like FileDialog, DirectoryDialog, ColorDialog, and FontDialog
#
# (if you're seeking the `dialog` keyword, that's just a `shell` variation
# under ShellProxy instead.
#
# Automatically uses the current shell if one is open.
# Otherwise, it instantiates a new shell parent
#
# Optionally takes a shell as an argument
#
# Follows the Proxy Design Pattern
class DialogProxy
# TODO write rspec tests
include ProxyProperties
include_package 'org.eclipse.swt.widgets'
include_package 'org.eclipse.swt.printing'
class << self
include_package 'org.eclipse.swt.widgets'
include_package 'org.eclipse.swt.printing'
def dialog_class(keyword)
the_class = eval(keyword.camelcase(:upper))
the_class if the_class.ancestors.include?(org.eclipse.swt.widgets.Dialog)
rescue => e
Glimmer::Config.logger.debug {"Dialog for keyword #{keyword} not found!"}
Glimmer::Config.logger.debug { e.full_message }
nil
end
end
attr_reader :swt_dialog
def initialize(keyword, *args, swt_dialog: nil)
DisplayProxy.instance.auto_exec do
dialog_class = self.class.dialog_class(keyword)
if swt_dialog
@swt_dialog = swt_dialog
else
style_args = args.select {|arg| arg.is_a?(Symbol) || arg.is_a?(String)}
if style_args.any?
style_arg_start_index = args.index(style_args.first)
style_arg_last_index = args.index(style_args.last)
args[style_arg_start_index..style_arg_last_index] = SWTProxy[style_args]
end
if args.first.respond_to?(:swt_widget) && args.first.swt_widget.is_a?(Shell)
args[0] = args[0].swt_widget
end
if !args.first.is_a?(Shell)
current_shell = DisplayProxy.instance.swt_display.shells.first
args.unshift(current_shell.nil? ? ShellProxy.new : current_shell)
end
parent = args[0]
@parent_proxy = parent.is_a?(Shell) ? ShellProxy.new(swt_widget: parent) : parent
@swt_dialog = dialog_class.new(*args)
end
end
end
def proxy_source_object
@swt_dialog
end
end
end
end
| ruby | MIT | 449cf07ada1ec965ae2ac91715ccdf22488df4ca | 2026-01-04T17:52:38.125591Z | false |
AndyObtiva/glimmer-dsl-swt | https://github.com/AndyObtiva/glimmer-dsl-swt/blob/449cf07ada1ec965ae2ac91715ccdf22488df4ca/lib/glimmer/swt/styled_text_proxy.rb | lib/glimmer/swt/styled_text_proxy.rb | # Copyright (c) 2007-2025 Andy Maleh
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
require 'glimmer/swt/widget_proxy'
module Glimmer
module SWT
# Proxy for org.eclipse.swt.custom.StyledText
#
# Follows the Proxy Design Pattern
class StyledTextProxy < WidgetProxy
def initialize(*args)
super
on_modify_text { |event|
@last_modify_text = text
}
end
end
end
end
| ruby | MIT | 449cf07ada1ec965ae2ac91715ccdf22488df4ca | 2026-01-04T17:52:38.125591Z | false |
AndyObtiva/glimmer-dsl-swt | https://github.com/AndyObtiva/glimmer-dsl-swt/blob/449cf07ada1ec965ae2ac91715ccdf22488df4ca/lib/glimmer/swt/proxy_properties.rb | lib/glimmer/swt/proxy_properties.rb | # Copyright (c) 2007-2025 Andy Maleh
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
require 'glimmer/swt/properties'
module Glimmer
module SWT
# Provides a default implementation for proxy properties, that is
# properties that come from a proxy object source such as swt_widget
# having Java camelcase format
module ProxyProperties
include Properties
# Subclasses must override to privde a proxy source if they want to take advantage of
# default implementation of attribute setters/getters
# It tries swt_widget, swt_display, swt_image, and swt_dialog by default.
def proxy_source_object
# TODO the logic here should not be needed if derived with polymorphism. Consider removing.
if respond_to?(:swt_widget)
swt_widget
elsif respond_to?(:swt_display)
swt_display
elsif respond_to?(:swt_image)
swt_image
elsif respond_to?(:swt_dialog)
swt_dialog
elsif respond_to?(:swt_transform)
swt_transform
end
end
def has_attribute_getter?(attribute_getter_name, *args)
attribute_getter_name = attribute_getter_name.to_s.underscore
return false unless !attribute_getter_name.end_with?('=') && !attribute_getter_name.start_with?('set_')
args.empty? && proxy_source_object&.respond_to?(attribute_getter_name)
end
def has_attribute_setter?(attribute_setter_name, *args)
attribute_setter_name = attribute_setter_name.to_s
underscored_attribute_setter_name = attribute_setter_name.underscore
return false unless attribute_setter_name.end_with?('=') || (attribute_setter_name.start_with?('set_') && !args.empty?)
attribute_name = underscored_attribute_setter_name.sub(/^set_/, '').sub(/=$/, '')
has_attribute?(attribute_name, *args)
end
def has_attribute?(attribute_name, *args)
Glimmer::SWT::DisplayProxy.instance.auto_exec do
proxy_source_object&.respond_to?(attribute_setter(attribute_name), args) or
respond_to?(ruby_attribute_setter(attribute_name), args)
end
end
def set_attribute(attribute_name, *args)
swt_widget_operation = false
result = nil
Glimmer::SWT::DisplayProxy.instance.auto_exec do
result = if proxy_source_object&.respond_to?(attribute_setter(attribute_name))
swt_widget_operation = true
proxy_source_object&.send(attribute_setter(attribute_name), *args) unless (proxy_source_object&.respond_to?(attribute_getter(attribute_name)) && proxy_source_object&.send(attribute_getter(attribute_name))) == args.first
elsif proxy_source_object&.respond_to?(ruby_attribute_setter(attribute_name))
swt_widget_operation = true
proxy_source_object&.send(ruby_attribute_setter(attribute_name), args)
end
end
unless swt_widget_operation
result = send(ruby_attribute_setter(attribute_name), args) if respond_to?(ruby_attribute_setter(attribute_name), args)
end
result
end
def get_attribute(attribute_name)
swt_widget_operation = false
result = nil
Glimmer::SWT::DisplayProxy.instance.auto_exec do
result = if proxy_source_object&.respond_to?(attribute_getter(attribute_name))
swt_widget_operation = true
proxy_source_object&.send(attribute_getter(attribute_name))
elsif proxy_source_object&.respond_to?(ruby_attribute_getter(attribute_name))
swt_widget_operation = true
proxy_source_object&.send(ruby_attribute_getter(attribute_name))
elsif proxy_source_object&.respond_to?(attribute_name)
swt_widget_operation = true
proxy_source_object&.send(attribute_name)
end
end
unless swt_widget_operation
if respond_to?(ruby_attribute_getter(attribute_name))
result = send(ruby_attribute_getter(attribute_name))
elsif respond_to?(attribute_name)
result = send(attribute_name)
end
end
result
end
def method_missing(method, *args, &block)
if has_attribute_setter?(method, *args)
set_attribute(method, *args)
elsif has_attribute_getter?(method, *args)
get_attribute(method, *args)
else
Glimmer::SWT::DisplayProxy.instance.auto_exec do
proxy_source_object&.send(method, *args, &block)
end
end
rescue => e
begin
super
rescue Exception => inner_error
Glimmer::Config.logger.error { "Neither self.class.name nor #{proxy_source_object&.class.name} can handle the method ##{method}" }
Glimmer::Config.logger.error { e.full_message }
raise inner_error
end
end
def respond_to?(method, *args, &block)
result = super
return true if result
Glimmer::SWT::DisplayProxy.instance.auto_exec do
proxy_source_object&.respond_to?(method, *args, &block)
end
end
end
end
end
| ruby | MIT | 449cf07ada1ec965ae2ac91715ccdf22488df4ca | 2026-01-04T17:52:38.125591Z | false |
AndyObtiva/glimmer-dsl-swt | https://github.com/AndyObtiva/glimmer-dsl-swt/blob/449cf07ada1ec965ae2ac91715ccdf22488df4ca/lib/glimmer/swt/tray_item_proxy.rb | lib/glimmer/swt/tray_item_proxy.rb | # Copyright (c) 2007-2025 Andy Maleh
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
require 'glimmer/swt/swt_proxy'
require 'glimmer/swt/widget_proxy'
require 'glimmer/swt/tray_proxy'
module Glimmer
module SWT
# Proxy for org.eclipse.swt.widgets.TrayItem
#
# Invoking `#swt_widget` returns the SWT TrayItem object wrapped by this proxy
#
# Follows the Proxy Design Pattern and Flyweight Design Pattern (caching memoization)
class TrayItemProxy < Glimmer::SWT::WidgetProxy
attr_reader :tray_proxy, :shell_proxy
attr_accessor :menu_proxy
def initialize(shell_proxy, *args)
@shell_proxy = shell_proxy
@tray_proxy = Glimmer::SWT::TrayProxy.instance
super('tray_item', @tray_proxy, args)
end
end
end
end
| ruby | MIT | 449cf07ada1ec965ae2ac91715ccdf22488df4ca | 2026-01-04T17:52:38.125591Z | false |
AndyObtiva/glimmer-dsl-swt | https://github.com/AndyObtiva/glimmer-dsl-swt/blob/449cf07ada1ec965ae2ac91715ccdf22488df4ca/lib/glimmer/swt/transform_proxy.rb | lib/glimmer/swt/transform_proxy.rb | # Copyright (c) 2007-2025 Andy Maleh
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
require 'glimmer/swt/display_proxy'
require 'glimmer/swt/proxy_properties'
require 'glimmer/swt/custom/shape'
module Glimmer
module SWT
# Proxy for org.eclipse.swt.graphics.Transform
#
# Follows the Proxy Design Pattern
class TransformProxy
include ProxyProperties
include_package 'org.eclipse.swt.graphics'
include_package 'org.eclipse.swt.widgets'
ATTRIBUTE_ALIASES = {
'rotation' => 'rotate',
'translation' => 'translate',
'inversion' => 'invert',
}
attr_reader :swt_transform, :parent
def initialize(parent, *args, swt_transform: nil, multiply: false)
Glimmer::SWT::DisplayProxy.instance.auto_exec do
@parent = parent
@multiply = multiply
if swt_transform.nil?
if !args.first.is_a?(Display) && !args.first.is_a?(DisplayProxy)
args.prepend DisplayProxy.instance.swt_display
end
if args.first.is_a?(DisplayProxy)
args[0] = args[0].swt_display
end
if args.last.is_a?(TransformProxy)
args[-1] = args[-1].swt_transform
end
if args.last.nil? || args.last.is_a?(Transform)
@swt_transform = args.last
@parent&.set_attribute('transform', self)
else
@swt_transform = Transform.new(*args)
end
else
@swt_transform = swt_transform
end
end
end
def post_add_content
if @multiply
Glimmer::SWT::DisplayProxy.instance.auto_exec {
@parent.multiply(@swt_transform)
}
else
@parent&.set_attribute('transform', self)
end
end
def content(&block)
Glimmer::DSL::Engine.add_content(self, Glimmer::DSL::SWT::TransformExpression.new, 'transform', &block)
end
def proxy_source_object
@swt_transform
end
def has_attribute?(attribute_name, *args)
ATTRIBUTE_ALIASES.keys.include?(attribute_name.to_s) || Glimmer::SWT::DisplayProxy.instance.auto_exec { @swt_transform.respond_to?(attribute_name) } || super
end
def set_attribute(attribute_name, *args)
attribute_name = ATTRIBUTE_ALIASES[attribute_name.to_s] || attribute_name
if @swt_transform.respond_to?(attribute_name)
Glimmer::SWT::DisplayProxy.instance.auto_exec { @swt_transform.send(attribute_name, *args) }
else
super
end
end
def get_attribute(attribute_name)
attribute_name = ATTRIBUTE_ALIASES[attribute_name.to_s] || attribute_name
super(attribute_name)
end
def method_missing(method_name, *args, &block)
result = Glimmer::SWT::DisplayProxy.instance.auto_exec { @swt_transform.send(method_name, *args, &block) }
result.nil? ? self : result
rescue => e
begin
super
rescue Exception => inner_e
Glimmer::Config.logger.error {"Neither TransformProxy nor #{@swt_transform.class.name} can handle the method ##{method_name}"}
Glimmer::Config.logger.error {e.full_message}
end
end
def respond_to?(method_name, *args, &block)
super ||
@swt_transform.respond_to?(method_name, *args, &block)
end
end
end
end
| ruby | MIT | 449cf07ada1ec965ae2ac91715ccdf22488df4ca | 2026-01-04T17:52:38.125591Z | false |
AndyObtiva/glimmer-dsl-swt | https://github.com/AndyObtiva/glimmer-dsl-swt/blob/449cf07ada1ec965ae2ac91715ccdf22488df4ca/lib/glimmer/swt/combo_proxy.rb | lib/glimmer/swt/combo_proxy.rb | # Copyright (c) 2007-2025 Andy Maleh
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
require 'glimmer/swt/widget_proxy'
module Glimmer
module SWT
# Proxy for org.eclipse.swt.widgets.Combo
#
# Follows the Proxy Design Pattern
class ComboProxy < WidgetProxy
attr_accessor :tool_item_proxy, :swt_tool_item
def initialize(*init_args, &block)
super
self.tool_item_proxy = WidgetProxy.new("tool_item", parent_proxy, [:separator]) if parent_proxy.swt_widget.is_a?(ToolBar)
self.swt_tool_item = tool_item_proxy&.swt_widget
end
def post_add_content
if self.tool_item_proxy
self.swt_widget.pack
self.tool_item_proxy.text = 'filler' # text seems needed (any text works)
self.tool_item_proxy.width = swt_widget.size.x
self.tool_item_proxy.control = swt_widget
end
end
end
end
end
| ruby | MIT | 449cf07ada1ec965ae2ac91715ccdf22488df4ca | 2026-01-04T17:52:38.125591Z | false |
AndyObtiva/glimmer-dsl-swt | https://github.com/AndyObtiva/glimmer-dsl-swt/blob/449cf07ada1ec965ae2ac91715ccdf22488df4ca/lib/glimmer/swt/cursor_proxy.rb | lib/glimmer/swt/cursor_proxy.rb | # Copyright (c) 2007-2025 Andy Maleh
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
require 'glimmer/error'
require 'glimmer/swt/swt_proxy'
require 'glimmer/swt/display_proxy'
module Glimmer
module SWT
# Proxy for org.eclipse.swt.graphics.Cursor
#
# Invoking `#swt_cursor` returns the SWT Cursor object wrapped by this proxy
#
# Follows the Proxy Design Pattern
class CursorProxy
CURSOR_STYLES = org.eclipse.swt.SWT.constants.select {|c| c.to_s.downcase.start_with?('cursor_')}.map {|c| c.to_s.downcase.sub('cursor_', '').to_sym}
ERROR_INVALID_CURSOR_STYLE = " is an invalid cursor style! Valid values are #{CURSOR_STYLES.map(&:to_s).join(", ")}"
include_package 'org.eclipse.swt.graphics'
attr_reader :swt_cursor, :cursor_style
# Builds a new CursorProxy from passed in cursor SWT style (e.g. :appstarting, :hand, or :help)
#
# Cursor SWT styles are those that begin with "CURSOR_" prefix
#
# They are expected to be passed in in short form without the prefix (but would work with the prefix too)
def initialize(cursor_style)
@cursor_style = cursor_style
@cursor_style = SWTProxy.reverse_lookup(@cursor_style).detect { |symbol| symbol.to_s.downcase.start_with?('cursor_') } if cursor_style.is_a?(Integer)
@cursor_style = @cursor_style.to_s.downcase
@cursor_style = @cursor_style.sub(/^cursor\_/, '') if @cursor_style.start_with?('cursor_')
detect_invalid_cursor_style
@swt_cursor = DisplayProxy.instance.swt_display.get_system_cursor(SWTProxy[swt_style])
end
def swt_style
@swt_style ||= @cursor_style.upcase.start_with?('CURSOR_') ? @cursor_style : "CURSOR_#{@cursor_style}"
end
private
def detect_invalid_cursor_style
raise Error, cursor_style.to_s + ERROR_INVALID_CURSOR_STYLE unless CURSOR_STYLES.include?(cursor_style.to_s.downcase.to_sym)
end
end
end
end
| ruby | MIT | 449cf07ada1ec965ae2ac91715ccdf22488df4ca | 2026-01-04T17:52:38.125591Z | false |
AndyObtiva/glimmer-dsl-swt | https://github.com/AndyObtiva/glimmer-dsl-swt/blob/449cf07ada1ec965ae2ac91715ccdf22488df4ca/lib/glimmer/swt/color_proxy.rb | lib/glimmer/swt/color_proxy.rb | # Copyright (c) 2007-2025 Andy Maleh
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
require 'glimmer/swt/swt_proxy'
require 'glimmer/swt/display_proxy'
module Glimmer
module SWT
# Proxy for org.eclipse.swt.graphics.Color
#
# Invoking `#swt_color` returns the SWT Color object wrapped by this proxy
#
# Follows the Proxy Design Pattern and Flyweight Design Pattern (caching memoization)
class ColorProxy
include_package 'org.eclipse.swt.graphics'
class << self
def create(*args)
flyweight_color_proxies[args] ||= new(*args)
end
# Flyweight Design Pattern memoization cache. Can be cleared if memory is needed.
def flyweight_color_proxies
@flyweight_color_proxies ||= {}
end
end
# Initializes a proxy for an SWT Color object
#
# Takes a standard color single argument, rgba 3 args, or rgba 4 args
#
# A standard color is a string/symbol representing one of the
# SWT.COLOR_*** constants like SWT.COLOR_RED, but in underscored string
# format (e.g :color_red).
# Glimmer can also accept standard color names without the color_ prefix,
# and it will automatically figure out the SWT.COLOR_*** constant
# (e.g. :red)
#
# rgb is 3 arguments representing Red, Green, Blue numeric values
#
# rgba is 4 arguments representing Red, Green, Blue, and Alpha numeric values
#
def initialize(*args)
@options = args.last.is_a?(Hash) ? args.pop : {}
@args = args
@args = @args.first if @args.first.is_a?(Array)
ensure_arg_values_within_valid_bounds unless @options[:ensure_bounds] == false
end
def swt_color
unless @swt_color
case @args.size
when 1
if @args.first.is_a?(String) || @args.first.is_a?(Symbol)
standard_color = @args.first
standard_color = "color_#{standard_color}".to_sym unless standard_color.to_s.downcase.include?('color_')
@swt_color = DisplayProxy.instance.swt_display.getSystemColor(SWTProxy[standard_color])
else
@swt_color = @args.first
end
when 3..4
@swt_color = Color.new(*@args)
end
end
@swt_color
end
def method_missing(method_name, *args, &block)
swt_color.send(method_name, *args, &block)
rescue => e
Glimmer::Config.logger.debug {"Neither ColorProxy nor #{swt_color.class.name} can handle the method ##{method_name}"}
super
end
def respond_to?(method_name, *args, &block)
super || swt_color.respond_to?(method_name, *args, &block)
end
private
def ensure_arg_values_within_valid_bounds
if @args.to_a.size >= 3
@args = @args.map do |value|
[[value.to_f, 255].min, 0].max
end
end
end
end
end
end
| ruby | MIT | 449cf07ada1ec965ae2ac91715ccdf22488df4ca | 2026-01-04T17:52:38.125591Z | false |
AndyObtiva/glimmer-dsl-swt | https://github.com/AndyObtiva/glimmer-dsl-swt/blob/449cf07ada1ec965ae2ac91715ccdf22488df4ca/lib/glimmer/swt/layout_data_proxy.rb | lib/glimmer/swt/layout_data_proxy.rb | # Copyright (c) 2007-2025 Andy Maleh
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
require 'glimmer'
require 'glimmer/swt/swt_proxy'
module Glimmer
module SWT
# Generic proxy for all SWT layout data objects, such as GridData & RowData
#
# This class is meant to be used with an existing WidgetProxy
# as it figures out the right SWT layout data class name
# by convention from the parent SWT widget layout class name
#
# The convention is:
# - Start with the parent widget layout package/class name (e.g. org.eclipse.swt.layout.RowLayout)
# - Replace the word "Layout" with "Data" in the class name
#
# Examples of figuring out SWT layout data class:
# - org.eclipse.swt.layout.RowData for org.eclipse.swt.layout.RowLayout
# - org.eclipse.swt.layout.GridData for org.eclipse.swt.layout.GridLayout
#
# Follows the Proxy Design Pattern
class LayoutDataProxy
include_package 'org.eclipse.swt.layout'
attr_reader :widget_proxy
attr_reader :swt_layout_data
# Inititalizes with owning widget proxy and layout data arguments
def initialize(widget_proxy, args)
DisplayProxy.instance.auto_exec do
@widget_proxy = widget_proxy
args = SWTProxy.constantify_args(args)
begin
@swt_layout_data = swt_layout_data_class.new(*args)
rescue => e
Glimmer::Config.logger.debug {"#{e.message}\n#{e.backtrace.join("\n")}"}
@swt_layout_data = args.first if args.count == 1
end
@widget_proxy.swt_widget.setLayoutData(@swt_layout_data)
end
end
# This figures out the right SWT layout data class name
# by convention from the parent SWT widget layout class name
#
# Supports layout data classes in and out of basic SWT library
#
# The convention is:
# - Start with the parent widget layout package/class name (e.g. org.eclipse.swt.layout.RowLayout)
# - Replace the word "Layout" with "Data" in the class name
#
# Examples of figuring out SWT layout data class:
# - org.eclipse.swt.layout.RowData for org.eclipse.swt.layout.RowLayout
# - org.eclipse.swt.layout.GridData for org.eclipse.swt.layout.GridLayout
#
def swt_layout_data_class
DisplayProxy.instance.auto_exec do
parent_layout_class_name = @widget_proxy.swt_widget.getParent.getLayout.class.name
layout_data_class_name = parent_layout_class_name.sub(/Layout$/, 'Data')
eval(layout_data_class_name)
end
end
def has_attribute?(attribute_name, *args)
@swt_layout_data.respond_to?(attribute_setter(attribute_name), args)
end
def set_attribute(attribute_name, *args)
DisplayProxy.instance.auto_exec do
args = SWTProxy.constantify_args(args)
if args.first != @swt_layout_data.send(attribute_getter(attribute_name))
@swt_layout_data.send(attribute_setter(attribute_name), *args)
@widget_proxy.swt_widget.getShell.pack
end
end
end
def get_attribute(attribute_name)
@swt_layout_data.send(attribute_getter(attribute_name))
end
def attribute_setter(attribute_name)
"#{attribute_name.to_s.camelcase(:lower)}="
end
def attribute_getter(attribute_name)
"#{attribute_name.to_s.camelcase(:lower)}"
end
def content(&block)
Glimmer::DSL::Engine.add_content(self, Glimmer::DSL::SWT::LayoutDataExpression.new, 'layout_data', &block)
end
end
end
end
| ruby | MIT | 449cf07ada1ec965ae2ac91715ccdf22488df4ca | 2026-01-04T17:52:38.125591Z | false |
AndyObtiva/glimmer-dsl-swt | https://github.com/AndyObtiva/glimmer-dsl-swt/blob/449cf07ada1ec965ae2ac91715ccdf22488df4ca/lib/glimmer/swt/display_proxy.rb | lib/glimmer/swt/display_proxy.rb | # Copyright (c) 2007-2025 Andy Maleh
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
require 'glimmer/swt/widget_listener_proxy'
require 'glimmer/swt/custom/drawable'
module Glimmer
module SWT
# Proxy for org.eclipse.swt.widgets.Display
#
# Maintains a singleton instance since SWT only supports
# a single active display at a time.
#
# Supports SWT Display's very useful asyncExec and syncExec methods
# to support proper multi-threaded manipulation of SWT UI objects
#
# Invoking `#swt_display` returns the SWT Display object wrapped by this proxy
#
# Follows the Proxy Design Pattern
class DisplayProxy
include_package 'org.eclipse.swt.widgets'
include Custom::Drawable
OBSERVED_MENU_ITEMS = ['about', 'preferences', 'quit']
class ConcreteListener
include org.eclipse.swt.widgets.Listener
def initialize(&listener_block)
@listener_block = listener_block
end
def handleEvent(event)
@listener_block.call(event)
end
end
class << self
# Returns singleton instance
def instance(*args)
if @instance.nil? || @instance.swt_display.nil? || @instance.swt_display.isDisposed
@thread = Thread.current
@instance = new(*args)
end
@instance
end
def thread
instance # ensure instance
@thread
end
# Current custom widgets, shells, and shapes being rendered. Useful to yoke all observers evaluated during rendering of their custom widgets/shells/shapes for automatical disposal on_widget_disposed/on_shape_disposed
def current_custom_widgets_and_shapes
@current_custom_widgets_and_shapes ||= []
end
end
# SWT Display object wrapped
attr_reader :swt_display
def initialize(*args)
Display.app_name ||= 'Glimmer'
@swt_display = Display.new(*args)
@swt_display.set_data('proxy', self)
@execs_in_progress = {}
on_swt_Dispose {
clear_shapes
}
end
def content(&block)
Glimmer::DSL::Engine.add_content(self, Glimmer::DSL::SWT::DisplayExpression.new, 'display', &block)
end
# asynchronously executes the block (required from threads other than first GUI thread)
# does not return the value produced by the block since it is async, running after the return
def async_exec(&block)
@swt_display.asyncExec do
execs_in_progress << :async_exec
begin
result = block.call
ensure
execs_in_progress.pop
end
end
end
# synchronously executes the block (required from threads other than first GUI thread)
# returns the value produced by the block
def sync_exec(&block)
result = nil
@swt_display.syncExec do
execs_in_progress << :sync_exec
begin
result = block.call
ensure
execs_in_progress.pop
end
end
result
end
def timer_exec(delay_in_millis, &block)
@swt_display.timerExec(delay_in_millis, &block)
end
# Indicates whether `sync_exec` is required because of running in a different thread from the GUI thread
# `async_exec` could be used as an alternative to `sync_exec` when required.
def sync_exec_required?
Thread.current != DisplayProxy.thread
end
def async_exec_in_progress?
execs_in_progress.last == :async_exec
end
def sync_exec_in_progress?
execs_in_progress.include?(:sync_exec)
end
def execs_in_progress
@execs_in_progress[Thread.current] ||= []
end
# Invoke block with `sync_exec` only when necessary (running from a separate thread)
# Override sync_exec as `true` to force using or `false` to force avoiding
# Override async_exec as `true` to force using or `:unless_in_progress` to force using only if no `async_exec` is in progress
# Disable auto execution of `sync_exec` via `Glimmer::Config.auto_sync_exec = false`
# Otherwise, runs normally, thus allowing SWT to decide how to batch/optimize GUI updates
def auto_exec(override_sync_exec: nil, override_async_exec: nil, &block)
if override_sync_exec || override_sync_exec.nil? && !override_async_exec && sync_exec_required? && Config.auto_sync_exec? && !sync_exec_in_progress? && !async_exec_in_progress?
sync_exec(&block)
elsif override_async_exec || override_async_exec.to_s == 'unless_in_progress' && !async_exec_in_progress?
async_exec(&block)
else
block.call
end
end
def on_widget_disposed(&block)
on_swt_Dispose(&block)
end
def disposed?
@swt_display.isDisposed
end
def method_missing(method_name, *args, &block)
if block && can_handle_observation_request?(method_name)
handle_observation_request(method_name, &block)
else
swt_display.send(method_name, *args, &block)
end
rescue => e
Glimmer::Config.logger.debug {"Neither DisplayProxy nor #{swt_display.class.name} can handle the method ##{method_name}"}
super
end
def respond_to?(method_name, *args, &block)
super ||
can_handle_observation_request?(method_name) ||
swt_display.respond_to?(method_name, *args, &block)
end
def can_handle_observation_request?(observation_request)
observation_request = observation_request.to_s
if observation_request.start_with?('on_swt_')
constant_name = observation_request.sub(/^on_swt_/, '')
SWTProxy.has_constant?(constant_name)
elsif observation_request.start_with?('on_')
event_name = observation_request.sub(/^on_/, '')
OBSERVED_MENU_ITEMS.include?(event_name)
else
false
end
end
def handle_observation_request(observation_request, &block)
observation_request = observation_request.to_s
if observation_request.start_with?('on_swt_')
constant_name = observation_request.sub(/^on_swt_/, '')
swt_event_reg = add_swt_event_filter(constant_name, &block)
DisplayProxy.current_custom_widgets_and_shapes.last&.observer_registrations&.push(swt_event_reg)
swt_event_reg
elsif observation_request.start_with?('on_')
event_name = observation_request.sub(/^on_/, '')
if OBSERVED_MENU_ITEMS.include?(event_name) && OS.mac?
auto_exec do
system_menu = swt_display.getSystemMenu
menu_item = system_menu.getItems.find {|menu_item| menu_item.getID == SWTProxy["ID_#{event_name.upcase}"]}
listener = ConcreteListener.new(&block)
display_mac_event_registration = menu_item.addListener(SWTProxy[:Selection], listener)
DisplayProxy.current_custom_widgets_and_shapes.last&.observer_registrations&.push(display_mac_event_registration)
display_mac_event_registration
end
end
end
end
def add_swt_event_filter(swt_constant, &block)
event_type = SWTProxy[swt_constant]
swt_listener = ConcreteListener.new(&block)
@swt_display.addFilter(event_type, swt_listener)
#WidgetListenerProxy.new(@swt_display.getListeners(event_type).last)
WidgetListenerProxy.new(
swt_display: @swt_display,
event_type: event_type,
filter: true,
swt_listener: swt_listener,
widget_add_listener_method: 'addFilter',
swt_listener_class: ConcreteListener,
swt_listener_method: 'handleEvent'
)
end
end
end
end
| ruby | MIT | 449cf07ada1ec965ae2ac91715ccdf22488df4ca | 2026-01-04T17:52:38.125591Z | false |
AndyObtiva/glimmer-dsl-swt | https://github.com/AndyObtiva/glimmer-dsl-swt/blob/449cf07ada1ec965ae2ac91715ccdf22488df4ca/lib/glimmer/swt/c_tab_item_proxy.rb | lib/glimmer/swt/c_tab_item_proxy.rb | # Copyright (c) 2007-2025 Andy Maleh
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
require 'glimmer/swt/widget_proxy'
require 'glimmer/swt/tab_item_proxy'
module Glimmer
module SWT
# Proxy for org.eclipse.swt.custom.CTabItem
#
# Functions differently from other widget proxies.
#
# Glimmer instantiates an SWT Composite alongside the SWT TabItem
# and returns it for `#swt_widget` to allow adding widgets into it.
#
# In order to get the SWT TabItem object, one must call `#swt_tab_item`.
#
# Behind the scenes, this creates a tab item widget proxy separately from a composite that
# is set as the control of the tab item and `#swt_widget`.
#
# In order to retrieve the tab item widget proxy, one must call `#widget_proxy`
#
# Follows the Proxy Design Pattern
class CTabItemProxy < TabItemProxy
ATTRIBUTES = TabItemProxy::ATTRIBUTES + %w[foreground selection_foreground show_close font]
def attributes
ATTRIBUTES
end
end
end
end
| ruby | MIT | 449cf07ada1ec965ae2ac91715ccdf22488df4ca | 2026-01-04T17:52:38.125591Z | false |
AndyObtiva/glimmer-dsl-swt | https://github.com/AndyObtiva/glimmer-dsl-swt/blob/449cf07ada1ec965ae2ac91715ccdf22488df4ca/lib/glimmer/swt/widget_listener_proxy.rb | lib/glimmer/swt/widget_listener_proxy.rb | # Copyright (c) 2007-2025 Andy Maleh
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
module Glimmer
module SWT
# Proxy for widget listeners
#
# Follows the Proxy Design Pattern
class WidgetListenerProxy
attr_reader :swt_widget, :swt_display, :swt_listener, :widget_add_listener_method, :swt_listener_class, :swt_listener_method, :event_type, :swt_constant
def initialize(swt_widget:nil, swt_display:nil, swt_listener:, widget_add_listener_method: nil, swt_listener_class: nil, swt_listener_method: nil, event_type: nil, swt_constant: nil, filter: false)
@swt_widget = swt_widget
@swt_display = swt_display
@filter = filter
@swt_listener = swt_listener
@widget_add_listener_method = widget_add_listener_method
@swt_listener_class = swt_listener_class
@swt_listener_method = swt_listener_method
@event_type = event_type
@swt_constant = swt_constant
end
def widget_remove_listener_method
@widget_add_listener_method.sub('add', 'remove')
end
def deregister
return if @swt_widget&.is_disposed || @swt_display&.is_disposed
if @swt_display
if @filter
@swt_display.removeFilter(@event_type, @swt_listener)
else
@swt_display.removeListener(@event_type, @swt_listener)
end
elsif @event_type
DisplayProxy.instance.auto_exec do
@swt_widget.removeListener(@event_type, @swt_listener)
end
else
DisplayProxy.instance.auto_exec do
@swt_widget.send(widget_remove_listener_method, @swt_listener)
end
end
end
alias unregister deregister # TODO consider dropping unregister (and in Observer too)
end
end
end
| ruby | MIT | 449cf07ada1ec965ae2ac91715ccdf22488df4ca | 2026-01-04T17:52:38.125591Z | false |
AndyObtiva/glimmer-dsl-swt | https://github.com/AndyObtiva/glimmer-dsl-swt/blob/449cf07ada1ec965ae2ac91715ccdf22488df4ca/lib/glimmer/swt/swt_proxy.rb | lib/glimmer/swt/swt_proxy.rb | # Copyright (c) 2007-2025 Andy Maleh
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
require 'glimmer/swt/style_constantizable'
module Glimmer
module SWT
# Proxy for org.eclipse.swt.SWT
#
# Follows the Proxy Design Pattern
class SWTProxy
include StyleConstantizable
class << self
JAVA_IMPORT = 'org.eclipse.swt.SWT'
java_import JAVA_IMPORT
def constant_java_import
JAVA_IMPORT
end
def constant_source_class
SWT
end
def constant_value_none
SWT::NONE
end
def extra_styles
EXTRA_STYLES
end
def cursor_styles
SWT.constants.select {|c| c.to_s.start_with?('CURSOR_')}
end
def color_styles
SWT.constants.select {|c| c.to_s.start_with?('COLOR_')}
end
def cursor_options
cursor_styles.map {|c| c.to_s.sub('CURSOR_', '').downcase}.map(&:to_sym)
end
def color_options
color_styles.map {|c| c.to_s.sub('COLOR_', '').downcase}.map(&:to_sym)
end
end
EXTRA_STYLES = {
NO_RESIZE: self[:shell_trim, :resize!, :max!],
WINDOW_TRIM: self[:shell_trim],
}
end
end
end
| ruby | MIT | 449cf07ada1ec965ae2ac91715ccdf22488df4ca | 2026-01-04T17:52:38.125591Z | false |
AndyObtiva/glimmer-dsl-swt | https://github.com/AndyObtiva/glimmer-dsl-swt/blob/449cf07ada1ec965ae2ac91715ccdf22488df4ca/lib/glimmer/swt/properties.rb | lib/glimmer/swt/properties.rb | # Copyright (c) 2007-2025 Andy Maleh
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
module Glimmer
module SWT
module Properties
class << self
def ruby_attribute_setter(attribute_name)
@ruby_attribute_setters ||= {}
@ruby_attribute_setters[attribute_name] ||= "#{normalized_attribute(attribute_name)}="
end
def attribute_setter(attribute_name)
@attribute_setters ||= {}
@attribute_setters[attribute_name] ||= "set#{normalized_attribute(attribute_name).camelcase(:upper)}"
end
def attribute_getter(attribute_name)
@attribute_getters ||= {}
@attribute_getters[attribute_name] ||= "get#{normalized_attribute(attribute_name).camelcase(:upper)}"
end
def normalized_attribute(attribute_name)
@normalized_attributes ||= {}
if @normalized_attributes[attribute_name].nil?
attribute_name = attribute_name.to_s if attribute_name.is_a?(Symbol)
attribute_name = attribute_name.underscore unless attribute_name.downcase?
attribute_name = attribute_name.sub(/^get_/, '') if attribute_name.start_with?('get_')
attribute_name = attribute_name.sub(/^set_/, '') if attribute_name.start_with?('set_')
attribute_name = attribute_name.sub(/=$/, '') if attribute_name.end_with?('=')
@normalized_attributes[attribute_name] = attribute_name
end
@normalized_attributes[attribute_name]
end
alias ruby_attribute_getter normalized_attribute
end
def ruby_attribute_setter(attribute_name)
Glimmer::SWT::Properties.ruby_attribute_setter(attribute_name)
end
def attribute_setter(attribute_name)
Glimmer::SWT::Properties.attribute_setter(attribute_name)
end
def attribute_getter(attribute_name)
Glimmer::SWT::Properties.attribute_getter(attribute_name)
end
def normalized_attribute(attribute_name)
Glimmer::SWT::Properties.normalized_attribute(attribute_name)
end
alias ruby_attribute_getter normalized_attribute
end
end
end
| ruby | MIT | 449cf07ada1ec965ae2ac91715ccdf22488df4ca | 2026-01-04T17:52:38.125591Z | false |
AndyObtiva/glimmer-dsl-swt | https://github.com/AndyObtiva/glimmer-dsl-swt/blob/449cf07ada1ec965ae2ac91715ccdf22488df4ca/lib/glimmer/swt/date_time_proxy.rb | lib/glimmer/swt/date_time_proxy.rb | # Copyright (c) 2007-2025 Andy Maleh
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
require 'date'
require 'glimmer/swt/widget_proxy'
module Glimmer
module SWT
# Proxy for org.eclipse.swt.widgets.DateTime
#
# Follows the Proxy Design Pattern
class DateTimeProxy < WidgetProxy
CUSTOM_ATTRIBUTES = %w[date_time date time month]
def date_time
DateTime.new(year, month, day, hours, minutes, seconds)
end
def date_time=(date_time_value)
self.time = date_time_value.to_time
end
def date
date_time.to_date
end
def date=(date_value)
auto_exec do
swt_widget.setDate(date_value.year, date_value.month - 1, date_value.day)
end
end
def time
date_time.to_time
end
def time=(time_value)
self.date = time_value.to_date
self.hours = time_value.hour
self.minutes = time_value.min
self.seconds = time_value.sec
end
def month
auto_exec do
swt_widget.month + 1
end
end
def month=(new_value)
auto_exec do
swt_widget.month = new_value - 1
end
end
def set_attribute(attribute_name, *args)
if CUSTOM_ATTRIBUTES.include?(attribute_name.to_s)
send(ruby_attribute_setter(attribute_name), args.first)
else
super(attribute_name, *args)
end
end
def get_attribute(attribute_name)
if CUSTOM_ATTRIBUTES.include?(attribute_name.to_s)
send(attribute_name)
else
super(attribute_name)
end
end
end
end
end
| ruby | MIT | 449cf07ada1ec965ae2ac91715ccdf22488df4ca | 2026-01-04T17:52:38.125591Z | false |
AndyObtiva/glimmer-dsl-swt | https://github.com/AndyObtiva/glimmer-dsl-swt/blob/449cf07ada1ec965ae2ac91715ccdf22488df4ca/lib/glimmer/swt/layout_proxy.rb | lib/glimmer/swt/layout_proxy.rb | # Copyright (c) 2007-2025 Andy Maleh
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
require 'glimmer'
require 'glimmer/swt/swt_proxy'
module Glimmer
module SWT
# Proxy for org.eclipse.swt.widgets.Layout
#
# This is meant to be used with a WidgetProxy where it will
# set the layout in the SWT widget upon instantiation.
#
# Follows the Proxy Design Pattern
class LayoutProxy
attr_reader :widget_proxy, :swt_layout
class << self
include_package 'org.eclipse.swt.layout'
include_package 'org.eclipse.swt.widgets'
def layout_exists?(underscored_layout_name)
begin
swt_layout_class_for(underscored_layout_name)
true
rescue NameError => e
false
end
end
# This supports layouts in and out of basic SWT library
def swt_layout_class_for(underscored_layout_name)
swt_layout_name = underscored_layout_name.camelcase(:upper)
swt_layout_class = eval(swt_layout_name)
unless swt_layout_class.ancestors.include?(Layout)
raise NameError, "Class #{swt_layout_class} matching #{underscored_layout_name} is not a subclass of org.eclipse.swt.widgets.Layout"
end
swt_layout_class
rescue => e
Glimmer::Config.logger.debug {e.message}
# Glimmer::Config.logger.debug {"#{e.message}\n#{e.backtrace.join("\n")}"}
raise e
end
end
def initialize(underscored_layout_name, widget_proxy, args)
DisplayProxy.instance.auto_exec do
@underscored_layout_name = underscored_layout_name
@widget_proxy = widget_proxy
args = SWTProxy.constantify_args(args)
@swt_layout = self.class.swt_layout_class_for(underscored_layout_name).new(*args)
@swt_layout.marginWidth = 15 if @swt_layout.respond_to?(:marginWidth)
@swt_layout.marginHeight = 15 if @swt_layout.respond_to?(:marginHeight)
@swt_layout.marginTop = 0 if @swt_layout.respond_to?(:marginTop)
@swt_layout.marginRight = 0 if @swt_layout.respond_to?(:marginRight)
@swt_layout.marginBottom = 0 if @swt_layout.respond_to?(:marginBottom)
@swt_layout.marginLeft = 0 if @swt_layout.respond_to?(:marginLeft)
old_layout = @widget_proxy.swt_widget.getLayout
@widget_proxy.swt_widget.setLayout(@swt_layout)
@widget_proxy.swt_widget.layout if old_layout
end
end
def has_attribute?(attribute_name, *args)
@swt_layout.respond_to?(attribute_setter(attribute_name), args)
end
def set_attribute(attribute_name, *args)
DisplayProxy.instance.auto_exec do
apply_property_type_converters(attribute_name, args)
if args.first != @swt_layout.send(attribute_getter(attribute_name))
@swt_layout.send(attribute_setter(attribute_name), *args)
@widget_proxy.swt_widget.layout
@widget_proxy.swt_widget.getShell.layout
end
end
end
def get_attribute(attribute_name)
@swt_layout.send(attribute_getter(attribute_name))
end
def apply_property_type_converters(attribute_name, args)
if args.count == 1 && SWTProxy.has_constant?(args.first)
args[0] = SWTProxy.constant(args.first)
end
end
def attribute_setter(attribute_name)
"#{attribute_name.to_s.camelcase(:lower)}="
end
def attribute_getter(attribute_name)
"#{attribute_name.to_s.camelcase(:lower)}"
end
end
end
end
| ruby | MIT | 449cf07ada1ec965ae2ac91715ccdf22488df4ca | 2026-01-04T17:52:38.125591Z | false |
AndyObtiva/glimmer-dsl-swt | https://github.com/AndyObtiva/glimmer-dsl-swt/blob/449cf07ada1ec965ae2ac91715ccdf22488df4ca/lib/glimmer/swt/shape_listener_proxy.rb | lib/glimmer/swt/shape_listener_proxy.rb | # Copyright (c) 2007-2025 Andy Maleh
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
module Glimmer
module SWT
# Proxy for widget listeners
#
# Follows the Proxy Design Pattern
class ShapeListenerProxy
attr_reader :shape, :observation_request, :widget_listener_proxy
def initialize(shape: nil, drawable: nil, shape_listener_block: nil, observation_request: nil, widget_listener_proxy: nil)
@shape = shape
@drawable = drawable
@shape_listener_block = shape_listener_block
@observation_request = observation_request
@widget_listener_proxy = widget_listener_proxy
end
# Deregisters shape listener
def deregister
if @observation_request == 'on_drop'
@widget_listener_proxy.deregister
@shape.widget_listener_proxies.delete(@widget_listener_proxy)
@drawable.drop_shapes.delete(shape)
elsif @observation_request == 'on_shape_disposed'
@shape.remove_shape_disposed_listener(@shape_listener_block)
else
@widget_listener_proxy.deregister
@shape.widget_listener_proxies.delete(@widget_listener_proxy)
end
end
alias unregister deregister # TODO consider dropping unregister (and in Observer too)
end
end
end
| ruby | MIT | 449cf07ada1ec965ae2ac91715ccdf22488df4ca | 2026-01-04T17:52:38.125591Z | false |
AndyObtiva/glimmer-dsl-swt | https://github.com/AndyObtiva/glimmer-dsl-swt/blob/449cf07ada1ec965ae2ac91715ccdf22488df4ca/lib/glimmer/swt/tab_folder_proxy.rb | lib/glimmer/swt/tab_folder_proxy.rb | # Copyright (c) 2007-2025 Andy Maleh
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
require 'glimmer/swt/widget_proxy'
module Glimmer
module SWT
# Proxy for org.eclipse.swt.widgets.TabProxy
#
# Follows the Proxy Design Pattern
class TabFolderProxy < WidgetProxy
def initialize(underscored_widget_name, parent, args, swt_widget: nil)
@initialize_tabs_on_select = args.delete(:initialize_tabs_on_select)
super
end
def post_add_content
shown = false
unless @initialize_tabs_on_select
@show_listener = parent_proxy.on_swt_show do
unless shown
shown = true
self.items.to_a.each do |item|
self.selection = item
end
self.selection = self.items.first unless self.items.first.nil?
@show_listener.deregister
end
end
end
end
end
CTabFolderProxy = TabFolderProxy
end
end
| ruby | MIT | 449cf07ada1ec965ae2ac91715ccdf22488df4ca | 2026-01-04T17:52:38.125591Z | false |
AndyObtiva/glimmer-dsl-swt | https://github.com/AndyObtiva/glimmer-dsl-swt/blob/449cf07ada1ec965ae2ac91715ccdf22488df4ca/lib/glimmer/swt/font_proxy.rb | lib/glimmer/swt/font_proxy.rb | # Copyright (c) 2007-2025 Andy Maleh
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
require 'glimmer/error'
require 'glimmer/swt/swt_proxy'
require 'glimmer/swt/display_proxy'
module Glimmer
module SWT
# Proxy for org.eclipse.swt.graphics.Font
#
# This class can be optionally used with WidgetProxy to manipulate
# an SWT widget font (reusing its FontData but building a new Font)
#
# Otherwise, if no WidgetProxy is passed to constructor, it builds new FontData
#
# Invoking `#swt_font` returns the SWT Font object wrapped by this proxy
#
# Follows the Proxy Design Pattern
class FontProxy
class << self
def create(*args)
flyweight_font_proxies[args] ||= new(*args)
end
# Flyweight Design Pattern memoization cache. Can be cleared if memory is needed.
def flyweight_font_proxies
@flyweight_font_proxies ||= {}
end
end
include_package 'org.eclipse.swt.graphics'
ERROR_INVALID_FONT_STYLE = " is an invalid font style! Valid values are :normal, :bold, and :italic"
FONT_STYLES = [:normal, :bold, :italic]
attr_reader :widget_proxy, :swt_font, :font_properties
# Builds a new font proxy from passed in widget_proxy and font_properties hash,
#
# It begins with existing SWT widget font and amends it with font properties.
#
# Font properties consist of: :name, :height, and :style (one needed minimum)
#
# Style (:style value) can only be one of FontProxy::FONT_STYLES values:
# that is :normal, :bold, or :italic
def initialize(widget_proxy = nil, font_properties)
@widget_proxy = widget_proxy
if font_properties.is_a?(FontData)
font_datum = font_properties
@font_properties = {name: font_properties.name, height: font_properties.height, style: font_properties.style}
elsif font_properties.is_a?(Hash)
@font_properties = font_properties
detect_invalid_font_property(font_properties)
font_properties[:style] = SWTProxy[*font_properties[:style]]
# TODO consider supporting other properties like locale in the future
font_data_args = [:name, :height, :style].map do |font_property_name|
font_properties[font_property_name] || send(font_property_name)
end
font_datum = FontData.new(*font_data_args)
end
@swt_font = Font.new(DisplayProxy.instance.swt_display, font_datum)
end
def name
font_datum.getName
end
def height
font_datum.getHeight
end
def style
font_datum.getStyle
end
private
def font_datum
@font_datum ||= DisplayProxy.instance.auto_exec { @widget_proxy ? @widget_proxy.swt_widget.getFont.getFontData[0] : FontData.new }
end
def detect_invalid_font_property(font_properties)
[font_properties[:style]].flatten.select do |style|
style.is_a?(Symbol) || style.is_a?(String)
end.each do |style|
raise Error, style.to_s + ERROR_INVALID_FONT_STYLE if !FONT_STYLES.include?(style.to_sym)
end
end
end
end
end
| ruby | MIT | 449cf07ada1ec965ae2ac91715ccdf22488df4ca | 2026-01-04T17:52:38.125591Z | false |
AndyObtiva/glimmer-dsl-swt | https://github.com/AndyObtiva/glimmer-dsl-swt/blob/449cf07ada1ec965ae2ac91715ccdf22488df4ca/lib/glimmer/swt/message_box_proxy.rb | lib/glimmer/swt/message_box_proxy.rb | # Copyright (c) 2007-2025 Andy Maleh
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
require 'glimmer/swt/swt_proxy'
require 'glimmer/swt/widget_proxy'
require 'glimmer/swt/display_proxy'
require 'glimmer/swt/shell_proxy'
module Glimmer
module SWT
# Proxy for org.eclipse.swt.widgets.MessageBox
#
# Follows the Proxy Design Pattern
class MessageBoxProxy
include_package 'org.eclipse.swt.widgets'
attr_reader :swt_widget
def initialize(parent, style)
# TODO consider consolidating with DialogProxy if it makes sense
if parent.nil?
@temporary_parent = parent = Glimmer::SWT::ShellProxy.new.swt_widget
end
@swt_widget = MessageBox.new(parent, style)
end
def open
DisplayProxy.instance.auto_exec do
@swt_widget.open.tap do |result|
@temporary_parent&.dispose
end
end
end
def content(&block)
Glimmer::DSL::Engine.add_content(self, Glimmer::DSL::SWT::MessageBoxExpression.new, 'message_box', &block)
end
# TODO refactor the following methods to put in a JavaBean mixin or somethin (perhaps contribute to OSS project too)
def attribute_setter(attribute_name)
"set#{attribute_name.to_s.camelcase(:upper)}"
end
def attribute_getter(attribute_name)
"get#{attribute_name.to_s.camelcase(:upper)}"
end
def has_attribute?(attribute_name, *args)
@swt_widget.respond_to?(attribute_setter(attribute_name), args)
end
def set_attribute(attribute_name, *args)
DisplayProxy.instance.auto_exec do
@swt_widget.send(attribute_setter(attribute_name), *args) unless @swt_widget.send(attribute_getter(attribute_name)) == args.first
end
end
def get_attribute(attribute_name)
DisplayProxy.instance.auto_exec do
@swt_widget.send(attribute_getter(attribute_name))
end
end
def method_missing(method_name, *args, &block)
DisplayProxy.instance.auto_exec do
swt_widget.send(method_name, *args, &block)
end
rescue => e
begin
super
rescue Exception => inner_error
Glimmer::Config.logger.error {"Neither MessageBoxProxy nor #{swt_widget.class.name} can handle the method ##{method_name}"}
Glimmer::Config.logger.error {e.full_message}
raise inner_error
end
end
def respond_to?(method_name, *args, &block)
super ||
swt_widget.respond_to?(method_name, *args, &block)
end
end
end
end
| ruby | MIT | 449cf07ada1ec965ae2ac91715ccdf22488df4ca | 2026-01-04T17:52:38.125591Z | false |
AndyObtiva/glimmer-dsl-swt | https://github.com/AndyObtiva/glimmer-dsl-swt/blob/449cf07ada1ec965ae2ac91715ccdf22488df4ca/lib/glimmer/swt/style_constantizable.rb | lib/glimmer/swt/style_constantizable.rb | # Copyright (c) 2007-2025 Andy Maleh
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
require 'glimmer/error'
module Glimmer
module SWT
# Mixin for all proxy classes that manage style constants (e.g. SWT, DND, etc...)
module StyleConstantizable
include SuperModule
class << self
REGEX_SYMBOL_NEGATIVITY = /^([^!]+)(!)?$/
def constant_java_import
raise 'Not implemented! Mixer must implement!'
end
def constant_source_class
raise 'Not implemented! Mixer must implement!'
end
def constant_value_none
# TODO instead of raising error try a convention instead like CLASSNAME::NONE by default
raise 'Not implemented! Mixer must implement!'
end
# hash of extra composite styles (i.e. style combinations defined under new style names)
def extra_styles
{}
end
def error_message_invalid_style
" is an invalid #{constant_source_class.name.split(':').last} style! Please choose a style from #{constant_java_import} class constants." # TODO parameterize
end
# Gets constants (e.g. SWT::CONSTANT) where constant is
# passed in as a lower case symbol
def [](*symbols)
symbols = symbols.first if symbols.size == 1 && symbols.first.is_a?(Array)
result = symbols.compact.map do |symbol|
constant(symbol).tap do |constant_value|
raise Glimmer::Error, symbol.to_s + error_message_invalid_style unless constant_value.is_a?(Integer)
end
end.reduce do |output, constant_value|
if constant_value < 0
output & constant_value
else
output | constant_value
end
end
result.nil? ? constant_value_none : result
end
# Returns style integer value for passed in symbol or allows
# passed in object to pass through (e.g. Integer). This makes is convenient
# to use symbols or actual style integers in Glimmer
# Does not raise error for invalid values. Just lets them pass as is.
# (look into [] operator if you want an error raised on invalid values)
def constant(symbol)
return symbol unless symbol.is_a?(Symbol) || symbol.is_a?(String)
symbol_string, negative = extract_symbol_string_negativity(symbol)
swt_constant_symbol = symbol_string.downcase == symbol_string ? symbol_string.upcase.to_sym : symbol_string.to_sym
bit_value = constant_source_class.const_get(swt_constant_symbol)
negative ? ~bit_value : bit_value
rescue => e
begin
# Glimmer::Config.logger.debug {e.full_message}
alternative_swt_constant_symbol = constant_source_class.constants.find {|c| c.to_s.upcase == swt_constant_symbol.to_s.upcase}
bit_value = constant_source_class.const_get(alternative_swt_constant_symbol)
negative ? ~bit_value : bit_value
rescue => e
# Glimmer::Config.logger.debug {e.full_message}
if symbol.to_s.size == 1 # accelerator key
symbol.to_s.bytes.first
else
bit_value = extra_styles[swt_constant_symbol]
if bit_value
negative ? ~bit_value : bit_value
else
symbol
end
end
end
end
def extract_symbol_string_negativity(symbol)
if symbol.is_a?(Symbol) || symbol.is_a?(String)
symbol_negativity_match = symbol.to_s.match(REGEX_SYMBOL_NEGATIVITY)
symbol = symbol_negativity_match[1]
negative = !!symbol_negativity_match[2]
[symbol, negative]
else
negative = symbol < 0
[symbol, negative]
end
end
def negative?(symbol)
extract_symbol_string_negativity(symbol)[1]
end
def has_constant?(symbol)
return false unless symbol.is_a?(Symbol) || symbol.is_a?(String)
constant(symbol).is_a?(Integer)
end
def constantify_args(args)
args.map {|arg| constant(arg)}
end
# Deconstructs a style integer into symbols
# Useful for debugging
def deconstruct(integer)
constant_source_class.constants.reduce([]) do |found, c|
constant_value = constant_source_class.const_get(c) rescue -1
is_found = constant_value.is_a?(Integer) && (integer & constant_value) == constant_value
is_found ? found += [c] : found
end
end
# Reverse engineer a style integer into a symbol
# Useful for debugging
def reverse_lookup(integer)
# TODO support looking up compound style mixes
constant_source_class.constants.reduce([]) do |found, c|
constant_value = constant_source_class.const_get(c) rescue -1
is_found = constant_value.is_a?(Integer) && integer == constant_value
is_found ? found += [c] : found
end
end
def include?(swt_constant, *symbols)
swt_constant & self[symbols] == self[symbols]
end
# TODO support listing all symbols
end
end
end
end
| ruby | MIT | 449cf07ada1ec965ae2ac91715ccdf22488df4ca | 2026-01-04T17:52:38.125591Z | false |
AndyObtiva/glimmer-dsl-swt | https://github.com/AndyObtiva/glimmer-dsl-swt/blob/449cf07ada1ec965ae2ac91715ccdf22488df4ca/lib/glimmer/swt/shell_proxy.rb | lib/glimmer/swt/shell_proxy.rb | # Copyright (c) 2007-2025 Andy Maleh
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
require 'glimmer/swt/swt_proxy'
require 'glimmer/swt/widget_proxy'
require 'glimmer/swt/display_proxy'
module Glimmer
module SWT
# Proxy for org.eclipse.swt.widgets.Shell
#
# Follows the Proxy Design Pattern
class ShellProxy < WidgetProxy
include_package 'org.eclipse.swt.widgets'
include_package 'org.eclipse.swt.layout'
WIDTH_MIN = 190
HEIGHT_MIN = 0
attr_reader :opened_before, :last_shell_closing
alias last_shell_closing? last_shell_closing
alias opened_before? opened_before
# Instantiates ShellProxy with same arguments expected by SWT Shell
# if swt_widget keyword arg was passed, then it is assumed the shell has already been instantiated
# and the proxy wraps it instead of creating a new one.
def initialize(*args, swt_widget: nil)
auto_exec do
if swt_widget
@swt_widget = swt_widget
else
if args.first.respond_to?(:swt_widget) && args.first.swt_widget.is_a?(Shell)
@parent_proxy = args[0]
args[0] = args[0].swt_widget
end
style_args = args.select {|arg| arg.is_a?(Symbol) || arg.is_a?(String)}.map(&:to_sym)
fill_screen = nil
if style_args.include?(:fill_screen)
args.delete(:fill_screen)
style_args.delete(:fill_screen)
fill_screen = true
end
if style_args.any?
style_arg_start_index = args.index(style_args.first)
style_arg_last_index = args.index(style_args.last)
args[style_arg_start_index..style_arg_last_index] = SWTProxy[style_args]
end
if args.first.nil? || (!args.first.is_a?(Display) && !args.first.is_a?(Shell))
@display = DisplayProxy.instance.swt_display
args = [@display] + args
end
args = args.compact
@swt_widget = Shell.new(*args)
@swt_widget.set_data('proxy', self)
@swt_widget.setLayout(FillLayout.new)
@swt_widget.setMinimumSize(WIDTH_MIN, HEIGHT_MIN)
# TODO make this an option not the default
shell_swt_display = Glimmer::SWT::DisplayProxy.instance.swt_display
on_swt_show do
if @filled_screen.nil? && fill_screen # only the first time
@swt_widget.set_size(@display.bounds.width, @display.bounds.height)
end
Thread.new do
sleep(0.25)
shell_swt_display.async_exec do
@swt_widget.setActive unless @swt_widget.isDisposed
end
end
end
end
on_widget_disposed do
@last_shell_closing = true if @display.shells.count == 1 && @display.shells.first == @swt_widget
clear_shapes unless @last_shell_closing
end
@display ||= @swt_widget.getDisplay
end
end
# Centers shell within monitor it is in
def center_within_display
auto_exec do
primary_monitor = @display.getPrimaryMonitor()
monitor_bounds = primary_monitor.getBounds()
shell_bounds = @swt_widget.getBounds()
location_x = monitor_bounds.x + (monitor_bounds.width - shell_bounds.width) / 2
location_y = monitor_bounds.y + (monitor_bounds.height - shell_bounds.height) / 2
@swt_widget.setLocation(location_x, location_y)
end
end
alias center_in_display center_within_display
# Opens shell and starts SWT's UI thread event loop
def open
open_only
start_event_loop unless nested?
end
alias show open
# Opens without starting the event loop.
def open_only
auto_exec do
if @opened_before
@swt_widget.setVisible(true)
else
@opened_before = true
@swt_widget.layout(true, true)
@swt_widget.pack(true)
center_within_display
@swt_widget.open
end
end
end
def nested?
auto_exec do
!swt_widget&.parent.nil?
end
end
alias nested nested?
def disposed?
swt_widget.isDisposed
end
alias disposed disposed?
# Hides shell. Automatically checks if widget is disposed to avoid crashing.
def hide
auto_exec do
@swt_widget.setVisible(false) unless @swt_widget.isDisposed
end
end
# Closes shell. Automatically checks if widget is disposed to avoid crashing.
def close
auto_exec do
@swt_widget.close unless @swt_widget.isDisposed
end
end
def visible?
auto_exec do
@swt_widget.isDisposed ? false : @swt_widget.isVisible
end
end
alias visible visible?
# Setting to true opens/shows shell. Setting to false hides the shell.
def visible=(visibility)
visibility ? show : hide
end
def include_focus_control?
DisplayProxy.instance.focus_control&.shell == swt_widget
end
def pack_same_size
auto_exec do
bounds = @swt_widget.getBounds
if OS.mac?
@swt_widget.pack
@swt_widget.setBounds(bounds)
elsif OS.windows? || OS::Underlying.windows?
minimum_size = @swt_widget.getMinimumSize
@swt_widget.setMinimumSize(bounds.width, bounds.height)
listener = on_control_resized { @swt_widget.setBounds(bounds) }
@swt_widget.layout(true, true)
@swt_widget.removeControlListener(listener.swt_listener)
@swt_widget.setMinimumSize(minimum_size)
elsif OS.linux?
@swt_widget.layout(true, true)
@swt_widget.setBounds(bounds)
end
end
end
def content(&block)
Glimmer::DSL::Engine.add_content(self, Glimmer::DSL::SWT::ShellExpression.new, 'shell', &block)
end
# (happens as part of `#open`)
# Starts SWT Event Loop.
#
# You may learn more about the SWT Event Loop here:
# https://help.eclipse.org/2019-12/nftopic/org.eclipse.platform.doc.isv/reference/api/org/eclipse/swt/widgets/Display.html
# This method is not needed except in rare circumstances where there is a need to start the SWT Event Loop before opening the shell.
def start_event_loop
auto_exec do
until @swt_widget.isDisposed
begin
@display.sleep unless @display.readAndDispatch
rescue => e
Glimmer::Config.logger.info {e.full_message}
end
end
end
end
def add_observer(observer, property_name)
case property_name.to_s
when 'visible?' #TODO see if you must handle non-? version and/or move elsewhere
visibility_notifier = proc do
observer.call(visible?)
end
on_swt_show(&visibility_notifier)
on_swt_hide(&visibility_notifier)
on_swt_close(&visibility_notifier)
else
super
end
end
end
WindowProxy = ShellProxy
end
end
| ruby | MIT | 449cf07ada1ec965ae2ac91715ccdf22488df4ca | 2026-01-04T17:52:38.125591Z | false |
AndyObtiva/glimmer-dsl-swt | https://github.com/AndyObtiva/glimmer-dsl-swt/blob/449cf07ada1ec965ae2ac91715ccdf22488df4ca/lib/glimmer/swt/packages.rb | lib/glimmer/swt/packages.rb | # Copyright (c) 2007-2025 Andy Maleh
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
require 'ext/glimmer/config'
module Glimmer
module SWT
# This contains Java imports of SWT Java packages
module Packages
class << self
def included(klass)
Glimmer::Config.import_swt_packages.to_a.each do |package|
include_package(package) if package.is_a?(String)
end
end
end
end
end
end
| ruby | MIT | 449cf07ada1ec965ae2ac91715ccdf22488df4ca | 2026-01-04T17:52:38.125591Z | false |
AndyObtiva/glimmer-dsl-swt | https://github.com/AndyObtiva/glimmer-dsl-swt/blob/449cf07ada1ec965ae2ac91715ccdf22488df4ca/lib/glimmer/swt/custom/code_text.rb | lib/glimmer/swt/custom/code_text.rb | # Copyright (c) 2007-2025 Andy Maleh
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
require 'glimmer/ui/custom_widget'
module Glimmer
module SWT
module Custom
# CodeText is a customization of StyledText with support for Ruby Syntax Highlighting
class CodeText
include Glimmer::UI::CustomWidget
class << self
def languages
require 'rouge'
Rouge::Lexer.all.map {|lexer| lexer.tag}.sort
end
def lexers
require 'rouge'
Rouge::Lexer.all.sort_by(&:title)
end
end
REGEX_COLOR_HEX6 = /^#([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/
FONT_NAMES_PREFERRED = ['Consolas', 'Courier', 'Monospace', 'Liberation Mono']
SHORTCUT_KEY_COMMAND = OS.mac? ? :command : :ctrl
# TODO support auto language detection
option :language, default: 'ruby'
# TODO consider supporting data-binding of language
# TODO support switcher of language that automatically updates the lexer
# TODO support method for redrawing the syntax highlighting
option :theme, default: 'glimmer'
option :lines, default: false
# This option indicates if default keyboard handlers/menus should be activated
option :default_behavior, default: true
alias lines? lines
attr_accessor :styled_text_proxy_text, :styled_text_proxy_top_pixel
attr_reader :styled_text_proxy, :lines_width, :line_numbers_styled_text_proxy
def method_missing(method_name, *args, &block)
dsl_mode = @dsl_mode || args.last.is_a?(Hash) && args.last[:dsl]
if dsl_mode
args.pop if args.last.is_a?(Hash) && args.last[:dsl]
super(method_name, *args, &block)
elsif @styled_text_proxy&.respond_to?(method_name, *args, &block)
@line_numbers_styled_text_proxy&.send(method_name, *args, &block) if method_name.to_s == 'font='
@styled_text_proxy&.send(method_name, *args, &block)
else
super
end
end
def respond_to?(method_name, *args, &block)
dsl_mode = @dsl_mode || args.last.is_a?(Hash) && args.last[:dsl]
if dsl_mode
args = args[0...-1] if args.last.is_a?(Hash) && args.last[:dsl]
super(method_name, *args, &block)
else
super || @styled_text_proxy&.respond_to?(method_name, *args, &block)
end
end
def has_instance_method?(method_name)
respond_to?(method_name)
end
def can_add_observer?(attribute_name)
@styled_text_proxy&.can_add_observer?(attribute_name) || super
end
def add_observer(observer, attribute_name)
if @styled_text_proxy&.can_add_observer?(attribute_name)
@styled_text_proxy.add_observer(observer, attribute_name)
else
super
end
end
def can_handle_observation_request?(observation_request)
@styled_text_proxy&.can_handle_observation_request?(observation_request) || super
rescue
super
end
def handle_observation_request(observation_request, &block)
if @styled_text_proxy&.can_handle_observation_request?(observation_request)
@styled_text_proxy.handle_observation_request(observation_request, &block)
else
super
end
rescue
super
end
def root_block=(block)
body_root.content(&block)
end
def line_numbers_block=(block)
@line_numbers_styled_text_proxy.content(&block)
end
def code_block=(block)
@styled_text_proxy.content(&block)
end
before_body do
require 'rouge'
require 'ext/rouge/themes/glimmer'
require 'ext/rouge/themes/glimmer_dark'
@dark_mode = Java::OrgEclipseSwtWidgets::Display.system_dark_theme?
self.theme = 'glimmer_dark' if @dark_mode && !theme.downcase.include?('dark')
@dark_theme = theme.include?('dark')
@swt_style = swt_style == 0 ? [:border, :multi, :v_scroll, :h_scroll] : swt_style
select_best_font
if lines == true
@lines_width = 4
elsif lines.is_a?(Hash)
@lines_width = lines[:width]
end
@dsl_mode = true
end
after_body do
@dsl_mode = nil
end
body {
if lines
@composite = composite {
grid_layout(2, false)
@line_numbers_styled_text_proxy = styled_text(swt(swt(@swt_style), :h_scroll!, :v_scroll!)) {
layout_data(:right, :fill, false, true)
text <= [self, :styled_text_proxy_text,
on_read: lambda { |text_value| line_numbers_text_from(text_value) },
after_read: lambda { @line_numbers_styled_text_proxy&.top_pixel = styled_text_proxy_top_pixel unless styled_text_proxy_top_pixel.nil? }
]
top_pixel <= [self, :styled_text_proxy_top_pixel]
font @font_options
background color(:widget_background)
foreground @dark_mode ? rgb(255, 255, 127) : :dark_blue
top_margin 5
right_margin 5
bottom_margin 5
left_margin 5
editable false
caret nil
on_focus_gained {
@styled_text_proxy&.setFocus
}
on_key_pressed {
@styled_text_proxy&.setFocus
}
on_mouse_up {
@styled_text_proxy&.setFocus
}
}
code_text_widget
}
else
code_text_widget
end
}
def code_text_widget
@styled_text_proxy = styled_text(@swt_style) {
# custom_widget_property_owner # TODO implement to route properties here without declaring method_missing
layout_data :fill, :fill, true, true if lines
text <=> [self, :styled_text_proxy_text] if lines
top_pixel <=> [self, :styled_text_proxy_top_pixel] if lines
font @font_options
background :black if @dark_mode
foreground rgb(75, 75, 75)
left_margin 5
top_margin 5
right_margin 5
bottom_margin 5
tabs 2
if default_behavior
on_key_pressed { |event|
character = event.keyCode.chr rescue nil
case [event.stateMask, character]
when [swt(SHORTCUT_KEY_COMMAND), 'a']
@styled_text_proxy.selectAll
when [(swt(:ctrl) if OS.mac?), 'a']
jump_to_beginning_of_line
when [(swt(:ctrl) if OS.mac?), 'e']
jump_to_end_of_line
when [swt(SHORTCUT_KEY_COMMAND), '=']
bump_font_height_up
when [swt(SHORTCUT_KEY_COMMAND), '-']
bump_font_height_down
when [swt(SHORTCUT_KEY_COMMAND), '0']
restore_font_height
end
}
on_verify_text { |verify_event|
if verify_event.text == "\n"
line_index = verify_event.widget.get_line_at_offset(verify_event.widget.get_caret_offset)
line = verify_event.widget.get_line(line_index)
line_indent = line.match(/^([ ]*)/)[1].to_s.size
verify_event.text += ' '*line_indent
verify_event.text += ' '*2 if line.strip.end_with?('{') || line.strip.match(/do([ ]*[|][^|]*[|])?$/) || line.start_with?('class') || line.start_with?('module') || line.strip.start_with?('def')
end
}
end
on_modify_text do |event|
# clear unnecessary syntax highlighting cache on text updates, and do it async to avoid affecting performance
new_text = event.data
async_exec do
unless @syntax_highlighting.nil?
lines = new_text.to_s.split("\n")
line_diff = @syntax_highlighting.keys - lines
line_diff.each do |line|
@syntax_highlighting.delete(line)
end
end
end
end
on_line_get_style do |line_style_event|
begin
styles = []
style_data = nil
syntax_highlighting(line_style_event.lineText).to_a.each do |token_hash|
start_index = token_hash[:token_index]
size = token_hash[:token_text].size
style_data = Rouge::Theme.find(theme).new.style_for(token_hash[:token_type])
foreground_color = hex_color_to_swt_color(style_data[:fg], [@dark_mode ? :white : :black])
background_color = hex_color_to_swt_color(style_data[:bg], [@dark_mode ? :black : :white])
font_styles = []
font_styles << :bold if style_data[:bold]
font_styles << :italic if style_data[:italic]
font_style = SWTProxy[*font_styles]
styles << StyleRange.new(line_style_event.lineOffset + start_index, size, foreground_color, background_color, font_style)
end
line_style_event.styles = styles.to_java(StyleRange) unless styles.empty?
rescue => e
Glimmer::Config.logger.error {"Error encountered with style data: #{style_data}"}
Glimmer::Config.logger.error {e.message}
Glimmer::Config.logger.error {e.full_message}
end
end
}
end
def syntax_highlighting(text)
return [] if text.to_s.strip.empty?
@syntax_highlighting ||= {}
unless @syntax_highlighting.keys.include?(text)
lex = lexer.lex(text).to_a
text_size = 0
@syntax_highlighting[text] = lex.map do |pair|
{token_type: pair.first, token_text: pair.last}
end.each do |hash|
hash[:token_index] = text_size
text_size += hash[:token_text].size
end
end
@syntax_highlighting[text]
end
def lexer
require 'rouge'
# TODO Try to use Rouge::Lexer.find_fancy('guess', code) in the future to guess the language or otherwise detect it from file extension
@lexer ||= Rouge::Lexer.find_fancy(language)
@lexer ||= Rouge::Lexer.find_fancy('ruby') # default to Ruby if no lexer is found
end
# TODO extract this to ColorProxy
def hex_color_to_swt_color(color_data, default_color)
color_data = "##{color_data.chars.drop(1).map {|c| c*2}.join}" if color_data.is_a?(String) && color_data.start_with?('#') && color_data&.size == 4
color_data = color_data.match(REGEX_COLOR_HEX6).to_a.drop(1).map {|c| "0x#{c}".hex}.to_a if color_data.is_a?(String) && color_data.start_with?('#')
color_data = [color_data] unless color_data.nil? || color_data.empty? || color_data.is_a?(Array)
color_data = default_color if color_data.nil? || color_data.empty?
color(*color_data).swt_color
end
def jump_to_beginning_of_line
current_line_index = @styled_text_proxy.getLineAtOffset(@styled_text_proxy.getCaretOffset)
beginning_of_current_line_offset = @styled_text_proxy.getOffsetAtLine(current_line_index)
@styled_text_proxy.setSelection(beginning_of_current_line_offset, beginning_of_current_line_offset)
end
def jump_to_end_of_line
current_line_index = @styled_text_proxy.getLineAtOffset(@styled_text_proxy.getCaretOffset)
current_line = @styled_text_proxy.getLine(current_line_index)
beginning_of_current_line_offset = @styled_text_proxy.getOffsetAtLine(current_line_index)
new_offset = beginning_of_current_line_offset + current_line.size
@styled_text_proxy.setSelection(new_offset, new_offset)
end
def line_numbers_text_from(text_value)
line_count = "#{text_value} ".split("\n").count
line_count = 1 if line_count == 0
lines_text_size = [line_count.to_s.size, @lines_width].max
@lines_width = lines_text_size if lines_text_size > @lines_width
line_count.times.map {|n| (' ' * (lines_text_size - (n+1).to_s.size)) + (n+1).to_s }.join("\n") + "\n"
end
def select_best_font
select_best_font_name
@font_options = {height: OS.mac? ? 15 : 12}
@font_options.merge!(name: @font_name) if @font_name
@font_options
end
def select_best_font_name
all_font_names = display.get_font_list(nil, true).map(&:name)
@font_name = 'Courier' if OS.mac?
FONT_NAMES_PREFERRED.each do |font_name|
@font_name ||= font_name if all_font_names.include?(font_name)
end
@font_name ||= all_font_names.find {|font_name| font_name.downcase.include?('mono')}
@font_name
end
def bump_font_height_up
@original_font_height ||= font_datum.height
new_font_height = font_datum.height + 1
update_font_height(new_font_height)
end
def bump_font_height_down
@original_font_height ||= font_datum.height
new_font_height = (font_datum.height - 1) == 0 ? font_datum.height : (font_datum.height - 1)
update_font_height(new_font_height)
end
def restore_font_height
return if @original_font_height.nil?
update_font_height(@original_font_height)
@original_font_height = nil
end
def update_font_height(new_font_height)
return if new_font_height.nil?
@styled_text_proxy.font = {name: font_datum.name, height: new_font_height, style: font_datum.style}
@line_numbers_styled_text_proxy&.font = {name: font_datum.name, height: new_font_height, style: font_datum.style}
@body_root.shell_proxy.layout(true, true)
@body_root.shell_proxy.pack_same_size
end
def font_datum
@styled_text_proxy.font.font_data.first
end
end
end
end
end
| ruby | MIT | 449cf07ada1ec965ae2ac91715ccdf22488df4ca | 2026-01-04T17:52:38.125591Z | false |
AndyObtiva/glimmer-dsl-swt | https://github.com/AndyObtiva/glimmer-dsl-swt/blob/449cf07ada1ec965ae2ac91715ccdf22488df4ca/lib/glimmer/swt/custom/drawable.rb | lib/glimmer/swt/custom/drawable.rb | # Copyright (c) 2007-2025 Andy Maleh
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
module Glimmer
module SWT
module Custom
# Represents SWT drawable controls (widgets like canvas) and display
module Drawable
attr_accessor :requires_shape_disposal, :image_double_buffered
alias requires_shape_disposal? requires_shape_disposal
alias image_double_buffered? image_double_buffered
include_package 'org.eclipse.swt.graphics'
def shapes
@shapes ||= []
end
def expanded_shapes
@shapes.map do |shape|
[shape] + shape.expanded_shapes
end.flatten
end
def image_buffered_shapes
@image_buffered_shapes ||= []
end
def drop_shapes
@drop_shapes ||= []
end
# TODO add a method like shapes that specifies drawable_properties to be able to adjust properties like transform in between shapes
def shape_at_location(x, y)
expanded_shapes.reverse.detect {|shape| shape.include?(x, y)}
end
def add_shape(shape)
if !@image_double_buffered || shape.args.first == @image_proxy_buffer
shapes << shape
else
image_buffered_shapes << shape
end
end
def clear_shapes(dispose_images: true, dispose_patterns: true)
# Optimize further by having a collection of disposable_shapes independent of shapes, which is much smaller and only has shapes that require disposal (shapes with patterns or image)
shapes.dup.each {|s| s.dispose(dispose_images: dispose_images, dispose_patterns: dispose_patterns) } if requires_shape_disposal?
end
alias dispose_shapes clear_shapes
def paint_pixel_by_pixel(width = nil, height = nil, &each_pixel_color)
if @image_double_buffered
work = lambda do |paint_event|
width ||= swt_drawable.bounds.width
height ||= swt_drawable.bounds.height
@image_proxy_buffer ||= ImageProxy.create_pixel_by_pixel(width, height, &each_pixel_color)
@image_proxy_buffer.shape(self).paint(paint_event)
end
else
work = lambda do |paint_event_or_image|
the_gc = paint_event_or_image.gc
current_foreground = nil
width ||= swt_drawable.bounds.width
height ||= swt_drawable.bounds.height
height.times do |y|
width.times do |x|
new_foreground = each_pixel_color.call(x, y)
new_foreground = Glimmer::SWT::ColorProxy.create(new_foreground, ensure_bounds: false) unless new_foreground.is_a?(ColorProxy) || new_foreground.is_a?(Color)
new_foreground = new_foreground.swt_color if new_foreground.is_a?(Glimmer::SWT::ColorProxy)
the_gc.foreground = current_foreground = new_foreground unless new_foreground == current_foreground
the_gc.draw_point x, y
end
end
end
end
if respond_to?(:gc)
work.call(self)
else
on_swt_paint(&work)
end
end
def swt_drawable
swt_drawable = nil
if respond_to?(:swt_image)
swt_drawable = swt_image
elsif respond_to?(:swt_display)
swt_drawable = swt_display
elsif respond_to?(:swt_widget)
swt_drawable = swt_widget
end
swt_drawable
end
def deregister_shape_painting
unless shell_proxy.last_shell_closing?
@paint_listener_proxy&.deregister
@resize_listener_proxy&.deregister
end
end
def setup_shape_painting
# TODO consider performance optimization relating to order of shape rendering (affecting only further shapes not previous ones)
if @paint_listener_proxy.nil?
shape_painter = lambda do |paint_event|
shape_painting_work = lambda do |paint_event|
paintable_shapes = @image_double_buffered ? image_buffered_shapes : shapes
paintable_shapes.each do |shape|
shape.paint(paint_event)
end
# When dragging, render dragged shape again on top of everything else.
if !@image_double_buffered && Glimmer::SWT::Custom::Shape.dragging?
Glimmer::SWT::Custom::Shape.dragged_shape.paint(paint_event)
end
end
if @image_double_buffered
if @image_proxy_buffer.nil?
swt_image = Image.new(DisplayProxy.instance.swt_display, bounds.width, bounds.height)
@image_proxy_buffer = ImageProxy.new(swt_image: swt_image)
shape_painting_work.call(@image_proxy_buffer)
end
@image_proxy_buffer.shape(self).paint(paint_event)
else
shape_painting_work.call(paint_event)
end
end
# TODO consider making this logic polymorphic (image vs other)
if respond_to?(:swt_image)
shape_painter.call(self) # treat self as paint event since image has its own gc and doesn't do repaints (it's a one time deal for now though could be adjusted in the future.)
else
@paint_listener_proxy = on_swt_paint(&shape_painter)
@resize_listener_proxy = on_swt_Resize { shapes.each(&:calculated_args_changed!) }
end
else
redraw if respond_to?(:redraw) && @finished_add_content && !is_disposed
end
end
alias resetup_shape_painting setup_shape_painting
end
end
end
end
| ruby | MIT | 449cf07ada1ec965ae2ac91715ccdf22488df4ca | 2026-01-04T17:52:38.125591Z | false |
AndyObtiva/glimmer-dsl-swt | https://github.com/AndyObtiva/glimmer-dsl-swt/blob/449cf07ada1ec965ae2ac91715ccdf22488df4ca/lib/glimmer/swt/custom/checkbox_group.rb | lib/glimmer/swt/custom/checkbox_group.rb | # Copyright (c) 2007-2025 Andy Maleh
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
require 'glimmer/ui/custom_widget'
module Glimmer
module SWT
module Custom
# A custom widget rendering a group of checkboxes generated via data-binding
class CheckboxGroup
include Glimmer::UI::CustomWidget
body {
composite {} # just an empty composite to hold checkboxs upon data-binding `selection`
}
def items=(text_array)
selection_value = selection
@items = Array[*text_array]
build_checkboxes
end
def items
@items || []
end
def selection=(selection_texts)
items.count.times do |index|
checkbox = checkboxes[index]
item = items[index]
label_text = labels[index]&.text
checkbox.selection = selection_texts.to_a.include?(label_text)
end
selection_texts
end
def selection
selection_indices.map do |selection_index|
labels[selection_index]&.text
end
end
def selection_indices=(indices)
self.selection=(indices.to_a.map {|index| items[index]})
end
alias select selection_indices=
def selection_indices
checkboxes.each_with_index.map do |checkbox, index|
index if checkbox.selection
end.to_a.compact
end
def checkboxes
@checkboxes ||= []
end
alias checks checkboxes
def labels
@labels ||= []
end
def can_handle_observation_request?(observation_request)
checkboxes.first&.can_handle_observation_request?(observation_request) || super(observation_request)
end
def handle_observation_request(observation_request, &block)
observation_requests << [observation_request, block]
delegate_observation_request_to_checkboxes(observation_request, &block)
super
end
def delegate_observation_request_to_checkboxes(observation_request, &block)
if observation_request != 'on_widget_disposed'
checkboxes.count.times do |index|
checkbox = checkboxes[index]
label = labels[index]
listener_block = lambda do |event|
event.widget = self.swt_widget
block.call(event)
end
if observation_request == 'on_widget_selected'
checkbox.handle_observation_request(observation_request, &listener_block) if checkbox.can_handle_observation_request?(observation_request)
label.handle_observation_request('on_mouse_up', &listener_block)
else
checkbox.handle_observation_request(observation_request, &listener_block) if checkbox.can_handle_observation_request?(observation_request)
label.handle_observation_request(observation_request, &listener_block) if label.can_handle_observation_request?(observation_request)
end
end
end
end
def observation_requests
@observation_requests ||= Set.new
end
def has_attribute?(attribute_name, *args)
(@composites.to_a + @checkboxes.to_a + @labels.to_a).map do |widget_proxy|
return true if widget_proxy.has_attribute?(attribute_name, *args)
end
super
end
def set_attribute(attribute_name, *args)
excluded_attributes = ['selection']
unless excluded_attributes.include?(attribute_name.to_s)
(@composites.to_a + @checkboxes.to_a + @labels.to_a).each do |widget_proxy|
widget_proxy.set_attribute(attribute_name, *args) if widget_proxy.has_attribute?(attribute_name, *args)
end
end
super
end
private
def build_checkboxes
current_selection = selection
@composites.to_a.each(&:dispose)
@checkboxes = []
@labels = []
@composites = []
items.each do |item|
body_root.content {
@composites << composite {
grid_layout(2, false) {
margin_width 0
margin_height 0
horizontal_spacing 0
vertical_spacing 0
}
checkboxes << checkbox { |checkbox_proxy|
on_widget_selected {
self.selection_indices = checkboxes.each_with_index.map {|cb, i| i if cb.selection}.to_a.compact
}
}
labels << label { |label_proxy|
layout_data :fill, :center, true, false
text item
on_mouse_up { |event|
found_text = labels.each_with_index.detect {|l, i| event.widget == l.swt_widget}[0]&.text
selection_values = self.selection
if selection_values.include?(found_text)
selection_values.delete(found_text)
else
selection_values << found_text
end
self.selection = selection_values
}
}
}
}
end
observation_requests.to_a.each do |observation_request, block|
delegate_observation_request_to_checkboxes(observation_request, &block)
end
self.selection = current_selection
end
end
CheckGroup = CheckboxGroup
end
end
end
| ruby | MIT | 449cf07ada1ec965ae2ac91715ccdf22488df4ca | 2026-01-04T17:52:38.125591Z | false |
AndyObtiva/glimmer-dsl-swt | https://github.com/AndyObtiva/glimmer-dsl-swt/blob/449cf07ada1ec965ae2ac91715ccdf22488df4ca/lib/glimmer/swt/custom/shape.rb | lib/glimmer/swt/custom/shape.rb | # Copyright (c) 2007-2025 Andy Maleh
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
require 'glimmer/swt/properties'
require 'glimmer/swt/swt_proxy'
require 'glimmer/swt/display_proxy'
require 'glimmer/swt/color_proxy'
require 'glimmer/swt/font_proxy'
require 'glimmer/swt/transform_proxy'
require 'glimmer/swt/shape_listener_proxy'
class Java::OrgEclipseSwtGraphics::GC
def setLineDashOffset(value)
lineMiterLimit = getLineAttributes&.miterLimit || 999_999
setLineAttributes(Java::OrgEclipseSwtGraphics::LineAttributes.new(getLineWidth, getLineCap, getLineJoin, getLineStyle, getLineDash.map(&:to_f).to_java(:float), value, lineMiterLimit))
end
alias set_line_dash_offset setLineDashOffset
alias line_dash_offset= setLineDashOffset
def getLineDashOffset
getLineAttributes&.dashOffset
end
alias get_line_dash_offset getLineDashOffset
alias line_dash_offset getLineDashOffset
def setLineMiterLimit(value)
lineDashOffset = getLineAttributes&.dashOffset || 0
setLineAttributes(Java::OrgEclipseSwtGraphics::LineAttributes.new(getLineWidth, getLineCap, getLineJoin, getLineStyle, getLineDash.map(&:to_f).to_java(:float), lineDashOffset, value))
end
alias set_line_miter_limit setLineMiterLimit
alias line_miter_limit= setLineMiterLimit
def getLineMiterLimit
getLineAttributes&.miterLimit
end
alias get_line_miter_limit getLineMiterLimit
alias line_miter_limit getLineMiterLimit
end
module Glimmer
module SWT
module Custom
# Represents a shape (graphics) to be drawn on a control/widget/canvas/display
# That is because Shape is drawn on a parent as graphics and doesn't have an SWT widget for itself
class Shape
include Properties
DropEvent = Struct.new(:doit, :x, :y, :dragged_shape, :dragged_shape_original_x, :dragged_shape_original_y, :dragging_x, :dragging_y, :drop_shapes, keyword_init: true)
class << self
attr_accessor :dragging, :dragging_x, :dragging_y, :dragged_shape, :dragged_shape_original_x, :dragged_shape_original_y, :drop_shape_handling_count
alias dragging? dragging
def create(parent, keyword, *args, &property_block)
potential_shape_class_name = keyword.to_s.camelcase(:upper).to_sym
if constants.include?(potential_shape_class_name)
const_get(potential_shape_class_name).new(parent, keyword, *args, &property_block)
else
new(parent, keyword, *args, &property_block)
end
end
def valid?(parent, keyword, *args, &block)
return true if keyword.to_s == 'shape'
gc_instance_methods.include?(method_name(keyword, arg_options(args))) ||
constants.include?(keyword.to_s.camelcase(:upper).to_sym)
end
def gc_instance_methods
@gc_instance_methods ||= org.eclipse.swt.graphics.GC.instance_methods.map(&:to_s)
end
def keywords
@keywords ||= gc_instance_methods.select do |method_name|
!method_name.end_with?('=') && (method_name.start_with?('draw_') || method_name.start_with?('fill_'))
end.reject do |method_name|
gc_instance_methods.include?("#{method_name}=") || gc_instance_methods.include?("set_#{method_name}")
end.map do |method_name|
method_name.gsub(/(draw|fill|gradient|round)_/, '')
end.uniq.compact.to_a
end
def arg_options(args, extract: false)
arg_options_method = extract ? :pop : :last
options = args.send(arg_options_method).symbolize_keys if args.last.is_a?(Hash)
# normalize :filled option as an alias to :fill
# options[:fill] = options.delete(:filled) if options&.keys&.include?(:filled)
options.nil? ? {} : options
end
def method_name(keyword, method_arg_options)
keyword = keyword.to_s
method_arg_options = method_arg_options.select {|key, value| %w[fill gradient round].include?(key.to_s)}
unless flyweight_method_names.keys.include?([keyword, method_arg_options])
gradient = 'Gradient' if method_arg_options[:gradient]
round = 'Round' if method_arg_options[:round]
gc_instance_method_name_prefix = !['polyline', 'point', 'image', 'focus'].include?(keyword) && (method_arg_options[:fill] || method_arg_options[:gradient]) ? 'fill' : 'draw'
flyweight_method_names[[keyword, method_arg_options]] = "#{gc_instance_method_name_prefix}#{gradient}#{round}#{keyword.capitalize}"
end
flyweight_method_names[[keyword, method_arg_options]]
end
def flyweight_method_names
@flyweight_method_names ||= {}
end
def pattern(*args)
found_pattern = flyweight_patterns[args]
if found_pattern.nil? || found_pattern.is_disposed
found_pattern = flyweight_patterns[args] = org.eclipse.swt.graphics.Pattern.new(*args)
end
found_pattern
end
def flyweight_patterns
@flyweight_patterns ||= {}
end
end
attr_reader :drawable, :parent, :name, :args, :options, :shapes, :properties, :disposed, :widget_listener_proxies
attr_accessor :extent
alias disposed? disposed
alias is_disposed disposed # for SWT widget compatibility
# TODO consider making shapes return a dup, always, in case consumers want to dispose
def initialize(parent, keyword, *args, &property_block)
@parent = parent
@drawable = @parent.is_a?(Drawable) ? @parent : @parent.drawable
@name = keyword
@options = self.class.arg_options(args, extract: true)
@method_name = self.class.method_name(keyword, @options) unless keyword.to_s == 'shape'
@args = args
@properties = {}
@shapes = [] # nested shapes
@options.reject {|key, value| %w[fill gradient round].include?(key.to_s)}.each do |property, property_args|
@properties[property] = property_args
end
@parent.add_shape(self)
post_add_content if property_block.nil?
end
def add_shape(shape)
@shapes << shape
calculated_args_changed_for_defaults!
end
def draw?
!fill?
end
alias drawn? draw?
def fill?
@options[:fill]
end
alias filled? fill?
def gradient?
@options[:gradient]
end
def round?
@options[:round]
end
# The bounding box top-left x, y, width, height in absolute positioning
def bounds
bounds_dependencies = [absolute_x, absolute_y, calculated_width, calculated_height]
if bounds_dependencies != @bounds_dependencies
# avoid repeating calculations
absolute_x, absolute_y, calculated_width, calculated_height = @bounds_dependencies = bounds_dependencies
@bounds = org.eclipse.swt.graphics.Rectangle.new(absolute_x, absolute_y, calculated_width, calculated_height)
end
@bounds
end
# The bounding box top-left x and y
def location
org.eclipse.swt.graphics.Point.new(bounds.x, bounds.y)
end
# The bounding box width and height (as a Point object with x being width and y being height)
def size
size_dependencies = [calculated_width, calculated_height]
if size_dependencies != @size_dependencies
# avoid repeating calculations
calculated_width, calculated_height = @size_dependencies = size_dependencies
@size = org.eclipse.swt.graphics.Point.new(calculated_width, calculated_height)
end
@size
end
def extent
@extent || size
end
# Returns if shape contains a point
# Subclasses (like polygon) may override to indicate if a point x,y coordinates falls inside the shape
# some shapes may choose to provide a fuzz factor to make usage of this method for mouse clicking more user friendly
def contain?(x, y)
x, y = inverse_transform_point(x, y)
# assume a rectangular filled shape by default (works for several shapes like image, text, and focus)
x.between?(self.absolute_x, self.absolute_x + calculated_width.to_f) && y.between?(self.absolute_y, self.absolute_y + calculated_height.to_f)
end
# Returns if shape includes a point. When the shape is filled, this is the same as contain. When the shape is drawn, it only returns true if the point lies on the edge (boundary/border)
# Subclasses (like polygon) may override to indicate if a point x,y coordinates falls on the edge of a drawn shape or inside a filled shape
# some shapes may choose to provide a fuzz factor to make usage of this method for mouse clicking more user friendly
def include?(x, y)
# assume a rectangular shape by default
contain?(x, y)
end
def include_with_children?(x, y, except_shape: nil)
included_in_self = (!self.equal?(except_shape) && include?(x, y))
# TODO note that expanded shapes does not filter when reject below happens, keeping nested shapes
included_in_self || expanded_shapes(except_shape: except_shape).any? { |shape| shape.include?(x, y) }
end
def bounds_contain?(x, y)
x, y = inverse_transform_point(x, y)
bounds.contains(x, y)
end
# Recursively checks if other shape is included in this shape, beginning by comparing to self
# and then recursing into children shapes.
def include_shape?(other)
self == other || shapes.any? { |shape| shape.include_shape?(other) }
end
# if there is a transform, apply on x, y point coordinates
def transform_point(x, y)
# keep in mind that transform is an array of a single element that is the transform object
current_transform = (transform || parent_shape_containers.map(&:transform).first)&.first
if current_transform
transform_array = [x, y].to_java(:float) # just placeholder data that gets overwritten with getElements
current_transform.transform(transform_array)
x = transform_array[0]
y = transform_array[1]
end
[x, y]
end
# if there is a transform, invert it and apply on x, y point coordinates
def inverse_transform_point(x, y)
# keep in mind that transform is an array of a single element that is the transform object
current_transform = (transform || parent_shape_containers.map(&:transform).compact.first)&.first
if current_transform
transform_array = [1,2,3,4,5,6].to_java(:float) # just placeholder data that gets overwritten with getElements
current_transform.getElements(transform_array)
inverse_transform = TransformProxy.new(DisplayProxy.instance.swt_display, *transform_array.to_a)
inverse_transform_array = [1,2,3,4,5,6].to_java(:float) # just placeholder data that gets overwritten with getElements
inverse_transform.getElements(inverse_transform_array)
# TODO avoid Matrix usage directly by relying on SWT Transform#invert method instead (much simpler)
matrix = Matrix[[inverse_transform_array[0], inverse_transform_array[1]], [inverse_transform_array[2], inverse_transform_array[3]]]
result = matrix * Matrix.column_vector([x, y])
x, y = result.to_a.flatten
x += inverse_transform_array[5]
y += inverse_transform_array[4]
end
[x, y]
end
# Indicates if a shape's x, y, width, height differ from its bounds calculation (e.g. arc / polygon)
def irregular?
false
end
# moves by x delta and y delta. Subclasses must implement
# provdies a default implementation that assumes moving x and y is sufficient by default (not for polygons though, which must override)
def move_by(x_delta, y_delta)
if respond_to?(:x) && respond_to?(:y) && respond_to?(:x=) && respond_to?(:y=)
if default_x?
self.x_delta += x_delta
else
self.x += x_delta
end
if default_y?
self.y_delta += y_delta
else
self.y += y_delta
end
end
end
alias translate move_by
# rotates shape for an angle around its center
# this operation is not cumulative (it resets angle every time)
# consumers may inspect corresponding rotation_angle attribute to know which angle the shape is currently at for convenience
# this overrides any pre-existing transforms that are applied to shape
def rotate(angle)
half_width = calculated_width/2.0
half_height = calculated_height/2.0
self.transform = Glimmer::SWT::TransformProxy.new(self).translate(half_width, half_height).rotate(angle).translate(-1.0*half_width, -1.0*half_height)
@rotation_angle = angle
end
# returns rotation angle
# consumers may inspect rotation_angle attribute to know which angle the shape is rotated at via rotate method
# it is not guaranteed to give the right result if a transform is applied outside of rotate method.
# starts at 0
def rotation_angle
@rotation_angle.to_f
end
def center_x
center_x_dependencies = [x_end, calculated_width]
if center_x_dependencies != @center_x_dependencies
@center_x_dependencies = center_x_dependencies
the_x_end, the_calculated_width = center_x_dependencies
@center_x = the_x_end - the_calculated_width/2.0
end
@center_x
end
def center_y
center_y_dependencies = [y_end, calculated_height]
if center_y_dependencies != @center_y_dependencies
@center_y_dependencies = center_y_dependencies
the_y_end, the_calculated_height = center_y_dependencies
@center_y = the_y_end - the_calculated_height/2.0
end
@center_y
end
def content(&block)
# TODO consider supporting adding content without redraw (redraw: false)
Glimmer::SWT::DisplayProxy.instance.auto_exec do
Glimmer::DSL::Engine.add_content(self, Glimmer::DSL::SWT::ShapeExpression.new, @name, &block)
calculated_args_changed!(children: false)
end
end
def has_some_background?
@properties.keys.map(&:to_s).include?('background') || @properties.keys.map(&:to_s).include?('background_pattern')
end
def has_some_foreground?
@properties.keys.map(&:to_s).include?('foreground') || @properties.keys.map(&:to_s).include?('foreground_pattern')
end
def post_add_content
amend_method_name_options_based_on_properties!
if !@content_added || @method_name != @original_method_name
@drawable.setup_shape_painting unless @drawable.is_a?(ImageProxy)
@content_added = true
end
end
def apply_property_arg_conversions(property, args)
method_name = attribute_setter(property)
args = args.dup
the_java_method = org.eclipse.swt.graphics.GC.java_class.declared_instance_methods.detect {|m| m.name == method_name}
return args if the_java_method.nil?
if the_java_method.parameter_types.first == org.eclipse.swt.graphics.Color.java_class && args.first.is_a?(org.eclipse.swt.graphics.RGB)
args[0] = [args[0].red, args[0].green, args[0].blue]
end
if ['setBackground', 'setForeground'].include?(method_name.to_s) && args.first.is_a?(Array)
args[0] = ColorProxy.new(args[0])
end
if method_name.to_s == 'setLineDash' && args.size > 1
args[0] = args.dup
args[1..-1] = []
end
if method_name.to_s == 'setAntialias' && [nil, true, false].include?(args.first)
args[0] = case args.first
when true
args[0] = :on
when false
args[0] = :off
when nil
args[0] = :default
end
end
if args.first.is_a?(Symbol) || args.first.is_a?(::String)
if the_java_method.parameter_types.first == org.eclipse.swt.graphics.Color.java_class
args[0] = ColorProxy.new(args[0])
end
if method_name.to_s == 'setLineStyle'
args[0] = "line_#{args[0]}" if !args[0].to_s.downcase.start_with?('line_')
end
if method_name.to_s == 'setFillRule'
args[0] = "fill_#{args[0]}" if !args[0].to_s.downcase.start_with?('fill_')
end
if method_name.to_s == 'setLineCap'
args[0] = "cap_#{args[0]}" if !args[0].to_s.downcase.start_with?('cap_')
end
if method_name.to_s == 'setLineJoin'
args[0] = "join_#{args[0]}" if !args[0].to_s.downcase.start_with?('join_')
end
if the_java_method.parameter_types.first == Java::int.java_class
args[0] = SWTProxy.constant(args[0])
end
end
if args.first.is_a?(ColorProxy)
args[0] = args[0].swt_color
end
if (args.first.is_a?(Hash) || args.first.is_a?(org.eclipse.swt.graphics.FontData)) && the_java_method.parameter_types.first == org.eclipse.swt.graphics.Font.java_class
args[0] = FontProxy.new(args[0])
end
if args.first.is_a?(FontProxy)
args[0] = args[0].swt_font
end
if args.first.is_a?(TransformProxy)
args[0] = args[0].swt_transform
end
if ['setBackgroundPattern', 'setForegroundPattern'].include?(method_name.to_s)
@drawable.requires_shape_disposal = true
args = args.first if args.first.is_a?(Array)
args.each_with_index do |arg, i|
arg = ColorProxy.new(arg.red, arg.green, arg.blue) if arg.is_a?(org.eclipse.swt.graphics.RGB)
arg = ColorProxy.new(arg) if arg.is_a?(Symbol) || arg.is_a?(::String)
arg = arg.swt_color if arg.is_a?(ColorProxy)
args[i] = arg
end
@pattern_args ||= {}
pattern_type = method_name.to_s.match(/set(.+)Pattern/)[1]
if args.first.is_a?(org.eclipse.swt.graphics.Pattern)
new_args = @pattern_args[pattern_type]
else
new_args = args.first.is_a?(org.eclipse.swt.widgets.Display) ? args : ([DisplayProxy.instance.swt_display] + args)
@pattern_args[pattern_type] = new_args.dup
end
args[0] = pattern(*new_args, type: pattern_type)
args[1..-1] = []
end
args
end
def apply_shape_arg_conversions!
if @args.size > 1 && (['polygon', 'polyline'].include?(@name))
@args[0] = @args.dup
@args[1..-1] = []
end
if @name == 'image'
if @args.first.is_a?(::String)
@args[0] = ImageProxy.create(@args[0])
end
if @args.first.is_a?(ImageProxy)
@image = @args[0] = @args[0].swt_image
end
if @args.first.nil?
@image = nil
end
end
if @name == 'text'
if @args[3].is_a?(Symbol) || @args[3].is_a?(::String)
@args[3] = [@args[3]]
end
if @args[3].is_a?(Array)
if @args[3].size == 1 && @args[3].first.is_a?(Array)
@args[3] = @args[3].first
end
@args[3] = SWTProxy[*@args[3]]
end
end
end
def apply_shape_arg_defaults!
if current_parameter_name?(:dest_x) && dest_x.nil?
self.dest_x = :default
elsif parameter_name?(:x) && x.nil?
self.x = :default
end
if current_parameter_name?(:dest_y) && dest_y.nil?
self.dest_y = :default
elsif parameter_name?(:y) && y.nil?
self.y = :default
end
self.width = :default if current_parameter_name?(:width) && width.nil?
self.height = :default if current_parameter_name?(:height) && height.nil?
if @name.include?('rectangle') && round? && @args.size.between?(4, 5)
(6 - @args.size).times {@args << 60}
elsif @name.include?('rectangle') && gradient? && @args.size == 4
set_attribute('vertical', true, redraw: false)
elsif (@name.include?('text') || @name.include?('string')) && !@properties.keys.map(&:to_s).include?('background') && @args.size < 4
set_attribute('is_transparent', true, redraw: false)
end
if @name.include?('image')
@drawable.requires_shape_disposal = true
end
end
# Tolerates shape extra args added by user by mistake
# (e.g. happens when switching from round rectangle to a standard one without removing all extra args)
def tolerate_shape_extra_args!
the_java_method_arg_count = org.eclipse.swt.graphics.GC.java_class.declared_instance_methods.select do |m|
m.name == @method_name.camelcase(:lower)
end.map(&:parameter_types).map(&:size).max
if the_java_method_arg_count && @args.to_a.size > the_java_method_arg_count
@args[the_java_method_arg_count..-1] = []
end
end
def amend_method_name_options_based_on_properties!
@original_method_name = @method_name
return if @name == 'point'
if (@name != 'text' && @name != 'string' && has_some_background? && !has_some_foreground?) || (@name == 'path' && has_some_background?)
@options[:fill] = true
elsif !has_some_background? && has_some_foreground?
@options[:fill] = false
elsif @name == 'rectangle' && has_some_background? && has_some_foreground?
@options[:fill] = true
@options[:gradient] = true
end
if @name == 'rectangle' && @args.size > 4 && @args.last.is_a?(Numeric)
@options[:round] = true
end
@method_name = self.class.method_name(@name, @options)
end
# parameter names for arguments to pass to SWT GC.xyz method for rendering shape (e.g. draw_image(image, x, y) yields :image, :x, :y parameter names)
def parameter_names
[:x, :y, :width, :height]
end
# subclasses may override to specify location parameter names if different from x and y (e.g. all polygon points are location parameters)
# used in calculating movement changes
def location_parameter_names
[:x, :y]
end
def possible_parameter_names
parameter_names
end
def parameter_name?(attribute_name)
possible_parameter_names.map(&:to_s).include?(ruby_attribute_getter(attribute_name))
end
def current_parameter_name?(attribute_name)
parameter_names.include?(attribute_name.to_s.to_sym)
end
def parameter_index(attribute_name)
parameter_names.index(attribute_name.to_s.to_sym)
end
def get_parameter_attribute(attribute_name)
@args[parameter_index(ruby_attribute_getter(attribute_name))]
end
def set_parameter_attribute(attribute_name, *args)
@args[parameter_index(ruby_attribute_getter(attribute_name))] = args.size == 1 ? args.first : args
end
def has_attribute?(attribute_name, *args)
attribute_name == 'data' or
self.class.gc_instance_methods.include?(attribute_setter(attribute_name)) or
parameter_name?(attribute_name) or
(respond_to?(attribute_name, super: true) and respond_to?(ruby_attribute_setter(attribute_name), super: true))
end
def set_attribute(attribute_name, *args)
options = args.last if args.last.is_a?(Hash)
args.pop if !options.nil? && !options[:redraw].nil?
options ||= {}
perform_redraw = @perform_redraw
perform_redraw = options[:redraw] if perform_redraw.nil? && !options.nil?
perform_redraw ||= true
property_change = nil
ruby_attribute_getter_name = ruby_attribute_getter(attribute_name)
ruby_attribute_setter_name = ruby_attribute_setter(attribute_name)
if attribute_name == 'data'
set_data(*args)
elsif parameter_name?(attribute_name)
return if ruby_attribute_getter_name == (args.size == 1 ? args.first : args)
set_parameter_attribute(ruby_attribute_getter_name, *args)
elsif (respond_to?(attribute_name, super: true) and respond_to?(ruby_attribute_setter_name, super: true))
return if self.send(ruby_attribute_getter_name) == (args.size == 1 ? args.first : args)
self.send(ruby_attribute_setter_name, *args)
else
# TODO consider this optimization of preconverting args (removing conversion from other methods) to reject equal args
args = apply_property_arg_conversions(ruby_attribute_getter_name, args)
return if @properties[ruby_attribute_getter_name] == args
new_property = !@properties.keys.include?(ruby_attribute_getter_name)
@properties[ruby_attribute_getter_name] = args
amend_method_name_options_based_on_properties! if @content_added && new_property
property_change = true
calculated_paint_args_changed! if container?
end
if @content_added && perform_redraw && !drawable.is_disposed
redrawn = false
unless property_change
calculated_paint_args_changed!(children: false)
if is_a?(PathSegment)
root_path&.calculated_path_args = @calculated_path_args = false
calculated_args_changed!
root_path&.calculated_args_changed!
end
if location_parameter_names.map(&:to_s).include?(ruby_attribute_getter_name)
calculated_args_changed!(children: true)
redrawn = parent.calculated_args_changed_for_defaults! if parent.is_a?(Shape)
end
if ['width', 'height'].include?(ruby_attribute_getter_name)
redrawn = calculated_args_changed_for_defaults!
end
end
# TODO consider redrawing an image proxy's gc in the future
# TODO consider ensuring only a single redraw happens for a hierarchy of nested shapes
drawable.redraw if !redrawn && !drawable.is_a?(ImageProxy)
end
end
def get_attribute(attribute_name)
if parameter_name?(attribute_name)
arg_index = parameter_index(attribute_name)
@args[arg_index] if arg_index
elsif (respond_to?(attribute_name, super: true) and respond_to?(ruby_attribute_setter(attribute_name), super: true))
self.send(attribute_name)
else
@properties[attribute_name.to_s]
end
end
def can_handle_observation_request?(observation_request)
observation_request = observation_request.to_s
observation_request.start_with?('on_') &&
(
observation_request == 'on_shape_disposed' ||
(
drawable.respond_to?(:can_handle_observation_request?) &&
drawable.can_handle_observation_request?(observation_request)
)
)
end
def handle_observation_request(observation_request, source_observation_request: nil, &block)
if observation_request.to_s == 'on_shape_disposed'
@on_shape_disposed_handlers ||= []
@on_shape_disposed_handlers << block
return ShapeListenerProxy.new(shape: self, drawable: drawable, shape_listener_block: block, observation_request: 'on_shape_disposed')
end
if observation_request == 'on_drop'
drawable.drop_shapes << self
handle_observation_request('on_mouse_up', source_observation_request: 'on_drop') do |event|
if Shape.dragging && include_with_children?(event.x, event.y, except_shape: Shape.dragged_shape)
drop_event = DropEvent.new(
doit: true,
dragged_shape: Shape.dragged_shape,
dragged_shape_original_x: Shape.dragged_shape_original_x,
dragged_shape_original_y: Shape.dragged_shape_original_y,
dragging_x: Shape.dragging_x,
dragging_y: Shape.dragging_y,
drop_shapes: drawable.drop_shapes,
x: event.x,
y: event.y
)
begin
block.call(drop_event)
rescue => e
Glimmer::Config.logger.error {e.full_message}
ensure
if drop_event.doit
Shape.dragging = false
Shape.dragged_shape = nil
elsif Shape.drop_shape_handling_count.to_i >= drawable.drop_shapes.count && Shape.dragged_shape
cancel_dragging!
end
end
else
if Shape.drop_shape_handling_count.to_i >= drawable.drop_shapes.count
cancel_dragging!
end
end
end
else
widget_listener_proxy = nil
shape_block = lambda do |event|
if @disposed
widget_listener_proxy.deregister
@widget_listener_proxies.delete(widget_listener_proxy)
else
Shape.drop_shape_handling_count += 1 if source_observation_request == 'on_drop' && event.x == Shape.dragging_x && event.y == Shape.dragging_y
if !event.respond_to?(:x) || !event.respond_to?(:y) || include_with_children?(event.x, event.y)
block.call(event)
elsif source_observation_request == 'on_drop' && Shape.drop_shape_handling_count.to_i >= drawable.drop_shapes.count
cancel_dragging!
end
end
end
widget_listener_proxy = drawable.respond_to?(:handle_observation_request) && drawable.handle_observation_request(observation_request, &shape_block)
@widget_listener_proxies ||= []
if widget_listener_proxy
@widget_listener_proxies << widget_listener_proxy
| ruby | MIT | 449cf07ada1ec965ae2ac91715ccdf22488df4ca | 2026-01-04T17:52:38.125591Z | true |
AndyObtiva/glimmer-dsl-swt | https://github.com/AndyObtiva/glimmer-dsl-swt/blob/449cf07ada1ec965ae2ac91715ccdf22488df4ca/lib/glimmer/swt/custom/refined_table.rb | lib/glimmer/swt/custom/refined_table.rb | # Copyright (c) 2007-2025 Andy Maleh
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
require 'glimmer/ui/custom_widget'
module Glimmer
module SWT
module Custom
# RefinedTable is a customization of Table with support for Filtering/Pagination
class RefinedTable
include Glimmer::UI::CustomWidget
option :per_page, default: 10
option :page, default: 0
option :model_array
option :query, default: ''
attr_accessor :filtered_model_array
attr_accessor :refined_model_array
attr_reader :table_proxy, :page_text_proxy, :first_button_proxy, :previous_button_proxy, :next_button_proxy, :last_button_proxy
before_body do
self.query ||= ''
@last_query = self.query
self.model_array ||= []
self.filtered_model_array = []
self.refined_model_array = []
end
after_body do
Glimmer::DataBinding::Observer.proc do |new_widget_bindings|
new_widget_bindings.each do |new_widget_binding|
if new_widget_binding.property.to_s == 'model_array' && !@data_bound
@data_bound = true
model_binding = new_widget_binding.model_binding
configure_sorting
observe(self, :model_array) do
clear_query_cache
filter_and_paginate
end
@table_proxy.content {
items <=> [self, :refined_model_array, model_binding.binding_options]
}
filter_and_paginate
end
end
end.observe(body_root.widget_bindings)
end
body {
composite {
text(:search, :border) {
layout_data(:fill, :center, true, false)
text <=> [self, :query, after_write: -> { filter_and_paginate }]
}
pagination
@children_owner = @table_proxy = table(*swt_style_symbols) {
layout_data(:fill, :fill, true, true)
}
}
}
def pagination
composite {
layout_data(:fill, :center, true, false)
fill_layout(:horizontal) {
margin_width 0
margin_height 0
}
@first_button_proxy = button {
text '<<'
enabled <= [self, :page, on_read: ->(value) {value > first_page}]
on_widget_selected do
self.page = first_page
filter_and_paginate
end
}
@previous_button_proxy = button {
text '<'
enabled <= [self, :page, on_read: ->(value) {value > first_page}]
on_widget_selected do
self.page -= 1
filter_and_paginate
end
}
@page_text_proxy = text(:border, :center) {
text <= [self, :page, on_read: ->(value) { "#{value} of #{page_count}" }]
on_focus_gained do
@page_text_proxy.select_all
end
on_focus_lost do
self.page = @page_text_proxy.text.to_i
filter_and_paginate
end
on_key_pressed do |key_event|
if key_event.keyCode == swt(:cr)
self.page = @page_text_proxy.text.to_i
filter_and_paginate
end
end
}
@next_button_proxy = button {
text '>'
enabled <= [self, :page, on_read: ->(value) {value < last_page}]
on_widget_selected do
self.page += 1
filter_and_paginate
end
}
@last_button_proxy = button {
text '>>'
enabled <= [self, :page, on_read: ->(value) {value < last_page}]
on_widget_selected do
self.page = last_page
filter_and_paginate
end
}
}
end
def table_block=(block)
@table_proxy.content(&block)
end
def page_text_block=(block)
@page_text_proxy.content(&block)
end
def first_button_block=(block)
@first_button_proxy.content(&block)
end
def previous_button_block=(block)
@previous_button_proxy.content(&block)
end
def next_button_block=(block)
@next_button_proxy.content(&block)
end
def last_button_block=(block)
@last_button_proxy.content(&block)
end
def page_count
(filtered_model_array && (filtered_model_array.count / per_page.to_f).ceil) || 0
end
def corrected_page(initial_page_value = nil)
correct_page = initial_page_value || page
correct_page = [correct_page, page_count].min
correct_page = [correct_page, 1].max
correct_page = (filtered_model_array&.count.to_i > 0) ? (correct_page > 0 ? correct_page : 1) : 0
correct_page
end
def first_page
(filtered_model_array&.count.to_i > 0) ? 1 : 0
end
def last_page
page_count
end
def filter_and_paginate
filter
paginate
end
def filter
new_query = query.to_s.strip
new_filtered_model_array = query_to_filtered_model_array_hash[new_query]
if new_filtered_model_array.nil?
if new_query.empty?
query_to_filtered_model_array_hash[new_query] = new_filtered_model_array = model_array.dup
else
new_filtered_model_array = model_array.select do |model|
@table_proxy.cells_for(model).any? do |cell_text|
cell_text.to_s.downcase.include?(new_query.downcase)
end
end
query_to_filtered_model_array_hash[new_query] = new_filtered_model_array
end
end
self.filtered_model_array = new_filtered_model_array
restore_query_page
@last_query = new_query
end
def paginate
self.page = corrected_page(page)
self.refined_model_array = filtered_model_array[(page - 1) * per_page, per_page]
end
def restore_query_page
new_query = query.to_s.strip
last_query = @last_query.to_s.strip
if last_query != new_query
query_to_page_hash[last_query] = page
else
query_to_page_hash[new_query] = page
end
if last_query != new_query && last_query.include?(new_query)
new_page = query_to_page_hash[new_query]
self.page = corrected_page(new_page) if new_page
end
end
def clear_query_cache
@query_to_filtered_model_array_hash = {}
@query_to_page_hash = {}
end
def query_to_filtered_model_array_hash
@query_to_filtered_model_array_hash ||= {}
end
def query_to_page_hash
@query_to_page_hash ||= {}
end
private
def configure_sorting
@table_proxy.sort_strategy = lambda do
new_sort = @table_proxy.sort_block || @table_proxy.sort_by_block || @table_proxy.sort_property
new_sort_direction = @table_proxy.sort_direction
return if new_sort == @last_sort && new_sort_direction == @last_sort_direction
array = model_array.dup
array = array.sort_by(&:hash) # this ensures consistent subsequent sorting in case there are equivalent sorts to avoid an infinite loop
# Converting value to_s first to handle nil cases. Should work with numeric, boolean, and date fields
if @table_proxy.sort_block
sorted_array = array.sort(&@table_proxy.sort_block)
elsif @table_proxy.sort_by_block
sorted_array = array.sort_by(&@table_proxy.sort_by_block)
else
sorted_array = array.sort_by do |object|
@table_proxy.sort_property.each_with_index.map do |a_sort_property, i|
value = object.send(a_sort_property)
# handle nil and difficult to compare types gracefully
if @table_proxy.sort_type[i] == Integer
value = value.to_i
elsif @table_proxy.sort_type[i] == Float
value = value.to_f
elsif @table_proxy.sort_type[i] == String
value = value.to_s
end
value
end
end
end
sorted_array = sorted_array.reverse if @table_proxy.sort_direction == :descending
self.model_array = sorted_array
@last_sort = new_sort
@last_sort_direction = new_sort_direction
end
end
end
end
end
end
| ruby | MIT | 449cf07ada1ec965ae2ac91715ccdf22488df4ca | 2026-01-04T17:52:38.125591Z | false |
AndyObtiva/glimmer-dsl-swt | https://github.com/AndyObtiva/glimmer-dsl-swt/blob/449cf07ada1ec965ae2ac91715ccdf22488df4ca/lib/glimmer/swt/custom/animation.rb | lib/glimmer/swt/custom/animation.rb | # Copyright (c) 2007-2025 Andy Maleh
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
require 'glimmer/data_binding/observable_model'
require 'glimmer/swt/properties'
require 'glimmer/swt/custom/shape'
require 'bigdecimal'
module Glimmer
module SWT
module Custom
# Represents an animation declaratively
class Animation
include Properties
include Glimmer::DataBinding::ObservableModel
class << self
def schedule_frame_animation(animation, &frame_animation_block)
frame_animation_queue(animation).prepend(frame_animation_block)
swt_display.async_exec do
frame_animation_queue(next_animation)&.pop&.call
end
end
def next_animation
animation = nil
while frame_animation_queues.values.reduce(:+)&.any? && (animation.nil? || frame_animation_queue(animation).last.nil?)
animation = frame_animation_queues.keys[next_animation_index]
frame_animation_queues.delete(animation) if frame_animation_queues.values.reduce(:+)&.any? && !animation.nil? && frame_animation_queue(animation).empty?
end
animation
end
def next_animation_index
next_schedule_index % frame_animation_queues.keys.size
end
def next_schedule_index
unless defined? @@next_schedule_index
@@next_schedule_index = 0
else
@@next_schedule_index += 1
end
end
def frame_animation_queues
unless defined? @@frame_animation_queues
@@frame_animation_queues = {}
end
@@frame_animation_queues
end
def frame_animation_queue(animation)
frame_animation_queues[animation] ||= []
end
def swt_display
unless defined? @@swt_display
@@swt_display = DisplayProxy.instance.swt_display
end
@@swt_display
end
end
attr_reader :parent, :options
attr_accessor :frame_index, :cycle, :frame_block, :every, :fps, :cycle_count, :frame_count, :started, :duration_limit, :duration, :finished, :cycle_count_index
alias current_frame_index frame_index
alias started? started
alias finished? finished
alias frame_rate fps
alias frame_rate= fps=
# TODO consider supporting an async: false option
def initialize(parent)
@parent = parent
@parent.requires_shape_disposal = true
self.started = true
self.frame_index = 0
self.cycle_count_index = 0
@start_number = 0 # denotes the number of starts (increments on every start)
self.class.swt_display # ensures initializing variable to set from GUI thread
end
def post_add_content
if @dispose_listener_registration.nil?
@dispose_listener_registration = @parent.on_widget_disposed { stop }
start if started?
end
end
def content(&block)
Glimmer::SWT::DisplayProxy.instance.auto_exec do
Glimmer::DSL::Engine.add_content(self, Glimmer::DSL::SWT::AnimationExpression.new, 'animation', &block)
end
end
# Starts an animation that is indefinite or has never been started before (i.e. having `started: false` option).
# Otherwise, resumes a stopped animation that has not been completed.
def start
return if @start_number > 0 && started?
@start_number += 1
@start_time = Time.now
@duration = 0
@original_start_time = @start_time if @duration.nil?
self.finished = false if finished?
self.started = true
# TODO track when finished in a variable for finite animations (whether by frame count, cycle count, or duration limit)
Thread.new do
start_number = @start_number
if cycle_count.is_a?(Integer) && cycle.is_a?(Array)
(cycle_count * cycle.length).times do
break unless draw_frame(start_number)
end
else
loop do
# this code has to be duplicated to break from a loop (break keyword only works when literally in a loop block)
break unless draw_frame(start_number)
end
end
end
end
def stop
return if stopped?
self.started = false
self.duration = (Time.now - @start_time) + @duration.to_f if duration_limited? && !@start_time.nil?
end
# Restarts an animation (whether indefinite or not and whether stopped or not)
def restart
@original_start_time = @start_time = Time.now
self.duration = 0
self.frame_index = 0
self.cycle_count_index = 0
stop
start
end
def stopped?
!started?
end
def finite?
frame_count_limited? || cycle_limited? || duration_limited?
end
def infinite?
!finite?
end
alias indefinite? infinite?
def has_attribute?(attribute_name, *args)
respond_to?(ruby_attribute_setter(attribute_name)) && respond_to?(ruby_attribute_getter(attribute_name))
end
def set_attribute(attribute_name, *args)
send(ruby_attribute_setter(attribute_name), *args)
end
def get_attribute(attribute_name)
send(ruby_attribute_getter(attribute_name))
end
def cycle=(*args)
if args.size == 1
if args.first.is_a?(Array)
@cycle = args.first
else
@cycle = [args.first]
end
elsif args.size > 1
@cycle = args
end
end
def cycle_count_index=(value)
@cycle_count_index = value
self.finished = true if cycle_limited? && @cycle_count_index == @cycle_count
@cycle_count_index
end
def frame_index=(value)
@frame_index = value
self.finished = true if frame_count_limited? && @frame_index == @frame_count
@frame_index
end
def duration=(value)
@duration = value
self.finished = true if surpassed_duration_limit?
@duration
end
def cycle_enabled?
@cycle.is_a?(Array)
end
def cycle_limited?
cycle_enabled? && @cycle_count.is_a?(Integer)
end
def duration_limited?
@duration_limit.is_a?(Numeric) && @duration_limit > 0
end
def frame_count_limited?
@frame_count.is_a?(Integer) && @frame_count > 0
end
def surpassed_duration_limit?
duration_limited? && ((Time.now - @start_time) > @duration_limit)
end
def within_duration_limit?
!surpassed_duration_limit?
end
private
# Returns true on success of painting a frame and false otherwise
def draw_frame(start_number)
if stopped? or
(start_number != @start_number) or
(frame_count_limited? && @frame_index == @frame_count) or
(cycle_limited? && @cycle_count_index == @cycle_count) or
surpassed_duration_limit?
self.duration = Time.now - @start_time
return false
end
block_args = [@frame_index]
block_args << @cycle[@frame_index % @cycle.length] if cycle_enabled?
current_frame_index = @frame_index
current_cycle_count_index = @cycle_count_index
self.class.schedule_frame_animation(self) do
self.duration = Time.now - @start_time # TODO should this be set here, after the if statement, in the else too, or outside both?
if started? && start_number == @start_number && within_duration_limit?
unless @parent.isDisposed
@shapes.to_a.each(&:dispose)
parent_shapes_before = @parent.shapes.clone
@parent.content {
frame_block.call(*block_args)
}
@shapes = @parent.shapes - parent_shapes_before
self.duration = Time.now - @start_time # TODO consider if this is needed
end
else
if stopped? && @frame_index > current_frame_index
self.frame_index = current_frame_index
self.cycle_count_index = current_cycle_count_index
end
end
end
self.frame_index += 1
self.cycle_count_index += 1 if cycle_limited? && (@frame_index % @cycle&.length&.to_i) == 0
# TODO consider using timer_exec as a perhaps more reliable alternative
if every.is_a?(Numeric) && every > 0
sleep(every)
elsif fps.is_a?(Numeric) && fps > 0
sleep((BigDecimal(1.0.to_s) / BigDecimal(fps.to_f.to_s)).to_f)
end
true
rescue => e
Glimmer::Config.logger.error {e}
false
end
end
end
end
end
| ruby | MIT | 449cf07ada1ec965ae2ac91715ccdf22488df4ca | 2026-01-04T17:52:38.125591Z | false |
AndyObtiva/glimmer-dsl-swt | https://github.com/AndyObtiva/glimmer-dsl-swt/blob/449cf07ada1ec965ae2ac91715ccdf22488df4ca/lib/glimmer/swt/custom/radio_group.rb | lib/glimmer/swt/custom/radio_group.rb | # Copyright (c) 2007-2025 Andy Maleh
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
require 'glimmer/ui/custom_widget'
module Glimmer
module SWT
module Custom
# A custom widget rendering a group of radios generated via data-binding
class RadioGroup
include Glimmer::UI::CustomWidget
body {
composite {} # just an empty composite to hold radios upon data-binding `selection`
}
def items=(text_array)
selection_value = selection
@items = Array[*text_array]
build_radios
end
def items
@items || []
end
alias get_items items
def selection=(text)
radios.count.times do |index|
radio = radios[index]
item = items[index]
radio.selection = item == text
end
end
def selection
selection_value = labels[selection_index]&.text unless selection_index == -1
selection_value.to_s
end
def selection_index=(index)
self.selection=(items[index])
end
alias select selection_index=
def selection_index
radios.index(radios.detect(&:selection)) || -1
end
def radios
@radios ||= []
end
def labels
@labels ||= []
end
def can_handle_observation_request?(observation_request)
radios.first&.can_handle_observation_request?(observation_request) or
super(observation_request)
end
def handle_observation_request(observation_request, &block)
observation_requests << [observation_request, block]
delegate_observation_request_to_radios(observation_request, &block)
super
end
def delegate_observation_request_to_radios(observation_request, &block)
if observation_request != 'on_widget_disposed'
radios.count.times do |index|
radio = radios[index]
label = labels[index]
if observation_request == 'on_widget_selected'
radio_block = lambda do |event|
if event.widget.selection || selection_index == -1
event.widget = self.swt_widget
block.call(event)
end
end
label_block = lambda do |event|
self.selection_index = index
block.call(event)
end
radio.handle_observation_request(observation_request, &radio_block) if radio.can_handle_observation_request?(observation_request)
label.handle_observation_request('on_mouse_up', &label_block)
else
listener_block = lambda do |event|
event.widget = self.swt_widget
block.call(event)
end
radio.handle_observation_request(observation_request, &listener_block) if radio.can_handle_observation_request?(observation_request)
label.handle_observation_request(observation_request, &listener_block) if label.can_handle_observation_request?(observation_request)
end
end
end
end
def observation_requests
@observation_requests ||= Set.new
end
def has_attribute?(attribute_name, *args)
(@composites.to_a + @radios.to_a + @labels.to_a).map do |widget_proxy|
return true if widget_proxy.has_attribute?(attribute_name, *args)
end
super
end
def set_attribute(attribute_name, *args)
excluded_attributes = ['selection']
unless excluded_attributes.include?(attribute_name.to_s)
(@composites.to_a + @radios.to_a + @labels.to_a).each do |widget_proxy|
widget_proxy.set_attribute(attribute_name, *args) if widget_proxy.has_attribute?(attribute_name, *args)
end
end
super
end
private
def build_radios
current_selection = selection
@composites.to_a.each(&:dispose)
@radios = []
@labels = []
@composites = []
items.each do |item|
body_root.content {
@composites << composite {
grid_layout(2, false) {
margin_width 0
margin_height 0
horizontal_spacing 0
vertical_spacing 0
}
radios << radio { |radio_proxy|
on_widget_selected {
self.selection = items[radios.index(radio_proxy)]
}
}
labels << label { |label_proxy|
layout_data :fill, :center, true, false
text item
on_mouse_up {
self.selection = label_proxy.text
}
}
}
}
end
observation_requests.to_a.each do |observation_request, block|
delegate_observation_request_to_radios(observation_request, &block)
end
self.selection = current_selection
end
end
end
end
end
| ruby | MIT | 449cf07ada1ec965ae2ac91715ccdf22488df4ca | 2026-01-04T17:52:38.125591Z | false |
AndyObtiva/glimmer-dsl-swt | https://github.com/AndyObtiva/glimmer-dsl-swt/blob/449cf07ada1ec965ae2ac91715ccdf22488df4ca/lib/glimmer/swt/custom/shape/path.rb | lib/glimmer/swt/custom/shape/path.rb | # Copyright (c) 2007-2025 Andy Maleh
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
require 'glimmer/swt/custom/shape'
require 'glimmer/swt/custom/shape/path_segment'
require 'glimmer/swt/swt_proxy'
require 'glimmer/swt/display_proxy'
require 'glimmer/swt/color_proxy'
require 'glimmer/swt/font_proxy'
require 'glimmer/swt/display_proxy'
module Glimmer
module SWT
module Custom
class Shape
# Represents a path to be drawn on a control/widget/canvas/display
# That is because Shape is drawn on a parent as graphics and doesn't have an SWT widget for itself
# swt_path is not guaranteed to have any object in it till after rendering
class Path < Shape
include PathSegment # a path may behave as a path segment in another path
attr_reader :swt_path, :path_segments
attr_accessor :calculated_path_args
def initialize(parent, keyword, *args, &property_block)
super
@path_segments = []
@uncalculated_path_segments = []
end
def parameter_names
[:swt_path]
end
def add_shape(shape)
if shape.is_a?(PathSegment)
Glimmer::SWT::DisplayProxy.instance.auto_exec do
@path_segments << shape
@uncalculated_path_segments << shape
end
else
super
end
end
def contain?(x, y)
include?(x, y, filled: true)
end
# checks if drawn or filled rectangle includes the point denoted by x and y (if drawn, it only returns true if point lies on the edge)
def include?(x, y, filled: nil)
x, y = inverse_transform_point(x, y)
filled = filled? if filled.nil?
makeshift_gc = org.eclipse.swt.graphics.GC.new(Glimmer::SWT::DisplayProxy.instance.swt_display)
@swt_path.contains(x.to_f, y.to_f, makeshift_gc, !filled)
end
def irregular?
true
end
def post_dispose_content(path_segment)
Glimmer::SWT::DisplayProxy.instance.auto_exec do
@path_segments.delete(path_segment)
@uncalculated_path_segments = @path_segments.dup
@swt_path&.dispose
@swt_path = nil
@args = []
calculated_args_changed!(children: false)
end
end
def clear
Glimmer::SWT::DisplayProxy.instance.auto_exec do
@path_segments.each { |path_segments| path_segments.class == Path && path_segments.dispose }
@path_segments.clear
@uncalculated_path_segments = @path_segments.dup
@swt_path&.dispose
@swt_path = nil
@args = []
calculated_args_changed!(children: false)
drawable.redraw unless drawable.is_a?(ImageProxy)
end
end
def dispose(dispose_images: true, dispose_patterns: true, redraw: true)
Glimmer::SWT::DisplayProxy.instance.auto_exec do
clear if self.class == Path
super(dispose_images: dispose_images, dispose_patterns: dispose_patterns, redraw: redraw) if (parent.is_a?(Shape) && (!parent.is_a?(PathSegment) || !parent.part_of_path?)) || parent.is_a?(Drawable)
end
end
def calculate_args!
new_swt_path = @swt_path.nil? || !@calculated_paint_args || !@calculated_path_args
if new_swt_path
Glimmer::SWT::DisplayProxy.instance.auto_exec do
@swt_path&.dispose
@swt_path = org.eclipse.swt.graphics.Path.new(Glimmer::SWT::DisplayProxy.instance.swt_display)
@uncalculated_path_segments = @path_segments.dup
end
end
# TODO recreate @swt_path only if one of the children get disposed (must notify parent on dispose)
@args = [@swt_path]
@uncalculated_path_segments.dup.each do |path_segment|
Glimmer::SWT::DisplayProxy.instance.auto_exec do
path_segment.add_to_swt_path(@swt_path)
@uncalculated_path_segments.delete(path_segment)
end
end
@calculated_path_args = true
if new_swt_path
@path_calculated_args = super
else
@path_calculated_args
end
rescue => e
Glimmer::Config.logger.error {e.full_message}
@args
end
def move_by(x_delta, y_delta)
@path_segments.each {|path_segment| path_segment.move_by(x_delta, y_delta)}
end
def bounds
if @path_segments != @bounds_path_segments
@bounds_path_segments = @path_segments
shape_bounds = geometry.getBounds2D
@bounds = org.eclipse.swt.graphics.Rectangle.new(shape_bounds.x, shape_bounds.y, shape_bounds.width, shape_bounds.height)
end
@bounds
end
def size
if @path_segments != @size_path_segments
@size_path_segments = @path_segments
shape_bounds = geometry.getBounds2D
@size = org.eclipse.swt.graphics.Point.new(shape_bounds.width, shape_bounds.height)
end
@size
end
# Logical x coordinate relative to parent
def x
x_value = bounds.x
x_value -= parent.absolute_x if parent.is_a?(Shape)
x_value
end
# Logical y coordinate relative to parent
def y
y_value = bounds.y
y_value -= parent.absolute_y if parent.is_a?(Shape)
y_value
end
def width
size.x
end
def height
size.y
end
def geometry
if @path_segments != @geometry_path_segments
@geometry_path_segments = @path_segments
@geometry = Java::JavaAwtGeom::Path2D::Double.new
@path_segments.each do |path_segment|
path_segment.add_to_geometry(@geometry)
end
end
@geometry
end
def path_segment_method_name
'addPath'
end
def path_segment_args
@args
end
def path_segment_geometry_method_name
if self.class == Path
'append'
else
super
end
end
def path_segment_geometry_args
if self.class == Path
# TODO consider supporting connected true instead of false (2nd arg)
[geometry, false]
else
super
end
end
def eql?(other)
(other.class == Path) && geometry.equals(other && other.respond_to?(:geometry) && other.geometry)
end
alias == eql?
def hash
geometry.hashCode
end
end
end
end
end
end
| ruby | MIT | 449cf07ada1ec965ae2ac91715ccdf22488df4ca | 2026-01-04T17:52:38.125591Z | false |
AndyObtiva/glimmer-dsl-swt | https://github.com/AndyObtiva/glimmer-dsl-swt/blob/449cf07ada1ec965ae2ac91715ccdf22488df4ca/lib/glimmer/swt/custom/shape/cubic.rb | lib/glimmer/swt/custom/shape/cubic.rb | # Copyright (c) 2007-2025 Andy Maleh
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
require 'glimmer/swt/custom/shape'
require 'glimmer/swt/custom/shape/path'
require 'glimmer/swt/custom/shape/path_segment'
require 'glimmer/swt/swt_proxy'
require 'glimmer/swt/display_proxy'
require 'glimmer/swt/color_proxy'
require 'glimmer/swt/font_proxy'
require 'glimmer/swt/transform_proxy'
module Glimmer
module SWT
module Custom
# Represents a shape (graphics) to be drawn on a control/widget/canvas/display
# That is because Shape is drawn on a parent as graphics and doesn't have an SWT widget for itself
class Shape
class Cubic < Path
def parameter_names
[:point_array]
end
def geometry
the_point_array = point_array
if the_point_array != @geometry_point_array
@geometry_point_array = the_point_array
@geometry = Java::JavaAwtGeom::Path2D::Double.new
add_to_geometry(@geometry)
end
@geometry
end
def contain?(x, y)
include?(x, y, filled: true)
end
# checks if drawn or filled rectangle includes the point denoted by x and y (if drawn, it only returns true if point lies on the edge)
def include?(x, y, filled: nil)
x, y = inverse_transform_point(x, y)
filled = filled? if filled.nil?
makeshift_gc = org.eclipse.swt.graphics.GC.new(Glimmer::SWT::DisplayProxy.instance.swt_display)
swt_path = org.eclipse.swt.graphics.Path.new(Glimmer::SWT::DisplayProxy.instance.swt_display)
the_path_segment_args = path_segment_args.dup
if previous_point_connected?
the_previous_path_segment = previous_path_segment
swt_path.moveTo(the_previous_path_segment.x, the_previous_path_segment.y)
else
swt_path.moveTo(the_path_segment_args.shift, the_path_segment_args.shift)
end
swt_path.curveTo(*the_path_segment_args)
swt_path.contains(x.to_f, y.to_f, makeshift_gc, !filled)
ensure
swt_path.dispose
end
def move_by(x_delta, y_delta)
the_point_array = @args.compact
the_point_array = the_point_array.first if the_point_array.first.is_a?(Array)
self.point_array = the_point_array.each_with_index.map {|coordinate, i| i.even? ? coordinate + x_delta : coordinate + y_delta}
end
def path_segment_method_name
'cubicTo'
end
def path_segment_args
# TODO make args auto-infer control points if previous_point_connected is true or if there is only a point_array with 1 point
@args.to_a
end
def default_path_segment_arg_count
8
end
def default_connected_path_segment_arg_count
6
end
def path_segment_geometry_method_name
'curveTo'
end
def previous_point_connected?
@args.compact.count == 6 && !first_path_segment?
end
def eql?(other)
other.is_a?(Cubic) && point_array == (other && other.respond_to?(:point_array) && other.point_array)
end
alias == eql?
def hash
point_array.hash
end
end
end
end
end
end
| ruby | MIT | 449cf07ada1ec965ae2ac91715ccdf22488df4ca | 2026-01-04T17:52:38.125591Z | false |
AndyObtiva/glimmer-dsl-swt | https://github.com/AndyObtiva/glimmer-dsl-swt/blob/449cf07ada1ec965ae2ac91715ccdf22488df4ca/lib/glimmer/swt/custom/shape/text.rb | lib/glimmer/swt/custom/shape/text.rb | # Copyright (c) 2007-2025 Andy Maleh
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
require 'glimmer/swt/custom/shape'
require 'glimmer/swt/swt_proxy'
require 'glimmer/swt/display_proxy'
require 'glimmer/swt/color_proxy'
require 'glimmer/swt/font_proxy'
require 'glimmer/swt/transform_proxy'
module Glimmer
module SWT
module Custom
# Represents a shape (graphics) to be drawn on a control/widget/canvas/display
# That is because Shape is drawn on a parent as graphics and doesn't have an SWT widget for itself
class Shape
class Text < Shape
def parameter_names
@parameter_names || text_parameter_names
end
def possible_parameter_names
# TODO refactor and improve this method through meta-programming (and share across other shapes)
(text_parameter_names + text_transparent_parameter_names + text_flags_parameter_names).uniq
end
def text_parameter_names
[:string, :x, :y]
end
def text_transparent_parameter_names
[:string, :x, :y, :is_transparent]
end
def text_flags_parameter_names
[:string, :x, :y, :flags]
end
def set_parameter_attribute(attribute_name, *args)
return super if @parameter_names.to_a.map(&:to_s).include?(attribute_name.to_s)
if text_parameter_names.map(&:to_s).include?(attribute_name.to_s)
@parameter_names = text_parameter_names
elsif text_transparent_parameter_names.map(&:to_s).include?(attribute_name.to_s)
@parameter_names = text_transparent_parameter_names
elsif text_flags_parameter_names.map(&:to_s).include?(attribute_name.to_s)
@parameter_names = text_flags_parameter_names
end
super
end
def width
@extent&.x
end
def height
@extent&.y
end
end
String = Text
end
end
end
end
| ruby | MIT | 449cf07ada1ec965ae2ac91715ccdf22488df4ca | 2026-01-04T17:52:38.125591Z | false |
AndyObtiva/glimmer-dsl-swt | https://github.com/AndyObtiva/glimmer-dsl-swt/blob/449cf07ada1ec965ae2ac91715ccdf22488df4ca/lib/glimmer/swt/custom/shape/line.rb | lib/glimmer/swt/custom/shape/line.rb | # Copyright (c) 2007-2025 Andy Maleh
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
require 'glimmer/swt/custom/shape'
require 'glimmer/swt/custom/shape/path_segment'
require 'glimmer/swt/swt_proxy'
require 'glimmer/swt/display_proxy'
require 'glimmer/swt/color_proxy'
require 'glimmer/swt/font_proxy'
require 'glimmer/swt/transform_proxy'
module Glimmer
module SWT
module Custom
# Represents a shape (graphics) to be drawn on a control/widget/canvas/display
# That is because Shape is drawn on a parent as graphics and doesn't have an SWT widget for itself
class Shape
class Line < Shape
include PathSegment
class << self
def include?(x1, y1, x2, y2, x, y)
distance1 = Math.sqrt((x - x1)**2 + (y - y1)**2)
distance2 = Math.sqrt((x2 - x)**2 + (y2 - y)**2)
distance = Math.sqrt((x2 - x1)**2 + (y2 - y1)**2)
(distance1 + distance2).to_i == distance.to_i
end
end
def parameter_names
[:x1, :y1, :x2, :y2]
end
def location_parameter_names
parameter_names
end
def bounds
shape_bounds = geometry.getBounds2D
org.eclipse.swt.graphics.Rectangle.new(shape_bounds.x, shape_bounds.y, shape_bounds.width, shape_bounds.height)
end
def size
shape_bounds = geometry.getBounds2D
org.eclipse.swt.graphics.Point.new(shape_bounds.width, shape_bounds.height)
end
def geometry
java.awt.geom.Line2D::Double.new(absolute_x1, absolute_y1, absolute_x2, absolute_y2)
end
# Logical x coordinate relative to parent
def x
x_value = bounds.x
x_value -= parent.absolute_x if parent.is_a?(Shape) && parent.class != Shape
x_value
end
# Logical y coordinate relative to parent
def y
y_value = bounds.y
y_value -= parent.absolute_y if parent.is_a?(Shape) && parent.class != Shape
y_value
end
def width
size.x
end
def height
size.y
end
def absolute_x1
if parent.is_a?(Shape) && parent.class != Shape
parent.absolute_x + x1
else
x1
end
end
def absolute_y1
if parent.is_a?(Shape) && parent.class != Shape
parent.absolute_y + y1
else
y1
end
end
def absolute_x2
if parent.is_a?(Shape) && parent.class != Shape
parent.absolute_x + x2.to_f
else
x2
end
end
def absolute_y2
if parent.is_a?(Shape) && parent.class != Shape
parent.absolute_y + y2.to_f
else
y2
end
end
def include?(x, y)
x, y = inverse_transform_point(x, y)
# TODO must account for line width
Line.include?(absolute_x1, absolute_y1, absolute_x2, absolute_y2, x, y)
end
alias contain? include?
def move_by(x_delta, y_delta)
self.x1 += x_delta
self.y1 += y_delta
self.x2 += x_delta
self.y2 += y_delta
end
def irregular?
true
end
def path_segment_method_name
'lineTo'
end
def path_segment_args
# TODO make args auto-infer first point if previous_point_connected is true or if there is only x1,y1 or x2,y2 (but not both), or if there is an x, y, or if there is a point_array with 1 point
@args
end
def default_path_segment_arg_count
4
end
def default_connected_path_segment_arg_count
2
end
def path_segment_geometry_args
# TODO make args auto-infer first point if previous_point_connected is true or if there is only x1,y1 or x2,y2 (but not both), or if there is an x, y, or if there is a point_array with 1 point
@args
end
def previous_point_connected?
@args.compact.count == 2 && !first_path_segment?
end
def eql?(other)
other.is_a?(Line) &&
x1 == (other && other.respond_to?(:x1) && other.x1) &&
y1 == (other && other.respond_to?(:y1) && other.y1) &&
x2 == (other && other.respond_to?(:x2) && other.x2) &&
y2 == (other && other.respond_to?(:y2) && other.y2)
end
alias == eql?
def hash
[x1, y1, x2, y2].hash
end
end
end
end
end
end
| ruby | MIT | 449cf07ada1ec965ae2ac91715ccdf22488df4ca | 2026-01-04T17:52:38.125591Z | false |
AndyObtiva/glimmer-dsl-swt | https://github.com/AndyObtiva/glimmer-dsl-swt/blob/449cf07ada1ec965ae2ac91715ccdf22488df4ca/lib/glimmer/swt/custom/shape/arc.rb | lib/glimmer/swt/custom/shape/arc.rb | # Copyright (c) 2007-2025 Andy Maleh
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
require 'glimmer/swt/custom/shape'
require 'glimmer/swt/swt_proxy'
require 'glimmer/swt/display_proxy'
require 'glimmer/swt/color_proxy'
require 'glimmer/swt/font_proxy'
require 'glimmer/swt/transform_proxy'
module Glimmer
module SWT
module Custom
# Represents a shape (graphics) to be drawn on a control/widget/canvas/display
# That is because Shape is drawn on a parent as graphics and doesn't have an SWT widget for itself
class Shape
class Arc < Shape
def parameter_names
[:x, :y, :width, :height, :start_angle, :arc_angle]
end
def bounds
shape_bounds = geometry.getBounds2D
org.eclipse.swt.graphics.Rectangle.new(shape_bounds.x, shape_bounds.y, shape_bounds.width, shape_bounds.height)
end
def size
shape_bounds = geometry.getBounds2D
org.eclipse.swt.graphics.Point.new(shape_bounds.width, shape_bounds.height)
end
def geometry
java.awt.geom.Arc2D::Double.new(self.absolute_x, self.absolute_y, calculated_width, calculated_height, start_angle, arc_angle, java.awt.geom.Arc2D::PIE)
end
# checks if shape contains the point denoted by x and y
def contain?(x, y)
x, y = inverse_transform_point(x, y)
geometry.contains(x, y)
end
def include?(x, y)
if filled?
contain?(x, y)
else
x, y = inverse_transform_point(x, y)
# give it some fuzz to allow a larger region around the drawn oval to accept including a point (helps with mouse clickability on a shape)
outer_shape_geometry = java.awt.geom.Arc2D::Double.new(self.absolute_x, self.absolute_y, calculated_width + 3, calculated_height + 3, start_angle, arc_angle, java.awt.geom.Arc2D::PIE)
inner_shape_geometry = java.awt.geom.Arc2D::Double.new(self.absolute_x, self.absolute_y, calculated_width - 3, calculated_height - 3, start_angle, arc_angle, java.awt.geom.Arc2D::PIE)
outer_shape_geometry.contains(x, y) && !inner_shape_geometry.contains(x, y)
end
end
def irregular?
true
end
end
end
end
end
end
| ruby | MIT | 449cf07ada1ec965ae2ac91715ccdf22488df4ca | 2026-01-04T17:52:38.125591Z | false |
AndyObtiva/glimmer-dsl-swt | https://github.com/AndyObtiva/glimmer-dsl-swt/blob/449cf07ada1ec965ae2ac91715ccdf22488df4ca/lib/glimmer/swt/custom/shape/oval.rb | lib/glimmer/swt/custom/shape/oval.rb | # Copyright (c) 2007-2025 Andy Maleh
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
require 'glimmer/swt/custom/shape'
require 'glimmer/swt/swt_proxy'
require 'glimmer/swt/display_proxy'
require 'glimmer/swt/color_proxy'
require 'glimmer/swt/font_proxy'
require 'glimmer/swt/transform_proxy'
module Glimmer
module SWT
module Custom
# Represents a shape (graphics) to be drawn on a control/widget/canvas/display
# That is because Shape is drawn on a parent as graphics and doesn't have an SWT widget for itself
class Shape
class Oval < Shape
# checks if shape contains the point denoted by x and y
def contain?(x, y)
x, y = inverse_transform_point(x, y)
shape_geometry = java.awt.geom.Ellipse2D::Double.new(self.absolute_x, self.absolute_y, calculated_width, calculated_height)
shape_geometry.contains(x, y)
end
# checks if drawn or filled oval includes the point denoted by x and y (if drawn, it only returns true if point lies on the edge)
def include?(x, y)
if filled?
contain?(x, y)
else
x, y = inverse_transform_point(x, y)
# give it some fuzz to allow a larger region around the drawn oval to accept including a point (helps with mouse clickability on a shape)
outer_shape_geometry = java.awt.geom.Ellipse2D::Double.new(self.absolute_x - 3, self.absolute_y - 3, calculated_width + 6, calculated_height + 6)
inner_shape_geometry = java.awt.geom.Ellipse2D::Double.new(self.absolute_x + 3, self.absolute_y + 3, calculated_width - 6, calculated_height - 6)
outer_shape_geometry.contains(x, y) && !inner_shape_geometry.contains(x, y)
end
end
end
end
end
end
end
| ruby | MIT | 449cf07ada1ec965ae2ac91715ccdf22488df4ca | 2026-01-04T17:52:38.125591Z | false |
AndyObtiva/glimmer-dsl-swt | https://github.com/AndyObtiva/glimmer-dsl-swt/blob/449cf07ada1ec965ae2ac91715ccdf22488df4ca/lib/glimmer/swt/custom/shape/point.rb | lib/glimmer/swt/custom/shape/point.rb | # Copyright (c) 2007-2025 Andy Maleh
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
require 'glimmer/swt/custom/shape'
require 'glimmer/swt/custom/shape/path_segment'
require 'glimmer/swt/swt_proxy'
require 'glimmer/swt/display_proxy'
require 'glimmer/swt/color_proxy'
require 'glimmer/swt/font_proxy'
require 'glimmer/swt/transform_proxy'
module Glimmer
module SWT
module Custom
# Represents a shape (graphics) to be drawn on a control/widget/canvas/display
# That is because Shape is drawn on a parent as graphics and doesn't have an SWT widget for itself
class Shape
class Point < Shape
include PathSegment
def parameter_names
[:x, :y]
end
def width
1
end
def height
1
end
def include?(x, y)
x, y = inverse_transform_point(x, y)
# give it some fuzz (helps makes mouse clicking easier)
x.to_i.between?(self.absolute_x.to_i - 2, self.absolute_x.to_i + 2) && y.to_i.between?(self.absolute_y.to_i - 2, self.absolute_y.to_i + 2)
end
def contain?(x, y)
include?(x, y)
end
def bounds_contain?(x, y)
include?(x, y)
end
def path_segment_method_name
'addRectangle'
end
def path_segment_args
@args + [1, 1]
end
def path_segment_geometry_method_name
'moveTo'
end
def path_segment_geometry_args
@args
end
def previous_point_connected?
false
end
def eql?(other)
other.is_a?(Point) && x == (other && other.respond_to?(:x) && other.x) && y == (other && other.respond_to?(:y) && other.y)
end
alias == eql?
def hash
[x, y].hash
end
end
end
end
end
end
| ruby | MIT | 449cf07ada1ec965ae2ac91715ccdf22488df4ca | 2026-01-04T17:52:38.125591Z | false |
AndyObtiva/glimmer-dsl-swt | https://github.com/AndyObtiva/glimmer-dsl-swt/blob/449cf07ada1ec965ae2ac91715ccdf22488df4ca/lib/glimmer/swt/custom/shape/polygon.rb | lib/glimmer/swt/custom/shape/polygon.rb | # Copyright (c) 2007-2025 Andy Maleh
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
require 'glimmer/swt/custom/shape'
require 'glimmer/swt/swt_proxy'
require 'glimmer/swt/display_proxy'
require 'glimmer/swt/color_proxy'
require 'glimmer/swt/font_proxy'
require 'glimmer/swt/transform_proxy'
module Glimmer
module SWT
module Custom
# Represents a shape (graphics) to be drawn on a control/widget/canvas/display
# That is because Shape is drawn on a parent as graphics and doesn't have an SWT widget for itself
class Shape
class Polygon < Shape
def parameter_names
[:point_array]
end
def location_parameter_names
parameter_names
end
def point_count
point_array.count / 2
end
def [](index)
index = 0 if index == point_count
org.eclipse.swt.graphics.Point.new(point_array[index * 2], point_array[index * 2 + 1])
end
def x_array
point_array.each_with_index.select {|pair| pair.last.even?}.map(&:first)
end
def y_array
point_array.each_with_index.select {|pair| pair.last.odd?}.map(&:first)
end
def point_xy_array
x_array.zip(y_array)
end
def absolute_point_array
if parent.is_a?(Shape)
point_array.each_with_index.map do |coordinate, i|
if i.even?
parent.absolute_x + coordinate
else
parent.absolute_y + coordinate
end
end
else
point_array
end
end
def absolute_x_array
absolute_point_array.each_with_index.select {|pair| pair.last.even?}.map(&:first)
end
def absolute_y_array
absolute_point_array.each_with_index.select {|pair| pair.last.odd?}.map(&:first)
end
def absolute_point_xy_array
absolute_x_array.zip(absolute_y_array)
end
def bounds
the_point_array = point_array
if the_point_array != @bounds_point_array
@bounds_point_array = point_array
shape_bounds = geometry.getBounds2D
@bounds = org.eclipse.swt.graphics.Rectangle.new(shape_bounds.x, shape_bounds.y, shape_bounds.width, shape_bounds.height)
end
@bounds
end
def size
the_point_array = point_array
if the_point_array != @size_point_array
@size_point_array = point_array
shape_bounds = geometry.getBounds2D
@size = org.eclipse.swt.graphics.Point.new(shape_bounds.width, shape_bounds.height)
end
@size
end
def geometry
the_point_array = point_array
if the_point_array != @geometry_point_array
@geometry_point_array = point_array
@geometry = java.awt.Polygon.new(absolute_x_array.to_java(:int), absolute_y_array.to_java(:int), point_count)
end
@geometry
end
# Logical x coordinate relative to parent
def x
x_dependencies = [bounds.x, parent.is_a?(Shape) && parent.absolute_x]
if x_dependencies != @x_dependencies
# avoid recalculating values
bounds_x, parent_absolute_x = @x_dependencies = x_dependencies
x_value = bounds_x
x_value -= parent_absolute_x if parent.is_a?(Shape)
@x = x_value
end
@x
end
# Logical y coordinate relative to parent
def y
y_dependencies = [bounds.y, parent.is_a?(Shape) && parent.absolute_y]
if y_dependencies != @y_dependencies
# avoid recalculating values
bounds_y, parent_absolute_y = @y_dependencies = y_dependencies
y_value = bounds_y
y_value -= parent_absolute_y if parent.is_a?(Shape)
@y = y_value
end
@y
end
def width
size.x
end
def height
size.y
end
def contain?(x, y)
x, y = inverse_transform_point(x, y)
geometry.contains(x, y)
end
def include?(x, y)
if filled?
contain?(x, y)
else
x, y = inverse_transform_point(x, y)
comparison_lines = absolute_point_xy_array.zip(absolute_point_xy_array.rotate(1))
comparison_lines.any? {|line| Line.include?(line.first.first, line.first.last, line.last.first, line.last.last, x, y)}
end
end
def move_by(x_delta, y_delta)
self.point_array = point_array.each_with_index.map {|coordinate, i| i.even? ? coordinate + x_delta : coordinate + y_delta}
end
def irregular?
true
end
end
end
end
end
end
| ruby | MIT | 449cf07ada1ec965ae2ac91715ccdf22488df4ca | 2026-01-04T17:52:38.125591Z | false |
AndyObtiva/glimmer-dsl-swt | https://github.com/AndyObtiva/glimmer-dsl-swt/blob/449cf07ada1ec965ae2ac91715ccdf22488df4ca/lib/glimmer/swt/custom/shape/quad.rb | lib/glimmer/swt/custom/shape/quad.rb | # Copyright (c) 2007-2025 Andy Maleh
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
require 'glimmer/swt/custom/shape'
require 'glimmer/swt/custom/shape/path'
require 'glimmer/swt/custom/shape/path_segment'
require 'glimmer/swt/swt_proxy'
require 'glimmer/swt/display_proxy'
require 'glimmer/swt/color_proxy'
require 'glimmer/swt/font_proxy'
require 'glimmer/swt/transform_proxy'
module Glimmer
module SWT
module Custom
# Represents a shape (graphics) to be drawn on a control/widget/canvas/display
# That is because Shape is drawn on a parent as graphics and doesn't have an SWT widget for itself
class Shape
class Quad < Path
def parameter_names
[:point_array]
end
def geometry
the_point_array = point_array
if the_point_array != @geometry_point_array
@geometry_point_array = the_point_array
@geometry = Java::JavaAwtGeom::Path2D::Double.new
add_to_geometry(@geometry)
end
@geometry
end
def contain?(x, y)
include?(x, y, filled: true)
end
# checks if drawn or filled rectangle includes the point denoted by x and y (if drawn, it only returns true if point lies on the edge)
def include?(x, y, filled: nil)
filled = filled? if filled.nil?
makeshift_gc = org.eclipse.swt.graphics.GC.new(Glimmer::SWT::DisplayProxy.instance.swt_display)
swt_path = org.eclipse.swt.graphics.Path.new(Glimmer::SWT::DisplayProxy.instance.swt_display)
the_path_segment_args = path_segment_args.dup
if previous_point_connected?
the_previous_path_segment = previous_path_segment
swt_path.moveTo(the_previous_path_segment.x, the_previous_path_segment.y)
else
swt_path.moveTo(the_path_segment_args.shift, the_path_segment_args.shift)
end
swt_path.quadTo(*the_path_segment_args)
swt_path.contains(x.to_f, y.to_f, makeshift_gc, !filled)
ensure
swt_path.dispose
end
def move_by(x_delta, y_delta)
the_point_array = @args.compact
the_point_array = the_point_array.first if the_point_array.first.is_a?(Array)
self.point_array = the_point_array.each_with_index.map {|coordinate, i| i.even? ? coordinate + x_delta : coordinate + y_delta}
end
def path_segment_method_name
'quadTo'
end
def path_segment_args
# TODO make args auto-infer control points if previous_point_connected is true or if there is only a point_array with 1 point
@args
end
def default_path_segment_arg_count
6
end
def default_connected_path_segment_arg_count
4
end
def previous_point_connected?
@args.compact.count == 4 && !first_path_segment?
end
def eql?(other)
other.is_a?(Quad) && point_array == (other && other.respond_to?(:point_array) && other.point_array)
end
alias == eql?
def hash
point_array.hash
end
end
end
end
end
end
| ruby | MIT | 449cf07ada1ec965ae2ac91715ccdf22488df4ca | 2026-01-04T17:52:38.125591Z | false |
AndyObtiva/glimmer-dsl-swt | https://github.com/AndyObtiva/glimmer-dsl-swt/blob/449cf07ada1ec965ae2ac91715ccdf22488df4ca/lib/glimmer/swt/custom/shape/rectangle.rb | lib/glimmer/swt/custom/shape/rectangle.rb | # Copyright (c) 2007-2025 Andy Maleh
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
require 'glimmer/swt/custom/shape'
require 'glimmer/swt/swt_proxy'
require 'glimmer/swt/display_proxy'
require 'glimmer/swt/color_proxy'
require 'glimmer/swt/transform_proxy'
module Glimmer
module SWT
module Custom
# Represents a shape (graphics) to be drawn on a control/widget/canvas/display
# That is because Shape is drawn on a parent as graphics and doesn't have an SWT widget for itself
class Shape
class Rectangle < Shape
def parameter_names
@parameter_names || rectangle_parameter_names
end
def possible_parameter_names
# TODO refactor and improve this method through meta-programming (and share across other shapes)
(rectangle_round_parameter_names + rectangle_gradient_parameter_names + rectangle_parameter_names + rectangle_rectangle_parameter_names).uniq
end
def rectangle_round_parameter_names
[:x, :y, :width, :height, :arc_width, :arc_height]
end
def rectangle_gradient_parameter_names
[:x, :y, :width, :height, :vertical]
end
def rectangle_parameter_names
[:x, :y, :width, :height]
end
def rectangle_rectangle_parameter_names
# this receives a Rectangle object
[:rectangle]
end
def set_parameter_attribute(attribute_name, *args)
return super if @parameter_names.to_a.map(&:to_s).include?(attribute_name.to_s)
if rectangle_parameter_names.map(&:to_s).include?(attribute_name.to_s)
@parameter_names = rectangle_parameter_names
elsif rectangle_round_parameter_names.map(&:to_s).include?(attribute_name.to_s)
@parameter_names = rectangle_round_parameter_names
elsif rectangle_gradient_parameter_names.map(&:to_s).include?(attribute_name.to_s)
@parameter_names = rectangle_gradient_parameter_names
elsif rectangle_rectangle_parameter_names.map(&:to_s).include?(attribute_name.to_s)
@parameter_names = rectangle_rectangle_parameter_names
end
super
end
def point_xy_array
[[x, y], [x + calculated_width, y], [x + calculated_width, y + calculated_height], [x, y + calculated_height]]
end
def absolute_point_xy_array
[[absolute_x, absolute_y], [absolute_x + calculated_width, absolute_y], [absolute_x + calculated_width, absolute_y + calculated_height], [absolute_x, absolute_y + calculated_height]]
end
# checks if drawn or filled rectangle includes the point denoted by x and y (if drawn, it only returns true if point lies on the edge)
def include?(x, y)
if filled?
contain?(x, y)
else
x, y = inverse_transform_point(x, y)
comparison_lines = absolute_point_xy_array.zip(absolute_point_xy_array.rotate(1))
comparison_lines.any? {|line| Line.include?(line.first.first, line.first.last, line.last.first, line.last.last, x, y)}
end
end
end
end
end
end
end
| ruby | MIT | 449cf07ada1ec965ae2ac91715ccdf22488df4ca | 2026-01-04T17:52:38.125591Z | false |
AndyObtiva/glimmer-dsl-swt | https://github.com/AndyObtiva/glimmer-dsl-swt/blob/449cf07ada1ec965ae2ac91715ccdf22488df4ca/lib/glimmer/swt/custom/shape/path_segment.rb | lib/glimmer/swt/custom/shape/path_segment.rb | # Copyright (c) 2007-2025 Andy Maleh
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
require 'glimmer/swt/custom/shape'
module Glimmer
module SWT
module Custom
class Shape
# Represents path segments like point, line, quad, and cubic curves
# Shapes could mix in
module PathSegment
def root_path
current_parent = parent
until current_parent.class == Path && !current_parent.parent.is_a?(Path)
current_parent = current_parent.parent
return current_parent if current_parent.nil?
end
current_parent
end
def path
current_parent = parent
until current_parent.class == Path
current_parent = current_parent.parent
return current_parent if current_parent.nil?
end
current_parent
end
# this is needed to indicate if a shape is part of a path or not (e.g. line and point could be either)
def part_of_path?
!!root_path
end
# Subclasses must override and implement to indicate method name to invoke on SWT Path object to add segment
def path_segment_method_name
nil
end
# Subclasses must override and implement to indicate args to pass when invoking SWT Path object method
def path_segment_args
[]
end
# Subclasses must override to indicate expected complete count of args when previous point is NOT connected (e.g. 4 for line, 6 for quad, 8 for cubic)
def default_path_segment_arg_count
end
# Subclasses must override to indicate expected count of args when previous point IS connected (e.g. 2 for line, 4 for quad, 6 for cubic)
def default_connected_path_segment_arg_count
end
# Subclasses may override to provide name of method to invoke for geometry object obtained from the Java AWT library java.awt.geom.Path2D.Double (e.g. curveTo vs cubicTo)
def path_segment_geometry_method_name
path_segment_method_name
end
# Subclasses must override and implement to indicate args to pass when invoking SWT Path object method
def path_segment_geometry_args
path_segment_args
end
# Subclasses must override to indicate otherwise
def previous_point_connected?
true
end
def dispose(dispose_images: true, dispose_patterns: true, redraw: true)
Glimmer::SWT::DisplayProxy.instance.auto_exec do
# including classes could override to dispose of resources first
# afterwards, parent removes from its path segments with post_dispose_content
parent.post_dispose_content(self) if parent.is_a?(Path)
if part_of_path?
drawable.redraw if redraw && !drawable.is_a?(ImageProxy)
else
super(dispose_images: dispose_images, dispose_patterns: dispose_patterns, redraw: redraw)
end
end
end
def first_path_segment?
parent.path_segments.first == self
end
def previous_path_segment
parent.path_segments[parent.path_segments.index(self) - 1] || self
end
def add_to_swt_path(swt_path)
the_path_segment_args = path_segment_args.dup
the_path_segment_args = the_path_segment_args.first if the_path_segment_args.size == 1 && the_path_segment_args.first.is_a?(Array)
if !is_a?(Point) && self.class != Path
if !previous_point_connected?
if the_path_segment_args.count == default_path_segment_arg_count
point = the_path_segment_args.shift, the_path_segment_args.shift
swt_path.moveTo(*point)
elsif first_path_segment?
point = the_path_segment_args[0..1]
swt_path.moveTo(*point)
end
end
end
swt_path.send(path_segment_method_name, *the_path_segment_args)
end
def add_to_geometry(geometry)
the_path_segment_geometry_args = path_segment_geometry_args.dup
if !is_a?(Point) && self.class != Path
if !previous_point_connected?
if the_path_segment_geometry_args.count == default_path_segment_arg_count
point = the_path_segment_geometry_args.shift, the_path_segment_geometry_args.shift
geometry.moveTo(point[0], point[1])
elsif first_path_segment?
point = the_path_segment_geometry_args[0..1]
geometry.moveTo(point[0], point[1])
end
end
end
geometry.send(path_segment_geometry_method_name, *the_path_segment_geometry_args)
end
end
end
end
end
end
| ruby | MIT | 449cf07ada1ec965ae2ac91715ccdf22488df4ca | 2026-01-04T17:52:38.125591Z | false |
AndyObtiva/glimmer-dsl-swt | https://github.com/AndyObtiva/glimmer-dsl-swt/blob/449cf07ada1ec965ae2ac91715ccdf22488df4ca/lib/glimmer/swt/custom/shape/polyline.rb | lib/glimmer/swt/custom/shape/polyline.rb | # Copyright (c) 2007-2025 Andy Maleh
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
require 'glimmer/swt/custom/shape'
require 'glimmer/swt/swt_proxy'
require 'glimmer/swt/display_proxy'
require 'glimmer/swt/color_proxy'
require 'glimmer/swt/font_proxy'
require 'glimmer/swt/transform_proxy'
module Glimmer
module SWT
module Custom
# Represents a shape (graphics) to be drawn on a control/widget/canvas/display
# That is because Shape is drawn on a parent as graphics and doesn't have an SWT widget for itself
class Shape
class Polyline < Shape
def parameter_names
[:point_array]
end
def location_parameter_names
parameter_names
end
def point_count
point_array = args.size > 1 ? args : self.point_array
point_array.count / 2
end
def [](index)
point_array = args.size > 1 ? args : self.point_array
index = 0 if index == point_count
org.eclipse.swt.graphics.Point.new(point_array[index * 2], point_array[index * 2 + 1])
end
def x_array
point_array = args.size > 1 ? args : self.point_array
point_array.each_with_index.select {|pair| pair.last.even?}.map(&:first)
end
def y_array
point_array = args.size > 1 ? args : self.point_array
point_array.each_with_index.select {|pair| pair.last.odd?}.map(&:first)
end
def point_xy_array
x_array.zip(y_array)
end
def absolute_point_array
point_array = args.size > 1 ? args : self.point_array
if parent.is_a?(Shape)
point_array.each_with_index.map do |coordinate, i|
if i.even?
parent.absolute_x + coordinate
else
parent.absolute_y + coordinate
end
end
else
point_array
end
end
def absolute_x_array
absolute_point_array.each_with_index.select {|pair| pair.last.even?}.map(&:first)
end
def absolute_y_array
absolute_point_array.each_with_index.select {|pair| pair.last.odd?}.map(&:first)
end
def absolute_point_xy_array
absolute_x_array.zip(absolute_y_array)
end
def bounds
shape_bounds = geometry.getBounds2D
org.eclipse.swt.graphics.Rectangle.new(shape_bounds.x, shape_bounds.y, shape_bounds.width, shape_bounds.height)
end
def size
shape_bounds = geometry.getBounds2D
org.eclipse.swt.graphics.Point.new(shape_bounds.width, shape_bounds.height)
end
def geometry
java.awt.Polygon.new(absolute_x_array.to_java(:int), absolute_y_array.to_java(:int), point_count)
end
# Logical x coordinate relative to parent
def x
x_value = bounds.x
x_value -= parent.absolute_x if parent.is_a?(Shape)
x_value
end
# Logical y coordinate relative to parent
def y
y_value = bounds.y
y_value -= parent.absolute_y if parent.is_a?(Shape)
y_value
end
def width
bounds.width
end
def height
bounds.height
end
def include?(x, y)
x, y = inverse_transform_point(x, y)
comparison_lines = absolute_point_xy_array.zip(absolute_point_xy_array.rotate(1))
comparison_lines.pop # ignore last pair since you don't want to compare last point with first point
comparison_lines.any? {|line| Line.include?(line.first.first, line.first.last, line.last.first, line.last.last, x, y)}
end
alias contain? include?
def move_by(x_delta, y_delta)
self.point_array = point_array.each_with_index.map {|coordinate, i| i.even? ? coordinate + x_delta : coordinate + y_delta}
end
def irregular?
true
end
end
end
end
end
end
| ruby | MIT | 449cf07ada1ec965ae2ac91715ccdf22488df4ca | 2026-01-04T17:52:38.125591Z | false |
AndyObtiva/glimmer-dsl-swt | https://github.com/AndyObtiva/glimmer-dsl-swt/blob/449cf07ada1ec965ae2ac91715ccdf22488df4ca/lib/glimmer/swt/custom/shape/focus.rb | lib/glimmer/swt/custom/shape/focus.rb | # Copyright (c) 2007-2025 Andy Maleh
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
require 'glimmer/swt/custom/shape'
require 'glimmer/swt/swt_proxy'
require 'glimmer/swt/display_proxy'
require 'glimmer/swt/color_proxy'
require 'glimmer/swt/font_proxy'
require 'glimmer/swt/transform_proxy'
module Glimmer
module SWT
module Custom
class Shape
# Represents a focus shape to be drawn on a control/widget/canvas/display
# Helps highlight focus on another selected shape
class Focus < Shape
def parameter_names
[:x, :y, :width, :height]
end
end
end
end
end
end
| ruby | MIT | 449cf07ada1ec965ae2ac91715ccdf22488df4ca | 2026-01-04T17:52:38.125591Z | false |
AndyObtiva/glimmer-dsl-swt | https://github.com/AndyObtiva/glimmer-dsl-swt/blob/449cf07ada1ec965ae2ac91715ccdf22488df4ca/lib/glimmer/swt/custom/shape/image.rb | lib/glimmer/swt/custom/shape/image.rb | # Copyright (c) 2007-2025 Andy Maleh
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
require 'glimmer/swt/custom/shape'
require 'glimmer/swt/swt_proxy'
require 'glimmer/swt/display_proxy'
require 'glimmer/swt/color_proxy'
require 'glimmer/swt/font_proxy'
require 'glimmer/swt/transform_proxy'
require 'glimmer/swt/image_proxy'
module Glimmer
module SWT
module Custom
# Represents a shape (graphics) to be drawn on a control/widget/canvas/display
# That is because Shape is drawn on a parent as graphics and doesn't have an SWT widget for itself
class Shape
class Image < Shape
def parameter_names
@parameter_names || image_whole_parameter_names
end
def possible_parameter_names
(image_part_parameter_names + image_whole_parameter_names).uniq
end
def image_part_parameter_names
[:image, :src_x, :src_y, :src_width, :src_height, :dest_x, :dest_y, :dest_width, :dest_height]
end
def image_whole_parameter_names
[:image, :x, :y]
end
def set_parameter_attribute(attribute_name, *args)
return super if @parameter_names.to_a.map(&:to_s).include?(attribute_name.to_s)
####TODO refactor and improve this method through meta-programming (and share across other shapes)
if image_part_parameter_names.map(&:to_s).include?(attribute_name.to_s)
@parameter_names = image_part_parameter_names
elsif image_whole_parameter_names.map(&:to_s).include?(attribute_name.to_s)
@parameter_names = image_whole_parameter_names
end
super
end
def x
dest_x || get_attribute('x')
end
def y
dest_y || get_attribute('y')
end
def width
dest_width || image_proxy.bounds.width
end
def height
dest_height || image_proxy.bounds.height
end
def image_proxy
ImageProxy.create(image)
end
def default_x?
super ||
current_parameter_name?(:dest_x) && (dest_x.nil? || dest_x.to_s == 'default')
end
def default_y?
super ||
current_parameter_name?(:dest_y) && (dest_y.nil? || dest_y.to_s == 'default')
end
def move_by(x_delta, y_delta)
if default_x?
self.default_x_delta += x_delta
elsif dest_x
self.dest_x += x_delta
else
self.x += x_delta
end
if default_y?
self.default_y_delta += y_delta
elsif dest_y
self.dest_y += y_delta
else
self.y += y_delta
end
end
end
end
end
end
end
| ruby | MIT | 449cf07ada1ec965ae2ac91715ccdf22488df4ca | 2026-01-04T17:52:38.125591Z | false |
AndyObtiva/glimmer-dsl-swt | https://github.com/AndyObtiva/glimmer-dsl-swt/blob/449cf07ada1ec965ae2ac91715ccdf22488df4ca/lib/glimmer/data_binding/list_selection_binding.rb | lib/glimmer/data_binding/list_selection_binding.rb | # Copyright (c) 2007-2025 Andy Maleh
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
require 'glimmer/data_binding/observable'
require 'glimmer/data_binding/observer'
module Glimmer
module DataBinding
# SWT List widget selection binding
class ListSelectionBinding
include Glimmer
include Observable
include Observer
attr_reader :widget_proxy
PROPERTY_TYPE_UPDATERS = {
:string => lambda { |widget_proxy, value| widget_proxy.swt_widget.select(widget_proxy.swt_widget.index_of(value.to_s)) },
:array => lambda { |widget_proxy, value| widget_proxy.swt_widget.selection=(value || []).to_java(:string) }
}
PROPERTY_EVALUATORS = {
:string => lambda do |selection_array|
return nil if selection_array.empty?
selection_array[0]
end,
:array => lambda do |selection_array|
selection_array
end
}
# Initialize with list widget and property_type
# property_type :string represents default list single selection
# property_type :array represents list multi selection
def initialize(widget_proxy, property_type, sync_exec: false, async_exec: false)
property_type = :string if property_type.nil? or property_type == :undefined
@widget_proxy = widget_proxy
@property_type = property_type
@sync_exec = sync_exec
@async_exec = async_exec
Glimmer::SWT::DisplayProxy.instance.auto_exec(override_sync_exec: @sync_exec, override_async_exec: @async_exec) do
@widget_proxy.on_widget_disposed do |dispose_event|
unregister_all_observables
end
end
end
def call(value)
Glimmer::SWT::DisplayProxy.instance.auto_exec(override_sync_exec: @sync_exec, override_async_exec: @async_exec) do
PROPERTY_TYPE_UPDATERS[@property_type].call(@widget_proxy, value) unless evaluate_property == value
end
end
def evaluate_property
selection_array = @widget_proxy.swt_widget.send('selection').to_a #TODO refactor send('selection') into proper method invocation
PROPERTY_EVALUATORS[@property_type].call(selection_array)
end
end
end
end
| ruby | MIT | 449cf07ada1ec965ae2ac91715ccdf22488df4ca | 2026-01-04T17:52:38.125591Z | false |
AndyObtiva/glimmer-dsl-swt | https://github.com/AndyObtiva/glimmer-dsl-swt/blob/449cf07ada1ec965ae2ac91715ccdf22488df4ca/lib/glimmer/data_binding/observable_widget.rb | lib/glimmer/data_binding/observable_widget.rb | # Copyright (c) 2007-2025 Andy Maleh
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
module Glimmer
module DataBinding
module ObservableWidget
# TODO see if it is worth it to eliminate duplication of method_missing
# from WidgetProxy using a module
def method_missing(method_name, *args, &block)
method_name = method_name.to_s
if block && can_handle_observation_request?(method_name)
handle_observation_request(method_name, &block)
else
super
end
end
end
end
end
| ruby | MIT | 449cf07ada1ec965ae2ac91715ccdf22488df4ca | 2026-01-04T17:52:38.125591Z | false |
AndyObtiva/glimmer-dsl-swt | https://github.com/AndyObtiva/glimmer-dsl-swt/blob/449cf07ada1ec965ae2ac91715ccdf22488df4ca/lib/glimmer/data_binding/widget_binding.rb | lib/glimmer/data_binding/widget_binding.rb | # Copyright (c) 2007-2025 Andy Maleh
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
require 'glimmer/data_binding/observable'
require 'glimmer/data_binding/observer'
require 'glimmer/swt/display_proxy'
module Glimmer
module DataBinding
class WidgetBinding
include Glimmer
include Observable
include Observer
attr_reader :widget, :property, :model_binding
def initialize(widget, property, sync_exec: nil, async_exec: nil)
@widget = widget
@property = property
@sync_exec = sync_exec
@async_exec = async_exec
SWT::DisplayProxy.instance.auto_exec(override_sync_exec: @sync_exec, override_async_exec: @async_exec) do
if @widget.is_a?(Glimmer::SWT::WidgetProxy) && @widget.respond_to?(:on_widget_disposed)
@widget.on_widget_disposed do |dispose_event|
unless @widget.shell_proxy.last_shell_closing?
@widget_proxy.widget_bindings.delete(self)
deregister_all_observables
end
end
end
# TODO look into hooking on_shape_disposed without slowing down shapes in samples like Tetris
end
# TODO try to come up with a more comprehensive and cleaner solution to miscallenous objects like MessageBoxProxy with regards to @widget_proxy
@widget_proxy = widget.is_a?(Glimmer::SWT::WidgetProxy) ? widget : (widget.respond_to?(:body_root) ? widget.body_root : widget)
end
def observe(*args)
if @widget_proxy.respond_to?(:widget_bindings)
# TODO try to come up with a more comprehensive and cleaner solution to miscallenous objects like MessageBoxProxy with regards to the following code
# assumes only one observation
@model_binding = args.first if args.size == 1
@widget_proxy.widget_bindings << self
end
super
end
def call(value)
SWT::DisplayProxy.instance.auto_exec(override_sync_exec: @sync_exec, override_async_exec: @async_exec) do
if @widget.respond_to?(:disposed?) && @widget.disposed?
unless @widget.shell_proxy.last_shell_closing?
@widget_proxy.widget_bindings.delete(self)
deregister_all_observables
end
return
end
# need the rescue false for a scenario with tree items not being equal to model objects raising an exception
if @async_exec || !((value == evaluate_property) rescue false) # need the rescue false for a scenario with tree items not being equal to model objects raising an exception
@widget.set_attribute(@property, value)
end
end
end
def evaluate_property
if @widget.respond_to?(:disposed?) && @widget.disposed?
unless @widget.shell_proxy.last_shell_closing?
@widget_proxy.widget_bindings.delete(self)
deregister_all_observables
end
return
end
@widget.get_attribute(@property)
end
end
end
end
| ruby | MIT | 449cf07ada1ec965ae2ac91715ccdf22488df4ca | 2026-01-04T17:52:38.125591Z | false |
AndyObtiva/glimmer-dsl-swt | https://github.com/AndyObtiva/glimmer-dsl-swt/blob/449cf07ada1ec965ae2ac91715ccdf22488df4ca/lib/glimmer/data_binding/table_items_binding.rb | lib/glimmer/data_binding/table_items_binding.rb | # Copyright (c) 2007-2025 Andy Maleh
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
require 'set'
require 'glimmer/data_binding/observable_array'
require 'glimmer/data_binding/observable_model'
require 'glimmer/data_binding/observable'
require 'glimmer/data_binding/observer'
require 'glimmer/swt/swt_proxy'
require 'glimmer/swt/display_proxy'
module Glimmer
module DataBinding
class TableItemsBinding
include DataBinding::Observable
include DataBinding::Observer
include_package 'org.eclipse.swt'
include_package 'org.eclipse.swt.widgets'
TABLE_ITEM_PROPERTIES = %w[background foreground font image]
attr_reader :data_binding_done
def initialize(parent, model_binding, column_properties = nil)
@table = parent.is_a?(Glimmer::SWT::TableProxy) ? parent : parent.body_root # assume custom widget in latter case
@table.table_items_binding = self
@model_binding = model_binding
@read_only_sort = @model_binding.binding_options[:read_only_sort]
@table.editable = false if @model_binding.binding_options[:read_only]
@table.column_properties = @model_binding.binding_options[:column_properties] || @model_binding.binding_options[:column_attributes] || column_properties
@column_properties = @table.column_properties # normalized column properties
Glimmer::SWT::DisplayProxy.instance.auto_exec(override_sync_exec: @model_binding.binding_options[:sync_exec], override_async_exec: @model_binding.binding_options[:async_exec]) do
@table.swt_widget.data = @model_binding
@table.swt_widget.set_data('table_items_binding', self)
@table.on_widget_disposed do |dispose_event|
unregister_all_observables
end
@table_observer_registration = observe(model_binding)
call
end
end
def call(*args)
options = args.last.is_a?(Hash) ? args.pop : {}
internal_sort = options[:internal_sort] || false
new_model_collection = args.first
Glimmer::SWT::DisplayProxy.instance.auto_exec(override_sync_exec: @model_binding.binding_options[:sync_exec], override_async_exec: @model_binding.binding_options[:async_exec]) do
new_model_collection = model_binding_evaluated_property = @model_binding.evaluate_property unless internal_sort # this ensures applying converters (e.g. :on_read)
return if same_table_data?(new_model_collection)
if same_model_collection?(new_model_collection)
new_model_collection_attribute_values = model_collection_attribute_values(new_model_collection)
@table.swt_widget.items.each_with_index do |table_item, row_index|
next if new_model_collection_attribute_values[row_index] == @last_model_collection_attribute_values[row_index]
model = table_item.get_data
(0..(@column_properties.size-1)).each do |column_index|
new_model_attribute_values_for_index = model_attribute_values_for_index(new_model_collection_attribute_values[row_index], column_index)
last_model_attribute_values_for_index = model_attribute_values_for_index(@last_model_collection_attribute_values[row_index], column_index)
next if new_model_attribute_values_for_index == last_model_attribute_values_for_index
model_attribute = @column_properties[column_index]
update_table_item_properties_from_model(table_item, row_index, column_index, model, model_attribute)
end
end
@last_model_collection_attribute_values = new_model_collection_attribute_values
else
if new_model_collection and new_model_collection.is_a?(Array)
@model_observer_registrations ||= {}
@table_item_property_observation_mutex ||= Mutex.new
brand_new_model_collection = !same_model_collection_with_different_sort?(new_model_collection)
Thread.new do
@data_binding_done = false
@table_item_property_observation_mutex.synchronize do
deregister_model_observer_registrations
new_model_collection.each_with_index do |model, model_index|
@model_observer_registrations[model_index] ||= {}
@column_properties.each do |column_property|
model_observer_registration = observe(model, column_property)
@model_observer_registrations[model_index][column_property] = model_observer_registration
add_dependent(@table_observer_registration => model_observer_registration)
end
end
if brand_new_model_collection
new_model_collection.each_with_index do |model, model_index|
TABLE_ITEM_PROPERTIES.each do |table_item_property|
@column_properties.each do |column_property|
column_property = "#{column_property}_#{table_item_property}"
model_observer_registration = observe(model, column_property)
@model_observer_registrations[model_index][column_property] = model_observer_registration
add_dependent(@table_observer_registration => model_observer_registration)
end
end
end
end
@data_binding_done = true
end
end
@model_collection = new_model_collection
else
@model_collection = []
end
populate_table(@model_collection, @table, @column_properties, internal_sort: internal_sort)
end
end
end
def populate_table(model_collection, parent, column_properties, internal_sort: false)
selected_table_item_models = parent.swt_widget.getSelection.map(&:get_data)
parent.finish_edit!
dispose_start_index = @last_model_collection_attribute_values &&
(model_collection.count < @last_model_collection_attribute_values.count) &&
(@last_model_collection_attribute_values.count - (@last_model_collection_attribute_values.count - model_collection.count))
if dispose_start_index
table_items_to_dispose = parent.swt_widget.items[dispose_start_index..-1]
parent.swt_widget.remove(dispose_start_index, (@last_model_collection_attribute_values.count-1))
table_items_to_dispose.each(&:dispose)
end
model_collection.each_with_index do |model, row_index|
table_item_exists = @last_model_collection_attribute_values &&
@last_model_collection_attribute_values.count > 0 &&
row_index < @last_model_collection_attribute_values.count
table_item = table_item_exists ? parent.swt_widget.items[row_index] : TableItem.new(parent.swt_widget, SWT::SWTProxy[:none])
(0..(column_properties.size-1)).each do |column_index|
model_attribute = column_properties[column_index]
update_table_item_properties_from_model(table_item, row_index, column_index, model, model_attribute)
end
table_item.set_data(model)
end
@last_model_collection_attribute_values = model_collection_attribute_values(model_collection)
selected_table_items = parent.search {|item| selected_table_item_models.include?(item.get_data) }
parent.swt_widget.setSelection(selected_table_items)
sorted_model_collection = parent.sort!(internal_sort: internal_sort)
call(sorted_model_collection, internal_sort: true) if @read_only_sort && !internal_sort && !sorted_model_collection.nil?
parent.swt_widget.redraw if parent&.swt_widget&.respond_to?(:redraw)
end
def update_table_item_properties_from_model(table_item, row_index, column_index, model, model_attribute)
Glimmer::SWT::DisplayProxy.instance.sync_exec do
old_table_item_values = @last_model_collection_attribute_values &&
@last_model_collection_attribute_values[row_index] &&
model_attribute_values_for_index(@last_model_collection_attribute_values[row_index], column_index)
text_value = model.send(model_attribute).to_s
old_table_item_value = old_table_item_values && old_table_item_values[0]
table_item.set_text(column_index, text_value) if old_table_item_value.nil? || text_value != old_table_item_value
TABLE_ITEM_PROPERTIES.each do |table_item_property|
if model.respond_to?("#{model_attribute}_#{table_item_property}")
table_item_value = model.send("#{model_attribute}_#{table_item_property}")
old_table_item_value = old_table_item_values && old_table_item_values[1 + TABLE_ITEM_PROPERTIES.index(table_item_property)]
if old_table_item_value.nil? || (table_item_value != old_table_item_value)
table_item_value = Glimmer::SWT::ColorProxy.create(*table_item_value).swt_color if table_item_value && %w[background foreground].include?(table_item_property.to_s)
table_item_value = Glimmer::SWT::FontProxy.create(table_item_value).swt_font if table_item_value && table_item_property.to_s == 'font'
table_item_value = Glimmer::SWT::ImageProxy.create(*table_item_value).swt_image if table_item_value && table_item_property.to_s == 'image'
table_item.send("set_#{table_item_property}", column_index, table_item_value)
end
end
end
end
end
def same_table_data?(new_model_collection)
(["text"] + TABLE_ITEM_PROPERTIES).all? do |table_item_property|
table_cells = @table.swt_widget.items.map do |item|
model = item.get_data
@table.column_properties.each_with_index.map do |column_property, i|
model_attribute = "#{column_property}"
model_attribute = "#{model_attribute}_#{table_item_property}" if TABLE_ITEM_PROPERTIES.include?(table_item_property)
item.send("get_#{table_item_property}", i) if model.respond_to?(model_attribute)
end
end
model_cells = new_model_collection.to_a.map do |m|
@table.cells_for(m, table_item_property: table_item_property)
end
model_cells = model_cells.map do |row|
row.map do |model_cell|
if model_cell
if %w[background foreground].include?(table_item_property.to_s)
Glimmer::SWT::ColorProxy.create(*model_cell).swt_color
elsif table_item_property.to_s == 'font'
Glimmer::SWT::FontProxy.create(model_cell).swt_font
elsif table_item_property.to_s == 'image'
Glimmer::SWT::ImageProxy.create(*model_cell).swt_image
else
model_cell
end
end
end
end
table_cells == model_cells
end
end
def same_model_collection?(new_model_collection)
new_model_collection == table_item_model_collection
end
def same_model_collection_with_different_sort?(new_model_collection)
Set.new(new_model_collection) == Set.new(table_item_model_collection)
end
def table_item_model_collection
@table.swt_widget.items.map(&:get_data)
end
def deregister_model_observer_registrations
@model_observer_registrations&.dup&.each do |model_index, model_column_properties|
model_column_properties.dup.each do |column_property, model_observer_registration|
remove_dependent(@table_observer_registration => model_observer_registration) if model_observer_registration
model_observer_registration&.unobserve
model_column_properties.delete(column_property)
end
@model_observer_registrations.delete(model_index)
end
end
def model_collection_attribute_values(model_collection)
model_collection.map do |model|
(["text"] + TABLE_ITEM_PROPERTIES).map do |table_item_property|
@table.cells_for(model, table_item_property: table_item_property)
end
end
end
def model_attribute_values_for_index(model_attribute_values, index)
model_attribute_values.map {|attribute_values| attribute_values[index]}
end
end
end
end
| ruby | MIT | 449cf07ada1ec965ae2ac91715ccdf22488df4ca | 2026-01-04T17:52:38.125591Z | false |
AndyObtiva/glimmer-dsl-swt | https://github.com/AndyObtiva/glimmer-dsl-swt/blob/449cf07ada1ec965ae2ac91715ccdf22488df4ca/lib/glimmer/data_binding/tree_items_binding.rb | lib/glimmer/data_binding/tree_items_binding.rb | # Copyright (c) 2007-2025 Andy Maleh
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
require 'glimmer/data_binding/observable_array'
require 'glimmer/data_binding/observable_model'
require 'glimmer/data_binding/observable'
require 'glimmer/data_binding/observer'
require 'glimmer/swt/swt_proxy'
module Glimmer
module DataBinding
class TreeItemsBinding
include DataBinding::Observable
include DataBinding::Observer
include_package 'org.eclipse.swt'
include_package 'org.eclipse.swt.widgets'
def initialize(parent, model_binding, tree_properties = nil)
@tree = parent
@model_binding = model_binding
@tree_properties = @model_binding.binding_options[:tree_properties] || @model_binding.binding_options[:tree_attributes] || [tree_properties].compact.flatten.first.to_h
if @tree.respond_to?(:tree_properties=)
@tree.tree_properties = @tree_properties
else # assume custom widget
@tree.body_root.tree_properties = @tree_properties
end
Glimmer::SWT::DisplayProxy.instance.auto_exec(override_sync_exec: @model_binding.binding_options[:sync_exec], override_async_exec: @model_binding.binding_options[:async_exec]) do
call
model = model_binding.base_model
observe(model, model_binding.property_name_expression)
@tree.on_widget_disposed do |dispose_event|
unregister_all_observables
end
end
end
def call(new_value=nil)
Glimmer::SWT::DisplayProxy.instance.auto_exec(override_sync_exec: @model_binding.binding_options[:sync_exec], override_async_exec: @model_binding.binding_options[:async_exec]) do
@model_tree_root_node = @model_binding.evaluate_property
old_tree_items = @tree.all_tree_items
old_model_tree_nodes = old_tree_items.map(&:get_data)
new_model_tree_nodes = []
recursive_depth_first_search(@model_tree_root_node, @tree_properties, new_model_tree_nodes)
return if old_model_tree_nodes == new_model_tree_nodes && old_tree_items.map(&:text) == new_model_tree_nodes.map {|model_tree_node| model_tree_node.send(@tree_properties[:text])}
populate_tree(@model_tree_root_node, @tree, @tree_properties)
end
end
def populate_tree(model_tree_root_node, parent, tree_properties)
# TODO get rid of model_tree_root_node, parent, tree_properties as an argument given it is stored as an instance variable
# TODO make it change things by delta instead of removing all
old_tree_items = parent.all_tree_items
selected_tree_item_models = parent.swt_widget.getSelection.map(&:get_data)
old_tree_item_expansion_by_data = old_tree_items.reduce({}) {|hash, ti| hash.merge(ti.getData => ti.getExpanded)}
old_tree_items.each do |tree_item|
tree_item.getData('observer_registrations').each(&:unregister)
end
parent.swt_widget.items.each(&:dispose)
parent.swt_widget.removeAll
populate_tree_node(model_tree_root_node, parent.swt_widget, tree_properties)
parent.all_tree_items.each { |ti| ti.setExpanded(!!old_tree_item_expansion_by_data[ti.getData]) }
selected_tree_items = parent.depth_first_search {|item| selected_tree_item_models.include?(item.get_data) }
parent.swt_widget.setSelection(selected_tree_items)
end
def populate_tree_node(model_tree_node, parent, tree_properties)
return if model_tree_node.nil?
tree_item = TreeItem.new(parent, SWT::SWTProxy[:none])
observer_registrations = @tree_properties.reduce([]) do |array, key_value_pair|
array + [observe(model_tree_node, key_value_pair.last)]
end
tree_item.set_data('observer_registrations', observer_registrations)
tree_item.set_data(model_tree_node)
tree_item.text = (model_tree_node && model_tree_node.send(tree_properties[:text])).to_s
[model_tree_node && model_tree_node.send(tree_properties[:children])].flatten.to_a.compact.each do |child|
populate_tree_node(child, tree_item, tree_properties)
end
end
def recursive_depth_first_search(model_tree_node, tree_properties, collection)
return if model_tree_node.nil?
collection << model_tree_node
model_tree_node.send(tree_properties[:children]).to_a.each do |child_model_tree_node|
recursive_depth_first_search(child_model_tree_node, tree_properties, collection)
end
end
end
end
end
| ruby | MIT | 449cf07ada1ec965ae2ac91715ccdf22488df4ca | 2026-01-04T17:52:38.125591Z | false |
AndyObtiva/glimmer-dsl-swt | https://github.com/AndyObtiva/glimmer-dsl-swt/blob/449cf07ada1ec965ae2ac91715ccdf22488df4ca/lib/glimmer/rake_task/scaffold.rb | lib/glimmer/rake_task/scaffold.rb | # Copyright (c) 2007-2025 Andy Maleh
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
require 'fileutils'
require 'os'
require 'facets/string/titlecase'
# TODO refactor to nest under RakeTask namespace
MAIN_OBJECT = self
module Glimmer
module RakeTask
class Scaffold
class << self
include FileUtils
VERSION = File.read(File.expand_path('../../../../VERSION', __FILE__)).strip
RUBY_VERSION = File.read(File.expand_path('../../../../RUBY_VERSION', __FILE__)).strip
# TODO externalize all constants into scaffold/files
GITIGNORE = <<~MULTI_LINE_STRING
*.gem
*.rbc
/.config
/.mvn/
/coverage/
/InstalledFiles
/pkg/
/spec/reports/
/spec/examples.txt
/test/tmp/
/test/version_tmp/
/tmp/
# Used by dotenv library to load environment variables.
# .env
## Specific to RubyMotion:
.dat*
.repl_history
build/
*.bridgesupport
build-iPhoneOS/
build-iPhoneSimulator/
## Specific to RubyMotion (use of CocoaPods):
#
# We recommend against adding the Pods directory to your .gitignore. However
# you should judge for yourself, the pros and cons are mentioned at:
# https://guides.cocoapods.org/using/using-cocoapods.html#should-i-check-the-pods-directory-into-source-control
#
# vendor/Pods/
## Documentation cache and generated files:
/.yardoc/
/_yardoc/
/doc/
/rdoc/
## Environment normalization:
/.bundle/
/vendor/bundle
/lib/bundler/man/
# for a library or gem, you might want to ignore these files since the code is
# intended to run in multiple environments; otherwise, check them in:
# Gemfile.lock
# .ruby-version
# .ruby-gemset
# unless supporting rvm < 1.11.0 or doing something fancy, ignore this:
.rvmrc
# Mac
.DS_Store
# Warbler
Jars.lock
# Gladiator (Glimmer Editor)
.gladiator
.gladiator-scratchpad
# Glimmer
/dist/
/packages/
/vendor/jars/
MULTI_LINE_STRING
GEMFILE_PREFIX = <<~MULTI_LINE_STRING
# frozen_string_literal: true
source 'https://rubygems.org'
git_source(:github) {|repo_name| "https://github.com/\#{repo_name}" }
MULTI_LINE_STRING
GEMFILE_APP_MIDFIX = <<~MULTI_LINE_STRING
gem 'glimmer-dsl-swt', '~> #{VERSION}'
MULTI_LINE_STRING
GEMFILE_GEM_MIDFIX = <<~MULTI_LINE_STRING
gem 'glimmer-dsl-swt', '~> #{VERSION.split('.')[0...2].join('.')}'
MULTI_LINE_STRING
GEMFILE_SUFFIX = <<~MULTI_LINE_STRING
group :development do
gem 'jar-dependencies', '>= 0.5.3'
gem 'rspec', '~> 3.5.0'
gem 'juwelier', '2.4.9'
gem 'warbler', '2.0.5'
gem 'simplecov', '>= 0'
end
MULTI_LINE_STRING
APP_GEMFILE = GEMFILE_PREFIX + GEMFILE_APP_MIDFIX + GEMFILE_SUFFIX
GEM_GEMFILE = GEMFILE_PREFIX + GEMFILE_GEM_MIDFIX + GEMFILE_SUFFIX
def app(app_name)
common_app(app_name)
end
def desktopify(app_name, website)
common_app(app_name, :desktopify, website: website)
end
def common_app(app_name, shell_type = :app, shell_options = {})
gem_name = file_name(app_name)
gem_summary = human_name(app_name)
return puts("The directory '#{gem_name}' already exists. Please either remove or pick a different name.") if Dir.exist?(gem_name)
system "jruby -S gem install bundler --no-document" if OS.windows? # resolves freezing issue with warbler and bundler 2.2.29 included in JRuby
system "jruby -S gem install juwelier -v2.4.9 --no-document" unless juwelier_exists?
system "jruby -S juwelier --markdown --rspec --summary '#{gem_summary}' --description '#{gem_summary}' #{gem_name}"
return puts('Your Git user.name and/or github.user are missing! Please add in for Juwelier to help Glimmer with Scaffolding.') if `git config --get github.user`.strip.empty? || `git config --get user.name`.strip.empty?
cd gem_name
rm_rf 'lib'
write '.gitignore', GITIGNORE
write '.ruby-version', RUBY_VERSION
write '.ruby-gemset', app_name
write 'VERSION', '1.0.0'
write 'LICENSE.txt', "Copyright (c) #{Time.now.year} #{app_name}"
write 'Gemfile', gemfile(shell_type)
write 'Rakefile', gem_rakefile(app_name, nil, gem_name)
mkdir 'app'
write "app/#{file_name(app_name)}.rb", app_main_file(app_name)
mkdir_p "app/#{file_name(app_name)}/model"
mkdir_p "app/#{file_name(app_name)}/view"
if shell_type == :desktopify
custom_shell('AppView', current_dir_name, shell_type, shell_options)
else
custom_shell('AppView', current_dir_name, shell_type)
end
mkdir_p 'icons/windows'
icon_file = "icons/windows/#{human_name(app_name)}.ico"
cp File.expand_path('../../../../icons/scaffold_app.ico', __FILE__), icon_file
puts "Created #{current_dir_name}/#{icon_file}"
mkdir_p 'icons/macosx'
icon_file = "icons/macosx/#{human_name(app_name)}.icns"
cp File.expand_path('../../../../icons/scaffold_app.icns', __FILE__), icon_file
puts "Created #{current_dir_name}/#{icon_file}"
mkdir_p 'icons/linux'
icon_file = "icons/linux/#{human_name(app_name)}.png"
cp File.expand_path('../../../../icons/scaffold_app.png', __FILE__), icon_file
puts "Created #{current_dir_name}/#{icon_file}"
mkdir_p "app/#{file_name(app_name)}"
write "app/#{file_name(app_name)}/launch.rb", app_launch_file(app_name)
mkdir_p 'bin'
write "bin/#{file_name(app_name)}", app_bin_command_file(app_name)
FileUtils.chmod 0755, "bin/#{file_name(app_name)}"
if OS.windows?
system "bundle"
system "rspec --init"
else
system "bash -c '#{RVM_FUNCTION}\n cd .\n bundle\n rspec --init\n'"
end
write 'spec/spec_helper.rb', spec_helper_file
if OS.mac?
system "bash -c '#{RVM_FUNCTION}\n cd .\n JRUBY_OPTS=\"$JRUBY_OPTS -J-XstartOnFirstThread\" glimmer run\n'"
elsif OS.linux?
system "bash -c '#{RVM_FUNCTION}\n cd .\n glimmer run\n'"
else
system "glimmer run"
end
end
def custom_shell(custom_shell_name, namespace, shell_type = nil, shell_options = {})
namespace ||= current_dir_name
root_dir = File.exists?('app') ? 'app' : 'lib'
parent_dir = "#{root_dir}/#{file_name(namespace)}/view"
return puts("The file '#{parent_dir}/#{file_name(custom_shell_name)}.rb' already exists. Please either remove or pick a different name.") if File.exist?("#{parent_dir}/#{file_name(custom_shell_name)}.rb")
mkdir_p parent_dir unless File.exists?(parent_dir)
write "#{parent_dir}/#{file_name(custom_shell_name)}.rb", custom_shell_file(custom_shell_name, namespace, shell_type, shell_options)
end
def custom_widget(custom_widget_name, namespace)
namespace ||= current_dir_name
root_dir = File.exists?('app') ? 'app' : 'lib'
parent_dir = "#{root_dir}/#{file_name(namespace)}/view"
return puts("The file '#{parent_dir}/#{file_name(custom_widget_name)}.rb' already exists. Please either remove or pick a different name.") if File.exist?("#{parent_dir}/#{file_name(custom_widget_name)}.rb")
mkdir_p parent_dir unless File.exists?(parent_dir)
write "#{parent_dir}/#{file_name(custom_widget_name)}.rb", custom_widget_file(custom_widget_name, namespace)
end
def custom_shape(custom_shape_name, namespace)
namespace ||= current_dir_name
root_dir = File.exists?('app') ? 'app' : 'lib'
parent_dir = "#{root_dir}/#{file_name(namespace)}/view"
return puts("The file '#{parent_dir}/#{file_name(custom_shape_name)}.rb' already exists. Please either remove or pick a different name.") if File.exist?("#{parent_dir}/#{file_name(custom_shape_name)}.rb")
mkdir_p parent_dir unless File.exists?(parent_dir)
write "#{parent_dir}/#{file_name(custom_shape_name)}.rb", custom_shape_file(custom_shape_name, namespace)
end
def custom_shell_gem(custom_shell_name, namespace)
gem_name = "glimmer-cs-#{compact_name(custom_shell_name)}"
gem_summary = "#{human_name(custom_shell_name)} - Glimmer Custom Shell"
begin
custom_shell_keyword = dsl_widget_name(custom_shell_name)
MAIN_OBJECT.method(custom_shell_keyword)
return puts("CustomShell keyword `#{custom_shell_keyword}` is unavailable (occupied by a built-in Ruby method)! Please pick a different name.")
rescue NameError
# No Op (keyword is not taken by a built in Ruby method)
end
if namespace
gem_name += "-#{compact_name(namespace)}"
gem_summary += " (#{human_name(namespace)})"
else
return puts('Namespace is required! Usage: glimmer scaffold:gem:customshell[name,namespace]') unless `git config --get github.user`.to_s.strip == 'AndyObtiva'
namespace = 'glimmer'
end
return puts("The directory '#{gem_name}' already exists. Please either remove or pick a different name.") if Dir.exist?(gem_name)
system "jruby -S gem install bundler --no-document" if OS.windows? # resolves freezing issue with warbler and bundler 2.2.29 included in JRuby
system "jruby -S gem install juwelier -v2.4.9 --no-document" unless juwelier_exists?
system "jruby -S juwelier --markdown --rspec --summary '#{gem_summary}' --description '#{gem_summary}' #{gem_name}"
return puts('Your Git user.name and/or github.user are missing! Please add in for Juwelier to help Glimmer with Scaffolding.') if `git config --get github.user`.strip.empty? && `git config --get user.name`.strip.empty?
cd gem_name
write '.gitignore', GITIGNORE
write '.ruby-version', RUBY_VERSION
write '.ruby-gemset', gem_name
write 'VERSION', '1.0.0'
write 'Gemfile', GEM_GEMFILE
write 'Rakefile', gem_rakefile(custom_shell_name, namespace, gem_name)
append "lib/#{gem_name}.rb", gem_main_file(custom_shell_name, namespace)
custom_shell(custom_shell_name, namespace, :gem)
mkdir_p "lib/#{gem_name}"
write "lib/#{gem_name}/launch.rb", gem_launch_file(gem_name, custom_shell_name, namespace)
mkdir_p 'bin'
write "bin/#{file_name(custom_shell_name)}", app_bin_command_file(gem_name, custom_shell_name, namespace)
FileUtils.chmod 0755, "bin/#{file_name(custom_shell_name)}"
if OS.windows?
system "bundle"
system "rspec --init"
else
system "bash -c '#{RVM_FUNCTION}\n cd .\n bundle\n rspec --init\n'"
end
write 'spec/spec_helper.rb', spec_helper_file
mkdir_p 'icons/windows'
icon_file = "icons/windows/#{human_name(gem_name)}.ico"
cp File.expand_path('../../../../icons/scaffold_app.ico', __FILE__), icon_file
puts "Created #{current_dir_name}/#{icon_file}"
mkdir_p 'icons/macosx'
icon_file = "icons/macosx/#{human_name(gem_name)}.icns"
cp File.expand_path('../../../../icons/scaffold_app.icns', __FILE__), icon_file
puts "Created #{current_dir_name}/#{icon_file}"
mkdir_p 'icons/linux'
icon_file = "icons/linux/#{human_name(gem_name)}.png"
cp File.expand_path('../../../../icons/scaffold_app.png', __FILE__), icon_file
puts "Created #{current_dir_name}/#{icon_file}"
if OS.mac?
system "bash -c '#{RVM_FUNCTION}\n cd .\n JRUBY_OPTS=\"$JRUBY_OPTS -J-XstartOnFirstThread\" glimmer run\n'"
elsif OS.linux?
system "bash -c '#{RVM_FUNCTION}\n cd .\n glimmer run\n'"
else
system "glimmer run"
end
puts "Finished creating #{gem_name} Ruby gem."
puts 'Edit Rakefile to configure gem details.'
puts 'Run `rake` to execute specs.'
puts 'Run `rake build` to build gem.'
puts 'Run `rake release` to release into rubygems.org once ready.'
end
def custom_widget_gem(custom_widget_name, namespace)
gem_name = "glimmer-cw-#{compact_name(custom_widget_name)}"
gem_summary = "#{human_name(custom_widget_name)} - Glimmer Custom Widget"
if namespace
gem_name += "-#{compact_name(namespace)}"
gem_summary += " (#{human_name(namespace)})"
else
return puts('Namespace is required! Usage: glimmer scaffold:custom_widget_gem[custom_widget_name,namespace]') unless `git config --get github.user`.to_s.strip == 'AndyObtiva'
namespace = 'glimmer'
end
return puts("The directory '#{gem_name}' already exists. Please either remove or pick a different name.") if Dir.exist?(gem_name)
system "jruby -S gem install bundler --no-document" if OS.windows? # resolves freezing issue with warbler and bundler 2.2.29 included in JRuby
system "jruby -S gem install juwelier -v2.4.9 --no-document" unless juwelier_exists?
system "jruby -S juwelier --markdown --rspec --summary '#{gem_summary}' --description '#{gem_summary}' #{gem_name}"
return puts('Your Git user.name and/or github.user are missing! Please add in for Juwelier to help Glimmer with Scaffolding.') if `git config --get github.user`.strip.empty? && `git config --get user.name`.strip.empty?
cd gem_name
write '.gitignore', GITIGNORE
write '.ruby-version', RUBY_VERSION
write '.ruby-gemset', gem_name
write 'VERSION', '1.0.0'
write 'Gemfile', GEM_GEMFILE
write 'Rakefile', gem_rakefile
append "lib/#{gem_name}.rb", gem_main_file(custom_widget_name, namespace)
custom_widget(custom_widget_name, namespace)
if OS.windows?
system "bundle"
system "rspec --init"
else
system "bash -c '#{RVM_FUNCTION}\n cd .\n bundle\n rspec --init\n'"
end
write 'spec/spec_helper.rb', spec_helper_file
puts "Finished creating #{gem_name} Ruby gem."
puts 'Edit Rakefile to configure gem details.'
puts 'Run `rake` to execute specs.'
puts 'Run `rake build` to build gem.'
puts 'Run `rake release` to release into rubygems.org once ready.'
end
def custom_shape_gem(custom_shape_name, namespace)
gem_name = "glimmer-cp-#{compact_name(custom_shape_name)}"
gem_summary = "#{human_name(custom_shape_name)} - Glimmer Custom Shape"
if namespace
gem_name += "-#{compact_name(namespace)}"
gem_summary += " (#{human_name(namespace)})"
else
return puts('Namespace is required! Usage: glimmer scaffold:custom_shape_gem[custom_shape_name,namespace]') unless `git config --get github.user`.to_s.strip == 'AndyObtiva'
namespace = 'glimmer'
end
return puts("The directory '#{gem_name}' already exists. Please either remove or pick a different name.") if Dir.exist?(gem_name)
system "jruby -S gem install bundler --no-document" if OS.windows? # resolves freezing issue with warbler and bundler 2.2.29 included in JRuby
system "jruby -S gem install juwelier -v2.4.9 --no-document" unless juwelier_exists?
system "jruby -S juwelier --markdown --rspec --summary '#{gem_summary}' --description '#{gem_summary}' #{gem_name}"
return puts('Your Git user.name and/or github.user are missing! Please add in for Juwelier to help Glimmer with Scaffolding.') if `git config --get github.user`.strip.empty? && `git config --get user.name`.strip.empty?
cd gem_name
write '.gitignore', GITIGNORE
write '.ruby-version', RUBY_VERSION
write '.ruby-gemset', gem_name
write 'VERSION', '1.0.0'
write 'Gemfile', GEM_GEMFILE
write 'Rakefile', gem_rakefile
append "lib/#{gem_name}.rb", gem_main_file(custom_shape_name, namespace)
custom_shape(custom_shape_name, namespace)
if OS.windows?
system "bundle"
system "rspec --init"
else
system "bash -c '#{RVM_FUNCTION}\n cd .\n bundle\n rspec --init\n'"
end
write 'spec/spec_helper.rb', spec_helper_file
puts "Finished creating #{gem_name} Ruby gem."
puts 'Edit Rakefile to configure gem details.'
puts 'Run `rake` to execute specs.'
puts 'Run `rake build` to build gem.'
puts 'Run `rake release` to release into rubygems.org once ready.'
end
private
def juwelier_exists?
OS.windows? ? system('where juwelier') : system('which juwelier')
end
def write(file, content)
File.write file, content
file_path = File.expand_path(file)
puts "Created #{current_dir_name}/#{file}"
end
def append(file, content)
File.open(file, 'a') do |f|
f.write(content)
end
end
def current_dir_name
File.basename(File.expand_path('.'))
end
def class_name(app_name)
app_name.underscore.camelcase(:upper)
end
def file_name(app_name)
app_name.underscore
end
alias dsl_widget_name file_name
def human_name(app_name)
app_name.underscore.titlecase
end
def compact_name(gem_name)
gem_name.underscore.camelcase.downcase
end
def gemfile(shell_type)
APP_GEMFILE
end
def app_main_file(app_name)
<<~MULTI_LINE_STRING
$LOAD_PATH.unshift(File.expand_path('..', __FILE__))
begin
require 'bundler/setup'
Bundler.require(:default)
rescue
# this runs when packaged as a gem (no bundler)
require 'glimmer-dsl-swt'
# add more gems if needed
end
class #{class_name(app_name)}
include Glimmer
APP_ROOT = File.expand_path('../..', __FILE__)
VERSION = File.read(File.join(APP_ROOT, 'VERSION'))
LICENSE = File.read(File.join(APP_ROOT, 'LICENSE.txt'))
Display.app_name = '#{human_name(app_name)}'
Display.app_version = VERSION
end
require '#{file_name(app_name)}/view/app_view'
MULTI_LINE_STRING
end
def gem_main_file(custom_widget_name, namespace = nil)
custom_widget_file_path = ''
custom_widget_file_path += "#{file_name(namespace)}/" if namespace
custom_widget_file_path += "view"
custom_widget_file_path += "/#{file_name(custom_widget_name)}"
<<~MULTI_LINE_STRING
$LOAD_PATH.unshift(File.expand_path('..', __FILE__))
require 'glimmer-dsl-swt'
require '#{custom_widget_file_path}'
MULTI_LINE_STRING
end
def app_launch_file(app_name)
<<~MULTI_LINE_STRING
require_relative '../#{file_name(app_name)}'
#{class_name(app_name)}::View::AppView.launch
MULTI_LINE_STRING
end
def app_bin_command_file(app_name_or_gem_name, custom_shell_name=nil, namespace=nil)
if custom_shell_name.nil?
runner = "File.expand_path('../../app/#{file_name(app_name_or_gem_name)}/launch.rb', __FILE__)"
else
runner = "File.expand_path('../../lib/#{app_name_or_gem_name}/launch.rb', __FILE__)"
end
<<~MULTI_LINE_STRING
#!/usr/bin/env jruby
runner = #{runner}
# Detect if inside a JAR file or not
if runner.include?('uri:classloader')
require runner
else
require 'glimmer/launcher'
launcher = Glimmer::Launcher.new([runner] + ARGV)
launcher.launch
end
MULTI_LINE_STRING
end
def gem_launch_file(gem_name, custom_shell_name, namespace)
# TODO change this so that it does not mix Glimmer unto the main object
<<~MULTI_LINE_STRING
require_relative '../#{gem_name}'
#{class_name(namespace)}::View::#{class_name(custom_shell_name)}.launch
MULTI_LINE_STRING
end
def gem_rakefile(custom_shell_name = nil, namespace = nil, gem_name = nil)
rakefile_content = File.read('Rakefile')
lines = rakefile_content.split("\n")
require_rake_line_index = lines.index(lines.detect {|l| l.include?("require 'rake'") })
lines.insert(require_rake_line_index, "require 'glimmer/launcher'")
gem_files_line_index = lines.index(lines.detect {|l| l.include?('# dependencies defined in Gemfile') })
if custom_shell_name
lines.insert(gem_files_line_index, " gem.files = Dir['VERSION', 'LICENSE.txt', 'app/**/*', 'bin/**/*', 'config/**/*', 'db/**/*', 'docs/**/*', 'fonts/**/*', 'icons/**/*', 'images/**/*', 'lib/**/*', 'script/**/*', 'sounds/**/*', 'vendor/**/*', 'videos/**/*']")
# the second executable is needed for warbler as it matches the gem name, which is the default expected file (alternatively in the future, we could do away with it and configure warbler to use the other file)
lines.insert(gem_files_line_index+1, " gem.require_paths = ['vendor', 'lib', 'app']")
lines.insert(gem_files_line_index+2, " gem.executables = ['#{file_name(custom_shell_name)}']") if custom_shell_name
else
lines.insert(gem_files_line_index, " gem.files = Dir['VERSION', 'LICENSE.txt', 'lib/**/*']")
end
spec_pattern_line_index = lines.index(lines.detect {|l| l.include?('spec.pattern =') })
lines.insert(spec_pattern_line_index+1, " spec.ruby_opts = [Glimmer::Launcher.jruby_os_specific_options]")
lines << "\nrequire 'glimmer/rake_task'\n"
file_content = lines.join("\n")
if custom_shell_name
file_content << <<~MULTI_LINE_STRING
Glimmer::RakeTask::Package.jpackage_extra_args =
" --name '#{human_name(custom_shell_name)}'" +
" --description '#{human_name(custom_shell_name)}'"
# You can add more options from https://docs.oracle.com/en/java/javase/16/jpackage/packaging-tool-user-guide.pdf
MULTI_LINE_STRING
end
file_content
end
def spec_helper_file
content = File.read('spec/spec_helper.rb')
lines = content.split("\n")
require_line_index = lines.index(lines.detect {|l| l.include?('RSpec.configure do') })
lines[require_line_index...require_line_index] = [
"require 'bundler/setup'",
'Bundler.require(:default, :development)',
]
configure_block_line_index = lines.index(lines.detect {|l| l.include?('RSpec.configure do') }) + 1
lines[configure_block_line_index...configure_block_line_index] = [
' # The following ensures rspec tests that instantiate and set Glimmer DSL widgets in @target get cleaned after',
' config.after do',
' @target.dispose if @target && @target.respond_to?(:dispose)',
' Glimmer::DSL::Engine.reset',
' end',
]
lines << "\nrequire 'glimmer/rake_task'\n"
lines.join("\n")
end
def custom_shell_file(custom_shell_name, namespace, shell_type, shell_options = {})
namespace_type = class_name(namespace) == class_name(current_dir_name) ? 'class' : 'module'
custom_shell_file_content = <<-MULTI_LINE_STRING
#{namespace_type} #{class_name(namespace)}
module View
class #{class_name(custom_shell_name)}
include Glimmer::UI::CustomShell
MULTI_LINE_STRING
if shell_type == :gem
custom_shell_file_content += <<-MULTI_LINE_STRING
APP_ROOT = File.expand_path('../../../..', __FILE__)
VERSION = File.read(File.join(APP_ROOT, 'VERSION'))
LICENSE = File.read(File.join(APP_ROOT, 'LICENSE.txt'))
Display.app_name = '#{human_name(custom_shell_name)}'
Display.app_version = VERSION
MULTI_LINE_STRING
end
custom_shell_file_content += <<-MULTI_LINE_STRING
## Add options like the following to configure CustomShell by outside consumers
#
# options :title, :background_color
# option :width, default: 320
# option :height, default: 240
#{'# ' if shell_type == :desktopify}option :greeting, default: 'Hello, World!'
## Use before_body block to pre-initialize variables to use in body
#
#
MULTI_LINE_STRING
if %i[gem app desktopify].include?(shell_type)
custom_shell_file_content += <<-MULTI_LINE_STRING
before_body do
@display = display {
on_about do
display_about_dialog
end
on_preferences do
#{shell_type == :desktopify ? 'display_about_dialog' : 'display_preferences_dialog'}
end
}
end
MULTI_LINE_STRING
else
custom_shell_file_content += <<-MULTI_LINE_STRING
# before_body do
#
# end
MULTI_LINE_STRING
end
custom_shell_file_content += <<-MULTI_LINE_STRING
## Use after_body block to setup observers for widgets in body
#
# after_body do
#
# end
## Add widget content inside custom shell body
## Top-most widget must be a shell or another custom shell
#
body {
shell#{'(:fill_screen)' if shell_type == :desktopify} {
# Replace example content below with custom shell content
minimum_size #{shell_type == :desktopify ? '768, 432' : '420, 240'}
image File.join(APP_ROOT, 'icons', 'windows', "#{human_name(current_dir_name)}.ico") if OS.windows?
image File.join(APP_ROOT, 'icons', 'linux', "#{human_name(current_dir_name)}.png") unless OS.windows?
text "#{human_name(namespace)}#{' - ' + human_name(custom_shell_name) if shell_type != :desktopify}"
MULTI_LINE_STRING
if shell_type == :desktopify
custom_shell_file_content += <<-MULTI_LINE_STRING
browser {
url "#{shell_options[:website]}"
}
MULTI_LINE_STRING
else
custom_shell_file_content += <<-MULTI_LINE_STRING
grid_layout
label(:center) {
text <= [self, :greeting]
font height: 40
layout_data :fill, :center, true, true
}
MULTI_LINE_STRING
end
if %i[gem app desktopify].include?(shell_type)
custom_shell_file_content += <<-MULTI_LINE_STRING
menu_bar {
menu {
text '&File'
menu_item {
text '&Preferences...'
on_widget_selected do
#{shell_type == :desktopify ? 'display_about_dialog' : 'display_preferences_dialog'}
end
}
}
menu {
text '&Help'
menu_item {
text '&About...'
on_widget_selected do
display_about_dialog
end
}
}
}
MULTI_LINE_STRING
end
custom_shell_file_content += <<-MULTI_LINE_STRING
}
}
MULTI_LINE_STRING
if %i[gem app desktopify].include?(shell_type)
custom_shell_file_content += <<-MULTI_LINE_STRING
def display_about_dialog
message_box(body_root) {
text 'About'
message "#{human_name(namespace)}#{" - #{human_name(custom_shell_name)}" if shell_type == :gem} \#{VERSION}\\n\\n\#{LICENSE}"
}.open
end
MULTI_LINE_STRING
end
if %i[gem app].include?(shell_type)
custom_shell_file_content += <<-MULTI_LINE_STRING
def display_preferences_dialog
dialog(swt_widget) {
grid_layout {
margin_height 5
margin_width 5
}
text 'Preferences'
group {
row_layout {
type :vertical
spacing 10
}
text 'Greeting'
font style: :bold
[
'Hello, World!',
'Howdy, Partner!'
].each do |greeting_text|
button(:radio) {
layout_data {
width 160
}
text greeting_text
selection <= [self, :greeting, on_read: ->(g) { g == greeting_text }]
on_widget_selected do |event|
self.greeting = event.widget.getText
end
}
end
}
}.open
end
MULTI_LINE_STRING
end
custom_shell_file_content += <<-MULTI_LINE_STRING
end
end
end
MULTI_LINE_STRING
end
def custom_widget_file(custom_widget_name, namespace)
namespace_type = class_name(namespace) == class_name(current_dir_name) ? 'class' : 'module'
<<-MULTI_LINE_STRING
#{namespace_type} #{class_name(namespace)}
module View
class #{class_name(custom_widget_name)}
include Glimmer::UI::CustomWidget
## Add options like the following to configure CustomWidget by outside consumers
#
# options :custom_text, :background_color
# option :foreground_color, default: :red
## Use before_body block to pre-initialize variables to use in body
#
#
# before_body do
#
# end
## Use after_body block to setup observers for widgets in body
#
# after_body do
#
| ruby | MIT | 449cf07ada1ec965ae2ac91715ccdf22488df4ca | 2026-01-04T17:52:38.125591Z | true |
AndyObtiva/glimmer-dsl-swt | https://github.com/AndyObtiva/glimmer-dsl-swt/blob/449cf07ada1ec965ae2ac91715ccdf22488df4ca/lib/glimmer/rake_task/package.rb | lib/glimmer/rake_task/package.rb | # Copyright (c) 2007-2025 Andy Maleh
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
require 'os'
# TODO refactor to nest under RakeTask namespace
module Glimmer
module RakeTask
module Package
JDK_VERSION = ' 18'
class << self
attr_accessor :jpackage_extra_args
def clean
require 'fileutils'
FileUtils.rm_rf('dist')
FileUtils.rm_rf('packages')
end
def gemspec
system 'rake gemspec:generate'
end
def gem
system 'rake build'
end
def lock_jars
puts 'Locking gem jar-dependencies by downloading and storing in vendor/jars...'
FileUtils.mkdir_p('vendor/jars')
command = "lock_jars --vendor-dir vendor/jars"
puts command
system command
end
def config
project_name = File.basename(File.expand_path('.'))
if !File.exists?('config/warble.rb')
puts 'Generating JAR configuration (config/warble.rb) to use with Warbler...'
FileUtils.mkdir_p('config')
if OS.windows?
system "jruby -S gem install warbler -v2.0.5 --no-document" unless warbler_exists?
else
system "bash -c '#{RVM_FUNCTION}\n cd .\n jruby -S gem install warbler -v2.0.5 --no-document\n'" unless warbler_exists?
end
if system('warble config')
new_config = File.read('config/warble.rb').split("\n").inject('') do |output, line|
if line.include?('config.dirs =')
line = line.sub('# ', '').sub(/=[^=\n]+$/, '= %w(app bin config db docs fonts icons images lib package script sounds vendor videos)')
end
if line.include?('config.includes =')
line = line.sub('# ', '').sub(/=[^=\n]+$/, "= FileList['LICENSE.txt', 'VERSION']")
end
if line.include?('config.autodeploy_dir =')
line = line.sub('# ', '')
end
output + "\n" + line
end
File.write('config/warble.rb', new_config)
else
puts 'Warbler executable "warble" is missing!'
end
end
end
def jar
FileUtils.mkdir_p('dist')
puts "Generating JAR with Warbler..."
system "jruby -S gem install warbler -v2.0.5 --no-document" unless warbler_exists?
system('warble')
end
def native(native_type=nil, native_extra_args)
puts "Generating native executable with jpackage..."
java_version = `jruby -v`
if java_version.include?(JDK_VERSION)
puts "Java Version #{JDK_VERSION} Detected!"
else
puts "WARNING! Glimmer Packaging Pre-Requisite Java Version #{JDK_VERSION} Is Not Found!"
end
require 'facets/string/titlecase'
require 'facets/string/underscore'
require 'facets/string/camelcase'
project_name = File.basename(File.expand_path('.'))
version_file = File.expand_path('./VERSION')
version = (File.read(version_file).strip if File.exists?(version_file) && File.file?(version_file)) rescue nil
license_file = File.expand_path('./LICENSE.txt')
license = (File.read(license_file).strip if File.exists?(license_file) && File.file?(license_file)) rescue nil
copyright = license.split("\n").first
human_name = project_name.underscore.titlecase
icon = "icons/#{OS.mac? ? 'macosx' : (OS.linux? ? 'linux' : 'windows')}/#{human_name}.#{OS.mac? ? 'icns' : (OS.linux? ? 'png' : 'ico')}"
native_type = 'app-image' if native_type.to_s.strip.empty?
if (`jpackage`.to_s.include?('Usage: jpackage') rescue nil)
FileUtils.rm_rf("packages/bundles")
FileUtils.mkdir_p('packages/bundles')
command = "jpackage"
command += " --type #{native_type}"
command += " --dest 'packages/bundles' --input 'dist' --main-class JarMain --main-jar '#{project_name}.jar' --name '#{human_name}' --vendor '#{human_name}' --icon '#{icon}' "
command += " --win-per-user-install --win-dir-chooser --win-menu --win-menu-group '#{human_name}' " if OS.windows? && native_type != 'app-image'
command += " --linux-menu-group '#{human_name}' " if OS.linux? && native_type != 'app-image'
command += " --java-options '-XstartOnFirstThread' --mac-package-name '#{human_name}' --mac-package-identifier 'org.#{project_name}.application.#{project_name}' " if OS.mac?
command += " --app-version \"#{version}\" " if version
command += " --license-file LICENSE.txt " if license && native_type != 'app-image'
command += " --copyright \"#{copyright}\" " if copyright
else
puts "jpackage does not exist in your Java installation. Please ensure jpackage is available in PATH environment variable."
return
end
Rake.application.load_rakefile # make sure to load potential jpackage_extra_args config in app Rakefile
command += " #{jpackage_extra_args} " if jpackage_extra_args
command += " #{ENV['JPACKAGE_EXTRA_ARGS']} " if ENV['JPACKAGE_EXTRA_ARGS']
command += " #{native_extra_args} " if native_extra_args
puts command
system command
end
private
def warbler_exists?
OS.windows? ? system('where warble') : system('which warble')
end
end
end
end
end
| ruby | MIT | 449cf07ada1ec965ae2ac91715ccdf22488df4ca | 2026-01-04T17:52:38.125591Z | false |
AndyObtiva/glimmer-dsl-swt | https://github.com/AndyObtiva/glimmer-dsl-swt/blob/449cf07ada1ec965ae2ac91715ccdf22488df4ca/lib/glimmer/rake_task/list.rb | lib/glimmer/rake_task/list.rb | # Copyright (c) 2007-2025 Andy Maleh
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
require 'text-table'
require 'facets/string/titlecase'
module Glimmer
module RakeTask
# Lists Glimmer related gems to use in rake_task.rb
class List
class << self
REGEX_GEM_LINE = /^([^\(]+) \(([^\)]+)\)$/
def custom_widget_gems(query=nil)
list_gems('glimmer-cw-', query) do |result|
puts
puts " Glimmer Custom Widget Gems#{" matching [#{query}]" if query} at rubygems.org:"
puts result
end
end
def custom_shell_gems(query=nil)
list_gems('glimmer-cs-', query) do |result|
puts
puts " Glimmer Custom Shell Gems#{" matching [#{query}]" if query} at rubygems.org:"
puts result
end
end
def custom_shape_gems(query=nil)
list_gems('glimmer-cp-', query) do |result|
puts
puts " Glimmer Custom Shape Gems#{" matching [#{query}]" if query} at rubygems.org:"
puts result
end
end
def dsl_gems(query=nil)
list_gems('glimmer-dsl-', query) do |result|
puts
puts " Glimmer DSL Gems#{" matching [#{query}]" if query} at rubygems.org:"
puts result
end
end
def list_gems(gem_prefix, query=nil, &printer)
lines = `gem search -d #{gem_prefix}`.split("\n")
gems = lines.slice_before {|l| l.match(REGEX_GEM_LINE) }.to_a
gems = gems.map do |gem|
{
name: gem[0].match(REGEX_GEM_LINE)[1],
version: gem[0].match(REGEX_GEM_LINE)[2],
author: gem[1].strip,
description: gem[4..-1]&.map(&:strip)&.join(' ').to_s
}
end.select do |gem|
query.nil? || "#{gem[:name]} #{gem[:author]} #{gem[:description]}".downcase.include?(query.to_s.downcase)
end
printer.call(tablify(gem_prefix, gems))
end
def tablify(gem_prefix, gems)
array_of_arrays = gems.map do |gem|
name, namespace = gem[:name].sub(gem_prefix, '').underscore.titlecase.split
human_name = name
human_name += " (#{namespace})" unless namespace.nil?
[
human_name,
gem[:name],
gem[:version],
gem[:author].sub('Author: ', ''),
gem[:description],
]
end
Text::Table.new(
:head => %w[Name Gem Version Author Description],
:rows => array_of_arrays,
:horizontal_padding => 1,
:vertical_boundary => ' ',
:horizontal_boundary => ' ',
:boundary_intersection => ' '
)
end
end
end
end
end
| ruby | MIT | 449cf07ada1ec965ae2ac91715ccdf22488df4ca | 2026-01-04T17:52:38.125591Z | false |
AndyObtiva/glimmer-dsl-swt | https://github.com/AndyObtiva/glimmer-dsl-swt/blob/449cf07ada1ec965ae2ac91715ccdf22488df4ca/lib/glimmer/ui/custom_shell.rb | lib/glimmer/ui/custom_shell.rb | # Copyright (c) 2007-2025 Andy Maleh
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
require 'glimmer/ui'
require 'glimmer/error'
module Glimmer
module UI
module CustomShell
include SuperModule
include Glimmer::UI::CustomWidget
class << self
def launch(*args, &content)
launched_custom_shell = send(keyword, *args, &content)
auto_exec do
launched_custom_shell.swt_widget.set_data('launched', true)
launched_custom_shell.open
end
end
end
def initialize(parent, *swt_constants, options, &content)
super
raise Error, 'Invalid custom shell (window) body root! Must be a shell (window) or another custom shell (window).' unless body_root.swt_widget.is_a?(org.eclipse.swt.widgets.Shell)
end
def swt_widget
if @swt_widget.nil? && children_owner
@swt_widget = children_owner.swt_widget
auto_exec do
@swt_widget.set_data('custom_widget', self)
@swt_widget.set_data('custom_shell', self)
@swt_widget.set_data('custom_window', self)
end
end
@swt_widget
end
# Classes may override
def open
body_root.open
end
# DO NOT OVERRIDE. JUST AN ALIAS FOR `#open`. OVERRIDE `#open` INSTEAD.
def show
open
end
# TODO consider using Forwardable instead
def close
body_root.close
end
def hide
body_root.hide
end
def visible?
body_root.visible?
end
def disposed?
swt_widget.is_disposed
end
def center_within_display
body_root.center_within_display
end
def start_event_loop
body_root.start_event_loop
end
end
CustomWindow = CustomShell
Application = CustomShell
end
end
| ruby | MIT | 449cf07ada1ec965ae2ac91715ccdf22488df4ca | 2026-01-04T17:52:38.125591Z | false |
AndyObtiva/glimmer-dsl-swt | https://github.com/AndyObtiva/glimmer-dsl-swt/blob/449cf07ada1ec965ae2ac91715ccdf22488df4ca/lib/glimmer/ui/custom_widget.rb | lib/glimmer/ui/custom_widget.rb | # Copyright (c) 2007-2025 Andy Maleh
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
require 'glimmer'
require 'glimmer/ui'
require 'glimmer/error'
require 'glimmer/swt/swt_proxy'
require 'glimmer/swt/display_proxy'
require 'glimmer/util/proc_tracker'
require 'glimmer/data_binding/observer'
require 'glimmer/data_binding/observable_model'
module Glimmer
module UI
module CustomWidget
include SuperModule
include DataBinding::ObservableModel
super_module_included do |klass|
# TODO clear memoization of WidgetProxy.swt_widget_class_for for a keyword if a custom widget was defined with that keyword
klass.include(Glimmer) unless klass.name.include?('Glimmer::UI::CustomShell')
Glimmer::UI::CustomWidget.add_custom_widget_namespaces_for(klass) unless klass.name.include?('Glimmer::UI::CustomShell')
end
class << self
def for(underscored_custom_widget_name)
unless flyweight_custom_widget_classes.keys.include?(underscored_custom_widget_name)
begin
extracted_namespaces = underscored_custom_widget_name.
to_s.
split(/__/).map do |namespace|
namespace.camelcase(:upper)
end
custom_widget_namespaces.each do |base|
extracted_namespaces.reduce(base) do |result, namespace|
if !result.constants.include?(namespace)
namespace = result.constants.detect {|c| c.to_s.upcase == namespace.to_s.upcase } || namespace
end
begin
flyweight_custom_widget_classes[underscored_custom_widget_name] = constant = result.const_get(namespace)
return constant if constant.ancestors.include?(Glimmer::UI::CustomWidget)
flyweight_custom_widget_classes[underscored_custom_widget_name] = constant
rescue => e
# Glimmer::Config.logger.debug {"#{e.message}\n#{e.backtrace.join("\n")}"}
flyweight_custom_widget_classes[underscored_custom_widget_name] = result
end
end
end
raise "#{underscored_custom_widget_name} has no custom widget class!"
rescue => e
Glimmer::Config.logger.debug {e.message}
Glimmer::Config.logger.debug {"#{e.message}\n#{e.backtrace.join("\n")}"}
flyweight_custom_widget_classes[underscored_custom_widget_name] = nil
end
end
flyweight_custom_widget_classes[underscored_custom_widget_name]
end
# Flyweight Design Pattern memoization cache. Can be cleared if memory is needed.
def flyweight_custom_widget_classes
@flyweight_custom_widget_classes ||= {}
end
# Returns keyword to use for this custom widget
def keyword
self.name.underscore.gsub('::', '__')
end
# Returns shortcut keyword to use for this custom widget (keyword minus namespace)
def shortcut_keyword
self.name.underscore.gsub('::', '__').split('__').last
end
def add_custom_widget_namespaces_for(klass)
Glimmer::UI::CustomWidget.namespaces_for_class(klass).drop(1).each do |namespace|
Glimmer::UI::CustomWidget.custom_widget_namespaces << namespace
end
end
def namespaces_for_class(m)
return [m] if m.name.nil?
namespace_constants = m.name.split(/::/).map(&:to_sym)
namespace_constants.reduce([Object]) do |output, namespace_constant|
output += [output.last.const_get(namespace_constant)]
end[1..-1].uniq.reverse
end
def custom_widget_namespaces
@custom_widget_namespaces ||= reset_custom_widget_namespaces
end
def reset_custom_widget_namespaces
@custom_widget_namespaces = Set[Object, Glimmer::UI]
end
# Allows defining convenience option accessors for an array of option names
# Example: `options :color1, :color2` defines `#color1` and `#color2`
# where they return the instance values `options[:color1]` and `options[:color2]`
# respectively.
# Can be called multiple times to set more options additively.
# When passed no arguments, it returns list of all option names captured so far
def options(*new_options)
new_options = new_options.compact.map(&:to_s).map(&:to_sym)
if new_options.empty?
@options ||= {} # maps options to defaults
else
new_options = new_options.reduce({}) {|new_options_hash, new_option| new_options_hash.merge(new_option => nil)}
@options = options.merge(new_options)
def_option_attr_accessors(new_options)
end
end
def option(new_option, default: nil)
new_option = new_option.to_s.to_sym
new_options = {new_option => default}
@options = options.merge(new_options)
def_option_attr_accessors(new_options)
end
def def_option_attr_accessors(new_options)
new_options.each do |option, default|
class_eval <<-end_eval, __FILE__, __LINE__
def #{option}
options[:#{option}]
end
def #{option}=(option_value)
self.options[:#{option}] = option_value
end
end_eval
end
end
def before_body(&block)
@before_body_block = block
end
def body(&block)
@body_block = block
end
def after_body(&block)
@after_body_block = block
end
end
attr_reader :body_root, :parent, :parent_proxy, :swt_style_symbols, :options
def initialize(parent, *swt_style_symbols, options, &content)
SWT::DisplayProxy.current_custom_widgets_and_shapes << self
@parent_proxy = @parent = parent
@parent_proxy = @parent&.get_data('proxy') if @parent.respond_to?(:get_data) && @parent.get_data('proxy')
@swt_style_symbols = swt_style_symbols
options ||= {}
@options = self.class.options.merge(options)
@content = Util::ProcTracker.new(content) if content
auto_exec { execute_hook('before_body') }
body_block = self.class.instance_variable_get("@body_block")
raise Glimmer::Error, 'Invalid custom widget for having no body! Please define body block!' if body_block.nil?
@body_root = auto_exec { instance_exec(&body_block) }
raise Glimmer::Error, 'Invalid custom widget for having an empty body! Please fill body block!' if @body_root.nil?
auto_exec do
@body_root.set_data('custom_widget', self)
end
auto_exec { execute_hook('after_body') }
auto_exec do
@dispose_listener_registration = @body_root.on_widget_disposed do
unless @body_root.shell_proxy.last_shell_closing?
observer_registrations.compact.each(&:deregister)
observer_registrations.clear
end
end
end
post_add_content if content.nil?
end
# Calls post_initialize_child on children_owner by default
# Subclasses may override to perform post initialization work on an added child
def post_initialize_child(child)
children_owner.post_initialize_child(child)
end
def post_add_content
SWT::DisplayProxy.current_custom_widgets_and_shapes.delete(self)
end
def swt_widget
if @swt_widget.nil? && children_owner
@swt_widget = children_owner.swt_widget
auto_exec do
@swt_widget.set_data('custom_widget', self)
end
end
@swt_widget
end
# returns calculated SWT style integer value from swt_style_symbols
# keep in mind that it would not work when using glimmer-only
# custom swt_style_symbols like :editable for table
# In that case, just reference swt_style_symbols array instead
def swt_style
@swt_style ||= SWT::SWTProxy[*@swt_style_symbols]
end
def observer_registrations
@observer_registrations ||= []
end
def can_handle_observation_request?(observation_request)
observation_request = observation_request.to_s
result = false
if observation_request.start_with?('on_updated_')
property = observation_request.sub(/^on_updated_/, '')
result = can_add_observer?(property)
end
result ||
(children_owner != body_root && children_owner&.can_handle_observation_request?(observation_request)) ||
body_root&.can_handle_observation_request?(observation_request)
end
def handle_observation_request(observation_request, &block)
observation_request = observation_request.to_s
if observation_request.start_with?('on_updated_')
property = observation_request.sub(/^on_updated_/, '') # TODO look into eliminating duplication from above
add_observer(DataBinding::Observer.proc(&block), property) if can_add_observer?(property)
elsif children_owner != body_root && children_owner&.can_handle_observation_request?(observation_request)
children_owner.handle_observation_request(observation_request, &block)
else
body_root.handle_observation_request(observation_request, &block)
end
end
def can_add_observer?(attribute_name)
has_instance_method?(attribute_name) ||
has_instance_method?("#{attribute_name}?") ||
(children_owner != @body_root && children_owner.can_add_observer?(attribute_name)) ||
@body_root.can_add_observer?(attribute_name)
end
def add_observer(observer, attribute_name)
if has_instance_method?(attribute_name)
super
elsif children_owner != @body_root && children_owner.can_add_observer?(attribute_name)
children_owner.add_observer(observer, attribute_name)
else
@body_root.add_observer(observer, attribute_name)
end
end
def has_attribute?(attribute_name, *args)
has_instance_method?(attribute_setter(attribute_name)) ||
(children_owner != @body_root && children_owner.has_attribute?(attribute_name, *args)) ||
@body_root.has_attribute?(attribute_name, *args)
end
def set_attribute(attribute_name, *args)
if has_instance_method?(attribute_setter(attribute_name))
send(attribute_setter(attribute_name), *args)
elsif (children_owner != @body_root && children_owner.has_attribute?(attribute_name, *args))
children_owner.set_attribute(attribute_name, *args)
else
@body_root.set_attribute(attribute_name, *args)
end
end
# This method ensures it has an instance method not coming from Glimmer DSL
def has_instance_method?(method_name)
respond_to?(method_name) and
!swt_widget&.respond_to?(method_name) and
(method(method_name) rescue nil) and
!method(method_name)&.source_location&.first&.include?('glimmer/dsl/engine.rb') and
!method(method_name)&.source_location&.first&.include?('glimmer/swt/widget_proxy.rb')
end
def get_attribute(attribute_name)
if has_instance_method?(attribute_name)
send(attribute_name)
elsif children_owner != @body_root && children_owner.has_attribute?(attribute_name)
children_owner.get_attribute(attribute_name)
else
@body_root.get_attribute(attribute_name)
end
end
def attribute_setter(attribute_name)
"#{attribute_name}="
end
def shell_proxy
@body_root.shell_proxy
end
def children_owner
@children_owner || @body_root
end
def disposed?
swt_widget.isDisposed
end
def has_style?(style)
(swt_style & SWT::SWTProxy[style]) == SWT::SWTProxy[style]
end
# TODO see if it is worth it to eliminate duplication of async_exec/sync_exec
# delegation to DisplayProxy, via a module
def async_exec(&block)
SWT::DisplayProxy.instance.async_exec(&block)
end
def sync_exec(&block)
SWT::DisplayProxy.instance.sync_exec(&block)
end
def timer_exec(delay_in_millis, &block)
SWT::DisplayProxy.instance.timer_exec(delay_in_millis, &block)
end
# Returns content block if used as an attribute reader (no args)
# Otherwise, if a block is passed, it adds it as content to this custom widget
def content(&block)
if block_given?
Glimmer::DSL::Engine.add_content(self, Glimmer::DSL::SWT::CustomWidgetExpression.new, self.class.keyword, &block)
else
@content
end
end
def method_missing(method, *args, &block)
# TODO Consider supporting a glimmer error silencing option for methods defined here
# but fail the glimmer DSL for the right reason to avoid seeing noise in the log output
if block && can_handle_observation_request?(method)
handle_observation_request(method, &block)
elsif children_owner != @body_root && children_owner.respond_to?(method, *args, &block)
children_owner.send(method, *args, &block)
else
body_root.send(method, *args, &block)
end
end
alias local_respond_to? respond_to?
def respond_to?(method, *args, &block)
super or
can_handle_observation_request?(method) or
children_owner.respond_to?(method, *args, &block) or
body_root.respond_to?(method, *args, &block)
end
private
def execute_hook(hook_name)
hook_block = self.class.instance_variable_get("@#{hook_name}_block")
return if hook_block.nil?
temp_method_name = "#{hook_name}_block_#{hook_block.hash.abs}_#{(Time.now.to_f * 1_000_000).to_i}"
singleton_class.define_method(temp_method_name, &hook_block)
send(temp_method_name)
singleton_class.send(:remove_method, temp_method_name)
end
end
end
end
| ruby | MIT | 449cf07ada1ec965ae2ac91715ccdf22488df4ca | 2026-01-04T17:52:38.125591Z | false |
AndyObtiva/glimmer-dsl-swt | https://github.com/AndyObtiva/glimmer-dsl-swt/blob/449cf07ada1ec965ae2ac91715ccdf22488df4ca/lib/glimmer/ui/custom_shape.rb | lib/glimmer/ui/custom_shape.rb | # Copyright (c) 2007-2025 Andy Maleh
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
require 'glimmer'
require 'glimmer/ui'
require 'glimmer/error'
require 'glimmer/swt/swt_proxy'
require 'glimmer/swt/display_proxy'
require 'glimmer/util/proc_tracker'
require 'glimmer/data_binding/observer'
require 'glimmer/data_binding/observable_model'
module Glimmer
module UI
module CustomShape
include SuperModule
include DataBinding::ObservableModel
super_module_included do |klass|
klass.include(Glimmer)
Glimmer::UI::CustomShape.add_custom_shape_namespaces_for(klass)
end
class << self
def for(underscored_custom_shape_name)
unless flyweight_custom_shape_classes.keys.include?(underscored_custom_shape_name)
begin
extracted_namespaces = underscored_custom_shape_name.
to_s.
split(/__/).map do |namespace|
namespace.camelcase(:upper)
end
custom_shape_namespaces.each do |base|
extracted_namespaces.reduce(base) do |result, namespace|
if !result.constants.include?(namespace)
namespace = result.constants.detect {|c| c.to_s.upcase == namespace.to_s.upcase } || namespace
end
begin
flyweight_custom_shape_classes[underscored_custom_shape_name] = constant = result.const_get(namespace)
return constant if constant.ancestors.include?(Glimmer::UI::CustomShape)
flyweight_custom_shape_classes[underscored_custom_shape_name] = constant
rescue => e
# Glimmer::Config.logger.debug {"#{e.message}\n#{e.backtrace.join("\n")}"}
flyweight_custom_shape_classes[underscored_custom_shape_name] = result
end
end
end
raise "#{underscored_custom_shape_name} has no custom shape class!"
rescue => e
Glimmer::Config.logger.debug {e.message}
Glimmer::Config.logger.debug {"#{e.message}\n#{e.backtrace.join("\n")}"}
flyweight_custom_shape_classes[underscored_custom_shape_name] = nil
end
end
flyweight_custom_shape_classes[underscored_custom_shape_name]
end
# Flyweight Design Pattern memoization cache. Can be cleared if memory is needed.
def flyweight_custom_shape_classes
@flyweight_custom_shape_classes ||= {}
end
# Returns keyword to use for this custom shape
def keyword
self.name.underscore.gsub('::', '__')
end
# Returns shortcut keyword to use for this custom shape (keyword minus namespace)
def shortcut_keyword
self.name.underscore.gsub('::', '__').split('__').last
end
def add_custom_shape_namespaces_for(klass)
Glimmer::UI::CustomShape.namespaces_for_class(klass).drop(1).each do |namespace|
Glimmer::UI::CustomShape.custom_shape_namespaces << namespace
end
end
def namespaces_for_class(m)
return [m] if m.name.nil?
namespace_constants = m.name.split(/::/).map(&:to_sym)
namespace_constants.reduce([Object]) do |output, namespace_constant|
output += [output.last.const_get(namespace_constant)]
end[1..-1].uniq.reverse
end
def custom_shape_namespaces
@custom_shape_namespaces ||= reset_custom_shape_namespaces
end
def reset_custom_shape_namespaces
@custom_shape_namespaces = Set[Object, Glimmer::UI]
end
# Allows defining convenience option accessors for an array of option names
# Example: `options :color1, :color2` defines `#color1` and `#color2`
# where they return the instance values `options[:color1]` and `options[:color2]`
# respectively.
# Can be called multiple times to set more options additively.
# When passed no arguments, it returns list of all option names captured so far
def options(*new_options)
new_options = new_options.compact.map(&:to_s).map(&:to_sym)
if new_options.empty?
@options ||= {} # maps options to defaults
else
new_options = new_options.reduce({}) {|new_options_hash, new_option| new_options_hash.merge(new_option => nil)}
@options = options.merge(new_options)
def_option_attr_accessors(new_options)
end
end
def option(new_option, default: nil)
new_option = new_option.to_s.to_sym
new_options = {new_option => default}
@options = options.merge(new_options)
def_option_attr_accessors(new_options)
end
def def_option_attr_accessors(new_options)
new_options.each do |option, default|
class_eval <<-end_eval, __FILE__, __LINE__
def #{option}
options[:#{option}]
end
def #{option}=(option_value)
self.options[:#{option}] = option_value
end
end_eval
end
end
def before_body(&block)
@before_body_block = block
end
def body(&block)
@body_block = block
end
def after_body(&block)
@after_body_block = block
end
end
attr_reader :body_root, :args, :parent, :parent_proxy, :options
def initialize(parent, *args, options, &content)
SWT::DisplayProxy.current_custom_widgets_and_shapes << self
@parent_proxy = @parent = parent
@parent_proxy = @parent&.get_data('proxy') if @parent.respond_to?(:get_data) && @parent.get_data('proxy')
@args = args
options ||= {}
@options = self.class.options.merge(options)
@content = Util::ProcTracker.new(content) if content
execute_hook('before_body')
body_block = self.class.instance_variable_get("@body_block")
raise Glimmer::Error, 'Invalid custom shape for having no body! Please define body block!' if body_block.nil?
@body_root = instance_exec(&body_block)
raise Glimmer::Error, 'Invalid custom shape for having an empty body! Please fill body block!' if @body_root.nil?
auto_exec do # TODO is this necessary given shape is a lightweight construct (not SWT widget) ?
@body_root.set_data('custom_shape', self)
end
auto_exec do
@dispose_listener_registration = @body_root.on_shape_disposed do
unless @body_root.shell_proxy.last_shell_closing?
observer_registrations.compact.each(&:deregister)
observer_registrations.clear
end
end
end
execute_hook('after_body')
post_add_content if content.nil?
end
# Subclasses may override to perform post initialization work on an added child
def post_initialize_child(child)
# No Op by default
end
def post_add_content
SWT::DisplayProxy.current_custom_widgets_and_shapes.delete(self)
end
def observer_registrations
@observer_registrations ||= []
end
def has_attribute?(attribute_name, *args)
has_instance_method?(attribute_setter(attribute_name)) ||
@body_root.has_attribute?(attribute_name, *args)
end
def set_attribute(attribute_name, *args)
if has_instance_method?(attribute_setter(attribute_name))
send(attribute_setter(attribute_name), *args)
else
@body_root.set_attribute(attribute_name, *args)
end
end
# This method ensures it has an instance method not coming from Glimmer DSL
def has_instance_method?(method_name)
respond_to?(method_name) and
!body_root&.respond_to?(method_name) and
(method(method_name) rescue nil) and
!method(method_name)&.source_location&.first&.include?('glimmer/dsl/engine.rb') and
!method(method_name)&.source_location&.first&.include?('glimmer/swt/custom/shape.rb')
end
def get_attribute(attribute_name)
if has_instance_method?(attribute_name)
send(attribute_name)
else
@body_root.get_attribute(attribute_name)
end
end
def attribute_setter(attribute_name)
"#{attribute_name}="
end
# TODO see if it is worth it to eliminate duplication of async_exec/sync_exec
# delegation to DisplayProxy, via a module
def async_exec(&block)
SWT::DisplayProxy.instance.async_exec(&block)
end
def sync_exec(&block)
SWT::DisplayProxy.instance.sync_exec(&block)
end
def timer_exec(delay_in_millis, &block)
SWT::DisplayProxy.instance.timer_exec(delay_in_millis, &block)
end
# Returns content block if used as an attribute reader (no args)
# Otherwise, if a block is passed, it adds it as content to this custom shape
def content(&block)
if block_given?
Glimmer::DSL::Engine.add_content(self, Glimmer::DSL::SWT::CustomShapeExpression.new, self.class.keyword, &block)
else
@content
end
end
# TODO consider bringing observer_registrations method from CustomWidget if needed
def can_handle_observation_request?(observation_request)
body_root&.can_handle_observation_request?(observation_request)
end
def handle_observation_request(observation_request, &block)
body_root.handle_observation_request(observation_request, &block)
end
# Sets data just like SWT widgets
def set_data(key=nil, value)
body_root.set_data(key, value)
end
alias setData set_data # for compatibility with SWT APIs
# Gets data just like SWT widgets
def get_data(key=nil)
body_root.get_data(key)
end
alias getData get_data # for compatibility with SWT APIs
alias data get_data # for compatibility with SWT APIs
def dispose(dispose_images: true, dispose_patterns: true, redraw: true)
body_root.dispose(dispose_images: dispose_images, dispose_patterns: dispose_patterns, redraw: redraw)
# @dispose_listener_registration.deregister # TODO enable once returning a true listener object or observer proc registration
end
def disposed
body_root.disposed
end
alias disposed? disposed
alias is_disposed disposed
def method_missing(method_name, *args, &block)
# TODO Consider supporting a glimmer error silencing option for methods defined here
# but fail the glimmer DSL for the right reason to avoid seeing noise in the log output
if block && can_handle_observation_request?(method_name)
handle_observation_request(method_name, &block)
else
body_root.send(method_name, *args, &block)
end
end
alias local_respond_to? respond_to?
def respond_to?(method_name, *args, &block)
super or
can_handle_observation_request?(method_name) or
body_root.respond_to?(method_name, *args, &block)
end
private
def execute_hook(hook_name)
hook_block = self.class.instance_variable_get("@#{hook_name}_block")
return if hook_block.nil?
temp_method_name = "#{hook_name}_block_#{hook_block.hash.abs}_#{(Time.now.to_f * 1_000_000).to_i}"
singleton_class.define_method(temp_method_name, &hook_block)
send(temp_method_name)
singleton_class.send(:remove_method, temp_method_name)
end
end
end
end
| ruby | MIT | 449cf07ada1ec965ae2ac91715ccdf22488df4ca | 2026-01-04T17:52:38.125591Z | false |
IF977/if977 | https://github.com/IF977/if977/blob/b2dfbaf030b3a693b2d52fa323292846d56e397a/hws/vcg-hw1/spec/rock_paper_scissors_spec.rb | hws/vcg-hw1/spec/rock_paper_scissors_spec.rb | require 'rock_paper_scissors'
require 'debugger'
#describe RockPaperScissors, :pending => true do
describe RockPaperScissors do
before(:each) do
@rock = ['Armando','R'] ; @paper = ['Dave','P'] ; @scissors = ['Sam','S']
end
describe 'game' do
it 'rock breaks scissors [10 points]' do
RockPaperScissors.winner(@rock, @scissors).should == @rock
end
it 'scissors cut paper [10 points]' do
RockPaperScissors.winner(@paper, @scissors).should == @scissors
end
it 'paper covers rock [10 points]' do
RockPaperScissors.winner(@rock, @paper).should == @paper
end
it 'first player wins if both use same strategy [10 points]' do
RockPaperScissors.winner(@scissors, ['Dave','S']).should == @scissors
end
end
it "should raise NoSuchStrategyError if strategy isn't R, P, or S [10 points]" do
lambda { RockPaperScissors.winner(@rock, ['Dave', 'w']) }.
should raise_error(RockPaperScissors::NoSuchStrategyError,
"Strategy must be one of R,P,S")
end
describe 'tournament' do
it 'base case [20 points]' do
RockPaperScissors.tournament_winner([@rock,@paper]).should == @paper
end
it 'recursive case [30 points]' do
tourney = [
[
[ ["Armando", "P"], ["Dave", "S"] ],
[ ["Richard", "R"], ["Michael", "S"] ]
],
[
[ ["Allen", "S"], ["Omer", "P"] ],
[ ["David E.", "R"], ["Richard X.", "P"] ]
]
]
RockPaperScissors.tournament_winner(tourney).should == ['Richard', 'R']
end
end
end
| ruby | MIT | b2dfbaf030b3a693b2d52fa323292846d56e397a | 2026-01-04T17:52:02.326044Z | false |
IF977/if977 | https://github.com/IF977/if977/blob/b2dfbaf030b3a693b2d52fa323292846d56e397a/hws/vcg-hw1/spec/dessert_spec.rb | hws/vcg-hw1/spec/dessert_spec.rb | require 'dessert'
require 'debugger'
#describe Dessert, :pending => true do
describe Dessert do
describe 'cake' do
before :each do
@subject = Dessert.new('cake', 400)
end
it 'should have 400 calories [10 points]' do
@subject.calories.should == 400
end
it 'should be named cake [10 points]' do
@subject.name.should == 'cake'
end
it 'should be delicious [10 points]' do
@subject.should be_delicious
end
it 'should not be healthy [10 points]' do
@subject.should_not be_healthy
end
end
describe 'apple' do
before :each do
@subject = Dessert.new('apple', 75)
end
it 'should be delicious [10 points]' do
@subject.should be_delicious
end
it 'should be healthy [10 points]' do
@subject.should be_healthy
end
end
describe 'can set' do
before(:each) { @dessert = Dessert.new('xxx', 0) }
it 'calories [10 points]' do
@dessert.calories = 80
@dessert.calories.should == 80
end
it 'name [10 points]' do
@dessert.name = 'ice cream'
@dessert.name.should == 'ice cream'
end
end
end
#describe JellyBean, :pending => true do
describe JellyBean do
describe 'when non-licorice' do
before :each do
@subject = JellyBean.new('vanilla')
end
it 'should contain 5 calories [5 points]' do
@subject.calories.should == 5
end
it 'should be named vanilla jelly bean [5 points]' do
@subject.name.should match /vanilla jelly bean/i
end
it 'should be delicious [5 points]' do
@subject.should be_delicious
end
end
describe 'when licorice' do
before :each do
@subject = JellyBean.new('licorice')
end
it 'should not be delicious [5 points]' do
@subject.should_not be_delicious
end
end
end
| ruby | MIT | b2dfbaf030b3a693b2d52fa323292846d56e397a | 2026-01-04T17:52:02.326044Z | false |
IF977/if977 | https://github.com/IF977/if977/blob/b2dfbaf030b3a693b2d52fa323292846d56e397a/hws/vcg-hw1/spec/attr_accessor_with_history_spec.rb | hws/vcg-hw1/spec/attr_accessor_with_history_spec.rb | require 'attr_accessor_with_history'
require 'debugger'
class TestClass1
attr_accessor_with_history :foo
end
class TestClass2
attr_accessor_with_history 'foo'
end
describe '#attr_accessor_with_history', :pending => true do
shared_examples 'all cases' do
it 'should define getter and setter [5 points]' do
@subject.foo = 'xyz'
@subject.foo.should == 'xyz'
end
it 'setter should return value set to [5 points]' do
(@subject.foo = 'xyz').should == 'xyz'
end
it 'should work if getter used first [10 points]' do
@subject.foo_history.should be_nil
end
it 'should work if setter used first [20 points]' do
@subject.foo = 'x'
@subject.foo = 'y'
@subject.foo_history.should == [nil, 'x']
end
it 'should remember values [10 points]' do
@subject.foo
@subject.foo = 3
@subject.foo = 'x'
@subject.foo_history.should == [nil, 3]
end
end
describe 'when a symbol is passed [10 points]' do
before(:each) { @subject = TestClass1.new }
include_examples 'all cases'
end
describe 'when a string is passed [10 points]' do
before(:each) { @subject = TestClass2.new }
include_examples 'all cases'
end
it 'should remember history separately for each instance [30 points]' do
obj1 = TestClass1.new
obj2 = TestClass1.new
obj1.foo = :x ; obj1.foo = :y
obj2.foo = 1 ; obj2.foo = 2
obj1.foo_history.should == [nil, :x]
obj2.foo_history.should == [nil, 1]
end
end
| ruby | MIT | b2dfbaf030b3a693b2d52fa323292846d56e397a | 2026-01-04T17:52:02.326044Z | false |
IF977/if977 | https://github.com/IF977/if977/blob/b2dfbaf030b3a693b2d52fa323292846d56e397a/hws/vcg-hw1/spec/fun_with_strings_spec.rb | hws/vcg-hw1/spec/fun_with_strings_spec.rb | require_relative '../lib/fun_with_strings'
require 'rspec'
require 'debugger'
#describe 'palindrome detection', :pending => true do
describe 'palindrome detection' do
it 'should work for simple strings [10 points]' do
'redivider'.should be_a_palindrome
'abracadabra'.should_not be_a_palindrome
end
it 'should be case-insensitive [10 points]' do
'ReDivider'.should be_a_palindrome
end
it 'should ignore nonword characters [10 points]' do
'A man, a plan, a canal -- Panama'.should be_a_palindrome
"Madam, I'm Adam!".should be_a_palindrome
end
end
#describe 'word count', :pending => true do
describe 'word count' do
it 'should return a hash [5 points]' do
'now is the time'.count_words.should be_a_kind_of Hash
end
it 'works on simple strings [10 points]' do
'Doo bee doo bee doo'.count_words.should ==
{'doo' => 3, 'bee' => 2}
end
it 'ignores punctuation [5 points]' do
'A man, a plan, a canal -- Panama!'.count_words.should ==
{'man' => 1, 'plan' => 1, 'canal' => 1, 'a' => 3, 'panama' => 1}
end
it 'works on the empty string [10 points]' do
''.count_words.should == {}
end
it 'ignores leading whitespace [10 points]' do
" toucan".count_words.should ==
{'toucan' => 1 }
end
it 'ignores embedded whitespace [10 points]' do
"four four \n four \t four!".count_words.should ==
{'four' => 4}
end
end
#describe 'anagram grouping', :pending => true do
describe 'anagram grouping' do
describe 'sanity checks' do
it 'should work on the empty string [5 points]' do
''.anagram_groups.should == []
end
it 'should return an array of arrays for nonempty string [5 points]' do
'x'.anagram_groups.each { |element| element.should be_an Array }
end
end
it 'for "scream cars for four scar creams" [10 points]' do
@anagrams = 'scream cars for four scar creams'.anagram_groups
@anagrams.each { |group| group.sort! }
[%w(cars scar), %w(four), %w(for), %w(creams scream)].each do |group|
@anagrams.should include(group)
end
end
end
| ruby | MIT | b2dfbaf030b3a693b2d52fa323292846d56e397a | 2026-01-04T17:52:02.326044Z | false |
IF977/if977 | https://github.com/IF977/if977/blob/b2dfbaf030b3a693b2d52fa323292846d56e397a/hws/vcg_hw0/spec/vcg_hw0_part1_spec.rb | hws/vcg_hw0/spec/vcg_hw0_part1_spec.rb | require 'spec_helper'
describe 'Ruby intro part 1' do
describe "#sum" do
it "should be defined" do
expect { sum([1,3,4]) }.not_to raise_error
end
it "returns correct sum [20 points]" do
expect(sum([1,2,3,4,5])).to be_a_kind_of Integer
expect(sum([1,2,3,4,5])).to be == 15
expect(sum([1,2,3,4,-5])).to be == 5
expect(sum([1,2,3,4,-5,5,-100])).to be == -90
end
it "works on the empty array [10 points]" do
expect { sum([]) }.not_to raise_error
expect(sum([])).to be_zero
end
end
describe "#max_2_sum" do
it "should be defined" do
expect { max_2_sum([1,2,3]) }.not_to raise_error
end
it "returns the correct sum [7 points]" do
expect(max_2_sum([1,2,3,4,5])).to be_a_kind_of Integer
expect(max_2_sum([1,-2,-3,-4,-5])).to be == -1
end
it 'works even if 2 largest values are the same [3 points]' do
expect(max_2_sum([1,2,3,3])).to be == 6
end
it "returns zero if array is empty [10 points]" do
expect(max_2_sum([])).to be_zero
end
it "returns value of the element if just one element [10 points]" do
expect(max_2_sum([3])).to be == 3
end
end
describe "#sum_to_n" do
it "should be defined" do
expect { sum_to_n?([1,2,3],4) }.not_to raise_error
end
it "returns true when any two elements sum to the second argument [30 points]" do
expect(sum_to_n?([1,2,3,4,5], 5)).to be true
expect(sum_to_n?([3,0,5], 5)).to be true
expect(sum_to_n?([-1,-2,3,4,5,-8], 12)).to be false
expect(sum_to_n?([-1,-2,3,4,6,-8], 12)).to be false
end
it "returns false for the single element array [5 points]" do
expect(sum_to_n?([1], 1)).to be false
expect(sum_to_n?([3], 0)).to be false
end
it "returns false for the empty array [5 points]" do
expect(sum_to_n?([], 0)).to be false
expect(sum_to_n?([], 7)).to be false
end
end
end | ruby | MIT | b2dfbaf030b3a693b2d52fa323292846d56e397a | 2026-01-04T17:52:02.326044Z | false |
IF977/if977 | https://github.com/IF977/if977/blob/b2dfbaf030b3a693b2d52fa323292846d56e397a/hws/vcg_hw0/spec/vcg_hw0_part3_spec.rb | hws/vcg_hw0/spec/vcg_hw0_part3_spec.rb | require 'spec_helper'
describe "BookInStock" do
it "should be defined" do
expect { BookInStock }.not_to raise_error
end
describe 'getters and setters' do
before(:each) { @book = BookInStock.new('isbn1', 33.8) }
it 'should set ISBN [10 points]' do
expect(@book.isbn).to be == 'isbn1'
end
it 'should set price [10 points]' do
expect(@book.price).to be == 33.8
end
it 'should be able to change ISBN [10 points]' do
@book.isbn = 'isbn2'
expect(@book.isbn).to be == 'isbn2'
end
it 'should be able to change price [10 points]' do
@book.price = 300.0
expect(@book.price).to be == 300.0
end
end
describe 'constructor' do
it 'should reject invalid ISBN number [10 points]' do
expect { BookInStock.new('', 25.00) }.to raise_error(ArgumentError)
end
it 'should reject zero price [10 points]' do
expect { BookInStock.new('isbn1', 0) }.to raise_error(ArgumentError)
end
it 'should reject negative price [10 points]' do
expect { BookInStock.new('isbn1', -5.0) }.to raise_error(ArgumentError)
end
end
describe "#price_as_string" do
it "should be defined" do
expect(BookInStock.new('isbn1', 10)).to respond_to(:price_as_string)
end
it 'should display 33.95 as "$33.95" [10 points]' do
expect(BookInStock.new('isbn11', 33.95).price_as_string).to be == '$33.95'
end
it "should display 1.1 as $1.10 [10 points]" do
expect(BookInStock.new('isbn11', 1.1).price_as_string).to be == '$1.10'
end
it "should display 20 as $20.00 [10 points]" do
expect(BookInStock.new('isbn11', 20).price_as_string).to be == '$20.00'
end
end
end | ruby | MIT | b2dfbaf030b3a693b2d52fa323292846d56e397a | 2026-01-04T17:52:02.326044Z | false |
IF977/if977 | https://github.com/IF977/if977/blob/b2dfbaf030b3a693b2d52fa323292846d56e397a/hws/vcg_hw0/spec/vcg_hw0_part2_spec.rb | hws/vcg_hw0/spec/vcg_hw0_part2_spec.rb | require 'spec_helper'
describe "#hello" do
it "should be defined" do
expect { hello("Testing") }.not_to raise_error()
#expect { hello("Testing") }.not_to raise_error(::NoMethodError)
end
it "The hello method returns the correct string [30 points]" do
expect(hello("Dan").class).to be == String
expect(hello("Dan")).to eq('Hello, Dan'), "Incorrect results for input: \"Dan\""
expect(hello("BILL")).to eq('Hello, BILL'), "Incorrect results for input: \"BILL\""
expect(hello("Mr. Ilson")).to eq('Hello, Mr. Ilson'), "Incorrect results for input: \"Mr. Ilson\""
end
end
describe "#starts_with_consonant?" do
it "should be defined" do
#expect { starts_with_consonant?("d") }.not_to raise_error(::NoMethodError)
expect { starts_with_consonant?("d") }.not_to raise_error()
end
it 'classifies true cases [10 points]' do
expect(starts_with_consonant?('v')).to be true #, "'v' is a consonant"
['v', 'vest', 'Veeee', 'crypt'].each do |string|
expect(starts_with_consonant?(string)).to be true #, "Incorrect results for input: \"#{string}\""
end
end
it 'classifies false cases [10 points]' do
expect(starts_with_consonant?('a')).to be false #, "'a' is not a consonant"
['asdfgh', 'Unix'].each do |string|
expect(starts_with_consonant?(string)).to be false #, "Incorrect results for input: \"#{string}\""
end
end
it 'works on the empty string [5 points]' do
expect(starts_with_consonant?('')).to be false
end
it 'works on nonletters [5 points]' do
expect(starts_with_consonant?('#foo')).to be false
end
end
describe "#binary_multiple_of_4?" do
it "should be defined" do
#expect { binary_multiple_of_4?("yes") }.not_to raise_error(::NoMethodError)
expect { binary_multiple_of_4?("yes") }.not_to raise_error()
end
it "classifies valid binary numbers [30 points]" do
["1010101010100", "0101010101010100", "100", "0"].each do |string|
expect(binary_multiple_of_4?(string)).to be true #, "Incorrect results for input: \"#{string}\""
end
["101", "1000000000001"].each do |string|
expect(binary_multiple_of_4?(string)).not_to be true #, "Incorrect results for input: \"#{string}\""
end
end
it "rejects invalid binary numbers [10 points]" do
expect(binary_multiple_of_4?('a100')).to be false #, "'a100' is not a valid binary number!"
expect(binary_multiple_of_4?('')).to be false #, "The empty string is not a valid binary number!"
end
end | ruby | MIT | b2dfbaf030b3a693b2d52fa323292846d56e397a | 2026-01-04T17:52:02.326044Z | false |
IF977/if977 | https://github.com/IF977/if977/blob/b2dfbaf030b3a693b2d52fa323292846d56e397a/hws/vcg_hw0/spec/spec_helper.rb | hws/vcg_hw0/spec/spec_helper.rb | require_relative '../vcg_hw0_part1'
require_relative '../vcg_hw0_part2'
require_relative '../vcg_hw0_part3'
#require 'yaml' | ruby | MIT | b2dfbaf030b3a693b2d52fa323292846d56e397a | 2026-01-04T17:52:02.326044Z | false |
grab/engineering-blog | https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/eventmachine-1.2.7/tests/test_tick_loop.rb | _vendor/ruby/2.6.0/gems/eventmachine-1.2.7/tests/test_tick_loop.rb | require "test/unit"
require 'em_test_helper'
class TestEmTickLoop < Test::Unit::TestCase
def test_em_tick_loop
i = 0
EM.tick_loop { i += 1; EM.stop if i == 10 }
EM.run { EM.add_timer(1) { EM.stop } }
assert_equal i, 10
end
def test_tick_loop_on_stop
t = nil
tick_loop = EM.tick_loop { :stop }
tick_loop.on_stop { t = true }
EM.run { EM.next_tick { EM.stop } }
assert t
end
def test_start_twice
i = 0
s = 0
tick_loop = EM.tick_loop { i += 1; :stop }
tick_loop.on_stop { s += 1; EM.stop }
EM.run { EM.next_tick { EM.stop } }
assert_equal 1, i
assert_equal 1, s
tick_loop.start
EM.run { EM.next_tick { EM.stop } }
assert_equal 2, i
assert_equal 1, s # stop callbacks are only called once
end
def test_stop
i, s = 0, 0
tick_loop = EM.tick_loop { i += 1 }
tick_loop.on_stop { s += 1 }
EM.run { EM.next_tick { tick_loop.stop; EM.next_tick { EM.stop } } }
assert tick_loop.stopped?
assert_equal 1, i
assert_equal 1, s
end
def test_immediate_stops
s = 0
tick_loop = EM::TickLoop.new { }
tick_loop.on_stop { s += 1 }
tick_loop.on_stop { s += 1 }
assert_equal 2, s
end
def test_stopped
tick_loop = EM::TickLoop.new { }
assert tick_loop.stopped?
tick_loop.start
assert !tick_loop.stopped?
end
end | ruby | MIT | d8026a4e9cc6348bf38951ee96c523f4ec19f3c4 | 2026-01-04T17:45:10.474201Z | false |
grab/engineering-blog | https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/eventmachine-1.2.7/tests/test_pause.rb | _vendor/ruby/2.6.0/gems/eventmachine-1.2.7/tests/test_pause.rb | require 'em_test_helper'
class TestPause < Test::Unit::TestCase
if EM.respond_to? :pause_connection
def setup
@port = next_port
end
def teardown
assert(!EM.reactor_running?)
end
def test_pause_resume
server = nil
s_rx = c_rx = 0
test_server = Module.new do
define_method :post_init do
server = self
end
define_method :receive_data do |data|
s_rx += 1
EM.add_periodic_timer(0.01) { send_data 'hi' }
send_data 'hi'
# pause server, now no outgoing data will actually
# be sent and no more incoming data will be received
pause
end
end
test_client = Module.new do
def post_init
EM.add_periodic_timer(0.01) do
send_data 'hello'
end
end
define_method :receive_data do |data|
c_rx += 1
end
end
EM.run do
EM.start_server "127.0.0.1", @port, test_server
EM.connect "127.0.0.1", @port, test_client
EM.add_timer(0.05) do
assert_equal 1, s_rx
assert_equal 0, c_rx
assert server.paused?
# resume server, queued outgoing and incoming data will be flushed
server.resume
assert !server.paused?
EM.add_timer(0.05) do
assert server.paused?
assert s_rx > 1
assert c_rx > 0
EM.stop
end
end
end
end
def test_pause_in_receive_data
incoming = []
test_server = Module.new do
define_method(:receive_data) do |data|
incoming << data
pause
EM.add_timer(0.5){ close_connection }
end
define_method(:unbind) do
EM.stop
end
end
buf = 'a' * 1024
EM.run do
EM.start_server "127.0.0.1", @port, test_server
cli = EM.connect "127.0.0.1", @port
128.times do
cli.send_data buf
end
end
assert_equal 1, incoming.size
assert incoming[0].bytesize > buf.bytesize
assert incoming[0].bytesize < buf.bytesize * 128
end
else
warn "EM.pause_connection not implemented, skipping tests in #{__FILE__}"
# Because some rubies will complain if a TestCase class has no tests
def test_em_pause_connection_not_implemented
assert true
end
end
end
| ruby | MIT | d8026a4e9cc6348bf38951ee96c523f4ec19f3c4 | 2026-01-04T17:45:10.474201Z | false |
grab/engineering-blog | https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/eventmachine-1.2.7/tests/test_queue.rb | _vendor/ruby/2.6.0/gems/eventmachine-1.2.7/tests/test_queue.rb | require 'em_test_helper'
class TestEMQueue < Test::Unit::TestCase
def test_queue_push
s = 0
EM.run do
q = EM::Queue.new
q.push(1)
EM.next_tick { s = q.size; EM.stop }
end
assert_equal 1, s
end
def test_queue_pop
x,y,z = nil
EM.run do
q = EM::Queue.new
q.push(1,2,3)
q.pop { |v| x = v }
q.pop { |v| y = v }
q.pop { |v| z = v; EM.stop }
end
assert_equal 1, x
assert_equal 2, y
assert_equal 3, z
end
def test_queue_reactor_thread
q = EM::Queue.new
Thread.new { q.push(1,2,3) }.join
assert q.empty?
EM.run { EM.next_tick { EM.stop } }
assert_equal 3, q.size
x = nil
Thread.new { q.pop { |v| x = v } }.join
assert_equal nil, x
EM.run { EM.next_tick { EM.stop } }
assert_equal 1, x
end
def test_num_waiting
q = EM::Queue.new
many = 3
many.times { q.pop {} }
EM.run { EM.next_tick { EM.stop } }
assert_equal many, q.num_waiting
end
def test_big_queue
EM.run do
q = EM::Queue.new
2000.times do |i|
q.push(*0..1000)
q.pop { |v| assert_equal v, i % 1001 }
end
q.pop do
assert_equal 1_999_999, q.size
EM.stop
end
end
end
end
| ruby | MIT | d8026a4e9cc6348bf38951ee96c523f4ec19f3c4 | 2026-01-04T17:45:10.474201Z | false |
grab/engineering-blog | https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/eventmachine-1.2.7/tests/test_pool.rb | _vendor/ruby/2.6.0/gems/eventmachine-1.2.7/tests/test_pool.rb | require 'em_test_helper'
class TestPool < Test::Unit::TestCase
def pool
@pool ||= EM::Pool.new
end
def go
EM.run { yield }
end
def stop
EM.stop
end
def deferrable
@deferrable ||= EM::DefaultDeferrable.new
end
def test_supports_more_work_than_resources
ran = false
go do
pool.perform do
ran = true
deferrable
end
stop
end
assert_equal false, ran
go do
pool.add :resource
stop
end
assert_equal true, ran
end
def test_reques_resources_on_error
pooled_res, pooled_res2 = nil
pool.add :res
go do
pool.perform do |res|
pooled_res = res
deferrable
end
stop
end
deferrable.fail
go do
pool.perform do |res|
pooled_res2 = res
deferrable
end
stop
end
assert_equal :res, pooled_res
assert_equal pooled_res, pooled_res2
end
def test_supports_custom_on_error
eres = nil
pool.on_error do |res|
eres = res
end
performs = []
pool.add :res
go do
pool.perform do |res|
performs << res
deferrable
end
pool.perform do |res|
performs << res
deferrable
end
deferrable.fail
stop
end
assert_equal :res, eres
# manual requeues required when error handler is installed:
assert_equal 1, performs.size
assert_equal :res, performs.first
end
def test_catches_successful_deferrables
performs = []
pool.add :res
go do
pool.perform { |res| performs << res; deferrable }
pool.perform { |res| performs << res; deferrable }
stop
end
assert_equal [:res], performs
deferrable.succeed
go { stop }
assert_equal [:res, :res], performs
end
def test_prunes_locked_and_removed_resources
performs = []
pool.add :res
deferrable.succeed
go do
pool.perform { |res| performs << res; pool.remove res; deferrable }
pool.perform { |res| performs << res; pool.remove res; deferrable }
stop
end
assert_equal [:res], performs
end
# Contents is only to be used for inspection of the pool!
def test_contents
pool.add :res
assert_equal [:res], pool.contents
# Assert that modifying the contents list does not affect the pools
# contents.
pool.contents.delete(:res)
assert_equal [:res], pool.contents
end
def test_contents_when_perform_errors_and_on_error_is_not_set
pool.add :res
assert_equal [:res], pool.contents
pool.perform do |r|
d = EM::DefaultDeferrable.new
d.fail
d
end
EM.run { EM.next_tick { EM.stop } }
assert_equal [:res], pool.contents
end
def test_contents_when_perform_errors_and_on_error_is_set
pool.add :res
res = nil
pool.on_error do |r|
res = r
end
assert_equal [:res], pool.contents
pool.perform do |r|
d = EM::DefaultDeferrable.new
d.fail 'foo'
d
end
EM.run { EM.next_tick { EM.stop } }
assert_equal :res, res
assert_equal [], pool.contents
end
def test_num_waiting
pool.add :res
assert_equal 0, pool.num_waiting
pool.perform { |r| EM::DefaultDeferrable.new }
assert_equal 0, pool.num_waiting
10.times { pool.perform { |r| EM::DefaultDeferrable.new } }
EM.run { EM.next_tick { EM.stop } }
assert_equal 10, pool.num_waiting
end
def test_exceptions_in_the_work_block_bubble_up_raise_and_fail_the_resource
pool.add :res
res = nil
pool.on_error { |r| res = r }
pool.perform { raise 'boom' }
assert_raises(RuntimeError) do
EM.run { EM.next_tick { EM.stop } }
end
assert_equal [], pool.contents
assert_equal :res, res
end
def test_removed_list_does_not_leak_on_errors
pool.add :res
pool.on_error do |r|
# This is actually the wrong thing to do, and not required, but some users
# might do it. When they do, they would find that @removed would cause a
# slow leak.
pool.remove r
end
pool.perform { d = EM::DefaultDeferrable.new; d.fail; d }
EM.run { EM.next_tick { EM.stop } }
assert_equal [], pool.instance_variable_get(:@removed)
end
end
| ruby | MIT | d8026a4e9cc6348bf38951ee96c523f4ec19f3c4 | 2026-01-04T17:45:10.474201Z | false |
grab/engineering-blog | https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/eventmachine-1.2.7/tests/test_pending_connect_timeout.rb | _vendor/ruby/2.6.0/gems/eventmachine-1.2.7/tests/test_pending_connect_timeout.rb | require 'em_test_helper'
class TestPendingConnectTimeout < Test::Unit::TestCase
if EM.respond_to? :get_pending_connect_timeout
def test_default
EM.run {
c = EM.connect("127.0.0.1", 54321)
assert_equal 20.0, c.pending_connect_timeout
EM.stop
}
end
def test_set_and_get
EM.run {
c = EM.connect("127.0.0.1", 54321)
c.pending_connect_timeout = 2.5
assert_equal 2.5, c.pending_connect_timeout
EM.stop
}
end
def test_for_real
start, finish = nil
timeout_handler = Module.new do
define_method :unbind do
finish = EM.current_time
EM.stop
end
end
EM.run {
setup_timeout
EM.heartbeat_interval = 0.1
start = EM.current_time
c = EM.connect('192.0.2.0', 54321, timeout_handler)
c.pending_connect_timeout = 0.2
}
assert_in_delta(0.2, (finish - start), 0.1)
end
else
warn "EM.pending_connect_timeout not implemented, skipping tests in #{__FILE__}"
# Because some rubies will complain if a TestCase class has no tests
def test_em_pending_connect_timeout_not_implemented
assert true
end
end
end
| ruby | MIT | d8026a4e9cc6348bf38951ee96c523f4ec19f3c4 | 2026-01-04T17:45:10.474201Z | false |
grab/engineering-blog | https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/eventmachine-1.2.7/tests/test_running.rb | _vendor/ruby/2.6.0/gems/eventmachine-1.2.7/tests/test_running.rb | require 'em_test_helper'
class TestRunning < Test::Unit::TestCase
def test_running
assert_equal( false, EM::reactor_running? )
r = false
EM.run {
r = EM::reactor_running?
EM.stop
}
assert_equal( true, r )
end
end
| ruby | MIT | d8026a4e9cc6348bf38951ee96c523f4ec19f3c4 | 2026-01-04T17:45:10.474201Z | false |
grab/engineering-blog | https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/eventmachine-1.2.7/tests/test_ssl_args.rb | _vendor/ruby/2.6.0/gems/eventmachine-1.2.7/tests/test_ssl_args.rb | require "test/unit"
require 'tempfile'
require 'em_test_helper'
module EM
def self._set_mocks
class <<self
alias set_tls_parms_old set_tls_parms
alias start_tls_old start_tls
begin
old, $VERBOSE = $VERBOSE, nil
def set_tls_parms *args; end
def start_tls *args; end
ensure
$VERBOSE = old
end
end
end
def self._clear_mocks
class <<self
begin
old, $VERBOSE = $VERBOSE, nil
alias set_tls_parms set_tls_parms_old
alias start_tls start_tls_old
ensure
$VERBOSE = old
end
end
end
end
class TestSslArgs < Test::Unit::TestCase
def setup
EM._set_mocks
end
def teardown
EM._clear_mocks
end
def test_tls_params_file_doesnt_exist
priv_file, cert_file = 'foo_priv_key', 'bar_cert_file'
[priv_file, cert_file].all? do |f|
assert(!File.exist?(f), "Cert file #{f} seems to exist, and should not for the tests")
end
# associate_callback_target is a pain! (build!)
conn = EM::Connection.new('foo')
assert_raises(EM::FileNotFoundException) do
conn.start_tls(:private_key_file => priv_file)
end
assert_raises(EM::FileNotFoundException) do
conn.start_tls(:cert_chain_file => cert_file)
end
assert_raises(EM::FileNotFoundException) do
conn.start_tls(:private_key_file => priv_file, :cert_chain_file => cert_file)
end
end
def test_tls_params_file_does_exist
priv_file = Tempfile.new('em_test')
cert_file = Tempfile.new('em_test')
priv_file_path = priv_file.path
cert_file_path = cert_file.path
conn = EM::Connection.new('foo')
params = {:private_key_file => priv_file_path, :cert_chain_file => cert_file_path}
begin
conn.start_tls params
rescue Object
assert(false, 'should not have raised an exception')
end
end
end if EM.ssl?
| ruby | MIT | d8026a4e9cc6348bf38951ee96c523f4ec19f3c4 | 2026-01-04T17:45:10.474201Z | false |
grab/engineering-blog | https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/eventmachine-1.2.7/tests/test_ssl_ecdh_curve.rb | _vendor/ruby/2.6.0/gems/eventmachine-1.2.7/tests/test_ssl_ecdh_curve.rb | require 'em_test_helper'
class TestSslEcdhCurve < Test::Unit::TestCase
module Client
def post_init
start_tls
end
def ssl_handshake_completed
$client_handshake_completed = true
$client_cipher_name = get_cipher_name
close_connection
end
def unbind
EM.stop_event_loop
end
end
module Server
def post_init
start_tls(:ecdh_curve => "prime256v1", :cipher_list => "ECDH")
end
def ssl_handshake_completed
$server_handshake_completed = true
$server_cipher_name = get_cipher_name
end
end
module NoCurveServer
def post_init
start_tls(:cipher_list => "ECDH")
end
def ssl_handshake_completed
$server_handshake_completed = true
$server_cipher_name = get_cipher_name
end
end
def test_no_ecdh_curve
omit_unless(EM.ssl?)
omit_if(rbx?)
$client_handshake_completed, $server_handshake_completed = false, false
EM.run {
EM.start_server("127.0.0.1", 16784, NoCurveServer)
EM.connect("127.0.0.1", 16784, Client)
}
assert(!$client_handshake_completed)
assert(!$server_handshake_completed)
end
def test_ecdh_curve
omit_unless(EM.ssl?)
omit_if(EM.library_type == :pure_ruby && RUBY_VERSION < "2.3.0")
omit_if(rbx?)
$client_handshake_completed, $server_handshake_completed = false, false
$server_cipher_name, $client_cipher_name = nil, nil
EM.run {
EM.start_server("127.0.0.1", 16784, Server)
EM.connect("127.0.0.1", 16784, Client)
}
assert($client_handshake_completed)
assert($server_handshake_completed)
assert($client_cipher_name.length > 0)
assert_equal($client_cipher_name, $server_cipher_name)
assert_match(/^(AECDH|ECDHE)/, $client_cipher_name)
end
end
| ruby | MIT | d8026a4e9cc6348bf38951ee96c523f4ec19f3c4 | 2026-01-04T17:45:10.474201Z | false |
grab/engineering-blog | https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/eventmachine-1.2.7/tests/test_system.rb | _vendor/ruby/2.6.0/gems/eventmachine-1.2.7/tests/test_system.rb | # coding: utf-8
require 'em_test_helper'
class TestSystem < Test::Unit::TestCase
def setup
@filename = File.expand_path("../я манал dump.txt", __FILE__)
@test_data = 'a' * 100
File.open(@filename, 'w'){|f| f.write(@test_data)}
end
def test_system
omit_if(windows?)
result = nil
status = nil
EM.run {
EM.system('cat', @filename){|out, state|
result = out
status = state.exitstatus
EM.stop
}
}
assert_equal(0, status)
assert_equal(@test_data, result)
end
def test_system_with_string
omit_if(windows?)
result = nil
status = nil
EM.run {
EM.system("cat '#@filename'"){|out, state|
result = out
status = state.exitstatus
EM.stop
}
}
assert_equal(0, status)
assert_equal(@test_data, result)
end
def teardown
File.unlink(@filename)
end
end
| ruby | MIT | d8026a4e9cc6348bf38951ee96c523f4ec19f3c4 | 2026-01-04T17:45:10.474201Z | false |
grab/engineering-blog | https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/eventmachine-1.2.7/tests/test_processes.rb | _vendor/ruby/2.6.0/gems/eventmachine-1.2.7/tests/test_processes.rb | require 'em_test_helper'
class TestProcesses < Test::Unit::TestCase
if !windows? && !jruby?
# EM::DeferrableChildProcess is a sugaring of a common use-case
# involving EM::popen.
# Call the #open method on EM::DeferrableChildProcess, passing
# a command-string. #open immediately returns an EM::Deferrable
# object. It also schedules the forking of a child process, which
# will execute the command passed to #open.
# When the forked child terminates, the Deferrable will be signalled
# and execute its callbacks, passing the data that the child process
# wrote to stdout.
#
def test_deferrable_child_process
ls = ""
EM.run {
d = EM::DeferrableChildProcess.open( "ls -ltr" )
d.callback {|data_from_child|
ls = data_from_child
EM.stop
}
}
assert( ls.length > 0)
end
def setup
$out = nil
$status = nil
end
def test_em_system
EM.run{
EM.system('ls'){ |out,status| $out, $status = out, status; EM.stop }
}
assert( $out.length > 0 )
assert_equal(0, $status.exitstatus)
assert_kind_of(Process::Status, $status)
end
def test_em_system_pid
$pids = []
EM.run{
$pids << EM.system('echo hi', proc{ |out,status|$pids << status.pid; EM.stop })
}
assert_equal $pids[0], $pids[1]
end
def test_em_system_with_proc
EM.run{
EM.system('ls', proc{ |out,status| $out, $status = out, status; EM.stop })
}
assert( $out.length > 0 )
assert_equal(0, $status.exitstatus)
assert_kind_of(Process::Status, $status)
end
def test_em_system_with_two_procs
EM.run{
EM.system('sh', proc{ |process|
process.send_data("echo hello\n")
process.send_data("exit\n")
}, proc{ |out,status|
$out = out
$status = status
EM.stop
})
}
assert_equal("hello\n", $out)
end
def test_em_system_cmd_arguments
EM.run{
EM.system('echo', '1', '2', 'version', proc{ |process|
}, proc{ |out,status|
$out = out
$status = status
EM.stop
})
}
assert_match(/1 2 version/i, $out)
end
def test_em_system_spaced_arguments
EM.run{
EM.system('ruby', '-e', 'puts "hello"', proc{ |out,status|
$out = out
EM.stop
})
}
assert_equal("hello\n", $out)
end
def test_em_popen_pause_resume
c_rx = 0
test_client = Module.new do
define_method :receive_data do |data|
c_rx += 1
pause
EM.add_timer(0.5) { EM.stop }
end
end
EM.run do
EM.popen('echo 1', test_client)
end
assert_equal 1, c_rx
end
else
warn "EM.popen not implemented, skipping tests in #{__FILE__}"
# Because some rubies will complain if a TestCase class has no tests
def test_em_popen_unsupported
assert true
end
end
end
| ruby | MIT | d8026a4e9cc6348bf38951ee96c523f4ec19f3c4 | 2026-01-04T17:45:10.474201Z | false |
grab/engineering-blog | https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/eventmachine-1.2.7/tests/test_ssl_extensions.rb | _vendor/ruby/2.6.0/gems/eventmachine-1.2.7/tests/test_ssl_extensions.rb | require 'em_test_helper'
require 'socket'
require 'openssl'
if EM.ssl?
class TestSslExtensions < Test::Unit::TestCase
module Client
def ssl_handshake_completed
$client_handshake_completed = true
close_connection
end
def unbind
EM.stop_event_loop
end
def post_init
start_tls(:ssl_version => :tlsv1, :sni_hostname => 'example.com')
end
end
module Server
def ssl_handshake_completed
$server_handshake_completed = true
$server_sni_hostname = get_sni_hostname
end
def post_init
start_tls(:ssl_version => :TLSv1)
end
end
def test_tlsext_sni_hostname
$server_handshake_completed = false
EM.run do
EM.start_server("127.0.0.1", 16784, Server)
EM.connect("127.0.0.1", 16784, Client)
end
assert($server_handshake_completed)
assert_equal('example.com', $server_sni_hostname)
end
end
else
warn "EM built without SSL support, skipping tests in #{__FILE__}"
end
| ruby | MIT | d8026a4e9cc6348bf38951ee96c523f4ec19f3c4 | 2026-01-04T17:45:10.474201Z | false |
grab/engineering-blog | https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/eventmachine-1.2.7/tests/test_ssl_protocols.rb | _vendor/ruby/2.6.0/gems/eventmachine-1.2.7/tests/test_ssl_protocols.rb | require 'em_test_helper'
require 'socket'
require 'openssl'
if EM.ssl?
class TestSslProtocols < Test::Unit::TestCase
module Client
def ssl_handshake_completed
$client_handshake_completed = true
close_connection
end
def unbind
EM.stop_event_loop
end
end
module Server
def ssl_handshake_completed
$server_handshake_completed = true
end
end
module ClientAny
include Client
def post_init
start_tls(:ssl_version => %w(sslv2 sslv3 tlsv1 tlsv1_1 tlsv1_2))
end
end
module ClientDefault
include Client
def post_init
start_tls
end
end
module ClientSSLv3
include Client
def post_init
start_tls(:ssl_version => %w(SSLv3))
end
end
module ServerSSLv3
include Server
def post_init
start_tls(:ssl_version => %w(SSLv3))
end
end
module ServerTLSv1CaseInsensitive
include Server
def post_init
start_tls(:ssl_version => %w(tlsv1))
end
end
module ServerAny
include Server
def post_init
start_tls(:ssl_version => %w(sslv2 sslv3 tlsv1 tlsv1_1 tlsv1_2))
end
end
module ServerDefault
include Server
def post_init
start_tls
end
end
module InvalidProtocol
include Client
def post_init
start_tls(:ssl_version => %w(tlsv1 badinput))
end
end
def test_invalid_ssl_version
assert_raises(RuntimeError, "Unrecognized SSL/TLS Version: badinput") do
EM.run do
EM.start_server("127.0.0.1", 16784, InvalidProtocol)
EM.connect("127.0.0.1", 16784, InvalidProtocol)
end
end
end
def test_any_to_v3
$client_handshake_completed, $server_handshake_completed = false, false
EM.run do
EM.start_server("127.0.0.1", 16784, ServerSSLv3)
EM.connect("127.0.0.1", 16784, ClientAny)
end
assert($client_handshake_completed)
assert($server_handshake_completed)
end
def test_case_insensitivity
$client_handshake_completed, $server_handshake_completed = false, false
EM.run do
EM.start_server("127.0.0.1", 16784, ServerTLSv1CaseInsensitive)
EM.connect("127.0.0.1", 16784, ClientAny)
end
assert($client_handshake_completed)
assert($server_handshake_completed)
end
def test_v3_to_any
$client_handshake_completed, $server_handshake_completed = false, false
EM.run do
EM.start_server("127.0.0.1", 16784, ServerAny)
EM.connect("127.0.0.1", 16784, ClientSSLv3)
end
assert($client_handshake_completed)
assert($server_handshake_completed)
end
def test_v3_to_v3
$client_handshake_completed, $server_handshake_completed = false, false
EM.run do
EM.start_server("127.0.0.1", 16784, ServerSSLv3)
EM.connect("127.0.0.1", 16784, ClientSSLv3)
end
assert($client_handshake_completed)
assert($server_handshake_completed)
end
def test_any_to_any
$client_handshake_completed, $server_handshake_completed = false, false
EM.run do
EM.start_server("127.0.0.1", 16784, ServerAny)
EM.connect("127.0.0.1", 16784, ClientAny)
end
assert($client_handshake_completed)
assert($server_handshake_completed)
end
def test_default_to_default
$client_handshake_completed, $server_handshake_completed = false, false
EM.run do
EM.start_server("127.0.0.1", 16784, ServerDefault)
EM.connect("127.0.0.1", 16784, ClientDefault)
end
assert($client_handshake_completed)
assert($server_handshake_completed)
end
module ServerV3StopAfterHandshake
def post_init
start_tls(:ssl_version => %w(SSLv3))
end
def ssl_handshake_completed
$server_handshake_completed = true
EM.stop_event_loop
end
end
module ServerTLSv1StopAfterHandshake
def post_init
start_tls(:ssl_version => %w(TLSv1))
end
def ssl_handshake_completed
$server_handshake_completed = true
EM.stop_event_loop
end
end
def test_v3_with_external_client
$server_handshake_completed = false
EM.run do
setup_timeout(2)
EM.start_server("127.0.0.1", 16784, ServerV3StopAfterHandshake)
EM.defer do
sock = TCPSocket.new("127.0.0.1", 16784)
ctx = OpenSSL::SSL::SSLContext.new
ctx.ssl_version = :SSLv3_client
ssl = OpenSSL::SSL::SSLSocket.new(sock, ctx)
ssl.connect
ssl.close rescue nil
sock.close rescue nil
end
end
assert($server_handshake_completed)
end
def test_tlsv1_with_external_client
$server_handshake_completed = false
EM.run do
setup_timeout(2)
EM.start_server("127.0.0.1", 16784, ServerTLSv1StopAfterHandshake)
EM.defer do
sock = TCPSocket.new("127.0.0.1", 16784)
ctx = OpenSSL::SSL::SSLContext.new
ctx.ssl_version = :TLSv1_client
ssl = OpenSSL::SSL::SSLSocket.new(sock, ctx)
ssl.connect
ssl.close rescue nil
sock.close rescue nil
end
end
assert($server_handshake_completed)
end
def test_tlsv1_required_with_external_client
$server_handshake_completed = false
EM.run do
n = 0
EM.add_periodic_timer(0.5) do
n += 1
(EM.stop rescue nil) if n == 2
end
EM.start_server("127.0.0.1", 16784, ServerTLSv1StopAfterHandshake)
EM.defer do
sock = TCPSocket.new("127.0.0.1", 16784)
ctx = OpenSSL::SSL::SSLContext.new
ctx.ssl_version = :SSLv3_client
ssl = OpenSSL::SSL::SSLSocket.new(sock, ctx)
assert_raise OpenSSL::SSL::SSLError do
ssl.connect
end
ssl.close rescue nil
sock.close rescue nil
EM.stop rescue nil
end
end
assert(!$server_handshake_completed)
end
end
else
warn "EM built without SSL support, skipping tests in #{__FILE__}"
end
| ruby | MIT | d8026a4e9cc6348bf38951ee96c523f4ec19f3c4 | 2026-01-04T17:45:10.474201Z | false |
grab/engineering-blog | https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/eventmachine-1.2.7/tests/test_ltp.rb | _vendor/ruby/2.6.0/gems/eventmachine-1.2.7/tests/test_ltp.rb | require 'em_test_helper'
class TestLineAndTextProtocol < Test::Unit::TestCase
class TLP_LineBuffer < EM::P::LineAndTextProtocol
attr_reader :line_buffer
def initialize
super
@line_buffer = []
end
def receive_line line
@line_buffer << line
end
end
module StopClient
def set_receive_data(&blk)
@rdb = blk
end
def receive_data data
@rdb.call(data) if @rdb
end
def unbind
EM.add_timer(0.1) { EM.stop }
end
end
def setup
@port = next_port
end
def test_simple_lines
conn = nil
EM.run {
EM.start_server( "127.0.0.1", @port, TLP_LineBuffer ) do |c|
conn = c
end
setup_timeout
EM.connect "127.0.0.1", @port, StopClient do |c|
c.send_data "aaa\nbbb\r\nccc\n"
c.close_connection_after_writing
end
}
assert_equal( %w(aaa bbb ccc), conn.line_buffer)
end
#--------------------------------------------------------------------
class TLP_ErrorMessage < EM::P::LineAndTextProtocol
attr_reader :error_message
def initialize
super
@error_message = []
end
def receive_line text
raise
end
def receive_error text
@error_message << text
end
end
def test_overlength_lines
conn = nil
EM.run {
EM.start_server( "127.0.0.1", @port, TLP_ErrorMessage ) do |c|
conn = c
end
setup_timeout
EM.connect "127.0.0.1", @port, StopClient do |c|
c.send_data "a" * (16*1024 + 1)
c.send_data "\n"
c.close_connection_after_writing
end
}
assert_equal( ["overlength line"], conn.error_message )
end
#--------------------------------------------------------------------
class LineAndTextTest < EM::P::LineAndTextProtocol
def receive_line line
if line =~ /content-length:\s*(\d+)/i
@content_length = $1.to_i
elsif line.length == 0
set_binary_mode @content_length
end
end
def receive_binary_data text
send_data "received #{text.length} bytes"
close_connection_after_writing
end
end
def test_lines_and_text
output = ''
EM.run {
EM.start_server( "127.0.0.1", @port, LineAndTextTest )
setup_timeout
EM.connect "127.0.0.1", @port, StopClient do |c|
c.set_receive_data { |data| output << data }
c.send_data "Content-length: 400\n"
c.send_data "\n"
c.send_data "A" * 400
EM.add_timer(0.1) { c.close_connection_after_writing }
end
}
assert_equal( "received 400 bytes", output )
end
#--------------------------------------------------------------------
class BinaryTextTest < EM::P::LineAndTextProtocol
def receive_line line
if line =~ /content-length:\s*(\d+)/i
set_binary_mode $1.to_i
else
raise "protocol error"
end
end
def receive_binary_data text
send_data "received #{text.length} bytes"
close_connection_after_writing
end
end
def test_binary_text
output = ''
EM.run {
EM.start_server( "127.0.0.1", @port, BinaryTextTest )
setup_timeout
EM.connect "127.0.0.1", @port, StopClient do |c|
c.set_receive_data { |data| output << data }
c.send_data "Content-length: 10000\n"
c.send_data "A" * 10000
EM.add_timer(0.1) { c.close_connection_after_writing }
end
}
assert_equal( "received 10000 bytes", output )
end
end
| ruby | MIT | d8026a4e9cc6348bf38951ee96c523f4ec19f3c4 | 2026-01-04T17:45:10.474201Z | false |
grab/engineering-blog | https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/eventmachine-1.2.7/tests/test_send_file.rb | _vendor/ruby/2.6.0/gems/eventmachine-1.2.7/tests/test_send_file.rb | require 'em_test_helper'
require 'tempfile'
class TestSendFile < Test::Unit::TestCase
if EM.respond_to?(:send_file_data)
module TestModule
def initialize filename
@filename = filename
end
def post_init
send_file_data @filename
close_connection_after_writing
end
end
module TestClient
def data_to(&blk)
@data_to = blk
end
def receive_data(data)
@data_to.call(data) if @data_to
end
def unbind
EM.stop
end
end
def setup
@file = Tempfile.new("em_test_file")
@filename = @file.path
@port = next_port
end
def test_send_file
File.open( @filename, "w" ) {|f|
f << ("A" * 5000)
}
data = ''
EM.run {
EM.start_server "127.0.0.1", @port, TestModule, @filename
setup_timeout
EM.connect "127.0.0.1", @port, TestClient do |c|
c.data_to { |d| data << d }
end
}
assert_equal( "A" * 5000, data )
end
# EM::Connection#send_file_data has a strict upper limit on the filesize it will work with.
def test_send_large_file
File.open( @filename, "w" ) {|f|
f << ("A" * 1000000)
}
data = ''
assert_raises(RuntimeError) {
EM.run {
EM.start_server "127.0.0.1", @port, TestModule, @filename
setup_timeout
EM.connect "127.0.0.1", @port, TestClient do |c|
c.data_to { |d| data << d }
end
}
}
end
module StreamTestModule
def initialize filename
@filename = filename
end
def post_init
EM::Deferrable.future( stream_file_data(@filename)) {
close_connection_after_writing
}
end
end
module ChunkStreamTestModule
def initialize filename
@filename = filename
end
def post_init
EM::Deferrable.future( stream_file_data(@filename, :http_chunks=>true)) {
close_connection_after_writing
}
end
end
def test_stream_file_data
File.open( @filename, "w" ) {|f|
f << ("A" * 1000)
}
data = ''
EM.run {
EM.start_server "127.0.0.1", @port, StreamTestModule, @filename
setup_timeout
EM.connect "127.0.0.1", @port, TestClient do |c|
c.data_to { |d| data << d }
end
}
assert_equal( "A" * 1000, data )
end
def test_stream_chunked_file_data
File.open( @filename, "w" ) {|f|
f << ("A" * 1000)
}
data = ''
EM.run {
EM.start_server "127.0.0.1", @port, ChunkStreamTestModule, @filename
setup_timeout
EM.connect "127.0.0.1", @port, TestClient do |c|
c.data_to { |d| data << d }
end
}
assert_equal( "3e8\r\n#{"A" * 1000}\r\n0\r\n\r\n", data )
end
module BadFileTestModule
def initialize filename
@filename = filename
end
def post_init
de = stream_file_data( @filename+".wrong" )
de.errback {|msg|
send_data msg
close_connection_after_writing
}
end
end
def test_stream_bad_file
data = ''
EM.run {
EM.start_server "127.0.0.1", @port, BadFileTestModule, @filename
setup_timeout(5)
EM.connect "127.0.0.1", @port, TestClient do |c|
c.data_to { |d| data << d }
end
}
assert_equal( "file not found", data )
end
else
warn "EM.send_file_data not implemented, skipping tests in #{__FILE__}"
# Because some rubies will complain if a TestCase class has no tests
def test_em_send_file_data_not_implemented
assert !EM.respond_to?(:send_file_data)
end
end
begin
require 'fastfilereaderext'
def test_stream_large_file_data
File.open( @filename, "w" ) {|f|
f << ("A" * 10000)
}
data = ''
EM.run {
EM.start_server "127.0.0.1", @port, StreamTestModule, @filename
setup_timeout
EM.connect "127.0.0.1", @port, TestClient do |c|
c.data_to { |d| data << d }
end
}
assert_equal( "A" * 10000, data )
end
def test_stream_large_chunked_file_data
File.open( @filename, "w" ) {|f|
f << ("A" * 100000)
}
data = ''
EM.run {
EM.start_server "127.0.0.1", @port, ChunkStreamTestModule, @filename
setup_timeout
EM.connect "127.0.0.1", @port, TestClient do |c|
c.data_to { |d| data << d }
end
}
expected = [
"4000\r\n#{"A" * 16384}\r\n" * 6,
"6a0\r\n#{"A" * 0x6a0}\r\n",
"0\r\n\r\n"
].join
assert_equal( expected, data )
end
rescue LoadError
warn "require 'fastfilereaderext' failed, skipping tests in #{__FILE__}"
end
end
| ruby | MIT | d8026a4e9cc6348bf38951ee96c523f4ec19f3c4 | 2026-01-04T17:45:10.474201Z | false |
grab/engineering-blog | https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/eventmachine-1.2.7/tests/test_hc.rb | _vendor/ruby/2.6.0/gems/eventmachine-1.2.7/tests/test_hc.rb | require 'em_test_helper'
class TestHeaderAndContentProtocol < Test::Unit::TestCase
class SimpleTest < EM::P::HeaderAndContentProtocol
attr_reader :first_header, :my_headers, :request
def receive_first_header_line hdr
@first_header ||= []
@first_header << hdr
end
def receive_headers hdrs
@my_headers ||= []
@my_headers << hdrs
end
def receive_request hdrs, content
@request ||= []
@request << [hdrs, content]
end
end
class StopOnUnbind < EM::Connection
def unbind
EM.add_timer(0.01) { EM.stop }
end
end
def setup
@port = next_port
end
def test_no_content
the_connection = nil
EM.run {
EM.start_server( "127.0.0.1", @port, SimpleTest ) do |conn|
the_connection = conn
end
setup_timeout
EM.connect "127.0.0.1", @port, StopOnUnbind do |c|
c.send_data [ "aaa\n", "bbb\r\n", "ccc\n", "\n" ].join
c.close_connection_after_writing
end
}
assert_equal( ["aaa"], the_connection.first_header )
assert_equal( [%w(aaa bbb ccc)], the_connection.my_headers )
assert_equal( [[%w(aaa bbb ccc), ""]], the_connection.request )
end
def test_content
the_connection = nil
content = "A" * 50
headers = ["aaa", "bbb", "Content-length: #{content.length}", "ccc"]
EM.run {
EM.start_server( "127.0.0.1", @port, SimpleTest ) do |conn|
the_connection = conn
end
setup_timeout
EM.connect "127.0.0.1", @port, StopOnUnbind do |c|
headers.each { |h| c.send_data "#{h}\r\n" }
c.send_data "\n"
c.send_data content
c.close_connection_after_writing
end
}
assert_equal( ["aaa"], the_connection.first_header )
assert_equal( [headers], the_connection.my_headers )
assert_equal( [[headers, content]], the_connection.request )
end
def test_several_requests
the_connection = nil
content = "A" * 50
headers = ["aaa", "bbb", "Content-length: #{content.length}", "ccc"]
EM.run {
EM.start_server( "127.0.0.1", @port, SimpleTest ) do |conn|
the_connection = conn
end
setup_timeout
EM.connect( "127.0.0.1", @port, StopOnUnbind ) do |c|
5.times do
headers.each { |h| c.send_data "#{h}\r\n" }
c.send_data "\n"
c.send_data content
end
c.close_connection_after_writing
end
}
assert_equal( ["aaa"] * 5, the_connection.first_header )
assert_equal( [headers] * 5, the_connection.my_headers )
assert_equal( [[headers, content]] * 5, the_connection.request )
end
# def x_test_multiple_content_length_headers
# # This is supposed to throw a RuntimeError but it throws a C++ exception instead.
# the_connection = nil
# content = "A" * 50
# headers = ["aaa", "bbb", ["Content-length: #{content.length}"]*2, "ccc"].flatten
# EM.run {
# EM.start_server( "127.0.0.1", @port, SimpleTest ) do |conn|
# the_connection = conn
# end
# EM.add_timer(4) {raise "test timed out"}
# test_proc = proc {
# t = TCPSocket.new "127.0.0.1", @port
# headers.each {|h| t.write "#{h}\r\n" }
# t.write "\n"
# t.write content
# t.close
# }
# EM.defer test_proc, proc {
# EM.stop
# }
# }
# end
def test_interpret_headers
the_connection = nil
content = "A" * 50
headers = [
"GET / HTTP/1.0",
"Accept: aaa",
"User-Agent: bbb",
"Host: ccc",
"x-tempest-header:ddd"
]
EM.run {
EM.start_server( "127.0.0.1", @port, SimpleTest ) do |conn|
the_connection = conn
end
setup_timeout
EM.connect( "127.0.0.1", @port, StopOnUnbind ) do |c|
headers.each { |h| c.send_data "#{h}\r\n" }
c.send_data "\n"
c.send_data content
c.close_connection_after_writing
end
}
hsh = the_connection.headers_2_hash( the_connection.my_headers.shift )
expect = {
:accept => "aaa",
:user_agent => "bbb",
:host => "ccc",
:x_tempest_header => "ddd"
}
assert_equal(expect, hsh)
end
end
| ruby | MIT | d8026a4e9cc6348bf38951ee96c523f4ec19f3c4 | 2026-01-04T17:45:10.474201Z | false |
grab/engineering-blog | https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/eventmachine-1.2.7/tests/test_exc.rb | _vendor/ruby/2.6.0/gems/eventmachine-1.2.7/tests/test_exc.rb | require 'em_test_helper'
class TestSomeExceptions < Test::Unit::TestCase
class DoomedConnectionError < StandardError
end
class DoomedConnection < EventMachine::Connection
def unbind
raise DoomedConnectionError
end
end
# Read the commentary in EM#run.
# This test exercises the ensure block in #run that makes sure
# EM#release_machine gets called even if an exception is
# thrown within the user code. Without the ensured call to release_machine,
# the second call to EM#run will fail with a C++ exception
# because the machine wasn't cleaned up properly.
def test_a
assert_raises(RuntimeError) {
EM.run {
raise "some exception"
}
}
end
def test_b
assert_raises(RuntimeError) {
EM.run {
raise "some exception"
}
}
end
def test_exception_on_unbind
assert_raises(DoomedConnectionError) {
EM.run {
EM.connect("localhost", 8888, DoomedConnection)
}
}
end
end
| ruby | MIT | d8026a4e9cc6348bf38951ee96c523f4ec19f3c4 | 2026-01-04T17:45:10.474201Z | false |
grab/engineering-blog | https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/eventmachine-1.2.7/tests/test_servers.rb | _vendor/ruby/2.6.0/gems/eventmachine-1.2.7/tests/test_servers.rb | require 'em_test_helper'
require 'socket'
class TestServers < Test::Unit::TestCase
def setup
@port = next_port
end
def server_alive?
port_in_use?(@port)
end
def run_test_stop_server
EM.run {
sig = EM.start_server("127.0.0.1", @port)
assert server_alive?, "Server didn't start"
EM.stop_server sig
# Give the server some time to shutdown.
EM.add_timer(0.1) {
assert !server_alive?, "Server didn't stop"
EM.stop
}
}
end
def test_stop_server
assert !server_alive?, "Port already in use"
2.times { run_test_stop_server }
assert !server_alive?, "Servers didn't stop"
end
end
| ruby | MIT | d8026a4e9cc6348bf38951ee96c523f4ec19f3c4 | 2026-01-04T17:45:10.474201Z | false |
grab/engineering-blog | https://github.com/grab/engineering-blog/blob/d8026a4e9cc6348bf38951ee96c523f4ec19f3c4/_vendor/ruby/2.6.0/gems/eventmachine-1.2.7/tests/test_httpclient2.rb | _vendor/ruby/2.6.0/gems/eventmachine-1.2.7/tests/test_httpclient2.rb | require 'em_test_helper'
class TestHttpClient2 < Test::Unit::TestCase
class TestServer < EM::Connection
end
def setup
@port = next_port
end
# #connect returns an object which has made a connection to an HTTP server
# and exposes methods for making HTTP requests on that connection.
# #connect can take either a pair of parameters (a host and a port),
# or a single parameter which is a Hash.
#
def test_connect
EM.run {
setup_timeout(1)
EM.start_server '127.0.0.1', @port, TestServer
silent do
EM::P::HttpClient2.connect '127.0.0.1', @port
EM::P::HttpClient2.connect( :host=>'127.0.0.1', :port=>@port )
end
EM.stop
}
end
def test_bad_port
EM.run {
setup_timeout(1)
EM.start_server '127.0.0.1', @port, TestServer
assert_raises( ArgumentError ) {
silent { EM::P::HttpClient2.connect '127.0.0.1', "xxx" }
}
EM.stop
}
end
def test_bad_server
err = nil
EM.run {
setup_timeout(1)
http = silent { EM::P::HttpClient2.connect '127.0.0.1', 9999 }
d = http.get "/"
d.errback { err = true; d.internal_error; EM.stop }
}
assert(err)
end
def test_get
content = nil
EM.run {
setup_timeout(1)
http = silent { EM::P::HttpClient2.connect :host => "google.com", :port => 80, :version => '1.0' }
d = http.get "/"
d.callback {
content = d.content
EM.stop
}
}
assert(content)
end
# Not a pipelined request because we wait for one response before we request the next.
# XXX this test is broken because it sends the second request to the first connection
# XXX right before the connection closes
def _test_get_multiple
content = nil
EM.run {
setup_timeout(1)
http = silent { EM::P::HttpClient2.connect "google.com", :version => '1.0' }
d = http.get "/"
d.callback {
e = http.get "/"
e.callback {
content = e.content
EM.stop
}
}
}
assert(content)
end
def test_get_pipeline
headers, headers2 = nil, nil
EM.run {
setup_timeout(1)
http = silent { EM::P::HttpClient2.connect "google.com", 80 }
d = http.get("/")
d.callback {
headers = d.headers
}
e = http.get("/")
e.callback {
headers2 = e.headers
}
EM.tick_loop { EM.stop if headers && headers2 }
EM.add_timer(1) { EM.stop }
}
assert(headers)
assert(headers2)
end
def test_authheader
EM.run {
setup_timeout(1)
EM.start_server '127.0.0.1', @port, TestServer
http = silent { EM::P::HttpClient2.connect '127.0.0.1', 18842 }
d = http.get :url=>"/", :authorization=>"Basic xxx"
d.callback {EM.stop}
d.errback {EM.stop}
}
end
def test_https_get
omit_unless(EM.ssl?)
d = nil
EM.run {
setup_timeout(1)
http = silent { EM::P::HttpClient2.connect :host => 'www.google.com', :port => 443, :ssl => true, :version => '1.0' }
d = http.get "/"
d.callback {EM.stop}
d.errback {EM.stop}
}
assert_equal(200, d.status)
end
end
| ruby | MIT | d8026a4e9cc6348bf38951ee96c523f4ec19f3c4 | 2026-01-04T17:45:10.474201Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.