copy.cpp 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  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 <LibGUI/Application.h>
  13. #include <LibGUI/Clipboard.h>
  14. #include <LibMain/Main.h>
  15. #include <unistd.h>
  16. struct Options {
  17. String data;
  18. StringView type;
  19. bool clear;
  20. };
  21. static ErrorOr<Options> parse_options(Main::Arguments arguments)
  22. {
  23. auto type = "text/plain"sv;
  24. Vector<StringView> text;
  25. bool clear = false;
  26. Core::ArgsParser args_parser;
  27. args_parser.set_general_help("Copy text from stdin or the command-line to the clipboard.");
  28. args_parser.add_option(type, "Pick a type", "type", 't', "type");
  29. args_parser.add_option(clear, "Instead of copying, clear the clipboard", "clear", 'c');
  30. args_parser.add_positional_argument(text, "Text to copy", "text", Core::ArgsParser::Required::No);
  31. args_parser.parse(arguments);
  32. Options options;
  33. options.type = type;
  34. options.clear = clear;
  35. if (clear) {
  36. // We're not copying anything.
  37. } else if (text.is_empty()) {
  38. // Copy our stdin.
  39. auto c_stdin = TRY(Core::File::standard_input());
  40. auto buffer = TRY(c_stdin->read_until_eof());
  41. dbgln("Read size {}", buffer.size());
  42. dbgln("Read data: `{}`", StringView(buffer.bytes()));
  43. options.data = TRY(String::from_utf8(StringView(buffer.bytes())));
  44. } else {
  45. // Copy the rest of our command-line args.
  46. StringBuilder builder;
  47. builder.join(' ', text);
  48. options.data = TRY(builder.to_string());
  49. }
  50. return options;
  51. }
  52. ErrorOr<int> serenity_main(Main::Arguments arguments)
  53. {
  54. auto app = TRY(GUI::Application::try_create(arguments));
  55. Options options = TRY(parse_options(arguments));
  56. auto& clipboard = GUI::Clipboard::the();
  57. if (options.clear)
  58. clipboard.clear();
  59. else
  60. clipboard.set_data(options.data.bytes(), options.type);
  61. return 0;
  62. }