about summary refs log tree commit diff stats
path: root/src/main.nim
blob: 808eff00f3913b7a2db69c69bbf3bc2271b2c6d0 (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
import version

# Note: we can't just import std/os or the compiler cries. (No idea why.)
from std/os import getEnv, putEnv, commandLineParams, getCurrentDir
import std/options
import std/posix

import server/forkserver
import config/chapath
import config/config
import js/javascript
import local/client
import local/term
import utils/strwidth
import utils/twtstr

import chagashi/charset

const ChaVersionStr = block:
  var s = "Chawan browser v0.1 "
  when defined(debug):
    s &= "(debug)"
  else:
    s &= "(release)"
  s &= '\n'
  s

proc help(i: int) =
  let s = ChaVersionStr & """
Usage: cha [options] [URL(s) or file(s)...]
Options:
    --                          Interpret all following arguments as URLs
    -c, --css <stylesheet>      Pass stylesheet (e.g. -c 'a{color: blue}')
    -d, --dump                  Print page to stdout
    -h, --help                  Print this usage message
    -o, --opt <config>          Pass config options (e.g. -o 'page.q="quit()"')
    -r, --run <script/file>     Run passed script or file
    -v, --version               Print version information
    -C, --config <file>         Override config path
    -I, --input-charset <enc>   Specify document charset
    -M, --monochrome            Set color-mode to 'monochrome'
    -O, --display-charset <enc> Specify display charset
    -T, --type <type>           Specify content mime type
    -V, --visual                Visual startup mode
"""
  if i == 0:
    stdout.write(s)
  else:
    stderr.write(s)
  quit(i)

proc version() =
  stdout.write(ChaVersionStr)
  quit(0)

type ParamParseContext = object
  params: seq[string]
  i: int
  configPath: Option[string]
  contentType: Option[string]
  charset: Charset
  dump: bool
  visual: bool
  opts: seq[string]
  stylesheet: string
  pages: seq[string]

proc getnext(ctx: var ParamParseContext): string =
  inc ctx.i
  if ctx.i < ctx.params.len:
    return ctx.params[ctx.i]
  help(1)

proc parseConfig(ctx: var ParamParseContext) =
  ctx.configPath = some(ctx.getnext())

proc parseMonochrome(ctx: var ParamParseContext) =
  ctx.opts.add("display.color-mode = monochrome")

proc parseVisual(ctx: var ParamParseContext) =
  ctx.visual = true

proc parseContentType(ctx: var ParamParseContext) =
  ctx.contentType = some(ctx.getnext())

proc getCharset(ctx: var ParamParseContext): Charset =
  let s = ctx.getnext()
  let charset = getCharset(s)
  if charset == CHARSET_UNKNOWN:
    stderr.write("Unknown charset " & s & "\n")
    quit(1)
  return charset

proc parseInputCharset(ctx: var ParamParseContext) =
  ctx.charset = ctx.getCharset()

proc parseOutputCharset(ctx: var ParamParseContext) =
  ctx.opts.add("encoding.display-charset = '" & $ctx.getCharset() & "'")

proc parseDump(ctx: var ParamParseContext) =
  ctx.dump = true

proc parseCSS(ctx: var ParamParseContext) =
  ctx.stylesheet &= ctx.getnext()

proc parseOpt(ctx: var ParamParseContext) =
  ctx.opts.add(ctx.getnext())

proc parseRun(ctx: var ParamParseContext) =
  let script = dqEscape(ctx.getnext())
  ctx.opts.add("start.startup-script = \"\"\"" & script & "\"\"\"")
  ctx.opts.add("start.headless = true")
  ctx.dump = true

proc parse(ctx: var ParamParseContext) =
  var escapeAll = false
  while ctx.i < ctx.params.len:
    let param = ctx.params[ctx.i]
    if escapeAll: # after --
      ctx.pages.add(param)
      inc ctx.i
      continue
    if param.len == 0:
      inc ctx.i
      continue
    if param[0] == '-':
      if param.len == 1:
        # If param == "-", i.e. it is a single dash, then ignore it.
        # (Some programs use single-dash to read from stdin, but we do that
        # automatically when stdin is not a tty. So ignoring it entirely
        # is probably for the best.)
        inc ctx.i
        continue
      if param[1] != '-':
        for j in 1 ..< param.len:
          const NeedsNextParam = {'C', 'I', 'O', 'T', 'c', 'o', 'r'}
          if j != param.high and param[j] in NeedsNextParam:
            # expecting next parameter, but not the last char...
            help(1)
          case param[j]
          of 'C': ctx.parseConfig()
          of 'I': ctx.parseInputCharset()
          of 'M': ctx.parseMonochrome()
          of 'O': ctx.parseOutputCharset()
          of 'T': ctx.parseContentType()
          of 'V': ctx.parseVisual()
          of 'c': ctx.parseCSS()
          of 'd': ctx.parseDump()
          of 'h': help(0)
          of 'o': ctx.parseOpt()
          of 'r': ctx.parseRun()
          of 'v': version()
          else: help(1)
      else:
        case param
        of "--config": ctx.parseConfig()
        of "--input-charset": ctx.parseInputCharset()
        of "--monochrome": ctx.parseMonochrome()
        of "--output-charset": ctx.parseOutputCharset()
        of "--type": ctx.parseContentType()
        of "--visual": ctx.parseVisual()
        of "--css": ctx.parseCSS()
        of "--dump": ctx.parseDump()
        of "--help": help(0)
        of "--opt": ctx.parseOpt()
        of "--run": ctx.parseRun()
        of "--version": version()
        of "--": escapeAll = true
        else: help(1)
    else:
      ctx.pages.add(param)
    inc ctx.i

proc main() =
  putEnv("CHA_LIBEXEC_DIR", ChaPath"${%CHA_LIBEXEC_DIR}".unquoteGet())
  let forkserver = newForkServer()
  var ctx = ParamParseContext(params: commandLineParams(), i: 0)
  ctx.parse()
  let jsrt = newJSRuntime()
  let jsctx = jsrt.newJSContext()
  var warnings = newSeq[string]()
  let (config, res) = readConfig(ctx.configPath, jsctx)
  if not res.success:
    stderr.writeLine(res.errorMsg)
    quit(1)
  warnings.add(res.warnings)
  for opt in ctx.opts:
    let res = config.parseConfig(getCurrentDir(), opt, laxnames = true)
    if not res.success:
      stderr.write(res.errorMsg)
      quit(1)
    warnings.add(res.warnings)
  config.css.stylesheet &= ctx.stylesheet
  block commands:
    let res = config.initCommands()
    if res.isNone:
      stderr.write("Error parsing commands: " & res.error)
      quit(1)
  isCJKAmbiguous = config.display.double_width_ambiguous
  if ctx.pages.len == 0 and stdin.isatty():
    if ctx.visual:
      ctx.pages.add(config.start.visual_home)
    elif (let httpHome = getEnv("HTTP_HOME"); httpHome != ""):
      ctx.pages.add(httpHome)
    elif (let wwwHome = getEnv("WWW_HOME"); wwwHome != ""):
      ctx.pages.add(wwwHome)
  if ctx.pages.len == 0 and not config.start.headless:
    if stdin.isatty():
      help(1)
  # make sure tmpdir & sockdir both exist; if we do this later, then
  # forkserver may try to open an empty dir
  discard mkdir(cstring(config.external.tmpdir), 0o700)
  discard mkdir(cstring(config.external.sockdir), 0o700)
  forkserver.loadForkServerConfig(config)
  let client = newClient(config, forkserver, jsctx, warnings)
  try:
    client.launchClient(ctx.pages, ctx.contentType, ctx.charset, ctx.dump)
  except CatchableError:
    client.flushConsole()
    raise

main()