Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

newwindow and clipboard and eventloop::new #2

Merged
merged 5 commits into from
Jul 19, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 1 addition & 2 deletions .rubocop.yml
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,7 @@ AllCops:
TargetRubyVersion: 2.6

Style/StringLiterals:
Enabled: true
EnforcedStyle: double_quotes
Enabled: false # Disable frozen literal string enforcement FOR NOW AS SOME NEED TO BE FREEZED and some don't

Style/StringLiteralsInInterpolation:
Enabled: true
Expand Down
2 changes: 2 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion Rakefile
Original file line number Diff line number Diff line change
Expand Up @@ -21,4 +21,4 @@ RbSys::ExtensionTask.new("wry_ruby") do |ext|
ext.lib_dir = "lib/wry_ruby"
end

task default: %i[compile test ]#no rubocop add later
task default: %i[compile test] # no rubocop add later
4 changes: 3 additions & 1 deletion ext/wry_ruby/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -10,5 +10,7 @@ publish = false
crate-type = ["cdylib"]

[dependencies]
magnus = { version = "0.5" }
magnus = { version = "0.5.4" }
wry = "0.29.0"
gdk = "0.16.2"
gtk="0.16.2"
77 changes: 77 additions & 0 deletions ext/wry_ruby/src/application/clipboard.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
// https://docs.rs/wry/latest/wry/application/clipboard/struct.Clipboard.html

use std::cell::RefCell;

use gdk;
use gtk;

use magnus::{function, method, Error, Module, Object};

use wry::application::clipboard::Clipboard as ClipboardImpl;

#[derive(Clone, Debug)]
#[magnus::wrap(class = "Clip")]
pub struct Clipboard {
inner: RefCell<ClipboardImpl>,
}

impl Clipboard {
pub fn new() -> Result<Self, Error> {
let inner = ClipboardImpl::new();

Ok(Self {
inner: RefCell::new(inner),
})
}

pub fn get(&self) -> std::cell::Ref<ClipboardImpl> {
self.inner.borrow()
}

pub fn get_mut(&self) -> std::cell::RefMut<ClipboardImpl> {
self.inner.borrow_mut()
}

/// Writes text to the clipboard.
///
/// # Arguments
///
/// * `s` - A string containing the text to be written.
///
/// # Equivalent Ruby Method
///
/// `clip.write_text("Hello World")`
pub fn write_text(&self, s: String) {
let text: &str = s.as_ref();
self.get_mut().write_text(text);
}

/// Reads text from the clipboard.
///
/// # Equivalent Ruby Method
///
/// `clip.read_text`
pub fn read_text(&self) -> Option<String> {
self.get().read_text()
}
}

/// Initializes the clipboard module.
///
/// # Equivalent Ruby Methods
///
/// - `clip = Clip.new`
/// - `clip.write_text("Hello World")`
/// - `clip.read_text`
pub fn init() -> Result<(), Error> {
gdk::init();
let _ = gtk::init();

let class = magnus::define_class("Clip", Default::default())?;

class.define_singleton_method("new", function!(Clipboard::new, 0))?;
class.define_method("write_text", method!(Clipboard::write_text, 1))?;
class.define_method("read_text", method!(Clipboard::read_text, 0))?;

Ok(())
}
39 changes: 39 additions & 0 deletions ext/wry_ruby/src/application/event_loop.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
use magnus::{
function, Error, Object,
};

use std::marker::PhantomData;
use std::sync::atomic::{AtomicPtr};

use wry::application::event_loop::{
EventLoop as EventLoopImpl,
};

#[magnus::wrap(class = "EventLoop")]
pub struct EventLoop {
inner: SafeWrapper<EventLoopImpl<()>>,
}

pub struct SafeWrapper<T> {
event_loop: AtomicPtr<T>,
_marker: PhantomData<*mut T>,
}

unsafe impl<T> Send for SafeWrapper<T> {}

impl EventLoop {
Copy link
Owner Author

@gintama91 gintama91 Jun 30, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

i am not implementing event_loop further(as of now) as per discussion in discord

pub fn new() -> Self {
let event_loop_impl = EventLoopImpl::new();
let inner = SafeWrapper {
event_loop: AtomicPtr::new(Box::into_raw(Box::new(event_loop_impl))),
_marker: PhantomData,
};
EventLoop { inner }
}
}

pub fn init() -> Result<(), Error> {
let class = magnus::define_class("WindowBuilder", Default::default())?;
class.define_singleton_method("new", function!(EventLoop::new, 0))?;
Ok(())
}
11 changes: 10 additions & 1 deletion ext/wry_ruby/src/application/mod.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,17 @@
use magnus:: Error;
use magnus::Error;

mod tray_id;

mod window;

mod clipboard;

mod event_loop;

