ui.c 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. /* ui.c - Functions for handling the UI interface
  2. Copyright (C) 2013 Manoel Trapier <godzil@godzil.net>
  3. This program is free software: you can redistribute it and/or modify
  4. it under the terms of the GNU General Public License as published by
  5. the Free Software Foundation, either version 3 of the License, or
  6. (at your option) any later version.
  7. This program is distributed in the hope that it will be useful,
  8. but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. GNU General Public License for more details.
  11. You should have received a copy of the GNU General Public License
  12. along with this program. If not, see <http://www.gnu.org/licenses/>.
  13. On Debian systems, the complete text of the GNU General Public License
  14. can be found in /usr/share/common-licenses/GPL-3 file.
  15. */
  16. #include <stdio.h>
  17. #include <stdlib.h>
  18. #include <stdint.h>
  19. #include <string.h>
  20. #include <limits.h>
  21. #include <time.h>
  22. #include <unistd.h>
  23. #define MAX_BAR (50)
  24. int output_ui_fd, output_ui;
  25. static uint16_t current_pass = 0;
  26. static const char rotator[] = "|/-\\";
  27. static char *cur_device;
  28. static void ui_print_text(char *text)
  29. {
  30. if (output_ui == 1) {
  31. if (output_ui_fd < 0) {
  32. write(-output_ui_fd, text, strlen(text));
  33. fsync(-output_ui_fd);
  34. }
  35. else if (output_ui_fd == 0) {
  36. write(1, text, strlen(text));
  37. fsync(1);
  38. }
  39. else {
  40. write(output_ui_fd, text, strlen(text));
  41. fsync(output_ui_fd);
  42. }
  43. }
  44. }
  45. void ui_print_new_pass(char *text)
  46. {
  47. if (output_ui == 1)
  48. {
  49. char buffer[256];
  50. current_pass++;
  51. sprintf(buffer, "Pass %d: %s\n", current_pass, text);
  52. ui_print_text(buffer);
  53. }
  54. }
  55. void ui_print_progress(int pos, int max)
  56. {
  57. if (output_ui == 1)
  58. {
  59. char buffer[256];
  60. static uint8_t last_car = 0;
  61. if (output_ui_fd == 0) {
  62. double percent = ((double)pos / (double)max) * 100.0;
  63. char bar[60];
  64. uint32_t nbbar = (pos * MAX_BAR) / max;
  65. uint32_t i;
  66. memset(bar, 0, 60);
  67. for(i = 0 ; i < MAX_BAR ; i++) {
  68. if (i < nbbar)
  69. bar[i] = '=';
  70. else bar[i] = ' ';
  71. }
  72. sprintf(buffer, "|%s %c %2.1f%%\r", bar, rotator[last_car], percent);
  73. last_car = (last_car + 1) % 4;
  74. }
  75. else {
  76. sprintf(buffer, "%d %d %d %s\n", current_pass, pos, max, cur_device);
  77. }
  78. ui_print_text(buffer);
  79. }
  80. }
  81. void ui_set_device(char *device)
  82. {
  83. cur_device = device;
  84. }