Skip to main content

runec/ide/
colors.rs

1use super::fields::Value;
2use super::{
3    Color, DocumentColor, Index, Location, Symbol, SymbolKind, TextEdit, TokenKind, config, index,
4};
5use crate::project::{Document, Project, SourceId};
6use crate::symbol::SymbolKind as RegistryKind;
7use crate::token::Kind;
8use crate::types::Type;
9use std::ops::Range;
10
11mod extra;
12
13#[derive(Clone, Copy, Debug, PartialEq, Eq)]
14pub(super) enum Encoding {
15    Rgb,
16    Argb,
17    Rgb15,
18    Hsl,
19    Hsl32,
20    Gray12,
21}
22
23struct Swatch {
24    range: Range<usize>,
25    color: Color,
26    encoding: Encoding,
27    value: u32,
28    editable: bool,
29    tag: bool,
30}
31
32impl Project {
33    pub fn document_colors(&self, source: SourceId) -> Vec<DocumentColor> {
34        self.color_swatches(source)
35            .into_iter()
36            .map(|swatch| DocumentColor {
37                range: swatch.range,
38                color: swatch.color,
39            })
40            .collect()
41    }
42
43    pub fn color_presentation(
44        &self,
45        source: SourceId,
46        range: Range<usize>,
47        color: Color,
48    ) -> Option<TextEdit> {
49        if [color.red, color.green, color.blue, color.alpha]
50            .iter()
51            .any(|value| !value.is_finite() || !(0.0..=1.0).contains(value))
52        {
53            return None;
54        }
55        let swatch = self
56            .color_swatches(source)
57            .into_iter()
58            .find(|swatch| swatch.range == range && swatch.editable)?;
59        let document = self.document(source)?;
60        let original = &document.text[range.clone()];
61        let key = document.text[..range.start]
62            .rsplit('\n')
63            .next()
64            .and_then(|line| line.split_once('='))
65            .map(|(key, _)| key.trim());
66        let signed = matches!(
67            (document.config.as_deref(), key),
68            (Some("particleemitter"), Some("rgba" | "rgbatarget"))
69                | (Some("npc"), Some("spotshadowcolour"))
70        );
71        let value = if color == swatch.color {
72            swatch.value
73        } else {
74            swatch.encoding.encode(color)
75        };
76        let value = if swatch.encoding == Encoding::Rgb {
77            value | swatch.value & 0xff000000
78        } else {
79            value
80        };
81        let replacement = if color == swatch.color {
82            original.to_string()
83        } else if swatch.tag || original.starts_with("0x") || original.starts_with("0X") {
84            let (prefix, digits) = if swatch.tag {
85                ("", original)
86            } else {
87                original.split_at(2)
88            };
89            let width = digits.bytes().filter(|byte| *byte != b'_').count();
90            if digits.bytes().any(|byte| byte.is_ascii_uppercase()) {
91                format!("{prefix}{value:0width$X}")
92            } else {
93                format!("{prefix}{value:0width$x}")
94            }
95        } else if original.starts_with('-') || signed {
96            if swatch.encoding == Encoding::Hsl {
97                (value as i16).to_string()
98            } else {
99                (value as i32).to_string()
100            }
101        } else {
102            value.to_string()
103        };
104        Some(TextEdit {
105            location: Location { source, range },
106            replacement,
107        })
108    }
109
110    fn color_swatches(&self, source: SourceId) -> Vec<Swatch> {
111        let Some(document) = self.document(source) else {
112            return Vec::new();
113        };
114        let mut scan = Scan {
115            project: self,
116            document,
117            index: self.symbol_index(),
118            out: Vec::new(),
119        };
120        if document.config.is_some() {
121            scan.config();
122        } else {
123            scan.script();
124        }
125        scan.out
126            .sort_by_key(|swatch| (swatch.range.start, swatch.range.end));
127        scan.out.dedup_by(|a, b| a.range == b.range);
128        scan.out
129    }
130}
131
132struct Scan<'a> {
133    project: &'a Project,
134    document: &'a Document,
135    index: &'a Index,
136    out: Vec<Swatch>,
137}
138
139impl Scan<'_> {
140    fn hex(&mut self, range: Range<usize>, encoding: Encoding) {
141        let Ok(value) = u32::from_str_radix(&self.document.text[range.clone()], 16) else {
142            return;
143        };
144        self.out.push(Swatch {
145            range,
146            color: encoding.decode(value),
147            encoding,
148            value,
149            editable: true,
150            tag: true,
151        });
152    }
153
154    fn value(&mut self, range: Range<usize>, encoding: Encoding) {
155        let text = &self.document.text[range.clone()];
156        let start = range.start + text.len() - text.trim_start().len();
157        let range = start..start + text.trim().len();
158        let text = &self.document.text[range.clone()];
159        let editable = !text.starts_with('^');
160        let Some(value) = self.resolve(text, 0) else {
161            return;
162        };
163        if matches!(encoding, Encoding::Rgb15) && value > 0x7fff
164            || encoding == Encoding::Hsl
165                && value > 0xffff
166                && !(i16::MIN as i32..=-1).contains(&(value as i32))
167        {
168            return;
169        }
170        self.out.push(Swatch {
171            range,
172            color: encoding.decode(value),
173            encoding,
174            value,
175            editable,
176            tag: false,
177        });
178    }
179
180    fn resolve(&self, text: &str, depth: usize) -> Option<u32> {
181        if depth > 16 {
182            return None;
183        }
184        if let Some(name) = text.strip_prefix('^') {
185            if let Some(id) = self.index.configs.keys.get(&config::key("constant", name)) {
186                let symbol = &self.index.configs.symbols[*id];
187                if let Some(definition) = &symbol.definition {
188                    let document = self.project.document(definition.source)?;
189                    let line = document.text[definition.range.end..].lines().next()?;
190                    let (_, value) = line.split_once('=')?;
191                    return self.resolve(value.split("//").next()?.trim(), depth + 1);
192                }
193            }
194            return match &self.project.registry.lookup_constant(name)?.kind {
195                RegistryKind::Constant { int_value, .. } => int_value.map(|value| value as u32),
196                _ => None,
197            };
198        }
199        number(text)
200    }
201
202    fn config(&mut self) {
203        let kind = self.document.config.as_deref().unwrap();
204        let tokens = config::typed_tokens(self.document, self.index.config_types());
205        let color_file = self
206            .document
207            .label
208            .file_stem()
209            .and_then(|name| name.to_str())
210            .is_some_and(|name| matches!(name, "colour" | "color" | "colours" | "colors"));
211        let mut constant = None;
212        for typed in tokens {
213            let token = typed.token;
214            let text = &self.document.text[token.range.clone()];
215            if kind == "constant" && token.declaration {
216                constant = named_encoding(text).or(color_file.then_some(Encoding::Rgb));
217            }
218            if token.kind == TokenKind::String {
219                self.tags(token.range.clone());
220            }
221            if matches!(
222                token.kind,
223                TokenKind::Number | TokenKind::Variable | TokenKind::EnumMember
224            ) && !token.declaration
225            {
226                if let Some(Value::Color(encoding)) = typed.value {
227                    if kind == "wma" && self.resolve(text, 0) == Some(u32::MAX) {
228                        continue;
229                    }
230                    if matches!(kind, "if" | "flo" | "flu" | "texture")
231                        && encoding == Encoding::Rgb
232                        && !text.starts_with(['^', '%'])
233                        && !text.starts_with("0x")
234                        && !text.starts_with("0X")
235                    {
236                        self.hex(token.range, encoding);
237                    } else {
238                        self.value(token.range, encoding);
239                    }
240                } else if kind == "constant"
241                    && let Some(encoding) = constant
242                {
243                    self.value(token.range, encoding);
244                }
245            }
246        }
247        extra::scan(self);
248    }
249
250    fn script(&mut self) {
251        for (token, range) in self.document.tokens.iter().zip(&self.document.spans) {
252            if matches!(token.kind, Kind::StringLiteral | Kind::RawStringLiteral) {
253                self.tags(range.clone());
254            }
255        }
256        let hooks = self
257            .index
258            .hooks
259            .get(&self.document.id)
260            .map_or(&[][..], Vec::as_slice);
261        let tokens = index::tokens(self.document, &|name| self.index.is_compound(name), hooks);
262        let tokens = tokens
263            .iter()
264            .filter(|(token, _)| {
265                !matches!(token.kind, Kind::SingleLineComment | Kind::MultiLineComment)
266            })
267            .collect::<Vec<_>>();
268        let scripts = self
269            .index
270            .references_in(self.document.id)
271            .filter(|reference| reference.declaration)
272            .map(|reference| self.index.symbol(reference.symbol))
273            .filter(|symbol| {
274                matches!(
275                    symbol.kind,
276                    SymbolKind::Procedure | SymbolKind::ClientScript | SymbolKind::Trigger
277                )
278            })
279            .collect::<Vec<_>>();
280        let mut stack: Vec<(Vec<Option<Encoding>>, usize, usize)> = Vec::new();
281        for (i, (token, range)) in tokens.iter().enumerate() {
282            if token.kind == Kind::LParen {
283                let previous = i.checked_sub(1).map(|i| tokens[i]);
284                let symbol = previous.and_then(|(_, range)| self.symbol(range.start));
285                let encodings = if previous.is_some_and(|(token, _)| token.kind == Kind::Return) {
286                    scripts
287                        .iter()
288                        .find(|symbol| {
289                            symbol.container.is_none()
290                                && symbol.extent.as_ref().is_some_and(|extent| {
291                                    extent.source == self.document.id
292                                        && extent.range.contains(&range.start)
293                                })
294                        })
295                        .map(|symbol| {
296                            symbol
297                                .returns
298                                .iter()
299                                .map(|ty| (*ty == Type::Colour).then_some(Encoding::Rgb))
300                                .collect()
301                        })
302                        .unwrap_or_default()
303                } else {
304                    symbol
305                        .filter(|symbol| {
306                            matches!(
307                                symbol.kind,
308                                SymbolKind::Command
309                                    | SymbolKind::Procedure
310                                    | SymbolKind::ClientScript
311                                    | SymbolKind::Trigger
312                            )
313                        })
314                        .map(|symbol| {
315                            symbol
316                                .parameters
317                                .iter()
318                                .enumerate()
319                                .map(|(argument, (_, ty))| {
320                                    if *ty == Type::Colour {
321                                        Some(Encoding::Rgb)
322                                    } else {
323                                        command_encoding(symbol, argument)
324                                    }
325                                })
326                                .collect()
327                        })
328                        .unwrap_or_default()
329                };
330                stack.push((encodings, 0, range.end));
331            } else if matches!(token.kind, Kind::Comma | Kind::RParen) {
332                if let Some((encodings, argument, start)) = stack.last_mut() {
333                    if let Some(Some(encoding)) = encodings.get(*argument) {
334                        let first = tokens.partition_point(|(_, range)| range.start < *start);
335                        if first < i {
336                            self.value(tokens[first].1.start..tokens[i - 1].1.end, *encoding);
337                        }
338                    }
339                    *argument += 1;
340                    *start = range.end;
341                }
342                if token.kind == Kind::RParen {
343                    stack.pop();
344                }
345            } else if token.kind == Kind::Equals || token.kind == Kind::ComparisonOperator {
346                let previous = i.checked_sub(1).map(|i| tokens[i]);
347                if previous
348                    .and_then(|(_, range)| self.symbol(range.start))
349                    .is_some_and(|symbol| symbol.value_type == Some(Type::Colour))
350                    && let Some((next, next_range)) = tokens.get(i + 1)
351                {
352                    let end = if next.kind == Kind::ConstantVar
353                        || next.kind == Kind::BinaryOperator && next.value == "-"
354                    {
355                        tokens.get(i + 2).map(|(_, range)| range.end)
356                    } else if next.kind == Kind::Number {
357                        Some(next_range.end)
358                    } else {
359                        None
360                    };
361                    if let Some(end) = end {
362                        self.value(next_range.start..end, Encoding::Rgb);
363                    }
364                }
365            } else if token.kind == Kind::ConstantVar {
366                let Some((_, name_range)) = tokens.get(i + 1) else {
367                    continue;
368                };
369                let symbol = self.symbol(name_range.start);
370                let encoding = symbol.and_then(|symbol| {
371                    if symbol.value_type == Some(Type::Colour) {
372                        Some(Encoding::Rgb)
373                    } else {
374                        named_encoding(&symbol.name).or_else(|| {
375                            let source =
376                                self.project.document(symbol.definition.as_ref()?.source)?;
377                            matches!(
378                                source.label.file_stem()?.to_str()?,
379                                "colour" | "color" | "colours" | "colors"
380                            )
381                            .then_some(Encoding::Rgb)
382                        })
383                    }
384                });
385                if let Some(encoding) = encoding {
386                    self.value(range.start..name_range.end, encoding);
387                }
388            }
389        }
390    }
391
392    fn symbol(&self, offset: usize) -> Option<&Symbol> {
393        self.index
394            .at(self.document.id, offset)
395            .map(|reference| self.index.symbol(reference.symbol))
396    }
397
398    fn tags(&mut self, range: Range<usize>) {
399        let text = &self.document.text[range.clone()];
400        for prefix in ["<col=", "<shad=", "<str=", "<u="] {
401            for (offset, _) in text.match_indices(prefix) {
402                let start = offset + prefix.len();
403                let Some(end) = text[start..].find('>') else {
404                    continue;
405                };
406                let value = &text[start..start + end];
407                if value.is_empty()
408                    || value.len() > 6
409                    || !value.bytes().all(|byte| byte.is_ascii_hexdigit())
410                {
411                    continue;
412                }
413                let value = u32::from_str_radix(value, 16).unwrap();
414                self.out.push(Swatch {
415                    range: range.start + start..range.start + start + end,
416                    color: Encoding::Rgb.decode(value),
417                    encoding: Encoding::Rgb,
418                    value,
419                    editable: true,
420                    tag: true,
421                });
422            }
423        }
424        let mut tag_end = 0;
425        for (offset, _) in text.match_indices('@') {
426            if offset < tag_end {
427                continue;
428            }
429            let Some(tag) = text
430                .get(offset..offset + 5)
431                .filter(|tag| tag.ends_with('@'))
432            else {
433                continue;
434            };
435            let value = match &tag[1..4] {
436                "red" => 0xff0000,
437                "gre" => 0x00ff00,
438                "blu" => 0x0000ff,
439                "yel" => 0xffff00,
440                "cya" => 0x00ffff,
441                "mag" => 0xff00ff,
442                "whi" => 0xffffff,
443                "bla" => 0,
444                "lre" => 0xff9040,
445                "dre" => 0x800000,
446                "dbl" => 0x000080,
447                "or1" => 0xffb000,
448                "or2" => 0xff7000,
449                "or3" => 0xff3000,
450                "gr1" => 0xc0ff00,
451                "gr2" => 0x80ff00,
452                "gr3" => 0x40ff00,
453                _ => continue,
454            };
455            tag_end = offset + 5;
456            self.out.push(Swatch {
457                range: range.start + offset..range.start + offset + 5,
458                color: Encoding::Rgb.decode(value),
459                encoding: Encoding::Rgb,
460                value,
461                editable: false,
462                tag: false,
463            });
464        }
465    }
466}
467
468fn named_encoding(name: &str) -> Option<Encoding> {
469    match name.rsplit('_').next()? {
470        "rgb" => Some(Encoding::Rgb),
471        "argb" => Some(Encoding::Argb),
472        "rgb15" => Some(Encoding::Rgb15),
473        "hsl" => Some(Encoding::Hsl),
474        _ => None,
475    }
476}
477
478fn command_encoding(symbol: &Symbol, argument: usize) -> Option<Encoding> {
479    if symbol.kind != SymbolKind::Command {
480        return None;
481    }
482    match (symbol.name.as_str(), argument) {
483        ("if_setcolour", 1)
484            if symbol
485                .parameters
486                .first()
487                .is_some_and(|(_, ty)| *ty == Type::Component) =>
488        {
489            Some(Encoding::Rgb)
490        }
491        ("text_coord", 2) => Some(Encoding::Rgb),
492        ("if_setrecol" | "cc_setrecol" | "op1131", 1 | 2) => Some(Encoding::Hsl),
493        ("op5401", 1) => Some(Encoding::Rgb),
494        ("hsvtorgb", 0) => Some(Encoding::Hsl),
495        _ => None,
496    }
497}
498
499fn number(text: &str) -> Option<u32> {
500    let value = text.replace('_', "");
501    if let Some(hex) = value
502        .strip_prefix("0x")
503        .or_else(|| value.strip_prefix("0X"))
504    {
505        u32::from_str_radix(hex, 16).ok()
506    } else {
507        value
508            .parse::<i64>()
509            .ok()
510            .filter(|value| (i32::MIN as i64..=u32::MAX as i64).contains(value))
511            .map(|value| value as u32)
512    }
513}
514
515impl Encoding {
516    fn decode(self, value: u32) -> Color {
517        match self {
518            Self::Rgb | Self::Argb => Color {
519                red: ((value >> 16) & 255) as f64 / 255.0,
520                green: ((value >> 8) & 255) as f64 / 255.0,
521                blue: (value & 255) as f64 / 255.0,
522                alpha: if self == Self::Argb {
523                    (value >> 24) as f64 / 255.0
524                } else {
525                    1.0
526                },
527            },
528            Self::Rgb15 => Color {
529                red: ((value >> 10) & 31) as f64 / 31.0,
530                green: ((value >> 5) & 31) as f64 / 31.0,
531                blue: (value & 31) as f64 / 31.0,
532                alpha: 1.0,
533            },
534            Self::Gray12 => {
535                let gray = (value as f64 / 4096.0).min(1.0);
536                Color {
537                    red: gray,
538                    green: gray,
539                    blue: gray,
540                    alpha: 1.0,
541                }
542            }
543            Self::Hsl | Self::Hsl32 => {
544                let (hue, saturation, lightness, gamma) = if self == Self::Hsl {
545                    (
546                        ((value >> 10) & 63) as f64 / 64.0 + 1.0 / 128.0,
547                        ((value >> 7) & 7) as f64 / 8.0 + 1.0 / 16.0,
548                        (value & 127) as f64 / 128.0,
549                        0.7,
550                    )
551                } else {
552                    (
553                        ((value as i32 >> 20) as f64 * 3.0 / 256.0).rem_euclid(1.0),
554                        (((value >> 10) & 1023) as f64 * 3.0 / 256.0).min(1.0),
555                        ((value & 1023) as f64 * 3.0 / 256.0).min(1.0),
556                        1.0,
557                    )
558                };
559                let q = if lightness < 0.5 {
560                    lightness * (1.0 + saturation)
561                } else {
562                    lightness + saturation - lightness * saturation
563                };
564                let p = 2.0 * lightness - q;
565                let channel = |offset: f64| {
566                    let h = (hue + offset).rem_euclid(1.0);
567                    let value = if h < 1.0 / 6.0 {
568                        p + (q - p) * 6.0 * h
569                    } else if h < 0.5 {
570                        q
571                    } else if h < 2.0 / 3.0 {
572                        p + (q - p) * (2.0 / 3.0 - h) * 6.0
573                    } else {
574                        p
575                    };
576                    value.powf(gamma)
577                };
578                Color {
579                    red: channel(1.0 / 3.0),
580                    green: channel(0.0),
581                    blue: channel(-1.0 / 3.0),
582                    alpha: 1.0,
583                }
584            }
585        }
586    }
587
588    fn encode(self, color: Color) -> u32 {
589        let channel = |value: f64, max: f64| (value * max).round() as u32;
590        match self {
591            Self::Rgb | Self::Argb => {
592                channel(color.red, 255.0) << 16
593                    | channel(color.green, 255.0) << 8
594                    | channel(color.blue, 255.0)
595                    | if self == Self::Argb {
596                        channel(color.alpha, 255.0) << 24
597                    } else {
598                        0
599                    }
600            }
601            Self::Rgb15 => {
602                channel(color.red, 31.0) << 10
603                    | channel(color.green, 31.0) << 5
604                    | channel(color.blue, 31.0)
605            }
606            Self::Gray12 => channel(
607                color.red * 0.2126 + color.green * 0.7152 + color.blue * 0.0722,
608                4096.0,
609            ),
610            Self::Hsl | Self::Hsl32 => {
611                let [r, g, b] = [color.red, color.green, color.blue].map(|value| {
612                    if self == Self::Hsl {
613                        value.powf(1.0 / 0.7)
614                    } else {
615                        value * 255.0 / 256.0
616                    }
617                });
618                let min = r.min(g).min(b);
619                let max = r.max(g).max(b);
620                let lightness = (min + max) / 2.0;
621                let delta = max - min;
622                let saturation = if delta == 0.0 {
623                    0.0
624                } else {
625                    delta / (1.0 - (2.0 * lightness - 1.0).abs())
626                };
627                let hue = if delta == 0.0 {
628                    0.0
629                } else if max == r {
630                    (g - b) / delta / 6.0
631                } else if max == g {
632                    ((b - r) / delta + 2.0) / 6.0
633                } else {
634                    ((r - g) / delta + 4.0) / 6.0
635                };
636                if self == Self::Hsl {
637                    ((hue.rem_euclid(1.0) * 64.0) as u32).min(63) << 10
638                        | ((saturation * 8.0) as u32).min(7) << 7
639                        | channel(lightness, 128.0).min(127)
640                } else {
641                    let scale = |value: f64| (value * 256.0 / 3.0) as i32;
642                    (scale(hue) << 20)
643                        .wrapping_add(scale(saturation) << 10)
644                        .wrapping_add(scale(lightness)) as u32
645                }
646            }
647        }
648    }
649}