aboutsummaryrefslogtreecommitdiffstats
path: root/src/css/cascade.nim
blob: a9080d44f487d5fe02b4b7ed97a3714179f56ddd (plain) (blame)
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
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
import std/algorithm
import std/options
import std/sets
import std/tables

import chame/tags
import css/cssparser
import css/cssvalues
import css/lunit
import css/match
import css/selectorparser
import css/sheet
import html/catom
import html/dom
import html/enums
import html/script
import types/bitmap
import types/color
import types/jscolor
import types/opt

type
  RuleListEntry = object
    normal: seq[CSSComputedEntry]
    important: seq[CSSComputedEntry]
    normalVars: seq[CSSVariable]
    importantVars: seq[CSSVariable]

  RuleList = array[CSSOrigin, RuleListEntry]

  RuleListMap = array[PseudoElement, RuleList]

  RulePair = tuple
    specificity: int
    rule: CSSRuleDef

  ToSorts = array[PseudoElement, seq[RulePair]]

  InitType = enum
    itUserAgent, itUser, itOther

  InitMap = array[CSSPropertyType, set[InitType]]

  ApplyValueContext = object
    vals: CSSValues
    parentComputed: CSSValues
    previousOrigin: CSSValues
    window: Window
    initMap: InitMap
    varsSeen: HashSet[CAtom]

# Forward declarations
proc applyValue(ctx: var ApplyValueContext; entry: CSSComputedEntry;
  initType: InitType; nextInitType: set[InitType])
proc applyStyle*(element: Element)

proc calcRule(tosorts: var ToSorts; element: Element;
    depends: var DependencyInfo; rule: CSSRuleDef) =
  for sel in rule.sels:
    if element.matches(sel, depends):
      if tosorts[sel.pseudo].len > 0 and tosorts[sel.pseudo][^1].rule == rule:
        tosorts[sel.pseudo][^1].specificity =
          max(tosorts[sel.pseudo][^1].specificity, sel.specificity)
      else:
        tosorts[sel.pseudo].add((sel.specificity, rule))

proc add(entry: var RuleListEntry; rule: CSSRuleDef) =
  entry.normal.add(rule.normalVals)
  entry.important.add(rule.importantVals)
  entry.normalVars.add(rule.normalVars)
  entry.importantVars.add(rule.importantVars)

proc calcRules(map: var RuleListMap; element: Element;
    sheet: CSSStylesheet; origin: CSSOrigin; depends: var DependencyInfo) =
  var rules: seq[CSSRuleDef] = @[]
  sheet.tagTable.withValue(element.localName, v):
    rules.add(v[])
  if element.id != CAtomNull:
    sheet.idTable.withValue(sheet.factory.toLowerAscii(element.id), v):
      rules.add(v[])
  for class in element.classList:
    sheet.classTable.withValue(sheet.factory.toLowerAscii(class), v):
      rules.add(v[])
  for attr in element.attrs:
    sheet.attrTable.withValue(attr.qualifiedName, v):
      rules.add(v[])
  for rule in sheet.generalList:
    rules.add(rule)
  var tosorts = ToSorts.default
  for rule in rules:
    tosorts.calcRule(element, depends, rule)
  for pseudo, it in tosorts.mpairs:
    it.sort(proc(x, y: RulePair): int =
      let n = cmp(x.specificity, y.specificity)
      if n != 0:
        return n
      return cmp(x.rule.idx, y.rule.idx), order = Ascending)
    for item in it:
      map[pseudo][origin].add(item.rule)

proc findVariable(computed: CSSValues; varName: CAtom): CSSVariable =
  var vars = computed.vars
  while vars != nil:
    let cvar = vars.table.getOrDefault(varName)
    if cvar != nil:
      return cvar
    vars = vars.parent
  return nil

proc applyVariable(ctx: var ApplyValueContext; t: CSSPropertyType;
    varName: CAtom; fallback: ref CSSComputedEntry; initType: InitType;
    nextInitType: set[InitType]) =
  let v = t.valueType
  let cvar = ctx.vals.findVariable(varName)
  if cvar == nil:
    if fallback != nil:
      ctx.applyValue(fallback[], initType, nextInitType)
    return
  for (iv, entry) in cvar.resolved.mitems:
    if iv == v:
      entry.t = t # must override, same var can be used for different props
      ctx.applyValue(entry, initType, nextInitType)
      return
  var entries: seq[CSSComputedEntry] = @[]
  if entries.parseComputedValues($t, cvar.cvals, ctx.window.attrsp[],
      ctx.window.factory).isSome:
    if entries[0].et == ceVar:
      if ctx.varsSeen.containsOrIncl(varName) or ctx.varsSeen.len > 20:
        ctx.varsSeen.clear()
        return
    else:
      ctx.varsSeen.clear()
      cvar.resolved.add((v, entries[0]))
    ctx.applyValue(entries[0], initType, nextInitType)

