hash
stringlengths 40
40
| date
stringdate 2019-01-22 05:28:56
2025-03-19 19:23:00
| author
stringclasses 199
values | commit_message
stringlengths 18
96
| is_merge
bool 1
class | masked_commit_message
stringlengths 12
90
| type
stringclasses 74
values | git_diff
stringlengths 222
1.21M
|
|---|---|---|---|---|---|---|---|
0e3def1d0bdd570f0132eeb1aa77885e5b12680f
|
2022-01-23 05:52:10
|
Linus Groh
|
libjs: Don't parse/re-format offset in parse_temporal_time_zone_string()
| false
|
Don't parse/re-format offset in parse_temporal_time_zone_string()
|
libjs
|
diff --git a/Userland/Libraries/LibJS/Runtime/Temporal/AbstractOperations.cpp b/Userland/Libraries/LibJS/Runtime/Temporal/AbstractOperations.cpp
index 8978fad79149..4e12280cffd2 100644
--- a/Userland/Libraries/LibJS/Runtime/Temporal/AbstractOperations.cpp
+++ b/Userland/Libraries/LibJS/Runtime/Temporal/AbstractOperations.cpp
@@ -1626,89 +1626,46 @@ ThrowCompletionOr<TemporalTimeZone> parse_temporal_time_zone_string(GlobalObject
{
auto& vm = global_object.vm();
+ auto optional_string_view_to_optional_string = [](Optional<StringView> const& s) {
+ return s.has_value() ? String { *s } : Optional<String> {};
+ };
+
// 1. Assert: Type(isoString) is String.
- // 2. If isoString does not satisfy the syntax of a TemporalTimeZoneString (see 13.33), then
+ // 2. Let parseResult be ParseText(! StringToCodePoints(isoString), TemporalTimeZoneString).
auto parse_result = parse_iso8601(Production::TemporalTimeZoneString, iso_string);
+
+ // 3. If parseResult is a List of errors, then
if (!parse_result.has_value()) {
// a. Throw a RangeError exception.
return vm.throw_completion<RangeError>(global_object, ErrorType::TemporalInvalidTimeZoneString, iso_string);
}
- // 3. Let z, sign, hours, minutes, seconds, fraction and name be the parts of isoString produced respectively by the UTCDesignator, TimeZoneUTCOffsetSign, TimeZoneUTCOffsetHour, TimeZoneUTCOffsetMinute, TimeZoneUTCOffsetSecond, TimeZoneUTCOffsetFractionalPart, and TimeZoneIANAName productions, or undefined if not present.
- auto z_part = parse_result->utc_designator;
- auto sign_part = parse_result->time_zone_utc_offset_sign;
- auto hours_part = parse_result->time_zone_utc_offset_hour;
- auto minutes_part = parse_result->time_zone_utc_offset_minute;
- auto seconds_part = parse_result->time_zone_utc_offset_second;
- auto fraction_part = parse_result->time_zone_utc_offset_fractional_part;
- auto name_part = parse_result->time_zone_iana_name;
-
- // 4. If z is not undefined, then
- if (z_part.has_value()) {
- // a. Return the Record { [[Z]]: true, [[OffsetString]]: undefined, [[Name]]: name }.
- return TemporalTimeZone { .z = true, .offset_string = {}, .name = name_part.has_value() ? String { *name_part } : Optional<String> {} };
- }
+ // 4. Let each of z, offsetString, and name be the source text matched by the respective UTCDesignator, TimeZoneNumericUTCOffset, and TimeZoneIANAName Parse Node enclosed by parseResult, or an empty sequence of code points if not present.
+ auto z = parse_result->utc_designator;
+ auto offset_string = parse_result->time_zone_numeric_utc_offset;
+ auto name = parse_result->time_zone_iana_name;
- Optional<String> offset_string;
- // 5. If hours is undefined, then
- if (!hours_part.has_value()) {
- // a. Let offsetString be undefined.
- // NOTE: No-op.
- }
+ // 5. If name is empty, then
+ // a. Set name to undefined.
// 6. Else,
- else {
- // a. Assert: sign is not undefined.
- VERIFY(sign_part.has_value());
-
- // b. Set hours to ! ToIntegerOrInfinity(hours).
- u8 hours = *hours_part->to_uint<u8>();
+ // a. Set name to ! CodePointsToString(name).
+ // NOTE: No-op.
- i8 sign;
- // c. If sign is the code unit 0x002D (HYPHEN-MINUS) or the code unit 0x2212 (MINUS SIGN), then
- if (sign_part->is_one_of("-", "\u2212")) {
- // i. Set sign to −1.
- sign = -1;
- }
- // d. Else,
- else {
- // i. Set sign to 1.
- sign = 1;
- }
-
- // e. Set minutes to ! ToIntegerOrInfinity(minutes).
- u8 minutes = *minutes_part.value_or("0"sv).to_uint<u8>();
-
- // f. Set seconds to ! ToIntegerOrInfinity(seconds).
- u8 seconds = *seconds_part.value_or("0"sv).to_uint<u8>();
-
- i32 nanoseconds;
- // g. If fraction is not undefined, then
- if (fraction_part.has_value()) {
- // i. Set fraction to the string-concatenation of the previous value of fraction and the string "000000000".
- auto fraction = String::formatted("{}000000000", *fraction_part);
- // ii. Let nanoseconds be the String value equal to the substring of fraction from 1 to 10.
- // iii. Set nanoseconds to ! ToIntegerOrInfinity(nanoseconds).
- // FIXME: 1-10 is wrong and should be 0-9; the decimal separator is no longer present in the parsed string.
- // See: https://github.com/tc39/proposal-temporal/pull/1999
- nanoseconds = *fraction.substring(0, 9).to_int<i32>();
- }
- // h. Else,
- else {
- // i. Let nanoseconds be 0.
- nanoseconds = 0;
- }
-
- // i. Let offsetNanoseconds be sign × (((hours × 60 + minutes) × 60 + seconds) × 10^9 + nanoseconds).
- // NOTE: Decimal point in 10^9 is important, otherwise it's all integers and the result overflows!
- auto offset_nanoseconds = sign * (((hours * 60 + minutes) * 60 + seconds) * 1000000000.0 + nanoseconds);
-
- // j. Let offsetString be ! FormatTimeZoneOffsetString(offsetNanoseconds).
- offset_string = format_time_zone_offset_string(offset_nanoseconds);
+ // 7. If z is not empty, then
+ if (z.has_value()) {
+ // a. Return the Record { [[Z]]: true, [[OffsetString]]: undefined, [[Name]]: name }.
+ return TemporalTimeZone { .z = true, .offset_string = {}, .name = optional_string_view_to_optional_string(name) };
}
- // 7. Return the Record { [[Z]]: false, [[OffsetString]]: offsetString, [[Name]]: name }.
- return TemporalTimeZone { .z = false, .offset_string = offset_string, .name = name_part.has_value() ? String { *name_part } : Optional<String> {} };
+ // 8. If offsetString is empty, then
+ // a. Set offsetString to undefined.
+ // 9. Else,
+ // a. Set offsetString to ! CodePointsToString(offsetString).
+ // NOTE: No-op.
+
+ // 10. Return the Record { [[Z]]: false, [[OffsetString]]: offsetString, [[Name]]: name }.
+ return TemporalTimeZone { .z = false, .offset_string = optional_string_view_to_optional_string(offset_string), .name = optional_string_view_to_optional_string(name) };
}
// 13.44 ParseTemporalYearMonthString ( isoString ), https://tc39.es/proposal-temporal/#sec-temporal-parsetemporalyearmonthstring
diff --git a/Userland/Libraries/LibJS/Runtime/Temporal/ISO8601.cpp b/Userland/Libraries/LibJS/Runtime/Temporal/ISO8601.cpp
index fb83e6490156..9af3ef742dbb 100644
--- a/Userland/Libraries/LibJS/Runtime/Temporal/ISO8601.cpp
+++ b/Userland/Libraries/LibJS/Runtime/Temporal/ISO8601.cpp
@@ -725,6 +725,7 @@ bool ISO8601Parser::parse_time_zone_numeric_utc_offset()
if (parse_time_zone_utc_offset_second())
(void)parse_time_zone_utc_offset_fraction();
}
+ m_state.parse_result.time_zone_numeric_utc_offset = transaction.parsed_string_view();
transaction.commit();
return true;
}
diff --git a/Userland/Libraries/LibJS/Runtime/Temporal/ISO8601.h b/Userland/Libraries/LibJS/Runtime/Temporal/ISO8601.h
index 4422b5a81e1a..5b631bac3dcf 100644
--- a/Userland/Libraries/LibJS/Runtime/Temporal/ISO8601.h
+++ b/Userland/Libraries/LibJS/Runtime/Temporal/ISO8601.h
@@ -31,6 +31,7 @@ struct ParseResult {
Optional<StringView> time_second_not_valid_month;
Optional<StringView> calendar_name;
Optional<StringView> utc_designator;
+ Optional<StringView> time_zone_numeric_utc_offset;
Optional<StringView> time_zone_utc_offset_sign;
Optional<StringView> time_zone_utc_offset_hour;
Optional<StringView> time_zone_utc_offset_minute;
|
45d0f84a273ab6ead8aefd32056cbc2c36ad5868
|
2021-07-23 03:03:21
|
Hendiadyoin1
|
userspaceemulator: Implement SoftFPU instructions
| false
|
Implement SoftFPU instructions
|
userspaceemulator
|
diff --git a/Userland/DevTools/UserspaceEmulator/SoftFPU.cpp b/Userland/DevTools/UserspaceEmulator/SoftFPU.cpp
index 9e1a80c81eb2..64e3463019cf 100644
--- a/Userland/DevTools/UserspaceEmulator/SoftFPU.cpp
+++ b/Userland/DevTools/UserspaceEmulator/SoftFPU.cpp
@@ -177,7 +177,7 @@ ALWAYS_INLINE void SoftFPU::fpu_set_exception(FPU_Exception ex)
}
template<Arithmetic T>
-__attribute__((pure)) ALWAYS_INLINE T SoftFPU::fpu_round(long double value) const
+ALWAYS_INLINE T SoftFPU::fpu_round(long double value) const
{
// FIXME: may need to set indefinite values manually
switch (fpu_get_round_mode()) {
@@ -195,7 +195,7 @@ __attribute__((pure)) ALWAYS_INLINE T SoftFPU::fpu_round(long double value) cons
}
template<Arithmetic T>
-__attribute__((pure)) ALWAYS_INLINE T SoftFPU::fpu_round_checked(long double value)
+ALWAYS_INLINE T SoftFPU::fpu_round_checked(long double value)
{
T result = fpu_round<T>(value);
if (auto rnd = value - result) {
@@ -209,13 +209,13 @@ __attribute__((pure)) ALWAYS_INLINE T SoftFPU::fpu_round_checked(long double val
}
template<FloatingPoint T>
-__attribute__((pure)) ALWAYS_INLINE T SoftFPU::fpu_convert(long double value) const
+ALWAYS_INLINE T SoftFPU::fpu_convert(long double value) const
{
// FIXME: actually round the right way
return static_cast<T>(value);
}
template<FloatingPoint T>
-__attribute__((pure)) ALWAYS_INLINE T SoftFPU::fpu_convert_checked(long double value)
+ALWAYS_INLINE T SoftFPU::fpu_convert_checked(long double value)
{
T result = fpu_convert<T>(value);
if (auto rnd = value - result) {
@@ -228,21 +228,1517 @@ __attribute__((pure)) ALWAYS_INLINE T SoftFPU::fpu_convert_checked(long double v
return result;
}
-template<Signed R, Signed I>
-__attribute__((const)) ALWAYS_INLINE R signed_saturate(I input)
+// Instructions
+
+// DATA TRANSFER
+void SoftFPU::FLD_RM32(const X86::Instruction& insn)
+{
+ if (insn.modrm().is_register()) {
+ fpu_push(fpu_get(insn.modrm().register_index()));
+ } else {
+ auto new_f32 = insn.modrm().read32(m_cpu, insn);
+ // FIXME: Respect shadow values
+ fpu_push(bit_cast<float>(new_f32.value()));
+ }
+}
+void SoftFPU::FLD_RM64(const X86::Instruction& insn)
+{
+ VERIFY(!insn.modrm().is_register());
+ auto new_f64 = insn.modrm().read64(m_cpu, insn);
+ // FIXME: Respect shadow values
+ fpu_push(bit_cast<double>(new_f64.value()));
+}
+void SoftFPU::FLD_RM80(const X86::Instruction& insn)
+{
+ VERIFY(!insn.modrm().is_register());
+
+ // long doubles can be up to 128 bits wide in memory for reasons (alignment) and only uses 80 bits of precision
+ // GCC uses 12 bytes in 32 bit and 16 bytes in 64 bit mode
+ // so in the 32 bit case we read a bit to much, but that shouldn't be an issue.
+ // FIXME: Respect shadow values
+ u128 new_f80 = insn.modrm().read128(m_cpu, insn).value();
+
+ fpu_push(*(long double*)new_f80.bytes().data());
+}
+
+void SoftFPU::FST_RM32(const X86::Instruction& insn)
+{
+ VERIFY(!insn.modrm().is_register());
+ float f32 = fpu_convert_checked<float>(fpu_get(0));
+
+ if (fpu_is_set(0))
+ insn.modrm().write32(m_cpu, insn, shadow_wrap_as_initialized(bit_cast<u32>(f32)));
+ else
+ insn.modrm().write32(m_cpu, insn, ValueWithShadow<u32>(bit_cast<u32>(f32), 0u));
+}
+void SoftFPU::FST_RM64(const X86::Instruction& insn)
+{
+ if (insn.modrm().is_register()) {
+ fpu_set(insn.modrm().register_index(), fpu_get(0));
+ } else {
+ double f64 = fpu_convert_checked<double>(fpu_get(0));
+ if (fpu_is_set(0))
+ insn.modrm().write64(m_cpu, insn, shadow_wrap_as_initialized(bit_cast<u64>(f64)));
+ else
+ insn.modrm().write64(m_cpu, insn, ValueWithShadow<u64>(bit_cast<u64>(f64), 0ULL));
+ }
+}
+
+void SoftFPU::FSTP_RM32(const X86::Instruction& insn)
+{
+ FST_RM32(insn);
+ fpu_pop();
+}
+void SoftFPU::FSTP_RM64(const X86::Instruction& insn)
+{
+ FST_RM64(insn);
+ fpu_pop();
+}
+void SoftFPU::FSTP_RM80(const X86::Instruction& insn)
+{
+ if (insn.modrm().is_register()) {
+ fpu_set(insn.modrm().register_index(), fpu_get(0));
+ fpu_pop();
+ } else {
+ // FIXME: Respect more shadow values
+ // long doubles can be up to 128 bits wide in memory for reasons (alignment) and only uses 80 bits of precision
+ // gcc uses 12 byte in 32 bit and 16 byte in 64 bit mode
+ // due to only 10 bytes being used, we just write these 10 into memory
+ // We have to do .bytes().data() to get around static type analysis
+ ValueWithShadow<u128> f80 { 0u, 0u };
+ u128 value {};
+ f80 = insn.modrm().read128(m_cpu, insn);
+ *(long double*)value.bytes().data() = fpu_pop();
+ memcpy(f80.value().bytes().data(), &value, 10); // copy
+ memset(f80.shadow().bytes().data(), 0x01, 10); // mark as initialized
+ insn.modrm().write128(m_cpu, insn, f80);
+ }
+}
+
+void SoftFPU::FILD_RM16(const X86::Instruction& insn)
+{
+ VERIFY(!insn.modrm().is_register());
+ auto m16int = insn.modrm().read16(m_cpu, insn);
+ warn_if_uninitialized(m16int, "int16 loaded as float");
+
+ fpu_push(static_cast<long double>(static_cast<i16>(m16int.value())));
+}
+void SoftFPU::FILD_RM32(const X86::Instruction& insn)
+{
+ VERIFY(!insn.modrm().is_register());
+ auto m32int = insn.modrm().read32(m_cpu, insn);
+ warn_if_uninitialized(m32int, "int32 loaded as float");
+
+ fpu_push(static_cast<long double>(static_cast<i32>(m32int.value())));
+}
+void SoftFPU::FILD_RM64(const X86::Instruction& insn)
+{
+ VERIFY(!insn.modrm().is_register());
+ auto m64int = insn.modrm().read64(m_cpu, insn);
+ warn_if_uninitialized(m64int, "int64 loaded as float");
+
+ fpu_push(static_cast<long double>(static_cast<i64>(m64int.value())));
+}
+
+void SoftFPU::FIST_RM16(const X86::Instruction& insn)
+{
+ VERIFY(!insn.modrm().is_register());
+ auto f = fpu_get(0);
+ set_c1(0);
+ auto int16 = fpu_round_checked<i16>(f);
+
+ // FIXME: Respect shadow values
+ insn.modrm().write16(m_cpu, insn, shadow_wrap_as_initialized(bit_cast<u16>(int16)));
+}
+void SoftFPU::FIST_RM32(const X86::Instruction& insn)
+{
+ VERIFY(!insn.modrm().is_register());
+ auto f = fpu_get(0);
+ set_c1(0);
+ auto int32 = fpu_round_checked<i32>(f);
+ // FIXME: Respect shadow values
+ insn.modrm().write32(m_cpu, insn, shadow_wrap_as_initialized(bit_cast<u32>(int32)));
+}
+
+void SoftFPU::FISTP_RM16(const X86::Instruction& insn)
+{
+ FIST_RM16(insn);
+ fpu_pop();
+}
+void SoftFPU::FISTP_RM32(const X86::Instruction& insn)
+{
+ FIST_RM32(insn);
+ fpu_pop();
+}
+void SoftFPU::FISTP_RM64(const X86::Instruction& insn)
+{
+ VERIFY(!insn.modrm().is_register());
+ auto f = fpu_pop();
+ set_c1(0);
+ auto i64 = fpu_round_checked<int64_t>(f);
+ // FIXME: Respect shadow values
+ insn.modrm().write64(m_cpu, insn, shadow_wrap_as_initialized(bit_cast<u64>(i64)));
+}
+
+void SoftFPU::FISTTP_RM16(const X86::Instruction& insn)
+{
+ VERIFY(!insn.modrm().is_register());
+ set_c1(0);
+ i16 value = static_cast<i16>(fpu_pop());
+ // FIXME: Respect shadow values
+ insn.modrm().write16(m_cpu, insn, shadow_wrap_as_initialized(bit_cast<u16>(value)));
+}
+void SoftFPU::FISTTP_RM32(const X86::Instruction& insn)
+{
+ VERIFY(!insn.modrm().is_register());
+ i32 value = static_cast<i32>(fpu_pop());
+ set_c1(0);
+ // FIXME: Respect shadow values
+ insn.modrm().write32(m_cpu, insn, shadow_wrap_as_initialized(bit_cast<u32>(value)));
+}
+void SoftFPU::FISTTP_RM64(const X86::Instruction& insn)
+{
+ VERIFY(!insn.modrm().is_register());
+ set_c1(0);
+ i64 value = static_cast<i64>(fpu_pop());
+ // FIXME: Respect shadow values
+ insn.modrm().write64(m_cpu, insn, shadow_wrap_as_initialized(bit_cast<u64>(value)));
+}
+
+void SoftFPU::FBLD_M80(const X86::Instruction&) { TODO_INSN(); }
+void SoftFPU::FBSTP_M80(const X86::Instruction&) { TODO_INSN(); }
+
+void SoftFPU::FXCH(const X86::Instruction& insn)
+{
+ // FIXME: implicit argument `D9 C9` -> st[0] <-> st[1]?
+ VERIFY(insn.modrm().is_register());
+ set_c1(0);
+ auto tmp = fpu_get(0);
+ fpu_set(0, fpu_get(insn.modrm().register_index()));
+ fpu_set(insn.modrm().register_index(), tmp);
+}
+
+void SoftFPU::FCMOVE(const X86::Instruction& insn)
+{
+ VERIFY(insn.modrm().is_register());
+ if (m_cpu.zf())
+ fpu_set(0, fpu_get(insn.modrm().rm()));
+}
+void SoftFPU::FCMOVNE(const X86::Instruction& insn)
+{
+ VERIFY(insn.modrm().is_register());
+ if (!m_cpu.zf())
+ fpu_set(0, fpu_get((insn.modrm().reg_fpu())));
+}
+
+void SoftFPU::FCMOVB(const X86::Instruction& insn)
+{
+ VERIFY(insn.modrm().is_register());
+ if (m_cpu.cf())
+ fpu_set(0, fpu_get(insn.modrm().rm()));
+}
+void SoftFPU::FCMOVNB(const X86::Instruction& insn)
+{
+ VERIFY(!insn.modrm().is_register());
+ auto m32int = (i32)insn.modrm().read32(m_cpu, insn).value();
+ // FIXME: Respect shadow values
+ fpu_push((long double)m32int);
+}
+void SoftFPU::FCMOVBE(const X86::Instruction& insn)
+{
+ if (m_cpu.cf() | m_cpu.zf())
+ fpu_set(0, fpu_get(insn.modrm().rm()));
+}
+void SoftFPU::FCMOVNBE(const X86::Instruction& insn)
+{
+ if (!(m_cpu.cf() | m_cpu.zf()))
+ fpu_set(0, fpu_get(insn.modrm().rm()));
+}
+
+void SoftFPU::FCMOVU(const X86::Instruction& insn)
+{
+ VERIFY(insn.modrm().is_register());
+ if (m_cpu.pf())
+ fpu_set(0, fpu_get((insn.modrm().reg_fpu())));
+}
+void SoftFPU::FCMOVNU(const X86::Instruction& insn)
+{
+ VERIFY(insn.modrm().is_register());
+ if (m_cpu.pf())
+ fpu_set(0, fpu_get((insn.modrm().reg_fpu())));
+}
+
+// BASIC ARITHMETIC
+void SoftFPU::FADD_RM32(const X86::Instruction& insn)
+{
+ // XXX look at ::INC_foo for how mem/reg stuff is handled, and use that here too to make sure this is only called for mem32 ops
+ if (insn.modrm().is_register()) {
+ fpu_set(0, fpu_get(insn.modrm().register_index()) + fpu_get(0));
+ } else {
+ auto new_f32 = insn.modrm().read32(m_cpu, insn);
+ // FIXME: Respect shadow values
+ auto f32 = bit_cast<float>(new_f32.value());
+ fpu_set(0, fpu_get(0) + f32);
+ }
+}
+void SoftFPU::FADD_RM64(const X86::Instruction& insn)
+{
+ // XXX look at ::INC_foo for how mem/reg stuff is handled, and use that here too to make sure this is only called for mem64 ops
+ if (insn.modrm().is_register()) {
+ fpu_set(insn.modrm().register_index(), fpu_get(insn.modrm().register_index()) + fpu_get(0));
+ } else {
+ auto new_f64 = insn.modrm().read64(m_cpu, insn);
+ // FIXME: Respect shadow values
+ auto f64 = bit_cast<double>(new_f64.value());
+ fpu_set(0, fpu_get(0) + f64);
+ }
+}
+void SoftFPU::FADDP(const X86::Instruction& insn)
+{
+ VERIFY(insn.modrm().is_register());
+ fpu_set(insn.modrm().register_index(), fpu_get(insn.modrm().register_index()) + fpu_get(0));
+ fpu_pop();
+}
+
+void SoftFPU::FIADD_RM32(const X86::Instruction& insn)
+{
+ VERIFY(!insn.modrm().is_register());
+ auto m32int = (i32)insn.modrm().read32(m_cpu, insn).value();
+ // FIXME: Respect shadow values
+ fpu_set(0, fpu_get(0) + (long double)m32int);
+}
+void SoftFPU::FIADD_RM16(const X86::Instruction& insn)
+{
+ VERIFY(!insn.modrm().is_register());
+ auto m16int = (i16)insn.modrm().read16(m_cpu, insn).value();
+ // FIXME: Respect shadow values
+ fpu_set(0, fpu_get(0) + (long double)m16int);
+}
+
+void SoftFPU::FSUB_RM32(const X86::Instruction& insn)
+{
+ if (insn.modrm().is_register()) {
+ fpu_set(0, fpu_get(0) - fpu_get(insn.modrm().register_index()));
+ } else {
+ auto new_f32 = insn.modrm().read32(m_cpu, insn);
+ // FIXME: Respect shadow values
+ auto f32 = bit_cast<float>(new_f32.value());
+ fpu_set(0, fpu_get(0) - f32);
+ }
+}
+void SoftFPU::FSUB_RM64(const X86::Instruction& insn)
+{
+ if (insn.modrm().is_register()) {
+ fpu_set(insn.modrm().register_index(), fpu_get(insn.modrm().register_index()) - fpu_get(0));
+ } else {
+ auto new_f64 = insn.modrm().read64(m_cpu, insn);
+ // FIXME: Respect shadow values
+ auto f64 = bit_cast<double>(new_f64.value());
+ fpu_set(0, fpu_get(0) - f64);
+ }
+}
+void SoftFPU::FSUBP(const X86::Instruction& insn)
+{
+ VERIFY(insn.modrm().is_register());
+ fpu_set(insn.modrm().register_index(), fpu_get(insn.modrm().register_index()) - fpu_get(0));
+ fpu_pop();
+}
+
+void SoftFPU::FSUBR_RM32(const X86::Instruction& insn)
+{
+ if (insn.modrm().is_register()) {
+ fpu_set(0, fpu_get(insn.modrm().register_index()) - fpu_get(0));
+ } else {
+ auto new_f32 = insn.modrm().read32(m_cpu, insn);
+ // FIXME: Respect shadow values
+ auto f32 = bit_cast<float>(new_f32.value());
+ fpu_set(0, f32 - fpu_get(0));
+ }
+}
+void SoftFPU::FSUBR_RM64(const X86::Instruction& insn)
+{
+ if (insn.modrm().is_register()) {
+ fpu_set(insn.modrm().register_index(), fpu_get(insn.modrm().register_index()) - fpu_get(0));
+ } else {
+ auto new_f64 = insn.modrm().read64(m_cpu, insn);
+ // FIXME: Respect shadow values
+ auto f64 = bit_cast<double>(new_f64.value());
+ fpu_set(0, f64 - fpu_get(0));
+ }
+}
+void SoftFPU::FSUBRP(const X86::Instruction& insn)
+{
+ VERIFY(insn.modrm().is_register());
+ fpu_set(insn.modrm().register_index(), fpu_get(0) - fpu_get(insn.modrm().register_index()));
+ fpu_pop();
+}
+
+void SoftFPU::FISUB_RM32(const X86::Instruction& insn)
+{
+ VERIFY(!insn.modrm().is_register());
+ auto m32int = (i32)insn.modrm().read32(m_cpu, insn).value();
+ // FIXME: Respect shadow values
+ fpu_set(0, fpu_get(0) - (long double)m32int);
+}
+void SoftFPU::FISUB_RM16(const X86::Instruction& insn)
+{
+ VERIFY(!insn.modrm().is_register());
+ auto m16int = (i16)insn.modrm().read16(m_cpu, insn).value();
+ // FIXME: Respect shadow values
+ fpu_set(0, fpu_get(0) - (long double)m16int);
+}
+
+void SoftFPU::FISUBR_RM16(const X86::Instruction& insn)
+{
+ VERIFY(!insn.modrm().is_register());
+ auto m16int = (i16)insn.modrm().read16(m_cpu, insn).value();
+ // FIXME: Respect shadow values
+ fpu_set(0, (long double)m16int - fpu_get(0));
+}
+void SoftFPU::FISUBR_RM32(const X86::Instruction& insn)
+{
+ VERIFY(!insn.modrm().is_register());
+ auto m32int = (i32)insn.modrm().read32(m_cpu, insn).value();
+ // FIXME: Respect shadow values
+ fpu_set(0, (long double)m32int - fpu_get(0));
+}
+
+void SoftFPU::FMUL_RM32(const X86::Instruction& insn)
+{
+ // XXX look at ::INC_foo for how mem/reg stuff is handled, and use that here too to make sure this is only called for mem32 ops
+ if (insn.modrm().is_register()) {
+ fpu_set(0, fpu_get(0) * fpu_get(insn.modrm().register_index()));
+ } else {
+ auto new_f32 = insn.modrm().read32(m_cpu, insn);
+ // FIXME: Respect shadow values
+ auto f32 = bit_cast<float>(new_f32.value());
+ fpu_set(0, fpu_get(0) * f32);
+ }
+}
+void SoftFPU::FMUL_RM64(const X86::Instruction& insn)
+{
+ // XXX look at ::INC_foo for how mem/reg stuff is handled, and use that here too to make sure this is only called for mem64 ops
+ if (insn.modrm().is_register()) {
+ fpu_set(insn.modrm().register_index(), fpu_get(insn.modrm().register_index()) * fpu_get(0));
+ } else {
+ auto new_f64 = insn.modrm().read64(m_cpu, insn);
+ // FIXME: Respect shadow values
+ auto f64 = bit_cast<double>(new_f64.value());
+ fpu_set(0, fpu_get(0) * f64);
+ }
+}
+void SoftFPU::FMULP(const X86::Instruction& insn)
+{
+ VERIFY(insn.modrm().is_register());
+ fpu_set(insn.modrm().register_index(), fpu_get(insn.modrm().register_index()) * fpu_get(0));
+ fpu_pop();
+}
+
+void SoftFPU::FIMUL_RM32(const X86::Instruction& insn)
+{
+ VERIFY(!insn.modrm().is_register());
+ auto m32int = (i32)insn.modrm().read32(m_cpu, insn).value();
+ // FIXME: Respect shadow values
+ fpu_set(0, fpu_get(0) * (long double)m32int);
+}
+void SoftFPU::FIMUL_RM16(const X86::Instruction& insn)
+{
+ VERIFY(!insn.modrm().is_register());
+ auto m16int = (i16)insn.modrm().read16(m_cpu, insn).value();
+ // FIXME: Respect shadow values
+ fpu_set(0, fpu_get(0) * (long double)m16int);
+}
+
+void SoftFPU::FDIV_RM32(const X86::Instruction& insn)
+{
+ if (insn.modrm().is_register()) {
+ fpu_set(0, fpu_get(0) / fpu_get(insn.modrm().register_index()));
+ } else {
+ auto new_f32 = insn.modrm().read32(m_cpu, insn);
+ // FIXME: Respect shadow values
+ auto f32 = bit_cast<float>(new_f32.value());
+ // FIXME: Raise IA on + infinity / +-infinity, +-0 / +-0, raise Z on finite / +-0
+ fpu_set(0, fpu_get(0) / f32);
+ }
+}
+void SoftFPU::FDIV_RM64(const X86::Instruction& insn)
+{
+ if (insn.modrm().is_register()) {
+ fpu_set(insn.modrm().register_index(), fpu_get(insn.modrm().register_index()) / fpu_get(0));
+ } else {
+ auto new_f64 = insn.modrm().read64(m_cpu, insn);
+ // FIXME: Respect shadow values
+ auto f64 = bit_cast<double>(new_f64.value());
+ // FIXME: Raise IA on + infinity / +-infinity, +-0 / +-0, raise Z on finite / +-0
+ fpu_set(0, fpu_get(0) / f64);
+ }
+}
+void SoftFPU::FDIVP(const X86::Instruction& insn)
+{
+ VERIFY(insn.modrm().is_register());
+ // FIXME: Raise IA on + infinity / +-infinity, +-0 / +-0, raise Z on finite / +-0
+ fpu_set(insn.modrm().register_index(), fpu_get(insn.modrm().register_index()) / fpu_get(0));
+ fpu_pop();
+}
+
+void SoftFPU::FDIVR_RM32(const X86::Instruction& insn)
+{
+ if (insn.modrm().is_register()) {
+ fpu_set(0, fpu_get(insn.modrm().register_index()) / fpu_get(0));
+ } else {
+ auto new_f32 = insn.modrm().read32(m_cpu, insn);
+ // FIXME: Respect shadow values
+ auto f32 = bit_cast<float>(new_f32.value());
+ // FIXME: Raise IA on + infinity / +-infinity, +-0 / +-0, raise Z on finite / +-0
+ fpu_set(0, f32 / fpu_get(0));
+ }
+}
+void SoftFPU::FDIVR_RM64(const X86::Instruction& insn)
+{
+ if (insn.modrm().is_register()) {
+ // XXX this is FDIVR, Instruction decodes this weirdly
+ //fpu_set(insn.modrm().register_index(), fpu_get(0) / fpu_get(insn.modrm().register_index()));
+ fpu_set(insn.modrm().register_index(), fpu_get(insn.modrm().register_index()) / fpu_get(0));
+ } else {
+ auto new_f64 = insn.modrm().read64(m_cpu, insn);
+ // FIXME: Respect shadow values
+ auto f64 = bit_cast<double>(new_f64.value());
+ // FIXME: Raise IA on + infinity / +-infinity, +-0 / +-0, raise Z on finite / +-0
+ fpu_set(0, f64 / fpu_get(0));
+ }
+}
+void SoftFPU::FDIVRP(const X86::Instruction& insn)
+{
+ VERIFY(insn.modrm().is_register());
+ // FIXME: Raise IA on + infinity / +-infinity, +-0 / +-0, raise Z on finite / +-0
+ fpu_set(insn.modrm().register_index(), fpu_get(0) / fpu_get(insn.modrm().register_index()));
+ fpu_pop();
+}
+
+void SoftFPU::FIDIV_RM16(const X86::Instruction& insn)
+{
+ VERIFY(!insn.modrm().is_register());
+ auto m16int = (i16)insn.modrm().read16(m_cpu, insn).value();
+ // FIXME: Respect shadow values
+ // FIXME: Raise IA on 0 / _=0, raise Z on finite / +-0
+ fpu_set(0, fpu_get(0) / (long double)m16int);
+}
+void SoftFPU::FIDIV_RM32(const X86::Instruction& insn)
+{
+ VERIFY(!insn.modrm().is_register());
+ auto m32int = (i32)insn.modrm().read32(m_cpu, insn).value();
+ // FIXME: Respect shadow values
+ // FIXME: Raise IA on 0 / _=0, raise Z on finite / +-0
+ fpu_set(0, fpu_get(0) / (long double)m32int);
+}
+
+void SoftFPU::FIDIVR_RM16(const X86::Instruction& insn)
+{
+ VERIFY(!insn.modrm().is_register());
+ auto m16int = (i16)insn.modrm().read16(m_cpu, insn).value();
+ // FIXME: Respect shadow values
+ // FIXME: Raise IA on 0 / _=0, raise Z on finite / +-0
+ fpu_set(0, (long double)m16int / fpu_get(0));
+}
+void SoftFPU::FIDIVR_RM32(const X86::Instruction& insn)
+{
+ VERIFY(!insn.modrm().is_register());
+ auto m32int = (i32)insn.modrm().read32(m_cpu, insn).value();
+ // FIXME: Respect shadow values
+ // FIXME: Raise IA on 0 / _=0, raise Z on finite / +-0
+ fpu_set(0, (long double)m32int / fpu_get(0));
+}
+
+void SoftFPU::FPREM(const X86::Instruction&)
+{
+ // FIXME: There are some exponent shenanigans supposed to be here
+ long double top = fpu_get(0);
+ long double one = fpu_get(1);
+
+ int Q = static_cast<int>(truncl(top / one));
+ top = top - (one * Q);
+ set_c2(0);
+ set_c1(Q & 1);
+ set_c3((Q >> 1) & 1);
+ set_c0((Q >> 2) & 1);
+
+ fpu_set(0, top);
+}
+void SoftFPU::FPREM1(const X86::Instruction&)
+{
+ // FIXME: There are some exponent shenanigans supposed to be here
+ long double top = fpu_get(0);
+ long double one = fpu_get(1);
+
+ int Q = static_cast<int>(roundl(top / one));
+ top = top - (one * Q);
+ set_c2(0);
+ set_c1(Q & 1);
+ set_c3((Q >> 1) & 1);
+ set_c0((Q >> 2) & 1);
+
+ fpu_set(0, top);
+}
+void SoftFPU::FABS(const X86::Instruction&)
+{
+ set_c1(0);
+ fpu_set(0, __builtin_fabsl(fpu_get(0)));
+}
+void SoftFPU::FCHS(const X86::Instruction&)
+{
+ set_c1(0);
+ fpu_set(0, -fpu_get(0));
+}
+
+void SoftFPU::FRNDINT(const X86::Instruction&)
+{
+ auto res = fpu_round<long double>(fpu_get(0));
+ if (auto rnd = (res - fpu_get(0))) {
+ if (rnd > 0)
+ set_c1(1);
+ else
+ set_c1(0);
+ }
+ fpu_set(0, res);
+}
+
+void SoftFPU::FSCALE(const X86::Instruction&)
+{
+ // FIXME: set C1 upon stack overflow or if result was rounded
+ fpu_set(0, fpu_get(0) * powl(2, floorl(fpu_get(1))));
+}
+
+void SoftFPU::FSQRT(const X86::Instruction&)
+{
+ // FIXME: set C1 upon stack overflow or if result was rounded
+ fpu_set(0, sqrtl(fpu_get(0)));
+}
+
+void SoftFPU::FXTRACT(const X86::Instruction&) { TODO_INSN(); }
+
+// COMPARISON
+
+// FIXME: there may be an implicit argument, how is this conveyed by the insn
+void SoftFPU::FCOM_RM32(const X86::Instruction&) { TODO_INSN(); }
+void SoftFPU::FCOM_RM64(const X86::Instruction&) { TODO_INSN(); }
+void SoftFPU::FCOMP_RM32(const X86::Instruction&) { TODO_INSN(); }
+void SoftFPU::FCOMP_RM64(const X86::Instruction&) { TODO_INSN(); }
+void SoftFPU::FCOMPP(const X86::Instruction&)
+{
+ if (fpu_isnan(0) || fpu_isnan(1)) {
+ fpu_set_exception(FPU_Exception::InvalidOperation);
+ if (m_fpu_mask_invalid)
+ fpu_set_unordered();
+ } else {
+ set_c2(0);
+ set_c0(fpu_get(0) < fpu_get(1));
+ set_c3(fpu_get(0) == fpu_get(1));
+ }
+ fpu_pop();
+ fpu_pop();
+}
+
+void SoftFPU::FUCOM(const X86::Instruction&) { TODO_INSN(); } // Needs QNaN detection
+void SoftFPU::FUCOMP(const X86::Instruction&) { TODO_INSN(); }
+void SoftFPU::FUCOMPP(const X86::Instruction&) { TODO_INSN(); }
+
+void SoftFPU::FICOM_RM16(const X86::Instruction& insn)
+{
+ // FIXME: Check for denormals
+ VERIFY(insn.modrm().is_register());
+ auto val_shd = insn.modrm().read16(m_cpu, insn);
+ warn_if_uninitialized(val_shd, "int16 compare to float");
+ auto val = static_cast<i16>(val_shd.value());
+ if (fpu_isnan(0)) {
+ fpu_set_unordered();
+ } else {
+ set_c0(fpu_get(0) < val);
+ set_c2(0);
+ set_c3(fpu_get(0) == val);
+ }
+ set_c1(0);
+}
+void SoftFPU::FICOM_RM32(const X86::Instruction& insn)
+{
+ // FIXME: Check for denormals
+ VERIFY(insn.modrm().is_register());
+ auto val_shd = insn.modrm().read32(m_cpu, insn);
+ warn_if_uninitialized(val_shd, "int32 comapre to float");
+ auto val = static_cast<i32>(val_shd.value());
+ if (fpu_isnan(0)) {
+ fpu_set_unordered();
+ } else {
+ set_c0(fpu_get(0) < val);
+ set_c2(0);
+ set_c3(fpu_get(0) == val);
+ }
+ set_c1(0);
+}
+void SoftFPU::FICOMP_RM16(const X86::Instruction& insn)
+{
+ FICOM_RM16(insn);
+ fpu_pop();
+}
+void SoftFPU::FICOMP_RM32(const X86::Instruction& insn)
+{
+ FICOM_RM32(insn);
+ fpu_pop();
+}
+
+void SoftFPU::FCOMI(const X86::Instruction& insn)
+{
+ auto i = insn.modrm().rm();
+ // FIXME: QNaN / exception handling.
+ set_c0(0);
+ if (isnan(fpu_get(0)) || isnan(fpu_get(1))) {
+ fpu_set_exception(FPU_Exception::InvalidOperation);
+ m_cpu.set_zf(1);
+ m_cpu.set_pf(1);
+ m_cpu.set_cf(1);
+ }
+ if (!fpu_is_set(1))
+ fpu_set_exception(FPU_Exception::Underflow);
+
+ m_cpu.set_zf(fpu_get(0) == fpu_get(i));
+ m_cpu.set_pf(false);
+ m_cpu.set_cf(fpu_get(0) < fpu_get(i));
+ // FIXME: is this supposed to be here?
+ // m_cpu.set_of(false);
+
+ // FIXME: Taint should be based on ST(0) and ST(i)
+ m_cpu.m_flags_tainted = false;
+}
+void SoftFPU::FCOMIP(const X86::Instruction& insn)
+{
+ FCOMI(insn);
+ fpu_pop();
+}
+
+void SoftFPU::FUCOMI(const X86::Instruction& insn)
+{
+ auto i = insn.modrm().rm();
+ // FIXME: Unordered comparison checks.
+ // FIXME: QNaN / exception handling.
+ set_c1(0);
+ if (fpu_isnan(0) || fpu_isnan(i)) {
+ m_cpu.set_zf(true);
+ m_cpu.set_pf(true);
+ m_cpu.set_cf(true);
+ } else {
+ m_cpu.set_zf(fpu_get(0) == fpu_get(i));
+ m_cpu.set_pf(false);
+ m_cpu.set_cf(fpu_get(0) < fpu_get(i));
+ m_cpu.set_of(false);
+ }
+
+ // FIXME: Taint should be based on ST(0) and ST(i)
+ m_cpu.m_flags_tainted = false;
+}
+void SoftFPU::FUCOMIP(const X86::Instruction& insn)
+{
+ FUCOMI(insn);
+ fpu_pop();
+}
+
+void SoftFPU::FTST(const X86::Instruction&)
+{
+ // FIXME: maybe check for denormal
+ set_c1(0);
+ if (fpu_isnan(0))
+ // raise #IA?
+ fpu_set_unordered();
+ else {
+ set_c0(fpu_get(0) < 0.);
+ set_c2(0);
+ set_c3(fpu_get(0) == 0.);
+ }
+}
+void SoftFPU::FXAM(const X86::Instruction&)
+{
+ if (m_reg_is_mmx[m_fpu_stack_top]) {
+ // technically a subset of NaN/INF, with the Tag set to valid,
+ // but we have our own helper for this
+ set_c0(0);
+ set_c2(0);
+ set_c3(0);
+ } else {
+ switch (fpu_get_tag(0)) {
+ case FPU_Tag::Valid:
+ set_c0(0);
+ set_c2(1);
+ set_c3(0);
+ break;
+ case FPU_Tag::Zero:
+ set_c0(1);
+ set_c2(0);
+ set_c3(0);
+ break;
+ case FPU_Tag::Special:
+ if (isinf(fpu_get(0))) {
+ set_c0(1);
+ set_c2(1);
+ set_c3(0);
+ } else if (isnan(fpu_get(0))) {
+ set_c0(1);
+ set_c2(0);
+ set_c3(0);
+ } else {
+ // denormalized
+ set_c0(0);
+ set_c2(1);
+ set_c3(1);
+ }
+ break;
+ case FPU_Tag::Empty:
+ set_c0(1);
+ set_c2(0);
+ set_c3(1);
+ break;
+ default:
+ VERIFY_NOT_REACHED();
+ }
+ }
+ set_c1(signbit(fpu_get(0)));
+}
+
+// TRANSCENDENTAL
+void SoftFPU::FSIN(const X86::Instruction&)
+{
+ // FIXME: set C1 upon stack overflow or if result was rounded
+ // FIXME: Set C2 to 1 if ST(0) is outside range of -2^63 to +2^63; else set to 0
+ fpu_set(0, sinl(fpu_get(0)));
+}
+void SoftFPU::FCOS(const X86::Instruction&)
+{
+ // FIXME: set C1 upon stack overflow or if result was rounded
+ // FIXME: Set C2 to 1 if ST(0) is outside range of -2^63 to +2^63; else set to 0
+ fpu_set(0, cosl(fpu_get(0)));
+}
+void SoftFPU::FSINCOS(const X86::Instruction&)
+{
+ // FIXME: set C1 upon stack overflow or if result was rounded
+ // FIXME: Set C2 to 1 if ST(0) is outside range of -2^63 to +2^63; else set to 0s
+ long double sin = sinl(fpu_get(0));
+ long double cos = cosl(fpu_get(0));
+ fpu_set(0, sin);
+ fpu_push(cos);
+}
+
+void SoftFPU::FPTAN(const X86::Instruction&)
+{
+ // FIXME: set C1 upon stack overflow or if result was rounded
+ // FIXME: Set C2 to 1 if ST(0) is outside range of -2^63 to +2^63; else set to 0
+ fpu_set(0, tanl(fpu_get(0)));
+ fpu_push(1.0f);
+}
+void SoftFPU::FPATAN(const X86::Instruction&)
+{
+ // FIXME: set C1 on stack underflow, or on rounding
+ // FIXME: Exceptions
+ fpu_set(1, atan2l(fpu_get(1), fpu_get(0)));
+ fpu_pop();
+}
+
+void SoftFPU::F2XM1(const X86::Instruction&)
+{
+ // FIXME: validate ST(0) is in range –1.0 to +1.0
+ auto val = fpu_get(0);
+ // FIXME: Set C0, C2, C3 in FPU status word.
+ fpu_set(0, powl(2, val) - 1.0l);
+}
+void SoftFPU::FYL2X(const X86::Instruction&)
+{
+ // FIXME: raise precision and under/overflow
+ // FIXME: detect denormal operands
+ // FIXME: QNaN
+ auto f0 = fpu_get(0);
+ auto f1 = fpu_get(1);
+
+ if (f0 < 0. || isnan(f0) || isnan(f1)
+ || (isinf(f0) && f1 == 0.) || (f0 == 1. && isinf(f1)))
+ fpu_set_exception(FPU_Exception::InvalidOperation);
+ if (f0 == 0.)
+ fpu_set_exception(FPU_Exception::ZeroDivide);
+
+ fpu_set(1, f1 * log2l(f0));
+ fpu_pop();
+}
+void SoftFPU::FYL2XP1(const X86::Instruction&)
+{
+ // FIXME: raise #O #U #P #D
+ // FIXME: QNaN
+ auto f0 = fpu_get(0);
+ auto f1 = fpu_get(1);
+ if (isnan(f0) || isnan(f1)
+ || (isinf(f1) && f0 == 0))
+ fpu_set_exception(FPU_Exception::InvalidOperation);
+
+ fpu_set(1, (f1 * log2l(f0 + 1.0l)));
+ fpu_pop();
+}
+
+// LOAD CONSTANT
+void SoftFPU::FLD1(const X86::Instruction&)
+{
+ fpu_push(1.0l);
+}
+void SoftFPU::FLDZ(const X86::Instruction&)
+{
+ fpu_push(0.0l);
+}
+void SoftFPU::FLDPI(const X86::Instruction&)
+{
+ fpu_push(M_PIl);
+}
+void SoftFPU::FLDL2E(const X86::Instruction&)
+{
+ fpu_push(M_LOG2El);
+}
+void SoftFPU::FLDLN2(const X86::Instruction&)
+{
+ fpu_push(M_LN2l);
+}
+void SoftFPU::FLDL2T(const X86::Instruction&)
+{
+ fpu_push(log2l(10.0l));
+}
+void SoftFPU::FLDLG2(const X86::Instruction&)
+{
+ fpu_push(log10l(2.0l));
+}
+
+// CONTROL
+void SoftFPU::FINCSTP(const X86::Instruction&)
+{
+ m_fpu_stack_top = (m_fpu_stack_top + 1u) % 8u;
+ set_c1(0);
+}
+void SoftFPU::FDECSTP(const X86::Instruction&)
+{
+ m_fpu_stack_top = (m_fpu_stack_top - 1u) % 8u;
+ set_c1(0);
+}
+
+void SoftFPU::FFREE(const X86::Instruction& insn)
+{
+ fpu_set_tag(insn.modrm().reg_fpu(), FPU_Tag::Empty);
+}
+void SoftFPU::FFREEP(const X86::Instruction& insn)
+{
+ FFREE(insn);
+ fpu_pop();
+}
+
+void SoftFPU::FNINIT(const X86::Instruction&)
+{
+ m_fpu_cw = 0x037F;
+ m_fpu_sw = 0;
+ m_fpu_tw = 0xFFFF;
+
+ m_fpu_ip = 0;
+ m_fpu_cs = 0;
+
+ m_fpu_dp = 0;
+ m_fpu_ds = 0;
+
+ m_fpu_iop = 0;
+};
+void SoftFPU::FNCLEX(const X86::Instruction&)
+{
+ m_fpu_error_invalid = 0;
+ m_fpu_error_denorm = 0;
+ m_fpu_error_zero_div = 0;
+ m_fpu_error_overflow = 0;
+ m_fpu_error_underflow = 0;
+ m_fpu_error_precision = 0;
+ m_fpu_error_stackfault = 0;
+ m_fpu_busy = 0;
+}
+
+void SoftFPU::FNSTCW(const X86::Instruction& insn)
+{
+ insn.modrm().write16(m_cpu, insn, shadow_wrap_as_initialized(m_fpu_cw));
+}
+void SoftFPU::FLDCW(const X86::Instruction& insn)
+{
+ m_fpu_cw = insn.modrm().read16(m_cpu, insn).value();
+}
+
+void SoftFPU::FNSTENV(const X86::Instruction& insn)
+{
+ // Assuming we are always in Protected mode
+ // FIXME: 16-bit Format
+
+ // 32-bit Format
+ /* 31--------------16---------------0
+ * | | CW | 0
+ * +----------------+---------------+
+ * | | SW | 4
+ * +----------------+---------------+
+ * | | TW | 8
+ * +----------------+---------------+
+ * | FIP | 12
+ * +----+-----------+---------------+
+ * |0000|fpuOp[10:0]| FIP_sel | 16
+ * +----+-----------+---------------+
+ * | FDP | 20
+ * +----------------+---------------+
+ * | | FDP_ds | 24
+ * +----------------|---------------+
+ * */
+
+ auto address = insn.modrm().resolve(m_cpu, insn);
+
+ m_cpu.write_memory16(address, shadow_wrap_as_initialized(m_fpu_cw));
+ address.set_offset(address.offset() + 4);
+ m_cpu.write_memory16(address, shadow_wrap_as_initialized(m_fpu_sw));
+ address.set_offset(address.offset() + 4);
+ m_cpu.write_memory16(address, shadow_wrap_as_initialized(m_fpu_tw));
+ address.set_offset(address.offset() + 4);
+ m_cpu.write_memory32(address, shadow_wrap_as_initialized(m_fpu_ip));
+ address.set_offset(address.offset() + 4);
+ m_cpu.write_memory16(address, shadow_wrap_as_initialized(m_fpu_cs));
+ address.set_offset(address.offset() + 2);
+ m_cpu.write_memory16(address, shadow_wrap_as_initialized<u16>(m_fpu_iop & 0x3FFU));
+ address.set_offset(address.offset() + 2);
+ m_cpu.write_memory32(address, shadow_wrap_as_initialized(m_fpu_dp));
+ address.set_offset(address.offset() + 4);
+ m_cpu.write_memory16(address, shadow_wrap_as_initialized(m_fpu_ds));
+}
+void SoftFPU::FLDENV(const X86::Instruction& insn)
+{
+ // Assuming we are always in Protected mode
+ // FIXME: 16-bit Format
+ auto address = insn.modrm().resolve(m_cpu, insn);
+
+ // FIXME: Shadow Values
+ m_fpu_cw = m_cpu.read_memory16(address).value();
+ address.set_offset(address.offset() + 4);
+ m_fpu_sw = m_cpu.read_memory16(address).value();
+ address.set_offset(address.offset() + 4);
+ m_fpu_tw = m_cpu.read_memory16(address).value();
+ address.set_offset(address.offset() + 4);
+ m_fpu_ip = m_cpu.read_memory32(address).value();
+ address.set_offset(address.offset() + 4);
+ m_fpu_cs = m_cpu.read_memory16(address).value();
+ address.set_offset(address.offset() + 2);
+ m_fpu_iop = m_cpu.read_memory16(address).value();
+ address.set_offset(address.offset() + 2);
+ m_fpu_dp = m_cpu.read_memory32(address).value();
+ address.set_offset(address.offset() + 4);
+ m_fpu_ds = m_cpu.read_memory16(address).value();
+}
+
+void SoftFPU::FNSAVE(const X86::Instruction& insn)
+{
+ FNSTENV(insn);
+
+ auto address = insn.modrm().resolve(m_cpu, insn);
+ address.set_offset(address.offset() + 28); // size of the ENV
+
+ // write fpu-stack to memory
+ u8 raw_data[80];
+ for (int i = 0; i < 8; ++i) {
+ memcpy(raw_data + 10 * i, &m_storage[i], 10);
+ }
+ for (int i = 0; i < 5; ++i) {
+ // FIXME: Shadow Value
+ m_cpu.write_memory128(address, shadow_wrap_as_initialized(((u128*)raw_data)[i]));
+ address.set_offset(address.offset() + 16);
+ }
+
+ FNINIT(insn);
+}
+void SoftFPU::FRSTOR(const X86::Instruction& insn)
+{
+ FLDENV(insn);
+
+ auto address = insn.modrm().resolve(m_cpu, insn);
+ address.set_offset(address.offset() + 28); // size of the ENV
+
+ // read fpu-stack from memory
+ u8 raw_data[80];
+ for (int i = 0; i < 5; ++i) {
+ // FIXME: Shadow Value
+ ((u128*)raw_data)[i] = m_cpu.read_memory128(address).value();
+ address.set_offset(address.offset() + 16);
+ }
+ for (int i = 0; i < 8; ++i) {
+ memcpy(&m_storage[i], raw_data + 10 * i, 10);
+ }
+
+ memset(m_reg_is_mmx, 0, sizeof(m_reg_is_mmx));
+}
+
+void SoftFPU::FNSTSW(const X86::Instruction& insn)
+{
+ insn.modrm().write16(m_cpu, insn, shadow_wrap_as_initialized(m_fpu_sw));
+}
+void SoftFPU::FNSTSW_AX(const X86::Instruction&)
+{
+ m_cpu.set_ax(shadow_wrap_as_initialized(m_fpu_sw));
+}
+// FIXME: FWAIT
+void SoftFPU::FNOP(const X86::Instruction&) { }
+
+// DO NOTHING?
+void SoftFPU::FNENI(const X86::Instruction&) { TODO_INSN(); }
+void SoftFPU::FNDISI(const X86::Instruction&) { TODO_INSN(); }
+void SoftFPU::FNSETPM(const X86::Instruction&) { TODO_INSN(); }
+
+// MMX
+// helpers
+#define LOAD_MM_MM64M() \
+ MMX mm; \
+ MMX mm64m; \
+ if (insn.modrm().mod() == 0b11) { /* 0b11 signals a register */ \
+ mm64m = mmx_get(insn.modrm().rm()); \
+ } else { \
+ auto temp = insn.modrm().read64(m_cpu, insn); \
+ warn_if_uninitialized(temp, "Read of uninitialized Memmory as Packed integer"); \
+ mm64m.raw = temp.value(); \
+ } \
+ mm = mmx_get(insn.modrm().reg())
+
+#define MMX_intrinsic(intrinsic, res_type, actor_type) \
+ LOAD_MM_MM64M(); \
+ mm.res_type = __builtin_ia32_##intrinsic(mm.actor_type, mm64m.actor_type); \
+ mmx_set(insn.modrm().reg(), mm); \
+ mmx_common();
+
+// ARITHMETIC
+void SoftFPU::PADDB_mm1_mm2m64(const X86::Instruction& insn)
+{
+ LOAD_MM_MM64M();
+ mm.v8 += mm64m.v8;
+ mmx_set(insn.modrm().reg(), mm);
+ mmx_common();
+}
+void SoftFPU::PADDW_mm1_mm2m64(const X86::Instruction& insn)
+{
+ LOAD_MM_MM64M();
+ mm.v16 += mm64m.v16;
+ mmx_set(insn.modrm().reg(), mm);
+ mmx_common();
+}
+void SoftFPU::PADDD_mm1_mm2m64(const X86::Instruction& insn)
{
- if (input > NumericLimits<R>::max())
- return NumericLimits<R>::max();
- if (input < NumericLimits<R>::min())
- return NumericLimits<R>::min();
- return static_cast<R>(input);
+ LOAD_MM_MM64M();
+ mm.v32 += mm64m.v32;
+ mmx_set(insn.modrm().reg(), mm);
+ mmx_common();
}
-template<Unsigned R, Unsigned I>
-__attribute__((const)) ALWAYS_INLINE R unsigned_saturate(I input)
+void SoftFPU::PADDSB_mm1_mm2m64(const X86::Instruction& insn)
{
- if (input > NumericLimits<R>::max())
- return NumericLimits<R>::max();
- return static_cast<R>(input);
+ MMX_intrinsic(paddsb, v8, v8);
}
+void SoftFPU::PADDSW_mm1_mm2m64(const X86::Instruction& insn)
+{
+ MMX_intrinsic(paddsw, v16, v16);
+}
+void SoftFPU::PADDUSB_mm1_mm2m64(const X86::Instruction& insn)
+{
+ MMX_intrinsic(paddusb, v8, v8);
+}
+void SoftFPU::PADDUSW_mm1_mm2m64(const X86::Instruction& insn)
+{
+ MMX_intrinsic(paddusw, v16, v16);
+}
+
+void SoftFPU::PSUBB_mm1_mm2m64(const X86::Instruction& insn)
+{
+ LOAD_MM_MM64M();
+ mm.v8 -= mm64m.v8;
+ mmx_set(insn.modrm().reg(), mm);
+ mmx_common();
+}
+void SoftFPU::PSUBW_mm1_mm2m64(const X86::Instruction& insn)
+{
+ LOAD_MM_MM64M();
+ mm.v16 -= mm64m.v16;
+ mmx_set(insn.modrm().reg(), mm);
+ mmx_common();
+}
+void SoftFPU::PSUBD_mm1_mm2m64(const X86::Instruction& insn)
+{
+ LOAD_MM_MM64M();
+ mm.v32 -= mm64m.v32;
+ mmx_set(insn.modrm().reg(), mm);
+ mmx_common();
+}
+void SoftFPU::PSUBSB_mm1_mm2m64(const X86::Instruction& insn)
+{
+ MMX_intrinsic(psubsb, v8, v8);
+}
+void SoftFPU::PSUBSW_mm1_mm2m64(const X86::Instruction& insn)
+{
+ MMX_intrinsic(psubsw, v16, v16);
+}
+void SoftFPU::PSUBUSB_mm1_mm2m64(const X86::Instruction& insn)
+{
+ MMX_intrinsic(psubusb, v8, v8);
+}
+void SoftFPU::PSUBUSW_mm1_mm2m64(const X86::Instruction& insn)
+{
+ MMX_intrinsic(psubusw, v16, v16);
+}
+
+void SoftFPU::PMULHW_mm1_mm2m64(const X86::Instruction& insn)
+{
+ MMX_intrinsic(pmulhw, v16, v16);
+}
+void SoftFPU::PMULLW_mm1_mm2m64(const X86::Instruction& insn)
+{
+ MMX_intrinsic(pmullw, v16, v16);
+}
+
+void SoftFPU::PMADDWD_mm1_mm2m64(const X86::Instruction& insn)
+{
+ MMX_intrinsic(pmaddwd, v32, v16);
+}
+
+// COMPARISON
+void SoftFPU::PCMPEQB_mm1_mm2m64(const X86::Instruction& insn)
+{
+ LOAD_MM_MM64M();
+
+ mm.v8 = mm.v8 == mm64m.v8;
+
+ mmx_set(insn.modrm().reg(), mm);
+ mmx_common();
+}
+void SoftFPU::PCMPEQW_mm1_mm2m64(const X86::Instruction& insn)
+{
+ LOAD_MM_MM64M();
+
+ mm.v16 = mm.v16 == mm64m.v16;
+ mmx_set(insn.modrm().reg(), mm);
+ mmx_common();
+}
+void SoftFPU::PCMPEQD_mm1_mm2m64(const X86::Instruction& insn)
+{
+ LOAD_MM_MM64M();
+
+ mm.v32 = mm.v32 == mm64m.v32;
+
+ mmx_set(insn.modrm().reg(), mm);
+ mmx_common();
+}
+
+void SoftFPU::PCMPGTB_mm1_mm2m64(const X86::Instruction& insn)
+{
+ LOAD_MM_MM64M();
+
+ mm.v8 = mm.v8 > mm64m.v8;
+
+ mmx_set(insn.modrm().reg(), mm);
+ mmx_common();
+}
+void SoftFPU::PCMPGTW_mm1_mm2m64(const X86::Instruction& insn)
+{
+ LOAD_MM_MM64M();
-}
\ No newline at end of file
+ mm.v16 = mm.v16 > mm64m.v16;
+
+ mmx_set(insn.modrm().reg(), mm);
+ mmx_common();
+}
+void SoftFPU::PCMPGTD_mm1_mm2m64(const X86::Instruction& insn)
+{
+ LOAD_MM_MM64M();
+
+ mm.v32 = mm.v32 > mm64m.v32;
+
+ mmx_set(insn.modrm().reg(), mm);
+ mmx_common();
+}
+
+// CONVERSION
+void SoftFPU::PACKSSDW_mm1_mm2m64(const X86::Instruction& insn)
+{
+ MMX_intrinsic(packssdw, v16, v32);
+}
+void SoftFPU::PACKSSWB_mm1_mm2m64(const X86::Instruction& insn)
+{
+ MMX_intrinsic(packsswb, v8, v16);
+}
+void SoftFPU::PACKUSWB_mm1_mm2m64(const X86::Instruction& insn)
+{
+ MMX_intrinsic(packuswb, v8, v16);
+}
+
+// UNPACK
+void SoftFPU::PUNPCKHBW_mm1_mm2m64(const X86::Instruction& insn)
+{
+ MMX_intrinsic(punpckhbw, v8, v8);
+}
+
+void SoftFPU::PUNPCKHWD_mm1_mm2m64(const X86::Instruction& insn)
+{
+ MMX_intrinsic(punpckhwd, v16, v16);
+}
+void SoftFPU::PUNPCKHDQ_mm1_mm2m64(const X86::Instruction& insn)
+{
+ MMX_intrinsic(punpckhdq, v32, v32);
+}
+
+void SoftFPU::PUNPCKLBW_mm1_mm2m32(const X86::Instruction& insn)
+{
+ MMX_intrinsic(punpcklbw, v8, v8);
+}
+void SoftFPU::PUNPCKLWD_mm1_mm2m32(const X86::Instruction& insn)
+{
+ MMX_intrinsic(punpcklwd, v16, v16);
+}
+void SoftFPU::PUNPCKLDQ_mm1_mm2m32(const X86::Instruction& insn)
+{
+ MMX_intrinsic(punpckldq, v32, v32);
+}
+
+// LOGICAL
+void SoftFPU::PAND_mm1_mm2m64(const X86::Instruction& insn)
+{
+ LOAD_MM_MM64M();
+
+ mm.raw &= mm64m.raw;
+
+ mmx_set(insn.modrm().reg(), mm);
+ mmx_common();
+}
+void SoftFPU::PANDN_mm1_mm2m64(const X86::Instruction& insn)
+{
+ LOAD_MM_MM64M();
+
+ mm.raw &= ~mm64m.raw;
+
+ mmx_set(insn.modrm().reg(), mm);
+ mmx_common();
+}
+void SoftFPU::POR_mm1_mm2m64(const X86::Instruction& insn)
+{
+ LOAD_MM_MM64M();
+
+ mm.raw |= mm64m.raw;
+
+ mmx_set(insn.modrm().reg(), mm);
+ mmx_common();
+}
+void SoftFPU::PXOR_mm1_mm2m64(const X86::Instruction& insn)
+{
+ LOAD_MM_MM64M();
+
+ mm.raw ^= mm64m.raw;
+
+ mmx_set(insn.modrm().reg(), mm);
+ mmx_common();
+}
+
+// SHIFT
+void SoftFPU::PSLLW_mm1_mm2m64(const X86::Instruction& insn)
+{
+ LOAD_MM_MM64M();
+
+ mm.v16 <<= mm64m.v16;
+
+ mmx_set(insn.modrm().reg(), mm);
+ mmx_common();
+}
+void SoftFPU::PSLLW_mm1_imm8(const X86::Instruction& insn)
+{
+ u8 imm = insn.imm8();
+ MMX mm = mmx_get(insn.modrm().reg());
+
+ mm.v16 <<= imm;
+
+ mmx_set(insn.modrm().reg(), mm);
+ mmx_common();
+}
+void SoftFPU::PSLLD_mm1_mm2m64(const X86::Instruction& insn)
+{
+ LOAD_MM_MM64M();
+
+ mm.v32 <<= mm64m.v32;
+
+ mmx_set(insn.modrm().reg(), mm);
+ mmx_common();
+}
+void SoftFPU::PSLLD_mm1_imm8(const X86::Instruction& insn)
+{
+ u8 imm = insn.imm8();
+ MMX mm = mmx_get(insn.modrm().reg());
+
+ mm.v32 <<= imm;
+
+ mmx_set(insn.modrm().reg(), mm);
+ mmx_common();
+}
+void SoftFPU::PSLLQ_mm1_mm2m64(const X86::Instruction& insn)
+{
+ LOAD_MM_MM64M();
+
+ mm.raw <<= mm64m.raw;
+
+ mmx_set(insn.modrm().reg(), mm);
+ mmx_common();
+}
+void SoftFPU::PSLLQ_mm1_imm8(const X86::Instruction& insn)
+{
+ u8 imm = insn.imm8();
+ MMX mm = mmx_get(insn.modrm().reg());
+
+ mm.raw <<= imm;
+
+ mmx_set(insn.modrm().reg(), mm);
+ mmx_common();
+}
+void SoftFPU::PSRAW_mm1_mm2m64(const X86::Instruction& insn)
+{
+ LOAD_MM_MM64M();
+
+ mm.v16 >>= mm64m.v16;
+
+ mmx_set(insn.modrm().reg(), mm);
+ mmx_common();
+}
+void SoftFPU::PSRAW_mm1_imm8(const X86::Instruction& insn)
+{
+ u8 imm = insn.imm8();
+ MMX mm = mmx_get(insn.modrm().reg());
+
+ mm.v16 >>= imm;
+
+ mmx_set(insn.modrm().reg(), mm);
+ mmx_common();
+}
+void SoftFPU::PSRAD_mm1_mm2m64(const X86::Instruction& insn)
+{
+ LOAD_MM_MM64M();
+
+ mm.v32 >>= mm64m.v32;
+
+ mmx_set(insn.modrm().reg(), mm);
+ mmx_common();
+}
+void SoftFPU::PSRAD_mm1_imm8(const X86::Instruction& insn)
+{
+ u8 imm = insn.imm8();
+ MMX mm = mmx_get(insn.modrm().reg());
+
+ mm.v32 >>= imm;
+
+ mmx_set(insn.modrm().reg(), mm);
+ mmx_common();
+}
+void SoftFPU::PSRLW_mm1_mm2m64(const X86::Instruction& insn)
+{
+ LOAD_MM_MM64M();
+
+ mm.v16u >>= mm64m.v16u;
+
+ mmx_set(insn.modrm().reg(), mm);
+ mmx_common();
+}
+void SoftFPU::PSRLW_mm1_imm8(const X86::Instruction& insn)
+{
+ u8 imm = insn.imm8();
+ MMX mm = mmx_get(insn.modrm().reg());
+
+ mm.v16u >>= imm;
+
+ mmx_set(insn.modrm().reg(), mm);
+ mmx_common();
+}
+void SoftFPU::PSRLD_mm1_mm2m64(const X86::Instruction& insn)
+{
+ LOAD_MM_MM64M();
+
+ mm.v32u >>= mm64m.v32u;
+
+ mmx_set(insn.modrm().reg(), mm);
+ mmx_common();
+}
+void SoftFPU::PSRLD_mm1_imm8(const X86::Instruction& insn)
+{
+ u8 imm = insn.imm8();
+ MMX mm = mmx_get(insn.modrm().reg());
+
+ mm.v32u >>= imm;
+
+ mmx_set(insn.modrm().reg(), mm);
+ mmx_common();
+}
+void SoftFPU::PSRLQ_mm1_mm2m64(const X86::Instruction& insn)
+{
+ LOAD_MM_MM64M();
+
+ mm.raw >>= mm64m.raw;
+
+ mmx_set(insn.modrm().reg(), mm);
+ mmx_common();
+}
+void SoftFPU::PSRLQ_mm1_imm8(const X86::Instruction& insn)
+{
+ u8 imm = insn.imm8();
+ MMX mm = mmx_get(insn.modrm().reg());
+
+ mm.raw >>= imm;
+
+ mmx_set(insn.modrm().reg(), mm);
+ mmx_common();
+}
+
+// DATA TRANSFER
+void SoftFPU::MOVD_mm1_rm32(const X86::Instruction& insn)
+{
+ u8 mmx_index = insn.modrm().reg();
+ // FIXME:: Shadow Value
+ // upper half is zeroed out
+ mmx_set(mmx_index, { .raw = insn.modrm().read32(m_cpu, insn).value() });
+ mmx_common();
+};
+void SoftFPU::MOVD_rm32_mm2(const X86::Instruction& insn)
+{
+ u8 mmx_index = insn.modrm().reg();
+ // FIXME:: Shadow Value
+ insn.modrm().write32(m_cpu, insn,
+ shadow_wrap_as_initialized(static_cast<u32>(mmx_get(mmx_index).raw)));
+ mmx_common();
+};
+
+void SoftFPU::MOVQ_mm1_mm2m64(const X86::Instruction& insn)
+{
+ // FIXME: Shadow Value
+ if (insn.modrm().mod() == 0b11) {
+ // instruction
+ mmx_set(insn.modrm().reg(),
+ mmx_get(insn.modrm().rm()));
+ } else {
+ mmx_set(insn.modrm().reg(),
+ { .raw = insn.modrm().read64(m_cpu, insn).value() });
+ }
+ mmx_common();
+}
+void SoftFPU::MOVQ_mm1m64_mm2(const X86::Instruction& insn)
+{
+ if (insn.modrm().mod() == 0b11) {
+ // instruction
+ mmx_set(insn.modrm().rm(),
+ mmx_get(insn.modrm().reg()));
+ } else {
+ // FIXME: Shadow Value
+ insn.modrm().write64(m_cpu, insn,
+ shadow_wrap_as_initialized(mmx_get(insn.modrm().reg()).raw));
+ }
+ mmx_common();
+}
+void SoftFPU::MOVQ_mm1_rm64(const X86::Instruction&) { TODO_INSN(); }; // long mode
+void SoftFPU::MOVQ_rm64_mm2(const X86::Instruction&) { TODO_INSN(); }; // long mode
+
+// EMPTY MMX STATE
+void SoftFPU::EMMS(const X86::Instruction&)
+{
+ // clear tagword
+ m_fpu_tw = 0xFFFF;
+}
+
+}
|
4a271430f879f2fb90c5ea0b27de6214d685eb28
|
2020-03-07 04:55:30
|
Andreas Kling
|
shell: Set up the PWD environment variable early
| false
|
Set up the PWD environment variable early
|
shell
|
diff --git a/Shell/main.cpp b/Shell/main.cpp
index 992f2740cbb9..99a4b780baba 100644
--- a/Shell/main.cpp
+++ b/Shell/main.cpp
@@ -981,6 +981,13 @@ int main(int argc, char** argv)
if (rc < 0)
perror("ttyname_r");
+ {
+ auto* cwd = getcwd(nullptr, 0);
+ g.cwd = cwd;
+ setenv("PWD", cwd, 1);
+ free(cwd);
+ }
+
{
auto* pw = getpwuid(getuid());
if (pw) {
@@ -1012,13 +1019,6 @@ int main(int argc, char** argv)
return 0;
}
- {
- auto* cwd = getcwd(nullptr, 0);
- g.cwd = cwd;
- setenv("PWD", cwd, 1);
- free(cwd);
- }
-
g.directory_stack.append(g.cwd);
load_history();
|
8e9d031cb3327619982297fa878265692c23edb4
|
2020-04-12 21:38:11
|
Hüseyin ASLITÜRK
|
libgfx: Add Bitmap::rotated and Bitmap::flipped
| false
|
Add Bitmap::rotated and Bitmap::flipped
|
libgfx
|
diff --git a/Libraries/LibGfx/Bitmap.cpp b/Libraries/LibGfx/Bitmap.cpp
index 962ea59ba9da..3cbf6b2001bc 100644
--- a/Libraries/LibGfx/Bitmap.cpp
+++ b/Libraries/LibGfx/Bitmap.cpp
@@ -98,6 +98,48 @@ Bitmap::Bitmap(BitmapFormat format, NonnullRefPtr<SharedBuffer>&& shared_buffer,
ASSERT(format != BitmapFormat::Indexed8);
}
+NonnullRefPtr<Gfx::Bitmap> Bitmap::rotated(Gfx::RotationDirection rotation_direction) const
+{
+ auto w = this->width();
+ auto h = this->height();
+
+ auto new_bitmap = Gfx::Bitmap::create(this->format(), { h, w });
+
+ for (int i = 0; i < w; i++) {
+ for (int j = 0; j < h; j++) {
+ Color color;
+ if (rotation_direction == Gfx::RotationDirection::Left)
+ color = this->get_pixel(w - i - 1, j);
+ else
+ color = this->get_pixel(i, h - j - 1);
+
+ new_bitmap->set_pixel(j, i, color);
+ }
+ }
+
+ return new_bitmap;
+}
+
+NonnullRefPtr<Gfx::Bitmap> Bitmap::flipped(Gfx::Orientation orientation) const
+{
+ auto w = this->width();
+ auto h = this->height();
+
+ auto new_bitmap = Gfx::Bitmap::create(this->format(), { w, h });
+
+ for (int i = 0; i < w; i++) {
+ for (int j = 0; j < h; j++) {
+ Color color = this->get_pixel(i, j);
+ if (orientation == Orientation::Vertical)
+ new_bitmap->set_pixel(i, h - j - 1, color);
+ else
+ new_bitmap->set_pixel(w - i - 1, j, color);
+ }
+ }
+
+ return new_bitmap;
+}
+
NonnullRefPtr<Bitmap> Bitmap::to_bitmap_backed_by_shared_buffer() const
{
if (m_shared_buffer)
diff --git a/Libraries/LibGfx/Bitmap.h b/Libraries/LibGfx/Bitmap.h
index 7fdec97e65b4..3340521a4b67 100644
--- a/Libraries/LibGfx/Bitmap.h
+++ b/Libraries/LibGfx/Bitmap.h
@@ -42,6 +42,11 @@ enum class BitmapFormat {
Indexed8
};
+enum RotationDirection {
+ Left,
+ Right
+};
+
class Bitmap : public RefCounted<Bitmap> {
public:
static NonnullRefPtr<Bitmap> create(BitmapFormat, const Size&);
@@ -50,6 +55,8 @@ class Bitmap : public RefCounted<Bitmap> {
static RefPtr<Bitmap> load_from_file(const StringView& path);
static NonnullRefPtr<Bitmap> create_with_shared_buffer(BitmapFormat, NonnullRefPtr<SharedBuffer>&&, const Size&);
+ NonnullRefPtr<Gfx::Bitmap> rotated(Gfx::RotationDirection) const;
+ NonnullRefPtr<Gfx::Bitmap> flipped(Gfx::Orientation) const;
NonnullRefPtr<Bitmap> to_bitmap_backed_by_shared_buffer() const;
ShareableBitmap to_shareable_bitmap(pid_t peer_pid = -1) const;
|
4d932ce701936b9f01032cb79bacfce2ecac9698
|
2020-05-02 15:54:10
|
AnotherTest
|
libcrypto: Tweak ::prune_padding() to be more intuitive with loop bounds
| false
|
Tweak ::prune_padding() to be more intuitive with loop bounds
|
libcrypto
|
diff --git a/Libraries/LibCrypto/Cipher/Mode/Mode.h b/Libraries/LibCrypto/Cipher/Mode/Mode.h
index f4c45c78496b..ee627a4e8b84 100644
--- a/Libraries/LibCrypto/Cipher/Mode/Mode.h
+++ b/Libraries/LibCrypto/Cipher/Mode/Mode.h
@@ -68,8 +68,8 @@ class Mode {
// cannot be padding (the entire block cannot be padding)
return;
}
- for (auto i = maybe_padding_length; i > 0; --i) {
- if (data[size - i] != maybe_padding_length) {
+ for (auto i = size - maybe_padding_length; i < size; ++i) {
+ if (data[i] != maybe_padding_length) {
// not padding, part of data
return;
}
@@ -84,8 +84,8 @@ class Mode {
return;
}
// FIXME: If we want to constant-time operations, this loop should not stop
- for (auto i = maybe_padding_length; i > 0; --i) {
- if (data[size - i - 1] != maybe_padding_length) {
+ for (auto i = size - maybe_padding_length - 1; i < size; ++i) {
+ if (data[i] != maybe_padding_length) {
// note that this is likely invalid padding
return;
}
|
fdacfefd0933af5daf3609a1e44de0675fb62217
|
2020-12-28 03:19:08
|
Idan Horowitz
|
libvt: Use the 'U+FFFD replacement character' to indicate a parsing error
| false
|
Use the 'U+FFFD replacement character' to indicate a parsing error
|
libvt
|
diff --git a/Libraries/LibVT/Terminal.cpp b/Libraries/LibVT/Terminal.cpp
index 1943a5bd5c9c..8eafd88d4425 100644
--- a/Libraries/LibVT/Terminal.cpp
+++ b/Libraries/LibVT/Terminal.cpp
@@ -829,7 +829,7 @@ void Terminal::on_input(u8 ch)
auto fail_utf8_parse = [this] {
m_parser_state = Normal;
- on_code_point('%');
+ on_code_point(U'�');
};
auto advance_utf8_parse = [this, ch] {
|
d1916700ea264a75e56c11991827257c29d77c07
|
2019-10-22 00:01:32
|
Andreas Kling
|
hackstudio: Restrict the "Go to line" shortcut to the text editor
| false
|
Restrict the "Go to line" shortcut to the text editor
|
hackstudio
|
diff --git a/DevTools/HackStudio/main.cpp b/DevTools/HackStudio/main.cpp
index 91420214934f..c3b2e95b556d 100644
--- a/DevTools/HackStudio/main.cpp
+++ b/DevTools/HackStudio/main.cpp
@@ -78,7 +78,7 @@ int main(int argc, char** argv)
text_editor->set_cursor(line_number, 0);
}
}
- }));
+ }, text_editor));
window->show();
return app.exec();
|
4e50079f3654a95f7296f8f632aa6aa92784678f
|
2020-10-16 03:19:53
|
Andreas Kling
|
ak: Redesign HashTable to use closed hashing
| false
|
Redesign HashTable to use closed hashing
|
ak
|
diff --git a/AK/HashFunctions.h b/AK/HashFunctions.h
index 757c43653e62..8395f7a10970 100644
--- a/AK/HashFunctions.h
+++ b/AK/HashFunctions.h
@@ -39,6 +39,16 @@ inline unsigned int_hash(u32 key)
return key;
}
+inline unsigned double_hash(u32 key)
+{
+ key = ~key + (key >> 23);
+ key ^= (key << 12);
+ key ^= (key >> 7);
+ key ^= (key << 2);
+ key ^= (key >> 20);
+ return key;
+}
+
inline unsigned pair_int_hash(u32 key1, u32 key2)
{
return int_hash((int_hash(key1) * 209) ^ (int_hash(key2 * 413)));
diff --git a/AK/HashTable.h b/AK/HashTable.h
index f74dfa548772..8d3bf7cd2ab7 100644
--- a/AK/HashTable.h
+++ b/AK/HashTable.h
@@ -26,11 +26,11 @@
#pragma once
-#include <AK/Assertions.h>
-#include <AK/SinglyLinkedList.h>
+#include <AK/HashFunctions.h>
+#include <AK/LogStream.h>
#include <AK/StdLibExtras.h>
-#include <AK/TemporaryChange.h>
-#include <AK/Traits.h>
+#include <AK/Types.h>
+#include <AK/kmalloc.h>
namespace AK {
@@ -39,182 +39,197 @@ enum class HashSetResult {
ReplacedExistingEntry
};
-template<typename T, typename>
-class HashTable;
-
-template<typename HashTableType, typename ElementType, typename BucketIteratorType>
+template<typename HashTableType, typename T, typename BucketType>
class HashTableIterator {
+ friend HashTableType;
+
public:
- bool operator!=(const HashTableIterator& other) const
- {
- if (m_is_end && other.m_is_end)
- return false;
- return &m_table != &other.m_table
- || m_is_end != other.m_is_end
- || m_bucket_index != other.m_bucket_index
- || m_bucket_iterator != other.m_bucket_iterator;
- }
- bool operator==(const HashTableIterator& other) const { return !(*this != other); }
- ElementType& operator*() { return *m_bucket_iterator; }
- ElementType* operator->() { return m_bucket_iterator.operator->(); }
- HashTableIterator& operator++()
- {
- skip_to_next();
- return *this;
- }
+ bool operator==(const HashTableIterator& other) const { return m_bucket == other.m_bucket; }
+ bool operator!=(const HashTableIterator& other) const { return m_bucket != other.m_bucket; }
+ T& operator*() { return *m_bucket->slot(); }
+ T* operator->() { return m_bucket->slot(); }
+ void operator++() { skip_to_next(); }
+private:
void skip_to_next()
{
- while (!m_is_end) {
- if (m_bucket_iterator.is_end()) {
- ++m_bucket_index;
- if (m_bucket_index >= m_table.capacity()) {
- m_is_end = true;
- return;
- }
- m_bucket_iterator = m_table.bucket(m_bucket_index).begin();
- } else {
- ++m_bucket_iterator;
- }
- if (!m_bucket_iterator.is_end())
+ if (!m_bucket)
+ return;
+ do {
+ ++m_bucket;
+ if (m_bucket->used)
return;
- }
+ } while (!m_bucket->end);
+ if (m_bucket->end)
+ m_bucket = nullptr;
}
-private:
- friend HashTableType;
-
- explicit HashTableIterator(HashTableType& table, bool is_end, BucketIteratorType bucket_iterator = {}, size_t bucket_index = 0)
- : m_table(table)
- , m_bucket_index(bucket_index)
- , m_is_end(is_end)
- , m_bucket_iterator(bucket_iterator)
+ explicit HashTableIterator(BucketType* bucket)
+ : m_bucket(bucket)
{
- ASSERT(!table.m_clearing);
- ASSERT(!table.m_rehashing);
- if (!is_end && !m_table.is_empty() && m_bucket_iterator.is_end()) {
- m_bucket_iterator = m_table.bucket(0).begin();
- if (m_bucket_iterator.is_end())
- skip_to_next();
- }
}
- HashTableType& m_table;
- size_t m_bucket_index { 0 };
- bool m_is_end { false };
- BucketIteratorType m_bucket_iterator;
+ BucketType* m_bucket { nullptr };
};
template<typename T, typename TraitsForT>
class HashTable {
-private:
- using Bucket = SinglyLinkedList<T>;
+ struct Bucket {
+ bool used;
+ bool deleted;
+ bool end;
+ alignas(T) u8 storage[sizeof(T)];
+
+ T* slot() { return reinterpret_cast<T*>(storage); }
+ const T* slot() const { return reinterpret_cast<const T*>(storage); }
+ };
public:
HashTable() { }
- HashTable(size_t capacity)
- : m_buckets(new Bucket[capacity])
- , m_capacity(capacity)
- {
- }
+ HashTable(size_t capacity) { rehash(capacity); }
+ ~HashTable() { clear(); }
+
HashTable(const HashTable& other)
{
- ensure_capacity(other.size());
+ rehash(other.capacity());
for (auto& it : other)
set(it);
}
+
HashTable& operator=(const HashTable& other)
{
if (this != &other) {
clear();
- ensure_capacity(other.size());
+ rehash(other.capacity());
for (auto& it : other)
set(it);
}
return *this;
}
+
HashTable(HashTable&& other)
: m_buckets(other.m_buckets)
, m_size(other.m_size)
, m_capacity(other.m_capacity)
+ , m_deleted_count(other.m_deleted_count)
{
other.m_size = 0;
other.m_capacity = 0;
+ other.m_deleted_count = 0;
other.m_buckets = nullptr;
}
+
HashTable& operator=(HashTable&& other)
{
if (this != &other) {
clear();
- m_buckets = other.m_buckets;
- m_size = other.m_size;
- m_capacity = other.m_capacity;
- other.m_size = 0;
- other.m_capacity = 0;
- other.m_buckets = nullptr;
+ m_buckets = exchange(other.m_buckets, nullptr);
+ m_size = exchange(other.m_size, 0);
+ m_capacity = exchange(other.m_capacity, 0);
+ m_deleted_count = exchange(other.m_deleted_count, 0);
}
return *this;
}
- ~HashTable() { clear(); }
bool is_empty() const { return !m_size; }
size_t size() const { return m_size; }
size_t capacity() const { return m_capacity; }
+ template<typename U, size_t N>
+ void set_from(U (&from_array)[N])
+ {
+ for (size_t i = 0; i < N; ++i) {
+ set(from_array[i]);
+ }
+ }
+
void ensure_capacity(size_t capacity)
{
ASSERT(capacity >= size());
- rehash(capacity);
+ rehash(capacity * 2);
}
- HashSetResult set(const T&);
- HashSetResult set(T&&);
+ bool contains(const T& value) const
+ {
+ return find(value) != end();
+ }
- template<typename U, size_t N>
- void set_from(U (&from_array)[N])
+ using Iterator = HashTableIterator<HashTable, T, Bucket>;
+
+ Iterator begin()
{
- for (size_t i = 0; i < N; ++i) {
- set(from_array[i]);
+ for (size_t i = 0; i < m_capacity; ++i) {
+ if (m_buckets[i].used)
+ return Iterator(&m_buckets[i]);
}
+ return end();
}
- bool contains(const T&) const;
- void clear();
-
- using Iterator = HashTableIterator<HashTable, T, typename Bucket::Iterator>;
- friend Iterator;
- Iterator begin() { return Iterator(*this, is_empty()); }
- Iterator end() { return Iterator(*this, true); }
+ Iterator end()
+ {
+ return Iterator(nullptr);
+ }
- using ConstIterator = HashTableIterator<const HashTable, const T, typename Bucket::ConstIterator>;
- friend ConstIterator;
- ConstIterator begin() const { return ConstIterator(*this, is_empty()); }
- ConstIterator end() const { return ConstIterator(*this, true); }
+ using ConstIterator = HashTableIterator<const HashTable, const T, const Bucket>;
- template<typename Finder>
- Iterator find(unsigned hash, Finder finder)
+ ConstIterator begin() const
{
- if (is_empty())
- return end();
- size_t bucket_index;
- auto& bucket = lookup_with_hash(hash, &bucket_index);
- auto bucket_iterator = bucket.find(finder);
- if (bucket_iterator != bucket.end())
- return Iterator(*this, false, bucket_iterator, bucket_index);
+ for (size_t i = 0; i < m_capacity; ++i) {
+ if (m_buckets[i].used)
+ return ConstIterator(&m_buckets[i]);
+ }
return end();
}
+ ConstIterator end() const
+ {
+ return ConstIterator(nullptr);
+ }
+
+ void clear()
+ {
+ if (!m_buckets)
+ return;
+
+ for (size_t i = 0; i < m_capacity; ++i) {
+ if (m_buckets[i].used)
+ m_buckets[i].slot()->~T();
+ }
+
+ kfree(m_buckets);
+ m_buckets = nullptr;
+ m_capacity = 0;
+ m_size = 0;
+ m_deleted_count = 0;
+ }
+
+ HashSetResult set(T&& value)
+ {
+ auto& bucket = lookup_for_writing(value);
+ if (bucket.used) {
+ (*bucket.slot()) = move(value);
+ return HashSetResult::ReplacedExistingEntry;
+ }
+
+ new (bucket.slot()) T(move(value));
+ bucket.used = true;
+ if (bucket.deleted) {
+ bucket.deleted = false;
+ --m_deleted_count;
+ }
+ ++m_size;
+ return HashSetResult::InsertedNewEntry;
+ }
+
+ HashSetResult set(const T& value)
+ {
+ return set(T(value));
+ }
+
template<typename Finder>
- ConstIterator find(unsigned hash, Finder finder) const
+ Iterator find(unsigned hash, Finder finder)
{
- if (is_empty())
- return end();
- size_t bucket_index;
- auto& bucket = lookup_with_hash(hash, &bucket_index);
- auto bucket_iterator = bucket.find(finder);
- if (bucket_iterator != bucket.end())
- return ConstIterator(*this, false, bucket_iterator, bucket_index);
- return end();
+ return Iterator(lookup_with_hash(hash, move(finder)));
}
Iterator find(const T& value)
@@ -222,6 +237,12 @@ class HashTable {
return find(TraitsForT::hash(value), [&](auto& other) { return TraitsForT::equals(value, other); });
}
+ template<typename Finder>
+ ConstIterator find(unsigned hash, Finder finder) const
+ {
+ return ConstIterator(lookup_with_hash(hash, move(finder)));
+ }
+
ConstIterator find(const T& value) const
{
return find(TraitsForT::hash(value), [&](auto& other) { return TraitsForT::equals(value, other); });
@@ -237,169 +258,119 @@ class HashTable {
return false;
}
- void remove(Iterator);
+ void remove(Iterator iterator)
+ {
+ ASSERT(iterator.m_bucket);
+ auto& bucket = *iterator.m_bucket;
+ ASSERT(bucket.used);
+ ASSERT(!bucket.end);
+ ASSERT(!bucket.deleted);
+ bucket.slot()->~T();
+ bucket.used = false;
+ bucket.deleted = true;
+ --m_size;
+ ++m_deleted_count;
+ }
private:
- Bucket& lookup(const T&, size_t* bucket_index = nullptr);
- const Bucket& lookup(const T&, size_t* bucket_index = nullptr) const;
-
- Bucket& lookup_with_hash(unsigned hash, size_t* bucket_index)
+ void insert_during_rehash(T&& value)
{
- if (bucket_index)
- *bucket_index = hash % m_capacity;
- return m_buckets[hash % m_capacity];
+ auto& bucket = lookup_for_writing(value);
+ new (bucket.slot()) T(move(value));
+ bucket.used = true;
}
- const Bucket& lookup_with_hash(unsigned hash, size_t* bucket_index) const
+ void rehash(size_t new_capacity)
{
- if (bucket_index)
- *bucket_index = hash % m_capacity;
- return m_buckets[hash % m_capacity];
- }
+ new_capacity = max(new_capacity, static_cast<size_t>(4));
- void rehash(size_t capacity);
- void insert(const T&);
- void insert(T&&);
+ auto* old_buckets = m_buckets;
+ auto old_capacity = m_capacity;
- Bucket& bucket(size_t index) { return m_buckets[index]; }
- const Bucket& bucket(size_t index) const { return m_buckets[index]; }
+ m_buckets = (Bucket*)kmalloc(sizeof(Bucket) * (new_capacity + 1));
+ __builtin_memset(m_buckets, 0, sizeof(Bucket) * (new_capacity + 1));
+ m_capacity = new_capacity;
+ m_deleted_count = 0;
- Bucket* m_buckets { nullptr };
+ m_buckets[m_capacity].end = true;
- size_t m_size { 0 };
- size_t m_capacity { 0 };
- bool m_clearing { false };
- bool m_rehashing { false };
-};
+ if (!old_buckets)
+ return;
-template<typename T, typename TraitsForT>
-HashSetResult HashTable<T, TraitsForT>::set(T&& value)
-{
- if (!m_capacity)
- rehash(1);
- auto& bucket = lookup(value);
- for (auto& e : bucket) {
- if (TraitsForT::equals(e, value)) {
- e = move(value);
- return HashSetResult::ReplacedExistingEntry;
+ for (size_t i = 0; i < old_capacity; ++i) {
+ auto& old_bucket = old_buckets[i];
+ if (old_bucket.used) {
+ insert_during_rehash(move(*old_bucket.slot()));
+ old_bucket.slot()->~T();
+ }
}
- }
- if (size() >= capacity()) {
- rehash(size() + 1);
- insert(move(value));
- } else {
- bucket.append(move(value));
- }
- m_size++;
- return HashSetResult::InsertedNewEntry;
-}
-template<typename T, typename TraitsForT>
-HashSetResult HashTable<T, TraitsForT>::set(const T& value)
-{
- if (!m_capacity)
- rehash(1);
- auto& bucket = lookup(value);
- for (auto& e : bucket) {
- if (TraitsForT::equals(e, value)) {
- e = value;
- return HashSetResult::ReplacedExistingEntry;
- }
- }
- if (size() >= capacity()) {
- rehash(size() + 1);
- insert(value);
- } else {
- bucket.append(value);
+ kfree(old_buckets);
}
- m_size++;
- return HashSetResult::InsertedNewEntry;
-}
-template<typename T, typename TraitsForT>
-void HashTable<T, TraitsForT>::rehash(size_t new_capacity)
-{
- TemporaryChange<bool> change(m_rehashing, true);
- new_capacity *= 2;
- auto* new_buckets = new Bucket[new_capacity];
- auto* old_buckets = m_buckets;
- size_t old_capacity = m_capacity;
- m_buckets = new_buckets;
- m_capacity = new_capacity;
-
- for (size_t i = 0; i < old_capacity; ++i) {
- for (auto& value : old_buckets[i]) {
- insert(move(value));
+ template<typename Finder>
+ Bucket* lookup_with_hash(unsigned hash, Finder finder, Bucket** usable_bucket_for_writing = nullptr) const
+ {
+ if (is_empty())
+ return nullptr;
+ size_t bucket_index = hash % m_capacity;
+ for (;;) {
+ auto& bucket = m_buckets[bucket_index];
+
+ if (usable_bucket_for_writing && !*usable_bucket_for_writing && !bucket.used) {
+ *usable_bucket_for_writing = &bucket;
+ }
+
+ if (bucket.used && finder(*bucket.slot()))
+ return &bucket;
+
+ if (!bucket.used && !bucket.deleted)
+ return nullptr;
+
+ hash = double_hash(hash);
+ bucket_index = hash % m_capacity;
}
}
- delete[] old_buckets;
-}
-
-template<typename T, typename TraitsForT>
-void HashTable<T, TraitsForT>::clear()
-{
- TemporaryChange<bool> change(m_clearing, true);
- if (m_buckets) {
- delete[] m_buckets;
- m_buckets = nullptr;
+ const Bucket* lookup_for_reading(const T& value) const
+ {
+ return lookup_with_hash(TraitsForT::hash(value), [&value](auto& entry) { return TraitsForT::equals(entry, value); });
}
- m_capacity = 0;
- m_size = 0;
-}
-template<typename T, typename TraitsForT>
-void HashTable<T, TraitsForT>::insert(T&& value)
-{
- auto& bucket = lookup(value);
- bucket.append(move(value));
-}
+ Bucket& lookup_for_writing(const T& value)
+ {
+ auto hash = TraitsForT::hash(value);
+ Bucket* usable_bucket_for_writing = nullptr;
+ if (auto* bucket_for_reading = lookup_with_hash(
+ hash,
+ [&value](auto& entry) { return TraitsForT::equals(entry, value); },
+ &usable_bucket_for_writing)) {
+ return *const_cast<Bucket*>(bucket_for_reading);
+ }
-template<typename T, typename TraitsForT>
-void HashTable<T, TraitsForT>::insert(const T& value)
-{
- auto& bucket = lookup(value);
- bucket.append(value);
-}
+ if ((used_bucket_count() + 1) >= m_capacity)
+ rehash((size() + 1) * 2);
+ else if (usable_bucket_for_writing)
+ return *usable_bucket_for_writing;
-template<typename T, typename TraitsForT>
-bool HashTable<T, TraitsForT>::contains(const T& value) const
-{
- if (is_empty())
- return false;
- auto& bucket = lookup(value);
- for (auto& e : bucket) {
- if (TraitsForT::equals(e, value))
- return true;
- }
- return false;
-}
+ size_t bucket_index = hash % m_capacity;
-template<typename T, typename TraitsForT>
-void HashTable<T, TraitsForT>::remove(Iterator it)
-{
- ASSERT(!is_empty());
- m_buckets[it.m_bucket_index].remove(it.m_bucket_iterator);
- --m_size;
-}
+ for (;;) {
+ auto& bucket = m_buckets[bucket_index];
+ if (!bucket.used)
+ return bucket;
+ hash = double_hash(hash);
+ bucket_index = hash % m_capacity;
+ }
+ }
-template<typename T, typename TraitsForT>
-auto HashTable<T, TraitsForT>::lookup(const T& value, size_t* bucket_index) -> Bucket&
-{
- unsigned hash = TraitsForT::hash(value);
- if (bucket_index)
- *bucket_index = hash % m_capacity;
- return m_buckets[hash % m_capacity];
-}
+ size_t used_bucket_count() const { return m_size + m_deleted_count; }
-template<typename T, typename TraitsForT>
-auto HashTable<T, TraitsForT>::lookup(const T& value, size_t* bucket_index) const -> const Bucket&
-{
- unsigned hash = TraitsForT::hash(value);
- if (bucket_index)
- *bucket_index = hash % m_capacity;
- return m_buckets[hash % m_capacity];
-}
+ Bucket* m_buckets { nullptr };
+ size_t m_size { 0 };
+ size_t m_capacity { 0 };
+ size_t m_deleted_count { 0 };
+};
}
|
84ec690d90988645f628943b5b15a4ce52f20632
|
2024-09-10 14:33:46
|
Andreas Kling
|
libgfx: Cache code point -> glyph ID lookups in TypefaceSkia
| false
|
Cache code point -> glyph ID lookups in TypefaceSkia
|
libgfx
|
diff --git a/Userland/Libraries/LibGfx/Font/TypefaceSkia.cpp b/Userland/Libraries/LibGfx/Font/TypefaceSkia.cpp
index 59f6f42c9399..b568194820e4 100644
--- a/Userland/Libraries/LibGfx/Font/TypefaceSkia.cpp
+++ b/Userland/Libraries/LibGfx/Font/TypefaceSkia.cpp
@@ -82,7 +82,36 @@ u16 TypefaceSkia::units_per_em() const
u32 TypefaceSkia::glyph_id_for_code_point(u32 code_point) const
{
- return impl().skia_typeface->unicharToGlyph(code_point);
+ return glyph_page(code_point / GlyphPage::glyphs_per_page).glyph_ids[code_point % GlyphPage::glyphs_per_page];
+}
+
+TypefaceSkia::GlyphPage const& TypefaceSkia::glyph_page(size_t page_index) const
+{
+ if (page_index == 0) {
+ if (!m_glyph_page_zero) {
+ m_glyph_page_zero = make<GlyphPage>();
+ populate_glyph_page(*m_glyph_page_zero, 0);
+ }
+ return *m_glyph_page_zero;
+ }
+ if (auto it = m_glyph_pages.find(page_index); it != m_glyph_pages.end()) {
+ return *it->value;
+ }
+
+ auto glyph_page = make<GlyphPage>();
+ populate_glyph_page(*glyph_page, page_index);
+ auto const* glyph_page_ptr = glyph_page.ptr();
+ m_glyph_pages.set(page_index, move(glyph_page));
+ return *glyph_page_ptr;
+}
+
+void TypefaceSkia::populate_glyph_page(GlyphPage& glyph_page, size_t page_index) const
+{
+ u32 first_code_point = page_index * GlyphPage::glyphs_per_page;
+ for (size_t i = 0; i < GlyphPage::glyphs_per_page; ++i) {
+ u32 code_point = first_code_point + i;
+ glyph_page.glyph_ids[i] = impl().skia_typeface->unicharToGlyph(code_point);
+ }
}
String TypefaceSkia::family() const
diff --git a/Userland/Libraries/LibGfx/Font/TypefaceSkia.h b/Userland/Libraries/LibGfx/Font/TypefaceSkia.h
index 4c24fa60fc16..e4b7312db4f4 100644
--- a/Userland/Libraries/LibGfx/Font/TypefaceSkia.h
+++ b/Userland/Libraries/LibGfx/Font/TypefaceSkia.h
@@ -38,6 +38,21 @@ class TypefaceSkia : public Gfx::Typeface {
ReadonlyBytes m_buffer;
unsigned m_ttc_index { 0 };
+
+ // This cache stores information per code point.
+ // It's segmented into pages with data about 256 code points each.
+ struct GlyphPage {
+ static constexpr size_t glyphs_per_page = 256;
+ u16 glyph_ids[glyphs_per_page];
+ };
+
+ // Fast cache for GlyphPage #0 (code points 0-255) to avoid hash lookups for all of ASCII and Latin-1.
+ OwnPtr<GlyphPage> mutable m_glyph_page_zero;
+
+ HashMap<size_t, NonnullOwnPtr<GlyphPage>> mutable m_glyph_pages;
+
+ [[nodiscard]] GlyphPage const& glyph_page(size_t page_index) const;
+ void populate_glyph_page(GlyphPage&, size_t page_index) const;
};
}
|
f923016e0b44ff482c402a40fe4adb21a4fd3107
|
2024-05-08 04:24:27
|
implicitfield
|
ak: Add `reinterpret_as_octal()`
| false
|
Add `reinterpret_as_octal()`
|
ak
|
diff --git a/AK/IntegralMath.h b/AK/IntegralMath.h
index e7ea6f6f7669..c1051fed8435 100644
--- a/AK/IntegralMath.h
+++ b/AK/IntegralMath.h
@@ -75,4 +75,16 @@ constexpr bool is_power_of(U x)
return true;
}
+template<Unsigned T>
+constexpr T reinterpret_as_octal(T decimal)
+{
+ T result = 0;
+ T n = 0;
+ while (decimal > 0) {
+ result += pow<T>(8, n++) * (decimal % 10);
+ decimal /= 10;
+ }
+ return result;
+}
+
}
|
4454735bf8ebddfad7fc6bc0c65b7ad52aa8fd92
|
2021-04-17 04:37:36
|
Nicholas-Baron
|
kernel: Add `-Wnull-dereference` flag
| false
|
Add `-Wnull-dereference` flag
|
kernel
|
diff --git a/Kernel/CMakeLists.txt b/Kernel/CMakeLists.txt
index c97fb0cf3e65..4349b51bcd85 100644
--- a/Kernel/CMakeLists.txt
+++ b/Kernel/CMakeLists.txt
@@ -298,7 +298,7 @@ set(SOURCES
${C_SOURCES}
)
-set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wno-unknown-warning-option -Wvla")
+set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wno-unknown-warning-option -Wvla -Wnull-dereference")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -pie -fPIE -fno-rtti -ffreestanding -fbuiltin")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -mno-80387 -mno-mmx -mno-sse -mno-sse2")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fno-asynchronous-unwind-tables")
|
e1c1aaa9567aa79b6f8e60716c9025cbfca76c5c
|
2023-05-03 13:09:49
|
Aliaksandr Kalenik
|
libweb: Implement "create navigation params from a srcdoc resource"
| false
|
Implement "create navigation params from a srcdoc resource"
|
libweb
|
diff --git a/Userland/Libraries/LibWeb/HTML/Navigable.cpp b/Userland/Libraries/LibWeb/HTML/Navigable.cpp
index f7763f151efe..fdb2161417c7 100644
--- a/Userland/Libraries/LibWeb/HTML/Navigable.cpp
+++ b/Userland/Libraries/LibWeb/HTML/Navigable.cpp
@@ -224,6 +224,74 @@ Vector<JS::NonnullGCPtr<SessionHistoryEntry>>& Navigable::get_session_history_en
VERIFY_NOT_REACHED();
}
+// https://html.spec.whatwg.org/multipage/browsing-the-web.html#create-navigation-params-from-a-srcdoc-resource
+static WebIDL::ExceptionOr<NavigationParams> create_navigation_params_from_a_srcdoc_resource(JS::GCPtr<SessionHistoryEntry> entry, JS::GCPtr<Navigable> navigable, SourceSnapshotParams const&, Optional<String> navigation_id)
+{
+ auto& vm = navigable->vm();
+ auto& realm = navigable->active_window()->realm();
+
+ // 1. Let documentResource be entry's document state's resource.
+ auto document_resource = entry->document_state->resource();
+ VERIFY(document_resource.has<String>());
+
+ // 2. Let response be a new response with
+ // URL: about:srcdoc
+ // header list: (`Content-Type`, `text/html`)
+ // body: the UTF-8 encoding of documentResource, as a body
+ auto response = Fetch::Infrastructure::Response::create(vm);
+ response->url_list().append(AK::URL("about:srcdoc"));
+ auto header = TRY_OR_THROW_OOM(vm, Fetch::Infrastructure::Header::from_string_pair("Content-Type"sv, "text/html"sv));
+ TRY_OR_THROW_OOM(vm, response->header_list()->append(move(header)));
+ response->set_body(TRY(Fetch::Infrastructure::byte_sequence_as_body(realm, document_resource.get<String>().bytes())));
+
+ // FIXME: 3. Let responseOrigin be the result of determining the origin given response's URL, targetSnapshotParams's sandboxing flags, null, and entry's document state's origin.
+
+ // 4. Let coop be a new cross-origin opener policy.
+ CrossOriginOpenerPolicy coop;
+
+ // 5. Let coopEnforcementResult be a new cross-origin opener policy enforcement result with
+ // url: response's URL
+ // FIXME: origin: responseOrigin
+ // cross-origin opener policy: coop
+ CrossOriginOpenerPolicyEnforcementResult coop_enforcement_result {
+ .url = *response->url(),
+ .origin = Origin {},
+ .cross_origin_opener_policy = coop
+ };
+
+ // FIXME: 6. Let policyContainer be the result of determining navigation params policy container given response's URL, entry's document state's history policy container, null, navigable's container document's policy container, and null.
+
+ // 7. Return a new navigation params, with
+ // id: navigationId
+ // request: null
+ // response: response
+ // FIXME: origin: responseOrigin
+ // FIXME: policy container: policyContainer
+ // FIXME: final sandboxing flag set: targetSnapshotParams's sandboxing flags
+ // cross-origin opener policy: coop
+ // COOP enforcement result: coopEnforcementResult
+ // reserved environment: null
+ // navigable: navigable
+ // FIXME: navigation timing type: navTimingType
+ // fetch controller: null
+ // commit early hints: null
+ HTML::NavigationParams navigation_params {
+ .id = navigation_id,
+ .request = {},
+ .response = *response,
+ .origin = Origin {},
+ .policy_container = PolicyContainer {},
+ .final_sandboxing_flag_set = SandboxingFlagSet {},
+ .cross_origin_opener_policy = move(coop),
+ .coop_enforcement_result = move(coop_enforcement_result),
+ .reserved_environment = {},
+ .browsing_context = navigable->active_browsing_context(),
+ .navigable = navigable,
+ };
+
+ return { navigation_params };
+}
+
// https://html.spec.whatwg.org/multipage/browsing-the-web.html#create-navigation-params-by-fetching
static WebIDL::ExceptionOr<Optional<NavigationParams>> create_navigation_params_by_fetching(JS::GCPtr<SessionHistoryEntry> entry, JS::GCPtr<Navigable> navigable, SourceSnapshotParams const& source_snapshot_params, Optional<String> navigation_id)
{
@@ -506,7 +574,7 @@ WebIDL::ExceptionOr<void> Navigable::populate_session_history_entry_document(JS:
// of creating navigation params from a srcdoc resource given entry, navigable,
// targetSnapshotParams, navigationId, and navTimingType.
if (document_resource.has<String>()) {
- TODO();
+ navigation_params = create_navigation_params_from_a_srcdoc_resource(entry, this, source_snapshot_params, navigation_id).release_value_but_fixme_should_propagate_errors();
}
// 2. Otherwise, if both of the following are true:
// - entry's URL's scheme is a fetch scheme; and
|
d82bd885cec366043605d7dc49ca42215618ef86
|
2022-03-07 15:23:57
|
Matthew Olsson
|
libpdf: Propagate ColorSpace errors
| false
|
Propagate ColorSpace errors
|
libpdf
|
diff --git a/Userland/Libraries/LibPDF/ColorSpace.cpp b/Userland/Libraries/LibPDF/ColorSpace.cpp
index 238f0d2544e6..d9f7179f3a42 100644
--- a/Userland/Libraries/LibPDF/ColorSpace.cpp
+++ b/Userland/Libraries/LibPDF/ColorSpace.cpp
@@ -10,7 +10,7 @@
namespace PDF {
-RefPtr<DeviceGrayColorSpace> DeviceGrayColorSpace::the()
+NonnullRefPtr<DeviceGrayColorSpace> DeviceGrayColorSpace::the()
{
static auto instance = adopt_ref(*new DeviceGrayColorSpace());
return instance;
@@ -23,7 +23,7 @@ Color DeviceGrayColorSpace::color(Vector<Value> const& arguments) const
return Color(gray, gray, gray);
}
-RefPtr<DeviceRGBColorSpace> DeviceRGBColorSpace::the()
+NonnullRefPtr<DeviceRGBColorSpace> DeviceRGBColorSpace::the()
{
static auto instance = adopt_ref(*new DeviceRGBColorSpace());
return instance;
@@ -38,7 +38,7 @@ Color DeviceRGBColorSpace::color(Vector<Value> const& arguments) const
return Color(r, g, b);
}
-RefPtr<DeviceCMYKColorSpace> DeviceCMYKColorSpace::the()
+NonnullRefPtr<DeviceCMYKColorSpace> DeviceCMYKColorSpace::the()
{
static auto instance = adopt_ref(*new DeviceCMYKColorSpace());
return instance;
@@ -54,23 +54,22 @@ Color DeviceCMYKColorSpace::color(Vector<Value> const& arguments) const
return Color::from_cmyk(c, m, y, k);
}
-RefPtr<CalRGBColorSpace> CalRGBColorSpace::create(RefPtr<Document> document, Vector<Value>&& parameters)
+PDFErrorOr<NonnullRefPtr<CalRGBColorSpace>> CalRGBColorSpace::create(RefPtr<Document> document, Vector<Value>&& parameters)
{
if (parameters.size() != 1)
- return {};
+ return Error { Error::Type::MalformedPDF, "RGB color space expects one parameter" };
auto param = parameters[0];
if (!param.has<NonnullRefPtr<Object>>() || !param.get<NonnullRefPtr<Object>>()->is<DictObject>())
- return {};
+ return Error { Error::Type::MalformedPDF, "RGB color space expects a dict parameter" };
auto dict = param.get<NonnullRefPtr<Object>>()->cast<DictObject>();
if (!dict->contains(CommonNames::WhitePoint))
- return {};
+ return Error { Error::Type::MalformedPDF, "RGB color space expects a Whitepoint key" };
- // FIXME: Propagate errors
- auto white_point_array = MUST(dict->get_array(document, CommonNames::WhitePoint));
+ auto white_point_array = TRY(dict->get_array(document, CommonNames::WhitePoint));
if (white_point_array->size() != 3)
- return {};
+ return Error { Error::Type::MalformedPDF, "RGB color space expects 3 Whitepoint parameters" };
auto color_space = adopt_ref(*new CalRGBColorSpace());
@@ -79,10 +78,10 @@ RefPtr<CalRGBColorSpace> CalRGBColorSpace::create(RefPtr<Document> document, Vec
color_space->m_whitepoint[2] = white_point_array->at(2).to_float();
if (color_space->m_whitepoint[1] != 1.0f)
- return {};
+ return Error { Error::Type::MalformedPDF, "RGB color space expects 2nd Whitepoint to be 1.0" };
if (dict->contains(CommonNames::BlackPoint)) {
- auto black_point_array = MUST(dict->get_array(document, CommonNames::BlackPoint));
+ auto black_point_array = TRY(dict->get_array(document, CommonNames::BlackPoint));
if (black_point_array->size() == 3) {
color_space->m_blackpoint[0] = black_point_array->at(0).to_float();
color_space->m_blackpoint[1] = black_point_array->at(1).to_float();
@@ -91,7 +90,7 @@ RefPtr<CalRGBColorSpace> CalRGBColorSpace::create(RefPtr<Document> document, Vec
}
if (dict->contains(CommonNames::Gamma)) {
- auto gamma_array = MUST(dict->get_array(document, CommonNames::Gamma));
+ auto gamma_array = TRY(dict->get_array(document, CommonNames::Gamma));
if (gamma_array->size() == 3) {
color_space->m_gamma[0] = gamma_array->at(0).to_float();
color_space->m_gamma[1] = gamma_array->at(1).to_float();
@@ -100,7 +99,7 @@ RefPtr<CalRGBColorSpace> CalRGBColorSpace::create(RefPtr<Document> document, Vec
}
if (dict->contains(CommonNames::Matrix)) {
- auto matrix_array = MUST(dict->get_array(document, CommonNames::Matrix));
+ auto matrix_array = TRY(dict->get_array(document, CommonNames::Matrix));
if (matrix_array->size() == 3) {
color_space->m_matrix[0] = matrix_array->at(0).to_float();
color_space->m_matrix[1] = matrix_array->at(1).to_float();
diff --git a/Userland/Libraries/LibPDF/ColorSpace.h b/Userland/Libraries/LibPDF/ColorSpace.h
index c22ee7d36ee5..87f1fe90f8d6 100644
--- a/Userland/Libraries/LibPDF/ColorSpace.h
+++ b/Userland/Libraries/LibPDF/ColorSpace.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2021, Matthew Olsson <[email protected]>
+ * Copyright (c) 2021-2022, Matthew Olsson <[email protected]>
*
* SPDX-License-Identifier: BSD-2-Clause
*/
@@ -34,7 +34,7 @@ class ColorSpace : public RefCounted<ColorSpace> {
class DeviceGrayColorSpace final : public ColorSpace {
public:
- static RefPtr<DeviceGrayColorSpace> the();
+ static NonnullRefPtr<DeviceGrayColorSpace> the();
virtual ~DeviceGrayColorSpace() override = default;
@@ -46,7 +46,7 @@ class DeviceGrayColorSpace final : public ColorSpace {
class DeviceRGBColorSpace final : public ColorSpace {
public:
- static RefPtr<DeviceRGBColorSpace> the();
+ static NonnullRefPtr<DeviceRGBColorSpace> the();
virtual ~DeviceRGBColorSpace() override = default;
@@ -58,7 +58,7 @@ class DeviceRGBColorSpace final : public ColorSpace {
class DeviceCMYKColorSpace final : public ColorSpace {
public:
- static RefPtr<DeviceCMYKColorSpace> the();
+ static NonnullRefPtr<DeviceCMYKColorSpace> the();
virtual ~DeviceCMYKColorSpace() override = default;
@@ -70,7 +70,7 @@ class DeviceCMYKColorSpace final : public ColorSpace {
class CalRGBColorSpace final : public ColorSpace {
public:
- static RefPtr<CalRGBColorSpace> create(RefPtr<Document>, Vector<Value>&& parameters);
+ static PDFErrorOr<NonnullRefPtr<CalRGBColorSpace>> create(RefPtr<Document>, Vector<Value>&& parameters);
virtual ~CalRGBColorSpace() override = default;
virtual Color color(Vector<Value> const& arguments) const override;
diff --git a/Userland/Libraries/LibPDF/Renderer.cpp b/Userland/Libraries/LibPDF/Renderer.cpp
index 78a9c88ee32d..87f00ea7dcb5 100644
--- a/Userland/Libraries/LibPDF/Renderer.cpp
+++ b/Userland/Libraries/LibPDF/Renderer.cpp
@@ -413,13 +413,13 @@ RENDERER_TODO(type3_font_set_glyph_width_and_bbox);
RENDERER_HANDLER(set_stroking_space)
{
- state().stroke_color_space = get_color_space(args[0]);
+ state().stroke_color_space = MUST(get_color_space(args[0]));
VERIFY(state().stroke_color_space);
}
RENDERER_HANDLER(set_painting_space)
{
- state().paint_color_space = get_color_space(args[0]);
+ state().paint_color_space = MUST(get_color_space(args[0]));
VERIFY(state().paint_color_space);
}
@@ -564,7 +564,7 @@ void Renderer::show_text(String const& string, float shift)
m_text_matrix = Gfx::AffineTransform(1, 0, 0, 1, delta_x, 0).multiply(m_text_matrix);
}
-RefPtr<ColorSpace> Renderer::get_color_space(Value const& value)
+PDFErrorOr<NonnullRefPtr<ColorSpace>> Renderer::get_color_space(Value const& value)
{
auto name = value.get<NonnullRefPtr<Object>>()->cast<NameObject>()->name();
@@ -580,12 +580,12 @@ RefPtr<ColorSpace> Renderer::get_color_space(Value const& value)
// The color space is a complex color space with parameters that resides in
// the resource dictionary
- auto color_space_resource_dict = MUST(m_page.resources->get_dict(m_document, CommonNames::ColorSpace));
+ auto color_space_resource_dict = TRY(m_page.resources->get_dict(m_document, CommonNames::ColorSpace));
if (!color_space_resource_dict->contains(name))
TODO();
- auto color_space_array = MUST(color_space_resource_dict->get_array(m_document, name));
- name = MUST(color_space_array->get_name_at(m_document, 0))->name();
+ auto color_space_array = TRY(color_space_resource_dict->get_array(m_document, name));
+ name = TRY(color_space_array->get_name_at(m_document, 0))->name();
Vector<Value> parameters;
parameters.ensure_capacity(color_space_array->size() - 1);
@@ -593,7 +593,7 @@ RefPtr<ColorSpace> Renderer::get_color_space(Value const& value)
parameters.unchecked_append(color_space_array->at(i));
if (name == CommonNames::CalRGB)
- return CalRGBColorSpace::create(m_document, move(parameters));
+ return TRY(CalRGBColorSpace::create(m_document, move(parameters)));
TODO();
}
diff --git a/Userland/Libraries/LibPDF/Renderer.h b/Userland/Libraries/LibPDF/Renderer.h
index cf10174df982..d35c5a57a754 100644
--- a/Userland/Libraries/LibPDF/Renderer.h
+++ b/Userland/Libraries/LibPDF/Renderer.h
@@ -97,7 +97,7 @@ class Renderer {
void set_graphics_state_from_dict(NonnullRefPtr<DictObject>);
// shift is the manual advance given in the TJ command array
void show_text(String const&, float shift = 0.0f);
- RefPtr<ColorSpace> get_color_space(Value const&);
+ PDFErrorOr<NonnullRefPtr<ColorSpace>> get_color_space(Value const&);
ALWAYS_INLINE GraphicsState const& state() const { return m_graphics_state_stack.last(); }
ALWAYS_INLINE GraphicsState& state() { return m_graphics_state_stack.last(); }
|
3425730294e9913627e36b2ddc559f337e0f186b
|
2021-11-10 19:17:49
|
Jan de Visser
|
libsql: Implement table joins
| false
|
Implement table joins
|
libsql
|
diff --git a/Tests/LibSQL/TestSqlStatementExecution.cpp b/Tests/LibSQL/TestSqlStatementExecution.cpp
index a7f0c0fbe406..e46056e42792 100644
--- a/Tests/LibSQL/TestSqlStatementExecution.cpp
+++ b/Tests/LibSQL/TestSqlStatementExecution.cpp
@@ -46,6 +46,17 @@ void create_table(NonnullRefPtr<SQL::Database> database)
EXPECT(result->inserted() == 1);
}
+void create_two_tables(NonnullRefPtr<SQL::Database> database)
+{
+ create_schema(database);
+ auto result = execute(database, "CREATE TABLE TestSchema.TestTable1 ( TextColumn1 text, IntColumn integer );");
+ EXPECT(result->error().code == SQL::SQLErrorCode::NoError);
+ EXPECT(result->inserted() == 1);
+ result = execute(database, "CREATE TABLE TestSchema.TestTable2 ( TextColumn2 text, IntColumn integer );");
+ EXPECT(result->error().code == SQL::SQLErrorCode::NoError);
+ EXPECT(result->inserted() == 1);
+}
+
TEST_CASE(create_schema)
{
ScopeGuard guard([]() { unlink(db_name); });
@@ -132,15 +143,15 @@ TEST_CASE(select_from_table)
ScopeGuard guard([]() { unlink(db_name); });
auto database = SQL::Database::construct(db_name);
create_table(database);
- auto result = execute(database, "INSERT INTO TestSchema.TestTable ( TextColumn, IntColumn ) VALUES ( 'Test_1', 42 ), ( 'Test_2', 43 );");
- EXPECT(result->error().code == SQL::SQLErrorCode::NoError);
- EXPECT(result->inserted() == 2);
- result = execute(database, "INSERT INTO TestSchema.TestTable ( TextColumn, IntColumn ) VALUES ( 'Test_3', 44 ), ( 'Test_4', 45 );");
- EXPECT(result->error().code == SQL::SQLErrorCode::NoError);
- EXPECT(result->inserted() == 2);
- result = execute(database, "INSERT INTO TestSchema.TestTable ( TextColumn, IntColumn ) VALUES ( 'Test_5', 46 );");
+ auto result = execute(database,
+ "INSERT INTO TestSchema.TestTable ( TextColumn, IntColumn ) VALUES "
+ "( 'Test_1', 42 ), "
+ "( 'Test_2', 43 ), "
+ "( 'Test_3', 44 ), "
+ "( 'Test_4', 45 ), "
+ "( 'Test_5', 46 );");
EXPECT(result->error().code == SQL::SQLErrorCode::NoError);
- EXPECT(result->inserted() == 1);
+ EXPECT(result->inserted() == 5);
result = execute(database, "SELECT * FROM TestSchema.TestTable;");
EXPECT(result->error().code == SQL::SQLErrorCode::NoError);
EXPECT(result->has_results());
@@ -152,15 +163,15 @@ TEST_CASE(select_with_column_names)
ScopeGuard guard([]() { unlink(db_name); });
auto database = SQL::Database::construct(db_name);
create_table(database);
- auto result = execute(database, "INSERT INTO TestSchema.TestTable ( TextColumn, IntColumn ) VALUES ( 'Test_1', 42 ), ( 'Test_2', 43 );");
- EXPECT(result->error().code == SQL::SQLErrorCode::NoError);
- EXPECT(result->inserted() == 2);
- result = execute(database, "INSERT INTO TestSchema.TestTable ( TextColumn, IntColumn ) VALUES ( 'Test_3', 44 ), ( 'Test_4', 45 );");
- EXPECT(result->error().code == SQL::SQLErrorCode::NoError);
- EXPECT(result->inserted() == 2);
- result = execute(database, "INSERT INTO TestSchema.TestTable ( TextColumn, IntColumn ) VALUES ( 'Test_5', 46 );");
+ auto result = execute(database,
+ "INSERT INTO TestSchema.TestTable ( TextColumn, IntColumn ) VALUES "
+ "( 'Test_1', 42 ), "
+ "( 'Test_2', 43 ), "
+ "( 'Test_3', 44 ), "
+ "( 'Test_4', 45 ), "
+ "( 'Test_5', 46 );");
EXPECT(result->error().code == SQL::SQLErrorCode::NoError);
- EXPECT(result->inserted() == 1);
+ EXPECT(result->inserted() == 5);
result = execute(database, "SELECT TextColumn FROM TestSchema.TestTable;");
EXPECT(result->error().code == SQL::SQLErrorCode::NoError);
EXPECT(result->has_results());
@@ -209,4 +220,77 @@ TEST_CASE(select_with_where)
}
}
+TEST_CASE(select_cross_join)
+{
+ ScopeGuard guard([]() { unlink(db_name); });
+ auto database = SQL::Database::construct(db_name);
+ create_two_tables(database);
+ auto result = execute(database,
+ "INSERT INTO TestSchema.TestTable1 ( TextColumn1, IntColumn ) VALUES "
+ "( 'Test_1', 42 ), "
+ "( 'Test_2', 43 ), "
+ "( 'Test_3', 44 ), "
+ "( 'Test_4', 45 ), "
+ "( 'Test_5', 46 );");
+ EXPECT(result->error().code == SQL::SQLErrorCode::NoError);
+ EXPECT(result->inserted() == 5);
+ result = execute(database,
+ "INSERT INTO TestSchema.TestTable2 ( TextColumn2, IntColumn ) VALUES "
+ "( 'Test_10', 40 ), "
+ "( 'Test_11', 41 ), "
+ "( 'Test_12', 42 ), "
+ "( 'Test_13', 47 ), "
+ "( 'Test_14', 48 );");
+ EXPECT(result->error().code == SQL::SQLErrorCode::NoError);
+ EXPECT(result->inserted() == 5);
+ result = execute(database, "SELECT * FROM TestSchema.TestTable1, TestSchema.TestTable2;");
+ EXPECT(result->error().code == SQL::SQLErrorCode::NoError);
+ EXPECT(result->has_results());
+ EXPECT_EQ(result->results().size(), 25u);
+ for (auto& row : result->results()) {
+ EXPECT(row.size() == 4);
+ EXPECT(row[1].to_int().value() >= 42);
+ EXPECT(row[1].to_int().value() <= 46);
+ EXPECT(row[3].to_int().value() >= 40);
+ EXPECT(row[3].to_int().value() <= 48);
+ }
+}
+
+TEST_CASE(select_inner_join)
+{
+ ScopeGuard guard([]() { unlink(db_name); });
+ auto database = SQL::Database::construct(db_name);
+ create_two_tables(database);
+ auto result = execute(database,
+ "INSERT INTO TestSchema.TestTable1 ( TextColumn1, IntColumn ) VALUES "
+ "( 'Test_1', 42 ), "
+ "( 'Test_2', 43 ), "
+ "( 'Test_3', 44 ), "
+ "( 'Test_4', 45 ), "
+ "( 'Test_5', 46 );");
+ EXPECT(result->error().code == SQL::SQLErrorCode::NoError);
+ EXPECT(result->inserted() == 5);
+ result = execute(database,
+ "INSERT INTO TestSchema.TestTable2 ( TextColumn2, IntColumn ) VALUES "
+ "( 'Test_10', 40 ), "
+ "( 'Test_11', 41 ), "
+ "( 'Test_12', 42 ), "
+ "( 'Test_13', 47 ), "
+ "( 'Test_14', 48 );");
+ EXPECT(result->error().code == SQL::SQLErrorCode::NoError);
+ EXPECT(result->inserted() == 5);
+ result = execute(database,
+ "SELECT TestTable1.IntColumn, TextColumn1, TextColumn2 "
+ "FROM TestSchema.TestTable1, TestSchema.TestTable2 "
+ "WHERE TestTable1.IntColumn = TestTable2.IntColumn;");
+ EXPECT(result->error().code == SQL::SQLErrorCode::NoError);
+ EXPECT(result->has_results());
+ EXPECT_EQ(result->results().size(), 1u);
+ auto& row = result->results()[0];
+ EXPECT_EQ(row.size(), 3u);
+ EXPECT_EQ(row[0].to_int().value(), 42);
+ EXPECT_EQ(row[1].to_string(), "Test_1");
+ EXPECT_EQ(row[2].to_string(), "Test_12");
+}
+
}
diff --git a/Userland/Libraries/LibSQL/AST/Expression.cpp b/Userland/Libraries/LibSQL/AST/Expression.cpp
index d3e1337be2cb..a7b793e602a6 100644
--- a/Userland/Libraries/LibSQL/AST/Expression.cpp
+++ b/Userland/Libraries/LibSQL/AST/Expression.cpp
@@ -170,11 +170,21 @@ Value ColumnNameExpression::evaluate(ExecutionContext& context) const
{
auto& descriptor = *context.current_row->descriptor();
VERIFY(context.current_row->size() == descriptor.size());
+ Optional<size_t> index_in_row;
for (auto ix = 0u; ix < context.current_row->size(); ix++) {
auto& column_descriptor = descriptor[ix];
- if (column_descriptor.name == column_name())
- return { (*context.current_row)[ix] };
+ if (!table_name().is_empty() && column_descriptor.table != table_name())
+ continue;
+ if (column_descriptor.name == column_name()) {
+ if (index_in_row.has_value()) {
+ context.result->set_error(SQLErrorCode::AmbiguousColumnName, column_name());
+ return Value::null();
+ }
+ index_in_row = ix;
+ }
}
+ if (index_in_row.has_value())
+ return (*context.current_row)[index_in_row.value()];
context.result->set_error(SQLErrorCode::ColumnDoesNotExist, column_name());
return Value::null();
}
diff --git a/Userland/Libraries/LibSQL/AST/Select.cpp b/Userland/Libraries/LibSQL/AST/Select.cpp
index 6214e67015e3..81ef322a5763 100644
--- a/Userland/Libraries/LibSQL/AST/Select.cpp
+++ b/Userland/Libraries/LibSQL/AST/Select.cpp
@@ -13,13 +13,14 @@ namespace SQL::AST {
RefPtr<SQLResult> Select::execute(ExecutionContext& context) const
{
- if (table_or_subquery_list().size() == 1 && table_or_subquery_list()[0].is_table()) {
- auto table = context.database->get_table(table_or_subquery_list()[0].schema_name(), table_or_subquery_list()[0].table_name());
+ NonnullRefPtrVector<ResultColumn> columns;
+ for (auto& table_descriptor : table_or_subquery_list()) {
+ if (!table_descriptor.is_table())
+ TODO();
+ auto table = context.database->get_table(table_descriptor.schema_name(), table_descriptor.table_name());
if (!table) {
- return SQLResult::construct(SQL::SQLCommand::Select, SQL::SQLErrorCode::TableDoesNotExist, table_or_subquery_list()[0].table_name());
+ return SQLResult::construct(SQL::SQLCommand::Select, SQL::SQLErrorCode::TableDoesNotExist, table_descriptor.table_name());
}
-
- NonnullRefPtrVector<ResultColumn> columns;
if (result_column_list().size() == 1 && result_column_list()[0].type() == ResultType::All) {
for (auto& col : table->columns()) {
columns.append(
@@ -27,35 +28,64 @@ RefPtr<SQLResult> Select::execute(ExecutionContext& context) const
create_ast_node<ColumnNameExpression>(table->parent()->name(), table->name(), col.name()),
""));
}
- } else {
- for (auto& col : result_column_list()) {
- columns.append(col);
- }
}
- context.result = SQLResult::construct();
- AK::NonnullRefPtr<TupleDescriptor> descriptor = AK::adopt_ref(*new TupleDescriptor);
- Tuple tuple(descriptor);
- for (auto& row : context.database->select_all(*table)) {
- context.current_row = &row;
- if (where_clause()) {
- auto where_result = where_clause()->evaluate(context);
- if (context.result->has_error())
- return context.result;
- if (!where_result)
- continue;
- }
- tuple.clear();
- for (auto& col : columns) {
- auto value = col.expression()->evaluate(context);
- if (context.result->has_error())
- return context.result;
- tuple.append(value);
+ }
+
+ VERIFY(!result_column_list().is_empty());
+ if (result_column_list().size() != 1 || result_column_list()[0].type() != ResultType::All) {
+ for (auto& col : result_column_list()) {
+ if (col.type() == ResultType::All)
+ // FIXME can have '*' for example in conjunction with computed columns
+ return SQLResult::construct(SQL::SQLCommand::Select, SQL::SQLErrorCode::SyntaxError, "*");
+ columns.append(col);
+ }
+ }
+
+ context.result = SQLResult::construct();
+ AK::NonnullRefPtr<TupleDescriptor> descriptor = AK::adopt_ref(*new TupleDescriptor);
+ Tuple tuple(descriptor);
+ Vector<Tuple> rows;
+ descriptor->empend("__unity__");
+ tuple.append(Value(SQLType::Boolean, true));
+ rows.append(tuple);
+
+ for (auto& table_descriptor : table_or_subquery_list()) {
+ if (!table_descriptor.is_table())
+ TODO();
+ auto table = context.database->get_table(table_descriptor.schema_name(), table_descriptor.table_name());
+ if (table->num_columns() == 0)
+ continue;
+ auto old_descriptor_size = descriptor->size();
+ descriptor->extend(table->to_tuple_descriptor());
+ for (auto cartesian_row = rows.first(); cartesian_row.size() == old_descriptor_size; cartesian_row = rows.first()) {
+ rows.remove(0);
+ for (auto& table_row : context.database->select_all(*table)) {
+ auto new_row = cartesian_row;
+ new_row.extend(table_row);
+ rows.append(new_row);
}
- context.result->append(tuple);
}
- return context.result;
}
- return SQLResult::construct();
+
+ for (auto& row : rows) {
+ context.current_row = &row;
+ if (where_clause()) {
+ auto where_result = where_clause()->evaluate(context);
+ if (context.result->has_error())
+ return context.result;
+ if (!where_result)
+ continue;
+ }
+ tuple.clear();
+ for (auto& col : columns) {
+ auto value = col.expression()->evaluate(context);
+ if (context.result->has_error())
+ return context.result;
+ tuple.append(value);
+ }
+ context.result->append(tuple);
+ }
+ return context.result;
}
}
diff --git a/Userland/Libraries/LibSQL/SQLResult.h b/Userland/Libraries/LibSQL/SQLResult.h
index 33eab92c2aa2..6f148736556d 100644
--- a/Userland/Libraries/LibSQL/SQLResult.h
+++ b/Userland/Libraries/LibSQL/SQLResult.h
@@ -51,6 +51,7 @@ constexpr char const* command_tag(SQLCommand command)
S(SchemaExists, "Schema '{}' already exist") \
S(TableDoesNotExist, "Table '{}' does not exist") \
S(ColumnDoesNotExist, "Column '{}' does not exist") \
+ S(AmbiguousColumnName, "Column name '{}' is ambiguous") \
S(TableExists, "Table '{}' already exist") \
S(InvalidType, "Invalid type '{}'") \
S(InvalidDatabaseName, "Invalid database name '{}'") \
|
fdc86ddae52dfdd2c65ed39d4c22f243ebe6a4ec
|
2021-09-26 15:25:51
|
Nico Weber
|
kernel: Add a GPIO class for aarch64
| false
|
Add a GPIO class for aarch64
|
kernel
|
diff --git a/Kernel/Prekernel/Arch/aarch64/GPIO.cpp b/Kernel/Prekernel/Arch/aarch64/GPIO.cpp
new file mode 100644
index 000000000000..3a0b8b40c726
--- /dev/null
+++ b/Kernel/Prekernel/Arch/aarch64/GPIO.cpp
@@ -0,0 +1,98 @@
+/*
+ * Copyright (c) 2021, Nico Weber <[email protected]>
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#include <Kernel/Prekernel/Arch/aarch64/GPIO.h>
+#include <Kernel/Prekernel/Arch/aarch64/MMIO.h>
+
+extern "C" void wait_cycles(int n);
+
+namespace Prekernel {
+
+// See BCM2835-ARM-Peripherals.pdf section "6 General Purpose I/O" or bcm2711-peripherals.pdf "Chapter 5. General Purpose I/O".
+
+// "6.1 Register View" / "5.2 Register View"
+
+struct PinData {
+ u32 bits[2];
+ u32 reserved;
+};
+
+struct GPIOControlRegisters {
+ u32 function_select[6]; // Every u32 stores a 3-bit function code for 10 pins.
+ u32 reserved;
+ PinData output_set;
+ PinData output_clear;
+ PinData level;
+ PinData event_detect_status;
+ PinData rising_edge_detect_enable;
+ PinData falling_edge_detect_enable;
+ PinData high_detect_enable;
+ PinData low_detect_enable;
+ PinData async_rising_edge_detect_enable;
+ PinData async_falling_edge_detect_enable;
+ u32 pull_up_down_enable;
+ PinData pull_up_down_enable_clock;
+ u32 test;
+};
+
+GPIO::GPIO()
+ : m_registers(MMIO::the().peripheral<GPIOControlRegisters>(0x20'0000))
+{
+}
+
+GPIO& GPIO::the()
+{
+ static GPIO instance;
+ return instance;
+}
+
+void GPIO::set_pin_function(unsigned pin_number, PinFunction function)
+{
+ // pin_number must be <= 53. We can't VERIFY() that since this function runs too early to print assertion failures.
+
+ unsigned function_select_index = pin_number / 10;
+ unsigned function_select_bits_start = (pin_number % 10) * 3;
+
+ u32 function_bits = m_registers->function_select[function_select_index];
+ function_bits = (function_bits & ~(0b111 << function_select_bits_start)) | (static_cast<u32>(function) << function_select_bits_start);
+ m_registers->function_select[function_select_index] = function_bits;
+}
+
+void GPIO::internal_enable_pins(u32 enable[2], PullUpDownState state)
+{
+ // Section "GPIO Pull-up/down Clock Registers (GPPUDCLKn)":
+ // The GPIO Pull-up/down Clock Registers control the actuation of internal pull-downs on
+ // the respective GPIO pins. These registers must be used in conjunction with the GPPUD
+ // register to effect GPIO Pull-up/down changes. The following sequence of events is
+ // required:
+ // 1. Write to GPPUD to set the required control signal (i.e. Pull-up or Pull-Down or neither
+ // to remove the current Pull-up/down)
+ m_registers->pull_up_down_enable = static_cast<u32>(state);
+
+ // 2. Wait 150 cycles – this provides the required set-up time for the control signal
+ wait_cycles(150);
+
+ // 3. Write to GPPUDCLK0/1 to clock the control signal into the GPIO pads you wish to
+ // modify – NOTE only the pads which receive a clock will be modified, all others will
+ // retain their previous state.
+ m_registers->pull_up_down_enable_clock.bits[0] = enable[0];
+ m_registers->pull_up_down_enable_clock.bits[1] = enable[1];
+
+ // 4. Wait 150 cycles – this provides the required hold time for the control signal
+ wait_cycles(150);
+
+ // 5. Write to GPPUD to remove the control signal
+ m_registers->pull_up_down_enable = 0;
+
+ // 6. Write to GPPUDCLK0/1 to remove the clock
+ m_registers->pull_up_down_enable_clock.bits[0] = 0;
+ m_registers->pull_up_down_enable_clock.bits[1] = 0;
+
+ // bcm2711-peripherals.pdf documents GPIO_PUP_PDN_CNTRL_REG[4] registers that store 2 bits state per register, similar to function_select.
+ // I don't know if the RPi3 has that already, so this uses the old BCM2835 approach for now.
+}
+
+}
diff --git a/Kernel/Prekernel/Arch/aarch64/GPIO.h b/Kernel/Prekernel/Arch/aarch64/GPIO.h
new file mode 100644
index 000000000000..4f38f9c37640
--- /dev/null
+++ b/Kernel/Prekernel/Arch/aarch64/GPIO.h
@@ -0,0 +1,60 @@
+/*
+ * Copyright (c) 2021, Nico Weber <[email protected]>
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#pragma once
+
+#include <AK/Array.h>
+#include <AK/Types.h>
+
+namespace Prekernel {
+
+struct GPIOControlRegisters;
+
+// Can configure the general-purpose I/O registers on a Raspberry Pi.
+class GPIO {
+public:
+ enum class PinFunction {
+ Input = 0,
+ Output = 1,
+ Alternate0 = 0b100,
+ Alternate1 = 0b101,
+ Alternate2 = 0b110,
+ Alternate3 = 0b111,
+ Alternate4 = 0b011,
+ Alternate5 = 0b010,
+ };
+
+ static GPIO& the();
+
+ void set_pin_function(unsigned pin_number, PinFunction);
+
+ enum class PullUpDownState {
+ Disable = 0,
+ PullDown = 1,
+ PullUp = 2,
+ };
+
+ template<size_t N>
+ void set_pin_pull_up_down_state(Array<int, N> pins, PullUpDownState state)
+ {
+ u32 enable[2] = {};
+ for (int pin : pins) {
+ if (pin < 32)
+ enable[0] |= (1 << pin);
+ else
+ enable[1] |= (1 << (pin - 32));
+ }
+ internal_enable_pins(enable, state);
+ }
+
+private:
+ GPIO();
+ void internal_enable_pins(u32 enable[2], PullUpDownState state);
+
+ GPIOControlRegisters volatile* m_registers;
+};
+
+}
diff --git a/Kernel/Prekernel/Arch/aarch64/MMIO.h b/Kernel/Prekernel/Arch/aarch64/MMIO.h
index 0eb00ea5d322..46e28e8a55e3 100644
--- a/Kernel/Prekernel/Arch/aarch64/MMIO.h
+++ b/Kernel/Prekernel/Arch/aarch64/MMIO.h
@@ -18,8 +18,12 @@ class MMIO {
public:
static MMIO& the();
- u32 read(FlatPtr offset) { return *(u32 volatile*)(m_base_address + offset); }
- void write(FlatPtr offset, u32 value) { *(u32 volatile*)(m_base_address + offset) = value; }
+ u32 read(FlatPtr offset) { return *peripheral_address(offset); }
+ void write(FlatPtr offset, u32 value) { *peripheral_address(offset) = value; }
+
+ u32 volatile* peripheral_address(FlatPtr offset) { return (u32 volatile*)(m_base_address + offset); }
+ template<class T>
+ T volatile* peripheral(FlatPtr offset) { return (T volatile*)peripheral_address(offset); }
private:
MMIO();
diff --git a/Kernel/Prekernel/Arch/aarch64/boot.S b/Kernel/Prekernel/Arch/aarch64/boot.S
index 2d92aecdd93c..264f800ad41e 100644
--- a/Kernel/Prekernel/Arch/aarch64/boot.S
+++ b/Kernel/Prekernel/Arch/aarch64/boot.S
@@ -21,3 +21,13 @@ start:
mov sp, x14
b init
+
+.globl wait_cycles
+.type wait_cycles, @function
+wait_cycles:
+Lstart:
+ // This is probably too fast when caching and branch prediction is turned on.
+ // FIXME: Make timer-based.
+ subs x0, x0, #1
+ bne Lstart
+ ret
diff --git a/Kernel/Prekernel/Arch/aarch64/init.cpp b/Kernel/Prekernel/Arch/aarch64/init.cpp
index d62e61701dc5..3451b19fa8c4 100644
--- a/Kernel/Prekernel/Arch/aarch64/init.cpp
+++ b/Kernel/Prekernel/Arch/aarch64/init.cpp
@@ -5,6 +5,7 @@
*/
#include <AK/Types.h>
+#include <Kernel/Prekernel/Arch/aarch64/GPIO.h>
#include <Kernel/Prekernel/Arch/aarch64/Mailbox.h>
extern "C" [[noreturn]] void halt();
@@ -12,6 +13,12 @@ extern "C" [[noreturn]] void halt();
extern "C" [[noreturn]] void init();
extern "C" [[noreturn]] void init()
{
+ auto& gpio = Prekernel::GPIO::the();
+ gpio.set_pin_function(14, Prekernel::GPIO::PinFunction::Alternate0);
+ gpio.set_pin_function(15, Prekernel::GPIO::PinFunction::Alternate0);
+
+ gpio.set_pin_pull_up_down_state(Array { 14, 15 }, Prekernel::GPIO::PullUpDownState::Disable);
+
[[maybe_unused]] u32 firmware_version = Prekernel::Mailbox::query_firmware_version();
halt();
}
@@ -32,3 +39,8 @@ void __stack_chk_fail()
{
halt();
}
+
+[[noreturn]] void __assertion_failed(char const*, char const*, unsigned int, char const*)
+{
+ halt();
+}
diff --git a/Kernel/Prekernel/CMakeLists.txt b/Kernel/Prekernel/CMakeLists.txt
index 66e88964b876..1583f253b45b 100644
--- a/Kernel/Prekernel/CMakeLists.txt
+++ b/Kernel/Prekernel/CMakeLists.txt
@@ -12,6 +12,7 @@ if ("${SERENITY_ARCH}" STREQUAL "aarch64")
Arch/aarch64/boot.S
${SOURCES}
+ Arch/aarch64/GPIO.cpp
Arch/aarch64/Mailbox.cpp
Arch/aarch64/MainIdRegister.cpp
Arch/aarch64/MMIO.cpp
|
605a225b53197089c09b14cc507ca7c6d816694c
|
2019-10-14 21:01:52
|
Andreas Kling
|
libhtml: Parse the :link and :hover CSS pseudo-classes
| false
|
Parse the :link and :hover CSS pseudo-classes
|
libhtml
|
diff --git a/Libraries/LibHTML/CSS/Selector.h b/Libraries/LibHTML/CSS/Selector.h
index 16111d641738..c30bad10d670 100644
--- a/Libraries/LibHTML/CSS/Selector.h
+++ b/Libraries/LibHTML/CSS/Selector.h
@@ -15,6 +15,13 @@ class Selector {
};
Type type { Type::Invalid };
+ enum class PseudoClass {
+ None,
+ Link,
+ Hover,
+ };
+ PseudoClass pseudo_class { PseudoClass::None };
+
enum class Relation {
None,
ImmediateChild,
diff --git a/Libraries/LibHTML/Parser/CSSParser.cpp b/Libraries/LibHTML/Parser/CSSParser.cpp
index fc96d6241cd1..a8afc81e2dc9 100644
--- a/Libraries/LibHTML/Parser/CSSParser.cpp
+++ b/Libraries/LibHTML/Parser/CSSParser.cpp
@@ -197,7 +197,7 @@ class CSSParser {
buffer.append(consume_one());
PARSE_ASSERT(!buffer.is_null());
- Selector::Component component { type, relation, String::copy(buffer) };
+ Selector::Component component { type, Selector::Component::PseudoClass::None, relation, String::copy(buffer) };
buffer.clear();
if (peek() == '[') {
@@ -209,12 +209,23 @@ class CSSParser {
}
if (peek() == ':') {
- // FIXME: Implement pseudo stuff.
+ // FIXME: Implement pseudo elements.
+ [[maybe_unused]] bool is_pseudo_element = false;
consume_one();
- if (peek() == ':')
+ if (peek() == ':') {
+ is_pseudo_element = true;
consume_one();
+ }
while (is_valid_selector_char(peek()))
- consume_one();
+ buffer.append(consume_one());
+
+ auto pseudo_name = String::copy(buffer);
+ buffer.clear();
+
+ if (pseudo_name == "link")
+ component.pseudo_class = Selector::Component::PseudoClass::Link;
+ else if (pseudo_name == "hover")
+ component.pseudo_class = Selector::Component::PseudoClass::Hover;
}
return component;
|
4acdb60ba38cf0c579d9b630d55868eb0571d724
|
2020-08-22 20:48:14
|
Ben Wiederhake
|
ak: Prevent confusing silent misuse of ByteBuffer
| false
|
Prevent confusing silent misuse of ByteBuffer
|
ak
|
diff --git a/AK/ByteBuffer.cpp b/AK/ByteBuffer.cpp
new file mode 100644
index 000000000000..9e9af19c6d12
--- /dev/null
+++ b/AK/ByteBuffer.cpp
@@ -0,0 +1,52 @@
+/*
+ * Copyright (c) 2020, the SerenityOS developers.
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright notice, this
+ * list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following disclaimer in the documentation
+ * and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
+ * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
+ * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include <AK/ByteBuffer.h>
+
+namespace AK {
+
+bool ByteBuffer::operator==(const ByteBuffer& other) const
+{
+ if (is_empty() != other.is_empty())
+ return false;
+ if (is_empty())
+ return true;
+ if (size() != other.size())
+ return false;
+
+ // So they both have data, and the same length.
+ // Avoid hitting conditionals in ever iteration.
+ size_t n = size();
+ const u8* this_data = data();
+ const u8* other_data = other.data();
+ for (size_t i = 0; i < n; ++i) {
+ if (this_data[i] != other_data[i])
+ return false;
+ }
+ return true;
+}
+
+}
diff --git a/AK/ByteBuffer.h b/AK/ByteBuffer.h
index 2c53a578fa44..43a79c2df180 100644
--- a/AK/ByteBuffer.h
+++ b/AK/ByteBuffer.h
@@ -147,6 +147,14 @@ class ByteBuffer {
bool operator!() const { return is_null(); }
bool is_null() const { return m_impl == nullptr; }
+ // Disable default implementations that would use surprising integer promotion.
+ bool operator==(const ByteBuffer& other) const;
+ bool operator!=(const ByteBuffer& other) const { return !(*this == other); }
+ bool operator<=(const ByteBuffer& other) const = delete;
+ bool operator>=(const ByteBuffer& other) const = delete;
+ bool operator<(const ByteBuffer& other) const = delete;
+ bool operator>(const ByteBuffer& other) const = delete;
+
u8& operator[](size_t i)
{
ASSERT(m_impl);
diff --git a/AK/Tests/TestByteBuffer.cpp b/AK/Tests/TestByteBuffer.cpp
index ce2e323336d8..b813829cb5e0 100644
--- a/AK/Tests/TestByteBuffer.cpp
+++ b/AK/Tests/TestByteBuffer.cpp
@@ -53,17 +53,21 @@ TEST_CASE(equality_operator)
EXPECT_EQ(d == d, true);
}
-TEST_CASE(other_operators)
+/*
+ * FIXME: These `negative_*` tests should cause precisely one compilation error
+ * each, and always for the specified reason. Currently we do not have a harness
+ * for that, so in order to run the test you need to set the #define to 1, compile
+ * it, and check the error messages manually.
+ */
+#define COMPILE_NEGATIVE_TESTS 0
+#if COMPILE_NEGATIVE_TESTS
+TEST_CASE(negative_operator_lt)
{
- ByteBuffer a = ByteBuffer::copy("Hello, world", 7);
- ByteBuffer b = ByteBuffer::copy("Hello, friend", 7);
- // `a` and `b` are both "Hello, ".
- ByteBuffer c = ByteBuffer::copy("asdf", 4);
- ByteBuffer d;
- EXPECT_EQ(a < a, true);
- EXPECT_EQ(a <= b, true);
- EXPECT_EQ(a >= c, false);
- EXPECT_EQ(a > d, false);
+ ByteBuffer a = ByteBuffer::copy("Hello, world", 10);
+ ByteBuffer b = ByteBuffer::copy("Hello, friend", 10);
+ (void)(a < b);
+ // error: error: use of deleted function ‘bool AK::ByteBuffer::operator<(const AK::ByteBuffer&) const’
}
+#endif /* COMPILE_NEGATIVE_TESTS */
TEST_MAIN(ByteBuffer)
|
fbbb4b33955ec089dc8b26df76f59e25ba49d37d
|
2021-04-12 17:36:24
|
Peter Elliott
|
ports: fallback to pro when curl is not installed
| false
|
fallback to pro when curl is not installed
|
ports
|
diff --git a/Ports/.port_include.sh b/Ports/.port_include.sh
index a1620d9eff94..2e282d450ea8 100755
--- a/Ports/.port_include.sh
+++ b/Ports/.port_include.sh
@@ -70,7 +70,7 @@ fetch() {
echo "URL: ${url}"
# FIXME: Serenity's curl port does not support https, even with openssl installed.
- if ! curl https://example.com -so /dev/null; then
+ if which curl && ! curl https://example.com -so /dev/null; then
url=$(echo "$url" | sed "s/^https:\/\//http:\/\//")
fi
@@ -79,7 +79,11 @@ fetch() {
if [ -f "$filename" ]; then
echo "$filename already exists"
else
- run_nocd curl ${curlopts:-} "$url" -L -o "$filename"
+ if which curl; then
+ run_nocd curl ${curlopts:-} "$url" -L -o "$filename"
+ else
+ run_nocd pro "$url" > "$filename"
+ fi
fi
# check md5sum if given
|
afde1821b5022cb8791e5aa442a56040e190772b
|
2021-11-30 22:35:32
|
davidot
|
libjs: Disallow numerical separators in octal numbers and after '.'
| false
|
Disallow numerical separators in octal numbers and after '.'
|
libjs
|
diff --git a/Userland/Libraries/LibJS/Lexer.cpp b/Userland/Libraries/LibJS/Lexer.cpp
index 907e4920ddd8..30e00eb63674 100644
--- a/Userland/Libraries/LibJS/Lexer.cpp
+++ b/Userland/Libraries/LibJS/Lexer.cpp
@@ -654,7 +654,7 @@ Token Lexer::next()
if (m_current_char == '.') {
// decimal
consume();
- while (is_ascii_digit(m_current_char) || match_numeric_literal_separator_followed_by(is_ascii_digit))
+ while (is_ascii_digit(m_current_char))
consume();
if (m_current_char == 'e' || m_current_char == 'E')
is_invalid_numeric_literal = !consume_exponent();
@@ -688,7 +688,7 @@ Token Lexer::next()
// octal without '0o' prefix. Forbidden in 'strict mode'
do {
consume();
- } while (is_ascii_digit(m_current_char) || match_numeric_literal_separator_followed_by(is_ascii_digit));
+ } while (is_ascii_digit(m_current_char));
}
} else {
// 1...9 or period
@@ -700,11 +700,15 @@ Token Lexer::next()
} else {
if (m_current_char == '.') {
consume();
- while (is_ascii_digit(m_current_char) || match_numeric_literal_separator_followed_by(is_ascii_digit))
+ if (m_current_char == '_')
+ is_invalid_numeric_literal = true;
+
+ while (is_ascii_digit(m_current_char) || match_numeric_literal_separator_followed_by(is_ascii_digit)) {
consume();
+ }
}
if (m_current_char == 'e' || m_current_char == 'E')
- is_invalid_numeric_literal = !consume_exponent();
+ is_invalid_numeric_literal = is_invalid_numeric_literal || !consume_exponent();
}
}
if (is_invalid_numeric_literal) {
diff --git a/Userland/Libraries/LibJS/Tests/syntax/numeric-separator.js b/Userland/Libraries/LibJS/Tests/syntax/numeric-separator.js
new file mode 100644
index 000000000000..589b744b6769
--- /dev/null
+++ b/Userland/Libraries/LibJS/Tests/syntax/numeric-separator.js
@@ -0,0 +1,26 @@
+describe("numeric separators", () => {
+ test("numeric separator works for 'normal' number", () => {
+ expect("1_2").toEvalTo(12);
+ expect("4_2.4_2").toEvalTo(42.42);
+ expect("1_2e0_2").toEvalTo(1200);
+
+ expect("1_2E+_1").not.toEval();
+ expect("1_2E+0_1").toEvalTo(120);
+ });
+
+ test("cannot use numeric separator after .", () => {
+ expect("4._3").not.toEval();
+ expect("0._3").not.toEval();
+ expect("1_.3._3").not.toEval();
+
+ // Actually a valid attempt to get property '_3' on 1.3 which fails but does parse.
+ expect("1.3._3").toEval();
+ });
+
+ test("cannot use numeric separator in octal escaped number", () => {
+ expect("00_1").not.toEval();
+ expect("01_1").not.toEval();
+ expect("07_3").not.toEval();
+ expect("00_1").not.toEval();
+ });
+});
|
c3441719eac25f3310974436a849d6bc92c7cfdd
|
2020-07-18 03:55:02
|
Andreas Kling
|
userspaceemulator: Implement the JCXZ instruction
| false
|
Implement the JCXZ instruction
|
userspaceemulator
|
diff --git a/DevTools/UserspaceEmulator/SoftCPU.cpp b/DevTools/UserspaceEmulator/SoftCPU.cpp
index a6d23af9f268..d65dcad0e61b 100644
--- a/DevTools/UserspaceEmulator/SoftCPU.cpp
+++ b/DevTools/UserspaceEmulator/SoftCPU.cpp
@@ -1289,7 +1289,13 @@ void SoftCPU::IN_AX_imm8(const X86::Instruction&) { TODO(); }
void SoftCPU::IN_EAX_DX(const X86::Instruction&) { TODO(); }
void SoftCPU::IN_EAX_imm8(const X86::Instruction&) { TODO(); }
void SoftCPU::IRET(const X86::Instruction&) { TODO(); }
-void SoftCPU::JCXZ_imm8(const X86::Instruction&) { TODO(); }
+
+void SoftCPU::JCXZ_imm8(const X86::Instruction& insn)
+{
+ if ((insn.a32() && ecx() == 0) || (!insn.a32() && cx() == 0))
+ set_eip(eip() + (i8)insn.imm8());
+}
+
void SoftCPU::JMP_FAR_mem16(const X86::Instruction&) { TODO(); }
void SoftCPU::JMP_FAR_mem32(const X86::Instruction&) { TODO(); }
void SoftCPU::JMP_RM16(const X86::Instruction&) { TODO(); }
|
4eef3e5a09f6dcdddb654e05a77831ef27a3a537
|
2020-03-20 19:11:23
|
Andreas Kling
|
ak: Add StringBuilder::join() for joining collections with a separator
| false
|
Add StringBuilder::join() for joining collections with a separator
|
ak
|
diff --git a/AK/StringBuilder.h b/AK/StringBuilder.h
index 139fe3017a29..fc627b230bbf 100644
--- a/AK/StringBuilder.h
+++ b/AK/StringBuilder.h
@@ -56,6 +56,19 @@ class StringBuilder {
bool is_empty() const { return m_length == 0; }
void trim(size_t count) { m_length -= count; }
+ template<class SeparatorType, class CollectionType>
+ void join(const SeparatorType& separator, const CollectionType& collection)
+ {
+ bool first = true;
+ for (auto& item : collection) {
+ if (first)
+ first = false;
+ else
+ append(separator);
+ append(item);
+ }
+ }
+
private:
void will_append(size_t);
|
fe848487dbcc584728cdcd7a2798fd1c68aa1251
|
2024-02-22 12:01:54
|
Matthew Olsson
|
libweb: Add Document::update_animations_and_send_events
| false
|
Add Document::update_animations_and_send_events
|
libweb
|
diff --git a/Userland/Libraries/LibWeb/DOM/Document.cpp b/Userland/Libraries/LibWeb/DOM/Document.cpp
index d00c30a9a62e..0eebf513aca1 100644
--- a/Userland/Libraries/LibWeb/DOM/Document.cpp
+++ b/Userland/Libraries/LibWeb/DOM/Document.cpp
@@ -3,6 +3,7 @@
* Copyright (c) 2021-2023, Linus Groh <[email protected]>
* Copyright (c) 2021-2023, Luke Wilde <[email protected]>
* Copyright (c) 2021-2023, Sam Atkins <[email protected]>
+ * Copyright (c) 2024, Matthew Olsson <[email protected]>
*
* SPDX-License-Identifier: BSD-2-Clause
*/
@@ -10,12 +11,16 @@
#include <AK/CharacterTypes.h>
#include <AK/Debug.h>
#include <AK/GenericLexer.h>
+#include <AK/InsertionSort.h>
#include <AK/StringBuilder.h>
#include <AK/Utf8View.h>
#include <LibCore/Timer.h>
#include <LibJS/Runtime/Array.h>
#include <LibJS/Runtime/FunctionObject.h>
#include <LibJS/Runtime/NativeFunction.h>
+#include <LibWeb/Animations/Animation.h>
+#include <LibWeb/Animations/AnimationPlaybackEvent.h>
+#include <LibWeb/Animations/AnimationTimeline.h>
#include <LibWeb/Animations/DocumentTimeline.h>
#include <LibWeb/Bindings/MainThreadVM.h>
#include <LibWeb/CSS/MediaQueryList.h>
@@ -3752,6 +3757,72 @@ void Document::append_pending_animation_event(Web::DOM::Document::PendingAnimati
m_pending_animation_event_queue.append(event);
}
+// https://www.w3.org/TR/web-animations-1/#update-animations-and-send-events
+void Document::update_animations_and_send_events(Optional<double> const& timestamp)
+{
+ // 1. Update the current time of all timelines associated with doc passing now as the timestamp.
+ //
+ // Note: Due to the hierarchical nature of the timing model, updating the current time of a timeline also involves:
+ // - Updating the current time of any animations associated with the timeline.
+ // - Running the update an animation’s finished state procedure for any animations whose current time has been
+ // updated.
+ // - Queueing animation events for any such animations.
+ for (auto const& timeline : m_associated_animation_timelines)
+ timeline->set_current_time(timestamp);
+
+ // 2. Remove replaced animations for doc.
+ remove_replaced_animations();
+
+ // 3. Perform a microtask checkpoint.
+ HTML::perform_a_microtask_checkpoint();
+
+ // 4. Let events to dispatch be a copy of doc’s pending animation event queue.
+ // 5. Clear doc’s pending animation event queue.
+ auto events_to_dispatch = move(m_pending_animation_event_queue);
+
+ // 6. Perform a stable sort of the animation events in events to dispatch as follows:
+ auto sort_events_by_composite_order = [](auto const& a, auto const& b) {
+ auto& a_effect = verify_cast<Animations::KeyframeEffect>(*a.target->effect());
+ auto& b_effect = verify_cast<Animations::KeyframeEffect>(*b.target->effect());
+ return Animations::KeyframeEffect::composite_order(a_effect, b_effect) < 0;
+ };
+
+ insertion_sort(events_to_dispatch, [&](auto const& a, auto const& b) {
+ // Sort the events by their scheduled event time such that events that were scheduled to occur earlier, sort
+ // before events scheduled to occur later and events whose scheduled event time is unresolved sort before events
+ // with a resolved scheduled event time.
+ //
+ // Within events with equal scheduled event times, sort by their composite order.
+ if (b.scheduled_event_time.has_value()) {
+ if (!a.scheduled_event_time.has_value())
+ return true;
+
+ auto a_time = a.scheduled_event_time.value();
+ auto b_time = b.scheduled_event_time.value();
+ if (a_time == b_time)
+ return sort_events_by_composite_order(a, b);
+
+ return a.scheduled_event_time.value() < b.scheduled_event_time.value();
+ }
+
+ if (a.scheduled_event_time.has_value())
+ return false;
+
+ return sort_events_by_composite_order(a, b);
+ });
+
+ // 7. Dispatch each of the events in events to dispatch at their corresponding target using the order established in
+ // the previous step.
+ for (auto const& event : events_to_dispatch)
+ event.target->dispatch_event(event.event);
+}
+
+// https://www.w3.org/TR/web-animations-1/#remove-replaced-animations
+void Document::remove_replaced_animations()
+{
+ // FIXME: Implement this
+}
+
// https://html.spec.whatwg.org/multipage/dom.html#dom-document-nameditem-filter
static bool is_potentially_named_element(DOM::Element const& element)
{
diff --git a/Userland/Libraries/LibWeb/DOM/Document.h b/Userland/Libraries/LibWeb/DOM/Document.h
index a994c6550284..15757ed1fc8a 100644
--- a/Userland/Libraries/LibWeb/DOM/Document.h
+++ b/Userland/Libraries/LibWeb/DOM/Document.h
@@ -559,6 +559,8 @@ class Document
Optional<double> scheduled_event_time;
};
void append_pending_animation_event(PendingAnimationEvent const&);
+ void update_animations_and_send_events(Optional<double> const& timestamp);
+ void remove_replaced_animations();
bool ready_to_run_scripts() const { return m_ready_to_run_scripts; }
|
c1de46aaaf2145c78103719e11ce2035cbd4128d
|
2021-06-08 15:45:04
|
Max Wipfli
|
kernel: Don't assume there are no nodes if m_unveiled_paths.is_empty()
| false
|
Don't assume there are no nodes if m_unveiled_paths.is_empty()
|
kernel
|
diff --git a/Kernel/FileSystem/VirtualFileSystem.cpp b/Kernel/FileSystem/VirtualFileSystem.cpp
index 60e5be00260f..cce7e71f5369 100644
--- a/Kernel/FileSystem/VirtualFileSystem.cpp
+++ b/Kernel/FileSystem/VirtualFileSystem.cpp
@@ -827,16 +827,14 @@ Custody& VFS::root_custody()
return *m_root_custody;
}
-const UnveilNode* VFS::find_matching_unveiled_path(StringView path)
+UnveilNode const& VFS::find_matching_unveiled_path(StringView path)
{
+ VERIFY(Process::current()->veil_state() != VeilState::None);
auto& unveil_root = Process::current()->unveiled_paths();
- if (unveil_root.is_empty())
- return nullptr;
LexicalPath lexical_path { path };
auto& path_parts = lexical_path.parts();
- auto& last_matching_node = unveil_root.traverse_until_last_accessible_node(path_parts.begin(), path_parts.end());
- return &last_matching_node;
+ return unveil_root.traverse_until_last_accessible_node(path_parts.begin(), path_parts.end());
}
KResult VFS::validate_path_against_process_veil(StringView path, int options)
@@ -850,22 +848,22 @@ KResult VFS::validate_path_against_process_veil(StringView path, int options)
if (String(path).contains("/.."))
return EINVAL;
- auto* unveiled_path = find_matching_unveiled_path(path);
- if (!unveiled_path || unveiled_path->permissions() == UnveilAccess::None) {
+ auto& unveiled_path = find_matching_unveiled_path(path);
+ if (unveiled_path.permissions() == UnveilAccess::None) {
dbgln("Rejecting path '{}' since it hasn't been unveiled.", path);
dump_backtrace();
return ENOENT;
}
if (options & O_CREAT) {
- if (!(unveiled_path->permissions() & UnveilAccess::CreateOrRemove)) {
+ if (!(unveiled_path.permissions() & UnveilAccess::CreateOrRemove)) {
dbgln("Rejecting path '{}' since it hasn't been unveiled with 'c' permission.", path);
dump_backtrace();
return EACCES;
}
}
if (options & O_UNLINK_INTERNAL) {
- if (!(unveiled_path->permissions() & UnveilAccess::CreateOrRemove)) {
+ if (!(unveiled_path.permissions() & UnveilAccess::CreateOrRemove)) {
dbgln("Rejecting path '{}' for unlink since it hasn't been unveiled with 'c' permission.", path);
dump_backtrace();
return EACCES;
@@ -874,13 +872,13 @@ KResult VFS::validate_path_against_process_veil(StringView path, int options)
}
if (options & O_RDONLY) {
if (options & O_DIRECTORY) {
- if (!(unveiled_path->permissions() & (UnveilAccess::Read | UnveilAccess::Browse))) {
+ if (!(unveiled_path.permissions() & (UnveilAccess::Read | UnveilAccess::Browse))) {
dbgln("Rejecting path '{}' since it hasn't been unveiled with 'r' or 'b' permissions.", path);
dump_backtrace();
return EACCES;
}
} else {
- if (!(unveiled_path->permissions() & UnveilAccess::Read)) {
+ if (!(unveiled_path.permissions() & UnveilAccess::Read)) {
dbgln("Rejecting path '{}' since it hasn't been unveiled with 'r' permission.", path);
dump_backtrace();
return EACCES;
@@ -888,14 +886,14 @@ KResult VFS::validate_path_against_process_veil(StringView path, int options)
}
}
if (options & O_WRONLY) {
- if (!(unveiled_path->permissions() & UnveilAccess::Write)) {
+ if (!(unveiled_path.permissions() & UnveilAccess::Write)) {
dbgln("Rejecting path '{}' since it hasn't been unveiled with 'w' permission.", path);
dump_backtrace();
return EACCES;
}
}
if (options & O_EXEC) {
- if (!(unveiled_path->permissions() & UnveilAccess::Execute)) {
+ if (!(unveiled_path.permissions() & UnveilAccess::Execute)) {
dbgln("Rejecting path '{}' since it hasn't been unveiled with 'x' permission.", path);
dump_backtrace();
return EACCES;
diff --git a/Kernel/FileSystem/VirtualFileSystem.h b/Kernel/FileSystem/VirtualFileSystem.h
index 95ac8e70ef9f..ad92143db130 100644
--- a/Kernel/FileSystem/VirtualFileSystem.h
+++ b/Kernel/FileSystem/VirtualFileSystem.h
@@ -102,7 +102,7 @@ class VFS {
private:
friend class FileDescription;
- const UnveilNode* find_matching_unveiled_path(StringView path);
+ UnveilNode const& find_matching_unveiled_path(StringView path);
KResult validate_path_against_process_veil(StringView path, int options);
bool is_vfs_root(InodeIdentifier) const;
|
1c2ac69e3c3f9fdd22db7d0fcdc8723e68cd2f94
|
2021-08-27 02:34:09
|
Timothy Flynn
|
js: Implement pretty-printing of Intl.DisplayNames
| false
|
Implement pretty-printing of Intl.DisplayNames
|
js
|
diff --git a/Userland/Utilities/js.cpp b/Userland/Utilities/js.cpp
index 30003e35c503..763d0f525196 100644
--- a/Userland/Utilities/js.cpp
+++ b/Userland/Utilities/js.cpp
@@ -29,6 +29,7 @@
#include <LibJS/Runtime/Error.h>
#include <LibJS/Runtime/FunctionObject.h>
#include <LibJS/Runtime/GlobalObject.h>
+#include <LibJS/Runtime/Intl/DisplayNames.h>
#include <LibJS/Runtime/Map.h>
#include <LibJS/Runtime/NativeFunction.h>
#include <LibJS/Runtime/NumberObject.h>
@@ -503,6 +504,20 @@ static void print_temporal_zoned_date_time(JS::Object const& object, HashTable<J
print_value(&zoned_date_time.calendar(), seen_objects);
}
+static void print_intl_display_names(JS::Object const& object, HashTable<JS::Object*>& seen_objects)
+{
+ auto& display_names = static_cast<JS::Intl::DisplayNames const&>(object);
+ print_type("Intl.DisplayNames");
+ out("\n locale: ");
+ print_value(js_string(object.vm(), display_names.locale()), seen_objects);
+ out("\n type: ");
+ print_value(js_string(object.vm(), display_names.type_string()), seen_objects);
+ out("\n style: ");
+ print_value(js_string(object.vm(), display_names.style_string()), seen_objects);
+ out("\n fallback: ");
+ print_value(js_string(object.vm(), display_names.fallback_string()), seen_objects);
+}
+
static void print_primitive_wrapper_object(FlyString const& name, JS::Object const& object, HashTable<JS::Object*>& seen_objects)
{
// BooleanObject, NumberObject, StringObject
@@ -576,6 +591,8 @@ static void print_value(JS::Value value, HashTable<JS::Object*>& seen_objects)
return print_temporal_time_zone(object, seen_objects);
if (is<JS::Temporal::ZonedDateTime>(object))
return print_temporal_zoned_date_time(object, seen_objects);
+ if (is<JS::Intl::DisplayNames>(object))
+ return print_intl_display_names(object, seen_objects);
return print_object(object, seen_objects);
}
|
624fad38215ba10cb3cea9b579bc99e1cbfd7b7a
|
2022-01-29 01:08:47
|
Timothy Flynn
|
js: Implement pretty-printing of Intl.PluralRules
| false
|
Implement pretty-printing of Intl.PluralRules
|
js
|
diff --git a/Userland/Utilities/js.cpp b/Userland/Utilities/js.cpp
index 12e622063e1e..f98e4acc9025 100644
--- a/Userland/Utilities/js.cpp
+++ b/Userland/Utilities/js.cpp
@@ -37,6 +37,7 @@
#include <LibJS/Runtime/Intl/ListFormat.h>
#include <LibJS/Runtime/Intl/Locale.h>
#include <LibJS/Runtime/Intl/NumberFormat.h>
+#include <LibJS/Runtime/Intl/PluralRules.h>
#include <LibJS/Runtime/Intl/RelativeTimeFormat.h>
#include <LibJS/Runtime/JSONObject.h>
#include <LibJS/Runtime/Map.h>
@@ -778,6 +779,36 @@ static void print_intl_relative_time_format(JS::Object& object, HashTable<JS::Ob
print_value(js_string(object.vm(), date_time_format.numeric_string()), seen_objects);
}
+static void print_intl_plural_rules(JS::Object const& object, HashTable<JS::Object*>& seen_objects)
+{
+ auto& plural_rules = static_cast<JS::Intl::PluralRules const&>(object);
+ print_type("Intl.PluralRules");
+ js_out("\n locale: ");
+ print_value(js_string(object.vm(), plural_rules.locale()), seen_objects);
+ js_out("\n type: ");
+ print_value(js_string(object.vm(), plural_rules.type_string()), seen_objects);
+ js_out("\n minimumIntegerDigits: ");
+ print_value(JS::Value(plural_rules.min_integer_digits()), seen_objects);
+ if (plural_rules.has_min_fraction_digits()) {
+ js_out("\n minimumFractionDigits: ");
+ print_value(JS::Value(plural_rules.min_fraction_digits()), seen_objects);
+ }
+ if (plural_rules.has_max_fraction_digits()) {
+ js_out("\n maximumFractionDigits: ");
+ print_value(JS::Value(plural_rules.max_fraction_digits()), seen_objects);
+ }
+ if (plural_rules.has_min_significant_digits()) {
+ js_out("\n minimumSignificantDigits: ");
+ print_value(JS::Value(plural_rules.min_significant_digits()), seen_objects);
+ }
+ if (plural_rules.has_max_significant_digits()) {
+ js_out("\n maximumSignificantDigits: ");
+ print_value(JS::Value(plural_rules.max_significant_digits()), seen_objects);
+ }
+ js_out("\n roundingType: ");
+ print_value(js_string(object.vm(), plural_rules.rounding_type_string()), seen_objects);
+}
+
static void print_primitive_wrapper_object(FlyString const& name, JS::Object const& object, HashTable<JS::Object*>& seen_objects)
{
// BooleanObject, NumberObject, StringObject
@@ -875,6 +906,8 @@ static void print_value(JS::Value value, HashTable<JS::Object*>& seen_objects)
return print_intl_date_time_format(object, seen_objects);
if (is<JS::Intl::RelativeTimeFormat>(object))
return print_intl_relative_time_format(object, seen_objects);
+ if (is<JS::Intl::PluralRules>(object))
+ return print_intl_plural_rules(object, seen_objects);
return print_object(object, seen_objects);
}
|
79b73b7fbbd7263311a7ec60d5f00a927d5158d9
|
2024-02-01 19:53:48
|
Aliaksandr Kalenik
|
libweb: Use Window::scroll() in Element::set_scroll_top()
| false
|
Use Window::scroll() in Element::set_scroll_top()
|
libweb
|
diff --git a/Userland/Libraries/LibWeb/DOM/Element.cpp b/Userland/Libraries/LibWeb/DOM/Element.cpp
index ec16cbcf5eb8..f6605b55c83a 100644
--- a/Userland/Libraries/LibWeb/DOM/Element.cpp
+++ b/Userland/Libraries/LibWeb/DOM/Element.cpp
@@ -1299,17 +1299,13 @@ void Element::set_scroll_top(double y)
// 8. If the element is the root element invoke scroll() on window with scrollX on window as first argument and y as second argument, and terminate these steps.
if (document.document_element() == this) {
- // FIXME: Implement this in terms of invoking scroll() on window.
- if (document.browsing_context() == &document.page().top_level_browsing_context())
- document.page().client().page_did_request_scroll_to({ static_cast<float>(window->scroll_x()), static_cast<float>(y) });
+ window->scroll(window->scroll_x(), y);
return;
}
// 9. If the element is the body element, document is in quirks mode, and the element is not potentially scrollable, invoke scroll() on window with scrollX as first argument and y as second argument, and terminate these steps.
if (document.body() == this && document.in_quirks_mode() && !is_potentially_scrollable()) {
- // FIXME: Implement this in terms of invoking scroll() on window.
- if (document.browsing_context() == &document.page().top_level_browsing_context())
- document.page().client().page_did_request_scroll_to({ static_cast<float>(window->scroll_x()), static_cast<float>(y) });
+ window->scroll(window->scroll_x(), y);
return;
}
|
cc0b970d81c731cf1b9ec81a6f70774524c701c4
|
2022-12-11 22:44:54
|
Ali Mohammad Pur
|
ak: Allow Optional<T> to be constructed by OptionalNone()
| false
|
Allow Optional<T> to be constructed by OptionalNone()
|
ak
|
diff --git a/AK/Optional.h b/AK/Optional.h
index 59b1dd1013ec..08f659dce41a 100644
--- a/AK/Optional.h
+++ b/AK/Optional.h
@@ -44,6 +44,10 @@ using ConditionallyResultType = typename Detail::ConditionallyResultType<conditi
template<typename>
class Optional;
+struct OptionalNone {
+ explicit OptionalNone() = default;
+};
+
template<typename T>
requires(!IsLvalueReference<T>) class [[nodiscard]] Optional<T> {
template<typename U>
@@ -56,6 +60,16 @@ requires(!IsLvalueReference<T>) class [[nodiscard]] Optional<T> {
ALWAYS_INLINE Optional() = default;
+ template<SameAs<OptionalNone> V>
+ Optional(V) { }
+
+ template<SameAs<OptionalNone> V>
+ Optional& operator=(V)
+ {
+ clear();
+ return *this;
+ }
+
#ifdef AK_HAS_CONDITIONALLY_TRIVIAL
Optional(Optional const& other)
requires(!IsCopyConstructible<T>)
@@ -115,6 +129,7 @@ requires(!IsLvalueReference<T>) class [[nodiscard]] Optional<T> {
}
template<typename U = T>
+ requires(!IsSame<OptionalNone, RemoveCVReference<U>>)
ALWAYS_INLINE explicit(!IsConvertible<U&&, T>) Optional(U&& value)
requires(!IsSame<RemoveCVReference<U>, Optional<T>> && IsConstructible<T, U &&>)
: m_has_value(true)
|
60dcf3e023b3595c4f1f944eda7b90d340833b06
|
2025-02-24 15:41:05
|
devgianlu
|
libcrypto: Refactor Edwards-curves implementation with OpenSSL
| false
|
Refactor Edwards-curves implementation with OpenSSL
|
libcrypto
|
diff --git a/Libraries/LibCrypto/CMakeLists.txt b/Libraries/LibCrypto/CMakeLists.txt
index 719a3afeedbb..7a659f3c04d3 100644
--- a/Libraries/LibCrypto/CMakeLists.txt
+++ b/Libraries/LibCrypto/CMakeLists.txt
@@ -22,12 +22,8 @@ set(SOURCES
Checksum/CRC32.cpp
Cipher/AES.cpp
Cipher/Cipher.cpp
- Curves/Curve25519.cpp
- Curves/Ed25519.cpp
- Curves/Ed448.cpp
+ Curves/EdwardsCurve.cpp
Curves/SECPxxxr1.cpp
- Curves/X25519.cpp
- Curves/X448.cpp
Hash/BLAKE2b.cpp
Hash/MD5.cpp
Hash/SHA1.cpp
diff --git a/Libraries/LibCrypto/Curves/Curve25519.cpp b/Libraries/LibCrypto/Curves/Curve25519.cpp
deleted file mode 100644
index 5651598ae1e7..000000000000
--- a/Libraries/LibCrypto/Curves/Curve25519.cpp
+++ /dev/null
@@ -1,360 +0,0 @@
-/*
- * Copyright (c) 2022, stelar7 <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#include <AK/Endian.h>
-#include <AK/Types.h>
-#include <LibCrypto/Curves/Curve25519.h>
-
-namespace Crypto::Curves {
-
-void Curve25519::set(u32* state, u32 value)
-{
- state[0] = value;
-
- for (auto i = 1; i < WORDS; i++) {
- state[i] = 0;
- }
-}
-
-void Curve25519::modular_square(u32* state, u32 const* value)
-{
- // Compute R = (A ^ 2) mod p
- modular_multiply(state, value, value);
-}
-
-void Curve25519::modular_subtract(u32* state, u32 const* first, u32 const* second)
-{
- // R = (A - B) mod p
- i64 temp = -19;
- for (auto i = 0; i < WORDS; i++) {
- temp += first[i];
- temp -= second[i];
- state[i] = temp & 0xFFFFFFFF;
- temp >>= 32;
- }
-
- // Compute R = A + (2^255 - 19) - B
- state[7] += 0x80000000;
-
- modular_reduce(state, state);
-}
-
-void Curve25519::modular_add(u32* state, u32 const* first, u32 const* second)
-{
- // R = (A + B) mod p
- u64 temp = 0;
- for (auto i = 0; i < WORDS; i++) {
- temp += first[i];
- temp += second[i];
- state[i] = temp & 0xFFFFFFFF;
- temp >>= 32;
- }
-
- modular_reduce(state, state);
-}
-
-void Curve25519::modular_multiply(u32* state, u32 const* first, u32 const* second)
-{
- // Compute R = (A * B) mod p
- u64 temp = 0;
- u64 carry = 0;
- u32 output[WORDS * 2];
-
- // Comba's method
- for (auto i = 0; i < 16; i++) {
- if (i < WORDS) {
- for (auto j = 0; j <= i; j++) {
- temp += (u64)first[j] * second[i - j];
- carry += temp >> 32;
- temp &= 0xFFFFFFFF;
- }
- } else {
- for (auto j = i - 7; j < WORDS; j++) {
- temp += (u64)first[j] * second[i - j];
- carry += temp >> 32;
- temp &= 0xFFFFFFFF;
- }
- }
-
- output[i] = temp & 0xFFFFFFFF;
- temp = carry & 0xFFFFFFFF;
- carry >>= 32;
- }
-
- // Reduce bit 255 (2^255 = 19 mod p)
- temp = (output[7] >> 31) * 19;
- // Mask the most significant bit
- output[7] &= 0x7FFFFFFF;
-
- // Fast modular reduction 1st pass
- for (auto i = 0; i < WORDS; i++) {
- temp += output[i];
- temp += (u64)output[i + 8] * 38;
- output[i] = temp & 0xFFFFFFFF;
- temp >>= 32;
- }
-
- // Reduce bit 256 (2^256 = 38 mod p)
- temp *= 38;
- // Reduce bit 255 (2^255 = 19 mod p)
- temp += (output[7] >> 31) * 19;
- // Mask the most significant bit
- output[7] &= 0x7FFFFFFF;
-
- // Fast modular reduction 2nd pass
- for (auto i = 0; i < WORDS; i++) {
- temp += output[i];
- output[i] = temp & 0xFFFFFFFF;
- temp >>= 32;
- }
-
- modular_reduce(state, output);
-}
-
-void Curve25519::export_state(u32* state, u8* output)
-{
- for (u32 i = 0; i < WORDS; i++) {
- state[i] = AK::convert_between_host_and_little_endian(state[i]);
- }
-
- memcpy(output, state, BYTES);
-}
-
-void Curve25519::import_state(u32* state, u8 const* data)
-{
- memcpy(state, data, BYTES);
- for (u32 i = 0; i < WORDS; i++) {
- state[i] = AK::convert_between_host_and_little_endian(state[i]);
- }
-}
-
-void Curve25519::modular_subtract_single(u32* r, u32 const* a, u32 b)
-{
- i64 temp = -19;
- temp -= b;
-
- // Compute R = A - 19 - B
- for (u32 i = 0; i < 8; i++) {
- temp += a[i];
- r[i] = temp & 0xFFFFFFFF;
- temp >>= 32;
- }
-
- // Compute R = A + (2^255 - 19) - B
- r[7] += 0x80000000;
- modular_reduce(r, r);
-}
-
-void Curve25519::modular_add_single(u32* state, u32 const* first, u32 second)
-{
- u64 temp = second;
-
- // Compute R = A + B
- for (u32 i = 0; i < 8; i++) {
- temp += first[i];
- state[i] = temp & 0xFFFFFFFF;
- temp >>= 32;
- }
-
- modular_reduce(state, state);
-}
-
-u32 Curve25519::modular_square_root(u32* r, u32 const* a, u32 const* b)
-{
- u32 c[8];
- u32 u[8];
- u32 v[8];
-
- // To compute the square root of (A / B), the first step is to compute the candidate root x = (A / B)^((p+3)/8)
- modular_square(v, b);
- modular_multiply(v, v, b);
- modular_square(v, v);
- modular_multiply(v, v, b);
- modular_multiply(c, a, v);
- modular_square(u, c);
- modular_multiply(u, u, c);
- modular_square(u, u);
- modular_multiply(v, u, c);
- to_power_of_2n(u, v, 3);
- modular_multiply(u, u, v);
- modular_square(u, u);
- modular_multiply(v, u, c);
- to_power_of_2n(u, v, 7);
- modular_multiply(u, u, v);
- modular_square(u, u);
- modular_multiply(v, u, c);
- to_power_of_2n(u, v, 15);
- modular_multiply(u, u, v);
- modular_square(u, u);
- modular_multiply(v, u, c);
- to_power_of_2n(u, v, 31);
- modular_multiply(v, u, v);
- to_power_of_2n(u, v, 62);
- modular_multiply(u, u, v);
- modular_square(u, u);
- modular_multiply(v, u, c);
- to_power_of_2n(u, v, 125);
- modular_multiply(u, u, v);
- modular_square(u, u);
- modular_square(u, u);
- modular_multiply(u, u, c);
-
- // The first candidate root is U = A * B^3 * (A * B^7)^((p - 5) / 8)
- modular_multiply(u, u, a);
- modular_square(v, b);
- modular_multiply(v, v, b);
- modular_multiply(u, u, v);
-
- // The second candidate root is V = U * sqrt(-1)
- modular_multiply(v, u, SQRT_MINUS_1);
-
- modular_square(c, u);
- modular_multiply(c, c, b);
-
- // Check whether B * U^2 = A
- u32 first_comparison = compare(c, a);
-
- modular_square(c, v);
- modular_multiply(c, c, b);
-
- // Check whether B * V^2 = A
- u32 second_comparison = compare(c, a);
-
- // Select the first or the second candidate root
- select(r, u, v, first_comparison);
-
- // Return 0 if the square root exists
- return first_comparison & second_comparison;
-}
-
-u32 Curve25519::compare(u32 const* a, u32 const* b)
-{
- u32 mask = 0;
- for (u32 i = 0; i < 8; i++) {
- mask |= a[i] ^ b[i];
- }
-
- // Return 0 if A = B, else 1
- return ((u32)(mask | (~mask + 1))) >> 31;
-}
-
-void Curve25519::modular_reduce(u32* state, u32 const* data)
-{
- // R = A mod p
- u64 temp = 19;
- u32 other[WORDS];
-
- for (auto i = 0; i < WORDS; i++) {
- temp += data[i];
- other[i] = temp & 0xFFFFFFFF;
- temp >>= 32;
- }
-
- // Compute B = A - (2^255 - 19)
- other[7] -= 0x80000000;
-
- u32 mask = (other[7] & 0x80000000) >> 31;
- select(state, other, data, mask);
-}
-
-void Curve25519::to_power_of_2n(u32* state, u32 const* value, u8 n)
-{
- // Pre-compute (A ^ 2) mod p
- modular_square(state, value);
-
- // Compute R = (A ^ (2^n)) mod p
- for (u32 i = 1; i < n; i++) {
- modular_square(state, state);
- }
-}
-
-void Curve25519::select(u32* state, u32 const* a, u32 const* b, u32 condition)
-{
- // If B < (2^255 - 19) then R = B, else R = A
- u32 mask = condition - 1;
-
- for (auto i = 0; i < WORDS; i++) {
- state[i] = (a[i] & mask) | (b[i] & ~mask);
- }
-}
-
-void Curve25519::copy(u32* state, u32 const* value)
-{
- for (auto i = 0; i < WORDS; i++) {
- state[i] = value[i];
- }
-}
-
-void Curve25519::modular_multiply_inverse(u32* state, u32 const* value)
-{
- // Compute R = A^-1 mod p
- u32 u[WORDS];
- u32 v[WORDS];
-
- // Fermat's little theorem
- modular_square(u, value);
- modular_multiply(u, u, value);
- modular_square(u, u);
- modular_multiply(v, u, value);
- to_power_of_2n(u, v, 3);
- modular_multiply(u, u, v);
- modular_square(u, u);
- modular_multiply(v, u, value);
- to_power_of_2n(u, v, 7);
- modular_multiply(u, u, v);
- modular_square(u, u);
- modular_multiply(v, u, value);
- to_power_of_2n(u, v, 15);
- modular_multiply(u, u, v);
- modular_square(u, u);
- modular_multiply(v, u, value);
- to_power_of_2n(u, v, 31);
- modular_multiply(v, u, v);
- to_power_of_2n(u, v, 62);
- modular_multiply(u, u, v);
- modular_square(u, u);
- modular_multiply(v, u, value);
- to_power_of_2n(u, v, 125);
- modular_multiply(u, u, v);
- modular_square(u, u);
- modular_square(u, u);
- modular_multiply(u, u, value);
- modular_square(u, u);
- modular_square(u, u);
- modular_multiply(u, u, value);
- modular_square(u, u);
- modular_multiply(state, u, value);
-}
-
-void Curve25519::modular_multiply_single(u32* state, u32 const* first, u32 second)
-{
- // Compute R = (A * B) mod p
- u64 temp = 0;
- u32 output[WORDS];
-
- for (auto i = 0; i < WORDS; i++) {
- temp += (u64)first[i] * second;
- output[i] = temp & 0xFFFFFFFF;
- temp >>= 32;
- }
-
- // Reduce bit 256 (2^256 = 38 mod p)
- temp *= 38;
- // Reduce bit 255 (2^255 = 19 mod p)
- temp += (output[7] >> 31) * 19;
- // Mask the most significant bit
- output[7] &= 0x7FFFFFFF;
-
- // Fast modular reduction
- for (auto i = 0; i < WORDS; i++) {
- temp += output[i];
- output[i] = temp & 0xFFFFFFFF;
- temp >>= 32;
- }
-
- modular_reduce(state, output);
-}
-}
diff --git a/Libraries/LibCrypto/Curves/Curve25519.h b/Libraries/LibCrypto/Curves/Curve25519.h
deleted file mode 100644
index b0ab7a9e86e3..000000000000
--- a/Libraries/LibCrypto/Curves/Curve25519.h
+++ /dev/null
@@ -1,71 +0,0 @@
-/*
- * Copyright (c) 2022, stelar7 <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#pragma once
-
-namespace Crypto::Curves {
-
-class Curve25519 {
-public:
- static constexpr u8 BASE_POINT_L_ORDER[33] {
- 0xED, 0xD3, 0xF5, 0x5C, 0x1A, 0x63, 0x12, 0x58,
- 0xD6, 0x9C, 0xF7, 0xA2, 0xDE, 0xF9, 0xDE, 0x14,
- 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
- 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10,
- 0x00
- };
-
- static constexpr u32 CURVE_D[8] {
- 0x135978A3, 0x75EB4DCA, 0x4141D8AB, 0x00700A4D,
- 0x7779E898, 0x8CC74079, 0x2B6FFE73, 0x52036CEE
- };
-
- static constexpr u32 CURVE_D_2[8] {
- 0x26B2F159, 0xEBD69B94, 0x8283B156, 0x00E0149A,
- 0xEEF3D130, 0x198E80F2, 0x56DFFCE7, 0x2406D9DC
- };
-
- static constexpr u32 ZERO[8] {
- 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000
- };
-
- static constexpr u32 SQRT_MINUS_1[8] {
- 0x4A0EA0B0, 0xC4EE1B27, 0xAD2FE478, 0x2F431806,
- 0x3DFBD7A7, 0x2B4D0099, 0x4FC1DF0B, 0x2B832480
- };
-
- static constexpr u8 BARRETT_REDUCTION_QUOTIENT[33] {
- 0x1B, 0x13, 0x2C, 0x0A, 0xA3, 0xE5, 0x9C, 0xED,
- 0xA7, 0x29, 0x63, 0x08, 0x5D, 0x21, 0x06, 0x21,
- 0xEB, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
- 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
- 0x0F
- };
-
- static constexpr u8 BITS = 255;
- static constexpr u8 BYTES = 32;
- static constexpr u8 WORDS = 8;
- static constexpr u32 A24 = 121666;
-
- static void set(u32* a, u32 b);
- static void select(u32* r, u32 const* a, u32 const* b, u32 c);
- static void copy(u32* a, u32 const* b);
- static void modular_square(u32* r, u32 const* a);
- static void modular_subtract(u32* r, u32 const* a, u32 const* b);
- static void modular_reduce(u32* r, u32 const* a);
- static void modular_add(u32* r, u32 const* a, u32 const* b);
- static void modular_multiply(u32* r, u32 const* a, u32 const* b);
- static void modular_multiply_inverse(u32* r, u32 const* a);
- static void to_power_of_2n(u32* r, u32 const* a, u8 n);
- static void export_state(u32* a, u8* data);
- static void import_state(u32* a, u8 const* data);
- static void modular_subtract_single(u32* r, u32 const* a, u32 b);
- static void modular_multiply_single(u32* r, u32 const* a, u32 b);
- static void modular_add_single(u32* r, u32 const* a, u32 b);
- static u32 modular_square_root(u32* r, u32 const* a, u32 const* b);
- static u32 compare(u32 const* a, u32 const* b);
-};
-}
diff --git a/Libraries/LibCrypto/Curves/Ed25519.cpp b/Libraries/LibCrypto/Curves/Ed25519.cpp
deleted file mode 100644
index 2e0d09bc9df8..000000000000
--- a/Libraries/LibCrypto/Curves/Ed25519.cpp
+++ /dev/null
@@ -1,434 +0,0 @@
-/*
- * Copyright (c) 2022, stelar7 <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#include <AK/Random.h>
-#include <LibCrypto/Curves/Curve25519.h>
-#include <LibCrypto/Curves/Ed25519.h>
-#include <LibCrypto/Hash/SHA2.h>
-#include <LibCrypto/SecureRandom.h>
-
-namespace Crypto::Curves {
-
-// https://datatracker.ietf.org/doc/html/rfc8032#section-5.1.5
-ErrorOr<ByteBuffer> Ed25519::generate_private_key()
-{
- // The private key is 32 octets (256 bits, corresponding to b) of
- // cryptographically secure random data. See [RFC4086] for a discussion
- // about randomness.
-
- auto buffer = TRY(ByteBuffer::create_uninitialized(key_size()));
- fill_with_secure_random(buffer);
- return buffer;
-}
-
-// https://datatracker.ietf.org/doc/html/rfc8032#section-5.1.5
-ErrorOr<ByteBuffer> Ed25519::generate_public_key(ReadonlyBytes private_key)
-{
- // The 32-byte public key is generated by the following steps.
-
- // 1. Hash the 32-byte private key using SHA-512, storing the digest in a 64-octet large buffer, denoted h.
- // Only the lower 32 bytes are used for generating the public key.
- auto digest = Crypto::Hash::SHA512::hash(private_key);
-
- // NOTE: we do these steps in the opposite order (since its easier to modify s)
- // 3. Interpret the buffer as the little-endian integer, forming a secret scalar s.
- memcpy(s, digest.data, 32);
-
- // 2. Prune the buffer:
- // The lowest three bits of the first octet are cleared,
- s[0] &= 0xF8;
- // the highest bit of the last octet is cleared,
- s[31] &= 0x7F;
- // and the second highest bit of the last octet is set.
- s[31] |= 0x40;
-
- // Perform a fixed-base scalar multiplication [s]B.
- point_multiply_scalar(&sb, s, &BASE_POINT);
-
- // 4. The public key A is the encoding of the point [s]B.
- // First, encode the y-coordinate (in the range 0 <= y < p) as a little-endian string of 32 octets.
- // The most significant bit of the final octet is always zero.
- // To form the encoding of the point [s]B, copy the least significant bit of the x coordinate
- // to the most significant bit of the final octet. The result is the public key.
- auto public_key = TRY(ByteBuffer::create_uninitialized(key_size()));
- encode_point(&sb, public_key.data());
-
- return public_key;
-}
-
-// https://datatracker.ietf.org/doc/html/rfc8032#section-5.1.6
-ErrorOr<ByteBuffer> Ed25519::sign(ReadonlyBytes public_key, ReadonlyBytes private_key, ReadonlyBytes message)
-{
- // 1. Hash the private key, 32 octets, using SHA-512.
- // Let h denote the resulting digest.
- auto h = Crypto::Hash::SHA512::hash(private_key);
-
- // Construct the secret scalar s from the first half of the digest,
- memcpy(s, h.data, 32);
- // NOTE: This is done later in step 4, but we can also do it here.
- s[0] &= 0xF8;
- s[31] &= 0x7F;
- s[31] |= 0x40;
-
- // and the corresponding public key A, as described in the previous section.
- // NOTE: The public key A is taken as input to this function.
-
- // Let prefix denote the second half of the hash digest, h[32],...,h[63].
- memcpy(p, h.data + 32, 32);
-
- // 2. Compute SHA-512(dom2(F, C) || p || PH(M)), where M is the message to be signed.
- auto hash = Hash::SHA512::create();
- // NOTE: dom2(F, C) is a blank octet string when signing or verifying Ed25519
- hash->update(p, 32);
- // NOTE: PH(M) = M
- hash->update(message.data(), message.size());
-
- // Interpret the 64-octet digest as a little-endian integer r.
- // For efficiency, do this by first reducing r modulo L, the group order of B.
- auto digest = hash->digest();
- barrett_reduce(r, digest.data);
-
- // 3. Compute the point [r]B.
- point_multiply_scalar(&rb, r, &BASE_POINT);
-
- auto R = TRY(ByteBuffer::create_uninitialized(32));
- // Let the string R be the encoding of this point
- encode_point(&rb, R.data());
-
- // 4. Compute SHA512(dom2(F, C) || R || A || PH(M)),
- // NOTE: We can reuse hash here, since digest() calls reset()
- // NOTE: dom2(F, C) is a blank octet string when signing or verifying Ed25519
- hash->update(R.data(), R.size());
- // NOTE: A == public_key
- hash->update(public_key.data(), public_key.size());
- // NOTE: PH(M) = M
- hash->update(message.data(), message.size());
-
- digest = hash->digest();
- // and interpret the 64-octet digest as a little-endian integer k.
- memcpy(k, digest.data, 64);
-
- // 5. Compute S = (r + k * s) mod L. For efficiency, again reduce k modulo L first.
- barrett_reduce(p, k);
- multiply(k, k + 32, p, s, 32);
- barrett_reduce(p, k);
- add(s, p, r, 32);
-
- // modular reduction
- auto reduced_s = TRY(ByteBuffer::create_uninitialized(32));
- auto is_negative = subtract(p, s, Curve25519::BASE_POINT_L_ORDER, 32);
- select(reduced_s.data(), p, s, is_negative, 32);
-
- // 6. Form the signature of the concatenation of R (32 octets) and the little-endian encoding of S
- // (32 octets; the three most significant bits of the final octet are always zero).
- auto signature = TRY(ByteBuffer::copy(R));
- signature.append(reduced_s);
-
- return signature;
-}
-
-// https://datatracker.ietf.org/doc/html/rfc8032#section-5.1.7
-bool Ed25519::verify(ReadonlyBytes public_key, ReadonlyBytes signature, ReadonlyBytes message)
-{
- auto not_valid = false;
-
- // 1. To verify a signature on a message M using public key A,
- // with F being 0 for Ed25519ctx, 1 for Ed25519ph, and if Ed25519ctx or Ed25519ph is being used, C being the context
- // first split the signature into two 32-octet halves.
- // If any of the decodings fail (including S being out of range), the signature is invalid.
-
- // NOTE: We dont care about F, since we dont implement Ed25519ctx or Ed25519PH
- // NOTE: C is the internal state, so its not a parameter
-
- auto half_signature_size = signature_size() / 2;
-
- // Decode the first half as a point R
- memcpy(r, signature.data(), half_signature_size);
-
- // and the second half as an integer S, in the range 0 <= s < L.
- memcpy(s, signature.data() + half_signature_size, half_signature_size);
-
- // NOTE: Ed25519 and Ed448 signatures are not malleable due to the verification check that decoded S is smaller than l.
- // Without this check, one can add a multiple of l into a scalar part and still pass signature verification,
- // resulting in malleable signatures.
- auto is_negative = subtract(p, s, Curve25519::BASE_POINT_L_ORDER, half_signature_size);
- not_valid |= 1 ^ is_negative;
-
- // Decode the public key A as point A'.
- not_valid |= decode_point(&ka, public_key.data());
-
- // 2. Compute SHA512(dom2(F, C) || R || A || PH(M)), and interpret the 64-octet digest as a little-endian integer k.
- auto hash = Hash::SHA512::create();
- // NOTE: dom2(F, C) is a blank octet string when signing or verifying Ed25519
- hash->update(r, half_signature_size);
- // NOTE: A == public_key
- hash->update(public_key.data(), key_size());
- // NOTE: PH(M) = M
- hash->update(message.data(), message.size());
-
- auto digest = hash->digest();
- auto k = digest.data;
-
- // 3. Check the group equation [8][S]B = [8]R + [8][k]A'.
- // It's sufficient, but not required, to instead check [S]B = R + [k]A'.
- // NOTE: For efficiency, do this by first reducing k modulo L.
- barrett_reduce(k, k);
-
- // NOTE: We check [S]B - [k]A' == R
- Curve25519::modular_subtract(ka.x, Curve25519::ZERO, ka.x);
- Curve25519::modular_subtract(ka.t, Curve25519::ZERO, ka.t);
- point_multiply_scalar(&sb, s, &BASE_POINT);
- point_multiply_scalar(&ka, k, &ka);
- point_add(&ka, &sb, &ka);
- encode_point(&ka, p);
-
- not_valid |= compare(p, r, half_signature_size);
-
- return !not_valid;
-}
-
-void Ed25519::point_double(Ed25519Point* result, Ed25519Point const* point)
-{
- Curve25519::modular_square(a, point->x);
- Curve25519::modular_square(b, point->y);
- Curve25519::modular_square(c, point->z);
- Curve25519::modular_add(c, c, c);
- Curve25519::modular_add(e, a, b);
- Curve25519::modular_add(f, point->x, point->y);
- Curve25519::modular_square(f, f);
- Curve25519::modular_subtract(f, e, f);
- Curve25519::modular_subtract(g, a, b);
- Curve25519::modular_add(h, c, g);
- Curve25519::modular_multiply(result->x, f, h);
- Curve25519::modular_multiply(result->y, e, g);
- Curve25519::modular_multiply(result->z, g, h);
- Curve25519::modular_multiply(result->t, e, f);
-}
-
-void Ed25519::point_multiply_scalar(Ed25519Point* result, u8 const* scalar, Ed25519Point const* point)
-{
- // Set U to the neutral element (0, 1, 1, 0)
- Curve25519::set(u.x, 0);
- Curve25519::set(u.y, 1);
- Curve25519::set(u.z, 1);
- Curve25519::set(u.t, 0);
-
- for (i32 i = Curve25519::BITS - 1; i >= 0; i--) {
- u8 b = (scalar[i / 8] >> (i % 8)) & 1;
-
- // Compute U = 2 * U
- point_double(&u, &u);
- // Compute V = U + P
- point_add(&v, &u, point);
-
- // If b is set, then U = V
- Curve25519::select(u.x, u.x, v.x, b);
- Curve25519::select(u.y, u.y, v.y, b);
- Curve25519::select(u.z, u.z, v.z, b);
- Curve25519::select(u.t, u.t, v.t, b);
- }
-
- Curve25519::copy(result->x, u.x);
- Curve25519::copy(result->y, u.y);
- Curve25519::copy(result->z, u.z);
- Curve25519::copy(result->t, u.t);
-}
-
-// https://datatracker.ietf.org/doc/html/rfc8032#section-5.1.2
-void Ed25519::encode_point(Ed25519Point* point, u8* data)
-{
- // Retrieve affine representation
- Curve25519::modular_multiply_inverse(point->z, point->z);
- Curve25519::modular_multiply(point->x, point->x, point->z);
- Curve25519::modular_multiply(point->y, point->y, point->z);
- Curve25519::set(point->z, 1);
- Curve25519::modular_multiply(point->t, point->x, point->y);
-
- // First, encode the y-coordinate (in the range 0 <= y < p) as a little-endian string of 32 octets.
- // The most significant bit of the final octet is always zero.
- Curve25519::export_state(point->y, data);
-
- // To form the encoding of the point [s]B,
- // copy the least significant bit of the x coordinate to the most significant bit of the final octet.
- data[31] |= (point->x[0] & 1) << 7;
-}
-
-void Ed25519::barrett_reduce(u8* result, u8 const* input)
-{
- // Barrett reduction b = 2^8 && k = 32
- u8 is_negative;
- u8 u[33];
- u8 v[33];
-
- multiply(NULL, u, input + 31, Curve25519::BARRETT_REDUCTION_QUOTIENT, 33);
- multiply(v, NULL, u, Curve25519::BASE_POINT_L_ORDER, 33);
-
- subtract(u, input, v, 33);
-
- is_negative = subtract(v, u, Curve25519::BASE_POINT_L_ORDER, 33);
- select(u, v, u, is_negative, 33);
- is_negative = subtract(v, u, Curve25519::BASE_POINT_L_ORDER, 33);
- select(u, v, u, is_negative, 33);
-
- copy(result, u, 32);
-}
-
-void Ed25519::multiply(u8* result_low, u8* result_high, u8 const* a, u8 const* b, u8 n)
-{
- // Comba's algorithm
- u32 temp = 0;
- for (u32 i = 0; i < n; i++) {
- for (u32 j = 0; j <= i; j++) {
- temp += (uint16_t)a[j] * b[i - j];
- }
-
- if (result_low != NULL) {
- result_low[i] = temp & 0xFF;
- }
-
- temp >>= 8;
- }
-
- if (result_high != NULL) {
- for (u32 i = n; i < (2 * n); i++) {
- for (u32 j = i + 1 - n; j < n; j++) {
- temp += (uint16_t)a[j] * b[i - j];
- }
-
- result_high[i - n] = temp & 0xFF;
- temp >>= 8;
- }
- }
-}
-
-void Ed25519::add(u8* result, u8 const* a, u8 const* b, u8 n)
-{
- // Compute R = A + B
- u16 temp = 0;
- for (u8 i = 0; i < n; i++) {
- temp += a[i];
- temp += b[i];
- result[i] = temp & 0xFF;
- temp >>= 8;
- }
-}
-
-u8 Ed25519::subtract(u8* result, u8 const* a, u8 const* b, u8 n)
-{
- i16 temp = 0;
-
- // Compute R = A - B
- for (i8 i = 0; i < n; i++) {
- temp += a[i];
- temp -= b[i];
- result[i] = temp & 0xFF;
- temp >>= 8;
- }
-
- // Return 1 if the result of the subtraction is negative
- return temp & 1;
-}
-
-void Ed25519::select(u8* r, u8 const* a, u8 const* b, u8 c, u8 n)
-{
- u8 mask = c - 1;
- for (u8 i = 0; i < n; i++) {
- r[i] = (a[i] & mask) | (b[i] & ~mask);
- }
-}
-
-// https://datatracker.ietf.org/doc/html/rfc8032#section-5.1.3
-u32 Ed25519::decode_point(Ed25519Point* point, u8 const* data)
-{
- u32 u[8];
- u32 v[8];
- u32 ret;
- u64 temp = 19;
-
- // 1. First, interpret the string as an integer in little-endian representation.
- // Bit 255 of this number is the least significant bit of the x-coordinate and denote this value x_0.
- u8 x0 = data[31] >> 7;
-
- // The y-coordinate is recovered simply by clearing this bit.
- Curve25519::import_state(point->y, data);
- point->y[7] &= 0x7FFFFFFF;
-
- // Compute U = Y + 19
- for (u32 i = 0; i < 8; i++) {
- temp += point->y[i];
- u[i] = temp & 0xFFFFFFFF;
- temp >>= 32;
- }
-
- // If the resulting value is >= p, decoding fails.
- ret = (u[7] >> 31) & 1;
-
- // 2. To recover the x-coordinate, the curve equation implies x^2 = (y^2 - 1) / (d y^2 + 1) (mod p).
- // The denominator is always non-zero mod p.
- // Let u = y^2 - 1 and v = d * y^2 + 1
- Curve25519::modular_square(v, point->y);
- Curve25519::modular_subtract_single(u, v, 1);
- Curve25519::modular_multiply(v, v, Curve25519::CURVE_D);
- Curve25519::modular_add_single(v, v, 1);
-
- // 3. Compute u = sqrt(u / v)
- ret |= Curve25519::modular_square_root(u, u, v);
-
- // If x = 0, and x_0 = 1, decoding fails.
- ret |= (Curve25519::compare(u, Curve25519::ZERO) ^ 1) & x0;
-
- // 4. Finally, use the x_0 bit to select the right square root.
- Curve25519::modular_subtract(v, Curve25519::ZERO, u);
- Curve25519::select(point->x, u, v, (x0 ^ u[0]) & 1);
- Curve25519::set(point->z, 1);
- Curve25519::modular_multiply(point->t, point->x, point->y);
-
- // Return 0 if the point has been successfully decoded, else 1
- return ret;
-}
-
-void Ed25519::point_add(Ed25519Point* result, Ed25519Point const* p, Ed25519Point const* q)
-{
- // Compute R = P + Q
- Curve25519::modular_add(c, p->y, p->x);
- Curve25519::modular_add(d, q->y, q->x);
- Curve25519::modular_multiply(a, c, d);
- Curve25519::modular_subtract(c, p->y, p->x);
- Curve25519::modular_subtract(d, q->y, q->x);
- Curve25519::modular_multiply(b, c, d);
- Curve25519::modular_multiply(c, p->z, q->z);
- Curve25519::modular_add(c, c, c);
- Curve25519::modular_multiply(d, p->t, q->t);
- Curve25519::modular_multiply(d, d, Curve25519::CURVE_D_2);
- Curve25519::modular_add(e, a, b);
- Curve25519::modular_subtract(f, a, b);
- Curve25519::modular_add(g, c, d);
- Curve25519::modular_subtract(h, c, d);
- Curve25519::modular_multiply(result->x, f, h);
- Curve25519::modular_multiply(result->y, e, g);
- Curve25519::modular_multiply(result->z, g, h);
- Curve25519::modular_multiply(result->t, e, f);
-}
-
-u8 Ed25519::compare(u8 const* a, u8 const* b, u8 n)
-{
- u8 mask = 0;
- for (u32 i = 0; i < n; i++) {
- mask |= a[i] ^ b[i];
- }
-
- // Return 0 if A = B, else 1
- return ((u8)(mask | (~mask + 1))) >> 7;
-}
-
-void Ed25519::copy(u8* a, u8 const* b, u32 n)
-{
- for (u32 i = 0; i < n; i++) {
- a[i] = b[i];
- }
-}
-
-}
diff --git a/Libraries/LibCrypto/Curves/Ed25519.h b/Libraries/LibCrypto/Curves/Ed25519.h
deleted file mode 100644
index e7f5b21a6cc6..000000000000
--- a/Libraries/LibCrypto/Curves/Ed25519.h
+++ /dev/null
@@ -1,74 +0,0 @@
-/*
- * Copyright (c) 2022, stelar7 <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#pragma once
-
-#include <AK/ByteBuffer.h>
-
-namespace Crypto::Curves {
-
-struct Ed25519Point {
- u32 x[8] {};
- u32 y[8] {};
- u32 z[8] {};
- u32 t[8] {};
-};
-
-class Ed25519 {
-public:
- static constexpr Ed25519Point BASE_POINT = {
- { 0x8F25D51A, 0xC9562D60, 0x9525A7B2, 0x692CC760, 0xFDD6DC5C, 0xC0A4E231, 0xCD6E53FE, 0x216936D3 },
- { 0x66666658, 0x66666666, 0x66666666, 0x66666666, 0x66666666, 0x66666666, 0x66666666, 0x66666666 },
- { 0x00000001, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000 },
- { 0xA5B7DDA3, 0x6DDE8AB3, 0x775152F5, 0x20F09F80, 0x64ABE37D, 0x66EA4E8E, 0xD78B7665, 0x67875F0F }
- };
-
- size_t key_size() { return 32; }
- size_t signature_size() { return 64; }
- ErrorOr<ByteBuffer> generate_private_key();
- ErrorOr<ByteBuffer> generate_public_key(ReadonlyBytes private_key);
-
- ErrorOr<ByteBuffer> sign(ReadonlyBytes public_key, ReadonlyBytes private_key, ReadonlyBytes message);
- bool verify(ReadonlyBytes public_key, ReadonlyBytes signature, ReadonlyBytes message);
-
-private:
- void encode_point(Ed25519Point* point, u8* data);
- u32 decode_point(Ed25519Point* point, u8 const* data);
-
- void point_add(Ed25519Point* result, Ed25519Point const* p, Ed25519Point const* q);
- void point_double(Ed25519Point* result, Ed25519Point const* point);
- void point_multiply_scalar(Ed25519Point* result, u8 const* scalar, Ed25519Point const* point);
-
- void barrett_reduce(u8* result, u8 const* input);
-
- void add(u8* result, u8 const* a, u8 const* b, u8 n);
- u8 subtract(u8* result, u8 const* a, u8 const* b, u8 n);
- void multiply(u8* result_low, u8* result_high, u8 const* a, u8 const* b, u8 n);
-
- void select(u8* result, u8 const* a, u8 const* b, u8 c, u8 n);
- u8 compare(u8 const* a, u8 const* b, u8 n);
- void copy(u8* a, u8 const* b, u32 n);
-
- u8 k[64] {};
- u8 p[32] {};
- u8 r[32] {};
- u8 s[32] {};
- Ed25519Point ka {};
- Ed25519Point rb {};
- Ed25519Point sb {};
- Ed25519Point u {};
- Ed25519Point v {};
- u32 a[8] {};
- u32 b[8] {};
- u32 c[8] {};
- u32 d[8] {};
- u32 e[8] {};
- u32 f[8] {};
- u32 g[8] {};
- u32 h[8] {};
-};
-
-}
diff --git a/Libraries/LibCrypto/Curves/Ed448.cpp b/Libraries/LibCrypto/Curves/Ed448.cpp
deleted file mode 100644
index 1129bf5cff6d..000000000000
--- a/Libraries/LibCrypto/Curves/Ed448.cpp
+++ /dev/null
@@ -1,82 +0,0 @@
-/*
- * Copyright (c) 2024, Altomani Gianluca <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#include <AK/ScopeGuard.h>
-#include <LibCrypto/Curves/Ed448.h>
-#include <LibCrypto/OpenSSL.h>
-
-#include <openssl/core_names.h>
-#include <openssl/evp.h>
-
-namespace Crypto::Curves {
-
-ErrorOr<ByteBuffer> Ed448::generate_private_key()
-{
- auto key = TRY(OpenSSL_PKEY::wrap(EVP_PKEY_Q_keygen(nullptr, nullptr, "ED448")));
-
- size_t key_size = EVP_PKEY_get_size(key.ptr());
- auto buf = TRY(ByteBuffer::create_uninitialized(key_size));
-
- OPENSSL_TRY(EVP_PKEY_get_raw_private_key(key.ptr(), buf.data(), &key_size));
-
- return buf.slice(0, key_size);
-}
-
-ErrorOr<ByteBuffer> Ed448::generate_public_key(ReadonlyBytes private_key)
-{
- auto key = TRY(OpenSSL_PKEY::wrap(EVP_PKEY_new_raw_private_key(EVP_PKEY_ED448, nullptr, private_key.data(), private_key.size())));
-
- size_t key_size = EVP_PKEY_get_size(key.ptr());
- auto buf = TRY(ByteBuffer::create_uninitialized(key_size));
-
- OPENSSL_TRY(EVP_PKEY_get_raw_public_key(key.ptr(), buf.data(), &key_size));
-
- return buf.slice(0, key_size);
-}
-
-ErrorOr<ByteBuffer> Ed448::sign(ReadonlyBytes private_key, ReadonlyBytes message, ReadonlyBytes context)
-{
- auto key = TRY(OpenSSL_PKEY::wrap(EVP_PKEY_new_raw_private_key_ex(nullptr, "ED448", nullptr, private_key.data(), private_key.size())));
-
- auto ctx = TRY(OpenSSL_MD_CTX::create());
-
- OSSL_PARAM params[] = {
- OSSL_PARAM_octet_string(OSSL_SIGNATURE_PARAM_CONTEXT_STRING, const_cast<u8*>(context.data()), context.size()),
- OSSL_PARAM_END
- };
-
- OPENSSL_TRY(EVP_DigestSignInit_ex(ctx.ptr(), nullptr, nullptr, nullptr, nullptr, key.ptr(), params));
-
- size_t sig_len = signature_size();
- auto sig = TRY(ByteBuffer::create_uninitialized(sig_len));
-
- OPENSSL_TRY(EVP_DigestSign(ctx.ptr(), sig.data(), &sig_len, message.data(), message.size()));
-
- return sig.slice(0, sig_len);
-}
-
-ErrorOr<bool> Ed448::verify(ReadonlyBytes public_key, ReadonlyBytes signature, ReadonlyBytes message, ReadonlyBytes context)
-{
- auto key = TRY(OpenSSL_PKEY::wrap(EVP_PKEY_new_raw_public_key_ex(nullptr, "ED448", nullptr, public_key.data(), public_key.size())));
-
- auto ctx = TRY(OpenSSL_MD_CTX::create());
-
- OSSL_PARAM params[] = {
- OSSL_PARAM_octet_string(OSSL_SIGNATURE_PARAM_CONTEXT_STRING, const_cast<u8*>(context.data()), context.size()),
- OSSL_PARAM_END
- };
-
- OPENSSL_TRY(EVP_DigestVerifyInit_ex(ctx.ptr(), nullptr, nullptr, nullptr, nullptr, key.ptr(), params));
-
- auto res = EVP_DigestVerify(ctx.ptr(), signature.data(), signature.size(), message.data(), message.size());
- if (res == 1)
- return true;
- if (res == 0)
- return false;
- OPENSSL_TRY(res);
- VERIFY_NOT_REACHED();
-}
-}
diff --git a/Libraries/LibCrypto/Curves/Ed448.h b/Libraries/LibCrypto/Curves/Ed448.h
deleted file mode 100644
index bba9a0456d92..000000000000
--- a/Libraries/LibCrypto/Curves/Ed448.h
+++ /dev/null
@@ -1,24 +0,0 @@
-/*
- * Copyright (c) 2024, Altomani Gianluca <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#pragma once
-
-#include <AK/ByteBuffer.h>
-
-namespace Crypto::Curves {
-
-class Ed448 {
-public:
- constexpr size_t key_size() const { return 57; }
- constexpr size_t signature_size() const { return 114; }
- ErrorOr<ByteBuffer> generate_private_key();
- ErrorOr<ByteBuffer> generate_public_key(ReadonlyBytes private_key);
-
- ErrorOr<ByteBuffer> sign(ReadonlyBytes private_key, ReadonlyBytes message, ReadonlyBytes context = {});
- ErrorOr<bool> verify(ReadonlyBytes public_key, ReadonlyBytes signature, ReadonlyBytes message, ReadonlyBytes context = {});
-};
-
-}
diff --git a/Libraries/LibCrypto/Curves/EdwardsCurve.cpp b/Libraries/LibCrypto/Curves/EdwardsCurve.cpp
new file mode 100644
index 000000000000..662ceed19e18
--- /dev/null
+++ b/Libraries/LibCrypto/Curves/EdwardsCurve.cpp
@@ -0,0 +1,113 @@
+/*
+ * Copyright (c) 2025, Altomani Gianluca <[email protected]>
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#include <AK/ScopeGuard.h>
+#include <LibCrypto/Curves/EdwardsCurve.h>
+#include <LibCrypto/OpenSSL.h>
+
+#include <openssl/core_names.h>
+#include <openssl/evp.h>
+
+namespace Crypto::Curves {
+
+ErrorOr<ByteBuffer> EdwardsCurve::generate_private_key()
+{
+ auto key = TRY(OpenSSL_PKEY::wrap(EVP_PKEY_Q_keygen(nullptr, nullptr, m_curve_name)));
+
+ size_t key_size = 0;
+ OPENSSL_TRY(EVP_PKEY_get_raw_private_key(key.ptr(), nullptr, &key_size));
+
+ auto buf = TRY(ByteBuffer::create_uninitialized(key_size));
+ OPENSSL_TRY(EVP_PKEY_get_raw_private_key(key.ptr(), buf.data(), &key_size));
+
+ return buf;
+}
+
+ErrorOr<ByteBuffer> EdwardsCurve::generate_public_key(ReadonlyBytes private_key)
+{
+ auto key = TRY(OpenSSL_PKEY::wrap(EVP_PKEY_new_raw_private_key_ex(nullptr, m_curve_name, nullptr, private_key.data(), private_key.size())));
+
+ size_t key_size = 0;
+ OPENSSL_TRY(EVP_PKEY_get_raw_public_key(key.ptr(), nullptr, &key_size));
+
+ auto buf = TRY(ByteBuffer::create_uninitialized(key_size));
+ OPENSSL_TRY(EVP_PKEY_get_raw_public_key(key.ptr(), buf.data(), &key_size));
+
+ return buf;
+}
+
+ErrorOr<ByteBuffer> SignatureEdwardsCurve::sign(ReadonlyBytes private_key, ReadonlyBytes message, ReadonlyBytes context)
+{
+ auto key = TRY(OpenSSL_PKEY::wrap(EVP_PKEY_new_raw_private_key_ex(nullptr, m_curve_name, nullptr, private_key.data(), private_key.size())));
+
+ auto ctx = TRY(OpenSSL_MD_CTX::create());
+
+ OSSL_PARAM params[2] = {
+ OSSL_PARAM_END,
+ OSSL_PARAM_END
+ };
+
+ if (!context.is_null()) {
+ params[0] = OSSL_PARAM_octet_string(OSSL_SIGNATURE_PARAM_CONTEXT_STRING, const_cast<u8*>(context.data()), context.size());
+ }
+
+ OPENSSL_TRY(EVP_DigestSignInit_ex(ctx.ptr(), nullptr, nullptr, nullptr, nullptr, key.ptr(), params));
+
+ size_t sig_len = 0;
+ OPENSSL_TRY(EVP_DigestSign(ctx.ptr(), nullptr, &sig_len, message.data(), message.size()));
+
+ auto sig = TRY(ByteBuffer::create_uninitialized(sig_len));
+ OPENSSL_TRY(EVP_DigestSign(ctx.ptr(), sig.data(), &sig_len, message.data(), message.size()));
+
+ return sig;
+}
+
+ErrorOr<bool> SignatureEdwardsCurve::verify(ReadonlyBytes public_key, ReadonlyBytes signature, ReadonlyBytes message, ReadonlyBytes context)
+{
+ auto key = TRY(OpenSSL_PKEY::wrap(EVP_PKEY_new_raw_public_key_ex(nullptr, m_curve_name, nullptr, public_key.data(), public_key.size())));
+
+ auto ctx = TRY(OpenSSL_MD_CTX::create());
+
+ OSSL_PARAM params[2] = {
+ OSSL_PARAM_END,
+ OSSL_PARAM_END
+ };
+
+ if (!context.is_null()) {
+ params[0] = OSSL_PARAM_octet_string(OSSL_SIGNATURE_PARAM_CONTEXT_STRING, const_cast<u8*>(context.data()), context.size());
+ }
+
+ OPENSSL_TRY(EVP_DigestVerifyInit_ex(ctx.ptr(), nullptr, nullptr, nullptr, nullptr, key.ptr(), params));
+
+ auto res = EVP_DigestVerify(ctx.ptr(), signature.data(), signature.size(), message.data(), message.size());
+ if (res == 1)
+ return true;
+ if (res == 0)
+ return false;
+ OPENSSL_TRY(res);
+ VERIFY_NOT_REACHED();
+}
+
+ErrorOr<ByteBuffer> ExchangeEdwardsCurve::compute_coordinate(ReadonlyBytes private_key, ReadonlyBytes public_key)
+{
+ auto key = TRY(OpenSSL_PKEY::wrap(EVP_PKEY_new_raw_private_key_ex(nullptr, m_curve_name, nullptr, private_key.data(), private_key.size())));
+ auto peerkey = TRY(OpenSSL_PKEY::wrap(EVP_PKEY_new_raw_public_key_ex(nullptr, m_curve_name, nullptr, public_key.data(), public_key.size())));
+
+ auto ctx = TRY(OpenSSL_PKEY_CTX::wrap(EVP_PKEY_CTX_new(key.ptr(), nullptr)));
+
+ OPENSSL_TRY(EVP_PKEY_derive_init(ctx.ptr()));
+ OPENSSL_TRY(EVP_PKEY_derive_set_peer(ctx.ptr(), peerkey.ptr()));
+
+ size_t key_size = 0;
+ OPENSSL_TRY(EVP_PKEY_derive(ctx.ptr(), nullptr, &key_size));
+
+ auto buf = TRY(ByteBuffer::create_uninitialized(key_size));
+ OPENSSL_TRY(EVP_PKEY_derive(ctx.ptr(), buf.data(), &key_size));
+
+ return buf;
+}
+
+}
diff --git a/Libraries/LibCrypto/Curves/EdwardsCurve.h b/Libraries/LibCrypto/Curves/EdwardsCurve.h
new file mode 100644
index 000000000000..2829e35646aa
--- /dev/null
+++ b/Libraries/LibCrypto/Curves/EdwardsCurve.h
@@ -0,0 +1,83 @@
+/*
+ * Copyright (c) 2025, Altomani Gianluca <[email protected]>
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#pragma once
+
+#include <AK/ByteBuffer.h>
+#include <LibCrypto/OpenSSL.h>
+
+namespace Crypto::Curves {
+
+class EdwardsCurve {
+public:
+ ErrorOr<ByteBuffer> generate_private_key();
+ ErrorOr<ByteBuffer> generate_public_key(ReadonlyBytes private_key);
+
+protected:
+ EdwardsCurve(char const* curve_name)
+ : m_curve_name(curve_name)
+ {
+ }
+
+ char const* m_curve_name;
+};
+
+class SignatureEdwardsCurve : public EdwardsCurve {
+public:
+ ErrorOr<ByteBuffer> sign(ReadonlyBytes private_key, ReadonlyBytes message, ReadonlyBytes context = {});
+ ErrorOr<bool> verify(ReadonlyBytes public_key, ReadonlyBytes signature, ReadonlyBytes message, ReadonlyBytes context = {});
+
+protected:
+ explicit SignatureEdwardsCurve(char const* curve_name)
+ : EdwardsCurve(curve_name)
+ {
+ }
+};
+
+class ExchangeEdwardsCurve : public EdwardsCurve {
+public:
+ ErrorOr<ByteBuffer> compute_coordinate(ReadonlyBytes private_key, ReadonlyBytes public_key);
+
+protected:
+ explicit ExchangeEdwardsCurve(char const* curve_name)
+ : EdwardsCurve(curve_name)
+ {
+ }
+};
+
+class Ed448 : public SignatureEdwardsCurve {
+public:
+ Ed448()
+ : SignatureEdwardsCurve("ED448")
+ {
+ }
+};
+
+class X448 : public ExchangeEdwardsCurve {
+public:
+ X448()
+ : ExchangeEdwardsCurve("X448")
+ {
+ }
+};
+
+class Ed25519 : public SignatureEdwardsCurve {
+public:
+ Ed25519()
+ : SignatureEdwardsCurve("ED25519")
+ {
+ }
+};
+
+class X25519 : public ExchangeEdwardsCurve {
+public:
+ X25519()
+ : ExchangeEdwardsCurve("X25519")
+ {
+ }
+};
+
+}
diff --git a/Libraries/LibCrypto/Curves/X25519.cpp b/Libraries/LibCrypto/Curves/X25519.cpp
deleted file mode 100644
index abac457b5cae..000000000000
--- a/Libraries/LibCrypto/Curves/X25519.cpp
+++ /dev/null
@@ -1,129 +0,0 @@
-/*
- * Copyright (c) 2022, stelar7 <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#include <AK/ByteReader.h>
-#include <AK/Random.h>
-#include <LibCrypto/Curves/Curve25519.h>
-#include <LibCrypto/Curves/X25519.h>
-#include <LibCrypto/SecureRandom.h>
-
-namespace Crypto::Curves {
-
-static constexpr u8 BITS = 255;
-static constexpr u8 BYTES = 32;
-static constexpr u8 WORDS = 8;
-static constexpr u32 A24 = 121666;
-
-static void conditional_swap(u32* first, u32* second, u32 condition)
-{
- u32 mask = ~condition + 1;
- for (auto i = 0; i < WORDS; i++) {
- u32 temp = mask & (first[i] ^ second[i]);
- first[i] ^= temp;
- second[i] ^= temp;
- }
-}
-
-ErrorOr<ByteBuffer> X25519::generate_private_key()
-{
- auto buffer = TRY(ByteBuffer::create_uninitialized(BYTES));
- fill_with_secure_random(buffer);
- return buffer;
-}
-
-ErrorOr<ByteBuffer> X25519::generate_public_key(ReadonlyBytes a)
-{
- u8 generator[BYTES] { 9 };
- return compute_coordinate(a, { generator, BYTES });
-}
-
-// https://datatracker.ietf.org/doc/html/rfc7748#section-5
-ErrorOr<ByteBuffer> X25519::compute_coordinate(ReadonlyBytes input_k, ReadonlyBytes input_u)
-{
- u32 k[WORDS] {};
- u32 u[WORDS] {};
- u32 x1[WORDS] {};
- u32 x2[WORDS] {};
- u32 z1[WORDS] {};
- u32 z2[WORDS] {};
- u32 t1[WORDS] {};
- u32 t2[WORDS] {};
-
- // Copy input to internal state
- Curve25519::import_state(k, input_k.data());
-
- // Set the three least significant bits of the first byte and the most significant bit of the last to zero,
- // set the second most significant bit of the last byte to 1
- k[0] &= 0xFFFFFFF8;
- k[7] &= 0x7FFFFFFF;
- k[7] |= 0x40000000;
-
- // Copy coordinate to internal state
- Curve25519::import_state(u, input_u.data());
- // mask the most significant bit in the final byte.
- u[7] &= 0x7FFFFFFF;
-
- // Implementations MUST accept non-canonical values and process them as
- // if they had been reduced modulo the field prime.
- Curve25519::modular_reduce(u, u);
-
- Curve25519::set(x1, 1);
- Curve25519::set(z1, 0);
- Curve25519::copy(x2, u);
- Curve25519::set(z2, 1);
-
- // Montgomery ladder
- u32 swap = 0;
- for (auto i = BITS - 1; i >= 0; i--) {
- u32 b = (k[i / BYTES] >> (i % BYTES)) & 1;
-
- conditional_swap(x1, x2, swap ^ b);
- conditional_swap(z1, z2, swap ^ b);
-
- swap = b;
-
- Curve25519::modular_add(t1, x2, z2);
- Curve25519::modular_subtract(x2, x2, z2);
- Curve25519::modular_add(z2, x1, z1);
- Curve25519::modular_subtract(x1, x1, z1);
- Curve25519::modular_multiply(t1, t1, x1);
- Curve25519::modular_multiply(x2, x2, z2);
- Curve25519::modular_square(z2, z2);
- Curve25519::modular_square(x1, x1);
- Curve25519::modular_subtract(t2, z2, x1);
- Curve25519::modular_multiply_single(z1, t2, A24);
- Curve25519::modular_add(z1, z1, x1);
- Curve25519::modular_multiply(z1, z1, t2);
- Curve25519::modular_multiply(x1, x1, z2);
- Curve25519::modular_subtract(z2, t1, x2);
- Curve25519::modular_square(z2, z2);
- Curve25519::modular_multiply(z2, z2, u);
- Curve25519::modular_add(x2, x2, t1);
- Curve25519::modular_square(x2, x2);
- }
-
- conditional_swap(x1, x2, swap);
- conditional_swap(z1, z2, swap);
-
- // Retrieve affine representation
- Curve25519::modular_multiply_inverse(u, z1);
- Curve25519::modular_multiply(u, u, x1);
-
- // Encode state for export
- auto buffer = TRY(ByteBuffer::create_uninitialized(BYTES));
- Curve25519::export_state(u, buffer.data());
-
- return buffer;
-}
-
-ErrorOr<ByteBuffer> X25519::derive_premaster_key(ReadonlyBytes shared_point)
-{
- VERIFY(shared_point.size() == BYTES);
- ByteBuffer premaster_key = TRY(ByteBuffer::copy(shared_point));
- return premaster_key;
-}
-
-}
diff --git a/Libraries/LibCrypto/Curves/X25519.h b/Libraries/LibCrypto/Curves/X25519.h
deleted file mode 100644
index 6fd62ec274dc..000000000000
--- a/Libraries/LibCrypto/Curves/X25519.h
+++ /dev/null
@@ -1,22 +0,0 @@
-/*
- * Copyright (c) 2022, stelar7 <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#pragma once
-
-#include <AK/ByteBuffer.h>
-
-namespace Crypto::Curves {
-
-class X25519 {
-public:
- size_t key_size() { return 32; }
- ErrorOr<ByteBuffer> generate_private_key();
- ErrorOr<ByteBuffer> generate_public_key(ReadonlyBytes a);
- ErrorOr<ByteBuffer> compute_coordinate(ReadonlyBytes a, ReadonlyBytes b);
- ErrorOr<ByteBuffer> derive_premaster_key(ReadonlyBytes shared_point);
-};
-
-}
diff --git a/Libraries/LibCrypto/Curves/X448.cpp b/Libraries/LibCrypto/Curves/X448.cpp
deleted file mode 100644
index 0e4cf4df187f..000000000000
--- a/Libraries/LibCrypto/Curves/X448.cpp
+++ /dev/null
@@ -1,384 +0,0 @@
-/*
- * Copyright (c) 2022, stelar7 <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#include <AK/ByteReader.h>
-#include <AK/Endian.h>
-#include <AK/Random.h>
-#include <LibCrypto/Curves/X448.h>
-#include <LibCrypto/SecureRandom.h>
-
-namespace Crypto::Curves {
-
-static constexpr u16 BITS = 448;
-static constexpr u8 BYTES = 56;
-static constexpr u8 WORDS = 14;
-static constexpr u32 A24 = 39082;
-
-static void import_state(u32* state, ReadonlyBytes data)
-{
- for (auto i = 0; i < WORDS; i++) {
- u32 value = ByteReader::load32(data.offset_pointer(sizeof(u32) * i));
- state[i] = AK::convert_between_host_and_little_endian(value);
- }
-}
-
-static ErrorOr<ByteBuffer> export_state(u32* data)
-{
- auto buffer = TRY(ByteBuffer::create_uninitialized(BYTES));
-
- for (auto i = 0; i < WORDS; i++) {
- u32 value = AK::convert_between_host_and_little_endian(data[i]);
- ByteReader::store(buffer.offset_pointer(sizeof(u32) * i), value);
- }
-
- return buffer;
-}
-
-static void select(u32* state, u32* a, u32* b, u32 condition)
-{
- // If B < (2^448 - 2^224 + 1) then R = B, else R = A
- u32 mask = condition - 1;
-
- for (auto i = 0; i < WORDS; i++) {
- state[i] = (a[i] & mask) | (b[i] & ~mask);
- }
-}
-
-static void set(u32* state, u32 value)
-{
- state[0] = value;
-
- for (auto i = 1; i < WORDS; i++) {
- state[i] = 0;
- }
-}
-
-static void copy(u32* state, u32* value)
-{
- for (auto i = 0; i < WORDS; i++) {
- state[i] = value[i];
- }
-}
-
-static void conditional_swap(u32* first, u32* second, u32 condition)
-{
- u32 mask = ~condition + 1;
- for (auto i = 0; i < WORDS; i++) {
- u32 temp = mask & (first[i] ^ second[i]);
- first[i] ^= temp;
- second[i] ^= temp;
- }
-}
-
-static void modular_reduce(u32* state, u32* data, u32 a_high)
-{
- u64 temp = 1;
- u32 other[WORDS];
-
- // Compute B = A - (2^448 - 2^224 - 1)
- for (auto i = 0; i < WORDS / 2; i++) {
- temp += data[i];
- other[i] = temp & 0xFFFFFFFF;
- temp >>= 32;
- }
-
- temp += 1;
-
- for (auto i = 7; i < WORDS; i++) {
- temp += data[i];
- other[i] = temp & 0xFFFFFFFF;
- temp >>= 32;
- }
-
- auto condition = (a_high + (u32)temp - 1) & 1;
- select(state, other, data, condition);
-}
-
-static void modular_multiply_single(u32* state, u32* first, u32 second)
-{
- // Compute R = (A * B) mod p
- u64 temp = 0;
- u64 carry = 0;
- u32 output[WORDS];
-
- for (auto i = 0; i < WORDS; i++) {
- temp += (u64)first[i] * second;
- output[i] = temp & 0xFFFFFFFF;
- temp >>= 32;
- }
-
- // Fast modular reduction
- carry = temp;
- for (auto i = 0; i < WORDS / 2; i++) {
- temp += output[i];
- output[i] = temp & 0xFFFFFFFF;
- temp >>= 32;
- }
-
- temp += carry;
- for (auto i = WORDS / 2; i < WORDS; i++) {
- temp += output[i];
- output[i] = temp & 0xFFFFFFFF;
- temp >>= 32;
- }
-
- modular_reduce(state, output, (u32)temp);
-}
-
-static void modular_multiply(u32* state, u32* first, u32* second)
-{
- // Compute R = (A * B) mod p
-
- u64 temp = 0;
- u64 carry = 0;
- u32 output[WORDS * 2];
-
- // Comba's method
- for (auto i = 0; i < WORDS * 2; i++) {
- if (i < 14) {
- for (auto j = 0; j <= i; j++) {
- temp += (u64)first[j] * second[i - j];
- carry += temp >> 32;
- temp &= 0xFFFFFFFF;
- }
- } else {
- for (auto j = i - 13; j < WORDS; j++) {
- temp += (u64)first[j] * second[i - j];
- carry += temp >> 32;
- temp &= 0xFFFFFFFF;
- }
- }
-
- output[i] = temp & 0xFFFFFFFF;
- temp = carry & 0xFFFFFFFF;
- carry >>= 32;
- }
-
- // Fast modular reduction (first pass)
- temp = 0;
- for (auto i = 0; i < WORDS / 2; i++) {
- temp += output[i];
- temp += output[i + 14];
- temp += output[i + 21];
- output[i] = temp & 0xFFFFFFFF;
- temp >>= 32;
- }
-
- for (auto i = WORDS / 2; i < WORDS; i++) {
- temp += output[i];
- temp += output[i + 7];
- temp += output[i + 14];
- temp += output[i + 14];
- output[i] = temp & 0xFFFFFFFF;
- temp >>= 32;
- }
-
- // Fast modular reduction (second pass)
- carry = temp;
- for (auto i = 0; i < WORDS / 2; i++) {
- temp += output[i];
- output[i] = temp & 0xFFFFFFFF;
- temp >>= 32;
- }
-
- temp += carry;
- for (auto i = WORDS / 2; i < WORDS; i++) {
- temp += output[i];
- output[i] = temp & 0xFFFFFFFF;
- temp >>= 32;
- }
-
- modular_reduce(state, output, (u32)temp);
-}
-
-static void modular_square(u32* state, u32* value)
-{
- // Compute R = (A ^ 2) mod p
- modular_multiply(state, value, value);
-}
-
-static void modular_add(u32* state, u32* first, u32* second)
-{
- u64 temp = 0;
-
- // Compute R = A + B
- for (auto i = 0; i < WORDS; i++) {
- temp += first[i];
- temp += second[i];
- state[i] = temp & 0xFFFFFFFF;
- temp >>= 32;
- }
-
- modular_reduce(state, state, (u32)temp);
-}
-
-static void modular_subtract(u32* state, u32* first, u32* second)
-{
- i64 temp = -1;
-
- // Compute R = A + (2^448 - 2^224 - 1) - B
- for (auto i = 0; i < 7; i++) {
- temp += first[i];
- temp -= second[i];
- state[i] = temp & 0xFFFFFFFF;
- temp >>= 32;
- }
-
- temp -= 1;
-
- for (auto i = 7; i < 14; i++) {
- temp += first[i];
- temp -= second[i];
- state[i] = temp & 0xFFFFFFFF;
- temp >>= 32;
- }
-
- temp += 1;
-
- modular_reduce(state, state, (u32)temp);
-}
-
-static void to_power_of_2n(u32* state, u32* value, u8 n)
-{
- // Compute R = (A ^ (2^n)) mod p
- modular_square(state, value);
- for (auto i = 1; i < n; i++) {
- modular_square(state, state);
- }
-}
-
-static void modular_multiply_inverse(u32* state, u32* value)
-{
- // Compute R = A^-1 mod p
- u32 u[WORDS];
- u32 v[WORDS];
-
- modular_square(u, value);
- modular_multiply(u, u, value);
- modular_square(u, u);
- modular_multiply(v, u, value);
- to_power_of_2n(u, v, 3);
- modular_multiply(v, u, v);
- to_power_of_2n(u, v, 6);
- modular_multiply(u, u, v);
- modular_square(u, u);
- modular_multiply(v, u, value);
- to_power_of_2n(u, v, 13);
- modular_multiply(u, u, v);
- modular_square(u, u);
- modular_multiply(v, u, value);
- to_power_of_2n(u, v, 27);
- modular_multiply(u, u, v);
- modular_square(u, u);
- modular_multiply(v, u, value);
- to_power_of_2n(u, v, 55);
- modular_multiply(u, u, v);
- modular_square(u, u);
- modular_multiply(v, u, value);
- to_power_of_2n(u, v, 111);
- modular_multiply(v, u, v);
- modular_square(u, v);
- modular_multiply(u, u, value);
- to_power_of_2n(u, u, 223);
- modular_multiply(u, u, v);
- modular_square(u, u);
- modular_square(u, u);
- modular_multiply(state, u, value);
-}
-
-ErrorOr<ByteBuffer> X448::generate_private_key()
-{
- auto buffer = TRY(ByteBuffer::create_uninitialized(BYTES));
- fill_with_secure_random(buffer);
- return buffer;
-}
-
-ErrorOr<ByteBuffer> X448::generate_public_key(ReadonlyBytes a)
-{
- u8 generator[BYTES] { 5 };
- return compute_coordinate(a, { generator, BYTES });
-}
-
-// https://datatracker.ietf.org/doc/html/rfc7748#section-5
-ErrorOr<ByteBuffer> X448::compute_coordinate(ReadonlyBytes input_k, ReadonlyBytes input_u)
-{
- u32 k[WORDS] {};
- u32 u[WORDS] {};
- u32 x1[WORDS] {};
- u32 x2[WORDS] {};
- u32 z1[WORDS] {};
- u32 z2[WORDS] {};
- u32 t1[WORDS] {};
- u32 t2[WORDS] {};
-
- // Copy input to internal state
- import_state(k, input_k);
-
- // Set the two least significant bits of the first byte to 0, and the most significant bit of the last byte to 1
- k[0] &= 0xFFFFFFFC;
- k[13] |= 0x80000000;
-
- // Copy coordinate to internal state
- import_state(u, input_u);
-
- // Implementations MUST accept non-canonical values and process them as
- // if they had been reduced modulo the field prime.
- modular_reduce(u, u, 0);
-
- set(x1, 1);
- set(z1, 0);
- copy(x2, u);
- set(z2, 1);
-
- // Montgomery ladder
- u32 swap = 0;
- for (auto i = BITS - 1; i >= 0; i--) {
- u32 b = (k[i / 32] >> (i % 32)) & 1;
-
- conditional_swap(x1, x2, swap ^ b);
- conditional_swap(z1, z2, swap ^ b);
-
- swap = b;
-
- modular_add(t1, x2, z2);
- modular_subtract(x2, x2, z2);
- modular_add(z2, x1, z1);
- modular_subtract(x1, x1, z1);
- modular_multiply(t1, t1, x1);
- modular_multiply(x2, x2, z2);
- modular_square(z2, z2);
- modular_square(x1, x1);
- modular_subtract(t2, z2, x1);
- modular_multiply_single(z1, t2, A24);
- modular_add(z1, z1, x1);
- modular_multiply(z1, z1, t2);
- modular_multiply(x1, x1, z2);
- modular_subtract(z2, t1, x2);
- modular_square(z2, z2);
- modular_multiply(z2, z2, u);
- modular_add(x2, x2, t1);
- modular_square(x2, x2);
- }
-
- conditional_swap(x1, x2, swap);
- conditional_swap(z1, z2, swap);
-
- // Retrieve affine representation
- modular_multiply_inverse(u, z1);
- modular_multiply(u, u, x1);
-
- // Encode state for export
- return export_state(u);
-}
-
-ErrorOr<ByteBuffer> X448::derive_premaster_key(ReadonlyBytes shared_point)
-{
- VERIFY(shared_point.size() == BYTES);
- ByteBuffer premaster_key = TRY(ByteBuffer::copy(shared_point));
- return premaster_key;
-}
-
-}
diff --git a/Libraries/LibCrypto/Curves/X448.h b/Libraries/LibCrypto/Curves/X448.h
deleted file mode 100644
index 9dffca25881d..000000000000
--- a/Libraries/LibCrypto/Curves/X448.h
+++ /dev/null
@@ -1,22 +0,0 @@
-/*
- * Copyright (c) 2022, stelar7 <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#pragma once
-
-#include <AK/ByteBuffer.h>
-
-namespace Crypto::Curves {
-
-class X448 {
-public:
- size_t key_size() { return 56; }
- ErrorOr<ByteBuffer> generate_private_key();
- ErrorOr<ByteBuffer> generate_public_key(ReadonlyBytes a);
- ErrorOr<ByteBuffer> compute_coordinate(ReadonlyBytes a, ReadonlyBytes b);
- ErrorOr<ByteBuffer> derive_premaster_key(ReadonlyBytes shared_point);
-};
-
-}
diff --git a/Libraries/LibWeb/Crypto/CryptoAlgorithms.cpp b/Libraries/LibWeb/Crypto/CryptoAlgorithms.cpp
index 11f223f1fcd1..de8ea53c89f6 100644
--- a/Libraries/LibWeb/Crypto/CryptoAlgorithms.cpp
+++ b/Libraries/LibWeb/Crypto/CryptoAlgorithms.cpp
@@ -3,7 +3,7 @@
* Copyright (c) 2024, stelar7 <[email protected]>
* Copyright (c) 2024, Jelle Raaijmakers <[email protected]>
* Copyright (c) 2024, Andreas Kling <[email protected]>
- * Copyright (c) 2024, Altomani Gianluca <[email protected]>
+ * Copyright (c) 2024-2025, Altomani Gianluca <[email protected]>
*
* SPDX-License-Identifier: BSD-2-Clause
*/
@@ -17,11 +17,8 @@
#include <LibCrypto/Authentication/HMAC.h>
#include <LibCrypto/Certificate/Certificate.h>
#include <LibCrypto/Cipher/AES.h>
-#include <LibCrypto/Curves/Ed25519.h>
-#include <LibCrypto/Curves/Ed448.h>
+#include <LibCrypto/Curves/EdwardsCurve.h>
#include <LibCrypto/Curves/SECPxxxr1.h>
-#include <LibCrypto/Curves/X25519.h>
-#include <LibCrypto/Curves/X448.h>
#include <LibCrypto/Hash/HKDF.h>
#include <LibCrypto/Hash/HashManager.h>
#include <LibCrypto/Hash/PBKDF2.h>
@@ -6091,7 +6088,7 @@ WebIDL::ExceptionOr<GC::Ref<JS::ArrayBuffer>> ED25519::sign([[maybe_unused]] Alg
return WebIDL::OperationError::create(realm, "Failed to generate public key"_string);
auto public_key = maybe_public_key.release_value();
- auto maybe_signature = curve.sign(public_key, private_key, message);
+ auto maybe_signature = curve.sign(private_key, message);
if (maybe_signature.is_error())
return WebIDL::OperationError::create(realm, "Failed to sign message"_string);
auto signature = maybe_signature.release_value();
@@ -6122,10 +6119,14 @@ WebIDL::ExceptionOr<JS::Value> ED25519::verify([[maybe_unused]] AlgorithmParams
// 9. Let result be a boolean with the value true if the signature is valid and the value false otherwise.
::Crypto::Curves::Ed25519 curve;
- auto result = curve.verify(public_key, signature, message);
+ auto maybe_verified = curve.verify(key->handle().get<ByteBuffer>(), signature, message);
+ if (maybe_verified.is_error()) {
+ auto error_message = MUST(String::from_utf8(maybe_verified.error().string_literal()));
+ return WebIDL::OperationError::create(realm, error_message);
+ }
// 10. Return result.
- return JS::Value(result);
+ return maybe_verified.release_value();
}
// https://wicg.github.io/webcrypto-secure-curves/#ed448-operations
diff --git a/Tests/LibCrypto/TestCurves.cpp b/Tests/LibCrypto/TestCurves.cpp
index 356cb4416a11..7dd36665d8e2 100644
--- a/Tests/LibCrypto/TestCurves.cpp
+++ b/Tests/LibCrypto/TestCurves.cpp
@@ -5,9 +5,8 @@
*/
#include <AK/ByteBuffer.h>
+#include <LibCrypto/Curves/EdwardsCurve.h>
#include <LibCrypto/Curves/SECPxxxr1.h>
-#include <LibCrypto/Curves/X25519.h>
-#include <LibCrypto/Curves/X448.h>
#include <LibTest/TestCase.h>
TEST_CASE(test_x25519)
diff --git a/Tests/LibCrypto/TestEd25519.cpp b/Tests/LibCrypto/TestEd25519.cpp
index 1b7751061b97..553588b29f66 100644
--- a/Tests/LibCrypto/TestEd25519.cpp
+++ b/Tests/LibCrypto/TestEd25519.cpp
@@ -5,7 +5,7 @@
*/
#include <AK/ByteBuffer.h>
-#include <LibCrypto/Curves/Ed25519.h>
+#include <LibCrypto/Curves/EdwardsCurve.h>
#include <LibTest/TestCase.h>
// https://datatracker.ietf.org/doc/html/rfc8032#section-7.1
@@ -45,9 +45,9 @@ TEST_CASE(TEST_1)
Crypto::Curves::Ed25519 curve;
- auto generated_signature = MUST(curve.sign(public_key, private_key, message));
+ auto generated_signature = TRY_OR_FAIL(curve.sign(private_key, message));
EXPECT_EQ(generated_signature, expected_signature);
- EXPECT_EQ(true, curve.verify(public_key, expected_signature, message));
+ EXPECT(TRY_OR_FAIL(curve.verify(public_key, expected_signature, message)));
}
TEST_CASE(TEST_2)
@@ -86,9 +86,9 @@ TEST_CASE(TEST_2)
Crypto::Curves::Ed25519 curve;
- auto generated_signature = MUST(curve.sign(public_key, private_key, message));
+ auto generated_signature = TRY_OR_FAIL(curve.sign(private_key, message));
EXPECT_EQ(generated_signature, expected_signature);
- EXPECT_EQ(true, curve.verify(public_key, expected_signature, message));
+ EXPECT(TRY_OR_FAIL(curve.verify(public_key, expected_signature, message)));
}
TEST_CASE(TEST_3)
@@ -128,9 +128,9 @@ TEST_CASE(TEST_3)
Crypto::Curves::Ed25519 curve;
- auto generated_signature = MUST(curve.sign(public_key, private_key, message));
+ auto generated_signature = TRY_OR_FAIL(curve.sign(private_key, message));
EXPECT_EQ(generated_signature, expected_signature);
- EXPECT_EQ(true, curve.verify(public_key, expected_signature, message));
+ EXPECT(TRY_OR_FAIL(curve.verify(public_key, expected_signature, message)));
}
TEST_CASE(TEST_SHA_ABC)
@@ -179,7 +179,7 @@ TEST_CASE(TEST_SHA_ABC)
Crypto::Curves::Ed25519 curve;
- auto generated_signature = MUST(curve.sign(public_key, private_key, message));
+ auto generated_signature = TRY_OR_FAIL(curve.sign(private_key, message));
EXPECT_EQ(generated_signature, expected_signature);
- EXPECT_EQ(true, curve.verify(public_key, expected_signature, message));
+ EXPECT(TRY_OR_FAIL(curve.verify(public_key, expected_signature, message)));
}
|
d7005be768d48f216ecdf0dac76e6909b2fb8e16
|
2023-12-06 17:28:04
|
Andreas Kling
|
libjs: Update CyclicModule to match current spec
| false
|
Update CyclicModule to match current spec
|
libjs
|
diff --git a/Userland/Libraries/LibJS/CyclicModule.cpp b/Userland/Libraries/LibJS/CyclicModule.cpp
index 56277429b65b..247b86f3456d 100644
--- a/Userland/Libraries/LibJS/CyclicModule.cpp
+++ b/Userland/Libraries/LibJS/CyclicModule.cpp
@@ -165,13 +165,12 @@ void continue_module_loading(GraphLoadingState& state, ThrowCompletionOr<Nonnull
// 4. Return UNUSED.
}
-// 16.2.1.5.1 Link ( ), https://tc39.es/ecma262/#sec-moduledeclarationlinking
+// 16.2.1.5.2 Link ( ), https://tc39.es/ecma262/#sec-moduledeclarationlinking
ThrowCompletionOr<void> CyclicModule::link(VM& vm)
{
dbgln_if(JS_MODULE_DEBUG, "[JS MODULE] link[{}]()", this);
- // 1. Assert: module.[[Status]] is not linking or evaluating.
- VERIFY(m_status != ModuleStatus::Linking);
- VERIFY(m_status != ModuleStatus::Evaluating);
+ // 1. Assert: module.[[Status]] is one of unlinked, linked, evaluating-async, or evaluated.
+ VERIFY(m_status == ModuleStatus::Unlinked || m_status == ModuleStatus::Linked || m_status == ModuleStatus::EvaluatingAsync || m_status == ModuleStatus::Evaluated);
// 2. Let stack be a new empty List.
Vector<Module*> stack;
@@ -194,11 +193,11 @@ ThrowCompletionOr<void> CyclicModule::link(VM& vm)
// b. Assert: module.[[Status]] is unlinked.
VERIFY(m_status == ModuleStatus::Unlinked);
- // c. Return result.
+ // c. Return ? result.
return result.release_error();
}
- // 5. Assert: module.[[Status]] is linked, evaluating-async, or evaluated.
+ // 5. Assert: module.[[Status]] is one of linked, evaluating-async, or evaluated.
VERIFY(m_status == ModuleStatus::Linked || m_status == ModuleStatus::EvaluatingAsync || m_status == ModuleStatus::Evaluated);
// 6. Assert: stack is empty.
VERIFY(stack.is_empty());
|
d639e9429f187bd27904146c915aa62cbeb820fc
|
2024-11-24 06:05:36
|
Timothy Flynn
|
libjs: Implement Temporal.PlainTime.prototype.round/equals
| false
|
Implement Temporal.PlainTime.prototype.round/equals
|
libjs
|
diff --git a/Libraries/LibJS/Runtime/Temporal/PlainTimePrototype.cpp b/Libraries/LibJS/Runtime/Temporal/PlainTimePrototype.cpp
index ad4facd86d76..8466178f6cb8 100644
--- a/Libraries/LibJS/Runtime/Temporal/PlainTimePrototype.cpp
+++ b/Libraries/LibJS/Runtime/Temporal/PlainTimePrototype.cpp
@@ -41,6 +41,8 @@ void PlainTimePrototype::initialize(Realm& realm)
define_native_function(realm, vm.names.with, with, 1, attr);
define_native_function(realm, vm.names.until, until, 1, attr);
define_native_function(realm, vm.names.since, since, 1, attr);
+ define_native_function(realm, vm.names.round, round, 1, attr);
+ define_native_function(realm, vm.names.equals, equals, 1, attr);
define_native_function(realm, vm.names.toString, to_string, 0, attr);
define_native_function(realm, vm.names.toLocaleString, to_locale_string, 0, attr);
define_native_function(realm, vm.names.toJSON, to_json, 0, attr);
@@ -193,6 +195,89 @@ JS_DEFINE_NATIVE_FUNCTION(PlainTimePrototype::since)
return TRY(difference_temporal_plain_time(vm, DurationOperation::Since, temporal_time, other, options));
}
+// 4.3.14 Temporal.PlainTime.prototype.round ( roundTo ), https://tc39.es/proposal-temporal/#sec-temporal.plaintime.prototype.round
+JS_DEFINE_NATIVE_FUNCTION(PlainTimePrototype::round)
+{
+ auto& realm = *vm.current_realm();
+
+ auto round_to_value = vm.argument(0);
+
+ // 1. Let temporalTime be the this value.
+ // 2. Perform ? RequireInternalSlot(temporalTime, [[InitializedTemporalTime]]).
+ auto temporal_time = TRY(typed_this_object(vm));
+
+ // 3. If roundTo is undefined, then
+ if (round_to_value.is_undefined()) {
+ // a. Throw a TypeError exception.
+ return vm.throw_completion<TypeError>(ErrorType::TemporalMissingOptionsObject);
+ }
+
+ GC::Ptr<Object> round_to;
+
+ // 4. If roundTo is a String, then
+ if (round_to_value.is_string()) {
+ // a. Let paramString be roundTo.
+ auto param_string = round_to_value;
+
+ // b. Set roundTo to OrdinaryObjectCreate(null).
+ round_to = Object::create(realm, nullptr);
+
+ // c. Perform ! CreateDataPropertyOrThrow(roundTo, "smallestUnit", paramString).
+ MUST(round_to->create_data_property_or_throw(vm.names.smallestUnit, param_string));
+ }
+ // 5. Else,
+ else {
+ // a. Set roundTo to ? GetOptionsObject(roundTo).
+ round_to = TRY(get_options_object(vm, round_to_value));
+ }
+
+ // 6. NOTE: The following steps read options and perform independent validation in alphabetical order
+ // (GetRoundingIncrementOption reads "roundingIncrement" and GetRoundingModeOption reads "roundingMode").
+
+ // 7. Let roundingIncrement be ? GetRoundingIncrementOption(roundTo).
+ auto rounding_increment = TRY(get_rounding_increment_option(vm, *round_to));
+
+ // 8. Let roundingMode be ? GetRoundingModeOption(roundTo, HALF-EXPAND).
+ auto rounding_mode = TRY(get_rounding_mode_option(vm, *round_to, RoundingMode::HalfExpand));
+
+ // 9. Let smallestUnit be ? GetTemporalUnitValuedOption(roundTo, "smallestUnit", TIME, REQUIRED).
+ auto smallest_unit = TRY(get_temporal_unit_valued_option(vm, *round_to, vm.names.smallestUnit, UnitGroup::Time, Required {}));
+ auto smallest_unit_value = smallest_unit.get<Unit>();
+
+ // 10. Let maximum be MaximumTemporalDurationRoundingIncrement(smallestUnit).
+ auto maximum = maximum_temporal_duration_rounding_increment(smallest_unit_value);
+
+ // 11. Assert: maximum is not UNSET.
+ VERIFY(!maximum.has<Unset>());
+
+ // 12. Perform ? ValidateTemporalRoundingIncrement(roundingIncrement, maximum, false).
+ TRY(validate_temporal_rounding_increment(vm, rounding_increment, maximum.get<u64>(), false));
+
+ // 13. Let result be RoundTime(temporalTime.[[Time]], roundingIncrement, smallestUnit, roundingMode).
+ auto result = round_time(temporal_time->time(), rounding_increment, smallest_unit_value, rounding_mode);
+
+ // 14. Return ! CreateTemporalTime(result).
+ return MUST(create_temporal_time(vm, result));
+}
+
+// 4.3.15 Temporal.PlainTime.prototype.equals ( other ), https://tc39.es/proposal-temporal/#sec-temporal.plaintime.prototype.equals
+JS_DEFINE_NATIVE_FUNCTION(PlainTimePrototype::equals)
+{
+ // 1. Let temporalTime be the this value.
+ // 2. Perform ? RequireInternalSlot(temporalTime, [[InitializedTemporalTime]]).
+ auto temporal_time = TRY(typed_this_object(vm));
+
+ // 3. Set other to ? ToTemporalTime(other).
+ auto other = TRY(to_temporal_time(vm, vm.argument(0)));
+
+ // 4. If CompareTimeRecord(temporalTime.[[Time]], other.[[Time]]) = 0, return true.
+ if (compare_time_record(temporal_time->time(), other->time()) == 0)
+ return true;
+
+ // 5. Return false.
+ return false;
+}
+
// 4.3.16 Temporal.PlainTime.prototype.toString ( [ options ] ), https://tc39.es/proposal-temporal/#sec-temporal.plaintime.prototype.tostring
JS_DEFINE_NATIVE_FUNCTION(PlainTimePrototype::to_string)
{
diff --git a/Libraries/LibJS/Runtime/Temporal/PlainTimePrototype.h b/Libraries/LibJS/Runtime/Temporal/PlainTimePrototype.h
index ae2c19d525af..ef940aa6749b 100644
--- a/Libraries/LibJS/Runtime/Temporal/PlainTimePrototype.h
+++ b/Libraries/LibJS/Runtime/Temporal/PlainTimePrototype.h
@@ -34,6 +34,8 @@ class PlainTimePrototype final : public PrototypeObject<PlainTimePrototype, Plai
JS_DECLARE_NATIVE_FUNCTION(with);
JS_DECLARE_NATIVE_FUNCTION(until);
JS_DECLARE_NATIVE_FUNCTION(since);
+ JS_DECLARE_NATIVE_FUNCTION(round);
+ JS_DECLARE_NATIVE_FUNCTION(equals);
JS_DECLARE_NATIVE_FUNCTION(to_string);
JS_DECLARE_NATIVE_FUNCTION(to_locale_string);
JS_DECLARE_NATIVE_FUNCTION(to_json);
diff --git a/Libraries/LibJS/Tests/builtins/Temporal/PlainTime/PlainTime.prototype.equals.js b/Libraries/LibJS/Tests/builtins/Temporal/PlainTime/PlainTime.prototype.equals.js
new file mode 100644
index 000000000000..4d810b3d37f9
--- /dev/null
+++ b/Libraries/LibJS/Tests/builtins/Temporal/PlainTime/PlainTime.prototype.equals.js
@@ -0,0 +1,13 @@
+describe("correct behavior", () => {
+ test("length is 1", () => {
+ expect(Temporal.PlainTime.prototype.equals).toHaveLength(1);
+ });
+
+ test("basic functionality", () => {
+ const firstPlainTime = new Temporal.PlainTime(1, 1, 1, 1, 1, 1);
+ const secondPlainTime = new Temporal.PlainTime(0, 1, 1, 1, 1, 1);
+ expect(firstPlainTime.equals(firstPlainTime)).toBeTrue();
+ expect(secondPlainTime.equals(secondPlainTime)).toBeTrue();
+ expect(secondPlainTime.equals(firstPlainTime)).toBeFalse();
+ });
+});
diff --git a/Libraries/LibJS/Tests/builtins/Temporal/PlainTime/PlainTime.prototype.round.js b/Libraries/LibJS/Tests/builtins/Temporal/PlainTime/PlainTime.prototype.round.js
new file mode 100644
index 000000000000..6d9402699b41
--- /dev/null
+++ b/Libraries/LibJS/Tests/builtins/Temporal/PlainTime/PlainTime.prototype.round.js
@@ -0,0 +1,147 @@
+describe("correct behavior", () => {
+ test("length is 1", () => {
+ expect(Temporal.PlainTime.prototype.round).toHaveLength(1);
+ });
+
+ test("basic functionality", () => {
+ const plainTime = new Temporal.PlainTime(18, 15, 9, 100, 200, 300);
+
+ const firstRoundedPlainTime = plainTime.round({ smallestUnit: "minute" });
+ expect(firstRoundedPlainTime.hour).toBe(18);
+ expect(firstRoundedPlainTime.minute).toBe(15);
+ expect(firstRoundedPlainTime.second).toBe(0);
+ expect(firstRoundedPlainTime.millisecond).toBe(0);
+ expect(firstRoundedPlainTime.microsecond).toBe(0);
+ expect(firstRoundedPlainTime.nanosecond).toBe(0);
+
+ const secondRoundedPlainTime = plainTime.round({
+ smallestUnit: "minute",
+ roundingMode: "ceil",
+ });
+ expect(secondRoundedPlainTime.hour).toBe(18);
+ expect(secondRoundedPlainTime.minute).toBe(16);
+ expect(secondRoundedPlainTime.second).toBe(0);
+ expect(secondRoundedPlainTime.millisecond).toBe(0);
+ expect(secondRoundedPlainTime.microsecond).toBe(0);
+ expect(secondRoundedPlainTime.nanosecond).toBe(0);
+
+ const thirdRoundedPlainTime = plainTime.round({
+ smallestUnit: "minute",
+ roundingMode: "ceil",
+ roundingIncrement: 30,
+ });
+ expect(thirdRoundedPlainTime.hour).toBe(18);
+ expect(thirdRoundedPlainTime.minute).toBe(30);
+ expect(thirdRoundedPlainTime.second).toBe(0);
+ expect(thirdRoundedPlainTime.millisecond).toBe(0);
+ expect(thirdRoundedPlainTime.microsecond).toBe(0);
+ expect(thirdRoundedPlainTime.nanosecond).toBe(0);
+
+ const fourthRoundedPlainTime = plainTime.round({
+ smallestUnit: "minute",
+ roundingMode: "floor",
+ roundingIncrement: 30,
+ });
+ expect(fourthRoundedPlainTime.hour).toBe(18);
+ expect(fourthRoundedPlainTime.minute).toBe(0);
+ expect(fourthRoundedPlainTime.second).toBe(0);
+ expect(fourthRoundedPlainTime.millisecond).toBe(0);
+ expect(fourthRoundedPlainTime.microsecond).toBe(0);
+ expect(fourthRoundedPlainTime.nanosecond).toBe(0);
+
+ const fifthRoundedPlainTime = plainTime.round({
+ smallestUnit: "hour",
+ roundingMode: "halfExpand",
+ roundingIncrement: 4,
+ });
+ expect(fifthRoundedPlainTime.hour).toBe(20);
+ expect(fifthRoundedPlainTime.minute).toBe(0);
+ expect(fifthRoundedPlainTime.second).toBe(0);
+ expect(fifthRoundedPlainTime.millisecond).toBe(0);
+ expect(fifthRoundedPlainTime.microsecond).toBe(0);
+ expect(fifthRoundedPlainTime.nanosecond).toBe(0);
+ });
+
+ test("string argument is implicitly converted to options object", () => {
+ const plainTime = new Temporal.PlainTime(18, 15, 9, 100, 200, 300);
+ expect(
+ plainTime.round("minute").equals(plainTime.round({ smallestUnit: "minute" }))
+ ).toBeTrue();
+ });
+});
+
+describe("errors", () => {
+ test("this value must be a Temporal.PlainTime object", () => {
+ expect(() => {
+ Temporal.PlainTime.prototype.round.call("foo", {});
+ }).toThrowWithMessage(TypeError, "Not an object of type Temporal.PlainTime");
+ });
+
+ test("missing options object", () => {
+ expect(() => {
+ const plainTime = new Temporal.PlainTime(18, 15, 9, 100, 200, 300);
+ plainTime.round();
+ }).toThrowWithMessage(TypeError, "Required options object is missing or undefined");
+ });
+
+ test("invalid rounding mode", () => {
+ expect(() => {
+ const plainTime = new Temporal.PlainTime(18, 15, 9, 100, 200, 300);
+ plainTime.round({ smallestUnit: "second", roundingMode: "serenityOS" });
+ }).toThrowWithMessage(
+ RangeError,
+ "serenityOS is not a valid value for option roundingMode"
+ );
+ });
+
+ test("invalid smallest unit", () => {
+ expect(() => {
+ const plainTime = new Temporal.PlainTime(18, 15, 9, 100, 200, 300);
+ plainTime.round({ smallestUnit: "serenityOS" });
+ }).toThrowWithMessage(
+ RangeError,
+ "serenityOS is not a valid value for option smallestUnit"
+ );
+ });
+
+ test("increment may not be NaN", () => {
+ expect(() => {
+ const plainTime = new Temporal.PlainTime(18, 15, 9, 100, 200, 300);
+ plainTime.round({ smallestUnit: "second", roundingIncrement: NaN });
+ }).toThrowWithMessage(RangeError, "NaN is not a valid value for option roundingIncrement");
+ });
+
+ test("increment may not be smaller than 1 or larger than maximum", () => {
+ const plainTime = new Temporal.PlainTime(18, 15, 9, 100, 200, 300);
+ expect(() => {
+ plainTime.round({ smallestUnit: "second", roundingIncrement: -1 });
+ }).toThrowWithMessage(RangeError, "-1 is not a valid value for option roundingIncrement");
+ expect(() => {
+ plainTime.round({ smallestUnit: "second", roundingIncrement: 0 });
+ }).toThrowWithMessage(RangeError, "0 is not a valid value for option roundingIncrement");
+ expect(() => {
+ plainTime.round({ smallestUnit: "second", roundingIncrement: Infinity });
+ }).toThrowWithMessage(
+ RangeError,
+ "Infinity is not a valid value for option roundingIncrement"
+ );
+ expect(() => {
+ plainTime.round({ smallestUnit: "hours", roundingIncrement: 24 });
+ }).toThrowWithMessage(RangeError, "24 is not a valid value for option roundingIncrement");
+ expect(() => {
+ plainTime.round({ smallestUnit: "minutes", roundingIncrement: 60 });
+ }).toThrowWithMessage(RangeError, "60 is not a valid value for option roundingIncrement");
+ expect(() => {
+ plainTime.round({ smallestUnit: "seconds", roundingIncrement: 60 });
+ }).toThrowWithMessage(RangeError, "60 is not a valid value for option roundingIncrement");
+ expect(() => {
+ plainTime.round({ smallestUnit: "milliseconds", roundingIncrement: 1000 });
+ }).toThrowWithMessage(RangeError, "1000 is not a valid value for option roundingIncrement");
+ expect(() => {
+ plainTime.round({ smallestUnit: "microseconds", roundingIncrement: 1000 });
+ }).toThrowWithMessage(RangeError, "1000 is not a valid value for option roundingIncrement");
+ expect(() => {
+ plainTime.round({ smallestUnit: "nanoseconds", roundingIncrement: 1000 });
+ }).toThrowWithMessage(RangeError, "1000 is not a valid value for option roundingIncrement");
+ });
+});
|
02e199a9cb76a983cd5d9ceb1540080f675a8141
|
2020-02-16 17:18:58
|
Andreas Kling
|
ak: Don't construct a String every time we LogStream<< a number
| false
|
Don't construct a String every time we LogStream<< a number
|
ak
|
diff --git a/AK/LogStream.cpp b/AK/LogStream.cpp
index 7d07f171176a..f986cd07592e 100644
--- a/AK/LogStream.cpp
+++ b/AK/LogStream.cpp
@@ -49,37 +49,51 @@ const LogStream& operator<<(const LogStream& stream, const StringView& value)
const LogStream& operator<<(const LogStream& stream, int value)
{
- return stream << String::number(value);
+ char buffer[32];
+ sprintf(buffer, "%d", value);
+ return stream << buffer;
}
const LogStream& operator<<(const LogStream& stream, long value)
{
- return stream << String::number(value);
+ char buffer[32];
+ sprintf(buffer, "%ld", value);
+ return stream << buffer;
}
const LogStream& operator<<(const LogStream& stream, long long value)
{
- return stream << String::number(value);
+ char buffer[32];
+ sprintf(buffer, "%lld", value);
+ return stream << buffer;
}
const LogStream& operator<<(const LogStream& stream, unsigned value)
{
- return stream << String::number(value);
+ char buffer[32];
+ sprintf(buffer, "%u", value);
+ return stream << buffer;
}
const LogStream& operator<<(const LogStream& stream, unsigned long long value)
{
- return stream << String::number(value);
+ char buffer[32];
+ sprintf(buffer, "%llu", value);
+ return stream << buffer;
}
const LogStream& operator<<(const LogStream& stream, unsigned long value)
{
- return stream << String::number(value);
+ char buffer[32];
+ sprintf(buffer, "%lu", value);
+ return stream << buffer;
}
const LogStream& operator<<(const LogStream& stream, const void* value)
{
- return stream << String::format("%p", value);
+ char buffer[32];
+ sprintf(buffer, "%p", value);
+ return stream << buffer;
}
#if defined(__serenity__) && !defined(KERNEL) && !defined(BOOTSTRAPPER)
|
94652fd2fbf8cc79dc8446ea38b366c0464d6d98
|
2020-02-22 14:39:54
|
Andreas Kling
|
kernel: Fully validate pointers when walking stack during profiling
| false
|
Fully validate pointers when walking stack during profiling
|
kernel
|
diff --git a/Kernel/Thread.cpp b/Kernel/Thread.cpp
index dcba4fae39f5..de857a066280 100644
--- a/Kernel/Thread.cpp
+++ b/Kernel/Thread.cpp
@@ -813,7 +813,7 @@ Vector<uintptr_t> Thread::raw_backtrace(uintptr_t ebp) const
ProcessPagingScope paging_scope(process);
Vector<uintptr_t, Profiling::max_stack_frame_count> backtrace;
backtrace.append(ebp);
- for (uintptr_t* stack_ptr = (uintptr_t*)ebp; MM.can_read_without_faulting(process, VirtualAddress(stack_ptr), sizeof(uintptr_t) * 2); stack_ptr = (uintptr_t*)*stack_ptr) {
+ for (uintptr_t* stack_ptr = (uintptr_t*)ebp; process.validate_read_from_kernel(VirtualAddress(stack_ptr), sizeof(uintptr_t) * 2) && MM.can_read_without_faulting(process, VirtualAddress(stack_ptr), sizeof(uintptr_t) * 2); stack_ptr = (uintptr_t*)*stack_ptr) {
uintptr_t retaddr = stack_ptr[1];
backtrace.append(retaddr);
if (backtrace.size() == Profiling::max_stack_frame_count)
|
ed5a9aa03850294d7b0280d58ed08f76c606e25c
|
2021-10-04 00:44:03
|
Linus Groh
|
libjs: Convert set_integrity_level() to ThrowCompletionOr
| false
|
Convert set_integrity_level() to ThrowCompletionOr
|
libjs
|
diff --git a/Userland/Libraries/LibJS/Runtime/Object.cpp b/Userland/Libraries/LibJS/Runtime/Object.cpp
index e0e6c4dc2995..2bc19b33a103 100644
--- a/Userland/Libraries/LibJS/Runtime/Object.cpp
+++ b/Userland/Libraries/LibJS/Runtime/Object.cpp
@@ -273,7 +273,7 @@ ThrowCompletionOr<bool> Object::has_own_property(PropertyName const& property_na
}
// 7.3.15 SetIntegrityLevel ( O, level ), https://tc39.es/ecma262/#sec-setintegritylevel
-bool Object::set_integrity_level(IntegrityLevel level)
+ThrowCompletionOr<bool> Object::set_integrity_level(IntegrityLevel level)
{
auto& global_object = this->global_object();
@@ -283,14 +283,14 @@ bool Object::set_integrity_level(IntegrityLevel level)
VERIFY(level == IntegrityLevel::Sealed || level == IntegrityLevel::Frozen);
// 3. Let status be ? O.[[PreventExtensions]]().
- auto status = TRY_OR_DISCARD(internal_prevent_extensions());
+ auto status = TRY(internal_prevent_extensions());
// 4. If status is false, return false.
if (!status)
return false;
// 5. Let keys be ? O.[[OwnPropertyKeys]]().
- auto keys = TRY_OR_DISCARD(internal_own_property_keys());
+ auto keys = TRY(internal_own_property_keys());
// 6. If level is sealed, then
if (level == IntegrityLevel::Sealed) {
@@ -299,7 +299,7 @@ bool Object::set_integrity_level(IntegrityLevel level)
auto property_name = PropertyName::from_value(global_object, key);
// i. Perform ? DefinePropertyOrThrow(O, k, PropertyDescriptor { [[Configurable]]: false }).
- TRY_OR_DISCARD(define_property_or_throw(property_name, { .configurable = false }));
+ TRY(define_property_or_throw(property_name, { .configurable = false }));
}
}
// 7. Else,
@@ -311,7 +311,7 @@ bool Object::set_integrity_level(IntegrityLevel level)
auto property_name = PropertyName::from_value(global_object, key);
// i. Let currentDesc be ? O.[[GetOwnProperty]](k).
- auto current_descriptor = TRY_OR_DISCARD(internal_get_own_property(property_name));
+ auto current_descriptor = TRY(internal_get_own_property(property_name));
// ii. If currentDesc is not undefined, then
if (!current_descriptor.has_value())
@@ -331,7 +331,7 @@ bool Object::set_integrity_level(IntegrityLevel level)
}
// 3. Perform ? DefinePropertyOrThrow(O, k, desc).
- TRY_OR_DISCARD(define_property_or_throw(property_name, descriptor));
+ TRY(define_property_or_throw(property_name, descriptor));
}
}
diff --git a/Userland/Libraries/LibJS/Runtime/Object.h b/Userland/Libraries/LibJS/Runtime/Object.h
index 95b33c34fb2f..d6b13ba82c0f 100644
--- a/Userland/Libraries/LibJS/Runtime/Object.h
+++ b/Userland/Libraries/LibJS/Runtime/Object.h
@@ -85,7 +85,7 @@ class Object : public Cell {
ThrowCompletionOr<bool> delete_property_or_throw(PropertyName const&);
ThrowCompletionOr<bool> has_property(PropertyName const&) const;
ThrowCompletionOr<bool> has_own_property(PropertyName const&) const;
- bool set_integrity_level(IntegrityLevel);
+ ThrowCompletionOr<bool> set_integrity_level(IntegrityLevel);
bool test_integrity_level(IntegrityLevel) const;
MarkedValueList enumerable_own_property_names(PropertyKind kind) const;
ThrowCompletionOr<Object*> copy_data_properties(Value source, HashTable<PropertyName, PropertyNameTraits> const& seen_names, GlobalObject& global_object);
diff --git a/Userland/Libraries/LibJS/Runtime/ObjectConstructor.cpp b/Userland/Libraries/LibJS/Runtime/ObjectConstructor.cpp
index 5890d4969738..efd4cafbe213 100644
--- a/Userland/Libraries/LibJS/Runtime/ObjectConstructor.cpp
+++ b/Userland/Libraries/LibJS/Runtime/ObjectConstructor.cpp
@@ -221,9 +221,7 @@ JS_DEFINE_NATIVE_FUNCTION(ObjectConstructor::freeze)
auto argument = vm.argument(0);
if (!argument.is_object())
return argument;
- auto status = argument.as_object().set_integrity_level(Object::IntegrityLevel::Frozen);
- if (vm.exception())
- return {};
+ auto status = TRY_OR_DISCARD(argument.as_object().set_integrity_level(Object::IntegrityLevel::Frozen));
if (!status) {
vm.throw_exception<TypeError>(global_object, ErrorType::ObjectFreezeFailed);
return {};
@@ -272,9 +270,7 @@ JS_DEFINE_NATIVE_FUNCTION(ObjectConstructor::seal)
auto argument = vm.argument(0);
if (!argument.is_object())
return argument;
- auto status = argument.as_object().set_integrity_level(Object::IntegrityLevel::Sealed);
- if (vm.exception())
- return {};
+ auto status = TRY_OR_DISCARD(argument.as_object().set_integrity_level(Object::IntegrityLevel::Sealed));
if (!status) {
vm.throw_exception<TypeError>(global_object, ErrorType::ObjectSealFailed);
return {};
diff --git a/Userland/Libraries/LibWeb/WebAssembly/WebAssemblyInstanceObject.cpp b/Userland/Libraries/LibWeb/WebAssembly/WebAssemblyInstanceObject.cpp
index c916c4729947..48b79c3532eb 100644
--- a/Userland/Libraries/LibWeb/WebAssembly/WebAssemblyInstanceObject.cpp
+++ b/Userland/Libraries/LibWeb/WebAssembly/WebAssemblyInstanceObject.cpp
@@ -54,7 +54,7 @@ void WebAssemblyInstanceObject::initialize(JS::GlobalObject& global_object)
});
}
- m_exports_object->set_integrity_level(IntegrityLevel::Frozen);
+ MUST(m_exports_object->set_integrity_level(IntegrityLevel::Frozen));
}
void WebAssemblyInstanceObject::visit_edges(Visitor& visitor)
|
346737701d8f00afcc601e2e3e1d735e30a487f1
|
2022-12-16 14:28:03
|
Andreas Kling
|
libweb: Allow setting HTMLTableElement.tHead to null value
| false
|
Allow setting HTMLTableElement.tHead to null value
|
libweb
|
diff --git a/Userland/Libraries/LibWeb/HTML/HTMLTableElement.cpp b/Userland/Libraries/LibWeb/HTML/HTMLTableElement.cpp
index 77e655f372e7..a8c7342fc340 100644
--- a/Userland/Libraries/LibWeb/HTML/HTMLTableElement.cpp
+++ b/Userland/Libraries/LibWeb/HTML/HTMLTableElement.cpp
@@ -93,8 +93,11 @@ void HTMLTableElement::delete_caption()
}
}
+// https://html.spec.whatwg.org/multipage/tables.html#dom-table-thead
JS::GCPtr<HTMLTableSectionElement> HTMLTableElement::t_head()
{
+ // The tHead IDL attribute must return, on getting, the first thead element child of the table element,
+ // if any, or null otherwise.
for (auto* child = first_child(); child; child = child->next_sibling()) {
if (is<HTMLTableSectionElement>(*child)) {
auto table_section_element = &verify_cast<HTMLTableSectionElement>(*child);
@@ -106,18 +109,24 @@ JS::GCPtr<HTMLTableSectionElement> HTMLTableElement::t_head()
return nullptr;
}
+// https://html.spec.whatwg.org/multipage/tables.html#dom-table-thead
WebIDL::ExceptionOr<void> HTMLTableElement::set_t_head(HTMLTableSectionElement* thead)
{
- // FIXME: This is not always the case, but this function is currently written in a way that assumes non-null.
- VERIFY(thead);
-
- if (thead->local_name() != TagNames::thead)
+ // If the new value is neither null nor a thead element, then a "HierarchyRequestError" DOMException must be thrown instead.
+ if (thead && thead->local_name() != TagNames::thead)
return WebIDL::HierarchyRequestError::create(realm(), "Element is not thead");
- // FIXME: The spec requires deleting the current thead if thead is null
- // Currently the wrapper generator doesn't send us a nullable value
+ // On setting, if the new value is null or a thead element, the first thead element child of the table element,
+ // if any, must be removed,
delete_t_head();
+ if (!thead)
+ return {};
+
+ // and the new value, if not null, must be inserted immediately before the first element in the table element
+ // that is neither a caption element nor a colgroup element, if any,
+ // or at the end of the table if there are no such elements.
+
// We insert the new thead after any <caption> or <colgroup> elements
DOM::Node* child_to_append_after = nullptr;
for (auto* child = first_child(); child; child = child->next_sibling()) {
|
a1e1aa96fbd404b440838dda179ec5c4e14f1013
|
2020-07-13 12:16:44
|
Stefano Cristiano
|
toolchain: Allow building using CMake on macOS
| false
|
Allow building using CMake on macOS
|
toolchain
|
diff --git a/CMakeLists.txt b/CMakeLists.txt
index 2238ca6e41bf..8301d495d4fc 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -126,6 +126,22 @@ set(CMAKE_RANLIB ${TOOLCHAIN_PREFIX}ranlib)
set(CMAKE_STRIP ${TOOLCHAIN_PREFIX}strip)
set(CMAKE_AR ${TOOLCHAIN_PREFIX}ar)
+foreach(lang ASM C CXX OBJC OBJCXX)
+ unset(CMAKE_${lang}_OSX_COMPATIBILITY_VERSION_FLAG)
+ unset(CMAKE_${lang}_OSX_CURRENT_VERSION_FLAG)
+ unset(CMAKE_${lang}_LINK_FLAGS)
+ unset(CMAKE_SHARED_LIBRARY_CREATE_${lang}_FLAGS)
+ unset(CMAKE_SHARED_MODULE_CREATE_${lang}_FLAGS)
+ unset(CMAKE_SHARED_MODULE_LOADER_${lang}_FLAG )
+ unset(CMAKE_${lang}_OSX_DEPLOYMENT_TARGET_FLAG)
+ unset(CMAKE_${lang}_SYSROOT_FLAG)
+ unset(CMAKE_SHARED_LIBRARY_SONAME_${lang}_FLAG)
+endforeach()
+
+set(CMAKE_INSTALL_NAME_TOOL "true")
+set(CMAKE_SHARED_LIBRARY_SUFFIX ".so")
+set(CMAKE_SHARED_LIBRARY_CREATE_CXX_FLAGS "-shared")
+
#FIXME: -fstack-protector
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Os -Wno-sized-deallocation -fno-sized-deallocation -fno-exceptions -fno-rtti -Wno-address-of-packed-member -Wundef -Wcast-qual -Wwrite-strings -Wimplicit-fallthrough -Wno-nonnull-compare -Wno-deprecated-copy -Wno-expansion-to-defined")
diff --git a/Libraries/LibC/CMakeLists.txt b/Libraries/LibC/CMakeLists.txt
index 2d37a9ce3df7..287597351837 100644
--- a/Libraries/LibC/CMakeLists.txt
+++ b/Libraries/LibC/CMakeLists.txt
@@ -54,10 +54,15 @@ set(ELF_SOURCES ${ELF_SOURCES} ../LibELF/Arch/i386/plt_trampoline.S)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -DSERENITY_LIBC_BUILD")
+find_program(INSTALL_COMMAND ginstall)
+if(NOT INSTALL_COMMAND)
+ set(INSTALL_COMMAND install)
+endif()
+
add_library(crt0 STATIC crt0.cpp)
add_custom_command(
TARGET crt0
- COMMAND install -D $<TARGET_OBJECTS:crt0> ${CMAKE_INSTALL_PREFIX}/usr/lib/crt0.o
+ COMMAND ${INSTALL_COMMAND} -D $<TARGET_OBJECTS:crt0> ${CMAKE_INSTALL_PREFIX}/usr/lib/crt0.o
)
set(SOURCES ${LIBC_SOURCES} ${AK_SOURCES} ${ELF_SOURCES})
diff --git a/Toolchain/BuildIt.sh b/Toolchain/BuildIt.sh
index 57098f3a7066..f2858a6c085d 100755
--- a/Toolchain/BuildIt.sh
+++ b/Toolchain/BuildIt.sh
@@ -1,6 +1,5 @@
#!/usr/bin/env bash
set -e
-shopt -s globstar
# This file will need to be run in bash, for now.
@@ -24,6 +23,12 @@ NPROC="nproc"
# It seems that Travis starts having trouble at 35 entries, so I think this is a good amount.
KEEP_CACHE_COUNT=8
+if command -v ginstall &>/dev/null; then
+ INSTALL=ginstall
+else
+ INSTALL=install
+fi
+
if [ "$(uname -s)" = "OpenBSD" ]; then
MAKE=gmake
MD5SUM="md5 -q"
@@ -230,11 +235,12 @@ pushd "$DIR/Build/"
pushd "$BUILD"
CXXFLAGS="-DBUILDING_SERENITY_TOOLCHAIN" cmake ..
cmake --build . --target LibC
- install -D Libraries/LibC/libc.a Libraries/LibM/libm.a Root/usr/lib/
+ "$INSTALL" -D Libraries/LibC/libc.a Libraries/LibM/libm.a Root/usr/lib/
SRC_ROOT=$(realpath "$DIR"/..)
- for header in "$SRC_ROOT"/Libraries/Lib{C,M}/**/*.h; do
+ FILES=$(find "$SRC_ROOT"/Libraries/LibC "$SRC_ROOT"/Libraries/LibM -name '*.h' -print)
+ for header in $FILES; do
target=$(echo "$header" | sed -e "s@$SRC_ROOT/Libraries/LibC@@" -e "s@$SRC_ROOT/Libraries/LibM@@")
- install -D "$header" "Root/usr/include/$target"
+ $INSTALL -D "$header" "Root/usr/include/$target"
done
unset SRC_ROOT
popd
|
035c4e15f48a7189683d03a3af8fc99fd127ac21
|
2019-12-02 17:47:32
|
Andreas Kling
|
build: Build LibDraw before WindowServer
| false
|
Build LibDraw before WindowServer
|
build
|
diff --git a/Kernel/makeall.sh b/Kernel/makeall.sh
index bf41b174921f..c24b587a57ea 100755
--- a/Kernel/makeall.sh
+++ b/Kernel/makeall.sh
@@ -24,6 +24,7 @@ build_targets="$build_targets ../Libraries/LibHTML/CodeGenerators/Generate_CSS_P
# Build LibC, LibCore, LibIPC and LibThread before IPC servers, since they depend on them.
build_targets="$build_targets ../Libraries/LibC"
build_targets="$build_targets ../Libraries/LibCore"
+build_targets="$build_targets ../Libraries/LibDraw"
build_targets="$build_targets ../Libraries/LibIPC"
build_targets="$build_targets ../Libraries/LibThread"
build_targets="$build_targets ../Libraries/LibPthread"
@@ -37,7 +38,6 @@ build_targets="$build_targets ../Servers/WindowServer"
build_targets="$build_targets ../AK"
-build_targets="$build_targets ../Libraries/LibDraw"
build_targets="$build_targets ../Libraries/LibGUI"
build_targets="$build_targets ../Libraries/LibHTML"
build_targets="$build_targets ../Libraries/LibM"
|
22831033d03dc8676b5d12af3619d10a295cf8cd
|
2020-09-06 22:01:51
|
Andreas Kling
|
kernel: Virtualize the File::stat() operation
| false
|
Virtualize the File::stat() operation
|
kernel
|
diff --git a/Kernel/FileSystem/FIFO.cpp b/Kernel/FileSystem/FIFO.cpp
index 3b22a45c6a94..3f9c1e33a12d 100644
--- a/Kernel/FileSystem/FIFO.cpp
+++ b/Kernel/FileSystem/FIFO.cpp
@@ -166,4 +166,11 @@ String FIFO::absolute_path(const FileDescription&) const
return String::format("fifo:%u", m_fifo_id);
}
+KResult FIFO::stat(::stat& st) const
+{
+ memset(&st, 0, sizeof(st));
+ st.st_mode = S_IFIFO;
+ return KSuccess;
+}
+
}
diff --git a/Kernel/FileSystem/FIFO.h b/Kernel/FileSystem/FIFO.h
index c41ee67ddb5f..81b04597f26d 100644
--- a/Kernel/FileSystem/FIFO.h
+++ b/Kernel/FileSystem/FIFO.h
@@ -59,6 +59,7 @@ class FIFO final : public File {
// ^File
virtual KResultOr<size_t> write(FileDescription&, size_t, const u8*, size_t) override;
virtual KResultOr<size_t> read(FileDescription&, size_t, u8*, size_t) override;
+ virtual KResult stat(::stat&) const override;
virtual bool can_read(const FileDescription&, size_t) const override;
virtual bool can_write(const FileDescription&, size_t) const override;
virtual String absolute_path(const FileDescription&) const override;
diff --git a/Kernel/FileSystem/File.h b/Kernel/FileSystem/File.h
index 48efffed73a5..9d3a1c607376 100644
--- a/Kernel/FileSystem/File.h
+++ b/Kernel/FileSystem/File.h
@@ -78,6 +78,7 @@ class File : public RefCounted<File> {
virtual KResultOr<size_t> write(FileDescription&, size_t, const u8*, size_t) = 0;
virtual int ioctl(FileDescription&, unsigned request, FlatPtr arg);
virtual KResultOr<Region*> mmap(Process&, FileDescription&, VirtualAddress preferred_vaddr, size_t offset, size_t size, int prot, bool shared);
+ virtual KResult stat(::stat&) const { return KResult(-EBADF); }
virtual String absolute_path(const FileDescription&) const = 0;
diff --git a/Kernel/FileSystem/FileDescription.cpp b/Kernel/FileSystem/FileDescription.cpp
index fae986825026..80153e62255f 100644
--- a/Kernel/FileSystem/FileDescription.cpp
+++ b/Kernel/FileSystem/FileDescription.cpp
@@ -77,20 +77,11 @@ FileDescription::~FileDescription()
KResult FileDescription::stat(::stat& buffer)
{
- if (is_fifo()) {
- memset(&buffer, 0, sizeof(buffer));
- buffer.st_mode = S_IFIFO;
- return KSuccess;
- }
- if (is_socket()) {
- memset(&buffer, 0, sizeof(buffer));
- buffer.st_mode = S_IFSOCK;
- return KSuccess;
- }
-
- if (!m_inode)
- return KResult(-EBADF);
- return metadata().stat(buffer);
+ LOCKER(m_lock);
+ // FIXME: This is a little awkward, why can't we always forward to File::stat()?
+ if (m_inode)
+ return metadata().stat(buffer);
+ return m_file->stat(buffer);
}
off_t FileDescription::seek(off_t offset, int whence)
diff --git a/Kernel/Net/Socket.cpp b/Kernel/Net/Socket.cpp
index 42a657a06df5..061068e3ecf9 100644
--- a/Kernel/Net/Socket.cpp
+++ b/Kernel/Net/Socket.cpp
@@ -220,4 +220,11 @@ KResult Socket::shutdown(int how)
return KSuccess;
}
+KResult Socket::stat(::stat& st) const
+{
+ memset(&st, 0, sizeof(st));
+ st.st_mode = S_IFSOCK;
+ return KSuccess;
+}
+
}
diff --git a/Kernel/Net/Socket.h b/Kernel/Net/Socket.h
index 8f78c19e5e9d..b72fa5f837b4 100644
--- a/Kernel/Net/Socket.h
+++ b/Kernel/Net/Socket.h
@@ -58,9 +58,9 @@ class Socket : public File {
bool is_shut_down_for_reading() const { return m_shut_down_for_reading; }
enum class SetupState {
- Unstarted, // we haven't tried to set the socket up yet
+ Unstarted, // we haven't tried to set the socket up yet
InProgress, // we're in the process of setting things up - for TCP maybe we've sent a SYN packet
- Completed, // the setup process is complete, but not necessarily successful
+ Completed, // the setup process is complete, but not necessarily successful
};
enum class Role : u8 {
@@ -126,6 +126,7 @@ class Socket : public File {
// ^File
virtual KResultOr<size_t> read(FileDescription&, size_t, u8*, size_t) override final;
virtual KResultOr<size_t> write(FileDescription&, size_t, const u8*, size_t) override final;
+ virtual KResult stat(::stat&) const override;
virtual String absolute_path(const FileDescription&) const override = 0;
bool has_receive_timeout() const { return m_receive_timeout.tv_sec || m_receive_timeout.tv_usec; }
@@ -144,8 +145,8 @@ class Socket : public File {
virtual const char* class_name() const override { return "Socket"; }
- virtual void shut_down_for_reading() {}
- virtual void shut_down_for_writing() {}
+ virtual void shut_down_for_reading() { }
+ virtual void shut_down_for_writing() { }
Role m_role { Role::None };
@@ -175,10 +176,10 @@ class Socket : public File {
NonnullRefPtrVector<Socket> m_pending;
};
-template <typename SocketType>
+template<typename SocketType>
class SocketHandle {
public:
- SocketHandle() {}
+ SocketHandle() { }
SocketHandle(NonnullRefPtr<SocketType>&& socket)
: m_socket(move(socket))
|
315c95a1ce52b3121a9993f25608354ac9a806e6
|
2024-01-24 16:37:03
|
Sam Atkins
|
hackstudio: Replace custom recent-project management with the LibGUI one
| false
|
Replace custom recent-project management with the LibGUI one
|
hackstudio
|
diff --git a/Userland/DevTools/HackStudio/HackStudioWidget.cpp b/Userland/DevTools/HackStudio/HackStudioWidget.cpp
index afe60febdcd8..4b49b973abd3 100644
--- a/Userland/DevTools/HackStudio/HackStudioWidget.cpp
+++ b/Userland/DevTools/HackStudio/HackStudioWidget.cpp
@@ -3,6 +3,7 @@
* Copyright (c) 2020-2022, Itamar S. <[email protected]>
* Copyright (c) 2023-2024, Abhishek R. <[email protected]>
* Copyright (c) 2020-2022, the SerenityOS developers.
+ * Copyright (c) 2024, Sam Atkins <[email protected]>
*
* SPDX-License-Identifier: BSD-2-Clause
*/
@@ -274,14 +275,7 @@ void HackStudioWidget::open_project(ByteString const& root_path)
LexicalPath::relative_path(absolute_new_path, m_project->root_path()));
};
- auto recent_projects = read_recent_projects();
- recent_projects.remove_all_matching([&](auto& p) { return p == absolute_root_path; });
- recent_projects.insert(0, absolute_root_path);
- if (recent_projects.size() > recent_projects_history_size)
- recent_projects.shrink(recent_projects_history_size);
-
- Config::write_string("HackStudio"sv, "Global"sv, "RecentProjects"sv, JsonArray(recent_projects).to_byte_string());
- update_recent_projects_submenu();
+ GUI::Application::the()->set_most_recently_open_file(absolute_root_path);
}
Vector<ByteString> HackStudioWidget::selected_file_paths() const
@@ -1403,29 +1397,6 @@ void HackStudioWidget::create_project_tab(GUI::Widget& parent)
};
}
-void HackStudioWidget::update_recent_projects_submenu()
-{
- if (!m_recent_projects_submenu)
- return;
-
- m_recent_projects_submenu->remove_all_actions();
- auto recent_projects = read_recent_projects();
-
- if (recent_projects.size() <= 1) {
- auto empty_action = GUI::Action::create("(No recently open files)", [](auto&) {});
- empty_action->set_enabled(false);
- m_recent_projects_submenu->add_action(empty_action);
- return;
- }
-
- for (size_t i = 1; i < recent_projects.size(); i++) {
- auto project_path = recent_projects[i];
- m_recent_projects_submenu->add_action(GUI::Action::create(recent_projects[i], [this, project_path](auto&) {
- open_project(project_path);
- }));
- }
-}
-
ErrorOr<void> HackStudioWidget::create_file_menu(GUI::Window& window)
{
auto file_menu = window.add_menu("&File"_string);
@@ -1450,8 +1421,10 @@ ErrorOr<void> HackStudioWidget::create_file_menu(GUI::Window& window)
{
auto icon = TRY(Gfx::Bitmap::load_from_file("/res/icons/16x16/open-recent.png"sv));
m_recent_projects_submenu->set_icon(icon);
+ m_recent_projects_submenu->add_recent_files_list(
+ [this](GUI::Action& action) { open_project(action.text()); },
+ GUI::Menu::AddTrailingSeparator::No);
}
- update_recent_projects_submenu();
file_menu->add_action(*m_save_action);
file_menu->add_action(*m_save_as_action);
file_menu->add_separator();
diff --git a/Userland/DevTools/HackStudio/HackStudioWidget.h b/Userland/DevTools/HackStudio/HackStudioWidget.h
index 0a92dbb6fef9..17583616bc86 100644
--- a/Userland/DevTools/HackStudio/HackStudioWidget.h
+++ b/Userland/DevTools/HackStudio/HackStudioWidget.h
@@ -2,6 +2,7 @@
* Copyright (c) 2018-2020, Andreas Kling <[email protected]>
* Copyright (c) 2020-2022, Itamar S. <[email protected]>
* Copyright (c) 2020-2021, the SerenityOS developers.
+ * Copyright (c) 2024, Sam Atkins <[email protected]>
*
* SPDX-License-Identifier: BSD-2-Clause
*/
@@ -86,8 +87,6 @@ class HackStudioWidget : public GUI::Widget {
void update_window_title();
private:
- static constexpr size_t recent_projects_history_size = 15;
-
static ByteString get_full_path_of_serenity_source(ByteString const& file);
ByteString get_absolute_path(ByteString const&) const;
Vector<ByteString> selected_file_paths() const;
@@ -149,7 +148,6 @@ class HackStudioWidget : public GUI::Widget {
void create_toolbar(GUI::Widget& parent);
ErrorOr<void> create_action_tab(GUI::Widget& parent);
ErrorOr<void> create_file_menu(GUI::Window&);
- void update_recent_projects_submenu();
ErrorOr<void> create_edit_menu(GUI::Window&);
void create_build_menu(GUI::Window&);
ErrorOr<void> create_view_menu(GUI::Window&);
diff --git a/Userland/DevTools/HackStudio/main.cpp b/Userland/DevTools/HackStudio/main.cpp
index d9de69efbbb3..953d0b49448c 100644
--- a/Userland/DevTools/HackStudio/main.cpp
+++ b/Userland/DevTools/HackStudio/main.cpp
@@ -42,6 +42,7 @@ ErrorOr<int> serenity_main(Main::Arguments arguments)
TRY(Core::System::pledge("stdio recvfd sendfd tty rpath cpath wpath proc exec unix fattr thread ptrace"));
auto app = TRY(GUI::Application::create(arguments));
+ app->set_config_domain("HackStudio"_string);
Config::pledge_domains({ "HackStudio", "Terminal", "FileManager" });
auto window = GUI::Window::construct();
|
f22322a06c19af9c2a9bab5e7454c425873c249c
|
2020-01-02 08:39:56
|
joshua stein
|
libc: move in_addr and sockaddr_in to netinet/in.h
| false
|
move in_addr and sockaddr_in to netinet/in.h
|
libc
|
diff --git a/Libraries/LibC/netinet/in.h b/Libraries/LibC/netinet/in.h
index fa342e3000c6..c44895b0c503 100644
--- a/Libraries/LibC/netinet/in.h
+++ b/Libraries/LibC/netinet/in.h
@@ -13,4 +13,15 @@ in_addr_t inet_addr(const char*);
#define IP_TTL 2
+struct in_addr {
+ uint32_t s_addr;
+};
+
+struct sockaddr_in {
+ uint16_t sin_family;
+ uint16_t sin_port;
+ struct in_addr sin_addr;
+ char sin_zero[8];
+};
+
__END_DECLS
diff --git a/Libraries/LibC/sys/socket.h b/Libraries/LibC/sys/socket.h
index af98d67d05b1..6bbbd3cca1ac 100644
--- a/Libraries/LibC/sys/socket.h
+++ b/Libraries/LibC/sys/socket.h
@@ -35,17 +35,6 @@ struct sockaddr {
char sa_data[14];
};
-struct in_addr {
- uint32_t s_addr;
-};
-
-struct sockaddr_in {
- uint16_t sin_family;
- uint16_t sin_port;
- struct in_addr sin_addr;
- char sin_zero[8];
-};
-
struct ucred {
pid_t pid;
uid_t uid;
|
566870b2bd4cf627dfae6573eae765cf1794fa58
|
2024-11-11 21:36:20
|
Pavel Shliak
|
libweb: Reduce PaintTextShadow struct from 72 to 64 bytes
| false
|
Reduce PaintTextShadow struct from 72 to 64 bytes
|
libweb
|
diff --git a/Libraries/LibWeb/Painting/Command.h b/Libraries/LibWeb/Painting/Command.h
index d02bd9dd5325..fca910767112 100644
--- a/Libraries/LibWeb/Painting/Command.h
+++ b/Libraries/LibWeb/Painting/Command.h
@@ -158,13 +158,13 @@ struct PaintInnerBoxShadow {
};
struct PaintTextShadow {
- int blur_radius;
- Gfx::IntRect shadow_bounding_rect;
- Gfx::IntRect text_rect;
NonnullRefPtr<Gfx::GlyphRun> glyph_run;
double glyph_run_scale { 1 };
- Color color;
+ Gfx::IntRect shadow_bounding_rect;
+ Gfx::IntRect text_rect;
Gfx::IntPoint draw_location;
+ int blur_radius;
+ Color color;
[[nodiscard]] Gfx::IntRect bounding_rect() const { return { draw_location, shadow_bounding_rect.size() }; }
void translate_by(Gfx::IntPoint const& offset) { draw_location.translate_by(offset); }
diff --git a/Libraries/LibWeb/Painting/DisplayListRecorder.cpp b/Libraries/LibWeb/Painting/DisplayListRecorder.cpp
index c8459328b42c..44385334af57 100644
--- a/Libraries/LibWeb/Painting/DisplayListRecorder.cpp
+++ b/Libraries/LibWeb/Painting/DisplayListRecorder.cpp
@@ -325,13 +325,13 @@ void DisplayListRecorder::paint_inner_box_shadow_params(PaintBoxShadowParams par
void DisplayListRecorder::paint_text_shadow(int blur_radius, Gfx::IntRect bounding_rect, Gfx::IntRect text_rect, Gfx::GlyphRun const& glyph_run, double glyph_run_scale, Color color, Gfx::IntPoint draw_location)
{
append(PaintTextShadow {
- .blur_radius = blur_radius,
- .shadow_bounding_rect = bounding_rect,
- .text_rect = text_rect,
.glyph_run = glyph_run,
.glyph_run_scale = glyph_run_scale,
- .color = color,
- .draw_location = draw_location });
+ .shadow_bounding_rect = bounding_rect,
+ .text_rect = text_rect,
+ .draw_location = draw_location,
+ .blur_radius = blur_radius,
+ .color = color });
}
void DisplayListRecorder::fill_rect_with_rounded_corners(Gfx::IntRect const& rect, Color color, Gfx::CornerRadius top_left_radius, Gfx::CornerRadius top_right_radius, Gfx::CornerRadius bottom_right_radius, Gfx::CornerRadius bottom_left_radius)
|
eb07668589385aee3088d9eac01fb53b1e223fe1
|
2021-09-20 02:23:35
|
Sam Atkins
|
libgfx: Add per-side overloads of Rect::inflate() and ::shrink()
| false
|
Add per-side overloads of Rect::inflate() and ::shrink()
|
libgfx
|
diff --git a/Userland/Libraries/LibGfx/Rect.h b/Userland/Libraries/LibGfx/Rect.h
index 878fd2392ecf..502fc0d67958 100644
--- a/Userland/Libraries/LibGfx/Rect.h
+++ b/Userland/Libraries/LibGfx/Rect.h
@@ -1,5 +1,6 @@
/*
* Copyright (c) 2018-2021, Andreas Kling <[email protected]>
+ * Copyright (c) 2021, Sam Atkins <[email protected]>
*
* SPDX-License-Identifier: BSD-2-Clause
*/
@@ -121,6 +122,14 @@ class Rect {
set_height(height() + h);
}
+ void inflate(T top, T right, T bottom, T left)
+ {
+ set_x(x() - left);
+ set_width(width() + left + right);
+ set_y(y() - top);
+ set_height(height() + top + bottom);
+ }
+
void inflate(Size<T> const& size)
{
set_x(x() - size.width() / 2);
@@ -137,6 +146,14 @@ class Rect {
set_height(height() - h);
}
+ void shrink(T top, T right, T bottom, T left)
+ {
+ set_x(x() + left);
+ set_width(width() - (left + right));
+ set_y(y() + top);
+ set_height(height() - (top + bottom));
+ }
+
void shrink(Size<T> const& size)
{
set_x(x() + size.width() / 2);
@@ -187,6 +204,13 @@ class Rect {
return rect;
}
+ [[nodiscard]] Rect<T> shrunken(T top, T right, T bottom, T left) const
+ {
+ Rect<T> rect = *this;
+ rect.shrink(top, right, bottom, left);
+ return rect;
+ }
+
[[nodiscard]] Rect<T> shrunken(Size<T> const& size) const
{
Rect<T> rect = *this;
@@ -201,6 +225,13 @@ class Rect {
return rect;
}
+ [[nodiscard]] Rect<T> inflated(T top, T right, T bottom, T left) const
+ {
+ Rect<T> rect = *this;
+ rect.inflate(top, right, bottom, left);
+ return rect;
+ }
+
[[nodiscard]] Rect<T> inflated(Size<T> const& size) const
{
Rect<T> rect = *this;
|
d60f8807e320762cbbc5f7bd72969e97c660598f
|
2022-12-25 20:28:58
|
Filiph Sandström
|
ladybird: Allow for setting the hompage through SettingsDialog
| false
|
Allow for setting the hompage through SettingsDialog
|
ladybird
|
diff --git a/Ladybird/SettingsDialog.cpp b/Ladybird/SettingsDialog.cpp
index 8ffae27c048e..f36542d83953 100644
--- a/Ladybird/SettingsDialog.cpp
+++ b/Ladybird/SettingsDialog.cpp
@@ -5,15 +5,44 @@
*/
#include "SettingsDialog.h"
+#include "Settings.h"
+#include <QCloseEvent>
+#include <QLabel>
+
+extern Browser::Settings* s_settings;
SettingsDialog::SettingsDialog(QMainWindow* window)
: m_window(window)
{
- m_layout = new QBoxLayout(QBoxLayout::Direction::TopToBottom, this);
+ m_layout = new QFormLayout;
+ m_homepage = new QLineEdit;
+ m_ok_button = new QPushButton("&Save");
+
+ m_layout->addWidget(new QLabel("Homepage"));
+ m_layout->addWidget(m_homepage);
+ m_layout->addWidget(m_ok_button);
+
+ m_homepage->setText(s_settings->homepage());
+
+ QObject::connect(m_ok_button, &QPushButton::released, this, [this] {
+ close();
+ });
setWindowTitle("Settings");
- resize(340, 400);
+ setFixedWidth(300);
setLayout(m_layout);
show();
setFocus();
}
+
+void SettingsDialog::closeEvent(QCloseEvent* event)
+{
+ save();
+ event->accept();
+}
+
+void SettingsDialog::save()
+{
+ // FIXME: Validate data.
+ s_settings->set_homepage(m_homepage->text());
+}
diff --git a/Ladybird/SettingsDialog.h b/Ladybird/SettingsDialog.h
index d303202d064c..710f2b84bc8d 100644
--- a/Ladybird/SettingsDialog.h
+++ b/Ladybird/SettingsDialog.h
@@ -4,9 +4,11 @@
* SPDX-License-Identifier: BSD-2-Clause
*/
-#include <QBoxLayout>
#include <QDialog>
+#include <QFormLayout>
+#include <QLineEdit>
#include <QMainWindow>
+#include <QPushButton>
#pragma once
@@ -15,7 +17,13 @@ class SettingsDialog : public QDialog {
public:
explicit SettingsDialog(QMainWindow* window);
+ void save();
+
+ virtual void closeEvent(QCloseEvent*) override;
+
private:
- QBoxLayout* m_layout;
+ QFormLayout* m_layout;
+ QPushButton* m_ok_button { nullptr };
+ QLineEdit* m_homepage { nullptr };
QMainWindow* m_window { nullptr };
};
|
a7316d36414f3487fd6f51899c682f8d84955006
|
2024-01-15 04:38:52
|
Shannon Booth
|
libjs: Update Temporal RoundDuration AO to some spec changes
| false
|
Update Temporal RoundDuration AO to some spec changes
|
libjs
|
diff --git a/Userland/Libraries/LibJS/Runtime/Temporal/Duration.cpp b/Userland/Libraries/LibJS/Runtime/Temporal/Duration.cpp
index f3a0112d9786..4337fbd9d333 100644
--- a/Userland/Libraries/LibJS/Runtime/Temporal/Duration.cpp
+++ b/Userland/Libraries/LibJS/Runtime/Temporal/Duration.cpp
@@ -1,6 +1,7 @@
/*
* Copyright (c) 2021-2023, Linus Groh <[email protected]>
* Copyright (c) 2021, Luke Wilde <[email protected]>
+ * Copyright (c) 2024, Shannon Booth <[email protected]>
*
* SPDX-License-Identifier: BSD-2-Clause
*/
@@ -1188,321 +1189,371 @@ ThrowCompletionOr<ZonedDateTime*> move_relative_zoned_date_time(VM& vm, ZonedDat
return MUST(create_temporal_zoned_date_time(vm, *intermediate_ns, zoned_date_time.time_zone(), zoned_date_time.calendar()));
}
-// 7.5.25 RoundDuration ( years, months, weeks, days, hours, minutes, seconds, milliseconds, microseconds, nanoseconds, increment, unit, roundingMode [ , relativeTo ] ), https://tc39.es/proposal-temporal/#sec-temporal-roundduration
-ThrowCompletionOr<RoundedDuration> round_duration(VM& vm, double years, double months, double weeks, double days, double hours, double minutes, double seconds, double milliseconds, double microseconds, double nanoseconds, u32 increment, StringView unit, StringView rounding_mode, Object* relative_to_object)
+// 7.5.27 RoundDuration ( years, months, weeks, days, hours, minutes, seconds, milliseconds, microseconds, nanoseconds, increment, unit, roundingMode [ , plainRelativeTo [ , calendarRec [ , zonedRelativeTo [ , timeZoneRec [ , precalculatedPlainDateTime ] ] ] ] ] ), https://tc39.es/proposal-temporal/#sec-temporal-roundduration
+// FIXME: Support calendarRec, zonedRelativeTo, timeZoneRec, precalculatedPlainDateTime
+ThrowCompletionOr<RoundedDuration> round_duration(VM& vm, double years, double months, double weeks, double days, double hours, double minutes, double seconds, double milliseconds, double microseconds, double nanoseconds, u32 increment, StringView unit, StringView rounding_mode, Object* plain_relative_to_object)
{
auto& realm = *vm.current_realm();
- Object* calendar = nullptr;
+ Object* calendar = nullptr; // FIXME: Should come from calendarRec
+
double fractional_seconds = 0;
+ double fractional_days = 0;
- // 1. If relativeTo is not present, set relativeTo to undefined.
- // NOTE: `relative_to_object` and `relative_to` in the various code paths below are all the same as far as the
- // spec is concerned, but the latter is more strictly typed for convenience.
- PlainDate* relative_to = nullptr;
+ // FIXME: 1. Assert: If either of plainRelativeTo or zonedRelativeTo are present and not undefined, calendarRec is not undefined.
+ // FIXME: 2. Assert: If zonedRelativeTo is present and not undefined, timeZoneRec is not undefined.
+
+ // 3. If plainRelativeTo is not present, set plainRelativeTo to undefined.
+ // NOTE: `plain_relative_to_object` and `plain_relative_to` in the various code paths below are all the same as far as the
+ // spec is concerned, but the latter is more strictly typed for convenience.
+ PlainDate* plain_relative_to = nullptr;
+
+ // FIXME: 4. If zonedRelativeTo is not present, set zonedRelativeTo to undefined.
+ ZonedDateTime* zoned_relative_to = nullptr;
+
+ // FIXME: 5. If precalculatedPlainDateTime is not present, set precalculatedPlainDateTime to undefined.
// FIXME: assuming "smallestUnit" as the option name here leads to confusing error messages in some cases:
// > new Temporal.Duration().total({ unit: "month" })
// Uncaught exception: [RangeError] month is not a valid value for option smallestUnit
- // 2. If unit is "year", "month", or "week", and relativeTo is undefined, then
- if (unit.is_one_of("year"sv, "month"sv, "week"sv) && !relative_to_object) {
- // a. Throw a RangeError exception.
- return vm.throw_completion<RangeError>(ErrorType::OptionIsNotValidValue, unit, "smallestUnit"sv);
+ // 6. If unit is "year", "month", or "week", then
+ if (unit.is_one_of("year"sv, "month"sv, "week"sv)) {
+ // a. If plainRelativeTo is undefined, throw a RangeError exception.
+ if (!plain_relative_to_object)
+ return vm.throw_completion<RangeError>(ErrorType::OptionIsNotValidValue, unit, "smallestUnit"sv);
+
+ // FIXME: b. Assert: CalendarMethodsRecordHasLookedUp(calendarRec, dateAdd) is true.
+ // FIXME: c. Assert: CalendarMethodsRecordHasLookedUp(calendarRec, dateUntil) is true.
}
- // 3. Let zonedRelativeTo be undefined.
- ZonedDateTime* zoned_relative_to = nullptr;
-
- // 4. If relativeTo is not undefined, then
- if (relative_to_object) {
- // a. If relativeTo has an [[InitializedTemporalZonedDateTime]] internal slot, then
- if (is<ZonedDateTime>(relative_to_object)) {
- auto* relative_to_zoned_date_time = static_cast<ZonedDateTime*>(relative_to_object);
-
- // i. Set zonedRelativeTo to relativeTo.
+ // FIXME: AD-HOC, should be coming from arguments given to this function.
+ if (plain_relative_to_object) {
+ if (is<ZonedDateTime>(plain_relative_to_object)) {
+ auto* relative_to_zoned_date_time = static_cast<ZonedDateTime*>(plain_relative_to_object);
zoned_relative_to = relative_to_zoned_date_time;
-
- // ii. Set relativeTo to ? ToTemporalDate(relativeTo).
- relative_to = TRY(to_temporal_date(vm, relative_to_object));
+ plain_relative_to = TRY(to_temporal_date(vm, plain_relative_to_object));
+ } else {
+ VERIFY(is<PlainDate>(plain_relative_to_object));
+ plain_relative_to = verify_cast<PlainDate>(plain_relative_to_object);
}
- // b. Else,
- else {
- // i. Assert: relativeTo has an [[InitializedTemporalDate]] internal slot.
- VERIFY(is<PlainDate>(relative_to_object));
-
- relative_to = static_cast<PlainDate*>(relative_to_object);
- }
-
- // c. Let calendar be relativeTo.[[Calendar]].
- calendar = &relative_to->calendar();
+ calendar = &plain_relative_to->calendar();
}
- // 5. Else,
- // a. NOTE: calendar will not be used below.
- // 6. If unit is one of "year", "month", "week", or "day", then
+ // 7. If unit is one of "year", "month", "week", or "day", then
if (unit.is_one_of("year"sv, "month"sv, "week"sv, "day"sv)) {
- // a. Let nanoseconds be ! TotalDurationNanoseconds(0, hours, minutes, seconds, milliseconds, microseconds, nanoseconds, 0).
- auto nanoseconds_bigint = total_duration_nanoseconds(0, hours, minutes, seconds, milliseconds, microseconds, Crypto::SignedBigInteger { nanoseconds }, 0);
- // b. Let intermediate be undefined.
- ZonedDateTime* intermediate = nullptr;
+ // a. Let nanoseconds be TotalDurationNanoseconds(hours, minutes, seconds, milliseconds, microseconds, nanoseconds).
+ // FIXME: We shouldn't be passing through 0 days and 0 offset digit
+ auto nanoseconds_bigint = total_duration_nanoseconds(0, hours, minutes, seconds, milliseconds, microseconds, Crypto::SignedBigInteger { nanoseconds }, 0);
- // c. If zonedRelativeTo is not undefined, then
+ // b. If zonedRelativeTo is not undefined, then
if (zoned_relative_to) {
- // i. Let intermediate be ? MoveRelativeZonedDateTime(zonedRelativeTo, years, months, weeks, days).
- intermediate = TRY(move_relative_zoned_date_time(vm, *zoned_relative_to, years, months, weeks, days));
- }
+ // i. Let intermediate be ? MoveRelativeZonedDateTime(zonedRelativeTo, calendarRec, timeZoneRec, years, months, weeks, days, precalculatedPlainDateTime).
+ // FIXME: Pass through calendarRecord, timeZoneRec and precalculatedPlainDateTime
+ auto* intermediate = TRY(move_relative_zoned_date_time(vm, *zoned_relative_to, years, months, weeks, days));
- // d. Let result be ? NanosecondsToDays(nanoseconds, intermediate).
- auto result = TRY(nanoseconds_to_days(vm, nanoseconds_bigint, intermediate));
+ // ii. Let result be ? NanosecondsToDays(nanoseconds, intermediate, timeZoneRec).
+ // FIXME: Pass through timeZoneRec
+ auto result = TRY(nanoseconds_to_days(vm, nanoseconds_bigint, intermediate));
- // e. Set days to days + result.[[Days]] + result.[[Nanoseconds]] / result.[[DayLength]].
- auto nanoseconds_division_result = result.nanoseconds.divided_by(Crypto::UnsignedBigInteger { result.day_length });
- days += result.days + nanoseconds_division_result.quotient.to_double() + nanoseconds_division_result.remainder.to_double() / result.day_length;
+ // iii. Let fractionalDays be days + result.[[Days]] + result.[[Nanoseconds]] / result.[[DayLength]].
+ auto nanoseconds_division_result = result.nanoseconds.divided_by(Crypto::UnsignedBigInteger { result.day_length });
+ fractional_days = days + result.days + nanoseconds_division_result.quotient.to_double() + nanoseconds_division_result.remainder.to_double() / result.day_length;
+ }
+ // c. Else,
+ else {
+ // i. Let fractionalDays be days + nanoseconds / nsPerDay.
+ auto nanoseconds_division_result = nanoseconds_bigint.divided_by(ns_per_day_bigint);
+ fractional_days = days + nanoseconds_division_result.quotient.to_double() + (nanoseconds_division_result.remainder.to_double() / ns_per_day);
+ }
- // f. Set hours, minutes, seconds, milliseconds, microseconds, and nanoseconds to 0.
+ // d. Set days, hours, minutes, seconds, milliseconds, microseconds, and nanoseconds to 0.
+ days = 0;
hours = 0;
minutes = 0;
seconds = 0;
milliseconds = 0;
microseconds = 0;
nanoseconds = 0;
+
+ // e. Assert: fractionalSeconds is not used below.
}
- // 7. Else,
+ // 8. Else,
else {
// a. Let fractionalSeconds be nanoseconds × 10^-9 + microseconds × 10^-6 + milliseconds × 10^-3 + seconds.
fractional_seconds = nanoseconds * 0.000000001 + microseconds * 0.000001 + milliseconds * 0.001 + seconds;
+
+ // b. Assert: fractionalDays is not used below.
}
- // 8. Let remainder be undefined.
- double remainder = 0;
+ // 9. Let total be unset.
+ double total = 0;
- // 9. If unit is "year", then
+ // 10. If unit is "year", then
if (unit == "year"sv) {
- VERIFY(relative_to);
+ VERIFY(plain_relative_to);
// a. Let yearsDuration be ! CreateTemporalDuration(years, 0, 0, 0, 0, 0, 0, 0, 0, 0).
auto* years_duration = MUST(create_temporal_duration(vm, years, 0, 0, 0, 0, 0, 0, 0, 0, 0));
- // b. Let dateAdd be ? GetMethod(calendar, "dateAdd").
+ // FIXME: b. Let yearsLater be ? AddDate(calendarRec, plainRelativeTo, yearsDuration).
auto date_add = TRY(Value(calendar).get_method(vm, vm.names.dateAdd));
+ auto* years_later = TRY(calendar_date_add(vm, *calendar, plain_relative_to, *years_duration, nullptr, date_add));
- // c. Let yearsLater be ? CalendarDateAdd(calendar, relativeTo, yearsDuration, undefined, dateAdd).
- auto* years_later = TRY(calendar_date_add(vm, *calendar, relative_to, *years_duration, nullptr, date_add));
-
- // d. Let yearsMonthsWeeks be ! CreateTemporalDuration(years, months, weeks, 0, 0, 0, 0, 0, 0, 0).
+ // c. Let yearsMonthsWeeks be ! CreateTemporalDuration(years, months, weeks, 0, 0, 0, 0, 0, 0, 0).
auto* years_months_weeks = MUST(create_temporal_duration(vm, years, months, weeks, 0, 0, 0, 0, 0, 0, 0));
- // e. Let yearsMonthsWeeksLater be ? CalendarDateAdd(calendar, relativeTo, yearsMonthsWeeks, undefined, dateAdd).
- auto* years_months_weeks_later = TRY(calendar_date_add(vm, *calendar, relative_to, *years_months_weeks, nullptr, date_add));
+ // FIXME: d. Let yearsMonthsWeeksLater be ? AddDate(calendarRec, plainRelativeTo, yearsMonthsWeeks).
+ auto* years_months_weeks_later = TRY(calendar_date_add(vm, *calendar, plain_relative_to, *years_months_weeks, nullptr, date_add));
- // f. Let monthsWeeksInDays be DaysUntil(yearsLater, yearsMonthsWeeksLater).
+ // e. Let monthsWeeksInDays be DaysUntil(yearsLater, yearsMonthsWeeksLater).
auto months_weeks_in_days = days_until(*years_later, *years_months_weeks_later);
- // g. Set relativeTo to yearsLater.
- relative_to = years_later;
+ // f. Set plainRelativeTo to yearsLater.
+ plain_relative_to = years_later;
- // h. Let days be days + monthsWeeksInDays.
- days += months_weeks_in_days;
+ // g. Set fractionalDays to fractionalDays + monthsWeeksInDays.
+ fractional_days = fractional_days + months_weeks_in_days;
- // i. Let wholeDaysDuration be ? CreateTemporalDuration(0, 0, 0, truncate(days), 0, 0, 0, 0, 0, 0).
- auto* whole_days_duration = TRY(create_temporal_duration(vm, 0, 0, 0, trunc(days), 0, 0, 0, 0, 0, 0));
+ // h. Let isoResult be ! AddISODate(plainRelativeTo.[[ISOYear]]. plainRelativeTo.[[ISOMonth]], plainRelativeTo.[[ISODay]], 0, 0, 0, truncate(fractionalDays), "constrain").
+ auto iso_result = MUST(add_iso_date(vm, plain_relative_to->iso_year(), plain_relative_to->iso_month(), plain_relative_to->iso_day(), 0, 0, 0, trunc(fractional_days), "constrain"sv));
- // j. Let wholeDaysLater be ? CalendarDateAdd(calendar, relativeTo, wholeDaysDuration, undefined, dateAdd).
- auto* whole_days_later = TRY(calendar_date_add(vm, *calendar, relative_to, *whole_days_duration, nullptr, date_add));
+ // i. Let wholeDaysLater be ? CreateTemporalDate(isoResult.[[Year]], isoResult.[[Month]], isoResult.[[Day]], calendarRec.[[Receiver]]).
+ // FIXME: Pass through receiver from calendarRec
+ auto* whole_days_later = TRY(create_temporal_date(vm, iso_result.year, iso_result.month, iso_result.day, *calendar));
- // k. Let untilOptions be OrdinaryObjectCreate(null).
+ // j. Let untilOptions be OrdinaryObjectCreate(null).
auto until_options = Object::create(realm, nullptr);
- // l. Perform ! CreateDataPropertyOrThrow(untilOptions, "largestUnit", "year").
+ // k. Perform ! CreateDataPropertyOrThrow(untilOptions, "largestUnit", "year").
MUST(until_options->create_data_property_or_throw(vm.names.largestUnit, PrimitiveString::create(vm, "year"_string)));
- // m. Let timePassed be ? CalendarDateUntil(calendar, relativeTo, wholeDaysLater, untilOptions).
- auto* time_passed = TRY(calendar_date_until(vm, *calendar, relative_to, whole_days_later, *until_options));
+ // l. Let timePassed be ? DifferenceDate(calendarRec, plainRelativeTo, wholeDaysLater, untilOptions).
+ // FIXME: Pass through calendarRec
+ auto time_passed = TRY(difference_date(vm, *calendar, *plain_relative_to, *whole_days_later, *until_options));
- // n. Let yearsPassed be timePassed.[[Years]].
+ // m. Let yearsPassed be timePassed.[[Years]].
auto years_passed = time_passed->years();
- // o. Set years to years + yearsPassed.
+ // n. Set years to years + yearsPassed.
years += years_passed;
- // p. Let oldRelativeTo be relativeTo.
- auto* old_relative_to = relative_to;
-
- // q. Let yearsDuration be ! CreateTemporalDuration(yearsPassed, 0, 0, 0, 0, 0, 0, 0, 0, 0).
+ // o. Let yearsDuration be ! CreateTemporalDuration(yearsPassed, 0, 0, 0, 0, 0, 0, 0, 0, 0).
years_duration = MUST(create_temporal_duration(vm, years_passed, 0, 0, 0, 0, 0, 0, 0, 0, 0));
- // r. Set relativeTo to ? CalendarDateAdd(calendar, relativeTo, yearsDuration, undefined, dateAdd).
- relative_to = TRY(calendar_date_add(vm, *calendar, relative_to, *years_duration, nullptr, date_add));
+ // p. Let moveResult be ? MoveRelativeDate(calendarRec, plainRelativeTo, yearsDuration).
+ // FIXME: Pass through calendarRec instead of date_add
+ auto move_result = TRY(move_relative_date(vm, *calendar, *plain_relative_to, *years_duration, date_add));
- // s. Let daysPassed be DaysUntil(oldRelativeTo, relativeTo).
- auto days_passed = days_until(*old_relative_to, *relative_to);
+ // q. Set plainRelativeTo to moveResult.[[RelativeTo]].
+ auto plain_relative_to = move_result.relative_to;
- // t. Set days to days - daysPassed.
- days -= days_passed;
+ // r. Let daysPassed be moveResult.[[Days]].
+ auto days_passed = move_result.days;
- // u. If days < 0, let sign be -1; else, let sign be 1.
- auto sign = days < 0 ? -1 : 1;
+ // s. Set fractionalDays to fractionalDays - daysPassed.
+ fractional_days -= days_passed;
- // v. Let oneYear be ! CreateTemporalDuration(sign, 0, 0, 0, 0, 0, 0, 0, 0, 0).
+ // t. If fractionalDays < 0, let sign be -1; else, let sign be 1.
+ auto sign = fractional_days < 0 ? -1 : 1;
+
+ // u. Let oneYear be ! CreateTemporalDuration(sign, 0, 0, 0, 0, 0, 0, 0, 0, 0).
auto* one_year = MUST(create_temporal_duration(vm, sign, 0, 0, 0, 0, 0, 0, 0, 0, 0));
- // w. Let moveResult be ? MoveRelativeDate(calendar, relativeTo, oneYear, dateAdd).
- auto move_result = TRY(move_relative_date(vm, *calendar, *relative_to, *one_year, date_add));
+ // v. Set moveResult to ? MoveRelativeDate(calendarRec, plainRelativeTo, oneYear).
+ // FIXME:: pass through calendarRec
+ move_result = TRY(move_relative_date(vm, *calendar, *plain_relative_to, *one_year, date_add));
- // x. Let oneYearDays be moveResult.[[Days]].
+ // w. Let oneYearDays be moveResult.[[Days]].
auto one_year_days = move_result.days;
- // y. Let fractionalYears be years + days / abs(oneYearDays).
- auto fractional_years = years + days / fabs(one_year_days);
+ // x. If oneYearDays = 0, throw a RangeError exception.
+ if (one_year_days == 0)
+ return vm.throw_completion<RangeError>(ErrorType::TemporalInvalidCalendarFunctionResult, "dateAdd", "result implying a year is zero days long");
+
+ // y. Let fractionalYears be years + fractionalDays / abs(oneYearDays).
+ auto fractional_years = years + fractional_days / fabs(one_year_days);
// z. Set years to RoundNumberToIncrement(fractionalYears, increment, roundingMode).
years = round_number_to_increment(fractional_years, increment, rounding_mode);
- // aa. Set remainder to fractionalYears - years.
- remainder = fractional_years - years;
+ // aa. Set total to fractionalYears.
+ total = fractional_years;
- // ab. Set months, weeks, and days to 0.
+ // ab. Set months and weeks to 0.
months = 0;
weeks = 0;
- days = 0;
}
// 10. Else if unit is "month", then
else if (unit == "month"sv) {
- VERIFY(relative_to);
+ VERIFY(plain_relative_to);
// a. Let yearsMonths be ! CreateTemporalDuration(years, months, 0, 0, 0, 0, 0, 0, 0, 0).
auto* years_months = MUST(create_temporal_duration(vm, years, months, 0, 0, 0, 0, 0, 0, 0, 0));
- // b. Let dateAdd be ? GetMethod(calendar, "dateAdd").
+ // FIXME: b. Let yearsMonthsLater be ? AddDate(calendarRec, plainRelativeTo, yearsMonths).
auto date_add = TRY(Value(calendar).get_method(vm, vm.names.dateAdd));
+ auto* years_months_later = TRY(calendar_date_add(vm, *calendar, plain_relative_to, *years_months, nullptr, date_add));
- // c. Let yearsMonthsLater be ? CalendarDateAdd(calendar, relativeTo, yearsMonths, undefined, dateAdd).
- auto* years_months_later = TRY(calendar_date_add(vm, *calendar, relative_to, *years_months, nullptr, date_add));
-
- // d. Let yearsMonthsWeeks be ! CreateTemporalDuration(years, months, weeks, 0, 0, 0, 0, 0, 0, 0).
+ // c. Let yearsMonthsWeeks be ! CreateTemporalDuration(years, months, weeks, 0, 0, 0, 0, 0, 0, 0).
auto* years_months_weeks = MUST(create_temporal_duration(vm, years, months, weeks, 0, 0, 0, 0, 0, 0, 0));
- // e. Let yearsMonthsWeeksLater be ? CalendarDateAdd(calendar, relativeTo, yearsMonthsWeeks, undefined, dateAdd).
- auto* years_months_weeks_later = TRY(calendar_date_add(vm, *calendar, relative_to, *years_months_weeks, nullptr, date_add));
+ // FIXME: d. Let yearsMonthsWeeksLater be ? AddDate(calendarRec, plainRelativeTo, yearsMonthsWeeks).
+ auto* years_months_weeks_later = TRY(calendar_date_add(vm, *calendar, plain_relative_to, *years_months_weeks, nullptr, date_add));
- // f. Let weeksInDays be DaysUntil(yearsMonthsLater, yearsMonthsWeeksLater).
+ // e. Let weeksInDays be DaysUntil(yearsMonthsLater, yearsMonthsWeeksLater).
auto weeks_in_days = days_until(*years_months_later, *years_months_weeks_later);
- // g. Set relativeTo to yearsMonthsLater.
- relative_to = years_months_later;
+ // f. Set plainRelativeTo to yearsMonthsLater.
+ plain_relative_to = years_months_later;
- // h. Let days be days + weeksInDays.
- days += weeks_in_days;
+ // g. Set fractionalDays to fractionalDays + weeksInDays.
+ fractional_days += weeks_in_days;
- // i. If days < 0, let sign be -1; else, let sign be 1.
- auto sign = days < 0 ? -1 : 1;
+ // h. Let isoResult be ! AddISODate(plainRelativeTo.[[ISOYear]], plainRelativeTo.[[ISOMonth]], plainRelativeTo.[[ISODay]], 0, 0, 0, truncate(fractionalDays), "constrain").
+ auto iso_result = MUST(add_iso_date(vm, plain_relative_to->iso_year(), plain_relative_to->iso_month(), plain_relative_to->iso_day(), 0, 0, 0, trunc(fractional_days), "constrain"sv));
- // j. Let oneMonth be ! CreateTemporalDuration(0, sign, 0, 0, 0, 0, 0, 0, 0, 0).
- auto* one_month = MUST(create_temporal_duration(vm, 0, sign, 0, 0, 0, 0, 0, 0, 0, 0));
+ // i. Let wholeDaysLater be ? CreateTemporalDate(isoResult.[[Year]], isoResult.[[Month]], isoResult.[[Day]], calendarRec.[[Receiver]]).
+ // FIXME: Pass through calendarRec
+ auto* whole_days_later = TRY(create_temporal_date(vm, iso_result.year, iso_result.month, iso_result.day, *calendar)); // FIXME: receiver
- // k. Let moveResult be ? MoveRelativeDate(calendar, relativeTo, oneMonth, dateAdd).
- auto move_result = TRY(move_relative_date(vm, *calendar, *relative_to, *one_month, date_add));
+ // j. Let untilOptions be OrdinaryObjectCreate(null).
+ auto until_options = Object::create(realm, nullptr);
- // l. Set relativeTo to moveResult.[[RelativeTo]].
- relative_to = move_result.relative_to.cell();
+ // k. Perform ! CreateDataPropertyOrThrow(untilOptions, "largestUnit", "month").
+ MUST(until_options->create_data_property_or_throw(vm.names.largestUnit, PrimitiveString::create(vm, "month"_string)));
- // m. Let oneMonthDays be moveResult.[[Days]].
- auto one_month_days = move_result.days;
+ // l. Let timePassed be ? DifferenceDate(calendarRec, plainRelativeTo, wholeDaysLater, untilOptions).
+ // FIXME: Pass through receiver from calendarRec
+ auto time_passed = TRY(difference_date(vm, *calendar, *plain_relative_to, *whole_days_later, *until_options));
- // n. Repeat, while abs(days) ≥ abs(oneMonthDays),
- while (fabs(days) >= fabs(one_month_days)) {
- // i. Set months to months + sign.
- months += sign;
+ // m. Let monthsPassed be timePassed.[[Months]].
+ auto months_passed = time_passed->months();
- // ii. Set days to days - oneMonthDays.
- days -= one_month_days;
+ // n. Set months to months + monthsPassed.
+ months += months_passed;
- // iii. Set moveResult to ? MoveRelativeDate(calendar, relativeTo, oneMonth, dateAdd).
- move_result = TRY(move_relative_date(vm, *calendar, *relative_to, *one_month, date_add));
+ // o. Let monthsPassedDuration be ! CreateTemporalDuration(0, monthsPassed, 0, 0, 0, 0, 0, 0, 0, 0).
+ auto* months_passed_duration = MUST(create_temporal_duration(vm, 0, months_passed, 0, 0, 0, 0, 0, 0, 0, 0));
- // iv. Set relativeTo to moveResult.[[RelativeTo]].
- relative_to = move_result.relative_to.cell();
+ // p. Let moveResult be ? MoveRelativeDate(calendarRec, plainRelativeTo, monthsPassedDuration).
+ // FIXME: Pass through calendarRec
+ auto move_result = TRY(move_relative_date(vm, *calendar, *plain_relative_to, *months_passed_duration, date_add));
- // v. Set oneMonthDays to moveResult.[[Days]].
- one_month_days = move_result.days;
- }
+ // q. Set plainRelativeTo to moveResult.[[RelativeTo]].
+ plain_relative_to = move_result.relative_to;
+
+ // r. Let daysPassed be moveResult.[[Days]].
+ auto days_passed = move_result.days;
+
+ // s. Set fractionalDays to fractionalDays - daysPassed.
+ fractional_days -= days_passed;
- // o. Let fractionalMonths be months + days / abs(oneMonthDays).
- auto fractional_months = months + days / fabs(one_month_days);
+ // t. If fractionalDays < 0, let sign be -1; else, let sign be 1.
+ auto sign = fractional_days < 0 ? -1 : 1;
+
+ // u. Let oneMonth be ! CreateTemporalDuration(0, sign, 0, 0, 0, 0, 0, 0, 0, 0).
+ auto* one_month = MUST(create_temporal_duration(vm, 0, sign, 0, 0, 0, 0, 0, 0, 0, 0));
- // p. Set months to RoundNumberToIncrement(fractionalMonths, increment, roundingMode).
+ // v. Let moveResult be ? MoveRelativeDate(calendarRec, plainRelativeTo, oneMonth).
+ // FIXME: spec bug, this should be set.
+ move_result = TRY(move_relative_date(vm, *calendar, *plain_relative_to, *one_month, date_add));
+
+ // w. Let oneMonthDays be moveResult.[[Days]].
+ auto one_month_days = move_result.days;
+
+ // x. If oneMonthDays = 0, throw a RangeError exception.
+ if (one_month_days == 0)
+ return vm.throw_completion<RangeError>(ErrorType::TemporalInvalidCalendarFunctionResult, "dateAdd", "result implying a month is zero days long");
+
+ // y. Let fractionalMonths be months + fractionalDays / abs(oneMonthDays).
+ auto fractional_months = months + fractional_days / fabs(one_month_days);
+
+ // z. Set months to RoundNumberToIncrement(fractionalMonths, increment, roundingMode).
months = round_number_to_increment(fractional_months, increment, rounding_mode);
- // q. Set remainder to fractionalMonths - months.
- remainder = fractional_months - months;
+ // aa. Set total to fractionalMonths.
+ total = fractional_months;
- // r. Set weeks and days to 0.
+ // ab. Set weeks to 0.
weeks = 0;
- days = 0;
}
// 11. Else if unit is "week", then
else if (unit == "week"sv) {
- VERIFY(relative_to);
+ VERIFY(plain_relative_to);
- // a. If days < 0, let sign be -1; else, let sign be 1.
- auto sign = days < 0 ? -1 : 1;
+ // a. Let isoResult be ! AddISODate(plainRelativeTo.[[ISOYear]], plainRelativeTo.[[ISOMonth]], plainRelativeTo.[[ISODay]], 0, 0, 0, truncate(fractionalDays), "constrain").
+ auto iso_result = MUST(add_iso_date(vm, plain_relative_to->iso_year(), plain_relative_to->iso_month(), plain_relative_to->iso_day(), 0, 0, 0, trunc(fractional_days), "constrain"sv));
- // b. Let oneWeek be ! CreateTemporalDuration(0, 0, sign, 0, 0, 0, 0, 0, 0, 0).
- auto* one_week = MUST(create_temporal_duration(vm, 0, 0, sign, 0, 0, 0, 0, 0, 0, 0));
+ // b. Let wholeDaysLater be ? CreateTemporalDate(isoResult.[[Year]], isoResult.[[Month]], isoResult.[[Day]], calendarRec.[[Receiver]]).
+ // FIXME: Pass through receiver from calendarRec
+ auto* whole_days_later = TRY(create_temporal_date(vm, iso_result.year, iso_result.month, iso_result.day, *calendar));
+
+ // c. Let untilOptions be OrdinaryObjectCreate(null).
+ auto until_options = Object::create(realm, nullptr);
- // c. Let dateAdd be ? GetMethod(calendar, "dateAdd").
+ // d. Perform ! CreateDataPropertyOrThrow(untilOptions, "largestUnit", "week").
+ MUST(until_options->create_data_property_or_throw(vm.names.largestUnit, PrimitiveString::create(vm, "month"_string)));
+
+ // e. Let timePassed be ? DifferenceDate(calendarRec, plainRelativeTo, wholeDaysLater, untilOptions).
+ // FIXME: Pass through calendarRec
+ auto time_passed = TRY(difference_date(vm, *calendar, *plain_relative_to, *whole_days_later, *until_options));
+
+ // f. Let weeksPassed be timePassed.[[Weeks]].
+ auto weeks_passed = time_passed->weeks();
+
+ // g. Set weeks to weeks + weeksPassed.
+ weeks += weeks_passed;
+
+ // h. Let weeksPassedDuration be ! CreateTemporalDuration(0, 0, weeksPassed, 0, 0, 0, 0, 0, 0, 0).
+ auto* weeks_passed_duration = MUST(create_temporal_duration(vm, 0, 0, weeks_passed, 0, 0, 0, 0, 0, 0, 0));
+
+ // FIXME: i. Let moveResult be ? MoveRelativeDate(calendarRec, plainRelativeTo, weeksPassedDuration).
auto date_add = TRY(Value(calendar).get_method(vm, vm.names.dateAdd));
+ auto move_result = TRY(move_relative_date(vm, *calendar, *plain_relative_to, *weeks_passed_duration, date_add));
- // d. Let moveResult be ? MoveRelativeDate(calendar, relativeTo, oneWeek, dateAdd).
- auto move_result = TRY(move_relative_date(vm, *calendar, *relative_to, *one_week, date_add));
+ // j. Set plainRelativeTo to moveResult.[[RelativeTo]].
+ plain_relative_to = move_result.relative_to;
- // e. Set relativeTo to moveResult.[[RelativeTo]].
- relative_to = move_result.relative_to.cell();
+ // k. Let daysPassed be moveResult.[[Days]].
+ auto days_passed = move_result.days;
- // f. Let oneWeekDays be moveResult.[[Days]].
- auto one_week_days = move_result.days;
+ // l. Set fractionalDays to fractionalDays - daysPassed.
+ fractional_days -= days_passed;
- // g. Repeat, while abs(days) ≥ abs(oneWeekDays),
- while (fabs(days) >= fabs(one_week_days)) {
- // i. Set weeks to weeks + sign.
- weeks += sign;
+ // m. If fractionalDays < 0, let sign be -1; else, let sign be 1.
+ auto sign = fractional_days < 0 ? -1 : 1;
- // ii. Set days to days - oneWeekDays.
- days -= one_week_days;
+ // n. Let oneWeek be ! CreateTemporalDuration(0, 0, sign, 0, 0, 0, 0, 0, 0, 0).
+ auto* one_week = MUST(create_temporal_duration(vm, 0, 0, sign, 0, 0, 0, 0, 0, 0, 0));
- // iii. Set moveResult to ? MoveRelativeDate(calendar, relativeTo, oneWeek, dateAdd).
- move_result = TRY(move_relative_date(vm, *calendar, *relative_to, *one_week, date_add));
+ // o. Let moveResult be ? MoveRelativeDate(calendarRec, plainRelativeTo, oneWeek).
+ // FIXME: spec bug, should be set
+ move_result = TRY(move_relative_date(vm, *calendar, *plain_relative_to, *one_week, date_add));
- // iv. Set relativeTo to moveResult.[[RelativeTo]].
- relative_to = move_result.relative_to.cell();
+ // p. Let oneWeekDays be moveResult.[[Days]].
+ auto one_week_days = move_result.days;
- // v. Set oneWeekDays to moveResult.[[Days]].
- one_week_days = move_result.days;
- }
+ // q. If oneWeekDays = 0, throw a RangeError exception.
+ if (one_week_days == 0)
+ return vm.throw_completion<RangeError>(ErrorType::TemporalInvalidCalendarFunctionResult, "dateAdd", "result implying a month is zero days long");
- // h. Let fractionalWeeks be weeks + days / abs(oneWeekDays).
- auto fractional_weeks = weeks + days / fabs(one_week_days);
+ // r. Let fractionalWeeks be weeks + fractionalDays / abs(oneWeekDays).
+ auto fractional_weeks = weeks + fractional_days / fabs(one_week_days);
- // i. Set weeks to RoundNumberToIncrement(fractionalWeeks, increment, roundingMode).
+ // s. Set weeks to RoundNumberToIncrement(fractionalWeeks, increment, roundingMode).
weeks = round_number_to_increment(fractional_weeks, increment, rounding_mode);
- // j. Set remainder to fractionalWeeks - weeks.
- remainder = fractional_weeks - weeks;
-
- // k. Set days to 0.
- days = 0;
+ // t. Set total to fractionalWeeks.
+ total = fractional_weeks;
}
// 12. Else if unit is "day", then
else if (unit == "day"sv) {
- // a. Let fractionalDays be days.
- auto fractional_days = days;
+ // a. Set days to RoundNumberToIncrement(fractionalDays, increment, roundingMode).
+ days = round_number_to_increment(fractional_days, increment, rounding_mode);
- // b. Set days to RoundNumberToIncrement(days, increment, roundingMode).
- days = round_number_to_increment(days, increment, rounding_mode);
-
- // c. Set remainder to fractionalDays - days.
- remainder = fractional_days - days;
+ // b. Set total to fractionalDays.
+ total = fractional_days;
}
// 13. Else if unit is "hour", then
else if (unit == "hour"sv) {
@@ -1512,8 +1563,8 @@ ThrowCompletionOr<RoundedDuration> round_duration(VM& vm, double years, double m
// b. Set hours to RoundNumberToIncrement(fractionalHours, increment, roundingMode).
hours = round_number_to_increment(fractional_hours, increment, rounding_mode);
- // c. Set remainder to fractionalHours - hours.
- remainder = fractional_hours - hours;
+ // c. Set total to fractionalHours.
+ total = fractional_hours;
// d. Set minutes, seconds, milliseconds, microseconds, and nanoseconds to 0.
minutes = 0;
@@ -1530,8 +1581,8 @@ ThrowCompletionOr<RoundedDuration> round_duration(VM& vm, double years, double m
// b. Set minutes to RoundNumberToIncrement(fractionalMinutes, increment, roundingMode).
minutes = round_number_to_increment(fractional_minutes, increment, rounding_mode);
- // c. Set remainder to fractionalMinutes - minutes.
- remainder = fractional_minutes - minutes;
+ // c. Set total to fractionalMinutes.
+ total = fractional_minutes;
// d. Set seconds, milliseconds, microseconds, and nanoseconds to 0.
seconds = 0;
@@ -1544,8 +1595,8 @@ ThrowCompletionOr<RoundedDuration> round_duration(VM& vm, double years, double m
// a. Set seconds to RoundNumberToIncrement(fractionalSeconds, increment, roundingMode).
seconds = round_number_to_increment(fractional_seconds, increment, rounding_mode);
- // b. Set remainder to fractionalSeconds - seconds.
- remainder = fractional_seconds - seconds;
+ // b. Set total to fractionalSeconds.
+ total = fractional_seconds;
// c. Set milliseconds, microseconds, and nanoseconds to 0.
milliseconds = 0;
@@ -1560,8 +1611,8 @@ ThrowCompletionOr<RoundedDuration> round_duration(VM& vm, double years, double m
// b. Set milliseconds to RoundNumberToIncrement(fractionalMilliseconds, increment, roundingMode).
milliseconds = round_number_to_increment(fractional_milliseconds, increment, rounding_mode);
- // c. Set remainder to fractionalMilliseconds - milliseconds.
- remainder = fractional_milliseconds - milliseconds;
+ // c. Set total to fractionalMilliseconds.
+ total = fractional_milliseconds;
// d. Set microseconds and nanoseconds to 0.
microseconds = 0;
@@ -1575,8 +1626,8 @@ ThrowCompletionOr<RoundedDuration> round_duration(VM& vm, double years, double m
// b. Set microseconds to RoundNumberToIncrement(fractionalMicroseconds, increment, roundingMode).
microseconds = round_number_to_increment(fractional_microseconds, increment, rounding_mode);
- // c. Set remainder to fractionalMicroseconds - microseconds.
- remainder = fractional_microseconds - microseconds;
+ // c. Set total to fractionalMicroseconds.
+ total = fractional_microseconds;
// d. Set nanoseconds to 0.
nanoseconds = 0;
@@ -1586,21 +1637,18 @@ ThrowCompletionOr<RoundedDuration> round_duration(VM& vm, double years, double m
// a. Assert: unit is "nanosecond".
VERIFY(unit == "nanosecond"sv);
- // b. Set remainder to nanoseconds.
- remainder = nanoseconds;
+ // b. Set total to nanoseconds.
+ total = nanoseconds;
// c. Set nanoseconds to RoundNumberToIncrement(nanoseconds, increment, roundingMode).
nanoseconds = round_number_to_increment(nanoseconds, increment, rounding_mode);
-
- // d. Set remainder to remainder - nanoseconds.
- remainder -= nanoseconds;
}
- // 19. Let duration be ? CreateDurationRecord(years, months, weeks, days, hours, minutes, seconds, milliseconds, microseconds, nanoseconds).
+ // 20. Let duration be ? CreateDurationRecord(years, months, weeks, days, hours, minutes, seconds, milliseconds, microseconds, nanoseconds).
auto duration = TRY(create_duration_record(vm, years, months, weeks, days, hours, minutes, seconds, milliseconds, microseconds, nanoseconds));
- // 20. Return the Record { [[DurationRecord]]: duration, [[Remainder]]: remainder }.
- return RoundedDuration { .duration_record = duration, .remainder = remainder };
+ // 21. Return the Record { [[DurationRecord]]: duration, [[Total]]: total }.
+ return RoundedDuration { .duration_record = duration, .total = total };
}
// 7.5.26 AdjustRoundedDurationDays ( years, months, weeks, days, hours, minutes, seconds, milliseconds, microseconds, nanoseconds, increment, unit, roundingMode, relativeTo ), https://tc39.es/proposal-temporal/#sec-temporal-adjustroundeddurationdays
diff --git a/Userland/Libraries/LibJS/Runtime/Temporal/Duration.h b/Userland/Libraries/LibJS/Runtime/Temporal/Duration.h
index dfdeccfe0eac..5d2c5bd942c2 100644
--- a/Userland/Libraries/LibJS/Runtime/Temporal/Duration.h
+++ b/Userland/Libraries/LibJS/Runtime/Temporal/Duration.h
@@ -107,7 +107,7 @@ struct MoveRelativeDateResult {
// Used by RoundDuration to temporarily hold values
struct RoundedDuration {
DurationRecord duration_record;
- double remainder;
+ double total;
};
// Table 8: Duration Record Fields, https://tc39.es/proposal-temporal/#table-temporal-duration-record-fields
diff --git a/Userland/Libraries/LibJS/Runtime/Temporal/DurationPrototype.cpp b/Userland/Libraries/LibJS/Runtime/Temporal/DurationPrototype.cpp
index afd5315444ff..97855405572f 100644
--- a/Userland/Libraries/LibJS/Runtime/Temporal/DurationPrototype.cpp
+++ b/Userland/Libraries/LibJS/Runtime/Temporal/DurationPrototype.cpp
@@ -445,6 +445,7 @@ JS_DEFINE_NATIVE_FUNCTION(DurationPrototype::round)
}
// 7.3.21 Temporal.Duration.prototype.total ( totalOf ), https://tc39.es/proposal-temporal/#sec-temporal.duration.prototype.total
+// FIXME: This is well out of date with the spec.
JS_DEFINE_NATIVE_FUNCTION(DurationPrototype::total)
{
auto& realm = *vm.current_realm();
@@ -501,67 +502,8 @@ JS_DEFINE_NATIVE_FUNCTION(DurationPrototype::total)
// 12. Let roundRecord be ? RoundDuration(unbalanceResult.[[Years]], unbalanceResult.[[Months]], unbalanceResult.[[Weeks]], balanceResult.[[Days]], balanceResult.[[Hours]], balanceResult.[[Minutes]], balanceResult.[[Seconds]], balanceResult.[[Milliseconds]], balanceResult.[[Microseconds]], balanceResult.[[Nanoseconds]], 1, unit, "trunc", relativeTo).
auto round_record = TRY(round_duration(vm, unbalance_result.years, unbalance_result.months, unbalance_result.weeks, balance_result.days, balance_result.hours, balance_result.minutes, balance_result.seconds, balance_result.milliseconds, balance_result.microseconds, balance_result.nanoseconds, 1, *unit, "trunc"sv, relative_to.is_object() ? &relative_to.as_object() : nullptr));
- // 13. Let roundResult be roundRecord.[[DurationRecord]].
- auto& round_result = round_record.duration_record;
-
- double whole;
-
- // 14. If unit is "year", then
- if (unit == "year"sv) {
- // a. Let whole be roundResult.[[Years]].
- whole = round_result.years;
- }
- // 15. Else if unit is "month", then
- else if (unit == "month"sv) {
- // a. Let whole be roundResult.[[Months]].
- whole = round_result.months;
- }
- // 16. Else if unit is "week", then
- else if (unit == "week"sv) {
- // a. Let whole be roundResult.[[Weeks]].
- whole = round_result.weeks;
- }
- // 17. Else if unit is "day", then
- else if (unit == "day"sv) {
- // a. Let whole be roundResult.[[Days]].
- whole = round_result.days;
- }
- // 18. Else if unit is "hour", then
- else if (unit == "hour"sv) {
- // a. Let whole be roundResult.[[Hours]].
- whole = round_result.hours;
- }
- // 19. Else if unit is "minute", then
- else if (unit == "minute"sv) {
- // a. Let whole be roundResult.[[Minutes]].
- whole = round_result.minutes;
- }
- // 20. Else if unit is "second", then
- else if (unit == "second"sv) {
- // a. Let whole be roundResult.[[Seconds]].
- whole = round_result.seconds;
- }
- // 21. Else if unit is "millisecond", then
- else if (unit == "millisecond"sv) {
- // a. Let whole be roundResult.[[Milliseconds]].
- whole = round_result.milliseconds;
- }
- // 22. Else if unit is "microsecond", then
- else if (unit == "microsecond"sv) {
- // a. Let whole be roundResult.[[Microseconds]].
- whole = round_result.microseconds;
- }
- // 23. Else,
- else {
- // a. Assert: unit is "nanosecond".
- VERIFY(unit == "nanosecond"sv);
-
- // b. Let whole be roundResult.[[Nanoseconds]].
- whole = round_result.nanoseconds;
- }
-
- // 24. Return 𝔽(whole + roundRecord.[[Remainder]]).
- return Value(whole + round_record.remainder);
+ // 13. Return 𝔽(roundRecord.[[Total]]).
+ return Value(round_record.total);
}
// 7.3.22 Temporal.Duration.prototype.toString ( [ options ] ), https://tc39.es/proposal-temporal/#sec-temporal.duration.prototype.tostring
diff --git a/Userland/Libraries/LibJS/Tests/builtins/Temporal/Duration/Duration.prototype.round.js b/Userland/Libraries/LibJS/Tests/builtins/Temporal/Duration/Duration.prototype.round.js
index 28672bfa14ee..51ea215aab5e 100644
--- a/Userland/Libraries/LibJS/Tests/builtins/Temporal/Duration/Duration.prototype.round.js
+++ b/Userland/Libraries/LibJS/Tests/builtins/Temporal/Duration/Duration.prototype.round.js
@@ -173,4 +173,24 @@ describe("errors", () => {
"A starting point is required for balancing calendar units"
);
});
+
+ test("invalid calendar throws range exception when performing round", () => {
+ const duration = Temporal.Duration.from({ nanoseconds: 0 });
+
+ const calendar = new (class extends Temporal.Calendar {
+ dateAdd(date, duration, options) {
+ return date;
+ }
+ })("iso8601");
+
+ expect(() => {
+ duration.round({
+ relativeTo: new Temporal.PlainDate(1997, 5, 10, calendar),
+ smallestUnit: "years",
+ });
+ }).toThrowWithMessage(
+ RangeError,
+ "Invalid calendar, dateAdd() function returned result implying a year is zero days long"
+ );
+ });
});
|
6708251968ebe7bf6aead688338d27ece32fa77f
|
2024-10-31 22:53:26
|
Timothy Flynn
|
libweb: Disable css/transition-basics.html test
| false
|
Disable css/transition-basics.html test
|
libweb
|
diff --git a/Tests/LibWeb/TestConfig.ini b/Tests/LibWeb/TestConfig.ini
index 4146270b790b..3d1d55588591 100644
--- a/Tests/LibWeb/TestConfig.ini
+++ b/Tests/LibWeb/TestConfig.ini
@@ -3,6 +3,7 @@ Ref/css-keyframe-fill-forwards.html
Ref/unicode-range.html
Text/input/Crypto/SubtleCrypto-exportKey.html
Text/input/Crypto/SubtleCrypto-generateKey.html
+Text/input/css/transition-basics.html
Text/input/HTML/cross-origin-window-properties.html
Text/input/HTML/DedicatedWorkerGlobalScope-instanceof.html
Text/input/WebAnimations/misc/DocumentTimeline.html
|
163b6bb401c7607220559ebddf58b007d2b9f07f
|
2024-03-12 13:21:50
|
MacDue
|
libweb: Special case SVG masks during layout
| false
|
Special case SVG masks during layout
|
libweb
|
diff --git a/Tests/LibWeb/Layout/expected/svg/objectBoundingBox-mask.txt b/Tests/LibWeb/Layout/expected/svg/objectBoundingBox-mask.txt
index 2104cc1d2c25..8a1eaea171c9 100644
--- a/Tests/LibWeb/Layout/expected/svg/objectBoundingBox-mask.txt
+++ b/Tests/LibWeb/Layout/expected/svg/objectBoundingBox-mask.txt
@@ -1,22 +1,31 @@
Viewport <#document> at (0,0) content-size 800x600 children: not-inline
- BlockContainer <html> at (0,0) content-size 800x216 [BFC] children: not-inline
- BlockContainer <body> at (8,8) content-size 784x200 children: inline
- frag 0 from SVGSVGBox start: 0, length: 0, rect: [8,8 200x200] baseline: 200
- SVGSVGBox <svg> at (8,8) content-size 200x200 [SVG] children: inline
+ BlockContainer <html> at (0,0) content-size 800x416 [BFC] children: not-inline
+ BlockContainer <body> at (8,8) content-size 784x400 children: inline
+ frag 0 from SVGSVGBox start: 0, length: 0, rect: [8,8 400x400] baseline: 400
+ SVGSVGBox <svg> at (8,8) content-size 400x400 [SVG] children: inline
TextNode <#text>
- SVGGraphicsBox <mask#myMask> at (8,8) content-size 1x1 children: inline
- TextNode <#text>
- SVGGeometryBox <rect> at (8,8) content-size 1x1 children: not-inline
- TextNode <#text>
- SVGGeometryBox <circle> at (8.09375,8.09375) content-size 0.8125x0.8125 children: not-inline
- TextNode <#text>
TextNode <#text>
SVGGeometryBox <rect> at (8,8) content-size 200x200 children: not-inline
+ SVGMaskBox <mask#myMask> at (8,8) content-size 200x200 children: inline
+ TextNode <#text>
+ SVGGeometryBox <rect> at (8,8) content-size 200x200 children: not-inline
+ TextNode <#text>
+ SVGGeometryBox <circle> at (26.75,26.75) content-size 162.5x162.5 children: not-inline
+ TextNode <#text>
+ TextNode <#text>
+ SVGGeometryBox <rect> at (208,208) content-size 200x100 children: not-inline
+ SVGMaskBox <mask#myMask> at (208,208) content-size 200x100 children: inline
+ TextNode <#text>
+ SVGGeometryBox <rect> at (208,208) content-size 200x100 children: not-inline
+ TextNode <#text>
+ SVGGeometryBox <circle> at (226.75,217.375) content-size 162.5x81.25 children: not-inline
+ TextNode <#text>
TextNode <#text>
TextNode <#text>
ViewportPaintable (Viewport<#document>) [0,0 800x600]
- PaintableWithLines (BlockContainer<HTML>) [0,0 800x216]
- PaintableWithLines (BlockContainer<BODY>) [8,8 784x200]
- SVGSVGPaintable (SVGSVGBox<svg>) [8,8 200x200]
+ PaintableWithLines (BlockContainer<HTML>) [0,0 800x416]
+ PaintableWithLines (BlockContainer<BODY>) [8,8 784x400]
+ SVGSVGPaintable (SVGSVGBox<svg>) [8,8 400x400]
SVGPathPaintable (SVGGeometryBox<rect>) [8,8 200x200]
+ SVGPathPaintable (SVGGeometryBox<rect>) [208,208 200x100]
diff --git a/Tests/LibWeb/Layout/expected/svg/svg-symbol-with-viewbox.txt b/Tests/LibWeb/Layout/expected/svg/svg-symbol-with-viewbox.txt
index b97eda9569d0..2f0eecf53338 100644
--- a/Tests/LibWeb/Layout/expected/svg/svg-symbol-with-viewbox.txt
+++ b/Tests/LibWeb/Layout/expected/svg/svg-symbol-with-viewbox.txt
@@ -9,7 +9,7 @@ Viewport <#document> at (0,0) content-size 800x600 children: not-inline
TextNode <#text>
SVGSVGBox <svg> at (8,8) content-size 300x150 [SVG] children: inline
TextNode <#text>
- SVGGraphicsBox <use> at (92.375,26.75) content-size 131.25x112.15625 children: not-inline
+ SVGGraphicsBox <use> at (8,8) content-size 300x150 children: not-inline
SVGGraphicsBox <symbol#braces> at (92.375,26.75) content-size 131.25x112.15625 [BFC] children: inline
TextNode <#text>
SVGGeometryBox <path> at (92.375,26.75) content-size 131.25x112.15625 children: inline
@@ -24,6 +24,6 @@ ViewportPaintable (Viewport<#document>) [0,0 800x600]
PaintableWithLines (BlockContainer(anonymous)) [8,8 784x0]
PaintableWithLines (BlockContainer<DIV>) [8,8 784x150]
SVGSVGPaintable (SVGSVGBox<svg>) [8,8 300x150]
- SVGGraphicsPaintable (SVGGraphicsBox<use>) [92.375,26.75 131.25x112.15625]
+ SVGGraphicsPaintable (SVGGraphicsBox<use>) [8,8 300x150]
SVGGraphicsPaintable (SVGGraphicsBox<symbol>#braces) [92.375,26.75 131.25x112.15625]
SVGPathPaintable (SVGGeometryBox<path>) [92.375,26.75 131.25x112.15625]
diff --git a/Tests/LibWeb/Layout/input/svg/objectBoundingBox-mask.html b/Tests/LibWeb/Layout/input/svg/objectBoundingBox-mask.html
index c85f681ca742..2216c7baa7b5 100644
--- a/Tests/LibWeb/Layout/input/svg/objectBoundingBox-mask.html
+++ b/Tests/LibWeb/Layout/input/svg/objectBoundingBox-mask.html
@@ -1,8 +1,9 @@
<!DOCTYPE html>
-<svg width="200" height="200">
+<svg width="400" height="400">
<mask id="myMask" maskContentUnits="objectBoundingBox">
<rect x="0" y="0" width="1" height="1" fill="white"/>
<circle cx="0.5" cy="0.5" r="0.4" fill="black"/>
</mask>
<rect x="0" y="0" width="200" height="200" fill="green" mask="url(#myMask)"/>
+ <rect x="200" y="200" width="200" height="100" fill="red" mask="url(#myMask)"/>
</svg>
diff --git a/Userland/Libraries/LibWeb/CMakeLists.txt b/Userland/Libraries/LibWeb/CMakeLists.txt
index e42113cc83c6..f03058f9237a 100644
--- a/Userland/Libraries/LibWeb/CMakeLists.txt
+++ b/Userland/Libraries/LibWeb/CMakeLists.txt
@@ -469,6 +469,7 @@ set(SOURCES
Layout/SVGGeometryBox.cpp
Layout/SVGGraphicsBox.cpp
Layout/SVGSVGBox.cpp
+ Layout/SVGMaskBox.cpp
Layout/SVGTextBox.cpp
Layout/SVGTextPathBox.cpp
Layout/TableFormattingContext.cpp
@@ -523,6 +524,7 @@ set(SOURCES
Painting/RecordingPainter.cpp
Painting/SVGPathPaintable.cpp
Painting/SVGGraphicsPaintable.cpp
+ Painting/SVGMaskPaintable.cpp
Painting/SVGPaintable.cpp
Painting/SVGSVGPaintable.cpp
Painting/ShadowPainting.cpp
diff --git a/Userland/Libraries/LibWeb/Layout/SVGFormattingContext.cpp b/Userland/Libraries/LibWeb/Layout/SVGFormattingContext.cpp
index 76dafe8dc7c6..29921a9951bc 100644
--- a/Userland/Libraries/LibWeb/Layout/SVGFormattingContext.cpp
+++ b/Userland/Libraries/LibWeb/Layout/SVGFormattingContext.cpp
@@ -14,6 +14,7 @@
#include <LibWeb/Layout/BlockFormattingContext.h>
#include <LibWeb/Layout/SVGFormattingContext.h>
#include <LibWeb/Layout/SVGGeometryBox.h>
+#include <LibWeb/Layout/SVGMaskBox.h>
#include <LibWeb/Layout/SVGSVGBox.h>
#include <LibWeb/Layout/SVGTextBox.h>
#include <LibWeb/Layout/SVGTextPathBox.h>
@@ -289,6 +290,8 @@ void SVGFormattingContext::run(Box const& box, LayoutMode layout_mode, Available
}();
for_each_in_subtree(box, [&](Node const& descendant) {
+ if (is<SVGMaskBox>(descendant))
+ return TraversalDecision::SkipChildrenAndContinue;
if (is<SVG::SVGViewport>(descendant.dom_node())) {
// Layout for a nested SVG viewport.
// https://svgwg.org/svg2-draft/coords.html#EstablishingANewSVGViewport.
@@ -391,14 +394,19 @@ void SVGFormattingContext::run(Box const& box, LayoutMode layout_mode, Available
// https://svgwg.org/svg2-draft/struct.html#Groups
// 5.2. Grouping: the ‘g’ element
// The ‘g’ element is a container element for grouping together related graphics elements.
- box.for_each_in_subtree_of_type<Box>([&](Box const& descendant) {
+ box.for_each_in_subtree_of_type<SVGBox>([&](SVGBox const& descendant) {
if (is_container_element(descendant)) {
Gfx::BoundingBox<CSSPixels> bounding_box;
- descendant.for_each_in_subtree_of_type<Box>([&](Box const& child_of_svg_container) {
- auto& box_state = m_state.get(child_of_svg_container);
+ for_each_in_subtree(descendant, [&](Node const& child_of_svg_container) {
+ if (!is<SVGBox>(child_of_svg_container))
+ return TraversalDecision::Continue;
+ // Masks do not change the bounding box of their parents.
+ if (is<SVGMaskBox>(child_of_svg_container))
+ return TraversalDecision::SkipChildrenAndContinue;
+ auto& box_state = m_state.get(static_cast<SVGBox const&>(child_of_svg_container));
bounding_box.add_point(box_state.offset);
bounding_box.add_point(box_state.offset.translated(box_state.content_width(), box_state.content_height()));
- return IterationDecision::Continue;
+ return TraversalDecision::Continue;
});
auto& box_state = m_state.get_mutable(descendant);
@@ -411,6 +419,28 @@ void SVGFormattingContext::run(Box const& box, LayoutMode layout_mode, Available
}
return IterationDecision::Continue;
});
+
+ // Lay out masks last (as their parent needs to be sized first).
+ box.for_each_in_subtree_of_type<SVGMaskBox>([&](SVGMaskBox const& mask_box) {
+ auto& mask_state = m_state.get_mutable(static_cast<Box const&>(mask_box));
+ auto parent_viewbox_transform = viewbox_transform;
+ if (mask_box.dom_node().mask_content_units() == SVG::MaskContentUnits::ObjectBoundingBox) {
+ auto* masked_node = mask_box.parent();
+ auto& masked_node_state = m_state.get(*masked_node);
+ mask_state.set_content_width(masked_node_state.content_width());
+ mask_state.set_content_height(masked_node_state.content_height());
+ parent_viewbox_transform = Gfx::AffineTransform {}.translate(masked_node_state.offset.to_type<float>());
+ } else {
+ mask_state.set_content_width(viewport_width);
+ mask_state.set_content_height(viewport_height);
+ }
+ // Pretend masks are a viewport so we can scale the contents depending on the `maskContentUnits`.
+ SVGFormattingContext nested_context(m_state, static_cast<Box const&>(mask_box), this, parent_viewbox_transform);
+ mask_state.set_has_definite_width(true);
+ mask_state.set_has_definite_height(true);
+ nested_context.run(static_cast<Box const&>(mask_box), layout_mode, available_space);
+ return IterationDecision::Continue;
+ });
}
}
diff --git a/Userland/Libraries/LibWeb/Layout/SVGMaskBox.cpp b/Userland/Libraries/LibWeb/Layout/SVGMaskBox.cpp
new file mode 100644
index 000000000000..c76c1c57d782
--- /dev/null
+++ b/Userland/Libraries/LibWeb/Layout/SVGMaskBox.cpp
@@ -0,0 +1,23 @@
+/*
+ * Copyright (c) 2024, MacDue <[email protected]>
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#include <LibWeb/Layout/SVGMaskBox.h>
+#include <LibWeb/Painting/SVGMaskPaintable.h>
+#include <LibWeb/Painting/StackingContext.h>
+
+namespace Web::Layout {
+
+SVGMaskBox::SVGMaskBox(DOM::Document& document, SVG::SVGMaskElement& element, NonnullRefPtr<CSS::StyleProperties> properties)
+ : SVGGraphicsBox(document, element, properties)
+{
+}
+
+JS::GCPtr<Painting::Paintable> SVGMaskBox::create_paintable() const
+{
+ return Painting::SVGMaskPaintable::create(*this);
+}
+
+}
diff --git a/Userland/Libraries/LibWeb/Layout/SVGMaskBox.h b/Userland/Libraries/LibWeb/Layout/SVGMaskBox.h
new file mode 100644
index 000000000000..f73fccd1cf47
--- /dev/null
+++ b/Userland/Libraries/LibWeb/Layout/SVGMaskBox.h
@@ -0,0 +1,28 @@
+/*
+ * Copyright (c) 2024, MacDue <[email protected]>
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#pragma once
+
+#include <LibWeb/Layout/SVGGraphicsBox.h>
+#include <LibWeb/SVG/SVGElement.h>
+#include <LibWeb/SVG/SVGMaskElement.h>
+
+namespace Web::Layout {
+
+class SVGMaskBox : public SVGGraphicsBox {
+ JS_CELL(SVGMaskBox, SVGBox);
+
+public:
+ SVGMaskBox(DOM::Document&, SVG::SVGMaskElement&, NonnullRefPtr<CSS::StyleProperties>);
+ virtual ~SVGMaskBox() override = default;
+
+ SVG::SVGMaskElement& dom_node() { return verify_cast<SVG::SVGMaskElement>(SVGGraphicsBox::dom_node()); }
+ SVG::SVGMaskElement const& dom_node() const { return verify_cast<SVG::SVGMaskElement>(SVGGraphicsBox::dom_node()); }
+
+ virtual JS::GCPtr<Painting::Paintable> create_paintable() const override;
+};
+
+}
diff --git a/Userland/Libraries/LibWeb/Layout/TreeBuilder.cpp b/Userland/Libraries/LibWeb/Layout/TreeBuilder.cpp
index f164a6e9ffd3..4bf10329fd8b 100644
--- a/Userland/Libraries/LibWeb/Layout/TreeBuilder.cpp
+++ b/Userland/Libraries/LibWeb/Layout/TreeBuilder.cpp
@@ -26,6 +26,7 @@
#include <LibWeb/Layout/ListItemBox.h>
#include <LibWeb/Layout/ListItemMarkerBox.h>
#include <LibWeb/Layout/Node.h>
+#include <LibWeb/Layout/SVGMaskBox.h>
#include <LibWeb/Layout/TableGrid.h>
#include <LibWeb/Layout/TableWrapper.h>
#include <LibWeb/Layout/TextNode.h>
@@ -335,6 +336,12 @@ void TreeBuilder::create_layout_tree(DOM::Node& dom_node, TreeBuilder::Context&
display = CSS::Display(CSS::DisplayOutside::Inline, CSS::DisplayInside::Flow);
}
+ if (context.layout_svg_mask && is<SVG::SVGMaskElement>(dom_node)) {
+ layout_node = document.heap().allocate_without_realm<Layout::SVGMaskBox>(document, static_cast<SVG::SVGMaskElement&>(dom_node), *style);
+ // We're here if our parent is a use of an SVG mask, but we don't want to lay out any <mask> elements that could be a child of this mask.
+ context.layout_svg_mask = false;
+ }
+
if (!layout_node)
return;
@@ -389,6 +396,19 @@ void TreeBuilder::create_layout_tree(DOM::Node& dom_node, TreeBuilder::Context&
pop_parent();
}
+ if (is<SVG::SVGGraphicsElement>(dom_node)) {
+ auto& graphics_element = static_cast<SVG::SVGGraphicsElement&>(dom_node);
+ // Create the layout tree for the SVG mask as a child of the masked element. Note: This will create
+ // a new subtree for each use of the mask (so there's not a 1-to-1 mapping from DOM node to mask
+ // layout node). Each use of a mask may be laid out differently so this duplication is necessary.
+ if (auto mask = graphics_element.mask()) {
+ TemporaryChange<bool> layout_mask(context.layout_svg_mask, true);
+ push_parent(verify_cast<NodeWithStyle>(*layout_node));
+ create_layout_tree(const_cast<SVG::SVGMaskElement&>(*mask), context);
+ pop_parent();
+ }
+ }
+
// https://html.spec.whatwg.org/multipage/rendering.html#button-layout
// If the computed value of 'inline-size' is 'auto', then the used value is the fit-content inline size.
if (dom_node.is_html_button_element() && dom_node.layout_node()->computed_values().width().is_auto()) {
diff --git a/Userland/Libraries/LibWeb/Layout/TreeBuilder.h b/Userland/Libraries/LibWeb/Layout/TreeBuilder.h
index df156c0caf0f..fe2841fcfa4e 100644
--- a/Userland/Libraries/LibWeb/Layout/TreeBuilder.h
+++ b/Userland/Libraries/LibWeb/Layout/TreeBuilder.h
@@ -23,6 +23,7 @@ class TreeBuilder {
private:
struct Context {
bool has_svg_root = false;
+ bool layout_svg_mask = false;
};
i32 calculate_list_item_index(DOM::Node&);
diff --git a/Userland/Libraries/LibWeb/Painting/SVGGraphicsPaintable.cpp b/Userland/Libraries/LibWeb/Painting/SVGGraphicsPaintable.cpp
index 6e1598dc6d99..e04874b24b7f 100644
--- a/Userland/Libraries/LibWeb/Painting/SVGGraphicsPaintable.cpp
+++ b/Userland/Libraries/LibWeb/Painting/SVGGraphicsPaintable.cpp
@@ -5,6 +5,7 @@
*/
#include <LibWeb/Layout/ImageBox.h>
+#include <LibWeb/Layout/SVGMaskBox.h>
#include <LibWeb/Painting/CommandExecutorCPU.h>
#include <LibWeb/Painting/SVGGraphicsPaintable.h>
#include <LibWeb/Painting/StackingContext.h>
@@ -23,12 +24,6 @@ SVGGraphicsPaintable::SVGGraphicsPaintable(Layout::SVGGraphicsBox const& layout_
{
}
-bool SVGGraphicsPaintable::forms_unconnected_subtree() const
-{
- // Masks should not be painted (i.e. reachable) unless referenced by another element.
- return is<SVG::SVGMaskElement>(dom_node());
-}
-
Layout::SVGGraphicsBox const& SVGGraphicsPaintable::layout_box() const
{
return static_cast<Layout::SVGGraphicsBox const&>(layout_node());
@@ -37,20 +32,10 @@ Layout::SVGGraphicsBox const& SVGGraphicsPaintable::layout_box() const
Optional<CSSPixelRect> SVGGraphicsPaintable::get_masking_area() const
{
auto const& graphics_element = verify_cast<SVG::SVGGraphicsElement const>(*dom_node());
- auto mask = graphics_element.mask();
- if (!mask)
+ auto* mask_box = graphics_element.layout_node()->first_child_of_type<Layout::SVGMaskBox>();
+ if (!mask_box)
return {};
- auto target_area = [&] {
- auto mask_units = mask->mask_units();
- if (mask_units == SVG::MaskUnits::UserSpaceOnUse) {
- auto const* svg_element = graphics_element.shadow_including_first_ancestor_of_type<SVG::SVGSVGElement>();
- return svg_element->paintable_box()->absolute_border_box_rect();
- } else {
- VERIFY(mask_units == SVG::MaskUnits::ObjectBoundingBox);
- return absolute_border_box_rect();
- }
- }();
- return mask->resolve_masking_area(target_area);
+ return mask_box->dom_node().resolve_masking_area(mask_box->paintable_box()->absolute_border_box_rect());
}
static Gfx::Bitmap::MaskKind mask_type_to_gfx_mask_kind(CSS::MaskType mask_type)
@@ -77,30 +62,24 @@ Optional<Gfx::Bitmap::MaskKind> SVGGraphicsPaintable::get_mask_type() const
RefPtr<Gfx::Bitmap> SVGGraphicsPaintable::calculate_mask(PaintContext& context, CSSPixelRect const& masking_area) const
{
auto const& graphics_element = verify_cast<SVG::SVGGraphicsElement const>(*dom_node());
- auto mask = graphics_element.mask();
- VERIFY(mask);
- if (mask->mask_content_units() != SVG::MaskContentUnits::UserSpaceOnUse) {
- // FIXME: Implement support for maskContentUnits=objectBoundingBox
- return {};
- }
+ auto* mask_box = graphics_element.layout_node()->first_child_of_type<Layout::SVGMaskBox>();
+ VERIFY(mask_box);
auto mask_rect = context.enclosing_device_rect(masking_area);
RefPtr<Gfx::Bitmap> mask_bitmap = {};
- if (mask && mask->layout_node() && is<PaintableBox>(mask->layout_node()->paintable())) {
- auto& mask_paintable = static_cast<PaintableBox const&>(*mask->layout_node()->paintable());
- auto mask_bitmap_or_error = Gfx::Bitmap::create(Gfx::BitmapFormat::BGRA8888, mask_rect.size().to_type<int>());
- if (mask_bitmap_or_error.is_error())
- return {};
- mask_bitmap = mask_bitmap_or_error.release_value();
- {
- CommandList painting_commands;
- RecordingPainter recording_painter(painting_commands);
- recording_painter.translate(-mask_rect.location().to_type<int>());
- auto paint_context = context.clone(recording_painter);
- paint_context.set_svg_transform(graphics_element.get_transform());
- StackingContext::paint_node_as_stacking_context(mask_paintable, paint_context);
- CommandExecutorCPU executor { *mask_bitmap };
- painting_commands.execute(executor);
- }
+ auto& mask_paintable = static_cast<PaintableBox const&>(*mask_box->paintable());
+ auto mask_bitmap_or_error = Gfx::Bitmap::create(Gfx::BitmapFormat::BGRA8888, mask_rect.size().to_type<int>());
+ if (mask_bitmap_or_error.is_error())
+ return {};
+ mask_bitmap = mask_bitmap_or_error.release_value();
+ {
+ CommandList painting_commands;
+ RecordingPainter recording_painter(painting_commands);
+ recording_painter.translate(-mask_rect.location().to_type<int>());
+ auto paint_context = context.clone(recording_painter);
+ paint_context.set_svg_transform(graphics_element.get_transform());
+ StackingContext::paint_node_as_stacking_context(mask_paintable, paint_context);
+ CommandExecutorCPU executor { *mask_bitmap };
+ painting_commands.execute(executor);
}
return mask_bitmap;
}
diff --git a/Userland/Libraries/LibWeb/Painting/SVGGraphicsPaintable.h b/Userland/Libraries/LibWeb/Painting/SVGGraphicsPaintable.h
index d7c4e4e2b3e5..e4ea76db5b1c 100644
--- a/Userland/Libraries/LibWeb/Painting/SVGGraphicsPaintable.h
+++ b/Userland/Libraries/LibWeb/Painting/SVGGraphicsPaintable.h
@@ -49,8 +49,6 @@ class SVGGraphicsPaintable : public SVGPaintable {
Layout::SVGGraphicsBox const& layout_box() const;
- virtual bool forms_unconnected_subtree() const override;
-
virtual Optional<CSSPixelRect> get_masking_area() const override;
virtual Optional<Gfx::Bitmap::MaskKind> get_mask_type() const override;
virtual RefPtr<Gfx::Bitmap> calculate_mask(PaintContext&, CSSPixelRect const& masking_area) const override;
diff --git a/Userland/Libraries/LibWeb/Painting/SVGMaskPaintable.cpp b/Userland/Libraries/LibWeb/Painting/SVGMaskPaintable.cpp
new file mode 100644
index 000000000000..534944f165ee
--- /dev/null
+++ b/Userland/Libraries/LibWeb/Painting/SVGMaskPaintable.cpp
@@ -0,0 +1,21 @@
+/*
+ * Copyright (c) 2024, MacDue <[email protected]>
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#include <LibWeb/Painting/SVGMaskPaintable.h>
+
+namespace Web::Painting {
+
+JS::NonnullGCPtr<SVGMaskPaintable> SVGMaskPaintable::create(Layout::SVGMaskBox const& layout_box)
+{
+ return layout_box.heap().allocate_without_realm<SVGMaskPaintable>(layout_box);
+}
+
+SVGMaskPaintable::SVGMaskPaintable(Layout::SVGMaskBox const& layout_box)
+ : SVGGraphicsPaintable(layout_box)
+{
+}
+
+}
diff --git a/Userland/Libraries/LibWeb/Painting/SVGMaskPaintable.h b/Userland/Libraries/LibWeb/Painting/SVGMaskPaintable.h
new file mode 100644
index 000000000000..b57ab8eaee88
--- /dev/null
+++ b/Userland/Libraries/LibWeb/Painting/SVGMaskPaintable.h
@@ -0,0 +1,30 @@
+/*
+ * Copyright (c) 2024, MacDue <[email protected]>
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#pragma once
+
+#include <LibWeb/Layout/SVGMaskBox.h>
+#include <LibWeb/Painting/SVGGraphicsPaintable.h>
+
+namespace Web::Painting {
+
+class SVGMaskPaintable : public SVGGraphicsPaintable {
+ JS_CELL(SVGMaskPaintable, SVGGraphicsPaintable);
+
+public:
+ static JS::NonnullGCPtr<SVGMaskPaintable> create(Layout::SVGMaskBox const&);
+
+ bool forms_unconnected_subtree() const override
+ {
+ // Masks should not be painted (i.e. reachable) unless referenced by another element.
+ return true;
+ }
+
+protected:
+ SVGMaskPaintable(Layout::SVGMaskBox const&);
+};
+
+}
diff --git a/Userland/Libraries/LibWeb/SVG/SVGDefsElement.cpp b/Userland/Libraries/LibWeb/SVG/SVGDefsElement.cpp
index 989728826e4e..62457ef9b93e 100644
--- a/Userland/Libraries/LibWeb/SVG/SVGDefsElement.cpp
+++ b/Userland/Libraries/LibWeb/SVG/SVGDefsElement.cpp
@@ -27,10 +27,4 @@ void SVGDefsElement::initialize(JS::Realm& realm)
set_prototype(&Bindings::ensure_web_prototype<Bindings::SVGDefsElementPrototype>(realm, "SVGDefsElement"_fly_string));
}
-JS::GCPtr<Layout::Node> SVGDefsElement::create_layout_node(NonnullRefPtr<CSS::StyleProperties> style)
-{
- // FIXME: We need this layout node so any <mask>s inside this element get layout computed.
- return heap().allocate_without_realm<Layout::SVGBox>(document(), *this, move(style));
-}
-
}
diff --git a/Userland/Libraries/LibWeb/SVG/SVGDefsElement.h b/Userland/Libraries/LibWeb/SVG/SVGDefsElement.h
index 6d5e63169f6c..ed4297b3a2c3 100644
--- a/Userland/Libraries/LibWeb/SVG/SVGDefsElement.h
+++ b/Userland/Libraries/LibWeb/SVG/SVGDefsElement.h
@@ -17,7 +17,10 @@ class SVGDefsElement final : public SVGGraphicsElement {
public:
virtual ~SVGDefsElement();
- virtual JS::GCPtr<Layout::Node> create_layout_node(NonnullRefPtr<CSS::StyleProperties>) override;
+ virtual JS::GCPtr<Layout::Node> create_layout_node(NonnullRefPtr<CSS::StyleProperties>) override
+ {
+ return nullptr;
+ }
private:
SVGDefsElement(DOM::Document&, DOM::QualifiedName);
diff --git a/Userland/Libraries/LibWeb/SVG/SVGMaskElement.cpp b/Userland/Libraries/LibWeb/SVG/SVGMaskElement.cpp
index f99f443c6edd..cb9006807521 100644
--- a/Userland/Libraries/LibWeb/SVG/SVGMaskElement.cpp
+++ b/Userland/Libraries/LibWeb/SVG/SVGMaskElement.cpp
@@ -7,7 +7,6 @@
#include <LibWeb/Bindings/SVGMaskElementPrototype.h>
#include <LibWeb/DOM/Document.h>
-#include <LibWeb/Layout/SVGGraphicsBox.h>
#include <LibWeb/SVG/AttributeNames.h>
#include <LibWeb/SVG/SVGMaskElement.h>
@@ -28,9 +27,10 @@ void SVGMaskElement::initialize(JS::Realm& realm)
set_prototype(&Bindings::ensure_web_prototype<Bindings::SVGMaskElementPrototype>(realm, "SVGMaskElement"_fly_string));
}
-JS::GCPtr<Layout::Node> SVGMaskElement::create_layout_node(NonnullRefPtr<CSS::StyleProperties> style)
+JS::GCPtr<Layout::Node> SVGMaskElement::create_layout_node(NonnullRefPtr<CSS::StyleProperties>)
{
- return heap().allocate_without_realm<Layout::SVGGraphicsBox>(document(), *this, move(style));
+ // Masks are handled as a special case in the TreeBuilder.
+ return nullptr;
}
void SVGMaskElement::attribute_changed(FlyString const& name, Optional<String> const& value)
diff --git a/Userland/Libraries/LibWeb/SVG/SVGMaskElement.h b/Userland/Libraries/LibWeb/SVG/SVGMaskElement.h
index 367258039a50..40a11eaa355d 100644
--- a/Userland/Libraries/LibWeb/SVG/SVGMaskElement.h
+++ b/Userland/Libraries/LibWeb/SVG/SVGMaskElement.h
@@ -8,16 +8,34 @@
#include <LibWeb/SVG/AttributeParser.h>
#include <LibWeb/SVG/SVGGraphicsElement.h>
+#include <LibWeb/SVG/SVGViewport.h>
namespace Web::SVG {
-class SVGMaskElement final : public SVGGraphicsElement {
+class SVGMaskElement final : public SVGGraphicsElement
+ , public SVGViewport {
+
WEB_PLATFORM_OBJECT(SVGMaskElement, SVGGraphicsElement);
JS_DECLARE_ALLOCATOR(SVGMaskElement);
public:
virtual ~SVGMaskElement() override;
+ virtual Optional<ViewBox> view_box() const override
+ {
+ // maskContentUnits = objectBoundingBox acts like the mask is sized to the bounding box
+ // of the target element, with a viewBox of "0 0 1 1".
+ if (mask_content_units() == MaskContentUnits::ObjectBoundingBox)
+ return ViewBox { 0, 0, 1, 1 };
+ return {};
+ }
+
+ virtual Optional<PreserveAspectRatio> preserve_aspect_ratio() const override
+ {
+ // preserveAspectRatio = none (allow mask to be scaled in both x and y to match target size)
+ return PreserveAspectRatio { PreserveAspectRatio::Align::None, {} };
+ }
+
virtual void attribute_changed(FlyString const& name, Optional<String> const& value) override;
virtual JS::GCPtr<Layout::Node> create_layout_node(NonnullRefPtr<CSS::StyleProperties>) override;
diff --git a/Userland/Libraries/LibWeb/SVG/SVGStopElement.cpp b/Userland/Libraries/LibWeb/SVG/SVGStopElement.cpp
index 793183bfbf0d..4a8147af9d22 100644
--- a/Userland/Libraries/LibWeb/SVG/SVGStopElement.cpp
+++ b/Userland/Libraries/LibWeb/SVG/SVGStopElement.cpp
@@ -6,8 +6,7 @@
#include <LibWeb/Bindings/Intrinsics.h>
#include <LibWeb/CSS/Parser/Parser.h>
-#include <LibWeb/CSS/StyleValues/IdentifierStyleValue.h>
-#include <LibWeb/Layout/BlockContainer.h>
+#include <LibWeb/CSS/StyleProperties.h>
#include <LibWeb/SVG/AttributeNames.h>
#include <LibWeb/SVG/AttributeParser.h>
#include <LibWeb/SVG/SVGStopElement.h>
|
e1965a5a8ea3f1ba467e91bea5c42359aaadc41c
|
2020-09-19 17:39:59
|
Andreas Kling
|
filemanager: Prevent feedback loop between treeview and directory view
| false
|
Prevent feedback loop between treeview and directory view
|
filemanager
|
diff --git a/Applications/FileManager/main.cpp b/Applications/FileManager/main.cpp
index f2812d27eeda..891ad3d23da3 100644
--- a/Applications/FileManager/main.cpp
+++ b/Applications/FileManager/main.cpp
@@ -219,6 +219,8 @@ int run_in_windowed_mode(RefPtr<Core::ConfigFile> config, String initial_locatio
tree_view.set_column_hidden(GUI::FileSystemModel::Column::SymlinkTarget, true);
tree_view.set_size_policy(GUI::SizePolicy::Fixed, GUI::SizePolicy::Fill);
tree_view.set_preferred_size(150, 0);
+ bool is_reacting_to_tree_view_selection_change = false;
+
auto& directory_view = splitter.add<DirectoryView>(DirectoryView::Mode::Normal);
// Open the root directory. FIXME: This is awkward.
@@ -521,10 +523,13 @@ int run_in_windowed_mode(RefPtr<Core::ConfigFile> config, String initial_locatio
window->set_title(String::format("%s - File Manager", new_path.characters()));
location_textbox.set_text(new_path);
- auto new_index = directories_model->index(new_path, GUI::FileSystemModel::Column::Name);
- if (new_index.is_valid()) {
- tree_view.expand_all_parents_of(new_index);
- tree_view.set_cursor(new_index, GUI::AbstractView::SelectionUpdate::Set);
+
+ if (!is_reacting_to_tree_view_selection_change) {
+ auto new_index = directories_model->index(new_path, GUI::FileSystemModel::Column::Name);
+ if (new_index.is_valid()) {
+ tree_view.expand_all_parents_of(new_index);
+ tree_view.set_cursor(new_index, GUI::AbstractView::SelectionUpdate::Set);
+ }
}
struct stat st;
@@ -659,6 +664,7 @@ int run_in_windowed_mode(RefPtr<Core::ConfigFile> config, String initial_locatio
auto path = directories_model->full_path(tree_view.selection().first());
if (directory_view.path() == path)
return;
+ TemporaryChange change(is_reacting_to_tree_view_selection_change, true);
directory_view.open(path);
copy_action->set_enabled(!tree_view.selection().is_empty());
directory_view.delete_action().set_enabled(!tree_view.selection().is_empty());
|
0315ee593706154d32abcf34ee006b702661aa27
|
2023-07-04 03:35:34
|
Jelle Raaijmakers
|
kernel: Clean up includes for Audio subsystem
| false
|
Clean up includes for Audio subsystem
|
kernel
|
diff --git a/Kernel/Devices/Audio/Channel.h b/Kernel/Devices/Audio/Channel.h
index 99e2fcd7bb3e..5af55240122f 100644
--- a/Kernel/Devices/Audio/Channel.h
+++ b/Kernel/Devices/Audio/Channel.h
@@ -7,10 +7,6 @@
#pragma once
#include <Kernel/Devices/CharacterDevice.h>
-#include <Kernel/Interrupts/IRQHandler.h>
-#include <Kernel/Memory/PhysicalAddress.h>
-#include <Kernel/Memory/PhysicalPage.h>
-#include <Kernel/Tasks/WaitQueue.h>
namespace Kernel {
diff --git a/Kernel/Devices/Audio/Controller.h b/Kernel/Devices/Audio/Controller.h
index 8377f10abdf4..7600133435eb 100644
--- a/Kernel/Devices/Audio/Controller.h
+++ b/Kernel/Devices/Audio/Controller.h
@@ -6,18 +6,12 @@
#pragma once
+#include <AK/Error.h>
#include <AK/IntrusiveList.h>
-#include <AK/OwnPtr.h>
#include <AK/RefPtr.h>
-#include <Kernel/Bus/PCI/Access.h>
-#include <Kernel/Bus/PCI/Device.h>
+#include <AK/Types.h>
#include <Kernel/Devices/Audio/Channel.h>
-#include <Kernel/Devices/Device.h>
-#include <Kernel/Library/LockWeakable.h>
-#include <Kernel/Locking/Mutex.h>
-#include <Kernel/Memory/PhysicalAddress.h>
-#include <Kernel/Memory/PhysicalPage.h>
-#include <Kernel/Security/Random.h>
+#include <Kernel/Library/UserOrKernelBuffer.h>
namespace Kernel {
diff --git a/Kernel/Devices/Audio/Management.cpp b/Kernel/Devices/Audio/Management.cpp
index 74a1581c9ffc..187b8b377761 100644
--- a/Kernel/Devices/Audio/Management.cpp
+++ b/Kernel/Devices/Audio/Management.cpp
@@ -6,11 +6,10 @@
#include <AK/Singleton.h>
#include <Kernel/Bus/PCI/API.h>
-#include <Kernel/Bus/PCI/IDs.h>
+#include <Kernel/Bus/PCI/Access.h>
#include <Kernel/Devices/Audio/AC97/AC97.h>
#include <Kernel/Devices/Audio/IntelHDA/Controller.h>
#include <Kernel/Devices/Audio/Management.h>
-#include <Kernel/Sections.h>
namespace Kernel {
diff --git a/Kernel/Devices/Audio/Management.h b/Kernel/Devices/Audio/Management.h
index 703bdb8c39ce..e479e66c77a5 100644
--- a/Kernel/Devices/Audio/Management.h
+++ b/Kernel/Devices/Audio/Management.h
@@ -6,12 +6,10 @@
#pragma once
-#include <AK/Badge.h>
#include <AK/Error.h>
#include <AK/IntrusiveList.h>
#include <AK/NonnullRefPtr.h>
-#include <AK/OwnPtr.h>
-#include <AK/Types.h>
+#include <Kernel/Bus/PCI/Definitions.h>
#include <Kernel/Devices/Audio/Controller.h>
namespace Kernel {
|
1603623772c689665904880f437e402d11e1cd53
|
2021-03-21 20:32:11
|
Andreas Kling
|
libjs: Move AST node stack from VM to Interpreter
| false
|
Move AST node stack from VM to Interpreter
|
libjs
|
diff --git a/Userland/Libraries/LibJS/AST.cpp b/Userland/Libraries/LibJS/AST.cpp
index f3268b0c483b..58d98faae422 100644
--- a/Userland/Libraries/LibJS/AST.cpp
+++ b/Userland/Libraries/LibJS/AST.cpp
@@ -235,7 +235,7 @@ Value CallExpression::execute(Interpreter& interpreter, GlobalObject& global_obj
}
}
- vm.call_frame().current_node = vm.current_node();
+ vm.call_frame().current_node = interpreter.current_node();
Object* new_object = nullptr;
Value result;
if (is<NewExpression>(*this)) {
diff --git a/Userland/Libraries/LibJS/Interpreter.cpp b/Userland/Libraries/LibJS/Interpreter.cpp
index e773fbd34f84..5750ecb129a1 100644
--- a/Userland/Libraries/LibJS/Interpreter.cpp
+++ b/Userland/Libraries/LibJS/Interpreter.cpp
@@ -146,12 +146,12 @@ void Interpreter::exit_scope(const ScopeNode& scope_node)
void Interpreter::enter_node(const ASTNode& node)
{
vm().call_frame().current_node = &node;
- vm().push_ast_node(node);
+ push_ast_node(node);
}
void Interpreter::exit_node(const ASTNode&)
{
- vm().pop_ast_node();
+ pop_ast_node();
}
void Interpreter::push_scope(ScopeFrame frame)
diff --git a/Userland/Libraries/LibJS/Interpreter.h b/Userland/Libraries/LibJS/Interpreter.h
index 5efb1428da61..a2b801cefa5d 100644
--- a/Userland/Libraries/LibJS/Interpreter.h
+++ b/Userland/Libraries/LibJS/Interpreter.h
@@ -80,6 +80,12 @@ class Interpreter : public Weakable<Interpreter> {
void enter_node(const ASTNode&);
void exit_node(const ASTNode&);
+ void push_ast_node(const ASTNode& node) { m_ast_nodes.append(&node); }
+ void pop_ast_node() { m_ast_nodes.take_last(); }
+
+ const ASTNode* current_node() const { return !m_ast_nodes.is_empty() ? m_ast_nodes.last() : nullptr; }
+ const Vector<const ASTNode*>& node_stack() const { return m_ast_nodes; }
+
Value execute_statement(GlobalObject&, const Statement&, ScopeType = ScopeType::Block);
private:
@@ -88,6 +94,7 @@ class Interpreter : public Weakable<Interpreter> {
void push_scope(ScopeFrame frame);
Vector<ScopeFrame> m_scope_stack;
+ Vector<const ASTNode*> m_ast_nodes;
NonnullRefPtr<VM> m_vm;
diff --git a/Userland/Libraries/LibJS/Runtime/Exception.cpp b/Userland/Libraries/LibJS/Runtime/Exception.cpp
index b7769581a3ab..f8f0f0c4c891 100644
--- a/Userland/Libraries/LibJS/Runtime/Exception.cpp
+++ b/Userland/Libraries/LibJS/Runtime/Exception.cpp
@@ -26,6 +26,7 @@
#include <AK/String.h>
#include <LibJS/AST.h>
+#include <LibJS/Interpreter.h>
#include <LibJS/Runtime/Exception.h>
#include <LibJS/Runtime/VM.h>
@@ -34,7 +35,8 @@ namespace JS {
Exception::Exception(Value value)
: m_value(value)
{
- auto& call_stack = vm().call_stack();
+ auto& vm = this->vm();
+ auto& call_stack = vm.call_stack();
for (ssize_t i = call_stack.size() - 1; i >= 0; --i) {
String function_name = call_stack[i]->function_name;
if (function_name.is_empty())
@@ -42,11 +44,13 @@ Exception::Exception(Value value)
m_trace.append(function_name);
}
- auto& node_stack = vm().node_stack();
- for (ssize_t i = node_stack.size() - 1; i >= 0; --i) {
- auto* node = node_stack[i];
- VERIFY(node);
- m_source_ranges.append(node->source_range());
+ if (auto* interpreter = vm.interpreter_if_exists()) {
+ auto& node_stack = interpreter->node_stack();
+ for (ssize_t i = node_stack.size() - 1; i >= 0; --i) {
+ auto* node = node_stack[i];
+ VERIFY(node);
+ m_source_ranges.append(node->source_range());
+ }
}
}
diff --git a/Userland/Libraries/LibJS/Runtime/Object.cpp b/Userland/Libraries/LibJS/Runtime/Object.cpp
index f828219e761e..91b58f671759 100644
--- a/Userland/Libraries/LibJS/Runtime/Object.cpp
+++ b/Userland/Libraries/LibJS/Runtime/Object.cpp
@@ -28,6 +28,7 @@
#include <AK/String.h>
#include <AK/TemporaryChange.h>
#include <LibJS/Heap/Heap.h>
+#include <LibJS/Interpreter.h>
#include <LibJS/Runtime/Accessor.h>
#include <LibJS/Runtime/Array.h>
#include <LibJS/Runtime/Error.h>
@@ -901,7 +902,8 @@ Value Object::call_native_property_getter(NativeProperty& property, Value this_v
{
auto& vm = this->vm();
CallFrame call_frame;
- call_frame.current_node = property.vm().current_node();
+ if (auto* interpreter = vm.interpreter_if_exists())
+ call_frame.current_node = interpreter->current_node();
call_frame.is_strict_mode = vm.in_strict_mode();
call_frame.this_value = this_value;
vm.push_call_frame(call_frame, global_object());
@@ -916,7 +918,8 @@ void Object::call_native_property_setter(NativeProperty& property, Value this_va
{
auto& vm = this->vm();
CallFrame call_frame;
- call_frame.current_node = property.vm().current_node();
+ if (auto* interpreter = vm.interpreter_if_exists())
+ call_frame.current_node = interpreter->current_node();
call_frame.is_strict_mode = vm.in_strict_mode();
call_frame.this_value = this_value;
vm.push_call_frame(call_frame, global_object());
diff --git a/Userland/Libraries/LibJS/Runtime/VM.cpp b/Userland/Libraries/LibJS/Runtime/VM.cpp
index 894524f20d43..38e4a395fce6 100644
--- a/Userland/Libraries/LibJS/Runtime/VM.cpp
+++ b/Userland/Libraries/LibJS/Runtime/VM.cpp
@@ -213,7 +213,8 @@ Value VM::construct(Function& function, Function& new_target, Optional<MarkedVal
{
CallFrame call_frame;
call_frame.callee = &function;
- call_frame.current_node = current_node();
+ if (auto* interpreter = interpreter_if_exists())
+ call_frame.current_node = interpreter->current_node();
call_frame.is_strict_mode = function.is_strict_mode();
push_call_frame(call_frame, function.global_object());
@@ -338,7 +339,8 @@ Value VM::call_internal(Function& function, Value this_value, Optional<MarkedVal
CallFrame call_frame;
call_frame.callee = &function;
- call_frame.current_node = current_node();
+ if (auto* interpreter = interpreter_if_exists())
+ call_frame.current_node = interpreter->current_node();
call_frame.is_strict_mode = function.is_strict_mode();
call_frame.function_name = function.name();
call_frame.this_value = function.bound_this().value_or(this_value);
diff --git a/Userland/Libraries/LibJS/Runtime/VM.h b/Userland/Libraries/LibJS/Runtime/VM.h
index 1dca17e66f9d..025d83e25e91 100644
--- a/Userland/Libraries/LibJS/Runtime/VM.h
+++ b/Userland/Libraries/LibJS/Runtime/VM.h
@@ -128,15 +128,10 @@ class VM : public RefCounted<VM> {
void pop_call_frame() { m_call_stack.take_last(); }
- void push_ast_node(const ASTNode& node) { m_ast_nodes.append(&node); }
- void pop_ast_node() { m_ast_nodes.take_last(); }
-
CallFrame& call_frame() { return *m_call_stack.last(); }
const CallFrame& call_frame() const { return *m_call_stack.last(); }
const Vector<CallFrame*>& call_stack() const { return m_call_stack; }
Vector<CallFrame*>& call_stack() { return m_call_stack; }
- const ASTNode* current_node() const { return !m_ast_nodes.is_empty() ? m_ast_nodes.last() : nullptr; }
- const Vector<const ASTNode*>& node_stack() const { return m_ast_nodes; }
const ScopeObject* current_scope() const { return call_frame().scope; }
ScopeObject* current_scope() { return call_frame().scope; }
@@ -256,7 +251,6 @@ class VM : public RefCounted<VM> {
Vector<Interpreter*> m_interpreters;
Vector<CallFrame*> m_call_stack;
- Vector<const ASTNode*> m_ast_nodes;
Value m_last_value;
ScopeType m_unwind_until { ScopeType::None };
|
508d56318931c0d6a3fd077ac2dc9f83bbfe612b
|
2021-09-04 06:59:09
|
Tobias Christiansen
|
pixelpaint: Add ProjectLoader to abstract away opening of files
| false
|
Add ProjectLoader to abstract away opening of files
|
pixelpaint
|
diff --git a/Userland/Applications/PixelPaint/CMakeLists.txt b/Userland/Applications/PixelPaint/CMakeLists.txt
index fa7cf8e41d1f..3fe320a349b8 100644
--- a/Userland/Applications/PixelPaint/CMakeLists.txt
+++ b/Userland/Applications/PixelPaint/CMakeLists.txt
@@ -30,6 +30,7 @@ set(SOURCES
PenTool.cpp
PickerTool.cpp
PixelPaintWindowGML.h
+ ProjectLoader.cpp
RectangleTool.cpp
RectangleSelectTool.cpp
Mask.cpp
diff --git a/Userland/Applications/PixelPaint/Image.cpp b/Userland/Applications/PixelPaint/Image.cpp
index 524e03f3e93a..5d32cf2dc8b6 100644
--- a/Userland/Applications/PixelPaint/Image.cpp
+++ b/Userland/Applications/PixelPaint/Image.cpp
@@ -24,23 +24,6 @@
namespace PixelPaint {
-static RefPtr<Gfx::Bitmap> try_decode_bitmap(ByteBuffer const& bitmap_data)
-{
- // Spawn a new ImageDecoder service process and connect to it.
- auto client = ImageDecoderClient::Client::construct();
-
- // FIXME: Find a way to avoid the memory copying here.
- auto decoded_image_or_error = client->decode_image(bitmap_data);
- if (!decoded_image_or_error.has_value())
- return nullptr;
-
- // FIXME: Support multi-frame images?
- auto decoded_image = decoded_image_or_error.release_value();
- if (decoded_image.frames.is_empty())
- return nullptr;
- return move(decoded_image.frames[0].bitmap);
-}
-
RefPtr<Image> Image::try_create_with_size(Gfx::IntSize const& size)
{
if (size.is_empty())
@@ -72,6 +55,23 @@ void Image::paint_into(GUI::Painter& painter, Gfx::IntRect const& dest_rect) con
}
}
+RefPtr<Gfx::Bitmap> Image::try_decode_bitmap(ByteBuffer const& bitmap_data)
+{
+ // Spawn a new ImageDecoder service process and connect to it.
+ auto client = ImageDecoderClient::Client::construct();
+
+ // FIXME: Find a way to avoid the memory copying here.
+ auto decoded_image_or_error = client->decode_image(bitmap_data);
+ if (!decoded_image_or_error.has_value())
+ return nullptr;
+
+ // FIXME: Support multi-frame images?
+ auto decoded_image = decoded_image_or_error.release_value();
+ if (decoded_image.frames.is_empty())
+ return nullptr;
+ return move(decoded_image.frames[0].bitmap);
+}
+
RefPtr<Image> Image::try_create_from_bitmap(NonnullRefPtr<Gfx::Bitmap> bitmap)
{
auto image = try_create_with_size({ bitmap->width(), bitmap->height() });
@@ -86,44 +86,6 @@ RefPtr<Image> Image::try_create_from_bitmap(NonnullRefPtr<Gfx::Bitmap> bitmap)
return image;
}
-Result<NonnullRefPtr<Image>, String> Image::try_create_from_pixel_paint_fd(int fd, String const& file_path)
-{
- auto file = Core::File::construct();
- file->open(fd, Core::OpenMode::ReadOnly, Core::File::ShouldCloseFileDescriptor::No);
- if (file->has_error())
- return String { file->error_string() };
-
- return try_create_from_pixel_paint_file(file, file_path);
-}
-
-Result<NonnullRefPtr<Image>, String> Image::try_create_from_pixel_paint_path(String const& file_path)
-{
- auto file_or_error = Core::File::open(file_path, Core::OpenMode::ReadOnly);
- if (file_or_error.is_error())
- return String { file_or_error.error().string() };
-
- return try_create_from_pixel_paint_file(*file_or_error.value(), file_path);
-}
-
-Result<NonnullRefPtr<Image>, String> Image::try_create_from_pixel_paint_file(Core::File& file, String const& file_path)
-{
- auto contents = file.read_all();
-
- auto json_or_error = JsonValue::from_string(contents);
- if (!json_or_error.has_value())
- return String { "Not a valid PP file"sv };
-
- auto& json = json_or_error.value().as_object();
- auto image_or_error = try_create_from_pixel_paint_json(json);
-
- if (image_or_error.is_error())
- return image_or_error.release_error();
-
- auto image = image_or_error.release_value();
- image->set_path(file_path);
- return image;
-}
-
Result<NonnullRefPtr<Image>, String> Image::try_create_from_pixel_paint_json(JsonObject const& json)
{
auto image = try_create_with_size({ json.get("width").to_i32(), json.get("height").to_i32() });
@@ -163,52 +125,6 @@ Result<NonnullRefPtr<Image>, String> Image::try_create_from_pixel_paint_json(Jso
return image.release_nonnull();
}
-Result<NonnullRefPtr<Image>, String> Image::try_create_from_fd_and_close(int fd, String const& file_path)
-{
- auto image_or_error = try_create_from_pixel_paint_fd(fd, file_path);
- if (!image_or_error.is_error()) {
- close(fd);
- return image_or_error.release_value();
- }
-
- auto file_or_error = MappedFile::map_from_fd_and_close(fd, file_path);
- if (file_or_error.is_error())
- return String::formatted("Unable to mmap file {}", file_or_error.error().string());
-
- auto& mapped_file = *file_or_error.value();
- // FIXME: Find a way to avoid the memory copy here.
- auto bitmap = try_decode_bitmap(ByteBuffer::copy(mapped_file.bytes()));
- if (!bitmap)
- return String { "Unable to decode image"sv };
- auto image = Image::try_create_from_bitmap(bitmap.release_nonnull());
- if (!image)
- return String { "Unable to allocate Image"sv };
- image->set_path(file_path);
- return image.release_nonnull();
-}
-
-Result<NonnullRefPtr<Image>, String> Image::try_create_from_path(String const& file_path)
-{
- auto image_or_error = try_create_from_pixel_paint_path(file_path);
- if (!image_or_error.is_error())
- return image_or_error.release_value();
-
- auto file_or_error = MappedFile::map(file_path);
- if (file_or_error.is_error())
- return String { "Unable to mmap file"sv };
-
- auto& mapped_file = *file_or_error.value();
- // FIXME: Find a way to avoid the memory copy here.
- auto bitmap = try_decode_bitmap(ByteBuffer::copy(mapped_file.bytes()));
- if (!bitmap)
- return String { "Unable to decode image"sv };
- auto image = Image::try_create_from_bitmap(bitmap.release_nonnull());
- if (!image)
- return String { "Unable to allocate Image"sv };
- image->set_path(file_path);
- return image.release_nonnull();
-}
-
void Image::serialize_as_json(JsonObjectSerializer<StringBuilder>& json) const
{
json.add("width", m_size.width());
diff --git a/Userland/Applications/PixelPaint/Image.h b/Userland/Applications/PixelPaint/Image.h
index 13430df76138..1ffa9d382ecb 100644
--- a/Userland/Applications/PixelPaint/Image.h
+++ b/Userland/Applications/PixelPaint/Image.h
@@ -46,10 +46,10 @@ class ImageClient {
class Image : public RefCounted<Image> {
public:
static RefPtr<Image> try_create_with_size(Gfx::IntSize const&);
- static Result<NonnullRefPtr<Image>, String> try_create_from_fd_and_close(int fd, String const& file_path);
- static Result<NonnullRefPtr<Image>, String> try_create_from_path(String const& file_path);
- static RefPtr<Image> try_create_from_bitmap(NonnullRefPtr<Gfx::Bitmap>);
static Result<NonnullRefPtr<Image>, String> try_create_from_pixel_paint_json(JsonObject const&);
+ static RefPtr<Image> try_create_from_bitmap(NonnullRefPtr<Gfx::Bitmap>);
+
+ static RefPtr<Gfx::Bitmap> try_decode_bitmap(const ByteBuffer& bitmap_data);
// This generates a new Bitmap with the final image (all layers composed according to their attributes.)
RefPtr<Gfx::Bitmap> try_compose_bitmap(Gfx::BitmapFormat format) const;
@@ -103,10 +103,6 @@ class Image : public RefCounted<Image> {
private:
explicit Image(Gfx::IntSize const&);
- static Result<NonnullRefPtr<Image>, String> try_create_from_pixel_paint_fd(int fd, String const& file_path);
- static Result<NonnullRefPtr<Image>, String> try_create_from_pixel_paint_path(String const& file_path);
- static Result<NonnullRefPtr<Image>, String> try_create_from_pixel_paint_file(Core::File& file, String const& file_path);
-
void did_change(Gfx::IntRect const& modified_rect = {});
void did_change_rect();
void did_modify_layer_stack();
diff --git a/Userland/Applications/PixelPaint/ProjectLoader.cpp b/Userland/Applications/PixelPaint/ProjectLoader.cpp
new file mode 100644
index 000000000000..0dfab4bdbf44
--- /dev/null
+++ b/Userland/Applications/PixelPaint/ProjectLoader.cpp
@@ -0,0 +1,75 @@
+/*
+ * Copyright (c) 2021, Tobias Christiansen <[email protected]>
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#include "ProjectLoader.h"
+#include "Image.h"
+#include "Layer.h"
+#include <AK/JsonObject.h>
+#include <AK/MappedFile.h>
+#include <AK/Result.h>
+#include <AK/String.h>
+#include <LibCore/File.h>
+#include <LibImageDecoderClient/Client.h>
+
+namespace PixelPaint {
+
+Result<void, String> ProjectLoader::try_load_from_fd_and_close(int fd, StringView path)
+{
+ auto file = Core::File::construct();
+ file->open(fd, Core::OpenMode::ReadOnly, Core::File::ShouldCloseFileDescriptor::No);
+ if (file->has_error())
+ return String { file->error_string() };
+
+ auto contents = file->read_all();
+
+ auto json_or_error = JsonValue::from_string(contents);
+ if (!json_or_error.has_value()) {
+ m_is_raw_image = true;
+
+ auto file_or_error = MappedFile::map_from_fd_and_close(fd, path);
+ if (file_or_error.is_error())
+ return String::formatted("Unable to mmap file {}", file_or_error.error().string());
+
+ auto& mapped_file = *file_or_error.value();
+ // FIXME: Find a way to avoid the memory copy here.
+ auto bitmap = Image::try_decode_bitmap(ByteBuffer::copy(mapped_file.bytes()));
+ if (!bitmap)
+ return String { "Unable to decode image"sv };
+ auto image = Image::try_create_from_bitmap(bitmap.release_nonnull());
+ if (!image)
+ return String { "Unable to allocate Image"sv };
+
+ image->set_path(path);
+ m_image = image;
+ return {};
+ }
+
+ close(fd);
+ auto& json = json_or_error.value().as_object();
+ auto image_or_error = Image::try_create_from_pixel_paint_json(json);
+
+ if (image_or_error.is_error())
+ return image_or_error.release_error();
+
+ auto image = image_or_error.release_value();
+ image->set_path(path);
+
+ if (json.has("guides"))
+ m_json_metadata = json.get("guides").as_array();
+
+ m_image = image;
+ return {};
+}
+Result<void, String> ProjectLoader::try_load_from_path(StringView path)
+{
+ auto file_or_error = Core::File::open(path, Core::OpenMode::ReadOnly);
+ if (file_or_error.is_error())
+ return String::formatted("Unable to open file because: {}", file_or_error.release_error());
+
+ return try_load_from_fd_and_close(file_or_error.release_value()->fd(), path);
+}
+
+}
diff --git a/Userland/Applications/PixelPaint/ProjectLoader.h b/Userland/Applications/PixelPaint/ProjectLoader.h
new file mode 100644
index 000000000000..eaed4eabbe41
--- /dev/null
+++ b/Userland/Applications/PixelPaint/ProjectLoader.h
@@ -0,0 +1,35 @@
+/*
+ * Copyright (c) 2021, Tobias Christiansen <[email protected]>
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#pragma once
+
+#include "Image.h"
+#include <AK/JsonArray.h>
+#include <AK/Result.h>
+#include <AK/StringView.h>
+
+namespace PixelPaint {
+
+class ProjectLoader {
+public:
+ ProjectLoader() = default;
+ ~ProjectLoader() = default;
+
+ Result<void, String> try_load_from_fd_and_close(int fd, StringView path);
+ Result<void, String> try_load_from_path(StringView path);
+
+ bool is_raw_image() const { return m_is_raw_image; }
+ bool has_image() const { return !m_image.is_null(); }
+ RefPtr<Image> release_image() const { return move(m_image); }
+ JsonArray const& json_metadata() const { return m_json_metadata; }
+
+private:
+ RefPtr<Image> m_image { nullptr };
+ bool m_is_raw_image { false };
+ JsonArray m_json_metadata {};
+};
+
+}
diff --git a/Userland/Applications/PixelPaint/main.cpp b/Userland/Applications/PixelPaint/main.cpp
index 26dbc1e81eab..5f88543da984 100644
--- a/Userland/Applications/PixelPaint/main.cpp
+++ b/Userland/Applications/PixelPaint/main.cpp
@@ -16,6 +16,7 @@
#include "LayerListWidget.h"
#include "LayerPropertiesWidget.h"
#include "PaletteWidget.h"
+#include "ProjectLoader.h"
#include "Tool.h"
#include "ToolPropertiesWidget.h"
#include "ToolboxWidget.h"
@@ -114,6 +115,7 @@ int main(int argc, char** argv)
};
Function<PixelPaint::ImageEditor&(NonnullRefPtr<PixelPaint::Image>)> create_new_editor;
+ PixelPaint::ProjectLoader loader;
auto& layer_list_widget = *main_widget.find_descendant_of_type_named<PixelPaint::LayerListWidget>("layer_list_widget");
layer_list_widget.on_layer_select = [&](auto* layer) {
@@ -151,23 +153,25 @@ int main(int argc, char** argv)
window);
auto open_image_file = [&](auto& path) {
- auto image_or_error = PixelPaint::Image::try_create_from_path(path);
- if (image_or_error.is_error()) {
+ auto try_load = loader.try_load_from_path(path);
+ if (try_load.is_error()) {
GUI::MessageBox::show_error(window, String::formatted("Unable to open file: {}", path));
return;
}
- auto& image = *image_or_error.value();
+ auto& image = *loader.release_image();
create_new_editor(image);
layer_list_widget.set_image(&image);
};
auto open_image_fd = [&](int fd, auto& path) {
- auto image_or_error = PixelPaint::Image::try_create_from_fd_and_close(fd, path);
- if (image_or_error.is_error()) {
- GUI::MessageBox::show_error(window, String::formatted("Unable to open file: {}, {}", path, image_or_error.error()));
+ auto try_load = loader.try_load_from_fd_and_close(fd, path);
+
+ if (try_load.is_error()) {
+ GUI::MessageBox::show_error(window, String::formatted("Unable to open file: {}, {}", path, try_load.error()));
return;
}
- auto& image = *image_or_error.value();
+
+ auto& image = *loader.release_image();
create_new_editor(image);
layer_list_widget.set_image(&image);
};
|
9c65c102452adddfa1bf1d2f8c79ed760eb1c647
|
2021-07-24 04:02:07
|
Tobias Christiansen
|
libweb: Add calc() resolution to CSS::Length
| false
|
Add calc() resolution to CSS::Length
|
libweb
|
diff --git a/Userland/Libraries/LibWeb/CSS/Length.cpp b/Userland/Libraries/LibWeb/CSS/Length.cpp
index a8c73d134a0a..2b2c91d6d714 100644
--- a/Userland/Libraries/LibWeb/CSS/Length.cpp
+++ b/Userland/Libraries/LibWeb/CSS/Length.cpp
@@ -1,9 +1,13 @@
/*
* Copyright (c) 2020, Andreas Kling <[email protected]>
+ * Copyright (c) 2021, Tobias Christiansen <[email protected]>
*
* SPDX-License-Identifier: BSD-2-Clause
*/
+#include <AK/NonnullOwnPtr.h>
+#include <AK/NonnullOwnPtrVector.h>
+#include <AK/Variant.h>
#include <LibWeb/CSS/Length.h>
#include <LibWeb/DOM/Document.h>
#include <LibWeb/HTML/HTMLHtmlElement.h>
@@ -39,6 +43,123 @@ float Length::relative_length_to_px(const Layout::Node& layout_node) const
}
}
+static float resolve_calc_value(CalculatedStyleValue::CalcValue const&, const Layout::Node& layout_node, float reference_for_percent);
+static float resolve_calc_number_value(CalculatedStyleValue::CalcNumberValue const&);
+static float resolve_calc_product(NonnullOwnPtr<CalculatedStyleValue::CalcProduct> const&, const Layout::Node& layout_node, float reference_for_percent);
+static float resolve_calc_sum(NonnullOwnPtr<CalculatedStyleValue::CalcSum> const&, const Layout::Node& layout_node, float reference_for_percent);
+static float resolve_calc_number_sum(NonnullOwnPtr<CalculatedStyleValue::CalcNumberSum> const&);
+static float resolve_calc_number_product(NonnullOwnPtr<CalculatedStyleValue::CalcNumberProduct> const&);
+
+float Length::resolve_calculated_value(const Layout::Node& layout_node, float reference_for_percent) const
+{
+ if (!m_calculated_style)
+ return 0.0f;
+
+ auto& expression = m_calculated_style->expression();
+
+ auto length = resolve_calc_sum(expression, layout_node, reference_for_percent);
+ return length;
+};
+
+static float resolve_calc_value(CalculatedStyleValue::CalcValue const& calc_value, const Layout::Node& layout_node, float reference_for_percent)
+{
+ return calc_value.visit(
+ [](float value) { return value; },
+ [&](Length length) {
+ return length.resolved_or_zero(layout_node, reference_for_percent).to_px(layout_node);
+ },
+ [&](NonnullOwnPtr<CalculatedStyleValue::CalcSum>& calc_sum) {
+ return resolve_calc_sum(calc_sum, layout_node, reference_for_percent);
+ },
+ [](auto&) {
+ VERIFY_NOT_REACHED();
+ return 0.0f;
+ });
+}
+
+static float resolve_calc_number_product(NonnullOwnPtr<CalculatedStyleValue::CalcNumberProduct> const& calc_number_product)
+{
+ auto value = resolve_calc_number_value(calc_number_product->first_calc_number_value);
+
+ for (auto& additional_number_value : calc_number_product->zero_or_more_additional_calc_number_values) {
+ auto additional_value = resolve_calc_number_value(additional_number_value.value);
+ if (additional_number_value.op == CalculatedStyleValue::CalcNumberProductPartWithOperator::Multiply)
+ value *= additional_value;
+ else if (additional_number_value.op == CalculatedStyleValue::CalcNumberProductPartWithOperator::Divide)
+ value /= additional_value;
+ else
+ VERIFY_NOT_REACHED();
+ }
+
+ return value;
+}
+
+static float resolve_calc_number_sum(NonnullOwnPtr<CalculatedStyleValue::CalcNumberSum> const& calc_number_sum)
+{
+ auto value = resolve_calc_number_product(calc_number_sum->first_calc_number_product);
+
+ for (auto& additional_product : calc_number_sum->zero_or_more_additional_calc_number_products) {
+ auto additional_value = resolve_calc_number_product(additional_product.calc_number_product);
+ if (additional_product.op == CSS::CalculatedStyleValue::CalcNumberSumPartWithOperator::Add)
+ value += additional_value;
+ else if (additional_product.op == CSS::CalculatedStyleValue::CalcNumberSumPartWithOperator::Subtract)
+ value -= additional_value;
+ else
+ VERIFY_NOT_REACHED();
+ }
+
+ return value;
+}
+
+static float resolve_calc_number_value(CalculatedStyleValue::CalcNumberValue const& number_value)
+{
+ return number_value.visit(
+ [](float number) { return number; },
+ [](NonnullOwnPtr<CalculatedStyleValue::CalcNumberSum>& calc_number_sum) {
+ return resolve_calc_number_sum(calc_number_sum);
+ });
+}
+
+static float resolve_calc_product(NonnullOwnPtr<CalculatedStyleValue::CalcProduct> const& calc_product, const Layout::Node& layout_node, float reference_for_percent)
+{
+ auto value = resolve_calc_value(calc_product->first_calc_value, layout_node, reference_for_percent);
+
+ for (auto& additional_value : calc_product->zero_or_more_additional_calc_values) {
+ additional_value.value.visit(
+ [&](CalculatedStyleValue::CalcValue const& calc_value) {
+ if (additional_value.op != CalculatedStyleValue::CalcProductPartWithOperator::Multiply)
+ VERIFY_NOT_REACHED();
+ auto resolved_value = resolve_calc_value(calc_value, layout_node, reference_for_percent);
+ value *= resolved_value;
+ },
+ [&](CalculatedStyleValue::CalcNumberValue const& calc_number_value) {
+ if (additional_value.op != CalculatedStyleValue::CalcProductPartWithOperator::Divide)
+ VERIFY_NOT_REACHED();
+ auto resolved_calc_number_value = resolve_calc_number_value(calc_number_value);
+ value /= resolved_calc_number_value;
+ });
+ }
+
+ return value;
+}
+
+static float resolve_calc_sum(NonnullOwnPtr<CalculatedStyleValue::CalcSum> const& calc_sum, const Layout::Node& layout_node, float reference_for_percent)
+{
+ auto value = resolve_calc_product(calc_sum->first_calc_product, layout_node, reference_for_percent);
+
+ for (auto& additional_product : calc_sum->zero_or_more_additional_calc_products) {
+ auto additional_value = resolve_calc_product(additional_product.calc_product, layout_node, reference_for_percent);
+ if (additional_product.op == CalculatedStyleValue::CalcSumPartWithOperator::Operation::Add)
+ value += additional_value;
+ else if (additional_product.op == CalculatedStyleValue::CalcSumPartWithOperator::Operation::Subtract)
+ value -= additional_value;
+ else
+ VERIFY_NOT_REACHED();
+ }
+
+ return value;
+}
+
const char* Length::unit_name() const
{
switch (m_type) {
diff --git a/Userland/Libraries/LibWeb/CSS/Length.h b/Userland/Libraries/LibWeb/CSS/Length.h
index c9c8c465d14c..5e14e11818fe 100644
--- a/Userland/Libraries/LibWeb/CSS/Length.h
+++ b/Userland/Libraries/LibWeb/CSS/Length.h
@@ -53,10 +53,10 @@ class Length {
{
if (is_undefined())
return fallback_for_undefined;
+ if (is_calculated())
+ return Length(resolve_calculated_value(layout_node, reference_for_percent), Type::Px);
if (is_percentage())
return make_px(raw_value() / 100.0f * reference_for_percent);
- if (is_calculated())
- return {};
if (is_relative())
return make_px(to_px(layout_node));
return *this;
@@ -153,6 +153,7 @@ class Length {
private:
float relative_length_to_px(const Layout::Node&) const;
+ float resolve_calculated_value(const Layout::Node& layout_node, float reference_for_percent) const;
const char* unit_name() const;
|
07e13e9868b933c5d51271c5e483724485da36fe
|
2020-08-02 21:04:50
|
Andreas Kling
|
libweb: Only allow editing of elements with contenteditable="true"
| false
|
Only allow editing of elements with contenteditable="true"
|
libweb
|
diff --git a/Base/res/html/misc/welcome.html b/Base/res/html/misc/welcome.html
index dc1f7371e0d0..6bd40f935ce7 100644
--- a/Base/res/html/misc/welcome.html
+++ b/Base/res/html/misc/welcome.html
@@ -1,5 +1,5 @@
<!DOCTYPE html>
-<html>
+<html contenteditable="true">
<head>
<title>Welcome!</title>
<!-- this is a comment -->
diff --git a/Libraries/LibWeb/DOM/AttributeNames.h b/Libraries/LibWeb/DOM/AttributeNames.h
index 4f45cde8c6e8..5a1b5fcdded5 100644
--- a/Libraries/LibWeb/DOM/AttributeNames.h
+++ b/Libraries/LibWeb/DOM/AttributeNames.h
@@ -34,51 +34,52 @@ namespace AttributeNames {
void initialize();
-#define ENUMERATE_HTML_ATTRIBUTES \
- __ENUMERATE_HTML_ATTRIBUTE(abbr) \
- __ENUMERATE_HTML_ATTRIBUTE(accept) \
- __ENUMERATE_HTML_ATTRIBUTE(action) \
- __ENUMERATE_HTML_ATTRIBUTE(align) \
- __ENUMERATE_HTML_ATTRIBUTE(allow) \
- __ENUMERATE_HTML_ATTRIBUTE(alt) \
- __ENUMERATE_HTML_ATTRIBUTE(async) \
- __ENUMERATE_HTML_ATTRIBUTE(bgcolor) \
- __ENUMERATE_HTML_ATTRIBUTE(class_) \
- __ENUMERATE_HTML_ATTRIBUTE(colspan) \
- __ENUMERATE_HTML_ATTRIBUTE(data) \
- __ENUMERATE_HTML_ATTRIBUTE(download) \
- __ENUMERATE_HTML_ATTRIBUTE(defer) \
- __ENUMERATE_HTML_ATTRIBUTE(dirname) \
- __ENUMERATE_HTML_ATTRIBUTE(headers) \
- __ENUMERATE_HTML_ATTRIBUTE(height) \
- __ENUMERATE_HTML_ATTRIBUTE(href) \
- __ENUMERATE_HTML_ATTRIBUTE(hreflang) \
- __ENUMERATE_HTML_ATTRIBUTE(id) \
- __ENUMERATE_HTML_ATTRIBUTE(imagesizes) \
- __ENUMERATE_HTML_ATTRIBUTE(imagesrcset) \
- __ENUMERATE_HTML_ATTRIBUTE(integrity) \
- __ENUMERATE_HTML_ATTRIBUTE(lang) \
- __ENUMERATE_HTML_ATTRIBUTE(max) \
- __ENUMERATE_HTML_ATTRIBUTE(media) \
- __ENUMERATE_HTML_ATTRIBUTE(method) \
- __ENUMERATE_HTML_ATTRIBUTE(min) \
- __ENUMERATE_HTML_ATTRIBUTE(name) \
- __ENUMERATE_HTML_ATTRIBUTE(pattern) \
- __ENUMERATE_HTML_ATTRIBUTE(ping) \
- __ENUMERATE_HTML_ATTRIBUTE(placeholder) \
- __ENUMERATE_HTML_ATTRIBUTE(rel) \
- __ENUMERATE_HTML_ATTRIBUTE(size) \
- __ENUMERATE_HTML_ATTRIBUTE(sizes) \
- __ENUMERATE_HTML_ATTRIBUTE(src) \
- __ENUMERATE_HTML_ATTRIBUTE(srcdoc) \
- __ENUMERATE_HTML_ATTRIBUTE(srcset) \
- __ENUMERATE_HTML_ATTRIBUTE(step) \
- __ENUMERATE_HTML_ATTRIBUTE(style) \
- __ENUMERATE_HTML_ATTRIBUTE(target) \
- __ENUMERATE_HTML_ATTRIBUTE(title) \
- __ENUMERATE_HTML_ATTRIBUTE(type) \
- __ENUMERATE_HTML_ATTRIBUTE(usemap) \
- __ENUMERATE_HTML_ATTRIBUTE(value) \
+#define ENUMERATE_HTML_ATTRIBUTES \
+ __ENUMERATE_HTML_ATTRIBUTE(abbr) \
+ __ENUMERATE_HTML_ATTRIBUTE(accept) \
+ __ENUMERATE_HTML_ATTRIBUTE(action) \
+ __ENUMERATE_HTML_ATTRIBUTE(align) \
+ __ENUMERATE_HTML_ATTRIBUTE(allow) \
+ __ENUMERATE_HTML_ATTRIBUTE(alt) \
+ __ENUMERATE_HTML_ATTRIBUTE(async) \
+ __ENUMERATE_HTML_ATTRIBUTE(bgcolor) \
+ __ENUMERATE_HTML_ATTRIBUTE(class_) \
+ __ENUMERATE_HTML_ATTRIBUTE(colspan) \
+ __ENUMERATE_HTML_ATTRIBUTE(contenteditable) \
+ __ENUMERATE_HTML_ATTRIBUTE(data) \
+ __ENUMERATE_HTML_ATTRIBUTE(download) \
+ __ENUMERATE_HTML_ATTRIBUTE(defer) \
+ __ENUMERATE_HTML_ATTRIBUTE(dirname) \
+ __ENUMERATE_HTML_ATTRIBUTE(headers) \
+ __ENUMERATE_HTML_ATTRIBUTE(height) \
+ __ENUMERATE_HTML_ATTRIBUTE(href) \
+ __ENUMERATE_HTML_ATTRIBUTE(hreflang) \
+ __ENUMERATE_HTML_ATTRIBUTE(id) \
+ __ENUMERATE_HTML_ATTRIBUTE(imagesizes) \
+ __ENUMERATE_HTML_ATTRIBUTE(imagesrcset) \
+ __ENUMERATE_HTML_ATTRIBUTE(integrity) \
+ __ENUMERATE_HTML_ATTRIBUTE(lang) \
+ __ENUMERATE_HTML_ATTRIBUTE(max) \
+ __ENUMERATE_HTML_ATTRIBUTE(media) \
+ __ENUMERATE_HTML_ATTRIBUTE(method) \
+ __ENUMERATE_HTML_ATTRIBUTE(min) \
+ __ENUMERATE_HTML_ATTRIBUTE(name) \
+ __ENUMERATE_HTML_ATTRIBUTE(pattern) \
+ __ENUMERATE_HTML_ATTRIBUTE(ping) \
+ __ENUMERATE_HTML_ATTRIBUTE(placeholder) \
+ __ENUMERATE_HTML_ATTRIBUTE(rel) \
+ __ENUMERATE_HTML_ATTRIBUTE(size) \
+ __ENUMERATE_HTML_ATTRIBUTE(sizes) \
+ __ENUMERATE_HTML_ATTRIBUTE(src) \
+ __ENUMERATE_HTML_ATTRIBUTE(srcdoc) \
+ __ENUMERATE_HTML_ATTRIBUTE(srcset) \
+ __ENUMERATE_HTML_ATTRIBUTE(step) \
+ __ENUMERATE_HTML_ATTRIBUTE(style) \
+ __ENUMERATE_HTML_ATTRIBUTE(target) \
+ __ENUMERATE_HTML_ATTRIBUTE(title) \
+ __ENUMERATE_HTML_ATTRIBUTE(type) \
+ __ENUMERATE_HTML_ATTRIBUTE(usemap) \
+ __ENUMERATE_HTML_ATTRIBUTE(value) \
__ENUMERATE_HTML_ATTRIBUTE(width)
#define __ENUMERATE_HTML_ATTRIBUTE(name) extern FlyString name;
diff --git a/Libraries/LibWeb/DOM/Document.h b/Libraries/LibWeb/DOM/Document.h
index 3f8bfe7cf17f..6997e1b4934e 100644
--- a/Libraries/LibWeb/DOM/Document.h
+++ b/Libraries/LibWeb/DOM/Document.h
@@ -157,6 +157,9 @@ class Document
const DocumentType* doctype() const;
const String& compat_mode() const;
+ void set_editable(bool editable) { m_editable = editable; }
+ virtual bool is_editable() const final;
+
private:
virtual RefPtr<LayoutNode> create_layout_node(const CSS::StyleProperties* parent_style) override;
@@ -186,6 +189,7 @@ class Document
NonnullRefPtrVector<HTML::HTMLScriptElement> m_scripts_to_execute_as_soon_as_possible;
QuirksMode m_quirks_mode { QuirksMode::No };
+ bool m_editable { false };
};
}
diff --git a/Libraries/LibWeb/DOM/Element.cpp b/Libraries/LibWeb/DOM/Element.cpp
index 78a2fc712063..6c8b08b47d44 100644
--- a/Libraries/LibWeb/DOM/Element.cpp
+++ b/Libraries/LibWeb/DOM/Element.cpp
@@ -290,4 +290,22 @@ String Element::inner_html() const
return builder.to_string();
}
+bool Element::is_editable() const
+{
+ auto contenteditable = attribute(HTML::AttributeNames::contenteditable);
+ // "true" and the empty string map to the "true" state.
+ if ((!contenteditable.is_null() && contenteditable.is_empty()) || contenteditable.equals_ignoring_case("true"))
+ return true;
+ // "false" maps to the "false" state.
+ if (contenteditable.equals_ignoring_case("false"))
+ return false;
+ // "inherit", an invalid value, and a missing value all map to the "inherit" state.
+ return parent() && parent()->is_editable();
+}
+
+bool Document::is_editable() const
+{
+ return m_editable;
+}
+
}
diff --git a/Libraries/LibWeb/DOM/Element.h b/Libraries/LibWeb/DOM/Element.h
index 579bee58ba64..937db4382be4 100644
--- a/Libraries/LibWeb/DOM/Element.h
+++ b/Libraries/LibWeb/DOM/Element.h
@@ -82,6 +82,8 @@ class Element : public ParentNode {
String inner_html() const;
void set_inner_html(StringView);
+ virtual bool is_editable() const final;
+
protected:
RefPtr<LayoutNode> create_layout_node(const CSS::StyleProperties* parent_style) override;
diff --git a/Libraries/LibWeb/DOM/Node.cpp b/Libraries/LibWeb/DOM/Node.cpp
index 744c0f27d2b3..4370a540c680 100644
--- a/Libraries/LibWeb/DOM/Node.cpp
+++ b/Libraries/LibWeb/DOM/Node.cpp
@@ -217,4 +217,9 @@ void Node::set_document(Badge<Document>, Document& document)
m_document = &document;
}
+bool Node::is_editable() const
+{
+ return parent() && parent()->is_editable();
+}
+
}
diff --git a/Libraries/LibWeb/DOM/Node.h b/Libraries/LibWeb/DOM/Node.h
index cc73a7ac67f8..1bf2ab9d9b5e 100644
--- a/Libraries/LibWeb/DOM/Node.h
+++ b/Libraries/LibWeb/DOM/Node.h
@@ -75,6 +75,8 @@ class Node
bool is_parent_node() const { return is_element() || is_document() || is_document_fragment(); }
virtual bool is_svg_element() const { return false; }
+ virtual bool is_editable() const;
+
RefPtr<Node> append_child(NonnullRefPtr<Node>, bool notify = true);
RefPtr<Node> insert_before(NonnullRefPtr<Node> node, RefPtr<Node> child, bool notify = true);
diff --git a/Libraries/LibWeb/Layout/LayoutText.cpp b/Libraries/LibWeb/Layout/LayoutText.cpp
index 55696b5531d8..61839b4bb137 100644
--- a/Libraries/LibWeb/Layout/LayoutText.cpp
+++ b/Libraries/LibWeb/Layout/LayoutText.cpp
@@ -117,6 +117,9 @@ void LayoutText::paint_cursor_if_needed(PaintContext& context, const LineBoxFrag
if (!(frame().cursor_position().offset() >= (unsigned)fragment.start() && frame().cursor_position().offset() < (unsigned)(fragment.start() + fragment.length())))
return;
+ if (!fragment.layout_node().node() || !fragment.layout_node().node()->is_editable())
+ return;
+
auto fragment_rect = fragment.absolute_rect();
float cursor_x = fragment_rect.x() + specified_style().font().width(fragment.text().substring_view(0, frame().cursor_position().offset() - fragment.start()));
diff --git a/Libraries/LibWeb/Page/EventHandler.cpp b/Libraries/LibWeb/Page/EventHandler.cpp
index bf03ab46e3aa..76e6c3badb04 100644
--- a/Libraries/LibWeb/Page/EventHandler.cpp
+++ b/Libraries/LibWeb/Page/EventHandler.cpp
@@ -231,31 +231,33 @@ void EventHandler::dump_selection(const char* event_name) const
bool EventHandler::handle_keydown(KeyCode key, unsigned, u32 code_point)
{
- // FIXME: Support backspacing across DOM node boundaries.
- if (key == KeyCode::Key_Backspace && m_frame.cursor_position().offset() > 0) {
- auto& text_node = downcast<DOM::Text>(*m_frame.cursor_position().node());
- StringBuilder builder;
- builder.append(text_node.data().substring_view(0, m_frame.cursor_position().offset() - 1));
- builder.append(text_node.data().substring_view(m_frame.cursor_position().offset(), text_node.data().length() - m_frame.cursor_position().offset()));
- text_node.set_data(builder.to_string());
- m_frame.set_cursor_position({ *m_frame.cursor_position().node(), m_frame.cursor_position().offset() - 1 });
- // FIXME: This should definitely use incremental layout invalidation instead!
- text_node.document().force_layout();
- return true;
- }
+ if (m_frame.cursor_position().node() && m_frame.cursor_position().node()->is_editable()) {
+ // FIXME: Support backspacing across DOM node boundaries.
+ if (key == KeyCode::Key_Backspace && m_frame.cursor_position().offset() > 0) {
+ auto& text_node = downcast<DOM::Text>(*m_frame.cursor_position().node());
+ StringBuilder builder;
+ builder.append(text_node.data().substring_view(0, m_frame.cursor_position().offset() - 1));
+ builder.append(text_node.data().substring_view(m_frame.cursor_position().offset(), text_node.data().length() - m_frame.cursor_position().offset()));
+ text_node.set_data(builder.to_string());
+ m_frame.set_cursor_position({ *m_frame.cursor_position().node(), m_frame.cursor_position().offset() - 1 });
+ // FIXME: This should definitely use incremental layout invalidation instead!
+ text_node.document().force_layout();
+ return true;
+ }
- if (code_point && m_frame.cursor_position().is_valid() && is<DOM::Text>(*m_frame.cursor_position().node())) {
- auto& text_node = downcast<DOM::Text>(*m_frame.cursor_position().node());
- StringBuilder builder;
- builder.append(text_node.data().substring_view(0, m_frame.cursor_position().offset()));
- builder.append_codepoint(code_point);
- builder.append(text_node.data().substring_view(m_frame.cursor_position().offset(), text_node.data().length() - m_frame.cursor_position().offset()));
- text_node.set_data(builder.to_string());
- // FIXME: This will advance the cursor incorrectly when inserting multiple whitespaces (DOM vs layout whitespace collapse difference.)
- m_frame.set_cursor_position({ *m_frame.cursor_position().node(), m_frame.cursor_position().offset() + 1 });
- // FIXME: This should definitely use incremental layout invalidation instead!
- text_node.document().force_layout();
- return true;
+ if (code_point && m_frame.cursor_position().is_valid() && is<DOM::Text>(*m_frame.cursor_position().node())) {
+ auto& text_node = downcast<DOM::Text>(*m_frame.cursor_position().node());
+ StringBuilder builder;
+ builder.append(text_node.data().substring_view(0, m_frame.cursor_position().offset()));
+ builder.append_codepoint(code_point);
+ builder.append(text_node.data().substring_view(m_frame.cursor_position().offset(), text_node.data().length() - m_frame.cursor_position().offset()));
+ text_node.set_data(builder.to_string());
+ // FIXME: This will advance the cursor incorrectly when inserting multiple whitespaces (DOM vs layout whitespace collapse difference.)
+ m_frame.set_cursor_position({ *m_frame.cursor_position().node(), m_frame.cursor_position().offset() + 1 });
+ // FIXME: This should definitely use incremental layout invalidation instead!
+ text_node.document().force_layout();
+ return true;
+ }
}
return false;
}
|
7d40e3eb0d3f3335bc5de180c435e6b05a0422ab
|
2023-01-05 22:12:31
|
Sam Atkins
|
libweb: Replace all px Length creation with Length::make_px(CSSPixels)
| false
|
Replace all px Length creation with Length::make_px(CSSPixels)
|
libweb
|
diff --git a/Userland/Libraries/LibWeb/CSS/Length.cpp b/Userland/Libraries/LibWeb/CSS/Length.cpp
index 68c7b65678c6..d2a964f04a6c 100644
--- a/Userland/Libraries/LibWeb/CSS/Length.cpp
+++ b/Userland/Libraries/LibWeb/CSS/Length.cpp
@@ -29,11 +29,6 @@ Length::Length(float value, Type type)
, m_value(value)
{
}
-Length::Length(CSSPixels value, Type type)
- : m_type(type)
- , m_value(value.value())
-{
-}
Length::~Length() = default;
Length Length::make_auto()
@@ -41,11 +36,6 @@ Length Length::make_auto()
return Length(0, Type::Auto);
}
-Length Length::make_px(float value)
-{
- return Length(value, Type::Px);
-}
-
Length Length::make_px(CSSPixels value)
{
return Length(value.value(), Type::Px);
diff --git a/Userland/Libraries/LibWeb/CSS/Length.h b/Userland/Libraries/LibWeb/CSS/Length.h
index bc4687e7f7c9..c8c549ad7d22 100644
--- a/Userland/Libraries/LibWeb/CSS/Length.h
+++ b/Userland/Libraries/LibWeb/CSS/Length.h
@@ -41,11 +41,9 @@ class Length {
// this file already. To break the cyclic dependency, we must move all method definitions out.
Length(int value, Type type);
Length(float value, Type type);
- Length(CSSPixels value, Type type);
~Length();
static Length make_auto();
- static Length make_px(float value);
static Length make_px(CSSPixels value);
static Length make_calculated(NonnullRefPtr<CalculatedStyleValue>);
Length percentage_of(Percentage const&) const;
diff --git a/Userland/Libraries/LibWeb/CSS/Parser/Parser.cpp b/Userland/Libraries/LibWeb/CSS/Parser/Parser.cpp
index dbe1e8fd024b..fa222c3d74f8 100644
--- a/Userland/Libraries/LibWeb/CSS/Parser/Parser.cpp
+++ b/Userland/Libraries/LibWeb/CSS/Parser/Parser.cpp
@@ -5028,7 +5028,7 @@ RefPtr<StyleValue> Parser::parse_flex_value(Vector<ComponentValue> const& compon
// Zero is a valid value for basis, but only if grow and shrink are already specified.
if (value->has_number() && value->to_number() == 0) {
if (flex_grow && flex_shrink && !flex_basis) {
- flex_basis = LengthStyleValue::create(Length(0, Length::Type::Px));
+ flex_basis = LengthStyleValue::create(Length::make_px(0));
continue;
}
}
diff --git a/Userland/Libraries/LibWeb/CSS/StyleValue.h b/Userland/Libraries/LibWeb/CSS/StyleValue.h
index 1a9e1ed552e1..5c2a495464fe 100644
--- a/Userland/Libraries/LibWeb/CSS/StyleValue.h
+++ b/Userland/Libraries/LibWeb/CSS/StyleValue.h
@@ -1508,7 +1508,7 @@ class NumericStyleValue : public StyleValue {
}
virtual bool has_length() const override { return to_number() == 0; }
- virtual Length to_length() const override { return Length(0, Length::Type::Px); }
+ virtual Length to_length() const override { return Length::make_px(0); }
virtual bool has_number() const override { return true; }
virtual float to_number() const override
diff --git a/Userland/Libraries/LibWeb/SVG/SVGGraphicsElement.cpp b/Userland/Libraries/LibWeb/SVG/SVGGraphicsElement.cpp
index cc49c2dfd2b9..f435327415b9 100644
--- a/Userland/Libraries/LibWeb/SVG/SVGGraphicsElement.cpp
+++ b/Userland/Libraries/LibWeb/SVG/SVGGraphicsElement.cpp
@@ -72,8 +72,8 @@ Optional<float> SVGGraphicsElement::stroke_width() const
float viewport_height = 0;
if (auto* svg_svg_element = first_ancestor_of_type<SVGSVGElement>()) {
if (auto* svg_svg_layout_node = svg_svg_element->layout_node()) {
- viewport_width = svg_svg_layout_node->computed_values().width().resolved(*svg_svg_layout_node, { 0, CSS::Length::Type::Px }).to_px(*svg_svg_layout_node);
- viewport_height = svg_svg_layout_node->computed_values().height().resolved(*svg_svg_layout_node, { 0, CSS::Length::Type::Px }).to_px(*svg_svg_layout_node);
+ viewport_width = svg_svg_layout_node->computed_values().width().resolved(*svg_svg_layout_node, CSS::Length::make_px(0)).to_px(*svg_svg_layout_node);
+ viewport_height = svg_svg_layout_node->computed_values().height().resolved(*svg_svg_layout_node, CSS::Length::make_px(0)).to_px(*svg_svg_layout_node);
}
}
auto scaled_viewport_size = CSS::Length::make_px((viewport_width + viewport_height) * 0.5f);
|
5908873b45ecf6dd43411b7df55701576b8e63a6
|
2022-09-20 14:02:13
|
Andreas Kling
|
libgui: Fire Show/Hide events when adding/removing widget from tree
| false
|
Fire Show/Hide events when adding/removing widget from tree
|
libgui
|
diff --git a/Userland/Libraries/LibGUI/Widget.cpp b/Userland/Libraries/LibGUI/Widget.cpp
index 1966f5a22ba5..cc16c057f205 100644
--- a/Userland/Libraries/LibGUI/Widget.cpp
+++ b/Userland/Libraries/LibGUI/Widget.cpp
@@ -219,6 +219,11 @@ void Widget::child_event(Core::ChildEvent& event)
}
if (window() && event.child() && is<Widget>(*event.child()))
window()->did_add_widget({}, verify_cast<Widget>(*event.child()));
+
+ if (event.child() && is<Widget>(*event.child()) && static_cast<Widget const&>(*event.child()).is_visible()) {
+ ShowEvent show_event;
+ event.child()->dispatch_event(show_event);
+ }
}
if (event.type() == Event::ChildRemoved) {
if (layout()) {
@@ -228,6 +233,10 @@ void Widget::child_event(Core::ChildEvent& event)
}
if (window() && event.child() && is<Widget>(*event.child()))
window()->did_remove_widget({}, verify_cast<Widget>(*event.child()));
+ if (event.child() && is<Widget>(*event.child())) {
+ HideEvent hide_event;
+ event.child()->dispatch_event(hide_event);
+ }
update();
}
return Core::Object::child_event(event);
|
4f47146433fb668bbbb67634a1dc936e53830279
|
2019-10-05 13:44:09
|
Andreas Kling
|
libgui: Add a "reload" action to GCommonActions
| false
|
Add a "reload" action to GCommonActions
|
libgui
|
diff --git a/Base/res/icons/16x16/reload.png b/Base/res/icons/16x16/reload.png
new file mode 100644
index 000000000000..24ba46e1f53a
Binary files /dev/null and b/Base/res/icons/16x16/reload.png differ
diff --git a/Libraries/LibGUI/GAction.cpp b/Libraries/LibGUI/GAction.cpp
index db134423b831..73376b0977fa 100644
--- a/Libraries/LibGUI/GAction.cpp
+++ b/Libraries/LibGUI/GAction.cpp
@@ -71,6 +71,11 @@ NonnullRefPtr<GAction> make_go_forward_action(Function<void(GAction&)> callback,
return GAction::create("Go forward", { Mod_Alt, Key_Right }, GraphicsBitmap::load_from_file("/res/icons/16x16/go-forward.png"), move(callback), widget);
}
+NonnullRefPtr<GAction> make_reload_action(Function<void(GAction&)> callback, GWidget* widget)
+{
+ return GAction::create("Reload", { Mod_Ctrl, Key_R }, GraphicsBitmap::load_from_file("/res/icons/16x16/reload.png"), move(callback), widget);
+}
+
}
GAction::GAction(const StringView& text, Function<void(GAction&)> on_activation_callback, GWidget* widget)
diff --git a/Libraries/LibGUI/GAction.h b/Libraries/LibGUI/GAction.h
index 6a91a372fd97..cb3e4752f22b 100644
--- a/Libraries/LibGUI/GAction.h
+++ b/Libraries/LibGUI/GAction.h
@@ -32,6 +32,7 @@ NonnullRefPtr<GAction> make_fullscreen_action(Function<void(GAction&)>, GWidget*
NonnullRefPtr<GAction> make_quit_action(Function<void(GAction&)>);
NonnullRefPtr<GAction> make_go_back_action(Function<void(GAction&)>, GWidget* widget = nullptr);
NonnullRefPtr<GAction> make_go_forward_action(Function<void(GAction&)>, GWidget* widget = nullptr);
+NonnullRefPtr<GAction> make_reload_action(Function<void(GAction&)>, GWidget* widget = nullptr);
};
class GAction : public RefCounted<GAction>
|
07e89ad5382d4c8881ac6e5d998659f57da34439
|
2022-08-15 02:22:35
|
Lucas CHOLLET
|
base: Launch ConfigServer at session start-up
| false
|
Launch ConfigServer at session start-up
|
base
|
diff --git a/Base/etc/SystemServer.ini b/Base/etc/SystemServer.ini
index 736fe8f3af9c..89c86d50e0ca 100644
--- a/Base/etc/SystemServer.ini
+++ b/Base/etc/SystemServer.ini
@@ -1,8 +1,3 @@
-[ConfigServer]
-Socket=/tmp/portal/config
-SocketPermissions=600
-User=anon
-
[RequestServer]
Socket=/tmp/portal/request
SocketPermissions=600
diff --git a/Base/home/anon/.config/SystemServer.ini b/Base/home/anon/.config/SystemServer.ini
index 1cb28c95cedb..75a20f682b33 100644
--- a/Base/home/anon/.config/SystemServer.ini
+++ b/Base/home/anon/.config/SystemServer.ini
@@ -1,3 +1,7 @@
+[ConfigServer]
+Socket=/tmp/user/%uid/portal/config
+SocketPermissions=600
+
[LaunchServer]
Socket=/tmp/user/%uid/portal/launch
SocketPermissions=600
diff --git a/Userland/Applications/Terminal/main.cpp b/Userland/Applications/Terminal/main.cpp
index efa09ad1074c..d6333b53731b 100644
--- a/Userland/Applications/Terminal/main.cpp
+++ b/Userland/Applications/Terminal/main.cpp
@@ -433,7 +433,7 @@ ErrorOr<int> serenity_main(Main::Arguments arguments)
TRY(Core::System::unveil("/bin/utmpupdate", "x"));
TRY(Core::System::unveil("/etc/FileIconProvider.ini", "r"));
TRY(Core::System::unveil("/tmp/user/%uid/portal/launch", "rw"));
- TRY(Core::System::unveil("/tmp/portal/config", "rw"));
+ TRY(Core::System::unveil("/tmp/user/%uid/portal/config", "rw"));
TRY(Core::System::unveil(nullptr, nullptr));
auto modified_state_check_timer = Core::Timer::create_repeating(500, [&] {
diff --git a/Userland/Libraries/LibConfig/Client.h b/Userland/Libraries/LibConfig/Client.h
index 48a93e349101..406dd3a93bf8 100644
--- a/Userland/Libraries/LibConfig/Client.h
+++ b/Userland/Libraries/LibConfig/Client.h
@@ -18,7 +18,7 @@ namespace Config {
class Client final
: public IPC::ConnectionToServer<ConfigClientEndpoint, ConfigServerEndpoint>
, public ConfigClientEndpoint {
- IPC_CLIENT_CONNECTION(Client, "/tmp/portal/config"sv)
+ IPC_CLIENT_CONNECTION(Client, "/tmp/user/%uid/portal/config"sv)
public:
void pledge_domains(Vector<String> const&);
|
529a8664f44a092ac2230ccbfa39032222c8a03d
|
2021-05-23 10:00:13
|
Brian Gianforcaro
|
userland: Tweak the visual display of the `bt` utility
| false
|
Tweak the visual display of the `bt` utility
|
userland
|
diff --git a/Userland/Utilities/bt.cpp b/Userland/Utilities/bt.cpp
index 957e407197e3..993d79d7e0c1 100644
--- a/Userland/Utilities/bt.cpp
+++ b/Userland/Utilities/bt.cpp
@@ -37,10 +37,14 @@ int main(int argc, char** argv)
while (iterator.has_next()) {
pid_t tid = iterator.next_path().to_int().value();
- outln("tid: {}", tid);
+ outln("thread: {}", tid);
+ outln("frames:");
auto symbols = Symbolication::symbolicate_thread(pid, tid);
+ auto frame_number = symbols.size() - 1;
for (auto& symbol : symbols) {
- out("{:p} ", symbol.address);
+ // Make kernel stack frames stand out.
+ int color = symbol.address < 0xc0000000 ? 35 : 31;
+ out("{:3}: \033[{};1m{:p}\033[0m | ", frame_number, color, symbol.address);
if (!symbol.name.is_empty())
out("{} ", symbol.name);
if (!symbol.filename.is_empty()) {
@@ -64,6 +68,7 @@ int main(int argc, char** argv)
out(")");
}
outln("");
+ frame_number--;
}
outln("");
}
|
7f98aaa65a03778cb54b0c85bb5a7df8f7e8eb1f
|
2021-05-05 02:06:58
|
Sergey Bugaev
|
userland: Pledge wpath & cpath in strace
| false
|
Pledge wpath & cpath in strace
|
userland
|
diff --git a/Userland/Utilities/strace.cpp b/Userland/Utilities/strace.cpp
index cc0099a889e0..7bd6e5fdefde 100644
--- a/Userland/Utilities/strace.cpp
+++ b/Userland/Utilities/strace.cpp
@@ -32,7 +32,7 @@ static void handle_sigint(int)
int main(int argc, char** argv)
{
- if (pledge("stdio proc exec ptrace sigaction", nullptr) < 0) {
+ if (pledge("stdio wpath cpath proc exec ptrace sigaction", nullptr) < 0) {
perror("pledge");
return 1;
}
@@ -60,6 +60,11 @@ int main(int argc, char** argv)
trace_file = open_result.value();
}
+ if (pledge("stdio proc exec ptrace sigaction", nullptr) < 0) {
+ perror("pledge");
+ return 1;
+ }
+
int status;
if (g_pid == -1) {
if (child_argv.is_empty()) {
|
84e17fcbcca4f1d572ff8b36978c3ee555ac62a0
|
2023-03-11 18:41:51
|
Aliaksandr Kalenik
|
webdriver: Fix crash in async execute script endpoint
| false
|
Fix crash in async execute script endpoint
|
webdriver
|
diff --git a/Userland/Libraries/LibWeb/WebDriver/ExecuteScript.cpp b/Userland/Libraries/LibWeb/WebDriver/ExecuteScript.cpp
index a2412ac5c040..60450d515de5 100644
--- a/Userland/Libraries/LibWeb/WebDriver/ExecuteScript.cpp
+++ b/Userland/Libraries/LibWeb/WebDriver/ExecuteScript.cpp
@@ -311,6 +311,8 @@ ExecuteScriptResultSerialized execute_script(Web::Page& page, DeprecatedString c
ExecuteScriptResultSerialized execute_async_script(Web::Page& page, DeprecatedString const& body, JS::MarkedVector<JS::Value> arguments, Optional<u64> const& timeout)
{
+ auto* document = page.top_level_browsing_context().active_document();
+ auto& settings_object = document->relevant_settings_object();
auto* window = page.top_level_browsing_context().active_window();
auto& realm = window->realm();
auto& vm = window->vm();
@@ -321,9 +323,15 @@ ExecuteScriptResultSerialized execute_async_script(Web::Page& page, DeprecatedSt
// FIXME: 5 Run the following substeps in parallel:
auto result = [&] {
+ // NOTE: We need to push an execution context in order to make create_resolving_functions() succeed.
+ vm.push_execution_context(settings_object.realm_execution_context());
+
// 1. Let resolvingFunctions be CreateResolvingFunctions(promise).
auto resolving_functions = promise->create_resolving_functions();
+ VERIFY(&settings_object.realm_execution_context() == &vm.running_execution_context());
+ vm.pop_execution_context();
+
// 2. Append resolvingFunctions.[[Resolve]] to arguments.
arguments.append(&resolving_functions.resolve);
|
5998e7f8a285bad44c6128c9ba1e9760ebac11c3
|
2022-04-26 01:34:53
|
MacDue
|
base: Add HighlightWindowBorder colors to Gruvbox Dark theme
| false
|
Add HighlightWindowBorder colors to Gruvbox Dark theme
|
base
|
diff --git a/Base/res/themes/Gruvbox Dark.ini b/Base/res/themes/Gruvbox Dark.ini
index 6054974c72b3..c53473ca8c58 100644
--- a/Base/res/themes/Gruvbox Dark.ini
+++ b/Base/res/themes/Gruvbox Dark.ini
@@ -10,8 +10,8 @@ InactiveWindowTitle=#bdae93
MovingWindowBorder1=#98971a
MovingWindowBorder2=#32302f
MovingWindowTitle=#ebdbb2
-HighlightWindowBorder1=#a10d0d
-HighlightWindowBorder2=#fabbbb
+HighlightWindowBorder1=#823517
+HighlightWindowBorder2=#383635
HighlightWindowTitle=#ebdbb2
HighlightSearching=#ebdbb2
HighlightSearchingText=#282828
|
cb3cc6ec27a76367bc90ad327dfb544fa1e618bd
|
2022-01-16 15:48:04
|
Michel Hermier
|
ak: Remove `kfree` definition
| false
|
Remove `kfree` definition
|
ak
|
diff --git a/AK/Demangle.h b/AK/Demangle.h
index a1a8521a8fd3..f3b7746af6d6 100644
--- a/AK/Demangle.h
+++ b/AK/Demangle.h
@@ -20,7 +20,7 @@ inline String demangle(StringView name)
auto* demangled_name = abi::__cxa_demangle(name.to_string().characters(), nullptr, nullptr, &status);
auto string = String(status == 0 ? demangled_name : name);
if (status == 0)
- kfree(demangled_name);
+ free(demangled_name);
return string;
}
diff --git a/AK/kmalloc.h b/AK/kmalloc.h
index 698d7998259f..183345c7538f 100644
--- a/AK/kmalloc.h
+++ b/AK/kmalloc.h
@@ -17,11 +17,10 @@
# define kmalloc malloc
# define kmalloc_good_size malloc_good_size
-# define kfree free
inline void kfree_sized(void* ptr, size_t)
{
- kfree(ptr);
+ free(ptr);
}
#endif
|
0c9db38e8f99af4ac005c1817cd3877601de83be
|
2021-05-22 19:22:11
|
Itamar
|
libcpp: Modify Token::to_string() to include more information
| false
|
Modify Token::to_string() to include more information
|
libcpp
|
diff --git a/Userland/Libraries/LibCpp/Parser.cpp b/Userland/Libraries/LibCpp/Parser.cpp
index da3ef9f5940d..d93b977dcab8 100644
--- a/Userland/Libraries/LibCpp/Parser.cpp
+++ b/Userland/Libraries/LibCpp/Parser.cpp
@@ -21,12 +21,7 @@ Parser::Parser(const StringView& program, const String& filename, Preprocessor::
if constexpr (CPP_DEBUG) {
dbgln("Tokens:");
for (auto& token : m_tokens) {
- StringView text;
- if (token.start().line != token.end().line || token.start().column > token.end().column)
- text = {};
- else
- text = text_of_token(token);
- dbgln("{} {}:{}-{}:{} ({})", token.to_string(), token.start().line, token.start().column, token.end().line, token.end().column, text);
+ dbgln("{}", token.to_string());
}
}
}
@@ -930,7 +925,7 @@ Optional<size_t> Parser::index_of_token_at(Position pos) const
void Parser::print_tokens() const
{
for (auto& token : m_tokens) {
- dbgln("{}", token.to_string());
+ outln("{}", token.to_string());
}
}
diff --git a/Userland/Libraries/LibCpp/SyntaxHighlighter.cpp b/Userland/Libraries/LibCpp/SyntaxHighlighter.cpp
index 79363df170ac..4b7d716b5196 100644
--- a/Userland/Libraries/LibCpp/SyntaxHighlighter.cpp
+++ b/Userland/Libraries/LibCpp/SyntaxHighlighter.cpp
@@ -63,7 +63,7 @@ void SyntaxHighlighter::rehighlight(const Palette& palette)
Vector<GUI::TextDocumentSpan> spans;
for (auto& token : tokens) {
- dbgln_if(SYNTAX_HIGHLIGHTING_DEBUG, "{} @ {}:{} - {}:{}", token.to_string(), token.start().line, token.start().column, token.end().line, token.end().column);
+ dbgln_if(SYNTAX_HIGHLIGHTING_DEBUG, "{} @ {}:{} - {}:{}", token.type_as_string(), token.start().line, token.start().column, token.end().line, token.end().column);
GUI::TextDocumentSpan span;
span.range.set_start({ token.start().line, token.start().column });
span.range.set_end({ token.end().line, token.end().column });
diff --git a/Userland/Libraries/LibCpp/Token.cpp b/Userland/Libraries/LibCpp/Token.cpp
index 06c21fcffe15..481ca0e42e92 100644
--- a/Userland/Libraries/LibCpp/Token.cpp
+++ b/Userland/Libraries/LibCpp/Token.cpp
@@ -5,6 +5,7 @@
*/
#include "Token.h"
+#include <AK/String.h>
namespace Cpp {
@@ -24,4 +25,15 @@ bool Position::operator<=(const Position& other) const
{
return !(*this > other);
}
+
+String Token::to_string() const
+{
+ return String::formatted("{} {}:{}-{}:{} ({})", type_to_string(m_type), start().line, start().column, end().line, end().column, text());
+}
+
+String Token::type_as_string() const
+{
+ return type_to_string(m_type);
+}
+
}
diff --git a/Userland/Libraries/LibCpp/Token.h b/Userland/Libraries/LibCpp/Token.h
index 3f9253b06a42..7a2fc919ed3b 100644
--- a/Userland/Libraries/LibCpp/Token.h
+++ b/Userland/Libraries/LibCpp/Token.h
@@ -116,10 +116,9 @@ struct Token {
VERIFY_NOT_REACHED();
}
- const char* to_string() const
- {
- return type_to_string(m_type);
- }
+ String to_string() const;
+ String type_as_string() const;
+
const Position& start() const { return m_start; }
const Position& end() const { return m_end; }
|
3b6325e7874292f78305014ab0312afad902b7cc
|
2021-09-20 02:23:35
|
Sam Atkins
|
libweb: Move InlineNode background code from `paint_fragment` -> `paint`
| false
|
Move InlineNode background code from `paint_fragment` -> `paint`
|
libweb
|
diff --git a/Userland/Libraries/LibWeb/Layout/InlineNode.cpp b/Userland/Libraries/LibWeb/Layout/InlineNode.cpp
index 0ef7b62d851b..bc7a6c8a8400 100644
--- a/Userland/Libraries/LibWeb/Layout/InlineNode.cpp
+++ b/Userland/Libraries/LibWeb/Layout/InlineNode.cpp
@@ -40,18 +40,17 @@ void InlineNode::split_into_lines(InlineFormattingContext& context, LayoutMode l
}
}
-void InlineNode::paint_fragment(PaintContext& context, const LineBoxFragment& fragment, PaintPhase phase) const
+void InlineNode::paint(PaintContext& context, PaintPhase phase)
{
auto& painter = context.painter();
if (phase == PaintPhase::Background) {
- painter.fill_rect(enclosing_int_rect(fragment.absolute_rect()), computed_values().background_color());
+ containing_block()->for_each_fragment([&](auto& fragment) {
+ if (is_inclusive_ancestor_of(fragment.layout_node()))
+ painter.fill_rect(enclosing_int_rect(fragment.absolute_rect()), computed_values().background_color());
+ return IterationDecision::Continue;
+ });
}
-}
-
-void InlineNode::paint(PaintContext& context, PaintPhase phase)
-{
- auto& painter = context.painter();
if (phase == PaintPhase::Foreground && document().inspected_node() == dom_node()) {
// FIXME: This paints a double-thick border between adjacent fragments, where ideally there
diff --git a/Userland/Libraries/LibWeb/Layout/InlineNode.h b/Userland/Libraries/LibWeb/Layout/InlineNode.h
index 5f6d4d45973d..e2e39600f3a9 100644
--- a/Userland/Libraries/LibWeb/Layout/InlineNode.h
+++ b/Userland/Libraries/LibWeb/Layout/InlineNode.h
@@ -16,7 +16,6 @@ class InlineNode : public NodeWithStyleAndBoxModelMetrics {
virtual ~InlineNode() override;
virtual void paint(PaintContext&, PaintPhase) override;
- virtual void paint_fragment(PaintContext&, const LineBoxFragment&, PaintPhase) const override;
virtual void split_into_lines(InlineFormattingContext&, LayoutMode) override;
};
|
44f8161166e302a44b021437751e58bf9f4916c3
|
2020-04-08 17:36:03
|
Brendan Coles
|
ircclient: Remove FIXME for RPL_TOPICWHOTIME
| false
|
Remove FIXME for RPL_TOPICWHOTIME
|
ircclient
|
diff --git a/Applications/IRCClient/IRCClient.cpp b/Applications/IRCClient/IRCClient.cpp
index a2da80d0428b..83314e3555f6 100644
--- a/Applications/IRCClient/IRCClient.cpp
+++ b/Applications/IRCClient/IRCClient.cpp
@@ -632,7 +632,6 @@ void IRCClient::handle_rpl_topic(const Message& msg)
auto& channel_name = msg.arguments[1];
auto& topic = msg.arguments[2];
ensure_channel(channel_name).handle_topic({}, topic);
- // FIXME: Handle RPL_TOPICWHOTIME so we can know who set it and when.
}
void IRCClient::handle_rpl_namreply(const Message& msg)
|
00cef330ef6e62eb6c5be284fd2bf1d490a58b04
|
2025-01-22 00:52:07
|
Shannon Booth
|
libweb: Partition Blob URL fetches by Storage Key
| false
|
Partition Blob URL fetches by Storage Key
|
libweb
|
diff --git a/Libraries/LibWeb/DOMURL/DOMURL.cpp b/Libraries/LibWeb/DOMURL/DOMURL.cpp
index cb7f5e17ce60..2981aee7f324 100644
--- a/Libraries/LibWeb/DOMURL/DOMURL.cpp
+++ b/Libraries/LibWeb/DOMURL/DOMURL.cpp
@@ -2,7 +2,7 @@
* Copyright (c) 2021, Idan Horowitz <[email protected]>
* Copyright (c) 2021, the SerenityOS developers.
* Copyright (c) 2023, networkException <[email protected]>
- * Copyright (c) 2024, Shannon Booth <[email protected]>
+ * Copyright (c) 2024-2025, Shannon Booth <[email protected]>
*
* SPDX-License-Identifier: BSD-2-Clause
*/
@@ -136,17 +136,21 @@ void DOMURL::revoke_object_url(JS::VM&, StringView url)
if (url_record.scheme() != "blob"sv)
return;
- // 3. Let origin be the origin of url record.
- auto origin = url_record.origin();
+ // 3. Let entry be urlRecord’s blob URL entry.
+ auto& entry = url_record.blob_url_entry();
- // 4. Let settings be the current settings object.
- auto& settings = HTML::current_principal_settings_object();
+ // 4. If entry is null, return.
+ if (!entry.has_value())
+ return;
+
+ // 5. Let isAuthorized be the result of checking for same-partition blob URL usage with entry and the current settings object.
+ bool is_authorized = FileAPI::check_for_same_partition_blob_url_usage(entry.value(), HTML::current_principal_settings_object());
- // 5. If origin is not same origin with settings’s origin, return.
- if (!origin.is_same_origin(settings.origin()))
+ // 6. If isAuthorized is false, then return.
+ if (!is_authorized)
return;
- // 6. Remove an entry from the Blob URL Store for url.
+ // 7. Remove an entry from the Blob URL Store for url.
FileAPI::remove_entry_from_blob_url_store(url);
}
diff --git a/Libraries/LibWeb/Fetch/Fetching/Fetching.cpp b/Libraries/LibWeb/Fetch/Fetching/Fetching.cpp
index 934626b731b9..d0347e612eb3 100644
--- a/Libraries/LibWeb/Fetch/Fetching/Fetching.cpp
+++ b/Libraries/LibWeb/Fetch/Fetching/Fetching.cpp
@@ -3,6 +3,7 @@
* Copyright (c) 2023, Luke Wilde <[email protected]>
* Copyright (c) 2023, Sam Atkins <[email protected]>
* Copyright (c) 2024, Jamie Mansfield <[email protected]>
+ * Copyright (c) 2025, Shannon Booth <[email protected]>
*
* SPDX-License-Identifier: BSD-2-Clause
*/
@@ -595,6 +596,21 @@ WebIDL::ExceptionOr<GC::Ptr<PendingResponse>> main_fetch(JS::Realm& realm, Infra
return GC::Ptr<PendingResponse> {};
}
+// https://fetch.spec.whatwg.org/#request-determine-the-environment
+static GC::Ptr<HTML::Environment> determine_the_environment(GC::Ref<Infrastructure::Request> request)
+{
+ // 1. If request’s reserved client is non-null, then return request’s reserved client.
+ if (request->reserved_client())
+ return request->reserved_client();
+
+ // 2. If request’s client is non-null, then return request’s client.
+ if (request->client())
+ return request->client();
+
+ // 3. Return null.
+ return {};
+}
+
// https://fetch.spec.whatwg.org/#fetch-finale
void fetch_response_handover(JS::Realm& realm, Infrastructure::FetchParams const& fetch_params, Infrastructure::Response& response)
{
@@ -817,30 +833,52 @@ WebIDL::ExceptionOr<GC::Ref<PendingResponse>> scheme_fetch(JS::Realm& realm, Inf
// 1. Let blobURLEntry be request’s current URL’s blob URL entry.
auto const& blob_url_entry = request->current_url().blob_url_entry();
- // 2. If request’s method is not `GET`, blobURLEntry is null, or blobURLEntry’s object is not a Blob object,
- // then return a network error. [FILEAPI]
+ // 2. If request’s method is not `GET` or blobURLEntry is null, then return a network error. [FILEAPI]
if (request->method() != "GET"sv.bytes() || !blob_url_entry.has_value()) {
// FIXME: Handle "blobURLEntry’s object is not a Blob object". It could be a MediaSource object, but we
// have not yet implemented the Media Source Extensions spec.
return PendingResponse::create(vm, request, Infrastructure::Response::network_error(vm, "Request has an invalid 'blob:' URL"sv));
}
- // 3. Let blob be blobURLEntry’s object.
- auto const blob = FileAPI::Blob::create(realm, blob_url_entry.value().object.data, blob_url_entry.value().object.type);
+ // 3. Let requestEnvironment be the result of determining the environment given request.
+ auto request_environment = determine_the_environment(request);
+
+ // 4. Let isTopLevelNavigation be true if request’s destination is "document"; otherwise, false.
+ bool is_top_level_navigation = request->destination() == Infrastructure::Request::Destination::Document;
+
+ // 5. If isTopLevelNavigation is false and requestEnvironment is null, then return a network error.
+ if (!is_top_level_navigation && !request_environment)
+ return PendingResponse::create(vm, request, Infrastructure::Response::network_error(vm, "Request is missing fetch client"sv));
+
+ // 6. Let navigationOrEnvironment be the string "navigation" if isTopLevelNavigation is true; otherwise, requestEnvironment.
+ auto navigation_or_environment = [&]() -> Variant<FileAPI::NavigationEnvironment, GC::Ref<HTML::Environment>> {
+ if (is_top_level_navigation)
+ return FileAPI::NavigationEnvironment {};
+ return GC::Ref { *request_environment };
+ }();
+
+ // 7. Let blob be the result of obtaining a blob object given blobURLEntry and navigationOrEnvironment.
+ auto blob_object = FileAPI::obtain_a_blob_object(blob_url_entry.value(), navigation_or_environment);
+
+ // 8. If blob is not a Blob object, then return a network error.
+ // FIXME: This should probably check for a MediaSource object as well, once we implement that.
+ if (!blob_object.has_value())
+ return PendingResponse::create(vm, request, Infrastructure::Response::network_error(vm, "Failed to obtain a Blob object from 'blob:' URL"sv));
+ auto const blob = FileAPI::Blob::create(realm, blob_object->data, blob_object->type);
- // 4. Let response be a new response.
+ // 9. Let response be a new response.
auto response = Infrastructure::Response::create(vm);
- // 5. Let fullLength be blob’s size.
+ // 10. Let fullLength be blob’s size.
auto full_length = blob->size();
- // 6. Let serializedFullLength be fullLength, serialized and isomorphic encoded.
+ // 11. Let serializedFullLength be fullLength, serialized and isomorphic encoded.
auto serialized_full_length = String::number(full_length);
- // 7. Let type be blob’s type.
+ // 12. Let type be blob’s type.
auto const& type = blob->type();
- // 8. If request’s header list does not contain `Range`:
+ // 13. If request’s header list does not contain `Range`:
if (!request->header_list()->contains("Range"sv.bytes())) {
// 1. Let bodyWithType be the result of safely extracting blob.
auto body_with_type = safely_extract_body(realm, blob->raw_bytes());
@@ -858,7 +896,7 @@ WebIDL::ExceptionOr<GC::Ref<PendingResponse>> scheme_fetch(JS::Realm& realm, Inf
auto content_type_header = Infrastructure::Header::from_string_pair("Content-Type"sv, type);
response->header_list()->append(move(content_type_header));
}
- // 9. Otherwise:
+ // 14. Otherwise:
else {
// 1. Set response’s range-requested flag.
response->set_range_requested(true);
@@ -933,7 +971,7 @@ WebIDL::ExceptionOr<GC::Ref<PendingResponse>> scheme_fetch(JS::Realm& realm, Inf
response->header_list()->append(move(content_range_header));
}
- // 10. Return response.
+ // 15. Return response.
return PendingResponse::create(vm, request, response);
}
// -> "data"
diff --git a/Libraries/LibWeb/FileAPI/BlobURLStore.cpp b/Libraries/LibWeb/FileAPI/BlobURLStore.cpp
index f73cc5ab50b3..d76cf21fc9a4 100644
--- a/Libraries/LibWeb/FileAPI/BlobURLStore.cpp
+++ b/Libraries/LibWeb/FileAPI/BlobURLStore.cpp
@@ -1,7 +1,7 @@
/*
* Copyright (c) 2023, Tim Flynn <[email protected]>
* Copyright (c) 2024, Andreas Kling <[email protected]>
- * Copyright (c) 2024, Shannon Booth <[email protected]>
+ * Copyright (c) 2024-2025, Shannon Booth <[email protected]>
*
* SPDX-License-Identifier: BSD-2-Clause
*/
@@ -14,6 +14,7 @@
#include <LibWeb/FileAPI/Blob.h>
#include <LibWeb/FileAPI/BlobURLStore.h>
#include <LibWeb/HTML/Scripting/Environments.h>
+#include <LibWeb/StorageAPI/StorageKey.h>
namespace Web::FileAPI {
@@ -78,6 +79,41 @@ ErrorOr<String> add_entry_to_blob_url_store(GC::Ref<Blob> object)
return url;
}
+// https://www.w3.org/TR/FileAPI/#check-for-same-partition-blob-url-usage
+bool check_for_same_partition_blob_url_usage(URL::BlobURLEntry const& blob_url_entry, GC::Ref<HTML::Environment> environment)
+{
+ // 1. Let blobStorageKey be the result of obtaining a storage key for non-storage purposes with blobUrlEntry’s environment.
+ auto blob_storage_key = StorageAPI::obtain_a_storage_key_for_non_storage_purposes(blob_url_entry.environment.origin);
+
+ // 2. Let environmentStorageKey be the result of obtaining a storage key for non-storage purposes with environment.
+ auto environment_storage_key = StorageAPI::obtain_a_storage_key_for_non_storage_purposes(environment);
+
+ // 3. If blobStorageKey is not equal to environmentStorageKey, then return false.
+ if (blob_storage_key != environment_storage_key)
+ return false;
+
+ // 4. Return true.
+ return true;
+}
+
+// https://www.w3.org/TR/FileAPI/#blob-url-obtain-object
+Optional<URL::BlobURLEntry::Object> obtain_a_blob_object(URL::BlobURLEntry const& blob_url_entry, Variant<GC::Ref<HTML::Environment>, NavigationEnvironment> environment)
+{
+ // 1. Let isAuthorized be true.
+ bool is_authorized = true;
+
+ // 2. If environment is not the string "navigation", then set isAuthorized to the result of checking for same-partition blob URL usage with blobUrlEntry and environment.
+ if (!environment.has<NavigationEnvironment>())
+ is_authorized = check_for_same_partition_blob_url_usage(blob_url_entry, environment.get<GC::Ref<HTML::Environment>>());
+
+ // 3. If isAuthorized is false, then return failure.
+ if (!is_authorized)
+ return {};
+
+ // 4. Return blobUrlEntry’s object.
+ return blob_url_entry.object;
+}
+
// https://w3c.github.io/FileAPI/#removeTheEntry
void remove_entry_from_blob_url_store(StringView url)
{
diff --git a/Libraries/LibWeb/FileAPI/BlobURLStore.h b/Libraries/LibWeb/FileAPI/BlobURLStore.h
index f082d134f057..cbcf09feffac 100644
--- a/Libraries/LibWeb/FileAPI/BlobURLStore.h
+++ b/Libraries/LibWeb/FileAPI/BlobURLStore.h
@@ -10,7 +10,7 @@
#include <AK/String.h>
#include <LibGC/Ptr.h>
#include <LibGC/Root.h>
-#include <LibURL/Forward.h>
+#include <LibURL/URL.h>
#include <LibWeb/Forward.h>
namespace Web::FileAPI {
@@ -27,6 +27,9 @@ using BlobURLStore = HashMap<String, BlobURLEntry>;
BlobURLStore& blob_url_store();
ErrorOr<String> generate_new_blob_url();
ErrorOr<String> add_entry_to_blob_url_store(GC::Ref<Blob> object);
+bool check_for_same_partition_blob_url_usage(URL::BlobURLEntry const&, GC::Ref<HTML::Environment>);
+struct NavigationEnvironment { };
+Optional<URL::BlobURLEntry::Object> obtain_a_blob_object(URL::BlobURLEntry const&, Variant<GC::Ref<HTML::Environment>, NavigationEnvironment> environment);
void remove_entry_from_blob_url_store(StringView url);
Optional<BlobURLEntry const&> resolve_a_blob_url(URL::URL const&);
diff --git a/Tests/LibWeb/Text/expected/FileAPI/Blob-partitioning.txt b/Tests/LibWeb/Text/expected/FileAPI/Blob-partitioning.txt
new file mode 100644
index 000000000000..1ffd8d1cfaa3
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/FileAPI/Blob-partitioning.txt
@@ -0,0 +1 @@
+TypeError: Failed to obtain a Blob object from 'blob:' URL
diff --git a/Tests/LibWeb/Text/input/FileAPI/Blob-partitioning.html b/Tests/LibWeb/Text/input/FileAPI/Blob-partitioning.html
new file mode 100644
index 000000000000..a00df69f46f0
--- /dev/null
+++ b/Tests/LibWeb/Text/input/FileAPI/Blob-partitioning.html
@@ -0,0 +1,42 @@
+<script src="../include.js"></script>
+<script>
+ asyncTest(async (done) => {
+ try {
+ const httpServer = httpTestServer();
+ const url = await httpServer.createEcho("GET", "/blob-partitioned-fetched", {
+ status: 200,
+ headers: {
+ "Access-Control-Allow-Origin": "*",
+ },
+ body: `
+ <script>
+ const blob = new Blob(["Hello, world!"], { type: "text/plain" });
+ const blobURL = URL.createObjectURL(blob);
+ window.parent.postMessage(blobURL, "*");
+ <\/script>
+ `
+ });
+
+ const options = {
+ method: 'GET',
+ mode: 'no-cors'
+ };
+ window.addEventListener("message", async (event) => {
+ const blobURL = event.data;
+ try {
+ const response = await fetch(blobURL, options);
+ } catch (e) {
+ println(e);
+ }
+ done();
+ });
+
+ const iframe = document.getElementById("testIframe");
+ iframe.src = url;
+
+ } catch (err) {
+ console.log("FAIL - " + err);
+ }
+ });
+</script>
+<iframe id="testIframe" src="about:blank"></iframe>
|
6bf50bc40bb93e91b269e525de3c19912bd1f38f
|
2021-12-13 18:26:10
|
Ali Mohammad Pur
|
shell: Make the Join operation respect nodes that have a next chain
| false
|
Make the Join operation respect nodes that have a next chain
|
shell
|
diff --git a/Userland/Shell/AST.cpp b/Userland/Shell/AST.cpp
index 09587b3573f6..f45c547ca38e 100644
--- a/Userland/Shell/AST.cpp
+++ b/Userland/Shell/AST.cpp
@@ -879,7 +879,7 @@ CloseFdRedirection::~CloseFdRedirection()
void CommandLiteral::dump(int level) const
{
Node::dump(level);
- print_indented("(Generated command literal)", level + 1);
+ print_indented(String::formatted("(Generated command literal: {})", m_command), level + 1);
}
RefPtr<Value> CommandLiteral::run(RefPtr<Shell>)
@@ -2036,6 +2036,13 @@ RefPtr<Value> Join::run(RefPtr<Shell> shell)
if (shell && shell->has_any_error())
return make_ref_counted<ListValue>({});
+ if (left.last().should_wait && !left.last().next_chain.is_empty()) {
+ // Join (C0s*; C1) X -> (C0s*; Join C1 X)
+ auto& lhs_node = left.last().next_chain.last().node;
+ lhs_node = make_ref_counted<Join>(m_position, lhs_node, m_right);
+ return make_ref_counted<CommandSequenceValue>(move(left));
+ }
+
auto right = m_right->to_lazy_evaluated_commands(shell);
if (shell && shell->has_any_error())
return make_ref_counted<ListValue>({});
|
1066831b397e63feafe171621714c52fca8494a6
|
2023-07-20 12:32:12
|
Sam Atkins
|
libgfx: Add a method to get a specific tag from an ICC Profile
| false
|
Add a method to get a specific tag from an ICC Profile
|
libgfx
|
diff --git a/Userland/Libraries/LibGfx/ICC/Profile.h b/Userland/Libraries/LibGfx/ICC/Profile.h
index 89200669a398..dd1053db8dfe 100644
--- a/Userland/Libraries/LibGfx/ICC/Profile.h
+++ b/Userland/Libraries/LibGfx/ICC/Profile.h
@@ -254,6 +254,11 @@ class Profile : public RefCounted<Profile> {
return {};
}
+ Optional<TagData const&> tag_data(TagSignature signature) const
+ {
+ return m_tag_table.get(signature).map([](auto it) -> TagData const& { return *it; });
+ }
+
size_t tag_count() const { return m_tag_table.size(); }
// Only versions 2 and 4 are in use.
|
708f8354771cc6a87082fbce06ff1f76ca6904cd
|
2021-05-24 17:58:57
|
Daniel Bertalan
|
libvt: Implement Bracketed Paste Mode
| false
|
Implement Bracketed Paste Mode
|
libvt
|
diff --git a/Userland/Libraries/LibVT/Terminal.cpp b/Userland/Libraries/LibVT/Terminal.cpp
index 477cc6e4dbfb..0e1bd262b837 100644
--- a/Userland/Libraries/LibVT/Terminal.cpp
+++ b/Userland/Libraries/LibVT/Terminal.cpp
@@ -105,6 +105,10 @@ void Terminal::alter_mode(bool should_set, Parameters params, Intermediates inte
m_client.set_cursor_style(None);
}
break;
+ case 2004:
+ dbgln_if(TERMINAL_DEBUG, "Setting bracketed mode enabled={}", should_set);
+ m_needs_bracketed_paste = should_set;
+ break;
default:
dbgln("Terminal::alter_mode: Unimplemented private mode {} (should_set={})", mode, should_set);
break;
diff --git a/Userland/Libraries/LibVT/Terminal.h b/Userland/Libraries/LibVT/Terminal.h
index e5a596c523de..2605299bbd35 100644
--- a/Userland/Libraries/LibVT/Terminal.h
+++ b/Userland/Libraries/LibVT/Terminal.h
@@ -157,6 +157,11 @@ class Terminal : public EscapeSequenceExecutor {
Attribute attribute_at(const Position&) const;
#endif
+ bool needs_bracketed_paste() const
+ {
+ return m_needs_bracketed_paste;
+ };
+
protected:
// ^EscapeSequenceExecutor
virtual void emit_code_point(u32) override;
@@ -336,6 +341,8 @@ class Terminal : public EscapeSequenceExecutor {
CursorStyle m_cursor_style { BlinkingBlock };
CursorStyle m_saved_cursor_style { BlinkingBlock };
+ bool m_needs_bracketed_paste { false };
+
Attribute m_current_attribute;
Attribute m_saved_attribute;
diff --git a/Userland/Libraries/LibVT/TerminalWidget.cpp b/Userland/Libraries/LibVT/TerminalWidget.cpp
index 432ff28df200..cc9351462581 100644
--- a/Userland/Libraries/LibVT/TerminalWidget.cpp
+++ b/Userland/Libraries/LibVT/TerminalWidget.cpp
@@ -748,17 +748,14 @@ void TerminalWidget::paste()
{
if (m_ptm_fd == -1)
return;
+
auto mime_type = GUI::Clipboard::the().mime_type();
if (!mime_type.starts_with("text/"))
return;
auto text = GUI::Clipboard::the().data();
if (text.is_empty())
return;
- int nwritten = write(m_ptm_fd, text.data(), text.size());
- if (nwritten < 0) {
- perror("write");
- VERIFY_NOT_REACHED();
- }
+ send_non_user_input(text);
}
void TerminalWidget::copy()
@@ -1091,20 +1088,21 @@ void TerminalWidget::drop_event(GUI::DropEvent& event)
if (event.mime_data().has_text()) {
event.accept();
auto text = event.mime_data().text();
- write(m_ptm_fd, text.characters(), text.length());
+ send_non_user_input(text.bytes());
} else if (event.mime_data().has_urls()) {
event.accept();
auto urls = event.mime_data().urls();
bool first = true;
for (auto& url : event.mime_data().urls()) {
- if (!first) {
- write(m_ptm_fd, " ", 1);
- first = false;
- }
+ if (!first)
+ send_non_user_input(" "sv.bytes());
+
if (url.protocol() == "file")
- write(m_ptm_fd, url.path().characters(), url.path().length());
+ send_non_user_input(url.path().bytes());
else
- write(m_ptm_fd, url.to_string().characters(), url.to_string().length());
+ send_non_user_input(url.to_string().bytes());
+
+ first = false;
}
}
}
@@ -1155,4 +1153,34 @@ void TerminalWidget::set_font_and_resize_to_fit(const Gfx::Font& font)
set_font(font);
resize(widget_size_for_font(font));
}
+
+// Used for sending data that was not directly typed by the user.
+// This basically wraps the code that handles sending the escape sequence in bracketed paste mode.
+void TerminalWidget::send_non_user_input(const ReadonlyBytes& bytes)
+{
+ constexpr StringView leading_control_sequence = "\e[200~";
+ constexpr StringView trailing_control_sequence = "\e[201~";
+
+ int nwritten;
+ if (m_terminal.needs_bracketed_paste()) {
+ // We do not call write() separately for the control sequences and the data,
+ // because that would present a race condition where another process could inject data
+ // to prematurely terminate the escape. Could probably be solved by file locking.
+ Vector<u8> output;
+ output.ensure_capacity(leading_control_sequence.bytes().size() + bytes.size() + trailing_control_sequence.bytes().size());
+
+ // HACK: We don't have a `Vector<T>::unchecked_append(Span<T> const&)` yet :^(
+ output.append(leading_control_sequence.bytes().data(), leading_control_sequence.bytes().size());
+ output.append(bytes.data(), bytes.size());
+ output.append(trailing_control_sequence.bytes().data(), trailing_control_sequence.bytes().size());
+ nwritten = write(m_ptm_fd, output.data(), output.size());
+ } else {
+ nwritten = write(m_ptm_fd, bytes.data(), bytes.size());
+ }
+ if (nwritten < 0) {
+ perror("write");
+ VERIFY_NOT_REACHED();
+ }
+}
+
}
diff --git a/Userland/Libraries/LibVT/TerminalWidget.h b/Userland/Libraries/LibVT/TerminalWidget.h
index 8e1e2fc79013..7d658969b462 100644
--- a/Userland/Libraries/LibVT/TerminalWidget.h
+++ b/Userland/Libraries/LibVT/TerminalWidget.h
@@ -118,6 +118,8 @@ class TerminalWidget final
void set_logical_focus(bool);
+ void send_non_user_input(const ReadonlyBytes&);
+
Gfx::IntRect glyph_rect(u16 row, u16 column);
Gfx::IntRect row_rect(u16 row);
|
f58ca99a66db8f2661b3f3addd3453ab2619dcdd
|
2024-03-20 01:29:41
|
Andreas Kling
|
libweb: Parse the ::backdrop pseudo element
| false
|
Parse the ::backdrop pseudo element
|
libweb
|
diff --git a/Userland/Libraries/LibWeb/CSS/Selector.cpp b/Userland/Libraries/LibWeb/CSS/Selector.cpp
index 2b8dc05757ad..1536e22bde69 100644
--- a/Userland/Libraries/LibWeb/CSS/Selector.cpp
+++ b/Userland/Libraries/LibWeb/CSS/Selector.cpp
@@ -394,6 +394,8 @@ StringView Selector::PseudoElement::name(Selector::PseudoElement::Type pseudo_el
return "-webkit-slider-runnable-track"sv;
case Selector::PseudoElement::Type::SliderThumb:
return "-webkit-slider-thumb"sv;
+ case Selector::PseudoElement::Type::Backdrop:
+ return "backdrop"sv;
case Selector::PseudoElement::Type::KnownPseudoElementCount:
break;
case Selector::PseudoElement::Type::UnknownWebKit:
@@ -430,6 +432,8 @@ Optional<Selector::PseudoElement> Selector::PseudoElement::from_string(FlyString
return Selector::PseudoElement { Selector::PseudoElement::Type::Placeholder };
} else if (name.equals_ignoring_ascii_case("selection"sv)) {
return Selector::PseudoElement { Selector::PseudoElement::Type::Selection };
+ } else if (name.equals_ignoring_ascii_case("backdrop"sv)) {
+ return Selector::PseudoElement { Selector::PseudoElement::Type::Backdrop };
} else if (name.equals_ignoring_ascii_case("-webkit-slider-runnable-track"sv)) {
return Selector::PseudoElement { Selector::PseudoElement::Type::SliderRunnableTrack };
} else if (name.equals_ignoring_ascii_case("-webkit-slider-thumb"sv)) {
diff --git a/Userland/Libraries/LibWeb/CSS/Selector.h b/Userland/Libraries/LibWeb/CSS/Selector.h
index 76a7dfbcb23f..1cf011562312 100644
--- a/Userland/Libraries/LibWeb/CSS/Selector.h
+++ b/Userland/Libraries/LibWeb/CSS/Selector.h
@@ -39,6 +39,7 @@ class Selector : public RefCounted<Selector> {
Selection,
SliderRunnableTrack,
SliderThumb,
+ Backdrop,
// Keep this last.
KnownPseudoElementCount,
|
ca50da63e45ab1145cdc98c55005badb7c7bc49c
|
2023-07-13 22:13:21
|
Aliaksandr Kalenik
|
libweb: Do not crash if "fill: none" is specified for svg text
| false
|
Do not crash if "fill: none" is specified for svg text
|
libweb
|
diff --git a/Tests/LibWeb/Layout/expected/svg/text-fill-none.txt b/Tests/LibWeb/Layout/expected/svg/text-fill-none.txt
new file mode 100644
index 000000000000..c467c8fd972a
--- /dev/null
+++ b/Tests/LibWeb/Layout/expected/svg/text-fill-none.txt
@@ -0,0 +1,8 @@
+Viewport <#document> at (0,0) content-size 800x600 children: not-inline
+ BlockContainer <html> at (0,0) content-size 800x600 [BFC] children: not-inline
+ BlockContainer <body> at (8,8) content-size 784x163 children: inline
+ line 0 width: 300, height: 163, bottom: 163, baseline: 13.53125
+ frag 0 from SVGSVGBox start: 0, length: 0, rect: [8,21 300x150]
+ SVGSVGBox <svg> at (8,21) content-size 300x150 [SVG] children: not-inline
+ SVGTextBox <text> at (8,21) content-size 0x0 children: not-inline
+ TextNode <#text>
diff --git a/Tests/LibWeb/Layout/input/svg/text-fill-none.html b/Tests/LibWeb/Layout/input/svg/text-fill-none.html
new file mode 100644
index 000000000000..dee2b3d7f7d0
--- /dev/null
+++ b/Tests/LibWeb/Layout/input/svg/text-fill-none.html
@@ -0,0 +1 @@
+<svg><text fill="none"></text></svg>
diff --git a/Userland/Libraries/LibWeb/Painting/SVGTextPaintable.cpp b/Userland/Libraries/LibWeb/Painting/SVGTextPaintable.cpp
index 51a3db795597..48a2a2cd36e1 100644
--- a/Userland/Libraries/LibWeb/Painting/SVGTextPaintable.cpp
+++ b/Userland/Libraries/LibWeb/Painting/SVGTextPaintable.cpp
@@ -31,6 +31,9 @@ void SVGTextPaintable::paint(PaintContext& context, PaintPhase phase) const
if (!is_visible())
return;
+ if (!layout_node().computed_values().fill().has_value())
+ return;
+
SVGGraphicsPaintable::paint(context, phase);
if (phase != PaintPhase::Foreground)
|
2119c9e801ebc49ad61d181aaa8fcca1db3aec82
|
2021-03-04 14:58:46
|
Andreas Kling
|
base: Remove two outdated aliases from /etc/shellrc
| false
|
Remove two outdated aliases from /etc/shellrc
|
base
|
diff --git a/Base/etc/shellrc b/Base/etc/shellrc
index 151fdcf07d90..7a6e639f69fb 100644
--- a/Base/etc/shellrc
+++ b/Base/etc/shellrc
@@ -1,7 +1,6 @@
#!sh
alias fm=FileManager
-alias hw=HelloWorld
alias irc=IRCClient
alias ms=Minesweeper
alias sh=Shell
@@ -25,7 +24,6 @@ alias sm=SystemMonitor
alias pv=Profiler
alias ws=WebServer
alias sl=Solitaire
-alias wv=WebView
alias ue=UserspaceEmulator
alias welcome=Serendipity
|
24510b0845e50891d70c38c7c0f7270d11913616
|
2022-10-20 18:46:23
|
Andreas Kling
|
libweb: Make window.parent and window.top return WindowProxy
| false
|
Make window.parent and window.top return WindowProxy
|
libweb
|
diff --git a/Userland/Libraries/LibWeb/HTML/Window.cpp b/Userland/Libraries/LibWeb/HTML/Window.cpp
index 181116d7b59e..088bb284c3ae 100644
--- a/Userland/Libraries/LibWeb/HTML/Window.cpp
+++ b/Userland/Libraries/LibWeb/HTML/Window.cpp
@@ -41,6 +41,7 @@
#include <LibWeb/HTML/Storage.h>
#include <LibWeb/HTML/Timer.h>
#include <LibWeb/HTML/Window.h>
+#include <LibWeb/HTML/WindowProxy.h>
#include <LibWeb/HighResolutionTime/Performance.h>
#include <LibWeb/HighResolutionTime/TimeOrigin.h>
#include <LibWeb/Layout/InitialContainingBlock.h>
@@ -554,10 +555,10 @@ JS::NonnullGCPtr<HTML::Storage> Window::session_storage()
}
// https://html.spec.whatwg.org/multipage/browsers.html#dom-parent
-Window* Window::parent()
+WindowProxy* Window::parent()
{
// 1. Let current be this Window object's browsing context.
- auto* current = associated_document().browsing_context();
+ auto* current = browsing_context();
// 2. If current is null, then return null.
if (!current)
@@ -566,16 +567,14 @@ Window* Window::parent()
// 3. If current is a child browsing context of another browsing context parent,
// then return parent's WindowProxy object.
if (current->parent()) {
- VERIFY(current->parent()->active_document());
- return ¤t->parent()->active_document()->window();
+ return current->parent()->window_proxy();
}
// 4. Assert: current is a top-level browsing context.
VERIFY(current->is_top_level());
- // FIXME: 5. Return current's WindowProxy object.
- VERIFY(current->active_document());
- return ¤t->active_document()->window();
+ // 5. Return current's WindowProxy object.
+ return current->window_proxy();
}
// https://html.spec.whatwg.org/multipage/web-messaging.html#window-post-message-steps
@@ -1098,13 +1097,13 @@ JS_DEFINE_NATIVE_FUNCTION(Window::top_getter)
{
auto* impl = TRY(impl_from(vm));
- auto* this_browsing_context = impl->associated_document().browsing_context();
- if (!this_browsing_context)
+ // 1. If this Window object's browsing context is null, then return null.
+ auto* browsing_context = impl->browsing_context();
+ if (!browsing_context)
return JS::js_null();
- VERIFY(this_browsing_context->top_level_browsing_context().active_document());
- auto& top_window = this_browsing_context->top_level_browsing_context().active_document()->window();
- return &top_window;
+ // 2. Return this Window object's browsing context's top-level browsing context's WindowProxy object.
+ return browsing_context->top_level_browsing_context().window_proxy();
}
JS_DEFINE_NATIVE_FUNCTION(Window::parent_getter)
diff --git a/Userland/Libraries/LibWeb/HTML/Window.h b/Userland/Libraries/LibWeb/HTML/Window.h
index cda069cac45d..ddc70c09c087 100644
--- a/Userland/Libraries/LibWeb/HTML/Window.h
+++ b/Userland/Libraries/LibWeb/HTML/Window.h
@@ -105,7 +105,8 @@ class Window final
JS::NonnullGCPtr<HTML::Storage> local_storage();
JS::NonnullGCPtr<HTML::Storage> session_storage();
- Window* parent();
+ // https://html.spec.whatwg.org/multipage/browsers.html#dom-parent
+ WindowProxy* parent();
WebIDL::ExceptionOr<void> post_message_impl(JS::Value, String const& target_origin);
|
cecedc57eb52642fb89320fa9b1ef5a3f2e10c7d
|
2023-09-18 01:08:12
|
nipos
|
libcore: Use BSD implementation of Process::get_name() on Haiku
| false
|
Use BSD implementation of Process::get_name() on Haiku
|
libcore
|
diff --git a/Userland/Libraries/LibCore/Process.cpp b/Userland/Libraries/LibCore/Process.cpp
index 0df8f251da22..5462c66afc5e 100644
--- a/Userland/Libraries/LibCore/Process.cpp
+++ b/Userland/Libraries/LibCore/Process.cpp
@@ -127,7 +127,7 @@ ErrorOr<String> Process::get_name()
return String::from_utf8(StringView { buffer, strlen(buffer) });
#elif defined(AK_LIBC_GLIBC) || (defined(AK_OS_LINUX) && !defined(AK_OS_ANDROID))
return String::from_utf8(StringView { program_invocation_name, strlen(program_invocation_name) });
-#elif defined(AK_OS_BSD_GENERIC)
+#elif defined(AK_OS_BSD_GENERIC) || defined(AK_OS_HAIKU)
auto const* progname = getprogname();
return String::from_utf8(StringView { progname, strlen(progname) });
#else
|
1a78edb8c90b151d6d6e63226ce63e759045eeb7
|
2024-10-06 19:15:08
|
Aliaksandr Kalenik
|
libweb: Define static position calculation separately for each FC
| false
|
Define static position calculation separately for each FC
|
libweb
|
diff --git a/Userland/Libraries/LibWeb/Layout/BlockFormattingContext.cpp b/Userland/Libraries/LibWeb/Layout/BlockFormattingContext.cpp
index 38f1638804c5..4d9fa836a7c9 100644
--- a/Userland/Libraries/LibWeb/Layout/BlockFormattingContext.cpp
+++ b/Userland/Libraries/LibWeb/Layout/BlockFormattingContext.cpp
@@ -1329,4 +1329,13 @@ CSSPixels BlockFormattingContext::greatest_child_width(Box const& box) const
return max_width;
}
+StaticPositionRect BlockFormattingContext::calculate_static_position_rect(Box const& box) const
+{
+ StaticPositionRect static_position;
+ auto const& box_state = m_state.get(box);
+ auto offset_to_static_parent = content_box_rect_in_static_position_ancestor_coordinate_space(box, *box.containing_block());
+ static_position.rect = { offset_to_static_parent.location().translated(0, box_state.vertical_offset_of_parent_block_container), { 0, 0 } };
+ return static_position;
+}
+
}
diff --git a/Userland/Libraries/LibWeb/Layout/BlockFormattingContext.h b/Userland/Libraries/LibWeb/Layout/BlockFormattingContext.h
index 6d7301d003f0..c5415155c7a1 100644
--- a/Userland/Libraries/LibWeb/Layout/BlockFormattingContext.h
+++ b/Userland/Libraries/LibWeb/Layout/BlockFormattingContext.h
@@ -25,6 +25,7 @@ class BlockFormattingContext : public FormattingContext {
virtual void run(AvailableSpace const&) override;
virtual CSSPixels automatic_content_width() const override;
virtual CSSPixels automatic_content_height() const override;
+ StaticPositionRect calculate_static_position_rect(Box const&) const;
auto const& left_side_floats() const { return m_left_floats; }
auto const& right_side_floats() const { return m_right_floats; }
diff --git a/Userland/Libraries/LibWeb/Layout/FlexFormattingContext.h b/Userland/Libraries/LibWeb/Layout/FlexFormattingContext.h
index 7ad776651d8d..ef3cd331ef4d 100644
--- a/Userland/Libraries/LibWeb/Layout/FlexFormattingContext.h
+++ b/Userland/Libraries/LibWeb/Layout/FlexFormattingContext.h
@@ -24,7 +24,7 @@ class FlexFormattingContext final : public FormattingContext {
Box const& flex_container() const { return context_box(); }
- virtual StaticPositionRect calculate_static_position_rect(Box const&) const override;
+ StaticPositionRect calculate_static_position_rect(Box const&) const;
private:
[[nodiscard]] bool should_treat_main_size_as_auto(Box const&) const;
diff --git a/Userland/Libraries/LibWeb/Layout/FormattingContext.cpp b/Userland/Libraries/LibWeb/Layout/FormattingContext.cpp
index 65eee891d263..f241c725b4a7 100644
--- a/Userland/Libraries/LibWeb/Layout/FormattingContext.cpp
+++ b/Userland/Libraries/LibWeb/Layout/FormattingContext.cpp
@@ -1174,53 +1174,6 @@ CSSPixelRect FormattingContext::content_box_rect_in_static_position_ancestor_coo
VERIFY_NOT_REACHED();
}
-// https://www.w3.org/TR/css-position-3/#staticpos-rect
-StaticPositionRect FormattingContext::calculate_static_position_rect(Box const& box) const
-{
- // NOTE: This is very ad-hoc.
- // The purpose of this function is to calculate the approximate position that `box`
- // would have had if it were position:static.
-
- CSSPixels x = 0;
- CSSPixels y = 0;
-
- VERIFY(box.parent());
- if (box.parent()->children_are_inline()) {
- // We're an abspos box with inline siblings. This is gonna get messy!
- if (auto* sibling = box.previous_sibling()) {
- // Hard case: there's a previous sibling. This means there's already inline content
- // preceding the hypothetical static position of `box` within its containing block.
- // If we had been position:static, that inline content would have been wrapped in
- // anonymous block box, so now we get to imagine what the world might have looked like
- // in that scenario..
- // Basically, we find its last associated line box fragment and place `box` under it.
- // FIXME: I'm 100% sure this can be smarter, better and faster.
- LineBoxFragment const* last_fragment = nullptr;
- auto& cb_state = m_state.get(*sibling->containing_block());
- for (auto& line_box : cb_state.line_boxes) {
- for (auto& fragment : line_box.fragments()) {
- if (&fragment.layout_node() == sibling)
- last_fragment = &fragment;
- }
- }
- if (last_fragment) {
- x = last_fragment->offset().x() + last_fragment->width();
- y = last_fragment->offset().y() + last_fragment->height();
- }
- } else {
- // Easy case: no previous sibling, we're at the top of the containing block.
- }
- } else {
- auto const& box_state = m_state.get(box);
- // We're among block siblings, Y can be calculated easily.
- y = box_state.vertical_offset_of_parent_block_container;
- }
- auto offset_to_static_parent = content_box_rect_in_static_position_ancestor_coordinate_space(box, *box.containing_block());
- StaticPositionRect static_position_rect;
- static_position_rect.rect = { offset_to_static_parent.location().translated(x, y), { 0, 0 } };
- return static_position_rect;
-}
-
void FormattingContext::layout_absolutely_positioned_element(Box const& box, AvailableSpace const& available_space)
{
if (box.is_svg_box()) {
diff --git a/Userland/Libraries/LibWeb/Layout/FormattingContext.h b/Userland/Libraries/LibWeb/Layout/FormattingContext.h
index 66dfc846cd7b..a2f8f6a819d9 100644
--- a/Userland/Libraries/LibWeb/Layout/FormattingContext.h
+++ b/Userland/Libraries/LibWeb/Layout/FormattingContext.h
@@ -107,7 +107,6 @@ class FormattingContext {
[[nodiscard]] CSSPixels calculate_stretch_fit_width(Box const&, AvailableSize const&) const;
[[nodiscard]] CSSPixels calculate_stretch_fit_height(Box const&, AvailableSize const&) const;
- virtual StaticPositionRect calculate_static_position_rect(Box const&) const;
bool can_skip_is_anonymous_text_run(Box&);
void compute_inset(NodeWithStyleAndBoxModelMetrics const&);
diff --git a/Userland/Libraries/LibWeb/Layout/GridFormattingContext.cpp b/Userland/Libraries/LibWeb/Layout/GridFormattingContext.cpp
index 2fe197d9a927..62c8fa78c0df 100644
--- a/Userland/Libraries/LibWeb/Layout/GridFormattingContext.cpp
+++ b/Userland/Libraries/LibWeb/Layout/GridFormattingContext.cpp
@@ -2508,6 +2508,18 @@ CSSPixels GridFormattingContext::calculate_minimum_contribution(GridItem const&
return calculate_min_content_contribution(item, dimension);
}
+StaticPositionRect GridFormattingContext::calculate_static_position_rect(Box const& box) const
+{
+ // Result of this function is only used when containing block is not a grid container.
+ // If the containing block is a grid container then static position is a grid area rect and
+ // layout_absolutely_positioned_element() defined for GFC knows how to handle this case.
+ StaticPositionRect static_position;
+ auto const& box_state = m_state.get(box);
+ auto offset_to_static_parent = content_box_rect_in_static_position_ancestor_coordinate_space(box, *box.containing_block());
+ static_position.rect = { offset_to_static_parent.location().translated(0, 0), { box_state.content_width(), box_state.content_height() } };
+ return static_position;
+}
+
}
namespace AK {
diff --git a/Userland/Libraries/LibWeb/Layout/GridFormattingContext.h b/Userland/Libraries/LibWeb/Layout/GridFormattingContext.h
index e2ba6b5f0675..580be87ff11c 100644
--- a/Userland/Libraries/LibWeb/Layout/GridFormattingContext.h
+++ b/Userland/Libraries/LibWeb/Layout/GridFormattingContext.h
@@ -109,6 +109,7 @@ class GridFormattingContext final : public FormattingContext {
virtual void run(AvailableSpace const& available_space) override;
virtual CSSPixels automatic_content_width() const override;
virtual CSSPixels automatic_content_height() const override;
+ StaticPositionRect calculate_static_position_rect(Box const&) const;
Box const& grid_container() const { return context_box(); }
diff --git a/Userland/Libraries/LibWeb/Layout/InlineFormattingContext.cpp b/Userland/Libraries/LibWeb/Layout/InlineFormattingContext.cpp
index b999e9b3288d..a8e758d625e0 100644
--- a/Userland/Libraries/LibWeb/Layout/InlineFormattingContext.cpp
+++ b/Userland/Libraries/LibWeb/Layout/InlineFormattingContext.cpp
@@ -463,4 +463,42 @@ void InlineFormattingContext::set_vertical_float_clearance(CSSPixels vertical_fl
{
m_vertical_float_clearance = vertical_float_clearance;
}
+
+StaticPositionRect InlineFormattingContext::calculate_static_position_rect(Box const& box) const
+{
+ CSSPixels x = 0;
+ CSSPixels y = 0;
+
+ VERIFY(box.parent());
+ VERIFY(box.parent()->children_are_inline());
+ // We're an abspos box with inline siblings. This is gonna get messy!
+ if (auto const* sibling = box.previous_sibling()) {
+ // Hard case: there's a previous sibling. This means there's already inline content
+ // preceding the hypothetical static position of `box` within its containing block.
+ // If we had been position:static, that inline content would have been wrapped in
+ // anonymous block box, so now we get to imagine what the world might have looked like
+ // in that scenario..
+ // Basically, we find its last associated line box fragment and place `box` under it.
+ // FIXME: I'm 100% sure this can be smarter, better and faster.
+ LineBoxFragment const* last_fragment = nullptr;
+ auto const& cb_state = m_state.get(*sibling->containing_block());
+ for (auto const& line_box : cb_state.line_boxes) {
+ for (auto const& fragment : line_box.fragments()) {
+ if (&fragment.layout_node() == sibling)
+ last_fragment = &fragment;
+ }
+ }
+ if (last_fragment) {
+ x = last_fragment->offset().x() + last_fragment->width();
+ y = last_fragment->offset().y() + last_fragment->height();
+ }
+ } else {
+ // Easy case: no previous sibling, we're at the top of the containing block.
+ }
+ auto offset_to_static_parent = content_box_rect_in_static_position_ancestor_coordinate_space(box, *box.containing_block());
+ StaticPositionRect static_position_rect;
+ static_position_rect.rect = { offset_to_static_parent.location().translated(x, y), { 0, 0 } };
+ return static_position_rect;
+}
+
}
diff --git a/Userland/Libraries/LibWeb/Layout/InlineFormattingContext.h b/Userland/Libraries/LibWeb/Layout/InlineFormattingContext.h
index 13d95c4568af..4cd7f4fd8824 100644
--- a/Userland/Libraries/LibWeb/Layout/InlineFormattingContext.h
+++ b/Userland/Libraries/LibWeb/Layout/InlineFormattingContext.h
@@ -26,6 +26,7 @@ class InlineFormattingContext final : public FormattingContext {
virtual void run(AvailableSpace const&) override;
virtual CSSPixels automatic_content_height() const override;
virtual CSSPixels automatic_content_width() const override;
+ StaticPositionRect calculate_static_position_rect(Box const&) const;
void dimension_box_on_line(Box const&, LayoutMode);
diff --git a/Userland/Libraries/LibWeb/Layout/TableFormattingContext.cpp b/Userland/Libraries/LibWeb/Layout/TableFormattingContext.cpp
index bc7d629d89ac..57a93c1e69f9 100644
--- a/Userland/Libraries/LibWeb/Layout/TableFormattingContext.cpp
+++ b/Userland/Libraries/LibWeb/Layout/TableFormattingContext.cpp
@@ -1849,6 +1849,15 @@ CSSPixels TableFormattingContext::border_spacing_vertical() const
return computed_values.border_spacing_vertical().to_px(table_box());
}
+StaticPositionRect TableFormattingContext::calculate_static_position_rect(Box const& box) const
+{
+ // FIXME: Implement static position calculation for table descendants instead of always returning a rectangle with zero position and size.
+ StaticPositionRect static_position;
+ auto offset_to_static_parent = content_box_rect_in_static_position_ancestor_coordinate_space(box, *box.containing_block());
+ static_position.rect = { offset_to_static_parent.location(), { 0, 0 } };
+ return static_position;
+}
+
template<>
Vector<TableFormattingContext::Row>& TableFormattingContext::table_rows_or_columns()
{
diff --git a/Userland/Libraries/LibWeb/Layout/TableFormattingContext.h b/Userland/Libraries/LibWeb/Layout/TableFormattingContext.h
index dac2b4b2730b..8145cd96cbc7 100644
--- a/Userland/Libraries/LibWeb/Layout/TableFormattingContext.h
+++ b/Userland/Libraries/LibWeb/Layout/TableFormattingContext.h
@@ -28,6 +28,7 @@ class TableFormattingContext final : public FormattingContext {
virtual void run(AvailableSpace const&) override;
virtual CSSPixels automatic_content_width() const override;
virtual CSSPixels automatic_content_height() const override;
+ StaticPositionRect calculate_static_position_rect(Box const&) const;
Box const& table_box() const { return context_box(); }
TableWrapper const& table_wrapper() const
|
6902a09e479acc5c4ab102fe1b16f4977e922e87
|
2020-09-26 03:25:33
|
AnotherTest
|
libgui: Register the 'ColorInput' and 'Frame' widgets
| false
|
Register the 'ColorInput' and 'Frame' widgets
|
libgui
|
diff --git a/Libraries/LibGUI/Widget.cpp b/Libraries/LibGUI/Widget.cpp
index ffd893f9d1b9..06365103e7d9 100644
--- a/Libraries/LibGUI/Widget.cpp
+++ b/Libraries/LibGUI/Widget.cpp
@@ -31,6 +31,7 @@
#include <LibGUI/BoxLayout.h>
#include <LibGUI/Button.h>
#include <LibGUI/CheckBox.h>
+#include <LibGUI/ColorInput.h>
#include <LibGUI/Event.h>
#include <LibGUI/GroupBox.h>
#include <LibGUI/Label.h>
@@ -58,6 +59,8 @@ namespace GUI {
REGISTER_WIDGET(GUI, Button)
REGISTER_WIDGET(GUI, CheckBox)
+REGISTER_WIDGET(GUI, ColorInput)
+REGISTER_WIDGET(GUI, Frame)
REGISTER_WIDGET(GUI, GroupBox)
REGISTER_WIDGET(GUI, HorizontalSplitter)
REGISTER_WIDGET(GUI, Label)
|
3d9b88d2a777d80084d2a8a8a678d0e75de6ccbc
|
2023-01-18 20:19:36
|
dependabot[bot]
|
ci: Bump r-lib/actions from 1 to 2
| false
|
Bump r-lib/actions from 1 to 2
|
ci
|
diff --git a/.github/workflows/manpages.yml b/.github/workflows/manpages.yml
index 3412a2d1fe18..87eb640846e0 100644
--- a/.github/workflows/manpages.yml
+++ b/.github/workflows/manpages.yml
@@ -12,7 +12,7 @@ jobs:
if: always() && github.repository == 'SerenityOS/serenity' && github.ref == 'refs/heads/master'
steps:
- uses: actions/checkout@v3
- - uses: r-lib/actions/setup-pandoc@v1
+ - uses: r-lib/actions/setup-pandoc@v2
with:
pandoc-version: '2.13'
- name: Actually build website
|
4e974e6d6020a518709364c6d0f97afcee8e77dc
|
2021-06-08 22:38:13
|
Timothy Flynn
|
libsql: Rename expression tree depth limit test case
| false
|
Rename expression tree depth limit test case
|
libsql
|
diff --git a/Tests/LibSQL/TestSqlExpressionParser.cpp b/Tests/LibSQL/TestSqlExpressionParser.cpp
index 4cf58324f2c6..15bd8d8415dd 100644
--- a/Tests/LibSQL/TestSqlExpressionParser.cpp
+++ b/Tests/LibSQL/TestSqlExpressionParser.cpp
@@ -603,7 +603,7 @@ TEST_CASE(in_selection_expression)
validate("15 NOT IN (SELECT * FROM table)", true);
}
-TEST_CASE(stack_limit)
+TEST_CASE(expression_tree_depth_limit)
{
auto too_deep_expression = String::formatted("{:+^{}}1", "", SQL::Limits::maximum_expression_tree_depth);
EXPECT(!parse(too_deep_expression.substring_view(1)).is_error());
|
684fa0f99b12e79eb95907b53498d09c95f1f1d9
|
2020-08-21 21:27:24
|
Andreas Kling
|
libweb: Make selection state recomputation implicit
| false
|
Make selection state recomputation implicit
|
libweb
|
diff --git a/Libraries/LibWeb/InProcessWebView.cpp b/Libraries/LibWeb/InProcessWebView.cpp
index 96f2fa2c4ed0..175abb5b6a01 100644
--- a/Libraries/LibWeb/InProcessWebView.cpp
+++ b/Libraries/LibWeb/InProcessWebView.cpp
@@ -109,8 +109,7 @@ void InProcessWebView::select_all()
if (is<LayoutText>(*last_layout_node))
last_layout_node_index_in_node = downcast<LayoutText>(*last_layout_node).text_for_rendering().length() - 1;
- layout_root->selection().set({ first_layout_node, 0 }, { last_layout_node, last_layout_node_index_in_node });
- layout_root->recompute_selection_states();
+ layout_root->set_selection({ { first_layout_node, 0 }, { last_layout_node, last_layout_node_index_in_node } });
update();
}
diff --git a/Libraries/LibWeb/Layout/LayoutDocument.cpp b/Libraries/LibWeb/Layout/LayoutDocument.cpp
index b891874887d2..c93792b7f957 100644
--- a/Libraries/LibWeb/Layout/LayoutDocument.cpp
+++ b/Libraries/LibWeb/Layout/LayoutDocument.cpp
@@ -146,4 +146,16 @@ void LayoutDocument::recompute_selection_states()
});
}
+void LayoutDocument::set_selection(const LayoutRange & selection)
+{
+ m_selection = selection;
+ recompute_selection_states();
+}
+
+void LayoutDocument::set_selection_end(const LayoutPosition& position)
+{
+ m_selection.set_end(position);
+ recompute_selection_states();
+}
+
}
diff --git a/Libraries/LibWeb/Layout/LayoutDocument.h b/Libraries/LibWeb/Layout/LayoutDocument.h
index 2f18e90f4405..0e5d39aebeb9 100644
--- a/Libraries/LibWeb/Layout/LayoutDocument.h
+++ b/Libraries/LibWeb/Layout/LayoutDocument.h
@@ -46,7 +46,8 @@ class LayoutDocument final : public LayoutBlock {
virtual HitTestResult hit_test(const Gfx::IntPoint&, HitTestType) const override;
const LayoutRange& selection() const { return m_selection; }
- LayoutRange& selection() { return m_selection; }
+ void set_selection(const LayoutRange&);
+ void set_selection_end(const LayoutPosition&);
void did_set_viewport_rect(Badge<Frame>, const Gfx::IntRect&);
diff --git a/Libraries/LibWeb/Page/EventHandler.cpp b/Libraries/LibWeb/Page/EventHandler.cpp
index cba26e89babc..d9623b810599 100644
--- a/Libraries/LibWeb/Page/EventHandler.cpp
+++ b/Libraries/LibWeb/Page/EventHandler.cpp
@@ -31,10 +31,10 @@
#include <LibWeb/DOM/Text.h>
#include <LibWeb/HTML/HTMLAnchorElement.h>
#include <LibWeb/HTML/HTMLIFrameElement.h>
+#include <LibWeb/InProcessWebView.h>
#include <LibWeb/Layout/LayoutDocument.h>
#include <LibWeb/Page/EventHandler.h>
#include <LibWeb/Page/Frame.h>
-#include <LibWeb/InProcessWebView.h>
#include <LibWeb/UIEvents/MouseEvent.h>
namespace Web {
@@ -156,8 +156,7 @@ bool EventHandler::handle_mousedown(const Gfx::IntPoint& position, unsigned butt
auto result = layout_root()->hit_test(position, HitTestType::TextCursor);
if (result.layout_node && result.layout_node->node()) {
m_frame.set_cursor_position(DOM::Position(*node, result.index_in_node));
- layout_root()->selection().set({ result.layout_node, result.index_in_node }, {});
- layout_root()->recompute_selection_states();
+ layout_root()->set_selection({ { result.layout_node, result.index_in_node }, {} });
dump_selection("MouseDown");
m_in_mouse_selection = true;
}
@@ -209,8 +208,7 @@ bool EventHandler::handle_mousemove(const Gfx::IntPoint& position, unsigned butt
if (m_in_mouse_selection) {
auto hit = layout_root()->hit_test(position, HitTestType::TextCursor);
if (hit.layout_node && hit.layout_node->node()) {
- layout_root()->selection().set_end({ hit.layout_node, hit.index_in_node });
- layout_root()->recompute_selection_states();
+ layout_root()->set_selection_end({ hit.layout_node, hit.index_in_node });
}
dump_selection("MouseMove");
page_client.page_did_change_selection();
|
734bd9841ad3d35c30ae34546f6f6d1215a260a4
|
2021-06-02 21:38:56
|
Marcus Nilsson
|
terminal: Close find & settings windows on application exit
| false
|
Close find & settings windows on application exit
|
terminal
|
diff --git a/Userland/Applications/Terminal/main.cpp b/Userland/Applications/Terminal/main.cpp
index 7704e02386c6..50fe3002a510 100644
--- a/Userland/Applications/Terminal/main.cpp
+++ b/Userland/Applications/Terminal/main.cpp
@@ -393,6 +393,13 @@ int main(int argc, char** argv)
window->set_menubar(menubar);
+ window->on_close = [&]() {
+ if (find_window)
+ find_window->close();
+ if (settings_window)
+ settings_window->close();
+ };
+
if (unveil("/res", "r") < 0) {
perror("unveil");
return 1;
|
8eef509c1b4a2d6761e9f0dd9b7860a7b5f3f255
|
2021-08-23 19:29:29
|
Sam Atkins
|
libweb: Add DOMTreeModel::index_for_node()
| false
|
Add DOMTreeModel::index_for_node()
|
libweb
|
diff --git a/Userland/Libraries/LibWeb/DOMTreeModel.cpp b/Userland/Libraries/LibWeb/DOMTreeModel.cpp
index df2209687a44..d3eaf157f67f 100644
--- a/Userland/Libraries/LibWeb/DOMTreeModel.cpp
+++ b/Userland/Libraries/LibWeb/DOMTreeModel.cpp
@@ -131,4 +131,20 @@ GUI::Variant DOMTreeModel::data(const GUI::ModelIndex& index, GUI::ModelRole rol
return {};
}
+GUI::ModelIndex DOMTreeModel::index_for_node(DOM::Node* node) const
+{
+ if (!node)
+ return {};
+
+ DOM::Node* parent = node->parent();
+ if (!parent)
+ return {};
+
+ auto maybe_row = parent->index_of_child(*node);
+ if (maybe_row.has_value())
+ return create_index(maybe_row.value(), 0, node);
+
+ return {};
+}
+
}
diff --git a/Userland/Libraries/LibWeb/DOMTreeModel.h b/Userland/Libraries/LibWeb/DOMTreeModel.h
index 574c2b316c9e..bfd5875ab41d 100644
--- a/Userland/Libraries/LibWeb/DOMTreeModel.h
+++ b/Userland/Libraries/LibWeb/DOMTreeModel.h
@@ -26,6 +26,8 @@ class DOMTreeModel final : public GUI::Model {
virtual GUI::ModelIndex index(int row, int column, const GUI::ModelIndex& parent = GUI::ModelIndex()) const override;
virtual GUI::ModelIndex parent_index(const GUI::ModelIndex&) const override;
+ GUI::ModelIndex index_for_node(DOM::Node*) const;
+
private:
explicit DOMTreeModel(DOM::Document&);
|
48bd094712189c5235d33c976176bd8c9a23e682
|
2024-10-27 15:56:12
|
stelar7
|
libweb: Implement RSAOAEP.encrypt()
| false
|
Implement RSAOAEP.encrypt()
|
libweb
|
diff --git a/Tests/LibWeb/Text/expected/Crypto/SubtleCrypto-encrypt.txt b/Tests/LibWeb/Text/expected/Crypto/SubtleCrypto-encrypt.txt
new file mode 100644
index 000000000000..44d016d6501a
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/Crypto/SubtleCrypto-encrypt.txt
@@ -0,0 +1 @@
+Encrypted OK with 64 bytes
diff --git a/Tests/LibWeb/Text/input/Crypto/SubtleCrypto-encrypt.html b/Tests/LibWeb/Text/input/Crypto/SubtleCrypto-encrypt.html
new file mode 100644
index 000000000000..94f3b10ad864
--- /dev/null
+++ b/Tests/LibWeb/Text/input/Crypto/SubtleCrypto-encrypt.html
@@ -0,0 +1,32 @@
+<script src="../include.js"></script>
+<script>
+ asyncTest(async done => {
+ const encoder = new TextEncoder();
+ const message = "Hello friends";
+ const encodedMessage = encoder.encode(message);
+
+ const generated = await window.crypto.subtle.generateKey(
+ {
+ name: "RSA-OAEP",
+ modulusLength: 512,
+ publicExponent: new Uint8Array([1, 0, 1]),
+ hash: "SHA-1",
+ },
+ true,
+ ["encrypt", "decrypt"]
+ );
+
+ const ciphertext = await window.crypto.subtle.encrypt(
+ {
+ name: "RSA-OAEP",
+ },
+ generated.publicKey,
+ encodedMessage
+ );
+
+ const buffer = new Uint8Array(ciphertext);
+ println(`Encrypted OK with ${buffer.byteLength} bytes`);
+
+ done();
+ });
+</script>
diff --git a/Userland/Libraries/LibCrypto/PK/RSA.h b/Userland/Libraries/LibCrypto/PK/RSA.h
index 4dafc2d62911..d24b9ddc0996 100644
--- a/Userland/Libraries/LibCrypto/PK/RSA.h
+++ b/Userland/Libraries/LibCrypto/PK/RSA.h
@@ -229,6 +229,8 @@ class RSA : public PKSystem<RSAPrivateKey<IntegerType>, RSAPublicKey<IntegerType
PrivateKeyType const& private_key() const { return m_private_key; }
PublicKeyType const& public_key() const { return m_public_key; }
+
+ void set_public_key(PublicKeyType const& key) { m_public_key = key; }
};
class RSA_PKCS1_EME : public RSA {
diff --git a/Userland/Libraries/LibWeb/Crypto/CryptoAlgorithms.cpp b/Userland/Libraries/LibWeb/Crypto/CryptoAlgorithms.cpp
index e89ccf62d4c5..9170d5595512 100644
--- a/Userland/Libraries/LibWeb/Crypto/CryptoAlgorithms.cpp
+++ b/Userland/Libraries/LibWeb/Crypto/CryptoAlgorithms.cpp
@@ -13,10 +13,12 @@
#include <LibCrypto/Curves/SECPxxxr1.h>
#include <LibCrypto/Hash/HKDF.h>
#include <LibCrypto/Hash/HashManager.h>
+#include <LibCrypto/Hash/MGF.h>
#include <LibCrypto/Hash/PBKDF2.h>
#include <LibCrypto/Hash/SHA1.h>
#include <LibCrypto/Hash/SHA2.h>
#include <LibCrypto/PK/RSA.h>
+#include <LibCrypto/Padding/OAEP.h>
#include <LibJS/Runtime/ArrayBuffer.h>
#include <LibJS/Runtime/DataView.h>
#include <LibJS/Runtime/TypedArray.h>
@@ -494,17 +496,45 @@ WebIDL::ExceptionOr<JS::NonnullGCPtr<JS::ArrayBuffer>> RSAOAEP::encrypt(Algorith
return WebIDL::InvalidAccessError::create(realm, "Key is not a public key"_string);
// 2. Let label be the contents of the label member of normalizedAlgorithm or the empty octet string if the label member of normalizedAlgorithm is not present.
- [[maybe_unused]] auto const& label = normalized_algorithm.label;
+ auto const& label = normalized_algorithm.label;
+
+ auto const& handle = key->handle();
+ auto public_key = handle.get<::Crypto::PK::RSAPublicKey<>>();
+ auto hash = TRY(verify_cast<RsaHashedKeyAlgorithm>(*key->algorithm()).hash().visit([](String const& name) -> JS::ThrowCompletionOr<String> { return name; }, [&](JS::Handle<JS::Object> const& obj) -> JS::ThrowCompletionOr<String> {
+ auto name_property = TRY(obj->get("name"));
+ return name_property.to_string(realm.vm()); }));
// 3. Perform the encryption operation defined in Section 7.1 of [RFC3447] with the key represented by key as the recipient's RSA public key,
// the contents of plaintext as the message to be encrypted, M and label as the label, L, and with the hash function specified by the hash attribute
// of the [[algorithm]] internal slot of key as the Hash option and MGF1 (defined in Section B.2.1 of [RFC3447]) as the MGF option.
+ auto error_message = MUST(String::formatted("Invalid hash function '{}'", hash));
+ ErrorOr<ByteBuffer> maybe_padding = Error::from_string_view(error_message.bytes_as_string_view());
+ if (hash.equals_ignoring_ascii_case("SHA-1"sv)) {
+ maybe_padding = ::Crypto::Padding::OAEP::eme_encode<::Crypto::Hash::SHA1, ::Crypto::Hash::MGF>(plaintext, label, public_key.length());
+ } else if (hash.equals_ignoring_ascii_case("SHA-256"sv)) {
+ maybe_padding = ::Crypto::Padding::OAEP::eme_encode<::Crypto::Hash::SHA256, ::Crypto::Hash::MGF>(plaintext, label, public_key.length());
+ } else if (hash.equals_ignoring_ascii_case("SHA-384"sv)) {
+ maybe_padding = ::Crypto::Padding::OAEP::eme_encode<::Crypto::Hash::SHA384, ::Crypto::Hash::MGF>(plaintext, label, public_key.length());
+ } else if (hash.equals_ignoring_ascii_case("SHA-512"sv)) {
+ maybe_padding = ::Crypto::Padding::OAEP::eme_encode<::Crypto::Hash::SHA512, ::Crypto::Hash::MGF>(plaintext, label, public_key.length());
+ }
+
// 4. If performing the operation results in an error, then throw an OperationError.
+ if (maybe_padding.is_error()) {
+ auto error_message = MUST(String::from_utf8(maybe_padding.error().string_literal()));
+ return WebIDL::OperationError::create(realm, error_message);
+ }
+
+ auto padding = maybe_padding.release_value();
// 5. Let ciphertext be the value C that results from performing the operation.
- // FIXME: Actually encrypt the data
- auto ciphertext = TRY_OR_THROW_OOM(vm, ByteBuffer::copy(plaintext));
+ auto ciphertext = TRY_OR_THROW_OOM(vm, ByteBuffer::create_uninitialized(public_key.length()));
+ auto ciphertext_bytes = ciphertext.bytes();
+
+ auto rsa = ::Crypto::PK::RSA {};
+ rsa.set_public_key(public_key);
+ rsa.encrypt(padding, ciphertext_bytes);
// 6. Return the result of creating an ArrayBuffer containing ciphertext.
return JS::ArrayBuffer::create(realm, move(ciphertext));
|
7362755f300bf536943b577affd4b1fcfdded2a5
|
2022-12-25 20:28:58
|
Andreas Kling
|
ladybird: Implement EventLoopPluginQt::quit()
| false
|
Implement EventLoopPluginQt::quit()
|
ladybird
|
diff --git a/Ladybird/EventLoopPluginQt.cpp b/Ladybird/EventLoopPluginQt.cpp
index 266778430b65..8a531e015bee 100644
--- a/Ladybird/EventLoopPluginQt.cpp
+++ b/Ladybird/EventLoopPluginQt.cpp
@@ -37,4 +37,9 @@ NonnullRefPtr<Web::Platform::Timer> EventLoopPluginQt::create_timer()
return TimerQt::create();
}
+void EventLoopPluginQt::quit()
+{
+ QCoreApplication::quit();
+}
+
}
diff --git a/Ladybird/EventLoopPluginQt.h b/Ladybird/EventLoopPluginQt.h
index f094ffcb6b3a..1c3751fe9894 100644
--- a/Ladybird/EventLoopPluginQt.h
+++ b/Ladybird/EventLoopPluginQt.h
@@ -18,6 +18,7 @@ class EventLoopPluginQt final : public Web::Platform::EventLoopPlugin {
virtual void spin_until(Function<bool()> goal_condition) override;
virtual void deferred_invoke(Function<void()>) override;
virtual NonnullRefPtr<Web::Platform::Timer> create_timer() override;
+ virtual void quit() override;
};
}
|
259a84b7b68dc61dc6bd98c4b562f7eb1ed74542
|
2023-04-13 19:27:30
|
Linus Groh
|
documentation: Document preference for SCREAMING_CASE constants
| false
|
Document preference for SCREAMING_CASE constants
|
documentation
|
diff --git a/Documentation/CodingStyle.md b/Documentation/CodingStyle.md
index b526658942d8..2af10bbeeea5 100644
--- a/Documentation/CodingStyle.md
+++ b/Documentation/CodingStyle.md
@@ -11,7 +11,11 @@ We'll definitely be tweaking and amending this over time, so let's consider it a
### Names
-A combination of CamelCase and snake\_case. Use CamelCase (Capitalize the first letter, including all letters in an acronym) in a class, struct, or namespace name. Use snake\_case (all lowercase, with underscores separating words) for variable and function names.
+A combination of CamelCase, snake\_case, and SCREAMING\_CASE:
+
+- Use CamelCase (Capitalize the first letter, including all letters in an acronym) in a class, struct, or namespace name
+- Use snake\_case (all lowercase, with underscores separating words) for variable and function names
+- Use SCREAMING\_CASE for constants (both global and static member variables)
###### Right:
|
3ab22c801261445d662b9fa3779197daba53f50e
|
2021-10-05 14:45:14
|
Linus Groh
|
libjs: Rename needs_argument_object to arguments_object_needed
| false
|
Rename needs_argument_object to arguments_object_needed
|
libjs
|
diff --git a/Userland/Libraries/LibJS/Runtime/ECMAScriptFunctionObject.cpp b/Userland/Libraries/LibJS/Runtime/ECMAScriptFunctionObject.cpp
index c7c609110d55..7896db8de3e7 100644
--- a/Userland/Libraries/LibJS/Runtime/ECMAScriptFunctionObject.cpp
+++ b/Userland/Libraries/LibJS/Runtime/ECMAScriptFunctionObject.cpp
@@ -159,9 +159,9 @@ ThrowCompletionOr<void> ECMAScriptFunctionObject::function_declaration_instantia
});
}
- auto needs_argument_object = this_mode() != ThisMode::Lexical;
+ auto arguments_object_needed = this_mode() != ThisMode::Lexical;
if (parameter_names.contains(vm.names.arguments.as_string()))
- needs_argument_object = false;
+ arguments_object_needed = false;
HashTable<FlyString> function_names;
Vector<FunctionDeclaration const&> functions_to_initialize;
@@ -175,12 +175,12 @@ ThrowCompletionOr<void> ECMAScriptFunctionObject::function_declaration_instantia
auto arguments_name = vm.names.arguments.as_string();
if (!has_parameter_expressions && function_names.contains(arguments_name))
- needs_argument_object = false;
+ arguments_object_needed = false;
- if (!has_parameter_expressions && needs_argument_object) {
+ if (!has_parameter_expressions && arguments_object_needed) {
scope_body->for_each_lexically_declared_name([&](auto const& name) {
if (name == arguments_name)
- needs_argument_object = false;
+ arguments_object_needed = false;
return IterationDecision::Continue;
});
}
@@ -206,7 +206,7 @@ ThrowCompletionOr<void> ECMAScriptFunctionObject::function_declaration_instantia
VERIFY(!vm.exception());
}
- if (needs_argument_object) {
+ if (arguments_object_needed) {
Object* arguments_object;
if (is_strict_mode() || !has_simple_parameter_list())
arguments_object = create_unmapped_arguments_object(global_object(), vm.running_execution_context().arguments);
|
f57c42fad7775b9256a82e3fb686dba4632e6b52
|
2023-09-09 16:33:11
|
Zaggy1024
|
libweb: Avoid conversion from floating point in CSS position resolution
| false
|
Avoid conversion from floating point in CSS position resolution
|
libweb
|
diff --git a/Userland/Libraries/LibWeb/CSS/Position.cpp b/Userland/Libraries/LibWeb/CSS/Position.cpp
index f4e19c0a3bd0..8dab7861c010 100644
--- a/Userland/Libraries/LibWeb/CSS/Position.cpp
+++ b/Userland/Libraries/LibWeb/CSS/Position.cpp
@@ -15,36 +15,32 @@ CSSPixelPoint PositionValue::resolved(Layout::Node const& node, CSSPixelRect con
// Note: A preset + a none default x/y_relative_to is impossible in the syntax (and makes little sense)
CSSPixels x = horizontal_position.visit(
[&](HorizontalPreset preset) -> CSSPixels {
- return rect.width() * [&] {
- switch (preset) {
- case HorizontalPreset::Left:
- return CSSPixels(0.0);
- case HorizontalPreset::Center:
- return CSSPixels(0.5);
- case HorizontalPreset::Right:
- return CSSPixels(1.0);
- default:
- VERIFY_NOT_REACHED();
- }
- }();
+ switch (preset) {
+ case HorizontalPreset::Left:
+ return 0;
+ case HorizontalPreset::Center:
+ return rect.width() / 2;
+ case HorizontalPreset::Right:
+ return rect.width();
+ default:
+ VERIFY_NOT_REACHED();
+ }
},
[&](LengthPercentage length_percentage) -> CSSPixels {
return length_percentage.to_px(node, rect.width());
});
CSSPixels y = vertical_position.visit(
[&](VerticalPreset preset) -> CSSPixels {
- return rect.height() * [&] {
- switch (preset) {
- case VerticalPreset::Top:
- return CSSPixels(0.0);
- case VerticalPreset::Center:
- return CSSPixels(0.5);
- case VerticalPreset::Bottom:
- return CSSPixels(1.0);
- default:
- VERIFY_NOT_REACHED();
- }
- }();
+ switch (preset) {
+ case VerticalPreset::Top:
+ return 0;
+ case VerticalPreset::Center:
+ return rect.height() / 2;
+ case VerticalPreset::Bottom:
+ return rect.height();
+ default:
+ VERIFY_NOT_REACHED();
+ }
},
[&](LengthPercentage length_percentage) -> CSSPixels {
return length_percentage.to_px(node, rect.height());
|
9ed051fe2584d4621e284e7ad6848d1d7801f257
|
2021-06-27 19:16:42
|
Gunnar Beutner
|
kernel: Implement initializing threads on x86_64
| false
|
Implement initializing threads on x86_64
|
kernel
|
diff --git a/Kernel/Arch/x86/common/Processor.cpp b/Kernel/Arch/x86/common/Processor.cpp
index b76380a6e507..a4d3af0cfb4e 100644
--- a/Kernel/Arch/x86/common/Processor.cpp
+++ b/Kernel/Arch/x86/common/Processor.cpp
@@ -40,6 +40,10 @@ Atomic<u32> Processor::s_idle_cpu_mask { 0 };
extern "C" void thread_context_first_enter(void);
extern "C" void exit_kernel_thread(void);
+// The compiler can't see the calls to this function inside assembly.
+// Declare it, to avoid dead code warnings.
+extern "C" void context_first_init(Thread* from_thread, Thread* to_thread, TrapFrame* trap) __attribute__((used));
+
UNMAP_AFTER_INIT static void sse_init()
{
write_cr0((read_cr0() & 0xfffffffbu) | 0x2);
@@ -1134,4 +1138,31 @@ UNMAP_AFTER_INIT void Processor::gdt_init()
// clang-format on
#endif
}
+
+extern "C" void context_first_init([[maybe_unused]] Thread* from_thread, [[maybe_unused]] Thread* to_thread, [[maybe_unused]] TrapFrame* trap)
+{
+ VERIFY(!are_interrupts_enabled());
+ VERIFY(is_kernel_mode());
+
+ dbgln_if(CONTEXT_SWITCH_DEBUG, "switch_context <-- from {} {} to {} {} (context_first_init)", VirtualAddress(from_thread), *from_thread, VirtualAddress(to_thread), *to_thread);
+
+ VERIFY(to_thread == Thread::current());
+
+ Scheduler::enter_current(*from_thread, true);
+
+ // Since we got here and don't have Scheduler::context_switch in the
+ // call stack (because this is the first time we switched into this
+ // context), we need to notify the scheduler so that it can release
+ // the scheduler lock. We don't want to enable interrupts at this point
+ // as we're still in the middle of a context switch. Doing so could
+ // trigger a context switch within a context switch, leading to a crash.
+ FlatPtr flags;
+#if ARCH(I386)
+ flags = trap->regs->eflags;
+#else
+ flags = trap->regs->rflags;
+#endif
+ Scheduler::leave_on_first_switch(flags & ~0x200);
+}
+
}
diff --git a/Kernel/Arch/x86/i386/CPU.cpp b/Kernel/Arch/x86/i386/CPU.cpp
index 8d25ca3d97b2..27636b9ad9ec 100644
--- a/Kernel/Arch/x86/i386/CPU.cpp
+++ b/Kernel/Arch/x86/i386/CPU.cpp
@@ -19,7 +19,6 @@ namespace Kernel {
// The compiler can't see the calls to these functions inside assembly.
// Declare them, to avoid dead code warnings.
extern "C" void enter_thread_context(Thread* from_thread, Thread* to_thread) __attribute__((used));
-extern "C" void context_first_init(Thread* from_thread, Thread* to_thread, TrapFrame* trap) __attribute__((used));
extern "C" u32 do_init_context(Thread* thread, u32 flags) __attribute__((used));
extern "C" void enter_thread_context(Thread* from_thread, Thread* to_thread)
@@ -73,26 +72,6 @@ extern "C" void enter_thread_context(Thread* from_thread, Thread* to_thread)
// TODO: ioperm?
}
-extern "C" void context_first_init([[maybe_unused]] Thread* from_thread, [[maybe_unused]] Thread* to_thread, [[maybe_unused]] TrapFrame* trap)
-{
- VERIFY(!are_interrupts_enabled());
- VERIFY(is_kernel_mode());
-
- dbgln_if(CONTEXT_SWITCH_DEBUG, "switch_context <-- from {} {} to {} {} (context_first_init)", VirtualAddress(from_thread), *from_thread, VirtualAddress(to_thread), *to_thread);
-
- VERIFY(to_thread == Thread::current());
-
- Scheduler::enter_current(*from_thread, true);
-
- // Since we got here and don't have Scheduler::context_switch in the
- // call stack (because this is the first time we switched into this
- // context), we need to notify the scheduler so that it can release
- // the scheduler lock. We don't want to enable interrupts at this point
- // as we're still in the middle of a context switch. Doing so could
- // trigger a context switch within a context switch, leading to a crash.
- Scheduler::leave_on_first_switch(trap->regs->eflags & ~0x200);
-}
-
extern "C" u32 do_init_context(Thread* thread, u32 flags)
{
VERIFY_INTERRUPTS_DISABLED();
diff --git a/Kernel/Arch/x86/x86_64/CPU.cpp b/Kernel/Arch/x86/x86_64/CPU.cpp
index 8d9c0954d3b1..4c02848a5226 100644
--- a/Kernel/Arch/x86/x86_64/CPU.cpp
+++ b/Kernel/Arch/x86/x86_64/CPU.cpp
@@ -19,7 +19,6 @@ namespace Kernel {
// The compiler can't see the calls to these functions inside assembly.
// Declare them, to avoid dead code warnings.
extern "C" void enter_thread_context(Thread* from_thread, Thread* to_thread) __attribute__((used));
-extern "C" void context_first_init(Thread* from_thread, Thread* to_thread, TrapFrame* trap) __attribute__((used));
extern "C" u32 do_init_context(Thread* thread, u32 flags) __attribute__((used));
extern "C" void enter_thread_context(Thread* from_thread, Thread* to_thread)
@@ -29,11 +28,6 @@ extern "C" void enter_thread_context(Thread* from_thread, Thread* to_thread)
TODO();
}
-extern "C" void context_first_init([[maybe_unused]] Thread* from_thread, [[maybe_unused]] Thread* to_thread, [[maybe_unused]] TrapFrame* trap)
-{
- TODO();
-}
-
extern "C" u32 do_init_context(Thread* thread, u32 flags)
{
(void)thread;
diff --git a/Kernel/Arch/x86/x86_64/Processor.cpp b/Kernel/Arch/x86/x86_64/Processor.cpp
index 6ed1bb4044df..f45c95cb4e1d 100644
--- a/Kernel/Arch/x86/x86_64/Processor.cpp
+++ b/Kernel/Arch/x86/x86_64/Processor.cpp
@@ -15,7 +15,6 @@
namespace Kernel {
-#define ENTER_THREAD_CONTEXT_ARGS_SIZE (2 * 4) // to_thread, from_thread
extern "C" void thread_context_first_enter(void);
extern "C" void do_assume_context(Thread* thread, u32 flags);
extern "C" void exit_kernel_thread(void);
@@ -28,11 +27,11 @@ asm(
// switch_context will have pushed from_thread and to_thread to our new
// stack prior to thread_context_first_enter() being called, and the
// pointer to TrapFrame was the top of the stack before that
-" movl 8(%esp), %ebx \n" // save pointer to TrapFrame
+" popq %rdi \n" // from_thread (argument 0)
+" popq %rsi \n" // to_thread (argument 1)
+" popq %rdx \n" // pointer to TrapFrame (argument 2)
" cld \n"
" call context_first_init \n"
-" addl $" __STRINGIFY(ENTER_THREAD_CONTEXT_ARGS_SIZE) ", %esp \n"
-" movl %ebx, 0(%esp) \n" // push pointer to TrapFrame
" jmp common_trap_exit \n"
);
// clang-format on
@@ -79,12 +78,12 @@ u32 Processor::init_context(Thread& thread, bool leave_crit)
VERIFY(in_critical() == 1);
}
- u32 kernel_stack_top = thread.kernel_stack_top();
+ u64 kernel_stack_top = thread.kernel_stack_top();
// Add a random offset between 0-256 (16-byte aligned)
kernel_stack_top -= round_up_to_power_of_two(get_fast_random<u8>(), 16);
- u32 stack_top = kernel_stack_top;
+ u64 stack_top = kernel_stack_top;
// TODO: handle NT?
VERIFY((cpu_flags() & 0x24000) == 0); // Assume !(NT | VM)
@@ -102,13 +101,13 @@ u32 Processor::init_context(Thread& thread, bool leave_crit)
// which should be in regs.rsp and exit_kernel_thread as return
// address.
stack_top -= 2 * sizeof(u64);
- *reinterpret_cast<u64*>(kernel_stack_top - 2 * sizeof(u32)) = regs.rsp;
- *reinterpret_cast<u32*>(kernel_stack_top - 3 * sizeof(u32)) = FlatPtr(&exit_kernel_thread);
+ *reinterpret_cast<u64*>(kernel_stack_top - 2 * sizeof(u64)) = regs.rsp;
+ *reinterpret_cast<u64*>(kernel_stack_top - 3 * sizeof(u64)) = FlatPtr(&exit_kernel_thread);
} else {
stack_top -= sizeof(RegisterState);
}
- // we want to end up 16-byte aligned, %esp + 4 should be aligned
+ // we want to end up 16-byte aligned, %rsp + 8 should be aligned
stack_top -= sizeof(u64);
*reinterpret_cast<u64*>(kernel_stack_top - sizeof(u64)) = 0;
@@ -116,7 +115,19 @@ u32 Processor::init_context(Thread& thread, bool leave_crit)
// we will end up either in kernel mode or user mode, depending on how the thread is set up
// However, the first step is to always start in kernel mode with thread_context_first_enter
RegisterState& iretframe = *reinterpret_cast<RegisterState*>(stack_top);
- // FIXME: copy state to be recovered through TSS
+ iretframe.rdi = regs.rdi;
+ iretframe.rsi = regs.rsi;
+ iretframe.rbp = regs.rbp;
+ iretframe.rsp = 0;
+ iretframe.rbx = regs.rbx;
+ iretframe.rdx = regs.rdx;
+ iretframe.rcx = regs.rcx;
+ iretframe.rax = regs.rax;
+ iretframe.rflags = regs.rflags;
+ iretframe.rip = regs.rip;
+ iretframe.cs = regs.cs;
+ if (return_to_user)
+ iretframe.userspace_rsp = regs.rsp;
// make space for a trap frame
stack_top -= sizeof(TrapFrame);
@@ -205,21 +216,15 @@ UNMAP_AFTER_INIT void Processor::initialize_context_switching(Thread& initial_th
"movq %[new_rsp], %%rsp \n" // switch to new stack
"pushq %[from_to_thread] \n" // to_thread
"pushq %[from_to_thread] \n" // from_thread
- "pushq $" __STRINGIFY(GDT_SELECTOR_CODE0) " \n"
"pushq %[new_rip] \n" // save the entry rip to the stack
- "movq %%rsp, %%rbx \n"
- "addq $40, %%rbx \n" // calculate pointer to TrapFrame
- "pushq %%rbx \n"
"cld \n"
"pushq %[cpu] \n" // push argument for init_finished before register is clobbered
"call pre_init_finished \n"
"pop %%rdi \n" // move argument for init_finished into place
"call init_finished \n"
- "addq $8, %%rsp \n"
"call post_init_finished \n"
- "pop %%rdi \n" // move pointer to TrapFrame into place
+ "movq 24(%%rsp), %%rdi \n" // move pointer to TrapFrame into place
"call enter_trap_no_irq \n"
- "addq $8, %%rsp \n"
"retq \n"
:: [new_rsp] "g" (regs.rsp),
[new_rip] "a" (regs.rip),
diff --git a/Kernel/Thread.cpp b/Kernel/Thread.cpp
index 8a2e14fc6e16..7e5cb0fe5071 100644
--- a/Kernel/Thread.cpp
+++ b/Kernel/Thread.cpp
@@ -105,7 +105,13 @@ Thread::Thread(NonnullRefPtr<Process> process, NonnullOwnPtr<Region> kernel_stac
m_regs.gs = GDT_SELECTOR_TLS | 3;
}
#else
+ // Only IF is set when a process boots.
m_regs.rflags = 0x0202;
+
+ if (m_process->is_kernel_process())
+ m_regs.cs = GDT_SELECTOR_CODE0;
+ else
+ m_regs.cs = GDT_SELECTOR_CODE3 | 3;
#endif
m_regs.cr3 = m_process->space().page_directory().cr3();
|
ed3f9347f3927a3005824173ab4c9f0d35739100
|
2023-05-13 16:23:49
|
thankyouverycool
|
fonteditor: Tighten lambda captures
| false
|
Tighten lambda captures
|
fonteditor
|
diff --git a/Userland/Applications/FontEditor/MainWidget.cpp b/Userland/Applications/FontEditor/MainWidget.cpp
index be0cd55c8cd8..34f81952cad1 100644
--- a/Userland/Applications/FontEditor/MainWidget.cpp
+++ b/Userland/Applications/FontEditor/MainWidget.cpp
@@ -86,7 +86,7 @@ ErrorOr<RefPtr<GUI::Window>> MainWidget::create_preview_window()
m_preview_label->set_font(edited_font());
m_preview_textbox = find_descendant_of_type_named<GUI::TextBox>("preview_textbox");
- m_preview_textbox->on_change = [&] {
+ m_preview_textbox->on_change = [this] {
auto maybe_preview = [](StringView text) -> ErrorOr<String> {
return TRY(String::formatted("{}\n{}", text, TRY(Unicode::to_unicode_uppercase_full(text))));
}(m_preview_textbox->text());
@@ -97,7 +97,7 @@ ErrorOr<RefPtr<GUI::Window>> MainWidget::create_preview_window()
m_preview_textbox->set_text(pangrams[0]);
auto& reload_button = *find_descendant_of_type_named<GUI::Button>("reload_button");
- reload_button.on_click = [&](auto) {
+ reload_button.on_click = [this](auto) {
static size_t i = 1;
if (i >= pangrams.size())
i = 0;
@@ -110,7 +110,7 @@ ErrorOr<RefPtr<GUI::Window>> MainWidget::create_preview_window()
ErrorOr<void> MainWidget::create_actions()
{
- m_new_action = GUI::Action::create("&New Font...", { Mod_Ctrl, Key_N }, TRY(Gfx::Bitmap::load_from_file("/res/icons/16x16/filetype-font.png"sv)), [&](auto&) {
+ m_new_action = GUI::Action::create("&New Font...", { Mod_Ctrl, Key_N }, TRY(Gfx::Bitmap::load_from_file("/res/icons/16x16/filetype-font.png"sv)), [this](auto&) {
if (!request_close())
return;
auto new_font_wizard = NewFontDialog::construct(window());
@@ -125,7 +125,7 @@ ErrorOr<void> MainWidget::create_actions()
});
m_new_action->set_status_tip("Create a new font");
- m_open_action = GUI::CommonActions::make_open_action([&](auto&) {
+ m_open_action = GUI::CommonActions::make_open_action([this](auto&) {
if (!request_close())
return;
@@ -138,7 +138,7 @@ ErrorOr<void> MainWidget::create_actions()
show_error(result.release_error(), "Opening"sv, LexicalPath { file.filename().to_deprecated_string() }.basename());
});
- m_save_action = GUI::CommonActions::make_save_action([&](auto&) {
+ m_save_action = GUI::CommonActions::make_save_action([this](auto&) {
if (m_path.is_empty())
return m_save_as_action->activate();
@@ -150,7 +150,7 @@ ErrorOr<void> MainWidget::create_actions()
show_error(result.release_error(), "Saving"sv, LexicalPath { m_path.to_deprecated_string() }.basename());
});
- m_save_as_action = GUI::CommonActions::make_save_as_action([&](auto&) {
+ m_save_as_action = GUI::CommonActions::make_save_as_action([this](auto&) {
LexicalPath lexical_path(m_path.is_empty() ? "Untitled.font"sv : m_path);
auto response = FileSystemAccessClient::Client::the().save_file(window(), lexical_path.title(), lexical_path.extension());
@@ -161,22 +161,22 @@ ErrorOr<void> MainWidget::create_actions()
show_error(result.release_error(), "Saving"sv, lexical_path.basename());
});
- m_cut_action = GUI::CommonActions::make_cut_action([&](auto&) {
+ m_cut_action = GUI::CommonActions::make_cut_action([this](auto&) {
if (auto result = cut_selected_glyphs(); result.is_error())
show_error(result.release_error(), "Cutting selection failed"sv);
});
- m_copy_action = GUI::CommonActions::make_copy_action([&](auto&) {
+ m_copy_action = GUI::CommonActions::make_copy_action([this](auto&) {
if (auto result = copy_selected_glyphs(); result.is_error())
show_error(result.release_error(), "Copying selection failed"sv);
});
- m_paste_action = GUI::CommonActions::make_paste_action([&](auto&) {
+ m_paste_action = GUI::CommonActions::make_paste_action([this](auto&) {
paste_glyphs();
});
m_paste_action->set_enabled(GUI::Clipboard::the().fetch_mime_type() == "glyph/x-fonteditor");
- GUI::Clipboard::the().on_change = [&](DeprecatedString const& data_type) {
+ GUI::Clipboard::the().on_change = [this](DeprecatedString const& data_type) {
m_paste_action->set_enabled(data_type == "glyph/x-fonteditor");
};
@@ -184,12 +184,12 @@ ErrorOr<void> MainWidget::create_actions()
delete_selected_glyphs();
});
- m_undo_action = GUI::CommonActions::make_undo_action([&](auto&) {
+ m_undo_action = GUI::CommonActions::make_undo_action([this](auto&) {
undo();
});
m_undo_action->set_enabled(false);
- m_redo_action = GUI::CommonActions::make_redo_action([&](auto&) {
+ m_redo_action = GUI::CommonActions::make_redo_action([this](auto&) {
redo();
});
m_redo_action->set_enabled(false);
@@ -203,7 +203,7 @@ ErrorOr<void> MainWidget::create_actions()
update_statusbar();
});
- m_open_preview_action = GUI::Action::create("&Preview Font", { Mod_Ctrl, Key_P }, TRY(Gfx::Bitmap::load_from_file("/res/icons/16x16/find.png"sv)), [&](auto&) {
+ m_open_preview_action = GUI::Action::create("&Preview Font", { Mod_Ctrl, Key_P }, TRY(Gfx::Bitmap::load_from_file("/res/icons/16x16/find.png"sv)), [this](auto&) {
if (!m_font_preview_window) {
if (auto maybe_window = create_preview_window(); maybe_window.is_error())
show_error(maybe_window.release_error(), "Creating preview window failed"sv);
@@ -217,7 +217,7 @@ ErrorOr<void> MainWidget::create_actions()
bool show_metadata = Config::read_bool("FontEditor"sv, "Layout"sv, "ShowMetadata"sv, true);
set_show_font_metadata(show_metadata);
- m_show_metadata_action = GUI::Action::create_checkable("Font &Metadata", { Mod_Ctrl, Key_M }, [&](auto& action) {
+ m_show_metadata_action = GUI::Action::create_checkable("Font &Metadata", { Mod_Ctrl, Key_M }, [this](auto& action) {
set_show_font_metadata(action.is_checked());
Config::write_bool("FontEditor"sv, "Layout"sv, "ShowMetadata"sv, action.is_checked());
});
@@ -226,7 +226,7 @@ ErrorOr<void> MainWidget::create_actions()
bool show_unicode_blocks = Config::read_bool("FontEditor"sv, "Layout"sv, "ShowUnicodeBlocks"sv, true);
set_show_unicode_blocks(show_unicode_blocks);
- m_show_unicode_blocks_action = GUI::Action::create_checkable("&Unicode Blocks", { Mod_Ctrl, Key_U }, [&](auto& action) {
+ m_show_unicode_blocks_action = GUI::Action::create_checkable("&Unicode Blocks", { Mod_Ctrl, Key_U }, [this](auto& action) {
set_show_unicode_blocks(action.is_checked());
Config::write_bool("FontEditor"sv, "Layout"sv, "ShowUnicodeBlocks"sv, action.is_checked());
});
@@ -235,7 +235,7 @@ ErrorOr<void> MainWidget::create_actions()
bool show_toolbar = Config::read_bool("FontEditor"sv, "Layout"sv, "ShowToolbar"sv, true);
set_show_toolbar(show_toolbar);
- m_show_toolbar_action = GUI::Action::create_checkable("&Toolbar", [&](auto& action) {
+ m_show_toolbar_action = GUI::Action::create_checkable("&Toolbar", [this](auto& action) {
set_show_toolbar(action.is_checked());
Config::write_bool("FontEditor"sv, "Layout"sv, "ShowToolbar"sv, action.is_checked());
});
@@ -244,7 +244,7 @@ ErrorOr<void> MainWidget::create_actions()
bool show_statusbar = Config::read_bool("FontEditor"sv, "Layout"sv, "ShowStatusbar"sv, true);
set_show_statusbar(show_statusbar);
- m_show_statusbar_action = GUI::Action::create_checkable("&Status Bar", [&](auto& action) {
+ m_show_statusbar_action = GUI::Action::create_checkable("&Status Bar", [this](auto& action) {
set_show_statusbar(action.is_checked());
Config::write_bool("FontEditor"sv, "Layout"sv, "ShowStatusbar"sv, action.is_checked());
});
@@ -253,7 +253,7 @@ ErrorOr<void> MainWidget::create_actions()
bool highlight_modifications = Config::read_bool("FontEditor"sv, "GlyphMap"sv, "HighlightModifications"sv, true);
set_highlight_modifications(highlight_modifications);
- m_highlight_modifications_action = GUI::Action::create_checkable("&Highlight Modifications", { Mod_Ctrl, Key_H }, [&](auto& action) {
+ m_highlight_modifications_action = GUI::Action::create_checkable("&Highlight Modifications", { Mod_Ctrl, Key_H }, [this](auto& action) {
set_highlight_modifications(action.is_checked());
Config::write_bool("FontEditor"sv, "GlyphMap"sv, "HighlightModifications"sv, action.is_checked());
});
@@ -262,14 +262,14 @@ ErrorOr<void> MainWidget::create_actions()
bool show_system_emoji = Config::read_bool("FontEditor"sv, "GlyphMap"sv, "ShowSystemEmoji"sv, true);
set_show_system_emoji(show_system_emoji);
- m_show_system_emoji_action = GUI::Action::create_checkable("System &Emoji", { Mod_Ctrl, Key_E }, [&](auto& action) {
+ m_show_system_emoji_action = GUI::Action::create_checkable("System &Emoji", { Mod_Ctrl, Key_E }, [this](auto& action) {
set_show_system_emoji(action.is_checked());
Config::write_bool("FontEditor"sv, "GlyphMap"sv, "ShowSystemEmoji"sv, action.is_checked());
});
m_show_system_emoji_action->set_checked(show_system_emoji);
m_show_system_emoji_action->set_status_tip("Show or hide system emoji");
- m_go_to_glyph_action = GUI::Action::create("&Go to Glyph...", { Mod_Ctrl, Key_G }, TRY(Gfx::Bitmap::load_from_file("/res/icons/16x16/go-to.png"sv)), [&](auto&) {
+ m_go_to_glyph_action = GUI::Action::create("&Go to Glyph...", { Mod_Ctrl, Key_G }, TRY(Gfx::Bitmap::load_from_file("/res/icons/16x16/go-to.png"sv)), [this](auto&) {
String input;
if (GUI::InputBox::show(window(), input, {}, "Go to glyph"sv, GUI::InputType::NonemptyText, "Hexadecimal"sv) == GUI::InputBox::ExecResult::OK) {
auto maybe_code_point = AK::StringUtils::convert_to_uint_from_hex(input);
@@ -284,12 +284,12 @@ ErrorOr<void> MainWidget::create_actions()
});
m_go_to_glyph_action->set_status_tip("Go to the specified code point");
- m_previous_glyph_action = GUI::Action::create("Pre&vious Glyph", { Mod_Alt, Key_Left }, TRY(Gfx::Bitmap::load_from_file("/res/icons/16x16/go-back.png"sv)), [&](auto&) {
+ m_previous_glyph_action = GUI::Action::create("Pre&vious Glyph", { Mod_Alt, Key_Left }, TRY(Gfx::Bitmap::load_from_file("/res/icons/16x16/go-back.png"sv)), [this](auto&) {
m_glyph_map_widget->select_previous_existing_glyph();
});
m_previous_glyph_action->set_status_tip("Seek the previous visible glyph");
- m_next_glyph_action = GUI::Action::create("&Next Glyph", { Mod_Alt, Key_Right }, TRY(Gfx::Bitmap::load_from_file("/res/icons/16x16/go-forward.png"sv)), [&](auto&) {
+ m_next_glyph_action = GUI::Action::create("&Next Glyph", { Mod_Alt, Key_Right }, TRY(Gfx::Bitmap::load_from_file("/res/icons/16x16/go-forward.png"sv)), [this](auto&) {
m_glyph_map_widget->select_next_existing_glyph();
});
m_next_glyph_action->set_status_tip("Seek the next visible glyph");
@@ -317,12 +317,12 @@ ErrorOr<void> MainWidget::create_actions()
m_glyph_editor_scale_actions.add_action(*m_scale_fifteen_action);
m_glyph_editor_scale_actions.set_exclusive(true);
- m_paint_glyph_action = GUI::Action::create_checkable("Paint Glyph", { Mod_Ctrl, KeyCode::Key_J }, TRY(Gfx::Bitmap::load_from_file("/res/icons/pixelpaint/pen.png"sv)), [&](auto&) {
+ m_paint_glyph_action = GUI::Action::create_checkable("Paint Glyph", { Mod_Ctrl, KeyCode::Key_J }, TRY(Gfx::Bitmap::load_from_file("/res/icons/pixelpaint/pen.png"sv)), [this](auto&) {
m_glyph_editor_widget->set_mode(GlyphEditorWidget::Paint);
});
m_paint_glyph_action->set_checked(true);
- m_move_glyph_action = GUI::Action::create_checkable("Move Glyph", { Mod_Ctrl, KeyCode::Key_K }, TRY(Gfx::Bitmap::load_from_file("/res/icons/16x16/selection-move.png"sv)), [&](auto&) {
+ m_move_glyph_action = GUI::Action::create_checkable("Move Glyph", { Mod_Ctrl, KeyCode::Key_K }, TRY(Gfx::Bitmap::load_from_file("/res/icons/16x16/selection-move.png"sv)), [this](auto&) {
m_glyph_editor_widget->set_mode(GlyphEditorWidget::Move);
});
@@ -330,23 +330,23 @@ ErrorOr<void> MainWidget::create_actions()
m_glyph_tool_actions.add_action(*m_move_glyph_action);
m_glyph_tool_actions.set_exclusive(true);
- m_rotate_counterclockwise_action = GUI::CommonActions::make_rotate_counterclockwise_action([&](auto&) {
+ m_rotate_counterclockwise_action = GUI::CommonActions::make_rotate_counterclockwise_action([this](auto&) {
m_glyph_editor_widget->rotate_90(Gfx::RotationDirection::CounterClockwise);
});
- m_rotate_clockwise_action = GUI::CommonActions::make_rotate_clockwise_action([&](auto&) {
+ m_rotate_clockwise_action = GUI::CommonActions::make_rotate_clockwise_action([this](auto&) {
m_glyph_editor_widget->rotate_90(Gfx::RotationDirection::Clockwise);
});
- m_flip_horizontal_action = GUI::Action::create("Flip Horizontally", { Mod_Ctrl | Mod_Shift, Key_Q }, TRY(Gfx::Bitmap::load_from_file("/res/icons/16x16/edit-flip-horizontal.png"sv)), [&](auto&) {
+ m_flip_horizontal_action = GUI::Action::create("Flip Horizontally", { Mod_Ctrl | Mod_Shift, Key_Q }, TRY(Gfx::Bitmap::load_from_file("/res/icons/16x16/edit-flip-horizontal.png"sv)), [this](auto&) {
m_glyph_editor_widget->flip(Gfx::Orientation::Horizontal);
});
- m_flip_vertical_action = GUI::Action::create("Flip Vertically", { Mod_Ctrl | Mod_Shift, Key_W }, TRY(Gfx::Bitmap::load_from_file("/res/icons/16x16/edit-flip-vertical.png"sv)), [&](auto&) {
+ m_flip_vertical_action = GUI::Action::create("Flip Vertically", { Mod_Ctrl | Mod_Shift, Key_W }, TRY(Gfx::Bitmap::load_from_file("/res/icons/16x16/edit-flip-vertical.png"sv)), [this](auto&) {
m_glyph_editor_widget->flip(Gfx::Orientation::Vertical);
});
- m_copy_text_action = GUI::Action::create("Copy as Te&xt", { Mod_Ctrl, Key_T }, TRY(Gfx::Bitmap::load_from_file("/res/icons/16x16/edit-copy.png"sv)), [&](auto&) {
+ m_copy_text_action = GUI::Action::create("Copy as Te&xt", { Mod_Ctrl, Key_T }, TRY(Gfx::Bitmap::load_from_file("/res/icons/16x16/edit-copy.png"sv)), [this](auto&) {
StringBuilder builder;
auto selection = m_glyph_map_widget->selection().normalized();
for (auto code_point = selection.start(); code_point < selection.start() + selection.size(); ++code_point) {
@@ -496,13 +496,13 @@ ErrorOr<void> MainWidget::create_widgets()
};
m_name_textbox = find_descendant_of_type_named<GUI::TextBox>("name_textbox");
- m_name_textbox->on_change = [&] {
+ m_name_textbox->on_change = [this] {
m_edited_font->set_name(m_name_textbox->text());
did_modify_font();
};
m_family_textbox = find_descendant_of_type_named<GUI::TextBox>("family_textbox");
- m_family_textbox->on_change = [&] {
+ m_family_textbox->on_change = [this] {
m_edited_font->set_family(m_family_textbox->text());
did_modify_font();
};
@@ -605,7 +605,7 @@ ErrorOr<void> MainWidget::create_widgets()
m_statusbar = find_descendant_of_type_named<GUI::Statusbar>("statusbar");
m_statusbar->segment(1).set_mode(GUI::Statusbar::Segment::Mode::Auto);
m_statusbar->segment(1).set_clickable(true);
- m_statusbar->segment(1).on_click = [&](auto) {
+ m_statusbar->segment(1).on_click = [this](auto) {
m_show_unicode_blocks_action->activate();
};
|
2093128b24c1ef17404e4e625b6f380b25aa84b5
|
2021-10-22 03:01:31
|
Linus Groh
|
libjs: Convert Temporal.PlainDate functions to ThrowCompletionOr
| false
|
Convert Temporal.PlainDate functions to ThrowCompletionOr
|
libjs
|
diff --git a/Userland/Libraries/LibJS/Runtime/Temporal/PlainDateConstructor.cpp b/Userland/Libraries/LibJS/Runtime/Temporal/PlainDateConstructor.cpp
index c7aeed99bc54..51a7471c6cb4 100644
--- a/Userland/Libraries/LibJS/Runtime/Temporal/PlainDateConstructor.cpp
+++ b/Userland/Libraries/LibJS/Runtime/Temporal/PlainDateConstructor.cpp
@@ -30,8 +30,8 @@ void PlainDateConstructor::initialize(GlobalObject& global_object)
define_direct_property(vm.names.prototype, global_object.temporal_plain_date_prototype(), 0);
u8 attr = Attribute::Writable | Attribute::Configurable;
- define_old_native_function(vm.names.from, from, 1, attr);
- define_old_native_function(vm.names.compare, compare, 2, attr);
+ define_native_function(vm.names.from, from, 1, attr);
+ define_native_function(vm.names.compare, compare, 2, attr);
define_direct_property(vm.names.length, Value(3), Attribute::Configurable);
}
@@ -74,34 +74,34 @@ ThrowCompletionOr<Object*> PlainDateConstructor::construct(FunctionObject& new_t
}
// 3.2.2 Temporal.PlainDate.from ( item [ , options ] ), https://tc39.es/proposal-temporal/#sec-temporal.plaindate.from
-JS_DEFINE_OLD_NATIVE_FUNCTION(PlainDateConstructor::from)
+JS_DEFINE_NATIVE_FUNCTION(PlainDateConstructor::from)
{
// 1. Set options to ? GetOptionsObject(options).
- auto* options = TRY_OR_DISCARD(get_options_object(global_object, vm.argument(1)));
+ auto* options = TRY(get_options_object(global_object, vm.argument(1)));
auto item = vm.argument(0);
// 2. If Type(item) is Object and item has an [[InitializedTemporalDate]] internal slot, then
if (item.is_object() && is<PlainDate>(item.as_object())) {
auto& plain_date_item = static_cast<PlainDate&>(item.as_object());
// a. Perform ? ToTemporalOverflow(options).
- (void)TRY_OR_DISCARD(to_temporal_overflow(global_object, *options));
+ (void)TRY(to_temporal_overflow(global_object, *options));
// b. Return ? CreateTemporalDate(item.[[ISOYear]], item.[[ISOMonth]], item.[[ISODay]], item.[[Calendar]]).
- return TRY_OR_DISCARD(create_temporal_date(global_object, plain_date_item.iso_year(), plain_date_item.iso_month(), plain_date_item.iso_day(), plain_date_item.calendar()));
+ return TRY(create_temporal_date(global_object, plain_date_item.iso_year(), plain_date_item.iso_month(), plain_date_item.iso_day(), plain_date_item.calendar()));
}
// 3. Return ? ToTemporalDate(item, options).
- return TRY_OR_DISCARD(to_temporal_date(global_object, item, options));
+ return TRY(to_temporal_date(global_object, item, options));
}
// 3.2.3 Temporal.PlainDate.compare ( one, two ), https://tc39.es/proposal-temporal/#sec-properties-of-the-temporal-plaindate-constructor
-JS_DEFINE_OLD_NATIVE_FUNCTION(PlainDateConstructor::compare)
+JS_DEFINE_NATIVE_FUNCTION(PlainDateConstructor::compare)
{
// 1. Set one to ? ToTemporalDate(one).
- auto* one = TRY_OR_DISCARD(to_temporal_date(global_object, vm.argument(0)));
+ auto* one = TRY(to_temporal_date(global_object, vm.argument(0)));
// 2. Set two to ? ToTemporalDate(two).
- auto* two = TRY_OR_DISCARD(to_temporal_date(global_object, vm.argument(1)));
+ auto* two = TRY(to_temporal_date(global_object, vm.argument(1)));
// 3. Return 𝔽(! CompareISODate(one.[[ISOYear]], one.[[ISOMonth]], one.[[ISODay]], two.[[ISOYear]], two.[[ISOMonth]], two.[[ISODay]])).
return Value(compare_iso_date(one->iso_year(), one->iso_month(), one->iso_day(), two->iso_year(), two->iso_month(), two->iso_day()));
diff --git a/Userland/Libraries/LibJS/Runtime/Temporal/PlainDateConstructor.h b/Userland/Libraries/LibJS/Runtime/Temporal/PlainDateConstructor.h
index 7c790a6a7cf4..29bf550f6047 100644
--- a/Userland/Libraries/LibJS/Runtime/Temporal/PlainDateConstructor.h
+++ b/Userland/Libraries/LibJS/Runtime/Temporal/PlainDateConstructor.h
@@ -24,8 +24,8 @@ class PlainDateConstructor final : public NativeFunction {
private:
virtual bool has_constructor() const override { return true; }
- JS_DECLARE_OLD_NATIVE_FUNCTION(from);
- JS_DECLARE_OLD_NATIVE_FUNCTION(compare);
+ JS_DECLARE_NATIVE_FUNCTION(from);
+ JS_DECLARE_NATIVE_FUNCTION(compare);
};
}
diff --git a/Userland/Libraries/LibJS/Runtime/Temporal/PlainDatePrototype.cpp b/Userland/Libraries/LibJS/Runtime/Temporal/PlainDatePrototype.cpp
index 55a9be6366c4..f1f58ceb68b3 100644
--- a/Userland/Libraries/LibJS/Runtime/Temporal/PlainDatePrototype.cpp
+++ b/Userland/Libraries/LibJS/Runtime/Temporal/PlainDatePrototype.cpp
@@ -33,288 +33,288 @@ void PlainDatePrototype::initialize(GlobalObject& global_object)
// 3.3.2 Temporal.PlainDate.prototype[ @@toStringTag ], https://tc39.es/proposal-temporal/#sec-temporal.plaindate.prototype-@@tostringtag
define_direct_property(*vm.well_known_symbol_to_string_tag(), js_string(vm, "Temporal.PlainDate"), Attribute::Configurable);
- define_old_native_accessor(vm.names.calendar, calendar_getter, {}, Attribute::Configurable);
- define_old_native_accessor(vm.names.year, year_getter, {}, Attribute::Configurable);
- define_old_native_accessor(vm.names.month, month_getter, {}, Attribute::Configurable);
- define_old_native_accessor(vm.names.monthCode, month_code_getter, {}, Attribute::Configurable);
- define_old_native_accessor(vm.names.day, day_getter, {}, Attribute::Configurable);
- define_old_native_accessor(vm.names.dayOfWeek, day_of_week_getter, {}, Attribute::Configurable);
- define_old_native_accessor(vm.names.dayOfYear, day_of_year_getter, {}, Attribute::Configurable);
- define_old_native_accessor(vm.names.weekOfYear, week_of_year_getter, {}, Attribute::Configurable);
- define_old_native_accessor(vm.names.daysInWeek, days_in_week_getter, {}, Attribute::Configurable);
- define_old_native_accessor(vm.names.daysInMonth, days_in_month_getter, {}, Attribute::Configurable);
- define_old_native_accessor(vm.names.daysInYear, days_in_year_getter, {}, Attribute::Configurable);
- define_old_native_accessor(vm.names.monthsInYear, months_in_year_getter, {}, Attribute::Configurable);
- define_old_native_accessor(vm.names.inLeapYear, in_leap_year_getter, {}, Attribute::Configurable);
- define_old_native_accessor(vm.names.era, era_getter, {}, Attribute::Configurable);
- define_old_native_accessor(vm.names.eraYear, era_year_getter, {}, Attribute::Configurable);
+ define_native_accessor(vm.names.calendar, calendar_getter, {}, Attribute::Configurable);
+ define_native_accessor(vm.names.year, year_getter, {}, Attribute::Configurable);
+ define_native_accessor(vm.names.month, month_getter, {}, Attribute::Configurable);
+ define_native_accessor(vm.names.monthCode, month_code_getter, {}, Attribute::Configurable);
+ define_native_accessor(vm.names.day, day_getter, {}, Attribute::Configurable);
+ define_native_accessor(vm.names.dayOfWeek, day_of_week_getter, {}, Attribute::Configurable);
+ define_native_accessor(vm.names.dayOfYear, day_of_year_getter, {}, Attribute::Configurable);
+ define_native_accessor(vm.names.weekOfYear, week_of_year_getter, {}, Attribute::Configurable);
+ define_native_accessor(vm.names.daysInWeek, days_in_week_getter, {}, Attribute::Configurable);
+ define_native_accessor(vm.names.daysInMonth, days_in_month_getter, {}, Attribute::Configurable);
+ define_native_accessor(vm.names.daysInYear, days_in_year_getter, {}, Attribute::Configurable);
+ define_native_accessor(vm.names.monthsInYear, months_in_year_getter, {}, Attribute::Configurable);
+ define_native_accessor(vm.names.inLeapYear, in_leap_year_getter, {}, Attribute::Configurable);
+ define_native_accessor(vm.names.era, era_getter, {}, Attribute::Configurable);
+ define_native_accessor(vm.names.eraYear, era_year_getter, {}, Attribute::Configurable);
u8 attr = Attribute::Writable | Attribute::Configurable;
- define_old_native_function(vm.names.toPlainYearMonth, to_plain_year_month, 0, attr);
- define_old_native_function(vm.names.toPlainMonthDay, to_plain_month_day, 0, attr);
- define_old_native_function(vm.names.getISOFields, get_iso_fields, 0, attr);
- define_old_native_function(vm.names.withCalendar, with_calendar, 1, attr);
- define_old_native_function(vm.names.equals, equals, 1, attr);
- define_old_native_function(vm.names.toPlainDateTime, to_plain_date_time, 0, attr);
- define_old_native_function(vm.names.toString, to_string, 0, attr);
- define_old_native_function(vm.names.toLocaleString, to_locale_string, 0, attr);
- define_old_native_function(vm.names.toJSON, to_json, 0, attr);
- define_old_native_function(vm.names.valueOf, value_of, 0, attr);
+ define_native_function(vm.names.toPlainYearMonth, to_plain_year_month, 0, attr);
+ define_native_function(vm.names.toPlainMonthDay, to_plain_month_day, 0, attr);
+ define_native_function(vm.names.getISOFields, get_iso_fields, 0, attr);
+ define_native_function(vm.names.withCalendar, with_calendar, 1, attr);
+ define_native_function(vm.names.equals, equals, 1, attr);
+ define_native_function(vm.names.toPlainDateTime, to_plain_date_time, 0, attr);
+ define_native_function(vm.names.toString, to_string, 0, attr);
+ define_native_function(vm.names.toLocaleString, to_locale_string, 0, attr);
+ define_native_function(vm.names.toJSON, to_json, 0, attr);
+ define_native_function(vm.names.valueOf, value_of, 0, attr);
}
// 3.3.3 get Temporal.PlainDate.prototype.calendar, https://tc39.es/proposal-temporal/#sec-get-temporal.plaindate.prototype.calendar
-JS_DEFINE_OLD_NATIVE_FUNCTION(PlainDatePrototype::calendar_getter)
+JS_DEFINE_NATIVE_FUNCTION(PlainDatePrototype::calendar_getter)
{
// 1. Let temporalDate be the this value.
// 2. Perform ? RequireInternalSlot(temporalDate, [[InitializedTemporalDate]]).
- auto* temporal_date = TRY_OR_DISCARD(typed_this_object(global_object));
+ auto* temporal_date = TRY(typed_this_object(global_object));
// 3. Return temporalDate.[[Calendar]].
return Value(&temporal_date->calendar());
}
// 3.3.4 get Temporal.PlainDate.prototype.year, https://tc39.es/proposal-temporal/#sec-get-temporal.plaindate.prototype.year
-JS_DEFINE_OLD_NATIVE_FUNCTION(PlainDatePrototype::year_getter)
+JS_DEFINE_NATIVE_FUNCTION(PlainDatePrototype::year_getter)
{
// 1. Let temporalDate be the this value.
// 2. Perform ? RequireInternalSlot(temporalDate, [[InitializedTemporalDate]]).
- auto* temporal_date = TRY_OR_DISCARD(typed_this_object(global_object));
+ auto* temporal_date = TRY(typed_this_object(global_object));
// 3. Let calendar be temporalDate.[[Calendar]].
auto& calendar = temporal_date->calendar();
// 4. Return ? CalendarYear(calendar, temporalDate).
- return Value(TRY_OR_DISCARD(calendar_year(global_object, calendar, *temporal_date)));
+ return Value(TRY(calendar_year(global_object, calendar, *temporal_date)));
}
// 3.3.5 get Temporal.PlainDate.prototype.month, https://tc39.es/proposal-temporal/#sec-get-temporal.plaindate.prototype.month
-JS_DEFINE_OLD_NATIVE_FUNCTION(PlainDatePrototype::month_getter)
+JS_DEFINE_NATIVE_FUNCTION(PlainDatePrototype::month_getter)
{
// 1. Let temporalDate be the this value.
// 2. Perform ? RequireInternalSlot(temporalDate, [[InitializedTemporalDate]]).
- auto* temporal_date = TRY_OR_DISCARD(typed_this_object(global_object));
+ auto* temporal_date = TRY(typed_this_object(global_object));
// 3. Let calendar be temporalDate.[[Calendar]].
auto& calendar = temporal_date->calendar();
// 4. Return ? CalendarMonth(calendar, temporalDate).
- return Value(TRY_OR_DISCARD(calendar_month(global_object, calendar, *temporal_date)));
+ return Value(TRY(calendar_month(global_object, calendar, *temporal_date)));
}
// 3.3.6 get Temporal.PlainDate.prototype.monthCode, https://tc39.es/proposal-temporal/#sec-get-temporal.plaindate.prototype.monthCode
-JS_DEFINE_OLD_NATIVE_FUNCTION(PlainDatePrototype::month_code_getter)
+JS_DEFINE_NATIVE_FUNCTION(PlainDatePrototype::month_code_getter)
{
// 1. Let temporalDate be the this value.
// 2. Perform ? RequireInternalSlot(temporalDate, [[InitializedTemporalDate]]).
- auto* temporal_date = TRY_OR_DISCARD(typed_this_object(global_object));
+ auto* temporal_date = TRY(typed_this_object(global_object));
// 3. Let calendar be temporalDate.[[Calendar]].
auto& calendar = temporal_date->calendar();
// 4. Return ? CalendarMonthCode(calendar, temporalDate).
- return js_string(vm, TRY_OR_DISCARD(calendar_month_code(global_object, calendar, *temporal_date)));
+ return js_string(vm, TRY(calendar_month_code(global_object, calendar, *temporal_date)));
}
// 3.3.7 get Temporal.PlainDate.prototype.day, https://tc39.es/proposal-temporal/#sec-get-temporal.plaindate.prototype.day
-JS_DEFINE_OLD_NATIVE_FUNCTION(PlainDatePrototype::day_getter)
+JS_DEFINE_NATIVE_FUNCTION(PlainDatePrototype::day_getter)
{
// 1. Let temporalDate be the this value.
// 2. Perform ? RequireInternalSlot(temporalDate, [[InitializedTemporalDate]]).
- auto* temporal_date = TRY_OR_DISCARD(typed_this_object(global_object));
+ auto* temporal_date = TRY(typed_this_object(global_object));
// 3. Let calendar be temporalDate.[[Calendar]].
auto& calendar = temporal_date->calendar();
// 4. Return ? CalendarDay(calendar, temporalDate).
- return Value(TRY_OR_DISCARD(calendar_day(global_object, calendar, *temporal_date)));
+ return Value(TRY(calendar_day(global_object, calendar, *temporal_date)));
}
// 3.3.8 get Temporal.PlainDate.prototype.dayOfWeek, https://tc39.es/proposal-temporal/#sec-get-temporal.plaindate.prototype.dayofweek
-JS_DEFINE_OLD_NATIVE_FUNCTION(PlainDatePrototype::day_of_week_getter)
+JS_DEFINE_NATIVE_FUNCTION(PlainDatePrototype::day_of_week_getter)
{
// 1. Let temporalDate be the this value.
// 2. Perform ? RequireInternalSlot(temporalDate, [[InitializedTemporalDate]]).
- auto* temporal_date = TRY_OR_DISCARD(typed_this_object(global_object));
+ auto* temporal_date = TRY(typed_this_object(global_object));
// 3. Let calendar be temporalDate.[[Calendar]].
auto& calendar = temporal_date->calendar();
// Return ? CalendarDayOfWeek(calendar, temporalDate).
- return Value(TRY_OR_DISCARD(calendar_day_of_week(global_object, calendar, *temporal_date)));
+ return Value(TRY(calendar_day_of_week(global_object, calendar, *temporal_date)));
}
// 3.3.9 get Temporal.PlainDate.prototype.dayOfYear, https://tc39.es/proposal-temporal/#sec-get-temporal.plaindate.prototype.dayofyear
-JS_DEFINE_OLD_NATIVE_FUNCTION(PlainDatePrototype::day_of_year_getter)
+JS_DEFINE_NATIVE_FUNCTION(PlainDatePrototype::day_of_year_getter)
{
// 1. Let temporalDate be the this value.
// 2. Perform ? RequireInternalSlot(temporalDate, [[InitializedTemporalDate]]).
- auto* temporal_date = TRY_OR_DISCARD(typed_this_object(global_object));
+ auto* temporal_date = TRY(typed_this_object(global_object));
// 3. Let calendar be temporalDate.[[Calendar]].
auto& calendar = temporal_date->calendar();
// 4. Return ? CalendarDayOfYear(calendar, temporalDate).
- return Value(TRY_OR_DISCARD(calendar_day_of_year(global_object, calendar, *temporal_date)));
+ return Value(TRY(calendar_day_of_year(global_object, calendar, *temporal_date)));
}
// 3.3.10 get Temporal.PlainDate.prototype.weekOfYear, https://tc39.es/proposal-temporal/#sec-get-temporal.plaindate.prototype.weekofyear
-JS_DEFINE_OLD_NATIVE_FUNCTION(PlainDatePrototype::week_of_year_getter)
+JS_DEFINE_NATIVE_FUNCTION(PlainDatePrototype::week_of_year_getter)
{
// 1. Let temporalDate be the this value.
// 2. Perform ? RequireInternalSlot(temporalDate, [[InitializedTemporalDate]]).
- auto* temporal_date = TRY_OR_DISCARD(typed_this_object(global_object));
+ auto* temporal_date = TRY(typed_this_object(global_object));
// 3. Let calendar be temporalDate.[[Calendar]].
auto& calendar = temporal_date->calendar();
// Return ? CalendarWeekOfYear(calendar, temporalDate).
- return Value(TRY_OR_DISCARD(calendar_week_of_year(global_object, calendar, *temporal_date)));
+ return Value(TRY(calendar_week_of_year(global_object, calendar, *temporal_date)));
}
// 3.3.11 get Temporal.PlainDate.prototype.daysInWeek, https://tc39.es/proposal-temporal/#sec-get-temporal.plaindate.prototype.daysinweek
-JS_DEFINE_OLD_NATIVE_FUNCTION(PlainDatePrototype::days_in_week_getter)
+JS_DEFINE_NATIVE_FUNCTION(PlainDatePrototype::days_in_week_getter)
{
// 1. Let temporalDate be the this value.
// 2. Perform ? RequireInternalSlot(temporalDate, [[InitializedTemporalDate]]).
- auto* temporal_date = TRY_OR_DISCARD(typed_this_object(global_object));
+ auto* temporal_date = TRY(typed_this_object(global_object));
// 3. Let calendar be temporalDate.[[Calendar]].
auto& calendar = temporal_date->calendar();
// 4. Return ? CalendarDaysInWeek(calendar, temporalDate).
- return Value(TRY_OR_DISCARD(calendar_days_in_week(global_object, calendar, *temporal_date)));
+ return Value(TRY(calendar_days_in_week(global_object, calendar, *temporal_date)));
}
// 3.3.12 get Temporal.PlainDate.prototype.daysInMonth, https://tc39.es/proposal-temporal/#sec-get-temporal.plaindate.prototype.daysinmonth
-JS_DEFINE_OLD_NATIVE_FUNCTION(PlainDatePrototype::days_in_month_getter)
+JS_DEFINE_NATIVE_FUNCTION(PlainDatePrototype::days_in_month_getter)
{
// 1. Let temporalDate be the this value.
// 2. Perform ? RequireInternalSlot(temporalDate, [[InitializedTemporalDate]]).
- auto* temporal_date = TRY_OR_DISCARD(typed_this_object(global_object));
+ auto* temporal_date = TRY(typed_this_object(global_object));
// 3. Let calendar be temporalDate.[[Calendar]].
auto& calendar = temporal_date->calendar();
// 4. Return ? CalendarDaysInMonth(calendar, temporalDate).
- return Value(TRY_OR_DISCARD(calendar_days_in_month(global_object, calendar, *temporal_date)));
+ return Value(TRY(calendar_days_in_month(global_object, calendar, *temporal_date)));
}
// 3.3.13 get Temporal.PlainDate.prototype.daysInYear, https://tc39.es/proposal-temporal/#sec-get-temporal.plaindate.prototype.daysinyear
-JS_DEFINE_OLD_NATIVE_FUNCTION(PlainDatePrototype::days_in_year_getter)
+JS_DEFINE_NATIVE_FUNCTION(PlainDatePrototype::days_in_year_getter)
{
// 1. Let temporalDate be the this value.
// 2. Perform ? RequireInternalSlot(temporalDate, [[InitializedTemporalDate]]).
- auto* temporal_date = TRY_OR_DISCARD(typed_this_object(global_object));
+ auto* temporal_date = TRY(typed_this_object(global_object));
// 3. Let calendar be temporalDate.[[Calendar]].
auto& calendar = temporal_date->calendar();
// 4. Return ? CalendarDaysInYear(calendar, temporalDate).
- return Value(TRY_OR_DISCARD(calendar_days_in_year(global_object, calendar, *temporal_date)));
+ return Value(TRY(calendar_days_in_year(global_object, calendar, *temporal_date)));
}
// 3.3.14 get Temporal.PlainDate.prototype.monthsInYear, https://tc39.es/proposal-temporal/#sec-get-temporal.plaindate.prototype.monthsinyear
-JS_DEFINE_OLD_NATIVE_FUNCTION(PlainDatePrototype::months_in_year_getter)
+JS_DEFINE_NATIVE_FUNCTION(PlainDatePrototype::months_in_year_getter)
{
// 1. Let temporalDate be the this value.
// 2. Perform ? RequireInternalSlot(temporalDate, [[InitializedTemporalDate]]).
- auto* temporal_date = TRY_OR_DISCARD(typed_this_object(global_object));
+ auto* temporal_date = TRY(typed_this_object(global_object));
// 3. Let calendar be temporalDate.[[Calendar]].
auto& calendar = temporal_date->calendar();
// 4. Return ? CalendarMonthsInYear(calendar, temporalDate).
- return Value(TRY_OR_DISCARD(calendar_months_in_year(global_object, calendar, *temporal_date)));
+ return Value(TRY(calendar_months_in_year(global_object, calendar, *temporal_date)));
}
// 3.3.15 get Temporal.PlainDate.prototype.inLeapYear, https://tc39.es/proposal-temporal/#sec-get-temporal.plaindate.prototype.inleapyear
-JS_DEFINE_OLD_NATIVE_FUNCTION(PlainDatePrototype::in_leap_year_getter)
+JS_DEFINE_NATIVE_FUNCTION(PlainDatePrototype::in_leap_year_getter)
{
// 1. Let temporalDate be the this value.
// 2. Perform ? RequireInternalSlot(temporalDate, [[InitializedTemporalDate]]).
- auto* temporal_date = TRY_OR_DISCARD(typed_this_object(global_object));
+ auto* temporal_date = TRY(typed_this_object(global_object));
// 3. Let calendar be temporalDate.[[Calendar]].
auto& calendar = temporal_date->calendar();
// 4. Return ? CalendarInLeapYear(calendar, temporalDate).
- return Value(TRY_OR_DISCARD(calendar_in_leap_year(global_object, calendar, *temporal_date)));
+ return Value(TRY(calendar_in_leap_year(global_object, calendar, *temporal_date)));
}
// 15.6.5.2 get Temporal.PlainDate.prototype.era, https://tc39.es/proposal-temporal/#sec-get-temporal.plaindate.prototype.era
-JS_DEFINE_OLD_NATIVE_FUNCTION(PlainDatePrototype::era_getter)
+JS_DEFINE_NATIVE_FUNCTION(PlainDatePrototype::era_getter)
{
// 1. Let plainDate be the this value.
// 2. Perform ? RequireInternalSlot(plainDate, [[InitializedTemporalDate]]).
- auto* plain_date = TRY_OR_DISCARD(typed_this_object(global_object));
+ auto* plain_date = TRY(typed_this_object(global_object));
// 3. Let calendar be plainDate.[[Calendar]].
auto& calendar = plain_date->calendar();
// 4. Return ? CalendarEra(calendar, plainDate).
- return TRY_OR_DISCARD(calendar_era(global_object, calendar, *plain_date));
+ return TRY(calendar_era(global_object, calendar, *plain_date));
}
// 15.6.5.3 get Temporal.PlainDate.prototype.eraYear, https://tc39.es/proposal-temporal/#sec-get-temporal.plaindate.prototype.erayear
-JS_DEFINE_OLD_NATIVE_FUNCTION(PlainDatePrototype::era_year_getter)
+JS_DEFINE_NATIVE_FUNCTION(PlainDatePrototype::era_year_getter)
{
// 1. Let plainDate be the this value.
// 2. Perform ? RequireInternalSlot(plainDate, [[InitializedTemporalDate]]).
- auto* plain_date = TRY_OR_DISCARD(typed_this_object(global_object));
+ auto* plain_date = TRY(typed_this_object(global_object));
// 3. Let calendar be plainDate.[[Calendar]].
auto& calendar = plain_date->calendar();
// 4. Return ? CalendarEraYear(calendar, plainDate).
- return TRY_OR_DISCARD(calendar_era_year(global_object, calendar, *plain_date));
+ return TRY(calendar_era_year(global_object, calendar, *plain_date));
}
// 3.3.16 Temporal.PlainDate.prototype.toPlainYearMonth ( ), https://tc39.es/proposal-temporal/#sec-temporal.plaindate.prototype.toplainyearmonth
-JS_DEFINE_OLD_NATIVE_FUNCTION(PlainDatePrototype::to_plain_year_month)
+JS_DEFINE_NATIVE_FUNCTION(PlainDatePrototype::to_plain_year_month)
{
// 1. Let temporalDate be the this value.
// 2. Perform ? RequireInternalSlot(temporalDate, [[InitializedTemporalDate]]).
- auto* temporal_date = TRY_OR_DISCARD(typed_this_object(global_object));
+ auto* temporal_date = TRY(typed_this_object(global_object));
// 3. Let calendar be temporalDate.[[Calendar]].
auto& calendar = temporal_date->calendar();
// 4. Let fieldNames be ? CalendarFields(calendar, « "monthCode", "year" »).
- auto field_names = TRY_OR_DISCARD(calendar_fields(global_object, calendar, { "monthCode"sv, "year"sv }));
+ auto field_names = TRY(calendar_fields(global_object, calendar, { "monthCode"sv, "year"sv }));
// 5. Let fields be ? PrepareTemporalFields(temporalDate, fieldNames, «»).
- auto* fields = TRY_OR_DISCARD(prepare_temporal_fields(global_object, *temporal_date, field_names, {}));
+ auto* fields = TRY(prepare_temporal_fields(global_object, *temporal_date, field_names, {}));
// 6. Return ? YearMonthFromFields(calendar, fields).
- return TRY_OR_DISCARD(year_month_from_fields(global_object, calendar, *fields));
+ return TRY(year_month_from_fields(global_object, calendar, *fields));
}
// 3.3.17 Temporal.PlainDate.prototype.toPlainMonthDay ( ), https://tc39.es/proposal-temporal/#sec-temporal.plaindate.prototype.toplainmonthday
-JS_DEFINE_OLD_NATIVE_FUNCTION(PlainDatePrototype::to_plain_month_day)
+JS_DEFINE_NATIVE_FUNCTION(PlainDatePrototype::to_plain_month_day)
{
// 1. Let temporalDate be the this value.
// 2. Perform ? RequireInternalSlot(temporalDate, [[InitializedTemporalDate]]).
- auto* temporal_date = TRY_OR_DISCARD(typed_this_object(global_object));
+ auto* temporal_date = TRY(typed_this_object(global_object));
// 3. Let calendar be temporalDate.[[Calendar]].
auto& calendar = temporal_date->calendar();
// 4. Let fieldNames be ? CalendarFields(calendar, « "day", "monthCode" »).
- auto field_names = TRY_OR_DISCARD(calendar_fields(global_object, calendar, { "day"sv, "monthCode"sv }));
+ auto field_names = TRY(calendar_fields(global_object, calendar, { "day"sv, "monthCode"sv }));
// 5. Let fields be ? PrepareTemporalFields(temporalDate, fieldNames, «»).
- auto* fields = TRY_OR_DISCARD(prepare_temporal_fields(global_object, *temporal_date, field_names, {}));
+ auto* fields = TRY(prepare_temporal_fields(global_object, *temporal_date, field_names, {}));
// 6. Return ? MonthDayFromFields(calendar, fields).
- return TRY_OR_DISCARD(month_day_from_fields(global_object, calendar, *fields));
+ return TRY(month_day_from_fields(global_object, calendar, *fields));
}
// 3.3.18 Temporal.PlainDate.prototype.getISOFields ( ), https://tc39.es/proposal-temporal/#sec-temporal.plaindate.prototype.getisofields
-JS_DEFINE_OLD_NATIVE_FUNCTION(PlainDatePrototype::get_iso_fields)
+JS_DEFINE_NATIVE_FUNCTION(PlainDatePrototype::get_iso_fields)
{
// 1. Let temporalDate be the this value.
// 2. Perform ? RequireInternalSlot(temporalDate, [[InitializedTemporalDate]]).
- auto* temporal_date = TRY_OR_DISCARD(typed_this_object(global_object));
+ auto* temporal_date = TRY(typed_this_object(global_object));
// 3. Let fields be ! OrdinaryObjectCreate(%Object.prototype%).
auto* fields = Object::create(global_object, global_object.object_prototype());
@@ -336,28 +336,28 @@ JS_DEFINE_OLD_NATIVE_FUNCTION(PlainDatePrototype::get_iso_fields)
}
// 3.3.22 Temporal.PlainDate.prototype.withCalendar ( calendar ), https://tc39.es/proposal-temporal/#sec-temporal.plaindate.prototype.withcalendar
-JS_DEFINE_OLD_NATIVE_FUNCTION(PlainDatePrototype::with_calendar)
+JS_DEFINE_NATIVE_FUNCTION(PlainDatePrototype::with_calendar)
{
// 1. Let temporalDate be the this value.
// 2. Perform ? RequireInternalSlot(temporalDate, [[InitializedTemporalDate]]).
- auto* temporal_date = TRY_OR_DISCARD(typed_this_object(global_object));
+ auto* temporal_date = TRY(typed_this_object(global_object));
// 3. Let calendar be ? ToTemporalCalendar(calendar).
- auto* calendar = TRY_OR_DISCARD(to_temporal_calendar(global_object, vm.argument(0)));
+ auto* calendar = TRY(to_temporal_calendar(global_object, vm.argument(0)));
// 4. Return ? CreateTemporalDate(temporalDate.[[ISOYear]], temporalDate.[[ISOMonth]], temporalDate.[[ISODay]], calendar).
- return TRY_OR_DISCARD(create_temporal_date(global_object, temporal_date->iso_year(), temporal_date->iso_month(), temporal_date->iso_day(), *calendar));
+ return TRY(create_temporal_date(global_object, temporal_date->iso_year(), temporal_date->iso_month(), temporal_date->iso_day(), *calendar));
}
// 3.3.25 Temporal.PlainDate.prototype.equals ( other ), https://tc39.es/proposal-temporal/#sec-temporal.plaindate.prototype.equals
-JS_DEFINE_OLD_NATIVE_FUNCTION(PlainDatePrototype::equals)
+JS_DEFINE_NATIVE_FUNCTION(PlainDatePrototype::equals)
{
// 1. Let temporalDate be the this value.
// 2. Perform ? RequireInternalSlot(temporalDate, [[InitializedTemporalDate]]).
- auto* temporal_date = TRY_OR_DISCARD(typed_this_object(global_object));
+ auto* temporal_date = TRY(typed_this_object(global_object));
// 3. Set other to ? ToTemporalDate(other).
- auto* other = TRY_OR_DISCARD(to_temporal_date(global_object, vm.argument(0)));
+ auto* other = TRY(to_temporal_date(global_object, vm.argument(0)));
// 4. If temporalDate.[[ISOYear]] ≠ other.[[ISOYear]], return false.
if (temporal_date->iso_year() != other->iso_year())
@@ -369,75 +369,74 @@ JS_DEFINE_OLD_NATIVE_FUNCTION(PlainDatePrototype::equals)
if (temporal_date->iso_day() != other->iso_day())
return Value(false);
// 7. Return ? CalendarEquals(temporalDate.[[Calendar]], other.[[Calendar]]).
- return Value(TRY_OR_DISCARD(calendar_equals(global_object, temporal_date->calendar(), other->calendar())));
+ return Value(TRY(calendar_equals(global_object, temporal_date->calendar(), other->calendar())));
}
// 3.3.26 Temporal.PlainDate.prototype.toPlainDateTime ( [ temporalTime ] ), https://tc39.es/proposal-temporal/#sec-temporal.plaindate.prototype.toplaindatetime
-JS_DEFINE_OLD_NATIVE_FUNCTION(PlainDatePrototype::to_plain_date_time)
+JS_DEFINE_NATIVE_FUNCTION(PlainDatePrototype::to_plain_date_time)
{
// 1. Let temporalDate be the this value.
// 2. Perform ? RequireInternalSlot(temporalDate, [[InitializedTemporalDate]]).
- auto* temporal_date = TRY_OR_DISCARD(typed_this_object(global_object));
+ auto* temporal_date = TRY(typed_this_object(global_object));
// 3. If temporalTime is undefined, then
if (vm.argument(0).is_undefined()) {
// a. Return ? CreateTemporalDateTime(temporalDate.[[ISOYear]], temporalDate.[[ISOMonth]], temporalDate.[[ISODay]], 0, 0, 0, 0, 0, 0, temporalDate.[[Calendar]]).
- return TRY_OR_DISCARD(create_temporal_date_time(global_object, temporal_date->iso_year(), temporal_date->iso_month(), temporal_date->iso_day(), 0, 0, 0, 0, 0, 0, temporal_date->calendar()));
+ return TRY(create_temporal_date_time(global_object, temporal_date->iso_year(), temporal_date->iso_month(), temporal_date->iso_day(), 0, 0, 0, 0, 0, 0, temporal_date->calendar()));
}
// 4. Set temporalTime to ? ToTemporalTime(temporalTime).
- auto* temporal_time = TRY_OR_DISCARD(to_temporal_time(global_object, vm.argument(0)));
+ auto* temporal_time = TRY(to_temporal_time(global_object, vm.argument(0)));
// 5. Return ? CreateTemporalDateTime(temporalDate.[[ISOYear]], temporalDate.[[ISOMonth]], temporalDate.[[ISODay]], temporalTime.[[ISOHour]], temporalTime.[[ISOMinute]], temporalTime.[[ISOSecond]], temporalTime.[[ISOMillisecond]], temporalTime.[[ISOMicrosecond]], temporalTime.[[ISONanosecond]], temporalDate.[[Calendar]]).
- return TRY_OR_DISCARD(create_temporal_date_time(global_object, temporal_date->iso_year(), temporal_date->iso_month(), temporal_date->iso_day(), temporal_time->iso_hour(), temporal_time->iso_minute(), temporal_time->iso_second(), temporal_time->iso_millisecond(), temporal_time->iso_microsecond(), temporal_time->iso_nanosecond(), temporal_date->calendar()));
+ return TRY(create_temporal_date_time(global_object, temporal_date->iso_year(), temporal_date->iso_month(), temporal_date->iso_day(), temporal_time->iso_hour(), temporal_time->iso_minute(), temporal_time->iso_second(), temporal_time->iso_millisecond(), temporal_time->iso_microsecond(), temporal_time->iso_nanosecond(), temporal_date->calendar()));
}
// 3.3.28 Temporal.PlainDate.prototype.toString ( [ options ] ), https://tc39.es/proposal-temporal/#sec-temporal.plaindate.prototype.tostring
-JS_DEFINE_OLD_NATIVE_FUNCTION(PlainDatePrototype::to_string)
+JS_DEFINE_NATIVE_FUNCTION(PlainDatePrototype::to_string)
{
// 1. Let temporalDate be the this value.
// 2. Perform ? RequireInternalSlot(temporalDate, [[InitializedTemporalDate]]).
- auto* temporal_date = TRY_OR_DISCARD(typed_this_object(global_object));
+ auto* temporal_date = TRY(typed_this_object(global_object));
// 3. Set options to ? GetOptionsObject(options).
- auto* options = TRY_OR_DISCARD(get_options_object(global_object, vm.argument(0)));
+ auto* options = TRY(get_options_object(global_object, vm.argument(0)));
// 4. Let showCalendar be ? ToShowCalendarOption(options).
- auto show_calendar = TRY_OR_DISCARD(to_show_calendar_option(global_object, *options));
+ auto show_calendar = TRY(to_show_calendar_option(global_object, *options));
// 5. Return ? TemporalDateToString(temporalDate, showCalendar).
- return js_string(vm, TRY_OR_DISCARD(temporal_date_to_string(global_object, *temporal_date, show_calendar)));
+ return js_string(vm, TRY(temporal_date_to_string(global_object, *temporal_date, show_calendar)));
}
// 3.3.29 Temporal.PlainDate.prototype.toLocaleString ( [ locales [ , options ] ] ), https://tc39.es/proposal-temporal/#sec-temporal.plaindate.prototype.tolocalestring
// NOTE: This is the minimum toLocaleString implementation for engines without ECMA-402.
-JS_DEFINE_OLD_NATIVE_FUNCTION(PlainDatePrototype::to_locale_string)
+JS_DEFINE_NATIVE_FUNCTION(PlainDatePrototype::to_locale_string)
{
// 1. Let temporalDate be the this value.
// 2. Perform ? RequireInternalSlot(temporalDate, [[InitializedTemporalDate]]).
- auto* temporal_date = TRY_OR_DISCARD(typed_this_object(global_object));
+ auto* temporal_date = TRY(typed_this_object(global_object));
// 3. Return ? TemporalDateToString(temporalDate, "auto").
- return js_string(vm, TRY_OR_DISCARD(temporal_date_to_string(global_object, *temporal_date, "auto"sv)));
+ return js_string(vm, TRY(temporal_date_to_string(global_object, *temporal_date, "auto"sv)));
}
// 3.3.30 Temporal.PlainDate.prototype.toJSON ( ), https://tc39.es/proposal-temporal/#sec-temporal.plaindate.prototype.tojson
-JS_DEFINE_OLD_NATIVE_FUNCTION(PlainDatePrototype::to_json)
+JS_DEFINE_NATIVE_FUNCTION(PlainDatePrototype::to_json)
{
// 1. Let temporalDate be the this value.
// 2. Perform ? RequireInternalSlot(temporalDate, [[InitializedTemporalDate]]).
- auto* temporal_date = TRY_OR_DISCARD(typed_this_object(global_object));
+ auto* temporal_date = TRY(typed_this_object(global_object));
// 3. Return ? TemporalDateToString(temporalDate, "auto").
- return js_string(vm, TRY_OR_DISCARD(temporal_date_to_string(global_object, *temporal_date, "auto"sv)));
+ return js_string(vm, TRY(temporal_date_to_string(global_object, *temporal_date, "auto"sv)));
}
// 3.3.31 Temporal.PlainDate.prototype.valueOf ( ), https://tc39.es/proposal-temporal/#sec-temporal.plaindate.prototype.valueof
-JS_DEFINE_OLD_NATIVE_FUNCTION(PlainDatePrototype::value_of)
+JS_DEFINE_NATIVE_FUNCTION(PlainDatePrototype::value_of)
{
// 1. Throw a TypeError exception.
- vm.throw_exception<TypeError>(global_object, ErrorType::Convert, "Temporal.PlainDate", "a primitive value");
- return {};
+ return vm.throw_completion<TypeError>(global_object, ErrorType::Convert, "Temporal.PlainDate", "a primitive value");
}
}
diff --git a/Userland/Libraries/LibJS/Runtime/Temporal/PlainDatePrototype.h b/Userland/Libraries/LibJS/Runtime/Temporal/PlainDatePrototype.h
index bc0d695d7b24..692cc36586b4 100644
--- a/Userland/Libraries/LibJS/Runtime/Temporal/PlainDatePrototype.h
+++ b/Userland/Libraries/LibJS/Runtime/Temporal/PlainDatePrototype.h
@@ -20,31 +20,31 @@ class PlainDatePrototype final : public PrototypeObject<PlainDatePrototype, Plai
virtual ~PlainDatePrototype() override = default;
private:
- JS_DECLARE_OLD_NATIVE_FUNCTION(calendar_getter);
- JS_DECLARE_OLD_NATIVE_FUNCTION(year_getter);
- JS_DECLARE_OLD_NATIVE_FUNCTION(month_getter);
- JS_DECLARE_OLD_NATIVE_FUNCTION(month_code_getter);
- JS_DECLARE_OLD_NATIVE_FUNCTION(day_getter);
- JS_DECLARE_OLD_NATIVE_FUNCTION(day_of_week_getter);
- JS_DECLARE_OLD_NATIVE_FUNCTION(day_of_year_getter);
- JS_DECLARE_OLD_NATIVE_FUNCTION(week_of_year_getter);
- JS_DECLARE_OLD_NATIVE_FUNCTION(days_in_week_getter);
- JS_DECLARE_OLD_NATIVE_FUNCTION(days_in_month_getter);
- JS_DECLARE_OLD_NATIVE_FUNCTION(days_in_year_getter);
- JS_DECLARE_OLD_NATIVE_FUNCTION(months_in_year_getter);
- JS_DECLARE_OLD_NATIVE_FUNCTION(in_leap_year_getter);
- JS_DECLARE_OLD_NATIVE_FUNCTION(era_getter);
- JS_DECLARE_OLD_NATIVE_FUNCTION(era_year_getter);
- JS_DECLARE_OLD_NATIVE_FUNCTION(to_plain_year_month);
- JS_DECLARE_OLD_NATIVE_FUNCTION(to_plain_month_day);
- JS_DECLARE_OLD_NATIVE_FUNCTION(get_iso_fields);
- JS_DECLARE_OLD_NATIVE_FUNCTION(with_calendar);
- JS_DECLARE_OLD_NATIVE_FUNCTION(equals);
- JS_DECLARE_OLD_NATIVE_FUNCTION(to_plain_date_time);
- JS_DECLARE_OLD_NATIVE_FUNCTION(to_string);
- JS_DECLARE_OLD_NATIVE_FUNCTION(to_locale_string);
- JS_DECLARE_OLD_NATIVE_FUNCTION(to_json);
- JS_DECLARE_OLD_NATIVE_FUNCTION(value_of);
+ JS_DECLARE_NATIVE_FUNCTION(calendar_getter);
+ JS_DECLARE_NATIVE_FUNCTION(year_getter);
+ JS_DECLARE_NATIVE_FUNCTION(month_getter);
+ JS_DECLARE_NATIVE_FUNCTION(month_code_getter);
+ JS_DECLARE_NATIVE_FUNCTION(day_getter);
+ JS_DECLARE_NATIVE_FUNCTION(day_of_week_getter);
+ JS_DECLARE_NATIVE_FUNCTION(day_of_year_getter);
+ JS_DECLARE_NATIVE_FUNCTION(week_of_year_getter);
+ JS_DECLARE_NATIVE_FUNCTION(days_in_week_getter);
+ JS_DECLARE_NATIVE_FUNCTION(days_in_month_getter);
+ JS_DECLARE_NATIVE_FUNCTION(days_in_year_getter);
+ JS_DECLARE_NATIVE_FUNCTION(months_in_year_getter);
+ JS_DECLARE_NATIVE_FUNCTION(in_leap_year_getter);
+ JS_DECLARE_NATIVE_FUNCTION(era_getter);
+ JS_DECLARE_NATIVE_FUNCTION(era_year_getter);
+ JS_DECLARE_NATIVE_FUNCTION(to_plain_year_month);
+ JS_DECLARE_NATIVE_FUNCTION(to_plain_month_day);
+ JS_DECLARE_NATIVE_FUNCTION(get_iso_fields);
+ JS_DECLARE_NATIVE_FUNCTION(with_calendar);
+ JS_DECLARE_NATIVE_FUNCTION(equals);
+ JS_DECLARE_NATIVE_FUNCTION(to_plain_date_time);
+ JS_DECLARE_NATIVE_FUNCTION(to_string);
+ JS_DECLARE_NATIVE_FUNCTION(to_locale_string);
+ JS_DECLARE_NATIVE_FUNCTION(to_json);
+ JS_DECLARE_NATIVE_FUNCTION(value_of);
};
}
|
d016d5e365ca7fabee627cf68032a3667fd29a37
|
2019-11-09 05:11:00
|
Andreas Kling
|
hackstudio: Start fleshing out the GUI for a GUI designer :^)
| false
|
Start fleshing out the GUI for a GUI designer :^)
|
hackstudio
|
diff --git a/AK/Tests/TestJSON.cpp b/AK/Tests/TestJSON.cpp
index 30cef3fd3e8f..bbdfd258177e 100644
--- a/AK/Tests/TestJSON.cpp
+++ b/AK/Tests/TestJSON.cpp
@@ -9,7 +9,7 @@
TEST_CASE(load_form)
{
- FILE* fp = fopen("../../Base/home/anon/test.frm", "r");
+ FILE* fp = fopen("../../Base/home/anon/little/test.frm", "r");
ASSERT(fp);
StringBuilder builder;
diff --git a/Base/home/anon/little/little.files b/Base/home/anon/little/little.files
index c4647b0dc776..46648a0e1855 100644
--- a/Base/home/anon/little/little.files
+++ b/Base/home/anon/little/little.files
@@ -1,3 +1,4 @@
main.cpp
Makefile
little.files
+test.frm
diff --git a/Base/home/anon/test.frm b/Base/home/anon/little/test.frm
similarity index 100%
rename from Base/home/anon/test.frm
rename to Base/home/anon/little/test.frm
diff --git a/DevTools/HackStudio/FormEditorWidget.cpp b/DevTools/HackStudio/FormEditorWidget.cpp
new file mode 100644
index 000000000000..14c82943380a
--- /dev/null
+++ b/DevTools/HackStudio/FormEditorWidget.cpp
@@ -0,0 +1,28 @@
+#include "FormEditorWidget.h"
+#include "FormWidget.h"
+#include <LibGUI/GPainter.h>
+
+FormEditorWidget::FormEditorWidget(GWidget* parent)
+ : GScrollableWidget(parent)
+{
+ set_fill_with_background_color(true);
+ set_background_color(Color::White);
+
+ set_frame_shape(FrameShape::Container);
+ set_frame_shadow(FrameShadow::Sunken);
+ set_frame_thickness(2);
+
+ m_form_widget = FormWidget::construct(*this);
+}
+
+FormEditorWidget::~FormEditorWidget()
+{
+}
+
+void FormEditorWidget::paint_event(GPaintEvent& event)
+{
+ GFrame::paint_event(event);
+
+ GPainter painter(*this);
+ painter.add_clip_rect(event.rect());
+}
diff --git a/DevTools/HackStudio/FormEditorWidget.h b/DevTools/HackStudio/FormEditorWidget.h
new file mode 100644
index 000000000000..ef53044f8f45
--- /dev/null
+++ b/DevTools/HackStudio/FormEditorWidget.h
@@ -0,0 +1,18 @@
+#pragma once
+
+#include <LibGUI/GScrollableWidget.h>
+
+class FormWidget;
+
+class FormEditorWidget final : public GScrollableWidget {
+ C_OBJECT(FormEditorWidget)
+public:
+ virtual ~FormEditorWidget() override;
+
+private:
+ virtual void paint_event(GPaintEvent&) override;
+
+ explicit FormEditorWidget(GWidget* parent);
+
+ RefPtr<FormWidget> m_form_widget;
+};
diff --git a/DevTools/HackStudio/FormWidget.cpp b/DevTools/HackStudio/FormWidget.cpp
new file mode 100644
index 000000000000..03d8555ad3cd
--- /dev/null
+++ b/DevTools/HackStudio/FormWidget.cpp
@@ -0,0 +1,27 @@
+#include "FormWidget.h"
+#include "FormEditorWidget.h"
+#include <LibGUI/GPainter.h>
+
+FormWidget::FormWidget(FormEditorWidget& parent)
+ : GWidget(&parent)
+{
+ set_fill_with_background_color(true);
+ set_background_color(Color::WarmGray);
+ set_relative_rect(20, 20, 400, 300);
+}
+
+FormWidget::~FormWidget()
+{
+}
+
+void FormWidget::paint_event(GPaintEvent& event)
+{
+ GPainter painter(*this);
+ painter.add_clip_rect(event.rect());
+
+ for (int y = 0; y < height(); y += m_grid_size) {
+ for (int x = 0; x < width(); x += m_grid_size) {
+ painter.set_pixel({ x, y }, Color::from_rgb(0x404040));
+ }
+ }
+}
diff --git a/DevTools/HackStudio/FormWidget.h b/DevTools/HackStudio/FormWidget.h
new file mode 100644
index 000000000000..c309b7e6a115
--- /dev/null
+++ b/DevTools/HackStudio/FormWidget.h
@@ -0,0 +1,22 @@
+#pragma once
+
+#include <LibGUI/GWidget.h>
+
+class FormEditorWidget;
+
+class FormWidget final : public GWidget {
+ C_OBJECT(FormWidget)
+public:
+ virtual ~FormWidget() override;
+
+ FormEditorWidget& editor();
+ const FormEditorWidget& editor() const;
+
+private:
+ virtual void paint_event(GPaintEvent&) override;
+
+ explicit FormWidget(FormEditorWidget& parent);
+
+ // FIXME: This should be an app-wide preference instead.
+ int m_grid_size { 5 };
+};
diff --git a/DevTools/HackStudio/Makefile b/DevTools/HackStudio/Makefile
index e37a4dd47b5e..964f5dd86c35 100644
--- a/DevTools/HackStudio/Makefile
+++ b/DevTools/HackStudio/Makefile
@@ -6,6 +6,8 @@ OBJS = \
TerminalWrapper.o \
FindInFilesWidget.o \
ProcessStateWidget.o \
+ FormEditorWidget.o \
+ FormWidget.o \
CppLexer.o \
Editor.o \
EditorWrapper.o \
diff --git a/DevTools/HackStudio/main.cpp b/DevTools/HackStudio/main.cpp
index f5521ef867ec..d4e508f399c0 100644
--- a/DevTools/HackStudio/main.cpp
+++ b/DevTools/HackStudio/main.cpp
@@ -2,6 +2,7 @@
#include "Editor.h"
#include "EditorWrapper.h"
#include "FindInFilesWidget.h"
+#include "FormEditorWidget.h"
#include "Locator.h"
#include "Project.h"
#include "TerminalWrapper.h"
@@ -19,6 +20,7 @@
#include <LibGUI/GMenuBar.h>
#include <LibGUI/GMessageBox.h>
#include <LibGUI/GSplitter.h>
+#include <LibGUI/GStackWidget.h>
#include <LibGUI/GTabWidget.h>
#include <LibGUI/GTextBox.h>
#include <LibGUI/GTextEditor.h>
@@ -35,6 +37,9 @@ String g_currently_open_file;
OwnPtr<Project> g_project;
RefPtr<GWindow> g_window;
RefPtr<GListView> g_project_list_view;
+RefPtr<GStackWidget> g_right_hand_stack;
+RefPtr<GSplitter> g_inner_splitter;
+RefPtr<FormEditorWidget> g_form_editor_widget;
static RefPtr<GTabWidget> s_action_tab_widget;
@@ -51,6 +56,20 @@ void add_new_editor(GWidget& parent)
wrapper->editor().set_focus(true);
}
+enum class EditMode {
+ Text,
+ Form,
+};
+
+void set_edit_mode(EditMode mode)
+{
+ if (mode == EditMode::Text) {
+ g_right_hand_stack->set_active_widget(g_inner_splitter);
+ } else if (mode == EditMode::Form) {
+ g_right_hand_stack->set_active_widget(g_form_editor_widget);
+ }
+}
+
EditorWrapper& current_editor_wrapper()
{
ASSERT(g_current_editor_wrapper);
@@ -98,9 +117,13 @@ int main(int argc, char** argv)
g_project_list_view->set_size_policy(SizePolicy::Fixed, SizePolicy::Fill);
g_project_list_view->set_preferred_size(140, 0);
- auto inner_splitter = GSplitter::construct(Orientation::Vertical, outer_splitter);
- inner_splitter->layout()->set_margins({ 0, 3, 0, 0 });
- add_new_editor(inner_splitter);
+ g_right_hand_stack = GStackWidget::construct(outer_splitter);
+
+ g_form_editor_widget = FormEditorWidget::construct(g_right_hand_stack);
+
+ g_inner_splitter = GSplitter::construct(Orientation::Vertical, g_right_hand_stack);
+ g_inner_splitter->layout()->set_margins({ 0, 3, 0, 0 });
+ add_new_editor(*g_inner_splitter);
auto new_action = GAction::create("Add new file to project...", { Mod_Ctrl, Key_N }, GraphicsBitmap::load_from_file("/res/icons/16x16/new.png"), [&](const GAction&) {
auto input_box = GInputBox::construct("Enter name of new file:", "Add new file to project", g_window);
@@ -136,7 +159,7 @@ int main(int argc, char** argv)
if (g_all_editor_wrappers.size() <= 1)
return;
Vector<EditorWrapper*> wrappers;
- inner_splitter->for_each_child_of_type<EditorWrapper>([&](auto& child) {
+ g_inner_splitter->for_each_child_of_type<EditorWrapper>([&](auto& child) {
wrappers.append(&child);
return IterationDecision::Continue;
});
@@ -154,7 +177,7 @@ int main(int argc, char** argv)
if (g_all_editor_wrappers.size() <= 1)
return;
Vector<EditorWrapper*> wrappers;
- inner_splitter->for_each_child_of_type<EditorWrapper>([&](auto& child) {
+ g_inner_splitter->for_each_child_of_type<EditorWrapper>([&](auto& child) {
wrappers.append(&child);
return IterationDecision::Continue;
});
@@ -173,7 +196,7 @@ int main(int argc, char** argv)
return;
auto wrapper = g_current_editor_wrapper;
switch_to_next_editor->activate();
- inner_splitter->remove_child(*wrapper);
+ g_inner_splitter->remove_child(*wrapper);
g_all_editor_wrappers.remove_first_matching([&](auto& entry) { return entry == wrapper.ptr(); });
update_actions();
});
@@ -202,7 +225,7 @@ int main(int argc, char** argv)
open_file(filename);
};
- s_action_tab_widget = GTabWidget::construct(inner_splitter);
+ s_action_tab_widget = GTabWidget::construct(g_inner_splitter);
s_action_tab_widget->set_size_policy(SizePolicy::Fill, SizePolicy::Fixed);
s_action_tab_widget->set_preferred_size(0, 24);
@@ -222,7 +245,7 @@ int main(int argc, char** argv)
});
auto add_editor_action = GAction::create("Add new editor", { Mod_Ctrl | Mod_Alt, Key_E }, [&](auto&) {
- add_new_editor(inner_splitter);
+ add_new_editor(*g_inner_splitter);
update_actions();
});
@@ -379,6 +402,12 @@ void open_file(const String& filename)
current_editor().on_change = nullptr;
}
+ if (filename.ends_with(".frm")) {
+ set_edit_mode(EditMode::Form);
+ } else {
+ set_edit_mode(EditMode::Text);
+ }
+
g_currently_open_file = filename;
g_window->set_title(String::format("%s - HackStudio", g_currently_open_file.characters()));
g_project_list_view->update();
|
933a717f3b5cc44dee5c2d3a55acd14ad6eb27fd
|
2022-03-20 02:33:51
|
Maciej
|
libcore: Make application/octet-stream the default guessed MIME type
| false
|
Make application/octet-stream the default guessed MIME type
|
libcore
|
diff --git a/Userland/Libraries/LibCore/MimeData.cpp b/Userland/Libraries/LibCore/MimeData.cpp
index 500e716bcc43..daedb8723561 100644
--- a/Userland/Libraries/LibCore/MimeData.cpp
+++ b/Userland/Libraries/LibCore/MimeData.cpp
@@ -86,7 +86,7 @@ String guess_mime_type_based_on_filename(StringView path)
return "text/html";
if (path.ends_with(".csv", CaseSensitivity::CaseInsensitive))
return "text/csv";
- return "text/plain";
+ return "application/octet-stream";
}
#define ENUMERATE_HEADER_CONTENTS \
|
3ba17d8df7dff55069a79832bffe5c94a3b3159b
|
2020-06-20 21:23:33
|
Andreas Kling
|
libjs: Make Interpreter::construct() take a GlobalObject&
| false
|
Make Interpreter::construct() take a GlobalObject&
|
libjs
|
diff --git a/Libraries/LibJS/Interpreter.cpp b/Libraries/LibJS/Interpreter.cpp
index abf18af759b7..de98858134a6 100644
--- a/Libraries/LibJS/Interpreter.cpp
+++ b/Libraries/LibJS/Interpreter.cpp
@@ -231,7 +231,7 @@ Value Interpreter::call(Function& function, Value this_value, Optional<MarkedVal
return result;
}
-Value Interpreter::construct(Function& function, Function& new_target, Optional<MarkedValueList> arguments)
+Value Interpreter::construct(Function& function, Function& new_target, Optional<MarkedValueList> arguments, GlobalObject& global_object)
{
auto& call_frame = push_call_frame();
call_frame.function_name = function.name();
@@ -239,7 +239,7 @@ Value Interpreter::construct(Function& function, Function& new_target, Optional<
call_frame.arguments = arguments.value().values();
call_frame.environment = function.create_environment();
- auto* new_object = Object::create_empty(*this, global_object());
+ auto* new_object = Object::create_empty(*this, global_object);
auto prototype = new_target.get("prototype");
if (exception())
return {};
diff --git a/Libraries/LibJS/Interpreter.h b/Libraries/LibJS/Interpreter.h
index 6897b5401853..00e4cacf79bc 100644
--- a/Libraries/LibJS/Interpreter.h
+++ b/Libraries/LibJS/Interpreter.h
@@ -117,7 +117,7 @@ class Interpreter : public Weakable<Interpreter> {
void exit_scope(const ScopeNode&);
Value call(Function&, Value this_value, Optional<MarkedValueList> arguments = {});
- Value construct(Function&, Function& new_target, Optional<MarkedValueList> arguments = {});
+ Value construct(Function&, Function& new_target, Optional<MarkedValueList> arguments, GlobalObject&);
CallFrame& push_call_frame()
{
diff --git a/Libraries/LibJS/Runtime/ReflectObject.cpp b/Libraries/LibJS/Runtime/ReflectObject.cpp
index 284054e46cd9..2c3cfa251c74 100644
--- a/Libraries/LibJS/Runtime/ReflectObject.cpp
+++ b/Libraries/LibJS/Runtime/ReflectObject.cpp
@@ -135,7 +135,7 @@ JS_DEFINE_NATIVE_FUNCTION(ReflectObject::construct)
}
new_target = &new_target_value.as_function();
}
- return interpreter.construct(*target, *new_target, move(arguments));
+ return interpreter.construct(*target, *new_target, move(arguments), global_object);
}
JS_DEFINE_NATIVE_FUNCTION(ReflectObject::define_property)
|
ee5a49e2fe78e1bd0a375971e8400f2ca401205c
|
2020-03-12 19:28:16
|
0xtechnobabble
|
libjs: Implement const variable declarations
| false
|
Implement const variable declarations
|
libjs
|
diff --git a/Libraries/LibJS/AST.cpp b/Libraries/LibJS/AST.cpp
index 309decb3d994..d1cf0710bbc4 100644
--- a/Libraries/LibJS/AST.cpp
+++ b/Libraries/LibJS/AST.cpp
@@ -456,6 +456,7 @@ Value UpdateExpression::execute(Interpreter& interpreter) const
break;
case UpdateOp::Decrement:
interpreter.set_variable(name, Value(previous_value.as_double() - 1));
+ break;
}
return previous_value;
@@ -520,19 +521,22 @@ Value VariableDeclaration::execute(Interpreter& interpreter) const
void VariableDeclaration::dump(int indent) const
{
- const char* op_string = nullptr;
+ const char* declaration_type_string = nullptr;
switch (m_declaration_type) {
case DeclarationType::Let:
- op_string = "Let";
+ declaration_type_string = "Let";
break;
case DeclarationType::Var:
- op_string = "Var";
+ declaration_type_string = "Var";
+ break;
+ case DeclarationType::Const:
+ declaration_type_string = "Const";
break;
}
ASTNode::dump(indent);
print_indent(indent + 1);
- printf("%s\n", op_string);
+ printf("%s\n", declaration_type_string);
m_name->dump(indent + 1);
if (m_initializer)
m_initializer->dump(indent + 1);
diff --git a/Libraries/LibJS/AST.h b/Libraries/LibJS/AST.h
index 5c28f44db3a9..9fd8d7baa66b 100644
--- a/Libraries/LibJS/AST.h
+++ b/Libraries/LibJS/AST.h
@@ -470,6 +470,7 @@ class UpdateExpression : public Expression {
enum class DeclarationType {
Var,
Let,
+ Const,
};
class VariableDeclaration : public Statement {
diff --git a/Libraries/LibJS/Interpreter.cpp b/Libraries/LibJS/Interpreter.cpp
index 2f0b20d87b6a..8a569e0fe398 100644
--- a/Libraries/LibJS/Interpreter.cpp
+++ b/Libraries/LibJS/Interpreter.cpp
@@ -57,7 +57,12 @@ Value Interpreter::run(const ScopeNode& scope_node, HashMap<String, Value> scope
void Interpreter::enter_scope(const ScopeNode& scope_node, HashMap<String, Value> scope_variables, ScopeType scope_type)
{
- m_scope_stack.append({ scope_type, scope_node, move(scope_variables) });
+ HashMap<String, Variable> scope_variables_with_declaration_type;
+ for (String name : scope_variables.keys()) {
+ scope_variables_with_declaration_type.set(name, { scope_variables.get(name).value(), DeclarationType::Var });
+ }
+
+ m_scope_stack.append({ scope_type, scope_node, move(scope_variables_with_declaration_type) });
}
void Interpreter::exit_scope(const ScopeNode& scope_node)
@@ -78,7 +83,10 @@ void Interpreter::declare_variable(String name, DeclarationType declaration_type
for (ssize_t i = m_scope_stack.size() - 1; i >= 0; --i) {
auto& scope = m_scope_stack.at(i);
if (scope.type == ScopeType::Function) {
- scope.variables.set(move(name), js_undefined());
+ if (scope.variables.get(name).has_value() && scope.variables.get(name).value().declaration_type != DeclarationType::Var)
+ ASSERT_NOT_REACHED();
+
+ scope.variables.set(move(name), { js_undefined(), declaration_type });
return;
}
}
@@ -86,7 +94,11 @@ void Interpreter::declare_variable(String name, DeclarationType declaration_type
global_object().put(move(name), js_undefined());
break;
case DeclarationType::Let:
- m_scope_stack.last().variables.set(move(name), js_undefined());
+ case DeclarationType::Const:
+ if (m_scope_stack.last().variables.get(name).has_value() && m_scope_stack.last().variables.get(name).value().declaration_type != DeclarationType::Var)
+ ASSERT_NOT_REACHED();
+
+ m_scope_stack.last().variables.set(move(name), { js_undefined(), declaration_type });
break;
}
}
@@ -95,8 +107,13 @@ void Interpreter::set_variable(String name, Value value)
{
for (ssize_t i = m_scope_stack.size() - 1; i >= 0; --i) {
auto& scope = m_scope_stack.at(i);
- if (scope.variables.contains(name)) {
- scope.variables.set(move(name), move(value));
+
+ auto possible_match = scope.variables.get(name);
+ if (possible_match.has_value()) {
+ if (possible_match.value().declaration_type == DeclarationType::Const)
+ ASSERT_NOT_REACHED();
+
+ scope.variables.set(move(name), { move(value), possible_match.value().declaration_type });
return;
}
}
@@ -110,7 +127,7 @@ Value Interpreter::get_variable(const String& name)
auto& scope = m_scope_stack.at(i);
auto value = scope.variables.get(name);
if (value.has_value())
- return value.value();
+ return value.value().value;
}
return global_object().get(name);
@@ -122,8 +139,8 @@ void Interpreter::collect_roots(Badge<Heap>, HashTable<Cell*>& roots)
for (auto& scope : m_scope_stack) {
for (auto& it : scope.variables) {
- if (it.value.is_cell())
- roots.set(it.value.as_cell());
+ if (it.value.value.is_cell())
+ roots.set(it.value.value.as_cell());
}
}
}
diff --git a/Libraries/LibJS/Interpreter.h b/Libraries/LibJS/Interpreter.h
index 6e590f3a3d2b..39fd4166af32 100644
--- a/Libraries/LibJS/Interpreter.h
+++ b/Libraries/LibJS/Interpreter.h
@@ -30,6 +30,7 @@
#include <AK/Vector.h>
#include <LibJS/Forward.h>
#include <LibJS/Heap.h>
+#include <LibJS/Value.h>
namespace JS {
@@ -38,10 +39,15 @@ enum class ScopeType {
Block,
};
+struct Variable {
+ Value value;
+ DeclarationType declaration_type;
+};
+
struct ScopeFrame {
ScopeType type;
const ScopeNode& scope_node;
- HashMap<String, Value> variables;
+ HashMap<String, Variable> variables;
};
class Interpreter {
diff --git a/Libraries/LibJS/Parser.cpp b/Libraries/LibJS/Parser.cpp
index 3128e44c8de0..fc8fb39d74c1 100644
--- a/Libraries/LibJS/Parser.cpp
+++ b/Libraries/LibJS/Parser.cpp
@@ -66,6 +66,7 @@ NonnullOwnPtr<Statement> Parser::parse_statement()
return parse_return_statement();
case TokenType::Var:
case TokenType::Let:
+ case TokenType::Const:
return parse_variable_declaration();
case TokenType::For:
return parse_for_statement();
@@ -261,6 +262,10 @@ NonnullOwnPtr<VariableDeclaration> Parser::parse_variable_declaration()
declaration_type = DeclarationType::Let;
consume(TokenType::Let);
break;
+ case TokenType::Const:
+ declaration_type = DeclarationType::Const;
+ consume(TokenType::Const);
+ break;
default:
ASSERT_NOT_REACHED();
}
|
583ca6af89c532e2347f494e9192697c6d4d9ca7
|
2024-12-13 17:01:27
|
sideshowbarker
|
libweb: Implement <input type=checkbox switch> experimentally
| false
|
Implement <input type=checkbox switch> experimentally
|
libweb
|
diff --git a/Libraries/LibWeb/CSS/Default.css b/Libraries/LibWeb/CSS/Default.css
index 256e641ff76b..18941f090fdc 100644
--- a/Libraries/LibWeb/CSS/Default.css
+++ b/Libraries/LibWeb/CSS/Default.css
@@ -857,3 +857,38 @@ progress {
filter: invert(100%);
}
}
+
+/* https://github.com/whatwg/html/pull/9546
+ */
+input[type=checkbox][switch] {
+ appearance: none;
+ height: 1em;
+ width: 1.8em;
+ vertical-align: middle;
+ border-radius: 1em;
+ position: relative;
+ overflow: hidden;
+ border-color: transparent;
+ background-color: ButtonFace;
+}
+
+input[type=checkbox][switch]::before {
+ content: '';
+ position: absolute;
+ height: 0;
+ width: 0;
+ border: .46em solid Field;
+ border-radius: 100%;
+ top: 0;
+ bottom: 0;
+ left: 0;
+ margin: auto;
+}
+
+input[type=checkbox][switch]:checked::before {
+ left: calc(100% - .87em);
+}
+
+input[type=checkbox][switch]:checked {
+ background-color: AccentColor;
+}
diff --git a/Libraries/LibWeb/CSS/SelectorEngine.cpp b/Libraries/LibWeb/CSS/SelectorEngine.cpp
index eef6bfc313f6..dbb6f89009c8 100644
--- a/Libraries/LibWeb/CSS/SelectorEngine.cpp
+++ b/Libraries/LibWeb/CSS/SelectorEngine.cpp
@@ -201,7 +201,9 @@ static inline bool matches_indeterminate_pseudo_class(DOM::Element const& elemen
auto const& input_element = static_cast<HTML::HTMLInputElement const&>(element);
switch (input_element.type_state()) {
case HTML::HTMLInputElement::TypeAttributeState::Checkbox:
- return input_element.indeterminate();
+ // https://whatpr.org/html-attr-input-switch/9546/semantics-other.html#selector-indeterminate
+ // input elements whose type attribute is in the Checkbox state, whose switch attribute is not set
+ return input_element.indeterminate() && !element.has_attribute(HTML::AttributeNames::switch_);
default:
return false;
}
diff --git a/Libraries/LibWeb/HTML/AttributeNames.cpp b/Libraries/LibWeb/HTML/AttributeNames.cpp
index 2e73cb25113c..5b0d4b0d06fc 100644
--- a/Libraries/LibWeb/HTML/AttributeNames.cpp
+++ b/Libraries/LibWeb/HTML/AttributeNames.cpp
@@ -28,6 +28,7 @@ void initialize_strings()
for_ = "for"_fly_string;
default_ = "default"_fly_string;
char_ = "char"_fly_string;
+ switch_ = "switch"_fly_string;
// NOTE: Special cases for attributes with dashes in them.
accept_charset = "accept-charset"_fly_string;
@@ -81,6 +82,7 @@ bool is_boolean_attribute(FlyString const& attribute)
|| attribute.equals_ignoring_ascii_case(AttributeNames::reversed)
|| attribute.equals_ignoring_ascii_case(AttributeNames::seeking)
|| attribute.equals_ignoring_ascii_case(AttributeNames::selected)
+ || attribute.equals_ignoring_ascii_case(AttributeNames::switch_)
|| attribute.equals_ignoring_ascii_case(AttributeNames::truespeed)
|| attribute.equals_ignoring_ascii_case(AttributeNames::willvalidate);
}
diff --git a/Libraries/LibWeb/HTML/AttributeNames.h b/Libraries/LibWeb/HTML/AttributeNames.h
index d82b5ddf479b..f8f1a7bf0f9d 100644
--- a/Libraries/LibWeb/HTML/AttributeNames.h
+++ b/Libraries/LibWeb/HTML/AttributeNames.h
@@ -278,6 +278,7 @@ namespace AttributeNames {
__ENUMERATE_HTML_ATTRIBUTE(step) \
__ENUMERATE_HTML_ATTRIBUTE(style) \
__ENUMERATE_HTML_ATTRIBUTE(summary) \
+ __ENUMERATE_HTML_ATTRIBUTE(switch_) \
__ENUMERATE_HTML_ATTRIBUTE(tabindex) \
__ENUMERATE_HTML_ATTRIBUTE(target) \
__ENUMERATE_HTML_ATTRIBUTE(text) \
diff --git a/Libraries/LibWeb/HTML/HTMLInputElement.cpp b/Libraries/LibWeb/HTML/HTMLInputElement.cpp
index c8e9034664eb..25d96221fa77 100644
--- a/Libraries/LibWeb/HTML/HTMLInputElement.cpp
+++ b/Libraries/LibWeb/HTML/HTMLInputElement.cpp
@@ -2343,13 +2343,16 @@ void HTMLInputElement::set_custom_validity(String const& error)
Optional<ARIA::Role> HTMLInputElement::default_role() const
{
+ // http://wpt.live/html-aam/roles-dynamic-switch.tentative.window.html "Disconnected <input type=checkbox switch>"
+ if (!is_connected())
+ return {};
// https://www.w3.org/TR/html-aria/#el-input-button
if (type_state() == TypeAttributeState::Button)
return ARIA::Role::button;
// https://www.w3.org/TR/html-aria/#el-input-checkbox
if (type_state() == TypeAttributeState::Checkbox) {
// https://github.com/w3c/html-aam/issues/496
- if (has_attribute("switch"_string))
+ if (has_attribute(HTML::AttributeNames::switch_))
return ARIA::Role::switch_;
return ARIA::Role::checkbox;
}
diff --git a/Libraries/LibWeb/HTML/HTMLInputElement.idl b/Libraries/LibWeb/HTML/HTMLInputElement.idl
index c2824993ba71..709d16c98d20 100644
--- a/Libraries/LibWeb/HTML/HTMLInputElement.idl
+++ b/Libraries/LibWeb/HTML/HTMLInputElement.idl
@@ -38,6 +38,8 @@ interface HTMLInputElement : HTMLElement {
[CEReactions] attribute unsigned long size;
[CEReactions, Reflect, URL] attribute USVString src;
[CEReactions, Reflect] attribute DOMString step;
+ // https://whatpr.org/html-attr-input-switch/9546/input.html#the-input-element:dom-input-switch
+ [CEReactions, Reflect] attribute boolean switch;
[CEReactions] attribute DOMString type;
[CEReactions, Reflect=value] attribute DOMString defaultValue;
[CEReactions, LegacyNullToEmptyString] attribute DOMString value;
diff --git a/Meta/Lagom/Tools/CodeGenerators/LibWeb/BindingsGenerator/IDLGenerators.cpp b/Meta/Lagom/Tools/CodeGenerators/LibWeb/BindingsGenerator/IDLGenerators.cpp
index 356e559a870c..8b546ca88169 100644
--- a/Meta/Lagom/Tools/CodeGenerators/LibWeb/BindingsGenerator/IDLGenerators.cpp
+++ b/Meta/Lagom/Tools/CodeGenerators/LibWeb/BindingsGenerator/IDLGenerators.cpp
@@ -288,7 +288,7 @@ CppType idl_type_name_to_cpp_type(Type const& type, Interface const& interface)
static ByteString make_input_acceptable_cpp(ByteString const& input)
{
- if (input.is_one_of("class", "template", "for", "default", "char", "namespace", "delete", "inline", "register")) {
+ if (input.is_one_of("class", "template", "for", "default", "char", "namespace", "delete", "inline", "register", "switch")) {
StringBuilder builder;
builder.append(input);
builder.append('_');
diff --git a/Tests/LibWeb/Text/expected/wpt-import/html-aam/roles-dynamic-switch.tentative.window.txt b/Tests/LibWeb/Text/expected/wpt-import/html-aam/roles-dynamic-switch.tentative.window.txt
new file mode 100644
index 000000000000..7325207a8fef
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/wpt-import/html-aam/roles-dynamic-switch.tentative.window.txt
@@ -0,0 +1,11 @@
+Harness status: OK
+
+Found 6 tests
+
+6 Pass
+Pass Disconnected <input type=checkbox switch>
+Pass Connected <input type=checkbox switch>
+Pass Connected <input type=checkbox switch>: adding switch attribute
+Pass Connected <input type=checkbox switch>: removing switch attribute
+Pass Connected <input type=checkbox switch>: removing type attribute
+Pass Connected <input type=checkbox switch>: adding type attribute
\ No newline at end of file
diff --git a/Tests/LibWeb/Text/expected/wpt-import/html/semantics/forms/the-input-element/input-type-checkbox-switch.tentative.window.txt b/Tests/LibWeb/Text/expected/wpt-import/html/semantics/forms/the-input-element/input-type-checkbox-switch.tentative.window.txt
new file mode 100644
index 000000000000..3fd6388f6b9a
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/wpt-import/html/semantics/forms/the-input-element/input-type-checkbox-switch.tentative.window.txt
@@ -0,0 +1,7 @@
+Harness status: OK
+
+Found 2 tests
+
+2 Pass
+Pass switch IDL attribute, setter
+Pass switch IDL attribute, getter
\ No newline at end of file
diff --git a/Tests/LibWeb/Text/expected/wpt-import/html/semantics/selectors/pseudo-classes/input-checkbox-switch.tentative.window.txt b/Tests/LibWeb/Text/expected/wpt-import/html/semantics/selectors/pseudo-classes/input-checkbox-switch.tentative.window.txt
new file mode 100644
index 000000000000..6beb49527147
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/wpt-import/html/semantics/selectors/pseudo-classes/input-checkbox-switch.tentative.window.txt
@@ -0,0 +1,11 @@
+Harness status: OK
+
+Found 6 tests
+
+6 Pass
+Pass Switch control does not match :indeterminate
+Pass Checkbox that is no longer a switch control does match :indeterminate
+Pass Checkbox that becomes a switch control does not match :indeterminate
+Pass Parent of a checkbox that becomes a switch control does not match :has(:indeterminate)
+Pass Parent of a switch control that becomes a checkbox continues to match :has(:checked)
+Pass A switch control that becomes a checkbox in a roundabout way
\ No newline at end of file
diff --git a/Tests/LibWeb/Text/input/wpt-import/html-aam/roles-dynamic-switch.tentative.window.html b/Tests/LibWeb/Text/input/wpt-import/html-aam/roles-dynamic-switch.tentative.window.html
new file mode 100644
index 000000000000..ff6dd4e2fa6b
--- /dev/null
+++ b/Tests/LibWeb/Text/input/wpt-import/html-aam/roles-dynamic-switch.tentative.window.html
@@ -0,0 +1,10 @@
+<!doctype html>
+<meta charset=utf-8>
+
+<script src="../resources/testharness.js"></script>
+<script src="../resources/testharnessreport.js"></script>
+<script src="../resources/testdriver.js"></script>
+<script src="../resources/testdriver-vendor.js"></script>
+<script src="../resources/testdriver-actions.js"></script>
+<div id=log></div>
+<script src="../html-aam/roles-dynamic-switch.tentative.window.js"></script>
diff --git a/Tests/LibWeb/Text/input/wpt-import/html-aam/roles-dynamic-switch.tentative.window.js b/Tests/LibWeb/Text/input/wpt-import/html-aam/roles-dynamic-switch.tentative.window.js
new file mode 100644
index 000000000000..2993c3676485
--- /dev/null
+++ b/Tests/LibWeb/Text/input/wpt-import/html-aam/roles-dynamic-switch.tentative.window.js
@@ -0,0 +1,71 @@
+// META: script=/resources/testdriver.js
+// META: script=/resources/testdriver-vendor.js
+// META: script=/resources/testdriver-actions.js
+
+promise_test(async () => {
+ const control = document.createElement("input");
+ control.type = "checkbox";
+ control.switch = true;
+ const role = await test_driver.get_computed_role(control);
+ assert_equals(role, "");
+}, `Disconnected <input type=checkbox switch>`);
+
+promise_test(async t => {
+ const control = document.createElement("input");
+ t.add_cleanup(() => control.remove());
+ control.type = "checkbox";
+ control.switch = true;
+ document.body.append(control);
+ const role = await test_driver.get_computed_role(control);
+ assert_equals(role, "switch");
+}, `Connected <input type=checkbox switch>`);
+
+promise_test(async t => {
+ const control = document.createElement("input");
+ t.add_cleanup(() => control.remove());
+ control.type = "checkbox";
+ document.body.append(control);
+ let role = await test_driver.get_computed_role(control);
+ assert_equals(role, "checkbox");
+ control.switch = true;
+ role = await test_driver.get_computed_role(control);
+ assert_equals(role, "switch");
+}, `Connected <input type=checkbox switch>: adding switch attribute`);
+
+promise_test(async t => {
+ const control = document.createElement("input");
+ t.add_cleanup(() => control.remove());
+ control.type = "checkbox";
+ control.switch = true;
+ document.body.append(control);
+ let role = await test_driver.get_computed_role(control);
+ assert_equals(role, "switch");
+ control.switch = false;
+ role = await test_driver.get_computed_role(control);
+ assert_equals(role, "checkbox");
+}, `Connected <input type=checkbox switch>: removing switch attribute`);
+
+promise_test(async t => {
+ const control = document.createElement("input");
+ t.add_cleanup(() => control.remove());
+ control.type = "checkbox";
+ document.body.append(control);
+ control.switch = true;
+ let role = await test_driver.get_computed_role(control);
+ assert_equals(role, "switch");
+ control.removeAttribute("type");
+ role = await test_driver.get_computed_role(control);
+ assert_equals(role, "textbox");
+}, `Connected <input type=checkbox switch>: removing type attribute`);
+
+promise_test(async t => {
+ const control = document.createElement("input");
+ t.add_cleanup(() => control.remove());
+ control.switch = true;
+ document.body.append(control);
+ let role = await test_driver.get_computed_role(control);
+ assert_equals(role, "textbox");
+ control.type = "checkbox";
+ role = await test_driver.get_computed_role(control);
+ assert_equals(role, "switch");
+}, `Connected <input type=checkbox switch>: adding type attribute`);
diff --git a/Tests/LibWeb/Text/input/wpt-import/html/semantics/forms/the-input-element/input-type-checkbox-switch.tentative.window.html b/Tests/LibWeb/Text/input/wpt-import/html/semantics/forms/the-input-element/input-type-checkbox-switch.tentative.window.html
new file mode 100644
index 000000000000..6cfe2938d214
--- /dev/null
+++ b/Tests/LibWeb/Text/input/wpt-import/html/semantics/forms/the-input-element/input-type-checkbox-switch.tentative.window.html
@@ -0,0 +1,8 @@
+<!doctype html>
+<meta charset=utf-8>
+
+<script src="../../../../resources/testharness.js"></script>
+<script src="../../../../resources/testharnessreport.js"></script>
+
+<div id=log></div>
+<script src="../../../../html/semantics/forms/the-input-element/input-type-checkbox-switch.tentative.window.js"></script>
diff --git a/Tests/LibWeb/Text/input/wpt-import/html/semantics/forms/the-input-element/input-type-checkbox-switch.tentative.window.js b/Tests/LibWeb/Text/input/wpt-import/html/semantics/forms/the-input-element/input-type-checkbox-switch.tentative.window.js
new file mode 100644
index 000000000000..6128a62a0fb0
--- /dev/null
+++ b/Tests/LibWeb/Text/input/wpt-import/html/semantics/forms/the-input-element/input-type-checkbox-switch.tentative.window.js
@@ -0,0 +1,19 @@
+test(t => {
+ const input = document.createElement("input");
+ input.switch = true;
+
+ assert_true(input.hasAttribute("switch"));
+ assert_equals(input.getAttribute("switch"), "");
+ assert_equals(input.type, "text");
+}, "switch IDL attribute, setter");
+
+test(t => {
+ const container = document.createElement("div");
+ container.innerHTML = "<input type=checkbox switch>";
+ const input = container.firstChild;
+
+ assert_true(input.hasAttribute("switch"));
+ assert_equals(input.getAttribute("switch"), "");
+ assert_equals(input.type, "checkbox");
+ assert_true(input.switch);
+}, "switch IDL attribute, getter");
diff --git a/Tests/LibWeb/Text/input/wpt-import/html/semantics/selectors/pseudo-classes/input-checkbox-switch.tentative.window.html b/Tests/LibWeb/Text/input/wpt-import/html/semantics/selectors/pseudo-classes/input-checkbox-switch.tentative.window.html
new file mode 100644
index 000000000000..25f97e03540f
--- /dev/null
+++ b/Tests/LibWeb/Text/input/wpt-import/html/semantics/selectors/pseudo-classes/input-checkbox-switch.tentative.window.html
@@ -0,0 +1,8 @@
+<!doctype html>
+<meta charset=utf-8>
+
+<script src="../../../../resources/testharness.js"></script>
+<script src="../../../../resources/testharnessreport.js"></script>
+
+<div id=log></div>
+<script src="../../../../html/semantics/selectors/pseudo-classes/input-checkbox-switch.tentative.window.js"></script>
diff --git a/Tests/LibWeb/Text/input/wpt-import/html/semantics/selectors/pseudo-classes/input-checkbox-switch.tentative.window.js b/Tests/LibWeb/Text/input/wpt-import/html/semantics/selectors/pseudo-classes/input-checkbox-switch.tentative.window.js
new file mode 100644
index 000000000000..b5d9898a640e
--- /dev/null
+++ b/Tests/LibWeb/Text/input/wpt-import/html/semantics/selectors/pseudo-classes/input-checkbox-switch.tentative.window.js
@@ -0,0 +1,75 @@
+test(t => {
+ const input = document.body.appendChild(document.createElement("input"));
+ t.add_cleanup(() => input.remove());
+ input.type = "checkbox";
+ input.switch = true;
+ input.indeterminate = true;
+
+ assert_false(input.matches(":indeterminate"));
+}, "Switch control does not match :indeterminate");
+
+test(t => {
+ const input = document.body.appendChild(document.createElement("input"));
+ t.add_cleanup(() => input.remove());
+ input.type = "checkbox";
+ input.switch = true;
+ input.indeterminate = true;
+
+ assert_false(input.matches(":indeterminate"));
+
+ input.switch = false;
+ assert_true(input.matches(":indeterminate"));
+}, "Checkbox that is no longer a switch control does match :indeterminate");
+
+test(t => {
+ const input = document.body.appendChild(document.createElement("input"));
+ t.add_cleanup(() => input.remove());
+ input.type = "checkbox";
+ input.indeterminate = true;
+
+ assert_true(input.matches(":indeterminate"));
+
+ input.setAttribute("switch", "blah");
+ assert_false(input.matches(":indeterminate"));
+}, "Checkbox that becomes a switch control does not match :indeterminate");
+
+test(t => {
+ const input = document.body.appendChild(document.createElement("input"));
+ t.add_cleanup(() => input.remove());
+ input.type = "checkbox";
+ input.indeterminate = true;
+
+ assert_true(document.body.matches(":has(:indeterminate)"));
+
+ input.switch = true;
+ assert_false(document.body.matches(":has(:indeterminate)"));
+}, "Parent of a checkbox that becomes a switch control does not match :has(:indeterminate)");
+
+test(t => {
+ const input = document.body.appendChild(document.createElement("input"));
+ t.add_cleanup(() => input.remove());
+ input.type = "checkbox";
+ input.switch = true
+ input.checked = true;
+
+ assert_true(document.body.matches(":has(:checked)"));
+
+ input.switch = false;
+ assert_true(document.body.matches(":has(:checked)"));
+
+ input.checked = false;
+ assert_false(document.body.matches(":has(:checked)"));
+}, "Parent of a switch control that becomes a checkbox continues to match :has(:checked)");
+
+test(t => {
+ const input = document.body.appendChild(document.createElement("input"));
+ t.add_cleanup(() => input.remove());
+ input.type = "checkbox";
+ input.switch = true;
+ input.indeterminate = true;
+ assert_false(input.matches(":indeterminate"));
+ input.type = "text";
+ input.removeAttribute("switch");
+ input.type = "checkbox";
+ assert_true(input.matches(":indeterminate"));
+}, "A switch control that becomes a checkbox in a roundabout way");
|
91f25c8f91a6ced1f340a290488802991906d18e
|
2020-07-21 22:38:01
|
Andreas Kling
|
build: Build with minimal debug info (-g1)
| false
|
Build with minimal debug info (-g1)
|
build
|
diff --git a/CMakeLists.txt b/CMakeLists.txt
index 8301d495d4fc..e2e485f3f5e0 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -144,7 +144,7 @@ set(CMAKE_SHARED_LIBRARY_CREATE_CXX_FLAGS "-shared")
#FIXME: -fstack-protector
-set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Os -Wno-sized-deallocation -fno-sized-deallocation -fno-exceptions -fno-rtti -Wno-address-of-packed-member -Wundef -Wcast-qual -Wwrite-strings -Wimplicit-fallthrough -Wno-nonnull-compare -Wno-deprecated-copy -Wno-expansion-to-defined")
+set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Os -g1 -Wno-sized-deallocation -fno-sized-deallocation -fno-exceptions -fno-rtti -Wno-address-of-packed-member -Wundef -Wcast-qual -Wwrite-strings -Wimplicit-fallthrough -Wno-nonnull-compare -Wno-deprecated-copy -Wno-expansion-to-defined")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -DDEBUG -DSANITIZE_PTRS")
add_link_options(--sysroot ${CMAKE_BINARY_DIR}/Root)
|
2e370fa4d5d3cadd58182be18b9aeb59e32ef58e
|
2019-01-27 02:28:43
|
Andreas Kling
|
libgui: Don't consider a GWidget focused if the window is inactive.
| false
|
Don't consider a GWidget focused if the window is inactive.
|
libgui
|
diff --git a/LibGUI/GEventLoop.cpp b/LibGUI/GEventLoop.cpp
index 96806f8559b1..40e64cd969ab 100644
--- a/LibGUI/GEventLoop.cpp
+++ b/LibGUI/GEventLoop.cpp
@@ -86,6 +86,14 @@ void GEventLoop::handle_paint_event(const GUI_Event& event, GWindow& window)
post_event(&window, make<GPaintEvent>(event.paint.rect));
}
+void GEventLoop::handle_window_activation_event(const GUI_Event& event, GWindow& window)
+{
+#ifdef GEVENTLOOP_DEBUG
+ dbgprintf("WID=%x WindowActivation\n", event.window_id);
+#endif
+ post_event(&window, make<GEvent>(event.type == GUI_Event::Type::WindowActivated ? GEvent::WindowBecameActive : GEvent::WindowBecameInactive));
+}
+
void GEventLoop::handle_key_event(const GUI_Event& event, GWindow& window)
{
#ifdef GEVENTLOOP_DEBUG
@@ -162,10 +170,8 @@ void GEventLoop::wait_for_event()
handle_mouse_event(event, *window);
break;
case GUI_Event::Type::WindowActivated:
- dbgprintf("WID=%x WindowActivated\n", event.window_id);
- break;
case GUI_Event::Type::WindowDeactivated:
- dbgprintf("WID=%x WindowDeactivated\n", event.window_id);
+ handle_window_activation_event(event, *window);
break;
case GUI_Event::Type::KeyDown:
case GUI_Event::Type::KeyUp:
diff --git a/LibGUI/GEventLoop.h b/LibGUI/GEventLoop.h
index b7150935c41e..d040c369007c 100644
--- a/LibGUI/GEventLoop.h
+++ b/LibGUI/GEventLoop.h
@@ -28,6 +28,7 @@ class GEventLoop {
void handle_paint_event(const GUI_Event&, GWindow&);
void handle_mouse_event(const GUI_Event&, GWindow&);
void handle_key_event(const GUI_Event&, GWindow&);
+ void handle_window_activation_event(const GUI_Event&, GWindow&);
struct QueuedEvent {
GObject* receiver { nullptr };
diff --git a/LibGUI/GWidget.cpp b/LibGUI/GWidget.cpp
index a650510ecadb..e2b77e33ecb5 100644
--- a/LibGUI/GWidget.cpp
+++ b/LibGUI/GWidget.cpp
@@ -145,6 +145,8 @@ bool GWidget::is_focused() const
auto* win = window();
if (!win)
return false;
+ if (!win->is_active())
+ return false;
return win->focused_widget() == this;
}
diff --git a/LibGUI/GWindow.cpp b/LibGUI/GWindow.cpp
index 41f086b15d3d..b6de4a75113c 100644
--- a/LibGUI/GWindow.cpp
+++ b/LibGUI/GWindow.cpp
@@ -81,6 +81,7 @@ void GWindow::event(GEvent& event)
ASSERT(result.widget);
return result.widget->event(*local_event);
}
+ return;
}
if (event.is_paint_event()) {
@@ -94,6 +95,7 @@ void GWindow::event(GEvent& event)
GUI_Rect gui_rect = rect;
int rc = gui_notify_paint_finished(m_window_id, &gui_rect);
ASSERT(rc == 0);
+ return;
}
if (event.is_key_event()) {
@@ -102,7 +104,14 @@ void GWindow::event(GEvent& event)
return m_focused_widget->event(event);
}
- return GObject::event(event);
+ if (event.type() == GEvent::WindowBecameActive || event.type() == GEvent::WindowBecameInactive) {
+ m_is_active = event.type() == GEvent::WindowBecameActive;
+ if (m_focused_widget)
+ m_focused_widget->update();
+ return;
+ }
+
+ GObject::event(event);
}
bool GWindow::is_visible() const
diff --git a/LibGUI/GWindow.h b/LibGUI/GWindow.h
index 12ade852b528..a958207f0810 100644
--- a/LibGUI/GWindow.h
+++ b/LibGUI/GWindow.h
@@ -32,6 +32,7 @@ class GWindow final : public GObject {
virtual void event(GEvent&) override;
bool is_visible() const;
+ bool is_active() const { return m_is_active; }
void close();
@@ -39,7 +40,6 @@ class GWindow final : public GObject {
const GWidget* main_widget() const { return m_main_widget; }
void set_main_widget(GWidget*);
-
GWidget* focused_widget() { return m_focused_widget; }
const GWidget* focused_widget() const { return m_focused_widget; }
void set_focused_widget(GWidget*);
@@ -51,6 +51,7 @@ class GWindow final : public GObject {
private:
RetainPtr<GraphicsBitmap> m_backing;
int m_window_id { -1 };
+ bool m_is_active { false };
GWidget* m_main_widget { nullptr };
GWidget* m_focused_widget { nullptr };
};
|
897471c8527ea14f693da2a95e5e9df4e54207be
|
2021-11-02 15:39:05
|
Linus Groh
|
meta: Don't check for toolchain if serenity.sh target is lagom
| false
|
Don't check for toolchain if serenity.sh target is lagom
|
meta
|
diff --git a/Meta/serenity.sh b/Meta/serenity.sh
index 84318a34ca23..c4b07c2fa9f6 100755
--- a/Meta/serenity.sh
+++ b/Meta/serenity.sh
@@ -88,21 +88,26 @@ else
TARGET="${SERENITY_ARCH:-"i686"}"
fi
-case "$1" in
- GNU|Clang)
- TOOLCHAIN_TYPE="$1"; shift
- ;;
- *)
- if [ -n "$1" ]; then
- echo "WARNING: unknown toolchain '$1'. Defaulting to GNU."
- echo " Valid values are 'Clang', 'GNU' (default)"
- fi
- TOOLCHAIN_TYPE="GNU"
- ;;
-esac
+CMAKE_ARGS=()
+
+# Toolchain selection only applies to non-lagom targets.
+if [ "$TARGET" != "lagom" ]; then
+ case "$1" in
+ GNU|Clang)
+ TOOLCHAIN_TYPE="$1"; shift
+ ;;
+ *)
+ if [ -n "$1" ]; then
+ echo "WARNING: unknown toolchain '$1'. Defaulting to GNU."
+ echo " Valid values are 'Clang', 'GNU' (default)"
+ fi
+ TOOLCHAIN_TYPE="GNU"
+ ;;
+ esac
+ CMAKE_ARGS+=( "-DSERENITY_TOOLCHAIN=$TOOLCHAIN_TYPE" )
+fi
CMD_ARGS=( "$@" )
-CMAKE_ARGS=( "-DSERENITY_TOOLCHAIN=$TOOLCHAIN_TYPE" )
get_top_dir() {
git rev-parse --show-toplevel
|
d95e50643e676ea3c2fbd09198a6a770ccaab83c
|
2021-12-05 20:01:03
|
Sam Atkins
|
libgui: Cast unused smart-pointer return values to void
| false
|
Cast unused smart-pointer return values to void
|
libgui
|
diff --git a/Userland/Libraries/LibGUI/SettingsWindow.cpp b/Userland/Libraries/LibGUI/SettingsWindow.cpp
index 3beb028c6183..1a74d2c00dfa 100644
--- a/Userland/Libraries/LibGUI/SettingsWindow.cpp
+++ b/Userland/Libraries/LibGUI/SettingsWindow.cpp
@@ -26,7 +26,7 @@ ErrorOr<NonnullRefPtr<SettingsWindow>> SettingsWindow::create(String title, Show
auto main_widget = TRY(window->try_set_main_widget<GUI::Widget>());
main_widget->set_fill_with_background_color(true);
- TRY(main_widget->try_set_layout<GUI::VerticalBoxLayout>());
+ (void)TRY(main_widget->try_set_layout<GUI::VerticalBoxLayout>());
main_widget->layout()->set_margins(4);
main_widget->layout()->set_spacing(6);
@@ -34,7 +34,7 @@ ErrorOr<NonnullRefPtr<SettingsWindow>> SettingsWindow::create(String title, Show
auto button_container = TRY(main_widget->try_add<GUI::Widget>());
button_container->set_shrink_to_fit(true);
- TRY(button_container->try_set_layout<GUI::HorizontalBoxLayout>());
+ (void)TRY(button_container->try_set_layout<GUI::HorizontalBoxLayout>());
button_container->layout()->set_spacing(6);
if (show_defaults_button == ShowDefaultsButton::Yes) {
diff --git a/Userland/Libraries/LibGUI/TextDocument.cpp b/Userland/Libraries/LibGUI/TextDocument.cpp
index aaed29702c89..7982b06d291d 100644
--- a/Userland/Libraries/LibGUI/TextDocument.cpp
+++ b/Userland/Libraries/LibGUI/TextDocument.cpp
@@ -85,7 +85,7 @@ bool TextDocument::set_text(StringView text, AllowCallback allow_callback)
// Don't show the file's trailing newline as an actual new line.
if (line_count() > 1 && line(line_count() - 1).is_empty())
- m_lines.take_last();
+ (void)m_lines.take_last();
m_client_notifications_enabled = true;
diff --git a/Userland/Libraries/LibGUI/Toolbar.cpp b/Userland/Libraries/LibGUI/Toolbar.cpp
index ec2aab974112..b87d172a3d07 100644
--- a/Userland/Libraries/LibGUI/Toolbar.cpp
+++ b/Userland/Libraries/LibGUI/Toolbar.cpp
@@ -118,7 +118,7 @@ ErrorOr<void> Toolbar::try_add_separator()
auto item = TRY(adopt_nonnull_own_or_enomem(new (nothrow) Item));
item->type = Item::Type::Separator;
- TRY(try_add<SeparatorWidget>(m_orientation == Gfx::Orientation::Horizontal ? Gfx::Orientation::Vertical : Gfx::Orientation::Horizontal));
+ (void)TRY(try_add<SeparatorWidget>(m_orientation == Gfx::Orientation::Horizontal ? Gfx::Orientation::Vertical : Gfx::Orientation::Horizontal));
m_items.unchecked_append(move(item));
return {};
}
diff --git a/Userland/Libraries/LibGUI/UndoStack.cpp b/Userland/Libraries/LibGUI/UndoStack.cpp
index 11585e362d46..9ca07e0f57de 100644
--- a/Userland/Libraries/LibGUI/UndoStack.cpp
+++ b/Userland/Libraries/LibGUI/UndoStack.cpp
@@ -57,7 +57,7 @@ void UndoStack::push(NonnullOwnPtr<Command> command)
{
// If the stack cursor is behind the top of the stack, nuke everything from here to the top.
while (m_stack.size() != m_stack_index)
- m_stack.take_last();
+ (void)m_stack.take_last();
if (m_clean_index.has_value() && m_clean_index.value() > m_stack.size())
m_clean_index = {};
|
53d73b95ce571023ac93ae231f679f3fa0267f4d
|
2023-11-01 17:35:57
|
david072
|
hackstudio: Also ask about unsaved changes when running
| false
|
Also ask about unsaved changes when running
|
hackstudio
|
diff --git a/Userland/DevTools/HackStudio/HackStudioWidget.cpp b/Userland/DevTools/HackStudio/HackStudioWidget.cpp
index d0b70fa481c9..1318f63e9b40 100644
--- a/Userland/DevTools/HackStudio/HackStudioWidget.cpp
+++ b/Userland/DevTools/HackStudio/HackStudioWidget.cpp
@@ -1323,6 +1323,9 @@ ErrorOr<NonnullRefPtr<GUI::Action>> HackStudioWidget::create_run_action()
{
auto icon = TRY(Gfx::Bitmap::load_from_file("/res/icons/16x16/program-run.png"sv));
return GUI::Action::create("&Run", { Mod_Ctrl, Key_R }, icon, [this](auto&) {
+ if (warn_unsaved_changes("There are unsaved changes, do you want to save before running?") == ContinueDecision::No)
+ return;
+
reveal_action_tab(*m_terminal_wrapper);
run();
});
|
1b94b4c593e5a0600d18f448c019a9a8b3533340
|
2022-04-09 21:57:24
|
Igor Pissolati
|
libweb: Bring MouseEvent a bit closer to spec
| false
|
Bring MouseEvent a bit closer to spec
|
libweb
|
diff --git a/Userland/Libraries/LibWeb/DOM/Document.cpp b/Userland/Libraries/LibWeb/DOM/Document.cpp
index d91d6c1e4452..c5804f59e3a2 100644
--- a/Userland/Libraries/LibWeb/DOM/Document.cpp
+++ b/Userland/Libraries/LibWeb/DOM/Document.cpp
@@ -980,7 +980,7 @@ NonnullRefPtr<Event> Document::create_event(String const& interface)
} else if (interface_lowercase == "messageevent") {
event = HTML::MessageEvent::create("");
} else if (interface_lowercase.is_one_of("mouseevent", "mouseevents")) {
- event = UIEvents::MouseEvent::create("", 0, 0, 0, 0);
+ event = UIEvents::MouseEvent::create("");
} else if (interface_lowercase == "storageevent") {
event = Event::create(""); // FIXME: Create StorageEvent
} else if (interface_lowercase == "svgevents") {
diff --git a/Userland/Libraries/LibWeb/HTML/HTMLElement.cpp b/Userland/Libraries/LibWeb/HTML/HTMLElement.cpp
index 748d85fc5edb..73de1cd369a5 100644
--- a/Userland/Libraries/LibWeb/HTML/HTMLElement.cpp
+++ b/Userland/Libraries/LibWeb/HTML/HTMLElement.cpp
@@ -395,7 +395,7 @@ bool HTMLElement::fire_a_synthetic_pointer_event(FlyString const& type, DOM::Ele
// 1. Let event be the result of creating an event using PointerEvent.
// 2. Initialize event's type attribute to e.
// FIXME: Actually create a PointerEvent!
- auto event = UIEvents::MouseEvent::create(type, 0.0, 0.0, 0.0, 0.0);
+ auto event = UIEvents::MouseEvent::create(type);
// 3. Initialize event's bubbles and cancelable attributes to true.
event->set_bubbles(true);
diff --git a/Userland/Libraries/LibWeb/Page/EventHandler.cpp b/Userland/Libraries/LibWeb/Page/EventHandler.cpp
index 90eed4facaa4..24166b3fb0c8 100644
--- a/Userland/Libraries/LibWeb/Page/EventHandler.cpp
+++ b/Userland/Libraries/LibWeb/Page/EventHandler.cpp
@@ -191,12 +191,12 @@ bool EventHandler::handle_mouseup(Gfx::IntPoint const& position, unsigned button
return false;
}
auto offset = compute_mouse_event_offset(position, paintable->layout_node());
- node->dispatch_event(UIEvents::MouseEvent::create(UIEvents::EventNames::mouseup, offset.x(), offset.y(), position.x(), position.y()));
+ node->dispatch_event(UIEvents::MouseEvent::create_from_platform_event(UIEvents::EventNames::mouseup, offset.x(), offset.y(), position.x(), position.y(), button));
handled_event = true;
bool run_activation_behavior = true;
if (node.ptr() == m_mousedown_target && button == GUI::MouseButton::Primary) {
- run_activation_behavior = node->dispatch_event(UIEvents::MouseEvent::create(UIEvents::EventNames::click, offset.x(), offset.y(), position.x(), position.y()));
+ run_activation_behavior = node->dispatch_event(UIEvents::MouseEvent::create_from_platform_event(UIEvents::EventNames::click, offset.x(), offset.y(), position.x(), position.y(), button));
}
if (run_activation_behavior) {
@@ -308,7 +308,7 @@ bool EventHandler::handle_mousedown(Gfx::IntPoint const& position, unsigned butt
m_mousedown_target = node;
auto offset = compute_mouse_event_offset(position, paintable->layout_node());
- node->dispatch_event(UIEvents::MouseEvent::create(UIEvents::EventNames::mousedown, offset.x(), offset.y(), position.x(), position.y()));
+ node->dispatch_event(UIEvents::MouseEvent::create_from_platform_event(UIEvents::EventNames::mousedown, offset.x(), offset.y(), position.x(), position.y(), button));
}
// NOTE: Dispatching an event may have disturbed the world.
@@ -416,7 +416,7 @@ bool EventHandler::handle_mousemove(Gfx::IntPoint const& position, unsigned butt
}
auto offset = compute_mouse_event_offset(position, paintable->layout_node());
- node->dispatch_event(UIEvents::MouseEvent::create(UIEvents::EventNames::mousemove, offset.x(), offset.y(), position.x(), position.y()));
+ node->dispatch_event(UIEvents::MouseEvent::create_from_platform_event(UIEvents::EventNames::mousemove, offset.x(), offset.y(), position.x(), position.y()));
// NOTE: Dispatching an event may have disturbed the world.
if (!paint_root() || paint_root() != node->document().paint_box())
return true;
diff --git a/Userland/Libraries/LibWeb/UIEvents/MouseEvent.cpp b/Userland/Libraries/LibWeb/UIEvents/MouseEvent.cpp
index 96bad7de8fb3..89c4c5225f15 100644
--- a/Userland/Libraries/LibWeb/UIEvents/MouseEvent.cpp
+++ b/Userland/Libraries/LibWeb/UIEvents/MouseEvent.cpp
@@ -4,23 +4,53 @@
* SPDX-License-Identifier: BSD-2-Clause
*/
+#include <LibGUI/Event.h>
#include <LibWeb/HTML/EventNames.h>
#include <LibWeb/UIEvents/EventNames.h>
#include <LibWeb/UIEvents/MouseEvent.h>
namespace Web::UIEvents {
-MouseEvent::MouseEvent(FlyString const& event_name, double offset_x, double offset_y, double client_x, double client_y)
- : UIEvent(event_name)
- , m_offset_x(offset_x)
- , m_offset_y(offset_y)
- , m_client_x(client_x)
- , m_client_y(client_y)
+MouseEvent::MouseEvent(FlyString const& event_name, MouseEventInit const& event_init)
+ : UIEvent(event_name, event_init)
+ , m_offset_x(event_init.offset_x)
+ , m_offset_y(event_init.offset_y)
+ , m_client_x(event_init.client_x)
+ , m_client_y(event_init.client_y)
+ , m_button(event_init.button)
{
set_event_characteristics();
}
-MouseEvent::~MouseEvent() = default;
+// https://www.w3.org/TR/uievents/#dom-mouseevent-button
+static i16 determine_button(unsigned mouse_button)
+{
+ switch (mouse_button) {
+ case GUI::MouseButton::Primary:
+ return 0;
+ case GUI::MouseButton::Middle:
+ return 1;
+ case GUI::MouseButton::Secondary:
+ return 2;
+ case GUI::MouseButton::Backward:
+ return 3;
+ case GUI::MouseButton::Forward:
+ return 4;
+ default:
+ VERIFY_NOT_REACHED();
+ }
+}
+
+NonnullRefPtr<MouseEvent> MouseEvent::create_from_platform_event(FlyString const& event_name, double offset_x, double offset_y, double client_x, double client_y, unsigned mouse_button)
+{
+ MouseEventInit event_init {};
+ event_init.offset_x = offset_x;
+ event_init.offset_y = offset_y;
+ event_init.client_x = client_x;
+ event_init.client_y = client_y;
+ event_init.button = determine_button(mouse_button);
+ return MouseEvent::create(event_name, event_init);
+}
void MouseEvent::set_event_characteristics()
{
diff --git a/Userland/Libraries/LibWeb/UIEvents/MouseEvent.h b/Userland/Libraries/LibWeb/UIEvents/MouseEvent.h
index 99c2df94f233..53186672838b 100644
--- a/Userland/Libraries/LibWeb/UIEvents/MouseEvent.h
+++ b/Userland/Libraries/LibWeb/UIEvents/MouseEvent.h
@@ -12,16 +12,27 @@
namespace Web::UIEvents {
+struct MouseEventInit : public EventModifierInit {
+ double offset_x = 0;
+ double offset_y = 0;
+ double client_x = 0;
+ double client_y = 0;
+
+ i16 button = 0;
+};
+
class MouseEvent final : public UIEvent {
public:
using WrapperType = Bindings::MouseEventWrapper;
- static NonnullRefPtr<MouseEvent> create(FlyString const& event_name, double offset_x, double offset_y, double client_x, double client_y)
+ static NonnullRefPtr<MouseEvent> create(FlyString const& event_name, MouseEventInit const& event_init = {})
{
- return adopt_ref(*new MouseEvent(event_name, offset_x, offset_y, client_x, client_y));
+ return adopt_ref(*new MouseEvent(event_name, event_init));
}
- virtual ~MouseEvent() override;
+ static NonnullRefPtr<MouseEvent> create_from_platform_event(FlyString const& event_name, double offset_x, double offset_y, double client_x, double client_y, unsigned mouse_button = 1);
+
+ virtual ~MouseEvent() override = default;
double offset_x() const { return m_offset_x; }
double offset_y() const { return m_offset_y; }
@@ -32,16 +43,18 @@ class MouseEvent final : public UIEvent {
double x() const { return client_x(); }
double y() const { return client_y(); }
-protected:
- MouseEvent(FlyString const& event_name, double offset_x, double offset_y, double client_x, double client_y);
+ i16 button() const { return m_button; }
private:
+ MouseEvent(FlyString const& event_name, MouseEventInit const& event_init);
+
void set_event_characteristics();
double m_offset_x { 0 };
double m_offset_y { 0 };
double m_client_x { 0 };
double m_client_y { 0 };
+ i16 m_button { 0 };
};
}
diff --git a/Userland/Libraries/LibWeb/UIEvents/MouseEvent.idl b/Userland/Libraries/LibWeb/UIEvents/MouseEvent.idl
index 972c3a54760f..330b65b898fd 100644
--- a/Userland/Libraries/LibWeb/UIEvents/MouseEvent.idl
+++ b/Userland/Libraries/LibWeb/UIEvents/MouseEvent.idl
@@ -7,4 +7,18 @@ interface MouseEvent : UIEvent {
readonly attribute double x;
readonly attribute double y;
+ readonly attribute short button;
+
};
+
+dictionary MouseEventInit : EventModifierInit {
+
+ // FIXME: offsetX and offsetY shouldn't be here.
+ double offsetX = 0;
+ double offsetY = 0;
+ double clientX = 0;
+ double clientY = 0;
+
+ short button = 0;
+
+};
\ No newline at end of file
|
bf2e6325a43947d36a2c55c314453dcc102fc8cd
|
2020-05-22 01:23:17
|
FalseHonesty
|
libgui: Add hook when a context menu is requested on a tab
| false
|
Add hook when a context menu is requested on a tab
|
libgui
|
diff --git a/Libraries/LibGUI/TabWidget.cpp b/Libraries/LibGUI/TabWidget.cpp
index e4d3fbb7996b..baf3799c6ac4 100644
--- a/Libraries/LibGUI/TabWidget.cpp
+++ b/Libraries/LibGUI/TabWidget.cpp
@@ -370,4 +370,19 @@ void TabWidget::keydown_event(KeyEvent& event)
Widget::keydown_event(event);
}
+void TabWidget::context_menu_event(ContextMenuEvent& context_menu_event)
+{
+ for (size_t i = 0; i < m_tabs.size(); ++i) {
+ auto button_rect = this->button_rect(i);
+ if (!button_rect.contains(context_menu_event.position()))
+ continue;
+ auto* widget = m_tabs[i].widget;
+ deferred_invoke([this, widget, context_menu_event](auto&) {
+ if (on_context_menu_request && widget)
+ on_context_menu_request(*widget, context_menu_event);
+ });
+ return;
+ }
+}
+
}
diff --git a/Libraries/LibGUI/TabWidget.h b/Libraries/LibGUI/TabWidget.h
index d2ebd063ea2a..3c49acfa5df3 100644
--- a/Libraries/LibGUI/TabWidget.h
+++ b/Libraries/LibGUI/TabWidget.h
@@ -84,6 +84,7 @@ class TabWidget : public Widget {
Function<void(Widget&)> on_change;
Function<void(Widget&)> on_middle_click;
+ Function<void(Widget&, const ContextMenuEvent&)> on_context_menu_request;
protected:
TabWidget();
@@ -95,6 +96,7 @@ class TabWidget : public Widget {
virtual void mousemove_event(MouseEvent&) override;
virtual void leave_event(Core::Event&) override;
virtual void keydown_event(KeyEvent&) override;
+ virtual void context_menu_event(ContextMenuEvent&) override;
private:
Gfx::Rect child_rect_for_size(const Gfx::Size&) const;
|
1bcbc3f827ede8e0e701b44b582e830a6a673c9a
|
2019-10-27 17:40:37
|
Andreas Kling
|
hackstudio: Allow switching between the two editors with Ctrl+E :^)
| false
|
Allow switching between the two editors with Ctrl+E :^)
|
hackstudio
|
diff --git a/DevTools/HackStudio/main.cpp b/DevTools/HackStudio/main.cpp
index 54696cc157f3..dd306fa2280c 100644
--- a/DevTools/HackStudio/main.cpp
+++ b/DevTools/HackStudio/main.cpp
@@ -27,6 +27,7 @@
#include <stdio.h>
#include <unistd.h>
+NonnullRefPtrVector<EditorWrapper> g_all_editor_wrappers;
RefPtr<EditorWrapper> g_current_editor_wrapper;
String g_currently_open_file;
@@ -38,6 +39,7 @@ void add_new_editor(GWidget& parent)
{
auto wrapper = EditorWrapper::construct(&parent);
g_current_editor_wrapper = wrapper;
+ g_all_editor_wrappers.append(wrapper);
}
EditorWrapper& current_editor_wrapper()
@@ -120,6 +122,18 @@ int main(int argc, char** argv)
open_file(filename);
});
+ auto switch_to_next_editor = GAction::create("Switch to next editor", { Mod_Ctrl, Key_E }, [&](auto&) {
+ if (g_all_editor_wrappers.size() <= 1)
+ return;
+ // FIXME: This will only work correctly when there are 2 editors. Make it work for any editor count.
+ for (auto& wrapper : g_all_editor_wrappers) {
+ if (&wrapper == ¤t_editor_wrapper())
+ continue;
+ wrapper.editor().set_focus(true);
+ return;
+ }
+ });
+
auto save_action = GAction::create("Save", { Mod_Ctrl, Key_S }, GraphicsBitmap::load_from_file("/res/icons/16x16/save.png"), [&](auto&) {
if (g_currently_open_file.is_empty())
return;
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.