| 1 | @[has_globals] |
| 2 | module main |
| 3 | |
| 4 | import alpm |
| 5 | import sync |
| 6 | import time |
| 7 | import x.progress |
| 8 | |
| 9 | #include "@VMODROOT/src/alpm_log.h" |
| 10 | |
| 11 | fn C.vpac_set_alpm_log(handle &alpm.Handle, ctx voidptr) int |
| 12 | |
| 13 | // ALPM_LOG_ERROR: the one level the log callback tells apart, the other one |
| 14 | // it passes being a warning (alpm_log.h) |
| 15 | const alpm_log_error = 1 |
| 16 | |
| 17 | // ProgressCfg is how the live display draws, the config's (progress ...) and |
| 18 | // (spinner ...) forms. style is the bar graphic, 'classic' or 'block', and |
| 19 | // parts holds the pieces of it the config respelled (start, end, fill, |
| 20 | // head, empty), the style's own standing for the rest. frames empty is the |
| 21 | // display's own spinner |
| 22 | struct ProgressCfg { |
| 23 | mut: |
| 24 | style string = 'classic' |
| 25 | parts map[string]string |
| 26 | length int = 30 |
| 27 | percent bool = true |
| 28 | eta bool = true |
| 29 | elapsed bool |
| 30 | rate bool = true |
| 31 | delay int = 50 |
| 32 | frames []string |
| 33 | interval int = 80 |
| 34 | done string = '✓' |
| 35 | timed bool |
| 36 | } |
| 37 | |
| 38 | __global cfg_progress = ProgressCfg{} |
| 39 | |
| 40 | // spinner_sets are the frame sets (spinner :frames) knows by name |
| 41 | const spinner_sets = ['dots', 'braille', 'line', 'arrows', 'circle', 'quarters', 'grow', 'bounce', |
| 42 | 'pulse', 'ellipsis', 'earth', 'moon'] |
| 43 | |
| 44 | // spinner_frames_named is a frame set by its name, none for a name outside |
| 45 | // spinner_sets |
| 46 | fn spinner_frames_named(name string) ?[]string { |
| 47 | return match name { |
| 48 | 'dots' { progress.spinner_dots() } |
| 49 | 'braille' { progress.spinner_braille() } |
| 50 | 'line' { progress.spinner_line() } |
| 51 | 'arrows' { progress.spinner_arrows() } |
| 52 | 'circle' { progress.spinner_circle() } |
| 53 | 'quarters' { progress.spinner_quarters() } |
| 54 | 'grow' { progress.spinner_grow() } |
| 55 | 'bounce' { progress.spinner_bounce() } |
| 56 | 'pulse' { progress.spinner_pulse() } |
| 57 | 'ellipsis' { progress.spinner_ellipsis() } |
| 58 | 'earth' { progress.spinner_earth() } |
| 59 | 'moon' { progress.spinner_moon() } |
| 60 | else { none } |
| 61 | } |
| 62 | } |
| 63 | |
| 64 | // part_rune is one cell of a bar graphic as the config spelled it: the |
| 65 | // first rune, or fallback for a part it left alone or emptied |
| 66 | fn part_rune(name string, fallback rune) rune { |
| 67 | text := cfg_progress.parts[name] or { return fallback } |
| 68 | runes := text.runes() |
| 69 | return if runes.len > 0 { runes[0] } else { fallback } |
| 70 | } |
| 71 | |
| 72 | // bar_style is the bar graphic the config draws |
| 73 | fn bar_style() progress.Style { |
| 74 | if cfg_progress.style == 'block' { |
| 75 | d := progress.BlockStyle{} |
| 76 | return progress.BlockStyle{ |
| 77 | start: cfg_progress.parts['start'] or { d.start } |
| 78 | end: cfg_progress.parts['end'] or { d.end } |
| 79 | fill: part_rune('fill', d.fill) |
| 80 | empty: part_rune('empty', d.empty) |
| 81 | } |
| 82 | } |
| 83 | d := progress.ClassicStyle{} |
| 84 | return progress.ClassicStyle{ |
| 85 | start: cfg_progress.parts['start'] or { d.start } |
| 86 | end: cfg_progress.parts['end'] or { d.end } |
| 87 | fill: part_rune('fill', d.fill) |
| 88 | // an emptied head is no head: the bar ends in its fill |
| 89 | head: if 'head' in cfg_progress.parts { part_rune('head', 0) } else { d.head } |
| 90 | empty: part_rune('empty', d.empty) |
| 91 | } |
| 92 | } |
| 93 | |
| 94 | // bar_opts dresses a bar the config's way: what a caller asks of its bar |
| 95 | // stays, and the rate is shown only where the caller has one to show |
| 96 | fn bar_opts(o progress.BarOptions) progress.BarOptions { |
| 97 | return progress.BarOptions{ |
| 98 | ...o |
| 99 | style: bar_style() |
| 100 | length: cfg_progress.length |
| 101 | show_percent: cfg_progress.percent |
| 102 | show_left: cfg_progress.eta |
| 103 | show_elapsed: cfg_progress.elapsed |
| 104 | show_rate: o.show_rate && cfg_progress.rate |
| 105 | } |
| 106 | } |
| 107 | |
| 108 | // spinner_opts dresses a spinner the config's way |
| 109 | fn spinner_opts(o progress.SpinnerOptions) progress.SpinnerOptions { |
| 110 | return progress.SpinnerOptions{ |
| 111 | ...o |
| 112 | frames: if cfg_progress.frames.len > 0 { |
| 113 | cfg_progress.frames.clone() |
| 114 | } else { |
| 115 | o.frames.clone() |
| 116 | } |
| 117 | interval: cfg_progress.interval * time.millisecond |
| 118 | done_frame: cfg_progress.done |
| 119 | show_elapsed: cfg_progress.timed |
| 120 | } |
| 121 | } |
| 122 | |
| 123 | // TransUI is a command's user interface: the shared progress display (one |
| 124 | // MultiBar that holds spinners for the command phases, download bars fed by |
| 125 | // alpm's dlcb and transaction phase bars fed by alpm's progresscb) and the |
| 126 | // prompter every question goes through, libalpm's own included. It is passed |
| 127 | // to alpm as the callback context. under --ui ipc there is no MultiBar: the |
| 128 | // same calls send events (Phase, Meter, the callbacks) |
| 129 | // every ui-bearing function spells its ui `mut ui TransUI`, the way it does |
| 130 | // for the _locked helpers: TransUI is @[heap], and a mut value parameter of |
| 131 | // one writes through, so the ui handed to a mode and the one its helpers |
| 132 | // reach are the same struct. only init_handle takes the reference spelled |
| 133 | // out, since it hands the pointer itself to libalpm |
| 134 | @[heap] |
| 135 | struct TransUI { |
| 136 | mut: |
| 137 | mb &progress.MultiBar = unsafe { nil } |
| 138 | // mu guards the fields below against libalpm's download callbacks: with |
| 139 | // parallel downloads on, dlcb arrives on several threads at once, and |
| 140 | // progresscb may join it. every method here takes mu before it touches |
| 141 | // state other callbacks or threads can see, and the _locked helpers |
| 142 | // below it are reached only with the mutex held. the bars and the |
| 143 | // multibar are drawn thread-safely by x.progress itself |
| 144 | mu &sync.Mutex = sync.new_mutex() |
| 145 | dbars map[string]&progress.Bar |
| 146 | pbar &progress.Bar = unsafe { nil } |
| 147 | pkey int |
| 148 | // dpad is the width every download bar reserves for its name, so all |
| 149 | // bars start at the same X coordinate; grows to the longest name seen |
| 150 | dpad int |
| 151 | // prompt asks the user; its noconfirm is --noconfirm, which every |
| 152 | // command that asks anything passes to new_trans_ui |
| 153 | prompt Prompter |
| 154 | // print_only (--print) answers every question silently, as pacman's |
| 155 | // --print does, so the listing on stdout stays clean |
| 156 | print_only bool |
| 157 | // download_only (install -w) fetches an ignored package without asking |
| 158 | download_only bool |
| 159 | // walking is set while install looks dependencies up for itself: the |
| 160 | // questions libalpm raises then are answered as --print answers them |
| 161 | walking bool |
| 162 | // dlast is what each download last reported under --ui ipc, so an event |
| 163 | // goes out as the percent moves or the time passes (download_due), not |
| 164 | // for every chunk; plast is the last progress event, which libalpm may |
| 165 | // send twice |
| 166 | dlast map[string]DownloadSent |
| 167 | plast ProgressEvent |
| 168 | } |
| 169 | |
| 170 | // TransUIOptions are what a command tells its TransUI |
| 171 | @[params] |
| 172 | struct TransUIOptions { |
| 173 | // noconfirm is --noconfirm: every prompt takes its default unasked |
| 174 | noconfirm bool |
| 175 | } |
| 176 | |
| 177 | // new_trans_ui makes a command's TransUI, with the prompter of the frontend |
| 178 | // --ui chose |
| 179 | fn new_trans_ui(o TransUIOptions) &TransUI { |
| 180 | return &TransUI{ |
| 181 | dbars: {} |
| 182 | prompt: if ipc_on() { |
| 183 | Prompter(IpcPrompter{ |
| 184 | noconfirm: o.noconfirm |
| 185 | }) |
| 186 | } else { |
| 187 | Prompter(TermPrompter{ |
| 188 | noconfirm: o.noconfirm |
| 189 | }) |
| 190 | } |
| 191 | } |
| 192 | } |
| 193 | |
| 194 | // group returns the live MultiBar, starting a new one if the previous one was |
| 195 | // paused for a prompt. the alpm callbacks reach the display through this |
| 196 | // struct, so they always draw on the current MultiBar |
| 197 | fn (mut ui TransUI) group() &progress.MultiBar { |
| 198 | ui.mu.lock() |
| 199 | defer { ui.mu.unlock() } |
| 200 | return ui.group_locked() |
| 201 | } |
| 202 | |
| 203 | // group_locked is group, with the ui's mutex already held: download bars and |
| 204 | // the lazy creation of the MultiBar must not race |
| 205 | fn (mut ui TransUI) group_locked() &progress.MultiBar { |
| 206 | if ui.mb == unsafe { nil } { |
| 207 | // the cursor stays visible: confirmation prompts are asked on a |
| 208 | // running display otherwise, and a hidden cursor makes them look dead |
| 209 | ui.mb = progress.MultiBar.new( |
| 210 | hide_cursor: false |
| 211 | delay: cfg_progress.delay * time.millisecond |
| 212 | ) |
| 213 | } |
| 214 | return ui.mb |
| 215 | } |
| 216 | |
| 217 | // Phase is a step a command shows while it works: a spinner on a terminal, |
| 218 | // phase events under --ui ipc |
| 219 | @[heap] |
| 220 | struct Phase { |
| 221 | mut: |
| 222 | spinner &progress.Spinner = unsafe { nil } |
| 223 | text string |
| 224 | started bool |
| 225 | done bool |
| 226 | } |
| 227 | |
| 228 | fn (mut ui TransUI) spinner(opts progress.SpinnerOptions) &Phase { |
| 229 | if ipc_on() { |
| 230 | return &Phase{ |
| 231 | text: opts.text |
| 232 | } |
| 233 | } |
| 234 | return &Phase{ |
| 235 | spinner: ui.group().add_spinner(spinner_opts(opts)) |
| 236 | text: opts.text |
| 237 | } |
| 238 | } |
| 239 | |
| 240 | fn (mut p Phase) start() { |
| 241 | if p.spinner != unsafe { nil } { |
| 242 | p.spinner.start() |
| 243 | return |
| 244 | } |
| 245 | p.started = true |
| 246 | emit(PhaseEvent{ |
| 247 | text: p.text |
| 248 | state: 'start' |
| 249 | }) |
| 250 | } |
| 251 | |
| 252 | // set_text renames the step; a running one reports the new name as a start |
| 253 | fn (mut p Phase) set_text(text string) { |
| 254 | p.text = text |
| 255 | if p.spinner != unsafe { nil } { |
| 256 | p.spinner.set_text(text) |
| 257 | return |
| 258 | } |
| 259 | if p.started && !p.done { |
| 260 | emit(PhaseEvent{ |
| 261 | text: text |
| 262 | state: 'start' |
| 263 | }) |
| 264 | } |
| 265 | } |
| 266 | |
| 267 | fn (p &Phase) is_done() bool { |
| 268 | if p.spinner != unsafe { nil } { |
| 269 | return p.spinner.is_done() |
| 270 | } |
| 271 | return p.done |
| 272 | } |
| 273 | |
| 274 | fn (mut p Phase) finish() { |
| 275 | if p.spinner != unsafe { nil } { |
| 276 | p.spinner.finish() |
| 277 | return |
| 278 | } |
| 279 | if p.done { |
| 280 | return |
| 281 | } |
| 282 | p.done = true |
| 283 | if p.started { |
| 284 | emit(PhaseEvent{ |
| 285 | text: p.text |
| 286 | state: 'done' |
| 287 | }) |
| 288 | } |
| 289 | } |
| 290 | |
| 291 | // Meter is a counted step: a bar on a terminal, progress events under |
| 292 | // --ui ipc, one each time the percent moves |
| 293 | @[heap] |
| 294 | struct Meter { |
| 295 | mut: |
| 296 | bar &progress.Bar = unsafe { nil } |
| 297 | text string |
| 298 | total i64 |
| 299 | count i64 |
| 300 | percent int = -1 |
| 301 | } |
| 302 | |
| 303 | fn (mut ui TransUI) meter(total i64, text string) &Meter { |
| 304 | if ipc_on() { |
| 305 | return &Meter{ |
| 306 | text: text |
| 307 | total: total |
| 308 | } |
| 309 | } |
| 310 | return &Meter{ |
| 311 | bar: ui.group().add_bar(total, bar_opts(text: text + ' ')) |
| 312 | text: text |
| 313 | total: total |
| 314 | } |
| 315 | } |
| 316 | |
| 317 | fn (mut m Meter) start() { |
| 318 | if m.bar != unsafe { nil } { |
| 319 | m.bar.start() |
| 320 | return |
| 321 | } |
| 322 | m.add(0) |
| 323 | } |
| 324 | |
| 325 | fn (mut m Meter) add(n i64) { |
| 326 | if m.bar != unsafe { nil } { |
| 327 | m.bar.add(n) |
| 328 | return |
| 329 | } |
| 330 | m.count += n |
| 331 | pct := if m.total > 0 { int(m.count * 100 / m.total) } else { 100 } |
| 332 | if pct != m.percent { |
| 333 | m.percent = pct |
| 334 | emit(ProgressEvent{ |
| 335 | op: m.text |
| 336 | percent: pct |
| 337 | current: int(m.count) |
| 338 | total: int(m.total) |
| 339 | }) |
| 340 | } |
| 341 | } |
| 342 | |
| 343 | // pause stops the live display before a confirmation prompt. the render |
| 344 | // thread must be gone before the prompt is written, otherwise its redraw can |
| 345 | // erase the prompt and leave the program waiting on a question nobody sees |
| 346 | fn (mut ui TransUI) pause() { |
| 347 | ui.mu.lock() |
| 348 | defer { ui.mu.unlock() } |
| 349 | if ui.mb != unsafe { nil } { |
| 350 | ui.mb.stop() |
| 351 | ui.mb = unsafe { nil } |
| 352 | } |
| 353 | ui.pbar = unsafe { nil } |
| 354 | ui.dbars = map[string]&progress.Bar{} |
| 355 | ui.dpad = 0 |
| 356 | ui.dlast = map[string]DownloadSent{} |
| 357 | ui.plast = ProgressEvent{} |
| 358 | } |
| 359 | |
| 360 | // stop ends the live display, the run over. reached with the ui's mutex, |
| 361 | // like every touch of the display's fields: a download callback creating a |
| 362 | // bar on another thread must not race the stop that tears it down |
| 363 | fn (mut ui TransUI) stop() { |
| 364 | ui.mu.lock() |
| 365 | defer { ui.mu.unlock() } |
| 366 | if ui.mb != unsafe { nil } { |
| 367 | ui.mb.stop() |
| 368 | } |
| 369 | } |
| 370 | |
| 371 | // sync asks the live display to paint right away: the finished frame of a |
| 372 | // spinner that just stopped is otherwise drawn by the next tick, which lands |
| 373 | // behind the result line the caller is about to print |
| 374 | fn (mut ui TransUI) sync() { |
| 375 | if ui.mb != unsafe { nil } { |
| 376 | ui.mb.flush() |
| 377 | } |
| 378 | } |
| 379 | |
| 380 | // stop_spinner finishes a spinner that is still running, so a command that |
| 381 | // fails or asks a question does not leave it turning on screen |
| 382 | fn stop_spinner(mut s Phase) { |
| 383 | if !s.is_done() { |
| 384 | s.finish() |
| 385 | } |
| 386 | } |
| 387 | |
| 388 | // end_frame is the stop a spinner window needs before plain printlns: the |
| 389 | // finished frame goes out right away, and the render thread is stopped. |
| 390 | // stopping the spinner alone leaves the thread drawing, and a further tick |
| 391 | // lands right inside the lines that follow (the report of verify showed it). |
| 392 | // the writes that are safe beside a live frame are the group's own println |
| 393 | // and the prompts, which reach it through ui.pause |
| 394 | fn end_frame(mut ui TransUI, mut s Phase) { |
| 395 | stop_spinner(mut s) |
| 396 | ui.sync() |
| 397 | ui.pause() |
| 398 | } |
| 399 | |
| 400 | // print_done is the transaction result line, e.g. "removed: <packages>". |
| 401 | // every command that commits a transaction reports through it |
| 402 | fn print_done(mut ui TransUI, label string, names []string) { |
| 403 | if ipc_on() { |
| 404 | emit(DoneEvent{ |
| 405 | action: label.trim_right(':') |
| 406 | packages: names |
| 407 | }) |
| 408 | return |
| 409 | } |
| 410 | ui.sync() |
| 411 | ui.group().println('${success(label)} ${names.join(' ')}') |
| 412 | } |
| 413 | |
| 414 | // say is a result line printed beside the live display, a message event |
| 415 | // under --ui ipc |
| 416 | fn (mut ui TransUI) say(text string) { |
| 417 | if ipc_on() { |
| 418 | emit(MessageEvent{ |
| 419 | text: text |
| 420 | }) |
| 421 | return |
| 422 | } |
| 423 | ui.group().println(text) |
| 424 | } |
| 425 | |
| 426 | // warn is a warning printed beside the live display, as say prints a result |
| 427 | // line: above the bars a download may still draw, never through them. under |
| 428 | // --ui ipc it is the warning message event warn() sends |
| 429 | fn (mut ui TransUI) warn(text string) { |
| 430 | if ipc_on() { |
| 431 | warn(text) |
| 432 | return |
| 433 | } |
| 434 | ui.group().println(warning(text)) |
| 435 | } |
| 436 | |
| 437 | // show_packages lists packages under a heading, the way a transaction shows |
| 438 | // the ones it removes or skips: name and version |
| 439 | fn (mut ui TransUI) show_packages(title string, pkgs []&alpm.Package) { |
| 440 | if ipc_on() { |
| 441 | emit(PackagesEvent{ |
| 442 | title: title.trim_right(':') |
| 443 | packages: pkgs.map(TransPkg{ |
| 444 | name: it.get_name() |
| 445 | version: it.get_version() |
| 446 | }) |
| 447 | }) |
| 448 | return |
| 449 | } |
| 450 | println(heading(title)) |
| 451 | println(table_text(pkgs.map(row(name_style(it.get_name()), version_style(it.get_version()))), |
| 452 | ' ', ' ')) |
| 453 | } |
| 454 | |
| 455 | fn safe_vstring(p &u8) string { |
| 456 | return if p == unsafe { nil } { '' } else { unsafe { p.vstring() } } |
| 457 | } |
| 458 | |
| 459 | // download_text pads a download bar's text to the shared name column: every |
| 460 | // bar reserves the same cells for its name (as wide as the longest name seen |
| 461 | // so far, plus the trailing space), so all bars sit at the same X coordinate |
| 462 | // whatever their filenames' lengths. when a longer name arrives later, the |
| 463 | // column widens and the running bars are re-padded in place (set_text is |
| 464 | // thread-safe); finished bars are left alone, their lines are already printed |
| 465 | // reached only with the ui's mutex held, from download_bar |
| 466 | fn (mut ui TransUI) download_text_locked(name string) string { |
| 467 | if name.len + 1 > ui.dpad { |
| 468 | ui.dpad = name.len + 1 |
| 469 | } |
| 470 | for key, mut bar in ui.dbars { |
| 471 | if bar.is_done() { |
| 472 | continue |
| 473 | } |
| 474 | bar.set_text(key + ' '.repeat(ui.dpad - key.len)) |
| 475 | } |
| 476 | return name + ' '.repeat(ui.dpad - name.len) |
| 477 | } |
| 478 | |
| 479 | // download_bar returns the display bar of one download, created on the file's |
| 480 | // first event, when its size is known; the shown group starts with it |
| 481 | // libalpm runs its dlcb on the parallel download threads, so the shared |
| 482 | // state is reached with the ui's mutex, and never the drawing itself |
| 483 | fn (mut ui TransUI) download_bar(name string, total i64, on_end string, show_rate bool) &progress.Bar { |
| 484 | ui.mu.lock() |
| 485 | defer { ui.mu.unlock() } |
| 486 | bar := ui.dbars[name] or { |
| 487 | mb := ui.group_locked() |
| 488 | b := mb.add_bar(total, bar_opts( |
| 489 | text: ui.download_text_locked(name) |
| 490 | show_rate: show_rate |
| 491 | rate_unit: progress.RateUnit.bytes_iec() |
| 492 | on_end: on_end |
| 493 | )) |
| 494 | ui.dbars[name] = b |
| 495 | mb.start() |
| 496 | b |
| 497 | } |
| 498 | return bar |
| 499 | } |
| 500 | |
| 501 | fn cb_download(ctx voidptr, filename &u8, event alpm.DownloadEventType, data voidptr) { |
| 502 | mut ui := &TransUI(ctx) |
| 503 | name := safe_vstring(filename) |
| 504 | if ipc_on() { |
| 505 | ipc_download(mut ui, name, event, data) |
| 506 | return |
| 507 | } |
| 508 | match event { |
| 509 | .init { |
| 510 | // the bar is created at the first progress event, when the |
| 511 | // download size is known |
| 512 | } |
| 513 | .progress { |
| 514 | p := unsafe { &alpm.DownloadEventProgress(data) } |
| 515 | // libalpm runs this callback on its parallel download threads: |
| 516 | // the shared display state is reached through the ui's mutex, the |
| 517 | // drawing itself is x.progress's to keep thread-safe |
| 518 | bar := ui.download_bar(name, p.total, '', true) |
| 519 | bar.set(p.downloaded) |
| 520 | } |
| 521 | .retry { |
| 522 | // libalpm moves on to the next mirror: a download that starts over |
| 523 | // starts its bar over, as pacman's dload_retry_event does, and one |
| 524 | // that resumes keeps its place |
| 525 | r := unsafe { &alpm.DownloadEventRetry(data) } |
| 526 | if r.resume == 0 { |
| 527 | ui.restart_download_bar(name) |
| 528 | } |
| 529 | } |
| 530 | .completed { |
| 531 | c := unsafe { &alpm.DownloadEventCompleted(data) } |
| 532 | // libalpm's result: 1 means the local copy met the time condition |
| 533 | // and nothing was fetched, 0 a finished download, -1 an error. a |
| 534 | // download can finish before its first progress event, so the bar |
| 535 | // may not exist yet; only result 1 is labelled up to date |
| 536 | on_end := if c.result == 1 { '${name} is up to date' } else { '' } |
| 537 | bar := ui.download_bar(name, c.total, on_end, false) |
| 538 | bar.set(c.total) |
| 539 | } |
| 540 | } |
| 541 | } |
| 542 | |
| 543 | // restart_download_bar puts a download's bar back at nothing, when libalpm |
| 544 | // starts the file over from another mirror. a bar not drawn yet has nothing |
| 545 | // to restart |
| 546 | fn (mut ui TransUI) restart_download_bar(name string) { |
| 547 | ui.mu.lock() |
| 548 | defer { ui.mu.unlock() } |
| 549 | mut bar := ui.dbars[name] or { return } |
| 550 | bar.set(0) |
| 551 | } |
| 552 | |
| 553 | // DownloadSent is what a download last reported under --ui ipc: its percent, |
| 554 | // and when, in the monotonic clock's nanoseconds |
| 555 | struct DownloadSent { |
| 556 | percent int |
| 557 | at i64 |
| 558 | } |
| 559 | |
| 560 | // download_beat is the longest a download in progress goes without an |
| 561 | // event: a large file on a slow line moves a percent in minutes, and a |
| 562 | // frontend's rate would stand still that long |
| 563 | const download_beat = i64(250 * time.millisecond) |
| 564 | |
| 565 | // download_due tells whether a progress report goes out: the first one of a |
| 566 | // download, then each time the percent moves or a beat has passed |
| 567 | fn download_due(last ?DownloadSent, percent int, now i64) bool { |
| 568 | sent := last or { return true } |
| 569 | return percent != sent.percent || now - sent.at >= download_beat |
| 570 | } |
| 571 | |
| 572 | // ipc_download reports a download as events: as its percent moves or a beat |
| 573 | // passes, once more when libalpm retries it from the next mirror, and once |
| 574 | // when it is done. the dlcb arrives on libalpm's parallel download threads, |
| 575 | // so the dedupe table is reached with the ui's mutex, and the event goes out |
| 576 | // once the lock is gone |
| 577 | fn ipc_download(mut ui TransUI, name string, event alpm.DownloadEventType, data voidptr) { |
| 578 | match event { |
| 579 | .progress { |
| 580 | p := unsafe { &alpm.DownloadEventProgress(data) } |
| 581 | pct := if p.total > 0 { int(p.downloaded * 100 / p.total) } else { 0 } |
| 582 | now := time.sys_mono_now() |
| 583 | ui.mu.lock() |
| 584 | if !download_due(ui.dlast[name] or { none }, pct, i64(now)) { |
| 585 | ui.mu.unlock() |
| 586 | return |
| 587 | } |
| 588 | ui.dlast[name] = DownloadSent{ |
| 589 | percent: pct |
| 590 | at: i64(now) |
| 591 | } |
| 592 | ui.mu.unlock() |
| 593 | emit(DownloadEvent{ |
| 594 | file: name |
| 595 | downloaded: p.downloaded |
| 596 | total: p.total |
| 597 | }) |
| 598 | } |
| 599 | .retry { |
| 600 | r := unsafe { &alpm.DownloadEventRetry(data) } |
| 601 | // what was reported is history: the next progress goes out |
| 602 | ui.mu.lock() |
| 603 | ui.dlast.delete(name) |
| 604 | ui.mu.unlock() |
| 605 | emit(DownloadEvent{ |
| 606 | file: name |
| 607 | retry: true |
| 608 | resume: r.resume != 0 |
| 609 | }) |
| 610 | } |
| 611 | .completed { |
| 612 | c := unsafe { &alpm.DownloadEventCompleted(data) } |
| 613 | emit(DownloadEvent{ |
| 614 | file: name |
| 615 | downloaded: c.total |
| 616 | total: c.total |
| 617 | done: true |
| 618 | result: int(c.result) |
| 619 | }) |
| 620 | } |
| 621 | else {} |
| 622 | } |
| 623 | } |
| 624 | |
| 625 | fn progress_verb(kind alpm.Progress) string { |
| 626 | return match kind { |
| 627 | .add_start { 'installing' } |
| 628 | .upgrade_start { 'upgrading' } |
| 629 | .downgrade_start { 'downgrading' } |
| 630 | .reinstall_start { 'reinstalling' } |
| 631 | .remove_start { 'removing' } |
| 632 | .conflicts_start { 'checking for file conflicts' } |
| 633 | .diskspace_start { 'checking available disk space' } |
| 634 | .integrity_start { 'checking package integrity' } |
| 635 | .load_start { 'loading package files' } |
| 636 | .keyring_start { 'checking keys in keyring' } |
| 637 | } |
| 638 | } |
| 639 | |
| 640 | fn cb_progress(ctx voidptr, kind alpm.Progress, pkgname &u8, percent i32, howmany uint, current uint) { |
| 641 | mut ui := &TransUI(ctx) |
| 642 | verb := progress_verb(kind) |
| 643 | name := safe_vstring(pkgname) |
| 644 | // pacman draws one bar per package for the package phases (the text is |
| 645 | // '(current/howmany) verb name' and the percent restarts for each |
| 646 | // package), and a single bar per whole-transaction check phase |
| 647 | // (conflicts, diskspace, integrity, load, keyring). libalpm also sends |
| 648 | // the final 100% event with a different `current`, so the phase bars |
| 649 | // must not be keyed on it. |
| 650 | pkg_wise := match kind { |
| 651 | .add_start, .upgrade_start, .downgrade_start, .reinstall_start, .remove_start { |
| 652 | true |
| 653 | } |
| 654 | else { |
| 655 | false |
| 656 | } |
| 657 | } |
| 658 | if ipc_on() { |
| 659 | ev := ProgressEvent{ |
| 660 | op: verb |
| 661 | pkg: if pkg_wise { name } else { '' } |
| 662 | percent: int(percent) |
| 663 | current: int(current) |
| 664 | total: int(howmany) |
| 665 | } |
| 666 | // plast guards the repeats; the shared state is touched holding the |
| 667 | // ui's mutex, and the event goes out with the lock gone |
| 668 | ui.mu.lock() |
| 669 | dup := ev == ui.plast |
| 670 | if !dup { |
| 671 | ui.plast = ev |
| 672 | } |
| 673 | ui.mu.unlock() |
| 674 | if !dup { |
| 675 | emit(ev) |
| 676 | } |
| 677 | return |
| 678 | } |
| 679 | // the key pairs the phase with the package the progress belongs to: the |
| 680 | // bar restarts when either changes. 1000003 is prime; a collision would |
| 681 | // need a transaction packaging over a million files in one phase |
| 682 | pkey := if pkg_wise { int(kind) * 1000003 + int(current) } else { int(kind) } |
| 683 | text := if !pkg_wise || name == '' { |
| 684 | '${verb} ' |
| 685 | } else { |
| 686 | '(${int(current)}/${int(howmany)}) ${verb} ${name} ' |
| 687 | } |
| 688 | ui.mu.lock() |
| 689 | defer { ui.mu.unlock() } |
| 690 | if ui.pbar == unsafe { nil } || ui.pkey != pkey { |
| 691 | ui.pkey = pkey |
| 692 | ui.pbar = ui.group_locked().add_bar(100, bar_opts(text: text)) |
| 693 | ui.group_locked().start() |
| 694 | } |
| 695 | ui.pbar.set_text(text) |
| 696 | ui.pbar.set(i64(percent)) |
| 697 | } |
| 698 | |
| 699 | // cb_question asks libalpm's questions the way pacman's frontend does, with |
| 700 | // pacman's defaults: yes to installing an ignored package, replacing a |
| 701 | // package, deleting a corrupted package file and importing a missing key; no |
| 702 | // to removing a conflicting package and to skipping packages whose |
| 703 | // dependencies cannot be resolved; the first of several providers. libalpm |
| 704 | // presets every answer to 0 before it asks, so a question left unanswered is |
| 705 | // a no, which is not pacman's default for half of them. the live display is |
| 706 | // paused first so it cannot draw over the listings, and every question goes |
| 707 | // through the ui's prompter, whose --noconfirm prints each one and takes its |
| 708 | // default. all of it follows pacman's cb_question in src/pacman/callback.c |
| 709 | fn cb_question(ctx voidptr, q &alpm.Question) { |
| 710 | mut ui := &TransUI(ctx) |
| 711 | kind := unsafe { q.type_ } |
| 712 | // --print lists the transaction and asks nothing: an ignored package and |
| 713 | // a replacement stay in the list, every other question is a no, and a |
| 714 | // provider is the first. install's own dependency walks answer the same |
| 715 | if ui.print_only || ui.walking { |
| 716 | set_answer(q, flag_answer(kind in [.install_ignorepkg, .replace_pkg])) |
| 717 | return |
| 718 | } |
| 719 | ui.pause() |
| 720 | answer := match kind { |
| 721 | .install_ignorepkg { |
| 722 | pkg := unsafe { q.install_ignorepkg.pkg } |
| 723 | // a download installs nothing, so the ignored package is fetched |
| 724 | if ui.download_only { |
| 725 | i32(1) |
| 726 | } else { |
| 727 | flag_answer(ui.yesno('${pkg.get_name()} is ignored. install it anyway?')) |
| 728 | } |
| 729 | } |
| 730 | .replace_pkg { |
| 731 | r := unsafe { q.replace } |
| 732 | old := r.oldpkg.get_name() |
| 733 | flag_answer(ui.yesno('replace ${old} with ${r.newdb.get_name()}/${r.newpkg.get_name()}?')) |
| 734 | } |
| 735 | .conflict_pkg { |
| 736 | conflict := unsafe { q.conflict.conflict } |
| 737 | kept := conflict.package1.get_name() |
| 738 | removed := conflict.package2.get_name() |
| 739 | flag_answer(ui.noyes('${kept} conflicts with ${removed}. remove ${removed}?')) |
| 740 | } |
| 741 | .corrupted_pkg { |
| 742 | c := unsafe { q.corrupted } |
| 743 | path := safe_vstring(c.filepath) |
| 744 | flag_answer(ui.yesno('${path} is corrupted (${c.reason.strerror()}). delete it?')) |
| 745 | } |
| 746 | .remove_pkgs { |
| 747 | // a sysupgrade whose packages have unresolvable dependencies: |
| 748 | // skipping them lets the rest of the upgrade go on |
| 749 | mut list := unsafe { q.remove_pkgs.packages } |
| 750 | pkgs := list.pkgs() |
| 751 | noun := if pkgs.len == 1 { 'package' } else { 'packages' } |
| 752 | ui.show_packages('${pkgs.len} ${noun} cannot be upgraded, their dependencies cannot be resolved:', |
| 753 | pkgs) |
| 754 | flag_answer(ui.noyes('skip them for this upgrade?')) |
| 755 | } |
| 756 | .select_provider { |
| 757 | sp := unsafe { q.select_provider } |
| 758 | mut list := sp.providers |
| 759 | providers := list.pkgs() |
| 760 | title := '${providers.len} providers for ${sp.depend.compute_string()}:' |
| 761 | // a frontend gets them as the choices; the terminal lists them as |
| 762 | // numbered rows first, and those are built only for it |
| 763 | choices := providers.map(provider_choice(it)) |
| 764 | if !ipc_on() { |
| 765 | println(heading(title)) |
| 766 | println(table_text(provider_rows(providers), ' ', ' ')) |
| 767 | } |
| 768 | i32(ui.choose(if ipc_on() { title.trim_right(':') } else { 'which one?' }, choices)) |
| 769 | } |
| 770 | .import_key { |
| 771 | k := unsafe { q.import_key } |
| 772 | fingerprint := safe_vstring(k.fingerprint) |
| 773 | // the uid is unknown for a db signature |
| 774 | uid := safe_vstring(k.uid) |
| 775 | key := if uid == '' { fingerprint } else { '${fingerprint}, "${uid}"' } |
| 776 | flag_answer(ui.yesno('import pgp key ${key}?')) |
| 777 | } |
| 778 | } |
| 779 | set_answer(q, answer) |
| 780 | } |
| 781 | |
| 782 | // provider_choice is a provider as a frontend's choice: repo/name version |
| 783 | fn provider_choice(pkg &alpm.Package) string { |
| 784 | repo := if db := pkg.get_db() { db.get_name() + '/' } else { '' } |
| 785 | return '${repo}${pkg.get_name()} ${pkg.get_version()}' |
| 786 | } |
| 787 | |
| 788 | // provider_rows are the providers numbered for the terminal's listing, the |
| 789 | // number the choose question asks for |
| 790 | fn provider_rows(providers []&alpm.Package) []Row { |
| 791 | mut rows := []Row{} |
| 792 | for i, pkg in providers { |
| 793 | styled := if db := pkg.get_db() { source_style(db.get_name()) + '/' } else { '' } |
| 794 | rows << row('${i + 1})', styled + name_style(pkg.get_name()), version_style(pkg.get_version())) |
| 795 | } |
| 796 | return rows |
| 797 | } |
| 798 | |
| 799 | // alpm_log_line is libalpm's log callback, its V half: alpm_log.h formats |
| 800 | // each error and warning libalpm says, and it is said to the user as |
| 801 | // pacman's cb_log says it. vpac's own dependency walks (ui.walking) look |
| 802 | // things up the transaction's prepare looks up again; what they would say |
| 803 | // is said then, once |
| 804 | @[export: 'vpac_log_line'] |
| 805 | fn alpm_log_line(ctx voidptr, level int, text &char) { |
| 806 | if ctx == unsafe { nil } || text == unsafe { nil } { |
| 807 | return |
| 808 | } |
| 809 | mut ui := unsafe { &TransUI(ctx) } |
| 810 | if ui.walking { |
| 811 | return |
| 812 | } |
| 813 | msg := unsafe { cstring_to_vstring(text) }.trim_space() |
| 814 | if msg == '' { |
| 815 | return |
| 816 | } |
| 817 | ui.alpm_said(level == alpm_log_error, msg) |
| 818 | } |
| 819 | |
| 820 | // alpm_said is a line libalpm logged: printed above any live bars (which |
| 821 | // hold it while they draw, as pacman buffers during progress), or a message |
| 822 | // event a frontend reads as a warning, an error flagged as one |
| 823 | fn (mut ui TransUI) alpm_said(is_error bool, text string) { |
| 824 | if ipc_on() { |
| 825 | emit(MessageEvent{ |
| 826 | text: text |
| 827 | warning: true |
| 828 | error: is_error |
| 829 | }) |
| 830 | return |
| 831 | } |
| 832 | line := if is_error { error_text(text) } else { warning(text) } |
| 833 | ui.mu.lock() |
| 834 | defer { ui.mu.unlock() } |
| 835 | if ui.mb != unsafe { nil } { |
| 836 | ui.mb.println(line) |
| 837 | } else { |
| 838 | eprintln(line) |
| 839 | } |
| 840 | } |
| 841 | |
| 842 | // set_answer writes a question's answer. every question struct keeps its |
| 843 | // answer right after the type, which is what libalpm's alpm_question_any_t |
| 844 | // exposes |
| 845 | fn set_answer(q &alpm.Question, answer i32) { |
| 846 | unsafe { |
| 847 | mut any := &alpm.QuestionAny(q) |
| 848 | any.answer = answer |
| 849 | } |
| 850 | } |
| 851 | |
| 852 | fn flag_answer(yes bool) i32 { |
| 853 | return if yes { 1 } else { 0 } |
| 854 | } |
| 855 | |
| 856 | // init_handle initializes alpm and attaches the progress display callbacks |
| 857 | // and the configured parallel download count |
| 858 | fn init_handle(ui &TransUI) !&alpm.Handle { |
| 859 | handle := alpm.initialize(root_path, db_path) or { |
| 860 | return error('failed to initialize alpm') |
| 861 | } |
| 862 | handle.option_set_dlcb(cb_download, voidptr(ui))! |
| 863 | handle.option_set_progresscb(cb_progress, voidptr(ui))! |
| 864 | handle.option_set_questioncb(cb_question, voidptr(ui))! |
| 865 | // libalpm's errors and warnings, which it says through this alone |
| 866 | if C.vpac_set_alpm_log(handle, voidptr(ui)) != 0 { |
| 867 | return error('could not set the log callback: ${handle.error().msg()}') |
| 868 | } |
| 869 | // the freshly calloc'd handle verifies nothing: pacman defaults to |
| 870 | // checking signature levels, so the configured level is made the |
| 871 | // handle's default for every db registered later, and for local and |
| 872 | // remote files the transaction loads (libalpm tells the two apart as |
| 873 | // pacman's SigLevel does; RemoteFileSigLevel follows SigLevel when it |
| 874 | // is not named). a file is checked at its load only, at the level of its |
| 875 | // origin (load_file_target); the remote level also decides whether a |
| 876 | // url's .sig is fetched, and the url install warns by it |
| 877 | handle.option_set_default_siglevel(cfg_siglevel)! |
| 878 | handle.option_set_local_file_siglevel(cfg_siglevel)! |
| 879 | handle.option_set_remote_file_siglevel(cfg_siglevel)! |
| 880 | // pacman's frontend sets these from the config; without a cache dir |
| 881 | // libalpm falls back to /tmp for downloads |
| 882 | for dir in cfg_cachedirs { |
| 883 | handle.option_add_cachedir(dir)! |
| 884 | } |
| 885 | // pacman's Architecture: without one libalpm's check_arch passes every |
| 886 | // package, whatever it was built for |
| 887 | handle.option_add_architecture(arch)! |
| 888 | // libalpm's own hook dir (under the root) is on the handle already; |
| 889 | // these are the config's, pacman's HookDir |
| 890 | for dir in cfg_hookdirs { |
| 891 | handle.option_add_hookdir(dir)! |
| 892 | } |
| 893 | if cfg_logfile != '' { |
| 894 | handle.option_set_logfile(cfg_logfile)! |
| 895 | } |
| 896 | if cfg_syslog { |
| 897 | handle.option_set_usesyslog(1)! |
| 898 | } |
| 899 | if cfg_gpgdir != '' { |
| 900 | handle.option_set_gpgdir(cfg_gpgdir)! |
| 901 | } |
| 902 | // the ignored packages are libalpm's to skip on upgrades, with a question |
| 903 | // for the user at the start of one |
| 904 | for name in cfg_ignore { |
| 905 | handle.option_add_ignore_pkg(name)! |
| 906 | } |
| 907 | for group in cfg_ignore_groups { |
| 908 | handle.option_add_ignore_group(group)! |
| 909 | } |
| 910 | // pacman.conf's NoUpgrade and NoExtract: globs of files an upgrade keeps |
| 911 | // (writing .pacnew beside them) and files an install never writes |
| 912 | for glob in cfg_noupgrade { |
| 913 | handle.option_add_noupgrade(glob)! |
| 914 | } |
| 915 | for glob in cfg_noextract { |
| 916 | handle.option_add_no_extract(glob)! |
| 917 | } |
| 918 | if cfg_disable_timeout { |
| 919 | handle.option_set_disable_dl_timeout(1)! |
| 920 | } |
| 921 | // pacman's DownloadUser: downloads run as this user, sandboxed. an empty |
| 922 | // one is pacman without DownloadUser, downloads as root, unsandboxed |
| 923 | if download_user != '' { |
| 924 | handle.option_set_sandboxuser(download_user) or { |
| 925 | return error('problem setting the download user "${download_user}" (user does not exist)') |
| 926 | } |
| 927 | } |
| 928 | // pacman's DisableSandboxFilesystem and DisableSandboxSyscalls: the |
| 929 | // downloader and the extraction run without either part of libalpm's |
| 930 | // sandbox. the installed libalpm has these two, not a whole-sandbox switch |
| 931 | if cfg_disable_sandbox { |
| 932 | handle.option_set_disable_sandbox_filesystem(1)! |
| 933 | handle.option_set_disable_sandbox_syscalls(1)! |
| 934 | } |
| 935 | handle.option_set_parallel_downloads(u32(parallel_downloads))! |
| 936 | return handle |
| 937 | } |
| 938 | |