proc applyGlobal(ctx: ApplyValueContext; t: CSSPropertyType;
    global: CSSGlobalType; initType: InitType) =
  case global
  of cgtInherit:
    ctx.vals.initialOrCopyFrom(ctx.parentComputed, t)
  of cgtInitial:
    ctx.vals.setInitial(t)
  of cgtUnset:
    ctx.vals.initialOrInheritFrom(ctx.parentComputed, t)
  of cgtRevert:
    if ctx.previousOrigin != nil and initType in ctx.initMap[t]:
      ctx.vals.copyFrom(ctx.previousOrigin, t)
    else:
      ctx.vals.initialOrInheritFrom(ctx.parentComputed, t)

proc applyValue(ctx: var ApplyValueContext; entry: CSSComputedEntry;
    initType: InitType; nextInitType: set[InitType]) =
  case entry.et
  of ceBit: ctx.vals.bits[entry.t].dummy = entry.bit
  of ceWord: ctx.vals.words[entry.t] = entry.word
  of ceObject: ctx.vals.objs[entry.t] = entry.obj
  of ceGlobal:
    ctx.applyGlobal(entry.t, entry.global, initType)
  of ceVar:
    ctx.applyVariable(entry.t, entry.cvar, entry.fallback, initType,
      nextInitType)
    return # maybe it applies, maybe it doesn't...
  ctx.initMap[entry.t] = ctx.initMap[entry.t] + nextInitType

proc applyPresHints(ctx: var ApplyValueContext; element: Element) =
  template set_cv(t, x, b: untyped) =
    ctx.applyValue(makeEntry(t, CSSValueWord(x: b)), itUserAgent, {itUser})
  template set_cv_new(t, x, b: untyped) =
    const v = valueType(t)
    let val = CSSValue(v: v, x: b)
    ctx.applyValue(makeEntry(t, val), itUserAgent, {itUser})
  template map_width =
    let s = parseDimensionValues(element.attr(satWidth))
    if s.isSome:
      set_cv cptWidth, length, s.get
  template map_height =
    let s = parseDimensionValues(element.attr(satHeight))
    if s.isSome:
      set_cv cptHeight, length, s.get
  template map_width_nozero =
    let s = parseDimensionValues(element.attr(satWidth))
    if s.isSome and s.get.num != 0:
      set_cv cptWidth, length, s.get
  template map_height_nozero =
    let s = parseDimensionValues(element.attr(satHeight))
    if s.isSome and s.get.num != 0:
      set_cv cptHeight, length, s.get
  template map_bgcolor =
    let s = element.attr(satBgcolor)
    if s != "":
      let c = parseLegacyColor(s)
      if c.isSome:
        set_cv cptBackgroundColor, color, c.get.cssColor()
  template map_size =
    let s = element.attrul(satSize)
    if s.isSome:
      set_cv cptWidth, length, resolveLength(cuCh, float32(s.get),
        ctx.window.attrsp[])
  template map_text =
    let s = element.attr(satText)
    if s != "":
      let c = parseLegacyColor(s)
      if c.isSome:
        set_cv cptColor, color, c.get.cssColor()
  template map_color =
    let s = element.attr(satColor)
    if s != "":
      let c = parseLegacyColor(s)
      if c.isSome:
        set_cv cptColor, color, c.get.cssColor()
  template map_colspan =
    let colspan = element.attrulgz(satColspan)
    if colspan.isSome:
      let i = colspan.get
      if i <= 1000:
        set_cv cptChaColspan, integer, int32(i)
  template map_rowspan =
    let rowspan = element.attrul(satRowspan)
    if rowspan.isSome:
      let i = rowspan.get
      if i <= 65534:
        set_cv cptChaRowspan, integer, int32(i)
  template set_bgcolor_is_canvas =
    let t = cptBgcolorIsCanvas
    let val = CSSValueBit(bgcolorIsCanvas: true)
    ctx.applyValue(makeEntry(t, val), itUserAgent, {itUser})
  template map_cellspacing =
    let s = element.attrul(satCellspacing)
    if s.isSome:
      let n = float32(s.get)
      set_cv_new cptBorderSpacing, length2, CSSLength2(a: cssLength(n))

  case element.tagType
  of TAG_TABLE:
    map_height_nozero
    map_width_nozero
    map_bgcolor
    map_cellspacing
  of TAG_TD, TAG_TH:
    map_height_nozero
    map_width_nozero
    map_bgcolor
    map_colspan
    map_rowspan
  of TAG_THEAD, TAG_TBODY, TAG_TFOOT, TAG_TR:
    map_height
    map_bgcolor
  of TAG_COL:
    map_width
  of TAG_IMG:
    map_width
    map_height
  of TAG_CANVAS:
    map_width
    map_height
  of TAG_HTML:
    set_bgcolor_is_canvas
  of TAG_BODY:
    set_bgcolor_is_canvas
    map_bgcolor
    map_text
  of TAG_TEXTAREA:
    let textarea = HTMLTextAreaElement(element)
    let cols = textarea.attrul(satCols).get(20)
    let rows = textarea.attrul(satRows).get(1)
    set_cv cptWidth, length, resolveLength(cuCh, float32(cols),
      ctx.window.attrsp[])
    set_cv cptHeight, length, resolveLength(cuEm, float32(rows),
      ctx.window.attrsp[])
  of TAG_FONT:
    map_color
  of TAG_INPUT:
    let input = HTMLInputElement(element)
    if input.inputType in InputTypeWithSize:
      map_size
  of TAG_SELECT:
    let select = HTMLSelectElement(element)
    if select.attrb(satMultiple):
      let size = element.attrulgz(satSize).get(4)
      set_cv cptHeight, length, resolveLength(cuEm, float32(size),
        ctx.window.attrsp[])
  else: discard

