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