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
refinery/refinerycms-news
https://github.com/refinery/refinerycms-news/blob/8e89de6c68077da150fb48dc5feb44c8f85a775c/db/migrate/20110817203704_add_image_id_to_news_items.rb
db/migrate/20110817203704_add_image_id_to_news_items.rb
class AddImageIdToNewsItems < ActiveRecord::Migration[4.2] def up unless ::Refinery::News::Item.column_names.map(&:to_sym).include?(:image_id) add_column ::Refinery::News::Item.table_name, :image_id, :integer end end def down remove_column ::Refinery::News::Item.table_name, :image_id end end
ruby
MIT
8e89de6c68077da150fb48dc5feb44c8f85a775c
2026-01-04T17:58:21.941874Z
false
refinery/refinerycms-news
https://github.com/refinery/refinerycms-news/blob/8e89de6c68077da150fb48dc5feb44c8f85a775c/db/migrate/20110817203701_create_news_items.rb
db/migrate/20110817203701_create_news_items.rb
class CreateNewsItems < ActiveRecord::Migration[4.2] def up create_table ::Refinery::News::Item.table_name do |t| t.string :title t.text :body t.datetime :publish_date t.timestamps end add_index ::Refinery::News::Item.table_name, :id end def down ::Refinery::UserPlugin.destroy_all :name => "refinerycms_news" ::Refinery::Page.delete_all :link_url => "/news" drop_table ::Refinery::News::Item.table_name end end
ruby
MIT
8e89de6c68077da150fb48dc5feb44c8f85a775c
2026-01-04T17:58:21.941874Z
false
refinery/refinerycms-news
https://github.com/refinery/refinerycms-news/blob/8e89de6c68077da150fb48dc5feb44c8f85a775c/db/migrate/20110817203706_remove_image_id_and_external_url_from_news.rb
db/migrate/20110817203706_remove_image_id_and_external_url_from_news.rb
class RemoveImageIdAndExternalUrlFromNews < ActiveRecord::Migration[4.2] def up if ::Refinery::News::Item.column_names.map(&:to_sym).include?(:external_url) remove_column ::Refinery::News::Item.table_name, :external_url end if ::Refinery::News::Item.column_names.map(&:to_sym).include?(:image_id) remove_column ::Refinery::News::Item.table_name, :image_id end end def down unless ::Refinery::News::Item.column_names.map(&:to_sym).include?(:external_url) add_column ::Refinery::News::Item.table_name, :external_url, :string end unless ::Refinery::News::Item.column_names.map(&:to_sym).include?(:image_id) add_column ::Refinery::News::Item.table_name, :image_id, :integer end end end
ruby
MIT
8e89de6c68077da150fb48dc5feb44c8f85a775c
2026-01-04T17:58:21.941874Z
false
refinery/refinerycms-news
https://github.com/refinery/refinerycms-news/blob/8e89de6c68077da150fb48dc5feb44c8f85a775c/db/migrate/20131128000000_move_slug_to_news_item_translations.rb
db/migrate/20131128000000_move_slug_to_news_item_translations.rb
class MoveSlugToNewsItemTranslations < ActiveRecord::Migration[4.2] def up # Fix index problem if this is rolled back remove_index Refinery::News::Item.translation_class.table_name, :refinery_news_item_id add_index Refinery::News::Item.translation_class.table_name, :refinery_news_item_id, :name => :index_refinery_news_item_translations_fk # Add the column add_column Refinery::News::Item.translation_class.table_name, :slug, :string # Ensure the slug is translated. Refinery::News::Item.reset_column_information Refinery::News::Item.find_each do |item| item.slug = item.slug item.save end end def down # Move the slug back to the news item table Refinery::News::Item.reset_column_information Refinery::News::Item.find_each do |item| item.slug = if item.translations.many? item.translations.detect{|t| t.slug.present?}.slug else item.translations.first.slug end item.save end # Remove the column from the translations table remove_column Refinery::News::Item.translation_class.table_name, :slug end end
ruby
MIT
8e89de6c68077da150fb48dc5feb44c8f85a775c
2026-01-04T17:58:21.941874Z
false
refinery/refinerycms-news
https://github.com/refinery/refinerycms-news/blob/8e89de6c68077da150fb48dc5feb44c8f85a775c/db/migrate/20120228150250_add_slug_to_news_items.rb
db/migrate/20120228150250_add_slug_to_news_items.rb
class AddSlugToNewsItems < ActiveRecord::Migration[4.2] def change add_column Refinery::News::Item.table_name, :slug, :string end end
ruby
MIT
8e89de6c68077da150fb48dc5feb44c8f85a775c
2026-01-04T17:58:21.941874Z
false
refinery/refinerycms-news
https://github.com/refinery/refinerycms-news/blob/8e89de6c68077da150fb48dc5feb44c8f85a775c/db/migrate/20110817203702_add_external_url_to_news_items.rb
db/migrate/20110817203702_add_external_url_to_news_items.rb
class AddExternalUrlToNewsItems < ActiveRecord::Migration[4.2] def up unless ::Refinery::News::Item.column_names.map(&:to_sym).include?(:external_url) add_column ::Refinery::News::Item.table_name, :external_url, :string end end def down if ::Refinery::News::Item.column_names.map(&:to_sym).include?(:external_url) remove_column ::Refinery::News::Item.table_name, :external_url end end end
ruby
MIT
8e89de6c68077da150fb48dc5feb44c8f85a775c
2026-01-04T17:58:21.941874Z
false
refinery/refinerycms-news
https://github.com/refinery/refinerycms-news/blob/8e89de6c68077da150fb48dc5feb44c8f85a775c/db/migrate/20120129230839_translate_source.rb
db/migrate/20120129230839_translate_source.rb
# This migration comes from refinery_news (originally 8) class TranslateSource < ActiveRecord::Migration[4.2] def up unless Refinery::News::Item::Translation.column_names.map(&:to_sym).include?(:source) add_column Refinery::News::Item::Translation.table_name, :source, :string end end def down if Refinery::News::Item::Translation.column_names.map(&:to_sym).include?(:source) remove_column Refinery::News::Item::Translation.table_name, :source end end end
ruby
MIT
8e89de6c68077da150fb48dc5feb44c8f85a775c
2026-01-04T17:58:21.941874Z
false
refinery/refinerycms-news
https://github.com/refinery/refinerycms-news/blob/8e89de6c68077da150fb48dc5feb44c8f85a775c/db/migrate/20110817203703_translate_news_items.rb
db/migrate/20110817203703_translate_news_items.rb
class TranslateNewsItems < ActiveRecord::Migration[4.2] def up ::Refinery::News::Item.reset_column_information unless defined?(::Refinery::News::Item::Translation) && ::Refinery::News::Item::Translation.table_exists? ::Refinery::News::Item.create_translation_table!({ :title => :string, :body => :text, }, { :migrate_data => true }) end end def down ::Refinery::News::Item.reset_column_information ::Refinery::News::Item.drop_translation_table! end end
ruby
MIT
8e89de6c68077da150fb48dc5feb44c8f85a775c
2026-01-04T17:58:21.941874Z
false
refinery/refinerycms-news
https://github.com/refinery/refinerycms-news/blob/8e89de6c68077da150fb48dc5feb44c8f85a775c/db/migrate/20110817203705_add_expiration_date_to_news_items.rb
db/migrate/20110817203705_add_expiration_date_to_news_items.rb
class AddExpirationDateToNewsItems < ActiveRecord::Migration[4.2] def up unless ::Refinery::News::Item.column_names.map(&:to_sym).include?(:expiration_date) add_column ::Refinery::News::Item.table_name, :expiration_date, :datetime end end def down if ::Refinery::News::Item.column_names.map(&:to_sym).include?(:expiration_date) remove_column ::Refinery::News::Item.table_name, :expiration_date end end end
ruby
MIT
8e89de6c68077da150fb48dc5feb44c8f85a775c
2026-01-04T17:58:21.941874Z
false
refinery/refinerycms-news
https://github.com/refinery/refinerycms-news/blob/8e89de6c68077da150fb48dc5feb44c8f85a775c/db/migrate/20120129230838_add_source_to_news_items.rb
db/migrate/20120129230838_add_source_to_news_items.rb
# This migration comes from refinery_news (originally 7) class AddSourceToNewsItems < ActiveRecord::Migration[4.2] def up unless Refinery::News::Item.column_names.map(&:to_sym).include?(:source) add_column Refinery::News::Item.table_name, :source, :string end end def down if Refinery::News::Item.column_names.map(&:to_sym).include?(:source) remove_column Refinery::News::Item.table_name, :source end end end
ruby
MIT
8e89de6c68077da150fb48dc5feb44c8f85a775c
2026-01-04T17:58:21.941874Z
false
refinery/refinerycms-news
https://github.com/refinery/refinerycms-news/blob/8e89de6c68077da150fb48dc5feb44c8f85a775c/spec/spec_helper.rb
spec/spec_helper.rb
require 'rubygems' # Configure Rails Environment ENV["RAILS_ENV"] ||= 'test' require File.expand_path("../dummy/config/environment", __FILE__) require 'rspec/rails' require 'capybara/rspec' Rails.backtrace_cleaner.remove_silencers! RSpec.configure do |config| config.mock_with :rspec config.filter_run :focus => true config.run_all_when_everything_filtered = true end # set javascript driver for capybara Capybara.javascript_driver = :selenium # Requires supporting files with custom matchers and macros, etc, # in ./support/ and its subdirectories including factories. ([Rails.root.to_s] | ::Refinery::Plugins.registered.pathnames).map{|p| Dir[File.join(p, 'spec', 'support', '**', '*.rb').to_s] }.flatten.sort.each do |support_file| require support_file end
ruby
MIT
8e89de6c68077da150fb48dc5feb44c8f85a775c
2026-01-04T17:58:21.941874Z
false
refinery/refinerycms-news
https://github.com/refinery/refinerycms-news/blob/8e89de6c68077da150fb48dc5feb44c8f85a775c/spec/helpers/refinery/news/items_helper_spec.rb
spec/helpers/refinery/news/items_helper_spec.rb
require 'spec_helper' module Refinery module News describe ItemsHelper, :type => :helper do describe '#news_item_archive_links' do before do 2.times { FactoryBot.create(:news_item, :publish_date => Time.utc(2012, 05)) } 3.times { FactoryBot.create(:news_item, :publish_date => Time.utc(2012, 04)) } end it 'returns list of links to archives' do expected = '<ul><li><a href="/news/archive/2012/5">May 2012 (2)</a></li><li><a href="/news/archive/2012/4">April 2012 (3)</a></li></ul>' expect(helper.news_item_archive_links).to eq(expected) end end describe "#archive_date_format" do context "when date_for_month is true" do it "returns month and year" do expect(helper.archive_date_format(true)).to eq("%B %Y") end end context "when date_for_month is nil" do it "returns year" do expect(helper.archive_date_format(nil)).to eq("%Y") end end end end end end
ruby
MIT
8e89de6c68077da150fb48dc5feb44c8f85a775c
2026-01-04T17:58:21.941874Z
false
refinery/refinerycms-news
https://github.com/refinery/refinerycms-news/blob/8e89de6c68077da150fb48dc5feb44c8f85a775c/spec/factories/news.rb
spec/factories/news.rb
FactoryBot.define do factory :news_item, :class => Refinery::News::Item do title "Refinery CMS News Item" content "Some random text ..." publish_date Time.now - 5.minutes end end
ruby
MIT
8e89de6c68077da150fb48dc5feb44c8f85a775c
2026-01-04T17:58:21.941874Z
false
refinery/refinerycms-news
https://github.com/refinery/refinerycms-news/blob/8e89de6c68077da150fb48dc5feb44c8f85a775c/spec/controllers/refinery/news/items_controller_spec.rb
spec/controllers/refinery/news/items_controller_spec.rb
require "spec_helper" module Refinery module News describe ItemsController, :type => :controller do let!(:item) { FactoryBot.create(:news_item) } let(:refinery_page) { Refinery::Page.where(:link_url => "/news").first } describe "#index" do it "assigns items and page" do get :index expect(assigns(:items).first).to eq(item) expect(assigns(:page)).to eq(refinery_page) end it "renders 'index' template" do get :index expect(response).to render_template(:index) end end describe "#show" do it "assigns item and page" do get :show, params: { id: item.id } expect(assigns(:item)).to eq(item) expect(assigns(:page)).to eq(refinery_page) end it "renders 'show' template" do get :show, params: { id: item.id } expect(response).to render_template(:show) end end describe "#archive" do context "when month is present" do it "assigns archive_date and items" do allow(Refinery::News::Item).to receive_message_chain(:archived, :translated, :by_archive, :page).and_return(item) get :archive, params: { month: 05, year: 1999 } expect(assigns(:archive_date)).to eq(Time.parse("05/1999")) expect(assigns(:items)).to eq(item) expect(assigns(:archive_for_month)).to be_truthy end end context "when month isnt present" do it "assigns archive_date and items" do allow(Refinery::News::Item).to receive_message_chain(:archived, :translated, :by_year, :page).and_return(item) get :archive, params: { year: 1999 } expect(assigns(:archive_date)).to eq(Time.parse("01/1999")) expect(assigns(:items)).to eq(item) end end it "renders 'archive' template" do get :archive, params: { year: 1999 } expect(response).to render_template(:archive) end it "assigns page" do get :archive, params: { year: 1999 } expect(assigns(:page)).to eq(refinery_page) end end end end end
ruby
MIT
8e89de6c68077da150fb48dc5feb44c8f85a775c
2026-01-04T17:58:21.941874Z
false
refinery/refinerycms-news
https://github.com/refinery/refinerycms-news/blob/8e89de6c68077da150fb48dc5feb44c8f85a775c/spec/models/refinery/news/item_spec.rb
spec/models/refinery/news/item_spec.rb
require 'spec_helper' module Refinery module News describe Item, :type => :model do let(:news_item) { FactoryBot.create(:news_item) } let(:publish_date) { Date.current } describe "#archive" do let(:publish_date) { Time.utc(2012,1,15) } let(:future_date) { Time.utc(2012,2,15) } let(:archive_range) { Time.parse("2012-01-17") } it "should show 5 news items with publish dates in same month" do 5.times { FactoryBot.create(:news_item, :publish_date => publish_date) } 2.times { FactoryBot.create(:news_item, :publish_date => future_date) } expect(Refinery::News::Item.by_archive(archive_range).count).to eq(5) end end describe "validations" do subject do Refinery::News::Item.create!( content: 'Some random text ...', publish_date: publish_date, title: 'Refinery CMS' ) end it { is_expected.to be_valid } describe '#errors' do subject { super().errors } it { is_expected.to be_empty } end describe '#title' do subject { super().title } it { is_expected.to eq("Refinery CMS") } end describe '#content' do subject { super().content } it { is_expected.to eq("Some random text ...") } end describe '#publish_date' do subject { super().publish_date } it { is_expected.to eq(publish_date) } end end describe "attribute aliasing" do subject { news_item } describe '#content' do subject { super().content } it { is_expected.to eq(news_item.body) } end end describe "default scope" do it "orders by publish date in DESC order" do news_item1 = FactoryBot.create(:news_item, :publish_date => 1.hour.ago) news_item2 = FactoryBot.create(:news_item, :publish_date => 2.hours.ago) news_items = Refinery::News::Item.all expect(news_items.first).to eq(news_item1) expect(news_items.second).to eq(news_item2) end end describe ".not_expired" do let!(:news_item) { FactoryBot.create(:news_item) } specify "expiration date not set" do expect(Refinery::News::Item.not_expired.count).to eq(1) end specify "expiration date set in future" do news_item.expiration_date = Time.now + 1.hour news_item.save! expect(Refinery::News::Item.not_expired.count).to eq(1) end specify "expiration date in past" do news_item.expiration_date = Time.now - 1.hour news_item.save! expect(Refinery::News::Item.not_expired.count).to eq(0) end end describe ".published" do it "returns only published news items" do FactoryBot.create(:news_item) FactoryBot.create(:news_item, :publish_date => Time.now + 1.hour) expect(Refinery::News::Item.published.count).to eq(1) end end describe ".latest" do it "returns 10 latest news items by default" do 5.times { FactoryBot.create(:news_item) } 5.times { FactoryBot.create(:news_item, :publish_date => Time.now + 1.hour) } expect(Refinery::News::Item.latest.count).to eq(5) 7.times { FactoryBot.create(:news_item) } expect(Refinery::News::Item.latest.count).to eq(10) end it "returns latest n news items" do 4.times { FactoryBot.create(:news_item) } expect(Refinery::News::Item.latest(3).count).to eq(3) end end describe ".not_published?" do it "returns not published news items" do news_item = FactoryBot.create(:news_item, :publish_date => Time.now + 1.hour) expect(news_item.not_published?).to be_truthy end end describe ".archived" do it "returns all published/expired news items" do expired = FactoryBot.create(:news_item, :publish_date => Time.now - 2.months, :expiration_date => Time.now - 1.months) published = FactoryBot.create(:news_item, :publish_date => Time.now - 1.month) not_published = FactoryBot.create(:news_item, :publish_date => Time.now + 1.month) expect(Refinery::News::Item.archived).to include(expired) expect(Refinery::News::Item.archived).to include(published) expect(Refinery::News::Item.archived).to_not include(not_published) end end describe "#should_generate_new_friendly_id?" do context "when title changes" do it "regenerates slug upon save" do news_item = FactoryBot.create(:news_item, :title => "Test Title") news_item.title = "Test Title 2" news_item.save! expect(news_item.slug).to eq("test-title-2") end end end end end end
ruby
MIT
8e89de6c68077da150fb48dc5feb44c8f85a775c
2026-01-04T17:58:21.941874Z
false
refinery/refinerycms-news
https://github.com/refinery/refinerycms-news/blob/8e89de6c68077da150fb48dc5feb44c8f85a775c/spec/features/news_archive.rb
spec/features/news_archive.rb
require "spec_helper" describe "manage news items", :type => :feature do before do date = "dec/2011" @time = Time.parse(date) end it "should display proper date" do expect(@time).to eq("dec/2011") end end
ruby
MIT
8e89de6c68077da150fb48dc5feb44c8f85a775c
2026-01-04T17:58:21.941874Z
false
refinery/refinerycms-news
https://github.com/refinery/refinerycms-news/blob/8e89de6c68077da150fb48dc5feb44c8f85a775c/spec/features/manage_news_items_spec.rb
spec/features/manage_news_items_spec.rb
require "spec_helper" describe "manage news items", :type => :feature do refinery_login context "when no news items" do it "invites to create one" do visit refinery.news_admin_items_path expect(page).to have_content("There are no news items yet. Click \"Add News Item\" to add your first news item.") end end describe "action links" do it "shows add news item link" do visit refinery.news_admin_items_path within "#actions" do expect(page).to have_content("Add News Item") expect(page).to have_selector("a[href='/#{Refinery::Core.backend_route}/news/items/new']") end end end describe "new/create" do it "allows to create news item" do visit refinery.news_admin_items_path click_link "Add News Item" fill_in "Title", :with => "My first news item" fill_in "Body", :with => "bla bla" fill_in "Source", :with => "http://refinerycms.com" click_button "Save" expect(page).to have_content("'My first news item' was successfully added.") expect(page.body).to match(/Remove this news item forever/) expect(page.body).to match(/Edit this news item/) expect(page.body).to match(%r{/#{Refinery::Core.backend_route}/news/items/my-first-news-item/edit}) expect(page.body).to match(/View this news item live/) expect(page.body).to match(%r{/news/items/my-first-news-item}) expect(Refinery::News::Item.count).to eq(1) end end describe "edit/update" do before { FactoryBot.create(:news_item, :title => "Update me") } it "updates news item" do visit refinery.news_admin_items_path expect(page).to have_content("Update me") click_link "Edit this news item" fill_in "Title", :with => "Updated" click_button "Save" expect(page).to have_content("'Updated' was successfully updated.") end end describe "destroy" do before { FactoryBot.create(:news_item, :title => "Delete me") } it "removes news item" do visit refinery.news_admin_items_path click_link "Remove this news item forever" expect(page).to have_content("'Delete me' was successfully removed.") expect(Refinery::News::Item.count).to eq(0) end end context "duplicate news item titles" do before { FactoryBot.create(:news_item, :title => "I was here first") } it "isn't a problem" do visit refinery.new_news_admin_item_path fill_in "Title", :with => "I was here first" fill_in "Body", :with => "Doesn't matter" click_button "Save" expect(Refinery::News::Item.count).to eq(2) end end end
ruby
MIT
8e89de6c68077da150fb48dc5feb44c8f85a775c
2026-01-04T17:58:21.941874Z
false
refinery/refinerycms-news
https://github.com/refinery/refinerycms-news/blob/8e89de6c68077da150fb48dc5feb44c8f85a775c/spec/features/visit_news_items_spec.rb
spec/features/visit_news_items_spec.rb
require "spec_helper" describe "visit news items", :type => :feature do before do FactoryBot.create(:page, :link_url => "/") FactoryBot.create(:page, :link_url => "/news", :title => "News") FactoryBot.create(:news_item, :title => "unpublished", :publish_date => 1.day.from_now) @published_news_item = FactoryBot.create(:news_item, :title => "published", :source => "http://refinerycms.com", :publish_date => 1.hour.ago) end it "shows news link in menu" do visit "/" within "#menu" do expect(page).to have_content("News") expect(page).to have_selector("a[href='/news']") end end it "shows news item" do visit refinery.news_items_path expect(page).to have_content("published") expect(page).to have_selector("a[href='/news/published']") expect(page).to have_no_content("unpublished") expect(page).to have_no_selector("a[href='/news/unpublished']") end it "has a source on the news item" do visit refinery.news_item_path(@published_news_item) expect(page).to have_content("Source http://refinerycms.com") end end
ruby
MIT
8e89de6c68077da150fb48dc5feb44c8f85a775c
2026-01-04T17:58:21.941874Z
false
refinery/refinerycms-news
https://github.com/refinery/refinerycms-news/blob/8e89de6c68077da150fb48dc5feb44c8f85a775c/lib/refinerycms-news.rb
lib/refinerycms-news.rb
require 'refinery/news'
ruby
MIT
8e89de6c68077da150fb48dc5feb44c8f85a775c
2026-01-04T17:58:21.941874Z
false
refinery/refinerycms-news
https://github.com/refinery/refinerycms-news/blob/8e89de6c68077da150fb48dc5feb44c8f85a775c/lib/generators/refinery/news_generator.rb
lib/generators/refinery/news_generator.rb
module Refinery class NewsGenerator < Rails::Generators::Base def rake_db rake("refinery_news:install:migrations") rake("refinery_settings:install:migrations") end def append_load_seed_data create_file 'db/seeds.rb' unless File.exists?(File.join(destination_root, 'db', 'seeds.rb')) append_file 'db/seeds.rb', :verbose => true do <<-EOH # Added by Refinery CMS News engine Refinery::News::Engine.load_seed EOH end end end end
ruby
MIT
8e89de6c68077da150fb48dc5feb44c8f85a775c
2026-01-04T17:58:21.941874Z
false
refinery/refinerycms-news
https://github.com/refinery/refinerycms-news/blob/8e89de6c68077da150fb48dc5feb44c8f85a775c/lib/refinery/news.rb
lib/refinery/news.rb
require 'refinerycms-core' require 'refinerycms-settings' module Refinery autoload :NewsGenerator, 'generators/refinery/news_generator' module News require 'refinery/news/engine' class << self attr_writer :root def root @root ||= Pathname.new(File.expand_path('../../../', __FILE__)) end def factory_paths @factory_paths ||= [ root.join("spec/factories").to_s ] end end end end
ruby
MIT
8e89de6c68077da150fb48dc5feb44c8f85a775c
2026-01-04T17:58:21.941874Z
false
refinery/refinerycms-news
https://github.com/refinery/refinerycms-news/blob/8e89de6c68077da150fb48dc5feb44c8f85a775c/lib/refinery/news/engine.rb
lib/refinery/news/engine.rb
module Refinery module News class Engine < Rails::Engine include Refinery::Engine isolate_namespace Refinery::News initializer "init plugin" do Refinery::Plugin.register do |plugin| plugin.pathname = root plugin.name = "refinerycms_news" plugin.menu_match = /refinery\/news(\/items)?$/ plugin.url = proc { Refinery::Core::Engine.routes.url_helpers.news_admin_items_path } end end config.after_initialize do Refinery.register_engine(Refinery::News) end end end end
ruby
MIT
8e89de6c68077da150fb48dc5feb44c8f85a775c
2026-01-04T17:58:21.941874Z
false
refinery/refinerycms-news
https://github.com/refinery/refinerycms-news/blob/8e89de6c68077da150fb48dc5feb44c8f85a775c/config/routes.rb
config/routes.rb
Refinery::Core::Engine.routes.draw do namespace :news do root :to => "items#index" get 'archive/:year(/:month)', :to => 'items#archive', :as => 'items_archive', :constraints => { :year => /\d{4}/, :month => /\d{1,2}/ } resources :items, :only => [:show, :index], :path => '' end namespace :news, :path => '' do namespace :admin, :path => Refinery::Core.backend_route do scope :path => 'news' do root :to => "items#index" resources :items, :except => :show end end end end
ruby
MIT
8e89de6c68077da150fb48dc5feb44c8f85a775c
2026-01-04T17:58:21.941874Z
false
apexatoll/cliptic
https://github.com/apexatoll/cliptic/blob/db087adb776515dc73af13d096e2ce9a3b8dabab/lib/cliptic.rb
lib/cliptic.rb
module Cliptic require 'cgi' require 'curb' require 'curses' require 'date' require 'fileutils' require 'json' require 'sqlite3' require 'time' class Screen extend Curses def self.setup init_curses set_colors if has_colors? redraw end def self.init_curses init_screen raw noecho curs_set(0) end def self.set_colors start_color use_default_colors 1.upto(8) do |i| init_pair(i, i, -1) init_pair(i+8, 0, i) end end def self.clear stdscr.clear stdscr.refresh end def self.too_small? lines < 36 || cols < 61 end def self.redraw(cb:nil) Interface::Resizer.new.show if Screen.too_small? Screen.clear cb.call if cb end end require_relative "cliptic/version" require_relative "cliptic/terminal.rb" require_relative "cliptic/lib.rb" require_relative "cliptic/config.rb" require_relative "cliptic/database.rb" require_relative "cliptic/windows.rb" require_relative "cliptic/interface.rb" require_relative "cliptic/menus.rb" require_relative "cliptic/main.rb" end
ruby
MIT
db087adb776515dc73af13d096e2ce9a3b8dabab
2026-01-04T17:58:20.682312Z
false
apexatoll/cliptic
https://github.com/apexatoll/cliptic/blob/db087adb776515dc73af13d096e2ce9a3b8dabab/lib/cliptic/main.rb
lib/cliptic/main.rb
module Cliptic module Main module Windows class Top_Bar < Cliptic::Interface::Top_Bar def initialize(date:Date.today) super(date:date) end end class Bottom_Bar < Cliptic::Interface::Bottom_Bar def draw super add_str(x:-1, str:controls) end def mode(mode) setpos.color($colors[mode]) << mode_str(mode) .center(8) color.refresh end def unsaved(bool) add_str(x:9, str:(bool ? "| +" : " "), bold:bool) end private def mode_str(mode) { N:"NORMAL", I:"INSERT" }[mode] end def controls "^S save | ^R reveal | ^E reset | ^G check" end end class Grid < Cliptic::Windows::Grid attr_reader :indices, :blocks def initialize(puzzle:) super(**puzzle.size, line:1) @indices,@blocks = puzzle.indices,puzzle.blocks link_cells_to_clues(clues:puzzle.clues) end def draw super add_indices add_blocks end def cell(y:, x:) cells[y][x] end private def add_indices indices.each{|i,pos|cell(**pos).set_number(n:i)} end def add_blocks blocks.each{|pos| cell(**pos).set_block} end def make_cells(y:, x:) y.times.map{|iy| x.times.map{|ix| Cell.new(sq:Pos.mk(iy,ix), grid:self) }} end def link_cells_to_clues(clues:) clues.each do |clue| clue.cells=clue.coords.map{|pos|cell(**pos)} end end end class Cell < Cliptic::Windows::Cell attr_reader :index, :blocked, :buffer attr_accessor :locked def initialize(sq:, grid:) super(sq:sq, grid:grid) @index, @blocked, @locked = false, false, false @buffer = " " end def set_number(n:index, active:false) @index = n unless index grid.color(active ? $colors[:active_num] : $colors[:num]) focus(y:-1, x:-1) grid << Chars.small_num(n) grid.color end def set_block focus(x:-1).grid.color($colors[:block]) << Chars::Block @blocked = true grid.color end def underline grid.attron(Curses::A_UNDERLINE) write grid.attroff(Curses::A_UNDERLINE) end def write(char=@buffer) unless @locked super(char) @buffer = char end; self end def unlock @locked = false unless @blocked; self end def color(cp) grid.color(cp) write grid.color end def clear @locked, @blocked = false, false @buffer = " " end end class Cluebox < Cliptic::Windows::Window def initialize(grid:) super(y:Curses.lines-grid.y-2, line:grid.y+1, col:0) end def show(clue:) draw(cp:$colors[:cluebox]) set_meta(clue) set_hint(clue) noutrefresh end private def set_meta(clue) add_str(y:0, x:2, str:clue.meta, cp:clue.done ? $colors[:correct] : $colors[:meta]) end def set_hint(clue) wrap_str(str:clue.hint, line:1) end def bottom_border side_border end end end module Fetch class Request URL="https://data.puzzlexperts.com/puzzleapp-v3/data.php" attr_reader :data def initialize(date:Date.today, psid:100000160) @data = {date:date, psid:psid} end def send_request valid_input? ? raw : (raise Cliptic::Errors::Invalid_Date.new(data[:date])) end def valid_input? JSON.parse(raw, symbolize_names:true) .dig(:cells, 0, :meta, :data).length > 0 end def raw @raw || Curl.get(URL, data) do |curl| curl.ssl_verify_peer = false end.body end end class Cache < Request Path = "#{Dir.home}/.cache/cliptic" def initialize(date:Date.today) super(date:date) make_cache_dir end def query date_cached? ? read_cache : send_request .tap{|str| write_cache(str)} end def make_cache_dir FileUtils.mkdir_p(Path) unless Dir.exist?(Path) end def date_cached? File.exist?(file_path) end def file_path "#{Path}/#{data[:date]}" end def read_cache File.read(file_path) end def write_cache(str) File.write(file_path, str) end end class Parser attr_reader :raw def initialize(date:Date.today) @raw = Cache.new(date:date).query end def parse [ parse_clues(raw), parse_size(raw) ] end private def parse_size(raw) Pos.mk(*["rows", "columns"] .map{|field| raw.scan(/#{field}=(.*?(?=&))/)[0][0]} ) end def parse_clues(raw) JSON.parse(raw, symbolize_names:true) .dig(:cells, 0, :meta, :data) .gsub(/^(.*?&){3}(.*)&id=.*$/, "\\2") .split(/(?:^|&).*?=/).drop(1) .each_slice(5).to_a .map{|data| Puzzle::Clue.new(**struct_clue(data))} end def struct_clue(raw_clue) { ans:raw_clue[0].chars.map(&:upcase), hint:CGI.unescape(raw_clue[1]), dir:raw_clue[2].to_sym, start:Pos.mk(raw_clue[3], raw_clue[4]) } end end end module Puzzle class Puzzle include Fetch attr_reader :clues, :size, :indices, :map, :sorted, :blocks def initialize(date:Date.today) @clues, @size = Parser.new(date:date).parse @indices = index_clues @map = map_clues @sorted = order_clues @blocks = find_blocks chain_clues end def first_clue sorted[:a][0].index == 1 ? sorted[:a][0] : sorted[:d][0] end def get_clue(y:, x:, dir:) map[:index][dir][y][x].is_a?(Clue) ? map[:index][dir][y][x] : map[:index][Pos.change_dir(dir)][y][x] end def get_clue_by_index(i:, dir:) sorted[dir] .find{|clue| clue.index == i} || sorted[Pos.change_dir(dir)] .find{|clue| clue.index == i} end def complete? clues.all?{|c| c.done} end def n_clues_done clues.select{|c| c.done}.count end def n_clues clues.count end def check_all clues.each{|c| c.check} end private def index_clues clues.map{|clue| clue.start.values}.uniq.sort .each_with_index .map{ |pos, n| [n+1, Pos.mk(*pos)] }.to_h .each{|n, pos| clues.find_all{|clue| clue.start==pos} .each{|clue| clue.index = n}} end def empty Array.new(size[:y]){ Array.new(size[:x], ".") } end def map_clues { index:{a:empty, d:empty}, chars:empty }.tap do |map| clues.each do |clue| clue.coords.zip(clue.ans) do |pos, char| map[:index][clue.dir][pos[:y]][pos[:x]] = clue map[:chars][pos[:y]][pos[:x]] = char end end end end def order_clues {a:[], d:[]}.tap do |order| clues.map{|clue| order[clue.dir] << clue} end end def find_blocks [].tap do |a| map[:chars].each_with_index.map do |row, y| row.each_with_index.map do |char, x| a << Pos.mk(y,x) if char == "." end end end end def chain_clues sorted.each do |dir, clues| clues.each_with_index do |clue, i| clue.next = sorted[dir][i+1] || sorted[Pos.change_dir(dir)][0] clue.prev = i == 0 ? sorted[Pos.change_dir(dir)].last : sorted[dir][i-1] end end end end class Clue attr_reader :ans, :dir, :start, :hint, :length, :coords attr_accessor :done, :index, :next, :prev, :cells def initialize(ans:, hint:, dir:, start:) @ans, @dir, @start = ans, dir, start @length = ans.length @hint = parse_hint(hint) @coords = map_coords(**start, l:length) @done = false end def meta @meta || "#{index} #{dir==:a ? "across" : "down"}" end def activate cells.first.set_number(active:true) cells.each{|c| c.underline} end def deactivate cells.first.set_number(active:false) cells.each{|c| c.write} check if $config[:auto_mark] end def has_cell?(y:, x:) coords.include?(Pos.mk(y,x)) end def check if full? correct? ? mark_correct : mark_incorrect end end def full? get_buffer.reject{|b| b == " "}.count == length end def clear cells.each{|c| c.write(" ")} end def reveal ans.zip(cells){|char, cell| cell.write(char)} mark_correct end private def parse_hint(hint) hint.match?(/^.*\(.*\)$/) ? hint : "#{hint} (#{length})" end def map_coords(y:, x:, l:) case dir when :a then x.upto(x+l-1) .map{|ix| Pos.mk(y,ix)} when :d then y.upto(y+l-1) .map{|iy| Pos.mk(iy,x)} end end def get_buffer cells.map{|c| c.buffer} end def correct? get_buffer.join == ans.join end def mark_correct cells.each do |cell| cell.color($colors[:correct]) cell.locked = true end @done = true end def mark_incorrect cells.each{|c| c.color($colors[:incorrect])} end end end module Player module Menus class Pause < Interface::Menu attr_reader :game def initialize(game:) super @game = game @draw_bars = false end def opts { "Continue" => ->{back; game.unpause}, "Exit Game" => ->{back; game.exit} } end def title "Paused" end def ctrls super.merge({ ?q => ->{back; game.unpause} }) end end class Puzzle_Complete < Interface::Menu def initialize super @draw_bars = false end def opts { "Exit" => ->{back; Screen.clear}, "Quit" => ->{exit} } end def title "Puzzle Complete!" end def ctrls super.merge({ ?q => ->{back; Screen.clear} }) end end class Reset_Progress < Interface::Yes_No_Menu def initialize(game:) super(yes:->{game.reset}, post_proc:->{game.unpause}) @draw_bars = false end def title "Reset puzzle progress?" end end end class Board include Puzzle, Windows attr_reader :puzzle, :grid, :box, :cursor, :clue, :dir, :state def initialize(date:Date.today)#, state:) @puzzle = Puzzle::Puzzle.new(date:date) @grid = Grid.new(puzzle:puzzle) @box = Cluebox.new(grid:grid) @cursor = Cursor.new(grid:grid) #@state = state end def setup(state:nil) grid.draw load_state(state:state) set_clue(clue:puzzle.first_clue, mv:true) if !@clue update self end def update cursor.reset grid.refresh end def redraw grid.draw grid.cells.flatten .find_all{|c| c.buffer != " "} .each{|c| c.unlock.write} puzzle.check_all if $config[:auto_mark] clue.activate end def move(y:0, x:0) cursor.move(y:y, x:x) if current_cell.blocked move(y:y, x:x) elsif outside_clue? set_clue(clue:get_clue_at(**cursor.pos)) end end def insert_char(char:, advance:true) addch(char:char) move_after_insert(advance:advance) check_current_clue end def delete_char(advance:true) addch(char:" ").underline advance_cursor(n:-1) if advance && !on_first_cell? end def next_clue(n:1) n.times do set_clue(clue:clue.next, mv:true) end next_clue if clue.done && !puzzle.complete? end def prev_clue(n:1) n.times do on_first_cell? ? set_clue(clue:clue.prev, mv:true) : to_start end prev_clue if clue.done && !puzzle.complete? end def to_start cursor.set(**clue.coords.first) end def to_end cursor.set(**clue.coords.last) end def swap_direction set_clue(clue:get_clue_at( **cursor.pos, dir:Pos.change_dir(dir))) end def save_state [].tap do |state| grid.cells.flatten.map do |cell| state << { sq:cell.sq, char:cell.buffer } unless cell.blocked || cell.buffer == " " end end end def goto_clue(n:) set_clue(clue:get_clue_by_index(i:n), mv:true) end def goto_cell(n:) if n > 0 && n <= clue.length cursor.set(**clue.cells[n-1].sq) end end def clear_clue clue.clear clue.activate end def reveal_clue clue.reveal next_clue(n:1) end def clear_all_cells grid.cells.flatten.each{|cell| cell.clear} puzzle.clues.each{|clue| clue.done = false} end def advance_cursor(n:1) case dir when :a then move(x:n) when :d then move(y:n) end end private def load_state(state:) if state.exists? state.chars.each do |s| grid.cell(**s[:sq]).write(s[:char]) end puzzle.check_all if $config[:auto_mark] end end def set_clue(clue:, mv:false) @clue.deactivate if @clue @clue = clue @dir = clue.dir clue.activate cursor.set(**clue.start.dup) if mv box.show(clue:clue) end def current_cell grid.cell(**cursor.pos) end def on_first_cell? current_cell == clue.cells.first end def on_last_cell? current_cell == clue.cells.last end def outside_clue? !clue.has_cell?(**cursor.pos) end def get_clue_at(y:, x:, dir:@dir) puzzle.get_clue(y:y, x:x, dir:dir) end def get_clue_by_index(i:) puzzle.get_clue_by_index(i:i, dir:dir) || clue end def addch(char:) current_cell.write(char.upcase) end def move_after_insert(advance:) if on_last_cell? next_clue(n:1) if $config[:auto_advance] elsif advance advance_cursor(n:1) end end def check_current_clue clue.check if $config[:auto_mark] end end class Cursor attr_reader :grid, :pos def initialize(grid:) @grid = grid end def set(y:, x:) @pos = Pos.mk(y,x) end def reset grid.cell(**pos).focus Curses.curs_set(1) end def move(y:, x:) @pos[:y]+= y @pos[:x]+= x wrap end def wrap pos[:x] += grid.sq[:x] while pos[:x] < 0 pos[:y] += grid.sq[:y] while pos[:y] < 0 pos[:x] -= grid.sq[:x] while pos[:x] >= grid.sq[:x] pos[:y] -= grid.sq[:y] while pos[:y] >= grid.sq[:y] end end class Game include Database, Windows, Menus attr_reader :state, :board, :top_b, :timer, :bot_b, :ctrls , :date attr_accessor :mode, :continue, :unsaved def initialize(date:Date.today) @date = date init_windows @timer = Timer.new(time:state.time, bar:top_b, callback:->{board.update}) @ctrls = Controller.new(game:self) @unsaved = false @continue = true draw end def play if state.done show_completed_menu else add_to_recents game_and_timer_threads.map(&:join) end end def redraw save Screen.clear init_windows draw end def unsaved=(bool) @unsaved = bool bot_b.unsaved(bool) end def mode=(mode) @mode = mode bot_b.mode(mode) end def user_input board.grid.getch end def pause timer.stop Menus::Pause.new(game:self).choose_opt end def unpause timer.start board.redraw end def save state.save(game:self) bot_b.time_str(t:5, x:10, str:"Saved!") self.unsaved = false end def reset_menu timer.stop Reset_Progress.new(game:self) end def reset state.delete if state.exists? board.clear_all_cells timer.reset end def reveal state.reveals+= 1 board.reveal_clue end def game_over save if $config[:auto_save] timer.stop completed if board.puzzle.complete? end def exit @continue = false Screen.clear end private def init_windows @state = State.new(date:date) @board = Board.new(date:date) @top_b = Top_Bar.new(date:date) @bot_b = Bottom_Bar.new end def draw [top_b, bot_b].each(&:draw) self.mode = :N board.setup(state:state) end def completed save log_score show_completed_menu end def run until game_finished? ctrls.route(char:user_input)&.call board.update end game_over end def game_finished? board.puzzle.complete? || !continue end def game_and_timer_threads [ Thread.new{run}, Thread.new{timer.start} ] end def show_completed_menu Puzzle_Complete.new.choose_opt end def add_to_recents Recents.new.add(date:date) end def log_score Scores.new.add(game:self) end end class Timer attr_reader :time, :bar, :callback, :run def initialize(time:0, bar:, callback:) @time = Time.abs(time) @bar, @callback = bar, callback end def start Thread.new{tick} @run = true end def stop @run = false end def reset @time = Time.abs(0) @run = false end private def tick while @run bar.add_str(x:-1, str:time_str) callback.call @time += 1 sleep(1) end end def time_str time.strftime("%T") end end class Controller attr_reader :game def initialize(game:) @game = game end def route(char:) if is_ctrl_key?(char) controls[:G][char.to_i] elsif is_arrow_key?(char) arrow(char) else case game.mode when :N then normal(char:char) when :I then insert(char:char) end end end def normal(char:, n:1) if (?0..?9).cover?(char) await_int(n:char.to_i) else controls(n)[:N][char] end end def insert(char:) case char when 27 then ->{game.mode = :N} when 127 then ->{game.board.delete_char} when ?A..?z ->{game.board.insert_char(char:char); game.unsaved = true } end end def is_ctrl_key?(char) (1..26).cover?(char) end def is_arrow_key?(char) (258..261).cover?(char) end def arrow(char) mv = case char when Curses::KEY_UP then {y:-1} when Curses::KEY_DOWN then {y:1} when Curses::KEY_LEFT then {x:-1} when Curses::KEY_RIGHT then {x:1} end ->{game.board.move(**mv)} end def controls(n=1) { G:{ 3 => ->{game.exit}, 5 => ->{game.reset_menu.choose_opt}, 7 => ->{game.board.puzzle.check_all}, 9 => ->{game.board.swap_direction}, 12 => ->{game.redraw}, 16 => ->{game.pause}, 18 => ->{game.reveal}, 19 => ->{game.save} }, N:{ ?j => ->{game.board.move(y:n)}, ?k => ->{game.board.move(y:n*-1)}, ?h => ->{game.board.move(x:n*-1)}, ?l => ->{game.board.move(x:n)}, ?i => ->{game.mode = :I}, ?I => ->{game.board.to_start; game.mode=:I}, ?w => ->{game.board.next_clue(n:n)}, ?a => ->{game.board.advance_cursor(n:1); game.mode=:I}, ?b => ->{game.board.prev_clue(n:n)}, ?e => ->{game.board.to_end}, ?r => ->{await_replace}, ?c => ->{await_delete; game.mode=:I}, ?d => ->{await_delete}, ?x => ->{game.board.delete_char(advance:false)} } } end def await_int(n:) char = game.user_input case char when ?g then ->{game.board.goto_clue(n:n)} when ?G then ->{game.board.goto_cell(n:n)} when ?0..?9 then await_int(n:(10*n)+char.to_i) else normal(char:char, n:n) end end def await_replace char = game.user_input case char when ?A..?z game.board.insert_char( char:char, advance:false) end end def await_delete case game.user_input when ?w then game.board.clear_clue end end end end end end
ruby
MIT
db087adb776515dc73af13d096e2ce9a3b8dabab
2026-01-04T17:58:20.682312Z
false
apexatoll/cliptic
https://github.com/apexatoll/cliptic/blob/db087adb776515dc73af13d096e2ce9a3b8dabab/lib/cliptic/version.rb
lib/cliptic/version.rb
module Cliptic VERSION = "0.1.3" end
ruby
MIT
db087adb776515dc73af13d096e2ce9a3b8dabab
2026-01-04T17:58:20.682312Z
false
apexatoll/cliptic
https://github.com/apexatoll/cliptic/blob/db087adb776515dc73af13d096e2ce9a3b8dabab/lib/cliptic/interface.rb
lib/cliptic/interface.rb
module Cliptic module Interface class Top_Bar < Windows::Bar attr_reader :date def initialize(date:Date.today) super(line:0) @date = date end def draw super add_str(x:1, str:title, bold:true) add_str(x:title.length+2, str:date.to_long) end def title "cliptic:" end def reset_pos move(line:0, col:0) end end class Bottom_Bar < Windows::Bar def initialize super(line:Curses.lines-1) end def draw super noutrefresh end def reset_pos move(line:Curses.lines-1, col:0) end end class Logo < Windows::Grid attr_reader :text def initialize(line:, text:"CLIptic") super(y:1, x:text.length, line:line) @text = text end def draw(cp_grid:$colors[:logo_grid], cp_text:$colors[:logo_text], bold:true) super(cp:cp_grid) bold(bold).color(cp_text) add_str(str:text) reset_attrs refresh end end class Menu_Box < Windows::Window include Interface attr_reader :logo, :title, :top_b, :bot_b, :draw_bars def initialize(y:, title:false) @logo = Logo.new(line:line+1) @title = title super(y:y, x:logo.x+4, line:line, col:nil) @top_b = Top_Bar.new @bot_b = Bottom_Bar.new @draw_bars = true end def draw super [top_b, bot_b].each(&:draw) if draw_bars logo.draw add_title if title self end def line (Curses.lines-15)/2 end def add_title(y:4, str:title, cp:$colors[:title], bold:true) add_str(y:y, str:str, cp:cp, bold:bold) end def reset_pos move(line:line) logo.move(line:line+1) [top_b, bot_b].each(&:reset_pos) end end class Resizer < Menu_Box def initialize super(y:8, title:title) end def title "Screen too small" end def draw Screen.clear reset_pos super wrap_str(str:prompt, line:5) refresh end def show while Screen.too_small? draw exit if (c = getch) == ?q || c == 3 end end def prompt "Screen too small. Increase screen size to run cliptic." end def line (Curses.lines-8)/2 end end class Selector < Windows::Window attr_reader :opts, :ctrls, :run, :tick attr_accessor :cursor def initialize(opts:, ctrls:, x:, line:, tick:nil, y:opts.length, col:nil) super(y:y, x:x, line:line, col:col) @opts, @ctrls, @tick = opts, ctrls, tick @cursor, @run = 0, true end def select while @run draw ctrls[getch]&.call end end def stop @run = false end def cursor=(n) @cursor = Pos.wrap(val:n,min:0,max:opts.length-1) end private def draw Curses.curs_set(0) setpos opts.each_with_index do |opt, i| standout if cursor == i self << format_opt(opt) standend end tick.call if tick refresh end def format_opt(opt) opt.to_s.center(x) end end class Date_Selector < Selector def initialize(opts:, ctrls:, line:, x:18, tick:) super(y:1, x:18, opts:opts, ctrls:ctrls, line:line, tick:tick) end def format_opt(opt) opt.to_s.rjust(2, "0").center(6) end end class Stat_Window < Windows::Window def initialize(y:5, x:33, line:) super(y:y, x:x, line:line) end def show(date:, cp:$colors[:stats]) draw(clr:true).color(cp) get_stats(date:date).each_with_index do |line, i| setpos(i+1, 8) self << line end color.noutrefresh end def get_stats(date:) Database::Stats.new(date:date).stats_str end end class Menu < Menu_Box attr_reader :selector, :height def initialize(height:opts.length+6, sel:Selector, sel_opts:opts.keys, tick:nil, **) super(y:height, title:title) @height = height @selector = sel.new(opts:sel_opts, ctrls:ctrls, line:line+5, x:logo.x, tick:tick) end def choose_opt show selector.select end def enter(pre_proc:->{hide}, post_proc:->{show}) pre_proc.call if pre_proc opts.values[selector.cursor]&.call reset_pos post_proc.call if post_proc end def back(post_proc:->{hide}) selector.stop post_proc.call if post_proc end def show draw end def hide clear end def ctrls { ?j => ->{selector.cursor += 1}, ?k => ->{selector.cursor -= 1}, 258 => ->{selector.cursor += 1}, 259 => ->{selector.cursor -= 1}, 10 => ->{enter}, ?q => ->{back}, 3 => ->{back}, Curses::KEY_RESIZE => ->{Screen.redraw(cb:->{redraw})} } end def reset_pos super selector.move(line:line+5) end def redraw reset_pos draw end end class Menu_With_Stats < Menu attr_reader :stat_win def initialize(height:opts.length+6, sel:Selector, **) super(height:height, sel:sel, sel_opts:opts, tick:->{update_stats}) @stat_win = Stat_Window.new(line:line+height) end def update_stats stat_win.show(date:stat_date) end def hide super stat_win.clear end def enter hide Main::Player::Game.new(date:stat_date).play reset_pos show end def reset_pos super stat_win.move(line:line+height) end end class SQL_Menu_With_Stats < Menu_With_Stats include Database attr_reader :dates def initialize(table:) @dates = table.new .select_list.map{|d| Date.parse(d[0])} super end def opts dates.map{|d| d.to_long} || [nil] end def stat_date dates[selector.cursor] end end class Yes_No_Menu < Menu attr_reader :yes, :no, :post_proc def initialize(yes:, no:->{back}, post_proc:nil, title:nil) super @title = title @yes, @no, @post_proc = yes, no, post_proc end def opts { "Yes" => ->{yes.call; back; post}, "No" => ->{no.call; post} } end def post post_proc.call if post_proc end end end end
ruby
MIT
db087adb776515dc73af13d096e2ce9a3b8dabab
2026-01-04T17:58:20.682312Z
false
apexatoll/cliptic
https://github.com/apexatoll/cliptic/blob/db087adb776515dc73af13d096e2ce9a3b8dabab/lib/cliptic/menus.rb
lib/cliptic/menus.rb
module Cliptic module Menus class Main < Interface::Menu def opts { "Play Today" => ->{Cliptic::Main::Player::Game.new.play}, "Select Date"=> ->{Select_Date.new.choose_opt}, "This Week" => ->{This_Week.new.choose_opt}, "Recent Puzzles" => ->{Recent_Puzzles.new.choose_opt}, "High Scores"=> ->{High_Scores.new.choose_opt}, "Quit" => ->{exit} } end def title "Main Menu" end end class Select_Date < Interface::Menu_With_Stats attr_reader :opts, :earliest_date def initialize @earliest_date = (Date.today << 9) + 1 set_date(date:Date.today) super(height:7, sel:Interface::Date_Selector) end def title "Select Date" end def ctrls super.merge({ ?h => ->{selector.cursor -= 1}, ?l => ->{selector.cursor += 1}, ?j => ->{inc_date(1)}, ?k => ->{inc_date(-1)}, 258 => ->{inc_date(1)}, 259 => ->{inc_date(-1)}, 260 => ->{selector.cursor -= 1}, 261 => ->{selector.cursor += 1} }) end def stat_date Date.new(*@opts.reverse) end private def set_date(date:) @opts = [] unless @opts @opts[0] = date.day @opts[1] = date.month @opts[2] = date.year end def next_date(n) @opts.dup.tap{|d| d[selector.cursor] += n } end def inc_date(n) case selector.cursor when 0 then inc_day(n) when 1 then inc_month(n) when 2 then @opts[2] += n end check_in_range end def inc_day(n) next_date(n).tap do |date| if valid?(date) @opts[0]+= n elsif date[0] == 0 set_date(date:stat_date-1) elsif date[0] > 28 set_date(date:stat_date+1) end end end def inc_month(n) next_date(n).tap do |date| if valid?(date) @opts[1] += n elsif date[1] == 0 set_date(date:stat_date << 1) elsif date[1] == 13 set_date(date:stat_date >> 1) elsif date[0] > 28 set_date(date:last_day_of_month(date:date)) end end end def valid?(date) Date.valid_date?(*date.reverse) end def last_day_of_month(date:) Date.new(date[2], date[1]+1, 1)-1 end def check_in_range set_date(date:Date.today) if date_late? set_date(date:earliest_date) if date_early? end def date_late? stat_date > Date.today end def date_early? stat_date < earliest_date end end class This_Week < Interface::Menu_With_Stats def days @days || 7.times.map{|i| Date.today - i} end def stat_date days[selector.cursor] end def opts @opts || days.map{|d| d.strftime("%A").ljust(9).center(12) + tickbox(d)} end def title "This Week" end def tickbox(date) "[#{Database::State.new(date:date).done ? Chars::Tick : " "}]" end end class Recent_Puzzles < Interface::SQL_Menu_With_Stats def initialize super(table:Database::Recents) end def title "Recently Played" end end class High_Scores < Interface::SQL_Menu_With_Stats def initialize super(table:Database::Scores) end def title "High Scores" end end end end
ruby
MIT
db087adb776515dc73af13d096e2ce9a3b8dabab
2026-01-04T17:58:20.682312Z
false
apexatoll/cliptic
https://github.com/apexatoll/cliptic/blob/db087adb776515dc73af13d096e2ce9a3b8dabab/lib/cliptic/terminal.rb
lib/cliptic/terminal.rb
module Cliptic module Terminal class Command def self.run ARGV.size > 0 ? parse_args : main_menu rescue StandardError => e Curses.close_screen abort(e.message) end private def self.setup Config::Default.set Screen.setup Config::Custom.set at_exit{close} end def self.main_menu setup Cliptic::Menus::Main.new.choose_opt end def self.parse_args case arg = ARGV.shift when "reset", "-r" then Reset_Stats.route.call when "today", "-t" then play(ARGV.shift.to_i) end end def self.play(offset) setup Cliptic::Main::Player:: Game.new(date:Date.today+offset).play end def self.close Curses.close_screen puts "Thanks for playing!" end end class Reset_Stats def self.route if valid_options.include?(c = ARGV.shift) ->{confirm_reset(c)} else ->{puts "Unknown option #{c}"} end end private def self.valid_options ["scores", "all", "states", "recents"] end def self.confirm_reset(table) puts prompt(table) user_confirmed? ? reset(table) : puts("Wise choice") end def self.prompt(table) <<~prompt cliptic: Reset #{table} Are you sure? This cannot be undone! [Y/n] prompt end def self.user_confirmed? gets.chomp === "Y" end def self.reset(table) table == "all" ? Database::Delete.all : Database::Delete.table(table) end end end end
ruby
MIT
db087adb776515dc73af13d096e2ce9a3b8dabab
2026-01-04T17:58:20.682312Z
false
apexatoll/cliptic
https://github.com/apexatoll/cliptic/blob/db087adb776515dc73af13d096e2ce9a3b8dabab/lib/cliptic/config.rb
lib/cliptic/config.rb
module Cliptic module Config Dir_Path = "#{Dir.home}/.config/cliptic" File_Path = "#{Dir_Path}/cliptic.rc" class Default def self.set $colors = colors $config = make_bool(config) end private def self.colors { box:8, grid:8, bar:16, logo_grid:8, logo_text:3, title:6, stats:6, active_num:3, num:8, block:8, I:15, N:12, correct:2, incorrect:1, meta:3, cluebox:8, menu_active:15, menu_inactive:0 } end def self.config { auto_advance:1, auto_mark:1, auto_save:1 } end def self.make_bool(hash) hash.each{|k, v| hash[k] = v == 1 } end end class Custom < Default def self.set cfg_file_exists? ? read_cfg : gen_cfg_menu.choose_opt end private def self.read_cfg Reader.new.tap do |file| key_map.each do |dest, key| dest.merge!(file.read(**key)) end end make_bool($config) end def self.key_map { $colors => {key:"hi"}, $config => {key:"set"} } end def self.cfg_file_exists? File.exist?(File_Path) end def self.gen_cfg_menu Cliptic::Interface::Yes_No_Menu.new( yes:->{Generator.new.write}, title:"Generate config file?" ) end end class Reader attr_reader :lines def initialize @lines = File.read(File_Path).each_line.map.to_a end def read(key:) lines.grep(/^\s*#{key}/) .map{|l| l.gsub(/^\s*#{key}\s+/, "") .split(/\s+/)} .map{|k, v| [k.to_sym, v.to_i]} .to_h end end class Generator def write FileUtils.mkdir_p(Dir_Path) unless cfg_dir_exists File.write(File_Path, make_file) end private def cfg_dir_exists Dir.exist?(Dir_Path) end def file_data { "Colour Settings" => { cmd:"hi", values:Default.colors }, "Interface Settings" => { cmd:"set", values:Default.config } } end def make_file file_data.map do |comment, data| ["//#{comment}"] + data[:values].map{|k, v| "#{data[:cmd]} #{k} #{v}"} + ["\n"] end.join("\n") end end end end
ruby
MIT
db087adb776515dc73af13d096e2ce9a3b8dabab
2026-01-04T17:58:20.682312Z
false
apexatoll/cliptic
https://github.com/apexatoll/cliptic/blob/db087adb776515dc73af13d096e2ce9a3b8dabab/lib/cliptic/windows.rb
lib/cliptic/windows.rb
module Cliptic module Windows class Window < Curses::Window include Chars attr_reader :y, :x, :line, :col attr_reader :centered_y, :centered_x def initialize(y:0, x:0, line:nil, col:nil) @y, @x = wrap_dims(y:y, x:x) @line,@col= center_pos(y:y,x:x,line:line,col:col) @centered_y, @centered_x = [line, col] .map{|pos| pos.nil?} super(@y, @x, @line, @col) keypad(true) end def draw(cp:$colors[:box]||0, clr:false) erase if clr setpos.color(cp) 1.upto(y) do |i| line = case i when 1 then top_border when y then bottom_border else side_border end self << line end; setpos.color.noutrefresh self end def color(cp=0) color_set(cp); self end def bold(on=true) on ? attron(Curses::A_BOLD) : attroff(Curses::A_BOLD) self end def wrap_str(str:, line:) split_str(str).each_with_index do |l, i| setpos(line+i, 2) self << l end; self end def setpos(y=0, x=0) super(y,x); self end def add_str(str:,y:line,x:(@x-str.length)/2, cp:nil, bold:false) color(cp) if cp setpos(*wrap_str_dims(y:y, x:x, str:str)) bold(bold) self << str noutrefresh reset_attrs end def clear erase noutrefresh self end def time_str(str:, y:, x:(@x-str.length)/2, t:5, cp:nil, bold:false) Thread.new{ add_str(str:str, y:y, x:x, cp:cp, bold:bold) sleep(t) add_str(str:" "*str.length, y:y, x:x, cp:cp, bold:bold) } self end def reset_attrs color(0).bold(false) self end def refresh super; self end def reset_pos move( *[centered_y, centered_x] .zip(total_dims, [y, x], [line, col]) .map{|cent, tot, dim, pos| cent ? (tot-dim)/2 : pos} ) refresh end def move(line:nil, col:nil) super(*center_pos(y:y, x:x, line:line, col:col)) end def standout color($colors[:menu_active]) end def standend color($colors[:menu_inactive]) end private def wrap_dims(y:, x:) [y, x].zip(total_dims) .map{|dim, tot| dim <= 0 ? dim+tot : dim} end def wrap_str_dims(y:, x:, str:) [y, x].zip(total_dims) .map{|pos,tot|pos<0 ? tot-str.length+pos : pos} end def total_dims [Curses.lines, Curses.cols] end def center_pos(y:, x:, line:, col:) [line, col].zip(total_dims, [y, x]) .map{|pos, tot, dim| pos || ((tot-dim)/2)} end def split_str(str) str.gsub(/(.{1,#{x-4}})(\s+|$\n?)|(.{1,#{x-4}})/, "\\1\\3\n").split("\n") end def top_border LU+(HL*(x-2))+RU end def bottom_border LL+(HL*(x-2))+RL end def side_border VL+(' '*(x-2))+VL end end class Grid < Window attr_reader :sq, :cells def initialize(y:, x:, line:nil, col:nil) @sq = Pos.mk(y,x) @y, @x = sq_to_dims(y:y, x:x) super(y:@y, x:@x, line:line, col:col) @cells = make_cells(**sq) end def draw(cp:$colors[:grid]||0) setpos.color(cp) 1.upto(y) do |i| line = case i when 1 then top_border when y then bottom_border else i.even? ? side_border : inner_border end self << line end; setpos.color self end def add_str(str:, y:0, x:0) str.chars.each_with_index do |char, i| cell(y:y, x:x+i).write(char) end end def cell(y:, x:) cells[y][x] end private def sq_to_dims(y:, x:) [ (2*y)+1, (4*x)+1 ] end def make_cells(y:, x:) y.times.map{|iy| x.times.map{|ix| Cell.new(sq:Pos.mk(iy,ix), grid:self)}} end def top_border LU+(HL*3+TD)*(sq[:x]-1)+HL*3+RU end def bottom_border LL+(HL*3+TU)*(sq[:x]-1)+HL*3+RL end def side_border (VL+" "*3)*sq[:x]+VL end def inner_border TR+(HL*3+XX)*(sq[:x]-1)+HL*3+TL end end class Cell attr_reader :sq, :grid, :pos def initialize(sq:, grid:) @sq, @grid, @pos = sq, grid, calc_abs_pos(**sq) end def focus(y:0, x:0) grid.setpos(*[y,x].zip(pos.values).map(&:sum)) self end def write(char) focus.grid << char; self end protected def calc_abs_pos(y:, x:) { y:(2*y)+1, x:(4*x)+2 } end end class Bar < Window attr_reader :bg_col def initialize(line:, bg_col:$colors[:bar]) super(y:1, x:0, line:line, col:0) @bg_col = bg_col end def add_str(y:0, x:, str:, bold:false, cp:bg_col) super(y:0, x:x, str:str, bold:bold, cp:cp) end def time_str(x:, str:, t:5, cp:bg_col, bold:false) super(y:0, x:x, str:str, t:5, cp:cp, bold:bold) end def draw bkgd(Curses.color_pair(bg_col)); self end end end end
ruby
MIT
db087adb776515dc73af13d096e2ce9a3b8dabab
2026-01-04T17:58:20.682312Z
false
apexatoll/cliptic
https://github.com/apexatoll/cliptic/blob/db087adb776515dc73af13d096e2ce9a3b8dabab/lib/cliptic/lib.rb
lib/cliptic/lib.rb
module Cliptic class Pos def self.mk(y,x) { y:y.to_i, x:x.to_i } end def self.wrap(val:, min:, max:) val > max ? min : (val < min ? max : val) end def self.change_dir(dir) dir == :a ? :d : :a end end class Date < Date def to_long self.strftime('%A %b %-d %Y') end end class Time < Time def self.abs(t) Time.at(t).utc end def to_s self.strftime("%T") end end module Chars HL = "\u2501" LL = "\u2517" LU = "\u250F" RL = "\u251B" RU = "\u2513" TD = "\u2533" TL = "\u252B" TR = "\u2523" TU = "\u253B" VL = "\u2503" XX = "\u254B" Tick = "\u2713" Nums = ["\u2080", "\u2081", "\u2082", "\u2083", "\u2084", "\u2085", "\u2086", "\u2087", "\u2088", "\u2089"] MS = "\u2588" LS = "\u258C" RS = "\u2590" Block = RS+MS+LS def self.small_num(n) n.to_s.chars.map{|n| Nums[n.to_i]}.join end end module Errors class Invalid_Date < StandardError attr_reader :date def initialize(date) @date = date end def message <<~msg Invalid date passed #{date} Earliest date #{Date.today<<9} msg end end end end
ruby
MIT
db087adb776515dc73af13d096e2ce9a3b8dabab
2026-01-04T17:58:20.682312Z
false
apexatoll/cliptic
https://github.com/apexatoll/cliptic/blob/db087adb776515dc73af13d096e2ce9a3b8dabab/lib/cliptic/database.rb
lib/cliptic/database.rb
module Cliptic module Database Dir_Path = "#{Dir.home}/.config/cliptic/db" File_Path = "#{Dir_Path}/cliptic.db" class SQL attr_reader :db, :table def initialize(table:) make_db_dir @table = table @db = SQLite3::Database.open(File_Path) db.results_as_hash = true self end def make_table db.execute(sql_make) end def select(cols:"*", where:nil, order:false, limit:false) db.execute( sql_select(cols:cols, where:where, order:order, limit:limit), where&.values&.map(&:to_s) ) end def insert(values:) db.execute(sql_insert(values:values), values.values) end def update(values:, where:) db.execute(sql_update(values:values, where:where), [values.values], [where.values]) end def delete(where:nil) db.execute(sql_delete(where:where), where&.values) end def drop db.execute("DROP TABLE #{table}") end private def make_db_dir FileUtils.mkdir_p(Dir_Path) unless Dir.exist?(Dir_Path) end def sql_make "CREATE TABLE IF NOT EXISTS #{table}(#{ cols.map{|col,type|"#{col} #{type}"}.join(", ") })" end def sql_select(cols:, where:, order:, limit:) "SELECT #{cols} FROM #{table}" + (where ? where_str(where) : "") + (order ? order_str(order) : "") + (limit ? " LIMIT #{limit}" : "") end def sql_insert(values:) <<~sql INSERT INTO #{table}(#{values.keys.join(", ")}) VALUES (#{Array.new(values.length, "?").join(", ")}) sql end def sql_update(values:, where:) <<~sql UPDATE #{table} SET #{placeholder(values.keys, ", ")} WHERE #{placeholder(where.keys)} sql end def sql_delete(where:) <<~sql DELETE FROM #{table} #{where ? where_str(where) : ""} sql end def where_str(where) " WHERE #{placeholder(where.keys)}" end def order_str(order) " ORDER BY #{order.keys .map{|k| "#{k} #{order[k]}"} .join(", ")}" end def placeholder(keys, glue=" AND ") keys.map{|k| "#{k} = ?"}.join(glue) end end class Delete def self.table(table) SQL.new(table:table).drop end def self.all File.delete(File_Path) end end class State < SQL include Chars attr_reader :date, :time, :chars, :n_done, :n_tot, :reveals, :done attr_accessor :reveals def initialize(date:Date.today) super(table:"states").make_table @date = date set end def cols { date: :DATE, time: :INT, chars: :TEXT, n_done: :INT, n_tot: :INT, reveals: :INT, done: :INT } end def exists? @exists || query.count > 0 end def save(game:) exists? ? save_existing(game) : save_new(game) end def delete super(where:{date:date.to_s}) @exists = false set end private def set @time,@chars,@n_done,@n_tot,@reveals,@done = exists? ? instantiate : blank end def instantiate [ query[0]["time"].to_i, parse_chars(query[0]["chars"]), query[0]["n_done"].to_i, query[0]["n_tot"].to_i, query[0]["reveals"].to_i, query[0]["done"].to_i == 1 ] end def blank [ 0, false, nil, nil, 0, false ] end def query @query || select(where:{date:date}) end def parse_chars(str) JSON.parse(str, symbolize_names:true) end def build(game:) { date: date.to_s, time: game.timer.time.to_i, chars: gen_chars(game), n_done: game.board.puzzle.n_clues_done, n_tot: game.board.puzzle.n_clues, reveals: reveals, done: game.board.puzzle.complete? ? 1 : 0 } end def gen_chars(game) JSON.generate(game.board.save_state) end def save_existing(game) update(where:{date:date.to_s}, values:build(game:game)) end def save_new(game) insert(values:build(game:game)) @exists = true end end class Stats < State def initialize(date:Date.today) super(date:date) end def stats_str (exists? ? exist_str : new_str).split("\n") end def exist_str <<~stats Time #{VL} #{Time.abs(time).to_s} Clues #{VL} #{n_done}/#{n_tot} Done #{VL} [#{done ? Tick : " "}] stats end def new_str "\n Not attempted\n" end end class Recents < SQL attr_reader :date def initialize super(table:"recents").make_table end def cols { date: :DATE, play_date: :DATE, play_time: :TIME } end def select_list select(cols:"*", order:{play_date:"DESC", play_time:"DESC"}, limit:10) end def add(date:) @date = date exists? ? add_existing : add_new end def exists? select(where:{date:date.to_s}).count > 0 end def add_new insert(values:build) end def add_existing update(values:build, where:{date:date.to_s}) end def build { date: date.to_s, play_date: Date.today.to_s, play_time: Time.now.strftime("%T") } end end class Scores < SQL def initialize super(table:"scores").make_table end def cols { date: :DATE, date_done: :DATE, time: :TEXT, reveals: :INT } end def add(game:) insert(values:build(game:game)) end def select_list select(cols:"*", where:{reveals:0}, order:{time:"ASC"}, limit:10) end def build(game:) { date:game.date.to_s, date_done:Date.today.to_s, time:game.timer.time.strftime("%T"), reveals:game.state.reveals } end end end end
ruby
MIT
db087adb776515dc73af13d096e2ce9a3b8dabab
2026-01-04T17:58:20.682312Z
false
zakird/wkhtmltopdf_binary_gem
https://github.com/zakird/wkhtmltopdf_binary_gem/blob/f54fc9988b9d4073ddf64e7463868e14ebc5bf5d/wkhtmltopdf-binary.rb
wkhtmltopdf-binary.rb
ruby
Apache-2.0
f54fc9988b9d4073ddf64e7463868e14ebc5bf5d
2026-01-04T17:14:44.364125Z
false
zakird/wkhtmltopdf_binary_gem
https://github.com/zakird/wkhtmltopdf_binary_gem/blob/f54fc9988b9d4073ddf64e7463868e14ebc5bf5d/test/test_with_docker.rb
test/test_with_docker.rb
require 'minitest/autorun' def macos? ENV['RUNNER_OS'] && ENV['RUNNER_OS'] == 'macOS' end def arm? ENV['ARM'] end class WithDockerTest < Minitest::Test SETUP = begin `docker-compose build --no-cache` if !macos? end def test_centos_6 test_on_x86 with: 'centos_6' end def test_centos_7 test_on_x86 with: 'centos_7' end def test_centos_8 test_on_x86 with: 'centos_8' end def test_debian_9 test_on_x86_and_arm with: 'debian_9' end def test_debian_10 test_on_x86_and_arm with: 'debian_10' end def test_debian_11 test_on_x86_and_arm with: 'debian_11' end def test_debian_12 test_on_x86_and_arm with: 'debian_12' end def test_debian_13 test_on_x86 with: 'debian_13' end def test_with_ubuntu_16 test_on_x86 with: 'ubuntu_16.04' end def test_with_ubuntu_18 test_on_x86 with: 'ubuntu_18.04' end def test_with_ubuntu_20 test_on_x86 with: 'ubuntu_20.04' end def test_with_ubuntu_22 test_on_x86_and_arm with: 'ubuntu_22.04' end def test_with_ubuntu_24 test_on_x86_and_arm with: 'ubuntu_24.04' end def test_with_archlinux test_on_x86 with: 'archlinux' end def test_rockylinux_8 test_on_x86 with: 'rockylinux_8' end def test_almalinux_8 test_on_x86 with: 'almalinux_8' end def test_with_macos assert_equal('wkhtmltopdf 0.12.6 (with patched qt)', `bin/wkhtmltopdf --version`.strip) if macos? end private def test_on_x86(with:) test_on_docker(with: with) if !macos? && !arm? end def test_on_x86_and_arm(with:) test_on_docker(with: with) unless macos? end def test_on_docker(with:) assert_match(/wkhtmltopdf 0\.12\.6(.1)? \(with patched qt\)/, `docker-compose run --rm #{with}`.strip) end end
ruby
Apache-2.0
f54fc9988b9d4073ddf64e7463868e14ebc5bf5d
2026-01-04T17:14:44.364125Z
false
zakird/wkhtmltopdf_binary_gem
https://github.com/zakird/wkhtmltopdf_binary_gem/blob/f54fc9988b9d4073ddf64e7463868e14ebc5bf5d/bin/wkhtmltopdf-binary.rb
bin/wkhtmltopdf-binary.rb
ruby
Apache-2.0
f54fc9988b9d4073ddf64e7463868e14ebc5bf5d
2026-01-04T17:14:44.364125Z
false
quzhi1/ChineseHistoricalSource
https://github.com/quzhi1/ChineseHistoricalSource/blob/067256781c674aea0deecf00f4c64a9927ca6309/ruby/es_feeder.rb
ruby/es_feeder.rb
# typed: strict # frozen_string_literal: true require 'concurrent-ruby' require 'elasticsearch' require 'io/console' require 'json' require 'sorbet-runtime' # Feed one history source class EsFeeder extend T::Sig URL = 'http://localhost:9200' sig { void } def initialize @client = T.let( Elasticsearch::Client.new( url: URL, log: false, user: 'elastic', password: 'changeme' ), Elasticsearch::Transport::Client ) end sig { params(json: T::Hash[String, String]).void } def feed_one(json) # puts "Feeding: #{json}" @client.create index: 'history_source', type: '_doc', body: json end sig { params(file_name: String).void } def run(file_name) puts "Processing #{file_name}" pool = Concurrent::FixedThreadPool.new(12) File.open(file_name, 'r') do |file| json_array = JSON.load(file) # rubocop:disable Security/JSONLoad json_array.each do |json| pool.post { feed_one(json) } end end pool.shutdown pool.wait_for_termination end sig { params(file_name: String).returns(Integer) } def doc_count(file_name) File.open(file_name, 'r') do |file| JSON.load(file).size # rubocop:disable Security/JSONLoad end end sig { params(source: String).void } def delete_source(source) @client.delete_by_query( index: 'history_source', body: { query: { bool: { must: [ { match: { source: source } } ] } } } ) end sig { void } def delete_all @client.delete_by_query( index: 'history_source', body: { query: { match_all: {} } } ) end sig { params(source: String).returns(Integer) } def count_by_source(source) res = @client.count( index: 'history_source', body: { query: { bool: { must: [ { match_phrase: { 'source.keyword' => { query: source } } } ] } } } ) res['count'] end sig { void } def ingest_all Dir['json/*.json'].each { |file_name| EsFeeder.new.run(file_name) } end sig { void } def post_run_test Dir['json/*.json'].each do |file_name| source = file_name.sub('json/', '').sub('.json', '') local_count = doc_count(file_name) es_count = count_by_source(source) if es_count != local_count raise "#{source} ingestion incomplete. "\ "Expected: #{local_count}. Actual: #{es_count}" else puts "#{source} ingestion is sucessful" end end end end es_feeder = EsFeeder.new # Ingest one source # es_feeder.run('json/宋史.json') # Ingest all sources es_feeder.ingest_all # Count local doc and elasticsearch doc # puts es_feeder.doc_count('json/旧五代史.json') # puts es_feeder.count_by_source('旧五代史') # Delete one souce # puts es_feeder.delete_source('宋史') # Delete all sources # puts es_feeder.delete_all # Test if any document missing es_feeder.post_run_test
ruby
MIT
067256781c674aea0deecf00f4c64a9927ca6309
2026-01-04T17:55:59.280757Z
false
quzhi1/ChineseHistoricalSource
https://github.com/quzhi1/ChineseHistoricalSource/blob/067256781c674aea0deecf00f4c64a9927ca6309/ruby/html_parser.rb
ruby/html_parser.rb
# typed: strict # frozen_string_literal: true require 'json' require 'pry' module HtmlParser extend T::Sig sig do params( source_page: Nokogiri::HTML::Document, count: Integer, ) .returns(String) end def get_book_name(source_page, count) chapter_name_xpath = '/html/body/div[3]/div[3]/article/ul/li[%<count>s]/span[2]/a/@data-title' .format(count: count) source_page.xpath(chapter_name_xpath).text.strip end sig do params( source_page: Nokogiri::HTML::Document, count: Integer, ) .returns(String) end def get_book_url(source_page, count) chapter_name_xpath = '/html/body/div[3]/div[3]/article/ul/li[%<count>s]/span[2]/a/@href' .format(count: count) source_page.xpath(chapter_name_xpath).text.strip end sig do params( source_page: Nokogiri::HTML::Document, count: Integer, ) .returns(String) end def get_translation_url(source_page, count) chapter_name_xpath = '/html/body/div[3]/div[3]/article/ul/li[%<count>s]/span[3]/a/@href' .format(count: count) source_page.xpath(chapter_name_xpath).text.strip end sig do params( source_page: Nokogiri::HTML::Document, count: Integer, ) .returns(String) end def get_chapter_name(source_page, count) chapter_name_xpath = '/html/body/div[3]/div[3]/ul/li[%<count>s]/a' .format(count: count) source_page.xpath(chapter_name_xpath).text.strip end sig do params( source_page: Nokogiri::HTML::Document, count: Integer, ) .returns(String) end def get_chapter_url(source_page, count) chapter_url_xpath = '/html/body/div[3]/div[3]/ul/li[%<count>s]/a/@href' .format(count: count) source_page.xpath(chapter_url_xpath).text.strip end end
ruby
MIT
067256781c674aea0deecf00f4c64a9927ca6309
2026-01-04T17:55:59.280757Z
false
quzhi1/ChineseHistoricalSource
https://github.com/quzhi1/ChineseHistoricalSource/blob/067256781c674aea0deecf00f4c64a9927ca6309/ruby/chapter_crawler.rb
ruby/chapter_crawler.rb
# typed: strict # frozen_string_literal: true require 'open-uri' require 'nokogiri' require 'powerpack' require 'sorbet-runtime' require_relative './html_parser.rb' # Simple web crawler for this project class ChapterCrawler extend T::Sig include HtmlParser ROOT_URL = 'https://duguoxue.com/ershisishi' sig { void } def run book_list = get_book_list book_list.each do |book_hash| json_array = process_source( book_hash[:book_name], book_hash[:book_url], book_hash[:translation_url] ) # puts json_array File.open("json/#{book_hash[:book_name]}.json", 'w') do |json_output| json_output.write(JSON.pretty_generate(json_array)) end end end sig do params( source: String, book_url: String, translation_url: String ) .returns( T::Array[ { 'source' => String, 'chapter' => String, 'text' => String, 'chapter_url' => String, 'chapter_translation' => String } ] ) end def process_source(source, book_url, translation_url) puts "Processing #{source}" # Translation hash: {'五帝本纪' => 'https://duguoxue.com/ershisishi/2692.html', ...} translation_hash = get_translation_hash(translation_url) source_page = Nokogiri::HTML(URI.parse(book_url).open) json_array = [] count = 1 loop do chapter_name = get_chapter_name(source_page, count) chapter_url = get_chapter_url(source_page, count) # Sometimes the translation title is 五帝本纪, but the title is 卷一·五帝本纪第一 # We need to run substring check translation_pair = translation_hash.find { |key, _| chapter_name.include?(key) } break if chapter_url.empty? || chapter_name.empty? if translation_pair chapter_translation = translation_pair[1] else puts "No translation found for chapter #{{ source: source, chapter_name: chapter_name }}" chapter_translation = translation_url end process_chapter(source, chapter_url, chapter_name, chapter_translation, json_array) count += 1 end json_array end sig do returns( T::Array[ { book_name: String, book_url: String, translation_url: String } ] ) end def get_book_list source_page = Nokogiri::HTML(URI.parse(ROOT_URL).open) count = 2 json_array = [] loop do book_name = get_book_name(source_page, count) book_url = get_book_url(source_page, count) translation_url = get_translation_url(source_page, count) break if book_name.empty? || book_url.empty? json_array << { book_name: book_name, book_url: book_url, translation_url: translation_url } count += 1 end json_array end # Translation hash: {'五帝本纪' => 'https://duguoxue.com/ershisishi/2692.html'} sig do params(translation_url: String) .returns(T::Hash[String, String]) end def get_translation_hash(translation_url) puts "Looking up translation #{translation_url}" count = 1 source_page = Nokogiri::HTML(URI.parse(translation_url).open) translation_hash = {} loop do chapter_name_xpath = '/html/body/div[3]/div[3]/ul/li[%<count>s]/a/text()' .format(count: count) chapter_translation_xpath = '/html/body/div[3]/div[3]/ul/li[%<count>s]/a/@href' .format(count: count) chapter_name = source_page.xpath(chapter_name_xpath).text.strip chapter_translation_url = source_page.xpath(chapter_translation_xpath).text.strip break if chapter_name.empty? || chapter_translation_url.empty? translation_hash[chapter_name] = chapter_translation_url count += 1 end translation_hash end sig do params( source: String, chapter_url: String, chapter_name: String, chapter_translation: String, json_array: T::Array[{ 'source' => String, 'chapter' => String, 'text' => String, 'chapter_url' => String, 'chapter_translation' => String }] ) .returns(T.untyped) end def process_chapter(source, chapter_url, chapter_name, chapter_translation, json_array) page = Nokogiri::HTML(open(chapter_url)) # rubocop:disable Security/Open # chapter = fetch_chapter_name(page) puts "\tProcessing chapter #{chapter_name}" count = 1 loop do para_xpath = '/html/body/div[3]/div[3]/p[%<para>s]/text()' .format(para: count) para = page.xpath(para_xpath).text.strip break if para.empty? # puts "\t\t#{para}" json_array << { 'source' => source, 'chapter' => chapter_name, 'text' => para, 'chapter_url' => chapter_url, 'translation' => chapter_translation } count += 1 end end end ChapterCrawler.new.run
ruby
MIT
067256781c674aea0deecf00f4c64a9927ca6309
2026-01-04T17:55:59.280757Z
false
AndyObtiva/glimmer-dsl-swt
https://github.com/AndyObtiva/glimmer-dsl-swt/blob/449cf07ada1ec965ae2ac91715ccdf22488df4ca/samples/hello/hello_c_combo.rb
samples/hello/hello_c_combo.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' # This is a sample for the c_combo widget, a more customizable version of combo class HelloCCombo class Person attr_accessor :country, :country_options def initialize self.country_options = ['', 'Canada', 'US', 'Mexico'] reset_country! end def reset_country! self.country = 'Canada' end end include Glimmer::UI::CustomShell before_body do @person = Person.new end body { shell { row_layout(:vertical) { fill true } text 'Hello, C Combo!' c_combo(:read_only) { selection <=> [@person, :country] # also binds to country_options by convention font height: 45 # unlike `combo`, `c_combo` changes height when setting the font height } button { text 'Reset Selection' on_widget_selected do @person.reset_country! end } } } end HelloCCombo.launch
ruby
MIT
449cf07ada1ec965ae2ac91715ccdf22488df4ca
2026-01-04T17:52:38.125591Z
false
AndyObtiva/glimmer-dsl-swt
https://github.com/AndyObtiva/glimmer-dsl-swt/blob/449cf07ada1ec965ae2ac91715ccdf22488df4ca/samples/hello/hello_arrow.rb
samples/hello/hello_arrow.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' include Glimmer shell { row_layout(:vertical) { fill true center true } text 'Hello, Arrow!' label(:center) { text 'Click the arrow to get a menu.' } arrow { # can be customized by passing `:arrow` SWT style + `:left`, `:right`, `:up`, or `:down` (default) menu { menu_item { text 'Item &1' on_widget_selected do message_box { text 'Item 1' message 'Item 1 selected!' }.open end } menu_item { text 'Item &2' on_widget_selected do message_box { text 'Item 2' message 'Item 2 selected!' }.open end } } on_widget_selected do |event| event.widget.menu.visible = true end } }.open
ruby
MIT
449cf07ada1ec965ae2ac91715ccdf22488df4ca
2026-01-04T17:52:38.125591Z
false
AndyObtiva/glimmer-dsl-swt
https://github.com/AndyObtiva/glimmer-dsl-swt/blob/449cf07ada1ec965ae2ac91715ccdf22488df4ca/samples/hello/hello_canvas_path.rb
samples/hello/hello_canvas_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-dsl-swt' class HelloCanvasPath include Glimmer::UI::Application after_body do regenerate end body { shell { grid_layout { margin_width 0 margin_height 0 margin_top 5 } text 'Hello, Canvas Path!' minimum_size 800, 700 @button = button { layout_data :center, :center, true, false text 'Regenerate' enabled false on_widget_selected do regenerate end } canvas { layout_data :fill, :fill, true, true background :white text('line', 15, 200) { foreground :red } @path1 = path { antialias :on foreground :red } text('quad', 15, 300) { foreground :dark_green } @path2 = path { antialias :on foreground :dark_green } text('cubic', 15, 400) { foreground :blue } @path3 = path { antialias :on foreground :blue } } on_widget_disposed do # safe to kill thread as data is in memory only, so no risk of data loss @thread.kill end } } def regenerate @thread = Thread.new do @button.enabled = false @path1.clear @path2.clear @path3.clear y1 = y2 = y3 = 300 700.times.each do |x| x += 55 x1 = x - 2 x2 = x - 1 x3 = x y1 = y3 y2 = y1 y3 = [[y3 + (rand*24 - 12), 0].max, 700].min @path1.content { line(x1, y1 - 100) } if x % 2 == 0 @path2.content { quad(x1, y1, x2, y2) } end if x % 3 == 0 @path3.content { cubic(x1, y1 + 100, x2, y2 + 100, x3, y3 + 100) } end sleep(0.01) end @button.enabled = true end end end HelloCanvasPath.launch
ruby
MIT
449cf07ada1ec965ae2ac91715ccdf22488df4ca
2026-01-04T17:52:38.125591Z
false
AndyObtiva/glimmer-dsl-swt
https://github.com/AndyObtiva/glimmer-dsl-swt/blob/449cf07ada1ec965ae2ac91715ccdf22488df4ca/samples/hello/hello_color_dialog.rb
samples/hello/hello_color_dialog.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' class HelloColorDialog include Glimmer::UI::CustomShell attr_accessor :selected_color before_body do self.selected_color = :black end body { shell { minimum_size 220, 0 grid_layout text 'Hello, Color Dialog!' label { layout_data :center, :center, true, false text 'Selected Color:' font height: 14, style: :bold } canvas(:border) { layout_data :center, :center, true, false background <=> [self, :selected_color] on_mouse_up do self.selected_color = color_dialog.open end } button { layout_data :center, :center, true, false text "Choose Color..." on_widget_selected do self.selected_color = color_dialog.open end } } } end HelloColorDialog.launch
ruby
MIT
449cf07ada1ec965ae2ac91715ccdf22488df4ca
2026-01-04T17:52:38.125591Z
false
AndyObtiva/glimmer-dsl-swt
https://github.com/AndyObtiva/glimmer-dsl-swt/blob/449cf07ada1ec965ae2ac91715ccdf22488df4ca/samples/hello/hello_date_time.rb
samples/hello/hello_date_time.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' class HelloDateTime class Person attr_accessor :date_of_birth end include Glimmer::UI::CustomShell before_body do @person = Person.new @person.date_of_birth = DateTime.new(2013, 7, 12, 18, 37, 23) end body { shell { row_layout :vertical text 'Hello, Date Time!' minimum_size 180, 180 label { text 'Date of Birth' font height: 16, style: :bold } date { # alias for date_time(:date) date_time <=> [@person, :date_of_birth] } date_drop_down { # alias for date_time(:date, :drop_down) date_time <=> [@person, :date_of_birth] } time { # alias for date_time(:time) date_time <=> [@person, :date_of_birth] } calendar { # alias for date_time(:calendar) date_time <=> [@person, :date_of_birth] } } } end HelloDateTime.launch
ruby
MIT
449cf07ada1ec965ae2ac91715ccdf22488df4ca
2026-01-04T17:52:38.125591Z
false
AndyObtiva/glimmer-dsl-swt
https://github.com/AndyObtiva/glimmer-dsl-swt/blob/449cf07ada1ec965ae2ac91715ccdf22488df4ca/samples/hello/hello_custom_widget.rb
samples/hello/hello_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-dsl-swt' # This class declares a `greeting_label` custom widget (by convention) class GreetingLabel include Glimmer::UI::CustomWidget # multiple options without default values options :name, :colors # single option with default value option :greeting, default: 'Hello' # internal attribute (not a custom widget option) attr_accessor :label_color def can_handle_observation_request?(event, &block) event.to_s == 'on_color_changed' || super end def handle_observation_request(event, &block) if event.to_s == 'on_color_changed' @color_changed_handlers ||= [] @color_changed_handlers << block else super end end before_body do @font = {height: 24, style: :bold} @label_color = :black end after_body do return if colors.nil? @thread = Thread.new do colors.cycle do |color| self.label_color = color @color_changed_handlers&.each {|handler| handler.call(color)} sleep(1) end end end body { # pass received swt style symbols through to label to customize (e.g. :center to center text) label(*swt_style_symbols) { text "#{greeting}, #{name}!" font @font foreground <=> [self, :label_color] on_widget_disposed do @thread&.kill # safe since it does not involve data end } } end # including Glimmer enables the Glimmer DSL syntax, including auto-discovery of the `greeting_label` custom widget include Glimmer shell { fill_layout :vertical minimum_size 215, 215 text 'Hello, Custom Widget!' # custom widget options are passed in a hash greeting_label(name: 'Sean') # pass :center SWT style followed by custom widget options hash greeting_label(:center, name: 'Laura', greeting: 'Aloha') # greeting_label(:right, name: 'Rick') { # you can nest attributes under custom widgets just like any standard widget foreground :red } # the colors option cycles between colors for the label foreground every second greeting_label(:center, name: 'Mary', greeting: 'Aloha', colors: [:red, :dark_green, :blue]) { on_color_changed do |color| puts "Label color changed: #{color}" end } }.open
ruby
MIT
449cf07ada1ec965ae2ac91715ccdf22488df4ca
2026-01-04T17:52:38.125591Z
false
AndyObtiva/glimmer-dsl-swt
https://github.com/AndyObtiva/glimmer-dsl-swt/blob/449cf07ada1ec965ae2ac91715ccdf22488df4ca/samples/hello/hello_layout.rb
samples/hello/hello_layout.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' class HelloLayout include Glimmer::UI::CustomShell body { shell { # shell (which is a composite) has fill_layout(:horizontal) by default with no margins text 'Hello, Layout!' tab_folder { # every tab item has its own composite, which can set a layout tab_item { text 'Fill Layout (horizontal)' fill_layout(:horizontal) { margin_width 30 margin_height 40 spacing 5 } 10.times { |n| label { text "<label #{n+1}>" } } } tab_item { text 'Fill Layout (vertical)' fill_layout { type :vertical # alternative way of specifying orientation margin_width 40 margin_height 30 spacing 10 } 10.times { |n| label(:center) { text "<label #{n+1}>" } } } tab_item { text 'Row Layout (horizontal)' row_layout(:horizontal) { # row layout has margin attributes for top, left, right, and bottom # in addition to width and height (and sets margin_width and margin_height to 5 by default) margin_top 40 margin_left 30 spacing 5 wrap false center true justify true } 10.times { |n| label { text "<label #{n+1}>" } } } tab_item { text 'Row Layout (wrap on shrink)' row_layout { # :horizontal is the default type margin_height 40 margin_width 30 spacing 35 # wrap true # is the default } 10.times { |n| label { text "<label #{n+1}>" } } } tab_item { text 'Row Layout (vertical)' background :yellow row_layout(:vertical) { |l| margin_height 0 margin_width 0 spacing 10 fill true # fills horizontally to match the widest child (opposite to row layout orientation) center false # enable and disable fill to see what this does } 10.times { |n| label { # layout_data allows a widget to tweak its layout configuration (generating RowData object for RowLayout) layout_data { height 30 # width unspecified yet calculated } text "<this is a ver#{'r'*(rand*200).to_i}y wide label #{n+1}>" background :green } } } tab_item { text 'Grid Layout' grid_layout { num_columns 5 make_columns_equal_width true horizontal_spacing 15 vertical_spacing 10 # grid layout has margin attributes for top, left, right, and bottom # in addition to width and height (and sets margin_width and margin_height to 5 by default) margin_height 0 margin_top 20 } 10.times { |n| label { text "<this label is wide enough to fill #{n+1}>" background :white } } label { # layout_data allows a widget to tweak its layout configuration (generating GridData object for GridLayout) layout_data { width_hint 120 height_hint 40 } text "<this label is clipped>" background :cyan } label { # layout_data allows a widget to tweak its layout configuration (generating GridData object for GridLayout) layout_data { horizontal_span 2 } text "<this label spans two columns, so it can contain more text than normal>" background :green } label { # layout_data allows a widget to tweak its layout configuration (generating GridData object for GridLayout) layout_data { vertical_span 2 vertical_alignment :fill } text "<this label spans two rows, \nso it can contain new lines\n1\n2\n3\n4\n5\n6\n7>" background :yellow } 5.times { label } # just filler label { # layout_data allows a widget to tweak its layout configuration (generating GridData object for GridLayout) layout_data { horizontal_span 5 horizontal_alignment :fill # could be :beginning, :center or :end too vertical_alignment :fill # could be :beginning, :center, or :end too grab_excess_horizontal_space true grab_excess_vertical_space true } # this is a short alternative for specifying what is above # layout_data(:fill, :fill, true, true) { # horizontal_span 5 # } text "<this label fills all the space it can get\nhorizontally and vertically>" background :magenta } } tab_item { text 'Grid Layout (non-equal columns)' grid_layout(2, false) # alt syntax: (numColumns, make_columns_equal_width) 10.times { |n| label { text "Field #{n+1}" } text { layout_data { width_hint 600 } text "Please enter text" } } } } } } end HelloLayout.launch
ruby
MIT
449cf07ada1ec965ae2ac91715ccdf22488df4ca
2026-01-04T17:52:38.125591Z
false
AndyObtiva/glimmer-dsl-swt
https://github.com/AndyObtiva/glimmer-dsl-swt/blob/449cf07ada1ec965ae2ac91715ccdf22488df4ca/samples/hello/hello_list_single_selection.rb
samples/hello/hello_list_single_selection.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' class HelloListSingleSelection class Person attr_accessor :country, :country_options def initialize self.country_options = ['', 'Canada', 'US', 'Mexico'] reset_country! end def reset_country! self.country = 'Canada' end end include Glimmer::UI::CustomShell before_body do @person = Person.new end body { shell { grid_layout text 'Hello, List Single Selection!' list { selection <=> [@person, :country] # also binds to country_options by convention } button { text 'Reset Selection To Default Value' on_widget_selected do @person.reset_country! end } } } end HelloListSingleSelection.launch
ruby
MIT
449cf07ada1ec965ae2ac91715ccdf22488df4ca
2026-01-04T17:52:38.125591Z
false
AndyObtiva/glimmer-dsl-swt
https://github.com/AndyObtiva/glimmer-dsl-swt/blob/449cf07ada1ec965ae2ac91715ccdf22488df4ca/samples/hello/hello_file_dialog.rb
samples/hello/hello_file_dialog.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' class HelloFileDialog include Glimmer::UI::CustomShell attr_accessor :selected_file before_body do @selected_file = 'Please select a file.' end body { shell { minimum_size 400, 0 grid_layout text 'Hello, File Dialog!' label { text 'Selected File:' font height: 14, style: :bold } label { layout_data :fill, :center, true, false text <=> [self, :selected_file] font height: 14 } button { text "Browse..." on_widget_selected do self.selected_file = file_dialog.open end } } } end HelloFileDialog.launch
ruby
MIT
449cf07ada1ec965ae2ac91715ccdf22488df4ca
2026-01-04T17:52:38.125591Z
false
AndyObtiva/glimmer-dsl-swt
https://github.com/AndyObtiva/glimmer-dsl-swt/blob/449cf07ada1ec965ae2ac91715ccdf22488df4ca/samples/hello/hello_print_dialog.rb
samples/hello/hello_print_dialog.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' class HelloPrintDialog include Glimmer::UI::CustomShell body { shell { text 'Hello, Print Dialog!' @composite = composite { row_layout(:vertical) { fill true center true } label(:center) { text "Whatever you see inside the app composite\nwill get printed when clicking the Print button." font height: 16 } button { text 'Print' on_widget_selected do # note: you may check out Hello, Print! for a simpler version that automates the work below image = Image.new(display.swt_display, @composite.bounds) gc = org.eclipse.swt.graphics.GC.new(image) success = @composite.print(gc) if success printer_data = print_dialog.open if printer_data printer = Printer.new(printer_data) if printer.start_job('Glimmer') printer_gc = org.eclipse.swt.graphics.GC.new(printer) if printer.start_page printer_gc.drawImage(image, 0, 0) printer.end_page else message_box { text 'Unable To Print' message 'Sorry! Cannot start printer page!' }.open end printer_gc.dispose printer.end_job else message_box { text 'Unable To Print' message 'Sorry! Cannot start printer job!' }.open end printer.dispose gc.dispose image.dispose end else message_box { text 'Unable To Print' message 'Sorry! Printing is not supported on this platform!' }.open end end } } } } end HelloPrintDialog.launch
ruby
MIT
449cf07ada1ec965ae2ac91715ccdf22488df4ca
2026-01-04T17:52:38.125591Z
false
AndyObtiva/glimmer-dsl-swt
https://github.com/AndyObtiva/glimmer-dsl-swt/blob/449cf07ada1ec965ae2ac91715ccdf22488df4ca/samples/hello/hello_refined_table.rb
samples/hello/hello_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-dsl-swt' require 'date' class HelloRefinedTable BaseballTeam = Struct.new(:name, :town, :ballpark, keyword_init: true) do class << self def all @all ||= [ {town: 'Chicago', name: 'White Sox', ballpark: 'Guaranteed Rate Field'}, {town: 'Cleveland', name: 'Indians', ballpark: 'Progressive Field'}, {town: 'Detroit', name: 'Tigers', ballpark: 'Comerica Park'}, {town: 'Kansas City', name: 'Royals', ballpark: 'Kauffman Stadium'}, {town: 'Minnesota', name: 'Twins', ballpark: 'Target Field'}, {town: 'Baltimore', name: 'Orioles', ballpark: 'Oriole Park at Camden Yards'}, {town: 'Boston', name: 'Red Sox', ballpark: 'Fenway Park'}, {town: 'New York', name: 'Yankees', ballpark: 'Comerica Park'}, {town: 'Tampa Bay', name: 'Rays', ballpark: 'Tropicana Field'}, {town: 'Toronto', name: 'Blue Jays', ballpark: 'Rogers Centre'}, {town: 'Houston', name: 'Astros', ballpark: 'Minute Maid Park'}, {town: 'Los Angeles', name: 'Angels', ballpark: 'Angel Stadium'}, {town: 'Oakland', name: 'Athletics', ballpark: 'RingCentral Coliseum'}, {town: 'Seattle', name: 'Mariners', ballpark: 'T-Mobile Park'}, {town: 'Texas', name: 'Rangers', ballpark: 'Globe Life Field'}, {town: 'Chicago', name: 'Cubs', ballpark: 'Wrigley Field'}, {town: 'Cincinnati', name: 'Reds', ballpark: 'Great American Ball Park'}, {town: 'Milwaukee', name: 'Brewers', ballpark: 'American Family Field'}, {town: 'Pittsburgh', name: 'Pirates', ballpark: 'PNC Park'}, {town: 'St. Louis', name: 'Cardinals', ballpark: 'Busch Stadium'}, {town: 'Atlanta', name: 'Braves', ballpark: 'Truist Park'}, {town: 'Miami', name: 'Marlins', ballpark: 'LoanDepot Park'}, {town: 'New York', name: 'Mets', ballpark: 'Citi Field'}, {town: 'Philadelphia', name: 'Phillies', ballpark: 'Citizens Bank Park'}, {town: 'Washington', name: 'Nationals', ballpark: 'Nationals Park'}, {town: 'Arizona', name: 'Diamondbacks', ballpark: 'Chase Field'}, {town: 'Colorado', name: 'Rockies', ballpark: 'Coors Field'}, {town: 'Los Angeles', name: 'Dodgers', ballpark: 'Dodger Stadium'}, {town: 'San Diego', name: 'Padres', ballpark: 'Petco Park'}, {town: 'San Francisco', name: 'Giants', ballpark: 'Oracle Park'}, ].map {|team_kwargs| new(team_kwargs)} end def all_team_names @all_team_names ||= BaseballTeam.all.map {|t| t[:name]} end end def complete_name "#{town} #{name}" end end BaseballGame = Struct.new(:date, :home_team, :away_team, keyword_init: true) do def home_team_name home_team.complete_name end def home_team_name=(new_name) new_home_team = BaseballTeam.all.find {|t| t[:name] == new_name} self.home_team = new_home_team if new_home_team end def home_team_name_options BaseballTeam.all_team_names end def away_team_name away_team.complete_name end def away_team_name=(new_name) new_away_team = BaseballTeam.all.find {|t| t[:name] == new_name} self.away_team = new_away_team if new_away_team end def away_team_name_options BaseballTeam.all_team_names end def ballpark home_team.ballpark end def date=(new_date) self['date'] = new_date.respond_to?(:to_date) ? new_date.to_date : new_date end def to_s "#{home_team_name} vs #{away_team_name} at #{ballpark}" end end BaseballSeason = Struct.new(:year) do attr_accessor :selected_game attr_writer :games def games if @games.nil? @games = [] baseball_team_combinations = BaseballTeam.all.combination(2).to_a current_day = first_day day_offset = 0 begin if (day_offset % 7 != 6) day_games = [] half_teams_count = BaseballTeam.all.count / 2 while day_games.uniq.count < half_teams_count baseball_team_pair = baseball_team_combinations.sample teams_played_so_far = day_games.map {|game| [game.home_team, game.away_team]}.flatten unless teams_played_so_far.include?(baseball_team_pair.first) || teams_played_so_far.include?(baseball_team_pair.last) baseball_game = BaseballGame.new( date: current_day, home_team: baseball_team_pair.first, away_team: baseball_team_pair.last, ) day_games << baseball_game @games << baseball_game end end end day_offset += 1 current_day += 1 end while current_day != first_day_of_playoffs end @games end def first_day @first_day ||= Date.new(year, 04, 01) end def first_day_of_playoffs @last_day ||= Date.new(year, 10, 01) end end include Glimmer::UI::Application before_body do @baseball_season = BaseballSeason.new(Time.now.year) end body { shell { text 'Hello, Refined Table!' refined_table(:editable, :border, per_page: 20) { # also `page: 1` by default table_column { width 100 text 'Date' editor :date_drop_down } table_column { width 200 text 'Ballpark' editor :none } table_column { width 150 text 'Home Team' editor :combo, :read_only # read_only is simply an SWT style passed to combo widget } table_column { width 150 text 'Away Team' editor :combo, :read_only # read_only is simply an SWT style passed to combo widget } menu { menu_item { text 'Book' on_widget_selected do message_box { text 'Game Booked!' message "The game \"#{@baseball_season.selected_game}\" has been booked!" }.open end } } model_array <=> [@baseball_season, :games, column_attributes: {'Home Team' => :home_team_name, 'Away Team' => :away_team_name}] selection <=> [@baseball_season, :selected_game] } } } end HelloRefinedTable.launch
ruby
MIT
449cf07ada1ec965ae2ac91715ccdf22488df4ca
2026-01-04T17:52:38.125591Z
false
AndyObtiva/glimmer-dsl-swt
https://github.com/AndyObtiva/glimmer-dsl-swt/blob/449cf07ada1ec965ae2ac91715ccdf22488df4ca/samples/hello/hello_link.rb
samples/hello/hello_link.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' class HelloLink include Glimmer::UI::CustomShell body { shell { |main_shell| grid_layout { margin_width 20 margin_height 10 } background :white text 'Hello, Link!' @link = link { background :white link_foreground :dark_green font height: 16 text <<~MULTI_LINE_STRING You may click on any <a>link</a> to get help. How do you know <a href="which-link-href-value">which link</a> you clicked? Just keep clicking <a href="all links">links</a> to find out! MULTI_LINE_STRING on_widget_selected do |selection_event| # This retrieves the clicked link href (or contained text if no href is set) @selected_link = selection_event.text end on_mouse_up do |mouse_event| unless @selected_link.nil? @help_shell.close unless @help_shell.nil? || @help_shell.disposed? @help_shell = shell(:no_trim) { grid_layout { margin_width 10 margin_height 10 } background :yellow label { background :yellow text "Did someone ask for help about \"#{@selected_link}\"?\nYou don't really need help. You did it!" } on_swt_show { x = main_shell.location.x + @link.location.x + mouse_event.x y = main_shell.location.y + @link.location.y + mouse_event.y + 20 @help_shell.location = Point.new(x, y) } on_focus_lost { @selected_link = nil @help_shell.close } } @help_shell.open end end } } } end HelloLink.launch
ruby
MIT
449cf07ada1ec965ae2ac91715ccdf22488df4ca
2026-01-04T17:52:38.125591Z
false
AndyObtiva/glimmer-dsl-swt
https://github.com/AndyObtiva/glimmer-dsl-swt/blob/449cf07ada1ec965ae2ac91715ccdf22488df4ca/samples/hello/hello_cool_bar.rb
samples/hello/hello_cool_bar.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' class HelloCoolBar include Glimmer::UI::CustomShell attr_accessor :operation, :font_size def font_size_options (10..30).to_a.map(&:to_s) end before_body do self.font_size = '30' end body { shell { fill_layout(:vertical) { margin_width 0 margin_height 0 } text 'Hello, Cool Bar!' minimum_size 280, 50 cool_bar { # optionally takes a :flat style and/or :vertical style if you need vertical layout tool_bar { tool_item { image File.expand_path('./images/cut.png', __dir__), height: 16 on_widget_selected do self.operation = 'Cut' end } tool_item { image File.expand_path('./images/copy.png', __dir__), height: 16 on_widget_selected do self.operation = 'Copy' end } tool_item { image File.expand_path('./images/paste.png', __dir__), height: 16 on_widget_selected do self.operation = 'Paste' end } } tool_bar { tool_item { text 'Font Size' } # a combo can be nested in a tool_bar (it auto-generates a tool_item for itself behind the scenes) combo { selection <=> [self, :font_size] } } } label { font <= [self, :font_size, on_read: ->(size) { {height: size.to_i} }] text <= [self, :operation] text <= [self, :font_size] } } } end HelloCoolBar.launch
ruby
MIT
449cf07ada1ec965ae2ac91715ccdf22488df4ca
2026-01-04T17:52:38.125591Z
false
AndyObtiva/glimmer-dsl-swt
https://github.com/AndyObtiva/glimmer-dsl-swt/blob/449cf07ada1ec965ae2ac91715ccdf22488df4ca/samples/hello/hello_progress_bar.rb
samples/hello/hello_progress_bar.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' class HelloProgressBar include Glimmer::UI::CustomShell class ProgressModel attr_accessor :minimum, :maximum, :selection, :delay end before_body do @progress_model = ProgressModel.new @progress_model.minimum = 0 @progress_model.maximum = 100 @progress_model.selection = 0 @progress_model.delay = 0.01 end body { shell { grid_layout(4, true) text 'Hello, Progress Bar!' progress_bar(:indeterminate) { layout_data(:fill, :center, true, false) { horizontal_span 4 } } label { text 'Minimum' } label { text 'Maximum' } label { text 'Selection' } label { text 'Delay in Seconds' } spinner { selection <=> [@progress_model, :minimum] } spinner { selection <=> [@progress_model, :maximum] } spinner { selection <=> [@progress_model, :selection] } spinner { digits 2 minimum 1 maximum 200 selection <=> [@progress_model, :delay, on_read: ->(v) {v.to_f*100.0}, on_write: ->(v) {v.to_f/100.0}] } progress_bar { layout_data(:fill, :center, true, false) { horizontal_span 4 } minimum <= [@progress_model, :minimum] maximum <= [@progress_model, :maximum] selection <= [@progress_model, :selection] } progress_bar(:vertical) { layout_data(:fill, :center, true, false) { horizontal_span 4 } minimum <= [@progress_model, :minimum] maximum <= [@progress_model, :maximum] selection <= [@progress_model, :selection] } button { layout_data(:fill, :center, true, false) { horizontal_span 4 } text "Start" on_widget_selected do # if a previous thread is running, then kill first # (killing is not dangerous since it is only a thread about updating progress) @current_thread&.kill @current_thread = Thread.new do @progress_model.selection = @progress_model.minimum (@progress_model.minimum..@progress_model.maximum).to_a.each do |n| @progress_model.selection = n sleep(@progress_model.delay) end end end } } } end HelloProgressBar.launch
ruby
MIT
449cf07ada1ec965ae2ac91715ccdf22488df4ca
2026-01-04T17:52:38.125591Z
false
AndyObtiva/glimmer-dsl-swt
https://github.com/AndyObtiva/glimmer-dsl-swt/blob/449cf07ada1ec965ae2ac91715ccdf22488df4ca/samples/hello/hello_list_multi_selection.rb
samples/hello/hello_list_multi_selection.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' class HelloListMultiSelection class Person attr_accessor :provinces, :provinces_options def initialize self.provinces_options = [ '', 'Alberta', 'British Columbia', 'Manitoba', 'New Brunswick', 'Newfoundland and Labrador', 'Northwest Territories', 'Nova Scotia', 'Nunavut', 'Ontario', 'Prince Edward Island', 'Quebec', 'Saskatchewan', 'Yukon' ] reset_provinces! end def reset_provinces! self.provinces = ['Quebec', 'Manitoba', 'Alberta'] end end include Glimmer::UI::CustomShell before_body do @person = Person.new end body { shell { grid_layout text 'Hello, List Multi Selection!' list(:multi, :border) { selection <=> [@person, :provinces] # also binds to provinces_options by convention } button { text 'Reset Selections To Default Values' on_widget_selected do @person.reset_provinces! end } } } end HelloListMultiSelection.launch
ruby
MIT
449cf07ada1ec965ae2ac91715ccdf22488df4ca
2026-01-04T17:52:38.125591Z
false
AndyObtiva/glimmer-dsl-swt
https://github.com/AndyObtiva/glimmer-dsl-swt/blob/449cf07ada1ec965ae2ac91715ccdf22488df4ca/samples/hello/hello_expand_bar.rb
samples/hello/hello_expand_bar.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' class HelloExpandBar include Glimmer::UI::CustomShell body { shell { grid_layout(1, false) { margin_width 0 margin_height 0 } minimum_size 320, 240 text 'Hello, Expand Bar!' @status_label = label(:center) { text ' ' layout_data :fill, :center, true, false font height: 24 } expand_bar { layout_data :fill, :fill, true, true expand_item { text 'Productivity' button { text 'Word Processing' } button { text 'Spreadsheets' } button { text 'Presentations' } button { text 'Database' } composite # just filler } expand_item { text 'Tools' button { text 'Calculator' } button { text 'Unit Converter' } button { text 'Currency Converter' } button { text 'Scientific Calculator' } composite # just filler } expand_item { text 'Reading' button { text 'eBooks' } button { text 'News' } button { text 'Blogs' } button { text 'Papers' } composite # just filler } on_item_expanded do |expand_event| @status_label.text = "#{expand_event.item.text} Expanded!" end on_item_collapsed do |expand_event| @status_label.text = "#{expand_event.item.text} Collapsed!" end } } } end HelloExpandBar.launch
ruby
MIT
449cf07ada1ec965ae2ac91715ccdf22488df4ca
2026-01-04T17:52:38.125591Z
false
AndyObtiva/glimmer-dsl-swt
https://github.com/AndyObtiva/glimmer-dsl-swt/blob/449cf07ada1ec965ae2ac91715ccdf22488df4ca/samples/hello/hello_tool_bar.rb
samples/hello/hello_tool_bar.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' class HelloToolBar include Glimmer::UI::CustomShell attr_accessor :operation, :font_size def font_size_options (10..30).to_a.map(&:to_s) end before_body do self.font_size = '30' end body { shell { row_layout(:vertical) { fill true margin_width 0 margin_height 0 } text 'Hello, Tool Bar!' minimum_size 280, 50 tool_bar { # optionally takes a :flat style, :wrap style if you need wrapping upon shrinking window, and :vertical style if you need vertical layout tool_item { image File.expand_path('./images/cut.png', __dir__), height: 16 on_widget_selected do self.operation = 'Cut' end } tool_item { image File.expand_path('./images/copy.png', __dir__), height: 16 on_widget_selected do self.operation = 'Copy' end } tool_item { image File.expand_path('./images/paste.png', __dir__), height: 16 on_widget_selected do self.operation = 'Paste' end } tool_item(:separator) # a combo can be nested in a tool_bar (it auto-generates a tool_item for itself behind the scenes) combo { selection <=> [self, :font_size] } } label { font <= [self, :font_size, on_read: ->(size) { {height: size.to_i} }] text <= [self, :operation] text <= [self, :font_size] } } } def cut_image File.expand_path('./images/cut.png', __dir__) end def copy_image File.expand_path('./images/copy.png', __dir__) end def paste_image File.expand_path('./images/paste.png', __dir__) end end HelloToolBar.launch
ruby
MIT
449cf07ada1ec965ae2ac91715ccdf22488df4ca
2026-01-04T17:52:38.125591Z
false
AndyObtiva/glimmer-dsl-swt
https://github.com/AndyObtiva/glimmer-dsl-swt/blob/449cf07ada1ec965ae2ac91715ccdf22488df4ca/samples/hello/hello_font_dialog.rb
samples/hello/hello_font_dialog.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' class HelloFontDialog include Glimmer::UI::CustomShell attr_accessor :selected_font_data before_body do @selected_font_data = FontData.new('Times New Roman', 40, swt(:bold)) end body { shell { grid_layout { margin_width 15 margin_width 15 } minimum_size 400, 0 text 'Hello, Font Dialog!' label { text 'Selected Font:' font height: 14, style: :bold } label(:center) { layout_data(:fill, :center, true, true) { vertical_indent 15 height_hint 200 } background :white font <=> [self, 'selected_font_data'] text <=> [self, 'selected_font_data', on_read: ->(font_data) { style = case font_data.style when swt(:normal) 'Normal' when swt(:italic) 'Italic' when swt(:bold) 'Bold' when swt(:bold, :italic) 'Bold Italic' end "#{font_data.name}\n#{font_data.height}\n#{style}" }] } button { text "Choose Font..." on_widget_selected do self.selected_font_data = font_dialog { font_list [@selected_font_data] }.open end } } } end HelloFontDialog.launch
ruby
MIT
449cf07ada1ec965ae2ac91715ccdf22488df4ca
2026-01-04T17:52:38.125591Z
false
AndyObtiva/glimmer-dsl-swt
https://github.com/AndyObtiva/glimmer-dsl-swt/blob/449cf07ada1ec965ae2ac91715ccdf22488df4ca/samples/hello/hello_pop_up_context_menu.rb
samples/hello/hello_pop_up_context_menu.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' include Glimmer shell { grid_layout { margin_width 0 margin_height 0 } text 'Hello, Pop Up Context Menu!' label { text "Right-Click on the Text to\nPop Up a Context Menu" font height: 50 menu { menu { text '&History' menu { text '&Recent' menu_item { text 'File 1' on_widget_selected do message_box { text 'File 1' message 'File 1 Contents' }.open end } menu_item { text 'File 2' on_widget_selected do message_box { text 'File 2' message 'File 2 Contents' }.open end } } menu { text '&Archived' menu_item { text 'File 3' on_widget_selected do message_box { text 'File 3' message 'File 3 Contents' }.open end } menu_item { text 'File 4' on_widget_selected do message_box { text 'File 4' message 'File 4 Contents' }.open end } } } } } }.open
ruby
MIT
449cf07ada1ec965ae2ac91715ccdf22488df4ca
2026-01-04T17:52:38.125591Z
false
AndyObtiva/glimmer-dsl-swt
https://github.com/AndyObtiva/glimmer-dsl-swt/blob/449cf07ada1ec965ae2ac91715ccdf22488df4ca/samples/hello/hello_styled_text.rb
samples/hello/hello_styled_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-dsl-swt' verbiage = <<-MULTI_LINE_STRING Glimmer DSL for SWT is a native-GUI cross-platform desktop development library written in JRuby, an OS-threaded faster version of Ruby. Glimmer's main innovation is a declarative Ruby DSL that enables productive and efficient authoring of desktop application user-interfaces while relying on the robust Eclipse SWT library. Glimmer additionally innovates by having built-in data-binding support, which greatly facilitates synchronizing the GUI with domain models, thus achieving true decoupling of object oriented components and enabling developers to solve business problems (test-first) without worrying about GUI concerns. To get started quickly, Glimmer offers scaffolding options for Apps, Gems, and Custom Widgets. Glimmer also includes native-executable packaging support, sorely lacking in other libraries, thus enabling the delivery of desktop apps written in Ruby as truly native DMG/PKG/APP files on the Mac + App Store, MSI/EXE files on Windows, and Gem Packaged Shell Scripts on Linux. MULTI_LINE_STRING class StyledTextPresenter include Glimmer attr_accessor :text, :caret_offset, :selection_count, :selection, :top_pixel def line_index_for_offset(line_offset) text[0..line_offset].split("\n").size end end include Glimmer @presenter = StyledTextPresenter.new @presenter.text = verbiage*4 @presenter.caret_offset = 0 @presenter.selection_count = 0 @presenter.selection = Point.new(0, 0) @presenter.top_pixel = 0 shell { text 'Hello, Styled Text!' composite { @styled_text = styled_text { layout_data :fill, :fill, true, true text <=> [@presenter, :text] left_margin 5 top_margin 5 right_margin 5 bottom_margin 5 # caret offset scrolls text to view when out of page caret_offset <=> [@presenter, :caret_offset] # selection_count is not needed if selection is used selection_count <=> [@presenter, :selection_count] # selection contains both caret_offset and selection_count, but setting it does not scroll text into view if out of page selection <=> [@presenter, :selection] # top_pixel indicates vertically what pixel scrolling is at in a long multi-page text document top_pixel <=> [@presenter, :top_pixel] # This demonstrates how to set styles via a listener on_line_get_style do |line_style_event| line_offset = line_style_event.lineOffset if @presenter.line_index_for_offset(line_offset) % 52 < 13 line_size = line_style_event.lineText.size style_range = StyleRange.new(line_offset, line_size, color(:blue).swt_color, nil, swt(:italic)) style_range.font = Font.new(display.swt_display, 'Times New Roman', 18, swt(:normal)) line_style_event.styles = [style_range] elsif @presenter.line_index_for_offset(line_offset) % 52 < 26 line_size = line_style_event.lineText.size style_range = StyleRange.new(line_offset, line_size, color(:dark_green).swt_color, color(:yellow).swt_color, swt(:bold)) line_style_event.styles = [style_range] elsif @presenter.line_index_for_offset(line_offset) % 52 < 39 line_size = line_style_event.lineText.size style_range = StyleRange.new(line_offset, line_size, color(:red).swt_color, nil, swt(:normal)) style_range.underline = true style_range.font = Font.new(display.swt_display, 'Arial', 16, swt(:normal)) line_style_event.styles = [style_range] else line_size = line_style_event.lineText.size style_range = StyleRange.new(line_offset, line_size, color(:dark_magenta).swt_color, color(:cyan).swt_color, swt(:normal)) style_range.strikeout = true line_style_event.styles = [style_range] end end } composite { row_layout :horizontal label { text 'Caret Offset:' } text { text <=> [@presenter, :caret_offset, on_read: ->(o) {"%04d" % [o] }] } label { text 'Selection Count:' } text { text <=> [@presenter, :selection_count, on_read: ->(o) {"%04d" % [o] }] } label { text 'Selection Start:' } text { text <=> [@presenter, 'selection.x', on_read: ->(o) {"%04d" % [o] }] } label { text 'Selection End:' } text { text <=> [@presenter, 'selection.y', on_read: ->(o) {"%04d" % [o] }] } label { text 'Top Pixel:' } text { text <=> [@presenter, :top_pixel, on_read: ->(o) {"%04d" % [o] }] } } } }.open
ruby
MIT
449cf07ada1ec965ae2ac91715ccdf22488df4ca
2026-01-04T17:52:38.125591Z
false
AndyObtiva/glimmer-dsl-swt
https://github.com/AndyObtiva/glimmer-dsl-swt/blob/449cf07ada1ec965ae2ac91715ccdf22488df4ca/samples/hello/hello_canvas.rb
samples/hello/hello_canvas.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' class HelloCanvas include Glimmer::UI::CustomShell attr_accessor :selected_shape attr_accessor :artist before_body do @image_object = image(File.expand_path('../../icons/scaffold_app.png', __dir__), width: 50) @artist = '' end after_body do Thread.new do 'Picasso'.chars.each do |character| sleep(1) self.artist += character end end end body { shell { text 'Hello, Canvas!' minimum_size 320, 400 @canvas = canvas { background :yellow rectangle(0, 0, 220, 400) { background rgb(255, 0, 0) } rectangle(50, 20, 300, 150, 30, 50) { background :magenta rectangle(:default, :default, :max, :max, 30, 50) { foreground :yellow } rectangle([:default, -70], :default, :default, [:default, 1]) { foreground :cyan text { string <= [self, :artist] x :default, 1 # add 1 pixel to default x (shape centered within parent horizontally) y :default, 1 # add 1 pixel to default y (shape centered within parent vertically) background :yellow foreground :dark_magenta font name: 'Courier', height: (OS.windows? ? 26 : 30) } } rectangle(155, 30) { # width and height are assumed to be the default (calculated from children) foreground :yellow 3.times do |n| line(45, 70 + n*10, 65 + n*10, 30 + n*10) { foreground :yellow } end 10.times do |n| point(15 + n*5, 50 + n*5) { foreground :yellow } end polyline(45, 60, 55, 20, 65, 60, 85, 80, 45, 60) image(@image_object, 0, 5) } } rectangle(150, 200, 100, 70, true) { background :dark_magenta foreground :yellow } rectangle(50, 200, 30, 70, false) { background :magenta foreground :dark_blue } oval(110, 310, 100, 100) { # patterns provide a differnet way to make gradients background_pattern 0, 0, 105, 0, :yellow, rgb(128, 138, 248) } arc(210, 210, 100, 100, 30, -77) { background :red } polygon(250, 210, 260, 170, 270, 210, 290, 230) { background :dark_yellow } menu { menu_item { text 'Change Background Color...' enabled <=> [self, :selected_shape, on_read: ->(shape) { shape.respond_to?(:background) && shape.background }] on_widget_selected do @selected_shape&.background = color_dialog.open self.selected_shape = nil end } menu_item { text 'Change Background Pattern Color 1...' enabled <=> [self, :selected_shape, on_read: ->(shape) { shape.respond_to?(:background_pattern) && shape.background_pattern }] on_widget_selected do if @selected_shape background_pattern_args = @selected_shape.background_pattern_args background_pattern_args[5] = color_dialog.open @selected_shape.background_pattern = background_pattern_args self.selected_shape = nil end end } menu_item { text 'Change Background Pattern Color 2...' enabled <=> [self, :selected_shape, on_read: ->(shape) { shape.respond_to?(:background_pattern) && shape.background_pattern }] on_widget_selected do if @selected_shape background_pattern_args = @selected_shape.background_pattern_args background_pattern_args[6] = color_dialog.open @selected_shape.background_pattern = background_pattern_args self.selected_shape = nil end end } menu_item(:separator) menu_item { text 'Change Foreground Color...' enabled <=> [self, :selected_shape, on_read: ->(shape) { shape.respond_to?(:foreground) && shape.foreground }] on_widget_selected do @selected_shape&.foreground = color_dialog.open self.selected_shape = nil end } } on_mouse_down do |mouse_event| @drag_detected = false @canvas.cursor = :hand self.selected_shape = @canvas.shape_at_location(mouse_event.x, mouse_event.y) end on_drag_detected do |drag_detect_event| @drag_detected = true @drag_current_x = drag_detect_event.x @drag_current_y = drag_detect_event.y end on_mouse_move do |mouse_event| if @drag_detected @selected_shape&.move_by(mouse_event.x - @drag_current_x, mouse_event.y - @drag_current_y) @drag_current_x = mouse_event.x @drag_current_y = mouse_event.y end end on_menu_detected do |menu_detect_event| @menu_detected = true end on_mouse_up do |mouse_event| @canvas.cursor = :arrow @drag_detected = false if @menu_detected @menu_detected = nil else self.selected_shape = nil end end } } } end HelloCanvas.launch
ruby
MIT
449cf07ada1ec965ae2ac91715ccdf22488df4ca
2026-01-04T17:52:38.125591Z
false
AndyObtiva/glimmer-dsl-swt
https://github.com/AndyObtiva/glimmer-dsl-swt/blob/449cf07ada1ec965ae2ac91715ccdf22488df4ca/samples/hello/hello_checkbox_group.rb
samples/hello/hello_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-dsl-swt' # This sample demonstrates the use of a `checkbox_group` (aka `check_group`) in Glimmer, which provides terser syntax # than HelloCheckbox for representing multiple checkbox buttons (`button(:check)`) by relying on data-binding to # automatically spawn the `checkbox` widgets (`button(:check)`) based on available options on the model. class HelloCheckboxGroup class Person attr_accessor :activities def initialize reset_activities end def activities_options ['Skiing', 'Snowboarding', 'Snowmobiling', 'Snowshoeing'] end def reset_activities self.activities = ['Snowboarding'] end end include Glimmer::UI::CustomShell before_body do @person = Person.new end body { shell { text 'Hello, Checkbox Group!' row_layout :vertical label { text 'Check all snow activities you are interested in:' font style: :bold } checkbox_group { selection <=> [@person, :activities] } button { text 'Reset Activities' on_widget_selected do @person.reset_activities end } } } end HelloCheckboxGroup.launch
ruby
MIT
449cf07ada1ec965ae2ac91715ccdf22488df4ca
2026-01-04T17:52:38.125591Z
false
AndyObtiva/glimmer-dsl-swt
https://github.com/AndyObtiva/glimmer-dsl-swt/blob/449cf07ada1ec965ae2ac91715ccdf22488df4ca/samples/hello/hello_radio.rb
samples/hello/hello_radio.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' class HelloRadio class Person attr_accessor :male, :female, :child, :teen, :adult, :senior def initialize reset! end def reset! self.male = nil self.female = nil self.child = nil self.teen = nil self.adult = true self.senior = nil end end include Glimmer::UI::CustomShell before_body do @person = Person.new end body { shell { text 'Hello, Radio!' row_layout :vertical label { text 'Gender:' font style: :bold } composite { row_layout radio { text 'Male' selection <=> [@person, :male] } radio { text 'Female' selection <=> [@person, :female] } } label { text 'Age Group:' font style: :bold } composite { row_layout radio { text 'Child' selection <=> [@person, :child] } radio { text 'Teen' selection <=> [@person, :teen] } radio { text 'Adult' selection <=> [@person, :adult] } radio { text 'Senior' selection <=> [@person, :senior] } } button { text 'Reset' on_widget_selected do @person.reset! end } } } end HelloRadio.launch
ruby
MIT
449cf07ada1ec965ae2ac91715ccdf22488df4ca
2026-01-04T17:52:38.125591Z
false
AndyObtiva/glimmer-dsl-swt
https://github.com/AndyObtiva/glimmer-dsl-swt/blob/449cf07ada1ec965ae2ac91715ccdf22488df4ca/samples/hello/hello_button.rb
samples/hello/hello_button.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' class HelloButton include Glimmer::UI::CustomShell attr_accessor :count before_body do self.count = 0 end body { shell { text 'Hello, Button!' button { text <= [self, :count, on_read: ->(value) { "Click To Increment: #{value} " }] on_widget_selected do self.count += 1 end } } } end HelloButton.launch
ruby
MIT
449cf07ada1ec965ae2ac91715ccdf22488df4ca
2026-01-04T17:52:38.125591Z
false
AndyObtiva/glimmer-dsl-swt
https://github.com/AndyObtiva/glimmer-dsl-swt/blob/449cf07ada1ec965ae2ac91715ccdf22488df4ca/samples/hello/hello_world.rb
samples/hello/hello_world.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' include Glimmer shell { text 'Glimmer' label { text 'Hello, World!' } }.open
ruby
MIT
449cf07ada1ec965ae2ac91715ccdf22488df4ca
2026-01-04T17:52:38.125591Z
false
AndyObtiva/glimmer-dsl-swt
https://github.com/AndyObtiva/glimmer-dsl-swt/blob/449cf07ada1ec965ae2ac91715ccdf22488df4ca/samples/hello/hello_group.rb
samples/hello/hello_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-dsl-swt' class HelloGroup class Person attr_accessor :male, :female, :child, :teen, :adult, :senior def initialize reset! end def reset! self.male = nil self.female = nil self.child = nil self.teen = nil self.adult = true self.senior = nil end end include Glimmer::UI::CustomShell before_body do @person = Person.new end body { shell { text 'Hello, Group!' row_layout :vertical group { row_layout text 'Gender' font style: :bold radio { text 'Male' selection <=> [@person, :male] } radio { text 'Female' selection <=> [@person, :female] } } group { row_layout text 'Age Group' font style: :bold radio { text 'Child' selection <=> [@person, :child] } radio { text 'Teen' selection <=> [@person, :teen] } radio { text 'Adult' selection <=> [@person, :adult] } radio { text 'Senior' selection <=> [@person, :senior] } } button { text 'Reset' on_widget_selected do @person.reset! end } } } end HelloGroup.launch
ruby
MIT
449cf07ada1ec965ae2ac91715ccdf22488df4ca
2026-01-04T17:52:38.125591Z
false
AndyObtiva/glimmer-dsl-swt
https://github.com/AndyObtiva/glimmer-dsl-swt/blob/449cf07ada1ec965ae2ac91715ccdf22488df4ca/samples/hello/hello_canvas_shape_listeners.rb
samples/hello/hello_canvas_shape_listeners.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' class HelloCanvasShapeListeners include Glimmer::UI::CustomShell attr_accessor :shape_name, :listener_event, :dragged_shape body { shell { row_layout(:vertical) { fill true center true margin_width 0 margin_height 0 } text 'Hello, Canvas Shape Listeners!' label(:center) { text 'Current Shape:' font style: :bold } label(:center) { text <= [self, :shape_name] } label(:center) { text 'Current Event:' font style: :bold } label(:center) { text <= [self, :listener_event] } canvas { |canvas_proxy| layout_data { width 350 height 200 } background :white @rectangle = rectangle(25, 25, 50, 50) { background :red # these listener events are limited to the rectangle bounds on_mouse_down do |event| self.shape_name = 'Square' self.listener_event = 'Mouse Down' end on_drag_detected do |event| self.shape_name = 'Square' self.listener_event += ' / Drag Detected' self.dragged_shape = @rectangle end on_mouse_move do |event| if listener_event.to_s.empty? || shape_name != 'Square' self.listener_event = "Mouse Move" elsif !listener_event.to_s.include?('Mouse Move') self.listener_event += " / Mouse Move" end self.shape_name = 'Square' end on_mouse_up do |event| self.shape_name = 'Square' self.listener_event += ' / Mouse Up' self.dragged_shape = nil end } @oval = oval(150, 120, 50, 50) { background :green # these listener events are limited to the oval bounds on_mouse_down do |event| self.shape_name = 'Circle' self.listener_event = 'Mouse Down' end on_drag_detected do |event| self.shape_name = 'Circle' self.listener_event += ' / Drag Detected' self.dragged_shape = @oval end on_mouse_move do |event| if listener_event.to_s.empty? || shape_name != 'Circle' self.listener_event = "Mouse Move" elsif !listener_event.to_s.include?('Mouse Move') self.listener_event += " / Mouse Move" end self.shape_name = 'Circle' end on_mouse_up do |event| self.shape_name = 'Circle' self.listener_event += ' / Mouse Up' self.dragged_shape = nil end } @polygon = polygon(260, 25, 300, 25, 260, 65) { background :blue # these listener events are limited to the polygon bounds on_mouse_down do |event| self.shape_name = 'Triangle' self.listener_event = 'Mouse Down' end on_drag_detected do |event| self.shape_name = 'Triangle' self.listener_event += ' / Drag Detected' self.dragged_shape = @polygon end on_mouse_move do |event| if listener_event.to_s.empty? || shape_name != 'Triangle' self.listener_event = "Mouse Move" elsif !listener_event.to_s.include?('Mouse Move') self.listener_event += " / Mouse Move" end self.shape_name = 'Triangle' end on_mouse_up do |event| self.shape_name = 'Triangle' self.listener_event += ' / Mouse Up' self.dragged_shape = nil end } # This is a general canvas listener event, which is used to move shape even if mouse goes out of its bounds on_mouse_move do |event| dragged_shape.move_by(event.x - @last_x.to_f, event.y - @last_y.to_f) if dragged_shape @last_x = event.x @last_y = event.y end } } } end HelloCanvasShapeListeners.launch
ruby
MIT
449cf07ada1ec965ae2ac91715ccdf22488df4ca
2026-01-04T17:52:38.125591Z
false
AndyObtiva/glimmer-dsl-swt
https://github.com/AndyObtiva/glimmer-dsl-swt/blob/449cf07ada1ec965ae2ac91715ccdf22488df4ca/samples/hello/hello_dialog.rb
samples/hello/hello_dialog.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' include Glimmer shell { |shell_proxy| row_layout :vertical text 'Hello, Dialog!' 7.times { |n| dialog_number = n + 1 button { layout_data { width 200 height 50 } text "Dialog #{dialog_number}" on_widget_selected do # pass the shell proxy as a parent to make the dialog support hitting the escape button for closing alone without closing app dialog(shell_proxy) { |dialog_proxy| row_layout(:vertical) { center true } text "Dialog #{dialog_number}" label { text "Given `dialog` is modal, you cannot interact with the main window till the dialog is closed." } composite { row_layout { margin_height 0 margin_top 0 margin_bottom 0 } label { text "Unlike `message_box`, `dialog` can contain arbitrary widgets:" } radio { text 'Radio' } checkbox { text 'Checkbox' } } button { text 'Close' on_widget_selected do dialog_proxy.close end } }.open end } } }.open
ruby
MIT
449cf07ada1ec965ae2ac91715ccdf22488df4ca
2026-01-04T17:52:38.125591Z
false
AndyObtiva/glimmer-dsl-swt
https://github.com/AndyObtiva/glimmer-dsl-swt/blob/449cf07ada1ec965ae2ac91715ccdf22488df4ca/samples/hello/hello_composite.rb
samples/hello/hello_composite.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' class HelloComposite include Glimmer::UI::CustomShell body { shell { # shell (which is a composite) has fill_layout(:horizontal) by default with no margins # we override below fill_layout(:vertical) text 'Hello, Composite!' composite { # composite simply contains widgets for visual organization via a layout # it has grid_layout(1, false) as its default layout label { text "Field is above its text widget" } text { layout_data :fill, :center, true, false # fill horizontally, align center vertically, grab remaining horizontal space, but not vertical } } composite { # composite simply contains widgets for visual organization via a layout grid_layout 2, true label { text "Field has equal width to its text widget's" } text { layout_data :fill, :center, true, false # fill horizontally, align center vertically, grab remaining horizontal space, but not vertical } } composite { # composite simply contains widgets for visual organization via a layout grid_layout 2, false label { text "Field has inequal width" } text { layout_data :fill, :center, true, false # fill horizontally, align center vertically, grab remaining horizontal space, but not vertical } } } } end HelloComposite.launch
ruby
MIT
449cf07ada1ec965ae2ac91715ccdf22488df4ca
2026-01-04T17:52:38.125591Z
false
AndyObtiva/glimmer-dsl-swt
https://github.com/AndyObtiva/glimmer-dsl-swt/blob/449cf07ada1ec965ae2ac91715ccdf22488df4ca/samples/hello/hello_canvas_data_binding.rb
samples/hello/hello_canvas_data_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-dsl-swt' class HelloCanvasDataBinding class PathShape attr_accessor :foreground_red, :foreground_green, :foreground_blue, :line_width_value, :line_style_value def foreground_value [foreground_red, foreground_green, foreground_blue] end def line_style_value_options [:solid, :dash, :dot, :dashdot, :dashdotdot] end end class LinePathShape < PathShape attr_accessor :x1_value, :y1_value, :x2_value, :y2_value end class QuadPathShape < PathShape attr_accessor :x1_value, :y1_value, :cx_value, :cy_value, :x2_value, :y2_value def point_array [x1_value, y1_value, cx_value, cy_value, x2_value, y2_value] end end class CubicPathShape < PathShape attr_accessor :x1_value, :y1_value, :cx1_value, :cy1_value, :cx2_value, :cy2_value, :x2_value, :y2_value def point_array [x1_value, y1_value, cx1_value, cy1_value, cx2_value, cy2_value, x2_value, y2_value] end end include Glimmer::GUI::Application # alias for Glimmer::UI::CustomShell / Glimmer::UI::CustomWindow CANVAS_WIDTH = 300 CANVAS_HEIGHT = 300 before_body do @line = LinePathShape.new @line.x1_value = 5 @line.y1_value = 5 @line.x2_value = CANVAS_WIDTH - 5 @line.y2_value = CANVAS_HEIGHT - 5 @line.foreground_red = 28 @line.foreground_green = 128 @line.foreground_blue = 228 @line.line_width_value = 3 @line.line_style_value = :dash @quad = QuadPathShape.new @quad.x1_value = 5 @quad.y1_value = CANVAS_HEIGHT - 5 @quad.cx_value = (CANVAS_WIDTH - 10)/2.0 @quad.cy_value = 5 @quad.x2_value = CANVAS_WIDTH - 5 @quad.y2_value = CANVAS_HEIGHT - 5 @quad.foreground_red = 28 @quad.foreground_green = 128 @quad.foreground_blue = 228 @quad.line_width_value = 3 @quad.line_style_value = :dot @cubic = CubicPathShape.new @cubic.x1_value = 5 @cubic.y1_value = (CANVAS_WIDTH - 10)/2.0 @cubic.cx1_value = (CANVAS_WIDTH - 10)*0.25 @cubic.cy1_value = (CANVAS_WIDTH - 10)*0.25 @cubic.cx2_value = (CANVAS_WIDTH - 10)*0.75 @cubic.cy2_value = (CANVAS_WIDTH - 10)*0.75 @cubic.x2_value = CANVAS_WIDTH - 5 @cubic.y2_value = (CANVAS_WIDTH - 10)/2.0 @cubic.foreground_red = 28 @cubic.foreground_green = 128 @cubic.foreground_blue = 228 @cubic.line_width_value = 3 @cubic.line_style_value = :dashdot end body { shell(:no_resize) { text 'Hello, Canvas Data-Binding!' tab_folder { tab_item { grid_layout(6, true) { margin_width 0 margin_height 0 horizontal_spacing 0 vertical_spacing 0 } text 'Line' label { layout_data(:fill, :center, false, false) { horizontal_span 3 } text 'x1' } label { layout_data(:fill, :center, false, false) { horizontal_span 3 } text 'y1' } spinner { layout_data(:fill, :center, false, false) { horizontal_span 3 } maximum CANVAS_WIDTH increment 3 selection <=> [@line, :x1_value] } spinner { layout_data(:fill, :center, false, false) { horizontal_span 3 } maximum CANVAS_HEIGHT increment 3 selection <=> [@line, :y1_value] } label { layout_data(:fill, :center, false, false) { horizontal_span 3 } text 'x2' } label { layout_data(:fill, :center, false, false) { horizontal_span 3 } text 'y2' } spinner { layout_data(:fill, :center, false, false) { horizontal_span 3 } maximum CANVAS_WIDTH increment 3 selection <=> [@line, :x2_value] } spinner { layout_data(:fill, :center, false, false) { horizontal_span 3 } maximum CANVAS_HEIGHT increment 3 selection <=> [@line, :y2_value] } label { layout_data(:fill, :center, false, false) { horizontal_span 2 } text 'foreground red' } label { layout_data(:fill, :center, false, false) { horizontal_span 2 } text 'foreground green' } label { layout_data(:fill, :center, false, false) { horizontal_span 2 } text 'foreground blue' } spinner { layout_data(:fill, :center, false, false) { horizontal_span 2 } maximum 255 increment 10 selection <=> [@line, :foreground_red] } spinner { layout_data(:fill, :center, false, false) { horizontal_span 2 } maximum 255 increment 10 selection <=> [@line, :foreground_green] } spinner { layout_data(:fill, :center, false, false) { horizontal_span 2 } maximum 255 increment 10 selection <=> [@line, :foreground_blue] } label { layout_data(:fill, :center, false, false) { horizontal_span 3 } text 'line width' } label { layout_data(:fill, :center, false, false) { horizontal_span 3 } text 'line style' } spinner { layout_data(:fill, :center, false, false) { horizontal_span 3 } maximum 255 selection <=> [@line, :line_width_value] } combo(:read_only) { layout_data(:fill, :center, false, false) { horizontal_span 3 } selection <=> [@line, :line_style_value] } @line_canvas = canvas { layout_data(:center, :center, false, false) { horizontal_span 6 width_hint CANVAS_WIDTH height_hint CANVAS_WIDTH } background :white line { x1 <= [@line, :x1_value] y1 <= [@line, :y1_value] x2 <= [@line, :x2_value] y2 <= [@line, :y2_value] foreground <= [@line, :foreground_value, computed_by: [:foreground_red, :foreground_green, :foreground_blue]] line_width <= [@line, :line_width_value] line_style <= [@line, :line_style_value] } @line_oval1 = oval { x <= [@line, :x1_value, on_read: ->(val) {val - 5}] y <= [@line, :y1_value, on_read: ->(val) {val - 5}] width 10 height 10 background :black } @line_oval2 = oval { x <= [@line, :x2_value, on_read: ->(val) {val - 5}] y <= [@line, :y2_value, on_read: ->(val) {val - 5}] width 10 height 10 background :black } on_mouse_down do |mouse_event| @selected_shape = @line_canvas.shape_at_location(mouse_event.x, mouse_event.y) @selected_shape = nil unless @selected_shape.is_a?(Glimmer::SWT::Custom::Shape::Oval) @line_canvas.cursor = :hand if @selected_shape end on_drag_detected do |drag_detect_event| @drag_detected = true @drag_current_x = drag_detect_event.x @drag_current_y = drag_detect_event.y end on_mouse_move do |mouse_event| if @drag_detected && @selected_shape delta_x = mouse_event.x - @drag_current_x delta_y = mouse_event.y - @drag_current_y case @selected_shape when @line_oval1 @line.x1_value += delta_x @line.y1_value += delta_y when @line_oval2 @line.x2_value += delta_x @line.y2_value += delta_y end @drag_current_x = mouse_event.x @drag_current_y = mouse_event.y end end on_mouse_up do |mouse_event| @line_canvas.cursor = :arrow @drag_detected = false @selected_shape = nil end } } tab_item { grid_layout(6, true) { margin_width 0 margin_height 0 horizontal_spacing 0 vertical_spacing 0 } text 'Quad' label { layout_data(:fill, :center, false, false) { horizontal_span 3 } text 'x1' } label { layout_data(:fill, :center, false, false) { horizontal_span 3 } text 'y1' } spinner { layout_data(:fill, :center, false, false) { horizontal_span 3 } maximum CANVAS_WIDTH increment 3 selection <=> [@quad, :x1_value] } spinner { layout_data(:fill, :center, false, false) { horizontal_span 3 } maximum CANVAS_HEIGHT increment 3 selection <=> [@quad, :y1_value] } label { layout_data(:fill, :center, false, false) { horizontal_span 3 } text 'control x' } label { layout_data(:fill, :center, false, false) { horizontal_span 3 } text 'control y' } spinner { layout_data(:fill, :center, false, false) { horizontal_span 3 } maximum CANVAS_WIDTH increment 3 selection <=> [@quad, :cx_value] } spinner { layout_data(:fill, :center, false, false) { horizontal_span 3 } maximum CANVAS_HEIGHT increment 3 selection <=> [@quad, :cy_value] } label { layout_data(:fill, :center, false, false) { horizontal_span 3 } text 'x2' } label { layout_data(:fill, :center, false, false) { horizontal_span 3 } text 'y2' } spinner { layout_data(:fill, :center, false, false) { horizontal_span 3 } maximum CANVAS_WIDTH increment 3 selection <=> [@quad, :x2_value] } spinner { layout_data(:fill, :center, false, false) { horizontal_span 3 } maximum CANVAS_HEIGHT increment 3 selection <=> [@quad, :y2_value] } label { layout_data(:fill, :center, false, false) { horizontal_span 2 } text 'foreground red' } label { layout_data(:fill, :center, false, false) { horizontal_span 2 } text 'foreground green' } label { layout_data(:fill, :center, false, false) { horizontal_span 2 } text 'foreground blue' } spinner { layout_data(:fill, :center, false, false) { horizontal_span 2 } maximum 255 increment 10 selection <=> [@quad, :foreground_red] } spinner { layout_data(:fill, :center, false, false) { horizontal_span 2 } maximum 255 increment 10 selection <=> [@quad, :foreground_green] } spinner { layout_data(:fill, :center, false, false) { horizontal_span 2 } maximum 255 increment 10 selection <=> [@quad, :foreground_blue] } label { layout_data(:fill, :center, false, false) { horizontal_span 3 } text 'line width' } label { layout_data(:fill, :center, false, false) { horizontal_span 3 } text 'line style' } spinner { layout_data(:fill, :center, false, false) { horizontal_span 3 } maximum 255 selection <=> [@quad, :line_width_value] } combo(:read_only) { layout_data(:fill, :center, false, false) { horizontal_span 3 } selection <=> [@quad, :line_style_value] } @quad_canvas = canvas { layout_data(:center, :center, false, false) { horizontal_span 6 width_hint CANVAS_WIDTH height_hint CANVAS_WIDTH } background :white path { foreground <= [@quad, :foreground_value, computed_by: [:foreground_red, :foreground_green, :foreground_blue]] line_width <= [@quad, :line_width_value] line_style <= [@quad, :line_style_value] quad { point_array <= [@quad, :point_array, computed_by: [:x1_value, :y1_value, :cx_value, :cy_value, :x2_value, :y2_value]] } } @quad_oval1 = oval { x <= [@quad, :x1_value, on_read: ->(val) {val - 5}] y <= [@quad, :y1_value, on_read: ->(val) {val - 5}] width 10 height 10 background :black } @quad_oval2 = oval { x <= [@quad, :cx_value, on_read: ->(val) {val - 5}] y <= [@quad, :cy_value, on_read: ->(val) {val - 5}] width 10 height 10 background :dark_gray } @quad_oval3 = oval { x <= [@quad, :x2_value, on_read: ->(val) {val - 5}] y <= [@quad, :y2_value, on_read: ->(val) {val - 5}] width 10 height 10 background :black } on_mouse_down do |mouse_event| @selected_shape = @quad_canvas.shape_at_location(mouse_event.x, mouse_event.y) @selected_shape = nil unless @selected_shape.is_a?(Glimmer::SWT::Custom::Shape::Oval) @quad_canvas.cursor = :hand if @selected_shape end on_drag_detected do |drag_detect_event| @drag_detected = true @drag_current_x = drag_detect_event.x @drag_current_y = drag_detect_event.y end on_mouse_move do |mouse_event| if @drag_detected && @selected_shape delta_x = mouse_event.x - @drag_current_x delta_y = mouse_event.y - @drag_current_y case @selected_shape when @quad_oval1 @quad.x1_value += delta_x @quad.y1_value += delta_y when @quad_oval2 @quad.cx_value += delta_x @quad.cy_value += delta_y when @quad_oval3 @quad.x2_value += delta_x @quad.y2_value += delta_y end @drag_current_x = mouse_event.x @drag_current_y = mouse_event.y end end on_mouse_up do |mouse_event| @quad_canvas.cursor = :arrow @drag_detected = false @selected_shape = nil end } } tab_item { grid_layout(6, true) { margin_width 0 margin_height 0 horizontal_spacing 0 vertical_spacing 0 } text 'Cubic' label { layout_data(:fill, :center, false, false) { horizontal_span 3 } text 'x1' } label { layout_data(:fill, :center, false, false) { horizontal_span 3 } text 'y1' } spinner { layout_data(:fill, :center, false, false) { horizontal_span 3 } maximum CANVAS_WIDTH increment 3 selection <=> [@cubic, :x1_value] } spinner { layout_data(:fill, :center, false, false) { horizontal_span 3 } maximum CANVAS_HEIGHT increment 3 selection <=> [@cubic, :y1_value] } label { layout_data(:fill, :center, false, false) { horizontal_span 3 } text 'control 1 x' } label { layout_data(:fill, :center, false, false) { horizontal_span 3 } text 'control 1 y' } spinner { layout_data(:fill, :center, false, false) { horizontal_span 3 } maximum CANVAS_WIDTH increment 3 selection <=> [@cubic, :cx1_value] } spinner { layout_data(:fill, :center, false, false) { horizontal_span 3 } maximum CANVAS_HEIGHT increment 3 selection <=> [@cubic, :cy1_value] } label { layout_data(:fill, :center, false, false) { horizontal_span 3 } text 'control 2 x' } label { layout_data(:fill, :center, false, false) { horizontal_span 3 } text 'control 2 y' } spinner { layout_data(:fill, :center, false, false) { horizontal_span 3 } maximum CANVAS_WIDTH increment 3 selection <=> [@cubic, :cx2_value] } spinner { layout_data(:fill, :center, false, false) { horizontal_span 3 } maximum CANVAS_HEIGHT increment 3 selection <=> [@cubic, :cy2_value] } label { layout_data(:fill, :center, false, false) { horizontal_span 3 } text 'x2' } label { layout_data(:fill, :center, false, false) { horizontal_span 3 } text 'y2' } spinner { layout_data(:fill, :center, false, false) { horizontal_span 3 } maximum CANVAS_WIDTH increment 3 selection <=> [@cubic, :x2_value] } spinner { layout_data(:fill, :center, false, false) { horizontal_span 3 } maximum CANVAS_HEIGHT increment 3 selection <=> [@cubic, :y2_value] } label { layout_data(:fill, :center, false, false) { horizontal_span 2 } text 'foreground red' } label { layout_data(:fill, :center, false, false) { horizontal_span 2 } text 'foreground green' } label { layout_data(:fill, :center, false, false) { horizontal_span 2 } text 'foreground blue' } spinner { layout_data(:fill, :center, false, false) { horizontal_span 2 } maximum 255 increment 10 selection <=> [@cubic, :foreground_red] } spinner { layout_data(:fill, :center, false, false) { horizontal_span 2 } maximum 255 increment 10 selection <=> [@cubic, :foreground_green] } spinner { layout_data(:fill, :center, false, false) { horizontal_span 2 } maximum 255 increment 10 selection <=> [@cubic, :foreground_blue] } label { layout_data(:fill, :center, false, false) { horizontal_span 3 } text 'line width' } label { layout_data(:fill, :center, false, false) { horizontal_span 3 } text 'line style' } spinner { layout_data(:fill, :center, false, false) { horizontal_span 3 } maximum 255 selection <=> [@cubic, :line_width_value] } combo(:read_only) { layout_data(:fill, :center, false, false) { horizontal_span 3 } selection <=> [@cubic, :line_style_value] } @cubic_canvas = canvas { layout_data(:center, :center, false, false) { horizontal_span 6 width_hint CANVAS_WIDTH height_hint CANVAS_WIDTH } background :white path { foreground <= [@cubic, :foreground_value, computed_by: [:foreground_red, :foreground_green, :foreground_blue]] line_width <= [@cubic, :line_width_value] line_style <= [@cubic, :line_style_value] cubic { point_array <= [@cubic, :point_array, computed_by: [:x1_value, :y1_value, :cx1_value, :cy1_value, :cx2_value, :cy2_value, :x2_value, :y2_value]] } } @cubic_oval1 = oval { x <= [@cubic, :x1_value, on_read: ->(val) {val - 5}] y <= [@cubic, :y1_value, on_read: ->(val) {val - 5}] width 10 height 10 background :black } @cubic_oval2 = oval { x <= [@cubic, :cx1_value, on_read: ->(val) {val - 5}] y <= [@cubic, :cy1_value, on_read: ->(val) {val - 5}] width 10 height 10 background :dark_gray } @cubic_oval3 = oval { x <= [@cubic, :cx2_value, on_read: ->(val) {val - 5}] y <= [@cubic, :cy2_value, on_read: ->(val) {val - 5}] width 10 height 10 background :dark_gray } @cubic_oval4 = oval { x <= [@cubic, :x2_value, on_read: ->(val) {val - 5}] y <= [@cubic, :y2_value, on_read: ->(val) {val - 5}] width 10 height 10 background :black } on_mouse_down do |mouse_event| @selected_shape = @cubic_canvas.shape_at_location(mouse_event.x, mouse_event.y) @selected_shape = nil unless @selected_shape.is_a?(Glimmer::SWT::Custom::Shape::Oval) @cubic_canvas.cursor = :hand if @selected_shape end on_drag_detected do |drag_detect_event| @drag_detected = true @drag_current_x = drag_detect_event.x @drag_current_y = drag_detect_event.y end on_mouse_move do |mouse_event| if @drag_detected && @selected_shape delta_x = mouse_event.x - @drag_current_x delta_y = mouse_event.y - @drag_current_y case @selected_shape when @cubic_oval1 @cubic.x1_value += delta_x @cubic.y1_value += delta_y when @cubic_oval2 @cubic.cx1_value += delta_x @cubic.cy1_value += delta_y when @cubic_oval3 @cubic.cx2_value += delta_x @cubic.cy2_value += delta_y when @cubic_oval4 @cubic.x2_value += delta_x @cubic.y2_value += delta_y end @drag_current_x = mouse_event.x @drag_current_y = mouse_event.y end end on_mouse_up do |mouse_event| @cubic_canvas.cursor = :arrow @drag_detected = false @selected_shape = nil end } } } } } end HelloCanvasDataBinding.launch
ruby
MIT
449cf07ada1ec965ae2ac91715ccdf22488df4ca
2026-01-04T17:52:38.125591Z
false
AndyObtiva/glimmer-dsl-swt
https://github.com/AndyObtiva/glimmer-dsl-swt/blob/449cf07ada1ec965ae2ac91715ccdf22488df4ca/samples/hello/hello_toggle.rb
samples/hello/hello_toggle.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' class HelloToggle include Glimmer::UI::CustomShell attr_accessor :red, :green, :blue, :final_color_text, :final_color after_body do observe(self, :red) do update_final_color! end observe(self, :green) do update_final_color! end observe(self, :blue) do update_final_color! end end body { shell { grid_layout 3, true text 'Hello, Toggle!' toggle { layout_data :fill, :center, true, false text 'Red' selection <=> [self, :red] } toggle { layout_data :fill, :center, true, false text 'Green' selection <=> [self, :green] } toggle { layout_data :fill, :center, true, false text 'Blue' selection <=> [self, :blue] } label(:center) { layout_data { horizontal_span 3 horizontal_alignment :fill grab_excess_horizontal_space true height_hint 20 } text <= [self, :final_color_text] background <= [self, :final_color] } } } def update_final_color! final_color_symbols = [:red, :green, :blue].map {|color| send(color) ? color : nil}.compact self.final_color_text = final_color_symbols.map {|color_symbol| color_symbol.to_s.capitalize}.join(' + ') self.final_color = final_color_symbols.map {|color_symbol| color(color_symbol)}.reduce {|output_color, color| rgb(output_color.red + color.red, output_color.green + color.green, output_color.blue + color.blue) } end end HelloToggle.launch
ruby
MIT
449cf07ada1ec965ae2ac91715ccdf22488df4ca
2026-01-04T17:52:38.125591Z
false
AndyObtiva/glimmer-dsl-swt
https://github.com/AndyObtiva/glimmer-dsl-swt/blob/449cf07ada1ec965ae2ac91715ccdf22488df4ca/samples/hello/hello_canvas_drag_and_drop.rb
samples/hello/hello_canvas_drag_and_drop.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' class HelloCanvasDragAndDrop include Glimmer::UI::CustomShell body { shell { row_layout(:vertical) { margin_width 0 margin_height 0 fill true center true } text 'Hello, Canvas Drag & Drop!' label(:center) { text 'Drag orange balls and drop in the square.' font height: 16 } canvas { layout_data { width 350 height 350 } background :white 10.times do |n| value = rand(10) oval((rand*300).to_i, (rand*200).to_i, 50, 50) { data 'value', value background rgb(255, 165, 0) # declare shape as a drag source, which unlike `drag_and_move true`, it means the shape now # goes back to original position if not dropped at an on_drop shape target drag_source true # unspecified width and height become max width and max height by default oval(0, 0) { foreground :black } text { x :default y :default string value.to_s } } end @drop_square = rectangle(150, 260, 50, 50) { background :white # unspecified width and height become max width and max height by default @drop_square_border = rectangle(0, 0) { foreground :black line_width 3 line_style :dash } @number_shape = text { x :default y :default string '0' } on_mouse_move do @drop_square_border.foreground = :red if Glimmer::SWT::Custom::Shape.dragging? end on_drop do |drop_event| # drop_event attributes: :x, :y, :dragged_shape, :dragged_shape_original_x, :dragged_shape_original_y, :dragging_x, :dragging_y, :drop_shapes # drop_event.doit = false # drop event can be cancelled by setting doit attribute to false ball_count = @number_shape.string.to_i @number_shape.dispose @drop_square.content { @number_shape = text { x :default y :default string (ball_count + drop_event.dragged_shape.get_data('value')).to_s } } drop_event.dragged_shape.dispose end } on_mouse_up do @drop_square_border.foreground = :black end } } } end HelloCanvasDragAndDrop.launch
ruby
MIT
449cf07ada1ec965ae2ac91715ccdf22488df4ca
2026-01-04T17:52:38.125591Z
false
AndyObtiva/glimmer-dsl-swt
https://github.com/AndyObtiva/glimmer-dsl-swt/blob/449cf07ada1ec965ae2ac91715ccdf22488df4ca/samples/hello/hello_tree.rb
samples/hello/hello_tree.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' class HelloTree EMPLOYEE_ATTRIBUTES = [ :first_name, :last_name, :position, :salary, :health_insurance, :desk_location, :sales_bonus_percentage, :merit_bonus, :work_expense, :technology_expense, :travel_expense, :client_expense, :sponsorship_expense, :food_expense, :office_expense, ] EmployeeStruct ||= Struct.new(*EMPLOYEE_ATTRIBUTES, keyword_init: true) class Employee < EmployeeStruct NAMES_FIRST = %w[ John Noah Bill James Oliver Bob Laura Stephanie Marie Emma Olivia Anna ] NAMES_LAST = %w[ Smith Johnson Williams Brown Jones Harvard Miller Davis Wilson Anderson Taylor Magnus ] EMPLOYMENT_TYPE_POSITIONS = { 'Sales' => 'Sales Person', 'HR' => 'HR Staff', 'Engineering' => 'Engineer', 'Finance' => 'Accountant', } SENIORITY_SALARIES = { 'Senior' => 111_111, 'Standard' => 88_888, 'Junior' => 55_555, } ALL_HEALTH_INSURANCES = [ 'Family Plan', 'Standard Plan', 'Minimal Plan', ] class << self attr_accessor :selected_employee def available_names @available_names ||= NAMES_FIRST.size.times.map { |n| NAMES_FIRST.rotate(n).zip(NAMES_LAST) }.flatten(1) end def select_name! available_names.shift end def all_desk_locations @all_desk_locations ||= 30.times.map do |n| floor = n + 1 [ "Floor #{floor} Sales", "Floor #{floor} Engineering", "Floor #{floor} HR", "Floor #{floor} Finance", ] end.reduce(:+) end def available_desk_locations @available_desk_locations ||= all_desk_locations.clone.reverse end def select_desk_location!(type) available_desk_locations.delete(available_desk_locations.detect {|desk_location| desk_location.to_s.end_with?(type)}) end def ceo @ceo ||= Employee.new( position: 'CEO', salary: 999_999, health_insurance: ALL_HEALTH_INSURANCES[0], desk_location: Employee.select_desk_location!('Sales'), ).tap do |employee| employee.subordinates << cto employee.subordinates << cfo employee.subordinates << cio end end def cto @cto ||= Employee.new( position: 'CTO', salary: 777_777, health_insurance: ALL_HEALTH_INSURANCES[0], desk_location: Employee.select_desk_location!('Engineering'), ).tap do |employee| employee.subordinates << vp('Engineering') end end def cfo @cfo ||= Employee.new( position: 'CFO', salary: 777_777, health_insurance: ALL_HEALTH_INSURANCES[0], desk_location: Employee.select_desk_location!('Finance'), ).tap do |employee| employee.subordinates << vp('Finance') end end def cio @cio ||= Employee.new( position: 'CIO', salary: 777_777, health_insurance: ALL_HEALTH_INSURANCES[0], desk_location: Employee.select_desk_location!('HR'), ).tap do |employee| employee.subordinates << vp('Sales') employee.subordinates << vp('HR') end end def vp(type) Employee.new( position: "VP #{type}", salary: 555_555, health_insurance: ALL_HEALTH_INSURANCES[0], desk_location: Employee.select_desk_location!(type), ).tap do |employee| 2.times { employee.subordinates << director(type) } end end def director(type) Employee.new( position: "Director #{type}", salary: 333_333, health_insurance: ALL_HEALTH_INSURANCES.sample, desk_location: Employee.select_desk_location!(type), ).tap do |employee| 3.times { employee.subordinates << manager(type) } end end def manager(type) Employee.new( position: "Manager #{type}", salary: 222_222, health_insurance: ALL_HEALTH_INSURANCES.sample, desk_location: Employee.select_desk_location!(type), ).tap do |employee| employee.subordinates << employee(type, 'Senior') employee.subordinates << employee(type, 'Standard') employee.subordinates << employee(type, 'Junior') end end def employee(type, seniority) seniority_title = seniority == 'Standard' ? '' : seniority Employee.new( position: "#{seniority_title} #{EMPLOYMENT_TYPE_POSITIONS[type]}", salary: SENIORITY_SALARIES[seniority], health_insurance: ALL_HEALTH_INSURANCES.sample, desk_location: Employee.select_desk_location!(type), ) end end def initialize(*args) super(*args) determine_type_from_position if first_name.nil? || last_name.nil? name = Employee.select_name! self.first_name = name.first self.last_name = name.last end self.sales_bonus_percentage = (rand*100).to_i if @type == 'Sales' self.merit_bonus = (rand*99_999).to_i [:work_expense, :technology_expense, :travel_expense, :client_expense, :sponsorship_expense, :food_expense, :office_expense].each do |attribute| self.send("#{attribute}=", rand*9_999) end observer = Glimmer::DataBinding::Observer.proc { notify_observers('to_s') } observer.observe(self, :first_name) observer.observe(self, :last_name) observer.observe(self, :position) end def determine_type_from_position(specified_position = nil) specified_position ||= position @type = EMPLOYMENT_TYPE_POSITIONS.keys.detect {|key| position.include?(key)} @type = 'Sales' if position == 'CEO' @type = 'Finance' if position == 'CFO' @type = 'HR' if position == 'CIO' @type = 'Engineering' if position == 'CTO' end def position_options [ 'CEO', 'CFO', 'CIO', 'CTO', 'VP Sales', 'VP HR', 'VP Engineering', 'VP Finance', 'Sales Director', 'HR Director', 'Engineering Director', 'Finance Director', 'Sales Manager', 'HR Manager', 'Engineering Manager', 'Finance Manager', 'Senior Sales Person', 'Sales Person', 'Junior Sales Person', 'Senior HR Staff', 'HR Staff', 'Junior HR Staff', 'Senior Engineer', 'Engineer', 'Junior Engineer', 'Senior Accountant', 'Accountant', 'Junior Accountant', ] end def health_insurance_options ALL_HEALTH_INSURANCES end def desk_location_options Employee.all_desk_locations end def subordinates @subordinates ||= [] end def to_s "#{first_name} #{last_name} (#{position})" end end include Glimmer::UI::CustomShell before_body do Employee.selected_employee = Employee.ceo end after_body do @tree.items.first.expanded = true end body { shell { fill_layout { margin_width 15 margin_height 15 } text 'Hello, Tree!' minimum_size 900, 600 sash_form { weights 1, 2 composite { fill_layout { margin_width 5 margin_height 5 } @tree = tree { items <= [Employee, :ceo, tree_properties: {children: :subordinates, text: :to_s}] selection <=> [Employee, :selected_employee] } } composite { grid_layout 2, false label { layout_data(:fill, :center, false, false) text 'First Name:' font height: 16, style: :bold } text { layout_data(:fill, :center, true, false) text <=> [Employee, "selected_employee.first_name"] font height: 16 } label { layout_data(:fill, :center, false, false) text 'Last Name:' font height: 16, style: :bold } text { layout_data(:fill, :center, true, false) text <=> [Employee, "selected_employee.last_name"] font height: 16 } label { layout_data(:fill, :center, false, false) text 'Position:' font height: 16, style: :bold } combo { layout_data(:fill, :center, true, false) selection <=> [Employee, "selected_employee.position"] font height: 16 } label { layout_data(:fill, :center, false, false) text 'Salary:' font height: 16, style: :bold } composite { layout_data(:fill, :center, true, false) row_layout { margin_width 0 margin_height 0 } label { text '$' font height: 20 } spinner { maximum 999_999 minimum 0 selection <=> [Employee, "selected_employee.salary"] font height: 16 } } label { layout_data(:fill, :center, false, false) text 'Health Insurance:' font height: 16, style: :bold } combo(:read_only) { layout_data(:fill, :center, true, false) selection <=> [Employee, "selected_employee.health_insurance"] font height: 16 } label { layout_data(:fill, :center, false, false) text 'Desk Location:' font height: 16, style: :bold } combo(:read_only) { layout_data(:fill, :center, true, false) selection <=> [Employee, "selected_employee.desk_location"] font height: 16 } label { layout_data(:fill, :center, false, false) text 'Sales Bonus Percentage:' font height: 16, style: :bold } composite { layout_data(:fill, :center, true, false) row_layout { margin_width 0 margin_height 0 } spinner { maximum 100 minimum 0 selection <=> [Employee, "selected_employee.sales_bonus_percentage"] font height: 16 } label { text '%' font height: 20 } } label { layout_data(:fill, :center, false, false) text 'Merit Bonus:' font height: 16, style: :bold } composite { layout_data(:fill, :center, true, false) row_layout { margin_width 0 margin_height 0 } label { text '$' font height: 20 } spinner { maximum 999_999 minimum 0 selection <=> [Employee, "selected_employee.merit_bonus"] font height: 16 } } [:work_expense, :technology_expense, :travel_expense, :client_expense, :sponsorship_expense, :food_expense, :office_expense].each do |attribute| label { layout_data(:fill, :center, false, false) text "#{attribute.to_s.split('_').map(&:capitalize).join(' ')}:" font height: 16, style: :bold } composite { layout_data(:fill, :center, true, false) row_layout { margin_width 0 margin_height 0 } label { text '$' font height: 20 } spinner { digits 2 maximum 999_999_00 minimum 0 increment 100 selection <=> [Employee, "selected_employee.#{attribute}", on_read: ->(v) {v.to_f * 100}, on_write: ->(v) {v.to_f / 100}] font height: 16 } } end } } } } end HelloTree.launch
ruby
MIT
449cf07ada1ec965ae2ac91715ccdf22488df4ca
2026-01-04T17:52:38.125591Z
false
AndyObtiva/glimmer-dsl-swt
https://github.com/AndyObtiva/glimmer-dsl-swt/blob/449cf07ada1ec965ae2ac91715ccdf22488df4ca/samples/hello/hello_combo.rb
samples/hello/hello_combo.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' class HelloCombo class Person attr_accessor :country, :country_options def initialize self.country_options = ['', 'Canada', 'US', 'Mexico'] reset_country! end def reset_country! self.country = 'Canada' end end include Glimmer::UI::CustomShell before_body do @person = Person.new end body { shell { row_layout(:vertical) { fill true } text 'Hello, Combo!' combo(:read_only) { selection <=> [@person, :country] # also binds to country_options by convention } button { text 'Reset Selection' on_widget_selected do @person.reset_country! end } } } end HelloCombo.launch
ruby
MIT
449cf07ada1ec965ae2ac91715ccdf22488df4ca
2026-01-04T17:52:38.125591Z
false
AndyObtiva/glimmer-dsl-swt
https://github.com/AndyObtiva/glimmer-dsl-swt/blob/449cf07ada1ec965ae2ac91715ccdf22488df4ca/samples/hello/hello_print.rb
samples/hello/hello_print.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' class HelloPrint include Glimmer::UI::CustomShell body { shell { text 'Hello, Print!' @composite = composite { row_layout(:vertical) { fill true center true } label(:center) { text "Whatever you see inside the app composite\nwill get printed when clicking the Print button." font height: 16 } button { text 'Print' on_widget_selected do # The widget#print method automates all the work seen in Hello, Print Dialog! # the caveat is it assumes everything fits on one page unless @composite.print message_box { text 'Unable To Print' message 'Sorry! Printing is not supported on this platform!' }.open end end } } } } end HelloPrint.launch
ruby
MIT
449cf07ada1ec965ae2ac91715ccdf22488df4ca
2026-01-04T17:52:38.125591Z
false
AndyObtiva/glimmer-dsl-swt
https://github.com/AndyObtiva/glimmer-dsl-swt/blob/449cf07ada1ec965ae2ac91715ccdf22488df4ca/samples/hello/hello_shape.rb
samples/hello/hello_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-dsl-swt' class HelloShape include Glimmer::UI::CustomShell body { shell { text 'Hello, Shape!' minimum_size 200, 225 @canvas = canvas { background :white 15.times { |n| x_location = (rand*125).to_i%200 + (rand*15).to_i y_location = (rand*125).to_i%200 + (rand*15).to_i foreground_color = rgb(rand*255, rand*255, rand*255) a_stick_figure = stick_figure(x_location, y_location, 35+n*2, 35+n*2) { foreground foreground_color drag_and_move true # on mouse click, change color on_mouse_up do a_stick_figure.foreground = rgb(rand*255, rand*255, rand*255) end } } } } } # method-based custom shape using `shape` keyword as a composite shape containing nested shapes # See HelloCustomShape sample for a class-based custom shape alternative that enables extracting custom shape to a separate class/file def stick_figure(x, y, width, height, &block) head_width = width*0.2 head_height = height*0.2 trunk_height = height*0.4 extremity_length = height*0.4 shape(x + head_width/2.0 + extremity_length, y) { # common attributes go here before nested shapes block.call # invoking content block (e.g. used from the outside to set foreground) # nested shapes go here oval(0, 0, head_width, head_height) line(head_width/2.0, head_height, head_width/2.0, head_height + trunk_height) line(head_width/2.0, head_height + trunk_height, head_width/2.0 + extremity_length, head_height + trunk_height + extremity_length) line(head_width/2.0, head_height + trunk_height, head_width/2.0 - extremity_length, head_height + trunk_height + extremity_length) line(head_width/2.0, head_height*2, head_width/2.0 + extremity_length, head_height + trunk_height - extremity_length) line(head_width/2.0, head_height*2, head_width/2.0 - extremity_length, head_height + trunk_height - extremity_length) } end end HelloShape.launch
ruby
MIT
449cf07ada1ec965ae2ac91715ccdf22488df4ca
2026-01-04T17:52:38.125591Z
false
AndyObtiva/glimmer-dsl-swt
https://github.com/AndyObtiva/glimmer-dsl-swt/blob/449cf07ada1ec965ae2ac91715ccdf22488df4ca/samples/hello/hello_canvas_transform.rb
samples/hello/hello_canvas_transform.rb
require 'glimmer-dsl-swt' include Glimmer glimmer_logo = File.expand_path('../../icons/scaffold_app.png', __dir__) shell { text 'Hello, Canvas Transform!' minimum_size (OS.windows? ? 347 : 330), (OS.windows? ? 372 : 352) canvas { background :white image(glimmer_logo, 0, 0) { transform { translation 110, 110 rotation 90 scale 0.21, 0.21 # also supports inversion, identity, shear, and multiplication {transform properties} } } image(glimmer_logo, 0, 0) { transform { translation 110, 220 scale 0.21, 0.21 } } image(glimmer_logo, 0, 0) { transform { translation 220, 220 rotation 270 scale 0.21, 0.21 } } image(glimmer_logo, 0, 0) { transform { translation 220, 110 rotation 180 scale 0.21, 0.21 } } } }.open
ruby
MIT
449cf07ada1ec965ae2ac91715ccdf22488df4ca
2026-01-04T17:52:38.125591Z
false
AndyObtiva/glimmer-dsl-swt
https://github.com/AndyObtiva/glimmer-dsl-swt/blob/449cf07ada1ec965ae2ac91715ccdf22488df4ca/samples/hello/hello_tab.rb
samples/hello/hello_tab.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' class HelloTab include Glimmer::UI::CustomShell body { shell { text 'Hello, Tab!' tab_folder { tab_item { text 'English' tool_tip_text 'English Greeting' label { text 'Hello, World!' } } tab_item { text 'French' tool_tip_text 'French Greeting' label { text 'Bonjour, Univers!' } } } } } end HelloTab.launch
ruby
MIT
449cf07ada1ec965ae2ac91715ccdf22488df4ca
2026-01-04T17:52:38.125591Z
false
AndyObtiva/glimmer-dsl-swt
https://github.com/AndyObtiva/glimmer-dsl-swt/blob/449cf07ada1ec965ae2ac91715ccdf22488df4ca/samples/hello/hello_checkbox.rb
samples/hello/hello_checkbox.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' class HelloCheckbox class Person attr_accessor :skiing, :snowboarding, :snowmobiling, :snowshoeing def initialize reset_activities! end def reset_activities! self.skiing = false self.snowboarding = true self.snowmobiling = false self.snowshoeing = false end end include Glimmer::UI::CustomShell before_body do @person = Person.new end body { shell { text 'Hello, Checkbox!' row_layout :vertical label { text 'Check all snow activities you are interested in:' font style: :bold } composite { checkbox { text 'Skiing' selection <=> [@person, :skiing] } checkbox { text 'Snowboarding' selection <=> [@person, :snowboarding] } checkbox { text 'Snowmobiling' selection <=> [@person, :snowmobiling] } checkbox { text 'Snowshoeing' selection <=> [@person, :snowshoeing] } } button { text 'Reset Activities' on_widget_selected do @person.reset_activities! end } } } end HelloCheckbox.launch
ruby
MIT
449cf07ada1ec965ae2ac91715ccdf22488df4ca
2026-01-04T17:52:38.125591Z
false
AndyObtiva/glimmer-dsl-swt
https://github.com/AndyObtiva/glimmer-dsl-swt/blob/449cf07ada1ec965ae2ac91715ccdf22488df4ca/samples/hello/hello_sash_form.rb
samples/hello/hello_sash_form.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' class SashFormPresenter attr_accessor :sash_width, :sash_color, :orientation def initialize self.sash_width = 10 self.orientation = :horizontal end def orientation_options [:horizontal, :vertical] end end @presenter = SashFormPresenter.new include Glimmer shell { grid_layout 1, false minimum_size 740, 0 text 'Hello, Sash Form!' @sash_form = sash_form { layout_data(:fill, :fill, true, true) { height_hint 200 } sash_width <=> [@presenter, :sash_width] background <=> [@presenter, :sash_color] orientation <=> [@presenter, :orientation] weights 1, 2 @green_label = label { text 'Hello, (resize >>)' background :dark_green foreground :white font height: 30 } @red_label = label { text '(<< resize) Sash Form!' background :red foreground :white font height: 30 } } composite { layout_data(:fill, :fill, true, true) grid_layout 2, true label { layout_data(:right, :center, true, false) text 'Sash Width:' font height: 16 } spinner { layout_data(:fill, :center, true, false) { width_hint 100 } selection <=> [@presenter, :sash_width] font height: 16 } label { layout_data(:right, :center, true, false) text 'Sash Color:' font height: 16 } button { layout_data :fill, :center, true, false text "Choose Color..." on_widget_selected do @presenter.sash_color = color_dialog.open end } label { layout_data(:right, :center, true, false) text 'Orientation:' font height: 16 } combo(:read_only, :border) { layout_data(:fill, :center, true, false) { width_hint 100 } selection <=> [@presenter, :orientation] font height: 16 } button { layout_data(:fill, :center, true, false) text 'Maximize Green Label' foreground :dark_green font height: 16 on_widget_selected do @sash_form.maximized_control = @green_label end } button { layout_data(:fill, :center, true, false) text 'Maximize Red Label' foreground :red font height: 16 on_widget_selected do @sash_form.maximized_control = @red_label end } button { layout_data(:fill, :center, true, false) { horizontal_span 2 } text 'Maximize None' font height: 16 on_widget_selected do @sash_form.maximized_control = nil end } } }.open
ruby
MIT
449cf07ada1ec965ae2ac91715ccdf22488df4ca
2026-01-04T17:52:38.125591Z
false
AndyObtiva/glimmer-dsl-swt
https://github.com/AndyObtiva/glimmer-dsl-swt/blob/449cf07ada1ec965ae2ac91715ccdf22488df4ca/samples/hello/hello_directory_dialog.rb
samples/hello/hello_directory_dialog.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' class HelloDirectoryDialog include Glimmer::UI::CustomShell attr_accessor :selected_directory before_body do @selected_directory = 'Please select a directory.' end body { shell { minimum_size 400, 0 grid_layout text 'Hello, Directory Dialog!' label { text 'Selected Directory:' font height: 14, style: :bold } label { layout_data :fill, :center, true, false text <= [self, :selected_directory] font height: 14 } button { text "Browse..." on_widget_selected do self.selected_directory = directory_dialog.open end } } } end HelloDirectoryDialog.launch
ruby
MIT
449cf07ada1ec965ae2ac91715ccdf22488df4ca
2026-01-04T17:52:38.125591Z
false
AndyObtiva/glimmer-dsl-swt
https://github.com/AndyObtiva/glimmer-dsl-swt/blob/449cf07ada1ec965ae2ac91715ccdf22488df4ca/samples/hello/hello_drag_and_drop.rb
samples/hello/hello_drag_and_drop.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' class Location attr_accessor :country def country_options %w[USA Canada Mexico Columbia UK Australia Germany Italy Spain] end end @location = Location.new include Glimmer shell { text 'Hello, Drag and Drop!' tab_folder { tab_item { fill_layout text 'List' list { selection <=> [@location, :country] # Option 1: Automatic Drag Data Setting drag_source true # Option 2: Manual Drag Data Setting # on_drag_set_data do |event| # drag_widget = event.widget.control # event.data = drag_widget.selection.first # end # Option 3: Full Customization of Drag Source (details at: https://www.eclipse.org/articles/Article-SWT-DND/DND-in-SWT.html) # drag_source(:drop_copy) { # options: :drop_copy, :drop_link, :drop_move, :drop_target_move # transfer :text # options: :text, :file, :rtf # # on_drag_start do |event| # drag_widget = event.widget.control.data('proxy') # obtain Glimmer widget proxy since it permits nicer syntax for setting cursor via symbol # drag_widget.cursor = :wait # end # # on_drag_set_data do |event| # drag_widget = event.widget.control # event.data = drag_widget.selection.first # end # # on_drag_finished do |event| # drag_widget = event.widget.control.data('proxy') # obtain Glimmer widget proxy since it permits nicer syntax for setting cursor via symbol # drag_widget.cursor = :arrow # end # } } list { # Option 1: Automatic Drop Data Consumption drop_target true # drop_target :unique # setting drop_target to :unique makes the list not add the same data twice # Option 2: Manual Drop Data Consumption # on_drop do |event| # drop_widget = event.widget.control # drop_widget.add(event.data) # drop_widget.select(drop_widget.items.count - 1) # end # Option 3: Full Customization of Drop Target (details at: https://www.eclipse.org/articles/Article-SWT-DND/DND-in-SWT.html) # drop_target(:drop_copy) { # options: :drop_copy, :drop_link, :drop_move, :drop_target_move # transfer :text # options: :text, :file, :rtf # # on_drag_enter do |event| # ### event.detail = DND::DROP_NONE # To reject a drop, you can set event.detail to DND::DROP_NONE # drop_widget = event.widget.control.data('proxy') # obtain Glimmer widget proxy since it permits nicer syntax for setting background via symbol # drop_widget.background = :red # end # # on_drag_leave do |event| # drop_widget = event.widget.control.data('proxy') # obtain Glimmer widget proxy since it permits nicer syntax for setting background via symbol # drop_widget.background = :white # end # # on_drop do |event| # drop_widget = event.widget.control.data('proxy') # obtain Glimmer widget proxy since it permits nicer syntax for setting background/cursor via symbol # drop_widget.background = :white # drop_widget.add(event.data) # drop_widget.select(drop_widget.items.count - 1) # drop_widget.cursor = :arrow # end # } } } tab_item { grid_layout 2, true text 'Label' label { layout_data { horizontal_span 2 } text 'Drag text from any label and drop it unto another label' } { Argentina: :green, Brazil: :red, Finland: :yellow, Sweden: :magenta, Denmark: :gray, Iceland: :cyan }.each do |country, color| label { layout_data :fill, :fill, true, true text country font height: 20 background color drag_source true drop_target true } end } tab_item { grid_layout 2, true text 'Text' label { text 'Drag' } label { text 'Drop To Insert' } text { layout_data :fill, :center, true, false text 'Text1' drag_source true } text { layout_data :fill, :center, true, false text 'Drop To Insert' drop_target true } label { text 'Drag' } label { text 'Drop To Replace' } text { layout_data :fill, :center, true, false text 'Text2' drag_source true } text { layout_data :fill, :center, true, false text 'Drop To Replace' drop_target :replace } } tab_item { grid_layout 2, true text 'Spinner' label { text 'Drag' } label { text 'Drop To Replace' } spinner { layout_data :fill, :center, true, false selection 30 drag_source true } spinner { layout_data :fill, :center, true, false drop_target true } } tab_item { fill_layout text 'File' @drop_zone_label = label(:center, :wrap) { text 'Drop One File Or More Here' background :white rectangle { foreground :black line_width 4 line_style :dash } drop_target(:drop_copy) { transfer :file on_drag_enter do |event| drop_widget = event.widget.control.data('proxy') # obtain Glimmer widget proxy since it permits nicer syntax for setting background via symbol drop_widget.background = :yellow end on_drag_leave do |event| drop_widget = event.widget.control.data('proxy') # obtain Glimmer widget proxy since it permits nicer syntax for setting background via symbol drop_widget.background = :white end on_drop do |event| drop_widget = event.widget.control.data('proxy') # obtain Glimmer widget proxy since it permits nicer syntax for setting background/cursor via symbol drop_widget.background = :white @drop_zone_label.text = event.data.to_a.join("\n") end } } } } }.open
ruby
MIT
449cf07ada1ec965ae2ac91715ccdf22488df4ca
2026-01-04T17:52:38.125591Z
false
AndyObtiva/glimmer-dsl-swt
https://github.com/AndyObtiva/glimmer-dsl-swt/blob/449cf07ada1ec965ae2ac91715ccdf22488df4ca/samples/hello/hello_menu_bar.rb
samples/hello/hello_menu_bar.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' include Glimmer COLORS = [:white, :red, :yellow, :green, :blue, :magenta, :gray, :black] shell { grid_layout { margin_width 0 margin_height 0 } text 'Hello, Menu Bar!' @label = label(:center) { font height: 50 text 'Check Out The Menu Bar Above!' } menu_bar { menu { text '&File' menu_item { text '&New' accelerator :command, :N on_widget_selected do message_box { text 'New' message 'New file created.' }.open end } menu_item { text '&Open...' accelerator :command, :O on_widget_selected do message_box { text 'Open' message 'Opening File...' }.open end } menu { text 'Open &Recent' menu_item { text 'File 1' on_widget_selected do message_box { text 'File 1' message 'File 1 Contents' }.open end } menu_item { text 'File 2' on_widget_selected do message_box { text 'File 2' message 'File 2 Contents' }.open end } } menu_item(:separator) menu_item { text 'E&xit' on_widget_selected do exit(0) end } } menu { text '&Edit' menu_item { text 'Cut' accelerator :command, :X } menu_item { text 'Copy' accelerator :command, :C } menu_item { text 'Paste' accelerator :command, :V } } menu { text '&Options' menu_item(:radio) { text '&Enabled' on_widget_selected do @select_one_menu.enabled = true @select_multiple_menu.enabled = true end } @select_one_menu = menu { text '&Select One' enabled false menu_item(:radio) { text 'Option 1' } menu_item(:radio) { text 'Option 2' } menu_item(:radio) { text 'Option 3' } } @select_multiple_menu = menu { text '&Select Multiple' enabled false menu_item(:check) { text 'Option 4' } menu_item(:check) { text 'Option 5' } menu_item(:check) { text 'Option 6' } } } menu { text '&Language' ['denmark', 'finland', 'france', 'germany', 'italy', 'mexico', 'netherlands', 'norway', 'usa'].each do |image_name| menu_item(:radio) { |a_menu_item| image File.expand_path("images/#{image_name}.png", __dir__) selection image_name == 'usa' on_widget_selected do if a_menu_item.selection message_box { text 'Language Selection' message "You selected the language of #{image_name.capitalize}!" }.open end end } end } menu { text '&Country' ['denmark', 'finland', 'france', 'germany', 'italy', 'mexico', 'netherlands', 'norway', 'usa'].each do |image_name| menu_item(:radio) { |a_menu_item| text image_name.capitalize image File.expand_path("images/#{image_name}.png", __dir__) selection image_name == 'usa' on_widget_selected do if a_menu_item.selection message_box { text 'Country Selection' message "You selected the country of #{image_name.capitalize}!" }.open end end } end } menu { text '&Format' menu { text '&Background Color' COLORS.each { |color_style| menu_item(:radio) { text color_style.to_s.split('_').map(&:capitalize).join(' ') on_widget_selected do @label.background = color_style end } } } menu { text 'Foreground &Color' COLORS.each { |color_style| menu_item(:radio) { text color_style.to_s.split('_').map(&:capitalize).join(' ') on_widget_selected do @label.foreground = color_style end } } } } menu { text '&View' menu_item(:radio) { text 'Small' on_widget_selected do @label.font = {height: 25} @label.parent.pack end } menu_item(:radio) { text 'Medium' selection true on_widget_selected do @label.font = {height: 50} @label.parent.pack end } menu_item(:radio) { text 'Large' on_widget_selected do @label.font = {height: 75} @label.parent.pack end } } menu { text '&Help' menu_item { text '&Manual' accelerator :command, :shift, :M on_widget_selected do message_box { text 'Manual' message 'Manual Contents' }.open end } menu_item { text '&Tutorial' accelerator :command, :shift, :T on_widget_selected do message_box { text 'Tutorial' message 'Tutorial Contents' }.open end } menu_item(:separator) menu_item { text '&Report an Issue...' on_widget_selected do message_box { text 'Report an Issue' message 'Reporting an issue...' }.open end } } } }.open
ruby
MIT
449cf07ada1ec965ae2ac91715ccdf22488df4ca
2026-01-04T17:52:38.125591Z
false
AndyObtiva/glimmer-dsl-swt
https://github.com/AndyObtiva/glimmer-dsl-swt/blob/449cf07ada1ec965ae2ac91715ccdf22488df4ca/samples/hello/hello_custom_shape.rb
samples/hello/hello_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-dsl-swt' # Creates a class-based custom shape representing the `stick_figure` keyword by convention class StickFigure include Glimmer::UI::CustomShape options :figure_x, :figure_y, :figure_width, :figure_height before_body do @head_width = figure_width*0.2 @head_height = figure_height*0.2 @trunk_height = figure_height*0.4 @extremity_length = figure_height*0.4 end body { shape(figure_x + @head_width/2.0 + @extremity_length, figure_y) { oval(0, 0, @head_width, @head_height) line(@head_width/2.0, @head_height, @head_width/2.0, @head_height + @trunk_height) line(@head_width/2.0, @head_height + @trunk_height, @head_width/2.0 + @extremity_length, @head_height + @trunk_height + @extremity_length) line(@head_width/2.0, @head_height + @trunk_height, @head_width/2.0 - @extremity_length, @head_height + @trunk_height + @extremity_length) line(@head_width/2.0, @head_height*2, @head_width/2.0 + @extremity_length, @head_height + @trunk_height - @extremity_length) line(@head_width/2.0, @head_height*2, @head_width/2.0 - @extremity_length, @head_height + @trunk_height - @extremity_length) } } end class HelloCustomShape include Glimmer::UI::Application WIDTH = 220 HEIGHT = 235 body { shell { text 'Hello, Custom Shape!' minimum_size WIDTH, HEIGHT @canvas = canvas { background :white 15.times do |n| x_location = (rand*WIDTH/2).to_i%WIDTH + (rand*15).to_i y_location = (rand*HEIGHT/2).to_i%HEIGHT + (rand*15).to_i foreground_color = rgb(rand*255, rand*255, rand*255) a_stick_figure = stick_figure(figure_x: x_location, figure_y: y_location, figure_width: 35+n*2, figure_height: 35+n*2) { foreground foreground_color drag_and_move true # on mouse click, change color on_mouse_up do a_stick_figure.foreground = rgb(rand*255, rand*255, rand*255) end } end } } } end HelloCustomShape.launch
ruby
MIT
449cf07ada1ec965ae2ac91715ccdf22488df4ca
2026-01-04T17:52:38.125591Z
false
AndyObtiva/glimmer-dsl-swt
https://github.com/AndyObtiva/glimmer-dsl-swt/blob/449cf07ada1ec965ae2ac91715ccdf22488df4ca/samples/hello/hello_scale.rb
samples/hello/hello_scale.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' class HelloScale include Glimmer::UI::CustomShell attr_accessor :value before_body do @value = 50 end body { shell { fill_layout :vertical text 'Hello, Scale!' label(:center) { text <= [self, :value] } scale { # optionally takes :vertical or :horizontal (default) SWT style minimum 0 maximum 100 selection <=> [self, :value] } } } end HelloScale.launch
ruby
MIT
449cf07ada1ec965ae2ac91715ccdf22488df4ca
2026-01-04T17:52:38.125591Z
false
AndyObtiva/glimmer-dsl-swt
https://github.com/AndyObtiva/glimmer-dsl-swt/blob/449cf07ada1ec965ae2ac91715ccdf22488df4ca/samples/hello/hello_spinner.rb
samples/hello/hello_spinner.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' class HelloSpinner class Person attr_accessor :donation end include Glimmer::UI::CustomShell before_body do @person = Person.new @person.donation = 500 # in cents end body { shell { grid_layout text 'Hello, Spinner!' label { text 'Please select the amount you would like to donate to the poor:' } composite { grid_layout 3, false label { layout_data { width_hint 240 } text 'Amount:' font style: :bold } label { text '$' } spinner { digits 2 # digits after the decimal point minimum 100 # minimum value (including digits after the decimal point) maximum 15000 # maximum value (including digits after the decimal point) increment 500 # increment on up and down (including digits after the decimal point) page_increment 5000 # page increment on page up and page down (including digits after the decimal point) selection <=> [@person, :donation] # selection must be set last if other properties are configured to ensure value is within bounds } label { layout_data(:fill, :center, true, false) text <=> [@person, :donation, on_read: ->(value) { "Thank you for your donation of $#{"%.2f" % (value.to_f / 100.0)}"}] } } } } end HelloSpinner.launch
ruby
MIT
449cf07ada1ec965ae2ac91715ccdf22488df4ca
2026-01-04T17:52:38.125591Z
false
AndyObtiva/glimmer-dsl-swt
https://github.com/AndyObtiva/glimmer-dsl-swt/blob/449cf07ada1ec965ae2ac91715ccdf22488df4ca/samples/hello/hello_code_text.rb
samples/hello/hello_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-dsl-swt' class HelloCodeText include Glimmer::UI::CustomShell attr_accessor :ruby_code, :js_code, :html_code before_body do self.ruby_code = <<~RUBY greeting = 'Hello, World!' include Glimmer shell { text 'Glimmer' label { text greeting font height: 30, style: :bold } }.open RUBY self.js_code = <<~JS function greet(greeting) { alert(greeting); } var greetingString = 'Hello, World!'; greet(greetingString); var moreGreetings = ['Howdy!', 'Aloha!', 'Hey!'] for(var greeting of moreGreetings) { greet(greeting) } JS self.html_code = <<~HTML <html> <body> <section class="accordion"> <form method="post" id="name"> <label for="name"> Name </label> <input name="name" type="text" /> <input type="submit" /> </form> </section> </body> </html> HTML end body { shell { minimum_size 640, 480 text 'Hello, Code Text!' tab_folder { tab_item { fill_layout text 'Ruby (glimmer theme)' # Note: code_text theme is currently ignored in dark mode code_text(language: 'ruby', theme: 'glimmer', lines: true) { # theme is currently ignored in dark mode text <=> [self, :ruby_code] } } tab_item { fill_layout text 'JavaScript (pastie theme)' # Note: code_text theme is currently ignored in dark mode code_text(:multi, :h_scroll, :v_scroll, language: 'javascript', theme: 'pastie', lines: {width: 2}) { root { grid_layout(2, false) { margin_width 2 } background Display.system_dark_theme? ? :black : :white } line_numbers { background Display.system_dark_theme? ? :black : :white } text <=> [self, :js_code] } } tab_item { fill_layout text 'HTML (github theme)' # Note: code_text theme is currently ignored in dark mode code_text(language: 'html', theme: 'github') { # default is lines: false text <=> [self, :html_code] } } } } } end HelloCodeText.launch
ruby
MIT
449cf07ada1ec965ae2ac91715ccdf22488df4ca
2026-01-04T17:52:38.125591Z
false
AndyObtiva/glimmer-dsl-swt
https://github.com/AndyObtiva/glimmer-dsl-swt/blob/449cf07ada1ec965ae2ac91715ccdf22488df4ca/samples/hello/hello_cursor.rb
samples/hello/hello_cursor.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' class HelloCursor include Glimmer::UI::CustomShell attr_accessor :selected_cursor # This method matches the name of the :selected_cursor property by convention def selected_cursor_options Glimmer::SWT::SWTProxy.cursor_options end before_body do self.selected_cursor = :arrow end body { shell { grid_layout text 'Hello, Cursor!' cursor <= [self, :selected_cursor] label { text 'Please select a cursor style and see it change the mouse cursor (varies per platform):' font style: :bold cursor :no } radio_group { grid_layout 5, true selection <=> [self, :selected_cursor] } } } end HelloCursor.launch
ruby
MIT
449cf07ada1ec965ae2ac91715ccdf22488df4ca
2026-01-04T17:52:38.125591Z
false
AndyObtiva/glimmer-dsl-swt
https://github.com/AndyObtiva/glimmer-dsl-swt/blob/449cf07ada1ec965ae2ac91715ccdf22488df4ca/samples/hello/hello_table.rb
samples/hello/hello_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-dsl-swt' class HelloTable class BaseballGame class << self attr_accessor :selected_game def all_playoff_games @all_playoff_games ||= { 'NLDS' => [ new(Time.new(2037, 10, 6, 12, 0), 'Chicago Cubs', 'Milwaukee Brewers', 'Free Bobblehead'), new(Time.new(2037, 10, 7, 12, 0), 'Chicago Cubs', 'Milwaukee Brewers'), new(Time.new(2037, 10, 8, 12, 0), 'Milwaukee Brewers', 'Chicago Cubs'), new(Time.new(2037, 10, 9, 12, 0), 'Milwaukee Brewers', 'Chicago Cubs'), new(Time.new(2037, 10, 10, 12, 0), 'Milwaukee Brewers', 'Chicago Cubs', 'Free Umbrella'), new(Time.new(2037, 10, 6, 18, 0), 'Cincinnati Reds', 'St Louis Cardinals', 'Free Bobblehead'), new(Time.new(2037, 10, 7, 18, 0), 'Cincinnati Reds', 'St Louis Cardinals'), new(Time.new(2037, 10, 8, 18, 0), 'St Louis Cardinals', 'Cincinnati Reds'), new(Time.new(2037, 10, 9, 18, 0), 'St Louis Cardinals', 'Cincinnati Reds'), new(Time.new(2037, 10, 10, 18, 0), 'St Louis Cardinals', 'Cincinnati Reds', 'Free Umbrella'), ], 'ALDS' => [ new(Time.new(2037, 10, 6, 12, 0), 'New York Yankees', 'Boston Red Sox', 'Free Bobblehead'), new(Time.new(2037, 10, 7, 12, 0), 'New York Yankees', 'Boston Red Sox'), new(Time.new(2037, 10, 8, 12, 0), 'Boston Red Sox', 'New York Yankees'), new(Time.new(2037, 10, 9, 12, 0), 'Boston Red Sox', 'New York Yankees'), new(Time.new(2037, 10, 10, 12, 0), 'Boston Red Sox', 'New York Yankees', 'Free Umbrella'), new(Time.new(2037, 10, 6, 18, 0), 'Houston Astros', 'Cleveland Indians', 'Free Bobblehead'), new(Time.new(2037, 10, 7, 18, 0), 'Houston Astros', 'Cleveland Indians'), new(Time.new(2037, 10, 8, 18, 0), 'Cleveland Indians', 'Houston Astros'), new(Time.new(2037, 10, 9, 18, 0), 'Cleveland Indians', 'Houston Astros'), new(Time.new(2037, 10, 10, 18, 0), 'Cleveland Indians', 'Houston Astros', 'Free Umbrella'), ], 'NLCS' => [ new(Time.new(2037, 10, 12, 12, 0), 'Chicago Cubs', 'Cincinnati Reds', 'Free Towel'), new(Time.new(2037, 10, 13, 12, 0), 'Chicago Cubs', 'Cincinnati Reds'), new(Time.new(2037, 10, 14, 12, 0), 'Cincinnati Reds', 'Chicago Cubs'), new(Time.new(2037, 10, 15, 18, 0), 'Cincinnati Reds', 'Chicago Cubs'), new(Time.new(2037, 10, 16, 18, 0), 'Cincinnati Reds', 'Chicago Cubs'), new(Time.new(2037, 10, 17, 18, 0), 'Chicago Cubs', 'Cincinnati Reds'), new(Time.new(2037, 10, 18, 12, 0), 'Chicago Cubs', 'Cincinnati Reds', 'Free Poncho'), ], 'ALCS' => [ new(Time.new(2037, 10, 12, 12, 0), 'Houston Astros', 'Boston Red Sox', 'Free Towel'), new(Time.new(2037, 10, 13, 12, 0), 'Houston Astros', 'Boston Red Sox'), new(Time.new(2037, 10, 14, 12, 0), 'Boston Red Sox', 'Houston Astros'), new(Time.new(2037, 10, 15, 18, 0), 'Boston Red Sox', 'Houston Astros'), new(Time.new(2037, 10, 16, 18, 0), 'Boston Red Sox', 'Houston Astros'), new(Time.new(2037, 10, 17, 18, 0), 'Houston Astros', 'Boston Red Sox'), new(Time.new(2037, 10, 18, 12, 0), 'Houston Astros', 'Boston Red Sox', 'Free Poncho'), ], 'World Series' => [ new(Time.new(2037, 10, 20, 18, 0), 'Chicago Cubs', 'Boston Red Sox', 'Free Baseball Cap'), new(Time.new(2037, 10, 21, 18, 0), 'Chicago Cubs', 'Boston Red Sox'), new(Time.new(2037, 10, 22, 18, 0), 'Boston Red Sox', 'Chicago Cubs'), new(Time.new(2037, 10, 23, 18, 0), 'Boston Red Sox', 'Chicago Cubs'), new(Time.new(2037, 10, 24, 18, 0), 'Boston Red Sox', 'Chicago Cubs'), new(Time.new(2037, 10, 25, 18, 0), 'Chicago Cubs', 'Boston Red Sox'), new(Time.new(2037, 10, 26, 18, 0), 'Chicago Cubs', 'Boston Red Sox', 'Free World Series Polo'), ] } end def playoff_type @playoff_type ||= 'World Series' end def playoff_type=(new_playoff_type) @playoff_type = new_playoff_type self.schedule=(all_playoff_games[@playoff_type]) self.selected_game = schedule.first unless selected_game.nil? end def playoff_type_options all_playoff_games.keys end def schedule @schedule ||= all_playoff_games[playoff_type] end def schedule=(new_schedule) @schedule = new_schedule end end include Glimmer include Glimmer::DataBinding::ObservableModel TEAM_BALLPARKS = { 'Boston Red Sox' => 'Fenway Park', 'Chicago Cubs' => 'Wrigley Field', 'Cincinnati Reds' => 'Great American Ball Park', 'Cleveland Indians' => 'Progressive Field', 'Houston Astros' => 'Minute Maid Park', 'Milwaukee Brewers' => 'Miller Park', 'New York Yankees' => 'Yankee Stadium', 'St Louis Cardinals' => 'Busch Stadium', } ATTRIBUTES = [:game_date, :game_time, :home_team, :away_team, :ballpark, :promotion] ATTRIBUTES_BACKGROUND = ATTRIBUTES.map {|attribute| "#{attribute}_background"} ATTRIBUTES_FOREGROUND = ATTRIBUTES.map {|attribute| "#{attribute}_foreground"} ATTRIBUTES_FONT = ATTRIBUTES.map {|attribute| "#{attribute}_font"} ATTRIBUTES_IMAGE = ATTRIBUTES.map {|attribute| "#{attribute}_image"} attr_accessor *([:booked, :date_time] + ATTRIBUTES + ATTRIBUTES_BACKGROUND + ATTRIBUTES_FOREGROUND + ATTRIBUTES_FONT + ATTRIBUTES_IMAGE) alias booked? booked def initialize(date_time, home_team, away_team, promotion = 'N/A') self.date_time = date_time self.home_team = home_team self.away_team = away_team self.promotion = promotion self.ballpark_image = [File.expand_path('hello_table/baseball_park.png', __dir__), width: 20, height: 20] self.booked = false observe(self, :date_time) do |new_value| notify_observers(:game_time) end end def home_team=(home_team_value) if home_team_value != away_team @home_team = home_team_value self.ballpark = TEAM_BALLPARKS[@home_team] end end def away_team=(away_team_value) if away_team_value != home_team @away_team = away_team_value end end def date Date.new(date_time.year, date_time.month, date_time.day) end def time Time.new(0, 1, 1, date_time.hour, date_time.min, date_time.sec, '+00:00') end def game_date date_time.strftime("%m/%d/%Y") end def game_time date_time.strftime("%I:%M %p") end def home_team_options TEAM_BALLPARKS.keys end def away_team_options TEAM_BALLPARKS.keys end def ballpark_options [TEAM_BALLPARKS[@home_team], TEAM_BALLPARKS[@away_team]] end def to_s "#{home_team} vs #{away_team} at #{ballpark} on #{game_date} #{game_time}" end def book! self.booked = true self.background = :dark_green self.foreground = :white self.font = {style: :italic} "Thank you for booking #{to_s}" end # Sets background for all attributes def background=(color) self.game_date_background = color self.game_time_background = color self.home_team_background = color self.away_team_background = color self.ballpark_background = color self.promotion_background = color end # Sets foreground for all attributes def foreground=(color) self.game_date_foreground = color self.game_time_foreground = color self.home_team_foreground = color self.away_team_foreground = color self.ballpark_foreground = color self.promotion_foreground = color end # Sets font for all attributes def font=(font_properties) self.game_date_font = font_properties self.game_time_font = font_properties self.home_team_font = font_properties self.away_team_font = font_properties self.ballpark_font = font_properties self.promotion_font = font_properties end end include Glimmer::UI::CustomShell before_body do Display.app_name = 'Hello, Table!' end body { shell { grid_layout text 'Hello, Table!' background_image File.expand_path('hello_table/baseball_park.png', __dir__) image File.expand_path('hello_table/baseball_park.png', __dir__) label { layout_data :center, :center, true, false text 'BASEBALL PLAYOFF SCHEDULE' background :transparent if OS.windows? foreground rgb(94, 107, 103) font name: 'Optima', height: 38, style: :bold } combo(:read_only) { layout_data :center, :center, true, false selection <=> [BaseballGame, :playoff_type] font height: 14 } table(:editable) { |table_proxy| layout_data :fill, :fill, true, true table_column { text 'Game Date' width 150 sort_property :date # ensure sorting by real date value (not `game_date` string specified in items below) editor :date_drop_down, property: :date_time } table_column { text 'Game Time' width 150 sort_property :time # ensure sorting by real time value (not `game_time` string specified in items below) editor :time, property: :date_time } table_column { text 'Ballpark' width 180 editor :none } table_column { text 'Home Team' width 150 editor :combo, :read_only # read_only is simply an SWT style passed to combo widget } table_column { text 'Away Team' width 150 editor :combo, :read_only # read_only is simply an SWT style passed to combo widget } table_column { text 'Promotion' width 150 # default text editor is used here } # This is a contextual pop up menu that shows up when right-clicking table rows menu { menu_item { text 'Book' on_widget_selected do book_selected_game end } } # Data-bind table items (rows) to a model collection (BaseballGame.schedule), # automatically inferring model attributes from column names by convention # (e.g. 'Home Team' column assumes a `home_team` attribute on models) # # By convention, every inferred model attribute can be accompanied by extra # model attributes to set extra table properties with the following suffixes: # `_background`, `_foreground`, `_font`, and `_image` # # For example, for :game_date, model could also implement these related properties: # `game_date_background`, `game_date_foreground`, `game_date_font`, `game_date_image` items <=> [BaseballGame, :schedule] # Data-bind table selection selection <=> [BaseballGame, :selected_game] # Default initial sort property sort_property :date # Sort by these additional properties after handling sort by the column the user clicked additional_sort_properties :date, :time, :home_team, :away_team, :ballpark, :promotion on_key_pressed do |key_event| book_selected_game if key_event.keyCode == swt(:cr) end } button { text 'Book Selected Game' layout_data :center, :center, true, false font height: 14 enabled <= [BaseballGame, 'selected_game.booked', on_read: ->(value) { value == false }] on_widget_selected do book_selected_game end } } } def book_selected_game return if BaseballGame.selected_game.booked? message_box { text 'Baseball Game Booked!' message BaseballGame.selected_game.book! }.open end end HelloTable.launch
ruby
MIT
449cf07ada1ec965ae2ac91715ccdf22488df4ca
2026-01-04T17:52:38.125591Z
false
AndyObtiva/glimmer-dsl-swt
https://github.com/AndyObtiva/glimmer-dsl-swt/blob/449cf07ada1ec965ae2ac91715ccdf22488df4ca/samples/hello/hello_computed.rb
samples/hello/hello_computed.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' class HelloComputed class Contact attr_accessor :first_name, :last_name, :year_of_birth def initialize(attribute_map) @first_name = attribute_map[:first_name] @last_name = attribute_map[:last_name] @year_of_birth = attribute_map[:year_of_birth] end def name "#{last_name}, #{first_name}" end def age Time.now.year - year_of_birth.to_i rescue 0 end end include Glimmer::UI::CustomShell before_body do @contact = Contact.new( first_name: 'Barry', last_name: 'McKibbin', year_of_birth: 1985 ) end body { shell { text 'Hello, Computed!' composite { grid_layout { num_columns 2 make_columns_equal_width true horizontal_spacing 20 vertical_spacing 10 } label {text 'First &Name: '} text { fill_horizontally_layout_data text <=> [@contact, :first_name] } label {text '&Last Name: '} text { fill_horizontally_layout_data text <=> [@contact, :last_name] } label {text '&Year of Birth: '} text { fill_horizontally_layout_data text <=> [@contact, :year_of_birth] } label {text 'Name: '} label { fill_horizontally_layout_data text <= [@contact, :name, computed_by: [:first_name, :last_name]] } label {text 'Age: '} label { fill_horizontally_layout_data text <= [@contact, :age, on_write: :to_i, computed_by: [:year_of_birth]] } } } } def fill_horizontally_layout_data layout_data { horizontal_alignment :fill grab_excess_horizontal_space true } end end HelloComputed.launch
ruby
MIT
449cf07ada1ec965ae2ac91715ccdf22488df4ca
2026-01-04T17:52:38.125591Z
false
AndyObtiva/glimmer-dsl-swt
https://github.com/AndyObtiva/glimmer-dsl-swt/blob/449cf07ada1ec965ae2ac91715ccdf22488df4ca/samples/hello/hello_label.rb
samples/hello/hello_label.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' class HelloLabel include Glimmer::UI::CustomShell body { shell { text 'Hello, Label!' tab_folder { tab_item { text 'left-aligned' grid_layout 2, true 1.upto(3) do |n| label(:left) { # :left is default in English, so it is unnecessary layout_data :fill, :center, true, false text "Field #{n}" } text { layout_data :fill, :center, true, false text "Enter Field #{n}" } end } tab_item { text 'center-aligned' grid_layout 2, true 1.upto(3) do |n| label(:center) { layout_data :fill, :center, true, false text "Field #{n}" } text { layout_data :fill, :center, true, false text "Enter Field #{n}" } end } tab_item { text 'right-aligned' grid_layout 2, true 1.upto(3) do |n| label(:right) { layout_data :fill, :center, true, false text "Field #{n}" } text { layout_data :fill, :center, true, false text "Enter Field #{n}" } end } tab_item { text 'images' grid_layout 2, true ['denmark', 'finland', 'norway'].each do |image_name| label { layout_data :center, :center, true, false image File.expand_path("images/#{image_name}.png", __dir__) } text { layout_data :fill, :center, true, false text "Enter Field #{image_name.capitalize}" } end } tab_item { text 'background images' grid_layout 2, true ['italy', 'france', 'mexico'].each do |image_name| label { layout_data :center, :center, true, false background_image File.expand_path("images/#{image_name}.png", __dir__) text image_name.capitalize font height: 26, style: :bold } text { layout_data :fill, :center, true, false text "Enter Field #{image_name.capitalize}" } end } tab_item { text 'horizontal separator' grid_layout 2, true label { layout_data :fill, :center, true, false text "Field 1" } text { layout_data :fill, :center, true, false text "Enter Field 1" } label(:separator, :horizontal) { layout_data(:fill, :center, true, false) { horizontal_span 2 } } label { layout_data :fill, :center, true, false text "Field 2" } text { layout_data :fill, :center, true, false text "Enter Field 2" } } tab_item { text 'vertical separator' grid_layout 3, true label { layout_data :fill, :center, true, false text "Field 1" } label(:separator, :vertical) { layout_data(:center, :center, false, false) { vertical_span 3 } } text { layout_data :fill, :center, true, false text "Enter Field 1" } label { layout_data :fill, :center, true, false text "Field 2" } text { layout_data :fill, :center, true, false text "Enter Field 2" } label { layout_data :fill, :center, true, false text "Field 3" } text { layout_data :fill, :center, true, false text "Enter Field 3" } } } } } end HelloLabel.launch
ruby
MIT
449cf07ada1ec965ae2ac91715ccdf22488df4ca
2026-01-04T17:52:38.125591Z
false
AndyObtiva/glimmer-dsl-swt
https://github.com/AndyObtiva/glimmer-dsl-swt/blob/449cf07ada1ec965ae2ac91715ccdf22488df4ca/samples/hello/hello_radio_group.rb
samples/hello/hello_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-dsl-swt' # This sample demonstrates the use of a `radio_group` in Glimmer, which provides terser syntax # than HelloRadio for representing multiple radio buttons by relying on data-binding to # automatically spawn the `radio` widgets based on available options on the model. class HelloRadioGroup class Person attr_accessor :gender, :age_group def initialize reset! end def gender_options ['Male', 'Female'] end def age_group_options ['Child', 'Teen', 'Adult', 'Senior'] end def reset! self.gender = nil self.age_group = 'Adult' end end include Glimmer::UI::CustomShell before_body do @person = Person.new end body { shell { text 'Hello, Radio Group!' row_layout :vertical label { text 'Gender:' font style: :bold } radio_group { row_layout :horizontal selection <=> [@person, :gender] } label { text 'Age Group:' font style: :bold } radio_group { row_layout :horizontal selection <=> [@person, :age_group] } button { text 'Reset' on_widget_selected do @person.reset! end } } } end HelloRadioGroup.launch
ruby
MIT
449cf07ada1ec965ae2ac91715ccdf22488df4ca
2026-01-04T17:52:38.125591Z
false
AndyObtiva/glimmer-dsl-swt
https://github.com/AndyObtiva/glimmer-dsl-swt/blob/449cf07ada1ec965ae2ac91715ccdf22488df4ca/samples/hello/hello_message_box.rb
samples/hello/hello_message_box.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' include Glimmer shell { text 'Hello, Message Box!' button { text 'Please Click To Win a Surprise' on_widget_selected do message_box { text 'Surprise' message "Congratulations!\n\nYou won $1,000,000!" }.open end } }.open
ruby
MIT
449cf07ada1ec965ae2ac91715ccdf22488df4ca
2026-01-04T17:52:38.125591Z
false
AndyObtiva/glimmer-dsl-swt
https://github.com/AndyObtiva/glimmer-dsl-swt/blob/449cf07ada1ec965ae2ac91715ccdf22488df4ca/samples/hello/hello_slider.rb
samples/hello/hello_slider.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' class HelloSlider include Glimmer::UI::CustomShell attr_accessor :value before_body do @value = 50 end body { shell { fill_layout :vertical text 'Hello, Slider!' label(:center) { text <= [self, :value] } slider { # optionally takes :vertical or :horizontal (default) SWT style minimum 0 maximum 110 # leave room for 10 extra (slider stops at 100) page_increment 10 # page increment occurs when clicking area between slider and beginning or end selection <=> [self, :value] } } } end HelloSlider.launch
ruby
MIT
449cf07ada1ec965ae2ac91715ccdf22488df4ca
2026-01-04T17:52:38.125591Z
false
AndyObtiva/glimmer-dsl-swt
https://github.com/AndyObtiva/glimmer-dsl-swt/blob/449cf07ada1ec965ae2ac91715ccdf22488df4ca/samples/hello/hello_custom_shell.rb
samples/hello/hello_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-dsl-swt' require 'date' # This class declares an `email_shell` custom shell, aka custom window (by convention) # Used to view an email message class EmailShell # including Glimmer::UI::CustomShell enables declaring as an `email_shell` custom widget Glimmer GUI DSL keyword # Glimmer::UI::CustomShell is a specialized Glimmer::UI::CustomWidget that has `shell` as its `body_root` include Glimmer::UI::CustomShell # aliases: Glimmer::UI::CustomWindow & Glimmer::UI::Application # multiple options without default values options :parent_shell, :date, :subject, :from, :message # single option with default value option :to, default: '"John Irwin" <john.irwin@example.com>' before_body do # build a custom swt_style based on passed in swt style symbols (built-in CustomShell attribute) @swt_style = swt(:shell_trim, :modeless, *swt_style_symbols) end body { # pass received @swt_style through to shell to customize it (e.g. :dialog_trim for a blocking shell) shell(parent_shell, @swt_style) { grid_layout(2, false) text subject label { text 'Date:' } label { text date } label { text 'From:' } label { text from } label { text 'To:' } label { text to } label { text 'Subject:' } label { text subject } label { layout_data(:fill, :fill, true, true) { horizontal_span 2 vertical_indent 10 } background :white text message } } } end class HelloCustomShell include Glimmer::UI::Application # aliases: Glimmer::UI::CustomShell & Glimmer::UI::CustomWindow Email = Struct.new(:date, :subject, :from, :message, keyword_init: true) EmailSystem = Struct.new(:emails, :selected_email, keyword_init: true) before_body do @email_system = EmailSystem.new( emails: [ Email.new( date: DateTime.new(2029, 10, 22, 11, 3, 0).strftime('%F %I:%M %p'), subject: '3rd Week Report', from: '"Dianne Tux" <dianne.tux@example.com>', message: "Hello,\n\nI was wondering if you'd like to go over the weekly report sometime this afternoon.\n\nDianne" ), Email.new( date: DateTime.new(2029, 10, 21, 8, 1, 0).strftime('%F %I:%M %p'), subject: 'Glimmer Upgrade v100.0', from: '"Robert McGabbins" <robert.mcgabbins@example.com>', message: "Team,\n\nWe are upgrading to Glimmer version 100.0.\n\nEveryone pull the latest code!\n\nRegards,\n\nRobert McGabbins" ), Email.new( date: DateTime.new(2029, 10, 19, 16, 58, 0).strftime('%F %I:%M %p'), subject: 'Christmas Party', from: '"Lisa Ferreira" <lisa.ferreira@example.com>', message: "Merry Christmas,\n\nAll office Christmas Party arrangements have been set\n\nMake sure to bring a Secret Santa gift\n\nBest regards,\n\nLisa Ferreira" ), Email.new( date: DateTime.new(2029, 10, 16, 9, 43, 0).strftime('%F %I:%M %p'), subject: 'Glimmer Upgrade v99.0', from: '"Robert McGabbins" <robert.mcgabbins@example.com>', message: "Team,\n\nWe are upgrading to Glimmer version 99.0.\n\nEveryone pull the latest code!\n\nRegards,\n\nRobert McGabbins" ), Email.new( date: DateTime.new(2029, 10, 15, 11, 2, 0).strftime('%F %I:%M %p'), subject: '2nd Week Report', from: '"Dianne Tux" <dianne.tux@example.com>', message: "Hello,\n\nI was wondering if you'd like to go over the weekly report sometime this afternoon.\n\nDianne" ), Email.new( date: DateTime.new(2029, 10, 2, 10, 34, 0).strftime('%F %I:%M %p'), subject: 'Glimmer Upgrade v98.0', from: '"Robert McGabbins" <robert.mcgabbins@example.com>', message: "Team,\n\nWe are upgrading to Glimmer version 98.0.\n\nEveryone pull the latest code!\n\nRegards,\n\nRobert McGabbins" ), ] ) end body { shell { grid_layout text 'Hello, Custom Shell!' label { font height: 24, style: :bold text 'Emails:' } label { font height: 18 text 'Click an email to view its message' } table { layout_data :fill, :fill, true, true table_column { text 'Date' width 180 } table_column { text 'Subject' width 180 } table_column { text 'From' width 360 } items <=> [@email_system, :emails] selection <=> [@email_system, :selected_email] on_mouse_up do |event| open_email(@email_system.selected_email) end on_key_pressed do |event| if [swt(:cr), swt(:space)].include?(event.keyCode) open_email(@email_system.selected_email) end end } } } def open_email(email) return if email.nil? # open a custom email shell email_shell( parent_shell: body_root, date: email.date, subject: email.subject, from: email.from, message: email.message ).open end end HelloCustomShell.launch
ruby
MIT
449cf07ada1ec965ae2ac91715ccdf22488df4ca
2026-01-04T17:52:38.125591Z
false
AndyObtiva/glimmer-dsl-swt
https://github.com/AndyObtiva/glimmer-dsl-swt/blob/449cf07ada1ec965ae2ac91715ccdf22488df4ca/samples/hello/hello_c_tab.rb
samples/hello/hello_c_tab.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. # Country flag images were made by [Freepik](https://www.flaticon.com/authors/freepik) from [www.flaticon.com](http://www.flaticon.com) require 'glimmer-dsl-swt' # This is a sample for the Custom Tab widgets (c_tab_folder & c_tab_item), which are more customizable versions of tab_folder and tab_item. class HelloCTab include Glimmer::UI::CustomShell body { shell { row_layout text 'Hello, C Tab!' minimum_size 200, 200 c_tab_folder { # accepts styles: :close, :top, :bottom, :flat, :border, :single, :multi layout_data { width 1024 height 200 } c_tab_item(:close) { text 'English' tool_tip_text 'English Greeting' foreground :blue selection_foreground :dark_blue font name: 'Times New Roman', height: 30, style: [:bold, :italic] image File.expand_path('images/usa.png', __dir__) label { text 'Hello, World!' font name: 'Times New Roman', height: 90, style: [:bold, :italic] } } c_tab_item(:close) { text 'French' tool_tip_text 'French Greeting' foreground :blue selection_foreground :dark_blue font name: 'Times New Roman', height: 30, style: [:bold, :italic] image File.expand_path('images/france.png', __dir__) label { text 'Bonjour, Univers!' font name: 'Times New Roman', height: 90, style: [:bold, :italic] } } c_tab_item(:close) { text 'Spanish' tool_tip_text 'Spanish Greeting' foreground :blue selection_foreground :dark_blue font name: 'Times New Roman', height: 30, style: [:bold, :italic] image File.expand_path('images/mexico.png', __dir__) label { text 'Hola, Mundo!' font name: 'Times New Roman', height: 90, style: [:bold, :italic] } } c_tab_item(:close) { text 'German' tool_tip_text 'German Greeting' foreground :blue selection_foreground :dark_blue font name: 'Times New Roman', height: 30, style: [:bold, :italic] image File.expand_path('images/germany.png', __dir__) label { text 'Hallo, Welt!' font name: 'Times New Roman', height: 90, style: [:bold, :italic] } } c_tab_item(:close) { text 'Italian' tool_tip_text 'Italian Greeting' foreground :blue selection_foreground :dark_blue font name: 'Times New Roman', height: 30, style: [:bold, :italic] image File.expand_path('images/italy.png', __dir__) label { text 'Ciao, Mondo!' font name: 'Times New Roman', height: 90, style: [:bold, :italic] } } c_tab_item(:close) { text 'Dutch' tool_tip_text 'Dutch Greeting' foreground :blue selection_foreground :dark_blue font name: 'Times New Roman', height: 30, style: [:bold, :italic] image File.expand_path('images/netherlands.png', __dir__) label { text 'Hallo, Wereld!' font name: 'Times New Roman', height: 90, style: [:bold, :italic] } } c_tab_item(:close) { text 'Danish' tool_tip_text 'Danish Greeting' foreground :blue selection_foreground :dark_blue font name: 'Times New Roman', height: 30, style: [:bold, :italic] image File.expand_path('images/denmark.png', __dir__) label { text 'Hej, Verden!' font name: 'Times New Roman', height: 90, style: [:bold, :italic] } } c_tab_item(:close) { text 'Finnish' tool_tip_text 'Finnish Greeting' foreground :blue selection_foreground :dark_blue font name: 'Times New Roman', height: 30, style: [:bold, :italic] image File.expand_path('images/finland.png', __dir__) label { text 'Hei, Maailma!' font name: 'Times New Roman', height: 90, style: [:bold, :italic] } } c_tab_item(:close) { text 'Norwegian' tool_tip_text 'Norwegian Greeting' foreground :blue selection_foreground :dark_blue font name: 'Times New Roman', height: 30, style: [:bold, :italic] image File.expand_path('images/norway.png', __dir__) label { text 'Hei, Verden!' font name: 'Times New Roman', height: 90, style: [:bold, :italic] } } } } } end HelloCTab.launch
ruby
MIT
449cf07ada1ec965ae2ac91715ccdf22488df4ca
2026-01-04T17:52:38.125591Z
false
AndyObtiva/glimmer-dsl-swt
https://github.com/AndyObtiva/glimmer-dsl-swt/blob/449cf07ada1ec965ae2ac91715ccdf22488df4ca/samples/hello/hello_browser.rb
samples/hello/hello_browser.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' include Glimmer shell { text 'Hello, Browser!' minimum_size 1024, 860 browser { url 'https://brightonresort.com/about' } }.open
ruby
MIT
449cf07ada1ec965ae2ac91715ccdf22488df4ca
2026-01-04T17:52:38.125591Z
false
AndyObtiva/glimmer-dsl-swt
https://github.com/AndyObtiva/glimmer-dsl-swt/blob/449cf07ada1ec965ae2ac91715ccdf22488df4ca/samples/hello/hello_scrolled_composite.rb
samples/hello/hello_scrolled_composite.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' include Glimmer shell { grid_layout { margin_width 0 margin_height 0 } text 'Hello, Scrolled Composite!' maximum_size 400, 400 composite { layout_data { horizontal_alignment :center } row_layout button { text '<<' on_widget_selected do @scrolled_composite.set_origin(0, @scrolled_composite.origin.y) end } button { text '>>' on_widget_selected do @scrolled_composite.set_origin(@inner_composite.size.x, @scrolled_composite.origin.y) end } button { text '^^' on_widget_selected do @scrolled_composite.set_origin(@scrolled_composite.origin.x, 0) end } button { text 'vv' on_widget_selected do @scrolled_composite.set_origin(@scrolled_composite.origin.x, @inner_composite.size.y) end } } @scrolled_composite = scrolled_composite { layout_data :fill, :fill, true, true @inner_composite = composite { row_layout(:vertical) background :white 50.times do |n| label { layout_data { height 20 } text "Line #{n+1} has a lot of gibberish in it. In fact, it has so much gibberish that it does not fit the window horizontally, so scrollbars must be used to see all the text." background :white } end } } }.open
ruby
MIT
449cf07ada1ec965ae2ac91715ccdf22488df4ca
2026-01-04T17:52:38.125591Z
false
AndyObtiva/glimmer-dsl-swt
https://github.com/AndyObtiva/glimmer-dsl-swt/blob/449cf07ada1ec965ae2ac91715ccdf22488df4ca/samples/hello/hello_canvas_animation.rb
samples/hello/hello_canvas_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-dsl-swt' require 'bigdecimal' class HelloCanvasAnimation include Glimmer::UI::CustomShell attr_accessor :animation_every, :animation_fps, :animation_frame_count, :animation_duration_limit, :animation_started, :animation_finished before_body do @animation_every = 0.050 # seconds @animation_fps = 0 @animation_frame_count = 100 @animation_duration_limit = 0 # seconds @animation_started = true @animation_finished = false end body { shell { grid_layout(2, true) text 'Hello, Canvas Animation!' # row 1 button { layout_data(:fill, :center, true, false) text <= [self, :animation_started, on_read: ->(value) { value ? 'Stop' : 'Resume' }] enabled <= [self, :animation_finished, on_read: :!] on_widget_selected do if @animation.started? @animation.stop else @animation.start end end } button { layout_data(:fill, :center, true, false) text 'Restart' on_widget_selected do @animation.restart end } # row 2 label { text 'every' } label { text 'frames per second' } # row 3 spinner { layout_data(:fill, :center, true, false) digits 3 minimum 0 maximum 100 selection <=> [self, :animation_every, on_read: ->(v) {(BigDecimal(v.to_s)*1000).to_f}, on_write: ->(v) {(BigDecimal(v.to_s)/1000).to_f}] } spinner { layout_data(:fill, :center, true, false) minimum 0 maximum 100 selection <=> [self, :animation_fps] } # row 4 label { text 'frame count (0=unlimited)' } label { text 'duration limit (0=unlimited)' } # row 5 spinner { layout_data(:fill, :center, true, false) minimum 0 maximum 100 selection <=> [self, :animation_frame_count] } spinner { layout_data(:fill, :center, true, false) minimum 0 maximum 10 selection <=> [self, :animation_duration_limit] } canvas { layout_data(:fill, :fill, true, true) { horizontal_span 2 width_hint 320 height_hint 320 } @animation = animation { every <= [self, :animation_every] fps <= [self, :animation_fps] frame_count <= [self, :animation_frame_count] duration_limit <= [self, :animation_duration_limit] started <=> [self, :animation_started] finished <=> [self, :animation_finished] frame do |index| background rgb(index%100, index%100 + 100, index%55 + 200) oval(index*3%300, index*3%300, 20, 20) { background :yellow } end } } } } def animation_every=(value) @animation_every = value self.animation_fps = 0 if @animation_every.to_f > 0 end def animation_fps=(value) @animation_fps = value self.animation_every = 0 if @animation_fps.to_f > 0 end end HelloCanvasAnimation.launch
ruby
MIT
449cf07ada1ec965ae2ac91715ccdf22488df4ca
2026-01-04T17:52:38.125591Z
false
AndyObtiva/glimmer-dsl-swt
https://github.com/AndyObtiva/glimmer-dsl-swt/blob/449cf07ada1ec965ae2ac91715ccdf22488df4ca/samples/hello/hello_shell.rb
samples/hello/hello_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-dsl-swt' class HelloShell include Glimmer::UI::CustomShell body { # this is the initial shell that opens. If you close it, you close the app. shell { |root_shell_proxy| row_layout(:vertical) text 'Hello, Shell!' button { layout_data { width 200 height 50 } text "Nested Shell" on_widget_selected do # build a nested shell, meaning a shell that specifies its parent shell (root_shell_proxy) shell(root_shell_proxy) { # shell has fill_layout(:horizontal) by default with no margins text 'Nested Shell' label { font height: 20 text "Since this shell is nested, \nyou can hit ESC to close" } }.open end } button { layout_data { width 200 height 50 } text "Independent Shell" on_widget_selected do # build an independent shell, meaning a shell that is independent of its parent shell { # shell has fill_layout(:horizontal) by default with no margins text 'Independent Shell' label { font height: 20 text "Since this shell is independent, \nyou cannot close by hitting ESC" } }.open end } button { layout_data { width 200 height 50 } text "Close-Button Shell" on_widget_selected do shell(:close) { # shell has fill_layout(:horizontal) by default with no margins text 'Nested Shell' label { font height: 20 text "Shell with close button only\n(varies per platform)" } }.open end } button { layout_data { width 200 height 50 } text "Minimize-Button Shell" on_widget_selected do # build a nested shell, meaning a shell that specifies its parent shell (root_shell_proxy) shell(root_shell_proxy, :min) { # shell has fill_layout(:horizontal) by default with no margins text 'Minimize-Button Shell' label { font height: 20 text "Shell with minimize button only\n(varies per platform)" } }.open end } button { layout_data { width 200 height 50 } text "Maximize-Button Shell" on_widget_selected do # build a nested shell, meaning a shell that specifies its parent shell (root_shell_proxy) shell(root_shell_proxy, :max) { # shell has fill_layout(:horizontal) by default with no margins text 'Maximize-Button Shell' label { font height: 20 text "Shell with maximize button only\n(varies per platform)" } }.open end } button { layout_data { width 200 height 50 } text "Buttonless Shell" on_widget_selected do # build a nested shell, meaning a shell that specifies its parent shell (root_shell_proxy) shell(root_shell_proxy, :title) { # shell has fill_layout(:horizontal) by default with no margins text 'Buttonless Shell' label { font height: 20 text "Buttonless shell (title only)\n(varies per platform)" } }.open end } button { layout_data { width 200 height 50 } text "No Trim Shell" on_widget_selected do # build a nested shell, meaning a shell that specifies its parent shell (root_shell_proxy) shell(root_shell_proxy, :no_trim) { # shell has fill_layout(:horizontal) by default with no margins text 'No Trim Shell' label { font height: 20 text "No trim shell, meaning no buttons or title bar.\n(varies per platform)" } }.open end } button { layout_data { width 200 height 50 } text "Always On Top Shell" on_widget_selected do # build a nested shell, meaning a shell that specifies its parent shell (root_shell_proxy) shell(root_shell_proxy, :on_top) { # shell has fill_layout(:horizontal) by default with no margins text 'Always On Top Shell' label { font height: 20 text "Always on top shell.\n(varies per platform)" } }.open end } } } end HelloShell.launch
ruby
MIT
449cf07ada1ec965ae2ac91715ccdf22488df4ca
2026-01-04T17:52:38.125591Z
false
AndyObtiva/glimmer-dsl-swt
https://github.com/AndyObtiva/glimmer-dsl-swt/blob/449cf07ada1ec965ae2ac91715ccdf22488df4ca/samples/hello/hello_canvas_animation_multi.rb
samples/hello/hello_canvas_animation_multi.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' include Glimmer shell { text 'Hello, Canvas Animation Multi!' minimum_size 1200, 420 canvas { background :white animation { every 0.01 # in seconds (one hundredth) frame { |index| # frame block loops indefinitely (unless frame_count is set to an integer) oval(0, 0, 400, 400) { # x, y, width, height foreground :black # sets oval background color } arc(0, 0, 400, 400, -1.4*index%360, 10) { # x, y, width, height, start angle, arc angle background rgb(50, 200, 50) # sets arc background color } } } } canvas { background :white colors = [:yellow, :red] animation { every 0.25 # in seconds (one quarter) cycle colors # cycles array of colors into the second variable of the frame block below frame { |index, color| # frame block loops indefinitely (unless frame_count or cycle_count is set to an integer) outside_color = colors[index % 2] inside_color = colors[(index + 1) % 2] background outside_color # sets canvas background color rectangle(0, 0, 200, 200) { background inside_color # sets rectangle background color } rectangle(200, 200, 200, 200) { background inside_color # sets rectangle background color } } } } canvas { background :white colors = [:yellow, :red] animation { every 0.25 # in seconds (one quarter) cycle colors # cycles array of colors into the second variable of the frame block below frame { |index, color| # frame block loops indefinitely (unless frame_count or cycle_count is set to an integer) outside_color = colors[index % 2] inside_color = colors[(index + 1) % 2] background outside_color # sets canvas background color rectangle(0, 0, 200, 200) { background inside_color # sets rectangle background color } rectangle(200, 200, 200, 200) { background inside_color # sets rectangle background color } } } animation { every 0.01 # in seconds (one hundredth) frame { |index| # frame block loops indefinitely (unless frame_count is set to an integer) oval(0, 0, 400, 400) { # x, y, width, height foreground :black # sets oval background color } arc(0, 0, 400, 400, -1.4*index%360, 10) { # x, y, width, height, start angle, arc angle background rgb(50, 200, 50) # sets arc background color } } } } }.open
ruby
MIT
449cf07ada1ec965ae2ac91715ccdf22488df4ca
2026-01-04T17:52:38.125591Z
false