MSVC: xz: Use _isatty() from <io.h> to implement isatty().
[xz.git] / src / xz / message.c
blob056ba5ea372d8d277e4c8d4be8f48ad7185efff4
1 ///////////////////////////////////////////////////////////////////////////////
2 //
3 /// \file message.c
4 /// \brief Printing messages
5 //
6 // Authors: Lasse Collin
7 // Jia Tan
8 //
9 // This file has been put into the public domain.
10 // You can do whatever you want with this file.
12 ///////////////////////////////////////////////////////////////////////////////
14 #include "private.h"
16 #include <stdarg.h>
18 #ifdef _MSC_VER
19 # include <io.h>
20 # define isatty _isatty
21 #endif
24 /// Number of the current file
25 static unsigned int files_pos = 0;
27 /// Total number of input files; zero if unknown.
28 static unsigned int files_total;
30 /// Verbosity level
31 static enum message_verbosity verbosity = V_WARNING;
33 /// Filename which we will print with the verbose messages
34 static const char *filename;
36 /// True once the a filename has been printed to stderr as part of progress
37 /// message. If automatic progress updating isn't enabled, this becomes true
38 /// after the first progress message has been printed due to user sending
39 /// SIGINFO, SIGUSR1, or SIGALRM. Once this variable is true, we will print
40 /// an empty line before the next filename to make the output more readable.
41 static bool first_filename_printed = false;
43 /// This is set to true when we have printed the current filename to stderr
44 /// as part of a progress message. This variable is useful only if not
45 /// updating progress automatically: if user sends many SIGINFO, SIGUSR1, or
46 /// SIGALRM signals, we won't print the name of the same file multiple times.
47 static bool current_filename_printed = false;
49 /// True if we should print progress indicator and update it automatically
50 /// if also verbose >= V_VERBOSE.
51 static bool progress_automatic;
53 /// True if message_progress_start() has been called but
54 /// message_progress_end() hasn't been called yet.
55 static bool progress_started = false;
57 /// This is true when a progress message was printed and the cursor is still
58 /// on the same line with the progress message. In that case, a newline has
59 /// to be printed before any error messages.
60 static bool progress_active = false;
62 /// Pointer to lzma_stream used to do the encoding or decoding.
63 static lzma_stream *progress_strm;
65 /// This is true if we are in passthru mode (not actually compressing or
66 /// decompressing) and thus cannot use lzma_get_progress(progress_strm, ...).
67 /// That is, we are using coder_passthru() in coder.c.
68 static bool progress_is_from_passthru;
70 /// Expected size of the input stream is needed to show completion percentage
71 /// and estimate remaining time.
72 static uint64_t expected_in_size;
75 // Use alarm() and SIGALRM when they are supported. This has two minor
76 // advantages over the alternative of polling gettimeofday():
77 // - It is possible for the user to send SIGINFO, SIGUSR1, or SIGALRM to
78 // get intermediate progress information even when --verbose wasn't used
79 // or stderr is not a terminal.
80 // - alarm() + SIGALRM seems to have slightly less overhead than polling
81 // gettimeofday().
82 #ifdef SIGALRM
84 const int message_progress_sigs[] = {
85 SIGALRM,
86 #ifdef SIGINFO
87 SIGINFO,
88 #endif
89 #ifdef SIGUSR1
90 SIGUSR1,
91 #endif
95 /// The signal handler for SIGALRM sets this to true. It is set back to false
96 /// once the progress message has been updated.
97 static volatile sig_atomic_t progress_needs_updating = false;
99 /// Signal handler for SIGALRM
100 static void
101 progress_signal_handler(int sig lzma_attribute((__unused__)))
103 progress_needs_updating = true;
104 return;
107 #else
109 /// This is true when progress message printing is wanted. Using the same
110 /// variable name as above to avoid some ifdefs.
111 static bool progress_needs_updating = false;
113 /// Elapsed time when the next progress message update should be done.
114 static uint64_t progress_next_update;
116 #endif
119 extern void
120 message_init(void)
122 // If --verbose is used, we use a progress indicator if and only
123 // if stderr is a terminal. If stderr is not a terminal, we print
124 // verbose information only after finishing the file. As a special
125 // exception, even if --verbose was not used, user can send SIGALRM
126 // to make us print progress information once without automatic
127 // updating.
128 progress_automatic = isatty(STDERR_FILENO);
130 // Commented out because COLUMNS is rarely exported to environment.
131 // Most users have at least 80 columns anyway, let's think something
132 // fancy here if enough people complain.
134 if (progress_automatic) {
135 // stderr is a terminal. Check the COLUMNS environment
136 // variable to see if the terminal is wide enough. If COLUMNS
137 // doesn't exist or it has some unparsable value, we assume
138 // that the terminal is wide enough.
139 const char *columns_str = getenv("COLUMNS");
140 if (columns_str != NULL) {
141 char *endptr;
142 const long columns = strtol(columns_str, &endptr, 10);
143 if (*endptr != '\0' || columns < 80)
144 progress_automatic = false;
149 #ifdef SIGALRM
150 // Establish the signal handlers which set a flag to tell us that
151 // progress info should be updated.
152 struct sigaction sa;
153 sigemptyset(&sa.sa_mask);
154 sa.sa_flags = 0;
155 sa.sa_handler = &progress_signal_handler;
157 for (size_t i = 0; message_progress_sigs[i] != 0; ++i)
158 if (sigaction(message_progress_sigs[i], &sa, NULL))
159 message_signal_handler();
160 #endif
162 return;
166 extern void
167 message_verbosity_increase(void)
169 if (verbosity < V_DEBUG)
170 ++verbosity;
172 return;
176 extern void
177 message_verbosity_decrease(void)
179 if (verbosity > V_SILENT)
180 --verbosity;
182 return;
186 extern enum message_verbosity
187 message_verbosity_get(void)
189 return verbosity;
193 extern void
194 message_set_files(unsigned int files)
196 files_total = files;
197 return;
201 /// Prints the name of the current file if it hasn't been printed already,
202 /// except if we are processing exactly one stream from stdin to stdout.
203 /// I think it looks nicer to not print "(stdin)" when --verbose is used
204 /// in a pipe and no other files are processed.
205 static void
206 print_filename(void)
208 if (!opt_robot && (files_total != 1 || filename != stdin_filename)) {
209 signals_block();
211 FILE *file = opt_mode == MODE_LIST ? stdout : stderr;
213 // If a file was already processed, put an empty line
214 // before the next filename to improve readability.
215 if (first_filename_printed)
216 fputc('\n', file);
218 first_filename_printed = true;
219 current_filename_printed = true;
221 // If we don't know how many files there will be due
222 // to usage of --files or --files0.
223 if (files_total == 0)
224 fprintf(file, "%s (%u)\n", filename,
225 files_pos);
226 else
227 fprintf(file, "%s (%u/%u)\n", filename,
228 files_pos, files_total);
230 signals_unblock();
233 return;
237 extern void
238 message_filename(const char *src_name)
240 // Start numbering the files starting from one.
241 ++files_pos;
242 filename = src_name;
244 if (verbosity >= V_VERBOSE
245 && (progress_automatic || opt_mode == MODE_LIST))
246 print_filename();
247 else
248 current_filename_printed = false;
250 return;
254 extern void
255 message_progress_start(lzma_stream *strm, bool is_passthru, uint64_t in_size)
257 // Store the pointer to the lzma_stream used to do the coding.
258 // It is needed to find out the position in the stream.
259 progress_strm = strm;
260 progress_is_from_passthru = is_passthru;
262 // Store the expected size of the file. If we aren't printing any
263 // statistics, then is will be unused. But since it is possible
264 // that the user sends us a signal to show statistics, we need
265 // to have it available anyway.
266 expected_in_size = in_size;
268 // Indicate that progress info may need to be printed before
269 // printing error messages.
270 progress_started = true;
272 // If progress indicator is wanted, print the filename and possibly
273 // the file count now.
274 if (verbosity >= V_VERBOSE && progress_automatic) {
275 // Start the timer to display the first progress message
276 // after one second. An alternative would be to show the
277 // first message almost immediately, but delaying by one
278 // second looks better to me, since extremely early
279 // progress info is pretty much useless.
280 #ifdef SIGALRM
281 // First disable a possibly existing alarm.
282 alarm(0);
283 progress_needs_updating = false;
284 alarm(1);
285 #else
286 progress_needs_updating = true;
287 progress_next_update = 1000;
288 #endif
291 return;
295 /// Make the string indicating completion percentage.
296 static const char *
297 progress_percentage(uint64_t in_pos)
299 // If the size of the input file is unknown or the size told us is
300 // clearly wrong since we have processed more data than the alleged
301 // size of the file, show a static string indicating that we have
302 // no idea of the completion percentage.
303 if (expected_in_size == 0 || in_pos > expected_in_size)
304 return "--- %";
306 // Never show 100.0 % before we actually are finished.
307 double percentage = (double)(in_pos) / (double)(expected_in_size)
308 * 99.9;
310 // Use big enough buffer to hold e.g. a multibyte decimal point.
311 static char buf[16];
312 snprintf(buf, sizeof(buf), "%.1f %%", percentage);
314 return buf;
318 /// Make the string containing the amount of input processed, amount of
319 /// output produced, and the compression ratio.
320 static const char *
321 progress_sizes(uint64_t compressed_pos, uint64_t uncompressed_pos, bool final)
323 // Use big enough buffer to hold e.g. a multibyte thousand separators.
324 static char buf[128];
325 char *pos = buf;
326 size_t left = sizeof(buf);
328 // Print the sizes. If this the final message, use more reasonable
329 // units than MiB if the file was small.
330 const enum nicestr_unit unit_min = final ? NICESTR_B : NICESTR_MIB;
331 my_snprintf(&pos, &left, "%s / %s",
332 uint64_to_nicestr(compressed_pos,
333 unit_min, NICESTR_TIB, false, 0),
334 uint64_to_nicestr(uncompressed_pos,
335 unit_min, NICESTR_TIB, false, 1));
337 // Avoid division by zero. If we cannot calculate the ratio, set
338 // it to some nice number greater than 10.0 so that it gets caught
339 // in the next if-clause.
340 const double ratio = uncompressed_pos > 0
341 ? (double)(compressed_pos) / (double)(uncompressed_pos)
342 : 16.0;
344 // If the ratio is very bad, just indicate that it is greater than
345 // 9.999. This way the length of the ratio field stays fixed.
346 if (ratio > 9.999)
347 snprintf(pos, left, " > %.3f", 9.999);
348 else
349 snprintf(pos, left, " = %.3f", ratio);
351 return buf;
355 /// Make the string containing the processing speed of uncompressed data.
356 static const char *
357 progress_speed(uint64_t uncompressed_pos, uint64_t elapsed)
359 // Don't print the speed immediately, since the early values look
360 // somewhat random.
361 if (elapsed < 3000)
362 return "";
364 // The first character of KiB/s, MiB/s, or GiB/s:
365 static const char unit[] = { 'K', 'M', 'G' };
367 size_t unit_index = 0;
369 // Calculate the speed as KiB/s.
370 double speed = (double)(uncompressed_pos)
371 / ((double)(elapsed) * (1024.0 / 1000.0));
373 // Adjust the unit of the speed if needed.
374 while (speed > 999.0) {
375 speed /= 1024.0;
376 if (++unit_index == ARRAY_SIZE(unit))
377 return ""; // Way too fast ;-)
380 // Use decimal point only if the number is small. Examples:
381 // - 0.1 KiB/s
382 // - 9.9 KiB/s
383 // - 99 KiB/s
384 // - 999 KiB/s
385 // Use big enough buffer to hold e.g. a multibyte decimal point.
386 static char buf[16];
387 snprintf(buf, sizeof(buf), "%.*f %ciB/s",
388 speed > 9.9 ? 0 : 1, speed, unit[unit_index]);
389 return buf;
393 /// Make a string indicating elapsed time. The format is either
394 /// M:SS or H:MM:SS depending on if the time is an hour or more.
395 static const char *
396 progress_time(uint64_t mseconds)
398 // 9999 hours = 416 days
399 static char buf[sizeof("9999:59:59")];
401 // 32-bit variable is enough for elapsed time (136 years).
402 uint32_t seconds = (uint32_t)(mseconds / 1000);
404 // Don't show anything if the time is zero or ridiculously big.
405 if (seconds == 0 || seconds > ((9999 * 60) + 59) * 60 + 59)
406 return "";
408 uint32_t minutes = seconds / 60;
409 seconds %= 60;
411 if (minutes >= 60) {
412 const uint32_t hours = minutes / 60;
413 minutes %= 60;
414 snprintf(buf, sizeof(buf),
415 "%" PRIu32 ":%02" PRIu32 ":%02" PRIu32,
416 hours, minutes, seconds);
417 } else {
418 snprintf(buf, sizeof(buf), "%" PRIu32 ":%02" PRIu32,
419 minutes, seconds);
422 return buf;
426 /// Return a string containing estimated remaining time when
427 /// reasonably possible.
428 static const char *
429 progress_remaining(uint64_t in_pos, uint64_t elapsed)
431 // Don't show the estimated remaining time when it wouldn't
432 // make sense:
433 // - Input size is unknown.
434 // - Input has grown bigger since we started (de)compressing.
435 // - We haven't processed much data yet, so estimate would be
436 // too inaccurate.
437 // - Only a few seconds has passed since we started (de)compressing,
438 // so estimate would be too inaccurate.
439 if (expected_in_size == 0 || in_pos > expected_in_size
440 || in_pos < (UINT64_C(1) << 19) || elapsed < 8000)
441 return "";
443 // Calculate the estimate. Don't give an estimate of zero seconds,
444 // since it is possible that all the input has been already passed
445 // to the library, but there is still quite a bit of output pending.
446 uint32_t remaining = (uint32_t)((double)(expected_in_size - in_pos)
447 * ((double)(elapsed) / 1000.0) / (double)(in_pos));
448 if (remaining < 1)
449 remaining = 1;
451 static char buf[sizeof("9 h 55 min")];
453 // Select appropriate precision for the estimated remaining time.
454 if (remaining <= 10) {
455 // A maximum of 10 seconds remaining.
456 // Show the number of seconds as is.
457 snprintf(buf, sizeof(buf), "%" PRIu32 " s", remaining);
459 } else if (remaining <= 50) {
460 // A maximum of 50 seconds remaining.
461 // Round up to the next multiple of five seconds.
462 remaining = (remaining + 4) / 5 * 5;
463 snprintf(buf, sizeof(buf), "%" PRIu32 " s", remaining);
465 } else if (remaining <= 590) {
466 // A maximum of 9 minutes and 50 seconds remaining.
467 // Round up to the next multiple of ten seconds.
468 remaining = (remaining + 9) / 10 * 10;
469 snprintf(buf, sizeof(buf), "%" PRIu32 " min %" PRIu32 " s",
470 remaining / 60, remaining % 60);
472 } else if (remaining <= 59 * 60) {
473 // A maximum of 59 minutes remaining.
474 // Round up to the next multiple of a minute.
475 remaining = (remaining + 59) / 60;
476 snprintf(buf, sizeof(buf), "%" PRIu32 " min", remaining);
478 } else if (remaining <= 9 * 3600 + 50 * 60) {
479 // A maximum of 9 hours and 50 minutes left.
480 // Round up to the next multiple of ten minutes.
481 remaining = (remaining + 599) / 600 * 10;
482 snprintf(buf, sizeof(buf), "%" PRIu32 " h %" PRIu32 " min",
483 remaining / 60, remaining % 60);
485 } else if (remaining <= 23 * 3600) {
486 // A maximum of 23 hours remaining.
487 // Round up to the next multiple of an hour.
488 remaining = (remaining + 3599) / 3600;
489 snprintf(buf, sizeof(buf), "%" PRIu32 " h", remaining);
491 } else if (remaining <= 9 * 24 * 3600 + 23 * 3600) {
492 // A maximum of 9 days and 23 hours remaining.
493 // Round up to the next multiple of an hour.
494 remaining = (remaining + 3599) / 3600;
495 snprintf(buf, sizeof(buf), "%" PRIu32 " d %" PRIu32 " h",
496 remaining / 24, remaining % 24);
498 } else if (remaining <= 999 * 24 * 3600) {
499 // A maximum of 999 days remaining. ;-)
500 // Round up to the next multiple of a day.
501 remaining = (remaining + 24 * 3600 - 1) / (24 * 3600);
502 snprintf(buf, sizeof(buf), "%" PRIu32 " d", remaining);
504 } else {
505 // The estimated remaining time is too big. Don't show it.
506 return "";
509 return buf;
513 /// Get how much uncompressed and compressed data has been processed.
514 static void
515 progress_pos(uint64_t *in_pos,
516 uint64_t *compressed_pos, uint64_t *uncompressed_pos)
518 uint64_t out_pos;
519 if (progress_is_from_passthru) {
520 // In passthru mode the progress info is in total_in/out but
521 // the *progress_strm itself isn't initialized and thus we
522 // cannot use lzma_get_progress().
523 *in_pos = progress_strm->total_in;
524 out_pos = progress_strm->total_out;
525 } else {
526 lzma_get_progress(progress_strm, in_pos, &out_pos);
529 // It cannot have processed more input than it has been given.
530 assert(*in_pos <= progress_strm->total_in);
532 // It cannot have produced more output than it claims to have ready.
533 assert(out_pos >= progress_strm->total_out);
535 if (opt_mode == MODE_COMPRESS) {
536 *compressed_pos = out_pos;
537 *uncompressed_pos = *in_pos;
538 } else {
539 *compressed_pos = *in_pos;
540 *uncompressed_pos = out_pos;
543 return;
547 extern void
548 message_progress_update(void)
550 if (!progress_needs_updating)
551 return;
553 // Calculate how long we have been processing this file.
554 const uint64_t elapsed = mytime_get_elapsed();
556 #ifndef SIGALRM
557 if (progress_next_update > elapsed)
558 return;
560 progress_next_update = elapsed + 1000;
561 #endif
563 // Get our current position in the stream.
564 uint64_t in_pos;
565 uint64_t compressed_pos;
566 uint64_t uncompressed_pos;
567 progress_pos(&in_pos, &compressed_pos, &uncompressed_pos);
569 // Block signals so that fprintf() doesn't get interrupted.
570 signals_block();
572 // Print the filename if it hasn't been printed yet.
573 if (!current_filename_printed)
574 print_filename();
576 // Print the actual progress message. The idea is that there is at
577 // least three spaces between the fields in typical situations, but
578 // even in rare situations there is at least one space.
579 const char *cols[5] = {
580 progress_percentage(in_pos),
581 progress_sizes(compressed_pos, uncompressed_pos, false),
582 progress_speed(uncompressed_pos, elapsed),
583 progress_time(elapsed),
584 progress_remaining(in_pos, elapsed),
586 fprintf(stderr, "\r %*s %*s %*s %10s %10s\r",
587 tuklib_mbstr_fw(cols[0], 6), cols[0],
588 tuklib_mbstr_fw(cols[1], 35), cols[1],
589 tuklib_mbstr_fw(cols[2], 9), cols[2],
590 cols[3],
591 cols[4]);
593 #ifdef SIGALRM
594 // Updating the progress info was finished. Reset
595 // progress_needs_updating to wait for the next SIGALRM.
597 // NOTE: This has to be done before alarm(1) or with (very) bad
598 // luck we could be setting this to false after the alarm has already
599 // been triggered.
600 progress_needs_updating = false;
602 if (verbosity >= V_VERBOSE && progress_automatic) {
603 // Mark that the progress indicator is active, so if an error
604 // occurs, the error message gets printed cleanly.
605 progress_active = true;
607 // Restart the timer so that progress_needs_updating gets
608 // set to true after about one second.
609 alarm(1);
610 } else {
611 // The progress message was printed because user had sent us
612 // SIGALRM. In this case, each progress message is printed
613 // on its own line.
614 fputc('\n', stderr);
616 #else
617 // When SIGALRM isn't supported and we get here, it's always due to
618 // automatic progress update. We set progress_active here too like
619 // described above.
620 assert(verbosity >= V_VERBOSE);
621 assert(progress_automatic);
622 progress_active = true;
623 #endif
625 signals_unblock();
627 return;
631 static void
632 progress_flush(bool finished)
634 if (!progress_started || verbosity < V_VERBOSE)
635 return;
637 uint64_t in_pos;
638 uint64_t compressed_pos;
639 uint64_t uncompressed_pos;
640 progress_pos(&in_pos, &compressed_pos, &uncompressed_pos);
642 // Avoid printing intermediate progress info if some error occurs
643 // in the beginning of the stream. (If something goes wrong later in
644 // the stream, it is sometimes useful to tell the user where the
645 // error approximately occurred, especially if the error occurs
646 // after a time-consuming operation.)
647 if (!finished && !progress_active
648 && (compressed_pos == 0 || uncompressed_pos == 0))
649 return;
651 progress_active = false;
653 const uint64_t elapsed = mytime_get_elapsed();
655 signals_block();
657 // When using the auto-updating progress indicator, the final
658 // statistics are printed in the same format as the progress
659 // indicator itself.
660 if (progress_automatic) {
661 const char *cols[5] = {
662 finished ? "100 %" : progress_percentage(in_pos),
663 progress_sizes(compressed_pos, uncompressed_pos, true),
664 progress_speed(uncompressed_pos, elapsed),
665 progress_time(elapsed),
666 finished ? "" : progress_remaining(in_pos, elapsed),
668 fprintf(stderr, "\r %*s %*s %*s %10s %10s\n",
669 tuklib_mbstr_fw(cols[0], 6), cols[0],
670 tuklib_mbstr_fw(cols[1], 35), cols[1],
671 tuklib_mbstr_fw(cols[2], 9), cols[2],
672 cols[3],
673 cols[4]);
674 } else {
675 // The filename is always printed.
676 fprintf(stderr, _("%s: "), filename);
678 // Percentage is printed only if we didn't finish yet.
679 if (!finished) {
680 // Don't print the percentage when it isn't known
681 // (starts with a dash).
682 const char *percentage = progress_percentage(in_pos);
683 if (percentage[0] != '-')
684 fprintf(stderr, "%s, ", percentage);
687 // Size information is always printed.
688 fprintf(stderr, "%s", progress_sizes(
689 compressed_pos, uncompressed_pos, true));
691 // The speed and elapsed time aren't always shown.
692 const char *speed = progress_speed(uncompressed_pos, elapsed);
693 if (speed[0] != '\0')
694 fprintf(stderr, ", %s", speed);
696 const char *elapsed_str = progress_time(elapsed);
697 if (elapsed_str[0] != '\0')
698 fprintf(stderr, ", %s", elapsed_str);
700 fputc('\n', stderr);
703 signals_unblock();
705 return;
709 extern void
710 message_progress_end(bool success)
712 assert(progress_started);
713 progress_flush(success);
714 progress_started = false;
715 return;
719 static void
720 vmessage(enum message_verbosity v, const char *fmt, va_list ap)
722 if (v <= verbosity) {
723 signals_block();
725 progress_flush(false);
727 // TRANSLATORS: This is the program name in the beginning
728 // of the line in messages. Usually it becomes "xz: ".
729 // This is a translatable string because French needs
730 // a space before a colon.
731 fprintf(stderr, _("%s: "), progname);
733 #ifdef __clang__
734 # pragma GCC diagnostic push
735 # pragma GCC diagnostic ignored "-Wformat-nonliteral"
736 #endif
737 vfprintf(stderr, fmt, ap);
738 #ifdef __clang__
739 # pragma GCC diagnostic pop
740 #endif
742 fputc('\n', stderr);
744 signals_unblock();
747 return;
751 extern void
752 message(enum message_verbosity v, const char *fmt, ...)
754 va_list ap;
755 va_start(ap, fmt);
756 vmessage(v, fmt, ap);
757 va_end(ap);
758 return;
762 extern void
763 message_warning(const char *fmt, ...)
765 va_list ap;
766 va_start(ap, fmt);
767 vmessage(V_WARNING, fmt, ap);
768 va_end(ap);
770 set_exit_status(E_WARNING);
771 return;
775 extern void
776 message_error(const char *fmt, ...)
778 va_list ap;
779 va_start(ap, fmt);
780 vmessage(V_ERROR, fmt, ap);
781 va_end(ap);
783 set_exit_status(E_ERROR);
784 return;
788 extern void
789 message_fatal(const char *fmt, ...)
791 va_list ap;
792 va_start(ap, fmt);
793 vmessage(V_ERROR, fmt, ap);
794 va_end(ap);
796 tuklib_exit(E_ERROR, E_ERROR, false);
800 extern void
801 message_bug(void)
803 message_fatal(_("Internal error (bug)"));
807 extern void
808 message_signal_handler(void)
810 message_fatal(_("Cannot establish signal handlers"));
814 extern const char *
815 message_strm(lzma_ret code)
817 switch (code) {
818 case LZMA_NO_CHECK:
819 return _("No integrity check; not verifying file integrity");
821 case LZMA_UNSUPPORTED_CHECK:
822 return _("Unsupported type of integrity check; "
823 "not verifying file integrity");
825 case LZMA_MEM_ERROR:
826 return strerror(ENOMEM);
828 case LZMA_MEMLIMIT_ERROR:
829 return _("Memory usage limit reached");
831 case LZMA_FORMAT_ERROR:
832 return _("File format not recognized");
834 case LZMA_OPTIONS_ERROR:
835 return _("Unsupported options");
837 case LZMA_DATA_ERROR:
838 return _("Compressed data is corrupt");
840 case LZMA_BUF_ERROR:
841 return _("Unexpected end of input");
843 case LZMA_OK:
844 case LZMA_STREAM_END:
845 case LZMA_GET_CHECK:
846 case LZMA_PROG_ERROR:
847 case LZMA_SEEK_NEEDED:
848 case LZMA_RET_INTERNAL1:
849 case LZMA_RET_INTERNAL2:
850 case LZMA_RET_INTERNAL3:
851 case LZMA_RET_INTERNAL4:
852 case LZMA_RET_INTERNAL5:
853 case LZMA_RET_INTERNAL6:
854 case LZMA_RET_INTERNAL7:
855 case LZMA_RET_INTERNAL8:
856 // Without "default", compiler will warn if new constants
857 // are added to lzma_ret, it is not too easy to forget to
858 // add the new constants to this function.
859 break;
862 return _("Internal error (bug)");
866 extern void
867 message_mem_needed(enum message_verbosity v, uint64_t memusage)
869 if (v > verbosity)
870 return;
872 // Convert memusage to MiB, rounding up to the next full MiB.
873 // This way the user can always use the displayed usage as
874 // the new memory usage limit. (If we rounded to the nearest,
875 // the user might need to +1 MiB to get high enough limit.)
876 memusage = round_up_to_mib(memusage);
878 uint64_t memlimit = hardware_memlimit_get(opt_mode);
880 // Handle the case when there is no memory usage limit.
881 // This way we don't print a weird message with a huge number.
882 if (memlimit == UINT64_MAX) {
883 message(v, _("%s MiB of memory is required. "
884 "The limiter is disabled."),
885 uint64_to_str(memusage, 0));
886 return;
889 // With US-ASCII:
890 // 2^64 with thousand separators + " MiB" suffix + '\0' = 26 + 4 + 1
891 // But there may be multibyte chars so reserve enough space.
892 char memlimitstr[128];
894 // Show the memory usage limit as MiB unless it is less than 1 MiB.
895 // This way it's easy to notice errors where one has typed
896 // --memory=123 instead of --memory=123MiB.
897 if (memlimit < (UINT32_C(1) << 20)) {
898 snprintf(memlimitstr, sizeof(memlimitstr), "%s B",
899 uint64_to_str(memlimit, 1));
900 } else {
901 // Round up just like with memusage. If this function is
902 // called for informational purposes (to just show the
903 // current usage and limit), we should never show that
904 // the usage is higher than the limit, which would give
905 // a false impression that the memory usage limit isn't
906 // properly enforced.
907 snprintf(memlimitstr, sizeof(memlimitstr), "%s MiB",
908 uint64_to_str(round_up_to_mib(memlimit), 1));
911 message(v, _("%s MiB of memory is required. The limit is %s."),
912 uint64_to_str(memusage, 0), memlimitstr);
914 return;
918 extern void
919 message_filters_show(enum message_verbosity v, const lzma_filter *filters)
921 if (v > verbosity)
922 return;
924 char *buf;
925 const lzma_ret ret = lzma_str_from_filters(&buf, filters,
926 LZMA_STR_ENCODER | LZMA_STR_GETOPT_LONG, NULL);
927 if (ret != LZMA_OK)
928 message_fatal("%s", message_strm(ret));
930 fprintf(stderr, _("%s: Filter chain: %s\n"), progname, buf);
931 free(buf);
932 return;
936 extern void
937 message_try_help(void)
939 // Print this with V_WARNING instead of V_ERROR to prevent it from
940 // showing up when --quiet has been specified.
941 message(V_WARNING, _("Try `%s --help' for more information."),
942 progname);
943 return;
947 extern void
948 message_version(void)
950 // It is possible that liblzma version is different than the command
951 // line tool version, so print both.
952 if (opt_robot) {
953 printf("XZ_VERSION=%" PRIu32 "\nLIBLZMA_VERSION=%" PRIu32 "\n",
954 LZMA_VERSION, lzma_version_number());
955 } else {
956 printf("xz (" PACKAGE_NAME ") " LZMA_VERSION_STRING "\n");
957 printf("liblzma %s\n", lzma_version_string());
960 tuklib_exit(E_SUCCESS, E_ERROR, verbosity != V_SILENT);
964 extern void
965 message_help(bool long_help)
967 printf(_("Usage: %s [OPTION]... [FILE]...\n"
968 "Compress or decompress FILEs in the .xz format.\n\n"),
969 progname);
971 // NOTE: The short help doesn't currently have options that
972 // take arguments.
973 if (long_help)
974 puts(_("Mandatory arguments to long options are mandatory "
975 "for short options too.\n"));
977 if (long_help)
978 puts(_(" Operation mode:\n"));
980 puts(_(
981 " -z, --compress force compression\n"
982 " -d, --decompress force decompression\n"
983 " -t, --test test compressed file integrity\n"
984 " -l, --list list information about .xz files"));
986 if (long_help)
987 puts(_("\n Operation modifiers:\n"));
989 puts(_(
990 " -k, --keep keep (don't delete) input files\n"
991 " -f, --force force overwrite of output file and (de)compress links\n"
992 " -c, --stdout write to standard output and don't delete input files"));
993 // NOTE: --to-stdout isn't included above because it's not
994 // the recommended spelling. It was copied from gzip but other
995 // compressors with gzip-like syntax don't support it.
997 if (long_help) {
998 puts(_(
999 " --single-stream decompress only the first stream, and silently\n"
1000 " ignore possible remaining input data"));
1001 puts(_(
1002 " --no-sparse do not create sparse files when decompressing\n"
1003 " -S, --suffix=.SUF use the suffix `.SUF' on compressed files\n"
1004 " --files[=FILE] read filenames to process from FILE; if FILE is\n"
1005 " omitted, filenames are read from the standard input;\n"
1006 " filenames must be terminated with the newline character\n"
1007 " --files0[=FILE] like --files but use the null character as terminator"));
1010 if (long_help) {
1011 puts(_("\n Basic file format and compression options:\n"));
1012 puts(_(
1013 " -F, --format=FMT file format to encode or decode; possible values are\n"
1014 " `auto' (default), `xz', `lzma', `lzip', and `raw'\n"
1015 " -C, --check=CHECK integrity check type: `none' (use with caution),\n"
1016 " `crc32', `crc64' (default), or `sha256'"));
1017 puts(_(
1018 " --ignore-check don't verify the integrity check when decompressing"));
1021 puts(_(
1022 " -0 ... -9 compression preset; default is 6; take compressor *and*\n"
1023 " decompressor memory usage into account before using 7-9!"));
1025 puts(_(
1026 " -e, --extreme try to improve compression ratio by using more CPU time;\n"
1027 " does not affect decompressor memory requirements"));
1029 puts(_(
1030 " -T, --threads=NUM use at most NUM threads; the default is 1; set to 0\n"
1031 " to use as many threads as there are processor cores"));
1033 if (long_help) {
1034 puts(_(
1035 " --block-size=SIZE\n"
1036 " start a new .xz block after every SIZE bytes of input;\n"
1037 " use this to set the block size for threaded compression"));
1038 puts(_(
1039 " --block-list=BLOCKS\n"
1040 " start a new .xz block after the given comma-separated\n"
1041 " intervals of uncompressed data; optionally, specify a\n"
1042 " filter chain number (0-9) followed by a `:' before the\n"
1043 " uncompressed data size"));
1044 puts(_(
1045 " --flush-timeout=TIMEOUT\n"
1046 " when compressing, if more than TIMEOUT milliseconds has\n"
1047 " passed since the previous flush and reading more input\n"
1048 " would block, all pending data is flushed out"
1050 puts(_( // xgettext:no-c-format
1051 " --memlimit-compress=LIMIT\n"
1052 " --memlimit-decompress=LIMIT\n"
1053 " --memlimit-mt-decompress=LIMIT\n"
1054 " -M, --memlimit=LIMIT\n"
1055 " set memory usage limit for compression, decompression,\n"
1056 " threaded decompression, or all of these; LIMIT is in\n"
1057 " bytes, % of RAM, or 0 for defaults"));
1059 puts(_(
1060 " --no-adjust if compression settings exceed the memory usage limit,\n"
1061 " give an error instead of adjusting the settings downwards"));
1064 if (long_help) {
1065 puts(_(
1066 "\n Custom filter chain for compression (alternative for using presets):"));
1068 puts(_(
1069 "\n"
1070 " --filters=FILTERS set the filter chain using the liblzma filter string\n"
1071 " syntax; use --filters-help for more information"
1074 puts(_(
1075 " --filters1=FILTERS ... --filters9=FILTERS\n"
1076 " set additional filter chains using the liblzma filter\n"
1077 " string syntax to use with --block-list"
1080 puts(_(
1081 " --filters-help display more information about the liblzma filter string\n"
1082 " syntax and exit."
1085 #if defined(HAVE_ENCODER_LZMA1) || defined(HAVE_DECODER_LZMA1) \
1086 || defined(HAVE_ENCODER_LZMA2) || defined(HAVE_DECODER_LZMA2)
1087 // TRANSLATORS: The word "literal" in "literal context bits"
1088 // means how many "context bits" to use when encoding
1089 // literals. A literal is a single 8-bit byte. It doesn't
1090 // mean "literally" here.
1091 puts(_(
1092 "\n"
1093 " --lzma1[=OPTS] LZMA1 or LZMA2; OPTS is a comma-separated list of zero or\n"
1094 " --lzma2[=OPTS] more of the following options (valid values; default):\n"
1095 " preset=PRE reset options to a preset (0-9[e])\n"
1096 " dict=NUM dictionary size (4KiB - 1536MiB; 8MiB)\n"
1097 " lc=NUM number of literal context bits (0-4; 3)\n"
1098 " lp=NUM number of literal position bits (0-4; 0)\n"
1099 " pb=NUM number of position bits (0-4; 2)\n"
1100 " mode=MODE compression mode (fast, normal; normal)\n"
1101 " nice=NUM nice length of a match (2-273; 64)\n"
1102 " mf=NAME match finder (hc3, hc4, bt2, bt3, bt4; bt4)\n"
1103 " depth=NUM maximum search depth; 0=automatic (default)"));
1104 #endif
1106 puts(_(
1107 "\n"
1108 " --x86[=OPTS] x86 BCJ filter (32-bit and 64-bit)\n"
1109 " --arm[=OPTS] ARM BCJ filter\n"
1110 " --armthumb[=OPTS] ARM-Thumb BCJ filter\n"
1111 " --arm64[=OPTS] ARM64 BCJ filter\n"
1112 " --powerpc[=OPTS] PowerPC BCJ filter (big endian only)\n"
1113 " --ia64[=OPTS] IA-64 (Itanium) BCJ filter\n"
1114 " --sparc[=OPTS] SPARC BCJ filter\n"
1115 " Valid OPTS for all BCJ filters:\n"
1116 " start=NUM start offset for conversions (default=0)"));
1118 #if defined(HAVE_ENCODER_DELTA) || defined(HAVE_DECODER_DELTA)
1119 puts(_(
1120 "\n"
1121 " --delta[=OPTS] Delta filter; valid OPTS (valid values; default):\n"
1122 " dist=NUM distance between bytes being subtracted\n"
1123 " from each other (1-256; 1)"));
1124 #endif
1127 if (long_help)
1128 puts(_("\n Other options:\n"));
1130 puts(_(
1131 " -q, --quiet suppress warnings; specify twice to suppress errors too\n"
1132 " -v, --verbose be verbose; specify twice for even more verbose"));
1134 if (long_help) {
1135 puts(_(
1136 " -Q, --no-warn make warnings not affect the exit status"));
1137 puts(_(
1138 " --robot use machine-parsable messages (useful for scripts)"));
1139 puts("");
1140 puts(_(
1141 " --info-memory display the total amount of RAM and the currently active\n"
1142 " memory usage limits, and exit"));
1143 puts(_(
1144 " -h, --help display the short help (lists only the basic options)\n"
1145 " -H, --long-help display this long help and exit"));
1146 } else {
1147 puts(_(
1148 " -h, --help display this short help and exit\n"
1149 " -H, --long-help display the long help (lists also the advanced options)"));
1152 puts(_(
1153 " -V, --version display the version number and exit"));
1155 puts(_("\nWith no FILE, or when FILE is -, read standard input.\n"));
1157 // TRANSLATORS: This message indicates the bug reporting address
1158 // for this package. Please add _another line_ saying
1159 // "Report translation bugs to <...>\n" with the email or WWW
1160 // address for translation bugs. Thanks.
1161 printf(_("Report bugs to <%s> (in English or Finnish).\n"),
1162 PACKAGE_BUGREPORT);
1163 printf(_("%s home page: <%s>\n"), PACKAGE_NAME, PACKAGE_URL);
1165 #if LZMA_VERSION_STABILITY != LZMA_VERSION_STABILITY_STABLE
1166 puts(_(
1167 "THIS IS A DEVELOPMENT VERSION NOT INTENDED FOR PRODUCTION USE."));
1168 #endif
1170 tuklib_exit(E_SUCCESS, E_ERROR, verbosity != V_SILENT);
1174 extern void
1175 message_filters_help(void)
1177 char *encoder_options;
1178 if (lzma_str_list_filters(&encoder_options, LZMA_VLI_UNKNOWN,
1179 LZMA_STR_ENCODER, NULL) != LZMA_OK)
1180 message_bug();
1182 if (!opt_robot) {
1183 puts(_(
1184 "Filter chains are set using the --filters=FILTERS or\n"
1185 "--filters1=FILTERS ... --filters9=FILTERS options. Each filter in the chain\n"
1186 "can be separated by spaces or `--'. Alternatively a preset <0-9>[e] can be\n"
1187 "specified instead of a filter chain.\n"
1190 puts(_("The supported filters and their options are:"));
1193 puts(encoder_options);
1195 tuklib_exit(E_SUCCESS, E_ERROR, verbosity != V_SILENT);