1/*
2 * Copyright (c) 2023 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#include "ClipboardHelper.h"
17#include <string>
18#include <windows.h>
19#include "StringHelper.h"
20
21void ClipboardHelper::SetClipboardData(const std::string& data)
22{
23    std::string newData = StringHelper::Utf8ToString(data);
24    OpenClipboard(NULL);
25    EmptyClipboard();
26    HANDLE hHandle = GlobalAlloc(GMEM_FIXED, newData.size() + 1);
27    char* pData = (char*)GlobalLock(hHandle);
28    copy(newData.begin(), newData.end(), pData);
29    ::SetClipboardData(CF_TEXT, hHandle);
30    GlobalUnlock(hHandle);
31    CloseClipboard();
32}
33
34const std::string ClipboardHelper::GetClipboardData()
35{
36    std::string data;
37    if (!IsClipboardFormatAvailable(CF_TEXT)) {
38        return data;
39    }
40    OpenClipboard(NULL);
41    HANDLE h = ::GetClipboardData(CF_TEXT);
42    char* p = (char*)GlobalLock(h);
43    std::string str(p);
44    data = str;
45    GlobalUnlock(h);
46    CloseClipboard();
47    StringHelper::Encode encode = StringHelper::DetectEncode((uint8_t*)str.c_str(), str.size());
48    if (encode == StringHelper::Encode::ANSI) {
49        data = StringHelper::StringToUtf8(data);
50    }
51    return data;
52}