aboutsummaryrefslogtreecommitdiff
path: root/Map/Business/WmapSyntaxHighlighter/SyntaxHighlighter.swift
blob: 8b31547408a3337be4cb3c531804d975e891dfbc (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
// Copyright (C) 2024 Rubén Beltrán del Río

// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.

// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.

// You should have received a copy of the GNU General Public License
// along with this program. If not, see https://map.tranquil.systems.
import AppKit

extension Wmap {
  class SyntaxHighlighter {
    var cachedSyntaxElements: [SyntaxElement] = []
    private var lineToElementsMap: [Int: [SyntaxElement]] = [:]
    private var cachedVertexLabels: Set<String> = Set()

    func updateSyntaxElements(from parsedMap: Wmap.ParsedMap) {
      cachedSyntaxElements = parsedMap.entities.flatMap { $0.syntaxElements }
      cachedVertexLabels = parsedMap.vertexLabels

      // Build line-to-elements mapping for fast lookup
      lineToElementsMap.removeAll()
      for element in cachedSyntaxElements {
        let line = element.range.start.line
        lineToElementsMap[line, default: []].append(element)
      }
    }

    func applySyntaxHighlighting(textStorage: NSTextStorage, range: NSRange) {
      // Get the line range that encompasses the edited range
      let string = textStorage.string as NSString
      let lineRange = string.lineRange(for: range)

      // Apply highlighting to elements that intersect with the line range
      for element in cachedSyntaxElements {
        // Safely convert string range to NSRange with bounds checking
        guard element.range.stringRange.lowerBound <= element.range.stringRange.upperBound,
          element.range.stringRange.upperBound <= textStorage.string.endIndex
        else {
          continue
        }

        let nsRange = NSRange(element.range.stringRange, in: textStorage.string)

        // Only process elements that intersect with our update area
        guard nsRange.location != NSNotFound,
          nsRange.location + nsRange.length <= textStorage.length,
          NSIntersectionRange(nsRange, lineRange).length > 0
        else {
          continue
        }

        let color = colorForSyntaxType(element.type)
        var attributes: [NSAttributedString.Key: Any] = [
          .foregroundColor: color
        ]

        if UserDefaults.standard.bool(forKey: "useSmartEditor") {
          if element.type == .vertexLabel
            && !cachedVertexLabels.contains(element.value.lowercased())
          {
            if UserDefaults.standard.bool(forKey: "highlightMissingComponents") {
              attributes[.underlineStyle] =
                NSUnderlineStyle.thick.rawValue | NSUnderlineStyle.patternDot.rawValue
              attributes[.underlineColor] = NSColor.Theme.Syntax.error
              attributes[.init("MissingComponent")] = element.value
            }
          }
        }

        textStorage.addAttributes(attributes, range: nsRange)
      }
    }

    private func colorForSyntaxType(_ type: SyntaxType) -> NSColor {
      switch type {
      case .keyword:
        return NSColor.Theme.Syntax.option
      case .vertexLabel:
        return NSColor.Theme.Syntax.vertex
      case .number:
        return NSColor.Theme.Syntax.number
      case .symbol:
        return NSColor.Theme.Syntax.symbol
      case .shape:
        return NSColor.Theme.Syntax.option
      case .text:
        return NSColor.Theme.Syntax.text
      case .punctuation:
        return NSColor.Theme.Syntax.punctuation
      case .stageNumber:
        return NSColor.Theme.Syntax.option
      }
    }
  }
}