pub fn init() -> Result<(), Error> {
tray_id::init()?;
window::init()?;
clipboard::init()?;
event_loop::init()?;
Ok(())
}
57 changes: 57 additions & 0 deletions ext/wry_ruby/src/application/window.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
use magnus::{Error, define_global_function, function};
use wry::application::dpi::LogicalSize;
use wry::application::window::WindowBuilder;
use wry::application::{
event::{Event, StartCause, WindowEvent},
event_loop::{ControlFlow, EventLoop},
};
use std::time::{Duration, Instant};

pub fn WindoWnew(title: String, width: u32, height: u32, resizable: bool,timeout: u64) {
let event_loop = EventLoop::new();
let mut window_builder = WindowBuilder::new();
window_builder = window_builder.with_title(title.clone());
gintama91 marked this conversation as resolved.
Show resolved Hide resolved
window_builder = window_builder.with_inner_size(LogicalSize::new(width, height));
window_builder = window_builder.with_resizable(resizable);

let window = window_builder.build(&event_loop).expect("Failed to create window");

// Get initial properties
let current_title = window.title();
let current_size = window.inner_size();
let resizable = window.is_resizable();

println!("Initial Title: {}", current_title);
println!("Initial Size: {:?}", current_size);
println!("Resizable: {}", resizable);

// ************************************************* as of now we are using this timeout to close for test******************************************************
let timeout_duration = Duration::from_secs(timeout);
let start_time = Instant::now();

event_loop.run(move |event, _, control_flow| {
*control_flow = ControlFlow::Wait;

match event {
Event::NewEvents(StartCause::Init) => println!("Wry has started!"),
Event::WindowEvent {
event: WindowEvent::CloseRequested,
..
} => *control_flow = ControlFlow::Exit,
_ => (),
}

let elapsed = Instant::now() - start_time;
if elapsed >= timeout_duration {
println!("Window creation timed out after {:?}.", timeout_duration);
*control_flow = ControlFlow::Exit;
}
});
}

pub fn init() -> Result<(), Error> {
println!("inside init");
define_global_function("new_window", function!(WindoWnew, 5));

Ok(())
}
2 changes: 1 addition & 1 deletion ext/wry_ruby/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,4 +5,4 @@ mod application;
#[magnus::init]
fn init() -> Result<(), Error> {
application::init()
}
}
3 changes: 2 additions & 1 deletion lib/example.rb
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
require_relative "wry_ruby/wry_ruby"
# frozen_string_literal: true

require_relative "wry_ruby/wry_ruby"
8 changes: 3 additions & 5 deletions test/test_application_tray.rb
Original file line number Diff line number Diff line change
@@ -1,16 +1,14 @@

require 'test_helper'
require "test_helper"

class TestWryRuby < Minitest::Test

def test_tray_id_new_with_empty_string
assert_raises(StandardError) do
TrayId.new("".freeze()) # Unique string is empty
TrayId.new("") # Unique string is empty
end
end

def test_tray_id_new_with_non_empty_string
tray_id = TrayId.new("hmm".freeze()) # Unique string is non-empty
tray_id = TrayId.new("hmm") # Unique string is non-empty
refute(tray_id.is_empty)
end

Expand Down
15 changes: 15 additions & 0 deletions test/test_clipboard.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
require 'test_helper'

class ClipboardTest < Minitest::Test
def test_clipboard_functionality
clip = Clip.new

# Write text to the clipboard
clip.write_text("Hello, World!")

# Read text from the clipboard
text = clip.read_text

assert_equal("Hello, World!", text)
end
end
9 changes: 5 additions & 4 deletions test/test_wry_ruby.rb
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
require 'test_helper'
require "test_helper"

class TestWryRuby < Minitest::Test
# def test_that_it_has_a_version_number
# refute_nil ::WryRuby::VERSION
# end

def test_hello_wry

end
# def test_hello_wry
# # title, width, height, resizable , timeout (seconds) to close window during test
# new_window "Hello Wry", 100, 400, true, 3
# end
end
8 changes: 4 additions & 4 deletions wry_ruby.gemspec
Original file line number Diff line number Diff line change
Expand Up @@ -36,12 +36,12 @@ Gem::Specification.new do |spec|

# Uncomment to register a new dependency of your gem
# spec.add_dependency "example-gem", "~> 1.0"

# needed until rubygems supports Rust support is out of beta
spec.add_dependency "rb_sys", "~> 0.9.39"
spec.add_dependency "rb_sys", "~> 0.9.39"

# only needed when developing or packaging your gem
spec.add_development_dependency "rake-compiler", "~> 1.2.0"
# only needed when developing or packaging your gem
spec.add_development_dependency "rake-compiler", "~> 1.2.0"

# For more information and examples about making a new gem, check out our
# guide at: https://bundler.io/guides/creating_gem.html
Expand Down
Loading