mirror of
https://github.com/kunkundi/crossdesk.git
synced 2026-03-25 10:01:18 +08:00
Compare commits
4 Commits
a5a3bfc201
...
5f320af6e6
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
5f320af6e6 | ||
|
|
17b7ba6b72 | ||
|
|
c70ebdfe15 | ||
|
|
a3e564f160 |
File diff suppressed because it is too large
Load Diff
@@ -187,6 +187,17 @@ static std::vector<std::string> takes_effect_after_restart = {
|
||||
"Takes effect after restart"};
|
||||
static std::vector<std::string> select_file = {
|
||||
reinterpret_cast<const char*>(u8"选择文件"), "Select File"};
|
||||
static std::vector<std::string> file_transfer_progress = {
|
||||
reinterpret_cast<const char*>(u8"文件传输进度"), "File Transfer Progress"};
|
||||
static std::vector<std::string> queued = {
|
||||
reinterpret_cast<const char*>(u8"队列中"), "Queued"};
|
||||
static std::vector<std::string> sending = {
|
||||
reinterpret_cast<const char*>(u8"正在传输"), "Sending"};
|
||||
static std::vector<std::string> completed = {
|
||||
reinterpret_cast<const char*>(u8"已完成"), "Completed"};
|
||||
static std::vector<std::string> failed = {
|
||||
reinterpret_cast<const char*>(u8"失败"), "Failed"};
|
||||
|
||||
#if _WIN32
|
||||
static std::vector<std::string> minimize_to_tray = {
|
||||
reinterpret_cast<const char*>(u8"退出时最小化到系统托盘:"),
|
||||
|
||||
@@ -209,6 +209,7 @@ int Render::ConnectTo(const std::string& remote_id, const char* password,
|
||||
AddDataStream(props->peer_, props->data_label_.c_str(), false);
|
||||
AddDataStream(props->peer_, props->file_label_.c_str(), true);
|
||||
AddDataStream(props->peer_, props->file_feedback_label_.c_str(), true);
|
||||
AddDataStream(props->peer_, props->clipboard_label_.c_str(), true);
|
||||
|
||||
props->connection_status_ = ConnectionStatus::Connecting;
|
||||
|
||||
|
||||
@@ -9,9 +9,11 @@
|
||||
#include <thread>
|
||||
|
||||
#include "OPPOSans_Regular.h"
|
||||
#include "clipboard.h"
|
||||
#include "device_controller_factory.h"
|
||||
#include "fa_regular_400.h"
|
||||
#include "fa_solid_900.h"
|
||||
#include "file_transfer.h"
|
||||
#include "layout_relative.h"
|
||||
#include "localization.h"
|
||||
#include "platform.h"
|
||||
@@ -716,6 +718,7 @@ int Render::CreateConnectionPeer() {
|
||||
AddDataStream(peer_, data_label_.c_str(), false);
|
||||
AddDataStream(peer_, file_label_.c_str(), true);
|
||||
AddDataStream(peer_, file_feedback_label_.c_str(), true);
|
||||
AddDataStream(peer_, clipboard_label_.c_str(), true);
|
||||
return 0;
|
||||
} else {
|
||||
return -1;
|
||||
@@ -1266,6 +1269,26 @@ void Render::InitializeModules() {
|
||||
keyboard_capturer_ = (KeyboardCapturer*)device_controller_factory_->Create(
|
||||
DeviceControllerFactory::Device::Keyboard);
|
||||
CreateConnectionPeer();
|
||||
|
||||
// start clipboard monitoring with callback to send data to peers
|
||||
Clipboard::StartMonitoring(
|
||||
100, [this](const char* data, size_t size) -> int {
|
||||
// send clipboard data to all connected peers
|
||||
std::shared_lock lock(client_properties_mutex_);
|
||||
int ret = -1;
|
||||
for (const auto& [remote_id, props] : client_properties_) {
|
||||
if (props && props->peer_ && props->connection_established_) {
|
||||
ret = SendReliableDataFrame(props->peer_, data, size,
|
||||
props->clipboard_label_.c_str());
|
||||
if (ret != 0) {
|
||||
LOG_WARN("Failed to send clipboard data to peer [{}], ret={}",
|
||||
remote_id.c_str(), ret);
|
||||
}
|
||||
}
|
||||
}
|
||||
return ret;
|
||||
});
|
||||
|
||||
modules_inited_ = true;
|
||||
}
|
||||
}
|
||||
@@ -1397,6 +1420,8 @@ void Render::HandleStreamWindow() {
|
||||
}
|
||||
|
||||
void Render::Cleanup() {
|
||||
Clipboard::StopMonitoring();
|
||||
|
||||
if (screen_capturer_) {
|
||||
screen_capturer_->Destroy();
|
||||
delete screen_capturer_;
|
||||
@@ -1544,6 +1569,166 @@ void Render::CleanSubStreamWindowProperties(
|
||||
}
|
||||
}
|
||||
|
||||
void Render::StartFileTransfer(std::shared_ptr<SubStreamWindowProperties> props,
|
||||
const std::filesystem::path& file_path,
|
||||
const std::string& file_label) {
|
||||
if (!props || !props->peer_) {
|
||||
LOG_ERROR("StartFileTransfer: invalid props or peer");
|
||||
return;
|
||||
}
|
||||
|
||||
bool expected = false;
|
||||
if (!props->file_sending_.compare_exchange_strong(expected, true)) {
|
||||
// Already sending, this should not happen if called correctly
|
||||
LOG_WARN(
|
||||
"StartFileTransfer called but file_sending_ is already true, "
|
||||
"file should have been queued: {}",
|
||||
file_path.filename().string().c_str());
|
||||
return;
|
||||
}
|
||||
|
||||
auto peer = props->peer_;
|
||||
auto props_weak = std::weak_ptr<SubStreamWindowProperties>(props);
|
||||
Render* render_ptr = this;
|
||||
|
||||
std::thread([peer, file_path, file_label, props_weak, render_ptr]() {
|
||||
auto props_locked = props_weak.lock();
|
||||
if (!props_locked) {
|
||||
return;
|
||||
}
|
||||
|
||||
std::error_code ec;
|
||||
uint64_t total_size = std::filesystem::file_size(file_path, ec);
|
||||
if (ec) {
|
||||
LOG_ERROR("Failed to get file size: {}", ec.message().c_str());
|
||||
props_locked->file_sending_ = false;
|
||||
return;
|
||||
}
|
||||
|
||||
props_locked->file_sent_bytes_ = 0;
|
||||
props_locked->file_total_bytes_ = total_size;
|
||||
props_locked->file_send_rate_bps_ = 0;
|
||||
props_locked->file_transfer_window_visible_ = true;
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(props_locked->file_transfer_mutex_);
|
||||
props_locked->file_send_start_time_ = std::chrono::steady_clock::now();
|
||||
props_locked->file_send_last_update_time_ =
|
||||
props_locked->file_send_start_time_;
|
||||
props_locked->file_send_last_bytes_ = 0;
|
||||
}
|
||||
|
||||
LOG_INFO(
|
||||
"File transfer started: {} ({} bytes), file_sending_={}, "
|
||||
"total_bytes_={}",
|
||||
file_path.filename().string(), total_size,
|
||||
props_locked->file_sending_.load(),
|
||||
props_locked->file_total_bytes_.load());
|
||||
|
||||
FileSender sender;
|
||||
uint32_t file_id = FileSender::NextFileId();
|
||||
|
||||
{
|
||||
std::lock_guard<std::shared_mutex> lock(
|
||||
render_ptr->file_id_to_props_mutex_);
|
||||
render_ptr->file_id_to_props_[file_id] = props_weak;
|
||||
}
|
||||
|
||||
props_locked->current_file_id_ = file_id;
|
||||
|
||||
// Update file transfer list: mark as sending
|
||||
// Find the queued file that matches the exact file path
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(props_locked->file_transfer_list_mutex_);
|
||||
for (auto& info : props_locked->file_transfer_list_) {
|
||||
if (info.file_path == file_path &&
|
||||
info.status ==
|
||||
SubStreamWindowProperties::FileTransferStatus::Queued) {
|
||||
info.status = SubStreamWindowProperties::FileTransferStatus::Sending;
|
||||
info.file_id = file_id;
|
||||
info.file_size = total_size;
|
||||
info.sent_bytes = 0;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
props_locked->file_transfer_window_visible_ = true;
|
||||
|
||||
// Progress will be updated via ACK from receiver
|
||||
int ret = sender.SendFile(
|
||||
file_path, file_path.filename().string(),
|
||||
[peer, file_label](const char* buf, size_t sz) -> int {
|
||||
return SendReliableDataFrame(peer, buf, sz, file_label.c_str());
|
||||
},
|
||||
64 * 1024, file_id);
|
||||
|
||||
// file_sending_ should remain true until we receive the final ACK from
|
||||
// receiver
|
||||
auto props_locked_final = props_weak.lock();
|
||||
if (props_locked_final) {
|
||||
// On error, set file_sending_ to false immediately to allow next file
|
||||
if (ret != 0) {
|
||||
props_locked_final->file_sending_ = false;
|
||||
props_locked_final->file_transfer_window_visible_ = false;
|
||||
props_locked_final->file_sent_bytes_ = 0;
|
||||
props_locked_final->file_total_bytes_ = 0;
|
||||
props_locked_final->file_send_rate_bps_ = 0;
|
||||
props_locked_final->current_file_id_ = 0;
|
||||
|
||||
// Unregister file_id mapping on error
|
||||
{
|
||||
std::lock_guard<std::shared_mutex> lock(
|
||||
render_ptr->file_id_to_props_mutex_);
|
||||
render_ptr->file_id_to_props_.erase(file_id);
|
||||
}
|
||||
|
||||
// Update file transfer list: mark as failed
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(
|
||||
props_locked_final->file_transfer_list_mutex_);
|
||||
for (auto& info : props_locked_final->file_transfer_list_) {
|
||||
if (info.file_id == file_id) {
|
||||
info.status =
|
||||
SubStreamWindowProperties::FileTransferStatus::Failed;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
LOG_ERROR("FileSender::SendFile failed for [{}], ret={}",
|
||||
file_path.string().c_str(), ret);
|
||||
|
||||
render_ptr->ProcessFileQueue(props_locked_final);
|
||||
}
|
||||
}
|
||||
}).detach();
|
||||
}
|
||||
|
||||
void Render::ProcessFileQueue(
|
||||
std::shared_ptr<SubStreamWindowProperties> props) {
|
||||
if (!props) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (props->file_sending_.load()) {
|
||||
return;
|
||||
}
|
||||
|
||||
SubStreamWindowProperties::QueuedFile queued_file;
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(props->file_queue_mutex_);
|
||||
if (props->file_send_queue_.empty()) {
|
||||
return;
|
||||
}
|
||||
queued_file = props->file_send_queue_.front();
|
||||
props->file_send_queue_.pop();
|
||||
}
|
||||
|
||||
LOG_INFO("Processing next file in queue: {}",
|
||||
queued_file.file_path.string().c_str());
|
||||
StartFileTransfer(props, queued_file.file_path, queued_file.file_label);
|
||||
}
|
||||
|
||||
void Render::UpdateRenderRect() {
|
||||
// std::shared_lock lock(client_properties_mutex_);
|
||||
for (auto& [_, props] : client_properties_) {
|
||||
|
||||
@@ -11,10 +11,12 @@
|
||||
|
||||
#include <atomic>
|
||||
#include <chrono>
|
||||
#include <filesystem>
|
||||
#include <fstream>
|
||||
#include <mutex>
|
||||
#include <nlohmann/json.hpp>
|
||||
#include <optional>
|
||||
#include <queue>
|
||||
#include <shared_mutex>
|
||||
#include <string>
|
||||
#include <unordered_map>
|
||||
@@ -47,6 +49,7 @@ class Render {
|
||||
std::string data_label_ = "control_data";
|
||||
std::string file_label_ = "file";
|
||||
std::string file_feedback_label_ = "file_feedback";
|
||||
std::string clipboard_label_ = "clipboard";
|
||||
std::string local_id_ = "";
|
||||
std::string remote_id_ = "";
|
||||
bool exit_ = false;
|
||||
@@ -129,16 +132,34 @@ class Render {
|
||||
std::atomic<bool> file_sending_ = false;
|
||||
std::atomic<uint64_t> file_sent_bytes_ = 0;
|
||||
std::atomic<uint64_t> file_total_bytes_ = 0;
|
||||
std::atomic<uint32_t> file_send_rate_bps_ = 0; // bytes per second
|
||||
std::string file_sending_name_ = "";
|
||||
std::atomic<uint32_t> file_send_rate_bps_ = 0;
|
||||
std::mutex file_transfer_mutex_;
|
||||
std::chrono::steady_clock::time_point file_send_start_time_;
|
||||
std::chrono::steady_clock::time_point file_send_last_update_time_;
|
||||
uint64_t file_send_last_bytes_ = 0;
|
||||
bool file_transfer_window_visible_ = false;
|
||||
bool file_transfer_completed_ = false;
|
||||
std::atomic<uint32_t> current_file_id_{
|
||||
0}; // Track current file transfer ID
|
||||
std::atomic<uint32_t> current_file_id_{0};
|
||||
|
||||
struct QueuedFile {
|
||||
std::filesystem::path file_path;
|
||||
std::string file_label;
|
||||
};
|
||||
std::queue<QueuedFile> file_send_queue_;
|
||||
std::mutex file_queue_mutex_;
|
||||
|
||||
enum class FileTransferStatus { Queued, Sending, Completed, Failed };
|
||||
|
||||
struct FileTransferInfo {
|
||||
std::string file_name;
|
||||
std::filesystem::path file_path;
|
||||
uint64_t file_size = 0;
|
||||
FileTransferStatus status = FileTransferStatus::Queued;
|
||||
uint64_t sent_bytes = 0;
|
||||
uint32_t file_id = 0;
|
||||
uint32_t rate_bps = 0;
|
||||
};
|
||||
std::vector<FileTransferInfo> file_transfer_list_;
|
||||
std::mutex file_transfer_list_mutex_;
|
||||
};
|
||||
|
||||
public:
|
||||
@@ -280,6 +301,12 @@ class Render {
|
||||
|
||||
int CreateConnectionPeer();
|
||||
|
||||
// File transfer helper functions
|
||||
void StartFileTransfer(std::shared_ptr<SubStreamWindowProperties> props,
|
||||
const std::filesystem::path& file_path,
|
||||
const std::string& file_label);
|
||||
void ProcessFileQueue(std::shared_ptr<SubStreamWindowProperties> props);
|
||||
|
||||
int AudioDeviceInit();
|
||||
int AudioDeviceDestroy();
|
||||
|
||||
@@ -489,6 +516,7 @@ class Render {
|
||||
std::string control_data_label_ = "control_data";
|
||||
std::string file_label_ = "file";
|
||||
std::string file_feedback_label_ = "file_feedback";
|
||||
std::string clipboard_label_ = "clipboard";
|
||||
Params params_;
|
||||
// Map file_id to props for tracking file transfer progress via ACK
|
||||
std::unordered_map<uint32_t, std::weak_ptr<SubStreamWindowProperties>>
|
||||
|
||||
@@ -6,6 +6,7 @@
|
||||
#include <fstream>
|
||||
#include <unordered_map>
|
||||
|
||||
#include "clipboard.h"
|
||||
#include "device_controller.h"
|
||||
#include "file_transfer.h"
|
||||
#include "localization.h"
|
||||
@@ -327,6 +328,14 @@ void Render::OnReceiveDataBufferCb(const char* data, size_t size,
|
||||
|
||||
receiver.OnData(data, size);
|
||||
return;
|
||||
} else if (source_id == render->clipboard_label_) {
|
||||
if (size > 0) {
|
||||
std::string clipboard_text(data, size);
|
||||
if (!Clipboard::SetText(clipboard_text)) {
|
||||
LOG_ERROR("Failed to set clipboard content from remote");
|
||||
}
|
||||
}
|
||||
return;
|
||||
} else if (source_id == render->file_feedback_label_) {
|
||||
if (size < sizeof(FileTransferAck)) {
|
||||
LOG_ERROR("FileTransferAck: buffer too small, size={}", size);
|
||||
@@ -361,10 +370,46 @@ void Render::OnReceiveDataBufferCb(const char* data, size_t size,
|
||||
props->file_sent_bytes_ = ack.acked_offset;
|
||||
props->file_total_bytes_ = ack.total_size;
|
||||
|
||||
uint32_t rate_bps = 0;
|
||||
{
|
||||
uint32_t data_channel_bitrate =
|
||||
props->net_traffic_stats_.data_outbound_stats.bitrate;
|
||||
|
||||
if (data_channel_bitrate > 0 && props->file_sending_.load()) {
|
||||
rate_bps = static_cast<uint32_t>(data_channel_bitrate * 0.99f);
|
||||
|
||||
uint32_t current_rate = props->file_send_rate_bps_.load();
|
||||
if (current_rate > 0) {
|
||||
// 70% old + 30% new for smoother display
|
||||
rate_bps = static_cast<uint32_t>(current_rate * 0.7 + rate_bps * 0.3);
|
||||
}
|
||||
} else {
|
||||
rate_bps = props->file_send_rate_bps_.load();
|
||||
}
|
||||
|
||||
props->file_send_rate_bps_ = rate_bps;
|
||||
props->file_send_last_bytes_ = ack.acked_offset;
|
||||
auto now = std::chrono::steady_clock::now();
|
||||
props->file_send_last_update_time_ = now;
|
||||
}
|
||||
|
||||
// Update file transfer list: update progress and rate
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(props->file_transfer_list_mutex_);
|
||||
for (auto& info : props->file_transfer_list_) {
|
||||
if (info.file_id == ack.file_id) {
|
||||
info.sent_bytes = ack.acked_offset;
|
||||
info.file_size = ack.total_size;
|
||||
info.rate_bps = rate_bps;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Check if transfer is completed
|
||||
if ((ack.flags & 0x01) != 0) {
|
||||
// Transfer completed - receiver has finished receiving the file
|
||||
props->file_transfer_completed_ = true;
|
||||
// Reopen window if it was closed by user
|
||||
props->file_transfer_window_visible_ = true;
|
||||
props->file_sending_ = false; // Mark sending as finished
|
||||
LOG_INFO(
|
||||
@@ -372,31 +417,28 @@ void Render::OnReceiveDataBufferCb(const char* data, size_t size,
|
||||
"acked_offset={}",
|
||||
ack.file_id, ack.total_size, ack.acked_offset);
|
||||
|
||||
// Update file transfer list: mark as completed
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(props->file_transfer_list_mutex_);
|
||||
for (auto& info : props->file_transfer_list_) {
|
||||
if (info.file_id == ack.file_id) {
|
||||
info.status =
|
||||
SubStreamWindowProperties::FileTransferStatus::Completed;
|
||||
info.sent_bytes = ack.total_size;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Unregister file_id mapping after completion
|
||||
{
|
||||
std::lock_guard<std::shared_mutex> lock(
|
||||
render->file_id_to_props_mutex_);
|
||||
render->file_id_to_props_.erase(ack.file_id);
|
||||
}
|
||||
}
|
||||
|
||||
// Update rate calculation
|
||||
auto now = std::chrono::steady_clock::now();
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(props->file_transfer_mutex_);
|
||||
auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
|
||||
now - props->file_send_last_update_time_)
|
||||
.count();
|
||||
|
||||
if (elapsed >= 100) {
|
||||
uint64_t bytes_sent_since_last =
|
||||
ack.acked_offset - props->file_send_last_bytes_;
|
||||
uint32_t rate_bps =
|
||||
static_cast<uint32_t>((bytes_sent_since_last * 8 * 1000) / elapsed);
|
||||
props->file_send_rate_bps_ = rate_bps;
|
||||
props->file_send_last_bytes_ = ack.acked_offset;
|
||||
props->file_send_last_update_time_ = now;
|
||||
}
|
||||
// Process next file in queue
|
||||
render->ProcessFileQueue(props);
|
||||
}
|
||||
|
||||
return;
|
||||
|
||||
@@ -207,113 +207,67 @@ int Render::ControlBar(std::shared_ptr<SubStreamWindowProperties>& props) {
|
||||
if (!path.empty()) {
|
||||
LOG_INFO("Selected file: {}", path.c_str());
|
||||
|
||||
// Send selected file over file data channel in a background thread.
|
||||
auto peer = props->peer_;
|
||||
props->file_sending_ = true;
|
||||
std::filesystem::path file_path = std::filesystem::path(path);
|
||||
std::string file_label = file_label_;
|
||||
auto props_weak = std::weak_ptr<SubStreamWindowProperties>(props);
|
||||
Render* render_ptr = this;
|
||||
|
||||
std::thread([peer, file_path, file_label, props_weak, render_ptr]() {
|
||||
auto props_locked = props_weak.lock();
|
||||
if (!props_locked) {
|
||||
return;
|
||||
}
|
||||
// Get file size
|
||||
std::error_code ec;
|
||||
uint64_t file_size = std::filesystem::file_size(file_path, ec);
|
||||
if (ec) {
|
||||
LOG_ERROR("Failed to get file size: {}", ec.message().c_str());
|
||||
file_size = 0;
|
||||
}
|
||||
|
||||
// Initialize file transfer progress
|
||||
std::error_code ec;
|
||||
uint64_t total_size = std::filesystem::file_size(file_path, ec);
|
||||
if (ec) {
|
||||
LOG_ERROR("Failed to get file size: {}", ec.message().c_str());
|
||||
return;
|
||||
}
|
||||
// Add file to transfer list
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(props->file_transfer_list_mutex_);
|
||||
SubStreamWindowProperties::FileTransferInfo info;
|
||||
info.file_name = file_path.filename().string();
|
||||
info.file_path = file_path; // Store full path for precise matching
|
||||
info.file_size = file_size;
|
||||
info.status = SubStreamWindowProperties::FileTransferStatus::Queued;
|
||||
info.sent_bytes = 0;
|
||||
info.file_id = 0;
|
||||
info.rate_bps = 0;
|
||||
props->file_transfer_list_.push_back(info);
|
||||
}
|
||||
props->file_transfer_window_visible_ = true;
|
||||
|
||||
// Set file transfer status (atomic variables don't need mutex)
|
||||
props_locked->file_sending_ = true;
|
||||
props_locked->file_sent_bytes_ = 0;
|
||||
props_locked->file_total_bytes_ = total_size;
|
||||
props_locked->file_send_rate_bps_ = 0;
|
||||
props_locked->file_transfer_window_visible_ = true;
|
||||
props_locked->file_transfer_completed_ = false;
|
||||
if (props->file_sending_.load()) {
|
||||
// Add to queue
|
||||
size_t queue_size = 0;
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(
|
||||
props_locked->file_transfer_mutex_);
|
||||
props_locked->file_sending_name_ = file_path.filename().string();
|
||||
std::lock_guard<std::mutex> lock(props->file_queue_mutex_);
|
||||
SubStreamWindowProperties::QueuedFile queued_file;
|
||||
queued_file.file_path = file_path;
|
||||
queued_file.file_label = file_label;
|
||||
props->file_send_queue_.push(queued_file);
|
||||
queue_size = props->file_send_queue_.size();
|
||||
}
|
||||
props_locked->file_send_start_time_ =
|
||||
std::chrono::steady_clock::now();
|
||||
props_locked->file_send_last_update_time_ =
|
||||
props_locked->file_send_start_time_;
|
||||
props_locked->file_send_last_bytes_ = 0;
|
||||
LOG_INFO("File added to queue: {} ({} files in queue)",
|
||||
file_path.filename().string().c_str(), queue_size);
|
||||
} else {
|
||||
StartFileTransfer(props, file_path, file_label);
|
||||
|
||||
LOG_INFO(
|
||||
"File transfer started: {} ({} bytes), file_sending_={}, "
|
||||
"total_bytes_={}",
|
||||
file_path.filename().string(), total_size,
|
||||
props_locked->file_sending_.load(),
|
||||
props_locked->file_total_bytes_.load());
|
||||
|
||||
FileSender sender;
|
||||
uint32_t file_id = FileSender::NextFileId();
|
||||
|
||||
{
|
||||
std::lock_guard<std::shared_mutex> lock(
|
||||
render_ptr->file_id_to_props_mutex_);
|
||||
render_ptr->file_id_to_props_[file_id] = props_weak;
|
||||
}
|
||||
|
||||
props_locked->current_file_id_ = file_id;
|
||||
|
||||
// Progress will be updated via ACK from receiver
|
||||
// Don't update file_sent_bytes_ here, let ACK control the progress
|
||||
int ret = sender.SendFile(
|
||||
file_path, file_path.filename().string(),
|
||||
[peer, file_label](const char* buf, size_t sz) -> int {
|
||||
return SendReliableDataFrame(peer, buf, sz, file_label.c_str());
|
||||
},
|
||||
64 * 1024, // chunk_size
|
||||
file_id); // file_id
|
||||
|
||||
// Mark sending thread as finished, but don't set completion flag yet
|
||||
// Completion will be set when we receive the final ACK from receiver
|
||||
auto props_locked_final = props_weak.lock();
|
||||
if (props_locked_final) {
|
||||
props_locked_final->file_sending_ = false;
|
||||
|
||||
if (ret != 0) {
|
||||
// On error, clean up immediately
|
||||
props_locked_final->file_transfer_completed_ = false;
|
||||
props_locked_final->file_transfer_window_visible_ = false;
|
||||
props_locked_final->file_sent_bytes_ = 0;
|
||||
props_locked_final->file_total_bytes_ = 0;
|
||||
props_locked_final->file_send_rate_bps_ = 0;
|
||||
props_locked_final->current_file_id_ = 0;
|
||||
|
||||
// Unregister file_id mapping on error
|
||||
{
|
||||
std::lock_guard<std::shared_mutex> lock(
|
||||
render_ptr->file_id_to_props_mutex_);
|
||||
render_ptr->file_id_to_props_.erase(file_id);
|
||||
}
|
||||
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(
|
||||
props_locked_final->file_transfer_mutex_);
|
||||
props_locked_final->file_sending_name_ = "";
|
||||
}
|
||||
|
||||
LOG_ERROR("FileSender::SendFile failed for [{}], ret={}",
|
||||
file_path.string().c_str(), ret);
|
||||
} else {
|
||||
// On success, keep file_id mapping and wait for final ACK
|
||||
// Don't set completion flag here - wait for ACK with completed
|
||||
// flag
|
||||
LOG_INFO("File send finished (waiting for ACK): {}",
|
||||
file_path.string().c_str());
|
||||
if (props->file_sending_.load()) {
|
||||
} else {
|
||||
// Failed to start (race condition: another file started between
|
||||
// check and call) Add to queue
|
||||
size_t queue_size = 0;
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(props->file_queue_mutex_);
|
||||
SubStreamWindowProperties::QueuedFile queued_file;
|
||||
queued_file.file_path = file_path;
|
||||
queued_file.file_label = file_label;
|
||||
props->file_send_queue_.push(queued_file);
|
||||
queue_size = props->file_send_queue_.size();
|
||||
}
|
||||
LOG_INFO(
|
||||
"File added to queue after race condition: {} ({} files in "
|
||||
"queue)",
|
||||
file_path.filename().string().c_str(), queue_size);
|
||||
}
|
||||
}).detach();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -30,47 +30,80 @@ int BitrateDisplay(int bitrate) {
|
||||
|
||||
int Render::FileTransferWindow(
|
||||
std::shared_ptr<SubStreamWindowProperties>& props) {
|
||||
if (!props->file_transfer_window_visible_ &&
|
||||
!props->file_transfer_completed_) {
|
||||
// Only show window if there are files in transfer list or currently
|
||||
// transferring
|
||||
std::vector<SubStreamWindowProperties::FileTransferInfo> file_list;
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(props->file_transfer_list_mutex_);
|
||||
file_list = props->file_transfer_list_;
|
||||
}
|
||||
|
||||
// Sort file list: Sending first, then Completed, then Queued, then Failed
|
||||
std::sort(
|
||||
file_list.begin(), file_list.end(),
|
||||
[](const SubStreamWindowProperties::FileTransferInfo& a,
|
||||
const SubStreamWindowProperties::FileTransferInfo& b) {
|
||||
// Priority: Sending > Completed > Queued > Failed
|
||||
auto get_priority =
|
||||
[](SubStreamWindowProperties::FileTransferStatus status) {
|
||||
switch (status) {
|
||||
case SubStreamWindowProperties::FileTransferStatus::Sending:
|
||||
return 0;
|
||||
case SubStreamWindowProperties::FileTransferStatus::Completed:
|
||||
return 1;
|
||||
case SubStreamWindowProperties::FileTransferStatus::Queued:
|
||||
return 2;
|
||||
case SubStreamWindowProperties::FileTransferStatus::Failed:
|
||||
return 3;
|
||||
}
|
||||
return 3;
|
||||
};
|
||||
return get_priority(a.status) < get_priority(b.status);
|
||||
});
|
||||
|
||||
// Only show window if file_transfer_window_visible_ is true
|
||||
// Window can be closed by user even during transfer
|
||||
// It will be reopened automatically when:
|
||||
// 1. A file transfer completes (in render_callback.cpp)
|
||||
// 2. A new file starts sending from queue (in render.cpp)
|
||||
if (!props->file_transfer_window_visible_) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
ImGuiIO& io = ImGui::GetIO();
|
||||
|
||||
// Position window at bottom-left of stream window
|
||||
float window_width = main_window_width_ * 0.35f;
|
||||
float window_height = main_window_height_ * 0.25f;
|
||||
float pos_x = 10.0f;
|
||||
float pos_y = 10.0f;
|
||||
|
||||
// Get stream window size and position
|
||||
ImVec2 stream_window_size =
|
||||
ImVec2(stream_window_width_, stream_window_height_);
|
||||
if (fullscreen_button_pressed_) {
|
||||
pos_y = stream_window_size.y - window_height - 10.0f;
|
||||
} else {
|
||||
pos_y = stream_window_size.y - window_height - 10.0f - title_bar_height_;
|
||||
}
|
||||
// Adjust window size based on number of files
|
||||
float file_transfer_window_width = main_window_width_ * 0.6f;
|
||||
float file_transfer_window_height =
|
||||
main_window_height_ * 0.3f; // Dynamic height
|
||||
float pos_x = file_transfer_window_width * 0.05f;
|
||||
float pos_y = stream_window_height_ - file_transfer_window_height -
|
||||
file_transfer_window_width * 0.05;
|
||||
float same_line_width = file_transfer_window_width * 0.1f;
|
||||
|
||||
ImGui::SetNextWindowPos(ImVec2(pos_x, pos_y), ImGuiCond_Always);
|
||||
ImGui::SetNextWindowSize(ImVec2(window_width, window_height),
|
||||
ImGuiCond_Always);
|
||||
ImGui::SetNextWindowSize(
|
||||
ImVec2(file_transfer_window_width, file_transfer_window_height),
|
||||
ImGuiCond_Always);
|
||||
|
||||
ImGui::PushStyleVar(ImGuiStyleVar_WindowRounding, 3.0f);
|
||||
ImGui::PushStyleVar(ImGuiStyleVar_WindowBorderSize, 1.0f);
|
||||
ImGui::PushStyleColor(ImGuiCol_WindowBg, ImVec4(1.0f, 1.0f, 1.0f, 0.8f));
|
||||
ImGui::PushStyleColor(ImGuiCol_WindowBg, ImVec4(1.0f, 1.0f, 1.0f, 0.9f));
|
||||
ImGui::PushStyleColor(ImGuiCol_Border, ImVec4(1.0f, 1.0f, 1.0f, 1.0f));
|
||||
ImGui::PushStyleColor(ImGuiCol_TitleBg, ImVec4(1.0f, 1.0f, 1.0f, 1.0f));
|
||||
ImGui::PushStyleColor(ImGuiCol_TitleBgActive, ImVec4(0.4f, 0.4f, 0.4f, 1.0f));
|
||||
ImGui::PushStyleColor(ImGuiCol_TitleBgActive, ImVec4(1.0f, 1.0f, 1.0f, 1.0f));
|
||||
|
||||
std::string window_title = "File Transfer";
|
||||
ImGui::SetWindowFontScale(0.5f);
|
||||
bool window_opened = true;
|
||||
|
||||
// ImGui::SetWindowFontScale(0.5f);
|
||||
if (ImGui::Begin("FileTransferWindow", &window_opened,
|
||||
ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoResize |
|
||||
ImGuiWindowFlags_NoMove |
|
||||
ImGuiWindowFlags_NoSavedSettings)) {
|
||||
if (ImGui::Begin(
|
||||
localization::file_transfer_progress[localization_language_index_]
|
||||
.c_str(),
|
||||
&window_opened,
|
||||
ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoResize |
|
||||
ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoSavedSettings |
|
||||
ImGuiWindowFlags_NoScrollbar)) {
|
||||
ImGui::SetWindowFontScale(1.0f);
|
||||
ImGui::SetWindowFontScale(0.5f);
|
||||
ImGui::PopStyleColor(4);
|
||||
ImGui::PopStyleVar(2);
|
||||
@@ -78,89 +111,115 @@ int Render::FileTransferWindow(
|
||||
// Close button handling
|
||||
if (!window_opened) {
|
||||
props->file_transfer_window_visible_ = false;
|
||||
props->file_transfer_completed_ = false;
|
||||
ImGui::End();
|
||||
return 0;
|
||||
}
|
||||
|
||||
bool is_sending = props->file_sending_.load();
|
||||
uint64_t total = props->file_total_bytes_.load();
|
||||
bool has_transfer = total > 0; // Check if there's an active transfer
|
||||
// Display file list
|
||||
if (file_list.empty()) {
|
||||
ImGui::Text("No files in transfer queue");
|
||||
} else {
|
||||
// Use a scrollable child window for the file list
|
||||
ImGui::SetWindowFontScale(0.5f);
|
||||
ImGui::BeginChild("FileList",
|
||||
ImVec2(0, file_transfer_window_height * 0.75f),
|
||||
ImGuiChildFlags_Border);
|
||||
ImGui::SetWindowFontScale(1.0f);
|
||||
ImGui::SetWindowFontScale(0.5f);
|
||||
|
||||
if (props->file_transfer_completed_ && !is_sending) {
|
||||
// Show completion message
|
||||
ImGui::SetCursorPos(ImVec2(10, 30));
|
||||
ImGui::TextColored(ImVec4(0.0f, 0.0f, 1.0f, 1.0f),
|
||||
"%s File transfer completed!", ICON_FA_CHECK);
|
||||
for (size_t i = 0; i < file_list.size(); ++i) {
|
||||
const auto& info = file_list[i];
|
||||
ImGui::PushID(static_cast<int>(i));
|
||||
|
||||
std::string file_name;
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(props->file_transfer_mutex_);
|
||||
file_name = props->file_sending_name_;
|
||||
}
|
||||
if (!file_name.empty()) {
|
||||
ImGui::SetCursorPos(ImVec2(10, 50));
|
||||
ImGui::Text("File: %s", file_name.c_str());
|
||||
// Status icon and file name
|
||||
const char* status_icon = "";
|
||||
ImVec4 status_color(0.5f, 0.5f, 0.5f, 1.0f);
|
||||
const char* status_text = "";
|
||||
|
||||
switch (info.status) {
|
||||
case SubStreamWindowProperties::FileTransferStatus::Queued:
|
||||
status_icon = ICON_FA_CLOCK;
|
||||
status_color =
|
||||
ImVec4(0.5f, 0.6f, 0.7f, 1.0f); // Common blue-gray for queued
|
||||
status_text =
|
||||
localization::queued[localization_language_index_].c_str();
|
||||
break;
|
||||
case SubStreamWindowProperties::FileTransferStatus::Sending:
|
||||
status_icon = ICON_FA_ARROW_UP;
|
||||
status_color = ImVec4(0.2f, 0.6f, 1.0f, 1.0f);
|
||||
status_text =
|
||||
localization::sending[localization_language_index_].c_str();
|
||||
break;
|
||||
case SubStreamWindowProperties::FileTransferStatus::Completed:
|
||||
status_icon = ICON_FA_CHECK;
|
||||
status_color = ImVec4(0.0f, 0.8f, 0.0f, 1.0f);
|
||||
status_text =
|
||||
localization::completed[localization_language_index_].c_str();
|
||||
break;
|
||||
case SubStreamWindowProperties::FileTransferStatus::Failed:
|
||||
status_icon = ICON_FA_XMARK;
|
||||
status_color = ImVec4(1.0f, 0.2f, 0.2f, 1.0f);
|
||||
status_text =
|
||||
localization::failed[localization_language_index_].c_str();
|
||||
break;
|
||||
}
|
||||
|
||||
ImGui::TextColored(status_color, "%s", status_icon);
|
||||
ImGui::SameLine();
|
||||
ImGui::Text("%s", info.file_name.c_str());
|
||||
ImGui::SameLine();
|
||||
ImGui::TextColored(status_color, "%s", status_text);
|
||||
|
||||
// Progress bar for sending files
|
||||
if (info.status ==
|
||||
SubStreamWindowProperties::FileTransferStatus::Sending &&
|
||||
info.file_size > 0) {
|
||||
float progress = static_cast<float>(info.sent_bytes) /
|
||||
static_cast<float>(info.file_size);
|
||||
progress = (std::max)(0.0f, (std::min)(1.0f, progress));
|
||||
|
||||
float text_height = ImGui::GetTextLineHeight();
|
||||
ImGui::ProgressBar(
|
||||
progress, ImVec2(file_transfer_window_width * 0.5f, text_height),
|
||||
"");
|
||||
ImGui::SameLine();
|
||||
|
||||
ImGui::Text("%.1f%%", progress * 100.0f);
|
||||
ImGui::SameLine();
|
||||
|
||||
float speed_x_pos = file_transfer_window_width * 0.65f;
|
||||
ImGui::SetCursorPosX(speed_x_pos);
|
||||
BitrateDisplay(static_cast<int>(info.rate_bps));
|
||||
} else if (info.status ==
|
||||
SubStreamWindowProperties::FileTransferStatus::Completed) {
|
||||
// Show completed size
|
||||
char size_str[64];
|
||||
if (info.file_size < 1024) {
|
||||
snprintf(size_str, sizeof(size_str), "%llu B",
|
||||
(unsigned long long)info.file_size);
|
||||
} else if (info.file_size < 1024 * 1024) {
|
||||
snprintf(size_str, sizeof(size_str), "%.2f KB",
|
||||
info.file_size / 1024.0f);
|
||||
} else {
|
||||
snprintf(size_str, sizeof(size_str), "%.2f MB",
|
||||
info.file_size / (1024.0f * 1024.0f));
|
||||
}
|
||||
ImGui::Text("Size: %s", size_str);
|
||||
}
|
||||
|
||||
ImGui::PopID();
|
||||
ImGui::Spacing();
|
||||
}
|
||||
|
||||
ImGui::SetCursorPos(ImVec2(10, 70));
|
||||
if (ImGui::Button("OK", ImVec2(80, 25))) {
|
||||
props->file_transfer_completed_ = false;
|
||||
props->file_transfer_window_visible_ = false;
|
||||
}
|
||||
} else if (has_transfer && !props->file_transfer_completed_) {
|
||||
// Show transfer progress (either sending or waiting for ACK)
|
||||
uint64_t sent = props->file_sent_bytes_.load();
|
||||
// Re-read total in case it was updated
|
||||
uint64_t current_total = props->file_total_bytes_.load();
|
||||
float progress = current_total > 0 ? static_cast<float>(sent) /
|
||||
static_cast<float>(current_total)
|
||||
: 0.0f;
|
||||
progress = (std::max)(0.0f, (std::min)(1.0f, progress));
|
||||
|
||||
// File name
|
||||
std::string file_name;
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(props->file_transfer_mutex_);
|
||||
file_name = props->file_sending_name_;
|
||||
}
|
||||
if (file_name.empty()) {
|
||||
file_name = "Sending...";
|
||||
}
|
||||
|
||||
ImGui::SetCursorPos(ImVec2(10, 30));
|
||||
ImGui::Text("File: %s", file_name.c_str());
|
||||
|
||||
// Progress bar
|
||||
ImGui::SetCursorPos(ImVec2(10, 50));
|
||||
ImGui::ProgressBar(progress, ImVec2(window_width - 40, 0), "");
|
||||
ImGui::SameLine(0, 5);
|
||||
ImGui::Text("%.1f%%", progress * 100.0f);
|
||||
|
||||
// Transfer rate and size info
|
||||
ImGui::SetCursorPos(ImVec2(10, 75));
|
||||
uint32_t rate_bps = props->file_send_rate_bps_.load();
|
||||
ImGui::Text("Speed: ");
|
||||
ImGui::SameLine();
|
||||
BitrateDisplay(static_cast<int>(rate_bps));
|
||||
|
||||
ImGui::SameLine(0, 20);
|
||||
// Format size display
|
||||
char size_str[64];
|
||||
if (current_total < 1024) {
|
||||
snprintf(size_str, sizeof(size_str), "%llu B",
|
||||
(unsigned long long)current_total);
|
||||
} else if (current_total < 1024 * 1024) {
|
||||
snprintf(size_str, sizeof(size_str), "%.2f KB",
|
||||
current_total / 1024.0f);
|
||||
} else {
|
||||
snprintf(size_str, sizeof(size_str), "%.2f MB",
|
||||
current_total / (1024.0f * 1024.0f));
|
||||
}
|
||||
ImGui::Text("Size: %s", size_str);
|
||||
ImGui::SetWindowFontScale(1.0f);
|
||||
ImGui::SetWindowFontScale(0.5f);
|
||||
ImGui::EndChild();
|
||||
ImGui::SetWindowFontScale(1.0f);
|
||||
}
|
||||
|
||||
ImGui::SetWindowFontScale(1.0f);
|
||||
ImGui::SetWindowFontScale(0.5f);
|
||||
ImGui::End();
|
||||
ImGui::SetWindowFontScale(1.0f);
|
||||
} else {
|
||||
ImGui::PopStyleColor(4);
|
||||
ImGui::PopStyleVar(2);
|
||||
|
||||
534
src/tools/clipboard.cpp
Normal file
534
src/tools/clipboard.cpp
Normal file
@@ -0,0 +1,534 @@
|
||||
|
||||
#include "clipboard.h"
|
||||
|
||||
#include <atomic>
|
||||
#include <chrono>
|
||||
#include <mutex>
|
||||
#include <string>
|
||||
#include <thread>
|
||||
|
||||
#include "rd_log.h"
|
||||
|
||||
#ifdef _WIN32
|
||||
#include <windows.h>
|
||||
#elif __linux__
|
||||
#include <X11/Xatom.h>
|
||||
#include <X11/Xlib.h>
|
||||
#include <X11/extensions/Xfixes.h>
|
||||
|
||||
#include <cstring>
|
||||
#include <memory>
|
||||
#endif
|
||||
|
||||
namespace crossdesk {
|
||||
|
||||
std::atomic<bool> g_monitoring{false};
|
||||
std::thread g_monitor_thread;
|
||||
std::mutex g_monitor_mutex;
|
||||
std::string g_last_clipboard_text;
|
||||
int g_check_interval_ms = 100;
|
||||
Clipboard::OnClipboardChanged g_on_clipboard_changed;
|
||||
|
||||
#ifdef _WIN32
|
||||
HWND g_clipboard_wnd = nullptr;
|
||||
const char* g_clipboard_class_name = "CrossDeskClipboardMonitor";
|
||||
#endif
|
||||
|
||||
#ifdef __linux__
|
||||
Display* g_x11_display = nullptr;
|
||||
Atom g_clipboard_atom = None;
|
||||
Atom g_xfixes_selection_notify = None;
|
||||
#endif
|
||||
} // namespace crossdesk
|
||||
|
||||
namespace crossdesk {
|
||||
|
||||
#ifdef _WIN32
|
||||
std::string Clipboard::GetText() {
|
||||
if (!OpenClipboard(nullptr)) {
|
||||
LOG_ERROR("Clipboard::GetText: failed to open clipboard");
|
||||
return "";
|
||||
}
|
||||
|
||||
std::string result;
|
||||
HANDLE hData = GetClipboardData(CF_UNICODETEXT);
|
||||
if (hData != nullptr) {
|
||||
wchar_t* pszText = static_cast<wchar_t*>(GlobalLock(hData));
|
||||
if (pszText != nullptr) {
|
||||
int size_needed = WideCharToMultiByte(CP_UTF8, 0, pszText, -1, nullptr, 0,
|
||||
nullptr, nullptr);
|
||||
if (size_needed > 0) {
|
||||
// -1 because WideCharToMultiByte contains '\0'
|
||||
result.resize(size_needed - 1);
|
||||
WideCharToMultiByte(CP_UTF8, 0, pszText, -1, &result[0], size_needed,
|
||||
nullptr, nullptr);
|
||||
}
|
||||
GlobalUnlock(hData);
|
||||
}
|
||||
}
|
||||
|
||||
CloseClipboard();
|
||||
return result;
|
||||
}
|
||||
|
||||
bool Clipboard::SetText(const std::string& text) {
|
||||
if (!OpenClipboard(nullptr)) {
|
||||
LOG_ERROR("Clipboard::SetText: failed to open clipboard");
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!EmptyClipboard()) {
|
||||
LOG_ERROR("Clipboard::SetText: failed to empty clipboard");
|
||||
CloseClipboard();
|
||||
return false;
|
||||
}
|
||||
|
||||
// Convert UTF-8 string to wide char
|
||||
int size_needed =
|
||||
MultiByteToWideChar(CP_UTF8, 0, text.c_str(), -1, nullptr, 0);
|
||||
if (size_needed <= 0) {
|
||||
LOG_ERROR("Clipboard::SetText: failed to convert to wide char");
|
||||
CloseClipboard();
|
||||
return false;
|
||||
}
|
||||
|
||||
HGLOBAL hMem = GlobalAlloc(GMEM_MOVEABLE, size_needed * sizeof(wchar_t));
|
||||
if (hMem == nullptr) {
|
||||
LOG_ERROR("Clipboard::SetText: failed to allocate memory");
|
||||
CloseClipboard();
|
||||
return false;
|
||||
}
|
||||
|
||||
wchar_t* pszText = static_cast<wchar_t*>(GlobalLock(hMem));
|
||||
if (pszText == nullptr) {
|
||||
LOG_ERROR("Clipboard::SetText: failed to lock memory");
|
||||
GlobalFree(hMem);
|
||||
CloseClipboard();
|
||||
return false;
|
||||
}
|
||||
|
||||
MultiByteToWideChar(CP_UTF8, 0, text.c_str(), -1, pszText, size_needed);
|
||||
GlobalUnlock(hMem);
|
||||
|
||||
if (SetClipboardData(CF_UNICODETEXT, hMem) == nullptr) {
|
||||
LOG_ERROR("Clipboard::SetText: failed to set clipboard data");
|
||||
GlobalFree(hMem);
|
||||
CloseClipboard();
|
||||
return false;
|
||||
}
|
||||
|
||||
CloseClipboard();
|
||||
return true;
|
||||
}
|
||||
|
||||
bool Clipboard::HasText() {
|
||||
if (!OpenClipboard(nullptr)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
bool has_text = IsClipboardFormatAvailable(CF_UNICODETEXT) ||
|
||||
IsClipboardFormatAvailable(CF_TEXT);
|
||||
CloseClipboard();
|
||||
return has_text;
|
||||
}
|
||||
|
||||
#elif __APPLE__
|
||||
// macOS implementation is in clipboard_mac.mm
|
||||
#elif __linux__
|
||||
|
||||
std::string Clipboard::GetText() {
|
||||
Display* display = XOpenDisplay(nullptr);
|
||||
if (display == nullptr) {
|
||||
LOG_ERROR("Clipboard::GetText: failed to open X display");
|
||||
return "";
|
||||
}
|
||||
|
||||
std::string result;
|
||||
Window owner = XGetSelectionOwner(display, XA_PRIMARY);
|
||||
if (owner == None) {
|
||||
// Try using CLIPBOARD
|
||||
owner =
|
||||
XGetSelectionOwner(display, XInternAtom(display, "CLIPBOARD", False));
|
||||
if (owner == None) {
|
||||
XCloseDisplay(display);
|
||||
return "";
|
||||
}
|
||||
}
|
||||
|
||||
Atom selection = XA_PRIMARY;
|
||||
Atom target = XInternAtom(display, "UTF8_STRING", False);
|
||||
if (target == None) {
|
||||
target = XA_STRING;
|
||||
}
|
||||
|
||||
XEvent event;
|
||||
Window window = XCreateSimpleWindow(display, DefaultRootWindow(display), 0, 0,
|
||||
1, 1, 0, 0, 0);
|
||||
XSelectInput(display, window, PropertyChangeMask);
|
||||
|
||||
XConvertSelection(display, selection, target, XA_PRIMARY, window,
|
||||
CurrentTime);
|
||||
|
||||
// Wait for selection conversion to complete
|
||||
bool done = false;
|
||||
while (!done) {
|
||||
XNextEvent(display, &event);
|
||||
if (event.type == SelectionNotify) {
|
||||
if (event.xselection.property == None) {
|
||||
// Try using CLIPBOARD
|
||||
if (selection == XA_PRIMARY) {
|
||||
selection = XInternAtom(display, "CLIPBOARD", False);
|
||||
XConvertSelection(display, selection, target, XA_PRIMARY, window,
|
||||
CurrentTime);
|
||||
continue;
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
Atom actual_type;
|
||||
int actual_format;
|
||||
unsigned long nitems;
|
||||
unsigned long bytes_after;
|
||||
unsigned char* data = nullptr;
|
||||
|
||||
if (XGetWindowProperty(display, window, XA_PRIMARY, 0, LONG_MAX / 4,
|
||||
False, AnyPropertyType, &actual_type,
|
||||
&actual_format, &nitems, &bytes_after,
|
||||
&data) == Success) {
|
||||
if (data != nullptr) {
|
||||
result = std::string(reinterpret_cast<char*>(data), nitems);
|
||||
XFree(data);
|
||||
}
|
||||
done = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
XDestroyWindow(display, window);
|
||||
XCloseDisplay(display);
|
||||
return result;
|
||||
}
|
||||
|
||||
bool Clipboard::SetText(const std::string& text) {
|
||||
Display* display = XOpenDisplay(nullptr);
|
||||
if (display == nullptr) {
|
||||
LOG_ERROR("Clipboard::SetText: failed to open X display");
|
||||
return false;
|
||||
}
|
||||
|
||||
Window window = XCreateSimpleWindow(display, DefaultRootWindow(display), 0, 0,
|
||||
1, 1, 0, 0, 0);
|
||||
Atom clipboard = XInternAtom(display, "CLIPBOARD", False);
|
||||
Atom utf8_string = XInternAtom(display, "UTF8_STRING", False);
|
||||
Atom targets = XInternAtom(display, "TARGETS", False);
|
||||
Atom xa_string = XA_STRING;
|
||||
|
||||
XSetSelectionOwner(display, clipboard, window, CurrentTime);
|
||||
if (XGetSelectionOwner(display, clipboard) != window) {
|
||||
LOG_ERROR("Clipboard::SetText: failed to set selection owner");
|
||||
XDestroyWindow(display, window);
|
||||
XCloseDisplay(display);
|
||||
return false;
|
||||
}
|
||||
|
||||
XChangeProperty(display, window, XA_PRIMARY, utf8_string, 8, PropModeReplace,
|
||||
reinterpret_cast<const unsigned char*>(text.c_str()),
|
||||
static_cast<int>(text.length()));
|
||||
|
||||
XEvent event;
|
||||
while (true) {
|
||||
XNextEvent(display, &event);
|
||||
if (event.type == SelectionRequest) {
|
||||
XSelectionRequestEvent* req = &event.xselectionrequest;
|
||||
XSelectionEvent se;
|
||||
se.type = SelectionNotify;
|
||||
se.display = req->display;
|
||||
se.requestor = req->requestor;
|
||||
se.selection = req->selection;
|
||||
se.time = req->time;
|
||||
se.target = req->target;
|
||||
se.property = req->property;
|
||||
|
||||
if (req->target == targets) {
|
||||
// Return supported formats
|
||||
Atom supported[] = {utf8_string, xa_string, targets};
|
||||
XChangeProperty(display, req->requestor, req->property, XA_ATOM, 32,
|
||||
PropModeReplace,
|
||||
reinterpret_cast<unsigned char*>(supported), 3);
|
||||
se.property = req->property;
|
||||
} else if (req->target == utf8_string || req->target == xa_string) {
|
||||
// Return text data
|
||||
XChangeProperty(display, req->requestor, req->property, req->target, 8,
|
||||
PropModeReplace,
|
||||
reinterpret_cast<const unsigned char*>(text.c_str()),
|
||||
static_cast<int>(text.length()));
|
||||
se.property = req->property;
|
||||
} else {
|
||||
se.property = None;
|
||||
}
|
||||
|
||||
XSendEvent(display, req->requestor, False, 0,
|
||||
reinterpret_cast<XEvent*>(&se));
|
||||
XSync(display, False);
|
||||
} else if (event.type == SelectionClear) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
XDestroyWindow(display, window);
|
||||
XCloseDisplay(display);
|
||||
return true;
|
||||
}
|
||||
|
||||
bool Clipboard::HasText() {
|
||||
Display* display = XOpenDisplay(nullptr);
|
||||
if (display == nullptr) {
|
||||
return false;
|
||||
}
|
||||
|
||||
Atom clipboard = XInternAtom(display, "CLIPBOARD", False);
|
||||
Window owner = XGetSelectionOwner(display, clipboard);
|
||||
if (owner == None) {
|
||||
owner = XGetSelectionOwner(display, XA_PRIMARY);
|
||||
}
|
||||
|
||||
XCloseDisplay(display);
|
||||
return owner != None;
|
||||
}
|
||||
|
||||
#else
|
||||
|
||||
std::string Clipboard::GetText() {
|
||||
LOG_ERROR("Clipboard::GetText: unsupported platform");
|
||||
return "";
|
||||
}
|
||||
|
||||
bool Clipboard::SetText(const std::string& text) {
|
||||
LOG_ERROR("Clipboard::SetText: unsupported platform");
|
||||
return false;
|
||||
}
|
||||
|
||||
bool Clipboard::HasText() {
|
||||
LOG_ERROR("Clipboard::HasText: unsupported platform");
|
||||
return false;
|
||||
}
|
||||
|
||||
#endif
|
||||
|
||||
void HandleClipboardChange() {
|
||||
if (!Clipboard::HasText()) {
|
||||
std::lock_guard<std::mutex> lock(g_monitor_mutex);
|
||||
if (!g_last_clipboard_text.empty()) {
|
||||
g_last_clipboard_text.clear();
|
||||
LOG_INFO("Clipboard content cleared");
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
std::string current_text = Clipboard::GetText();
|
||||
|
||||
// Check if the content has changed
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(g_monitor_mutex);
|
||||
if (current_text != g_last_clipboard_text) {
|
||||
g_last_clipboard_text = current_text;
|
||||
if (!current_text.empty()) {
|
||||
if (g_on_clipboard_changed) {
|
||||
int ret = g_on_clipboard_changed(current_text.c_str(),
|
||||
current_text.length());
|
||||
if (ret != 0) {
|
||||
LOG_WARN("Clipboard callback returned error: {}", ret);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#ifdef _WIN32
|
||||
LRESULT CALLBACK ClipboardWndProc(HWND hwnd, UINT uMsg, WPARAM wParam,
|
||||
LPARAM lParam) {
|
||||
if (uMsg == WM_CLIPBOARDUPDATE) {
|
||||
HandleClipboardChange();
|
||||
return 0;
|
||||
}
|
||||
return DefWindowProc(hwnd, uMsg, wParam, lParam);
|
||||
}
|
||||
|
||||
static void MonitorThreadFunc() {
|
||||
// Create a hidden window to receive clipboard messages
|
||||
WNDCLASSA wc = {0};
|
||||
wc.lpfnWndProc = ClipboardWndProc;
|
||||
wc.hInstance = GetModuleHandle(nullptr);
|
||||
wc.lpszClassName = g_clipboard_class_name;
|
||||
RegisterClassA(&wc);
|
||||
|
||||
g_clipboard_wnd = CreateWindowA(g_clipboard_class_name, nullptr, 0, 0, 0, 0,
|
||||
0, HWND_MESSAGE, nullptr, nullptr, nullptr);
|
||||
if (!g_clipboard_wnd) {
|
||||
LOG_ERROR("Failed to create clipboard monitor window");
|
||||
g_monitoring.store(false);
|
||||
return;
|
||||
}
|
||||
|
||||
// Register clipboard format listener
|
||||
if (!AddClipboardFormatListener(g_clipboard_wnd)) {
|
||||
LOG_ERROR("Failed to add clipboard format listener");
|
||||
DestroyWindow(g_clipboard_wnd);
|
||||
g_clipboard_wnd = nullptr;
|
||||
g_monitoring.store(false);
|
||||
return;
|
||||
}
|
||||
|
||||
LOG_INFO("Clipboard event monitoring started (Windows)");
|
||||
|
||||
MSG msg;
|
||||
while (g_monitoring.load()) {
|
||||
BOOL ret = GetMessage(&msg, nullptr, 0, 0);
|
||||
if (ret == 0 || ret == -1) {
|
||||
break;
|
||||
}
|
||||
TranslateMessage(&msg);
|
||||
DispatchMessage(&msg);
|
||||
}
|
||||
|
||||
RemoveClipboardFormatListener(g_clipboard_wnd);
|
||||
if (g_clipboard_wnd) {
|
||||
DestroyWindow(g_clipboard_wnd);
|
||||
g_clipboard_wnd = nullptr;
|
||||
}
|
||||
UnregisterClassA(g_clipboard_class_name, GetModuleHandle(nullptr));
|
||||
}
|
||||
|
||||
#elif __APPLE__
|
||||
// macOS use notification mechanism, need external functions
|
||||
extern void StartMacOSClipboardMonitoring();
|
||||
extern void StopMacOSClipboardMonitoring();
|
||||
|
||||
static void MonitorThreadFunc() { StartMacOSClipboardMonitoring(); }
|
||||
|
||||
#elif __linux__
|
||||
static void MonitorThreadFunc() {
|
||||
g_x11_display = XOpenDisplay(nullptr);
|
||||
if (!g_x11_display) {
|
||||
LOG_ERROR("Failed to open X display for clipboard monitoring");
|
||||
g_monitoring.store(false);
|
||||
return;
|
||||
}
|
||||
|
||||
// Check if XFixes extension is available
|
||||
int event_base, error_base;
|
||||
if (!XFixesQueryExtension(g_x11_display, &event_base, &error_base)) {
|
||||
LOG_WARN("XFixes extension not available, falling back to polling");
|
||||
XCloseDisplay(g_x11_display);
|
||||
g_x11_display = nullptr;
|
||||
// fallback to polling mode
|
||||
while (g_monitoring.load()) {
|
||||
std::this_thread::sleep_for(
|
||||
std::chrono::milliseconds(g_check_interval_ms));
|
||||
if (!g_monitoring.load()) {
|
||||
break;
|
||||
}
|
||||
HandleClipboardChange();
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
g_clipboard_atom = XInternAtom(g_x11_display, "CLIPBOARD", False);
|
||||
g_xfixes_selection_notify =
|
||||
XInternAtom(g_x11_display, "XFIXES_SELECTION_NOTIFY", False);
|
||||
|
||||
// Create event window
|
||||
Window root = DefaultRootWindow(g_x11_display);
|
||||
Window event_window =
|
||||
XCreateSimpleWindow(g_x11_display, root, 0, 0, 1, 1, 0, 0, 0);
|
||||
|
||||
// Select events to monitor
|
||||
XFixesSelectSelectionInput(g_x11_display, event_window, g_clipboard_atom,
|
||||
XFixesSetSelectionOwnerNotifyMask |
|
||||
XFixesSelectionWindowDestroyNotifyMask |
|
||||
XFixesSelectionClientCloseNotifyMask);
|
||||
|
||||
LOG_INFO("Clipboard event monitoring started (Linux XFixes)");
|
||||
|
||||
XEvent event;
|
||||
while (g_monitoring.load()) {
|
||||
XNextEvent(g_x11_display, &event);
|
||||
if (event.type == event_base + XFixesSelectionNotify) {
|
||||
HandleClipboardChange();
|
||||
}
|
||||
}
|
||||
|
||||
XFixesSelectSelectionInput(g_x11_display, event_window, g_clipboard_atom, 0);
|
||||
XDestroyWindow(g_x11_display, event_window);
|
||||
XCloseDisplay(g_x11_display);
|
||||
g_x11_display = nullptr;
|
||||
}
|
||||
|
||||
#else
|
||||
// Fallback to polling mode for other platforms
|
||||
static void MonitorThreadFunc() {
|
||||
while (g_monitoring.load()) {
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds(g_check_interval_ms));
|
||||
if (!g_monitoring.load()) {
|
||||
break;
|
||||
}
|
||||
HandleClipboardChange();
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
void Clipboard::StartMonitoring(int check_interval_ms,
|
||||
OnClipboardChanged on_changed) {
|
||||
if (g_monitoring.load()) {
|
||||
LOG_WARN("Clipboard monitoring is already running");
|
||||
return;
|
||||
}
|
||||
|
||||
g_check_interval_ms = check_interval_ms > 0 ? check_interval_ms : 100;
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(g_monitor_mutex);
|
||||
g_on_clipboard_changed = on_changed;
|
||||
if (HasText()) {
|
||||
g_last_clipboard_text = GetText();
|
||||
} else {
|
||||
g_last_clipboard_text.clear();
|
||||
}
|
||||
}
|
||||
g_monitoring.store(true);
|
||||
|
||||
g_monitor_thread = std::thread(MonitorThreadFunc);
|
||||
LOG_INFO("Clipboard event monitoring started");
|
||||
}
|
||||
|
||||
void Clipboard::StopMonitoring() {
|
||||
if (!g_monitoring.load()) {
|
||||
return;
|
||||
}
|
||||
|
||||
g_monitoring.store(false);
|
||||
|
||||
#ifdef _WIN32
|
||||
if (g_clipboard_wnd) {
|
||||
PostMessage(g_clipboard_wnd, WM_QUIT, 0, 0);
|
||||
}
|
||||
#elif __APPLE__
|
||||
StopMacOSClipboardMonitoring();
|
||||
#endif
|
||||
|
||||
if (g_monitor_thread.joinable()) {
|
||||
g_monitor_thread.join();
|
||||
}
|
||||
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(g_monitor_mutex);
|
||||
g_last_clipboard_text.clear();
|
||||
g_on_clipboard_changed = nullptr;
|
||||
}
|
||||
|
||||
LOG_INFO("Clipboard monitoring stopped");
|
||||
}
|
||||
|
||||
bool Clipboard::IsMonitoring() { return g_monitoring.load(); }
|
||||
|
||||
} // namespace crossdesk
|
||||
38
src/tools/clipboard.h
Normal file
38
src/tools/clipboard.h
Normal file
@@ -0,0 +1,38 @@
|
||||
/*
|
||||
* @Author: DI JUNKUN
|
||||
* @Date: 2025-12-28
|
||||
* Copyright (c) 2025 by DI JUNKUN, All Rights Reserved.
|
||||
*/
|
||||
|
||||
#ifndef _CLIPBOARD_H_
|
||||
#define _CLIPBOARD_H_
|
||||
|
||||
#include <functional>
|
||||
#include <string>
|
||||
|
||||
namespace crossdesk {
|
||||
|
||||
class Clipboard {
|
||||
public:
|
||||
using OnClipboardChanged = std::function<int(const char* data, size_t size)>;
|
||||
|
||||
Clipboard() = default;
|
||||
~Clipboard() = default;
|
||||
|
||||
static std::string GetText();
|
||||
|
||||
static bool SetText(const std::string& text);
|
||||
|
||||
static bool HasText();
|
||||
|
||||
static void StartMonitoring(int check_interval_ms = 100,
|
||||
OnClipboardChanged on_changed = nullptr);
|
||||
|
||||
static void StopMonitoring();
|
||||
|
||||
static bool IsMonitoring();
|
||||
};
|
||||
|
||||
} // namespace crossdesk
|
||||
|
||||
#endif
|
||||
120
src/tools/clipboard_mac.mm
Normal file
120
src/tools/clipboard_mac.mm
Normal file
@@ -0,0 +1,120 @@
|
||||
/*
|
||||
* @Author: DI JUNKUN
|
||||
* @Date: 2025-12-18
|
||||
* Copyright (c) 2025 by DI JUNKUN, All Rights Reserved.
|
||||
*/
|
||||
|
||||
#include "clipboard.h"
|
||||
|
||||
#include <AppKit/AppKit.h>
|
||||
#include <CoreFoundation/CoreFoundation.h>
|
||||
#include <atomic>
|
||||
#include <mutex>
|
||||
#include <string>
|
||||
#include <thread>
|
||||
|
||||
#include "rd_log.h"
|
||||
|
||||
namespace crossdesk {
|
||||
|
||||
extern std::atomic<bool> g_monitoring;
|
||||
extern std::mutex g_monitor_mutex;
|
||||
extern std::string g_last_clipboard_text;
|
||||
extern Clipboard::OnClipboardChanged g_on_clipboard_changed;
|
||||
|
||||
static CFRunLoopRef g_monitor_runloop = nullptr;
|
||||
|
||||
std::string Clipboard::GetText() {
|
||||
@autoreleasepool {
|
||||
NSPasteboard* pasteboard = [NSPasteboard generalPasteboard];
|
||||
NSString* string = [pasteboard stringForType:NSPasteboardTypeString];
|
||||
if (string == nil) {
|
||||
return "";
|
||||
}
|
||||
return std::string([string UTF8String]);
|
||||
}
|
||||
}
|
||||
|
||||
bool Clipboard::SetText(const std::string& text) {
|
||||
@autoreleasepool {
|
||||
NSPasteboard* pasteboard = [NSPasteboard generalPasteboard];
|
||||
[pasteboard clearContents];
|
||||
NSString* string = [NSString stringWithUTF8String:text.c_str()];
|
||||
if (string == nil) {
|
||||
LOG_ERROR("Clipboard::SetText: failed to create NSString");
|
||||
return false;
|
||||
}
|
||||
BOOL success = [pasteboard setString:string forType:NSPasteboardTypeString];
|
||||
return success == YES;
|
||||
}
|
||||
}
|
||||
|
||||
bool Clipboard::HasText() {
|
||||
@autoreleasepool {
|
||||
NSPasteboard* pasteboard = [NSPasteboard generalPasteboard];
|
||||
NSArray* types = [pasteboard types];
|
||||
return [types containsObject:NSPasteboardTypeString];
|
||||
}
|
||||
}
|
||||
|
||||
extern void HandleClipboardChange();
|
||||
|
||||
void StartMacOSClipboardMonitoring() {
|
||||
@autoreleasepool {
|
||||
NSPasteboard* pasteboard = [NSPasteboard generalPasteboard];
|
||||
|
||||
// Store RunLoop reference for waking up
|
||||
NSRunLoop* runLoop = [NSRunLoop currentRunLoop];
|
||||
g_monitor_runloop = [runLoop getCFRunLoop];
|
||||
if (g_monitor_runloop) {
|
||||
CFRetain(g_monitor_runloop);
|
||||
}
|
||||
|
||||
// Track changeCount to detect clipboard changes
|
||||
// Use __block to allow modification inside the block
|
||||
__block NSInteger lastChangeCount = [pasteboard changeCount];
|
||||
|
||||
LOG_INFO("Clipboard event monitoring started (macOS)");
|
||||
|
||||
// Use a timer to periodically check changeCount
|
||||
// This is more reliable than NSPasteboardDidChangeNotification which may not be available
|
||||
NSTimer* timer =
|
||||
[NSTimer scheduledTimerWithTimeInterval:0.1
|
||||
repeats:YES
|
||||
block:^(NSTimer* timer) {
|
||||
if (!g_monitoring.load()) {
|
||||
[timer invalidate];
|
||||
return;
|
||||
}
|
||||
NSInteger currentChangeCount = [pasteboard changeCount];
|
||||
if (currentChangeCount != lastChangeCount) {
|
||||
lastChangeCount = currentChangeCount;
|
||||
HandleClipboardChange();
|
||||
}
|
||||
}];
|
||||
|
||||
while (g_monitoring.load()) {
|
||||
@autoreleasepool {
|
||||
NSDate* date = [NSDate dateWithTimeIntervalSinceNow:0.1];
|
||||
[runLoop runMode:NSDefaultRunLoopMode beforeDate:date];
|
||||
}
|
||||
}
|
||||
|
||||
// Cleanup
|
||||
[timer invalidate];
|
||||
if (g_monitor_runloop) {
|
||||
CFRelease(g_monitor_runloop);
|
||||
g_monitor_runloop = nullptr;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void StopMacOSClipboardMonitoring() {
|
||||
// Wake up the RunLoop immediately so it can check g_monitoring and exit
|
||||
// This ensures the RunLoop exits promptly instead of waiting up to 0.1 seconds
|
||||
if (g_monitor_runloop) {
|
||||
CFRunLoopWakeUp(g_monitor_runloop);
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace crossdesk
|
||||
Submodule submodules/minirtc updated: e049099e43...fc5591eec7
Reference in New Issue
Block a user