proc applyDeclarations(rules: RuleList; parent, element: Element;
    window: Window): CSSValues =
  result = CSSValues()
  var parentVars: CSSVariableMap = nil
  var ctx = ApplyValueContext(window: window, vals: result)
  if parent != nil:
    if parent.computed == nil:
      parent.applyStyle()
    ctx.parentComputed = parent.computed
    parentVars = ctx.parentComputed.vars
  for origin in CSSOrigin:
    if rules[origin].importantVars.len > 0:
      if result.vars == nil:
        result.vars = newCSSVariableMap(parentVars)
      for i in countdown(rules[origin].importantVars.high, 0):
        let cvar = rules[origin].importantVars[i]
        result.vars.putIfAbsent(cvar.name, cvar)
  for origin in countdown(CSSOrigin.high, CSSOrigin.low):
    if rules[origin].normalVars.len > 0:
      if result.vars == nil:
        result.vars = newCSSVariableMap(parentVars)
      for i in countdown(rules[origin].normalVars.high, 0):
        let cvar = rules[origin].normalVars[i]
        result.vars.putIfAbsent(cvar.name, cvar)
  if result.vars == nil:
    result.vars = parentVars # inherit parent
  for entry in rules[coUserAgent].normal: # user agent
    ctx.applyValue(entry, itOther, {itUserAgent, itUser})
  let uaProperties = result.copyProperties()
  # Presentational hints override user agent style, but respect user/author
  # style.
  if element != nil:
    ctx.applyPresHints(element)
  ctx.previousOrigin = uaProperties
  for entry in rules[coUser].normal:
    ctx.applyValue(entry, itUserAgent, {itUser})
  # save user properties so author can use them
  ctx.previousOrigin = result.copyProperties() # use user for author revert
  for entry in rules[coAuthor].normal:
    ctx.applyValue(entry, itUser, {itOther})
  for entry in rules[coAuthor].important:
    ctx.applyValue(entry, itUser, {itOther})
  ctx.previousOrigin = uaProperties # use UA for user important revert
  for entry in rules[coUser].important:
    ctx.applyValue(entry, itUserAgent, {itOther})
  ctx.previousOrigin = nil # reset origin for UA
  for entry in rules[coUserAgent].important:
    ctx.applyValue(entry, itUserAgent, {itOther})
  # fill in defaults
  for t in CSSPropertyType:
    if ctx.initMap[t] == {}:
      result.initialOrInheritFrom(ctx.parentComputed, t)
  # Quirk: it seems others aren't implementing what the spec says about
  # blockification.
  # Well, neither will I, because the spec breaks on actual websites.
  # Curse CSS.
  if result{"position"} in {PositionAbsolute, PositionFixed}:
    if result{"display"} == DisplayInline:
      result{"display"} = DisplayInlineBlock
  elif result{"float"} != FloatNone:
    result{"display"} = result{"display"}.blockify()
  if (result{"overflow-x"} in {OverflowVisible, OverflowClip}) !=
      (result{"overflow-y"} in {OverflowVisible, OverflowClip}):
    result{"overflow-x"} = result{"overflow-x"}.bfcify()
    result{"overflow-y"} = result{"overflow-y"}.bfcify()

func hasValues(rules: RuleList): bool =
  for x in rules:
    if x.normal.len > 0 or x.important.len > 0:
      return true
  return false

