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