copy.cpp 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. /*
  2. * Copyright (c) 2019-2021, Sergey Bugaev <bugaevc@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <AK/Assertions.h>
  7. #include <AK/ByteBuffer.h>
  8. #include <AK/String.h>
  9. #include <AK/StringBuilder.h>
  10. #include <LibCore/ArgsParser.h>
  11. #include <LibCore/File.h>
  12. #include <LibCore/System.h>
  13. #include <LibGUI/Application.h>
  14. #include <LibGUI/Clipboard.h>
  15. #include <LibMain/Main.h>
  16. #include <unistd.h>
  17. struct Options {
  18. String data;
  19. StringView type;
  20. bool clear;
  21. };
  22. static Options parse_options(Main::Arguments arguments)
  23. {
  24. const char* type = "text/plain";
  25. Vector<const char*> text;
  26. bool clear = false;
  27. Core::ArgsParser args_parser;
  28. args_parser.set_general_help("Copy text from stdin or the command-line to the clipboard.");
  29. args_parser.add_option(type, "Pick a type", "type", 't', "type");
  30. args_parser.add_option(clear, "Instead of copying, clear the clipboard", "clear", 'c');
  31. args_parser.add_positional_argument(text, "Text to copy", "text", Core::ArgsParser::Required::No);
  32. args_parser.parse(arguments);
  33. Options options;
  34. options.type = type;
  35. options.clear = clear;
  36. if (clear) {
  37. // We're not copying anything.
  38. } else if (text.is_empty()) {
  39. // Copy our stdin.
  40. auto c_stdin = Core::File::construct();
  41. bool success = c_stdin->open(
  42. STDIN_FILENO,
  43. Core::OpenMode::ReadOnly,
  44. Core::File::ShouldCloseFileDescriptor::No);
  45. VERIFY(success);
  46. auto buffer = c_stdin->read_all();
  47. dbgln("Read size {}", buffer.size());
  48. options.data = String((char*)buffer.data(), buffer.size());
  49. } else {
  50. // Copy the rest of our command-line args.
  51. StringBuilder builder;
  52. builder.join(' ', text);
  53. options.data = builder.to_string();
  54. }
  55. return options;
  56. }
  57. ErrorOr<int> serenity_main(Main::Arguments arguments)
  58. {
  59. auto app = GUI::Application::construct(arguments);
  60. Options options = parse_options(arguments);
  61. auto& clipboard = GUI::Clipboard::the();
  62. if (options.clear)
  63. clipboard.clear();
  64. else
  65. clipboard.set_data(options.data.bytes(), options.type);
  66. return 0;
  67. }