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