summaryrefslogtreecommitdiff
path: root/Userland/Libraries/LibChess/UCIEndpoint.h
blob: 87f3e00a166a8ee12ca4d793e5dd2fca4943751e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
/*
 * Copyright (c) 2020-2022, the SerenityOS developers.
 * Copyright (c) 2023, Tim Ledbetter <timledbetter@gmail.com>
 *
 * SPDX-License-Identifier: BSD-2-Clause
 */

#pragma once

#include <LibChess/UCICommand.h>
#include <LibCore/IODevice.h>
#include <LibCore/Notifier.h>
#include <LibCore/Object.h>

namespace Chess::UCI {

class Endpoint : public Core::Object {
    C_OBJECT(Endpoint)
public:
    virtual ~Endpoint() override = default;

    Function<void(DeprecatedString, Error)> on_command_read_error;

    virtual void handle_uci() { }
    virtual void handle_debug(DebugCommand const&) { }
    virtual void handle_isready() { }
    virtual void handle_setoption(SetOptionCommand const&) { }
    virtual void handle_position(PositionCommand const&) { }
    virtual void handle_go(GoCommand const&) { }
    virtual void handle_stop() { }
    virtual void handle_id(IdCommand const&) { }
    virtual void handle_uciok() { }
    virtual void handle_readyok() { }
    virtual void handle_bestmove(BestMoveCommand const&) { }
    virtual void handle_info(InfoCommand const&) { }
    virtual void handle_quit() { }
    virtual void handle_ucinewgame() { }
    virtual void handle_unexpected_eof() { }

    void send_command(Command const&);

    virtual void event(Core::Event&) override;

    Core::IODevice& in() { return *m_in; }
    Core::IODevice& out() { return *m_out; }

    void set_in(RefPtr<Core::IODevice> in)
    {
        m_in = in;
        set_in_notifier();
    }
    void set_out(RefPtr<Core::IODevice> out) { m_out = out; }

protected:
    Endpoint() = default;
    Endpoint(NonnullRefPtr<Core::IODevice> in, NonnullRefPtr<Core::IODevice> out);
    virtual void custom_event(Core::CustomEvent&) override;

private:
    enum EndpointEventType {
        UnexpectedEof
    };
    void set_in_notifier();
    ErrorOr<NonnullOwnPtr<Command>> read_command(StringView line) const;

    RefPtr<Core::IODevice> m_in;
    RefPtr<Core::IODevice> m_out;
    RefPtr<Core::Notifier> m_in_notifier;
};

}