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

avm2: Add style sheet support for TextField #19143

Merged
merged 4 commits into from
Jan 11, 2025
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
19 changes: 12 additions & 7 deletions core/src/avm2/globals/flash/text/StyleSheet.as
Original file line number Diff line number Diff line change
@@ -1,28 +1,30 @@
package flash.text {
import flash.events.EventDispatcher;

[Ruffle(InstanceAllocator)]
public dynamic class StyleSheet extends EventDispatcher {
// Shallow copies of the original style objects. Not used by Ruffle itself, just for getStyle()
private var _styles: Object = {};

public function StyleSheet() {}

public function get styleNames():Array {
var result = [];
for (var key in _styles) {
result.push(key);
}
return result;
}

public function clear():void {
_styles = {};
clearInternal();
}

public function getStyle(styleName:String):Object {
return _createShallowCopy(_styles[styleName.toLowerCase()]);
}

public function parseCSS(CSSText:String):void {
var parsed = innerParseCss(CSSText);
if (!parsed) {
Expand All @@ -34,12 +36,12 @@ package flash.text {
setStyle(key, parsed[key]);
}
}

public function setStyle(styleName:String, styleObject:Object):void {
_styles[styleName.toLowerCase()] = _createShallowCopy(styleObject);
transform(_createShallowCopy(styleObject)); // TODO: Store this in a way that Rust can access it, when we implement `TextField.stylesheet`
setStyleInternal(styleName.toLowerCase(), transform(_createShallowCopy(styleObject)));
}

public function transform(formatObject:Object):TextFormat {
if (!formatObject) {
return null;
Expand Down Expand Up @@ -131,5 +133,8 @@ package flash.text {
private native function innerParseCss(css: String): Object;
private native function innerParseColor(color: String): Number;
private native function innerParseFontFamily(fontFamily: String): String;

private native function setStyleInternal(selector: String, textFormat: TextFormat): void;
private native function clearInternal(): void;
}
}
9 changes: 2 additions & 7 deletions core/src/avm2/globals/flash/text/TextField.as
Original file line number Diff line number Diff line change
Expand Up @@ -73,13 +73,8 @@ package flash.text {
public native function get selectable():Boolean;
public native function set selectable(value:Boolean):void;

public function get styleSheet():StyleSheet {
return this._styleSheet;
}
public function set styleSheet(value:StyleSheet):void {
this._styleSheet = value;
stub_setter("flash.text.TextField", "styleSheet");
}
public native function get styleSheet():StyleSheet;
public native function set styleSheet(value:StyleSheet):void;

public native function get text():String;
public native function set text(value:String):void;
Expand Down
45 changes: 45 additions & 0 deletions core/src/avm2/globals/flash/text/style_sheet.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@ use crate::html::{transform_dashes_to_camel_case, CssStream};
use crate::string::AvmString;
use ruffle_wstr::{WStr, WString};

pub use crate::avm2::object::style_sheet_allocator;

pub fn inner_parse_css<'gc>(
activation: &mut Activation<'_, 'gc>,
_this: Value<'gc>,
Expand Down Expand Up @@ -101,3 +103,46 @@ pub fn inner_parse_font_family<'gc>(

Ok(Value::String(AvmString::new(activation.gc(), result)))
}

pub fn clear_internal<'gc>(
_activation: &mut Activation<'_, 'gc>,
this: Value<'gc>,
_args: &[Value<'gc>],
) -> Result<Value<'gc>, Error<'gc>> {
let this = this.as_object().unwrap();

let Some(this) = this.as_style_sheet() else {
return Ok(Value::Undefined);
};

this.clear();

Ok(Value::Undefined)
}

pub fn set_style_internal<'gc>(
activation: &mut Activation<'_, 'gc>,
this: Value<'gc>,
args: &[Value<'gc>],
) -> Result<Value<'gc>, Error<'gc>> {
let this = this.as_object().unwrap();

let Some(this) = this.as_style_sheet() else {
return Ok(Value::Undefined);
};

let Some(selector) = args.try_get_string(activation, 0)? else {
return Ok(Value::Undefined);
};
let text_format = args
.try_get_object(activation, 1)
.and_then(|tf| tf.as_text_format().map(|tf| tf.clone()));

if let Some(text_format) = text_format {
this.set_style(selector.as_wstr().to_owned(), text_format);
} else {
this.remove_style(selector.as_wstr());
}

Ok(Value::Undefined)
}
43 changes: 43 additions & 0 deletions core/src/avm2/globals/flash/text/text_field.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1804,3 +1804,46 @@ pub fn get_char_boundaries<'gc>(
.into();
Ok(rect)
}

pub fn get_style_sheet<'gc>(
_activation: &mut Activation<'_, 'gc>,
this: Value<'gc>,
_args: &[Value<'gc>],
) -> Result<Value<'gc>, Error<'gc>> {
let this = this.as_object().unwrap();

let Some(this) = this
.as_display_object()
.and_then(|this| this.as_edit_text())
else {
return Ok(Value::Undefined);
};

Ok(match this.style_sheet() {
Some(style_sheet) => Value::Object(Object::StyleSheetObject(style_sheet)),
None => Value::Null,
})
}

pub fn set_style_sheet<'gc>(
activation: &mut Activation<'_, 'gc>,
this: Value<'gc>,
args: &[Value<'gc>],
) -> Result<Value<'gc>, Error<'gc>> {
let this = this.as_object().unwrap();

let Some(this) = this
.as_display_object()
.and_then(|this| this.as_edit_text())
else {
return Ok(Value::Undefined);
};

let style_sheet = args
.try_get_object(activation, 0)
.and_then(|o| o.as_style_sheet());

this.set_style_sheet(activation.context, style_sheet);

Ok(Value::Undefined)
}
13 changes: 13 additions & 0 deletions core/src/avm2/object.rs
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,7 @@ mod soundchannel_object;
mod soundtransform_object;
mod stage3d_object;
mod stage_object;
mod stylesheet_object;
mod textformat_object;
mod texture_object;
mod vector_object;
Expand Down Expand Up @@ -144,6 +145,9 @@ pub use crate::avm2::object::stage3d_object::{
stage_3d_allocator, Stage3DObject, Stage3DObjectWeak,
};
pub use crate::avm2::object::stage_object::{StageObject, StageObjectWeak};
pub use crate::avm2::object::stylesheet_object::{
style_sheet_allocator, StyleSheetObject, StyleSheetObjectWeak,
};
pub use crate::avm2::object::textformat_object::{
textformat_allocator, TextFormatObject, TextFormatObjectWeak,
};
Expand Down Expand Up @@ -206,6 +210,7 @@ use crate::font::Font;
LocalConnectionObject(LocalConnectionObject<'gc>),
SharedObjectObject(SharedObjectObject<'gc>),
SoundTransformObject(SoundTransformObject<'gc>),
StyleSheetObject(StyleSheetObject<'gc>),
}
)]
pub trait TObject<'gc>: 'gc + Collect + Debug + Into<Object<'gc>> + Clone + Copy {
Expand Down Expand Up @@ -1286,6 +1291,10 @@ pub trait TObject<'gc>: 'gc + Collect + Debug + Into<Object<'gc>> + Clone + Copy
fn as_sound_transform(&self) -> Option<SoundTransformObject<'gc>> {
None
}

fn as_style_sheet(&self) -> Option<StyleSheetObject<'gc>> {
None
}
}

pub enum ObjectPtr {}
Expand Down Expand Up @@ -1339,6 +1348,7 @@ impl<'gc> Object<'gc> {
Self::LocalConnectionObject(o) => WeakObject::LocalConnectionObject(LocalConnectionObjectWeak(Gc::downgrade(o.0))),
Self::SharedObjectObject(o) => WeakObject::SharedObjectObject(SharedObjectObjectWeak(Gc::downgrade(o.0))),
Self::SoundTransformObject(o) => WeakObject::SoundTransformObject(SoundTransformObjectWeak(Gc::downgrade(o.0))),
Self::StyleSheetObject(o) => WeakObject::StyleSheetObject(StyleSheetObjectWeak(Gc::downgrade(o.0))),
}
}
}
Expand Down Expand Up @@ -1402,6 +1412,7 @@ pub enum WeakObject<'gc> {
LocalConnectionObject(LocalConnectionObjectWeak<'gc>),
SharedObjectObject(SharedObjectObjectWeak<'gc>),
SoundTransformObject(SoundTransformObjectWeak<'gc>),
StyleSheetObject(StyleSheetObjectWeak<'gc>),
}

impl<'gc> WeakObject<'gc> {
Expand Down Expand Up @@ -1448,6 +1459,7 @@ impl<'gc> WeakObject<'gc> {
Self::LocalConnectionObject(o) => GcWeak::as_ptr(o.0) as *const ObjectPtr,
Self::SharedObjectObject(o) => GcWeak::as_ptr(o.0) as *const ObjectPtr,
Self::SoundTransformObject(o) => GcWeak::as_ptr(o.0) as *const ObjectPtr,
Self::StyleSheetObject(o) => GcWeak::as_ptr(o.0) as *const ObjectPtr,
}
}

Expand Down Expand Up @@ -1494,6 +1506,7 @@ impl<'gc> WeakObject<'gc> {
Self::LocalConnectionObject(o) => LocalConnectionObject(o.0.upgrade(mc)?).into(),
Self::SharedObjectObject(o) => SharedObjectObject(o.0.upgrade(mc)?).into(),
Self::SoundTransformObject(o) => SoundTransformObject(o.0.upgrade(mc)?).into(),
Self::StyleSheetObject(o) => StyleSheetObject(o.0.upgrade(mc)?).into(),
})
}
}
Expand Down
94 changes: 94 additions & 0 deletions core/src/avm2/object/stylesheet_object.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
use crate::avm2::activation::Activation;
use crate::avm2::object::script_object::ScriptObjectData;
use crate::avm2::object::{ClassObject, Object, ObjectPtr, TObject};
use crate::avm2::Error;
use crate::html::TextFormat;
use core::fmt;
use fnv::FnvHashMap;
use gc_arena::{Collect, Gc, GcWeak};
use ruffle_wstr::{WStr, WString};
use std::cell::RefCell;

