1/*
2 * Copyright (c) 2021 Huawei Device Co., Ltd.
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 *     http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16#ifndef ECMASCRIPT_TOOLING_PROTOCOL_HANDLER_H
17#define ECMASCRIPT_TOOLING_PROTOCOL_HANDLER_H
18
19#include <condition_variable>
20#include <functional>
21#include <queue>
22#include <memory>
23
24#include "protocol_channel.h"
25
26namespace panda::ecmascript::tooling {
27class ProtocolHandler final : public ProtocolChannel {
28public:
29    enum DispatchStatus : int32_t {
30        UNKNOWN = 0,
31        DISPATCHING,
32        DISPATCHED
33    };
34
35    ProtocolHandler(std::function<void(const void *, const std::string &)> callback, const EcmaVM *vm)
36        : callback_(std::move(callback)), dispatcher_(vm, this), vm_(vm) {}
37    ~ProtocolHandler() override = default;
38
39    void WaitForDebugger() override;
40    void RunIfWaitingForDebugger() override;
41    void ProcessCommand();
42    void DispatchCommand(std::string &&msg);
43    int32_t GetDispatchStatus();
44
45    void SendResponse(const DispatchRequest &request, const DispatchResponse &response,
46                      const PtBaseReturns &result) override;
47    void SendNotification(const PtBaseEvents &events) override;
48
49    std::unique_ptr<PtJson> CreateErrorReply(const DispatchResponse &response);
50    void SendReply(const PtJson &reply);
51
52private:
53    NO_MOVE_SEMANTIC(ProtocolHandler);
54    NO_COPY_SEMANTIC(ProtocolHandler);
55
56    std::function<void(const void *, const std::string &)> callback_;
57    Dispatcher dispatcher_;
58
59    bool waitingForDebugger_ {false};
60    const EcmaVM *vm_ {nullptr};
61
62    std::condition_variable requestQueueCond_;
63    std::queue<std::string> requestQueue_;
64    std::mutex requestLock_;
65    std::atomic<bool> isDispatchingMessage_ {false};
66};
67}  // namespace panda::ecmascript::tooling
68
69#endif
70