proc applyStyle*(element: Element) =
  let document = element.document
  let window = document.window
  var depends = DependencyInfo.default
  var map = RuleListMap.default
  for sheet in document.uaSheets:
    map.calcRules(element, sheet, coUserAgent, depends)
  map.calcRules(element, document.userSheet, coUser, depends)
  for sheet in document.authorSheets:
    map.calcRules(element, sheet, coAuthor, depends)
  let style = element.cachedStyle
  if window.styling and style != nil:
    for decl in style.decls:
      #TODO variables
      let vals = parseComputedValues(decl.name, decl.value, window.attrsp[],
        window.factory)
      if decl.important:
        map[peNone][coAuthor].important.add(vals)
      else:
        map[peNone][coAuthor].normal.add(vals)
  element.applyStyleDependencies(depends)
  element.computedMap[peNone] =
    map[peNone].applyDeclarations(element.parentElement, element, window)
  for pseudo in peBefore..peAfter:
    if map[pseudo].hasValues() or window.settings.scripting == smApp:
      let computed = map[pseudo].applyDeclarations(element, nil, window)
      element.computedMap[pseudo] = computed

# Abstraction over the DOM to pretend that elements, text, replaced and
# pseudo-elements are derived from the same type.
type
  StyledType* = enum
    stElement, stText, stReplacement

  StyledNode* = object
    element*: Element
    pseudo*: PseudoElement
    case t*: StyledType
    of stText:
      text*: CharacterData
    of stElement:
      discard
    of stReplacement:
      # replaced elements: quotes, images, or (TODO) markers
      content*: CSSContent

when defined(debug):
  func `$`*(node: StyledNode): string =
    case node.t
    of stText:
      return "#text " & node.text.data
    of stElement:
      if node.pseudo != peNone:
        return $node.element.tagType & "::" & $node.pseudo
      return $node.element
    of stReplacement:
      return "#replacement"

# Defined here so it isn't accidentally used in dom.
#TODO it may be better to do it in dom anyway, so we can cache it...
func newCharacterData*(data: sink string): CharacterData =
  return CharacterData(data: data)

template computed*(styledNode: StyledNode): CSSValues =
  styledNode.element.computedMap[styledNode.pseudo]

proc initStyledElement*(element: Element): StyledNode =
  if element.computed == nil:
    element.applyStyle()
  return StyledNode(t: stElement, element: element)

proc initStyledReplacement(parent: Element; content: sink CSSContent):
    StyledNode =
  return StyledNode(t: stReplacement, element: parent, content: content)

proc initStyledImage(parent: Element; bmp: NetworkBitmap): StyledNode =
  return initStyledReplacement(parent, CSSContent(t: ContentImage, bmp: bmp))

proc initStyledPseudo(parent: Element; pseudo: PseudoElement): StyledNode =
  return StyledNode(t: stElement, pseudo: pseudo, element: parent)

proc initStyledText(parent: Element; text: CharacterData): StyledNode =
  return StyledNode(t: stText, element: parent, text: text)

proc initStyledText(parent: Element; s: sink string): StyledNode =
  return initStyledText(parent, newCharacterData(s))

# Many yields; we use a closure iterator to avoid bloating the code.
iterator children*(styledNode: StyledNode): StyledNode {.closure.} =
  if styledNode.t != stElement:
    return
  if styledNode.pseudo == peNone:
    let parent = styledNode.element
    if parent.computedMap[peBefore] != nil and
        parent.computedMap[peBefore]{"content"}.len > 0:
      yield initStyledPseudo(parent, peBefore)
    case parent.tagType
    of TAG_INPUT:
      #TODO cache (just put value in a CharacterData)
      let s = HTMLInputElement(parent).inputString()
      if s.len > 0:
        yield initStyledText(parent, s)
    of TAG_TEXTAREA:
      #TODO cache (do the same as with input, and add borders in render)
      yield initStyledText(parent, HTMLTextAreaElement(parent).textAreaString())
    of TAG_IMG: yield initStyledImage(parent, HTMLImageElement(parent).bitmap)
    of TAG_CANVAS:
      yield initStyledImage(parent, HTMLImageElement(parent).bitmap)
    of TAG_VIDEO: yield initStyledText(parent, "[video]")
    of TAG_AUDIO: yield initStyledText(parent, "[audio]")
    of TAG_BR:
      yield initStyledReplacement(parent, CSSContent(t: ContentNewline))
    of TAG_IFRAME: yield initStyledText(parent, "[iframe]")
    elif parent.tagType(Namespace.SVG) == TAG_SVG:
      yield initStyledImage(parent, SVGSVGElement(parent).bitmap)
    else:
      for it in parent.childList:
        if it of Element:
          yield initStyledElement(Element(it))
        elif it of Text:
          yield initStyledText(parent, Text(it))
    if parent.computedMap[peAfter] != nil and
        parent.computedMap[peAfter]{"content"}.len > 0:
      yield initStyledPseudo(parent, peAfter)
  else:
    let parent = styledNode.element
    for content in parent.computedMap[styledNode.pseudo]{"content"}:
      yield parent.initStyledReplacement(content)