/// A class instance allocator that allocates StyleSheet objects.
pub fn style_sheet_allocator<'gc>(
class: ClassObject<'gc>,
activation: &mut Activation<'_, 'gc>,
) -> Result<Object<'gc>, Error<'gc>> {
let base = ScriptObjectData::new(class);

Ok(StyleSheetObject(Gc::new(
activation.gc(),
StyleSheetObjectData {
base,
styles: RefCell::new(Default::default()),
},
))
.into())
}

#[derive(Clone, Collect, Copy)]
#[collect(no_drop)]
pub struct StyleSheetObject<'gc>(pub Gc<'gc, StyleSheetObjectData<'gc>>);

#[derive(Clone, Collect, Copy, Debug)]
#[collect(no_drop)]
pub struct StyleSheetObjectWeak<'gc>(pub GcWeak<'gc, StyleSheetObjectData<'gc>>);

impl fmt::Debug for StyleSheetObject<'_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("StyleSheetObject")
.field("ptr", &Gc::as_ptr(self.0))
.finish()
}
}

#[derive(Collect)]
#[collect(no_drop)]
#[repr(C, align(8))]
pub struct StyleSheetObjectData<'gc> {
/// Base script object
base: ScriptObjectData<'gc>,

styles: RefCell<FnvHashMap<WString, TextFormat>>,
}

