paste.cpp 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. #include <AK/String.h>
  2. #include <LibCore/CEventLoop.h>
  3. #include <LibGUI/GClipboard.h>
  4. #include <getopt.h>
  5. #include <stdio.h>
  6. #include <stdlib.h>
  7. struct Options {
  8. bool print_type { false };
  9. bool no_newline { false };
  10. };
  11. void print_usage(FILE* stream, const char* argv0)
  12. {
  13. fprintf(
  14. stream,
  15. "Usage:\n"
  16. "\t%s [--print-type] [--no-newline]\n"
  17. "\n"
  18. "\t--print-type\t\tDisplay the copied type.\n"
  19. "\t-n, --no-newline\tDo not append a newline.\n"
  20. "\t-h, --help\t\tPrint this help message.\n",
  21. argv0);
  22. }
  23. Options parse_options(int argc, char* argv[])
  24. {
  25. Options options;
  26. static struct option long_options[] = {
  27. { "print-type", no_argument, 0, 'p' },
  28. { "no-newline", no_argument, 0, 'n' },
  29. { "help", no_argument, 0, 'h' },
  30. { 0, 0, 0, 0 }
  31. };
  32. while (true) {
  33. int option_index;
  34. int c = getopt_long(argc, argv, "hn", long_options, &option_index);
  35. if (c == -1)
  36. break;
  37. if (c == 0)
  38. c = long_options[option_index].val;
  39. switch (c) {
  40. case 'p':
  41. options.print_type = true;
  42. break;
  43. case 'n':
  44. options.no_newline = true;
  45. break;
  46. case 'h':
  47. print_usage(stdout, argv[0]);
  48. exit(0);
  49. default:
  50. print_usage(stderr, argv[0]);
  51. exit(1);
  52. }
  53. }
  54. return options;
  55. }
  56. int main(int argc, char* argv[])
  57. {
  58. Options options = parse_options(argc, argv);
  59. CEventLoop loop;
  60. GClipboard& clipboard = GClipboard::the();
  61. auto data_and_type = clipboard.data_and_type();
  62. if (!options.print_type) {
  63. printf("%s", data_and_type.data.characters());
  64. // Append a newline to text contents, but
  65. // only if we're not asked not to do this.
  66. if (data_and_type.type == "text" && !options.no_newline)
  67. putchar('\n');
  68. } else {
  69. printf("%s\n", data_and_type.type.characters());
  70. }
  71. }