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