const _: () = assert!(std::mem::offset_of!(StyleSheetObjectData, base) == 0);
const _: () = assert!(
std::mem::align_of::<StyleSheetObjectData>() == std::mem::align_of::<ScriptObjectData>()
);

impl<'gc> TObject<'gc> for StyleSheetObject<'gc> {
fn gc_base(&self) -> Gc<'gc, ScriptObjectData<'gc>> {
// SAFETY: Object data is repr(C), and a compile-time assert ensures
// that the ScriptObjectData stays at offset 0 of the struct- so the
// layouts are compatible

unsafe { Gc::cast(self.0) }
}

fn as_ptr(&self) -> *const ObjectPtr {
Gc::as_ptr(self.0) as *const ObjectPtr
}

fn as_style_sheet(&self) -> Option<StyleSheetObject<'gc>> {
Some(*self)
}
}

impl StyleSheetObject<'_> {
pub fn get_style(self, selector: &WStr) -> Option<TextFormat> {
self.0.styles.borrow().get(selector).cloned()
}

pub fn set_style(self, selector: WString, format: TextFormat) {
self.0.styles.borrow_mut().insert(selector, format);
}

pub fn remove_style(self, selector: &WStr) {
self.0.styles.borrow_mut().remove(selector);
}

pub fn clear(self) {
self.0.styles.borrow_mut().clear();
}
}
Loading